diff --git a/generated-src/beam_renderer.cpp b/generated-src/beam_renderer.cpp deleted file mode 100644 index b43b005..0000000 --- a/generated-src/beam_renderer.cpp +++ /dev/null @@ -1,607 +0,0 @@ -#include "classes.h" - -// 0041e480 -void BeamRenderer::Begin(ANM2 *anm2, uint32_t layer, uint8_t isUseOverlay, uint8_t isUnk) -{ - DAT_00c78ef0 = anm2; - DAT_00c78ef4 = layer; - (*GHIDRA_CAST((GHIDRA_CAST(&(DAT_00c78ef8)) + 0x0))) = isUseOverlay; - (*GHIDRA_CAST((GHIDRA_CAST(&(DAT_00c78ef8)) + 0x1))) = isUnk; - g_beamRendererPointsEnd = g_beamRendererPoints; - return; -} - -// 0041e720 -void BeamRenderer::Add(Vector *point, ColorMod *color, float spritesheetCoordinate, float width) -{ - int iVar1; - float fVar2; - float dirX; - float dirY; - uint64_t local_70; - float local_68; - float fStack_64; - float fStack_60; - float fStack_5c; - Vector newPointPos; - float normalX; - float normalY; - float newPointCoord; - float newPointWidth; - float local_40; - float fStack_3c; - float fStack_38; - float fStack_34; - float local_30; - float fStack_2c; - float fStack_28; - float fStack_24; - uint64_t local_20; - float local_18; - uint32_t local_c; - void *pointsEnd; - - pointsEnd = g_beamRendererPointsEnd; - local_c = __security_cookie ^ GHIDRA_UINT(&dirX); - newPointPos.x = point->x; - newPointPos.y = point->y; - local_68 = color->_tint[0]; - fStack_64 = color->_tint[1]; - fStack_60 = color->_tint[2]; - fStack_5c = color->_tint[3]; - local_18 = color->_offset[2]; - local_30 = color->_colorize[0]; - fStack_2c = color->_colorize[1]; - fStack_28 = color->_colorize[2]; - fStack_24 = color->_colorize[3]; - local_70 = *GHIDRA_CAST(color->_offset); - iVar1 = GHIDRA_INT(g_beamRendererPointsEnd) - GHIDRA_INT(g_beamRendererPoints) >> 0x1f; - normalX = g_vectorZero.x; - normalY = g_vectorZero.y; - newPointCoord = spritesheetCoordinate; - newPointWidth = width; - local_40 = local_68; - fStack_3c = fStack_64; - fStack_38 = fStack_60; - fStack_34 = fStack_5c; - local_20 = local_70; - if ((GHIDRA_INT(g_beamRendererPointsEnd) - GHIDRA_INT(g_beamRendererPoints)) / 0x44 + iVar1 != iVar1) { - dirY = newPointPos.y - *GHIDRA_CAST((GHIDRA_CAST(g_beamRendererPointsEnd) + -0x40)); - dirX = newPointPos.x - *GHIDRA_CAST((GHIDRA_CAST(g_beamRendererPointsEnd) + -0x44)); - fVar2 = sqrtf(dirY * dirY + dirX * dirX); - if (0.0 < fVar2) { - dirX = dirX * (1.0 / fVar2); - dirY = dirY * (1.0 / fVar2); - } - fVar2 = cos(1.5707964); - local_70 = CONCAT44((*GHIDRA_CAST((GHIDRA_CAST(&(local_70)) + 0x4))),fVar2); - fVar2 = sin(1.5707964); - normalX = (float)local_70 * dirX - fVar2 * dirY; - normalY = fVar2 * dirX + (float)local_70 * dirY; - (GHIDRA_CAST((GHIDRA_CAST((GHIDRA_INT(pointsEnd) + -0x44)))))->Point::UpdateNormal(&newPointPos); - } - pointsEnd = g_beamRendererPointsEnd; - if (g_beamRendererPointsEnd == DAT_00c78f04) { - FUN_0041fcb0(g_beamRendererPointsEnd,&newPointPos); - return; - } - *GHIDRA_CAST(g_beamRendererPointsEnd) = newPointPos.x; - *GHIDRA_CAST((GHIDRA_CAST(pointsEnd) + 4)) = newPointPos.y; - *GHIDRA_CAST((GHIDRA_CAST(pointsEnd) + 8)) = normalX; - *GHIDRA_CAST((GHIDRA_CAST(pointsEnd) + 0xc)) = normalY; - *GHIDRA_CAST((GHIDRA_CAST(pointsEnd) + 0x10)) = newPointCoord; - *GHIDRA_CAST((GHIDRA_CAST(pointsEnd) + 0x14)) = newPointWidth; - *GHIDRA_CAST((GHIDRA_CAST(pointsEnd) + 0x38)) = local_20; - *GHIDRA_CAST((GHIDRA_CAST(pointsEnd) + 0x18)) = local_40; - *GHIDRA_CAST((GHIDRA_CAST(pointsEnd) + 0x1c)) = fStack_3c; - *GHIDRA_CAST((GHIDRA_CAST(pointsEnd) + 0x20)) = fStack_38; - *GHIDRA_CAST((GHIDRA_CAST(pointsEnd) + 0x24)) = fStack_34; - *GHIDRA_CAST((GHIDRA_CAST(pointsEnd) + 0x40)) = local_18; - *GHIDRA_CAST((GHIDRA_CAST(pointsEnd) + 0x28)) = local_30; - *GHIDRA_CAST((GHIDRA_CAST(pointsEnd) + 0x2c)) = fStack_2c; - *GHIDRA_CAST((GHIDRA_CAST(pointsEnd) + 0x30)) = fStack_28; - *GHIDRA_CAST((GHIDRA_CAST(pointsEnd) + 0x34)) = fStack_24; - g_beamRendererPointsEnd = (void *)(GHIDRA_INT(g_beamRendererPointsEnd) + 0x44); - return; -} - -// 0041e960 -void BeamRenderer::End() -{ - char cVar1; - LayerState *layer; - float *pfVar2; - void *pvVar3; - int iVar4; - AnimationState *animState; - KColor *color; - uint8_t *unusedArg; - float *pfVar5; - uint32_t bytesLeft; - bool isBytesLeft; - int *piVar6; - float nextUvY; - float fVar7; - float fVar8; - float fVar9; - float nextEdgeOffsetY; - int *imageRefCount; - uint8_t auStack_202 [2]; - Vector startCornerA; - Vector startCornerB; - Vector endCornerA; - uint8_t local_1dc [20]; - float fStack_1c8; - float fStack_1c4; - float fStack_1c0; - uint8_t local_1bc; - float local_1b8 [14]; - uint32_t local_180; - float local_17c [4]; - uint32_t local_16c; - Vector local_168; - uint64_t local_160; - Vector local_158; - Vector local_150; - Vector local_148; - Vector local_140; - Vector local_138; - int *texture; - int *textureRefCount; - Vector local_128; - Color pointColor; - Color nextPointColor; - Vector local_c0; - float *layerFrame; - float local_b4; - uint8_t *local_b0; - float local_ac; - float local_a8; - uint8_t spriteFlipX; - uint8_t layerFlipX; - float *local_a0; - char isPerVertexColor; - uint8_t coloredQuad [24]; - ColorMod shaderColor; - float endTint; - float fStack_50; - float fStack_4c; - float fStack_48; - float endColorize; - float fStack_40; - float fStack_3c; - float fStack_38; - uint64_t endOffsetXY; - float endOffsetZ; - uint32_t stackCookie; - uint8_t *puStack_20; - void *local_1c; - uint8_t *puStack_18; - uint32_t local_14; - float *nextPointColorize; - float uvLeft; - - puStack_20 = coloredQuad + 0x94; - local_14 = 0xffffffff; - puStack_18 = &LAB_00af1720; - local_1c = ExceptionList; - stackCookie = __security_cookie ^ GHIDRA_UINT((coloredQuad + 0x88)); - ExceptionList = &local_1c; - layer = ANM2::GetLayer(DAT_00c78ef0,DAT_00c78ef4); - LayerState::GetTexture(layer,&texture); - local_14 = 0; - if ((texture != GHIDRA_CAST(0x0)) && - (1 < GHIDRA_UINT(((GHIDRA_INT(g_beamRendererPointsEnd) - GHIDRA_INT(g_beamRendererPoints)) / 0x44)))) { - if ((char)DAT_00c78ef8 == '\0') { - animState = &DAT_00c78ef0->_animState; - } - else { - animState = &DAT_00c78ef0->_overlayAnimState; - } - pfVar2 = AnimationState::GetLayerFrame(animState,GHIDRA_INT(DAT_00c78ef4)); - layerFrame = pfVar2; - if (pfVar2 != GHIDRA_CAST(0x0)) { - iVar4 = *GHIDRA_CAST(ThreadLocalStoragePointer); - if ((*GHIDRA_CAST((iVar4 + 0xc)) < DAT_00c7f6d0) && (_Init_thread_header(), DAT_00c7f6d0 == -1)) { - _atexit(GHIDRA_CAST<_func_4879 *>(&LAB_00b15320)); - _Init_thread_footer(); - } - if ((*GHIDRA_CAST((iVar4 + 0xc)) < DAT_00c7f6e0) && (_Init_thread_header(), DAT_00c7f6e0 == -1)) { - _atexit(GHIDRA_CAST<_func_4879 *>(&LAB_00b15310)); - _Init_thread_footer(); - } - DAT_00c7f6d8 = DAT_00c7f6d4; - DAT_00c7f6e8 = DAT_00c7f6e4; - layer = ANM2::GetLayer(DAT_00c78ef0,DAT_00c78ef4); - isPerVertexColor = '\0'; - layerFlipX = layer->_flipX; - spriteFlipX = DAT_00c78ef0->_flipX; - pfVar5 = g_beamRendererPoints; - if (g_beamRendererPoints != (void *)(GHIDRA_INT(g_beamRendererPointsEnd) + -0x44)) { -LAB_0041eac0: - local_a0 = pfVar5 + 0x11; - fVar7 = pfVar2[2]; - local_b4 = fVar7 * pfVar5[4] * pfVar5[2] * 0.5; - local_b0 = GHIDRA_CAST((fVar7 * pfVar5[4] * pfVar5[3] * 0.5)); - fVar9 = fVar7 * pfVar5[0x15] * pfVar5[0x13] * 0.5; - nextEdgeOffsetY = fVar7 * pfVar5[0x15] * pfVar5[0x14] * 0.5; - fVar8 = pfVar5[5]; - cVar1 = (char)(GHIDRA_UINT(DAT_00c78ef8) >> 8); - if (cVar1 != '\0') { - fVar8 = fVar8 * pfVar2[3]; - } - nextUvY = pfVar5[0x16]; - if (cVar1 != '\0') { - nextUvY = nextUvY * pfVar2[3]; - } - uvLeft = *pfVar2; - nextUvY = pfVar2[1] + nextUvY; - fVar7 = fVar7 + uvLeft; - piVar6 = GHIDRA_CAST((pfVar2[1] + fVar8)); - local_ac = fVar9; - local_a8 = nextEdgeOffsetY; - if (layerFlipX == spriteFlipX) { - local_158.x = fVar7; - local_158.y = nextUvY; - local_150.x = uvLeft; - local_150.y = nextUvY; - local_148.x = fVar7; - local_148.y = (float)piVar6; - local_140.x = uvLeft; - local_140.y = (float)piVar6; - DestinationQuad::DestinationQuad - (GHIDRA_CAST(local_1dc),&local_140,&local_148,&local_150,&local_158); - local_1bc = 1; - if (DAT_00c7f6d8 == DAT_00c7f6dc) goto LAB_0041eca3; - (GHIDRA_CAST((DAT_00c7f6d8)))->SourceQuad::SourceQuad(local_1dc); - DAT_00c7f6d8 = DAT_00c7f6d8 + 1; - } - else { - local_168.x = uvLeft; - local_168.y = nextUvY; - (*GHIDRA_CAST((GHIDRA_CAST(&(local_160)) + 0x0))) = fVar7; - (*GHIDRA_CAST((GHIDRA_CAST(&(local_160)) + 0x4))) = nextUvY; - local_128.x = fVar7; - local_128.y = (float)piVar6; - local_c0.x = uvLeft; - local_c0.y = (float)piVar6; - DestinationQuad::DestinationQuad - (GHIDRA_CAST(local_1dc),&local_128,&local_c0,GHIDRA_CAST(&local_160), - &local_168); - local_1bc = 1; - if (DAT_00c7f6d8 == DAT_00c7f6dc) { -LAB_0041eca3: - local_1bc = 1; - msvc::vector::_Emplace_reallocate(); - fVar9 = local_ac; - nextEdgeOffsetY = local_a8; - } - else { - (GHIDRA_CAST((DAT_00c7f6d8)))->SourceQuad::SourceQuad(local_1dc); - DAT_00c7f6d8 = DAT_00c7f6d8 + 1; - } - } - (GHIDRA_CAST((GHIDRA_CAST((local_1dc + 0x10)))))->KColor::SetFromARGB(0xffffffff); - local_138.x = *local_a0 - fVar9; - endCornerA.x = fVar9 + *local_a0; - local_138.y = local_a0[1] - nextEdgeOffsetY; - endCornerA.y = nextEdgeOffsetY + local_a0[1]; - startCornerB.x = *pfVar5 - local_b4; - startCornerA.x = *pfVar5 + local_b4; - startCornerB.y = pfVar5[1] - (float)local_b0; - startCornerA.y = (float)local_b0 + pfVar5[1]; - pvVar3 = set_quad_corner_colors - (coloredQuad,&startCornerA,&startCornerB,&endCornerA,&local_138,color); - if (DAT_00c7f6e8 == DAT_00c7f6ec) { - FUN_0041fa30(); - } - else { - render_quad_copy(DAT_00c7f6e8,pvVar3); - DAT_00c7f6e8 = (void *)(GHIDRA_INT(DAT_00c7f6e8) + 0x70); - } - if (isPerVertexColor == '\0') { - pointColor._tint[0] = pfVar5[6]; - pointColor._tint[1] = pfVar5[7]; - pointColor._tint[2] = pfVar5[8]; - pointColor._tint[3] = pfVar5[9]; - pointColor._offset[2] = pfVar5[0x10]; - pointColor._colorize[0] = pfVar5[10]; - pointColor._colorize[1] = pfVar5[0xb]; - pointColor._colorize[2] = pfVar5[0xc]; - pointColor._colorize[3] = pfVar5[0xd]; - (*GHIDRA_CAST((GHIDRA_CAST(&(pointColor._offset)) + 0x0))) = *GHIDRA_CAST((pfVar5 + 0xe)); - (GHIDRA_CAST((&pointColor)))->Color::__mul(GHIDRA_CAST((pfVar2 + 0xc))); - nextPointColor._tint[0] = local_a0[6]; - nextPointColor._tint[1] = local_a0[7]; - nextPointColor._tint[2] = local_a0[8]; - nextPointColor._tint[3] = local_a0[9]; - nextPointColor._colorize[0] = local_a0[10]; - nextPointColor._colorize[1] = local_a0[0xb]; - nextPointColor._colorize[2] = local_a0[0xc]; - nextPointColor._colorize[3] = local_a0[0xd]; - (*GHIDRA_CAST((GHIDRA_CAST(&(nextPointColor._offset)) + 0x0))) = *GHIDRA_CAST((local_a0 + 0xe)); - nextPointColor._offset[2] = local_a0[0x10]; - (GHIDRA_CAST((&nextPointColor)))->Color::__mul(GHIDRA_CAST((pfVar2 + 0xc))); - local_16c = 0; - pfVar2 = local_17c; - local_180 = 0; - pfVar5 = local_1b8 + 10; - local_17c[0] = pointColor._colorize[0]; - local_17c[1] = pointColor._colorize[1]; - local_17c[2] = pointColor._colorize[2]; - local_17c[3] = pointColor._colorize[3]; - bytesLeft = 0xc; - local_1b8[10] = nextPointColor._colorize[0]; - local_1b8[0xb] = nextPointColor._colorize[1]; - local_1b8[0xc] = nextPointColor._colorize[2]; - local_1b8[0xd] = nextPointColor._colorize[3]; - do { - if (*pfVar2 != *pfVar5) goto LAB_0041ef3a; - pfVar2 = pfVar2 + 1; - pfVar5 = pfVar5 + 1; - isBytesLeft = 3 < bytesLeft; - bytesLeft = bytesLeft - 4; - } while (isBytesLeft); - pfVar2 = local_1b8 + 5; - local_1b8[5] = pointColor._offset[0]; - pfVar5 = local_1b8; - bytesLeft = 0xc; - local_1b8[6] = pointColor._offset[1]; - local_1b8[7] = pointColor._offset[2]; - local_1b8[0] = nextPointColor._offset[0]; - local_1b8[1] = nextPointColor._offset[1]; - local_1b8[9] = 0.0; - local_1b8[8] = 1.0; - local_1b8[4] = 0.0; - local_1b8[2] = nextPointColor._offset[2]; - local_1b8[3] = 1.0; - do { - if (*pfVar2 != *pfVar5) goto LAB_0041ef3a; - pfVar2 = pfVar2 + 1; - pfVar5 = pfVar5 + 1; - isBytesLeft = 3 < bytesLeft; - bytesLeft = bytesLeft - 4; - } while (isBytesLeft); - isPerVertexColor = '\0'; - goto LAB_0041ef41; - } - goto LAB_0041ef47; - } -LAB_0041ef71: - (*GHIDRA_CAST((GHIDRA_CAST(&(local_1dc)) + 0x10))) = g_graphicsManager_blendMode[0]; - fStack_1c8 = (float)g_graphicsManager_blendMode[1]; - fStack_1c4 = (float)g_graphicsManager_blendMode[2]; - fStack_1c0 = (float)g_graphicsManager_blendMode[3]; - iVar4 = (GHIDRA_INT(DAT_00c7f6d8) - GHIDRA_INT(DAT_00c7f6d4)) / 0x24; - local_168.y = (float)g_graphicsManager_blendMode[4]; - local_b4 = (float)iVar4; - layer = ANM2::GetLayer(DAT_00c78ef0,DAT_00c78ef4); - g_graphicsManager_blendMode[0] = layer->_blendMode[0]; - g_graphicsManager_blendMode[1] = layer->_blendMode[1]; - g_graphicsManager_blendMode[2] = layer->_blendMode[2]; - g_graphicsManager_blendMode[3] = layer->_blendMode[3]; - g_graphicsManager_blendMode[4] = layer->_blendMode[4]; - local_a0 = GHIDRA_CAST(GHIDRA_UINT((isPerVertexColor != '\0'))); - layer = ANM2::GetLayer(DAT_00c78ef0,DAT_00c78ef4); - if (((DAT_00c78ef0->_bitflags | layer->_bitflags) & 0x20U) != 0) { - if (isPerVertexColor != '\0') { - KAGE_LogMessage(8,(uint8_t *) - "Beam renderer needs per-vertex colors for Dogma but his shader doesn\'t support it!\n" - ); - } - local_a0 = GHIDRA_CAST(0x2); - } - unusedArg = &g_shaders + GHIDRA_INT(local_a0) * 0x50; - if ((unusedArg != GHIDRA_CAST(0x0)) && (((&DAT_00c7911c)[GHIDRA_INT(local_a0) * 0x50] & 1) != 0)) { - g_currentShader = unusedArg; - } - if (iVar4 != 0) { - local_ac = 0.0; - (*GHIDRA_CAST((GHIDRA_CAST(&(local_160)) + 0x4))) = (float)CONCAT31((*GHIDRA_CAST((GHIDRA_CAST(&(local_160)) + 0x5))),local_a0 != GHIDRA_CAST(0x1)); - local_a8 = 0.0; - local_b0 = GHIDRA_CAST(0x0); - do { - fVar7 = pfVar2[0x10]; - fVar8 = pfVar2[0x11]; - fVar9 = pfVar2[0x12]; - pfVar5 = GHIDRA_CAST((local_b0 + 0x28 + GHIDRA_INT(g_beamRendererPoints))); - pointColor._colorize[0] = *pfVar5; - pointColor._colorize[1] = pfVar5[1]; - pointColor._colorize[2] = pfVar5[2]; - pointColor._colorize[3] = pfVar5[3]; - pfVar5 = GHIDRA_CAST((local_b0 + 0x18 + GHIDRA_INT(g_beamRendererPoints))); - (*GHIDRA_CAST((GHIDRA_CAST(&(pointColor._offset)) + 0x0))) = *GHIDRA_CAST((local_b0 + 0x38 + GHIDRA_INT(g_beamRendererPoints))); - local_138.y = pfVar2[0xc]; - pointColor._tint[0] = local_138.y * *pfVar5; - local_140.y = pfVar2[0xd]; - pointColor._tint[1] = local_140.y * pfVar5[1]; - local_148.y = pfVar2[0xe]; - pointColor._tint[2] = local_148.y * pfVar5[2]; - local_150.y = pfVar2[0xf]; - pointColor._tint[3] = local_150.y * pfVar5[3]; - local_158.y = fVar7 + fVar8 + fVar9; - if (local_158.y != 0.0) { - if (pointColor._colorize[0] + pointColor._colorize[1] + pointColor._colorize[2] == 0.0) - { - pointColor._colorize[0] = fVar7; - pointColor._colorize[1] = fVar8; - pointColor._colorize[2] = fVar9; - pointColor._colorize[3] = pfVar2[0x13]; - } - else { - pointColor._colorize[0] = (fVar7 + pointColor._colorize[0]) * 0.5; - pointColor._colorize[1] = (fVar8 + pointColor._colorize[1]) * 0.5; - pointColor._colorize[2] = (fVar9 + pointColor._colorize[2]) * 0.5; - pointColor._colorize[3] = (pointColor._colorize[3] + pfVar2[0x13]) * 0.5; - } - } - pointColor._offset[2] = - pfVar2[0x16] + *GHIDRA_CAST((local_b0 + 0x40 + GHIDRA_INT(g_beamRendererPoints))); - pfVar5 = GHIDRA_CAST((local_b0 + 0x5c + GHIDRA_INT(g_beamRendererPoints))); - shaderColor._offset[1] = pfVar2[0x15] + pointColor._offset[1]; - shaderColor._offset[0] = pfVar2[0x14] + pointColor._offset[0]; - shaderColor._colorize[0] = pointColor._colorize[0]; - shaderColor._colorize[1] = pointColor._colorize[1]; - shaderColor._colorize[2] = pointColor._colorize[2]; - shaderColor._colorize[3] = pointColor._colorize[3]; - nextPointColorize = GHIDRA_CAST((local_b0 + 0x6c + GHIDRA_INT(g_beamRendererPoints))); - nextPointColor._colorize[0] = *nextPointColorize; - nextPointColor._colorize[1] = nextPointColorize[1]; - nextPointColor._colorize[2] = nextPointColorize[2]; - (*GHIDRA_CAST((GHIDRA_CAST(&(nextPointColor._offset)) + 0x0))) = - *GHIDRA_CAST((local_b0 + 0x7c + GHIDRA_INT(g_beamRendererPoints))); - nextPointColor._tint[0] = local_138.y * *pfVar5; - nextPointColor._tint[1] = local_140.y * pfVar5[1]; - nextPointColor._tint[2] = local_148.y * pfVar5[2]; - nextPointColor._tint[3] = local_150.y * pfVar5[3]; - nextPointColor._colorize[3] = nextPointColorize[3]; - if (local_158.y != 0.0) { - nextPointColor._colorize[3] = pfVar2[0x13]; - if (nextPointColor._colorize[0] + nextPointColor._colorize[1] + - nextPointColor._colorize[2] != 0.0) { - fVar7 = (fVar7 + nextPointColor._colorize[0]) * 0.5; - fVar8 = (fVar8 + nextPointColor._colorize[1]) * 0.5; - nextPointColor._colorize[3] = - (nextPointColorize[3] + nextPointColor._colorize[3]) * 0.5; - fVar9 = (fVar9 + nextPointColor._colorize[2]) * 0.5; - } - nextPointColor._colorize[0] = fVar7; - nextPointColor._colorize[1] = fVar8; - nextPointColor._colorize[2] = fVar9; - } - nextPointColor._offset[2] = - pfVar2[0x16] + *GHIDRA_CAST((local_b0 + 0x84 + GHIDRA_INT(g_beamRendererPoints))); - piVar6 = GHIDRA_CAST(0x0); - imageRefCount = GHIDRA_CAST(0x0); - endOffsetXY = CONCAT44(pfVar2[0x15] + nextPointColor._offset[1], - pfVar2[0x14] + nextPointColor._offset[0]); - local_c0.y = (float)textureRefCount; - local_128.y = (float)texture; - endColorize = nextPointColor._colorize[0]; - fStack_40 = nextPointColor._colorize[1]; - fStack_3c = nextPointColor._colorize[2]; - fStack_38 = nextPointColor._colorize[3]; - shaderColor._tint[0] = pointColor._tint[0]; - shaderColor._tint[1] = pointColor._tint[1]; - shaderColor._tint[2] = pointColor._tint[2]; - shaderColor._tint[3] = pointColor._tint[3]; - shaderColor._offset[2] = pointColor._offset[2]; - endTint = nextPointColor._tint[0]; - fStack_50 = nextPointColor._tint[1]; - fStack_4c = nextPointColor._tint[2]; - fStack_48 = nextPointColor._tint[3]; - endOffsetZ = nextPointColor._offset[2]; - if (textureRefCount != GHIDRA_CAST(0x0)) { - cVar1 = (**(code **)(*textureRefCount + 4))(); - if (cVar1 != '\0') { - if (((imageRefCount != GHIDRA_CAST(0x0)) && - (cVar1 = (**(code **)(*imageRefCount + 0xc))(), cVar1 != '\0')) && - (g_imageReleaseFn != (void *)0x0)) { - (*g_imageReleaseFn)(auStack_202 + -10); - } - piVar6 = GHIDRA_CAST(local_128.y); - imageRefCount = GHIDRA_CAST(local_c0.y); - } - } - apply_sprite_shader_params(&shaderColor,SUB41((*GHIDRA_CAST((GHIDRA_CAST(&(local_160)) + 0x4))),0),piVar6,imageRefCount); - pvVar3 = DAT_00c7f6e4; - local_17c[3] = fStack_48; - local_1b8[0xd] = fStack_48; - local_17c[0] = endTint; - local_17c[1] = fStack_50; - local_17c[2] = fStack_4c; - local_1b8[10] = endTint; - local_1b8[0xb] = fStack_50; - local_1b8[0xc] = fStack_4c; - local_1b8[8] = shaderColor._tint[3]; - local_1b8[3] = shaderColor._tint[3]; - local_1b8[0] = shaderColor._tint[0]; - local_1b8[1] = shaderColor._tint[1]; - local_1b8[2] = shaderColor._tint[2]; - local_1b8[5] = shaderColor._tint[0]; - pfVar2 = GHIDRA_CAST((GHIDRA_INT(local_a8) + 0x20 + GHIDRA_INT(DAT_00c7f6e4))); - *pfVar2 = shaderColor._tint[0]; - pfVar2[1] = shaderColor._tint[1]; - pfVar2[2] = shaderColor._tint[2]; - pfVar2[3] = shaderColor._tint[3]; - *GHIDRA_CAST((GHIDRA_CAST(local_a8) + 0x30 + GHIDRA_INT(pvVar3))) = 0; - local_1b8[6] = shaderColor._tint[1]; - local_1b8[7] = shaderColor._tint[2]; - pfVar2 = GHIDRA_CAST((GHIDRA_INT(local_a8) + 0x34 + GHIDRA_INT(pvVar3))); - *pfVar2 = shaderColor._tint[0]; - pfVar2[1] = shaderColor._tint[1]; - pfVar2[2] = shaderColor._tint[2]; - pfVar2[3] = shaderColor._tint[3]; - *GHIDRA_CAST((GHIDRA_CAST(local_a8) + 0x44 + GHIDRA_INT(pvVar3))) = 0; - pfVar2 = GHIDRA_CAST((GHIDRA_INT(local_a8) + 0x48 + GHIDRA_INT(pvVar3))); - *pfVar2 = endTint; - pfVar2[1] = fStack_50; - pfVar2[2] = fStack_4c; - pfVar2[3] = fStack_48; - *GHIDRA_CAST((GHIDRA_CAST(local_a8) + 0x58 + GHIDRA_INT(pvVar3))) = 0; - pfVar2 = GHIDRA_CAST((GHIDRA_INT(local_a8) + 0x5c + GHIDRA_INT(pvVar3))); - *pfVar2 = endTint; - pfVar2[1] = fStack_50; - pfVar2[2] = fStack_4c; - pfVar2[3] = fStack_48; - *GHIDRA_CAST((GHIDRA_CAST(local_a8) + 0x6c + GHIDRA_INT(pvVar3))) = 0; - iVar4 = (**(code **)(*texture + 0x14))(GHIDRA_INT(&(DAT_00c7f6d4->_topLeft).x) + GHIDRA_INT(local_ac)); - if ((iVar4 != 0) && (local_a0 == GHIDRA_CAST(0x1))) { - *GHIDRA_CAST((iVar4 + 0x24)) = shaderColor._colorize[0]; - *GHIDRA_CAST((iVar4 + 0x28)) = shaderColor._colorize[1]; - *GHIDRA_CAST((iVar4 + 0x2c)) = shaderColor._colorize[2]; - *GHIDRA_CAST((iVar4 + 0x30)) = shaderColor._colorize[3]; - *GHIDRA_CAST((iVar4 + 0x34)) = (*GHIDRA_CAST((GHIDRA_CAST(&(shaderColor._offset)) + 0x0))); - *GHIDRA_CAST((iVar4 + 100)) = shaderColor._colorize[0]; - *GHIDRA_CAST((iVar4 + 0x68)) = shaderColor._colorize[1]; - *GHIDRA_CAST((iVar4 + 0x6c)) = shaderColor._colorize[2]; - *GHIDRA_CAST((iVar4 + 0x70)) = shaderColor._colorize[3]; - *GHIDRA_CAST((iVar4 + 0x3c)) = shaderColor._offset[2]; - *GHIDRA_CAST((iVar4 + 0x74)) = (*GHIDRA_CAST((GHIDRA_CAST(&(shaderColor._offset)) + 0x0))); - *GHIDRA_CAST((iVar4 + 0x7c)) = shaderColor._offset[2]; - *GHIDRA_CAST((iVar4 + 0xb4)) = endOffsetXY; - *GHIDRA_CAST((iVar4 + 0xf4)) = endOffsetXY; - *GHIDRA_CAST((iVar4 + 0xa4)) = endColorize; - *GHIDRA_CAST((iVar4 + 0xa8)) = fStack_40; - *GHIDRA_CAST((iVar4 + 0xac)) = fStack_3c; - *GHIDRA_CAST((iVar4 + 0xb0)) = fStack_38; - *GHIDRA_CAST((iVar4 + 0xbc)) = endOffsetZ; - *GHIDRA_CAST((iVar4 + 0xe4)) = endColorize; - *GHIDRA_CAST((iVar4 + 0xe8)) = fStack_40; - *GHIDRA_CAST((iVar4 + 0xec)) = fStack_3c; - *GHIDRA_CAST((iVar4 + 0xf0)) = fStack_38; - *GHIDRA_CAST((iVar4 + 0xfc)) = endOffsetZ; - } - local_a8 = (float)(GHIDRA_INT(local_a8) + 0x70); - unusedArg = local_b0 + 0x44; - local_ac = (float)(GHIDRA_INT(local_ac) + 0x24); - local_b4 = (float)(GHIDRA_INT(local_b4) + -1); - pfVar2 = layerFrame; - local_b0 = unusedArg; - } while (local_b4 != 0.0); - } - g_graphicsManager_blendMode[0] = (*GHIDRA_CAST((GHIDRA_CAST(&(local_1dc)) + 0x10))); - g_graphicsManager_blendMode[1] = GHIDRA_INT(fStack_1c8); - g_graphicsManager_blendMode[2] = GHIDRA_INT(fStack_1c4); - g_graphicsManager_blendMode[3] = GHIDRA_INT(fStack_1c0); - g_graphicsManager_blendMode[4] = GHIDRA_INT(local_168.y); - shader_cache_find(GHIDRA_INT(unusedArg)); - } - } - local_14 = 1; - if (((textureRefCount != GHIDRA_CAST(0x0)) && - (cVar1 = (**(code **)(*textureRefCount + 0xc))(), cVar1 != '\0')) && - (g_imageReleaseFn != (void *)0x0)) { - (*g_imageReleaseFn)(); - } - ExceptionList = local_1c; - return; -LAB_0041ef3a: - isPerVertexColor = '\x01'; -LAB_0041ef41: - pfVar2 = layerFrame; -LAB_0041ef47: - pfVar5 = local_a0; - if (local_a0 == GHIDRA_CAST((GHIDRA_INT(g_beamRendererPointsEnd) + -0x44))) goto LAB_0041ef71; - goto LAB_0041eac0; -} diff --git a/generated-src/classes.h b/generated-src/classes.h index 6ba84a7..3f13505 100644 --- a/generated-src/classes.h +++ b/generated-src/classes.h @@ -136,6 +136,7 @@ struct AnmFileData; struct Backdrop; struct BackdropConfig; struct BackwardsStageDesc; +struct BeamPoint; struct BeamRenderer; struct BeastArena; struct BezierPoint; @@ -161,6 +162,7 @@ struct CellSpace; struct ChallengeParam; struct ChallengeParams; struct Checksum; +struct ClubSwing; struct CoPlayerState; struct Color; struct ColorMod; @@ -315,6 +317,7 @@ struct GridEntity_TrapDoor; struct GridEntity_Wall; struct GridEntity_Web; struct GridHurt; +struct GridPath; struct GroupIconResource; struct HBITMAP__; struct HBRUSH__; @@ -375,6 +378,7 @@ struct KAGE_ReferenceCount_ImageBase; struct KColor; struct KerningPair; struct KeyConfigs; +struct KnifeHit; struct KnifeShot; struct KnifeThrow; struct LRoomAreaDesc; @@ -405,6 +409,7 @@ struct LuaEngine; struct LuaIgnored; struct LuaItemUse; struct LuaMod; +struct LuaOpaque; struct LuaRef; struct LuaRoomList; struct MTRNG; @@ -527,6 +532,7 @@ struct RadiusDamage; struct RailManager; struct RailPoint; struct RainSpawner; +struct Reach; struct RebirthSaveData; struct RedirectedPath; struct ReferenceCountBase; @@ -580,6 +586,7 @@ struct ShopRestock; struct SimpleString; struct Size; struct SkinColors; +struct SlotDrop; struct SmeltedTrinket; struct SoundEffect; struct SoundEffects; @@ -613,9 +620,11 @@ struct TechLaserShot; struct TechXShot; struct TemporaryEffect; struct TemporaryEffects; +struct TexelQuery; struct TextMeasure; struct TexturePtr; struct Thread; +struct TrailPoint; struct TrinketPoolItem; struct TypeDescriptor; struct UmbilicalBabyData; @@ -972,22 +981,6 @@ LAYOUT32(offsetof(Ambush, _maxWaves) == 0x18); LAYOUT32(offsetof(Ambush, _isActive) == 0x20); LAYOUT32(offsetof(Ambush, _currentWave) == 0x24); -struct BeamRenderer { - static void Begin(ANM2 *anm2, uint32_t layer, uint8_t isUseOverlay, uint8_t isUnk); // 0041e480 - static void Add(Vector *point, ColorMod *color, float spritesheetCoordinate, float width); // 0041e720 - static void End(); // 0041e960 - - uint8_t _anm2[0x118]; // ANM2 - int _layer; - uint8_t _useOverlayData; - uint8_t _unkBool; -}; -LAYOUT32(offsetof(BeamRenderer, _anm2) == 0x0); -LAYOUT32(offsetof(BeamRenderer, _layer) == 0x118); -LAYOUT32(offsetof(BeamRenderer, _useOverlayData) == 0x11c); -LAYOUT32(offsetof(BeamRenderer, _unkBool) == 0x11d); -LAYOUT32(sizeof(BeamRenderer) == 0x11e); - struct BitSet128 { static BitSet128 * operator_and(BitSet128 *outResult, BitSet128 *a, BitSet128 *b); // 00417170 uint8_t IsNonZero(); // 004171b0 @@ -3943,13 +3936,6 @@ LAYOUT32(offsetof(Sprite, _shadowLayerIndex) == 0x10c); LAYOUT32(offsetof(Sprite, _bitflags) == 0x110); LAYOUT32(sizeof(Sprite) == 0x114); -struct SpriteTrailData { - virtual ~SpriteTrailData(); // 005d2370 slot 0 ::FUN_005d2370 - - uint8_t _pad_0x4[0x14]; -}; -LAYOUT32(sizeof(SpriteTrailData) == 0x18); - struct StatsPanel { static void add_stat_line(); // 0084dc00 void set(Entity_Player *player, uint8_t isGoldenTrinket); // 0084dea0 @@ -4013,60 +3999,6 @@ struct UserProfile { }; -struct VideoPlayer { - void play(uint8_t *fileName, float volume); // 009f2ee0 - void unload(); // 00a62880 - static void render(uint8_t param_1); // 00a62b10 -}; - - -struct Weapon_Bombs { - virtual ~Weapon_Bombs(); // 009f9880 slot 0 - virtual void Init(uint32_t param_2, uint32_t param_3); // 009f34d0 slot 1 Weapon::Init - virtual void Update(char param_2); // 009f34f0 slot 2 Weapon::Update - virtual void Fire(Vector *param_1, uint8_t param_2, uint8_t param_3); // 009f9b60 slot 3 - virtual void Reset(); // 009f3480 slot 4 Weapon::Reset - virtual void ClearReferences(); // 009f3320 slot 5 Weapon::ClearReferences - virtual long double GetMaxCharge(); // 009f3130 slot 6 Weapon::GetMaxCharge - virtual long double GetChargeBarAmount(); // 009f4150 slot 7 Weapon::GetChargeBarAmount - virtual void vfunc_8(); // 009f3130 slot 8 Weapon::GetMaxCharge - virtual Entity * GetFocusEntity(); // 009fa190 slot 9 - virtual Entity * GetMainEntity(); // 009f3150 slot 10 Weapon::GetMainEntity - virtual void guard_check_icall(); // 0040c200 slot 11 ::guard_check_icall - virtual int GetMarkedTargetVariant(); // 009fa1b0 slot 12 - virtual uint8_t CanTakeDamageFromTearEffects(); // 00709c30 slot 13 GridEntity::CanTakeDamageFromTearEffects - virtual uint8_t CanShutDoors(); // 005ccc00 slot 14 Entity::CanShutDoors - virtual void vfunc_15(); // 005ccc00 slot 15 Entity::CanShutDoors - virtual void vfunc_16(); // 005ccc00 slot 16 Entity::CanShutDoors - - uint8_t _pad_0x4[0x44]; -}; -LAYOUT32(sizeof(Weapon_Bombs) == 0x48); - -struct Weapon_Bone { - virtual ~Weapon_Bone(); // 009f9aa0 slot 0 - virtual void Init(uint32_t param_2, uint32_t param_3); // 009f34d0 slot 1 Weapon::Init - virtual void Update(uint8_t isInterpolated); // 009fa220 slot 2 - virtual void Fire(Vector *direction, uint8_t isShooting, uint8_t isInterpolated); // 009fa450 slot 3 - virtual void Reset(); // 009fed90 slot 4 - virtual void ClearReferences(); // 009fedf0 slot 5 - virtual long double GetMaxCharge(); // 009feeb0 slot 6 - virtual long double GetChargeBarAmount(); // 009f4150 slot 7 Weapon::GetChargeBarAmount - virtual void vfunc_8(); // 009f3130 slot 8 Weapon::GetMaxCharge - virtual int CountSeedEffects(); // 0085e1b0 slot 9 Seeds::CountSeedEffects - virtual Entity * GetMainEntity(); // 009f3150 slot 10 Weapon::GetMainEntity - virtual void TriggerNewRoom(); // 009fef20 slot 11 - virtual uint32_t GetFocusEntity(); // 009f3140 slot 12 Weapon::GetFocusEntity - virtual uint8_t CanShutDoors(); // 005ccc00 slot 13 Entity::CanShutDoors - virtual uint8_t CanTriggerCursedEyeTeleport(); // 009ff1a0 slot 14 - virtual uint8_t CanTriggerKidneyStone(); // 009ff210 slot 15 - virtual uint8_t CanOverrideForgottenThrow(); // 009ff230 slot 16 - static void init_club(int *param_1); // 009ff0c0 - - uint8_t _pad_0x4[0x5c]; -}; -LAYOUT32(sizeof(Weapon_Bone) == 0x60); - struct Weapon_Deathmatch { virtual ~Weapon_Deathmatch(); // 009f3260 slot 0 virtual void Init(uint32_t param_2, uint32_t param_3); // 009f34d0 slot 1 Weapon::Init @@ -6132,8 +6064,6 @@ uint8_t str_ne(std_string *a, uint8_t *b); // 004f84a0 void rng_pair_init(void *self); // 004f88a0 uint32_t FUN_004f88e0(); // 004f88e0 uint32_t FUN_004f8930(); // 004f8930 -void FUN_004f8cc0(int param_1); // 004f8cc0 -void quakey_timer_callback(Entity *source); // 004fd280 void pow_wrapper(); // 00505b40 void set_byte_0x101(void *self, uint8_t value); // 00505b50 int FUN_00505ca0(); // 00505ca0 @@ -6309,9 +6239,7 @@ void FUN_005cd840(uint32_t param_1); // 005cd840 void FUN_005cd850(); // 005cd850 void FUN_005cd8c0(uint8_t param_1); // 005cd8c0 void FUN_005cda90(); // 005cda90 -void FUN_005d2270(); // 005d2270 void FUN_005d2300(); // 005d2300 -void FUN_005d2370(uint8_t param_1); // 005d2370 void FUN_005d23a0(uint8_t param_1); // 005d23a0 void FUN_005d4210(); // 005d4210 void FUN_00607540(); // 00607540 @@ -6458,7 +6386,6 @@ void FUN_00676bd0(); // 00676bd0 int FUN_0067adc0(); // 0067adc0 void FUN_0067ae30(int *param_1); // 0067ae30 void FUN_0067af30(); // 0067af30 -void tear_flags_area_apply(Vector *position, Entity *source, float radius, float damage, BitSet128 flags); // 0067d430 uint32_t FUN_0067d9b0(); // 0067d9b0 void FUN_0067dac0(int *param_1); // 0067dac0 uint32_t * FUN_0067ef50(uint32_t *param_1, uint32_t *param_2, uint32_t *param_3); // 0067ef50 @@ -6732,12 +6659,10 @@ Entity_Player * FUN_007103c0(uint32_t *param_1); // 007103c0 uint32_t FUN_00710f70(int param_1); // 00710f70 void FUN_00711530(int param_1); // 00711530 uint32_t FUN_00711740(); // 00711740 -void FUN_007135d0(uint32_t param_1, uint8_t param_2, int *param_3); // 007135d0 void FUN_00718ed0(uint32_t param_1); // 00718ed0 uint32_t FUN_00718ee0(); // 00718ee0 void FUN_0071df70(uint8_t param_1); // 0071df70 void FUN_00721e60(int param_1, int param_2, int param_3, int param_4, int param_5, int param_6); // 00721e60 -void FUN_00721eb0(); // 00721eb0 void FUN_00722020(int param_1); // 00722020 void FUN_007221a0(uint32_t *param_1); // 007221a0 uint32_t * FUN_00722250(uint32_t *param_1, uint32_t *param_2, uint32_t *param_3); // 00722250 @@ -6896,7 +6821,6 @@ uint8_t teleport_to_random_room_of_types(Entity_Player *player, void *roomTypes, void FUN_007cf940(); // 007cf940 long double FUN_007cf9a0(float *param_1, KColor *param_2, uint32_t param_3); // 007cf9a0 uint8_t * FUN_007cfa90(); // 007cfa90 -bool FUN_007d1810(); // 007d1810 void FUN_007d3330(int param_1); // 007d3330 Game * damage_charge_scale(); // 007d3560 void FUN_007d3e00(); // 007d3e00 @@ -7007,7 +6931,6 @@ void FUN_007e9170(char param_1); // 007e9170 void FUN_007e92e0(uint32_t param_1, uint32_t param_2); // 007e92e0 void FUN_007e93d0(int param_1); // 007e93d0 void FUN_007ea0c0(); // 007ea0c0 -void FUN_007ebc40(); // 007ebc40 void FUN_00812ea0(float *param_1, int *param_2, int *param_3); // 00812ea0 uint32_t FUN_00813420(int param_1, int param_2); // 00813420 uint32_t FUN_0081e220(); // 0081e220 @@ -7086,7 +7009,6 @@ void FUN_0083c480(); // 0083c480 void item_pool_icons_render(void *iconLayer, Vector *position, KColor *color); // 0083d8c0 char * FUN_00840510(); // 00840510 std_string * int_to_string(std_string *outString, int value); // 00840540 -void collectible_icon_render(void *param_1, ColorMod *param_2, int *param_3, int *param_4); // 00848c20 void FUN_0084a870(float *param_1); // 0084a870 void FUN_0084abc0(uint32_t *param_1, float *param_2, uint32_t *param_3, uint32_t *param_4); // 0084abc0 void FUN_0084bba0(); // 0084bba0 @@ -9265,23 +9187,16 @@ void Catch_All_0095c01b(); // 0095c01b void * FUN_0095c430(void *param_1, void *param_2, void *param_3); // 0095c430 void Catch_All_0095c63e(); // 0095c63e void FUN_0095c670(); // 0095c670 -int FUN_0095c930(); // 0095c930 -uint32_t FUN_0095c960(); // 0095c960 void FUN_0095eb00(uint32_t param_1, int param_2); // 0095eb00 void cutscene_render_skip_vote_count(void *cutscene, void *state); // 0095eb60 -void FUN_0095fbd0(); // 0095fbd0 -void FUN_0095fcd0(uint32_t *param_1); // 0095fcd0 -uint32_t FUN_0095fd40(); // 0095fd40 uint32_t * FUN_00960880(void *param_1, uint32_t *param_2); // 00960880 void FUN_00960bc0(); // 00960bc0 -uint32_t FUN_00961ad0(); // 00961ad0 void FUN_0096d120(int *param_1); // 0096d120 uint32_t FUN_0097e7c0(); // 0097e7c0 void pressure_plate_kill_enemies_timer_callback(int *param_1); // 00983f30 void FUN_0098b0a0(); // 0098b0a0 void FUN_0098b130(); // 0098b130 void FUN_00993740(); // 00993740 -uint32_t * FUN_00995f40(uint32_t *param_1); // 00995f40 void FUN_00997660(void *param_1, int param_2); // 00997660 void FUN_009976c0(void *param_1, int param_2); // 009976c0 void Catch_All_009979a9(); // 009979a9 @@ -9292,7 +9207,6 @@ uint32_t * FUN_009983f0(uint32_t *param_1); // 009983f0 void netplay_player_list_destructor(void *self); // 00998800 void FUN_0099a830(); // 0099a830 void FUN_0099c310(); // 0099c310 -float bezier_closest_point(Vector *point, void *segmentStart, void *segmentEnd, float *outT); // 0099c430 void ** vector_LaserSample_erase(void *self, void **outIter, void *where); // 009a1610 void FUN_009a1770(uint32_t *param_1); // 009a1770 void * vector_LaserSample_emplace_reallocate(void *self, void *where, void *value); // 009a17b0 @@ -9485,8 +9399,6 @@ uint32_t * FUN_009f9350(); // 009f9350 uint32_t * FUN_009f93d0(); // 009f93d0 uint32_t * FUN_009f9440(); // 009f9440 uint32_t * FUN_009f95d0(); // 009f95d0 -uint32_t * FUN_009f96c0(); // 009f96c0 -uint32_t * FUN_009f9740(); // 009f9740 uint32_t * FUN_00a06940(void *param_1, uint32_t *param_2); // 00a06940 void * operator_new(uint32_t size); // 00a0f4c0 void * operator_new_tracked(uint32_t size); // 00a0f4e0 @@ -21192,7 +21104,6 @@ ItemConfig * GetItemConfig(); // 0042ca00 void SpawnLocust(Entity_Player *player, int collectibleType, Vector *pos); // 005b35c0 int Random(int Max); // 0067f010 Vector * GetRandomPickupVelocity(Vector *outVelocity, Vector *position, uint32_t pickupVelType, RNG *rng); // 006ee440 -Vector * GetCollectibleSpawnPosition(Vector *outPosition, Vector *target); // 006eeaa0 void Shutdown(); // 009ab700 } namespace ItemInfo { @@ -21242,19 +21153,10 @@ void ENTITY_BIG_HORN(Entity_NPC *npc); // 00453140 void ENTITY_FLY_isaac_spawned(Entity_NPC *npc); // 004568d0 void ENTITY_WAR(Entity_NPC *npc); // 00458870 void ENTITY_DEATH(Entity_NPC *npc); // 00459d20 -void ENTITY_FALLEN(Entity_NPC *npc); // 0045b830 void ENTITY_HEADLESS_HORSEMAN(Entity_NPC *npc); // 0045cd60 void ENTITY_DARK_ONE(Entity_NPC *npc); // 0045d7d0 float ENTITY_ISAAC(Entity_NPC *npc); // 00463100 -void ENTITY_DADDYLONGLEGS(Entity_NPC *npc); // 00468180 -void ENTITY_SLOTH(Entity_NPC *npc); // 004741f0 -void ENTITY_LUST(Entity_NPC *npc); // 00474e00 -void ENTITY_WRATH(Entity_NPC *npc); // 00475110 -void ENTITY_GREED(Entity_NPC *npc); // 00475a30 -void ENTITY_ENVY(Entity_NPC *npc); // 004760a0 void ENTITY_PIN(Entity_NPC *npc); // 00476860 -void ENTITY_PRIDE(Entity_NPC *npc); // 00479d80 -Entity_NPC * ENTITY_SATAN(Entity_NPC *npc); // 0047f640 void ENTITY_THE_LAMB(Entity_NPC *npc); // 00483710 void ENTITY_BROWNIE(Entity_NPC *npc); // 0048c3b0 void ENTITY_CORN_MINE(Entity_NPC *npc); // 0048ee30 @@ -21314,17 +21216,12 @@ void ENTITY_BALL_AND_CHAIN(Entity_NPC *npc); // 004f4730 void ENTITY_POOFER(Entity_NPC *npc); // 004f64e0 void ENTITY_MOCKULUS(Entity_NPC *npc); // 004f76f0 void ENTITY_MORNINGSTAR(Entity_NPC *npc); // 004f7e60 -void ENTITY_QUAKE_GRIMACE(Entity_NPC *npc); // 004f8960 -void ENTITY_BOMB_GRIMACE(Entity_NPC *npc); // 004f8df0 void ENTITY_ROCK_SPIDER(Entity_NPC *npc); // 004f9ad0 void ENTITY_FACELESS(Entity_NPC *npc); // 004faad0 void ENTITY_DANNY(Entity_NPC *npc); // 004fbd10 -void ENTITY_BLASTER(Entity_NPC *npc); // 004fcc20 -void ENTITY_QUAKEY(Entity_NPC *npc); // 004fd540 void ENTITY_MOLE(Entity_NPC *npc); // 004fdf80 void ENTITY_GYRO(Entity_NPC *npc); // 004ff620 void ENTITY_FIRE_WORM(Entity_NPC *npc); // 00500990 -void ENTITY_HARDY(Entity_NPC *npc); // 00500f70 void ENTITY_BOUNCER(Entity_NPC *npc); // 00501f30 void ENTITY_FLESH_MAIDEN(Entity_NPC *npc); // 00502980 void ENTITY_BOMBGAGGER(Entity_NPC *npc); // 00503300 @@ -21340,12 +21237,8 @@ void ENTITY_HANGER(Entity_NPC *npc); // 0051cb30 void ENTITY_URIEL(Entity_NPC *npc); // 0051e0f0 void ENTITY_HEART(Entity_NPC *npc); // 0051f2f0 void ENTITY_POKY(Entity_NPC *npc); // 00521ab0 -void ENTITY_EYE(Entity_NPC *npc); // 00522ef0 -void ENTITY_FRED(Entity_NPC *npc); // 00524a10 void ENTITY_DOPLE(Entity_NPC *npc); // 00525650 void ENTITY_BABY(Entity_NPC *npc); // 0052ae30 -void ENTITY_VIS_chubber_projectile(Entity_NPC *npc); // 0052c2f0 -void ENTITY_VIS(Entity_NPC *npc); // 0052c720 void ENTITY_COD_WORM(Entity_NPC *npc); // 00531350 void ENTITY_MOBILE_HOST(Entity_NPC *npc); // 005321d0 void ENTITY_MOMS_HAND(Entity_NPC *npc); // 00533b80 @@ -21353,8 +21246,6 @@ void ENTITY_WIZOOB(Entity_NPC *npc); // 005374a0 void ENTITY_HOMUNCULUS(Entity_NPC *npc); // 00539b90 void ENTITY_OOB(Entity_NPC *npc); // 0053ab40 void ENTITY_BLACK_MAW(Entity_NPC *npc); // 0053b2f0 -void ENTITY_WALL_CREEP(Entity_NPC *npc); // 0053c0d0 -Entity_Effect * ENTITY_MEATBALL(Entity_NPC *npc); // 00541ce0 float ENTITY_TARBOY(Entity_NPC *npc); // 005442a0 void ENTITY_FISTULOID(Entity_NPC *npc); // 00545f70 void ENTITY_GUSH(Entity_NPC *npc); // 00547330 diff --git a/generated-src/npc_helper.cpp b/generated-src/npc_helper.cpp index 110c3a6..63a1f07 100644 --- a/generated-src/npc_helper.cpp +++ b/generated-src/npc_helper.cpp @@ -6820,170 +6820,6 @@ LAB_00548a4b: return; } -// 0054f670 -void NpcHelper::needle_render(Entity_NPC *npc) -{ - float fVar1; - double dVar2; - uint32_t trailStart; - int iVar4; - float *pfVar5; - int iVar6; - LayerState *layer; - int iVar7; - uint32_t uVar8; - int iVar9; - uint32_t uVar10; - uint32_t heightIndex; - int segmentCount; - float *segmentPosCursor; - uint32_t trailIndex; - float fVar11; - float fVar12; - float fVar13; - float fVar14; - float fVar15; - float prevHeight; - float remainingSpacing; - Vector prevPos; - uint8_t *layerIndex; - int segmentsLeft; - float segmentData [7]; - int *trailHeights; - int *trailPositions; - uint32_t trailStart; - - if ((npc->_state == 6) && (2 < GHIDRA_UINT((npc->_sprite)._layerCount))) { - pfVar5 = segmentData; - iVar7 = 2; - do { - pfVar5 = pfVar5 + 2; - pfVar5[1] = 0.0; - *pfVar5 = 0.0; - iVar7 = iVar7 + -1; - } while (iVar7 != 0); - segmentCount = 0; - remainingSpacing = 15.0; - trailStart = (npc->_vectorDeque1)._offset; - prevPos.x = (npc->_pos).x; - prevPos.y = (npc->_pos).y; - prevHeight = (npc->_v1).y; - iVar7 = *GHIDRA_CAST((GHIDRA_CAST(g_game->_room) + 0x12bc)); - trailPositions = (npc->_vectorDeque1)._proxy; - heightIndex = (npc->_vectorDeque2)._offset; - trailHeights = (npc->_vectorDeque2)._proxy; - trailStart = (npc->_vectorDeque1)._size; - trailIndex = trailStart; - while (trailIndex != trailStart + trailStart) { - if (trailPositions == GHIDRA_CAST(0x0)) { - iVar6 = 0; - } - else { - iVar6 = *trailPositions; - } - iVar4 = (trailIndex & 1) * 8; - pfVar5 = GHIDRA_CAST((*GHIDRA_CAST((*GHIDRA_CAST((iVar6 + 4)) + - (*GHIDRA_CAST((iVar6 + 8)) - 1U & trailIndex >> 1) * 4)) + iVar4)); - fVar14 = *pfVar5 - prevPos.x; - fVar12 = pfVar5[1] - prevPos.y; - if (trailHeights == GHIDRA_CAST(0x0)) { - iVar6 = 0; - } - else { - iVar6 = *trailHeights; - } - uVar8 = heightIndex >> 1; - iVar9 = (heightIndex & 1) * 8; - fVar15 = *GHIDRA_CAST((*GHIDRA_CAST((*GHIDRA_CAST((iVar6 + 4)) + (*GHIDRA_CAST((iVar6 + 8)) - 1U & uVar8) * 4)) + 4 - + iVar9)) - prevHeight; - fVar11 = sqrtf(fVar12 * fVar12 + fVar14 * fVar14 + fVar15 * fVar15); - remainingSpacing = remainingSpacing - fVar11; - if (0.0 < remainingSpacing) { - if (trailPositions == GHIDRA_CAST(0x0)) { - iVar6 = 0; - } - else { - iVar6 = *trailPositions; - } - pfVar5 = GHIDRA_CAST((*GHIDRA_CAST((*GHIDRA_CAST((iVar6 + 4)) + - (*GHIDRA_CAST((iVar6 + 8)) - 1U & trailIndex >> 1) * 4)) + iVar4)); - prevPos.x = *pfVar5; - prevPos.y = pfVar5[1]; - if (trailHeights == GHIDRA_CAST(0x0)) { - iVar6 = 0; - } - else { - iVar6 = *trailHeights; - } - trailIndex = trailIndex + 1; - heightIndex = heightIndex + 1; - prevHeight = *GHIDRA_CAST((*GHIDRA_CAST((*GHIDRA_CAST((iVar6 + 4)) + - (*GHIDRA_CAST((iVar6 + 8)) - 1U & uVar8) * 4)) + 4 + iVar9)); - } - else { - fVar11 = (fVar11 + remainingSpacing) / fVar11; - prevPos.x = fVar14 * fVar11 + prevPos.x; - prevPos.y = fVar12 * fVar11 + prevPos.y; - prevHeight = fVar11 * fVar15 + prevHeight; - segmentData[segmentCount * 2 + 2] = prevPos.x; - segmentData[segmentCount * 2 + 3] = prevPos.y; - segmentData[segmentCount] = prevHeight; - segmentCount = segmentCount + 1; - remainingSpacing = 15.0; - if (1 < segmentCount) goto LAB_0054f962; - uVar10 = heightIndex - 1; - uVar8 = trailIndex - 1; - if (trailIndex <= trailStart) { - uVar10 = heightIndex; - uVar8 = trailIndex; - } - trailIndex = uVar8 + 1; - heightIndex = uVar10 + 1; - } - } - if (segmentCount < 2) { - pfVar5 = segmentData + segmentCount; - for (iVar6 = 2 - segmentCount; iVar6 != 0; iVar6 = iVar6 + -1) { - *pfVar5 = prevHeight; - pfVar5 = pfVar5 + 1; - } - do { - segmentData[segmentCount * 2 + 2] = prevPos.x; - segmentData[segmentCount * 2 + 3] = prevPos.y; - segmentCount = segmentCount + 1; - } while (segmentCount < 2); - } -LAB_0054f962: - pfVar5 = segmentData; - segmentPosCursor = segmentData; - segmentsLeft = 2; - layerIndex = GHIDRA_CAST(0x1); - do { - segmentPosCursor = segmentPosCursor + 2; - fVar12 = *segmentPosCursor; - fVar14 = segmentPosCursor[1]; - fVar11 = (npc->_pos).x; - fVar15 = (npc->_pos).y; - fVar1 = *pfVar5; - fVar13 = (npc->_posOffset).y; - if (iVar7 == 5) { - fVar13 = -fVar13; - } - layer = ANM2::GetLayer(&npc->_sprite,layerIndex); - (layer->_pos).x = (fVar12 - fVar11) * 0.65; - (layer->_pos).y = ((fVar14 - fVar15) + (fVar1 - fVar13)) * 0.65; - dVar2 = __uint_to_double_fixup[-(GHIDRA_INT(layerIndex) >> 0x1f)]; - fVar12 = *pfVar5; - layer = ANM2::GetLayer(&npc->_sprite,layerIndex); - pfVar5 = pfVar5 + 1; - layer->_visible = fVar12 <= -6.0 - (float)((double)GHIDRA_INT(layerIndex) + dVar2) * 3.0; - layerIndex = layerIndex + 1; - segmentsLeft = segmentsLeft + -1; - } while (segmentsLeft != 0); - } - return; -} - // 00557f70 Vector * NpcHelper::willo_slot(Entity_NPC *npc, Vector *outPos, int slot) { diff --git a/generated-src/point.cpp b/generated-src/point.cpp deleted file mode 100644 index 8099f41..0000000 --- a/generated-src/point.cpp +++ /dev/null @@ -1,61 +0,0 @@ -#include "classes.h" - -// 0041e4c0 -void Point::UpdateNormal(Vector *unk) -{ - float fVar1; - float dirX; - float newNormalY; - float newNormalX; - float dirY; - float oldNormalX; - float oldNormalY; - - oldNormalX = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[2])) + 0x2)))); - if ((oldNormalX == g_vectorZero.x) && (*GHIDRA_CAST((this + 4)) == g_vectorZero.y)) { - dirX = unk->x - *GHIDRA_CAST(this); - dirY = unk->y - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x1)))); - oldNormalX = sqrtf(dirX * dirX + dirY * dirY); - unk = GHIDRA_CAST(dirX); - if (0.0 < oldNormalX) { - unk = GHIDRA_CAST((dirX * (1.0 / oldNormalX))); - dirY = dirY * (1.0 / oldNormalX); - } - oldNormalX = cos(1.5707964); - oldNormalY = sin(1.5707964); - *GHIDRA_CAST((this + 4)) = (float)unk * oldNormalY + dirY * oldNormalX; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[2])) + 0x2)))) = (float)unk * oldNormalX - dirY * oldNormalY; - return; - } - oldNormalY = *GHIDRA_CAST((this + 4)); - dirY = unk->y - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x1)))); - unk = GHIDRA_CAST((unk->x - *GHIDRA_CAST(this))); - fVar1 = sqrtf(dirY * dirY + (float)unk * (float)unk); - if (0.0 < fVar1) { - unk = GHIDRA_CAST(((float)unk * (1.0 / fVar1))); - dirY = dirY * (1.0 / fVar1); - } - fVar1 = cos(1.5707964); - newNormalY = sin(1.5707964); - newNormalX = ((float)unk * fVar1 - dirY * newNormalY) + oldNormalX; - newNormalY = (float)unk * newNormalY + dirY * fVar1 + *GHIDRA_CAST((this + 4)); - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[2])) + 0x2)))) = newNormalX; - *GHIDRA_CAST((this + 4)) = newNormalY; - fVar1 = sqrtf(newNormalY * newNormalY + newNormalX * newNormalX); - if (fVar1 <= 0.0) { - fVar1 = *GHIDRA_CAST((this + 4)); - } - else { - newNormalY = newNormalY * (1.0 / fVar1); - newNormalX = newNormalX * (1.0 / fVar1); - fVar1 = newNormalY; - } - oldNormalY = oldNormalY * newNormalY + oldNormalX * newNormalX; - oldNormalX = 0.4; - if (0.4 <= oldNormalY) { - oldNormalX = oldNormalY; - } - *GHIDRA_CAST((this + 4)) = fVar1 / oldNormalX; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[2])) + 0x2)))) = newNormalX / oldNormalX; - return; -} diff --git a/generated-src/stubs.cpp b/generated-src/stubs.cpp index 26df7d0..e5ec014 100644 --- a/generated-src/stubs.cpp +++ b/generated-src/stubs.cpp @@ -8227,9 +8227,6 @@ void Ambush::StartChallenge() { generated_stub("Ambush::StartChallenge 00833420" void Ambush::SpawnWave() { generated_stub("Ambush::SpawnWave 00833600"); } void Ambush::SpawnBossrushWave() { generated_stub("Ambush::SpawnBossrushWave 00833c40"); } void Ambush::Update() { generated_stub("Ambush::Update 00834350"); } -void BeamRenderer::Begin(ANM2 *anm2, uint32_t layer, uint8_t isUseOverlay, uint8_t isUnk) { generated_stub("BeamRenderer::Begin 0041e480"); } -void BeamRenderer::Add(Vector *point, ColorMod *color, float spritesheetCoordinate, float width) { generated_stub("BeamRenderer::Add 0041e720"); } -void BeamRenderer::End() { generated_stub("BeamRenderer::End 0041e960"); } BitSet128 * BitSet128::operator_and(BitSet128 *outResult, BitSet128 *a, BitSet128 *b) { generated_stub("BitSet128::operator_and 00417170"); } uint8_t BitSet128::IsNonZero() { generated_stub("BitSet128::IsNonZero 004171b0"); } BitSet128 * BitSet128::operator__(BitSet128 *other) { generated_stub("BitSet128::operator__ 00435bf0"); } @@ -9273,7 +9270,6 @@ void NpcHelper::bouncer_death_gib(Entity_Effect *timer) { generated_stub("NpcHel void NpcHelper::migraine_timer_spawn(Entity *timer) { generated_stub("NpcHelper::migraine_timer_spawn 00528ec0"); } uint8_t NpcHelper::tarboy_is_creep_near(Entity_NPC *npc, Vector *position) { generated_stub("NpcHelper::tarboy_is_creep_near 005441e0"); } void NpcHelper::leper_flesh_ai(Entity_NPC *npc) { generated_stub("NpcHelper::leper_flesh_ai 00548720"); } -void NpcHelper::needle_render(Entity_NPC *npc) { generated_stub("NpcHelper::needle_render 0054f670"); } Vector * NpcHelper::willo_slot(Entity_NPC *npc, Vector *outPos, int slot) { generated_stub("NpcHelper::willo_slot 00557f70"); } void NpcHelper::willo_get_target_pos(Entity_NPC *npc, Vector *outPos, float *outSpread) { generated_stub("NpcHelper::willo_get_target_pos 00558070"); } void NpcHelper::willo_orbit(Entity_NPC *npc) { generated_stub("NpcHelper::willo_orbit 005581b0"); } @@ -9335,7 +9331,6 @@ void PersistentGameDataWriter::write(PersistentGameData *data, void *header) { g PickupGhostData::~PickupGhostData() { generated_stub("PickupGhostData::~PickupGhostData 005d23a0"); } void PngWriter::write_end() { generated_stub("PngWriter::write_end 009e8d40"); } void PngWriter::write_info() { generated_stub("PngWriter::write_info 009e8ee0"); } -void Point::UpdateNormal(Vector *unk) { generated_stub("Point::UpdateNormal 0041e4c0"); } uint8_t ProceduralEffect::roll_trigger_target(uint32_t *outTarget, float *outChance, RNG *rng) { generated_stub("ProceduralEffect::roll_trigger_target 009e0700"); } uint8_t ProceduralEffect::roll_spawn_target(uint32_t *outTarget, float *outChance, RNG *rng) { generated_stub("ProceduralEffect::roll_spawn_target 009e0ad0"); } void ProceduralEffect::roll_params(int conditionType, int actionType, uint32_t seed) { generated_stub("ProceduralEffect::roll_params 009e0f60"); } @@ -9390,7 +9385,6 @@ int Sprite::GetLayerCount() { generated_stub("Sprite::GetLayerCount 00440e40"); void Sprite::set_offset(Vector *offset) { generated_stub("Sprite::set_offset 00456340"); } long double Sprite::PlaybackSpeed() { generated_stub("Sprite::PlaybackSpeed 00456360"); } Vector * Sprite::Offset() { generated_stub("Sprite::Offset 0049cb40"); } -SpriteTrailData::~SpriteTrailData() { generated_stub("SpriteTrailData::~SpriteTrailData 005d2370"); } void StatsPanel::add_stat_line() { generated_stub("StatsPanel::add_stat_line 0084dc00"); } void StatsPanel::set(Entity_Player *player, uint8_t isGoldenTrinket) { generated_stub("StatsPanel::set 0084dea0"); } void StatsPanel::snapshot_stats(uint32_t param_1) { generated_stub("StatsPanel::snapshot_stats 0084e9d0"); } @@ -9412,44 +9406,6 @@ void TexturePtr::release() { generated_stub("TexturePtr::release 0040c440"); } UmbilicalBabyData::~UmbilicalBabyData() { generated_stub("UmbilicalBabyData::~UmbilicalBabyData 00431790"); } uint32_t UmbilicalBabyData::last_point() { generated_stub("UmbilicalBabyData::last_point 00435590"); } void UserProfile::find_or_create() { generated_stub("UserProfile::find_or_create 00a23ae0"); } -void VideoPlayer::play(uint8_t *fileName, float volume) { generated_stub("VideoPlayer::play 009f2ee0"); } -void VideoPlayer::unload() { generated_stub("VideoPlayer::unload 00a62880"); } -void VideoPlayer::render(uint8_t param_1) { generated_stub("VideoPlayer::render 00a62b10"); } -Weapon_Bombs::~Weapon_Bombs() { generated_stub("Weapon_Bombs::~Weapon_Bombs 009f9880"); } -void Weapon_Bombs::Init(uint32_t param_2, uint32_t param_3) { generated_stub("Weapon_Bombs::Init 009f34d0"); } -void Weapon_Bombs::Update(char param_2) { generated_stub("Weapon_Bombs::Update 009f34f0"); } -void Weapon_Bombs::Fire(Vector *param_1, uint8_t param_2, uint8_t param_3) { generated_stub("Weapon_Bombs::Fire 009f9b60"); } -void Weapon_Bombs::Reset() { generated_stub("Weapon_Bombs::Reset 009f3480"); } -void Weapon_Bombs::ClearReferences() { generated_stub("Weapon_Bombs::ClearReferences 009f3320"); } -long double Weapon_Bombs::GetMaxCharge() { generated_stub("Weapon_Bombs::GetMaxCharge 009f3130"); } -long double Weapon_Bombs::GetChargeBarAmount() { generated_stub("Weapon_Bombs::GetChargeBarAmount 009f4150"); } -void Weapon_Bombs::vfunc_8() { generated_stub("Weapon_Bombs::vfunc_8 009f3130"); } -Entity * Weapon_Bombs::GetFocusEntity() { generated_stub("Weapon_Bombs::GetFocusEntity 009fa190"); } -Entity * Weapon_Bombs::GetMainEntity() { generated_stub("Weapon_Bombs::GetMainEntity 009f3150"); } -void Weapon_Bombs::guard_check_icall() { generated_stub("Weapon_Bombs::guard_check_icall 0040c200"); } -int Weapon_Bombs::GetMarkedTargetVariant() { generated_stub("Weapon_Bombs::GetMarkedTargetVariant 009fa1b0"); } -uint8_t Weapon_Bombs::CanTakeDamageFromTearEffects() { generated_stub("Weapon_Bombs::CanTakeDamageFromTearEffects 00709c30"); } -uint8_t Weapon_Bombs::CanShutDoors() { generated_stub("Weapon_Bombs::CanShutDoors 005ccc00"); } -void Weapon_Bombs::vfunc_15() { generated_stub("Weapon_Bombs::vfunc_15 005ccc00"); } -void Weapon_Bombs::vfunc_16() { generated_stub("Weapon_Bombs::vfunc_16 005ccc00"); } -Weapon_Bone::~Weapon_Bone() { generated_stub("Weapon_Bone::~Weapon_Bone 009f9aa0"); } -void Weapon_Bone::Init(uint32_t param_2, uint32_t param_3) { generated_stub("Weapon_Bone::Init 009f34d0"); } -void Weapon_Bone::Update(uint8_t isInterpolated) { generated_stub("Weapon_Bone::Update 009fa220"); } -void Weapon_Bone::Fire(Vector *direction, uint8_t isShooting, uint8_t isInterpolated) { generated_stub("Weapon_Bone::Fire 009fa450"); } -void Weapon_Bone::Reset() { generated_stub("Weapon_Bone::Reset 009fed90"); } -void Weapon_Bone::ClearReferences() { generated_stub("Weapon_Bone::ClearReferences 009fedf0"); } -long double Weapon_Bone::GetMaxCharge() { generated_stub("Weapon_Bone::GetMaxCharge 009feeb0"); } -long double Weapon_Bone::GetChargeBarAmount() { generated_stub("Weapon_Bone::GetChargeBarAmount 009f4150"); } -void Weapon_Bone::vfunc_8() { generated_stub("Weapon_Bone::vfunc_8 009f3130"); } -int Weapon_Bone::CountSeedEffects() { generated_stub("Weapon_Bone::CountSeedEffects 0085e1b0"); } -Entity * Weapon_Bone::GetMainEntity() { generated_stub("Weapon_Bone::GetMainEntity 009f3150"); } -void Weapon_Bone::TriggerNewRoom() { generated_stub("Weapon_Bone::TriggerNewRoom 009fef20"); } -uint32_t Weapon_Bone::GetFocusEntity() { generated_stub("Weapon_Bone::GetFocusEntity 009f3140"); } -uint8_t Weapon_Bone::CanShutDoors() { generated_stub("Weapon_Bone::CanShutDoors 005ccc00"); } -uint8_t Weapon_Bone::CanTriggerCursedEyeTeleport() { generated_stub("Weapon_Bone::CanTriggerCursedEyeTeleport 009ff1a0"); } -uint8_t Weapon_Bone::CanTriggerKidneyStone() { generated_stub("Weapon_Bone::CanTriggerKidneyStone 009ff210"); } -uint8_t Weapon_Bone::CanOverrideForgottenThrow() { generated_stub("Weapon_Bone::CanOverrideForgottenThrow 009ff230"); } -void Weapon_Bone::init_club(int *param_1) { generated_stub("Weapon_Bone::init_club 009ff0c0"); } Weapon_Deathmatch::~Weapon_Deathmatch() { generated_stub("Weapon_Deathmatch::~Weapon_Deathmatch 009f3260"); } void Weapon_Deathmatch::Init(uint32_t param_2, uint32_t param_3) { generated_stub("Weapon_Deathmatch::Init 009f34d0"); } void Weapon_Deathmatch::Update(char param_2) { generated_stub("Weapon_Deathmatch::Update 009f34f0"); } @@ -10111,20 +10067,11 @@ int FUN_00456880() { generated_stub("FUN_00456880 00456880"); } void NpcAI::ENTITY_FLY_isaac_spawned(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_FLY_isaac_spawned 004568d0"); } void NpcAI::ENTITY_WAR(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_WAR 00458870"); } void NpcAI::ENTITY_DEATH(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_DEATH 00459d20"); } -void NpcAI::ENTITY_FALLEN(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_FALLEN 0045b830"); } void NpcAI::ENTITY_HEADLESS_HORSEMAN(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_HEADLESS_HORSEMAN 0045cd60"); } void NpcAI::ENTITY_DARK_ONE(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_DARK_ONE 0045d7d0"); } float NpcAI::ENTITY_ISAAC(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_ISAAC 00463100"); } -void NpcAI::ENTITY_DADDYLONGLEGS(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_DADDYLONGLEGS 00468180"); } -void NpcAI::ENTITY_SLOTH(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_SLOTH 004741f0"); } -void NpcAI::ENTITY_LUST(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_LUST 00474e00"); } -void NpcAI::ENTITY_WRATH(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_WRATH 00475110"); } -void NpcAI::ENTITY_GREED(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_GREED 00475a30"); } -void NpcAI::ENTITY_ENVY(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_ENVY 004760a0"); } void NpcAI::ENTITY_PIN(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_PIN 00476860"); } void FUN_00479d50(uint32_t *param_1) { generated_stub("FUN_00479d50 00479d50"); } -void NpcAI::ENTITY_PRIDE(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_PRIDE 00479d80"); } -Entity_NPC * NpcAI::ENTITY_SATAN(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_SATAN 0047f640"); } void NpcAI::ENTITY_THE_LAMB(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_THE_LAMB 00483710"); } void NpcAI::ENTITY_BROWNIE(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_BROWNIE 0048c3b0"); } void NpcAI::ENTITY_CORN_MINE(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_CORN_MINE 0048ee30"); } @@ -10265,19 +10212,12 @@ uint8_t str_ne(std_string *a, uint8_t *b) { generated_stub("str_ne 004f84a0"); } void rng_pair_init(void *self) { generated_stub("rng_pair_init 004f88a0"); } uint32_t FUN_004f88e0() { generated_stub("FUN_004f88e0 004f88e0"); } uint32_t FUN_004f8930() { generated_stub("FUN_004f8930 004f8930"); } -void NpcAI::ENTITY_QUAKE_GRIMACE(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_QUAKE_GRIMACE 004f8960"); } -void FUN_004f8cc0(int param_1) { generated_stub("FUN_004f8cc0 004f8cc0"); } -void NpcAI::ENTITY_BOMB_GRIMACE(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_BOMB_GRIMACE 004f8df0"); } void NpcAI::ENTITY_ROCK_SPIDER(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_ROCK_SPIDER 004f9ad0"); } void NpcAI::ENTITY_FACELESS(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_FACELESS 004faad0"); } void NpcAI::ENTITY_DANNY(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_DANNY 004fbd10"); } -void NpcAI::ENTITY_BLASTER(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_BLASTER 004fcc20"); } -void quakey_timer_callback(Entity *source) { generated_stub("quakey_timer_callback 004fd280"); } -void NpcAI::ENTITY_QUAKEY(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_QUAKEY 004fd540"); } void NpcAI::ENTITY_MOLE(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_MOLE 004fdf80"); } void NpcAI::ENTITY_GYRO(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_GYRO 004ff620"); } void NpcAI::ENTITY_FIRE_WORM(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_FIRE_WORM 00500990"); } -void NpcAI::ENTITY_HARDY(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_HARDY 00500f70"); } void NpcAI::ENTITY_BOUNCER(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_BOUNCER 00501f30"); } void NpcAI::ENTITY_FLESH_MAIDEN(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_FLESH_MAIDEN 00502980"); } void NpcAI::ENTITY_BOMBGAGGER(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_BOMBGAGGER 00503300"); } @@ -10298,12 +10238,8 @@ void NpcAI::ENTITY_HANGER(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_HANGE void NpcAI::ENTITY_URIEL(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_URIEL 0051e0f0"); } void NpcAI::ENTITY_HEART(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_HEART 0051f2f0"); } void NpcAI::ENTITY_POKY(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_POKY 00521ab0"); } -void NpcAI::ENTITY_EYE(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_EYE 00522ef0"); } -void NpcAI::ENTITY_FRED(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_FRED 00524a10"); } void NpcAI::ENTITY_DOPLE(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_DOPLE 00525650"); } void NpcAI::ENTITY_BABY(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_BABY 0052ae30"); } -void NpcAI::ENTITY_VIS_chubber_projectile(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_VIS_chubber_projectile 0052c2f0"); } -void NpcAI::ENTITY_VIS(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_VIS 0052c720"); } void NpcAI::ENTITY_COD_WORM(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_COD_WORM 00531350"); } void NpcAI::ENTITY_MOBILE_HOST(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_MOBILE_HOST 005321d0"); } void NpcAI::ENTITY_MOMS_HAND(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_MOMS_HAND 00533b80"); } @@ -10311,8 +10247,6 @@ void NpcAI::ENTITY_WIZOOB(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_WIZOO void NpcAI::ENTITY_HOMUNCULUS(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_HOMUNCULUS 00539b90"); } void NpcAI::ENTITY_OOB(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_OOB 0053ab40"); } void NpcAI::ENTITY_BLACK_MAW(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_BLACK_MAW 0053b2f0"); } -void NpcAI::ENTITY_WALL_CREEP(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_WALL_CREEP 0053c0d0"); } -Entity_Effect * NpcAI::ENTITY_MEATBALL(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_MEATBALL 00541ce0"); } float NpcAI::ENTITY_TARBOY(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_TARBOY 005442a0"); } void NpcAI::ENTITY_FISTULOID(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_FISTULOID 00545f70"); } void npc_distribute_orbit_angles(Entity_NPC *npc) { generated_stub("npc_distribute_orbit_angles 00547040"); } @@ -10562,9 +10496,7 @@ void FUN_005cd840(uint32_t param_1) { generated_stub("FUN_005cd840 005cd840"); } void FUN_005cd850() { generated_stub("FUN_005cd850 005cd850"); } void FUN_005cd8c0(uint8_t param_1) { generated_stub("FUN_005cd8c0 005cd8c0"); } void FUN_005cda90() { generated_stub("FUN_005cda90 005cda90"); } -void FUN_005d2270() { generated_stub("FUN_005d2270 005d2270"); } void FUN_005d2300() { generated_stub("FUN_005d2300 005d2300"); } -void FUN_005d2370(uint8_t param_1) { generated_stub("FUN_005d2370 005d2370"); } void FUN_005d23a0(uint8_t param_1) { generated_stub("FUN_005d23a0 005d23a0"); } void FUN_005d4210() { generated_stub("FUN_005d4210 005d4210"); } void FUN_00607540() { generated_stub("FUN_00607540 00607540"); } @@ -10737,7 +10669,6 @@ void FUN_00676bd0() { generated_stub("FUN_00676bd0 00676bd0"); } int FUN_0067adc0() { generated_stub("FUN_0067adc0 0067adc0"); } void FUN_0067ae30(int *param_1) { generated_stub("FUN_0067ae30 0067ae30"); } void FUN_0067af30() { generated_stub("FUN_0067af30 0067af30"); } -void tear_flags_area_apply(Vector *position, Entity *source, float radius, float damage, BitSet128 flags) { generated_stub("tear_flags_area_apply 0067d430"); } uint32_t FUN_0067d9b0() { generated_stub("FUN_0067d9b0 0067d9b0"); } void FUN_0067dac0(int *param_1) { generated_stub("FUN_0067dac0 0067dac0"); } uint32_t * FUN_0067ef50(uint32_t *param_1, uint32_t *param_2, uint32_t *param_3) { generated_stub("FUN_0067ef50 0067ef50"); } @@ -10937,7 +10868,6 @@ void FUN_006e2ff0(int param_1) { generated_stub("FUN_006e2ff0 006e2ff0"); } void FUN_006ee330() { generated_stub("FUN_006ee330 006ee330"); } Vector * Isaac::GetRandomPickupVelocity(Vector *outVelocity, Vector *position, uint32_t pickupVelType, RNG *rng) { generated_stub("Isaac::GetRandomPickupVelocity 006ee440"); } int FUN_006ee640(int param_1, int param_2, uint32_t *param_3, uint32_t param_4) { generated_stub("FUN_006ee640 006ee640"); } -Vector * Isaac::GetCollectibleSpawnPosition(Vector *outPosition, Vector *target) { generated_stub("Isaac::GetCollectibleSpawnPosition 006eeaa0"); } uint32_t FUN_006eeeb0() { generated_stub("FUN_006eeeb0 006eeeb0"); } uint32_t get_mt_state_checksum() { generated_stub("get_mt_state_checksum 006ef1f0"); } int FUN_006ef3f0() { generated_stub("FUN_006ef3f0 006ef3f0"); } @@ -11017,12 +10947,10 @@ Entity_Player * FUN_007103c0(uint32_t *param_1) { generated_stub("FUN_007103c0 0 uint32_t FUN_00710f70(int param_1) { generated_stub("FUN_00710f70 00710f70"); } void FUN_00711530(int param_1) { generated_stub("FUN_00711530 00711530"); } uint32_t FUN_00711740() { generated_stub("FUN_00711740 00711740"); } -void FUN_007135d0(uint32_t param_1, uint8_t param_2, int *param_3) { generated_stub("FUN_007135d0 007135d0"); } void FUN_00718ed0(uint32_t param_1) { generated_stub("FUN_00718ed0 00718ed0"); } uint32_t FUN_00718ee0() { generated_stub("FUN_00718ee0 00718ee0"); } void FUN_0071df70(uint8_t param_1) { generated_stub("FUN_0071df70 0071df70"); } void FUN_00721e60(int param_1, int param_2, int param_3, int param_4, int param_5, int param_6) { generated_stub("FUN_00721e60 00721e60"); } -void FUN_00721eb0() { generated_stub("FUN_00721eb0 00721eb0"); } void FUN_00722020(int param_1) { generated_stub("FUN_00722020 00722020"); } void FUN_007221a0(uint32_t *param_1) { generated_stub("FUN_007221a0 007221a0"); } uint32_t * FUN_00722250(uint32_t *param_1, uint32_t *param_2, uint32_t *param_3) { generated_stub("FUN_00722250 00722250"); } @@ -11181,7 +11109,6 @@ uint8_t teleport_to_random_room_of_types(Entity_Player *player, void *roomTypes, void FUN_007cf940() { generated_stub("FUN_007cf940 007cf940"); } long double FUN_007cf9a0(float *param_1, KColor *param_2, uint32_t param_3) { generated_stub("FUN_007cf9a0 007cf9a0"); } uint8_t * FUN_007cfa90() { generated_stub("FUN_007cfa90 007cfa90"); } -bool FUN_007d1810() { generated_stub("FUN_007d1810 007d1810"); } void FUN_007d3330(int param_1) { generated_stub("FUN_007d3330 007d3330"); } Game * damage_charge_scale() { generated_stub("damage_charge_scale 007d3560"); } void FUN_007d3e00() { generated_stub("FUN_007d3e00 007d3e00"); } @@ -11293,7 +11220,6 @@ void FUN_007e9170(char param_1) { generated_stub("FUN_007e9170 007e9170"); } void FUN_007e92e0(uint32_t param_1, uint32_t param_2) { generated_stub("FUN_007e92e0 007e92e0"); } void FUN_007e93d0(int param_1) { generated_stub("FUN_007e93d0 007e93d0"); } void FUN_007ea0c0() { generated_stub("FUN_007ea0c0 007ea0c0"); } -void FUN_007ebc40() { generated_stub("FUN_007ebc40 007ebc40"); } void FUN_00812ea0(float *param_1, int *param_2, int *param_3) { generated_stub("FUN_00812ea0 00812ea0"); } uint32_t FUN_00813420(int param_1, int param_2) { generated_stub("FUN_00813420 00813420"); } uint32_t FUN_0081e220() { generated_stub("FUN_0081e220 0081e220"); } @@ -11379,7 +11305,6 @@ void ItemInfo::render_popup_callback(int param_1, uint32_t param_2) { generated_ void ItemInfo::render_line(uint8_t *param_1, Vector *param_2, int param_3) { generated_stub("ItemInfo::render_line 008404a0"); } char * FUN_00840510() { generated_stub("FUN_00840510 00840510"); } std_string * int_to_string(std_string *outString, int value) { generated_stub("int_to_string 00840540"); } -void collectible_icon_render(void *param_1, ColorMod *param_2, int *param_3, int *param_4) { generated_stub("collectible_icon_render 00848c20"); } void FUN_0084a870(float *param_1) { generated_stub("FUN_0084a870 0084a870"); } void FUN_0084abc0(uint32_t *param_1, float *param_2, uint32_t *param_3, uint32_t *param_4) { generated_stub("FUN_0084abc0 0084abc0"); } void FUN_0084bba0() { generated_stub("FUN_0084bba0 0084bba0"); } @@ -13564,23 +13489,16 @@ void Catch_All_0095c01b() { generated_stub("Catch_All_0095c01b 0095c01b"); } void * FUN_0095c430(void *param_1, void *param_2, void *param_3) { generated_stub("FUN_0095c430 0095c430"); } void Catch_All_0095c63e() { generated_stub("Catch_All_0095c63e 0095c63e"); } void FUN_0095c670() { generated_stub("FUN_0095c670 0095c670"); } -int FUN_0095c930() { generated_stub("FUN_0095c930 0095c930"); } -uint32_t FUN_0095c960() { generated_stub("FUN_0095c960 0095c960"); } void FUN_0095eb00(uint32_t param_1, int param_2) { generated_stub("FUN_0095eb00 0095eb00"); } void cutscene_render_skip_vote_count(void *cutscene, void *state) { generated_stub("cutscene_render_skip_vote_count 0095eb60"); } -void FUN_0095fbd0() { generated_stub("FUN_0095fbd0 0095fbd0"); } -void FUN_0095fcd0(uint32_t *param_1) { generated_stub("FUN_0095fcd0 0095fcd0"); } -uint32_t FUN_0095fd40() { generated_stub("FUN_0095fd40 0095fd40"); } uint32_t * FUN_00960880(void *param_1, uint32_t *param_2) { generated_stub("FUN_00960880 00960880"); } void FUN_00960bc0() { generated_stub("FUN_00960bc0 00960bc0"); } -uint32_t FUN_00961ad0() { generated_stub("FUN_00961ad0 00961ad0"); } void FUN_0096d120(int *param_1) { generated_stub("FUN_0096d120 0096d120"); } uint32_t FUN_0097e7c0() { generated_stub("FUN_0097e7c0 0097e7c0"); } void pressure_plate_kill_enemies_timer_callback(int *param_1) { generated_stub("pressure_plate_kill_enemies_timer_callback 00983f30"); } void FUN_0098b0a0() { generated_stub("FUN_0098b0a0 0098b0a0"); } void FUN_0098b130() { generated_stub("FUN_0098b130 0098b130"); } void FUN_00993740() { generated_stub("FUN_00993740 00993740"); } -uint32_t * FUN_00995f40(uint32_t *param_1) { generated_stub("FUN_00995f40 00995f40"); } void FUN_00997660(void *param_1, int param_2) { generated_stub("FUN_00997660 00997660"); } void FUN_009976c0(void *param_1, int param_2) { generated_stub("FUN_009976c0 009976c0"); } void Catch_All_009979a9() { generated_stub("Catch_All_009979a9 009979a9"); } @@ -13591,7 +13509,6 @@ uint32_t * FUN_009983f0(uint32_t *param_1) { generated_stub("FUN_009983f0 009983 void netplay_player_list_destructor(void *self) { generated_stub("netplay_player_list_destructor 00998800"); } void FUN_0099a830() { generated_stub("FUN_0099a830 0099a830"); } void FUN_0099c310() { generated_stub("FUN_0099c310 0099c310"); } -float bezier_closest_point(Vector *point, void *segmentStart, void *segmentEnd, float *outT) { generated_stub("bezier_closest_point 0099c430"); } void ** vector_LaserSample_erase(void *self, void **outIter, void *where) { generated_stub("vector_LaserSample_erase 009a1610"); } void FUN_009a1770(uint32_t *param_1) { generated_stub("FUN_009a1770 009a1770"); } void * vector_LaserSample_emplace_reallocate(void *self, void *where, void *value) { generated_stub("vector_LaserSample_emplace_reallocate 009a17b0"); } @@ -13785,8 +13702,6 @@ uint32_t * FUN_009f9350() { generated_stub("FUN_009f9350 009f9350"); } uint32_t * FUN_009f93d0() { generated_stub("FUN_009f93d0 009f93d0"); } uint32_t * FUN_009f9440() { generated_stub("FUN_009f9440 009f9440"); } uint32_t * FUN_009f95d0() { generated_stub("FUN_009f95d0 009f95d0"); } -uint32_t * FUN_009f96c0() { generated_stub("FUN_009f96c0 009f96c0"); } -uint32_t * FUN_009f9740() { generated_stub("FUN_009f9740 009f9740"); } uint32_t * FUN_00a06940(void *param_1, uint32_t *param_2) { generated_stub("FUN_00a06940 00a06940"); } void * operator_new(uint32_t size) { generated_stub("operator_new 00a0f4c0"); } void * operator_new_tracked(uint32_t size) { generated_stub("operator_new_tracked 00a0f4e0"); } diff --git a/generated-src/video_player.cpp b/generated-src/video_player.cpp deleted file mode 100644 index 37cffe5..0000000 --- a/generated-src/video_player.cpp +++ /dev/null @@ -1,310 +0,0 @@ -#include "classes.h" - -// 009f2ee0 -void VideoPlayer::play(uint8_t *fileName, float volume) -{ - uint32_t *extraout_EAX; - uint32_t *pathText; - void *allocBlock; - int startFrame; - uint8_t *copyPtr; - uint32_t allocSize; - void *redirectedPath [4]; - uint32_t redirectedPathSize; - uint32_t redirectedPathCapacity; - void *local_ac [4]; - uint32_t pathSize; - uint32_t pathCapacity; - uint8_t fileNameLocal [128]; - uint32_t local_14; - void *local_10; - uint8_t *puStack_c; - uint32_t local_8; - uint8_t copyChar; - int decoder; - Manager *manager; - - local_8 = 0xffffffff; - puStack_c = &LAB_00b101ab; - local_10 = ExceptionList; - local_14 = __security_cookie ^ GHIDRA_UINT((fileNameLocal + 0x90)); - ExceptionList = &local_10; - copyPtr = fileName; - do { - copyChar = *copyPtr; - copyPtr = copyPtr + 1; - copyPtr[GHIDRA_INT(local_ac) + (0x17 - GHIDRA_INT(fileName))] = copyChar; - } while (copyChar != 0); - strstr(GHIDRA_CAST(fileNameLocal),".ogv"); - manager = g_manager; - copyPtr = fileNameLocal; - pathSize = 0; - pathCapacity = 0xf; - local_ac[0] = (void *)0x0; - do { - copyChar = *copyPtr; - copyPtr = copyPtr + 1; - } while (copyChar != 0); - (GHIDRA_CAST((GHIDRA_CAST(local_ac))))->msvc::string::assign(fileNameLocal,GHIDRA_INT(copyPtr) - GHIDRA_INT((fileNameLocal + 1))); - local_8 = 0; - ModManager::TryRedirectPath - (GHIDRA_CAST(&manager->_modManager),GHIDRA_CAST(redirectedPath),GHIDRA_CAST(local_ac) - ); - (*GHIDRA_CAST((GHIDRA_CAST(&(local_8)) + 0x0))) = 1; - pathText = extraout_EAX; - if (0xf < GHIDRA_UINT(extraout_EAX[5])) { - pathText = GHIDRA_CAST(*extraout_EAX); - } - FUN_00a62910(pathText); - local_8 = (*GHIDRA_CAST((GHIDRA_CAST(&(GHIDRA_UINT(local_8))) + 0x1))) << 8; - if (0xf < redirectedPathCapacity) { - allocSize = redirectedPathCapacity + 1; - allocBlock = redirectedPath[0]; - if (0xfff < allocSize) { - allocBlock = *(void **)(GHIDRA_INT(redirectedPath[0]) + -4); - allocSize = redirectedPathCapacity + 0x24; - if (0x1f < GHIDRA_UINT((GHIDRA_INT(redirectedPath[0]) + (-4 - GHIDRA_INT(allocBlock))))) goto LAB_009f3050; - } - operator_delete(allocBlock,allocSize); - } - local_8 = -1; - redirectedPathSize = 0; - redirectedPathCapacity = 0xf; - redirectedPath[0] = (void *)(GHIDRA_UINT(redirectedPath[0]) & 0xffffff00); - if (0xf < pathCapacity) { - allocSize = pathCapacity + 1; - allocBlock = local_ac[0]; - if (0xfff < allocSize) { - allocBlock = *(void **)(GHIDRA_INT(local_ac[0]) + -4); - allocSize = pathCapacity + 0x24; - if (0x1f < GHIDRA_UINT((GHIDRA_INT(local_ac[0]) + (-4 - GHIDRA_INT(allocBlock))))) { -LAB_009f3050: - /* WARNING: Subroutine does not return */ - _invalid_parameter_noinfo_noreturn(); - } - } - operator_delete(allocBlock,allocSize); - } - decoder = *GHIDRA_CAST((GHIDRA_CAST(this) + 4)); - if (decoder != 0) { - if (volume < 1.0) { - if (0.0 < volume) { - *GHIDRA_CAST((decoder + 0x48)) = volume; - } - else { - *GHIDRA_CAST((decoder + 0x48)) = 0; - } - } - else { - *GHIDRA_CAST((decoder + 0x48)) = 0x3f800000; - } - } - decoder = *GHIDRA_CAST((GHIDRA_CAST(this) + 4)); - if (decoder != 0) { - (**(code **)(**GHIDRA_CAST((decoder + 0x28)) + 0x1c))(); - FUN_00aaaa90(); - *GHIDRA_CAST((decoder + 0x98)) = 0; - *GHIDRA_CAST((decoder + 0x94)) = 0; - startFrame = GHIDRA_INT((*GHIDRA_CAST((decoder + 0x70)) * 0.0)); - if (startFrame < 0) { - startFrame = 0; - } - else if (*GHIDRA_CAST((decoder + 0x6c)) < startFrame) { - startFrame = *GHIDRA_CAST((decoder + 0x6c)); - } - *GHIDRA_CAST((decoder + 0x88)) = startFrame; - *GHIDRA_CAST((decoder + 0x90)) = 0; - *GHIDRA_CAST((decoder + 0x74)) = 0; - *GHIDRA_CAST((GHIDRA_CAST(this) + 0x10)) = 0; - if (*GHIDRA_CAST((GHIDRA_CAST(this) + 4)) != 0) { - (**(code **)(**GHIDRA_CAST((*GHIDRA_CAST((GHIDRA_CAST(this) + 4)) + 0x28)) + 0x18))(); - *GHIDRA_CAST((GHIDRA_CAST(this) + 0x10)) = 1; - } - } - ExceptionList = local_10; - return; -} - -// 00a62880 -void VideoPlayer::unload() -{ - char isLastRef; - uint32_t uVar1; - uint32_t extraout_ECX; - void *local_10; - uint8_t *puStack_c; - uint32_t local_8; - - local_8 = 0xffffffff; - puStack_c = &LAB_00af12a0; - local_10 = ExceptionList; - uVar1 = __security_cookie ^ GHIDRA_INT(register0x00000010) - 4U; - ExceptionList = &local_10; - TheoraVideoManager::destroyVideoClip(*(void **)(GHIDRA_CAST(this) + 4)); - *GHIDRA_CAST((GHIDRA_CAST(this) + 4)) = 0; - *GHIDRA_CAST(this) = 0; - *GHIDRA_CAST((GHIDRA_CAST(this) + 0x10)) = 0; - KAGE::SmartPointer::reset(extraout_ECX); - local_8 = 0; - if (*GHIDRA_CAST((GHIDRA_CAST(this) + 0xc)) != GHIDRA_CAST(0x0)) { - isLastRef = (**(code **)(**GHIDRA_CAST((GHIDRA_CAST(this) + 0xc)) + 0xc))(uVar1); - if ((isLastRef != '\0') && (g_renderTargetReleaseFn != (void *)0x0)) { - (*g_renderTargetReleaseFn)(GHIDRA_INT(this) + 8); - } - } - ExceptionList = local_10; - return; -} - -// 00a62b10 -void VideoPlayer::render(uint8_t param_1) -{ - uint8_t *puVar1; - void *pvVar2; - int iVar3; - uint32_t uVar4; - int *frameNode; - int in_ECX; - int *countNode; - uint32_t extraout_ECX; - uint8_t *puVar5; - int iVar6; - int iVar7; - uint32_t texHeight; - long double clockTime; - KColor white; - void *scopeLock; - uint8_t local_24; - float local_20; - uint8_t *local_1c; - int *frameListHead; - int self; - void *local_10; - uint8_t *puStack_c; - uint32_t local_8; - code *drawFn; - int *nextNode; - - local_8 = 0xffffffff; - puStack_c = &LAB_00b1317d; - local_10 = ExceptionList; - uVar4 = __security_cookie ^ GHIDRA_INT(register0x00000010) - 4U; - puVar1 = *GHIDRA_CAST((in_ECX + 4)); - if (puVar1 == GHIDRA_CAST(0x0)) { - return; - } - self = in_ECX; - ExceptionList = &local_10; - local_1c = puVar1; - if (*GHIDRA_CAST((puVar1 + 0x88)) != -1) goto LAB_00a62d83; - pvVar2 = *(void **)(*GHIDRA_CAST((puVar1 + 0x1c)) + 0xc); - scopeLock = (void *)0x0; - local_24 = 0; - if (pvVar2 != (void *)0x0) { - scopeLock = pvVar2; - (GHIDRA_CAST((pvVar2)))->Mutex::lock(); - } - local_8 = 0; - clockTime = (long double)(**(code **)(**GHIDRA_CAST((puVar1 + 0x28)) + 4))(uVar4); - iVar6 = 0; - frameListHead = GHIDRA_CAST(**GHIDRA_CAST((puVar1 + 0x1c))); - frameNode = GHIDRA_CAST(*frameListHead); - local_20 = (float)*GHIDRA_CAST((puVar1 + 0x98)) * *GHIDRA_CAST((puVar1 + 0x58)) + (float)clockTime; - countNode = frameNode; - puVar5 = puVar1; - iVar7 = iVar6; - if (frameNode == frameListHead) { -LAB_00a62be2: - iVar6 = 0; - if (frameNode != frameListHead) { - while ((iVar3 = frameNode[2], *GHIDRA_CAST((iVar3 + 8)) != '\0' && - ((float)*GHIDRA_CAST((iVar3 + 0xc)) * *GHIDRA_CAST((puVar1 + 0x58)) + *GHIDRA_CAST((iVar3 + 4)) + - *GHIDRA_CAST((puVar5 + 0x5c)) < local_20))) { - iVar7 = iVar7 + -1; - iVar6 = iVar6 + 1; - if ((iVar7 == 1) || (frameNode = GHIDRA_CAST(*frameNode), frameNode == frameListHead)) break; - } - if (0 < iVar6) { - *GHIDRA_CAST((puVar5 + 0x9c)) = *GHIDRA_CAST((puVar5 + 0x9c)) + iVar6; - FUN_00aaaae0(iVar6); - } - } - } - else { - do { - nextNode = GHIDRA_CAST(*countNode); - iVar7 = iVar6 + 1; - if (*GHIDRA_CAST((countNode[2] + 8)) == '\0') { - iVar7 = iVar6; - } - countNode = nextNode; - iVar6 = iVar7; - } while (nextNode != frameListHead); - puVar5 = local_1c; - if (iVar7 != 1) goto LAB_00a62be2; - } - iVar7 = 0; - if (*GHIDRA_CAST((*GHIDRA_CAST((*GHIDRA_CAST(**GHIDRA_CAST((puVar5 + 0x1c))) + 8)) + 8)) != '\0') { - iVar7 = *GHIDRA_CAST((*GHIDRA_CAST(**GHIDRA_CAST((puVar5 + 0x1c))) + 8)); - } - if (((iVar7 != 0) && - (local_20 < (float)*GHIDRA_CAST((iVar7 + 0xc)) * *GHIDRA_CAST((puVar5 + 0x58)) + *GHIDRA_CAST((iVar7 + 4)))) - && (puVar5[0x90] != '\0')) { - iVar7 = 0; - } - local_8 = 0xffffffff; - (GHIDRA_CAST((&scopeLock)))->Mutex::ScopeLock::~ScopeLock(); - if (iVar7 == 0) { - } - else { - (*(code *)epoxy_glEnable)(0xde1); - (*(code *)epoxy_glBindTexture)(0xde1,*GHIDRA_CAST((*GHIDRA_CAST((self + 8)) + 0x58))); - local_1c = epoxy_glTexSubImage2D; - local_20 = *GHIDRA_CAST((iVar7 + 0x18)); - iVar7 = *GHIDRA_CAST((self + 4)); - if (iVar7 == 0) { - texHeight = 0; - iVar6 = 0; - } - else { - texHeight = *GHIDRA_CAST((iVar7 + 100)); - iVar6 = *GHIDRA_CAST((iVar7 + 0x60)) / 2; - if (*GHIDRA_CAST((iVar7 + 0x40)) == '\0') { - iVar6 = *GHIDRA_CAST((iVar7 + 0x60)); - } - } - (*(code *)epoxy_glTexSubImage2D)(0xde1,0,0,0,iVar6,texHeight,0x1907,0x1401,local_20); - iVar7 = *GHIDRA_CAST((self + 4)); - *GHIDRA_CAST((iVar7 + 0xa0)) = *GHIDRA_CAST((iVar7 + 0xa0)) + 1; - pvVar2 = *(void **)(*GHIDRA_CAST((iVar7 + 0x1c)) + 0xc); - scopeLock = (void *)0x0; - local_24 = 0; - if (*GHIDRA_CAST((iVar7 + 0x90)) == '\0') { - if (pvVar2 != (void *)0x0) { - scopeLock = pvVar2; - (GHIDRA_CAST((pvVar2)))->Mutex::lock(); - } - local_8 = 1; - FUN_00aaaae0(1); - *GHIDRA_CAST((iVar7 + 0x90)) = 1; - local_8 = 0xffffffff; - (GHIDRA_CAST((&scopeLock)))->Mutex::ScopeLock::~ScopeLock(); - } - else { - if (pvVar2 != (void *)0x0) { - scopeLock = pvVar2; - (GHIDRA_CAST((pvVar2)))->Mutex::lock(); - } - local_8 = 2; - FUN_00aaaae0(1); - local_8 = 0xffffffff; - (GHIDRA_CAST((&scopeLock)))->Mutex::ScopeLock::~ScopeLock(); - } - } -LAB_00a62d83: - drawFn = *(code **)(**GHIDRA_CAST((self + 8)) + 0x20); - (GHIDRA_CAST((&white)))->KColor::SetFromARGB(0xffffffff); - (*drawFn)(¶m_1,extraout_ECX); - ExceptionList = local_10; - return; -} diff --git a/generated-src/weapon_bombs.cpp b/generated-src/weapon_bombs.cpp deleted file mode 100644 index 759af20..0000000 --- a/generated-src/weapon_bombs.cpp +++ /dev/null @@ -1,199 +0,0 @@ -#include "classes.h" - -// 009f9b60 -void Weapon_Bombs::Fire(Vector *param_1, uint8_t param_2, uint8_t param_3) -{ - Vector shotDirection; - uint8_t isAxisAligned; - Vector *vecResult; - uint32_t rngResult; - Entity_Bomb *firedBomb; - Weapon *in_ECX; - int unusedArg; - Entity_Bomb *oldLink; - uint32_t randomShotsLeft; - int bomb; - Entity_Bomb *linkSlot; - float fVar1; - float fVar2; - float fVar3; - float shotSpeed; - Vector local_80; - Vector local_78; - uint32_t isLudovico; - Weapon *weapon; - Vector aimDirection; - Vector spawnPos; - Vector scratchVec; - Vector multiShotOffset; - Vector multiShotVelocity; - uint32_t multiShotParams; - float fStack_3c; - float fStack_38; - float fStack_34; - float local_30; - int iStack_2c; - float fStack_28; - uint32_t uStack_24; - uint32_t local_20; - - weapon = in_ECX; - Weapon::Fire(in_ECX,param_1,param_2,param_3); - bomb = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((in_ECX)) + 0x4)))); - isLudovico = GHIDRA_UINT(in_ECX->_modifiers) >> 4 & 0xffffff01; - if (bomb == 0) { - spawnPos.x = g_vectorZero.x; - spawnPos.y = g_vectorZero.y; - } - else { - spawnPos.x = *GHIDRA_CAST((bomb + 0x33c)); - spawnPos.y = *GHIDRA_CAST((bomb + 0x340)); - if ((*GHIDRA_CAST((bomb + 0x28)) == 1) || - ((*GHIDRA_CAST((bomb + 0x28)) == 3 && (bomb = *GHIDRA_CAST((bomb + 0x410)), bomb != 0)))) { - shotSpeed = *GHIDRA_CAST((bomb + 0x1464)); - goto LAB_009f9c09; - } - } - shotSpeed = 1.0; -LAB_009f9c09: - if ((param_2 == 0) || (0.0 < *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((in_ECX)) + 0xc)))) || *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((in_ECX)) + 0xc)))) == 0.0)) - { - if ((char)isLudovico == '\0') { - return; - } - } - else if (((char)isLudovico == '\0') || (*GHIDRA_CAST((in_ECX + 1)) == 0)) { - if (param_3 != 0) { - return; - } - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((in_ECX)) + 0xc)))) = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((in_ECX)) + 0x10)))); - Weapon::SetBlinkTime(in_ECX,7 - GHIDRA_INT((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((in_ECX)) + 0x10)))) * -0.45)),bomb); - aimDirection.x = param_1->x; - aimDirection.y = param_1->y; - isAxisAligned = Weapon::IsAxisAligned(in_ECX); - if (isAxisAligned == 0) { - fVar2 = sqrtf(aimDirection.x * aimDirection.x + aimDirection.y * aimDirection.y); - if (0.0 < fVar2) { - aimDirection.x = aimDirection.x * (1.0 / fVar2); - aimDirection.y = aimDirection.y * (1.0 / fVar2); - } - } - else { - vecResult = Vector::ToCardinal(&scratchVec,&aimDirection); - aimDirection.x = vecResult->x; - aimDirection.y = vecResult->y; - } - Weapon::TriggerTearEffects(in_ECX,&aimDirection,1); - fVar2 = aimDirection.x * 12.0; - fVar3 = aimDirection.y * 12.0; - vecResult = Weapon::get_tear_movement_inheritance(in_ECX,&scratchVec,&g_vectorZero); - fVar2 = fVar2 + vecResult->x; - fVar3 = fVar3 + vecResult->y; - Weapon::GetMultiShotParams(in_ECX,&multiShotParams,unusedArg); - local_78.x = -fVar3; - if ((*GHIDRA_CAST((GHIDRA_CAST(&(uStack_24)) + 0x1))) != '\0') { - local_80.x = -fVar2 * shotSpeed; - local_80.y = local_78.x * shotSpeed; - Weapon::fire_bomb(in_ECX,&spawnPos,&local_80); - } - if ((*GHIDRA_CAST((GHIDRA_CAST(&(uStack_24)) + 0x2))) != '\0') { - local_78.x = local_78.x * shotSpeed; - local_78.y = fVar2 * shotSpeed; - Weapon::fire_bomb(in_ECX,&spawnPos,&local_78); - local_78.x = fVar3 * shotSpeed; - local_78.y = -fVar2 * shotSpeed; - Weapon::fire_bomb(in_ECX,&spawnPos,&local_78); - } - for (randomShotsLeft = local_20 & 0xffff; randomShotsLeft != 0; - randomShotsLeft = randomShotsLeft - 1) { - rngResult = Random(); - local_78.x = (float)((double)GHIDRA_INT(rngResult) + - __uint_to_double_fixup[-(GHIDRA_INT(rngResult) >> 0x1f)]) * 2.3283064e-10 * 360.0 - * 0.017453292; - local_80.x = cos(local_78.x); - fVar1 = sin(local_78.x); - scratchVec.x = (local_80.x * fVar2 - fVar1 * fVar3) * shotSpeed; - scratchVec.y = (fVar1 * fVar2 + local_80.x * fVar3) * shotSpeed; - Weapon::fire_bomb(in_ECX,&spawnPos,&scratchVec); - } - local_80.x = 0.0; - local_78.x = 0.0; - if ((short)multiShotParams < 1) { - return; - } - do { - shotDirection.y = fVar3; - shotDirection.x = fVar2; - Entity_Player::GetMultiShotPositionVelocity - (&multiShotOffset,GHIDRA_INT(local_78.x),5,shotDirection,shotSpeed,(short)multiShotParams, - fStack_3c,fStack_38,fStack_34,local_30,iStack_2c,fStack_28,(uint8_t)uStack_24, - (short)local_20); - scratchVec.x = spawnPos.x + multiShotOffset.x; - scratchVec.y = spawnPos.y + multiShotOffset.y; - firedBomb = Weapon::fire_bomb(in_ECX,&scratchVec,&multiShotVelocity); - if ((char)isLudovico != '\0') { - if (GHIDRA_CAST(local_80.x) == GHIDRA_CAST(0x0)) { - oldLink = *GHIDRA_CAST((in_ECX + 1)); - linkSlot = GHIDRA_CAST((in_ECX + 1)); - if (oldLink != firedBomb) goto LAB_009f9fda; - } - else { - oldLink = *GHIDRA_CAST((GHIDRA_CAST(local_80.x) + 0x3c0)); - linkSlot = GHIDRA_CAST((GHIDRA_INT(local_80.x) + 0x3c0)); -LAB_009f9fda: - if (oldLink != GHIDRA_CAST(0x0)) { - local_80.x = (float)linkSlot; - msvc::multiset::erase(&local_80); - } - *GHIDRA_CAST(linkSlot) = firedBomb; - if (firedBomb != GHIDRA_CAST(0x0)) { - msvc::multiset::insert(linkSlot); - } - } - in_ECX = weapon; - local_80.x = (float)firedBomb; - } - local_78.x = (float)(GHIDRA_INT(local_78.x) + 1); - if (GHIDRA_INT((short)multiShotParams) <= GHIDRA_INT(local_78.x)) { - return; - } - } while( true ); - } - bomb = *GHIDRA_CAST((in_ECX + 1)); - if ((bomb != 0) && (param_2 != 0)) { - aimDirection.x = param_1->x; - aimDirection.y = param_1->y; - if (1.0 < aimDirection.x * aimDirection.x + aimDirection.y * aimDirection.y) { - (GHIDRA_CAST((&aimDirection)))->Vector::Normalize(); - } - fVar2 = *GHIDRA_CAST((bomb + 0x36c)); - fVar3 = aimDirection.x * shotSpeed * 1.2 * 0.5; - fVar1 = aimDirection.y * shotSpeed * 1.2 * 0.5; - if (fVar2 != 0.0) { - *GHIDRA_CAST((bomb + 0x360)) = - (fVar3 * *GHIDRA_CAST((bomb + 0x39c))) / fVar2 + *GHIDRA_CAST((bomb + 0x360)); - *GHIDRA_CAST((bomb + 0x364)) = - (fVar1 * *GHIDRA_CAST((bomb + 0x39c))) / fVar2 + *GHIDRA_CAST((bomb + 0x364)); - bomb = *GHIDRA_CAST((in_ECX + 1)); - } - for (bomb = *GHIDRA_CAST((bomb + 0x3c0)); bomb != 0; bomb = *GHIDRA_CAST((bomb + 0x3c0))) { - fVar2 = *GHIDRA_CAST((bomb + 0x36c)); - if (fVar2 != 0.0) { - *GHIDRA_CAST((bomb + 0x360)) = - (*GHIDRA_CAST((bomb + 0x39c)) * fVar3) / fVar2 + *GHIDRA_CAST((bomb + 0x360)); - *GHIDRA_CAST((bomb + 0x364)) = - (fVar1 * *GHIDRA_CAST((bomb + 0x39c))) / fVar2 + *GHIDRA_CAST((bomb + 0x364)); - } - } - } - return; -} - -// 009fa190 -Entity * Weapon_Bombs::GetFocusEntity() -{ - if ((*GHIDRA_CAST((GHIDRA_CAST(this) + 0x34)) >> 4 & 1) == 0) { - return GHIDRA_CAST(0x0); - } - return *GHIDRA_CAST((GHIDRA_CAST(this) + 0x44)); -} diff --git a/generated-src/weapon_bone.cpp b/generated-src/weapon_bone.cpp deleted file mode 100644 index 58f3bf6..0000000 --- a/generated-src/weapon_bone.cpp +++ /dev/null @@ -1,2649 +0,0 @@ -#include "classes.h" - -// 009fa220 -void Weapon_Bone::Update(uint8_t isInterpolated) -{ - void *player = this; - int iVar1; - uint8_t isCheck; - Entity_Player *owner; - float *extraout_EAX; - Entity_Player *player; - Entity_Player *playerOwner; - float fVar2; - float offsetX; - float chargeStep; - float flyingOffsetX; - Vector flyingOffset; - - owner = *GHIDRA_CAST((GHIDRA_CAST(player) + 4)); - playerOwner = owner; - if (owner == GHIDRA_CAST(0x0)) { -LAB_009fa24f: - player = GHIDRA_CAST(0x0); - if ((owner != GHIDRA_CAST(0x0)) && (owner->_type == 1)) goto LAB_009fa25f; - } - else { - if (owner->_type == 1) { - player = owner; - goto LAB_009fa25f; - } - if (owner->_type != 3) goto LAB_009fa24f; - player = *GHIDRA_CAST(&owner->_isControlsEnabled); - } - playerOwner = GHIDRA_CAST(0x0); -LAB_009fa25f: - if (*GHIDRA_CAST((GHIDRA_CAST(player) + 0x30)) == 0xb) { - *GHIDRA_CAST((GHIDRA_CAST(player) + 0x10)) = 0x41700000; - if ((player != GHIDRA_CAST(0x0)) && - (isCheck = Entity_Player::HasCollectible(player,0x3b,0), isCheck != 0)) { - *GHIDRA_CAST((GHIDRA_CAST(player) + 0x10)) = 0x40c00000; - } - owner = *GHIDRA_CAST((GHIDRA_CAST(player) + 4)); - *GHIDRA_CAST((GHIDRA_CAST(player) + 0x34)) = 0x80000000; - } - fVar2 = -10.0; - offsetX = 0.0; - if (owner != GHIDRA_CAST(0x0)) { - if (playerOwner == GHIDRA_CAST(0x0)) { - offsetX = (owner->_sprite)._scale.x * 0.0; - if (owner->_type == 3) { - fVar2 = (owner->_sprite)._scale.y * -20.0; - } - else { - fVar2 = (owner->_sprite)._scale.y * -10.0; - } - } - else { - fVar2 = (playerOwner->_playerSpriteScale).x; - if (fVar2 <= 1.0) { - fVar2 = 1.0; - } - iVar1 = playerOwner->_entityGridCollisionClass; - if ((((iVar1 == 0) || (iVar1 == 3)) || (iVar1 == 1)) || (iVar1 == 2)) { - Entity_Player::GetFlyingOffset(playerOwner,&flyingOffset); - flyingOffsetX = *extraout_EAX / 0.65 + 0.0; - flyingOffset.x = extraout_EAX[1] / 0.65 - 10.0; - } - else { - flyingOffsetX = 0.0; - flyingOffset.x = -10.0; - } - isCheck = TemporaryEffects::HasCollectibleEffect(&playerOwner->_temporaryeffects,0x271); - if (isCheck != 0) { - fVar2 = fVar2 * 4.0; - } - offsetX = flyingOffsetX * fVar2 + (playerOwner->_posOffset).x; - fVar2 = flyingOffset.x * fVar2 + (playerOwner->_posOffset).y; - } - } - chargeStep = 1.0; - iVar1 = *GHIDRA_CAST((GHIDRA_CAST(player) + 0x44)); - if (iVar1 != 0) { - *GHIDRA_CAST((iVar1 + 0x34c)) = offsetX; - *GHIDRA_CAST((iVar1 + 0x350)) = fVar2; - } - iVar1 = *GHIDRA_CAST((GHIDRA_CAST(player) + 0x48)); - if (iVar1 != 0) { - *GHIDRA_CAST((iVar1 + 0x34c)) = offsetX; - *GHIDRA_CAST((iVar1 + 0x350)) = fVar2; - } - iVar1 = *GHIDRA_CAST((GHIDRA_CAST(player) + 0x4c)); - if (iVar1 != 0) { - *GHIDRA_CAST((iVar1 + 0x34c)) = offsetX; - *GHIDRA_CAST((iVar1 + 0x350)) = fVar2; - } - iVar1 = *GHIDRA_CAST((GHIDRA_CAST(player) + 0x50)); - if (iVar1 != 0) { - *GHIDRA_CAST((iVar1 + 0x34c)) = offsetX; - *GHIDRA_CAST((iVar1 + 0x350)) = fVar2; - } - if ((isInterpolated == 0) && (-1.0 < *GHIDRA_CAST((GHIDRA_CAST(player) + 0xc)))) { - if (*GHIDRA_CAST((GHIDRA_CAST(player) + 4)) != 0) { - chargeStep = *GHIDRA_CAST((*GHIDRA_CAST((GHIDRA_CAST(player) + 4)) + 0x39c)); - } - *GHIDRA_CAST((GHIDRA_CAST(player) + 0xc)) = *GHIDRA_CAST((GHIDRA_CAST(player) + 0xc)) - chargeStep; - } - return; -} - -// 009fa450 -void Weapon_Bone::Fire(Vector *direction, uint8_t isShooting, uint8_t isInterpolated) -{ - Entity_Bomb *pEVar1; - code *pcVar2; - Manager *pMVar3; - uint8_t bVar4; - Vector *pVVar5; - uint32_t uVar6; - TearParams *pTVar7; - BitSet128 *pBVar8; - Vector *pVVar9; - Entity_Player **ppEVar10; - int *effectIt; - std_string *anim; - float *clampedValue; - uint32_t rngResult; - Entity_Bomb **ppEVar11; - Entity_Tear *fetusTear; - Entity_Knife *club; - char cVar12; - uint8_t extraout_CL; - uint8_t extraout_CL_00; - Entity_Player *pEVar13; - int unusedCollectibleId; - int extraout_ECX; - int extraout_ECX_00; - undefined3 uVar20; - uint32_t rngResult; - int *piVar15; - int extraout_ECX_01; - uint3 uVar21; - int iVar16; - float *extraout_ECX_02; - float *extraout_ECX_03; - float *extraout_ECX_04; - void *pvVar17; - float *pfVar18; - int unused; - float *extraout_ECX_05; - Entity_Player *pEVar19; - float *extraout_ECX_06; - float *extraout_ECX_07; - float *extraout_ECX_08; - int extraout_ECX_09; - int extraout_ECX_10; - float *extraout_ECX_11; - int unused_00; - float *extraout_ECX_12; - Entity_Knife *extraout_ECX_13; - Entity_Knife *extraout_ECX_14; - Entity_Knife *extraout_ECX_15; - Entity_Knife *unused_01; - float *extraout_ECX_16; - int extraout_ECX_17; - int extraout_ECX_18; - float *extraout_ECX_19; - float *extraout_ECX_20; - float *extraout_ECX_21; - uint8_t *puVar22; - int *extraout_EDX; - Entity_Player *this_00; - void **heldEntitySlot; - float fVar23; - uint8_t auVar24 [16]; - float fVar25; - float fVar26; - Entity_Bomb *pEVar27; - float fVar28; - double dVar29; - undefined3 in_stack_00000009; - undefined3 in_stack_0000000d; - int iVar30; - BitSet128 *b; - Entity *pEVar31; - uint8_t local_2f8 [36]; - uint32_t uStack_2d4; - uint8_t *local_2d0; - float fStack_2cc; - int lanesPerEye; - float fStack_2c4; - float fStack_2c0; - float local_2bc; - void *pvStack_2b8; - float fStack_2b4; - uint8_t *puStack_2b0; - uint8_t local_2ac [8]; - Vector local_2a4; - uint32_t local_29c; - Entity_Bomb *local_298; - Entity_Player *maxCharge; - uint32_t isBrimstone; - Vector *aimDirection; - uint32_t local_288; - Entity_Bomb *local_284; - float damageMultiplier; - uint8_t local_27c [8]; - Vector local_274; - Vector ownerVelocityX; - Vector local_264; - uint32_t isCursedEye; - Vector local_258; - float local_250; - Vector local_24c; - uint32_t isCSection; - Vector ownerPos; - Vector local_238; - Entity_Player *shotSpeed; - int weaponType; - Entity_Player *chargeThreshold; - Entity_Player *maxFireDelay; - Vector local_220; - Vector local_218; - Entity_Player *newCharge; - Entity_Player *clubScale; - uint8_t *local_208; - char isEpicFetus; - char isReleased; - Entity_Player *local_200; - char local_1f9; - Vector shotDirection; - Vector local_1f0; - Entity_Player *ownerPlayer; - Vector local_1e4; - uint8_t isChocolateMilk; - Entity_Bomb *local_1d8; - uint16_t local_1d2; - Entity_Knife *heldClub; - Entity_Player *player; - char isChargeMode; - char isDrFetus; - uint8_t local_1c6; - uint8_t local_1c5; - uint8_t local_1c4 [8]; - int tearBombVariant; - Color tearColor; - BitSet128 tearFlags; - Entity_Player *tearDamage; - float tearScale; - float tearHeight; - uint32_t uStack_16c; - uint32_t local_168; - float local_164; - float local_160; - TearParams local_158; - Color flashColor; - uint8_t local_c4 [24]; - float fStack_ac; - float fStack_a8; - Vector local_a4; - uint8_t *local_9c; - uint8_t chargeColor [40]; - uint8_t *puStack_70; - uint8_t local_6c [28]; - uint8_t local_50 [4]; - void *pvStack_4c; - void *pvStack_48; - uint8_t *puStack_44; - uint8_t clubFlashColor [32]; - Vector VStack_20; - uint8_t *puStack_18; - void *securityCookie; - void *local_10; - uint8_t *puStack_c; - uint32_t local_8; - uint32_t *bombFlagsHigh; - int *effectsEnd; - Entity_Player *owner; - uint64_t savedBombFlags; - - local_8 = -NAN; - puStack_c = &LAB_00b106ce; - local_10 = ExceptionList; - securityCookie = (void *)(__security_cookie ^ GHIDRA_UINT((clubFlashColor + 0x3c))); - ExceptionList = &local_10; - aimDirection = direction; - iVar30 = _isShooting; - owner = _isInterpolated; - ownerVelocityX.y = (float)this; - Weapon::Fire(this,direction,isShooting,isInterpolated); - weaponType = *GHIDRA_CAST((GHIDRA_CAST(this) + 0x30)); - pEVar19 = *GHIDRA_CAST((GHIDRA_CAST(this) + 4)); - pEVar13 = pEVar19; - if (pEVar19 == GHIDRA_CAST(0x0)) { -LAB_009fa53d: - ownerPlayer = GHIDRA_CAST(0x0); - player = pEVar19; - if (pEVar19 == GHIDRA_CAST(0x0)) { -LAB_009fa4db: - } - else { - ownerPlayer = GHIDRA_CAST(0x0); - if (pEVar19->_type == 1) goto LAB_009fa525; - } - this_00 = ownerPlayer; - if (pEVar19 != GHIDRA_CAST(0x0)) { - player = GHIDRA_CAST(0x0); - if (pEVar19->_type == 1) goto LAB_009fa525; - ownerPlayer = this_00; - if (pEVar19->_type == 3) { - player = GHIDRA_CAST(0x0); - pEVar13 = *GHIDRA_CAST(&pEVar19->_isControlsEnabled); - if (*GHIDRA_CAST(&pEVar19->_isControlsEnabled) != GHIDRA_CAST(0x0)) - goto LAB_009fa525; - } - } - shotSpeed = GHIDRA_CAST(0x3f800000); - player = GHIDRA_CAST(0x0); - if (pEVar19 != GHIDRA_CAST(0x0)) goto LAB_009fa572; - ownerPos.x = g_vectorZero.x; - player = GHIDRA_CAST(0x0); - shotSpeed = GHIDRA_CAST(0x3f800000); - ownerPos.y = g_vectorZero.y; - } - else { - if (pEVar19->_type != 1) { - if (pEVar19->_type != 3) goto LAB_009fa53d; - ownerPlayer = *GHIDRA_CAST(&pEVar19->_isControlsEnabled); - goto LAB_009fa4db; - } - player = pEVar19; - ownerPlayer = pEVar19; -LAB_009fa525: - shotSpeed = GHIDRA_CAST(pEVar13->_shotspeed); - this_00 = ownerPlayer; -LAB_009fa572: - ownerPos.x = (pEVar19->_pos).x; - ownerPos.y = (pEVar19->_pos).y; - } - local_200 = player; - uVar6 = *GHIDRA_CAST((GHIDRA_CAST(this) + 0x34)); - isChocolateMilk = *GHIDRA_CAST((GHIDRA_CAST(this) + 0x34)) & 1; - isCursedEye = uVar6 >> 1 & 0xffffff01; - isBrimstone = uVar6 >> 2 & 0xffffff01; - local_1f0.y = (float)this_00; - (*GHIDRA_CAST((GHIDRA_CAST(&(local_1c4)) + 0x0))) = shotSpeed; - local_250 = (float)(uVar6 >> 3 & 0xffffff01); - if ((*GHIDRA_CAST((GHIDRA_CAST(this) + 0x30)) == 0xb) || (this_00 == GHIDRA_CAST(0x0))) { -LAB_009fa64b: - isDrFetus = '\0'; - if ((weaponType != 0xb) && (this_00 != GHIDRA_CAST(0x0))) goto LAB_009fa65b; -LAB_009fa671: - isEpicFetus = '\0'; - } - else { - owner = GHIDRA_CAST(0x0); - iVar30 = 0x34; - bVar4 = Entity_Player::HasCollectible(this_00,0x34,0); - if (bVar4 == 0) goto LAB_009fa64b; - owner = GHIDRA_CAST(0x0); - iVar30 = 0xa8; - bVar4 = Entity_Player::HasCollectible(this_00,0xa8,0); - if (bVar4 != 0) goto LAB_009fa64b; - isDrFetus = '\x01'; -LAB_009fa65b: - owner = GHIDRA_CAST(0x0); - iVar30 = 0xa8; - bVar4 = Entity_Player::HasCollectible(this_00,0xa8,0); - if (bVar4 == 0) goto LAB_009fa671; - isEpicFetus = '\x01'; - } - if (((*GHIDRA_CAST((GHIDRA_CAST(this) + 0x34)) >> 4 & 1) == 0) || (local_1f9 = '\x01', isEpicFetus != '\0')) { - local_1f9 = '\0'; - } - if ((weaponType == 0xb) || (this_00 == GHIDRA_CAST(0x0))) { -LAB_009fa6bd: - local_1c6 = '\0'; - } - else { - owner = GHIDRA_CAST(0x2c0); - iVar30 = 0x9fa6b2; - bVar4 = TemporaryEffects::HasCollectibleEffect(&this_00->_temporaryeffects,0x2c0); - local_1c6 = '\x01'; - if (bVar4 == 0) goto LAB_009fa6bd; - } - isCSection = *GHIDRA_CAST((GHIDRA_CAST(this) + 0x34)) >> 0xb & 0xffffff01; - uVar6 = isCSection; - if (((isChocolateMilk == 0) && ((char)isCursedEye == '\0')) && ((char)isBrimstone == '\0')) { - isChargeMode = '\0'; - if ((*GHIDRA_CAST((GHIDRA_CAST(&(local_250)) + 0x0))) != '\0') goto LAB_009fa703; - } - else { -LAB_009fa703: - isChargeMode = '\x01'; - } - if (((*GHIDRA_CAST((GHIDRA_CAST(this) + 0x34)) >> 7 & 1) != 0) || (*GHIDRA_CAST((GHIDRA_CAST(this) + 0x10)) <= 0.0)) { - pfVar18 = GHIDRA_CAST((GHIDRA_INT(this) + 0x10)); - local_1e4.y = 0.001; - local_1c5 = 1; - player = local_200; - shotSpeed = (*GHIDRA_CAST((GHIDRA_CAST(&(GHIDRA_CAST(local_1c4))) + 0x0))); - clampedValue = &local_1e4.y; - if (0.001 < *pfVar18 || *pfVar18 == 0.001) { - clampedValue = pfVar18; - } - ownerPlayer = GHIDRA_CAST(local_1f0.y); - chargeThreshold = GHIDRA_CAST(*clampedValue); - local_1e4.y = (float)chargeThreshold; - maxFireDelay = chargeThreshold; - this_00 = GHIDRA_CAST(local_1f0.y); - if ((char)isCSection != '\0') { - isChargeMode = '\x01'; - local_1c5 = 1; - isDrFetus = isDrFetus; - goto LAB_009fa822; - } - } - else { - pfVar18 = GHIDRA_CAST((GHIDRA_INT(this) + 0x10)); - local_1e4.y = 0.001; - local_1c5 = 0; - clampedValue = &local_1e4.y; - if (0.001 < *pfVar18 || *pfVar18 == 0.001) { - clampedValue = pfVar18; - } - chargeThreshold = GHIDRA_CAST(*clampedValue); - maxFireDelay = chargeThreshold; -LAB_009fa822: - local_1e4.y = (float)chargeThreshold; - } - isReleased = '\0'; - isCSection = uVar6; - chargeThreshold = GHIDRA_CAST(local_1e4.y); - maxFireDelay = GHIDRA_CAST(local_1e4.y); - if (this_00 == GHIDRA_CAST(0x0)) { -LAB_009fa84b: - local_200 = GHIDRA_CAST(0x1); - if (local_1c6 != '\0') { - local_200 = GHIDRA_CAST(0x3); - } - } - else { - owner = GHIDRA_CAST(0x0); - iVar30 = 0x72; - bVar4 = Entity_Player::HasCollectible(this_00,0x72,0); - if (bVar4 == 0) goto LAB_009fa84b; - local_200 = GHIDRA_CAST(0x2); - } - fVar23 = 2.0; - if (weaponType == 0xb) { - local_200 = GHIDRA_CAST(&DAT_00000009); - } - if ((((char)isCursedEye == '\0') && ((char)isCSection == '\0')) || (isChocolateMilk != 0)) { - fVar23 = 3.0; - } - local_1c6 = isShooting; - maxCharge = GHIDRA_CAST((fVar23 * (float)maxFireDelay)); - local_258.y = fVar23 * (float)maxFireDelay; - chargeThreshold = GHIDRA_CAST(((float)chargeThreshold + local_1e4.y)); - if ((isEpicFetus != '\0') && (player != GHIDRA_CAST(0x0))) { - if ((isShooting == 0) || - ((((pvVar17 = player->_heldEntity, pvVar17 == (void *)0x0 || - (*GHIDRA_CAST((GHIDRA_CAST(pvVar17) + 0x171)) != '\0')) || (*GHIDRA_CAST((GHIDRA_CAST(pvVar17) + 0x28)) != 1000)) || - (*GHIDRA_CAST((GHIDRA_CAST(pvVar17) + 0x2c)) != 0x76)))) { - if ((*GHIDRA_CAST((GHIDRA_CAST(this) + 0x58)) != GHIDRA_CAST(0x0)) && (isInterpolated == 0)) { - owner = GHIDRA_CAST(0x9fab42); - (**(code **)(**GHIDRA_CAST((GHIDRA_CAST(this) + 0x58)) + 0x28))(); - } - } - else { - iVar30 = 10; - owner = player; - Weapon::SetBlinkTime(this,10,GHIDRA_INT(player)); - if (*GHIDRA_CAST((GHIDRA_CAST(this) + 0x58)) == 0) { - if (isInterpolated == 0) { - owner = GHIDRA_CAST(Random()); - iVar30 = 0; - local_1f0.y = (float)Game::Spawn(g_game,1000,0x1e,&ownerPos,&g_vectorZero, - *GHIDRA_CAST((GHIDRA_CAST(this) + 4)),0,GHIDRA_UINT(owner)); - ((GHIDRA_CAST(local_1f0.y))->_bodySprite)._animState._animFrame = 0.0; - *GHIDRA_CAST(&((GHIDRA_CAST(local_1f0.y))->_bodySprite)._animState._isPlaying) = 0; - pEVar19 = *GHIDRA_CAST((GHIDRA_CAST(this) + 0x58)); - if (pEVar19 != GHIDRA_CAST(local_1f0.y)) { - if (pEVar19 != GHIDRA_CAST(0x0)) { - (*GHIDRA_CAST((GHIDRA_CAST(&(local_1c4)) + 0x0))) = GHIDRA_CAST((GHIDRA_INT(this) + 0x58)); - msvc::multiset::erase(); - } - owner = GHIDRA_CAST((GHIDRA_INT(this) + 0x58)); - *GHIDRA_CAST(owner) = local_1f0.y; - iVar30 = 0x9fa9ca; - msvc::multiset::insert(); - pEVar19 = *GHIDRA_CAST((GHIDRA_CAST(this) + 0x58)); - } - if (pEVar19 != GHIDRA_CAST(0x0)) goto LAB_009fa9d5; - } - } - else { -LAB_009fa9d5: - local_238.x = aimDirection->x; - local_238.y = aimDirection->y; - local_208 = GHIDRA_CAST(local_238.y); - local_1e4.y = local_238.x; - if (1.0 < local_238.x * local_238.x + local_238.y * local_238.y) { - (GHIDRA_CAST((&local_238)))->Vector::Normalize(); - local_208 = GHIDRA_CAST(local_238.y); - local_1e4.y = local_238.x; - } - owner = GHIDRA_CAST(0x0); - iVar30 = 0x166; - local_238.x = local_1e4.y; - local_238.y = (float)local_208; - bVar4 = Entity_Player::HasCollectible(player,0x166,0); - if (bVar4 == 0) { -LAB_009faadb: - pEVar19 = GHIDRA_CAST(local_1e4.y); - } - else { - owner = GHIDRA_CAST(0x0); - iVar30 = 0xf5; - bVar4 = Entity_Player::HasCollectible(player,0xf5,0); - if (bVar4 != 0) goto LAB_009faadb; - (*GHIDRA_CAST((GHIDRA_CAST(&(local_1c4)) + 0x0))) = cos(0.7853982); - owner = GHIDRA_CAST(0x9faa98); - fVar23 = sin(0.7853982); - fVar25 = fVar23 * (float)local_208; - local_208 = (uint8_t *) - (fVar23 * local_1e4.y + (*GHIDRA_CAST((GHIDRA_CAST(&((float)local_1c4)) + 0x0))) * (float)local_208); - pEVar19 = GHIDRA_CAST(((*GHIDRA_CAST((GHIDRA_CAST(&((float)local_1c4)) + 0x0))) * local_1e4.y - fVar25)); - } - iVar16 = *GHIDRA_CAST((GHIDRA_CAST(this) + 0x58)); - *GHIDRA_CAST((iVar16 + 0x360)) = - (float)pEVar19 * 8.0 * *GHIDRA_CAST((iVar16 + 0x39c)) + *GHIDRA_CAST((iVar16 + 0x360)); - *GHIDRA_CAST((iVar16 + 0x364)) = - (float)local_208 * 8.0 * *GHIDRA_CAST((iVar16 + 0x39c)) + *GHIDRA_CAST((iVar16 + 0x364)); - } - } - } - iVar16 = *GHIDRA_CAST((GHIDRA_CAST(this) + 4)); - clubScale = GHIDRA_CAST(0x3f800000); - if (iVar16 != 0) { - if (player == GHIDRA_CAST(0x0)) { - pVVar9 = GHIDRA_CAST((iVar16 + 0xe4)); - pVVar5 = GHIDRA_CAST(local_1c4); - if (*GHIDRA_CAST((iVar16 + 0x28)) != 3) { - if (1.0 < pVVar9->x) { - pVVar5 = pVVar9; - } - goto LAB_009fabed; - } - (*GHIDRA_CAST((GHIDRA_CAST(&(local_1c4)) + 0x0))) = pVVar9->x * 0.8; - local_1f0.y = 0.8; - if ((*GHIDRA_CAST((GHIDRA_CAST(&((float)local_1c4)) + 0x0))) <= 0.8) { - pVVar5 = GHIDRA_CAST(&local_1f0.y); - } - } - else { - local_238.x = (player->_playerSpriteScale).x; - local_238.y = (player->_playerSpriteScale).y; - pVVar5 = &local_238; - if (local_238.x <= 1.0) { - pVVar5 = GHIDRA_CAST(local_1c4); - } -LAB_009fabed: - (*GHIDRA_CAST((GHIDRA_CAST(&(local_1c4)) + 0x0))) = GHIDRA_CAST(0x3f800000); - } - clubScale = GHIDRA_CAST(pVVar5->x); - } - if ((this_00 != GHIDRA_CAST(0x0)) && (weaponType != 0xb)) { - bVar4 = TemporaryEffects::HasCollectibleEffect(&this_00->_temporaryeffects,0x271); - if (bVar4 != 0) { - clubScale = GHIDRA_CAST(((float)clubScale * 4.0)); - } - owner = GHIDRA_CAST(0x0); - iVar30 = 0xa9; - bVar4 = Entity_Player::HasCollectible(this_00,0xa9,0); - if (bVar4 == 0) { - owner = GHIDRA_CAST(0x0); - iVar30 = 0x213; - bVar4 = Entity_Player::HasCollectible(this_00,0x213,0); - if (bVar4 != 0) { - clubScale = GHIDRA_CAST(((float)clubScale * 1.5)); - } - } - else { - clubScale = GHIDRA_CAST(((float)clubScale + (float)clubScale)); - } - } - if ((local_1f9 != '\0') && (*GHIDRA_CAST((GHIDRA_CAST(this) + 0x54)) == 0)) { - TearParams::constructor(GHIDRA_CAST((local_1c4 + 4))); - if (this_00 != GHIDRA_CAST(0x0)) { - pEVar31 = *GHIDRA_CAST((GHIDRA_CAST(this) + 4)); - uVar6 = Random(); - this_00 = ownerPlayer; - pTVar7 = Entity_Player::GetTearHitParams - (ownerPlayer,&local_158,8,1.0,(uVar6 & 1) * 2 + -1,pEVar31); - TearParams::operator_(GHIDRA_CAST((local_1c4 + 4)),pTVar7); - } - uVar6 = Random(); - local_238.x = ownerPos.x + 0.0; - local_238.y = ownerPos.y + 5.0; - local_1d8 = (Entity_Bomb *) - Game::Spawn(g_game,2,(*GHIDRA_CAST((GHIDRA_CAST(&(local_1c4)) + 0x4))),&local_238,&g_vectorZero, - *GHIDRA_CAST((GHIDRA_CAST(this) + 4)),2,uVar6); - if ((local_1d8 == GHIDRA_CAST(0x0)) || (local_1d8->_type != 2)) { - local_1d8 = GHIDRA_CAST(0x0); - } - local_1f0.y = (float)&local_1d8->_parent; - local_218.y = *GHIDRA_CAST((GHIDRA_CAST(this) + 4)); - if (local_1d8->_parent != 0) { - (*GHIDRA_CAST((GHIDRA_CAST(&(local_1c4)) + 0x0))) = local_1f0.y; - msvc::multiset::erase(); - } - *GHIDRA_CAST(local_1f0.y) = local_218.y; - if (GHIDRA_CAST(local_218.y) != GHIDRA_CAST(0x0)) { - msvc::multiset::insert(); - } - Entity_Projectile::SetHeight(GHIDRA_CAST(local_1d8),-40.0); - owner = tearDamage; - (**(code **)(*GHIDRA_CAST(local_1d8) + 0x40))(); - b = &g_tearFlagSpectral; - pBVar8 = BitSet128::operator_or(GHIDRA_CAST(local_50),&tearFlags,&g_tearFlagLudovico); - pBVar8 = BitSet128::operator_or(GHIDRA_CAST(&local_2bc),pBVar8,b); - Entity_Tear::SetTearFlags(GHIDRA_CAST(local_1d8),*pBVar8); - iVar30 = 1; - (**(code **)(*GHIDRA_CAST(local_1d8) + 0x3c))(); - fVar23 = sqrtf((float)tearDamage); - local_1f0.y = 0.01; - (*GHIDRA_CAST((GHIDRA_CAST(&(local_1c4)) + 0x0))) = (float)tearDamage * 0.04 + 1.5 + fVar23 * 0.15; - pfVar18 = GHIDRA_CAST(local_1c4); - if ((*GHIDRA_CAST((GHIDRA_CAST(&((float)local_1c4)) + 0x0))) <= 0.01) { - pfVar18 = &local_1f0.y; - } - fVar23 = *pfVar18; - local_1d8->_bounceCount = GHIDRA_INT(fVar23); - local_1d8->_fallAcceleration = fVar23; - Entity_Tear::ResetSpriteScale(GHIDRA_CAST(local_1d8)); - (**(code **)(*GHIDRA_CAST(local_1d8) + 0xc))(); - if (*GHIDRA_CAST((GHIDRA_CAST(this) + 0x54)) != local_1d8) { - if (*GHIDRA_CAST((GHIDRA_CAST(this) + 0x54)) != GHIDRA_CAST(0x0)) { - (*GHIDRA_CAST((GHIDRA_CAST(&(local_1c4)) + 0x0))) = GHIDRA_CAST((GHIDRA_INT(this) + 0x54)); - msvc::multiset::erase(); - } - owner = GHIDRA_CAST((GHIDRA_INT(this) + 0x54)); - *GHIDRA_CAST(owner) = local_1d8; - iVar30 = 0x9faefd; - msvc::multiset::insert(); - } - } - if ((weaponType == 0xb) || (this_00 == GHIDRA_CAST(0x0))) { -LAB_009faf2a: - local_1f9 = '\0'; - if ((weaponType != 0xb) && (this_00 != GHIDRA_CAST(0x0))) goto LAB_009faf3a; -LAB_009faf4d: - cVar12 = '\0'; - } - else { - owner = GHIDRA_CAST(0x0); - iVar30 = 0x57; - bVar4 = Entity_Player::HasCollectible(this_00,0x57,0); - if (bVar4 == 0) goto LAB_009faf2a; - local_1f9 = '\x01'; -LAB_009faf3a: - owner = GHIDRA_CAST(0x0); - iVar30 = 0x37; - bVar4 = Entity_Player::HasCollectible(this_00,0x37,0); - if (bVar4 == 0) goto LAB_009faf4d; - cVar12 = '\x01'; - } - pEVar19 = local_200; - local_1d2 = CONCAT11(cVar12,(uint8_t)local_1d2); - local_208 = GHIDRA_CAST(0x0); - do { - if ((local_208 == GHIDRA_CAST(0x0)) || - (((local_208 == GHIDRA_CAST(0x1) && (cVar12 != '\0')) || (local_1f9 != '\0')))) { - local_1f0.y = (float)(GHIDRA_INT(this) + GHIDRA_INT(local_208) * 4 + 0x44); - piVar15 = *GHIDRA_CAST((GHIDRA_CAST(this) + GHIDRA_INT(local_208) * 4 + 0x44)); - if (piVar15 != GHIDRA_CAST(0x0)) { - if ((piVar15[10] == 8) && (GHIDRA_CAST(piVar15[0xb]) == pEVar19)) goto LAB_009fb07f; - owner = GHIDRA_CAST(0x9faff5); - (**(code **)(*piVar15 + 0x28))(); - } - local_218.y = (float)Weapon::fire_bone_club - (this,*GHIDRA_CAST((GHIDRA_CAST(this) + 4)),GHIDRA_UINT(pEVar19),1,iVar30, - GHIDRA_INT(owner),0.0); - if (*GHIDRA_CAST(local_1f0.y) != GHIDRA_CAST(local_218.y)) { - if (*GHIDRA_CAST(local_1f0.y) != GHIDRA_CAST(0x0)) { - (*GHIDRA_CAST((GHIDRA_CAST(&(local_1c4)) + 0x0))) = local_1f0.y; - iVar30 = 0x9fb038; - msvc::multiset::erase(); - } - *GHIDRA_CAST(local_1f0.y) = local_218.y; - if (GHIDRA_CAST(local_218.y) != GHIDRA_CAST(0x0)) { - iVar30 = 0x9fb050; - msvc::multiset::insert(); - } - } - *GHIDRA_CAST((GHIDRA_CAST(local_218.y) + 0x438)) = (&DAT_00b81710)[GHIDRA_INT(local_208)]; - *GHIDRA_CAST((GHIDRA_CAST(local_218.y) + 0x467)) = local_208 == GHIDRA_CAST(0x0); - owner = GHIDRA_CAST(0x9fb079); - (**(code **)(*GHIDRA_CAST(local_218.y) + 0xc))(); - } - else { - local_1f0.y = (float)(GHIDRA_INT(this) + GHIDRA_INT(local_208) * 4 + 0x44); - if (*GHIDRA_CAST(local_1f0.y) != GHIDRA_CAST(0x0)) { - owner = GHIDRA_CAST(0x9faf94); - (**(code **)(**GHIDRA_CAST(local_1f0.y) + 0x28))(); - if (*GHIDRA_CAST(local_1f0.y) != 0) { - (*GHIDRA_CAST((GHIDRA_CAST(&(local_1c4)) + 0x0))) = local_1f0.y; - owner = GHIDRA_CAST(local_1c4); - iVar30 = 0x9fafbc; - msvc::multiset::erase(); - *GHIDRA_CAST(local_1f0.y) = 0; - } - } - } -LAB_009fb07f: - pEVar13 = ownerPlayer; - local_208 = local_208 + 1; - cVar12 = (*GHIDRA_CAST((GHIDRA_CAST(&(local_1d2)) + 0x1))); - } while (local_208 < &DAT_00000004); - heldClub = *GHIDRA_CAST((GHIDRA_CAST(this) + 0x44)); - shotDirection.y = aimDirection->y; - shotDirection.x = aimDirection->x; - if (shotDirection.y == 0.0) { - if (shotDirection.x == 0.0) { - shotDirection.x = *GHIDRA_CAST((GHIDRA_CAST(this) + 0x20)); - shotDirection.y = *GHIDRA_CAST((GHIDRA_CAST(this) + 0x24)); - } - if (((shotDirection.y == 0.0) && (shotDirection.x == 0.0)) && (player != GHIDRA_CAST(0x0))) - { - switch(player->_headDirection) { - case 0: - shotDirection.x = (float)&DAT_bf800000; - break; - case 1: - shotDirection.y = (float)&DAT_bf800000; - break; - case 2: - shotDirection.x = 1.0; - break; - case 3: - shotDirection.y = 1.0; - } - } - } - bVar4 = Weapon::IsAxisAligned(this); - if (bVar4 != 0) { - pVVar9 = Vector::ToCardinal(&local_274,&shotDirection); - shotDirection.x = (float)pVVar9->x; - shotDirection.y = (float)pVVar9->y; - } - local_218.y = shotDirection.y; - local_1f0.y = shotDirection.x; - if ((((player != GHIDRA_CAST(0x0)) && (iVar30 = *GHIDRA_CAST((GHIDRA_CAST(this) + 4)), iVar30 != 0)) && - (*GHIDRA_CAST((iVar30 + 0x28)) == 1)) && - ((0 < *GHIDRA_CAST((iVar30 + 0x145c)) || - ((*GHIDRA_CAST((iVar30 + 0x2c)) == 1 && (*GHIDRA_CAST((iVar30 + 0x1aec)) == 8)))))) { - (*GHIDRA_CAST((GHIDRA_CAST(&(local_1c4)) + 0x0))) = (float)GHIDRA_INT(*GHIDRA_CAST((iVar30 + 0x1578))) * 45.0 * 0.017453292; - local_2a4.y = cos((*GHIDRA_CAST((GHIDRA_CAST(&((float)local_1c4)) + 0x0)))); - fVar23 = sin((*GHIDRA_CAST((GHIDRA_CAST(&((float)local_1c4)) + 0x0)))); - shotDirection.x = (float)(local_2a4.y * local_1f0.y - fVar23 * local_218.y); - shotDirection.y = (float)(local_2a4.y * local_218.y + fVar23 * local_1f0.y); - ownerPlayer = pEVar13; - } - if ((heldClub->_isSwinging == 0) && (heldClub->_isFlying == 0)) { - local_1f0.y = (float)(GHIDRA_INT(this) + 0x44); - local_1e4.y = 0.0; - owner = GHIDRA_CAST(shotDirection.y); - pEVar19 = GHIDRA_CAST(shotDirection.x); - do { - (*GHIDRA_CAST((GHIDRA_CAST(&(local_1c4)) + 0x0))) = *GHIDRA_CAST(local_1f0.y); - if ((*GHIDRA_CAST((GHIDRA_CAST(&(GHIDRA_CAST(local_1c4))) + 0x0))) != GHIDRA_CAST(0x0)) { - fVar23 = atan2f((float)owner,(float)pEVar19); - fVar23 = fVar23 * 57.295776 + - *GHIDRA_CAST((&(*GHIDRA_CAST((GHIDRA_CAST(((GHIDRA_CAST((GHIDRA_INT(local_1e4.y) + 0xb7f600))))) + 0x1c08))) + 0x508)) - ; - if (360.0 < ABS(fVar23)) { - fVar23 = fmodf(fVar23,360.0); - } - if (fVar23 <= 180.0) { - if (fVar23 < -180.0) { - fVar23 = fVar23 + 360.0; - } - } - else { - fVar23 = fVar23 - 360.0; - } - *GHIDRA_CAST((((GHIDRA_CAST(((*GHIDRA_CAST((GHIDRA_CAST(&(local_1c4)) + 0x0))) + 0x41c)))->_animDefaultName)._buf + 4)) = fVar23; - owner = GHIDRA_CAST(shotDirection.y); - pEVar19 = GHIDRA_CAST(shotDirection.x); - } - local_1e4.y = (float)&(*GHIDRA_CAST((GHIDRA_CAST(((GHIDRA_CAST(local_1e4.y)))) + 0x4))); - local_1f0.y = (float)(GHIDRA_INT(local_1f0.y) + 4); - } while (GHIDRA_UINT(local_1e4.y) < GHIDRA_CAST(0x10)); - if ((*GHIDRA_CAST((GHIDRA_CAST((heldClub)) + 0x466))) == '\0') { - heldClub->_rotationOffset = 0.0; - } - iVar30 = g_game->_frameCount - heldClub->_spawnFrame; - if (*GHIDRA_CAST((GHIDRA_CAST(this) + 0x14)) <= 0.0) { - if (iVar30 < 2) { - local_1f0.y = (float)clubScale; - } - else { - fVar23 = (heldClub->_sprite)._scale.x; - local_1f0.y = ((float)clubScale - fVar23) * 0.5 + fVar23; - } - } - else { - if (1 < iVar30) goto LAB_009fb512; - local_1f0.y = (float)clubScale; - } - local_1e4.y = (float)(GHIDRA_INT(this) + 0x44); - local_218.y = 5.60519e-45; - do { - if (*GHIDRA_CAST(local_1e4.y) != 0) { - init_club(); - iVar30 = *GHIDRA_CAST(local_1e4.y); - fVar23 = local_1f0.y * g_vectorOne.y; - *GHIDRA_CAST((iVar30 + 0xe4)) = local_1f0.y * g_vectorOne.x; - *GHIDRA_CAST((iVar30 + 0xe8)) = fVar23; - } - owner = GHIDRA_CAST((GHIDRA_INT(local_218.y) + -0x2f00)); - local_1e4.y = (float)&(*GHIDRA_CAST((GHIDRA_CAST(((GHIDRA_CAST(local_1e4.y)))) + 0x4))); - local_218.y = (float)&(*GHIDRA_CAST((GHIDRA_CAST((owner)) + 0x2eff))); - } while (&(*GHIDRA_CAST((GHIDRA_CAST((owner)) + 0x2eff))) != GHIDRA_CAST(0x0)); - } -LAB_009fb512: - if (local_1c6 == 0) { - if (((char)isBrimstone != '\0') && (bVar4 = Weapon::IsItemAnimFinished(this,0x76), bVar4 != 0)) - { - Weapon::stop_costume_item_anim(this,0x76); - } - if ((char)isCursedEye != '\0') { - Weapon::stop_costume_item_anim(this,0x13c); - } - if ((isChocolateMilk != 0) && (bVar4 = Weapon::IsItemAnimFinished(this,0x45), bVar4 != 0)) { - Weapon::stop_costume_item_anim(this,0x45); - } - if (((*GHIDRA_CAST((GHIDRA_CAST(&(local_250)) + 0x0))) != '\0') && (bVar4 = Weapon::IsItemAnimFinished(this,0xe5), bVar4 != 0)) { - Weapon::stop_costume_item_anim(this,0xe5); - } - if (((char)isCSection != '\0') && - (bVar4 = Weapon::is_c_section_anim_finished(this,isCSection), bVar4 != 0)) { - Weapon::update_c_section_charge_anim(this,unusedCollectibleId,0,aimDirection,0.0); - } - } - if (isInterpolated != 0) { - ExceptionList = local_10; - return; - } - owner = *GHIDRA_CAST((GHIDRA_CAST(this) + 0x14)); - newCharge = owner; - if (local_1c6 == 0) { - if ((isChargeMode != '\0') || - (((player != GHIDRA_CAST(0x0) && (player->_heldEntity != (void *)0x0)) || - ((char)isCSection != '\0')))) { - if (0.0 < (float)owner) { - newCharge = GHIDRA_CAST(0x0); - if (0.0 <= *GHIDRA_CAST((GHIDRA_CAST(this) + 0xc))) { - *GHIDRA_CAST((GHIDRA_CAST(this) + 0x5c)) = 0; - } - } - goto LAB_009fba4f; - } - if (1.0 < (float)owner) { - EntityList::QuerySublist - (GHIDRA_CAST((GHIDRA_INT(g_game->_room) + 0x1218)),GHIDRA_CAST(&local_2bc),8,1,-1,0,0) - ; - local_8 = 5.60519e-45; - local_200 = GHIDRA_CAST(0x0); - iVar30 = extraout_ECX; - if (puStack_2b0 != GHIDRA_CAST(0x0)) { - do { - (*GHIDRA_CAST((GHIDRA_CAST(&(local_1c4)) + 0x0))) = *GHIDRA_CAST((GHIDRA_CAST(pvStack_2b8) + GHIDRA_INT(local_200) * 4)); - iVar30 = ((*GHIDRA_CAST((GHIDRA_CAST(&(GHIDRA_CAST(local_1c4))) + 0x0))))->_parent; - if ((iVar30 != 0) && - ((iVar30 == *GHIDRA_CAST((GHIDRA_CAST(this) + 4)) || - (*GHIDRA_CAST((iVar30 + 0x3bc)) == *GHIDRA_CAST((GHIDRA_CAST(this) + 4)))))) { - fVar23 = *GHIDRA_CAST(((((*GHIDRA_CAST((GHIDRA_CAST(&(GHIDRA_CAST(local_1c4))) + 0x0))))->_bodySprite)._animDefaultName. - _buf + 8)) * 0.5; - if (360.0 < ABS(fVar23)) { - fVar23 = fmodf(fVar23,360.0); - iVar30 = extraout_ECX_00; - } - if (fVar23 <= 180.0) { - if (fVar23 < -180.0) { - fVar23 = fVar23 + 360.0; - } - } - else { - fVar23 = fVar23 - 360.0; - } - *GHIDRA_CAST((((GHIDRA_CAST(((*GHIDRA_CAST((GHIDRA_CAST(&(local_1c4)) + 0x0))) + 0x41c)))->_animDefaultName)._buf + 8)) = fVar23; - } - local_200 = GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((local_200)) + 0x1)))); - } while (local_200 < puStack_2b0); - pEVar13 = ownerPlayer; - } - Weapon::SetBlinkTime(this,7 - GHIDRA_INT(((float)maxFireDelay * -0.45)),iVar30); - Weapon::TriggerTearEffects(this,&shotDirection,1); - (*GHIDRA_CAST((GHIDRA_CAST(&(local_1c4)) + 0x0))) = (float)maxFireDelay * 3.0; - local_1f0.y = 300.0; - maxFireDelay = (*GHIDRA_CAST((GHIDRA_CAST(&(GHIDRA_CAST(local_1c4))) + 0x0))); - pfVar18 = GHIDRA_CAST(local_1c4); - if (*GHIDRA_CAST((GHIDRA_CAST(this) + 0x14)) <= (*GHIDRA_CAST((GHIDRA_CAST(&((float)local_1c4)) + 0x0)))) { - pfVar18 = GHIDRA_CAST((GHIDRA_INT(this) + 0x14)); - } - local_200 = GHIDRA_CAST(*pfVar18); - if ((pEVar13 == GHIDRA_CAST(0x0)) || - (bVar4 = Entity_Player::HasCollectible(pEVar13,0xe9,0), bVar4 == 0)) { - fVar23 = 300.0; - local_1e4.y = 0.2; - local_250 = (float)local_200 / (float)maxFireDelay; - pfVar18 = &local_250; - if ((float)local_200 / (float)maxFireDelay <= 0.2) { - pfVar18 = &local_1e4.y; - } - local_218.y = (float)*pfVar18; - if (pEVar13 == GHIDRA_CAST(0x0)) { - (*GHIDRA_CAST((GHIDRA_CAST(&(local_1c4)) + 0x0))) = GHIDRA_CAST(0x43820000); - } - else { - (*GHIDRA_CAST((GHIDRA_CAST(&(local_1c4)) + 0x0))) = pEVar13->_tearrange; - } - } - else { - local_1e4.y = 0.2; - local_1f0.y = 100000.0; - fVar23 = 100000.0; - local_250 = (float)local_200 / (float)maxFireDelay; - (*GHIDRA_CAST((GHIDRA_CAST(&(local_1c4)) + 0x0))) = pEVar13->_tearrange; - pfVar18 = &local_250; - if ((float)local_200 / (float)maxFireDelay <= 0.2) { - pfVar18 = &local_1e4.y; - } - local_218.y = (float)*pfVar18; - } - local_1e4.y = 0.2; - local_200 = GHIDRA_CAST(0x43480000); - pfVar18 = GHIDRA_CAST(local_1c4); - if (fVar23 <= (*GHIDRA_CAST((GHIDRA_CAST(&((float)local_1c4)) + 0x0)))) { - pfVar18 = &local_1f0.y; - } - (*GHIDRA_CAST((GHIDRA_CAST(&(local_1c4)) + 0x0))) = GHIDRA_CAST((*pfVar18 * 0.9)); - ppEVar10 = GHIDRA_CAST(local_1c4); - if (*pfVar18 * 0.9 <= 200.0) { - ppEVar10 = &local_200; - } - uVar6 = 0; - owner = *ppEVar10; - local_200 = GHIDRA_CAST((GHIDRA_INT(this) + 0x44)); - (*GHIDRA_CAST((GHIDRA_CAST(&(local_1c4)) + 0x0))) = owner; - do { - club = *GHIDRA_CAST(local_200); - if ((club != GHIDRA_CAST(0x0)) && ((uVar6 == 0 || ((*GHIDRA_CAST((GHIDRA_CAST((club)) + 0x466))) != '\0')))) { - Entity_Knife::Shoot(club,local_218.y,(float)owner); - owner = (*GHIDRA_CAST((GHIDRA_CAST(&(GHIDRA_CAST(local_1c4))) + 0x0))); - } - uVar6 = uVar6 + 1; - local_200 = GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((local_200)) + 0x4)))); - } while (uVar6 < 4); - Weapon::SetHeadLockTime(this,2); - if (player != GHIDRA_CAST(0x0)) { - Entity_Player::TryForgottenThrow(player,&shotDirection); - } - local_8 = -NAN; - if ((*GHIDRA_CAST((GHIDRA_CAST(&(local_2bc)) + 0x0))) == '\0') { - local_8 = 7.00649e-45; - tracked_alloc(1,pvStack_2b8,0); - } - } - if (*GHIDRA_CAST((GHIDRA_CAST(this) + 0x44)) != 0) { - *GHIDRA_CAST((*GHIDRA_CAST((GHIDRA_CAST(this) + 0x44)) + 0x466)) = 0; - } - if (*GHIDRA_CAST((GHIDRA_CAST(this) + 0x48)) != 0) { - *GHIDRA_CAST((*GHIDRA_CAST((GHIDRA_CAST(this) + 0x48)) + 0x466)) = 0; - } - if (*GHIDRA_CAST((GHIDRA_CAST(this) + 0x4c)) != 0) { - *GHIDRA_CAST((*GHIDRA_CAST((GHIDRA_CAST(this) + 0x4c)) + 0x466)) = 0; - } - if (*GHIDRA_CAST((GHIDRA_CAST(this) + 0x50)) != 0) { - *GHIDRA_CAST((*GHIDRA_CAST((GHIDRA_CAST(this) + 0x50)) + 0x466)) = 0; - } - *GHIDRA_CAST((GHIDRA_CAST(this) + 0x20)) = g_vectorZero.x; - *GHIDRA_CAST((GHIDRA_CAST(this) + 0x24)) = g_vectorZero.y; - owner = GHIDRA_CAST(0x0); -LAB_009fb9ec: - club = heldClub; - goto LAB_009fb9f2; - } -LAB_009fba4f: - iVar30 = *GHIDRA_CAST((GHIDRA_CAST(this) + 4)); - if (((iVar30 == 0) || (*GHIDRA_CAST((iVar30 + 0x28)) != 1)) || - (piVar15 = GHIDRA_CAST(isCSection), *GHIDRA_CAST((iVar30 + 0x18f8)) < 1)) { - uVar20 = (undefined3)(GHIDRA_UINT(player) >> 8); - if ((player == GHIDRA_CAST(0x0)) || ((player->_temporaryeffects)._disabled != 0)) { - rngResult = CONCAT31(uVar20,local_1c5); - } - else { - effectIt = (player->_temporaryeffects)._effects._begin; - effectsEnd = (player->_temporaryeffects)._effects._end; - if (effectIt == effectsEnd) { - rngResult = CONCAT31(uVar20,local_1c5); - } - else { - do { - piVar15 = GHIDRA_CAST(*effectIt); - if ((*piVar15 == 0) && (piVar15[1] == 0x78)) goto LAB_009fbb0b; - effectIt = effectIt + 4; - rngResult = CONCAT31(CONCAT21((short)(GHIDRA_UINT(player) >> 0x10),isDrFetus),local_1c5); - ownerPlayer = pEVar13; - } while (effectIt != effectsEnd); - isDrFetus = isDrFetus; - player = player; - } - } - if ((char)rngResult == '\0') { - if ((char)isCSection != '\0') goto LAB_009fbb7b; - } - else { - if (isChargeMode == '\0') goto LAB_009fbb11; -LAB_009fbb7b: - if ((((local_1c6 != 0) && ((float)maxCharge <= (float)owner)) && - (local_1c6 = 0, 0.0 < (float)owner)) && - (newCharge = GHIDRA_CAST(0x0), 0.0 <= *GHIDRA_CAST((GHIDRA_CAST(this) + 0xc)))) { - *GHIDRA_CAST((GHIDRA_CAST(this) + 0x5c)) = 0; - } - isReleased = '\x01'; - } - } - else { -LAB_009fbb0b: - rngResult = CONCAT31((int3)(GHIDRA_UINT(piVar15) >> 8),local_1c5); -LAB_009fbb11: - isChargeMode = '\0'; - newCharge = owner; - local_1f0.y = (float)owner; - *GHIDRA_CAST((GHIDRA_CAST(this) + 0x14)) = 0; - if ((char)rngResult != '\0') { - (*GHIDRA_CAST((GHIDRA_CAST(&(local_1c4)) + 0x0))) = GHIDRA_CAST(0x3f800000); - isReleased = '\x01'; - pfVar18 = GHIDRA_CAST(local_1c4); - if (1.0 <= (float)owner) { - pfVar18 = &local_1f0.y; - } - newCharge = GHIDRA_CAST(*pfVar18); - } - } - pEVar19 = player; - pfVar18 = GHIDRA_CAST((GHIDRA_INT(this) + 0x14)); - iVar30 = CONCAT22((short)(GHIDRA_UINT(rngResult) >> 0x10),CONCAT11(local_1c6,(char)rngResult)); - if ((local_1c6 == 0) || ((heldClub->_isSwinging != 0 && ((char)rngResult == '\0')))) { - if ((isChargeMode == '\0') && (local_1c6 != 0)) goto LAB_009fbc0f; -LAB_009fbc27: - if ((((player != GHIDRA_CAST(0x0)) && (player->_heldEntity != (void *)0x0)) && - (local_1c6 == 0)) || - ((((char)isCSection != '\0' && (local_1c6 == 0)) && - ((*GHIDRA_CAST((GHIDRA_CAST(this) + 0xc)) <= 0.0 && *GHIDRA_CAST((GHIDRA_CAST(this) + 0xc)) != 0.0 && - (1.0 < *pfVar18)))))) goto LAB_009fbcd3; - owner = newCharge; - if (((isChocolateMilk == 0) && ((char)isBrimstone == '\0')) && ((*GHIDRA_CAST((GHIDRA_CAST(&(local_250)) + 0x0))) == '\0')) { - if ((char)isCursedEye != '\0') goto LAB_009fbc86; - goto LAB_009fdeca; - } - if ((char)isCursedEye == '\0') { - if (local_1c6 == 0) { - if ((0.0 < *GHIDRA_CAST((GHIDRA_CAST(this) + 0xc)) || *GHIDRA_CAST((GHIDRA_CAST(this) + 0xc)) == 0.0) || - (*pfVar18 <= 1.0)) goto LAB_009fb9ec; - goto LAB_009fbcd3; - } - } - else { -LAB_009fbc86: - if (local_1c6 == 0) { - if ((0.0 < *GHIDRA_CAST((GHIDRA_CAST(this) + 0xc)) || *GHIDRA_CAST((GHIDRA_CAST(this) + 0xc)) == 0.0) || - (*GHIDRA_CAST((GHIDRA_CAST(this) + 0x5c)) < 1)) goto LAB_009fb9ec; - goto LAB_009fbcd3; - } - } - } - else { - if (isChargeMode != '\0') { - if (*pfVar18 <= 1.0 && *pfVar18 != 1.0) { - *pfVar18 = 1.0; - newCharge = GHIDRA_CAST(0x3f800000); - } - goto LAB_009fbc27; - } -LAB_009fbc0f: - if (((0.0 < *GHIDRA_CAST((GHIDRA_CAST(this) + 0xc)) || *GHIDRA_CAST((GHIDRA_CAST(this) + 0xc)) == 0.0) || - (0.0 < *pfVar18)) || (heldClub->_isFlying != 0)) goto LAB_009fbc27; -LAB_009fbcd3: - Weapon::GetMultiShotParams(this,local_2f8 + 8,iVar30); - iVar30 = *GHIDRA_CAST((GHIDRA_CAST(this) + 4)); - *GHIDRA_CAST((GHIDRA_CAST(this) + 0xc)) = maxFireDelay; - iVar16 = extraout_ECX_01; - if (iVar30 != 0) { - uVar21 = (uint3)(GHIDRA_UINT(extraout_ECX_01) >> 8); - if (*GHIDRA_CAST((iVar30 + 0x28)) == 1) { - iVar16 = CONCAT31(uVar21,*GHIDRA_CAST((iVar30 + 0x1578))); - } - else if ((iVar30 == 0) || (iVar16 = GHIDRA_UINT(uVar21) << 8, *GHIDRA_CAST((iVar30 + 0x28)) != 1)) - goto LAB_009fbd18; - cVar12 = (char)iVar16; - iVar16 = CONCAT31((int3)(GHIDRA_UINT(iVar16) >> 8),-cVar12); - *GHIDRA_CAST((iVar30 + 0x1578)) = -cVar12; - } -LAB_009fbd18: - Weapon::SetBlinkTime(this,7 - GHIDRA_INT(((float)maxFireDelay * -0.45)),iVar16); - Weapon::TriggerTearEffects(this,&shotDirection,1); - pfVar18 = &local_1f0.y; - local_1f0.y = 0.5; - damageMultiplier = 1.0; - local_2bc = (*GHIDRA_CAST((GHIDRA_CAST(&((float)local_2f8)) + 0x8))); - pvStack_2b8 = (*GHIDRA_CAST((GHIDRA_CAST(&((void *)local_2f8)) + 0xc))); - fStack_2b4 = (*GHIDRA_CAST((GHIDRA_CAST(&((float)local_2f8)) + 0x10))); - puStack_2b0 = (*GHIDRA_CAST((GHIDRA_CAST(&(GHIDRA_CAST(local_2f8))) + 0x14))); - (*GHIDRA_CAST((GHIDRA_CAST(&(local_1c4)) + 0x0))) = 1.0 / ((float)clubScale * 0.5 + 0.5); - clampedValue = GHIDRA_CAST(local_1c4); - if ((*GHIDRA_CAST((GHIDRA_CAST(&((float)local_1c4)) + 0x0))) <= 0.5) { - clampedValue = pfVar18; - } - fStack_2cc = (*GHIDRA_CAST((GHIDRA_CAST(&((float)local_2f8)) + 0x18))); - lanesPerEye = (*GHIDRA_CAST((GHIDRA_CAST(&(local_2f8)) + 0x1c))); - fStack_2c4 = (*GHIDRA_CAST((GHIDRA_CAST(&((float)local_2f8)) + 0x20))); - fStack_2c0 = uStack_2d4; - local_208 = local_2d0; - local_238.y = *clampedValue; - local_1d2 = (*GHIDRA_CAST((GHIDRA_CAST(&(local_2f8)) + 0x8))); - if (pEVar19 != GHIDRA_CAST(0x0)) { - pvVar17 = pEVar19->_heldEntity; - local_1f0.y = (float)&pEVar19->_heldEntity; - if (pvVar17 != (void *)0x0) { - fVar23 = (pEVar19->_pos).y; - *GHIDRA_CAST((GHIDRA_CAST(pvVar17) + 0x33c)) = (pEVar19->_pos).x; - *GHIDRA_CAST((GHIDRA_CAST(pvVar17) + 0x340)) = fVar23; - owner = pEVar19->_heldEntity; - local_1e4.y = (float)owner; - if (owner->_type == 4) { - savedBombFlags = owner->_flags; - bombFlagsHigh = GHIDRA_CAST((GHIDRA_INT(&owner->_flags) + 4)); - *bombFlagsHigh = *bombFlagsHigh & 0xfdffffdf; - *GHIDRA_CAST(&owner->_flags) = GHIDRA_INT(savedBombFlags); - owner->_renderZOffset = 0; - local_218.y = 0.0; - if (0 < (*GHIDRA_CAST((GHIDRA_CAST(&((short)local_2f8)) + 0x8)))) { - (*GHIDRA_CAST((GHIDRA_CAST(&(local_1c4)) + 0x0))) = (*GHIDRA_CAST((GHIDRA_CAST(&(GHIDRA_INT((short)local_2f8))) + 0x8))) / 2; - do { - owner = GHIDRA_CAST(local_1e4.y); - FUN_009f4230(local_27c,local_218.y,5,shotDirection.x,shotDirection.y,shotSpeed); - if (local_218.y == (*GHIDRA_CAST((GHIDRA_CAST(&((float)local_1c4)) + 0x0)))) { - (*GHIDRA_CAST((GHIDRA_CAST(&(((GHIDRA_CAST((GHIDRA_INT(local_1e4.y) + 0x41c)))->_animState))) + 0x15))) = 1; - } - else { - owner = GHIDRA_CAST(Weapon)::fire_bomb(this,&ownerPos,&g_vectorZero); - iVar30 = *GHIDRA_CAST((GHIDRA_CAST(player->_heldEntity) + 0x410)); - *GHIDRA_CAST(&owner->_isControlsEnabled) = iVar30; - owner->_controlsCooldown = iVar30; - anim = ANM2::GetAnimation(GHIDRA_CAST(&(GHIDRA_CAST((GHIDRA_INT(local_1e4.y) + 0x48)))->_animState), - GHIDRA_CAST((local_c4 + 0x14))); - local_8 = 0.0; - if (0xf < anim->_capacity) { - anim = *GHIDRA_CAST(anim->_buf); - } - ANM2::Play(&owner->_sprite,GHIDRA_CAST(anim),0); - local_8 = -NAN; - (GHIDRA_CAST((local_c4 + 0x14)))->msvc::string::_Tidy_deallocate(); - if ((owner->_sprite)._animState._animData != (void *)0x0) { - AnimationState::SetFrameFloat - (&(owner->_sprite)._animState, - (float)GHIDRA_INT(((GHIDRA_CAST((GHIDRA_INT(local_1e4.y) + 0x48)))->_animState)). - _animFrame); - } - } - owner->_entityCollisionClass = 4; - owner->_entityGridCollisionClass = 6; - local_2a4.y = local_274.y; - local_1d8 = GHIDRA_CAST(local_274.x); - if ((owner->_variant == 0x13) || (owner->_variant == 0x14)) { - fVar23 = atan2f(local_274.y,local_274.x); - *GHIDRA_CAST((GHIDRA_INT((owner->_bodySprite)._filename._buf) + 0xc)) = fVar23 * 57.295776; - } - else { - *GHIDRA_CAST((owner->_bodySprite)._filename._buf) = -5.0; - } - (owner->_posOffset).x = 0.0; - (owner->_posOffset).y = -14.0; - fVar25 = sqrtf(local_2a4.y * local_2a4.y + (float)local_1d8 * (float)local_1d8); - pEVar27 = local_1d8; - fVar23 = local_2a4.y; - if (0.0 < fVar25) { - pEVar27 = GHIDRA_CAST(((float)local_1d8 * (1.0 / fVar25))); - fVar23 = local_2a4.y * (1.0 / fVar25); - } - fVar25 = (player->_lastVelocity).x * 0.6; - iVar30 = *GHIDRA_CAST(owner); - fVar26 = (player->_lastVelocity).y * 0.6; - (owner->_velocity).x = (float)pEVar27 * 20.0 + fVar25 + fVar25; - (owner->_velocity).y = fVar23 * 20.0 + fVar26 + fVar26; - (**(code **)(iVar30 + 0x40))(); - local_218.y = (float)(GHIDRA_INT(local_218.y) + 1); - (owner->_bodySprite)._filename._size = 0x41700000; - } while (GHIDRA_INT(local_218.y) < GHIDRA_INT(local_1d2)); - } - } - else if ((owner->_type == 1000) && (owner->_variant == 0x76)) { - iVar30 = *GHIDRA_CAST((GHIDRA_CAST(this) + 0x58)); - if (iVar30 == 0) { - local_220.x = ownerPos.x + shotDirection.x * 80.0; - local_220.y = ownerPos.y + shotDirection.y * 80.0; - } - else { - local_220.x = *GHIDRA_CAST((iVar30 + 0x33c)); - local_220.y = *GHIDRA_CAST((iVar30 + 0x340)); - } - bombFlagsHigh = GHIDRA_CAST((GHIDRA_INT(&owner->_flags) + 4)); - *bombFlagsHigh = *bombFlagsHigh & 0xffffffdf; - *GHIDRA_CAST(&owner->_flags) = GHIDRA_INT(owner->_flags); - local_218.y = (float)(local_220.x - ownerPos.x); - local_1d8 = GHIDRA_CAST((local_220.y - ownerPos.y)); - owner->_renderZOffset = 0; - (owner->_posOffset).x = 0.0; - (owner->_posOffset).y = 0.0; - (owner->_bodySprite)._animState._animData = (void *)0x1; - local_1e4.y = 0.0; - if (0 < (*GHIDRA_CAST((GHIDRA_CAST(&((short)local_2f8)) + 0x8)))) { - local_220.x = 1.0; - local_24c.y = (float)((*GHIDRA_CAST((GHIDRA_CAST(&(GHIDRA_INT((short)local_2f8))) + 0x8))) / 2); - local_220.y = 0.0; - do { - FUN_009f4230(local_27c,local_1e4.y,5,local_220.x,local_220.y,shotSpeed); - fVar23 = atan2f(local_274.y,local_274.x); - (*GHIDRA_CAST((GHIDRA_CAST(&(local_1c4)) + 0x0))) = fVar23 * 57.295776 * 0.017453292; - local_2a4.y = cos((*GHIDRA_CAST((GHIDRA_CAST(&((float)local_1c4)) + 0x0)))); - fVar23 = sin((*GHIDRA_CAST((GHIDRA_CAST(&((float)local_1c4)) + 0x0)))); - (*GHIDRA_CAST((GHIDRA_CAST(&(local_1c4)) + 0x0))) = ownerPos.x + (local_218.y * local_2a4.y - (float)local_1d8 * fVar23) - ; - local_2a4.y = ownerPos.y + (float)local_1d8 * local_2a4.y + local_218.y * fVar23; - if (local_1e4.y == local_24c.y) { - pEVar19 = owner; - } - else { - uVar6 = Random(); - pEVar19 = (Entity_Player *) - Game::Spawn(g_game,1000,0x76,&ownerPos,&g_vectorZero, - *GHIDRA_CAST((GHIDRA_CAST(this) + 4)),0,uVar6); - } - local_1e4.y = (float)&(*GHIDRA_CAST((GHIDRA_CAST(((GHIDRA_CAST(local_1e4.y)))) + 0x1))); - (pEVar19->_targetPosition).y = local_2a4.y; - (pEVar19->_bodySprite)._animState._animData = (void *)local_1e4.y; - (pEVar19->_targetPosition).x = (*GHIDRA_CAST((GHIDRA_CAST(&((float)local_1c4)) + 0x0))); - } while (GHIDRA_INT(local_1e4.y) < GHIDRA_INT(local_1d2)); - } - } - *GHIDRA_CAST((*GHIDRA_CAST(local_1f0.y) + 0x171)) = 1; - pfVar18 = GHIDRA_CAST(0x0); - if (*GHIDRA_CAST(local_1f0.y) != 0) { - local_24c.y = local_1f0.y; - msvc::multiset::erase(); - pfVar18 = extraout_ECX_02; - } - *GHIDRA_CAST(local_1f0.y) = 0; - } - } - if (isChocolateMilk != 0) { - pfVar18 = GHIDRA_CAST(local_1c4); - local_24c.y = 1.0; - (*GHIDRA_CAST((GHIDRA_CAST(&(local_1c4)) + 0x0))) = (*GHIDRA_CAST((GHIDRA_CAST(this) + 0x14)) / (float)maxFireDelay - 1.0) + 1.0; - clampedValue = &local_24c.y; - if (1.0 <= (*GHIDRA_CAST((GHIDRA_CAST(&((float)local_1c4)) + 0x0)))) { - clampedValue = pfVar18; - } - damageMultiplier = *clampedValue; - } - if (((*GHIDRA_CAST((GHIDRA_CAST(&(local_250)) + 0x0))) != '\0') && ((float)chargeThreshold <= *GHIDRA_CAST((GHIDRA_CAST(this) + 0x14)))) { - Weapon::UpdateHeadChargeAnimation(this,0xe5,2,&shotDirection,-1.0); - local_220.x = shotDirection.x * 10.0; - local_220.y = shotDirection.y * 10.0; - local_1e4.y = local_220.y; - local_1d8 = GHIDRA_CAST(local_220.x); - pVVar9 = Weapon::get_tear_movement_inheritance(this,&local_274,&local_220); - owner = ownerPlayer; - local_1d8 = GHIDRA_CAST(((float)local_1d8 + pVVar9->x)); - local_1e4.y = local_1e4.y + pVVar9->y; - if ((ownerPlayer == GHIDRA_CAST(0x0)) || - (bVar4 = Entity_Player::HasCollectible(ownerPlayer,0x95,0), bVar4 == 0)) { - local_1f0.y = 1.68156e-44; - if (owner != GHIDRA_CAST(0x0)) goto LAB_009fc57a; - } - else { - uVar6 = Random(); - fVar23 = (float)((double)GHIDRA_INT(uVar6) + __uint_to_double_fixup[-(GHIDRA_INT(uVar6) >> 0x1f)]) * - 2.3283064e-10 * 0.2 + 0.7; - local_1d8 = GHIDRA_CAST(((float)local_1d8 * fVar23)); - local_1e4.y = local_1e4.y * fVar23; -LAB_009fc57a: - local_1f0.y = 1.68156e-44; - bVar4 = Entity_Player::HasCollectible(owner,0x213,0); - if (bVar4 != 0) { - bVar4 = Entity_Player::HasCollectible(owner,0x76,0); - local_1f0.y = (float)(GHIDRA_UINT((bVar4 == 0)) * 2 + 5); - } - } - bVar4 = Entity_Player::HasCollectible(owner,0x34,0); - owner = GHIDRA_CAST(local_1f0.y); - if (bVar4 != 0) { - owner = GHIDRA_CAST(&DAT_00000005); - } - (*GHIDRA_CAST((GHIDRA_CAST(&(local_1c4)) + 0x0))) = lanesPerEye; - local_24c.y = (float)(GHIDRA_INT((&(owner->_sprite)._filename + -3)) + - GHIDRA_INT((((float)GHIDRA_INT(owner) / 5.0) * (float)GHIDRA_INT(local_1d2)))) / - (float)lanesPerEye; - iVar30 = 0x9fc63a; - dVar29 = ceil((double)local_24c.y); - local_218.y = (float)dVar29; - local_2a4.y = 0.0; - pfVar18 = extraout_ECX_03; - if (0 < (*GHIDRA_CAST((GHIDRA_CAST(&(GHIDRA_INT(local_1c4))) + 0x0)))) { - do { - fVar25 = local_2a4.y; - fVar23 = 0.0; - if (1 < (*GHIDRA_CAST((GHIDRA_CAST(&(GHIDRA_INT(local_1c4))) + 0x0)))) { - local_1f0.y = (float)((*GHIDRA_CAST((GHIDRA_CAST(&(local_2f8)) + 0x20))) ^ 0x80000000); - local_24c.y = (*GHIDRA_CAST((GHIDRA_CAST(&((float)GHIDRA_INT(local_1c4))) + 0x0))) - 1.0; - if (local_24c.y == 0.0) { - iVar30 = 0x9fc6b2; - KAGE_LogMessage(0x10,GHIDRA_CAST("Start and End parameters cannot be the same!")); - } - fVar23 = ((float)GHIDRA_INT(fVar25) - 0.0) / (local_24c.y - 0.0); - auVar24 = ZEXT416(GHIDRA_UINT(fVar23)); - if (fVar23 <= 0.0) { - auVar24 = ZEXT816(0); - } - if (1.0 <= (*GHIDRA_CAST((GHIDRA_CAST(&(auVar24)) + 0x0)))) { - (*GHIDRA_CAST((GHIDRA_CAST(&(auVar24)) + 0x0))) = 0x3f800000; - } - fVar23 = ((*GHIDRA_CAST((GHIDRA_CAST(&((float)local_2f8)) + 0x20))) - local_1f0.y) * (*GHIDRA_CAST((GHIDRA_CAST(&(auVar24)) + 0x0))) + local_1f0.y; - } - local_24c.y = fVar23 * 0.017453292; - local_1f0.y = cos(local_24c.y); - fVar23 = sin(local_24c.y); - fVar28 = (float)local_1d8 * local_1f0.y; - fVar26 = local_1e4.y * local_1f0.y; - local_1f0.y = 0.0; - pfVar18 = extraout_ECX_04; - if (0 < GHIDRA_INT(local_218.y)) { - local_264.y = (fVar28 - local_1e4.y * fVar23) * (float)shotSpeed; - local_220.y = (fVar26 + (float)local_1d8 * fVar23) * (float)shotSpeed; - do { - uVar6 = Random(); - fVar23 = (float)((double)GHIDRA_INT(uVar6) + __uint_to_double_fixup[-(GHIDRA_INT(uVar6) >> 0x1f)]) * - 2.3283064e-10 * 3.14; - local_24c.y = fVar23 + fVar23; - local_284 = GHIDRA_CAST(sin(local_24c.y)); - uVar6 = Random(); - local_298 = (Entity_Bomb *) - ((float)((double)GHIDRA_INT(uVar6) + - __uint_to_double_fixup[-(GHIDRA_INT(uVar6) >> 0x1f)]) * 2.3283064e-10); - fVar23 = cos(local_24c.y); - local_274.x = fVar23 * (float)local_298 * 3.5 + local_264.y; - local_274.y = (float)local_298 * (float)local_284 * 3.5 + local_220.y; - pEVar27 = GHIDRA_CAST(Weapon)::fire_tear(this,&ownerPos,&local_274,0,iVar30,1.0,0.0) - ; - local_284 = pEVar27; - if ((pEVar27->_variant == 0x1d) && (uVar6 = Random(), (uVar6 & 3) != 0)) { - pvStack_48 = (void *)0x0; - puStack_44 = &DAT_0000000f; - (*GHIDRA_CAST((GHIDRA_CAST(&(local_6c)) + 0x14))) = (void *)0x0; - (GHIDRA_CAST((local_6c + 0x14)))->msvc::string::assign(GHIDRA_CAST("gfx/tears_brokenbone.png"),0x18); - local_8 = 1.4013e-45; - iVar30 = 0x9fc8f0; - Sprite::ReplaceSpritesheet - (GHIDRA_CAST(&pEVar27->_sprite),0,GHIDRA_CAST((local_6c + 0x14))); - local_8 = -NAN; - bVar4 = extraout_CL; - if (&DAT_0000000f < puStack_44) { - puVar22 = puStack_44 + 1; - pvVar17 = (*GHIDRA_CAST((GHIDRA_CAST(&((void *)local_6c)) + 0x14))); - if (GHIDRA_CAST(0xfff) < puVar22) { - pvVar17 = *(void **)((*GHIDRA_CAST((GHIDRA_CAST(&(local_6c)) + 0x14))) + -4); - puVar22 = puStack_44 + 0x24; - if (0x1f < GHIDRA_UINT(((*GHIDRA_CAST((GHIDRA_CAST(&(local_6c)) + 0x14))) + (-4 - GHIDRA_INT(pvVar17))))) { - /* WARNING: Subroutine does not return */ - _invalid_parameter_noinfo_noreturn(); - } - } - iVar30 = 0x9fc928; - operator_delete(pvVar17,GHIDRA_UINT(puVar22)); - bVar4 = extraout_CL_00; - } - ANM2::LoadGraphics(&pEVar27->_sprite,bVar4); - } - if (ownerPlayer == GHIDRA_CAST(0x0)) { -LAB_009fc98a: - pEVar27->_explosionDamage = ownerPlayer->_tearfallaccel + 0.5; - uVar6 = Random(); - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((pEVar27)) + 0x414)))) = - (ownerPlayer->_tearfallspeed - - (float)((double)GHIDRA_INT(uVar6) + __uint_to_double_fixup[-(GHIDRA_INT(uVar6) >> 0x1f)]) * - 2.3283064e-10 * 15.0) + 5.0; - } - else { - iVar30 = 0x9fc94c; - bVar4 = Entity_Player::HasCollectible(ownerPlayer,0x95,0); - if (bVar4 == 0) { - local_50 = *(uint8_t (*) [4])&(GHIDRA_CAST(&pEVar27->_rocketAngle))->_l; - pvStack_4c = (void *)pEVar27->_rocketSpeed; - pvStack_48 = *(void **)&pEVar27->_collisionCooldown; - puStack_44 = GHIDRA_CAST(pEVar27->_scale); - pBVar8 = BitSet128::operator_and - (GHIDRA_CAST(&fStack_a8),GHIDRA_CAST(local_50), - &g_tearFlagHydrobounce); - if ((GHIDRA_INT(pBVar8->_l) == 0 && *GHIDRA_CAST((GHIDRA_INT(&pBVar8->_l) + 4)) == 0) && - (GHIDRA_INT(pBVar8->_h) == 0 && *GHIDRA_CAST((GHIDRA_INT(&pBVar8->_h) + 4)) == 0)) - goto LAB_009fc98a; - } - } - uVar6 = Random(); - rngResult = Random(); - pEVar27 = local_284; - local_298 = GHIDRA_CAST(0x3c23d70a); - local_284 = (Entity_Bomb *) - ((((float)(uVar6 & 1) + 0.0) * 0.4 + 0.9 + - (float)((double)GHIDRA_INT(rngResult) + - __uint_to_double_fixup[-(GHIDRA_INT(rngResult) >> 0x1f)]) * 2.3283064e-10 - * 0.05) * local_284->_fallAcceleration); - ppEVar11 = &local_284; - if ((float)local_284 <= 0.01) { - ppEVar11 = &local_298; - } - pEVar1 = *ppEVar11; - pEVar27->_bounceCount = GHIDRA_INT(pEVar1); - pEVar27->_fallAcceleration = (float)pEVar1; - Entity_Tear::ResetSpriteScale(GHIDRA_CAST(pEVar27)); - pfVar18 = GHIDRA_CAST(GHIDRA_INT(local_218.y)); - local_1f0.y = (float)(GHIDRA_INT(local_1f0.y) + 1); - } while (GHIDRA_INT(local_1f0.y) < GHIDRA_INT(pfVar18)); - fVar25 = local_2a4.y; - } - local_2a4.y = (float)(GHIDRA_INT(fVar25) + 1); - } while (GHIDRA_INT(local_2a4.y) < (*GHIDRA_CAST((GHIDRA_CAST(&(GHIDRA_INT(local_1c4))) + 0x0)))); - } - } - if (((char)isBrimstone != '\0') && ((float)chargeThreshold <= *GHIDRA_CAST((GHIDRA_CAST(this) + 0x14)))) { - Weapon::UpdateHeadChargeAnimation(this,0x76,2,&shotDirection,-1.0); - local_220.y = atan2f(shotDirection.y,shotDirection.x); - local_220.y = local_220.y * 57.295776; - local_1e4.y = 0.0; - do { - (*GHIDRA_CAST((GHIDRA_CAST(&(local_1c4)) + 0x0))) = *GHIDRA_CAST((GHIDRA_CAST(this) + GHIDRA_INT(local_1e4.y) * 4 + 0x44)); - pEVar27 = GHIDRA_CAST(local_1e4.y); - if (((*GHIDRA_CAST((GHIDRA_CAST(&(GHIDRA_CAST(local_1c4))) + 0x0))) != GHIDRA_CAST(0x0)) && - ((GHIDRA_CAST(local_1e4.y) == GHIDRA_CAST(0x0) || - (((GHIDRA_CAST(local_1e4.y) == GHIDRA_CAST(0x1) && ((*GHIDRA_CAST((GHIDRA_CAST(&(uStack_2d4)) + 0x1))) != '\0')) || - ((*GHIDRA_CAST((GHIDRA_CAST(&(uStack_2d4)) + 0x2))) != '\0')))))) { - pcVar2 = *(code **)(*(*GHIDRA_CAST((GHIDRA_CAST(&(GHIDRA_CAST(local_1c4))) + 0x0))) + 0x3c); - if (ownerPlayer == GHIDRA_CAST(0x0)) { - (GHIDRA_CAST((&flashColor)))->Color::Reset(); - flashColor._tint[0] = 1.0; - flashColor._tint[1] = 0.0; - flashColor._tint[2] = 0.0; - flashColor._tint[3] = 1.0; - flashColor._offset[0] = 0.0; - flashColor._offset[1] = 0.0; - flashColor._offset[2] = 0.0; - } - else { - (GHIDRA_CAST((GHIDRA_CAST(local_6c))))->Color::Reset(); - (*GHIDRA_CAST((GHIDRA_CAST(&(local_6c)) + 0x0))) = 1.0; - (*GHIDRA_CAST((GHIDRA_CAST(&(local_6c)) + 0x4))) = 0.0; - (*GHIDRA_CAST((GHIDRA_CAST(&(local_6c)) + 0x8))) = 0.0; - (*GHIDRA_CAST((GHIDRA_CAST(&(local_6c)) + 0xc))) = 1.0; - pvStack_4c = (void *)0x0; - (*GHIDRA_CAST((GHIDRA_CAST(&(local_c4)) + 0x0))) = (ownerPlayer->_laserColor)._tint[0]; - (*GHIDRA_CAST((GHIDRA_CAST(&(local_c4)) + 0x4))) = (ownerPlayer->_laserColor)._tint[1]; - (*GHIDRA_CAST((GHIDRA_CAST(&(local_c4)) + 0x8))) = (ownerPlayer->_laserColor)._tint[2]; - (*GHIDRA_CAST((GHIDRA_CAST(&(local_c4)) + 0xc))) = (ownerPlayer->_laserColor)._tint[3]; - pvStack_48 = (void *)0x0; - puStack_44 = GHIDRA_CAST(0x0); - (*GHIDRA_CAST((GHIDRA_CAST(&(local_c4)) + 0x10))) = (ownerPlayer->_laserColor)._colorize[0]; - (*GHIDRA_CAST((GHIDRA_CAST(&(local_c4)) + 0x14))) = (ownerPlayer->_laserColor)._colorize[1]; - fStack_ac = (ownerPlayer->_laserColor)._colorize[2]; - fStack_a8 = (ownerPlayer->_laserColor)._colorize[3]; - local_a4.x = (ownerPlayer->_laserColor)._offset[0]; - local_a4.y = (ownerPlayer->_laserColor)._offset[1]; - local_9c = GHIDRA_CAST((ownerPlayer->_laserColor)._offset[2]); - (GHIDRA_CAST((GHIDRA_CAST(local_c4))))->Color::__mul(GHIDRA_CAST(local_6c)); - puStack_70 = local_9c; - (*GHIDRA_CAST((GHIDRA_CAST(&(chargeColor)) + 0x0))) = (*GHIDRA_CAST((GHIDRA_CAST(&(local_c4)) + 0x0))); - (*GHIDRA_CAST((GHIDRA_CAST(&(chargeColor)) + 0x4))) = (*GHIDRA_CAST((GHIDRA_CAST(&(local_c4)) + 0x4))); - (*GHIDRA_CAST((GHIDRA_CAST(&(chargeColor)) + 0x8))) = (*GHIDRA_CAST((GHIDRA_CAST(&(local_c4)) + 0x8))); - (*GHIDRA_CAST((GHIDRA_CAST(&(chargeColor)) + 0xc))) = (*GHIDRA_CAST((GHIDRA_CAST(&(local_c4)) + 0xc))); - (*GHIDRA_CAST((GHIDRA_CAST(&(chargeColor)) + 0x10))) = (*GHIDRA_CAST((GHIDRA_CAST(&(local_c4)) + 0x10))); - (*GHIDRA_CAST((GHIDRA_CAST(&(chargeColor)) + 0x14))) = (*GHIDRA_CAST((GHIDRA_CAST(&(local_c4)) + 0x14))); - (*GHIDRA_CAST((GHIDRA_CAST(&(chargeColor)) + 0x18))) = fStack_ac; - (*GHIDRA_CAST((GHIDRA_CAST(&(chargeColor)) + 0x1c))) = fStack_a8; - (*GHIDRA_CAST((GHIDRA_CAST(&(chargeColor)) + 0x20))) = local_a4; - } - rngResult = 1; - uVar6 = 1; - (*pcVar2)(); - pEVar27 = GHIDRA_CAST(local_1e4.y); - if (GHIDRA_CAST(local_1e4.y) == GHIDRA_CAST(0x0)) { - if (0 < local_1d2) { - local_29c = 0x3f800000; - local_298 = GHIDRA_CAST(local_1e4.y); - iVar30 = 0; - do { - fVar23 = fStack_2c4; - fVar25 = fStack_2c0; - FUN_009f4230(local_2ac,iVar30,10,local_29c,local_298,shotSpeed); - fVar26 = atan2f(local_2a4.y,local_2a4.x); - local_264.y = (fVar26 * 57.295776 + local_220.y) * 0.017453292; - local_284 = GHIDRA_CAST(sin(local_264.y)); - pEVar31 = GHIDRA_CAST(0x9fcd6b); - fVar26 = cos(local_264.y); - local_274.y = (float)local_284 * 6.0; - local_274.x = fVar26 * 6.0; - local_24c.x = ownerPos.x + fVar26 * 30.0; - local_24c.y = ownerPos.y + (float)local_284 * 30.0; - Weapon::fire_brimstone_ball - (this,&local_24c,&local_274,GHIDRA_CAST((*GHIDRA_CAST((GHIDRA_CAST(this) + 0x44)) + 0x34c)) - ,GHIDRA_UINT(fVar23),GHIDRA_UINT(fVar25),pEVar31); - iVar30 = iVar30 + 1; - } while (iVar30 < local_1d2); - } - pEVar27 = GHIDRA_CAST(local_1e4.y); - } - else { - fVar23 = atan2f(shotDirection.y,shotDirection.x); - fVar23 = fVar23 * 57.295776 + (float)(&DAT_00b81710)[GHIDRA_INT(pEVar27)]; - if (360.0 < ABS(fVar23)) { - fVar23 = fmodf(fVar23,360.0); - } - if (fVar23 <= 180.0) { - if (fVar23 < -180.0) { - fVar23 = fVar23 + 360.0; - } - } - else { - fVar23 = fVar23 - 360.0; - } - local_264.y = fVar23 * 0.017453292; - local_284 = GHIDRA_CAST(sin(local_264.y)); - pEVar31 = GHIDRA_CAST(0x9fd007); - fVar23 = cos(local_264.y); - local_1f0.y = (float)local_284 * 6.0; - local_1f0.x = fVar23 * 6.0; - local_218.x = ownerPos.x + fVar23 * 30.0; - local_218.y = ownerPos.y + (float)local_284 * 30.0; - Weapon::fire_brimstone_ball - (this,&local_218,&local_1f0, - GHIDRA_CAST((*GHIDRA_CAST((GHIDRA_CAST(this) + GHIDRA_INT(pEVar27) * 4 + 0x44)) + 0x34c)),uVar6, - rngResult,pEVar31); - } - } - pMVar3 = g_manager; - local_1e4.y = (float)&(*GHIDRA_CAST((GHIDRA_CAST((pEVar27)) + 0x1))); - } while (GHIDRA_UINT(local_1e4.y) < &DAT_00000004); - (*GHIDRA_CAST((GHIDRA_CAST(&(local_1c4)) + 0x0))) = GHIDRA_CAST(0x7); - seed_fart_sound_override(GHIDRA_CAST(local_1c4)); - (GHIDRA_CAST((&pMVar3->_sfxManager)))->SoundEffects::Play((*GHIDRA_CAST((GHIDRA_CAST(&(local_1c4)) + 0x0))),0.5,2,0,1.0,0.0); - Weapon::SetBlinkTime(this,0x24,unused); - pfVar18 = extraout_ECX_05; - } - if (((char)isCSection != '\0') && ((float)chargeThreshold <= *GHIDRA_CAST((GHIDRA_CAST(this) + 0x14)))) { - Weapon::update_c_section_charge_anim(this,GHIDRA_INT(pfVar18),2,aimDirection,-1.0); - fVar23 = atan2f(shotDirection.y,shotDirection.x); - local_284 = GHIDRA_CAST((fVar23 * 57.295776)); - local_1f0.y = 0.0; - do { - fVar23 = local_1f0.y; - if (*GHIDRA_CAST((GHIDRA_CAST(this) + GHIDRA_INT(local_1f0.y) * 4 + 0x44)) != 0) { - if (local_1f0.y == 0.0) { - (*GHIDRA_CAST((GHIDRA_CAST(&(local_1c4)) + 0x0))) = GHIDRA_CAST(0x0); - if (0 < local_1d2) { - local_24c.x = 1.0; - local_24c.y = 0.0; - local_298 = GHIDRA_CAST(0x3c23d70a); - do { - FUN_009f4230(local_50,(*GHIDRA_CAST((GHIDRA_CAST(&(local_1c4)) + 0x0))),10,local_24c.x,local_24c.y,shotSpeed); - fVar23 = atan2f((float)puStack_44,(float)pvStack_48); - local_220.y = (fVar23 * 57.295776 + (float)local_284) * 0.017453292; - local_264.y = sin(local_220.y); - iVar30 = 0x9fd2a2; - fVar23 = cos(local_220.y); - local_2a4.y = local_264.y * 10.0; - local_2a4.x = fVar23 * 10.0; - local_1e4.x = ownerPos.x + fVar23 * 4.0; - local_1e4.y = ownerPos.y + local_264.y * 4.0; - fetusTear = fire_fetus_tear(this,&local_1e4,&local_2a4,0,*GHIDRA_CAST((GHIDRA_CAST(this) + 4)) - ,1.0,iVar30); - local_220.y = fetusTear->_fScale * 1.2; - pfVar18 = &local_220.y; - if (local_220.y <= 0.01) { - pfVar18 = GHIDRA_CAST(&local_298); - } - fVar23 = *pfVar18; - fetusTear->_baseScale = fVar23; - fetusTear->_fScale = fVar23; - Entity_Tear::ResetSpriteScale(fetusTear); - fetusTear->_tearRange = fetusTear->_tearRange + fetusTear->_tearRange; - (**(code **)(*GHIDRA_CAST(fetusTear) + 0xc))(); - (*GHIDRA_CAST((GHIDRA_CAST(&(local_1c4)) + 0x0))) = (*GHIDRA_CAST((GHIDRA_CAST(&(local_1c4)) + 0x0))) + 1; - } while ((*GHIDRA_CAST((GHIDRA_CAST(&(GHIDRA_INT(local_1c4))) + 0x0))) < GHIDRA_INT(local_1d2)); - } - } - else if (((local_1f0.y == 1.4013e-45) && ((*GHIDRA_CAST((GHIDRA_CAST(&(uStack_2d4)) + 0x1))) != '\0')) || - ((*GHIDRA_CAST((GHIDRA_CAST(&(uStack_2d4)) + 0x2))) != '\0')) { - fVar25 = atan2f(shotDirection.y,shotDirection.x); - fVar23 = fVar25 * 57.295776 + (float)(&DAT_00b81710)[GHIDRA_INT(fVar23)]; - if (360.0 < ABS(fVar23)) { - fVar23 = fmodf(fVar23,360.0); - } - if (fVar23 <= 180.0) { - if (fVar23 < -180.0) { - fVar23 = fVar23 + 360.0; - } - } - else { - fVar23 = fVar23 - 360.0; - } - local_220.y = fVar23 * 0.017453292; - local_264.y = sin(local_220.y); - iVar30 = 0x9fd0d2; - fVar23 = cos(local_220.y); - local_274.y = local_264.y * 10.0; - local_274.x = fVar23 * 10.0; - local_218.x = ownerPos.x + fVar23 * 4.0; - local_218.y = ownerPos.y + local_264.y * 4.0; - fetusTear = fire_fetus_tear(this,&local_218,&local_274,0,*GHIDRA_CAST((GHIDRA_CAST(this) + 4)),1.0 - ,iVar30); - local_264.y = 0.01; - local_220.y = fetusTear->_fScale * 1.2; - pVVar9 = &local_220; - if (local_220.y <= 0.01) { - pVVar9 = &local_264; - } - fVar23 = pVVar9->y; - fetusTear->_baseScale = fVar23; - fetusTear->_fScale = fVar23; - Entity_Tear::ResetSpriteScale(fetusTear); - fetusTear->_tearRange = fetusTear->_tearRange + fetusTear->_tearRange; - (**(code **)(*GHIDRA_CAST(fetusTear) + 0xc))(); - } - } - local_1f0.y = (float)(GHIDRA_INT(local_1f0.y) + 1); - } while (GHIDRA_UINT(local_1f0.y) < &DAT_00000004); - } - if ((char)isCursedEye == '\0') { - local_1e4.y = 1.4013e-45; - } - else { - local_1e4.y = *GHIDRA_CAST((GHIDRA_CAST(this) + 0x5c)); - } - fVar23 = 0.0; - EntityList::QuerySublist - (GHIDRA_CAST((GHIDRA_INT(g_game->_room) + 0x1218)),GHIDRA_CAST(local_27c),8,1,-1,0,0); - rngResult = (*GHIDRA_CAST((GHIDRA_CAST(&(local_27c)) + 0x4))); - local_8 = 2.8026e-45; - fVar25 = 0.0; - if (local_274.y != 0.0) { - fVar26 = local_274.y; - club = heldClub; - do { - piVar15 = *GHIDRA_CAST((rngResult + GHIDRA_INT(fVar25) * 4)); - if (GHIDRA_CAST(piVar15[0xef]) == club) { - (**(code **)(*piVar15 + 0x28))(); - fVar26 = local_274.y; - club = heldClub; - } - fVar25 = (float)(GHIDRA_INT(fVar25) + 1); - } while (GHIDRA_UINT(fVar25) < GHIDRA_UINT(fVar26)); - this = (void *)ownerVelocityX.y; - } - local_1d8 = GHIDRA_CAST(0x0); - (*GHIDRA_CAST((GHIDRA_CAST(&(local_1c4)) + 0x0))) = GHIDRA_CAST(0x0); - do { - owner = (*GHIDRA_CAST((GHIDRA_CAST(&(GHIDRA_CAST(local_1c4))) + 0x0))); - if ((*GHIDRA_CAST((&(*GHIDRA_CAST((GHIDRA_CAST(((GHIDRA_CAST(this)))) + 0x44))) + (*GHIDRA_CAST((GHIDRA_CAST(&(local_1c4)) + 0x0))) * 4)) != 0) && - (((*GHIDRA_CAST((GHIDRA_CAST(&(GHIDRA_CAST(local_1c4))) + 0x0))) == GHIDRA_CAST(0x0) || - ((((*GHIDRA_CAST((GHIDRA_CAST(&(GHIDRA_CAST(local_1c4))) + 0x0))) == GHIDRA_CAST(0x1) && ((*GHIDRA_CAST((GHIDRA_CAST(&(uStack_2d4)) + 0x1))) != '\0')) - || ((*GHIDRA_CAST((GHIDRA_CAST(&(uStack_2d4)) + 0x2))) != '\0')))))) { - (*GHIDRA_CAST((GHIDRA_CAST(&(local_1c4)) + 0x4))) = 0.0; - tearBombVariant = 0; - (GHIDRA_CAST((&tearColor)))->Color::Color(); - tearFlags._l = 0; - tearFlags._h = 0; - tearDamage = GHIDRA_CAST(0x40600000); - tearScale = 1.0; - tearHeight = -23.75; - uStack_16c = 0x3f800000; - local_168 = 0x3fd9999a; - local_164 = 1.0; - local_160 = 0.0; - piVar15 = extraout_EDX; - if (ownerPlayer != GHIDRA_CAST(0x0)) { - pEVar31 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(((GHIDRA_CAST(this)))) + 0x4)))); - uVar6 = Random(); - pTVar7 = Entity_Player::GetTearHitParams - (ownerPlayer,&local_158,10,1.0,(uVar6 & 1) * 2 + -1,pEVar31); - (*GHIDRA_CAST((GHIDRA_CAST(&(local_1c4)) + 0x4))) = pTVar7->_tearVariant; - tearBombVariant = pTVar7->_bombVariant; - if (&tearColor != GHIDRA_CAST(&pTVar7->_tearColor)) { - tearColor._tint[0] = (pTVar7->_tearColor)._tint[0]; - tearColor._tint[1] = (pTVar7->_tearColor)._tint[1]; - tearColor._tint[2] = (pTVar7->_tearColor)._tint[2]; - tearColor._tint[3] = (pTVar7->_tearColor)._tint[3]; - tearColor._colorize[0] = (pTVar7->_tearColor)._colorize[0]; - tearColor._colorize[1] = (pTVar7->_tearColor)._colorize[1]; - tearColor._colorize[2] = (pTVar7->_tearColor)._colorize[2]; - tearColor._colorize[3] = (pTVar7->_tearColor)._colorize[3]; - (*GHIDRA_CAST((GHIDRA_CAST(&(tearColor._offset)) + 0x0))) = *GHIDRA_CAST((pTVar7->_tearColor)._offset); - tearColor._offset[2] = (pTVar7->_tearColor)._offset[2]; - } - tearFlags._l = (pTVar7->_flags)._l; - tearFlags._h = (pTVar7->_flags)._h; - tearDamage = GHIDRA_CAST(pTVar7->_tearDamage); - tearScale = pTVar7->_tearScale; - tearHeight = pTVar7->_tearHeight; - uStack_16c = pTVar7[1]._tearVariant; - local_168 = pTVar7[1]._bombVariant; - local_164 = pTVar7[1]._tearColor._tint[0]; - piVar15 = *GHIDRA_CAST((&(*GHIDRA_CAST((GHIDRA_CAST(((GHIDRA_CAST(this)))) + 0x44))) + (*GHIDRA_CAST((GHIDRA_CAST(&(local_1c4)) + 0x0))) * 4)); - local_160 = pTVar7[1]._tearColor._tint[1]; - owner = (*GHIDRA_CAST((GHIDRA_CAST(&(GHIDRA_CAST(local_1c4))) + 0x0))); - } - fVar23 = 0.0; - ownerVelocityX.y = damageMultiplier * (float)tearDamage; - pfVar18 = &ownerVelocityX.y; - if ((float)(damageMultiplier * (float)tearDamage) <= (float)local_1d8) { - pfVar18 = GHIDRA_CAST(&local_1d8); - } - local_1d8 = GHIDRA_CAST(*pfVar18); - (**(code **)(*piVar15 + 0x3c))(); - iVar30 = *GHIDRA_CAST((&(*GHIDRA_CAST((GHIDRA_CAST(((GHIDRA_CAST(this)))) + 0x44))) + GHIDRA_INT(owner) * 4)); - *GHIDRA_CAST((iVar30 + 0x410)) = (uint32_t)tearFlags._l; - *GHIDRA_CAST((iVar30 + 0x414)) = (*GHIDRA_CAST((GHIDRA_CAST(&(tearFlags._l)) + 0x4))); - *GHIDRA_CAST((iVar30 + 0x418)) = (uint32_t)tearFlags._h; - *GHIDRA_CAST((iVar30 + 0x41c)) = (*GHIDRA_CAST((GHIDRA_CAST(&(tearFlags._h)) + 0x4))); - (**(code **)(**GHIDRA_CAST((&(*GHIDRA_CAST((GHIDRA_CAST(((GHIDRA_CAST(this)))) + 0x44))) + GHIDRA_INT(owner) * 4)) + 0x40))(); - fVar25 = atan2f(shotDirection.y,shotDirection.x); - fVar25 = fVar25 * 57.295776 + (float)(&DAT_00b81710)[GHIDRA_INT(owner)]; - if (360.0 < ABS(fVar25)) { - fVar25 = fmodf(fVar25,360.0); - } - if (fVar25 <= 180.0) { - if (fVar25 < -180.0) { - fVar25 = fVar25 + 360.0; - } - } - else { - fVar25 = fVar25 - 360.0; - } - *GHIDRA_CAST((*GHIDRA_CAST((&(*GHIDRA_CAST((GHIDRA_CAST(((GHIDRA_CAST(this)))) + 0x44))) + GHIDRA_INT(owner) * 4)) + 0x438)) = fVar25 - ; - iVar30 = *GHIDRA_CAST((&(*GHIDRA_CAST((GHIDRA_CAST(((GHIDRA_CAST(this)))) + 0x44))) + GHIDRA_INT(owner) * 4)); - *GHIDRA_CAST((iVar30 + 0x4ec)) = SUB42(local_1e4.y,0); - *GHIDRA_CAST((iVar30 + 0x4ee)) = 0; - Entity_Knife::SetAttackAnimation - (*GHIDRA_CAST((&(*GHIDRA_CAST((GHIDRA_CAST(((GHIDRA_CAST(this)))) + 0x44))) + GHIDRA_INT(owner) * 4))); - *GHIDRA_CAST((*GHIDRA_CAST((&(*GHIDRA_CAST((GHIDRA_CAST(((GHIDRA_CAST(this)))) + 0x44))) + GHIDRA_INT(owner) * 4)) + 0x466)) = - isChargeMode == '\0'; - } - (*GHIDRA_CAST((GHIDRA_CAST(&(local_1c4)) + 0x0))) = &(*GHIDRA_CAST((GHIDRA_CAST((owner)) + 0x1))); - } while ((*GHIDRA_CAST((GHIDRA_CAST(&(GHIDRA_UINT(local_1c4))) + 0x0))) < GHIDRA_CAST(0x4)); - (*GHIDRA_CAST((GHIDRA_CAST(&(local_1c4)) + 0x0))) = GHIDRA_CAST(0x0); - if (0 < local_1d2) { - local_288 = 0x3f800000; - ownerVelocityX.y = (float)(GHIDRA_INT(local_1d2) / 2); - local_284 = GHIDRA_CAST(0x0); - do { - rngResult = (*GHIDRA_CAST((GHIDRA_CAST(&(local_1c4)) + 0x0))); - fVar23 = fStack_2c0; - FUN_009f4230(local_50,(*GHIDRA_CAST((GHIDRA_CAST(&(local_1c4)) + 0x0))),10,local_288,local_284,shotSpeed); - fVar25 = atan2f((float)puStack_44,(float)pvStack_48); - fVar25 = fVar25 * 57.295776; - local_264.y = fVar25; - if ((float)rngResult == ownerVelocityX.y) { - if (360.0 < ABS(fVar25)) { - fVar25 = fmodf(fVar25,360.0); - } - (*GHIDRA_CAST((GHIDRA_CAST(&(local_1c4)) + 0x0))) = rngResult; - if (fVar25 <= 180.0) { - if (fVar25 < -180.0) { - fVar25 = fVar25 + 360.0; - } - heldClub->_rotationOffset = fVar25; - } - else { - heldClub->_rotationOffset = fVar25 - 360.0; - } - } - else { - (*GHIDRA_CAST((GHIDRA_CAST(&(local_1c4)) + 0x4))) = 0.0; - tearBombVariant = 0; - pEVar31 = GHIDRA_CAST(0x9fd86a); - (GHIDRA_CAST((&tearColor)))->Color::Color(); - tearFlags._l = 0; - tearFlags._h = 0; - tearDamage = GHIDRA_CAST(0x40600000); - tearScale = 1.0; - tearHeight = -23.75; - uStack_16c = 0x3f800000; - local_168 = 0x3fd9999a; - local_164 = 1.0; - local_160 = 0.0; - if (ownerPlayer != GHIDRA_CAST(0x0)) { - pEVar31 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(((GHIDRA_CAST(this)))) + 0x4)))); - uVar6 = Random(); - fVar23 = (float)((uVar6 & 1) * 2 - 1); - pTVar7 = Entity_Player::GetTearHitParams - (ownerPlayer,&local_158,10,1.0,GHIDRA_INT(fVar23),pEVar31); - (*GHIDRA_CAST((GHIDRA_CAST(&(local_1c4)) + 0x4))) = pTVar7->_tearVariant; - tearBombVariant = pTVar7->_bombVariant; - if (&tearColor != GHIDRA_CAST(&pTVar7->_tearColor)) { - tearColor._tint[0] = (pTVar7->_tearColor)._tint[0]; - tearColor._tint[1] = (pTVar7->_tearColor)._tint[1]; - tearColor._tint[2] = (pTVar7->_tearColor)._tint[2]; - tearColor._tint[3] = (pTVar7->_tearColor)._tint[3]; - tearColor._colorize[0] = (pTVar7->_tearColor)._colorize[0]; - tearColor._colorize[1] = (pTVar7->_tearColor)._colorize[1]; - tearColor._colorize[2] = (pTVar7->_tearColor)._colorize[2]; - tearColor._colorize[3] = (pTVar7->_tearColor)._colorize[3]; - (*GHIDRA_CAST((GHIDRA_CAST(&(tearColor._offset)) + 0x0))) = *GHIDRA_CAST((pTVar7->_tearColor)._offset); - tearColor._offset[2] = (pTVar7->_tearColor)._offset[2]; - } - tearFlags._l = (pTVar7->_flags)._l; - tearFlags._h = (pTVar7->_flags)._h; - tearDamage = GHIDRA_CAST(pTVar7->_tearDamage); - tearScale = pTVar7->_tearScale; - tearHeight = pTVar7->_tearHeight; - uStack_16c = pTVar7[1]._tearVariant; - local_168 = pTVar7[1]._bombVariant; - local_164 = pTVar7[1]._tearColor._tint[0]; - local_160 = pTVar7[1]._tearColor._tint[1]; - } - local_220.y = damageMultiplier * (float)tearDamage; - pfVar18 = &local_220.y; - if (damageMultiplier * (float)tearDamage <= (float)local_1d8) { - pfVar18 = GHIDRA_CAST(&local_1d8); - } - local_1d8 = GHIDRA_CAST(*pfVar18); - club = Weapon::fire_bone_club - (this,GHIDRA_CAST(heldClub),GHIDRA_UINT(local_200),0,GHIDRA_INT(fVar23),GHIDRA_INT(pEVar31), - local_264.y); - fVar23 = 0.0; - (**(code **)(*GHIDRA_CAST(club) + 0x3c))(); - iVar30 = *GHIDRA_CAST(club); - *GHIDRA_CAST(&(club->_tearFlags)._l) = (uint32_t)tearFlags._l; - *GHIDRA_CAST((GHIDRA_INT(&(club->_tearFlags)._l) + 4)) = (*GHIDRA_CAST((GHIDRA_CAST(&(tearFlags._l)) + 0x4))); - *GHIDRA_CAST(&(club->_tearFlags)._h) = (uint32_t)tearFlags._h; - *GHIDRA_CAST((GHIDRA_INT(&(club->_tearFlags)._h) + 4)) = (*GHIDRA_CAST((GHIDRA_CAST(&(tearFlags._h)) + 0x4))); - (**(code **)(iVar30 + 0x40))(); - (club->_sprite)._scale.x = (heldClub->_sprite)._scale.x; - (club->_sprite)._scale.y = (heldClub->_sprite)._scale.y; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((club)) + 0x4ec)))) = SUB42(local_1e4.y,0); - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((club)) + 0x4ee)))) = 0; - Entity_Knife::SetAttackAnimation(club); - (**(code **)(*GHIDRA_CAST(club) + 0xc))(); - } - (*GHIDRA_CAST((GHIDRA_CAST(&(local_1c4)) + 0x0))) = &((*GHIDRA_CAST((GHIDRA_CAST(&(GHIDRA_CAST(local_1c4))) + 0x0)))(*GHIDRA_CAST((GHIDRA_CAST(()))) + 0x1)); - } while ((*GHIDRA_CAST((GHIDRA_CAST(&(GHIDRA_INT(local_1c4))) + 0x0))) < GHIDRA_INT(local_1d2)); - } - for ((*GHIDRA_CAST((GHIDRA_CAST(&(local_1c4)) + 0x0))) = GHIDRA_UINT(local_208) & 0xffff; - (*GHIDRA_CAST((GHIDRA_CAST(&(GHIDRA_CAST(local_1c4))) + 0x0))) != GHIDRA_CAST(0x0); - (*GHIDRA_CAST((GHIDRA_CAST(&(local_1c4)) + 0x0))) = &(GHIDRA_CAST(((*GHIDRA_CAST((GHIDRA_CAST(&(local_1c4)) + 0x0)))(*GHIDRA_CAST((GHIDRA_CAST(( + -0x2f00))))) + 0x2eff)))) { - (*GHIDRA_CAST((GHIDRA_CAST(&(local_1c4)) + 0x4))) = 0.0; - tearBombVariant = 0; - (GHIDRA_CAST((&tearColor)))->Color::Color(); - tearFlags._l = 0; - tearFlags._h = 0; - tearDamage = GHIDRA_CAST(0x40600000); - tearScale = 1.0; - tearHeight = -23.75; - uStack_16c = 0x3f800000; - local_168 = 0x3fd9999a; - local_164 = 1.0; - local_160 = 0.0; - if (ownerPlayer != GHIDRA_CAST(0x0)) { - pEVar31 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(((GHIDRA_CAST(this)))) + 0x4)))); - uVar6 = Random(); - fVar23 = (float)((uVar6 & 1) * 2 - 1); - pTVar7 = Entity_Player::GetTearHitParams(ownerPlayer,&local_158,10,1.0,GHIDRA_INT(fVar23),pEVar31); - (*GHIDRA_CAST((GHIDRA_CAST(&(local_1c4)) + 0x4))) = pTVar7->_tearVariant; - tearBombVariant = pTVar7->_bombVariant; - if (&tearColor != GHIDRA_CAST(&pTVar7->_tearColor)) { - tearColor._tint[0] = (pTVar7->_tearColor)._tint[0]; - tearColor._tint[1] = (pTVar7->_tearColor)._tint[1]; - tearColor._tint[2] = (pTVar7->_tearColor)._tint[2]; - tearColor._tint[3] = (pTVar7->_tearColor)._tint[3]; - tearColor._colorize[0] = (pTVar7->_tearColor)._colorize[0]; - tearColor._colorize[1] = (pTVar7->_tearColor)._colorize[1]; - tearColor._colorize[2] = (pTVar7->_tearColor)._colorize[2]; - tearColor._colorize[3] = (pTVar7->_tearColor)._colorize[3]; - (*GHIDRA_CAST((GHIDRA_CAST(&(tearColor._offset)) + 0x0))) = *GHIDRA_CAST((pTVar7->_tearColor)._offset); - tearColor._offset[2] = (pTVar7->_tearColor)._offset[2]; - } - tearFlags._l = (pTVar7->_flags)._l; - tearFlags._h = (pTVar7->_flags)._h; - tearDamage = GHIDRA_CAST(pTVar7->_tearDamage); - tearScale = pTVar7->_tearScale; - tearHeight = pTVar7->_tearHeight; - uStack_16c = pTVar7[1]._tearVariant; - local_168 = pTVar7[1]._bombVariant; - local_164 = pTVar7[1]._tearColor._tint[0]; - local_160 = pTVar7[1]._tearColor._tint[1]; - } - ownerVelocityX.y = damageMultiplier * (float)tearDamage; - pfVar18 = &ownerVelocityX.y; - if ((float)(damageMultiplier * (float)tearDamage) <= (float)local_1d8) { - pfVar18 = GHIDRA_CAST(&local_1d8); - } - local_1d8 = GHIDRA_CAST(*pfVar18); - iVar30 = 0x9fdc3d; - uVar6 = Random(); - club = Weapon::fire_bone_club - (this,GHIDRA_CAST(heldClub),GHIDRA_UINT(local_200),0,GHIDRA_INT(fVar23),iVar30, - (float)((double)GHIDRA_INT(uVar6) + __uint_to_double_fixup[-(GHIDRA_INT(uVar6) >> 0x1f)]) - * 2.3283064e-10 * 360.0); - fVar23 = 0.0; - (**(code **)(*GHIDRA_CAST(club) + 0x3c))(); - iVar30 = *GHIDRA_CAST(club); - *GHIDRA_CAST(&(club->_tearFlags)._l) = (uint32_t)tearFlags._l; - *GHIDRA_CAST((GHIDRA_INT(&(club->_tearFlags)._l) + 4)) = (*GHIDRA_CAST((GHIDRA_CAST(&(tearFlags._l)) + 0x4))); - *GHIDRA_CAST(&(club->_tearFlags)._h) = (uint32_t)tearFlags._h; - *GHIDRA_CAST((GHIDRA_INT(&(club->_tearFlags)._h) + 4)) = (*GHIDRA_CAST((GHIDRA_CAST(&(tearFlags._h)) + 0x4))); - (**(code **)(iVar30 + 0x40))(); - (club->_sprite)._scale.x = (heldClub->_sprite)._scale.x; - (club->_sprite)._scale.y = (heldClub->_sprite)._scale.y; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((club)) + 0x4ec)))) = SUB42(local_1e4.y,0); - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((club)) + 0x4ee)))) = 0; - Entity_Knife::SetAttackAnimation(club); - (**(code **)(*GHIDRA_CAST(club) + 0xc))(); - } - uVar6 = Random(); - pMVar3 = g_manager; - (*GHIDRA_CAST((GHIDRA_CAST(&(local_1c4)) + 0x0))) = GHIDRA_CAST(0xfc); - local_238.y = ((float)((double)GHIDRA_INT(uVar6) + __uint_to_double_fixup[-(GHIDRA_INT(uVar6) >> 0x1f)]) * - 2.3283064e-10 * 0.2 + 0.9) * local_238.y; - seed_fart_sound_override(GHIDRA_CAST(local_1c4)); - (GHIDRA_CAST((&pMVar3->_sfxManager)))->SoundEffects::Play((*GHIDRA_CAST((GHIDRA_CAST(&(local_1c4)) + 0x0))),1.0,1,0,local_238.y,0.0); - if ((20.0 < (float)local_1d8) && (1.5 < (float)clubScale)) { - Game::ShakeScreen(g_game,GHIDRA_INT(((float)clubScale * 5.0))); - } - if (isChargeMode == '\0') { - owner = GHIDRA_CAST(0x3f800000); - if (isReleased == '\0') goto LAB_009fde0f; - if ((GHIDRA_CAST(this))->_pendingDamage <= 1.0 && - (GHIDRA_CAST(this))->_pendingDamage != 1.0) { - (GHIDRA_CAST(this))->_pendingDamage = 1.0; - } - } - else { - owner = GHIDRA_CAST(0x0); -LAB_009fde0f: - newCharge = owner; - } - *GHIDRA_CAST((&(*GHIDRA_CAST((GHIDRA_CAST(((GHIDRA_CAST(this)))) + 0x44))) + 0x18)) = 0; - (GHIDRA_CAST(this))->_index = GHIDRA_INT(g_vectorZero.x); - (GHIDRA_CAST(this))->_collisionIndex = GHIDRA_INT(g_vectorZero.y); - if ((char)isCursedEye != '\0') { - owner = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(((GHIDRA_CAST(this)))) + 0x4)))); - if (((owner == GHIDRA_CAST(0x0)) || (pEVar19 = owner, owner->_type != 1)) && - ((pEVar19 = GHIDRA_CAST(0x0), owner != GHIDRA_CAST(0x0) && (owner->_type == 3)))) { - owner->_chargeBarSprites[5]._numEvents = 0; - } - else if (pEVar19 != GHIDRA_CAST(0x0)) { - Entity_Player::stop_costume_item_anims(pEVar19); - } - } - pEVar19 = player; - if (player != GHIDRA_CAST(0x0)) { - Entity_Player::TryForgottenThrow(player,&shotDirection); - } - if (local_27c[0] == '\0') { - local_8 = 4.2039e-45; - tracked_alloc(1,(*GHIDRA_CAST((GHIDRA_CAST(&((void *)local_27c)) + 0x4))),0); - } - local_8 = -NAN; - iVar30 = GHIDRA_UINT(local_1c6) << 8; - pfVar18 = &(GHIDRA_CAST(this))->_pendingDamage; -LAB_009fdeca: - owner = newCharge; - if ((char)(GHIDRA_UINT(iVar30) >> 8) == '\0') goto LAB_009fb9ec; - } - owner = newCharge; - if (weaponType == 0xb) goto LAB_009fb9ec; - if (((heldClub->_isSwinging != 0) && (isReleased == '\0')) || (*pfVar18 < 1.0)) { - club = heldClub; - goto LAB_009fb9f2; - } - (GHIDRA_CAST((GHIDRA_CAST(clubFlashColor))))->Color::Reset(); - pfVar18 = &local_258.y; - (*GHIDRA_CAST((GHIDRA_CAST(&(clubFlashColor)) + 0x0))) = 1.0; - (*GHIDRA_CAST((GHIDRA_CAST(&(clubFlashColor)) + 0x4))) = 1.0; - (*GHIDRA_CAST((GHIDRA_CAST(&(clubFlashColor)) + 0x8))) = 1.0; - (*GHIDRA_CAST((GHIDRA_CAST(&(clubFlashColor)) + 0xc))) = (void *)0x0; - local_238.y = 1.001; - owner = GHIDRA_CAST(((float)newCharge + 1.0)); - clampedValue = &local_238.y; - if (1.001 <= (float)maxCharge) { - clampedValue = pfVar18; - } - newCharge = GHIDRA_CAST(*clampedValue); - if ((float)owner <= (float)newCharge) { - newCharge = owner; - } - if (pEVar19 == GHIDRA_CAST(0x0)) goto LAB_009fe321; - pfVar18 = GHIDRA_CAST(CONCAT31((int3)(GHIDRA_UINT(pfVar18) >> 8),isEpicFetus)); - if ((isDrFetus != '\0') || (isEpicFetus != '\0')) { - heldEntitySlot = &pEVar19->_heldEntity; - (*GHIDRA_CAST((GHIDRA_CAST(&(local_1c4)) + 0x0))) = heldEntitySlot; - if (*heldEntitySlot == (void *)0x0) { - if (isChargeMode == '\0') { - fVar23 = 1.0; - } - else { - fVar23 = (float)maxCharge - 30.0; - if (fVar23 <= 2.0) { - fVar23 = 2.0; - } - } - if ((GHIDRA_CAST(this))->_pendingDamage == fVar23) { - if (isEpicFetus == '\0') { - local_274.x = (player->_pos).x; - local_274.y = (player->_pos).y; - pEVar27 = Weapon::fire_bomb(this,&local_274,&g_vectorZero); - if (*(*GHIDRA_CAST((GHIDRA_CAST(&((void **)local_1c4)) + 0x0))) != (void *)0x0) { - local_258.y = (*GHIDRA_CAST((GHIDRA_CAST(&((float)local_1c4)) + 0x0))); - msvc::multiset::erase(); - } - *(*GHIDRA_CAST((GHIDRA_CAST(&(GHIDRA_CAST(local_1c4))) + 0x0))) = pEVar27; - if (pEVar27 != GHIDRA_CAST(0x0)) { - msvc::multiset::insert(); - } - savedBombFlags = pEVar27->_flags; - bombFlagsHigh = GHIDRA_CAST((GHIDRA_INT(&pEVar27->_flags) + 4)); - *bombFlagsHigh = *bombFlagsHigh | 0x2000020; - *GHIDRA_CAST(&pEVar27->_flags) = GHIDRA_INT(savedBombFlags); - pEVar27->_explosionCountdown1 = 0x2d; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((pEVar27)) + 0x414)))) = 0x2d; - pEVar27->_entityCollisionClass = 0; - pEVar27->_entityGridCollisionClass = 0; - pEVar27->_visible = 0; - fVar23 = atan2f(shotDirection.y,shotDirection.x); - pEVar27->_rocketAngle = fVar23 * 57.295776; - if ((pEVar27->_variant == 0x13) || (pEVar27->_variant == 0x14)) { - ANM2::Play(&pEVar27->_sprite,s_Idle,0); - (pEVar27->_sprite)._rotation = 0.0; - } - } - else { - uVar6 = Random(); - local_274.x = (player->_pos).x; - local_274.y = (player->_pos).y; - (*GHIDRA_CAST((GHIDRA_CAST(&(local_1c4)) + 0x0))) = - Game::Spawn(g_game,1000,0x76,&local_274,&g_vectorZero, - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(((GHIDRA_CAST(this)))) + 0x4)))),0,uVar6); - if (*heldEntitySlot != (void *)0x0) { - local_258.y = (float)heldEntitySlot; - msvc::multiset::erase(); - } - *heldEntitySlot = (*GHIDRA_CAST((GHIDRA_CAST(&((void *)local_1c4)) + 0x0))); - if ((*GHIDRA_CAST((GHIDRA_CAST(&(GHIDRA_CAST(local_1c4))) + 0x0))) != GHIDRA_CAST(0x0)) { - msvc::multiset::insert(); - } - savedBombFlags = ((*GHIDRA_CAST((GHIDRA_CAST(&(GHIDRA_CAST(local_1c4))) + 0x0))))->_flags; - bombFlagsHigh = GHIDRA_CAST((GHIDRA_INT(&((*GHIDRA_CAST((GHIDRA_CAST(&(GHIDRA_CAST(local_1c4))) + 0x0))))->_flags) + 4)); - *bombFlagsHigh = *bombFlagsHigh | 0x20; - ((*GHIDRA_CAST((GHIDRA_CAST(&(GHIDRA_CAST(local_1c4))) + 0x0))))->_visible = 0; - *GHIDRA_CAST(&((*GHIDRA_CAST((GHIDRA_CAST(&(GHIDRA_CAST(local_1c4))) + 0x0))))->_flags) = GHIDRA_INT(savedBombFlags); - } - pMVar3 = g_manager; - (*GHIDRA_CAST((GHIDRA_CAST(&(local_1c4)) + 0x0))) = GHIDRA_CAST(0xc9); - seed_fart_sound_override(GHIDRA_CAST(local_1c4)); - (GHIDRA_CAST((&pMVar3->_sfxManager)))->SoundEffects::Play((*GHIDRA_CAST((GHIDRA_CAST(&(local_1c4)) + 0x0))),1.0,2,0,1.0,0.0); - pfVar18 = extraout_ECX_06; - } - } - pEVar19 = player; - } - pvVar17 = pEVar19->_heldEntity; - if (pvVar17 == (void *)0x0) goto LAB_009fe321; - fVar23 = (pEVar19->_pos).y; - *GHIDRA_CAST((GHIDRA_CAST(pvVar17) + 0x33c)) = (pEVar19->_pos).x; - *GHIDRA_CAST((GHIDRA_CAST(pvVar17) + 0x340)) = fVar23; - pvVar17 = pEVar19->_heldEntity; - fVar23 = (pEVar19->_velocity).y; - *GHIDRA_CAST((GHIDRA_CAST(pvVar17) + 0x360)) = (pEVar19->_velocity).x; - *GHIDRA_CAST((GHIDRA_CAST(pvVar17) + 0x364)) = fVar23; - switch(pEVar19->_headDirection) { - case 0: - fVar23 = (pEVar19->_sprite)._scale.x * 8.0; - break; - case 1: - fVar23 = (pEVar19->_sprite)._scale.x * -12.0; - goto LAB_009fe24e; - case 2: - fVar23 = (pEVar19->_sprite)._scale.x * -8.0; -LAB_009fe24e: - fVar25 = (pEVar19->_sprite)._scale.y; - pvVar17 = pEVar19->_heldEntity; - *GHIDRA_CAST((GHIDRA_CAST(pvVar17) + 0x34c)) = fVar23; - *GHIDRA_CAST((GHIDRA_CAST(pvVar17) + 0x350)) = fVar25 * -4.0; - *GHIDRA_CAST((GHIDRA_CAST(pEVar19->_heldEntity) + 0x354)) = 0xffffffff; - goto LAB_009fe2f0; - default: - fVar23 = (pEVar19->_sprite)._scale.x * 12.0; - } - fVar25 = (pEVar19->_sprite)._scale.y; - pvVar17 = pEVar19->_heldEntity; - *GHIDRA_CAST((GHIDRA_CAST(pvVar17) + 0x34c)) = fVar23; - *GHIDRA_CAST((GHIDRA_CAST(pvVar17) + 0x350)) = fVar25 * -4.0; - *GHIDRA_CAST((GHIDRA_CAST(pEVar19->_heldEntity) + 0x354)) = 0; -LAB_009fe2f0: - pvVar17 = pEVar19->_heldEntity; - if (*GHIDRA_CAST((GHIDRA_CAST(pvVar17) + 0x28)) == 4) { - fVar23 = atan2f(shotDirection.y,shotDirection.x); - *GHIDRA_CAST((GHIDRA_CAST(pvVar17) + 0x428)) = fVar23 * 57.295776; - pfVar18 = extraout_ECX_07; - } -LAB_009fe321: - club = heldClub; - if ((char)isCursedEye == '\0') { - if (isChocolateMilk != 0) goto LAB_009fe472; - if ((char)isBrimstone != '\0') goto LAB_009fe5d9; - if ((float)maxCharge <= (GHIDRA_CAST(this))->_pendingDamage) { - (*GHIDRA_CAST((GHIDRA_CAST(&(clubFlashColor)) + 0xc))) = (void *)0x3f800000; - VStack_20.x = 0.2; - VStack_20.y = 0.2; - puStack_18 = GHIDRA_CAST(0x3e4ccccd); - (GHIDRA_CAST((GHIDRA_CAST(clubFlashColor))))->Color::__mul(&heldClub->_color); - pfVar18 = extraout_ECX_08; - } - } - else { - if ((float)maxCharge < (GHIDRA_CAST(this))->_pendingDamage || - (float)maxCharge == (GHIDRA_CAST(this))->_pendingDamage) { - Weapon::UpdateHeadChargeAnimation(this,0x13c,1,&shotDirection,-1.0); - club = heldClub; - (*GHIDRA_CAST((GHIDRA_CAST(&(clubFlashColor)) + 0xc))) = (void *)0x3f800000; - VStack_20.x = 0.2; - VStack_20.y = 0.2; - puStack_18 = GHIDRA_CAST(0x3e4ccccd); - (GHIDRA_CAST((GHIDRA_CAST(clubFlashColor))))->Color::__mul(&heldClub->_color); - iVar30 = extraout_ECX_10; - } - else { - Weapon::UpdateHeadChargeAnimation(this,0x13c,0,&shotDirection,0.0); - iVar30 = extraout_ECX_09; - club = heldClub; - } - Weapon::SetBlinkTime(this,1,iVar30); - uVar6 = GHIDRA_UINT((((float)newCharge * 5.0) / (float)maxCharge)); - *GHIDRA_CAST((&(*GHIDRA_CAST((GHIDRA_CAST(((GHIDRA_CAST(this)))) + 0x44))) + 0x18)) = uVar6; - if ((1.0 < (float)newCharge) && (uVar6 == 0)) { - *GHIDRA_CAST((&(*GHIDRA_CAST((GHIDRA_CAST(((GHIDRA_CAST(this)))) + 0x44))) + 0x18)) = 1; - } - pfVar18 = extraout_ECX_11; - if (isChocolateMilk != 0) { -LAB_009fe472: - fVar23 = (GHIDRA_CAST(this))->_pendingDamage; - if ((float)maxCharge <= fVar23) { - puVar22 = &DAT_bf800000; - } - else { - puVar22 = GHIDRA_CAST(((fVar23 / (float)maxCharge) * 18.0)); - } - Weapon::UpdateHeadChargeAnimation - (this,0x45,GHIDRA_UINT(((float)maxCharge <= fVar23)),&shotDirection,(float)puVar22); - Weapon::SetBlinkTime(this,1,unused_00); - fVar25 = ((float)newCharge / (float)maxFireDelay - 1.0) * 0.5 + 1.0; - fVar23 = 1.0; - if (1.0 <= fVar25) { - fVar23 = fVar25; - } - fVar23 = fVar23 * (float)clubScale; - fVar25 = fVar23; - if ((heldClub->_isSwinging != 0) && (fVar25 = (heldClub->_sprite)._scale.x, fVar25 <= fVar23)) - { - fVar25 = fVar23; - } - iVar30 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(((GHIDRA_CAST(this)))) + 0x44)))); - if (iVar30 != 0) { - fVar23 = fVar25 * g_vectorOne.y; - *GHIDRA_CAST((iVar30 + 0xe4)) = fVar25 * g_vectorOne.x; - *GHIDRA_CAST((iVar30 + 0xe8)) = fVar23; - } - iVar30 = *GHIDRA_CAST(((GHIDRA_CAST((&(*GHIDRA_CAST((GHIDRA_CAST(((GHIDRA_CAST(this)))) + 0x44))) + 4)))->_filename)._buf); - if (iVar30 != 0) { - fVar23 = fVar25 * g_vectorOne.y; - *GHIDRA_CAST((iVar30 + 0xe4)) = fVar25 * g_vectorOne.x; - *GHIDRA_CAST((iVar30 + 0xe8)) = fVar23; - } - iVar30 = *GHIDRA_CAST((&(*GHIDRA_CAST((GHIDRA_CAST(((GHIDRA_CAST(this)))) + 0x44))) + 8)); - if (iVar30 != 0) { - fVar23 = fVar25 * g_vectorOne.y; - *GHIDRA_CAST((iVar30 + 0xe4)) = fVar25 * g_vectorOne.x; - *GHIDRA_CAST((iVar30 + 0xe8)) = fVar23; - } - iVar30 = *GHIDRA_CAST((&(*GHIDRA_CAST((GHIDRA_CAST(((GHIDRA_CAST(this)))) + 0x44))) + 0xc)); - pfVar18 = extraout_ECX_12; - club = heldClub; - if (iVar30 != 0) { - fVar23 = fVar25 * g_vectorOne.y; - *GHIDRA_CAST((iVar30 + 0xe4)) = fVar25 * g_vectorOne.x; - *GHIDRA_CAST((iVar30 + 0xe8)) = fVar23; - } - } - if ((char)isBrimstone != '\0') { -LAB_009fe5d9: - if ((float)chargeThreshold <= (GHIDRA_CAST(this))->_pendingDamage) { - Weapon::UpdateHeadChargeAnimation(this,0x76,1,&shotDirection,-1.0); - owner = ownerPlayer; - (GHIDRA_CAST((GHIDRA_CAST(chargeColor))))->Color::Reset(); - (*GHIDRA_CAST((GHIDRA_CAST(&(chargeColor)) + 0x0))) = 1.0; - (*GHIDRA_CAST((GHIDRA_CAST(&(chargeColor)) + 0x4))) = 0.0; - (*GHIDRA_CAST((GHIDRA_CAST(&(chargeColor)) + 0x8))) = 0.0; - (*GHIDRA_CAST((GHIDRA_CAST(&(chargeColor)) + 0xc))) = (void *)0x3f800000; - if (owner != GHIDRA_CAST(0x0)) { - (*GHIDRA_CAST((GHIDRA_CAST(&(local_2f8)) + 0x0))) = (owner->_laserColor)._tint[0]; - (*GHIDRA_CAST((GHIDRA_CAST(&(local_2f8)) + 0x4))) = (owner->_laserColor)._tint[1]; - (*GHIDRA_CAST((GHIDRA_CAST(&(local_2f8)) + 0x8))) = (owner->_laserColor)._tint[2]; - (*GHIDRA_CAST((GHIDRA_CAST(&(local_2f8)) + 0xc))) = (owner->_laserColor)._tint[3]; - local_2d0 = GHIDRA_CAST((owner->_laserColor)._offset[2]); - (*GHIDRA_CAST((GHIDRA_CAST(&(local_2f8)) + 0x10))) = (owner->_laserColor)._colorize[0]; - (*GHIDRA_CAST((GHIDRA_CAST(&(local_2f8)) + 0x14))) = (owner->_laserColor)._colorize[1]; - (*GHIDRA_CAST((GHIDRA_CAST(&(local_2f8)) + 0x18))) = (owner->_laserColor)._colorize[2]; - (*GHIDRA_CAST((GHIDRA_CAST(&(local_2f8)) + 0x1c))) = (owner->_laserColor)._colorize[3]; - (*GHIDRA_CAST((GHIDRA_CAST(&(local_2f8)) + 0x20))) = (owner->_laserColor)._offset[0]; - uStack_2d4 = (owner->_laserColor)._offset[1]; - (GHIDRA_CAST((GHIDRA_CAST(local_2f8))))->Color::__mul(GHIDRA_CAST(chargeColor)); - puStack_70 = local_2d0; - (*GHIDRA_CAST((GHIDRA_CAST(&(chargeColor)) + 0x0))) = (*GHIDRA_CAST((GHIDRA_CAST(&(local_2f8)) + 0x0))); - (*GHIDRA_CAST((GHIDRA_CAST(&(chargeColor)) + 0x4))) = (*GHIDRA_CAST((GHIDRA_CAST(&(local_2f8)) + 0x4))); - (*GHIDRA_CAST((GHIDRA_CAST(&(chargeColor)) + 0x8))) = (*GHIDRA_CAST((GHIDRA_CAST(&(local_2f8)) + 0x8))); - (*GHIDRA_CAST((GHIDRA_CAST(&(chargeColor)) + 0xc))) = (*GHIDRA_CAST((GHIDRA_CAST(&(local_2f8)) + 0xc))); - (*GHIDRA_CAST((GHIDRA_CAST(&(chargeColor)) + 0x10))) = (*GHIDRA_CAST((GHIDRA_CAST(&(local_2f8)) + 0x10))); - (*GHIDRA_CAST((GHIDRA_CAST(&(chargeColor)) + 0x14))) = (*GHIDRA_CAST((GHIDRA_CAST(&(local_2f8)) + 0x14))); - (*GHIDRA_CAST((GHIDRA_CAST(&(chargeColor)) + 0x18))) = (*GHIDRA_CAST((GHIDRA_CAST(&(local_2f8)) + 0x18))); - (*GHIDRA_CAST((GHIDRA_CAST(&(chargeColor)) + 0x1c))) = (*GHIDRA_CAST((GHIDRA_CAST(&(local_2f8)) + 0x1c))); - (*GHIDRA_CAST((GHIDRA_CAST(&(chargeColor)) + 0x20))) = (*GHIDRA_CAST((GHIDRA_CAST(&(local_2f8)) + 0x20))); - (*GHIDRA_CAST((GHIDRA_CAST(&(chargeColor)) + 0x24))) = uStack_2d4; - } - club = heldClub; - (*GHIDRA_CAST((GHIDRA_CAST(&(clubFlashColor)) + 0x0))) = (*GHIDRA_CAST((GHIDRA_CAST(&(chargeColor)) + 0x0))); - (*GHIDRA_CAST((GHIDRA_CAST(&(clubFlashColor)) + 0x4))) = (*GHIDRA_CAST((GHIDRA_CAST(&(chargeColor)) + 0x4))); - (*GHIDRA_CAST((GHIDRA_CAST(&(clubFlashColor)) + 0x8))) = (*GHIDRA_CAST((GHIDRA_CAST(&(chargeColor)) + 0x8))); - (*GHIDRA_CAST((GHIDRA_CAST(&(clubFlashColor)) + 0xc))) = (*GHIDRA_CAST((GHIDRA_CAST(&(chargeColor)) + 0xc))); - (*GHIDRA_CAST((GHIDRA_CAST(&(clubFlashColor)) + 0x10))) = (*GHIDRA_CAST((GHIDRA_CAST(&(chargeColor)) + 0x10))); - (*GHIDRA_CAST((GHIDRA_CAST(&(clubFlashColor)) + 0x14))) = (*GHIDRA_CAST((GHIDRA_CAST(&(chargeColor)) + 0x14))); - (*GHIDRA_CAST((GHIDRA_CAST(&(clubFlashColor)) + 0x18))) = (*GHIDRA_CAST((GHIDRA_CAST(&(chargeColor)) + 0x18))); - (*GHIDRA_CAST((GHIDRA_CAST(&(clubFlashColor)) + 0x1c))) = (*GHIDRA_CAST((GHIDRA_CAST(&(chargeColor)) + 0x1c))); - VStack_20.x = (*GHIDRA_CAST((GHIDRA_CAST(&((float)chargeColor)) + 0x20))); - VStack_20.y = (*GHIDRA_CAST((GHIDRA_CAST(&((float)chargeColor)) + 0x24))); - puStack_18 = puStack_70; - iVar30 = Entity::GetIntervalTicks(GHIDRA_CAST(heldClub),2.0,0.0); - unused_01 = extraout_ECX_14; - if (iVar30 != 0) { - unused_01 = extraout_ECX_14; - if ((club->_sprite)._animState._animData != (void *)0x0) { - pfVar18 = AnimationState::GetNullFrameById(&(club->_sprite)._animState,0); - unused_01 = extraout_ECX_15; - if (pfVar18 != GHIDRA_CAST(0x0)) { - local_238.y = *pfVar18 / 0.65; - local_1e4.y = pfVar18[1] / 0.65; - local_258.y = (club->_sprite)._rotation * 0.017453292; - ownerVelocityX.y = cos(local_258.y); - fVar23 = sin(local_258.y); - (*GHIDRA_CAST((GHIDRA_CAST(&(local_1c4)) + 0x0))) = (local_238.y * ownerVelocityX.y - local_1e4.y * fVar23) * 1.2; - local_1e4.y = (local_1e4.y * ownerVelocityX.y + local_238.y * fVar23) * 1.2; - local_258.y = cos(1.5707964); - fVar23 = sin(1.5707964); - local_200 = (Entity_Player *) - (local_258.y * (*GHIDRA_CAST((GHIDRA_CAST(&((float)local_1c4)) + 0x0))) - local_1e4.y * fVar23); - local_1f0.y = (*GHIDRA_CAST((GHIDRA_CAST(&((float)local_1c4)) + 0x0))) * fVar23 + local_258.y * local_1e4.y; - fVar23 = sqrtf((float)local_200 * (float)local_200 + local_1f0.y * local_1f0.y); - if (0.0 < fVar23) { - local_200 = GHIDRA_CAST(((float)local_200 * (1.0 / fVar23))); - local_1f0.y = local_1f0.y * (1.0 / fVar23); - } - local_238.y = (club->_sprite)._scale.y; - uVar6 = Random(); - local_258.y = (float)((double)GHIDRA_INT(uVar6) + - __uint_to_double_fixup[-(GHIDRA_INT(uVar6) >> 0x1f)]) * 2.3283064e-10; - ownerVelocityX.y = (club->_pos).x; - local_220.y = (club->_pos).y; - uVar6 = Random(); - fVar23 = (float)((double)GHIDRA_INT(uVar6) + __uint_to_double_fixup[-(GHIDRA_INT(uVar6) >> 0x1f)]) * - 2.3283064e-10; - local_264.x = fVar23 * (float)local_200 * local_258.y * local_238.y * 10.0 + - local_258.y * (*GHIDRA_CAST((GHIDRA_CAST(&((float)local_1c4)) + 0x0))) + ownerVelocityX.y; - local_264.y = fVar23 * local_1f0.y * local_258.y * local_238.y * 10.0 + - local_258.y * local_1e4.y + local_220.y; - local_238.y = (float)Random(); - iVar30 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(((GHIDRA_CAST(this)))) + 0x4)))); - pVVar9 = &ownerVelocityX; - if (iVar30 == 0) { - local_274.x = g_vectorZero.x; - local_274.y = g_vectorZero.y; - pVVar9 = &local_274; - } - else { - ownerVelocityX.x = *GHIDRA_CAST((iVar30 + 0x360)); - ownerVelocityX.y = *GHIDRA_CAST((iVar30 + 0x364)); - } - uVar6 = Random(); - fVar23 = (float)((double)GHIDRA_INT(uVar6) + __uint_to_double_fixup[-(GHIDRA_INT(uVar6) >> 0x1f)]) * - 2.3283064e-10 * 3.14; - (*GHIDRA_CAST((GHIDRA_CAST(&(local_1c4)) + 0x0))) = fVar23 + fVar23; - uVar6 = Random(); - local_200 = (Entity_Player *) - ((float)((double)GHIDRA_INT(uVar6) + - __uint_to_double_fixup[-(GHIDRA_INT(uVar6) >> 0x1f)]) * 2.3283064e-10); - fVar23 = cos((*GHIDRA_CAST((GHIDRA_CAST(&((float)local_1c4)) + 0x0)))); - local_258.y = fVar23 * (float)local_200; - fVar23 = sin((*GHIDRA_CAST((GHIDRA_CAST(&((float)local_1c4)) + 0x0)))); - local_258.x = local_258.y + local_258.y + pVVar9->x * 0.2 + 0.0; - local_258.y = (fVar23 * (float)local_200 + fVar23 * (float)local_200 + pVVar9->y * 0.2 - ) - 1.0; - pEVar31 = Game::Spawn(g_game,1000,0x6f,&local_264,&local_258,GHIDRA_CAST(0x0),0, - GHIDRA_UINT(local_238.y)); - if (ownerPlayer != GHIDRA_CAST(0x0)) { - (*GHIDRA_CAST((GHIDRA_CAST(&(chargeColor)) + 0x0))) = (ownerPlayer->_laserColor)._tint[0]; - (*GHIDRA_CAST((GHIDRA_CAST(&(chargeColor)) + 0x4))) = (ownerPlayer->_laserColor)._tint[1]; - (*GHIDRA_CAST((GHIDRA_CAST(&(chargeColor)) + 0x8))) = (ownerPlayer->_laserColor)._tint[2]; - (*GHIDRA_CAST((GHIDRA_CAST(&(chargeColor)) + 0xc))) = (ownerPlayer->_laserColor)._tint[3]; - (*GHIDRA_CAST((GHIDRA_CAST(&(chargeColor)) + 0x10))) = (ownerPlayer->_laserColor)._colorize[0]; - (*GHIDRA_CAST((GHIDRA_CAST(&(chargeColor)) + 0x14))) = (ownerPlayer->_laserColor)._colorize[1]; - (*GHIDRA_CAST((GHIDRA_CAST(&(chargeColor)) + 0x18))) = (ownerPlayer->_laserColor)._colorize[2]; - (*GHIDRA_CAST((GHIDRA_CAST(&(chargeColor)) + 0x1c))) = (ownerPlayer->_laserColor)._colorize[3]; - (*GHIDRA_CAST((GHIDRA_CAST(&(chargeColor)) + 0x20))) = (ownerPlayer->_laserColor)._offset[0]; - (*GHIDRA_CAST((GHIDRA_CAST(&(chargeColor)) + 0x24))) = (ownerPlayer->_laserColor)._offset[1]; - puStack_70 = GHIDRA_CAST((ownerPlayer->_laserColor)._offset[2]); - (**(code **)(*GHIDRA_CAST(pEVar31) + 0x3c))(); - } - uVar6 = Random(); - fVar25 = (float)((double)GHIDRA_INT(uVar6) + __uint_to_double_fixup[-(GHIDRA_INT(uVar6) >> 0x1f)]) * - 2.3283064e-10 * 0.3 + 0.3; - fVar23 = (heldClub->_sprite)._scale.x; - (pEVar31->_sprite)._scale.y = fVar25 * (heldClub->_sprite)._scale.y; - (pEVar31->_sprite)._scale.x = fVar25 * fVar23; - (pEVar31->_posOffset).x = (heldClub->_posOffset).x; - (pEVar31->_posOffset).y = (heldClub->_posOffset).y; - pEVar31->_renderDepthOffset = -100.0; - unused_01 = heldClub; - club = heldClub; - } - } - } - } - else { - Weapon::UpdateHeadChargeAnimation - (this,0x76,0,&shotDirection, - ((GHIDRA_CAST(this))->_pendingDamage / (float)chargeThreshold) * 18.0); - unused_01 = extraout_ECX_13; - } - Weapon::SetBlinkTime(this,1,GHIDRA_INT(unused_01)); - pfVar18 = extraout_ECX_16; - } - } - if ((*GHIDRA_CAST((GHIDRA_CAST(&(local_250)) + 0x0))) != '\0') { - if ((float)chargeThreshold <= (GHIDRA_CAST(this))->_pendingDamage) { - Weapon::UpdateHeadChargeAnimation(this,0xe5,1,&shotDirection,-1.0); - (*GHIDRA_CAST((GHIDRA_CAST(&(clubFlashColor)) + 0x0))) = 1.0; - (*GHIDRA_CAST((GHIDRA_CAST(&(clubFlashColor)) + 0x4))) = 1.0; - (*GHIDRA_CAST((GHIDRA_CAST(&(clubFlashColor)) + 0x8))) = 1.0; - (*GHIDRA_CAST((GHIDRA_CAST(&(clubFlashColor)) + 0xc))) = (void *)0x3f800000; - VStack_20.x = 0.2; - VStack_20.y = 0.2; - puStack_18 = GHIDRA_CAST(0x3e4ccccd); - (GHIDRA_CAST((GHIDRA_CAST(clubFlashColor))))->Color::__mul(&club->_color); - iVar30 = extraout_ECX_18; - } - else { - Weapon::UpdateHeadChargeAnimation - (this,0xe5,0,&shotDirection, - ((GHIDRA_CAST(this))->_pendingDamage / (float)chargeThreshold) * 18.0); - iVar30 = extraout_ECX_17; - } - Weapon::SetBlinkTime(this,1,iVar30); - pfVar18 = extraout_ECX_19; - } - if ((char)isCSection != '\0') { - local_258.y = (GHIDRA_CAST(this))->_pendingDamage; - if ((float)chargeThreshold <= local_258.y) { - puVar22 = &DAT_bf800000; - iVar30 = 1; -LAB_009fece6: - Weapon::update_c_section_charge_anim(this,GHIDRA_INT(pfVar18),iVar30,aimDirection,(float)puVar22); - pfVar18 = extraout_ECX_21; - } - else { - bVar4 = Weapon::is_c_section_anim_finished(this,GHIDRA_INT(pfVar18)); - pfVar18 = extraout_ECX_20; - if (bVar4 != 0) { - puVar22 = GHIDRA_CAST(((local_258.y / (float)chargeThreshold) * 18.0)); - iVar30 = 0; - goto LAB_009fece6; - } - } - Weapon::SetBlinkTime(this,1,GHIDRA_INT(pfVar18)); - } - iVar30 = Entity::GetIntervalTicks(GHIDRA_CAST(club),4.0,0.0); - if ((iVar30 != 0) && (0.0 < (*GHIDRA_CAST((GHIDRA_CAST(&((float)clubFlashColor)) + 0xc))))) { - (**(code **)(*GHIDRA_CAST(club) + 0x3c))(); - } - pVVar9 = Weapon::get_aim_direction(this,&local_274,&shotDirection); - (GHIDRA_CAST(this))->_index = GHIDRA_INT(pVVar9->x); - (GHIDRA_CAST(this))->_collisionIndex = GHIDRA_INT(pVVar9->y); - owner = newCharge; -LAB_009fb9f2: - if (club->_isFlying != 0) { - Weapon::SetHeadLockTime(this,2); - } - (GHIDRA_CAST(this))->_pendingDamage = (float)owner; - ExceptionList = local_10; - return; -} - -// 009fed90 -void Weapon_Bone::Reset() -{ - this->ClearReferences(); - *GHIDRA_CAST((GHIDRA_CAST(this) + 0x1c)) = 0; - *GHIDRA_CAST((GHIDRA_CAST(this) + 0xc)) = 0; - *GHIDRA_CAST((GHIDRA_CAST(this) + 0x10)) = 0x41200000; - *GHIDRA_CAST((GHIDRA_CAST(this) + 0x14)) = 0; - *GHIDRA_CAST((GHIDRA_CAST(this) + 0x18)) = 0x3f800000; - *GHIDRA_CAST((GHIDRA_CAST(this) + 0x38)) = 0; - *GHIDRA_CAST((GHIDRA_CAST(this) + 0x20)) = g_vectorZero.x; - *GHIDRA_CAST((GHIDRA_CAST(this) + 0x24)) = g_vectorZero.y; - *GHIDRA_CAST((GHIDRA_CAST(this) + 0x5c)) = 0; - return; -} - -// 009fedf0 -void Weapon_Bone::ClearReferences() -{ - int *entitySlot; - int remaining; - int *local_8; - - entitySlot = GHIDRA_CAST((GHIDRA_INT(this) + 8)); - local_8 = this; - if (*GHIDRA_CAST((GHIDRA_CAST(this) + 8)) != GHIDRA_CAST(0x0)) { - (**(code **)(**GHIDRA_CAST((GHIDRA_CAST(this) + 8)) + 0x28))(); - if (*entitySlot != 0) { - local_8 = entitySlot; - msvc::multiset::erase(&local_8); - *entitySlot = 0; - } - } - entitySlot = GHIDRA_CAST((GHIDRA_INT(this) + 0x44)); - remaining = 4; - do { - if (GHIDRA_CAST(*entitySlot) != GHIDRA_CAST(0x0)) { - (**(code **)(*GHIDRA_CAST(*entitySlot) + 0x28))(); - (**(code **)(*GHIDRA_CAST(*entitySlot) + 0x44))(); - } - entitySlot = entitySlot + 1; - remaining = remaining + -1; - } while (remaining != 0); - entitySlot = GHIDRA_CAST((GHIDRA_INT(this) + 0x58)); - if (*GHIDRA_CAST((GHIDRA_CAST(this) + 0x58)) != GHIDRA_CAST(0x0)) { - (**(code **)(**GHIDRA_CAST((GHIDRA_CAST(this) + 0x58)) + 0x28))(); - if (*entitySlot != 0) { - local_8 = entitySlot; - msvc::multiset::erase(&local_8); - *entitySlot = 0; - } - } - entitySlot = GHIDRA_CAST((GHIDRA_INT(this) + 0x54)); - if (*GHIDRA_CAST((GHIDRA_CAST(this) + 0x54)) != GHIDRA_CAST(0x0)) { - (**(code **)(**GHIDRA_CAST((GHIDRA_CAST(this) + 0x54)) + 0x28))(); - if (*entitySlot != 0) { - local_8 = entitySlot; - msvc::multiset::erase(&local_8); - *entitySlot = 0; - } - } - return; -} - -// 009feeb0 -long double Weapon_Bone::GetMaxCharge() -{ - int in_ECX; - float fireDelay; - - if (((*GHIDRA_CAST((in_ECX + 0x34)) & 0x80e) == 0) || ((*GHIDRA_CAST((in_ECX + 0x34)) & 1) != 0)) { - fireDelay = *GHIDRA_CAST((in_ECX + 0x10)); - if (fireDelay < 0.001) { - fireDelay = 0.001; - } - return (long double)fireDelay * (long double)3.0; - } - fireDelay = *GHIDRA_CAST((in_ECX + 0x10)); - if (fireDelay < 0.001) { - fireDelay = 0.001; - } - return (long double)fireDelay + (long double)fireDelay; -} - -// 009ff0c0 -void Weapon_Bone::init_club(int *param_1) -{ - int iVar1; - uint64_t qVar2; - ColorMod *pCVar3; - BitSet128 *tearFlags; - Weapon *in_ECX; - float damage; - int iVar4; - int iVar5; - Weapon *this; - uint8_t local_50 [4]; - BitSet128 local_4c; - ColorMod tearColor; - uint32_t local_c; - code *setDamageFn; - - local_c = __security_cookie ^ GHIDRA_UINT(local_50); - (*GHIDRA_CAST((GHIDRA_CAST(&(local_4c._l)) + 0x0))) = *param_1; - if (*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((in_ECX)) + 0x30)))) == 0xb) { - (**(code **)(GHIDRA_CAST(local_4c._l) + 0x40))(); - return; - } - pCVar3 = Weapon::get_tear_color(in_ECX,&tearColor); - this = GHIDRA_CAST(0xff); - iVar5 = -1; - (**(code **)(GHIDRA_CAST(local_4c._l) + 0x3c))(pCVar3,0xffffffff,0xff,0); - tearFlags = Weapon::get_owner_tear_flags(in_ECX,GHIDRA_CAST((local_50 + -0xc))); - iVar4 = *GHIDRA_CAST((GHIDRA_INT(&tearFlags->_l) + 4)); - qVar2 = tearFlags->_h; - iVar1 = *GHIDRA_CAST((GHIDRA_INT(&tearFlags->_h) + 4)); - param_1[0x104] = GHIDRA_INT(tearFlags->_l); - param_1[0x105] = iVar4; - param_1[0x106] = GHIDRA_INT(qVar2); - param_1[0x107] = iVar1; - setDamageFn = *(code **)(*param_1 + 0x40); - damage = Weapon::get_damage(this); - (*setDamageFn)(damage); - if ((*GHIDRA_CAST((iVar5 + 0x34)) >> 7 & 1) == 0) { - iVar4 = 0x40400000; - } - else { - iVar4 = 0x3f000000; - } - param_1[0xdf] = iVar4; - return; -} - -// 009ff1a0 -uint8_t Weapon_Bone::CanTriggerCursedEyeTeleport() -{ - int iVar1; - float minChargeTime; - - if (((*GHIDRA_CAST((GHIDRA_CAST(this) + 0x30)) != 0xb) && (iVar1 = *GHIDRA_CAST((GHIDRA_CAST(this) + 4)), iVar1 != 0)) && - (*GHIDRA_CAST((iVar1 + 0x28)) == 1)) { - if ((*GHIDRA_CAST((iVar1 + 0x140c)) != 0) && - (iVar1 = this->GetFocusEntity(), iVar1 != 0)) { - return 0; - } - if (0.0 < *GHIDRA_CAST((GHIDRA_CAST(this) + 0x14))) { - minChargeTime = *GHIDRA_CAST((GHIDRA_CAST(this) + 0x10)); - if (minChargeTime < 0.001) { - minChargeTime = 0.001; - } - if (*GHIDRA_CAST((GHIDRA_CAST(this) + 0x14)) < minChargeTime + minChargeTime) { - return 1; - } - } - } - return 0; -} - -// 009ff210 -uint8_t Weapon_Bone::CanTriggerKidneyStone() -{ - if ((*GHIDRA_CAST((GHIDRA_CAST(this) + 0x30)) == 0xb) || - ((*GHIDRA_CAST((GHIDRA_CAST(this) + 0x44)) != 0 && (*GHIDRA_CAST((*GHIDRA_CAST((GHIDRA_CAST(this) + 0x44)) + 0x464)) != '\0')))) - { - return 0; - } - return 1; -} - -// 009ff230 -uint8_t Weapon_Bone::CanOverrideForgottenThrow() -{ - void *player = this; - int iVar1; - bool bVar2; - uint8_t isDrFetusOnly; - Entity_Player *player; - Entity_Player *ownerPlayer; - bool isDrFetusOnly; - uint8_t modifierBits; - uint32_t modifiers; - - ownerPlayer = *GHIDRA_CAST((GHIDRA_CAST(player) + 4)); - iVar1 = *GHIDRA_CAST((GHIDRA_CAST(player) + 0x30)); - if (ownerPlayer == GHIDRA_CAST(0x0)) { -LAB_009ff265: - player = GHIDRA_CAST(0x0); - if ((ownerPlayer == GHIDRA_CAST(0x0)) || (ownerPlayer->_type != 1)) { -LAB_009ff273: - ownerPlayer = GHIDRA_CAST(0x0); - } - } - else { - if (ownerPlayer->_type != 1) { - if (ownerPlayer->_type != 3) goto LAB_009ff265; - player = *GHIDRA_CAST(&ownerPlayer->_isControlsEnabled); - goto LAB_009ff273; - } - player = ownerPlayer; - } - modifierBits = *GHIDRA_CAST((GHIDRA_CAST(player) + 0x34)); - modifiers = *GHIDRA_CAST((GHIDRA_CAST(player) + 0x34)); - if ((((iVar1 == 0xb) || (player == GHIDRA_CAST(0x0))) || - (isDrFetusOnly = Entity_Player::HasCollectible(player,0x34,0), isDrFetusOnly == 0)) || - (isDrFetusOnly = Entity_Player::HasCollectible(player,0xa8,0), isDrFetusOnly != 0)) { - isDrFetusOnly = false; - if ((iVar1 != 0xb) && (player != GHIDRA_CAST(0x0))) goto LAB_009ff2f1; - } - else { - isDrFetusOnly = true; -LAB_009ff2f1: - isDrFetusOnly = Entity_Player::HasCollectible(player,0xa8,0); - if (isDrFetusOnly != 0) { - bVar2 = true; - goto LAB_009ff309; - } - } - bVar2 = false; -LAB_009ff309: - if (((((modifierBits & 1) == 0) && ((modifiers >> 1 & 1) == 0)) && - (((modifiers >> 2 & 1) == 0 && ((modifiers >> 3 & 1) == 0)))) && - (((((!isDrFetusOnly && (!bVar2)) || (ownerPlayer == GHIDRA_CAST(0x0))) || - (ownerPlayer->_heldEntity == (void *)0x0)) && - ((*GHIDRA_CAST((GHIDRA_CAST(player) + 0x44)) == 0 || (*GHIDRA_CAST((*GHIDRA_CAST((GHIDRA_CAST(player) + 0x44)) + 0x466)) == '\0'))) - ))) { - return 0; - } - return 1; -} diff --git a/src/anm2.h b/src/anm2.h index b6e92ad..819a8a0 100644 --- a/src/anm2.h +++ b/src/anm2.h @@ -296,6 +296,16 @@ struct ANM2Base bool isUnknown108 = false; }; +// What GetTexel samples: a screen position, where the sprite draws, the alpha a texel must reach and the layer it looks +// in (any for -1). +struct TexelQuery +{ + Vector renderPos{}; + Vector sample{}; + float alphaThreshold = 0; + int layerId = -1; +}; + // 004074c0, 00408170 Construction and destruction are the defaults. // Sprite's field accessors (004073d0, 00407410, 00407420, 00407430, 00417200, 00417210, 00420160, 00420170, 00431300, // 00435c60, 0043ee80, 00440e40, 00456340, 00456360, 0049cb40) are the public fields. @@ -345,6 +355,7 @@ struct ANM2 : ANM2Base bool IsEventTriggered(std::string_view eventName) const; bool WasEventTriggered(std::string_view eventName) const; + KColor GetTexel(const TexelQuery& query) const; LayerState* GetLayer(int layerId); LayerState* GetLayer(std::string_view name); diff --git a/src/anm2_texel.cpp b/src/anm2_texel.cpp new file mode 100644 index 0000000..183660d --- /dev/null +++ b/src/anm2_texel.cpp @@ -0,0 +1,102 @@ +#include "anm2.h" +#include "fx_layers.h" +#include "npc_ai.h" +#include "room_render.h" +#include +#include + +// Turns a point about the origin, as KAGE's Quad::rotate turns a quad's corners. +static Vector point_turn(Vector point, float cosine, float sine) +{ + return vector_make(point.x * cosine - point.y * sine, point.y * cosine + point.x * sine); +} + +// 0040b600 The color an animation of a sprite shows at a screen position: the texel of the first visible layer +// keyframe over it that reaches the alpha, in the sprite's, layer's and keyframe's tints and offsets (colorize aside), +// else clear. A turned layer is turned back about the origin, sample and all. +static KColor animation_texel_get(const ANM2& sprite, const AnimationState& animation, const TexelQuery& query) +{ + if (!animation.animData) return {}; + + const std::vector& tracks = animation.animData->animLayers; + for (size_t track = 0; track < tracks.size(); track++) + { + const AnimationLayer& layer = tracks[track]; + int frameIndex = track < animation.layerFrames.size() ? animation.layerFrames[track] : -1; + bool isLayerKnown = layer.layerId >= 0 && layer.layerId < (int)sprite.layerStates.size(); + if (layer.frames.empty() || (query.layerId >= 0 && layer.layerId != query.layerId) || !isLayerKnown) continue; + if (frameIndex < 0 || frameIndex >= (int)layer.frames.size()) continue; + + const AnimationFrame& frame = layer.frames[frameIndex]; + const LayerState& state = sprite.layerStates[layer.layerId]; + if (!frame.isVisible || !state.isVisible || !state.spriteSheet) continue; + + SpriteDraw draw = {.position = query.renderPos}; + SourceQuad source = AnimationLayer::GetSourceQuad(frame, state, draw, sprite); + DestinationQuad screen = AnimationLayer::GetDestQuad(frame, state, draw, sprite); + Vector sample = query.sample; + float layerTurn = frame.rotation + state.rotation; + float spriteTurn = sprite.rotation; + if (spriteTurn != 0 || layerTurn != 0) + { + float layerScaleX = frame.scale.x * state.size.x; + float layerScaleY = state.isFlipY ? -(frame.scale.y * state.size.y) : frame.scale.y * state.size.y; + float spriteScaleY = sprite.isFlipY ? -sprite.scale.y : sprite.scale.y; + if ((sprite.scale.x < 0) != (layerScaleX < 0)) + { + if (sprite.scale.x < 0) + { + layerTurn = -layerTurn; + spriteTurn = -spriteTurn; + } + if (layerScaleX < 0) layerTurn = -layerTurn; + } + if ((spriteScaleY < 0) != (layerScaleY < 0)) + { + if (spriteScaleY < 0) + { + layerTurn = -layerTurn; + spriteTurn = -spriteTurn; + } + if (layerScaleY < 0) layerTurn = -layerTurn; + } + + float angle = -(layerTurn + spriteTurn) * DEGREES_TO_RADIANS; + float cosine = std::cos(angle); + float sine = std::sin(angle); + for (Vector* corner : {&screen._topLeft, &screen._topRight, &screen._bottomLeft, &screen._bottomRight}) + *corner = point_turn(*corner, cosine, sine); + sample = point_turn(sample, cosine, sine); + } + + Vector topLeft = screen._topLeft; + Vector bottomRight = screen._bottomRight; + bool isOverX = topLeft.x < sample.x && sample.x < bottomRight.x; + if (!isOverX || topLeft.y >= sample.y || sample.y >= bottomRight.y) continue; + + float across = std::clamp((sample.x - topLeft.x) / (bottomRight.x - topLeft.x), 0.0f, 1.0f); + float down = std::clamp((sample.y - topLeft.y) / (bottomRight.y - topLeft.y), 0.0f, 1.0f); + float texelX = (source._bottomRight.x - source._topLeft.x) * across + source._topLeft.x; + float texelY = (source._bottomRight.y - source._topLeft.y) * down + source._topLeft.y; + KColor texel = image_texel_get(*state.spriteSheet, (uint32_t)(int)texelX, (uint32_t)(int)texelY); + if (texel._alpha < query.alphaThreshold) continue; + + ColorMod color = sprite.color; + color_multiply(color, state.color); + color_multiply(color, frame.color); + float red = color._tint[0] * texel._red + color._offset[0]; + float green = color._tint[1] * texel._green + color._offset[1]; + float blue = color._tint[2] * texel._blue + color._offset[2]; + return kcolor_rgba(red, green, blue, color._tint[3] * texel._alpha); + } + return {}; +} + +// 0040b590 The color the sprite shows at a screen position: its overlay's, unless that falls short of the alpha, then +// its main animation's. +KColor ANM2::GetTexel(const TexelQuery& query) const +{ + KColor texel = animation_texel_get(*this, overlayAnimState, query); + if (texel._alpha < query.alphaThreshold) texel = animation_texel_get(*this, animState, query); + return texel; +} diff --git a/src/beam_renderer.cpp b/src/beam_renderer.cpp new file mode 100644 index 0000000..cb97e6f --- /dev/null +++ b/src/beam_renderer.cpp @@ -0,0 +1,149 @@ +#include "beam_renderer.h" +#include "fx_layers.h" +#include "kage_graphics.h" +#include "npc_ai.h" +#include "render_passes.h" +#include + +// A point's edges spread along its direction turned a quarter, and a joint's normal is never shortened past this. +constexpr float BEAM_NORMAL_TURN = 1.5707964f; +constexpr float JOINT_DOT_MIN = 0.4f; +constexpr float HALF_WIDTH = 0.5f; + +BeamRenderer g_beamRenderer; + +// The unit direction from one point to another turned a quarter clockwise, the way KAGE turns it (by cos and sin of a +// float quarter turn, so x keeps a trace of the direction). +static Vector normal_get(Vector from, Vector to) +{ + Vector direction = vector_normalized(vector_sub(to, from)); + float cosine = std::cos(BEAM_NORMAL_TURN); + float sine = std::sin(BEAM_NORMAL_TURN); + return vector_make(direction.x * cosine - direction.y * sine, sine * direction.x + cosine * direction.y); +} + +// 0041e4c0 (Point::UpdateNormal) Bends the normal toward the next point: the new segment's normal when it has none, +// else the mean of both, lengthened as the joint sharpens so the strip keeps its width. +void BeamPoint::UpdateNormal(Vector next) +{ + Vector turned = normal_get(pos, next); + if (vector_is_zero(normal)) + { + normal = turned; + return; + } + + Vector mean = vector_add(turned, normal); + Vector unit = vector_length(mean) > 0 ? vector_normalized(mean) : mean; + float sharpness = std::max(vector_dot(normal, unit), JOINT_DOT_MIN); + normal = vector_scale(unit, 1 / sharpness); +} + +// 0041e480 Starts a beam of a sprite's layer, dropping the points of the last one. +void BeamRenderer::Begin(ANM2& beamSprite, int beamLayerId, BeamFrame beamFrame, BeamCoordinate beamCoordinate) +{ + sprite = &beamSprite; + layerId = beamLayerId; + frame = beamFrame; + coordinate = beamCoordinate; + points.clear(); +} + +// 0041e720 Adds a point, its normal along the segment from the last one, whose own normal bends toward it. +void BeamRenderer::Add(BeamPoint point) +{ + point.normal = {}; + if (!points.empty()) + { + point.normal = normal_get(points.back().pos, point.pos); + points.back().UpdateNormal(point.pos); + } + points.push_back(point); +} + +// The color a point draws in over the keyframe's: tints multiplied, offsets added, and the keyframe's colorize taken +// when the point has none, else the mean of both. +static ColorMod point_color(const ColorMod& point, const ColorMod& keyframe) +{ + ColorMod color = point; + for (int channel = 0; channel < 4; channel++) color._tint[channel] *= keyframe._tint[channel]; + for (int channel = 0; channel < 3; channel++) color._offset[channel] += keyframe._offset[channel]; + + bool isKeyframeColorized = keyframe._colorize[0] + keyframe._colorize[1] + keyframe._colorize[2] != 0; + bool isPointColorized = point._colorize[0] + point._colorize[1] + point._colorize[2] != 0; + for (int channel = 0; isKeyframeColorized && channel < 4; channel++) + { + float mean = (keyframe._colorize[channel] + point._colorize[channel]) / 2; + color._colorize[channel] = isPointColorized ? mean : keyframe._colorize[channel]; + } + return color; +} + +// The quad between two points, each edge as wide as the keyframe times the point's width. +static KAGE::Graphics::ColorQuad segment_quad(const BeamPoint& start, const BeamPoint& end, float keyframeWidth) +{ + Vector startEdge = vector_scale(start.normal, keyframeWidth * start.width * HALF_WIDTH); + Vector endEdge = vector_scale(end.normal, keyframeWidth * end.width * HALF_WIDTH); + KAGE::Graphics::ColorQuad quad; + quad._topLeft = vector_add(start.pos, startEdge); + quad._topRight = vector_sub(start.pos, startEdge); + quad._bottomLeft = vector_add(end.pos, endEdge); + quad._bottomRight = vector_sub(end.pos, endEdge); + return quad; +} + +// 0041e960 Draws the strip: the keyframe's spritesheet column stretched along each segment, mirrored when the layer +// and the sprite flip differently, in the layer's blending with the points' colors over the keyframe's. Needs a +// texture, a keyframe and two points. +// The original switches to a per-vertex color shader when the points' colorize or offset differ, and to its static +// shader for ANIM_RENDER_STATIC. Here each segment takes its first point's colorize and offset through the sprite +// shader, as the uniform shader does. +void BeamRenderer::End() +{ + LayerState* layer = sprite ? sprite->GetLayer(layerId) : nullptr; + if (!layer || !layer->spriteSheet || points.size() < 2) return; + + const AnimationState& animation = frame == BEAM_FRAME_OVERLAY ? sprite->overlayAnimState : sprite->animState; + const AnimationFrame* keyframe = animation.GetLayerFrame(layerId); + if (!keyframe) return; + + namespace Graphics = KAGE::Graphics; + using Factor = Graphics::BlendFactor; + Graphics::ImageBase& image = *layer->spriteSheet; + const std::array& mode = layer->blendMode; + Graphics::BlendMode saved = Graphics::manager.blendMode; + Graphics::manager.blendMode = {(Graphics::BlendEquation)mode[BLEND_EQUATION], (Factor)mode[BLEND_RGB_SOURCE], + (Factor)mode[BLEND_RGB_DEST], (Factor)mode[BLEND_ALPHA_SOURCE], + (Factor)mode[BLEND_ALPHA_DEST]}; + + bool isMirrored = layer->isFlipX != sprite->isFlipX; + float left = isMirrored ? keyframe->crop.x + keyframe->width : keyframe->crop.x; + float right = isMirrored ? keyframe->crop.x : keyframe->crop.x + keyframe->width; + float coordinateScale = coordinate == BEAM_COORDINATE_HEIGHTS ? keyframe->height : 1; + for (size_t index = 0; index + 1 < points.size(); index++) + { + const BeamPoint& start = points[index]; + const BeamPoint& end = points[index + 1]; + float top = keyframe->crop.y + start.coordinate * coordinateScale; + float bottom = keyframe->crop.y + end.coordinate * coordinateScale; + SourceQuad source; + source._topLeft = vector_make(left, top); + source._topRight = vector_make(right, top); + source._bottomLeft = vector_make(left, bottom); + source._bottomRight = vector_make(right, bottom); + source._coordinateSpace = Graphics::COORDINATES_PIXEL; + + ColorMod startColor = point_color(start.color, keyframe->color); + ColorMod endColor = point_color(end.color, keyframe->color); + KColor startTint = + kcolor_rgba(startColor._tint[0], startColor._tint[1], startColor._tint[2], startColor._tint[3]); + KColor endTint = kcolor_rgba(endColor._tint[0], endColor._tint[1], endColor._tint[2], endColor._tint[3]); + Graphics::ColorQuad quad = segment_quad(start, end, keyframe->width); + quad.colors = {startTint, startTint, endTint, endTint}; + apply_sprite_shader_params(startColor, SPRITE_SHADER_COLOR_APPLY, image); + image.Render({&source, 1}, {&quad, 1}); + } + + Graphics::manager.blendMode = saved; + Graphics::manager.shader_default_set(); +} diff --git a/src/beam_renderer.h b/src/beam_renderer.h new file mode 100644 index 0000000..994229a --- /dev/null +++ b/src/beam_renderer.h @@ -0,0 +1,48 @@ +#pragma once + +#include "anm2.h" +#include + +// Which animation of the sprite a beam takes its layer's keyframe from. +enum BeamFrame +{ + BEAM_FRAME_MAIN, + BEAM_FRAME_OVERLAY +}; + +// Whether a point's spritesheet coordinate counts pixels down the keyframe, or keyframe heights. +enum BeamCoordinate +{ + BEAM_COORDINATE_PIXELS, + BEAM_COORDINATE_HEIGHTS +}; + +// One point of a beam: where it is, the normal its edges spread along, its width as a scale of the keyframe's, its +// spritesheet coordinate and its color. +struct BeamPoint +{ + ColorMod color = COLOR_DEFAULT; + Vector normal{}; + Vector pos{}; + float coordinate = 0; + float width = 0; + + void UpdateNormal(Vector next); +}; + +// KAGE's strip renderer: a layer of a sprite drawn along the points Add collects between Begin and End, one textured +// quad between each two points. +struct BeamRenderer +{ + std::vector points; + ANM2* sprite = nullptr; + BeamCoordinate coordinate = BEAM_COORDINATE_PIXELS; + BeamFrame frame = BEAM_FRAME_MAIN; + int layerId = 0; + + void Begin(ANM2& beamSprite, int beamLayerId, BeamFrame beamFrame, BeamCoordinate beamCoordinate); + void Add(BeamPoint point); + void End(); +}; + +extern BeamRenderer g_beamRenderer; diff --git a/src/bomb_explosion.cpp b/src/bomb_explosion.cpp index c1e0b68..8c11508 100644 --- a/src/bomb_explosion.cpp +++ b/src/bomb_explosion.cpp @@ -75,7 +75,7 @@ static bool is_scissored(Entity* source) // Room::CheckLine's explosion mode (2): the line walked in steps, cell by cell. A metal block stops it, and so does a // wall, unless it is a door, a wall the check ignores, or a lock Broken Padlock lets the blast through. -static bool explosion_line_clear(const Vector& start, const Vector& end, bool isIgnoreWalls) +bool explosion_line_clear(const Vector& start, const Vector& end, bool isIgnoreWalls) { Room& room = *g_game->room; Vector step = vector_sub(start, end); diff --git a/src/boss_ai.h b/src/boss_ai.h index 5ccf2a9..c26d7fd 100644 --- a/src/boss_ai.h +++ b/src/boss_ai.h @@ -141,6 +141,7 @@ void boss_baby_plum_update(Entity_NPC& npc); void boss_blastocyst_update(Entity_NPC& npc); void boss_cage_update(Entity_NPC& npc); void boss_chub_update(Entity_NPC& npc); +void boss_daddy_long_legs_update(Entity_NPC& npc); void boss_dingle_update(Entity_NPC& npc); void boss_duke_update(Entity_NPC& npc); void boss_famine_update(Entity_NPC& npc); @@ -166,6 +167,9 @@ void boss_peep_update(Entity_NPC& npc); void boss_pestilence_update(Entity_NPC& npc); void boss_polycephalus_update(Entity_NPC& npc); void boss_widow_update(Entity_NPC& npc); +void boss_satan_update(Entity_NPC& npc); +void boss_fallen_update(Entity_NPC& npc); +void boss_music_crossfade(); // Gemini's baby, the variant its twin is tied to. constexpr int GEMINI_BABY = 10; diff --git a/src/boss_daddy_long_legs.cpp b/src/boss_daddy_long_legs.cpp new file mode 100644 index 0000000..2e392e7 --- /dev/null +++ b/src/boss_daddy_long_legs.cpp @@ -0,0 +1,402 @@ +#include "boss_ai.h" +#include "entity_bomb.h" +#include "entity_config.h" +#include "grid_entity_trap_door.h" +#include "npc_caves.h" +#include "room_grid.h" + +// Daddy Long Legs (variant 0) and the Triachnid stomp from above the room: the body (i1 0) rises and drops onto its +// target, or sends down legs (i1 1, copies of itself that each stomp once and vanish), spits spiders or Trites. +constexpr int TRIACHNID = 1; +constexpr int DLL_RISE = NPC_STATE_JUMP; +constexpr int DLL_STOMP = NPC_STATE_STOMP; +constexpr int DLL_SPIT = NPC_STATE_ATTACK; +constexpr int DLL_LEGS = NPC_STATE_ATTACK2; +constexpr int DLL_LEG = 1; +constexpr float DLL_FRICTION = 0.8f; + +// Resting, it acts 1 time in 20: rising, sending legs or spitting, never spitting with 4 or more enemies about. +constexpr uint32_t DLL_ACT_ODDS = 20; +constexpr std::array DLL_ACTIONS = {DLL_RISE, DLL_LEGS, DLL_LEGS, DLL_SPIT, DLL_SPIT}; +constexpr int DLL_CROWD = 4; +constexpr uint32_t DLL_CROWDED_ACTIONS = 3; + +// It stomps 4 times (the Triachnid 3), then 1 time in 7 once more. Its body is half as wide while up. +constexpr int DLL_STOMPS = 4; +constexpr int TRIACHNID_STOMPS = 3; +constexpr uint32_t DLL_EXTRA_STOMP_ODDS = 7; +constexpr int DLL_STOMP_LIMB_LIMIT = 4; +constexpr float DLL_UP_WIDTH = 0.5f; + +// A landing: 300 crushing damage within 44 (50 for a Delirium form). The body's drop rings out shots at 10 (the +// Triachnid's in black and white), a ripple and a grey dust cloud. A leg's stomp puffs dust on it. +constexpr float DLL_CRUSH_DAMAGE = 300; +constexpr float DLL_DELIRIUM_CRUSH_DAMAGE = 50; +constexpr float DLL_CRUSH_RADIUS = 44; +constexpr float DLL_SHOT_SPEED = 10; +constexpr ColorMod TRIACHNID_SHOT_COLOR = {{0, 0, 0, 1}, {0, 0, 0, 0}, {1, 1, 1}}; +constexpr float DLL_DROP_VOLUME = 0.7f; +constexpr int DLL_DROP_SHAKE = 12; +constexpr int DLL_STOMP_SHAKE = 8; +constexpr float DLL_RIPPLE_AMPLITUDE = 0.04f; +constexpr float DLL_RIPPLE_SPEED = 0.025f; +constexpr int DLL_RIPPLE_DURATION = 13; +constexpr ColorMod DLL_DUST_COLOR = {{0.62f, 0.62f, 0.62f, 0.8f}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod DLL_STOMP_DUST_COLOR = {{0.8f, 0.8f, 0.8f, 0.7f}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr int DLL_STOMP_DUST_SUBTYPE = 2; +constexpr float DLL_STOMP_DUST_DROP = 15; +constexpr int DLL_DUST_PRIORITY = 255; + +// The Triachnid's landings leave white creep, twice as large, and its drop spreads more for 24 frames, 50 and 2 a +// frame further out, 1.05 times larger each. +constexpr float TRIACHNID_CREEP_SCALE = 2; +constexpr int TRIACHNID_CREEP_FRAMES = 24; +constexpr float TRIACHNID_CREEP_REACH = 50; +constexpr float TRIACHNID_CREEP_GROWTH = 0.05f; + +// The spit: a grey cloud, then two or three spiders thrown 100 out (at most 3 for a Delirium form), or a Trite. +constexpr ColorMod DLL_CLOUD_COLOR = {{0, 0, 0, 0.55f}, {0, 0, 0, 0}, {0.4f, 0.38f, 0.34f}}; +constexpr float DLL_CLOUD_SCALE = 0.75f; +constexpr float DLL_CLOUD_LIFT = -26; +constexpr int DLL_SPIDERS = 2; +constexpr int DLL_DELIRIUM_SPIDERS = 3; +constexpr float DLL_SPIDER_REACH = 100; +constexpr int DLL_PATH_LIMIT = 951; +constexpr float DLL_SPIDER_ARC = -8; +constexpr float DLL_SPIDER_PACE = 0.04f; +constexpr float DLL_SPIDER_LIFT = 10; +constexpr int TRITE_VARIANT = 1; +constexpr int TRITE_SPIN_UP = 5; + +// The legs: one lands on the target's path (a fraction of 20 frames ahead, 20 around), the rest 80 to 180 from the +// target 1 time in 4, else up to 400 from the body, each scattered 20, 5 picks drawn. They fall 16 frames in, 10 +// apart. +constexpr float LEG_LEAD_FRAMES = 20; +constexpr float LEG_NEAR = 20; +constexpr float LEG_SCATTER = 40; +constexpr float LEG_TARGET_SPREAD = 100; +constexpr float LEG_TARGET_MIN = 80; +constexpr float LEG_BODY_SPREAD = 400; +constexpr int LEG_PICKS = 5; +constexpr int LEG_FIRST_DELAY = 16; +constexpr int LEG_DELAY_STEP = 10; + +// Its death bleeds the walls for 30 frames, 7 drops. +constexpr int DLL_DEATH_BLOOD_FRAMES = 30; +constexpr int DLL_DEATH_BLOOD_DROPS = 7; + +static bool dll_is_calm(Entity_NPC& npc) +{ + return npc.HasEntityFlags(FLAG_DELIRIUM_FORM) && room_is_clear(); +} + +// Its stomp animation: an arm on the first two of a stomp (always for the Triachnid), a leg after, mirrored in turn. +static std::string_view dll_stomp_animation(Entity_NPC& npc, int stomp) +{ + npc.sprite.isFlipX = (stomp & 1) == 0; + return stomp / 2 == 0 || npc.variant == TRIACHNID ? "StompArm" : "StompLeg"; +} + +// Its animation ended: the next stomp or the drop, a rise turning into stomps, else rest. A leg vanishes. +static void dll_animation_end(Entity_NPC& npc) +{ + if (npc.state == DLL_STOMP) + { + if (npc.i1 != 0) return npc.Remove(); + + int stomp = npc.i2++; + int stomps = npc.variant == TRIACHNID ? TRIACHNID_STOMPS : DLL_STOMPS; + if (stomp < stomps || Random() % DLL_EXTRA_STOMP_ODDS == 0) + { + int limb = std::min(npc.i2, DLL_STOMP_LIMB_LIMIT) - 1; + std::string_view animation = dll_stomp_animation(npc, limb); + npc_anim_restart(npc.sprite, animation); + return; + } + npc.state = NPC_STATE_MOVE; + npc.sprite.Play("Down"); + npc.stateFrame = 0; + npc.SetSize(npc.config->collisionRadius, vector_make(-1, -1), -1); + return; + } + if (npc.state == DLL_RISE) + { + npc.state = DLL_STOMP; + npc.SetSize(npc.config->collisionRadius * DLL_UP_WIDTH, vector_make(-1, -1), -1); + return; + } + npc.state = NPC_STATE_IDLE; + npc.sprite.Play("Idle"); +} + +// A landing: the body's drop ripples, rings out shots and kicks up dust, a leg's stomp puffs dust. Both crush what is +// under them, and the Triachnid's leave white creep. +static void dll_land(Entity_NPC& npc) +{ + bool isDrop = npc.state == NPC_STATE_MOVE; + if (isDrop) + { + npc.PlaySound(SOUND_HELLBOSS_GROUNDPOUND, DLL_DROP_VOLUME, 2, false, 1); + shockwave_make(npc.pos, DLL_RIPPLE_AMPLITUDE, DLL_RIPPLE_SPEED, DLL_RIPPLE_DURATION); + game_shake_screen(DLL_DROP_SHAKE); + npc.MakeGroundPoof(npc.pos, DLL_DUST_COLOR, 1); + } + else + { + npc.PlaySound(SOUND_FORESTBOSS_STOMPS, 1, 2, false, 1); + game_shake_screen(DLL_STOMP_SHAKE); + auto* dust = static_cast(g_game->Spawn({.position = npc.pos, + .spawner = &npc, + .subType = DLL_STOMP_DUST_SUBTYPE, + .type = ENTITY_EFFECT, + .variant = EFFECT_POOF02, + .seed = Random()})); + bool isFlipped = (Random() & 1) == 0; + dust->sprite.offset = vector_make(0, DLL_STOMP_DUST_DROP); + dust->sprite.isFlipX = isFlipped; + dust->SetColor(DLL_STOMP_DUST_COLOR, -1, DLL_DUST_PRIORITY, false, true); + dust->FollowParent(&npc); + dust->Update(); + } + + float damage = npc.HasEntityFlags(FLAG_DELIRIUM_FORM) ? DLL_DELIRIUM_CRUSH_DAMAGE : DLL_CRUSH_DAMAGE; + explosion_damage({.position = npc.pos, + .source = &npc, + .damageFlags = DAMAGE_CRUSH, + .damage = damage, + .radius = DLL_CRUSH_RADIUS, + .isLineCheck = false}); + if (isDrop) + { + ProjectileParams params; + if (npc.variant == TRIACHNID) + { + std::ranges::copy(TRIACHNID_SHOT_COLOR._tint, params.color._tint); + std::ranges::copy(TRIACHNID_SHOT_COLOR._offset, params.color._offset); + } + npc.FireProjectiles(npc.pos, vector_make(DLL_SHOT_SPEED, 0), PROJECTILES_EIGHT, params); + } + if (npc.variant != TRIACHNID) return; + + Entity* creep = g_game->Spawn({.position = npc.pos, .spawner = &npc, .type = ENTITY_EFFECT, .variant = EFFECT_CREEP_WHITE, .seed = Random()}); + creep->sprite.scale = vector_make(TRIACHNID_CREEP_SCALE, TRIACHNID_CREEP_SCALE); + creep->Update(); +} + +// Resting: 1 time in 20 it picks its next move. +static void dll_rest(Entity_NPC& npc) +{ + if (dll_is_calm(npc) || Random() % DLL_ACT_ODDS != 0) return; + + uint32_t choices = g_game->room->GetAliveEnemiesCount() < DLL_CROWD ? (uint32_t)DLL_ACTIONS.size() : DLL_CROWDED_ACTIONS; + npc.state = DLL_ACTIONS[Random() % choices]; + npc.stateFrame = 0; + npc.i2 = 0; +} + +// Dropping: harmless until it lands, the Triachnid spreading creep after, and on its first frame it hangs over its +// target's column. +static void dll_drop(Entity_NPC& npc, int ticks) +{ + npc.sprite.Play("Down"); + bool isLanded = npc.sprite.WasEventTriggered("Land"); + npc.entityCollisionClass = isLanded ? ENTCOLL_ALL : ENTCOLL_NONE; + for (int tick = 0; isLanded && tick < ticks; tick++) + { + npc.stateFrame++; + if (npc.variant != TRIACHNID || npc.stateFrame >= TRIACHNID_CREEP_FRAMES) continue; + + float angle = random_unit() * RANDOM_HALF_TURN; + angle += angle; + float reach = (float)npc.stateFrame + (float)npc.stateFrame + TRIACHNID_CREEP_REACH; + Vector at = vector_make(std::cos(angle) * reach + npc.pos.x, std::sin(angle) * reach + npc.pos.y); + Entity* creep = g_game->Spawn({.position = at, .spawner = &npc, .type = ENTITY_EFFECT, .variant = EFFECT_CREEP_WHITE, .seed = Random()}); + float growth = (float)npc.stateFrame * TRIACHNID_CREEP_GROWTH + 1; + creep->sprite.scale = vector_make(growth, growth); + creep->Update(); + } + if (npc.sprite.GetFrame() == 0) npc.pos = vector_make(npc.GetPlayerTarget()->pos.x, npc.targetPosition.y); +} + +// Stomping: the body hovers over its target on each stomp's first frame, a leg waits out its delay first. +static void dll_stomp(Entity_NPC& npc, int ticks) +{ + if (npc.projectileDelay >= 1) + { + npc.projectileDelay -= ticks; + if (npc.projectileDelay <= 0) npc.sprite.Play("StompArm", PLAY_FORCED); + return; + } + + bool isDown = !npc.sprite.WasEventTriggered("Jump") && npc.sprite.WasEventTriggered("Land"); + npc.entityCollisionClass = isDown ? ENTCOLL_ALL : ENTCOLL_NONE; + if (npc.i1 == 0) + { + if (npc.sprite.GetFrame() == 0) npc.pos = npc.GetPlayerTarget()->pos; + return; + } + std::string_view animation = dll_stomp_animation(npc, std::min(npc.i2, DLL_STOMP_LIMB_LIMIT)); + npc.sprite.Play(animation); +} + +// One spider thrown out of the body to a free spot, its spot marked off for walkers. +static void dll_spider_throw(Entity_NPC& npc) +{ + Vector spot = room_free_pickup_position_find({.position = npc.pos, .step = DLL_SPIDER_REACH}); + auto* spider = static_cast(g_game->Spawn({.position = spot, .spawner = &npc, .type = ENTITY_SPIDER, .seed = Random()})); + + Room& room = *g_game->room; + int column = (int)((spot.x - GRID_ORIGIN_X) / GRID_CELL_SIZE + 0.5f); + int row = (int)((spot.y - GRID_ORIGIN_Y) / GRID_CELL_SIZE + 0.5f); + if (column >= 0 && column < room.gridWidth && row >= 0 && row < room.gridHeight) + { + int cell = row * room.gridWidth + column; + if (cell < ROOM_GRID_CELLS && room.gridPaths[cell] < DLL_PATH_LIMIT) room.gridPaths[cell] = GRID_PATH_FREED; + } + + spider->targetPosition = spider->pos; + spider->pos = npc.pos; + spider->state = NPC_STATE_JUMP; + spider->v2.y = DLL_SPIDER_ARC; + spider->velocity = vector_scale(vector_sub(spider->targetPosition, npc.pos), DLL_SPIDER_PACE); + spider->v1 = spider->velocity; + spider->posOffset.y -= DLL_SPIDER_LIFT; +} + +// The spit: on Shoot a cloud, then spiders (Daddy Long Legs) or a hopping Trite (the Triachnid). +static void dll_spit(Entity_NPC& npc) +{ + npc.sprite.Play("Attack1"); + if (!npc.sprite.IsEventTriggered("Shoot")) return; + + npc.PlaySound(SOUND_BOSS_SPIT_BLOB_BARF, 1, 2, false, 1); + Entity_Effect* cloud = npc.MakeBloodCloud(npc.pos, DLL_CLOUD_COLOR, DLL_CLOUD_SCALE); + cloud->posOffset = vector_make(0, DLL_CLOUD_LIFT); + if (npc.variant == 0) + { + int count = (int)(Random() & 1) + DLL_SPIDERS; + if (npc.HasEntityFlags(FLAG_DELIRIUM_FORM)) + count = std::min(count, DLL_DELIRIUM_SPIDERS - npc.CountRelatedEntities(ENTITY_SPIDER, 0, nullptr)); + for (int i = 0; i < count; i++) dll_spider_throw(npc); + return; + } + + if (npc.HasEntityFlags(FLAG_DELIRIUM_FORM) && + (uint32_t)npc.CountRelatedEntities(ENTITY_HOPPER, TRITE_VARIANT, nullptr) >= DLL_DELIRIUM_SPIDERS) + return; + auto* trite = static_cast(g_game->Spawn({.position = npc.pos, .spawner = &npc, .type = ENTITY_HOPPER, .variant = TRITE_VARIANT, .seed = Random()})); + trite->targetPosition = npc.GetPlayerTarget()->pos; + trite->state = NPC_STATE_MOVE; + trite->stateFrame = TRITE_SPIN_UP; + npc_anim_restart(trite->sprite, "Hop"); + if (trite->sprite.animState.animData) trite->sprite.animState.SetFrameFloat(TRITE_SPIN_UP); +} + +// Where a leg falls: on its target's path for the chosen one, else near the target or anywhere around the body. +static Vector dll_leg_spot(Entity_NPC& npc, bool isOnTarget) +{ + Entity* target = npc.GetPlayerTarget(); + Vector spot{}; + if (isOnTarget) + { + Vector lead = vector_add(target->pos, vector_scale(target->velocity, random_unit() * LEG_LEAD_FRAMES)); + spot = room_free_pickup_position_find({.position = lead, .step = LEG_NEAR}); + float y = random_unit() * LEG_SCATTER - LEG_SCATTER / 2; + return vector_make(random_unit() * LEG_SCATTER - LEG_SCATTER / 2 + spot.x, y + spot.y); + } + + bool isNearTarget = (Random() & 3) == 0; + Vector result{}; + for (int pick = 0; pick < LEG_PICKS; pick++) + { + FreeSpotSearch search{.isAvoidActiveEntities = true}; + search.position = isNearTarget ? target->pos : npc.pos; + search.step = isNearTarget ? random_unit() * LEG_TARGET_SPREAD + LEG_TARGET_MIN : random_unit() * LEG_BODY_SPREAD; + spot = room_free_pickup_position_find(search); + float y = random_unit() * LEG_SCATTER - LEG_SCATTER / 2; + result = vector_make(random_unit() * LEG_SCATTER - LEG_SCATTER / 2 + spot.x, y + spot.y); + } + return result; +} + +// The legs: on its first frame it sends 4 (the Triachnid 3) stomping copies down in turn, one on its target. +static void dll_legs(Entity_NPC& npc) +{ + npc.sprite.Play("Attack2"); + bool isDown = !npc.sprite.WasEventTriggered("Jump") || npc.sprite.WasEventTriggered("Land"); + npc.entityCollisionClass = isDown ? ENTCOLL_ALL : ENTCOLL_NONE; + if (npc.stateFrame != 0) return; + + npc.stateFrame = 1; + int count = npc.variant == TRIACHNID ? TRIACHNID_STOMPS : DLL_STOMPS; + int onTarget = random_below(count); + int delay = LEG_FIRST_DELAY; + for (int leg = 0; leg < count; leg++) + { + Vector spot = dll_leg_spot(npc, leg == onTarget); + auto* copy = static_cast(g_game->Spawn({.position = spot, .spawner = &npc, .type = npc.type, .variant = npc.variant, .seed = Random()})); + copy->AddEntityFlags(FLAG_DONT_COUNT_BOSS_HP); + copy->i1 = DLL_LEG; + copy->state = DLL_STOMP; + copy->i2 = npc.i2++; + copy->projectileDelay = delay; + if (copy->sprite.SetAnimation("StompArm", SWITCH_KEEP_FRAME) && copy->sprite.animState.animData) + { + copy->sprite.animState.SetFrameFloat(0); + copy->sprite.animState.isPlaying = false; + } + copy->entityCollisionClass = ENTCOLL_NONE; + copy->SetSize(npc.config->collisionRadius * DLL_UP_WIDTH, vector_make(-1, -1), -1); + delay += LEG_DELAY_STEP; + } +} + +// 00468180 NpcAI::ENTITY_DADDYLONGLEGS: Daddy Long Legs and the Triachnid rest, rise and stomp down on their target, +// send stomping legs, or spit spiders or Trites. Their own legs cannot hurt them. +void boss_daddy_long_legs_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_INIT) + { + npc.targetPosition = npc.pos; + npc.state = NPC_STATE_IDLE; + return; + } + + if (npc_anim_is_done(npc) && npc.projectileDelay < 1) dll_animation_end(npc); + bool isLanding = npc.state == NPC_STATE_MOVE || npc.state == DLL_STOMP; + if (isLanding && npc.sprite.animState.animData && npc.sprite.IsEventTriggered("Land")) dll_land(npc); + + int ticks = npc_ticks_get(npc); + npc.friction *= DLL_FRICTION; + switch (npc.state) + { + case NPC_STATE_IDLE: + dll_rest(npc); + break; + case NPC_STATE_MOVE: + dll_drop(npc, ticks); + break; + case DLL_RISE: + npc.entityCollisionClass = npc.sprite.WasEventTriggered("Jump") ? ENTCOLL_NONE : ENTCOLL_ALL; + npc.sprite.Play("Up"); + break; + case DLL_STOMP: + dll_stomp(npc, ticks); + break; + case DLL_SPIT: + dll_spit(npc); + break; + case DLL_LEGS: + dll_legs(npc); + break; + } + + if (npc.pendingDamage > 0) + for (DamageEvent& event : npc.damageEvents) + if (event.source.type == ENTITY_DADDYLONGLEGS) event.damage = 0; + if (!npc.isDead || npc.i1 != 0) return; + + Room& room = *g_game->room; + room.bloodFromWallsDuration = DLL_DEATH_BLOOD_FRAMES; + room.bloodFromWallsCount = DLL_DEATH_BLOOD_DROPS; +} diff --git a/src/boss_death.cpp b/src/boss_death.cpp index db45bdf..1a77e8b 100644 --- a/src/boss_death.cpp +++ b/src/boss_death.cpp @@ -21,10 +21,6 @@ #include #include -constexpr int ENTITY_SLOTH = 46; -constexpr int ENTITY_ENVY = 51; -constexpr int ENTITY_PRIDE = 52; -constexpr int ENTITY_FALLEN = 81; constexpr int VARIANT_SUPER = 1; constexpr int VARIANT_ULTRA_PRIDE = 2; constexpr int VARIANT_KRAMPUS = 1; diff --git a/src/boss_fallen.cpp b/src/boss_fallen.cpp new file mode 100644 index 0000000..7b0a5c0 --- /dev/null +++ b/src/boss_fallen.cpp @@ -0,0 +1,340 @@ +#include "boss_ai.h" +#include "entity_laser.h" +#include "npc_caves.h" +#include "sfx_manager.h" +#include + +// The Fallen's moves (states): a spread of shots, a charge, a cross of beams, and Krampus's spinning cross. +enum FallenState +{ + FALLEN_SHOTS = NPC_STATE_ATTACK, + FALLEN_CHARGE = NPC_STATE_ATTACK2, + FALLEN_CROSS = NPC_STATE_ATTACK3, + FALLEN_SPIN = NPC_STATE_ATTACK4, + FALLEN_SPLIT = NPC_STATE_SUMMON +}; + +constexpr int KRAMPUS = 1; +constexpr float FALLEN_FRICTION = 0.8f; + +// Walking about, it acts one frame in three (its halves every frame): a charge one roll in 80, Krampus's beams one in +// 20 lined up within 20 and 400 of the target (or one in 200 anyway), else one in 20 the shots within 230. +constexpr float WALK_SPEED = 1; +constexpr float FALLEN_WALK_THRESHOLD = 3; +constexpr int FALLEN_ACT_ODDS = 3; +constexpr int CHARGE_ODDS = 80; +constexpr int KRAMPUS_BEAM_ODDS = 20; +constexpr int KRAMPUS_BEAM_ANYWAY_ODDS = 200; +constexpr float KRAMPUS_LINE_UP = 20; +constexpr float KRAMPUS_BEAM_REACH = 400; +constexpr int SHOTS_ODDS = 20; +constexpr float SHOTS_REACH = 230; + +// The shots: three (four on Shoot2) at 8.2 toward the target 10 frames ahead. Krampus follows them with his beams one +// time in three. +constexpr float SHOT_LEAD_FRAMES = 10; +constexpr float FALLEN_SHOT_SPEED = 8.2f; + +// The charge: it chases the target's spot 10 frames ahead at 1.4, growling from frame 120, until an eighth of its +// health is hurt away, when it turns to its beams. +constexpr float CHARGE_LEAD_FRAMES = 10; +constexpr float CHARGE_ACCEL = 1.4f; +constexpr int CHARGE_GROWL_FRAMES = 119; +constexpr int CHARGE_GROWL_ODDS = 60; +constexpr int CHARGE_GROWL_DELAY = 120; +constexpr float CHARGE_HURT_SHARE = 0.125f; + +// The beams: four brimstone beams for 30 frames from 10 out (20 up), a diagonal cross for Krampus one time in two (and +// in his first 60 frames), or his spin, which turns a quarter at 2 a frame after 30 frames for 50. Tracers show the +// way 22 frames ahead (32 for Krampus). Between Shoot2 and its end it drifts to the target at 8 to 15 a frame. +constexpr int BEAMS = 4; +constexpr float BEAM_TURN = 90; +constexpr float BEAM_DIAGONAL = 45; +constexpr float BEAM_OUT = 10; +constexpr float FALLEN_BEAM_RISE = 20; +constexpr float FALLEN_BEAM_DEPTH = -10; +constexpr int FALLEN_BEAM_TIMEOUT = 30; +constexpr int SPIN_TIMEOUT = 50; +constexpr int SPIN_DELAY = 30; +constexpr float SPIN_TURN = 90; +constexpr float SPIN_SPEED = 2; +constexpr int YOUNG_FRAMES = 60; +constexpr float TRACER_RISE = 40; +constexpr float FALLEN_TRACER_SCALE = 4; +constexpr int FALLEN_TRACER_TIMEOUT = 22; +constexpr int TRACER_TIMEOUT_KRAMPUS = 32; +constexpr ColorMod FALLEN_TRACER_COLOR = {{0.6f, 0.05f, 0, 0.8f}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr float DRIFT_MARGIN = 100; +constexpr float DRIFT_SCALE = 0.05f; +constexpr float DRIFT_MIN = 8; +constexpr float DRIFT_MAX = 15; +constexpr float DRIFT_DECAY = 0.2f; + +// Below half health the Fallen (not its halves, nor Krampus) splits into two halves of three quarters, 30 to each side +// and 20 up, each with half its health (20 as Delirium's form), with two black puffs. +constexpr float SPLIT_HEALTH = 0.5f; +constexpr float FALLEN_SPLIT_SCALE = 0.75f; +constexpr float DELIRIUM_SPLIT_HEALTH = 20; +constexpr float SPLIT_PUFF_TURN = 30; +constexpr int SPLIT_PUFF_SIZE = 3; +constexpr float SPLIT_VOLUME = 2; +constexpr ColorMod SPLIT_PUFF_COLOR = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +static const Vector SPLIT_SPOTS[] = {vector_make(30, -20), vector_make(-30, -20)}; + +// The wing beats' sounds, at the pitch its size gives. +static void wing_sounds_play(Entity_NPC& npc) +{ + if (!npc.sprite.animState.animData) return; + if (npc.sprite.IsEventTriggered("FlapChase")) npc_sound_play(SOUND_FALLEN_FLAP_CHASE, 1, 2, champion_pitch_get(npc)); + if (npc.sprite.IsEventTriggered("Flap")) npc_sound_play(SOUND_FALLEN_FLAP, 1, 2, champion_pitch_get(npc)); + if (npc.sprite.IsEventTriggered("OpenWings")) npc_sound_play(SOUND_FALLEN_OPEN_WINGS, 1, 2, champion_pitch_get(npc)); +} + +// The beams' tracers, showing where the cross will fire. +static void tracers_spawn(Entity_NPC& npc) +{ + int timeout = npc.variant == KRAMPUS ? TRACER_TIMEOUT_KRAMPUS : FALLEN_TRACER_TIMEOUT; + float turn = npc.i1 ? BEAM_DIAGONAL : 0; + for (int i = 0; i < BEAMS; i++) + following_effect_spawn(npc, {.offset = vector_make(0, -TRACER_RISE), + .targetPosition = vector_from_angle((float)i * BEAM_TURN + turn), + .color = FALLEN_TRACER_COLOR, + .scale = FALLEN_TRACER_SCALE, + .timeout = timeout}); +} + +// Whether Krampus's cross fires diagonally: one time in two, and always while he is young. +static bool is_cross_diagonal(Entity_NPC& npc) +{ + return npc.variant == KRAMPUS && npc.state == FALLEN_CROSS && + ((Random() & 1) == 0 || g_game->frameCount - npc.spawnFrame < YOUNG_FRAMES); +} + +// Starts the beams with a yell: the cross, or for Krampus one time in four the spin. +static void beams_start(Entity_NPC& npc) +{ + npc.PlaySound(SOUND_MONSTER_YELL_B, 1, 2, false, 1); + npc.state = FALLEN_CROSS; + if (npc.variant == KRAMPUS && (Random() & 3) == 0) npc.state = FALLEN_SPIN; + npc.i1 = is_cross_diagonal(npc); + tracers_spawn(npc); + npc.stateFrame = 0; + npc.v1.x = 0; +} + +// Walking about at random, and now and then the charge, Krampus's beams or the shots. +static void walk_update(Entity_NPC& npc) +{ + npc.pathfinder.MoveRandomlyAxisAligned(WALK_SPEED, STATUS_OBEYED); + npc.AnimWalkFrame("Walk", "Walk", FALLEN_WALK_THRESHOLD); + if (npc.HasEntityFlags(FLAG_DELIRIUM_FORM) && room_is_clear()) return; + if (Random() % FALLEN_ACT_ODDS != 0 && npc.spawnerType != npc.type) return; + + Vector toTarget = vector_sub(npc.GetPlayerTarget()->pos, npc.pos); + if (Random() % CHARGE_ODDS == 0 && npc.variant == 0) + { + npc.PlaySound(SOUND_MONSTER_YELL_B, 1, 2, false, 1); + npc.state = FALLEN_CHARGE; + npc.stateFrame = 0; + return; + } + + bool isLinedUp = (std::abs(toTarget.x) < KRAMPUS_LINE_UP || std::abs(toTarget.y) < KRAMPUS_LINE_UP) && + vector_length(toTarget) < KRAMPUS_BEAM_REACH; + bool isBeams = npc.variant == KRAMPUS && + ((Random() % KRAMPUS_BEAM_ODDS == 0 && isLinedUp) || Random() % KRAMPUS_BEAM_ANYWAY_ODDS == 0); + if (isBeams) return beams_start(npc); + if (Random() % SHOTS_ODDS != 0 || vector_length(toTarget) >= SHOTS_REACH) return; + + npc.sprite.isFlipX = toTarget.x < 0; + npc.state = FALLEN_SHOTS; + npc.stateFrame = 0; +} + +// The shots on Shoot (three) and Shoot2 (four), then walking on, or Krampus's beams one time in three. +static void shots_update(Entity_NPC& npc) +{ + npc.stateFrame++; + npc.sprite.Play("Attack1"); + if (npc.sprite.animState.animData) + { + bool isShoot = npc.sprite.IsEventTriggered("Shoot"); + if (isShoot || npc.sprite.IsEventTriggered("Shoot2")) + { + npc.PlaySound(isShoot ? SOUND_MONSTER_GRUNT_2 : SOUND_MONSTER_GRUNT_1, 1, 2, false, 1); + Entity& target = *npc.GetPlayerTarget(); + Vector aim = vector_sub(vector_add(vector_scale(target.velocity, SHOT_LEAD_FRAMES), target.pos), npc.pos); + Vector velocity = vector_scale(vector_normalized(aim), FALLEN_SHOT_SPEED); + npc.FireProjectiles(npc.pos, velocity, isShoot ? PROJECTILES_THREE : PROJECTILES_FOUR, ProjectileParams()); + return; + } + if (!npc_anim_is_done(npc)) return; + } + if (Random() % FALLEN_ACT_ODDS != 0 || npc.variant != KRAMPUS) + { + npc.state = NPC_STATE_MOVE; + return; + } + beams_start(npc); +} + +// The charge: it chases its target, growling after a while, until hurt enough, then fires its cross. +static void charge_update(Entity_NPC& npc) +{ + if (npc.stateFrame == 0) + { + npc.sprite.Play("ChargeStart"); + npc.stateFrame++; + } + else if (npc_anim_is_done(npc)) npc.sprite.Play("Charge"); + if (!npc.sprite.IsPlaying("Charge")) return; + + if (npc.stateFrame++ > CHARGE_GROWL_FRAMES && Random() % CHARGE_GROWL_ODDS != 0) + npc.PlaySound(SOUND_FALLEN_GROWL, 1, CHARGE_GROWL_DELAY, false, 1); + Vector aim = vector_add(npc.CalcTargetPosition(0), vector_scale(npc.GetPlayerTarget()->velocity, CHARGE_LEAD_FRAMES)); + Vector toAim = vector_sub(aim, npc.pos); + npc_push(npc, vector_scale(vector_normalized(toAim), CHARGE_ACCEL)); + npc.v1.x += npc.pendingDamage; + npc.sprite.isFlipX = toAim.x < 0; + if (npc.v1.x <= npc.maxHitPoints * CHARGE_HURT_SHARE) return; + + npc.state = FALLEN_CROSS; + npc.stateFrame = 0; + npc.v1.x = 0; + npc.i1 = is_cross_diagonal(npc); + tracers_spawn(npc); +} + +// An angle brought within -180 to 180, as the beams take it. +static float angle_wrap(float degrees) +{ + if (std::abs(degrees) > 360) degrees = std::fmod(degrees, 360.0f); + if (degrees > 180) return degrees - 360; + return degrees < -180 ? degrees + 360 : degrees; +} + +// The cross of four beams on Shoot, the spin's turning a quarter either way. From Shoot2 it drifts toward the target, +// slowing to a stop. +static void beams_update(Entity_NPC& npc) +{ + bool isSpin = npc.state == FALLEN_SPIN; + npc.sprite.Play(isSpin ? "Attack2Alt" : "Attack2"); + if (npc.sprite.animState.animData && npc.sprite.IsEventTriggered("Shoot2")) + { + Vector spot = g_game->room->GetClampedPositionImpl(npc.GetPlayerTarget()->pos, DRIFT_MARGIN, DRIFT_MARGIN, + DRIFT_MARGIN, DRIFT_MARGIN); + Vector drift = vector_scale(vector_sub(spot, npc.pos), DRIFT_SCALE); + float speed = vector_length(drift); + if (speed < DRIFT_MIN && speed > 0) drift = vector_scale(drift, DRIFT_MIN / speed); + else if (speed > DRIFT_MAX) drift = vector_scale(drift, DRIFT_MAX / speed); + npc.targetPosition = drift; + npc.v1.y = 1; + npc.sprite.isFlipX = drift.x < 0; + } + else if (npc.sprite.WasEventTriggered("Shoot2") && npc.v1.y > 0) + { + npc.velocity = vector_add(npc.velocity, vector_scale(npc.targetPosition, npc.v1.y * npc.speedMultiplier)); + npc.v1.y = std::max(npc.v1.y - npc.speedMultiplier * DRIFT_DECAY, 0.0f); + } + npc.stateFrame++; + + if (npc.sprite.animState.animData) + { + if (npc.sprite.IsEventTriggered("Shoot")) + { + float spin = (Random() & 1) ? -1.0f : 1.0f; + float turn = npc.variant == KRAMPUS && npc.state == FALLEN_CROSS && npc.i1 ? BEAM_DIAGONAL : 0; + for (int i = 0; i < BEAMS; i++) + { + float angle = (float)i * BEAM_TURN + turn; + Vector from = isSpin ? npc.pos : vector_add(npc.pos, vector_make(std::cos(angle * DEGREES_TO_RADIANS) * BEAM_OUT, + std::sin(angle * DEGREES_TO_RADIANS) * BEAM_OUT - FALLEN_BEAM_RISE)); + Entity_Laser* laser = Entity_Laser::ShootAngle({.position = from, + .posOffset = vector_make(0, -FALLEN_BEAM_RISE), + .source = &npc, + .angleDegrees = angle_wrap(angle), + .timeout = isSpin ? SPIN_TIMEOUT : FALLEN_BEAM_TIMEOUT, + .variant = LASER_THICK_RED}); + laser->renderDepthOffset = FALLEN_BEAM_DEPTH; + if (isSpin) + { + laser->isActiveRotating = true; + laser->rotationDelay = SPIN_DELAY; + laser->rotationDegrees = spin * SPIN_TURN; + laser->rotationSpd = spin * SPIN_SPEED; + } + laser->Update(); + } + return; + } + if (!npc_anim_is_done(npc)) return; + } + npc.state = NPC_STATE_MOVE; +} + +// The split: once its animation ends, two black puffs and two smaller halves take its place. +static void split_update(Entity_NPC& npc) +{ + npc.sprite.Play("Split"); + npc.stateFrame++; + npc.entityCollisionClass = ENTCOLL_NONE; + if (!npc_anim_is_done(npc)) return; + + npc.PlaySound(SOUND_SUMMONSOUND, SPLIT_VOLUME, 2, false, 1); + for (int i = -1; i <= 0; i++) + { + auto* puff = static_cast(g_game->Spawn({.position = npc.pos, .spawner = &npc, + .subType = SPLIT_PUFF_SIZE, .type = ENTITY_EFFECT, + .variant = EFFECT_POOF01, .seed = Random()})); + puff->SetColor(SPLIT_PUFF_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + puff->rotation = (float)i * SPLIT_PUFF_TURN; + } + for (const Vector& spot : SPLIT_SPOTS) + { + auto* half = static_cast(g_game->Spawn({.position = vector_add(npc.pos, spot), .spawner = &npc, + .type = npc.type, .variant = npc.variant, + .seed = Random()})); + half->health *= SPLIT_HEALTH; + if (npc.HasEntityFlags(FLAG_DELIRIUM_FORM)) + { + half->maxHitPoints = DELIRIUM_SPLIT_HEALTH; + half->health = DELIRIUM_SPLIT_HEALTH; + } + half->scale = FALLEN_SPLIT_SCALE; + half->sprite.scale = vector_make(half->shrinkStatus1 * FALLEN_SPLIT_SCALE, half->shrinkStatus1 * FALLEN_SPLIT_SCALE); + } + npc.Kill(EntityRef()); +} + +// 0045b830 The Fallen (81) and Krampus (81.1): wanders and shoots, charges, fires crosses of beams, and the Fallen +// splits in two below half health. +void boss_fallen_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_INIT) + { + npc.state = NPC_STATE_MOVE; + return; + } + wing_sounds_play(npc); + npc.friction *= FALLEN_FRICTION; + + bool isWhole = npc.spawnerType != npc.type && npc.variant == 0; + if (npc.health / npc.maxHitPoints < SPLIT_HEALTH && isWhole && npc.state != FALLEN_SPLIT) + { + npc.PlaySound(SOUND_MONSTER_ROAR_2, 1, 2, false, 1); + npc.state = FALLEN_SPLIT; + npc.stateFrame = 0; + npc.health = std::max(npc.health, 1.0f); + npc.isDead = false; + } + + switch (npc.state) + { + case NPC_STATE_MOVE: return walk_update(npc); + case FALLEN_SHOTS: return shots_update(npc); + case FALLEN_CHARGE: return charge_update(npc); + case FALLEN_CROSS: + case FALLEN_SPIN: return beams_update(npc); + case FALLEN_SPLIT: return split_update(npc); + } +} diff --git a/src/boss_satan.cpp b/src/boss_satan.cpp new file mode 100644 index 0000000..672c52e --- /dev/null +++ b/src/boss_satan.cpp @@ -0,0 +1,586 @@ +#include "boss_ai.h" +#include "entity_bomb.h" +#include "entity_config.h" +#include "entity_laser.h" +#include "grid_entity_trap_door.h" +#include "manager.h" +#include "music_manager.h" +#include "npc_caves.h" +#include "room_grid.h" +#include "sfx_manager.h" +#include +#include +#include + +// Satan's phases (his i1): the statue, waiting while the Fallen fights, the fight, his death, and the feet he leaves. +enum SatanPhase +{ + SATAN_STATUE, + SATAN_AWAKENING, + SATAN_FIGHT, + SATAN_DYING, + SATAN_FEET +}; + +// His attacks (states): a spread of shots, a brimstone beam straight down, two sweeping beams, and two shot fans. +enum SatanAttack +{ + SATAN_SPREAD = NPC_STATE_ATTACK, + SATAN_BEAM = NPC_STATE_ATTACK2, + SATAN_SWEEP = NPC_STATE_ATTACK3, + SATAN_FANS = NPC_STATE_ATTACK4 +}; + +constexpr int SATAN_FEET_VARIANT = 10; +constexpr float SATAN_FRICTION = 0.8f; +constexpr int KAMIKAZE_LEECH = 1; + +// The statue sinks 80 into the floor, blocks its cell's path and wakes 130 frames in, calling the Fallen and two +// kamikaze leeches 30 below it (50 to each side). Satan rises 25 frames after he is the last enemy left. +constexpr float SATAN_STATUE_SINK = 80; +constexpr int STATUE_PATH_BLOCKED = 2000; +constexpr int STATUE_PATH_AWAKE = 1000; +constexpr int STATUE_SOUND_FRAME = 2; +constexpr int STATUE_WAKE_FRAMES = 130; +constexpr float SUMMON_DROP = 30; +constexpr float LEECH_SPREAD = 50; +constexpr int RISE_FRAME = 25; +constexpr float BOSS_MUSIC_FADE = 0.08f; + +// The fight: Satan keeps below y 245 and 120 from the side walls, walks toward a spot 60 above his target (93% of its +// height, at least 305), leading it by 25 frames of its speed, and steps at most 15 across and 7 down a frame. +constexpr float FIGHT_TOP = 245; +constexpr float WALK_TARGET_SCALE = 0.93f; +constexpr float WALK_TARGET_MIN = 305; +constexpr float WALK_TARGET_RISE = 60; +constexpr float WALK_LEAD_FRAMES = 25; +constexpr float WALK_STEP_X = 15; +constexpr float WALK_STEP_Y = 7; +constexpr float WALK_ACCEL = 0.1f; +constexpr float SIDE_MARGIN = 120; + +// The attack choices: a beam when the target crosses beneath him (above 70 over his aim), one roll in 15 for a spread +// (3 in 10) or the fans, and the sweep for a target 40 to 200 to the side. +constexpr float BEAM_REACH_UP = -70; +constexpr int BEAM_REPEAT_ODDS = 10; +constexpr float SWEEP_REPEAT_REACH = 40; +constexpr int SWEEP_REPEAT_ODDS = 3; +constexpr int SHOT_ODDS = 15; +constexpr int SPREAD_ODDS = 10; +constexpr int SPREAD_IN_TEN = 3; +constexpr int ATTACK_ODDS = 3; +constexpr float WALK_ONLY_REACH = 100; +constexpr float SWEEP_REACH_MIN = 40; +constexpr float SWEEP_LEAD_MAX = 200; + +// The spread: big shots aimed 5 frames ahead, five (four on Shoot2) at 8.2 (10 past 300) times 0.85, again from frame +// 10 unless the target is 300 away or one roll in 3. +constexpr float SPREAD_LEAD_FRAMES = 5; +constexpr float SPREAD_SCALE = 1.4f; +constexpr float SPREAD_SPREAD = 1.15f; +constexpr float SPREAD_FALL_ACCEL = -0.07f; +constexpr float SPREAD_HEIGHT = -40; +constexpr float SPREAD_FALL_SPEED = 5.5f; +constexpr float SPREAD_FAR = 300; +constexpr float SPREAD_SPEED = 8.2f; +constexpr float SPREAD_SPEED_FAR = 10; +constexpr float SPREAD_SPEED_SCALE = 0.85f; +constexpr float SPREAD_REPEAT_FRAME = 10; + +// The beams: a straight one 60 above him for 16 frames, 1.2 wide, and two that sweep 1.5 a frame from 40 to each side +// of straight down, 100 out, for 14 frames. He shakes 10 (5 for the sweeps and fans) while they fire. +constexpr float SATAN_BEAM_RISE = 60; +constexpr float BEAM_ANGLE = 90; +constexpr int SATAN_BEAM_TIMEOUT = 16; +constexpr float BEAM_SCALE = 1.2f; +constexpr float SATAN_BEAM_DEPTH = 3000; +constexpr float BEAM_RECOIL = 5; +constexpr float BEAM_SHAKE = 10; +constexpr float SWEEP_SHAKE = 5; +constexpr int SATAN_SWEEP_TIMEOUT = 14; +constexpr float SWEEP_REACH = 100; +constexpr float SWEEP_ROTATION = 40; +constexpr float SATAN_SWEEP_SPEED = 1.5f; +constexpr float SWEEP_ANGLE_LEFT = 120; +constexpr float SWEEP_ANGLE_RIGHT = 60; +constexpr float SWEEP_RECOIL = 2.5f; + +// The fans: a ring each side, 100 out, of shots kept within their side's half turn. +constexpr float FAN_REACH = 100; +constexpr float FAN_HEIGHT = -40; +constexpr float FAN_FALL_SPEED = 2.5f; +constexpr float FAN_DOT_LIMIT = -0.38f; +static const Vector FAN_VELOCITY = vector_make(7.5f, 14); + +// His death: grey dust and a shake at Shoot, three red bursts about him at Shoot2, then the feet take over. +constexpr ColorMod DEATH_DUST_COLOR = {{0.52f, 0.52f, 0.52f, 0.8f}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod DEATH_BURST_COLOR = {{1, 0.05f, 0.05f, 0.8f}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr int DEATH_SHAKE = 12; +constexpr int DEATH_BURST_SIZE = 2; +constexpr float DEATH_BURST_REACH = 10; +static const std::array DEATH_BURSTS = {vector_make(-40, -10), vector_make(40, -10), vector_make(0, 10)}; + +// The feet: hidden, each rolls one in 9 to stomp on its target, unless the other lifted less than 21 frames ago, kept +// 111 from it. A stomp crushes 300 within 70 and ripples the room, and with fewer than 4 enemies one roll in 2 calls a +// leech 200 out. A foot's death kills the other and hurts every enemy left by 100. +constexpr int SATAN_STOMP_ODDS = 9; +constexpr int STOMP_SETTLE_FRAMES = 21; +constexpr float FEET_SPACING = 111; +constexpr int STOMP_LEECH_CROWD = 4; +constexpr float STOMP_LEECH_REACH = 200; +constexpr float SATAN_STOMP_DAMAGE = 300; +constexpr float SATAN_STOMP_RADIUS = 70; +constexpr float SATAN_STOMP_RIPPLE_AMPLITUDE = 0.04f; +constexpr float SATAN_STOMP_RIPPLE_SPEED = 0.025f; +constexpr int SATAN_STOMP_RIPPLE_FRAMES = 13; +constexpr ColorMod SATAN_STOMP_DUST_COLOR = {{0.62f, 0.62f, 0.62f, 0.8f}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr float FEET_DEATH_DAMAGE = 100; +constexpr int FEET_DEATH_COUNTDOWN = 30; + +// 007ebc40 Crossfades to the room's boss track as a boss fight starts. +void boss_music_crossfade() +{ + g_manager->musicManager.Crossfade(g_game->room->boss_music_get(), BOSS_MUSIC_FADE); +} + +// Explosions and crushes neither a player nor a familiar set off pass Satan by, his feet's stomps among them. +static void stray_blasts_ignore(Entity_NPC& npc) +{ + if (npc.pendingDamage <= 0) return; + for (DamageEvent& event : npc.damageEvents) + { + bool isBlast = event.damageFlags & (DAMAGE_EXPLOSION | DAMAGE_CRUSH); + bool isPlayers = event.source.type == ENTITY_PLAYER || event.source.spawnerType == ENTITY_PLAYER || + event.source.spawnerType == ENTITY_FAMILIAR; + if (!isBlast || isPlayers) continue; + npc.pendingDamage -= event.damage; + event.damage = 0; + } +} + +// A blow that would kill him mid fight starts his death instead, at no health. +static void death_start(Entity_NPC& npc) +{ + npc.damageEvents.clear(); + npc.pendingDamage = 0; + npc.pendingDamageFlags = 0; + npc.stateFrame = 0; + npc.health = 0; + npc.state = NPC_STATE_MOVE; + npc.isDead = false; + npc.i1 = SATAN_DYING; + npc_sound_play(SOUND_SATAN_HURT, 1, 2, champion_pitch_get(npc)); + npc_anim_restart(npc.sprite, "Death"); + npc.RemoveStatusEffects(); +} + +// The first update: Satan sinks into his statue with no health to hurt, a foot hides with a stomp's sound. +static void satan_init(Entity_NPC& npc) +{ + npc.state = NPC_STATE_IDLE; + npc.entityCollisionClass = ENTCOLL_NONE; + if (npc.variant != SATAN_FEET_VARIANT) + { + npc.ClearEntityFlags(FLAG_APPEAR); + npc.maxHitPoints = 0; + npc.health = 0; + npc.damageEvents.clear(); + npc.pendingDamage = 0; + npc.pendingDamageFlags = 0; + npc.shadowSize = 0; + npc.pos.y += SATAN_STATUE_SINK; + npc.targetPosition = npc.pos; + return; + } + npc_sound_play(SOUND_SATAN_STOMP, 1, 4, champion_pitch_get(npc)); + npc.i1 = SATAN_FEET; + npc.stateFrame = 0; + npc.isVisible = false; + npc.shadowSize = 0; +} + +// Spawns an entity from Satan and runs its first update at once. +static void summon(Entity_NPC& npc, int type, int variant, Vector offset) +{ + Entity* entity = g_game->Spawn({.position = vector_add(npc.pos, offset), .spawner = &npc, .type = type, + .variant = variant, .seed = Random()}); + entity->Update(); +} + +// The statue: it blocks its cell, then wakes with a blast, calls the Fallen and two leeches and starts the boss music. +static void statue_update(Entity_NPC& npc, int ticks, int gridIndex) +{ + npc.entityGridCollisionClass = GRIDCOLL_NONE; + Room& room = *g_game->room; + if (gridIndex >= 0) room.gridPaths[gridIndex] = STATUE_PATH_BLOCKED; + for (; ticks > 0; ticks--) + if (++npc.stateFrame == STATUE_SOUND_FRAME) npc_sound_play(SOUND_SATAN_APPEAR, 1, 2, champion_pitch_get(npc)); + + if (npc.stateFrame > STATUE_WAKE_FRAMES) + { + npc_sound_play(SOUND_SATAN_BLAST, 1, 2, champion_pitch_get(npc)); + npc_sound_play(SOUND_SUMMONSOUND, 2, 2, champion_pitch_get(npc)); + npc.stateFrame = 0; + npc.i1++; + summon(npc, ENTITY_FALLEN, 0, vector_make(0, SUMMON_DROP)); + summon(npc, ENTITY_LEECH, KAMIKAZE_LEECH, vector_make(LEECH_SPREAD, SUMMON_DROP)); + summon(npc, ENTITY_LEECH, KAMIKAZE_LEECH, vector_make(-LEECH_SPREAD, SUMMON_DROP)); + boss_music_crossfade(); + } + + const AnimationData* anim = npc.sprite.animState.animData; + bool isIdleDone = anim && !npc.sprite.animState.isPlaying && anim->name == "SmallIdle" && !anim->isLooping; + if (!anim || (!npc.sprite.animState.isPlaying && !isIdleDone)) npc_anim_restart(npc.sprite, "SmallIdle"); + npc.pos = npc.targetPosition; + npc.AddEntityFlags(FLAG_NO_PHYSICS_KNOCKBACK); +} + +// Waiting: once Satan is the last enemy he takes his full health, rises with his own music and joins the fight. +static void awakening_update(Entity_NPC& npc, int ticks, int gridIndex) +{ + Room& room = *g_game->room; + if (gridIndex >= 0) room.gridPaths[gridIndex] = STATUE_PATH_AWAKE; + if (room.GetAliveEnemiesCount() == 1) + { + for (; ticks > 0; ticks--) + { + if (++npc.stateFrame != RISE_FRAME) continue; + room.entityList.bossMaxHealth = 0; + npc.maxHitPoints = npc.config->baseHP; + npc.health = npc.maxHitPoints; + npc_sound_play(SOUND_SATAN_RISE_UP, 1, 2, champion_pitch_get(npc)); + npc_anim_restart(npc.sprite, "Change"); + npc.shadowSize = npc.config->shadowSize; + g_manager->musicManager.Crossfade(MUSIC_SATAN_BOSS, BOSS_MUSIC_FADE); + } + if (npc.sprite.IsEventTriggered("Shoot")) npc.PlaySound(SOUND_SATAN_BLAST, 1, 2, false, 1); + if (npc.stateFrame > RISE_FRAME && npc_anim_is_done(npc)) + { + npc.i1++; + npc.state = NPC_STATE_MOVE; + npc.stateFrame = 0; + if (gridIndex >= 0) room.gridPaths[gridIndex] = 0; + npc.ClearEntityFlags(FLAG_NO_PHYSICS_KNOCKBACK); + } + } + npc.pos = npc.targetPosition; +} + +// Picks a shot attack: a spread three times in ten, else the fans. +static const char* shot_attack_pick(Entity_NPC& npc) +{ + npc.stateFrame = 0; + bool isSpread = Random() % SPREAD_ODDS < SPREAD_IN_TEN; + npc.state = isSpread ? SATAN_SPREAD : SATAN_FANS; + npc.i2 = npc.state; + return isSpread ? "Attack01" : "Attack03"; +} + +// Walking after the target, and choosing the next attack: the beam when it crosses beneath, now and then a shot attack +// (never twice running), else the sweep when it is near enough to the side, else closing in. +static void walk_update(Entity_NPC& npc, Entity& target) +{ + npc.sprite.Play("Walk"); + float aimY = std::max(target.pos.y * WALK_TARGET_SCALE, WALK_TARGET_MIN); + float leadX = target.velocity.x * 2 * WALK_LEAD_FRAMES + target.pos.x - npc.pos.x; + float dx = target.pos.x - npc.pos.x; + float dy = aimY - npc.pos.y - WALK_TARGET_RISE; + const char* anim = nullptr; + + bool isBeam = + (leadX * dx < 0 && dy > BEAM_REACH_UP && (npc.i2 != SATAN_BEAM || Random() % BEAM_REPEAT_ODDS == 0)) || + (npc.i2 == SATAN_SWEEP && std::abs(dx) < SWEEP_REPEAT_REACH && Random() % SWEEP_REPEAT_ODDS == 0); + if (isBeam) + { + npc.PlaySound(SOUND_SATAN_CHARGE_UP, 1, 2, false, 1); + npc.stateFrame = 0; + npc.state = SATAN_BEAM; + npc.i2 = SATAN_BEAM; + anim = "Attack02"; + } + else if (Random() % SHOT_ODDS == 0) anim = shot_attack_pick(npc); + else if (Random() % ATTACK_ODDS == 0 && npc.i2 != SATAN_SPREAD && npc.i2 != SATAN_FANS) anim = shot_attack_pick(npc); + else if (std::abs(dx) > WALK_ONLY_REACH || dy < 0) + npc_push(npc, vector_make(std::clamp(dx, -WALK_STEP_X, WALK_STEP_X) * WALK_ACCEL, + std::clamp(dy, -WALK_STEP_Y, WALK_STEP_Y) * WALK_ACCEL)); + else if (std::abs(dx) > SWEEP_REACH_MIN && std::abs(leadX) < SWEEP_LEAD_MAX) + { + npc.PlaySound(SOUND_SATAN_CHARGE_UP, 1, 2, false, 1); + npc.stateFrame = 0; + npc.state = SATAN_SWEEP; + npc.i2 = SATAN_SWEEP; + anim = "Attack03"; + } + if (anim) npc_anim_restart(npc.sprite, anim); + + Vector next = g_game->room->GetClampedPositionImpl(vector_add(npc.pos, npc.velocity), 0, SIDE_MARGIN, 0, + SIDE_MARGIN); + npc.velocity = vector_sub(next, npc.pos); +} + +// The spread: shots at the target's lead on Shoot and Shoot2, repeated from frame 10 while it stays near. +static void spread_update(Entity_NPC& npc, Entity& target) +{ + Vector lead = vector_make(target.velocity.x * 2 * SPREAD_LEAD_FRAMES + target.pos.x - npc.pos.x, + target.velocity.y * 2 * SPREAD_LEAD_FRAMES + target.pos.y - npc.pos.y); + if (npc_anim_is_done(npc)) + { + if (vector_length(lead) >= SPREAD_FAR || Random() % ATTACK_ODDS == 0) npc.state = NPC_STATE_MOVE; + else + { + npc_anim_restart(npc.sprite, "Attack01"); + if (npc.sprite.animState.animData) npc.sprite.animState.SetFrameFloat(SPREAD_REPEAT_FRAME); + } + } + + bool isShoot2 = npc.sprite.IsEventTriggered("Shoot2"); + if (!npc.sprite.IsEventTriggered("Shoot") && !isShoot2) return; + + ProjectileParams params; + params.scale = SPREAD_SCALE; + params.spread = SPREAD_SPREAD; + params.fallingAccelModifier = SPREAD_FALL_ACCEL; + npc.PlaySound(SOUND_SATAN_SPIT, 1, 2, false, 1); + if (!isShoot2) + { + params.heightModifier = SPREAD_HEIGHT; + params.fallingSpeedModifier = SPREAD_FALL_SPEED; + } + float speed = (vector_length(lead) <= SPREAD_FAR ? SPREAD_SPEED : SPREAD_SPEED_FAR) * SPREAD_SPEED_SCALE; + npc.FireProjectiles(npc.pos, vector_resized(lead, speed), isShoot2 ? PROJECTILES_FOUR : PROJECTILES_FIVE, params); +} + +// Satan shakes from side to side between an attack's Shoot and Shoot2, on frames he updates. +static void attack_shake(Entity_NPC& npc, int ticks, float shake) +{ + if (!npc.sprite.WasEventTriggered("Shoot") || npc.sprite.WasEventTriggered("Shoot2") || ticks <= 0) return; + npc.pos.x += (int)npc.updateTime % 2 == 1 ? shake : -shake; +} + +// A brimstone beam of Satan's from a spot, at an angle, drawn over the room. +static Entity_Laser* beam_fire(Entity_NPC& npc, Vector from, float angle, int timeout) +{ + Entity_Laser* laser = Entity_Laser::ShootAngle( + {.position = from, .source = &npc, .angleDegrees = angle, .timeout = timeout, .variant = LASER_THICK_RED}); + laser->renderDepthOffset = SATAN_BEAM_DEPTH; + return laser; +} + +// The beam straight down from his mouth. +static void beam_update(Entity_NPC& npc, int ticks) +{ + if (npc.sprite.IsEventTriggered("Shoot")) + { + Entity_Laser* laser = beam_fire(npc, vector_make(npc.pos.x, npc.pos.y - SATAN_BEAM_RISE), BEAM_ANGLE, SATAN_BEAM_TIMEOUT); + laser->scale = BEAM_SCALE; + laser->ResetSpriteScale(); + laser->Update(); + npc.pos.x -= BEAM_RECOIL; + } + attack_shake(npc, ticks, BEAM_SHAKE); +} + +// The two sweeping beams, 100 to each side, turning toward each other. +static void sweep_update(Entity_NPC& npc, int ticks) +{ + if (!npc.sprite.IsEventTriggered("Shoot")) return attack_shake(npc, ticks, SWEEP_SHAKE); + + for (int side = -1; side <= 1; side += 2) + { + float angle = side < 0 ? SWEEP_ANGLE_LEFT : SWEEP_ANGLE_RIGHT; + Vector from = vector_make(npc.pos.x + side * SWEEP_REACH, npc.pos.y - SATAN_BEAM_RISE); + Entity_Laser* laser = beam_fire(npc, from, angle, SATAN_SWEEP_TIMEOUT); + laser->rotationDegrees = side * SWEEP_ROTATION; + laser->isActiveRotating = true; + laser->rotationDelay = 0; + laser->rotationSpd = side * SATAN_SWEEP_SPEED; + laser->Update(); + npc.pos.x -= SWEEP_RECOIL; + } +} + +// The two fans of shots, 100 to each side, each kept to its own side. +static void fans_update(Entity_NPC& npc, int ticks) +{ + if (!npc.sprite.IsEventTriggered("Shoot")) return attack_shake(npc, ticks, SWEEP_SHAKE); + + npc.PlaySound(SOUND_SATAN_SPIT, 1, 2, false, 1); + for (int side = -1; side <= 1; side += 2) + { + ProjectileParams params; + params.fireDirectionLimit = vector_make((float)side, 0); + params.scale = SPREAD_SCALE; + params.heightModifier = FAN_HEIGHT; + params.fallingSpeedModifier = FAN_FALL_SPEED; + params.dotProductLimit = FAN_DOT_LIMIT; + npc.FireProjectiles(vector_make(npc.pos.x + side * FAN_REACH, npc.pos.y), FAN_VELOCITY, PROJECTILES_RING, + params); + npc.pos.x -= SWEEP_RECOIL; + } +} + +// The fight: solid and kept low in the room, he walks and attacks, walking again when an attack's animation ends. +static void fight_update(Entity_NPC& npc, int ticks) +{ + npc.renderZOffset = 0; + npc.entityCollisionClass = ENTCOLL_ALL; + npc.entityGridCollisionClass = GRIDCOLL_WALLS_X; + npc.pos.y = std::max(npc.pos.y, FIGHT_TOP); + Entity& target = *npc.GetPlayerTarget(); + + switch (npc.state) + { + case NPC_STATE_MOVE: return walk_update(npc, target); + case SATAN_SPREAD: return spread_update(npc, target); + case SATAN_BEAM: beam_update(npc, ticks); break; + case SATAN_SWEEP: sweep_update(npc, ticks); break; + case SATAN_FANS: fans_update(npc, ticks); break; + default: return; + } + if (npc_anim_is_done(npc)) npc.state = NPC_STATE_MOVE; +} + +// His death: he bleeds and bursts as it plays, then leaves two feet tied to each other and is gone. +static void dying_update(Entity_NPC& npc) +{ + npc.stateFrame++; + npc.entityCollisionClass = ENTCOLL_NONE; + npc.isInvincible = true; + ANM2& sprite = npc.sprite; + if (sprite.animState.animData) + if (const NullFrame* guide = sprite.animState.GetNullFrame("BloodGuide")) npc.update_blood_guide_gibs(*guide); + + if (sprite.animState.animData) + { + if (sprite.IsEventTriggered("Sound")) npc.PlaySound(SOUND_SATAN_GROW, 1, 2, false, 1); + if (sprite.IsEventTriggered("Shoot")) + { + npc.MakeGroundPoof(npc.pos, DEATH_DUST_COLOR, 1); + game_shake_screen(DEATH_SHAKE); + } + if (sprite.IsEventTriggered("Shoot2")) + for (const Vector& spot : DEATH_BURSTS) + { + float angle = random_unit() * RANDOM_HALF_TURN * 2; + uint32_t seed = Random(); + Vector position = vector_make(std::cos(angle) * DEATH_BURST_REACH + spot.x + npc.pos.x, + std::sin(angle) * DEATH_BURST_REACH + spot.y + npc.pos.y); + Entity* burst = g_game->Spawn({.position = position, .spawner = &npc, .subType = DEATH_BURST_SIZE, + .type = ENTITY_EFFECT, .variant = EFFECT_POOF02, .seed = seed}); + burst->SetColor(DEATH_BURST_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + burst->sprite.isFlipX = (Random() & 1) == 0; + burst->Update(); + } + if (!npc_anim_is_done(npc)) return; + } + + auto spawnFoot = [&] { + return static_cast(g_game->Spawn({.spawner = &npc, .type = npc.type, + .variant = npc.variant + SATAN_FEET_VARIANT, + .seed = Random()})); + }; + Entity_NPC* first = spawnFoot(); + Entity_NPC* second = spawnFoot(); + second->parent = first; + first->child = second; + second->state = NPC_STATE_INIT; + first->state = NPC_STATE_INIT; + first->Update(); + second->Update(); + npc.Remove(); +} + +// Moves a foot to 111 from another that stands nearer. +static void foot_space(Entity_NPC& foot, Entity_NPC& other) +{ + Vector away = vector_sub(other.pos, foot.pos); + float distance = vector_length(away); + if (distance >= FEET_SPACING || distance <= 0) return; + foot.pos = vector_sub(foot.pos, vector_scale(away, (FEET_SPACING - distance) / distance)); +} + +// A hidden foot comes down on its target now and then, calling a leech when few enemies are left. +static void foot_rest(Entity_NPC& npc) +{ + npc.isVisible = false; + npc.entityCollisionClass = ENTCOLL_NONE; + npc.entityGridCollisionClass = GRIDCOLL_GROUND; + if (Random() % SATAN_STOMP_ODDS != 0) return; + if (npc.parent && npc.stateFrame != 0 && npc.ParentNPC()->stateFrame < STOMP_SETTLE_FRAMES) return; + if (npc.child && npc.ChildNPC()->stateFrame < STOMP_SETTLE_FRAMES) return; + + npc.state = NPC_STATE_STOMP; + npc.stateFrame = 0; + npc_anim_restart(npc.sprite, "Stomp"); + npc.isVisible = true; + Entity& target = *npc.GetPlayerTarget(); + npc.pos = target.pos; + if (npc.parent) foot_space(npc, *npc.ParentNPC()); + if (npc.child) foot_space(npc, *npc.ChildNPC()); + if (g_game->room->GetAliveEnemiesCount() >= STOMP_LEECH_CROWD || (Random() & 1) != 0) return; + + Vector spot = room_free_pickup_position_find( + {.position = target.pos, .step = STOMP_LEECH_REACH, .isAvoidActiveEntities = true}); + g_game->Spawn({.position = spot, .spawner = &npc, .type = ENTITY_LEECH, .variant = KAMIKAZE_LEECH, .seed = Random()}); +} + +// A stomp: solid from the landing until it lifts, crushing and rippling where it lands. The feet share the lower +// health, and one's death ends the other and hurts every enemy left. +static void foot_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_IDLE) return foot_rest(npc); + + if (npc.state == NPC_STATE_STOMP) + { + npc.stateFrame++; + bool isDown = npc.sprite.WasEventTriggered("Stomp") && !npc.sprite.WasEventTriggered("Lift"); + npc.entityCollisionClass = isDown ? ENTCOLL_ALL : ENTCOLL_NONE; + if (npc.sprite.IsEventTriggered("Stomp")) + { + npc.PlaySound(SOUND_HELLBOSS_GROUNDPOUND, 1, 2, false, 1); + explosion_damage({.position = npc.pos, .source = &npc, .damageFlags = DAMAGE_CRUSH, + .damage = SATAN_STOMP_DAMAGE, .radius = SATAN_STOMP_RADIUS, .isLineCheck = false}); + shockwave_make(npc.pos, SATAN_STOMP_RIPPLE_AMPLITUDE, SATAN_STOMP_RIPPLE_SPEED, SATAN_STOMP_RIPPLE_FRAMES); + npc.MakeGroundPoofAtSelf(SATAN_STOMP_DUST_COLOR, 1); + } + if (npc_anim_is_done(npc)) + { + npc.isVisible = false; + npc.state = NPC_STATE_IDLE; + } + } + if (npc.parent) + { + Entity_NPC& other = *npc.ParentNPC(); + float health = std::min(npc.health, other.health); + other.health = health; + npc.health = health; + } + if (!npc.isDead) return; + + if (npc.child) npc.child->Kill(EntityRef()); + if (npc.parent) npc.parent->Kill(EntityRef()); + for (Entity* entity : std::vector(g_game->room->entityList.updateEL)) + if (entity->CanShutDoors()) entity->TakeDamage(FEET_DEATH_DAMAGE, 0, EntityRef(), FEET_DEATH_COUNTDOWN); +} + +// 0047f640 Satan (84) and his feet (84.10): the statue that wakes to call the Fallen, the fight once it falls, his +// death, and the feet stomping until they die. +void boss_satan_update(Entity_NPC& npc) +{ + stray_blasts_ignore(npc); + if (npc.i1 == SATAN_FIGHT && npc.health - npc.pendingDamage < 0) death_start(npc); + if (npc.state == NPC_STATE_INIT) return satan_init(npc); + + npc.friction *= SATAN_FRICTION; + int ticks = npc_ticks_get(npc); + int gridIndex = g_game->room->GetGridIndex(vector_add(npc.pos, npc.posOffset)); + switch (npc.i1) + { + case SATAN_STATUE: return statue_update(npc, ticks, gridIndex); + case SATAN_AWAKENING: return awakening_update(npc, ticks, gridIndex); + case SATAN_FIGHT: return fight_update(npc, ticks); + case SATAN_DYING: return dying_update(npc); + case SATAN_FEET: return foot_update(npc); + } +} diff --git a/src/cutscene.cpp b/src/cutscene.cpp index 222c0e6..691a30e 100644 --- a/src/cutscene.cpp +++ b/src/cutscene.cpp @@ -325,22 +325,33 @@ void Cutscene::VideoPart::Start() { subtitleFrame = 0; subtitleIndex = 0; - player->play((uint8_t*)file.c_str(), music_volume_get() * VIDEO_VOLUME_SCALE); + player->play(file, music_volume_get() * VIDEO_VOLUME_SCALE); if (!isKeepMusic) g_manager->musicManager.Fadeout(MUSIC_FADE_RATE); startTime = time_ms(); } -void Cutscene::VideoPart::Update() { reconstruction_missing("Cutscene::VideoPart::Update 0095fbd0 (video clip)"); } -void Cutscene::VideoPart::Render(Vector) +// 0095fbd0 Moves the subtitles on to the part's frame (30 a second) every other frame. The clip plays itself. +void Cutscene::VideoPart::Update() { - reconstruction_missing("Cutscene::VideoPart::Render 0095fcd0 (video clip)"); + if (g_manager->framecount & 1) return; + subtitles_advance((uint32_t)((time_ms() - startTime) * FRAMES_PER_SECOND / MS_PER_SECOND)); } -bool Cutscene::VideoPart::IsFinished() + +// 0095fcd0 Draws the clip blended normally at the offset, then the subtitles. +void Cutscene::VideoPart::Render(Vector offset) { - reconstruction_missing("Cutscene::VideoPart::IsFinished 0095fd40 (video clip)"); + KAGE::Graphics::manager.blend_set(KAGE::Graphics::BLEND_NORMAL); + player->render(offset); + render_subtitles(); } -int Cutscene::VideoPart::GetWidth() { reconstruction_missing("Cutscene::VideoPart::GetWidth 0095c930 (video clip)"); } -int Cutscene::VideoPart::GetHeight() { reconstruction_missing("Cutscene::VideoPart::GetHeight 0095c960 (video clip)"); } + +// 0095fd40 Whether the clip played to its end, or none opened. +bool Cutscene::VideoPart::IsFinished() { return player->is_finished(); } + +// (0095c930, 0095c960) The canvas the clip is drawn for. With no clip open the original gives 0 by 0, which zeroes the +// screen scale for the frame the part shows, so the default canvas stands in. +int Cutscene::VideoPart::GetWidth() { return CANVAS_DEFAULT.width; } +int Cutscene::VideoPart::GetHeight() { return CANVAS_DEFAULT.height; } // 0095fd70 Loads the title and body fonts, as mods may replace them. void Cutscene::TemporaryPart::Load() diff --git a/src/cutscene.h b/src/cutscene.h index 380c24b..4978d35 100644 --- a/src/cutscene.h +++ b/src/cutscene.h @@ -3,6 +3,7 @@ #include "anm2.h" #include "font.h" #include "platform.h" +#include "video_player.h" #include #include #include diff --git a/src/data.cpp b/src/data.cpp index 1df3baa..8e28caa 100644 --- a/src/data.cpp +++ b/src/data.cpp @@ -16,12 +16,14 @@ constexpr std::string_view PARENT_FOLDER = "../"; std::string dataDirectory = "resources/"; std::string languageDirectory; -// A game path lowercased with forward slashes, as the game normalizes every path before a lookup. +// A game path lowercased with forward slashes, as the game normalizes every path before a lookup. A path already under +// the resources, which mods build from their script's path as the original's absolute ones, stays there. static std::string path_normalize(std::string_view path) { std::string normalized(path); for (char& letter : normalized) letter = letter == '\\' ? '/' : (char)std::tolower((unsigned char)letter); if (normalized.starts_with(MODS_FROM_RESOURCES)) normalized.erase(0, PARENT_FOLDER.size()); + else if (normalized.starts_with(dataDirectory)) normalized.erase(0, dataDirectory.size()); return normalized; } diff --git a/src/entity.cpp b/src/entity.cpp index 550e7d2..f212eff 100644 --- a/src/entity.cpp +++ b/src/entity.cpp @@ -1,5 +1,6 @@ #include "entity.h" #include "entity_effect.h" +#include "entity_familiar.h" #include "entity_list.h" #include "entity_npc.h" #include "entity_player.h" @@ -9,6 +10,7 @@ #include "lua_engine.h" #include "manager.h" #include "room.h" +#include "room_grid.h" #include #include #include @@ -485,6 +487,14 @@ void Entity::CopyStatusEffects() } } +// Sorted insertion into a hit list, as the entities keep them. +void hit_list_insert(std::vector& hitList, Entity& entity) +{ + uint32_t index = entity.GetHitListIndex(); + auto at = std::lower_bound(hitList.begin(), hitList.end(), index); + if (at == hitList.end() || *at != index) hitList.insert(at, index); +} + // 006b62b0 The index hits on it are recorded under: its body's for segmented bosses that share them. uint32_t Entity::GetHitListIndex() { @@ -592,10 +602,19 @@ bool Entity::CanDevolve() return config && !config->devolve.empty(); } -// 006b9740 -bool Entity::IsPlayerInRadius(const Vector&, float) +// 006b9740 Whether a player (or Isaac's Heart) is within radius of a position. A friendly entity never sees one. +bool Entity::IsPlayerInRadius(const Vector& center, float radius) { - reconstruction_missing("Entity::IsPlayerInRadius 006b9740"); + if (IsFriendly() || radius <= 0) return false; + + for (Entity_Player* player : g_game->playerManager.playerList) + { + Vector delta = vector_make(center.x - player->pos.x, center.y - player->pos.y); + if (delta.x * delta.x + delta.y * delta.y < radius * radius) return true; + } + for (Entity* entity : entity_query_radius(center, radius, QUERY_FAMILIARS)) + if (entity->type == ENTITY_FAMILIAR && entity->variant == Entity_Familiar::ISAACS_HEART) return true; + return false; } // 007e9130 The boss id its config gives, 0 without one. diff --git a/src/entity.h b/src/entity.h index 5e18568..b476bd6 100644 --- a/src/entity.h +++ b/src/entity.h @@ -36,6 +36,7 @@ enum EntityType : int ENTITY_GLOBIN = 24, ENTITY_BOOMFLY = 25, ENTITY_MAW = 26, + ENTITY_HOST = 27, ENTITY_CHUB = 28, ENTITY_HOPPER = 29, ENTITY_BOIL = 30, @@ -52,13 +53,20 @@ enum EntityType : int ENTITY_STONEHEAD = 42, ENTITY_POKY = 44, ENTITY_MOM = 45, + ENTITY_SLOTH = 46, + ENTITY_LUST = 47, + ENTITY_WRATH = 48, + ENTITY_GLUTTONY = 49, ENTITY_GREED = 50, + ENTITY_ENVY = 51, + ENTITY_PRIDE = 52, ENTITY_FLAMING_HOPPER = 54, ENTITY_LEECH = 55, ENTITY_LUMP = 56, ENTITY_MEMBRAIN = 57, ENTITY_PARA_BITE = 58, ENTITY_FRED = 59, + ENTITY_EYE = 60, ENTITY_SUCKER = 61, ENTITY_PIN = 62, ENTITY_FAMINE = 63, @@ -72,8 +80,10 @@ enum EntityType : int ENTITY_MOMS_HEART = 78, ENTITY_GEMINI = 79, ENTITY_MOTER = 80, + ENTITY_FALLEN = 81, ENTITY_SATAN = 84, ENTITY_SPIDER = 85, + ENTITY_KEEPER = 86, ENTITY_BUTTLICKER = 89, ENTITY_HANGER = 90, ENTITY_HEART = 92, @@ -84,6 +94,7 @@ enum EntityType : int ENTITY_HEART_OF_INFAMY = 98, ENTITY_GURDY_JR = 99, ENTITY_WIDOW = 100, + ENTITY_DADDYLONGLEGS = 101, ENTITY_ISAAC_BOSS = 102, ENTITY_BRIMSTONE_HEAD = 203, ENTITY_BABY_LONG_LEGS = 206, @@ -106,6 +117,9 @@ enum EntityType : int ENTITY_GURGLING = 237, ENTITY_SPLASHER = 238, ENTITY_GRUB = 239, + ENTITY_WALL_CREEP = 240, + ENTITY_RAGE_CREEP = 241, + ENTITY_BLIND_CREEP = 242, ENTITY_CONJOINED_SPITTY = 243, ENTITY_ROUND_WORM = 244, ENTITY_POOP = 245, @@ -118,6 +132,7 @@ enum EntityType : int ENTITY_POLYCEPHALUS = 269, ENTITY_URIEL = 271, ENTITY_GABRIEL = 272, + ENTITY_THE_LAMB = 273, ENTITY_MEGA_SATAN = 274, ENTITY_ROUNDY = 276, ENTITY_BLACK_BONY = 277, @@ -126,6 +141,7 @@ enum EntityType : int ENTITY_BLACK_GLOBIN_BODY = 280, ENTITY_FLESH_DEATHS_HEAD = 286, ENTITY_ULCER = 289, + ENTITY_MEATBALL = 290, ENTITY_PITFALL = 291, ENTITY_MOVABLE_TNT = 292, ENTITY_CORN_MINE = 295, @@ -134,27 +150,43 @@ enum EntityType : int ENTITY_POISON_MIND = 301, ENTITY_STONEY = 302, ENTITY_BLISTER = 303, + ENTITY_THE_THING = 304, ENTITY_PORTAL = 306, ENTITY_STAIN = 401, + ENTITY_BROWNIE = 402, ENTITY_LITTLE_HORN = 404, + ENTITY_RAG_MAN = 405, ENTITY_ULTRA_GREED = 406, ENTITY_HUSH = 407, + ENTITY_RAG_MEGA = 409, ENTITY_SISTERS_VIS = 410, ENTITY_BIG_HORN = 411, ENTITY_DELIRIUM = 412, ENTITY_MATRIARCH = 413, ENTITY_BLOOD_PUPPY = 802, ENTITY_BISHOP = 805, + ENTITY_WRAITH = 807, ENTITY_WILLO = 808, + ENTITY_BOMB_GRIMACE = 809, ENTITY_SMALL_LEECH = 810, ENTITY_DEEP_GAPER = 811, ENTITY_BLURB = 813, ENTITY_STRIDER = 814, + ENTITY_FISSURE = 815, + ENTITY_POLTY = 816, ENTITY_ROCK_SPIDER = 818, ENTITY_FLY_BOMB = 819, + ENTITY_BLASTER = 821, + ENTITY_QUAKEY = 823, + ENTITY_GYRO = 824, + ENTITY_HARDY = 826, + ENTITY_BIG_BONY = 830, + ENTITY_GUTTED_FATTY = 831, + ENTITY_PEEPER_FATTY = 835, ENTITY_SMALL_MAGGOT = 853, ENTITY_PUSTULE = 861, ENTITY_CYST = 862, + ENTITY_EVIS = 865, ENTITY_DARK_ESAU = 866, ENTITY_DRIP = 870, ENTITY_SPLURT = 871, @@ -162,7 +194,9 @@ enum EntityType : int ENTITY_GRUDGE = 877, ENTITY_NEEDLE = 881, ENTITY_CULTIST = 885, + ENTITY_VIS_FATTY = 886, ENTITY_BALL_AND_CHAIN = 893, + ENTITY_REAP_CREEP = 900, ENTITY_VISAGE = 903, ENTITY_HERETIC = 905, ENTITY_HORNFEL = 906, @@ -178,6 +212,8 @@ enum EntityType : int ENTITY_COLOSTOMIA = 917, ENTITY_TURDLET = 918, ENTITY_RAGLICH = 919, + ENTITY_HORNY_BOYS = 920, + ENTITY_CLUTCH = 921, ENTITY_DOGMA = 950, ENTITY_BEAST = 951, ENTITY_GENERIC_PROP = 960, @@ -298,6 +334,8 @@ enum DamageFlag : uint64_t DAMAGE_SPAWN_RED_HEART = 1ull << 26, DAMAGE_SPAWN_COIN = 1ull << 27, DAMAGE_NO_PENALTIES = 1ull << 28, + DAMAGE_CLONES = 1ull << 29, + DAMAGE_SPAWN_TEMP_HEART = 1ull << 29, DAMAGE_IGNORE_ARMOR = 1ull << 30, DAMAGE_SPAWN_CARD = 1ull << 31, DAMAGE_SPAWN_RUNE = 1ull << 32, @@ -743,5 +781,6 @@ private: void magnet_pull_update(); }; +void hit_list_insert(std::vector& hitList, Entity& entity); Vector render_position_get(const Vector& world, RenderSnap snap); int render_z_get(float depth); diff --git a/src/entity_bomb.h b/src/entity_bomb.h index 38caba3..915eddf 100644 --- a/src/entity_bomb.h +++ b/src/entity_bomb.h @@ -104,6 +104,7 @@ private: }; void explosion_damage(Explosion explosion); +bool explosion_line_clear(const Vector& start, const Vector& end, bool isIgnoreWalls); void explosion_effects(const Explosion& explosion); void explosion_tear_flag_effects(const Explosion& explosion); Entity* bomb_crater_spawn(const Vector& position, Entity* spawner, float scale); diff --git a/src/entity_collision.cpp b/src/entity_collision.cpp index 244900c..666c8a7 100644 --- a/src/entity_collision.cpp +++ b/src/entity_collision.cpp @@ -17,7 +17,6 @@ // What crushes rocks on contact: The Nail, Leo (worn or rolled by Zodiac), Thunder Thighs, Stompy and Mega Mush. constexpr int COLLECTIBLE_LEO = 302; constexpr int COLLECTIBLE_THUNDER_THIGHS = 314; -constexpr int PLAYERFORM_STOMPY = 13; // A transformation counts once the player holds this many of its items. constexpr int PLAYER_FORM_ITEMS = 3; @@ -224,7 +223,7 @@ bool Entity_Player::CanCrushRocks() { return temporaryEffects.HasCollectibleEffect(COLLECTIBLE_THE_NAIL) || HasCollectible(COLLECTIBLE_LEO) || temporaryEffects.HasCollectibleEffect(COLLECTIBLE_LEO) || GetZodiacEffect() == COLLECTIBLE_LEO || - HasCollectible(COLLECTIBLE_THUNDER_THIGHS) || HasPlayerForm(PLAYERFORM_STOMPY) || + HasCollectible(COLLECTIBLE_THUNDER_THIGHS) || HasPlayerForm(PLAYER_FORM_STOMPY) || temporaryEffects.HasCollectibleEffect(COLLECTIBLE_MEGA_MUSH); } diff --git a/src/entity_combat.cpp b/src/entity_combat.cpp index 9e3a8a9..e9f8e4c 100644 --- a/src/entity_combat.cpp +++ b/src/entity_combat.cpp @@ -61,10 +61,8 @@ constexpr int STATIC_OBSTACLE_EXTRA = 202; // The items, trinkets and player kinds the combat code reads (Lua's ids). constexpr int COLLECTIBLE_MOMS_HEELS = 30; -constexpr int COLLECTIBLE_MULLIGAN = 151; constexpr int COLLECTIBLE_ARIES = 300; constexpr int NULLITEM_TOOTH_AND_NAIL = 59; -constexpr int PLAYER_FORM_GUPPY = 0; constexpr int PLAYER_FORM_COUNT_NEEDED = 3; constexpr int BABY_CROW = 12; constexpr int BLUE_FLY_MAX = 30; @@ -193,14 +191,6 @@ constexpr KColor BLOOD_BASE_COLOR = kcolor_rgba(0.61960787f, 0.043137256f, 0.058 constexpr ColorMod POISON_GIB_TINT = {{1, 1, 1, 1}, {0.3f, 1.6f, 0, 1}, {0, 0, 0}}; constexpr ColorMod TOOTH_COLOR = {{0.54902f, 0.482353f, 0.482353f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; -// Sorted insertion into a hit list, as the entities keep them. -static void hit_list_add(std::vector& hitList, Entity& entity) -{ - uint32_t index = entity.GetHitListIndex(); - auto at = std::lower_bound(hitList.begin(), hitList.end(), index); - if (at == hitList.end() || *at != index) hitList.insert(at, index); -} - // Spawns an effect with a seed drawn by the caller. static Entity_Effect* effect_spawn(int variant, int subType, Vector position, Vector velocity, Entity* spawner, uint32_t seed) @@ -803,7 +793,7 @@ static TearContact tear_contact_get(Entity_Tear& tear, Entity& collider, Entity* { if (!EntityList::HitListContains(tear.hitList, collider)) { - hit_list_add(tear.hitList, collider); + hit_list_insert(tear.hitList, collider); tear_push(tear, collider, TEAR_DEFLECTOR_MASS_SCALE); } return TEAR_CONTACT_PASS; @@ -953,7 +943,7 @@ bool Entity_Tear::HandleCollision(Entity* collider, bool isLow) tearFlags[TEAR_BOUNCE] || tearFlags[TEAR_LUDOVICO] || tearFlags[TEAR_BOOGER_FLAG] || tearFlags[TEAR_STICKY] || tearFlags[TEAR_SPORE_FLAG] || tearFlags[TEAR_FETUS_FLAG]; if (EntityList::HitListContains(hitList, *collider) && isPassing) return true; - hit_list_add(hitList, *collider); + hit_list_insert(hitList, *collider); bool isSticking = tearFlags[TEAR_STICKY] || tearFlags[TEAR_BOOGER_FLAG] || tearFlags[TEAR_SPORE_FLAG]; if (collider->IsActiveEnemy(DEAD_EXCLUDED) && isSticking) reconstruction_missing("Entity_Tear::HandleCollision 00673660: a sticky tear sticking to an enemy"); diff --git a/src/entity_effect.cpp b/src/entity_effect.cpp index 3315dac..ed5fddc 100644 --- a/src/entity_effect.cpp +++ b/src/entity_effect.cpp @@ -1,5 +1,6 @@ #include "entity_effect.h" #include "entity_effect_combat.h" +#include "entity_effect_trail.h" #include "entity_list.h" #include "entity_player.h" #include "entity_player_forgotten.h" @@ -98,6 +99,7 @@ static const EffectBehaviour* behaviour_find(int variant) std::array table{}; for (auto group : {ambient_effect_behaviours(), hazard_effect_behaviours(), floor_effect_behaviours(), beam_effect_behaviours(), player_effect_behaviours(), mines_effect_behaviours(), + trail_effect_behaviours(), spike_effect_behaviours(), std::span(TIMER_BEHAVIOURS)}) for (const EffectBehaviour& behaviour : group) table[behaviour.variant] = behaviour; return table; diff --git a/src/entity_effect.h b/src/entity_effect.h index 47cc9a3..7ee74d4 100644 --- a/src/entity_effect.h +++ b/src/entity_effect.h @@ -50,8 +50,10 @@ enum EffectVariant : int EFFECT_BULLET_POOF = 11, EFFECT_TEAR_POOF_A = 12, EFFECT_TEAR_POOF_B = 13, + EFFECT_RIPPLE_POOF = 14, EFFECT_POOF01 = 15, EFFECT_POOF02 = 16, + EFFECT_CRACK_THE_SKY = 19, EFFECT_TINY_BUG = 21, EFFECT_CREEP_RED = 22, EFFECT_CREEP_GREEN = 23, @@ -59,18 +61,23 @@ enum EffectVariant : int EFFECT_CREEP_WHITE = 25, EFFECT_CREEP_BLACK = 26, EFFECT_WOOD_PARTICLE = 27, + EFFECT_PLAYER_CREEP_LEMON_MISHAP = 32, EFFECT_TINY_FLY = 33, EFFECT_FART = 34, EFFECT_TOOTH_PARTICLE = 35, + EFFECT_PLAYER_CREEP_HOLYWATER = 37, EFFECT_SPIDER_EXPLOSION = 38, EFFECT_HEAVEN_LIGHT_DOOR = 39, EFFECT_WATER_DROPLET = 41, EFFECT_POOP_EXPLOSION = 43, + EFFECT_PLAYER_CREEP_WHITE = 44, + EFFECT_PLAYER_CREEP_BLACK = 45, EFFECT_PLAYER_CREEP_RED = 46, EFFECT_HEART = 49, EFFECT_LASER_IMPACT = 50, EFFECT_HOT_BOMB_FIRE = 51, EFFECT_PLAYER_CREEP_GREEN = 53, + EFFECT_PLAYER_CREEP_HOLYWATER_TRAIL = 54, EFFECT_SPIKE = 55, EFFECT_CREEP_BROWN = 56, EFFECT_PULLING_EFFECT = 57, @@ -90,10 +97,14 @@ enum EffectVariant : int EFFECT_SHOCKWAVE_RANDOM = 73, EFFECT_ISAACS_CARPET = 74, EFFECT_DICE_FLOOR = 76, + EFFECT_PLAYER_CREEP_LEMON_PARTY = 78, EFFECT_TEAR_POOF_SMALL = 79, EFFECT_TEAR_POOF_VERYSMALL = 80, + EFFECT_EVIL_EYE = 84, EFFECT_FALLING_EMBER = 87, EFFECT_DARK_BALL_SMOKE_PARTICLE = 88, + EFFECT_PLAYER_CREEP_PUDDLE_MILK = 90, + EFFECT_PLAYER_CREEP_BLACKPOWDER = 92, EFFECT_PENTAGRAM_BLACKPOWDER = 93, EFFECT_CREEP_SLIPPERY_BROWN = 94, EFFECT_WATER_SPLASH = 99, @@ -103,8 +114,8 @@ enum EffectVariant : int EFFECT_BRIMSTONE_BALL = 113, EFFECT_FORGOTTEN_CHAIN = 114, EFFECT_BROKEN_SHOVEL_SHADOW = 115, - EFFECT_FORGOTTEN_SOUL = 117, EFFECT_DIRT_PATCH = 116, + EFFECT_FORGOTTEN_SOUL = 117, EFFECT_SMALL_ROCKET = 118, EFFECT_SPAWNER = 120, EFFECT_LIGHT = 121, @@ -114,7 +125,9 @@ enum EffectVariant : int EFFECT_BIG_HORN_HAND = 125, EFFECT_TECH_DOT = 126, EFFECT_BIG_SPLASH = 132, + EFFECT_WATER_RIPPLE = 133, EFFECT_PEDESTAL_RIPPLE = 134, + EFFECT_RAIN_DROP = 135, EFFECT_GRID_ENTITY_PROJECTILE_HELPER = 136, EFFECT_MINES_TRAPDOOR_COVER = 139, EFFECT_BACKDROP_DECORATION = 140, @@ -128,10 +141,14 @@ enum EffectVariant : int EFFECT_TALL_LADDER = 156, EFFECT_TADPOLE = 158, EFFECT_LIL_GHOST = 159, - EFFECT_COLOSTOMIA_PUDDLE = 168, EFFECT_PORTAL_TELEPORT = 161, + EFFECT_SPRITE_TRAIL = 166, + EFFECT_COLOSTOMIA_PUDDLE = 168, + EFFECT_CREEP_STATIC = 169, + EFFECT_RIFT = 180, EFFECT_ANIMA_CHAIN = 193, - EFFECT_GENERIC_TRACER = 198 + EFFECT_GENERIC_TRACER = 198, + EFFECT_PLAYER_CREEP_YELLOW = 204 }; // Construction and destruction (005cd9f0, 005cd960) are the defaults, the extra data shared with its other holders. @@ -199,6 +216,7 @@ std::span ambient_effect_behaviours(); std::span hazard_effect_behaviours(); std::span floor_effect_behaviours(); std::span beam_effect_behaviours(); +std::span spike_effect_behaviours(); // The frame the plain poofs share: the sprite turned by the effect's rotation (mirrored unless flipped), the effect // gone once its animation ends. diff --git a/src/entity_effect_ambient.cpp b/src/entity_effect_ambient.cpp index 46941b4..bab4bca 100644 --- a/src/entity_effect_ambient.cpp +++ b/src/entity_effect_ambient.cpp @@ -19,24 +19,6 @@ #include #include #include -#include "stb_image.h" - -// The ambient and environment variants (Lua's EffectVariant). -enum AmbientVariant : int -{ - EFFECT_WATER_RIPPLE = 133, - EFFECT_RAIN_DROP = 135, - EFFECT_PLAYER_CREEP_LEMON_MISHAP = 32, - EFFECT_PLAYER_CREEP_HOLYWATER = 37, - EFFECT_PLAYER_CREEP_WHITE = 44, - EFFECT_PLAYER_CREEP_BLACK = 45, - EFFECT_PLAYER_CREEP_HOLYWATER_TRAIL = 54, - EFFECT_PLAYER_CREEP_LEMON_PARTY = 78, - EFFECT_PLAYER_CREEP_PUDDLE_MILK = 90, - EFFECT_PLAYER_CREEP_BLACKPOWDER = 92, - EFFECT_CREEP_STATIC = 169, - EFFECT_PLAYER_CREEP_YELLOW = 204 -}; constexpr int ROOM_BARREN_TYPE = 19; constexpr int SOUND_DROPLET_SPLASH = 397; @@ -1030,115 +1012,6 @@ static ColorMod color_make(std::array tint, std::array offse return {{tint[0], tint[1], tint[2], tint[3]}, {0, 0, 0, 0}, {offset[0], offset[1], offset[2]}}; } -// A spritesheet's texels, read once from its file. -struct Texels -{ - std::vector rgba; - int height = 0; - int width = 0; -}; - -static const Texels& texels_get(const KAGE::Graphics::ImageBase& image) -{ - static std::unordered_map cache; - auto [entry, isNew] = cache.try_emplace(image.path); - if (!isNew) return entry->second; - - int channels = 0; - Texels& texels = entry->second; - stbi_uc* data = stbi_load(resource_path(image.path).c_str(), &texels.width, &texels.height, &channels, STBI_rgb_alpha); - if (data) texels.rgba.assign(data, data + (size_t)texels.width * texels.height * 4); - stbi_image_free(data); - return texels; -} - -// The texel at a spritesheet position, white off the image. -static KColor texel_read(const KAGE::Graphics::ImageBase& image, int x, int y) -{ - const Texels& texels = texels_get(image); - if ((uint32_t)x >= (uint32_t)texels.width || (uint32_t)y >= (uint32_t)texels.height || texels.rgba.empty()) - return kcolor_rgba(1, 1, 1, 1); - - const uint8_t* texel = &texels.rgba[((size_t)y * texels.width + x) * 4]; - return kcolor_rgba(texel[0] / 255.0f, texel[1] / 255.0f, texel[2] / 255.0f, texel[3] / 255.0f); -} - -// ANM2::GetTexel 0040b600: the color a sprite drawn at a place shows at a point, from the first layer (by track) -// whose texel there is at least half opaque, tinted and offset by the sprite's, layer's and keyframe's colors. None is -// clear. The original reads the texel back from the texture, this from the spritesheet's file. -static KColor sprite_texel_get(ANM2& sprite, Vector point, Vector place) -{ - const AnimationState& state = sprite.animState; - if (!state.animData) return kcolor_rgba(0, 0, 0, 0); - - for (size_t track = 0; track < state.animData->animLayers.size(); track++) - { - const AnimationLayer& animLayer = state.animData->animLayers[track]; - int frameIndex = state.layerFrames[track]; - LayerState* layer = sprite.GetLayer(animLayer.layerId); - if (animLayer.frames.empty() || !layer || frameIndex < 0 || frameIndex >= (int)animLayer.frames.size()) continue; - - const AnimationFrame& frame = animLayer.frames[frameIndex]; - if (!frame.isVisible || !layer->isVisible || !layer->spriteSheet) continue; - - SourceQuad source = AnimationLayer::GetSourceQuad(frame, *layer, SpriteDraw{}, sprite); - DestinationQuad screen = AnimationLayer::GetDestQuad(frame, *layer, SpriteDraw{place, {}, {}}, sprite); - float layerTurn = frame.rotation + layer->rotation; - float spriteTurn = sprite.rotation; - if (spriteTurn != 0 || layerTurn != 0) - { - float scaleX = frame.scale.x * layer->size.x; - float scaleY = frame.scale.y * layer->size.y; - float spriteScaleY = sprite.isFlipY ? -sprite.scale.y : sprite.scale.y; - if ((sprite.scale.x < 0) != (scaleX < 0)) - { - if (sprite.scale.x < 0) - { - layerTurn = -layerTurn; - spriteTurn = -spriteTurn; - } - if (scaleX < 0) layerTurn = -layerTurn; - } - if (layer->isFlipY) scaleY = -scaleY; - if ((spriteScaleY < 0) != (scaleY < 0)) - { - if (spriteScaleY < 0) - { - layerTurn = -layerTurn; - spriteTurn = -spriteTurn; - } - if (scaleY < 0) layerTurn = -layerTurn; - } - - float angle = -(layerTurn + spriteTurn) * DEGREES_TO_RADIANS; - float cosine = std::cos(angle); - float sine = std::sin(angle); - for (Vector* corner : {&screen._topLeft, &screen._topRight, &screen._bottomLeft, &screen._bottomRight}) - *corner = vector_make(corner->x * cosine - corner->y * sine, corner->y * cosine + corner->x * sine); - point = vector_make(cosine * point.x - sine * point.y, cosine * point.y + sine * point.x); - } - - Vector topLeft = screen._topLeft; - Vector bottomRight = screen._bottomRight; - if (point.x <= topLeft.x || point.x >= bottomRight.x || point.y <= topLeft.y || point.y >= bottomRight.y) continue; - - float u = std::clamp((point.x - topLeft.x) / (bottomRight.x - topLeft.x), 0.0f, 1.0f); - float v = std::clamp((point.y - topLeft.y) / (bottomRight.y - topLeft.y), 0.0f, 1.0f); - float x = (source._bottomRight.x - source._topLeft.x) * u + source._topLeft.x; - float y = (source._bottomRight.y - source._topLeft.y) * v + source._topLeft.y; - KColor texel = texel_read(*layer->spriteSheet, (int)x, (int)y); - if (texel._alpha < CREEP_TEXEL_OPAQUE) continue; - - std::array tint{}; - std::array offset{}; - for (int i = 0; i < 4; i++) tint[i] = frame.color._tint[i] * (layer->color._tint[i] * sprite.color._tint[i]); - for (int i = 0; i < 3; i++) offset[i] = frame.color._offset[i] + (layer->color._offset[i] + sprite.color._offset[i]); - return kcolor_rgba(tint[0] * texel._red + offset[0], tint[1] * texel._green + offset[1], - tint[2] * texel._blue + offset[2], tint[3] * texel._alpha); - } - return kcolor_rgba(0, 0, 0, 0); -} - // Lost Cork's multiplier for a creep's owner, 1 to 3, or 0 for none. static int lost_cork_get(Entity* owner) { @@ -1244,7 +1117,8 @@ static void creep_players_touch(Entity_Effect& creep, void (*touch)(Entity_Effec if (distance >= creep.size * creep.sprite.scale.x + player->size) continue; Vector point = vector_scale(player->pos, SCREEN_SCALE); - KColor texel = sprite_texel_get(creep.sprite, point, vector_scale(creep.pos, SCREEN_SCALE)); + KColor texel = creep.sprite.GetTexel( + {.renderPos = vector_scale(creep.pos, SCREEN_SCALE), .sample = point, .alphaThreshold = CREEP_TEXEL_OPAQUE}); if (texel._alpha <= CREEP_TEXEL_OPAQUE) continue; touch(creep, *player); if (creep.variant != EFFECT_CREEP_STATIC) player->SetFootprintColor(texel, false); @@ -1825,6 +1699,22 @@ static void light_beam_update(Entity_Effect& beam) } } +// The heaven door's travel: the door draws over the player, who rises up the light to the next floor (the Cathedral +// from the Womb), and past the Dark Room the floor's seed moves on so it is laid out anew. +static void heaven_door_travel(Entity_Effect& door, Entity_Player& player) +{ + Game& game = *g_game; + door.renderDepthOffset = player.pos.y - door.pos.y + 1; + game.stageTransition.start({}); + player.AnimateLightTravel(); + player.moveToTarget = door.pos; + game.gameStateFlags |= 1ull << GAME_STATE_HEAVEN_PATH; + if (game.stage < STAGE_DARK_ROOM) return; + + bool isAltPath = game.stageType == STAGETYPE_REPENTANCE || game.stageType == STAGETYPE_REPENTANCE_B; + game.seedEffects.ForgetStageSeed((int)game.stage + (isAltPath ? 1 : 0)); +} + // The heaven door: open while the room is clear (in Backasswards only in the starting room or Genesis's), it takes a // player standing in it once ready up to the next floor. A player stepping in too early closes it again. static void heaven_door_update(Entity_Effect& door) @@ -1849,9 +1739,8 @@ static void heaven_door_update(Entity_Effect& door) { if (player->variant != 0 || player->entityCollisionClass == ENTCOLL_NONE) continue; if (distance_squared(player->pos, door.pos) >= HEAVEN_DOOR_RANGE_SQUARED || !is_player_free(*player)) continue; - if (door.state >= HEAVEN_DOOR_READY) - reconstruction_missing("Entity_Effect::Update 005d4380: the heaven door's travel (StartStageTransition)"); - if (door.state < HEAVEN_DOOR_EARLY) door.state = HEAVEN_DOOR_RESET; + if (door.state >= HEAVEN_DOOR_READY) heaven_door_travel(door, *player); + else if (door.state < HEAVEN_DOOR_EARLY) door.state = HEAVEN_DOOR_RESET; npc_sound_play(SOUND_HEAVEN_DOOR, 1, 2, 1); isEntered = true; break; diff --git a/src/entity_effect_combat.cpp b/src/entity_effect_combat.cpp index 879799d..919702e 100644 --- a/src/entity_effect_combat.cpp +++ b/src/entity_effect_combat.cpp @@ -212,7 +212,6 @@ constexpr float EXPLOSION_LARGE_SCALE = 1.4f; constexpr float EXPLOSION_SMALL_VOLUME = 0.95f; constexpr float EXPLOSION_LARGE_VOLUME = 1.1f; constexpr int ENTITY_DUKE_OF_FLIES = 67; -constexpr int ENTITY_RAG_MEGA = 409; constexpr const char* GFUEL_EXPLOSION_ANM2 = "gfx/promo/gfuel/effects/explosion3.anm2"; constexpr float SCISSORS_SCALE_DOUBLE = 0.75f; constexpr float SCISSORS_SCALE_TRIPLE = 0.5f; diff --git a/src/entity_effect_spike.cpp b/src/entity_effect_spike.cpp new file mode 100644 index 0000000..2b32ae6 --- /dev/null +++ b/src/entity_effect_spike.cpp @@ -0,0 +1,67 @@ +#include "entity_effect.h" +#include "entity_player.h" +#include "game.h" +#include "player_manager.h" + +// A spike rising from the womb's floor (Mama Gurdy's): it hurts the walking players it touches for a heart, without +// Callus or Socks, then sinks. Two Flat Files keep it down. +constexpr int SPIKE_DAMAGE_COUNTDOWN = 30; +constexpr int SPIKE_FLAT_FILES = 2; + +// Where a spike is in its rise: rising, up and hurting, and sinking. +enum SpikeState +{ + SPIKE_RISING = 1, + SPIKE_UP, + SPIKE_SINKING +}; + +// Part of 005cdb20 (Init's spike case) Starts rising for a heart's damage, or flattened by two Flat Files. +static void spike_init(Entity_Effect& spike) +{ + spike.state = SPIKE_RISING; + spike.collisionDamage = 1; + Entity_Player* owner = g_game->playerManager.FirstTrinketOwner(TRINKET_FLAT_FILE); + bool isFlat = owner && owner->GetTrinketMultiplier(TRINKET_FLAT_FILE) >= SPIKE_FLAT_FILES; + spike.sprite.Play(isFlat ? "SummonWombDisabled" : "SummonWomb"); +} + +// 005f2dd5 (Update's spike case) Rises (or, flattened, goes), hurts the walking players within reach while up, then sinks +// and goes. +static void spike_update(Entity_Effect& spike) +{ + if (spike.state == SPIKE_RISING && spike.sprite.IsFinished()) + { + if (spike.sprite.IsFinished("SummonWombDisabled")) spike.Remove(); + else spike.state = SPIKE_UP; + } + else if (spike.state == SPIKE_UP) + { + PlayerManager& players = g_game->playerManager; + for (int i = (int)players.playerList.size() - 1; i >= 0; i--) + { + Entity_Player& player = *players.playerList[i]; + float reach = player.size + spike.size; + float dx = player.pos.x - spike.pos.x; + float dy = player.pos.y - spike.pos.y; + if (dx * dx + dy * dy >= reach * reach || player.IsFlying()) continue; + if (player.HasTrinket(TRINKET_CALLUS) || player.HasCollectible(COLLECTIBLE_SOCKS)) continue; + + player.TakeDamage(spike.collisionDamage, DAMAGE_SPIKES, EntityRef(&spike), SPIKE_DAMAGE_COUNTDOWN); + } + if (!spike.sprite.IsFinished()) return; + + spike.sprite.Play("UnsummonWomb"); + spike.state = SPIKE_SINKING; + } + else if (spike.state == SPIKE_SINKING && spike.sprite.IsFinished()) spike.Remove(); +} + +constexpr auto SPIKE_BEHAVIOURS = std::to_array({ + {EFFECT_SPIKE, spike_init, effect_finishing, nullptr}, +}); + +std::span spike_effect_behaviours() +{ + return SPIKE_BEHAVIOURS; +} diff --git a/src/entity_effect_trail.cpp b/src/entity_effect_trail.cpp new file mode 100644 index 0000000..593d8c7 --- /dev/null +++ b/src/entity_effect_trail.cpp @@ -0,0 +1,98 @@ +#include "entity_effect_trail.h" +#include "beam_renderer.h" +#include "npc_ai.h" +#include +#include + +// A trail fades by its MinRadius each frame (scaled by the room's time), and Init starts it at this. +constexpr float TRAIL_FADE_DEFAULT = 0.1f; +// The most points a trail keeps, the oldest dropped first. +constexpr size_t TRAIL_POINTS_MAX = 128; +// A trail whose parent is gone has this state, and removes itself once its points have faded. +constexpr int TRAIL_ORPHANED = 99; +// Render skips a point closer to the last one drawn than this many of its widths. +constexpr float TRAIL_POINT_SPACING = 0.4f; + +// The trail's extra data, made when the effect has none of its kind. +static SpriteTrailData& trail_data_get(Entity_Effect& trail) +{ + auto* data = dynamic_cast(trail.extraData.get()); + if (data) return *data; + + trail.extraData = std::make_shared(); + return static_cast(*trail.extraData); +} + +// 005cdb20 (Init's case 166) Draws first in its layer, additively, with a fresh trail fading by the default. +static void trail_init(Entity_Effect& trail) +{ + trail.renderZOffset = INT_MIN; + trail.extraData = std::make_shared(); + trail.minRadius = TRAIL_FADE_DEFAULT; + layer_additive_set(*trail.sprite.GetLayer(0)); +} + +// 005dbcfd (Update's case 166) Lays a point where the effect is, as wide as its sprite's first layer, fades every +// point, and drops faded points from the tail (keeping one before a live point) and any past the limit. Orphaned by a +// spawner, it lays no more and goes once nothing is left. +// The original reads a missing first layer keyframe. Here no point is laid without one. +static void trail_update(Entity_Effect& trail) +{ + SpriteTrailData& data = trail_data_get(trail); + std::deque& points = data.points; + if (trail.spawnerType != 0 && !trail.parent) trail.state = TRAIL_ORPHANED; + + const AnimationFrame* keyframe = trail.state == 0 ? trail.sprite.animState.GetLayerFrame(0) : nullptr; + if (keyframe) + { + TrailPoint point = { + .color = trail.sprite.color, .pos = trail.pos, .width = trail.sprite.scale.x * keyframe->scale.x}; + if (!points.empty()) + point.coordinate = vector_length(vector_sub(points.back().pos, trail.pos)) + points.back().coordinate; + points.push_back(point); + } + + for (TrailPoint& point : points) point.life = std::max(point.life - trail.minRadius * trail.speedMultiplier, 0.0f); + while (!points.empty()) + { + bool isTailFaded = points[0].life == 0 && (points.size() < 2 || points[1].life == 0); + if (!isTailFaded && points.size() < TRAIL_POINTS_MAX) break; + points.pop_front(); + } + + if (trail.state == TRAIL_ORPHANED && points.empty()) trail.Remove(); +} + +// 00607620 (Render's case 166) Draws its sprite's first layer along the points, newest first, skipping points +// crowding the last drawn one, each as wide and as opaque as it has left. +static void trail_render(Entity_Effect& trail, const Vector& offset) +{ + auto* data = dynamic_cast(trail.extraData.get()); + if (!trail.sprite.isLoaded || !data || data->points.size() < 2) return; + + g_beamRenderer.Begin(trail.sprite, 0, BEAM_FRAME_MAIN, BEAM_COORDINATE_PIXELS); + Vector last{}; + bool isFirst = true; + for (auto point = data->points.rbegin(); point != data->points.rend(); ++point) + { + bool isCrowded = vector_length(vector_sub(point->pos, last)) < point->width * TRAIL_POINT_SPACING; + if (!isFirst && isCrowded) continue; + + BeamPoint beamPoint = { + .color = point->color, .coordinate = point->coordinate, .width = point->width * point->life}; + beamPoint.color._tint[3] *= point->life; + beamPoint.pos = vector_add(render_position_get(point->pos, RENDER_SNAPPED), offset); + g_beamRenderer.Add(beamPoint); + last = point->pos; + isFirst = false; + } + g_beamRenderer.End(); +} + +constexpr EffectBehaviour TRAIL_BEHAVIOURS[] = { + {EFFECT_SPRITE_TRAIL, trail_init, effect_finishing, trail_render}}; + +std::span trail_effect_behaviours() +{ + return TRAIL_BEHAVIOURS; +} diff --git a/src/entity_effect_trail.h b/src/entity_effect_trail.h new file mode 100644 index 0000000..7384607 --- /dev/null +++ b/src/entity_effect_trail.h @@ -0,0 +1,26 @@ +#pragma once + +#include "entity_effect.h" +#include +#include + +// One point a sprite trail left: where its effect was, its color and width then, how far along the trail it lies, and +// how much of it is left (1 when laid, fading to 0). +struct TrailPoint +{ + ColorMod color = COLOR_DEFAULT; + Vector pos{}; + float coordinate = 0; + float life = 1; + float width = 0; +}; + +// Construction (005d2270) and destruction (005d2370) are the defaults. +// The extra data of a sprite trail (effect 166): the points it laid, the oldest first. +struct SpriteTrailData : Entity_Effect::ExtraData +{ + std::deque points; +}; + +// The sprite trail, a strip of its sprite drawn along where it has been. +std::span trail_effect_behaviours(); diff --git a/src/entity_factory.cpp b/src/entity_factory.cpp index b4c0bd7..fc40bdf 100644 --- a/src/entity_factory.cpp +++ b/src/entity_factory.cpp @@ -29,14 +29,11 @@ constexpr int SPAWN_STATUS_FRAMES = 90; // The entity types, variants and boss ids spawning and layouts single out. constexpr int ENTITY_HORF = 12; -constexpr int ENTITY_HOST = 27; constexpr int ENTITY_FLAMINGHOPPER = 54; -constexpr int ENTITY_EYE = 60; constexpr int ENTITY_WALKINGBOIL = 88; constexpr int ENTITY_GREED_GAPER = 299; constexpr int ENTITY_MUSHROOM = 300; constexpr int ENTITY_SUB_HORF = 812; -constexpr int ENTITY_GYRO = 824; constexpr int EFFECT_CRAWLSPACE_LADDER = 192; constexpr int BOSS_SATAN = 24; @@ -44,17 +41,8 @@ constexpr int CARD_SPECIAL_CHANCE = 25; constexpr int CARD_RUNE_CHANCE = 10; constexpr int PICKUP_RANDOM_CARD = 301; -constexpr int SLOT_MACHINE = 1; -constexpr int SLOT_BEGGAR = 4; -constexpr int SLOT_DEVIL_BEGGAR = 5; -constexpr int SLOT_KEY_MASTER = 7; -constexpr int SLOT_SHELL_GAME = 6; constexpr int SLOT_DONATION = 8; constexpr int SLOT_CLOSET_TAINTED = 14; -constexpr int SLOT_HELL_GAME = 15; -constexpr int SLOT_CRANE_GAME = 16; -constexpr int SLOT_CONFESSIONAL = 17; -constexpr int SLOT_ROTTEN_BEGGAR = 18; constexpr int SHOPKEEPER_SPECIAL = 3; constexpr int SHOPKEEPER_SECRET_SPECIAL = 4; constexpr int EFFECT_VARIANT_TRAPDOOR_MARKER = 39; diff --git a/src/entity_familiar.cpp b/src/entity_familiar.cpp index 311c458..ec0ac58 100644 --- a/src/entity_familiar.cpp +++ b/src/entity_familiar.cpp @@ -124,6 +124,17 @@ constexpr int ORBIT_LAYER_WISPS = 8; constexpr int COLLECTIBLE_UNICORN_STUMP_ID = 298; constexpr int VERSUS_PUNCHING_INTERVAL = 16; +// How long a versus familiar leaves alone a target it chased too long. +constexpr int VERSUS_GIVE_UP_FRAMES = -900; + +// Headless Baby's blood and creep and Juicy Sack's creep: how often, and their sizes. +constexpr int HEADLESS_SPLAT_INTERVAL = 3; +constexpr int HEADLESS_CREEP_INTERVAL = 2; +constexpr int HEADLESS_CREEP_ODDS = 5; +constexpr int JUICY_SACK_CREEP_INTERVAL = 4; +constexpr float TRAIL_SCALE_RANGE = 0.5f; +constexpr float TRAIL_SCALE_MIN = 0.2f; + // How much bigger the familiars of BFFS! and Hive Mind look. constexpr float LOCUST_MULTIPLIED_SCALE = 1.1f; constexpr float MULTIPLIED_SCALE = 1.25f; @@ -161,6 +172,15 @@ std::vector familiar_query(int queryVariant) return found; } +// In a versus match, a familiar that chased its target longer than its limit leaves it alone for a while. +void familiar_chase_limit(Entity_Familiar& familiar, int chaseFrames) +{ + if (!familiar_versus() || !familiar.target) return; + + int& frames = familiar.targetFrames[familiar.target->index]; + if (frames > chaseFrames) frames = VERSUS_GIVE_UP_FRAMES; +} + // Whether a versus match runs, where familiars fight each other. bool familiar_versus() { @@ -487,6 +507,30 @@ void Entity_Familiar::Update() update_tail(); } +// A trail's size: a fifth to seven tenths of its own. +static float trail_scale() +{ + return random_unit() * TRAIL_SCALE_RANGE + TRAIL_SCALE_MIN; +} + +// Sizes a familiar's fresh splat or creep and runs its first frame. +static void trail_finish(Entity& trail, float scale) +{ + trail.sprite.scale = vector_make(scale, scale); + trail.Update(); +} + +// Leaves creep of a kind under a familiar (Headless Baby's red, Juicy Sack's white). +static void creep_drop(Entity_Familiar& familiar, int creepVariant) +{ + Entity* creep = g_game->Spawn({.position = familiar.pos, + .spawner = &familiar, + .type = ENTITY_EFFECT, + .variant = creepVariant, + .seed = Random()}); + trail_finish(*creep, trail_scale()); +} + // The behaviours of 0061da10 by variant. The familiars not reconstructed yet stop the game. void Entity_Familiar::variant_update() { @@ -510,9 +554,41 @@ void Entity_Familiar::variant_update() switch (variant) { case DEMON_BABY: return ai_auto_shooter(); + case BUM_FRIEND: + case DARK_BUM: + case KEY_BUM: + case SUPER_BUM: return ai_pickup_sack(); + case HOLY_WATER: + case BIG_CHUBBY: return ai_charger(); + case CUBE_OF_MEAT_3: + case CUBE_OF_MEAT_4: + case LEECH: return ai_walker(); + case BALL_OF_BANDAGES_3: + case BALL_OF_BANDAGES_4: + ai_walker(); + return Shoot(); + case HEADLESS_BABY: + FollowParent(); + if (IsFrame(HEADLESS_SPLAT_INTERVAL, 0)) + { + float scale = trail_scale(); + trail_finish(*g_game->Spawn({.position = pos, .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_SPLAT, + .seed = Random()}), + scale); + } + if (IsFrame(HEADLESS_CREEP_INTERVAL, 0) && random_below(HEADLESS_CREEP_ODDS) > 1) + creep_drop(*this, EFFECT_PLAYER_CREEP_RED); + return; + case JUICY_SACK: + sprite.Play("FloatDown"); + FollowParent(); + if (IsFrame(JUICY_SACK_CREEP_INTERVAL, 0)) creep_drop(*this, EFFECT_PLAYER_CREEP_WHITE); + return; case LITTLE_CHUBBY: case BOBS_BRAIN: return ai_charger(); - case DEAD_BIRD: return ai_flying_bird(); + case DEAD_BIRD: + case EVES_BIRD_FOOT: + case LIL_HAUNT: return ai_flying_bird(); case INCUBUS: FollowParent(); return update_weapon(false); diff --git a/src/entity_familiar.h b/src/entity_familiar.h index 6c6e1cf..62f3efe 100644 --- a/src/entity_familiar.h +++ b/src/entity_familiar.h @@ -102,6 +102,8 @@ struct Entity_Familiar : Entity JUICY_SACK = 52, ROBO_BABY_2 = 53, ROTTEN_BABY = 54, + HEADLESS_BABY = 55, + LEECH = 56, MYSTERY_SACK = 57, BBF = 58, BOBS_BRAIN = 59, @@ -426,6 +428,7 @@ template bool familiar_listed(const List& list, int value) std::vector familiar_query(int queryVariant); bool familiar_versus(); +void familiar_chase_limit(Entity_Familiar& familiar, int chaseFrames); void familiar_sound_play(int sound, SoundPlay play = {}); bool familiar_unicorn_active(Entity_Player& owner); Entity* spawn_dip_at(int subType, const Vector* position, Entity* spawner, const Vector* targetPosition); @@ -434,3 +437,4 @@ Vector direction_unit(int direction); void familiar_check(Entity_Player& player, const FamiliarCount& familiars); void familiars_evaluate(Entity_Player& player); int familiar_lullaby_delay(Entity_Familiar& familiar, int fireDelay); +bool bum_pickup_collect(Entity_Familiar& bum, Entity_Pickup& pickup); diff --git a/src/entity_knife.cpp b/src/entity_knife.cpp index 31450d8..6c463e1 100644 --- a/src/entity_knife.cpp +++ b/src/entity_knife.cpp @@ -1,14 +1,24 @@ #include "entity_knife.h" #include "anm2.h" +#include "boss_ai.h" +#include "entity_combat.h" #include "entity_config.h" #include "entity_effect.h" #include "entity_familiar.h" +#include "entity_laser.h" #include "entity_player.h" +#include "entity_projectile.h" #include "entity_tear.h" +#include "game.h" #include "log.h" #include "lua_engine.h" +#include "manager.h" #include "npc_ai.h" -#include "weapon_knives.h" +#include "room.h" +#include "room_grid.h" +#include "sfx_manager.h" +#include "weapon.h" +#include #include constexpr float KNIFE_DAMAGE_DEFAULT = 22; @@ -20,17 +30,316 @@ constexpr float KNIFE_GRAVITY = -2; constexpr float KNIFE_ORBIT_GRAVITY = -1; constexpr float KNIFE_SWING_GRAVITY_SCALE = 0.75f; constexpr float KNIFE_HYDROBOUNCE_LIFT = -10; -constexpr int KNIFE_SUBTYPE_HELD_ITEM = 4; constexpr const char* DEAD_EYE_EFFECT_PATH = "gfx/DeadEyeTearEffect.anm2"; +// How far from its owner a knife is held: Mom's Knife, a swung weapon, a sword, or a tear's knife by the tear's size. +constexpr float KNIFE_HOLD_DISTANCE = 30; +constexpr float KNIFE_SWUNG_HOLD_DISTANCE = 4; +constexpr float KNIFE_SWORD_HOLD_DISTANCE = 0.1f; +constexpr float KNIFE_TEAR_HOLD_SCALE = 20; + +// The flight: the pull back while flying out and while returning (weaker in orbit), the held turn rate, the anchor's +// drift with the charge, and how quickly a flying knife turns. +constexpr float KNIFE_PULL_OUT = -2; +constexpr float KNIFE_PULL_BACK = -5; +constexpr float KNIFE_ORBIT_PULL_OUT = -0.5f; +constexpr float KNIFE_ORBIT_PULL_BACK = -0.75f; +constexpr float KNIFE_HELD_TURN = 0.3f; +constexpr float KNIFE_FLYING_TURN = 0.8f; +constexpr float KNIFE_SNAP_ANGLE = 0.1f; +constexpr float KNIFE_ANCHOR_DRIFT = 0.8f; +constexpr float KNIFE_SPIRAL_SPEED = 0.75f; +constexpr float KNIFE_BIG_SPIRAL_SPEED = 0.5f; +constexpr float KNIFE_FRICTION = 0.7f; + +// An orbiting knife's loop: its turn per distance, how its offset bends it, and how it stretches. +constexpr float KNIFE_ORBIT_TURN_SKEW = 0.002f; +constexpr float KNIFE_ORBIT_RADIUS_SKEW = 0.02f; +constexpr float KNIFE_ORBIT_RADIUS_SHARE = 0.25f; +constexpr float KNIFE_ORBIT_STRETCH_X = 0.0002f; +constexpr float KNIFE_ORBIT_STRETCH_Y = 0.0014f; +constexpr float KNIFE_SPLIT_ORBIT_TURN = 0.5f; +constexpr float KNIFE_SPLIT_ORBIT_SHARE = 0.7f; + +// Spiral, Big Spiral and Square paths: the turn per distance, the widest swing, and the square's legs. +constexpr float KNIFE_SPIRAL_TURN = 3; +constexpr float KNIFE_SPIRAL_REACH = 50; +constexpr float KNIFE_BIG_SPIRAL_TURN = 2; +constexpr float KNIFE_BIG_SPIRAL_REACH = 180; +constexpr float KNIFE_SPIRAL_SPREAD = 0.5f; +constexpr float KNIFE_SQUARE_PERIOD = 120; +constexpr float KNIFE_SQUARE_SIDE = 20; +constexpr float KNIFE_SQUARE_OFFSET = 15; +constexpr uint32_t KNIFE_RNG_SHIFT = 35; + +// Brimstone's homing knives thrown back from a returning knife, and the knives Monstro's Lung throws. +constexpr float KNIFE_BRIMSTONE_REACH = 30; +constexpr float KNIFE_BRIMSTONE_DAMAGE = 0.4f; +constexpr float KNIFE_PATH_LIFT = -10; +constexpr float KNIFE_LUNG_MIN_CHARGE = 0.25f; +constexpr int KNIFE_LUNG_MIN_COUNT = 3; +constexpr float KNIFE_LUNG_REACH = 30; +constexpr float KNIFE_LUNG_FOLLOW_SPEED = 0.05f; +constexpr float KNIFE_PATH_STEER = 8; +constexpr float KNIFE_PATH_MARGIN = -200; +constexpr int KNIFE_PATH_LIFETIME = 300; +constexpr float KNIFE_PATH_DISTANCE_START = 1e7f; +constexpr float KNIFE_PATH_PROGRESS_FOUND = -99; +constexpr float KNIFE_PATH_HYDROBOUNCE_HOP = -5; +constexpr float KNIFE_PATH_HYDROBOUNCE_SPREAD = 3; + +// Hydrobounce's hop: its gravity, bounce and the splash it lands with. +constexpr float KNIFE_HOP_GRAVITY = 1.5f; +constexpr float KNIFE_HOP_SINK = -0.1f; +constexpr float KNIFE_HOP_MIN_BOUNCE = 0.5f; +constexpr float KNIFE_HOP_BOUNCE = -0.8f; +constexpr float KNIFE_SPLASH_SCALE = 0.75f; +constexpr float KNIFE_SPLASH_VOLUME = 0.5f; +constexpr float KNIFE_SPLASH_RADIUS = 30; + +// Ludovico's knife: how it turns, seeks (in reach), wiggles and rings its children around it. +constexpr float LUDOVICO_TURN = 0.24f; +constexpr float LUDOVICO_STILL_SPEED_SQUARED = 0.1f; +constexpr float LUDOVICO_REACH = 150; +constexpr float LUDOVICO_WIGGLE_RATE = 0.4f; +constexpr float LUDOVICO_WIGGLE_SHARE = 0.5f; +constexpr float LUDOVICO_WIGGLE_MAX = 30; +constexpr float LUDOVICO_RING_RADIUS = 5; +constexpr float LUDOVICO_RING_SPIN = 6; +constexpr float LUDOVICO_PULSE_RATE = 0.3f; +constexpr float LUDOVICO_PULSE_SHARE = 0.25f; +constexpr float INTERPOLATION_HALF_FRAME = 0.5f; + +// The chained knife's length, and the swung item's steps. +constexpr float KNIFE_CHAIN_LENGTH = 30; +constexpr int KNIFE_ITEM_WAIT_FRAMES = 4; +constexpr int KNIFE_ITEM_LUNGE_FRAME = 5; +constexpr float KNIFE_ITEM_LUNGE_SPEED = 16; + +// The sword's beam: its speed, the spin's doubling, its damage and the smallest tear. +constexpr float SWORD_BEAM_SPEED = 10; +constexpr float SWORD_BEAM_FALL_SPREAD = 0.2f; +constexpr float SWORD_BEAM_DAMAGE_BONUS = 2; +constexpr float SWORD_SPIN_BEAM_DAMAGE = 4; +constexpr float SWORD_BEAM_SCALE_MIN = 0.01f; +// The flag a sword carries while a full-health beam waits for the end of its swing. +constexpr uint64_t FLAG_SWORD_BEAM = FLAG_SPAWN_STICKY_SPIDERS; + +// Technology's laser and Brimstone's ring on a thrown knife, and Mysterious Liquid's creep. +constexpr float KNIFE_TECH_LIFT = -8; +constexpr float KNIFE_LASER_FRONT = 3000; +constexpr float KNIFE_LASER_BACK = -10; +constexpr float KNIFE_LASER_FRONT_Y = -0.5f; +constexpr int KNIFE_LASER_FADE_FRAMES = 8; +constexpr float KNIFE_LASER_GROW = 4; +constexpr float KNIFE_CREEP_MARGIN = 15; +constexpr float KNIFE_CREEP_SCALE = 0.4f; +constexpr int KNIFE_CREEP_FRAMES = 30; + +// The hit list's refresh and the grid hits of a knife. +constexpr int KNIFE_HIT_REFRESH = 3; +constexpr int SCYTHE_HIT_REFRESH = 5; +constexpr int SCYTHE_WAIT_HIT_REFRESH = 10; +constexpr float GRID_STEP = 40; +constexpr int KNIFE_HIT_COUNTDOWN = 30; +// Local until entity_player_weapons.cpp drops its copy for the shared PlayerItemId enum. +constexpr float KNIFE_BRIDGE_TURN = 90; +constexpr float KNIFE_TURN_QUARTER = 90; +constexpr float KNIFE_TURN_HALF = 180; +constexpr float KNIFE_TURN_FULL = 360; + +// The Dead Eye mark over a club: as strong as the charges (up to eight), lower and narrower while held. +constexpr int DEAD_EYE_LEVELS = 8; +constexpr float DEAD_EYE_HELD_SCALE_X = 0.9f; +constexpr float DEAD_EYE_HELD_SCALE_Y = 0.5f; +constexpr float DEAD_EYE_HELD_OFFSET = 0.5f; + +// The orbiting knife's two trailing ghosts: their fade and spacing. +constexpr int ORBIT_TRAIL_COUNT = 2; +constexpr float ORBIT_TRAIL_ALPHA = 0.6f; +constexpr float ORBIT_TRAIL_FADE = 0.3f; +constexpr float ORBIT_TRAIL_SPACING = 0.2f; + +// Notched Axe's empowered glow. +constexpr float AXE_GLOW_RATE = 0.2f; +constexpr std::array AXE_GLOW_PHASES = {0.5f, 0.25f, 0}; +constexpr std::array AXE_GLOW_STRENGTHS = {0.17f, 0.1f, 0.25f}; + +// Angelic Prism's four colored knives, split 20 degrees apart around a 30 degree turn. +constexpr std::array PRISM_COLORS = {{ + {{1, 1, 1, 1}, {0, 0, 0, 0}, {0.607843f, -0.392157f, -0.392157f}}, + {{1, 1, 1, 1}, {0, 0, 0, 0}, {0.541176f, 0.607843f, -0.392157f}}, + {{1, 1, 1, 1}, {0, 0, 0, 0}, {-0.392157f, 0.607843f, -0.262745f}}, + {{1, 1, 1, 1}, {0, 0, 0, 0}, {-0.392157f, 0.403922f, 0.607843f}}, +}}; +constexpr float PRISM_STEP = 20; +constexpr float PRISM_TURN = 30; +constexpr float PRISM_SPEED_BONUS = 2; + +// Multidimensional Baby's knife flickers through six tints, two frames each. +constexpr std::array MULTIDIMENSIONAL_COLORS = {{ + {{-1, -1, -1, 1}, {0, 0, 0, 0}, {1, 1, 1}}, + {{-0.33f, -0.33f, -0.33f, 1}, {0, 0, 0, 0}, {0.66f, 0.66f, 0.66f}}, + {{0.33f, 0.33f, 0.33f, 1}, {0, 0, 0, 0}, {0.33f, 0.33f, 0.33f}}, + {{1, 1, 1, 1}, {0, 0, 0, 0}, {0, 0, 0}}, + {{0.33f, 0.33f, 0.33f, 1}, {0, 0, 0, 0}, {0.33f, 0.33f, 0.33f}}, + {{-0.33f, -0.33f, -0.33f, 1}, {0, 0, 0, 0}, {0.66f, 0.66f, 0.66f}}, +}}; +constexpr int MULTIDIMENSIONAL_FRAMES = 2; + +// The sword's idle animations by facing, plain and charged. +constexpr std::array SWORD_IDLE_ANIMATIONS = {"IdleLeft", "IdleUp", "IdleRight", "IdleDown"}; +constexpr std::array SWORD_CHARGED_ANIMATIONS = {"ChargedLeft", "ChargedUp", "ChargedRight", + "ChargedDown"}; + // The sprite of Dead Eye's mark over a knife, loaded once for every knife. static ANM2 deadEyeSprite; +// How a knife's variant moves: thrown (Mom's Knife), swung (the clubs) or as a sword. +enum KnifeKind +{ + KNIFE_KIND_THROWN, + KNIFE_KIND_SWUNG, + KNIFE_KIND_SWORD +}; + // Whether a knife is a swung weapon: the clubs, bones, the bag and the axe. -static bool is_swung_variant(int variant) +bool is_swung_knife_variant(int variant) { return variant == KNIFE_BONE_CLUB || variant == KNIFE_BONE_SCYTHE || variant == KNIFE_DONKEY_JAWBONE || - variant == KNIFE_BAG_OF_CRAFTING || variant == 8 || variant == KNIFE_NOTCHED_AXE; + variant == KNIFE_BAG_OF_CRAFTING || variant == KNIFE_BERSERK_CLUB || variant == KNIFE_NOTCHED_AXE; +} + +// The way a knife's variant moves. +static KnifeKind knife_kind(int variant) +{ + if (is_swung_knife_variant(variant)) return KNIFE_KIND_SWUNG; + return variant == KNIFE_SPIRIT_SWORD || variant == KNIFE_TECH_SWORD ? KNIFE_KIND_SWORD : KNIFE_KIND_THROWN; +} + +// The weapon a knife's holder must keep for the knife to stay. +static WeaponType knife_weapon_type(KnifeKind kind) +{ + if (kind == KNIFE_KIND_SWUNG) return WEAPON_BONE; + return kind == KNIFE_KIND_SWORD ? WEAPON_SPIRIT_SWORD : WEAPON_KNIFE; +} + +// Plays a sound through the fart seeds. +static void knife_sound_play(int sound, float volume) +{ + seed_fart_sound_override(&sound); + g_manager->sfxManager.Play(sound, {.volume = volume}); +} + +// The point a fraction t along one bezier segment. +static Vector knife_path_point(const BezierPoint& start, const BezierPoint& end, float t) +{ + float u = 1 - t; + float b0 = u * u * u; + float b1 = u * u * 3 * t; + float b2 = u * 3 * t * t; + float b3 = t * t * t; + return vector_make(b0 * start.point.x + b1 * start.handleOut.x + b2 * end.handleIn.x + b3 * end.point.x, + b0 * start.point.y + b1 * start.handleOut.y + b2 * end.handleIn.y + b3 * end.point.y); +} + +// Turns a vector by an angle in degrees. +static Vector vector_rotated(Vector v, float degrees) +{ + float c = std::cos(degrees * DEGREES_TO_RADIANS); + float s = std::sin(degrees * DEGREES_TO_RADIANS); + return vector_make(v.x * c - v.y * s, v.x * s + v.y * c); +} + +// Whether the knife's holder still has the weapon the knife belongs to. Abyss's knife locust is not reconstructed yet. +static bool is_owner_armed(Entity* owner, WeaponType weaponType) +{ + if (owner->is_player()) return owner->ToPlayer()->HasWeaponType(weaponType); + if (!owner->IsFamiliar()) return true; + + Entity_Familiar& familiar = *static_cast(owner); + if (familiar.variant == Entity_Familiar::ABYSS_LOCUST && weaponType == WEAPON_KNIFE) + reconstruction_missing("Entity_Knife::Update 00961b00 (Abyss's knife locust)"); + return familiar.player && familiar.player->HasWeaponType(weaponType); +} + +// 0067d430 Hurts every vulnerable enemy within a radius of a position and gives it the tear effects. +void tear_flags_area_apply(const Vector& position, Entity* source, float radius, float damage, const TearFlags& flags) +{ + for (Entity* enemy : entity_query_radius(position, radius, QUERY_ENEMIES)) + { + if (!enemy->IsVulnerableEnemy(nullptr)) continue; + enemy->TakeDamage(damage, 0, EntityRef(source), KNIFE_HIT_COUNTDOWN); + Entity_Tear::ApplyTearFlagEffects(enemy, position, flags, source, damage); + } +} + +// Room::ScreenWrapPosition (00652ab0, 008131e0): a position that left the room a margin in wraps to the far side, across +// the axis it left along (sideways when it left straight or more up or down than sideways). +Vector room_screen_wrap(const Vector& position, float margin) +{ + Room& room = *g_game->room; + Vector clamped = room.GetClampedPositionImpl(position, margin, margin, margin, margin); + if (clamped.x == position.x && clamped.y == position.y) return position; + + float dx = clamped.x - position.x; + float dy = clamped.y - position.y; + bool isWrapX = dy == 0 || (dx != 0 && std::abs(dx) < std::abs(dy)); + Vector wrapped = position; + if (isWrapX) + { + float width = room.bottomRightPos.x - margin - (room.topLeftPos.x + margin); + if (clamped.x > position.x) wrapped.x += width; + else if (clamped.x < position.x) wrapped.x -= width; + } + else + { + float height = room.bottomRightPos.y - margin - (room.topLeftPos.y + margin); + if (clamped.y > position.y) wrapped.y += height; + else if (clamped.y < position.y) wrapped.y -= height; + } + return wrapped; +} + +// 0099c430 The squared distance from a point to a bezier segment, walked as five chords, and the fraction along it. +float bezier_closest_point(const Vector& point, const BezierPoint& start, const BezierPoint& end, float& outT) +{ + constexpr int CHORDS = 5; + float best = 1e6f; + float bestT = 0; + float previousT = 0; + Vector previous = start.point; + + for (int step = 1; step <= CHORDS; step++) + { + float t = (float)step / CHORDS; + Vector sample = knife_path_point(start, end, t); + Vector along = vector_sub(sample, previous); + Vector toPoint = vector_sub(point, previous); + float lengthSquared = vector_length_squared(along); + float share = lengthSquared == 0 ? 0 : vector_dot(along, toPoint) / lengthSquared; + float distance = 0; + if (lengthSquared == 0 || share < 0) + { + share = 0; + distance = vector_length_squared(toPoint); + } + else + { + share = std::min(share, 1.0f); + distance = vector_length_squared(vector_sub(point, vector_add(previous, vector_scale(along, share)))); + } + + if (distance < best) + { + bestT = (t - previousT) * share + previousT; + best = vector_length_squared(vector_sub(point, knife_path_point(start, end, bestT))); + } + previous = sample; + previousT = t; + } + outT = bestT; + return best; } // 00960c10 Sets a knife up: Dead Eye's shared mark sprite first, then its own sprite, its default damage, distance and @@ -76,8 +385,11 @@ void Entity_Knife::Init(int knifeType, int knifeVariant, int knifeSubType, uint3 fallingSpeed = 0; isDeadEyeHit = false; isSwinging = false; + isAttacking = false; + isSwingCharged = false; + isRecoiled = false; isSpinAttack = false; - removeDistance = KNIFE_DISTANCE_NONE; + splitDistance = KNIFE_DISTANCE_NONE; spinsLeft = 0; pathOffset = random_unit() * KNIFE_PATH_OFFSET_RANGE - KNIFE_PATH_OFFSET_RANGE / 2; AddEntityFlags(FLAG_NO_KNOCKBACK); @@ -86,11 +398,11 @@ void Entity_Knife::Init(int knifeType, int knifeVariant, int knifeSubType, uint3 hitList.clear(); bool isHeldItem = subtype == KNIFE_SUBTYPE_HELD_ITEM; - if (is_swung_variant(variant) || variant == KNIFE_SPIRIT_SWORD || variant == KNIFE_TECH_SWORD) + if (knife_kind(variant) != KNIFE_KIND_THROWN) { sprite.GetLayer(0)->isVisible = !isHeldItem; sprite.GetLayer(1)->isVisible = isHeldItem; - if (variant == KNIFE_SPIRIT_SWORD || variant == KNIFE_TECH_SWORD) sprite.GetLayer(2)->isVisible = isHeldItem; + if (knife_kind(variant) == KNIFE_KIND_SWORD) sprite.GetLayer(2)->isVisible = isHeldItem; } lua_engine_get().PostKnifeInit(this); } @@ -99,7 +411,7 @@ void Entity_Knife::Init(int knifeType, int knifeVariant, int knifeSubType, uint3 // Babylon's as Mom's Knife. int Entity_Knife::GetBaseVariant() { - if (is_swung_variant(variant)) return KNIFE_BONE_CLUB; + if (is_swung_knife_variant(variant)) return KNIFE_BONE_CLUB; if (variant == KNIFE_SUMPTORIUM) return KNIFE_MOMS_KNIFE; return variant == KNIFE_TECH_SWORD ? KNIFE_SPIRIT_SWORD : variant; } @@ -163,7 +475,7 @@ Entity_Player* Entity_Knife::GetPlayer() void Entity_Knife::Shoot(float throwCharge, float range) { float gravity = tearFlags[TEAR_ORBIT] ? KNIFE_ORBIT_GRAVITY : KNIFE_GRAVITY; - bool isSwung = is_swung_variant(variant); + bool isSwung = is_swung_knife_variant(variant); maxDistance = throwCharge * range; if (isSwung) gravity *= KNIFE_SWING_GRAVITY_SCALE; if (tearFlags[TEAR_HYDROBOUNCE]) @@ -201,7 +513,7 @@ void Entity_Knife::Reset() knifeVelocity = 0; isPrismApplied = false; isMultidimensionalApplied = false; - if (is_swung_variant(variant) && sprite.IsPlaying("Spin")) sprite.Play("Idle"); + if (is_swung_knife_variant(variant) && sprite.IsPlaying("Spin")) sprite.Play("Idle"); } // 009665e0 Sorts by its own depth, ignoring the sorting layer. @@ -211,101 +523,1220 @@ int Entity_Knife::GetRenderZ() } // 009666c0 The first knife of its chain of knives. -Entity* Entity_Knife::GetRootParent() +Entity_Knife* Entity_Knife::GetRootParent() { Entity* root = this; while (root->parent && root->parent->type == ENTITY_KNIFE) root = root->parent; - return root; + return static_cast(root); } -// The rest of Entity_Knife is not reconstructed yet. - -// 00961b00 -void Entity_Knife::Update() +// 00961320 Lays out a fresh path from the knife along a direction (curled for an orbiting knife), bent toward enemies +// for a homing one, that it follows offset sideways. +void Entity_Knife::InitHomingPath(Vector direction, Entity* source, float offset) { - reconstruction_missing("Entity_Knife::Update 00961b00"); + constexpr uint32_t PATH_SAMPLES = 30; + constexpr float PATH_REACH = 150; + constexpr float PATH_LENGTH = 200; + constexpr float PATH_MARGIN = 20; + constexpr float CURL_RADIUS = 60; + + homingLaser.samples.clear(); + homingLaser.smoothedSamples.clear(); + homingLaser.nonOptimizedSamples.clear(); + homingLaser.bezier.clear(); + pathSegment = 0; + pathOffset = offset; + pathProgress = KNIFE_PATH_PROGRESS_NONE; + homingLaser.sampleNum = PATH_SAMPLES; + homingLaser.totalLength = 0; + homingLaser.reach = PATH_REACH; + + Vector end = Entity_Laser::CalculateEndPoint(pos, direction, {}, nullptr, PATH_MARGIN); + homingLaser.origin = pos; + homingLaser.endPoint = vector_add(vector_scale(direction, PATH_LENGTH), end); + if (tearFlags[TEAR_ORBIT]) homingLaser.build_curl_path(CURL_RADIUS); + homingLaser.build_bezier_path(tearFlags[TEAR_HOMING] ? BEZIER_PATH_HOMING : BEZIER_PATH_STRAIGHT, source); } -// 00967db0 -void Entity_Knife::Interpolate() +// 009614d0 Takes a parent knife's look and power: its offset, color, flags, damage, turn and size, and whether Angelic +// Prism and Multidimensional Baby already split it. +void Entity_Knife::copy_parent_state(Entity_Knife& source) { - reconstruction_missing("Entity_Knife::Interpolate 00967db0"); + posOffset = source.posOffset; + SetColor(source.color, -1, COLOR_PRIORITY_DEFAULT, false, true); + tearFlags = source.tearFlags; + SetCollisionDamage(source.collisionDamage); + rotationOffset = angle_wrap(source.rotationOffset); + sprite.scale = source.sprite.scale; + isMultidimensionalApplied = source.isMultidimensionalApplied; + isPrismApplied = source.isPrismApplied; } -// 00965d30 -void Entity_Knife::Render(const Vector&) +// 00961870 Angelic Prism splits a flying knife into four colored ones, fanned 20 degrees apart: a held or thrown one +// hides and hands its flight on past the split, a path follower lays out fresh paths and goes. The root speeds up. +bool Entity_Knife::spawn_child_knife() { - reconstruction_missing("Entity_Knife::Render 00965d30"); + if (isPrismApplied || !isVisible || knifeVelocity <= 0 || + (subtype != KNIFE_SUBTYPE_HELD && subtype != KNIFE_SUBTYPE_PATH)) + return false; + + isVisible = false; + showDistance = knifeDistance; + isPrismApplied = true; + GetRootParent()->knifeVelocity += PRISM_SPEED_BONUS; + for (int i = 0; i < (int)PRISM_COLORS.size(); i++) + { + Entity* spawned = game_spawn({.position = pos, + .spawner = this, + .subType = subtype, + .type = ENTITY_KNIFE, + .variant = variant, + .seed = Random()}, + POOL_KEEP); + if (!spawned) break; + + Entity_Knife& child = *static_cast(spawned); + child.parent = this; + child.copy_parent_state(*this); + child.SetColor(PRISM_COLORS[i], -1, COLOR_PRIORITY_DEFAULT, false, true); + float angle = (float)i * PRISM_STEP; + if (subtype == KNIFE_SUBTYPE_PATH) + { + float offset = random_unit() * KNIFE_PATH_OFFSET_RANGE - KNIFE_PATH_OFFSET_RANGE / 2; + child.InitHomingPath(vector_from_angle(rotation - PRISM_TURN + angle), this, offset); + } + else + { + child.splitDistance = knifeDistance; + child.splitAngle = angle - PRISM_TURN; + } + child.Update(); + } + if (subtype == KNIFE_SUBTYPE_PATH) Remove(); + return true; } -// 009666f0 -bool Entity_Knife::HandleCollision(Entity*, bool) -{ - reconstruction_missing("Entity_Knife::HandleCollision 009666f0"); -} - -// 00961320 -void Entity_Knife::InitHomingPath(Vector, Entity*, float) -{ - reconstruction_missing("Entity_Knife::InitHomingPath 00961320"); -} - -// 009614d0 -void Entity_Knife::copy_parent_state(Entity_Knife*) -{ - reconstruction_missing("Entity_Knife::copy_parent_state 009614d0"); -} - -// 00961870 -uint32_t Entity_Knife::spawn_child_knife() -{ - reconstruction_missing("Entity_Knife::spawn_child_knife 00961870"); -} - -// 00967180 +// 00967180 Starts a throw's extras: the used tear effects reset, Monstro's Lung throws three to five homing knives (by +// the charge) from a root knife, and Tech X rings the knife with a laser that lasts the throw. void Entity_Knife::UpdateHomingPath() { - reconstruction_missing("Entity_Knife::UpdateHomingPath 00967180"); + constexpr float RING_MIN_CHARGE = 0.33f; + constexpr float RING_RADIUS_MIN = 20; + constexpr float RING_RADIUS_GROWTH = 60; + constexpr int RING_TIMEOUT = 600; + + bool isRoot = !parent || parent->type != ENTITY_KNIFE; + usedTearFlags.reset(); + Entity_Player* player = GetPlayer(); + if (!player) return; + + int baseVariant = GetBaseVariant(); + if (baseVariant != KNIFE_BONE_CLUB && baseVariant != KNIFE_SPIRIT_SWORD && isRoot && + player->HasCollectible(COLLECTIBLE_MONSTROS_LUNG) && charge > KNIFE_LUNG_MIN_CHARGE) + { + int count = (int)((float)(Random() % 3 + KNIFE_LUNG_MIN_COUNT) * charge); + for (; count > 0; count--) + { + float angle = random_unit() * KNIFE_TURN_FULL - KNIFE_TURN_HALF; + Vector direction = vector_from_angle(angle); + Entity* spawned = game_spawn({.position = vector_add(parent->pos, vector_scale(direction, KNIFE_LUNG_REACH)), + .spawner = player, + .subType = KNIFE_SUBTYPE_PATH, + .type = ENTITY_KNIFE, + .seed = Random()}, + POOL_OVERWRITE); + Entity_Knife& knife = *static_cast(spawned); + knife.posOffset = vector_make(0, KNIFE_PATH_LIFT); + knife.SetCollisionDamage(collisionDamage); + knife.SetColor(sprite.color, -1, COLOR_PRIORITY_DEFAULT, false, true); + knife.homingLaser = homingLaser; + knife.parent = this; + knife.tearFlags = tearFlags; + knife.InitHomingPath(direction, this, 0); + knife.pathFollowSpeed = KNIFE_LUNG_FOLLOW_SPEED; + knife.Update(); + } + } + + if (!player->HasCollectible(COLLECTIBLE_TECH_X)) return; + if (brimstoneLaser) brimstoneLaser->Remove(); + Entity_Laser& laser = *static_cast(game_spawn({.position = pos, + .spawner = player, + .subType = LASER_SUBTYPE_RING_FOLLOW_PARENT, + .type = ENTITY_LASER, + .variant = LASER_THIN_RED, + .seed = Random()}, + POOL_OVERWRITE)); + laser.SetColor(player->laserColor, -1, COLOR_PRIORITY_DEFAULT, false, true); + laser.posOffset = posOffset; + laser.parent = this; + laser.renderDepthOffset = KNIFE_LASER_FRONT; + laser.tearFlags = tearFlags; + laser.SetCollisionDamage(std::max(charge, RING_MIN_CHARGE) * collisionDamage); + laser.timeout = RING_TIMEOUT; + laser.radius = std::clamp(charge, 0.0f, 1.0f) * RING_RADIUS_GROWTH + RING_RADIUS_MIN; + laser.spawnerEntity = player; + laser.Update(); + brimstoneLaser = &laser; } -// 00967650 -void Entity_Knife::update_target(float*) +// 00967650 Homing: picks the nearest enemy it can hurt (or a versus rival), then bends the throw toward a point that +// slides onto it, curving the knife along a quadratic from its anchor and turning the flight angle with it. +void Entity_Knife::update_target(float& angle) { - reconstruction_missing("Entity_Knife::update_target 00967650"); + constexpr float SEEK_RANGE_SQUARED = 22500; + constexpr float TARGET_SLIDE = 0.04f; + constexpr float MIN_REACH = 0.0001f; + constexpr float REACH_SHARE = 0.25f; + + if (!target) + { + Entity* nearest = nullptr; + float nearestDistance = SEEK_RANGE_SQUARED; + for (Entity* entity : g_game->room->entityList.updateEL) + { + bool isEnemy = entity->IsVulnerableEnemy(this) && !entity->HasEntityFlags(FLAG_FRIENDLY | FLAG_NO_TARGET); + bool isRival = g_game->deathmatchManager.state >= DEATHMATCH_INTRO && entity->IsFamiliar() && + entity->variant == Entity_Familiar::PUNCHING_BAG && !entity->IsDescendantOf(spawnerEntity); + float distance = vector_length_squared(vector_sub(pos, entity->pos)); + if ((isEnemy || isRival) && entity->pendingDamage < entity->health && distance < nearestDistance) + { + nearestDistance = distance; + nearest = entity; + } + } + target = nearest; + } + + if (target) + { + if (vector_is_zero(targetPosition)) + { + float share = 1 - std::clamp(knifeDistance / maxDistance, 0.0f, 1.0f); + targetPosition = vector_add(pos, vector_scale(vector_sub(target->pos, pos), share)); + } + else + targetPosition = vector_add(targetPosition, vector_scale(vector_sub(target->pos, targetPosition), TARGET_SLIDE)); + } + + if (vector_is_zero(targetPosition) || knifeDistance <= 0) return; + Vector toTarget = vector_sub(targetPosition, anchorPosition); + Vector toKnife = vector_sub(pos, anchorPosition); + float reach = vector_length(toTarget); + if (reach <= MIN_REACH) return; + + float minReach = maxDistance * REACH_SHARE; + if (reach < minReach) + { + toTarget = vector_scale(toTarget, minReach / reach); + reach = minReach; + } + float t = knifeDistance / reach; + Vector control = vector_scale(toKnife, 1 / t); + pos = vector_add(vector_add(anchorPosition, vector_scale(control, (1 - t) * t)), vector_scale(toTarget, t * t)); + Vector tangent = vector_add(vector_scale(vector_sub(toTarget, control), 2 * t), control); + angle = vector_angle(tangent); } -// 00967a70 -void Entity_Knife::apply_wiggle(float*) +// 00967a70 Wiggle: sways the knife across its flight (along it in orbit), growing with its distance and charge, each +// split knife out of phase with the root, and turns the flight angle with the slope. +void Entity_Knife::apply_wiggle(float& angle) { - reconstruction_missing("Entity_Knife::apply_wiggle 00967a70"); + constexpr float WIGGLE_WAVELENGTH = 20; + constexpr float WIGGLE_AMPLITUDE = 30; + + Entity* owner = parent; + if (!owner) return; + + Vector toOwner{}; + if (owner->type == ENTITY_PLAYER) + { + toOwner = vector_sub(owner->pos, pos); + float length = vector_length(toOwner); + if (length > 0) toOwner = vector_scale(toOwner, 1 / length); + } + else if (owner->type == ENTITY_KNIFE && owner->parent && owner->parent->type == ENTITY_PLAYER) + toOwner = vector_normalized(vector_sub(owner->parent->pos, pos)); + + Vector across = tearFlags[TEAR_ORBIT] ? vector_make(toOwner.x, toOwner.y) : vector_make(-toOwner.y, toOwner.x); + float phase = 0; + if (GetRootParent() != this) + { + RNG rng; + rng.SetSeed(initSeed, KNIFE_RNG_SHIFT); + phase = rng.RandomFloat() * 2 * PI_F; + } + + float sway = std::sin(knifeDistance / WIGGLE_WAVELENGTH + phase) * WIGGLE_AMPLITUDE * knifeDistance / maxDistance * + charge; + pos = vector_add(pos, vector_scale(across, sway)); + float slope = std::cos(knifeDistance / WIGGLE_WAVELENGTH + phase) / WIGGLE_WAVELENGTH * WIGGLE_AMPLITUDE * + knifeDistance / maxDistance * charge; + angle -= std::atan(slope) * KNIFE_TURN_HALF / PI_F; } -// 00967d20 +// 00967d20 Continuum: a knife that left the room comes back in on the far side. void Entity_Knife::screen_wrap() { - reconstruction_missing("Entity_Knife::screen_wrap 00967d20"); + constexpr float KNIFE_WRAP_MARGIN = -100; + + for (Vector wrapped = room_screen_wrap(pos, KNIFE_WRAP_MARGIN); wrapped.x != pos.x || wrapped.y != pos.y; + wrapped = room_screen_wrap(pos, KNIFE_WRAP_MARGIN)) + pos = wrapped; } -// 009680d0 -void Entity_Knife::SetAttackAnimation() +// Brimstone's homing knife, thrown back toward the room every other frame of a returning knife. +void Entity_Knife::brimstone_knife_spawn(Entity_Player* player) { - reconstruction_missing("Entity_Knife::SetAttackAnimation 009680d0"); + uint32_t seed = Random(); + Vector direction = vector_from_angle(rotation); + Entity* spawned = game_spawn({.position = vector_add(parent->pos, vector_scale(direction, KNIFE_BRIMSTONE_REACH)), + .spawner = player, + .subType = KNIFE_SUBTYPE_PATH, + .type = ENTITY_KNIFE, + .seed = seed}, + POOL_KEEP); + if (!spawned) return; + + Entity_Knife& knife = *static_cast(spawned); + knife.posOffset = vector_make(0, KNIFE_PATH_LIFT); + knife.SetCollisionDamage(collisionDamage * KNIFE_BRIMSTONE_DAMAGE); + knife.SetColor(sprite.color, -1, COLOR_PRIORITY_DEFAULT, false, true); + knife.homingLaser = homingLaser; + knife.parent = this; + knife.tearFlags = tearFlags; + float offset = random_unit() * KNIFE_PATH_OFFSET_RANGE - KNIFE_PATH_OFFSET_RANGE / 2; + knife.InitHomingPath(vector_from_angle(rotation), this, offset); + knife.sprite.scale = sprite.scale; + knife.Update(); } -// 00968430 -void Entity_Knife::SpinAttack(short, int) +// The sword's beam at the end of a full-health (or spin) swing: a sword beam tear along the swing, faster and harder +// for a spin. +void Entity_Knife::sword_beam_fire(Entity_Player* player) { - reconstruction_missing("Entity_Knife::SpinAttack 00968430"); + ClearEntityFlags(FLAG_SWORD_BEAM); + Vector velocity = vector_scale(vector_from_angle(displayRotation), SWORD_BEAM_SPEED); + if (player) + { + Vector inherited = player->GetTearMovementInheritance(velocity, INHERIT_CHECKED); + velocity = vector_scale(vector_add(velocity, inherited), player->shotSpeed); + } + if (isSpinAttack) velocity = vector_scale(velocity, 2); + + Entity_Tear& tear = *static_cast( + g_game->Spawn({.position = pos, + .velocity = velocity, + .spawner = spawnerEntity, + .type = ENTITY_TEAR, + .variant = variant == KNIFE_TECH_SWORD ? TEAR_TECH_SWORD_BEAM : TEAR_SWORD_BEAM, + .seed = Random()})); + if (player) + { + tear.fallingAccel = player->tearFallingAcceleration; + tear.fallingSpeed = random_unit() * SWORD_BEAM_FALL_SPREAD - player->tearFallingSpeed; + tear.SetHeight(player->tearHeight); + } + tear.parent = spawnerEntity; + TearFlags flags = tearFlags; + flags.reset(TEAR_FETUS_FLAG); + tear.SetTearFlags(flags); + tear.isFireSoundMuted = true; + tear.SetColor(color, -1, COLOR_PRIORITY_DEFAULT, false, true); + tear.SetCollisionDamage(isSpinAttack ? collisionDamage * SWORD_SPIN_BEAM_DAMAGE + SWORD_SPIN_BEAM_DAMAGE + : collisionDamage + SWORD_BEAM_DAMAGE_BONUS); + tear.baseScale = std::max(sprite.scale.x, SWORD_BEAM_SCALE_MIN); + tear.fScale = tear.baseScale; + tear.ResetSpriteScale(); + tear.Update(); } -// 00968660 -uint8_t Entity_Knife::drain_notched_axe(int) +// 00961b00 One frame of a knife: held around or thrown out from its owner (or steered as Ludovico's), following a homing +// path, chained to its parent or swung as an item; then Multidimensional Baby's flicker, Strange Attractor's pull, +// the hit list's refresh, the mods' update and the grid it cuts. A knife whose owner lost its weapon goes. +void Entity_Knife::Update() { - reconstruction_missing("Entity_Knife::drain_notched_axe 00968660"); + if (!isInterpolating) friction *= KNIFE_FRICTION; + Entity_Player* player = GetPlayer(); + + if (!parent) + Remove(); + else if (subtype == KNIFE_SUBTYPE_HELD) + { + if (variant == KNIFE_NOTCHED_AXE) + { + LayerState& layer = *sprite.GetLayer(0); + float time = (float)g_game->frameCount * AXE_GLOW_RATE; + for (int i = 0; i < 3; i++) + layer.color._offset[i] = player && player->HasCollectible(COLLECTIBLE_BOOK_OF_BELIAL_PASSIVE) + ? std::sin(time + AXE_GLOW_PHASES[i]) * AXE_GLOW_STRENGTHS[i] + + AXE_GLOW_STRENGTHS[i] + : 0; + } + + if (!tearFlags[TEAR_LUDOVICO]) + { + if (!held_update(player)) return; + } + else if (parent->is_player()) + ludovico_update(); + + if (isFlying && tearFlags[TEAR_HYDROBOUNCE]) hydrobounce_update(); + if (!isInterpolating) lasers_update(player); + } + else if (subtype == KNIFE_SUBTYPE_PATH) + path_update(); + else if (subtype == KNIFE_SUBTYPE_CHAINED) + { + chained_update(); + friction *= KNIFE_FRICTION; + } + else if (subtype == KNIFE_SUBTYPE_HELD_ITEM) + held_item_update(); + + if (!isInterpolating && isMultidimensionalApplied) + { + int index = (g_game->frameCount - spawnFrame) / MULTIDIMENSIONAL_FRAMES % (int)MULTIDIMENSIONAL_COLORS.size(); + ColorMod flicker = color; + color_multiply(flicker, MULTIDIMENSIONAL_COLORS[index]); + sprite.color = flicker; + } + if (tearFlags[TEAR_ATTRACTOR] && !isInterpolating) + reconstruction_missing("Entity_Knife::Update 00961b00 (Strange Attractor, Game::AttractEntities 00705b90)"); + + KnifeKind kind = knife_kind(variant); + if (kind != KNIFE_KIND_THROWN && isFlying && config) size = config->collisionRadius * sprite.scale.x; + int refresh = kind == KNIFE_KIND_THROWN ? KNIFE_HIT_REFRESH : 0; + if (variant == KNIFE_BONE_SCYTHE) refresh = tearFlags[TEAR_WAIT] ? SCYTHE_WAIT_HIT_REFRESH : SCYTHE_HIT_REFRESH; + if (refresh && IsFrame(refresh, 0)) hitList.clear(); + + lua_engine_get().PostKnifeUpdate(this); + if (isInterpolating) return; + + if ((kind == KNIFE_KIND_THROWN || isFlying) && isVisible) grid_hit_update(player); + Entity::Update(); } -// 009688d0 -void Entity_Knife::UpdateSwingHits() +// A held or thrown knife: it follows its root knife's turn and charge, keeps to its owner's weapon, swings or spins +// with the root, sits around the owner (turning toward the aim) or flies out and back along its tear effects' paths, +// and fires Brimstone's homing knives and Mysterious Liquid's creep as it goes. False when the knife went and the +// frame ends there. +bool Entity_Knife::held_update(Entity_Player* player) { - reconstruction_missing("Entity_Knife::UpdateSwingHits 009688d0"); + KnifeKind kind = knife_kind(variant); + Entity_Knife* root = GetRootParent(); + Entity* owner = root->parent; + bool isRoot = root == this; + float holdDistance = kind == KNIFE_KIND_SWUNG ? KNIFE_SWUNG_HOLD_DISTANCE + : kind == KNIFE_KIND_SWORD ? KNIFE_SWORD_HOLD_DISTANCE + : KNIFE_HOLD_DISTANCE; + if (parent->type == ENTITY_TEAR && kind == KNIFE_KIND_THROWN) + holdDistance = parent->ToTear()->fScale * KNIFE_TEAR_HOLD_SCALE; + + // A knife without an owner is removed: the original reads through null. + bool isOwnerChecked = variant != KNIFE_NOTCHED_AXE && variant != KNIFE_BERSERK_CLUB && variant != KNIFE_BAG_OF_CRAFTING; + if (!owner || (isOwnerChecked && !is_owner_armed(owner, knife_weapon_type(kind)))) + { + Remove(); + return false; + } + + if (!isRoot) + { + if (kind != KNIFE_KIND_THROWN && g_game->frameCount - spawnFrame < 2) sprite.Play(root->sprite.GetAnimation()); + rotation = root->rotation; + displayRotation = rotationOffset + root->displayRotation - root->rotationOffset; + charge = root->charge; + if (!isFlying && root->isFlying) + { + height = root->height; + fallingSpeed = root->fallingSpeed; + basePosOffsetY = root->basePosOffsetY; + UpdateHomingPath(); + } + } + + bool isSwingHandled = false; + if (kind == KNIFE_KIND_SWORD) + { + if (sprite.animState.animData && sprite.IsEventTriggered("SwingEnd") && !isInterpolating) + { + if (HasEntityFlags(FLAG_SWORD_BEAM) || isSpinAttack) + { + sword_beam_fire(player); + if (isSpinAttack && spinsLeft > 1) + { + if (spinEffect) spinEffect->Remove(); + spinsLeft--; + SpinAttack(spinsLeft, 2); + isSwingHandled = true; + } + } + } + else if (!isRoot && root->isSpinAttack && !isSpinAttack) + { + SpinAttack(root->spinsLeft, 0); + isSwingHandled = true; + } + } + if (root->isSwinging && !root->isFlying && !isSwingHandled) + { + UpdateSwingHits(); + isSwingHandled = true; + } + if (kind == KNIFE_KIND_SWORD && !root->isSwinging) + { + if (root->isAttacking) + { + int facing = vector_to_direction(vector_from_angle(displayRotation)); + sprite.Play(root->isSwingCharged ? SWORD_CHARGED_ANIMATIONS[facing] : SWORD_IDLE_ANIMATIONS[facing]); + } + if (!isSwingHandled) UpdateSwingHits(); + } + + Vector tip{}; + float angle = 0; + if (!root->isFlying) + { + if (isRoot) + { + if (g_game->frameCount - spawnFrame < 2 || std::abs(displayRotation - rotation) <= KNIFE_SNAP_ANGLE) + displayRotation = rotationOffset + rotation; + else + { + float turn = player && player->HasCollectible(COLLECTIBLE_TRACTOR_BEAM) ? 1 : KNIFE_HELD_TURN; + displayRotation = angle_lerp(displayRotation, rotationOffset + rotation, turn); + } + } + else + isFlying = false; + + targetPosition = {}; + target = nullptr; + if (splitDistance >= 0 && !isRoot) Remove(); + splitDistance = KNIFE_DISTANCE_NONE; + if (showDistance >= 0) isVisible = true; + showDistance = KNIFE_DISTANCE_NONE; + pos = vector_add(owner->pos, vector_scale(vector_from_angle(displayRotation), holdDistance)); + anchorPosition = owner->pos; + tip = pos; + basePosOffsetY = posOffset.y; + angle = vector_angle(vector_sub(pos, owner->pos)); + } + else + { + if (isRoot) + { + float speed = speedMultiplier; + if (tearFlags[TEAR_BIG_SPIRAL]) speed *= KNIFE_BIG_SPIRAL_SPEED; + else if (tearFlags[TEAR_SPIRAL]) speed *= KNIFE_SPIRAL_SPEED; + displayRotation = angle_lerp(displayRotation, rotationOffset + rotation, KNIFE_FLYING_TURN); + + float velocity = knifeVelocity; + knifeDistance += speed * velocity * 0.5f; + float pullOut = tearFlags[TEAR_ORBIT] ? KNIFE_ORBIT_PULL_OUT : KNIFE_PULL_OUT; + float pullBack = tearFlags[TEAR_ORBIT] ? KNIFE_ORBIT_PULL_BACK : KNIFE_PULL_BACK; + if (kind == KNIFE_KIND_SWUNG) + { + pullOut *= KNIFE_SWING_GRAVITY_SCALE; + pullBack *= KNIFE_SWING_GRAVITY_SCALE; + } + if (!isInterpolating) + { + knifeVelocity = (velocity <= 0 ? pullBack : pullOut) * speed + velocity; + if (velocity > 0 && knifeVelocity <= 0 && kind == KNIFE_KIND_SWUNG) hitList.clear(); + } + + if (knifeDistance < 0) + { + targetPosition = {}; + target = nullptr; + knifeDistance = 0; + isFlying = false; + isPrismApplied = false; + isMultidimensionalApplied = false; + posOffset.y = basePosOffsetY; + if (kind == KNIFE_KIND_SWUNG) sprite.Play("Idle"); + if (kind != KNIFE_KIND_THROWN && parent == player) knife_sound_play(SOUND_SCAMPER, 1); + } + } + else if (kind != KNIFE_KIND_THROWN) + { + if (!isFlying) + { + if (kind == KNIFE_KIND_SWUNG) + { + sprite.rotation = 0; + sprite.Play("Spin"); + sprite.SetFrame((float)random_below(sprite.animState.GetAnimationLength())); + } + hitList.clear(); + } + if (knifeVelocity > 0 && root->knifeVelocity <= 0) hitList.clear(); + } + + if (vector_is_zero(anchorPosition)) anchorPosition = owner->pos; + if (!isRoot) + { + isFlying = true; + knifeDistance = root->knifeDistance; + maxDistance = root->maxDistance; + charge = root->charge; + knifeVelocity = root->knifeVelocity; + } + float share = std::min(std::max(knifeDistance / maxDistance, 0.0f), 1.0f); + float keep = 1 - charge * share * KNIFE_ANCHOR_DRIFT; + anchorPosition = vector_add(anchorPosition, vector_scale(vector_sub(owner->pos, anchorPosition), keep)); + + if (!tearFlags[TEAR_ORBIT]) + pos = vector_add(anchorPosition, vector_scale(vector_from_angle(displayRotation), knifeDistance + holdDistance)); + else + { + float skew = angle_wrap(rotationOffset); + float turn = knifeDistance * PI_F * 2 * (skew * KNIFE_ORBIT_TURN_SKEW + 1) + displayRotation; + float radius = (1 - skew * KNIFE_ORBIT_RADIUS_SKEW) * knifeDistance * KNIFE_ORBIT_RADIUS_SHARE + holdDistance; + pos = vector_add(anchorPosition, vector_scale(vector_from_angle(turn), radius)); + float stretchX = knifeDistance * KNIFE_ORBIT_STRETCH_X * std::abs(knifeVelocity) + 1; + float stretchY = knifeDistance * KNIFE_ORBIT_STRETCH_Y * std::abs(knifeVelocity) + 1; + float stretch = stretchY > stretchX ? stretchY : stretchX; + SetSize(stretch * config->collisionRadius, vector_make(stretchX / stretch, stretchY / stretch), -1); + } + + angle = vector_angle(vector_sub(pos, owner->pos)); + if (tearFlags[TEAR_ORBIT]) angle += KNIFE_TURN_QUARTER; + if (splitDistance >= 0) + { + if (knifeDistance < splitDistance && !isRoot) + { + Remove(); + return false; + } + if (knifeDistance > splitDistance) + for (Entity_Knife* knife = this; knife->splitDistance >= 0;) + { + float distance = knife->splitDistance; + float turn = displayRotation; + if (tearFlags[TEAR_ORBIT]) + { + turn = distance * PI_F * KNIFE_SPLIT_ORBIT_TURN + displayRotation; + distance *= KNIFE_SPLIT_ORBIT_SHARE; + } + Vector fork = vector_add(anchorPosition, vector_scale(vector_from_angle(turn), distance + holdDistance)); + pos = vector_add(fork, vector_rotated(vector_sub(pos, fork), knife->splitAngle)); + angle += knife->splitAngle; + pos = vector_add(pos, vector_rotated(knife->splitOffset, angle)); + if (!knife->parent || knife->parent->type != ENTITY_KNIFE) break; + knife = static_cast(knife->parent.get()); + } + } + + tip.y = pos.y; + if (showDistance >= 0 && !isVisible && knifeDistance > showDistance) isVisible = true; + tip.x = pos.x; + if (tearFlags[TEAR_CONTINUUM]) screen_wrap(); + if (tearFlags[TEAR_HOMING]) update_target(angle); + if (tearFlags[TEAR_WIGGLE]) apply_wiggle(angle); + + bool isBigSpiral = tearFlags[TEAR_BIG_SPIRAL]; + if (isBigSpiral || tearFlags[TEAR_SPIRAL]) + { + float phase = 0; + if (!isRoot) + { + RNG rng; + rng.SetSeed(initSeed, KNIFE_RNG_SHIFT); + phase = rng.RandomFloat() * KNIFE_TURN_FULL; + } + float turnRate = isBigSpiral ? KNIFE_BIG_SPIRAL_TURN : KNIFE_SPIRAL_TURN; + float reach = std::clamp(knifeDistance * KNIFE_SPIRAL_SPREAD, 0.0f, + isBigSpiral ? KNIFE_BIG_SPIRAL_REACH : KNIFE_SPIRAL_REACH); + Vector swing = vector_rotated(vector_from_angle(knifeDistance * turnRate + phase), angle); + pos = vector_add(pos, vector_scale(swing, reach)); + angle = knifeDistance * turnRate + KNIFE_TURN_QUARTER + phase + angle; + } + + if (tearFlags[TEAR_SQUARE]) + { + float phase = 0; + if (!isRoot) + { + RNG rng; + rng.SetSeed(initSeed, KNIFE_RNG_SHIFT); + phase = rng.RandomFloat() * KNIFE_SQUARE_PERIOD; + } + Vector ahead = vector_from_angle(angle); + float c = std::cos(PI_F / 2); + float s = std::sin(PI_F / 2); + Vector side = vector_make(c * ahead.x - s * ahead.y, s * ahead.x + c * ahead.y); + float leg = std::fmod(phase + knifeDistance, KNIFE_SQUARE_PERIOD); + float forward = 0; + float across = 0; + if (leg < 40) + { + forward = leg * KNIFE_SQUARE_SIDE / 40; + across = -KNIFE_SQUARE_OFFSET; + } + else if (leg < 60) + { + forward = (60 - leg) * KNIFE_SQUARE_SIDE / 20; + across = -(KNIFE_SQUARE_OFFSET - (leg - 40) * 30 / 20); + angle += KNIFE_TURN_QUARTER; + } + else if (leg < 100) + { + forward = (leg - 60) * KNIFE_SQUARE_SIDE / 40; + across = KNIFE_SQUARE_OFFSET; + } + else + { + forward = (KNIFE_SQUARE_PERIOD - leg) * KNIFE_SQUARE_SIDE / 20; + across = KNIFE_SQUARE_OFFSET - (leg - 100) * 30 / 20; + angle -= KNIFE_TURN_QUARTER; + } + pos = vector_add(pos, vector_add(vector_scale(ahead, forward), vector_scale(side, across))); + } + + if (isRoot && player && player->HasCollectible(COLLECTIBLE_BRIMSTONE) && knifeVelocity < 0 && IsFrame(2, 0)) + brimstone_knife_spawn(player); + } + + if (kind == KNIFE_KIND_THROWN) + { + sprite.rotation = angle_wrap(angle - KNIFE_TURN_QUARTER); + sprite.GetLayer(0)->isFlipX = sprite.rotation > 0; + } + else if (isFlying) + { + if (kind == KNIFE_KIND_SWORD) sprite.rotation = angle_wrap(angle - KNIFE_TURN_QUARTER); + } + else + { + sprite.rotation = angle_wrap(vector_angle(vector_sub(tip, owner->pos)) - KNIFE_TURN_QUARTER); + if (const AnimationFrame* frame = sprite.animState.GetLayerFrame(0)) + { + Vector facing = vector_from_angle(sprite.rotation); + knifeDepthOffset = facing.x * frame->pos.y + facing.y * frame->pos.x; + } + } + flightAngle = angle; + + if (isFlying && isVisible && tearFlags[TEAR_MYSTERIOUS_LIQUID_CREEP] && IsFrame(2, 0) && (Random() & 1) == 0) + { + Vector at = g_game->room->GetClampedPosition(pos, KNIFE_CREEP_MARGIN); + Entity_Effect& creep = *static_cast(g_game->Spawn({.position = at, + .spawner = spawnerEntity, + .type = ENTITY_EFFECT, + .variant = EFFECT_PLAYER_CREEP_GREEN, + .seed = Random()})); + creep.SetTimeout(KNIFE_CREEP_FRAMES); + creep.sprite.scale = vector_scale(vector_make(KNIFE_CREEP_SCALE, KNIFE_CREEP_SCALE), sprite.scale.x); + creep.Update(); + } + + bool isLoose = !isRoot || variant == KNIFE_BERSERK_CLUB || variant == KNIFE_BAG_OF_CRAFTING; + if (isLoose && !root->isFlying && !root->isAttacking && !root->isSwinging) Remove(); + return true; +} + +// Ludovico's knife: steered by the shots, it turns with its motion, seeks the nearest enemy when homing, wiggles, +// stays in the room unless Continuum wraps it, and rings the knives chained to it around itself. +void Entity_Knife::ludovico_update() +{ + constexpr float REACH_SQUARED = LUDOVICO_REACH * LUDOVICO_REACH; + + if (!parent->ToPlayer()->HasWeaponType(knife_weapon_type(knife_kind(variant)))) Remove(); + isFlying = false; + if (vector_length_squared(velocity) > LUDOVICO_STILL_SPEED_SQUARED) + sprite.rotation = angle_lerp(sprite.rotation, vector_angle(velocity) - KNIFE_TURN_QUARTER, LUDOVICO_TURN); + sprite.GetLayer(0)->isFlipX = sprite.rotation > 0; + if (tearFlags[TEAR_CONTINUUM]) screen_wrap(); + + if (tearFlags[TEAR_HOMING] && !target) + { + Entity* nearest = nullptr; + float nearestDistance = REACH_SQUARED; + for (Entity* enemy : entity_query_radius(pos, LUDOVICO_REACH, QUERY_ENEMIES)) + { + if (!enemy->IsVulnerableEnemy(nullptr)) continue; + float distance = vector_length_squared(vector_sub(pos, enemy->pos)); + if (enemy->pendingDamage < enemy->health && distance < nearestDistance) + { + nearestDistance = distance; + nearest = enemy; + } + } + target = nearest; + } + else if (tearFlags[TEAR_HOMING]) + { + velocity = vector_sub(velocity, vector_normalized(vector_sub(pos, target->pos))); + if (vector_length_squared(vector_sub(pos, target->pos)) > REACH_SQUARED) target = nullptr; + } + + if (tearFlags[TEAR_WIGGLE]) + { + Vector across = vector_normalized(vector_make(velocity.y, -velocity.x)); + float sway = std::min(vector_length(velocity) * LUDOVICO_WIGGLE_SHARE, LUDOVICO_WIGGLE_MAX); + pos = vector_add(pos, vector_scale(across, std::sin((float)g_game->frameCount * LUDOVICO_WIGGLE_RATE) * sway)); + } + if (!tearFlags[TEAR_CONTINUUM]) pos = g_game->room->GetClampedPosition(pos, 0); + + std::vector ring; + for (Entity* knife = child; knife; knife = knife->child) ring.push_back(knife); + float time = (float)g_game->frameCount + (isInterpolating ? INTERPOLATION_HALF_FRAME : 0); + for (size_t i = 0; i < ring.size(); i++) + { + Entity_Knife& knife = *static_cast(ring[i]); + knife.velocity = velocity; + float radius = size * LUDOVICO_RING_RADIUS; + float angle = (float)i * KNIFE_TURN_FULL / (float)ring.size() + time * LUDOVICO_RING_SPIN; + if (tearFlags[TEAR_PULSE]) + radius *= (std::sin(time * LUDOVICO_PULSE_RATE) + 1) * 0.5f * LUDOVICO_PULSE_SHARE + 1; + knife.pos = vector_add(pos, vector_scale(vector_from_angle(angle), radius)); + knife.sprite.rotation = angle_wrap(angle - KNIFE_TURN_QUARTER); + knife.SetColor(sprite.color, -1, COLOR_PRIORITY_DEFAULT, false, true); + knife.tearFlags = tearFlags; + knife.SetCollisionDamage(collisionDamage); + } +} + +// Hydrobounce's landing: the knife stops falling (bouncing back up while it flies out fast), splashes, and hurts and +// affects the enemies around it. +void Entity_Knife::hydrobounce_land() +{ + Entity* splash = g_game->Spawn( + {.position = pos, .type = ENTITY_EFFECT, .variant = EFFECT_RIPPLE_POOF, .seed = Random()}); + splash->sprite.scale = vector_make(KNIFE_SPLASH_SCALE, KNIFE_SPLASH_SCALE); + splash->SetColor(sprite.color, -1, COLOR_PRIORITY_DEFAULT, false, true); + splash->Update(); + knife_sound_play(SOUND_TEAR_IMPACTS, KNIFE_SPLASH_VOLUME); + tear_flags_area_apply(pos, this, KNIFE_SPLASH_RADIUS, collisionDamage, tearFlags); +} + +// Hydrobounce on a thrown knife: it hops while flying out and sinks back on return, the sprite tilting with the hop. +void Entity_Knife::hydrobounce_update() +{ + if (height < 0 || fallingSpeed < 0) + { + height += fallingSpeed; + if (knifeVelocity <= 0) fallingSpeed = std::max(height * KNIFE_HOP_SINK, fallingSpeed); + else fallingSpeed += KNIFE_HOP_GRAVITY; + if (height >= 0) + { + height = 0; + bool isBouncing = knifeVelocity > 0 && fallingSpeed > KNIFE_HOP_MIN_BOUNCE; + fallingSpeed = isBouncing ? fallingSpeed * KNIFE_HOP_BOUNCE : 0; + hydrobounce_land(); + } + } + posOffset.y = height + basePosOffsetY; + + if (knife_kind(variant) != KNIFE_KIND_THROWN) return; + float tilt = std::atan2(-fallingSpeed, knifeVelocity) * RADIANS_TO_DEGREES; + sprite.rotation += tilt * std::sin(sprite.rotation * DEGREES_TO_RADIANS); + if (knifeVelocity < 0) + { + LayerState& layer = *sprite.GetLayer(0); + layer.isFlipX = !layer.isFlipX; + } +} + +// A thrown knife's lasers: a resting knife fades out Tech X's ring, a flying one under Technology keeps a laser from +// the player to the knife, which goes when the knife lands or dies. +void Entity_Knife::lasers_update(Entity_Player* player) +{ + if (!isFlying || isDead) + { + if (Entity_Laser* ring = static_cast(brimstoneLaser.get())) + { + if (ring->timeout > KNIFE_LASER_FADE_FRAMES) + ring->timeout = KNIFE_LASER_FADE_FRAMES; + else + { + ColorMod faded = ring->sprite.color; + faded._tint[3] = (float)std::min(ring->timeout, KNIFE_LASER_FADE_FRAMES) * color._tint[3] / + KNIFE_LASER_FADE_FRAMES; + ring->sprite.color = faded; + ring->radius += KNIFE_LASER_GROW; + } + } + } + else if (player && player->HasCollectible(COLLECTIBLE_TECHNOLOGY)) + { + Entity_Laser* laser = static_cast(techLaser.get()); + bool isNew = !laser; + if (isNew) + { + laser = Entity_Laser::ShootAngle({.position = player->pos, + .posOffset = vector_add(player->posOffset, vector_make(0, KNIFE_TECH_LIFT)), + .source = player, + .timeout = -1, + .variant = LASER_THIN_RED}); + TearFlags flags = tearFlags; + for (int bit : {TEAR_WIGGLE, TEAR_SQUARE, TEAR_SPIRAL, TEAR_BIG_SPIRAL, TEAR_ORBIT}) flags.reset(bit); + laser->tearFlags = flags; + laser->SetColor(player->laserColor, -1, COLOR_PRIORITY_DEFAULT, false, true); + laser->SetCollisionDamage(charge * collisionDamage); + laser->mass = 0; + techLaser = laser; + } + Vector toKnife = vector_sub(pos, laser->pos); + laser->set_aim_angle(vector_angle(toKnife)); + laser->maxDistance = vector_length(toKnife); + laser->renderDepthOffset = toKnife.y < KNIFE_LASER_FRONT_Y ? KNIFE_LASER_BACK : KNIFE_LASER_FRONT; + if (isNew) laser->Update(); + } + if ((!isFlying || isDead) && techLaser) techLaser->Remove(); +} + +// A knife following a homing path: it steers toward the next stretch of the path (offset sideways), hops under +// Hydrobounce, and goes when it loses the path, leaves the room (Continuum wraps it once onto a fresh path) or ages out. +void Entity_Knife::path_update() +{ + float bestT = KNIFE_PATH_PROGRESS_NONE; + float bestDistance = KNIFE_PATH_DISTANCE_START; + int bestSegment = 0; + for (int segment = pathSegment; segment + 1 < (int)homingLaser.bezier.size(); segment++) + { + float t = 0; + float distance = bezier_closest_point(pos, homingLaser.bezier[segment], homingLaser.bezier[segment + 1], t); + if (distance >= bestDistance || (segment == pathSegment && t <= pathProgress)) continue; + bestT = t; + bestDistance = distance; + bestSegment = segment; + } + + if (tearFlags[TEAR_HYDROBOUNCE]) + { + if (g_game->frameCount - spawnFrame == 1) + fallingSpeed = KNIFE_PATH_HYDROBOUNCE_HOP - random_unit() * KNIFE_PATH_HYDROBOUNCE_SPREAD; + if (height < 0 || fallingSpeed < 0) + { + float fall = fallingSpeed + KNIFE_HOP_GRAVITY; + height += fallingSpeed; + fallingSpeed = fall; + if (height >= 0) + { + height = 0; + fallingSpeed = fall <= KNIFE_HOP_MIN_BOUNCE ? 0 : fall * KNIFE_HOP_BOUNCE; + hydrobounce_land(); + } + } + posOffset.y = height + basePosOffsetY; + } + + if (bestT <= KNIFE_PATH_PROGRESS_FOUND) + Remove(); + else + { + const BezierPoint& start = homingLaser.bezier[bestSegment]; + const BezierPoint& end = homingLaser.bezier[bestSegment + 1]; + Vector at = knife_path_point(start, end, bestT); + Vector next = knife_path_point(start, end, bestT + pathFollowSpeed); + Vector along = vector_normalized(vector_sub(next, at)); + Vector goal = vector_make(along.y * pathOffset + next.x, -along.x * pathOffset + next.y); + AddVelocity_divided(vector_resized(vector_sub(goal, pos), KNIFE_PATH_STEER), false); + sprite.rotation = angle_wrap(std::atan2(fallingSpeed + velocity.y, velocity.x) * RADIANS_TO_DEGREES - + KNIFE_TURN_QUARTER); + sprite.GetLayer(0)->isFlipX = sprite.rotation > 0; + pathSegment = bestSegment; + pathProgress = bestT; + } + + Vector inside = g_game->room->GetClampedPositionImpl(pos, KNIFE_PATH_MARGIN, KNIFE_PATH_MARGIN, KNIFE_PATH_MARGIN, + KNIFE_PATH_MARGIN); + if (vector_length_squared(vector_sub(pos, inside)) > 1) + { + if (!tearFlags[TEAR_CONTINUUM]) + Remove(); + else + { + pos = room_screen_wrap(pos, KNIFE_PATH_MARGIN); + tearFlags.reset(TEAR_CONTINUUM); + tearFlags.reset(TEAR_ORBIT); + Entity* source = parent->parent; + float offset = random_unit() * KNIFE_PATH_OFFSET_RANGE - KNIFE_PATH_OFFSET_RANGE / 2; + InitHomingPath(vector_normalized(velocity), source, offset); + } + } + if (g_game->frameCount - spawnFrame > KNIFE_PATH_LIFETIME) Remove(); +} + +// A knife chained to its parent: dragged along within the chain's length, pointing away from it. +void Entity_Knife::chained_update() +{ + Vector toParent = vector_sub(parent->pos, pos); + if (vector_length_squared(toParent) > KNIFE_CHAIN_LENGTH * KNIFE_CHAIN_LENGTH) + pos = vector_sub(parent->pos, vector_resized(toParent, KNIFE_CHAIN_LENGTH)); + sprite.rotation = angle_wrap(vector_angle(toParent) + KNIFE_TURN_QUARTER); + sprite.GetLayer(0)->isFlipX = sprite.rotation > 0; +} + +// A swung weapon held as an item: it swings, then lunges along its turn once its wait is over (Anti-Gravity holds it +// a few frames), or is pulled to its place by its parent (or linked knife). It goes once the swing ends, handing its +// hit list to the knife it is linked to. +void Entity_Knife::held_item_update() +{ + if (isSwinging) + { + UpdateSwingHits(); + if (!parent) + { + Remove(); + return; + } + } + + Vector anchor = parent->pos; + bool isWaiting = tearFlags[TEAR_WAIT]; + if ((isWaiting && g_game->frameCount - spawnFrame > KNIFE_ITEM_WAIT_FRAMES) || vector_is_zero(targetPosition)) + { + if (isWaiting) + velocity = sprite.GetFrame() < KNIFE_ITEM_LUNGE_FRAME + ? Vector{} + : vector_scale(vector_from_angle(displayRotation), KNIFE_ITEM_LUNGE_SPEED); + } + else + { + Vector place = vector_scale(vector_from_angle(rotation), targetPosition.x); + if (!linkedKnife) + velocity = vector_scale(vector_sub(vector_add(anchor, place), pos), 1 / friction); + else + velocity = vector_sub(vector_add(place, linkedKnife->pos), pos); + displayRotation = rotation; + sprite.rotation = rotation - KNIFE_TURN_QUARTER; + if (const AnimationFrame* frame = sprite.animState.GetLayerFrame(0)) + { + Vector facing = vector_from_angle(sprite.rotation); + knifeDepthOffset = facing.x * frame->pos.y + facing.y * frame->pos.x; + } + } + + if (isSwinging) return; + Remove(); + if (linkedKnife) static_cast(linkedKnife.get())->hitList = hitList; +} + +// The grid under a thrown knife: one time in four, Acid or Terra flags break a rock outright (filling the pit beyond +// it with a bridge); otherwise the cell takes a hit. +void Entity_Knife::grid_hit_update(Entity_Player* player) +{ + Room& room = *g_game->room; + int gridIndex = room.GetGridIndex(pos); + if (gridIndex < 0) return; + + GridEntity* grid = gridIndex < ROOM_GRID_CELLS ? room.gridEntities[gridIndex] : nullptr; + if (grid && grid->collisionClass != COLLISION_PIT && grid->collisionClass != COLLISION_NONE && (Random() & 3) == 0) + { + TearFlags flags = tearFlags; + if (player) flags |= player->GetTearHitParams(WEAPON_KNIFE, 1, 0, spawnerEntity).tearFlags; + if ((flags[TEAR_ACID] || flags[TEAR_ROCK_FLAG]) && grid->CanTakeDamageFromTearEffects() && + grid->Destroy(false, EntityRef(this))) + { + Vector beyond = vector_cardinal(vector_from_angle(sprite.rotation + KNIFE_BRIDGE_TURN)); + if (vector_is_zero(beyond)) return; + int pitIndex = room.GetGridIndex(vector_add(grid->Position(), vector_scale(beyond, GRID_STEP))); + if (pitIndex >= 0) room_bridge_make(pitIndex < ROOM_GRID_CELLS ? room.gridEntities[pitIndex] : nullptr, grid); + return; + } + } + if (gridIndex < ROOM_GRID_CELLS && room.gridEntities[gridIndex]) room.gridEntities[gridIndex]->Hurt(1, EntityRef(this)); +} + +// 00967db0 Between frames: a held or thrown knife (not Ludovico's) runs a whole interpolated update, a path follower or +// swung item drifts half its velocity, and a chained knife keeps to its chain. +void Entity_Knife::Interpolate() +{ + switch (subtype) + { + case KNIFE_SUBTYPE_HELD: + isInterpolating = true; + Update(); + if (!tearFlags[TEAR_LUDOVICO]) + { + preInterpolatePos = pos; + return; + } + break; + case KNIFE_SUBTYPE_PATH: + case KNIFE_SUBTYPE_HELD_ITEM: + isInterpolating = true; + break; + case KNIFE_SUBTYPE_CHAINED: + if (parent) chained_update(); + return; + default: + return; + } + preInterpolatePos = pos; + pos = vector_add(pos, vector_scale(velocity, friction * 0.5f)); +} + +// The two fading ghosts an orbiting thrown knife leaves behind it on its loop. +void Entity_Knife::render_orbit_trail(const Vector& offset) +{ + ColorMod saved = sprite.color; + float savedRotation = sprite.rotation; + float reach = GetBaseVariant() == KNIFE_BONE_CLUB ? KNIFE_SWUNG_HOLD_DISTANCE : KNIFE_HOLD_DISTANCE; + Entity* owner = GetRootParent()->parent; + + if (owner) + for (int i = ORBIT_TRAIL_COUNT - 1; i >= 0; i--) + { + float skew = angle_wrap(rotationOffset); + float distance = knifeDistance - (float)(i + 1) * knifeVelocity * ORBIT_TRAIL_SPACING; + float turn = distance * PI_F * 2 * (skew * KNIFE_ORBIT_TURN_SKEW + 1) + displayRotation; + float radius = (1 - skew * KNIFE_ORBIT_RADIUS_SKEW) * distance * KNIFE_ORBIT_RADIUS_SHARE + reach; + Vector ghost = vector_add(anchorPosition, vector_scale(vector_from_angle(turn), radius)); + + sprite.color = saved; + sprite.color._tint[3] = (ORBIT_TRAIL_ALPHA - (float)i * ORBIT_TRAIL_FADE) * saved._tint[3]; + sprite.rotation = vector_angle(vector_sub(ghost, owner->pos)); + Vector at = vector_add(render_position_get(vector_add(ghost, posOffset), RENDER_SNAPPED), offset); + sprite.Render({at, {}, {}}); + } + sprite.color = saved; + sprite.rotation = savedRotation; +} + +// 00965d30 Draws a visible knife (none of a player's during a floor change): an orbiting thrown knife's trail first, +// then the knife, then Dead Eye's mark over a club while its player holds charges. +void Entity_Knife::Render(const Vector& offset) +{ + if (!isVisible) return; + Entity_Player* player = GetPlayer(); + if (player && g_game->stageTransition.state != STAGE_TRANSITION_NONE) return; + + if (tearFlags[TEAR_ORBIT] && isFlying && subtype == KNIFE_SUBTYPE_HELD) render_orbit_trail(offset); + renderPosition = vector_add(render_position_get(vector_add(pos, posOffset), RENDER_SNAPPED), offset); + sprite.Render({renderPosition, {}, {}}); + + if (GetBaseVariant() == KNIFE_BONE_CLUB && subtype != KNIFE_SUBTYPE_HELD_ITEM && player && player->deadEyeCharges > 0) + { + const AnimationFrame* frame = sprite.animState.GetLayerFrame(0); + ColorMod mark = COLOR_DEFAULT; + mark._tint[3] = (float)std::min((int)player->deadEyeCharges, DEAD_EYE_LEVELS) / DEAD_EYE_LEVELS; + deadEyeSprite.color = mark; + Vector at = renderPosition; + if (!isFlying && frame) + { + Vector facing = vector_from_angle(sprite.rotation); + deadEyeSprite.rotation = vector_angle(frame->pos) + sprite.rotation; + deadEyeSprite.scale = vector_make(sprite.scale.x * DEAD_EYE_HELD_SCALE_X, sprite.scale.y * DEAD_EYE_HELD_SCALE_Y); + at.x += (frame->pos.x * facing.x - frame->pos.y * facing.y) * sprite.scale.x * DEAD_EYE_HELD_OFFSET; + at.y += (frame->pos.y * facing.x + frame->pos.x * facing.y) * sprite.scale.y * DEAD_EYE_HELD_OFFSET; + } + else + { + deadEyeSprite.rotation = 0; + deadEyeSprite.scale = sprite.scale; + } + deadEyeSprite.Render({at, {}, {}}); + } + lua_engine_get().PostKnifeRender(this, offset); +} + +// 009666f0 A knife touching something: the mods decide first. A sword, a held club or a hidden knife passes through; a +// thrown knife pushes bombs along; a vulnerable enemy (or fire, poop or TNT) not hit yet takes the knife's hit (a club's +// scaled by its swing, Mom's Knife's by its charge and speed, with the player's tear effects one throw in six, or two +// held) and its effects. A Lost Contact knife may destroy an enemy shot. +bool Entity_Knife::HandleCollision(Entity* collider, bool isLow) +{ + constexpr float BOMB_PUSH = 0.6f; + constexpr float BOMB_DRAG = 0.8f; + constexpr float CLUB_SWING_SHARE = 3; + constexpr float SCYTHE_DAMAGE_BASE = 0.4f; + constexpr float CLUB_DAMAGE_SCALE = 1.5f; + constexpr float CLUB_DAMAGE_MIN_BONUS = 1.75f; + constexpr float KNIFE_DAMAGE_BASE = 2; + constexpr float KNIFE_DAMAGE_GROWTH = 4; + constexpr float GROW_DISTANCE = 1800; + constexpr float GROW_BONUS = 4; + constexpr float SHRINK_DISTANCE = 200; + constexpr float SHRINK_MIN = 0.1f; + constexpr int LUDOVICO_HIT_INTERVAL = 5; + constexpr uint32_t SHOT_BREAK_ODDS = 5; + constexpr uint32_t SHOT_BREAK_LUDOVICO_ODDS = 20; + + LuaResult result = lua_engine_get().PreKnifeCollision(this, collider, isLow); + if (result != LUA_RESULT_NIL) return result == LUA_RESULT_TRUE; + + int baseVariant = GetBaseVariant(); + if (baseVariant == KNIFE_SPIRIT_SWORD || (baseVariant == KNIFE_BONE_CLUB && !isFlying) || !isVisible) return true; + if (collider->IsEnemy() && collider->HasEntityFlags(FLAG_FRIENDLY)) return true; + + if (collider->type == ENTITY_BOMB && isFlying && knifeVelocity > 0 && collider->friction != 0) + { + Vector push = vector_sub(vector_scale(vector_from_angle(flightAngle), knifeVelocity * BOMB_PUSH), + vector_scale(collider->velocity, BOMB_DRAG)); + collider->velocity = vector_add(collider->velocity, + vector_scale(push, collider->speedMultiplier / collider->friction)); + } + + bool isBreakable = collider->type == ENTITY_FIREPLACE || collider->type == ENTITY_MOVABLE_TNT || + collider->type == ENTITY_POOP; + if ((collider->IsVulnerableEnemy(nullptr) && !IsDescendantOf(collider)) || isBreakable) + { + std::vector& hits = GetHitEntities(); + if (EntityList::HitListContains(hits, *collider)) return true; + if (tearFlags[TEAR_LUDOVICO] && !IsFrame(LUDOVICO_HIT_INTERVAL, (int)index)) return true; + if (subtype == KNIFE_SUBTYPE_CHAINED && collider->type == ENTITY_MOVABLE_TNT) return true; + if (baseVariant != KNIFE_BONE_CLUB || !isBreakable) + { + uint32_t hitIndex = collider->GetHitListIndex(); + auto at = std::lower_bound(hits.begin(), hits.end(), hitIndex); + if (at == hits.end() || *at != hitIndex) hits.insert(at, hitIndex); + } + + Entity_Player* player = GetPlayer(); + TearFlags flags = tearFlags; + float damage = collisionDamage; + float swing = std::clamp(charge * knifeVelocity / CLUB_SWING_SHARE, 0.0f, 1.0f); + if (baseVariant == KNIFE_BONE_CLUB) + { + if (variant == KNIFE_BONE_SCYTHE) + damage = (swing * SCYTHE_DAMAGE_BASE + SCYTHE_DAMAGE_BASE) * damage; + else + damage = std::max(damage * CLUB_DAMAGE_SCALE, damage + CLUB_DAMAGE_MIN_BONUS); + if (Entity* spawner = spawnerEntity) + { + float distance = vector_length(vector_sub(pos, spawner->pos)); + if (tearFlags[TEAR_GROW]) damage *= std::min(distance, GROW_DISTANCE) * GROW_BONUS / GROW_DISTANCE + 1; + if (tearFlags[TEAR_SHRINK]) + damage *= std::max(1 - std::min(distance, SHRINK_DISTANCE) / SHRINK_DISTANCE, SHRINK_MIN); + } + } + else + { + if (player) + { + int displacement = (Random() & 1) * 2 - 1; + TearParams params = player->GetTearHitParams(WEAPON_KNIFE, 1, displacement, spawnerEntity); + damage = params.tearDamage; + if (random_below(isFlying ? 2 : 6) == 0) flags = params.tearFlags; + } + damage = (swing * KNIFE_DAMAGE_GROWTH + KNIFE_DAMAGE_BASE) * damage; + } + + uint64_t damageFlags = tear_damage_flags_get(flags, this); + collider->TakeDamage(damage, damageFlags, EntityRef(this), KNIFE_HIT_COUNTDOWN); + if (collider->type == ENTITY_FIREPLACE) return true; + + Entity_Tear::ApplyTearFlagEffects(collider, pos, flags, this, damage); + apply_hit_effects({.position = pos, + .targetPosition = collider->pos, + .target = collider, + .damage = damage, + .targetSize = collider->size, + .isFlying = isFlying}); + return true; + } + + if (collider->type != ENTITY_PROJECTILE || !tearFlags[TEAR_SHIELDED]) return true; + if (static_cast(collider)->projectileFlags & PROJECTILE_CANT_HIT_PLAYER) return true; + bool isBroken = Random() % SHOT_BREAK_ODDS == 0 && !tearFlags[TEAR_LUDOVICO]; + if (!isBroken && Random() % SHOT_BREAK_LUDOVICO_ODDS != 0) return true; + static_cast(collider)->projectileFlags = 0; + collider->isDead = true; + return true; } diff --git a/src/entity_knife.h b/src/entity_knife.h index c660140..38b33c6 100644 --- a/src/entity_knife.h +++ b/src/entity_knife.h @@ -4,13 +4,51 @@ #include "homing_laser.h" #include -// The distances a knife has no use for yet: removed or shown once it flies past them. +// The distances a knife has no use for yet: where it splits off its parent and where it shows up. constexpr float KNIFE_DISTANCE_NONE = -1; +// The knives (Lua's KnifeVariant): Mom's Knife, the Forgotten's swung weapons, Bloody Babylon's and the swords. +enum KnifeVariant : int +{ + KNIFE_MOMS_KNIFE, + KNIFE_BONE_CLUB, + KNIFE_BONE_SCYTHE, + KNIFE_DONKEY_JAWBONE, + KNIFE_BAG_OF_CRAFTING, + KNIFE_SUMPTORIUM, + KNIFE_BERSERK_CLUB = 8, + KNIFE_NOTCHED_AXE = 9, + KNIFE_SPIRIT_SWORD = 10, + KNIFE_TECH_SWORD = 11 +}; + +// What a knife is by subtype: held or thrown, following a homing path, chained to its parent, or swung as an item. +enum KnifeSubType : int +{ + KNIFE_SUBTYPE_HELD, + KNIFE_SUBTYPE_PATH, + KNIFE_SUBTYPE_CHAINED = 3, + KNIFE_SUBTYPE_HELD_ITEM = 4 +}; + +// Where apply_hit_effects lands its effects: the knife's point, the target and its size, the damage and its flags, and +// whether the knife hit while thrown. +struct KnifeHit +{ + Vector position{}; + Vector targetPosition{}; + Entity* target = nullptr; + uint64_t damageFlags = 0; + float damage = 0; + float targetSize = 0; + bool isFlying = false; +}; + // Construction and destruction (00960b50, 00960a70) are the defaults. // Field accessors (004d7790, 004d77a0, 0060cf10, 0060cfb0, 0085de90, 0085deb0, 0085dec0) are the public fields. // A knife (Lua's EntityKnife): Mom's Knife and the swung weapons (bones, clubs, swords), with the tear effects they -// carry, their charge and flight, and the path a homing knife follows. +// carry, their charge and flight, and the path a homing knife follows. A knife split off its parent (Cricket's Body, +// Angelic Prism) follows it out to splitDistance, then turns off by splitAngle and splitOffset. struct Entity_Knife : Entity { HomingLaser homingLaser; @@ -23,10 +61,12 @@ struct Entity_Knife : Entity EntityPtr techLaser; Vector anchorPosition{}; Vector initPosition{}; + Vector splitOffset{}; float basePosOffsetY = 0; float charge = 0; float displayRotation = 0; float fallingSpeed = 0; + float flightAngle = 0; float height = 0; float knifeDepthOffset = 0; float knifeDistance = 0; @@ -36,18 +76,24 @@ struct Entity_Knife : Entity float pathOffset = 0; float pathProgress = 0; float rotation = 0; - float removeDistance = KNIFE_DISTANCE_NONE; float rotationOffset = 0; float scale = 0; float showDistance = KNIFE_DISTANCE_NONE; + float splitAngle = 0; + float splitDistance = KNIFE_DISTANCE_NONE; int pathSegment = 0; short spinsLeft = 0; + short swingEffects = 0; + short swingTick = 0; + bool isAttacking = false; bool isDeadEyeHit = false; bool isFlying = false; bool isMultidimensionalApplied = false; bool isPrimaryClub = false; bool isPrismApplied = false; + bool isRecoiled = false; bool isSpinAttack = false; + bool isSwingCharged = false; bool isSwinging = false; bool isUsingParentHitList = false; @@ -61,19 +107,42 @@ struct Entity_Knife : Entity int GetBaseVariant(); std::vector& GetHitEntities(); - void InitHomingPath(Vector direction, Entity* source, float pathOffset); - void copy_parent_state(Entity_Knife* source); - uint32_t spawn_child_knife(); + void InitHomingPath(Vector direction, Entity* source, float offset); + void copy_parent_state(Entity_Knife& source); + bool spawn_child_knife(); Entity_Player* GetPlayer(); - Entity* GetRootParent(); + Entity_Knife* GetRootParent(); void Shoot(float charge, float range); void UpdateHomingPath(); - void update_target(float* outAngle); - void apply_wiggle(float*); + void update_target(float& angle); + void apply_wiggle(float& angle); void screen_wrap(); void Reset(); void SetAttackAnimation(); void SpinAttack(short remainingSpins, int startFrame); - uint8_t drain_notched_axe(int charge); + bool drain_notched_axe(int charge); void UpdateSwingHits(); + void apply_hit_effects(const KnifeHit& hit); + +private: + bool held_update(Entity_Player* player); + void ludovico_update(); + void path_update(); + void chained_update(); + void held_item_update(); + void hydrobounce_land(); + void hydrobounce_update(); + void lasers_update(Entity_Player* player); + void grid_hit_update(Entity_Player* player); + void sword_beam_fire(Entity_Player* player); + void brimstone_knife_spawn(Entity_Player* player); + void render_orbit_trail(const Vector& offset); }; + +bool is_swung_knife_variant(int variant); +float bezier_closest_point(const Vector& point, const BezierPoint& start, const BezierPoint& end, float& outT); +Vector room_screen_wrap(const Vector& position, float margin); +void tear_flags_area_apply(const Vector& position, Entity* source, float radius, float damage, + const TearFlags& flags); + +extern Entity_Player* g_notchedAxePlayer; diff --git a/src/entity_knife_hits.cpp b/src/entity_knife_hits.cpp new file mode 100644 index 0000000..8b5e462 --- /dev/null +++ b/src/entity_knife_hits.cpp @@ -0,0 +1,1078 @@ +#include "boss_ai.h" +#include "capsule.h" +#include "entity_bomb.h" +#include "entity_effect_combat.h" +#include "entity_familiar.h" +#include "entity_knife.h" +#include "entity_laser.h" +#include "entity_pickup.h" +#include "entity_player.h" +#include "entity_projectile.h" +#include "entity_tear.h" +#include "log.h" +#include "manager.h" +#include "room_grid.h" +#include "sfx_manager.h" +#include "weapon.h" +#include +#include + +// The player swinging a Notched Axe this frame, whose rocks and poop roll the axe's rewards (DAT_00c7ac6c). +Entity_Player* g_notchedAxePlayer = nullptr; + +// Local until entity_combat.cpp and entity_player_weapons.cpp drop their copies for the shared PlayerItemId enum. +// Local until room_update.cpp drops its copy for the shared EffectVariant enum. + +// A club's reach and knockback: the scythe's longer tip, the bag's harder push, the recoil on the swinger. +constexpr float CLUB_TIP_DISTANCE = 28; +constexpr float CLUB_TIP_RADIUS = 30; +constexpr float CLUB_KNOCKBACK = 18; +constexpr float SCYTHE_TIP_DISTANCE = 40; +constexpr float SCYTHE_TIP_RADIUS = 45; +constexpr float SCYTHE_KNOCKBACK = 9; +constexpr float BAG_KNOCKBACK = 36; +constexpr float KNOCKBACK_SHARE = 3; +constexpr float RECOIL = 4; +constexpr float SWING_KNOCKBACK_MASS = 50; + +// A swing's damage by weapon, and the sword's own (a spin's, and the touch of an idle sword's wider hit box). +constexpr float CLUB_DAMAGE = 3; +constexpr float SCYTHE_DAMAGE = 1.5f; +constexpr float JAWBONE_VERSUS_DAMAGE = 1.5f; +constexpr float SWORD_DAMAGE = 3; +constexpr float SWORD_DAMAGE_BONUS = 3.5f; +constexpr float SWORD_SPIN_DAMAGE = 8; +constexpr float SWORD_SPIN_DAMAGE_BONUS = 10; +constexpr float SWORD_SPIN_REACH = 1.8f; +constexpr float SWORD_IDLE_REACH = 0.8f; + +// The frames of a swing that hit, and the frame Anti-Gravity holds a swing on while it waits. +constexpr int SWING_FIRST_HIT_FRAME = 2; +constexpr int SWING_HIT_FRAMES = 6; +constexpr int SWING_WAIT_FRAME = 4; +constexpr int SWING_WAIT_LIMIT = 29; +constexpr int SWING_SHOT_FRAMES = 5; + +// What else a swing hits: fire it puts out, Mother's balls, projectiles and pickups it bats, and the cube baby. +constexpr float FIREPLACE_SWING_DAMAGE = 1000; +constexpr int FIREPLACE_HARD_VARIANT = 11; +constexpr int MOTHER_BALL_VARIANT = 100; +constexpr float PROJECTILE_BAT_HEIGHT = -50; +constexpr float CUBE_BABY_DRAG = 0.25f; +constexpr float LUDOVICO_TEAR_BAT = 1.25f; +constexpr int SWING_HIT_SOUND = 77; +constexpr float SWING_HIT_PITCH = 1.5f; +constexpr int SWING_HIT_SOUND_DELAY = 10; +constexpr int SWING_COUNTDOWN = 30; +constexpr int JAWBONE_DAMAGE_COOLDOWN = 15; +constexpr int AXE_BURN_FRAMES = 90; +constexpr int GUPPY_FORM_COUNT = 3; +constexpr int SWING_BLUE_FLY_MAX = 29; +constexpr uint32_t MULLIGAN_ODDS = 6; +constexpr uint32_t MULLIGAN_VERSUS_ODDS = 4; + +// The extra swings of a multi-shot club: their spacing, spread and sound, and the reach the player's range adds. +constexpr float SWING_REACH_BASE = 4; +constexpr float SWING_REACH_RANGE = 260; +constexpr float SWING_REACH_RANGE_SHARE = 0.15f; +constexpr float JAWBONE_REACH = 20; +constexpr float SWING_SPACING = 5; +constexpr float SWING_SPREAD = 30; +constexpr int SWING_SOUND = 252; +constexpr float SWING_SOUND_PITCH = 0.9f; +constexpr float SWING_SOUND_PITCH_SPREAD = 0.2f; +constexpr float SWING_LASER_REACH = 60; +constexpr int SWING_LASER_TIMEOUT = 3; +constexpr float SWING_LASER_DEPTH = 3000; +constexpr int EVIL_EYE_LUCK = 15; +constexpr int EVIL_EYE_MIN_ODDS = 5; +constexpr float EVIL_EYE_SPEED = 3; +constexpr int EVIL_EYE_SUBTYPE = 10; + +// SetAttackAnimation and SpinAttack: the swing starts close to the holder, and the spin's sound. +constexpr float SWING_START_DISTANCE = 5; +constexpr float SPIN_PITCH_BASE = 0.9f; +constexpr float SPIN_PITCH_SPREAD = 0.2f; +constexpr float SPIN_PITCH_MIN = 0.5f; + +// Notched Axe's draining charge and the dust it throws when it breaks. +constexpr int AXE_PARTICLES = 2; +constexpr int AXE_ROCK_PARTICLE = 27; +constexpr int AXE_DUST_PARTICLE = 86; +constexpr float AXE_PARTICLE_SPEED = 3; +constexpr float AXE_PARTICLE_SPREAD = 4; +constexpr float AXE_DUST_SPEED = 2; +constexpr float AXE_DUST_SPREAD = 3; + +// apply_hit_effects: the shards' speed and lift, Ipecac's blast, Haemolacria's burst and Rift. +constexpr float KNIFE_SHARD_SPEED = 10; +constexpr float SHARD_HEIGHT_DEFAULT = -15; +constexpr float SHARD_BACKSTEP = 8; +constexpr float SHARD_QUAD_HEIGHT = 0.65f; +constexpr float SHARD_QUAD_FALL = 0.3f; +constexpr float SHARD_FALL_SPREAD = 0.2f; +constexpr float SHARD_SPLIT_HEIGHT = 1.5f; +constexpr float SHARD_DAMAGE = 0.5f; +constexpr float SHARD_SCALE_MIN = 0.01f; +constexpr const char* BROKEN_BONE_SHEET = "gfx/tears_brokenbone.png"; +constexpr float CLUB_BLAST_RADIUS = 60; +constexpr float CLUB_BLAST_DAMAGE = 0.5f; +constexpr float KNIFE_BLAST_STEP = 8; +constexpr float KNIFE_BLAST_DAMAGE_BASE = 10; +constexpr float KNIFE_BLAST_SCALE_MIN = 2; +constexpr float KNIFE_BLAST_SCALE_MAX = 6; +constexpr float KNIFE_BLAST_SCALE_CHARGE = 4; +constexpr float KNIFE_BLAST_REFERENCE_DAMAGE = 31; +constexpr float KNIFE_BLAST_RADIUS_MAX = 70; +constexpr int BLAST_BLUE_FLY_ODDS = 6; +constexpr int BLAST_BLUE_FLY_MAX = 30; +constexpr float POISON_CLOUD_DEPTH = -5; +constexpr float POISON_CLOUD_FLATTEN = 0.4f; +constexpr int POISON_CLOUD_SUBTYPE = 4; +constexpr ColorMod POISON_SPLAT_COLOR = {{0.02f, 0.9f, 0.02f, 1}, {0, 0, 0, 0}, {0, 0.33333334f, 0}}; +constexpr ColorMod POISON_CLOUD_COLOR = {{0.02f, 0.9f, 0.02f, 1}, {0, 0, 0, 0}, {0.039215688f, 0.3921569f, 0}}; +constexpr int BURST_MIN = 6; +constexpr uint32_t BURST_SPREAD = 6; +constexpr float BURST_SCALE = 1.5f; +constexpr float BURST_DAMAGE_SPREAD = 0.5f; +constexpr float BURST_DAMAGE_MIN = 0.75f; +constexpr float BURST_FALL_ACCEL = 1.3f; +constexpr float HAEMO_FALL_SPREAD = 0.75f; +constexpr float BURST_FALL_MIN = 0.5f; +constexpr float BURST_TRAIL_SPEED = 1.1f; +constexpr float BURST_TRAIL_PLAYBACK = 0.6f; +constexpr float BURST_TRAIL_PLAYBACK_MIN = 0.5f; +constexpr float BURST_TRAIL_SCALE = 0.6f; +constexpr int BURST_TRAIL_DEPTH = -400; +constexpr float KNIFE_SPLIT_SCALE = 0.8f; +constexpr float SPLIT_ANGLE = 90; +constexpr float RIFT_MARGIN = -10; +constexpr int RIFT_FRAMES = 60; +constexpr int RIFT_VERSUS_FRAMES = 30; +constexpr float SHARD_CRAWLSPACE_OFFSET_Y = -18; +constexpr float RANDOM_HALF_TURN_KNIFE = 3.14f; + +// The tear effects a shard or stuck tear does not inherit. +constexpr std::array QUAD_SHARD_DROPPED = {TEAR_EXPLOSIVE, TEAR_QUADSPLIT, TEAR_SPLIT, TEAR_LUDOVICO, TEAR_BONE_FLAG, + TEAR_ABSORB, TEAR_WAIT, TEAR_HYDROBOUNCE, TEAR_FETUS_FLAG}; +constexpr std::array BURST_SHARD_DROPPED = {TEAR_ABSORB, TEAR_LUDOVICO, TEAR_WAIT, TEAR_BURSTSPLIT, TEAR_EXPLOSIVE, + TEAR_FETUS_FLAG}; +constexpr std::array SPLIT_SHARD_DROPPED = {TEAR_ABSORB, TEAR_LUDOVICO, TEAR_WAIT, TEAR_EXPLOSIVE, TEAR_FETUS_FLAG}; +constexpr std::array BONE_SHARD_DROPPED = {TEAR_ABSORB, TEAR_BONE_FLAG, TEAR_WAIT, TEAR_EXPLOSIVE, TEAR_FETUS_FLAG}; +constexpr std::array STUCK_TEAR_DROPPED = {TEAR_QUADSPLIT, TEAR_SPLIT, TEAR_LUDOVICO, TEAR_BONE_FLAG, TEAR_ABSORB, + TEAR_HYDROBOUNCE, TEAR_FETUS_FLAG}; + +// Tear flags without some bits. +template static TearFlags flags_without(TearFlags flags, const std::array& dropped) +{ + for (int bit : dropped) flags.reset(bit); + return flags; +} + +// Plays a sound through the fart seeds. +static void swing_sound_play(int sound, SoundPlay play) +{ + seed_fart_sound_override(&sound); + g_manager->sfxManager.Play(sound, play); +} + +// Sorted insertion into a hit list, as the entities keep them. +static void swing_hit_add(std::vector& hitList, Entity& entity) +{ + uint32_t index = entity.GetHitListIndex(); + auto at = std::lower_bound(hitList.begin(), hitList.end(), index); + if (at == hitList.end() || *at != index) hitList.insert(at, index); +} + +// Pushes an entity away from a point by a strength, against its friction. +static void swing_push(Entity& entity, const Vector& from, float strength) +{ + Vector away = vector_normalized(vector_sub(entity.pos, from)); + if (entity.friction != 0) entity.velocity = vector_add(entity.velocity, vector_scale(away, strength / entity.friction)); +} + +// 00961ad0 Whether the knife is a Notched Axe its player empowers. +static bool is_axe_empowered(Entity_Knife& knife) +{ + if (knife.variant != KNIFE_NOTCHED_AXE) return false; + Entity_Player* player = knife.GetPlayer(); + return player && player->HasCollectible(COLLECTIBLE_BOOK_OF_BELIAL_PASSIVE); +} + +// A bone shard thrown from a hit: a broken bone tear at a speed, fired by a player, with the knife's look and the tear +// effects it keeps. +static Entity_Tear& bone_shard_spawn(Entity_Knife& knife, const Vector& position, const Vector& velocity, Entity* owner) +{ + Entity_Tear& shard = *static_cast(g_game->Spawn({.position = position, + .velocity = velocity, + .spawner = owner, + .type = ENTITY_TEAR, + .variant = TEAR_BONE, + .seed = Random()})); + shard.sprite.ReplaceSpritesheet(0, BROKEN_BONE_SHEET); + shard.sprite.LoadGraphics(); + shard.SetCollisionDamage(knife.collisionDamage * SHARD_DAMAGE); + return shard; +} + +// Sets a shard's size from the knife's and gives it the knife's color. +static void shard_finish(Entity_Knife& knife, Entity_Tear& shard, float scale, Entity* owner) +{ + shard.baseScale = std::max(scale, SHARD_SCALE_MIN); + shard.fScale = shard.baseScale; + shard.ResetSpriteScale(); + shard.SetColor(knife.sprite.color, -1, COLOR_PRIORITY_DEFAULT, false, true); + shard.parent = owner; + shard.Update(); +} + +// Ipecac's poison splat and cloud around a blast. +static void poison_cloud_spawn(const Vector& position, float scale, bool isCloud) +{ + Entity* splat = g_game->Spawn({.position = position, .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_SPLAT, .seed = Random()}); + float size = (random_unit() + 1) * scale; + splat->sprite.scale = vector_make(size, size); + splat->SetColor(POISON_SPLAT_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + splat->Update(); + if (!isCloud) return; + + Entity* cloud = g_game->Spawn({.position = position, + .subType = POISON_CLOUD_SUBTYPE, + .type = ENTITY_EFFECT, + .variant = EFFECT_BLOOD_EXPLOSION, + .seed = Random()}); + cloud->SetColor(POISON_CLOUD_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + cloud->sprite.scale = vector_make(scale, scale * POISON_CLOUD_FLATTEN); + cloud->renderDepthOffset = POISON_CLOUD_DEPTH; + cloud->Update(); +} + +// 009680d0 Starts a swing: a sword swings toward its facing, a club alternates Swing and Swing2. Held by a player or +// familiar, the weapon starts close by, pointing away. The swing hits anew. +void Entity_Knife::SetAttackAnimation() +{ + if (g_game->frameCount == spawnFrame) displayRotation = rotation; + + if (GetBaseVariant() == KNIFE_SPIRIT_SWORD) + { + Vector facing = vector_from_angle(displayRotation); + const char* name = std::abs(facing.x) <= std::abs(facing.y) ? (facing.y < 0 ? "AttackUp" : "AttackDown") + : (facing.x < 0 ? "AttackLeft" : "AttackRight"); + sprite.Play(name, PLAY_FORCED); + } + else + sprite.Play(sprite.GetAnimation() == "Swing" ? "Swing2" : "Swing", PLAY_FORCED); + + if (parent && (parent->is_player() || parent->IsFamiliar())) + { + pos = vector_add(parent->pos, vector_scale(vector_from_angle(displayRotation), SWING_START_DISTANCE)); + anchorPosition = parent->pos; + sprite.rotation = angle_wrap(vector_angle(vector_sub(pos, parent->pos)) - 90); + } + isDeadEyeHit = false; + isSwinging = true; + isAttacking = true; + isSpinAttack = false; + hitList.clear(); +} + +// 00968430 Spins a sword around its holder, from a frame on, with spins still to come: its spin sound (lower for a +// bigger sword), and the hits start at once. Other knives log the attempt and do nothing. +void Entity_Knife::SpinAttack(short remainingSpins, int startFrame) +{ + if (g_game->frameCount == spawnFrame) displayRotation = rotation; + if (GetBaseVariant() != KNIFE_SPIRIT_SWORD) + { + KAGE_LogMessage(LOG_INFO, (uint8_t*)"Tried to use spin attack on an unsupported knife variant! (%d)\n"); + return; + } + + Vector facing = vector_from_angle(displayRotation); + const char* name = std::abs(facing.x) <= std::abs(facing.y) ? (facing.y < 0 ? "SpinUp" : "SpinDown") + : (facing.x < 0 ? "SpinLeft" : "SpinRight"); + sprite.Play(name, PLAY_FORCED); + if (startFrame > 0 && sprite.animState.animData) sprite.animState.SetFrameFloat((float)startFrame); + + float pitch = std::max(1 / (sprite.scale.x * 0.5f + 0.5f), SPIN_PITCH_MIN); + pitch *= random_unit() * SPIN_PITCH_SPREAD + SPIN_PITCH_BASE; + swing_sound_play(SOUND_SWORD_SPIN, {.pitch = pitch}); + isDeadEyeHit = false; + isSwinging = true; + isAttacking = false; + isSpinAttack = true; + swingEffects = 1; + swingTick = 0; + spinsLeft = remainingSpins; + hitList.clear(); + UpdateSwingHits(); +} + +// 00968660 Notched Axe wears down by a charge on each hit while its linked swing shows (an empowered axe three hits in +// four free): once its charge runs out the axe breaks with a snap and dust, and the swing hides. True when it broke. +bool Entity_Knife::drain_notched_axe(int drain) +{ + Entity_Player* player = GetPlayer(); + Entity* swing = linkedKnife; + if (!player || !swing || swing->type != ENTITY_KNIFE || !swing->isVisible) return false; + if (is_axe_empowered(*this) && (Random() & 3) != 0) return false; + + int slot = player->GetActiveItemSlot(COLLECTIBLE_NOTCHED_AXE); + if (slot >= 0) + { + player->AddActiveCharge(-drain, slot, false, false, false); + if (player->GetActiveItem(slot) > 0) return false; + player->DischargeActiveItem(slot, false); + } + player->temporaryEffects.RemoveCollectibleEffect(COLLECTIBLE_NOTCHED_AXE, -1); + swing_sound_play(SOUND_BONE_SNAP, {}); + swing_sound_play(SOUND_POT_BREAK, {}); + game_particles_spawn({.position = player->pos, + .speed = random_unit() * AXE_PARTICLE_SPREAD + AXE_PARTICLE_SPEED, + .count = AXE_PARTICLES, + .variant = AXE_ROCK_PARTICLE}); + float dustSpeed = random_unit() * AXE_DUST_SPREAD + AXE_DUST_SPEED; + game_particles_spawn({.position = player->pos, + .speed = dustSpeed, + .count = (int)(Random() & 1) + AXE_PARTICLES, + .variant = AXE_DUST_PARTICLE}); + if (linkedKnife && linkedKnife->type == ENTITY_KNIFE) linkedKnife->isVisible = false; + return true; +} + +// The swing's hit box: a circle at the tip of a club (a scythe's wider), or a sword's two null capsules, longer for a +// spin and shorter for an idle sword's touch. +struct SwingReach +{ + Capsule tip; + Capsule extra; + Vector center{}; + Vector tipPosition{}; + float radius = 0; + float tipDistance = 0; + float tipRadius = 0; +}; + +// Builds the swing's hit box and the circle around it the grid and entity searches use. +static SwingReach swing_reach_get(Entity_Knife& knife, bool isIdleSword) +{ + SwingReach reach; + bool isScythe = knife.variant == KNIFE_BONE_SCYTHE; + float scaleY = knife.sprite.scale.y; + reach.tipDistance = isScythe ? SCYTHE_TIP_DISTANCE : CLUB_TIP_DISTANCE; + reach.tipRadius = isScythe ? SCYTHE_TIP_RADIUS : CLUB_TIP_RADIUS; + reach.tipPosition = vector_add(knife.pos, vector_scale(vector_from_angle(knife.displayRotation), reach.tipDistance * scaleY)); + reach.tip = Capsule(reach.tipPosition, vector_make(1, 1), 0, scaleY * reach.tipRadius); + + if (knife.GetBaseVariant() == KNIFE_SPIRIT_SWORD) + { + knife.GetNullCapsule(reach.tip, "Hit"); + knife.GetNullCapsule(reach.extra, "Hit2"); + if (knife.isSpinAttack || isIdleSword) + { + float stretch = isIdleSword ? SWORD_IDLE_REACH : SWORD_SPIN_REACH; + for (Capsule* capsule : {&reach.tip, &reach.extra}) + { + capsule->halfLength = (capsule->radius + capsule->halfLength) * stretch - capsule->radius; + capsule->start = vector_sub(capsule->center, vector_scale(capsule->direction, capsule->halfLength)); + capsule->end = vector_add(capsule->center, vector_scale(capsule->direction, capsule->halfLength)); + } + } + } + + reach.center = reach.tip.center; + reach.radius = reach.tip.radius + reach.tip.halfLength; + if (reach.extra.radius > 0) + { + Vector between = vector_sub(reach.extra.center, reach.tip.center); + float distance = vector_length(between); + reach.radius = (distance + reach.tip.radius + reach.tip.halfLength + reach.extra.radius + reach.extra.halfLength) / 2; + if (distance > 0) + reach.center = vector_add(reach.center, vector_scale(between, (reach.radius - reach.tip.radius - + reach.tip.halfLength) / distance)); + } + return reach; +} + +// Whether a capsule touches the swing's hit box. +static bool swing_touches(const SwingReach& reach, const Capsule& other) +{ + return Capsule::Collide(other, reach.tip) || (reach.extra.radius > 0 && Capsule::Collide(other, reach.extra)); +} + +// The grid a swing reaches: a Notched Axe breaks what it can (bridging the pit behind), the rest takes a hit. +// False when the axe broke and the swing stops. +static bool swing_grid_hit(Entity_Knife& knife, const SwingReach& reach, bool& isHit) +{ + constexpr float CELL = 40; + constexpr float CELL_RADIUS = 20; + + Room& room = *g_game->room; + int centerIndex = room.GetGridIndex(reach.center); + if (centerIndex < 0) return true; + + int span = (int)std::ceil(reach.radius / CELL); + int column = centerIndex % room.gridWidth; + int row = centerIndex / room.gridWidth; + for (int x = std::max(column - span, 0); x <= std::min(column + span, room.gridWidth); x++) + for (int y = std::max(row - span, 0); y <= std::min(row + span, room.gridHeight); y++) + { + if (x >= room.gridWidth || y >= room.gridHeight) continue; + GridEntity* grid = room.gridEntities[room.gridWidth * y + x]; + if (!grid) continue; + Capsule cell(room.GetGridPosition(grid->gridIndex), vector_make(1, 1), 0, CELL_RADIUS); + if (!swing_touches(reach, cell)) continue; + + if (knife.variant != KNIFE_NOTCHED_AXE) + { + if (grid->Hurt(1, EntityRef())) isHit = true; + continue; + } + if (grid->collisionClass <= COLLISION_NONE || !grid->Destroy(false, EntityRef(&knife))) continue; + + Vector beyond = vector_cardinal(vector_from_angle(knife.sprite.rotation + 90)); + Vector pit = vector_add(room.GetGridPosition(grid->gridIndex), vector_scale(beyond, CELL)); + int pitIndex = room.GetGridIndex(pit); + if (!vector_is_zero(beyond) && pitIndex >= 0) + room_bridge_make(pitIndex < ROOM_GRID_CELLS ? room.gridEntities[pitIndex] : nullptr, grid); + if (knife.drain_notched_axe(1)) + { + g_notchedAxePlayer = nullptr; + return false; + } + isHit = true; + } + return true; +} + +// What a swing hits this frame and how hard: its damage, tear effects, knockback and recoil, and who swings it. +struct SwingHit +{ + TearFlags tearFlags; + SwingReach reach; + Vector knockbackOrigin{}; + Entity* owner = nullptr; + Entity_Player* player = nullptr; + float damage = 0; + float knockback = 0; + float recoil = 0; + bool isHit = false; + bool isIdleSword = false; +}; + +// The damage flags a swing deals an enemy: Mulligan's (or the Guppy form's) blue flies, the axe's crush, Clones and +// the empowered axe's fire. +static uint64_t swing_damage_flags(Entity_Knife& knife, Entity& enemy, Entity_Player* player) +{ + uint64_t flags = 0; + if (enemy.IsVulnerableEnemy(nullptr) && player) + { + bool isGuppy = !player->hasCurseMistEffect && !player->isCoopGhost && player->playerForms[0] >= GUPPY_FORM_COUNT; + uint32_t odds = g_game->deathmatchManager.state < DEATHMATCH_INTRO ? MULLIGAN_ODDS : MULLIGAN_VERSUS_ODDS; + bool isFly = isGuppy || (player->HasCollectible(COLLECTIBLE_MULLIGAN) && Random() % odds == 0); + if (isFly && player->numBlueFlies <= SWING_BLUE_FLY_MAX) flags = DAMAGE_SPAWN_FLY; + } + if (knife.variant == KNIFE_NOTCHED_AXE) flags |= DAMAGE_CRUSH; + if (knife.HasEntityFlags(FLAG_BLEED_OUT)) flags |= DAMAGE_CLONES; + if (is_axe_empowered(knife)) flags |= DAMAGE_CHAMPION_REWARD; + return flags; +} + +// An enemy (or fire, poop, TNT) a swing reaches: hit once per swing, pushed away and hurt, with the swing's effects, +// and the swinger recoils from the first living one. False when the axe broke and the swing stops. +static bool swing_enemy_hit(Entity_Knife& knife, Entity& enemy, SwingHit& hit) +{ + std::vector& hits = knife.GetHitEntities(); + if (EntityList::HitListContains(hits, enemy)) return true; + if (enemy.type != ENTITY_POOP && enemy.type != ENTITY_MOVABLE_TNT) swing_hit_add(hits, enemy); + + if (enemy.type == ENTITY_FIREPLACE && enemy.variant != FIREPLACE_HARD_VARIANT) + { + enemy.TakeDamage(FIREPLACE_SWING_DAMAGE, 0, EntityRef(knife.parent), SWING_COUNTDOWN); + hit.isHit = true; + return true; + } + if (enemy.type == ENTITY_FROZEN_ENEMY) + { + if (hit.player) Entity::ForceCollide(hit.player, &enemy, true); + return true; + } + if (enemy.type == ENTITY_MOTHER && enemy.variant == MOTHER_BALL_VARIANT) + reconstruction_missing("Entity_Knife::UpdateSwingHits 009688d0 (batting Mother's ball)"); + if (enemy.type == ENTITY_SHOPKEEPER || enemy.isDead) return true; + + Vector away = vector_normalized(vector_sub(enemy.pos, hit.knockbackOrigin)); + bool isEmpowered = is_axe_empowered(knife); + if (!enemy.HasEntityFlags(FLAG_NO_KNOCKBACK)) + { + float strength = hit.knockback * SWING_KNOCKBACK_MASS / (enemy.mass + SWING_KNOCKBACK_MASS); + if (enemy.friction != 0) + enemy.velocity = vector_add(enemy.velocity, vector_scale(away, enemy.speedMultiplier * strength / enemy.friction)); + if (isEmpowered) reconstruction_missing("Entity_Knife::UpdateSwingHits 009688d0 (Entity::AddKnockback)"); + } + + uint64_t damageFlags = swing_damage_flags(knife, enemy, hit.player); + if (enemy.TakeDamage(hit.damage, damageFlags, EntityRef(knife.parent), SWING_COUNTDOWN)) + { + if (enemy.IsVulnerableEnemy(nullptr)) + { + swing_sound_play(SWING_HIT_SOUND, {.frameDelay = SWING_HIT_SOUND_DELAY, .pitch = SWING_HIT_PITCH}); + Entity_Tear::ApplyTearFlagEffects(&enemy, knife.pos, hit.tearFlags, &knife, hit.damage); + if (knife.variant == KNIFE_DONKEY_JAWBONE && hit.player) + { + if (hit.player->damageCooldown < 1) hit.player->AddEntityFlags(FLAG_NO_DAMAGE_BLINK); + hit.player->damageCooldown = std::max(hit.player->damageCooldown, JAWBONE_DAMAGE_COOLDOWN); + } + if (isEmpowered) enemy.AddBurn(EntityRef(hit.player), AXE_BURN_FRAMES, 0, false); + } + if (knife.variant == KNIFE_NOTCHED_AXE && knife.drain_notched_axe(2)) + { + g_notchedAxePlayer = nullptr; + return false; + } + knife.apply_hit_effects({.position = hit.reach.tipPosition, + .targetPosition = enemy.pos, + .target = &enemy, + .damageFlags = damageFlags, + .damage = hit.damage, + .targetSize = enemy.size}); + } + + if (enemy.pendingDamage < enemy.health && !knife.isRecoiled && !knife.isFlying && hit.owner) + { + Entity& owner = *hit.owner; + if (owner.friction != 0) owner.velocity = vector_add(owner.velocity, vector_scale(away, -hit.recoil / owner.friction)); + knife.isRecoiled = true; + if (hit.isIdleSword && owner.type != ENTITY_TEAR) knife.isAttacking = false; + } + hit.isHit = true; + return true; +} + +// Something else a swing reaches: bombs and the cube baby are batted away, enemy shots are reflected (the bag eats +// them), pickups are batted and picked up (chests opened), and the player's Ludovico tear is batted. +static void swing_other_hit(Entity_Knife& knife, Entity& entity, SwingHit& hit) +{ + std::vector& hits = knife.GetHitEntities(); + Entity_Player* player = hit.player; + switch (entity.type) + { + case ENTITY_BOMB: + { + Entity_Bomb& bomb = static_cast(entity); + if (bomb.parent == player && bomb.isFetus && bomb.posOffset.y < 0) return; + if (EntityList::HitListContains(hits, bomb)) return; + swing_hit_add(hits, bomb); + swing_push(bomb, hit.knockbackOrigin, hit.knockback); + return; + } + case ENTITY_FAMILIAR: + { + if (entity.variant != Entity_Familiar::CUBE_BABY || EntityList::HitListContains(hits, entity)) return; + swing_hit_add(hits, entity); + entity.velocity = vector_scale(entity.velocity, CUBE_BABY_DRAG); + swing_push(entity, hit.knockbackOrigin, hit.knockback); + swing_sound_play(SOUND_CUBE_BABY_KICK, {}); + return; + } + case ENTITY_PROJECTILE: + { + Entity_Projectile& shot = static_cast(entity); + if (!player || shot.isDead || shot.height <= PROJECTILE_BAT_HEIGHT) return; + Vector away = vector_normalized(vector_sub(shot.pos, hit.knockbackOrigin)); + if (knife.variant != KNIFE_BAG_OF_CRAFTING) + shot.Reflect(vector_scale(away, hit.knockback)); + else + { + shot.projectileFlags = 0; + shot.isDead = true; + } + return; + } + case ENTITY_TEAR: + { + if (!player) break; + Entity_Tear& tear = static_cast(entity); + if (tear.parent != player || !tear.tearFlags[TEAR_LUDOVICO] || EntityList::HitListContains(hits, tear)) return; + swing_hit_add(hits, tear); + tear.velocity = vector_scale(vector_normalized(vector_sub(tear.pos, knife.pos)), hit.knockback * LUDOVICO_TEAR_BAT); + return; + } + default: + break; + } + + if (entity.type != ENTITY_PICKUP) return; + Entity_Pickup& pickup = static_cast(entity); + bool isBag = knife.variant == KNIFE_BAG_OF_CRAFTING; + bool isBattable = pickup.variant != PICKUP_COLLECTIBLE && (pickup.price == 0 || isBag) && !pickup.isDead && + pickup.entityCollisionClass != ENTCOLL_NONE && !pickup.HasEntityFlags(FLAG_NO_KNOCKBACK) && + (!hit.owner || hit.owner->type != ENTITY_TEAR); + if (!isBattable || EntityList::HitListContains(hits, pickup)) return; + + swing_hit_add(hits, pickup); + swing_push(pickup, knife.pos, hit.knockback); + if (player && (pickup.CanBePickedUp(isBag) || Entity_Pickup::IsChest(pickup.variant))) + if (!isBag || !player->bag_of_crafting_collect(&pickup)) Entity::ForceCollide(player, &pickup, true); + if (Entity_Pickup::IsChest(pickup.variant)) + pickup.TakeDamage(hit.damage, knife.variant == KNIFE_NOTCHED_AXE ? DAMAGE_CRUSH : 0, EntityRef(knife.parent), + SWING_COUNTDOWN); +} + +// The extra swings of a club or sword swing, one every other frame while they last: each a held swing knife from the +// holder, spaced further out with the range and fanned at random, linked back to this one; Technology adds its laser +// along it and Evil Eye may throw an eye. False when the pool handed back this knife, which then goes. +static bool swing_effect_spawn(Entity_Knife& knife, Entity_Player* player, const SwingReach& reach) +{ + Entity* owner = knife.parent; + if (owner && owner->type == ENTITY_KNIFE) owner = owner->parent; + int baseVariant = knife.GetBaseVariant(); + bool isSecondSwing = (knife.swingTick / 2) & 1; + if (baseVariant == KNIFE_BONE_CLUB && knife.sprite.GetAnimation() == "Swing2") isSecondSwing = !isSecondSwing; + + float reachExtra = SWING_REACH_BASE; + float firstReach = SWING_REACH_BASE; + if (owner && owner->is_player()) + { + reachExtra = std::max((owner->ToPlayer()->tearRange - SWING_REACH_RANGE) * SWING_REACH_RANGE_SHARE, 0.0f) + + SWING_REACH_BASE; + firstReach = reachExtra; + } + if (knife.variant == KNIFE_DONKEY_JAWBONE) + { + reachExtra = std::max(JAWBONE_REACH, reachExtra); + firstReach = reachExtra; + } + + float scaleX = knife.sprite.scale.x; + Entity* spawned = g_game->Spawn({.position = owner ? owner->pos : knife.pos, + .spawner = knife.spawnerEntity, + .subType = KNIFE_SUBTYPE_HELD_ITEM, + .type = ENTITY_KNIFE, + .variant = knife.variant, + .seed = Random()}); + if (spawned == &knife) + { + knife.Remove(); + return false; + } + + Entity_Knife& swing = *static_cast(spawned); + swing.parent = owner; + swing.targetPosition.y = 0; + if (knife.swingTick == 0) + { + swing.targetPosition.x = firstReach; + swing.rotation = knife.rotation + knife.rotationOffset; + } + else + { + swing.targetPosition.x = scaleX * SWING_SPACING * (float)knife.swingTick + reachExtra; + swing.rotation = random_unit() * SWING_SPREAD - SWING_SPREAD / 2 + knife.rotation + knife.rotationOffset; + float pitch = random_unit() * SWING_SOUND_PITCH_SPREAD + SWING_SOUND_PITCH; + swing_sound_play(SWING_SOUND, {.frameDelay = 1, .pitch = pitch}); + } + swing.mass = knife.mass; + swing.posOffset = knife.posOffset; + swing.SetColor(knife.sprite.color, -1, COLOR_PRIORITY_DEFAULT, false, true); + swing.sprite.scale = knife.sprite.scale; + swing.tearFlags = knife.tearFlags; + swing.SetCollisionDamage(knife.collisionDamage); + swing.linkedKnife = &knife; + knife.spinEffect = &swing; + if (baseVariant == KNIFE_BONE_CLUB) + { + swing.sprite.Play(isSecondSwing ? "Swing" : "Swing2", PLAY_FORCED); + swing.SetAttackAnimation(); + } + else if (baseVariant == KNIFE_SPIRIT_SWORD) + { + if (knife.isFlying) swing.pos = knife.pos; + if (!knife.isSpinAttack) swing.SetAttackAnimation(); + else swing.SpinAttack(1, knife.sprite.GetFrame()); + swing.sprite.rotation = knife.sprite.rotation; + } + swing.Update(); + if (!player) return true; + + if (player->HasCollectible(COLLECTIBLE_TECHNOLOGY)) + { + float laserReach = (angle_wrap(knife.rotationOffset) * SWING_LASER_REACH / 180 + reach.tipRadius + reach.tipDistance) * + knife.sprite.scale.y; + Entity_Laser& laser = *static_cast(g_game->Spawn({.position = swing.pos, + .spawner = player, + .subType = LASER_SUBTYPE_RING_FOLLOW_PARENT, + .type = ENTITY_LASER, + .variant = LASER_THIN_RED, + .seed = Random()})); + laser.SetColor(player->laserColor, -1, COLOR_PRIORITY_DEFAULT, false, true); + laser.posOffset = knife.posOffset; + laser.parent = &swing; + laser.renderDepthOffset = SWING_LASER_DEPTH; + laser.tearFlags = knife.tearFlags; + laser.SetCollisionDamage(knife.collisionDamage); + laser.isOneHit = true; + laser.timeout = SWING_LASER_TIMEOUT; + laser.radius = laserReach; + laser.spawnerEntity = player; + laser.Update(); + } + + bool isTool = knife.variant == KNIFE_BAG_OF_CRAFTING || knife.variant == KNIFE_SUMPTORIUM || + knife.variant == KNIFE_NOTCHED_AXE || knife.variant == KNIFE_BERSERK_CLUB; + if (player == owner && !isTool && player->HasCollectible(COLLECTIBLE_EVIL_EYE) && + random_below(std::max(EVIL_EYE_LUCK - (int)player->luck, EVIL_EYE_MIN_ODDS)) == 0) + { + uint32_t seed = Random(); + Entity* eye = g_game->Spawn({.position = swing.pos, + .velocity = vector_scale(vector_from_angle(swing.rotation), EVIL_EYE_SPEED), + .spawner = knife.spawnerEntity, + .subType = EVIL_EYE_SUBTYPE, + .type = ENTITY_EFFECT, + .variant = EFFECT_EVIL_EYE, + .seed = seed}); + eye->parent = player; + } + return true; +} + +// 009688d0 One frame of a swing: on its hitting frames a held swing (or an idle sword's touch) breaks the grid it +// reaches and hits the enemies, shots, pickups and bombs in its hit box once each, Dead Eye counting a hit. A club or +// sword with extra swings throws one every other frame. The swing ends with its animation (or a sword's SwingEnd), +// and Dead Eye's charge is lost on a swing that hit nothing. +void Entity_Knife::UpdateSwingHits() +{ + if (isInterpolating || isDead) return; + + Entity_Player* player = GetPlayer(); + Entity* owner = parent; + if (owner && owner->type == ENTITY_KNIFE) owner = owner->parent; + if (owner && owner->type != ENTITY_PLAYER && owner->type != ENTITY_FAMILIAR && owner->type != ENTITY_TEAR) + owner = nullptr; + + int baseVariant = GetBaseVariant(); + bool isIdleSword = baseVariant == KNIFE_SPIRIT_SWORD && !isSwinging; + if (subtype == KNIFE_SUBTYPE_HELD_ITEM || isIdleSword) + { + if (tearFlags[TEAR_WAIT] && sprite.GetFrame() >= SWING_SHOT_FRAMES && + g_game->frameCount - spawnFrame <= SWING_WAIT_LIMIT && sprite.animState.animData) + sprite.animState.SetFrameFloat(SWING_WAIT_FRAME); + int frame = sprite.animState.animData ? (int)std::floor(sprite.animState.animFrame) : -1; + bool isHitFrame = sprite.animState.animData && (unsigned)(frame - SWING_FIRST_HIT_FRAME) < SWING_HIT_FRAMES; + + if (baseVariant == KNIFE_SPIRIT_SWORD || isHitFrame) + { + SwingHit hit; + bool isScythe = variant == KNIFE_BONE_SCYTHE; + hit.knockback = mass * (isScythe ? SCYTHE_KNOCKBACK : CLUB_KNOCKBACK); + if (variant == KNIFE_BAG_OF_CRAFTING) hit.knockback = BAG_KNOCKBACK; + hit.knockback /= KNOCKBACK_SHARE; + hit.recoil = player && player->playerType == PLAYER_THEFORGOTTEN_B ? 0 : mass * RECOIL / KNOCKBACK_SHARE; + hit.player = player; + hit.owner = owner; + hit.isIdleSword = isIdleSword; + hit.tearFlags = tearFlags; + hit.knockbackOrigin = player ? player->pos : pos; + if (variant == KNIFE_NOTCHED_AXE) g_notchedAxePlayer = player; + hit.damage = (isScythe ? SCYTHE_DAMAGE : CLUB_DAMAGE) * collisionDamage; + if (g_game->deathmatchManager.state >= DEATHMATCH_INTRO && variant == KNIFE_DONKEY_JAWBONE) + hit.damage = collisionDamage * JAWBONE_VERSUS_DAMAGE; + else if (variant == KNIFE_TECH_SWORD) + hit.tearFlags.set(TEAR_SHIELDED); + if (baseVariant == KNIFE_SPIRIT_SWORD) + { + hit.damage = collisionDamage; + if (isSpinAttack) hit.damage = hit.damage * SWORD_SPIN_DAMAGE + SWORD_SPIN_DAMAGE_BONUS; + else if (!isIdleSword) hit.damage = hit.damage * SWORD_DAMAGE + SWORD_DAMAGE_BONUS; + } + hit.reach = swing_reach_get(*this, isIdleSword); + + if (!swing_grid_hit(*this, hit.reach, hit.isHit)) return; + bool isShotsHit = hit.tearFlags[TEAR_SHIELDED] || variant == KNIFE_BAG_OF_CRAFTING || + variant == KNIFE_DONKEY_JAWBONE || (baseVariant == KNIFE_SPIRIT_SWORD && isSpinAttack); + uint32_t partitions = QUERY_FAMILIARS | QUERY_TEARS | QUERY_ENEMIES | QUERY_PICKUPS; + if (isShotsHit && frame < SWING_SHOT_FRAMES) partitions |= QUERY_PROJECTILES; + + for (Entity* entity : entity_query_radius(hit.reach.center, hit.reach.radius, partitions)) + { + if (entity->size == 0 || entity->entityCollisionClass == ENTCOLL_NONE) continue; + if (hit.reach.tip.halfLength > 0 && !swing_touches(hit.reach, entity->GetCollisionCapsule({}))) continue; + + bool isVersusRival = g_game->deathmatchManager.state >= DEATHMATCH_INTRO && entity->is_player() && + entity != spawnerEntity; + bool isEnemy = (entity->type >= ENTITY_FIRST_ENEMY && entity->type < ENTITY_EFFECT) || isVersusRival; + if (isEnemy && !entity->HasEntityFlags(FLAG_FRIENDLY)) + { + if (!swing_enemy_hit(*this, *entity, hit)) return; + } + else if (!isIdleSword) + swing_other_hit(*this, *entity, hit); + } + + if (hit.isHit && player && player->HasCollectible(COLLECTIBLE_DEAD_EYE) && linkedKnife) + { + Entity_Knife& main = *static_cast(linkedKnife.get()); + if (!main.isDeadEyeHit) player->AddDeadEyeCharge(); + main.isDeadEyeHit = true; + } + if (variant == KNIFE_NOTCHED_AXE) g_notchedAxePlayer = nullptr; + } + } + + if (subtype != KNIFE_SUBTYPE_HELD_ITEM) + { + if (swingEffects > 0) + { + if ((swingTick & 1) == 0) + { + if (!swing_effect_spawn(*this, player, swing_reach_get(*this, false))) return; + swingEffects--; + } + swingTick++; + } + bool isStopped = !sprite.animState.animData || !sprite.animState.isPlaying; + if (isStopped && player && isPrimaryClub) + { + // ClearDeadEyeCharge does nothing without charges. + if (!isDeadEyeHit && player->deadEyeCharges != 0) player->ClearDeadEyeCharge(); + isDeadEyeHit = false; + } + } + + bool isStopped = !sprite.animState.animData || !sprite.animState.isPlaying; + if (isStopped || (baseVariant == KNIFE_SPIRIT_SWORD && isAttacking && sprite.WasEventTriggered("SwingEnd"))) + isSwinging = false; +} + +// 0096ae70 What a knife's hit sets off: a held club's Ipecac blast, Haemolacria's burst or the Parasite's four shards; +// a thrown knife's Cricket's Body split (once a throw) or Ipecac blast (once a throw, bigger with the charge). Mom's +// Knife (and the scythe) set off the rest only one hit in four: Cricket's Body's and Compound Fracture's bone shards, +// Rift, and Sticky, Booger and Spore tears stuck in a living enemy. +void Entity_Knife::apply_hit_effects(const KnifeHit& hit) +{ + Entity_Player* player = GetPlayer(); + float scaleY = sprite.scale.y; + float tearHeight = player ? player->tearHeight : SHARD_HEIGHT_DEFAULT; + float fallSpeed = player ? player->tearFallingSpeed : 0; + float fallAccel = player ? player->tearFallingAcceleration : 0; + float shardSpeed = player ? player->shotSpeed * KNIFE_SHARD_SPEED : KNIFE_SHARD_SPEED; + Vector toTarget = vector_normalized(vector_sub(hit.targetPosition, hit.position)); + Vector hitPosition = vector_sub(hit.targetPosition, vector_scale(toTarget, hit.targetSize)); + Vector shardPosition = vector_sub(hitPosition, vector_scale(toTarget, SHARD_BACKSTEP * scaleY)); + int baseVariant = GetBaseVariant(); + + if (!hit.isFlying && baseVariant == KNIFE_BONE_CLUB) + { + if (tearFlags[TEAR_EXPLOSIVE]) + { + explosion_tear_flag_effects({.tearFlags = tearFlags, .position = hitPosition, .source = this, + .radius = CLUB_BLAST_RADIUS}); + explosion_damage({.tearFlags = tearFlags, + .position = hitPosition, + .source = this, + .damageFlags = hit.damageFlags | DAMAGE_EXPLOSION, + .damage = hit.damage * CLUB_BLAST_DAMAGE, + .radius = CLUB_BLAST_RADIUS}); + if (tearFlags[TEAR_POISON]) poison_cloud_spawn(hitPosition, 1, false); + Entity* blast = g_game->Spawn({.position = hitPosition, .type = ENTITY_EFFECT, .variant = EFFECT_BOMB_EXPLOSION, + .seed = Random()}); + blast->posOffset = posOffset; + blast->SetColor(sprite.color, -1, COLOR_PRIORITY_DEFAULT, false, true); + } + + if (tearFlags[TEAR_BURSTSPLIT]) + { + int count = (int)(Random() % BURST_SPREAD) + BURST_MIN; + float burstScale = scaleY / BURST_SCALE; + for (int i = 0; i < count; i++) + { + uint32_t seed = Random(); + float angle = random_unit() * RANDOM_HALF_TURN_KNIFE; + angle += angle; + Vector velocity = vector_make(std::cos(angle) * shardSpeed, std::sin(angle) * shardSpeed); + Entity_Tear& tear = *static_cast(g_game->Spawn({.position = shardPosition, + .velocity = velocity, + .spawner = player, + .type = ENTITY_TEAR, + .variant = TEAR_BLOOD, + .seed = seed})); + tear.SetTearFlags(flags_without(tearFlags, BURST_SHARD_DROPPED)); + float strength = random_unit() * BURST_DAMAGE_SPREAD + BURST_DAMAGE_MIN; + tear.SetCollisionDamage(collisionDamage / BURST_SCALE * strength); + tear.baseScale = std::max(burstScale * strength, SHARD_SCALE_MIN); + tear.fScale = tear.baseScale; + tear.ResetSpriteScale(); + tear.SetHeight(SHARD_HEIGHT_DEFAULT); + tear.fallingAccel = BURST_FALL_ACCEL; + tear.fallingSpeed = (random_unit() * HAEMO_FALL_SPREAD + BURST_FALL_MIN) * (tearHeight * 0.5f); + tear.SetColor(sprite.color, -1, COLOR_PRIORITY_DEFAULT, false, true); + tear.Update(); + + Entity* trail = g_game->Spawn({.position = tear.pos, + .velocity = vector_scale(tear.velocity, BURST_TRAIL_SPEED), + .type = ENTITY_EFFECT, + .variant = EFFECT_HAEMO_TRAIL, + .seed = Random()}); + trail->sprite.playbackSpeed = random_unit() * BURST_TRAIL_PLAYBACK + BURST_TRAIL_PLAYBACK_MIN; + float trailScale = random_unit() * BURST_TRAIL_SCALE + BURST_TRAIL_SCALE; + trail->sprite.scale = vector_make(tear.fScale * 0.5f * trailScale, tear.fScale * 0.5f * trailScale); + trail->posOffset = tear.posOffset; + trail->renderZOffset = BURST_TRAIL_DEPTH; + trail->sprite.color = sprite.color; + trail->Update(); + } + } + else if (tearFlags[TEAR_QUADSPLIT]) + { + Vector spread = vector_scale(random_direction(), shardSpeed); + for (int i = 0; i < 4; i++) + { + Vector velocity = i < 2 ? spread : vector_make(spread.y, -spread.x); + if (i & 1) velocity = vector_scale(velocity, -1); + Entity_Tear& shard = bone_shard_spawn(*this, shardPosition, velocity, player); + shard.SetHeight(tearHeight * SHARD_QUAD_HEIGHT); + shard.fallingAccel = fallAccel; + float fall = fallSpeed > 0 ? fallSpeed * SHARD_QUAD_FALL : fallSpeed; + shard.fallingSpeed = random_unit() * SHARD_FALL_SPREAD - fall; + shard.SetTearFlags(flags_without(tearFlags, QUAD_SHARD_DROPPED)); + shard_finish(*this, shard, scaleY, player); + } + } + } + else + { + bool isRolled = variant == KNIFE_BONE_SCYTHE || variant == KNIFE_MOMS_KNIFE; + bool isProcEffects = !isRolled || (Random() & 3) == 0; + if (hit.isFlying && knifeVelocity > 0) + { + TearFlags fresh = tearFlags & ~usedTearFlags; + if (fresh[TEAR_SPLIT] && baseVariant == KNIFE_MOMS_KNIFE) + { + usedTearFlags.set(TEAR_SPLIT); + for (int i = 0; i < 2; i++) + { + Entity* spawned = game_spawn({.position = pos, .spawner = this, .type = ENTITY_KNIFE, .seed = Random()}, + POOL_KEEP); + if (!spawned) continue; + Entity_Knife& split = *static_cast(spawned); + split.parent = this; + split.copy_parent_state(*this); + split.splitDistance = knifeDistance; + split.splitAngle = i == 0 ? SPLIT_ANGLE : -SPLIT_ANGLE; + split.isUsingParentHitList = true; + split.sprite.scale = vector_scale(sprite.scale, KNIFE_SPLIT_SCALE); + } + } + + if (fresh[TEAR_EXPLOSIVE] && baseVariant != KNIFE_SPIRIT_SWORD) + { + usedTearFlags.set(TEAR_EXPLOSIVE); + Vector at = vector_add(pos, vector_scale(vector_from_angle(rotation), KNIFE_BLAST_STEP)); + explosion_tear_flag_effects({.tearFlags = tearFlags, .position = at, .source = this, + .radius = CLUB_BLAST_RADIUS}); + Entity* owner = spawnerEntity; + float blastScale = std::clamp(charge * KNIFE_BLAST_SCALE_CHARGE + KNIFE_BLAST_SCALE_MIN, + KNIFE_BLAST_SCALE_MIN, KNIFE_BLAST_SCALE_MAX); + float damage = blastScale * collisionDamage + KNIFE_BLAST_DAMAGE_BASE; + uint64_t damageFlags = DAMAGE_EXPLOSION; + if (owner && owner->is_player()) + { + Entity_Player& shooter = *owner->ToPlayer(); + bool isGuppy = shooter.HasPlayerForm(0); + if ((isGuppy || shooter.HasCollectible(COLLECTIBLE_MULLIGAN)) && + ((spawnerType != ENTITY_FAMILIAR && Random() % BLAST_BLUE_FLY_ODDS == 0) || + (isGuppy && shooter.numBlueFlies < BLAST_BLUE_FLY_MAX))) + damageFlags |= DAMAGE_SPAWN_FLY; + } + float radius = sprite.scale.x * std::min(std::sqrt(damage / KNIFE_BLAST_REFERENCE_DAMAGE) * CLUB_BLAST_RADIUS, + KNIFE_BLAST_RADIUS_MAX); + float sizeScale = radius / CLUB_BLAST_RADIUS; + explosion_damage({.tearFlags = tearFlags, + .position = at, + .source = this, + .damageFlags = damageFlags, + .damage = damage, + .radius = radius}); + if (tearFlags[TEAR_POISON]) poison_cloud_spawn(at, sizeScale, true); + Entity* blast = g_game->Spawn({.position = at, .type = ENTITY_EFFECT, .variant = EFFECT_BOMB_EXPLOSION, + .seed = Random()}); + blast->posOffset = posOffset; + if (sizeScale != 1) blast->sprite.scale = vector_scale(blast->sprite.scale, sizeScale); + blast->SetColor(sprite.color, -1, COLOR_PRIORITY_DEFAULT, false, true); + } + } + if (!isProcEffects) return; + } + + if (tearFlags[TEAR_SPLIT] && baseVariant != KNIFE_MOMS_KNIFE) + for (int i = 0; i < 2; i++) + { + Vector velocity = vector_make(toTarget.y * shardSpeed, -toTarget.x * shardSpeed); + if (i == 1) velocity = vector_scale(velocity, -1); + Entity_Tear& shard = bone_shard_spawn(*this, shardPosition, velocity, player); + shard.SetHeight(tearHeight / SHARD_SPLIT_HEIGHT); + shard.fallingSpeed = fallSpeed; + shard.baseScale = std::max(scaleY, SHARD_SCALE_MIN); + shard.fScale = shard.baseScale; + shard.ResetSpriteScale(); + shard.SetTearFlags(flags_without(tearFlags, SPLIT_SHARD_DROPPED)); + shard.SetColor(sprite.color, -1, COLOR_PRIORITY_DEFAULT, false, true); + shard.parent = player; + shard.Update(); + } + + if (tearFlags[TEAR_BONE_FLAG]) + for (int i = 0; i < 2; i++) + { + float angle = random_unit() * RANDOM_HALF_TURN_KNIFE; + angle += angle; + Vector velocity = vector_make(std::cos(angle) * shardSpeed, std::sin(angle) * shardSpeed); + Entity_Tear& shard = bone_shard_spawn(*this, shardPosition, velocity, player); + shard.height = tearHeight; + shard.posOffset.y = shard.get_height_offset_y(tearHeight); + if (g_game->room->roomType == ROOM_DUNGEON) + { + shard.posOffset.y = SHARD_CRAWLSPACE_OFFSET_Y; + if (tearHeight > CRAWLSPACE_HEIGHT_MAX) shard.height = CRAWLSPACE_HEIGHT_MAX; + } + shard.fallingSpeed = fallSpeed; + shard.SetTearFlags(flags_without(tearFlags, BONE_SHARD_DROPPED)); + shard_finish(*this, shard, scaleY, player); + } + + if (tearFlags[TEAR_JACOBS]) + reconstruction_missing("Entity_Knife::apply_hit_effects 0096ae70 (Jacob's Ladder, spawn_chain_lightning 00707e10)"); + + if (tearFlags[TEAR_RIFT] && g_game->room->IsPositionInRoom(hitPosition, RIFT_MARGIN)) + { + Vector at = g_game->room->GetClampedPositionImpl(hitPosition, 0, 0, 0, 0); + Entity_Effect& rift = *static_cast(g_game->Spawn( + {.position = at, .spawner = spawnerEntity, .type = ENTITY_EFFECT, .variant = EFFECT_RIFT, .seed = Random()})); + rift.sprite.scale = vector_make(scale, scale); + rift.SetCollisionDamage(collisionDamage * 0.5f); + rift.SetTimeout(g_game->deathmatchManager.state >= DEATHMATCH_INTRO ? RIFT_VERSUS_FRAMES : RIFT_FRAMES); + rift.Update(); + swing_sound_play(SOUND_OCCULAR_RIFT_PORTAL, {}); + } + + Entity& target = *hit.target; + bool isSticky = tearFlags[TEAR_STICKY] || tearFlags[TEAR_BOOGER_FLAG] || tearFlags[TEAR_SPORE_FLAG]; + if (!target.IsActiveEnemy(DEAD_EXCLUDED) || !isSticky) return; + + Vector offset = vector_sub(hitPosition, target.pos); + float length = vector_length(offset); + if (target.size < length && length > 0) offset = vector_scale(offset, target.size / length); + int tearVariant = tearFlags[TEAR_BOOGER_FLAG] ? TEAR_BOOGER : tearFlags[TEAR_SPORE_FLAG] ? TEAR_SPORE : TEAR_EXPLOSIVO; + TearFlags flags = flags_without(tearFlags, STUCK_TEAR_DROPPED); + Entity_Tear& tear = *static_cast(g_game->Spawn({.position = vector_add(target.pos, offset), + .spawner = spawnerEntity, + .type = ENTITY_TEAR, + .variant = tearVariant, + .seed = Random()})); + tear.Update(); + tear.SetTearFlags(flags); + tear.SetCollisionDamage(collisionDamage); + tear.baseScale = std::max(scale, SHARD_SCALE_MIN); + tear.fScale = tear.baseScale; + tear.ResetSpriteScale(); + Entity::ForceCollide(&tear, &target, true); +} diff --git a/src/entity_npc.cpp b/src/entity_npc.cpp index 93852db..4e271c5 100644 --- a/src/entity_npc.cpp +++ b/src/entity_npc.cpp @@ -32,7 +32,6 @@ constexpr int CHARGE_BAR_FRAMES = 100; constexpr int ENTITY_FEAR_IMMUNE = 205; constexpr int ENTITY_NO_DECOY_TYPE = 213; constexpr int ENTITY_MOMS_HEART_PLAYER_PICK = 53; -constexpr int ENTITY_DEATH_REWARD_EXEMPT = 885; constexpr int ENTITY_UNREACHABLE_EXEMPT = 886; constexpr int ENTITY_FLICKER_TYPE = 252; constexpr int ENTITY_DEATH_SPARK_TYPE = 882; @@ -56,7 +55,6 @@ constexpr int DEATH_NO_BURST_FIRST = 74; constexpr int DEATH_NO_BURST_LAST = 76; constexpr int MULLIGAN_VARIANT_FLEEING = 2; constexpr int CHALLENGE_KILL_CHARGE = 33; -constexpr int COLLECTIBLE_LIL_PORTAL_ID = 661; constexpr std::string_view BIG_HORN_SPIT_EVENT = "Item"; constexpr std::string_view DIRT_LAYER = "dirt"; constexpr std::string_view HOLE_LAYER = "Hole"; @@ -97,10 +95,8 @@ constexpr float SHIELD_SECOND = 30; constexpr float SHIELD_BASE = 0.09f; constexpr float SHIELD_FALLOFF = 0.18f; constexpr uint32_t BLACK_HEART_CHANCE = 5; -constexpr float EXORCIST_ROOM_MARGIN = -10; constexpr int SOUND_POOP_DEATH = 237; constexpr float POOP_DEATH_VOLUME = 0.9f; -constexpr uint32_t DEBUG_HEALTH_VALUES = 1 << 6; constexpr uint64_t FLAG_FRIENDLY_BALL_DYING = 1ull << 60; // The burst effects a dead NPC leaves besides blood (Lua's EffectVariant). @@ -120,16 +116,11 @@ constexpr int SHADOW_CHARGER_SUBTYPE = 1; constexpr int TYPE_NO_TICK_A = 274; constexpr int TYPE_NO_TICK_B = 275; -constexpr int ENTITY_KEY_TEAR_A = 43; -constexpr int ENTITY_KEY_TEAR_B = 44; - // The items and seeds whose effects the NPC update reads, by Lua id. constexpr int COLLECTIBLE_HOURGLASS_ID = 66; constexpr int COLLECTIBLE_GAMEKID_ID = 93; constexpr int COLLECTIBLE_CHAMPION_BELT_ID = 208; -constexpr int COLLECTIBLE_GIMPY_ID = 225; constexpr int COLLECTIBLE_STOP_WATCH_ID = 232; -constexpr int COLLECTIBLE_INFESTATION_2_ID = 234; constexpr int COLLECTIBLE_SOUL_ID = 335; constexpr int COLLECTIBLE_TOXIC_SHOCK_ID = 350; constexpr int COLLECTIBLE_BETRAYAL_ID = 391; @@ -138,11 +129,7 @@ constexpr int COLLECTIBLE_MAW_OF_THE_VOID_ID = 408; constexpr int COLLECTIBLE_JAR_OF_FLIES_ID = 434; constexpr int COLLECTIBLE_CONTAGION_ID = 466; constexpr int COLLECTIBLE_BROKEN_MODEM_ID = 514; -constexpr int COLLECTIBLE_SANGUINE_BOND_ID = 640; -constexpr int COLLECTIBLE_VASCULITIS_ID = 657; constexpr int COLLECTIBLE_GUPPYS_EYE_ID = 665; -constexpr int COLLECTIBLE_BONE_SPURS_ID = 683; -constexpr int COLLECTIBLE_LIL_ABADDON_ID = 684; constexpr int COLLECTIBLE_SALVATION_ID = 696; constexpr int COLLECTIBLE_VANISHING_TWIN_ID = 697; constexpr int TRINKET_PURPLE_HEART_ID = 5; @@ -150,7 +137,6 @@ constexpr int TRINKET_TICK_ID = 53; constexpr int TRINKET_SUPER_MAGNET_ID = 68; constexpr int TRINKET_LIGHTER_ID = 135; constexpr int TRINKET_ICE_CUBE_ID = 188; -constexpr int TRINKET_DEVILS_CROWN_ID = 185; constexpr int NULLITEM_DAMOCLES_WEAKNESS = 64; constexpr int CHALLENGE_BEANS = 30; @@ -434,7 +420,7 @@ bool game_is_hard_mode() } // 00703470 Remembers a boss as met this run, but for the ones the boss list leaves out. -static void game_encountered_boss_add(int bossType, int bossVariant) +void game_encountered_boss_add(int bossType, int bossVariant) { std::vector& bosses = g_game->encounteredBosses; auto isSame = [&](const BossId& boss) { @@ -2451,61 +2437,6 @@ void Entity_NPC::fire_projectile_from_params(Entity_Projectile* projectile) projectile->apply_spawn_flags({this, flags, scale, isChampion ? championColorIdx : -1}); } -// The NPC types with their own interpolation or drawing, which the generic steps below do not cover. -constexpr std::array INTERPOLATE_SPECIAL_TYPES = {62, 815, 830, 831, 881, 915}; -constexpr std::array RENDER_SPECIAL_TYPES = {273, 411, 807, 810, 815, 816, 835, 865, 881, 886, 893, - 906, 909, 910, 912, 920, 921, 950, 951, 964, 965}; - -// 006d2b50 Moves it the interpolation's half step (Entity::Interpolate), runs its AI's interpolation call, and moves -// the effect it aims with. -void Entity_NPC::Interpolate() -{ - if (pauseTimer != 0) return; - if (type == ENTITY_MINECART) minecart_interpolate(*this); - else Entity::Interpolate(); - if (aiCallFlags & AI_CALL_INTERPOLATE) ai_call(AI_PHASE_INTERPOLATE); - UpdateChildEffectPosition(true); - - bool isHeld = HasEntityFlags(FLAG_FREEZE | FLAG_HELD) || holdCountdown > 0; - bool isStill = isHeld || state == NPC_STATE_APPEAR || state == NPC_STATE_DEATH || state == NPC_STATE_UNIQUE_DEATH; - if (!isStill && std::ranges::find(INTERPOLATE_SPECIAL_TYPES, type) != INTERPOLATE_SPECIAL_TYPES.end()) - reconstruction_missing("Entity_NPC::Interpolate 006d2b50: a jumping enemy's height"); - if (type == ENTITY_HEART && variant == 1 && entityRef && entityRef->IsEnemy()) - { - Entity* partner = entityRef; - targetPosition = vector_sub(partner->pos, pos); - partner->targetPosition = vector_scale(targetPosition, -1); - } -} - -// 006d2e50 Draws it (Entity::Render) and, in the normal and above water passes, the status effect it suffers on its -// OverlayEffect null. -void Entity_NPC::Render(const Vector& offset) -{ - if (type == ENTITY_MINECART && variant == 0 && child) return; - bool isLinked = (type == ENTITY_LARRYJR && variant == 3 && child) || (type == ENTITY_POOP && entityRef); - if (minecart || isLinked || std::ranges::find(RENDER_SPECIAL_TYPES, type) != RENDER_SPECIAL_TYPES.end()) - reconstruction_missing("Entity_NPC::Render 006d2e50: a special enemy's drawing"); - if (spawnerEntity && spawnerEntity->type == ENTITY_PLAYER && g_manager->netplayManager.is_online()) - reconstruction_missing("Entity_NPC::Render 006d2e50: a remote player's faded enemy"); - if (championColorIdx == CHAMPION_SIZE_PULSE) - reconstruction_missing("Entity_NPC::Render 006d2e50: the size pulsing champion"); - - Entity::Render(offset); - if (!isVisible) - renderPosition = vector_add(render_position_get(vector_add(pos, posOffset), RENDER_SNAPPED), offset); - lua_engine_get().PostNPCRender(this, offset); - - RenderMode renderMode = g_game->room->entityList.renderMode; - if (renderMode != RENDER_NORMAL && renderMode != RENDER_WATER_ABOVE) return; - status_overlay_render(offset); - if (g_game->playerManager.FirstCollectibleOwner(COLLECTIBLE_SPIDER_MOD_ID, LAZARUS_SHARE_CHECK) && isVisible && - IsActiveEnemy(DEAD_EXCLUDED)) - reconstruction_missing("Entity_NPC::Render 006d2e50: Spider Mod's health bar"); - if (HasEntityFlags(FLAG_PERSISTENT | FLAG_FRIENDLY_BALL_DYING) && (g_game->debugFlags & DEBUG_HEALTH_VALUES)) - reconstruction_missing("Entity_NPC::Render 006d2e50: the debug health text"); -} - // Part of 006d2e50: the status effect sprite drawn on the OverlayEffect null, once on a shared body. void Entity_NPC::status_overlay_render(const Vector& offset) { @@ -2645,52 +2576,6 @@ void Entity_NPC::trigger_kill_item_effects() lua_engine_get().PostNPCDeath(this); } -// 006bbdc0 The rewards a dead enemy gives its killers: the damage flags' and Gimpy's drops, the familiars' and -// items' on-kill effects, Keeper's and the bosses' coins, the soul hearts of Sanguine Bond and the like. None of them -// happens without its item or flag, which is all this covers yet. -void Entity_NPC::trigger_death_rewards() -{ - bool isRewarded = Entity::is_enemy_type(type) && type != ENTITY_FIREPLACE && type != ENTITY_SHOPKEEPER && - type != ENTITY_MOVABLE_TNT && !(type == ENTITY_DEATH_REWARD_EXEMPT && variant == 10) && - type != ENTITY_FROZEN_ENEMY && type != ENTITY_MINECART && type != ENTITY_POOP; - if (!isRewarded) return; - if (DoesEntityShareStatus() && parent && type != ENTITY_LARRYJR && type != ENTITY_BUTTLICKER) return; - - PlayerManager& players = g_game->playerManager; - auto isFamiliarKill = [](const DamageEvent& event) { - return event.source.type == ENTITY_FAMILIAR || event.source.type == ENTITY_BLOOD_PUPPY || - (event.source.type == ENTITY_TEAR && - (event.source.variant == ENTITY_KEY_TEAR_A || event.source.variant == ENTITY_KEY_TEAR_B)); - }; - bool isRewardItem = players.FirstCollectibleOwner(COLLECTIBLE_GIMPY_ID, LAZARUS_SHARE_CHECK) || - (killDamageFlags & ((uint64_t)DAMAGE_SPAWN_RED_HEART | DAMAGE_SPAWN_COIN | - DAMAGE_SPAWN_BLACK_HEART | DAMAGE_SPAWN_CARD | DAMAGE_SPAWN_RUNE)) || - std::ranges::any_of(killDamageEvents, isFamiliarKill) || - players.RandomCollectibleOwner(COLLECTIBLE_INFESTATION_2_ID, initSeed, nullptr) || - players.RandomCollectibleOwner(COLLECTIBLE_BONE_SPURS_ID, initSeed, nullptr) || - players.RandomCollectibleOwner(COLLECTIBLE_LIL_ABADDON_ID, initSeed, nullptr) || - players.RandomTrinketOwner(TRINKET_DEVILS_CROWN_ID, initSeed, nullptr) || - players.FirstCollectibleOwner(COLLECTIBLE_VASCULITIS_ID, LAZARUS_SHARE_CHECK); - if (!HasEntityFlags(FLAG_NO_REWARD) && isRewardItem) - reconstruction_missing("Entity_NPC::trigger_death_rewards 006bbdc0: the kill's item and flag rewards"); - if (!CanShutDoors()) return; - - if (g_game->room->isExorcistActive && g_game->room->IsPositionInRoom(pos, EXORCIST_ROOM_MARGIN)) - reconstruction_missing("Entity_NPC::trigger_death_rewards 006bbdc0: the Exorcist's souls"); - if (g_game->room->IsPositionInRoom(pos, EXORCIST_ROOM_MARGIN)) - for (Entity_Player* player : players.playerList) - if (player->variant == 0 && player->HasCollectible(COLLECTIBLE_LIL_PORTAL_ID)) - reconstruction_missing("Entity_NPC::trigger_death_rewards 006bbdc0: Lil Portal's growth"); - for (Entity_Player* player : players.playerList) - { - bool isLiving = player->variant == 0 && !player->isCoopGhost; - if (isLiving && player->playerType == PLAYER_MAGDALENE_B) - reconstruction_missing("Entity_NPC::trigger_death_rewards 006bbdc0: Tainted Magdalene's hearts"); - if (player->variant == 0 && player->HasCollectible(COLLECTIBLE_SANGUINE_BOND_ID)) - reconstruction_missing("Entity_NPC::trigger_death_rewards 006bbdc0: the soul drops"); - } -} - // 00447770 Its parent, which only NPCs are. Entity_NPC* Entity_NPC::ParentNPC() { @@ -2816,12 +2701,6 @@ Entity_NPC* Entity_NPC::ThrowStrider(const Vector&, Entity*, const Vector&) reconstruction_missing("Entity_NPC::ThrowStrider 0055cef0"); } -// 00565680 -void Entity_NPC::render_v1_layer_frames() -{ - reconstruction_missing("Entity_NPC::render_v1_layer_frames 00565680"); -} - // 0059bed0 void Entity_NPC::RenderSegmentLink(const Vector&, bool) { diff --git a/src/entity_npc.h b/src/entity_npc.h index 3684f11..b6ff0e8 100644 --- a/src/entity_npc.h +++ b/src/entity_npc.h @@ -383,6 +383,7 @@ bool any_player_flying(); Entity* game_nearest_target_player(const Vector& position, Entity* source, bool isPlayersOnly, bool isTargetDecoys, float maxDistance); void game_shake_screen(int timeout); +void game_encountered_boss_add(int bossType, int bossVariant); bool game_is_hard_mode(); uint32_t room_grid_collision_at(const Vector& position); ColorMod champion_sprite_color_get(int championColor); diff --git a/src/entity_npc_render.cpp b/src/entity_npc_render.cpp new file mode 100644 index 0000000..b777630 --- /dev/null +++ b/src/entity_npc_render.cpp @@ -0,0 +1,453 @@ +#include "entity_npc.h" +#include "entity_config.h" +#include "entity_player.h" +#include "game.h" +#include "lua_engine.h" +#include "manager.h" +#include "mines.h" +#include "npc_ai.h" +#include "room.h" +#include +#include +#include +#include + +constexpr float NPC_SCREEN_SCALE = 0.65f; +constexpr int NPC_DEBUG_HEALTH_FLAG = 1 << 6; +constexpr int SPAWN_BAR_DELAY = 2; +constexpr float HEALTH_BAR_DROP = 10; + +// The variants with their own height or drawing: Wormwood, Big Bony's bone, Singe's ball, the Ultra Greed coin +// pile's statue, the Shell and Dogma's body. +constexpr int WORMWOOD = 3; +constexpr int BIG_BONY_BONE = 10; +constexpr int FESTERING_GUTS = 20; +constexpr int SHELL = 3; +constexpr int SCOURGE_CHAIN = 10; +constexpr int RIDDEN_MINECART = 10; +constexpr int SINGE_BALL_VARIANT = 1; +constexpr int HEART_PAIRED = 1; + +// The ghost wraith's faintness without water to reflect it. +constexpr float WRAITH_DRY_ALPHA = 0.2f; + +// The size pulsing champion's beat: its speed per room frame and how much it swells. +constexpr float SIZE_PULSE_SPEED = 0.2f; +constexpr float SIZE_PULSE_SWELL = 0.15f; + +// The Lamb's dash: the afterimages it leaves, how far back they reach along its velocity, and the faint copy on top. +constexpr int LAMB_DASH_STATE = NPC_STATE_ATTACK2; +constexpr int LAMB_AFTERIMAGES = 7; +constexpr float LAMB_AFTERIMAGE_REACH = 5; +constexpr float LAMB_AFTERIMAGE_FADE = 0.9f; +constexpr float LAMB_AFTERIMAGE_BASE = 0.1f; +constexpr float LAMB_COPY_ALPHA = 0.2f; + +// The small leech hides above water while it swims below this height. +constexpr float SMALL_LEECH_SURFACE = -3; + +// A pickup held at the Item null rides a little lower. +constexpr float HELD_PICKUP_DROP = 6.5f; + +// The Needle's two trailing segments, spaced along its trail, and the depth they sink out of sight at. +constexpr int NEEDLE_SEGMENTS = 2; +constexpr float NEEDLE_SEGMENT_SPACING = 15; +constexpr float NEEDLE_HIDE_DEPTH = -6; +constexpr float NEEDLE_HIDE_STEP = 3; + +// The Fissure's head frames by its v1.x, its segments' sideways nudge, and the depths its layers fade over. +constexpr float FISSURE_TURN = 4; +constexpr float FISSURE_NUDGE = 3; +constexpr float FISSURE_FADE_START = -2; +constexpr float FISSURE_FADE_LENGTH = 18; +constexpr float FISSURE_REFLECT_FADE_START = 2; +constexpr float FISSURE_REFLECT_FADE_LENGTH = 78; + +// The player's Spider Mod, whose health bars Render draws. +constexpr int SPIDER_MOD_ITEM = 403; + +static bool is_type(const Entity_NPC& npc, int type, int variant) +{ + return npc.type == type && npc.variant == variant; +} + +// A world position's snapped place on screen, shifted by offset. +static Vector npc_screen_position(const Vector& world, const Vector& offset) +{ + return vector_add(render_position_get(world, RENDER_SNAPPED), offset); +} + +// The speed its jump height moves at for the half step, for the enemies whose AI keeps one: Wormwood's, Singe's ball's +// and Big Bony's bone's in v1, and the Needle's, Fissure's and Festering Guts's while jumping. +static const float* npc_height_speed(Entity_NPC& npc) +{ + if (is_type(npc, ENTITY_PIN, WORMWOOD)) return &npc.v1.x; + if (is_type(npc, ENTITY_SINGE, SINGE_BALL_VARIANT) || is_type(npc, ENTITY_BIG_BONY, BIG_BONY_BONE)) return &npc.v1.y; + + bool isJumper = npc.type == ENTITY_NEEDLE || npc.type == ENTITY_FISSURE || is_type(npc, ENTITY_GUTTED_FATTY, FESTERING_GUTS); + return isJumper && npc.state == NPC_STATE_JUMP ? &npc.v1.x : nullptr; +} + +// 006d2b50 Moves it the interpolation's half step (a minecart along its rail), runs its AI's interpolation call, moves +// the effect it aims with, raises a jumping enemy by half its height speed, and points a paired Heart at its Mask. +void Entity_NPC::Interpolate() +{ + if (pauseTimer != 0) return; + if (type == ENTITY_MINECART) minecart_interpolate(*this); + else Entity::Interpolate(); + if (aiCallFlags & AI_CALL_INTERPOLATE) ai_call(AI_PHASE_INTERPOLATE); + UpdateChildEffectPosition(true); + + bool isHeld = HasEntityFlags(FLAG_FREEZE | FLAG_HELD) || holdCountdown > 0; + bool isStill = isHeld || state == NPC_STATE_APPEAR || state == NPC_STATE_DEATH || state == NPC_STATE_UNIQUE_DEATH; + const float* heightSpeed = isStill ? nullptr : npc_height_speed(*this); + if (heightSpeed) posOffset.y = *heightSpeed * speedMultiplier / 2 + posOffset.y; + + Entity* partner = entityRef; + if (!is_type(*this, ENTITY_HEART, HEART_PAIRED) || !partner || !partner->IsEnemy()) return; + targetPosition = vector_sub(partner->pos, pos); + partner->targetPosition = vector_scale(targetPosition, -1); +} + +// 0054f670 NpcHelper::needle_render: while the Needle leaps, places its two trailing segments along its trail (a +// point every 15 units, counting height) and hides each one sunk below the floor. +static void needle_render(Entity_NPC& npc) +{ + if (npc.state != NPC_STATE_JUMP || npc.sprite.layerStates.size() <= NEEDLE_SEGMENTS) return; + + std::array points{}; + std::array heights{}; + Vector previous = npc.pos; + float previousHeight = npc.v1.y; + float spacing = NEEDLE_SEGMENT_SPACING; + int count = 0; + + for (size_t i = 0; i < npc.vectorDeque1.size() && count < NEEDLE_SEGMENTS;) + { + Vector delta = vector_sub(npc.vectorDeque1[i], previous); + float rise = npc.vectorDeque2[i].y - previousHeight; + float distance = std::sqrt(delta.x * delta.x + delta.y * delta.y + rise * rise); + spacing -= distance; + if (spacing > 0) + { + previous = npc.vectorDeque1[i]; + previousHeight = npc.vectorDeque2[i].y; + i++; + continue; + } + + float t = (distance + spacing) / distance; + previous = vector_add(previous, vector_scale(delta, t)); + previousHeight += rise * t; + points[count] = previous; + heights[count] = previousHeight; + count++; + spacing = NEEDLE_SEGMENT_SPACING; + if (i == 0) i++; + } + for (; count < NEEDLE_SEGMENTS; count++) + { + points[count] = previous; + heights[count] = previousHeight; + } + + bool isReflected = g_game->room->entityList.renderMode == RENDER_WATER_REFLECT; + float lift = isReflected ? -npc.posOffset.y : npc.posOffset.y; + for (int segment = 0; segment < NEEDLE_SEGMENTS; segment++) + { + LayerState* layer = npc.sprite.GetLayer(segment + 1); + Vector shift = vector_make(points[segment].x - npc.pos.x, points[segment].y - npc.pos.y + heights[segment] - lift); + layer->pos = vector_scale(shift, NPC_SCREEN_SCALE); + layer->isVisible = heights[segment] <= NEEDLE_HIDE_DEPTH - (float)(segment + 1) * NEEDLE_HIDE_STEP; + } +} + +// The wraith's alpha in the mirror world's Downpour II: seen only in the other pass than the one it lives in, faintly +// where no water reflects it, brighter in lightning. +static float wraith_alpha_get(RenderMode renderMode) +{ + Game& game = *g_game; + bool isMirrorStage = game.stage == STAGE_BASEMENT_II || + (game.stage == STAGE_BASEMENT_I && (game.GetCurses() & CURSE_OF_LABYRINTH)); + bool isMirror = game.currentDimensionIdx == 1 && + (game.stageType == STAGETYPE_REPENTANCE || game.stageType == STAGETYPE_REPENTANCE_B) && isMirrorStage; + if ((renderMode != RENDER_WATER_REFLECT) == isMirror) return 1; + + bool isDry = game.room->waterAmount <= 0 || !g_manager->optionsConfig.render.isWaterSurfaceEnabled; + float alpha = isDry ? WRAITH_DRY_ALPHA : 0; + if (game.lightningIntensity > 0) alpha = std::min(std::max(game.lightningIntensity + alpha, alpha), 1.0f); + return alpha; +} + +// The Lamb's dash: afterimages trailing back along its velocity, fading out, then a faint copy over it. +static void lamb_afterimages_render(Entity_NPC& npc, const Vector& offset) +{ + Vector step = vector_scale(npc.velocity, -LAMB_AFTERIMAGE_REACH / LAMB_AFTERIMAGES); + Vector at = npc.pos; + ColorMod color = npc.sprite.color; + + for (int i = LAMB_AFTERIMAGES - 1; i >= 0; i--) + { + float fade = (float)i * LAMB_AFTERIMAGE_FADE / LAMB_AFTERIMAGES + LAMB_AFTERIMAGE_BASE; + npc.sprite.color = {{fade * color._tint[0], fade * color._tint[1], fade * color._tint[2], + fade * color._tint[3] / 2}, + {}, + {}}; + npc.sprite.Render(SpriteDraw{npc_screen_position(vector_add(at, npc.posOffset), offset), {}, {}}); + at = vector_add(at, step); + } + + npc.sprite.color = {{color._tint[0], color._tint[1], color._tint[2], color._tint[3] * LAMB_COPY_ALPHA}, {}, {}}; + npc.sprite.Render(SpriteDraw{npc_screen_position(vector_add(npc.pos, npc.posOffset), offset), {}, {}}); + npc.sprite.color = color; +} + +// The players riding a minecart, nearest the back first, each drawn where it sits in the cart. +static void minecart_riders_render(Entity_NPC& cart, const Vector& offset) +{ + std::map riders; + + for (Entity_Player* player : g_game->playerManager.playerList) + if (player->minecart == &cart) riders.emplace(player->minecartOffset.y, player); + for (auto& [depth, player] : riders) + { + Vector standing = player->pos; + player->pos = vector_add(cart.pos, player->minecartOffset); + player->isVisible = true; + player->Render(vector_add(offset, vector_scale(player->minecartOffset, NPC_SCREEN_SCALE))); + player->pos = standing; + player->isVisible = false; + } +} + +// The entity a poop carries, drawn where the poop is. +static void poop_rider_render(Entity_NPC& npc, const Vector& offset) +{ + Entity* rider = npc.entityRef; + Vector shift = vector_sub(vector_add(npc.pos, npc.posOffset), vector_add(rider->pos, rider->posOffset)); + + rider->isVisible = true; + rider->Render(vector_add(offset, vector_scale(shift, NPC_SCREEN_SCALE))); + rider->isVisible = false; +} + +// The entity Big Horn's hand or a Polty holds, drawn on its Item null. +static void held_entity_render(Entity_NPC& npc) +{ + Entity* held = npc.entityRef; + const NullFrame* frame = npc.sprite.animState.animData ? npc.sprite.GetNullFrame("Item") : nullptr; + if (!held || !frame || !frame->isVisible) return; + + Vector savedOffset = held->sprite.offset; + Vector savedScale = held->sprite.scale; + float drop = held->type == ENTITY_PICKUP ? HELD_PICKUP_DROP : 0; + held->sprite.offset = vector_make(frame->pos.x, drop + frame->pos.y); + held->sprite.scale = vector_make(savedScale.x * frame->scale.x, savedScale.y * frame->scale.y); + held->sprite.Render(SpriteDraw{npc.renderPosition, {}, {}}); + held->sprite.offset = savedOffset; + held->sprite.scale = savedScale; +} + +// The drawing of the bosses and enemies with their own (Entity::Render for the rest), between the chain or link +// drawn behind them and the one drawn in front. +static void npc_body_render(Entity_NPC& npc, const Vector& offset) +{ + bool isChained = npc.type == ENTITY_BALL_AND_CHAIN && !vector_is_zero(npc.targetPosition); + if (npc.type == ENTITY_BALL_AND_CHAIN && !isChained) return npc.Entity::Render(offset); + if (isChained && npc.pos.y > npc.targetPosition.y) + reconstruction_missing("NpcHelper::ball_and_chain_render_chain 004f5f20"); + if (npc.type == ENTITY_POOP && npc.entityRef && npc.isVisible) poop_rider_render(npc, offset); + + switch (npc.type) + { + case ENTITY_PEEPER_FATTY: + return reconstruction_missing("Entity_NPC::Render 006d2e50: the Peeping Fatty's eyes (005579b0)"); + case ENTITY_EVIS: + return reconstruction_missing("Entity_NPC::Render 006d2e50: Evis's cord (004e07a0)"); + case ENTITY_HORNFEL: + return reconstruction_missing("Entity_NPC::Render 006d2e50: Hornfel's drawing"); + case ENTITY_SCOURGE: + if (npc.variant != SCOURGE_CHAIN) return npc.Entity::Render(offset); + return reconstruction_missing("Entity_NPC::Render 006d2e50: the Scourge's chain (00589de0)"); + case ENTITY_MOTHER: + return reconstruction_missing("NpcHelper::mother_render 0056fcf0"); + case ENTITY_HORNY_BOYS: + return reconstruction_missing("NpcHelper::horny_boys_render 004bcfd0"); + case ENTITY_CLUTCH: + return reconstruction_missing("NpcHelper::clutch_render 00575a10"); + case ENTITY_BEAST: + return reconstruction_missing("Entity_NPC::Render 006d2e50: the Beast's drawing (00598260)"); + case ENTITY_MINECART: + if (npc.variant == RIDDEN_MINECART) return minecart_riders_render(npc, offset); + return npc.Entity::Render(offset); + default: + return npc.Entity::Render(offset); + } +} + +// The links and overlays drawn in front of its body: the Vis Fatty's overlay, the chain and the Shell's link when it +// lies above them, and the Chimera's other half. +static void npc_front_render(Entity_NPC& npc, const Vector& offset) +{ + if (npc.type == ENTITY_VIS_FATTY) npc.render_overlay(offset, false); + if (npc.type == ENTITY_BALL_AND_CHAIN && !vector_is_zero(npc.targetPosition) && npc.pos.y <= npc.targetPosition.y) + reconstruction_missing("NpcHelper::ball_and_chain_render_chain 004f5f20"); + if (is_type(npc, ENTITY_LARRYJR, SHELL) && npc.child && npc.pos.y <= npc.child->pos.y) + npc.RenderSegmentLink(offset, false); + if (npc.type == ENTITY_CHIMERA) reconstruction_missing("NpcHelper::chimera_render_child 004a1000"); +} + +// Whether a local player controls it. +static bool npc_is_locally_controlled(Entity_NPC& npc) +{ + NetplayManager& netplay = g_manager->netplayManager; + return npc.controllerID != -1 && (!netplay.is_online() || netplay.IsIdxLocalPlayer(npc.controllerID)); +} + +// Whether a health bar shows over it: Spider Mod's over a hurtable enemy with its OverlayEffect null shown, or the bar +// of a local player's controlled enemy. +static bool npc_is_health_bar_shown(Entity_NPC& npc) +{ + bool isSpiderMod = g_game->playerManager.FirstCollectibleOwner(SPIDER_MOD_ITEM, LAZARUS_SHARE_CHECK) && npc.isVisible && + npc.IsActiveEnemy(DEAD_EXCLUDED) && !npc.HasEntityFlags(FLAG_NO_TARGET) && + npc.sprite.color._tint[3] > 0 && g_game->frameCount - npc.spawnFrame >= SPAWN_BAR_DELAY && + npc.health > 0 && npc.GetStatusEffectTarget() == &npc && !npc.HasEntityFlags(FLAG_HIDE_HP_BAR); + if (isSpiderMod) + { + const NullFrame* frame = npc.sprite.GetNullFrame("OverlayEffect"); + return frame && frame->isVisible; + } + return npc_is_locally_controlled(npc); +} + +// 006d2e50 Draws it: hidden in the wrong pass or tinted, on its minecart, with a special body for some bosses, the +// size pulse, the Lamb's afterimages, and the links in front, then what it holds, its status effect, a health bar +// and its controller's charge bar. +void Entity_NPC::Render(const Vector& offset) +{ + if (is_type(*this, ENTITY_MINECART, 0) && child) return; + + RenderMode renderMode = g_game->room->entityList.renderMode; + Entity_NPC* cart = is_type(*this, ENTITY_MINECART, RIDDEN_MINECART) ? this : static_cast(minecart.get()); + Vector base = offset; + Vector cartPosition{}; + float alpha = type == ENTITY_WRAITH && !is_type(*this, ENTITY_MINECART, RIDDEN_MINECART) ? wraith_alpha_get(renderMode) : 1; + bool isHidden = alpha == 0; + + if (type == ENTITY_NEEDLE) needle_render(*this); + if (type == ENTITY_FISSURE) render_v1_layer_frames(); + if (type == ENTITY_NEEDLE || type == ENTITY_FISSURE) isHidden = !sprite.GetLayer(0)->isVisible; + if (type == ENTITY_SMALL_LEECH && posOffset.y > SMALL_LEECH_SURFACE && !HasEntityFlags(FLAG_HELD) && + renderMode == RENDER_WATER_ABOVE) + alpha = 0; + + if (cart && isVisible) + { + const NullFrame* frame = cart->sprite.animState.animData ? cart->sprite.animState.GetNullFrameById(0) : nullptr; + if (frame) + { + cartPosition = npc_screen_position(pos, offset); + base = vector_add(base, frame->pos); + cart->sprite.RenderLayer(0, SpriteDraw{cartPosition, {}, {}}); + } + alpha *= cart->sprite.color._tint[3]; + } + if (spawnerEntity && spawnerEntity->type == ENTITY_PLAYER && g_manager->netplayManager.is_online()) + reconstruction_missing("Entity_NPC::Render 006d2e50: a remote player's faded enemy"); + + Vector savedScale = sprite.scale; + float savedAlpha = sprite.color._tint[3]; + if (alpha > 0) + { + sprite.color._tint[3] = savedAlpha * alpha; + if (championColorIdx == CHAMPION_SIZE_PULSE) + { + float swell = std::clamp(std::sin((float)g_game->room->GetFrameCount() * SIZE_PULSE_SPEED), 0.0f, 1.0f); + sprite.scale = vector_scale(savedScale, swell * SIZE_PULSE_SWELL + 1); + } + if (type == ENTITY_THE_LAMB && state == LAMB_DASH_STATE) + { + if (!isExists || !isVisible) return; + lamb_afterimages_render(*this, base); + } + if (is_type(*this, ENTITY_LARRYJR, SHELL) && child && child->pos.y < pos.y) RenderSegmentLink(base, false); + if (is_type(*this, ENTITY_DOGMA, 0)) render_overlay(base, false); + npc_body_render(*this, base); + npc_front_render(*this, base); + } + + if (!isVisible || alpha <= 0) renderPosition = npc_screen_position(vector_add(pos, posOffset), base); + if ((type == ENTITY_BIG_HORN || type == ENTITY_POLTY) && entityRef) held_entity_render(*this); + if (alpha > 0) + { + if (championColorIdx == CHAMPION_SIZE_PULSE) sprite.scale = savedScale; + sprite.color._tint[3] = savedAlpha; + } + lua_engine_get().PostNPCRender(this, base); + + bool isMainPass = renderMode == RENDER_NORMAL || renderMode == RENDER_WATER_ABOVE; + if (isMainPass && !isHidden) + { + if (type == ENTITY_DUMMY) reconstruction_missing("Entity_NPC::Render 006d2e50: the dummy's damage text"); + status_overlay_render(base); + if (npc_is_health_bar_shown(*this)) + { + float barPosition[2] = {renderPosition.x, renderPosition.y + HEALTH_BAR_DROP}; + render_debug(barPosition, 0); + } + } + + if (cart && isVisible) + { + cart->sprite.RenderLayer(1, SpriteDraw{cartPosition, {}, {}}); + if (type == ENTITY_HORNFEL) reconstruction_missing("NpcHelper::hornfel_render_minecart 004b7c30"); + } + if (npc_is_locally_controlled(*this) && chargeBarSprite.isLoaded && chargeBarSprite.color._tint[3] > 0) + { + Vector at = vector_make(sprite.scale.y * 12 + renderPosition.x, renderPosition.y - sprite.scale.y * 35); + chargeBarSprite.Render(SpriteDraw{at, {}, {}}); + } + if (HasEntityFlags(FLAG_PERSISTENT | FLAG_DELIRIUM_FORM) && (g_game->debugFlags & NPC_DEBUG_HEALTH_FLAG)) + reconstruction_missing("Entity_NPC::Render 006d2e50: the debug health text"); +} + +// The fade of a Fissure layer at a depth: gone above the floor, or below it in the reflection. +static float fissure_alpha(float height, bool isReflected) +{ + float start = isReflected ? FISSURE_REFLECT_FADE_START : FISSURE_FADE_START; + float length = isReflected ? FISSURE_REFLECT_FADE_LENGTH : FISSURE_FADE_LENGTH; + return 1 - std::clamp((height - start) / length, 0.0f, 1.0f); +} + +// 00565680 The Fissure's head frame by its turn (v1.x), its two segments raised to the heights its trail recorded, +// the far one turned to its side, and each layer faded by its depth. +void Entity_NPC::render_v1_layer_frames() +{ + int frame = v1.x < 0 ? 1 : (v1.x <= FISSURE_TURN ? 0 : 2); + if (sprite.animState.animData) sprite.animState.SetLayerFrame(0, frame); + + float headHeight = posOffset.y; + float nearHeight = headHeight; + float farHeight = headHeight; + LayerState* farLayer = sprite.GetLayer(2); + if (vectorDeque1.size() > 1) + { + farLayer->pos = vector_make(0, (vectorDeque1[1].y - v1.y) * NPC_SCREEN_SCALE); + sprite.GetLayer(1)->pos = farLayer->pos; + nearHeight = vectorDeque1[1].y + posOffset.y - v1.y; + farHeight = nearHeight; + } + if (vectorDeque1.size() > 2) + { + const Vector& far = vectorDeque1[2]; + farLayer->pos = vector_make(far.x <= 0 ? FISSURE_NUDGE : -FISSURE_NUDGE, (far.y - v1.y) * NPC_SCREEN_SCALE); + farLayer->isFlipY = vectorDeque1[1].y < far.y; + farLayer->isFlipX = far.x > 0; + farHeight = far.y + posOffset.y - v1.y; + } + + bool isReflected = g_game->room->entityList.renderMode == RENDER_WATER_REFLECT; + sprite.GetLayer(0)->color._tint[3] = fissure_alpha(headHeight, isReflected); + sprite.GetLayer(1)->color._tint[3] = fissure_alpha(nearHeight, isReflected); + farLayer->color._tint[3] = fissure_alpha(farHeight, isReflected); +} diff --git a/src/entity_npc_rewards.cpp b/src/entity_npc_rewards.cpp new file mode 100644 index 0000000..e2bdcd0 --- /dev/null +++ b/src/entity_npc_rewards.cpp @@ -0,0 +1,344 @@ +#include "boss_ai.h" +#include "entity_effect_combat.h" +#include "entity_familiar.h" +#include "entity_pickup.h" +#include "entity_player.h" +#include "item_config.h" +#include "item_pool.h" +#include "manager.h" +#include "room_descriptor.h" +#include +#include + +// The Cultist's variant that gives no kill rewards, as the fireplace, the shopkeeper, movable TNT, props, minecarts and +// poop do not. +constexpr int CULTIST_BLOOD_VARIANT = 10; +constexpr int TEAR_SHARP_KEY = 43; +constexpr int TEAR_SHARP_KEY_SPECTRAL = 44; + +// Gimpy's half heart: one in a hundred kills of a weak enemy, one in twenty of a sturdier one, one in ten of a strong +// one (twice as likely for a champion's reward), one in ten again under Daemon's Tail. +constexpr float EXORCIST_ROOM_MARGIN = -10; +constexpr int EFFECT_HUNGRY_SOUL = 186; +constexpr float GIMPY_WEAK_HEALTH = 10; +constexpr float GIMPY_STRONG_HEALTH = 30; +constexpr uint32_t GIMPY_WEAK_ODDS = 100; +constexpr uint32_t GIMPY_ODDS = 20; +constexpr uint32_t GIMPY_STRONG_ODDS = 10; +constexpr uint32_t GIMPY_DAEMONS_TAIL_ODDS = 10; + +// Sharp Key's chest: one kill in ten by its keys opens one at once. +constexpr std::array SHARP_KEY_SHIFTS = {2, 21, 9}; +constexpr uint32_t SHARP_KEY_ODDS = 10; +constexpr int LEECH_HEAL = 1; +constexpr float LEECH_HEART_RISE = -24; +constexpr int GUPPYS_HAIRBALL_SIZES = 4; +constexpr int BLOOD_PUPPY_BOSS_COINS = 4; + +// Bone Spurs' spurs: two from a sturdy enemy half the time, thrown out at five, the second at three to five. +constexpr std::array BONE_SPURS_SHIFTS = {6, 17, 9}; +constexpr float BONE_SPURS_HEALTH = 8; +constexpr float BONE_SPUR_SPEED = 5; +constexpr float BONE_SPUR_SPEED_MIN = 3; +constexpr float BONE_SPUR_LEAD = 0.25f; +constexpr int BONE_PARTICLE_VARIANT = 35; +constexpr int BONE_SPUR_PARTICLES = 8; +constexpr float BONE_PARTICLE_SPEED = 2; +constexpr float BONE_PARTICLE_SPEED_RANGE = 3; +constexpr float BONE_BREAK_VOLUME = 0.7f; +constexpr float BONE_BREAK_PITCH_RANGE = 0.2f; + +// Cantripped: one kill in five drops a card. +constexpr uint32_t CANTRIPPED_ODDS = 5; +constexpr float CANTRIPPED_CARD_SPEED = 3; + +// Tainted Magdalene's (or a Yum Heart blessing's) half hearts and Tainted Keeper's coins: thrown at two to five, gone +// in two seconds, three for a boss's coins. A champion gives two coins, a boss more by its health and the floor, a room +// coming back fewer (one, ever less likely, up to ten). +constexpr std::array MAGDALENE_HEART_SHIFTS = {7, 17, 21}; +constexpr std::array KEEPER_COIN_SHIFTS = {9, 11, 19}; +constexpr std::array KEEPER_REVISIT_SHIFTS = {13, 5, 19}; +constexpr int NULL_ITEM_TEMPORARY_HEARTS = 114; +constexpr float DROP_SPEED_MIN = 2; +constexpr float DROP_SPEED_RANGE = 3; +constexpr int DROP_TIMEOUT = 60; +constexpr int BOSS_COIN_TIMEOUT = 90; +constexpr int KEEPER_ROOM_COINS = 8; +constexpr int KEEPER_REVISIT_LIMIT = 9; +constexpr float KEEPER_BOSS_HEALTH_BASE = 38; +constexpr float KEEPER_BOSS_HEALTH_STEP = 10; + +// The floor a boss's coins count by: one more on an alt floor. +static int reward_stage_get() +{ + Game& game = *g_game; + bool isAlt = game.stageType == STAGETYPE_REPENTANCE || game.stageType == STAGETYPE_REPENTANCE_B; + return (int)game.stage + (isAlt ? 1 : 0); +} + +// A pickup thrown out of the dead enemy in a random direction at two to five, gone after a while. +static void reward_pickup_throw(Entity_NPC& npc, const EntitySpawn& spawn, int timeout) +{ + float angle = random_unit() * RANDOM_HALF_TURN; + angle += angle; + float sine = std::sin(angle); + float speed = random_unit() * DROP_SPEED_RANGE + DROP_SPEED_MIN; + EntitySpawn thrown = spawn; + thrown.position = npc.pos; + thrown.velocity = vector_make(std::cos(angle) * speed, sine * speed); + thrown.spawner = &npc; + thrown.type = ENTITY_PICKUP; + auto* pickup = static_cast(g_game->Spawn(thrown)); + pickup->timeout = timeout; + pickup->Update(); +} + +// Whether a kill came from a familiar of a variant (or an effect, for Hungry Soul's soul). +static bool is_killed_by(Entity_NPC& npc, int type, int variant) +{ + return std::ranges::any_of(npc.killDamageEvents, [&](const DamageEvent& event) + { return event.source.type == type && event.source.variant == variant; }); +} + +// What the damage flags of the killing hit drop: a red heart, a coin, a black heart, a card or a rune. +static void kill_flag_drops(Entity_NPC& npc) +{ + uint64_t flags = npc.killDamageFlags; + auto drop = [&](int variant, int subType) + { + g_game->Spawn( + {.position = npc.pos, .subType = subType, .type = ENTITY_PICKUP, .variant = variant, .seed = Random()}); + }; + if (flags & DAMAGE_SPAWN_RED_HEART) drop(PICKUP_HEART, HEART_FULL); + if (flags & DAMAGE_SPAWN_COIN) drop(PICKUP_COIN, 0); + if (flags & DAMAGE_SPAWN_BLACK_HEART) drop(PICKUP_HEART, HEART_BLACK); + if (flags & DAMAGE_SPAWN_CARD) drop(PICKUP_TAROTCARD, ItemPool::GetCardEx((int)npc.dropRNG.Next(), 0, 0, 0, false)); + if (flags & DAMAGE_SPAWN_RUNE) + drop(PICKUP_TAROTCARD, ItemPool::GetCardEx((int)npc.dropRNG.Next(), 0, -1, 0, false)); +} + +// What the killing hits' sources do: a Leech heals its player, a Blood Puppy grows, Guppy's Hairball grows, and one +// Sharp Key kill in ten opens a chest at once. +static void kill_source_rewards(Entity_NPC& npc) +{ + for (const DamageEvent& event : npc.killDamageEvents) + { + Entity* source = event.source.entity; + if (event.source.type == ENTITY_FAMILIAR && source && source->type == ENTITY_FAMILIAR) + { + auto& familiar = static_cast(*source); + if (event.source.variant == Entity_Familiar::LEECH) + { + Entity_Player* player = familiar.player; + if (g_game->deathmatchManager.is_active() || !player || player->isDead) continue; + player->AddHearts(LEECH_HEAL, false, false); + Entity* heart = g_game->Spawn( + {.position = player->pos, .type = ENTITY_EFFECT, .variant = EFFECT_HEART, .seed = Random()}); + heart->sprite.offset = vector_make(0, LEECH_HEART_RISE); + heart->renderDepthOffset = 1; + } + else if (event.source.variant == Entity_Familiar::BLOOD_PUPPY) + familiar.AddCoins(npc.IsBoss() ? BLOOD_PUPPY_BOSS_COINS : 1); + else if (event.source.variant == Entity_Familiar::GUPPYS_HAIRBALL) + familiar.subtype = std::min(familiar.subtype + 1, GUPPYS_HAIRBALL_SIZES); + continue; + } + if (event.source.type == ENTITY_BLOOD_PUPPY) + reconstruction_missing("Entity_NPC::trigger_death_rewards 006bbdc0: a Blood Puppy's feeding"); + + bool isSharpKey = event.source.type == ENTITY_TEAR && + (event.source.variant == TEAR_SHARP_KEY || event.source.variant == TEAR_SHARP_KEY_SPECTRAL); + if (!isSharpKey) continue; + RNG rng = {npc.initSeed, SHARP_KEY_SHIFTS[0], SHARP_KEY_SHIFTS[1], SHARP_KEY_SHIFTS[2]}; + rng.Next(); + rng.Next(); + if (rng.Next() % SHARP_KEY_ODDS != 0 || !source) continue; + + Entity* spawner = source->spawnerEntity; + Entity_Player* player = spawner && spawner->type == ENTITY_PLAYER ? spawner->ToPlayer() : nullptr; + auto* chest = static_cast( + g_game->Spawn({.position = npc.pos, .type = ENTITY_PICKUP, .variant = PICKUP_CHEST, .seed = rng.Next()})); + chest->TryOpenChest(player); + if (Entity_Pickup::IsChest(chest->variant)) chest->Remove(); + } +} + +// Bone Spurs' spurs fly out of a kill not made by a spur, with a burst of bone and a crack. +static void bone_spurs_spawn(Entity_NPC& npc, Entity_Player& owner) +{ + int count = 1; + if (npc.maxHitPoints > BONE_SPURS_HEALTH) + { + RNG rng = {npc.initSeed, BONE_SPURS_SHIFTS[0], BONE_SPURS_SHIFTS[1], BONE_SPURS_SHIFTS[2]}; + if ((rng.Next() & 1) == 0) count = 2; + } + for (int i = 0; i < count; i++) + { + float angle = random_unit() * RANDOM_HALF_TURN; + angle += angle; + float sine = std::sin(angle); + float push = random_unit() + 1; + Vector velocity = vector_make(std::cos(angle) * push + npc.velocity.x, push * sine + npc.velocity.y); + float speed = i == 0 ? BONE_SPUR_SPEED : random_unit() * 2 + BONE_SPUR_SPEED_MIN; + velocity = vector_resized(velocity, speed); + Entity* spur = g_game->Spawn({.position = vector_add(vector_scale(velocity, BONE_SPUR_LEAD), npc.pos), + .velocity = velocity, + .spawner = &owner, + .type = ENTITY_FAMILIAR, + .variant = Entity_Familiar::BONE_SPUR, + .seed = Random()}); + spur->ClearEntityFlags(FLAG_APPEAR); + spur->Update(); + } + game_particles_spawn({.position = npc.pos, + .height = npc.posOffset.y, + .speed = random_unit() * BONE_PARTICLE_SPEED_RANGE + BONE_PARTICLE_SPEED, + .count = BONE_SPUR_PARTICLES, + .variant = BONE_PARTICLE_VARIANT}); + npc_sound_play(SOUND_BONE_SNAP, BONE_BREAK_VOLUME, 2, random_unit() * BONE_BREAK_PITCH_RANGE + 1); +} + +// What the players' items and the run do with any kill: Gimpy's half hearts, the killing hit's drops and sources, +// Infestation 2's spider, Bone Spurs' spurs, Hungry Soul's soul, Cricket's Leg and Cantripped's cards. +static void kill_item_rewards(Entity_NPC& npc) +{ + PlayerManager& players = g_game->playerManager; + bool isChampionReward = npc.killDamageFlags & DAMAGE_CHAMPION_REWARD; + uint32_t gimpyOdds = npc.maxHitPoints < GIMPY_WEAK_HEALTH ? GIMPY_WEAK_ODDS + : npc.maxHitPoints < GIMPY_STRONG_HEALTH ? GIMPY_ODDS + : GIMPY_STRONG_ODDS; + if (isChampionReward) gimpyOdds /= 2; + bool isGimpyHeart = + players.FirstCollectibleOwner(COLLECTIBLE_GIMPY, LAZARUS_SHARE_CHECK) && + npc.dropRNG.RandomInt(gimpyOdds) == 0 && + (!players.AnyoneHasTrinket(TRINKET_DAEMONS_TAIL) || npc.dropRNG.RandomInt(GIMPY_DAEMONS_TAIL_ODDS) == 0); + if (isGimpyHeart) + g_game->Spawn({.position = npc.pos, + .subType = HEART_HALF, + .type = ENTITY_PICKUP, + .variant = PICKUP_HEART, + .seed = Random()}); + kill_flag_drops(npc); + kill_source_rewards(npc); + + if (players.RandomCollectibleOwner(COLLECTIBLE_INFESTATION_2, npc.initSeed, nullptr) && + !is_killed_by(npc, ENTITY_FAMILIAR, Entity_Familiar::BLUE_SPIDER)) + reconstruction_missing( + "Entity_NPC::trigger_death_rewards 006bbdc0: Infestation 2 (spawn_blue_spider 00638e30)"); + Entity_Player* spurs = players.RandomCollectibleOwner(COLLECTIBLE_BONE_SPURS, npc.initSeed, nullptr); + if (spurs && !is_killed_by(npc, ENTITY_FAMILIAR, Entity_Familiar::BONE_SPUR)) bone_spurs_spawn(npc, *spurs); + if (players.RandomCollectibleOwner(COLLECTIBLE_HUNGRY_SOUL, npc.initSeed, nullptr) && + !is_killed_by(npc, ENTITY_EFFECT, EFFECT_HUNGRY_SOUL)) + reconstruction_missing("Entity_NPC::trigger_death_rewards 006bbdc0: Hungry Soul's soul"); + if (players.RandomTrinketOwner(TRINKET_CRICKET_LEG, npc.initSeed, nullptr)) + reconstruction_missing("Entity_NPC::trigger_death_rewards 006bbdc0: Cricket's Leg (SpawnTrinketRandomPickup)"); + + if (g_game->challenge == CHALLENGE_CANTRIPPED && npc.dropRNG.Next() % CANTRIPPED_ODDS == 0) + { + uint32_t seed = Random(); + float angle = random_unit() * RANDOM_HALF_TURN; + angle += angle; + Vector direction = + vector_make(std::cos(angle) * CANTRIPPED_CARD_SPEED, std::sin(angle) * CANTRIPPED_CARD_SPEED); + g_game->Spawn({.position = npc.pos, + .velocity = vector_scale(direction, random_unit()), + .subType = 1, + .type = ENTITY_PICKUP, + .variant = PICKUP_TAROTCARD, + .seed = seed}); + } +} + +// Tainted Magdalene's (or a Yum Heart blessing's) half hearts: one kill in two, or every kill with the blessing or the +// killing hit's temporary heart flag. +static void magdalene_hearts_drop(Entity_NPC& npc) +{ + PlayerManager& players = g_game->playerManager; + bool isBlessed = players.HasTemporaryEffect(g_manager->itemConfig.GetNullItem(NULL_ITEM_TEMPORARY_HEARTS)); + bool isMagdalene = std::ranges::any_of(players.playerList, + [](Entity_Player* player) + { + return player->variant == PLAYER_VARIANT_PLAYER && + !player->isCoopGhost && player->playerType == PLAYER_MAGDALENE_B; + }); + if (!isMagdalene && !isBlessed) return; + + RNG rng = {npc.initSeed, MAGDALENE_HEART_SHIFTS[0], MAGDALENE_HEART_SHIFTS[1], MAGDALENE_HEART_SHIFTS[2]}; + bool isDropped = (rng.Next() & 1) == 0 || (npc.killDamageFlags & DAMAGE_SPAWN_TEMP_HEART) || isBlessed; + if (isDropped) + reward_pickup_throw(npc, {.subType = HEART_HALF, .variant = PICKUP_HEART, .seed = rng.Next()}, DROP_TIMEOUT); +} + +// Tainted Keeper's coins: one from an enemy, two from a champion and more from a boss by its health, up to eight in a +// room's first visit or ambush, else one at most and ever less often (ten per room). A champion's reward adds some. +static void keeper_coins_drop(Entity_NPC& npc) +{ + PlayerManager& players = g_game->playerManager; + bool isKeeper = std::ranges::any_of(players.playerList, + [](Entity_Player* player) + { + return player->variant == PLAYER_VARIANT_PLAYER && !player->isCoopGhost && + player->playerType == PLAYER_KEEPER_B; + }); + if (!isKeeper) return; + + RoomDescriptor& room = *g_game->room->descriptor; + int limit = KEEPER_ROOM_COINS; + if (npc.spawnGridIndex < 0 || (room.visitedCount != 1 && !npc.HasEntityFlags(FLAG_AMBUSH))) + { + if (room.tKeeperCoinSpawns > KEEPER_REVISIT_LIMIT) return; + RNG revisit = {npc.initSeed, KEEPER_REVISIT_SHIFTS[0], KEEPER_REVISIT_SHIFTS[1], KEEPER_REVISIT_SHIFTS[2]}; + uint32_t odds = (uint32_t)room.tKeeperCoinSpawns + 1; + if (revisit.Next() % odds != 0) return; + room.tKeeperCoinSpawns++; + limit = 1; + } + + int timeout = DROP_TIMEOUT; + int count = npc.championColorIdx >= 0 ? 2 : 1; + if (npc.IsBoss()) + { + float health = (float)reward_stage_get() * KEEPER_BOSS_HEALTH_STEP + KEEPER_BOSS_HEALTH_BASE; + count = std::max(1, (int)std::ceil(npc.maxHitPoints / health)); + timeout = BOSS_COIN_TIMEOUT; + } + count = std::min(count, limit); + + RNG rng = {npc.initSeed, KEEPER_COIN_SHIFTS[0], KEEPER_COIN_SHIFTS[1], KEEPER_COIN_SHIFTS[2]}; + if (npc.killDamageFlags & DAMAGE_CHAMPION_REWARD) count += (int)(rng.Next() % (uint32_t)(count / 2 + 2)); + for (int i = 0; i < count; i++) reward_pickup_throw(npc, {.variant = PICKUP_COIN, .seed = rng.Next()}, timeout); +} + +// 006bbdc0 The rewards a dead enemy gives its killers: the damage flags' and items' drops and on-kill effects, +// Vasculitis's tears, then +// for an enemy that holds the doors Vade Retro's souls, Quints' familiars, Tainted Magdalene's hearts, Tainted +// Keeper's coins and the Urn of Souls' souls. +void Entity_NPC::trigger_death_rewards() +{ + bool isVersusPlayer = g_game->deathmatchManager.is_active() && type == ENTITY_PLAYER; + bool isRewarded = Entity::is_enemy_type(type) && type != ENTITY_FIREPLACE && type != ENTITY_SHOPKEEPER && + type != ENTITY_MOVABLE_TNT && !(type == ENTITY_CULTIST && variant == CULTIST_BLOOD_VARIANT) && + type != ENTITY_GENERIC_PROP && type != ENTITY_MINECART && type != ENTITY_POOP; + if (!isRewarded && !isVersusPlayer) return; + if (DoesEntityShareStatus() && parent && GetLastParent() != this && type != ENTITY_LARRYJR && + type != ENTITY_BUTTLICKER) + return; + + if (!HasEntityFlags(FLAG_NO_REWARD)) kill_item_rewards(*this); + if (g_game->playerManager.FirstCollectibleOwner(COLLECTIBLE_VASCULITIS, LAZARUS_SHARE_CHECK)) + reconstruction_missing("Entity_NPC::trigger_death_rewards 006bbdc0: Vasculitis's tears"); + if (!CanShutDoors()) return; + + Room& room = *g_game->room; + if (room.isExorcistActive && room.IsPositionInRoom(pos, EXORCIST_ROOM_MARGIN)) + reconstruction_missing("Entity_NPC::trigger_death_rewards 006bbdc0: Vade Retro's souls"); + if (room.IsPositionInRoom(pos, EXORCIST_ROOM_MARGIN)) + for (Entity_Player* player : g_game->playerManager.playerList) + if (player->variant == PLAYER_VARIANT_PLAYER && player->HasCollectible(COLLECTIBLE_QUINTS)) + reconstruction_missing("Entity_NPC::trigger_death_rewards 006bbdc0: Quints' familiars"); + magdalene_hearts_drop(*this); + keeper_coins_drop(*this); + for (Entity_Player* player : g_game->playerManager.playerList) + if (player->variant == PLAYER_VARIANT_PLAYER && player->HasCollectible(COLLECTIBLE_URN_OF_SOULS)) + reconstruction_missing("Entity_NPC::trigger_death_rewards 006bbdc0: the Urn of Souls' souls"); +} diff --git a/src/entity_pickup.cpp b/src/entity_pickup.cpp index be44d82..f994c91 100644 --- a/src/entity_pickup.cpp +++ b/src/entity_pickup.cpp @@ -28,25 +28,7 @@ constexpr std::array CHESTS = {PICKUP_CHEST, PICKUP_LOCKEDCHEST, // The coins a coin subtype is worth (penny, nickel, dime, double, lucky, sticky, golden), from subtype 1. constexpr std::array COIN_VALUES = {1, 1, 5, 10, 2, 1, 5, 1}; -// The pickup subtypes the code tells apart, as Lua's HeartSubType, CoinSubType, KeySubType and BombSubType name them. -// HeartKind (entity_player.h) holds the soul, black, golden, bone and rotten hearts. -enum HeartSubType : int -{ - HEART_FULL = 1, - HEART_HALF = 2, - HEART_ETERNAL = 4, - HEART_DOUBLEPACK = 5, - HEART_HALF_SOUL = 8, - HEART_SCARED = 9, - HEART_BLENDED = 10 -}; -enum KeySubType : int -{ - KEY_NORMAL = 1, - KEY_GOLDEN, - KEY_DOUBLEPACK, - KEY_CHARGED -}; +// A bomb's subtypes the code tells apart, as Lua's BombSubType names them. enum BombSubType : int { BOMB_NORMAL = 1, @@ -76,7 +58,6 @@ constexpr int TRINKET_MOMS_PEARL = 38; constexpr int TRINKET_BLOODY_PENNY = 49; constexpr int TRINKET_FLAT_PENNY = 51; constexpr int TRINKET_SUPER_MAGNET = 68; -constexpr int TRINKET_ROTTEN_PENNY = 126; constexpr int TRINKET_BLESSED_PENNY = 131; constexpr int TRINKET_APPLE_OF_SODOM = 140; constexpr int TRINKET_CHARGED_PENNY = 147; @@ -106,7 +87,6 @@ constexpr int ACHIEVEMENT_GOLDEN_PENNY = 613; constexpr int ACHIEVEMENT_GOLDEN_BATTERY = 615; // The other entities and effects pickups spawn, meet and are saved with. -constexpr int ENTITY_POLTY = 816; constexpr int FAMILIAR_BUM_FRIEND = 24; constexpr int FAMILIAR_DARK_BUM = 64; constexpr int FAMILIAR_BUMBO = 88; @@ -130,9 +110,7 @@ constexpr int POOF02_LAVA_SPLASH = 66; constexpr int WISP_HEALED_BY_HEARTS = 296; // The sounds pickups play. -constexpr int SOUND_CHEST_DROP = 21; constexpr int SOUND_KEYPICKUP_GAUNTLET = 58; -constexpr int SOUND_KEY_DROP0 = 59; constexpr int SOUND_MEAT_FEET_SLOW0 = 68; constexpr int SOUND_DIMEDROP = 198; constexpr int SOUND_DIMEPICKUP = 199; @@ -143,7 +121,6 @@ constexpr int SOUND_NICKELDROP = 231; constexpr int SOUND_NICKELPICKUP = 232; constexpr int SOUND_PENNYDROP = 233; constexpr int SOUND_PENNYPICKUP = 234; -constexpr int SOUND_SUPERHOLY = 266; constexpr int SOUND_PING_PONG = 458; constexpr int SOUND_BONE_HEART = 461; constexpr int SOUND_SHOVEL_DROP = 463; @@ -1350,7 +1327,15 @@ bool Entity_Pickup::HandleCollision(Entity* collider, bool isLow) variant); bool isGreed = (collider->type == ENTITY_ULTRA_GREED || collider->type == ENTITY_BUMBINO) && variant == PICKUP_COIN; - if (isBum || isEater || isGreed) + if (isBum && bum_pickup_collect(*static_cast(collider), *this)) + { + RemoveOtherOptions(); + g_game->scoreSheet.add_pickup_points(variant, subtype, pos); + PlayPickupSound(); + collect_finish(nullptr); + return true; + } + if (isEater || isGreed) reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: a familiar or enemy collecting it"); return g_game->room->roomType == ROOM_DUNGEON || collider->type == ENTITY_BOMB || price != 0; } @@ -1472,7 +1457,7 @@ bool Entity_Pickup::HandleCollision(Entity* collider, bool isLow) // and the run's note that a heart, bomb or coin was picked up. void Entity_Pickup::collect_finish(Entity_Player* player) { - if (!player->proceduralItems.empty()) + if (player && !player->proceduralItems.empty()) reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: the procedural items' pickup trigger"); velocity = {}; diff --git a/src/entity_pickup.h b/src/entity_pickup.h index 43b54d7..8d23d4e 100644 --- a/src/entity_pickup.h +++ b/src/entity_pickup.h @@ -86,6 +86,26 @@ enum CoinSubType : int COIN_GOLDEN }; +// The heart and key subtypes the code tells apart, as Lua's HeartSubType and KeySubType name them. HeartKind +// (entity_player.h) holds the soul, black, golden, bone and rotten hearts. +enum HeartSubType : int +{ + HEART_FULL = 1, + HEART_HALF = 2, + HEART_ETERNAL = 4, + HEART_DOUBLEPACK = 5, + HEART_HALF_SOUL = 8, + HEART_SCARED = 9, + HEART_BLENDED = 10 +}; +enum KeySubType : int +{ + KEY_NORMAL = 1, + KEY_GOLDEN, + KEY_DOUBLEPACK, + KEY_CHARGED +}; + // The game state bit set once a heart, bomb or coin is picked, and Daemon's Tail's 1 in 5 heart chance. constexpr int GAME_STATE_HEART_BOMB_COIN_PICKED = 41; constexpr int DAEMONS_TAIL_ODDS = 5; diff --git a/src/entity_pickup_chest.cpp b/src/entity_pickup_chest.cpp index 61dfe6e..785e62c 100644 --- a/src/entity_pickup_chest.cpp +++ b/src/entity_pickup_chest.cpp @@ -1,4 +1,5 @@ #include "entity_pickup.h" +#include "entity_bomb.h" #include "entity_effect.h" #include "entity_npc.h" #include "entity_player.h" @@ -9,6 +10,8 @@ #include "manager.h" #include "npc_ai.h" #include "room.h" +#include "room_grid.h" +#include "room_transition.h" #include "sfx_manager.h" #include #include @@ -24,7 +27,6 @@ constexpr float LOOT_ANGLE_SCALE = 3.14f; constexpr std::array LOCKED_CHESTS = {PICKUP_LOCKEDCHEST, PICKUP_ETERNALCHEST, PICKUP_OLDCHEST}; constexpr std::array GOLDEN_CHESTS = {PICKUP_LOCKEDCHEST, PICKUP_BOMBCHEST, PICKUP_ETERNALCHEST, PICKUP_MEGACHEST}; -constexpr std::array UNWRITTEN_LOOT = {PICKUP_REDCHEST, PICKUP_MOMSCHEST, PICKUP_OLDCHEST, PICKUP_GRAB_BAG}; constexpr int EVENT_LOCKED_CHESTS_OPENED = 198; constexpr float CHEST_VANISH_VOLUME = 0.7f; constexpr float SPIKED_CHEST_DAMAGE = 1; @@ -129,11 +131,61 @@ struct ChestDraw std::array trinketRngs{}; std::array isTrinketProc{}; LootList loot; + RNG daemonsTailRng{}; RNG* rng = nullptr; + Entity_Player* player = nullptr; uint32_t poolFlags = 0; bool isDaemonsTail = false; + bool isPokerChip = false; + bool isPokerDouble = false; }; +// The outcomes of an old chest, a red chest and a sack. A sack's outcome is its pickup's subtype and variant. +enum OldChestOutcome +{ + OLD_OUTCOME_SOUL_HEARTS, + OLD_OUTCOME_TRINKETS, + OLD_OUTCOME_ITEM, + OLD_OUTCOME_ANGEL_ITEM +}; +enum RedChestOutcome +{ + RED_OUTCOME_ITEM, + RED_OUTCOME_TELEPORT, + RED_OUTCOME_SPIDERS, + RED_OUTCOME_TROLL_BOMB, + RED_OUTCOME_FLIES, + RED_OUTCOME_BLUE_SPIDERS, + RED_OUTCOME_SOUL_HEARTS, + RED_OUTCOME_BOMBS, + RED_OUTCOME_PILLS +}; +constexpr int SACK_OUTCOME_SHIFT = 16; +constexpr int SACK_OUTCOME_MASK = 0xffff; +constexpr int SACK_BLACK = 2; +constexpr int SACK_BLACK_HEART = HEART_BLACK << SACK_OUTCOME_SHIFT | PICKUP_HEART; +constexpr int SACK_BONE_HEART = HEART_BONE << SACK_OUTCOME_SHIFT | PICKUP_HEART; + +// What an old, red or Mom's chest gives beyond its outcomes: three trinkets, Left Hand's extra pickup (from two +// copies) or its spiders' ban (from three), the Red Key until Mom's chests' items are unlocked, the familiars and +// entities a red chest lets out, and the Poker Chip's banned item qualities. +constexpr int OLD_CHEST_TRINKETS = 3; +constexpr int OLD_CHEST_SOUL_HEARTS = 3; +constexpr int RED_CHEST_FAMILIARS = 3; +constexpr int LEFT_HAND_EXTRA = 2; +constexpr int LEFT_HAND_NO_SPIDERS = 3; +constexpr int ACHIEVEMENT_MOMS_CHEST_ITEMS = 415; +constexpr int FAMILIAR_BLUE_FLY = 43; +constexpr int FAMILIAR_BLUE_SPIDER = 73; +constexpr int RED_CHEST_TELEPORT = 1; +constexpr int RED_CHEST_BOMB_SUBTYPE = 3; +constexpr float RED_CHEST_SPIDER_STEP = 70; +constexpr float RED_CHEST_SPIDER_HEIGHT = -30; +constexpr uint32_t POKER_QUALITY_BANS = 0x1f0; +constexpr int POKER_TOP_QUALITY = 2; +constexpr std::array DAEMONS_TAIL_SHIFTS = {1, 5, 16}; +constexpr std::array POKER_CHIP_SHIFTS = {1, 21, 20}; + // Adds weight to an outcome, never below zero, or adds the outcome (inlined in the original). void WeightedOutcomePicker::AddOutcomeWeight(int id, int weight) { @@ -184,6 +236,31 @@ static void loot_item_add(ChestDraw& draw, int pool) draw.loot.entries.push_back({.subType = item, .type = ENTITY_PICKUP, .variant = PICKUP_COLLECTIBLE, .seed = seed}); } +// The Poker Chip's item (FUN_006ee640): a first draw (left in the pool) shows a quality, and the item drawn is of the +// next quality up (a quality 3 or 4 its own), the first when none is. +static void loot_poker_item_add(ChestDraw& draw, int pool, int fallbackPool) +{ + uint32_t seed = draw.rng->Next(); + ItemPool& itemPool = g_game->itemPool; + int first = + itemPool.GetCollectible((ItemPoolType)pool, draw.rng->Next(), draw.poolFlags | POOL_FLAG_NO_DECREASE, 0, 0); + int quality = g_manager->itemConfig.GetCollectible(first)->quality; + int target = quality > POKER_TOP_QUALITY ? quality : quality + 1; + uint32_t flags = ~(POOL_FLAG_BAN_QUALITY_0 << target) & (draw.poolFlags | POKER_QUALITY_BANS); + int item = itemPool.GetCollectible((ItemPoolType)pool, draw.rng->Next(), flags, 0, fallbackPool); + if (item == COLLECTIBLE_BREAKFAST) item = first; + draw.loot.entries.push_back({.subType = item, .type = ENTITY_PICKUP, .variant = PICKUP_COLLECTIBLE, .seed = seed}); +} + +// The Poker Chip doubles a chest's pickups, or half the time trades them for an attack fly. +static int poker_chip_count(ChestDraw& draw, int count) +{ + if (!draw.isPokerChip) return count; + if (draw.isPokerDouble && count != 0) return count * 2; + draw.loot.entries.push_back({.type = ENTITY_ATTACKFLY, .seed = draw.rng->Next()}); + return 0; +} + // Rolls each bonus trinket for the first player holding it (a Lazarus twin's own copy counts for globally shared // ones): one in five passes Child's Heart under Daemon's Tail, then one, two or three copies add their pickup a // third, two thirds or every time. @@ -240,16 +317,20 @@ static void chest_pickups_add(ChestDraw& draw, int count, bool isGilded) WeightedOutcomePicker picker; int heartWeight = draw.isDaemonsTail ? 4 : 20; if (isGilded) - picker.outcomes = {{CHEST_PICKUP_COINS, 25}, {CHEST_PICKUP_HEART, heartWeight}, {CHEST_PICKUP_KEY, 10}, - {CHEST_PICKUP_BOMB, 20}, {CHEST_PICKUP_PILL, 5}, {CHEST_PICKUP_CARD, 5}, - {CHEST_PICKUP_RUNE, 5}, {CHEST_PICKUP_TRINKET, 5}, {CHEST_PICKUP_BATTERY, 5}}; + picker.outcomes = {{CHEST_PICKUP_COINS, 25}, {CHEST_PICKUP_HEART, heartWeight}, + {CHEST_PICKUP_KEY, 10}, {CHEST_PICKUP_BOMB, 20}, + {CHEST_PICKUP_PILL, 5}, {CHEST_PICKUP_CARD, 5}, + {CHEST_PICKUP_RUNE, 5}, {CHEST_PICKUP_TRINKET, 5}, + {CHEST_PICKUP_BATTERY, 5}}; else - picker.outcomes = {{CHEST_PICKUP_COINS, 35}, {CHEST_PICKUP_HEART, heartWeight}, {CHEST_PICKUP_KEY, 15}, + picker.outcomes = {{CHEST_PICKUP_COINS, 35}, + {CHEST_PICKUP_HEART, heartWeight}, + {CHEST_PICKUP_KEY, 15}, {CHEST_PICKUP_BOMB, 30}}; - constexpr std::array PICKUP_VARIANTS = {PICKUP_COIN, PICKUP_HEART, PICKUP_KEY, - PICKUP_BOMB, PICKUP_PILL, PICKUP_TAROTCARD, - PICKUP_TAROTCARD, PICKUP_TRINKET, PICKUP_LIL_BATTERY}; + constexpr std::array PICKUP_VARIANTS = {PICKUP_COIN, PICKUP_HEART, PICKUP_KEY, + PICKUP_BOMB, PICKUP_PILL, PICKUP_TAROTCARD, + PICKUP_TAROTCARD, PICKUP_TRINKET, PICKUP_LIL_BATTERY}; for (; count > 0; count--) { int outcome = outcome_draw(picker, *draw.rng); @@ -325,14 +406,16 @@ static void chest_loot_draw(ChestDraw& draw, int variant) loot_add(draw, PICKUP_TAROTCARD); break; case CHEST_OUTCOME_ITEM: - loot_item_add(draw, POOL_GOLDEN_CHEST); + if (!draw.isPokerChip) loot_item_add(draw, POOL_GOLDEN_CHEST); + else loot_poker_item_add(draw, POOL_GOLDEN_CHEST, variant == PICKUP_ETERNALCHEST ? POOL_ANGEL : 0); break; default: { int roll = isGolden ? GOLDEN_PICKUP_COUNT_ROLL : PICKUP_COUNT_ROLL; int count = std::max(PICKUP_COUNT_MIN, (int)draw.rng->RandomInt(roll)); chest_trinket_pickup_add(draw, CHEST_TRINKET_PRECEDENCE.size()); - chest_pickups_add(draw, chest_pickup_count_grow(draw, count), outcome == CHEST_OUTCOME_GILDED_PICKUPS); + count = poker_chip_count(draw, chest_pickup_count_grow(draw, count)); + chest_pickups_add(draw, count, outcome == CHEST_OUTCOME_GILDED_PICKUPS); } } } @@ -351,23 +434,171 @@ static void wooden_chest_loot_draw(ChestDraw& draw) count++; chest_trinket_pickup_add(draw, WOODEN_CHEST_TRINKETS); if (g_game->playerManager.FirstCollectibleOwner(COLLECTIBLE_MOMS_KEY, LAZARUS_SHARE_CHECK)) count *= 2; + if (draw.isPokerChip && poker_chip_count(draw, count) == 0) return; + if (draw.isPokerChip) count *= 2; int outcome = outcome_draw(picker, *draw.rng); + if (outcome == WOODEN_OUTCOME_ITEM && draw.isPokerChip) return loot_poker_item_add(draw, POOL_WOODEN_CHEST, 0); if (outcome == WOODEN_OUTCOME_ITEM) return loot_item_add(draw, POOL_WOODEN_CHEST); for (; count > 0; count--) loot_add(draw, outcome == WOODEN_OUTCOME_CARDS ? PICKUP_TAROTCARD : PICKUP_PILL); } +// An old chest's loot: soul hearts, three trinkets, an old chest's item, or rarely an angel room's. +static void old_chest_loot_draw(ChestDraw& draw) +{ + WeightedOutcomePicker picker; + picker.outcomes = {{OLD_OUTCOME_SOUL_HEARTS, draw.isDaemonsTail ? 9 : 43}, + {OLD_OUTCOME_TRINKETS, 42}, + {OLD_OUTCOME_ITEM, 10}, + {OLD_OUTCOME_ANGEL_ITEM, 5}}; + switch (outcome_draw(picker, *draw.rng)) + { + case OLD_OUTCOME_SOUL_HEARTS: + for (int i = (int)draw.rng->RandomInt(OLD_CHEST_SOUL_HEARTS) + 1; i > 0; i--) + loot_add(draw, PICKUP_HEART, HEART_SOUL); + break; + case OLD_OUTCOME_TRINKETS: + for (int i = 0; i < OLD_CHEST_TRINKETS; i++) loot_add(draw, PICKUP_TRINKET); + break; + case OLD_OUTCOME_ITEM: + loot_item_add(draw, POOL_OLD_CHEST); + break; + case OLD_OUTCOME_ANGEL_ITEM: + loot_item_add(draw, POOL_ANGEL); + break; + } +} + +// Adds an entity that is no pickup to a chest's loot, seeded by the next draw. +static void loot_entity_add(ChestDraw& draw, int type, int variant) +{ + draw.loot.entries.push_back({.type = type, .variant = variant, .seed = draw.rng->Next()}); +} + +// A red chest's loot: a devil item on the Chest's first room, else a red chest's item, a teleport to the devil room +// (not from the devil room or Genesis), spiders (unless three Left Hands), a Mega Troll Bomb, blue flies or spiders, +// soul hearts, troll bombs or pills. Two Left Hands add a pill or a soul heart. +static void red_chest_loot_draw(ChestDraw& draw, bool isChestFloor) +{ + Game& game = *g_game; + if (isChestFloor && game.startingRoomIdx == game.currentRoomIdx) + { + uint32_t seed = draw.rng->Next(); + int item = game.itemPool.GetCollectible(POOL_DEVIL, draw.rng->Next(), + draw.poolFlags | POOL_FLAG_BAN_DEVIL_SACRIFICE, 0, 0); + draw.loot.entries.push_back( + {.subType = item, .type = ENTITY_PICKUP, .variant = PICKUP_COLLECTIBLE, .seed = seed}); + return; + } + + int leftHands = draw.player ? draw.player->GetTrinketMultiplier(TRINKET_LEFT_HAND) : 0; + WeightedOutcomePicker picker; + picker.outcomes = {{RED_OUTCOME_ITEM, 10}}; + if (game.currentRoomIdx != ROOM_DEVIL_IDX && game.currentRoomIdx != ROOM_GENESIS_IDX) + picker.AddOutcomeWeight(RED_OUTCOME_TELEPORT, 5); + if (!draw.player || leftHands < LEFT_HAND_NO_SPIDERS) picker.AddOutcomeWeight(RED_OUTCOME_SPIDERS, 13); + picker.AddOutcomeWeight(RED_OUTCOME_TROLL_BOMB, 13); + picker.AddOutcomeWeight(RED_OUTCOME_FLIES, 7); + picker.AddOutcomeWeight(RED_OUTCOME_BLUE_SPIDERS, 7); + picker.AddOutcomeWeight(RED_OUTCOME_SOUL_HEARTS, draw.isDaemonsTail ? 3 : 15); + picker.AddOutcomeWeight(RED_OUTCOME_BOMBS, 15); + picker.AddOutcomeWeight(RED_OUTCOME_PILLS, 15); + + int outcome = outcome_draw(picker, *draw.rng); + switch (outcome) + { + case RED_OUTCOME_ITEM: + loot_item_add(draw, POOL_RED_CHEST); + break; + case RED_OUTCOME_TELEPORT: + draw.loot.entries.push_back({.variant = RED_CHEST_TELEPORT}); + break; + case RED_OUTCOME_SPIDERS: + loot_entity_add(draw, ENTITY_SPIDER, 0); + loot_entity_add(draw, ENTITY_SPIDER, 0); + break; + case RED_OUTCOME_TROLL_BOMB: + loot_entity_add(draw, ENTITY_BOMB, BOMB_SUPERTROLL); + break; + case RED_OUTCOME_FLIES: + case RED_OUTCOME_BLUE_SPIDERS: + for (int i = 0; i < RED_CHEST_FAMILIARS; i++) + loot_entity_add(draw, ENTITY_FAMILIAR, + outcome == RED_OUTCOME_FLIES ? FAMILIAR_BLUE_FLY : FAMILIAR_BLUE_SPIDER); + break; + case RED_OUTCOME_SOUL_HEARTS: + { + loot_add(draw, PICKUP_HEART, HEART_SOUL); + bool isSecond = draw.rng->RandomInt(2) == 0 && + (!draw.isDaemonsTail || draw.daemonsTailRng.RandomInt(DAEMONS_TAIL_ODDS) == 0); + if (isSecond) loot_add(draw, PICKUP_HEART, HEART_SOUL); + break; + } + case RED_OUTCOME_BOMBS: + loot_add(draw, PICKUP_BOMB, RED_CHEST_BOMB_SUBTYPE); + loot_add(draw, PICKUP_BOMB, RED_CHEST_BOMB_SUBTYPE); + break; + case RED_OUTCOME_PILLS: + loot_add(draw, PICKUP_PILL); + loot_add(draw, PICKUP_PILL); + break; + } + + if (!draw.player || leftHands < LEFT_HAND_EXTRA) return; + bool isPill = (draw.rng->Next() & 1) == 0; + loot_add(draw, isPill ? PICKUP_PILL : PICKUP_HEART, HEART_SOUL); +} + +// A sack's loot: two or three pickups, bombs, keys, coins, batteries or cards, or from a black sack bombs, pills and a +// black or bone heart (one heart at most). +static void sack_loot_draw(ChestDraw& draw, int subtype) +{ + WeightedOutcomePicker picker; + if (subtype == SACK_BLACK) + picker.outcomes = {{PICKUP_BOMB, 15}, {SACK_BLACK_HEART, 10}, {SACK_BONE_HEART, 5}, {PICKUP_PILL, 15}}; + else + picker.outcomes = { + {PICKUP_BOMB, 15}, {PICKUP_KEY, 20}, {PICKUP_COIN, 15}, {PICKUP_LIL_BATTERY, 4}, {PICKUP_TAROTCARD, 4}}; + + for (int count = (int)draw.rng->RandomInt(2) + 2; count > 0; count--) + { + int outcome = outcome_draw(picker, *draw.rng); + int variant = outcome & SACK_OUTCOME_MASK; + draw.rng->Next(); + loot_add(draw, variant, outcome >> SACK_OUTCOME_SHIFT); + if (subtype != SACK_BLACK || variant != PICKUP_HEART) continue; + picker.AddOutcomeWeight(SACK_BLACK_HEART, -10); + picker.AddOutcomeWeight(SACK_BONE_HEART, -5); + } +} + +// Mom's chest's loot: a Mom's chest item, the Red Key until those are unlocked (outside a daily or debug run). +static void moms_chest_loot_draw(ChestDraw& draw) +{ + bool isLocked = !g_manager->persistentGameData.achievements[ACHIEVEMENT_MOMS_CHEST_ITEMS] && + (g_manager->state != MANAGER_STATE_GAME || (g_game->dailyChallenge._id == 0 && !g_game->isDebug)); + if (!isLocked) return loot_item_add(draw, POOL_MOMS_CHEST); + + uint32_t seed = draw.rng->Next(); + draw.loot.entries.push_back( + {.subType = COLLECTIBLE_RED_KEY, .type = ENTITY_PICKUP, .variant = PICKUP_COLLECTIBLE, .seed = seed}); +} + // 006dae40 What the chest gives, drawn from its RNG, or from a copy with POOL_DRAW_PEEK, which also leaves the items // in their pools. An eternal chest gives nothing a quarter of the time (and stays). Ace of Spades, Safety Cap, // Match Stick, Child's Heart and Rusted Key may add their pickups, and in the Chest every chest gives a treasure item. -// Red, old and Mom's chests, sacks and Poker Chip stop the game until reached. +// Old chests give hearts, trinkets or items, red chests also teleports and enemies, Mom's chests their item, sacks +// pickups, and the Poker Chip doubles a chest's pickups or trades them for an attack fly, and raises its items' +// quality. LootList Entity_Pickup::GetChestLoot(PoolDraw draw, Entity_Player* player) { ChestDraw chest; RNG peek = dropRNG; chest.rng = draw == POOL_DRAW_TAKE ? &dropRNG : &peek; + chest.player = player; chest.poolFlags = draw == POOL_DRAW_TAKE ? 0 : POOL_FLAG_NO_DECREASE; chest.isDaemonsTail = g_game->playerManager.AnyoneHasTrinket(TRINKET_DAEMONS_TAIL); + chest.daemonsTailRng = {dropRNG._seed, DAEMONS_TAIL_SHIFTS[0], DAEMONS_TAIL_SHIFTS[1], DAEMONS_TAIL_SHIFTS[2]}; for (size_t index = 0; index < CHEST_TRINKETS.size(); index++) chest.trinketRngs[index].SetSeed(dropRNG._seed, CHEST_TRINKETS[index].shiftIndex); @@ -380,11 +611,18 @@ LootList Entity_Pickup::GetChestLoot(PoolDraw draw, Entity_Player* player) bool isChestFloor = !game.IsGreedMode() && game.stage == STAGE_DARK_ROOM && !isDeathmatch; bool isPokerChip = isDeathmatch ? player && player->HasTrinket(TRINKET_POKER_CHIP) : game.playerManager.AnyoneHasTrinket(TRINKET_POKER_CHIP); - if (isPokerChip) reconstruction_missing("Entity_Pickup::GetChestLoot 006dae40 (Poker Chip)"); - if (std::ranges::count(UNWRITTEN_LOOT, variant) > 0) - reconstruction_missing("Entity_Pickup::GetChestLoot 006dae40 (red, old and Mom's chests and sacks)"); + if (isPokerChip) + { + RNG poker = {chest.rng->_seed, POKER_CHIP_SHIFTS[0], POKER_CHIP_SHIFTS[1], POKER_CHIP_SHIFTS[2]}; + chest.isPokerChip = true; + chest.isPokerDouble = (poker.Next() & 1) == 0; + } if (variant == PICKUP_WOODENCHEST) wooden_chest_loot_draw(chest); + else if (variant == PICKUP_REDCHEST) red_chest_loot_draw(chest, isChestFloor); + else if (variant == PICKUP_MOMSCHEST) moms_chest_loot_draw(chest); + else if (variant == PICKUP_OLDCHEST) old_chest_loot_draw(chest); + else if (variant == PICKUP_GRAB_BAG) sack_loot_draw(chest, subtype); else if (!isChestFloor) chest_loot_draw(chest, variant); else { @@ -451,6 +689,40 @@ bool Entity_Pickup::TryOpenChest(Entity_Player* player) return true; } +// What a red chest lets out that is no ordinary spawn: a teleport to the devil room, spiders (the first thrown halfway +// to the player), blue flies and blue spiders. Whether the entry was spawned here. +static bool red_chest_entry_spawn(Entity_Pickup& chest, const LootEntry& entry, Entity_Player& player, bool isFirst) +{ + if (entry.type == 0 && entry.variant == RED_CHEST_TELEPORT) + { + Game& game = *g_game; + game.InitializeDevilAngelRoom(false, false); + game.leaveDoor = -1; + game.StartRoomTransition({.player = &player, .animation = TRANSITION_TELEPORT, .roomIndex = ROOM_DEVIL_IDX}); + return true; + } + if (entry.type == ENTITY_SPIDER) + { + Vector target{}; + if (isFirst) + { + // The player's NPC target fields (0x144c, 0x1450) are not known yet and taken as empty. + Entity* aim = player.darkArtsLastSnare ? player.darkArtsLastSnare->GetLastParent() : &player; + Vector halfway = vector_scale(vector_add(aim->pos, chest.pos), 0.5f); + target = room_free_pickup_position_find({.position = halfway, .step = RED_CHEST_SPIDER_STEP}); + } + Entity_NPC::ThrowSpider(chest.pos, &chest, target, false, RED_CHEST_SPIDER_HEIGHT); + return true; + } + if (entry.type != ENTITY_FAMILIAR) return false; + + if (entry.variant == FAMILIAR_BLUE_FLY) player.AddBlueFlies(1, chest.pos, nullptr); + else if (entry.variant == FAMILIAR_BLUE_SPIDER) + reconstruction_missing( + "Entity_Pickup::TryOpenChest 006e6e40: a red chest's blue spiders (spawn_blue_spider 00638e30)"); + return true; +} + // Spawns what a chest gives: the first item turns the chest into its pedestal (a pay to play look for those) and // more stand beside it, pickups and enemies fly out from a spot beside the chest (a Mega Chest's slower at first), // enemies placed towards the player, and chests come out smaller. Red chests' spiders, flies and teleports stop the @@ -468,8 +740,10 @@ void Entity_Pickup::chest_loot_spawn(const LootList& loot, Entity_Player& player { Entity_Pickup* item = this; if (variant == PICKUP_COLLECTIBLE) - item = static_cast(g_game->Spawn({.position = pos, .subType = entry.subType, - .type = ENTITY_PICKUP, .variant = PICKUP_COLLECTIBLE, + item = static_cast(g_game->Spawn({.position = pos, + .subType = entry.subType, + .type = ENTITY_PICKUP, + .variant = PICKUP_COLLECTIBLE, .seed = entry.seed})); else Morph(ENTITY_PICKUP, PICKUP_COLLECTIBLE, entry.subType, false, false, false); if (item->variant == PICKUP_COLLECTIBLE) @@ -482,8 +756,8 @@ void Entity_Pickup::chest_loot_spawn(const LootList& loot, Entity_Player& player isPushing = true; continue; } - if (entry.type != ENTITY_PICKUP) - reconstruction_missing("Entity_Pickup::TryOpenChest 006e6e40 (a red chest's spiders, flies or teleport)"); + if (entry.type != ENTITY_PICKUP && red_chest_entry_spawn(*this, entry, player, &entry == &loot.entries.front())) + continue; float speed = variant == PICKUP_MEGACHEST ? std::min(1.0f, (float)spawned * MEGA_CHEST_SPEED_STEP + MEGA_CHEST_SPEED_BASE) diff --git a/src/entity_player.cpp b/src/entity_player.cpp index 323bfa8..22d0efc 100644 --- a/src/entity_player.cpp +++ b/src/entity_player.cpp @@ -3,6 +3,7 @@ #include "entity_effect.h" #include "entity_familiar.h" #include "entity_npc.h" +#include "entity_slot.h" #include "game.h" #include "log.h" #include "lua_engine.h" @@ -32,8 +33,6 @@ constexpr float GREED_START_SPOT_Y = 280; constexpr float BACKASSWARDS_START_OFFSET_Y = 100; constexpr int BETHANY_START_CHARGE = 4; constexpr int MAGDALENE_B_START_RED_HEARTS = 4; -constexpr int PLAYERFORM_BOOK_WORM = 10; -constexpr int PLAYERFORM_NECROMANCER = 15; constexpr float EDEN_SPEED_SPREAD = 0.3f; constexpr float EDEN_FIRE_DELAY_SPREAD = 1.5f; constexpr float EDEN_RANGE_SPREAD = 120; @@ -110,12 +109,6 @@ static int card_roll(uint32_t seed, int runeChance, bool isPlaying) return lua_engine_get().GetCard({.rng = &rng, .card = card, .isPlaying = isPlaying, .isRunes = isPlaying}); } -// Room methods the room's takeover has not declared yet. -static Vector room_random_pickup_position() -{ - reconstruction_missing("Room::get_random_pickup_position 00813460"); -} - // A generator with a seed and the shift triple at an index of RNG's table. RNG rng_make(uint32_t seed, uint32_t shiftIndex) { @@ -616,7 +609,7 @@ void Entity_Player::InitPreLevelInitStats() } break; case PLAYER_BETHANY: - if (HasCollectible(COLLECTIBLE_BOOK_OF_VIRTUES)) IncrementPlayerFormCounter(PLAYERFORM_BOOK_WORM, 1); + if (HasCollectible(COLLECTIBLE_BOOK_OF_VIRTUES)) IncrementPlayerFormCounter(PLAYER_FORM_BOOKWORM, 1); break; case PLAYER_BETHANY_B: AddBloodCharge(redHearts); @@ -1103,7 +1096,7 @@ void Entity_Player::floor_items_recharge() } else if (active.item == COLLECTIBLE_ERASER) AddActiveCharge(1, slot, false, false, true); } - if (!hasCurseMistEffect && !isCoopGhost && playerForms[PLAYERFORM_NECROMANCER] > 2) + if (!hasCurseMistEffect && !isCoopGhost && playerForms[PLAYER_FORM_NECROMANCER] > 2) reconstruction_missing("Entity_Player::level_start 007a4ba0 (the Necronomicon transformation)"); for (int i = HasTrinket(TRINKET_BETHS_FAITH) ? GetTrinketMultiplier(TRINKET_BETHS_FAITH) * 4 : 0; i > 0; i--) AddWisp(COLLECTIBLE_BOOK_OF_VIRTUES, pos, false, false); @@ -1125,7 +1118,7 @@ void Entity_Player::stem_cell_heal() for (int i = 0; i < 2; i++) { uint32_t seed = Random(); - g_game->Spawn({.position = room_random_pickup_position(), + g_game->Spawn({.position = room_pickup_position_random(false, false), .type = ENTITY_PICKUP, .variant = PICKUP_HEART, .seed = seed}); @@ -1422,6 +1415,18 @@ void Entity_Player::ClearReferences() release_weapons_and_effects(false); } +// 0065cf60 Whether the player is a co-op baby still blinking in after joining. +bool Entity_Player::IsP2Appearing() +{ + return variant == PLAYER_VARIANT_COOP_BABY && damageCooldown > 0; +} + +// 00782a60 Whether the head is free to turn, its last turn having run out. +uint32_t Entity_Player::CanTurnHead() +{ + return headDirectionTime < 0; +} + // 00757ab0 Whether the player shuts the room's doors, as players do only in the deathmatch. bool Entity_Player::CanShutDoors() { diff --git a/src/entity_player.h b/src/entity_player.h index 800d4ac..1f397da 100644 --- a/src/entity_player.h +++ b/src/entity_player.h @@ -193,6 +193,19 @@ enum PlayerItemId : int COLLECTIBLE_COMPASS = 21, COLLECTIBLE_BREAKFAST = 25, COLLECTIBLE_BIBLE = 33, + COLLECTIBLE_GIMPY = 225, + COLLECTIBLE_INFESTATION_2 = 234, + COLLECTIBLE_QUINTS = 661, + COLLECTIBLE_BONE_SPURS = 683, + COLLECTIBLE_HUNGRY_SOUL = 684, + COLLECTIBLE_DOLLAR = 18, + COLLECTIBLE_ROTTEN_MEAT = 26, + COLLECTIBLE_BLOOD_BAG = 119, + COLLECTIBLE_IV_BAG = 135, + COLLECTIBLE_CRYSTAL_BALL = 158, + COLLECTIBLE_PORTABLE_SLOT = 177, + COLLECTIBLE_BUDDY_IN_A_BOX = 518, + COLLECTIBLE_BATTERY_PACK = 603, COLLECTIBLE_BOOK_OF_BELIAL = 34, COLLECTIBLE_NECRONOMICON = 35, COLLECTIBLE_POOP = 36, @@ -236,6 +249,7 @@ enum PlayerItemId : int COLLECTIBLE_BOBS_CURSE = 140, COLLECTIBLE_NOTCHED_AXE = 147, COLLECTIBLE_IPECAC = 149, + COLLECTIBLE_MULLIGAN = 151, COLLECTIBLE_MUTANT_SPIDER = 153, COLLECTIBLE_PEEPER = 155, COLLECTIBLE_BLOODY_LUST = 157, @@ -250,6 +264,7 @@ enum PlayerItemId : int COLLECTIBLE_GNAWED_LEAF = 210, COLLECTIBLE_BALL_OF_BANDAGES = 207, COLLECTIBLE_GUPPYS_COLLAR = 212, + COLLECTIBLE_POLYPHEMUS = 169, COLLECTIBLE_ANEMIC = 214, COLLECTIBLE_ANTI_GRAVITY = 222, COLLECTIBLE_PYROMANIAC = 223, @@ -257,6 +272,7 @@ enum PlayerItemId : int COLLECTIBLE_MONSTROS_LUNG = 229, COLLECTIBLE_BALL_OF_TAR = 231, COLLECTIBLE_STOP_WATCH = 232, + COLLECTIBLE_TINY_PLANET = 233, COLLECTIBLE_E_COLI = 236, COLLECTIBLE_KEY_PIECE_1 = 238, COLLECTIBLE_KEY_PIECE_2 = 239, @@ -312,6 +328,8 @@ enum PlayerItemId : int COLLECTIBLE_SERPENTS_KISS = 393, COLLECTIBLE_MARKED = 394, COLLECTIBLE_TECH_X = 395, + COLLECTIBLE_TRACTOR_BEAM = 397, + COLLECTIBLE_EVIL_EYE = 410, COLLECTIBLE_LUSTY_BLOOD = 411, COLLECTIBLE_CAMBION_CONCEPTION = 412, COLLECTIBLE_IMMACULATE_CONCEPTION = 413, @@ -361,6 +379,7 @@ enum PlayerItemId : int COLLECTIBLE_SOCKS = 571, COLLECTIBLE_EYE_OF_THE_OCCULT = 572, COLLECTIBLE_DIRTY_MIND = 576, + COLLECTIBLE_DAMOCLES = 577, COLLECTIBLE_RED_KEY = 580, COLLECTIBLE_WAVY_CAP = 582, COLLECTIBLE_BOOK_OF_VIRTUES = 584, @@ -449,6 +468,14 @@ enum PlayerItemId : int TRINKET_SAFETY_CAP = 44, TRINKET_ACE_OF_SPADES = 45, TRINKET_POKER_CHIP = 76, + TRINKET_CRICKET_LEG = 185, + TRINKET_AAA_BATTERY = 3, + TRINKET_FISH_HEAD = 29, + TRINKET_BOBS_BLADDER = 71, + TRINKET_KARMA = 85, + TRINKET_PAY_TO_WIN = 112, + TRINKET_ROTTEN_PENNY = 126, + TRINKET_BETHS_ESSENCE = 182, TRINKET_SECOND_HAND = 78, TRINKET_MOMS_LOCKET = 87, TRINKET_CURSED_SKULL = 43, @@ -581,9 +608,8 @@ enum PlayerChallenge : int CHALLENGE_RED_REDEMPTION = 44 }; -// How far a held item's sprite rises over the head, and the Missing Pages form's index. +// How far a held item's sprite rises over the head. constexpr float HELD_SPRITE_RISE = -4; -constexpr int PLAYER_FORM_MISSING_PAGES = 15; // One active item slot: the item, its charges and the data it keeps between uses. struct ActiveItemDesc @@ -687,6 +713,24 @@ struct History void remove_index_refs(int index); }; +// A familiar as it follows its player into a saved run or through Curse of the Mist (FamiliarData). +struct FamiliarData +{ + Vector formationTargetOffset{}; + float health = 0; + int coins = 0; + int hearts = 0; + int keys = 0; + int roomClearCount = 0; + int state = 0; + int subtype = 0; + int variant = 0; + uint32_t dropSeed = 0; + uint32_t initSeed = 0; + bool isNotCountedAsFollower = false; + bool isSubtype55555 = false; +}; + // Coins, keys, bombs and charges, as Curse of the Mist keeps them aside. struct ConsumableData { @@ -943,7 +987,7 @@ public: std::shared_ptr playerHUD; std::vector contactHitList; std::vector darkArtsHitList; - std::vector curseMistFamiliars; + std::vector curseMistFamiliars; std::vector pendingWisps; std::deque echoChamberItems; EntityDesc friendBallEnemy; @@ -1284,7 +1328,7 @@ public: void AddJarHearts(int amount); void AddGoldenKey(); void RemoveGoldenKey(); - void restore_curse_mist_backup(int* backup); + void restore_curse_mist_backup(const ConsumableData& backup); Entity* AddBlueFlies(int amount, Vector pos, Entity* target); void RemoveBlueFly(); void AddLeprosy(); @@ -1497,6 +1541,8 @@ public: bool try_end_astral_projection(); void fire_saturnus_tears(); int GetMaxInventorySize(); + Entity_Pickup* DropCollectible(int collectible, Entity_Pickup* existing, bool isRemoveFromForm); + Entity_Pickup* DropCollectibleByHistoryIndex(int index, Entity_Pickup* existing); bool CanAddCollectibleToInventory(int id); void SetPocketActiveItem(int collectible, int slot, bool keepInPools); void get_salvation_scale(); diff --git a/src/entity_player_actives.cpp b/src/entity_player_actives.cpp index 92b9d5f..45f3b94 100644 --- a/src/entity_player_actives.cpp +++ b/src/entity_player_actives.cpp @@ -126,7 +126,6 @@ constexpr int NINE_VOLT_RECHARGE_FRAMES = 450; constexpr int NECROMANCER_FORM_ITEMS = 3; constexpr int OVERLAY_DELAY = 3; constexpr int PERCENT = 100; -constexpr int PLAYERFORM_NECROMANCER = 15; constexpr int REVELATIONS_SOUL_HEARTS = 2; constexpr int REVELATIONS_STATE_FLAG = 7; constexpr int SUPLEX_AIMING = 2; @@ -433,7 +432,7 @@ int Entity_Player::GetCollectibleMaxCharge(int collectibleId, int varData) if (varData < GLOWING_HOUR_GLASS_LIT_USES) return 0; break; case COLLECTIBLE_NECRONOMICON: - if (HasPlayerForm(PLAYERFORM_NECROMANCER) && varData == 1) return NECRONOMICON_FORM_CHARGES; + if (HasPlayerForm(PLAYER_FORM_NECROMANCER) && varData == 1) return NECRONOMICON_FORM_CHARGES; break; } ItemConfig_Item* item = g_manager->itemConfig.GetCollectible(collectibleId); @@ -462,7 +461,7 @@ int Entity_Player::GetActiveMinUsableCharge(int slot) if (active.item == COLLECTIBLE_LARYNX || active.item == COLLECTIBLE_EVERYTHING_JAR || active.item == COLLECTIBLE_NOTCHED_AXE) return 1; - if (active.item == COLLECTIBLE_NECRONOMICON && HasPlayerForm(PLAYERFORM_NECROMANCER) && active.varData == 1) + if (active.item == COLLECTIBLE_NECRONOMICON && HasPlayerForm(PLAYER_FORM_NECROMANCER) && active.varData == 1) return 1; return GetCollectibleMaxCharge(active.item, active.varData); } @@ -473,7 +472,7 @@ ChargeType active_charge_type(Entity_Player& player, int slot) { ActiveItemDesc& active = player.activeItems[slot]; bool isNecromancer = !player.hasCurseMistEffect && !player.isCoopGhost && - player.playerForms[PLAYERFORM_NECROMANCER] >= NECROMANCER_FORM_ITEMS; + player.playerForms[PLAYER_FORM_NECROMANCER] >= NECROMANCER_FORM_ITEMS; bool isFilledNecronomicon = active.item == COLLECTIBLE_NECRONOMICON && isNecromancer && active.varData == 1; if (active.item == 0 || isFilledNecronomicon) return CHARGE_SPECIAL; @@ -1442,7 +1441,7 @@ static void use_overlay_show(Entity_Player& player, int item, int slot) isSkipped = player.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_BOOK_OF_BELIAL); break; case COLLECTIBLE_NECRONOMICON: - isSkipped = player.HasPlayerForm(PLAYERFORM_NECROMANCER) && varData != 0; + isSkipped = player.HasPlayerForm(PLAYER_FORM_NECROMANCER) && varData != 0; break; case COLLECTIBLE_DEAD_SEA_SCROLLS: isSkipped = player.itemState != 0; diff --git a/src/entity_player_bombs.cpp b/src/entity_player_bombs.cpp index f69ca21..818e5aa 100644 --- a/src/entity_player_bombs.cpp +++ b/src/entity_player_bombs.cpp @@ -27,7 +27,6 @@ constexpr int COLLECTIBLE_ROCKET_IN_A_JAR = 583; constexpr int COLLECTIBLE_BLOOD_BOMBS = 614; constexpr int COLLECTIBLE_BRIMSTONE_BOMBS = 646; constexpr int COLLECTIBLE_GHOST_BOMBS = 727; -constexpr int TRINKET_BOBS_BLADDER = 71; constexpr int TRINKET_SHORT_FUSE = 133; constexpr int TRINKET_RING_CAP = 164; diff --git a/src/entity_player_characters.cpp b/src/entity_player_characters.cpp index 1c99ddb..bf1cb48 100644 --- a/src/entity_player_characters.cpp +++ b/src/entity_player_characters.cpp @@ -1,6 +1,7 @@ #include "entity_player_characters.h" #include "entity_effect.h" #include "entity_familiar.h" +#include "entity_player_tainted.h" #include "game.h" #include "hud.h" #include "item_overlay.h" @@ -85,10 +86,28 @@ bool is_azazel(Entity_Player& player) player.temporaryEffects.HasTrinketEffect(TRINKET_AZAZELS_STUMP); } -// Whether the frame and the stat evaluation are reconstructed for the player's character: the normal ones. -bool is_character_reconstructed(const Entity_Player& player) +// Whether the frame and the stat evaluation are reconstructed for the player's character: the normal ones and the +// tainted ones the frame (00782af0, 00794e50) has no branch for. Tainted Judas's and Tainted Keeper's Birthright have +// one. +bool is_character_reconstructed(Entity_Player& player) { - return player.playerType >= PLAYER_ISAAC && player.playerType <= PLAYER_ESAU; + switch (player.playerType) + { + case PLAYER_JUDAS_B: + case PLAYER_KEEPER_B: + return !player.HasCollectible(COLLECTIBLE_BIRTHRIGHT); + case PLAYER_ISAAC_B: + case PLAYER_CAIN_B: + case PLAYER_EVE_B: + case PLAYER_AZAZEL_B: + case PLAYER_EDEN_B: + case PLAYER_THELOST_B: + case PLAYER_APOLLYON_B: + case PLAYER_BETHANY_B: + return true; + default: + return player.playerType >= PLAYER_ISAAC && player.playerType <= PLAYER_ESAU; + } } // The tears up or down a character adds to the items' before Binge Eater's: Samson's, the tainted ones', Azazel's (or @@ -736,8 +755,7 @@ void Entity_Player::player_type_change_prepare(int oldType) if (oldType == PLAYER_JACOB || oldType == PLAYER_THEFORGOTTEN_B) remove_twin(); } if (oldType == PLAYER_LAZARUS_B || oldType == PLAYER_LAZARUS2_B) remove_twin(); - if (playerType == PLAYER_ISAAC_B) - reconstruction_missing("Entity_Player::player_type_change_prepare 007cf610 (Tainted Isaac's inventory)"); + if (playerType == PLAYER_ISAAC_B) tainted_isaac_inventory_trim(*this); if ((playerType == PLAYER_JACOB_B || playerType == PLAYER_JACOB2_B) && !temporaryEffects.HasNullEffect(NULLITEM_JACOBS_CURSE)) reconstruction_missing("Entity_Player::player_type_change_prepare 007cf610 (Tainted Jacob's curse)"); diff --git a/src/entity_player_characters.h b/src/entity_player_characters.h index 25f15d9..8fe2f39 100644 --- a/src/entity_player_characters.h +++ b/src/entity_player_characters.h @@ -26,7 +26,7 @@ bool is_character_slowed(Entity_Player& player); bool is_eden(const Entity_Player& player); bool is_azazel(Entity_Player& player); -bool is_character_reconstructed(const Entity_Player& player); +bool is_character_reconstructed(Entity_Player& player); // Eve's Whore of Babylon and Tainted Eve's last heart (007c9ea0). bool is_whore_of_babylon_awake(Entity_Player& player); diff --git a/src/entity_player_collectibles.cpp b/src/entity_player_collectibles.cpp index 97a986c..2e4a090 100644 --- a/src/entity_player_collectibles.cpp +++ b/src/entity_player_collectibles.cpp @@ -44,7 +44,6 @@ constexpr int EFFECT_END_ITEMS[] = {66, 77, 93, 117, 282, 298, 299, 409, 497, 58 constexpr int DEAD_CAT_LIVES_PER_COPY = 9; constexpr int HEARTBREAK_BROKEN_HEARTS = 3; -constexpr int PLAYER_FORM_LEO = 13; // 00721b70 Takes an item out of the history: the first entry of the same kind and id, Tainted Isaac's inventory // following. A locked history keeps its items. Whether one was removed. @@ -100,7 +99,7 @@ void Entity_Player::SwapActiveItems() void Entity_Player::TriggerCollectibleRemoved(int collectibleId) { if (collectibleId == REMOVAL_MAGIC_MUSHROOM || collectibleId == REMOVAL_LEO) - IncrementPlayerFormCounter(PLAYER_FORM_LEO, -1); + IncrementPlayerFormCounter(PLAYER_FORM_STOMPY, -1); else if (collectibleId == REMOVAL_DEAD_CAT) deadCatLives = (short)std::min(deadCatLives, GetCollectibleNum(REMOVAL_DEAD_CAT) * DEAD_CAT_LIVES_PER_COPY); else if (collectibleId == REMOVAL_HEARTBREAK) AddBrokenHearts(-HEARTBREAK_BROKEN_HEARTS); @@ -108,7 +107,7 @@ void Entity_Player::TriggerCollectibleRemoved(int collectibleId) if (GetCollectibleNum(collectibleId) <= 0) { if (collectibleId == REMOVAL_NECRONOMICON || collectibleId == REMOVAL_MISSING_PAGE_2) - IncrementPlayerFormCounter(PLAYER_FORM_MISSING_PAGES, -1); + IncrementPlayerFormCounter(PLAYER_FORM_NECROMANCER, -1); if (std::ranges::find(REMOVAL_EFFECT_ITEMS, collectibleId) != std::end(REMOVAL_EFFECT_ITEMS)) reconstruction_missing("Entity_Player::TriggerCollectibleRemoved 0078ff90 (an item that made room)"); } diff --git a/src/entity_player_damage.cpp b/src/entity_player_damage.cpp index e0ede89..eb6ee6f 100644 --- a/src/entity_player_damage.cpp +++ b/src/entity_player_damage.cpp @@ -31,9 +31,6 @@ constexpr int TRINKET_WALNUT = 108; constexpr int NULLITEM_BOOMERANG = 30; constexpr int NULLITEM_DOUBLE_DAMAGE = 29; constexpr int NULLITEM_SHACKLES_GHOST = 101; -constexpr int PLAYER_FORM_ADULT = 11; -constexpr int PLAYER_FORM_BEELZEBUB = 13; -constexpr int PLAYER_FORM_BOB = 4; constexpr int SAMSON_B_HIT_CHARGE = 10000; constexpr int BLEED_OUT_HEALTH = 600; @@ -422,7 +419,7 @@ static void hit_items_check(Entity_Player& player, uint64_t damageFlags, bool is { bool isItemHit = std::ranges::any_of(HIT_COLLECTIBLES, [&](int item) { return player.HasCollectible(item); }) || std::ranges::any_of(HIT_TRINKETS, [&](int trinket) { return player.HasTrinket(trinket); }) || - (isPenalized && player.HasTrinket(TRINKET_PERFECTION)) || player.HasPlayerForm(PLAYER_FORM_BEELZEBUB) || + (isPenalized && player.HasTrinket(TRINKET_PERFECTION)) || player.HasPlayerForm(PLAYER_FORM_STOMPY) || (player.HasCollectible(CROWN_OF_LIGHT) && !g_game->deathmatchManager.is_active()) || (player.HasCollectible(COLLECTIBLE_HYPERCOAGULATION) && !(damageFlags & HYPERCOAGULATION_IGNORED)) || std::ranges::any_of(player.activeItems, [](const ActiveItemDesc& active) { return active.item == COLLECTIBLE_LARYNX; }); diff --git a/src/entity_player_death.cpp b/src/entity_player_death.cpp index 39b56df..5a51590 100644 --- a/src/entity_player_death.cpp +++ b/src/entity_player_death.cpp @@ -19,7 +19,6 @@ constexpr int COLLECTIBLE_CHARM_VAMPIRE = 62; constexpr int COLLECTIBLE_ANKH = 161; constexpr int COLLECTIBLE_JUDAS_SHADOW = 311; constexpr int COLLECTIBLE_POLYDACTYLY = 454; -constexpr int TRINKET_AAA_BATTERY = 3; constexpr int TRINKET_BROKEN_ANKH = 28; constexpr int TRINKET_LOCUST_OF_WRATH = 113; constexpr int TRINKET_LOCUST_OF_CONQUEST = 117; @@ -416,9 +415,9 @@ void Entity_Player::ClearTemporaryEffects() SetPocketActiveItem(0, ACTIVE_SLOT_COUNT - 1, false); } -// 007d41d0 Puts an active item in a pocket slot (2 or 3), the one there before removed with its pocket. -// Only emptying the slot is reconstructed: a new item stops the game. -void Entity_Player::SetPocketActiveItem(int collectible, int slot, bool) +// 007d41d0 Puts an active item in a pocket slot (2 or 3), the one there before removed with its pocket. The new item +// takes a pocket and leaves the pools unless kept there (Wait What? takes Butter Bean with it), but not in Cantripped. +void Entity_Player::SetPocketActiveItem(int collectible, int slot, bool keepInPools) { if (slot < POCKET_ACTIVE_FIRST_SLOT || slot >= ACTIVE_SLOT_COUNT) return; @@ -429,8 +428,14 @@ void Entity_Player::SetPocketActiveItem(int collectible, int slot, bool) std::shift_left(pocketItems.begin() + i, pocketItems.end(), 1); pocketItems.back() = {0, POCKET_CARD}; } - if (collectible != 0 && g_manager->itemConfig.GetCollectible(collectible)) - reconstruction_missing("Entity_Player::SetPocketActiveItem 007d41d0 (a new pocket active)"); + if (collectible == 0 || !g_manager->itemConfig.GetCollectible(collectible)) return; + + AddPocketItem(slot + 1, POCKET_ACTIVE); + AddCollectible(collectible, -1, true, slot, 0); + ItemPool& pool = g_game->itemPool; + if (keepInPools || collectible < 0 || g_game->challenge == CHALLENGE_CANTRIPPED) return; + if (collectible == COLLECTIBLE_WAIT_WHAT) pool.RemoveCollectible(COLLECTIBLE_BUTTER_BEAN, REMOVE_ANY, REMOVE_APPLY); + if (collectible < (int)pool.removedCollectibles.size()) pool.removedCollectibles[collectible] = true; } // 007ad440 How many pocket slots the player has: one, two with Starter Deck, Little Baggy or Polydactyly, and one diff --git a/src/entity_player_evaluate.cpp b/src/entity_player_evaluate.cpp index 2207501..e0f2577 100644 --- a/src/entity_player_evaluate.cpp +++ b/src/entity_player_evaluate.cpp @@ -6,6 +6,7 @@ #include "game.h" #include "lua_engine.h" #include "room.h" +#include "room_path.h" #include "log.h" #include "manager.h" #include @@ -49,9 +50,6 @@ constexpr int PILL_LUCK_DOWN = 17; constexpr int PILL_LUCK_UP = 18; constexpr int PILL_SHOT_SPEED_DOWN = 47; constexpr int PILL_SHOT_SPEED_UP = 48; -constexpr int PLAYER_FORM_SPUN = 5; -constexpr int PLAYER_FORM_CONJOINED = 7; -constexpr int PLAYER_FORM_LEVIATHAN = 14; constexpr int TRINKET_CRACKED_CROWN = 92; constexpr int FAMILIAR_ITEM_WISP = 206; constexpr int COLLECTIBLE_FORTUNE_COOKIE = 557; @@ -97,6 +95,7 @@ constexpr float BERSERK_CHARGE_FULL = 100000; constexpr float HOLOGRAM_ALPHA = 0.2f; constexpr float COLOR_OFFSET_UNIT = 0.003921569f; constexpr float HELD_THROW_SCALE = 0.1f; +constexpr float TAINTED_BETHANY_STAT_SCALE = 0.75f; // Whether the player owns any of the listed collectibles. static bool is_owning_any(Entity_Player& player, std::span collectibles) @@ -234,6 +233,7 @@ static void fire_delay_evaluate(Entity_Player& p, const StatBonuses& bonus, floa else if (p.HasWeaponType(WEAPON_BOMBS)) rate /= 2.5f; else if (p.HasWeaponType(WEAPON_BONE)) rate *= 0.5f; if (has(152)) rate /= 1.5f; + if (p.playerType == PLAYER_EVE_B) rate *= 0.66f; if (has(310)) rate *= 0.66f; if (p.HasWeaponType(WEAPON_MONSTROS_LUNGS)) rate /= 4.3f; else if (p.HasWeaponType(WEAPON_TECH_X) && has(229)) rate /= 3.1f; @@ -519,7 +519,7 @@ static void speed_evaluate(Entity_Player& p, const StatBonuses& bonus, float cro if (p.coopBabyBuffTimers[COOP_BUFF_SPEED] > 0) p.moveSpeed = p.moveSpeed + 0.15f; if (has(230)) p.moveSpeed = p.moveSpeed + 0.2f; if (p.HasPlayerForm(PLAYER_FORM_SPUN)) p.moveSpeed = p.moveSpeed + 0.15f; - if (p.HasPlayerForm(PLAYER_FORM_LEVIATHAN)) p.moveSpeed = p.moveSpeed + 0.2f; + if (p.HasPlayerForm(PLAYER_FORM_FLIGHT)) p.moveSpeed = p.moveSpeed + 0.2f; if (has(130) || has(181)) p.moveSpeed = std::max(p.moveSpeed, 1.5f); if (has(COLLECTIBLE_TAURUS) || p.GetZodiacEffect() == COLLECTIBLE_TAURUS) p.moveSpeed = p.moveSpeed - 0.3f; if (has(300) || p.GetZodiacEffect() == 300) p.moveSpeed = p.moveSpeed + 0.25f; @@ -803,14 +803,14 @@ static bool is_flying(Entity_Player& p) TemporaryEffects& effects = p.temporaryEffects; int wings = effects.GetCollectibleEffectNum(20); for (int id : {185, 184, 181, 179, 159, 130, 82, 20}) wings += p.GetCollectibleNum(id); - if (wings >= 1 || p.HasPlayerForm(0) || p.HasPlayerForm(1) || p.HasPlayerForm(8)) return true; + if (wings >= 1 || p.HasPlayerForm(PLAYER_FORM_GUPPY) || p.HasPlayerForm(PLAYER_FORM_BEELZEBUB) || p.HasPlayerForm(PLAYER_FORM_LEVIATHAN)) return true; bool isFlyingType = p.variant == PLAYER_VARIANT_COOP_BABY || p.playerType == PLAYER_THELOST || p.playerType == PLAYER_THELOST_B || p.playerType == PLAYER_JACOB2_B || p.playerType == PLAYER_THESOUL_B || p.playerType == PLAYER_AZAZEL || p.playerType == PLAYER_THESOUL; - return isFlyingType || p.HasPlayerForm(3) || effects.HasCollectibleEffect(33) || effects.HasCollectibleEffect(20) || - effects.HasCollectibleEffect(409) || effects.HasTrinketEffect(118) || p.HasPlayerForm(14) || + return isFlyingType || p.HasPlayerForm(PLAYER_FORM_SERAPHIM) || effects.HasCollectibleEffect(33) || effects.HasCollectibleEffect(20) || + effects.HasCollectibleEffect(409) || effects.HasTrinketEffect(118) || p.HasPlayerForm(PLAYER_FORM_FLIGHT) || effects.GetCollectibleEffectNum(COLLECTIBLE_ASTRAL_PROJECTION) == 1 || effects.HasNullEffect(NULLITEM_REVERSE_SUN) || effects.HasNullEffect(NULLITEM_REVERSE_DEVIL) || effects.HasNullEffect(NULLITEM_ESAU_JR) || effects.HasNullEffect(NULLITEM_SPIRIT_SHACKLES_SOUL) || @@ -819,16 +819,30 @@ static bool is_flying(Entity_Player& p) p.HasCollectible(633); } -// The flying section of 00763570: flight and the grid collision it gives. Losing flight asks whether the player can -// walk back to the entrance (the original keeps it flying by a Transcendence effect if not), which stops the game. +// 007d1810 Whether a player on the ground is stranded: one colliding with the floor that cannot walk to the entrance. +static bool is_stranded_on_ground(Entity_Player& p) +{ + int collision = p.entityGridCollisionClass; + bool isGrounded = collision != GRIDCOLL_NONE && collision != GRIDCOLL_WALLS && collision != GRIDCOLL_WALLS_X && + collision != GRIDCOLL_WALLS_Y; + return isGrounded && !is_reachable_from_player(*g_game->room, {p.pos, &p, REACH_ENTRANCE}); +} + +// The flying section of 00763570: flight and the grid collision it gives. A player losing flight where it cannot walk +// to the entrance keeps flying by a Bible effect. static void flying_evaluate(Entity_Player& p) { bool wasFlying = p.canFly; p.canFly = is_flying(p); p.entityGridCollisionClass = p.canFly ? GRIDCOLL_WALLS : GRIDCOLL_GROUND; - if (wasFlying && !p.canFly) - reconstruction_missing("Entity_Player::EvaluateItems 00763570 (Room::is_reachable_from_player 00823be0)"); + if (wasFlying && !p.canFly && is_stranded_on_ground(p)) + { + p.canFly = true; + p.entityGridCollisionClass = GRIDCOLL_WALLS; + if (!p.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_BIBLE)) + p.temporaryEffects.AddCollectibleEffect(COLLECTIBLE_BIBLE, true, 1); + } static_cast(g_luaEngine)->EvaluateItems(&p, CACHE_FLYING); p.entityGridCollisionClass = p.canFly ? GRIDCOLL_WALLS : GRIDCOLL_GROUND; if (p.canFly != wasFlying) p.UpdateCostumes(); @@ -995,6 +1009,7 @@ void Entity_Player::EvaluateItems() StatBonuses bonus = stat_bonuses_get(*this); float crownScale = (float)GetTrinketMultiplier(TRINKET_CRACKED_CROWN) * 0.2f + 1; + if (playerType == PLAYER_BETHANY_B) crownScale *= TAINTED_BETHANY_STAT_SCALE; if (cacheFlags & CACHE_WEAPON) weapons_evaluate(*this); if (cacheFlags & CACHE_SHOTSPEED) cacheFlags |= CACHE_RANGE; if (cacheFlags & CACHE_FIREDELAY) fire_delay_evaluate(*this, bonus, crownScale); diff --git a/src/entity_player_forgotten.cpp b/src/entity_player_forgotten.cpp index fe69954..a62be3a 100644 --- a/src/entity_player_forgotten.cpp +++ b/src/entity_player_forgotten.cpp @@ -20,8 +20,6 @@ constexpr int FORGOTTEN_SWAP_HOLD_COOLDOWN = 10; constexpr int D_INFINITY_FACES = 10; constexpr int D_INFINITY_FACE_SHIFT = 16; constexpr int D_INFINITY_FACE_MASK = 0xffff; -constexpr int TAINTED_ISAAC_SLOTS = 8; -constexpr int TAINTED_ISAAC_BIRTHRIGHT_SLOTS = 12; constexpr uint32_t DROP_HOLD_FRAMES = 120; constexpr uint32_t SPECIAL_DAILY_NO_DROP = 4; constexpr int ACTION_TRIGGER_DROP = 0x20; @@ -423,7 +421,7 @@ static void tainted_inventory_rotate(Entity_Player& player) if (player.playerType == PLAYER_ISAAC_B) { - int limit = player.HasCollectible(COLLECTIBLE_BIRTHRIGHT) ? TAINTED_ISAAC_BIRTHRIGHT_SLOTS : TAINTED_ISAAC_SLOTS; + int limit = player.GetMaxInventorySize(); auto end = std::find_if(player.inventory.begin(), player.inventory.begin() + limit, [](int entry) { return entry < 0; }); if (end - player.inventory.begin() > 1) { diff --git a/src/entity_player_forms.cpp b/src/entity_player_forms.cpp new file mode 100644 index 0000000..14b4d40 --- /dev/null +++ b/src/entity_player_forms.cpp @@ -0,0 +1,166 @@ +#include "entity_effect.h" +#include "entity_pickup.h" +#include "entity_player.h" +#include "game.h" +#include "hud.h" +#include "item_overlay.h" +#include "manager.h" +#include "menu_options.h" +#include "player_stats.h" +#include "room_grid.h" +#include "sfx_manager.h" +#include +#include + +// The unlocks Guppy and Beelzebub give. +constexpr int ACHIEVEMENT_GUPPYS_HAIRBALL = 65; +constexpr int ACHIEVEMENT_LORD_OF_THE_FLIES = 178; +constexpr int ACHIEVEMENT_ANGRY_FLY = 352; + +// The health the transformations give the first time: Fun Guy's and Adult's heart, Seraphim's soul hearts and +// Leviathan's black hearts, in halves. +constexpr int FORM_HEART_HALVES = 2; +constexpr int SERAPHIM_SOUL_HALVES = 6; +constexpr int LEVIATHAN_BLACK_HALVES = 4; + +// Where Spun's pill drops, and the poof a transformation shows under the player. +constexpr float SPUN_PILL_STEP = 40; +constexpr float FORM_POOF_OFFSET_Y = 5; +constexpr int FORM_POOF_SUBTYPE = 2; + +// Whether the player was given this transformation's reward already. +static bool is_form_rewarded(Entity_Player& player, int form) +{ + return player.playerFormsRewarded & (1u << form); +} + +// Announces the Necromancer: its sound and the Necronomicon's giant book. +static void necromancer_announce() +{ + sound_play(SOUND_NECROMANCER); + g_game->itemOverlay.Show(GIANTBOOK_NECROMANCER, 3, nullptr); +} + +// The Necromancer's part of 0075e320: the first Necronomicon already turned stays the Necromancer's book (charged the +// first time) and the others turn back. Gaining it with none turned turns the first held one. +static void necronomicon_transform(Entity_Player& player, bool isActive) +{ + bool isRewarded = is_form_rewarded(player, PLAYER_FORM_NECROMANCER); + bool isFound = false; + for (int slot = 0; slot < ACTIVE_SLOT_COUNT; slot++) + { + ActiveItemDesc& active = player.activeItems[slot]; + if (active.item != COLLECTIBLE_NECRONOMICON) continue; + + if (isFound) active.varData = 0; + else if (active.varData == 1) + { + if (!isRewarded) player.AddActiveCharge(player.GetActiveMaxCharge(slot), slot, false, false, true); + if (isActive) necromancer_announce(); + isFound = true; + } + sound_play(SOUND_NECROMANCER); + g_game->hud.InvalidateActiveItem(&player, slot); + } + if (isFound || !isActive) return; + + int slot = player.GetActiveItemSlot(COLLECTIBLE_NECRONOMICON); + if (slot < 0) return; + + player.activeItems[slot].varData = !isRewarded; + if (!isRewarded) player.AddActiveCharge(player.GetActiveMaxCharge(slot), slot, false, false, true); + g_game->hud.InvalidateActiveItem(&player, slot); + necromancer_announce(); +} + +// What a transformation gives the first time it is gained: Guppy's and Beelzebub's unlocks (every time), health or +// Spun's pill. +static void form_reward(Entity_Player& player, int form) +{ + PersistentGameData& save = g_manager->persistentGameData; + bool isRewarded = is_form_rewarded(player, form); + switch (form) + { + case PLAYER_FORM_GUPPY: save.TryUnlock(ACHIEVEMENT_GUPPYS_HAIRBALL); break; + case PLAYER_FORM_BEELZEBUB: + save.TryUnlock(ACHIEVEMENT_LORD_OF_THE_FLIES); + save.TryUnlock(ACHIEVEMENT_ANGRY_FLY); + break; + case PLAYER_FORM_FUN_GUY: + case PLAYER_FORM_ADULT: + if (isRewarded) break; + player.AddMaxHearts(FORM_HEART_HALVES, false); + player.AddHearts(FORM_HEART_HALVES, false, false); + break; + case PLAYER_FORM_SERAPHIM: + if (!isRewarded) player.AddSoulHearts(SERAPHIM_SOUL_HALVES, false); + break; + case PLAYER_FORM_SPUN: + { + if (isRewarded) break; + uint32_t seed = player.GetCollectibleRNG(COLLECTIBLE_VIRUS).Next(); + g_game->Spawn({.position = room_free_pickup_position_find({.position = player.pos, .step = SPUN_PILL_STEP}), + .spawner = &player, + .type = ENTITY_PICKUP, + .variant = PICKUP_PILL, + .seed = seed}); + break; + } + case PLAYER_FORM_LEVIATHAN: + if (!isRewarded) player.AddBlackHearts(LEVIATHAN_BLACK_HALVES); + break; + } +} + +// 0075e320 Counts items towards a transformation (the Necromancer's from the Necronomicon, Missing Page 2 and the +// Missing Page). Gaining one evaluates its stats, rewards it, dresses the player and announces it. Losing one takes its +// costume off. A form outside the counters is ignored, where the original writes past them. +void Entity_Player::IncrementPlayerFormCounter(int form, int num) +{ + if (form < 0 || form >= PLAYER_FORM_SLOTS) return; + + bool wasActive = HasPlayerForm(form); + playerForms[form] = std::max(playerForms[form] + num, 0); + if (form == PLAYER_FORM_NECROMANCER) + playerForms[form] = (int)HasCollectible(COLLECTIBLE_NECRONOMICON) + + (int)HasCollectible(COLLECTIBLE_MISSING_PAGE_2) + (int)HasTrinket(TRINKET_MISSING_PAGE); + bool isActive = HasPlayerForm(form); + if (isActive == wasActive) return; + + if (isActive) Player_stats_add(g_game->onlinePlayerStats, ONLINE_STAT_TRANSFORMATIONS, this, 1); + ItemConfig& items = g_manager->itemConfig; + ItemConfig_PlayerForm* config = form < (int)items.playerForms.size() ? items.playerForms[form].get() : nullptr; + if (config) cacheFlags |= config->cacheFlags; + if (form == PLAYER_FORM_NECROMANCER) necronomicon_transform(*this, isActive); + if (!isActive) + { + if (config && config->costume != -1) RemoveCostume(items.GetNullItem(config->costume)); + return; + } + + form_reward(*this, form); + AddPlayerFormCostume(form); + if (config) + { + std::string name(string_table_translate(g_manager->stringTable, config->name)); + g_game->hud.ShowStackedItemTextCustom(name.c_str(), ""); + } + sound_play(SOUND_POWERUP_SPEWER); + g_game->Spawn({.position = vector_make(pos.x, pos.y + FORM_POOF_OFFSET_Y), + .spawner = this, + .subType = FORM_POOF_SUBTYPE, + .type = ENTITY_EFFECT, + .variant = EFFECT_POOF01, + .seed = Random()}); + playerFormsRewarded |= 1u << form; +} + +// 0075e9a0 Puts on a transformation's costume, if it has one. +void Entity_Player::AddPlayerFormCostume(int form) +{ + ItemConfig& items = g_manager->itemConfig; + if (form < 0 || form >= (int)items.playerForms.size() || !items.playerForms[form]) return; + + int costume = items.playerForms[form]->costume; + if (costume != -1) AddCostume(items.GetNullItem(costume), false); +} diff --git a/src/entity_player_frame.cpp b/src/entity_player_frame.cpp index b2bdfe1..b07dee0 100644 --- a/src/entity_player_frame.cpp +++ b/src/entity_player_frame.cpp @@ -645,10 +645,9 @@ void Entity_Player::update_shooting() // The temporary effects' part of 00782af0: Mars' dash, a pony's charge and Recall ignore knockback, the stats are // evaluated when the effects changed, and the timed ones count down. The items' frame (update_effects) is not reached -// by a plain player. +// by a plain player, but its closing PostPEffectUpdate callback is. static void temporary_effects_update(Entity_Player& player) { - TemporaryEffects& effects = player.temporaryEffects; bool isDashing = effects.HasCollectibleEffect(COLLECTIBLE_MARS) || player.ponyCharge >= 1 || effects.HasCollectibleEffect(COLLECTIBLE_RECALL); @@ -660,7 +659,10 @@ static void temporary_effects_update(Entity_Player& player) player.EvaluateItems(); } effects.isEvaluateCachePending = false; - if (!player.HasEntityFlags(FLAG_INTERPOLATION_UPDATE)) effects.Update(); + if (player.HasEntityFlags(FLAG_INTERPOLATION_UPDATE)) return; + + effects.Update(); + lua_engine_get().PostPEffectUpdate(&player); } // 00782af0 The player's frame. Only the frame of a plain character is reconstructed: the base entity moves it, it walks diff --git a/src/entity_player_items.cpp b/src/entity_player_items.cpp index 4f2cb69..25d7187 100644 --- a/src/entity_player_items.cpp +++ b/src/entity_player_items.cpp @@ -600,8 +600,6 @@ constexpr int SWARM_FLIES = 8; constexpr int EXPERIMENTAL_STATS = 7; constexpr int EXPERIMENTAL_CHANGES = 6; constexpr int EXPERIMENTAL_UPS = 4; -constexpr int PLAYER_FORM_STOMPY = 13; -constexpr int PLAYER_FORM_PAGES = 15; constexpr uint32_t CURSES_ALL = 0xffffffff; constexpr uint32_t CHAOS_PICKUP_MASK = 7; constexpr int CHAOS_PICKUP_MAX = 6; @@ -767,20 +765,6 @@ void Entity_Player::UpdateBookOfVirtues(bool isAddedBookOfVirtues) active.varData = 0; } -// 0075e320 Counts items towards a transformation (the Missing Pages' from its two books and trinket). Only the counting is -// reconstructed: a transformation won or lost stops the game until reached. -void Entity_Player::IncrementPlayerFormCounter(int ePlayerForm, int num) -{ - - bool wasActive = HasPlayerForm(ePlayerForm); - playerForms[ePlayerForm] = std::max(playerForms[ePlayerForm] + num, 0); - if (ePlayerForm == PLAYER_FORM_MISSING_PAGES) - playerForms[ePlayerForm] = (int)HasCollectible(COLLECTIBLE_NECRONOMICON) + - (int)HasCollectible(COLLECTIBLE_MISSING_PAGE_2) + (int)HasTrinket(TRINKET_MISSING_PAGE); - if (HasPlayerForm(ePlayerForm) != wasActive) - reconstruction_missing("Entity_Player::IncrementPlayerFormCounter 0075e320 (a transformation)"); -} - // The run's unlocks for holding many items: the tag sets, Blood Clot's and Rubber Cement's counters, ten tears ups and // three star items. void Entity_Player::collectible_unlocks_check(int collectibleId, ItemConfig_Item& item) @@ -1092,7 +1076,7 @@ static void collectible_effect_apply(Entity_Player& p, const CollectibleGain& ga return; case 35: case 262: - p.IncrementPlayerFormCounter(PLAYER_FORM_PAGES, 1); + p.IncrementPlayerFormCounter(PLAYER_FORM_NECROMANCER, 1); return; case 54: game.ApplyMapEffect(); @@ -1507,6 +1491,9 @@ void Entity_Player::costume_layers_map(SkinColors& colors) } } +// The color Black Judas and Tainted Judas darken a costume with when their folder has no sheet for it (00c5d090). +constexpr ColorMod BLACK_JUDAS_COSTUME_TINT = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0.0314f, 0, 0}}; + // The UpdateCostumes part that dresses a mapped costume for the character: its sheets from the character's costume // folder and, for a costume with skin alts drawn for another skin, the skin color's sheets, darkened for Black Judas // when the folder has none, and its animation kept as it was. The dark tint is the one the original keeps in its data. @@ -1516,7 +1503,6 @@ void Entity_Player::costume_skin_apply(CostumeSpriteDesc& costume, int skinColor bool isAlt = costume.isHasSkinAlt && costume.defaultSkinColor != skinColor; bool isAnyFound = false; - if (isDark) reconstruction_missing("Entity_Player::UpdateCostumes 0075bf00 (Black Judas's costume tint)"); std::string animation = costume.sprite.animState.animData ? costume.sprite.GetAnimation() : std::string(); bool isPlaying = costume.sprite.animState.animData && costume.sprite.animState.isPlaying; int frame = (int)costume.sprite.animState.animFrame; @@ -1530,7 +1516,8 @@ void Entity_Player::costume_skin_apply(CostumeSpriteDesc& costume, int skinColor std::string skinned = costume_path_apply_skin_color(path, isAlt ? skinColor : -1, playerType, isAlt ? &isSkinFound : nullptr, &isCharacterFound); costume.sprite.ReplaceSpritesheet(layer, skinned); - if (LayerState* recolored = costume.sprite.GetLayer(layer)) recolored->color = COLOR_DEFAULT; + if (LayerState* recolored = costume.sprite.GetLayer(layer)) + recolored->color = isDark && !isCharacterFound ? BLACK_JUDAS_COSTUME_TINT : COLOR_DEFAULT; isAnyFound |= isSkinFound || isCharacterFound; } if (isAlt && !isAnyFound && !is_eden_hair(costume.item)) diff --git a/src/entity_player_missing.cpp b/src/entity_player_missing.cpp index 036a630..2965d7b 100644 --- a/src/entity_player_missing.cpp +++ b/src/entity_player_missing.cpp @@ -27,7 +27,6 @@ Entity_Familiar* Entity_Player::AddItemWisp(int, Vector, bool) } void Entity_Player::ResetDamageCooldown() { reconstruction_missing("Entity_Player::ResetDamageCooldown 0060d090"); } Vector Entity_Player::SpriteScale() { reconstruction_missing("Entity_Player::SpriteScale 0060d0a0"); } -bool Entity_Player::IsP2Appearing() { reconstruction_missing("Entity_Player::IsP2Appearing 0065cf60"); } void Entity_Player::set_last_damage(uint64_t, const EntityRef&) { reconstruction_missing("Entity_Player::set_last_damage 006dad80"); @@ -48,10 +47,6 @@ void Entity_Player::trigger_max_hearts_removed(int) void Entity_Player::RemoveBlackHeart(int) { reconstruction_missing("Entity_Player::RemoveBlackHeart 007591e0"); } void Entity_Player::AddGoldenKey() { reconstruction_missing("Entity_Player::AddGoldenKey 00759620"); } void Entity_Player::RemoveGoldenKey() { reconstruction_missing("Entity_Player::RemoveGoldenKey 00759660"); } -void Entity_Player::restore_curse_mist_backup(int*) -{ - reconstruction_missing("Entity_Player::restore_curse_mist_backup 00759950"); -} void Entity_Player::RemoveBlueFly() { reconstruction_missing("Entity_Player::RemoveBlueFly 00759b80"); } void Entity_Player::AddLeprosy() { reconstruction_missing("Entity_Player::AddLeprosy 00759b90"); } Entity* Entity_Player::AddBoneOrbital(Vector) { reconstruction_missing("Entity_Player::AddBoneOrbital 00759bc0"); } @@ -60,10 +55,6 @@ Entity* Entity_Player::AddSwarmFlyOrbital(Vector) reconstruction_missing("Entity_Player::AddSwarmFlyOrbital 00759bf0"); } void Entity_Player::AddNullCostume(int) { reconstruction_missing("Entity_Player::AddNullCostume 0075d800"); } -void Entity_Player::AddPlayerFormCostume(int) -{ - reconstruction_missing("Entity_Player::AddPlayerFormCostume 0075e9a0"); -} void Entity_Player::SetItemState(int) { reconstruction_missing("Entity_Player::SetItemState 0075ea20"); } void Entity_Player::RespawnFamiliars() { reconstruction_missing("Entity_Player::RespawnFamiliars 00770600"); } void Entity_Player::GetNPCTarget() { reconstruction_missing("Entity_Player::GetNPCTarget 00770610"); } @@ -81,7 +72,6 @@ bool Entity_Player::TryRemoveSmeltedTrinket(uint32_t) reconstruction_missing("Entity_Player::TryRemoveSmeltedTrinket 00772260"); } bool Entity_Player::replace_trinket() { reconstruction_missing("Entity_Player::replace_trinket 00772530"); } -uint32_t Entity_Player::CanTurnHead() { reconstruction_missing("Entity_Player::CanTurnHead 00782a60"); } void Entity_Player::RemoveCollectibleByHistoryIndex(int, bool) { reconstruction_missing("Entity_Player::RemoveCollectibleByHistoryIndex 0078fec0"); @@ -99,7 +89,8 @@ void Entity_Player::AnimateTrinket(int, std::string_view, std::string_view) reconstruction_missing("Entity_Player::AnimateTrinket 007ab550"); } void Entity_Player::AnimateTrapdoor() { reconstruction_missing("Entity_Player::AnimateTrapdoor 007abc00"); } -void Entity_Player::AnimateLightTravel() { reconstruction_missing("Entity_Player::AnimateLightTravel 007abc10"); } +// 007abc10 Plays the rise up a beam of light. +void Entity_Player::AnimateLightTravel() { PlayExtraAnimation("LightTravel"); } void Entity_Player::AnimateAppear() { reconstruction_missing("Entity_Player::AnimateAppear 007abcb0"); } void Entity_Player::AnimateTeleport(bool) { reconstruction_missing("Entity_Player::AnimateTeleport 007abcc0"); } void Entity_Player::AddPrettyFly() { reconstruction_missing("Entity_Player::AddPrettyFly 007abdf0"); } @@ -218,7 +209,6 @@ void Entity_Player::ThrowFriendlyDip(int, Vector, Vector) void Entity_Player::AddUrnSouls(uint32_t) { reconstruction_missing("Entity_Player::AddUrnSouls 007d3480"); } void Entity_Player::AddGigaBombs(int) { reconstruction_missing("Entity_Player::AddGigaBombs 007d34f0"); } void Entity_Player::fire_saturnus_tears() { reconstruction_missing("Entity_Player::fire_saturnus_tears 007d3e40"); } -int Entity_Player::GetMaxInventorySize() { reconstruction_missing("Entity_Player::GetMaxInventorySize 007d4150"); } void Entity_Player::get_salvation_scale() { reconstruction_missing("Entity_Player::get_salvation_scale 007d4340"); } void Entity_Player::update_suplex() { reconstruction_missing("Entity_Player::update_suplex 007d4390"); } uint32_t Entity_Player::bag_of_crafting_collect(Entity_Pickup*) @@ -242,8 +232,6 @@ void Entity_Player::spawn_lil_clot_familiars() } void Entity_Player::creep_contact_add(int, int) { reconstruction_missing("Entity_Player::creep_contact_add 007d8740"); } bool Entity_Player::spawn_ghost_corpse() { reconstruction_missing("Entity_Player::spawn_ghost_corpse 007d87a0"); } -void Entity_Player::AddCurseMistEffect() { reconstruction_missing("Entity_Player::AddCurseMistEffect 007d8980"); } -void Entity_Player::RemoveCurseMistEffect() { reconstruction_missing("Entity_Player::RemoveCurseMistEffect 007d8d20"); } void Entity_Player::AttachMinecart(Entity_NPC*) { reconstruction_missing("Entity_Player::AttachMinecart 007d9180"); } void Entity_Player::add_samson_berserk_charge(int) { @@ -292,5 +280,4 @@ void Entity_Player::PlayCollectibleAnim(int, bool, std::string_view, int) { reconstruction_missing("Entity_Player::PlayCollectibleAnim 00759f50"); } -bool History::RemoveHistoryItemByIndex(int) { reconstruction_missing("History::RemoveHistoryItemByIndex 00721c00"); } void History::merge(History&) { reconstruction_missing("History::merge 00721c80"); } diff --git a/src/entity_player_mist.cpp b/src/entity_player_mist.cpp new file mode 100644 index 0000000..440a601 --- /dev/null +++ b/src/entity_player_mist.cpp @@ -0,0 +1,150 @@ +#include "entity_player.h" +#include "boss_ai.h" +#include "entity_familiar.h" +#include "game.h" +#include "player_manager.h" +#include +#include + +// The caps Curse of the Mist's consumables come back under: 99 (999 coins with Deep Pockets, 29 poop mana with Tainted +// ???'s Birthright, 9 without). +constexpr int MIST_CONSUMABLE_CAP = 99; +constexpr int MIST_DEEP_POCKETS_COIN_CAP = 999; +constexpr int MIST_POOP_MANA_CAP = 9; +constexpr int MIST_BIRTHRIGHT_POOP_MANA_CAP = 29; + +// The familiars the mist keeps aside, which hold their own state: Bumbo, Damocles and the abyss locusts. +static bool is_mist_kept_familiar(int variant) +{ + return variant == Entity_Familiar::BUMBO || variant == Entity_Familiar::DAMOCLES || + variant == Entity_Familiar::ABYSS_LOCUST; +} + +// 00759950 Gives the player a set of consumables, and (a real player) tells the HUD they changed. +void Entity_Player::restore_curse_mist_backup(const ConsumableData& backup) +{ + numCoins = backup.coins; + numKeys = backup.keys; + numBombs = backup.bombs; + hasGoldenKey = backup.isGoldenKey; + hasGoldenBomb = backup.isGoldenBomb; + numGigaBombs = backup.gigaBombs; + effectiveSoulCharge = backup.soulCharges; + effectiveBloodCharge = backup.bloodCharges; + poopMana = backup.poopMana; + if (isValid) ConsumableCountChanged(-1); +} + +// 007d8980 Puts the player under Curse of the Mist (the mineshaft's): it stops bleeding out and, a real player, sets its +// consumables and its Bumbo, Damocles and locusts aside (the locusts leave) to start from nothing. Its pockets and +// trinkets go aside too, then its stats are evaluated again. Keeper keeps his coin hearts aside. +void Entity_Player::AddCurseMistEffect() +{ + if (hasCurseMistEffect) return; + + if (backupPlayer && isValid) backupPlayer->AddCurseMistEffect(); + ClearEntityFlags(FLAG_BLEED_OUT); + cacheFlags |= CACHE_ALL; + bleedOutHealth = 0; + hasCurseMistEffect = true; + UpdateCostumes(); + + if (isValid) + { + consumablesBackup = {.bloodCharges = effectiveBloodCharge, + .bombs = numBombs, + .coins = numCoins, + .gigaBombs = numGigaBombs, + .keys = numKeys, + .poopMana = poopMana, + .soulCharges = effectiveSoulCharge, + .isGoldenBomb = hasGoldenBomb, + .isGoldenKey = hasGoldenKey}; + restore_curse_mist_backup({}); + curseMistFamiliars.clear(); + for (Entity* entity : entity_query(ENTITY_FAMILIAR, -1)) + { + if (!is_mist_kept_familiar(entity->variant)) continue; + + static_cast(entity)->store_backup(&curseMistFamiliars.emplace_back()); + if (entity->variant == Entity_Familiar::ABYSS_LOCUST) entity->Remove(); + } + } + + curseMistPocketItems = pocketItems; + pocketItems.fill({}); + curseMistTrinkets = trinkets; + trinkets.fill(0); + EvaluateItems(); + if (playerType != PLAYER_KEEPER) return; + + curseMistRedHearts = redHearts; + AddMaxHearts(0, false); +} + +// 007d8d20 Lifts Curse of the Mist: a real player gets its consumables back with what it found added (under their +// caps), and its kept familiars their state, the locusts spawned again, the nth kept one of a variant going to the nth +// such familiar (the last when fewer). Its pockets and trinkets come back, and Keeper's coin hearts. +void Entity_Player::RemoveCurseMistEffect() +{ + if (!hasCurseMistEffect) return; + + if (backupPlayer && isValid) backupPlayer->RemoveCurseMistEffect(); + cacheFlags |= CACHE_ALL; + hasCurseMistEffect = false; + UpdateCostumes(); + + PlayerManager& players = g_game->playerManager; + ConsumableData& backup = consumablesBackup; + if (isValid) + { + int coinCap = players.FirstCollectibleOwner(COLLECTIBLE_DEEP_POCKETS, LAZARUS_SHARE_CHECK) + ? MIST_DEEP_POCKETS_COIN_CAP + : MIST_CONSUMABLE_CAP; + int poopCap = players.FirstBirthrightOwner(PLAYER_BLUEBABY_B) ? MIST_BIRTHRIGHT_POOP_MANA_CAP + : MIST_POOP_MANA_CAP; + backup.coins = std::min(numCoins + backup.coins, coinCap); + backup.keys = std::min(numKeys + backup.keys, MIST_CONSUMABLE_CAP); + backup.bombs = std::min(backup.bombs + numBombs, MIST_CONSUMABLE_CAP); + backup.isGoldenKey = backup.isGoldenKey || hasGoldenKey; + backup.isGoldenBomb = backup.isGoldenBomb || hasGoldenBomb; + backup.gigaBombs = std::min(backup.gigaBombs + numGigaBombs, backup.bombs); + backup.soulCharges = std::min(effectiveSoulCharge + backup.soulCharges, MIST_CONSUMABLE_CAP); + backup.bloodCharges = std::min(backup.bloodCharges + effectiveBloodCharge, MIST_CONSUMABLE_CAP); + backup.poopMana = std::min(poopMana + backup.poopMana, poopCap); + restore_curse_mist_backup(backup); + } + + pocketItems = curseMistPocketItems; + trinkets = curseMistTrinkets; + if (isValid) ConsumableCountChanged(-1); + EvaluateItems(); + + std::map restored; + for (const FamiliarData& saved : curseMistFamiliars) + { + size_t index = restored[saved.variant]; + if (saved.variant == Entity_Familiar::ABYSS_LOCUST) + g_game->Spawn({.position = pos, + .spawner = this, + .subType = saved.subtype, + .type = ENTITY_FAMILIAR, + .variant = Entity_Familiar::ABYSS_LOCUST, + .seed = Random()}); + + std::vector familiars = entity_query(ENTITY_FAMILIAR, saved.variant); + if (!familiars.empty()) + { + auto& familiar = static_cast(*familiars[std::min(index, familiars.size() - 1)]); + familiar.RestoreState(saved); + familiar.AddEntityFlags(FLAG_APPEAR); + if (familiar.variant == Entity_Familiar::DAMOCLES) familiar.subtype = saved.subtype; + } + restored[saved.variant] = index + 1; + } + curseMistFamiliars.clear(); + if (playerType != PLAYER_KEEPER) return; + + AddMaxHearts(GetHeartLimit(false) - maxHearts, false); + redHearts = curseMistRedHearts; +} diff --git a/src/entity_player_room.cpp b/src/entity_player_room.cpp index 87edb2f..fe4c8f5 100644 --- a/src/entity_player_room.cpp +++ b/src/entity_player_room.cpp @@ -11,7 +11,6 @@ constexpr int TRINKET_DOOR_STOP = 124; constexpr int TRINKET_LIL_CLOT = 176; -constexpr int TRINKET_BETHS_ESSENCE = 182; constexpr int TRINKET_THE_TWINS = 183; constexpr int COLLECTIBLE_BROKEN_WATCH = 337; constexpr int COLLECTIBLE_DOG_TOOTH = 445; diff --git a/src/entity_player_tainted.cpp b/src/entity_player_tainted.cpp new file mode 100644 index 0000000..b978f84 --- /dev/null +++ b/src/entity_player_tainted.cpp @@ -0,0 +1,148 @@ +#include "entity_player_tainted.h" +#include "game.h" +#include "grid_entity_door.h" +#include "hud.h" +#include "manager.h" +#include "npc_ai.h" +#include "room.h" +#include "room_grid.h" +#include + +constexpr int INVENTORY_SLOTS = 8; +constexpr int INVENTORY_BIRTHRIGHT_SLOTS = 12; +constexpr float DROP_SEARCH_STEP = 40; +constexpr float PEDESTAL_DOOR_REACH = 70; +constexpr int DEAD_CAT_LIVES_MAX = 9; + +// 007d4150 How many items Tainted Isaac's inventory holds: 8, 12 with Birthright. +int Entity_Player::GetMaxInventorySize() +{ + return HasCollectible(COLLECTIBLE_BIRTHRIGHT) ? INVENTORY_BIRTHRIGHT_SLOTS : INVENTORY_SLOTS; +} + +// 00790530 Drops an owned collectible (passive Damocles as the active) onto a pedestal given or a new one beside the +// player, seeded by the item's generator. The pedestal takes the pool the item came from, an active's charge and data, +// and Dead Cat's lives the loss took (9 at most). The item is removed with modifiers ignored, from the first slot. +Entity_Pickup* Entity_Player::DropCollectible(int collectible, Entity_Pickup* existing, bool isRemoveFromForm) +{ + int shown = collectible == COLLECTIBLE_PASSIVE_DAMOCLES ? COLLECTIBLE_DAMOCLES : collectible; + + g_pickupIgnoreModifiers++; + if (existing) + { + existing->Morph(existing->type, existing->variant, shown, false, true, true); + existing->UpdateSprite(true); + } + else + { + uint32_t seed = GetCollectibleRNG(collectible).Next(); + Vector spot = room_free_pickup_position_find({pos, DROP_SEARCH_STEP}); + existing = static_cast(g_game->Spawn({.position = spot, .spawner = this, .subType = shown, + .type = ENTITY_PICKUP, .variant = PICKUP_COLLECTIBLE, + .seed = seed})); + } + auto entry = std::ranges::find_if(history.historyItems, [&](HistoryItem& item) + { return !item.isTrinket && item.id == collectible; }); + g_pickupIgnoreModifiers--; + existing->itemPoolType = entry != history.historyItems.end() ? entry->itemPoolType : 0; + + auto active = std::ranges::find_if(activeItems, [&](ActiveItemDesc& slot) { return slot.item == collectible; }); + if (active != activeItems.end()) + { + existing->charge = active->batteryCharge + active->charge; + existing->varData = active->varData; + } + int lives = deadCatLives; + existing->isTouched = true; + RemoveCollectible(collectible, true, ACTIVE_SLOT_PRIMARY, isRemoveFromForm); + if (collectible == COLLECTIBLE_DEAD_CAT && deadCatLives <= lives) + existing->charge = std::min(lives - deadCatLives, DEAD_CAT_LIVES_MAX); + return existing; +} + +// 007906f0 Drops the collectible at a history index, if the player still owns it, and takes it out of the history. +// The original's unused flag is gone. +Entity_Pickup* Entity_Player::DropCollectibleByHistoryIndex(int index, Entity_Pickup* existing) +{ + if (index < 0 || index >= (int)history.historyItems.size()) return nullptr; + HistoryItem& item = history.historyItems[index]; + if (item.isTrinket || item.id < 0 || collectibleCounts[item.id] <= 0) return nullptr; + + bool wasLocked = history.isLocked; + history.isLocked = true; + Entity_Pickup* dropped = DropCollectible(item.id, existing, false); + history.isLocked = wasLocked; + history.RemoveHistoryItemByIndex(index); + return dropped; +} + +// 00721c00 Takes the item at a history index out, Tainted Isaac's inventory following. A locked history keeps it. +// Whether it was removed. The original erases at a negative index. Here that removes nothing. +bool History::RemoveHistoryItemByIndex(int index) +{ + if (isLocked || index < 0 || index >= (int)historyItems.size()) return false; + + historyItems.erase(historyItems.begin() + index); + remove_index_refs(index); + g_game->hud.mark_all_slots_dirty(HISTORY_KEEP_ICONS, HISTORY_KEEP_ITEMS); + return true; +} + +// 00721eb0 Refills Tainted Isaac's inventory from the history: the first passives it can hold, in pickup order. +void inventory_rebuild(History& history) +{ + std::array& inventory = history.player->inventory; + int size = history.player->GetMaxInventorySize(); + int filled = 0; + + inventory.fill(-1); + for (int index = 0; index < (int)history.historyItems.size() && filled < size; index++) + { + HistoryItem& item = history.historyItems[index]; + if (!item.isTrinket && history.player->CanAddCollectibleToInventory(item.id)) inventory[filled++] = index; + } +} + +// The Tainted Isaac part of 006e8ae0: with a full inventory, the item held up is added first, then the inventory's +// first item goes onto the pedestal and the others move up a slot. A pedestal by a door moves off it. Whether the +// items were exchanged. +bool tainted_isaac_pedestal_swap(Entity_Pickup& pickup, Entity_Player& player) +{ + std::array& inventory = player.inventory; + + player.FlushQueueItem(); + if (inventory[player.GetMaxInventorySize() - 1] < 0) return false; + if (!player.DropCollectibleByHistoryIndex(inventory[0], &pickup)) return false; + std::shift_right(inventory.begin(), inventory.end(), 1); + inventory[0] = -1; + + auto isNear = [&](GridEntity_Door* door) + { return door && vector_length_squared(vector_sub(door->Position(), player.pos)) < PEDESTAL_DOOR_REACH * PEDESTAL_DOOR_REACH; }; + if (std::ranges::any_of(g_game->room->doors, isNear)) pickup.gridRepositionState = 1; + return true; +} + +// The Tainted Isaac part of 007cf610: a player becoming him keeps the first passives his inventory holds and loses +// the later ones, then the inventory is rebuilt. The original reads the count of a procedural item before its list. +// Here a procedural item is kept. +void tainted_isaac_inventory_trim(Entity_Player& player) +{ + History& history = player.history; + int kept = player.GetMaxInventorySize(); + + history.isLocked = true; + for (auto item = history.historyItems.begin(); item != history.historyItems.end();) + { + bool isHeld = !item->isTrinket && item->id >= 0 && player.CanAddCollectibleToInventory(item->id); + if (!isHeld || kept > 0) + { + if (isHeld) kept--; + item++; + continue; + } + if (player.collectibleCounts[item->id] > 0) player.RemoveCollectible(item->id, true, ACTIVE_SLOT_PRIMARY, true); + item = history.historyItems.erase(item); + } + history.isLocked = false; + inventory_rebuild(history); +} diff --git a/src/entity_player_tainted.h b/src/entity_player_tainted.h new file mode 100644 index 0000000..be42610 --- /dev/null +++ b/src/entity_player_tainted.h @@ -0,0 +1,10 @@ +#pragma once + +#include "entity_pickup.h" +#include "entity_player.h" + +// Tainted Isaac's inventory: the pedestal swap of a full inventory (006e8ae0), and the passives a new Tainted Isaac +// keeps (007cf610) with the inventory rebuilt from the history (00721eb0). +bool tainted_isaac_pedestal_swap(Entity_Pickup& pickup, Entity_Player& player); +void tainted_isaac_inventory_trim(Entity_Player& player); +void inventory_rebuild(History& history); diff --git a/src/entity_player_weapons.cpp b/src/entity_player_weapons.cpp index aaf1c0b..ab37df9 100644 --- a/src/entity_player_weapons.cpp +++ b/src/entity_player_weapons.cpp @@ -77,13 +77,11 @@ constexpr float TECH_X_RING_LIFT = -20; constexpr int COLLECTIBLE_BRIMSTONE_WEAPON = 118; constexpr int COLLECTIBLE_CURSED_EYE_WEAPON = 316; constexpr int COLLECTIBLE_DEAD_TOOTH = 446; -constexpr int COLLECTIBLE_EVIL_EYE = 410; constexpr int COLLECTIBLE_EYE_SORE = 558; constexpr int COLLECTIBLE_INNER_EYE = 2; constexpr int COLLECTIBLE_LARGE_ZIT = 502; constexpr int COLLECTIBLE_NEPTUNUS = 597; constexpr int COLLECTIBLE_THE_WIZ = 358; -constexpr int COLLECTIBLE_TRACTOR_BEAM = 397; constexpr int NULLITEM_DARK_ARTS = 111; // The items GetWeaponModifiers turns into modifier bits, in the order it asks. diff --git a/src/entity_slot.cpp b/src/entity_slot.cpp index d0d5aa4..45c3b9b 100644 --- a/src/entity_slot.cpp +++ b/src/entity_slot.cpp @@ -1,53 +1,101 @@ #include "entity_slot.h" +#include "boss_ai.h" #include "entity_config.h" +#include "entity_bomb.h" +#include "entity_effect_combat.h" #include "entity_pickup.h" +#include "entity_player.h" #include "game.h" +#include "grid_entity_door.h" #include "log.h" #include "manager.h" +#include "npc_basement.h" +#include "npc_caves.h" +#include "persistent_game_data.h" #include "room.h" +#include "room_grid.h" +#include "room_render.h" +#include #include -// Lua's SlotVariant: the machines and beggars. -enum SlotVariant : int -{ - SLOT_MACHINE = 1, - SLOT_BLOOD_DONATION_MACHINE, - SLOT_FORTUNE_TELLING_MACHINE, - SLOT_BEGGAR, - SLOT_DEVIL_BEGGAR, - SLOT_SHELL_GAME, - SLOT_KEY_MASTER, - SLOT_DONATION_MACHINE, - SLOT_BOMB_BUM, - SLOT_SHOP_RESTOCK_MACHINE, - SLOT_GREED_DONATION_MACHINE, - SLOT_MOMS_DRESSER, - SLOT_BATTERY_BUM, - SLOT_ISAAC_SECRET, - SLOT_HELL_GAME, - SLOT_CRANE_GAME, - SLOT_CONFESSIONAL, - SLOT_ROTTEN_BEGGAR, - SLOT_REVIVE_MACHINE -}; - -// The event counters the donation machines show (DONATION_MACHINE_COUNTER, GREED_DONATION_MACHINE_COUNTER). -constexpr int EVENT_DONATION_MACHINE = 20; -constexpr int EVENT_GREED_DONATION_MACHINE = 115; - -// The run's state flags of a broken or jammed donation machine. +// The run's state flags of a broken or jammed donation machine, and of one blown up. constexpr int GAME_STATE_DONATION_SLOT_BROKEN = 17; constexpr int GAME_STATE_DONATION_SLOT_JAMMED = 18; +constexpr int GAME_STATE_DONATION_SLOT_BLOWN = 30; constexpr int GAME_STATE_GREED_SLOT_JAMMED = 34; -// The animations a jammed donation machine plays, one at random. +// The animations a jammed donation machine plays, one at random, and the shell a shell game pays from. constexpr std::array COIN_JAM_ANIMATIONS = {"CoinJam", "CoinJam2", "CoinJam3", "CoinJam4"}; +constexpr std::array SHELL_PRIZE_ANIMATIONS = {"Shell1Prize", "Shell2Prize", "Shell3Prize"}; + +// The prizes a shell game and the Hell Game hide (a collectible now and then), the chests the Key Master pays, the +// food a beggar gives, and the trinkets a Rotten Beggar may give. +constexpr int PRIZE_SPIDERS = 0; +constexpr int PRIZE_COLLECTIBLE = PICKUP_COLLECTIBLE; +constexpr std::array SHELL_GAME_PRIZES = {PICKUP_HEART, PICKUP_COIN, PICKUP_KEY, PICKUP_BOMB}; +constexpr std::array HELL_GAME_PRIZES = {PICKUP_HEART, PICKUP_COIN, PICKUP_KEY, + PICKUP_BOMB, PICKUP_TAROTCARD, PRIZE_SPIDERS}; +constexpr std::array KEY_MASTER_CHESTS = {PICKUP_CHEST, PICKUP_LOCKEDCHEST, PICKUP_REDCHEST}; +constexpr std::array ROTTEN_BEGGAR_TRINKETS = {TRINKET_FISH_HEAD, TRINKET_FISH_TAIL, TRINKET_BOBS_BLADDER, + TRINKET_ROTTEN_PENNY}; +constexpr std::array BATTERY_BUM_CHARGES = {1, 1, 1, 2, 2, 3}; +constexpr int BEGGAR_FOOD_FIRST = 22; +constexpr int BEGGAR_FOOD_COUNT = 5; + +// Which shell game layer shows each prize, for the layers that do not always show. +constexpr std::array SHELL_PRIZE_LAYERS = {PRIZE_SPIDERS, PICKUP_BOMB, PICKUP_HEART, PICKUP_KEY, + PICKUP_COIN, -1, PICKUP_TAROTCARD, PRIZE_COLLECTIBLE}; +constexpr int SHELL_ALWAYS_LAYER = 5; + +// The slot machine's prizes (rolled from 3) and the reels each shows. +enum SlotMachinePrize : int +{ + SLOT_PRIZE_NONE = 0, + SLOT_PRIZE_FLY = 3, + SLOT_PRIZE_BOMBS, + SLOT_PRIZE_HEARTS, + SLOT_PRIZE_HEARTS2, + SLOT_PRIZE_KEYS, + SLOT_PRIZE_PILLS, + SLOT_PRIZE_DOLLAR, + SLOT_PRIZE_PORTABLE_SLOT, + SLOT_PRIZE_COINS, + SLOT_PRIZE_COINS2, + SLOT_PRIZE_COINS3 +}; +constexpr std::array SLOT_MACHINE_REELS = {0, 2, 6, 6, 4, 5, 1, 7, 3, 3, 3}; + +// The Bomb Bum's prizes. +constexpr int BOMB_BUM_COINS = 1; +constexpr int BOMB_BUM_HEARTS = 2; +constexpr int BOMB_BUM_ITEM = 3; + +// The achievements donations unlock, and the counts that unlock them. +constexpr std::array, 10> DONATION_UNLOCKS = {{{10, 134}, + {20, 151}, + {50, 135}, + {100, 152}, + {150, 136}, + {200, 153}, + {400, 137}, + {600, 154}, + {900, 59}, + {999, 138}}}; +constexpr int ACHIEVEMENT_BLOOD_BAG = 147; +constexpr int ACHIEVEMENT_BONE_HEARTS = 391; +constexpr int ACHIEVEMENT_ROTTEN_HEARTS = 411; + +// The pedestals a slot's collectible stands on. +constexpr int FORTUNE_PEDESTAL = 1; +constexpr int BLOOD_DONATION_PEDESTAL = 2; +constexpr int SLOT_MACHINE_PEDESTAL = 3; +constexpr int CONFESSIONAL_PEDESTAL = 15; -constexpr int SLOT_STATE_IDLE = 1; -constexpr int SLOT_STATE_JAMMED = 3; constexpr int REVIVE_MACHINE_EXCLUDED_ROOM = -20; constexpr int DIGIT_BASE = 10; constexpr int HUNDREDS = 100; +constexpr int COUNTER_LIMIT = 1000; +constexpr int COUNTER_FULL = 999; constexpr float MACHINE_OFFSET_Y = -8; constexpr float BEGGAR_OFFSET_Y = 8; constexpr float BLOOD_MACHINE_OFFSET_X = -5; @@ -57,6 +105,123 @@ constexpr float MACHINE_DEPTH = 0.75f; constexpr int HELL_GAME_PRIZE_LAYER = 7; constexpr int CRANE_GAME_PRIZE_LAYER = 2; +constexpr int APPEAR_POOF_FRAMES = 3; +constexpr int POOF_MACHINE = 3; +constexpr int POOF_BEGGAR = 2; +constexpr float SLOT_FRICTION = 0.8f; +constexpr int PAY_FRAMES = 30; +constexpr int BLOOD_PAY_COOLDOWN = 15; +constexpr float VERSUS_BLOOD_DAMAGE = 8; +constexpr int COIN_FRAMES = 15; +constexpr int COUNTER_DONE_FRAMES = 20; +constexpr int TOUCH_FRAMES = 4; +constexpr int ENEMY_TYPE_FIRST = 10; +constexpr int TOUCH_SLOWDOWN = 10; +constexpr int COIN_INSERT2_TOUCHES = 61; +constexpr int COIN_INSERT3_TOUCHES = 121; +constexpr int TROLL_BOMB_FRAMES = 30; +constexpr uint32_t TROLL_BOMB_INTERVAL = 5; +constexpr int GRID_PATH_MARK = 900; + +constexpr int THROW_TRIES = 10; +constexpr float THROW_SPEED = 5; +constexpr float THROW_LIFT = 0.2f; +constexpr float THROW_DROP = 3; +constexpr float THROW_REACH = 7; +constexpr float SHELL_OFFSET_X = 37; +constexpr float SHELL_OFFSET_Y = 5; +constexpr float SHELL_THROW = 4; +constexpr float SHELL_SCATTER = 2; +constexpr float SHELL_SIDE_REACH = 20; +constexpr float SLOT_SPIDER_HEIGHT = -30; +constexpr float BUTTER_BEAN_SLOT_RADIUS = 9; +constexpr float ROTTEN_FART_RADIUS = 85; +constexpr float ROTTEN_BUTTER_BEAN_RADIUS = 120; +constexpr float KARMA_BEGGAR_DROP = 40; +constexpr float KEY_MASTER_ITEM_DROP = 80; +constexpr float KEY_MASTER_CHEST_SPEED = 5; + +constexpr uint32_t BREAK_ODDS = 50; +constexpr uint32_t PRIZE_ROLL = 21; +constexpr uint32_t LUCKY_PRIZE_ROLL = 15; +constexpr uint32_t PRIZE_REROLL = 10; +constexpr uint32_t DOLLAR_KEEP = 3; +constexpr uint32_t PORTABLE_SLOT_KEEP = 4; +constexpr float FORTUNE_CHANCE = 0.65f; +constexpr float HARD_FORTUNE_CHANCE = 0.85f; +constexpr float LUCKY_FORTUNE = 0.46f; +constexpr float SEED_FORTUNE_CHANCE = 0.002f; +constexpr float CONFESSIONAL_CHANCE = 0.3f; +constexpr float HARD_CONFESSIONAL_CHANCE = 0.25f; +constexpr float LUCKY_CONFESSIONAL = 1.5f; +constexpr float ANGEL_CHANCE_BLESSING = 0.1f; +constexpr int CRANE_WIN = 25; +constexpr int CRANE_LUCK = 5; +constexpr int CRANE_PRIZES = 3; +constexpr int BETHS_ESSENCE_ODDS = 4; +constexpr int DONATION_JAM_ODDS = 3000; +constexpr int DONATION_LIMIT = 7; +constexpr int DONATION_LIMIT_RANGE = 9; +constexpr int DONATION_PAYOUT_DIMES = 15; +constexpr int BATTERY_BUM_CHARGE_FRAMES = 20; +constexpr float BATTERY_SPARK_RISE = -24; + +constexpr float KARMA_COINS = 0.4f; +constexpr float KARMA_HEARTS = 0.8f; +constexpr float KARMA_LUCK = 0.95f; +constexpr float KARMA_RESTOCK_LUCK = 0.15f; + +constexpr int BLOOD_TRAILS = 5; +constexpr int BLOOD_TRAIL_SPLATS = 4; +constexpr float BLOOD_TRAIL_MIN = 30; +constexpr float BLOOD_TRAIL_RANGE = 20; +constexpr float BLOOD_TRAIL_FLAT = 0.65f; +constexpr float BLOOD_TRAIL_START = 0.2f; +constexpr float BLOOD_TRAIL_SCALE = 2; +constexpr float BLOOD_TRAIL_TURN = 40; +constexpr float BLOOD_TRAIL_SHRINK = 0.9f; +constexpr float BLOOD_TRAIL_FADE = 0.6f; +constexpr float SLOT_BLOOD_RISE = -10; +constexpr float SLOT_BLOOD_DEPTH = 5; +constexpr float BLOOD_SPLASH_RISE = -2; +constexpr int BLOOD_EXPLOSION_MACHINE = 4; +constexpr int SLOT_BLOOD_SPLASH = 3; + +constexpr ColorMod ROTTEN_SPLAT_COLOR = {{0.7f, 0.9f, 0.65f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr float ROTTEN_SPLAT_MIN = 0.2f; +constexpr float ROTTEN_SPLAT_RANGE = 0.4f; +constexpr float ROTTEN_PARTICLE_SPEED = 2; +constexpr float ROTTEN_PARTICLE_HEIGHT = 100000; + +constexpr float COLLECTIBLE_SPOT_STEP = 40; +constexpr float COLLECTIBLE_SPOT_CLEARANCE = 400; +constexpr float COLLECTIBLE_DOOR_CLEARANCE = 2500; +constexpr int COLLECTIBLE_SPOT_ROWS = 3; + +// What a broken slot leaves: its chances of a pill or trinket thrown slowly, of a chest, of coins, a heart, a key or a +// bomb in each stack, and the drop trinkets that may add their pickup. +constexpr float BREAK_DROP_SLOW = 0.4f; +constexpr float BREAK_CHEST_CHANCE = 0.01f; +constexpr float BREAK_COINS = 0.35f; +constexpr float BREAK_HEARTS = 0.55f; +constexpr float BREAK_KEYS = 0.7f; +constexpr int BREAK_TRINKET_SHIFT = 27; +constexpr uint32_t BREAK_TRINKET_CHANCE = 33; +constexpr std::array, 5> BREAK_DROP_TRINKETS = {{{TRINKET_ACE_OF_SPADES, PICKUP_TAROTCARD}, + {TRINKET_SAFETY_CAP, PICKUP_PILL}, + {TRINKET_CHILDS_HEART, PICKUP_HEART}, + {TRINKET_MATCH_STICK, PICKUP_BOMB}, + {TRINKET_RUSTED_KEY, PICKUP_KEY}}}; + +// Restarts an overlay animation from its first frame. +static void overlay_restart(ANM2& sprite, std::string_view name) +{ + if (!sprite.SetOverlayAnimation(name, SWITCH_KEEP_FRAME)) return; + + sprite.overlayAnimState.Rewind(); + sprite.overlayAnimState.isPlaying = true; +} + // Whether the run counts toward achievements (Game::AchievementUnlocksDisallowed 00705080, which Game does not declare // yet): not on a custom seed, a seed or mod that blocks them, or a rerun. static bool achievements_disallowed() @@ -66,6 +231,117 @@ static bool achievements_disallowed() Manager::AchievementUnlocksDisallowed() || game.isRerun; } +// The beggars, which pay in their own animations and leave or die as bums do. +static bool is_beggar(int variant) +{ + return variant == SLOT_BEGGAR || variant == SLOT_DEVIL_BEGGAR || variant == SLOT_KEY_MASTER || + variant == SLOT_BOMB_BUM || variant == SLOT_BATTERY_BUM || variant == SLOT_ROTTEN_BEGGAR; +} + +// The velocity a slot throws a pickup at: a random direction (from the RNG, or the global one without it) pushed +// down, tried up to ten times until the way from the slot is clear. +static Vector throw_velocity_get(const Vector& from, RNG* rng) +{ + Vector velocity{}; + for (int i = 0; i < THROW_TRIES; i++) + { + Vector direction = rng ? RandomVector(rng->Next()) : random_direction(); + velocity = vector_make(direction.x * THROW_SPEED, direction.y * THROW_SPEED * THROW_LIFT + THROW_DROP); + if (room_check_line(from, vector_add(from, vector_scale(velocity, THROW_REACH)), LINE_MODE_CELL, 0)) break; + } + return velocity; +} + +// Game::ShowFortuneText 009807a0: a random line of a fortune category on the fortune paper. +static void fortune_show(const char* category) +{ + reconstruction_missing(category[8] == 'S' ? "Game::ShowFortuneText 009807a0 (Fortune_Seeds)" + : "Game::ShowFortuneText 009807a0 (Fortune_General)"); +} + +// Room::ShopRestockFull 00815ae0: restocks every shop item in the room. +static void room_shop_restock_full() +{ + reconstruction_missing("Room::ShopRestockFull 00815ae0"); +} + +// A Battery Bum's charge (the timer callback 0065d930 and FUN_007919c0): one charge to its player's active items, +// then their overcharge. +static void battery_bum_charge(Entity_Effect* timer) +{ + Entity* parent = timer->parent; + if (!parent || parent->type != ENTITY_PLAYER) return; + + Entity_Player& player = *parent->ToPlayer(); + int charge = 1; + int given = 0; + for (bool isOvercharge : {false, true}) + for (int slot = 0; slot < ACTIVE_SLOT_COUNT && charge >= 1; slot++) + { + given += player.AddActiveCharge(charge, slot, false, isOvercharge, false); + charge -= given; + } +} + +// 00813460 Room::get_random_pickup_position: a free spot a random distance out from the room's center, up to its +// larger side. +Vector room_pickup_position_random(bool isAvoidActiveEntities, bool isAllowPits) +{ + Room& room = *g_game->room; + float width = room.bottomRightPos.x - room.topLeftPos.x; + float height = room.bottomRightPos.y - room.topLeftPos.y; + float reach = std::max(width, height) * random_unit(); + Vector center = vector_make(width * 0.5f + room.topLeftPos.x, height * 0.5f + room.topLeftPos.y); + return room_free_pickup_position_find({.position = center, + .step = reach, + .isAvoidActiveEntities = isAvoidActiveEntities, + .isAllowPits = isAllowPits}); +} + +// 006eeaa0 Isaac::GetCollectibleSpawnPosition: where a collectible appears below a spot, a row or two down on open +// floor clear of other collectibles and slots, else the nearest free spot. One near a door moves on. +Vector collectible_spawn_position(Vector target) +{ + Room& room = *g_game->room; + Vector spot = target; + bool isFree = false; + for (int row = 1; row < COLLECTIBLE_SPOT_ROWS; row++) + { + Vector below = vector_make(target.x, (float)row * GRID_CELL_SIZE + target.y); + int column = (int)((below.x - GRID_ORIGIN_X) / GRID_CELL_SIZE + 0.5f); + int line = (int)((below.y - GRID_ORIGIN_Y) / GRID_CELL_SIZE + 0.5f); + if (column >= 0 && column < room.gridWidth && line >= 0 && line < room.gridHeight) + { + int index = room.gridWidth * line + column; + GridEntity* grid = index < ROOM_GRID_CELLS ? room.gridEntities[index] : nullptr; + bool isBlocking = + grid && (grid->collisionClass != COLLISION_NONE || grid->type == GRID_SPIKES || + grid->type == GRID_TRAPDOOR || grid->type == GRID_STAIRS || grid->type == GRID_SPIKES_ONOFF); + if (isBlocking) break; + } + + spot = below; + isFree = true; + for (Entity* entity : room.entityList.updateEL) + { + bool isBlocker = (entity->type == ENTITY_PICKUP && entity->variant == PICKUP_COLLECTIBLE) || + (entity->type == ENTITY_SLOT && !entity->isDead); + if (isBlocker && vector_length_squared(vector_sub(entity->pos, below)) < COLLECTIBLE_SPOT_CLEARANCE) + isFree = false; + } + } + if (!isFree) spot = room_free_pickup_position_find({.position = spot}); + + for (GridEntity_Door* door : room.doors) + { + if (!door) continue; + Vector doorPosition = room.GetGridPosition(door->gridIndex); + if (vector_length_squared(vector_sub(doorPosition, spot)) < COLLECTIBLE_DOOR_CLEARANCE) + return room_free_pickup_position_find({.position = spot, .step = COLLECTIBLE_SPOT_STEP}); + } + return spot; +} + // 0065d200 Starts a slot from its config's sprite, sized and offset for its kind. The donation machines show their // save's count and break or jam as the run left them, the dresser appears on a first visit, and the Revive Machine // only stays in co-op. In Greed mode the blood donation machine is a devil beggar. @@ -125,16 +401,16 @@ void Entity_Slot::Init(int entityType, int entityVariant, int entitySubType, uin { posOffset.y = MACHINE_OFFSET_Y; sizeMulti = vector_make(MACHINE_WIDTH, MACHINE_DEPTH); - counter_show(persistentData->eventCounters[EVENT_DONATION_MACHINE]); + counter_show(persistentData->eventCounters[EVENT_COUNTER_DONATIONS]); bool isOnline = g_manager->netplayManager.is_online(); - bool isBroken = g_game->GetStateFlag((GameStateFlag)GAME_STATE_DONATION_SLOT_BROKEN) || - (isOnline ? g_game->challenge != 0 || g_game->dailyChallenge._id != 0 - : achievements_disallowed()); + bool isBroken = + g_game->GetStateFlag((GameStateFlag)GAME_STATE_DONATION_SLOT_BROKEN) || + (isOnline ? g_game->challenge != 0 || g_game->dailyChallenge._id != 0 : achievements_disallowed()); if (isBroken) Remove(); if (g_game->GetStateFlag((GameStateFlag)GAME_STATE_DONATION_SLOT_JAMMED)) { sprite.Play(COIN_JAM_ANIMATIONS[Random() & 3]); - state = SLOT_STATE_JAMMED; + state = SLOT_STATE_BROKEN; } AddEntityFlags(FLAG_NO_KNOCKBACK); break; @@ -142,12 +418,12 @@ void Entity_Slot::Init(int entityType, int entityVariant, int entitySubType, uin case SLOT_GREED_DONATION_MACHINE: posOffset.y = MACHINE_OFFSET_Y; sizeMulti = vector_make(MACHINE_WIDTH, MACHINE_DEPTH); - counter_show(persistentData->eventCounters[EVENT_GREED_DONATION_MACHINE]); + counter_show(persistentData->eventCounters[EVENT_COUNTER_GREED_DONATIONS]); if (achievements_disallowed() && !g_manager->netplayManager.is_online()) Remove(); if (g_game->GetStateFlag((GameStateFlag)GAME_STATE_GREED_SLOT_JAMMED)) { sprite.Play(COIN_JAM_ANIMATIONS[Random() & 3]); - state = SLOT_STATE_JAMMED; + state = SLOT_STATE_BROKEN; } break; case SLOT_SHOP_RESTOCK_MACHINE: @@ -193,32 +469,6 @@ void Entity_Slot::Render(const Vector& offset) prizeAnm2.Render(SpriteDraw{renderPosition, {}, {}}); } -// The rest of Entity_Slot is not reconstructed yet. - -// 0065d950 -void Entity_Slot::Update() -{ - reconstruction_missing("Entity_Slot::Update 0065d950"); -} - -// 00664560 -bool Entity_Slot::TakeDamage(float, uint64_t, const EntityRef&, int) -{ - reconstruction_missing("Entity_Slot::TakeDamage 00664560"); -} - -// 006627e0 -bool Entity_Slot::HandleCollision(Entity*, bool) -{ - reconstruction_missing("Entity_Slot::HandleCollision 006627e0"); -} - -// 00663aa0 -void Entity_Slot::spawn_break_drops() -{ - reconstruction_missing("Entity_Slot::spawn_break_drops 00663aa0"); -} - // 00665500 Sets the collectible a slot pays out, shown on the Hell Game's prize layer or the Crane Game's glass (a // question mark under Curse of the Blind). void Entity_Slot::SetPrizeType(int collectibleId) @@ -236,3 +486,1621 @@ void Entity_Slot::SetPrizeType(int collectibleId) sprite.LoadGraphics(); } } + +// 006657a0 (an overload Ghidra names Entity_Slot::HandleCollision) Throws pickups out of the slot, each at a velocity +// drawn from the RNG unless one is given. +void Entity_Slot::drops_spawn(const SlotDrop& drop) +{ + for (int i = 0; i < drop.count; i++) + { + Vector thrown = throw_velocity_get(pos, drop.rng); + uint32_t seed = dropRNG.Next(); + g_game->Spawn({.position = vector_add(pos, drop.offset), + .velocity = vector_is_zero(drop.velocity) ? thrown : drop.velocity, + .subType = drop.subType, + .type = ENTITY_PICKUP, + .variant = drop.variant, + .seed = seed}); + } +} + +// The slot blows up: an explosion, its break drops, and its death animation. +void Entity_Slot::explode() +{ + g_game->Spawn({.position = pos, .type = ENTITY_EFFECT, .variant = EFFECT_BOMB_EXPLOSION, .seed = Random()}); + spawn_break_drops(); + state = SLOT_STATE_BROKEN; + sprite.Play("Death"); +} + +// A paid out beggar teleports away. +void Entity_Slot::leave() +{ + state = SLOT_STATE_GONE; + sprite.Play("Teleport"); +} + +// Appearing: a poof the first frame of a slot that does not play an appear animation, shown after three frames, or +// its appear animation played to the end (where the Greed donation machine shows its count). True while it holds the +// rest of the update. +bool Entity_Slot::appear_update() +{ + if (sprite.GetAnimation() != "Appear") + { + if (timeout == 0) + { + int poof = is_beggar(variant) ? POOF_BEGGAR : POOF_MACHINE; + uint32_t seed = Random(); + g_game->Spawn( + {.position = pos, .subType = poof, .type = ENTITY_EFFECT, .variant = EFFECT_POOF01, .seed = seed}); + } + timeout++; + if (timeout < APPEAR_POOF_FRAMES) return true; + + isVisible = true; + state = SLOT_STATE_IDLE; + return true; + } + + sprite.Update(); + if (!sprite.IsFinished()) return true; + + state = SLOT_STATE_IDLE; + if (sprite.animState.animData) counter_show(persistentData->eventCounters[EVENT_COUNTER_GREED_DONATIONS]); + return true; +} + +// Slots hold their spot, but for a broken one that is no machine, which slides to a stop. A broken restock machine +// counts down its last restock. A restock machine that ends its wiggle restocks the shop, and after five may blow up. +void Entity_Slot::movement_update() +{ + if (targetPosition.x == 0 && targetPosition.y == 0) + { + targetPosition = pos; + velocity = {}; + } + + bool isMachine = variant == SLOT_SHELL_GAME || variant == SLOT_HELL_GAME || variant == SLOT_DONATION_MACHINE || + variant == SLOT_GREED_DONATION_MACHINE; + if (state != SLOT_STATE_BROKEN || isMachine) velocity = vector_sub(targetPosition, pos); + friction *= SLOT_FRICTION; + if (state == SLOT_STATE_BROKEN) + { + entityGridCollisionClass = GRIDCOLL_GROUND; + if (variant == SLOT_SHOP_RESTOCK_MACHINE && triggerTimer != 0 && --triggerTimer == 0) room_shop_restock_full(); + } + if (variant != SLOT_SHOP_RESTOCK_MACHINE || !sprite.IsFinished("WiggleEnd")) return; + + room_shop_restock_full(); + donationValue = 0; + sprite.Play("Idle"); + if (++triggerTimer <= 4) return; + + dropRNG.Next(); + if (dropRNG._seed & 1) return; + triggerTimer = 0; + explode(); +} + +// The slot machine's spin ends: one in fifty it blows up, else it rolls its prize (luckier with Lucky Foot or the +// Poker Chip) and shows it on the reels, three different symbols for none. +void Entity_Slot::slot_machine_roll(Entity_Player& player) +{ + sprite.SetFrame("Prize", 0); + dropRNG.Next(); + if (dropRNG._seed % BREAK_ODDS == 0) return explode(); + + prizeType = 0; + bool isLucky = player.HasCollectible(COLLECTIBLE_LUCKY_FOOT) || + (player.HasTrinket(TRINKET_POKER_CHIP) && (dropRNG.Next(), (dropRNG._seed & 3) == 0)); + dropRNG.Next(); + prizeType = (int)(dropRNG._seed % (isLucky ? LUCKY_PRIZE_ROLL : PRIZE_ROLL)) + SLOT_PRIZE_FLY; + + if (prizeType == SLOT_PRIZE_DOLLAR) + { + dropRNG.Next(); + if (dropRNG._seed % PRIZE_REROLL >= DOLLAR_KEEP) prizeType = SLOT_PRIZE_COINS; + } + else if (prizeType == SLOT_PRIZE_PORTABLE_SLOT) + { + dropRNG.Next(); + if (dropRNG._seed % PRIZE_REROLL > PORTABLE_SLOT_KEEP) prizeType = SLOT_PRIZE_COINS; + } + else if (prizeType > SLOT_PRIZE_PORTABLE_SLOT && (dropRNG.Next(), dropRNG._seed % PRIZE_REROLL != 0)) prizeType++; + + if (prizeType == SLOT_PRIZE_KEYS && (dropRNG.Next(), dropRNG._seed % 3 == 0)) prizeType = SLOT_PRIZE_COINS; + bool isHearts = prizeType == SLOT_PRIZE_HEARTS || prizeType == SLOT_PRIZE_HEARTS2; + if (isHearts && player.HasTrinket(TRINKET_DAEMONS_TAIL)) + { + RNG& daemonsTail = player.GetTrinketRNG(TRINKET_DAEMONS_TAIL); + daemonsTail.Next(); + if (daemonsTail._seed % 5 != 0) prizeType = SLOT_PRIZE_COINS; + } + if (g_game->difficulty == DIFFICULTY_HARD && (dropRNG.Next(), (dropRNG._seed & 1) == 0)) + prizeType = SLOT_PRIZE_NONE; + + if (prizeType >= SLOT_PRIZE_FLY && prizeType <= SLOT_PRIZE_COINS3) + { + int reel = SLOT_MACHINE_REELS[prizeType - SLOT_PRIZE_FLY]; + for (int layer = 1; layer <= 3; layer++) sprite.SetLayerFrame(layer, reel); + return; + } + + std::array reels{}; + do + { + for (int& reel : reels) reel = (int)(dropRNG.Next() & 7); + } while (reels[0] == reels[1] && reels[1] == reels[2]); + for (int layer = 1; layer <= 3; layer++) sprite.SetLayerFrame(layer, reels[layer - 1]); + npc_sound_play(SOUND_SCAMPER, 1, 2, 1); +} + +// The Crane Game: its wiggle ends in a prize (one in four, better with the Poker Chip) or none. The prize drops its +// collectible and loads the next, three in all. Its Explosion event blows it up. +void Entity_Slot::crane_game_update(Entity_Player& player) +{ + if (sprite.IsFinished("Wiggle")) + { + dropRNG.Next(); + int roll = (int)(dropRNG._seed % HUNDREDS); + if (player.HasTrinket(TRINKET_POKER_CHIP)) roll -= CRANE_LUCK; + bool isWin = roll < CRANE_WIN; + sprite.Play(isWin ? "Prize" : "NoPrize"); + npc_sound_play(isWin ? SOUND_THUMBSUP : SOUND_THUMBS_DOWN, 1, 2, 1); + } + if (sprite.IsEventTriggered("Prize")) + { + uint32_t seed = dropRNG.Next(); + g_game + ->Spawn({.position = collectible_spawn_position(pos), + .subType = prizeCollectible, + .type = ENTITY_PICKUP, + .variant = PICKUP_COLLECTIBLE, + .seed = seed}) + ->Update(); + npc_sound_play(SOUND_SLOTSPAWN, 1, 2, 1); + SetPrizeType(g_game->itemPool.GetCollectible(POOL_CRANE_GAME, dropRNG._seed, 0, COLLECTIBLE_BUDDY_IN_A_BOX, 0)); + } + if (sprite.IsEventTriggered("Explosion")) explode(); + if (!sprite.IsFinished("Prize")) return; + + if (++donationValue < CRANE_PRIZES) return sprite.Play("Regenerate"); + state = SLOT_STATE_GONE; + sprite.Play("OutOfPrizes"); +} + +// The Confessional: its wiggle ends in a prize (three in ten, a quarter in hard mode, half again with Lucky Foot) or +// none. A prize may blow it up, may leave a devil deal's item (Redemption if it can) when none was taken, may take +// back a broken heart, give a soul or eternal heart, or lift the curses with an angel room's blessing. +void Entity_Slot::confessional_update(Entity_Player& player) +{ + if (sprite.IsPlaying("Wiggle")) + { + float chance = g_game->difficulty == DIFFICULTY_HARD ? HARD_CONFESSIONAL_CHANCE : CONFESSIONAL_CHANCE; + if (player.HasCollectible(COLLECTIBLE_LUCKY_FOOT)) chance *= LUCKY_CONFESSIONAL; + sprite.Play(dropRNG.RandomFloat() < chance ? "Prize" : "NoPrize"); + } + if (!sprite.IsEventTriggered("Prize")) return; + + if (dropRNG.RandomInt(20) == 0) + { + explode(); + return; + } + if (dropRNG.RandomInt(30) == 0) + { + Remove(); + g_game->Spawn({.position = pos, .type = ENTITY_EFFECT, .variant = EFFECT_BOMB_EXPLOSION, .seed = Random()}); + ItemPool& pool = g_game->itemPool; + int item = 0; + if (g_game->devilRoomDeals >= 1 && + pool.RemoveCollectible(COLLECTIBLE_REDEMPTION, REMOVE_AVAILABLE, REMOVE_APPLY)) + item = COLLECTIBLE_REDEMPTION; + else + { + int poolType = pool.GetPoolForRoom(ROOM_ANGEL, initSeed); + item = pool.GetCollectible((ItemPoolType)poolType, initSeed, 0, COLLECTIBLE_BIBLE, 0); + if (item == 0) return; + } + uint32_t seed = dropRNG.Next(); + auto* pickup = static_cast(g_game->Spawn( + {.position = pos, .subType = item, .type = ENTITY_PICKUP, .variant = PICKUP_COLLECTIBLE, .seed = seed})); + pickup->SetAlternatePedestal(CONFESSIONAL_PEDESTAL); + pickup->Update(); + return; + } + + if (player.brokenHearts > 0) + { + player.AddBrokenHearts(-1); + player.UseActiveItem({.item = COLLECTIBLE_NECRONOMICON, .flags = USE_NOANIM}); + npc_sound_play(SOUND_THUMBSUP, 1, 2, 1); + return; + } + + RNG& daemonsTail = player.GetTrinketRNG(TRINKET_DAEMONS_TAIL); + bool isDaemonsTail = player.HasTrinket(TRINKET_DAEMONS_TAIL); + if (dropRNG.RandomInt(2) == 0 && (!isDaemonsTail || daemonsTail.RandomInt(DAEMONS_TAIL_ODDS) == 0)) + { + player.AddSoulHearts(2, false); + npc_sound_play(SOUND_HOLY, 1, 2, 1); + return player.AnimateHappy(); + } + if (dropRNG.RandomInt(16) == 0 && (!isDaemonsTail || daemonsTail.RandomInt(DAEMONS_TAIL_ODDS) == 0)) + { + player.AddEternalHearts(1); + npc_sound_play(SOUND_SUPERHOLY, 1, 2, 1); + return player.AnimateHappy(); + } + g_game->RemoveCurses(UINT32_MAX); + g_game->angelRoomChance += ANGEL_CHANCE_BLESSING; + std::string_view blessing = string_table_translate(g_manager->stringTable, "#YOU_FEEL_BLESSED"); + g_game->hud.show_fortune_text_impl(std::string(blessing).c_str()); +} + +// What a slot does while it is not paying out: machines wiggle after taking a payment, broken ones show it, leaving +// beggars vanish, and a bombed Bomb Bum throws Troll Bombs once its animation shows the Prize event. +void Entity_Slot::idle_update() +{ + if (state == SLOT_STATE_PICK) + { + if (variant != SLOT_BOMB_BUM) return; + if (sprite.IsEventTriggered("Prize")) triggerTimer = TROLL_BOMB_FRAMES; + if (!sprite.IsFinished()) return; + state = SLOT_STATE_IDLE; + return sprite.Play("Idle"); + } + + bool isMachine = variant == SLOT_MACHINE || variant == SLOT_FORTUNE_TELLING_MACHINE || + variant == SLOT_BLOOD_DONATION_MACHINE || variant == SLOT_CRANE_GAME || + variant == SLOT_CONFESSIONAL; + if (state == SLOT_STATE_REWARD) + { + if (isMachine && sprite.IsFinished()) sprite.Play("Wiggle"); + if (variant == SLOT_ISAAC_SECRET) reconstruction_missing("Entity_Slot::Update 0065d950: Isaac's secret closet"); + } + else if (state == SLOT_STATE_BROKEN) + { + if ((isMachine || variant == SLOT_REVIVE_MACHINE) && + (sprite.animState.IsLoopingAnimation() || sprite.IsFinished())) + sprite.Play("Broken"); + } + else if (state == SLOT_STATE_GONE && variant != SLOT_CRANE_GAME) + { + entityCollisionClass = ENTCOLL_NONE; + if (sprite.IsEventTriggered("Disappear")) shadowSize = 0; + if (sprite.IsFinished()) Remove(); + } +} + +// The slot machine pays out a prize shown on its reels: a fly (a Pretty Fly one time in three), pickups, a fart with +// the Dollar or the Portable Slot, or coins. +void Entity_Slot::slot_machine_pay(Entity_Player& player, RNG& prizeRng, int count) +{ + if (sprite.GetAnimation() != "Prize") return; + + state = SLOT_STATE_IDLE; + if (prizeType == SLOT_PRIZE_FLY) + { + if (dropRNG.RandomInt(3) == 0) + { + player.AddPrettyFly(); + return player.AnimateHappy(); + } + Vector velocity = throw_velocity_get(pos, &prizeRng); + g_game->Spawn({.position = pos, .velocity = velocity, .type = ENTITY_FLY, .seed = dropRNG.Next()}); + return player.AnimateSad(); + } + + static constexpr std::array PICKUPS = {PICKUP_BOMB, PICKUP_HEART, PICKUP_HEART, PICKUP_KEY, PICKUP_PILL}; + if (prizeType >= SLOT_PRIZE_BOMBS && prizeType <= SLOT_PRIZE_PILLS) + { + npc_sound_play(SOUND_SLOTSPAWN, 1, 2, 1); + return drops_spawn({.rng = &prizeRng, .count = count, .variant = PICKUPS[prizeType - SLOT_PRIZE_BOMBS]}); + } + + if (prizeType == SLOT_PRIZE_DOLLAR || prizeType == SLOT_PRIZE_PORTABLE_SLOT) + { + npc_sound_play(SOUND_SLOTSPAWN, 1, 2, 1); + game_butter_bean_fart( + {.position = pos, .source = this, .radius = BUTTER_BEAN_SLOT_RADIUS, .isShowEffect = false}); + Remove(); + g_game->Spawn({.position = pos, .type = ENTITY_EFFECT, .variant = EFFECT_BOMB_EXPLOSION, .seed = Random()}); + bool isDollar = prizeType == SLOT_PRIZE_DOLLAR; + int item = isDollar ? COLLECTIBLE_DOLLAR : COLLECTIBLE_PORTABLE_SLOT; + auto* pickup = static_cast(g_game->Spawn({.position = pos, + .subType = item, + .type = ENTITY_PICKUP, + .variant = PICKUP_COLLECTIBLE, + .seed = dropRNG.Next()})); + if (!isDollar) g_game->itemPool.RemoveCollectible(COLLECTIBLE_PORTABLE_SLOT, REMOVE_ANY, REMOVE_APPLY); + pickup->itemPoolType = POOL_SHOP; + pickup->SetAlternatePedestal(SLOT_MACHINE_PEDESTAL); + pickup->Update(); + return; + } + + if (prizeType < SLOT_PRIZE_COINS || prizeType > SLOT_PRIZE_COINS3) return; + npc_sound_play(SOUND_SLOTSPAWN, 1, 2, 1); + int stacks = std::max((int)dropRNG.RandomInt(3), 1); + for (int i = 0; i < stacks; i++) drops_spawn({.rng = &prizeRng, .count = count, .variant = PICKUP_COIN}); +} + +// The blood donation machine pays: one time in a hundred Child's Heart, one in fifteen an IV Bag (or Blood Bag) as it +// blows up, else coins (fewer in hard mode, one at most for coin hearts, one more with PHD). It bleeds as it pays. +void Entity_Slot::blood_donation_pay(Entity_Player& player, RNG& prizeRng, int count) +{ + sprite.Play("Prize"); + if (!sprite.IsEventTriggered("Prize")) return; + + if (dropRNG.RandomInt(HUNDREDS) == 0 && g_game->itemPool.RemoveTrinket(TRINKET_CHILDS_HEART)) + { + Vector velocity = throw_velocity_get(pos, &prizeRng); + g_game->Spawn({.position = pos, + .velocity = velocity, + .subType = TRINKET_CHILDS_HEART, + .type = ENTITY_PICKUP, + .variant = PICKUP_TRINKET, + .seed = Random()}); + } + else if (dropRNG.RandomInt(15) == 0) + { + bool isIvBag = + dropRNG.RandomInt(2) != 0 && g_game->itemPool.is_collectible_available(COLLECTIBLE_IV_BAG, UNLOCK_CHECKED); + int item = COLLECTIBLE_IV_BAG; + if (!isIvBag && persistentData->Unlocked(ACHIEVEMENT_BLOOD_BAG)) item = COLLECTIBLE_BLOOD_BAG; + g_game->itemPool.RemoveCollectible(item, REMOVE_ANY, REMOVE_APPLY); + Remove(); + g_game->Spawn({.position = pos, .type = ENTITY_EFFECT, .variant = EFFECT_BOMB_EXPLOSION, .seed = Random()}); + auto* pickup = static_cast(g_game->Spawn({.position = pos, + .subType = item, + .type = ENTITY_PICKUP, + .variant = PICKUP_COLLECTIBLE, + .seed = dropRNG.Next()})); + pickup->SetAlternatePedestal(BLOOD_DONATION_PEDESTAL); + pickup->Update(); + } + else + { + int stacks = 0; + bool isBonus = false; + if (player.GetHealthType() != HEALTH_COIN) + { + stacks = std::max((int)dropRNG.RandomInt(game_is_hard_mode() ? 2 : 3), 1); + isBonus = player.HasCollectible(COLLECTIBLE_PHD); + } + else + { + stacks = (int)dropRNG.RandomInt(2); + RNG phd = rng_make(dropRNG._seed, 8); + isBonus = player.HasCollectible(COLLECTIBLE_PHD) && phd.RandomInt(4) == 0; + } + if (isBonus) stacks++; + for (int i = 0; i < stacks; i++) drops_spawn({.rng = &prizeRng, .count = count, .variant = PICKUP_COIN}); + } + if (!isExists) return; + + npc_sound_play(SOUND_BLOODBANK_SPAWN, 1, 2, 1); + Entity* blood = g_game->Spawn({.position = pos, + .subType = SLOT_BLOOD_SPLASH, + .type = ENTITY_EFFECT, + .variant = EFFECT_BLOOD_EXPLOSION, + .seed = Random()}); + blood->sprite.offset = vector_make(0, BLOOD_SPLASH_RISE); + blood->renderDepthOffset = SLOT_BLOOD_DEPTH; +} + +// The fortune machine pays: a fortune most of the time (more often in hard mode, less with luck), a seed's fortune one +// time in five hundred. Otherwise it may blow up, leave a Crystal Ball as it goes, or give a card, a trinket or a soul +// heart. +void Entity_Slot::fortune_pay(Entity_Player& player, RNG& prizeRng, int count) +{ + sprite.Play("Prize"); + if (!sprite.IsEventTriggered("Prize")) return; + + float chance = g_game->difficulty == DIFFICULTY_HARD ? HARD_FORTUNE_CHANCE : FORTUNE_CHANCE; + bool isLucky = player.HasCollectible(COLLECTIBLE_LUCKY_FOOT) || + (player.HasTrinket(TRINKET_POKER_CHIP) && dropRNG.RandomInt(5) == 0); + if (isLucky) chance *= LUCKY_FORTUNE; + float roll = dropRNG.RandomFloat(); + if (roll < chance) return fortune_show(roll >= SEED_FORTUNE_CHANCE ? "Fortune_General" : "Fortune_Seeds"); + + npc_sound_play(SOUND_SLOTSPAWN, 1, 2, 1); + if (dropRNG.RandomInt(20) == 0) return explode(); + if (dropRNG.RandomInt(30) == 0) + { + Remove(); + g_game->Spawn({.position = pos, .type = ENTITY_EFFECT, .variant = EFFECT_BOMB_EXPLOSION, .seed = Random()}); + auto* pickup = static_cast(g_game->Spawn({.position = pos, + .subType = COLLECTIBLE_CRYSTAL_BALL, + .type = ENTITY_PICKUP, + .variant = PICKUP_COLLECTIBLE, + .seed = dropRNG.Next()})); + pickup->SetAlternatePedestal(FORTUNE_PEDESTAL); + pickup->Update(); + return; + } + if (dropRNG.RandomInt(3) == 0) return drops_spawn({.rng = &prizeRng, .count = count, .variant = PICKUP_TAROTCARD}); + + bool isTrinket = + dropRNG.RandomInt(3) != 0 || (player.HasTrinket(TRINKET_DAEMONS_TAIL) && + player.GetTrinketRNG(TRINKET_DAEMONS_TAIL).RandomInt(DAEMONS_TAIL_ODDS) != 0); + if (!isTrinket) + return drops_spawn({.rng = &prizeRng, .count = count, .subType = HEART_SOUL, .variant = PICKUP_HEART}); + + Vector velocity = throw_velocity_get(pos, &prizeRng); + g_game->Spawn({.position = pos, + .velocity = velocity, + .type = ENTITY_PICKUP, + .variant = PICKUP_TRINKET, + .seed = dropRNG.Next()}); +} + +// The beggar pays: half the time a heart, key or bomb, else a card, or a collectible it leaves for (food, or from its +// own pool for the Lost). +void Entity_Slot::beggar_pay(Entity_Player& player, RNG& prizeRng, int count) +{ + sprite.Play("Prize"); + if (!sprite.IsEventTriggered("Prize")) return; + + npc_sound_play(SOUND_SLOTSPAWN, 1, 2, 1); + if (dropRNG.RandomInt(2) == 0) + { + bool isHeart = + dropRNG.RandomInt(3) == 0 && (!player.HasTrinket(TRINKET_DAEMONS_TAIL) || + player.GetTrinketRNG(TRINKET_DAEMONS_TAIL).RandomInt(DAEMONS_TAIL_ODDS) == 0); + int variantDropped = isHeart ? PICKUP_HEART : dropRNG.RandomInt(2) == 0 ? PICKUP_KEY : PICKUP_BOMB; + return drops_spawn({.rng = &prizeRng, .count = count, .variant = variantDropped}); + } + + int item = 0; + uint32_t seed = 0; + if (dropRNG.RandomInt(2) == 0) + { + if (dropRNG.RandomInt(2) != 0) + return drops_spawn({.rng = &prizeRng, .count = count, .variant = PICKUP_TAROTCARD}); + + item = BEGGAR_FOOD_FIRST + (int)dropRNG.RandomInt(BEGGAR_FOOD_COUNT); + PlayerManager& players = g_game->playerManager; + if (players.FirstPlayerByType(PLAYER_THELOST_B) || players.FirstBirthrightOwner(PLAYER_THELOST)) + item = g_game->itemPool.GetCollectible(POOL_BEGGAR, dropRNG.Next(), 0, 0, 0); + seed = dropRNG.Next(); + } + else + { + seed = dropRNG.Next(); + item = g_game->itemPool.GetCollectible(POOL_BEGGAR, dropRNG.Next(), 0, 0, 0); + } + g_game->Spawn({.position = collectible_spawn_position(pos), + .subType = item, + .type = ENTITY_PICKUP, + .variant = PICKUP_COLLECTIBLE, + .seed = seed}); + leave(); + g_game->SetStateFlag(LEVEL_STATE_BUM_LEFT, true); +} + +// The devil beggar pays: half the time a pill or card, else a trinket, or a devil beggar's collectible it leaves for. +void Entity_Slot::devil_beggar_pay(RNG& prizeRng, int count) +{ + sprite.Play("Prize"); + if (!sprite.IsEventTriggered("Prize")) return; + + npc_sound_play(SOUND_SLOTSPAWN, 1, 2, 1); + Vector velocity = throw_velocity_get(pos, &prizeRng); + if (dropRNG.RandomInt(2) == 0) + { + int variantDropped = dropRNG.RandomInt(2) == 0 ? PICKUP_PILL : PICKUP_TAROTCARD; + return drops_spawn({.rng = &prizeRng, .count = count, .variant = variantDropped}); + } + if (dropRNG.RandomInt(4) == 0) + { + g_game->Spawn({.position = pos, + .velocity = velocity, + .type = ENTITY_PICKUP, + .variant = PICKUP_TRINKET, + .seed = dropRNG.Next()}); + return; + } + + uint32_t seed = dropRNG.Next(); + int item = g_game->itemPool.GetCollectible(POOL_DEMON_BEGGAR, dropRNG.Next(), 0, 0, 0); + g_game->Spawn({.position = collectible_spawn_position(pos), + .subType = item, + .type = ENTITY_PICKUP, + .variant = PICKUP_COLLECTIBLE, + .seed = seed}); + leave(); + g_game->SetStateFlag(LEVEL_STATE_EVIL_BUM_LEFT, true); +} + +// A shell game shows what its picked shell hid: a win (one in three, luckier with Lucky Foot or the Poker Chip) gives +// its prize, a collectible it leaves for, or the Hell Game's blue spiders. A loss gives an attack fly or a spider. +void Entity_Slot::shell_game_pay(Entity_Player& player, RNG& prizeRng, int count) +{ + sprite.Play(SHELL_PRIZE_ANIMATIONS[shellGameAnimationIndex]); + if (sprite.IsEventTriggered("Prize")) + { + RNG& luckyFoot = player.GetCollectibleRNG(COLLECTIBLE_LUCKY_FOOT); + bool isWin = dropRNG.RandomInt(3) == 0 || + (player.HasCollectible(COLLECTIBLE_LUCKY_FOOT) && luckyFoot.RandomInt(3) == 0) || + (player.HasTrinket(TRINKET_POKER_CHIP) && luckyFoot.RandomInt(20) == 0); + float side = (float)(shellGameAnimationIndex - 1); + Vector offset = vector_make(side * SHELL_OFFSET_X, SHELL_OFFSET_Y); + bool isHell = variant == SLOT_HELL_GAME; + if (!isWin) + { + npc_sound_play(SOUND_ERROR_BUZZ, 1, 2, 1); + Vector velocity = vector_add(vector_make(side * SHELL_THROW, SHELL_THROW), + vector_scale(random_direction(), SHELL_SCATTER)); + if (isHell) Entity_NPC::ThrowSpider(vector_add(pos, offset), nullptr, {}, false, SLOT_SPIDER_HEIGHT); + else + g_game->Spawn({.position = vector_add(pos, offset), + .velocity = velocity, + .type = ENTITY_ATTACKFLY, + .seed = dropRNG.Next()}); + } + else + { + npc_sound_play(SOUND_SLOTSPAWN, 1, 2, 1); + int stacks = 1; + if (prizeType == PICKUP_COIN) stacks = (int)dropRNG.RandomInt(2) + 2; + else if (prizeType != PRIZE_COLLECTIBLE) stacks = std::max((int)dropRNG.RandomInt(3), 2); + + int subType = 0; + if (prizeType == PRIZE_SPIDERS) + for (int i = 0; i < stacks; i++) player.ThrowBlueSpider(vector_add(pos, offset), {}); + else if (prizeType == PRIZE_COLLECTIBLE) + { + int item = isHell ? prizeCollectible : COLLECTIBLE_SKATOLE; + uint32_t seed = dropRNG.Next(); + g_game->Spawn({.position = collectible_spawn_position(pos), + .subType = item, + .type = ENTITY_PICKUP, + .variant = PICKUP_COLLECTIBLE, + .seed = seed}); + if (isHell) g_game->itemPool.RemoveCollectible(prizeCollectible, REMOVE_ANY, REMOVE_APPLY); + leave(); + } + else + { + if ((prizeType == PICKUP_HEART && isHell) || prizeType == PICKUP_TAROTCARD) stacks = 1; + if (prizeType == PICKUP_HEART && isHell) subType = HEART_BLACK; + for (int i = 0; i < stacks; i++) + { + Vector velocity{}; + for (int tries = 0; tries < THROW_TRIES; tries++) + { + velocity = vector_add(vector_make(side * SHELL_THROW, SHELL_THROW), + vector_scale(random_direction(), SHELL_SCATTER)); + Vector end = vector_add(pos, vector_scale(velocity, THROW_REACH)); + if (room_check_line(vector_add(pos, offset), end, LINE_MODE_CELL, 0)) break; + } + drops_spawn({.rng = &prizeRng, + .offset = offset, + .velocity = velocity, + .count = count, + .subType = subType, + .variant = prizeType}); + } + } + } + } + if (!sprite.IsFinished()) return; + state = SLOT_STATE_IDLE; + sprite.Play("Idle"); +} + +// The Key Master pays: mostly a chest (always with a golden key), else Paper Clip or a Key Master's collectible, and +// leaves. +void Entity_Slot::key_master_pay(RNG& prizeRng) +{ + sprite.Play("Prize"); + if (!sprite.IsEventTriggered("Prize")) return; + + npc_sound_play(SOUND_SLOTSPAWN, 1, 2, 1); + if (dropRNG.RandomInt(8) != 0 && !isUnknown418) + { + Vector velocity = throw_velocity_get(pos, &prizeRng); + uint32_t seed = dropRNG.Next(); + int chest = KEY_MASTER_CHESTS[dropRNG.RandomInt(3)]; + g_game->Spawn({.position = pos, + .velocity = vector_scale(velocity, KEY_MASTER_CHEST_SPEED), + .type = ENTITY_PICKUP, + .variant = chest, + .seed = seed}); + return; + } + + Vector velocity = throw_velocity_get(pos, &prizeRng); + if (!isUnknown418 && dropRNG.RandomInt(2) == 0 && g_game->itemPool.RemoveTrinket(TRINKET_PAPER_CLIP)) + g_game->Spawn({.position = pos, + .velocity = velocity, + .spawner = this, + .subType = TRINKET_PAPER_CLIP, + .type = ENTITY_PICKUP, + .variant = PICKUP_TRINKET, + .seed = dropRNG.Next()}); + else + { + uint32_t seed = dropRNG.Next(); + int item = g_game->itemPool.GetCollectible(POOL_KEY_MASTER, dropRNG.Next(), 0, 0, 0); + Vector spot = room_free_pickup_position_find({.position = vector_make(pos.x, pos.y + KEY_MASTER_ITEM_DROP)}); + g_game->Spawn( + {.position = spot, .subType = item, .type = ENTITY_PICKUP, .variant = PICKUP_COLLECTIBLE, .seed = seed}); + } + isUnknown418 = false; + leave(); +} + +// The donation machine takes a coin into its save's count (shown on its digits), which unlocks achievements as it +// grows and at 1000 blows the machine up into dimes. It may give luck or Karma's gifts, and may jam the more the run +// donated to Greed. +void Entity_Slot::donation_pay(Entity_Player& player) +{ + if (!sprite.overlayAnimState.IsEventTriggered("CoinInsert")) return; + + state = SLOT_STATE_IDLE; + int count = persistentData->eventCounters[EVENT_COUNTER_DONATIONS] % COUNTER_LIMIT; + persistentData->IncreaseEventCounter(EVENT_COUNTER_DONATIONS, 1); + counter_show(++count); + if (dropRNG.RandomInt(50) == 0) player.DonateLuck(1); + if (player.HasTrinket(TRINKET_KARMA) && dropRNG.RandomInt(3) == 0) + { + float roll = dropRNG.RandomFloat(); + int multiplier = player.GetTrinketMultiplier(TRINKET_KARMA); + if (roll < KARMA_COINS) player.AddCoins(multiplier); + else if (roll < KARMA_HEARTS) player.AddHearts(multiplier * 2, false, false); + else if (roll < KARMA_LUCK) player.DonateLuck(multiplier); + else + { + uint32_t seed = dropRNG.Next(); + Vector spot = room_free_pickup_position_find({.position = vector_make(pos.x, pos.y + KARMA_BEGGAR_DROP)}); + g_game->Spawn( + {.position = spot, .spawner = this, .type = ENTITY_SLOT, .variant = SLOT_BEGGAR, .seed = seed}); + } + } + g_game->donationModAngel++; + g_game->donationModGreed++; + for (auto [needed, achievement] : DONATION_UNLOCKS) + if (count >= needed) persistentData->TryUnlock(achievement); + + if (count >= COUNTER_LIMIT) + { + g_game->Spawn({.position = pos, .type = ENTITY_EFFECT, .variant = EFFECT_BOMB_EXPLOSION, .seed = Random()}); + sprite.Play("Death"); + state = SLOT_STATE_BROKEN; + for (int i = 0; i < DONATION_PAYOUT_DIMES; i++) + { + Vector velocity = throw_velocity_get(pos, nullptr); + g_game->Spawn({.position = pos, + .velocity = velocity, + .subType = COIN_DIME, + .type = ENTITY_PICKUP, + .variant = PICKUP_COIN, + .seed = dropRNG.Next()}); + } + g_game->gameStateFlags |= 1ull << GAME_STATE_DONATION_SLOT_BROKEN; + } + + if (count == COUNTER_FULL) + { + touch = 0; + timeout = COUNTER_DONE_FRAMES; + } + else timeout = (int16_t)std::max(0, COIN_FRAMES - touch / TOUCH_SLOWDOWN); + npc_sound_play(SOUND_COIN_SLOT, 1, 2, 1); + + int jamOdds = g_game->donationModGreed * 3; + jamOdds -= std::min(jamOdds, player.GetTrinketMultiplier(TRINKET_KARMA)); + if (state == SLOT_STATE_BROKEN || dropRNG.RandomInt(DONATION_JAM_ODDS) >= (uint32_t)(jamOdds * 3)) return; + + sprite.Play(COIN_JAM_ANIMATIONS[Random() & 3]); + g_game->gameStateFlags |= 1ull << GAME_STATE_DONATION_SLOT_JAMMED; + state = SLOT_STATE_BROKEN; +} + +// The Bomb Bum pays its rolled prize: coins (or with Daemon's Tail most likely), hearts, or a Bomb Bum's collectible it +// leaves for. +void Entity_Slot::bomb_bum_pay(Entity_Player& player, RNG& prizeRng, int count) +{ + sprite.Play("Prize"); + if (!sprite.IsEventTriggered("Prize")) return; + + npc_sound_play(SOUND_SLOTSPAWN, 1, 2, 1); + if (prizeType == BOMB_BUM_COINS || prizeType == BOMB_BUM_HEARTS) + { + int variantDropped = PICKUP_HEART; + int stacks = 1; + if (prizeType == BOMB_BUM_COINS || + (player.HasTrinket(TRINKET_DAEMONS_TAIL) && + player.GetTrinketRNG(TRINKET_DAEMONS_TAIL).RandomInt(DAEMONS_TAIL_ODDS) != 0)) + { + variantDropped = PICKUP_COIN; + stacks = (int)dropRNG.RandomInt(3) + 1; + } + for (int i = 0; i < stacks; i++) drops_spawn({.rng = &prizeRng, .count = count, .variant = variantDropped}); + return; + } + + uint32_t seed = dropRNG.Next(); + int item = g_game->itemPool.GetCollectible(POOL_BOMB_BUM, dropRNG.Next(), 0, 0, 0); + g_game->Spawn({.position = collectible_spawn_position(pos), + .subType = item, + .type = ENTITY_PICKUP, + .variant = PICKUP_COLLECTIBLE, + .seed = seed}); + leave(); +} + +// The restock machine takes a coin: it restocks the shop more surely the more coins it took (or with the Poker Chip), +// and from the fifth restock may blow up instead (less likely with Pay To Win). +void Entity_Slot::restock_pay(Entity_Player& player) +{ + if (!sprite.overlayAnimState.IsEventTriggered("CoinInsert")) return; + + state = SLOT_STATE_IDLE; + bool isRestock = false; + if (donationValue >= 0 && donationValue <= 2) isRestock = dropRNG.RandomInt(4 - donationValue) == 0; + else isRestock = dropRNG.RandomInt(4) != 0; + + bool isPokerChip = player.HasTrinket(TRINKET_POKER_CHIP) && dropRNG.RandomInt(20) == 0; + if (!isPokerChip && !isRestock) donationValue++; + else + { + triggerTimer++; + donationValue = 0; + int odds = player.HasTrinket(TRINKET_PAY_TO_WIN) ? player.GetTrinketMultiplier(TRINKET_PAY_TO_WIN) + 1 : 2; + if (triggerTimer < 5 || dropRNG.RandomInt(odds) != 0) room_shop_restock_full(); + else explode(); + } + timeout = COIN_FRAMES; + npc_sound_play(SOUND_COIN_SLOT, 1, 2, 1); +} + +// The Battery Bum pays: one time in sixteen a Battery Bum's collectible it leaves for, one in eight a battery trinket +// or Lil' Batteries, else charges for the player's actives over the next frames. +void Entity_Slot::battery_bum_pay(Entity_Player& player, RNG& prizeRng, int count) +{ + sprite.Play("Prize"); + if (!sprite.IsEventTriggered("Prize")) return; + + if (dropRNG.RandomInt(16) == 0) + { + npc_sound_play(SOUND_SLOTSPAWN, 1, 2, 1); + int item = g_game->itemPool.GetCollectible(POOL_BATTERY_BUM, dropRNG.Next(), 0, COLLECTIBLE_BATTERY_PACK, 0); + uint32_t seed = dropRNG.Next(); + g_game->Spawn({.position = collectible_spawn_position(pos), + .subType = item, + .type = ENTITY_PICKUP, + .variant = PICKUP_COLLECTIBLE, + .seed = seed}); + leave(); + g_game->SetStateFlag(LEVEL_STATE_BUM_LEFT, true); + persistentData->IncreaseEventCounter(EVENT_COUNTER_BATTERY_BUM_ITEMS, 1); + donationValue = 0; + return; + } + + donationValue = 0; + if (dropRNG.RandomInt(8) == 0) + { + npc_sound_play(SOUND_SLOTSPAWN, 1, 2, 1); + Vector velocity = throw_velocity_get(pos, &prizeRng); + int trinket = 0; + if (dropRNG.RandomInt(10) == 0 && g_game->itemPool.RemoveTrinket(TRINKET_AAA_BATTERY)) + trinket = TRINKET_AAA_BATTERY; + else if (dropRNG.RandomInt(10) == 0 && g_game->itemPool.RemoveTrinket(TRINKET_WATCH_BATTERY)) + trinket = TRINKET_WATCH_BATTERY; + if (!trinket) return drops_spawn({.rng = &prizeRng, .count = count, .variant = PICKUP_LIL_BATTERY}); + + g_game->Spawn({.position = pos, + .velocity = velocity, + .subType = trinket, + .type = ENTITY_PICKUP, + .variant = PICKUP_TRINKET, + .seed = dropRNG.Next()}); + return; + } + + int charges = BATTERY_BUM_CHARGES[dropRNG.RandomInt(BATTERY_BUM_CHARGES.size())]; + for (int slot = 0; slot < ACTIVE_SLOT_COUNT; slot++) + { + if (player.GetActiveMaxCharge(slot) != 0) continue; + if (charges > 0) + { + Entity_Effect* timer = Entity_Effect::CreateTimer(reinterpret_cast(&battery_bum_charge), + BATTERY_BUM_CHARGE_FRAMES / charges, charges, true); + timer->parent = &player; + timer->Update(); + } + break; + } + player.AnimateHappy(); + npc_sound_play(SOUND_BATTERYCHARGE, 1, 2, 1); + Entity* spark = g_game->Spawn( + {.position = player.pos, .subType = 1, .type = ENTITY_EFFECT, .variant = EFFECT_HEART, .seed = Random()}); + spark->sprite.offset = vector_make(0, BATTERY_SPARK_RISE); + spark->renderDepthOffset = 1; +} + +// The Rotten Beggar pays: one time in twenty-four a Rotten Beggar's collectible it leaves for, one in four rotten or +// bone hearts (once unlocked), a rotten trinket, or a fart, else blue flies or spiders. +void Entity_Slot::rotten_beggar_pay(Entity_Player& player, RNG& prizeRng, int count) +{ + sprite.Play("Prize"); + if (!sprite.IsEventTriggered("Prize")) return; + + donationValue = 0; + if (dropRNG.RandomInt(24) == 0) + { + npc_sound_play(SOUND_SLOTSPAWN, 1, 2, 1); + int item = g_game->itemPool.GetCollectible(POOL_ROTTEN_BEGGAR, dropRNG.Next(), 0, COLLECTIBLE_ROTTEN_MEAT, 0); + uint32_t seed = dropRNG.Next(); + g_game->Spawn({.position = collectible_spawn_position(pos), + .subType = item, + .type = ENTITY_PICKUP, + .variant = PICKUP_COLLECTIBLE, + .seed = seed}); + leave(); + g_game->SetStateFlag(LEVEL_STATE_BUM_LEFT, true); + return; + } + + if (dropRNG.RandomInt(4) != 0) + { + npc_sound_play(SOUND_SLOTSPAWN, 1, 2, 1); + if (dropRNG.RandomInt(2) == 0) return (void)player.AddBlueFlies((int)dropRNG.RandomInt(3) + 1, pos, nullptr); + for (int i = (int)dropRNG.RandomInt(3) + 1; i > 0; i--) player.ThrowBlueSpider(pos, {}); + return; + } + + uint32_t roll = dropRNG.RandomInt(6); + if (roll == 0 && persistentData->Unlocked(ACHIEVEMENT_BONE_HEARTS)) + { + npc_sound_play(SOUND_SLOTSPAWN, 1, 2, 1); + return drops_spawn({.rng = &prizeRng, .count = count, .subType = HEART_BONE, .variant = PICKUP_HEART}); + } + if (roll >= 1 && roll <= 3 && persistentData->Unlocked(ACHIEVEMENT_ROTTEN_HEARTS)) + { + npc_sound_play(SOUND_SLOTSPAWN, 1, 2, 1); + return drops_spawn({.rng = &prizeRng, .count = count, .subType = HEART_ROTTEN, .variant = PICKUP_HEART}); + } + + RNG trinketRng = rng_make(dropRNG._seed, 7); + uint32_t pick = trinketRng.RandomInt(8); + if (pick < ROTTEN_BEGGAR_TRINKETS.size() && g_game->itemPool.RemoveTrinket(ROTTEN_BEGGAR_TRINKETS[pick])) + { + npc_sound_play(SOUND_SLOTSPAWN, 1, 2, 1); + Vector velocity = throw_velocity_get(pos, &prizeRng); + g_game->Spawn({.position = pos, + .velocity = velocity, + .subType = ROTTEN_BEGGAR_TRINKETS[pick], + .type = ENTITY_PICKUP, + .variant = PICKUP_TRINKET, + .seed = dropRNG.Next()}); + return; + } + game_fart({.position = pos, .source = &player, .radius = ROTTEN_FART_RADIUS}); + game_butter_bean_fart( + {.position = pos, .source = &player, .radius = ROTTEN_BUTTER_BEAN_RADIUS, .isShowEffect = false}); +} + +// Pays out what a slot owes once its payment animation is done, by kind. The payout's pickups are thrown by an RNG +// from the slot's, and the Poker Chip multiplies them up to three. +void Entity_Slot::payout(Entity_Player& player) +{ + RNG prizeRng = rng_make(dropRNG._seed, 3); + int count = + player.HasTrinket(TRINKET_POKER_CHIP) ? std::min(player.GetTrinketMultiplier(TRINKET_POKER_CHIP), 3) : 1; + switch (variant) + { + case SLOT_MACHINE: + slot_machine_pay(player, prizeRng, count); + break; + case SLOT_BLOOD_DONATION_MACHINE: + blood_donation_pay(player, prizeRng, count); + break; + case SLOT_FORTUNE_TELLING_MACHINE: + fortune_pay(player, prizeRng, count); + break; + case SLOT_BEGGAR: + beggar_pay(player, prizeRng, count); + break; + case SLOT_DEVIL_BEGGAR: + devil_beggar_pay(prizeRng, count); + break; + case SLOT_SHELL_GAME: + case SLOT_HELL_GAME: + shell_game_pay(player, prizeRng, count); + break; + case SLOT_KEY_MASTER: + key_master_pay(prizeRng); + break; + case SLOT_DONATION_MACHINE: + donation_pay(player); + break; + case SLOT_BOMB_BUM: + bomb_bum_pay(player, prizeRng, count); + break; + case SLOT_SHOP_RESTOCK_MACHINE: + restock_pay(player); + break; + case SLOT_GREED_DONATION_MACHINE: + if (sprite.overlayAnimState.IsEventTriggered("CoinInsert")) + reconstruction_missing("Entity_Slot::Update 0065d950: the Greed donation machine's coin"); + break; + case SLOT_BATTERY_BUM: + battery_bum_pay(player, prizeRng, count); + break; + case SLOT_ISAAC_SECRET: + reconstruction_missing("Entity_Slot::Update 0065d950: Isaac's secret closet"); + case SLOT_CRANE_GAME: + case SLOT_CONFESSIONAL: + break; + case SLOT_ROTTEN_BEGGAR: + rotten_beggar_pay(player, prizeRng, count); + break; + case SLOT_REVIVE_MACHINE: + if (sprite.overlayAnimState.IsEventTriggered("CoinInsert")) + reconstruction_missing("Entity_Slot::Update 0065d950: the Revive Machine's coin"); + break; + default: + KAGE_LogMessage(LOG_INFO, (uint8_t*)"Slot type %d is not implemented!\n"); + break; + } + + bool isCoinMachine = variant == SLOT_MACHINE || variant == SLOT_DONATION_MACHINE || + variant == SLOT_SHOP_RESTOCK_MACHINE || variant == SLOT_GREED_DONATION_MACHINE || + variant == SLOT_REVIVE_MACHINE; + if (state != SLOT_STATE_REWARD || !sprite.IsFinished() || isCoinMachine) return; + state = SLOT_STATE_IDLE; + sprite.Play("Idle"); +} + +// 0065d950 Runs a slot each frame: its appearance, its spot, a Rotten Beggar's first splat, a Bomb Bum's Troll Bombs, +// the slot machine's roll once its spin ends, the Crane Game and Confessional prizes, and the payout once a payment's +// animation is done. A shell game shuffles with a sound, and touches count while a player keeps touching it. +void Entity_Slot::Update() +{ + if (variant == SLOT_CRANE_GAME && state != SLOT_STATE_BROKEN && prizeCollectible == 0) + SetPrizeType(g_game->itemPool.GetCollectible(POOL_CRANE_GAME, dropRNG._seed, 0, COLLECTIBLE_BUDDY_IN_A_BOX, 0)); + if (variant == SLOT_MOMS_DRESSER && g_game->frameCount - spawnFrame > 1) + { + isVisible = true; + if (sprite.animState.animData && sprite.animState.IsEventTriggered("Ground")) + npc_sound_play(SOUND_CHEST_DROP, 1, 2, 1); + } + if (HasEntityFlags(FLAG_APPEAR)) + { + state = SLOT_STATE_APPEAR; + timeout = 0; + ClearEntityFlags(FLAG_APPEAR); + if (variant == SLOT_GREED_DONATION_MACHINE) + { + sprite.Play("Appear"); + isVisible = true; + } + } + if (state == SLOT_STATE_APPEAR && appear_update()) return; + + if (variant == SLOT_ROTTEN_BEGGAR && g_game->frameCount - spawnFrame == 1) + { + Entity* splat = + g_game->Spawn({.position = pos, .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_SPLAT, .seed = Random()}); + float scale = random_unit() * ROTTEN_SPLAT_RANGE + ROTTEN_SPLAT_MIN; + splat->sprite.scale = vector_make(scale, scale); + splat->SetColor(ROTTEN_SPLAT_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + splat->Update(); + game_particles_spawn({.position = pos, + .height = ROTTEN_PARTICLE_HEIGHT, + .speed = ROTTEN_PARTICLE_SPEED, + .count = (int)(Random() % 3) + 1, + .variant = EFFECT_WORM}); + } + + Entity_Player* owner = target ? target->ToPlayer() : nullptr; + Entity_Player& player = owner ? *owner : *g_game->playerManager.GetPlayer(0); + movement_update(); + + if (variant == SLOT_BOMB_BUM && triggerTimer != 0 && triggerTimer-- % TROLL_BOMB_INTERVAL == 0) + { + Vector spot = room_pickup_position_random(false, false); + Room& room = *g_game->room; + room.SetGridPath(room.GetGridIndex(spot), GRID_PATH_MARK); + g_game->Spawn( + {.position = spot, .spawner = this, .type = ENTITY_BOMB, .variant = BOMB_TROLL, .seed = Random()}); + } + + if (timeout > 0 && --timeout == 0 && state == SLOT_STATE_REWARD && variant == SLOT_MACHINE) + sprite.Play("WiggleEnd"); + if (timeout == 0 && variant == SLOT_MACHINE && sprite.IsFinished("WiggleEnd")) slot_machine_roll(player); + if (timeout == 0 && variant == SLOT_CRANE_GAME) crane_game_update(player); + else if (timeout == 0 && variant == SLOT_CONFESSIONAL) confessional_update(player); + + bool isShellGame = variant == SLOT_SHELL_GAME || variant == SLOT_HELL_GAME; + bool isBusy = + (is_beggar(variant) || variant == SLOT_ISAAC_SECRET) && sprite.IsPlaying("PayPrize") && !sprite.IsFinished(); + bool isPaying = state == SLOT_STATE_REWARD && timeout == 0 && !isBusy && !isShellGame; + if (isPaying || (state == SLOT_STATE_PICK && isShellGame)) payout(player); + else idle_update(); + if (variant == SLOT_ISAAC_SECRET && !isExists) return; + + if (isShellGame && sprite.IsPlaying("PayShuffle") && sprite.IsEventTriggered("Shuffle")) + { + float pitch = random_unit() * 0.1f + 1; + npc_sound_play(SOUND_SHELLGAME, random_unit() * 0.1f + 0.5f, 2, pitch); + } + if (unkShort1 == 0) touch = 0; + else + { + touch++; + unkShort1--; + } + Entity::Update(); + prizeAnm2.Update(); +} + +// Whether a player paid what the slot asks: a coin (Karma may give some back), a hit for blood (Karma's gifts), a key, +// a bomb or five coins. A forced collision pays nothing. +bool Entity_Slot::is_payment_taken(Entity_Player& player) +{ + if (g_forceCollideDepth != 0) return true; + if (player.isCoopGhost) return false; + + switch (variant) + { + case SLOT_MACHINE: + case SLOT_FORTUNE_TELLING_MACHINE: + case SLOT_BEGGAR: + case SLOT_DONATION_MACHINE: + case SLOT_SHOP_RESTOCK_MACHINE: + case SLOT_GREED_DONATION_MACHINE: + case SLOT_BATTERY_BUM: + case SLOT_ROTTEN_BEGGAR: + case SLOT_REVIVE_MACHINE: + { + if (player.numCoins <= 0) return false; + player.AddCoins(-1); + if (!player.HasTrinket(TRINKET_KARMA) || dropRNG.RandomInt(3) != 0) return true; + + int multiplier = 0; + if (variant == SLOT_BEGGAR) + { + float roll = dropRNG.RandomFloat(); + multiplier = player.GetTrinketMultiplier(TRINKET_KARMA); + if (roll < KARMA_COINS) player.AddCoins(multiplier); + else if (roll < KARMA_HEARTS) player.AddHearts(multiplier * 2, false, false); + else if (roll < KARMA_LUCK) player.DonateLuck(multiplier); + } + else if (variant == SLOT_SHOP_RESTOCK_MACHINE && dropRNG.RandomFloat() < KARMA_RESTOCK_LUCK) + player.DonateLuck(player.GetTrinketMultiplier(TRINKET_KARMA)); + return true; + } + case SLOT_BLOOD_DONATION_MACHINE: + case SLOT_DEVIL_BEGGAR: + case SLOT_HELL_GAME: + case SLOT_CONFESSIONAL: + { + if (variant == SLOT_HELL_GAME && state == SLOT_STATE_REWARD) return true; + if (variant == SLOT_HELL_GAME && state != SLOT_STATE_IDLE) return false; + if (player.IsP2Appearing() || player.damageCooldown >= BLOOD_PAY_COOLDOWN) return false; + + uint64_t flags = DAMAGE_RED_HEARTS; + if (g_game->challenge == CHALLENGE_GUARDIAN) flags |= DAMAGE_ISAAC_HURT; + player.damageCooldown = 0; + player.TakeDamage(g_game->deathmatchManager.is_active() ? VERSUS_BLOOD_DAMAGE : 1, flags, EntityRef(this), + PAY_FRAMES); + int paidState = state; + if (player.HasTrinket(TRINKET_KARMA) && dropRNG.RandomInt(3) == 0) + { + float roll = dropRNG.RandomFloat(); + if (roll < KARMA_COINS) + { + uint32_t seed = dropRNG.Next(); + Vector spot = + room_free_pickup_position_find({.position = vector_make(pos.x, pos.y + KARMA_BEGGAR_DROP)}); + g_game->Spawn( + {.position = spot, .spawner = this, .type = ENTITY_SLOT, .variant = SLOT_BEGGAR, .seed = seed}); + } + else if (roll < KARMA_HEARTS) + player.AddHearts(player.GetTrinketMultiplier(TRINKET_KARMA) * 2, false, false); + else if (roll < KARMA_LUCK) player.DonateLuck(player.GetTrinketMultiplier(TRINKET_KARMA)); + } + return paidState == SLOT_STATE_IDLE; + } + case SLOT_SHELL_GAME: + if (state == SLOT_STATE_REWARD) return true; + if (state != SLOT_STATE_IDLE || player.numCoins <= 0) return false; + player.AddCoins(-1); + return true; + case SLOT_KEY_MASTER: + if (player.hasGoldenKey) return true; + if (player.numKeys < 1) return false; + player.AddKeys(-1); + return true; + case SLOT_ISAAC_SECRET: + return true; + case SLOT_BOMB_BUM: + if (player.hasGoldenBomb) return true; + if (player.numBombs < 1) return false; + player.AddBombs(-1); + return true; + case SLOT_CRANE_GAME: + if (player.numCoins <= 4) return false; + player.AddCoins(-5); + return true; + } + return false; +} + +// Starts a shell game once paid: the shells shuffle over a prize (a collectible one time in thirteen, Daemon's Tail +// trading a shell game's hearts away), whose layer alone shows. +void Entity_Slot::shell_game_start(Entity_Player& player) +{ + sprite.Play("PayShuffle"); + if (prizeAnm2.SetAnimation("Prizes", SWITCH_KEEP_FRAME)) + { + prizeAnm2.animState.Rewind(); + prizeAnm2.animState.isPlaying = true; + } + + if (variant == SLOT_HELL_GAME) + { + prizeType = HELL_GAME_PRIZES[dropRNG.RandomInt(HELL_GAME_PRIZES.size())]; + if (dropRNG.RandomInt(13) == 0) prizeType = PRIZE_COLLECTIBLE; + } + else + { + prizeType = SHELL_GAME_PRIZES[dropRNG.RandomInt(SHELL_GAME_PRIZES.size())]; + if (dropRNG.RandomInt(13) == 0 && + g_game->itemPool.is_collectible_available(COLLECTIBLE_SKATOLE, UNLOCK_CHECKED)) + prizeType = PRIZE_COLLECTIBLE; + if (prizeType == PICKUP_HEART && player.HasTrinket(TRINKET_DAEMONS_TAIL) && + player.GetTrinketRNG(TRINKET_DAEMONS_TAIL).RandomInt(DAEMONS_TAIL_ODDS) != 0) + prizeType = SHELL_GAME_PRIZES[1 + dropRNG.RandomInt(3)]; + else dropRNG.Next(); + } + + int layerLimit = variant == SLOT_HELL_GAME ? (int)SHELL_PRIZE_LAYERS.size() : SHELL_ALWAYS_LAYER + 1; + for (int layer = 0; layer < (int)prizeAnm2.layerStates.size(); layer++) + { + bool isShown = layer == SHELL_ALWAYS_LAYER || (layer < layerLimit && SHELL_PRIZE_LAYERS[layer] == prizeType); + if (variant != SLOT_HELL_GAME && layer == 0) isShown = prizeType == PRIZE_COLLECTIBLE; + prizeAnm2.GetLayer(layer)->isVisible = isShown; + } + + if (variant == SLOT_HELL_GAME && prizeType == PRIZE_COLLECTIBLE) + { + bool isGreed = g_game->difficulty == DIFFICULTY_GREED || g_game->difficulty == DIFFICULTY_GREEDIER; + ItemPoolType pool = isGreed ? POOL_GREED_DEVIL : POOL_DEVIL; + SetPrizeType(g_game->itemPool.GetCollectible(pool, initSeed, POOL_FLAG_NO_DECREASE, COLLECTIBLE_DEMON_BABY, 0)); + } + state = SLOT_STATE_REWARD; + persistentData->IncreaseEventCounter(EVENT_COUNTER_SHELL_GAMES_PLAYED, 1); + npc_sound_play(SOUND_SCAMPER, 1, 2, 1); +} + +// How a slot takes a payment: the shell games start or pick a shell, beggars decide whether this payment pays out, the +// Key Master and Bomb Bum use golden ones first, coin machines play their coin, and the rest start their payment. +void Entity_Slot::payment_react(Entity_Player& player, Entity* collider) +{ + if (variant == SLOT_SHELL_GAME || variant == SLOT_HELL_GAME) + { + if (state == SLOT_STATE_IDLE) return shell_game_start(player); + if (state != SLOT_STATE_REWARD || (sprite.animState.animData && sprite.animState.isPlaying)) return; + + float x = collider->pos.x; + shellGameAnimationIndex = x < pos.x - SHELL_SIDE_REACH ? 0 : x <= pos.x + SHELL_SIDE_REACH ? 1 : 2; + state = SLOT_STATE_PICK; + return; + } + + const char* animation = nullptr; + switch (variant) + { + case SLOT_BEGGAR: + case SLOT_DEVIL_BEGGAR: + case SLOT_BATTERY_BUM: + case SLOT_ROTTEN_BEGGAR: + { + npc_sound_play(variant == SLOT_DEVIL_BEGGAR ? SOUND_TEAR_IMPACTS : SOUND_SCAMPER, 1, 2, 1); + donationValue++; + int needed = 0; + if (variant == SLOT_BATTERY_BUM || variant == SLOT_ROTTEN_BEGGAR) + { + int roll = (int)dropRNG.RandomInt(3); + needed = (int)dropRNG.RandomInt(2) + roll; + if (g_game->difficulty == DIFFICULTY_HARD) needed = std::max(2, needed); + } + else + { + int roll = (int)dropRNG.RandomInt(4); + int rollB = (int)dropRNG.RandomInt(4); + needed = (int)dropRNG.RandomInt(2) + roll + rollB; + if (g_game->difficulty == DIFFICULTY_HARD) needed = std::max(5, needed); + } + animation = "PayNothing"; + if (needed < donationValue) + { + donationValue = (int)dropRNG.RandomInt(2) + 2; + if (player.HasCollectible(COLLECTIBLE_LUCKY_FOOT)) donationValue++; + state = SLOT_STATE_REWARD; + animation = "PayPrize"; + } + break; + } + case SLOT_KEY_MASTER: + { + npc_sound_play(SOUND_KEY_DROP0, 2, 2, 1); + uint32_t roll = dropRNG.RandomInt(100); + sprite.GetLayer(2)->isVisible = !player.hasGoldenKey; + sprite.GetLayer(3)->isVisible = player.hasGoldenKey; + animation = "PayNothing"; + if (player.hasGoldenKey || roll < 35) + { + if (player.hasGoldenKey) + { + player.RemoveGoldenKey(); + isUnknown418 = true; + } + state = SLOT_STATE_REWARD; + animation = "PayPrize"; + } + break; + } + case SLOT_BOMB_BUM: + { + npc_sound_play(SOUND_SCAMPER, 1, 2, 1); + prizeType = 0; + sprite.GetLayer(2)->isVisible = !player.hasGoldenBomb; + sprite.GetLayer(3)->isVisible = player.hasGoldenBomb; + if (player.hasGoldenBomb) + { + prizeType = BOMB_BUM_ITEM; + player.RemoveGoldenBomb(); + } + else + { + uint32_t roll = dropRNG.RandomInt(100); + prizeType = roll < 25 ? BOMB_BUM_COINS : roll < 35 ? BOMB_BUM_HEARTS : roll < 40 ? BOMB_BUM_ITEM : 0; + } + animation = prizeType == 0 ? "PayNothing" : "PayPrize"; + if (prizeType != 0) state = SLOT_STATE_REWARD; + break; + } + case SLOT_DONATION_MACHINE: + case SLOT_SHOP_RESTOCK_MACHINE: + case SLOT_GREED_DONATION_MACHINE: + case SLOT_REVIVE_MACHINE: + { + if (variant == SLOT_GREED_DONATION_MACHINE) + { + Entity* spawner = spawnerEntity; + isUnknown544 = !spawner || spawner == collider || spawner == player.twin_get() || player.backupPlayer; + } + const char* insert = "CoinInsert"; + if (variant != SLOT_SHOP_RESTOCK_MACHINE) + insert = touch >= COIN_INSERT3_TOUCHES ? "CoinInsert3" + : touch >= COIN_INSERT2_TOUCHES ? "CoinInsert2" + : insert; + overlay_restart(sprite, insert); + state = SLOT_STATE_REWARD; + return; + } + case SLOT_BLOOD_DONATION_MACHINE: + case SLOT_MACHINE: + case SLOT_FORTUNE_TELLING_MACHINE: + if (variant == SLOT_BLOOD_DONATION_MACHINE) + persistentData->IncreaseEventCounter(EVENT_COUNTER_BLOOD_DONATIONS, 1); + npc_sound_play(variant == SLOT_BLOOD_DONATION_MACHINE ? SOUND_BLOODBANK_TOUCHED : SOUND_COIN_SLOT, 1, 2, 1); + state = SLOT_STATE_REWARD; + timeout = PAY_FRAMES; + return sprite.Play("Initiate"); + case SLOT_ISAAC_SECRET: + state = SLOT_STATE_REWARD; + timeout = PAY_FRAMES; + return sprite.Play("PayPrize"); + case SLOT_CONFESSIONAL: + case SLOT_CRANE_GAME: + if (variant == SLOT_CRANE_GAME) npc_sound_play(SOUND_COIN_SLOT, 1, 2, 1); + state = SLOT_STATE_REWARD; + timeout = PAY_FRAMES; + sprite.Play("Initiate"); + return overlay_restart(sprite, variant == SLOT_CRANE_GAME ? "CoinInsert" : "HeartInsert"); + default: + return; + } + npc_anim_restart(sprite, animation); +} + +// 006627e0 A player touching an idle slot pays it, which makes it the slot's target, may give Beth's Essence a wisp +// for a beggar, and starts the slot's payment. A player touching Mom's dresser opens it. Touches are counted while a +// player keeps touching. Enemies and bombs pass through a slot. +bool Entity_Slot::HandleCollision(Entity* collider, bool) +{ + bool isPlayer = collider->type == ENTITY_PLAYER; + if (variant == SLOT_MOMS_DRESSER && isPlayer && collider->variant == PLAYER_VARIANT_PLAYER && + state != SLOT_STATE_BROKEN && (!sprite.animState.animData || !sprite.animState.isPlaying)) + reconstruction_missing("Entity_Slot::HandleCollision 006627e0: Mom's dresser (FUN_006653e0, FUN_0075d9f0)"); + + bool isShellGame = variant == SLOT_SHELL_GAME || variant == SLOT_HELL_GAME; + const AnimationData* animation = sprite.animState.animData; + bool isBusy = is_beggar(variant) && animation && !animation->isLooping && sprite.animState.isPlaying; + bool isReady = (state == SLOT_STATE_IDLE && timeout <= 0 && !isBusy) || (state == SLOT_STATE_REWARD && isShellGame); + if (isPlayer && variant != SLOT_MOMS_DRESSER && isReady) + { + Entity_Player* toucher = collider->ToPlayer(); + Entity_Player* twin = toucher->twin_get(); + Entity_Player& player = toucher->playerType == PLAYER_THESOUL_B && twin ? *twin : *toucher; + bool isBlood = variant == SLOT_BLOOD_DONATION_MACHINE || variant == SLOT_DEVIL_BEGGAR || + variant == SLOT_HELL_GAME || variant == SLOT_CONFESSIONAL; + bool isHellPaid = variant == SLOT_HELL_GAME && state == SLOT_STATE_REWARD; + bool isRefused = isBlood && !isHellPaid && + (player.IsP2Appearing() || (variant == SLOT_HELL_GAME && state != SLOT_STATE_IDLE)); + if (isRefused && g_forceCollideDepth == 0 && !player.isCoopGhost) return false; + if (is_payment_taken(player)) + { + target = &player; + if (is_beggar(variant) && player.HasTrinket(TRINKET_BETHS_ESSENCE) && + player.GetTrinketRNG(TRINKET_BETHS_ESSENCE).RandomInt(BETHS_ESSENCE_ODDS) == 0) + reconstruction_missing("Entity_Slot::HandleCollision 006627e0: Beth's Essence's wisp"); + payment_react(player, collider); + } + } + + if (isPlayer && collider->variant == PLAYER_VARIANT_PLAYER && state != SLOT_STATE_BROKEN) unkShort1 = TOUCH_FRAMES; + bool isVersus = g_game->deathmatchManager.is_active() && isPlayer; + bool isPassing = + (collider->type >= ENEMY_TYPE_FIRST && collider->type < ENTITY_EFFECT) || collider->type == ENTITY_BOMB; + return !isVersus && isPassing; +} + +// The blood donation machine blown up sprays five trails of blood splats from it, each splat smaller and turned a +// little from the last. +void Entity_Slot::blood_trails_spawn() +{ + Entity* blood = g_game->Spawn({.position = pos, + .subType = BLOOD_EXPLOSION_MACHINE, + .type = ENTITY_EFFECT, + .variant = EFFECT_BLOOD_EXPLOSION, + .seed = Random()}); + blood->sprite.offset = vector_make(0, SLOT_BLOOD_RISE); + blood->renderDepthOffset = SLOT_BLOOD_DEPTH; + + for (int trail = 0; trail < BLOOD_TRAILS; trail++) + { + float angle = random_unit() * RANDOM_HALF_TURN; + angle += angle; + float length = random_unit() * BLOOD_TRAIL_RANGE + BLOOD_TRAIL_MIN; + Vector step = vector_make(std::cos(angle) * length, std::sin(angle) * length * BLOOD_TRAIL_FLAT); + Vector spot = vector_add(vector_scale(step, BLOOD_TRAIL_START), pos); + float scale = random_unit() * 2 + BLOOD_TRAIL_SCALE; + for (int splat = 0; splat < BLOOD_TRAIL_SPLATS; splat++) + { + Entity* drop = g_game->Spawn( + {.position = spot, .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_SPLAT, .seed = Random()}); + if (drop && drop->type == ENTITY_EFFECT) + { + drop->sprite.scale = vector_make(scale, scale); + drop->Update(); + } + float turn = (random_unit() * BLOOD_TRAIL_TURN - BLOOD_TRAIL_TURN / 2) * DEGREES_TO_RADIANS; + float c = std::cos(turn); + float s = std::sin(turn); + spot = vector_make((step.x * c - step.y * s) + spot.x, step.x * s + step.y * c + spot.y); + step = vector_scale(step, BLOOD_TRAIL_SHRINK); + scale *= BLOOD_TRAIL_FADE; + } + } +} + +// 00664560 A slot hit by an explosion breaks: the donation machine loses some of its count as pennies, a restock +// machine restocks one last time and blows up, a beggar bleeds and dies (a bum killed this floor), the blood donation +// machine sprays blood, and Mom's dresser breaks. The Bomb Bum takes a bomb as a payment instead, and only a crushing +// blast kills it. The Greed donation machine breaks only to a co-op player's blast. A touch from Isaac's secret pays. +bool Entity_Slot::TakeDamage(float, uint64_t damageFlags, const EntityRef& source, int) +{ + if (variant == SLOT_ISAAC_SECRET) + { + if (state != SLOT_STATE_IDLE) return false; + state = SLOT_STATE_REWARD; + timeout = PAY_FRAMES; + sprite.Play("PayPrize"); + return false; + } + if (!(damageFlags & DAMAGE_EXPLOSION)) return false; + + if (variant == SLOT_DONATION_MACHINE && state != SLOT_STATE_BROKEN) + { + sprite.Play("Death"); + state = SLOT_STATE_BROKEN; + int lost = std::min(persistentData->eventCounters[EVENT_COUNTER_DONATIONS] % COUNTER_LIMIT, + (int)dropRNG.RandomInt(DONATION_LIMIT_RANGE) + DONATION_LIMIT); + persistentData->IncreaseEventCounter(EVENT_COUNTER_DONATIONS, -lost); + for (int i = 0; i < lost - 1; i++) + { + Vector velocity = throw_velocity_get(pos, &dropRNG); + g_game->Spawn({.position = pos, + .velocity = velocity, + .subType = COIN_PENNY, + .type = ENTITY_PICKUP, + .variant = PICKUP_COIN, + .seed = dropRNG.Next()}); + } + g_game->gameStateFlags |= 1ull << GAME_STATE_DONATION_SLOT_BROKEN | 1ull << GAME_STATE_DONATION_SLOT_BLOWN; + return false; + } + if (variant == SLOT_GREED_DONATION_MACHINE) + { + PlayerManager& players = g_game->playerManager; + if (!players.IsCoopPlay() || players.count_main_players() < 2) return false; + sprite.Play("Death"); + state = SLOT_STATE_BROKEN; + return true; + } + if (variant == SLOT_SHOP_RESTOCK_MACHINE && state != SLOT_STATE_BROKEN) + { + room_shop_restock_full(); + triggerTimer = 0; + explode(); + return false; + } + if (state == SLOT_STATE_BROKEN) return false; + + if (variant == SLOT_BOMB_BUM && !(damageFlags & DAMAGE_CRUSH)) + { + if (state != SLOT_STATE_IDLE || source.spawnerType == ENTITY_SLOT) return false; + npc_anim_restart(sprite, "Bombed"); + state = SLOT_STATE_PICK; + return false; + } + state = SLOT_STATE_BROKEN; + if (variant == SLOT_MACHINE) persistentData->IncreaseEventCounter(EVENT_COUNTER_SLOT_MACHINES_BROKEN, 1); + if (variant == SLOT_BLOOD_DONATION_MACHINE) blood_trails_spawn(); + + if (is_beggar(variant) || variant == SLOT_SHELL_GAME || variant == SLOT_HELL_GAME) + { + Entity* blood = g_game->Spawn( + {.position = pos, .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_EXPLOSION, .seed = Random()}); + blood->sprite.offset = vector_make(0, SLOT_BLOOD_RISE); + BloodExplode(); + Remove(); + if (is_beggar(variant)) g_game->levelStateFlags |= 1u << LEVEL_STATE_BUM_KILLED; + if (variant == SLOT_BATTERY_BUM) persistentData->IncreaseEventCounter(EVENT_COUNTER_BATTERY_BUMS_KILLED, 1); + } + if (variant == SLOT_MOMS_DRESSER) + { + if (sprite.GetAnimation() != "Broken" || + (sprite.animState.animData && sprite.animState.animData->isLooping && !sprite.animState.isPlaying)) + npc_anim_restart(sprite, "Broken"); + state = SLOT_STATE_BROKEN; + } + spawn_break_drops(); + return true; +} + +// 00663aa0 What a broken slot leaves: spiders from a devil beggar or the Hell Game, maggots, gibs and maybe a rotten +// heart from a Rotten Beggar, coins from a restock machine, coins or hearts from the blood donation machine, Mom's +// dresser's clothes or a rare item, a Revive Machine's hearts or bomb in a boss room, and from the rest a trinket or +// pill, a rare chest, or coins, hearts, keys and bombs (Lucky Toe giving one more, drop trinkets a matching pickup). +void Entity_Slot::spawn_break_drops() +{ + RNG* daemonsTail = nullptr; + g_game->playerManager.RandomTrinketOwner(TRINKET_DAEMONS_TAIL, initSeed, &daemonsTail); + RNG velocityRng = {initSeed, 1, 9, 29}; + auto drop = [&](int dropVariant, int subType, uint32_t seed, float speed) + { + Vector velocity = vector_scale(Entity_Pickup::GetRandomPickupVelocity(pos, &velocityRng, 1), speed); + g_game->Spawn({.position = pos, + .velocity = velocity, + .subType = subType, + .type = ENTITY_PICKUP, + .variant = dropVariant, + .seed = seed}); + }; + + switch (variant) + { + case SLOT_DEVIL_BEGGAR: + case SLOT_HELL_GAME: + Entity_NPC::ThrowSpider(pos, this, {}, false, SLOT_SPIDER_HEIGHT); + Entity_NPC::ThrowSpider(pos, this, {}, false, SLOT_SPIDER_HEIGHT); + return; + case SLOT_ROTTEN_BEGGAR: + reconstruction_missing( + "Entity_Slot::spawn_break_drops 00663aa0: the Rotten Beggar's maggots (spawn_small_maggot)"); + case SLOT_SHOP_RESTOCK_MACHINE: + for (int i = (int)dropRNG.RandomInt(4); i > 0; i--) + { + uint32_t seed = dropRNG.Next(); + drop(PICKUP_COIN, 0, seed, 1); + } + return; + case SLOT_BLOOD_DONATION_MACHINE: + for (int i = (int)dropRNG.RandomInt(2) + 1; i > 0; i--) + { + bool isCoins = + dropRNG.RandomInt(2) == 0 || (daemonsTail && daemonsTail->RandomInt(DAEMONS_TAIL_ODDS) != 0); + if (!isCoins) + { + uint32_t seed = dropRNG.Next(); + drop(PICKUP_HEART, 0, seed, 1); + continue; + } + for (int coin = (int)dropRNG.RandomInt(4) + 1; coin > 0; coin--) + { + uint32_t seed = dropRNG.Next(); + drop(PICKUP_COIN, 0, seed, 1); + } + } + return; + case SLOT_MOMS_DRESSER: + reconstruction_missing("Entity_Slot::spawn_break_drops 00663aa0: Mom's dresser"); + case SLOT_REVIVE_MACHINE: + reconstruction_missing("Entity_Slot::spawn_break_drops 00663aa0: the Revive Machine"); + default: + break; + } + + if (dropRNG.RandomInt(5) == 0) + { + int dropVariant = dropRNG.RandomInt(2) != 0 ? PICKUP_PILL : PICKUP_TRINKET; + uint32_t seed = dropRNG.Next(); + return drop(dropVariant, 0, seed, BREAK_DROP_SLOW); + } + if (dropRNG.RandomFloat() < BREAK_CHEST_CHANCE) + return (void)g_game->Spawn( + {.position = pos, .type = ENTITY_PICKUP, .variant = PICKUP_CHEST, .seed = dropRNG.Next()}); + if (dropRNG.RandomFloat() < BREAK_CHEST_CHANCE) + return (void)g_game->Spawn( + {.position = pos, .type = ENTITY_PICKUP, .variant = PICKUP_LOCKEDCHEST, .seed = dropRNG.Next()}); + + RNG trinketRng = rng_make(initSeed, BREAK_TRINKET_SHIFT); + int stacks = std::max((int)dropRNG.RandomInt(4), 2); + if (dropRNG.RandomInt(3) != 0 && g_game->playerManager.AnyoneHasTrinket(TRINKET_LUCKY_TOE)) stacks++; + for (auto [trinket, dropVariant] : BREAK_DROP_TRINKETS) + { + Entity_Player* owner = g_game->playerManager.RandomTrinketOwner(trinket, trinketRng.Next(), nullptr); + if (!owner || !owner->HasTrinket(trinket)) continue; + bool isDaemonsTailBlocked = trinket == TRINKET_CHILDS_HEART && owner->HasTrinket(TRINKET_DAEMONS_TAIL) && + Random() % DAEMONS_TAIL_ODDS != 0; + if (isDaemonsTailBlocked) continue; + + int multiplier = g_game->playerManager.GetTrinketMultiplier(trinket); + uint32_t chance = multiplier == 2 ? BREAK_TRINKET_CHANCE * 2 : multiplier > 2 ? HUNDREDS : BREAK_TRINKET_CHANCE; + RNG& trinketDrop = owner->GetTrinketRNG(trinket); + if (trinketDrop.RandomInt(HUNDREDS) >= chance) continue; + + Vector velocity = Entity_Pickup::GetRandomPickupVelocity(pos, &velocityRng, 1); + g_game->Spawn({.position = pos, + .velocity = velocity, + .type = ENTITY_PICKUP, + .variant = dropVariant, + .seed = trinketDrop.Next()}); + break; + } + + for (int i = 0; i < stacks; i++) + { + float roll = dropRNG.RandomFloat(); + if (roll < BREAK_COINS) + { + for (int coin = (int)dropRNG.RandomInt(3) + 1; coin > 0; coin--) + { + uint32_t seed = dropRNG.Next(); + drop(PICKUP_COIN, 0, seed, 1); + } + continue; + } + if (roll < BREAK_HEARTS && !(daemonsTail && daemonsTail->RandomInt(DAEMONS_TAIL_ODDS) != 0)) + { + uint32_t seed = dropRNG.Next(); + drop(PICKUP_HEART, 0, seed, 1); + if (dropRNG.RandomInt(2) == 0) stacks--; + continue; + } + uint32_t seed = dropRNG.Next(); + drop(roll >= BREAK_KEYS ? PICKUP_BOMB : PICKUP_KEY, 0, seed, 1); + } +} diff --git a/src/entity_slot.h b/src/entity_slot.h index b4690cf..1ea0178 100644 --- a/src/entity_slot.h +++ b/src/entity_slot.h @@ -2,6 +2,54 @@ #include "entity.h" +// Lua's SlotVariant: the machines and beggars. +enum SlotVariant : int +{ + SLOT_MACHINE = 1, + SLOT_BLOOD_DONATION_MACHINE, + SLOT_FORTUNE_TELLING_MACHINE, + SLOT_BEGGAR, + SLOT_DEVIL_BEGGAR, + SLOT_SHELL_GAME, + SLOT_KEY_MASTER, + SLOT_DONATION_MACHINE, + SLOT_BOMB_BUM, + SLOT_SHOP_RESTOCK_MACHINE, + SLOT_GREED_DONATION_MACHINE, + SLOT_MOMS_DRESSER, + SLOT_BATTERY_BUM, + SLOT_ISAAC_SECRET, + SLOT_HELL_GAME, + SLOT_CRANE_GAME, + SLOT_CONFESSIONAL, + SLOT_ROTTEN_BEGGAR, + SLOT_REVIVE_MACHINE +}; + +// Where a slot is: appearing, waiting for a payment, paying out, broken (or jammed), leaving, and a shell game's pick +// (or a bombed Bomb Bum). +enum SlotState : int +{ + SLOT_STATE_APPEAR, + SLOT_STATE_IDLE, + SLOT_STATE_REWARD, + SLOT_STATE_BROKEN, + SLOT_STATE_GONE, + SLOT_STATE_PICK +}; + +// What a slot throws out (the pickups Entity_Slot::HandleCollision 006657a0 overload spawns): count pickups of a +// variant and subtype, thrown by its RNG unless a velocity is given, from an offset. +struct SlotDrop +{ + RNG* rng = nullptr; + Vector offset{}; + Vector velocity{}; + int count = 1; + int subType = 0; + int variant = 0; +}; + // Construction and destruction (0065d130) are the defaults. // A slot machine, beggar or other paying machine (Lua's EntitySlot), which pays out a prize: its state, the prize it // shows and the save data its donations count into. @@ -32,4 +80,33 @@ struct Entity_Slot : Entity private: void counter_show(int count); + void drops_spawn(const SlotDrop& drop); + void explode(); + void leave(); + bool appear_update(); + void movement_update(); + void slot_machine_roll(Entity_Player& player); + void crane_game_update(Entity_Player& player); + void confessional_update(Entity_Player& player); + void idle_update(); + void payout(Entity_Player& player); + void slot_machine_pay(Entity_Player& player, RNG& prizeRng, int count); + void blood_donation_pay(Entity_Player& player, RNG& prizeRng, int count); + void fortune_pay(Entity_Player& player, RNG& prizeRng, int count); + void beggar_pay(Entity_Player& player, RNG& prizeRng, int count); + void devil_beggar_pay(RNG& prizeRng, int count); + void shell_game_pay(Entity_Player& player, RNG& prizeRng, int count); + void key_master_pay(RNG& prizeRng); + void donation_pay(Entity_Player& player); + void bomb_bum_pay(Entity_Player& player, RNG& prizeRng, int count); + void restock_pay(Entity_Player& player); + void battery_bum_pay(Entity_Player& player, RNG& prizeRng, int count); + void rotten_beggar_pay(Entity_Player& player, RNG& prizeRng, int count); + bool is_payment_taken(Entity_Player& player); + void payment_react(Entity_Player& player, Entity* collider); + void shell_game_start(Entity_Player& player); + void blood_trails_spawn(); }; + +Vector room_pickup_position_random(bool isAvoidActiveEntities, bool isAllowPits); +Vector collectible_spawn_position(Vector target); diff --git a/src/familiar_ai.cpp b/src/familiar_ai.cpp index 0a41459..a5be166 100644 --- a/src/familiar_ai.cpp +++ b/src/familiar_ai.cpp @@ -51,12 +51,18 @@ constexpr float BLUE_FLY_PULL_MAX = 2; constexpr float BLUE_FLY_FRICTION = 0.8f; constexpr float BLUE_FLY_STUN_FRICTION = 0.96f; -// The birds' chase. +// The birds' chase (Bird Cage's further, slower and away from the player), and Lil Haunt's cry and fading. constexpr float BIRD_RANGE = 300; +constexpr float BIRD_CAGE_RANGE = 360; constexpr int BIRD_TARGET_INTERVAL = 13; -constexpr uint32_t BIRD_TARGET_FLAGS = TARGET_RETARGET | TARGET_PREFER_HEALTHY | TARGET_PREFER_WEAK; constexpr float BIRD_FRICTION = 0.9f; +constexpr float BIRD_CAGE_PULL = 0.8f; constexpr float BIRD_RETURN_DISTANCE = 6400; +constexpr int SOUND_LIL_HAUNT_CHASE = 859; +constexpr int LIL_HAUNT_CRY_DELAY = 450; +constexpr int LIL_HAUNT_VERSUS_CHASE_FRAMES = 599; +constexpr float LIL_HAUNT_IDLE_ALPHA = 0.5f; +constexpr float LIL_HAUNT_FADE = 0.15f; // Demon Baby's shots. constexpr float AUTO_SHOOTER_RANGE = 150; @@ -226,27 +232,47 @@ void Entity_Familiar::ai_auto_shooter() if (variant != BUMBO) play_idle_anim(); } -// 0061b8c0 Dead Bird and its kin: flies after enemies, back to the player when it strays with none, flapping. Bird Cage -// and Lil Haunt hunt their own ways, which stops the game. +// 0061b8c0 Dead Bird and its kin (Eve's Bird Foot, Best Bud, Lil Haunt, Bird Cage's bird): flies after enemies, back +// to the player when it strays with none. Lil Haunt cries when it finds one and fades while it has none. void Entity_Familiar::ai_flying_bird() { - if (variant == BIRD_CAGE || variant == LIL_HAUNT) - return reconstruction_missing("Entity_Familiar::ai_flying_bird 0061b8c0 (Bird Cage and Lil Haunt)"); + float pull = 1; + float birdFriction = BIRD_FRICTION; + if (variant == BIRD_CAGE) + { + PickEnemyTarget( + {.range = BIRD_CAGE_RANGE, .frameInterval = BIRD_TARGET_INTERVAL, .flags = TARGET_PREFER_HEALTHY}); + pull = BIRD_CAGE_PULL; + birdFriction = BIRD_CAGE_PULL; + } + else + { + bool hadTarget = target != nullptr; + PickEnemyTarget({.range = BIRD_RANGE, .frameInterval = BIRD_TARGET_INTERVAL}); + if (!hadTarget && target && variant == LIL_HAUNT) + familiar_sound_play(SOUND_LIL_HAUNT_CHASE, {.frameDelay = LIL_HAUNT_CRY_DELAY}); + } + if (variant == LIL_HAUNT) familiar_chase_limit(*this, LIL_HAUNT_VERSUS_CHASE_FRAMES); - PickEnemyTarget({.range = BIRD_RANGE, .frameInterval = BIRD_TARGET_INTERVAL, .flags = BIRD_TARGET_FLAGS}); - if (target) velocity = vector_add(velocity, vector_normalized(vector_sub(target->pos, pos))); + if (target) velocity = vector_add(velocity, vector_scale(vector_normalized(vector_sub(target->pos, pos)), pull)); else { Vector home = vector_sub(player->pos, pos); if (vector_length_squared(home) > BIRD_RETURN_DISTANCE) - velocity = vector_add(velocity, vector_normalized(home)); + velocity = vector_add(velocity, vector_scale(vector_normalized(home), pull)); } - if (variant == DEAD_BIRD) sprite.Play("Flying"); + if (variant == DEAD_BIRD || variant == BIRD_CAGE) sprite.Play("Flying"); else if (variant == EVES_BIRD_FOOT) sprite.Play("FlyingTransparent"); else if (variant == BEST_BUD) sprite.Play("Idle"); + else if (variant == LIL_HAUNT) + { + sprite.Play(target ? "FloatChase" : "Float"); + float alpha = sprite.color._tint[3]; + sprite.color._tint[3] = ((target ? 1 : LIL_HAUNT_IDLE_ALPHA) - alpha) * LIL_HAUNT_FADE + alpha; + } sprite.isFlipX = velocity.x > 0; - velocity = vector_scale(velocity, BIRD_FRICTION); + velocity = vector_scale(velocity, birdFriction); } // 00615d80 A blue fly: stunned a moment after it spawns, then circles its parent (or player) until an enemy comes near, diff --git a/src/familiar_bums.cpp b/src/familiar_bums.cpp new file mode 100644 index 0000000..32ddba9 --- /dev/null +++ b/src/familiar_bums.cpp @@ -0,0 +1,324 @@ +#include "entity_familiar.h" +#include "entity_list.h" +#include "entity_npc.h" +#include "entity_pickup.h" +#include "entity_player.h" +#include "game.h" +#include "item_pool.h" +#include "npc_ai.h" +#include "room_grid.h" +#include + +// How the bums trail: the player within this reach (or the bum ahead of them in line), pulled toward the one they +// follow, and the reach of their pickup hunt. +constexpr float BUM_PLAYER_REACH = 80; +constexpr float BUM_LINE_REACH = 50; +constexpr float BUM_FOLLOW_PULL = 0.8f; +constexpr float BUM_CHASE_PULL = 1.1f; +constexpr float BUM_TOUCH_DISTANCE_SQUARED = 100; +constexpr float BUM_FRICTION = 0.8f; +constexpr int BUM_SEARCH_INTERVAL = 5; +constexpr float BUM_SEARCH_RADIUS = 200; +constexpr float BUM_SEARCH_DISTANCE_SQUARED = 40000; +constexpr float BUM_SPIDER_HEIGHT = -30; + +// What fills a bum before it pays: Bum Friend's coins, Dark Bum's red hearts. Key Bum waits for more keys than its +// state. +constexpr int BUM_FRIEND_COINS = 5; +constexpr int DARK_BUM_HEARTS = 2; + +// Bum Friend's price (one more half the time without BFFS!), and its item once it holds ten coins. +constexpr int BUM_FRIEND_PRICE = 3; +constexpr int BUM_FRIEND_ITEM_PRICE = 10; +constexpr int BUM_FRIEND_ITEM_CHANCE = 3; +constexpr int BUM_FRIEND_RARE_ITEM_CHANCE = 100; +constexpr int BUM_FRIEND_DROPS[] = {PICKUP_HEART, PICKUP_KEY, PICKUP_BOMB}; + +// Dark Bum's price and its occasional extra heart, and Key Bum's price and chests. +constexpr int DARK_BUM_PRICE = 3; +constexpr int DARK_BUM_EXTRA_HEART_CHANCE = 10; +constexpr int DARK_BUM_DROP_KINDS = 5; +constexpr int KEY_BUM_PRICE = 4; +constexpr int KEY_BUM_BFFS_PRICE = 3; +constexpr int KEY_BUM_DROPS[] = {PICKUP_CHEST, PICKUP_LOCKEDCHEST, PICKUP_REDCHEST}; + +// What a charged key leaves a Key Bum: a full battery. +constexpr int CHARGED_KEY_BATTERY = 1; + +// Bumbo grows with coins at its last size, and Lil Portal rounds its coins up to a hundred. +constexpr int BUMBO_LAST_SIZE = 3; +constexpr int BUMBO_GROWTH_ODDS = 5; +constexpr int BUMBO_BFFS_GROWTH_ODDS = 4; +constexpr int LIL_PORTAL_COIN_ROUND = 100; + +// The bums that line up behind each other, and the red hearts Dark Bum hunts. +constexpr int LINED_BUM_VARIANTS[] = {Entity_Familiar::BUM_FRIEND, Entity_Familiar::DARK_BUM, Entity_Familiar::KEY_BUM, + Entity_Familiar::SUPER_BUM, Entity_Familiar::BUMBO}; +constexpr int RED_HEART_SUBTYPES[] = {HEART_FULL, HEART_HALF, HEART_DOUBLEPACK, HEART_SCARED}; + +// What the bums' payouts draw. +enum BumDrop +{ + BUM_DROP_SPIDER, + BUM_DROP_PILL, + BUM_DROP_CARD +}; + +// Whether a bum hunts this pickup: coins for Bum Friend, red hearts for Dark Bum, keys but golden ones for Key Bum, +// all of them for Super Bum. +static bool is_bum_pickup(int bumVariant, Entity_Pickup& pickup) +{ + bool isSuper = bumVariant == Entity_Familiar::SUPER_BUM; + if (pickup.variant == PICKUP_COIN) return bumVariant == Entity_Familiar::BUM_FRIEND || isSuper; + if (pickup.variant == PICKUP_HEART) + return (bumVariant == Entity_Familiar::DARK_BUM || isSuper) && + familiar_listed(RED_HEART_SUBTYPES, pickup.subtype); + if (pickup.variant == PICKUP_KEY) + return (bumVariant == Entity_Familiar::KEY_BUM || isSuper) && pickup.subtype != KEY_GOLDEN; + return false; +} + +// Part of 006e8ae0: a bum (or Bumbo, for coins) touching a pickup it hunts counts it. A charged key also leaves a +// battery. False when the bum does not take it. +bool bum_pickup_collect(Entity_Familiar& bum, Entity_Pickup& pickup) +{ + int hunter = bum.variant == Entity_Familiar::BUMBO ? (int)Entity_Familiar::BUM_FRIEND : bum.variant; + if (!is_bum_pickup(hunter, pickup)) return false; + + if (pickup.variant == PICKUP_COIN) bum.AddCoins(pickup.GetCoinValue()); + else if (pickup.variant == PICKUP_HEART) + bum.hearts += pickup.subtype == HEART_HALF ? 1 : pickup.subtype == HEART_DOUBLEPACK ? 4 : 2; + else + { + bum.keys += pickup.subtype == KEY_DOUBLEPACK ? 2 : 1; + if (pickup.subtype == KEY_CHARGED) + g_game + ->Spawn({.position = pickup.pos, + .subType = CHARGED_KEY_BATTERY, + .type = ENTITY_PICKUP, + .variant = PICKUP_LIL_BATTERY, + .seed = pickup.dropRNG.Next()}) + ->Update(); + } + return true; +} + +// 0062a930 Counts coins a familiar collected. Lil Portal rounds its count up to a hundred and spits a blue fly, Bumbo +// at its last size grows a little more with every coin. +void Entity_Familiar::AddCoins(int count) +{ + coins += count; + if (variant == LIL_PORTAL) + { + int excess = coins % LIL_PORTAL_COIN_ROUND; + if (excess > 0) coins += (LIL_PORTAL_COIN_ROUND - 1) * excess; + player->AddBlueFlies(1, pos, nullptr); + return; + } + if (variant != BUMBO || state != BUMBO_LAST_SIZE) return; + + int odds = player->HasCollectible(COLLECTIBLE_BFFS) ? BUMBO_BFFS_GROWTH_ODDS : BUMBO_GROWTH_ODDS; + for (; count > 0; count--) + if (dropRNG.RandomInt(odds) == 0) counter++; +} + +// The free spot halfway between a bum and its player, where its payout drops. +static Vector bum_drop_spot(Entity_Familiar& bum) +{ + Vector half = vector_make(bum.pos.x * 0.5f + bum.player->pos.x * 0.5f, bum.pos.y * 0.5f + bum.player->pos.y * 0.5f); + return room_free_pickup_position_find({.position = half}); +} + +// Drops a bum's pickup at its spot, the drop generator seeding it. +static void bum_drop(Entity_Familiar& bum, Entity* spawner, int pickupVariant, int subtype) +{ + Vector spot = bum_drop_spot(bum); + g_game->Spawn({.position = spot, + .spawner = spawner, + .subType = subtype, + .type = ENTITY_PICKUP, + .variant = pickupVariant, + .seed = bum.dropRNG.Next()}); +} + +// Bum Friend's payout: three or four coins for a heart, key, bomb, trinket, pill, card or battery (Daemon's Tail +// mostly keeps the hearts away), or ten for a beggar's item, once a floor (rarely without the ten). +static void bum_friend_pay(Entity_Familiar& bum, int drops) +{ + RNG& rng = bum.dropRNG; + int price = BUM_FRIEND_PRICE; + if (!bum.player->HasCollectible(COLLECTIBLE_BFFS)) price += (int)rng.RandomInt(2); + bool isItem = bum.coins >= BUM_FRIEND_ITEM_PRICE && bum.subtype == 0 && rng.RandomInt(BUM_FRIEND_ITEM_CHANCE) == 0; + if (!isItem) isItem = rng.RandomInt(BUM_FRIEND_RARE_ITEM_CHANCE) == 0; + + int pickupVariant = PICKUP_COLLECTIBLE; + int subtype = 0; + if (isItem) + { + subtype = g_game->itemPool.GetCollectible(POOL_BEGGAR, rng.Next(), 0, 0, 0); + price = BUM_FRIEND_ITEM_PRICE; + bum.subtype = 1; + familiar_sound_play(SOUND_THUMBSUP); + } + else if (rng.RandomInt(2) == 0) + { + int kind = (int)rng.RandomInt(3); + if (kind == 0 && bum.player->HasTrinket(TRINKET_DAEMONS_TAIL) && Random() % DAEMONS_TAIL_ODDS != 0) + kind = (int)rng.RandomInt(2) + 1; + pickupVariant = BUM_FRIEND_DROPS[kind]; + } + else if (rng.RandomInt(3) == 0) pickupVariant = PICKUP_TRINKET; + else + { + uint32_t kind = rng.RandomInt(4); + pickupVariant = kind == 0 ? PICKUP_PILL : kind == 1 ? PICKUP_TAROTCARD : PICKUP_LIL_BATTERY; + } + + bum.coins = std::max(bum.coins - price, 0); + for (; drops > 0; drops--) bum_drop(bum, &bum, pickupVariant, subtype); +} + +// Dark Bum's payout: three red hearts (sometimes four without BFFS!) for a pill, a card, black hearts or a spider, +// blue or thrown. +static void dark_bum_pay(Entity_Familiar& bum, int drops) +{ + RNG& rng = bum.dropRNG; + bum.hearts -= DARK_BUM_PRICE; + if (rng.RandomInt(DARK_BUM_EXTRA_HEART_CHANCE) == 0 && !bum.player->HasCollectible(COLLECTIBLE_BFFS)) bum.hearts--; + familiar_sound_play(SOUND_DARK_BUM_PAYOUT); + + switch (rng.RandomInt(DARK_BUM_DROP_KINDS)) + { + case BUM_DROP_PILL: return bum_drop(bum, &bum, PICKUP_PILL, 0); + case BUM_DROP_CARD: return bum_drop(bum, &bum, PICKUP_TAROTCARD, 0); + case BUM_DROP_SPIDER: + { + Vector spot = bum_drop_spot(bum); + if (rng.RandomInt(2) != 0) + { + Entity_NPC::ThrowSpider(bum.pos, &bum, spot, false, BUM_SPIDER_HEIGHT); + return; + } + Vector still{}; + bum.player->numBlueSpiders++; + spawn_blue_spider(&spot, bum.player, &still); + return; + } + default: + for (; drops > 0; drops--) bum_drop(bum, &bum, PICKUP_HEART, HEART_BLACK); + } +} + +// Key Bum's payout: four keys (three with BFFS!) for a chest, a locked chest or a red chest, and a new number of keys +// to wait for. +static void key_bum_pay(Entity_Familiar& bum, int drops) +{ + RNG& rng = bum.dropRNG; + int price = bum.player->HasCollectible(COLLECTIBLE_BFFS) ? KEY_BUM_BFFS_PRICE : KEY_BUM_PRICE; + bum.state = (int)rng.RandomInt(price) + 2; + bum.keys = std::max(bum.keys - price, 0); + for (; drops > 0; drops--) + { + Vector spot = bum_drop_spot(bum); + uint32_t seed = rng.Next(); + g_game->Spawn({.position = spot, + .type = ENTITY_PICKUP, + .variant = KEY_BUM_DROPS[rng.RandomInt(3)], + .seed = seed}); + } +} + +// A bum without a pickup to chase trails the player, or the bum ahead of it, and readies its payout once full and +// near the player. +static void bum_follow(Entity_Familiar& bum) +{ + Vector lead = bum.player->pos; + float leadReach = BUM_PLAYER_REACH; + for (Entity_Familiar* other : familiar_query(-1)) + { + if (!other->isExists) continue; + if (other == &bum) break; + if (!familiar_listed(LINED_BUM_VARIANTS, other->variant)) continue; + + lead = other->pos; + leadReach = BUM_LINE_REACH; + } + + Vector toLead = vector_sub(lead, bum.pos); + float leadDistance = vector_length(toLead); + if (vector_length(vector_sub(bum.player->pos, bum.pos)) >= BUM_PLAYER_REACH) + { + if (leadReach < leadDistance) + bum.velocity = vector_make(toLead.x / leadDistance * BUM_FOLLOW_PULL + bum.velocity.x, + toLead.y / leadDistance * BUM_FOLLOW_PULL + bum.velocity.y); + return; + } + bool isFull = bum.coins > BUM_FRIEND_COINS || bum.hearts > DARK_BUM_HEARTS || bum.state < bum.keys; + if (isFull && bum.sprite.IsPlaying("FloatDown")) bum.sprite.Play("PreSpawn", PLAY_FORCED); +} + +// A bum reaching its pickup touches it. A sticky nickel cannot be taken and is struck off. True when the pickup is +// gone, which sends the bum looking right away. +static bool bum_chase(Entity_Familiar& bum) +{ + Vector toward = vector_sub(bum.target->pos, bum.pos); + if (vector_length_squared(toward) >= BUM_TOUCH_DISTANCE_SQUARED) + { + bum.velocity = vector_add(bum.velocity, vector_scale(vector_normalized(toward), BUM_CHASE_PULL)); + return false; + } + + bum.collide_with_entity(bum.target); + if (!bum.target || bum.target->isDead) + { + bum.target = nullptr; + return true; + } + if (bum.target->IsType(ENTITY_PICKUP, PICKUP_COIN, COIN_STICKYNICKEL)) + { + hit_list_insert(bum.hitList, *bum.target); + bum.target = nullptr; + } + return false; +} + +// The nearest free pickup the bum hunts within reach, skipping the ones it struck off (but nickels). +static void bum_target_pick(Entity_Familiar& bum) +{ + float best = BUM_SEARCH_DISTANCE_SQUARED; + for (Entity* entity : entity_query_radius(bum.pos, BUM_SEARCH_RADIUS, QUERY_PICKUPS)) + { + if (entity->type != ENTITY_PICKUP) continue; + + auto& pickup = static_cast(*entity); + bool isStruck = EntityList::HitListContains(bum.hitList, pickup) && + !(pickup.variant == PICKUP_COIN && pickup.subtype == COIN_NICKEL); + float distance = vector_length_squared(vector_sub(pickup.pos, bum.pos)); + if (!is_bum_pickup(bum.variant, pickup) || pickup.isDead || pickup.price != 0 || isStruck || distance >= best) + continue; + + bum.target = &pickup; + best = distance; + } +} + +// 0061a4e0 Bum Friend, Dark Bum, Key Bum and Super Bum: chase the pickups they take, else trail the player in line, +// and pay out once full and near the player, Super Bum paying its coins first, then its hearts, then its keys. +void Entity_Familiar::ai_pickup_sack() +{ + bool isSearchDue = false; + if (target && !target->isDead) isSearchDue = bum_chase(*this); + else bum_follow(*this); + friction *= BUM_FRICTION; + if ((isSearchDue || IsFrame(BUM_SEARCH_INTERVAL, 0)) && !target) bum_target_pick(*this); + + if (sprite.IsFinished("Spawn")) return sprite.Play("FloatDown"); + if (!sprite.IsFinished("PreSpawn")) return; + + sprite.Play("Spawn", PLAY_FORCED); + bool isSuper = variant == SUPER_BUM; + int drops = isSuper ? 2 : 1; + if (variant == BUM_FRIEND || (isSuper && coins > BUM_FRIEND_COINS)) bum_friend_pay(*this, drops); + else if (variant == DARK_BUM || (isSuper && hearts > DARK_BUM_HEARTS)) dark_bum_pay(*this, drops); + else if (variant == KEY_BUM || isSuper) key_bum_pay(*this, drops); +} diff --git a/src/familiar_collision.cpp b/src/familiar_collision.cpp index f06ff24..fb6da36 100644 --- a/src/familiar_collision.cpp +++ b/src/familiar_collision.cpp @@ -36,8 +36,6 @@ constexpr int CHARGER_BUMP_RECOVER = 30; constexpr float SPIN_HIT_PUSH = 5; constexpr float SPIN_HIT_SCALE = 1.5f; constexpr float SPIN_HIT_BASE = 6; -constexpr int PLAYERFORM_LORD_OF_THE_FLIES_ID = 1; -constexpr int PLAYERFORM_SPIDERBABY_ID = 12; // The blue flies' and spiders' pop, and the locusts' tear effects. constexpr int SOUND_INSECT_POP = 1015; @@ -80,14 +78,6 @@ enum LocustKind LOCUST_DEATH }; -// Sorted insertion into a hit list, as the entities keep them. -static void hit_list_add(std::vector& hitList, Entity& entity) -{ - uint32_t index = entity.GetHitListIndex(); - auto at = std::lower_bound(hitList.begin(), hitList.end(), index); - if (at == hitList.end() || *at != index) hitList.insert(at, index); -} - // A blue fly popping on what it hit: a puff, then its locust's effect (an explosion, poison, slowing or death). static void blue_fly_pop(Entity_Familiar& fly, Entity& collider, float damageMultiplier) { @@ -143,7 +133,7 @@ static void brain_explode(Entity_Familiar& brain, Entity& collider, float damage // blue fly or spider bounces off an enemy too fast for it, then the blue flies and spiders pop and the brains blow. bool Entity_Familiar::collision_contact(Entity& collider, float damageMultiplier, float damage) { - hit_list_add(hitList, collider); + hit_list_insert(hitList, collider); bool isIgnored = true; bool isSwatted = false; if (familiar_listed(CONTACT_VARIANTS, variant)) @@ -233,7 +223,7 @@ bool Entity_Familiar::HandleCollision(Entity* collider, bool isLow) player->velocity = vector_sub(player->velocity, away); } collider->TakeDamage(collisionDamage * SPIN_HIT_SCALE + SPIN_HIT_BASE, 0, EntityRef(this), 0); - hit_list_add(hitList, *collider); + hit_list_insert(hitList, *collider); } bool isOwnersFoe = !spawnerEntity || !spawnerEntity->IsDescendantOf(collider); @@ -248,8 +238,8 @@ bool Entity_Familiar::HandleCollision(Entity* collider, bool isLow) Entity_Player& touched = *static_cast(collider); bool isFlyLord = touched.HasCollectible(COLLECTIBLE_SKATOLE) || - (touched.variant == PLAYER_VARIANT_PLAYER && touched.HasPlayerForm(PLAYERFORM_LORD_OF_THE_FLIES_ID)); - bool isSpiderLord = touched.variant == PLAYER_VARIANT_PLAYER && touched.HasPlayerForm(PLAYERFORM_SPIDERBABY_ID); + (touched.variant == PLAYER_VARIANT_PLAYER && touched.HasPlayerForm(PLAYER_FORM_BEELZEBUB)); + bool isSpiderLord = touched.variant == PLAYER_VARIANT_PLAYER && touched.HasPlayerForm(PLAYER_FORM_SPIDER_BABY); if (isFlyLord && (variant == BLUE_FLY || variant == BLUE_SPIDER || variant == ABYSS_LOCUST)) return true; if (isSpiderLord && (variant == BLUE_SPIDER || variant == SPIDER_BABY)) return true; } diff --git a/src/familiar_evaluate.cpp b/src/familiar_evaluate.cpp index c4a955a..b85ed4d 100644 --- a/src/familiar_evaluate.cpp +++ b/src/familiar_evaluate.cpp @@ -78,7 +78,6 @@ constexpr int TRINKET_ISAACS_HEAD = 54; constexpr int TRINKET_SOUL = 57; constexpr int TRINKET_FOUND_SOUL_ID = 180; constexpr int SOUL_TRINKET_CAP = 3; -constexpr int PLAYERFORM_SPIDERBABY = 12; constexpr int FORM_RNG_SHIFT = 35; constexpr int FAMILIAR_ACHIEVEMENT_COUNT = 4; constexpr int ACHIEVEMENT_FAMILIARS = 355; @@ -254,7 +253,7 @@ void familiars_evaluate(Entity_Player& p) unwritten_familiars_check(p); familiar_check(p, {.rng = &formRng, - .count = p.HasPlayerForm(PLAYERFORM_SPIDERBABY) ? 1 : 0, + .count = p.HasPlayerForm(PLAYER_FORM_SPIDER_BABY) ? 1 : 0, .variant = Entity_Familiar::SPIDER_BABY}); trinket_check(p, TRINKET_ISAACS_HEAD, Entity_Familiar::ISAACS_HEAD, p.HasTrinket(TRINKET_ISAACS_HEAD) ? 1 : 0); trinket_check(p, TRINKET_SOUL, Entity_Familiar::BLUE_BABY_SOUL, diff --git a/src/familiar_missing.cpp b/src/familiar_missing.cpp index 74a3f47..8632fee 100644 --- a/src/familiar_missing.cpp +++ b/src/familiar_missing.cpp @@ -99,24 +99,12 @@ bool Entity_Familiar::CanPlayerFire() reconstruction_missing("Entity_Familiar::CanPlayerFire 0062a8f0"); } -// 00616db0 -void Entity_Familiar::ai_walker() -{ - reconstruction_missing("Entity_Familiar::ai_walker 00616db0"); -} - // 0061a240 void Entity_Familiar::ai_blue_babys_only_friend() { reconstruction_missing("Entity_Familiar::ai_blue_babys_only_friend 0061a240"); } -// 0061a4e0 -void Entity_Familiar::ai_pickup_sack() -{ - reconstruction_missing("Entity_Familiar::ai_pickup_sack 0061a4e0"); -} - // 0061bd50 void Entity_Familiar::ai_daddy_longlegs() { @@ -135,12 +123,6 @@ void Entity_Familiar::ai_key_full() reconstruction_missing("Entity_Familiar::ai_key_full 0061d6b0"); } -// 0062a930 -void Entity_Familiar::AddCoins(int) -{ - reconstruction_missing("Entity_Familiar::AddCoins 0062a930"); -} - // 0062c8d0 void Entity_Familiar::farting_baby_fart() { diff --git a/src/familiar_shoot.cpp b/src/familiar_shoot.cpp index 6dba89b..bb28126 100644 --- a/src/familiar_shoot.cpp +++ b/src/familiar_shoot.cpp @@ -11,7 +11,6 @@ // The items and trinkets the familiars' shots read. constexpr int COLLECTIBLE_HIVE_MIND = 248; -constexpr int COLLECTIBLE_TINY_PLANET = 233; constexpr int TRINKET_FORGOTTEN_LULLABY = 141; constexpr int TRINKET_ISAACS_HEAD_ID = 54; diff --git a/src/familiar_walker.cpp b/src/familiar_walker.cpp new file mode 100644 index 0000000..e9e2d77 --- /dev/null +++ b/src/familiar_walker.cpp @@ -0,0 +1,106 @@ +#include "boss_ai.h" +#include "entity_effect.h" +#include "entity_familiar.h" +#include "entity_player.h" +#include "game.h" +#include "npc_ai.h" +#include + +// The walkers' hunt: their reach grows with their contact damage, and they head home once this far from the one +// they follow. +constexpr float WALKER_RANGE_PER_DAMAGE = 15; +constexpr float WALKER_RANGE_BASE = 65; +constexpr int WALKER_TARGET_INTERVAL = 8; +constexpr float WALKER_HOME_DISTANCE_SQUARED = 6400; + +// Their pace (faster for the last Cube of Meat and Leech, a little less in a versus match), as the path finder +// takes it. +constexpr float WALKER_SPEED = 1.8f; +constexpr float WALKER_FAST_SPEED = 2.2f; +constexpr float WALKER_VERSUS_SPEED = 2; +constexpr float WALKER_PATH_SCALE = 0.83f; +constexpr float WALKER_FRICTION = 0.85f; +constexpr float WALKER_IDLE_SPEED = 2; + +// The blood the bigger Cubes of Meat drip, one frame in four. +constexpr int WALKER_DRIP_ODDS = 4; +constexpr float WALKER_DRIP_SCALE = 0.3f; +constexpr float WALKER_DRIP_SCALE_BASE = 0.1f; + +// How long a versus walker chases one target before it gives up on it for a while. +constexpr int WALKER_VERSUS_CHASE_FRAMES = 449; + +// Leech joins the line of leeches: behind the last one following something, else behind the player. +static Vector leech_lead_find(Entity_Familiar& leech) +{ + if (leech.parent) return leech.parent->pos; + + Vector lead = leech.player->pos; + for (Entity* entity : entity_query(ENTITY_FAMILIAR, Entity_Familiar::LEECH)) + { + if (!entity->isExists || !entity->parent || entity->child) continue; + + leech.parent = entity; + entity->child = &leech; + lead = entity->pos; + break; + } + if (!leech.parent) leech.parent = leech.player; + return lead; +} + +// The animation a walker shows for its motion: Leech's moves and bites by direction, the Cubes of Meat and Balls of +// Bandages walking sideways or up and down. Facing left flips the sideways ones. +static void walker_animate(Entity_Familiar& walker, bool isChasing) +{ + bool isLeech = walker.variant == Entity_Familiar::LEECH; + Vector motion = walker.velocity; + if (vector_length(motion) < WALKER_IDLE_SPEED) + { + if (!isLeech) walker.sprite.Play("Idle"); + else if (walker.sprite.animState.animData) walker.sprite.animState.SetFrameFloat(0); + return; + } + + if (std::fabs(motion.y) < std::fabs(motion.x)) + { + walker.sprite.Play(!isLeech ? "WalkHori" : isChasing ? "Attack Hori" : "Move Hori"); + walker.sprite.isFlipX = motion.x < 0; + } + else if (!isLeech) walker.sprite.Play("WalkVert"); + else if (isChasing) walker.sprite.Play(motion.y > 0 ? "Attack Down" : "Attack Up"); + else walker.sprite.Play(motion.y > 0 ? "Move Down" : "Move Up"); +} + +// 00616db0 The walkers (the bigger Cubes of Meat and Balls of Bandages, Leech): path to the nearest enemy in reach, +// else home to the player (Leech to the leech ahead), the cubes dripping blood. +void Entity_Familiar::ai_walker() +{ + Vector home = variant == LEECH ? leech_lead_find(*this) : player->pos; + familiar_chase_limit(*this, WALKER_VERSUS_CHASE_FRAMES); + + PickEnemyTarget({.range = collisionDamage * WALKER_RANGE_PER_DAMAGE + WALKER_RANGE_BASE, + .frameInterval = WALKER_TARGET_INTERVAL}); + Vector goal = target ? target->pos : home; + float reach = target ? 0 : WALKER_HOME_DISTANCE_SQUARED; + bool isChasing = false; + if (vector_length_squared(vector_sub(goal, pos)) > reach) + { + float speed = variant == CUBE_OF_MEAT_4 || variant == LEECH ? WALKER_FAST_SPEED : WALKER_SPEED; + if (familiar_versus() && variant == CUBE_OF_MEAT_4) speed = WALKER_VERSUS_SPEED; + pathfinder.FindGridPath(goal, speed * WALKER_PATH_SCALE, 0, DIRECT_PATH_FAR); + isChasing = target != nullptr; + } + + if ((variant == CUBE_OF_MEAT_3 || variant == CUBE_OF_MEAT_4) && Random() % WALKER_DRIP_ODDS == 0) + { + Entity* drip = + g_game->Spawn({.position = pos, .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_SPLAT, .seed = Random()}); + float scale = random_unit() * WALKER_DRIP_SCALE + WALKER_DRIP_SCALE_BASE; + drip->sprite.scale = vector_make(scale, scale); + drip->Update(); + } + + friction *= WALKER_FRICTION; + walker_animate(*this, isChasing); +} diff --git a/src/fx_layers.cpp b/src/fx_layers.cpp index 3db8903..95a4ea6 100644 --- a/src/fx_layers.cpp +++ b/src/fx_layers.cpp @@ -1,5 +1,6 @@ #include "fx_layers.h" #include "data.h" +#include "entity_effect.h" #include "game.h" #include "log.h" #include "manager.h" @@ -56,7 +57,6 @@ constexpr int DELETE_THIS_STAGES = 11; constexpr int STAGE_TYPE_COUNT = 5; constexpr uint32_t CURSE_DARKNESS = 1; constexpr uint32_t CHALLENGE_DELETE_THIS = 45; -constexpr uint32_t EFFECT_SPRITE_TRAIL = 166; // A normal room shows its floor's light rays one time in RAY_ODDS (in RAY_ODDS_CHAPTER_ONE on the first chapter). constexpr uint32_t RAY_ODDS = 2; diff --git a/src/game.h b/src/game.h index c56d289..fcb64d6 100644 --- a/src/game.h +++ b/src/game.h @@ -317,6 +317,7 @@ public: void SetColorModifier(const ColorModState& color, bool isLerp, float rate); void save_rewind_state(int leaveDoor); void StartRoomTransition(RoomTransitionRequest request); + void ChangeRoom(int roomIndex, int dimension); void ShowHallucination(int frames, int backdrop); void Fadeout(float speed, FadeOutTarget target, KColor color = kcolor_rgba(0, 0, 0, 1)); void store_game_state(GameState& state); diff --git a/src/game_restore.cpp b/src/game_restore.cpp index 589402a..fa94414 100644 --- a/src/game_restore.cpp +++ b/src/game_restore.cpp @@ -606,8 +606,7 @@ void Entity_Player::RestoreGameState(GameStatePlayer& saved) isLevelStartPending = saved.isLevelStartPending; hasCurseMistEffect = saved.hasCurseMistEffect; consumablesBackup = saved.consumablesBackup; - if (!saved.curseMistFamiliars.empty()) - reconstruction_missing("Entity_Player::RestoreGameState 007ae4b0: Curse of the Mist's familiars"); + curseMistFamiliars = saved.curseMistFamiliars; curseMistRedHearts = saved.curseMistRedHearts; curseMistPocketItems = saved.curseMistPocketItems; curseMistTrinkets = saved.curseMistTrinkets; diff --git a/src/game_save.cpp b/src/game_save.cpp index 3ef06b1..2cd3242 100644 --- a/src/game_save.cpp +++ b/src/game_save.cpp @@ -415,8 +415,7 @@ void Entity_Player::StoreGameState(GameStatePlayer* saveState, bool isSaveTempor state.isLevelStartPending = isLevelStartPending; state.hasCurseMistEffect = hasCurseMistEffect; state.consumablesBackup = consumablesBackup; - state.curseMistFamiliars.clear(); - for (Entity_Familiar* familiar : curseMistFamiliars) familiar->store_backup(&state.curseMistFamiliars.emplace_back()); + state.curseMistFamiliars = curseMistFamiliars; state.curseMistRedHearts = curseMistRedHearts; state.curseMistPocketItems = curseMistPocketItems; state.curseMistTrinkets = curseMistTrinkets; diff --git a/src/game_state_player.h b/src/game_state_player.h index 460d2a7..a619616 100644 --- a/src/game_state_player.h +++ b/src/game_state_player.h @@ -18,24 +18,6 @@ constexpr int SAVE_FORGOTTEN_BODY_ROOM_NONE = -100000; constexpr int SAVE_MONKEY_PAW_CHARGES = 3; constexpr float SAVE_ROCK_BOTTOM_LUCK_UNSET = -9999; -// A familiar as it follows its player into a saved run or through Curse of the Mist (FamiliarData). -struct FamiliarData -{ - Vector formationTargetOffset{}; - float health = 0; - int coins = 0; - int hearts = 0; - int keys = 0; - int roomClearCount = 0; - int state = 0; - int subtype = 0; - int variant = 0; - uint32_t dropSeed = 0; - uint32_t initSeed = 0; - bool isNotCountedAsFollower = false; - bool isSubtype55555 = false; -}; - // A co-op baby or a sub player, by its character and health. struct CoPlayerState { diff --git a/src/grid_entity.cpp b/src/grid_entity.cpp index 2ce136c..8efd235 100644 --- a/src/grid_entity.cpp +++ b/src/grid_entity.cpp @@ -64,7 +64,6 @@ constexpr float SACRIFICE_LIKE_ITEM = 0.63f; constexpr float SACRIFICE_LIKE_FORM = 0.65f; constexpr int SACRIFICE_LIKE_COIN_COUNT = 6; constexpr int SACRIFICE_LIKE_FORM_STEPS = 3; -constexpr int PLAYER_FORM_EVIL_ANGEL = 8; constexpr float SACRIFICE_BLESS_SMALL = 0.15f; constexpr float SACRIFICE_BLESS_LARGE = 0.5f; constexpr int SACRIFICE_ANGEL_DELAY = 35; @@ -382,7 +381,7 @@ static void sacrifice_like_reward(GridEntity& spikes, RNG& reward, Entity_Player else if (roll < SACRIFICE_LIKE_ITEM) sacrifice_pickups_spawn(reward, position, PICKUP_COLLECTIBLE, 0, 1); else if (roll < SACRIFICE_LIKE_FORM && rewardPlayer) - rewardPlayer->IncrementPlayerFormCounter(PLAYER_FORM_EVIL_ANGEL, SACRIFICE_LIKE_FORM_STEPS); + rewardPlayer->IncrementPlayerFormCounter(PLAYER_FORM_LEVIATHAN, SACRIFICE_LIKE_FORM_STEPS); } // The sacrifice room's twelfth and later reward: half the time, unless the run ends before the Dark Room or Cathedral diff --git a/src/grid_entity_decoration.cpp b/src/grid_entity_decoration.cpp index 1ba31b1..ceb29d2 100644 --- a/src/grid_entity_decoration.cpp +++ b/src/grid_entity_decoration.cpp @@ -7,7 +7,6 @@ #include "room_render.h" #include "seeds.h" #include -#include #include #include @@ -20,113 +19,6 @@ constexpr int DECORATION_ATTEMPTS = 20; // A puddle stains a footprint with its texel under the player, any layer's that is not quite clear. constexpr float PUDDLE_ALPHA_THRESHOLD = 0.01f; -constexpr int ANY_LAYER = -1; - -// What Sprite::GetTexel samples: a screen position, where the sprite draws, the alpha a texel must reach and the -// layer it looks in (any for -1). -struct TexelQuery -{ - Vector sample{}; - Vector renderPos{}; - float alphaThreshold = 0; - int layerId = ANY_LAYER; -}; - -// Turns a point about the origin, as KAGE's Quad::rotate turns a quad's corners. -static Vector point_turn(Vector point, float cosine, float sine) -{ - return vector_make(point.x * cosine - point.y * sine, point.y * cosine + point.x * sine); -} - -// 0040b600 (ANM2::GetTexel) The color an animation of a sprite shows at a screen position: the texel of the first -// visible layer keyframe over it that reaches the alpha, in the sprite's, layer's and keyframe's tints and offsets -// (colorize aside), else clear. A turned layer is turned back about the origin, sample and all. -static KColor animation_texel_get(const ANM2& sprite, const AnimationState& animation, const TexelQuery& query) -{ - if (!animation.animData) return {}; - - const std::vector& tracks = animation.animData->animLayers; - for (size_t track = 0; track < tracks.size(); track++) - { - const AnimationLayer& layer = tracks[track]; - int frameIndex = track < animation.layerFrames.size() ? animation.layerFrames[track] : -1; - bool isLayerKnown = layer.layerId >= 0 && layer.layerId < (int)sprite.layerStates.size(); - if (layer.frames.empty() || (query.layerId >= 0 && layer.layerId != query.layerId) || !isLayerKnown) continue; - if (frameIndex < 0 || frameIndex >= (int)layer.frames.size()) continue; - - const AnimationFrame& frame = layer.frames[frameIndex]; - const LayerState& state = sprite.layerStates[layer.layerId]; - if (!frame.isVisible || !state.isVisible || !state.spriteSheet) continue; - - SpriteDraw draw = {.position = query.renderPos}; - SourceQuad source = AnimationLayer::GetSourceQuad(frame, state, draw, sprite); - DestinationQuad screen = AnimationLayer::GetDestQuad(frame, state, draw, sprite); - Vector sample = query.sample; - float layerTurn = frame.rotation + state.rotation; - float spriteTurn = sprite.rotation; - if (spriteTurn != 0 || layerTurn != 0) - { - float layerScaleX = frame.scale.x * state.size.x; - float layerScaleY = state.isFlipY ? -(frame.scale.y * state.size.y) : frame.scale.y * state.size.y; - float spriteScaleY = sprite.isFlipY ? -sprite.scale.y : sprite.scale.y; - if ((sprite.scale.x < 0) != (layerScaleX < 0)) - { - if (sprite.scale.x < 0) - { - layerTurn = -layerTurn; - spriteTurn = -spriteTurn; - } - if (layerScaleX < 0) layerTurn = -layerTurn; - } - if ((spriteScaleY < 0) != (layerScaleY < 0)) - { - if (spriteScaleY < 0) - { - layerTurn = -layerTurn; - spriteTurn = -spriteTurn; - } - if (layerScaleY < 0) layerTurn = -layerTurn; - } - - float angle = -(layerTurn + spriteTurn) * DEGREES_TO_RADIANS; - float cosine = std::cos(angle); - float sine = std::sin(angle); - for (Vector* corner : {&screen._topLeft, &screen._topRight, &screen._bottomLeft, &screen._bottomRight}) - *corner = point_turn(*corner, cosine, sine); - sample = point_turn(sample, cosine, sine); - } - - Vector topLeft = screen._topLeft; - Vector bottomRight = screen._bottomRight; - bool isOverX = topLeft.x < sample.x && sample.x < bottomRight.x; - if (!isOverX || topLeft.y >= sample.y || sample.y >= bottomRight.y) continue; - - float across = std::clamp((sample.x - topLeft.x) / (bottomRight.x - topLeft.x), 0.0f, 1.0f); - float down = std::clamp((sample.y - topLeft.y) / (bottomRight.y - topLeft.y), 0.0f, 1.0f); - float texelX = (source._bottomRight.x - source._topLeft.x) * across + source._topLeft.x; - float texelY = (source._bottomRight.y - source._topLeft.y) * down + source._topLeft.y; - KColor texel = image_texel_get(*state.spriteSheet, (uint32_t)(int)texelX, (uint32_t)(int)texelY); - if (texel._alpha < query.alphaThreshold) continue; - - ColorMod color = sprite.color; - color_multiply(color, state.color); - color_multiply(color, frame.color); - float red = color._tint[0] * texel._red + color._offset[0]; - float green = color._tint[1] * texel._green + color._offset[1]; - float blue = color._tint[2] * texel._blue + color._offset[2]; - return kcolor_rgba(red, green, blue, color._tint[3] * texel._alpha); - } - return {}; -} - -// 0040b590 (Sprite::GetTexel) The color a sprite shows at a screen position: its overlay's, unless that falls short -// of the alpha, then its main animation's. -static KColor sprite_texel_get(const ANM2& sprite, const TexelQuery& query) -{ - KColor texel = animation_texel_get(sprite, sprite.overlayAnimState, query); - if (texel._alpha < query.alphaThreshold) texel = animation_texel_get(sprite, sprite.animState, query); - return texel; -} // 0099acc0 Picks the prop: a crawlspace's ladder, Greed's props, or one of the backdrop's (G FUEL's on its seed) drawn // from the cell's decoration seed until it suits the backdrop and the room has no puddle yet. Counts the puddles. @@ -214,10 +106,10 @@ void GridEntity_Decoration::Update() if (player->entityGridCollisionClass != GRIDCOLL_GROUND) continue; - TexelQuery query = {.sample = render_position_get(player->pos, RENDER_SNAPPED), - .renderPos = get_render_position(), + TexelQuery query = {.renderPos = get_render_position(), + .sample = render_position_get(player->pos, RENDER_SNAPPED), .alphaThreshold = PUDDLE_ALPHA_THRESHOLD}; - KColor texel = sprite_texel_get(sprite, query); + KColor texel = sprite.GetTexel(query); if (texel._alpha > 0) player->SetFootprintColor(texel, true); } diff --git a/src/grid_entity_door.cpp b/src/grid_entity_door.cpp index 8760292..66e00b4 100644 --- a/src/grid_entity_door.cpp +++ b/src/grid_entity_door.cpp @@ -13,7 +13,6 @@ constexpr int DOOR_TARGET_MIRROR = -100; constexpr int DOOR_TARGET_MINESHAFT = -101; // The stage of the Blue Womb, the dimension of Downpour's mirror world and of Home's dark closet, and Home's stage. -constexpr int DIMENSION_MIRROR = 1; constexpr int DIMENSION_DEATH_CERTIFICATE = 2; // The secret exits get_secret_exit_kind tells apart, by the exit room's subtype, and the boss subtype of Mom's Heart's diff --git a/src/grid_entity_poop.cpp b/src/grid_entity_poop.cpp index f994ccd..204e836 100644 --- a/src/grid_entity_poop.cpp +++ b/src/grid_entity_poop.cpp @@ -100,7 +100,6 @@ constexpr int BLACK_POOP_CONFUSION = 60; constexpr ColorMod BLACK_POOP_CLOUD = {{0.01f, 0.01f, 0.01f, 1}, {0, 0, 0, 1}, {0, 0, 0}}; constexpr float BROWN_CAP_DAMAGE = 100; constexpr float BROWN_CAP_RADIUS = 50; -constexpr int PLAYER_FORM_POOP = 9; constexpr int OH_CRAP_FORM_COUNT = 3; // The gibs: a third more of them per hit with Extra Blood, how fast they fly, and a rainbow gib's flatter throw. @@ -856,7 +855,7 @@ static void meconium_drop_try(const Vector& position, const EntityRef& source, R // Whether a player has the Oh Crap form and so heals on broken poop. static bool is_oh_crap(Entity_Player& player) { - return !player.hasCurseMistEffect && !player.isCoopGhost && player.playerForms[PLAYER_FORM_POOP] >= OH_CRAP_FORM_COUNT; + return !player.hasCurseMistEffect && !player.isCoopGhost && player.playerForms[PLAYER_FORM_OH_CRAP] >= OH_CRAP_FORM_COUNT; } // Lil Larva's blue flies and Brown Cap's blast from a broken poop (the breaker's trinkets in versus). diff --git a/src/homing_laser.cpp b/src/homing_laser.cpp index fa583ee..999b3ad 100644 --- a/src/homing_laser.cpp +++ b/src/homing_laser.cpp @@ -1,5 +1,6 @@ #include "homing_laser.h" #include "boss_ai.h" +#include "entity_familiar.h" #include "entity_laser.h" #include "entity_player.h" #include "entity_tear.h" @@ -16,6 +17,15 @@ constexpr float SMOOTHING_FULL_LENGTH = 200; constexpr float PLAYER_CUT_DISTANCE_SQUARED = 100; constexpr uint32_t PLAYER_CUT_FIRST_SAMPLE = 2; constexpr float GRID_HALF_CELL = GRID_CELL_SIZE / 2; +constexpr float OBSTACLE_MARGIN = 20; + +// A hunting path: 40 long steps turned 0.3 toward the nearest target, up to 25 points, smoothed at 0.4. A path shorter +// than 0.1 does not hunt. +constexpr float HUNT_STEP = 40; +constexpr float HUNT_TURN = 0.3f; +constexpr size_t HUNT_MAX_POINTS = 25; +constexpr float HUNT_TENSION = 0.4f; +constexpr float HUNT_MIN_LENGTH_SQUARED = 0.01f; // A point on the cubic curve from one bezier point to the next, t from 0 to 1. static Vector bezier_evaluate(const BezierPoint& from, const BezierPoint& to, float t) @@ -101,8 +111,63 @@ LineCheck room_line_check(const Vector& from, const Vector& to, int gridCollisio return {progress < 1 ? position : to, progress >= 1}; } +// The entities a homing path bends toward: vulnerable enemies (of another type than the source for that path type), +// a versus rival's punching bag, and the players too for a path that hits them. +static std::vector homing_targets_get(BezierPathType pathType, Entity* source) +{ + std::vector targets; + for (Entity* entity : g_game->room->entityList.updateEL) + { + bool isTarget = entity->IsVulnerableEnemy(nullptr) && !entity->HasEntityFlags(FLAG_FRIENDLY | FLAG_NO_TARGET) && + entity != source && !(pathType == BEZIER_PATH_OTHER_TYPES && entity->type == source->type); + bool isRivalBag = g_game->deathmatchManager.is_active() && entity->type == ENTITY_FAMILIAR && + entity->variant == Entity_Familiar::PUNCHING_BAG && + !entity->IsDescendantOf(source->spawnerEntity); + if (isTarget || isRivalBag) targets.push_back(entity); + if (pathType == BEZIER_PATH_WITH_PLAYERS && entity->type == ENTITY_PLAYER && entity != source) + targets.push_back(entity); + } + return targets; +} + +// A path that hunts its way from its origin through the room: 40 long steps, each turned toward the nearest target +// (more so the more it already faces it), until it leaves the room or has 25 points. +static void homing_hunt(HomingLaser& path, const std::vector& targets) +{ + Vector heading = vector_sub(path.bezier.back().point, path.bezier.front().point); + if (vector_length_squared(heading) < HUNT_MIN_LENGTH_SQUARED) return; + + path.bezier.pop_back(); + while (!targets.empty()) + { + Vector last = path.bezier.back().point; + Entity* nearest = nullptr; + float best = INFINITY; + for (Entity* target : targets) + { + float distance = vector_length_squared(vector_sub(last, target->pos)); + if (distance >= best) continue; + nearest = target; + best = distance; + } + if (!nearest) break; + + Vector toward = vector_normalized(vector_sub(nearest->pos, last)); + float facing = (vector_dot(vector_normalized(heading), toward) + 1) * BEZIER_HALF; + size_t count = path.bezier.size(); + if (count > 1) heading = vector_sub(path.bezier[count - 1].point, path.bezier[count - 2].point); + heading = vector_normalized(vector_add(vector_normalized(heading), vector_scale(toward, HUNT_TURN * facing))); + + Vector next = vector_add(last, vector_scale(heading, HUNT_STEP)); + path.bezier.push_back({next, {}, {}}); + if (!g_game->room->IsPositionInRoom(next, 0) || path.bezier.size() >= HUNT_MAX_POINTS) break; + } + path.compute_bezier_handles(HUNT_TENSION); +} + // 0099c790 Lays out the path's bezier points: a straight one from the origin to the end unless some are already -// there. The homing paths and Eye of the Occult's bend are not reconstructed yet. +// there, then for a path that hits players one hunting its targets. Eye of the Occult's bend and the homing and +// other types' bends toward their targets are not reconstructed yet. void HomingLaser::build_bezier_path(BezierPathType pathType, Entity* source) { if (bezier.empty()) @@ -112,11 +177,14 @@ void HomingLaser::build_bezier_path(BezierPathType pathType, Entity* source) bezier.push_back({endPoint, middle, endPoint}); } + std::vector targets; + if (pathType != BEZIER_PATH_STRAIGHT) targets = homing_targets_get(pathType, source); Entity_Laser* laser = owner && owner->type == ENTITY_LASER ? static_cast(owner) : nullptr; if (laser && laser->tearFlags[TEAR_OCCULT]) reconstruction_missing("HomingLaser::build_bezier_path 0099c790: Eye of the Occult's bend"); - if (pathType != BEZIER_PATH_STRAIGHT && source) + if (pathType == BEZIER_PATH_HOMING || pathType == BEZIER_PATH_OTHER_TYPES) reconstruction_missing("HomingLaser::build_bezier_path 0099c790: a homing path"); + if (pathType == BEZIER_PATH_WITH_PLAYERS && bezier.size() == 2) homing_hunt(*this, targets); } // 0099e360 Samples the bezier path evenly along its length, then eases the kept samples toward them: a ring all at @@ -301,10 +369,32 @@ void HomingLaser::compute_axis_bezier_handles() reconstruction_missing("HomingLaser::compute_axis_bezier_handles 0099dca0"); } -// 0099e160 -void HomingLaser::compute_bezier_handles(float) +// 0099e160 Smooths the path: each point's handles lie along the line from its neighbours, scaled by the tension +// (halved between two neighbours). A path ending where it started (three points or more) wraps around. +void HomingLaser::compute_bezier_handles(float tension) { - reconstruction_missing("HomingLaser::compute_bezier_handles 0099e160"); + if (bezier.empty()) return; + + size_t last = bezier.size() - 1; + bool isClosed = vector_length_squared(vector_sub(bezier[last].point, bezier[0].point)) < HUNT_MIN_LENGTH_SQUARED && + bezier.size() >= 3; + for (size_t i = 0; i <= last; i++) + { + Vector previous{}; + Vector next{}; + if (isClosed && i == 0) previous = vector_sub(bezier[0].point, bezier[last - 1].point); + else + { + if (isClosed && i == last) next = vector_sub(bezier[1].point, bezier[i].point); + if (i != 0) previous = vector_sub(bezier[i].point, bezier[i - 1].point); + } + if (i < last) next = vector_sub(bezier[i + 1].point, bezier[i].point); + + Vector handle = vector_scale(vector_add(previous, next), tension); + if (isClosed || (i != 0 && i < last)) handle = vector_scale(handle, BEZIER_HALF); + bezier[i].handleIn = vector_sub(bezier[i].point, handle); + bezier[i].handleOut = vector_add(bezier[i].point, handle); + } } // 0099ec00 @@ -325,10 +415,21 @@ void HomingLaser::build_wiggle_bezier() reconstruction_missing("HomingLaser::build_wiggle_bezier 0099fed0"); } -// 009a0c50 -void HomingLaser::truncate_samples_at_obstacle(const Vector&) +// 009a0c50 Cuts the path at the first segment past the first that a wall or obstacle stops, the stop taking the +// place of the segment's start. +void HomingLaser::truncate_samples_at_obstacle(const Vector& offset) { - reconstruction_missing("HomingLaser::truncate_samples_at_obstacle 009a0c50"); + for (size_t i = 1; i + 1 < samples.size(); i++) + { + Vector start = samples[i]; + Vector segment = vector_sub(samples[i + 1], start); + Vector stop = Entity_Laser::CalculateEndPoint(start, vector_normalized(segment), offset, nullptr, OBSTACLE_MARGIN); + if (vector_length_squared(vector_sub(start, stop)) >= vector_length_squared(segment)) continue; + + samples[i] = stop; + samples.resize(i + 1); + return; + } } // 009a0fa0 diff --git a/src/info_display.cpp b/src/info_display.cpp index fa53ff9..defb783 100644 --- a/src/info_display.cpp +++ b/src/info_display.cpp @@ -17,8 +17,6 @@ constexpr int DEFAULT_TRINKET_COUNT = 190; constexpr int DEFAULT_CARD_COUNT = 98; constexpr int DEFAULT_PILL_COUNT = 50; -// Necromancer's items, which count toward it without a tag. -constexpr int PLAYER_FORM_NECROMANCER = 15; // A group of info_display.xml: its element names and the kind of entry it fills. struct InfoDisplayGroup diff --git a/src/item_config.h b/src/item_config.h index e179224..0934ede 100644 --- a/src/item_config.h +++ b/src/item_config.h @@ -26,6 +26,27 @@ constexpr int EXTRA_WISP_SLOTS = 19; constexpr int TAG_CACHE_SLOTS = 32; constexpr int LOCUST_QUALITY_COUNT = 5; +// Lua's PlayerForm: the transformations, by the slot of Entity_Player::playerForms that counts their items. +enum PlayerForm : int +{ + PLAYER_FORM_GUPPY, + PLAYER_FORM_BEELZEBUB, + PLAYER_FORM_FUN_GUY, + PLAYER_FORM_SERAPHIM, + PLAYER_FORM_BOB, + PLAYER_FORM_SPUN, + PLAYER_FORM_YES_MOTHER, + PLAYER_FORM_CONJOINED, + PLAYER_FORM_LEVIATHAN, + PLAYER_FORM_OH_CRAP, + PLAYER_FORM_BOOKWORM, + PLAYER_FORM_ADULT, + PLAYER_FORM_SPIDER_BABY, + PLAYER_FORM_STOMPY, + PLAYER_FORM_FLIGHT, + PLAYER_FORM_NECROMANCER +}; + // What an ItemConfig_Item describes, by the XML element it came from. enum ItemType : int { diff --git a/src/item_overlay.h b/src/item_overlay.h index 21a0804..658febc 100644 --- a/src/item_overlay.h +++ b/src/item_overlay.h @@ -27,7 +27,8 @@ enum GiantbookOverlay : int GIANTBOOK_CLICKER = 39, GIANTBOOK_SLEEP_NIGHTMARE = 44, GIANTBOOK_MEGA_MUSH = 45, - GIANTBOOK_ETERNAL_BLACK_HEART = 46 + GIANTBOOK_ETERNAL_BLACK_HEART = 46, + GIANTBOOK_NECROMANCER = 47 }; // Destruction (009abd80) is the default. diff --git a/src/item_pickup.cpp b/src/item_pickup.cpp index 5758ad1..d7d83d5 100644 --- a/src/item_pickup.cpp +++ b/src/item_pickup.cpp @@ -5,6 +5,7 @@ #include "entity_pickup.h" #include "active_items.h" #include "entity_player.h" +#include "entity_player_tainted.h" #include "game.h" #include "grid_entity.h" #include "item_pool.h" @@ -14,6 +15,8 @@ #include "room_grid.h" #include "room_special.h" #include "seeds.h" +#include +#include // The items, characters, rooms and unlocks the pedestals ask about. constexpr int COLLECTIBLE_KEY_PIECE_A = 238; @@ -409,9 +412,9 @@ bool Entity_Pickup::collectible_collect(Entity_Player& player) else sprite.Play("Idle"); player.AnimatePickup(&sprite, false, HasEntityFlags(FLAG_NO_DEATH_TRIGGER) ? "UseItem" : "Pickup"); - bool isExchanged = item->type == ITEM_ACTIVE && active_pedestal_swap(*this, player); - if (item->type != ITEM_ACTIVE && player.playerType == PLAYER_ISAAC_B && player.CanAddCollectibleToInventory(item->id)) - reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: Tainted Isaac's inventory"); + bool isInventoryItem = player.playerType == PLAYER_ISAAC_B && player.CanAddCollectibleToInventory(item->id); + bool isExchanged = item->type == ITEM_ACTIVE ? active_pedestal_swap(*this, player) + : isInventoryItem && tainted_isaac_pedestal_swap(*this, player); if (game.deathmatchManager.is_active()) reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: the deathmatch's items"); @@ -503,8 +506,9 @@ void item_text_show(HUD& hud, Entity_Player* player, ItemConfig_Item* item) } // 006edfa0 Turns a cycling pedestal to its next item every 30 frames (every 6 with four or more, every frame with -// eight), every frame while paused, or at once when forced. An emptied pedestal stops cycling. Only the wait is -// reconstructed: a turn stops the game until reached. +// eight), every frame while paused, or at once when forced. The shown item goes to the back of the list and the first +// one is shown, keeping its price, seed, wait and animation frame. An emptied pedestal stops cycling. +// The original fills the list past its count with whatever its stack held. Here those entries keep their values. void Entity_Pickup::update_cycle_collectible(bool isForce) { constexpr int CYCLE_FRAMES_FEW = 30; @@ -521,5 +525,18 @@ void Entity_Pickup::update_cycle_collectible(bool isForce) return; } bool isTurn = isForce || (g_game->frameCount - spawnFrame >= 1 && IsFrame(frequency, 0)) || g_game->IsPaused(); - if (isTurn) reconstruction_missing("Entity_Pickup::update_cycle_collectible 006edfa0 (a turn)"); + if (!isTurn) return; + + std::array list = cycleCollectibleList; + uint32_t count = cycleCollectibleCount; + int heldWait = wait; + float frame = sprite.animState.animData ? std::floor(sprite.animState.animFrame) : -1; + std::shift_left(list.begin(), list.begin() + count, 1); + list[count - 1] = (uint32_t)subtype; + + Morph(type, variant, (int)cycleCollectibleList[0], true, true, true); + if (sprite.animState.animData) sprite.animState.SetFrameFloat(frame); + wait = heldWait; + cycleCollectibleList = list; + cycleCollectibleCount = count; } diff --git a/src/item_pool.cpp b/src/item_pool.cpp index aeee2eb..cb243b0 100644 --- a/src/item_pool.cpp +++ b/src/item_pool.cpp @@ -92,7 +92,6 @@ constexpr uint32_t DESCRIPTOR_DEVIL_TREASURE = 0x800; constexpr int BOSS_THE_FALLEN = 23; constexpr int HOME_CHEST_SUBTYPE = 2; -constexpr int COLLECTIBLE_ROTTEN_MEAT = 26; constexpr int COLLECTIBLE_ROSARY = 72; constexpr int COLLECTIBLE_VIRGO = 303; constexpr int COLLECTIBLE_CHAOS = 402; diff --git a/src/level.cpp b/src/level.cpp index 73c76c1..b4adc5f 100644 --- a/src/level.cpp +++ b/src/level.cpp @@ -89,18 +89,15 @@ constexpr int ACHIEVEMENT_STORE_UPGRADE_4 = 154; constexpr int ACHIEVEMENT_SOMETHING_WICKED = 346; constexpr int ACHIEVEMENT_SOMETHING_WICKED_PLUS = 347; constexpr int ACHIEVEMENT_THE_FORGOTTEN = 390; -constexpr int ACHIEVEMENT_PLANETARIUMS = 406; constexpr int EVENT_COUNTER_SUPER_SINS_A = 24; constexpr int EVENT_COUNTER_SUPER_SINS_B = 25; constexpr int EVENT_COUNTER_CURSE_ODDS = 11; constexpr int COLLECTIBLE_XRAY_VISION = 76; -constexpr int COLLECTIBLE_CRYSTAL_BALL = 158; constexpr int COLLECTIBLE_MAGIC_8_BALL = 194; constexpr int COLLECTIBLE_MOMS_SHOVEL = 552; constexpr int TRINKET_GOLDEN_HORSE_SHOE = 82; constexpr int TRINKET_FRAGMENTED_CARD = 102; constexpr int TRINKET_SILVER_DOLLAR = 110; -constexpr int TRINKET_PAY_TO_WIN = 112; constexpr int TRINKET_TELESCOPE_LENS = 152; constexpr int COLLECTIBLE_VOODOO_HEAD = 599; constexpr int TRINKET_MYOSOTIS = 137; @@ -3011,36 +3008,6 @@ int Level::GetNeighborRoomIdx(int roomIdx, int doorSlot) return neighbor < 0 ? -2 : neighbor; } -// 0074c9e0 The slots a red room would open toward. -uint32_t Level::get_red_room_neighbor_slots(int, int, int*) -{ - reconstruction_missing("Level::get_red_room_neighbor_slots 0074c9e0"); -} - -// 0074cb50 The layout room a red room door would make. -LevelGenerator_Room Level::get_door_neighbor_room(int, int) -{ - reconstruction_missing("Level::get_door_neighbor_room 0074cb50"); -} - -// 0074cd70 Whether a Red Key outline shows on a door. -bool Level::CanSpawnDoorOutline(int, int) -{ - reconstruction_missing("Level::CanSpawnDoorOutline 0074cd70"); -} - -// 0074cea0 A red room's type. -int Level::roll_red_room_type() -{ - reconstruction_missing("Level::roll_red_room_type 0074cea0"); -} - -// 0074d010 Opens a red room through a door. -bool Level::MakeRedRoomDoor(int, int) -{ - reconstruction_missing("Level::MakeRedRoomDoor 0074d010"); -} - // 0074d780 Adds a second boss room. bool Level::TryInitializeExtraBossRoom(uint32_t) { diff --git a/src/level.h b/src/level.h index 45fce5f..6fe5863 100644 --- a/src/level.h +++ b/src/level.h @@ -25,6 +25,9 @@ constexpr int PORTAL_ROOM_NONE = -99999; // The xorshift a level's RNGs start on before Level::Init seeds them (shift index 35). constexpr RNG LEVEL_RNG_DEFAULT = {RNG_SEED_DEFAULT, 5, 9, 7}; +// The mirror world's dimension, the mineshaft's on a Mines floor. +constexpr int DIMENSION_MIRROR = 1; + // The secret exit a floor's door leads to, also the exit room's layout subtype. Mom's Heart's leads to the Corpse // and the Ascent. enum SecretExitKind @@ -292,10 +295,10 @@ public: int GetTargetSlot(int roomIdx, int doorSlot); static XY get_door_neighbor_pos(XY gridPos, RoomShape shape, int doorSlot); int GetNeighborRoomIdx(int roomIdx, int doorSlot); - static uint32_t get_red_room_neighbor_slots(int roomIdx, int doorSlot, int* outSlots); + bool get_red_room_neighbor_slots(int roomIdx, int doorSlot, int* outSlot, int* outEntrySlot); LevelGenerator_Room get_door_neighbor_room(int roomIdx, int doorSlot); bool CanSpawnDoorOutline(int roomIdx, int doorSlot); - static int roll_red_room_type(); + static int roll_red_room_type(RNG& rng); bool MakeRedRoomDoor(int roomIdx, int doorSlot); void UncoverHiddenDoor(int roomIdx, int doorSlot); bool prepare_blue_room(int currentRoomIdx, int targetRoomIdx, int direction); diff --git a/src/level_red_room.cpp b/src/level_red_room.cpp new file mode 100644 index 0000000..08e44e1 --- /dev/null +++ b/src/level_red_room.cpp @@ -0,0 +1,310 @@ +#include "game.h" +#include "grid_entity_door.h" +#include "level.h" +#include "level_generator.h" +#include "log.h" +#include "manager.h" +#include "npc_ai.h" +#include "platform.h" +#include "room.h" +#include "room_config.h" +#include "sfx_manager.h" +#include + +// The map's width and height in cells. +constexpr int MAP_SIZE = 13; + +// The Red Key's weighted room types (weights out of 512, the rest a normal room), and what it makes of a planetarium +// before planetariums are unlocked. +constexpr std::array, 16> RED_ROOM_TYPES = {{{2, ROOM_DEVIL}, + {2, ROOM_ANGEL}, + {3, ROOM_SECRET}, + {3, ROOM_SUPERSECRET}, + {6, ROOM_SHOP}, + {4, ROOM_TREASURE}, + {2, ROOM_PLANETARIUM}, + {9, ROOM_CURSE}, + {8, ROOM_SACRIFICE}, + {5, ROOM_ARCADE}, + {2, ROOM_CHEST}, + {2, ROOM_DICE}, + {4, ROOM_LIBRARY}, + {2, ROOM_ISAACS}, + {2, ROOM_BARREN}, + {7, ROOM_MINIBOSS}}}; +constexpr uint32_t RED_ROOM_ROLL_MASK = 0x1ff; + +// The Red Key's room rng, and what a red room's config query asks: four doors, a devil or angel room's subtype and +// variant limit (Number Magnet's devil rooms), a miniboss's difficulty by floor, and Home's own rooms. +constexpr uint32_t RED_ROOM_ROW_SEED = 929; +constexpr std::array RED_ROOM_SHIFTS = {4, 3, 27}; +constexpr uint32_t RED_ROOM_DOORS = 0xf; +constexpr uint32_t RED_ROOM_SPECIAL_VARIANTS = 99; +constexpr int RED_ROOM_DIFFICULTY_MAX = 15; +constexpr int RED_ROOM_LATE_MINIBOSS = 10; +constexpr int RED_ROOM_LATE_STAGE = 6; +constexpr int HOME_STAGE_ID = 35; +constexpr int HOME_ROOM_SUBTYPE = 11; +constexpr int HOME_DIFFICULTY_MAX = 10; +constexpr XY HOME_RED_ROOM_CELL = {3, 7}; +constexpr int NEXT_STAGE_ROOM = -2; +constexpr int ROOM_IDX_MIN = -20; +constexpr int ROOM_IDX_MAX = 168; +constexpr int LAST_DOOR_SLOT = 7; + +// The slot a door enters a neighbouring room by: the opposite side, its second door when the neighbour's origin lies +// before the cell on that side. +static int entry_slot_get(int slot, const RoomDescriptor& neighbor, int cell) +{ + int entry = (slot + 2) % 4; + bool isHorizontal = entry == DOOR_UP0 || entry == DOOR_DOWN0; + if (isHorizontal ? neighbor.gridIndex % MAP_SIZE < cell % MAP_SIZE + : neighbor.gridIndex / MAP_SIZE < cell / MAP_SIZE) + entry += 4; + return entry; +} + +// Whether a neighbouring room may get a door back toward a red room: its layout has the slot, it is not the last boss +// room, nor the start room's bottom side on the Chest or Dark Room or with a photo door. Red Redemption allows all. +static bool is_entry_allowed(Level& level, const RoomDescriptor& neighbor, int entry, int slot) +{ + if (g_game->challenge == CHALLENGE_RED_REDEMPTION) return true; + + bool isStartDown = slot == DOOR_DOWN0 && neighbor.gridIndex == level.startingRoomIdx; + return (neighbor.data->doors & 1u << entry) && neighbor.listIndex != level.lastBossRoomListIdx && + (level.stage != STAGE_DARK_ROOM || !isStartDown) && (!level.HasPhotoDoor() || !isStartDown); +} + +// Room::open_red_room_doors 00827550: puts the room's new red doors in, leading to the red room (or the next floor), +// unlocked, removes the slot's red outline and plays the unlock sound. +static void red_doors_open(Room& room, int doorSlot, RoomDescriptor* target) +{ + for (int slot = 0; slot < DOOR_SLOT_COUNT; slot++) + { + if (!(room.descriptor->allowedDoors & 1u << slot) || room.doors[slot]) continue; + room.MakeDoor(slot); + GridEntity_Door* door = room.doors[slot]; + if (!door) continue; + + door->targetRoomIdx = target ? target->safeGridIndex : NEXT_STAGE_ROOM; + door->SetRoomTypes(room.descriptor->data->type, target ? target->data->type : ROOM_DEFAULT); + door->slot = slot; + if (door->variant == DOOR_LOCKED || door->variant == DOOR_LOCKED_DOUBLE || door->variant == DOOR_LOCKED_CRACKED) + { + door->variant = DOOR_UNLOCKED; + door->extraSprite.Reset(); + door->LoadSprite(); + } + if (door->variant == DOOR_HIDDEN) door->variant = DOOR_UNLOCKED; + door->UpdateAnimation(); + } + + EntityPtr& outline = room.redDoorOutlines[doorSlot]; + if (outline) + { + outline->Remove(); + outline = nullptr; + } + npc_sound_play(SOUND_UNLOCK, 1, 2, 1); +} + +// 0074c9e0 The doors a red room at a cell would share with the room through a slot: its own slot and the neighbour's +// entry slot (-1 each when there is no room there, or the entry is not allowed). False when the neighbour refuses. +bool Level::get_red_room_neighbor_slots(int roomIdx, int doorSlot, int* outSlot, int* outEntrySlot) +{ + int cell = GetNeighborRoomIdx(roomIdx, doorSlot); + RoomDescriptor* neighbor = cell >= 0 && cell < MAP_SIZE * MAP_SIZE ? GetRoomByIdx(cell) : nullptr; + if (!neighbor || !neighbor->data) + { + *outSlot = -1; + *outEntrySlot = -1; + return true; + } + + int entry = entry_slot_get(doorSlot, *neighbor, cell); + *outSlot = doorSlot; + bool isAllowed = is_entry_allowed(*this, *neighbor, entry, doorSlot); + *outEntrySlot = isAllowed ? entry : -1; + return isAllowed; +} + +// 0074cb50 The layout room a red room door would make: the empty cell beyond the slot when every room around it +// accepts a door, the next floor (an invalid cell) off the map's edge, or none. +LevelGenerator_Room Level::get_door_neighbor_room(int roomIdx, int doorSlot) +{ + LevelGenerator_Room none; + none.shape = ROOMSHAPE_NULL; + int cell = GetNeighborRoomIdx(roomIdx, doorSlot); + if (cell == NEXT_STAGE_ROOM) + { + bool isNextStage = g_game->challenge != CHALLENGE_RED_REDEMPTION && IsNextStageAvailable(); + none.shape = isNextStage ? ROOMSHAPE_1x1 : ROOMSHAPE_NULL; + return none; + } + if (GetRoomByIdx(cell)->data) return none; + + for (int slot = 0; slot < 4; slot++) + { + int around = GetNeighborRoomIdx(cell, slot); + if (around < 0 || around >= MAP_SIZE * MAP_SIZE) continue; + RoomDescriptor* other = GetRoomByIdx(around); + if (other->data && !is_entry_allowed(*this, *other, entry_slot_get(slot, *other, around), slot)) return none; + } + + LevelGenerator_Room room; + room.position = {cell % MAP_SIZE, cell / MAP_SIZE}; + room.shape = ROOMSHAPE_1x1; + return room; +} + +// 0074cd70 Whether a Red Key outline shows on a door slot: the room's layout has the door, none stands there, it is +// not the last boss room, and a red room could go there (at Home only the one cell), or a red room leads on to the +// next floor. +bool Level::CanSpawnDoorOutline(int roomIdx, int doorSlot) +{ + RoomDescriptor* room = GetRoomByIdx(roomIdx); + bool isLastBoss = room->data->type == ROOM_BOSS && room->listIndex == g_game->lastBossRoomListIdx; + bool isDoorFree = doorSlot > LAST_DOOR_SLOT || !g_game->room->doors[doorSlot]; + if (isLastBoss || room->gridIndex < 0 || !(room->data->doors & 1u << doorSlot) || !isDoorFree) return false; + + LevelGenerator_Room neighbor = get_door_neighbor_room(roomIdx, doorSlot); + if (stage == STAGE_HOME && !(neighbor.position == HOME_RED_ROOM_CELL)) return false; + return neighbor.shape > ROOMSHAPE_NULL && + (neighbor.position.x >= 0 || (room->flags & ROOM_DESCRIPTOR_FLAG_RED_ROOM)); +} + +// 0074cea0 A red room's type from the Red Key's rng: mostly a normal room, else a special room by weight. A +// planetarium is a treasure room until planetariums are unlocked (outside a daily or debug run), and an angel room a +// devil room once a deal was taken. +int Level::roll_red_room_type(RNG& rng) +{ + int roll = (int)(rng.Next() & RED_ROOM_ROLL_MASK); + int type = ROOM_DEFAULT; + for (auto [weight, roomType] : RED_ROOM_TYPES) + { + if (roll < weight) + { + type = roomType; + break; + } + roll -= weight; + } + + bool isPlanetariumLocked = + !g_manager->persistentGameData.achievements[ACHIEVEMENT_PLANETARIUMS] && + (g_manager->state != MANAGER_STATE_GAME || (g_game->dailyChallenge._id == 0 && !g_game->isDebug)); + if (type == ROOM_PLANETARIUM && isPlanetariumLocked) return ROOM_TREASURE; + if (type == ROOM_ANGEL && g_game->devilRoomDeals > 0) return ROOM_DEVIL; + return type; +} + +// 0074d010 Opens a red room through a door slot (the Red Key, Cracked Key, Soul of Cain): picks a room for the empty +// cell beyond from the cell's seed, places it with doors to every room around that takes one, or opens the way to the +// next floor off the map's edge, and puts the new doors in if the slot's room is the current one. +bool Level::MakeRedRoomDoor(int roomIdx, int doorSlot) +{ + roomIdx = std::clamp(roomIdx, ROOM_IDX_MIN, ROOM_IDX_MAX); + int slot = doorSlot < 0 ? LAST_DOOR_SLOT : std::min(doorSlot, LAST_DOOR_SLOT); + RoomDescriptor* source = GetRoomByIdx(roomIdx); + LevelGenerator_Room neighbor = get_door_neighbor_room(roomIdx, slot); + if (neighbor.shape == ROOMSHAPE_NULL) return false; + + RoomDescriptor* target = nullptr; + if (neighbor.position.x < 0) + { + if (!IsNextStageAvailable()) return false; + source->allowedDoors |= 1u << slot; + source->doors[slot] = NEXT_STAGE_ROOM; + } + else + { + uint32_t seed = (dungeonPlacementSeed + neighbor.position.y * RED_ROOM_ROW_SEED) * (neighbor.position.x + 1); + RNG rng = {seed, RED_ROOM_SHIFTS[0], RED_ROOM_SHIFTS[1], RED_ROOM_SHIFTS[2]}; + RoomConfig& config = g_game->roomConfig; + RoomConfig_Room* data = nullptr; + if (stage == STAGE_HOME) + { + RoomQuery query = {.shape = ROOMSHAPE_ANY, + .maxDifficulty = HOME_DIFFICULTY_MAX, + .minDifficulty = 1, + .stageId = HOME_STAGE_ID, + .subtype = HOME_ROOM_SUBTYPE}; + data = config.GetRandomRoom(rng.Next(), WEIGHT_KEEP, query); + } + else + { + int type = roll_red_room_type(rng); + int stageId = g_game->GetStageID(); + if (g_game->challenge == CHALLENGE_RED_REDEMPTION) + stageId = RoomConfig::GetStageID((int)stage, GetRoomStageType(neighbor.position.ToGridIdx()), + ROOM_MODE_CURRENT); + + RoomQuery query = {.requiredDoors = RED_ROOM_DOORS, + .shape = ROOMSHAPE_1x1, + .maxDifficulty = RED_ROOM_DIFFICULTY_MAX, + .minDifficulty = 1, + .stageId = stageId, + .type = type}; + if (type == ROOM_ANGEL || type == ROOM_DEVIL) + { + query.maxVariant = RED_ROOM_SPECIAL_VARIANTS; + query.subtype = + type == ROOM_DEVIL && g_game->playerManager.AnyoneHasTrinket(TRINKET_NUMBER_MAGNET) ? 1 : 0; + } + else if (type == ROOM_CHALLENGE) query.subtype = 0; + else if (type == ROOM_MINIBOSS) + query.minDifficulty = query.maxDifficulty = + (int)stage > RED_ROOM_LATE_STAGE ? RED_ROOM_LATE_MINIBOSS : 1; + + data = config.GetRandomRoom(rng.Next(), WEIGHT_KEEP, query); + if (!data && type != ROOM_DEFAULT) + { + query.stageId = 0; + data = config.GetRandomRoom(rng.Next(), WEIGHT_KEEP, query); + if (!data) + { + query = {.requiredDoors = RED_ROOM_DOORS, + .shape = ROOMSHAPE_1x1, + .maxDifficulty = RED_ROOM_DIFFICULTY_MAX, + .minDifficulty = 1, + .stageId = stageId, + .subtype = query.subtype}; + data = config.GetRandomRoom(rng.Next(), WEIGHT_KEEP, query); + } + } + } + if (!data) + { + log_printf(LOG_INFO, "failed to generate room with red key!\n"); + return false; + } + if (!place_room(neighbor, data, rng._seed, nullptr)) + { + log_printf(LOG_INFO, "failed to place room at (%d, %d)\n", neighbor.position.x, neighbor.position.y); + return false; + } + + target = &roomList[nbRooms - 1]; + target->flags |= ROOM_DESCRIPTOR_FLAG_RED_ROOM; + for (int side = 0; side < 4; side++) + { + int cell = GetNeighborRoomIdx(target->gridIndex, side); + int ownSlot = -1; + int entry = -1; + get_red_room_neighbor_slots(target->gridIndex, side, &ownSlot, &entry); + if (ownSlot >= 0) + { + target->allowedDoors = (target->allowedDoors | 1u << ownSlot) & target->data->doors; + target->doors[ownSlot] = cell; + } + RoomDescriptor* other = entry >= 0 ? GetRoomByIdx(cell) : nullptr; + if (!other || !other->data) continue; + other->allowedDoors = (other->allowedDoors | 1u << entry) & other->data->doors; + other->doors[entry] = target->gridIndex; + } + } + + if (source == g_game->room->descriptor) red_doors_open(*g_game->room, slot, target); + UpdateVisibility(); + return true; +} diff --git a/src/lua_api.cpp b/src/lua_api.cpp index 64dd944..aa25372 100644 --- a/src/lua_api.cpp +++ b/src/lua_api.cpp @@ -95,6 +95,7 @@ void lua_object_push(lua_State* state, void* object, LuaClass luaClass) void* lua_object_check(lua_State* state, int index, LuaClass luaClass) { void** block = lua_type(state, index) == LUA_TUSERDATA ? (void**)lua_touserdata(state, index) : nullptr; + const char* actual = luaL_typename(state, index); lua_rawgetp(state, LUA_REGISTRYINDEX, lua_class_key(luaClass)); if (!block || !lua_getmetatable(state, index)) lua_pushnil(state); while (!lua_isnil(state, -1)) @@ -109,8 +110,7 @@ void* lua_object_check(lua_State* state, int index, LuaClass luaClass) } field_raw_get(state, -2, "__name"); - const char* expected = lua_pushfstring(state, "%s expected, got %s", lua_tostring(state, -1), - luaL_typename(state, index)); + const char* expected = lua_pushfstring(state, "%s expected, got %s", lua_tostring(state, -1), actual); luaL_argerror(state, index, expected); return nullptr; } diff --git a/src/lua_api.h b/src/lua_api.h index 9e7605d..7970e44 100644 --- a/src/lua_api.h +++ b/src/lua_api.h @@ -21,8 +21,10 @@ extern "C" } #undef luaL_newstate +struct ActiveItemDesc; struct ColorMod; struct EntityPtr; +struct EntityList_EL; struct EntityRef; struct Entity_Bomb; struct Entity_Effect; @@ -53,6 +55,7 @@ struct ItemConfig_Pill; struct KColor; struct ANM2; struct PathFinder; +struct PosVel; struct ProjectileParams; struct QueueItemData; struct RoomConfig_Room; @@ -83,6 +86,11 @@ struct LuaIgnored { }; +// A value the original pushes as a class it never registers: a userdata without a metatable, which scripts can only +// hold or pass on. +struct LuaOpaque +{}; + // An argument a script may leave out, which reads as Default when it is nil or missing. template struct LuaDefault { @@ -104,8 +112,8 @@ struct LuaRoomList // The Lua class each C++ type is pushed and checked as. TearFlags are Lua's BitSet128 and ColorMod is Lua's Color. template constexpr LuaClass LUA_CLASS_OF = LUA_CLASS_COUNT; -template <> -inline constexpr LuaClass LUA_CLASS_OF> = LUA_CLASS_BIT_SET128; +template <> inline constexpr LuaClass LUA_CLASS_OF = LUA_CLASS_ACTIVE_ITEM_DESC; +template <> inline constexpr LuaClass LUA_CLASS_OF> = LUA_CLASS_BIT_SET128; template <> inline constexpr LuaClass LUA_CLASS_OF = LUA_CLASS_COLOR; template <> @@ -130,8 +138,8 @@ template <> inline constexpr LuaClass LUA_CLASS_OF = LUA_CLASS_PROJECTILE; template <> inline constexpr LuaClass LUA_CLASS_OF = LUA_CLASS_TEAR; -template <> -inline constexpr LuaClass LUA_CLASS_OF = LUA_CLASS_ENTITY_PTR; +template <> inline constexpr LuaClass LUA_CLASS_OF = LUA_CLASS_ENTITY_LIST; +template <> inline constexpr LuaClass LUA_CLASS_OF = LUA_CLASS_ENTITY_PTR; template <> inline constexpr LuaClass LUA_CLASS_OF = LUA_CLASS_ENTITY_REF; template <> @@ -208,8 +216,8 @@ template <> inline constexpr LuaClass LUA_CLASS_OF = LUA_CLASS_ROOM_LIST; template <> inline constexpr LuaClass LUA_CLASS_OF = LUA_CLASS_PATH_FINDER; -template <> -inline constexpr LuaClass LUA_CLASS_OF = LUA_CLASS_SEEDS; +template <> inline constexpr LuaClass LUA_CLASS_OF = LUA_CLASS_POS_VEL; +template <> inline constexpr LuaClass LUA_CLASS_OF = LUA_CLASS_SEEDS; template <> inline constexpr LuaClass LUA_CLASS_OF = LUA_CLASS_SFX_MANAGER; template <> @@ -218,10 +226,11 @@ template <> inline constexpr LuaClass LUA_CLASS_OF = LUA_CLASS_TEAR_PARAMS; template <> inline constexpr LuaClass LUA_CLASS_OF = LUA_CLASS_TEMPORARY_EFFECT; -template <> -inline constexpr LuaClass LUA_CLASS_OF = LUA_CLASS_TEMPORARY_EFFECTS; +template <> inline constexpr LuaClass LUA_CLASS_OF> = LUA_CLASS_EFFECT_LIST; +template <> inline constexpr LuaClass LUA_CLASS_OF = LUA_CLASS_TEMPORARY_EFFECTS; template <> inline constexpr LuaClass LUA_CLASS_OF = LUA_CLASS_VECTOR; +template <> inline constexpr LuaClass LUA_CLASS_OF> = LUA_CLASS_VECTOR_LIST; // The class and member type of a pointer to a data member, for decltype only. template @@ -246,6 +255,7 @@ void lua_property_set(lua_State* state, const char* table, const char* name); void lua_api_bit_set128_register(lua_State* state); void lua_api_color_register(lua_State* state); +void lua_api_containers_register(lua_State* state); void lua_api_entity_register(lua_State* state); void lua_api_entities_register(lua_State* state); void lua_api_entity_player_register(lua_State* state); @@ -280,6 +290,8 @@ void lua_push(lua_State* state, const T& value) else if constexpr (std::is_floating_point_v) lua_pushnumber(state, value); else if constexpr (IS_LUA_STRING) lua_pushlstring(state, value.data(), value.size()); else if constexpr (std::is_same_v) lua_pushstring(state, value); + else if constexpr (std::is_same_v) + lua_newuserdata(state, sizeof(void*)); else if constexpr (std::is_pointer_v) { static_assert(IS_LUA_CLASS>>); @@ -416,3 +428,25 @@ void lua_gc_set(lua_State* state) }); lua_table_set(state, -2, "__gc"); } + +// The object a list element is pushed as: what a unique_ptr holds, else the element itself. +template auto* lua_list_element(T& element) +{ + if constexpr (requires { element.get(); }) + return element.get(); + else + return &element; +} + +// Registers a list a binding hands out (the original's CppContainer classes): its Size and length, and Get, nil past +// the end where the original throws. +template void lua_list_register(lua_State* state, const char* name) +{ + lua_class_begin(state, name, LUA_CLASS_OF); + lua_property(state, "Size", [](List& list) { return (int)list.size(); }); + lua_method(state, "__len", [](List& list) { return (int)list.size(); }); + lua_method(state, "Get", [](List& list, uint32_t index) { + return index < list.size() ? lua_list_element(list[index]) : nullptr; + }); + lua_class_end(state, LUA_SCOPE_NAMESPACE); +} diff --git a/src/lua_api_containers.cpp b/src/lua_api_containers.cpp new file mode 100644 index 0000000..5fb70f5 --- /dev/null +++ b/src/lua_api_containers.cpp @@ -0,0 +1,55 @@ +#include "classes.h" +#include "entity_list.h" +#include "entity_player.h" +#include "lua_api.h" +#include "temporary_effects.h" +#include "weapon.h" +#include + +// (004176f0, 0085e0c0) Registers the CppContainer namespace: EntityList, the entities Room:GetEntities hands out, +// whose Get clamps the index to the last entity (the NPC queries hand out copies), and the EffectList and VectorList +// other bindings return. +// The original reads before an empty EntityList. Here Get gives nil for one. +static void containers_register(lua_State* state) +{ + lua_namespace_begin(state, "CppContainer"); + lua_class_begin(state, "EntityList", LUA_CLASS_ENTITY_LIST); + lua_gc_set(state); + lua_property(state, "Size", [](EntityList_EL& list) { return (int)list.size(); }); + lua_method(state, "__len", [](EntityList_EL& list) { return (int)list.size(); }); + lua_method(state, "Get", [](EntityList_EL& list, uint32_t index) { + return list.empty() ? nullptr : list[std::min(index, list.size() - 1)]; + }); + lua_class_end(state, LUA_SCOPE_NAMESPACE); + + lua_list_register>(state, "EffectList"); + lua_list_register>(state, "VectorList"); + lua_class_end(state); +} + +// Registers the PlayerTypes namespace: PosVel, a shot's start and speed, and ActiveItemDesc, an active item slot. +static void player_types_register(lua_State* state) +{ + lua_namespace_begin(state, "PlayerTypes"); + lua_class_begin(state, "PosVel", LUA_CLASS_POS_VEL); + lua_field<&PosVel::position>(state, "Position"); + lua_field<&PosVel::velocity>(state, "Velocity"); + lua_class_end(state, LUA_SCOPE_NAMESPACE); + + lua_class_begin(state, "ActiveItemDesc", LUA_CLASS_ACTIVE_ITEM_DESC); + lua_field<&ActiveItemDesc::item>(state, "Item"); + lua_field<&ActiveItemDesc::charge>(state, "Charge"); + lua_field<&ActiveItemDesc::batteryCharge>(state, "BatteryCharge"); + lua_field<&ActiveItemDesc::subCharge>(state, "SubCharge"); + lua_field<&ActiveItemDesc::timeRechargeCooldown>(state, "TimedRechargeCooldown"); + lua_field<&ActiveItemDesc::partialCharge>(state, "PartialCharge"); + lua_field<&ActiveItemDesc::varData>(state, "VarData"); + lua_class_end(state, LUA_SCOPE_NAMESPACE); + lua_class_end(state); +} + +void lua_api_containers_register(lua_State* state) +{ + containers_register(state); + player_types_register(state); +} diff --git a/src/lua_api_entities.cpp b/src/lua_api_entities.cpp index 44fa966..5053f41 100644 --- a/src/lua_api_entities.cpp +++ b/src/lua_api_entities.cpp @@ -9,14 +9,43 @@ #include "entity_player.h" #include "entity_projectile.h" #include "entity_tear.h" +#include "boss_ai.h" +#include "entity_list.h" #include "lua_api.h" -#include "weapon.h" #include "path_finder.h" +#include "weapon.h" +#include + +// The entities of a query as the EntityList Lua copies out. +template static EntityList_EL entity_list_make(const std::vector& entities) +{ + EntityList_EL list; + list.assign(entities.begin(), entities.end()); + return list; +} + +// The orbiters RecalculateOrbitOffset spaces, which the original returns: the familiars sharing the layer and the +// orbit's centre, and this one when it joins. +static int familiar_orbit_count(Entity_Familiar& familiar, int layer, bool isJoining) +{ + if (familiar.isSubtype55555 || layer < 0) return 0; + + Entity* centre = familiar.get_orbit_parent(); + auto isOrbiter = [&](Entity_Familiar* other) { + return other->isExists && other != &familiar && other->orbitLayer == layer && + other->get_orbit_parent() == centre; + }; + return (int)std::ranges::count_if(familiar_query(-1), isOrbiter) + isJoining; +} // Registers Lua's EntityTear and EntityProjectile, the shots of players and enemies. static void shots_register(lua_State* state) { lua_class_begin(state, "EntityTear", LUA_CLASS_TEAR, LUA_CLASS_ENTITY); + lua_field<&Entity_Tear::stickTarget>(state, "StickTarget"); + lua_method(state, "SetDeadEyeIntensity", + [](Entity_Tear& tear, float intensity) { tear.SetDeadEyeIntensity(intensity); }); + lua_method(state, "ResetSpriteScale", [](Entity_Tear& tear) { tear.ResetSpriteScale(); }); lua_field<&Entity_Tear::height>(state, "Height"); lua_field<&Entity_Tear::fallingSpeed>(state, "FallingSpeed"); lua_field<&Entity_Tear::fallingAccel>(state, "FallingAcceleration"); @@ -94,6 +123,7 @@ static void weapons_register(lua_State* state) lua_method(state, "GetKnifeDistance", [](Entity_Knife& knife) { return knife.knifeDistance; }); lua_method(state, "GetKnifeVelocity", [](Entity_Knife& knife) { return knife.knifeVelocity; }); lua_method(state, "SetPathFollowSpeed", [](Entity_Knife& knife, float speed) { knife.pathFollowSpeed = speed; }); + lua_method(state, "GetRenderZ", [](Entity_Knife& knife) { return knife.GetRenderZ(); }); weapon_lua_knife_register(state); lua_class_end(state); @@ -129,6 +159,17 @@ static void weapons_register(lua_State* state) [](Entity_Laser& laser, float chance) { laser.blackHpDropChance = chance; }); lua_method(state, "IsCircleLaser", [](Entity_Laser& laser) { return laser.IsCircleLaser(); }); lua_method(state, "IsSampleLaser", [](Entity_Laser& laser) { return laser.isSampleLaser; }); + lua_field<&Entity_Laser::rotationDelay>(state, "RotationDelay"); + lua_field<&Entity_Laser::bounceLaser>(state, "BounceLaser"); + lua_property(state, "HomingLaser", [](Entity_Laser&) { return LuaOpaque{}; }); + lua_method(state, "GetRenderZ", [](Entity_Laser& laser) { return laser.GetRenderZ(); }); + lua_method(state, "GetEndPoint", [](Entity_Laser& laser) -> Vector& { return laser.endPoint; }); + lua_method(state, "GetSamples", + [](Entity_Laser& laser) -> std::vector& { return laser.homingLaser.samples; }); + lua_method(state, "GetNonOptimizedSamples", + [](Entity_Laser& laser) -> std::vector& { return laser.homingLaser.nonOptimizedSamples; }); + lua_method(state, "SetMultidimensionalTouched", + [](Entity_Laser& laser, bool isTouched) { laser.isMultidimensionalTouched = isTouched; }); weapon_lua_laser_register(state); lua_class_end(state); } @@ -137,6 +178,23 @@ static void weapons_register(lua_State* state) static void companions_register(lua_State* state) { lua_class_begin(state, "EntityFamiliar", LUA_CLASS_FAMILIAR, LUA_CLASS_ENTITY); + lua_method(state, "PickEnemyTarget", + [](Entity_Familiar& familiar, float range, int frameInterval, uint32_t flags, Vector coneDirection, + float coneAngle) { + familiar.PickEnemyTarget({.coneDirection = coneDirection, + .coneAngle = coneAngle, + .range = range, + .frameInterval = frameInterval, + .flags = flags}); + }); + lua_method(state, "FireProjectile", [](Entity_Familiar& familiar, Vector direction, bool isExact) { + return familiar.FireProjectile(direction, isExact ? FIRE_EXACT : FIRE_INHERIT_MOTION); + }); + lua_method(state, "MoveDelayed", [](Entity_Familiar& familiar, int frames) { familiar.MoveDelayed(frames); }); + lua_method(state, "RecalculateOrbitOffset", [](Entity_Familiar& familiar, int layer, bool isJoining) { + familiar.RecalculateOrbitOffset(layer, isJoining ? ORBIT_JOIN : ORBIT_LEAVE); + return familiar_orbit_count(familiar, layer, isJoining); + }); lua_field<&Entity_Familiar::player>(state, "Player"); lua_field<&Entity_Familiar::state>(state, "State"); lua_field<&Entity_Familiar::coins>(state, "Coins"); @@ -180,6 +238,7 @@ static void companions_register(lua_State* state) lua_class_end(state); lua_class_begin(state, "EntityEffect", LUA_CLASS_EFFECT, LUA_CLASS_ENTITY); + lua_static(state, "IsPlayerCreep", [](int variant) { return Entity_Effect::IsPlayerCreep(variant); }); lua_field<&Entity_Effect::state>(state, "State"); lua_field<&Entity_Effect::timeout>(state, "Timeout"); lua_field<&Entity_Effect::lifespan>(state, "LifeSpan"); @@ -206,6 +265,17 @@ static void companions_register(lua_State* state) static void npc_pickup_register(lua_State* state) { lua_class_begin(state, "EntityNPC", LUA_CLASS_NPC, LUA_CLASS_ENTITY); + lua_method(state, "CanBeDamagedFromVelocity", + [](Entity_NPC& npc, Vector velocity) { return npc.CanBeDamagedFromVelocity(velocity); }); + lua_method(state, "CanReroll", [](Entity_NPC& npc) { return npc.CanReroll(); }); + lua_method(state, "QueryNPCsType", + [](Entity_NPC&, int type, int variant) { return entity_list_make(entity_query(type, variant)); }); + lua_method(state, "QueryNPCsSpawnerType", [](Entity_NPC&, int spawnerType, int type, bool isEnemiesOnly) { + SpawnerQueryMode mode = isEnemiesOnly ? SPAWNER_QUERY_ENEMIES : SPAWNER_QUERY_ALL; + return entity_list_make(npc_query_spawner_type(spawnerType, type, mode)); + }); + lua_method(state, "QueryNPCsGroup", + [](Entity_NPC&, int group) { return entity_list_make(Entity_NPC::QueryNPCsGroup(group)); }); lua_field<&Entity_NPC::state>(state, "State"); lua_field<&Entity_NPC::stateFrame>(state, "StateFrame"); lua_field<&Entity_NPC::i1>(state, "I1"); diff --git a/src/lua_api_entity_player.cpp b/src/lua_api_entity_player.cpp index 00c9df5..bc474e1 100644 --- a/src/lua_api_entity_player.cpp +++ b/src/lua_api_entity_player.cpp @@ -1,16 +1,20 @@ #include "classes.h" #include "active_items.h" +#include "entity_effect.h" #include "entity_familiar.h" #include "entity_pickup.h" #include "entity_player.h" #include "entity_tear.h" #include "item_config.h" +#include "log.h" #include "lua_api.h" #include "temporary_effects.h" #include "weapon.h" // The QueueItemData flag Touched reads: the item was held before, so picking it up again gives no pickup effect. constexpr uint32_t QUEUE_ITEM_TOUCHED = 0x1; +// The most charges Dead Eye stacks. +constexpr uint32_t DEAD_EYE_CHARGES_MAX = 8; // The weapon a player's fire delay belongs to: the override in slot 0, else the first. static Weapon* player_weapon_main(Entity_Player& player) @@ -370,7 +374,106 @@ static void player_stats_register(lua_State* state) lua_method(state, "SpriteScale", [](Entity_Player& player) { return player.SpriteScale(); }); } -// Registers Lua's EntityPlayer, TemporaryEffects and TearParams. +// (007e92a0, 004361a0, 004361b0, 0085e240, 005cd7d0, 0085e2c0, 00753c30, 0065cf60, 00782a60) Registers the player's +// drawing and the state the rest of EntityPlayer reads: the body's turn, the melee damage, the held item state, the +// range bonus, the tractor beam, the last action buttons and Curse Mist. The original pushes the pocket items, the +// Friend Ball enemy and the multi shot parameters as unregistered classes. +static void player_state_register(lua_State* state) +{ + lua_method(state, "RenderGlow", [](Entity_Player& player, Vector position) { player.RenderGlow(position); }); + lua_method(state, "RenderBody", [](Entity_Player& player, Vector position) { player.RenderBody(position); }); + lua_method(state, "RenderHead", [](Entity_Player& player, Vector position) { player.RenderHead(position); }); + lua_method(state, "RenderTop", [](Entity_Player& player, Vector position) { player.RenderTop(position); }); + lua_method(state, "IsFullSpriteRendering", [](Entity_Player& player) { return player.IsFullSpriteRendering(); }); + lua_method(state, "IsP2Appearing", [](Entity_Player& player) { return player.IsP2Appearing(); }); + lua_method(state, "CanTurnHead", [](Entity_Player& player) { return player.CanTurnHead() != 0; }); + lua_method(state, "GetSmoothBodyRotation", [](Entity_Player& player) { return player.bodyAngle; }); + lua_method(state, "GetTearPoisonDamage", [](Entity_Player& player) { return player.meleeDamage; }); + lua_method(state, "GetItemState", [](Entity_Player& player) { return player.itemState; }); + lua_method(state, "ResetItemState", [](Entity_Player& player) { player.ResetItemState(); }); + lua_method(state, "GetTearRangeModifier", [](Entity_Player& player) { return player.tearRangeModifier; }); + lua_method(state, "GetTractorBeam", [](Entity_Player& player) -> Entity* { + if (player.tractorBeam) + reconstruction_missing("Entity_Player::GetTractorBeam 00665c10 (the beam is an int here)"); + return nullptr; + }); + lua_method(state, "GetLastActionTriggers", [](Entity_Player& player) { return player.lastActionTriggers; }); + lua_field<&Entity_Player::blinkTime>(state, "HeadFrameDelay"); + lua_method(state, "GetNPCTarget", [](Entity_Player&) -> Entity* { + reconstruction_missing("Entity_Player::GetNPCTarget 00770610"); + return nullptr; + }); + lua_method(state, "HasCurseMistEffect", [](Entity_Player& player) { return player.hasCurseMistEffect; }); + lua_method(state, "AddCurseMistEffect", [](Entity_Player& player) { player.AddCurseMistEffect(); }); + lua_method(state, "RemoveCurseMistEffect", [](Entity_Player& player) { player.RemoveCurseMistEffect(); }); + lua_method(state, "GetPocketItem", [](Entity_Player&, int) { return LuaOpaque{}; }); + lua_method(state, "FriendBallEnemy", [](Entity_Player&) { return LuaOpaque{}; }); + lua_method(state, "GetMultiShotParams", [](Entity_Player&, int) { return LuaOpaque{}; }); + lua_method(state, "GetGreedDonationBreakChance", + [](Entity_Player& player) { return player.GetGreedDonationBreakChance(); }); + lua_method(state, "GetLaserOffset", [](Entity_Player& player, int offsetId, Vector direction) { + return player.GetLaserOffset(offsetId, direction); + }); + lua_method(state, "GetTearMovementInheritance", [](Entity_Player& player, Vector direction, bool isAlways) { + return player.GetTearMovementInheritance(direction, isAlways ? INHERIT_ALWAYS : INHERIT_CHECKED); + }); + lua_method(state, "GetCostumeNullPos", + [](Entity_Player& player, std::string_view name, bool isHeadScale, Vector direction) { + return player.GetCostumeNullPos(name, isHeadScale, direction); + }); + lua_method(state, "IsPosInSpotLight", + [](Entity_Player& player, Vector position) { return player.IsPosInSpotLight(position); }); + lua_method(state, "GetBombFlags", + [](Entity_Player& player, bool isRollChances) { return player.GetBombFlags(isRollChances); }); + lua_method(state, "GetBombVariant", + [](Entity_Player&, TearFlags, bool) { return Entity_Player::GetBombVariant(); }); +} + +// (0075e160, 0085e200, 007bf660, 0085e260, 007c78b0) Registers the player's actions the rest of EntityPlayer lacks: +// queueing an item, the hearts check, blue spiders, controls, skins and costumes, Dead Eye, Maw of the Void, Dollar +// Bill, Zit, Red Candle, the poop spells, Brimstone's delayed shot and whether an item can be picked up. +static void player_actions_register(lua_State* state) +{ + lua_method(state, "QueueItem", + [](Entity_Player& player, ItemConfig_Item& item, int charge, int flags, int varData) { + player.SetQueuedItem({.item = &item, .charge = charge, .flags = (uint8_t)flags, .varData = varData}); + }); + lua_method(state, "HasFullHeartsAndSoulHearts", + [](Entity_Player& player) { return player.maxHearts <= player.soulHearts + player.redHearts; }); + lua_method(state, "RemoveBlueSpider", [](Entity_Player& player) { player.numBlueSpiders--; }); + lua_method(state, "AddControlsCooldown", + [](Entity_Player& player, int frames) { player.controlsCooldown += frames; }); + lua_method(state, "AddDeadEyeCharge", [](Entity_Player& player) { + if (player.deadEyeCharges < DEAD_EYE_CHARGES_MAX) + { + player.cacheFlags |= CACHE_DAMAGE; + player.deadEyeCharges++; + player.EvaluateItems(); + } + player.deadEyeMisses = 0; + }); + lua_method(state, "RemoveSkinCostume", [](Entity_Player& player) { player.RemoveSkinCostume(); }); + lua_method(state, "InitBabySkin", [](Entity_Player& player) { player.InitBabySkin(); }); + lua_method(state, "ReplaceCostumeSprite", + [](Entity_Player& player, ItemConfig_Item& item, std::string_view path, int) { + player.ReplaceCostumeSprite(&item, path); + }); + lua_method(state, "CanPickupItem", [](Entity_Player& player) { return player.CanPickupItem(); }); + lua_method(state, "SpawnMawOfVoid", + [](Entity_Player& player, int timeout) { return player.SpawnMawOfVoid(timeout); }); + lua_method(state, "AddDollarBillEffect", [](Entity_Player& player) { player.AddDollarBillEffect(); }); + lua_method(state, "DoZitEffect", [](Entity_Player& player, Vector direction) { player.DoZitEffect(direction); }); + lua_method(state, "ShootRedCandle", [](Entity_Player& player, Vector direction) { + Entity* flame = player.ShootRedCandle(direction); + return flame && flame->type == ENTITY_EFFECT ? static_cast(flame) : nullptr; + }); + lua_method(state, "UsePoopSpell", [](Entity_Player& player, uint32_t spell) { player.UsePoopSpell(spell); }); + lua_method(state, "FireDelayedBrimstone", [](Entity_Player& player, float angle, Entity* parent) { + return player.FireDelayedBrimstone(angle, parent); + }); +} + +// (007537a0) Registers Lua's EntityPlayer, TemporaryEffects and TearParams. void lua_api_entity_player_register(lua_State* state) { lua_class_begin(state, "EntityPlayer", LUA_CLASS_PLAYER, LUA_CLASS_ENTITY); @@ -378,13 +481,19 @@ void lua_api_entity_player_register(lua_State* state) player_items_register(state); player_misc_register(state); player_stats_register(state); + player_state_register(state); + player_actions_register(state); weapon_lua_player_register(state); lua_class_end(state); lua_class_begin(state, "QueueItemData", LUA_CLASS_QUEUE_ITEM_DATA); lua_field<&QueueItemData::item>(state, "Item"); lua_field<&QueueItemData::charge>(state, "Charge"); - lua_property(state, "Touched", [](QueueItemData& queued) { return (queued.flags & QUEUE_ITEM_TOUCHED) != 0; }); + lua_property( + state, "Touched", [](QueueItemData& queued) { return (queued.flags & QUEUE_ITEM_TOUCHED) != 0; }, + [](QueueItemData& queued, bool isTouched) { + queued.flags = isTouched ? queued.flags | QUEUE_ITEM_TOUCHED : queued.flags & ~QUEUE_ITEM_TOUCHED; + }); lua_class_end(state); lua_class_begin(state, "TemporaryEffect", LUA_CLASS_TEMPORARY_EFFECT); @@ -394,6 +503,8 @@ void lua_api_entity_player_register(lua_State* state) lua_class_end(state); lua_class_begin(state, "TemporaryEffects", LUA_CLASS_TEMPORARY_EFFECTS); + lua_method(state, "GetEffectsList", + [](TemporaryEffects& effects) -> std::vector& { return effects.effects; }); lua_method(state, "GetCollectibleEffect", [](TemporaryEffects& effects, int id) { return effects.GetCollectibleEffect(id); }); lua_method(state, "GetTrinketEffect", diff --git a/src/lua_api_game.cpp b/src/lua_api_game.cpp index 0cdb64e..973fe07 100644 --- a/src/lua_api_game.cpp +++ b/src/lua_api_game.cpp @@ -1,21 +1,226 @@ #include "classes.h" #include "boss_ai.h" +#include "entity_bomb.h" +#include "entity_effect_combat.h" #include "entity_npc.h" +#include "entity_pickup.h" #include "entity_player.h" #include "game.h" +#include "game_end.h" +#include "grid_entity_trap_door.h" #include "hud.h" #include "item_pool.h" #include "lua_api.h" #include "manager.h" #include "music_manager.h" #include "npc_basement.h" +#include "room.h" +#include "room_special.h" #include "room_transition.h" #include "seeds.h" #include "sfx_manager.h" +#include "stage_transition.h" #include // The reach of a Fart a script leaves out. constexpr float FART_RADIUS = 85; +// The last stage the run's stage counters keep. +constexpr int STAGE_COUNTER_MAX = 13; +// Making this many devil deals in one run unlocks Azazel. +constexpr int AZAZEL_DEALS = 3; +constexpr int ACHIEVEMENT_AZAZEL = 79; +// A Greed run's waves, bosses and the devil's included (one more in Greedier). +constexpr int GREED_WAVE_TOTAL = 11; +// The argument past the last line HUD:ShowFortuneText reads. +constexpr int FORTUNE_ARGUMENT_END = 34; + +// 006fe2f0 Moves the players into a room of the floor at once: each leaves the room, the level changes room, the new +// room updates once and the item pool takes the room's pool. A Random() is drawn and dropped on the way. +void Game::ChangeRoom(int roomIndex, int dimension) +{ + for (Entity_Player* player : playerManager.playerList) player->room_exit(false); + Level::ChangeRoom(roomIndex, dimension); + room->Update(); + + Random(); + int pool = itemPool.get_pool_from_room_entities(room->roomType, *room->descriptor, room->bossId); + itemPool.lastPool = pool == POOL_NONE ? POOL_TREASURE : pool; +} + +// 00703850 A random player within a radius of a position, else the last of the shuffled players. +// The original reads before an empty player list. Here there is no player then. +static Entity_Player* game_random_player(Game& game, Vector position, float radius) +{ + std::vector players = game.playerManager.playerList; + if (players.empty()) return nullptr; + + for (size_t index = players.size() - 1; index > 0; index--) + std::swap(players[index], players[Random() % (index + 1)]); + for (Entity_Player* player : players) + if (vector_length_squared(vector_sub(position, player->pos)) < radius * radius) return player; + return players.back(); +} + +// 00704b70 Rerolls the collectibles the floor's other rooms keep: each saved pedestal of an item that may be rerolled +// becomes a fresh, untouched one. +static void game_level_collectibles_reroll(Game& game) +{ + for (int index = 0; index < game.nbRooms; index++) + for (EntitySaveState& saved : game.roomList[index].savedEntities) + { + bool isRerollable = Entity_Pickup::CanRerollVariant(PICKUP_COLLECTIBLE, saved.subtype); + if (saved.type != ENTITY_PICKUP || saved.variant != PICKUP_COLLECTIBLE || saved.subtype == 0 || + !isRerollable) + continue; + saved.subtype = 0; + saved.boolStorage1 = false; + } +} + +// (00704b10, 00704b30, 00704b40, 0065d000, 007e92c0, 00738310, 00738320, 007e9330, 007e9370, 0085e3c0, 0085e3d0, +// 0085e3f0, 0085e400, 00753c50, 007e92d0, 00753c80, 00753cb0, 0085e370, 00703560) Registers Game's run counters: the +// devil deals and donations, and the stages cleared without damage, hearts or half health. +// The original pushes the last levels with damage or without half health as an unregistered class. +static void game_counters_register(lua_State* state) +{ + lua_method(state, "AddDevilRoomDeal", [](Game& game) { + if (++game.devilRoomDeals >= AZAZEL_DEALS) g_manager->persistentGameData.TryUnlock(ACHIEVEMENT_AZAZEL); + }); + lua_method(state, "DonateGreed", [](Game& game, int amount) { game.donationModGreed += amount; }); + lua_method(state, "DonateAngel", [](Game& game, int amount) { game.donationModAngel += amount; }); + lua_method(state, "GetDonationModGreed", [](Game& game) { return game.donationModGreed; }); + lua_method(state, "GetDonationModAngel", [](Game& game) { return game.donationModAngel; }); + lua_method(state, "ClearDonationModGreed", [](Game& game) { game.donationModGreed = 0; }); + lua_method(state, "ClearDonationModAngel", [](Game& game) { game.donationModAngel = 0; }); + lua_method(state, "SetLastDevilRoomStage", + [](Game& game, int stage) { game.lastDevilRoomStage = std::clamp(stage, 0, STAGE_COUNTER_MAX); }); + lua_method(state, "AddTreasureRoomsVisited", [](Game& game) { game.treasureRoomsVisited++; }); + lua_method(state, "AddStageWithoutHeartsPicked", [](Game& game) { game.stagesWithoutHeartsPicked++; }); + lua_method(state, "ClearStagesWithoutHeartsPicked", [](Game& game) { game.stagesWithoutHeartsPicked = 0; }); + lua_method(state, "AddStageWithoutDamage", [](Game& game) { game.stagesWithoutDamage++; }); + lua_method(state, "ClearStagesWithoutDamage", [](Game& game) { game.stagesWithoutDamage = 0; }); + lua_method(state, "SetLastLevelWithDamage", + [](Game& game, int stage) { game.lastLevelWithDamage = std::clamp(stage, 0, STAGE_COUNTER_MAX); }); + lua_method(state, "GetLastLevelWithDamage", [](Game&) { return LuaOpaque{}; }); + lua_method(state, "SetLastLevelWithoutHalfHp", + [](Game& game, int stage) { game.lastLevelWithoutHalfHp = std::clamp(stage, 0, STAGE_COUNTER_MAX); }); + lua_method(state, "GetLastLevelWithoutHalfHp", [](Game&) { return LuaOpaque{}; }); + lua_method(state, "AddEncounteredBoss", + [](Game&, int type, int variant) { game_encountered_boss_add(type, variant); }); + lua_method(state, "GetNumEncounteredBosses", [](Game& game) { return (int)game.encounteredBosses.size(); }); + lua_method(state, "GetGreedWavesNum", + [](Game& game) { return GREED_WAVE_TOTAL + (game.difficulty == DIFFICULTY_GREEDIER); }); +} + +// (00440ee0, 00440620, 00753cc0, 004a5d00, 00703460, 005b1860, 00456860, 0085e390) Registers Game's screen and world +// effects: explosions, particles, shockwaves, darkness, pixelation, hallucinations, fades and the HUD font. +// The original pushes the ambush and the item overlay as unregistered classes. +static void game_effects_register(lua_State* state) +{ + lua_method(state, "BombDamage", + [](Game&, Vector position, float damage, float radius, bool isLineCheck, Entity* source, TearFlags flags, + int64_t damageFlags, bool isDamageSource) { + explosion_damage({.tearFlags = flags, + .position = position, + .source = source, + .damageFlags = (uint64_t)damageFlags, + .damage = damage, + .radius = radius, + .isDamageSource = isDamageSource, + .isLineCheck = isLineCheck}); + }); + lua_method(state, "BombExplosionEffects", + [](Game&, Vector position, float damage, TearFlags flags, const ColorMod& color, Entity* source, + float radiusMultiplier, bool isLineCheck, int64_t damageFlags, bool isDamageSource) { + explosion_effects({.tearFlags = flags, + .color = color, + .position = position, + .source = source, + .damageFlags = (uint64_t)damageFlags, + .damage = damage, + .radiusMultiplier = radiusMultiplier, + .isDamageSource = isDamageSource, + .isLineCheck = isLineCheck}); + }); + lua_method(state, "BombTearflagEffects", + [](Game&, Vector position, float radius, TearFlags flags, Entity* source, float radiusMultiplier) { + explosion_tear_flag_effects({.tearFlags = flags, + .position = position, + .source = source, + .radius = radius, + .radiusMultiplier = radiusMultiplier}); + }); + lua_method(state, "SpawnParticles", + [](Game&, Vector position, int variant, int count, float speed, const ColorMod& color, float height, + int subType) { + game_particles_spawn({.color = color, + .position = position, + .height = height, + .speed = speed, + .count = count, + .subType = subType, + .variant = variant}); + }); + lua_method(state, "MakeShockwave", [](Game&, Vector position, float amplitude, float speed, int duration) { + shockwave_make(position, amplitude, speed, duration); + }); + lua_method(state, "UpdateStrangeAttractor", + [](Game&, Vector, float, float) { reconstruction_missing("Game::AttractEntities 00705b90"); }); + lua_method(state, "CharmFart", + [](Game&, Vector, float, Entity*) { reconstruction_missing("Game::CharmFart 00703f90"); }); + lua_method(state, "Darken", [](Game& game, float strength, int timeout) { + game.darknessStrength = strength; + game.darknessTimeout = timeout; + }); + lua_method(state, "GetTargetDarkness", [](Game& game) { return game.darknessStrength; }); + lua_method(state, "AddPixelation", [](Game& game, int duration) { + game.pixelationTimer = std::max(duration, game.pixelationTimer); + game.pixelationDuration = game.pixelationTimer; + }); + lua_method(state, "ShowHallucination", + [](Game& game, int frames, int backdrop) { game.ShowHallucination(frames, backdrop); }); + lua_method(state, "HasHallucination", [](Game& game) { return game.hallucinationTimer > 0; }); + lua_method(state, "Fadein", [](Game& game, float speed, bool isShowIcon, KColor color) { + game.Fadein(speed, isShowIcon ? FADE_ICON_SHOW : FADE_ICON_HIDE, color); + }); + lua_method(state, "Fadeout", + [](Game& game, float speed, FadeOutTarget target, KColor color) { game.Fadeout(speed, target, color); }); + lua_method(state, "GetFont", [](Game&) { return &g_manager->font2_TeamMeatEx12; }); + lua_method(state, "GetAmbush", [](Game&) { return LuaOpaque{}; }); + lua_method(state, "GetItemOverlay", [](Game&) { return LuaOpaque{}; }); + lua_method(state, "ShowFortune", [](Game&) { reconstruction_missing("Game::ShowFortuneText 009807a0"); }); + lua_method(state, "ShowRule", [](Game&) { reconstruction_missing("Game::ShowFortuneText 009807a0"); }); +} + +// (00704f20, 006f9770) Registers how Game moves the run on: its frame and draw, room and floor changes, rerolls, +// the ending and the next victory lap. +// The original hands StartStageTransition a player from its stack. Here it has none. +static void game_flow_register(lua_State* state) +{ + lua_method(state, "Update", [](Game& game) { game.Update(); }); + lua_method(state, "Render", [](Game& game) { game.Render(); }); + lua_method(state, "ChangeRoom", + [](Game& game, int roomIndex, int dimension) { game.ChangeRoom(roomIndex, dimension); }); + lua_method(state, "MoveToRandomRoom", [](Game& game, bool isErrorRoom, uint32_t seed, Entity_Player* player) { + game_random_room_move(game, isErrorRoom, seed, player); + }); + lua_method(state, "StartStageTransition", [](Game& game, bool isSameStage, StageTransitionType type) { + game.stageTransition.start({.type = type, .isSameStage = isSameStage}); + }); + lua_method(state, "GetRandomPlayer", game_random_player); + lua_method(state, "RerollLevelCollectibles", game_level_collectibles_reroll); + lua_method(state, "RerollLevelPickups", + [](Game&, uint32_t) { reconstruction_missing("Game::RerollLevelPickups 00704c50"); }); + lua_method(state, "RerollEnemy", [](Game&, Entity*, bool) { + reconstruction_missing("Game::RerollEnemy 007050c0"); + return false; + }); + lua_method(state, "SpawnEntityDesc", + [](Game&, LuaIgnored, Vector, Entity*) { reconstruction_missing("Game::SpawnEntityDesc 006fece0"); }); + lua_method(state, "End", [](Game&, GameEnding ending) { game_end(ending); }); + lua_method(state, "FinishChallenge", [](Game&) { challenge_finish(); }); + lua_method(state, "NextVictoryLap", [](Game&) { reconstruction_missing("Game::NextVictoryLap 006f7ac0"); }); +} // (00703510, 00703570) Registers Lua's Game: the run's level, room, players, pools, seeds and HUD, spawning, room // transitions and farts, and its state flags and counters. Game is also the Level it derives from. @@ -79,9 +284,23 @@ static void game_register(lua_State* state) lua_field<&Game::blueWombParTime>(state, "BlueWombParTime"); lua_field<&Game::bossRushParTime>(state, "BossRushParTime"); lua_field<&Game::screenShakeOffset>(state, "ScreenShakeOffset"); + game_counters_register(state); + game_effects_register(state); + game_flow_register(state); lua_class_end(state); } +// HUD:ShowFortuneText: the string arguments after the HUD, up to the first that is not one, as a fortune's lines. +static int hud_fortune_text_show(lua_State* state) +{ + HUD& hud = *static_cast(lua_object_check(state, 1, LUA_CLASS_HUD)); + std::vector lines; + for (int index = 2; index < FORTUNE_ARGUMENT_END && lua_type(state, index) == LUA_TSTRING; index++) + lines.emplace_back(lua_tostring(state, index)); + hud.ShowFortuneText(lines); + return 0; +} + // Registers Lua's HUD, ItemPool and Seeds, the parts of a run Game hands out. static void game_parts_register(lua_State* state) { @@ -101,6 +320,8 @@ static void game_parts_register(lua_State* state) lua_method(state, "Update", [](HUD& hud) { hud.Update(); }); lua_method(state, "PostUpdate", [](HUD& hud) { hud.PostUpdate(); }); lua_method(state, "Render", [](HUD& hud) { hud.Render(); }); + lua_pushcfunction(state, hud_fortune_text_show); + lua_table_set(state, -2, "ShowFortuneText"); lua_class_end(state); lua_class_begin(state, "ItemPool", LUA_CLASS_ITEM_POOL); @@ -136,6 +357,7 @@ static void game_parts_register(lua_State* state) lua_class_begin(state, "Seeds", LUA_CLASS_SEEDS); lua_method(state, "GetStartSeed", [](Seeds& seeds) { return seeds.GetStartSeed(); }); lua_method(state, "IsCustomRun", [](Seeds& seeds) { return seeds.isCustomRun; }); + lua_method(state, "IsInitialized", [](Seeds& seeds) { return seeds.gameStartSeed != 0; }); lua_method(state, "GetStartSeedString", [](Seeds& seeds) { return seeds.GetStartSeedString(); }); lua_method(state, "GetNextSeed", [](Seeds& seeds) { return seeds.GetNextSeed(); }); lua_method(state, "GetStageSeed", [](Seeds& seeds, int stage) { return seeds.GetStageSeed(stage); }); diff --git a/src/lua_api_grid_entity.cpp b/src/lua_api_grid_entity.cpp index d0fab51..e831fc4 100644 --- a/src/lua_api_grid_entity.cpp +++ b/src/lua_api_grid_entity.cpp @@ -127,6 +127,7 @@ static void grid_entity_kinds_register(lua_State* state) lua_class_begin(state, "GridEntityPoop", LUA_CLASS_GRID_ENTITY_POOP, LUA_CLASS_GRID_ENTITY); lua_method(state, "RespawnRedPoop", [](GridEntity_Poop& poop) { poop.RespawnRedPoop(); }); + lua_method(state, "ReduceSpawnRate", [](GridEntity_Poop& poop) { poop.varData = 1; }); lua_field<&GridEntity_Poop::reviveTimer>(state, "ReviveTimer"); lua_field<&GridEntity_Poop::stateAnimation>(state, "StateAnimation"); lua_field<&GridEntity_Poop::isUnderPlayer>(state, "UnderPlayer"); diff --git a/src/lua_api_item_config.cpp b/src/lua_api_item_config.cpp index 3d62eee..82d2054 100644 --- a/src/lua_api_item_config.cpp +++ b/src/lua_api_item_config.cpp @@ -2,18 +2,6 @@ #include "item_config.h" #include "lua_api.h" -// Registers a list of configs Config hands out: its Size, and Get, nil past the end where the original reads on. -template -static void config_list_register(lua_State* state, const char* name, LuaClass luaClass) -{ - using List = std::vector>; - lua_class_begin(state, name, luaClass); - lua_property(state, "Size", [](List& list) { return (int)list.size(); }); - lua_method(state, "Get", - [](List& list, uint32_t index) { return index < list.size() ? list[index].get() : nullptr; }); - lua_class_end(state, LUA_SCOPE_NAMESPACE); -} - // Registers ItemConfig.Item, a collectible, trinket or null item, and ItemConfig.Costume. static void item_register(lua_State* state) { @@ -108,9 +96,9 @@ void lua_api_item_config_register(lua_State* state) lua_namespace_begin(state, "ItemConfig"); item_register(state); pocket_items_register(state); - config_list_register(state, "ItemConfigList", LUA_CLASS_ITEM_CONFIG_ITEM_LIST); - config_list_register(state, "CardConfigList", LUA_CLASS_ITEM_CONFIG_CARD_LIST); - config_list_register(state, "PillConfigList", LUA_CLASS_ITEM_CONFIG_PILL_LIST); + lua_list_register>>(state, "ItemConfigList"); + lua_list_register>>(state, "CardConfigList"); + lua_list_register>>(state, "PillConfigList"); lua_class_begin(state, "Config", LUA_CLASS_ITEM_CONFIG); lua_method(state, "GetCollectible", [](ItemConfig& config, int id) { return config.GetCollectible(id); }); diff --git a/src/lua_api_room.cpp b/src/lua_api_room.cpp index c228472..c6d2677 100644 --- a/src/lua_api_room.cpp +++ b/src/lua_api_room.cpp @@ -1,14 +1,19 @@ #include "classes.h" +#include "entity_knife.h" #include "entity_npc.h" #include "game.h" +#include "item_pool.h" #include "grid_entity.h" #include "grid_entity_door.h" #include "level.h" #include "lua_api.h" +#include "npc_basement.h" #include "room.h" #include "room_config.h" #include "room_descriptor.h" +#include "room_clear.h" #include "room_grid.h" +#include "room_special.h" // The frames KeepDoorsClosed holds the room uncleared for. constexpr int ROOM_CLEAR_DELAY_KEPT = 10; @@ -22,17 +27,6 @@ static void descriptor_flag_add(lua_State* state, const char* name) [](RoomDescriptor& room, bool isSet) { room.flags = isSet ? room.flags | Flag : room.flags & ~Flag; }); } -// Registers a list of a room config's spawns or entries: its Size, and Get, nil past the end. -template -static void room_config_list_register(lua_State* state, const char* name, LuaClass luaClass) -{ - using List = std::vector; - lua_class_begin(state, name, luaClass); - lua_property(state, "Size", [](List& list) { return (int)list.size(); }); - lua_method(state, "Get", [](List& list, uint32_t index) { return index < list.size() ? &list[index] : nullptr; }); - lua_class_end(state, LUA_SCOPE_NAMESPACE); -} - // Registers RoomConfig.Spawn, a cell of a layout and the entities it picks one of, RoomConfig.Entry, one of those, and // their lists, in the RoomConfig namespace begun before. static void room_config_spawns_register(lua_State* state) @@ -53,8 +47,8 @@ static void room_config_spawns_register(lua_State* state) lua_field_get<&RoomEntry::weight>(state, "Weight"); lua_class_end(state, LUA_SCOPE_NAMESPACE); - room_config_list_register(state, "SpawnList", LUA_CLASS_ROOM_CONFIG_SPAWN_LIST); - room_config_list_register(state, "EntryList", LUA_CLASS_ROOM_CONFIG_ENTRY_LIST); + lua_list_register>(state, "SpawnList"); + lua_list_register>(state, "EntryList"); } // Registers Lua's Level, which Game is: the floor's stage, curses, rooms and maps. @@ -102,6 +96,7 @@ static void level_register(lua_State* state) lua_method(state, "GetRooms", [](Level& level) { return LuaRoomList{level.roomList.data(), level.nbRooms}; }); lua_method(state, "GetNonCompleteRoomIndex", [](Level& level) { return level.GetNonCompleteRoomIndex(); }); lua_method(state, "ChangeRoom", [](Level& level, int index, int dimension) { level.ChangeRoom(index, dimension); }); + lua_method(state, "Update", [](Level& level) { level.Update(); }); lua_method(state, "GetEnterPosition", [](Level& level) { return level.GetEnterPosition(); }); lua_field<&Level::enterDoor>(state, "EnterDoor"); lua_field<&Level::leaveDoor>(state, "LeaveDoor"); @@ -201,6 +196,90 @@ static void level_register(lua_State* state) lua_class_end(state); } +// (00812c10, 00813b60, 00813b30, 00813c40, 00813bf0, 00812de0) Registers Room's grid helpers: the path value under +// a position, damaging and destroying grid entities, bridging pits and where a beam lands. +static void room_grid_register(lua_State* state) +{ + lua_method(state, "GetGridPathFromPos", [](Room& room, Vector position) { + int column = (int)((position.x - GRID_ORIGIN_X) / GRID_CELL_SIZE + 0.5f); + int row = (int)((position.y - GRID_ORIGIN_Y) / GRID_CELL_SIZE + 0.5f); + bool isOnGrid = column >= 0 && column < room.gridWidth && row >= 0 && row < room.gridHeight; + int index = row * room.gridWidth + column; + return isOnGrid && index < ROOM_GRID_CELLS ? room.gridPaths[index] : 0; + }); + lua_method(state, "GetClampedGridIndex", + [](Room& room, Vector position) { return room_clamped_grid_index_get(room, position); }); + lua_method(state, "DamageGrid", [](Room& room, uint32_t index, int damage) { + GridEntity* grid = room.GetGridEntity(index); + return grid && grid->Hurt(damage, EntityRef{}); + }); + lua_method(state, "DamageGridWithSource", [](Room& room, uint32_t index, int damage, const EntityRef& source) { + GridEntity* grid = room.GetGridEntity(index); + return grid && grid->Hurt(damage, source); + }); + lua_method(state, "DestroyGrid", [](Room&, int index, bool isImmediate, bool isDefuseBombRock) { + return room_grid_destroy( + {.gridIndex = index, .isImmediate = isImmediate, .isDefuseBombRock = isDefuseBombRock}); + }); + lua_method(state, "DestroyGridWithSource", + [](Room&, int index, bool isImmediate, bool isDefuseBombRock, const EntityRef& source) { + return room_grid_destroy({.source = source, + .gridIndex = index, + .isImmediate = isImmediate, + .isDefuseBombRock = isDefuseBombRock}); + }); + lua_method(state, "TryMakeBridge", + [](Room&, GridEntity* pit, GridEntity* rock) { return room_bridge_make(pit, rock); }); + lua_method(state, "GetLaserTarget", + [](Room&, Vector position, Vector direction) { return room_laser_target_get(position, direction); }); + lua_method(state, "ScreenWrapPosition", + [](Room&, Vector position, float margin) { return room_screen_wrap(position, margin); }); +} + +// (007e91a0, 007537c0, 007537d0, 004566f0, 00820aa0, 006b8400, 007e91b0, 007e91f0, 007120c0, 005784d0, 005b16c0, +// 0085e130, 00428a50) Registers Room's state: its entities, colors, rain and lava, the red heart damage taken, the +// bleeding walls, the dungeon's rock and the shop and clear helpers. The original pushes the L room descriptions as +// unregistered classes. +static void room_state_register(lua_State* state) +{ + lua_method(state, "GetEntities", [](Room& room) -> EntityList_EL& { return room.entityList.updateEL; }); + lua_method(state, "GetRedHeartDamage", [](Room& room) { return room.isRedHeartDamaged; }); + lua_method(state, "SetRedHeartDamage", [](Room& room) { room.isRedHeartDamaged = true; }); + lua_method(state, "SetCardAgainstHumanity", [](Room& room) { room.isCardAgainstHumanity = true; }); + lua_method(state, "EmitBloodFromWalls", [](Room& room, int duration, int count) { + room.bloodFromWallsDuration = duration; + room.bloodFromWallsCount = count; + }); + lua_method(state, "GetDungeonRockIdx", [](Room& room) { + return g_game->levelStateFlags & 1u << LEVEL_STATE_DUNGEON_ROCK_BROKEN ? -1 : room.dungeonRockIdx; + }); + lua_method(state, "SetFirstEnemyDead", [](Room& room, bool isDead) { room.isFirstEnemyDead = isDead; }); + lua_method(state, "SetFloorColor", [](Room& room, const ColorMod& color) { room.floorColor = color; }); + lua_method(state, "SetWallColor", [](Room& room, const ColorMod& color) { room.wallColor = color; }); + lua_method(state, "GetLavaIntensity", [](Room& room) { return room.lavaIntensity; }); + lua_method(state, "StopRain", [](Room& room) { room.isRainStopped = true; }); + lua_method(state, "InvalidatePickupVision", [](Room& room) { room.isPickupVisionInvalid = true; }); + lua_method(state, "GetEnemyDamageInflicted", [](Room& room) { return room.entityList.enemyDamageInflicted; }); + lua_method(state, "GetLRoomAreaDesc", [](Room&) { return LuaOpaque{}; }); + lua_method(state, "GetLRoomTileDesc", [](Room&) { return LuaOpaque{}; }); + lua_method(state, "GetSeededCollectible", [](Room& room, uint32_t seed, bool isNoDecrease) { + return g_game->itemPool.GetSeededCollectible(seed, isNoDecrease, *room.descriptor); + }); + lua_method(state, "ShopRestockPartial", [](Room& room) { room_restock_partial(room); }); + lua_method(state, "ShopRestockFull", [](Room&) { reconstruction_missing("Room::ShopRestockFull 00815ae0"); }); + lua_method(state, "ShopReshuffle", + [](Room&, bool, bool) { reconstruction_missing("Room::ShopReshuffle 00816000"); }); + lua_method(state, "SpawnClearAward", [](Room& room) { room_clear_award_spawn(room); }); + lua_method(state, "TriggerClear", [](Room& room, bool isSilent) { + room_clear_trigger(room, isSilent ? CLEAR_SOUND_SILENT : CLEAR_SOUND_PLAY); + }); + lua_method(state, "RespawnEnemies", [](Room&) { reconstruction_missing("Room::RespawnEnemies 0081fd60"); }); + lua_method(state, "MamaMegaExplosion", + [](Room&, Vector, Entity_Player*) { reconstruction_missing("Room::MamaMegaExplosion 00820910"); }); + lua_method(state, "Update", [](Room& room) { room.Update(); }); + lua_method(state, "Render", [](Room& room) { room.Render(); }); +} + // (007f79d0, 0081e240, 00820c00) Registers Lua's Room: the current room's grid, entities, doors, clear state and the // doors it may spawn. static void room_register(lua_State* state) @@ -323,6 +402,8 @@ static void room_register(lua_State* state) return room.TrySpawnSecretExit(isAnimated, isForced); }); lua_method(state, "TrySpawnSpecialQuestDoor", [](Room& room) { return room.TrySpawnSpecialQuestDoor(); }); + room_grid_register(state); + room_state_register(state); lua_class_end(state); } diff --git a/src/lua_api_sprite.cpp b/src/lua_api_sprite.cpp index ffa6210..06813f1 100644 --- a/src/lua_api_sprite.cpp +++ b/src/lua_api_sprite.cpp @@ -57,6 +57,9 @@ static void sprite_register(lua_State* state) [](ANM2& sprite) -> const std::string& { return sprite.GetDefaultAnimationName(); }); lua_method(state, "GetDefaultAnimationName", [](ANM2& sprite) -> const std::string& { return sprite.GetDefaultAnimationName(); }); + lua_method(state, "GetTexel", [](ANM2& sprite, Vector sample, Vector renderPos, float alpha, int layerId) { + return sprite.GetTexel({.renderPos = renderPos, .sample = sample, .alphaThreshold = alpha, .layerId = layerId}); + }); lua_method(state, "PlayOverlay", [](ANM2& sprite, std::string_view name, bool isForced) { sprite.PlayOverlay(name, isForced ? PLAY_FORCED : PLAY_UNFORCED); diff --git a/src/lua_engine.cpp b/src/lua_engine.cpp index 1492281..59bbfcc 100644 --- a/src/lua_engine.cpp +++ b/src/lua_engine.cpp @@ -178,10 +178,11 @@ void LuaEngine::Init(LuaMode luaMode) // SFXManager and MusicManager classes with the functions returning them. void LuaEngine::RegisterAPI() { - for (auto registerPart : {lua_api_vector_register, lua_api_color_register, lua_api_rng_register, - lua_api_bit_set128_register, lua_api_sprite_register, lua_api_entity_register, - lua_api_entities_register, lua_api_entity_player_register, lua_api_game_register, - lua_api_room_register, lua_api_item_config_register, lua_api_isaac_register}) + for (auto registerPart : + {lua_api_vector_register, lua_api_color_register, lua_api_rng_register, lua_api_bit_set128_register, + lua_api_containers_register, lua_api_sprite_register, lua_api_entity_register, lua_api_entities_register, + lua_api_entity_player_register, lua_api_game_register, lua_api_room_register, lua_api_item_config_register, + lua_api_isaac_register}) registerPart(state); } diff --git a/src/lua_engine.h b/src/lua_engine.h index 8b3680a..003752b 100644 --- a/src/lua_engine.h +++ b/src/lua_engine.h @@ -36,6 +36,7 @@ constexpr int LUA_REF_NONE = -2; // The game classes the API binds, each with the registry key of the metatable its objects get. enum LuaClass { + LUA_CLASS_ACTIVE_ITEM_DESC, LUA_CLASS_BIT_SET128, LUA_CLASS_COLOR, LUA_CLASS_ENTITY, @@ -49,6 +50,8 @@ enum LuaClass LUA_CLASS_PLAYER, LUA_CLASS_PROJECTILE, LUA_CLASS_TEAR, + LUA_CLASS_EFFECT_LIST, + LUA_CLASS_ENTITY_LIST, LUA_CLASS_ENTITY_PTR, LUA_CLASS_ENTITY_REF, LUA_CLASS_FONT, @@ -77,6 +80,7 @@ enum LuaClass LUA_CLASS_LEVEL, LUA_CLASS_MUSIC_MANAGER, LUA_CLASS_PATH_FINDER, + LUA_CLASS_POS_VEL, LUA_CLASS_PROJECTILE_PARAMS, LUA_CLASS_QUEUE_ITEM_DATA, LUA_CLASS_RNG, @@ -95,6 +99,7 @@ enum LuaClass LUA_CLASS_TEMPORARY_EFFECT, LUA_CLASS_TEMPORARY_EFFECTS, LUA_CLASS_VECTOR, + LUA_CLASS_VECTOR_LIST, LUA_CLASS_COUNT }; diff --git a/src/music_manager.h b/src/music_manager.h index 3a2b00a..02f7219 100644 --- a/src/music_manager.h +++ b/src/music_manager.h @@ -49,6 +49,7 @@ enum MusicId : int MUSIC_MOM_BOSS = 20, MUSIC_MOMS_HEART_BOSS = 21, MUSIC_ISAAC_BOSS = 22, + MUSIC_SATAN_BOSS = 23, MUSIC_DARK_ROOM_BOSS = 24, MUSIC_CHEST_BOSS = 25, MUSIC_BOSS2 = 26, diff --git a/src/npc_ai.cpp b/src/npc_ai.cpp index bc88f23..6a59ac0 100644 --- a/src/npc_ai.cpp +++ b/src/npc_ai.cpp @@ -1,6 +1,6 @@ #include "npc_ai.h" #include "boss_ai.h" -#include "npc_depths.h" +#include "npc_alt.h" #include "game.h" #include "manager.h" #include "npc_fireplace.h" @@ -166,7 +166,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 39: case 49: case 836: - return (void)NpcAI::ENTITY_VIS(&npc); + return npc_vis_update(npc); case 40: case 218: case 862: @@ -185,17 +185,12 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 45: return boss_mom_update(npc); case 46: - return (void)NpcAI::ENTITY_SLOTH(&npc); case 47: - return (void)NpcAI::ENTITY_LUST(&npc); case 48: - return (void)NpcAI::ENTITY_WRATH(&npc); case 50: - return (void)NpcAI::ENTITY_GREED(&npc); case 51: - return (void)NpcAI::ENTITY_ENVY(&npc); case 52: - return (void)NpcAI::ENTITY_PRIDE(&npc); + return npc_sin_update(npc); case 53: return (void)NpcAI::ENTITY_DOPLE(&npc); case 56: @@ -206,9 +201,9 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 58: return npc_para_bite_update(npc); case 59: - return (void)NpcAI::ENTITY_FRED(&npc); + return npc_fred_update(npc); case 60: - return (void)NpcAI::ENTITY_EYE(&npc); + return npc_eye_update(npc); case 62: return (void)NpcAI::ENTITY_PIN(&npc); case 63: @@ -240,12 +235,12 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 79: return boss_gemini_update(npc); case 81: - return (void)NpcAI::ENTITY_FALLEN(&npc); + return boss_fallen_update(npc); case 82: case 83: return (void)NpcAI::ENTITY_HEADLESS_HORSEMAN(&npc); case 84: - return (void)NpcAI::ENTITY_SATAN(&npc); + return boss_satan_update(npc); case 85: case 94: case 215: @@ -279,7 +274,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 100: return boss_widow_update(npc); case 101: - return (void)NpcAI::ENTITY_DADDYLONGLEGS(&npc); + return boss_daddy_long_legs_update(npc); case 102: return (void)NpcAI::ENTITY_ISAAC(&npc); case 201: @@ -336,7 +331,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 241: case 242: case 304: - return (void)NpcAI::ENTITY_WALL_CREEP(&npc); + return npc_wall_creep_update(npc); case 244: case 255: case 276: @@ -387,7 +382,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 288: return npc_dukie_update(npc); case 290: - return (void)NpcAI::ENTITY_MEATBALL(&npc); + return npc_meatball_update(npc); case 291: return npc_pitfall_update(npc); case 292: @@ -447,7 +442,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 802: return (void)NpcAI::ENTITY_BLOOD_PUPPY(&npc); case 804: - return (void)NpcAI::ENTITY_QUAKE_GRIMACE(&npc); + return npc_quake_grimace_update(npc); case 805: return (void)NpcAI::ENTITY_BISHOP(&npc); case 806: @@ -455,7 +450,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 808: return (void)NpcAI::ENTITY_WILLO(&npc); case 809: - return (void)NpcAI::ENTITY_BOMB_GRIMACE(&npc); + return npc_bomb_grimace_update(npc); case 810: return (void)NpcAI::ENTITY_SMALL_LEECH(&npc); case 811: @@ -475,17 +470,17 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 820: return (void)NpcAI::ENTITY_DANNY(&npc); case 821: - return (void)NpcAI::ENTITY_BLASTER(&npc); + return npc_blaster_update(npc); case 822: return (void)NpcAI::ENTITY_BOUNCER(&npc); case 823: - return (void)NpcAI::ENTITY_QUAKEY(&npc); + return npc_quakey_update(npc); case 824: return (void)NpcAI::ENTITY_GYRO(&npc); case 825: return (void)NpcAI::ENTITY_FIRE_WORM(&npc); case 826: - return (void)NpcAI::ENTITY_HARDY(&npc); + return npc_hardy_update(npc); case 827: return (void)NpcAI::ENTITY_FACELESS(&npc); case 828: diff --git a/src/npc_ai.h b/src/npc_ai.h index dbca27f..f2434a0 100644 --- a/src/npc_ai.h +++ b/src/npc_ai.h @@ -109,6 +109,7 @@ void npc_fly_update(Entity_NPC& npc); void npc_gaper_update(Entity_NPC& npc); void npc_horf_update(Entity_NPC& npc); void npc_dip_update(Entity_NPC& npc); +void npc_sin_update(Entity_NPC& npc); // The corn dip's variant. constexpr int DIP_CORN = 1; diff --git a/src/npc_alt.h b/src/npc_alt.h new file mode 100644 index 0000000..488d98b --- /dev/null +++ b/src/npc_alt.h @@ -0,0 +1,22 @@ +#pragma once + +#include "npc_depths.h" + +// The alt path enemies' AIs (the Downpour, Dross, Mines and Ashpit) the dispatcher (npc_ai_update) runs by type. +void npc_blaster_update(Entity_NPC& npc); +void npc_quakey_update(Entity_NPC& npc); +void npc_hardy_update(Entity_NPC& npc); + +// The variants rock_spider_throw throws: a small, big or tinted rock spider, or a coal spider (a fireplace). +enum RockSpiderKind +{ + SPIDER_THROW_SMALL, + SPIDER_THROW_BIG, + SPIDER_THROW_TINTED, + SPIDER_THROW_COAL +}; + +Entity_NPC* rock_spider_throw(const Vector& position, const Vector& velocity, Entity* spawner, RockSpiderKind kind, + float height); +void npc_bomb_grimace_update(Entity_NPC& npc); +void npc_quake_grimace_update(Entity_NPC& npc); diff --git a/src/npc_basement.h b/src/npc_basement.h index 791a450..55fb288 100644 --- a/src/npc_basement.h +++ b/src/npc_basement.h @@ -28,6 +28,7 @@ void npc_boil_update(Entity_NPC& npc); void npc_walking_boil_update(Entity_NPC& npc); void npc_baby_long_legs_update(Entity_NPC& npc); void npc_movable_tnt_update(Entity_NPC& npc); +void npc_vis_update(Entity_NPC& npc); // Cancels an enemy's pending damage of the given kinds, but the players' own, friendly ones' and TNT's. void npc_hostile_damage_ignore(Entity_NPC& npc, uint64_t damageFlags); diff --git a/src/npc_blaster.cpp b/src/npc_blaster.cpp new file mode 100644 index 0000000..9807f17 --- /dev/null +++ b/src/npc_blaster.cpp @@ -0,0 +1,120 @@ +#include "npc_alt.h" +#include "boss_ai.h" + +// The Blaster takes a quarter of any damage but explosions and crushing. Wandering, it starts its attack one time in +// 70 while fewer than 4 fly bombs fly, facing its prey. +constexpr float BLASTER_ARMOR = 0.75f; +constexpr uint64_t BLASTER_UNARMORED = DAMAGE_EXPLOSION | DAMAGE_CRUSH; +constexpr ColorMod BLASTER_SPLAT_COLOR = {{0, 0, 0, 1}, {0, 0, 0, 0}, {30 / 255.0f, 30 / 255.0f, 30 / 255.0f}}; +constexpr float BLASTER_WALK_THRESHOLD = 0.1f; +constexpr float BLASTER_FRICTION = 0.7f; +constexpr uint32_t BLASTER_ATTACK_ODDS = 70; +constexpr int BLASTER_BOMB_LIMIT = 4; + +// Its shot: a fly bomb spat ahead (never backward) toward where its prey will be, at 10, which kicks it back at 4 a +// frame for 5 frames. +constexpr float BLASTER_LEAD = 0.1f; +constexpr float BLASTER_MUZZLE = 5; +constexpr float BLASTER_BOMB_SPEED = 10; +constexpr int BLASTER_RECOIL_FRAMES = 5; +constexpr float BLASTER_RECOIL = 4; +constexpr float BLASTER_RECOIL_FRICTION = 0.9f; +constexpr int BLASTER_SHOT_DELAY = 10; +constexpr float FLY_BOMB_HEALTH = 0.1f; +constexpr int FLY_BOMB_FUSE = 60; + +// Where its prey will be, moving on for a tenth of its distance, or where its controller aims. +static Vector blaster_aim_get(Entity_NPC& npc) +{ + if (npc.controllerID != -1) return npc.GetAimTargetPosition(); + + Entity* prey = npc.GetPlayerTarget(); + float lead = vector_length(vector_sub(npc.pos, prey->pos)) * BLASTER_LEAD; + return vector_make(prey->velocity.x * lead + prey->pos.x, prey->velocity.y * lead + prey->pos.y); +} + +// Spits a fly bomb at its aim, lit at once, a charmed Blaster's charmed too. +static void blaster_shoot(Entity_NPC& npc) +{ + npc.PlaySound(SOUND_BULLET_SHOT, 1, BLASTER_SHOT_DELAY, false, 1); + Vector direction = vector_sub(blaster_aim_get(npc), npc.pos); + if (npc.sprite.isFlipX ? direction.x >= 0 : direction.x <= 0) direction.x = 0; + direction = vector_normalized(direction); + npc.targetPosition = direction; + npc.stateFrame = BLASTER_RECOIL_FRAMES; + + uint32_t seed = Random(); + auto* bomb = static_cast(g_game->Spawn({.position = vector_add(npc.pos, vector_scale(direction, BLASTER_MUZZLE)), + .velocity = vector_scale(direction, BLASTER_BOMB_SPEED), + .spawner = &npc, + .type = ENTITY_FLY_BOMB, + .seed = seed})); + bomb->ClearEntityFlags(FLAG_APPEAR); + if (npc.HasEntityFlags(FLAG_CHARM)) bomb->AddCharmed({}, -1, false, false); + bomb->Update(); + bomb->state = NPC_STATE_SPECIAL; + bomb->health = FLY_BOMB_HEALTH; + bomb->i1 = FLY_BOMB_FUSE; +} + +// 004fcc20 The Blaster's AI: an armored wanderer spitting fly bombs that kick it back. +void npc_blaster_update(Entity_NPC& npc) +{ + if (npc.aiCallPhase == AI_PHASE_PRE_UPDATE) + { + for (DamageEvent& event : npc.damageEvents) + { + if (event.damageFlags & BLASTER_UNARMORED) continue; + + float blocked = event.damage * BLASTER_ARMOR; + npc.pendingDamage -= blocked; + event.damage -= blocked; + } + if (!(npc.pendingDamage >= 0)) npc.pendingDamage = 0; + return; + } + + if (npc.state == NPC_STATE_INIT) + { + npc.state = NPC_STATE_MOVE; + npc.sprite.Play("WalkVert"); + npc.splatColor = BLASTER_SPLAT_COLOR; + npc.aiCallFlags = AI_CALL_PRE_UPDATE; + } + else if (npc.state == NPC_STATE_MOVE) + { + npc.AnimWalkFrame("WalkHori", "WalkVert", BLASTER_WALK_THRESHOLD); + npc.friction *= BLASTER_FRICTION; + bool isFriendlyIdle = npc.IsFriendly() && npc.controllerID == -1; + npc.pathfinder.MoveRandomly(isFriendlyIdle ? STATUS_IGNORED : STATUS_OBEYED); + npc.SpawnControlTarget(0, -1); + + bool isAttacking = npc.controllerID == -1 && Random() % BLASTER_ATTACK_ODDS == 0; + if (npc.controllerID != -1 && npc.IsControllerActionPressed(CONTROLLER_ACTION_SHOOT)) + { + Vector aim = npc.GetAimTargetPosition(); + isAttacking = aim.x != npc.pos.x || aim.y != npc.pos.y; + } + if (!isAttacking || npc.HasEntityFlags(FLAG_CONFUSION | FLAG_FEAR)) return; + if (entity_query(ENTITY_FLY_BOMB, 0).size() >= BLASTER_BOMB_LIMIT) return; + + npc.state = NPC_STATE_ATTACK; + npc.sprite.Play("Attack"); + float x = npc.controllerID == -1 ? npc.GetPlayerTarget()->pos.x : npc.GetAimTargetPosition().x; + npc.sprite.isFlipX = npc.pos.x > x; + } + else if (npc.state == NPC_STATE_ATTACK) + { + npc.SpawnControlTarget(0, -1); + if (npc.sprite.animState.animData && npc.sprite.animState.IsEventTriggered("Shoot")) blaster_shoot(npc); + if (npc.stateFrame < 1) npc.friction *= BLASTER_FRICTION; + else + { + npc.stateFrame -= npc_ticks_get(npc); + npc.velocity.x -= npc.targetPosition.x * BLASTER_RECOIL * npc.speedMultiplier; + npc.velocity.y -= npc.targetPosition.y * BLASTER_RECOIL * npc.speedMultiplier; + npc.friction *= BLASTER_RECOIL_FRICTION; + } + if (npc_anim_is_done(npc)) npc.state = NPC_STATE_MOVE; + } +} diff --git a/src/npc_bomb_grimace.cpp b/src/npc_bomb_grimace.cpp new file mode 100644 index 0000000..d9c3f3e --- /dev/null +++ b/src/npc_bomb_grimace.cpp @@ -0,0 +1,144 @@ +#include "npc_alt.h" +#include "boss_ai.h" +#include "entity_pickup.h" +#include "level.h" + +// The Bomb Grimace: an invincible face in the wall held in its cell (its cell walls the grid path off). It starts +// with a bomb before it (but in the mineshaft), and once its bomb is gone it spits another 30 frames later. The +// mineshaft's spit on and on until the escape. +constexpr int GRIMACE_PATH_MARKER = 3999; +constexpr uint64_t GRIMACE_FLAGS = + FLAG_NO_STATUS_EFFECTS | FLAG_NO_PHYSICS_KNOCKBACK | FLAG_HIDE_HP_BAR | FLAG_NO_PLAYER_CONTROL; +constexpr ColorMod GRIMACE_SPLAT_COLOR = {{1, 1, 1, 1}, {1, 1, 1, 1}, {0, 0, 0}}; +constexpr float GRIMACE_CELL = 40; +constexpr float GRIMACE_ORIGIN_X = 40; +constexpr float GRIMACE_ORIGIN_Y = 120; +constexpr float GRIMACE_FIRST_BOMB_DROP = 40; +constexpr int GRIMACE_RELOAD_FRAMES = 30; +constexpr int GRIMACE_SPIT_DELAY = 2; +constexpr float GRIMACE_SPIT_DROP = 6; +constexpr float GRIMACE_SPIT_SPEED = 1.25f; + +// Destroyed, it scatters 10 bombs one a frame, 4 out at 0.5 to 2, and never comes back to its cell. +constexpr int GRIMACE_SCATTER_INTERVAL = 1; +constexpr int GRIMACE_SCATTER_BOMBS = 10; +constexpr float GRIMACE_SCATTER_REACH = 4; +constexpr float GRIMACE_SCATTER_SPEED_MIN = 0.5f; +constexpr float GRIMACE_SCATTER_SPEED_RANGE = 1.5f; + +// The center of the grid cell under a position. +static Vector grimace_cell_get(Room& room, Vector position) +{ + int cell = room.GetGridIndex(position); + return vector_make((float)(cell % room.gridWidth) * GRIMACE_CELL + GRIMACE_ORIGIN_X, + (float)(cell / room.gridWidth) * GRIMACE_CELL + GRIMACE_ORIGIN_Y); +} + +// A troll bomb spawned at a position. +static Entity* grimace_bomb_spawn(Vector position, Vector velocity, Entity* spawner, uint32_t seed) +{ + return g_game->Spawn({.position = position, + .velocity = velocity, + .spawner = spawner, + .type = ENTITY_PICKUP, + .variant = PICKUP_THROWABLEBOMB, + .seed = seed}); +} + +// 004f8cc0 One bomb of a destroyed Bomb Grimace's scatter. +static void grimace_scatter(Entity_Effect* timer) +{ + Vector direction = random_direction(); + uint32_t seed = Random(); + float speed = random_unit() * GRIMACE_SCATTER_SPEED_RANGE + GRIMACE_SCATTER_SPEED_MIN; + grimace_bomb_spawn(vector_add(vector_scale(direction, GRIMACE_SCATTER_REACH), timer->pos), + vector_scale(direction, speed), nullptr, seed); +} + +// Its bomb, the one it watches until it is gone. +static void grimace_bomb_set(Entity_NPC& npc, Entity* bomb) +{ + npc.child = bomb; + bomb->parent = &npc; +} + +// Takes its cell and lays its first bomb before it, already lying still. +static void grimace_init(Entity_NPC& npc, bool isInMineshaft) +{ + Room& room = *g_game->room; + npc.AddEntityFlags(GRIMACE_FLAGS); + npc.isInvincible = true; + npc.aiCallFlags = AI_CALL_PRE_UPDATE; + npc.state = NPC_STATE_IDLE; + if (!npc.minecart) + { + Vector cell = grimace_cell_get(room, npc.pos); + npc.pathfinder.UpdateGridIndex(); + npc.targetPosition = cell; + } + if (isInMineshaft) npc.ClearEntityFlags(FLAG_APPEAR); + + if (!npc.child && !isInMineshaft) + { + Vector cell = grimace_cell_get(room, vector_make(npc.pos.x + 0, npc.pos.y + GRIMACE_FIRST_BOMB_DROP)); + Entity* bomb = grimace_bomb_spawn(cell, {}, &npc, Random()); + grimace_bomb_set(npc, bomb); + bomb->Update(); + AnimationState& animation = bomb->sprite.animState; + if (animation.animData) animation.AdvancePosition(animation.animData->length - 1); + } + npc.splatColor = GRIMACE_SPLAT_COLOR; +} + +// 004f8df0 The Bomb Grimace's AI: a wall face spitting troll bombs, one at a time. +void npc_bomb_grimace_update(Entity_NPC& npc) +{ + Game& game = *g_game; + if (npc.aiCallPhase == AI_PHASE_PRE_UPDATE) + { + if (!npc.minecart && !npc.isDead && npc.pathfinder.gridIndex >= 0) + game.room->SetGridPath(npc.pathfinder.gridIndex, GRIMACE_PATH_MARKER); + return; + } + + bool isInMineshaft = game.HasAbandonedMineshaft() && game.currentDimensionIdx == DIMENSION_MIRROR && + !game.Level::GetStateFlag(LEVEL_STATE_MINESHAFT_ESCAPE); + if (npc.state == NPC_STATE_INIT) grimace_init(npc, isInMineshaft); + + if (npc.state == NPC_STATE_IDLE) + { + npc.sprite.Play("Idle"); + if (npc.stateFrame >= 1 && !isInMineshaft) + { + if (--npc.stateFrame == 0) npc.state = NPC_STATE_ATTACK; + } + else if (!npc.child || npc.child->isDead) + { + npc.child = nullptr; + npc.stateFrame = GRIMACE_RELOAD_FRAMES; + } + } + else if (npc.state == NPC_STATE_ATTACK) + { + npc.sprite.Play("Shoot"); + AnimationState& animation = npc.sprite.animState; + if (animation.animData && animation.IsEventTriggered("Shoot")) + { + npc.PlaySound(SOUND_STONESHOOT, 1, GRIMACE_SPIT_DELAY, false, 1); + uint32_t seed = Random(); + grimace_bomb_set(npc, grimace_bomb_spawn(vector_make(npc.pos.x + 0, npc.pos.y + GRIMACE_SPIT_DROP), + vector_make(0, GRIMACE_SPIT_SPEED), &npc, seed)); + } + if (npc_anim_is_done(npc)) npc.state = NPC_STATE_IDLE; + } + + if (npc.isDead) + { + Entity_Effect* scatter = Entity_Effect::CreateTimer(reinterpret_cast(&grimace_scatter), + GRIMACE_SCATTER_INTERVAL, GRIMACE_SCATTER_BOMBS, false); + scatter->pos = npc.pos; + scatter->Update(); + game.GetRoomByIdx(game.currentRoomIdx)->restrictedGridIndexes.insert(npc.spawnGridIndex); + } + if (!npc.minecart) npc.velocity = vector_sub(npc.targetPosition, npc.pos); +} diff --git a/src/npc_collision.cpp b/src/npc_collision.cpp index 95aa02f..34434c3 100644 --- a/src/npc_collision.cpp +++ b/src/npc_collision.cpp @@ -24,10 +24,6 @@ constexpr int ENTITY_MEGA_MAW = 262; constexpr int ENTITY_SWARM = 281; constexpr int ENTITY_ULTRA_COIN = 293; constexpr int ENTITY_FISTULOID = 308; -constexpr int ENTITY_BROWNIE = 402; -constexpr int ENTITY_BOMB_GRIMACE = 809; -constexpr int ENTITY_FISSURE = 815; -constexpr int ENTITY_BLASTER = 821; constexpr int ENTITY_BOUNCER = 822; constexpr int ENTITY_GASBAG = 856; constexpr int ENTITY_ARMYFLY = 868; @@ -141,14 +137,6 @@ static bool is_in(std::span kinds, int kind) return std::ranges::find(kinds, kind) != kinds.end(); } -// Sorted insertion into a hit list, as the entities keep them. -static void hit_list_add(std::vector& hitList, Entity& entity) -{ - uint32_t index = entity.GetHitListIndex(); - auto at = std::lower_bound(hitList.begin(), hitList.end(), index); - if (at == hitList.end() || *at != index) hitList.insert(at, index); -} - static void damage_deal(Entity& target, float damage, uint64_t damageFlags, Entity* source) { target.TakeDamage(damage, damageFlags, source ? EntityRef(source) : EntityRef(), CONTACT_COUNTDOWN); @@ -275,7 +263,7 @@ static Verdict contact_pairs(Contact& contact) if (isBall && collider.IsVulnerableEnemy(nullptr) && vector_length(npc.velocity) > BALL_SPEED && !EntityList::HitListContains(npc.hitList, collider)) { - hit_list_add(npc.hitList, collider); + hit_list_insert(npc.hitList, collider); damage_deal(collider, BALL_DAMAGE, 0, &npc); } if (npc.type == ENTITY_VISAGE) reconstruction_missing("Entity_NPC::HandleCollision 006cd410: Visage's contacts"); @@ -784,7 +772,7 @@ static Verdict contact_late(Contact& contact) else if (npcType == ENTITY_GRUDGE && collider.IsEnemy() && npc.collisionDamage > 0 && !EntityList::HitListContains(npc.hitList, collider)) { - hit_list_add(npc.hitList, collider); + hit_list_insert(npc.hitList, collider); damage_deal(collider, GRUDGE_DAMAGE, 0, &npc); } return std::nullopt; @@ -798,7 +786,7 @@ static void contact_enemy(Entity_NPC& npc, Entity& other) if (npc.type == ENTITY_BLOOD_PUPPY && other.IsEnemy()) { if (EntityList::HitListContains(npc.hitList, other)) return; - hit_list_add(npc.hitList, other); + hit_list_insert(npc.hitList, other); damage = npc.variant == 1 ? BLOOD_PUPPY_BIG_BITE : BLOOD_PUPPY_BITE; } else @@ -809,7 +797,7 @@ static void contact_enemy(Entity_NPC& npc, Entity& other) if ((isSameSide && !isTargeted) || npc.collisionDamage <= 0 || EntityList::HitListContains(npc.hitList, other)) return; - hit_list_add(npc.hitList, other); + hit_list_insert(npc.hitList, other); damage = std::log((npc.maxHitPoints + CHARMED_DAMAGE_BASE) / CHARMED_DAMAGE_SCALE) * CHARMED_DAMAGE_LOG; if (npc.HasEntityFlags(FLAG_DELIRIUM_FORM) && g_game->deathmatchManager.is_active()) damage = npc.collisionDamage; @@ -833,7 +821,7 @@ static void contact_impact(Entity_NPC& npc, Entity& other) if (!other.IsVulnerableEnemy(nullptr) || !npc.HasEntityFlags(FLAG_APPLY_IMPACT_DAMAGE) || EntityList::HitListContains(npc.hitList, other)) return; - hit_list_add(npc.hitList, other); + hit_list_insert(npc.hitList, other); int stage = g_game->stage; if (g_game->stageType == STAGETYPE_REPENTANCE || g_game->stageType == STAGETYPE_REPENTANCE_B) stage++; damage_deal(other, (float)(stage - 1) * 2 + IMPACT_DAMAGE_BASE, 0, nullptr); diff --git a/src/npc_depths.h b/src/npc_depths.h index da41ad8..94aa445 100644 --- a/src/npc_depths.h +++ b/src/npc_depths.h @@ -15,3 +15,7 @@ void npc_blister_update(Entity_NPC& npc); void npc_fat_sack_update(Entity_NPC& npc); void npc_deep_gaper_update(Entity_NPC& npc); void npc_blurb_update(Entity_NPC& npc); +void npc_fred_update(Entity_NPC& npc); +void npc_eye_update(Entity_NPC& npc); +void npc_meatball_update(Entity_NPC& npc); +void npc_wall_creep_update(Entity_NPC& npc); diff --git a/src/npc_eye.cpp b/src/npc_eye.cpp new file mode 100644 index 0000000..441429e --- /dev/null +++ b/src/npc_eye.cpp @@ -0,0 +1,339 @@ +#include "npc_depths.h" +#include "boss_ai.h" +#include "camera.h" +#include "entity_effect.h" +#include "entity_familiar.h" +#include "entity_laser.h" +#include "grid_entity.h" +#include "npc_caves.h" + +// The Eye (variant 0) and the Bloodshot Eye turn their pupils toward their target and fire a beam, the Holy Eye calls +// down beams of light around its target. +constexpr int EYE_BLOODSHOT = 1; +constexpr int HOLY_EYE = 2; +constexpr int EYE_SHOOTING = NPC_STATE_ATTACK; + +// They sit on their cell, under everything, breaking what grew there, and mark it off for walkers. +constexpr int EYE_RENDER_Z = -3000; +constexpr int EYE_PATH_LIMIT = 951; +constexpr float EYE_FRICTION = 0.8f; + +// The pupil turns at 6 degrees a frame (the Bloodshot Eye's 9), slower the farther the target is (a degree per 330), +// aiming where the target will be in 2 frames. A tenth of the frames it looks within half that turn, it fires. +constexpr float EYE_TURN_BASE = 3; +constexpr float EYE_TURN_DISTANCE = 330; +constexpr float EYE_LEAD_FRAMES = 2; +constexpr float EYE_MIN_AIM = 0.001f; +constexpr uint32_t EYE_SHOT_ODDS = 10; +constexpr float EYE_CONTROL_DEADZONE = 0.1f; + +// The Eye's pupil rides 6 from its middle and its beam starts 2.5 times as far out. The Bloodshot Eye's pupil sits on +// its PupilPos null, its rotation frame a quarter turn on. +constexpr float EYE_PUPIL_REACH = 6; +constexpr float EYE_MUZZLE_SCALE = 2.5f; +constexpr float BLOODSHOT_ROTATE_OFFSET = 105; +constexpr float BLOODSHOT_MUZZLE_HEIGHT = -20; +constexpr float BLOODSHOT_TRACER_DROP = -8; +constexpr float EYE_SCREEN_SCALE = 0.65f; + +// The tracer warning of the beam, and the beams: the Eye's thin and short, the Bloodshot Eye's thick. +constexpr ColorMod EYE_TRACER_COLOR = {{0.6f, 0.05f, 0, 0.8f}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr int EYE_TRACER_TIMEOUT = 15; +constexpr float EYE_TRACER_SCALE = 4; +constexpr int EYE_BEAM_TIMEOUT = 3; +constexpr int BLOODSHOT_BEAM_TIMEOUT = 8; +constexpr float EYE_BEAM_DEPTH = 3000; + +// The Holy Eye calls its light 15 to 75 frames in (30 under control), then every 60 to 120 (60), sooner as it is hurt +// (10 frames a point). Its four beams land ever wider around its target's path: on its lead, then 100, 70 and 50 +// out, 20 from the walls. +constexpr uint32_t HOLY_EYE_FIRST_SPREAD = 60; +constexpr int HOLY_EYE_FIRST_DELAY = 15; +constexpr int HOLY_EYE_CONTROL_FIRST_DELAY = 30; +constexpr uint32_t HOLY_EYE_SPREAD = 60; +constexpr int HOLY_EYE_DELAY = 60; +constexpr float HOLY_EYE_HURT_HASTE = 10; +constexpr float HOLY_EYE_SOUND_VOLUME = 0.5f; +constexpr float HOLY_EYE_SOUND_PITCH = 1.5f; +constexpr float HOLY_EYE_LEAD = 5; +constexpr float HOLY_EYE_WALL_MARGIN = 20; +constexpr int HOLY_LIGHT_SUBTYPE = 2; +constexpr float HOLY_LIGHT_SIZE = 10; +constexpr float HOLY_LIGHT_DAMAGE = 7; + +// Each beam's reach around the target and lead on its velocity, by how many fell before it. +struct HolyLightAim +{ + float scatter = 0; + float lead = 0; +}; +constexpr std::array HOLY_LIGHT_AIMS = {{{0, HOLY_EYE_LEAD}, {100, 15}, {70, 20}, {50, 30}}}; + +// The cell an eye sits on, or -1 outside the room. +static int eye_cell_get(const Vector& position) +{ + Room& room = *g_game->room; + int column = (int)((position.x - GRID_ORIGIN_X) / GRID_CELL_SIZE + 0.5f); + int row = (int)((position.y - GRID_ORIGIN_Y) / GRID_CELL_SIZE + 0.5f); + if (column < 0 || column >= room.gridWidth || row < 0 || row >= room.gridHeight) return -1; + return room.gridWidth * row + column; +} + +// An eye breaks what grew on its cell as it opens. +static void eye_cell_clear(Entity_NPC& npc, int cell) +{ + GridEntity* grid = cell >= 0 && cell < ROOM_GRID_CELLS ? g_game->room->GetGridEntity((uint32_t)cell) : nullptr; + if (grid) grid->Destroy(false, EntityRef(&npc)); +} + +// Every frame: held on its spot and its cell marked off. +static void eye_hold(Entity_NPC& npc, int cell) +{ + Room& room = *g_game->room; + npc.friction *= EYE_FRICTION; + npc.velocity = vector_sub(npc.targetPosition, npc.pos); + if (cell >= 0 && cell < ROOM_GRID_CELLS && room.gridPaths[cell] < EYE_PATH_LIMIT) room.gridPaths[cell] = GRID_PATH_FREED; +} + +static bool eye_is_dazed(Entity_NPC& npc) +{ + return npc.HasEntityFlags(FLAG_CONFUSION | FLAG_FEAR | FLAG_SHRINK); +} + +// The shot's start: the Eye blinks Shoot, the Bloodshot Eye its overlay. +static void eye_shot_start(Entity_NPC& npc) +{ + if (npc.variant == 0) npc.sprite.Play("Shoot"); + else npc.sprite.PlayOverlay("ShootOverlay"); + npc.state = EYE_SHOOTING; + npc.stateFrame = 0; +} + +// Turning: the pupil swings toward where its target is headed, firing now and then when it looks close enough. +static void eye_turn(Entity_NPC& npc) +{ + float turnLimit = (float)(npc.variant + 1) * EYE_TURN_BASE + EYE_TURN_BASE; + if (npc.controllerID != -1) + { + Vector push = npc.GetControllerMovementInput(EYE_CONTROL_DEADZONE); + if (!vector_is_zero(push)) npc.v1.x = angle_approach(npc.v1.x, vector_angle(push), turnLimit); + if (npc.IsControllerActionPressed(CONTROLLER_ACTION_SHOOT) && !eye_is_dazed(npc)) eye_shot_start(npc); + return; + } + + Vector away = vector_sub(npc.pos, npc.CalcTargetPosition(0)); + Vector targetVelocity = npc.GetPlayerTarget()->velocity; + Vector aim = vector_sub(away, vector_scale(targetVelocity, EYE_LEAD_FRAMES)); + if (aim.y == 0) aim.y = EYE_MIN_AIM; + float limit = turnLimit - vector_length(away) / EYE_TURN_DISTANCE; + float delta = vector_angle(aim) - npc.v1.x + 180; + while (delta > 180) delta -= 360; + while (delta < -180) delta += 360; + + float turn = limit; + if (delta <= limit) turn = -limit <= delta ? delta : -limit; + bool isShooting = std::abs(turn) < limit / 2 && Random() % EYE_SHOT_ODDS == 0 && !npc.HasEntityFlags(FLAG_CONFUSION) && + !npc.HasEntityFlags(FLAG_FEAR | FLAG_SHRINK) && g_game->room->camera->IsPosVisible(npc.pos); + if (isShooting) + { + eye_shot_start(npc); + Vector muzzle = npc.variant == 0 ? vector_scale(npc.sprite.GetLayer(1)->pos, EYE_MUZZLE_SCALE) + : vector_add(npc.sprite.GetNullFrame("PupilPos")->pos, vector_make(0, BLOODSHOT_TRACER_DROP)); + following_effect_spawn(npc, {.offset = muzzle, + .targetPosition = vector_from_angle(npc.v1.x), + .color = EYE_TRACER_COLOR, + .scale = EYE_TRACER_SCALE, + .timeout = EYE_TRACER_TIMEOUT}); + } + npc.v1.x += turn; +} + +// The pupil drawn at its angle: the Eye's pupil layer moved, the Bloodshot Eye's Rotate frame picked. +static void eye_pupil_place(Entity_NPC& npc) +{ + if (npc.variant == 0) + { + npc.sprite.GetLayer(1)->pos = vector_scale(vector_from_angle(npc.v1.x), EYE_PUPIL_REACH); + return; + } + + float angle = angle_wrap(npc.v1.x + BLOODSHOT_ROTATE_OFFSET); + const AnimationData* data = npc.sprite.animState.animData; + if (data) npc.sprite.animState.SetFrameFloat((float)(int)((float)data->length * ((angle + 180) / 360))); +} + +// Shooting: on Shoot its beam from the pupil, then back to turning once the blink ends. +static void eye_shoot(Entity_NPC& npc) +{ + bool isShot = npc.variant == 0 ? npc.sprite.IsEventTriggered("Shoot") + : npc.sprite.overlayAnimState.IsEventTriggered("Shoot"); + if (isShot) + { + Vector from = npc.pos; + Vector offset{}; + if (npc.variant == 0) from = vector_add(from, vector_scale(npc.sprite.GetLayer(1)->pos, EYE_MUZZLE_SCALE)); + else + { + offset = vector_make(0, BLOODSHOT_MUZZLE_HEIGHT); + Vector pupil = npc.sprite.GetNullFrame("PupilPos")->pos; + from = vector_add(from, vector_make(pupil.x / EYE_SCREEN_SCALE, pupil.y / EYE_SCREEN_SCALE - BLOODSHOT_MUZZLE_HEIGHT)); + } + Entity_Laser* laser = Entity_Laser::ShootAngle({.position = from, + .posOffset = offset, + .source = &npc, + .angleDegrees = npc.v1.x, + .timeout = npc.variant == 0 ? EYE_BEAM_TIMEOUT : BLOODSHOT_BEAM_TIMEOUT, + .variant = npc.variant == 0 ? LASER_THIN_RED : LASER_THICK_RED}); + laser->renderDepthOffset = EYE_BEAM_DEPTH; + laser->Update(); + } + + if (npc.variant != 0) + { + AnimationState& overlay = npc.sprite.overlayAnimState; + if (!overlay.animData || !overlay.isPlaying) + { + npc.state = NPC_STATE_MOVE; + overlay.SetAnimationData(nullptr); + } + return; + } + if (npc_anim_is_done(npc)) + { + npc.state = NPC_STATE_MOVE; + npc.sprite.Play("Eye Opened"); + } +} + +// The Bloodshot Eye's blink squashes its body along its overlay's Deform null. +static void bloodshot_deform(Entity_NPC& npc) +{ + if (npc.variant != EYE_BLOODSHOT || !npc.sprite.overlayAnimState.isPlaying) return; + + const NullFrame* deform = npc.sprite.overlayAnimState.GetNullFrame("Deform"); + if (!deform || !deform->isVisible) return; + + LayerState* body = npc.sprite.GetLayer(0); + body->pos = deform->pos; + body->size = deform->scale; + body->color = deform->color; +} + +// The Holy Eye's light: a beam from the sky around its target's path, by how many fell before it, its cell marked. +static void holy_light_call(Entity_NPC& npc) +{ + npc.PlaySound(SOUND_LASERRING_WEAK, HOLY_EYE_SOUND_VOLUME, 2, false, HOLY_EYE_SOUND_PITCH); + Entity* target = npc.GetPlayerTarget(); + Vector aim = target->pos; + if (npc.i1 >= 0 && npc.i1 < (int)HOLY_LIGHT_AIMS.size()) + { + const HolyLightAim& spread = HOLY_LIGHT_AIMS[npc.i1]; + Vector scatter{}; + if (spread.scatter > 0) + { + Vector direction = random_direction(); + scatter = vector_scale(direction, spread.scatter * random_unit()); + } + aim = vector_add(aim, vector_add(scatter, vector_scale(target->velocity, spread.lead))); + } + + Room& room = *g_game->room; + aim = room.GetClampedPositionImpl(aim, HOLY_EYE_WALL_MARGIN, HOLY_EYE_WALL_MARGIN, HOLY_EYE_WALL_MARGIN, + HOLY_EYE_WALL_MARGIN); + if (npc.controllerID != -1) aim = npc.GetAimTargetPosition(); + room.SetGridPath(room.GetGridIndex(aim), GRID_PATH_FREED); + + Entity* light = g_game->Spawn({.position = aim, + .spawner = &npc, + .subType = HOLY_LIGHT_SUBTYPE, + .type = ENTITY_EFFECT, + .variant = EFFECT_CRACK_THE_SKY, + .seed = Random()}); + light->SetSize(HOLY_LIGHT_SIZE, vector_make(-1, -1), -1); + light->SetCollisionDamage(HOLY_LIGHT_DAMAGE); + light->Update(); + npc.i1++; +} + +// The Holy Eye waits out its cooldown, then calls its light on each Shoot of its attack. +static void holy_eye_update(Entity_NPC& npc, int cell) +{ + if (npc.state == NPC_STATE_INIT) + { + npc.targetPosition = npc.pos; + npc.state = NPC_STATE_IDLE; + npc.sprite.Play("Idle"); + eye_cell_clear(npc, cell); + npc.projectileCooldown = npc.controllerID == -1 ? (int)(Random() % HOLY_EYE_FIRST_SPREAD) + HOLY_EYE_FIRST_DELAY + : HOLY_EYE_CONTROL_FIRST_DELAY; + npc.sprite.GetLayer(1)->bitflags |= 1; + npc.sprite.GetLayer(2)->bitflags |= 1; + return; + } + + npc.SpawnControlTarget(0, -1); + if (npc.state == NPC_STATE_IDLE) + { + npc.projectileCooldown -= npc_ticks_get(npc); + bool isReady = npc.projectileCooldown <= 0 && !eye_is_dazed(npc) && + (npc.controllerID == -1 || (npc.IsControllerActionPressed(CONTROLLER_ACTION_SHOOT) && + !vector_is_zero(npc.GetAimTargetPosition()))); + if (isReady) + { + npc.sprite.Play("Attack"); + npc.state = EYE_SHOOTING; + npc.i1 = 0; + } + } + else if (npc.state == EYE_SHOOTING) + { + if (npc.sprite.animState.animData && npc.sprite.IsEventTriggered("Shoot")) holy_light_call(npc); + if (npc_anim_is_done(npc)) + { + npc.sprite.Play("Idle"); + npc.state = NPC_STATE_IDLE; + npc.projectileCooldown = + npc.controllerID == -1 ? (int)(Random() % HOLY_EYE_SPREAD) + HOLY_EYE_DELAY : HOLY_EYE_DELAY; + } + } + + if (npc.pendingDamage > 0) npc.projectileCooldown += (int)(npc.pendingDamage * -HOLY_EYE_HURT_HASTE); + eye_hold(npc, cell); +} + +// 00522ef0 NpcAI::ENTITY_EYE: the eyes sit on their cell, turning their pupils toward their target and firing beams, +// or calling down light for the Holy Eye. +void npc_eye_update(Entity_NPC& npc) +{ + int cell = eye_cell_get(npc.pos); + if (npc.variant == HOLY_EYE) return holy_eye_update(npc, cell); + + if (npc.state == NPC_STATE_INIT) + { + npc.targetPosition = npc.pos; + npc.state = NPC_STATE_IDLE; + npc.v1.x = 0; + if (npc.variant == 0) npc_anim_restart(npc.sprite, "Eye Open"); + else if (npc.sprite.SetAnimation("Rotate", SWITCH_KEEP_FRAME) && npc.sprite.animState.animData) + { + npc.sprite.animState.SetFrameFloat(0); + npc.sprite.animState.isPlaying = false; + } + npc.renderZOffset = EYE_RENDER_Z; + return eye_cell_clear(npc, cell); + } + + eye_hold(npc, cell); + if (npc.state == NPC_STATE_MOVE) + { + eye_turn(npc); + eye_pupil_place(npc); + } + else if (npc.state == EYE_SHOOTING) eye_shoot(npc); + else if (npc_anim_is_done(npc)) + { + npc.state = NPC_STATE_MOVE; + if (npc.variant == 0) npc.sprite.Play("Eye Opened"); + } + bloodshot_deform(npc); +} diff --git a/src/npc_fireplace.cpp b/src/npc_fireplace.cpp index 9aa74d7..3f4a86d 100644 --- a/src/npc_fireplace.cpp +++ b/src/npc_fireplace.cpp @@ -81,7 +81,6 @@ constexpr float RELIGHT_OFFSET = 0.35f; constexpr float RELIGHT_BLUE = 0.5f; // The sounds of a fire: lit again, and put out. -constexpr int SOUND_CANDLE_LIGHT = 471; constexpr int SOUND_STEAM_HALFSEC = 261; constexpr float PUT_OUT_VOLUME = 0.85f; diff --git a/src/npc_fred.cpp b/src/npc_fred.cpp new file mode 100644 index 0000000..dcb37b8 --- /dev/null +++ b/src/npc_fred.cpp @@ -0,0 +1,253 @@ +#include "npc_depths.h" +#include "boss_ai.h" +#include "entity_config.h" +#include "entity_player.h" +#include "npc_caves.h" +#include "room_grid.h" + +// Fred burrows about the Womb: it surfaces where it lands, now and then spits a heavy shot, and hops a little nearer +// its target, or anywhere well away from the players once under control. +constexpr int FRED_SPIT = NPC_STATE_ATTACK; +constexpr int FRED_SURFACING = NPC_STATE_SPECIAL; +constexpr float FRED_FRICTION = 0.65f; + +// Surfaced, it spits 1 time in 30 (under control, with its cooldown over and a target in reach) at a target within +// 200, then waits 60 frames. It hops 1 time in 20, 100 toward its target. +constexpr uint32_t FRED_SPIT_ODDS = 30; +constexpr uint32_t FRED_HOP_ODDS = 20; +constexpr float FRED_CONTROL_RANGE = 1000; +constexpr int FRED_CONTROL_RANGE_FRAMES = 7; +constexpr float FRED_SPIT_RANGE = 200; +constexpr int FRED_SPIT_COOLDOWN = 60; +constexpr float FRED_HOP = 100; +constexpr float FRED_DEADZONE = 0.1f; + +// The spit: one heavy, explosive shot lobbed high at 10, slowed to 0.55. +constexpr float FRED_SPIT_VOLUME = 0.7f; +constexpr float FRED_SPIT_SPEED = 10; +constexpr float FRED_SPIT_ACCEL = 0.3f; +constexpr float FRED_SPIT_SCALE = 1.6f; +constexpr float FRED_SPIT_FALL_SCALE = 0.7f; +constexpr float FRED_SPIT_LIFT = 13; +constexpr float FRED_SPIT_SLOW = 0.55f; + +// Burrowing, it eases toward its spot (1.07 times faster a frame, from 0.005) and surfaces with a cross of shots at 7. +// Its next spot is a random free cell 130 to 1000 from the nearest player, 20 in from the walls. Under control it +// heads for its aim, which must lie 80 from the players. +constexpr float FRED_EASE_GROWTH = 1.07f; +constexpr float FRED_EASE_STEP = 0.005f; +constexpr float FRED_LAND_SHOT_SPEED = 7; +constexpr float FRED_SPOT_MARGIN = 20; +constexpr float FRED_SPOT_NEAR_SQUARED = 16900; +constexpr float FRED_SPOT_FAR_SQUARED = 1e6f; +constexpr int FRED_SPOT_PATH_LIMIT = 500; +constexpr float FRED_CELL = 40; +constexpr float FRED_CELL_ORIGIN_Y = 120; +constexpr float FRED_CONTROL_SEARCH = 40; +constexpr float FRED_CONTROL_TRAVEL = 3; +constexpr float FRED_CONTROL_CLEARANCE = 80; +constexpr int FRED_CONTROL_TARGET_MODE = 2; + +static bool fred_is_calm(Entity_NPC& npc) +{ + return npc.HasEntityFlags(FLAG_DELIRIUM_FORM) && room_is_clear(); +} + +static bool fred_is_dazed(Entity_NPC& npc) +{ + return npc.HasEntityFlags(FLAG_CONFUSION | FLAG_FEAR | FLAG_SHRINK); +} + +// Surfaced: it may spit at a target within reach, and may hop off toward its target (or its controller's push). +// Whether it hopped. +static bool fred_surfaced(Entity_NPC& npc, Vector away) +{ + float distance = vector_length(away); + if (!fred_is_calm(npc)) + { + bool isSpitting = npc.controllerID == -1 + ? Random() % FRED_SPIT_ODDS == 0 + : npc.projectileCooldown < 1 && + npc.IsTargetInAttackRange(FRED_CONTROL_RANGE, FRED_CONTROL_RANGE_FRAMES, false); + if (isSpitting && !fred_is_dazed(npc)) + { + if (npc.controllerID != -1) + { + npc.UpdateControllerMovement(true); + distance = vector_length(vector_scale(npc.controllerMovement, FRED_HOP)); + } + if (distance < FRED_SPIT_RANGE) + { + npc.sprite.Play("Attack", npc.controllerID != -1 ? PLAY_FORCED : PLAY_UNFORCED); + npc.state = FRED_SPIT; + npc.projectileCooldown = FRED_SPIT_COOLDOWN; + } + } + } + + bool isHopping = npc.controllerID == -1 ? Random() % FRED_HOP_ODDS == 0 + : !vector_is_zero(npc.GetControllerInput(FRED_DEADZONE)); + if (!isHopping) return false; + + if (npc.controllerID == -1) + npc.targetPosition = room_free_pickup_position_find({.position = vector_sub(npc.pos, vector_scale(away, FRED_HOP / distance))}); + else npc.targetPosition = vector_add(npc.pos, vector_scale(npc.GetControllerInput(FRED_DEADZONE), FRED_HOP)); + npc.sprite.Play(npc.pos.y <= npc.targetPosition.y ? "JumpDownHead" : "JumpUpHead"); + npc.v1.x = 0; + npc.state = NPC_STATE_JUMP; + return true; +} + +// The spit: on Shoot one heavy shot lobbed at its target (or where its controller pushes). +static void fred_spit(Entity_NPC& npc) +{ + npc.UpdateControllerMovement(false); + if (!npc.sprite.animState.animData || !npc.sprite.IsEventTriggered("Shoot")) return; + + Vector aim = npc.GetPlayerTarget()->pos; + if (npc.controllerID != -1 && !vector_is_zero(npc.controllerMovement)) + aim = vector_add(npc.pos, vector_scale(npc.controllerMovement, FRED_HOP)); + npc.PlaySound(SOUND_HEARTOUT, FRED_SPIT_VOLUME, 2, false, 1); + + ProjectileParams params; + Entity_Projectile* shot = npc.FireBossProjectiles(1, aim, FRED_SPIT_SPEED, params); + shot->projectileFlags |= PROJECTILE_EXPLODE; + shot->fallingAccel -= FRED_SPIT_ACCEL; + shot->scale = FRED_SPIT_SCALE; + shot->fallingSpeed = shot->fallingSpeed * FRED_SPIT_FALL_SCALE - FRED_SPIT_LIFT; + shot->velocity = vector_scale(shot->velocity, FRED_SPIT_SLOW); +} + +// Its next spot once it lands: a random cell well away from the players, or its controller's aim. +static void fred_spot_pick(Entity_NPC& npc) +{ + Room& room = *g_game->room; + if (npc.controllerID == -1) + { + Vector spot = room.GetRandomPosition(FRED_SPOT_MARGIN); + float distance = vector_length_squared(vector_sub(spot, game_nearest_player(spot)->pos)); + if (distance <= FRED_SPOT_NEAR_SQUARED || distance >= FRED_SPOT_FAR_SQUARED) return; + + int cell = room.GetGridIndex(spot); + if (cell >= 0 && cell < ROOM_GRID_CELLS && room.gridPaths[cell] >= FRED_SPOT_PATH_LIMIT) return; + npc.targetPosition = vector_make((float)(cell % room.gridWidth) * FRED_CELL + FRED_CELL, + (float)(cell / room.gridWidth) * FRED_CELL + FRED_CELL_ORIGIN_Y); + return; + } + + npc.SpawnControlTarget(FRED_CONTROL_TARGET_MODE, -1); + npc.pathfinder.FindGridPath(g_vectorZero, FRED_CONTROL_TRAVEL, 0, DIRECT_PATH_FAR); + Vector aim = npc.GetAimTargetPosition(); + if (room_grid_collision_at(aim) != 0) + aim = room_free_pickup_position_find({.position = aim, .step = FRED_CONTROL_SEARCH, .isAvoidActiveEntities = true}); + if (!npc.IsPlayerInRadius(aim, FRED_CONTROL_CLEARANCE)) npc.targetPosition = aim; +} + +// Burrowing: once it jumped it can be hit, sinks on Land (with a cross of shots on Shoot), picks its next spot and +// eases toward it. +static void fred_burrow(Entity_NPC& npc) +{ + ANM2& sprite = npc.sprite; + if (!sprite.animState.animData || !sprite.WasEventTriggered("Jump")) return; + + npc.entityCollisionClass = ENTCOLL_ALL; + npc.shadowSize = npc.config->shadowSize; + if (sprite.IsEventTriggered("Land")) + { + npc.UpdateDirtColor(true); + npc.shadowSize = 0; + } + if (sprite.animState.animData && sprite.WasEventTriggered("Land")) + { + if (sprite.IsEventTriggered("Shoot") && !fred_is_calm(npc)) + { + npc.PlaySound(SOUND_MEAT_JUMPS, 1, 2, false, 1); + if (!fred_is_dazed(npc)) + { + npc.PlaySound(SOUND_MEATHEADSHOOT, 1, 2, false, 1); + ProjectileParams params; + npc.FireProjectiles(npc.pos, vector_make(FRED_LAND_SHOT_SPEED, 0), PROJECTILES_PLUS, params); + } + } + return fred_spot_pick(npc); + } + if (npc.controllerID != -1) return npc.pathfinder.FindGridPath(g_vectorZero, 1, 0, DIRECT_PATH_FAR); + + npc.v1.x = std::min(npc.v1.x * FRED_EASE_GROWTH + FRED_EASE_STEP, 1.0f); + npc.velocity = vector_scale(vector_sub(npc.targetPosition, npc.pos), npc.v1.x); +} + +// The surfaced states end here: underground and untouchable at its spot until it jumps, else holding it. +static void fred_hold(Entity_NPC& npc) +{ + bool isUnder = (npc.state == NPC_STATE_JUMP && npc.sprite.animState.animData && npc.sprite.WasEventTriggered("Land")) || + (npc.state == FRED_SURFACING && + (!npc.sprite.animState.animData || !npc.sprite.WasEventTriggered("Jump"))); + if (isUnder) + { + npc.entityCollisionClass = ENTCOLL_NONE; + npc.pos = npc.targetPosition; + return; + } + npc.entityCollisionClass = ENTCOLL_ALL; + npc.velocity = vector_sub(npc.targetPosition, npc.pos); +} + +// 00524a10 NpcAI::ENTITY_FRED: Fred surfaces, spits heavy shots, hops toward its target and burrows to a far spot, +// shrugging off explosions other enemies set off. +void npc_fred_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_INIT) + { + npc.targetPosition = npc.pos; + npc.state = FRED_SURFACING; + npc_anim_restart(npc.sprite, "Appear"); + npc.UpdateDirtColor(true); + npc.shadowSize = 0; + return; + } + + if (npc.pendingDamage > 0) + for (DamageEvent& event : npc.damageEvents) + { + bool isPlayers = event.source.IsFriendly() || event.source.type == ENTITY_PLAYER || + event.source.spawnerType == ENTITY_PLAYER || event.source.spawnerType == ENTITY_FAMILIAR; + if (event.damageFlags & DAMAGE_EXPLOSION && !isPlayers && !(event.damageFlags & DAMAGE_TNT)) + event.damage = 0; + } + npc.friction *= FRED_FRICTION; + + int previous = npc.state; + if (npc_anim_is_done(npc)) + { + npc.state = NPC_STATE_IDLE; + if (previous == NPC_STATE_JUMP) + { + npc.state = FRED_SURFACING; + npc.sprite.Play("DigUp"); + npc.UpdateDirtColor(true); + } + } + + Vector away = vector_sub(npc.pos, npc.CalcTargetPosition(0)); + if (npc.projectileCooldown > 0) npc.projectileCooldown -= npc_ticks_get(npc); + switch (npc.state) + { + case NPC_STATE_IDLE: + if (!fred_surfaced(npc, away)) fred_hold(npc); + break; + case NPC_STATE_JUMP: + fred_burrow(npc); + break; + case FRED_SURFACING: + if (npc.sprite.animState.animData && npc.sprite.IsEventTriggered("Jump")) + npc.PlaySound(SOUND_MEAT_JUMPS, 1, 2, false, 1); + fred_hold(npc); + break; + case FRED_SPIT: + fred_spit(npc); + fred_hold(npc); + break; + } + npc.UpdateDirtColor(false); +} diff --git a/src/npc_hardy.cpp b/src/npc_hardy.cpp new file mode 100644 index 0000000..a0502d5 --- /dev/null +++ b/src/npc_hardy.cpp @@ -0,0 +1,272 @@ +#include "npc_alt.h" +#include "boss_ai.h" +#include "entity_player.h" +#include "npc_fireplace.h" +#include "room_grid.h" + +// The Hardy, its armor (subtype) breaking in steps: it rests (60 frames after a crash) until, one time in 5 every 5th +// frame, it winds up and slides at 20 toward its prey (a frightened or shrunk one away, a confused one anywhere). +// It sheds dust as it slides and stops below a speed of 1, braking below 9, after 30 frames once it hit something. +// Explosions and crushing hurt it two and a half times as much. +constexpr float HARDY_FRICTION = 0.95f; +constexpr float HARDY_REST_FRICTION = 0.5f; +constexpr float HARDY_CRASH_FRICTION = 0.6f; +constexpr float HARDY_BRAKE_FRICTION = 0.8f; +constexpr ColorMod HARDY_SPLAT_COLOR = {{0, 0, 0, 1}, {0, 0, 0, 0}, {30 / 255.0f, 30 / 255.0f, 30 / 255.0f}}; +constexpr uint32_t HARDY_START_ODDS = 5; +constexpr int HARDY_START_FRAMES = 5; +constexpr int HARDY_REST_FRAMES = 60; +constexpr float HARDY_SLIDE_SPEED = 20; +constexpr float HARDY_PUSH = 0.7f; +constexpr int HARDY_SLIDE_MIN_FRAMES = 30; +constexpr float HARDY_STOP_SPEED = 1; +constexpr float HARDY_BRAKE_SPEED = 9; +constexpr int HARDY_SLIDE_SOUND_DELAY = 2; +constexpr float HARDY_SLIDE_PITCH = 1.1f; +constexpr int HARDY_BUMPS_BEFORE_BRAKING = 4; +constexpr float HARDY_WEAKNESS = 2.5f; +constexpr uint64_t HARDY_WEAK_TO = DAMAGE_EXPLOSION | DAMAGE_CRUSH; + +// Its crash into a wall or solid grid head on: a shake, the grid entity broken, players within 90 thrown back, and its +// armor cracking: a ring of 8 rocks, then the ring and 6 lobbed at its prey, then its death in 8 bigger bursting rocks +// and 2 or 3 rock spiders thrown off the wall within 60 degrees. +constexpr float HARDY_HEAD_ON = 0.5f; +constexpr int HARDY_CRASH_DELAY = 30; +constexpr int HARDY_CRASH_SHAKE = 12; +constexpr float HARDY_PUSH_RADIUS = 90; +constexpr float HARDY_PUSH_SPEED = 3; +constexpr float HARDY_PUSH_FORCE = 6; +constexpr float HARDY_RING_SPEED = 10; +constexpr int HARDY_LOBBED_ROCKS = 6; +constexpr int HARDY_DEATH_ROCKS = 8; +constexpr float HARDY_DEATH_ROCK_SCALE = 1.2f; +constexpr float HARDY_SPIDER_SPREAD = 120; +constexpr float HARDY_SPIDER_REACH = 20; +constexpr float HARDY_SPIDER_HEIGHT = -10; + +// Its slide's dust: in the Hardy's stone color, within its size, drifting 1 to 3, one time in 2. +constexpr ColorMod HARDY_DUST_COLOR = {{140 / 255.0f, 123 / 255.0f, 123 / 255.0f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr int HARDY_DUST_PRIORITY = 255; + +// Its armor's steps, and what it leaves dying: a Dip of twice the health. +enum HardyArmor +{ + HARDY_ARMOR_WHOLE, + HARDY_ARMOR_CRACKED, + HARDY_ARMOR_BROKEN +}; + +// A thrown rock spider's hop lifts it about 4, and one thrown from higher than 50 passes over everything. +constexpr float ROCK_SPIDER_THROW_LIFT = 4; +constexpr float ROCK_SPIDER_HIGH_THROW = -50; + +// Its animation for its armor: name1 to name3. +static void hardy_play(Entity_NPC& npc, std::string_view name) +{ + npc.sprite.Play(std::string(name) + std::to_string(npc.subtype + 1)); +} + +// 004f9920 (Entity_NPC::ThrowRockSpider) Throws a rock spider (a coal spider, a fireplace, for the coal kind) at a +// velocity from a height, landing in its jump, charmed with a charmed spawner. Thrown high it passes over everything. +Entity_NPC* rock_spider_throw(const Vector& position, const Vector& velocity, Entity* spawner, RockSpiderKind kind, + float height) +{ + int type = kind == SPIDER_THROW_COAL ? ENTITY_FIREPLACE : ENTITY_ROCK_SPIDER; + int variant = kind == SPIDER_THROW_COAL ? (int)FIRE_COAL : (int)kind; + auto* spider = static_cast( + g_game->Spawn({.position = position, .spawner = spawner, .type = type, .variant = variant, .seed = Random()})); + spider->ClearEntityFlags(FLAG_APPEAR); + if (spawner && spawner->HasEntityFlags(FLAG_CHARM)) spider->AddCharmed({}, -1, false, false); + spider->Update(); + spider->posOffset = vector_make(0, height); + spider->v1.x = (random_unit() - 0.5f) * 2 - ROCK_SPIDER_THROW_LIFT; + spider->velocity = velocity; + spider->state = NPC_STATE_SPECIAL; + if (spider->posOffset.y < ROCK_SPIDER_HIGH_THROW) + { + spider->entityGridCollisionClass = GRIDCOLL_WALLS; + spider->entityCollisionClass = ENTCOLL_NONE; + } + return spider; +} + +// A puff of dust within its size, drifting off. +static void hardy_dust(Entity_NPC& npc) +{ + Vector direction = random_direction(); + float speed = random_unit() * 2 + 1; + float reach = random_unit(); + Vector position = vector_make(direction.x * reach * npc.size + npc.pos.x, direction.y * reach * npc.size + npc.pos.y); + uint32_t seed = Random(); + Entity* dust = g_game->Spawn({.position = position, + .velocity = vector_scale(direction, speed), + .type = ENTITY_EFFECT, + .variant = EFFECT_TOOTH_PARTICLE, + .seed = seed}); + dust->posOffset = npc.posOffset; + dust->SetColor(HARDY_DUST_COLOR, -1, HARDY_DUST_PRIORITY, false, true); + dust->Update(); +} + +// The crash: what it hit breaks, players are thrown back, and its armor cracks a step (or it dies). +static void hardy_crash(Entity_NPC& npc, Vector contact) +{ + npc_sound_play(SOUND_HELLBOSS_GROUNDPOUND, 1, HARDY_CRASH_DELAY, 1); + game_shake_screen(HARDY_CRASH_SHAKE); + if (GridEntity* grid = room_grid_entity_at(contact)) grid->Destroy(false, EntityRef(&npc)); + + Vector prey = npc.GetPlayerTarget()->pos; + if (!npc.IsFriendly()) + for (Entity_Player* player : g_game->playerManager.playerList) + { + Vector away = vector_sub(player->pos, npc.pos); + if (vector_length(away) >= HARDY_PUSH_RADIUS) continue; + player->TryThrow(EntityRef(&npc), vector_scale(vector_normalized(away), HARDY_PUSH_SPEED), HARDY_PUSH_FORCE); + } + + ProjectileParams params; + params.variant = PROJECTILE_ROCK; + if (npc.subtype == HARDY_ARMOR_WHOLE || npc.subtype == HARDY_ARMOR_CRACKED) + { + npc.subtype++; + npc.FireProjectiles(npc.pos, vector_make(HARDY_RING_SPEED, 0), PROJECTILES_EIGHT, params); + if (npc.subtype == HARDY_ARMOR_BROKEN) npc.FireBossProjectiles(HARDY_LOBBED_ROCKS, prey, 0, params); + } + else + { + npc.Kill(EntityRef()); + params.scale *= HARDY_DEATH_ROCK_SCALE; + params.bulletFlags = PROJECTILE_BURST; + npc.FireBossProjectiles(HARDY_DEATH_ROCKS, prey, 0, params); + for (int spiders = (int)(Random() & 1) + 2; spiders > 0; spiders--) + { + Vector back = vector_make(-npc.gridCollisionNormal.x, -npc.gridCollisionNormal.y); + float turn = (random_unit() - 0.5f) * HARDY_SPIDER_SPREAD * DEGREES_TO_RADIANS; + float cosine = std::cos(turn); + float sine = std::sin(turn); + Vector direction = vector_make(cosine * back.x - sine * back.y, cosine * back.y + sine * back.x); + Vector position = vector_add(vector_scale(direction, HARDY_SPIDER_REACH), npc.pos); + float speed = random_unit() * 2 + 1; + rock_spider_throw(position, vector_scale(direction, speed), &npc, SPIDER_THROW_SMALL, HARDY_SPIDER_HEIGHT); + } + } + npc.state = NPC_STATE_SPECIAL; +} + +// Resting until it starts a slide: a wind-up toward its prey, or a slide away from it or anywhere. +static void hardy_rest(Entity_NPC& npc) +{ + hardy_play(npc, "Idle"); + if (npc.stateFrame > 0) npc.stateFrame--; + bool isStarting = Random() % HARDY_START_ODDS == 0 && npc.IsFrame(HARDY_START_FRAMES, (int)npc.index); + if (isStarting && npc.stateFrame < 1) + { + npc.i2 = 0; + if (npc.HasEntityFlags(FLAG_FEAR | FLAG_SHRINK) || npc.HasEntityFlags(FLAG_CONFUSION)) + { + npc.i1 = 0; + npc.state = NPC_STATE_JUMP; + hardy_play(npc, "Slide"); + npc.velocity = npc.HasEntityFlags(FLAG_FEAR | FLAG_SHRINK) + ? vector_sub(npc.CalcTargetPosition(1), npc.pos) + : random_direction(); + } + else npc.state = NPC_STATE_ATTACK; + } + npc.friction *= HARDY_REST_FRICTION; +} + +// Sliding: pushed along its way until it has hit something for 30 frames, crashing head on into walls and rocks. +static void hardy_slide(Entity_NPC& npc) +{ + if (npc_anim_is_done(npc)) hardy_play(npc, "Slide"); + npc.i1++; + if (npc.i2 < 1 || npc.i1 < HARDY_SLIDE_MIN_FRAMES) + { + Vector direction = vector_normalized(npc.velocity); + if (npc.friction != 0) + { + npc.velocity.y = npc.speedMultiplier * direction.y * HARDY_PUSH / npc.friction + npc.velocity.y; + npc.velocity.x = npc.speedMultiplier * direction.x * HARDY_PUSH / npc.friction + npc.velocity.x; + } + } + else + { + float speed = vector_length(npc.velocity); + if (speed < HARDY_STOP_SPEED) npc.state = NPC_STATE_IDLE; + else if (speed < HARDY_BRAKE_SPEED) npc.friction *= HARDY_BRAKE_FRICTION; + } + if ((Random() & 1) == 0) hardy_dust(npc); + + if (npc.isCollidesWithGrid) + { + Vector contact = vector_make(npc.gridCollisionNormal.x * npc.size + npc.gridCollisionVelocity.x + npc.pos.x, + npc.gridCollisionVelocity.y + npc.pos.y + npc.gridCollisionNormal.y * npc.size); + uint32_t collision = room_grid_collision_at(contact); + bool isHeadOn = vector_dot(npc.gridCollisionNormal, vector_normalized(npc.gridCollisionVelocity)) > HARDY_HEAD_ON; + if (npc.state != NPC_STATE_JUMP && isHeadOn && (collision == COLLISION_SOLID || collision == COLLISION_WALL)) + hardy_crash(npc, contact); + npc.i2++; + } + if (npc.i2 > HARDY_BUMPS_BEFORE_BRAKING) npc.friction *= HARDY_CRASH_FRICTION; +} + +// 00500f70 The Hardy's AI: it rests and slides at its prey, crashing into walls and rocks until its armor breaks. +void npc_hardy_update(Entity_NPC& npc) +{ + npc.friction *= HARDY_FRICTION; + switch (npc.state) + { + case NPC_STATE_INIT: + npc.stateFrame = 0; + npc.state = NPC_STATE_IDLE; + npc.splatColor = HARDY_SPLAT_COLOR; + break; + case NPC_STATE_IDLE: hardy_rest(npc); break; + case NPC_STATE_MOVE: + case NPC_STATE_JUMP: hardy_slide(npc); break; + case NPC_STATE_ATTACK: + { + hardy_play(npc, "Attack"); + AnimationState& animation = npc.sprite.animState; + if (!animation.animData || !animation.IsEventTriggered("Slide")) break; + + Vector direction = vector_normalized(vector_sub(npc.GetPlayerTarget()->pos, npc.pos)); + if (npc.friction != 0) + { + npc.velocity.y = npc.speedMultiplier * direction.y * HARDY_SLIDE_SPEED / npc.friction + npc.velocity.y; + npc.velocity.x = npc.speedMultiplier * direction.x * HARDY_SLIDE_SPEED / npc.friction + npc.velocity.x; + } + npc.PlaySound(SOUND_MONSTER_ROAR_0, 1, HARDY_SLIDE_SOUND_DELAY, false, HARDY_SLIDE_PITCH); + npc.i1 = 0; + npc.state = NPC_STATE_MOVE; + break; + } + case NPC_STATE_SPECIAL: + hardy_play(npc, "Hit"); + npc.friction *= HARDY_CRASH_FRICTION; + if (!npc_anim_is_done(npc)) break; + + npc.stateFrame = HARDY_REST_FRAMES; + npc.state = NPC_STATE_IDLE; + break; + default: break; + } + + for (DamageEvent& event : npc.damageEvents) + { + if (!(event.damageFlags & HARDY_WEAK_TO)) continue; + + npc.pendingDamage -= event.damage; + float damage = event.damage; + event.damage = damage * HARDY_WEAKNESS; + npc.pendingDamage = damage * HARDY_WEAKNESS + npc.pendingDamage; + } + if (npc.isDead) + { + Entity* dip = g_game->Spawn({.position = npc.pos, .type = ENTITY_DIP, .seed = Random()}); + dip->maxHitPoints += dip->maxHitPoints; + dip->health = dip->maxHitPoints; + } + if (npc.state != NPC_STATE_SPECIAL) npc.sprite.isFlipX = npc.velocity.x < 0; +} diff --git a/src/npc_hopper.cpp b/src/npc_hopper.cpp index 0e237d5..50fbe88 100644 --- a/src/npc_hopper.cpp +++ b/src/npc_hopper.cpp @@ -6,7 +6,6 @@ // The hoppers this AI runs: the Hopper (with the Trite, Eggy and the tainted hopper as its variants), the Leaper, // the flaming hopper, the Keeper, Rag Man's Ragling, Ministro and Pon. -constexpr int ENTITY_KEEPER = 86; constexpr int ENTITY_RAGLING = 246; constexpr int ENTITY_MINISTRO = 305; constexpr int ENTITY_PON = 840; diff --git a/src/npc_lump.cpp b/src/npc_lump.cpp index 78e303b..1ed77cc 100644 --- a/src/npc_lump.cpp +++ b/src/npc_lump.cpp @@ -2,6 +2,7 @@ #include "boss_ai.h" #include "entity_combat.h" #include "entity_player.h" +#include "room_grid.h" #include "sfx_manager.h" // The Lump shakes in place, spits 3 shots at 7 at a prey within 260 (63 frames apart), and after 36 frames out hides @@ -41,14 +42,6 @@ constexpr int LUMP_SURFACE_PATH_MAX = 900; constexpr float LUMP_SURFACE_CLEARANCE = 60; constexpr float LUMP_FLIP_SPEED = 1; -// 00812de0 Room::GetClampedGridIndex: the cell under a position, pulled onto the grid when off it. -static int room_clamped_grid_index_get(Room& room, Vector position) -{ - int column = std::max((int)((position.x - GRID_ORIGIN_X) / GRID_CELL_SIZE + 0.5f), 0); - int row = std::max((int)((position.y - GRID_ORIGIN_Y) / GRID_CELL_SIZE + 0.5f), 0); - return std::min(row, room.gridHeight - 1) * room.gridWidth + std::min(column, room.gridWidth - 1); -} - // Starting to spit at its prey (or where its controller aims). static void lump_spit_start(Entity_NPC& npc) { diff --git a/src/npc_maggot.cpp b/src/npc_maggot.cpp index 09e1fd0..c8305c9 100644 --- a/src/npc_maggot.cpp +++ b/src/npc_maggot.cpp @@ -448,8 +448,9 @@ static void maggot_charge_try(Entity_NPC& npc, MaggotFrame& frame) { if (std::abs(delta.x) >= CHARGE_AXIS && std::abs(delta.y) >= CHARGE_AXIS) return; if (vector_length_squared(delta) >= CHARGE_RANGE_SQUARED && npc.type != ENTITY_LEECH) return; - if (npc.type == ENTITY_LEECH) reconstruction_missing("Room::CheckLine 007f0df0: the leech's mode 2 line"); - if (!room_check_line(cell, spot, LINE_MODE_GROUND, 0)) return; + bool isClear = npc.type == ENTITY_LEECH ? explosion_line_clear(cell, spot, false) + : room_check_line(cell, spot, LINE_MODE_GROUND, 0); + if (!isClear) return; } if (npc.type == ENTITY_LEECH) npc.PlaySound(SOUND_LEECH, 1, MAGGOT_CHARGE_SOUND_DELAY, false, 1); diff --git a/src/npc_meatball.cpp b/src/npc_meatball.cpp new file mode 100644 index 0000000..043a1d2 --- /dev/null +++ b/src/npc_meatball.cpp @@ -0,0 +1,206 @@ +#include "npc_depths.h" +#include "boss_ai.h" +#include "entity_effect.h" +#include "npc_caves.h" +#include "room_config.h" + +// The Meatball wanders, charges up and either spits a stream of shots or sprays a line of blood creep, and dies into +// a Host. +constexpr int MEATBALL_CHARGE = NPC_STATE_SPECIAL; +constexpr int MEATBALL_SPIT = NPC_STATE_ATTACK; +constexpr int MEATBALL_SPRAY = NPC_STATE_ATTACK2; +constexpr float MEATBALL_FRICTION = 0.8f; + +// It charges 1 time in 20 at a target within 300 in its line of fire, then rests 90 frames (60 under control, the +// bar showing them). Under control it sprays at an aim 10 or more away, else spits. +constexpr float MEATBALL_RANGE_SQUARED = 90000; +constexpr uint32_t MEATBALL_CHARGE_ODDS = 20; +constexpr int MEATBALL_COOLDOWN = 90; +constexpr int MEATBALL_CONTROL_COOLDOWN = 60; +constexpr float MEATBALL_BAR_FULL = 60; +constexpr float MEATBALL_CONTROL_RANGE = 1000; +constexpr int MEATBALL_CONTROL_RANGE_FRAMES = 7; +constexpr float MEATBALL_SPRAY_AIM_SQUARED = 100; + +// The spit: a shot at 10 every other frame between Shoot and Stop. +constexpr float MEATBALL_SPIT_INTERVAL = 2; +constexpr float MEATBALL_SPIT_SPEED = 10; + +// The spray: a creep puddle every frame, 25 further along its aim each, with blood flying off and a splat where the +// puddle lies in the room. +constexpr float MEATBALL_SPRAY_STEP = 25; +constexpr float MEATBALL_BLOOD_SPEED = 2; +constexpr float MEATBALL_BLOOD_LIFT = -16; +constexpr float MEATBALL_BLOOD_BACK = 5; +constexpr float MEATBALL_BLOOD_DEPTH = 10; +constexpr int MEATBALL_BLOOD_SUBTYPE = 2; +constexpr int MEATBALL_BLOOD_PRIORITY = 255; + +// It drips a splat every 7 frames, 0.4 to 0.9 wide. +constexpr int MEATBALL_DRIP_FRAMES = 7; +constexpr float MEATBALL_DRIP_SIZE = 0.4f; +constexpr float MEATBALL_DRIP_SPREAD = 0.5f; + +// Turns to face along a direction, unless it has none. +static void meatball_face(Entity_NPC& npc, Vector direction) +{ + if (!vector_is_zero(direction)) npc.sprite.isFlipX = direction.x < 0; +} + +// Wandering: with its cooldown over, it charges at a target in reach and in line (or on its controller's call). +static void meatball_wander(Entity_NPC& npc, Vector toTarget) +{ + if (npc.projectileCooldown > 0) npc.projectileCooldown -= npc_ticks_get(npc); + npc.pathfinder.MoveRandomly(STATUS_OBEYED); + npc.sprite.Play("Idle"); + if (npc.controllerID != -1) meatball_face(npc, npc.GetControllerInput(0)); + + if (npc.controllerID == -1) + { + if (vector_length_squared(toTarget) >= MEATBALL_RANGE_SQUARED) return; + if (!room_check_line(npc.pos, npc.GetPlayerTarget()->pos, LINE_MODE_PROJECTILE, LINE_CHECK_THRESHOLD) || + Random() % MEATBALL_CHARGE_ODDS != 0) + return; + } + else if (!npc.IsTargetInAttackRange(MEATBALL_CONTROL_RANGE, MEATBALL_CONTROL_RANGE_FRAMES, false) && + !npc.IsControllerActionPressed(CONTROLLER_ACTION_SHOOT)) + return; + if (npc.projectileCooldown >= 1) return; + + npc.state = MEATBALL_CHARGE; + npc.projectileCooldown = npc.controllerID == -1 ? MEATBALL_COOLDOWN : MEATBALL_CONTROL_COOLDOWN; + meatball_face(npc, npc.controllerID == -1 ? toTarget : npc.GetControllerMovementInput(0)); +} + +// Charging: once done it spits or sprays (by chance, or by its controller's aim) along its aim. +static void meatball_charge(Entity_NPC& npc, Vector toTarget) +{ + npc.SpawnControlTarget(0, -1); + npc.sprite.Play("Charge"); + if (!npc_anim_is_done(npc)) return; + + npc.stateFrame = 0; + npc.state = (int)(Random() & 1) | MEATBALL_SPIT; + Vector aim = toTarget; + if (npc.controllerID != -1) + { + aim = vector_sub(npc.GetAimTargetPosition(), npc.pos); + npc.state = vector_length_squared(aim) >= MEATBALL_SPRAY_AIM_SQUARED ? MEATBALL_SPRAY : MEATBALL_SPIT; + } + meatball_face(npc, aim); + npc.targetPosition = vector_normalized(aim); + npc.PlaySound(npc.state == MEATBALL_SPIT ? SOUND_BOSS_GURGLE_ROAR : SOUND_BOSS_LITE_GURGLE, 1, 2, false, 1); +} + +// Whether a point lies in the room: inside its L, or within its corners. +static bool meatball_is_in_room(const Vector& point) +{ + Room& room = *g_game->room; + int shape = room.GetRoomShape(); + if (shape >= ROOMSHAPE_LTL && shape <= ROOMSHAPE_LBR) + { + Vector clamped = room.GetClampedPositionImpl(point, 0, 0, 0, 0); + return clamped.x == point.x && clamped.y == point.y; + } + return point.x >= room.topLeftPos.x && point.x <= room.bottomRightPos.x && point.y >= room.topLeftPos.y && + point.y <= room.bottomRightPos.y; +} + +// One puddle of the spray: red creep, and in the room blood flying back off it and a splat. +static void meatball_puddle(Entity_NPC& npc) +{ + Vector point = vector_add(npc.pos, vector_scale(npc.targetPosition, (float)npc.stateFrame * MEATBALL_SPRAY_STEP)); + Entity* creep = g_game->Spawn({.position = point, + .spawner = &npc, + .type = ENTITY_EFFECT, + .variant = EFFECT_CREEP_RED, + .seed = Random()}); + creep->sprite.scale = vector_make(1, 1); + creep->Update(); + if (!meatball_is_in_room(point)) return; + + Vector velocity = vector_scale(npc.targetPosition, random_unit() * MEATBALL_BLOOD_SPEED); + float lift = random_unit() * MEATBALL_BLOOD_LIFT; + Entity* blood = g_game->Spawn({.position = vector_sub(point, vector_scale(npc.targetPosition, MEATBALL_BLOOD_BACK)), + .velocity = velocity, + .subType = MEATBALL_BLOOD_SUBTYPE, + .type = ENTITY_EFFECT, + .variant = EFFECT_BLOOD_EXPLOSION, + .seed = Random()}); + blood->SetColor(COLOR_DEFAULT, -1, MEATBALL_BLOOD_PRIORITY, false, true); + blood->sprite.offset = vector_make(0, lift); + blood->renderDepthOffset = MEATBALL_BLOOD_DEPTH; + blood->sprite.rotation = random_unit() * 360; + + Entity* splat = g_game->Spawn({.position = point, .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_SPLAT, .seed = Random()}); + splat->Update(); +} + +// The spit or the spray, back to wandering once its animation ends. +static void meatball_attack(Entity_NPC& npc) +{ + bool isSpit = npc.state == MEATBALL_SPIT; + npc.sprite.Play(isSpit ? "Shoot1" : "Shoot2"); + if (npc_anim_is_done(npc)) npc.state = NPC_STATE_MOVE; + + bool isFiring = npc.sprite.WasEventTriggered("Shoot") && !npc.sprite.WasEventTriggered("Stop"); + if (isSpit) + { + if (npc.GetIntervalTicks(MEATBALL_SPIT_INTERVAL, 0) == 0 || !isFiring) return; + ProjectileParams params; + npc.FireBossProjectiles(1, g_vectorZero, MEATBALL_SPIT_SPEED, params); + return; + } + if (!isFiring) return; + for (int tick = npc_ticks_get(npc); tick > 0; tick--) + { + meatball_puddle(npc); + npc.stateFrame++; + } +} + +// 00541ce0 NpcAI::ENTITY_MEATBALL: the Meatball wanders, charges, spits shots or sprays creep along its aim, drips +// splats, and turns into a Host when it dies. +void npc_meatball_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_INIT) + { + npc.state = NPC_STATE_MOVE; + return; + } + + Vector toTarget = vector_sub(npc.CalcTargetPosition(0), npc.pos); + npc.UpdateChargeBar(MEATBALL_BAR_FULL, 0, (float)npc.projectileCooldown, true); + switch (npc.state) + { + case NPC_STATE_MOVE: + meatball_wander(npc, toTarget); + break; + case MEATBALL_CHARGE: + meatball_charge(npc, toTarget); + break; + case MEATBALL_SPIT: + case MEATBALL_SPRAY: + meatball_attack(npc); + break; + } + + if (!npc.HasEntityFlags(FLAG_INTERPOLATION_UPDATE) && !g_game->IsPaused() && g_game->frameCount % MEATBALL_DRIP_FRAMES == 0) + npc.MakeSplat(random_unit() * MEATBALL_DRIP_SPREAD + MEATBALL_DRIP_SIZE); + if (npc.isDead) + { + int type = ENTITY_HOST; + int variant = 0; + Entity_NPC::Redirect(&type, &variant); + if (type != 0) + { + npc.Morph(type, variant, 0, -1); + npc.isDead = false; + npc.health = npc.maxHitPoints; + npc.stateFrame = 0; + npc.projectileCooldown = 0; + npc.state = NPC_STATE_IDLE; + } + } + npc.friction *= MEATBALL_FRICTION; +} diff --git a/src/npc_needle.cpp b/src/npc_needle.cpp index c5a535d..04c1b0c 100644 --- a/src/npc_needle.cpp +++ b/src/npc_needle.cpp @@ -136,8 +136,8 @@ static void needle_leap_update(Entity_NPC& npc) bool isTrailMoved = vector_length(vector_sub(npc.pos, npc.vectorDeque1.front())) > NEEDLE_TRAIL_STEP; if (isTrailMoved || npc.v1.y > NEEDLE_TRAIL_HIGH) { - npc.vectorDeque1.push_back(npc.pos); - npc.vectorDeque2.push_back(vector_make(0, npc.v1.y)); + npc.vectorDeque1.push_front(npc.pos); + npc.vectorDeque2.push_front(vector_make(0, npc.v1.y)); } while (npc.vectorDeque1.size() > NEEDLE_TRAIL_LENGTH) { diff --git a/src/npc_quake_grimace.cpp b/src/npc_quake_grimace.cpp new file mode 100644 index 0000000..d692771 --- /dev/null +++ b/src/npc_quake_grimace.cpp @@ -0,0 +1,104 @@ +#include "npc_alt.h" +#include "boss_ai.h" +#include "level.h" + +// The Quake Grimace: an invincible wall face held in its cell (walling the grid path off) that slams every 10 frames, +// sending a crackwave along the way it faces (its subtype: left, up, right, down). It closes its eyes once the room's +// pressure plates are pressed. +constexpr int QUAKE_GRIMACE_PATH_MARKER = 3999; +constexpr uint64_t QUAKE_GRIMACE_FLAGS = FLAG_NO_STATUS_EFFECTS | FLAG_HIDE_HP_BAR | FLAG_NO_PLAYER_CONTROL; +constexpr int QUAKE_GRIMACE_REST_FRAMES = 10; +constexpr float QUAKE_GRIMACE_CELL = 40; +constexpr float QUAKE_GRIMACE_ORIGIN_X = 40; +constexpr float QUAKE_GRIMACE_ORIGIN_Y = 120; +constexpr int QUAKE_GRIMACE_SLAM_DELAY = 2; +constexpr int QUAKE_GRIMACE_SHAKE = 16; +constexpr int CRACKWAVE_FROM_GRIMACE = 1; +constexpr std::array QUAKE_GRIMACE_FACINGS = {180, -90, 0, 90}; + +// Closes its eyes for good, at once when asked. +static void quake_grimace_close(Entity_NPC& npc) +{ + npc.state = NPC_STATE_SPECIAL; + npc.sprite.Play("CloseEyes"); +} + +// Takes its cell, its eyes already shut once the room's plates are pressed. +static void quake_grimace_init(Entity_NPC& npc, bool isDisarmed) +{ + Room& room = *g_game->room; + npc.AddEntityFlags(QUAKE_GRIMACE_FLAGS); + npc.isInvincible = true; + npc.state = NPC_STATE_IDLE; + npc.aiCallFlags = AI_CALL_PRE_UPDATE; + npc.stateFrame = QUAKE_GRIMACE_REST_FRAMES; + if (!npc.minecart) + { + int cell = room.GetGridIndex(npc.pos); + npc.pathfinder.UpdateGridIndex(); + npc.targetPosition = vector_make((float)(cell % room.gridWidth) * QUAKE_GRIMACE_CELL + QUAKE_GRIMACE_ORIGIN_X, + (float)(cell / room.gridWidth) * QUAKE_GRIMACE_CELL + QUAKE_GRIMACE_ORIGIN_Y); + } + if (!isDisarmed) return; + + quake_grimace_close(npc); + AnimationState& animation = npc.sprite.animState; + if (animation.animData) animation.AdvancePosition(animation.animData->length - 1); +} + +// Its slam: a shake and a crackwave crawling off the way it faces. +static void quake_grimace_slam(Entity_NPC& npc) +{ + npc_sound_play(SOUND_HELLBOSS_GROUNDPOUND, 1, QUAKE_GRIMACE_SLAM_DELAY, 1); + game_shake_screen(QUAKE_GRIMACE_SHAKE); + auto* wave = static_cast(g_game->Spawn({.position = npc.pos, + .spawner = &npc, + .subType = CRACKWAVE_FROM_GRIMACE, + .type = ENTITY_EFFECT, + .variant = EFFECT_CRACKWAVE, + .seed = Random()})); + wave->parent = &npc; + wave->rotation = QUAKE_GRIMACE_FACINGS[std::min((uint32_t)npc.subtype, (uint32_t)QUAKE_GRIMACE_FACINGS.size() - 1)]; +} + +// 004f8960 The Quake Grimace's AI: a wall face slamming crackwaves until the room's plates are pressed. +// Done slamming it keeps slamming, as the original never returns to its rest. +void npc_quake_grimace_update(Entity_NPC& npc) +{ + Game& game = *g_game; + if (npc.aiCallPhase == AI_PHASE_PRE_UPDATE) + { + if (!npc.minecart && !npc.isDead && npc.pathfinder.gridIndex >= 0) + game.room->SetGridPath(npc.pathfinder.gridIndex, QUAKE_GRIMACE_PATH_MARKER); + return; + } + + RoomDescriptor* room = game.GetRoomByIdx(game.currentRoomIdx, game.currentDimensionIdx); + bool isDisarmed = room->flags & ROOM_DESCRIPTOR_FLAG_PRESSURE_PLATES_TRIGGERED; + if ((npc.state == NPC_STATE_IDLE || npc.state == NPC_STATE_ATTACK) && isDisarmed) quake_grimace_close(npc); + + int ticks = npc_ticks_get(npc); + if (npc.state == NPC_STATE_INIT) + { + quake_grimace_init(npc, isDisarmed); + return; + } + if (npc.state == NPC_STATE_IDLE) + { + npc.sprite.Play("Idle"); + npc.stateFrame -= ticks; + if (npc.stateFrame <= 0) npc.state = NPC_STATE_ATTACK; + } + else if (npc.state == NPC_STATE_ATTACK) + { + npc.sprite.Play("Slam"); + AnimationState& animation = npc.sprite.animState; + if (animation.animData && animation.IsEventTriggered("Hit")) quake_grimace_slam(npc); + if (npc_anim_is_done(npc)) + { + npc.sprite.Play("Idle"); + npc.stateFrame = QUAKE_GRIMACE_REST_FRAMES; + } + } + if (!npc.minecart) npc.velocity = vector_sub(npc.targetPosition, npc.pos); +} diff --git a/src/npc_quakey.cpp b/src/npc_quakey.cpp new file mode 100644 index 0000000..7dfc409 --- /dev/null +++ b/src/npc_quakey.cpp @@ -0,0 +1,192 @@ +#include "npc_alt.h" +#include "boss_ai.h" +#include "entity_player.h" +#include "grid_entity_trap_door.h" + +// The Quakey walks its grid path at 0.3, rumbling one time in 3 while it sees its prey. Once its 120 frame cooldown +// is out it leaps at 12 toward its prey: one time in 15 within 120 of it, else one time in 120. Hornfel's Quakeys +// never leap. +constexpr float QUAKEY_WALK_THRESHOLD = 0.1f; +constexpr float QUAKEY_SPEED = 0.3f; +constexpr int QUAKEY_PATH_MARKER = 900; +constexpr float QUAKEY_FEAR_FRICTION = 0.8f; +constexpr int QUAKEY_COOLDOWN = 120; +constexpr float QUAKEY_NEAR = 120; +constexpr uint32_t QUAKEY_NEAR_ODDS = 15; +constexpr uint32_t QUAKEY_FAR_ODDS = 120; +constexpr float QUAKEY_CONTROLLED_RANGE = 1000; +constexpr int QUAKEY_RANGE_FRAMES = 7; +constexpr float QUAKEY_LEAP_SPEED = 12; +constexpr uint32_t QUAKEY_RUMBLE_ODDS = 3; +constexpr int QUAKEY_RUMBLE_DELAY = 60; +constexpr int QUAKEY_LEAP_DELAY = 10; +constexpr float QUAKEY_GLIDE_FRICTION = 0.9f; +constexpr float QUAKEY_LAND_FRICTION = 0.6f; +constexpr ColorMod QUAKEY_SPLAT_COLOR = {{1, 1, 1, 1}, {0.8f, 0.78f, 0.74f, 1}, {0, 0, 0}}; + +// Its landing: a ring of 8 rocks at 10, a shake and ripple, players within 150 thrown back, and (but Gideon's) 12 +// rock falls stepping 150 toward its prey, one every 2 frames. +constexpr int QUAKEY_STOMP_DELAY = 20; +constexpr int QUAKEY_SHAKE = 14; +constexpr float QUAKEY_WAVE_AMPLITUDE = 0.035f; +constexpr float QUAKEY_WAVE_SPEED = 0.03f; +constexpr int QUAKEY_WAVE_FRAMES = 10; +constexpr float QUAKEY_RING_SPEED = 10; +constexpr float QUAKEY_PUSH_RADIUS = 150; +constexpr float QUAKEY_PUSH_SPEED = 3; +constexpr float QUAKEY_PUSH_FORCE = 9; +constexpr int QUAKEY_FALL_INTERVAL = 2; +constexpr int QUAKEY_FALLS = 12; +constexpr float QUAKEY_FALL_REACH = 150; +constexpr uint64_t QUAKEY_FALL_FLAGS = FLAG_FRIENDLY | FLAG_CHARM; +constexpr uint64_t QUAKEY_FALL_HIGH_FLAGS = 1ull << 52; + +// A falling rock: within 80 of the fall's step (kept 20 off the walls), drifting up to 3, 400 above, falling 2 faster +// plus up to 10, scaled 0.8 to 1.2. +constexpr float ROCK_FALL_MARGIN = 20; +constexpr float ROCK_FALL_SPREAD = 80; +constexpr float ROCK_FALL_DRIFT = 3; +constexpr float ROCK_FALL_HEIGHT = 400; +constexpr float ROCK_FALL_ACCEL = 2; +constexpr float ROCK_FALL_SPEED = 10; +constexpr float ROCK_FALL_SCALE_MIN = 0.8f; +constexpr float ROCK_FALL_SCALE_RANGE = 0.4f; +constexpr float ROCK_FALL_ACCELERATION = 0.95f; + +// 004fd280 One step of the Quakey's rock fall: a rock dropping around the next point along its line. The timer's +// state holds the Quakey's champion color, and its first spare value the steps taken (the original reads the timer's +// own count). +static void quakey_rock_fall(Entity_Effect* timer) +{ + float reach = (float)timer->varData[0]++ / QUAKEY_FALLS * QUAKEY_FALL_REACH; + Vector step = vector_make(reach * timer->targetPosition.x + timer->pos.x, + reach * timer->targetPosition.y + timer->pos.y); + Vector center = g_game->room->GetClampedPositionImpl(step, ROCK_FALL_MARGIN, ROCK_FALL_MARGIN, ROCK_FALL_MARGIN, + ROCK_FALL_MARGIN); + Vector direction = random_direction(); + uint32_t seed = Random(); + Vector velocity = vector_scale(direction, random_unit() * ROCK_FALL_DRIFT); + float spread = random_unit() * ROCK_FALL_SPREAD; + + auto* rock = static_cast(g_game->Spawn({.position = vector_add(vector_scale(direction, spread), center), + .velocity = velocity, + .type = ENTITY_PROJECTILE, + .variant = PROJECTILE_ROCK, + .seed = seed})); + rock->scale = random_unit() * ROCK_FALL_SCALE_RANGE + ROCK_FALL_SCALE_MIN; + rock->height -= ROCK_FALL_HEIGHT; + rock->fallingAccel += ROCK_FALL_ACCEL; + float fall = random_unit() * ROCK_FALL_SPEED; + rock->spawnerType = ENTITY_QUAKEY; + rock->projectileFlags = PROJECTILE_ACCELERATE; + rock->acceleration = ROCK_FALL_ACCELERATION; + rock->fallingSpeed = fall + rock->fallingSpeed; + rock->apply_spawn_flags({nullptr, timer->flags, timer->scale, timer->state}); + rock->Update(); +} + +// The landing's stomp: rocks out, players pushed away, and a rock fall toward its prey. +static void quakey_stomp(Entity_NPC& npc) +{ + npc_sound_play(SOUND_HELLBOSS_GROUNDPOUND, 1, QUAKEY_STOMP_DELAY, 1); + game_shake_screen(QUAKEY_SHAKE); + shockwave_make(npc.pos, QUAKEY_WAVE_AMPLITUDE, QUAKEY_WAVE_SPEED, QUAKEY_WAVE_FRAMES); + ProjectileParams params; + params.variant = PROJECTILE_ROCK; + npc.FireProjectiles(npc.pos, vector_make(QUAKEY_RING_SPEED, 0), PROJECTILES_EIGHT, params); + + if (!npc.IsFriendly()) + for (Entity_Player* player : g_game->playerManager.playerList) + { + Vector away = vector_sub(player->pos, npc.pos); + if (vector_length(away) >= QUAKEY_PUSH_RADIUS) continue; + player->TryThrow(EntityRef(&npc), vector_scale(vector_normalized(away), QUAKEY_PUSH_SPEED), QUAKEY_PUSH_FORCE); + } + if (npc.spawnerType == ENTITY_GIDEON) return; + + npc.GetPlayerTarget(); + Entity_Effect* fall = Entity_Effect::CreateTimer(reinterpret_cast(&quakey_rock_fall), QUAKEY_FALL_INTERVAL, + QUAKEY_FALLS, false); + fall->pos = npc.pos; + fall->targetPosition = vector_normalized(vector_sub(npc.GetPlayerTarget()->pos, npc.pos)); + fall->parent = &npc; + fall->state = npc.isChampion ? npc.championColorIdx : -1; + fall->AddEntityFlags(npc.flags & (QUAKEY_FALL_FLAGS | QUAKEY_FALL_HIGH_FLAGS)); + fall->scale = npc.scale; +} + +// Walking: after its prey (away while afraid or shrunk), leaping once the cooldown is out. +static void quakey_walk(Entity_NPC& npc) +{ + npc.AnimWalkFrame("WalkHori", "WalkVert", QUAKEY_WALK_THRESHOLD); + if (npc.HasEntityFlags(FLAG_FEAR | FLAG_SHRINK) && npc.controllerID == -1) + { + npc.pathfinder.EvadeTarget(npc.GetPlayerTarget()->pos, STATUS_OBEYED); + npc.friction *= QUAKEY_FEAR_FRICTION; + if (npc.pathfinder.evadeMovementCountdown > 0) npc.friction *= QUAKEY_FEAR_FRICTION; + return; + } + + npc.pathfinder.FindGridPath(npc.CalcTargetPosition(0), QUAKEY_SPEED, QUAKEY_PATH_MARKER, DIRECT_PATH_FAR); + if (npc.spawnerType == ENTITY_HORNFEL) return; + + if (npc.projectileCooldown > 0) npc.projectileCooldown -= npc_ticks_get(npc); + Vector prey = npc.GetPlayerTarget()->pos; + if (npc.projectileCooldown >= 1) return; + + bool isLeaping = false; + if (npc.controllerID != -1) + isLeaping = npc.IsTargetInAttackRange(QUAKEY_CONTROLLED_RANGE, QUAKEY_RANGE_FRAMES, false) || + npc.IsControllerActionPressed(CONTROLLER_ACTION_SHOOT); + else + { + bool isNear = vector_length(vector_sub(npc.pos, prey)) < QUAKEY_NEAR && Random() % QUAKEY_NEAR_ODDS == 0; + isLeaping = isNear || Random() % QUAKEY_FAR_ODDS == 0; + } + if (!isLeaping) return; + + npc.sprite.Play("Jump"); + npc.state = NPC_STATE_ATTACK; + npc.targetPosition = vector_scale(vector_normalized(vector_sub(prey, npc.pos)), QUAKEY_LEAP_SPEED); + if (npc.controllerID != -1) + { + npc.targetPosition = vector_scale(npc.GetControllerMovementInput(0), QUAKEY_LEAP_SPEED); + if (vector_is_zero(npc.targetPosition)) + npc.targetPosition = vector_scale(npc.GetControllerInput(0), QUAKEY_LEAP_SPEED); + } + npc.projectileCooldown = QUAKEY_COOLDOWN; +} + +// 004fd540 The Quakey's AI: it walks after its prey and leaps at it, landing in a stomp that rings out rocks and +// drops more along a line toward its prey. +void npc_quakey_update(Entity_NPC& npc) +{ + npc.UpdateChargeBar(QUAKEY_COOLDOWN, 0, (float)npc.projectileCooldown, true); + if (npc.state == NPC_STATE_INIT) + { + npc.state = NPC_STATE_MOVE; + npc.sprite.Play("WalkVert"); + npc.splatColor = QUAKEY_SPLAT_COLOR; + } + else if (npc.state == NPC_STATE_MOVE) + { + quakey_walk(npc); + if (npc.pathfinder.hasDirectPath && Random() % QUAKEY_RUMBLE_ODDS == 0) + npc.PlaySound(SOUND_MONSTER_ROAR_1, 1, QUAKEY_RUMBLE_DELAY, false, 1); + } + else if (npc.state == NPC_STATE_ATTACK) + { + AnimationState& animation = npc.sprite.animState; + if (animation.animData && animation.IsEventTriggered("Jump")) + { + npc.PlaySound(SOUND_SCAMPER, 1, QUAKEY_LEAP_DELAY, false, 1); + npc.velocity = vector_add(vector_scale(npc.targetPosition, npc.speedMultiplier), npc.velocity); + npc.targetPosition = {}; + } + if (animation.animData && animation.IsEventTriggered("Shoot")) quakey_stomp(npc); + + if (animation.animData && animation.WasEventTriggered("Shoot")) npc.friction *= QUAKEY_LAND_FRICTION; + else npc.friction *= vector_is_zero(npc.targetPosition) ? QUAKEY_GLIDE_FRICTION : QUAKEY_LAND_FRICTION; + if (npc_anim_is_done(npc)) npc.state = NPC_STATE_MOVE; + } +} diff --git a/src/npc_sins.cpp b/src/npc_sins.cpp new file mode 100644 index 0000000..cc1bfee --- /dev/null +++ b/src/npc_sins.cpp @@ -0,0 +1,682 @@ +#include "boss_ai.h" +#include "entity_bomb.h" +#include "entity_laser.h" +#include "entity_slot.h" +#include "npc_caves.h" +#include "room_grid.h" +#include "entity_player.h" +#include +#include + +// The variants the sins share: the plain sin and its super version. Sloth's third variant is Ultra Pride. +constexpr int SIN_SUPER = 1; +constexpr int SLOTH_ULTRA_PRIDE = 2; + +// Where a sin is in its routine: walking, its two attacks, and Greed's summon. +constexpr int SIN_WALK = NPC_STATE_MOVE; +constexpr int SIN_ATTACK = NPC_STATE_ATTACK; +constexpr int SIN_ATTACK2 = NPC_STATE_ATTACK2; +constexpr int SIN_SUMMON = NPC_STATE_SUMMON; + +constexpr uint32_t SIN_ATTACK_ODDS = 50; +constexpr uint32_t SIN_DISTRACTED_ODDS = 10; +constexpr float SIN_FRICTION = 0.75f; +constexpr float SIN_WALK_SPEED = 1; +constexpr float SIN_WALK_THRESHOLD = 0.1f; +constexpr float SIN_SHOT_TRAJECTORY = 10; + +constexpr ColorMod SLOTH_SPLAT_COLOR = {{0, 1, 0, 1}, {0, 0, 0, 0}, {0, 0.3f, 0}}; +constexpr ColorMod SLOTH_SHOT_COLOR = {{1, 1, 1, 1}, {0.4f, 2, 0.5f, 1}, {0, 0, 0}}; +constexpr ColorMod SLOTH_BLOOD_COLOR = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0.08f, 0.5f, 0.01f}}; +constexpr ColorMod SLOTH_SPLASH_COLOR = {{0, 0, 0, 0.5f}, {0, 0, 0, 0}, {0.08f, 0.5f, 0.01f}}; +constexpr int SLOTH_ATTACK_FRAME = 5; +constexpr int SLOTH_ATTACK_END = 29; +constexpr int SLOTH_ENEMY_LIMIT = 3; +constexpr float SLOTH_LINE_REACH = 60; +constexpr float SLOTH_SPIT_VOLUME = 0.7f; +constexpr int SLOTH_ULTRA_SHOTS = 3; +constexpr float SLOTH_ULTRA_SHOT_SCALE = 1.2f; +constexpr int SLOTH_SUPER_SHOTS = 2; +constexpr float SLOTH_SHOT_ACCEL = 0.3f; +constexpr float SLOTH_SHOT_FALL = 0.7f; +constexpr float SLOTH_SHOT_LIFT = 13; +constexpr float SLOTH_SHOT_SLOW = 0.55f; +constexpr float SLOTH_SHOT_SCALE = 1.6f; +constexpr int SLOTH_SPIDERS = 2; +constexpr float SLOTH_SPIDER_STEP = 70; +constexpr float SLOTH_SPIDER_HEIGHT = -30; +constexpr float SLOTH_SUMMON_VOLUME = 0.8f; +constexpr float SLOTH_CHARGER_REACH = 30; +constexpr int SLOTH_CREEP_FIRST = 6; +constexpr int SLOTH_CREEP_COUNT = 9; +constexpr float SLOTH_CREEP_SPACING = 25; +constexpr float SLOTH_CREEP_SCALE = 1.6f; +constexpr float SLOTH_CREEP_GROWTH = 0.07f; +constexpr float SLOTH_BLOOD_SPEED = 10; +constexpr float SLOTH_BLOOD_BACK = 5; +constexpr float SLOTH_BLOOD_LIFT = -16; +constexpr float SLOTH_BLOOD_SPIN = 360; + +constexpr float LUST_FRICTION = 0.95f; +constexpr int LUST_CREEP_FRAMES = 7; +constexpr float LUST_LEAD = 10; +constexpr float LUST_PATH_SPEED = 0.996f; +constexpr int LUST_PATH_MARK = 900; +constexpr float LUST_SPEED = 0.65f; + +constexpr ColorMod WRATH_SPLAT_COLOR = {{0.05f, 0, 0, 1}, {0, 0, 0, 0}, {0.2f, 0.2f, 0.2f}}; +constexpr float WRATH_FRICTION = 0.85f; +constexpr float WRATH_DASH_FRICTION = 0.8f; +constexpr float WRATH_DASH_SPEED = 1.5f; +constexpr float WRATH_ALIGN = 0.1f; +constexpr float WRATH_OWN_BOMB_DAMAGE = 20; +constexpr float WRATH_PLAYER_BOMB_DAMAGE = 200; +constexpr int WRATH_BOMB_ODDS_MIN = 60; +constexpr float WRATH_LEAD = 16; +constexpr float WRATH_LINE_WIDTH = 20; +constexpr float WRATH_DASH_REACH = 200; +constexpr int WRATH_BOMB_FRAME = 4; +constexpr int WRATH_BOMB_FRAMES = 60; +constexpr float WRATH_BOMB_SPEED = 10; +constexpr float WRATH_BOMB_REACH = 130; +constexpr float WRATH_EVADE = 50; +constexpr float WRATH_EVADE_FRICTION = 0.5f; + +constexpr ColorMod GREED_SPLAT_COLOR = {{0.4f, 0.2f, 0.2f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr uint32_t GREED_SUMMON_ODDS = 3; +constexpr int GREED_ENEMY_LIMIT = 3; +constexpr int GREED_ANIM_FRAME = 1; +constexpr int GREED_ACT_FRAME = 5; +constexpr int GREED_SHOOT_END = 24; +constexpr int GREED_SUMMON_END = 26; +constexpr float GREED_SHOT_SPEED = 10; +constexpr float GREED_SUMMON_VOLUME = 1.2f; +constexpr float GREED_MINION_REACH = 50; + +constexpr int ENVY_SIZE_STEP = 10; +constexpr int ENVY_SMALLEST = 30; +constexpr std::array ENVY_WALKS = {"Walk0", "Walk1", "Walk2", "Walk3", "Walk4"}; +constexpr std::array ENVY_HEALTH_DIVISORS = {1, 3, 4, 5}; +constexpr ColorMod ENVY_SPLAT_COLOR = {{0.9f, 0.9f, 0.9f, 1}, {0.9f, 0.9f, 1, 0.3f}, {0, 0, 0}}; +constexpr ColorMod SUPER_ENVY_SPLAT_COLOR = {{0.8f, 0.75f, 1, 1}, {2.1f, 1.7f, 2.5f, 1}, {0, 0, 0}}; +constexpr float ENVY_FRICTION = 0.9f; +constexpr float ENVY_SPLIT_REACH = 10; +constexpr float ENVY_SPLIT_SPEED = 0.4f; +constexpr float ENVY_SPEED_LARGE = 0.25f; +constexpr float ENVY_SPEED = 0.35f; +constexpr float ENVY_SPEED_MEDIUM = 0.45f; +constexpr float ENVY_FLEE_REACH = 120; +constexpr float ENVY_FLEE_STRENGTH = 0.02f; +constexpr float MEGA_SATAN_FLOOR = 320; + +constexpr ColorMod PRIDE_SPLAT_COLOR = {{1, 1, 1, 1}, {0, 0, 0, 0}, {0, 0.2f, 0.2f}}; +constexpr ColorMod SUPER_PRIDE_LASER_COLOR = {{0.882f, 0.51f, 0.47f, 1}, {0, 0, 0, 0}, {0.824f, 0.235f, 0.706f}}; +constexpr int PRIDE_ZAP_FRAME = 12; +constexpr int PRIDE_LASER_FRAME = 20; +constexpr int PRIDE_LASERS = 4; +constexpr int PRIDE_LASER_VARIANT = 4; +constexpr int PRIDE_LASER_TIMEOUT = 17; +constexpr float PRIDE_LASER_FIRST = 45; +constexpr float PRIDE_LASER_TURN = 90; +constexpr float PRIDE_LASER_RISE = -10; +constexpr float PRIDE_LASER_OFFSET = -20; +constexpr float PRIDE_RING_DROP = 20; +constexpr float PRIDE_RING_SPEED = 8; +constexpr float PRIDE_RING_SHOTS = 6; +constexpr int PRIDE_BOMB_DELAY = 6; +constexpr int PRIDE_BOMB_INTERVAL = 5; +constexpr int PRIDE_BOMB_END = 20; +constexpr int SUPER_PRIDE_BOMB_END = 10; +constexpr int PRIDE_BOMB_MARK = 900; +constexpr int PRIDE_ATTACK_END = 45; + +// The walk most sins share, its frame following the velocity. +static void sin_walk_animate(Entity_NPC& npc) +{ + npc.AnimWalkFrame("WalkHori", "WalkVert", SIN_WALK_THRESHOLD); +} + +// Sloth's spit at frame 5: Ultra Pride's three homing shots, Super Sloth's spiders thrown halfway to the target, or the +// plain Sloth's Charger, sent dashing the way it faces. +static void sloth_spit(Entity_NPC& npc) +{ + if (npc.variant == SLOTH_ULTRA_PRIDE) + { + npc.PlaySound(SOUND_HEARTOUT, SLOTH_SPIT_VOLUME, 2, false, 1); + ProjectileParams params; + params.bulletFlags |= PROJECTILE_SMART; + params.scale = SLOTH_ULTRA_SHOT_SCALE; + npc.FireBossProjectiles(SLOTH_ULTRA_SHOTS, npc.GetPlayerTarget()->pos, SIN_SHOT_TRAJECTORY, params); + return; + } + + if (npc.variant == SIN_SUPER) + { + npc.PlaySound(SOUND_SPIDER_COUGH, 1, 2, false, 1); + bool isBig = (Random() & 1) == 0; + for (int i = 0; i < (isBig ? 1 : SLOTH_SPIDERS); i++) + { + Vector halfway = vector_scale(vector_add(npc.GetPlayerTarget()->pos, npc.pos), 0.5f); + Vector spot = room_free_pickup_position_find({.position = halfway, .step = SLOTH_SPIDER_STEP}); + Entity_NPC::ThrowSpider(npc.pos, &npc, spot, isBig, SLOTH_SPIDER_HEIGHT); + } + return; + } + + npc.PlaySound(SOUND_SUMMONSOUND, SLOTH_SUMMON_VOLUME, 2, false, 1); + npc.PlaySound(SOUND_MONSTER_GRUNT_2, 1, 2, false, 1); + uint32_t seed = Random(); + float side = npc.sprite.isFlipX ? -1.0f : 1.0f; + Vector spot = vector_make(side * SLOTH_CHARGER_REACH + npc.pos.x, npc.pos.y); + auto* charger = static_cast( + g_game->Spawn({.position = spot, .spawner = &npc, .type = ENTITY_CHARGER, .seed = seed})); + charger->state = NPC_STATE_ATTACK; + charger->v1 = vector_make(side, 0); + npc.entityCollisionClass = ENTCOLL_PLAYEROBJECTS; +} + +// One link of Ultra Pride's creep line, ever further toward the target's side: green creep, with a spray of blood and +// a splash where it lands inside the room. +static void ultra_pride_creep(Entity_NPC& npc, float toTargetX) +{ + float step = (float)(npc.stateFrame - (SLOTH_CREEP_FIRST - 1)) * (toTargetX >= 0 ? 1.0f : -1.0f); + Vector at = vector_make(step * SLOTH_CREEP_SPACING + npc.pos.x, npc.pos.y); + Entity* creep = g_game->Spawn( + {.position = at, .spawner = &npc, .type = ENTITY_EFFECT, .variant = EFFECT_CREEP_GREEN, .seed = Random()}); + float scale = step * SLOTH_CREEP_GROWTH + SLOTH_CREEP_SCALE; + creep->sprite.scale = vector_make(scale, scale); + creep->Update(); + if (!g_game->room->IsPositionInRoom(creep->pos, 0)) return; + + Vector direction = vector_normalized(vector_make(step, 0)); + uint32_t seed = Random(); + Vector spray = vector_scale(direction, random_unit() * SLOTH_BLOOD_SPEED); + Entity* blood = g_game->Spawn({.position = vector_sub(creep->pos, vector_scale(direction, SLOTH_BLOOD_BACK)), + .velocity = spray, + .subType = 2, + .type = ENTITY_EFFECT, + .variant = EFFECT_BLOOD_EXPLOSION, + .seed = seed}); + blood->sprite.rotation = random_unit() * SLOTH_BLOOD_SPIN; + blood->posOffset = vector_make(0, random_unit() * SLOTH_BLOOD_LIFT); + blood->SetColor(SLOTH_BLOOD_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + + Entity* splash = + g_game->Spawn({.position = creep->pos, .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_SPLAT, .seed = Random()}); + splash->sizeMulti = vector_make(scale, scale); + splash->SetColor(SLOTH_SPLASH_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + splash->Update(); +} + +// Sloth's lob at frame 5: one slow, high, exploding shot, two for Super Sloth. +static void sloth_lob(Entity_NPC& npc) +{ + npc.PlaySound(SOUND_HEARTOUT, SLOTH_SPIT_VOLUME, 2, false, 1); + int count = npc.variant == SIN_SUPER ? SLOTH_SUPER_SHOTS : 1; + for (int i = 0; i < count; i++) + { + ProjectileParams params; + Entity_Projectile* shot = npc.FireBossProjectiles(1, npc.GetPlayerTarget()->pos, SIN_SHOT_TRAJECTORY, params); + shot->projectileFlags |= PROJECTILE_EXPLODE; + shot->fallingAccel -= SLOTH_SHOT_ACCEL; + shot->fallingSpeed = shot->fallingSpeed * SLOTH_SHOT_FALL - SLOTH_SHOT_LIFT; + shot->velocity = vector_scale(shot->velocity, SLOTH_SHOT_SLOW); + shot->SetColor(SLOTH_SHOT_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + shot->scale = SLOTH_SHOT_SCALE; + shot->parent = &npc; + } +} + +// 004741f0 NpcAI::ENTITY_SLOTH: Sloth, Super Sloth and Ultra Pride wander along the axes and now and then spit (a +// Charger, spiders or homing shots) or lob (exploding shots, or Ultra Pride's creep line toward the target). +static void sloth_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_INIT) + { + npc.state = SIN_WALK; + std::copy_n(SLOTH_SPLAT_COLOR._tint, 4, npc.splatColor._tint); + std::copy_n(SLOTH_SPLAT_COLOR._offset, 3, npc.splatColor._offset); + return; + } + + npc.friction *= SIN_FRICTION; + Vector toTarget = vector_sub(npc.GetPlayerTarget()->pos, npc.pos); + if (npc.state == SIN_ATTACK || npc.state == SIN_ATTACK2) + { + bool isUltra = npc.variant == SLOTH_ULTRA_PRIDE; + if (npc.state == SIN_ATTACK && npc.stateFrame == SLOTH_ATTACK_FRAME) sloth_spit(npc); + else if (npc.state == SIN_ATTACK2 && isUltra && npc.stateFrame >= SLOTH_CREEP_FIRST && + npc.stateFrame < SLOTH_CREEP_FIRST + SLOTH_CREEP_COUNT) + ultra_pride_creep(npc, toTarget.x); + else if (npc.state == SIN_ATTACK2 && npc.stateFrame == SLOTH_ATTACK_FRAME) + { + if (isUltra) npc_sound_play(SOUND_HEARTIN, SLOTH_SPIT_VOLUME, 2, 1); + else sloth_lob(npc); + } + if (npc.stateFrame > SLOTH_ATTACK_END) npc.state = SIN_WALK; + npc.stateFrame++; + return; + } + if (npc.state != SIN_WALK) return (void)npc.stateFrame++; + + sin_walk_animate(npc); + npc.pathfinder.MoveRandomlyAxisAligned(SIN_WALK_SPEED, STATUS_OBEYED); + bool isSkipped = Random() % SIN_ATTACK_ODDS != 0 || npc.HasEntityFlags(FLAG_CONFUSION) || + (npc.HasEntityFlags(FLAG_FEAR | FLAG_SHRINK) && Random() % SIN_DISTRACTED_ODDS != 0); + if (isSkipped) return (void)npc.stateFrame++; + + npc.stateFrame = 0; + npc.sprite.isFlipX = toTarget.x < 0; + npc_anim_restart(npc.sprite, "Attack"); + bool isSpit = (Random() & 1) == 0 && g_game->room->GetAliveEnemiesCount() <= SLOTH_ENEMY_LIMIT; + bool isLob = !isSpit && (std::abs(toTarget.y) <= SLOTH_LINE_REACH || npc.variant != SLOTH_ULTRA_PRIDE); + npc.state = isLob ? SIN_ATTACK2 : SIN_ATTACK; + npc.stateFrame++; +} + +// 00474e00 NpcAI::ENTITY_LUST: Lust chases where its target is heading, along a path when out of sight. Super Lust +// leaves red creep. +static void lust_update(Entity_NPC& npc) +{ + npc.friction *= LUST_FRICTION; + if (npc.IsFrame(LUST_CREEP_FRAMES, 0) && npc.variant == SIN_SUPER) + g_game + ->Spawn({.position = npc.pos, + .spawner = &npc, + .type = ENTITY_EFFECT, + .variant = EFFECT_CREEP_RED, + .seed = Random()}) + ->Update(); + sin_walk_animate(npc); + + Vector target = npc.CalcTargetPosition(0); + Vector lead = vector_sub(vector_add(vector_scale(npc.GetPlayerTarget()->velocity, LUST_LEAD), target), npc.pos); + if (!room_check_line(npc.pos, npc.CalcTargetPosition(0), LINE_MODE_GROUND, 0)) + return npc.pathfinder.FindGridPath(npc.CalcTargetPosition(0), LUST_PATH_SPEED, LUST_PATH_MARK, DIRECT_PATH_FAR); + npc_push(npc, vector_scale(vector_normalized(lead), LUST_SPEED)); +} + +// Wrath's dash: pushed along its direction and drawn to its cell's line, until it hits something. +static void wrath_dash(Entity_NPC& npc) +{ + if (npc.isCollidesWithGrid || npc.isCollidesWithEntity) + { + npc.state = SIN_WALK; + return; + } + + npc.friction *= WRATH_DASH_FRICTION; + npc_push(npc, vector_scale(npc.v2, WRATH_DASH_SPEED)); + Vector cell = g_game->room->GetGridPosition(npc.pathfinder.gridIndex); + if (std::abs(npc.velocity.x) <= std::abs(npc.velocity.y)) + npc.pos.x = npc.pos.x * (1 - WRATH_ALIGN) + cell.x * WRATH_ALIGN; + else npc.pos.y = cell.y * WRATH_ALIGN + npc.pos.y * (1 - WRATH_ALIGN); +} + +// Wrath walking: by its last bomb it wanders off (its target cleared once it heads back toward it). Otherwise it +// either drops a bomb at random, more often near its target, or dashes or rolls a bomb at a target in line with it. +static void wrath_walk(Entity_NPC& npc) +{ + if (!vector_is_zero(npc.v1) && npc.stateFrame >= 1) + { + npc.stateFrame--; + if (vector_length(vector_sub(npc.v1, npc.pos)) >= WRATH_BOMB_REACH) return; + + npc.pathfinder.MoveRandomlyAxisAligned(SIN_WALK_SPEED, STATUS_OBEYED); + Vector toGoal = vector_sub(npc.targetPosition, npc.pos); + Vector toBomb = vector_sub(npc.v1, npc.pos); + bool isTowardBomb = toGoal.x * toBomb.x > WRATH_EVADE || toBomb.y * toGoal.y > WRATH_EVADE; + if (vector_is_zero(npc.targetPosition) || !isTowardBomb) return; + + KAGE_LogMessage(LOG_INFO, (uint8_t*)"Wrath: Evade own bomb.\n"); + npc.friction *= WRATH_EVADE_FRICTION; + npc.targetPosition = {}; + return; + } + + npc.pathfinder.MoveRandomlyAxisAligned(SIN_WALK_SPEED, STATUS_OBEYED); + Vector target = npc.CalcTargetPosition(0); + int odds = std::max(WRATH_BOMB_ODDS_MIN, (int)vector_length(vector_sub(target, npc.pos))); + if (Random() % (uint32_t)odds == 0) + { + npc.state = SIN_ATTACK2; + npc_anim_restart(npc.sprite, "Attack"); + npc.v2 = {}; + return; + } + + npc.pathfinder.UpdateGridIndex(); + Vector targetVelocity = npc.GetPlayerTarget()->velocity; + Room& room = *g_game->room; + Vector predicted = vector_add(target, vector_scale(targetVelocity, random_unit() * WRATH_LEAD)); + Vector cell = room.GetGridPosition(npc.pathfinder.gridIndex); + Vector gap = vector_sub(predicted, cell); + bool isInLine = std::abs(gap.x) < WRATH_LINE_WIDTH || std::abs(gap.y) < WRATH_LINE_WIDTH; + if (!isInLine || vector_length(gap) >= WRATH_DASH_REACH || !room_check_line(cell, predicted, LINE_MODE_GROUND, 0)) + return; + + if (std::abs(gap.x) <= std::abs(gap.y)) npc.v2 = vector_make(0, gap.y >= 0 ? 1.0f : -1.0f); + else npc.v2 = vector_make(gap.x >= 0 ? 1.0f : -1.0f, 0); + npc.stateFrame = 0; + if ((Random() & 1) != 0) return (void)(npc.state = SIN_ATTACK); + + npc.state = SIN_ATTACK2; + npc_anim_restart(npc.sprite, "Attack"); +} + +// 00475110 NpcAI::ENTITY_WRATH: Wrath drops bombs (Super Wrath's are Mega Troll Bombs) or rolls them along its dash +// direction, and runs from them. It takes 20 from its own blasts and 200 from the players'. +static void wrath_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_INIT) + { + npc.state = SIN_WALK; + if (npc.variant == SIN_SUPER) npc.splatColor = WRATH_SPLAT_COLOR; + return; + } + + for (DamageEvent& event : npc.damageEvents) + { + if (!(event.damageFlags & DAMAGE_EXPLOSION)) continue; + if (event.source.spawnerType == npc.type) event.damage = WRATH_OWN_BOMB_DAMAGE; + else if (event.source.spawnerType == ENTITY_PLAYER) event.damage = WRATH_PLAYER_BOMB_DAMAGE; + } + + npc.friction *= WRATH_FRICTION; + if (npc.state == SIN_ATTACK) wrath_dash(npc); + else if (npc.state == SIN_WALK) wrath_walk(npc); + else if (npc.state == SIN_ATTACK2) + { + if (npc.stateFrame > WRATH_BOMB_FRAME) + { + Room& room = *g_game->room; + npc.v1 = room.GetGridPosition(room.GetGridIndex(npc.pos)); + uint32_t seed = Random(); + Entity* bomb = g_game->Spawn({.position = npc.v1, + .velocity = vector_scale(npc.v2, WRATH_BOMB_SPEED), + .spawner = &npc, + .type = ENTITY_BOMB, + .variant = npc.variant == SIN_SUPER ? BOMB_SUPERTROLL : BOMB_NORMAL, + .seed = seed}); + bomb->entityCollisionClass = vector_is_zero(npc.v2) ? ENTCOLL_NONE : ENTCOLL_PLAYERONLY; + npc.stateFrame = WRATH_BOMB_FRAMES; + npc.state = SIN_WALK; + } + npc.stateFrame++; + } + + if (npc.state == SIN_WALK || npc.state == SIN_ATTACK) sin_walk_animate(npc); +} + +// Greed's summon at frame 5: two Hoppers (Keepers for Super Greed) beside it when it is alone, else above and below. +static void greed_summon(Entity_NPC& npc) +{ + npc.PlaySound(SOUND_SUMMONSOUND, GREED_SUMMON_VOLUME, 2, false, 1); + int minion = npc.variant == SIN_SUPER ? ENTITY_KEEPER : ENTITY_HOPPER; + bool isAlone = g_game->room->GetAliveEnemiesCount() == 1; + Vector offset = isAlone ? vector_make(GREED_MINION_REACH, 0) : vector_make(0, GREED_MINION_REACH); + Vector first = room_free_pickup_position_find({.position = vector_sub(npc.pos, offset)}); + Vector second = room_free_pickup_position_find({.position = vector_add(npc.pos, offset)}); + g_game->Spawn({.position = first, .spawner = &npc, .type = minion, .seed = Random()}); + g_game->Spawn({.position = second, .spawner = &npc, .type = minion, .seed = Random()}); +} + +// Greed's shot: at frame 1 it faces its target along an axis, at frame 5 it fires three shots that way (four for +// Super Greed). +static void greed_shoot(Entity_NPC& npc, Vector toTarget) +{ + if (npc.stateFrame == GREED_ACT_FRAME) + { + ProjectileParams params; + ProjectilesMode mode = npc.variant == SIN_SUPER ? PROJECTILES_FOUR : PROJECTILES_THREE; + return npc.FireProjectiles(npc.pos, npc.v1, mode, params); + } + if (npc.stateFrame != GREED_ANIM_FRAME) + { + if (npc.stateFrame > GREED_SHOOT_END) npc.state = SIN_WALK; + return; + } + + npc.sprite.isFlipX = false; + switch (vector_to_direction(toTarget)) + { + case DIRECTION_LEFT: + npc_anim_restart(npc.sprite, "Attack01Hori"); + npc.sprite.isFlipX = true; + break; + case DIRECTION_UP: + npc_anim_restart(npc.sprite, "Attack01Up"); + break; + case DIRECTION_RIGHT: + npc_anim_restart(npc.sprite, "Attack01Hori"); + break; + case DIRECTION_DOWN: + npc_anim_restart(npc.sprite, "Attack01Down"); + break; + default: + break; + } + npc.v1 = vector_scale(vector_cardinal(toTarget), GREED_SHOT_SPEED); +} + +// 00475a30 NpcAI::ENTITY_GREED: Greed and Super Greed wander along the axes, and now and then shoot along an axis at +// their target or, while few enemies are left, summon two minions. +static void greed_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_INIT) + { + npc.state = SIN_WALK; + npc.splatColor = GREED_SPLAT_COLOR; + } + + npc.friction *= SIN_FRICTION; + Vector toTarget = vector_sub(npc.GetPlayerTarget()->pos, npc.pos); + switch (npc.state) + { + case SIN_WALK: + sin_walk_animate(npc); + npc.pathfinder.MoveRandomlyAxisAligned(SIN_WALK_SPEED, STATUS_OBEYED); + if (Random() % SIN_ATTACK_ODDS != 0) break; + + npc.stateFrame = 0; + npc.state = Random() % GREED_SUMMON_ODDS == 0 && g_game->room->GetAliveEnemiesCount() < GREED_ENEMY_LIMIT + ? SIN_SUMMON + : SIN_ATTACK; + break; + case SIN_ATTACK: + greed_shoot(npc, toTarget); + break; + case SIN_SUMMON: + if (npc.stateFrame == GREED_ANIM_FRAME) + { + npc.sprite.isFlipX = false; + npc_anim_restart(npc.sprite, "Attack02"); + } + else if (npc.stateFrame == GREED_ACT_FRAME) greed_summon(npc); + else if (npc.stateFrame > GREED_SUMMON_END) npc.state = SIN_WALK; + break; + } + npc.stateFrame++; +} + +// One of Envy's heads splitting off a dead one: the next size down, nudged out from it, appearing at once. +static void envy_split(Entity_NPC& npc, Vector position, Vector velocity) +{ + uint32_t seed = npc.dropRNG.Next(); + Entity* head = g_game->Spawn({.position = position, + .velocity = velocity, + .spawner = &npc, + .type = npc.type, + .variant = npc.variant + ENVY_SIZE_STEP, + .seed = seed}); + head->ClearEntityFlags(FLAG_APPEAR); + head->Update(); +} + +// Envy's first update: the head's look and health for its size (a third, a quarter or a fifth for the smaller +// ones), a random drift and its splat color. +static void envy_init(Entity_NPC& npc) +{ + int size = std::min(npc.variant / ENVY_SIZE_STEP, ENVY_SMALLEST / ENVY_SIZE_STEP); + bool isSuper = npc.variant % ENVY_SIZE_STEP == SIN_SUPER; + npc.sprite.Play(ENVY_WALKS[size == 0 ? 0 : size + (isSuper ? 1 : 0)]); + npc.health /= ENVY_HEALTH_DIVISORS[size]; + npc.maxHitPoints /= ENVY_HEALTH_DIVISORS[size]; + + npc.entityGridCollisionClass = GRIDCOLL_WALLS; + npc.state = SIN_WALK; + npc.velocity = random_direction(); + npc.splatColor = isSuper ? SUPER_ENVY_SPLAT_COLOR : ENVY_SPLAT_COLOR; +} + +// 004760a0 NpcAI::ENTITY_ENVY: Envy's head bounces about the room diagonally, smaller heads faster, fleeing its target +// when afraid or shrunk. A dead head splits in two of the next size down, Super Envy's sometimes in three. +static void envy_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_INIT) return envy_init(npc); + + if (npc.isDead && npc.variant < ENVY_SMALLEST) + { + Vector out = vector_scale(random_direction(), ENVY_SPLIT_REACH); + envy_split(npc, vector_add(npc.pos, out), vector_scale(out, ENVY_SPLIT_SPEED)); + envy_split(npc, vector_sub(npc.pos, out), vector_scale(out, -ENVY_SPLIT_SPEED)); + if (npc.variant % ENVY_SIZE_STEP == SIN_SUPER && npc.variant / ENVY_SIZE_STEP < (int)(Random() & 1) + 1) + envy_split(npc, vector_sub(npc.pos, out), vector_make(out.y * ENVY_SPLIT_SPEED, -out.x * ENVY_SPLIT_SPEED)); + } + + if (g_game->room->bossId == BOSS_ID_MEGA_SATAN && npc.pos.y < MEGA_SATAN_FLOOR) + { + npc.pos.y = MEGA_SATAN_FLOOR; + npc.velocity.y = -npc.velocity.y; + } + + npc.friction *= ENVY_FRICTION; + if (npc.HasEntityFlags(FLAG_CONFUSION)) npc.pathfinder.MoveRandomly(STATUS_OBEYED); + int size = npc.variant / ENVY_SIZE_STEP; + float speed = size == 0 ? ENVY_SPEED_LARGE : size == 2 ? ENVY_SPEED_MEDIUM : ENVY_SPEED; + npc_push(npc, vector_make(npc.velocity.x < 0 ? -speed : speed, npc.velocity.y < 0 ? -speed : speed)); + npc.sprite.isFlipX = npc.velocity.x < 0; + if (!npc.HasEntityFlags(FLAG_FEAR | FLAG_SHRINK)) return; + + Vector away = vector_sub(npc.pos, npc.GetPlayerTarget()->pos); + float distance = vector_length(away); + if (distance > 0) + away = vector_scale(away, std::clamp((ENVY_FLEE_REACH - distance) * ENVY_FLEE_STRENGTH, 0.0f, 1.0f) / distance); + npc_push(npc, away); +} + +// Pride's zap at frame 20: four diagonal lasers (tinted for Super Pride), which also fires a ring of shots. +static void pride_zap(Entity_NPC& npc) +{ + if (npc.variant == SIN_SUPER && npc.stateFrame == PRIDE_LASER_FRAME) + { + ProjectileParams params; + npc.FireProjectiles(vector_make(npc.pos.x, npc.pos.y + PRIDE_RING_DROP), + vector_make(PRIDE_RING_SPEED, PRIDE_RING_SHOTS), PROJECTILES_RING, params); + } + if (npc.stateFrame == PRIDE_ZAP_FRAME) npc_sound_play(SOUND_PRIDE_ZAP, 1, 2, champion_pitch_get(npc)); + if (npc.stateFrame != PRIDE_LASER_FRAME) return; + + for (int i = 0; i < PRIDE_LASERS; i++) + { + Entity_Laser* laser = + Entity_Laser::ShootAngle({.position = vector_make(npc.pos.x, npc.pos.y + PRIDE_LASER_RISE), + .posOffset = vector_make(0, PRIDE_LASER_OFFSET), + .source = &npc, + .angleDegrees = (float)i * PRIDE_LASER_TURN + PRIDE_LASER_FIRST, + .timeout = PRIDE_LASER_TIMEOUT, + .variant = PRIDE_LASER_VARIANT}); + if (npc.variant == SIN_SUPER) laser->SetColor(SUPER_PRIDE_LASER_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + laser->Update(); + } +} + +// Pride's bombs: from frame 6 every fifth frame a Troll Bomb (a Mega Troll Bomb for Super Pride) at a random free spot, +// four of them, two for Super Pride. +static void pride_bomb(Entity_NPC& npc) +{ + int frame = npc.stateFrame - PRIDE_BOMB_DELAY; + if (frame == 1) npc.PlaySound(SOUND_GURG_BARF, 1, 2, false, 1); + if (frame < 0 || frame % PRIDE_BOMB_INTERVAL != 0) return; + + bool isSuper = npc.variant == SIN_SUPER; + bool isDropping = (npc.variant == 0 && frame < PRIDE_BOMB_END) || (isSuper && frame < SUPER_PRIDE_BOMB_END); + if (!isDropping) return; + + Vector spot = room_pickup_position_random(false, false); + Room& room = *g_game->room; + room.SetGridPath(room.GetGridIndex(spot), PRIDE_BOMB_MARK); + g_game->Spawn({.position = spot, + .spawner = &npc, + .type = ENTITY_BOMB, + .variant = isSuper ? BOMB_SUPERTROLL : BOMB_TROLL, + .seed = Random()}); +} + +// 00479d80 NpcAI::ENTITY_PRIDE: Pride wanders along the axes, ignoring what it spawned hurting it, and now and then +// zaps four lasers or drops Troll Bombs about the room. +static void pride_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_INIT) + { + npc.state = SIN_WALK; + npc.splatColor = PRIDE_SPLAT_COLOR; + } + + std::erase_if(npc.damageEvents, [&](DamageEvent& event) { return event.source.spawnerType == npc.type; }); + npc.friction *= SIN_FRICTION; + if (npc.state == SIN_WALK) + { + if (vector_length(npc.velocity) >= 1) + { + if (std::abs(npc.velocity.x) <= std::abs(npc.velocity.y)) + npc.sprite.Play(npc.velocity.y <= 0 ? "WalkUp" : "WalkDown"); + else + { + npc.sprite.Play("WalkHori"); + npc.sprite.isFlipX = npc.velocity.x < 0; + } + } + else if (npc.sprite.SetAnimation("WalkDown", SWITCH_KEEP_FRAME) && npc.sprite.animState.animData) + { + npc.sprite.animState.SetFrameFloat(0); + npc.sprite.animState.isPlaying = false; + } + + npc.pathfinder.MoveRandomlyAxisAligned(SIN_WALK_SPEED, STATUS_OBEYED); + if (Random() % SIN_ATTACK_ODDS == 0) + { + npc.stateFrame = 0; + bool isZap = (Random() & 1) == 0; + npc.state = isZap ? SIN_ATTACK : SIN_ATTACK2; + npc_anim_restart(npc.sprite, isZap ? "Attack01" : "Attack02"); + } + } + else if (npc.state == SIN_ATTACK || npc.state == SIN_ATTACK2) + { + if (npc.state == SIN_ATTACK) pride_zap(npc); + else pride_bomb(npc); + if (npc.stateFrame > PRIDE_ATTACK_END) npc.state = SIN_WALK; + } + npc.stateFrame++; +} + +// The seven deadly sins' AIs by type, but Gluttony, which shares Vis's. +void npc_sin_update(Entity_NPC& npc) +{ + switch (npc.type) + { + case ENTITY_SLOTH: + return sloth_update(npc); + case ENTITY_LUST: + return lust_update(npc); + case ENTITY_WRATH: + return wrath_update(npc); + case ENTITY_GREED: + return greed_update(npc); + case ENTITY_ENVY: + return envy_update(npc); + case ENTITY_PRIDE: + return pride_update(npc); + } +} diff --git a/src/npc_vis.cpp b/src/npc_vis.cpp new file mode 100644 index 0000000..405f435 --- /dev/null +++ b/src/npc_vis.cpp @@ -0,0 +1,458 @@ +#include "npc_basement.h" +#include "boss_ai.h" +#include "camera.h" +#include "entity_config.h" +#include "entity_familiar.h" +#include "entity_laser.h" +#include "entity_tear.h" +#include "grid_entity.h" +#include "manager.h" +#include "npc_caves.h" +#include "texture_cache.h" +#include + +// The Vis family (39: Vis, Double Vis, the Chubber and its worms, the Scarred Double Vis), the Gluttonies (49) and +// Vis Versa (836), and the Cage's own Vis. +constexpr int DOUBLE_VIS = 1; +constexpr int CHUBBER = 2; +constexpr int SCARRED_DOUBLE_VIS = 3; +constexpr int CHUBBER_WORM = 22; +constexpr int SUPER_GLUTTONY = 1; +constexpr int TYPE_GLUTTONY = 49; +constexpr int TYPE_VIS_VERSA = 836; +constexpr int VIS_CAGE_SPAWNER = 265; + +// What the Vis family is doing: walking, the Gluttony's fat attack, the brimstone and the Chubber's throw. +constexpr int VIS_FAT_ATTACK = NPC_STATE_ATTACK; +constexpr int VIS_BRIMSTONE = NPC_STATE_ATTACK2; +constexpr int VIS_THROW = NPC_STATE_ATTACK3; + +// The Cage's Vis wears the Cage's colors. +constexpr std::string_view CAGE_VIS_SHEET = "gfx/Monsters/Classic/Monster_176_CageVis.png"; +constexpr std::string_view CAGE_LASER_SHEET = "gfx/Effects/Effect_018_CageLaserEffects.png"; +constexpr ColorMod CAGE_VIS_TINT = {{120 / 255.0f, 130 / 255.0f, 130 / 255.0f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod CAGE_VIS_SPLAT = {{10 / 255.0f, 80 / 255.0f, 10 / 255.0f, 1}, {0, 0, 0, 0}, + {100 / 255.0f, 100 / 255.0f, 80 / 255.0f}}; +constexpr int LASER_IMPACT_CAGE = 2; + +// Its cell is marked so walkers keep off, below the paths the room already blocks. +constexpr int VIS_PATH_LIMIT = 951; + +// It wanders at 0.7 and checks for a shot every 3 frames: in line with its target (within 20 on an axis) and within +// 400, on screen. The Gluttony rolls first: 1 time in 7 it fat attacks a target within 70 to 200, else it only looks +// for a shot 1 time in 10. +constexpr float VIS_WANDER_SPEED = 0.7f; +constexpr float VIS_WALK_THRESHOLD = 0.1f; +constexpr int VIS_CHECK_FRAMES = 3; +constexpr float VIS_LINE_SLACK = 20; +constexpr float VIS_RANGE = 400; +constexpr float VIS_CONTROL_RANGE = 1000; +constexpr int VIS_CONTROL_RANGE_FRAMES = 7; +constexpr uint32_t GLUTTONY_FAT_ODDS = 10; +constexpr uint32_t GLUTTONY_CLOSE_ODDS = 7; +constexpr float GLUTTONY_CLOSE_MIN = 70; +constexpr float GLUTTONY_CLOSE_SPREAD = 130; +constexpr float VIS_CONTROL_SHOT_FRAME = 8; +constexpr float VIS_FRICTION = 0.8f; +constexpr unsigned int CHUBBER_ATTACK = 3; +constexpr int ANIMATION_NAME_SIZE = 64; + +// The fat attack: eight shots at 8 (12 in hard mode), and the Super Gluttony's five boss shots. +constexpr float GLUTTONY_SHOT_SPEED = 8; +constexpr float GLUTTONY_HARD_SHOT_SPEED = 12; +constexpr int SUPER_GLUTTONY_SHOTS = 5; + +// The tracer warning of a beam: 20 above it, 28 frames, 4 wide, in red (Vis Versa's in its own colors). +constexpr float VIS_MOUTH_HEIGHT = -20; +constexpr ColorMod VIS_TRACER_COLOR = {{0.6f, 0.05f, 0, 0.8f}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod VIS_VERSA_TRACER_COLOR = {{0.25f, 0.1f, 0.4f, 0.8f}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod CAGE_VIS_TRACER_COLOR = {{0.1f, 0.3f, 0.2f, 0.8f}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr float VIS_TRACER_SCALE = 4; +constexpr int VIS_TRACER_TIMEOUT = 28; + +// The beams: from 6 ahead of it, 32 frames, drawn in front unless they point up (or back for the rear ones). +constexpr float VIS_BEAM_LEAD = 6; +constexpr int VIS_BEAM_TIMEOUT = 32; +constexpr float VIS_BEAM_UP = -0.5f; +constexpr float VIS_BEAM_FRONT_DEPTH = 3000; +constexpr float VIS_BEAM_BACK_DEPTH = -10; +constexpr ColorMod VIS_VERSA_BEAM_COLOR = {{1, 1, 1, 1}, {0.8f, 0.1f, 1, 1}, {0.18f, 0, 0.22f}}; +constexpr int VIS_VERSA_BEAM_PRIORITY = 255; + +// Vis Versa steers its beam's end toward its target: 2 a frame (0.4 under control), slower while the target is +// behind, and starts after 5 frames. +constexpr int VIS_VERSA_AIM_DELAY = 5; +constexpr float VIS_VERSA_STEER = 2; +constexpr float VIS_VERSA_CONTROL_STEER = 0.4f; +constexpr float VIS_VERSA_SETTLED = 0.01f; +constexpr float VIS_VERSA_CONTROL_EASE = 0.9f; + +// The Chubber throws its worm at 16 (faster sideways), nudged off its row when thrown sideways. +constexpr float CHUBBER_THROW_SPEED = 16; +constexpr float CHUBBER_SIDE_BOOST = 1.4f; +constexpr float CHUBBER_ROW_NUDGE = 0.1f; + +// The worm flies out and slows to a stop over 21 frames, then is pulled back to 20 short of the Chubber by frame 43. +// A loose one (its subtype) flies on until 80 out of the room. +constexpr int CHUBBER_WORM_LOOSE = 1; +constexpr float CHUBBER_WORM_OUT_FRAMES = 21; +constexpr int CHUBBER_WORM_BACK_FRAME = 43; +constexpr float CHUBBER_WORM_REACH = 20; +constexpr float CHUBBER_WORM_ROOM_MARGIN = -80; +constexpr float CHUBBER_WORM_MOVING = 0.001f; + +// The facings, in the order the worm numbers them. +enum WormFacing +{ + WORM_LEFT, + WORM_UP, + WORM_RIGHT, + WORM_DOWN +}; + +// The first frame: it walks, preloading its beam and impact, or the Cage's Vis takes the Cage's sheet and colors. +static void vis_init(Entity_NPC& npc) +{ + EntityConfig& config = g_manager->entityConfig; + npc.state = NPC_STATE_MOVE; + if (npc.spawnerType != VIS_CAGE_SPAWNER) + { + config.PreloadResources(config.GetEntity(ENTITY_EFFECT, EFFECT_LASER_IMPACT, 1)); + auto laser = config.entities.find(entity_key(ENTITY_LASER, LASER_THICK_RED, 0)); + config.PreloadResources(laser != config.entities.end() ? &laser->second : config.GetEntity(ENTITY_LASER, 0, 0)); + return; + } + if (npc.type != ENTITY_VIS || npc.variant != 0) return; + + npc.sprite.ReplaceSpritesheet(1, CAGE_VIS_SHEET); + npc.sprite.LoadGraphics(); + std::ranges::copy(CAGE_VIS_TINT._tint, npc.sprite.GetLayer(0)->color._tint); + npc.splatColor = CAGE_VIS_SPLAT; + config.PreloadResources(config.GetEntity(ENTITY_EFFECT, EFFECT_LASER_IMPACT, LASER_IMPACT_CAGE)); + TextureCache::Preload(CAGE_LASER_SHEET); +} + +static bool is_cage_vis(Entity_NPC& npc) +{ + return npc.spawnerType == VIS_CAGE_SPAWNER && npc.type == ENTITY_VIS && npc.variant == 0; +} + +// How many beams it fires: four for the Scarred Double Vis, two for the Double Vis and the Super Gluttony, else one. +static int vis_beam_count(Entity_NPC& npc) +{ + if (npc.type == ENTITY_VIS && npc.variant == SCARRED_DOUBLE_VIS) return 4; + bool isDouble = (npc.type == ENTITY_VIS && npc.variant == DOUBLE_VIS) || + (npc.type == TYPE_GLUTTONY && npc.variant == SUPER_GLUTTONY); + return isDouble ? 2 : 1; +} + +// The tracers warning of its beams: ahead in its color, then red behind and, for the Scarred Double Vis, to its sides. +static void vis_tracers_spawn(Entity_NPC& npc) +{ + ColorMod color = VIS_TRACER_COLOR; + if (npc.type == TYPE_VIS_VERSA && g_game->GetStageID() != STAGE_ID_GEHENNA) color = VIS_VERSA_TRACER_COLOR; + else if (is_cage_vis(npc)) color = CAGE_VIS_TRACER_COLOR; + + std::array directions = {npc.v1, vector_scale(npc.v1, -1), vector_make(-npc.v1.y, npc.v1.x), + vector_make(npc.v1.y, -npc.v1.x)}; + for (int i = 0; i < vis_beam_count(npc); i++) + following_effect_spawn(npc, {.offset = vector_make(0, VIS_MOUTH_HEIGHT), + .targetPosition = directions[i], + .color = i == 0 ? color : VIS_TRACER_COLOR, + .scale = VIS_TRACER_SCALE, + .timeout = VIS_TRACER_TIMEOUT}); +} + +// The brimstone's start: facing its target (or its controller's push) along an axis, warned by tracers, the Chubber's +// throw instead. +static void vis_brimstone_start(Entity_NPC& npc, Vector toTarget) +{ + Vector aim = npc.controllerID == -1 ? toTarget : npc.GetControllerMovementInput(0); + npc.v1 = vector_cardinal(aim); + npc.state = npc.variant == CHUBBER ? VIS_THROW : VIS_BRIMSTONE; + if (npc.variant != CHUBBER) vis_tracers_spawn(npc); + npc.stateFrame = 0; + npc.targetPosition = {}; + + bool isSideways = std::abs(npc.v1.x) > 0; + unsigned int attack = npc.state == VIS_THROW ? CHUBBER_ATTACK : (unsigned int)npc.variant + 1; + char name[ANIMATION_NAME_SIZE]; + std::snprintf(name, sizeof(name), "Attack%02u%s", attack, isSideways ? "Horiz" : npc.v1.y >= 0 ? "Down" : "Up"); + npc.sprite.Play(name); + if (isSideways) npc.sprite.isFlipX = npc.v1.x < 0; + if (npc.controllerID != -1 && npc.sprite.animState.animData) + npc.sprite.animState.SetFrameFloat(VIS_CONTROL_SHOT_FRAME); +} + +// Whether the Gluttony starts its fat attack once its 1 in 7 roll came up: when its target is close enough. +static bool gluttony_is_fat_attacking(Entity_NPC& npc, Vector toTarget) +{ + if (npc.controllerID != -1) return npc.IsControllerActionPressed(CONTROLLER_ACTION_SHOOT); + + return vector_length(toTarget) < random_unit() * GLUTTONY_CLOSE_SPREAD + GLUTTONY_CLOSE_MIN; +} + +// Walking: it wanders (steered under control) and every 3 frames looks for a shot along an axis. +static void vis_walk(Entity_NPC& npc, Vector toTarget) +{ + npc.AnimWalkFrame("WalkHori", "WalkHori", VIS_WALK_THRESHOLD); + if (npc.controllerID == -1) npc.pathfinder.MoveRandomlyAxisAligned(VIS_WANDER_SPEED, STATUS_OBEYED); + else npc.pathfinder.FindGridPath(g_vectorZero, VIS_WANDER_SPEED, 0, DIRECT_PATH_FAR); + if (npc.controllerID == -1 && !npc.IsFrame(VIS_CHECK_FRAMES, (int)npc.index)) return; + + if (npc.type == TYPE_GLUTTONY) + { + uint32_t roll = Random(); + bool isCloseRoll = npc.controllerID != -1 || Random() % GLUTTONY_CLOSE_ODDS == 0; + if (isCloseRoll && gluttony_is_fat_attacking(npc, toTarget)) + { + npc.state = VIS_FAT_ATTACK; + npc.stateFrame = 0; + return; + } + if (!isCloseRoll && roll % GLUTTONY_FAT_ODDS != 0) return; + } + if (npc.HasEntityFlags(FLAG_CONFUSION | FLAG_FEAR | FLAG_SHRINK)) return; + + bool isInSight = false; + if (npc.controllerID != -1) isInSight = npc.IsTargetInAttackRange(VIS_CONTROL_RANGE, VIS_CONTROL_RANGE_FRAMES, false); + else if ((std::abs(toTarget.x) < VIS_LINE_SLACK || std::abs(toTarget.y) < VIS_LINE_SLACK) && + vector_length(toTarget) < VIS_RANGE) + isInSight = g_game->room->camera->IsPosVisible(npc.pos); + if (isInSight) vis_brimstone_start(npc, toTarget); +} + +// The Gluttony's fat attack: on Shoot eight shots around it, and the Super Gluttony's five at its target. +static void gluttony_fat_attack(Entity_NPC& npc) +{ + npc.sprite.Play("FatAttack"); + if (!npc.sprite.animState.animData) return void(npc.state = NPC_STATE_MOVE); + if (!npc.sprite.IsEventTriggered("Shoot")) + { + if (npc_anim_is_done(npc)) npc.state = NPC_STATE_MOVE; + return; + } + + ProjectileParams params; + float speed = game_is_hard_mode() ? GLUTTONY_HARD_SHOT_SPEED : GLUTTONY_SHOT_SPEED; + npc.FireProjectiles(npc.pos, vector_make(speed, 0), PROJECTILES_EIGHT, params); + if (npc.variant != SUPER_GLUTTONY) return; + + ProjectileParams bossParams; + npc.FireBossProjectiles(SUPER_GLUTTONY_SHOTS, npc.GetPlayerTarget()->pos, 0, bossParams); +} + +// One beam along a direction from 6 to a side of it, drawn in front of it or behind. +static Entity_Laser* vis_beam_fire(Entity_NPC& npc, Vector direction, float side, bool isFront) +{ + Entity_Laser* laser = Entity_Laser::ShootAngle({.position = vector_make(side * VIS_BEAM_LEAD + npc.pos.x, npc.pos.y), + .posOffset = vector_make(0, VIS_MOUTH_HEIGHT), + .source = &npc, + .angleDegrees = vector_angle(direction), + .timeout = VIS_BEAM_TIMEOUT, + .variant = LASER_THICK_RED}); + laser->renderDepthOffset = isFront ? VIS_BEAM_FRONT_DEPTH : VIS_BEAM_BACK_DEPTH; + return laser; +} + +// Vis Versa picks its target's spot to sweep toward, or follows its controller's aim. +static void vis_versa_target(Entity_NPC& npc) +{ + if (npc.controllerID != -1) + { + npc.SpawnControlTarget(0, -1); + Vector aim = npc.GetAimTargetPosition(); + if (vector_is_zero(npc.targetPosition)) npc.targetPosition = aim; + else + { + float ease = 1 - npc_friction_scaled(VIS_VERSA_CONTROL_EASE, npc.speedMultiplier); + npc.targetPosition = vector_add(npc.targetPosition, vector_scale(vector_sub(aim, npc.targetPosition), ease)); + } + return; + } + if (npc.stateFrame <= VIS_VERSA_AIM_DELAY || !vector_is_zero(npc.targetPosition)) return; + + Entity* target = npc.GetPlayerTarget(); + npc.targetPosition = target->pos; + npc.target = target; +} + +// The brimstone: on Shoot its beams, ahead and (for the doubles) behind and to its sides. Vis Versa's beam is its +// child, tinted outside Gehenna, and bends with Eye of the Occult. +static void vis_brimstone(Entity_NPC& npc) +{ + if (npc.type == TYPE_VIS_VERSA) vis_versa_target(npc); + if (!npc.sprite.IsEventTriggered("Shoot")) + { + if (npc_anim_is_done(npc)) npc.state = NPC_STATE_MOVE; + return; + } + + Vector v1 = npc.v1; + Entity_Laser* laser = vis_beam_fire(npc, v1, v1.x, v1.y >= VIS_BEAM_UP); + if (npc.type == TYPE_VIS_VERSA) + { + npc.child = laser; + laser->targetPosition = npc.targetPosition; + if (g_game->GetStageID() != STAGE_ID_GEHENNA) + laser->SetColor(VIS_VERSA_BEAM_COLOR, -1, VIS_VERSA_BEAM_PRIORITY, false, true); + laser->tearFlags = TearFlags().set(TEAR_OCCULT); + } + laser->Update(); + if (vis_beam_count(npc) < 2) return; + + vis_beam_fire(npc, vector_scale(v1, -1), -v1.x, v1.y < VIS_BEAM_UP)->Update(); + if (vis_beam_count(npc) < 4) return; + + bool isUp = v1.y < VIS_BEAM_UP; + vis_beam_fire(npc, vector_make(v1.y, -v1.x), -v1.y, !isUp && v1.x <= -VIS_BEAM_UP)->Update(); + vis_beam_fire(npc, vector_make(-v1.y, v1.x), v1.y, !isUp && v1.x >= VIS_BEAM_UP)->Update(); +} + +// The Chubber's throw: on Shoot a worm along its facing, held to it. +static void chubber_throw(Entity_NPC& npc) +{ + if (!npc.sprite.IsEventTriggered("Shoot")) + { + if (npc_anim_is_done(npc)) npc.state = NPC_STATE_MOVE; + return; + } + + Vector velocity = vector_make(npc.v1.x * CHUBBER_THROW_SPEED * CHUBBER_SIDE_BOOST, npc.v1.y * CHUBBER_THROW_SPEED); + auto* worm = static_cast(g_game->Spawn({.position = npc.pos, + .velocity = velocity, + .spawner = &npc, + .type = npc.type, + .variant = CHUBBER_WORM, + .seed = Random()})); + worm->state = NPC_STATE_INIT; + worm->parent = &npc; + if (std::abs(npc.v1.y) < std::abs(npc.v1.x)) worm->pos.y += CHUBBER_ROW_NUDGE; + worm->Update(); +} + +// Vis Versa's beam end sweeps toward its target, slower while the target lies behind it, once its beam is out. +static void vis_versa_sweep(Entity_NPC& npc) +{ + Entity* laser = npc.child; + bool isBeaming = (laser && laser->type == ENTITY_LASER) || npc.state == VIS_BRIMSTONE; + if (!isBeaming) + { + if (!vector_is_zero(npc.targetPosition)) + { + npc.targetPosition = {}; + npc.target = nullptr; + } + return; + } + + Entity* target = npc.target; + if (target || npc.controllerID != -1) + { + Vector aim = npc.controllerID == -1 ? target->pos : npc.GetAimTargetPosition(); + Vector toAim = vector_sub(aim, npc.targetPosition); + float steer = npc.controllerID == -1 ? VIS_VERSA_STEER : VIS_VERSA_CONTROL_STEER; + float facing = vector_dot(npc.v1, vector_normalized(vector_sub(npc.targetPosition, npc.pos))); + if (facing < 0) steer *= facing + 1; + if (vector_length_squared(toAim) > VIS_VERSA_SETTLED) + npc.targetPosition = vector_add(npc.targetPosition, vector_resized(toAim, steer)); + else npc.targetPosition = aim; + } + if (laser && laser->type == ENTITY_LASER) laser->targetPosition = npc.targetPosition; +} + +// The facing of a worm's velocity (vertical on a tie), or of its throw once it barely moves. +static WormFacing worm_facing_get(Vector velocity) +{ + if (std::abs(velocity.x) <= std::abs(velocity.y)) return velocity.y >= 0 ? WORM_DOWN : WORM_UP; + return velocity.x < 0 ? WORM_LEFT : WORM_RIGHT; +} + +// 0052c2f0 NpcAI::ENTITY_VIS_chubber_projectile: the Chubber's worm flies out along its throw, slowing to a stop, and +// is reeled back to the Chubber, dying with it. A loose worm flies straight on, turned along its flight, until it +// leaves the room. +static void chubber_worm_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_INIT) + { + npc.v1 = npc.velocity; + npc.state = NPC_STATE_MOVE; + npc.stateFrame = 0; + npc.health = 0; + npc.maxHitPoints = 0; + npc.entityGridCollisionClass = GRIDCOLL_NONE; + npc.isCanShutDoors = false; + return; + } + + if (npc.subtype == CHUBBER_WORM_LOOSE) + { + npc.velocity = npc.v1; + if (!g_game->room->IsPositionInRoom(npc.pos, CHUBBER_WORM_ROOM_MARGIN)) npc.Remove(); + } + else + { + Entity* chubber = npc.parent; + float outward = 1 - (float)npc.stateFrame / CHUBBER_WORM_OUT_FRAMES; + if (!chubber || outward >= 0) npc.velocity = vector_scale(npc.v1, outward); + else + { + Vector toChubber = vector_sub(chubber->pos, npc.pos); + float distance = vector_length(toChubber); + if (distance > 0) toChubber = vector_scale(toChubber, (distance - CHUBBER_WORM_REACH) / distance); + int framesLeft = std::max(CHUBBER_WORM_BACK_FRAME - npc.stateFrame, 1); + npc.velocity = vector_scale(toChubber, -outward / (float)framesLeft); + } + if (!npc.parent) return npc.Kill(EntityRef()); + + if (npc.stateFrame >= CHUBBER_WORM_BACK_FRAME) npc.Remove(); + npc.stateFrame++; + } + + bool isMoving = vector_length_squared(npc.velocity) >= CHUBBER_WORM_MOVING; + WormFacing facing = worm_facing_get(isMoving ? npc.velocity : npc.v1); + npc.sprite.isFlipX = facing == WORM_LEFT; + npc.sprite.Play(facing == WORM_UP ? "Up" : facing == WORM_DOWN ? "Down" : "Side"); + if (npc.subtype == 0) return; + + float along = vector_dot(npc.v1, npc.velocity); + float angle = vector_angle(vector_scale(npc.v1, along)); + if (facing == WORM_LEFT) angle = 180 - angle; + else if (facing == WORM_UP) angle += 90; + else if (facing == WORM_DOWN) angle -= 90; + npc.sprite.GetLayer(0)->rotation = angle_wrap(angle); +} + +// 0052c720 NpcAI::ENTITY_VIS: the Vis family, the Gluttonies and Vis Versa wander along the axes and fire brimstone +// at a target in line, the Gluttony also bursts into shots and the Chubber throws worms on a leash. +void npc_vis_update(Entity_NPC& npc) +{ + if (npc.variant == CHUBBER_WORM) return chubber_worm_update(npc); + if (npc.state == NPC_STATE_INIT) return vis_init(npc); + + Room& room = *g_game->room; + int cell = room.GetGridIndex(npc.pos); + if (npc.controllerID == -1 && cell >= 0 && cell < ROOM_GRID_CELLS && room.gridPaths[cell] < VIS_PATH_LIMIT) + room.gridPaths[cell] = GRID_PATH_FREED; + + Vector toTarget = vector_sub(npc.GetPlayerTarget()->pos, npc.pos); + switch (npc.state) + { + case NPC_STATE_MOVE: + vis_walk(npc, toTarget); + break; + case VIS_FAT_ATTACK: + gluttony_fat_attack(npc); + break; + case VIS_BRIMSTONE: + vis_brimstone(npc); + break; + case VIS_THROW: + chubber_throw(npc); + break; + } + + if (npc.type == TYPE_VIS_VERSA) vis_versa_sweep(npc); + npc.stateFrame += npc_ticks_get(npc); + npc.friction *= VIS_FRICTION; +} diff --git a/src/npc_wall_creep.cpp b/src/npc_wall_creep.cpp new file mode 100644 index 0000000..f5e6700 --- /dev/null +++ b/src/npc_wall_creep.cpp @@ -0,0 +1,650 @@ +#include "npc_depths.h" +#include "boss_ai.h" +#include "camera.h" +#include "entity_config.h" +#include "entity_effect.h" +#include "entity_laser.h" +#include "manager.h" +#include "npc_caves.h" +#include "room_grid.h" + +// The creeps crawl along a wall, keeping level with their target, and shoot out from it: the Wall Creep (240, its +// Soy, Rag and Tainted Soy variants), the Rage Creep (241, which fires brimstone, and its split variant), the Blind +// Creep (242, which wanders) and The Thing (304, which bites what passes before it and leaves a trail of creep). +constexpr int SOY_CREEP = 1; +constexpr int RAG_CREEP = 2; +constexpr int TAINTED_SOY_CREEP = 3; +constexpr int SPLIT_RAGE_CREEP = 1; +constexpr int CREEP_ATTACK = NPC_STATE_ATTACK; + +// The walls, as i1 numbers them, and their facings. +enum CreepWall +{ + CREEP_WALL_TOP = 1, + CREEP_WALL_BOTTOM = 2, + CREEP_WALL_LEFT = 3, + CREEP_WALL_RIGHT = 4 +}; + +// The room's walls lie 5 in from its edges. On a side wall it hangs 25 up (the Rage Creep does not) and is wider. +constexpr float CREEP_WALL_INSET = 5; +constexpr float CREEP_FAR = 10000; +constexpr float CREEP_SIDE_LIFT = -25; +constexpr float CREEP_SIDE_WIDTH = 1.8f; +constexpr float CREEP_CRAWL_SPEED = 5; +constexpr ColorMod RAG_CREEP_SPLAT = {{1, 1, 1, 1}, {0.84f, 0.4f, 0.68f, 1}, {0, 0, 0}}; + +// It crawls toward its target's level (on a side wall 5 below it for the Wall Creep, 10 above for the Rage Creep, 15 +// below for the others), at its speed, the Soy Creep's 0.7 of it, the Rage Creep's half, the Blind Creep's quarter. +// Scared, it flees 50 a frame. It stops within 10. +constexpr float CREEP_FLEE = 50; +constexpr float CREEP_CONTROL_REACH = 100; +constexpr float CREEP_ARRIVED = 10; +constexpr float SOY_CREEP_PACE = 0.7f; +constexpr float RAGE_CREEP_PACE = 0.5f; +constexpr float BLIND_CREEP_PACE = 0.25f; +constexpr float WALL_CREEP_SIDE_AIM = 5; +constexpr float RAGE_CREEP_SIDE_AIM = -10; +constexpr float CREEP_SIDE_AIM = 15; +constexpr float CREEP_STOPPED = 0.0001f; +constexpr float CREEP_QUARTER_TURN = 1.5707964f; + +// It attacks once its wait (15 to 60 frames) is over, on screen, braced at a mass of 200. A confused one rarely does. +constexpr uint32_t CREEP_WAIT_SPREAD = 45; +constexpr int CREEP_WAIT = 15; +constexpr float CREEP_BRACED_MASS = 200; +constexpr uint32_t CREEP_CONFUSED_ODDS = 100; +constexpr float CREEP_CONTROL_RANGE = 1000; +constexpr int CREEP_CONTROL_RANGE_FRAMES = 7; + +// The shots out of the wall at 8, from their wall's mouth, kept 5 in the room. The Rag Creep's home in. +constexpr float CREEP_SHOT_SPEED = 8; +constexpr float CREEP_SHOT_MARGIN = 5; +constexpr float RAG_CREEP_HOMING = 0.8f; + +// The Soy Creep's spray: a stream of milky shots for 90 frames, one every other frame (every third for the Tainted +// Soy Creep, four at a time), scattered 4 across and given random falls and sizes, each with a poof. +constexpr int SOY_SPRAY_FRAMES = 90; +constexpr int SOY_CONTROL_STOP_LOW = 2; +constexpr uint32_t SOY_CONTROL_STOP_SPAN = 73; +constexpr int SOY_PERIOD = 2; +constexpr int TAINTED_SOY_PERIOD = 3; +constexpr float SOY_SHOT_HEIGHT = 12; +constexpr float SOY_SHOT_FALL = 2; +constexpr float SOY_SHOT_ACCEL = 0.12f; +constexpr float SOY_SHOT_SCALE = 0.15f; +constexpr float TAINTED_SOY_SCALE = 0.1f; +constexpr float TAINTED_SOY_SPREAD = 2; +constexpr float TAINTED_SOY_LEAD = 0.25f; +constexpr float SOY_SCATTER = 4; +constexpr float SOY_SHOT_MARGIN = 3; +constexpr int SOY_SHOT_VARIANT = 4; +constexpr ColorMod SOY_SHOT_COLOR = {{1, 1, 1, 1}, {1, 1, 1, 1}, {0.8f, 0.7f, 0.5f}}; +constexpr float SOY_POOF_LIFT = -11; +constexpr float SOY_POOF_DEPTH = 15; +constexpr float SOY_SPRAY_PITCH = 1.2f; + +// The Rage Creep's beam out of the wall for 45 frames (the split one's two, 30 apart), warned by a tracer. +constexpr int RAGE_BEAM_TIMEOUT = 45; +constexpr float RAGE_BEAM_DEPTH = 1000; +constexpr float SPLIT_BEAM_TURN = 30; +constexpr float SPLIT_BEAM_GAP = 2; +constexpr ColorMod RAGE_TRACER_COLOR = {{0.6f, 0.05f, 0, 0.8f}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr int RAGE_TRACER_TIMEOUT = 18; +constexpr float RAGE_TRACER_SCALE = 4; + +// The Thing bites what lies in its line within 60 (80 on the top wall, 70 on a side), every other frame: 5 to an +// enemy, its contact damage to a player. Its bite leaves a line of creep 40 apart, every other frame for its first 10 +// (14 on a side wall) of 120. +constexpr float THING_REACH = 60; +constexpr float THING_TOP_REACH = 80; +constexpr float THING_SIDE_REACH = 70; +constexpr float THING_LINE = 25; +constexpr float THING_BITE_INTERVAL = 2; +constexpr float THING_ENEMY_BITE = 5; +constexpr int THING_BITE_COUNTDOWN = 30; +constexpr int THING_TRAIL_FRAMES = 120; +constexpr int THING_TRAIL_END = 110; +constexpr int THING_SIDE_TRAIL_END = 106; +constexpr float THING_TRAIL_STEP = 40; +constexpr float THING_TRAIL_SCATTER = 20; + +// The Thing's jaw (i2): shut, opening, open and biting, closing. +enum ThingJaw +{ + JAW_SHUT, + JAW_OPENING, + JAW_OPEN, + JAW_CLOSING +}; + +// A direction turned a quarter turn the way the original turns it, through the angle's cosine and sine. +static Vector vector_quarter_turn(Vector v) +{ + float cosine = std::cos(CREEP_QUARTER_TURN); + float sine = std::sin(CREEP_QUARTER_TURN); + return vector_make(cosine * v.x - sine * v.y, sine * v.x + cosine * v.y); +} + +// The room's walls as a creep crawls them. +struct CreepWalls +{ + float left = 0; + float top = 0; + float right = 0; + float bottom = 0; +}; + +static CreepWalls creep_walls_get() +{ + Room& room = *g_game->room; + return {room.topLeftPos.x + CREEP_WALL_INSET, room.topLeftPos.y + CREEP_WALL_INSET, + room.bottomRightPos.x - CREEP_WALL_INSET, room.bottomRightPos.y - CREEP_WALL_INSET}; +} + +static bool creep_is_soy(Entity_NPC& npc) +{ + return npc.type == ENTITY_WALL_CREEP && (npc.variant == SOY_CREEP || npc.variant == TAINTED_SOY_CREEP); +} + +static bool creep_is_scared(Entity_NPC& npc) +{ + return npc.HasEntityFlags(FLAG_FEAR | FLAG_SHRINK); +} + +// A side wall's hold: turned along it, hanging up off the floor (but the Rage Creep), wider, crawling up and down. +static void creep_side_cling(Entity_NPC& npc, CreepWall wall, float x) +{ + npc.targetPosition = vector_make(x, npc.pos.y); + npc.i1 = wall; + npc.entityGridCollisionClass = GRIDCOLL_WALLS_Y; + npc.sprite.rotation = wall == CREEP_WALL_LEFT ? -90 : 90; + if (npc.type != ENTITY_RAGE_CREEP) npc.posOffset = vector_make(0, CREEP_SIDE_LIFT); + npc.sizeMulti.x = CREEP_SIDE_WIDTH; + npc.v1 = vector_make(0, CREEP_CRAWL_SPEED); +} + +// A top or bottom wall's hold: turned along it, crawling sideways. +static void creep_level_cling(Entity_NPC& npc, CreepWall wall, float y) +{ + npc.targetPosition = vector_make(npc.pos.x, y); + npc.i1 = wall; + npc.entityGridCollisionClass = GRIDCOLL_WALLS_X; + npc.sprite.rotation = wall == CREEP_WALL_TOP ? 0 : 180; + npc.posOffset = {}; + npc.v1 = vector_make(CREEP_CRAWL_SPEED, 0); +} + +// The first frame: it clings to the nearest wall (the first of left, right, top and bottom on a tie). +static void creep_init(Entity_NPC& npc, const CreepWalls& walls) +{ + float best = CREEP_FAR; + if (std::abs(walls.left - npc.pos.x) < best) + { + best = std::abs(walls.left - npc.pos.x); + creep_side_cling(npc, CREEP_WALL_LEFT, walls.left); + } + if (std::abs(walls.right - npc.pos.x) < best) + { + best = std::abs(walls.right - npc.pos.x); + creep_side_cling(npc, CREEP_WALL_RIGHT, walls.right); + } + if (std::abs(walls.top - npc.pos.y) < best) + { + best = std::abs(walls.top - npc.pos.y); + creep_level_cling(npc, CREEP_WALL_TOP, walls.top); + } + if (std::abs(walls.bottom - npc.pos.y) < best) creep_level_cling(npc, CREEP_WALL_BOTTOM, walls.bottom); + + npc.pos = npc.targetPosition; + npc.sprite.Play("Walk"); + npc.state = NPC_STATE_MOVE; + if (npc.type == ENTITY_WALL_CREEP && npc.variant == RAG_CREEP) npc.splatColor = RAG_CREEP_SPLAT; +} + +// A shot's mouth and velocity out of its wall. +struct CreepShot +{ + Vector offset{}; + Vector velocity{}; +}; + +static CreepShot creep_shot_get(int wall, float sideDrop) +{ + switch (wall) + { + case CREEP_WALL_TOP: + return {vector_make(0, 4), vector_make(0, CREEP_SHOT_SPEED)}; + case CREEP_WALL_BOTTOM: + return {vector_make(0, -12), vector_make(0, -CREEP_SHOT_SPEED)}; + case CREEP_WALL_LEFT: + return {vector_make(0, sideDrop), vector_make(CREEP_SHOT_SPEED, 0)}; + case CREEP_WALL_RIGHT: + return {vector_make(4, sideDrop), vector_make(-CREEP_SHOT_SPEED, 0)}; + } + return {}; +} + +// The angle its beams leave its wall at. +static float creep_wall_angle(int wall) +{ + switch (wall) + { + case CREEP_WALL_TOP: + return 90; + case CREEP_WALL_BOTTOM: + return -90; + case CREEP_WALL_RIGHT: + return 180; + } + return 0; +} + +// One drop of the Soy Creep's spray, with its poof. +static void soy_shot_fire(Entity_NPC& npc) +{ + Vector from = npc.pos; + Vector velocity{}; + switch (npc.i1) + { + case CREEP_WALL_TOP: + velocity.y = CREEP_SHOT_SPEED; + from.y += 4; + break; + case CREEP_WALL_BOTTOM: + velocity.y = -CREEP_SHOT_SPEED; + from.y += 10; + break; + case CREEP_WALL_LEFT: + velocity.x = CREEP_SHOT_SPEED; + from.y -= 10; + break; + case CREEP_WALL_RIGHT: + from.x += 4; + velocity.x = -CREEP_SHOT_SPEED; + from.y -= 10; + break; + } + + ProjectileParams params; + params.heightModifier += SOY_SHOT_HEIGHT; + params.fallingSpeedModifier = (random_unit() - 0.5f) * SOY_SHOT_FALL; + params.fallingAccelModifier -= SOY_SHOT_ACCEL; + params.scale = random_unit() * SOY_SHOT_SCALE + SOY_SHOT_SCALE; + params.color = SOY_SHOT_COLOR; + params.variant = SOY_SHOT_VARIANT; + Vector across = vector_quarter_turn(vector_normalized(velocity)); + from = vector_add(from, vector_scale(across, (random_unit() - 0.5f) * SOY_SCATTER)); + + ProjectilesMode mode = PROJECTILES_SINGLE; + if (npc.variant == TAINTED_SOY_CREEP) + { + params.scale += TAINTED_SOY_SCALE; + mode = PROJECTILES_FOUR; + params.spread = TAINTED_SOY_SPREAD; + from = vector_add(from, vector_scale(velocity, TAINTED_SOY_LEAD)); + } + Room& room = *g_game->room; + npc.FireProjectiles(room.GetClampedPositionImpl(from, SOY_SHOT_MARGIN, SOY_SHOT_MARGIN, SOY_SHOT_MARGIN, SOY_SHOT_MARGIN), + velocity, mode, params); + + Entity* poof = g_game->Spawn({.position = from, .type = ENTITY_EFFECT, .variant = EFFECT_TEAR_POOF_VERYSMALL, .seed = Random()}); + poof->sprite.rotation = random_unit() * 360; + poof->sprite.color = SOY_SHOT_COLOR; + poof->posOffset = vector_make(0, SOY_POOF_LIFT); + poof->renderDepthOffset = SOY_POOF_DEPTH; + npc_sound_play(SOUND_TEARS_FIRE, 1, 2, SOY_SPRAY_PITCH); +} + +// The Soy Creep's attack: its spray loops for 90 frames after Shoot (cut short under control out of range), then +// ends. +static void soy_spray(Entity_NPC& npc) +{ + if (npc.projectileCooldown < 0) + { + if (npc_anim_is_done(npc)) npc.state = NPC_STATE_MOVE; + return; + } + + if (npc_anim_is_done(npc)) npc.sprite.Play("AttackLoop"); + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc.PlaySound(SOUND_SPIDER_SPIT_ROAR, 1, 2, false, SOY_SPRAY_PITCH); + npc.projectileCooldown = SOY_SPRAY_FRAMES; + } + if (npc.controllerID != -1 && (uint32_t)(npc.projectileCooldown - SOY_CONTROL_STOP_LOW) < SOY_CONTROL_STOP_SPAN && + !npc.IsTargetInAttackRange(CREEP_CONTROL_RANGE, CREEP_CONTROL_RANGE_FRAMES, false)) + npc.projectileCooldown = 1; + + int period = npc.variant == TAINTED_SOY_CREEP ? TAINTED_SOY_PERIOD : SOY_PERIOD; + for (int tick = 0; tick < npc_ticks_get(npc) && npc.projectileCooldown >= 1; tick++) + { + if (--npc.projectileCooldown < 1) + { + npc.sprite.Play("AttackEnd"); + npc.projectileCooldown = -1; + break; + } + if (npc.projectileCooldown % period == 1) soy_shot_fire(npc); + } +} + +// The Rage Creep's beam (the split one's two) out of its wall on Shoot. Whether it fired. +static bool rage_creep_fire(Entity_NPC& npc) +{ + if (!npc.sprite.IsEventTriggered("Shoot")) return false; + + float angle = creep_wall_angle(npc.i1); + Vector mouth = vector_add(npc.pos, npc.posOffset); + auto fire = [&](Vector from, float beamAngle) { + Entity_Laser* laser = Entity_Laser::ShootAngle({.position = from, + .source = &npc, + .angleDegrees = beamAngle, + .timeout = RAGE_BEAM_TIMEOUT, + .variant = LASER_THICK_RED}); + laser->renderDepthOffset = RAGE_BEAM_DEPTH; + laser->Update(); + }; + if (npc.variant == SPLIT_RAGE_CREEP) + { + Vector gap = vector_scale(vector_from_angle(angle + 90), SPLIT_BEAM_GAP); + fire(vector_sub(mouth, gap), angle - SPLIT_BEAM_TURN); + fire(vector_add(mouth, gap), angle + SPLIT_BEAM_TURN); + } + else fire(mouth, angle); + return true; +} + +// The attack by kind, then held in place until its animation ends. +static void creep_attack(Entity_NPC& npc) +{ + bool isSound = false; + if (npc.type == ENTITY_WALL_CREEP && creep_is_soy(npc)) + { + soy_spray(npc); + isSound = npc.sprite.animState.animData && npc.sprite.IsEventTriggered("Sound"); + } + else if (npc.type == ENTITY_WALL_CREEP) + { + if (npc.sprite.IsEventTriggered("Shoot")) + { + CreepShot shot = creep_shot_get(npc.i1, -5); + ProjectileParams params; + if (npc.variant == RAG_CREEP) + { + params.bulletFlags |= PROJECTILE_SMART; + params.homingStrength = RAG_CREEP_HOMING; + } + Vector from = g_game->room->GetClampedPosition(vector_add(npc.pos, shot.offset), CREEP_SHOT_MARGIN); + npc.FireProjectiles(from, shot.velocity, PROJECTILES_SINGLE, params); + } + isSound = npc.sprite.animState.animData && npc.sprite.IsEventTriggered("Sound"); + } + else if (npc.type == ENTITY_RAGE_CREEP) isSound = rage_creep_fire(npc); + else if (npc.type == ENTITY_BLIND_CREEP) + { + if (npc.sprite.IsEventTriggered("Shoot")) + { + CreepShot shot = creep_shot_get(npc.i1, 0); + ProjectileParams params; + Room& room = *g_game->room; + Vector from = room.GetClampedPositionImpl(vector_add(npc.pos, shot.offset), CREEP_SHOT_MARGIN, + CREEP_SHOT_MARGIN, CREEP_SHOT_MARGIN, CREEP_SHOT_MARGIN); + npc.FireProjectiles(from, shot.velocity, PROJECTILES_THREE, params); + npc.PlaySound(SOUND_SPIDER_SPIT_ROAR, 1, 2, false, 1); + } + if ((Random() & 1) == 0) + { + if (npc.i1 < CREEP_WALL_LEFT) npc.v1.x = -npc.v1.x; + else npc.v1.y = -npc.v1.y; + } + } + if (isSound) npc.PlaySound(SOUND_SPIDER_SPIT_ROAR, 1, 2, false, 1); + + npc.velocity = vector_sub(npc.targetPosition, npc.pos); + if (!npc_anim_is_done(npc)) return; + npc.state = NPC_STATE_MOVE; + npc.mass = npc.config->mass; +} + +// Its pace along its wall: the kind's share of its crawl, scaled by its controller's push. +static Vector creep_pace(Entity_NPC& npc, float push) +{ + switch (npc.type) + { + case ENTITY_WALL_CREEP: + return vector_scale(creep_is_soy(npc) ? vector_scale(npc.v1, SOY_CREEP_PACE) : npc.v1, push); + case ENTITY_RAGE_CREEP: + return vector_scale(npc.v1, push * RAGE_CREEP_PACE); + case ENTITY_BLIND_CREEP: + return vector_scale(npc.v1, push * BLIND_CREEP_PACE); + default: + return vector_scale(npc.v1, push); + } +} + +// Crawling along a wall toward its target's level, the Blind Creep bouncing between the corners instead. Its sprite +// faces along its crawl. +static void creep_crawl(Entity_NPC& npc, const CreepWalls& walls, Vector away, float push) +{ + switch (npc.i1) + { + case CREEP_WALL_TOP: + npc.pos.y = walls.top; + break; + case CREEP_WALL_BOTTOM: + npc.pos.y = walls.bottom; + break; + case CREEP_WALL_LEFT: + npc.pos.x = walls.left; + break; + case CREEP_WALL_RIGHT: + npc.pos.x = walls.right; + break; + } + + if (npc.controllerID != -1) npc.targetPosition = vector_sub(npc.pos, away); + else if (!creep_is_scared(npc)) npc.targetPosition = npc.CalcTargetPosition(0); + else npc.targetPosition = vector_add(npc.pos, vector_resized(away, CREEP_FLEE)); + + bool isLevel = npc.i1 < CREEP_WALL_LEFT; + bool isBlind = npc.type == ENTITY_BLIND_CREEP && npc.controllerID == -1; + if (isBlind) + { + float& along = isLevel ? npc.pos.x : npc.pos.y; + float low = (isLevel ? walls.left : walls.top) + npc.size; + float high = (isLevel ? walls.right : walls.bottom) - npc.size; + float clamped = std::min(std::max(along, low), high); + if (clamped != along) + { + float& speed = isLevel ? npc.v1.x : npc.v1.y; + speed = -speed; + along = clamped; + } + npc.velocity = vector_scale(npc.v1, BLIND_CREEP_PACE); + } + else + { + float aim = npc.targetPosition.x; + if (!isLevel) + { + float lead = npc.type == ENTITY_WALL_CREEP ? WALL_CREEP_SIDE_AIM + : npc.type == ENTITY_RAGE_CREEP ? RAGE_CREEP_SIDE_AIM : CREEP_SIDE_AIM; + aim = (npc.controllerID != -1 ? 0 : lead) + npc.targetPosition.y; + } + float at = isLevel ? npc.pos.x : npc.pos.y; + float& speed = isLevel ? npc.v1.x : npc.v1.y; + if ((aim < at && speed > 0) || (at < aim && speed < 0)) speed = -speed; + if (std::abs(aim - at) > CREEP_ARRIVED) npc.velocity = creep_pace(npc, push); + } + + if (npc.i1 == CREEP_WALL_TOP) npc.sprite.isFlipX = npc.v1.x > 0; + else if (npc.i1 == CREEP_WALL_BOTTOM) npc.sprite.isFlipX = npc.v1.x < 0; + else if (npc.i1 == CREEP_WALL_LEFT) npc.sprite.isFlipY = npc.v1.y > 0; + else npc.sprite.isFlipY = npc.v1.y < 0; +} + +// The Thing's bite: every other frame it hurts what lies in its line within reach. +static void thing_bite(Entity_NPC& npc) +{ + float reach = npc.i1 == CREEP_WALL_TOP ? THING_TOP_REACH : npc.i1 >= CREEP_WALL_LEFT ? THING_SIDE_REACH : THING_REACH; + if (npc.GetIntervalTicks(THING_BITE_INTERVAL, 0) == 0 || creep_is_scared(npc)) return; + + float angle = npc.sprite.rotation * DEGREES_TO_RADIANS; + for (Entity* other : entity_query_radius(npc.pos, reach, QUERY_ALL)) + { + if (other->entityCollisionClass == ENTCOLL_NONE || other == &npc) continue; + + Vector offset = vector_sub(npc.pos, other->pos); + if (std::abs(std::cos(angle) * offset.x - std::sin(angle) * offset.y) >= THING_LINE) continue; + + bool isPlayerSide = other->type == ENTITY_PLAYER || other->type == ENTITY_FAMILIAR; + if (isPlayerSide && npc.IsHostileTo(other)) + { + other->TakeDamage(npc.collisionDamage, 0, EntityRef(&npc), THING_BITE_COUNTDOWN); + continue; + } + bool isVersusPlayer = g_game->deathmatchManager.is_active() && other->type == ENTITY_PLAYER; + bool isEnemy = other->type >= ENTITY_FIRST_ENEMY && other->type <= ENTITY_LAST_ENEMY; + if ((isVersusPlayer || isEnemy) && npc.IsHostileTo(other)) + other->TakeDamage(THING_ENEMY_BITE, 0, EntityRef(&npc), THING_BITE_COUNTDOWN); + } +} + +// The Thing's jaw: it bites while open, starting its creep trail, and leaves the trail out along its facing. +static void thing_jaw_update(Entity_NPC& npc) +{ + AnimationState& animation = npc.sprite.animState; + if (animation.animData && !animation.isPlaying) + { + if (npc.sprite.GetAnimation() == "Attack") npc.i2 = JAW_OPEN; + else if (npc.sprite.GetAnimation() == "PutAway") npc.i2 = JAW_SHUT; + } + if (npc.i2 == JAW_OPEN) + { + thing_bite(npc); + if (npc.projectileCooldown < 1) + { + npc.projectileCooldown = THING_TRAIL_FRAMES; + npc.v2 = npc.pos; + npc.PlaySound(SOUND_SPIDER_SPIT_ROAR, 1, 2, false, 1); + } + } + + int trailEnd = npc.i1 < CREEP_WALL_LEFT ? THING_TRAIL_END : THING_SIDE_TRAIL_END; + for (int tick = 0; tick < npc_ticks_get(npc) && npc.projectileCooldown >= 1; tick++) + { + if (npc.projectileCooldown > trailEnd && npc.projectileCooldown % 2 == 0) + { + Vector facing = vector_from_angle(npc.sprite.rotation + 90); + Vector across = vector_quarter_turn(facing); + float scatter = (random_unit() - 0.5f) * THING_TRAIL_SCATTER; + float out = (float)((THING_TRAIL_FRAMES - npc.projectileCooldown) / 2) * THING_TRAIL_STEP; + Vector at = vector_add(npc.v2, vector_add(vector_scale(across, scatter), vector_scale(facing, out))); + Entity* creep = g_game->Spawn({.position = at, .spawner = &npc, .type = ENTITY_EFFECT, .variant = EFFECT_CREEP_RED, .seed = Random()}); + creep->Update(); + } + npc.projectileCooldown--; + } +} + +// Its crawl animation: walking, or still on its first frame when stopped. The Thing keeps its jaw's loops. +static void creep_walk_animate(Entity_NPC& npc) +{ + bool isStopped = vector_length_squared(npc.velocity) <= CREEP_STOPPED; + bool isThing = npc.type == ENTITY_THE_THING; + if (isThing && npc.i2 == JAW_OPEN) return npc.sprite.Play(isStopped ? "AttackLoopIdle" : "AttackLoopWalk"); + if (isThing && npc.i2 != JAW_SHUT) return; + if (!isStopped) return npc.sprite.Play("Walk"); + + if (npc.sprite.SetAnimation("Walk", SWITCH_KEEP_FRAME) && npc.sprite.animState.animData) + { + npc.sprite.animState.SetFrameFloat(0); + npc.sprite.animState.isPlaying = false; + } +} + +// The Thing opens its jaw at a target in its line, and closes it once the target leaves. +static void thing_jaw_decide(Entity_NPC& npc, Vector away) +{ + float angle = npc.sprite.rotation * DEGREES_TO_RADIANS; + float offLine = std::cos(angle) * away.x - std::sin(angle) * away.y; + bool isInLine = npc.controllerID == -1 ? std::abs(offLine) < THING_LINE + : npc.IsTargetInAttackRange(CREEP_CONTROL_RANGE, CREEP_CONTROL_RANGE_FRAMES, false); + if (isInLine && npc.i2 == JAW_SHUT) + { + npc.PlaySound(SOUND_BOSS_LITE_HISS, 1, 2, false, 1); + npc.sprite.Play("Attack"); + npc.i2 = JAW_OPENING; + return; + } + if (isInLine || npc.i2 != JAW_OPEN) return; + + npc.sprite.Play("PutAway"); + npc.i2 = JAW_CLOSING; +} + +// A creep's attack start once its wait is over: on screen (the Blind Creep anywhere), braced, the Rage Creep warning +// of its beam. +static void creep_attack_start(Entity_NPC& npc) +{ + if (npc.stateFrame >= 0) return; + if (npc.HasEntityFlags(FLAG_CONFUSION) && Random() % CREEP_CONFUSED_ODDS != 0) return; + if (creep_is_scared(npc)) return; + if (npc.controllerID == -1) + { + if (!g_game->room->camera->IsPosVisible(npc.pos) && npc.type != ENTITY_BLIND_CREEP) return; + } + else if (!npc.IsTargetInAttackRange(CREEP_CONTROL_RANGE, CREEP_CONTROL_RANGE_FRAMES, false)) + return; + + npc.state = CREEP_ATTACK; + if (npc.type == ENTITY_RAGE_CREEP) + following_effect_spawn(npc, {.targetPosition = vector_from_angle(creep_wall_angle(npc.i1)), + .color = RAGE_TRACER_COLOR, + .scale = RAGE_TRACER_SCALE, + .timeout = RAGE_TRACER_TIMEOUT}); + if (creep_is_soy(npc)) + { + npc.sprite.Play("AttackStart"); + npc.projectileCooldown = 0; + } + else npc.sprite.Play("Attack"); + int wait = npc.controllerID == -1 ? (int)(Random() % CREEP_WAIT_SPREAD) : 0; + npc.mass = CREEP_BRACED_MASS; + npc.stateFrame = wait + CREEP_WAIT; + npc.targetPosition = npc.pos; +} + +// Crawling: along its wall after its target (or away when scared), then attacking once its wait runs out. +static void creep_move(Entity_NPC& npc, const CreepWalls& walls) +{ + if (!npc.sprite.animState.animData) npc.sprite.Play("Walk"); + + Vector away = vector_sub(npc.pos, npc.GetPlayerTarget()->pos); + float push = 1; + if (npc.controllerID != -1) + { + Vector input = npc.GetControllerInput(0); + push = vector_length(input); + away = vector_scale(input, -CREEP_CONTROL_REACH); + } + creep_crawl(npc, walls, away, push); + if (npc.type == ENTITY_THE_THING) thing_jaw_update(npc); + creep_walk_animate(npc); + + if (npc.stateFrame >= 0) npc.stateFrame -= npc_ticks_get(npc); + if (npc.type == ENTITY_THE_THING) return thing_jaw_decide(npc, away); + creep_attack_start(npc); +} + +// 0053c0d0 NpcAI::ENTITY_WALL_CREEP: the creeps cling to the nearest wall, crawl along it to stay level with their +// target and shoot, spray or fire brimstone out of it, and The Thing bites what passes before it. +void npc_wall_creep_update(Entity_NPC& npc) +{ + npc.velocity = {}; + CreepWalls walls = creep_walls_get(); + if (npc.state == NPC_STATE_INIT) return creep_init(npc, walls); + if (npc.state == NPC_STATE_MOVE) return creep_move(npc, walls); + if (npc.state == CREEP_ATTACK) creep_attack(npc); +} diff --git a/src/persistent_game_data.h b/src/persistent_game_data.h index ca97211..646a9be 100644 --- a/src/persistent_game_data.h +++ b/src/persistent_game_data.h @@ -13,6 +13,7 @@ constexpr int ACHIEVEMENT_COUNT = 642; // The achievements the game checks by id. constexpr int ACHIEVEMENT_THE_WOMB = 4; constexpr int ACHIEVEMENT_IT_LIVES = 34; +constexpr int ACHIEVEMENT_PLANETARIUMS = 406; constexpr int ACHIEVEMENT_THE_POLAROID = 57; constexpr int ACHIEVEMENT_THE_NEGATIVE = 78; constexpr int ACHIEVEMENT_KRAMPUS = 142; @@ -34,6 +35,10 @@ enum EventCounter : int EVENT_COUNTER_DEATHS = 10, EVENT_COUNTER_ISAAC_KILLS = 11, EVENT_COUNTER_SATAN_KILLS = 13, + EVENT_COUNTER_SHELL_GAMES_PLAYED = 14, + EVENT_COUNTER_BLOOD_DONATIONS = 17, + EVENT_COUNTER_SLOT_MACHINES_BROKEN = 18, + EVENT_COUNTER_DONATIONS = 20, EVENT_COUNTER_STREAK = 22, EVENT_COUNTER_BEST_STREAK = 23, EVENT_COUNTER_BLUE_BABY_KILLS = 24, @@ -48,6 +53,8 @@ enum EventCounter : int EVENT_COUNTER_DAILIES_PLAYED = 190, EVENT_COUNTER_MOTHER_KILLS = 491, EVENT_COUNTER_BEAST_KILLS = 492, + EVENT_COUNTER_BATTERY_BUMS_KILLED = 494, + EVENT_COUNTER_BATTERY_BUM_ITEMS = 495, EVENT_COUNTER_RUN_MASK_HIGH = 496, EVENT_COUNTER_ONLINE_BEST_STREAK = 498 }; diff --git a/src/player_hud.cpp b/src/player_hud.cpp index 64877a7..91bd3f7 100644 --- a/src/player_hud.cpp +++ b/src/player_hud.cpp @@ -14,6 +14,7 @@ #include #include #include +#include constexpr const char* HEARTS_PNG = "gfx/ui/ui_hearts.png"; constexpr const char* HEARTS_SMALL_PNG = "gfx/ui/ui_hearts_small.png"; @@ -28,6 +29,24 @@ constexpr const char* MANTLE_HOLY_MANTLE = "HolyMantle"; constexpr const char* MANTLE_HOLY_CARD = "HolyMantleHolyCard"; constexpr const char* EXTRA_LIVES_FORMAT = "x%d%s"; +// Tainted Isaac's inventory: the icons' frame, the step between slots, the icons' shadow, and ui_inventory's layers. +constexpr float INVENTORY_ICON_SIZE = 32; +constexpr float INVENTORY_STEP = 12; +constexpr float INVENTORY_DOT_ALPHA = 0.5f; +constexpr int INVENTORY_LAYER_DOT = 0; +constexpr int INVENTORY_LAYER_SELECT = 1; +constexpr ColorMod INVENTORY_SHADOW = {{0, 0, 0, 0.3f}, {0, 0, 0, 0}, {0, 0, 0}}; + +// Tainted Cain's crafting table: the result box faded while empty, its icon, and the bag's slots in rows of four. +constexpr const char* CRAFTING_RESULT_ANIMATION = "Result"; +constexpr ColorMod CRAFTING_EMPTY_COLOR = {{1, 1, 1, 0.5f}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr float CRAFTING_ICON_SIZE = 32; +constexpr float CRAFTING_STEP = 12; +constexpr float CRAFTING_SLOTS_X = 64; +constexpr float CRAFTING_SLOTS_Y = 6; +constexpr float CRAFTING_SLOT_REACH = 8; +constexpr int CRAFTING_COLUMNS = 4; + // The flash colors of HeartFlash, which add to a heart's color: red, soul, black, gold and rotten. constexpr std::array, HEART_FLASH_COUNT> HEART_FLASH_OFFSETS = {{{0, 0, 0}, {128 / 255.0f, 0, 0}, @@ -499,15 +518,47 @@ void PlayerHUD::pockets_update() } } -// The inventory icons of Update when the corner is redrawn: Tainted Isaac's inventory, or the Cantripped challenge's -// cards, else none. +// The inventory icons of Update when the corner is redrawn: Tainted Isaac's passives (an empty slot shows none, an +// active or unknown item is left out), or the Cantripped challenge's item cards, else none. An icon loaded before is +// reused, once per id. A glitched item keeps no image, and an item whose image fails to load is left out. +// The original reads the id of a card's missing item. Here that card is left out. void PlayerHUD::inventory_update() { - bool isCantripped = g_game->challenge == CHALLENGE_CANTRIPPED && !player->itemCards.empty(); + bool isInventory = player->playerType == PLAYER_ISAAC_B; + bool isCantripped = !isInventory && g_game->challenge == CHALLENGE_CANTRIPPED && !player->itemCards.empty(); + std::map loaded; - if (player->playerType == PLAYER_ISAAC_B || isCantripped) - reconstruction_missing("PlayerHUD::Update 00842230: Tainted Isaac's inventory and the Cantripped cards' icons"); + for (PlayerHUDIcon& icon : inventoryIcons) loaded.emplace(icon.id, icon.image); inventoryIcons.clear(); + auto icon_add = [&](int id) + { + ItemConfig_Item* item = g_manager->itemConfig.GetCollectible(id); + if (!item || (isInventory && item->type == ITEM_ACTIVE)) return; + if (auto cached = loaded.find(id); cached != loaded.end()) + { + inventoryIcons.push_back({cached->second, id}); + loaded.erase(cached); + } + else if (id < 0) inventoryIcons.push_back({nullptr, id}); + else if (KAGE::Graphics::ImagePtr image = Manager::LoadImage(item->gfxFilename)) inventoryIcons.push_back({image, id}); + }; + + if (isInventory) + { + for (int entry : player->inventory) + { + if (entry < 0) inventoryIcons.emplace_back(); + else icon_add(player->history.historyItems[entry].id); + } + } + else if (isCantripped) + { + for (uint32_t card : player->itemCards) + { + if (card == 0) inventoryIcons.emplace_back(); + else icon_add((int)card); + } + } isDirty = false; } @@ -1434,16 +1485,107 @@ void PlayerHUD::RenderPocketItems(Vector at, PlayerHudLayout layout, float alpha } } -// 00848d20 Draws Tainted Isaac's inventory. -void PlayerHUD::render_inventory(Vector, float) +// (00848c20) Draws an inventory or crafting icon in a quad: a glitched item through the procedural items. +static void inventory_icon_draw(const PlayerHUDIcon& icon, const KAGE::Graphics::ColorQuad& quad, const ColorMod& color) { - reconstruction_missing("PlayerHUD::render_inventory 00848d20"); + if (icon.id < 0) reconstruction_missing("GlitchedCollectibleGfx::render_item 009e0240: a TMTRAINER item's icon"); + if (!icon.image) return; + + apply_sprite_shader_params(color, SPRITE_SHADER_COLOR_APPLY, *icon.image); + icon.image->Render(KAGE::Graphics::source_quad_rect({}, vector_make(INVENTORY_ICON_SIZE, INVENTORY_ICON_SIZE)), quad, + kcolor_rgba(color._tint[0], color._tint[1], color._tint[2], color._tint[3])); } -// 00849510 Draws Tainted Cain's crafting bag. -void PlayerHUD::RenderCraftingTable(Vector, float) +// 00848d20 Draws Tainted Isaac's inventory in two rows: each held item's icon at half size over its shadow, shaken +// with the screen and widening the corner's bounds, or a faint dot for an empty slot. The first slot is marked as the +// one the next item replaces. +void PlayerHUD::render_inventory(Vector at, float inventoryScale) { - reconstruction_missing("PlayerHUD::RenderCraftingTable 00849510"); + ANM2& sprite = hud->inventorySprite; + int slots = player->GetMaxInventorySize(); + int columns = slots / 2; + float half = inventoryScale * INVENTORY_ICON_SIZE * 0.5f; + float inset = inventoryScale * INVENTORY_ICON_SIZE * 0.25f; + Vector shake = g_game->screenShakeOffset; + + sprite.scale = vector_make(inventoryScale, inventoryScale); + for (int slot = 0; slot < slots; slot++) + { + Vector cell = vector_make((float)(slot % columns) * INVENTORY_STEP * inventoryScale + at.x, + (float)(slot / columns) * INVENTORY_STEP * inventoryScale + at.y); + bool isShown = slot < (int)inventoryIcons.size() && (inventoryIcons[slot].image || inventoryIcons[slot].id < 0); + if (isShown) + { + const PlayerHUDIcon& icon = inventoryIcons[slot]; + KAGE::Graphics::manager.shader_default_set(); + Vector size = vector_make(half, half); + Vector spot = vector_make(cell.x + shake.x, cell.y + shake.y); + inventory_icon_draw(icon, KAGE::Graphics::color_quad_rect(vector_make(spot.x + inventoryScale, spot.y + inventoryScale), + size, kcolor_rgba(1, 1, 1, 1)), + INVENTORY_SHADOW); + KAGE::Graphics::ColorQuad quad = KAGE::Graphics::color_quad_rect(spot, size, kcolor_rgba(1, 1, 1, 1)); + inventory_icon_draw(icon, quad, COLOR_DEFAULT); + for (Vector corner : {quad._topLeft, quad._bottomRight}) + { + boundsMin = vector_make(std::min(boundsMin.x, corner.x), std::min(boundsMin.y, corner.y)); + boundsMax = vector_make(std::max(boundsMax.x, corner.x), std::max(boundsMax.y, corner.y)); + } + } + else + { + sprite.GetLayer(INVENTORY_LAYER_DOT)->color._tint[3] = INVENTORY_DOT_ALPHA; + sprite.RenderLayer(INVENTORY_LAYER_DOT, {vector_make(inset + cell.x, inset + cell.y)}); + } + if (slot == 0) sprite.RenderLayer(INVENTORY_LAYER_SELECT, {vector_make(inset + cell.x, cell.y + inset)}); + } + KAGE::Graphics::manager.shader_default_set(); +} + +// Shows a frame of the crafting table sprite's animation, stopped there. +static void crafting_frame_set(ANM2& sprite, std::string_view animation, float frame) +{ + if (!sprite.SetAnimation(animation) || !sprite.animState.animData) return; + sprite.animState.SetFrameFloat(frame); + sprite.animState.isPlaying = false; +} + +// 00849510 Draws Tainted Cain's crafting bag: the result box, faint while the bag makes nothing, else with the item's +// icon over its shadow, then the bag's eight pickups in two rows, each widening the corner's bounds. The Cantripped +// challenge's card table is not written yet. +void PlayerHUD::RenderCraftingTable(Vector at, float tableScale) +{ + ANM2& sprite = hud->craftingTableSprite; + if (g_game->challenge == CHALLENGE_CANTRIPPED) + reconstruction_missing("PlayerHUD::RenderCraftingTable 00849510 (the Cantripped cards)"); + + sprite.scale = vector_make(tableScale, tableScale); + crafting_frame_set(sprite, CRAFTING_RESULT_ANIMATION, 0); + if (!craftingResultImage) sprite.color = CRAFTING_EMPTY_COLOR; + sprite.Render({at}); + sprite.color = COLOR_DEFAULT; + if (craftingResultImage) + { + Vector shake = g_game->screenShakeOffset; + float half = tableScale * CRAFTING_ICON_SIZE * 0.5f; + float size = tableScale * CRAFTING_ICON_SIZE; + KAGE::Graphics::ColorQuad quad = KAGE::Graphics::color_quad_rect( + vector_make(at.x + shake.x - half, at.y + shake.y - half), vector_make(size, size), kcolor_rgba(1, 1, 1, 1)); + KAGE::Graphics::manager.shader_default_set(); + for (const ColorMod& color : {INVENTORY_SHADOW, COLOR_DEFAULT}) + inventory_icon_draw({craftingResultImage, 0}, quad, color); + } + + float reach = tableScale * CRAFTING_SLOT_REACH; + for (int slot = 0; slot < BAG_OF_CRAFTING_SIZE; slot++) + { + Vector spot = vector_make(((float)(slot % CRAFTING_COLUMNS) * CRAFTING_STEP - CRAFTING_SLOTS_X) * tableScale + at.x, + ((float)(slot / CRAFTING_COLUMNS) * CRAFTING_STEP - CRAFTING_SLOTS_Y) * tableScale + at.y); + crafting_frame_set(sprite, "Idle", (float)player->bagOfCraftingContent[slot]); + sprite.Render({spot}); + boundsMin = vector_make(std::min(boundsMin.x, spot.x - reach), std::min(boundsMin.y, spot.y - reach)); + boundsMax = vector_make(std::max(boundsMax.x, spot.x + reach), std::max(boundsMax.y, spot.y + reach)); + } + KAGE::Graphics::manager.shader_default_set(); } // 0084a3e0 Draws Tainted ???'s poop spell queue. diff --git a/src/player_stats.h b/src/player_stats.h index 07b62dc..2a57477 100644 --- a/src/player_stats.h +++ b/src/player_stats.h @@ -15,6 +15,7 @@ enum OnlineStat : int ONLINE_STAT_DAMAGE_TAKEN = 3, ONLINE_STAT_DEAL_DEATHS = 4, ONLINE_STAT_ESCAPES = 9, + ONLINE_STAT_TRANSFORMATIONS = 10, ONLINE_STAT_REVIVES = 12, ONLINE_STAT_COINS_SPENT = 13, ONLINE_STAT_FIRES_PUT_OUT = 14, diff --git a/src/room.cpp b/src/room.cpp index 14e57bb..55c403a 100644 --- a/src/room.cpp +++ b/src/room.cpp @@ -202,14 +202,15 @@ constexpr int ROOM_MINESHAFT_IDX = -101; constexpr int ACHIEVEMENT_MEGA_SATAN = 155; // The effects pressure plates and rain spawn, and a minecart on its rail. -constexpr int EFFECT_RAIN_DROP = 135; constexpr int MINECART_VERTICAL = 4; constexpr float MINECART_SPEED = 0.2f; -// The rain's spots: kept off the walls, where the light is bright enough, their ellipses' radii, and how fast a -// stopped rain fades. +// The rain's spots: kept off the walls, where the light is bright enough (the lighting layer at screen scale), their +// ellipses' radii, and how fast a stopped rain fades. constexpr float RAIN_MARGIN = 20; constexpr float RAIN_LIGHT_MIN = 0.6f; +constexpr float RAIN_LIGHT_THIRD = 0.333f; +constexpr float LIGHT_LAYER_SCALE = 0.65f; constexpr float RAIN_RADIUS_MIN = 20; constexpr float RAIN_RADIUS_RANGE = 60; constexpr float RAIN_FADE = 0.02f; @@ -229,7 +230,6 @@ constexpr float COLOR_MODIFIER_RATE = 0.015f; // The collectibles, trinkets, seeds and challenges Room checks. constexpr int COLLECTIBLE_INFESTATION = 148; -constexpr int COLLECTIBLE_INFESTATION_2 = 234; constexpr int COLLECTIBLE_THE_STAIRWAY = 586; constexpr int COLLECTIBLE_ISAACS_TOMB = 701; constexpr int COLLECTIBLE_CARD_READING = 660; @@ -2540,14 +2540,28 @@ void Room::attach_minecarts() } } -// How bright the lighting layer is at a point of the room, the light rain falls in: none without the layer. -// Reading it needs the layer image's pixels, which the renderer does not keep. -static float fx_light_get(Room& room) +// 00995f40 The lighting layer's color at a point of the room: the texel its first tile shows there, mirrored with that +// tile and shifted by its velocity. Black without a lighting layer. +// A point left of or above the image wraps to a texel past it (white), as the original's conversion does. +static KColor fx_light_get(Room& room, Vector point) { - for (const FXLayer& layer : room.fxLayers.layers) - if (room.fxLayers.isLoaded && layer.type == FX_LAYER_LIGHTING && !layer.tiles.empty()) - reconstruction_missing("Room::init_rain 00824350: the lighting layer's pixel (FUN_00995f40)"); - return 0; + FXLayers& fx = room.fxLayers; + if (!fx.isLoaded) return kcolor_rgba(0, 0, 0, 1); + + for (const FXLayer& layer : fx.layers) + { + if (layer.type != FX_LAYER_LIGHTING || layer.tiles.empty() || !layer.image) continue; + + const FXTile& tile = layer.tiles[0]; + float x = (point.x - (fx.roomBottomRight.x + fx.roomTopLeft.x) * 0.5f) * LIGHT_LAYER_SCALE; + float y = (point.y - (fx.roomTopLeft.y + fx.roomBottomRight.y) * 0.5f) * LIGHT_LAYER_SCALE; + if (tile.isFlipX) x = -x; + if (tile.isFlipY) y = -y; + float texelY = (float)layer.image->height * 0.5f + y - tile.velocity.y; + float texelX = (float)layer.image->width * 0.5f + x - tile.velocity.x; + return image_texel_get(*layer.image, (uint32_t)(int64_t)texelX, (uint32_t)(int64_t)texelY); + } + return kcolor_rgba(0, 0, 0, 1); } // 00824350 Starts the rain of a watery Downpour, Dross or flooded Corpse room: up to four spots it falls around (four @@ -2578,7 +2592,8 @@ void Room::init_rain() float y = (bottomRightPos.y - RAIN_MARGIN - top) * (float)rng.Next() * 2.3283062e-10f + top; float left = topLeftPos.x + RAIN_MARGIN; float x = (bottomRightPos.x - RAIN_MARGIN - left) * (float)rng.Next() * 2.3283062e-10f + left; - if (fx_light_get(*this) < RAIN_LIGHT_MIN) continue; + KColor light = fx_light_get(*this, vector_make(x, y)); + if ((light._green + light._red + light._blue) * RAIN_LIGHT_THIRD < RAIN_LIGHT_MIN) continue; float angle = (float)rng.Next() * 2.3283062e-10f * 360 * DEGREES_TO_RADIANS; float cosine = std::cos(angle); diff --git a/src/room_clear.cpp b/src/room_clear.cpp index ccac9c5..5125d5f 100644 --- a/src/room_clear.cpp +++ b/src/room_clear.cpp @@ -86,6 +86,19 @@ constexpr int ACHIEVEMENT_CHAD = 17; constexpr int ACHIEVEMENT_GISH = 18; constexpr int ACHIEVEMENT_ANGELS = 155; +// The endings' unlocks: Judas for Satan; the Lamb's run under 20 minutes (ZIP!), without a heart, bomb or coin picked +// up (It's the key), the gate to the Void, and the first three victory laps (Once more with feeling!, Butter, RERUN). +constexpr int ACHIEVEMENT_JUDAS = 3; +constexpr int ACHIEVEMENT_ZIP = 326; +constexpr int ACHIEVEMENT_ITS_THE_KEY = 327; +constexpr int ACHIEVEMENT_GATE_IS_OPEN = 348; +constexpr std::array VICTORY_LAP_UNLOCKS = {321, 360, ACHIEVEMENT_RERUN}; +constexpr int ZIP_FRAMES = 36000; + +// A Cathedral or Sheol kill opens a Void portal one time in 100 below 15 (unless the run ends in the Void). +constexpr uint32_t FINAL_VOID_PORTAL_PERCENT = 15; +constexpr uint32_t FINAL_VOID_PORTAL_ROLL = 100; + // The unlocks of reaching a floor's last boss without damage since a floor: Basement Boy and Sprinkler, Spelunker Boy // and Telekinesis, Dark Boy and Leprosy, Mama's Boy and Pop!, and Dead Boy. struct NoDamageUnlock @@ -979,6 +992,90 @@ static void womb_award_spawn(Room& room, ClearAward& award, int stage, bool isCo void_portal_spawn(room, award); } +// The big chest a final floor's boss leaves on the room's cleared middle, or a trophy once a challenge ends here. +static void final_chest_spawn(Room& room, ClearAward& award, bool isContinuing) +{ + Vector spot = award.reward; + reward_spot_clear(room, spot); + if (!isContinuing) + { + g_game->Spawn({.position = spot, .type = ENTITY_PICKUP, .variant = PICKUP_TROPHY, .seed = Random()}); + return; + } + g_manager->achievementOverlay.isPopupBlocked = true; + g_game->Spawn({.position = spot, .type = ENTITY_PICKUP, .variant = PICKUP_BIGCHEST, .seed = award.rng.Next()}); +} + +// Opens the save for a victory lap's unlock (unless achievements are off this run), then closes it again. +static void victory_lap_unlock(int achievement) +{ + PersistentGameData& data = g_manager->persistentGameData; + data.SetReadOnly(Manager::AchievementUnlocksDisallowed()); + data.TryUnlock(achievement); + data.SetReadOnly(true); +} + +// Satan's and Isaac's floor: the mark and the kill count (Satan's first unlocks Judas), the chest, and one time in +// 100 below 15 a Void portal, unless the challenge ends in the Void. +static void sheol_award_spawn(Room& room, ClearAward& award, bool isContinuing) +{ + PersistentGameData& data = g_manager->persistentGameData; + bool isSheol = g_game->stageType == STAGETYPE_ORIGINAL; + PlayerManager::unlock_completion_mark(isSheol ? COMPLETION_SATAN : COMPLETION_ISAAC); + if (isSheol) data.TryUnlock(ACHIEVEMENT_JUDAS); + data.IncreaseEventCounter(isSheol ? EVENT_COUNTER_SATAN_KILLS : EVENT_COUNTER_ISAAC_KILLS, 1); + + final_chest_spawn(room, award, isContinuing); + bool isPortalRolled = g_game->GetChallengeParams().endStage != STAGE_VOID && + award.rng.RandomInt(FINAL_VOID_PORTAL_ROLL) < FINAL_VOID_PORTAL_PERCENT; + if (isPortalRolled && isContinuing && is_void_reachable()) void_portal_spawn(room, award); +} + +// The Lamb's and ???'s floor: the mark and the kill count, and for the Lamb the gate to the Void, the speed and thrift +// unlocks, the victory laps' unlocks and, outside challenges, the victory lap's prompt. Then the chest (none when the +// challenge ends in the Void) and a Void portal where the run may go there. +static void dark_room_award_spawn(Room& room, ClearAward& award, bool isContinuing) +{ + Game& game = *g_game; + PersistentGameData& data = g_manager->persistentGameData; + if (game.stageType != STAGETYPE_ORIGINAL) + { + PlayerManager::unlock_completion_mark(COMPLETION_BLUE_BABY); + data.IncreaseEventCounter(EVENT_COUNTER_BLUE_BABY_KILLS, 1); + } + else + { + PlayerManager::unlock_completion_mark(COMPLETION_LAMB); + data.IncreaseEventCounter(EVENT_COUNTER_LAMB_KILLS, 1); + data.TryUnlock(ACHIEVEMENT_GATE_IS_OPEN); + if (game.timeCounter < ZIP_FRAMES) data.TryUnlock(ACHIEVEMENT_ZIP); + if (!game.GetStateFlag((GameStateFlag)GAME_STATE_HEART_BOMB_COIN_PICKED)) data.TryUnlock(ACHIEVEMENT_ITS_THE_KEY); + for (int lap = 0; lap < (int)VICTORY_LAP_UNLOCKS.size(); lap++) + if (game.victoryLap > lap) victory_lap_unlock(VICTORY_LAP_UNLOCKS[lap]); + if (game.challenge == 0 && game.dailyChallenge._id == 0 && !game.IsGreedMode()) + game.genericPrompt.Show(PROMPT_LOCAL); + } + + if (game.GetChallengeParams().endStage != STAGE_VOID) final_chest_spawn(room, award, isContinuing); + if (isContinuing && is_void_reachable()) void_portal_spawn(room, award); +} + +// Mega Satan: the kill counts and marks. Unless the challenge is to beat him, the run ends at once with his ending, or +// where it goes on to the Void a big chest and a Void portal come. A Mega Satan challenge's end leaves a trophy. +static void mega_satan_award_spawn(Room& room, ClearAward& award, bool isContinuing) +{ + Game& game = *g_game; + g_manager->persistentGameData.IncreaseEventCounter(EVENT_COUNTER_MEGA_SATAN_KILLS, 1); + g_manager->persistentGameData.AddBoss(BOSS_MEGA_SATAN_ID); + PlayerManager::unlock_completion_mark(COMPLETION_MEGA_SATAN); + if (game.GetChallengeParams().isMegaSatan) return final_chest_spawn(room, award, false); + if (!isContinuing || !is_void_reachable()) return game_end(ENDING_MEGA_SATAN); + + g_manager->achievementOverlay.isPopupBlocked = true; + game.Spawn({.position = award.reward, .type = ENTITY_PICKUP, .variant = PICKUP_BIGCHEST, .seed = award.rng.Next()}); + void_portal_spawn(room, award); +} + // The kill records a boss clear keeps: each floor's boss kills (Steven, Chad and Gish at 40 Basement, 30 Caves and // 20 Depths kills), the first Monstro's Lung, Lil Chubby and angel unlocks, and the no-damage runs to a last boss. static void boss_kill_records(int stage, bool isLastBoss) @@ -1020,7 +1117,7 @@ static int boss_stage_get() } // A boss room's award: Boss Rush's records, the pits some layouts fill, the co-op ghosts revived at the last boss, -// the trapdoor and the boss's items. The endings past the Womb are not reconstructed yet. +// the trapdoor and the boss's items, and past the Womb the endings and their chests. The Void's are not yet. static void boss_award_spawn(Room& room, ClearAward& award) { Game& game = *g_game; @@ -1060,7 +1157,10 @@ static void boss_award_spawn(Room& room, ClearAward& award) else if (stage == STAGE_DEPTHS_II && room.bossId != BOSS_MEGA_SATAN_ID) moms_award_spawn(room, award, isContinuing); else if ((stage == STAGE_WOMB_II || stage == STAGE_BLUE_WOMB) && room.bossId != BOSS_MEGA_SATAN_ID) womb_award_spawn(room, award, stage, isContinuing); - else reconstruction_missing("Room::SpawnClearAward 007fb250: the final bosses' endings and chests"); + else if (room.bossId == BOSS_MEGA_SATAN_ID) mega_satan_award_spawn(room, award, isContinuing); + else if (stage == STAGE_SHEOL) sheol_award_spawn(room, award, isContinuing); + else if (stage == STAGE_DARK_ROOM) dark_room_award_spawn(room, award, isContinuing); + else reconstruction_missing("Room::SpawnClearAward 007fb250: the Void's bosses' items and Delirium's chest"); boss_kill_records(stage, isLastBoss); } diff --git a/src/room_grid.cpp b/src/room_grid.cpp index 5ecfe96..f5a19cd 100644 --- a/src/room_grid.cpp +++ b/src/room_grid.cpp @@ -7,6 +7,7 @@ #include "log.h" #include "npc_ai.h" #include "room.h" +#include #include // The partitions a query bit looks in, in the order QueryRadius goes through them. @@ -88,6 +89,14 @@ GridEntity* room_grid_entity_at(const Vector& position) return gridIndex < 0 ? nullptr : g_game->room->GetGridEntity((uint32_t)gridIndex); } +// 00812de0 Room::GetClampedGridIndex: the cell under a position, pulled onto the grid when off it. +int room_clamped_grid_index_get(Room& room, Vector position) +{ + int column = std::max((int)((position.x - GRID_ORIGIN_X) / GRID_CELL_SIZE + 0.5f), 0); + int row = std::max((int)((position.y - GRID_ORIGIN_Y) / GRID_CELL_SIZE + 0.5f), 0); + return std::min(row, room.gridHeight - 1) * room.gridWidth + std::min(column, room.gridWidth - 1); +} + // Whether a cell takes a pickup: free of grid collision (or a pit, when allowed) and of trapdoors, stairs, pressure // plates and teleporters. static bool is_cell_free(Room& room, int gridIndex, const FreeSpotSearch& search) diff --git a/src/room_grid.h b/src/room_grid.h index a513c4b..3c535eb 100644 --- a/src/room_grid.h +++ b/src/room_grid.h @@ -38,6 +38,7 @@ struct GridDestroy EntityList_EL entity_query_radius(const Vector& position, float radius, uint32_t partitions); GridEntity* room_grid_entity_at(const Vector& position); +int room_clamped_grid_index_get(Room& room, Vector position); Vector room_free_pickup_position_find(const FreeSpotSearch& search); Vector room_free_tile_position_find(const Vector& position, float distanceThreshold); bool room_grid_destroy(const GridDestroy& destroy); diff --git a/src/room_lighting.cpp b/src/room_lighting.cpp index 9a3fa5d..7f71c7d 100644 --- a/src/room_lighting.cpp +++ b/src/room_lighting.cpp @@ -90,7 +90,6 @@ constexpr int VISAGE_HEART_STATE_LIT = 113; constexpr int VISAGE_HEART_STATE_FLARE = 104; constexpr int VISAGE_MASK_STATE_LIT = 105; constexpr int BOSS_ID_WIDOW = 51; -constexpr int ENTITY_THE_LAMB = 273; constexpr int ENTITY_PREY = 817; constexpr int FLAMING_VARIANT = 2; constexpr int FLAMING_TYPES[] = {10, 208, 226}; diff --git a/src/room_path.cpp b/src/room_path.cpp new file mode 100644 index 0000000..9fc2ae0 --- /dev/null +++ b/src/room_path.cpp @@ -0,0 +1,166 @@ +#include "room_path.h" +#include "game.h" +#include "grid_entity_pit.h" +#include "grid_entity_teleporter.h" +#include "log.h" +#include +#include +#include + +constexpr int PATH_NEIGHBORS_MAX = 32; +constexpr int PATH_CARVE_COST = 448; +constexpr int PATH_BLOCKED = 1000; +constexpr float PATH_HEURISTIC_SCALE = 10; +constexpr uint16_t PATH_NO_CELL = 0xffff; + +// The obstacles a carving search may cross and break: the rocks but blocks and pillars, and the pits it fills. +static bool is_carvable(GridEntityType type) +{ + switch (type) + { + case GRID_ROCK: + case GRID_ROCKT: + case GRID_ROCK_BOMB: + case GRID_ROCK_ALT: + case GRID_ROCK_SS: + case GRID_ROCK_SPIKED: + case GRID_ROCK_ALT2: + case GRID_ROCK_GOLD: + case GRID_PIT: + return true; + default: + return false; + } +} + +// The distance from a cell to the goal in cells, ten times over, as the search's estimate. +static uint32_t path_estimate(const Room& room, int cell, int goal) +{ + float columns = (float)(goal % room.gridWidth) - (float)(cell % room.gridWidth); + float rows = (float)(goal / room.gridWidth) - (float)(cell / room.gridWidth); + return (uint32_t)(std::sqrt(rows * rows + columns * columns) * PATH_HEURISTIC_SCALE); +} + +// The cells a search steps to from one: left, right, up and down, then the other teleporters of the variant of a +// working teleporter it stands on. The scan for those starts past it and stops two cells short of a full turn. +static int path_neighbors_get(Room& room, int cell, uint32_t flags, std::array& neighbors) +{ + int column = cell % room.gridWidth; + int row = cell / room.gridWidth; + int count = 0; + + neighbors[count++] = room.GetGridIndexByTile(column - 1, row); + neighbors[count++] = room.GetGridIndexByTile(column + 1, row); + neighbors[count++] = room.GetGridIndexByTile(column, row - 1); + neighbors[count++] = room.GetGridIndexByTile(column, row + 1); + if (!(flags & GRID_PATH_TELEPORTERS)) return count; + + GridEntity* teleporter = room.gridEntities[cell]; + if (!teleporter || teleporter->type != GRID_TELEPORTER || teleporter->state == TELEPORTER_STATE_OFF) return count; + int cells = room.gridWidth * room.gridHeight; + int scan = teleporter->gridIndex; + for (int step = 0; step < cells - 2; step++) + { + scan = (scan + 1) % cells; + GridEntity* other = scan < ROOM_GRID_CELLS ? room.gridEntities[scan] : nullptr; + bool isPartner = other && other->type == GRID_TELEPORTER && other->variant == teleporter->variant; + if (isPartner && count < PATH_NEIGHBORS_MAX) neighbors[count++] = scan; + } + return count; +} + +// What stepping onto a cell costs: 1 onto open ground, the carve cost onto an obstacle a carving search breaks, or +// nothing (0) when it is closed. Spikes and cells marked by the paths are solid. +static uint32_t path_step_cost(Room& room, int cell, uint32_t flags) +{ + GridEntity* grid = room.gridEntities[cell]; + int collision = grid ? (grid->type == GRID_SPIKES ? COLLISION_SOLID : grid->collisionClass) : COLLISION_NONE; + + if (room.gridPaths[cell] >= PATH_BLOCKED) collision = COLLISION_SOLID; + if ((flags & GRID_PATH_PLAYER_WALLS) && collision == COLLISION_WALL_EXCEPT_PLAYER) collision = COLLISION_NONE; + if ((flags & GRID_PATH_CARVE) && collision == COLLISION_SOLID) + return grid && is_carvable(grid->type) ? PATH_CARVE_COST : 0; + return collision == COLLISION_NONE ? 1 : 0; +} + +// The carve of a found path, from the goal back to the start: rocks break (lifted off on the room's first frame) and +// empty pits fill. +static void path_carve(Room& room, const std::array& cameFrom, int goal) +{ + for (int cell = goal; cell != PATH_NO_CELL; cell = cameFrom[cell]) + { + GridEntity* grid = room.gridEntities[cell]; + if (!grid || !is_carvable(grid->type)) continue; + if (grid->type == GRID_PIT) + { + if (grid->state != PIT_STATE_EMPTY) continue; + grid->state = PIT_STATE_FILLED; + static_cast(grid)->UpdateCollision(); + } + else if (room.enterFrame == g_game->frameCount) + reconstruction_missing("Room::PickupGridEntity 00825c50"); + else grid->Destroy(true, EntityRef()); + } +} + +// 00821fc0 Whether a path joins two cells, by an A* search that expands the open cell of lowest estimate, the first in +// cell order on a tie. Estimates are compared in 16 bits as the original's are. A carving search clears its path. +bool is_grid_path_valid(Room& room, const GridPath& path) +{ + std::array costs; + std::array estimates; + std::array cameFrom; + std::array neighbors; + std::set closed; + std::set open = {path.start}; + + costs.fill(UINT32_MAX); + estimates.fill(UINT32_MAX); + cameFrom.fill(PATH_NO_CELL); + costs[path.start] = 0; + estimates[path.start] = path_estimate(room, path.start, path.goal) & PATH_NO_CELL; + + while (!open.empty()) + { + int current = *std::ranges::min_element(open, {}, [&](int cell) { return (uint16_t)estimates[cell]; }); + if (current == path.goal) + { + if (path.flags & GRID_PATH_CARVE) path_carve(room, cameFrom, current); + return true; + } + open.erase(current); + closed.insert(current); + + int count = path_neighbors_get(room, current, path.flags, neighbors); + for (int i = 0; i < count; i++) + { + int next = neighbors[i]; + if (next < 0) continue; + uint32_t step = path_step_cost(room, next, path.flags); + if (step == 0 || closed.contains(next)) continue; + + uint32_t cost = costs[current] + step; + if (open.contains(next) && cost >= costs[next]) continue; + open.insert(next); + costs[next] = cost; + cameFrom[next] = (uint16_t)current; + estimates[next] = path_estimate(room, next, path.goal) + cost; + } + } + return false; +} + +// 00823be0 Whether a position can walk to the room's entrance or to the player: its cell must be open (or a wall only +// players pass), then a path must join them through those walls and the teleporters. +bool is_reachable_from_player(Room& room, const Reach& reach) +{ + Entity_Player* player = reach.player ? reach.player : g_game->GetPlayer(0); + int goal = room.GetGridIndex(reach.goal == REACH_PLAYER ? player->pos : player->GetEnterPosition()); + int start = room.GetGridIndex(reach.position); + if (start < 0) return false; + + uint32_t collision = room.GetGridCollision(start); + bool isStartOpen = collision == COLLISION_NONE || collision == COLLISION_WALL_EXCEPT_PLAYER; + return goal >= 0 && isStartOpen && + is_grid_path_valid(room, {start, goal, GRID_PATH_PLAYER_WALLS | GRID_PATH_TELEPORTERS}); +} diff --git a/src/room_path.h b/src/room_path.h new file mode 100644 index 0000000..1b2fc70 --- /dev/null +++ b/src/room_path.h @@ -0,0 +1,39 @@ +#pragma once + +#include "entity_player.h" +#include "room.h" + +// What a grid path search may cross (Room::is_obstacle_path_valid's flags): walls only players pass, the teleporters +// of a variant, and breakable obstacles, which it then clears along the path it found. +enum GridPathFlag : uint32_t +{ + GRID_PATH_PLAYER_WALLS = 1 << 0, + GRID_PATH_TELEPORTERS = 1 << 1, + GRID_PATH_CARVE = 1 << 2 +}; + +// Where a reachability check walks to: the room's entrance or the player. +enum ReachGoal +{ + REACH_ENTRANCE, + REACH_PLAYER +}; + +// A path search over the room's grid between two cells. +struct GridPath +{ + int start = -1; + int goal = -1; + uint32_t flags = 0; +}; + +// A position checked against a player (null for the first) and the goal it must walk to. +struct Reach +{ + Vector position{}; + Entity_Player* player = nullptr; + ReachGoal goal = REACH_ENTRANCE; +}; + +bool is_grid_path_valid(Room& room, const GridPath& path); +bool is_reachable_from_player(Room& room, const Reach& reach); diff --git a/src/room_render.cpp b/src/room_render.cpp index 534bb09..04ce3c9 100644 --- a/src/room_render.cpp +++ b/src/room_render.cpp @@ -5,6 +5,7 @@ #include "game.h" #include "gl.h" #include "grid_entity_door.h" +#include "grid_entity_pit.h" #include "grid_entity_rock.h" #include "log.h" #include "manager.h" @@ -57,6 +58,12 @@ constexpr float SHOCKWAVE_IDLE_X = -150; constexpr float GRID_SCREEN_CELL = 26; constexpr float FLOOR_MARGIN = 52; constexpr int WALL_CELLS = 2; +constexpr float PIT_MASK_CELL_OFFSET = 39; + +// A flooded Mines room's lava paints over the pits' shapes keeping their alpha. +constexpr KAGE::Graphics::BlendMode LAVA_MASK_BLEND = {KAGE::Graphics::EQUATION_ADD, KAGE::Graphics::FACTOR_SRC_ALPHA, + KAGE::Graphics::FACTOR_ONE_MINUS_SRC_ALPHA, + KAGE::Graphics::FACTOR_ZERO, KAGE::Graphics::FACTOR_ONE}; // The depths render_up_to draws entities to: the floor's entities, those under the grid entities, a grid row's (its // world bottom, scaled) and the margin past the last row. @@ -93,6 +100,58 @@ constexpr ColorMod LIGHT_PLATE_REWARD = {{1, 0.4f, 0.4f, 1}, {0, 0, 0, 0}, {0, 0 constexpr ColorMod LIGHT_PLATE_CLEAR = {{1, 1, 0, 1}, {0, 0, 0, 0}, {0, 0, 0}}; constexpr ColorMod LIGHT_PLATE = {{1, 1, 1, 0.2f}, {0, 0, 0, 0}, {0, 0, 0}}; +// A light color: a tint, nothing colorized or offset. +static constexpr ColorMod light_tint(float red, float green, float blue, float alpha) +{ + return {{red, green, blue, alpha}, {0, 0, 0, 0}, {0, 0, 0}}; +} + +// The lava pits' glow: a pulse over the frames, flickering the lava's heat, half over a filled pit. The flooded Mines' +// is orange, a shaft's red, G FUEL!'s flooded Caves blue, over the light in a blend that keeps the light's alpha. +constexpr float LAVA_PULSE_SPEED = 0.1f; +constexpr float LAVA_PULSE_RANGE = 0.2f; +constexpr float LAVA_PULSE_BASE = 0.8f; +constexpr float LAVA_FLICKER = 0.1f; +constexpr float LAVA_FLICKER_BASE = 0.9f; +constexpr float LAVA_FILLED_SHARE = 0.5f; +constexpr float LAVA_FUEL_WATER = 0.5f; +constexpr float LAVA_MINES_GREEN = 0.35f; +constexpr float LAVA_FUEL_GREEN = 0.3f; +constexpr float LAVA_FUEL_GREEN_BASE = 0.4f; +constexpr float LAVA_SHAFT_RED = 0.4f; +constexpr float LAVA_SHAFT_RED_BASE = 0.6f; +constexpr float LAVA_LIGHT_SCALE = 0.8f; +constexpr std::array LAVA_LIGHT_BLEND = { + KAGE::Graphics::EQUATION_ADD, KAGE::Graphics::FACTOR_ONE, KAGE::Graphics::FACTOR_ONE_MINUS_SRC_ALPHA, + KAGE::Graphics::FACTOR_SRC_ALPHA, KAGE::Graphics::FACTOR_ONE_MINUS_SRC_ALPHA}; +constexpr std::array LIGHT_NORMAL_BLEND = { + KAGE::Graphics::EQUATION_ADD, KAGE::Graphics::FACTOR_ONE, KAGE::Graphics::FACTOR_ONE_MINUS_SRC_ALPHA, + KAGE::Graphics::FACTOR_ONE, KAGE::Graphics::FACTOR_ONE_MINUS_SRC_ALPHA}; + +// The doors' lights, and the layers of Home's and the mineshaft's doors that light them. +constexpr ColorMod DOOR_LIGHT_MINES = light_tint(1, 0.5f, 0.2f, 1); +constexpr ColorMod DOOR_LIGHT_MINES_OPENING = light_tint(1, 0.5f, 0.2f, 0.5f); +constexpr ColorMod DOOR_LIGHT_MAUSOLEUM = light_tint(0.8f, 0.1f, 1, 1); +constexpr ColorMod DOOR_LIGHT_MOMS_HEART = light_tint(1, 0.2f, 0.2f, 1); +constexpr ColorMod DOOR_LIGHT_LIT_ROOM = light_tint(0.3f, 0.6f, 1, 1); +constexpr ColorMod DOOR_LIGHT_ANGEL = light_tint(0.92f, 0.95f, 1, 1); +constexpr float DOOR_OPENING_SCALE = 0.5f; +constexpr float DOOR_LIT_ROOM_SCALE = 0.7f; +constexpr float DOOR_MINESHAFT_GREEN = 0.95f; +constexpr float DOOR_MINESHAFT_BLUE = 0.9f; +constexpr int DOOR_KEY_TURN_FRAMES = 19; +constexpr int DOOR_HOME_LIGHT_LAYER = 3; +constexpr int DOOR_MINESHAFT_LIGHT_LAYER = 5; + +// The trapdoors' lights: the Mines exit's flame flickering 3 around a point 14 over its hole, and the Mausoleum's red. +constexpr ColorMod TRAPDOOR_LIGHT_MINES = light_tint(1, 0.8f, 0.2f, 1); +constexpr ColorMod TRAPDOOR_LIGHT_MAUSOLEUM = light_tint(1, 0.5f, 0.5f, 2); +constexpr float TRAPDOOR_MAUSOLEUM_WIDTH = 1.2f; +constexpr float TRAPDOOR_MAUSOLEUM_HEIGHT = 0.75f; +constexpr RNG TRAPDOOR_FLICKER_RNG = {0, 5, 27, 25}; +constexpr float TRAPDOOR_FLICKER = 3; +constexpr float TRAPDOOR_FLAME_HEIGHT = 14; + // How strongly lights glow: the player's Spirit of the Night aura, the flicker of flames, the bullet glow's pulse. constexpr float GLOW_STACK_MAX = 4; constexpr float GLOW_ALPHA_STEP = 0.07f; @@ -123,14 +182,8 @@ constexpr int BABY_SKIN_GLOW = 66; constexpr int GRID_STATE_POOP_DESTROYED = 1000; constexpr int PLATE_VARIANT_REWARD = 9; constexpr int PLATE_VARIANT_ROOM_CLEAR = 3; -constexpr int DOOR_ROOM_SECRET_EXIT = 27; -constexpr int DOOR_ROOM_ANGEL = 15; -constexpr int DOOR_VARIANT_LIGHT = 8; -constexpr int DOOR_STATE_LIGHT = 4; -constexpr int ROOM_IDX_SECRET_EXIT = -10; constexpr int ROOM_IDX_BLUE_WOMB_LIGHT = -9; constexpr int BOSS_MOM_MAUSOLEUM = 89; -constexpr int DIMENSION_MIRROR = 1; constexpr int DIMENSION_DEATH_CERTIFICATE = 2; constexpr uint32_t ROOM_DESCRIPTOR_FLAG_LIT_DOOR = 1u << 18; constexpr uint32_t WATER_CLIP_UNDER = 1 << 1; @@ -560,10 +613,34 @@ static void water_shader_render(Room&, Vector) reconstruction_missing("Room::render_water_shader 00821950"); } -// 00826f80 Draws the flooded Mines' water over the floor. Not reconstructed yet. -static void water_overlay_render(Room&, Vector) +// 007135d0 Draws a pit's first layer at its cell of a room surface with another image in place of its sheet. +static void pit_mask_render(GridEntity& pit, KAGE::Graphics::ImagePtr image) { - reconstruction_missing("Room::render_water_overlay 00826f80"); + int width = g_game->room->gridWidth; + Vector cell = vector_make((float)(pit.gridIndex % width) * GRID_SCREEN_CELL + PIT_MASK_CELL_OFFSET, + (float)(pit.gridIndex / width) * GRID_SCREEN_CELL + PIT_MASK_CELL_OFFSET); + LayerState* layer = pit.sprite.GetLayer(0); + KAGE::Graphics::ImagePtr sheet = layer->spriteSheet; + + layer->spriteSheet = image; + pit.sprite.animState.RenderLayer(0, {cell}, pit.sprite); + layer->spriteSheet = sheet; +} + +// 00826f80 Draws the flooded Mines' lava pits (the textured pit surface render_lava_pit_mask fills) over the floor. +static void water_overlay_render(Room& room, Vector surfaceOffset) +{ + KAGE::Graphics::Manager& graphics = KAGE::Graphics::manager; + Vector size = vector_make(room.floorScreenBottomRight.x - room.floorScreenTopLeft.x, + room.floorScreenBottomRight.y - room.floorScreenTopLeft.y); + Vector corner = vector_make(surfaceOffset.x + FLOOR_MARGIN, surfaceOffset.y + FLOOR_MARGIN); + SourceQuad source = KAGE::Graphics::source_quad_rect(vector_make(FLOOR_MARGIN, FLOOR_MARGIN), size); + + graphics.blend_set(KAGE::Graphics::BLEND_NORMAL); + shader_select(COLOR_OFFSET_SHADER); + apply_sprite_shader_params(COLOR_DEFAULT, SPRITE_SHADER_COLOR_APPLY, *roomSurfaces.texturedPit); + roomSurfaces.texturedPit->Render(source, KAGE::Graphics::color_quad_rect(corner, size, WHITE), WHITE); + graphics.shader_default_set(); } // 00825de0 Draws the Ashpit's drifting dust into the dust surface. Not reconstructed yet past the Ashpit check. @@ -572,11 +649,35 @@ static void darkness_overlay_render(Room& room) if (room.is_ashpit_rays()) reconstruction_missing("Room::render_darkness_overlay 00825de0"); } -// 00826ae0 Draws a flooded Mines room's lava pits into the textured pit surface. Not reconstructed yet past its check. +// 00826ae0 Fills a flooded Mines room's textured pit surface: each pit's shape cut from the pit mask, painted with lava +// as red as its heat in a blend that keeps the shape, then with cold lava as the lava cools while water covers it. static void lava_pit_mask_render(Room& room) { - if (room.backdropType == BACKDROP_MINES && room.descriptor->flags & ROOM_DESCRIPTOR_FLAG_HAS_WATER) - reconstruction_missing("Room::render_lava_pit_mask 00826ae0"); + if (room.backdropType != BACKDROP_MINES || !(room.descriptor->flags & ROOM_DESCRIPTOR_FLAG_HAS_WATER)) return; + + KAGE::Graphics::Manager& graphics = KAGE::Graphics::manager; + KAGE::Graphics::ImageBase& surface = *roomSurfaces.texturedPit; + KAGE::Graphics::BlendMode saved = graphics.blendMode; + Vector size = vector_make((float)surface.width, (float)surface.height); + SourceQuad source = KAGE::Graphics::source_quad_rect({}, size); + KAGE::Graphics::ColorQuad quad = KAGE::Graphics::color_quad_rect({}, size, WHITE); + float heat = room.lavaIntensity; + + surface_begin(roomSurfaces.texturedPit, KAGE::Graphics::TARGET_OWN_SIZE); + graphics.blend_set(KAGE::Graphics::BLEND_NORMAL); + DAT_00c33910 = 0; + shader_select(COLOR_OFFSET_SHADER); + for (int i = 0; i < room.gridWidth * room.gridHeight; i++) + if (is_grid_type(room.gridEntities[i], GRID_PIT)) pit_mask_render(*room.gridEntities[i], roomSurfaces.pitMask); + + graphics.blendMode = LAVA_MASK_BLEND; + DAT_00c33910 = 1; + roomSurfaces.lava->Render(source, quad, kcolor_rgba(heat * 0.5f + 0.5f, heat, heat, 1)); + if (room.waterAmount > 0) roomSurfaces.coldLava->Render(source, quad, kcolor_rgba(1, 1, 1, 1 - heat * heat)); + graphics.Present(KAGE::Graphics::PRESENT_FINISH); + graphics.blendMode = saved; + graphics.render_target_pop(KAGE::Graphics::PRESENT_FLUSH); + graphics.shader_default_set(); } // 00820fd0 Draws the floor under the water surface into its surface. Not reconstructed yet past its check. @@ -1102,54 +1203,142 @@ void Room::Render() if (game.debugFlags & DEBUG_FLAG_ROOM_INFO) reconstruction_missing("Room::Render 0080f200: the room info text"); } -// The light of a door: the secret exits' and the Ascent's lit doors, doors into lit rooms, the mirror world's -// mineshaft doors and angel room doors. Whether it lights before any light is drawn. -static bool is_door_lit(GridEntity_Door& door) +// The glow of a lava pit: in a flooded Mines room orange as hot as its lava, drawn plainly. In a flooded shaft it is +// red (blue in a flooded Caves room under G FUEL!, always full there), drawn over the light. It pulses, and is half as +// strong over a filled pit. +static void pit_light_render(Room& room, GridEntity& pit, Vector offset) +{ + Game& game = *g_game; + bool isFlooded = room.descriptor->flags & ROOM_DESCRIPTOR_FLAG_HAS_WATER; + bool isShaft = room.backdropType == BACKDROP_MINES_SHAFT || room.backdropType == BACKDROP_ASHPIT_SHAFT; + bool isFuel = game.seedEffects.HasSeedEffect(SEED_G_FUEL) && game.GetStageID() == STAGE_ID_FLOODED_CAVES; + bool isMinesLava = room.backdropType == BACKDROP_MINES && isFlooded; + if (!isMinesLava && !(isShaft && isFlooded) && !(isFuel && room.waterAmount > LAVA_FUEL_WATER)) return; + + float pulse = std::sin((float)game.frameCount * LAVA_PULSE_SPEED) * LAVA_PULSE_RANGE + LAVA_PULSE_BASE; + float heat = isFuel && !isMinesLava ? 1 : room.lavaIntensity; + float alpha = (pulse * LAVA_FLICKER + LAVA_FLICKER_BASE) * heat; + if ((uint32_t)pit.state > PIT_STATE_BRIDGE_PENDING) alpha *= LAVA_FILLED_SHARE; + if (alpha <= 0) return; + + if (isMinesLava) + { + light_draw(room, pit.Position(), offset, light_tint(1, pulse * LAVA_MINES_GREEN, 0, alpha), LAVA_LIGHT_SCALE); + return; + } + room.lightSprite.GetLayer(0)->blendMode = LAVA_LIGHT_BLEND; + ColorMod color = isFuel ? light_tint(0, pulse * LAVA_FUEL_GREEN + LAVA_FUEL_GREEN_BASE, + pulse * LAVA_SHAFT_RED + LAVA_SHAFT_RED_BASE, alpha) + : light_tint(pulse * LAVA_SHAFT_RED + LAVA_SHAFT_RED_BASE, 0, 0, alpha); + light_draw(room, pit.Position(), offset, color, LAVA_LIGHT_SCALE); + room.lightSprite.GetLayer(0)->blendMode = LIGHT_NORMAL_BLEND; +} + +// The light of a lit door, false for an unlit one: the Mines exit's orange once unlocked (half once damaged), the Mausoleum +// exit's purple once its key turned, the red one in Mom's Heart's exit room, Home's as its light layer, blue into lit +// rooms, the mirror world's mineshaft doors as bright as their light layer, and angel room doors. +static bool door_light_get(GridEntity_Door& door, ColorMod& color, float& scale) { Game& game = *g_game; int exitKind = game.get_secret_exit_kind(); + bool isUnlocked = door.variant == DOOR_UNLOCKED; + scale = 1; - if (door.targetRoomType == DOOR_ROOM_SECRET_EXIT) - return exitKind == SECRET_EXIT_MINES ? door.variant == DOOR_VARIANT_LIGHT || door.state == DOOR_STATE_LIGHT - : exitKind == SECRET_EXIT_MAUSOLEUM; - if (game.currentRoomIdx == ROOM_IDX_SECRET_EXIT && exitKind == SECRET_EXIT_MOMS_HEART) - return door.variant == DOOR_VARIANT_LIGHT; + if (door.targetRoomType == ROOM_SECRET_EXIT) + { + bool isKeyTurning = door.sprite.IsPlaying("KeyOpen") && door.sprite.GetFrame() < DOOR_KEY_TURN_FRAMES; + if (exitKind == SECRET_EXIT_MINES && isUnlocked) color = DOOR_LIGHT_MINES; + else if (exitKind == SECRET_EXIT_MINES && door.state == DOOR_STATE_DAMAGED) + { + color = DOOR_LIGHT_MINES_OPENING; + scale = DOOR_OPENING_SCALE; + } + else if (exitKind == SECRET_EXIT_MAUSOLEUM && isUnlocked && !isKeyTurning) color = DOOR_LIGHT_MAUSOLEUM; + else return false; + return true; + } + if (game.currentRoomIdx == ROOM_SECRET_EXIT_IDX && exitKind == SECRET_EXIT_MOMS_HEART) + { + color = DOOR_LIGHT_MOMS_HEART; + return isUnlocked; + } RoomConfig_Room* config = game.room->descriptor->data; - if (config && config->stageId == STAGE_ID_HOME) return true; - if (game.GetRoomByIdx(door.targetRoomIdx)->flags & ROOM_DESCRIPTOR_FLAG_LIT_DOOR) return true; - if (door.doorFlags & DOOR_FLAG_MINESHAFT && game.currentDimensionIdx == DIMENSION_MIRROR) return true; - return door.targetRoomType == DOOR_ROOM_ANGEL && door.variant == DOOR_VARIANT_LIGHT; + if (config && config->stageId == STAGE_ID_HOME) + { + LayerState* layer = door.sprite.GetLayer(DOOR_HOME_LIGHT_LAYER); + if (layer) color = layer->color; + return layer && layer->isVisible; + } + if (game.GetRoomByIdx(door.targetRoomIdx)->flags & ROOM_DESCRIPTOR_FLAG_LIT_DOOR) + { + color = DOOR_LIGHT_LIT_ROOM; + scale = DOOR_LIT_ROOM_SCALE; + return true; + } + if (door.doorFlags & DOOR_FLAG_MINESHAFT && game.currentDimensionIdx == DIMENSION_MIRROR) + { + LayerState* layer = door.sprite.GetLayer(DOOR_MINESHAFT_LIGHT_LAYER); + if (!layer || !layer->isVisible || layer->color._tint[3] <= 0) return false; + color = light_tint(1, DOOR_MINESHAFT_GREEN, DOOR_MINESHAFT_BLUE, layer->color._tint[3]); + return true; + } + color = DOOR_LIGHT_ANGEL; + return door.targetRoomType == ROOM_ANGEL && isUnlocked; } -// 0080c810 Draws a grid entity's light into the light overlay: pressure plates (red reward plates, yellow room clear -// plates, white unpressed ones, dimmer once pressed), teleporters at their sprite's light null, and the lava pits, -// lit doors and the last boss's trapdoor in the Mausoleum's heart. -// The lava pits', doors' and trapdoor's lights are not reconstructed yet. +// The light of a trapdoor: in the Mines exit room a yellow flame flickering over its hole while the hole shows, and +// over the last boss's trapdoor in the Mausoleum's heart a wide red glow. +static void trapdoor_light_render(Room& room, GridEntity& trapdoor, Vector offset) +{ + Game& game = *g_game; + ANM2& light = room.lightSprite; + Vector position = vector_add(render_position_get(trapdoor.Position(), RENDER_SNAPPED), offset); + + if (room.roomType == ROOM_SECRET_EXIT && game.get_secret_exit_kind() == SECRET_EXIT_MINES) + { + const AnimationFrame* hole = trapdoor.sprite.animState.GetLayerFrame(0); + if (!hole || !hole->isVisible) return; + + RNG rng = {trapdoor.spawnSeed + (uint32_t)game.frameCount, TRAPDOOR_FLICKER_RNG._shift1, + TRAPDOOR_FLICKER_RNG._shift2, TRAPDOOR_FLICKER_RNG._shift3}; + Vector direction = RandomVector(rng.Next()); + float flicker = rng.RandomFloat(); + light.color = TRAPDOOR_LIGHT_MINES; + light.scale = vector_make(1, 1); + sprite_draw(light, vector_make(position.x + 0 + flicker * direction.x * TRAPDOOR_FLICKER, + flicker * direction.y * TRAPDOOR_FLICKER + (position.y - TRAPDOOR_FLAME_HEIGHT))); + return; + } + if (!Room::IsCurrentRoomLastBoss() || !game.IsMausoleumHeartStage()) return; + + std::array saved = light.GetLayer(0)->blendMode; + light.GetLayer(0)->blendMode = LAVA_LIGHT_BLEND; + light.color = TRAPDOOR_LIGHT_MAUSOLEUM; + light.scale = vector_make(TRAPDOOR_MAUSOLEUM_WIDTH, TRAPDOOR_MAUSOLEUM_HEIGHT); + sprite_draw(light, position); + light.GetLayer(0)->blendMode = saved; +} + +// 0080c810 Draws a grid entity's light into the light overlay: lava pits, lit doors and trapdoors, pressure plates +// (red reward plates, yellow room clear plates, white unpressed ones, dimmer once pressed), and teleporters at their +// sprite's light null. static void grid_light_render(Room& room, GridEntity& grid, Vector offset) { Vector position = grid.Position(); switch (grid.type) { - case GRID_PIT: + case GRID_PIT: pit_light_render(room, grid, offset); return; + case GRID_TRAPDOOR: trapdoor_light_render(room, grid, offset); return; + case GRID_DOOR: { - bool isFlooded = room.descriptor->flags & ROOM_DESCRIPTOR_FLAG_HAS_WATER; - bool isShaft = room.backdropType == BACKDROP_MINES_SHAFT || room.backdropType == BACKDROP_ASHPIT_SHAFT; - bool isFuelFlood = g_game->seedEffects.HasSeedEffect(SEED_G_FUEL) && - g_game->GetStageID() == STAGE_ID_FLOODED_CAVES && room.waterAmount > 0.5f; - if (room.backdropType == BACKDROP_MINES ? isFlooded : (isShaft && isFlooded) || isFuelFlood) - reconstruction_missing("Room::render_grid_entity_light 0080c810: the lava pits"); + ColorMod color = COLOR_DEFAULT; + float scale = 1; + if (door_light_get(static_cast(grid), color, scale)) + light_draw(room, position, offset, color, scale); return; } - case GRID_DOOR: - if (is_door_lit(static_cast(grid))) - reconstruction_missing("Room::render_grid_entity_light 0080c810: the doors' lights"); - return; - case GRID_TRAPDOOR: - if (Room::IsCurrentRoomLastBoss() && g_game->IsMausoleumHeartStage()) - reconstruction_missing("Room::render_grid_entity_light 0080c810: the trapdoor's light"); - return; case GRID_PRESSURE_PLATE: { float alpha = grid.state == 0 ? 1 : PLATE_PRESSED_ALPHA; diff --git a/src/room_special.cpp b/src/room_special.cpp index ca6c811..75dab82 100644 --- a/src/room_special.cpp +++ b/src/room_special.cpp @@ -788,7 +788,6 @@ void npc_shopkeeper_update(Entity_NPC& npc) npc.UpdatePickupGhosts(); } -constexpr int SOUND_COIN_SLOT = 45; constexpr int SOUND_MIRROR_BREAK = 610; constexpr int FAMILIAR_KNIFE_FULL = 223; constexpr int TRINKET_PAPER_CLIP_ID = 19; @@ -1161,7 +1160,7 @@ bool GridEntity_Door::TryUnlock(Entity_Player& player, bool isForce) variant = DOOR_UNLOCKED; if (targetRoomType == ROOM_BOSS && targetRoomIdx >= 0 && game.stage == STAGE_BLUE_WOMB) grid_sound_play(SOUND_BOSS_LITE_ROAR, {.pitch = HUSH_DOOR_PITCH}); - else grid_sound_play(doorFlags & DOOR_FLAG_COIN_LOCK ? SOUND_COIN_SLOT : SOUND_UNLOCK); + else grid_sound_play(doorFlags & DOOR_FLAG_COIN_LOCK ? SOUND_COIN_INSERT : SOUND_UNLOCK); if (!isBlueKey) return true; if (sprite.IsPlaying("GoldenKeyOpen")) sprite.Play("KeyOpen"); diff --git a/src/room_state.cpp b/src/room_state.cpp index 0c22cd3..a8048d1 100644 --- a/src/room_state.cpp +++ b/src/room_state.cpp @@ -25,10 +25,6 @@ constexpr int GRID_PATH_RESET = 900; constexpr int EFFECT_BUTTERFLY = 69; constexpr int HEAVEN_LIGHT_MOONLIGHT = 1; constexpr int GIDEON_TYPE = 907; -constexpr int SLOT_DONATION_MACHINE = 8; -constexpr int SLOT_SHOP_RESTOCK_MACHINE = 10; -constexpr int SLOT_STATE_BROKEN = 3; -constexpr int SLOT_STATE_GONE = 4; constexpr int CHEST_RECLOSED_SUBTYPE = 1; constexpr int SHOP_ITEM_ID_MIN = -2; diff --git a/src/room_update.cpp b/src/room_update.cpp index 3722486..2626bd9 100644 --- a/src/room_update.cpp +++ b/src/room_update.cpp @@ -110,7 +110,6 @@ constexpr int SOUND_THUNDER = 472; constexpr int SOUND_ALARM = 460; constexpr int PLAYER_THE_FORGOTTEN_B = 35; constexpr int DIMENSION_DEATH_CERTIFICATE = 2; -constexpr int DIMENSION_MIRROR = 1; constexpr int BOSS_THE_BEAST_ROOM = 91; constexpr int ROOM_IDX_DUNGEON_BEAST = -16; constexpr int GREED_LAST_STAGE = 5; @@ -121,14 +120,12 @@ constexpr uint32_t RNG_SHIFT_COUPON_2 = 27; // The entities with ambient loops of their own (Lua's EntityType, EffectVariant and laser variants). constexpr int AMBIENT_FLY_TYPES[] = {13, 14, 18, 25, 61, 80, 214, 222, 249, 256, 281, 296, 808, 819, 838, 868}; -constexpr int ENTITY_VIS_FATTY = 886; constexpr int BEAST_FLY_VARIANTS[] = {11, 21}; constexpr int DOGMA_ANGEL = 2; constexpr int DOGMA_ANGEL_STATE = 10; constexpr int LASER_LOOP_VARIANTS[] = {6, 15}; constexpr int EFFECT_DOGMA_BLACKHOLE = 171; constexpr int EFFECT_URN_OF_SOULS = 178; -constexpr int EFFECT_RIFT = 180; constexpr int BLACKHOLE_STATE_OPEN = 1; // How the sources sound: the reach of the enemies' loops, the flies' buzz (Hush's flies quieter, the whole buzz capped), diff --git a/src/sfx_manager.h b/src/sfx_manager.h index 15cc2d4..f68ab41 100644 --- a/src/sfx_manager.h +++ b/src/sfx_manager.h @@ -37,7 +37,9 @@ enum SoundId : int SOUND_BOSS_LITE_ROAR = 14, SOUND_BOSS_LITE_SLOPPY_ROAR = 15, SOUND_BOSS_SPIT_BLOB_BARF = 16, + SOUND_CHEST_DROP = 21, SOUND_CHEST_OPEN = 22, + SOUND_COIN_SLOT = 24, SOUND_CUTE_GRUNT = 25, SOUND_DEATH_BURST_LARGE = 28, SOUND_BOSS1_EXPLOSIONS = 28, @@ -52,6 +54,7 @@ enum SoundId : int SOUND_HOLY = 54, SOUND_ISAAC_HURT_GRUNT = 55, SOUND_CHILD_ANGRY_ROAR = 57, + SOUND_KEY_DROP0 = 59, SOUND_DIP_HURT = 60, SOUND_MAGGOT_BURST_OUT = 64, SOUND_MAGGOT_ENTER_GROUND = 66, @@ -98,6 +101,8 @@ enum SoundId : int SOUND_ANGRY_GURGLE = 167, SOUND_BATTERYCHARGE = 170, SOUND_BEEP = 171, + SOUND_BLOODBANK_TOUCHED = 174, + SOUND_BLOODBANK_SPAWN = 175, SOUND_BLOODSHOOT = 178, SOUND_BOIL_HATCH = 181, SOUND_BOSS2_BUBBLES = 185, @@ -114,12 +119,22 @@ enum SoundId : int SOUND_MEATHEADSHOOT = 226, SOUND_METAL_BLOCKBREAK = 229, SOUND_PLOP = 237, + SOUND_SATAN_APPEAR = 238, + SOUND_SATAN_BLAST = 239, + SOUND_SATAN_CHARGE_UP = 240, + SOUND_SATAN_GROW = 241, + SOUND_SATAN_HURT = 242, + SOUND_SATAN_RISE_UP = 243, + SOUND_SATAN_SPIT = 245, + SOUND_SATAN_STOMP = 246, SOUND_SCAMPER = 249, SOUND_SHELLGAME = 252, + SOUND_SLOTSPAWN = 255, SOUND_SPLATTER = 258, SOUND_STONESHOOT = 262, SOUND_WEIRD_WORM_SPIT = 263, SOUND_SUMMONSOUND = 265, + SOUND_SUPERHOLY = 266, SOUND_THUMBS_DOWN = 267, SOUND_THUMBSUP = 268, SOUND_HAPPY_RAINBOW = 270, @@ -146,6 +161,7 @@ enum SoundId : int SOUND_SKIN_PULL = 314, SOUND_WHISTLE = 315, SOUND_DEVILROOM_DEAL = 316, + SOUND_SPIDER_SPIT_ROAR = 317, SOUND_WORM_SPIT = 318, SOUND_LITTLE_SPIT = 319, SOUND_HEARTBEAT = 321, @@ -160,9 +176,11 @@ enum SoundId : int SOUND_BONE_SNAP = 462, SOUND_SHOVEL_DIG = 464, SOUND_GOLD_HEART_DROP = 466, + SOUND_CANDLE_LIGHT = 471, SOUND_BOSS2_DIVE = 474, SOUND_DEMON_HIT = 477, SOUND_WOOD_PLANK_BREAK = 481, + SOUND_BULLET_SHOT = 482, SOUND_FLAME_BURST = 483, SOUND_BATTERYDISCHARGE = 493, SOUND_FREEZE = 496, @@ -176,8 +194,10 @@ enum SoundId : int SOUND_MOM_AND_DAD_4 = 601, SOUND_VAMP_DOUBLE = 614, SOUND_GFUEL_AIR_HORN = 828, + SOUND_DARK_BUM_PAYOUT = 853, SOUND_POOP_THROW = 865, SOUND_SUMMON_WAVE = 872, + SOUND_PRIDE_ZAP = 903, SOUND_CAGE_DEATH = 918, SOUND_CAGE_JUMP = 919, SOUND_CAGE_RIBS = 920, @@ -206,6 +226,10 @@ enum SoundId : int SOUND_MEGAFATTY_SUCKIN = 957, SOUND_MEGAFATTY_VOMIT = 958, SOUND_STAIN_ATTACK_VOX = 959, + SOUND_FALLEN_FLAP_CHASE = 964, + SOUND_FALLEN_GROWL = 965, + SOUND_FALLEN_FLAP = 966, + SOUND_FALLEN_OPEN_WINGS = 967, SOUND_TERATOMA_BOUNCE_BIG = 968, SOUND_TERATOMA_BOUNCE_MEDIUM = 969, SOUND_TERATOMA_BOUNCE_SMALL = 970, @@ -237,11 +261,18 @@ enum SoundId : int SOUND_MONSTERS_NEXT_DOOR = 1008, SOUND_IMMACULATE_CONCEPTION = 1010, SOUND_SHINYROCK_SHIMMER = 1014, + SOUND_NECROMANCER = 1049, SOUND_TRAP_DOOR_LEVEL = 1052, SOUND_GIANT_CHEST_OPEN = 1075, SOUND_BRAIN_MOVE = 1080, SOUND_POISON_MIND_HURT = 1081, - SOUND_BUTTLICKER_GROWL = 1085 + SOUND_BUTTLICKER_GROWL = 1085, + SOUND_POT_BREAK = 138, + SOUND_SWORD_SPIN = 538, + SOUND_CUBE_BABY_KICK = 852, + SOUND_OCCULAR_RIFT_PORTAL = 1088, + SOUND_ROCKET_LAUNCH_SHORT = 585, + SOUND_ROCKET_LAUNCH_TINY = 586 }; // Construction, copies and destruction (00a2a990, 00a2aa60, 00a2ab40, 00a2ac90) are the defaults. diff --git a/src/video_player.cpp b/src/video_player.cpp new file mode 100644 index 0000000..6b015ca --- /dev/null +++ b/src/video_player.cpp @@ -0,0 +1,19 @@ +#include "video_player.h" +#include "manager.h" +#include "platform.h" + +// 009f2ee0 Opens an .ogv (or a mod's replacement) to play at a volume. With no decoder it only logs the video. +void VideoPlayer::play(std::string_view fileName, float volume) +{ + file = g_manager->modManager.TryRedirectPath(fileName); + log_printf(LOG_INFO, "VideoPlayer: no decoder for %s (volume %.2f), skipped\n", file.c_str(), volume); +} + +// 00a62880 Closes the clip. +void VideoPlayer::unload() { file.clear(); } + +// 00a62b10 Draws the clip's current frame at an offset. There is none without a decoder. +void VideoPlayer::render(Vector) {} + +// Whether the clip played to its end, or none is open. Without a decoder none ever is. +bool VideoPlayer::is_finished() { return true; } diff --git a/src/video_player.h b/src/video_player.h new file mode 100644 index 0000000..22701f2 --- /dev/null +++ b/src/video_player.h @@ -0,0 +1,18 @@ +#pragma once + +#include "classes.h" +#include +#include + +// Copies, assignment and destruction are the defaults. +// The cutscene player's video clip. The game carries no Theora decoder yet, so a clip never opens: play logs the +// video asked for, and the clip counts as finished at once, as a video the original fails to open does. +struct VideoPlayer +{ + std::string file; + + void play(std::string_view fileName, float volume); + void unload(); + void render(Vector offset); + bool is_finished(); +}; diff --git a/src/weapon.cpp b/src/weapon.cpp index 8433016..9a44968 100644 --- a/src/weapon.cpp +++ b/src/weapon.cpp @@ -1,5 +1,6 @@ #include "weapon.h" #include "weapon_lasers.h" +#include "weapon_bombs.h" #include "weapon_knives.h" #include "entity_familiar.h" #include "entity_player.h" @@ -42,7 +43,6 @@ constexpr int SEEDED_VARIANT_SPEEDY = 2; constexpr int COLLECTIBLE_EYE_DROPS = 600; constexpr int COLLECTIBLE_KIDNEY_STONE_WEAPON = 440; -constexpr int COLLECTIBLE_POLYPHEMUS = 169; constexpr int COLLECTIBLE_ANALOG_STICK = 465; constexpr int COLLECTIBLE_TECHNOLOGY_2 = 152; constexpr int COLLECTIBLE_ISAACS_TEARS = 323; @@ -88,12 +88,14 @@ static Vector vector_scale(Vector v, float scale) { return vector_make(v.x * sca static bool is_zero(Vector v) { return v.x == 0 && v.y == 0; } // 009f9020 Makes the weapon of a type for an owner through the type's maker, written for tears (009f9260), the -// lasers (weapon_laser_make) and the knife (weapon_knife_make). +// lasers (weapon_laser_make), the knife and clubs (weapon_knife_make) and Dr. Fetus (weapon_bomb_make). WeaponPtr weapon_create(WeaponType type, Entity* owner) { Weapon* made = type == WEAPON_TEARS ? new Weapon_Tears() : weapon_laser_make(type); if (!made) made = weapon_knife_make(type); - if (!made) reconstruction_missing("Isaac::CreateWeapon 009f9020 (weapons other than tears, lasers and knives)"); + if (!made) made = weapon_bomb_make(type); + if (!made) + reconstruction_missing("Isaac::CreateWeapon 009f9020 (Epic Fetus, Ludovico, C Section and the rest)"); WeaponPtr weapon(made); @@ -585,7 +587,6 @@ void Weapon::update_c_section_charge_anim(HeadCharge, const Vector&, float) { reconstruction_missing("Weapon::update_c_section_charge_anim 009f52c0"); } -Entity_Bomb* Weapon::fire_bomb(Weapon&, const PosVel&) { reconstruction_missing("Weapon::fire_bomb 009f5d60"); } // 00a0d870 Counts both eyes' fire delays down at the owner's speed, outside interpolation frames. void Weapon_Tears::Update(bool isInterpolated) diff --git a/src/weapon.h b/src/weapon.h index 786d58a..25f071f 100644 --- a/src/weapon.h +++ b/src/weapon.h @@ -264,6 +264,7 @@ struct Weapon Entity_Laser* fire_laser(const TechLaserShot& shot); Entity_Laser* fire_tech_x_laser(const TechXShot& shot); Entity_Knife* fire_knife(Entity* knifeParent, int knifeVariant, bool isCantOverwrite, float rotationOffset); + Entity_Knife* fire_bone_club(Entity* clubParent, int clubVariant, bool isCantOverwrite, float rotationOffset); Entity_Knife* FireSword(Entity* swordParent, int swordVariant, float rotationOffset, bool isUnknown1, bool isUnknown2, int unknown3, Entity* unknown4); }; diff --git a/src/weapon_bombs.cpp b/src/weapon_bombs.cpp new file mode 100644 index 0000000..b12ec27 --- /dev/null +++ b/src/weapon_bombs.cpp @@ -0,0 +1,131 @@ +#include "weapon_bombs.h" +#include "entity_bomb.h" +#include "entity_player.h" +#include "boss_ai.h" +#include "game.h" +#include "manager.h" +#include "npc_ai.h" +#include "sfx_manager.h" +#include + +// Dr. Fetus' throw: its speed, the slowest a bomb leaves at, Ludovico's push, and the blink. +constexpr float BOMB_THROW_SPEED = 12; +constexpr float BOMB_MIN_SPEED = 6; +constexpr float BOMB_LUDOVICO_PUSH = 1.2f * 0.5f; +constexpr float BOMB_BLINK_BASE = 7; +constexpr float BOMB_BLINK_SHARE = -0.45f; +constexpr float ROCKET_BIG_SCALE = 0.7f; +constexpr float BOMB_RANDOM_TURN = 360; + +// 009f9020's maker for Dr. Fetus' weapon (009f96c0), or none for the other types. +Weapon* weapon_bomb_make(WeaponType type) +{ + return type == WEAPON_BOMBS ? new Weapon_Bombs() : nullptr; +} + +// 009f5d60 Throws a bomb: through the owning player (a familiar's player, the familiar as the source), a rocket +// launching with its sound, never slower than a walk; or a plain bomb from the owner, unmoved by knockback. +Entity_Bomb* Weapon::fire_bomb(Weapon& weapon, const PosVel& shot) +{ + if (Entity_Player* player = weapon.owner_player()) + { + Entity_Bomb* bomb = player->FireBomb(shot.position, shot.velocity, weapon.owner); + if (bomb) + { + if (bomb->variant == BOMB_ROCKET || bomb->variant == BOMB_ROCKET_GIGA) + { + int sound = bomb->scale >= ROCKET_BIG_SCALE ? SOUND_ROCKET_LAUNCH_SHORT : SOUND_ROCKET_LAUNCH_TINY; + seed_fart_sound_override(&sound); + g_manager->sfxManager.Play(sound); + } + if (vector_length_squared(bomb->velocity) < BOMB_MIN_SPEED * BOMB_MIN_SPEED) + bomb->velocity = vector_scale(vector_normalized(bomb->velocity), BOMB_MIN_SPEED); + return bomb; + } + } + + Entity* bomb = game_spawn({.position = shot.position, + .velocity = shot.velocity, + .spawner = weapon.owner, + .type = ENTITY_BOMB, + .seed = Random()}, + POOL_OVERWRITE); + bomb->AddEntityFlags(FLAG_NO_KNOCKBACK); + bomb->parent = weapon.owner; + bomb->Update(); + return static_cast(bomb); +} + +// The camera follows Ludovico's bomb (009fa190). +Entity* Weapon_Bombs::GetFocusEntity() +{ + return (modifiers & WEAPON_MOD_LUDOVICO_TECHNIQUE) ? ludovicoBomb.get() : nullptr; +} + +// Marked's target (009fa1b0). +int Weapon_Bombs::GetMarkedTargetVariant() +{ + return marked_target_variant(); +} + +// 009f9b60 Throws Dr. Fetus' bombs once the fire delay passed: along the aim (snapped to the four directions unless +// free) with the owner's movement, one more backward and two sideways when the volley does, the random ones, and one +// per shot of the volley. Under Ludovico the volley's bombs chain from the first, and the shots steer that chain. +void Weapon_Bombs::Fire(const Vector& shootDirection, bool isShooting, bool isInterpolated) +{ + Weapon::Fire(shootDirection, isShooting, isInterpolated); + bool isLudovico = modifiers & WEAPON_MOD_LUDOVICO_TECHNIQUE; + Vector spawnPosition = owner ? owner->pos : Vector{}; + Entity_Player* player = owner_player(); + float shotSpeed = player ? player->shotSpeed : 1; + + bool isReady = isShooting && fireDelay < 0; + if (isReady && (!isLudovico || !ludovicoBomb)) + { + if (isInterpolated) return; + fireDelay = maxFireDelay; + SetBlinkTime((int)BOMB_BLINK_BASE - (int)(maxFireDelay * BOMB_BLINK_SHARE)); + Vector aim = IsAxisAligned() ? vector_cardinal(shootDirection) : vector_normalized(shootDirection); + TriggerTearEffects(aim, 1); + Vector throwVelocity = vector_add(vector_scale(aim, BOMB_THROW_SPEED), get_tear_movement_inheritance({})); + Weapon_MultiShotParams params = GetMultiShotParams(); + + if (params.isShootingBackwards) + fire_bomb(*this, {spawnPosition, vector_scale(throwVelocity, -shotSpeed)}); + if (params.isShootingSideways) + { + fire_bomb(*this, {spawnPosition, vector_scale(vector_make(-throwVelocity.y, throwVelocity.x), shotSpeed)}); + fire_bomb(*this, {spawnPosition, vector_scale(vector_make(throwVelocity.y, -throwVelocity.x), shotSpeed)}); + } + for (int i = 0; i < params.numRandomDirTears; i++) + { + float turn = random_unit() * BOMB_RANDOM_TURN * DEGREES_TO_RADIANS; + float c = std::cos(turn); + float s = std::sin(turn); + Vector turned = vector_make(c * throwVelocity.x - s * throwVelocity.y, s * throwVelocity.x + c * throwVelocity.y); + fire_bomb(*this, {spawnPosition, vector_scale(turned, shotSpeed)}); + } + + Entity* chainEnd = nullptr; + for (int i = 0; i < params.numTears; i++) + { + PosVel lane = Entity_Player::GetMultiShotPositionVelocity(i, WEAPON_BOMBS, throwVelocity, shotSpeed, params); + Entity_Bomb* bomb = fire_bomb(*this, {vector_add(spawnPosition, lane.position), lane.velocity}); + if (!isLudovico) continue; + if (chainEnd) chainEnd->child = bomb; + else ludovicoBomb = bomb; + chainEnd = bomb; + } + return; + } + if (!isReady && !isLudovico) return; + + Entity* bomb = ludovicoBomb; + if (!bomb || !isShooting) return; + Vector aim = shootDirection; + if (vector_length_squared(aim) > 1) aim = vector_normalized(aim); + Vector push = vector_scale(aim, shotSpeed * BOMB_LUDOVICO_PUSH); + for (; bomb; bomb = bomb->child) + if (bomb->friction != 0) + bomb->velocity = vector_add(bomb->velocity, vector_scale(push, bomb->speedMultiplier / bomb->friction)); +} diff --git a/src/weapon_bombs.h b/src/weapon_bombs.h new file mode 100644 index 0000000..c75c458 --- /dev/null +++ b/src/weapon_bombs.h @@ -0,0 +1,17 @@ +#pragma once + +#include "weapon.h" + +// Destruction (009f9880) is the default. +// Dr. Fetus' weapon: each shot throws a bomb (with the volley's extra, backward, sideways and random ones), or under +// Ludovico keeps a chain of bombs it steers with the shots. +struct Weapon_Bombs : Weapon +{ + EntityPtr ludovicoBomb; + + void Fire(const Vector& shootDirection, bool isShooting, bool isInterpolated) override; + Entity* GetFocusEntity() override; + int GetMarkedTargetVariant() override; +}; + +Weapon* weapon_bomb_make(WeaponType type); diff --git a/src/weapon_knives.cpp b/src/weapon_knives.cpp index 7123ebd..1836c99 100644 --- a/src/weapon_knives.cpp +++ b/src/weapon_knives.cpp @@ -8,6 +8,7 @@ #include "entity_tear.h" #include "game.h" #include "log.h" +#include "manager.h" #include "npc_ai.h" #include "npc_basement.h" #include @@ -34,9 +35,10 @@ constexpr int KNIFE_HEAD_LOCK = 2; // The angles the knife slots sit at around the aim: ahead, behind (Mom's Eye) and both sides (Loki's Horns). constexpr std::array KNIFE_SLOT_ANGLES = {0, 180, 90, -90}; -// 009f9020's maker for the knife weapon (009f9540), or none for the other types. +// 009f9020's makers for the knife and club weapons (009f9540, 009f9740), or none for the other types. Weapon* weapon_knife_make(WeaponType type) { + if (type == WEAPON_BONE || type == WEAPON_NOTCHED_AXE) return new Weapon_Bone(); return type == WEAPON_KNIFE ? new Weapon_Knife() : nullptr; } @@ -274,3 +276,483 @@ void Weapon_Knife::Fire(const Vector& shootDirection, bool isShooting, bool isIn SetBlinkTime(isThrownClose ? KNIFE_THROWN_BLINK : KNIFE_HELD_BLINK); if (main->isFlying && !isAimFixed && !isTractorBeam) SetHeadLockTime(KNIFE_HEAD_LOCK); } + +// Local until familiar_shoot.cpp drops its copy for the shared PlayerItemId enum. + +// The Forgotten's clubs: how long a swing lasts, how their size follows the holder, and how far a throw reaches. +constexpr float CLUB_CHARGE_DELAYS = 3; +constexpr float CLUB_FAST_CHARGE_DELAYS = 2; +constexpr float CLUB_FULL_CHARGE_MIN = 1.001f; +constexpr float CLUB_THROW_SHARE_MIN = 0.2f; +constexpr float CLUB_THROW_REACH = 300; +constexpr float CLUB_THROW_ORBIT_REACH = 100000; +constexpr float CLUB_THROW_RANGE_SHARE = 0.9f; +constexpr float CLUB_THROW_RANGE_MIN = 200; +constexpr float CLUB_THROW_SPREAD_SHARE = 0.5f; +constexpr float CLUB_FAMILIAR_SCALE = 0.8f; +constexpr float CLUB_MEGA_MUSH_SCALE = 4; +constexpr float CLUB_POLYPHEMUS_SCALE = 2; +constexpr float CLUB_HAEMOLACRIA_SCALE = 1.5f; +constexpr float CLUB_LIFT = -10; +constexpr float CLUB_FAMILIAR_LIFT = -20; +constexpr float CLUB_MASS = 3; +constexpr float CLUB_SOY_MASS = 0.5f; +constexpr float AXE_DAMAGE = 7; +constexpr float AXE_FIRE_DELAY = 15; +constexpr float AXE_EMPOWERED_FIRE_DELAY = 6; +constexpr float CLUB_SWING_BLINK_BASE = 7; +constexpr float CLUB_SWING_BLINK_SHARE = -0.45f; +constexpr float CLUB_SHAKE_DAMAGE = 20; +constexpr float CLUB_SHAKE_SCALE = 1.5f; +constexpr int CLUB_SHAKE_PER_SCALE = 5; +constexpr int CLUB_FLASH_INTERVAL = 4; +constexpr int CLUB_FLASH_FRAMES = 8; +constexpr int CLUB_FLASH_PRIORITY = 1; +constexpr float CLUB_FLASH_OFFSET = 0.2f; +constexpr int CLUB_SWING_SOUND = 252; +constexpr float CLUB_SWING_PITCH = 0.9f; +constexpr float CLUB_SWING_PITCH_SPREAD = 0.2f; +constexpr float CLUB_SWING_PITCH_MIN = 0.5f; +constexpr float CLUB_RANDOM_TURN = 360; +constexpr float FLYING_OFFSET_SCALE = 0.65f; +constexpr float SHOT_ROTATION_DEGREES = 45; + +// 009f6af0 Fires a bone club through the owning player (Entity_Player::FireBoneClub 007ae030): spawned by the player +// from its position, hanging from a parent at an angle with the player's tear color, flags and damage, raised by the +// player's flying offset when it can fly, kept from being overwritten when asked. The weapon's owner spawns it. +Entity_Knife* Weapon::fire_bone_club(Entity* clubParent, int clubVariant, bool isCantOverwrite, float rotationOffset) +{ + Entity_Player* player = owner_player(); + if (!player) return nullptr; + + Entity_Knife& club = *static_cast(game_spawn({.position = player->pos, + .spawner = player, + .type = ENTITY_KNIFE, + .variant = clubVariant, + .seed = Random()}, + POOL_OVERWRITE)); + club.parent = clubParent; + club.posOffset = vector_make(0, CLUB_LIFT); + if (player->canFly) + club.posOffset = vector_add(vector_scale(player->GetFlyingOffset(), 1 / FLYING_OFFSET_SCALE), club.posOffset); + club.SetColor(player->tearColor, -1, COLOR_PRIORITY_DEFAULT, false, true); + club.tearFlags = player->tearFlags; + club.SetCollisionDamage(player->damage); + club.rotationOffset = angle_wrap(rotationOffset); + if (isCantOverwrite) club.AddEntityFlags(FLAG_DONT_OVERWRITE); + club.spawnerEntity = owner; + return &club; +} + +// 009fa220 Notched Axe swings at its own pace (faster when empowered) and overrides the other weapons. The clubs ride at +// the holder's offset: a player's flying offset scaled by its size (four times under Mega Mush), a familiar's higher. +// Then the fire delay counts down. +void Weapon_Bone::Update(bool isInterpolated) +{ + Entity_Player* player = owner_player(); + Entity_Player* holder = owner && owner->is_player() ? owner->ToPlayer() : nullptr; + if (weaponType == WEAPON_NOTCHED_AXE) + { + maxFireDelay = player && player->HasCollectible(COLLECTIBLE_BOOK_OF_BELIAL_PASSIVE) ? AXE_EMPOWERED_FIRE_DELAY + : AXE_FIRE_DELAY; + modifiers = WEAPON_MOD_OVERRIDE; + } + + Vector offset = vector_make(0, CLUB_LIFT); + if (owner && !holder) + offset = vector_make(owner->sprite.scale.x * 0, + owner->sprite.scale.y * (owner->IsFamiliar() ? CLUB_FAMILIAR_LIFT : CLUB_LIFT)); + else if (holder) + { + float size = std::max(holder->playerSpriteScale.x, 1.0f); + int gridClass = holder->entityGridCollisionClass; + Vector lift = vector_make(0, CLUB_LIFT); + if (gridClass == GRIDCOLL_NONE || gridClass == GRIDCOLL_WALLS || gridClass == GRIDCOLL_WALLS_X || + gridClass == GRIDCOLL_WALLS_Y) + lift = vector_add(vector_scale(holder->GetFlyingOffset(), 1 / FLYING_OFFSET_SCALE), lift); + if (holder->temporaryEffects.HasCollectibleEffect(COLLECTIBLE_MEGA_MUSH)) size *= CLUB_MEGA_MUSH_SCALE; + offset = vector_add(vector_scale(lift, size), holder->posOffset); + } + for (EntityPtr& club : knives) + if (club) club->posOffset = offset; + Weapon::Update(isInterpolated); +} + +// 009fed90 Drops the links and restarts the fire delay, charge, aim and Cursed Eye's charges. +void Weapon_Bone::Reset() +{ + Weapon::Reset(); + cursedEyeCharges = 0; +} + +// 009fedf0 Removes Technology 2's laser, the clubs (which let go of their links), Epic Fetus' target and Ludovico's +// tear. +void Weapon_Bone::ClearReferences() +{ + if (technology2Laser) + { + technology2Laser->Remove(); + technology2Laser = nullptr; + } + for (EntityPtr& club : knives) + if (club) + { + club->Remove(); + club->ClearReferences(); + } + for (EntityPtr* link : {&epicFetusTarget, &ludovicoTear}) + if (*link) + { + (*link)->Remove(); + *link = nullptr; + } +} + +// 009feeb0 The charge a full throw takes: three fire delays, two with Cursed Eye, Brimstone, Monstro's Lung or C Section +// (unless Chocolate Milk). +float Weapon_Bone::GetMaxCharge() +{ + uint32_t fastModifiers = WEAPON_MOD_CURSED_EYE | WEAPON_MOD_BRIMSTONE | WEAPON_MOD_MONSTROS_LUNG | WEAPON_MOD_C_SECTION; + bool isFast = (modifiers & fastModifiers) && !(modifiers & WEAPON_MOD_CHOCOLATE_MILK); + return std::max(maxFireDelay, KNIFE_CHARGE_MINIMUM) * (isFast ? CLUB_FAST_CHARGE_DELAYS : CLUB_CHARGE_DELAYS); +} + +// The clubs come back to rest in a new room (009fef20, shared with Weapon_Knife). +void Weapon_Bone::TriggerNewRoom() +{ + for (EntityPtr& club : knives) + if (club) static_cast(club.get())->Reset(); +} + +// 009ff1a0 Whether a short charge lets Cursed Eye teleport the player: a player's club (not the axe) charged under two +// fire delays, unless Marked aims. +bool Weapon_Bone::CanTriggerCursedEyeTeleport() +{ + if (weaponType == WEAPON_NOTCHED_AXE || !owner || !owner->is_player()) return false; + if (owner->ToPlayer()->markedTarget && GetMarkedTargetVariant()) return false; + return charge > 0 && charge < std::max(maxFireDelay, KNIFE_CHARGE_MINIMUM) * 2; +} + +// 009ff210 Kidney Stone fires unless the club is thrown (never for the axe). +bool Weapon_Bone::CanTriggerKidneyStone() +{ + if (weaponType == WEAPON_NOTCHED_AXE) return false; + return !knives[0] || !static_cast(knives[0].get())->isFlying; +} + +// 009ff230 Whether the club stands in for the Forgotten's throw: with a charging item, with Dr. Fetus or Epic Fetus while +// the player holds something, or while the club is mid-attack. +bool Weapon_Bone::CanOverrideForgottenThrow() +{ + Entity_Player* player = owner_player(); + Entity_Player* holder = owner && owner->is_player() ? owner->ToPlayer() : nullptr; + bool isClub = weaponType != WEAPON_NOTCHED_AXE && player; + bool isEpicFetus = isClub && player->HasCollectible(COLLECTIBLE_EPIC_FETUS); + bool isDrFetus = isClub && player->HasCollectible(COLLECTIBLE_DR_FETUS) && !isEpicFetus; + uint32_t chargeModifiers = + WEAPON_MOD_CHOCOLATE_MILK | WEAPON_MOD_CURSED_EYE | WEAPON_MOD_BRIMSTONE | WEAPON_MOD_MONSTROS_LUNG; + if (modifiers & chargeModifiers) return true; + if ((isDrFetus || isEpicFetus) && holder && holder->heldEntity) return true; + return knives[0] && static_cast(knives[0].get())->isAttacking; +} + +// 009ff0c0 Gives a club the owner's look: the axe only its damage; a club the tear color, flags and damage, and its +// weight (light under Soy Milk). +void Weapon_Bone::init_club(Entity_Knife& club) +{ + if (weaponType == WEAPON_NOTCHED_AXE) + { + club.SetCollisionDamage(AXE_DAMAGE); + return; + } + club.SetColor(get_tear_color(), -1, COLOR_PRIORITY_DEFAULT, false, true); + club.tearFlags = get_owner_tear_flags(); + club.SetCollisionDamage(get_damage()); + club.mass = (modifiers & WEAPON_MOD_SOY_MILK) ? CLUB_SOY_MASS : CLUB_MASS; +} + +// The club a weapon swings: Notched Axe's axe, Mom's Knife's scythe, Berserk's jawbone, or the bone club. +int Weapon_Bone::club_variant() +{ + if (weaponType == WEAPON_NOTCHED_AXE) return KNIFE_NOTCHED_AXE; + Entity_Player* player = owner_player(); + if (player && player->HasCollectible(COLLECTIBLE_MOMS_KNIFE)) return KNIFE_BONE_SCYTHE; + if (player && player->temporaryEffects.HasCollectibleEffect(COLLECTIBLE_BERSERK)) return KNIFE_DONKEY_JAWBONE; + return KNIFE_BONE_CLUB; +} + +// How big the clubs are: as big as the player (at least normal), a familiar's smaller, four times under Mega Mush, +// doubled by Polyphemus or half again by Haemolacria. +float Weapon_Bone::club_scale() +{ + float size = 1; + if (owner && owner->is_player()) + size = std::max(owner->ToPlayer()->playerSpriteScale.x, 1.0f); + else if (owner && owner->IsFamiliar()) + size = std::max(owner->sprite.scale.x * CLUB_FAMILIAR_SCALE, CLUB_FAMILIAR_SCALE); + else if (owner) + size = std::max(owner->sprite.scale.x, 1.0f); + + Entity_Player* player = owner_player(); + if (!player || weaponType == WEAPON_NOTCHED_AXE) return size; + if (player->temporaryEffects.HasCollectibleEffect(COLLECTIBLE_MEGA_MUSH)) size *= CLUB_MEGA_MUSH_SCALE; + if (player->HasCollectible(COLLECTIBLE_POLYPHEMUS)) size *= CLUB_POLYPHEMUS_SCALE; + else if (player->HasCollectible(COLLECTIBLE_HAEMOLACRIA)) size *= CLUB_HAEMOLACRIA_SCALE; + return size; +} + +// The clubs held this frame: the main one always, Mom's Eye's behind and Loki's Horns' on every side, each made anew +// when missing or of another kind, and removed when their item is gone. +void Weapon_Bone::clubs_hold(int variant) +{ + Entity_Player* player = owner_player(); + bool isClub = weaponType != WEAPON_NOTCHED_AXE && player; + bool isLokisHorns = isClub && player->HasCollectible(COLLECTIBLE_LOKIS_HORNS); + bool isMomsEye = isClub && player->HasCollectible(COLLECTIBLE_MOMS_EYE); + + for (int slot = 0; slot < KNIFE_SLOT_COUNT; slot++) + { + EntityPtr& held = knives[slot]; + if (slot != 0 && !(slot == 1 && isMomsEye) && !isLokisHorns) + { + if (!held) continue; + held->Remove(); + held = nullptr; + continue; + } + if (held && held->type == ENTITY_KNIFE && held->variant == variant) continue; + if (held) held->Remove(); + + Entity_Knife* club = fire_bone_club(owner, variant, true, 0); + held = club; + club->rotation = KNIFE_SLOT_ANGLES[slot]; + club->isPrimaryClub = slot == 0; + club->Update(); + } +} + +// Where the clubs aim: the shot, the last aim, or the head's facing, snapped to the four directions unless the aim +// is free, and turned by R U A Wizard (or the spinning co-op baby). +Vector Weapon_Bone::shot_direction(const Vector& shootDirection) +{ + Vector shot = shootDirection; + Entity_Player* holder = owner && owner->is_player() ? owner->ToPlayer() : nullptr; + if (vector_is_zero(shot)) shot = direction; + if (vector_is_zero(shot) && holder && holder->headDirection != DIRECTION_NONE) + shot = vector_from_direction(holder->headDirection); + if (IsAxisAligned()) shot = vector_cardinal(shot); + if (holder && is_shot_rotated()) + { + float turn = (float)holder->tearDisplacement * SHOT_ROTATION_DEGREES * DEGREES_TO_RADIANS; + shot = vector_make(std::cos(turn) * shot.x - std::sin(turn) * shot.y, + std::cos(turn) * shot.y + std::sin(turn) * shot.x); + } + return shot; +} + +// The tear a swung club is made like: the owning player's hit params, with the tear side alternating at random. +ClubSwing Weapon_Bone::club_swing_get() +{ + ClubSwing swing; + if (Entity_Player* player = owner_player()) + { + int displacement = (int)(Random() & 1) * 2 - 1; + swing.params = player->GetTearHitParams(WEAPON_BONE, 1, displacement, owner); + } + swing.damage = swing.params.tearDamage; + swing.swingEffects = (modifiers & WEAPON_MOD_CURSED_EYE) ? (short)cursedEyeCharges : 1; + return swing; +} + +// One extra club fanned out from the held one at an angle, swinging with a fresh tear's look. Its damage. +float Weapon_Bone::club_fan(Entity_Knife& held, int variant, float angle, const ClubSwing& look) +{ + Entity_Knife* club = fire_bone_club(&held, variant, false, angle); + club->SetColor(look.params.tearColor, -1, COLOR_PRIORITY_DEFAULT, false, true); + club->tearFlags = look.params.tearFlags; + club->SetCollisionDamage(look.damage); + club->sprite.scale = held.sprite.scale; + club->swingEffects = look.swingEffects; + club->swingTick = 0; + club->SetAttackAnimation(); + club->Update(); + return look.damage; +} + +// A swing: the fire delay restarts, the tear side flips, the old fanned clubs go, the held clubs that fire this time +// (the side ones when the volley shoots sideways or backwards) swing with a fresh tear's look and damage, an extra club +// fans out for each extra shot and each random one, the swing sounds (lower for big clubs) and a heavy big club shakes +// the screen. +void Weapon_Bone::swing(const Vector& shot, float clubScale, int variant) +{ + Entity_Knife& held = *static_cast(knives[0].get()); + Entity_Player* holder = owner && owner->is_player() ? owner->ToPlayer() : nullptr; + Weapon_MultiShotParams params = GetMultiShotParams(); + fireDelay = std::max(maxFireDelay, KNIFE_CHARGE_MINIMUM); + if (holder) holder->tearDisplacement = (int8_t)-holder->tearDisplacement; + SetBlinkTime((int)CLUB_SWING_BLINK_BASE - (int)(fireDelay * CLUB_SWING_BLINK_SHARE)); + TriggerTearEffects(shot, 1); + float pitch = std::max(1 / (clubScale * 0.5f + 0.5f), CLUB_SWING_PITCH_MIN); + if (holder && holder->heldEntity) reconstruction_missing("Weapon_Bone::Fire 009fa450 (a held bomb or fetus)"); + + for (Entity* knife : entity_query(ENTITY_KNIFE, KNIFE_BONE_CLUB)) + if (knife->parent == &held) knife->Remove(); + + float heaviest = 0; + for (int slot = 0; slot < KNIFE_SLOT_COUNT; slot++) + { + Entity_Knife* club = static_cast(knives[slot].get()); + bool isFiring = slot == 0 || (slot == 1 && params.isShootingBackwards) || params.isShootingSideways; + if (!club || !isFiring) continue; + + ClubSwing look = club_swing_get(); + heaviest = std::max(look.damage, heaviest); + club->SetColor(look.params.tearColor, -1, COLOR_PRIORITY_DEFAULT, false, true); + club->tearFlags = look.params.tearFlags; + club->SetCollisionDamage(look.damage); + club->rotation = angle_wrap(vector_angle(shot) + KNIFE_SLOT_ANGLES[slot]); + club->swingEffects = look.swingEffects; + club->swingTick = 0; + club->SetAttackAnimation(); + club->isAttacking = true; + } + + float shotSpeed = owner_player() ? owner_player()->shotSpeed : 1; + for (int i = 0; i < params.numTears; i++) + { + PosVel lane = Entity_Player::GetMultiShotPositionVelocity(i, WEAPON_BONE, vector_make(1, 0), shotSpeed, params); + float angle = vector_angle(lane.velocity); + if (i == params.numTears / 2) held.rotationOffset = angle_wrap(angle); + else heaviest = std::max(club_fan(held, variant, angle, club_swing_get()), heaviest); + } + for (int i = 0; i < params.numRandomDirTears; i++) + { + ClubSwing look = club_swing_get(); + heaviest = std::max(club_fan(held, variant, random_unit() * CLUB_RANDOM_TURN, look), heaviest); + } + + pitch *= random_unit() * CLUB_SWING_PITCH_SPREAD + CLUB_SWING_PITCH; + int sound = CLUB_SWING_SOUND; + seed_fart_sound_override(&sound); + g_manager->sfxManager.Play(sound, {.frameDelay = 1, .pitch = pitch}); + if (heaviest > CLUB_SHAKE_DAMAGE && clubScale > CLUB_SHAKE_SCALE) game_shake_screen((int)(clubScale * CLUB_SHAKE_PER_SCALE)); + cursedEyeCharges = 0; + direction = {}; + if (holder && holder->playerType == PLAYER_THEFORGOTTEN_B) holder->TryForgottenThrow(shot); +} + +// A release after a charged swing: the fanned clubs close in, and the main club (and every club still mid-attack) +// flies out with the charge (at least a fifth) as far as the range allows, endlessly in orbit with Tiny Planet. +void Weapon_Bone::throw_clubs(const Vector& shot) +{ + for (Entity* knife : entity_query(ENTITY_KNIFE, KNIFE_BONE_CLUB)) + { + Entity* clubParent = knife->parent; + if (!clubParent || (clubParent != owner && clubParent->parent != owner)) continue; + Entity_Knife& club = *static_cast(knife); + club.rotationOffset = angle_wrap(club.rotationOffset * CLUB_THROW_SPREAD_SHARE); + } + + float delay = std::max(maxFireDelay, KNIFE_CHARGE_MINIMUM); + SetBlinkTime((int)CLUB_SWING_BLINK_BASE - (int)(delay * CLUB_SWING_BLINK_SHARE)); + TriggerTearEffects(shot, 1); + float full = delay * CLUB_CHARGE_DELAYS; + float share = std::max(std::min(charge, full) / full, CLUB_THROW_SHARE_MIN); + Entity_Player* player = owner_player(); + bool isOrbit = player && player->HasCollectible(COLLECTIBLE_TINY_PLANET); + float reach = isOrbit ? CLUB_THROW_ORBIT_REACH : CLUB_THROW_REACH; + float range = player ? player->tearRange : KNIFE_RANGE_DEFAULT; + range = std::max(std::min(range, reach) * CLUB_THROW_RANGE_SHARE, CLUB_THROW_RANGE_MIN); + + for (int slot = 0; slot < KNIFE_SLOT_COUNT; slot++) + { + Entity_Knife* club = static_cast(knives[slot].get()); + if (club && (slot == 0 || club->isAttacking)) club->Shoot(share, range); + } + SetHeadLockTime(KNIFE_HEAD_LOCK); + Entity_Player* holder = owner && owner->is_player() ? owner->ToPlayer() : nullptr; + if (holder && holder->playerType == PLAYER_THEFORGOTTEN_B) holder->TryForgottenThrow(shot); +} + +// 009fa450 Swings and throws the clubs: they sit around the owner turned toward the aim, growing to their size. A press +// swings once the fire delay passed (the swing leaves a charge of one); holding on after a swing charges, the club +// flashing once full; a release with more than a swing's charge throws. The charging items (Chocolate Milk, Cursed +// Eye, Brimstone, Monstro's Lung, C Section, Soy Milk's rapid swings), Dr. Fetus, Epic Fetus and Ludovico change all +// of this and are not reconstructed yet. TryForgottenThrow only acts for Tainted Forgotten, so it is only asked for +// him. +void Weapon_Bone::Fire(const Vector& shootDirection, bool isShooting, bool isInterpolated) +{ + Weapon::Fire(shootDirection, isShooting, isInterpolated); + Entity_Player* player = owner_player(); + Entity_Player* holder = owner && owner->is_player() ? owner->ToPlayer() : nullptr; + bool isClub = weaponType != WEAPON_NOTCHED_AXE && player; + uint32_t synergies = WEAPON_MOD_CHOCOLATE_MILK | WEAPON_MOD_CURSED_EYE | WEAPON_MOD_BRIMSTONE | + WEAPON_MOD_MONSTROS_LUNG | WEAPON_MOD_LUDOVICO_TECHNIQUE | WEAPON_MOD_SOY_MILK | + WEAPON_MOD_C_SECTION; + bool isFetus = isClub && (player->HasCollectible(COLLECTIBLE_DR_FETUS) || player->HasCollectible(COLLECTIBLE_EPIC_FETUS)); + bool isRapid = maxFireDelay <= 0 || (holder && holder->peeBurstCooldown >= 1) || + (holder && !holder->temporaryEffects.isDisabled && + holder->temporaryEffects.HasNullEffect(NULLITEM_SOUL_FORGOTTEN)); + if ((modifiers & synergies) || isFetus || isRapid) + reconstruction_missing("Weapon_Bone::Fire 009fa450 (the clubs with a charging item, Dr. Fetus, Epic Fetus, " + "Ludovico or rapid swings)"); + + float clubScale = club_scale(); + int variant = club_variant(); + float maxCharge = std::max(maxFireDelay, KNIFE_CHARGE_MINIMUM) * CLUB_CHARGE_DELAYS; + clubs_hold(variant); + Entity_Knife& held = *static_cast(knives[0].get()); + Vector shot = shot_direction(shootDirection); + + if (!held.isSwinging && !held.isFlying) + { + for (int slot = 0; slot < KNIFE_SLOT_COUNT; slot++) + if (Entity_Knife* club = static_cast(knives[slot].get())) + club->rotation = angle_wrap(vector_angle(shot) + KNIFE_SLOT_ANGLES[slot]); + if (!held.isAttacking) held.rotationOffset = 0; + + int age = g_game->frameCount - held.spawnFrame; + bool isResized = charge <= 0 || age < 2; + float size = charge <= 0 && age >= 2 ? (clubScale - held.sprite.scale.x) * 0.5f + held.sprite.scale.x : clubScale; + if (isResized) + for (EntityPtr& knife : knives) + if (Entity_Knife* club = static_cast(knife.get())) + { + init_club(*club); + club->sprite.scale = vector_make(size, size); + } + } + if (isInterpolated) return; + + float newCharge = charge; + if (!isShooting) + { + if (holder && holder->heldEntity) reconstruction_missing("Weapon_Bone::Fire 009fa450 (a held bomb or fetus)"); + if (charge > 1) throw_clubs(shot); + for (EntityPtr& knife : knives) + if (knife) static_cast(knife.get())->isAttacking = false; + direction = {}; + newCharge = 0; + } + else if (fireDelay < 0 && charge <= 0 && !held.isFlying) + { + swing(shot, clubScale, variant); + newCharge = 1; + } + else if (weaponType != WEAPON_NOTCHED_AXE && !held.isSwinging && charge >= 1) + { + newCharge = std::min(charge + 1, std::max(maxCharge, CLUB_FULL_CHARGE_MIN)); + ColorMod flash = {{1, 1, 1, 0}, {0, 0, 0, 0}, {0, 0, 0}}; + if (maxCharge <= charge) + { + flash = {{1, 1, 1, 1}, {0, 0, 0, 0}, {CLUB_FLASH_OFFSET, CLUB_FLASH_OFFSET, CLUB_FLASH_OFFSET}}; + color_multiply(flash, held.color); + } + if (held.GetIntervalTicks(CLUB_FLASH_INTERVAL, 0) && flash._tint[3] > 0) + held.SetColor(flash, CLUB_FLASH_FRAMES, CLUB_FLASH_PRIORITY, true, true); + direction = get_aim_direction(shot); + } + + if (held.isFlying) SetHeadLockTime(KNIFE_HEAD_LOCK); + charge = newCharge; +} diff --git a/src/weapon_knives.h b/src/weapon_knives.h index 14586ab..cd2c774 100644 --- a/src/weapon_knives.h +++ b/src/weapon_knives.h @@ -1,5 +1,6 @@ #pragma once +#include "entity_knife.h" #include "weapon.h" #include @@ -7,20 +8,6 @@ constexpr int KNIFE_SLOT_COUNT = 4; // How far above its parent a knife hangs. constexpr float KNIFE_LIFT = -10; -// The knives (Lua's KnifeVariant): Mom's Knife, the Forgotten's swung weapons, Bloody Babylon's and the swords. -enum KnifeVariant : int -{ - KNIFE_MOMS_KNIFE, - KNIFE_BONE_CLUB, - KNIFE_BONE_SCYTHE, - KNIFE_DONKEY_JAWBONE, - KNIFE_BAG_OF_CRAFTING, - KNIFE_SUMPTORIUM, - KNIFE_NOTCHED_AXE = 9, - KNIFE_SPIRIT_SWORD = 10, - KNIFE_TECH_SWORD = 11 -}; - // A throw of the held knives: the shot's direction, how far the range lets them fly (at least minRange) and the // variant of the extra knives. struct KnifeThrow @@ -53,4 +40,47 @@ struct Weapon_Knife : Weapon void ludovico_update(const Vector& shootDirection, bool isShooting, bool isInterpolated); }; +// What a swing gives each club it starts: the tear effects, color and damage of a fresh tear, and the extra swings. +struct ClubSwing +{ + TearParams params; + float damage = 0; + short swingEffects = 1; +}; + +// Destruction (009f9aa0) is the default. +// The Forgotten's weapon (and Notched Axe's): bone clubs held around the owner (Mom's Eye's behind, Loki's Horns' to the +// sides) that swing on a press, one more fanned out per extra shot, and once a held swing charges are thrown on +// release. Mom's Knife makes them scythes, Berserk jawbones. epicFetusTarget is Epic Fetus' target, ludovicoTear +// Ludovico's tear; neither combination is reconstructed yet. +struct Weapon_Bone : Weapon +{ + std::array knives; + EntityPtr epicFetusTarget; + EntityPtr ludovicoTear; + int cursedEyeCharges = 0; + + void Update(bool isInterpolated) override; + void Fire(const Vector& shootDirection, bool isShooting, bool isInterpolated) override; + void Reset() override; + void ClearReferences() override; + float GetMaxCharge() override; + // 0085e1b0 The camera follows Epic Fetus' target. + Entity* GetFocusEntity() override { return epicFetusTarget; } + void TriggerNewRoom() override; + bool CanTriggerCursedEyeTeleport() override; + bool CanTriggerKidneyStone() override; + bool CanOverrideForgottenThrow() override; + + void init_club(Entity_Knife& club); + int club_variant(); + float club_scale(); + void clubs_hold(int variant); + Vector shot_direction(const Vector& shootDirection); + ClubSwing club_swing_get(); + float club_fan(Entity_Knife& held, int variant, float angle, const ClubSwing& look); + void swing(const Vector& shot, float clubScale, int variant); + void throw_clubs(const Vector& shot); +}; + Weapon* weapon_knife_make(WeaponType type);