repo_id
stringlengths
4
98
size
int64
611
5.02M
file_path
stringlengths
1
276
content
stringlengths
611
5.02M
shard_id
int64
0
109
quality_score
float32
0.5
1
quality_prediction
int8
1
1
quality_confidence
float32
0.5
1
topic_primary
stringclasses
1 value
topic_group
stringclasses
1 value
topic_score
float32
0.05
1
topic_all
stringclasses
96 values
quality2_score
float32
0.5
1
quality2_prediction
int8
1
1
quality2_confidence
float32
0.5
1
hedgewars/hw
46,788
share/hedgewars/Data/Missions/Campaign/A_Classic_Fairytale/journey.lua
--[[ A Classic Fairytale: The Journey Back = SUMMARY = This is a very complex and heavily scripted mission with 2 major gameplay variants and 2 sub-variants each. This mission is mostly about movement and overcoming obstacles, and not much about fighting. The player has either 1 or 2 hogs (depending on previous mission) and must reach the left coast. The cyborg will show up from time to time and constantly annoys the heroes with obstacles and additional challenges. The mission's gameplay is affected by whether Dense Cloud survived in the previous mission. The mission's dialogues are affected by the decision of the player in the previous mission. = GOALS = - Collect the crate at the left coast - (Need to accomplish various sub-goals before this is possible) - Then kill the cyborg = FLOW CHART = == Linear events == Note: This mission's gameplay is significantly affected by the choices of the previous mission (The Shadow Falls). There are two major paths, and each of them has two variants. === PATH ONE (AL) === Condition: Cyborg's offer in ACF2 accepted and Dense Cloud survived. - Mission starts with Dense Cloud and Leaks a Lot - Mines time: 5s - Cut scene: startAnimAL (initial instructions) - Hog moves past flower (via teamwork) - Animation: pastFlowerAnimAL - Player jumps up the tree - Cut scene: outPutAnimAL - Cyborg teleports one hog to the pit, while the other hog remains - TBS - Trapped hog walks out of pit - Cut scene: midAnimAL - Trapped hog is teleported below bridge (and trapped again) - A huge barricade at the bridge is erected, and mines spawn on bridge - Now any hog needs to collect the final crate - TBS - Final crate collected - Cut scene: endAnimAL - Cyborg and princess apear, player must kill cyborg | Cyborg killed - Cut scene: winAnim > Victory | Princess killed - Cut scene: endFailAnim > Game over === PATH TWO (AD) === Condition: Cyborg's offer in ACF2 accepted, but Dense Cloud died afterwards. - Mission starts with Leaks a Lot only - Cut scene: startAnimAD (initial instructions) - Hog moves past flower (via blowtorch) - Animation: pastFlowerAnimAD - TBS - Hog proceeds all the way to the bridge - Cut scene: outPutAnimAD (the “Princess Game”) - Hog is teleported to the pit - TBS - Hog must reach goal crate within a given number of turns | Hog reaches goal crate within the turn limit - Cut scene: endAnimAD - Cyborg and princess spawn | Cyborg killed - Cut scene: winAnim > Victory | Princess killed - Cut scene: endFailAnim > Game over | Turn limit exceeded - Cut scene: failAnimAD (princess is caged and killed by cyborg) > Game over === PATH THREE (RL) === Condition: Cyborg's offer in ACF2 rejected. This is almost identical to Path One, only the dialogues differ. All AL animations are replaced with RL animations. === PATH FOUR (attacked) === Condition: Cyborg from ACF2 was attacked. This is almost identical to Path Two, only the dialogues differ. Uses startAnim and midAnim from SetupAnimAttacked. == Non-linear events == - Any of the Natives dies > Game over ]] HedgewarsScriptLoad("/Scripts/Locale.lua") HedgewarsScriptLoad("/Scripts/Animate.lua") --///////////////////////////////CONSTANTS/////////////////////////// choiceAccepted = 1 choiceRefused = 2 choiceAttacked = 3 endStage = 1 cannibalNum = 8 cannibalNames = {loc("John"), loc("Flesh for Brainz"), loc("Eye Chewer"), loc("Torn Muscle"), loc("Nom-Nom"), loc("Vedgies"), loc("Brain Blower"), loc("Gorkij")} cannibalPos = {{2471, 1174}, {939, 1019}, {1953, 902}, {3055, 1041}, {1121, 729}, {1150, 718}, {1149, 680}, {1161, 773}} startLeaksPosDuo = {3572, 1426} startEventXDuo = 3300 startDensePosDuo = {3454, 1471} startCyborgPosDuo = {3202, 1307} midDensePosDuo = {1464, 1410} midCyborgPosDuo = {1264, 1390} --///////////////////////////////VARIABLES/////////////////////////// m2Choice = 0 m2DenseDead = 0 TurnsLeft = 0 stage = 0 nativesTeamName = nil princessTeamName = nil cannibalsTeamName = nil cyborgTeamName = nil startAnimStarted = false blowTaken = false gravityTaken = false sniperTaken = false leaksDead = false denseDead = false princessDead = false cyborgDead = false victory = false cannibalDead = {} hedgeHidden = {} startAnim = {} startAnimAD = {} startAnimAL = {} startAnimRL = {} pastFlowerAnimAL = {} pastFlowerAnimRL = {} pastFlowerAnim = {} outPitAnimAL = {} outPitAnimRL = {} outPitAnim = {} midAnim = {} midAnimAD = {} failAnim = {} failAnimAD = {} endAnim = {} endAnimAD = {} endAnimAL = {} endAnimRL = {} endFailAnim = {} winAnim = {} winAnimAD = {} --/////////////////////////Animation Functions/////////////////////// function AfterMidFailAnim() EndTurn(true) end function AfterMidAnimAlone() SetupCourse() for i = 5, 8 do RestoreHedge(cannibals[i]) AnimSetGearPosition(cannibals[i], unpack(cannibalPos[i])) end AddAmmo(cannibals[5], amDEagle, 0) AddEvent(CheckOnFirstGirder, {}, DoOnFirstGirder, {}, 0) AddEvent(CheckTookSniper, {}, DoTookSniper, {}, 0) AddEvent(CheckFailedCourse, {}, DoFailedCourse, {}, 0) SetGearMessage(leaks, band(GetGearMessage(leaks), bnot(gmAllStoppable))) TurnsLeft = 12 SetTurnTimeLeft(TurnTime) ShowMission(loc("The Journey Back"), loc("Collateral Damage"), loc("Save the princess by collecting the crate in under 12 turns!") .. "|" .. loc("Mines time: 3 seconds"), 7, 6000) -----------------------///////////////------------ end function SkipEndAnimAlone() RestoreHedge(cyborg) RestoreHedge(princess) AnimSetGearPosition(cyborg, 437, 1700) AnimSetGearPosition(princess, 519, 1726) end function SkipEndAnimDuo() RestoreHedge(cyborg) RestoreHedge(princess) if princessHidden then RestoreHog(princess) princessHidden = false end AnimSetGearPosition(cyborg, 437, 1700) AnimSetGearPosition(princess, 519, 1726) AnimSetGearPosition(leaks, 763, 1760) AnimSetGearPosition(dense, 835, 1519) HogTurnLeft(leaks, true) HogTurnLeft(dense, true) end function AfterEndAnimAlone() stage = endStage SetGearMessage(dense, band(GetGearMessage(dense), bnot(gmAllStoppable))) AnimSwitchHog(leaks) SetTurnTimeLeft(MAX_TURN_TIME) ShowMission(loc("The Journey Back"), loc("Collateral Damage II"), loc("Save Fell From Heaven!"), 1, 4000) AddEvent(CheckLost, {}, DoLost, {}, 0) AddEvent(CheckWon, {}, DoWon, {}, 0) RemoveEventFunc(CheckFailedCourse) end function AfterEndAnimDuo() stage = endStage SetGearMessage(dense, band(GetGearMessage(dense), bnot(gmAllStoppable))) AnimSwitchHog(leaks) SetTurnTimeLeft(MAX_TURN_TIME) ShowMission(loc("The Journey Back"), loc("Collateral Damage II"), loc("Save Fell From Heaven!"), 1, 4000) AddEvent(CheckLost, {}, DoLost, {}, 0) AddEvent(CheckWon, {}, DoWon, {}, 0) end function SkipMidAnimAlone() AnimSetGearPosition(leaks, 2656, 1845) AnimSwitchHog(leaks) AnimWait(dense, 1) AddFunction({func = HideHedge, args = {princess}}) AddFunction({func = HideHedge, args = {cyborg}}) end function AfterStartAnim() SetGearMessage(leaks, band(GetGearMessage(leaks), bnot(gmAllStoppable))) SetTurnTimeLeft(TurnTime) local goal = loc("Get the crate on the other side of the island.") local hint = loc("Hint: You might want to stay out of sight and take all the crates ...") local stuck = loc("If you get stuck, use your Desert Eagle or restart the mission!") local conds = loc("Leaks A Lot must survive!") if m2DenseDead == 0 then conds = loc("Your hogs must survive!") end ShowMission(loc("The Journey Back"), loc("Adventurous"), goal .. "|" .. hint .. "|" .. stuck .. "|" .. conds, 1, 7000) end function SkipStartAnim() AnimTurn(leaks, "Left") AnimSwitchHog(leaks) end function PlaceCratesDuo() SpawnSupplyCrate(3090, 827, amBaseballBat) girderCrate1 = SpawnSupplyCrate(2366, 1814, amGirder) girderCrate2 = SpawnSupplyCrate(2630, 1278, amGirder) SpawnSupplyCrate(2322, 1810, amParachute) SpawnSupplyCrate(3157, 1009, amLowGravity) sniperCrate = SpawnSupplyCrate(784, 1715, amSniperRifle) end function PlaceMinesDuo() AddGear(2920, 1448, gtMine, 0, 0, 0, 0) AddGear(2985, 1338, gtMine, 0, 0, 0, 0) AddGear(3005, 1302, gtMine, 0, 0, 0, 0) AddGear(3030, 1270, gtMine, 0, 0, 0, 0) AddGear(3046, 1257, gtMine, 0, 0, 0, 0) AddGear(2954, 1400, gtMine, 0, 0, 0, 0) AddGear(2967, 1385, gtMine, 0, 0, 0, 0) AddGear(2849, 1449, gtMine, 0, 0, 0, 0) AddGear(2811, 1436, gtMine, 0, 0, 0, 0) AddGear(2773, 1411, gtMine, 0, 0, 0, 0) AddGear(2732, 1390, gtMine, 0, 0, 0, 0) AddGear(2700, 1362, gtMine, 0, 0, 0, 0) AddGear(2642, 1321, gtMine, 0, 0, 0, 0) AddGear(2172, 1417, gtMine, 0, 0, 0, 0) AddGear(2190, 1363, gtMine, 0, 0, 0, 0) AddGear(2219, 1332, gtMine, 0, 0, 0, 0) AddGear(1201, 1207, gtMine, 0, 0, 0, 0) AddGear(1247, 1205, gtMine, 0, 0, 0, 0) AddGear(1295, 1212, gtMine, 0, 0, 0, 0) AddGear(1356, 1209, gtMine, 0, 0, 0, 0) AddGear(1416, 1201, gtMine, 0, 0, 0, 0) AddGear(1466, 1201, gtMine, 0, 0, 0, 0) AddGear(1678, 1198, gtMine, 0, 0, 0, 0) AddGear(1738, 1198, gtMine, 0, 0, 0, 0) AddGear(1796, 1198, gtMine, 0, 0, 0, 0) AddGear(1637, 1217, gtMine, 0, 0, 0, 0) AddGear(1519, 1213, gtMine, 0, 0, 0, 0) end function AfterPastFlowerAnim() PlaceMinesDuo() AddEvent(CheckDensePit, {}, DoDensePit, {}, 0) SetGearMessage(dense, band(GetGearMessage(dense), bnot(gmAllStoppable))) SetGearMessage(leaks, band(GetGearMessage(leaks), bnot(gmAllStoppable))) EndTurn(true) ShowMission(loc("The Journey Back"), loc("The Savior"), loc("Get Dense Cloud out of the pit!") .. "|" .. loc("Your hogs must survive!") .. "|" .. loc("Beware of mines: They explode after 5 seconds."), 10, 5000) end function SkipPastFlowerAnim() AnimSetGearPosition(dense, 2656, 1845) AnimTurn(dense, "Left") AnimSwitchHog(leaks) AnimWait(leaks, 1) AddFunction({func = HideHedge, args = {cyborg}}) end function AfterOutPitAnim() SetupCourseDuo() RestoreHedge(cannibals[5]) AddAmmo(cannibals[5], amDEagle, 0) HideHedge(cannibals[5]) SetGearMessage(dense, band(GetGearMessage(dense), bnot(gmAllStoppable))) SetGearMessage(leaks, band(GetGearMessage(leaks), bnot(gmAllStoppable))) EndTurn(true) ShowMission(loc("The Journey Back"), loc("They never learn"), loc("Free Dense Cloud and continue the mission!") .. "|" .. loc("Collect the weapon crate at the left coast!") .. "|" .. loc("Your hogs must survive!") .. "|" .. loc("Mines time: 5 seconds"), 1, 5000) end function SkipOutPitAnim() AnimSetGearPosition(dense, unpack(midDensePosDuo)) AnimSwitchHog(dense) AnimWait(dense, 1) AddFunction({func = HideHedge, args = {cyborg}}) end function RestoreCyborg(x, y, xx, yy) RestoreHedge(cyborg) RestoreHedge(princess) AnimOutOfNowhere(cyborg, x, y) AnimOutOfNowhere(princess, xx, yy) HogTurnLeft(princess, false) return true end function RestoreCyborgOnly(x, y) RestoreHedge(cyborg) SetState(cyborg, 0) AnimOutOfNowhere(cyborg, x, y) return true end function TargetPrincess() SetWeapon(amDEagle) SetGearMessage(cyborg, gmUp) return true end function HideCyborg() HideHedge(cyborg) HideHedge(princess) end function HideCyborgOnly() HideHedge(cyborg) end function SetupKillRoom() PlaceGirder(2342, 1814, 2) PlaceGirder(2294, 1783, 0) PlaceGirder(2245, 1814, 2) end function SetupCourseDuo() PlaceGirder(1083, 1152, 6) PlaceGirder(1087, 1150, 6) PlaceGirder(1133, 1155, 0) PlaceGirder(1135, 1152, 0) PlaceGirder(1135, 1078, 0) PlaceGirder(1087, 1016, 2) PlaceGirder(1018, 921, 5) PlaceGirder(1016, 921, 5) PlaceGirder(962, 782, 6) PlaceGirder(962, 662, 2) PlaceGirder(962, 661, 2) PlaceGirder(962, 650, 2) PlaceGirder(962, 630, 2) PlaceGirder(1033, 649, 0) PlaceGirder(952, 650, 0) SpawnSupplyCrate(1846, 1100, amFirePunch, AMMO_INFINITE) SpawnSupplyCrate(1900, 1100, amPickHammer) SpawnSupplyCrate(950, 674, amDynamite) SpawnSupplyCrate(994, 825, amRope) SpawnSupplyCrate(570, 1357, amLowGravity) end local trackedGears = {} -- Remove mines and crates for the princess cage scene. -- Some annoying gears might get in the way for this scene, like a dropped -- mine, or the crate on the leaf. function ClearTrashForPrincessCage() for gear, _ in pairs(trackedGears) do if GetY(gear) > 1600 and GetX(gear) > 1800 and GetX(gear) < 2700 then DeleteGear(gear) end end end -- Dump mines in princess cage function DumpMines(t) if not t then t = 0 end AddGear(2261, 1835, gtMine, 0, 0, 0, t) AddGear(2280, 1831, gtMine, 0, 0, 0, t) AddGear(2272, 1809, gtMine, 0, 0, 0, t) AddGear(2290, 1815, gtMine, 0, 0, 0, t) AddGear(2278, 1815, gtMine, 0, 0, 0, t) AddGear(2307, 1811, gtMine, 0, 0, 0, t) AddGear(2286, 1820, gtMine, 0, 0, 0, t) AddGear(2309, 1813, gtMine, 0, 0, 0, t) AddGear(2303, 1822, gtMine, 0, 0, 0, t) AddGear(2317, 1827, gtMine, 0, 0, 0, t) AddGear(2312, 1816, gtMine, 0, 0, 0, t) AddGear(2316, 1812, gtMine, 0, 0, 0, t) AddGear(2307, 1802, gtMine, 0, 0, 0, t) AddGear(2276, 1818, gtMine, 0, 0, 0, t) AddGear(2284, 1816, gtMine, 0, 0, 0, t) AddGear(2292, 1811, gtMine, 0, 0, 0, t) AddGear(2295, 1814, gtMine, 0, 0, 0, t) AddGear(2306, 1811, gtMine, 0, 0, 0, t) AddGear(2292, 1815, gtMine, 0, 0, 0, t) AddGear(2314, 1815, gtMine, 0, 0, 0, t) AddGear(2286, 1813, gtMine, 0, 0, 0, t) AddGear(2275, 1813, gtMine, 0, 0, 0, t) AddGear(2269, 1814, gtMine, 0, 0, 0, t) AddGear(2273, 1812, gtMine, 0, 0, 0, t) AddGear(2300, 1808, gtMine, 0, 0, 0, t) AddGear(2322, 1812, gtMine, 0, 0, 0, t) AddGear(2323, 1813, gtMine, 0, 0, 0, t) AddGear(2311, 1811, gtMine, 0, 0, 0, t) AddGear(2303, 1809, gtMine, 0, 0, 0, t) AddGear(2287, 1808, gtMine, 0, 0, 0, t) AddGear(2282, 1808, gtMine, 0, 0, 0, t) AddGear(2277, 1809, gtMine, 0, 0, 0, t) AddGear(2296, 1809, gtMine, 0, 0, 0, t) AddGear(2314, 1818, gtMine, 0, 0, 0, t) end function SetupAnimRefusedDied() SetupAnimAcceptedDied() table.insert(startAnim, {func = AnimSay, args = {leaks, loc("I just wonder where Ramon and Spiky disappeared..."), SAY_THINK, 6000}}) end function SetupAnimAttacked() SetupAnimAcceptedDied() startAnim = {} table.insert(startAnim, {func = AnimWait, args = {leaks, 3000}}) table.insert(startAnim, {func = AnimTurn, args = {leaks, "Left"}}) table.insert(startAnim, {func = AnimSay, args = {leaks, loc("I wonder where Dense Cloud is..."), SAY_THINK, 4000}}) table.insert(startAnim, {func = AnimSay, args = {leaks, loc("He must be in the village already."), SAY_THINK, 4000}}) table.insert(startAnim, {func = AnimSay, args = {leaks, loc("I'd better get going myself."), SAY_THINK, 4000}}) AddSkipFunction(startAnim, SkipStartAnim, {}) midAnim = {} table.insert(midAnim, {func = AnimWait, args = {leaks, 500}}) table.insert(midAnim, {func = AnimCustomFunction, swh = false, args = {leaks, RestoreCyborg, {1300, 1200, 1390, 1200}}}) table.insert(midAnim, {func = AnimSwitchHog, args = {cyborg}}) table.insert(midAnim, {func = AnimCustomFunction, args = {cyborg, TargetPrincess, {}}}) table.insert(midAnim, {func = AnimSay, args = {cyborg, loc("Welcome, Leaks A Lot!"), SAY_SAY, 3000}}) table.insert(midAnim, {func = AnimSay, args = {cyborg, loc("I want to play a game..."), SAY_SAY, 3000}}) table.insert(midAnim, {func = AnimSay, args = {princess, loc("Help me, please!"), SAY_SHOUT, 3000}}) table.insert(midAnim, {func = AnimSay, args = {cyborg, loc("If you can get that crate fast enough, your beloved \"princess\" may go free."), SAY_SAY, 7000}}) table.insert(midAnim, {func = AnimSay, args = {cyborg, loc("However, if you fail to do so, she dies a most violent death! Muahahaha!"), SAY_SAY, 8000}}) table.insert(midAnim, {func = AnimSay, args = {cyborg, loc("Good luck...or else!"), SAY_SAY, 4000}}) table.insert(midAnim, {func = AnimTeleportGear, args = {leaks, 2656, 1845}}) table.insert(midAnim, {func = AnimCustomFunction, args = {cyborg, HideCyborg, {}}, swh = false}) table.insert(midAnim, {func = AnimSay, args = {leaks, loc("Hey! This is cheating!"), SAY_SHOUT, 4000}}) AddSkipFunction(midAnim, SkipMidAnimAlone, {}) end function SetupAnimAcceptedDied() table.insert(startAnimAD, {func = AnimWait, args = {leaks, 3000}}) table.insert(startAnimAD, {func = AnimTurn, args = {leaks, "Left"}}) table.insert(startAnimAD, {func = AnimSay, args = {leaks, loc("I need to get to the other side of this island, fast!"), SAY_THINK, 5000}}) table.insert(startAnimAD, {func = AnimSay, args = {leaks, loc("With Dense Cloud on the land of shadows, I'm the village's only hope..."), SAY_THINK, 7000}}) AddSkipFunction(startAnimAD, SkipStartAnim, {}) table.insert(midAnimAD, {func = AnimWait, args = {leaks, 500}}) table.insert(midAnimAD, {func = AnimCustomFunction, swh = false, args = {leaks, RestoreCyborg, {1300, 1200, 1390, 1200}}}) table.insert(midAnimAD, {func = AnimSwitchHog, args = {cyborg}}) table.insert(midAnimAD, {func = AnimCustomFunction, args = {cyborg, TargetPrincess, {}}}) table.insert(midAnimAD, {func = AnimSay, args = {cyborg, loc("Welcome, Leaks A Lot!"), SAY_SAY, 3000}}) table.insert(midAnimAD, {func = AnimSay, args = {cyborg, loc("I want to play a game..."), SAY_SAY, 3000}}) table.insert(midAnimAD, {func = AnimSay, args = {princess, loc("Help me, please!"), SAY_SHOUT, 3000}}) table.insert(midAnimAD, {func = AnimSay, args = {cyborg, loc("If you can get that crate fast enough, your beloved \"princess\" may go free."), SAY_SAY, 7000}}) table.insert(midAnimAD, {func = AnimSay, args = {cyborg, loc("However, if you fail to do so, she dies a most violent death, just like your friend! Muahahaha!"), SAY_SAY, 8000}}) table.insert(midAnimAD, {func = AnimSay, args = {cyborg, loc("Good luck...or else!"), SAY_SAY, 4000}}) table.insert(midAnimAD, {func = AnimTeleportGear, args = {leaks, 2656, 1845}}) table.insert(midAnimAD, {func = AnimCustomFunction, args = {cyborg, HideCyborg, {}}, swh = false}) table.insert(midAnimAD, {func = AnimSay, args = {leaks, loc("Hey! This is cheating!"), SAY_SHOUT, 4000}}) AddSkipFunction(midAnimAD, SkipMidAnimAlone, {}) table.insert(failAnimAD, {func = AnimCustomFunction, args = {cyborg, ClearTrashForPrincessCage, {}}}) table.insert(failAnimAD, {func = AnimCustomFunction, swh = false, args = {leaks, RestoreCyborg, {2299, 1687, 2294, 1845}}}) table.insert(failAnimAD, {func = AnimTeleportGear, args = {leaks, 2090, 1845}}) table.insert(failAnimAD, {func = AnimCustomFunction, swh = false, args = {cyborg, SetupKillRoom, {}}}) table.insert(failAnimAD, {func = AnimTurn, swh = false, args = {cyborg, "Left"}}) table.insert(failAnimAD, {func = AnimTurn, swh = false, args = {princess, "Left"}}) table.insert(failAnimAD, {func = AnimTurn, swh = false, args = {leaks, "Right"}}) table.insert(failAnimAD, {func = AnimWait, args = {cyborg, 1000}}) table.insert(failAnimAD, {func = AnimSay, args = {cyborg, loc("You have failed to complete your task, young one!"), SAY_SAY, 6000}}) table.insert(failAnimAD, {func = AnimSay, args = {cyborg, loc("It's time you learned that your actions have consequences!"), SAY_SAY, 7000}}) table.insert(failAnimAD, {func = AnimSay, args = {princess, loc("No! Please, help me!"), SAY_SAY, 4000}}) table.insert(failAnimAD, {func = AnimSwitchHog, args = {cyborg}}) table.insert(failAnimAD, {func = AnimCustomFunction, args = {cyborg, DumpMines, {}}}) table.insert(failAnimAD, {func = AnimCustomFunction, args = {cyborg, KillPrincess, {}}}) table.insert(failAnimAD, {func = AnimWait, args = {cyborg, 500}}) table.insert(failAnimAD, {func = AnimSay, args = {leaks, loc("No! What have I done?! What have YOU done?!"), SAY_SHOUT, 3000}}) table.insert(failAnimAD, {func = AnimSwitchHog, args = {princess}}) AddSkipFunction(failAnimAD, SkipFailAnimAlone, {}) table.insert(endAnimAD, {func = AnimCustomFunction, swh = false, args = {leaks, RestoreCyborg, {437, 1700, 519, 1726}}}) table.insert(endAnimAD, {func = AnimTurn, swh = false, args = {cyborg, "Right"}}) table.insert(endAnimAD, {func = AnimTurn, swh = false, args = {princess, "Right"}}) table.insert(endAnimAD, {func = AnimSay, args = {princess, loc("Help me, Leaks!"), SAY_SHOUT, 3000}}) table.insert(endAnimAD, {func = AnimSay, args = {leaks, loc("But you said you'd let her go!"), SAY_SHOUT, 5000}}) table.insert(endAnimAD, {func = AnimSay, args = {cyborg, loc("And you believed me? Oh, god, that's cute!"), SAY_SHOUT, 7000}}) table.insert(endAnimAD, {func = AnimSay, args = {leaks, loc("I won't let you kill her!"), SAY_SHOUT, 4000}}) AddSkipFunction(endAnimAD, SkipEndAnimAlone, {}) table.insert(endFailAnim, {func = AnimCaption, args = {leaks, loc("Leaks A Lot, depressed for killing his loved one, failed to save the village..."), 3000}}) table.insert(winAnimAD, {func = AnimCustomFunction, args = {princess, CondNeedToTurn, {leaks, princess}}}) table.insert(winAnimAD, {func = AnimSay, args = {princess, loc("Thank you, oh, thank you, Leaks A Lot!"), SAY_SAY, 5000}}) table.insert(winAnimAD, {func = AnimSay, args = {princess, loc("How can I ever repay you for saving my life?"), SAY_SAY, 6000}}) table.insert(winAnimAD, {func = AnimSay, args = {leaks, loc("There's nothing more satisfying for me than seeing you share your beauty with the world every morning, my princess!"), SAY_SAY, 10000}}) table.insert(winAnimAD, {func = AnimSay, args = {leaks, loc("Let's go home!"), SAY_SAY, 3000}}) table.insert(winAnimAD, {func = AnimCaption, args = {leaks, loc("And so they discovered that cyborgs weren't invulnerable..."), 2000}}) startAnim = startAnimAD midAnim = midAnimAD failAnim = failAnimAD endAnim = endAnimAD winAnim = winAnimAD end function SetupAnimAcceptedLived() table.insert(startAnimAL, {func = AnimWait, args = {leaks, 3000}}) table.insert(startAnimAL, {func = AnimCustomFunction, args = {dense, CondNeedToTurn, {leaks, dense}}}) table.insert(startAnimAL, {func = AnimSay, args = {leaks, loc("All right, we just need to get to the other side of the island!"), SAY_SAY, 8000}}) table.insert(startAnimAL, {func = AnimSay, args = {dense, loc("We have no time to waste..."), SAY_SAY, 4000}}) table.insert(startAnimAL, {func = AnimSwitchHog, args = {leaks}}) AddSkipFunction(startAnimAL, SkipStartAnim, {}) table.insert(pastFlowerAnimAL, {func = AnimCustomFunction, args = {dense, RestoreCyborgOnly, {unpack(startCyborgPosDuo)}}, swh = false}) table.insert(pastFlowerAnimAL, {func = AnimTurn, args = {cyborg, "Right"}}) table.insert(pastFlowerAnimAL, {func = AnimSay, args = {cyborg, loc("Well, well! Isn't that the cutest thing you've ever seen?"), SAY_SAY, 7000}}) table.insert(pastFlowerAnimAL, {func = AnimSay, args = {cyborg, loc("Two little hogs cooperating, getting past obstacles..."), SAY_SAY, 7000}}) table.insert(pastFlowerAnimAL, {func = AnimSay, args = {cyborg, loc("Let me test your skills a little, will you?"), SAY_SAY, 6000}}) table.insert(pastFlowerAnimAL, {func = AnimWait, args = {cyborg, 2000}}) table.insert(pastFlowerAnimAL, {func = AnimTeleportGear, args = {cyborg, 2456, 1845}}) table.insert(pastFlowerAnimAL, {func = AnimTeleportGear, args = {dense, 2656, 1845}}) table.insert(pastFlowerAnimAL, {func = AnimCustomFunction, args = {dense, CondNeedToTurn, {cyborg, dense}}}) table.insert(pastFlowerAnimAL, {func = AnimSay, args = {dense, loc("Why are you doing this?"), SAY_SAY, 4000}}) table.insert(pastFlowerAnimAL, {func = AnimSay, args = {cyborg, loc("To help you, of course!"), SAY_SAY, 4000}}) table.insert(pastFlowerAnimAL, {func = AnimSwitchHog, args = {leaks}}) table.insert(pastFlowerAnimAL, {func = AnimDisappear, swh = false, args = {cyborg, 3781, 1583}}) table.insert(pastFlowerAnimAL, {func = AnimCustomFunction, swh = false, args = {cyborg, HideCyborgOnly, {}}}) AddSkipFunction(pastFlowerAnimAL, SkipPastFlowerAnim, {}) table.insert(outPitAnimAL, {func = AnimCustomFunction, args = {dense, RestoreCyborgOnly, {unpack(midCyborgPosDuo)}}, swh = false}) table.insert(outPitAnimAL, {func = AnimTurn, args = {cyborg, "Right"}}) table.insert(outPitAnimAL, {func = AnimTeleportGear, args = {dense, unpack(midDensePosDuo)}}) table.insert(outPitAnimAL, {func = AnimTurn, args = {dense, "Left"}}) table.insert(outPitAnimAL, {func = AnimSay, args = {dense, loc("OH, COME ON!"), SAY_SHOUT, 3000}}) table.insert(outPitAnimAL, {func = AnimSay, args = {cyborg, loc("Let's see what your comrade does now!"), SAY_SAY, 5000}}) table.insert(outPitAnimAL, {func = AnimSwitchHog, args = {dense}}) table.insert(outPitAnimAL, {func = AnimDisappear, swh = false, args = {cyborg, 3781, 1583}}) table.insert(outPitAnimAL, {func = AnimCustomFunction, swh = false, args = {cyborg, HideCyborgOnly, {}}}) AddSkipFunction(outPitAnimAL, SkipOutPitAnim, {}) table.insert(endAnim, {func = AnimCustomFunction, swh = false, args = {leaks, RestoreCyborg, {437, 1700, 519, 1726}}}) table.insert(endAnim, {func = AnimTeleportGear, args = {leaks, 763, 1760}}) table.insert(endAnim, {func = AnimTeleportGear, args = {dense, 835, 1519}}) table.insert(endAnim, {func = AnimTurn, swh = false, args = {leaks, "Left"}}) table.insert(endAnim, {func = AnimTurn, swh = false, args = {dense, "Left"}}) table.insert(endAnim, {func = AnimTurn, swh = false, args = {cyborg, "Right"}}) table.insert(endAnim, {func = AnimTurn, swh = false, args = {princess, "Right"}}) table.insert(endAnim, {func = AnimSay, args = {princess, loc("Help me, please!"), SAY_SHOUT, 3000}}) table.insert(endAnim, {func = AnimSay, args = {leaks, loc("What are you doing? Let her go!"), SAY_SHOUT, 5000}}) table.insert(endAnim, {func = AnimSay, args = {cyborg, loc("Yeah? Watcha gonna do? Cry?"), SAY_SHOUT, 5000}}) table.insert(endAnim, {func = AnimSay, args = {leaks, loc("We won't let you hurt her!"), SAY_SHOUT, 4000}}) AddSkipFunction(endAnim, SkipEndAnimDuo, {}) table.insert(endFailAnim, {func = AnimCaption, args = {leaks, loc("Leaks A Lot, depressed for killing his loved one, failed to save the village..."), 3000}}) table.insert(winAnim, {func = AnimCustomFunction, args = {princess, CondNeedToTurn, {leaks, princess}}}) table.insert(winAnim, {func = AnimSay, args = {princess, loc("Thank you, oh, thank you, my heroes!"), SAY_SAY, 5000}}) table.insert(winAnim, {func = AnimSay, args = {princess, loc("How can I ever repay you for saving my life?"), SAY_SAY, 6000}}) table.insert(winAnim, {func = AnimSay, args = {leaks, loc("There's nothing more satisfying to us than seeing you share your beauty..."), SAY_SAY, 7000}}) table.insert(winAnim, {func = AnimSay, args = {leaks, loc("... share your beauty with the world every morning, my princess!"), SAY_SAY, 7000}}) table.insert(winAnim, {func = AnimSay, args = {leaks, loc("Let's go home!"), SAY_SAY, 3000}}) table.insert(winAnim, {func = AnimCaption, args = {leaks, loc("And so they discovered that cyborgs weren't invulnerable..."), 2000}}) startAnim = startAnimAL pastFlowerAnim = pastFlowerAnimAL outPitAnim = outPitAnimAL end function SetupAnimRefusedLived() table.insert(startAnimRL, {func = AnimWait, args = {leaks, 3000}}) table.insert(startAnimRL, {func = AnimCustomFunction, args = {dense, CondNeedToTurn, {leaks, dense}}}) table.insert(startAnimRL, {func = AnimSay, args = {leaks, loc("All right, we just need to get to the other side of the island!"), SAY_SAY, 7000}}) table.insert(startAnimRL, {func = AnimSay, args = {dense, loc("Dude, can you see Ramon and Spiky?"), SAY_SAY, 5000}}) table.insert(startAnimRL, {func = AnimSay, args = {leaks, loc("No...I wonder where they disappeared?!"), SAY_SAY, 5000}}) AddSkipFunction(startAnimRL, SkipStartAnim, {}) table.insert(pastFlowerAnimRL, {func = AnimCustomFunction, args = {dense, RestoreCyborgOnly, {unpack(startCyborgPosDuo)}}, swh = false}) table.insert(pastFlowerAnimRL, {func = AnimTurn, args = {cyborg, "Right"}}) table.insert(pastFlowerAnimRL, {func = AnimSay, args = {cyborg, loc("Well, well! Isn't that the cutest thing you've ever seen?"), SAY_SAY, 7000}}) table.insert(pastFlowerAnimRL, {func = AnimSay, args = {cyborg, loc("Two little hogs cooperating, getting past obstacles..."), SAY_SAY, 7000}}) table.insert(pastFlowerAnimRL, {func = AnimSay, args = {cyborg, loc("Let me test your skills a little, will you?"), SAY_SAY, 6000}}) table.insert(pastFlowerAnimRL, {func = AnimWait, args = {cyborg, 2000}}) table.insert(pastFlowerAnimRL, {func = AnimTeleportGear, args = {cyborg, 2456, 1845}}) table.insert(pastFlowerAnimRL, {func = AnimTeleportGear, args = {dense, 2656, 1845}}) table.insert(pastFlowerAnimRL, {func = AnimCustomFunction, args = {dense, CondNeedToTurn, {cyborg, dense}}}) table.insert(pastFlowerAnimRL, {func = AnimSay, args = {dense, loc("Why are you doing this?"), SAY_SAY, 4000}}) table.insert(pastFlowerAnimRL, {func = AnimSay, args = {cyborg, loc("You couldn't possibly believe that after refusing my offer I'd just let you go!"), SAY_SAY, 9000}}) table.insert(pastFlowerAnimRL, {func = AnimSay, args = {cyborg, loc("You're funny!"), SAY_SAY, 4000}}) table.insert(pastFlowerAnimRL, {func = AnimSwitchHog, args = {dense}}) table.insert(pastFlowerAnimRL, {func = AnimDisappear, swh = false, args = {cyborg, 3781, 1583}}) table.insert(pastFlowerAnimRL, {func = AnimCustomFunction, swh = false, args = {cyborg, HideCyborgOnly, {}}}) AddSkipFunction(pastFlowerAnimRL, SkipPastFlowerAnim, {}) table.insert(outPitAnimRL, {func = AnimCustomFunction, args = {dense, RestoreCyborgOnly, {unpack(midCyborgPosDuo)}}, swh = false}) table.insert(outPitAnimRL, {func = AnimTurn, args = {cyborg, "Right"}}) table.insert(outPitAnimRL, {func = AnimTeleportGear, args = {dense, unpack(midDensePosDuo)}}) table.insert(outPitAnimRL, {func = AnimTurn, args = {dense, "Left"}}) table.insert(outPitAnimRL, {func = AnimSay, args = {dense, loc("OH, COME ON!"), SAY_SHOUT, 3000}}) table.insert(outPitAnimRL, {func = AnimSay, args = {cyborg, loc("Let's see what your comrade does now!"), SAY_SAY, 5000}}) table.insert(outPitAnimRL, {func = AnimSwitchHog, args = {dense}}) table.insert(outPitAnimRL, {func = AnimDisappear, swh = false, args = {cyborg, 3781, 1583}}) table.insert(outPitAnimRL, {func = AnimCustomFunction, swh = false, args = {cyborg, HideCyborgOnly, {}}}) AddSkipFunction(outPitAnimRL, SkipOutPitAnim, {}) table.insert(endAnim, {func = AnimCustomFunction, args = {leaks, RestoreCyborg, {437, 1700, 519, 1726}}}) table.insert(endAnim, {func = AnimTeleportGear, args = {leaks, 763, 1760}}) table.insert(endAnim, {func = AnimTeleportGear, args = {dense, 835, 1519}}) table.insert(endAnim, {func = AnimTurn, swh = false, args = {leaks, "Left"}}) table.insert(endAnim, {func = AnimTurn, swh = false, args = {dense, "Left"}}) table.insert(endAnim, {func = AnimTurn, swh = false, args = {cyborg, "Right"}}) table.insert(endAnim, {func = AnimTurn, swh = false, args = {princess, "Right"}}) table.insert(endAnim, {func = AnimSay, args = {princess, loc("Help me, please!"), SAY_SHOUT, 3000}}) table.insert(endAnim, {func = AnimSay, args = {leaks, loc("What are you doing? Let her go!"), SAY_SHOUT, 5000}}) table.insert(endAnim, {func = AnimSay, args = {cyborg, loc("Yeah? Watcha gonna do? Cry?"), SAY_SHOUT, 5000}}) table.insert(endAnim, {func = AnimSay, args = {leaks, loc("We won't let you hurt her!"), SAY_SHOUT, 4000}}) AddSkipFunction(endAnim, SkipEndAnimDuo, {}) table.insert(endFailAnim, {func = AnimCaption, args = {leaks, loc("Leaks A Lot, depressed for killing his loved one, failed to save the village..."), 3000}}) table.insert(winAnim, {func = AnimCustomFunction, args = {princess, CondNeedToTurn, {leaks, princess}}}) table.insert(winAnim, {func = AnimSay, args = {princess, loc("Thank you, oh, thank you, my heroes!"), SAY_SAY, 5000}}) table.insert(winAnim, {func = AnimSay, args = {princess, loc("How can I ever repay you for saving my life?"), SAY_SAY, 6000}}) table.insert(winAnim, {func = AnimSay, args = {leaks, loc("There's nothing more satisfying to us than seeing you share your beauty with the world every morning, my princess!"), SAY_SAY, 10000}}) table.insert(winAnim, {func = AnimSay, args = {leaks, loc("Let's go home!"), SAY_SAY, 3000}}) table.insert(winAnim, {func = AnimCaption, args = {leaks, loc("And so they discovered that cyborgs weren't invulnerable..."), 2000}}) startAnim = startAnimRL pastFlowerAnim = pastFlowerAnimRL outPitAnim = outPitAnimRL end function KillPrincess() EndTurn(true) end --/////////////////////////////Misc Functions//////////////////////// function HideHedge(hedge) if hedgeHidden[hedge] ~= true then HideHog(hedge) hedgeHidden[hedge] = true end end function RestoreHedge(hedge) if hedgeHidden[hedge] == true then RestoreHog(hedge) hedgeHidden[hedge] = false end end function CondNeedToTurn(hog1, hog2) local xl, xd = GetX(hog1), GetX(hog2) if xl > xd then AnimInsertStepNext({func = AnimTurn, args = {hog1, "Left"}}) AnimInsertStepNext({func = AnimTurn, args = {hog2, "Right"}}) elseif xl < xd then AnimInsertStepNext({func = AnimTurn, args = {hog2, "Left"}}) AnimInsertStepNext({func = AnimTurn, args = {hog1, "Right"}}) end end function NeedToTurn(hog1, hog2) local xl, xd = GetX(hog1), GetX(hog2) if xl > xd then AnimTurn(hog1, "Left") AnimTurn(hog2, "Right") elseif xl < xd then AnimTurn(hog2, "Left") AnimTurn(hog1, "Right") end end function SetupPlaceAlone() ------ AMMO CRATE LIST ------ SpawnSupplyCrate(3124, 952, amBaseballBat) SpawnSupplyCrate(2508, 1110, amFirePunch) ------ UTILITY CRATE LIST ------ blowCrate = SpawnSupplyCrate(3675, 1480, amBlowTorch) gravityCrate = SpawnSupplyCrate(3448, 1349, amLowGravity) SpawnSupplyCrate(3212, 1256, amGirder) SpawnSupplyCrate(3113, 911, amParachute) sniperCrate = SpawnSupplyCrate(784, 1715, amSniperRifle) ------ MINE LIST ------ AddGear(3328, 1399, gtMine, 0, 0, 0, 0) AddGear(3028, 1262, gtMine, 0, 0, 0, 0) AddGear(2994, 1274, gtMine, 0, 0, 0, 0) AddGear(2956, 1277, gtMine, 0, 0, 0, 0) AddGear(2925, 1282, gtMine, 0, 0, 0, 0) AddGear(2838, 1276, gtMine, 0, 0, 0, 0) AddGear(2822, 1278, gtMine, 0, 0, 0, 0) AddGear(2786, 1283, gtMine, 0, 0, 0, 0) AddGear(2766, 1270, gtMine, 0, 0, 0, 0) AddGear(2749, 1231, gtMine, 0, 0, 0, 0) AddGear(2717, 1354, gtMine, 0, 0, 0, 0) AddGear(2167, 1330, gtMine, 0, 0, 0, 0) AddGear(2201, 1321, gtMine, 0, 0, 0, 0) AddGear(2239, 1295, gtMine, 0, 0, 0, 0) AnimSetGearPosition(leaks, 3781, 1583) AddAmmo(cannibals[1], amShotgun, AMMO_INFINITE) AddAmmo(leaks, amSwitch, 0) end function SetupPlaceDuo() PlaceCratesDuo() AnimSetGearPosition(leaks, unpack(startLeaksPosDuo)) AnimSetGearPosition(dense, unpack(startDensePosDuo)) end function SetupEventsDuo() AddEvent(CheckPastFlower, {}, DoPastFlower, {}, 0) AddEvent(CheckLeaksDead, {}, DoLeaksDead, {}, 0) AddEvent(CheckDenseDead, {}, DoDenseDead, {}, 0) AddEvent(CheckTookSniper2, {}, DoTookSniper2, {}, 0) end function SetupEventsAlone() AddEvent(CheckLeaksDead, {}, DoLeaksDead, {}, 0) AddEvent(CheckTookBlowTorch, {}, DoTookBlowTorch, {}, 0) AddEvent(CheckTookLowGravity, {}, DoTookLowGravity, {}, 0) AddEvent(CheckOnBridge, {}, DoOnBridge, {}, 0) end function StartMission() if m2DenseDead == 1 then DeleteGear(dense) if m2Choice == choiceAccepted then SetupAnimAcceptedDied() elseif m2Choice == choiceRefused then SetupAnimRefusedDied() else SetupAnimAttacked() end SetupPlaceAlone() SetupEventsAlone() else if m2Choice == choiceAccepted then SetupAnimAcceptedLived() else SetupAnimRefusedLived() end SetupPlaceDuo() SetupEventsDuo() end HideHedge(cyborg) HideHedge(princess) for i = 5, 8 do HideHedge(cannibals[i]) end end function SetupCourse() ------ GIRDER LIST ------ PlaceGirder(1091, 1150, 6) PlaceGirder(1091, 989, 6) PlaceGirder(1091, 829, 6) PlaceGirder(1091, 669, 6) PlaceGirder(1091, 668, 6) PlaceGirder(1091, 669, 6) PlaceGirder(1088, 667, 6) PlaceGirder(1091, 658, 6) PlaceGirder(1091, 646, 6) PlaceGirder(1091, 607, 6) PlaceGirder(1091, 571, 6) PlaceGirder(1376, 821, 6) PlaceGirder(1145, 1192, 1) PlaceGirder(1169, 1076, 3) PlaceGirder(1351, 1082, 4) PlaceGirder(1469, 987, 3) PlaceGirder(1386, 951, 0) PlaceGirder(1465, 852, 3) PlaceGirder(1630, 913, 0) PlaceGirder(1733, 856, 7) PlaceGirder(1688, 713, 5) PlaceGirder(1556, 696, 2) PlaceGirder(1525, 696, 2) PlaceGirder(1457, 697, 2) PlaceGirder(1413, 700, 3) PlaceGirder(1270, 783, 2) PlaceGirder(1207, 825, 2) PlaceGirder(1135, 775, 1) ------ UTILITY CRATE LIST ------ SpawnSupplyCrate(1590, 628, amParachute) SpawnSupplyCrate(1540, 100, amDynamite) SpawnSupplyCrate(2175, 1815, amLowGravity) SpawnSupplyCrate(2210, 1499, amFirePunch) girderCrate = SpawnSupplyCrate(2300, 1663, amGirder) SpawnSupplyCrate(610, 1394, amPickHammer) ------ BARREL LIST ------ SetHealth(AddGear(1148, 736, gtExplosives, 0, 0, 0, 0), 20) end function PlaceCourseMines() AddGear(1215, 1193, gtMine, 0, 0, 0, 0) AddGear(1259, 1199, gtMine, 0, 0, 0, 0) AddGear(1310, 1198, gtMine, 0, 0, 0, 0) AddGear(1346, 1196, gtMine, 0, 0, 0, 0) AddGear(1383, 1192, gtMine, 0, 0, 0, 0) AddGear(1436, 1196, gtMine, 0, 0, 0, 0) AddGear(1487, 1199, gtMine, 0, 0, 0, 0) AddGear(1651, 1209, gtMine, 0, 0, 0, 0) AddGear(1708, 1209, gtMine, 0, 0, 0, 0) AddGear(1759, 1190, gtMine, 0, 0, 0, 0) AddGear(1815, 1184, gtMine, 0, 0, 0, 0) end --////////////////////////////Event Functions//////////////////////// function CheckDensePit() if GetHealth(dense) ~= nil then return GetY(dense) < 1250 and StoppedGear(dense) else return false end end function DoDensePit() EndTurn(true) RestoreHedge(cyborg) AnimWait(cyborg, 1) AddFunction({func = AddAnim, args = {outPitAnim}}) AddFunction({func = AddFunction, args = {{func = AfterOutPitAnim, args = {}}}}) end function CheckPastFlower() if denseDead == true or leaksDead == true then return false end return (GetX(dense) < startEventXDuo and StoppedGear(dense)) or (GetX(leaks) < startEventXDuo and StoppedGear(leaks)) end function DoPastFlower() EndTurn(true) RestoreHedge(cyborg) AnimWait(cyborg, 1) AddFunction({func = AddAnim, args = {pastFlowerAnim}}) AddFunction({func = AddFunction, args = {{func = AfterPastFlowerAnim, args = {}}}}) end function CheckLeaksDead() return leaksDead end function DoLeaksDead() if not princessDead then EndTurn(true) AddCaption(loc("The village, unprepared, was destroyed by the cyborgs...")) DismissTeam(nativesTeamName) DismissTeam(princessTeamName) end end function CheckDenseDead() return denseDead end function DoDenseDead() if not princessDead then EndTurn(true) AddCaption(loc("The village, unprepared, was destroyed by the cyborgs...")) DismissTeam(nativesTeamName) DismissTeam(princessTeamName) end end function CheckTookBlowTorch() return blowTaken end function DoTookBlowTorch() ShowMission(loc("The Journey Back"), loc("The Tunnel Maker"), loc("Get past the flower.").."|".. loc("Hint: Select the blow torch, aim and press [Fire]. Press [Fire] again to stop.").."|".. loc("Don't blow up the crate."), 2, 6000) end function CheckTookLowGravity() return gravityTaken end function DoTookLowGravity() ShowMission(loc("The Journey Back"), loc("The Moonwalk"), loc("Hop on top of the next flower and advance to the left coast.").."|".. loc("Hint: Select the low gravity and press [Fire].") .. "|" .. loc("Beware of mines: They explode after 3 seconds."), 2, 6000) end function CheckOnBridge() return leaksDead == false and GetX(leaks) < 1651 and StoppedGear(leaks) end function DoOnBridge() EndTurn(true) RestoreHedge(cyborg) RestoreHedge(princess) AnimWait(cyborg, 1) AddFunction({func = AddAnim, args = {midAnim}}) AddFunction({func = AddFunction, args = {{func = AfterMidAnimAlone, args = {}}}}) end function CheckOnFirstGirder() return leaksDead == false and GetX(leaks) < 1160 and StoppedGear(leaks) end function DoOnFirstGirder() PlaceCourseMines() ShowMission(loc("The Journey Back"), loc("Slippery"), loc("Collect the weapon crate at the left coast!") .. "|" .. loc("You'd better watch your steps...") .. "|" .. loc("Mines time: 3 seconds"), 7, 4000) end function CheckTookSniper() return sniperTaken and StoppedGear(leaks) end function DoTookSniper() EndTurn(true) RestoreHedge(cyborg) RestoreHedge(princess) AnimWait(cyborg, 1) AddFunction({func = AddAnim, args = {endAnim}}) AddFunction({func = AddFunction, args = {{func = AfterEndAnimAlone, args = {}}}}) end function CheckTookSniper2() return sniperTaken and leaksDead == false and StoppedGear(leaks) and denseDead == false and StoppedGear(dense) end function DoTookSniper2() EndTurn(true) RestoreHedge(cyborg) RestoreHedge(princess) AnimWait(cyborg, 1) AddFunction({func = AddAnim, args = {endAnim}}) AddFunction({func = AddFunction, args = {{func = AfterEndAnimDuo, args = {}}}}) end function CheckLost() return princessDead end function DoLost() if not cyborgDead then SwitchHog(cyborg) end if (not (leaksDead or denseDead)) and (TurnsLeft > 0) then AddAnim(endFailAnim) end AddFunction({func = DismissTeam, args = {nativesTeamName}}) AddFunction({func = DismissTeam, args = {princessTeamName}}) AddFunction({func = EndTurn, args = {true}}) end function CheckWon() return cyborgDead and not princessDead end function DoWon() victory = true if progress and progress<3 then SaveCampaignVar("Progress", "3") end AddAnim(winAnim) AddFunction({func = FinishWon, args = {}}) end function FinishWon() SwitchHog(leaks) DismissTeam(cannibalsTeamName) DismissTeam(cyborgTeamName) EndTurn(true) end function CheckFailedCourse() return TurnsLeft == 0 end function DoFailedCourse() EndTurn(true) RestoreHedge(cyborg) RestoreHedge(princess) AnimWait(cyborg, 1) AddFunction({func = AddAnim, args = {failAnim}}) AddFunction({func = AddFunction, args = {{func = AfterMidFailAnim, args = {}}}}) AddEvent(CheckLost, {}, DoLost, {}) end function SkipFailAnimAlone() DumpMines(1) KillPrincess() AnimSwitchHog(princess) end --////////////////////////////Main Functions///////////////////////// function onGameInit() progress = tonumber(GetCampaignVar("Progress")) m2Choice = tonumber(GetCampaignVar("M2Choice")) or choiceRefused m2DenseDead = tonumber(GetCampaignVar("M2DenseDead")) or 0 Seed = 0 GameFlags = gfSolidLand + gfDisableWind TurnTime = 40000 CaseFreq = 0 MinesNum = 0 if m2DenseDead == 1 then MinesTime = 3000 else MinesTime = 5000 end Explosives = 0 Map = "A_Classic_Fairytale_journey" Theme = "Nature" -- Disable Sudden Death HealthDecrease = 0 WaterRise = 0 AnimInit(true) nativesTeamName = AddMissionTeam(-2) leaks = AddHog(loc("Leaks A Lot"), 0, 100, "Rambo") dense = AddHog(loc("Dense Cloud"), 0, 100, "RobinHood") princessTeamName = AddTeam(loc("Princess"), -2, "Bone", "Island", "HillBilly_qau", "cm_female") SetTeamPassive(princessTeamName, true) princess = AddHog(loc("Fell From Heaven"), 0, 200, "tiara") cannibalsTeamName = AddTeam(loc("Cannibal Sentry"), -1, "skull", "Island", "Pirate_qau", "cm_vampire") cannibals = {} for i = 1, 4 do cannibals[i] = AddHog(cannibalNames[i], 3, 40, "Zombi") AnimSetGearPosition(cannibals[i], unpack(cannibalPos[i])) SetEffect(cannibals[i], heArtillery, 1) end for i = 5, 8 do cannibals[i] = AddHog(cannibalNames[i], 3, 40, "Zombi") AnimSetGearPosition(cannibals[i], 0, 0) SetEffect(cannibals[i], heArtillery, 1) end cyborgTeamName = AddTeam(loc("011101001"), -1, "ring", "UFO", "Robot_qau", "cm_binary") cyborg = AddHog(loc("Y3K1337"), 0, 200, "cyborg1") AnimSetGearPosition(dense, 0, 0) AnimSetGearPosition(leaks, 0, 0) AnimSetGearPosition(cyborg, 0, 0) AnimSetGearPosition(princess, 0, 0) end function onGameStart() StartMission() end function onGameTick() AnimUnWait() if ShowAnimation() == false then return end ExecuteAfterAnimations() CheckEvents() end -- Track gears for princess cage cleanup function onGearAdd(gear) local gt = GetGearType(gear) if gt == gtCase or gt == gtMine then trackedGears[gear] = true end end function onGearDelete(gear) if trackedGears[gear] then trackedGears[gear] = nil end if gear == blowCrate then blowTaken = true elseif gear == gravityCrate then gravityTaken = true elseif gear == leaks and not victory then leaksDead = true elseif gear == dense and not victory then denseDead = true elseif gear == cyborg then cyborgDead = true elseif gear == princess and not victory then princessDead = true elseif gear == sniperCrate then sniperTaken = true else for i = 1, 4 do if gear == cannibals[i] then cannibalDead[i] = true end end end end function onAmmoStoreInit() SetAmmo(amBlowTorch, 0, 0, 0, 1) SetAmmo(amParachute, 0, 0, 0, 1) SetAmmo(amGirder, 0, 0, 0, 3) SetAmmo(amLowGravity, 0, 0, 0, 1) SetAmmo(amBaseballBat, 0, 0, 0, 1) SetAmmo(amFirePunch, 1, 0, 0, 1) SetAmmo(amSkip, 9, 0, 0, 0) SetAmmo(amSwitch, 9, 0, 0, 0) SetAmmo(amDEagle, 9, 0, 0, 0) SetAmmo(amRope, 0, 0, 0, 1) SetAmmo(amSniperRifle, 0, 0, 0, 1) SetAmmo(amDynamite, 0, 0, 0, 1) SetAmmo(amPickHammer, 0, 0, 0, 1) end function onNewTurn() if not startAnimStarted then AddAnim(startAnim) AddFunction({func = AfterStartAnim, args = {}}) startAnimStarted = true end if AnimInProgress() then SetTurnTimeLeft(MAX_TURN_TIME) elseif victory then EndTurn(true) elseif stage == endStage then if GetHogTeamName(CurrentHedgehog) == nativesTeamName and CurrentHedgehog ~= leaks then AnimSwitchHog(leaks) SetTurnTimeLeft(MAX_TURN_TIME) else SkipTurn() end elseif GetHogTeamName(CurrentHedgehog) ~= nativesTeamName then SetTurnTimeLeft(20000) else TurnsLeft = TurnsLeft - 1 if TurnsLeft >= 1 then AddCaption(string.format(loc("Turns left: %d"), TurnsLeft), capcolDefault, capgrpGameState) end end end function onPrecise() if GameTime > 2500 and AnimInProgress() then SetAnimSkip(true) return end end function onGameResult(winner) if winner == GetTeamClan(nativesTeamName) then SendStat(siGameResult, loc("Mission succeeded!")) else SendStat(siGameResult, loc("Mission failed!")) end end
0
0.817066
1
0.817066
game-dev
MEDIA
0.9523
game-dev
0.988395
1
0.988395
SinlessDevil/ZumaClone
6,637
Assets/ThirdParty/NiceVibrations/Demos/DemoAssets/WobbleDemo/Scripts/WobbleButton.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; namespace MoreMountains.NiceVibrations { public class WobbleButton : MonoBehaviour, IPointerExitHandler, IPointerEnterHandler { public RenderMode ParentCanvasRenderMode { get; protected set; } [Header("Bindings")] public Camera TargetCamera; public AudioSource SpringAudioSource; public Animator TargetAnimator; [Header("Haptics")] public TextAsset AHAPFile; [Header("Colors")] public Image TargetModel; [Header("Wobble")] public float OffDuration = 0.1f; public float MaxRange; public AnimationCurve WobbleCurve; public float DragResetDuration = 4f; public float WobbleFactor = 2f; protected Vector3 _neutralPosition; protected Canvas _canvas; protected Vector3 _newTargetPosition; protected Vector3 _eventPosition; protected Vector2 _workPosition; protected float _initialZPosition; protected bool _dragging; protected int _pointerID; protected PointerEventData _pointerEventData; protected RectTransform _rectTransform; protected Vector3 _dragEndedPosition; protected float _dragEndedAt; protected Vector3 _dragResetDirection; protected bool _pointerOn = false; protected bool _draggedOnce = false; protected int _sparkAnimationParameter; protected long[] _wobbleAndroidPattern = { 0, 40, 40, 80 }; protected int[] _wobbleAndroidAmplitude = { 0, 40, 0, 80 }; protected virtual void Start() { //Initialization(); } public virtual void SetPitch(float newPitch) { SpringAudioSource.pitch = newPitch; } public virtual void Initialization() { _sparkAnimationParameter = Animator.StringToHash("Spark"); ParentCanvasRenderMode = GetComponentInParent<Canvas>().renderMode; _canvas = GetComponentInParent<Canvas>(); _initialZPosition = transform.position.z; _rectTransform = this.gameObject.GetComponent<RectTransform>(); SetNeutralPosition(); } public virtual void SetNeutralPosition() { _neutralPosition = _rectTransform.transform.position; } protected virtual Vector3 GetWorldPosition(Vector3 testPosition) { if (ParentCanvasRenderMode == RenderMode.ScreenSpaceCamera) { RectTransformUtility.ScreenPointToLocalPointInRectangle(_canvas.transform as RectTransform, testPosition, _canvas.worldCamera, out _workPosition); return _canvas.transform.TransformPoint(_workPosition); } else { return testPosition; } } protected virtual void Update() { if (_pointerOn && !_dragging) { _newTargetPosition = GetWorldPosition(_pointerEventData.position); float distance = (_newTargetPosition - _neutralPosition).magnitude; if (distance < MaxRange) { _dragging = true; } else { _dragging = false; } } if (_dragging) { StickToPointer(); } else { GoBackToInitialPosition(); } } protected virtual void StickToPointer() { _draggedOnce = true; _eventPosition = _pointerEventData.position; _newTargetPosition = GetWorldPosition(_eventPosition); // We clamp the stick's position to let it move only inside its defined max range _newTargetPosition = Vector2.ClampMagnitude(_newTargetPosition - _neutralPosition, MaxRange); _newTargetPosition = _neutralPosition + _newTargetPosition; _newTargetPosition.z = _initialZPosition; transform.position = _newTargetPosition; } protected virtual void GoBackToInitialPosition() { if (!_draggedOnce) { return; } if (Time.time - _dragEndedAt < DragResetDuration) { float time = Remap(Time.time - _dragEndedAt, 0f, DragResetDuration, 0f, 1f); float value = WobbleCurve.Evaluate(time) * WobbleFactor; _newTargetPosition = Vector3.LerpUnclamped(_neutralPosition, _dragEndedPosition, value); _newTargetPosition.z = _initialZPosition; } else { _newTargetPosition = _neutralPosition; _newTargetPosition.z = _initialZPosition; } transform.position = _newTargetPosition; } public virtual void OnPointerEnter(PointerEventData data) { _pointerID = data.pointerId; _pointerEventData = data; _pointerOn = true; } public virtual void OnPointerExit(PointerEventData data) { _eventPosition = _pointerEventData.position; _newTargetPosition = GetWorldPosition(_eventPosition); _newTargetPosition = Vector2.ClampMagnitude(_newTargetPosition - _neutralPosition, MaxRange); _newTargetPosition = _neutralPosition + _newTargetPosition; _newTargetPosition.z = _initialZPosition; _dragging = false; _dragEndedPosition = _newTargetPosition; _dragEndedAt = Time.time; _dragResetDirection = _dragEndedPosition - _neutralPosition; _pointerOn = false; TargetAnimator.SetTrigger(_sparkAnimationParameter); SpringAudioSource.Play(); MMVibrationManager.AdvancedHapticPattern(AHAPFile.text, _wobbleAndroidPattern, _wobbleAndroidAmplitude, -1, _wobbleAndroidPattern, _wobbleAndroidAmplitude, _wobbleAndroidAmplitude, -1, HapticTypes.LightImpact, this); } protected virtual float Remap(float x, float A, float B, float C, float D) { float remappedValue = C + (x - A) / (B - A) * (D - C); return remappedValue; } } }
0
0.827307
1
0.827307
game-dev
MEDIA
0.847583
game-dev
0.975338
1
0.975338
Refactorio/RedMew
3,484
map_gen/maps/crash_site/outpost_data/big_science_factory.lua
local ob = require 'map_gen.maps.crash_site.outpost_builder' local Token = require 'utils.token' local loot = { {weight = 10}, {stack = {name = 'coin', count = 250, distance_factor = 1 / 20}, weight = 5}, {stack = {name = 'automation-science-pack', count = 200, distance_factor = 1 / 10}, weight = 2}, {stack = {name = 'logistic-science-pack', count = 100, distance_factor = 1 / 10}, weight = 2}, {stack = {name = 'military-science-pack', count = 75, distance_factor = 1 / 10}, weight = 3}, {stack = {name = 'chemical-science-pack', count = 75, distance_factor = 1 / 10}, weight = 3}, {stack = {name = 'production-science-pack', count = 50, distance_factor = 1 / 10}, weight = 5}, {stack = {name = 'utility-science-pack', count = 50, distance_factor = 1 / 10}, weight = 5} } local weights = ob.prepare_weighted_loot(loot) local loot_callback = Token.register( function(chest) ob.do_random_loot(chest, weights, loot) end ) local factory = { callback = ob.magic_item_crafting_callback, data = { recipe = 'production-science-pack', output = {min_rate = 0.0625 / 60, distance_factor = 0.0625 / 60 / 512, item = 'production-science-pack'} } } local factory_b = { callback = ob.magic_item_crafting_callback, data = { recipe = 'utility-science-pack', output = {min_rate = 0.0625 / 60, distance_factor = 0.0625 / 60 / 512, item = 'utility-science-pack'} } } local market = { callback = ob.market_set_items_callback, data = { market_name = 'Big Science Factory', upgrade_rate = 0.5, upgrade_base_cost = 500, upgrade_cost_base = 2, { name = 'automation-science-pack', price = 10, distance_factor = 5 / 512, min_price = 1 }, { name = 'logistic-science-pack', price = 20, distance_factor = 10 / 512, min_price = 2 }, { name = 'military-science-pack', price = 40, distance_factor = 20 / 512, min_price = 4 }, { name = 'chemical-science-pack', price = 60, distance_factor = 30 / 512, min_price = 4 }, { name = 'production-science-pack', price = 120, distance_factor = 60 / 512, min_price = 4 }, { name = 'utility-science-pack', price = 180, distance_factor = 90 / 512, min_price = 4 } } } local base_factory = require 'map_gen.maps.crash_site.outpost_data.big_factory' local level2 = ob.extend_1_way(base_factory[1], {loot = {callback = loot_callback}}) local level3 = ob.extend_1_way( base_factory[2], { factory = factory, fallback = level2, max_count = 3 } ) local level3b = ob.extend_1_way( base_factory[2], { factory = factory_b, fallback = level2, max_count = 3 } ) local level4 = ob.extend_1_way( base_factory[3], { market = market, fallback = level3b } ) return { settings = { blocks = 9, variance = 3, min_step = 2, max_level = 3 }, walls = { require 'map_gen.maps.crash_site.outpost_data.heavy_laser_turrets' }, bases = { {level3, level2}, {level4} } }
0
0.822466
1
0.822466
game-dev
MEDIA
0.959614
game-dev
0.870991
1
0.870991
emacs-ng/emacs-ng
3,221
test/lisp/cedet/semantic-utest-ia-resources/testsubclass.hh
// testsubclass.hh --- unit test for analyzer and complex C++ inheritance // Copyright (C) 2007-2025 Free Software Foundation, Inc. // Author: Eric M. Ludlam <zappo@gnu.org> // This file is part of GNU Emacs. // GNU Emacs is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // GNU Emacs is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>. //#include <cmath> // #include <stdio.h> #ifndef TESTSUBCLASS_HH #define TESTSUBCLASS_HH namespace animal { class moose { public: moose() : fFeet(0), fIsValid(false) { } virtual void setFeet(int); int getFeet(); void doNothing(); enum moose_enum { NAME1, NAME2, NAME3 }; protected: bool fIsValid; int fIsProtectedInt; private: int fFeet; // Usually 2 or 4. bool fIsPrivateBool; }; // moose int two_prototypes(); int two_prototypes(); class quadruped { public: quadruped(int a) : fQuadPrivate(a) { } int fQuadPublic; protected: int fQuadProtected; private: int fQuadPrivate; }; } namespace deer { class moose : public animal::moose { public: moose() : fAntlers(false) { } void setAntlers(bool); bool getAntlers(); void doSomething(); protected: bool fSomeField; private: bool fAntlers; }; } // deer // A second namespace of the same name will test the // namespace merging needed to resolve deer::alces namespace deer { class alces : public animal::moose { public: alces(int lat) : fLatin(lat) { } void setLatin(bool); bool getLatin(); void doLatinStuff(moose moosein); // for completion testing moose createMoose(); // for completion testing. protected: bool fAlcesBool; int fAlcesInt; private: bool fLatin; int fGreek; }; }; // A third namespace with classes that does protected and private inheritance. namespace sneaky { class antelope : public animal::quadruped { public: antelope(int a) : animal::quadruped(), fAntyProtected(a) {} int fAntyPublic; bool testAccess(); protected: int fAntyProtected; private : int fAntyPrivate; }; class jackalope : protected animal::quadruped { public: jackalope(int a) : animal::quadruped(), fBunny(a) {} int fBunnyPublic; bool testAccess(); protected: bool fBunnyProtected; private : bool fBunnyPrivate; }; // Nothing specified means private. class bugalope : /* private*/ animal::quadruped { public: bugalope(int a) : animal::quadruped(), fBug(a) {} int fBugPublic; bool testAccess(); protected: bool fBugProtected; private : bool fBugPrivate; }; }; #endif
0
0.85695
1
0.85695
game-dev
MEDIA
0.619423
game-dev
0.658886
1
0.658886
fredakilla/GPlayEngine
5,102
thirdparty/bullet/src/Bullet3Geometry/b3GeometryUtil.cpp
/* Copyright (c) 2003-2006 Gino van den Bergen / Erwin Coumans http://continuousphysics.com/Bullet/ This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "b3GeometryUtil.h" /* Make sure this dummy function never changes so that it can be used by probes that are checking whether the library is actually installed. */ extern "C" { void b3BulletMathProbe (); void b3BulletMathProbe () {} } bool b3GeometryUtil::isPointInsidePlanes(const b3AlignedObjectArray<b3Vector3>& planeEquations, const b3Vector3& point, b3Scalar margin) { int numbrushes = planeEquations.size(); for (int i=0;i<numbrushes;i++) { const b3Vector3& N1 = planeEquations[i]; b3Scalar dist = b3Scalar(N1.dot(point))+b3Scalar(N1[3])-margin; if (dist>b3Scalar(0.)) { return false; } } return true; } bool b3GeometryUtil::areVerticesBehindPlane(const b3Vector3& planeNormal, const b3AlignedObjectArray<b3Vector3>& vertices, b3Scalar margin) { int numvertices = vertices.size(); for (int i=0;i<numvertices;i++) { const b3Vector3& N1 = vertices[i]; b3Scalar dist = b3Scalar(planeNormal.dot(N1))+b3Scalar(planeNormal[3])-margin; if (dist>b3Scalar(0.)) { return false; } } return true; } bool notExist(const b3Vector3& planeEquation,const b3AlignedObjectArray<b3Vector3>& planeEquations); bool notExist(const b3Vector3& planeEquation,const b3AlignedObjectArray<b3Vector3>& planeEquations) { int numbrushes = planeEquations.size(); for (int i=0;i<numbrushes;i++) { const b3Vector3& N1 = planeEquations[i]; if (planeEquation.dot(N1) > b3Scalar(0.999)) { return false; } } return true; } void b3GeometryUtil::getPlaneEquationsFromVertices(b3AlignedObjectArray<b3Vector3>& vertices, b3AlignedObjectArray<b3Vector3>& planeEquationsOut ) { const int numvertices = vertices.size(); // brute force: for (int i=0;i<numvertices;i++) { const b3Vector3& N1 = vertices[i]; for (int j=i+1;j<numvertices;j++) { const b3Vector3& N2 = vertices[j]; for (int k=j+1;k<numvertices;k++) { const b3Vector3& N3 = vertices[k]; b3Vector3 planeEquation,edge0,edge1; edge0 = N2-N1; edge1 = N3-N1; b3Scalar normalSign = b3Scalar(1.); for (int ww=0;ww<2;ww++) { planeEquation = normalSign * edge0.cross(edge1); if (planeEquation.length2() > b3Scalar(0.0001)) { planeEquation.normalize(); if (notExist(planeEquation,planeEquationsOut)) { planeEquation[3] = -planeEquation.dot(N1); //check if inside, and replace supportingVertexOut if needed if (areVerticesBehindPlane(planeEquation,vertices,b3Scalar(0.01))) { planeEquationsOut.push_back(planeEquation); } } } normalSign = b3Scalar(-1.); } } } } } void b3GeometryUtil::getVerticesFromPlaneEquations(const b3AlignedObjectArray<b3Vector3>& planeEquations , b3AlignedObjectArray<b3Vector3>& verticesOut ) { const int numbrushes = planeEquations.size(); // brute force: for (int i=0;i<numbrushes;i++) { const b3Vector3& N1 = planeEquations[i]; for (int j=i+1;j<numbrushes;j++) { const b3Vector3& N2 = planeEquations[j]; for (int k=j+1;k<numbrushes;k++) { const b3Vector3& N3 = planeEquations[k]; b3Vector3 n2n3; n2n3 = N2.cross(N3); b3Vector3 n3n1; n3n1 = N3.cross(N1); b3Vector3 n1n2; n1n2 = N1.cross(N2); if ( ( n2n3.length2() > b3Scalar(0.0001) ) && ( n3n1.length2() > b3Scalar(0.0001) ) && ( n1n2.length2() > b3Scalar(0.0001) ) ) { //point P out of 3 plane equations: // d1 ( N2 * N3 ) + d2 ( N3 * N1 ) + d3 ( N1 * N2 ) //P = ------------------------------------------------------------------------- // N1 . ( N2 * N3 ) b3Scalar quotient = (N1.dot(n2n3)); if (b3Fabs(quotient) > b3Scalar(0.000001)) { quotient = b3Scalar(-1.) / quotient; n2n3 *= N1[3]; n3n1 *= N2[3]; n1n2 *= N3[3]; b3Vector3 potentialVertex = n2n3; potentialVertex += n3n1; potentialVertex += n1n2; potentialVertex *= quotient; //check if inside, and replace supportingVertexOut if needed if (isPointInsidePlanes(planeEquations,potentialVertex,b3Scalar(0.01))) { verticesOut.push_back(potentialVertex); } } } } } } }
0
0.798853
1
0.798853
game-dev
MEDIA
0.778178
game-dev,graphics-rendering
0.966817
1
0.966817
hakan-krgn/hCore
4,043
hCore-bukkit/nms/v1_16_R3/src/main/java/com/hakan/core/scoreboard/versions/Scoreboard_v1_16_R3.java
package com.hakan.core.scoreboard.versions; import com.hakan.core.HCore; import com.hakan.core.scoreboard.Scoreboard; import com.hakan.core.scoreboard.ScoreboardHandler; import com.hakan.core.utils.ColorUtil; import com.hakan.core.utils.ReflectionUtils; import net.minecraft.server.v1_16_R3.EnumChatFormat; import net.minecraft.server.v1_16_R3.IScoreboardCriteria; import net.minecraft.server.v1_16_R3.PacketPlayOutScoreboardDisplayObjective; import net.minecraft.server.v1_16_R3.PacketPlayOutScoreboardObjective; import net.minecraft.server.v1_16_R3.PacketPlayOutScoreboardScore; import net.minecraft.server.v1_16_R3.PacketPlayOutScoreboardTeam; import net.minecraft.server.v1_16_R3.ScoreboardServer; import org.bukkit.craftbukkit.v1_16_R3.util.CraftChatMessage; import org.bukkit.entity.Player; import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.Collections; /** * {@inheritDoc} */ public final class Scoreboard_v1_16_R3 extends Scoreboard { private int mode = 0; /** * {@inheritDoc} */ private Scoreboard_v1_16_R3(@Nonnull Player player, @Nonnull String title) { super(player, title); } /** * {@inheritDoc} */ @Nonnull @Override public Scoreboard show() { PacketPlayOutScoreboardObjective objective = new PacketPlayOutScoreboardObjective(); ReflectionUtils.setField(objective, "a", "board"); ReflectionUtils.setField(objective, "b", CraftChatMessage.fromStringOrNull(super.title)); ReflectionUtils.setField(objective, "c", IScoreboardCriteria.EnumScoreboardHealthDisplay.INTEGER); ReflectionUtils.setField(objective, "d", this.mode); PacketPlayOutScoreboardDisplayObjective displayObjective = new PacketPlayOutScoreboardDisplayObjective(); ReflectionUtils.setField(displayObjective, "a", 1); ReflectionUtils.setField(displayObjective, "b", "board"); HCore.sendPacket(super.player, objective, displayObjective); int length = super.lines.length; for (int i = 0; i < length; i++) { String line = super.getLine(i); if (line == null) continue; String color = (i >= 10) ? "§" + new String[]{"a", "b", "c", "d", "e", "f"}[i - 10] : "§" + i; PacketPlayOutScoreboardTeam team = new PacketPlayOutScoreboardTeam(); ReflectionUtils.setField(team, "a", "team_" + i); ReflectionUtils.setField(team, "b", CraftChatMessage.fromStringOrNull("team_" + i)); ReflectionUtils.setField(team, "c", CraftChatMessage.fromStringOrNull(ColorUtil.colored(line))); ReflectionUtils.setField(team, "d", CraftChatMessage.fromStringOrNull(" ")); ReflectionUtils.setField(team, "e", "always"); ReflectionUtils.setField(team, "f", "always"); ReflectionUtils.setField(team, "g", EnumChatFormat.RESET); ReflectionUtils.setField(team, "h", (this.mode == 0) ? Collections.singletonList(color) : new ArrayList<>()); ReflectionUtils.setField(team, "i", this.mode); ReflectionUtils.setField(team, "j", 1); PacketPlayOutScoreboardScore score = new PacketPlayOutScoreboardScore(); ReflectionUtils.setField(score, "a", color); ReflectionUtils.setField(score, "b", "board"); ReflectionUtils.setField(score, "c", 15 - i); ReflectionUtils.setField(score, "d", ScoreboardServer.Action.CHANGE); HCore.sendPacket(super.player, team, score); } this.mode = 2; return this; } /** * {@inheritDoc} */ @Nonnull @Override public Scoreboard delete() { PacketPlayOutScoreboardObjective objective = new PacketPlayOutScoreboardObjective(); ReflectionUtils.setField(objective, "a", "board"); ReflectionUtils.setField(objective, "d", 1); HCore.sendPacket(super.player, objective); ScoreboardHandler.getContent().remove(super.player.getUniqueId()); return this; } }
0
0.837582
1
0.837582
game-dev
MEDIA
0.800679
game-dev
0.86499
1
0.86499
eclipse-threadx/guix
159,361
test/example_internal/all_widgets_5_2_5/all_widgets_5_2_5_specifications.c
/*******************************************************************************/ /* This file is auto-generated by Azure RTOS GUIX Studio. Do not edit this */ /* file by hand. Modifications to this file should only be made by running */ /* the Azure RTOS GUIX Studio application and re-generating the application */ /* specification file(s). For more information please refer to the Azure RTOS */ /* GUIX Studio User Guide, or visit our web site at azure.com/rtos */ /* */ /* GUIX Studio Revision 6.2.0.1 */ /* Date (dd.mm.yyyy): 31.10.2022 Time (hh:mm): 14:07 */ /*******************************************************************************/ #define GUIX_STUDIO_GENERATED_FILE #include <stddef.h> #include "all_widgets_5_2_5_resources.h" #include "all_widgets_5_2_5_specifications.h" static GX_WIDGET *gx_studio_nested_widget_create(GX_BYTE *control, GX_CONST GX_STUDIO_WIDGET *definition, GX_WIDGET *parent); SPRITE_SCREEN_CONTROL_BLOCK sprite_screen; INDICATOR_SCREEN_CONTROL_BLOCK indicator_screen; TEXT_SCREEN_CONTROL_BLOCK text_screen; WINDOW_SCREEN_CONTROL_BLOCK window_screen; BUTTON_SCREEN_CONTROL_BLOCK button_screen; GX_DISPLAY Primary_control_block; GX_WINDOW_ROOT Primary_root_window; GX_CANVAS Primary_canvas_control_block; ULONG Primary_canvas_memory[307200]; extern GX_CONST GX_THEME *Primary_theme_table[]; extern GX_CONST GX_CHAR **Primary_language_table[]; GX_STUDIO_DISPLAY_INFO all_widgets_5_2_5_display_table[1] = { { "Primary", "Primary_canvas", Primary_theme_table, Primary_language_table, PRIMARY_LANGUAGE_TABLE_SIZE, PRIMARY_STRING_TABLE_SIZE, 640, /* x resolution */ 480, /* y resolution */ &Primary_control_block, &Primary_canvas_control_block, &Primary_root_window, Primary_canvas_memory, /* canvas memory area */ 1228800 /* canvas memory size in bytes */ } }; UINT gx_studio_button_create(GX_CONST GX_STUDIO_WIDGET *info, GX_WIDGET *control_block, GX_WIDGET *parent) { UINT status; GX_BUTTON *button = (GX_BUTTON *) control_block; status = gx_button_create(button, info->widget_name, parent, info->style, info->widget_id, &info->size); return status; } UINT gx_studio_text_button_create(GX_CONST GX_STUDIO_WIDGET *info, GX_WIDGET *control_block, GX_WIDGET *parent) { UINT status; GX_TEXT_BUTTON *button = (GX_TEXT_BUTTON *) control_block; GX_TEXT_BUTTON_PROPERTIES *props = (GX_TEXT_BUTTON_PROPERTIES *) info->properties; status = gx_text_button_create(button, info->widget_name, parent, props->string_id, info->style, info->widget_id, &info->size); if (status == GX_SUCCESS) { gx_text_button_font_set(button, props->font_id); gx_text_button_text_color_set(button, props->normal_text_color_id, props->selected_text_color_id); } return status; } UINT gx_studio_multi_line_text_button_create(GX_CONST GX_STUDIO_WIDGET *info, GX_WIDGET *control_block, GX_WIDGET *parent) { UINT status; GX_MULTI_LINE_TEXT_BUTTON *button = (GX_MULTI_LINE_TEXT_BUTTON *) control_block; GX_ML_TEXT_BUTTON_PROPERTIES *props = (GX_ML_TEXT_BUTTON_PROPERTIES *) info->properties; status = gx_multi_line_text_button_create(button, info->widget_name, parent, props->string_id, info->style, info->widget_id, &info->size); if (status == GX_SUCCESS) { gx_text_button_font_set((GX_TEXT_BUTTON *) button, props->font_id); gx_text_button_text_color_set((GX_TEXT_BUTTON *) button, props->normal_text_color_id, props->selected_text_color_id); } return status; } UINT gx_studio_checkbox_create(GX_CONST GX_STUDIO_WIDGET *info, GX_WIDGET *control_block, GX_WIDGET *parent) { UINT status; GX_CHECKBOX *button = (GX_CHECKBOX *) control_block; GX_TEXT_BUTTON *text_button = (GX_TEXT_BUTTON *) button; GX_CHECKBOX_PROPERTIES *props = (GX_CHECKBOX_PROPERTIES *) info->properties; status = gx_checkbox_create(button, info->widget_name, parent, props->string_id, info->style, info->widget_id, &info->size); if (status == GX_SUCCESS) { gx_text_button_font_set(text_button, props->font_id); gx_text_button_text_color_set(text_button, props->normal_text_color_id, props->selected_text_color_id); if (props->unchecked_pixelmap_id || props->checked_pixelmap_id || props->unchecked_disabled_pixelmap_id || props->checked_disabled_pixelmap_id) { gx_checkbox_pixelmap_set(button, props->unchecked_pixelmap_id, props->checked_pixelmap_id, props->unchecked_disabled_pixelmap_id, props->checked_disabled_pixelmap_id); } } return status; } UINT gx_studio_radio_button_create(GX_CONST GX_STUDIO_WIDGET *info, GX_WIDGET *control_block, GX_WIDGET *parent) { UINT status; GX_RADIO_BUTTON *button = (GX_RADIO_BUTTON *) control_block; GX_TEXT_BUTTON *text_button = (GX_TEXT_BUTTON *) button; GX_RADIO_BUTTON_PROPERTIES *props = (GX_RADIO_BUTTON_PROPERTIES *) info->properties; status = gx_radio_button_create(button, info->widget_name, parent, props->string_id, info->style, info->widget_id, &info->size); if (status == GX_SUCCESS) { gx_text_button_font_set(text_button, props->font_id); gx_text_button_text_color_set(text_button, props->normal_text_color_id, props->selected_text_color_id); if (props->off_pixelmap_id || props->on_pixelmap_id || props->off_disabled_pixelmap_id || props->on_disabled_pixelmap_id) { gx_radio_button_pixelmap_set(button, props->off_pixelmap_id, props->on_pixelmap_id, props->off_disabled_pixelmap_id, props->on_disabled_pixelmap_id); } } return status; } UINT gx_studio_icon_button_create(GX_CONST GX_STUDIO_WIDGET *info, GX_WIDGET *control_block, GX_WIDGET *parent) { UINT status; GX_ICON_BUTTON *button = (GX_ICON_BUTTON *) control_block; GX_ICON_BUTTON_PROPERTIES *props = (GX_ICON_BUTTON_PROPERTIES *) info->properties; status = gx_icon_button_create(button, info->widget_name, parent, props->pixelmap_id, info->style, info->widget_id, &info->size); return status; } UINT gx_studio_pixelmap_button_create(GX_CONST GX_STUDIO_WIDGET *info, GX_WIDGET *control_block, GX_WIDGET *parent) { UINT status; GX_PIXELMAP_BUTTON *button = (GX_PIXELMAP_BUTTON *) control_block; GX_PIXELMAP_BUTTON_PROPERTIES *props = (GX_PIXELMAP_BUTTON_PROPERTIES *) info->properties; status = gx_pixelmap_button_create(button, info->widget_name, parent, props->normal_pixelmap_id, props->selected_pixelmap_id, props->disabled_pixelmap_id, info->style, info->widget_id, &info->size); return status; } UINT gx_studio_icon_create(GX_CONST GX_STUDIO_WIDGET *info, GX_WIDGET *control_block, GX_WIDGET *parent) { UINT status; GX_ICON *icon = (GX_ICON *) control_block; GX_ICON_PROPERTIES *props = (GX_ICON_PROPERTIES *) info->properties; status = gx_icon_create(icon, info->widget_name, parent, props->normal_pixelmap_id, info->style, info->widget_id, info->size.gx_rectangle_left, info->size.gx_rectangle_top); if (props->selected_pixelmap_id) { gx_icon_pixelmap_set(icon, props->normal_pixelmap_id, props->selected_pixelmap_id); } else { gx_widget_resize((GX_WIDGET *)icon, (GX_RECTANGLE *)&info->size); } return status; } UINT gx_studio_slider_create(GX_CONST GX_STUDIO_WIDGET *info, GX_WIDGET *control_block, GX_WIDGET *parent) { UINT status; GX_SLIDER *slider = (GX_SLIDER *) control_block; GX_SLIDER_PROPERTIES *props = (GX_SLIDER_PROPERTIES *) info->properties; GX_SLIDER_INFO slider_info; slider_info.gx_slider_info_min_val = props->minval; slider_info.gx_slider_info_max_val = props->maxval; slider_info.gx_slider_info_current_val = props->current_val; slider_info.gx_slider_info_increment = props->increment; slider_info.gx_slider_info_min_travel = props->min_travel; slider_info.gx_slider_info_max_travel = props->max_travel; slider_info.gx_slider_info_needle_width = props->needle_width; slider_info.gx_slider_info_needle_height = props->needle_height; slider_info.gx_slider_info_needle_inset = props->needle_inset; slider_info.gx_slider_info_needle_hotspot_offset = props->needle_hotspot; status = gx_slider_create(slider, info->widget_name, parent, props->tickmark_count, &slider_info, info->style, info->widget_id, &info->size); return status; } UINT gx_studio_pixelmap_slider_create(GX_CONST GX_STUDIO_WIDGET *info, GX_WIDGET *control_block, GX_WIDGET *parent) { UINT status; GX_PIXELMAP_SLIDER *slider = (GX_PIXELMAP_SLIDER *) control_block; GX_PIXELMAP_SLIDER_PROPERTIES *props = (GX_PIXELMAP_SLIDER_PROPERTIES *) info->properties; GX_PIXELMAP_SLIDER_INFO pixelmap_info; GX_SLIDER_INFO slider_info; slider_info.gx_slider_info_min_val = props->min_val; slider_info.gx_slider_info_max_val = props->max_val; slider_info.gx_slider_info_current_val = props->current_val; slider_info.gx_slider_info_increment = props->increment; slider_info.gx_slider_info_min_travel = props->min_travel; slider_info.gx_slider_info_max_travel = props->max_travel; slider_info.gx_slider_info_needle_width = props->needle_width; slider_info.gx_slider_info_needle_height = props->needle_height; slider_info.gx_slider_info_needle_inset = props->needle_inset; slider_info.gx_slider_info_needle_hotspot_offset = props->needle_hotspot; pixelmap_info.gx_pixelmap_slider_info_lower_background_pixelmap = props->lower_pixelmap; pixelmap_info.gx_pixelmap_slider_info_upper_background_pixelmap = props->upper_pixelmap; pixelmap_info.gx_pixelmap_slider_info_needle_pixelmap = props->needle_pixelmap; status = gx_pixelmap_slider_create(slider, info->widget_name, parent, &slider_info, &pixelmap_info, info->style, info->widget_id, &info->size); return status; } UINT gx_studio_progress_bar_create(GX_CONST GX_STUDIO_WIDGET *info, GX_WIDGET *control_block, GX_WIDGET *parent) { UINT status; GX_PROGRESS_BAR *bar = (GX_PROGRESS_BAR *) control_block; GX_PROGRESS_BAR_INFO *bar_info = (GX_PROGRESS_BAR_INFO *) info->properties; status = gx_progress_bar_create(bar, info->widget_name, parent, bar_info, info->style, info->widget_id, &info->size); return status; } UINT gx_studio_sprite_create(GX_CONST GX_STUDIO_WIDGET *info, GX_WIDGET *control_block, GX_WIDGET *parent) { UINT status; GX_SPRITE *sprite = (GX_SPRITE *) control_block; GX_SPRITE_PROPERTIES *props = (GX_SPRITE_PROPERTIES *) info->properties; status = gx_sprite_create(sprite, info->widget_name, parent, props->frame_list, props->frame_count, info->style, info->widget_id, &info->size); return status; } UINT gx_studio_prompt_create(GX_CONST GX_STUDIO_WIDGET *info, GX_WIDGET *control_block, GX_WIDGET *parent) { UINT status; GX_PROMPT *prompt = (GX_PROMPT *) control_block; GX_PROMPT_PROPERTIES *props = (GX_PROMPT_PROPERTIES *) info->properties; status = gx_prompt_create(prompt, info->widget_name, parent, props->string_id, info->style, info->widget_id, &info->size); if (status == GX_SUCCESS) { gx_prompt_font_set(prompt, props->font_id); gx_prompt_text_color_set(prompt, props->normal_text_color_id, props->selected_text_color_id); } return status; } UINT gx_studio_pixelmap_prompt_create(GX_CONST GX_STUDIO_WIDGET *info, GX_WIDGET *control_block, GX_WIDGET *parent) { UINT status; GX_PIXELMAP_PROMPT *pix_prompt = (GX_PIXELMAP_PROMPT *) control_block; GX_PROMPT *prompt = (GX_PROMPT *) pix_prompt; GX_PIXELMAP_PROMPT_PROPERTIES *props = (GX_PIXELMAP_PROMPT_PROPERTIES *) info->properties; status = gx_pixelmap_prompt_create(pix_prompt, info->widget_name, parent, props->string_id, props->fill_map_id, info->style, info->widget_id, &info->size); if (status == GX_SUCCESS) { gx_pixelmap_prompt_pixelmap_set(pix_prompt, props->left_map_id, props->fill_map_id, props->right_map_id, props->selected_left_map_id, props->selected_fill_map_id, props->selected_right_map_id); gx_prompt_font_set(prompt, props->font_id); gx_prompt_text_color_set(prompt, props->normal_text_color_id, props->selected_text_color_id); } return status; } UINT gx_studio_window_create(GX_CONST GX_STUDIO_WIDGET *info, GX_WIDGET *control_block, GX_WIDGET *parent) { UINT status; GX_WINDOW *window = (GX_WINDOW *) control_block; GX_WINDOW_PROPERTIES *props = (GX_WINDOW_PROPERTIES *) info->properties; status = gx_window_create(window, info->widget_name, parent, info->style, info->widget_id, &info->size); if (status == GX_SUCCESS) { if (props->wallpaper_id) { gx_window_wallpaper_set(window, props->wallpaper_id, info->style & GX_STYLE_TILE_WALLPAPER); } } return status; } UINT gx_studio_vertical_list_create(GX_CONST GX_STUDIO_WIDGET *info, GX_WIDGET *control_block, GX_WIDGET *parent) { UINT status; GX_VERTICAL_LIST *list = (GX_VERTICAL_LIST *) control_block; GX_VERTICAL_LIST_PROPERTIES *props = (GX_VERTICAL_LIST_PROPERTIES *) info->properties; status = gx_vertical_list_create(list, info->widget_name, parent, props->total_rows, props->callback, info->style, info->widget_id, &info->size); if (status == GX_SUCCESS) { if (props->wallpaper_id) { gx_window_wallpaper_set((GX_WINDOW *) list, props->wallpaper_id, info->style & GX_STYLE_TILE_WALLPAPER); } } return status; } UINT gx_studio_horizontal_list_create(GX_CONST GX_STUDIO_WIDGET *info, GX_WIDGET *control_block, GX_WIDGET *parent) { UINT status; GX_HORIZONTAL_LIST *list = (GX_HORIZONTAL_LIST *) control_block; GX_HORIZONTAL_LIST_PROPERTIES *props = (GX_HORIZONTAL_LIST_PROPERTIES *) info->properties; status = gx_horizontal_list_create(list, info->widget_name, parent, props->total_rows, props->callback, info->style, info->widget_id, &info->size); if (status == GX_SUCCESS) { if (props->wallpaper_id) { gx_window_wallpaper_set((GX_WINDOW *) list, props->wallpaper_id, info->style & GX_STYLE_TILE_WALLPAPER); } } return status; } UINT gx_studio_drop_list_create(GX_CONST GX_STUDIO_WIDGET *info, GX_WIDGET *control_block, GX_WIDGET *parent) { UINT status; GX_DROP_LIST *list = (GX_DROP_LIST *) control_block; GX_DROP_LIST_PROPERTIES *props = (GX_DROP_LIST_PROPERTIES *) info->properties; status = gx_drop_list_create(list, info->widget_name, parent, props->total_rows, props->open_height, props->callback, info->style, info->widget_id, &info->size); if (status == GX_SUCCESS) { if (props->pixelmap_id) { gx_drop_list_pixelmap_set(list, props->pixelmap_id); } if (props->wallpaper_id) { gx_window_wallpaper_set((GX_WINDOW *)&list->gx_drop_list_popup.gx_popup_list_list, props->wallpaper_id, info->style & GX_STYLE_TILE_WALLPAPER); } } return status; } UINT gx_studio_text_input_create(GX_CONST GX_STUDIO_WIDGET *info, GX_WIDGET *control_block, GX_WIDGET *parent) { UINT status; GX_SINGLE_LINE_TEXT_INPUT *input = (GX_SINGLE_LINE_TEXT_INPUT *) control_block; GX_PROMPT *prompt = (GX_PROMPT *) input; GX_SINGLE_LINE_TEXT_INPUT_PROPERTIES *props = (GX_SINGLE_LINE_TEXT_INPUT_PROPERTIES *) info->properties; status = gx_single_line_text_input_create(input, info->widget_name, parent, props->buffer, props->buffer_size, info->style, info->widget_id, &info->size); if (status == GX_SUCCESS) { gx_prompt_font_set(prompt, props->font_id); gx_prompt_text_color_set(prompt, props->normal_text_color_id, props->selected_text_color_id); } return status; } UINT gx_studio_multi_line_text_view_create(GX_CONST GX_STUDIO_WIDGET *info, GX_WIDGET *control_block, GX_WIDGET *parent) { UINT status; GX_MULTI_LINE_TEXT_VIEW *view = (GX_MULTI_LINE_TEXT_VIEW *) control_block; GX_ML_TEXT_VIEW_PROPERTIES *props = (GX_ML_TEXT_VIEW_PROPERTIES *) info->properties; status = gx_multi_line_text_view_create(view, info->widget_name, parent, props->string_id, info->style, info->widget_id, &info->size); if (status == GX_SUCCESS) { gx_multi_line_text_view_font_set(view, props->font_id); gx_multi_line_text_view_text_color_set(view, props->normal_text_color_id, props->selected_text_color_id); } return status; } UINT gx_studio_multi_line_text_input_create(GX_CONST GX_STUDIO_WIDGET *info, GX_WIDGET *control_block, GX_WIDGET *parent) { UINT status; GX_MULTI_LINE_TEXT_INPUT *input = (GX_MULTI_LINE_TEXT_INPUT *) control_block; GX_MULTI_LINE_TEXT_INPUT_PROPERTIES *props = (GX_MULTI_LINE_TEXT_INPUT_PROPERTIES *) info->properties; status = gx_multi_line_text_input_create(input, info->widget_name, parent, props->buffer, props->buffer_size, info->style, info->widget_id, &info->size); if (status == GX_SUCCESS) { gx_multi_line_text_view_font_set((GX_MULTI_LINE_TEXT_VIEW *) input, props->font_id); gx_multi_line_text_view_text_color_set((GX_MULTI_LINE_TEXT_VIEW *) input, props->normal_text_color_id, props->selected_text_color_id); } return status; } UINT gx_studio_horizontal_scrollbar_create(GX_CONST GX_STUDIO_WIDGET *info, GX_WIDGET *control_block, GX_WIDGET *parent) { UINT status; GX_SCROLLBAR *scroll = (GX_SCROLLBAR *) control_block; GX_SCROLLBAR_APPEARANCE *appearance = (GX_SCROLLBAR_APPEARANCE *) info->properties; status = gx_horizontal_scrollbar_create(scroll, info->widget_name, parent, appearance, info->style); return status; } UINT gx_studio_vertical_scrollbar_create(GX_CONST GX_STUDIO_WIDGET *info, GX_WIDGET *control_block, GX_WIDGET *parent) { UINT status; GX_SCROLLBAR *scroll = (GX_SCROLLBAR *) control_block; GX_SCROLLBAR_APPEARANCE *appearance = (GX_SCROLLBAR_APPEARANCE *) info->properties; status = gx_vertical_scrollbar_create(scroll, info->widget_name, parent, appearance, info->style); return status; } GX_WINDOW_PROPERTIES sprite_screen_properties = { 0 /* wallpaper pixelmap id */ }; GX_WINDOW_PROPERTIES sprite_screen_apple_window_properties = { GX_PIXELMAP_ID_RED_APPLE /* wallpaper pixelmap id */ }; GX_SLIDER_PROPERTIES sprite_screen_slider_2_properties = { 10, /* tickmark count */ 0, /* mimimun value */ 255, /* maximum value */ 255, /* current value */ 10, /* increment */ 10, /* minimum travel */ 10, /* maximum travel */ 5, /* needle width */ 20, /* needle height */ 4, /* needle inset */ 2 /* needle hotspot */ }; GX_TEXT_BUTTON_PROPERTIES sprite_screen_next_button_5_properties = { GX_STRING_ID_STRING_36, /* string id */ GX_FONT_ID_BUTTON, /* font id */ GX_COLOR_ID_WHITE, /* normal text color */ GX_COLOR_ID_WHITE /* selected text color */ }; GX_SPRITE_FRAME sprite_screen_sprite_frame_list[18] = { { GX_PIXELMAP_ID_FRAME_000, /* pixelmap id */ 0, /* x offset */ 0, /* y offset */ 5, /* frame delay */ GX_SPRITE_BACKGROUND_NO_ACTION, /* background operation */ 255 /* alpha value */ }, { GX_PIXELMAP_ID_FRAME_001, /* pixelmap id */ 0, /* x offset */ 0, /* y offset */ 5, /* frame delay */ GX_SPRITE_BACKGROUND_NO_ACTION, /* background operation */ 255 /* alpha value */ }, { GX_PIXELMAP_ID_FRAME_002, /* pixelmap id */ 0, /* x offset */ 0, /* y offset */ 5, /* frame delay */ GX_SPRITE_BACKGROUND_NO_ACTION, /* background operation */ 255 /* alpha value */ }, { GX_PIXELMAP_ID_FRAME_003, /* pixelmap id */ 0, /* x offset */ 0, /* y offset */ 5, /* frame delay */ GX_SPRITE_BACKGROUND_NO_ACTION, /* background operation */ 255 /* alpha value */ }, { GX_PIXELMAP_ID_FRAME_004, /* pixelmap id */ 0, /* x offset */ 0, /* y offset */ 2, /* frame delay */ GX_SPRITE_BACKGROUND_NO_ACTION, /* background operation */ 255 /* alpha value */ }, { GX_PIXELMAP_ID_FRAME_005, /* pixelmap id */ 0, /* x offset */ 0, /* y offset */ 5, /* frame delay */ GX_SPRITE_BACKGROUND_NO_ACTION, /* background operation */ 255 /* alpha value */ }, { GX_PIXELMAP_ID_FRAME_000, /* pixelmap id */ 0, /* x offset */ 0, /* y offset */ 5, /* frame delay */ GX_SPRITE_BACKGROUND_NO_ACTION, /* background operation */ 255 /* alpha value */ }, { GX_PIXELMAP_ID_FRAME_001, /* pixelmap id */ 0, /* x offset */ 0, /* y offset */ 5, /* frame delay */ GX_SPRITE_BACKGROUND_NO_ACTION, /* background operation */ 255 /* alpha value */ }, { GX_PIXELMAP_ID_FRAME_002, /* pixelmap id */ 0, /* x offset */ 0, /* y offset */ 5, /* frame delay */ GX_SPRITE_BACKGROUND_NO_ACTION, /* background operation */ 255 /* alpha value */ }, { GX_PIXELMAP_ID_FRAME_003, /* pixelmap id */ 0, /* x offset */ 0, /* y offset */ 5, /* frame delay */ GX_SPRITE_BACKGROUND_NO_ACTION, /* background operation */ 255 /* alpha value */ }, { GX_PIXELMAP_ID_FRAME_004, /* pixelmap id */ 0, /* x offset */ 0, /* y offset */ 5, /* frame delay */ GX_SPRITE_BACKGROUND_NO_ACTION, /* background operation */ 255 /* alpha value */ }, { GX_PIXELMAP_ID_FRAME_005, /* pixelmap id */ 0, /* x offset */ 0, /* y offset */ 5, /* frame delay */ GX_SPRITE_BACKGROUND_NO_ACTION, /* background operation */ 255 /* alpha value */ }, { GX_PIXELMAP_ID_FRAME_000, /* pixelmap id */ 0, /* x offset */ 0, /* y offset */ 5, /* frame delay */ GX_SPRITE_BACKGROUND_NO_ACTION, /* background operation */ 255 /* alpha value */ }, { GX_PIXELMAP_ID_FRAME_001, /* pixelmap id */ 0, /* x offset */ 0, /* y offset */ 5, /* frame delay */ GX_SPRITE_BACKGROUND_NO_ACTION, /* background operation */ 255 /* alpha value */ }, { GX_PIXELMAP_ID_FRAME_002, /* pixelmap id */ 0, /* x offset */ 0, /* y offset */ 5, /* frame delay */ GX_SPRITE_BACKGROUND_NO_ACTION, /* background operation */ 255 /* alpha value */ }, { GX_PIXELMAP_ID_FRAME_003, /* pixelmap id */ 0, /* x offset */ 0, /* y offset */ 5, /* frame delay */ GX_SPRITE_BACKGROUND_NO_ACTION, /* background operation */ 255 /* alpha value */ }, { GX_PIXELMAP_ID_FRAME_003, /* pixelmap id */ 0, /* x offset */ 0, /* y offset */ 5, /* frame delay */ GX_SPRITE_BACKGROUND_NO_ACTION, /* background operation */ 255 /* alpha value */ }, { GX_PIXELMAP_ID_FRAME_005, /* pixelmap id */ 0, /* x offset */ 0, /* y offset */ 5, /* frame delay */ GX_SPRITE_BACKGROUND_NO_ACTION, /* background operation */ 255 /* alpha value */ } }; GX_SPRITE_PROPERTIES sprite_screen_sprite_properties = { sprite_screen_sprite_frame_list, /* address of frame list */ 18, /* frame count */ }; GX_CONST GX_STUDIO_WIDGET sprite_screen_sprite_define = { "sprite", GX_TYPE_SPRITE, /* widget type */ ID_BIRD_SPRITE, /* widget id */ GX_STYLE_BORDER_NONE|GX_STYLE_TRANSPARENT|GX_STYLE_ENABLED|GX_STYLE_SPRITE_AUTO, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(GX_SPRITE), /* control block size */ GX_COLOR_ID_WIDGET_FILL, /* normal color id */ GX_COLOR_ID_SELECTED_FILL, /* selected color id */ gx_studio_sprite_create, /* create function */ GX_NULL, /* drawing function override */ GX_NULL, /* event function override */ {98, 76, 214, 176}, /* widget size */ GX_NULL, /* no next widget */ GX_NULL, /* no child widgets */ offsetof(SPRITE_SCREEN_CONTROL_BLOCK, sprite_screen_sprite), /* control block */ (void *) &sprite_screen_sprite_properties /* extended properties */ }; GX_CONST GX_STUDIO_WIDGET sprite_screen_next_button_5_define = { "next_button_5", GX_TYPE_TEXT_BUTTON, /* widget type */ IDB_NEXT, /* widget id */ GX_STYLE_BORDER_RAISED|GX_STYLE_ENABLED|GX_STYLE_TEXT_CENTER, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(GX_TEXT_BUTTON), /* control block size */ GX_COLOR_ID_NEXT_BUTTON_LOWER, /* normal color id */ GX_COLOR_ID_NEXT_BUTTON_UPPER, /* selected color id */ gx_studio_text_button_create, /* create function */ GX_NULL, /* drawing function override */ GX_NULL, /* event function override */ {501, 397, 580, 421}, /* widget size */ &sprite_screen_sprite_define, /* next widget definition */ GX_NULL, /* no child widgets */ offsetof(SPRITE_SCREEN_CONTROL_BLOCK, sprite_screen_next_button_5), /* control block */ (void *) &sprite_screen_next_button_5_properties /* extended properties */ }; GX_CONST GX_STUDIO_WIDGET sprite_screen_slider_2_define = { "slider_2", GX_TYPE_SLIDER, /* widget type */ ID_ALPHA_SLIDER, /* widget id */ GX_STYLE_BORDER_RAISED|GX_STYLE_ENABLED|GX_STYLE_SHOW_NEEDLE|GX_STYLE_SHOW_TICKMARKS, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(GX_SLIDER), /* control block size */ GX_COLOR_ID_BTN_UPPER, /* normal color id */ GX_COLOR_ID_BTN_UPPER, /* selected color id */ gx_studio_slider_create, /* create function */ GX_NULL, /* drawing function override */ GX_NULL, /* event function override */ {214, 353, 410, 390}, /* widget size */ &sprite_screen_next_button_5_define, /* next widget definition */ GX_NULL, /* no child widgets */ offsetof(SPRITE_SCREEN_CONTROL_BLOCK, sprite_screen_slider_2), /* control block */ (void *) &sprite_screen_slider_2_properties /* extended properties */ }; GX_CONST GX_STUDIO_WIDGET sprite_screen_apple_window_define = { "apple_window", GX_TYPE_WINDOW, /* widget type */ GX_ID_NONE, /* widget id */ GX_STYLE_BORDER_NONE|GX_STYLE_TRANSPARENT, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(GX_WINDOW), /* control block size */ GX_COLOR_ID_WHITE, /* normal color id */ GX_COLOR_ID_WHITE, /* selected color id */ gx_studio_window_create, /* create function */ (VOID (*)(GX_WIDGET *)) apple_window_draw, /* drawing function override */ GX_NULL, /* event function override */ {213, 80, 411, 348}, /* widget size */ &sprite_screen_slider_2_define, /* next widget definition */ GX_NULL, /* no child widgets */ offsetof(SPRITE_SCREEN_CONTROL_BLOCK, sprite_screen_apple_window), /* control block */ (void *) &sprite_screen_apple_window_properties /* extended properties */ }; GX_CONST GX_STUDIO_WIDGET sprite_screen_define = { "sprite_screen", GX_TYPE_WINDOW, /* widget type */ ID_SPRITE_SCREEN, /* widget id */ GX_STYLE_BORDER_THICK, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(SPRITE_SCREEN_CONTROL_BLOCK), /* control block size */ GX_COLOR_ID_WHITE, /* normal color id */ GX_COLOR_ID_WHITE, /* selected color id */ gx_studio_window_create, /* create function */ GX_NULL, /* drawing function override */ (UINT (*)(GX_WIDGET *, GX_EVENT *)) sprite_event_handler, /* event function override */ {41, 31, 597, 441}, /* widget size */ GX_NULL, /* next widget */ &sprite_screen_apple_window_define, /* child widget */ 0, /* control block */ (void *) &sprite_screen_properties /* extended properties */ }; GX_WINDOW_PROPERTIES indicator_screen_properties = { 0 /* wallpaper pixelmap id */ }; GX_SLIDER_PROPERTIES indicator_screen_slider_properties = { 9, /* tickmark count */ 0, /* mimimun value */ 100, /* maximum value */ 50, /* current value */ 10, /* increment */ 10, /* minimum travel */ 10, /* maximum travel */ 5, /* needle width */ 20, /* needle height */ 5, /* needle inset */ 2 /* needle hotspot */ }; GX_SLIDER_PROPERTIES indicator_screen_slider_1_properties = { 9, /* tickmark count */ 0, /* mimimun value */ 100, /* maximum value */ 50, /* current value */ 10, /* increment */ 10, /* minimum travel */ 10, /* maximum travel */ 20, /* needle width */ 5, /* needle height */ 5, /* needle inset */ 2 /* needle hotspot */ }; GX_PIXELMAP_SLIDER_PROPERTIES indicator_screen_pixelmap_slider_properties = { 0, /* minimum value */ 100, /* maximum value */ 50, /* current value */ 10, /* increment */ 10, /* minimum travel */ 10, /* maximum travel */ 20, /* needle width */ 5, /* needle height */ 0, /* needle inset */ 10, /* needle hotspot */ GX_PIXELMAP_ID_HORIZONTAL_FILL_BKGND, /* lower pixelmap id */ 0, /* upper pixelmap id */ GX_PIXELMAP_ID_I_INDICATOR_HORIZONTAL /* needle pixelmap id */ }; GX_PIXELMAP_SLIDER_PROPERTIES indicator_screen_pixelmap_slider_1_properties = { 0, /* minimum value */ 100, /* maximum value */ 50, /* current value */ 10, /* increment */ 10, /* minimum travel */ 10, /* maximum travel */ 0, /* needle width */ 0, /* needle height */ -2, /* needle inset */ 10, /* needle hotspot */ GX_PIXELMAP_ID_I_ORANGEFILL_MIDDLE, /* lower pixelmap id */ GX_PIXELMAP_ID_I_EMPTYFILL_MIDDLE, /* upper pixelmap id */ GX_PIXELMAP_ID_I_INDICATOR /* needle pixelmap id */ }; GX_ICON_PROPERTIES indicator_screen_icon_1_properties = { GX_PIXELMAP_ID_I_EMPTYFILL_TOP, /* normal pixelmap id */ 0 /* selected pixelmap id */ }; GX_ICON_PROPERTIES indicator_screen_icon_2_properties = { GX_PIXELMAP_ID_I_ORANGEFILL_BOTTOM, /* normal pixelmap id */ 0 /* selected pixelmap id */ }; GX_PROMPT_PROPERTIES indicator_screen_slider_title_properties = { GX_STRING_ID_STRING_38, /* string id */ GX_FONT_ID_PROMPT, /* font id */ GX_COLOR_ID_TEXT, /* normal text color */ GX_COLOR_ID_TEXT /* selected text color */ }; GX_TEXT_BUTTON_PROPERTIES indicator_screen_next_button_3_properties = { GX_STRING_ID_STRING_36, /* string id */ GX_FONT_ID_BUTTON, /* font id */ GX_COLOR_ID_WHITE, /* normal text color */ GX_COLOR_ID_WHITE /* selected text color */ }; GX_PROGRESS_BAR_INFO indicator_screen_progress_bar_1_properties = { 0, /* mimimun value */ 100, /* maximum value */ 50, /* current value */ GX_FONT_ID_SYSTEM, /* font_id */ GX_COLOR_ID_SHINE, /* normal text color */ GX_COLOR_ID_SHINE, /* selected text color */ 0 /* fill pixelmap */ }; GX_PIXELMAP_SLIDER_PROPERTIES indicator_screen_pixelmap_slider_2_properties = { 0, /* minimum value */ 100, /* maximum value */ 80, /* current value */ 10, /* increment */ 10, /* minimum travel */ 10, /* maximum travel */ 0, /* needle width */ 20, /* needle height */ 4, /* needle inset */ 10, /* needle hotspot */ GX_PIXELMAP_ID_I_ORANGEFILL_MIDDLE_HORIZONTAL, /* lower pixelmap id */ GX_PIXELMAP_ID_I_EMPTYFILL_MIDDLE_HORIZONTAL, /* upper pixelmap id */ GX_PIXELMAP_ID_I_INDICATOR_HORIZONTAL /* needle pixelmap id */ }; GX_CONST GX_STUDIO_WIDGET indicator_screen_pixelmap_slider_2_define = { "pixelmap_slider_2", GX_TYPE_PIXELMAP_SLIDER, /* widget type */ ID_PIXELMAP_SLIDER1, /* widget id */ GX_STYLE_BORDER_RAISED|GX_STYLE_TRANSPARENT|GX_STYLE_ENABLED|GX_STYLE_TILE_BACKGROUND, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(GX_PIXELMAP_SLIDER), /* control block size */ GX_COLOR_ID_WIDGET_FILL, /* normal color id */ GX_COLOR_ID_WIDGET_FILL, /* selected color id */ gx_studio_pixelmap_slider_create, /* create function */ GX_NULL, /* drawing function override */ GX_NULL, /* event function override */ {171, 289, 331, 326}, /* widget size */ GX_NULL, /* no next widget */ GX_NULL, /* no child widgets */ offsetof(INDICATOR_SCREEN_CONTROL_BLOCK, indicator_screen_pixelmap_slider_2), /* control block */ (void *) &indicator_screen_pixelmap_slider_2_properties /* extended properties */ }; GX_CONST GX_STUDIO_WIDGET indicator_screen_progress_bar_1_define = { "progress_bar_1", GX_TYPE_PROGRESS_BAR, /* widget type */ GX_ID_NONE, /* widget id */ GX_STYLE_BORDER_RAISED|GX_STYLE_PROGRESS_PERCENT|GX_STYLE_PROGRESS_TEXT_DRAW, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(GX_PROGRESS_BAR), /* control block size */ GX_COLOR_ID_SHADOW, /* normal color id */ GX_COLOR_ID_SELECTED_FILL, /* selected color id */ gx_studio_progress_bar_create, /* create function */ GX_NULL, /* drawing function override */ GX_NULL, /* event function override */ {276, 225, 441, 263}, /* widget size */ &indicator_screen_pixelmap_slider_2_define, /* next widget definition */ GX_NULL, /* no child widgets */ offsetof(INDICATOR_SCREEN_CONTROL_BLOCK, indicator_screen_progress_bar_1), /* control block */ (void *) &indicator_screen_progress_bar_1_properties /* extended properties */ }; GX_CONST GX_STUDIO_WIDGET indicator_screen_next_button_3_define = { "next_button_3", GX_TYPE_TEXT_BUTTON, /* widget type */ IDB_NEXT, /* widget id */ GX_STYLE_BORDER_RAISED|GX_STYLE_ENABLED|GX_STYLE_TEXT_CENTER, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(GX_TEXT_BUTTON), /* control block size */ GX_COLOR_ID_NEXT_BUTTON_LOWER, /* normal color id */ GX_COLOR_ID_NEXT_BUTTON_UPPER, /* selected color id */ gx_studio_text_button_create, /* create function */ GX_NULL, /* drawing function override */ GX_NULL, /* event function override */ {375, 345, 454, 372}, /* widget size */ &indicator_screen_progress_bar_1_define, /* next widget definition */ GX_NULL, /* no child widgets */ offsetof(INDICATOR_SCREEN_CONTROL_BLOCK, indicator_screen_next_button_3), /* control block */ (void *) &indicator_screen_next_button_3_properties /* extended properties */ }; GX_CONST GX_STUDIO_WIDGET indicator_screen_slider_title_define = { "slider_title", GX_TYPE_PROMPT, /* widget type */ GX_ID_NONE, /* widget id */ GX_STYLE_BORDER_NONE|GX_STYLE_TRANSPARENT|GX_STYLE_ENABLED|GX_STYLE_TEXT_CENTER, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(GX_PROMPT), /* control block size */ GX_COLOR_ID_WIDGET_FILL, /* normal color id */ GX_COLOR_ID_SELECTED_FILL, /* selected color id */ gx_studio_prompt_create, /* create function */ GX_NULL, /* drawing function override */ GX_NULL, /* event function override */ {235, 68, 372, 91}, /* widget size */ &indicator_screen_next_button_3_define, /* next widget definition */ GX_NULL, /* no child widgets */ offsetof(INDICATOR_SCREEN_CONTROL_BLOCK, indicator_screen_slider_title), /* control block */ (void *) &indicator_screen_slider_title_properties /* extended properties */ }; GX_CONST GX_STUDIO_WIDGET indicator_screen_icon_2_define = { "icon_2", GX_TYPE_ICON, /* widget type */ GX_ID_NONE, /* widget id */ GX_STYLE_BORDER_NONE|GX_STYLE_ENABLED|GX_STYLE_HALIGN_LEFT|GX_STYLE_VALIGN_TOP, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(GX_ICON), /* control block size */ GX_COLOR_ID_WIDGET_FILL, /* normal color id */ GX_COLOR_ID_SELECTED_FILL, /* selected color id */ gx_studio_icon_create, /* create function */ GX_NULL, /* drawing function override */ GX_NULL, /* event function override */ {163, 262, 184, 271}, /* widget size */ &indicator_screen_slider_title_define, /* next widget definition */ GX_NULL, /* no child widgets */ offsetof(INDICATOR_SCREEN_CONTROL_BLOCK, indicator_screen_icon_2), /* control block */ (void *) &indicator_screen_icon_2_properties /* extended properties */ }; GX_CONST GX_STUDIO_WIDGET indicator_screen_icon_1_define = { "icon_1", GX_TYPE_ICON, /* widget type */ GX_ID_NONE, /* widget id */ GX_STYLE_BORDER_NONE|GX_STYLE_ENABLED|GX_STYLE_HALIGN_LEFT|GX_STYLE_VALIGN_TOP, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(GX_ICON), /* control block size */ GX_COLOR_ID_WIDGET_FILL, /* normal color id */ GX_COLOR_ID_SELECTED_FILL, /* selected color id */ gx_studio_icon_create, /* create function */ GX_NULL, /* drawing function override */ GX_NULL, /* event function override */ {163, 134, 184, 143}, /* widget size */ &indicator_screen_icon_2_define, /* next widget definition */ GX_NULL, /* no child widgets */ offsetof(INDICATOR_SCREEN_CONTROL_BLOCK, indicator_screen_icon_1), /* control block */ (void *) &indicator_screen_icon_1_properties /* extended properties */ }; GX_CONST GX_STUDIO_WIDGET indicator_screen_pixelmap_slider_1_define = { "pixelmap_slider_1", GX_TYPE_PIXELMAP_SLIDER, /* widget type */ ID_PIXELMAP_SLIDER1, /* widget id */ GX_STYLE_BORDER_RAISED|GX_STYLE_TRANSPARENT|GX_STYLE_ENABLED|GX_STYLE_SLIDER_VERTICAL|GX_STYLE_TILE_BACKGROUND, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(GX_PIXELMAP_SLIDER), /* control block size */ GX_COLOR_ID_WIDGET_FILL, /* normal color id */ GX_COLOR_ID_WIDGET_FILL, /* selected color id */ gx_studio_pixelmap_slider_create, /* create function */ GX_NULL, /* drawing function override */ GX_NULL, /* event function override */ {160, 144, 188, 264}, /* widget size */ &indicator_screen_icon_1_define, /* next widget definition */ GX_NULL, /* no child widgets */ offsetof(INDICATOR_SCREEN_CONTROL_BLOCK, indicator_screen_pixelmap_slider_1), /* control block */ (void *) &indicator_screen_pixelmap_slider_1_properties /* extended properties */ }; GX_CONST GX_STUDIO_WIDGET indicator_screen_pixelmap_slider_define = { "pixelmap_slider", GX_TYPE_PIXELMAP_SLIDER, /* widget type */ ID_PIXELMAP_SLIDER_H, /* widget id */ GX_STYLE_BORDER_RAISED|GX_STYLE_TRANSPARENT|GX_STYLE_ENABLED, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(GX_PIXELMAP_SLIDER), /* control block size */ GX_COLOR_ID_BTN_LOWER, /* normal color id */ GX_COLOR_ID_BTN_LOWER, /* selected color id */ gx_studio_pixelmap_slider_create, /* create function */ GX_NULL, /* drawing function override */ GX_NULL, /* event function override */ {283, 185, 426, 206}, /* widget size */ &indicator_screen_pixelmap_slider_1_define, /* next widget definition */ GX_NULL, /* no child widgets */ offsetof(INDICATOR_SCREEN_CONTROL_BLOCK, indicator_screen_pixelmap_slider), /* control block */ (void *) &indicator_screen_pixelmap_slider_properties /* extended properties */ }; GX_CONST GX_STUDIO_WIDGET indicator_screen_slider_1_define = { "slider_1", GX_TYPE_SLIDER, /* widget type */ ID_SLIDER_1, /* widget id */ GX_STYLE_BORDER_RECESSED|GX_STYLE_ENABLED|GX_STYLE_SHOW_NEEDLE|GX_STYLE_SHOW_TICKMARKS|GX_STYLE_SLIDER_VERTICAL, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(GX_SLIDER), /* control block size */ GX_COLOR_ID_BTN_UPPER, /* normal color id */ GX_COLOR_ID_BTN_UPPER, /* selected color id */ gx_studio_slider_create, /* create function */ GX_NULL, /* drawing function override */ GX_NULL, /* event function override */ {207, 133, 240, 272}, /* widget size */ &indicator_screen_pixelmap_slider_define, /* next widget definition */ GX_NULL, /* no child widgets */ offsetof(INDICATOR_SCREEN_CONTROL_BLOCK, indicator_screen_slider_1), /* control block */ (void *) &indicator_screen_slider_1_properties /* extended properties */ }; GX_CONST GX_STUDIO_WIDGET indicator_screen_slider_define = { "slider", GX_TYPE_SLIDER, /* widget type */ ID_SLIDER_HORIZONTAL, /* widget id */ GX_STYLE_BORDER_RAISED|GX_STYLE_ENABLED|GX_STYLE_SHOW_NEEDLE|GX_STYLE_SHOW_TICKMARKS, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(GX_SLIDER), /* control block size */ GX_COLOR_ID_ORANGE, /* normal color id */ GX_COLOR_ID_ORANGE, /* selected color id */ gx_studio_slider_create, /* create function */ GX_NULL, /* drawing function override */ GX_NULL, /* event function override */ {263, 130, 446, 166}, /* widget size */ &indicator_screen_slider_1_define, /* next widget definition */ GX_NULL, /* no child widgets */ offsetof(INDICATOR_SCREEN_CONTROL_BLOCK, indicator_screen_slider), /* control block */ (void *) &indicator_screen_slider_properties /* extended properties */ }; GX_CONST GX_STUDIO_WIDGET indicator_screen_define = { "indicator_screen", GX_TYPE_WINDOW, /* widget type */ ID_INDICATOR_SCREEN, /* widget id */ GX_STYLE_BORDER_THIN, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(INDICATOR_SCREEN_CONTROL_BLOCK), /* control block size */ GX_COLOR_ID_WINDOW_FILL, /* normal color id */ GX_COLOR_ID_WINDOW_FILL, /* selected color id */ gx_studio_window_create, /* create function */ GX_NULL, /* drawing function override */ (UINT (*)(GX_WIDGET *, GX_EVENT *)) next_button_handler, /* event function override */ {146, 53, 465, 386}, /* widget size */ GX_NULL, /* next widget */ &indicator_screen_slider_define, /* child widget */ 0, /* control block */ (void *) &indicator_screen_properties /* extended properties */ }; GX_WINDOW_PROPERTIES text_screen_properties = { 0 /* wallpaper pixelmap id */ }; GX_PROMPT_PROPERTIES text_screen_prompt_1_properties = { GX_STRING_ID_STRING_24, /* string id */ GX_FONT_ID_PROMPT, /* font id */ GX_COLOR_ID_TEXT, /* normal text color */ GX_COLOR_ID_SELECTED_TEXT /* selected text color */ }; GX_PROMPT_PROPERTIES text_screen_prompt_2_properties = { GX_STRING_ID_STRING_29, /* string id */ GX_FONT_ID_PROMPT, /* font id */ GX_COLOR_ID_WHITE, /* normal text color */ GX_COLOR_ID_WHITE /* selected text color */ }; GX_PROMPT_PROPERTIES text_screen_prompt_3_properties = { GX_STRING_ID_STRING_27, /* string id */ GX_FONT_ID_PROMPT, /* font id */ GX_COLOR_ID_TEXT, /* normal text color */ GX_COLOR_ID_SELECTED_TEXT /* selected text color */ }; GX_PIXELMAP_PROMPT_PROPERTIES text_screen_prompt_4_properties = { GX_STRING_ID_STRING_30, /* string id */ GX_FONT_ID_PROMPT, /* font id */ GX_COLOR_ID_TEXT, /* normal text color */ GX_COLOR_ID_SELECTED_TEXT, /* selected text color */ GX_PIXELMAP_ID_TFIELD_LEFT_SMALL, /* left pixelmap id */ GX_PIXELMAP_ID_TFIELD_FILL_SMALL, /* fill pixelmap id */ GX_PIXELMAP_ID_TFIELD_RIGHT_SMALL, /* right pixelmap id */ 0, /* selected left pixelmap id */ 0, /* selected fill pixelmap id */ 0 /* selected right pixelmap id */ }; GX_CHAR text_screen_text_input_1_buffer[100]; GX_SINGLE_LINE_TEXT_INPUT_PROPERTIES text_screen_text_input_1_properties = { GX_STRING_ID_STRING_34, /* string id */ GX_FONT_ID_TEXT_INPUT, /* font id */ GX_COLOR_ID_TEXT_INPUT_TEXT, /* normal text color */ GX_COLOR_ID_TEXT_INPUT_TEXT, /* selected text color */ text_screen_text_input_1_buffer, /* buffer */ 100, /* buffer size */ }; GX_ML_TEXT_VIEW_PROPERTIES text_screen_text_view_1_properties = { GX_STRING_ID_STRING_31, /* string id */ GX_FONT_ID_TEXT_INPUT, /* font id */ GX_COLOR_ID_TEXT_INPUT_TEXT, /* normal text color */ GX_COLOR_ID_TEXT_INPUT_TEXT /* selected text color */ }; GX_CHAR text_screen_text_input_2_buffer[100]; GX_MULTI_LINE_TEXT_INPUT_PROPERTIES text_screen_text_input_2_properties = { GX_STRING_ID_STRING_31, /* string id */ GX_FONT_ID_TEXT_INPUT, /* font id */ GX_COLOR_ID_TEXT_INPUT_TEXT, /* normal text color */ GX_COLOR_ID_TEXT_INPUT_TEXT, /* selected text color */ text_screen_text_input_2_buffer, /* buffer */ 100 /* buffer size */ }; GX_TEXT_BUTTON_PROPERTIES text_screen_next_button_2_properties = { GX_STRING_ID_STRING_36, /* string id */ GX_FONT_ID_BUTTON, /* font id */ GX_COLOR_ID_WHITE, /* normal text color */ GX_COLOR_ID_WHITE /* selected text color */ }; GX_CONST GX_STUDIO_WIDGET text_screen_next_button_2_define = { "next_button_2", GX_TYPE_TEXT_BUTTON, /* widget type */ IDB_NEXT, /* widget id */ GX_STYLE_BORDER_RAISED|GX_STYLE_ENABLED|GX_STYLE_TEXT_CENTER, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(GX_TEXT_BUTTON), /* control block size */ GX_COLOR_ID_NEXT_BUTTON_LOWER, /* normal color id */ GX_COLOR_ID_NEXT_BUTTON_UPPER, /* selected color id */ gx_studio_text_button_create, /* create function */ GX_NULL, /* drawing function override */ GX_NULL, /* event function override */ {496, 414, 575, 438}, /* widget size */ GX_NULL, /* no next widget */ GX_NULL, /* no child widgets */ offsetof(TEXT_SCREEN_CONTROL_BLOCK, text_screen_next_button_2), /* control block */ (void *) &text_screen_next_button_2_properties /* extended properties */ }; GX_CONST GX_STUDIO_WIDGET text_screen_text_input_2_define = { "text_input_2", GX_TYPE_MULTI_LINE_TEXT_INPUT, /* widget type */ GX_ID_NONE, /* widget id */ GX_STYLE_BORDER_THIN|GX_STYLE_ENABLED|GX_STYLE_TEXT_LEFT, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(GX_MULTI_LINE_TEXT_INPUT), /* control block size */ GX_COLOR_ID_TEXT_INPUT_FILL, /* normal color id */ GX_COLOR_ID_TEXT_INPUT_FILL, /* selected color id */ gx_studio_multi_line_text_input_create, /* create function */ GX_NULL, /* drawing function override */ GX_NULL, /* event function override */ {321, 242, 572, 394}, /* widget size */ &text_screen_next_button_2_define, /* next widget definition */ GX_NULL, /* no child widgets */ offsetof(TEXT_SCREEN_CONTROL_BLOCK, text_screen_text_input_2), /* control block */ (void *) &text_screen_text_input_2_properties /* extended properties */ }; GX_CONST GX_STUDIO_WIDGET text_screen_text_view_1_define = { "text_view_1", GX_TYPE_MULTI_LINE_TEXT_VIEW, /* widget type */ GX_ID_NONE, /* widget id */ GX_STYLE_BORDER_THIN|GX_STYLE_ENABLED|GX_STYLE_TEXT_LEFT, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(GX_MULTI_LINE_TEXT_VIEW), /* control block size */ GX_COLOR_ID_TEXT_INPUT_FILL, /* normal color id */ GX_COLOR_ID_TEXT_INPUT_FILL, /* selected color id */ gx_studio_multi_line_text_view_create, /* create function */ GX_NULL, /* drawing function override */ GX_NULL, /* event function override */ {56, 242, 306, 394}, /* widget size */ &text_screen_text_input_2_define, /* next widget definition */ GX_NULL, /* no child widgets */ offsetof(TEXT_SCREEN_CONTROL_BLOCK, text_screen_text_view_1), /* control block */ (void *) &text_screen_text_view_1_properties /* extended properties */ }; GX_CONST GX_STUDIO_WIDGET text_screen_text_input_1_define = { "text_input_1", GX_TYPE_SINGLE_LINE_TEXT_INPUT, /* widget type */ GX_ID_NONE, /* widget id */ GX_STYLE_BORDER_RECESSED|GX_STYLE_ENABLED|GX_STYLE_TEXT_LEFT, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(GX_SINGLE_LINE_TEXT_INPUT), /* control block size */ GX_COLOR_ID_TEXT_INPUT_FILL, /* normal color id */ GX_COLOR_ID_TEXT_INPUT_FILL, /* selected color id */ gx_studio_text_input_create, /* create function */ GX_NULL, /* drawing function override */ GX_NULL, /* event function override */ {56, 196, 363, 231}, /* widget size */ &text_screen_text_view_1_define, /* next widget definition */ GX_NULL, /* no child widgets */ offsetof(TEXT_SCREEN_CONTROL_BLOCK, text_screen_text_input_1), /* control block */ (void *) &text_screen_text_input_1_properties /* extended properties */ }; GX_CONST GX_STUDIO_WIDGET text_screen_prompt_4_define = { "prompt_4", GX_TYPE_PIXELMAP_PROMPT, /* widget type */ ID_PROMPT_4, /* widget id */ GX_STYLE_BORDER_NONE|GX_STYLE_TEXT_CENTER, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(GX_PIXELMAP_PROMPT), /* control block size */ GX_COLOR_ID_WIDGET_FILL, /* normal color id */ GX_COLOR_ID_SELECTED_FILL, /* selected color id */ gx_studio_pixelmap_prompt_create, /* create function */ GX_NULL, /* drawing function override */ GX_NULL, /* event function override */ {56, 151, 363, 186}, /* widget size */ &text_screen_text_input_1_define, /* next widget definition */ GX_NULL, /* no child widgets */ offsetof(TEXT_SCREEN_CONTROL_BLOCK, text_screen_prompt_4), /* control block */ (void *) &text_screen_prompt_4_properties /* extended properties */ }; GX_CONST GX_STUDIO_WIDGET text_screen_prompt_3_define = { "prompt_3", GX_TYPE_PROMPT, /* widget type */ ID_PROMPT_3, /* widget id */ GX_STYLE_BORDER_NONE|GX_STYLE_TRANSPARENT|GX_STYLE_TEXT_CENTER, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(GX_PROMPT), /* control block size */ GX_COLOR_ID_WIDGET_FILL, /* normal color id */ GX_COLOR_ID_SELECTED_FILL, /* selected color id */ gx_studio_prompt_create, /* create function */ GX_NULL, /* drawing function override */ GX_NULL, /* event function override */ {56, 64, 363, 88}, /* widget size */ &text_screen_prompt_4_define, /* next widget definition */ GX_NULL, /* no child widgets */ offsetof(TEXT_SCREEN_CONTROL_BLOCK, text_screen_prompt_3), /* control block */ (void *) &text_screen_prompt_3_properties /* extended properties */ }; GX_CONST GX_STUDIO_WIDGET text_screen_prompt_2_define = { "prompt_2", GX_TYPE_PROMPT, /* widget type */ ID_PROMPT_2, /* widget id */ GX_STYLE_BORDER_THICK|GX_STYLE_TEXT_CENTER, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(GX_PROMPT), /* control block size */ GX_COLOR_ID_WIDGET_FILL, /* normal color id */ GX_COLOR_ID_SELECTED_FILL, /* selected color id */ gx_studio_prompt_create, /* create function */ GX_NULL, /* drawing function override */ GX_NULL, /* event function override */ {56, 98, 363, 141}, /* widget size */ &text_screen_prompt_3_define, /* next widget definition */ GX_NULL, /* no child widgets */ offsetof(TEXT_SCREEN_CONTROL_BLOCK, text_screen_prompt_2), /* control block */ (void *) &text_screen_prompt_2_properties /* extended properties */ }; GX_CONST GX_STUDIO_WIDGET text_screen_prompt_1_define = { "prompt_1", GX_TYPE_PROMPT, /* widget type */ ID_PROMPT_1, /* widget id */ GX_STYLE_BORDER_THIN|GX_STYLE_TRANSPARENT|GX_STYLE_TEXT_CENTER, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(GX_PROMPT), /* control block size */ GX_COLOR_ID_WIDGET_FILL, /* normal color id */ GX_COLOR_ID_SELECTED_FILL, /* selected color id */ gx_studio_prompt_create, /* create function */ GX_NULL, /* drawing function override */ GX_NULL, /* event function override */ {56, 31, 363, 54}, /* widget size */ &text_screen_prompt_2_define, /* next widget definition */ GX_NULL, /* no child widgets */ offsetof(TEXT_SCREEN_CONTROL_BLOCK, text_screen_prompt_1), /* control block */ (void *) &text_screen_prompt_1_properties /* extended properties */ }; GX_CONST GX_STUDIO_WIDGET text_screen_define = { "text_screen", GX_TYPE_WINDOW, /* widget type */ ID_TEXT_SCREEN, /* widget id */ GX_STYLE_BORDER_THIN, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(TEXT_SCREEN_CONTROL_BLOCK), /* control block size */ GX_COLOR_ID_WINDOW_FILL, /* normal color id */ GX_COLOR_ID_WINDOW_FILL, /* selected color id */ gx_studio_window_create, /* create function */ GX_NULL, /* drawing function override */ (UINT (*)(GX_WIDGET *, GX_EVENT *)) next_button_handler, /* event function override */ {39, 25, 582, 443}, /* widget size */ GX_NULL, /* next widget */ &text_screen_prompt_1_define, /* child widget */ 0, /* control block */ (void *) &text_screen_properties /* extended properties */ }; GX_WINDOW_PROPERTIES window_screen_properties = { 0 /* wallpaper pixelmap id */ }; GX_WINDOW_PROPERTIES window_screen_window_5_properties = { 0 /* wallpaper pixelmap id */ }; GX_WINDOW_PROPERTIES window_screen_window_6_properties = { 0 /* wallpaper pixelmap id */ }; GX_WINDOW_PROPERTIES window_screen_window_7_properties = { 0 /* wallpaper pixelmap id */ }; GX_WINDOW_PROPERTIES window_screen_window_8_properties = { 0 /* wallpaper pixelmap id */ }; GX_WINDOW_PROPERTIES window_screen_scroll_frame_1_properties = { 0 /* wallpaper pixelmap id */ }; GX_WINDOW_PROPERTIES window_screen_window_4_properties = { GX_PIXELMAP_ID_FISH /* wallpaper pixelmap id */ }; GX_SCROLLBAR_APPEARANCE window_screen_hscroll_1_properties = { 20, /* scroll width */ 18, /* thumb width */ 20, /* thumb travel min */ 20, /* thumb travel max */ 0, /* scroll fill pixelmap */ 0, /* scroll thumb pixelmap */ 0, /* scroll up pixelmap */ 0, /* scroll down pixelmap */ GX_COLOR_ID_WIDGET_FILL, /* scroll fill color */ GX_COLOR_ID_SCROLL_BUTTON, /* scroll button color */ }; GX_SCROLLBAR_APPEARANCE window_screen_vertical_scroll_1_properties = { 20, /* scroll width */ 18, /* thumb width */ 20, /* thumb travel min */ 20, /* thumb travel max */ 0, /* scroll fill pixelmap */ 0, /* scroll thumb pixelmap */ 0, /* scroll up pixelmap */ 0, /* scroll down pixelmap */ GX_COLOR_ID_WIDGET_FILL, /* scroll fill color */ GX_COLOR_ID_SCROLL_BUTTON, /* scroll button color */ }; GX_VERTICAL_LIST_PROPERTIES window_screen_vertical_list_properties = { 0, /* wallpaper id */ GX_NULL, /* callback function */ 4 /* total rows */ }; GX_TEXT_BUTTON_PROPERTIES window_screen_button_1_properties = { GX_STRING_ID_STRING_19, /* string id */ GX_FONT_ID_BUTTON, /* font id */ GX_COLOR_ID_BTN_TEXT, /* normal text color */ GX_COLOR_ID_BTN_TEXT /* selected text color */ }; GX_TEXT_BUTTON_PROPERTIES window_screen_button_2_properties = { GX_STRING_ID_STRING_20, /* string id */ GX_FONT_ID_BUTTON, /* font id */ GX_COLOR_ID_BTN_TEXT, /* normal text color */ GX_COLOR_ID_BTN_TEXT /* selected text color */ }; GX_TEXT_BUTTON_PROPERTIES window_screen_button_3_properties = { GX_STRING_ID_STRING_21, /* string id */ GX_FONT_ID_BUTTON, /* font id */ GX_COLOR_ID_BTN_TEXT, /* normal text color */ GX_COLOR_ID_BTN_TEXT /* selected text color */ }; GX_TEXT_BUTTON_PROPERTIES window_screen_button_4_properties = { GX_STRING_ID_STRING_22, /* string id */ GX_FONT_ID_BUTTON, /* font id */ GX_COLOR_ID_BTN_TEXT, /* normal text color */ GX_COLOR_ID_BTN_TEXT /* selected text color */ }; GX_PROMPT_PROPERTIES window_screen_nested_label_1_properties = { GX_STRING_ID_STRING_16, /* string id */ GX_FONT_ID_PROMPT, /* font id */ GX_COLOR_ID_TEXT, /* normal text color */ GX_COLOR_ID_SELECTED_TEXT /* selected text color */ }; GX_PROMPT_PROPERTIES window_screen_frame_label_1_properties = { GX_STRING_ID_STRING_17, /* string id */ GX_FONT_ID_PROMPT, /* font id */ GX_COLOR_ID_TEXT, /* normal text color */ GX_COLOR_ID_SELECTED_TEXT /* selected text color */ }; GX_PROMPT_PROPERTIES window_screen_vlist_label_1_properties = { GX_STRING_ID_STRING_18, /* string id */ GX_FONT_ID_PROMPT, /* font id */ GX_COLOR_ID_TEXT, /* normal text color */ GX_COLOR_ID_SELECTED_TEXT /* selected text color */ }; GX_HORIZONTAL_LIST_PROPERTIES window_screen_horizontal_list_1_properties = { 0, /* wallpaper id */ GX_NULL, /* callback function */ 5 /* total columns */ }; GX_ICON_BUTTON_PROPERTIES window_screen_icon_button_1_properties = { GX_PIXELMAP_ID_I_HISTORY_LG /* pixelmap id */ }; GX_ICON_BUTTON_PROPERTIES window_screen_icon_button_2_properties = { GX_PIXELMAP_ID_I_MEDICATIONSGREEN_LG /* pixelmap id */ }; GX_ICON_BUTTON_PROPERTIES window_screen_icon_button_3_properties = { GX_PIXELMAP_ID_I_PATIENTLIST_LG /* pixelmap id */ }; GX_ICON_BUTTON_PROPERTIES window_screen_icon_button_4_properties = { GX_PIXELMAP_ID_I_MEDICATIONSRED_LG /* pixelmap id */ }; GX_ICON_BUTTON_PROPERTIES window_screen_icon_button_5_properties = { GX_PIXELMAP_ID_BLACK_PAUSE /* pixelmap id */ }; GX_PROMPT_PROPERTIES window_screen_hlist_label_1_properties = { GX_STRING_ID_STRING_23, /* string id */ GX_FONT_ID_PROMPT, /* font id */ GX_COLOR_ID_TEXT, /* normal text color */ GX_COLOR_ID_SELECTED_TEXT /* selected text color */ }; GX_TEXT_BUTTON_PROPERTIES window_screen_next_button_1_properties = { GX_STRING_ID_STRING_36, /* string id */ GX_FONT_ID_BUTTON, /* font id */ GX_COLOR_ID_WHITE, /* normal text color */ GX_COLOR_ID_WHITE /* selected text color */ }; GX_DROP_LIST_PROPERTIES window_screen_drop_list_properties = { 0, /* widget pixelmap id */ 0, /* popup list wallpaper pixelmap id */ drop_list_row_create, /* callback function */ 100, /* total rows */ 100 /* open height */ }; GX_PROMPT_PROPERTIES window_screen_hlist_label_properties = { GX_STRING_ID_STRING_37, /* string id */ GX_FONT_ID_PROMPT, /* font id */ GX_COLOR_ID_TEXT, /* normal text color */ GX_COLOR_ID_SELECTED_TEXT /* selected text color */ }; GX_CONST GX_STUDIO_WIDGET window_screen_window_8_define = { "window_8", GX_TYPE_WINDOW, /* widget type */ GX_ID_NONE, /* widget id */ GX_STYLE_BORDER_THIN, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(GX_WINDOW), /* control block size */ GX_COLOR_ID_WINDOW_FILL, /* normal color id */ GX_COLOR_ID_WINDOW_FILL, /* selected color id */ gx_studio_window_create, /* create function */ GX_NULL, /* drawing function override */ GX_NULL, /* event function override */ {211, 90, 304, 162}, /* widget size */ GX_NULL, /* no next widget */ GX_NULL, /* no child widgets */ offsetof(WINDOW_SCREEN_CONTROL_BLOCK, window_screen_window_8), /* control block */ (void *) &window_screen_window_8_properties /* extended properties */ }; GX_CONST GX_STUDIO_WIDGET window_screen_window_7_define = { "window_7", GX_TYPE_WINDOW, /* widget type */ GX_ID_NONE, /* widget id */ GX_STYLE_BORDER_THIN, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(GX_WINDOW), /* control block size */ GX_COLOR_ID_BLUE, /* normal color id */ GX_COLOR_ID_BLUE, /* selected color id */ gx_studio_window_create, /* create function */ GX_NULL, /* drawing function override */ GX_NULL, /* event function override */ {92, 69, 185, 141}, /* widget size */ &window_screen_window_8_define, /* next widget definition */ GX_NULL, /* no child widgets */ offsetof(WINDOW_SCREEN_CONTROL_BLOCK, window_screen_window_7), /* control block */ (void *) &window_screen_window_7_properties /* extended properties */ }; GX_CONST GX_STUDIO_WIDGET window_screen_window_6_define = { "window_6", GX_TYPE_WINDOW, /* widget type */ GX_ID_NONE, /* widget id */ GX_STYLE_BORDER_THIN, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(GX_WINDOW), /* control block size */ GX_COLOR_ID_BLACK, /* normal color id */ GX_COLOR_ID_BLACK, /* selected color id */ gx_studio_window_create, /* create function */ GX_NULL, /* drawing function override */ GX_NULL, /* event function override */ {73, 58, 319, 172}, /* widget size */ GX_NULL, /* no next widget */ &window_screen_window_7_define, /* child widget definition */ offsetof(WINDOW_SCREEN_CONTROL_BLOCK, window_screen_window_6), /* control block */ (void *) &window_screen_window_6_properties /* extended properties */ }; GX_CONST GX_STUDIO_WIDGET window_screen_vertical_scroll_1_define = { "vertical_scroll_1", GX_TYPE_VERTICAL_SCROLL, /* widget type */ ID_VERTICAL_SCROLLBAR, /* widget id */ GX_STYLE_BORDER_NONE|GX_SCROLLBAR_RELATIVE_THUMB|GX_SCROLLBAR_END_BUTTONS|GX_SCROLLBAR_VERTICAL, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(GX_SCROLLBAR), /* control block size */ GX_COLOR_ID_WIDGET_FILL, /* normal color id */ GX_COLOR_ID_SELECTED_FILL, /* selected color id */ gx_studio_vertical_scrollbar_create, /* create function */ GX_NULL, /* drawing function override */ GX_NULL, /* event function override */ {542, 48, 561, 161}, /* widget size */ GX_NULL, /* no next widget */ GX_NULL, /* no child widgets */ offsetof(WINDOW_SCREEN_CONTROL_BLOCK, window_screen_vertical_scroll_1), /* control block */ (void *) &window_screen_vertical_scroll_1_properties /* extended properties */ }; GX_CONST GX_STUDIO_WIDGET window_screen_hscroll_1_define = { "hscroll_1", GX_TYPE_HORIZONTAL_SCROLL, /* widget type */ ID_HORIZONTAL_SCROLLBAR, /* widget id */ GX_STYLE_BORDER_NONE|GX_SCROLLBAR_RELATIVE_THUMB|GX_SCROLLBAR_END_BUTTONS|GX_SCROLLBAR_HORIZONTAL, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(GX_SCROLLBAR), /* control block size */ GX_COLOR_ID_WIDGET_FILL, /* normal color id */ GX_COLOR_ID_SELECTED_FILL, /* selected color id */ gx_studio_horizontal_scrollbar_create, /* create function */ GX_NULL, /* drawing function override */ GX_NULL, /* event function override */ {352, 162, 541, 181}, /* widget size */ &window_screen_vertical_scroll_1_define, /* next widget definition */ GX_NULL, /* no child widgets */ offsetof(WINDOW_SCREEN_CONTROL_BLOCK, window_screen_hscroll_1), /* control block */ (void *) &window_screen_hscroll_1_properties /* extended properties */ }; GX_CONST GX_STUDIO_WIDGET window_screen_window_4_define = { "window_4", GX_TYPE_WINDOW, /* widget type */ GX_ID_NONE, /* widget id */ GX_STYLE_BORDER_THIN, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(GX_WINDOW), /* control block size */ GX_COLOR_ID_WINDOW_FILL, /* normal color id */ GX_COLOR_ID_WINDOW_FILL, /* selected color id */ gx_studio_window_create, /* create function */ GX_NULL, /* drawing function override */ GX_NULL, /* event function override */ {351, 47, 750, 446}, /* widget size */ &window_screen_hscroll_1_define, /* next widget definition */ GX_NULL, /* no child widgets */ offsetof(WINDOW_SCREEN_CONTROL_BLOCK, window_screen_window_4), /* control block */ (void *) &window_screen_window_4_properties /* extended properties */ }; GX_CONST GX_STUDIO_WIDGET window_screen_button_4_define = { "button_4", GX_TYPE_TEXT_BUTTON, /* widget type */ GX_ID_NONE, /* widget id */ GX_STYLE_BORDER_RAISED|GX_STYLE_ENABLED|GX_STYLE_TEXT_CENTER, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(GX_TEXT_BUTTON), /* control block size */ GX_COLOR_ID_BTN_LOWER, /* normal color id */ GX_COLOR_ID_BTN_UPPER, /* selected color id */ gx_studio_text_button_create, /* create function */ GX_NULL, /* drawing function override */ GX_NULL, /* event function override */ {59, 326, 156, 360}, /* widget size */ GX_NULL, /* no next widget */ GX_NULL, /* no child widgets */ offsetof(WINDOW_SCREEN_CONTROL_BLOCK, window_screen_button_4), /* control block */ (void *) &window_screen_button_4_properties /* extended properties */ }; GX_CONST GX_STUDIO_WIDGET window_screen_button_3_define = { "button_3", GX_TYPE_TEXT_BUTTON, /* widget type */ GX_ID_NONE, /* widget id */ GX_STYLE_BORDER_RAISED|GX_STYLE_ENABLED|GX_STYLE_TEXT_CENTER, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(GX_TEXT_BUTTON), /* control block size */ GX_COLOR_ID_BTN_LOWER, /* normal color id */ GX_COLOR_ID_BTN_UPPER, /* selected color id */ gx_studio_text_button_create, /* create function */ GX_NULL, /* drawing function override */ GX_NULL, /* event function override */ {59, 291, 156, 325}, /* widget size */ &window_screen_button_4_define, /* next widget definition */ GX_NULL, /* no child widgets */ offsetof(WINDOW_SCREEN_CONTROL_BLOCK, window_screen_button_3), /* control block */ (void *) &window_screen_button_3_properties /* extended properties */ }; GX_CONST GX_STUDIO_WIDGET window_screen_button_2_define = { "button_2", GX_TYPE_TEXT_BUTTON, /* widget type */ GX_ID_NONE, /* widget id */ GX_STYLE_BORDER_RAISED|GX_STYLE_ENABLED|GX_STYLE_TEXT_CENTER, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(GX_TEXT_BUTTON), /* control block size */ GX_COLOR_ID_BTN_LOWER, /* normal color id */ GX_COLOR_ID_BTN_UPPER, /* selected color id */ gx_studio_text_button_create, /* create function */ GX_NULL, /* drawing function override */ GX_NULL, /* event function override */ {59, 256, 156, 290}, /* widget size */ &window_screen_button_3_define, /* next widget definition */ GX_NULL, /* no child widgets */ offsetof(WINDOW_SCREEN_CONTROL_BLOCK, window_screen_button_2), /* control block */ (void *) &window_screen_button_2_properties /* extended properties */ }; GX_CONST GX_STUDIO_WIDGET window_screen_button_1_define = { "button_1", GX_TYPE_TEXT_BUTTON, /* widget type */ GX_ID_NONE, /* widget id */ GX_STYLE_BORDER_RAISED|GX_STYLE_ENABLED|GX_STYLE_TEXT_CENTER, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(GX_TEXT_BUTTON), /* control block size */ GX_COLOR_ID_BTN_LOWER, /* normal color id */ GX_COLOR_ID_BTN_UPPER, /* selected color id */ gx_studio_text_button_create, /* create function */ GX_NULL, /* drawing function override */ GX_NULL, /* event function override */ {59, 221, 156, 255}, /* widget size */ &window_screen_button_2_define, /* next widget definition */ GX_NULL, /* no child widgets */ offsetof(WINDOW_SCREEN_CONTROL_BLOCK, window_screen_button_1), /* control block */ (void *) &window_screen_button_1_properties /* extended properties */ }; GX_CONST GX_STUDIO_WIDGET window_screen_icon_button_5_define = { "icon_button_5", GX_TYPE_ICON_BUTTON, /* widget type */ GX_ID_NONE, /* widget id */ GX_STYLE_BORDER_RAISED|GX_STYLE_ENABLED|GX_STYLE_HALIGN_CENTER|GX_STYLE_VALIGN_CENTER, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(GX_ICON_BUTTON), /* control block size */ GX_COLOR_ID_BTN_LOWER, /* normal color id */ GX_COLOR_ID_BTN_UPPER, /* selected color id */ gx_studio_icon_button_create, /* create function */ GX_NULL, /* drawing function override */ GX_NULL, /* event function override */ {385, 220, 435, 281}, /* widget size */ GX_NULL, /* no next widget */ GX_NULL, /* no child widgets */ offsetof(WINDOW_SCREEN_CONTROL_BLOCK, window_screen_icon_button_5), /* control block */ (void *) &window_screen_icon_button_5_properties /* extended properties */ }; GX_CONST GX_STUDIO_WIDGET window_screen_icon_button_4_define = { "icon_button_4", GX_TYPE_ICON_BUTTON, /* widget type */ GX_ID_NONE, /* widget id */ GX_STYLE_BORDER_RAISED|GX_STYLE_ENABLED|GX_STYLE_HALIGN_CENTER|GX_STYLE_VALIGN_CENTER, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(GX_ICON_BUTTON), /* control block size */ GX_COLOR_ID_BTN_LOWER, /* normal color id */ GX_COLOR_ID_BTN_UPPER, /* selected color id */ gx_studio_icon_button_create, /* create function */ GX_NULL, /* drawing function override */ GX_NULL, /* event function override */ {334, 220, 384, 281}, /* widget size */ &window_screen_icon_button_5_define, /* next widget definition */ GX_NULL, /* no child widgets */ offsetof(WINDOW_SCREEN_CONTROL_BLOCK, window_screen_icon_button_4), /* control block */ (void *) &window_screen_icon_button_4_properties /* extended properties */ }; GX_CONST GX_STUDIO_WIDGET window_screen_icon_button_3_define = { "icon_button_3", GX_TYPE_ICON_BUTTON, /* widget type */ GX_ID_NONE, /* widget id */ GX_STYLE_BORDER_RAISED|GX_STYLE_ENABLED|GX_STYLE_HALIGN_CENTER|GX_STYLE_VALIGN_CENTER, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(GX_ICON_BUTTON), /* control block size */ GX_COLOR_ID_BTN_LOWER, /* normal color id */ GX_COLOR_ID_BTN_UPPER, /* selected color id */ gx_studio_icon_button_create, /* create function */ GX_NULL, /* drawing function override */ GX_NULL, /* event function override */ {283, 220, 333, 281}, /* widget size */ &window_screen_icon_button_4_define, /* next widget definition */ GX_NULL, /* no child widgets */ offsetof(WINDOW_SCREEN_CONTROL_BLOCK, window_screen_icon_button_3), /* control block */ (void *) &window_screen_icon_button_3_properties /* extended properties */ }; GX_CONST GX_STUDIO_WIDGET window_screen_icon_button_2_define = { "icon_button_2", GX_TYPE_ICON_BUTTON, /* widget type */ GX_ID_NONE, /* widget id */ GX_STYLE_BORDER_RAISED|GX_STYLE_ENABLED|GX_STYLE_HALIGN_CENTER|GX_STYLE_VALIGN_CENTER, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(GX_ICON_BUTTON), /* control block size */ GX_COLOR_ID_BTN_LOWER, /* normal color id */ GX_COLOR_ID_BTN_UPPER, /* selected color id */ gx_studio_icon_button_create, /* create function */ GX_NULL, /* drawing function override */ GX_NULL, /* event function override */ {232, 220, 282, 281}, /* widget size */ &window_screen_icon_button_3_define, /* next widget definition */ GX_NULL, /* no child widgets */ offsetof(WINDOW_SCREEN_CONTROL_BLOCK, window_screen_icon_button_2), /* control block */ (void *) &window_screen_icon_button_2_properties /* extended properties */ }; GX_CONST GX_STUDIO_WIDGET window_screen_icon_button_1_define = { "icon_button_1", GX_TYPE_ICON_BUTTON, /* widget type */ GX_ID_NONE, /* widget id */ GX_STYLE_BORDER_RAISED|GX_STYLE_ENABLED|GX_STYLE_HALIGN_CENTER|GX_STYLE_VALIGN_CENTER, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(GX_ICON_BUTTON), /* control block size */ GX_COLOR_ID_BTN_LOWER, /* normal color id */ GX_COLOR_ID_BTN_UPPER, /* selected color id */ gx_studio_icon_button_create, /* create function */ GX_NULL, /* drawing function override */ GX_NULL, /* event function override */ {181, 220, 231, 281}, /* widget size */ &window_screen_icon_button_2_define, /* next widget definition */ GX_NULL, /* no child widgets */ offsetof(WINDOW_SCREEN_CONTROL_BLOCK, window_screen_icon_button_1), /* control block */ (void *) &window_screen_icon_button_1_properties /* extended properties */ }; GX_CONST GX_STUDIO_WIDGET window_screen_hlist_label_define = { "hlist_label", GX_TYPE_PROMPT, /* widget type */ GX_ID_NONE, /* widget id */ GX_STYLE_BORDER_NONE|GX_STYLE_TRANSPARENT|GX_STYLE_TEXT_CENTER, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(GX_PROMPT), /* control block size */ GX_COLOR_ID_WIDGET_FILL, /* normal color id */ GX_COLOR_ID_SELECTED_FILL, /* selected color id */ gx_studio_prompt_create, /* create function */ GX_NULL, /* drawing function override */ GX_NULL, /* event function override */ {253, 298, 341, 321}, /* widget size */ GX_NULL, /* no next widget */ GX_NULL, /* no child widgets */ offsetof(WINDOW_SCREEN_CONTROL_BLOCK, window_screen_hlist_label), /* control block */ (void *) &window_screen_hlist_label_properties /* extended properties */ }; GX_CONST GX_STUDIO_WIDGET window_screen_drop_list_define = { "drop_list", GX_TYPE_DROP_LIST, /* widget type */ ID_DROP_LIST, /* widget id */ GX_STYLE_BORDER_THIN|GX_STYLE_ENABLED, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(GX_DROP_LIST), /* control block size */ GX_COLOR_ID_WIDGET_FILL, /* normal color id */ GX_COLOR_ID_WIDGET_FILL, /* selected color id */ gx_studio_drop_list_create, /* create function */ GX_NULL, /* drawing function override */ GX_NULL, /* event function override */ {183, 321, 430, 349}, /* widget size */ &window_screen_hlist_label_define, /* next widget definition */ GX_NULL, /* no child widgets */ offsetof(WINDOW_SCREEN_CONTROL_BLOCK, window_screen_drop_list), /* control block */ (void *) &window_screen_drop_list_properties /* extended properties */ }; GX_CONST GX_STUDIO_WIDGET window_screen_next_button_1_define = { "next_button_1", GX_TYPE_TEXT_BUTTON, /* widget type */ IDB_NEXT, /* widget id */ GX_STYLE_BORDER_RAISED|GX_STYLE_ENABLED|GX_STYLE_TEXT_CENTER, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(GX_TEXT_BUTTON), /* control block size */ GX_COLOR_ID_NEXT_BUTTON_LOWER, /* normal color id */ GX_COLOR_ID_NEXT_BUTTON_UPPER, /* selected color id */ gx_studio_text_button_create, /* create function */ GX_NULL, /* drawing function override */ GX_NULL, /* event function override */ {491, 434, 570, 458}, /* widget size */ &window_screen_drop_list_define, /* next widget definition */ GX_NULL, /* no child widgets */ offsetof(WINDOW_SCREEN_CONTROL_BLOCK, window_screen_next_button_1), /* control block */ (void *) &window_screen_next_button_1_properties /* extended properties */ }; GX_CONST GX_STUDIO_WIDGET window_screen_hlist_label_1_define = { "hlist_label_1", GX_TYPE_PROMPT, /* widget type */ GX_ID_NONE, /* widget id */ GX_STYLE_BORDER_NONE|GX_STYLE_TRANSPARENT|GX_STYLE_TEXT_CENTER, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(GX_PROMPT), /* control block size */ GX_COLOR_ID_WIDGET_FILL, /* normal color id */ GX_COLOR_ID_SELECTED_FILL, /* selected color id */ gx_studio_prompt_create, /* create function */ GX_NULL, /* drawing function override */ GX_NULL, /* event function override */ {242, 193, 373, 216}, /* widget size */ &window_screen_next_button_1_define, /* next widget definition */ GX_NULL, /* no child widgets */ offsetof(WINDOW_SCREEN_CONTROL_BLOCK, window_screen_hlist_label_1), /* control block */ (void *) &window_screen_hlist_label_1_properties /* extended properties */ }; GX_CONST GX_STUDIO_WIDGET window_screen_horizontal_list_1_define = { "horizontal_list_1", GX_TYPE_HORIZONTAL_LIST, /* widget type */ GX_ID_NONE, /* widget id */ GX_STYLE_BORDER_THIN, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(GX_HORIZONTAL_LIST), /* control block size */ GX_COLOR_ID_WINDOW_FILL, /* normal color id */ GX_COLOR_ID_WINDOW_FILL, /* selected color id */ gx_studio_horizontal_list_create, /* create function */ GX_NULL, /* drawing function override */ GX_NULL, /* event function override */ {180, 219, 437, 282}, /* widget size */ &window_screen_hlist_label_1_define, /* next widget definition */ &window_screen_icon_button_1_define, /* child widget definition */ offsetof(WINDOW_SCREEN_CONTROL_BLOCK, window_screen_horizontal_list_1), /* control block */ (void *) &window_screen_horizontal_list_1_properties /* extended properties */ }; GX_CONST GX_STUDIO_WIDGET window_screen_vlist_label_1_define = { "vlist_label_1", GX_TYPE_PROMPT, /* widget type */ GX_ID_NONE, /* widget id */ GX_STYLE_BORDER_NONE|GX_STYLE_TRANSPARENT|GX_STYLE_TEXT_CENTER, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(GX_PROMPT), /* control block size */ GX_COLOR_ID_WIDGET_FILL, /* normal color id */ GX_COLOR_ID_SELECTED_FILL, /* selected color id */ gx_studio_prompt_create, /* create function */ GX_NULL, /* drawing function override */ GX_NULL, /* event function override */ {45, 193, 176, 216}, /* widget size */ &window_screen_horizontal_list_1_define, /* next widget definition */ GX_NULL, /* no child widgets */ offsetof(WINDOW_SCREEN_CONTROL_BLOCK, window_screen_vlist_label_1), /* control block */ (void *) &window_screen_vlist_label_1_properties /* extended properties */ }; GX_CONST GX_STUDIO_WIDGET window_screen_frame_label_1_define = { "frame_label_1", GX_TYPE_PROMPT, /* widget type */ GX_ID_NONE, /* widget id */ GX_STYLE_BORDER_NONE|GX_STYLE_TRANSPARENT|GX_STYLE_TEXT_CENTER, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(GX_PROMPT), /* control block size */ GX_COLOR_ID_WIDGET_FILL, /* normal color id */ GX_COLOR_ID_SELECTED_FILL, /* selected color id */ gx_studio_prompt_create, /* create function */ GX_NULL, /* drawing function override */ GX_NULL, /* event function override */ {389, 21, 520, 44}, /* widget size */ &window_screen_vlist_label_1_define, /* next widget definition */ GX_NULL, /* no child widgets */ offsetof(WINDOW_SCREEN_CONTROL_BLOCK, window_screen_frame_label_1), /* control block */ (void *) &window_screen_frame_label_1_properties /* extended properties */ }; GX_CONST GX_STUDIO_WIDGET window_screen_nested_label_1_define = { "nested_label_1", GX_TYPE_PROMPT, /* widget type */ GX_ID_NONE, /* widget id */ GX_STYLE_BORDER_NONE|GX_STYLE_TRANSPARENT|GX_STYLE_TEXT_CENTER, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(GX_PROMPT), /* control block size */ GX_COLOR_ID_WIDGET_FILL, /* normal color id */ GX_COLOR_ID_SELECTED_FILL, /* selected color id */ gx_studio_prompt_create, /* create function */ GX_NULL, /* drawing function override */ GX_NULL, /* event function override */ {118, 21, 249, 44}, /* widget size */ &window_screen_frame_label_1_define, /* next widget definition */ GX_NULL, /* no child widgets */ offsetof(WINDOW_SCREEN_CONTROL_BLOCK, window_screen_nested_label_1), /* control block */ (void *) &window_screen_nested_label_1_properties /* extended properties */ }; GX_CONST GX_STUDIO_WIDGET window_screen_vertical_list_define = { "vertical_list", GX_TYPE_VERTICAL_LIST, /* widget type */ ID_VERTICAL_LIST, /* widget id */ GX_STYLE_BORDER_RAISED, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(GX_VERTICAL_LIST), /* control block size */ GX_COLOR_ID_WINDOW_FILL, /* normal color id */ GX_COLOR_ID_WINDOW_FILL, /* selected color id */ gx_studio_vertical_list_create, /* create function */ GX_NULL, /* drawing function override */ GX_NULL, /* event function override */ {57, 219, 158, 362}, /* widget size */ &window_screen_nested_label_1_define, /* next widget definition */ &window_screen_button_1_define, /* child widget definition */ offsetof(WINDOW_SCREEN_CONTROL_BLOCK, window_screen_vertical_list), /* control block */ (void *) &window_screen_vertical_list_properties /* extended properties */ }; GX_CONST GX_STUDIO_WIDGET window_screen_scroll_frame_1_define = { "scroll_frame_1", GX_TYPE_WINDOW, /* widget type */ GX_ID_NONE, /* widget id */ GX_STYLE_BORDER_THIN, /* style flags */ 0, /* status flags */ sizeof(GX_WINDOW), /* control block size */ GX_COLOR_ID_WINDOW_FILL, /* normal color id */ GX_COLOR_ID_WINDOW_FILL, /* selected color id */ gx_studio_window_create, /* create function */ GX_NULL, /* drawing function override */ GX_NULL, /* event function override */ {351, 47, 562, 182}, /* widget size */ &window_screen_vertical_list_define, /* next widget definition */ &window_screen_window_4_define, /* child widget definition */ offsetof(WINDOW_SCREEN_CONTROL_BLOCK, window_screen_scroll_frame_1), /* control block */ (void *) &window_screen_scroll_frame_1_properties /* extended properties */ }; GX_CONST GX_STUDIO_WIDGET window_screen_window_5_define = { "window_5", GX_TYPE_WINDOW, /* widget type */ GX_ID_NONE, /* widget id */ GX_STYLE_BORDER_THICK, /* style flags */ 0, /* status flags */ sizeof(GX_WINDOW), /* control block size */ GX_COLOR_ID_ORANGE, /* normal color id */ GX_COLOR_ID_ORANGE, /* selected color id */ gx_studio_window_create, /* create function */ GX_NULL, /* drawing function override */ GX_NULL, /* event function override */ {56, 46, 341, 184}, /* widget size */ &window_screen_scroll_frame_1_define, /* next widget definition */ &window_screen_window_6_define, /* child widget definition */ offsetof(WINDOW_SCREEN_CONTROL_BLOCK, window_screen_window_5), /* control block */ (void *) &window_screen_window_5_properties /* extended properties */ }; GX_CONST GX_STUDIO_WIDGET window_screen_define = { "window_screen", GX_TYPE_WINDOW, /* widget type */ ID_WINDOW_SCREEN, /* widget id */ GX_STYLE_BORDER_THIN, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(WINDOW_SCREEN_CONTROL_BLOCK), /* control block size */ GX_COLOR_ID_WINDOW_FILL, /* normal color id */ GX_COLOR_ID_WINDOW_FILL, /* selected color id */ gx_studio_window_create, /* create function */ GX_NULL, /* drawing function override */ (UINT (*)(GX_WIDGET *, GX_EVENT *)) next_button_handler, /* event function override */ {24, 12, 578, 466}, /* widget size */ GX_NULL, /* next widget */ &window_screen_window_5_define, /* child widget */ 0, /* control block */ (void *) &window_screen_properties /* extended properties */ }; GX_WINDOW_PROPERTIES button_screen_properties = { 0 /* wallpaper pixelmap id */ }; GX_PROMPT_PROPERTIES button_screen_title_1_properties = { GX_STRING_ID_STRING_1, /* string id */ GX_FONT_ID_PROMPT, /* font id */ GX_COLOR_ID_TEXT, /* normal text color */ GX_COLOR_ID_TEXT /* selected text color */ }; GX_TEXT_BUTTON_PROPERTIES button_screen_text_button_1_properties = { GX_STRING_ID_STRING_4, /* string id */ GX_FONT_ID_BUTTON, /* font id */ GX_COLOR_ID_BTN_TEXT, /* normal text color */ GX_COLOR_ID_BTN_TEXT /* selected text color */ }; GX_CHECKBOX_PROPERTIES button_screen_checkbox_properties = { GX_STRING_ID_STRING_3, /* string id */ GX_FONT_ID_BUTTON, /* font id */ GX_COLOR_ID_BTN_TEXT, /* normal text color */ GX_COLOR_ID_BTN_TEXT, /* selected text color */ 0, /* unchecked pixelmap id */ 0, /* checked pixelmap id */ 0, /* unchecked disabled pixelmap id */ 0 /* checked disabled pixelmap id */ }; GX_RADIO_BUTTON_PROPERTIES button_screen_radio_button1_properties = { GX_STRING_ID_STRING_9, /* string id */ GX_FONT_ID_BUTTON, /* font id */ GX_COLOR_ID_BTN_TEXT, /* normal text color */ GX_COLOR_ID_BTN_TEXT, /* selected text color */ 0, /* off pixelmap id */ 0, /* on pixelmap id */ 0, /* off disabled pixelmap id */ 0 /* on disabled pixelmap id */ }; GX_PIXELMAP_BUTTON_PROPERTIES button_screen_pixelmap_button1_properties = { GX_PIXELMAP_ID_ORANGE_BUTTON, /* normal pixelmap id */ GX_PIXELMAP_ID_ORANGE_BUTTON_PRESSED, /* selected pixelmap id */ GX_PIXELMAP_ID_BUTTON_DISABLED /* disabled pixelmap id */ }; GX_ICON_PROPERTIES button_screen_icon_properties = { GX_PIXELMAP_ID_I_HISTORY_LG, /* normal pixelmap id */ 0 /* selected pixelmap id */ }; GX_ICON_BUTTON_PROPERTIES button_screen_icon_button_6_properties = { GX_PIXELMAP_ID_SAVE_ICON /* pixelmap id */ }; GX_PROMPT_PROPERTIES button_screen_button_label_1_properties = { GX_STRING_ID_STRING_10, /* string id */ GX_FONT_ID_FONT_1BIT, /* font id */ GX_COLOR_ID_TEXT, /* normal text color */ GX_COLOR_ID_SELECTED_TEXT /* selected text color */ }; GX_PROMPT_PROPERTIES button_screen_radio_label_1_properties = { GX_STRING_ID_STRING_13, /* string id */ GX_FONT_ID_PROMPT, /* font id */ GX_COLOR_ID_TEXT, /* normal text color */ GX_COLOR_ID_SELECTED_TEXT /* selected text color */ }; GX_PROMPT_PROPERTIES button_screen_pixbutton_label_1_properties = { GX_STRING_ID_STRING_11, /* string id */ GX_FONT_ID_PROMPT, /* font id */ GX_COLOR_ID_TEXT, /* normal text color */ GX_COLOR_ID_SELECTED_TEXT /* selected text color */ }; GX_PROMPT_PROPERTIES button_screen_texbutton_label_1_properties = { GX_STRING_ID_STRING_2, /* string id */ GX_FONT_ID_FONT_4BIT, /* font id */ GX_COLOR_ID_TEXT, /* normal text color */ GX_COLOR_ID_SELECTED_TEXT /* selected text color */ }; GX_PROMPT_PROPERTIES button_screen_checkbox_label_1_properties = { GX_STRING_ID_STRING_12, /* string id */ GX_FONT_ID_PROMPT, /* font id */ GX_COLOR_ID_TEXT, /* normal text color */ GX_COLOR_ID_SELECTED_TEXT /* selected text color */ }; GX_PROMPT_PROPERTIES button_screen_iconbutton_label_1_properties = { GX_STRING_ID_STRING_14, /* string id */ GX_FONT_ID_PROMPT, /* font id */ GX_COLOR_ID_TEXT, /* normal text color */ GX_COLOR_ID_SELECTED_TEXT /* selected text color */ }; GX_PROMPT_PROPERTIES button_screen_icon_label_1_properties = { GX_STRING_ID_STRING_15, /* string id */ GX_FONT_ID_PROMPT, /* font id */ GX_COLOR_ID_TEXT, /* normal text color */ GX_COLOR_ID_SELECTED_TEXT /* selected text color */ }; GX_TEXT_BUTTON_PROPERTIES button_screen_next_button_properties = { GX_STRING_ID_STRING_36, /* string id */ GX_FONT_ID_BUTTON, /* font id */ GX_COLOR_ID_WHITE, /* normal text color */ GX_COLOR_ID_WHITE /* selected text color */ }; GX_ML_TEXT_BUTTON_PROPERTIES button_screen_multi_line_button_1_properties = { GX_STRING_ID_STRING_39, /* string id */ GX_FONT_ID_BUTTON, /* font id */ GX_COLOR_ID_BTN_TEXT, /* normal text color */ GX_COLOR_ID_BTN_TEXT /* selected text color */ }; GX_PROMPT_PROPERTIES button_screen_texbutton_label_2_properties = { GX_STRING_ID_STRING_40, /* string id */ GX_FONT_ID_FONT_8BIT, /* font id */ GX_COLOR_ID_TEXT, /* normal text color */ GX_COLOR_ID_SELECTED_TEXT /* selected text color */ }; GX_CONST GX_STUDIO_WIDGET button_screen_texbutton_label_2_define = { "texbutton_label_2", GX_TYPE_PROMPT, /* widget type */ GX_ID_NONE, /* widget id */ GX_STYLE_BORDER_NONE|GX_STYLE_TRANSPARENT|GX_STYLE_TEXT_LEFT, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(GX_PROMPT), /* control block size */ GX_COLOR_ID_WIDGET_FILL, /* normal color id */ GX_COLOR_ID_SELECTED_FILL, /* selected color id */ gx_studio_prompt_create, /* create function */ GX_NULL, /* drawing function override */ GX_NULL, /* event function override */ {295, 195, 544, 211}, /* widget size */ GX_NULL, /* no next widget */ GX_NULL, /* no child widgets */ offsetof(BUTTON_SCREEN_CONTROL_BLOCK, button_screen_texbutton_label_2), /* control block */ (void *) &button_screen_texbutton_label_2_properties /* extended properties */ }; GX_CONST GX_STUDIO_WIDGET button_screen_multi_line_button_1_define = { "multi_line_button_1", GX_TYPE_MULTI_LINE_TEXT_BUTTON, /* widget type */ GX_ID_NONE, /* widget id */ GX_STYLE_BORDER_NONE|GX_STYLE_ENABLED|GX_STYLE_TEXT_CENTER, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(GX_MULTI_LINE_TEXT_BUTTON), /* control block size */ GX_COLOR_ID_BTN_LOWER, /* normal color id */ GX_COLOR_ID_BTN_UPPER, /* selected color id */ gx_studio_multi_line_text_button_create, /* create function */ GX_NULL, /* drawing function override */ GX_NULL, /* event function override */ {117, 176, 252, 244}, /* widget size */ &button_screen_texbutton_label_2_define, /* next widget definition */ GX_NULL, /* no child widgets */ offsetof(BUTTON_SCREEN_CONTROL_BLOCK, button_screen_multi_line_button_1), /* control block */ (void *) &button_screen_multi_line_button_1_properties /* extended properties */ }; GX_CONST GX_STUDIO_WIDGET button_screen_next_button_define = { "next_button", GX_TYPE_TEXT_BUTTON, /* widget type */ IDB_NEXT, /* widget id */ GX_STYLE_BORDER_RAISED|GX_STYLE_ENABLED|GX_STYLE_TEXT_CENTER, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(GX_TEXT_BUTTON), /* control block size */ GX_COLOR_ID_NEXT_BUTTON_LOWER, /* normal color id */ GX_COLOR_ID_NEXT_BUTTON_UPPER, /* selected color id */ gx_studio_text_button_create, /* create function */ GX_NULL, /* drawing function override */ GX_NULL, /* event function override */ {484, 441, 563, 465}, /* widget size */ &button_screen_multi_line_button_1_define, /* next widget definition */ GX_NULL, /* no child widgets */ offsetof(BUTTON_SCREEN_CONTROL_BLOCK, button_screen_next_button), /* control block */ (void *) &button_screen_next_button_properties /* extended properties */ }; GX_CONST GX_STUDIO_WIDGET button_screen_icon_label_1_define = { "icon_label_1", GX_TYPE_PROMPT, /* widget type */ GX_ID_NONE, /* widget id */ GX_STYLE_BORDER_NONE|GX_STYLE_TRANSPARENT|GX_STYLE_TEXT_LEFT, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(GX_PROMPT), /* control block size */ GX_COLOR_ID_WIDGET_FILL, /* normal color id */ GX_COLOR_ID_SELECTED_FILL, /* selected color id */ gx_studio_prompt_create, /* create function */ GX_NULL, /* drawing function override */ GX_NULL, /* event function override */ {297, 421, 371, 444}, /* widget size */ &button_screen_next_button_define, /* next widget definition */ GX_NULL, /* no child widgets */ offsetof(BUTTON_SCREEN_CONTROL_BLOCK, button_screen_icon_label_1), /* control block */ (void *) &button_screen_icon_label_1_properties /* extended properties */ }; GX_CONST GX_STUDIO_WIDGET button_screen_iconbutton_label_1_define = { "iconbutton_label_1", GX_TYPE_PROMPT, /* widget type */ GX_ID_NONE, /* widget id */ GX_STYLE_BORDER_NONE|GX_STYLE_TRANSPARENT|GX_STYLE_TEXT_LEFT, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(GX_PROMPT), /* control block size */ GX_COLOR_ID_WIDGET_FILL, /* normal color id */ GX_COLOR_ID_SELECTED_FILL, /* selected color id */ gx_studio_prompt_create, /* create function */ GX_NULL, /* drawing function override */ GX_NULL, /* event function override */ {297, 385, 447, 408}, /* widget size */ &button_screen_icon_label_1_define, /* next widget definition */ GX_NULL, /* no child widgets */ offsetof(BUTTON_SCREEN_CONTROL_BLOCK, button_screen_iconbutton_label_1), /* control block */ (void *) &button_screen_iconbutton_label_1_properties /* extended properties */ }; GX_CONST GX_STUDIO_WIDGET button_screen_checkbox_label_1_define = { "checkbox_label_1", GX_TYPE_PROMPT, /* widget type */ GX_ID_NONE, /* widget id */ GX_STYLE_BORDER_NONE|GX_STYLE_TRANSPARENT|GX_STYLE_TEXT_LEFT, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(GX_PROMPT), /* control block size */ GX_COLOR_ID_WIDGET_FILL, /* normal color id */ GX_COLOR_ID_SELECTED_FILL, /* selected color id */ gx_studio_prompt_create, /* create function */ GX_NULL, /* drawing function override */ GX_NULL, /* event function override */ {297, 325, 417, 348}, /* widget size */ &button_screen_iconbutton_label_1_define, /* next widget definition */ GX_NULL, /* no child widgets */ offsetof(BUTTON_SCREEN_CONTROL_BLOCK, button_screen_checkbox_label_1), /* control block */ (void *) &button_screen_checkbox_label_1_properties /* extended properties */ }; GX_CONST GX_STUDIO_WIDGET button_screen_texbutton_label_1_define = { "texbutton_label_1", GX_TYPE_PROMPT, /* widget type */ GX_ID_NONE, /* widget id */ GX_STYLE_BORDER_NONE|GX_STYLE_TRANSPARENT|GX_STYLE_TEXT_LEFT, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(GX_PROMPT), /* control block size */ GX_COLOR_ID_WIDGET_FILL, /* normal color id */ GX_COLOR_ID_SELECTED_FILL, /* selected color id */ gx_studio_prompt_create, /* create function */ GX_NULL, /* drawing function override */ GX_NULL, /* event function override */ {297, 146, 461, 169}, /* widget size */ &button_screen_checkbox_label_1_define, /* next widget definition */ GX_NULL, /* no child widgets */ offsetof(BUTTON_SCREEN_CONTROL_BLOCK, button_screen_texbutton_label_1), /* control block */ (void *) &button_screen_texbutton_label_1_properties /* extended properties */ }; GX_CONST GX_STUDIO_WIDGET button_screen_pixbutton_label_1_define = { "pixbutton_label_1", GX_TYPE_PROMPT, /* widget type */ GX_ID_NONE, /* widget id */ GX_STYLE_BORDER_NONE|GX_STYLE_TRANSPARENT|GX_STYLE_TEXT_LEFT, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(GX_PROMPT), /* control block size */ GX_COLOR_ID_WIDGET_FILL, /* normal color id */ GX_COLOR_ID_SELECTED_FILL, /* selected color id */ gx_studio_prompt_create, /* create function */ GX_NULL, /* drawing function override */ GX_NULL, /* event function override */ {297, 271, 479, 294}, /* widget size */ &button_screen_texbutton_label_1_define, /* next widget definition */ GX_NULL, /* no child widgets */ offsetof(BUTTON_SCREEN_CONTROL_BLOCK, button_screen_pixbutton_label_1), /* control block */ (void *) &button_screen_pixbutton_label_1_properties /* extended properties */ }; GX_CONST GX_STUDIO_WIDGET button_screen_radio_label_1_define = { "radio_label_1", GX_TYPE_PROMPT, /* widget type */ GX_ID_NONE, /* widget id */ GX_STYLE_BORDER_NONE|GX_STYLE_TRANSPARENT|GX_STYLE_TEXT_LEFT, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(GX_PROMPT), /* control block size */ GX_COLOR_ID_WIDGET_FILL, /* normal color id */ GX_COLOR_ID_SELECTED_FILL, /* selected color id */ gx_studio_prompt_create, /* create function */ GX_NULL, /* drawing function override */ GX_NULL, /* event function override */ {297, 353, 452, 376}, /* widget size */ &button_screen_pixbutton_label_1_define, /* next widget definition */ GX_NULL, /* no child widgets */ offsetof(BUTTON_SCREEN_CONTROL_BLOCK, button_screen_radio_label_1), /* control block */ (void *) &button_screen_radio_label_1_properties /* extended properties */ }; GX_CONST GX_STUDIO_WIDGET button_screen_button_label_1_define = { "button_label_1", GX_TYPE_PROMPT, /* widget type */ GX_ID_NONE, /* widget id */ GX_STYLE_BORDER_NONE|GX_STYLE_TRANSPARENT|GX_STYLE_TEXT_LEFT, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(GX_PROMPT), /* control block size */ GX_COLOR_ID_WIDGET_FILL, /* normal color id */ GX_COLOR_ID_SELECTED_FILL, /* selected color id */ gx_studio_prompt_create, /* create function */ GX_NULL, /* drawing function override */ GX_NULL, /* event function override */ {297, 103, 407, 126}, /* widget size */ &button_screen_radio_label_1_define, /* next widget definition */ GX_NULL, /* no child widgets */ offsetof(BUTTON_SCREEN_CONTROL_BLOCK, button_screen_button_label_1), /* control block */ (void *) &button_screen_button_label_1_properties /* extended properties */ }; GX_CONST GX_STUDIO_WIDGET button_screen_icon_button_6_define = { "icon_button_6", GX_TYPE_ICON_BUTTON, /* widget type */ ID_ICON_BUTTON, /* widget id */ GX_STYLE_BORDER_RAISED|GX_STYLE_ENABLED, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(GX_ICON_BUTTON), /* control block size */ GX_COLOR_ID_BTN_LOWER, /* normal color id */ GX_COLOR_ID_BTN_UPPER, /* selected color id */ gx_studio_icon_button_create, /* create function */ GX_NULL, /* drawing function override */ GX_NULL, /* event function override */ {229, 386, 252, 409}, /* widget size */ &button_screen_button_label_1_define, /* next widget definition */ GX_NULL, /* no child widgets */ offsetof(BUTTON_SCREEN_CONTROL_BLOCK, button_screen_icon_button_6), /* control block */ (void *) &button_screen_icon_button_6_properties /* extended properties */ }; GX_CONST GX_STUDIO_WIDGET button_screen_icon_define = { "icon", GX_TYPE_ICON, /* widget type */ ID_ICON, /* widget id */ GX_STYLE_BORDER_NONE|GX_STYLE_TRANSPARENT|GX_STYLE_ENABLED|GX_STYLE_HALIGN_LEFT|GX_STYLE_VALIGN_TOP, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(GX_ICON), /* control block size */ GX_COLOR_ID_WIDGET_FILL, /* normal color id */ GX_COLOR_ID_SELECTED_FILL, /* selected color id */ gx_studio_icon_create, /* create function */ GX_NULL, /* drawing function override */ GX_NULL, /* event function override */ {221, 416, 258, 453}, /* widget size */ &button_screen_icon_button_6_define, /* next widget definition */ GX_NULL, /* no child widgets */ offsetof(BUTTON_SCREEN_CONTROL_BLOCK, button_screen_icon), /* control block */ (void *) &button_screen_icon_properties /* extended properties */ }; GX_CONST GX_STUDIO_WIDGET button_screen_pixelmap_button1_define = { "pixelmap_button1", GX_TYPE_PIXELMAP_BUTTON, /* widget type */ ID_PIXELMAP_BUTTON, /* widget id */ GX_STYLE_BORDER_NONE|GX_STYLE_ENABLED|GX_STYLE_HALIGN_CENTER|GX_STYLE_VALIGN_CENTER, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(GX_PIXELMAP_BUTTON), /* control block size */ GX_COLOR_ID_BTN_LOWER, /* normal color id */ GX_COLOR_ID_BTN_UPPER, /* selected color id */ gx_studio_pixelmap_button_create, /* create function */ GX_NULL, /* drawing function override */ GX_NULL, /* event function override */ {131, 251, 252, 313}, /* widget size */ &button_screen_icon_define, /* next widget definition */ GX_NULL, /* no child widgets */ offsetof(BUTTON_SCREEN_CONTROL_BLOCK, button_screen_pixelmap_button1), /* control block */ (void *) &button_screen_pixelmap_button1_properties /* extended properties */ }; GX_CONST GX_STUDIO_WIDGET button_screen_radio_button1_define = { "radio_button1", GX_TYPE_RADIO_BUTTON, /* widget type */ ID_RADIO_BUTTON, /* widget id */ GX_STYLE_BORDER_NONE|GX_STYLE_TRANSPARENT|GX_STYLE_ENABLED|GX_STYLE_BUTTON_RADIO|GX_STYLE_TEXT_LEFT, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(GX_RADIO_BUTTON), /* control block size */ GX_COLOR_ID_BTN_LOWER, /* normal color id */ GX_COLOR_ID_BTN_UPPER, /* selected color id */ gx_studio_radio_button_create, /* create function */ GX_NULL, /* drawing function override */ GX_NULL, /* event function override */ {125, 356, 252, 379}, /* widget size */ &button_screen_pixelmap_button1_define, /* next widget definition */ GX_NULL, /* no child widgets */ offsetof(BUTTON_SCREEN_CONTROL_BLOCK, button_screen_radio_button1), /* control block */ (void *) &button_screen_radio_button1_properties /* extended properties */ }; GX_CONST GX_STUDIO_WIDGET button_screen_checkbox_define = { "checkbox", GX_TYPE_CHECKBOX, /* widget type */ ID_CHECKBOX, /* widget id */ GX_STYLE_BORDER_NONE|GX_STYLE_TRANSPARENT|GX_STYLE_ENABLED|GX_STYLE_BUTTON_TOGGLE|GX_STYLE_TEXT_LEFT, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(GX_CHECKBOX), /* control block size */ GX_COLOR_ID_BTN_LOWER, /* normal color id */ GX_COLOR_ID_BTN_UPPER, /* selected color id */ gx_studio_checkbox_create, /* create function */ GX_NULL, /* drawing function override */ GX_NULL, /* event function override */ {150, 320, 252, 349}, /* widget size */ &button_screen_radio_button1_define, /* next widget definition */ GX_NULL, /* no child widgets */ offsetof(BUTTON_SCREEN_CONTROL_BLOCK, button_screen_checkbox), /* control block */ (void *) &button_screen_checkbox_properties /* extended properties */ }; GX_CONST GX_STUDIO_WIDGET button_screen_text_button_1_define = { "text_button_1", GX_TYPE_TEXT_BUTTON, /* widget type */ ID_TEXT_BUTTON, /* widget id */ GX_STYLE_BORDER_RAISED|GX_STYLE_ENABLED|GX_STYLE_TEXT_CENTER, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(GX_TEXT_BUTTON), /* control block size */ GX_COLOR_ID_BTN_LOWER, /* normal color id */ GX_COLOR_ID_BTN_UPPER, /* selected color id */ gx_studio_text_button_create, /* create function */ GX_NULL, /* drawing function override */ GX_NULL, /* event function override */ {117, 140, 252, 169}, /* widget size */ &button_screen_checkbox_define, /* next widget definition */ GX_NULL, /* no child widgets */ offsetof(BUTTON_SCREEN_CONTROL_BLOCK, button_screen_text_button_1), /* control block */ (void *) &button_screen_text_button_1_properties /* extended properties */ }; GX_CONST GX_STUDIO_WIDGET button_screen_base_button_1_define = { "base_button_1", GX_TYPE_BUTTON, /* widget type */ GX_ID_NONE, /* widget id */ GX_STYLE_BORDER_RAISED|GX_STYLE_ENABLED, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(GX_BUTTON), /* control block size */ GX_COLOR_ID_BTN_LOWER, /* normal color id */ GX_COLOR_ID_BTN_UPPER, /* selected color id */ gx_studio_button_create, /* create function */ GX_NULL, /* drawing function override */ GX_NULL, /* event function override */ {117, 100, 252, 133}, /* widget size */ &button_screen_text_button_1_define, /* next widget definition */ GX_NULL, /* no child widgets */ offsetof(BUTTON_SCREEN_CONTROL_BLOCK, button_screen_base_button_1), /* control block */ (void *) GX_NULL /* no extended properties */ }; GX_CONST GX_STUDIO_WIDGET button_screen_title_1_define = { "title_1", GX_TYPE_PROMPT, /* widget type */ GX_ID_NONE, /* widget id */ GX_STYLE_BORDER_THICK|GX_STYLE_TRANSPARENT|GX_STYLE_TEXT_CENTER, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(GX_PROMPT), /* control block size */ GX_COLOR_ID_WIDGET_FILL, /* normal color id */ GX_COLOR_ID_SELECTED_FILL, /* selected color id */ gx_studio_prompt_create, /* create function */ GX_NULL, /* drawing function override */ GX_NULL, /* event function override */ {179, 30, 442, 71}, /* widget size */ &button_screen_base_button_1_define, /* next widget definition */ GX_NULL, /* no child widgets */ offsetof(BUTTON_SCREEN_CONTROL_BLOCK, button_screen_title_1), /* control block */ (void *) &button_screen_title_1_properties /* extended properties */ }; GX_CONST GX_STUDIO_WIDGET button_screen_define = { "button_screen", GX_TYPE_WINDOW, /* widget type */ ID_BUTTON_SCREEN, /* widget id */ GX_STYLE_BORDER_THICK, /* style flags */ GX_STATUS_ACCEPTS_FOCUS, /* status flags */ sizeof(BUTTON_SCREEN_CONTROL_BLOCK), /* control block size */ GX_COLOR_ID_WINDOW_FILL, /* normal color id */ GX_COLOR_ID_WINDOW_FILL, /* selected color id */ gx_studio_window_create, /* create function */ GX_NULL, /* drawing function override */ (UINT (*)(GX_WIDGET *, GX_EVENT *)) buttons_handler, /* event function override */ {73, 7, 575, 475}, /* widget size */ GX_NULL, /* next widget */ &button_screen_title_1_define, /* child widget */ 0, /* control block */ (void *) &button_screen_properties /* extended properties */ }; GX_CONST GX_STUDIO_WIDGET_ENTRY all_widgets_5_2_5_widget_table[] = { { &sprite_screen_define, (GX_WIDGET *) &sprite_screen }, { &indicator_screen_define, (GX_WIDGET *) &indicator_screen }, { &text_screen_define, (GX_WIDGET *) &text_screen }, { &window_screen_define, (GX_WIDGET *) &window_screen }, { &button_screen_define, (GX_WIDGET *) &button_screen }, {GX_NULL, GX_NULL} }; GX_WIDGET *gx_studio_widget_create(GX_BYTE *control, GX_CONST GX_STUDIO_WIDGET *definition, GX_WIDGET *parent) { UINT status = GX_SUCCESS; GX_WIDGET *widget = GX_NULL; while(definition && status == GX_SUCCESS) { if (definition->create_function) { if (definition->style & GX_STYLE_DYNAMICALLY_ALLOCATED) { status = gx_widget_allocate(&widget, definition->control_block_size); if (status != GX_SUCCESS) { return GX_NULL; } } else { if(!control) { return GX_NULL; } widget = (GX_WIDGET *) (control + definition->control_block_offset); } status = definition->create_function(definition, widget, parent); if (status == GX_SUCCESS) { gx_widget_fill_color_set(widget, definition->normal_fill_color_id, definition->selected_fill_color_id); if (!(definition->status & GX_STATUS_ACCEPTS_FOCUS)) { gx_widget_status_remove(widget, GX_STATUS_ACCEPTS_FOCUS); } if (definition->draw_function) { gx_widget_draw_set(widget, definition->draw_function); } if (definition->event_function) { gx_widget_event_process_set(widget, definition->event_function); } if (definition->child_widget) { gx_studio_widget_create(control, definition->child_widget, widget); } } definition = definition->next_widget; } } return widget; } UINT gx_studio_named_widget_create(char *name, GX_WIDGET *parent, GX_WIDGET **new_widget) { UINT status = GX_FAILURE; GX_CONST GX_STUDIO_WIDGET_ENTRY *entry = all_widgets_5_2_5_widget_table; GX_WIDGET *widget = GX_NULL; while(entry->widget_information) { if (!strcmp(name, entry->widget_information->widget_name)) { widget = gx_studio_widget_create((GX_BYTE *) entry->widget, entry->widget_information, parent); if (widget) { status = GX_SUCCESS; } break; } entry++; } if (new_widget) { *new_widget = widget; } return status; } UINT gx_studio_display_configure(USHORT display, UINT (*driver)(GX_DISPLAY *), USHORT language, USHORT theme, GX_WINDOW_ROOT **return_root) { GX_CONST GX_THEME *theme_ptr; GX_RECTANGLE size; GX_STUDIO_DISPLAY_INFO *display_info = &all_widgets_5_2_5_display_table[display]; /* create the requested display */ gx_display_create(display_info->display, display_info->name, driver, (GX_VALUE) display_info->x_resolution, (GX_VALUE) display_info->y_resolution); /* install the request theme */ if(display_info->theme_table) { theme_ptr = display_info->theme_table[theme]; if(theme_ptr) { gx_display_color_table_set(display_info->display, theme_ptr->theme_color_table, theme_ptr->theme_color_table_size); /* install the color palette if required */ if (display_info->display->gx_display_driver_palette_set && theme_ptr->theme_palette != NULL) { display_info->display->gx_display_driver_palette_set(display_info->display, theme_ptr->theme_palette, theme_ptr->theme_palette_size); } gx_display_font_table_set(display_info->display, theme_ptr->theme_font_table, theme_ptr->theme_font_table_size); gx_display_pixelmap_table_set(display_info->display, theme_ptr->theme_pixelmap_table, theme_ptr->theme_pixelmap_table_size); gx_system_scroll_appearance_set(theme_ptr->theme_vertical_scroll_style, (GX_SCROLLBAR_APPEARANCE *) &theme_ptr->theme_vertical_scrollbar_appearance); gx_system_scroll_appearance_set(theme_ptr->theme_horizontal_scroll_style, (GX_SCROLLBAR_APPEARANCE *) &theme_ptr->theme_horizontal_scrollbar_appearance); } } /* Install the language table. */ if(display_info->language_table) { gx_system_language_table_set((GX_CHAR ***) display_info->language_table, display_info->language_table_size, display_info->string_table_size); gx_system_active_language_set(language); } /* create the canvas for this display */ gx_canvas_create(display_info->canvas, display_info->canvas_name, display_info->display, GX_CANVAS_MANAGED | GX_CANVAS_VISIBLE, display_info->x_resolution, display_info->y_resolution, display_info->canvas_memory, display_info->canvas_memory_size); /* Create the root window for this canvas */ gx_utility_rectangle_define(&size, 0, 0, (GX_VALUE) (display_info->x_resolution - 1), (GX_VALUE) (display_info->y_resolution - 1)); gx_window_root_create(display_info->root_window, display_info->name, display_info->canvas, GX_STYLE_NONE, 0, &size); if (return_root) { *return_root = display_info->root_window; } return GX_SUCCESS; } #undef GUIX_STUDIO_GENERATED_FILE
0
0.938991
1
0.938991
game-dev
MEDIA
0.403253
game-dev
0.855186
1
0.855186
defold/defold
19,195
external/box2d/Box2D/include/box2d/math_functions.h
// SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #pragma once #include "base.h" #include <float.h> #include <math.h> #include <stdbool.h> /** * @defgroup math Math * @brief Vector math types and functions * @{ */ /// 2D vector /// This can be used to represent a point or free vector typedef struct b2Vec2 { /// coordinates float x, y; } b2Vec2; /// Cosine and sine pair /// This uses a custom implementation designed for cross-platform determinism typedef struct b2CosSin { /// cosine and sine float cosine; float sine; } b2CosSin; /// 2D rotation /// This is similar to using a complex number for rotation typedef struct b2Rot { /// cosine and sine float c, s; } b2Rot; /// A 2D rigid transform typedef struct b2Transform { b2Vec2 p; b2Rot q; } b2Transform; /// A 2-by-2 Matrix typedef struct b2Mat22 { /// columns b2Vec2 cx, cy; } b2Mat22; /// Axis-aligned bounding box typedef struct b2AABB { b2Vec2 lowerBound; b2Vec2 upperBound; } b2AABB; /// separation = dot(normal, point) - offset typedef struct b2Plane { b2Vec2 normal; float offset; } b2Plane; /**@}*/ /** * @addtogroup math * @{ */ /// https://en.wikipedia.org/wiki/Pi #define B2_PI 3.14159265359f static const b2Vec2 b2Vec2_zero = { 0.0f, 0.0f }; static const b2Rot b2Rot_identity = { 1.0f, 0.0f }; static const b2Transform b2Transform_identity = { { 0.0f, 0.0f }, { 1.0f, 0.0f } }; static const b2Mat22 b2Mat22_zero = { { 0.0f, 0.0f }, { 0.0f, 0.0f } }; /// @return the minimum of two integers B2_INLINE int b2MinInt( int a, int b ) { return a < b ? a : b; } /// @return the maximum of two integers B2_INLINE int b2MaxInt( int a, int b ) { return a > b ? a : b; } /// @return the absolute value of an integer B2_INLINE int b2AbsInt( int a ) { return a < 0 ? -a : a; } /// @return an integer clamped between a lower and upper bound B2_INLINE int b2ClampInt( int a, int lower, int upper ) { return a < lower ? lower : ( a > upper ? upper : a ); } /// @return the minimum of two floats B2_INLINE float b2MinFloat( float a, float b ) { return a < b ? a : b; } /// @return the maximum of two floats B2_INLINE float b2MaxFloat( float a, float b ) { return a > b ? a : b; } /// @return the absolute value of a float B2_INLINE float b2AbsFloat( float a ) { return a < 0 ? -a : a; } /// @return a float clamped between a lower and upper bound B2_INLINE float b2ClampFloat( float a, float lower, float upper ) { return a < lower ? lower : ( a > upper ? upper : a ); } /// Compute an approximate arctangent in the range [-pi, pi] /// This is hand coded for cross-platform determinism. The atan2f /// function in the standard library is not cross-platform deterministic. /// Accurate to around 0.0023 degrees B2_API float b2Atan2( float y, float x ); /// Compute the cosine and sine of an angle in radians. Implemented /// for cross-platform determinism. B2_API b2CosSin b2ComputeCosSin( float radians ); /// Vector dot product B2_INLINE float b2Dot( b2Vec2 a, b2Vec2 b ) { return a.x * b.x + a.y * b.y; } /// Vector cross product. In 2D this yields a scalar. B2_INLINE float b2Cross( b2Vec2 a, b2Vec2 b ) { return a.x * b.y - a.y * b.x; } /// Perform the cross product on a vector and a scalar. In 2D this produces a vector. B2_INLINE b2Vec2 b2CrossVS( b2Vec2 v, float s ) { return B2_LITERAL( b2Vec2 ){ s * v.y, -s * v.x }; } /// Perform the cross product on a scalar and a vector. In 2D this produces a vector. B2_INLINE b2Vec2 b2CrossSV( float s, b2Vec2 v ) { return B2_LITERAL( b2Vec2 ){ -s * v.y, s * v.x }; } /// Get a left pointing perpendicular vector. Equivalent to b2CrossSV(1.0f, v) B2_INLINE b2Vec2 b2LeftPerp( b2Vec2 v ) { return B2_LITERAL( b2Vec2 ){ -v.y, v.x }; } /// Get a right pointing perpendicular vector. Equivalent to b2CrossVS(v, 1.0f) B2_INLINE b2Vec2 b2RightPerp( b2Vec2 v ) { return B2_LITERAL( b2Vec2 ){ v.y, -v.x }; } /// Vector addition B2_INLINE b2Vec2 b2Add( b2Vec2 a, b2Vec2 b ) { return B2_LITERAL( b2Vec2 ){ a.x + b.x, a.y + b.y }; } /// Vector subtraction B2_INLINE b2Vec2 b2Sub( b2Vec2 a, b2Vec2 b ) { return B2_LITERAL( b2Vec2 ){ a.x - b.x, a.y - b.y }; } /// Vector negation B2_INLINE b2Vec2 b2Neg( b2Vec2 a ) { return B2_LITERAL( b2Vec2 ){ -a.x, -a.y }; } /// Vector linear interpolation /// https://fgiesen.wordpress.com/2012/08/15/linear-interpolation-past-present-and-future/ B2_INLINE b2Vec2 b2Lerp( b2Vec2 a, b2Vec2 b, float t ) { return B2_LITERAL( b2Vec2 ){ ( 1.0f - t ) * a.x + t * b.x, ( 1.0f - t ) * a.y + t * b.y }; } /// Component-wise multiplication B2_INLINE b2Vec2 b2Mul( b2Vec2 a, b2Vec2 b ) { return B2_LITERAL( b2Vec2 ){ a.x * b.x, a.y * b.y }; } /// Multiply a scalar and vector B2_INLINE b2Vec2 b2MulSV( float s, b2Vec2 v ) { return B2_LITERAL( b2Vec2 ){ s * v.x, s * v.y }; } /// a + s * b B2_INLINE b2Vec2 b2MulAdd( b2Vec2 a, float s, b2Vec2 b ) { return B2_LITERAL( b2Vec2 ){ a.x + s * b.x, a.y + s * b.y }; } /// a - s * b B2_INLINE b2Vec2 b2MulSub( b2Vec2 a, float s, b2Vec2 b ) { return B2_LITERAL( b2Vec2 ){ a.x - s * b.x, a.y - s * b.y }; } /// Component-wise absolute vector B2_INLINE b2Vec2 b2Abs( b2Vec2 a ) { b2Vec2 b; b.x = b2AbsFloat( a.x ); b.y = b2AbsFloat( a.y ); return b; } /// Component-wise minimum vector B2_INLINE b2Vec2 b2Min( b2Vec2 a, b2Vec2 b ) { b2Vec2 c; c.x = b2MinFloat( a.x, b.x ); c.y = b2MinFloat( a.y, b.y ); return c; } /// Component-wise maximum vector B2_INLINE b2Vec2 b2Max( b2Vec2 a, b2Vec2 b ) { b2Vec2 c; c.x = b2MaxFloat( a.x, b.x ); c.y = b2MaxFloat( a.y, b.y ); return c; } /// Component-wise clamp vector v into the range [a, b] B2_INLINE b2Vec2 b2Clamp( b2Vec2 v, b2Vec2 a, b2Vec2 b ) { b2Vec2 c; c.x = b2ClampFloat( v.x, a.x, b.x ); c.y = b2ClampFloat( v.y, a.y, b.y ); return c; } /// Get the length of this vector (the norm) B2_INLINE float b2Length( b2Vec2 v ) { return sqrtf( v.x * v.x + v.y * v.y ); } /// Get the distance between two points B2_INLINE float b2Distance( b2Vec2 a, b2Vec2 b ) { float dx = b.x - a.x; float dy = b.y - a.y; return sqrtf( dx * dx + dy * dy ); } /// Convert a vector into a unit vector if possible, otherwise returns the zero vector. /// todo MSVC is not inlining this function in several places per warning 4710 B2_INLINE b2Vec2 b2Normalize( b2Vec2 v ) { float length = sqrtf( v.x * v.x + v.y * v.y ); if ( length < FLT_EPSILON ) { return B2_LITERAL( b2Vec2 ){ 0.0f, 0.0f }; } float invLength = 1.0f / length; b2Vec2 n = { invLength * v.x, invLength * v.y }; return n; } /// Determines if the provided vector is normalized (norm(a) == 1). B2_INLINE bool b2IsNormalized( b2Vec2 a ) { float aa = b2Dot( a, a ); return b2AbsFloat( 1.0f - aa ) < 10.0f * FLT_EPSILON; } /// Convert a vector into a unit vector if possible, otherwise returns the zero vector. Also /// outputs the length. B2_INLINE b2Vec2 b2GetLengthAndNormalize( float* length, b2Vec2 v ) { *length = sqrtf( v.x * v.x + v.y * v.y ); if ( *length < FLT_EPSILON ) { return B2_LITERAL( b2Vec2 ){ 0.0f, 0.0f }; } float invLength = 1.0f / *length; b2Vec2 n = { invLength * v.x, invLength * v.y }; return n; } /// Normalize rotation B2_INLINE b2Rot b2NormalizeRot( b2Rot q ) { float mag = sqrtf( q.s * q.s + q.c * q.c ); float invMag = mag > 0.0 ? 1.0f / mag : 0.0f; b2Rot qn = { q.c * invMag, q.s * invMag }; return qn; } /// Integrate rotation from angular velocity /// @param q1 initial rotation /// @param deltaAngle the angular displacement in radians B2_INLINE b2Rot b2IntegrateRotation( b2Rot q1, float deltaAngle ) { // dc/dt = -omega * sin(t) // ds/dt = omega * cos(t) // c2 = c1 - omega * h * s1 // s2 = s1 + omega * h * c1 b2Rot q2 = { q1.c - deltaAngle * q1.s, q1.s + deltaAngle * q1.c }; float mag = sqrtf( q2.s * q2.s + q2.c * q2.c ); float invMag = mag > 0.0 ? 1.0f / mag : 0.0f; b2Rot qn = { q2.c * invMag, q2.s * invMag }; return qn; } /// Get the length squared of this vector B2_INLINE float b2LengthSquared( b2Vec2 v ) { return v.x * v.x + v.y * v.y; } /// Get the distance squared between points B2_INLINE float b2DistanceSquared( b2Vec2 a, b2Vec2 b ) { b2Vec2 c = { b.x - a.x, b.y - a.y }; return c.x * c.x + c.y * c.y; } /// Make a rotation using an angle in radians B2_INLINE b2Rot b2MakeRot( float radians ) { b2CosSin cs = b2ComputeCosSin( radians ); return B2_LITERAL( b2Rot ){ cs.cosine, cs.sine }; } /// Compute the rotation between two unit vectors B2_API b2Rot b2ComputeRotationBetweenUnitVectors( b2Vec2 v1, b2Vec2 v2 ); /// Is this rotation normalized? B2_INLINE bool b2IsNormalizedRot( b2Rot q ) { // larger tolerance due to failure on mingw 32-bit float qq = q.s * q.s + q.c * q.c; return 1.0f - 0.0006f < qq && qq < 1.0f + 0.0006f; } /// Normalized linear interpolation /// https://fgiesen.wordpress.com/2012/08/15/linear-interpolation-past-present-and-future/ /// https://web.archive.org/web/20170825184056/http://number-none.com/product/Understanding%20Slerp,%20Then%20Not%20Using%20It/ B2_INLINE b2Rot b2NLerp( b2Rot q1, b2Rot q2, float t ) { float omt = 1.0f - t; b2Rot q = { omt * q1.c + t * q2.c, omt * q1.s + t * q2.s, }; float mag = sqrtf( q.s * q.s + q.c * q.c ); float invMag = mag > 0.0 ? 1.0f / mag : 0.0f; b2Rot qn = { q.c * invMag, q.s * invMag }; return qn; } /// Compute the angular velocity necessary to rotate between two rotations over a give time /// @param q1 initial rotation /// @param q2 final rotation /// @param inv_h inverse time step B2_INLINE float b2ComputeAngularVelocity( b2Rot q1, b2Rot q2, float inv_h ) { // ds/dt = omega * cos(t) // dc/dt = -omega * sin(t) // s2 = s1 + omega * h * c1 // c2 = c1 - omega * h * s1 // omega * h * s1 = c1 - c2 // omega * h * c1 = s2 - s1 // omega * h = (c1 - c2) * s1 + (s2 - s1) * c1; // omega * h = s1 * c1 - c2 * s1 + s2 * c1 - s1 * c1 // omega * h = s2 * c1 - c2 * s1 = sin(a2 - a1) ~= a2 - a1 for small delta float omega = inv_h * ( q2.s * q1.c - q2.c * q1.s ); return omega; } /// Get the angle in radians in the range [-pi, pi] B2_INLINE float b2Rot_GetAngle( b2Rot q ) { return b2Atan2( q.s, q.c ); } /// Get the x-axis B2_INLINE b2Vec2 b2Rot_GetXAxis( b2Rot q ) { b2Vec2 v = { q.c, q.s }; return v; } /// Get the y-axis B2_INLINE b2Vec2 b2Rot_GetYAxis( b2Rot q ) { b2Vec2 v = { -q.s, q.c }; return v; } /// Multiply two rotations: q * r B2_INLINE b2Rot b2MulRot( b2Rot q, b2Rot r ) { // [qc -qs] * [rc -rs] = [qc*rc-qs*rs -qc*rs-qs*rc] // [qs qc] [rs rc] [qs*rc+qc*rs -qs*rs+qc*rc] // s(q + r) = qs * rc + qc * rs // c(q + r) = qc * rc - qs * rs b2Rot qr; qr.s = q.s * r.c + q.c * r.s; qr.c = q.c * r.c - q.s * r.s; return qr; } /// Transpose multiply two rotations: qT * r B2_INLINE b2Rot b2InvMulRot( b2Rot q, b2Rot r ) { // [ qc qs] * [rc -rs] = [qc*rc+qs*rs -qc*rs+qs*rc] // [-qs qc] [rs rc] [-qs*rc+qc*rs qs*rs+qc*rc] // s(q - r) = qc * rs - qs * rc // c(q - r) = qc * rc + qs * rs b2Rot qr; qr.s = q.c * r.s - q.s * r.c; qr.c = q.c * r.c + q.s * r.s; return qr; } /// relative angle between b and a (rot_b * inv(rot_a)) B2_INLINE float b2RelativeAngle( b2Rot b, b2Rot a ) { // sin(b - a) = bs * ac - bc * as // cos(b - a) = bc * ac + bs * as float s = b.s * a.c - b.c * a.s; float c = b.c * a.c + b.s * a.s; return b2Atan2( s, c ); } /// Convert an angle in the range [-2*pi, 2*pi] into the range [-pi, pi] B2_INLINE float b2UnwindAngle( float radians ) { if ( radians < -B2_PI ) { return radians + 2.0f * B2_PI; } else if ( radians > B2_PI ) { return radians - 2.0f * B2_PI; } return radians; } /// Convert any into the range [-pi, pi] (slow) B2_INLINE float b2UnwindLargeAngle( float radians ) { while ( radians > B2_PI ) { radians -= 2.0f * B2_PI; } while ( radians < -B2_PI ) { radians += 2.0f * B2_PI; } return radians; } /// Rotate a vector B2_INLINE b2Vec2 b2RotateVector( b2Rot q, b2Vec2 v ) { return B2_LITERAL( b2Vec2 ){ q.c * v.x - q.s * v.y, q.s * v.x + q.c * v.y }; } /// Inverse rotate a vector B2_INLINE b2Vec2 b2InvRotateVector( b2Rot q, b2Vec2 v ) { return B2_LITERAL( b2Vec2 ){ q.c * v.x + q.s * v.y, -q.s * v.x + q.c * v.y }; } /// Transform a point (e.g. local space to world space) B2_INLINE b2Vec2 b2TransformPoint( b2Transform t, const b2Vec2 p ) { float x = ( t.q.c * p.x - t.q.s * p.y ) + t.p.x; float y = ( t.q.s * p.x + t.q.c * p.y ) + t.p.y; return B2_LITERAL( b2Vec2 ){ x, y }; } /// Inverse transform a point (e.g. world space to local space) B2_INLINE b2Vec2 b2InvTransformPoint( b2Transform t, const b2Vec2 p ) { float vx = p.x - t.p.x; float vy = p.y - t.p.y; return B2_LITERAL( b2Vec2 ){ t.q.c * vx + t.q.s * vy, -t.q.s * vx + t.q.c * vy }; } /// Multiply two transforms. If the result is applied to a point p local to frame B, /// the transform would first convert p to a point local to frame A, then into a point /// in the world frame. /// v2 = A.q.Rot(B.q.Rot(v1) + B.p) + A.p /// = (A.q * B.q).Rot(v1) + A.q.Rot(B.p) + A.p B2_INLINE b2Transform b2MulTransforms( b2Transform A, b2Transform B ) { b2Transform C; C.q = b2MulRot( A.q, B.q ); C.p = b2Add( b2RotateVector( A.q, B.p ), A.p ); return C; } /// Creates a transform that converts a local point in frame B to a local point in frame A. /// v2 = A.q' * (B.q * v1 + B.p - A.p) /// = A.q' * B.q * v1 + A.q' * (B.p - A.p) B2_INLINE b2Transform b2InvMulTransforms( b2Transform A, b2Transform B ) { b2Transform C; C.q = b2InvMulRot( A.q, B.q ); C.p = b2InvRotateVector( A.q, b2Sub( B.p, A.p ) ); return C; } /// Multiply a 2-by-2 matrix times a 2D vector B2_INLINE b2Vec2 b2MulMV( b2Mat22 A, b2Vec2 v ) { b2Vec2 u = { A.cx.x * v.x + A.cy.x * v.y, A.cx.y * v.x + A.cy.y * v.y, }; return u; } /// Get the inverse of a 2-by-2 matrix B2_INLINE b2Mat22 b2GetInverse22( b2Mat22 A ) { float a = A.cx.x, b = A.cy.x, c = A.cx.y, d = A.cy.y; float det = a * d - b * c; if ( det != 0.0f ) { det = 1.0f / det; } b2Mat22 B = { { det * d, -det * c }, { -det * b, det * a }, }; return B; } /// Solve A * x = b, where b is a column vector. This is more efficient /// than computing the inverse in one-shot cases. B2_INLINE b2Vec2 b2Solve22( b2Mat22 A, b2Vec2 b ) { float a11 = A.cx.x, a12 = A.cy.x, a21 = A.cx.y, a22 = A.cy.y; float det = a11 * a22 - a12 * a21; if ( det != 0.0f ) { det = 1.0f / det; } b2Vec2 x = { det * ( a22 * b.x - a12 * b.y ), det * ( a11 * b.y - a21 * b.x ) }; return x; } /// Does a fully contain b B2_INLINE bool b2AABB_Contains( b2AABB a, b2AABB b ) { bool s = true; s = s && a.lowerBound.x <= b.lowerBound.x; s = s && a.lowerBound.y <= b.lowerBound.y; s = s && b.upperBound.x <= a.upperBound.x; s = s && b.upperBound.y <= a.upperBound.y; return s; } /// Get the center of the AABB. B2_INLINE b2Vec2 b2AABB_Center( b2AABB a ) { b2Vec2 b = { 0.5f * ( a.lowerBound.x + a.upperBound.x ), 0.5f * ( a.lowerBound.y + a.upperBound.y ) }; return b; } /// Get the extents of the AABB (half-widths). B2_INLINE b2Vec2 b2AABB_Extents( b2AABB a ) { b2Vec2 b = { 0.5f * ( a.upperBound.x - a.lowerBound.x ), 0.5f * ( a.upperBound.y - a.lowerBound.y ) }; return b; } /// Union of two AABBs B2_INLINE b2AABB b2AABB_Union( b2AABB a, b2AABB b ) { b2AABB c; c.lowerBound.x = b2MinFloat( a.lowerBound.x, b.lowerBound.x ); c.lowerBound.y = b2MinFloat( a.lowerBound.y, b.lowerBound.y ); c.upperBound.x = b2MaxFloat( a.upperBound.x, b.upperBound.x ); c.upperBound.y = b2MaxFloat( a.upperBound.y, b.upperBound.y ); return c; } /// Compute the bounding box of an array of circles B2_INLINE b2AABB b2MakeAABB( const b2Vec2* points, int count, float radius ) { B2_ASSERT( count > 0 ); b2AABB a = { points[0], points[0] }; for ( int i = 1; i < count; ++i ) { a.lowerBound = b2Min( a.lowerBound, points[i] ); a.upperBound = b2Max( a.upperBound, points[i] ); } b2Vec2 r = { radius, radius }; a.lowerBound = b2Sub( a.lowerBound, r ); a.upperBound = b2Add( a.upperBound, r ); return a; } /// Signed separation of a point from a plane B2_INLINE float b2PlaneSeparation( b2Plane plane, b2Vec2 point ) { return b2Dot( plane.normal, point ) - plane.offset; } /// Is this a valid number? Not NaN or infinity. B2_API bool b2IsValidFloat( float a ); /// Is this a valid vector? Not NaN or infinity. B2_API bool b2IsValidVec2( b2Vec2 v ); /// Is this a valid rotation? Not NaN or infinity. Is normalized. B2_API bool b2IsValidRotation( b2Rot q ); /// Is this a valid bounding box? Not Nan or infinity. Upper bound greater than or equal to lower bound. B2_API bool b2IsValidAABB( b2AABB aabb ); /// Is this a valid plane? Normal is a unit vector. Not Nan or infinity. B2_API bool b2IsValidPlane( b2Plane a ); /// Box2D bases all length units on meters, but you may need different units for your game. /// You can set this value to use different units. This should be done at application startup /// and only modified once. Default value is 1. /// For example, if your game uses pixels for units you can use pixels for all length values /// sent to Box2D. There should be no extra cost. However, Box2D has some internal tolerances /// and thresholds that have been tuned for meters. By calling this function, Box2D is able /// to adjust those tolerances and thresholds to improve accuracy. /// A good rule of thumb is to pass the height of your player character to this function. So /// if your player character is 32 pixels high, then pass 32 to this function. Then you may /// confidently use pixels for all the length values sent to Box2D. All length values returned /// from Box2D will also be pixels because Box2D does not do any scaling internally. /// However, you are now on the hook for coming up with good values for gravity, density, and /// forces. /// @warning This must be modified before any calls to Box2D B2_API void b2SetLengthUnitsPerMeter( float lengthUnits ); /// Get the current length units per meter. B2_API float b2GetLengthUnitsPerMeter( void ); /**@}*/ /** * @defgroup math_cpp C++ Math * @brief Math operator overloads for C++ * * See math_functions.h for details. * @{ */ #ifdef __cplusplus /// Unary add one vector to another inline void operator+=( b2Vec2& a, b2Vec2 b ) { a.x += b.x; a.y += b.y; } /// Unary subtract one vector from another inline void operator-=( b2Vec2& a, b2Vec2 b ) { a.x -= b.x; a.y -= b.y; } /// Unary multiply a vector by a scalar inline void operator*=( b2Vec2& a, float b ) { a.x *= b; a.y *= b; } /// Unary negate a vector inline b2Vec2 operator-( b2Vec2 a ) { return { -a.x, -a.y }; } /// Binary vector addition inline b2Vec2 operator+( b2Vec2 a, b2Vec2 b ) { return { a.x + b.x, a.y + b.y }; } /// Binary vector subtraction inline b2Vec2 operator-( b2Vec2 a, b2Vec2 b ) { return { a.x - b.x, a.y - b.y }; } /// Binary scalar and vector multiplication inline b2Vec2 operator*( float a, b2Vec2 b ) { return { a * b.x, a * b.y }; } /// Binary scalar and vector multiplication inline b2Vec2 operator*( b2Vec2 a, float b ) { return { a.x * b, a.y * b }; } /// Binary vector equality inline bool operator==( b2Vec2 a, b2Vec2 b ) { return a.x == b.x && a.y == b.y; } /// Binary vector inequality inline bool operator!=( b2Vec2 a, b2Vec2 b ) { return a.x != b.x || a.y != b.y; } #endif /**@}*/
0
0.831317
1
0.831317
game-dev
MEDIA
0.785468
game-dev
0.922088
1
0.922088
LessonStudio/Arduino_BLE_iOS_CPP
91,257
iOS_Example/cocos2d/external/bullet/BulletSoftBody/btSoftBody.cpp
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ ///btSoftBody implementation by Nathanael Presson #include "btSoftBodyInternals.h" #include "BulletSoftBody/btSoftBodySolvers.h" #include "btSoftBodyData.h" #include "LinearMath/btSerializer.h" // btSoftBody::btSoftBody(btSoftBodyWorldInfo* worldInfo,int node_count, const btVector3* x, const btScalar* m) :m_softBodySolver(0),m_worldInfo(worldInfo) { /* Init */ initDefaults(); /* Default material */ Material* pm=appendMaterial(); pm->m_kLST = 1; pm->m_kAST = 1; pm->m_kVST = 1; pm->m_flags = fMaterial::Default; /* Nodes */ const btScalar margin=getCollisionShape()->getMargin(); m_nodes.resize(node_count); for(int i=0,ni=node_count;i<ni;++i) { Node& n=m_nodes[i]; ZeroInitialize(n); n.m_x = x?*x++:btVector3(0,0,0); n.m_q = n.m_x; n.m_im = m?*m++:1; n.m_im = n.m_im>0?1/n.m_im:0; n.m_leaf = m_ndbvt.insert(btDbvtVolume::FromCR(n.m_x,margin),&n); n.m_material= pm; } updateBounds(); } btSoftBody::btSoftBody(btSoftBodyWorldInfo* worldInfo) :m_worldInfo(worldInfo) { initDefaults(); } void btSoftBody::initDefaults() { m_internalType = CO_SOFT_BODY; m_cfg.aeromodel = eAeroModel::V_Point; m_cfg.kVCF = 1; m_cfg.kDG = 0; m_cfg.kLF = 0; m_cfg.kDP = 0; m_cfg.kPR = 0; m_cfg.kVC = 0; m_cfg.kDF = (btScalar)0.2; m_cfg.kMT = 0; m_cfg.kCHR = (btScalar)1.0; m_cfg.kKHR = (btScalar)0.1; m_cfg.kSHR = (btScalar)1.0; m_cfg.kAHR = (btScalar)0.7; m_cfg.kSRHR_CL = (btScalar)0.1; m_cfg.kSKHR_CL = (btScalar)1; m_cfg.kSSHR_CL = (btScalar)0.5; m_cfg.kSR_SPLT_CL = (btScalar)0.5; m_cfg.kSK_SPLT_CL = (btScalar)0.5; m_cfg.kSS_SPLT_CL = (btScalar)0.5; m_cfg.maxvolume = (btScalar)1; m_cfg.timescale = 1; m_cfg.viterations = 0; m_cfg.piterations = 1; m_cfg.diterations = 0; m_cfg.citerations = 4; m_cfg.collisions = fCollision::Default; m_pose.m_bvolume = false; m_pose.m_bframe = false; m_pose.m_volume = 0; m_pose.m_com = btVector3(0,0,0); m_pose.m_rot.setIdentity(); m_pose.m_scl.setIdentity(); m_tag = 0; m_timeacc = 0; m_bUpdateRtCst = true; m_bounds[0] = btVector3(0,0,0); m_bounds[1] = btVector3(0,0,0); m_worldTransform.setIdentity(); setSolver(eSolverPresets::Positions); /* Collision shape */ ///for now, create a collision shape internally m_collisionShape = new btSoftBodyCollisionShape(this); m_collisionShape->setMargin(0.25f); m_initialWorldTransform.setIdentity(); m_windVelocity = btVector3(0,0,0); m_restLengthScale = btScalar(1.0); } // btSoftBody::~btSoftBody() { //for now, delete the internal shape delete m_collisionShape; int i; releaseClusters(); for(i=0;i<m_materials.size();++i) btAlignedFree(m_materials[i]); for(i=0;i<m_joints.size();++i) btAlignedFree(m_joints[i]); } // bool btSoftBody::checkLink(int node0,int node1) const { return(checkLink(&m_nodes[node0],&m_nodes[node1])); } // bool btSoftBody::checkLink(const Node* node0,const Node* node1) const { const Node* n[]={node0,node1}; for(int i=0,ni=m_links.size();i<ni;++i) { const Link& l=m_links[i]; if( (l.m_n[0]==n[0]&&l.m_n[1]==n[1])|| (l.m_n[0]==n[1]&&l.m_n[1]==n[0])) { return(true); } } return(false); } // bool btSoftBody::checkFace(int node0,int node1,int node2) const { const Node* n[]={ &m_nodes[node0], &m_nodes[node1], &m_nodes[node2]}; for(int i=0,ni=m_faces.size();i<ni;++i) { const Face& f=m_faces[i]; int c=0; for(int j=0;j<3;++j) { if( (f.m_n[j]==n[0])|| (f.m_n[j]==n[1])|| (f.m_n[j]==n[2])) c|=1<<j; else break; } if(c==7) return(true); } return(false); } // btSoftBody::Material* btSoftBody::appendMaterial() { Material* pm=new(btAlignedAlloc(sizeof(Material),16)) Material(); if(m_materials.size()>0) *pm=*m_materials[0]; else ZeroInitialize(*pm); m_materials.push_back(pm); return(pm); } // void btSoftBody::appendNote( const char* text, const btVector3& o, const btVector4& c, Node* n0, Node* n1, Node* n2, Node* n3) { Note n; ZeroInitialize(n); n.m_rank = 0; n.m_text = text; n.m_offset = o; n.m_coords[0] = c.x(); n.m_coords[1] = c.y(); n.m_coords[2] = c.z(); n.m_coords[3] = c.w(); n.m_nodes[0] = n0;n.m_rank+=n0?1:0; n.m_nodes[1] = n1;n.m_rank+=n1?1:0; n.m_nodes[2] = n2;n.m_rank+=n2?1:0; n.m_nodes[3] = n3;n.m_rank+=n3?1:0; m_notes.push_back(n); } // void btSoftBody::appendNote( const char* text, const btVector3& o, Node* feature) { appendNote(text,o,btVector4(1,0,0,0),feature); } // void btSoftBody::appendNote( const char* text, const btVector3& o, Link* feature) { static const btScalar w=1/(btScalar)2; appendNote(text,o,btVector4(w,w,0,0), feature->m_n[0], feature->m_n[1]); } // void btSoftBody::appendNote( const char* text, const btVector3& o, Face* feature) { static const btScalar w=1/(btScalar)3; appendNote(text,o,btVector4(w,w,w,0), feature->m_n[0], feature->m_n[1], feature->m_n[2]); } // void btSoftBody::appendNode( const btVector3& x,btScalar m) { if(m_nodes.capacity()==m_nodes.size()) { pointersToIndices(); m_nodes.reserve(m_nodes.size()*2+1); indicesToPointers(); } const btScalar margin=getCollisionShape()->getMargin(); m_nodes.push_back(Node()); Node& n=m_nodes[m_nodes.size()-1]; ZeroInitialize(n); n.m_x = x; n.m_q = n.m_x; n.m_im = m>0?1/m:0; n.m_material = m_materials[0]; n.m_leaf = m_ndbvt.insert(btDbvtVolume::FromCR(n.m_x,margin),&n); } // void btSoftBody::appendLink(int model,Material* mat) { Link l; if(model>=0) l=m_links[model]; else { ZeroInitialize(l);l.m_material=mat?mat:m_materials[0]; } m_links.push_back(l); } // void btSoftBody::appendLink( int node0, int node1, Material* mat, bool bcheckexist) { appendLink(&m_nodes[node0],&m_nodes[node1],mat,bcheckexist); } // void btSoftBody::appendLink( Node* node0, Node* node1, Material* mat, bool bcheckexist) { if((!bcheckexist)||(!checkLink(node0,node1))) { appendLink(-1,mat); Link& l=m_links[m_links.size()-1]; l.m_n[0] = node0; l.m_n[1] = node1; l.m_rl = (l.m_n[0]->m_x-l.m_n[1]->m_x).length(); m_bUpdateRtCst=true; } } // void btSoftBody::appendFace(int model,Material* mat) { Face f; if(model>=0) { f=m_faces[model]; } else { ZeroInitialize(f);f.m_material=mat?mat:m_materials[0]; } m_faces.push_back(f); } // void btSoftBody::appendFace(int node0,int node1,int node2,Material* mat) { if (node0==node1) return; if (node1==node2) return; if (node2==node0) return; appendFace(-1,mat); Face& f=m_faces[m_faces.size()-1]; btAssert(node0!=node1); btAssert(node1!=node2); btAssert(node2!=node0); f.m_n[0] = &m_nodes[node0]; f.m_n[1] = &m_nodes[node1]; f.m_n[2] = &m_nodes[node2]; f.m_ra = AreaOf( f.m_n[0]->m_x, f.m_n[1]->m_x, f.m_n[2]->m_x); m_bUpdateRtCst=true; } // void btSoftBody::appendTetra(int model,Material* mat) { Tetra t; if(model>=0) t=m_tetras[model]; else { ZeroInitialize(t);t.m_material=mat?mat:m_materials[0]; } m_tetras.push_back(t); } // void btSoftBody::appendTetra(int node0, int node1, int node2, int node3, Material* mat) { appendTetra(-1,mat); Tetra& t=m_tetras[m_tetras.size()-1]; t.m_n[0] = &m_nodes[node0]; t.m_n[1] = &m_nodes[node1]; t.m_n[2] = &m_nodes[node2]; t.m_n[3] = &m_nodes[node3]; t.m_rv = VolumeOf(t.m_n[0]->m_x,t.m_n[1]->m_x,t.m_n[2]->m_x,t.m_n[3]->m_x); m_bUpdateRtCst=true; } // void btSoftBody::appendAnchor(int node,btRigidBody* body, bool disableCollisionBetweenLinkedBodies,btScalar influence) { btVector3 local = body->getWorldTransform().inverse()*m_nodes[node].m_x; appendAnchor(node,body,local,disableCollisionBetweenLinkedBodies,influence); } // void btSoftBody::appendAnchor(int node,btRigidBody* body, const btVector3& localPivot,bool disableCollisionBetweenLinkedBodies,btScalar influence) { if (disableCollisionBetweenLinkedBodies) { if (m_collisionDisabledObjects.findLinearSearch(body)==m_collisionDisabledObjects.size()) { m_collisionDisabledObjects.push_back(body); } } Anchor a; a.m_node = &m_nodes[node]; a.m_body = body; a.m_local = localPivot; a.m_node->m_battach = 1; a.m_influence = influence; m_anchors.push_back(a); } // void btSoftBody::appendLinearJoint(const LJoint::Specs& specs,Cluster* body0,Body body1) { LJoint* pj = new(btAlignedAlloc(sizeof(LJoint),16)) LJoint(); pj->m_bodies[0] = body0; pj->m_bodies[1] = body1; pj->m_refs[0] = pj->m_bodies[0].xform().inverse()*specs.position; pj->m_refs[1] = pj->m_bodies[1].xform().inverse()*specs.position; pj->m_cfm = specs.cfm; pj->m_erp = specs.erp; pj->m_split = specs.split; m_joints.push_back(pj); } // void btSoftBody::appendLinearJoint(const LJoint::Specs& specs,Body body) { appendLinearJoint(specs,m_clusters[0],body); } // void btSoftBody::appendLinearJoint(const LJoint::Specs& specs,btSoftBody* body) { appendLinearJoint(specs,m_clusters[0],body->m_clusters[0]); } // void btSoftBody::appendAngularJoint(const AJoint::Specs& specs,Cluster* body0,Body body1) { AJoint* pj = new(btAlignedAlloc(sizeof(AJoint),16)) AJoint(); pj->m_bodies[0] = body0; pj->m_bodies[1] = body1; pj->m_refs[0] = pj->m_bodies[0].xform().inverse().getBasis()*specs.axis; pj->m_refs[1] = pj->m_bodies[1].xform().inverse().getBasis()*specs.axis; pj->m_cfm = specs.cfm; pj->m_erp = specs.erp; pj->m_split = specs.split; pj->m_icontrol = specs.icontrol; m_joints.push_back(pj); } // void btSoftBody::appendAngularJoint(const AJoint::Specs& specs,Body body) { appendAngularJoint(specs,m_clusters[0],body); } // void btSoftBody::appendAngularJoint(const AJoint::Specs& specs,btSoftBody* body) { appendAngularJoint(specs,m_clusters[0],body->m_clusters[0]); } // void btSoftBody::addForce(const btVector3& force) { for(int i=0,ni=m_nodes.size();i<ni;++i) addForce(force,i); } // void btSoftBody::addForce(const btVector3& force,int node) { Node& n=m_nodes[node]; if(n.m_im>0) { n.m_f += force; } } void btSoftBody::addAeroForceToNode(const btVector3& windVelocity,int nodeIndex) { btAssert(nodeIndex >= 0 && nodeIndex < m_nodes.size()); const btScalar dt = m_sst.sdt; const btScalar kLF = m_cfg.kLF; const btScalar kDG = m_cfg.kDG; //const btScalar kPR = m_cfg.kPR; //const btScalar kVC = m_cfg.kVC; const bool as_lift = kLF>0; const bool as_drag = kDG>0; const bool as_aero = as_lift || as_drag; const bool as_vaero = as_aero && (m_cfg.aeromodel < btSoftBody::eAeroModel::F_TwoSided); Node& n = m_nodes[nodeIndex]; if( n.m_im>0 ) { btSoftBody::sMedium medium; EvaluateMedium(m_worldInfo, n.m_x, medium); medium.m_velocity = windVelocity; medium.m_density = m_worldInfo->air_density; /* Aerodynamics */ if(as_vaero) { const btVector3 rel_v = n.m_v - medium.m_velocity; const btScalar rel_v_len = rel_v.length(); const btScalar rel_v2 = rel_v.length2(); if(rel_v2>SIMD_EPSILON) { const btVector3 rel_v_nrm = rel_v.normalized(); btVector3 nrm = n.m_n; if (m_cfg.aeromodel == btSoftBody::eAeroModel::V_TwoSidedLiftDrag) { nrm *= (btScalar)( (btDot(nrm,rel_v) < 0) ? -1 : +1); btVector3 fDrag(0, 0, 0); btVector3 fLift(0, 0, 0); btScalar n_dot_v = nrm.dot(rel_v_nrm); btScalar tri_area = 0.5f * n.m_area; fDrag = 0.5f * kDG * medium.m_density * rel_v2 * tri_area * n_dot_v * (-rel_v_nrm); // Check angle of attack // cos(10) = 0.98480 if ( 0 < n_dot_v && n_dot_v < 0.98480f) fLift = 0.5f * kLF * medium.m_density * rel_v_len * tri_area * btSqrt(1.0f-n_dot_v*n_dot_v) * (nrm.cross(rel_v_nrm).cross(rel_v_nrm)); // Check if the velocity change resulted by aero drag force exceeds the current velocity of the node. btVector3 del_v_by_fDrag = fDrag*n.m_im*m_sst.sdt; btScalar del_v_by_fDrag_len2 = del_v_by_fDrag.length2(); btScalar v_len2 = n.m_v.length2(); if (del_v_by_fDrag_len2 >= v_len2 && del_v_by_fDrag_len2 > 0) { btScalar del_v_by_fDrag_len = del_v_by_fDrag.length(); btScalar v_len = n.m_v.length(); fDrag *= btScalar(0.8)*(v_len / del_v_by_fDrag_len); } n.m_f += fDrag; n.m_f += fLift; } else if (m_cfg.aeromodel == btSoftBody::eAeroModel::V_Point || m_cfg.aeromodel == btSoftBody::eAeroModel::V_OneSided || m_cfg.aeromodel == btSoftBody::eAeroModel::V_TwoSided) { if (btSoftBody::eAeroModel::V_TwoSided) nrm *= (btScalar)( (btDot(nrm,rel_v) < 0) ? -1 : +1); const btScalar dvn = btDot(rel_v,nrm); /* Compute forces */ if(dvn>0) { btVector3 force(0,0,0); const btScalar c0 = n.m_area * dvn * rel_v2/2; const btScalar c1 = c0 * medium.m_density; force += nrm*(-c1*kLF); force += rel_v.normalized() * (-c1 * kDG); ApplyClampedForce(n, force, dt); } } } } } } void btSoftBody::addAeroForceToFace(const btVector3& windVelocity,int faceIndex) { const btScalar dt = m_sst.sdt; const btScalar kLF = m_cfg.kLF; const btScalar kDG = m_cfg.kDG; // const btScalar kPR = m_cfg.kPR; // const btScalar kVC = m_cfg.kVC; const bool as_lift = kLF>0; const bool as_drag = kDG>0; const bool as_aero = as_lift || as_drag; const bool as_faero = as_aero && (m_cfg.aeromodel >= btSoftBody::eAeroModel::F_TwoSided); if(as_faero) { btSoftBody::Face& f=m_faces[faceIndex]; btSoftBody::sMedium medium; const btVector3 v=(f.m_n[0]->m_v+f.m_n[1]->m_v+f.m_n[2]->m_v)/3; const btVector3 x=(f.m_n[0]->m_x+f.m_n[1]->m_x+f.m_n[2]->m_x)/3; EvaluateMedium(m_worldInfo,x,medium); medium.m_velocity = windVelocity; medium.m_density = m_worldInfo->air_density; const btVector3 rel_v=v-medium.m_velocity; const btScalar rel_v_len = rel_v.length(); const btScalar rel_v2=rel_v.length2(); if(rel_v2>SIMD_EPSILON) { const btVector3 rel_v_nrm = rel_v.normalized(); btVector3 nrm = f.m_normal; if (m_cfg.aeromodel == btSoftBody::eAeroModel::F_TwoSidedLiftDrag) { nrm *= (btScalar)( (btDot(nrm,rel_v) < 0) ? -1 : +1); btVector3 fDrag(0, 0, 0); btVector3 fLift(0, 0, 0); btScalar n_dot_v = nrm.dot(rel_v_nrm); btScalar tri_area = 0.5f * f.m_ra; fDrag = 0.5f * kDG * medium.m_density * rel_v2 * tri_area * n_dot_v * (-rel_v_nrm); // Check angle of attack // cos(10) = 0.98480 if ( 0 < n_dot_v && n_dot_v < 0.98480f) fLift = 0.5f * kLF * medium.m_density * rel_v_len * tri_area * btSqrt(1.0f-n_dot_v*n_dot_v) * (nrm.cross(rel_v_nrm).cross(rel_v_nrm)); fDrag /= 3; fLift /= 3; for(int j=0;j<3;++j) { if (f.m_n[j]->m_im>0) { // Check if the velocity change resulted by aero drag force exceeds the current velocity of the node. btVector3 del_v_by_fDrag = fDrag*f.m_n[j]->m_im*m_sst.sdt; btScalar del_v_by_fDrag_len2 = del_v_by_fDrag.length2(); btScalar v_len2 = f.m_n[j]->m_v.length2(); if (del_v_by_fDrag_len2 >= v_len2 && del_v_by_fDrag_len2 > 0) { btScalar del_v_by_fDrag_len = del_v_by_fDrag.length(); btScalar v_len = f.m_n[j]->m_v.length(); fDrag *= btScalar(0.8)*(v_len / del_v_by_fDrag_len); } f.m_n[j]->m_f += fDrag; f.m_n[j]->m_f += fLift; } } } else if (m_cfg.aeromodel == btSoftBody::eAeroModel::F_OneSided || m_cfg.aeromodel == btSoftBody::eAeroModel::F_TwoSided) { if (btSoftBody::eAeroModel::F_TwoSided) nrm *= (btScalar)( (btDot(nrm,rel_v) < 0) ? -1 : +1); const btScalar dvn=btDot(rel_v,nrm); /* Compute forces */ if(dvn>0) { btVector3 force(0,0,0); const btScalar c0 = f.m_ra*dvn*rel_v2; const btScalar c1 = c0*medium.m_density; force += nrm*(-c1*kLF); force += rel_v.normalized()*(-c1*kDG); force /= 3; for(int j=0;j<3;++j) ApplyClampedForce(*f.m_n[j],force,dt); } } } } } // void btSoftBody::addVelocity(const btVector3& velocity) { for(int i=0,ni=m_nodes.size();i<ni;++i) addVelocity(velocity,i); } /* Set velocity for the entire body */ void btSoftBody::setVelocity( const btVector3& velocity) { for(int i=0,ni=m_nodes.size();i<ni;++i) { Node& n=m_nodes[i]; if(n.m_im>0) { n.m_v = velocity; } } } // void btSoftBody::addVelocity(const btVector3& velocity,int node) { Node& n=m_nodes[node]; if(n.m_im>0) { n.m_v += velocity; } } // void btSoftBody::setMass(int node,btScalar mass) { m_nodes[node].m_im=mass>0?1/mass:0; m_bUpdateRtCst=true; } // btScalar btSoftBody::getMass(int node) const { return(m_nodes[node].m_im>0?1/m_nodes[node].m_im:0); } // btScalar btSoftBody::getTotalMass() const { btScalar mass=0; for(int i=0;i<m_nodes.size();++i) { mass+=getMass(i); } return(mass); } // void btSoftBody::setTotalMass(btScalar mass,bool fromfaces) { int i; if(fromfaces) { for(i=0;i<m_nodes.size();++i) { m_nodes[i].m_im=0; } for(i=0;i<m_faces.size();++i) { const Face& f=m_faces[i]; const btScalar twicearea=AreaOf( f.m_n[0]->m_x, f.m_n[1]->m_x, f.m_n[2]->m_x); for(int j=0;j<3;++j) { f.m_n[j]->m_im+=twicearea; } } for( i=0;i<m_nodes.size();++i) { m_nodes[i].m_im=1/m_nodes[i].m_im; } } const btScalar tm=getTotalMass(); const btScalar itm=1/tm; for( i=0;i<m_nodes.size();++i) { m_nodes[i].m_im/=itm*mass; } m_bUpdateRtCst=true; } // void btSoftBody::setTotalDensity(btScalar density) { setTotalMass(getVolume()*density,true); } // void btSoftBody::setVolumeMass(btScalar mass) { btAlignedObjectArray<btScalar> ranks; ranks.resize(m_nodes.size(),0); int i; for(i=0;i<m_nodes.size();++i) { m_nodes[i].m_im=0; } for(i=0;i<m_tetras.size();++i) { const Tetra& t=m_tetras[i]; for(int j=0;j<4;++j) { t.m_n[j]->m_im+=btFabs(t.m_rv); ranks[int(t.m_n[j]-&m_nodes[0])]+=1; } } for( i=0;i<m_nodes.size();++i) { if(m_nodes[i].m_im>0) { m_nodes[i].m_im=ranks[i]/m_nodes[i].m_im; } } setTotalMass(mass,false); } // void btSoftBody::setVolumeDensity(btScalar density) { btScalar volume=0; for(int i=0;i<m_tetras.size();++i) { const Tetra& t=m_tetras[i]; for(int j=0;j<4;++j) { volume+=btFabs(t.m_rv); } } setVolumeMass(volume*density/6); } // void btSoftBody::transform(const btTransform& trs) { const btScalar margin=getCollisionShape()->getMargin(); ATTRIBUTE_ALIGNED16(btDbvtVolume) vol; for(int i=0,ni=m_nodes.size();i<ni;++i) { Node& n=m_nodes[i]; n.m_x=trs*n.m_x; n.m_q=trs*n.m_q; n.m_n=trs.getBasis()*n.m_n; vol = btDbvtVolume::FromCR(n.m_x,margin); m_ndbvt.update(n.m_leaf,vol); } updateNormals(); updateBounds(); updateConstants(); m_initialWorldTransform = trs; } // void btSoftBody::translate(const btVector3& trs) { btTransform t; t.setIdentity(); t.setOrigin(trs); transform(t); } // void btSoftBody::rotate( const btQuaternion& rot) { btTransform t; t.setIdentity(); t.setRotation(rot); transform(t); } // void btSoftBody::scale(const btVector3& scl) { const btScalar margin=getCollisionShape()->getMargin(); ATTRIBUTE_ALIGNED16(btDbvtVolume) vol; for(int i=0,ni=m_nodes.size();i<ni;++i) { Node& n=m_nodes[i]; n.m_x*=scl; n.m_q*=scl; vol = btDbvtVolume::FromCR(n.m_x,margin); m_ndbvt.update(n.m_leaf,vol); } updateNormals(); updateBounds(); updateConstants(); } // btScalar btSoftBody::getRestLengthScale() { return m_restLengthScale; } // void btSoftBody::setRestLengthScale(btScalar restLengthScale) { for(int i=0, ni=m_links.size(); i<ni; ++i) { Link& l=m_links[i]; l.m_rl = l.m_rl / m_restLengthScale * restLengthScale; l.m_c1 = l.m_rl*l.m_rl; } m_restLengthScale = restLengthScale; if (getActivationState() == ISLAND_SLEEPING) activate(); } // void btSoftBody::setPose(bool bvolume,bool bframe) { m_pose.m_bvolume = bvolume; m_pose.m_bframe = bframe; int i,ni; /* Weights */ const btScalar omass=getTotalMass(); const btScalar kmass=omass*m_nodes.size()*1000; btScalar tmass=omass; m_pose.m_wgh.resize(m_nodes.size()); for(i=0,ni=m_nodes.size();i<ni;++i) { if(m_nodes[i].m_im<=0) tmass+=kmass; } for( i=0,ni=m_nodes.size();i<ni;++i) { Node& n=m_nodes[i]; m_pose.m_wgh[i]= n.m_im>0 ? 1/(m_nodes[i].m_im*tmass) : kmass/tmass; } /* Pos */ const btVector3 com=evaluateCom(); m_pose.m_pos.resize(m_nodes.size()); for( i=0,ni=m_nodes.size();i<ni;++i) { m_pose.m_pos[i]=m_nodes[i].m_x-com; } m_pose.m_volume = bvolume?getVolume():0; m_pose.m_com = com; m_pose.m_rot.setIdentity(); m_pose.m_scl.setIdentity(); /* Aqq */ m_pose.m_aqq[0] = m_pose.m_aqq[1] = m_pose.m_aqq[2] = btVector3(0,0,0); for( i=0,ni=m_nodes.size();i<ni;++i) { const btVector3& q=m_pose.m_pos[i]; const btVector3 mq=m_pose.m_wgh[i]*q; m_pose.m_aqq[0]+=mq.x()*q; m_pose.m_aqq[1]+=mq.y()*q; m_pose.m_aqq[2]+=mq.z()*q; } m_pose.m_aqq=m_pose.m_aqq.inverse(); updateConstants(); } void btSoftBody::resetLinkRestLengths() { for(int i=0, ni=m_links.size();i<ni;++i) { Link& l = m_links[i]; l.m_rl = (l.m_n[0]->m_x-l.m_n[1]->m_x).length(); l.m_c1 = l.m_rl*l.m_rl; } } // btScalar btSoftBody::getVolume() const { btScalar vol=0; if(m_nodes.size()>0) { int i,ni; const btVector3 org=m_nodes[0].m_x; for(i=0,ni=m_faces.size();i<ni;++i) { const Face& f=m_faces[i]; vol+=btDot(f.m_n[0]->m_x-org,btCross(f.m_n[1]->m_x-org,f.m_n[2]->m_x-org)); } vol/=(btScalar)6; } return(vol); } // int btSoftBody::clusterCount() const { return(m_clusters.size()); } // btVector3 btSoftBody::clusterCom(const Cluster* cluster) { btVector3 com(0,0,0); for(int i=0,ni=cluster->m_nodes.size();i<ni;++i) { com+=cluster->m_nodes[i]->m_x*cluster->m_masses[i]; } return(com*cluster->m_imass); } // btVector3 btSoftBody::clusterCom(int cluster) const { return(clusterCom(m_clusters[cluster])); } // btVector3 btSoftBody::clusterVelocity(const Cluster* cluster,const btVector3& rpos) { return(cluster->m_lv+btCross(cluster->m_av,rpos)); } // void btSoftBody::clusterVImpulse(Cluster* cluster,const btVector3& rpos,const btVector3& impulse) { const btVector3 li=cluster->m_imass*impulse; const btVector3 ai=cluster->m_invwi*btCross(rpos,impulse); cluster->m_vimpulses[0]+=li;cluster->m_lv+=li; cluster->m_vimpulses[1]+=ai;cluster->m_av+=ai; cluster->m_nvimpulses++; } // void btSoftBody::clusterDImpulse(Cluster* cluster,const btVector3& rpos,const btVector3& impulse) { const btVector3 li=cluster->m_imass*impulse; const btVector3 ai=cluster->m_invwi*btCross(rpos,impulse); cluster->m_dimpulses[0]+=li; cluster->m_dimpulses[1]+=ai; cluster->m_ndimpulses++; } // void btSoftBody::clusterImpulse(Cluster* cluster,const btVector3& rpos,const Impulse& impulse) { if(impulse.m_asVelocity) clusterVImpulse(cluster,rpos,impulse.m_velocity); if(impulse.m_asDrift) clusterDImpulse(cluster,rpos,impulse.m_drift); } // void btSoftBody::clusterVAImpulse(Cluster* cluster,const btVector3& impulse) { const btVector3 ai=cluster->m_invwi*impulse; cluster->m_vimpulses[1]+=ai;cluster->m_av+=ai; cluster->m_nvimpulses++; } // void btSoftBody::clusterDAImpulse(Cluster* cluster,const btVector3& impulse) { const btVector3 ai=cluster->m_invwi*impulse; cluster->m_dimpulses[1]+=ai; cluster->m_ndimpulses++; } // void btSoftBody::clusterAImpulse(Cluster* cluster,const Impulse& impulse) { if(impulse.m_asVelocity) clusterVAImpulse(cluster,impulse.m_velocity); if(impulse.m_asDrift) clusterDAImpulse(cluster,impulse.m_drift); } // void btSoftBody::clusterDCImpulse(Cluster* cluster,const btVector3& impulse) { cluster->m_dimpulses[0]+=impulse*cluster->m_imass; cluster->m_ndimpulses++; } struct NodeLinks { btAlignedObjectArray<int> m_links; }; // int btSoftBody::generateBendingConstraints(int distance,Material* mat) { int i,j; if(distance>1) { /* Build graph */ const int n=m_nodes.size(); const unsigned inf=(~(unsigned)0)>>1; unsigned* adj=new unsigned[n*n]; #define IDX(_x_,_y_) ((_y_)*n+(_x_)) for(j=0;j<n;++j) { for(i=0;i<n;++i) { if(i!=j) { adj[IDX(i,j)]=adj[IDX(j,i)]=inf; } else { adj[IDX(i,j)]=adj[IDX(j,i)]=0; } } } for( i=0;i<m_links.size();++i) { const int ia=(int)(m_links[i].m_n[0]-&m_nodes[0]); const int ib=(int)(m_links[i].m_n[1]-&m_nodes[0]); adj[IDX(ia,ib)]=1; adj[IDX(ib,ia)]=1; } //special optimized case for distance == 2 if (distance == 2) { btAlignedObjectArray<NodeLinks> nodeLinks; /* Build node links */ nodeLinks.resize(m_nodes.size()); for( i=0;i<m_links.size();++i) { const int ia=(int)(m_links[i].m_n[0]-&m_nodes[0]); const int ib=(int)(m_links[i].m_n[1]-&m_nodes[0]); if (nodeLinks[ia].m_links.findLinearSearch(ib)==nodeLinks[ia].m_links.size()) nodeLinks[ia].m_links.push_back(ib); if (nodeLinks[ib].m_links.findLinearSearch(ia)==nodeLinks[ib].m_links.size()) nodeLinks[ib].m_links.push_back(ia); } for (int ii=0;ii<nodeLinks.size();ii++) { int i=ii; for (int jj=0;jj<nodeLinks[ii].m_links.size();jj++) { int k = nodeLinks[ii].m_links[jj]; for (int kk=0;kk<nodeLinks[k].m_links.size();kk++) { int j = nodeLinks[k].m_links[kk]; if (i!=j) { const unsigned sum=adj[IDX(i,k)]+adj[IDX(k,j)]; btAssert(sum==2); if(adj[IDX(i,j)]>sum) { adj[IDX(i,j)]=adj[IDX(j,i)]=sum; } } } } } } else { ///generic Floyd's algorithm for(int k=0;k<n;++k) { for(j=0;j<n;++j) { for(i=j+1;i<n;++i) { const unsigned sum=adj[IDX(i,k)]+adj[IDX(k,j)]; if(adj[IDX(i,j)]>sum) { adj[IDX(i,j)]=adj[IDX(j,i)]=sum; } } } } } /* Build links */ int nlinks=0; for(j=0;j<n;++j) { for(i=j+1;i<n;++i) { if(adj[IDX(i,j)]==(unsigned)distance) { appendLink(i,j,mat); m_links[m_links.size()-1].m_bbending=1; ++nlinks; } } } delete[] adj; return(nlinks); } return(0); } // void btSoftBody::randomizeConstraints() { unsigned long seed=243703; #define NEXTRAND (seed=(1664525L*seed+1013904223L)&0xffffffff) int i,ni; for(i=0,ni=m_links.size();i<ni;++i) { btSwap(m_links[i],m_links[NEXTRAND%ni]); } for(i=0,ni=m_faces.size();i<ni;++i) { btSwap(m_faces[i],m_faces[NEXTRAND%ni]); } #undef NEXTRAND } // void btSoftBody::releaseCluster(int index) { Cluster* c=m_clusters[index]; if(c->m_leaf) m_cdbvt.remove(c->m_leaf); c->~Cluster(); btAlignedFree(c); m_clusters.remove(c); } // void btSoftBody::releaseClusters() { while(m_clusters.size()>0) releaseCluster(0); } // int btSoftBody::generateClusters(int k,int maxiterations) { int i; releaseClusters(); m_clusters.resize(btMin(k,m_nodes.size())); for(i=0;i<m_clusters.size();++i) { m_clusters[i] = new(btAlignedAlloc(sizeof(Cluster),16)) Cluster(); m_clusters[i]->m_collide= true; } k=m_clusters.size(); if(k>0) { /* Initialize */ btAlignedObjectArray<btVector3> centers; btVector3 cog(0,0,0); int i; for(i=0;i<m_nodes.size();++i) { cog+=m_nodes[i].m_x; m_clusters[(i*29873)%m_clusters.size()]->m_nodes.push_back(&m_nodes[i]); } cog/=(btScalar)m_nodes.size(); centers.resize(k,cog); /* Iterate */ const btScalar slope=16; bool changed; int iterations=0; do { const btScalar w=2-btMin<btScalar>(1,iterations/slope); changed=false; iterations++; int i; for(i=0;i<k;++i) { btVector3 c(0,0,0); for(int j=0;j<m_clusters[i]->m_nodes.size();++j) { c+=m_clusters[i]->m_nodes[j]->m_x; } if(m_clusters[i]->m_nodes.size()) { c /= (btScalar)m_clusters[i]->m_nodes.size(); c = centers[i]+(c-centers[i])*w; changed |= ((c-centers[i]).length2()>SIMD_EPSILON); centers[i] = c; m_clusters[i]->m_nodes.resize(0); } } for(i=0;i<m_nodes.size();++i) { const btVector3 nx=m_nodes[i].m_x; int kbest=0; btScalar kdist=ClusterMetric(centers[0],nx); for(int j=1;j<k;++j) { const btScalar d=ClusterMetric(centers[j],nx); if(d<kdist) { kbest=j; kdist=d; } } m_clusters[kbest]->m_nodes.push_back(&m_nodes[i]); } } while(changed&&(iterations<maxiterations)); /* Merge */ btAlignedObjectArray<int> cids; cids.resize(m_nodes.size(),-1); for(i=0;i<m_clusters.size();++i) { for(int j=0;j<m_clusters[i]->m_nodes.size();++j) { cids[int(m_clusters[i]->m_nodes[j]-&m_nodes[0])]=i; } } for(i=0;i<m_faces.size();++i) { const int idx[]={ int(m_faces[i].m_n[0]-&m_nodes[0]), int(m_faces[i].m_n[1]-&m_nodes[0]), int(m_faces[i].m_n[2]-&m_nodes[0])}; for(int j=0;j<3;++j) { const int cid=cids[idx[j]]; for(int q=1;q<3;++q) { const int kid=idx[(j+q)%3]; if(cids[kid]!=cid) { if(m_clusters[cid]->m_nodes.findLinearSearch(&m_nodes[kid])==m_clusters[cid]->m_nodes.size()) { m_clusters[cid]->m_nodes.push_back(&m_nodes[kid]); } } } } } /* Master */ if(m_clusters.size()>1) { Cluster* pmaster=new(btAlignedAlloc(sizeof(Cluster),16)) Cluster(); pmaster->m_collide = false; pmaster->m_nodes.reserve(m_nodes.size()); for(int i=0;i<m_nodes.size();++i) pmaster->m_nodes.push_back(&m_nodes[i]); m_clusters.push_back(pmaster); btSwap(m_clusters[0],m_clusters[m_clusters.size()-1]); } /* Terminate */ for(i=0;i<m_clusters.size();++i) { if(m_clusters[i]->m_nodes.size()==0) { releaseCluster(i--); } } } else { //create a cluster for each tetrahedron (if tetrahedra exist) or each face if (m_tetras.size()) { m_clusters.resize(m_tetras.size()); for(i=0;i<m_clusters.size();++i) { m_clusters[i] = new(btAlignedAlloc(sizeof(Cluster),16)) Cluster(); m_clusters[i]->m_collide= true; } for (i=0;i<m_tetras.size();i++) { for (int j=0;j<4;j++) { m_clusters[i]->m_nodes.push_back(m_tetras[i].m_n[j]); } } } else { m_clusters.resize(m_faces.size()); for(i=0;i<m_clusters.size();++i) { m_clusters[i] = new(btAlignedAlloc(sizeof(Cluster),16)) Cluster(); m_clusters[i]->m_collide= true; } for(i=0;i<m_faces.size();++i) { for(int j=0;j<3;++j) { m_clusters[i]->m_nodes.push_back(m_faces[i].m_n[j]); } } } } if (m_clusters.size()) { initializeClusters(); updateClusters(); //for self-collision m_clusterConnectivity.resize(m_clusters.size()*m_clusters.size()); { for (int c0=0;c0<m_clusters.size();c0++) { m_clusters[c0]->m_clusterIndex=c0; for (int c1=0;c1<m_clusters.size();c1++) { bool connected=false; Cluster* cla = m_clusters[c0]; Cluster* clb = m_clusters[c1]; for (int i=0;!connected&&i<cla->m_nodes.size();i++) { for (int j=0;j<clb->m_nodes.size();j++) { if (cla->m_nodes[i] == clb->m_nodes[j]) { connected=true; break; } } } m_clusterConnectivity[c0+c1*m_clusters.size()]=connected; } } } } return(m_clusters.size()); } // void btSoftBody::refine(ImplicitFn* ifn,btScalar accurary,bool cut) { const Node* nbase = &m_nodes[0]; int ncount = m_nodes.size(); btSymMatrix<int> edges(ncount,-2); int newnodes=0; int i,j,k,ni; /* Filter out */ for(i=0;i<m_links.size();++i) { Link& l=m_links[i]; if(l.m_bbending) { if(!SameSign(ifn->Eval(l.m_n[0]->m_x),ifn->Eval(l.m_n[1]->m_x))) { btSwap(m_links[i],m_links[m_links.size()-1]); m_links.pop_back();--i; } } } /* Fill edges */ for(i=0;i<m_links.size();++i) { Link& l=m_links[i]; edges(int(l.m_n[0]-nbase),int(l.m_n[1]-nbase))=-1; } for(i=0;i<m_faces.size();++i) { Face& f=m_faces[i]; edges(int(f.m_n[0]-nbase),int(f.m_n[1]-nbase))=-1; edges(int(f.m_n[1]-nbase),int(f.m_n[2]-nbase))=-1; edges(int(f.m_n[2]-nbase),int(f.m_n[0]-nbase))=-1; } /* Intersect */ for(i=0;i<ncount;++i) { for(j=i+1;j<ncount;++j) { if(edges(i,j)==-1) { Node& a=m_nodes[i]; Node& b=m_nodes[j]; const btScalar t=ImplicitSolve(ifn,a.m_x,b.m_x,accurary); if(t>0) { const btVector3 x=Lerp(a.m_x,b.m_x,t); const btVector3 v=Lerp(a.m_v,b.m_v,t); btScalar m=0; if(a.m_im>0) { if(b.m_im>0) { const btScalar ma=1/a.m_im; const btScalar mb=1/b.m_im; const btScalar mc=Lerp(ma,mb,t); const btScalar f=(ma+mb)/(ma+mb+mc); a.m_im=1/(ma*f); b.m_im=1/(mb*f); m=mc*f; } else { a.m_im/=0.5f;m=1/a.m_im; } } else { if(b.m_im>0) { b.m_im/=0.5f;m=1/b.m_im; } else m=0; } appendNode(x,m); edges(i,j)=m_nodes.size()-1; m_nodes[edges(i,j)].m_v=v; ++newnodes; } } } } nbase=&m_nodes[0]; /* Refine links */ for(i=0,ni=m_links.size();i<ni;++i) { Link& feat=m_links[i]; const int idx[]={ int(feat.m_n[0]-nbase), int(feat.m_n[1]-nbase)}; if((idx[0]<ncount)&&(idx[1]<ncount)) { const int ni=edges(idx[0],idx[1]); if(ni>0) { appendLink(i); Link* pft[]={ &m_links[i], &m_links[m_links.size()-1]}; pft[0]->m_n[0]=&m_nodes[idx[0]]; pft[0]->m_n[1]=&m_nodes[ni]; pft[1]->m_n[0]=&m_nodes[ni]; pft[1]->m_n[1]=&m_nodes[idx[1]]; } } } /* Refine faces */ for(i=0;i<m_faces.size();++i) { const Face& feat=m_faces[i]; const int idx[]={ int(feat.m_n[0]-nbase), int(feat.m_n[1]-nbase), int(feat.m_n[2]-nbase)}; for(j=2,k=0;k<3;j=k++) { if((idx[j]<ncount)&&(idx[k]<ncount)) { const int ni=edges(idx[j],idx[k]); if(ni>0) { appendFace(i); const int l=(k+1)%3; Face* pft[]={ &m_faces[i], &m_faces[m_faces.size()-1]}; pft[0]->m_n[0]=&m_nodes[idx[l]]; pft[0]->m_n[1]=&m_nodes[idx[j]]; pft[0]->m_n[2]=&m_nodes[ni]; pft[1]->m_n[0]=&m_nodes[ni]; pft[1]->m_n[1]=&m_nodes[idx[k]]; pft[1]->m_n[2]=&m_nodes[idx[l]]; appendLink(ni,idx[l],pft[0]->m_material); --i;break; } } } } /* Cut */ if(cut) { btAlignedObjectArray<int> cnodes; const int pcount=ncount; int i; ncount=m_nodes.size(); cnodes.resize(ncount,0); /* Nodes */ for(i=0;i<ncount;++i) { const btVector3 x=m_nodes[i].m_x; if((i>=pcount)||(btFabs(ifn->Eval(x))<accurary)) { const btVector3 v=m_nodes[i].m_v; btScalar m=getMass(i); if(m>0) { m*=0.5f;m_nodes[i].m_im/=0.5f; } appendNode(x,m); cnodes[i]=m_nodes.size()-1; m_nodes[cnodes[i]].m_v=v; } } nbase=&m_nodes[0]; /* Links */ for(i=0,ni=m_links.size();i<ni;++i) { const int id[]={ int(m_links[i].m_n[0]-nbase), int(m_links[i].m_n[1]-nbase)}; int todetach=0; if(cnodes[id[0]]&&cnodes[id[1]]) { appendLink(i); todetach=m_links.size()-1; } else { if(( (ifn->Eval(m_nodes[id[0]].m_x)<accurary)&& (ifn->Eval(m_nodes[id[1]].m_x)<accurary))) todetach=i; } if(todetach) { Link& l=m_links[todetach]; for(int j=0;j<2;++j) { int cn=cnodes[int(l.m_n[j]-nbase)]; if(cn) l.m_n[j]=&m_nodes[cn]; } } } /* Faces */ for(i=0,ni=m_faces.size();i<ni;++i) { Node** n= m_faces[i].m_n; if( (ifn->Eval(n[0]->m_x)<accurary)&& (ifn->Eval(n[1]->m_x)<accurary)&& (ifn->Eval(n[2]->m_x)<accurary)) { for(int j=0;j<3;++j) { int cn=cnodes[int(n[j]-nbase)]; if(cn) n[j]=&m_nodes[cn]; } } } /* Clean orphans */ int nnodes=m_nodes.size(); btAlignedObjectArray<int> ranks; btAlignedObjectArray<int> todelete; ranks.resize(nnodes,0); for(i=0,ni=m_links.size();i<ni;++i) { for(int j=0;j<2;++j) ranks[int(m_links[i].m_n[j]-nbase)]++; } for(i=0,ni=m_faces.size();i<ni;++i) { for(int j=0;j<3;++j) ranks[int(m_faces[i].m_n[j]-nbase)]++; } for(i=0;i<m_links.size();++i) { const int id[]={ int(m_links[i].m_n[0]-nbase), int(m_links[i].m_n[1]-nbase)}; const bool sg[]={ ranks[id[0]]==1, ranks[id[1]]==1}; if(sg[0]||sg[1]) { --ranks[id[0]]; --ranks[id[1]]; btSwap(m_links[i],m_links[m_links.size()-1]); m_links.pop_back();--i; } } #if 0 for(i=nnodes-1;i>=0;--i) { if(!ranks[i]) todelete.push_back(i); } if(todelete.size()) { btAlignedObjectArray<int>& map=ranks; for(int i=0;i<nnodes;++i) map[i]=i; PointersToIndices(this); for(int i=0,ni=todelete.size();i<ni;++i) { int j=todelete[i]; int& a=map[j]; int& b=map[--nnodes]; m_ndbvt.remove(m_nodes[a].m_leaf);m_nodes[a].m_leaf=0; btSwap(m_nodes[a],m_nodes[b]); j=a;a=b;b=j; } IndicesToPointers(this,&map[0]); m_nodes.resize(nnodes); } #endif } m_bUpdateRtCst=true; } // bool btSoftBody::cutLink(const Node* node0,const Node* node1,btScalar position) { return(cutLink(int(node0-&m_nodes[0]),int(node1-&m_nodes[0]),position)); } // bool btSoftBody::cutLink(int node0,int node1,btScalar position) { bool done=false; int i,ni; // const btVector3 d=m_nodes[node0].m_x-m_nodes[node1].m_x; const btVector3 x=Lerp(m_nodes[node0].m_x,m_nodes[node1].m_x,position); const btVector3 v=Lerp(m_nodes[node0].m_v,m_nodes[node1].m_v,position); const btScalar m=1; appendNode(x,m); appendNode(x,m); Node* pa=&m_nodes[node0]; Node* pb=&m_nodes[node1]; Node* pn[2]={ &m_nodes[m_nodes.size()-2], &m_nodes[m_nodes.size()-1]}; pn[0]->m_v=v; pn[1]->m_v=v; for(i=0,ni=m_links.size();i<ni;++i) { const int mtch=MatchEdge(m_links[i].m_n[0],m_links[i].m_n[1],pa,pb); if(mtch!=-1) { appendLink(i); Link* pft[]={&m_links[i],&m_links[m_links.size()-1]}; pft[0]->m_n[1]=pn[mtch]; pft[1]->m_n[0]=pn[1-mtch]; done=true; } } for(i=0,ni=m_faces.size();i<ni;++i) { for(int k=2,l=0;l<3;k=l++) { const int mtch=MatchEdge(m_faces[i].m_n[k],m_faces[i].m_n[l],pa,pb); if(mtch!=-1) { appendFace(i); Face* pft[]={&m_faces[i],&m_faces[m_faces.size()-1]}; pft[0]->m_n[l]=pn[mtch]; pft[1]->m_n[k]=pn[1-mtch]; appendLink(pn[0],pft[0]->m_n[(l+1)%3],pft[0]->m_material,true); appendLink(pn[1],pft[0]->m_n[(l+1)%3],pft[0]->m_material,true); } } } if(!done) { m_ndbvt.remove(pn[0]->m_leaf); m_ndbvt.remove(pn[1]->m_leaf); m_nodes.pop_back(); m_nodes.pop_back(); } return(done); } // bool btSoftBody::rayTest(const btVector3& rayFrom, const btVector3& rayTo, sRayCast& results) { if(m_faces.size()&&m_fdbvt.empty()) initializeFaceTree(); results.body = this; results.fraction = 1.f; results.feature = eFeature::None; results.index = -1; return(rayTest(rayFrom,rayTo,results.fraction,results.feature,results.index,false)!=0); } // void btSoftBody::setSolver(eSolverPresets::_ preset) { m_cfg.m_vsequence.clear(); m_cfg.m_psequence.clear(); m_cfg.m_dsequence.clear(); switch(preset) { case eSolverPresets::Positions: m_cfg.m_psequence.push_back(ePSolver::Anchors); m_cfg.m_psequence.push_back(ePSolver::RContacts); m_cfg.m_psequence.push_back(ePSolver::SContacts); m_cfg.m_psequence.push_back(ePSolver::Linear); break; case eSolverPresets::Velocities: m_cfg.m_vsequence.push_back(eVSolver::Linear); m_cfg.m_psequence.push_back(ePSolver::Anchors); m_cfg.m_psequence.push_back(ePSolver::RContacts); m_cfg.m_psequence.push_back(ePSolver::SContacts); m_cfg.m_dsequence.push_back(ePSolver::Linear); break; } } // void btSoftBody::predictMotion(btScalar dt) { int i,ni; /* Update */ if(m_bUpdateRtCst) { m_bUpdateRtCst=false; updateConstants(); m_fdbvt.clear(); if(m_cfg.collisions&fCollision::VF_SS) { initializeFaceTree(); } } /* Prepare */ m_sst.sdt = dt*m_cfg.timescale; m_sst.isdt = 1/m_sst.sdt; m_sst.velmrg = m_sst.sdt*3; m_sst.radmrg = getCollisionShape()->getMargin(); m_sst.updmrg = m_sst.radmrg*(btScalar)0.25; /* Forces */ addVelocity(m_worldInfo->m_gravity*m_sst.sdt); applyForces(); /* Integrate */ for(i=0,ni=m_nodes.size();i<ni;++i) { Node& n=m_nodes[i]; n.m_q = n.m_x; btVector3 deltaV = n.m_f*n.m_im*m_sst.sdt; { btScalar maxDisplacement = m_worldInfo->m_maxDisplacement; btScalar clampDeltaV = maxDisplacement/m_sst.sdt; for (int c=0;c<3;c++) { if (deltaV[c]>clampDeltaV) { deltaV[c] = clampDeltaV; } if (deltaV[c]<-clampDeltaV) { deltaV[c]=-clampDeltaV; } } } n.m_v += deltaV; n.m_x += n.m_v*m_sst.sdt; n.m_f = btVector3(0,0,0); } /* Clusters */ updateClusters(); /* Bounds */ updateBounds(); /* Nodes */ ATTRIBUTE_ALIGNED16(btDbvtVolume) vol; for(i=0,ni=m_nodes.size();i<ni;++i) { Node& n=m_nodes[i]; vol = btDbvtVolume::FromCR(n.m_x,m_sst.radmrg); m_ndbvt.update( n.m_leaf, vol, n.m_v*m_sst.velmrg, m_sst.updmrg); } /* Faces */ if(!m_fdbvt.empty()) { for(int i=0;i<m_faces.size();++i) { Face& f=m_faces[i]; const btVector3 v=( f.m_n[0]->m_v+ f.m_n[1]->m_v+ f.m_n[2]->m_v)/3; vol = VolumeOf(f,m_sst.radmrg); m_fdbvt.update( f.m_leaf, vol, v*m_sst.velmrg, m_sst.updmrg); } } /* Pose */ updatePose(); /* Match */ if(m_pose.m_bframe&&(m_cfg.kMT>0)) { const btMatrix3x3 posetrs=m_pose.m_rot; for(int i=0,ni=m_nodes.size();i<ni;++i) { Node& n=m_nodes[i]; if(n.m_im>0) { const btVector3 x=posetrs*m_pose.m_pos[i]+m_pose.m_com; n.m_x=Lerp(n.m_x,x,m_cfg.kMT); } } } /* Clear contacts */ m_rcontacts.resize(0); m_scontacts.resize(0); /* Optimize dbvt's */ m_ndbvt.optimizeIncremental(1); m_fdbvt.optimizeIncremental(1); m_cdbvt.optimizeIncremental(1); } // void btSoftBody::solveConstraints() { /* Apply clusters */ applyClusters(false); /* Prepare links */ int i,ni; for(i=0,ni=m_links.size();i<ni;++i) { Link& l=m_links[i]; l.m_c3 = l.m_n[1]->m_q-l.m_n[0]->m_q; l.m_c2 = 1/(l.m_c3.length2()*l.m_c0); } /* Prepare anchors */ for(i=0,ni=m_anchors.size();i<ni;++i) { Anchor& a=m_anchors[i]; const btVector3 ra=a.m_body->getWorldTransform().getBasis()*a.m_local; a.m_c0 = ImpulseMatrix( m_sst.sdt, a.m_node->m_im, a.m_body->getInvMass(), a.m_body->getInvInertiaTensorWorld(), ra); a.m_c1 = ra; a.m_c2 = m_sst.sdt*a.m_node->m_im; a.m_body->activate(); } /* Solve velocities */ if(m_cfg.viterations>0) { /* Solve */ for(int isolve=0;isolve<m_cfg.viterations;++isolve) { for(int iseq=0;iseq<m_cfg.m_vsequence.size();++iseq) { getSolver(m_cfg.m_vsequence[iseq])(this,1); } } /* Update */ for(i=0,ni=m_nodes.size();i<ni;++i) { Node& n=m_nodes[i]; n.m_x = n.m_q+n.m_v*m_sst.sdt; } } /* Solve positions */ if(m_cfg.piterations>0) { for(int isolve=0;isolve<m_cfg.piterations;++isolve) { const btScalar ti=isolve/(btScalar)m_cfg.piterations; for(int iseq=0;iseq<m_cfg.m_psequence.size();++iseq) { getSolver(m_cfg.m_psequence[iseq])(this,1,ti); } } const btScalar vc=m_sst.isdt*(1-m_cfg.kDP); for(i=0,ni=m_nodes.size();i<ni;++i) { Node& n=m_nodes[i]; n.m_v = (n.m_x-n.m_q)*vc; n.m_f = btVector3(0,0,0); } } /* Solve drift */ if(m_cfg.diterations>0) { const btScalar vcf=m_cfg.kVCF*m_sst.isdt; for(i=0,ni=m_nodes.size();i<ni;++i) { Node& n=m_nodes[i]; n.m_q = n.m_x; } for(int idrift=0;idrift<m_cfg.diterations;++idrift) { for(int iseq=0;iseq<m_cfg.m_dsequence.size();++iseq) { getSolver(m_cfg.m_dsequence[iseq])(this,1,0); } } for(int i=0,ni=m_nodes.size();i<ni;++i) { Node& n=m_nodes[i]; n.m_v += (n.m_x-n.m_q)*vcf; } } /* Apply clusters */ dampClusters(); applyClusters(true); } // void btSoftBody::staticSolve(int iterations) { for(int isolve=0;isolve<iterations;++isolve) { for(int iseq=0;iseq<m_cfg.m_psequence.size();++iseq) { getSolver(m_cfg.m_psequence[iseq])(this,1,0); } } } // void btSoftBody::solveCommonConstraints(btSoftBody** /*bodies*/,int /*count*/,int /*iterations*/) { /// placeholder } // void btSoftBody::solveClusters(const btAlignedObjectArray<btSoftBody*>& bodies) { const int nb=bodies.size(); int iterations=0; int i; for(i=0;i<nb;++i) { iterations=btMax(iterations,bodies[i]->m_cfg.citerations); } for(i=0;i<nb;++i) { bodies[i]->prepareClusters(iterations); } for(i=0;i<iterations;++i) { const btScalar sor=1; for(int j=0;j<nb;++j) { bodies[j]->solveClusters(sor); } } for(i=0;i<nb;++i) { bodies[i]->cleanupClusters(); } } // void btSoftBody::integrateMotion() { /* Update */ updateNormals(); } // btSoftBody::RayFromToCaster::RayFromToCaster(const btVector3& rayFrom,const btVector3& rayTo,btScalar mxt) { m_rayFrom = rayFrom; m_rayNormalizedDirection = (rayTo-rayFrom); m_rayTo = rayTo; m_mint = mxt; m_face = 0; m_tests = 0; } // void btSoftBody::RayFromToCaster::Process(const btDbvtNode* leaf) { btSoftBody::Face& f=*(btSoftBody::Face*)leaf->data; const btScalar t=rayFromToTriangle( m_rayFrom,m_rayTo,m_rayNormalizedDirection, f.m_n[0]->m_x, f.m_n[1]->m_x, f.m_n[2]->m_x, m_mint); if((t>0)&&(t<m_mint)) { m_mint=t;m_face=&f; } ++m_tests; } // btScalar btSoftBody::RayFromToCaster::rayFromToTriangle( const btVector3& rayFrom, const btVector3& rayTo, const btVector3& rayNormalizedDirection, const btVector3& a, const btVector3& b, const btVector3& c, btScalar maxt) { static const btScalar ceps=-SIMD_EPSILON*10; static const btScalar teps=SIMD_EPSILON*10; const btVector3 n=btCross(b-a,c-a); const btScalar d=btDot(a,n); const btScalar den=btDot(rayNormalizedDirection,n); if(!btFuzzyZero(den)) { const btScalar num=btDot(rayFrom,n)-d; const btScalar t=-num/den; if((t>teps)&&(t<maxt)) { const btVector3 hit=rayFrom+rayNormalizedDirection*t; if( (btDot(n,btCross(a-hit,b-hit))>ceps) && (btDot(n,btCross(b-hit,c-hit))>ceps) && (btDot(n,btCross(c-hit,a-hit))>ceps)) { return(t); } } } return(-1); } // void btSoftBody::pointersToIndices() { #define PTR2IDX(_p_,_b_) reinterpret_cast<btSoftBody::Node*>((_p_)-(_b_)) btSoftBody::Node* base=m_nodes.size() ? &m_nodes[0] : 0; int i,ni; for(i=0,ni=m_nodes.size();i<ni;++i) { if(m_nodes[i].m_leaf) { m_nodes[i].m_leaf->data=*(void**)&i; } } for(i=0,ni=m_links.size();i<ni;++i) { m_links[i].m_n[0]=PTR2IDX(m_links[i].m_n[0],base); m_links[i].m_n[1]=PTR2IDX(m_links[i].m_n[1],base); } for(i=0,ni=m_faces.size();i<ni;++i) { m_faces[i].m_n[0]=PTR2IDX(m_faces[i].m_n[0],base); m_faces[i].m_n[1]=PTR2IDX(m_faces[i].m_n[1],base); m_faces[i].m_n[2]=PTR2IDX(m_faces[i].m_n[2],base); if(m_faces[i].m_leaf) { m_faces[i].m_leaf->data=*(void**)&i; } } for(i=0,ni=m_anchors.size();i<ni;++i) { m_anchors[i].m_node=PTR2IDX(m_anchors[i].m_node,base); } for(i=0,ni=m_notes.size();i<ni;++i) { for(int j=0;j<m_notes[i].m_rank;++j) { m_notes[i].m_nodes[j]=PTR2IDX(m_notes[i].m_nodes[j],base); } } #undef PTR2IDX } // void btSoftBody::indicesToPointers(const int* map) { #define IDX2PTR(_p_,_b_) map?(&(_b_)[map[(((char*)_p_)-(char*)0)]]): \ (&(_b_)[(((char*)_p_)-(char*)0)]) btSoftBody::Node* base=m_nodes.size() ? &m_nodes[0]:0; int i,ni; for(i=0,ni=m_nodes.size();i<ni;++i) { if(m_nodes[i].m_leaf) { m_nodes[i].m_leaf->data=&m_nodes[i]; } } for(i=0,ni=m_links.size();i<ni;++i) { m_links[i].m_n[0]=IDX2PTR(m_links[i].m_n[0],base); m_links[i].m_n[1]=IDX2PTR(m_links[i].m_n[1],base); } for(i=0,ni=m_faces.size();i<ni;++i) { m_faces[i].m_n[0]=IDX2PTR(m_faces[i].m_n[0],base); m_faces[i].m_n[1]=IDX2PTR(m_faces[i].m_n[1],base); m_faces[i].m_n[2]=IDX2PTR(m_faces[i].m_n[2],base); if(m_faces[i].m_leaf) { m_faces[i].m_leaf->data=&m_faces[i]; } } for(i=0,ni=m_anchors.size();i<ni;++i) { m_anchors[i].m_node=IDX2PTR(m_anchors[i].m_node,base); } for(i=0,ni=m_notes.size();i<ni;++i) { for(int j=0;j<m_notes[i].m_rank;++j) { m_notes[i].m_nodes[j]=IDX2PTR(m_notes[i].m_nodes[j],base); } } #undef IDX2PTR } // int btSoftBody::rayTest(const btVector3& rayFrom,const btVector3& rayTo, btScalar& mint,eFeature::_& feature,int& index,bool bcountonly) const { int cnt=0; btVector3 dir = rayTo-rayFrom; if(bcountonly||m_fdbvt.empty()) {/* Full search */ for(int i=0,ni=m_faces.size();i<ni;++i) { const btSoftBody::Face& f=m_faces[i]; const btScalar t=RayFromToCaster::rayFromToTriangle( rayFrom,rayTo,dir, f.m_n[0]->m_x, f.m_n[1]->m_x, f.m_n[2]->m_x, mint); if(t>0) { ++cnt; if(!bcountonly) { feature=btSoftBody::eFeature::Face; index=i; mint=t; } } } } else {/* Use dbvt */ RayFromToCaster collider(rayFrom,rayTo,mint); btDbvt::rayTest(m_fdbvt.m_root,rayFrom,rayTo,collider); if(collider.m_face) { mint=collider.m_mint; feature=btSoftBody::eFeature::Face; index=(int)(collider.m_face-&m_faces[0]); cnt=1; } } for (int i=0;i<m_tetras.size();i++) { const btSoftBody::Tetra& tet = m_tetras[i]; int tetfaces[4][3] = {{0,1,2},{0,1,3},{1,2,3},{0,2,3}}; for (int f=0;f<4;f++) { int index0=tetfaces[f][0]; int index1=tetfaces[f][1]; int index2=tetfaces[f][2]; btVector3 v0=tet.m_n[index0]->m_x; btVector3 v1=tet.m_n[index1]->m_x; btVector3 v2=tet.m_n[index2]->m_x; const btScalar t=RayFromToCaster::rayFromToTriangle( rayFrom,rayTo,dir, v0,v1,v2, mint); if(t>0) { ++cnt; if(!bcountonly) { feature=btSoftBody::eFeature::Tetra; index=i; mint=t; } } } } return(cnt); } // void btSoftBody::initializeFaceTree() { m_fdbvt.clear(); for(int i=0;i<m_faces.size();++i) { Face& f=m_faces[i]; f.m_leaf=m_fdbvt.insert(VolumeOf(f,0),&f); } } // btVector3 btSoftBody::evaluateCom() const { btVector3 com(0,0,0); if(m_pose.m_bframe) { for(int i=0,ni=m_nodes.size();i<ni;++i) { com+=m_nodes[i].m_x*m_pose.m_wgh[i]; } } return(com); } // bool btSoftBody::checkContact( const btCollisionObjectWrapper* colObjWrap, const btVector3& x, btScalar margin, btSoftBody::sCti& cti) const { btVector3 nrm; const btCollisionShape *shp = colObjWrap->getCollisionShape(); // const btRigidBody *tmpRigid = btRigidBody::upcast(colObjWrap->getCollisionObject()); //const btTransform &wtr = tmpRigid ? tmpRigid->getWorldTransform() : colObjWrap->getWorldTransform(); const btTransform &wtr = colObjWrap->getWorldTransform(); //todo: check which transform is needed here btScalar dst = m_worldInfo->m_sparsesdf.Evaluate( wtr.invXform(x), shp, nrm, margin); if(dst<0) { cti.m_colObj = colObjWrap->getCollisionObject(); cti.m_normal = wtr.getBasis()*nrm; cti.m_offset = -btDot( cti.m_normal, x - cti.m_normal * dst ); return(true); } return(false); } // void btSoftBody::updateNormals() { const btVector3 zv(0,0,0); int i,ni; for(i=0,ni=m_nodes.size();i<ni;++i) { m_nodes[i].m_n=zv; } for(i=0,ni=m_faces.size();i<ni;++i) { btSoftBody::Face& f=m_faces[i]; const btVector3 n=btCross(f.m_n[1]->m_x-f.m_n[0]->m_x, f.m_n[2]->m_x-f.m_n[0]->m_x); f.m_normal=n.normalized(); f.m_n[0]->m_n+=n; f.m_n[1]->m_n+=n; f.m_n[2]->m_n+=n; } for(i=0,ni=m_nodes.size();i<ni;++i) { btScalar len = m_nodes[i].m_n.length(); if (len>SIMD_EPSILON) m_nodes[i].m_n /= len; } } // void btSoftBody::updateBounds() { /*if( m_acceleratedSoftBody ) { // If we have an accelerated softbody we need to obtain the bounds correctly // For now (slightly hackily) just have a very large AABB // TODO: Write get bounds kernel // If that is updating in place, atomic collisions might be low (when the cloth isn't perfectly aligned to an axis) and we could // probably do a test and exchange reasonably efficiently. m_bounds[0] = btVector3(-1000, -1000, -1000); m_bounds[1] = btVector3(1000, 1000, 1000); } else {*/ if(m_ndbvt.m_root) { const btVector3& mins=m_ndbvt.m_root->volume.Mins(); const btVector3& maxs=m_ndbvt.m_root->volume.Maxs(); const btScalar csm=getCollisionShape()->getMargin(); const btVector3 mrg=btVector3( csm, csm, csm)*1; // ??? to investigate... m_bounds[0]=mins-mrg; m_bounds[1]=maxs+mrg; if(0!=getBroadphaseHandle()) { m_worldInfo->m_broadphase->setAabb( getBroadphaseHandle(), m_bounds[0], m_bounds[1], m_worldInfo->m_dispatcher); } } else { m_bounds[0]= m_bounds[1]=btVector3(0,0,0); } //} } // void btSoftBody::updatePose() { if(m_pose.m_bframe) { btSoftBody::Pose& pose=m_pose; const btVector3 com=evaluateCom(); /* Com */ pose.m_com = com; /* Rotation */ btMatrix3x3 Apq; const btScalar eps=SIMD_EPSILON; Apq[0]=Apq[1]=Apq[2]=btVector3(0,0,0); Apq[0].setX(eps);Apq[1].setY(eps*2);Apq[2].setZ(eps*3); for(int i=0,ni=m_nodes.size();i<ni;++i) { const btVector3 a=pose.m_wgh[i]*(m_nodes[i].m_x-com); const btVector3& b=pose.m_pos[i]; Apq[0]+=a.x()*b; Apq[1]+=a.y()*b; Apq[2]+=a.z()*b; } btMatrix3x3 r,s; PolarDecompose(Apq,r,s); pose.m_rot=r; pose.m_scl=pose.m_aqq*r.transpose()*Apq; if(m_cfg.maxvolume>1) { const btScalar idet=Clamp<btScalar>( 1/pose.m_scl.determinant(), 1,m_cfg.maxvolume); pose.m_scl=Mul(pose.m_scl,idet); } } } // void btSoftBody::updateArea(bool averageArea) { int i,ni; /* Face area */ for(i=0,ni=m_faces.size();i<ni;++i) { Face& f=m_faces[i]; f.m_ra = AreaOf(f.m_n[0]->m_x,f.m_n[1]->m_x,f.m_n[2]->m_x); } /* Node area */ if (averageArea) { btAlignedObjectArray<int> counts; counts.resize(m_nodes.size(),0); for(i=0,ni=m_nodes.size();i<ni;++i) { m_nodes[i].m_area = 0; } for(i=0,ni=m_faces.size();i<ni;++i) { btSoftBody::Face& f=m_faces[i]; for(int j=0;j<3;++j) { const int index=(int)(f.m_n[j]-&m_nodes[0]); counts[index]++; f.m_n[j]->m_area+=btFabs(f.m_ra); } } for(i=0,ni=m_nodes.size();i<ni;++i) { if(counts[i]>0) m_nodes[i].m_area/=(btScalar)counts[i]; else m_nodes[i].m_area=0; } } else { // initialize node area as zero for(i=0,ni=m_nodes.size();i<ni;++i) { m_nodes[i].m_area=0; } for(i=0,ni=m_faces.size();i<ni;++i) { btSoftBody::Face& f=m_faces[i]; for(int j=0;j<3;++j) { f.m_n[j]->m_area += f.m_ra; } } for(i=0,ni=m_nodes.size();i<ni;++i) { m_nodes[i].m_area *= 0.3333333f; } } } void btSoftBody::updateLinkConstants() { int i,ni; /* Links */ for(i=0,ni=m_links.size();i<ni;++i) { Link& l=m_links[i]; Material& m=*l.m_material; l.m_c0 = (l.m_n[0]->m_im+l.m_n[1]->m_im)/m.m_kLST; } } void btSoftBody::updateConstants() { resetLinkRestLengths(); updateLinkConstants(); updateArea(); } // void btSoftBody::initializeClusters() { int i; for( i=0;i<m_clusters.size();++i) { Cluster& c=*m_clusters[i]; c.m_imass=0; c.m_masses.resize(c.m_nodes.size()); for(int j=0;j<c.m_nodes.size();++j) { if (c.m_nodes[j]->m_im==0) { c.m_containsAnchor = true; c.m_masses[j] = BT_LARGE_FLOAT; } else { c.m_masses[j] = btScalar(1.)/c.m_nodes[j]->m_im; } c.m_imass += c.m_masses[j]; } c.m_imass = btScalar(1.)/c.m_imass; c.m_com = btSoftBody::clusterCom(&c); c.m_lv = btVector3(0,0,0); c.m_av = btVector3(0,0,0); c.m_leaf = 0; /* Inertia */ btMatrix3x3& ii=c.m_locii; ii[0]=ii[1]=ii[2]=btVector3(0,0,0); { int i,ni; for(i=0,ni=c.m_nodes.size();i<ni;++i) { const btVector3 k=c.m_nodes[i]->m_x-c.m_com; const btVector3 q=k*k; const btScalar m=c.m_masses[i]; ii[0][0] += m*(q[1]+q[2]); ii[1][1] += m*(q[0]+q[2]); ii[2][2] += m*(q[0]+q[1]); ii[0][1] -= m*k[0]*k[1]; ii[0][2] -= m*k[0]*k[2]; ii[1][2] -= m*k[1]*k[2]; } } ii[1][0]=ii[0][1]; ii[2][0]=ii[0][2]; ii[2][1]=ii[1][2]; ii = ii.inverse(); /* Frame */ c.m_framexform.setIdentity(); c.m_framexform.setOrigin(c.m_com); c.m_framerefs.resize(c.m_nodes.size()); { int i; for(i=0;i<c.m_framerefs.size();++i) { c.m_framerefs[i]=c.m_nodes[i]->m_x-c.m_com; } } } } // void btSoftBody::updateClusters() { BT_PROFILE("UpdateClusters"); int i; for(i=0;i<m_clusters.size();++i) { btSoftBody::Cluster& c=*m_clusters[i]; const int n=c.m_nodes.size(); //const btScalar invn=1/(btScalar)n; if(n) { /* Frame */ const btScalar eps=btScalar(0.0001); btMatrix3x3 m,r,s; m[0]=m[1]=m[2]=btVector3(0,0,0); m[0][0]=eps*1; m[1][1]=eps*2; m[2][2]=eps*3; c.m_com=clusterCom(&c); for(int i=0;i<c.m_nodes.size();++i) { const btVector3 a=c.m_nodes[i]->m_x-c.m_com; const btVector3& b=c.m_framerefs[i]; m[0]+=a[0]*b;m[1]+=a[1]*b;m[2]+=a[2]*b; } PolarDecompose(m,r,s); c.m_framexform.setOrigin(c.m_com); c.m_framexform.setBasis(r); /* Inertia */ #if 1/* Constant */ c.m_invwi=c.m_framexform.getBasis()*c.m_locii*c.m_framexform.getBasis().transpose(); #else #if 0/* Sphere */ const btScalar rk=(2*c.m_extents.length2())/(5*c.m_imass); const btVector3 inertia(rk,rk,rk); const btVector3 iin(btFabs(inertia[0])>SIMD_EPSILON?1/inertia[0]:0, btFabs(inertia[1])>SIMD_EPSILON?1/inertia[1]:0, btFabs(inertia[2])>SIMD_EPSILON?1/inertia[2]:0); c.m_invwi=c.m_xform.getBasis().scaled(iin)*c.m_xform.getBasis().transpose(); #else/* Actual */ c.m_invwi[0]=c.m_invwi[1]=c.m_invwi[2]=btVector3(0,0,0); for(int i=0;i<n;++i) { const btVector3 k=c.m_nodes[i]->m_x-c.m_com; const btVector3 q=k*k; const btScalar m=1/c.m_nodes[i]->m_im; c.m_invwi[0][0] += m*(q[1]+q[2]); c.m_invwi[1][1] += m*(q[0]+q[2]); c.m_invwi[2][2] += m*(q[0]+q[1]); c.m_invwi[0][1] -= m*k[0]*k[1]; c.m_invwi[0][2] -= m*k[0]*k[2]; c.m_invwi[1][2] -= m*k[1]*k[2]; } c.m_invwi[1][0]=c.m_invwi[0][1]; c.m_invwi[2][0]=c.m_invwi[0][2]; c.m_invwi[2][1]=c.m_invwi[1][2]; c.m_invwi=c.m_invwi.inverse(); #endif #endif /* Velocities */ c.m_lv=btVector3(0,0,0); c.m_av=btVector3(0,0,0); { int i; for(i=0;i<n;++i) { const btVector3 v=c.m_nodes[i]->m_v*c.m_masses[i]; c.m_lv += v; c.m_av += btCross(c.m_nodes[i]->m_x-c.m_com,v); } } c.m_lv=c.m_imass*c.m_lv*(1-c.m_ldamping); c.m_av=c.m_invwi*c.m_av*(1-c.m_adamping); c.m_vimpulses[0] = c.m_vimpulses[1] = btVector3(0,0,0); c.m_dimpulses[0] = c.m_dimpulses[1] = btVector3(0,0,0); c.m_nvimpulses = 0; c.m_ndimpulses = 0; /* Matching */ if(c.m_matching>0) { for(int j=0;j<c.m_nodes.size();++j) { Node& n=*c.m_nodes[j]; const btVector3 x=c.m_framexform*c.m_framerefs[j]; n.m_x=Lerp(n.m_x,x,c.m_matching); } } /* Dbvt */ if(c.m_collide) { btVector3 mi=c.m_nodes[0]->m_x; btVector3 mx=mi; for(int j=1;j<n;++j) { mi.setMin(c.m_nodes[j]->m_x); mx.setMax(c.m_nodes[j]->m_x); } ATTRIBUTE_ALIGNED16(btDbvtVolume) bounds=btDbvtVolume::FromMM(mi,mx); if(c.m_leaf) m_cdbvt.update(c.m_leaf,bounds,c.m_lv*m_sst.sdt*3,m_sst.radmrg); else c.m_leaf=m_cdbvt.insert(bounds,&c); } } } } // void btSoftBody::cleanupClusters() { for(int i=0;i<m_joints.size();++i) { m_joints[i]->Terminate(m_sst.sdt); if(m_joints[i]->m_delete) { btAlignedFree(m_joints[i]); m_joints.remove(m_joints[i--]); } } } // void btSoftBody::prepareClusters(int iterations) { for(int i=0;i<m_joints.size();++i) { m_joints[i]->Prepare(m_sst.sdt,iterations); } } // void btSoftBody::solveClusters(btScalar sor) { for(int i=0,ni=m_joints.size();i<ni;++i) { m_joints[i]->Solve(m_sst.sdt,sor); } } // void btSoftBody::applyClusters(bool drift) { BT_PROFILE("ApplyClusters"); // const btScalar f0=m_sst.sdt; //const btScalar f1=f0/2; btAlignedObjectArray<btVector3> deltas; btAlignedObjectArray<btScalar> weights; deltas.resize(m_nodes.size(),btVector3(0,0,0)); weights.resize(m_nodes.size(),0); int i; if(drift) { for(i=0;i<m_clusters.size();++i) { Cluster& c=*m_clusters[i]; if(c.m_ndimpulses) { c.m_dimpulses[0]/=(btScalar)c.m_ndimpulses; c.m_dimpulses[1]/=(btScalar)c.m_ndimpulses; } } } for(i=0;i<m_clusters.size();++i) { Cluster& c=*m_clusters[i]; if(0<(drift?c.m_ndimpulses:c.m_nvimpulses)) { const btVector3 v=(drift?c.m_dimpulses[0]:c.m_vimpulses[0])*m_sst.sdt; const btVector3 w=(drift?c.m_dimpulses[1]:c.m_vimpulses[1])*m_sst.sdt; for(int j=0;j<c.m_nodes.size();++j) { const int idx=int(c.m_nodes[j]-&m_nodes[0]); const btVector3& x=c.m_nodes[j]->m_x; const btScalar q=c.m_masses[j]; deltas[idx] += (v+btCross(w,x-c.m_com))*q; weights[idx] += q; } } } for(i=0;i<deltas.size();++i) { if(weights[i]>0) { m_nodes[i].m_x+=deltas[i]/weights[i]; } } } // void btSoftBody::dampClusters() { int i; for(i=0;i<m_clusters.size();++i) { Cluster& c=*m_clusters[i]; if(c.m_ndamping>0) { for(int j=0;j<c.m_nodes.size();++j) { Node& n=*c.m_nodes[j]; if(n.m_im>0) { const btVector3 vx=c.m_lv+btCross(c.m_av,c.m_nodes[j]->m_q-c.m_com); if(vx.length2()<=n.m_v.length2()) { n.m_v += c.m_ndamping*(vx-n.m_v); } } } } } } // void btSoftBody::Joint::Prepare(btScalar dt,int) { m_bodies[0].activate(); m_bodies[1].activate(); } // void btSoftBody::LJoint::Prepare(btScalar dt,int iterations) { static const btScalar maxdrift=4; Joint::Prepare(dt,iterations); m_rpos[0] = m_bodies[0].xform()*m_refs[0]; m_rpos[1] = m_bodies[1].xform()*m_refs[1]; m_drift = Clamp(m_rpos[0]-m_rpos[1],maxdrift)*m_erp/dt; m_rpos[0] -= m_bodies[0].xform().getOrigin(); m_rpos[1] -= m_bodies[1].xform().getOrigin(); m_massmatrix = ImpulseMatrix( m_bodies[0].invMass(),m_bodies[0].invWorldInertia(),m_rpos[0], m_bodies[1].invMass(),m_bodies[1].invWorldInertia(),m_rpos[1]); if(m_split>0) { m_sdrift = m_massmatrix*(m_drift*m_split); m_drift *= 1-m_split; } m_drift /=(btScalar)iterations; } // void btSoftBody::LJoint::Solve(btScalar dt,btScalar sor) { const btVector3 va=m_bodies[0].velocity(m_rpos[0]); const btVector3 vb=m_bodies[1].velocity(m_rpos[1]); const btVector3 vr=va-vb; btSoftBody::Impulse impulse; impulse.m_asVelocity = 1; impulse.m_velocity = m_massmatrix*(m_drift+vr*m_cfm)*sor; m_bodies[0].applyImpulse(-impulse,m_rpos[0]); m_bodies[1].applyImpulse( impulse,m_rpos[1]); } // void btSoftBody::LJoint::Terminate(btScalar dt) { if(m_split>0) { m_bodies[0].applyDImpulse(-m_sdrift,m_rpos[0]); m_bodies[1].applyDImpulse( m_sdrift,m_rpos[1]); } } // void btSoftBody::AJoint::Prepare(btScalar dt,int iterations) { static const btScalar maxdrift=SIMD_PI/16; m_icontrol->Prepare(this); Joint::Prepare(dt,iterations); m_axis[0] = m_bodies[0].xform().getBasis()*m_refs[0]; m_axis[1] = m_bodies[1].xform().getBasis()*m_refs[1]; m_drift = NormalizeAny(btCross(m_axis[1],m_axis[0])); m_drift *= btMin(maxdrift,btAcos(Clamp<btScalar>(btDot(m_axis[0],m_axis[1]),-1,+1))); m_drift *= m_erp/dt; m_massmatrix= AngularImpulseMatrix(m_bodies[0].invWorldInertia(),m_bodies[1].invWorldInertia()); if(m_split>0) { m_sdrift = m_massmatrix*(m_drift*m_split); m_drift *= 1-m_split; } m_drift /=(btScalar)iterations; } // void btSoftBody::AJoint::Solve(btScalar dt,btScalar sor) { const btVector3 va=m_bodies[0].angularVelocity(); const btVector3 vb=m_bodies[1].angularVelocity(); const btVector3 vr=va-vb; const btScalar sp=btDot(vr,m_axis[0]); const btVector3 vc=vr-m_axis[0]*m_icontrol->Speed(this,sp); btSoftBody::Impulse impulse; impulse.m_asVelocity = 1; impulse.m_velocity = m_massmatrix*(m_drift+vc*m_cfm)*sor; m_bodies[0].applyAImpulse(-impulse); m_bodies[1].applyAImpulse( impulse); } // void btSoftBody::AJoint::Terminate(btScalar dt) { if(m_split>0) { m_bodies[0].applyDAImpulse(-m_sdrift); m_bodies[1].applyDAImpulse( m_sdrift); } } // void btSoftBody::CJoint::Prepare(btScalar dt,int iterations) { Joint::Prepare(dt,iterations); const bool dodrift=(m_life==0); m_delete=(++m_life)>m_maxlife; if(dodrift) { m_drift=m_drift*m_erp/dt; if(m_split>0) { m_sdrift = m_massmatrix*(m_drift*m_split); m_drift *= 1-m_split; } m_drift/=(btScalar)iterations; } else { m_drift=m_sdrift=btVector3(0,0,0); } } // void btSoftBody::CJoint::Solve(btScalar dt,btScalar sor) { const btVector3 va=m_bodies[0].velocity(m_rpos[0]); const btVector3 vb=m_bodies[1].velocity(m_rpos[1]); const btVector3 vrel=va-vb; const btScalar rvac=btDot(vrel,m_normal); btSoftBody::Impulse impulse; impulse.m_asVelocity = 1; impulse.m_velocity = m_drift; if(rvac<0) { const btVector3 iv=m_normal*rvac; const btVector3 fv=vrel-iv; impulse.m_velocity += iv+fv*m_friction; } impulse.m_velocity=m_massmatrix*impulse.m_velocity*sor; if (m_bodies[0].m_soft==m_bodies[1].m_soft) { if ((impulse.m_velocity.getX() ==impulse.m_velocity.getX())&&(impulse.m_velocity.getY() ==impulse.m_velocity.getY())&& (impulse.m_velocity.getZ() ==impulse.m_velocity.getZ())) { if (impulse.m_asVelocity) { if (impulse.m_velocity.length() <m_bodies[0].m_soft->m_maxSelfCollisionImpulse) { } else { m_bodies[0].applyImpulse(-impulse*m_bodies[0].m_soft->m_selfCollisionImpulseFactor,m_rpos[0]); m_bodies[1].applyImpulse( impulse*m_bodies[0].m_soft->m_selfCollisionImpulseFactor,m_rpos[1]); } } } } else { m_bodies[0].applyImpulse(-impulse,m_rpos[0]); m_bodies[1].applyImpulse( impulse,m_rpos[1]); } } // void btSoftBody::CJoint::Terminate(btScalar dt) { if(m_split>0) { m_bodies[0].applyDImpulse(-m_sdrift,m_rpos[0]); m_bodies[1].applyDImpulse( m_sdrift,m_rpos[1]); } } // void btSoftBody::applyForces() { BT_PROFILE("SoftBody applyForces"); // const btScalar dt = m_sst.sdt; const btScalar kLF = m_cfg.kLF; const btScalar kDG = m_cfg.kDG; const btScalar kPR = m_cfg.kPR; const btScalar kVC = m_cfg.kVC; const bool as_lift = kLF>0; const bool as_drag = kDG>0; const bool as_pressure = kPR!=0; const bool as_volume = kVC>0; const bool as_aero = as_lift || as_drag ; //const bool as_vaero = as_aero && // (m_cfg.aeromodel < btSoftBody::eAeroModel::F_TwoSided); //const bool as_faero = as_aero && // (m_cfg.aeromodel >= btSoftBody::eAeroModel::F_TwoSided); const bool use_medium = as_aero; const bool use_volume = as_pressure || as_volume ; btScalar volume = 0; btScalar ivolumetp = 0; btScalar dvolumetv = 0; btSoftBody::sMedium medium; if(use_volume) { volume = getVolume(); ivolumetp = 1/btFabs(volume)*kPR; dvolumetv = (m_pose.m_volume-volume)*kVC; } /* Per vertex forces */ int i,ni; for(i=0,ni=m_nodes.size();i<ni;++i) { btSoftBody::Node& n=m_nodes[i]; if(n.m_im>0) { if(use_medium) { /* Aerodynamics */ addAeroForceToNode(m_windVelocity, i); } /* Pressure */ if(as_pressure) { n.m_f += n.m_n*(n.m_area*ivolumetp); } /* Volume */ if(as_volume) { n.m_f += n.m_n*(n.m_area*dvolumetv); } } } /* Per face forces */ for(i=0,ni=m_faces.size();i<ni;++i) { // btSoftBody::Face& f=m_faces[i]; /* Aerodynamics */ addAeroForceToFace(m_windVelocity, i); } } // void btSoftBody::PSolve_Anchors(btSoftBody* psb,btScalar kst,btScalar ti) { const btScalar kAHR=psb->m_cfg.kAHR*kst; const btScalar dt=psb->m_sst.sdt; for(int i=0,ni=psb->m_anchors.size();i<ni;++i) { const Anchor& a=psb->m_anchors[i]; const btTransform& t=a.m_body->getWorldTransform(); Node& n=*a.m_node; const btVector3 wa=t*a.m_local; const btVector3 va=a.m_body->getVelocityInLocalPoint(a.m_c1)*dt; const btVector3 vb=n.m_x-n.m_q; const btVector3 vr=(va-vb)+(wa-n.m_x)*kAHR; const btVector3 impulse=a.m_c0*vr*a.m_influence; n.m_x+=impulse*a.m_c2; a.m_body->applyImpulse(-impulse,a.m_c1); } } // void btSoftBody::PSolve_RContacts(btSoftBody* psb, btScalar kst, btScalar ti) { const btScalar dt = psb->m_sst.sdt; const btScalar mrg = psb->getCollisionShape()->getMargin(); for(int i=0,ni=psb->m_rcontacts.size();i<ni;++i) { const RContact& c = psb->m_rcontacts[i]; const sCti& cti = c.m_cti; btRigidBody* tmpRigid = (btRigidBody*)btRigidBody::upcast(cti.m_colObj); const btVector3 va = tmpRigid ? tmpRigid->getVelocityInLocalPoint(c.m_c1)*dt : btVector3(0,0,0); const btVector3 vb = c.m_node->m_x-c.m_node->m_q; const btVector3 vr = vb-va; const btScalar dn = btDot(vr, cti.m_normal); if(dn<=SIMD_EPSILON) { const btScalar dp = btMin( (btDot(c.m_node->m_x, cti.m_normal) + cti.m_offset), mrg ); const btVector3 fv = vr - (cti.m_normal * dn); // c0 is the impulse matrix, c3 is 1 - the friction coefficient or 0, c4 is the contact hardness coefficient const btVector3 impulse = c.m_c0 * ( (vr - (fv * c.m_c3) + (cti.m_normal * (dp * c.m_c4))) * kst ); c.m_node->m_x -= impulse * c.m_c2; if (tmpRigid) tmpRigid->applyImpulse(impulse,c.m_c1); } } } // void btSoftBody::PSolve_SContacts(btSoftBody* psb,btScalar,btScalar ti) { for(int i=0,ni=psb->m_scontacts.size();i<ni;++i) { const SContact& c=psb->m_scontacts[i]; const btVector3& nr=c.m_normal; Node& n=*c.m_node; Face& f=*c.m_face; const btVector3 p=BaryEval( f.m_n[0]->m_x, f.m_n[1]->m_x, f.m_n[2]->m_x, c.m_weights); const btVector3 q=BaryEval( f.m_n[0]->m_q, f.m_n[1]->m_q, f.m_n[2]->m_q, c.m_weights); const btVector3 vr=(n.m_x-n.m_q)-(p-q); btVector3 corr(0,0,0); btScalar dot = btDot(vr,nr); if(dot<0) { const btScalar j=c.m_margin-(btDot(nr,n.m_x)-btDot(nr,p)); corr+=c.m_normal*j; } corr -= ProjectOnPlane(vr,nr)*c.m_friction; n.m_x += corr*c.m_cfm[0]; f.m_n[0]->m_x -= corr*(c.m_cfm[1]*c.m_weights.x()); f.m_n[1]->m_x -= corr*(c.m_cfm[1]*c.m_weights.y()); f.m_n[2]->m_x -= corr*(c.m_cfm[1]*c.m_weights.z()); } } // void btSoftBody::PSolve_Links(btSoftBody* psb,btScalar kst,btScalar ti) { for(int i=0,ni=psb->m_links.size();i<ni;++i) { Link& l=psb->m_links[i]; if(l.m_c0>0) { Node& a=*l.m_n[0]; Node& b=*l.m_n[1]; const btVector3 del=b.m_x-a.m_x; const btScalar len=del.length2(); if (l.m_c1+len > SIMD_EPSILON) { const btScalar k=((l.m_c1-len)/(l.m_c0*(l.m_c1+len)))*kst; a.m_x-=del*(k*a.m_im); b.m_x+=del*(k*b.m_im); } } } } // void btSoftBody::VSolve_Links(btSoftBody* psb,btScalar kst) { for(int i=0,ni=psb->m_links.size();i<ni;++i) { Link& l=psb->m_links[i]; Node** n=l.m_n; const btScalar j=-btDot(l.m_c3,n[0]->m_v-n[1]->m_v)*l.m_c2*kst; n[0]->m_v+= l.m_c3*(j*n[0]->m_im); n[1]->m_v-= l.m_c3*(j*n[1]->m_im); } } // btSoftBody::psolver_t btSoftBody::getSolver(ePSolver::_ solver) { switch(solver) { case ePSolver::Anchors: return(&btSoftBody::PSolve_Anchors); case ePSolver::Linear: return(&btSoftBody::PSolve_Links); case ePSolver::RContacts: return(&btSoftBody::PSolve_RContacts); case ePSolver::SContacts: return(&btSoftBody::PSolve_SContacts); default: { } } return(0); } // btSoftBody::vsolver_t btSoftBody::getSolver(eVSolver::_ solver) { switch(solver) { case eVSolver::Linear: return(&btSoftBody::VSolve_Links); default: { } } return(0); } // void btSoftBody::defaultCollisionHandler(const btCollisionObjectWrapper* pcoWrap) { switch(m_cfg.collisions&fCollision::RVSmask) { case fCollision::SDF_RS: { btSoftColliders::CollideSDF_RS docollide; btRigidBody* prb1=(btRigidBody*) btRigidBody::upcast(pcoWrap->getCollisionObject()); btTransform wtr=pcoWrap->getWorldTransform(); const btTransform ctr=pcoWrap->getWorldTransform(); const btScalar timemargin=(wtr.getOrigin()-ctr.getOrigin()).length(); const btScalar basemargin=getCollisionShape()->getMargin(); btVector3 mins; btVector3 maxs; ATTRIBUTE_ALIGNED16(btDbvtVolume) volume; pcoWrap->getCollisionShape()->getAabb( pcoWrap->getWorldTransform(), mins, maxs); volume=btDbvtVolume::FromMM(mins,maxs); volume.Expand(btVector3(basemargin,basemargin,basemargin)); docollide.psb = this; docollide.m_colObj1Wrap = pcoWrap; docollide.m_rigidBody = prb1; docollide.dynmargin = basemargin+timemargin; docollide.stamargin = basemargin; m_ndbvt.collideTV(m_ndbvt.m_root,volume,docollide); } break; case fCollision::CL_RS: { btSoftColliders::CollideCL_RS collider; collider.ProcessColObj(this,pcoWrap); } break; } } // void btSoftBody::defaultCollisionHandler(btSoftBody* psb) { const int cf=m_cfg.collisions&psb->m_cfg.collisions; switch(cf&fCollision::SVSmask) { case fCollision::CL_SS: { //support self-collision if CL_SELF flag set if (this!=psb || psb->m_cfg.collisions&fCollision::CL_SELF) { btSoftColliders::CollideCL_SS docollide; docollide.ProcessSoftSoft(this,psb); } } break; case fCollision::VF_SS: { //only self-collision for Cluster, not Vertex-Face yet if (this!=psb) { btSoftColliders::CollideVF_SS docollide; /* common */ docollide.mrg= getCollisionShape()->getMargin()+ psb->getCollisionShape()->getMargin(); /* psb0 nodes vs psb1 faces */ docollide.psb[0]=this; docollide.psb[1]=psb; docollide.psb[0]->m_ndbvt.collideTT( docollide.psb[0]->m_ndbvt.m_root, docollide.psb[1]->m_fdbvt.m_root, docollide); /* psb1 nodes vs psb0 faces */ docollide.psb[0]=psb; docollide.psb[1]=this; docollide.psb[0]->m_ndbvt.collideTT( docollide.psb[0]->m_ndbvt.m_root, docollide.psb[1]->m_fdbvt.m_root, docollide); } } break; default: { } } } void btSoftBody::setWindVelocity( const btVector3 &velocity ) { m_windVelocity = velocity; } const btVector3& btSoftBody::getWindVelocity() { return m_windVelocity; } int btSoftBody::calculateSerializeBufferSize() const { int sz = sizeof(btSoftBodyData); return sz; } ///fills the dataBuffer and returns the struct name (and 0 on failure) const char* btSoftBody::serialize(void* dataBuffer, class btSerializer* serializer) const { btSoftBodyData* sbd = (btSoftBodyData*) dataBuffer; btCollisionObject::serialize(&sbd->m_collisionObjectData, serializer); btHashMap<btHashPtr,int> m_nodeIndexMap; sbd->m_numMaterials = m_materials.size(); sbd->m_materials = sbd->m_numMaterials? (SoftBodyMaterialData**) serializer->getUniquePointer((void*)&m_materials): 0; if (sbd->m_materials) { int sz = sizeof(SoftBodyMaterialData*); int numElem = sbd->m_numMaterials; btChunk* chunk = serializer->allocate(sz,numElem); //SoftBodyMaterialData** memPtr = chunk->m_oldPtr; SoftBodyMaterialData** memPtr = (SoftBodyMaterialData**)chunk->m_oldPtr; for (int i=0;i<numElem;i++,memPtr++) { btSoftBody::Material* mat = m_materials[i]; *memPtr = mat ? (SoftBodyMaterialData*)serializer->getUniquePointer((void*)mat) : 0; if (!serializer->findPointer(mat)) { //serialize it here btChunk* chunk = serializer->allocate(sizeof(SoftBodyMaterialData),1); SoftBodyMaterialData* memPtr = (SoftBodyMaterialData*)chunk->m_oldPtr; memPtr->m_flags = mat->m_flags; memPtr->m_angularStiffness = mat->m_kAST; memPtr->m_linearStiffness = mat->m_kLST; memPtr->m_volumeStiffness = mat->m_kVST; serializer->finalizeChunk(chunk,"SoftBodyMaterialData",BT_SBMATERIAL_CODE,mat); } } serializer->finalizeChunk(chunk,"SoftBodyMaterialData",BT_ARRAY_CODE,(void*) &m_materials); } sbd->m_numNodes = m_nodes.size(); sbd->m_nodes = sbd->m_numNodes ? (SoftBodyNodeData*)serializer->getUniquePointer((void*)&m_nodes): 0; if (sbd->m_nodes) { int sz = sizeof(SoftBodyNodeData); int numElem = sbd->m_numNodes; btChunk* chunk = serializer->allocate(sz,numElem); SoftBodyNodeData* memPtr = (SoftBodyNodeData*)chunk->m_oldPtr; for (int i=0;i<numElem;i++,memPtr++) { m_nodes[i].m_f.serializeFloat( memPtr->m_accumulatedForce); memPtr->m_area = m_nodes[i].m_area; memPtr->m_attach = m_nodes[i].m_battach; memPtr->m_inverseMass = m_nodes[i].m_im; memPtr->m_material = m_nodes[i].m_material? (SoftBodyMaterialData*)serializer->getUniquePointer((void*) m_nodes[i].m_material):0; m_nodes[i].m_n.serializeFloat(memPtr->m_normal); m_nodes[i].m_x.serializeFloat(memPtr->m_position); m_nodes[i].m_q.serializeFloat(memPtr->m_previousPosition); m_nodes[i].m_v.serializeFloat(memPtr->m_velocity); m_nodeIndexMap.insert(&m_nodes[i],i); } serializer->finalizeChunk(chunk,"SoftBodyNodeData",BT_SBNODE_CODE,(void*) &m_nodes); } sbd->m_numLinks = m_links.size(); sbd->m_links = sbd->m_numLinks? (SoftBodyLinkData*) serializer->getUniquePointer((void*)&m_links[0]):0; if (sbd->m_links) { int sz = sizeof(SoftBodyLinkData); int numElem = sbd->m_numLinks; btChunk* chunk = serializer->allocate(sz,numElem); SoftBodyLinkData* memPtr = (SoftBodyLinkData*)chunk->m_oldPtr; for (int i=0;i<numElem;i++,memPtr++) { memPtr->m_bbending = m_links[i].m_bbending; memPtr->m_material = m_links[i].m_material? (SoftBodyMaterialData*)serializer->getUniquePointer((void*) m_links[i].m_material):0; memPtr->m_nodeIndices[0] = m_links[i].m_n[0] ? m_links[i].m_n[0] - &m_nodes[0]: -1; memPtr->m_nodeIndices[1] = m_links[i].m_n[1] ? m_links[i].m_n[1] - &m_nodes[0]: -1; btAssert(memPtr->m_nodeIndices[0]<m_nodes.size()); btAssert(memPtr->m_nodeIndices[1]<m_nodes.size()); memPtr->m_restLength = m_links[i].m_rl; } serializer->finalizeChunk(chunk,"SoftBodyLinkData",BT_ARRAY_CODE,(void*) &m_links[0]); } sbd->m_numFaces = m_faces.size(); sbd->m_faces = sbd->m_numFaces? (SoftBodyFaceData*) serializer->getUniquePointer((void*)&m_faces[0]):0; if (sbd->m_faces) { int sz = sizeof(SoftBodyFaceData); int numElem = sbd->m_numFaces; btChunk* chunk = serializer->allocate(sz,numElem); SoftBodyFaceData* memPtr = (SoftBodyFaceData*)chunk->m_oldPtr; for (int i=0;i<numElem;i++,memPtr++) { memPtr->m_material = m_faces[i].m_material ? (SoftBodyMaterialData*) serializer->getUniquePointer((void*)m_faces[i].m_material): 0; m_faces[i].m_normal.serializeFloat( memPtr->m_normal); for (int j=0;j<3;j++) { memPtr->m_nodeIndices[j] = m_faces[i].m_n[j]? m_faces[i].m_n[j] - &m_nodes[0]: -1; } memPtr->m_restArea = m_faces[i].m_ra; } serializer->finalizeChunk(chunk,"SoftBodyFaceData",BT_ARRAY_CODE,(void*) &m_faces[0]); } sbd->m_numTetrahedra = m_tetras.size(); sbd->m_tetrahedra = sbd->m_numTetrahedra ? (SoftBodyTetraData*) serializer->getUniquePointer((void*)&m_tetras[0]):0; if (sbd->m_tetrahedra) { int sz = sizeof(SoftBodyTetraData); int numElem = sbd->m_numTetrahedra; btChunk* chunk = serializer->allocate(sz,numElem); SoftBodyTetraData* memPtr = (SoftBodyTetraData*)chunk->m_oldPtr; for (int i=0;i<numElem;i++,memPtr++) { for (int j=0;j<4;j++) { m_tetras[i].m_c0[j].serializeFloat( memPtr->m_c0[j] ); memPtr->m_nodeIndices[j] = m_tetras[j].m_n[j]? m_tetras[j].m_n[j]-&m_nodes[0] : -1; } memPtr->m_c1 = m_tetras[i].m_c1; memPtr->m_c2 = m_tetras[i].m_c2; memPtr->m_material = m_tetras[i].m_material ? (SoftBodyMaterialData*)serializer->getUniquePointer((void*) m_tetras[i].m_material): 0; memPtr->m_restVolume = m_tetras[i].m_rv; } serializer->finalizeChunk(chunk,"SoftBodyTetraData",BT_ARRAY_CODE,(void*) &m_tetras[0]); } sbd->m_numAnchors = m_anchors.size(); sbd->m_anchors = sbd->m_numAnchors ? (SoftRigidAnchorData*) serializer->getUniquePointer((void*)&m_anchors[0]):0; if (sbd->m_anchors) { int sz = sizeof(SoftRigidAnchorData); int numElem = sbd->m_numAnchors; btChunk* chunk = serializer->allocate(sz,numElem); SoftRigidAnchorData* memPtr = (SoftRigidAnchorData*)chunk->m_oldPtr; for (int i=0;i<numElem;i++,memPtr++) { m_anchors[i].m_c0.serializeFloat(memPtr->m_c0); m_anchors[i].m_c1.serializeFloat(memPtr->m_c1); memPtr->m_c2 = m_anchors[i].m_c2; m_anchors[i].m_local.serializeFloat(memPtr->m_localFrame); memPtr->m_nodeIndex = m_anchors[i].m_node? m_anchors[i].m_node-&m_nodes[0]: -1; memPtr->m_rigidBody = m_anchors[i].m_body? (btRigidBodyData*) serializer->getUniquePointer((void*)m_anchors[i].m_body): 0; btAssert(memPtr->m_nodeIndex < m_nodes.size()); } serializer->finalizeChunk(chunk,"SoftRigidAnchorData",BT_ARRAY_CODE,(void*) &m_anchors[0]); } sbd->m_config.m_dynamicFriction = m_cfg.kDF; sbd->m_config.m_baumgarte = m_cfg.kVCF; sbd->m_config.m_pressure = m_cfg.kPR; sbd->m_config.m_aeroModel = this->m_cfg.aeromodel; sbd->m_config.m_lift = m_cfg.kLF; sbd->m_config.m_drag = m_cfg.kDG; sbd->m_config.m_positionIterations = m_cfg.piterations; sbd->m_config.m_driftIterations = m_cfg.diterations; sbd->m_config.m_clusterIterations = m_cfg.citerations; sbd->m_config.m_velocityIterations = m_cfg.viterations; sbd->m_config.m_maxVolume = m_cfg.maxvolume; sbd->m_config.m_damping = m_cfg.kDP; sbd->m_config.m_poseMatch = m_cfg.kMT; sbd->m_config.m_collisionFlags = m_cfg.collisions; sbd->m_config.m_volume = m_cfg.kVC; sbd->m_config.m_rigidContactHardness = m_cfg.kCHR; sbd->m_config.m_kineticContactHardness = m_cfg.kKHR; sbd->m_config.m_softContactHardness = m_cfg.kSHR; sbd->m_config.m_anchorHardness = m_cfg.kAHR; sbd->m_config.m_timeScale = m_cfg.timescale; sbd->m_config.m_maxVolume = m_cfg.maxvolume; sbd->m_config.m_softRigidClusterHardness = m_cfg.kSRHR_CL; sbd->m_config.m_softKineticClusterHardness = m_cfg.kSKHR_CL; sbd->m_config.m_softSoftClusterHardness = m_cfg.kSSHR_CL; sbd->m_config.m_softRigidClusterImpulseSplit = m_cfg.kSR_SPLT_CL; sbd->m_config.m_softKineticClusterImpulseSplit = m_cfg.kSK_SPLT_CL; sbd->m_config.m_softSoftClusterImpulseSplit = m_cfg.kSS_SPLT_CL; //pose for shape matching { sbd->m_pose = (SoftBodyPoseData*)serializer->getUniquePointer((void*)&m_pose); int sz = sizeof(SoftBodyPoseData); btChunk* chunk = serializer->allocate(sz,1); SoftBodyPoseData* memPtr = (SoftBodyPoseData*)chunk->m_oldPtr; m_pose.m_aqq.serializeFloat(memPtr->m_aqq); memPtr->m_bframe = m_pose.m_bframe; memPtr->m_bvolume = m_pose.m_bvolume; m_pose.m_com.serializeFloat(memPtr->m_com); memPtr->m_numPositions = m_pose.m_pos.size(); memPtr->m_positions = memPtr->m_numPositions ? (btVector3FloatData*)serializer->getUniquePointer((void*)&m_pose.m_pos[0]): 0; if (memPtr->m_numPositions) { int numElem = memPtr->m_numPositions; int sz = sizeof(btVector3Data); btChunk* chunk = serializer->allocate(sz,numElem); btVector3FloatData* memPtr = (btVector3FloatData*)chunk->m_oldPtr; for (int i=0;i<numElem;i++,memPtr++) { m_pose.m_pos[i].serializeFloat(*memPtr); } serializer->finalizeChunk(chunk,"btVector3FloatData",BT_ARRAY_CODE,(void*)&m_pose.m_pos[0]); } memPtr->m_restVolume = m_pose.m_volume; m_pose.m_rot.serializeFloat(memPtr->m_rot); m_pose.m_scl.serializeFloat(memPtr->m_scale); memPtr->m_numWeigts = m_pose.m_wgh.size(); memPtr->m_weights = memPtr->m_numWeigts? (float*) serializer->getUniquePointer((void*) &m_pose.m_wgh[0]) : 0; if (memPtr->m_numWeigts) { int numElem = memPtr->m_numWeigts; int sz = sizeof(float); btChunk* chunk = serializer->allocate(sz,numElem); float* memPtr = (float*) chunk->m_oldPtr; for (int i=0;i<numElem;i++,memPtr++) { *memPtr = m_pose.m_wgh[i]; } serializer->finalizeChunk(chunk,"float",BT_ARRAY_CODE,(void*)&m_pose.m_wgh[0]); } serializer->finalizeChunk(chunk,"SoftBodyPoseData",BT_ARRAY_CODE,(void*)&m_pose); } //clusters for convex-cluster collision detection sbd->m_numClusters = m_clusters.size(); sbd->m_clusters = sbd->m_numClusters? (SoftBodyClusterData*) serializer->getUniquePointer((void*)m_clusters[0]) : 0; if (sbd->m_numClusters) { int numElem = sbd->m_numClusters; int sz = sizeof(SoftBodyClusterData); btChunk* chunk = serializer->allocate(sz,numElem); SoftBodyClusterData* memPtr = (SoftBodyClusterData*) chunk->m_oldPtr; for (int i=0;i<numElem;i++,memPtr++) { memPtr->m_adamping= m_clusters[i]->m_adamping; m_clusters[i]->m_av.serializeFloat(memPtr->m_av); memPtr->m_clusterIndex = m_clusters[i]->m_clusterIndex; memPtr->m_collide = m_clusters[i]->m_collide; m_clusters[i]->m_com.serializeFloat(memPtr->m_com); memPtr->m_containsAnchor = m_clusters[i]->m_containsAnchor; m_clusters[i]->m_dimpulses[0].serializeFloat(memPtr->m_dimpulses[0]); m_clusters[i]->m_dimpulses[1].serializeFloat(memPtr->m_dimpulses[1]); m_clusters[i]->m_framexform.serializeFloat(memPtr->m_framexform); memPtr->m_idmass = m_clusters[i]->m_idmass; memPtr->m_imass = m_clusters[i]->m_imass; m_clusters[i]->m_invwi.serializeFloat(memPtr->m_invwi); memPtr->m_ldamping = m_clusters[i]->m_ldamping; m_clusters[i]->m_locii.serializeFloat(memPtr->m_locii); m_clusters[i]->m_lv.serializeFloat(memPtr->m_lv); memPtr->m_matching = m_clusters[i]->m_matching; memPtr->m_maxSelfCollisionImpulse = m_clusters[i]->m_maxSelfCollisionImpulse; memPtr->m_ndamping = m_clusters[i]->m_ndamping; memPtr->m_ldamping = m_clusters[i]->m_ldamping; memPtr->m_adamping = m_clusters[i]->m_adamping; memPtr->m_selfCollisionImpulseFactor = m_clusters[i]->m_selfCollisionImpulseFactor; memPtr->m_numFrameRefs = m_clusters[i]->m_framerefs.size(); memPtr->m_numMasses = m_clusters[i]->m_masses.size(); memPtr->m_numNodes = m_clusters[i]->m_nodes.size(); memPtr->m_nvimpulses = m_clusters[i]->m_nvimpulses; m_clusters[i]->m_vimpulses[0].serializeFloat(memPtr->m_vimpulses[0]); m_clusters[i]->m_vimpulses[1].serializeFloat(memPtr->m_vimpulses[1]); memPtr->m_ndimpulses = m_clusters[i]->m_ndimpulses; memPtr->m_framerefs = memPtr->m_numFrameRefs? (btVector3FloatData*)serializer->getUniquePointer((void*)&m_clusters[i]->m_framerefs[0]) : 0; if (memPtr->m_framerefs) { int numElem = memPtr->m_numFrameRefs; int sz = sizeof(btVector3FloatData); btChunk* chunk = serializer->allocate(sz,numElem); btVector3FloatData* memPtr = (btVector3FloatData*) chunk->m_oldPtr; for (int j=0;j<numElem;j++,memPtr++) { m_clusters[i]->m_framerefs[j].serializeFloat(*memPtr); } serializer->finalizeChunk(chunk,"btVector3FloatData",BT_ARRAY_CODE,(void*)&m_clusters[i]->m_framerefs[0]); } memPtr->m_masses = memPtr->m_numMasses ? (float*) serializer->getUniquePointer((void*)&m_clusters[i]->m_masses[0]): 0; if (memPtr->m_masses) { int numElem = memPtr->m_numMasses; int sz = sizeof(float); btChunk* chunk = serializer->allocate(sz,numElem); float* memPtr = (float*) chunk->m_oldPtr; for (int j=0;j<numElem;j++,memPtr++) { *memPtr = m_clusters[i]->m_masses[j]; } serializer->finalizeChunk(chunk,"float",BT_ARRAY_CODE,(void*)&m_clusters[i]->m_masses[0]); } memPtr->m_nodeIndices = memPtr->m_numNodes ? (int*) serializer->getUniquePointer((void*) &m_clusters[i]->m_nodes) : 0; if (memPtr->m_nodeIndices ) { int numElem = memPtr->m_numMasses; int sz = sizeof(int); btChunk* chunk = serializer->allocate(sz,numElem); int* memPtr = (int*) chunk->m_oldPtr; for (int j=0;j<numElem;j++,memPtr++) { int* indexPtr = m_nodeIndexMap.find(m_clusters[i]->m_nodes[j]); btAssert(indexPtr); *memPtr = *indexPtr; } serializer->finalizeChunk(chunk,"int",BT_ARRAY_CODE,(void*)&m_clusters[i]->m_nodes); } } serializer->finalizeChunk(chunk,"SoftBodyClusterData",BT_ARRAY_CODE,(void*)m_clusters[0]); } sbd->m_numJoints = m_joints.size(); sbd->m_joints = m_joints.size()? (btSoftBodyJointData*) serializer->getUniquePointer((void*)&m_joints[0]) : 0; if (sbd->m_joints) { int sz = sizeof(btSoftBodyJointData); int numElem = m_joints.size(); btChunk* chunk = serializer->allocate(sz,numElem); btSoftBodyJointData* memPtr = (btSoftBodyJointData*)chunk->m_oldPtr; for (int i=0;i<numElem;i++,memPtr++) { memPtr->m_jointType = (int)m_joints[i]->Type(); m_joints[i]->m_refs[0].serializeFloat(memPtr->m_refs[0]); m_joints[i]->m_refs[1].serializeFloat(memPtr->m_refs[1]); memPtr->m_cfm = m_joints[i]->m_cfm; memPtr->m_erp = m_joints[i]->m_erp; memPtr->m_split = m_joints[i]->m_split; memPtr->m_delete = m_joints[i]->m_delete; for (int j=0;j<4;j++) { memPtr->m_relPosition[0].m_floats[j] = 0.f; memPtr->m_relPosition[1].m_floats[j] = 0.f; } memPtr->m_bodyA = 0; memPtr->m_bodyB = 0; if (m_joints[i]->m_bodies[0].m_soft) { memPtr->m_bodyAtype = BT_JOINT_SOFT_BODY_CLUSTER; memPtr->m_bodyA = serializer->getUniquePointer((void*)m_joints[i]->m_bodies[0].m_soft); } if (m_joints[i]->m_bodies[0].m_collisionObject) { memPtr->m_bodyAtype = BT_JOINT_COLLISION_OBJECT; memPtr->m_bodyA = serializer->getUniquePointer((void*)m_joints[i]->m_bodies[0].m_collisionObject); } if (m_joints[i]->m_bodies[0].m_rigid) { memPtr->m_bodyAtype = BT_JOINT_RIGID_BODY; memPtr->m_bodyA = serializer->getUniquePointer((void*)m_joints[i]->m_bodies[0].m_rigid); } if (m_joints[i]->m_bodies[1].m_soft) { memPtr->m_bodyBtype = BT_JOINT_SOFT_BODY_CLUSTER; memPtr->m_bodyB = serializer->getUniquePointer((void*)m_joints[i]->m_bodies[1].m_soft); } if (m_joints[i]->m_bodies[1].m_collisionObject) { memPtr->m_bodyBtype = BT_JOINT_COLLISION_OBJECT; memPtr->m_bodyB = serializer->getUniquePointer((void*)m_joints[i]->m_bodies[1].m_collisionObject); } if (m_joints[i]->m_bodies[1].m_rigid) { memPtr->m_bodyBtype = BT_JOINT_RIGID_BODY; memPtr->m_bodyB = serializer->getUniquePointer((void*)m_joints[i]->m_bodies[1].m_rigid); } } serializer->finalizeChunk(chunk,"btSoftBodyJointData",BT_ARRAY_CODE,(void*) &m_joints[0]); } return btSoftBodyDataName; }
0
0.992639
1
0.992639
game-dev
MEDIA
0.725229
game-dev
0.978432
1
0.978432
microsoft/TestApi
4,647
Releases/TestApi_v0.6/Sources/TestApiCore/Code/Text/RegexSetNode.cs
// (c) Copyright Microsoft Corporation. // This source is subject to the Microsoft Public License (Ms-PL). // Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details. // All other rights reserved. using System; namespace Microsoft.Test.Text { /// <summary> /// Represents a set of characters inside [ ] /// For example [a-z]. /// </summary> class RegexSetNode : RegexNode { private int mMapSize = 128; private byte[] mMap = new byte[128]; //Indicates which characters are present in the set private bool mPositiveSet; //If false, the characters added by the user are excluded private int mNumChoices; //Reflects number of possible characters that can be chosen in the set public RegexSetNode(bool positiveSet) { if (RegexCompiler.IsInvalidSection) { RegexCompiler.InvalidableNodes.Add(this); } mPositiveSet = positiveSet; mNumChoices = mPositiveSet ? 0 : mMapSize; //In a negative set all characters can be chosen } //Expands the set range to cover unicode characters private void ExpandToUnicodeRange() { byte[] mNewMap = new byte[char.MaxValue + 1]; Array.Copy(mMap, 0, mNewMap, 0, 128); if (!mPositiveSet) mNumChoices += char.MaxValue + 1 - 128; mMapSize = char.MaxValue + 1; mMap = mNewMap; } public void AddChars(string chars) { //mark the added characters and update the number of available choices foreach (char c in chars.ToCharArray()) { if (c > mMapSize - 1) ExpandToUnicodeRange(); if (mMap[c] == 0) { mMap[c] = 1; mNumChoices += mPositiveSet ? 1 : -1; } } //check if this set still has invalid characters available if ((mPositiveSet && mNumChoices == mMapSize) || (!mPositiveSet && mNumChoices == 0)) { //can never be invalid RegexCompiler.InvalidableNodes.Remove(this); } } //Add the chars in alphabet from start to end to the set public void AddRange(char start, char end) { RegexNode.AssertParse((start < end) && end <= char.MaxValue, "Invalid range specified in char set"); if (end > mMapSize) ExpandToUnicodeRange(); //mark the added characters and update the number of available choices for (long c = start; c <= end; c++) { if (mMap[c] == 0) { mMap[c] = 1; mNumChoices += mPositiveSet ? 1 : -1; } } //check if this set still has invalid characters available if ((mPositiveSet && mNumChoices == mMapSize) || (!mPositiveSet && mNumChoices == 0)) { //can never be invalid RegexCompiler.InvalidableNodes.Remove(this); } } public override string Generate(Random random) { if (this == RegexCompiler.InvalidNode) { RegexNode.AssertParse(mNumChoices > 0, "No valid range specified in char set"); //select from the elements that are not available (elements that are invalid) int randIndex = random.Next(mMapSize - mNumChoices); int i = -1; while (randIndex >= 0) //seek to the available element { i++; //invert positive and negative sets if ((mPositiveSet && mMap[i] == 0) || (!mPositiveSet && mMap[i] == 1)) randIndex--; } return Convert.ToChar(i).ToString(); } else { RegexNode.AssertParse(mNumChoices > 0, "No valid range specified in char set"); //select from the elements that are available int randIndex = random.Next(mNumChoices); int i = -1; while (randIndex >= 0) //seek to the available element { i++; if ((mPositiveSet && mMap[i] == 1) || (!mPositiveSet && mMap[i] == 0)) randIndex--; } return Convert.ToChar(i).ToString(); } } } }
0
0.96002
1
0.96002
game-dev
MEDIA
0.468078
game-dev
0.917083
1
0.917083
modernuo/ModernUO
1,427
Projects/UOContent/Mobiles/Townfolk/EscortableMage.cs
using ModernUO.Serialization; using Server.Items; namespace Server.Mobiles; [SerializationGenerator(0, false)] public partial class EscortableMage : BaseEscortable { [Constructible] public EscortableMage() { Title = "the mage"; SetSkill(SkillName.EvalInt, 80.0, 100.0); SetSkill(SkillName.Inscribe, 80.0, 100.0); SetSkill(SkillName.Magery, 80.0, 100.0); SetSkill(SkillName.Meditation, 80.0, 100.0); SetSkill(SkillName.MagicResist, 80.0, 100.0); } public override bool CanTeach => true; public override bool ClickTitle => false; // Do not display 'the mage' when single-clicking private static int GetRandomHue() { return Utility.Random(5) switch { 0 => Utility.RandomBlueHue(), 1 => Utility.RandomGreenHue(), 2 => Utility.RandomRedHue(), 3 => Utility.RandomYellowHue(), 4 => Utility.RandomNeutralHue(), _ => Utility.RandomBlueHue() }; } public override void InitOutfit() { AddItem(new Robe(GetRandomHue())); var lowHue = GetRandomHue(); AddItem(new ShortPants(lowHue)); if (Female) { AddItem(new ThighBoots(lowHue)); } else { AddItem(new Boots(lowHue)); } Utility.AssignRandomHair(this); PackGold(200, 250); } }
0
0.804511
1
0.804511
game-dev
MEDIA
0.979303
game-dev
0.894956
1
0.894956
TheGreyGhost/MinecraftByExample
8,096
src/main/java/minecraftbyexample/mbe06_redstone/input_and_output/BlockRedstoneMeter.java
package minecraftbyexample.mbe06_redstone.input_and_output; import net.minecraft.block.Block; import net.minecraft.block.BlockRenderType; import net.minecraft.block.BlockState; import net.minecraft.block.material.Material; import net.minecraft.entity.LivingEntity; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.Direction; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.shapes.ISelectionContext; import net.minecraft.util.math.shapes.VoxelShape; import net.minecraft.util.math.shapes.VoxelShapes; import net.minecraft.world.IBlockReader; import net.minecraft.world.World; import net.minecraft.world.server.ServerWorld; import java.util.Random; import static net.minecraft.util.Direction.*; /** * User: The Grey Ghost * Date: 27/11/2015 * * BlockRedstoneMeter is a simple block with an associated TileEntity to render the block's power level. * It gets weak power from all directions except UP. * The meter provides weak power to the block UP - if a lamp is placed on top of the meter, it will flash * at a speed related to the input power. * We use a TileEntity because our block needs to store the input power level, for later use when others call the getWeakPower(). * for the reason why, see http://greyminecraftcoder.blogspot.com/2020/05/redstone-1152.html */ public class BlockRedstoneMeter extends Block { public BlockRedstoneMeter() { super(Block.Properties.create(Material.IRON)); } @Override public boolean hasTileEntity(BlockState state) { return true; } // Called when the block is placed or loaded client side to get the tile entity for the block // Should return a new instance of the tile entity for the block @Override public TileEntity createTileEntity(BlockState state, IBlockReader blockReader) {return new TileEntityRedstoneMeter();} // ------ methods relevant to redstone // The methods below are used to provide power to neighbours. /** * This block can provide power * @return */ @Override public boolean canProvidePower(BlockState iBlockState) { return true; } /** How much weak power does this block provide to the adjacent block? * The meter provides weak power to the block above it. * The meter flashes the power according to how strong the input signals are * See https://greyminecraftcoder.blogspot.com/2020/05/redstone-1152.html for more information * @param blockReader * @param pos the position of this block * @param state the blockstate of this block * @param directionFromNeighborToThis eg EAST means that this is to the EAST of the block which is asking for weak power * @return The power provided [0 - 15] */ @Override public int getWeakPower(BlockState state, IBlockReader blockReader, BlockPos pos, Direction directionFromNeighborToThis) { if (directionFromNeighborToThis != DOWN) { return 0; } boolean isOutputOn = false; TileEntity tileentity = blockReader.getTileEntity(pos); if (tileentity instanceof TileEntityRedstoneMeter) { // prevent a crash if not the right type, or is null TileEntityRedstoneMeter tileEntityRedstoneMeter = (TileEntityRedstoneMeter) tileentity; isOutputOn = tileEntityRedstoneMeter.getOutputState(); } final int OUTPUT_POWER_WHEN_ON = 15; return isOutputOn ? OUTPUT_POWER_WHEN_ON : 0; } /** * The redstone meter doesn't provide strong power to any other block. * @param worldIn * @param pos the position of this block * @param state the blockstate of this block * @param directionFromNeighborToThis eg EAST means that this is to the EAST of the block which is asking for strong power * @return The power provided [0 - 15] */ @Override public int getStrongPower(BlockState state, IBlockReader worldIn, BlockPos pos, Direction directionFromNeighborToThis) { return 0; } // Retrieve the current input power level of the meter - the maximum of the five sides EAST, WEST, NORTH, SOUTH, DOWN // Don't look UP private int getPowerLevelInputFromNeighbours(World world, BlockPos pos) { // int powerLevel = world.getRedstonePowerFromNeighbors(pos); // if input can come from any side, use this line int maxPowerFound = 0; Direction [] directions = new Direction[]{DOWN, WEST, EAST, NORTH, SOUTH}; for (Direction whichFace : directions) { BlockPos neighborPos = pos.offset(whichFace); int powerLevel = world.getRedstonePower(neighborPos, whichFace); maxPowerFound = Math.max(powerLevel, maxPowerFound); } return maxPowerFound; } // ------ various block methods that react to changes and are responsible for updating the redstone power information // Called when a neighbouring block changes. // Only called on the server side- so it doesn't help us alter rendering on the client side. @Override public void neighborChanged(BlockState currentState, World world, BlockPos pos, Block blockIn, BlockPos fromPos, boolean isMoving) { calculatePowerInputAndNotifyNeighbors(world, pos); } // Our flashing output uses scheduled ticks to toggle the output. // Scheduling of ticks is by calling world.scheduleTick(pos, block, numberOfTicksToDelay); see ScheduledTogglingOutput // @Override public void tick(BlockState state, ServerWorld world, BlockPos pos, Random rand) { TileEntity te = world.getTileEntity(pos); if (te instanceof TileEntityRedstoneMeter) { TileEntityRedstoneMeter tileEntityRedstoneMeter = (TileEntityRedstoneMeter)te; boolean currentOutputState = tileEntityRedstoneMeter.getOutputState(); tileEntityRedstoneMeter.onScheduledTick(world, pos, state.getBlock()); boolean newOutputState = tileEntityRedstoneMeter.getOutputState(); if (newOutputState != currentOutputState) { world.notifyNeighborsOfStateChange(pos, this); } } } /** * Called by ItemBlocks after a block is set in the world, to allow post-place logic */ @Override public void onBlockPlacedBy(World worldIn, BlockPos pos, BlockState state, LivingEntity placer, ItemStack stack) { // not needed here } // not needed for this block because we have only one blockstate @Override public void onBlockAdded(BlockState state, World worldIn, BlockPos pos, BlockState oldState, boolean isMoving) { super.onBlockAdded(state, worldIn, pos, oldState, isMoving); } // not needed for this block because we have only one blockstate public void onReplaced(BlockState state, World worldIn, BlockPos pos, BlockState newState, boolean isMoving) { super.onReplaced(state, worldIn, pos, newState, isMoving); } private void calculatePowerInputAndNotifyNeighbors(World world, BlockPos pos) { // calculate the power level from neighbours and store in our TileEntity for later use in getWeakPower() int powerLevel = getPowerLevelInputFromNeighbours(world, pos); TileEntity tileentity = world.getTileEntity(pos); if (tileentity instanceof TileEntityRedstoneMeter) { // prevent a crash if not the right type, or is null TileEntityRedstoneMeter tileEntityRedstoneMeter = (TileEntityRedstoneMeter) tileentity; boolean currentOutputState = tileEntityRedstoneMeter.getOutputState(); tileEntityRedstoneMeter.setPowerLevelServer(powerLevel); // this method will also schedule the next tick using call world.scheduleTick(pos, block, delay); if (currentOutputState != tileEntityRedstoneMeter.getOutputState()) { world.notifyNeighborsOfStateChange(pos, this); } } } //----- methods related to the block's appearance (see MBE01_BLOCK_SIMPLE and MBE02_BLOCK_PARTIAL) @Override public VoxelShape getShape(BlockState state, IBlockReader worldIn, BlockPos pos, ISelectionContext context) { return VoxelShapes.fullCube(); } // render using a BakedModel // not strictly required because the default (super method) is MODEL. @Override public BlockRenderType getRenderType(BlockState iBlockState) { return BlockRenderType.MODEL; } }
0
0.910446
1
0.910446
game-dev
MEDIA
0.99592
game-dev
0.938481
1
0.938481
chai3d/chai3d
12,279
modules/Bullet/externals/bullet/src/BulletCollision/NarrowPhaseCollision/btGjkPairDetector.cpp
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "btGjkPairDetector.h" #include "BulletCollision/CollisionShapes/btConvexShape.h" #include "BulletCollision/NarrowPhaseCollision/btSimplexSolverInterface.h" #include "BulletCollision/NarrowPhaseCollision/btConvexPenetrationDepthSolver.h" #if defined(DEBUG) || defined (_DEBUG) //#define TEST_NON_VIRTUAL 1 #include <stdio.h> //for debug printf #ifdef __SPU__ #include <spu_printf.h> #define printf spu_printf #endif //__SPU__ #endif //must be above the machine epsilon #define REL_ERROR2 btScalar(1.0e-6) //temp globals, to improve GJK/EPA/penetration calculations int gNumDeepPenetrationChecks = 0; int gNumGjkChecks = 0; btGjkPairDetector::btGjkPairDetector(const btConvexShape* objectA,const btConvexShape* objectB,btSimplexSolverInterface* simplexSolver,btConvexPenetrationDepthSolver* penetrationDepthSolver) :m_cachedSeparatingAxis(btScalar(0.),btScalar(1.),btScalar(0.)), m_penetrationDepthSolver(penetrationDepthSolver), m_simplexSolver(simplexSolver), m_minkowskiA(objectA), m_minkowskiB(objectB), m_shapeTypeA(objectA->getShapeType()), m_shapeTypeB(objectB->getShapeType()), m_marginA(objectA->getMargin()), m_marginB(objectB->getMargin()), m_ignoreMargin(false), m_lastUsedMethod(-1), m_catchDegeneracies(1), m_fixContactNormalDirection(1) { } btGjkPairDetector::btGjkPairDetector(const btConvexShape* objectA,const btConvexShape* objectB,int shapeTypeA,int shapeTypeB,btScalar marginA, btScalar marginB, btSimplexSolverInterface* simplexSolver,btConvexPenetrationDepthSolver* penetrationDepthSolver) :m_cachedSeparatingAxis(btScalar(0.),btScalar(1.),btScalar(0.)), m_penetrationDepthSolver(penetrationDepthSolver), m_simplexSolver(simplexSolver), m_minkowskiA(objectA), m_minkowskiB(objectB), m_shapeTypeA(shapeTypeA), m_shapeTypeB(shapeTypeB), m_marginA(marginA), m_marginB(marginB), m_ignoreMargin(false), m_lastUsedMethod(-1), m_catchDegeneracies(1), m_fixContactNormalDirection(1) { } void btGjkPairDetector::getClosestPoints(const ClosestPointInput& input,Result& output,class btIDebugDraw* debugDraw,bool swapResults) { (void)swapResults; getClosestPointsNonVirtual(input,output,debugDraw); } #ifdef __SPU__ void btGjkPairDetector::getClosestPointsNonVirtual(const ClosestPointInput& input,Result& output,class btIDebugDraw* debugDraw) #else void btGjkPairDetector::getClosestPointsNonVirtual(const ClosestPointInput& input, Result& output, class btIDebugDraw* debugDraw) #endif { m_cachedSeparatingDistance = 0.f; btScalar distance=btScalar(0.); btVector3 normalInB(btScalar(0.),btScalar(0.),btScalar(0.)); btVector3 pointOnA,pointOnB; btTransform localTransA = input.m_transformA; btTransform localTransB = input.m_transformB; btVector3 positionOffset=(localTransA.getOrigin() + localTransB.getOrigin()) * btScalar(0.5); localTransA.getOrigin() -= positionOffset; localTransB.getOrigin() -= positionOffset; bool check2d = m_minkowskiA->isConvex2d() && m_minkowskiB->isConvex2d(); btScalar marginA = m_marginA; btScalar marginB = m_marginB; gNumGjkChecks++; //for CCD we don't use margins if (m_ignoreMargin) { marginA = btScalar(0.); marginB = btScalar(0.); } m_curIter = 0; int gGjkMaxIter = 1000;//this is to catch invalid input, perhaps check for #NaN? m_cachedSeparatingAxis.setValue(0,1,0); bool isValid = false; bool checkSimplex = false; bool checkPenetration = true; m_degenerateSimplex = 0; m_lastUsedMethod = -1; { btScalar squaredDistance = BT_LARGE_FLOAT; btScalar delta = btScalar(0.); btScalar margin = marginA + marginB; m_simplexSolver->reset(); for ( ; ; ) //while (true) { btVector3 seperatingAxisInA = (-m_cachedSeparatingAxis)* input.m_transformA.getBasis(); btVector3 seperatingAxisInB = m_cachedSeparatingAxis* input.m_transformB.getBasis(); btVector3 pInA = m_minkowskiA->localGetSupportVertexWithoutMarginNonVirtual(seperatingAxisInA); btVector3 qInB = m_minkowskiB->localGetSupportVertexWithoutMarginNonVirtual(seperatingAxisInB); btVector3 pWorld = localTransA(pInA); btVector3 qWorld = localTransB(qInB); if (check2d) { pWorld[2] = 0.f; qWorld[2] = 0.f; } btVector3 w = pWorld - qWorld; delta = m_cachedSeparatingAxis.dot(w); // potential exit, they don't overlap if ((delta > btScalar(0.0)) && (delta * delta > squaredDistance * input.m_maximumDistanceSquared)) { m_degenerateSimplex = 10; checkSimplex=true; //checkPenetration = false; break; } //exit 0: the new point is already in the simplex, or we didn't come any closer if (m_simplexSolver->inSimplex(w)) { m_degenerateSimplex = 1; checkSimplex = true; break; } // are we getting any closer ? btScalar f0 = squaredDistance - delta; btScalar f1 = squaredDistance * REL_ERROR2; if (f0 <= f1) { if (f0 <= btScalar(0.)) { m_degenerateSimplex = 2; } else { m_degenerateSimplex = 11; } checkSimplex = true; break; } //add current vertex to simplex m_simplexSolver->addVertex(w, pWorld, qWorld); btVector3 newCachedSeparatingAxis; //calculate the closest point to the origin (update vector v) if (!m_simplexSolver->closest(newCachedSeparatingAxis)) { m_degenerateSimplex = 3; checkSimplex = true; break; } if(newCachedSeparatingAxis.length2()<REL_ERROR2) { m_cachedSeparatingAxis = newCachedSeparatingAxis; m_degenerateSimplex = 6; checkSimplex = true; break; } btScalar previousSquaredDistance = squaredDistance; squaredDistance = newCachedSeparatingAxis.length2(); #if 0 ///warning: this termination condition leads to some problems in 2d test case see Bullet/Demos/Box2dDemo if (squaredDistance>previousSquaredDistance) { m_degenerateSimplex = 7; squaredDistance = previousSquaredDistance; checkSimplex = false; break; } #endif // //redundant m_simplexSolver->compute_points(pointOnA, pointOnB); //are we getting any closer ? if (previousSquaredDistance - squaredDistance <= SIMD_EPSILON * previousSquaredDistance) { // m_simplexSolver->backup_closest(m_cachedSeparatingAxis); checkSimplex = true; m_degenerateSimplex = 12; break; } m_cachedSeparatingAxis = newCachedSeparatingAxis; //degeneracy, this is typically due to invalid/uninitialized worldtransforms for a btCollisionObject if (m_curIter++ > gGjkMaxIter) { #if defined(DEBUG) || defined (_DEBUG) printf("btGjkPairDetector maxIter exceeded:%i\n",m_curIter); printf("sepAxis=(%f,%f,%f), squaredDistance = %f, shapeTypeA=%i,shapeTypeB=%i\n", m_cachedSeparatingAxis.getX(), m_cachedSeparatingAxis.getY(), m_cachedSeparatingAxis.getZ(), squaredDistance, m_minkowskiA->getShapeType(), m_minkowskiB->getShapeType()); #endif break; } bool check = (!m_simplexSolver->fullSimplex()); //bool check = (!m_simplexSolver->fullSimplex() && squaredDistance > SIMD_EPSILON * m_simplexSolver->maxVertex()); if (!check) { //do we need this backup_closest here ? // m_simplexSolver->backup_closest(m_cachedSeparatingAxis); m_degenerateSimplex = 13; break; } } if (checkSimplex) { m_simplexSolver->compute_points(pointOnA, pointOnB); normalInB = m_cachedSeparatingAxis; btScalar lenSqr =m_cachedSeparatingAxis.length2(); //valid normal if (lenSqr < 0.0001) { m_degenerateSimplex = 5; } if (lenSqr > SIMD_EPSILON*SIMD_EPSILON) { btScalar rlen = btScalar(1.) / btSqrt(lenSqr ); normalInB *= rlen; //normalize btScalar s = btSqrt(squaredDistance); btAssert(s > btScalar(0.0)); pointOnA -= m_cachedSeparatingAxis * (marginA / s); pointOnB += m_cachedSeparatingAxis * (marginB / s); distance = ((btScalar(1.)/rlen) - margin); isValid = true; m_lastUsedMethod = 1; } else { m_lastUsedMethod = 2; } } bool catchDegeneratePenetrationCase = (m_catchDegeneracies && m_penetrationDepthSolver && m_degenerateSimplex && ((distance+margin) < 0.01)); //if (checkPenetration && !isValid) if (checkPenetration && (!isValid || catchDegeneratePenetrationCase )) { //penetration case //if there is no way to handle penetrations, bail out if (m_penetrationDepthSolver) { // Penetration depth case. btVector3 tmpPointOnA,tmpPointOnB; gNumDeepPenetrationChecks++; m_cachedSeparatingAxis.setZero(); bool isValid2 = m_penetrationDepthSolver->calcPenDepth( *m_simplexSolver, m_minkowskiA,m_minkowskiB, localTransA,localTransB, m_cachedSeparatingAxis, tmpPointOnA, tmpPointOnB, debugDraw ); if (isValid2) { btVector3 tmpNormalInB = tmpPointOnB-tmpPointOnA; btScalar lenSqr = tmpNormalInB.length2(); if (lenSqr <= (SIMD_EPSILON*SIMD_EPSILON)) { tmpNormalInB = m_cachedSeparatingAxis; lenSqr = m_cachedSeparatingAxis.length2(); } if (lenSqr > (SIMD_EPSILON*SIMD_EPSILON)) { tmpNormalInB /= btSqrt(lenSqr); btScalar distance2 = -(tmpPointOnA-tmpPointOnB).length(); //only replace valid penetrations when the result is deeper (check) if (!isValid || (distance2 < distance)) { distance = distance2; pointOnA = tmpPointOnA; pointOnB = tmpPointOnB; normalInB = tmpNormalInB; isValid = true; m_lastUsedMethod = 3; } else { m_lastUsedMethod = 8; } } else { m_lastUsedMethod = 9; } } else { ///this is another degenerate case, where the initial GJK calculation reports a degenerate case ///EPA reports no penetration, and the second GJK (using the supporting vector without margin) ///reports a valid positive distance. Use the results of the second GJK instead of failing. ///thanks to Jacob.Langford for the reproduction case ///http://code.google.com/p/bullet/issues/detail?id=250 if (m_cachedSeparatingAxis.length2() > btScalar(0.)) { btScalar distance2 = (tmpPointOnA-tmpPointOnB).length()-margin; //only replace valid distances when the distance is less if (!isValid || (distance2 < distance)) { distance = distance2; pointOnA = tmpPointOnA; pointOnB = tmpPointOnB; pointOnA -= m_cachedSeparatingAxis * marginA ; pointOnB += m_cachedSeparatingAxis * marginB ; normalInB = m_cachedSeparatingAxis; normalInB.normalize(); isValid = true; m_lastUsedMethod = 6; } else { m_lastUsedMethod = 5; } } } } } } if (isValid && ((distance < 0) || (distance*distance < input.m_maximumDistanceSquared))) { m_cachedSeparatingAxis = normalInB; m_cachedSeparatingDistance = distance; output.addContactPoint( normalInB, pointOnB+positionOffset, distance); } }
0
0.966685
1
0.966685
game-dev
MEDIA
0.947607
game-dev
0.984896
1
0.984896
50C4L/portal-cpp-opengl
2,562
thirdparty/include/bullet/BulletCollision/BroadphaseCollision/btCollisionAlgorithm.h
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef BT_COLLISION_ALGORITHM_H #define BT_COLLISION_ALGORITHM_H #include "LinearMath/btScalar.h" #include "LinearMath/btAlignedObjectArray.h" struct btBroadphaseProxy; class btDispatcher; class btManifoldResult; class btCollisionObject; struct btCollisionObjectWrapper; struct btDispatcherInfo; class btPersistentManifold; typedef btAlignedObjectArray<btPersistentManifold*> btManifoldArray; struct btCollisionAlgorithmConstructionInfo { btCollisionAlgorithmConstructionInfo() : m_dispatcher1(0), m_manifold(0) { } btCollisionAlgorithmConstructionInfo(btDispatcher* dispatcher, int temp) : m_dispatcher1(dispatcher) { (void)temp; } btDispatcher* m_dispatcher1; btPersistentManifold* m_manifold; // int getDispatcherId(); }; ///btCollisionAlgorithm is an collision interface that is compatible with the Broadphase and btDispatcher. ///It is persistent over frames class btCollisionAlgorithm { protected: btDispatcher* m_dispatcher; protected: // int getDispatcherId(); public: btCollisionAlgorithm(){}; btCollisionAlgorithm(const btCollisionAlgorithmConstructionInfo& ci); virtual ~btCollisionAlgorithm(){}; virtual void processCollision(const btCollisionObjectWrapper* body0Wrap, const btCollisionObjectWrapper* body1Wrap, const btDispatcherInfo& dispatchInfo, btManifoldResult* resultOut) = 0; virtual btScalar calculateTimeOfImpact(btCollisionObject* body0, btCollisionObject* body1, const btDispatcherInfo& dispatchInfo, btManifoldResult* resultOut) = 0; virtual void getAllContactManifolds(btManifoldArray& manifoldArray) = 0; }; #endif //BT_COLLISION_ALGORITHM_H
0
0.886958
1
0.886958
game-dev
MEDIA
0.987182
game-dev
0.830261
1
0.830261
CitizensDev/Citizens2
6,246
v1_21_R6/src/main/java/net/citizensnpcs/nms/v1_21_R6/entity/nonliving/FallingBlockController.java
package net.citizensnpcs.nms.v1_21_R6.entity.nonliving; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.craftbukkit.v1_21_R6.CraftServer; import org.bukkit.craftbukkit.v1_21_R6.CraftWorld; import org.bukkit.craftbukkit.v1_21_R6.entity.CraftEntity; import org.bukkit.craftbukkit.v1_21_R6.entity.CraftFallingBlock; import org.bukkit.craftbukkit.v1_21_R6.util.CraftMagicNumbers; import org.bukkit.entity.FallingBlock; import net.citizensnpcs.api.npc.NPC; import net.citizensnpcs.nms.v1_21_R6.util.NMSBoundingBox; import net.citizensnpcs.nms.v1_21_R6.util.NMSImpl; import net.citizensnpcs.npc.AbstractEntityController; import net.citizensnpcs.npc.CitizensNPC; import net.citizensnpcs.npc.ai.NPCHolder; import net.citizensnpcs.util.NMS; import net.citizensnpcs.util.Util; import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; import net.minecraft.tags.TagKey; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.MoverType; import net.minecraft.world.entity.item.FallingBlockEntity; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.material.Fluid; import net.minecraft.world.level.material.PushReaction; import net.minecraft.world.level.portal.TeleportTransition; import net.minecraft.world.level.storage.ValueOutput; import net.minecraft.world.phys.AABB; import net.minecraft.world.phys.Vec3; public class FallingBlockController extends AbstractEntityController { @Override protected org.bukkit.entity.Entity createEntity(Location at, NPC npc) { ServerLevel ws = ((CraftWorld) at.getWorld()).getHandle(); Block id = CraftMagicNumbers.getBlock(npc.getItemProvider().get().getType()); final EntityFallingBlockNPC handle = new EntityFallingBlockNPC(EntityType.FALLING_BLOCK, ws, npc); handle.setPos(at.getX(), at.getY(), at.getZ()); handle.setDeltaMovement(Vec3.ZERO); NMSImpl.setFallingBlockState(handle, id.defaultBlockState()); return handle.getBukkitEntity(); } @Override public FallingBlock getBukkitEntity() { return (FallingBlock) super.getBukkitEntity(); } public static class EntityFallingBlockNPC extends FallingBlockEntity implements NPCHolder { private final CitizensNPC npc; public EntityFallingBlockNPC(EntityType<? extends FallingBlockEntity> types, Level level) { this(types, level, null); } public EntityFallingBlockNPC(EntityType<? extends FallingBlockEntity> types, Level level, NPC npc) { super(types, level); this.npc = (CitizensNPC) npc; } @Override public boolean broadcastToPlayer(ServerPlayer player) { return NMS.shouldBroadcastToPlayer(npc, () -> super.broadcastToPlayer(player)); } @Override public CraftEntity getBukkitEntity() { if (npc != null && !(super.getBukkitEntity() instanceof NPCHolder)) { NMSImpl.setBukkitEntity(this, new FallingBlockNPC(this)); } return super.getBukkitEntity(); } @Override public NPC getNPC() { return npc; } @Override public PushReaction getPistonPushReaction() { return Util.callPistonPushEvent(npc) ? PushReaction.IGNORE : super.getPistonPushReaction(); } @Override public boolean isPushable() { return npc == null ? super.isPushable() : npc.data().<Boolean> get(NPC.Metadata.COLLIDABLE, !npc.isProtected()); } @Override protected AABB makeBoundingBox(Vec3 vec3) { return NMSBoundingBox.makeBB(npc, super.makeBoundingBox(vec3)); } @Override public void push(Entity entity) { // this method is called by both the entities involved - cancelling // it will not stop the NPC from moving. super.push(entity); if (npc != null) { Util.callCollisionEvent(npc, entity.getBukkitEntity()); } } @Override public void refreshDimensions() { if (npc == null) { super.refreshDimensions(); } else { NMSImpl.setSize(this, firstTick); } } @Override public boolean save(ValueOutput save) { return npc == null ? super.save(save) : false; } @Override public Entity teleport(TeleportTransition transition) { if (npc == null) return super.teleport(transition); return NMSImpl.teleportAcrossWorld(this, transition); } @Override public void tick() { if (npc != null) { npc.update(); Vec3 mot = getDeltaMovement(); if (Math.abs(mot.x) > EPSILON || Math.abs(mot.y) > EPSILON || Math.abs(mot.z) > EPSILON) { mot = mot.multiply(0.98, 0.98, 0.98); setDeltaMovement(mot); move(MoverType.SELF, mot); } } else { super.tick(); } } @Override public boolean updateFluidHeightAndDoFluidPushing(TagKey<Fluid> tagkey, double d0) { if (npc == null) return super.updateFluidHeightAndDoFluidPushing(tagkey, d0); Vec3 old = getDeltaMovement().add(0, 0, 0); boolean res = super.updateFluidHeightAndDoFluidPushing(tagkey, d0); if (!npc.isPushableByFluids()) { setDeltaMovement(old); } return res; } private static final double EPSILON = 0.001; } public static class FallingBlockNPC extends CraftFallingBlock implements NPCHolder { private final CitizensNPC npc; public FallingBlockNPC(EntityFallingBlockNPC entity) { super((CraftServer) Bukkit.getServer(), entity); this.npc = entity.npc; } @Override public NPC getNPC() { return npc; } } }
0
0.918802
1
0.918802
game-dev
MEDIA
0.99723
game-dev
0.973101
1
0.973101
mastercomfig/tf2-patches-old
19,982
src/game/server/tf2/info_act.cpp
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ //=============================================================================// #include "cbase.h" #include "EntityOutput.h" #include "EntityList.h" #include "tf_team.h" #include "tier1/strtools.h" #include "baseentity.h" #include "tf_shareddefs.h" #include "info_act.h" // Global pointer to the current act CHandle<CInfoAct> g_hCurrentAct; BEGIN_DATADESC( CInfoAct ) // inputs DEFINE_INPUTFUNC( FIELD_VOID, "Start", InputStart ), DEFINE_INPUTFUNC( FIELD_VOID, "FinishWinNone", InputFinishWinNone ), DEFINE_INPUTFUNC( FIELD_VOID, "FinishWin1", InputFinishWin1 ), DEFINE_INPUTFUNC( FIELD_VOID, "FinishWin2", InputFinishWin2 ), DEFINE_INPUTFUNC( FIELD_FLOAT, "AddTime", InputAddTime ), // outputs DEFINE_OUTPUT( m_OnStarted, "OnStarted" ), DEFINE_OUTPUT( m_OnFinishedTeamNone, "OnFinishedWinNone" ), DEFINE_OUTPUT( m_OnFinishedTeam1, "OnFinishedWin1" ), DEFINE_OUTPUT( m_OnFinishedTeam2, "OnFinishedWin2" ), DEFINE_OUTPUT( m_OnTimerExpired, "OnTimerExpired" ), DEFINE_OUTPUT( m_Respawn1Team1Events[CInfoAct::RESPAWN_TIMER_90_REMAINING], "OnRespawn1Team1_90sec" ), DEFINE_OUTPUT( m_Respawn1Team1Events[CInfoAct::RESPAWN_TIMER_60_REMAINING], "OnRespawn1Team1_60sec" ), DEFINE_OUTPUT( m_Respawn1Team1Events[CInfoAct::RESPAWN_TIMER_45_REMAINING], "OnRespawn1Team1_45sec" ), DEFINE_OUTPUT( m_Respawn1Team1Events[CInfoAct::RESPAWN_TIMER_30_REMAINING], "OnRespawn1Team1_30sec" ), DEFINE_OUTPUT( m_Respawn1Team1Events[CInfoAct::RESPAWN_TIMER_10_REMAINING], "OnRespawn1Team1_10sec" ), DEFINE_OUTPUT( m_Respawn1Team1Events[CInfoAct::RESPAWN_TIMER_0_REMAINING], "OnRespawn1Team1" ), DEFINE_OUTPUT( m_Respawn1Team1TimeRemaining, "Respawn1Team1TimeRemaining" ), DEFINE_OUTPUT( m_Respawn2Team1Events[CInfoAct::RESPAWN_TIMER_90_REMAINING], "OnRespawn2Team1_90sec" ), DEFINE_OUTPUT( m_Respawn2Team1Events[CInfoAct::RESPAWN_TIMER_60_REMAINING], "OnRespawn2Team1_60sec" ), DEFINE_OUTPUT( m_Respawn2Team1Events[CInfoAct::RESPAWN_TIMER_45_REMAINING], "OnRespawn2Team1_45sec" ), DEFINE_OUTPUT( m_Respawn2Team1Events[CInfoAct::RESPAWN_TIMER_30_REMAINING], "OnRespawn2Team1_30sec" ), DEFINE_OUTPUT( m_Respawn2Team1Events[CInfoAct::RESPAWN_TIMER_10_REMAINING], "OnRespawn2Team1_10sec" ), DEFINE_OUTPUT( m_Respawn2Team1Events[CInfoAct::RESPAWN_TIMER_0_REMAINING], "OnRespawn2Team1" ), DEFINE_OUTPUT( m_Respawn2Team1TimeRemaining, "Respawn2Team1TimeRemaining" ), DEFINE_OUTPUT( m_Respawn1Team2Events[CInfoAct::RESPAWN_TIMER_90_REMAINING], "OnRespawn1Team2_90sec" ), DEFINE_OUTPUT( m_Respawn1Team2Events[CInfoAct::RESPAWN_TIMER_60_REMAINING], "OnRespawn1Team2_60sec" ), DEFINE_OUTPUT( m_Respawn1Team2Events[CInfoAct::RESPAWN_TIMER_45_REMAINING], "OnRespawn1Team2_45sec" ), DEFINE_OUTPUT( m_Respawn1Team2Events[CInfoAct::RESPAWN_TIMER_30_REMAINING], "OnRespawn1Team2_30sec" ), DEFINE_OUTPUT( m_Respawn1Team2Events[CInfoAct::RESPAWN_TIMER_10_REMAINING], "OnRespawn1Team2_10sec" ), DEFINE_OUTPUT( m_Respawn1Team2Events[CInfoAct::RESPAWN_TIMER_0_REMAINING], "OnRespawn1Team2" ), DEFINE_OUTPUT( m_Respawn1Team2TimeRemaining, "Respawn1Team2TimeRemaining" ), DEFINE_OUTPUT( m_Respawn2Team2Events[CInfoAct::RESPAWN_TIMER_90_REMAINING], "OnRespawn2Team2_90sec" ), DEFINE_OUTPUT( m_Respawn2Team2Events[CInfoAct::RESPAWN_TIMER_60_REMAINING], "OnRespawn2Team2_60sec" ), DEFINE_OUTPUT( m_Respawn2Team2Events[CInfoAct::RESPAWN_TIMER_45_REMAINING], "OnRespawn2Team2_45sec" ), DEFINE_OUTPUT( m_Respawn2Team2Events[CInfoAct::RESPAWN_TIMER_30_REMAINING], "OnRespawn2Team2_30sec" ), DEFINE_OUTPUT( m_Respawn2Team2Events[CInfoAct::RESPAWN_TIMER_10_REMAINING], "OnRespawn2Team2_10sec" ), DEFINE_OUTPUT( m_Respawn2Team2Events[CInfoAct::RESPAWN_TIMER_0_REMAINING], "OnRespawn2Team2" ), DEFINE_OUTPUT( m_Respawn2Team2TimeRemaining, "Respawn2Team2TimeRemaining" ), DEFINE_OUTPUT( m_Team1RespawnDelayDone, "OnTeam1RespawnDelayDone" ), DEFINE_OUTPUT( m_Team2RespawnDelayDone, "OnTeam2RespawnDelayDone" ), // keys DEFINE_KEYFIELD_NOT_SAVED( m_iActNumber, FIELD_INTEGER, "ActNumber" ), DEFINE_KEYFIELD_NOT_SAVED( m_flActTimeLimit, FIELD_FLOAT, "ActTimeLimit" ), DEFINE_KEYFIELD_NOT_SAVED( m_iszIntermissionCamera, FIELD_STRING, "IntermissionCamera" ), DEFINE_KEYFIELD_NOT_SAVED( m_nRespawn1Team1Time, FIELD_INTEGER, "Respawn1Team1Time" ), DEFINE_KEYFIELD_NOT_SAVED( m_nRespawn2Team1Time, FIELD_INTEGER, "Respawn2Team1Time" ), DEFINE_KEYFIELD_NOT_SAVED( m_nRespawn1Team2Time, FIELD_INTEGER, "Respawn1Team2Time" ), DEFINE_KEYFIELD_NOT_SAVED( m_nRespawn2Team2Time, FIELD_INTEGER, "Respawn2Team2Time" ), DEFINE_KEYFIELD_NOT_SAVED( m_nRespawnTeam1Delay, FIELD_INTEGER, "RespawnTeam1InitialDelay" ), DEFINE_KEYFIELD_NOT_SAVED( m_nRespawnTeam2Delay, FIELD_INTEGER, "RespawnTeam2InitialDelay" ), // functions DEFINE_FUNCTION( ActThink ), DEFINE_FUNCTION( ActThinkEndActOverlayTime ), DEFINE_FUNCTION( RespawnTimerThink ), DEFINE_FUNCTION( Team1RespawnDelayThink ), DEFINE_FUNCTION( Team2RespawnDelayThink ), END_DATADESC() IMPLEMENT_SERVERCLASS_ST(CInfoAct, DT_InfoAct) SendPropInt(SENDINFO(m_iActNumber), 5 ), SendPropInt(SENDINFO(m_spawnflags), SF_ACT_BITS, SPROP_UNSIGNED ), SendPropFloat(SENDINFO(m_flActTimeLimit), 12 ), SendPropInt(SENDINFO(m_nRespawn1Team1Time), 8 ), SendPropInt(SENDINFO(m_nRespawn2Team1Time), 8 ), SendPropInt(SENDINFO(m_nRespawn1Team2Time), 8 ), SendPropInt(SENDINFO(m_nRespawn2Team2Time), 8 ), SendPropInt(SENDINFO(m_nRespawnTeam1Delay), 8 ), SendPropInt(SENDINFO(m_nRespawnTeam2Delay), 8 ), END_SEND_TABLE(); LINK_ENTITY_TO_CLASS( info_act, CInfoAct ); #define RESPAWN_TIMER_CONTEXT "RespawnTimerThink" #define RESPAWN_TEAM_1_DELAY_CONTEXT "RespawnTeam1DelayThink" #define RESPAWN_TEAM_2_DELAY_CONTEXT "RespawnTeam2DelayThink" //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CInfoAct::CInfoAct( void ) { // No act == -1 m_iActNumber = -1; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- int CInfoAct::UpdateTransmitState() { return SetTransmitState( FL_EDICT_ALWAYS ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CInfoAct::Spawn( void ) { m_flActStartedAt = 0; m_iWinners = 0; } //----------------------------------------------------------------------------- // Purpose: Set up respawn timers //----------------------------------------------------------------------------- void CInfoAct::SetUpRespawnTimers() { // NOTE: Need to add the second there so the respawn timers don't immediately trigger SetContextThink( RespawnTimerThink, gpGlobals->curtime + 1.0f, RESPAWN_TIMER_CONTEXT ); if (m_nRespawnTeam1Delay != 0) { SetContextThink( Team1RespawnDelayThink, gpGlobals->curtime + m_nRespawnTeam1Delay, RESPAWN_TEAM_1_DELAY_CONTEXT ); } else { m_Team1RespawnDelayDone.FireOutput( this, this ); } if (m_nRespawnTeam2Delay != 0) { SetContextThink( Team2RespawnDelayThink, gpGlobals->curtime + m_nRespawnTeam2Delay, RESPAWN_TEAM_2_DELAY_CONTEXT ); } else { m_Team2RespawnDelayDone.FireOutput( this, this ); } } void CInfoAct::ShutdownRespawnTimers() { SetContextThink( NULL, 0, RESPAWN_TIMER_CONTEXT ); SetContextThink( NULL, 0, RESPAWN_TEAM_1_DELAY_CONTEXT ); SetContextThink( NULL, 0, RESPAWN_TEAM_2_DELAY_CONTEXT ); } //----------------------------------------------------------------------------- // Respawn delay //----------------------------------------------------------------------------- void CInfoAct::Team1RespawnDelayThink() { m_Team1RespawnDelayDone.FireOutput( this, this ); SetContextThink( NULL, 0, RESPAWN_TEAM_1_DELAY_CONTEXT ); } void CInfoAct::Team2RespawnDelayThink() { m_Team2RespawnDelayDone.FireOutput( this, this ); SetContextThink( NULL, 0, RESPAWN_TEAM_2_DELAY_CONTEXT ); } //----------------------------------------------------------------------------- // Computes the time remaining //----------------------------------------------------------------------------- int CInfoAct::ComputeTimeRemaining( int nPeriod, int nDelay ) { if (nPeriod <= 0) return -1; int nTimeDelta = (int)(gpGlobals->curtime - m_flActStartedAt); Assert( nTimeDelta >= 0 ); nTimeDelta -= nDelay; // This case takes care of the initial spawn delay time... if (nTimeDelta <= 0) { return nPeriod - nTimeDelta; } int nFactor = nTimeDelta / nPeriod; int nTimeRemainder = nTimeDelta - nFactor * nPeriod; if (nTimeRemainder == 0) return 0; return nPeriod - nTimeRemainder; } //----------------------------------------------------------------------------- // Fires respawn events //----------------------------------------------------------------------------- void CInfoAct::FireRespawnEvents( int nTimeRemaining, COutputEvent *pRespawnEvents, COutputInt &respawnTime ) { if (nTimeRemaining < 0) return; switch (nTimeRemaining) { case 90: pRespawnEvents[RESPAWN_TIMER_90_REMAINING].FireOutput( this, this ); break; case 60: pRespawnEvents[RESPAWN_TIMER_60_REMAINING].FireOutput( this, this ); break; case 45: pRespawnEvents[RESPAWN_TIMER_45_REMAINING].FireOutput( this, this ); break; case 30: pRespawnEvents[RESPAWN_TIMER_30_REMAINING].FireOutput( this, this ); break; case 10: pRespawnEvents[RESPAWN_TIMER_10_REMAINING].FireOutput( this, this ); break; case 0: pRespawnEvents[RESPAWN_TIMER_0_REMAINING].FireOutput( this, this ); break; default: break; } respawnTime.Set( nTimeRemaining, this, this ); } //----------------------------------------------------------------------------- // Respawn timers //----------------------------------------------------------------------------- void CInfoAct::RespawnTimerThink() { int nTimeRemaining = ComputeTimeRemaining( m_nRespawn1Team1Time, m_nRespawnTeam1Delay ); FireRespawnEvents( nTimeRemaining, m_Respawn1Team1Events, m_Respawn1Team1TimeRemaining ); nTimeRemaining = ComputeTimeRemaining( m_nRespawn2Team1Time, m_nRespawnTeam1Delay ); FireRespawnEvents( nTimeRemaining, m_Respawn2Team1Events, m_Respawn2Team1TimeRemaining ); nTimeRemaining = ComputeTimeRemaining( m_nRespawn1Team2Time, m_nRespawnTeam2Delay ); FireRespawnEvents( nTimeRemaining, m_Respawn1Team2Events, m_Respawn1Team2TimeRemaining ); nTimeRemaining = ComputeTimeRemaining( m_nRespawn2Team2Time, m_nRespawnTeam2Delay ); FireRespawnEvents( nTimeRemaining, m_Respawn2Team2Events, m_Respawn2Team2TimeRemaining ); SetNextThink( gpGlobals->curtime + 1.0f, RESPAWN_TIMER_CONTEXT ); } //----------------------------------------------------------------------------- // Purpose: The act has started //----------------------------------------------------------------------------- void CInfoAct::StartAct( void ) { // FIXME: Should this change? // Don't allow two simultaneous acts if (g_hCurrentAct) { g_hCurrentAct->FinishAct( ); } // Set the global act to this g_hCurrentAct = this; m_flActStartedAt = gpGlobals->curtime; m_OnStarted.FireOutput( this, this ); // Do we have a timelimit? if ( m_flActTimeLimit ) { SetNextThink( gpGlobals->curtime + m_flActTimeLimit ); SetThink( ActThink ); } SetUpRespawnTimers(); // Tell all the clients CReliableBroadcastRecipientFilter filter; UserMessageBegin( filter, "ActBegin" ); WRITE_BYTE( (byte)m_iActNumber ); WRITE_FLOAT( m_flActStartedAt ); MessageEnd(); // If we're not an intermission, clean up if ( !HasSpawnFlags( SF_ACT_INTERMISSION ) ) { CleanupOnActStart(); } // Cycle through all players and start the act for ( int i = 1; i <= gpGlobals->maxClients; i++ ) { CBaseTFPlayer *pPlayer = (CBaseTFPlayer*)UTIL_PlayerByIndex( i ); if ( pPlayer ) { // Am I an intermission? if ( HasSpawnFlags( SF_ACT_INTERMISSION ) ) { StartIntermission( pPlayer ); } else { StartActOverlayTime( pPlayer ); } } } // Think again soon, to remove player locks if ( !HasSpawnFlags(SF_ACT_INTERMISSION) ) { SetNextThink( gpGlobals->curtime + MIN_ACT_OVERLAY_TIME ); SetThink( ActThinkEndActOverlayTime ); } } //----------------------------------------------------------------------------- // Purpose: Update a client who joined during the middle of an act //----------------------------------------------------------------------------- void CInfoAct::UpdateClient( CBaseTFPlayer *pPlayer ) { CSingleUserRecipientFilter user( pPlayer ); user.MakeReliable(); UserMessageBegin( user, "ActBegin" ); WRITE_BYTE( (byte)m_iActNumber ); WRITE_FLOAT( m_flActStartedAt ); MessageEnd(); } //----------------------------------------------------------------------------- // Purpose: The act has finished //----------------------------------------------------------------------------- void CInfoAct::FinishAct( ) { if ( g_hCurrentAct.Get() != this ) { DevWarning( 2, "Attempted to finish an act which wasn't started!\n" ); return; } ShutdownRespawnTimers(); switch( m_iWinners) { case 0: m_OnFinishedTeamNone.FireOutput( this, this ); break; case 1: m_OnFinishedTeam1.FireOutput( this, this ); break; case 2: m_OnFinishedTeam2.FireOutput( this, this ); break; default: Assert(0); break; } g_hCurrentAct = NULL; // Tell all the clients CReliableBroadcastRecipientFilter filter; UserMessageBegin( filter, "ActEnd" ); WRITE_BYTE( m_iWinners ); MessageEnd(); // Am I an intermission? if ( HasSpawnFlags( SF_ACT_INTERMISSION ) ) { // Cycle through all players and end the intermission for them for ( int i = 1; i <= gpGlobals->maxClients; i++ ) { CBaseTFPlayer *pPlayer = (CBaseTFPlayer*)UTIL_PlayerByIndex( i ); if ( pPlayer ) { EndIntermission( pPlayer ); } } } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CInfoAct::ActThink( void ) { m_OnTimerExpired.FireOutput( this,this ); } //----------------------------------------------------------------------------- // Purpose: Force the players not to move to give them time to read the act overlays //----------------------------------------------------------------------------- void CInfoAct::StartActOverlayTime( CBaseTFPlayer *pPlayer ) { // Lock the player in place pPlayer->CleanupOnActStart(); pPlayer->LockPlayerInPlace(); if ( pPlayer->GetActiveWeapon() ) { pPlayer->GetActiveWeapon()->Holster(); } pPlayer->m_Local.m_iHideHUD |= (HIDEHUD_WEAPONSELECTION | HIDEHUD_HEALTH); pPlayer->GetLocalData()->m_bForceMapOverview = true; } //----------------------------------------------------------------------------- // Purpose: Release the players after overlay time has finished //----------------------------------------------------------------------------- void CInfoAct::EndActOverlayTime( CBaseTFPlayer *pPlayer ) { // Release the player pPlayer->UnlockPlayer(); if ( pPlayer->GetActiveWeapon() ) { pPlayer->GetActiveWeapon()->Deploy(); } pPlayer->m_Local.m_iHideHUD &= ~(HIDEHUD_WEAPONSELECTION | HIDEHUD_HEALTH); pPlayer->GetLocalData()->m_bForceMapOverview = false; } //----------------------------------------------------------------------------- // Purpose: Unlock the players after an act has started //----------------------------------------------------------------------------- void CInfoAct::ActThinkEndActOverlayTime( void ) { // Cycle through all players and end the intermission for them for ( int i = 1; i <= gpGlobals->maxClients; i++ ) { CBaseTFPlayer *pPlayer = (CBaseTFPlayer*)UTIL_PlayerByIndex( i ); if ( pPlayer ) { EndActOverlayTime( pPlayer ); } } // Think again when the act ends, if we have a timelimit if ( m_flActTimeLimit ) { SetNextThink( gpGlobals->curtime + m_flActTimeLimit - MIN_ACT_OVERLAY_TIME ); SetThink( ActThink ); } } //----------------------------------------------------------------------------- // Purpose: Clean up entities before a new act starts //----------------------------------------------------------------------------- void CInfoAct::CleanupOnActStart( void ) { // Remove all resource chunks CBaseEntity *pEntity = NULL; while ((pEntity = gEntList.FindEntityByClassname( pEntity, "resource_chunk" )) != NULL) { UTIL_Remove( pEntity ); } } //----------------------------------------------------------------------------- // Purpose: Intermission handling //----------------------------------------------------------------------------- void CInfoAct::StartIntermission( CBaseTFPlayer *pPlayer ) { // Do we have a camera point? if ( m_iszIntermissionCamera != NULL_STRING ) { CBaseEntity *pCamera = gEntList.FindEntityByName( NULL, STRING(m_iszIntermissionCamera) ); if ( pCamera ) { // Move the player to the camera point pPlayer->SetViewEntity( pCamera ); pPlayer->m_Local.m_iHideHUD |= (HIDEHUD_WEAPONSELECTION | HIDEHUD_HEALTH | HIDEHUD_MISCSTATUS); } } // Lock the player in place pPlayer->LockPlayerInPlace(); } //----------------------------------------------------------------------------- // Purpose: Intermission handling //----------------------------------------------------------------------------- void CInfoAct::EndIntermission( CBaseTFPlayer *pPlayer ) { // Force the player to respawn pPlayer->UnlockPlayer(); pPlayer->SetViewEntity( pPlayer ); pPlayer->ForceRespawn(); pPlayer->m_Local.m_iHideHUD &= ~(HIDEHUD_WEAPONSELECTION | HIDEHUD_HEALTH | HIDEHUD_MISCSTATUS); } //----------------------------------------------------------------------------- // Purpose: Force the act to start //----------------------------------------------------------------------------- void CInfoAct::InputStart( inputdata_t &inputdata ) { StartAct(); } //----------------------------------------------------------------------------- // Purpose: Force the act to finish, with team 1 as the winners //----------------------------------------------------------------------------- void CInfoAct::InputFinishWinNone( inputdata_t &inputdata ) { m_iWinners = 0; FinishAct(); } //----------------------------------------------------------------------------- // Purpose: Force the act to finish, with team 1 as the winners //----------------------------------------------------------------------------- void CInfoAct::InputFinishWin1( inputdata_t &inputdata ) { m_iWinners = 1; FinishAct(); } //----------------------------------------------------------------------------- // Purpose: Force the act to finish, with team 2 as the winners //----------------------------------------------------------------------------- void CInfoAct::InputFinishWin2( inputdata_t &inputdata ) { m_iWinners = 2; FinishAct(); } //----------------------------------------------------------------------------- // Purpose: Add time to the act's time //----------------------------------------------------------------------------- void CInfoAct::InputAddTime( inputdata_t &inputdata ) { float flNewTime = inputdata.value.Float(); // Think again when the act ends, if we have a timelimit if ( flNewTime ) { m_flActTimeLimit += flNewTime; SetNextThink( GetNextThink() + flNewTime ); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CInfoAct::IsAWaitingAct( void ) { return HasSpawnFlags(SF_ACT_WAITINGFORGAMESTART); } //----------------------------------------------------------------------------- // Purpose: Return true if the current act (if any) is a waiting act. //----------------------------------------------------------------------------- bool CurrentActIsAWaitingAct( void ) { if ( g_hCurrentAct ) return g_hCurrentAct->IsAWaitingAct(); return false; }
0
0.958385
1
0.958385
game-dev
MEDIA
0.989651
game-dev
0.6459
1
0.6459
PlayFab/PlayFab-Samples
56,417
VideoTutorialSamples/PlayFabAuthentication/Assets/GooglePlayGames/Platforms/Native/NativeRealtimeMultiplayerClient.cs
// <copyright file="NativeRealtimeMultiplayerClient.cs" company="Google Inc."> // Copyright (C) 2014 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> #if (UNITY_ANDROID || (UNITY_IPHONE && !NO_GPGS)) namespace GooglePlayGames.Native { using System; using System.Linq; using System.Collections.Generic; using GooglePlayGames.BasicApi.Multiplayer; using GooglePlayGames.OurUtils; using GooglePlayGames.Native.PInvoke; using Types = GooglePlayGames.Native.Cwrapper.Types; using Status = GooglePlayGames.Native.Cwrapper.CommonErrorStatus; public class NativeRealtimeMultiplayerClient : IRealTimeMultiplayerClient { private readonly object mSessionLock = new object(); private readonly NativeClient mNativeClient; private readonly RealtimeManager mRealtimeManager; private volatile RoomSession mCurrentSession; internal NativeRealtimeMultiplayerClient(NativeClient nativeClient, RealtimeManager manager) { mNativeClient = Misc.CheckNotNull(nativeClient); mRealtimeManager = Misc.CheckNotNull(manager); mCurrentSession = GetTerminatedSession(); // register callback for when the application pauses. OnPause // will disconnect the client, we need to leave the room manually // the disconnection does not trigger and events. PlayGamesHelperObject.AddPauseCallback(HandleAppPausing); } private RoomSession GetTerminatedSession() { var terminatedRoom = new RoomSession(mRealtimeManager, new NoopListener()); terminatedRoom.EnterState(new ShutdownState(terminatedRoom), false); return terminatedRoom; } public void CreateQuickGame(uint minOpponents, uint maxOpponents, uint variant, RealTimeMultiplayerListener listener) { CreateQuickGame (minOpponents, maxOpponents, variant, 0, listener); } public void CreateQuickGame(uint minOpponents, uint maxOpponents, uint variant, ulong exclusiveBitMask, RealTimeMultiplayerListener listener) { lock (mSessionLock) { var newSession = new RoomSession(mRealtimeManager, listener); if (mCurrentSession.IsActive()) { Logger.e("Received attempt to create a new room without cleaning up the old one."); newSession.LeaveRoom(); return; } mCurrentSession = newSession; //Quickgames start when there is the min number of players Logger.d("QuickGame: Setting MinPlayersToStart = " + minOpponents); mCurrentSession.MinPlayersToStart = minOpponents; // We're holding the session lock, so no other threads could have torn down the session // in the meantime. using (var configBuilder = RealtimeRoomConfigBuilder.Create()) { var config = configBuilder.SetMinimumAutomatchingPlayers(minOpponents) .SetMaximumAutomatchingPlayers(maxOpponents) .SetVariant(variant) .SetExclusiveBitMask(exclusiveBitMask) .Build(); using (config) { using (var helper = HelperForSession(newSession)) { newSession.StartRoomCreation(mNativeClient.GetUserId(), () => mRealtimeManager.CreateRoom(config, helper, newSession.HandleRoomResponse) ); } } } } } private static RealTimeEventListenerHelper HelperForSession(RoomSession session) { return RealTimeEventListenerHelper.Create() .SetOnDataReceivedCallback((room, participant, data, isReliable) => session.OnDataReceived(room, participant, data, isReliable)) .SetOnParticipantStatusChangedCallback((room, participant) => session.OnParticipantStatusChanged(room, participant)) .SetOnRoomConnectedSetChangedCallback((room) => session.OnConnectedSetChanged(room)) .SetOnRoomStatusChangedCallback((room) => session.OnRoomStatusChanged(room)); } private void HandleAppPausing(bool paused) { if (paused) { Logger.d("Application is pausing, which disconnects the RTMP " + " client. Leaving room."); LeaveRoom(); } } public void CreateWithInvitationScreen(uint minOpponents, uint maxOppponents, uint variant, RealTimeMultiplayerListener listener) { lock (mSessionLock) { var newRoom = new RoomSession(mRealtimeManager, listener); if (mCurrentSession.IsActive()) { Logger.e("Received attempt to create a new room without cleaning up the old one."); newRoom.LeaveRoom(); return; } // The user attempted to create a room via the invitation screen, this is now the new // current room. mCurrentSession = newRoom; mCurrentSession.ShowingUI = true; mRealtimeManager.ShowPlayerSelectUI(minOpponents, maxOppponents, true, response => { mCurrentSession.ShowingUI = false; if (response.Status() != Status.UIStatus.VALID) { Logger.d("User did not complete invitation screen."); newRoom.LeaveRoom(); return; } // the min number to start is the number of automatched // plus the number of named invitations // plus the local player. mCurrentSession.MinPlayersToStart = response.MinimumAutomatchingPlayers() + (uint)response.Count() + 1; using (var configBuilder = RealtimeRoomConfigBuilder.Create()) { configBuilder.SetVariant(variant); configBuilder.PopulateFromUIResponse(response); using (var config = configBuilder.Build()) { using (var helper = HelperForSession(newRoom)) { newRoom.StartRoomCreation(mNativeClient.GetUserId(), () => mRealtimeManager.CreateRoom(config, helper, newRoom.HandleRoomResponse)); } } } }); } } public void ShowWaitingRoomUI() { lock (mSessionLock) { mCurrentSession.ShowWaitingRoomUI(); } } public void GetAllInvitations(Action<Invitation[]> callback) { mRealtimeManager.FetchInvitations((response) => { if (!response.RequestSucceeded()) { Logger.e("Couldn't load invitations."); callback(new Invitation[0]); return; } List<Invitation> invites = new List<Invitation>(); foreach (var invitation in response.Invitations()) { using (invitation) { invites.Add(invitation.AsInvitation()); } } callback(invites.ToArray()); }); } public void AcceptFromInbox(RealTimeMultiplayerListener listener) { lock (mSessionLock) { var newRoom = new RoomSession(mRealtimeManager, listener); if (mCurrentSession.IsActive()) { Logger.e("Received attempt to accept invitation without cleaning up " + "active session."); newRoom.LeaveRoom(); return; } // The user accepted an invitation from the inbox, this is now the current room. mCurrentSession = newRoom; mCurrentSession.ShowingUI = true; mRealtimeManager.ShowRoomInboxUI( response => { mCurrentSession.ShowingUI = false; if (response.ResponseStatus() != Status.UIStatus.VALID) { Logger.d("User did not complete invitation screen."); newRoom.LeaveRoom(); return; } // We are not cleaning up the invitation here to workaround a bug in the // C++ SDK where it holds a reference to un-owned memory rather than making a // copy. This is cleaned up after the callback comes back instead. var invitation = response.Invitation(); using (var helper = HelperForSession(newRoom)) { Logger.d("About to accept invitation " + invitation.Id()); newRoom.StartRoomCreation(mNativeClient.GetUserId(), () => mRealtimeManager.AcceptInvitation(invitation, helper, acceptResponse => { // Clean up the invitation here (see above comment). using (invitation) { newRoom.HandleRoomResponse(acceptResponse); newRoom.SetInvitation(invitation.AsInvitation()); } })); } }); } } public void AcceptInvitation(string invitationId, RealTimeMultiplayerListener listener) { lock (mSessionLock) { var newRoom = new RoomSession(mRealtimeManager, listener); if (mCurrentSession.IsActive()) { Logger.e("Received attempt to accept invitation without cleaning up " + "active session."); newRoom.LeaveRoom(); return; } mCurrentSession = newRoom; mRealtimeManager.FetchInvitations(response => { if (!response.RequestSucceeded()) { Logger.e("Couldn't load invitations."); newRoom.LeaveRoom(); return; } foreach (var invitation in response.Invitations()) { using (invitation) { if (invitation.Id().Equals(invitationId)) { mCurrentSession.MinPlayersToStart = invitation.AutomatchingSlots() + invitation.ParticipantCount(); Logger.d("Setting MinPlayersToStart with invitation to : " + mCurrentSession.MinPlayersToStart); using (var helper = HelperForSession(newRoom)) { newRoom.StartRoomCreation(mNativeClient.GetUserId(), () => mRealtimeManager.AcceptInvitation( invitation, helper, newRoom.HandleRoomResponse)); return; } } } } Logger.e("Room creation failed since we could not find invitation with ID " + invitationId); newRoom.LeaveRoom(); }); } } public Invitation GetInvitation() { return mCurrentSession.GetInvitation(); } public void LeaveRoom() { mCurrentSession.LeaveRoom(); } public void SendMessageToAll(bool reliable, byte[] data) { mCurrentSession.SendMessageToAll(reliable, data); } public void SendMessageToAll(bool reliable, byte[] data, int offset, int length) { mCurrentSession.SendMessageToAll(reliable, data, offset, length); } public void SendMessage(bool reliable, string participantId, byte[] data) { mCurrentSession.SendMessage(reliable, participantId, data); } public void SendMessage(bool reliable, string participantId, byte[] data, int offset, int length) { mCurrentSession.SendMessage(reliable, participantId, data, offset, length); } public List<Participant> GetConnectedParticipants() { return mCurrentSession.GetConnectedParticipants(); } public Participant GetSelf() { return mCurrentSession.GetSelf(); } public Participant GetParticipant(string participantId) { return mCurrentSession.GetParticipant(participantId); } public bool IsRoomConnected() { return mCurrentSession.IsRoomConnected(); } public void DeclineInvitation(string invitationId) { mRealtimeManager.FetchInvitations(response => { if (!response.RequestSucceeded()) { Logger.e("Couldn't load invitations."); return; } foreach (var invitation in response.Invitations()) { using (invitation) { if (invitation.Id().Equals(invitationId)) { mRealtimeManager.DeclineInvitation(invitation); } } } }); } /// <summary> /// A stub implementation of the RealTimeMultiplayerListener API. Used so that we can guarantee /// that we will never have a null reference to a listener object. /// </summary> private class NoopListener : RealTimeMultiplayerListener { public void OnRoomSetupProgress(float percent) { } public void OnRoomConnected(bool success) { } public void OnLeftRoom() { } public void OnParticipantLeft(Participant participant) { } public void OnPeersConnected(string[] participantIds) { } public void OnPeersDisconnected(string[] participantIds) { } public void OnRealTimeMessageReceived(bool isReliable, string senderId, byte[] data) { } } /// <summary>A class that encapsulates the state machine required to map the native callbacks to the /// corresponding callbacks in Unity. This session exposes an API that mirrors all the commands /// that can be issued to the RealtimeMultiplayerClient and directs these to the current state /// of the state machine which performs the actual logic. /// /// <para>All methods that can transitively update the state of the statemachine must be guarded with /// the lifecycle lock to ensure a consistent user-facing view of the state of the session.</para> /// /// <para>Note that this class maintains the invariant that mState is never null.</para> /// <para>See the doc for the individual states for details on state transitions and note that /// all states assume that all lifecycle methods will be invoked while the containing /// RoomSession is holding the lifecycle lock.</para> /// </summary> private class RoomSession { private readonly object mLifecycleLock = new object(); private readonly OnGameThreadForwardingListener mListener; private readonly RealtimeManager mManager; private volatile string mCurrentPlayerId; private volatile State mState; private volatile bool mStillPreRoomCreation; Invitation mInvitation; private volatile bool mShowingUI; private uint mMinPlayersToStart; internal RoomSession(RealtimeManager manager, RealTimeMultiplayerListener listener) { mManager = Misc.CheckNotNull(manager); mListener = new OnGameThreadForwardingListener(listener); EnterState(new BeforeRoomCreateStartedState(this), false); mStillPreRoomCreation = true; } internal bool ShowingUI { get { return mShowingUI; } set { mShowingUI = value; } } internal uint MinPlayersToStart { get { return mMinPlayersToStart; } set { mMinPlayersToStart = value; } } internal RealtimeManager Manager() { return mManager; } internal bool IsActive() { return mState.IsActive(); } internal string SelfPlayerId() { return mCurrentPlayerId; } public void SetInvitation(Invitation invitation) { mInvitation = invitation; } public Invitation GetInvitation() { return mInvitation; } internal OnGameThreadForwardingListener OnGameThreadListener() { return mListener; } /// <summary> /// Enters the state firing on the OnStateEntered event. /// </summary> /// <param name="handler">Handler for the state.</param> internal void EnterState(State handler) { EnterState(handler, true); } /// <summary> /// Sets the state of the session to the given state. /// </summary> /// <remarks> /// Lifecycle methods - these might cause state transitions, and thus require us to hold a /// lock while they're executing to prevent any externally visible inconsistent state (e.g. /// receiving any callbacks after we've left a room). /// </remarks> /// <param name="handler">Handler - the State Handler.</param> /// <param name="fireStateEnteredEvent">If set to <c>true</c> fire the StateEntered event.</param> internal void EnterState(State handler, bool fireStateEnteredEvent) { lock (mLifecycleLock) { mState = Misc.CheckNotNull(handler); if (fireStateEnteredEvent) { Logger.d("Entering state: " + handler.GetType().Name); mState.OnStateEntered(); } } } internal void LeaveRoom() { if (!ShowingUI) { lock (mLifecycleLock) { mState.LeaveRoom(); } } else { Logger.d("Not leaving room since showing UI"); } } internal void ShowWaitingRoomUI() { mState.ShowWaitingRoomUI(MinPlayersToStart); } /// <summary> /// Starts the room creation provided the session is still in a state that allows room /// creation (i.e. it hasn't been torn down). /// </summary> /// <param name="currentPlayerId">The current player identifier.</param> /// <param name="createRoom">The action that will begin creating the room.</param> internal void StartRoomCreation(string currentPlayerId, Action createRoom) { lock (mLifecycleLock) { if (!mStillPreRoomCreation) { Logger.e("Room creation started more than once, this shouldn't happen!"); return; } if (!mState.IsActive()) { Logger.w("Received an attempt to create a room after the session was already " + "torn down!"); return; } mCurrentPlayerId = Misc.CheckNotNull(currentPlayerId); mStillPreRoomCreation = false; EnterState(new RoomCreationPendingState(this)); createRoom.Invoke(); } } internal void OnRoomStatusChanged(NativeRealTimeRoom room) { lock (mLifecycleLock) { mState.OnRoomStatusChanged(room); } } internal void OnConnectedSetChanged(NativeRealTimeRoom room) { lock (mLifecycleLock) { mState.OnConnectedSetChanged(room); } } internal void OnParticipantStatusChanged(NativeRealTimeRoom room, MultiplayerParticipant participant) { lock (mLifecycleLock) { mState.OnParticipantStatusChanged(room, participant); } } /// <summary> /// Handles the room response. /// </summary> /// <param name="response">Response.</param> /// <param name="invitation">Invitation if accepting an invitation, this is stored in the session, otherwise null</param> internal void HandleRoomResponse(RealtimeManager.RealTimeRoomResponse response) { lock (mLifecycleLock) { mState.HandleRoomResponse(response); } } /** * Non-Lifecycle methods - these cannot cause state transitions, and thus we do not need to * hold any locks. We rely on only accessing volatile fields to ensure consistency instead. */ internal void OnDataReceived(NativeRealTimeRoom room, MultiplayerParticipant sender, byte[] data, bool isReliable) { mState.OnDataReceived(room, sender, data, isReliable); } internal void SendMessageToAll(bool reliable, byte[] data) { SendMessageToAll(reliable, data, 0, data.Length); } internal void SendMessageToAll(bool reliable, byte[] data, int offset, int length) { mState.SendToAll(data, offset, length, reliable); } internal void SendMessage(bool reliable, string participantId, byte[] data) { SendMessage(reliable, participantId, data, 0, data.Length); } internal void SendMessage(bool reliable, string participantId, byte[] data, int offset, int length) { mState.SendToSpecificRecipient(participantId, data, offset, length, reliable); } internal List<Participant> GetConnectedParticipants() { return mState.GetConnectedParticipants(); } internal virtual Participant GetSelf() { return mState.GetSelf(); } internal virtual Participant GetParticipant(string participantId) { return mState.GetParticipant(participantId); } internal virtual bool IsRoomConnected() { return mState.IsRoomConnected(); } } private static T WithDefault<T>(T presented, T defaultValue) where T : class { return presented != null ? presented : defaultValue; } /// <summary> /// Simple forwarding wrapper that makes sure all callbacks occur on the game thread. /// </summary> class OnGameThreadForwardingListener { private readonly RealTimeMultiplayerListener mListener; internal OnGameThreadForwardingListener(RealTimeMultiplayerListener listener) { mListener = Misc.CheckNotNull(listener); } public void RoomSetupProgress(float percent) { PlayGamesHelperObject.RunOnGameThread(() => mListener.OnRoomSetupProgress(percent)); } public void RoomConnected(bool success) { PlayGamesHelperObject.RunOnGameThread(() => mListener.OnRoomConnected(success)); } public void LeftRoom() { PlayGamesHelperObject.RunOnGameThread(() => mListener.OnLeftRoom()); } public void PeersConnected(string[] participantIds) { PlayGamesHelperObject.RunOnGameThread(() => mListener.OnPeersConnected(participantIds)); } public void PeersDisconnected(string[] participantIds) { PlayGamesHelperObject.RunOnGameThread( () => mListener.OnPeersDisconnected(participantIds)); } public void RealTimeMessageReceived(bool isReliable, string senderId, byte[] data) { PlayGamesHelperObject.RunOnGameThread( () => mListener.OnRealTimeMessageReceived(isReliable, senderId, data)); } public void ParticipantLeft(Participant participant) { PlayGamesHelperObject.RunOnGameThread( () => mListener.OnParticipantLeft(participant)); } } /// <summary> /// A base state implementation. All methods do nothing or return stub values. States that /// require specific behavior must override the corresponding methods. /// </summary> internal abstract class State { internal virtual void HandleRoomResponse(RealtimeManager.RealTimeRoomResponse response) { Logger.d(this.GetType().Name + ".HandleRoomResponse: Defaulting to no-op."); } internal virtual bool IsActive() { Logger.d(this.GetType().Name + ".IsNonPreemptable: Is preemptable by default."); return true; } internal virtual void LeaveRoom() { Logger.d(this.GetType().Name + ".LeaveRoom: Defaulting to no-op."); } internal virtual void ShowWaitingRoomUI(uint minimumParticipantsBeforeStarting) { Logger.d(this.GetType().Name + ".ShowWaitingRoomUI: Defaulting to no-op."); } internal virtual void OnStateEntered() { Logger.d(this.GetType().Name + ".OnStateEntered: Defaulting to no-op."); } internal virtual void OnRoomStatusChanged(NativeRealTimeRoom room) { Logger.d(this.GetType().Name + ".OnRoomStatusChanged: Defaulting to no-op."); } internal virtual void OnConnectedSetChanged(NativeRealTimeRoom room) { Logger.d(this.GetType().Name + ".OnConnectedSetChanged: Defaulting to no-op."); } internal virtual void OnParticipantStatusChanged(NativeRealTimeRoom room, MultiplayerParticipant participant) { Logger.d(this.GetType().Name + ".OnParticipantStatusChanged: Defaulting to no-op."); } internal virtual void OnDataReceived(NativeRealTimeRoom room, MultiplayerParticipant sender, byte[] data, bool isReliable) { Logger.d(this.GetType().Name + ".OnDataReceived: Defaulting to no-op."); } internal virtual void SendToSpecificRecipient( string recipientId, byte[] data, int offset, int length, bool isReliable) { Logger.d(this.GetType().Name + ".SendToSpecificRecipient: Defaulting to no-op."); } internal virtual void SendToAll(byte[] data, int offset, int length, bool isReliable) { Logger.d(this.GetType().Name + ".SendToApp: Defaulting to no-op."); } internal virtual List<Participant> GetConnectedParticipants() { Logger.d(this.GetType().Name + ".GetConnectedParticipants: Returning empty connected" + " participants"); return new List<Participant>(); } internal virtual Participant GetSelf() { Logger.d(this.GetType().Name + ".GetSelf: Returning null self."); return null; } internal virtual Participant GetParticipant(string participantId) { Logger.d(this.GetType().Name + ".GetSelf: Returning null participant."); return null; } internal virtual bool IsRoomConnected() { Logger.d(this.GetType().Name + ".IsRoomConnected: Returning room not connected."); return false; } } /// <summary> /// A base class for all states where message passing is enabled (i.e. the Active and /// Connecting states). /// </summary> private abstract class MessagingEnabledState : State { protected readonly RoomSession mSession; protected NativeRealTimeRoom mRoom; protected Dictionary<string, MultiplayerParticipant> mNativeParticipants; protected Dictionary<string, Participant> mParticipants; internal MessagingEnabledState(RoomSession session, NativeRealTimeRoom room) { mSession = Misc.CheckNotNull(session); UpdateCurrentRoom(room); } internal void UpdateCurrentRoom(NativeRealTimeRoom room) { if (mRoom != null) { mRoom.Dispose(); } mRoom = Misc.CheckNotNull(room); mNativeParticipants = mRoom.Participants().ToDictionary(p => p.Id()); mParticipants = mNativeParticipants.Values .Select(p => p.AsParticipant()) .ToDictionary(p => p.ParticipantId); } internal sealed override void OnRoomStatusChanged(NativeRealTimeRoom room) { HandleRoomStatusChanged(room); UpdateCurrentRoom(room); } internal virtual void HandleRoomStatusChanged(NativeRealTimeRoom room) { // noop } internal sealed override void OnConnectedSetChanged(NativeRealTimeRoom room) { HandleConnectedSetChanged(room); UpdateCurrentRoom(room); } internal virtual void HandleConnectedSetChanged(NativeRealTimeRoom room) { // noop } internal sealed override void OnParticipantStatusChanged(NativeRealTimeRoom room, MultiplayerParticipant participant) { HandleParticipantStatusChanged(room, participant); UpdateCurrentRoom(room); } internal virtual void HandleParticipantStatusChanged(NativeRealTimeRoom room, MultiplayerParticipant participant) { // noop } internal sealed override List<Participant> GetConnectedParticipants() { var connectedParticipants = mParticipants.Values .Where(p => p.IsConnectedToRoom) .ToList(); connectedParticipants.Sort(); return connectedParticipants; } internal override void SendToSpecificRecipient( string recipientId, byte[] data, int offset, int length, bool isReliable) { if (!mNativeParticipants.ContainsKey(recipientId)) { Logger.e("Attempted to send message to unknown participant " + recipientId); return; } if (isReliable) { mSession.Manager().SendReliableMessage(mRoom, mNativeParticipants[recipientId], Misc.GetSubsetBytes(data, offset, length), null); } else { mSession.Manager().SendUnreliableMessageToSpecificParticipants(mRoom, new List<MultiplayerParticipant> { mNativeParticipants[recipientId] }, Misc.GetSubsetBytes(data, offset, length)); } } internal override void SendToAll(byte[] data, int offset, int length, bool isReliable) { var trimmed = Misc.GetSubsetBytes(data, offset, length); if (isReliable) { foreach (var participantId in mNativeParticipants.Keys) { SendToSpecificRecipient(participantId, trimmed, 0, trimmed.Length, true); } } else { mSession.Manager().SendUnreliableMessageToAll(mRoom, trimmed); } } internal override void OnDataReceived(NativeRealTimeRoom room, MultiplayerParticipant sender, byte[] data, bool isReliable) { mSession.OnGameThreadListener().RealTimeMessageReceived(isReliable, sender.Id(), data); } } /// <summary>The state of the session before we have initiated room creation. This is necessary /// in cases where we have to do additional callbacks to look up information before the room /// can be created (e.g. finding the invitation corresponding to an ID). /// /// <para>This is the initial state for all sessions. In the event of an error before room /// creation states, this state will immediately transition to Shutdown (as there is nothing /// to clean up). Unlike other states, transitions out of this state are determined externally /// by the enclosing room (which knows when we can begin room creation).</para> /// </summary> class BeforeRoomCreateStartedState : State { private readonly RoomSession mContainingSession; internal BeforeRoomCreateStartedState(RoomSession session) { mContainingSession = Misc.CheckNotNull(session); } internal override void LeaveRoom() { Logger.d("Session was torn down before room was created."); mContainingSession.OnGameThreadListener().RoomConnected(false); mContainingSession.EnterState(new ShutdownState(mContainingSession)); } } /// <summary>The state we were have issued a room creation request. Normally this state /// immediately transitions into the connecting state where we begin creating the mesh network. /// /// <para>This state can transition to 3 other states: Connecting, Aborting room, or shutdown. /// If room creation proceeds normally and there are no intervening calls to leave room, we /// transition into 'Connecting'. If the user tears down the session before room creation /// completes, we transition into 'Aborting Room', and if the room creation fails we transition /// immediately to 'Shutdown'.</para> /// </summary> class RoomCreationPendingState : State { private readonly RoomSession mContainingSession; internal RoomCreationPendingState(RoomSession session) { mContainingSession = Misc.CheckNotNull(session); } internal override void HandleRoomResponse(RealtimeManager.RealTimeRoomResponse response) { if (!response.RequestSucceeded()) { mContainingSession.EnterState(new ShutdownState(mContainingSession)); mContainingSession.OnGameThreadListener().RoomConnected(false); return; } mContainingSession.EnterState(new ConnectingState(response.Room(), mContainingSession)); } internal override bool IsActive() { // The client must explicitly leave before cleaning up a room that is being created. return true; } internal override void LeaveRoom() { Logger.d("Received request to leave room during room creation, aborting creation."); mContainingSession.EnterState(new AbortingRoomCreationState(mContainingSession)); } } /// <summary>A state indicating we're in the process of creating a fully connected mesh network /// between all multiplayer clients. /// /// <para>We can transition into 2 states from 'Connecting': 'Active' and 'Leaving room'. /// If we are able to create a mesh network from all participants, we move into 'Active'. /// If any participant fails to create the mesh or the user asks to leave the room, we /// transition into 'Leave Room'.</para> /// </summary> class ConnectingState : MessagingEnabledState { private const float InitialPercentComplete = 20.0F; private static readonly HashSet<Types.ParticipantStatus> FailedStatuses = new HashSet<Types.ParticipantStatus> { Types.ParticipantStatus.DECLINED, Types.ParticipantStatus.LEFT, }; private HashSet<string> mConnectedParticipants = new HashSet<string>(); private float mPercentComplete = InitialPercentComplete; private float mPercentPerParticipant; internal ConnectingState(NativeRealTimeRoom room, RoomSession session) : base(session, room) { mPercentPerParticipant = (100.0f - InitialPercentComplete) / (float)session.MinPlayersToStart; } internal override void OnStateEntered() { mSession.OnGameThreadListener().RoomSetupProgress(mPercentComplete); } internal override void HandleConnectedSetChanged(NativeRealTimeRoom room) { HashSet<string> newConnectedSet = new HashSet<string>(); // handle when an invitation is received, so number of total // participants is not known. if (room.Status() == Types.RealTimeRoomStatus.AUTO_MATCHING || room.Status() == Types.RealTimeRoomStatus.CONNECTING) { if (mSession.MinPlayersToStart <= room.ParticipantCount()) { mSession.MinPlayersToStart = mSession.MinPlayersToStart + room.ParticipantCount(); mPercentPerParticipant = (100.0f - InitialPercentComplete) / (float)mSession.MinPlayersToStart; } } foreach (var participant in room.Participants()) { using (participant) { if (participant.IsConnectedToRoom()) { newConnectedSet.Add(participant.Id()); } } } // If the connected set hasn't actually changed, bail out. if (mConnectedParticipants.Equals(newConnectedSet)) { Logger.w("Received connected set callback with unchanged connected set!"); return; } var noLongerConnected = mConnectedParticipants.Except(newConnectedSet); // Check if the room has been deleted. // creation. if (room.Status() == Types.RealTimeRoomStatus.DELETED) { Logger.e("Participants disconnected during room setup, failing. " + "Participants were: " + string.Join(",", noLongerConnected.ToArray())); mSession.OnGameThreadListener().RoomConnected(false); mSession.EnterState(new ShutdownState(mSession)); return; } var newlyConnected = newConnectedSet.Except(mConnectedParticipants); Logger.d("New participants connected: " + string.Join(",", newlyConnected.ToArray())); // If we're fully connected, transition to the Active state and signal the client. if (room.Status() == Types.RealTimeRoomStatus.ACTIVE) { Logger.d("Fully connected! Transitioning to active state."); mSession.EnterState(new ActiveState(room, mSession)); mSession.OnGameThreadListener().RoomConnected(true); return; } // Otherwise, we're not fully there. Increment the progress by the appropriate // amount and inform the client. mPercentComplete += mPercentPerParticipant * (float)newlyConnected.Count(); mConnectedParticipants = newConnectedSet; mSession.OnGameThreadListener().RoomSetupProgress(mPercentComplete); } internal override void HandleParticipantStatusChanged(NativeRealTimeRoom room, MultiplayerParticipant participant) { if (!FailedStatuses.Contains(participant.Status())) { return; } // call PeersDisconnected when the player leaves or declines // this let's the caller know that someone declined. mSession.OnGameThreadListener().ParticipantLeft(participant.AsParticipant()); if (room.Status() != Types.RealTimeRoomStatus.CONNECTING && room.Status() != Types.RealTimeRoomStatus.AUTO_MATCHING) { LeaveRoom(); } } internal override void LeaveRoom() { mSession.EnterState(new LeavingRoom(mSession, mRoom, () => mSession.OnGameThreadListener().RoomConnected(false))); } internal override void ShowWaitingRoomUI(uint minimumParticipantsBeforeStarting) { mSession.ShowingUI = true; mSession.Manager().ShowWaitingRoomUI(mRoom, minimumParticipantsBeforeStarting, response => { mSession.ShowingUI = false; Logger.d("ShowWaitingRoomUI Response: " + response.ResponseStatus()); if(response.ResponseStatus() == Status.UIStatus.VALID) { Logger.d("Connecting state ShowWaitingRoomUI: room pcount:" + response.Room().ParticipantCount() + " status: " + response.Room().Status()); if (response.Room().Status() == Types.RealTimeRoomStatus.ACTIVE) { mSession.EnterState(new ActiveState(response.Room(), mSession)); } } else if(response.ResponseStatus() == Status.UIStatus.ERROR_LEFT_ROOM){ LeaveRoom(); } else { mSession.OnGameThreadListener().RoomSetupProgress(this.mPercentComplete); } }); } } /// <summary>The active state, i.e. we have created a full mesh network and have informed the user. /// <para>The only transition out of 'Active' is into 'Leaving Room'. This occurs either when /// we are informed that the user has been unexpectedly disconnected, or when the user /// explicitly asks to leave.</para> /// </summary> class ActiveState : MessagingEnabledState { internal ActiveState(NativeRealTimeRoom room, RoomSession session) : base(session, room) { } internal override void OnStateEntered() { if (GetSelf() == null) { Logger.e("Room reached active state with unknown participant for the player"); LeaveRoom(); } } internal override bool IsRoomConnected() { return true; } internal override Participant GetParticipant(string participantId) { if (!mParticipants.ContainsKey(participantId)) { Logger.e("Attempted to retrieve unknown participant " + participantId); return null; } return mParticipants[participantId]; } internal override Participant GetSelf() { foreach (var participant in mParticipants.Values) { if (participant.Player != null && participant.Player.id.Equals(mSession.SelfPlayerId())) { return participant; } } return null; } internal override void HandleConnectedSetChanged(NativeRealTimeRoom room) { List<string> newlyConnected = new List<string>(); List<string> newlyLeft = new List<string>(); var updatedParticipants = room.Participants().ToDictionary(p => p.Id()); foreach (var participantId in mNativeParticipants.Keys) { var freshParticipant = updatedParticipants[participantId]; var staleParticipant = mNativeParticipants[participantId]; if (!freshParticipant.IsConnectedToRoom()) { newlyLeft.Add(participantId); } if (!staleParticipant.IsConnectedToRoom() && freshParticipant.IsConnectedToRoom()) { newlyConnected.Add(participantId); } } // Update the cached participants to reflect the new statuses by cleaning up the old // ones and then updating the new values. foreach (var participant in mNativeParticipants.Values) { participant.Dispose(); } mNativeParticipants = updatedParticipants; mParticipants = mNativeParticipants.Values .Select(p => p.AsParticipant()) .ToDictionary(p => p.ParticipantId); Logger.d("Updated participant statuses: " + string.Join(",", mParticipants.Values.Select(p => p.ToString()).ToArray())); // Check whether the current player was disconnected from the room. if (newlyLeft.Contains(GetSelf().ParticipantId)) { Logger.w("Player was disconnected from the multiplayer session."); } // Strip out the participant ID of the local player - this player is not a "peer". var selfId = GetSelf().ParticipantId; newlyConnected = newlyConnected.Where(peerId => !peerId.Equals(selfId)).ToList(); newlyLeft = newlyLeft.Where(peerId => !peerId.Equals(selfId)).ToList(); // Otherwise inform the client about changes in room participants, screening out // results about the local player. if (newlyConnected.Count > 0) { newlyConnected.Sort(); mSession.OnGameThreadListener() .PeersConnected(newlyConnected.Where(peer => !peer.Equals(selfId)).ToArray()); } if (newlyLeft.Count > 0) { newlyLeft.Sort(); mSession.OnGameThreadListener() .PeersDisconnected(newlyLeft.Where(peer => !peer.Equals(selfId)).ToArray()); } } internal override void LeaveRoom() { mSession.EnterState(new LeavingRoom(mSession, mRoom, () => mSession.OnGameThreadListener().LeftRoom())); } } /// <summary> /// A terminal state. Once this state is reached the session is considered dead and can be /// safely disposed of. /// </summary> class ShutdownState : State { private readonly RoomSession mSession; internal ShutdownState(RoomSession session) { mSession = Misc.CheckNotNull(session); } internal override bool IsActive() { return false; } internal override void LeaveRoom() { mSession.OnGameThreadListener().LeftRoom(); } } /// <summary> /// A state indicating the we're in the process of leaving a room. Sessions that enter this /// state immediately transition into 'Shutdown' after issuing a request to leave the room. /// </summary> class LeavingRoom : State { private readonly RoomSession mSession; private readonly NativeRealTimeRoom mRoomToLeave; private readonly Action mLeavingCompleteCallback; internal LeavingRoom(RoomSession session, NativeRealTimeRoom room, Action leavingCompleteCallback) { mSession = Misc.CheckNotNull(session); mRoomToLeave = Misc.CheckNotNull(room); mLeavingCompleteCallback = Misc.CheckNotNull(leavingCompleteCallback); } internal override bool IsActive() { return false; } internal override void OnStateEntered() { mSession.Manager().LeaveRoom(mRoomToLeave, (status) => { mLeavingCompleteCallback(); mSession.EnterState(new ShutdownState(mSession)); } ); } } /// <summary>The state indicating that we were in the process of creating a room, but that the /// user quit before this room was sucessfully created. This state is implemented such that any /// room response that we receive will result in the room being left, and the session /// transitioning to a terminal state. /// /// <para>This state transitions into 'Shutdown' (if the room creation failed) or 'Leaving room' /// (if room creation succeeded).</para> /// </summary> class AbortingRoomCreationState : State { private readonly RoomSession mSession; internal AbortingRoomCreationState(RoomSession session) { mSession = Misc.CheckNotNull(session); } internal override bool IsActive() { return false; } internal override void HandleRoomResponse(RealtimeManager.RealTimeRoomResponse response) { // If the room creation didn't succeed, we have nothing left to do, just bail out // and alert the user callback. if (!response.RequestSucceeded()) { mSession.EnterState(new ShutdownState(mSession)); mSession.OnGameThreadListener().RoomConnected(false); return; } // We just created a room which we're not going to use. Clean up and notify the user // when we're done. mSession.EnterState(new LeavingRoom(mSession, response.Room(), () => mSession.OnGameThreadListener().RoomConnected(false))); } } } } #endif
0
0.974116
1
0.974116
game-dev
MEDIA
0.313415
game-dev
0.98921
1
0.98921
NebulaSS13/Nebula
8,372
code/game/objects/structures/grille.dm
/obj/structure/grille name = "grille" desc = "A flimsy lattice of rods, with screws to secure it to the floor." icon = 'icons/obj/structures/grille.dmi' icon_state = "grille" density = TRUE anchored = TRUE obj_flags = OBJ_FLAG_CONDUCTIBLE | OBJ_FLAG_MOVES_UNSUPPORTED layer = BELOW_OBJ_LAYER explosion_resistance = 1 rad_resistance_modifier = 0.1 color = COLOR_STEEL material = /decl/material/solid/metal/steel parts_type = /obj/item/stack/material/rods parts_amount = 2 handle_generic_blending = TRUE material_alteration = MAT_FLAG_ALTERATION_COLOR | MAT_FLAG_ALTERATION_NAME max_health = 20 var/destroyed = 0 var/list/connections var/list/other_connections /obj/structure/grille/clear_connections() connections = null other_connections = null /obj/structure/grille/get_material_health_modifier() . = (1/15) /obj/structure/grille/set_connections(dirs, other_dirs) connections = dirs_to_corner_states(dirs) other_connections = dirs_to_corner_states(other_dirs) /obj/structure/grille/update_material_desc(override_desc) if(material) desc = "A lattice of [material.solid_name] rods, with screws to secure it to the floor." else ..() /obj/structure/grille/Initialize() . = ..() if(!istype(material)) . = INITIALIZE_HINT_QDEL if(. != INITIALIZE_HINT_QDEL) . = INITIALIZE_HINT_LATELOAD /obj/structure/grille/LateInitialize() ..() update_connections(1) update_icon() /obj/structure/grille/explosion_act(severity) ..() if(!QDELETED(src)) physically_destroyed() /obj/structure/grille/on_update_icon() ..() var/on_frame = is_on_frame() if(destroyed) if(on_frame) icon_state = "broken_onframe" else icon_state = "broken" else var/image/I icon_state = "" if(on_frame) for(var/i = 1 to 4) var/conn = connections ? connections[i] : "0" if(other_connections && other_connections[i] != "0") I = image(icon, "grille_other_onframe[conn]", dir = BITFLAG(i-1)) else I = image(icon, "grille_onframe[conn]", dir = BITFLAG(i-1)) add_overlay(I) else for(var/i = 1 to 4) var/conn = connections ? connections[i] : "0" if(other_connections && other_connections[i] != "0") I = image(icon, "grille_other[conn]", dir = BITFLAG(i-1)) else I = image(icon, "grille[conn]", dir = BITFLAG(i-1)) add_overlay(I) /obj/structure/grille/Bumped(atom/user) if(ismob(user)) shock(user, 70) /obj/structure/grille/attack_hand(mob/user) if(!user.check_intent(I_FLAG_HARM)) return ..() user.setClickCooldown(DEFAULT_ATTACK_COOLDOWN) playsound(loc, 'sound/effects/grillehit.ogg', 80, 1) user.do_attack_animation(src) if(shock(user, 70)) return TRUE var/damage_dealt = 1 var/attack_message = "kicks" if(user.can_shred()) attack_message = "mangles" damage_dealt = 5 attack_generic(user, damage_dealt, attack_message) return TRUE /obj/structure/grille/CanPass(atom/movable/mover, turf/target, height=0, air_group=0) if(air_group || (height==0)) return 1 if(istype(mover) && mover.checkpass(PASS_FLAG_GRILLE)) return 1 else if(istype(mover, /obj/item/projectile)) return prob(30) else return !density /obj/structure/grille/bullet_act(var/obj/item/projectile/Proj) if(!Proj) return //Flimsy grilles aren't so great at stopping projectiles. However they can absorb some of the impact var/damage = Proj.get_structure_damage() var/passthrough = 0 if(!damage) return //20% chance that the grille provides a bit more cover than usual. Support structure for example might take up 20% of the grille's area. //If they click on the grille itself then we assume they are aiming at the grille itself and the extra cover behaviour is always used. switch(Proj.atom_damage_type) if(BRUTE) //bullets if(Proj.original == src || prob(20)) Proj.damage *= clamp(Proj.damage/60, 0, 0.5) if(prob(max((damage-10)/25, 0))*100) passthrough = 1 else Proj.damage *= clamp(Proj.damage/60, 0, 1) passthrough = 1 if(BURN) //beams and other projectiles are either blocked completely by grilles or stop half the damage. if(!(Proj.original == src || prob(20))) Proj.damage *= 0.5 passthrough = 1 if(passthrough) . = PROJECTILE_CONTINUE damage = clamp((damage - Proj.damage)*(Proj.atom_damage_type == BRUTE? 0.4 : 1), 0, 10) //if the bullet passes through then the grille avoids most of the damage take_damage(damage*0.2, Proj.atom_damage_type) /obj/structure/grille/proc/cut_grille() playsound(loc, 'sound/items/Wirecutter.ogg', 100, 1) if(destroyed) qdel(src) else set_density(0) if(material) var/res = material.create_object(get_turf(src), 1, parts_type) if(paint_color) for(var/obj/item/thing in res) thing.set_color(paint_color) destroyed = TRUE parts_amount = 1 update_icon() /obj/structure/grille/attackby(obj/item/used_item, mob/user) if(IS_WIRECUTTER(used_item)) if(!material.conductive || !shock(user, 100)) cut_grille() return TRUE if((IS_SCREWDRIVER(used_item))) var/turf/turf = loc if(((istype(turf) && turf.simulated) || anchored)) if(!shock(user, 90)) playsound(loc, 'sound/items/Screwdriver.ogg', 100, 1) anchored = !anchored user.visible_message( SPAN_NOTICE("[user] [anchored ? "fastens" : "unfastens"] the grille."), SPAN_NOTICE("You have [anchored ? "fastened the grille to" : "unfastened the grill from"] the floor.") ) update_connections(1) update_icon() return TRUE //window placing if(istype(used_item,/obj/item/stack/material)) var/obj/item/stack/material/ST = used_item if(ST.material.opacity > 0.7) return FALSE var/dir_to_set = 5 if(!is_on_frame()) if(loc == user.loc) dir_to_set = user.dir else dir_to_set = get_dir(loc, user) if(dir_to_set & (dir_to_set - 1)) //Only works for cardinal direcitons, diagonals aren't supposed to work like this. to_chat(user, "<span class='notice'>You can't reach.</span>") return TRUE place_window(user, loc, dir_to_set, ST) return TRUE if(!(used_item.obj_flags & OBJ_FLAG_CONDUCTIBLE) || !shock(user, 70)) user.setClickCooldown(DEFAULT_ATTACK_COOLDOWN) user.do_attack_animation(src) playsound(loc, 'sound/effects/grillehit.ogg', 80, 1) switch(used_item.atom_damage_type) if(BURN) take_damage(used_item.expend_attack_force(user)) if(BRUTE) take_damage(used_item.expend_attack_force(user) * 0.1) return TRUE return ..() /obj/structure/grille/physically_destroyed(var/skip_qdel) SHOULD_CALL_PARENT(FALSE) if(!destroyed) visible_message(SPAN_DANGER("\The [src] falls to pieces!")) cut_grille() . = TRUE // shock user with probability prb (if all connections & power are working) // returns 1 if shocked, 0 otherwise /obj/structure/grille/proc/shock(mob/user, prb) if(!anchored || destroyed) // anchored/destroyed grilles are never connected return FALSE if(!(material.conductive)) return FALSE if(!prob(prb)) return FALSE if(!in_range(src, user))//To prevent TK and exosuit users from getting shocked return FALSE var/turf/my_turf = get_turf(src) var/obj/structure/cable/cable = my_turf.get_cable_node() if(!cable) return FALSE if(!electrocute_mob(user, cable, src)) return FALSE if(cable.powernet) cable.powernet.trigger_warning() spark_at(src, cardinal_only = TRUE) return !!HAS_STATUS(user, STAT_STUN) /obj/structure/grille/fire_act(datum/gas_mixture/air, exposed_temperature, exposed_volume) if(!destroyed) if(exposed_temperature > material.temperature_damage_threshold) take_damage(1, BURN) ..() // Used in mapping to avoid /obj/structure/grille/broken destroyed = 1 icon_state = "broken" density = FALSE /obj/structure/grille/broken/Initialize() . = ..() take_damage(rand(1, 5)) //In the destroyed but not utterly threshold. /obj/structure/grille/proc/is_on_frame() if(locate(/obj/structure/wall_frame) in loc) return TRUE /proc/place_grille(mob/user, loc, obj/item/stack/material/rods/ST) if(ST.in_use) return if(ST.get_amount() < 2) to_chat(user, SPAN_WARNING("You need at least two rods to do this.")) return user.visible_message(SPAN_NOTICE("\The [user] begins assembling a [ST.material.solid_name] grille.")) if(do_after(user, 1 SECOND, ST) && ST.use(2)) var/obj/structure/grille/F = new(loc, ST.material.type) user.visible_message(SPAN_NOTICE("\The [user] finishes building \a [F].")) F.add_fingerprint(user)
0
0.991094
1
0.991094
game-dev
MEDIA
0.929433
game-dev
0.956074
1
0.956074
shiptest-ss13/Shiptest
13,391
code/modules/mob/living/carbon/human/species_types/ethereal.dm
#define ELZUOSE_EMAG_COLORS list("#00ffff", "#ffc0cb", "#9400D3", "#4B0082", "#0000FF", "#00FF00", "#FFFF00", "#FF7F00", "#FF0000") #define GOOD_SOIL list(/turf/open/floor/ship/dirt, /turf/open/floor/grass/ship, /turf/open/floor/plating/asteroid/whitesands/grass, /turf/open/floor/grass/fairy/beach, /turf/open/floor/plating/asteroid/dirt) #define DIG_TIME (7.5 SECONDS) #define ROOT_TIME (3 SECONDS) #define ROOT_CHARGE_GAIN (5 * ELZUOSE_CHARGE_SCALING_MULTIPLIER) /datum/species/elzuose name = "\improper Elzuose" id = SPECIES_ELZUOSE attack_verb = "burn" attack_sound = 'sound/weapons/etherealhit.ogg' miss_sound = 'sound/weapons/etherealmiss.ogg' meat = /obj/item/food/meat/slab/human/mutant/ethereal mutantstomach = /obj/item/organ/stomach/ethereal mutanttongue = /obj/item/organ/tongue/ethereal siemens_coeff = 0.5 //They thrive on energy attack_type = BURN //burn bish exotic_bloodtype = "E" species_age_max = 300 species_traits = list(DYNCOLORS, EYECOLOR, HAIR, FACEHAIR, HAS_FLESH, HAS_BONE) changesource_flags = MIRROR_BADMIN | WABBAJACK | MIRROR_PRIDE | MIRROR_MAGIC | RACE_SWAP | ERT_SPAWN species_language_holder = /datum/language_holder/ethereal inherent_traits = list(TRAIT_NOHUNGER) toxic_food = NONE // Body temperature for ethereals is much higher then humans as they like hotter environments bodytemp_normal = (HUMAN_BODYTEMP_NORMAL + 50) bodytemp_heat_damage_limit = (HUMAN_BODYTEMP_NORMAL + 65) // Cold temperatures hurt faster as it is harder to move with out the heat energy bodytemp_cold_damage_limit = (HUMAN_BODYTEMP_NORMAL - 20) min_temp_comfortable = (HUMAN_BODYTEMP_NORMAL - 10) max_temp_comfortable = HUMAN_BODYTEMP_NORMAL + 55 hair_color = "fixedmutcolor" hair_alpha = 140 mutant_bodyparts = list("elzu_horns", "tail_elzu") default_features = list("elzu_horns" = "None", "tail_elzu" = "None", "body_size" = "Normal") species_eye_path = 'icons/mob/ethereal_parts.dmi' mutant_organs = list(/obj/item/organ/tail/elzu) species_chest = /obj/item/bodypart/chest/ethereal species_head = /obj/item/bodypart/head/ethereal species_l_arm = /obj/item/bodypart/l_arm/ethereal species_r_arm = /obj/item/bodypart/r_arm/ethereal species_l_leg = /obj/item/bodypart/leg/left/ethereal species_r_leg = /obj/item/bodypart/leg/right/ethereal var/current_color var/EMPeffect = FALSE var/static/unhealthy_color = rgb(237, 164, 149) loreblurb = "Elzuosa are an uncommon and unusual species best described as crystalline, electrically-powered plantpeople. They hail from the warm planet Kalixcis, where they evolved alongside the Sarathi. Kalixcian culture places no importance on blood-bonds, and those from it tend to consider their family anyone they are sufficiently close to, and choose their own names." var/drain_time = 0 //used to keep ethereals from spam draining power sources var/obj/effect/dummy/lighting_obj/ethereal_light var/datum/action/innate/root/rooting /datum/species/elzuose/Destroy(force) if(ethereal_light) QDEL_NULL(ethereal_light) return ..() /datum/species/elzuose/on_species_gain(mob/living/carbon/_carbon, datum/species/old_species, pref_load) . = ..() if(!ishuman(_carbon)) return var/mob/living/carbon/human/ethereal = _carbon default_color = "#[ethereal.dna.features["ethcolor"]]" RegisterSignal(ethereal, COMSIG_ATOM_EMP_ACT, PROC_REF(on_emp_act)) ethereal_light = ethereal.mob_light() spec_updatehealth(ethereal) rooting = new rooting.Grant(_carbon) RegisterSignal(ethereal, COMSIG_DIGOUT, PROC_REF(digout)) RegisterSignal(ethereal, COMSIG_MOVABLE_MOVED, PROC_REF(uproot)) //The following code is literally only to make admin-spawned ethereals not be black. _carbon.dna.features["mcolor"] = _carbon.dna.features["ethcolor"] //Ethcolor and Mut color are both dogshit and will be replaced for(var/obj/item/bodypart/BP as anything in _carbon.bodyparts) if(BP.limb_id == SPECIES_ELZUOSE) BP.update_limb(is_creating = TRUE) /datum/species/elzuose/on_species_loss(mob/living/carbon/human/_carbon, datum/species/new_species, pref_load) UnregisterSignal(_carbon, COMSIG_ATOM_EMP_ACT) UnregisterSignal(_carbon, COMSIG_DIGOUT) UnregisterSignal(_carbon, COMSIG_MOVABLE_MOVED) QDEL_NULL(ethereal_light) if(rooting) rooting.Remove(_carbon) return ..() /datum/action/innate/root name = "Root" desc = "Root into good soil to gain charge." check_flags = AB_CHECK_CONSCIOUS button_icon_state = "plant-22" icon_icon = 'icons/obj/flora/plants.dmi' background_icon_state = "bg_alien" /datum/action/innate/root/Activate() var/mob/living/carbon/human/_human = owner var/datum/species/elzuose/_elzu = _human.dna.species // this is healthy for elzu, they shouldnt be able to overcharge and get heart attacks from this var/obj/item/organ/stomach/ethereal/stomach = _human.getorganslot(ORGAN_SLOT_STOMACH) if(_human.wear_suit && istype(_human.wear_suit, /obj/item/clothing)) var/obj/item/clothing/CS = _human.wear_suit if (CS.clothing_flags & THICKMATERIAL) to_chat(_human, span_warning("Your [CS.name] is too thick to root in!")) return if(stomach.crystal_charge > ELZUOSE_CHARGE_FULL) to_chat(_human,span_warning("Your charge is full!")) return _elzu.drain_time = world.time + ROOT_TIME _human.visible_message(span_notice("[_human] is digging into the ground"),span_warning("You start to dig yourself into the ground to root. You won't won't be able to move once you start the process."),span_notice("You hear digging.")) if(!do_after(_human,DIG_TIME, target = _human)) to_chat(_human,span_warning("You were interupted!")) return _human.apply_status_effect(/datum/status_effect/rooted) to_chat(_human, span_notice("You root into the ground and begin to feed.")) while(do_after(_human, ROOT_TIME, target = _human)) if(istype(stomach)) to_chat(_human, span_notice("You receive some charge from rooting.")) stomach.adjust_charge(ROOT_CHARGE_GAIN) _human.adjustBruteLoss(-3) _human.adjustFireLoss(-3) if(stomach.crystal_charge > ELZUOSE_CHARGE_FULL) stomach.crystal_charge = ELZUOSE_CHARGE_FULL to_chat(_human, span_notice("You're full on charge!")) break else to_chat(_human,span_warning("You're missing your biological battery and can't recieve charge from rooting!")) break /datum/species/elzuose/proc/digout(mob/living/carbon/human/_human) if(do_after(_human, DIG_TIME,target = _human)) to_chat(_human,span_notice("You finish digging yourself out.")) _human.remove_status_effect(/datum/status_effect/rooted) return /datum/species/elzuose/proc/uproot(mob/living/carbon/human/_human) //You got moved and uprooted, time to suffer the consequences. if(_human.has_status_effect(/datum/status_effect/rooted)) _human.visible_message(span_warning("[_human] is forcefully uprooted. That looked like it hurt."),span_warning("You're forcefully unrooted! Ouch!"),span_warning("You hear someone scream in pain.")) _human.apply_damage(8,BRUTE,BODY_ZONE_CHEST) _human.apply_damage(8,BRUTE,BODY_ZONE_L_LEG) _human.apply_damage(8,BRUTE,BODY_ZONE_R_LEG) _human.force_scream() _human.remove_status_effect(/datum/status_effect/rooted) return /datum/action/innate/root/IsAvailable() if(..()) var/mob/living/carbon/human/_human = owner var/turf/terrain = get_turf(_human) if(_human.has_status_effect(/datum/status_effect/rooted)) return FALSE if(is_type_in_list(terrain, GOOD_SOIL)) return TRUE for(var/atom/movable/thing in terrain.contents) if(is_type_in_list(thing, list(/obj/machinery/hydroponics/wooden, /obj/machinery/hydroponics/soil))) return TRUE return FALSE /datum/species/elzuose/random_name(gender,unique,lastname) if(unique) return random_unique_lizard_name(gender) var/randname = lizard_name(gender) if(lastname) randname += " [lastname]" return randname /datum/species/elzuose/spec_updatehealth(mob/living/carbon/human/_human) . = ..() if(!ethereal_light) return if(_human.stat != DEAD && !EMPeffect) current_color = health_adjusted_color(_human, default_color) set_ethereal_light(_human, current_color) ethereal_light.set_light_on(TRUE) fixed_mut_color = copytext_char(current_color, 2) else ethereal_light.set_light_on(FALSE) fixed_mut_color = rgb(128,128,128) for(var/obj/item/bodypart/parts_to_update as anything in _human.bodyparts) parts_to_update.species_color = fixed_mut_color parts_to_update.update_limb() _human.update_body() _human.update_hair() /datum/species/elzuose/proc/health_adjusted_color(mob/living/carbon/human/_human, default_color) var/health_percent = max(_human.health, 0) / 100 var/static/unhealthy_color_red_part = GETREDPART(unhealthy_color) var/static/unhealthy_color_green_part = GETGREENPART(unhealthy_color) var/static/unhealthy_color_blue_part = GETBLUEPART(unhealthy_color) var/default_color_red_part = GETREDPART(default_color) var/default_color_green_part = GETGREENPART(default_color) var/default_color_blue_part = GETBLUEPART(default_color) var/result = rgb( unhealthy_color_red_part + ((default_color_red_part - unhealthy_color_red_part) * health_percent), unhealthy_color_green_part + ((default_color_green_part - unhealthy_color_green_part) * health_percent), unhealthy_color_blue_part + ((default_color_blue_part - unhealthy_color_blue_part) * health_percent) ) return result /datum/species/elzuose/proc/set_ethereal_light(mob/living/carbon/human/_human, current_color) if(!ethereal_light) return var/health_percent = max(_human.health, 0) / 100 var/light_range = 1 + (1 * health_percent) var/light_power = 1 + round(0.5 * health_percent) ethereal_light.set_light_range_power_color(light_range, light_power, current_color) /datum/species/elzuose/proc/on_emp_act(mob/living/carbon/human/_human, severity) EMPeffect = TRUE spec_updatehealth(_human) to_chat(_human, span_notice("You feel the light of your body leave you.")) switch(severity) if(EMP_LIGHT) addtimer(CALLBACK(src, PROC_REF(stop_emp), _human), 10 SECONDS, TIMER_UNIQUE|TIMER_OVERRIDE) //We're out for 10 seconds if(EMP_HEAVY) addtimer(CALLBACK(src, PROC_REF(stop_emp), _human), 20 SECONDS, TIMER_UNIQUE|TIMER_OVERRIDE) //We're out for 20 seconds /datum/species/elzuose/spec_life(mob/living/carbon/human/_human) .=..() handle_charge(_human) /datum/species/elzuose/proc/stop_emp(mob/living/carbon/human/_human) EMPeffect = FALSE spec_updatehealth(_human) to_chat(_human, span_notice("You feel more energized as your shine comes back.")) /datum/species/elzuose/proc/handle_charge(mob/living/carbon/human/_human) switch(get_charge(_human)) if(ELZUOSE_CHARGE_NONE to ELZUOSE_CHARGE_LOWPOWER) if(get_charge(_human) == ELZUOSE_CHARGE_NONE) _human.throw_alert("ELZUOSE_CHARGE", /atom/movable/screen/alert/etherealcharge, 3) else _human.throw_alert("ELZUOSE_CHARGE", /atom/movable/screen/alert/etherealcharge, 2) if(_human.health > 10.5) apply_damage(0.2, TOX, null, null, _human) if(ELZUOSE_CHARGE_LOWPOWER to ELZUOSE_CHARGE_NORMAL) _human.throw_alert("ELZUOSE_CHARGE", /atom/movable/screen/alert/etherealcharge, 1) if(ELZUOSE_CHARGE_FULL to ELZUOSE_CHARGE_OVERLOAD) _human.throw_alert("ethereal_overcharge", /atom/movable/screen/alert/ethereal_overcharge, 1) if(ELZUOSE_CHARGE_OVERLOAD to ELZUOSE_CHARGE_DANGEROUS) _human.throw_alert("ethereal_overcharge", /atom/movable/screen/alert/ethereal_overcharge, 2) if(prob(10)) //10% each tick for ethereals to explosively release excess energy if it reaches dangerous levels discharge_process(_human) else _human.clear_alert("ELZUOSE_CHARGE") _human.clear_alert("ethereal_overcharge") /datum/species/elzuose/proc/discharge_process(mob/living/carbon/human/_human) _human.visible_message(span_danger("[_human] begins to spark violently!"),_human,span_warning("You begin to lose control over your charge!")) var/static/mutable_appearance/overcharge //shameless copycode from lightning spell overcharge = overcharge || mutable_appearance('icons/effects/effects.dmi', "electricity", EFFECTS_LAYER) _human.add_overlay(overcharge) if(do_after(_human, 50, _human, TRUE)) _human.flash_lighting_fx(5, 7, current_color) var/obj/item/organ/stomach/ethereal/stomach = _human.getorganslot(ORGAN_SLOT_STOMACH) playsound(_human, 'sound/magic/lightningshock.ogg', 100, TRUE, extrarange = 5) _human.cut_overlay(overcharge) tesla_zap(_human, 2, (stomach.crystal_charge / ELZUOSE_CHARGE_SCALING_MULTIPLIER) * 50, ZAP_OBJ_DAMAGE | ZAP_ALLOW_DUPLICATES) if(istype(stomach)) stomach.adjust_charge(ELZUOSE_CHARGE_FULL - stomach.crystal_charge) to_chat(_human,span_warning("You violently discharge energy!")) _human.visible_message(span_danger("[_human] violently discharges energy!")) if(prob(10)) //chance of developing heart disease to dissuade overcharging oneself var/datum/disease/D = new /datum/disease/heart_failure _human.ForceContractDisease(D) to_chat(_human, span_userdanger("You're pretty sure you just felt your heart stop for a second there.")) _human.playsound_local(_human, 'sound/effects/singlebeat.ogg', 100, 0) _human.Paralyze(100) return /datum/species/elzuose/proc/get_charge(mob/living/carbon/_human) //this feels like it should be somewhere else. Eh? var/obj/item/organ/stomach/ethereal/stomach = _human.getorganslot(ORGAN_SLOT_STOMACH) if(istype(stomach)) return stomach.crystal_charge return ELZUOSE_CHARGE_NONE
0
0.938784
1
0.938784
game-dev
MEDIA
0.960931
game-dev
0.653203
1
0.653203
jhocking/uia-3e
2,110
ch12/Assets/Scripts/UIController.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; using TMPro; public class UIController : MonoBehaviour { [SerializeField] TMP_Text healthLabel; [SerializeField] TMP_Text levelEnding; [SerializeField] InventoryPopup popup; void OnEnable() { Messenger.AddListener(GameEvent.HEALTH_UPDATED, OnHealthUpdated); Messenger.AddListener(GameEvent.LEVEL_FAILED, OnLevelFailed); Messenger.AddListener(GameEvent.LEVEL_COMPLETE, OnLevelComplete); Messenger.AddListener(GameEvent.GAME_COMPLETE, OnGameComplete); } void OnDisable() { Messenger.RemoveListener(GameEvent.HEALTH_UPDATED, OnHealthUpdated); Messenger.RemoveListener(GameEvent.LEVEL_FAILED, OnLevelFailed); Messenger.RemoveListener(GameEvent.LEVEL_COMPLETE, OnLevelComplete); Messenger.RemoveListener(GameEvent.GAME_COMPLETE, OnGameComplete); } void Start() { OnHealthUpdated(); levelEnding.gameObject.SetActive(false); popup.gameObject.SetActive(false); } void Update() { if (Input.GetKeyDown(KeyCode.M)) { bool isShowing = popup.gameObject.activeSelf; popup.gameObject.SetActive(!isShowing); popup.Refresh(); } } private void OnHealthUpdated() { string message = $"Health: {Managers.Player.health}/{Managers.Player.maxHealth}"; healthLabel.text = message; } private void OnLevelFailed() { StartCoroutine(FailLevel()); } private IEnumerator FailLevel() { levelEnding.gameObject.SetActive(true); levelEnding.text = "Level Failed"; yield return new WaitForSeconds(2); Managers.Player.Respawn(); Managers.Mission.RestartCurrent(); } private void OnLevelComplete() { StartCoroutine(CompleteLevel()); } private IEnumerator CompleteLevel() { levelEnding.gameObject.SetActive(true); levelEnding.text = "Level Complete!"; yield return new WaitForSeconds(2); Managers.Mission.GoToNext(); } private void OnGameComplete() { levelEnding.gameObject.SetActive(true); levelEnding.text = "You Finished the Game!"; } public void SaveGame() { Managers.Data.SaveGameState(); } public void LoadGame() { Managers.Data.LoadGameState(); } }
0
0.844303
1
0.844303
game-dev
MEDIA
0.588878
game-dev
0.916834
1
0.916834
aysihuniks/NClaim
13,332
src/main/java/nesoi/aysihuniks/nclaim/ui/claim/management/TimeManagementMenu.java
package nesoi.aysihuniks.nclaim.ui.claim.management; import com.google.common.collect.Sets; import nesoi.aysihuniks.nclaim.NClaim; import nesoi.aysihuniks.nclaim.enums.Balance; import nesoi.aysihuniks.nclaim.model.Claim; import nesoi.aysihuniks.nclaim.model.User; import nesoi.aysihuniks.nclaim.ui.shared.BackgroundMenu; import nesoi.aysihuniks.nclaim.ui.shared.BaseMenu; import nesoi.aysihuniks.nclaim.utils.MessageType; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.inventory.ClickType; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.nandayo.dapi.util.ItemCreator; import org.nandayo.dapi.guimanager.button.Button; import org.nandayo.dapi.guimanager.MenuType; import org.nandayo.dapi.guimanager.button.SingleSlotButton; import org.nandayo.dapi.message.ChannelType; import org.nandayo.dapi.object.DMaterial; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.function.Function; public class TimeManagementMenu extends BaseMenu { private int days; private int hours; private int minutes; private int timeUnit; private final @NotNull Claim claim; private final boolean admin; public TimeManagementMenu(@NotNull Player player, int days, int hours, int minutes, int timeUnit, @NotNull Claim claim, boolean admin) { super("claim_time_management_menu"); this.claim = claim; this.days = days; this.hours = hours; this.minutes = minutes; this.timeUnit = timeUnit; this.admin = admin; setupMenu(); displayTo(player); } @Override public Function<Integer, @Nullable SingleSlotButton> backgroundButtonFunction() { return BackgroundMenu::getButton; } private void setupMenu() { createInventory(MenuType.CHEST_5_ROWS, getString("title")); addButton(new Button() { @Override public @NotNull Set<Integer> getSlots() { return Sets.newHashSet(13); } @Override public ItemStack getItem() { List<String> lore = new ArrayList<>(getStringList("claim_info.lore")); lore.replaceAll(s -> s.replace("{time_left}", NClaim.inst().getClaimExpirationManager().getFormattedTimeLeft(claim)) .replace("{expires_at}", NClaim.serializeDate(claim.getExpiredAt()))); return ItemCreator.of(NClaim.getMaterial(DMaterial.GLOW_ITEM_FRAME, DMaterial.ITEM_FRAME)) .name(getString("claim_info.display_name")) .lore(lore) .get(); } }); addButton(new Button() { @Override public @NotNull Set<Integer> getSlots() { return Sets.newHashSet(31); } @Override public ItemStack getItem() { double totalPrice = calculateTotalPrice(); double tax = totalPrice * NClaim.inst().getNconfig().getTimeExtensionTaxRate(); double finalPrice = totalPrice + tax; List<String> lore = new ArrayList<>(getStringList("confirm.lore")); String priceStr = admin ? NClaim.inst().getGuiLangManager().getString("free") : String.format("%.2f", finalPrice); lore.replaceAll(s -> s.replace("{price}", priceStr) .replace("{d}", String.valueOf(days)) .replace("{h}", String.valueOf(hours)) .replace("{m}", String.valueOf(minutes))); return ItemCreator.of(Material.BLUE_ICE) .name(getString("confirm.display_name")) .lore(lore) .get(); } @Override public void onClick(@NotNull Player player, @NotNull ClickType clickType) { if (days == 0 && hours == 0 && minutes == 0) { ChannelType.CHAT.send(player, NClaim.inst().getLangManager().getString("claim.time.no_time_selected")); MessageType.FAIL.playSound(player); return; } if (!admin) { double totalPrice = calculateTotalPrice(); double tax = totalPrice * NClaim.inst().getNconfig().getTimeExtensionTaxRate(); double finalPrice = totalPrice + tax; if (NClaim.inst().getBalanceSystem() == Balance.PLAYERDATA) { User user = User.getUser(player.getUniqueId()); if (user == null) { ChannelType.CHAT.send(player, NClaim.inst().getLangManager().getString("command.player_data_not_found")); MessageType.FAIL.playSound(player); return; } if (user.getBalance() < finalPrice) { ChannelType.CHAT.send(player, NClaim.inst().getLangManager().getString("command.balance.not_enough")); MessageType.FAIL.playSound(player); return; } user.addBalance(-finalPrice); } else { if (NClaim.inst().getEconomy().getBalance(player) < finalPrice) { ChannelType.CHAT.send(player, NClaim.inst().getLangManager().getString("command.balance.not_enough")); MessageType.FAIL.playSound(player); return; } NClaim.inst().getEconomy().withdrawPlayer(player, finalPrice); } } NClaim.inst().getClaimExpirationManager().extendClaimExpiration(claim, days, hours, minutes); String priceStr = admin ? NClaim.inst().getGuiLangManager().getString("free") : String.format("%.2f", calculateTotalPrice() + calculateTotalPrice() * NClaim.inst().getNconfig().getTimeExtensionTaxRate()); ChannelType.CHAT.send(player, NClaim.inst().getLangManager().getString("command.expiration_extended") .replace("{d}", String.valueOf(days)) .replace("{h}", String.valueOf(hours)) .replace("{m}", String.valueOf(minutes)) .replace("{price}", priceStr)); MessageType.CONFIRM.playSound(player); player.closeInventory(); } }); addButton(new Button() { @Override public @NotNull Set<Integer> getSlots() { return Sets.newHashSet(10); } @Override public ItemStack getItem() { return ItemCreator.of(Material.OAK_DOOR) .name(NClaim.inst().getGuiLangManager().getString("back.display_name")) .get(); } @Override public void onClick(@NotNull Player player, @NotNull ClickType clickType) { if(!admin && !claim.isOwner(player.getUniqueId())) { MessageType.FAIL.playSound(player); return; } MessageType.MENU_BACK.playSound(player); new ClaimManagementMenu(player, claim, admin); } }); addButton(new Button() { @Override public @NotNull Set<Integer> getSlots() { return Sets.newHashSet(16); } @Override public ItemStack getItem() { List<String> lore = new ArrayList<>(getStringList("select_time_unit.lore")); lore.replaceAll(s -> s.replace("{days_status}", timeUnit == 0 ? "&e" + getString("days_status") : "&7" + getString("days_status")) .replace("{hours_status}", timeUnit == 1 ? "&e" + getString("hours_status") : "&7" + getString("hours_status")) .replace("{minutes_status}", timeUnit == 2 ? "&e" + getString("minutes_status") : "&7" + getString("minutes_status"))); return ItemCreator.of(Material.CHAIN) .name(getString("select_time_unit.display_name")) .lore(lore) .get(); } @Override public void onClick(@NotNull Player player, @NotNull ClickType clickType) { timeUnit = (timeUnit + 1) % 3; MessageType.MENU_REFRESH.playSound(player); new TimeManagementMenu(player, days, hours, minutes, timeUnit, claim, admin); } }); addTimeButtons(); } private double calculateTotalPrice() { return (days * NClaim.inst().getNconfig().getTimeExtensionPricePerDay()) + (hours * NClaim.inst().getNconfig().getTimeExtensionPricePerHour()) + (minutes * NClaim.inst().getNconfig().getTimeExtensionPricePerMinute()); } private void addTimeButtons() { addButton(new Button() { @Override public @NotNull Set<Integer> getSlots() { return Sets.newHashSet(28); } @Override public ItemStack getItem() { return ItemCreator.of(Material.LIME_CONCRETE) .name(getString("add_one.display_name") .replace("{unit}", getTimeUnitString())) .get(); } @Override public void onClick(@NotNull Player player, @NotNull ClickType clickType) { adjustTime(1, admin); MessageType.VALUE_INCREASE.playSound(player); new TimeManagementMenu(player, days, hours, minutes, timeUnit, claim, admin); } }); addButton(new Button() { @Override public @NotNull Set<Integer> getSlots() { return Sets.newHashSet(29); } @Override public ItemStack getItem() { return ItemCreator.of(Material.GREEN_CONCRETE) .name(getString("add_six.display_name") .replace("{unit}", getTimeUnitString())) .get(); } @Override public void onClick(@NotNull Player player, @NotNull ClickType clickType) { adjustTime(6, admin); MessageType.VALUE_INCREASE.playSound(player); new TimeManagementMenu(player, days, hours, minutes, timeUnit, claim, admin); } }); addButton(new Button() { @Override public @NotNull Set<Integer> getSlots() { return Sets.newHashSet(33); } @Override public ItemStack getItem() { return ItemCreator.of(Material.PINK_CONCRETE) .name(getString("subtract_one.display_name") .replace("{unit}", getTimeUnitString())) .get(); } @Override public void onClick(@NotNull Player player, @NotNull ClickType clickType) { adjustTime(-1, admin); MessageType.VALUE_DECREASE.playSound(player); new TimeManagementMenu(player, days, hours, minutes, timeUnit, claim, admin); } }); addButton(new Button() { @Override public @NotNull Set<Integer> getSlots() { return Sets.newHashSet(34); } @Override public ItemStack getItem() { return ItemCreator.of(Material.RED_CONCRETE) .name(getString("subtract_six.display_name") .replace("{unit}", getTimeUnitString())) .get(); } @Override public void onClick(@NotNull Player player, @NotNull ClickType clickType) { adjustTime(-6, admin); MessageType.VALUE_DECREASE.playSound(player); new TimeManagementMenu(player, days, hours, minutes, timeUnit, claim, admin); } }); } private String getTimeUnitString() { switch (timeUnit) { case 1: return getString("hours_status"); case 2: return getString("minutes_status"); default: return getString("days_status"); } } private void adjustTime(int amount, boolean admin) { switch (timeUnit) { case 0: days = admin ? days + amount : Math.max(0, days + amount); break; case 1: hours = admin ? hours + amount : Math.max(0, hours + amount); break; case 2: minutes = admin ? minutes + amount : Math.max(0, minutes + amount); break; } } }
0
0.926
1
0.926
game-dev
MEDIA
0.678701
game-dev
0.988199
1
0.988199
andreasdr/tdme2
3,628
src/tdme/engine/PointsParticleSystem.cpp
#include <tdme/engine/PointsParticleSystem.h> #include <string> #include <tdme/tdme.h> #include <tdme/engine/fileio/textures/fwd-tdme.h> #include <tdme/engine/primitives/BoundingBox.h> #include <tdme/engine/Engine.h> #include <tdme/engine/Partition.h> #include <tdme/engine/Transform.h> using std::string; using tdme::engine::primitives::BoundingBox; using tdme::engine::Engine; using tdme::engine::Partition; using tdme::engine::PointsParticleSystem; using tdme::engine::Texture; using tdme::engine::Transform; PointsParticleSystem::PointsParticleSystem(const string& id, ParticleEmitter* emitter, int32_t maxPoints, float pointSize, bool autoEmit, Texture* texture, int32_t textureHorizontalSprites, int32_t textureVerticalSprites, float fps) : PointsParticleSystemInternal(id, emitter, maxPoints, pointSize, autoEmit, texture, textureHorizontalSprites, textureVerticalSprites, fps) { } void PointsParticleSystem::initialize() { PointsParticleSystemInternal::initialize(); } void PointsParticleSystem::setTransform(const Transform& transform) { PointsParticleSystemInternal::setTransform(transform); // if (parentEntity == nullptr && frustumCulling == true && engine != nullptr && enabled == true) engine->partition->updateEntity(this); } void PointsParticleSystem::update() { // PointsParticleSystemInternal::update(); // if (parentEntity == nullptr && frustumCulling == true && engine != nullptr && enabled == true) engine->partition->updateEntity(this); } void PointsParticleSystem::setEnabled(bool enabled) { // return if enable state has not changed if (this->enabled == enabled) return; // frustum if root entity if (parentEntity == nullptr) { // frustum culling enabled? if (frustumCulling == true) { // yeo, add or remove from partition if (enabled == true) { if (engine != nullptr) engine->partition->addEntity(this); } else { if (engine != nullptr) engine->partition->removeEntity(this); } } } // call parent class::setEnabled() PointsParticleSystemInternal::setEnabled(enabled); } void PointsParticleSystem::updateParticles() { PointsParticleSystemInternal::updateParticles(); if (parentEntity == nullptr && frustumCulling == true && engine != nullptr && enabled == true) engine->partition->updateEntity(this); } bool PointsParticleSystem::isFrustumCulling() { return frustumCulling; } void PointsParticleSystem::setFrustumCulling(bool frustumCulling) { // check if enabled and engine attached if (enabled == true && engine != nullptr) { // had frustum culling if (this->frustumCulling == true) { // yep, remove if set to false now if (frustumCulling == false) engine->partition->removeEntity(this); } else { // yep, add if set to true now if (frustumCulling == true) engine->partition->addEntity(this); } } this->frustumCulling = frustumCulling; // delegate change to engine engine->registerEntity(this); } void PointsParticleSystem::setAutoEmit(bool autoEmit) { if (this->isAutoEmit() == autoEmit) return; // delegate to base class PointsParticleSystemInternal::setAutoEmit(autoEmit); // delegate change to engine engine->registerEntity(this); } void PointsParticleSystem::dispose() { PointsParticleSystemInternal::dispose(); } void PointsParticleSystem::setEngine(Engine* engine) { if (this->engine != nullptr) this->engine->deregisterEntity(this); this->engine = engine; if (engine != nullptr) engine->registerEntity(this); PointsParticleSystemInternal::setEngine(engine); } void PointsParticleSystem::setRenderer(RendererBackend* rendererBackend) { PointsParticleSystemInternal::setRenderer(rendererBackend); }
0
0.934578
1
0.934578
game-dev
MEDIA
0.933146
game-dev
0.898541
1
0.898541
526077247/GenshinGamePlay
3,997
Modules/com.tuyoogame.yooasset/Runtime/FileSystem/DefaultWebServerFileSystem/Operation/DWSFSLoadBundleOperation.cs
 namespace YooAsset { internal class DWSFSLoadAssetBundleOperation : FSLoadBundleOperation { private enum ESteps { None, DownloadAssetBundle, Done, } private readonly DefaultWebServerFileSystem _fileSystem; private readonly PackageBundle _bundle; private DownloadAssetBundleOperation _downloadAssetBundleOp; private ESteps _steps = ESteps.None; internal DWSFSLoadAssetBundleOperation(DefaultWebServerFileSystem fileSystem, PackageBundle bundle) { _fileSystem = fileSystem; _bundle = bundle; } internal override void InternalOnStart() { _steps = ESteps.DownloadAssetBundle; } internal override void InternalOnUpdate() { if (_steps == ESteps.None || _steps == ESteps.Done) return; if (_steps == ESteps.DownloadAssetBundle) { if (_downloadAssetBundleOp == null) { DownloadParam downloadParam = new DownloadParam(int.MaxValue, 60); string fileLoadPath = _fileSystem.GetWebFileLoadPath(_bundle); downloadParam.MainURL = DownloadSystemHelper.ConvertToWWWPath(fileLoadPath); downloadParam.FallbackURL = downloadParam.MainURL; if (_bundle.Encrypted) { _downloadAssetBundleOp = new DownloadWebEncryptAssetBundleOperation(true, _fileSystem.DecryptionServices, _bundle, downloadParam); OperationSystem.StartOperation(_fileSystem.PackageName, _downloadAssetBundleOp); } else { _downloadAssetBundleOp = new DownloadWebNormalAssetBundleOperation(_fileSystem.DisableUnityWebCache, _bundle, downloadParam); OperationSystem.StartOperation(_fileSystem.PackageName, _downloadAssetBundleOp); } } DownloadProgress = _downloadAssetBundleOp.DownloadProgress; DownloadedBytes = _downloadAssetBundleOp.DownloadedBytes; Progress = _downloadAssetBundleOp.Progress; if (_downloadAssetBundleOp.IsDone == false) return; if (_downloadAssetBundleOp.Status == EOperationStatus.Succeed) { var assetBundle = _downloadAssetBundleOp.Result; if (assetBundle == null) { _steps = ESteps.Done; Status = EOperationStatus.Failed; Error = $"{nameof(DownloadAssetBundleOperation)} loaded asset bundle is null !"; } else { _steps = ESteps.Done; Result = new AssetBundleResult(_fileSystem, _bundle, assetBundle, null); Status = EOperationStatus.Succeed; } } else { _steps = ESteps.Done; Status = EOperationStatus.Failed; Error = _downloadAssetBundleOp.Error; } } } internal override void InternalWaitForAsyncComplete() { if (_steps != ESteps.Done) { _steps = ESteps.Done; Status = EOperationStatus.Failed; Error = "WebGL platform not support sync load method !"; UnityEngine.Debug.LogError(Error); } } public override void AbortDownloadOperation() { if (_steps == ESteps.DownloadAssetBundle) { if (_downloadAssetBundleOp != null) _downloadAssetBundleOp.SetAbort(); } } } }
0
0.876253
1
0.876253
game-dev
MEDIA
0.469851
game-dev
0.59459
1
0.59459
DirtBagXon/hypseus-singe
25,914
src/game/gpworld.cpp
/* * ____ DAPHNE COPYRIGHT NOTICE ____ * * Copyright (C) 2001 Mark Broadhead * * This file is part of DAPHNE, a laserdisc arcade game emulator * * DAPHNE is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * DAPHNE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ // gpworld.cpp // by Mark Broadhead // // Sega GP World Hardware // // GP World is a rare game that came in a huge cabinet with two monitors, side // by side. // The image from the laserdisc was stretched to an 8x3 aspect and graphics were // overlayed // on top. The hardware is similar to Astron Belt but somewhat more powerful. // // TODO: // // game wont be playable until vldp can do multiple speeds // samples are needed for game generated sounds // game seems to lockup with writes to dac0 and dae0? #include "config.h" #include <string.h> #include "gpworld.h" #include <plog/Log.h> #include "../io/conout.h" #include "../ldp-in/ldv1000.h" #include "../ldp-out/ldp.h" #include "../video/palette.h" #include "../sound/sound.h" #include "../sound/samples.h" #include "../cpu/cpu.h" #include "../cpu/generic_z80.h" gpworld::gpworld() { struct cpu::def cpu; m_shortgamename = "gpworld"; memset(&cpu, 0, sizeof(struct cpu::def)); memset(banks, 0xff, 7); // fill banks with 0xFF's banks[5] = 0x00; banks[6] = 0x00; memset(sprite, 0x00, 0x30000); // making sure sprite[] is zero'd out memset(m_cpumem, 0x00, 0x10000); // making sure m_cpumem[] is zero'd out palette_modified = true; m_disc_fps = 29.97; // m_game_type = GAME_GPWORLD; m_video_overlay_width = GPWORLD_OVERLAY_W; m_video_overlay_height = GPWORLD_OVERLAY_H; m_palette_color_count = GPWORLD_COLOR_COUNT; cpu.type = cpu::type::Z80; cpu.hz = 5000000; // guess based on Astron's clock speed cpu.irq_period[0] = 16.6666; // interrupt from vblank (60hz) cpu.nmi_period = 16.6666; // nmi from LD-V1000 command strobe cpu.initial_pc = 0; cpu.must_copy_context = false; cpu.mem = m_cpumem; cpu::add(&cpu); // add a z80 m_transparent_color = 0; ldp_output_latch = 0xff; nmie = false; m_align = false; m_shifter = true; m_num_sounds = 10; // With the lack of any hardware reference.... m_sound_name[S_GP_ENG1] = "gp_engine1.wav"; m_sound_name[S_GP_ENG2] = "gp_engine2.wav"; m_sound_name[S_GP_COUNT] = "gp_count.wav"; m_sound_name[S_GP_START] = "gp_signal.wav"; m_sound_name[S_GP_TIRE] = "gp_tires.wav"; m_sound_name[S_GP_REV] = "gp_roar.wav"; m_sound_name[S_GP_CRASH] = "gp_crash.wav"; m_sound_name[S_GP_COIN] = "dl_credit.wav"; m_sound_name[S_GP_DINK] = "dl2_bad.wav"; m_sound_name[S_GP_GEAR] = "gr_alarm4.wav"; const static struct rom_def gpworld_roms[] = {// main z80 rom {"gpw_6162a.bin", NULL, &m_cpumem[0x0000], 0x4000, 0}, {"gpw_6163.bin", NULL, &m_cpumem[0x4000], 0x4000, 0}, {"gpw_6164.bin", NULL, &m_cpumem[0x8000], 0x4000, 0}, // character graphics {"gpw_6148.bin", NULL, &character[0x0000], 0x1000, 0}, // sprites {"gpw_6149.bin", NULL, &sprite[0x0000], 0x4000, 0}, {"gpw_6150.bin", NULL, &sprite[0x8000], 0x4000, 0}, {"gpw_6151.bin", NULL, &sprite[0x4000], 0x4000, 0}, {"gpw_6152.bin", NULL, &sprite[0xc000], 0x4000, 0}, {"gpw_6153.bin", NULL, &sprite[0x10000], 0x4000, 0}, {"gpw_6154.bin", NULL, &sprite[0x18000], 0x4000, 0}, {"gpw_6155.bin", NULL, &sprite[0x14000], 0x4000, 0}, {"gpw_6156.bin", NULL, &sprite[0x1c000], 0x4000, 0}, {"gpw_6157.bin", NULL, &sprite[0x20000], 0x4000, 0}, {"gpw_6158.bin", NULL, &sprite[0x28000], 0x4000, 0}, // misc proms (unused) {"gpw_6146.bin", NULL, &miscprom[0x000], 0x20, 0}, {"gpw_6147.bin", NULL, &miscprom[0x020], 0x100, 0}, {"gpw_5501.bin", NULL, &miscprom[0x120], 0x100, 0}, {NULL}}; m_rom_list = gpworld_roms; } // does anything special needed to send an IRQ void gpworld::do_irq(unsigned int which_irq) { if (which_irq == 0) { // Redraws the screen (if needed) on interrupt recalc_palette(); blit(); Z80_ASSERT_IRQ; } } // does anything special needed to send an NMI void gpworld::do_nmi() { // only do an nmi if nmie is enabled if (nmie) { ldv1000::write(ldp_output_latch); ldp_input_latch = ldv1000::read(); Z80_ASSERT_NMI; } } // reads a byte from the cpu's memory Uint8 gpworld::cpu_mem_read(Uint16 addr) { Uint8 result = m_cpumem[addr]; // main rom if (addr <= 0xbfff) { } // sprites else if (addr >= 0xc000 && addr <= 0xc7ff) { } // unknown else if (addr >= 0xc800 && addr <= 0xc9ff) { } // color else if (addr >= 0xca00 && addr <= 0xcfff) { } // tile ram else if (addr >= 0xd000 && addr <= 0xd7ff) { } // ld-v1000 laserdisc player else if (addr == 0xd800) { result = read_ldp(addr); LOGD << fmt("LDP read %x", result); } // unknown else if (addr == 0xd801) { } // steering else if (addr == 0xda00) { result = banks[1]; } // unknown else if (addr == 0xda01) { } else if (addr == 0xda02) { } else if (addr == 0xda03) { } // brake and accelerator else if (addr == 0xda20) { if (m_cpumem[0xda02] & 0x01) { result = banks[5]; } else { result = banks[6]; } } // unknown else if (addr == 0xda40) { } else if (addr == 0xda80) { } else if (addr == 0xdaa0) { } // work ram (all?) else if (addr >= 0xe000) { } else { LOGW << fmt("Unmapped read from %x (PC is %x)", addr, Z80_GET_PC); } return result; } // writes a byte to the cpu's memory void gpworld::cpu_mem_write(Uint16 addr, Uint8 value) { m_cpumem[addr] = value; // main rom if (addr <= 0xbfff) { LOGW << fmt("Attempted write to main ROM! at %x with value %x", addr, value); } // sprite else if (addr >= 0xc000 && addr <= 0xc7ff) { m_video_overlay_needs_update = true; } // unknown else if (addr >= 0xc800 && addr <= 0xc9ff) { } // color (c800-c9ff is tile color and ca00-cbff is sprite color) else if (addr >= 0xc800 && addr <= 0xcfff) { palette_modified = true; } // tile ram else if (addr >= 0xd000 && addr <= 0xd7ff) { m_video_overlay_needs_update = true; } // disc else if (addr == 0xd800) { LOGD << fmt("LDP write %x", value); write_ldp(value, addr); } // unknown else if (addr == 0xda00) { } // sound (uses analog hardware) - unsupported - sound with samples else if (addr == 0xda01) { if (value != 0xff) { static Uint8 lastbeep[0xff] = {0}; // audio streams (primitive control) if (++lastbeep[value] > 6) { switch (value) { case 0xdc: case 0xde: sound::play(S_GP_TIRE); break; case 0xec: case 0xee: samples::flush_queue(); sound::play(S_GP_START); break; case 0xf4: samples::flush_queue(); sound::play(S_GP_COUNT); break; case 0xf5: sound::play(S_GP_REV); break; break; case 0xf9: case 0xfB: sound::play(S_GP_COIN); break; case 0xfe: if (++ign > 0x0a) { sound::play(banks[2] ? S_GP_ENG2 : S_GP_ENG1); ign--; } break; default: LOGD << fmt("%x write %x", addr, value); break; } lastbeep[value] = 0; } } } else if (addr == 0xdac0 || addr == 0xdae0) { switch (value) { case 0x90: ign = 0x00; samples::flush_queue(); sound::play(S_GP_CRASH); break; default: sound::play(S_GP_DINK); LOGD << fmt("%x write %x", addr, value); break; } } // bit 0 selects whether brake or accelerater are read through 0xda20 else if (addr == 0xda02) { } // unknown else if (addr == 0xda03) { } // unknown else if (addr == 0xda20) { } else if (addr == 0xda40) { } else if (addr == 0xda80) { } else if (addr == 0xdaa0) { } // work ram (all of it?) else if (addr >= 0xe000) { } else { m_cpumem[addr] = value; LOGW << fmt("Unmapped write to %x with value %x (PC is %x)", addr, value, Z80_GET_PC); } } Uint8 gpworld::read_ldp(Uint16 addr) { Uint8 result = ldp_input_latch; LOGD << fmt("Read from player %x at pc: %x", result, Z80_GET_PC); return result; } void gpworld::write_ldp(Uint8 value, Uint16 addr) { LOGD << fmt("Write to player %x at pc %x", value, Z80_GET_PC); ldp_output_latch = value; } // reads a byte from the cpu's port Uint8 gpworld::port_read(Uint16 port) { port &= 0xff; switch (port) { // shifter (anything else?) case 0x80: return banks[2]; break; // Input switches... start, test, coins, etc case 0x81: return banks[0]; break; // Dipswitch 1 case 0x82: return banks[3]; break; // Dipswitch 2 case 0x83: return banks[4]; break; default: LOGW << fmt("ERROR: CPU port %x read requested, but this function is " "unimplemented!", port); } return (0); } // writes a byte to the cpu's port void gpworld::port_write(Uint16 port, Uint8 value) { port &= 0xff; switch (port) { // bit 2 - start lamp // bit 6 - nmie case 0x01: if (value & 0x40) nmie = true; else { nmie = false; if (value == 0x00) { ldv1000::write(GPWORLD_RST); lss = GPWORLD_LSS; rss = GPWORLD_RSS; ign = value; align(); } } break; default: LOGW << fmt("ERROR: CPU port %x write requested (value %x) but this " "function is unimplemented!", port, value); break; } } void gpworld::palette_calculate() { // transparent color default to 0, so no change to transparency is needed // color conversion for all 2^12 possible colors for (int i = 0; i < 4096; i++) { Uint8 bit0, bit1, bit2, bit3; // red component bit0 = static_cast<Uint8>((i >> 3) & 0x01); bit1 = static_cast<Uint8>((i >> 2) & 0x01); bit2 = static_cast<Uint8>((i >> 1) & 0x01); bit3 = static_cast<Uint8>((i >> 0) & 0x01); palette_lookup[i].r = static_cast<Uint8>((0x8f * bit0) + (0x43 * bit1) + (0x1f * bit2) + (0x0e * bit3)); // green component bit0 = static_cast<Uint8>((i >> 7) & 0x01); bit1 = static_cast<Uint8>((i >> 6) & 0x01); bit2 = static_cast<Uint8>((i >> 5) & 0x01); bit3 = static_cast<Uint8>((i >> 4) & 0x01); palette_lookup[i].g = static_cast<Uint8>((0x8f * bit0) + (0x43 * bit1) + (0x1f * bit2) + (0x0e * bit3)); // blue component bit0 = static_cast<Uint8>((i >> 11) & 0x01); bit1 = static_cast<Uint8>((i >> 10) & 0x01); bit2 = static_cast<Uint8>((i >> 9) & 0x01); bit3 = static_cast<Uint8>((i >> 8) & 0x01); palette_lookup[i].b = static_cast<Uint8>((0x8f * bit0) + (0x43 * bit1) + (0x1f * bit2) + (0x0e * bit3)); } recalc_palette(); } void gpworld::recalc_palette() { if (palette_modified) { m_video_overlay_needs_update = true; Uint8 used_tile_colors[4096] = {0}; // int used_colors = 0; int i; // load current palette with values from the lookup according to sprite // color ram for (i = 0; i < 256; i++) { int j; j = 0xca00 + (i * 0x02); int color = m_cpumem[j] | ((m_cpumem[j + 1] & 0x0f) << 8); palette::set_color(i, palette_lookup[color]); // the final palette is blank in gpworld so we'll put our tile // palette here // we need to check if this palette is ever written to if (i >= 240 && color) { printline("Color written to palette 15! This will screw up the " "tile palette!"); } } // start of the blank palette 15 int k = 240; // load current palette with values from the lookup according to color // ram for (i = 0; i < 256; i++) { int j; j = 0xc800 + (i * 0x02); int color = m_cpumem[j] | ((m_cpumem[j + 1] & 0x0f) << 8); if (color) { // we already have this color mapped if (used_tile_colors[color]) { // point to the already mapped color tile_color_pointer[i] = used_tile_colors[color]; } // a new color else { palette::set_color(k, palette_lookup[color]); used_tile_colors[color] = k; tile_color_pointer[i] = k; k++; if (k > 255) { printline("Too many tile colors! FIX ME!"); } } } // if the color is black else { tile_color_pointer[i] = 0; } } palette::finalize(); } palette_modified = false; } void gpworld::draw_char(char l, int x_offset, int y_offset) { int i = -1; Uint8 c = 0x01; switch (l) { case 0x44: i = 0; c = 0xf3; break; case 0x48: i = 1; break; case 0x49: i = 2; break; case 0x4c: i = 3; break; case 0x4f: i = 4; break; case 0x55: i = 5; c = 0xeb; break; default: return; } const Uint8* char_bitmap = gear[i]; for (int y = 0; y < 8; y++) { Uint8 pixel_row = char_bitmap[y]; for (int x = 0; x < 8; x++) { Uint8 pixel = (pixel_row & (0x80 >> x)) >> (7 - x); if (pixel) { int pixel_index = (y_offset * 8 + y) * GPWORLD_OVERLAY_W + (x_offset * 8 + x); *((Uint8 *)m_video_overlay[m_active_video_overlay]->pixels + pixel_index) = c; } } } } void gpworld::draw_shift(const char* w) { const int x_offset = 0x01, y_offset = 0x1c; for (int i = 0; w[i] != '\0'; i++) { draw_char(w[i], x_offset + i, y_offset); } } // updates gpworld's video void gpworld::repaint() { // This should be much faster SDL_FillRect(m_video_overlay[m_active_video_overlay], NULL, m_transparent_color); // The sprites are bottom priority so we draw them first // START modified Mame code // check if sprites need to be drawn int spr_number, sprite_bottom_y, sprite_top_y; Uint8 *sprite_base; for (spr_number = 0; spr_number < 64; spr_number++) { sprite_base = m_cpumem + GPWORLD_SPRITE_ADDRESS + 0x8 * spr_number; sprite_top_y = sprite_base[SPR_Y_TOP]; sprite_bottom_y = sprite_base[SPR_Y_BOTTOM]; if (sprite_bottom_y && (sprite_bottom_y - sprite_top_y > 0)) { draw_sprite(spr_number); } } // END modified Mame code Uint8 pixel[8]; Uint8 p = 5; // loop through video memory and draw characters for (int charx = 19; charx < 64; charx++) { for (int chary = 0; chary < 32; chary++) { for (int y = 0; y < 8; y++) { int current_character = chary * 64 + charx + GPWORLD_VID_ADDRESS; pixel[0] = static_cast<Uint8>( ((character[m_cpumem[current_character] * 8 + y] & 0x80) >> 7) | ((character[m_cpumem[current_character] * 8 + y + 0x800] & 0x80) >> 6)); pixel[1] = static_cast<Uint8>( ((character[m_cpumem[current_character] * 8 + y] & 0x40) >> 6) | ((character[m_cpumem[current_character] * 8 + y + 0x800] & 0x40) >> 5)); pixel[2] = static_cast<Uint8>( ((character[m_cpumem[current_character] * 8 + y] & 0x20) >> 5) | ((character[m_cpumem[current_character] * 8 + y + 0x800] & 0x20) >> 4)); pixel[3] = static_cast<Uint8>( ((character[m_cpumem[current_character] * 8 + y] & 0x10) >> 4) | ((character[m_cpumem[current_character] * 8 + y + 0x800] & 0x10) >> 3)); pixel[4] = static_cast<Uint8>( ((character[m_cpumem[current_character] * 8 + y] & 0x08) >> 3) | ((character[m_cpumem[current_character] * 8 + y + 0x800] & 0x08) >> 2)); pixel[5] = static_cast<Uint8>( ((character[m_cpumem[current_character] * 8 + y] & 0x04) >> 2) | ((character[m_cpumem[current_character] * 8 + y + 0x800] & 0x04) >> 1)); pixel[6] = static_cast<Uint8>( ((character[m_cpumem[current_character] * 8 + y] & 0x02) >> 1) | ((character[m_cpumem[current_character] * 8 + y + 0x800] & 0x02) >> 0)); pixel[7] = static_cast<Uint8>( ((character[m_cpumem[current_character] * 8 + y] & 0x01) >> 0) | ((character[m_cpumem[current_character] * 8 + y + 0x800] & 0x01) << 1)); for (int x = 0; x < 8; x++) { if (pixel[x]) { *((Uint8 *)m_video_overlay[m_active_video_overlay]->pixels + ((chary * 8 + y + p) * GPWORLD_OVERLAY_W) + ((charx - 19) * 7 + x + p)) = tile_color_pointer[(pixel[x]) | ((m_cpumem[current_character]) & 0xfc)]; } } } } } // draw state of the shifter if (m_shifter) draw_shift(banks[2] ? "DLO" : "UHI"); } // this gets called when the user presses a key or moves the joystick void gpworld::input_enable(Uint8 move, Sint8 mouseID) { switch (move) { case SWITCH_UP: break; case SWITCH_LEFT: banks[1] &= ~lss; if (lss < 0x80) lss = lss << 1; break; case SWITCH_RIGHT: banks[1] &= ~rss; if (rss < 0x08) rss = rss << 1; break; case SWITCH_DOWN: break; case SWITCH_START1: // '1' on keyboard banks[0] &= ~0x10; break; case SWITCH_BUTTON1: // space on keyboard banks[2] = ~banks[2]; m_video_overlay_needs_update = true; break; case SWITCH_BUTTON2: // left shift banks[5] = 0xff; break; case SWITCH_BUTTON3: // left alt banks[6] = 0xff; break; case SWITCH_COIN1: banks[0] &= ~0x01; break; case SWITCH_COIN2: banks[0] &= ~0x02; break; case SWITCH_SERVICE: banks[0] &= ~0x08; break; case SWITCH_TEST: banks[0] &= ~0x04; break; } } // this gets called when the user releases a key or moves the joystick back to // center position void gpworld::input_disable(Uint8 move, Sint8 mouseID) { switch (move) { case SWITCH_UP: break; case SWITCH_LEFT: case SWITCH_RIGHT: banks[1] = 0xff; lss = GPWORLD_LSS; rss = GPWORLD_RSS; if (m_align) align(); break; case SWITCH_DOWN: break; case SWITCH_START1: // '1' on keyboard banks[0] |= 0x10; break; case SWITCH_BUTTON1: // space on keyboard sound::play(S_GP_GEAR); break; case SWITCH_BUTTON2: // left shift banks[5] = 0x00; break; case SWITCH_BUTTON3: // left alt banks[6] = 0x00; break; case SWITCH_COIN1: banks[0] |= 0x01; break; case SWITCH_COIN2: banks[0] |= 0x02; break; case SWITCH_SERVICE: banks[0] |= 0x08; break; case SWITCH_TEST: banks[0] |= 0x04; break; } } // used to set dip switch values bool gpworld::set_bank(Uint8 which_bank, Uint8 value) { bool result = true; switch (which_bank) { case 0: // bank A banks[3] = (Uint8)(value ^ 0xff); // dip switches are active low break; case 1: // bank B banks[4] = (Uint8)(value ^ 0xff); // switches are active low break; default: printline("ERROR: Bank specified is out of range!"); result = false; break; } return result; } // START modified Mame code void gpworld::draw_sprite(int spr_number) { int p = 12; int sx, sy, row, height, src, sprite_color, sprite_bank; Uint8 *sprite_base; int skip; /* bytes to skip before drawing each row (can be negative) */ sprite_base = m_cpumem + GPWORLD_SPRITE_ADDRESS + 0x8 * spr_number; src = sprite_base[SPR_GFXOFS_LO] + (sprite_base[SPR_GFXOFS_HI] << 8); skip = sprite_base[SPR_SKIP_LO] + (sprite_base[SPR_SKIP_HI] << 8); height = sprite_base[SPR_Y_BOTTOM] - sprite_base[SPR_Y_TOP]; sy = sprite_base[SPR_Y_TOP] + 1; sx = sprite_base[SPR_X_LO] + ((sprite_base[SPR_X_HI] & 0x01) << 8) - 19 * 8; sprite_color = (sprite_base[SPR_X_HI] >> 4) & 0x0f; sprite_bank = (sprite_base[SPR_X_HI] >> 1) & 0x07; if (spr_number == 0x1) { sx -= 0x2; p -= 0x4; if (sx < 0x4) sx -= 0x4; if (sy < 0x4) p -= 0x7; } LOGD << fmt( "Draw Sprite #%x with src %x, skip %x, height %x, y %x, x %x", spr_number, src, skip, height, sy, sx); for (row = p; row < height + p; row++) { int x, y; int src2; src = src2 = src + skip; x = sx - 12; y = sy + row; while (1) { int spr_index = (src2 & 0x7fff) | (sprite_bank << 16); if (spr_index > max_sprites) break; int data_lo = sprite[spr_index]; int data_high = sprite[spr_index | 0x8000]; Uint8 pixel1 = data_high >> 0x04; Uint8 pixel2 = data_high & 0x0f; Uint8 pixel3 = data_lo >> 0x04; Uint8 pixel4 = data_lo & 0x0f; // draw these guys backwards if (src & 0x8000) { Uint8 temp_pixel; temp_pixel = pixel1; pixel1 = pixel4; pixel4 = temp_pixel; temp_pixel = pixel2; pixel2 = pixel3; pixel3 = temp_pixel; src2--; } else { src2++; } // TODO: also check to make sure they don't get drawn off the right // of the screen if (!(x & 0xf0000000)) { // draw the pixel - don't draw if its black as to not cover up // any tiles if (pixel1 && (pixel1 != 0xf)) { *((Uint8 *)m_video_overlay[m_active_video_overlay]->pixels + (y * GPWORLD_OVERLAY_W) + x + 0) = pixel1 + (0x10 * sprite_color); } if (pixel2 && (pixel2 != 0xf)) { *((Uint8 *)m_video_overlay[m_active_video_overlay]->pixels + (y * GPWORLD_OVERLAY_W) + x + 1) = pixel2 + (0x10 * sprite_color); } if (pixel3 && (pixel3 != 0xf)) { *((Uint8 *)m_video_overlay[m_active_video_overlay]->pixels + (y * GPWORLD_OVERLAY_W) + x + 2) = pixel3 + (0x10 * sprite_color); } if (pixel4 && (pixel4 != 0xf)) { *((Uint8 *)m_video_overlay[m_active_video_overlay]->pixels + (y * GPWORLD_OVERLAY_W) + x + 3) = pixel4 + (0x10 * sprite_color); } } x += 4; // stop drawing when the sprite data is 0xf if (((data_lo & 0x0f) == 0x0f) && (!(src & 0x8000))) { break; } else if ((src & 0x8000) && ((data_high & 0xf0) == 0xf0)) { break; } } } } // END modified Mame code void gpworld::set_preset(int preset) { if (preset == 1) m_align = true; if (preset == 2) m_shifter = false; } void gpworld::align() { m_cpumem[0xe02e] = 0x00; }
0
0.859272
1
0.859272
game-dev
MEDIA
0.40295
game-dev,audio-video-media
0.98505
1
0.98505
DanieltheDeveloper/azerothcore-transmog-3.3.5a
24,779
patches/lose files/Interface/addons/Transmogrification/Libs/AceAddon-3.0/AceAddon-3.0.lua
--- **AceAddon-3.0** provides a template for creating addon objects. -- It'll provide you with a set of callback functions that allow you to simplify the loading -- process of your addon.\\ -- Callbacks provided are:\\ -- * **OnInitialize**, which is called directly after the addon is fully loaded. -- * **OnEnable** which gets called during the PLAYER_LOGIN event, when most of the data provided by the game is already present. -- * **OnDisable**, which is only called when your addon is manually being disabled. -- @usage -- -- A small (but complete) addon, that doesn't do anything, -- -- but shows usage of the callbacks. -- local MyAddon = LibStub("AceAddon-3.0"):NewAddon("MyAddon") -- -- function MyAddon:OnInitialize() -- -- do init tasks here, like loading the Saved Variables, -- -- or setting up slash commands. -- end -- -- function MyAddon:OnEnable() -- -- Do more initialization here, that really enables the use of your addon. -- -- Register Events, Hook functions, Create Frames, Get information from -- -- the game that wasn't available in OnInitialize -- end -- -- function MyAddon:OnDisable() -- -- Unhook, Unregister Events, Hide frames that you created. -- -- You would probably only use an OnDisable if you want to -- -- build a "standby" mode, or be able to toggle modules on/off. -- end -- @class file -- @name AceAddon-3.0.lua -- @release $Id: AceAddon-3.0.lua 895 2009-12-06 16:28:55Z nevcairiel $ local MAJOR, MINOR = "AceAddon-3.0", 5 local AceAddon, oldminor = LibStub:NewLibrary(MAJOR, MINOR) if not AceAddon then return end -- No Upgrade needed. AceAddon.frame = AceAddon.frame or CreateFrame("Frame", "AceAddon30Frame") -- Our very own frame AceAddon.addons = AceAddon.addons or {} -- addons in general AceAddon.statuses = AceAddon.statuses or {} -- statuses of addon. AceAddon.initializequeue = AceAddon.initializequeue or {} -- addons that are new and not initialized AceAddon.enablequeue = AceAddon.enablequeue or {} -- addons that are initialized and waiting to be enabled AceAddon.embeds = AceAddon.embeds or setmetatable({}, {__index = function(tbl, key) tbl[key] = {} return tbl[key] end }) -- contains a list of libraries embedded in an addon -- Lua APIs local tinsert, tconcat, tremove = table.insert, table.concat, table.remove local fmt, tostring = string.format, tostring local select, pairs, next, type, unpack = select, pairs, next, type, unpack local loadstring, assert, error = loadstring, assert, error local setmetatable, getmetatable, rawset, rawget = setmetatable, getmetatable, rawset, rawget -- Global vars/functions that we don't upvalue since they might get hooked, or upgraded -- List them here for Mikk's FindGlobals script -- GLOBALS: LibStub, IsLoggedIn, geterrorhandler --[[ xpcall safecall implementation ]] local xpcall = xpcall local function errorhandler(err) return geterrorhandler()(err) end local function CreateDispatcher(argCount) local code = [[ local xpcall, eh = ... local method, ARGS local function call() return method(ARGS) end local function dispatch(func, ...) method = func if not method then return end ARGS = ... return xpcall(call, eh) end return dispatch ]] local ARGS = {} for i = 1, argCount do ARGS[i] = "arg"..i end code = code:gsub("ARGS", tconcat(ARGS, ", ")) return assert(loadstring(code, "safecall Dispatcher["..argCount.."]"))(xpcall, errorhandler) end local Dispatchers = setmetatable({}, {__index=function(self, argCount) local dispatcher = CreateDispatcher(argCount) rawset(self, argCount, dispatcher) return dispatcher end}) Dispatchers[0] = function(func) return xpcall(func, errorhandler) end local function safecall(func, ...) -- we check to see if the func is passed is actually a function here and don't error when it isn't -- this safecall is used for optional functions like OnInitialize OnEnable etc. When they are not -- present execution should continue without hinderance if type(func) == "function" then return Dispatchers[select('#', ...)](func, ...) end end -- local functions that will be implemented further down local Enable, Disable, EnableModule, DisableModule, Embed, NewModule, GetModule, GetName, SetDefaultModuleState, SetDefaultModuleLibraries, SetEnabledState, SetDefaultModulePrototype -- used in the addon metatable local function addontostring( self ) return self.name end --- Create a new AceAddon-3.0 addon. -- Any libraries you specified will be embeded, and the addon will be scheduled for -- its OnInitialize and OnEnable callbacks. -- The final addon object, with all libraries embeded, will be returned. -- @paramsig [object ,]name[, lib, ...] -- @param object Table to use as a base for the addon (optional) -- @param name Name of the addon object to create -- @param lib List of libraries to embed into the addon -- @usage -- -- Create a simple addon object -- MyAddon = LibStub("AceAddon-3.0"):NewAddon("MyAddon", "AceEvent-3.0") -- -- -- Create a Addon object based on the table of a frame -- local MyFrame = CreateFrame("Frame") -- MyAddon = LibStub("AceAddon-3.0"):NewAddon(MyFrame, "MyAddon", "AceEvent-3.0") function AceAddon:NewAddon(objectorname, ...) local object,name local i=1 if type(objectorname)=="table" then object=objectorname name=... i=2 else name=objectorname end if type(name)~="string" then error(("Usage: NewAddon([object,] name, [lib, lib, lib, ...]): 'name' - string expected got '%s'."):format(type(name)), 2) end if self.addons[name] then error(("Usage: NewAddon([object,] name, [lib, lib, lib, ...]): 'name' - Addon '%s' already exists."):format(name), 2) end object = object or {} object.name = name local addonmeta = {} local oldmeta = getmetatable(object) if oldmeta then for k, v in pairs(oldmeta) do addonmeta[k] = v end end addonmeta.__tostring = addontostring setmetatable( object, addonmeta ) self.addons[name] = object object.modules = {} object.defaultModuleLibraries = {} Embed( object ) -- embed NewModule, GetModule methods self:EmbedLibraries(object, select(i,...)) -- add to queue of addons to be initialized upon ADDON_LOADED tinsert(self.initializequeue, object) return object end --- Get the addon object by its name from the internal AceAddon registry. -- Throws an error if the addon object cannot be found (except if silent is set). -- @param name unique name of the addon object -- @param silent if true, the addon is optional, silently return nil if its not found -- @usage -- -- Get the Addon -- MyAddon = LibStub("AceAddon-3.0"):GetAddon("MyAddon") function AceAddon:GetAddon(name, silent) if not silent and not self.addons[name] then error(("Usage: GetAddon(name): 'name' - Cannot find an AceAddon '%s'."):format(tostring(name)), 2) end return self.addons[name] end -- - Embed a list of libraries into the specified addon. -- This function will try to embed all of the listed libraries into the addon -- and error if a single one fails. -- -- **Note:** This function is for internal use by :NewAddon/:NewModule -- @paramsig addon, [lib, ...] -- @param addon addon object to embed the libs in -- @param lib List of libraries to embed into the addon function AceAddon:EmbedLibraries(addon, ...) for i=1,select("#", ... ) do local libname = select(i, ...) self:EmbedLibrary(addon, libname, false, 4) end end -- - Embed a library into the addon object. -- This function will check if the specified library is registered with LibStub -- and if it has a :Embed function to call. It'll error if any of those conditions -- fails. -- -- **Note:** This function is for internal use by :EmbedLibraries -- @paramsig addon, libname[, silent[, offset]] -- @param addon addon object to embed the library in -- @param libname name of the library to embed -- @param silent marks an embed to fail silently if the library doesn't exist (optional) -- @param offset will push the error messages back to said offset, defaults to 2 (optional) function AceAddon:EmbedLibrary(addon, libname, silent, offset) local lib = LibStub:GetLibrary(libname, true) if not lib and not silent then error(("Usage: EmbedLibrary(addon, libname, silent, offset): 'libname' - Cannot find a library instance of %q."):format(tostring(libname)), offset or 2) elseif lib and type(lib.Embed) == "function" then lib:Embed(addon) tinsert(self.embeds[addon], libname) return true elseif lib then error(("Usage: EmbedLibrary(addon, libname, silent, offset): 'libname' - Library '%s' is not Embed capable"):format(libname), offset or 2) end end --- Return the specified module from an addon object. -- Throws an error if the addon object cannot be found (except if silent is set) -- @name //addon//:GetModule -- @paramsig name[, silent] -- @param name unique name of the module -- @param silent if true, the module is optional, silently return nil if its not found (optional) -- @usage -- -- Get the Addon -- MyAddon = LibStub("AceAddon-3.0"):GetAddon("MyAddon") -- -- Get the Module -- MyModule = MyAddon:GetModule("MyModule") function GetModule(self, name, silent) if not self.modules[name] and not silent then error(("Usage: GetModule(name, silent): 'name' - Cannot find module '%s'."):format(tostring(name)), 2) end return self.modules[name] end local function IsModuleTrue(self) return true end --- Create a new module for the addon. -- The new module can have its own embeded libraries and/or use a module prototype to be mixed into the module.\\ -- A module has the same functionality as a real addon, it can have modules of its own, and has the same API as -- an addon object. -- @name //addon//:NewModule -- @paramsig name[, prototype|lib[, lib, ...]] -- @param name unique name of the module -- @param prototype object to derive this module from, methods and values from this table will be mixed into the module (optional) -- @param lib List of libraries to embed into the addon -- @usage -- -- Create a module with some embeded libraries -- MyModule = MyAddon:NewModule("MyModule", "AceEvent-3.0", "AceHook-3.0") -- -- -- Create a module with a prototype -- local prototype = { OnEnable = function(self) print("OnEnable called!") end } -- MyModule = MyAddon:NewModule("MyModule", prototype, "AceEvent-3.0", "AceHook-3.0") function NewModule(self, name, prototype, ...) if type(name) ~= "string" then error(("Usage: NewModule(name, [prototype, [lib, lib, lib, ...]): 'name' - string expected got '%s'."):format(type(name)), 2) end if type(prototype) ~= "string" and type(prototype) ~= "table" and type(prototype) ~= "nil" then error(("Usage: NewModule(name, [prototype, [lib, lib, lib, ...]): 'prototype' - table (prototype), string (lib) or nil expected got '%s'."):format(type(prototype)), 2) end if self.modules[name] then error(("Usage: NewModule(name, [prototype, [lib, lib, lib, ...]): 'name' - Module '%s' already exists."):format(name), 2) end -- modules are basically addons. We treat them as such. They will be added to the initializequeue properly as well. -- NewModule can only be called after the parent addon is present thus the modules will be initialized after their parent is. local module = AceAddon:NewAddon(fmt("%s_%s", self.name or tostring(self), name)) module.IsModule = IsModuleTrue module:SetEnabledState(self.defaultModuleState) module.moduleName = name if type(prototype) == "string" then AceAddon:EmbedLibraries(module, prototype, ...) else AceAddon:EmbedLibraries(module, ...) end AceAddon:EmbedLibraries(module, unpack(self.defaultModuleLibraries)) if not prototype or type(prototype) == "string" then prototype = self.defaultModulePrototype or nil end if type(prototype) == "table" then local mt = getmetatable(module) mt.__index = prototype setmetatable(module, mt) -- More of a Base class type feel. end safecall(self.OnModuleCreated, self, module) -- Was in Ace2 and I think it could be a cool thing to have handy. self.modules[name] = module return module end --- Returns the real name of the addon or module, without any prefix. -- @name //addon//:GetName -- @paramsig -- @usage -- print(MyAddon:GetName()) -- -- prints "MyAddon" function GetName(self) return self.moduleName or self.name end --- Enables the Addon, if possible, return true or false depending on success. -- This internally calls AceAddon:EnableAddon(), thus dispatching a OnEnable callback -- and enabling all modules of the addon (unless explicitly disabled).\\ -- :Enable() also sets the internal `enableState` variable to true -- @name //addon//:Enable -- @paramsig -- @usage -- -- Enable MyModule -- MyAddon = LibStub("AceAddon-3.0"):GetAddon("MyAddon") -- MyModule = MyAddon:GetModule("MyModule") -- MyModule:Enable() function Enable(self) self:SetEnabledState(true) return AceAddon:EnableAddon(self) end --- Disables the Addon, if possible, return true or false depending on success. -- This internally calls AceAddon:DisableAddon(), thus dispatching a OnDisable callback -- and disabling all modules of the addon.\\ -- :Disable() also sets the internal `enableState` variable to false -- @name //addon//:Disable -- @paramsig -- @usage -- -- Disable MyAddon -- MyAddon = LibStub("AceAddon-3.0"):GetAddon("MyAddon") -- MyAddon:Disable() function Disable(self) self:SetEnabledState(false) return AceAddon:DisableAddon(self) end --- Enables the Module, if possible, return true or false depending on success. -- Short-hand function that retrieves the module via `:GetModule` and calls `:Enable` on the module object. -- @name //addon//:EnableModule -- @paramsig name -- @usage -- -- Enable MyModule using :GetModule -- MyAddon = LibStub("AceAddon-3.0"):GetAddon("MyAddon") -- MyModule = MyAddon:GetModule("MyModule") -- MyModule:Enable() -- -- -- Enable MyModule using the short-hand -- MyAddon = LibStub("AceAddon-3.0"):GetAddon("MyAddon") -- MyAddon:EnableModule("MyModule") function EnableModule(self, name) local module = self:GetModule( name ) return module:Enable() end --- Disables the Module, if possible, return true or false depending on success. -- Short-hand function that retrieves the module via `:GetModule` and calls `:Disable` on the module object. -- @name //addon//:DisableModule -- @paramsig name -- @usage -- -- Disable MyModule using :GetModule -- MyAddon = LibStub("AceAddon-3.0"):GetAddon("MyAddon") -- MyModule = MyAddon:GetModule("MyModule") -- MyModule:Disable() -- -- -- Disable MyModule using the short-hand -- MyAddon = LibStub("AceAddon-3.0"):GetAddon("MyAddon") -- MyAddon:DisableModule("MyModule") function DisableModule(self, name) local module = self:GetModule( name ) return module:Disable() end --- Set the default libraries to be mixed into all modules created by this object. -- Note that you can only change the default module libraries before any module is created. -- @name //addon//:SetDefaultModuleLibraries -- @paramsig lib[, lib, ...] -- @param lib List of libraries to embed into the addon -- @usage -- -- Create the addon object -- MyAddon = LibStub("AceAddon-3.0"):NewAddon("MyAddon") -- -- Configure default libraries for modules (all modules need AceEvent-3.0) -- MyAddon:SetDefaultModuleLibraries("AceEvent-3.0") -- -- Create a module -- MyModule = MyAddon:NewModule("MyModule") function SetDefaultModuleLibraries(self, ...) if next(self.modules) then error("Usage: SetDefaultModuleLibraries(...): cannot change the module defaults after a module has been registered.", 2) end self.defaultModuleLibraries = {...} end --- Set the default state in which new modules are being created. -- Note that you can only change the default state before any module is created. -- @name //addon//:SetDefaultModuleState -- @paramsig state -- @param state Default state for new modules, true for enabled, false for disabled -- @usage -- -- Create the addon object -- MyAddon = LibStub("AceAddon-3.0"):NewAddon("MyAddon") -- -- Set the default state to "disabled" -- MyAddon:SetDefaultModuleState(false) -- -- Create a module and explicilty enable it -- MyModule = MyAddon:NewModule("MyModule") -- MyModule:Enable() function SetDefaultModuleState(self, state) if next(self.modules) then error("Usage: SetDefaultModuleState(state): cannot change the module defaults after a module has been registered.", 2) end self.defaultModuleState = state end --- Set the default prototype to use for new modules on creation. -- Note that you can only change the default prototype before any module is created. -- @name //addon//:SetDefaultModulePrototype -- @paramsig prototype -- @param prototype Default prototype for the new modules (table) -- @usage -- -- Define a prototype -- local prototype = { OnEnable = function(self) print("OnEnable called!") end } -- -- Set the default prototype -- MyAddon:SetDefaultModulePrototype(prototype) -- -- Create a module and explicitly Enable it -- MyModule = MyAddon:NewModule("MyModule") -- MyModule:Enable() -- -- should print "OnEnable called!" now -- @see NewModule function SetDefaultModulePrototype(self, prototype) if next(self.modules) then error("Usage: SetDefaultModulePrototype(prototype): cannot change the module defaults after a module has been registered.", 2) end if type(prototype) ~= "table" then error(("Usage: SetDefaultModulePrototype(prototype): 'prototype' - table expected got '%s'."):format(type(prototype)), 2) end self.defaultModulePrototype = prototype end --- Set the state of an addon or module -- This should only be called before any enabling actually happend, e.g. in/before OnInitialize. -- @name //addon//:SetEnabledState -- @paramsig state -- @param state the state of an addon or module (enabled=true, disabled=false) function SetEnabledState(self, state) self.enabledState = state end --- Return an iterator of all modules associated to the addon. -- @name //addon//:IterateModules -- @paramsig -- @usage -- -- Enable all modules -- for name, module in MyAddon:IterateModules() do -- module:Enable() -- end local function IterateModules(self) return pairs(self.modules) end -- Returns an iterator of all embeds in the addon -- @name //addon//:IterateEmbeds -- @paramsig local function IterateEmbeds(self) return pairs(AceAddon.embeds[self]) end --- Query the enabledState of an addon. -- @name //addon//:IsEnabled -- @paramsig -- @usage -- if MyAddon:IsEnabled() then -- MyAddon:Disable() -- end local function IsEnabled(self) return self.enabledState end local mixins = { NewModule = NewModule, GetModule = GetModule, Enable = Enable, Disable = Disable, EnableModule = EnableModule, DisableModule = DisableModule, IsEnabled = IsEnabled, SetDefaultModuleLibraries = SetDefaultModuleLibraries, SetDefaultModuleState = SetDefaultModuleState, SetDefaultModulePrototype = SetDefaultModulePrototype, SetEnabledState = SetEnabledState, IterateModules = IterateModules, IterateEmbeds = IterateEmbeds, GetName = GetName, } local function IsModule(self) return false end local pmixins = { defaultModuleState = true, enabledState = true, IsModule = IsModule, } -- Embed( target ) -- target (object) - target object to embed aceaddon in -- -- this is a local function specifically since it's meant to be only called internally function Embed(target) for k, v in pairs(mixins) do target[k] = v end for k, v in pairs(pmixins) do target[k] = target[k] or v end end -- - Initialize the addon after creation. -- This function is only used internally during the ADDON_LOADED event -- It will call the **OnInitialize** function on the addon object (if present), -- and the **OnEmbedInitialize** function on all embeded libraries. -- -- **Note:** Do not call this function manually, unless you're absolutely sure that you know what you are doing. -- @param addon addon object to intialize function AceAddon:InitializeAddon(addon) safecall(addon.OnInitialize, addon) local embeds = self.embeds[addon] for i = 1, #embeds do local lib = LibStub:GetLibrary(embeds[i], true) if lib then safecall(lib.OnEmbedInitialize, lib, addon) end end -- we don't call InitializeAddon on modules specifically, this is handled -- from the event handler and only done _once_ end -- - Enable the addon after creation. -- Note: This function is only used internally during the PLAYER_LOGIN event, or during ADDON_LOADED, -- if IsLoggedIn() already returns true at that point, e.g. for LoD Addons. -- It will call the **OnEnable** function on the addon object (if present), -- and the **OnEmbedEnable** function on all embeded libraries.\\ -- This function does not toggle the enable state of the addon itself, and will return early if the addon is disabled. -- -- **Note:** Do not call this function manually, unless you're absolutely sure that you know what you are doing. -- Use :Enable on the addon itself instead. -- @param addon addon object to enable function AceAddon:EnableAddon(addon) if type(addon) == "string" then addon = AceAddon:GetAddon(addon) end if self.statuses[addon.name] or not addon.enabledState then return false end -- set the statuses first, before calling the OnEnable. this allows for Disabling of the addon in OnEnable. self.statuses[addon.name] = true safecall(addon.OnEnable, addon) -- make sure we're still enabled before continueing if self.statuses[addon.name] then local embeds = self.embeds[addon] for i = 1, #embeds do local lib = LibStub:GetLibrary(embeds[i], true) if lib then safecall(lib.OnEmbedEnable, lib, addon) end end -- enable possible modules. for name, module in pairs(addon.modules) do self:EnableAddon(module) end end return self.statuses[addon.name] -- return true if we're disabled end -- - Disable the addon -- Note: This function is only used internally. -- It will call the **OnDisable** function on the addon object (if present), -- and the **OnEmbedDisable** function on all embeded libraries.\\ -- This function does not toggle the enable state of the addon itself, and will return early if the addon is still enabled. -- -- **Note:** Do not call this function manually, unless you're absolutely sure that you know what you are doing. -- Use :Disable on the addon itself instead. -- @param addon addon object to enable function AceAddon:DisableAddon(addon) if type(addon) == "string" then addon = AceAddon:GetAddon(addon) end if not self.statuses[addon.name] then return false end -- set statuses first before calling OnDisable, this allows for aborting the disable in OnDisable. self.statuses[addon.name] = false safecall( addon.OnDisable, addon ) -- make sure we're still disabling... if not self.statuses[addon.name] then local embeds = self.embeds[addon] for i = 1, #embeds do local lib = LibStub:GetLibrary(embeds[i], true) if lib then safecall(lib.OnEmbedDisable, lib, addon) end end -- disable possible modules. for name, module in pairs(addon.modules) do self:DisableAddon(module) end end return not self.statuses[addon.name] -- return true if we're disabled end --- Get an iterator over all registered addons. -- @usage -- -- Print a list of all installed AceAddon's -- for name, addon in AceAddon:IterateAddons() do -- print("Addon: " .. name) -- end function AceAddon:IterateAddons() return pairs(self.addons) end --- Get an iterator over the internal status registry. -- @usage -- -- Print a list of all enabled addons -- for name, status in AceAddon:IterateAddonStatus() do -- if status then -- print("EnabledAddon: " .. name) -- end -- end function AceAddon:IterateAddonStatus() return pairs(self.statuses) end -- Following Iterators are deprecated, and their addon specific versions should be used -- e.g. addon:IterateEmbeds() instead of :IterateEmbedsOnAddon(addon) function AceAddon:IterateEmbedsOnAddon(addon) return pairs(self.embeds[addon]) end function AceAddon:IterateModulesOfAddon(addon) return pairs(addon.modules) end -- Event Handling local function onEvent(this, event, arg1) if event == "ADDON_LOADED" or event == "PLAYER_LOGIN" then -- if a addon loads another addon, recursion could happen here, so we need to validate the table on every iteration while(#AceAddon.initializequeue > 0) do local addon = tremove(AceAddon.initializequeue, 1) -- this might be an issue with recursion - TODO: validate if event == "ADDON_LOADED" then addon.baseName = arg1 end AceAddon:InitializeAddon(addon) tinsert(AceAddon.enablequeue, addon) end if IsLoggedIn() then while(#AceAddon.enablequeue > 0) do local addon = tremove(AceAddon.enablequeue, 1) AceAddon:EnableAddon(addon) end end end end AceAddon.frame:RegisterEvent("ADDON_LOADED") AceAddon.frame:RegisterEvent("PLAYER_LOGIN") AceAddon.frame:SetScript("OnEvent", onEvent) -- upgrade embeded for name, addon in pairs(AceAddon.addons) do Embed(addon) end
0
0.911399
1
0.911399
game-dev
MEDIA
0.66696
game-dev
0.860197
1
0.860197
jaspervdj/JVGS
2,098
src/game/CollisionResponsePositioner.h
#ifndef JVGS_GAME_COLLISIONRESPONSEPOSITIONER_H #define JVGS_GAME_COLLISIONRESPONSEPOSITIONER_H #include "../sketch/Sketch.h" #include "../sketch/Group.h" #include "../sketch/Path.h" #include "../math/LineSegment.h" #include "../math/BoundedObject.h" #include "../math/Vector2D.h" #include "../math/MathManager.h" #include "../math/CollisionDetector.h" #include "Positioner.h" #include <vector> class TiXmlElement; namespace jvgs { namespace game { class Entity; class CollisionResponsePositioner: public Positioner { private: # ifndef SWIG const static float VERY_CLOSE; const static int MAX_STEPS; const static float SLIP_LIMIT; # else static float VERY_CLOSE; static int MAX_STEPS; static float SLIP_LIMIT; # endif /** MathManager to perform calculations. */ math::MathManager *mathManager; /** Max distance from collision if you want to jump. */ float jumpDistanceLimit; protected: /* Override */ void loadData(TiXmlElement *element); public: /** Constructor. * @param entity Entity to respond to collisions. */ CollisionResponsePositioner(Entity *entity); /** Constructor. * @param entity Entity to respond to collisions. * @param element TiXmlElement containing the data. */ CollisionResponsePositioner(Entity *entity, TiXmlElement *element); /** Destructor. */ virtual ~CollisionResponsePositioner(); /* Override */ virtual void affect(float ms); /* Override */ virtual bool canJump(); }; } } #endif
0
0.768182
1
0.768182
game-dev
MEDIA
0.9794
game-dev
0.871671
1
0.871671
modernuo/ModernUO
19,178
Projects/UOContent/Skills/AnimalTaming.cs
using System; using System.Collections.Generic; using Server.Engines.Virtues; using Server.Factions; using Server.Mobiles; using Server.Spells; using Server.Spells.Necromancy; using Server.Spells.Spellweaving; using Server.Targeting; namespace Server.SkillHandlers { public static class AnimalTaming { private static readonly HashSet<Mobile> m_BeingTamed = new(); public static bool DisableMessage { get; set; } public static void Initialize() { SkillInfo.Table[(int)SkillName.AnimalTaming].Callback = OnUse; } public static TimeSpan OnUse(Mobile m) { m.RevealingAction(); m.Target = new InternalTarget(); m.RevealingAction(); if (!DisableMessage) { m.SendLocalizedMessage(502789); // Tame which animal? } return TimeSpan.FromSeconds(30); } public static bool CheckMastery(Mobile tamer, BaseCreature creature) => SummonFamiliarSpell.Table.TryGetValue(tamer, out var bc) && bc is DarkWolfFamiliar { Deleted: false } && creature is DireWolf or GreyWolf or TimberWolf or WhiteWolf or BakeKitsune; public static bool MustBeSubdued(BaseCreature bc) => bc.Owners.Count <= 0 && bc.SubdueBeforeTame && bc.Hits > bc.HitsMax / 10; public static void ScaleStats(BaseCreature bc, double scalar) { if (bc.RawStr > 0) { bc.RawStr = (int)Math.Max(1, bc.RawStr * scalar); } if (bc.RawDex > 0) { bc.RawDex = (int)Math.Max(1, bc.RawDex * scalar); } if (bc.RawInt > 0) { bc.RawInt = (int)Math.Max(1, bc.RawInt * scalar); } if (bc.HitsMaxSeed > 0) { bc.HitsMaxSeed = (int)Math.Max(1, bc.HitsMaxSeed * scalar); bc.Hits = bc.Hits; } if (bc.StamMaxSeed > 0) { bc.StamMaxSeed = (int)Math.Max(1, bc.StamMaxSeed * scalar); bc.Stam = bc.Stam; } } public static void ScaleSkills(BaseCreature bc, double scalar) { ScaleSkills(bc, scalar, scalar); } public static void ScaleSkills(BaseCreature bc, double scalar, double capScalar) { for (var i = 0; i < bc.Skills.Length; ++i) { bc.Skills[i].Base *= scalar; bc.Skills[i].Cap = Math.Max(100.0, bc.Skills[i].Cap * capScalar); if (bc.Skills[i].Base > bc.Skills[i].Cap) { bc.Skills[i].Cap = bc.Skills[i].Base; } } } private class InternalTarget : Target { private bool m_SetSkillTime = true; public InternalTarget() : base(Core.AOS ? 3 : 2, false, TargetFlags.None) { } protected override void OnTargetFinish(Mobile from) { if (m_SetSkillTime) { from.NextSkillTime = Core.TickCount; } } protected override void OnTarget(Mobile from, object targeted) { from.RevealingAction(); if (targeted is not Mobile mobile) { from.SendLocalizedMessage(502801); // You can't tame that! return; } if (mobile is not BaseCreature creature) { // That being cannot be tamed. mobile.PrivateOverheadMessage(MessageType.Regular, 0x3B2, 502469, from.NetState); return; } if (!creature.Tamable) { // That creature cannot be tamed. creature.PrivateOverheadMessage(MessageType.Regular, 0x3B2, 1049655, from.NetState); return; } if (creature.Controlled) { // That animal looks tame already. creature.PrivateOverheadMessage(MessageType.Regular, 0x3B2, 502804, from.NetState); return; } if (from.Female && !creature.AllowFemaleTamer) { // That creature can only be tamed by males. creature.PrivateOverheadMessage(MessageType.Regular, 0x3B2, 1049653, from.NetState); return; } if (!from.Female && !creature.AllowMaleTamer) { // That creature can only be tamed by females. creature.PrivateOverheadMessage(MessageType.Regular, 0x3B2, 1049652, from.NetState); return; } if (creature is CuSidhe && from.Race != Race.Elf) { // You can't tame that! creature.PrivateOverheadMessage(MessageType.Regular, 0x3B2, 502801, from.NetState); return; } if (from.Followers + creature.ControlSlots > from.FollowersMax) { from.SendLocalizedMessage(1049611); // You have too many followers to tame that creature. return; } if (creature.Owners.Count >= BaseCreature.MaxOwners && !creature.Owners.Contains(from)) { // This animal has had too many owners and is too upset for you to tame. creature.PrivateOverheadMessage(MessageType.Regular, 0x3B2, 1005615, from.NetState); return; } if (MustBeSubdued(creature)) { // You must subdue this creature before you can tame it! creature.PrivateOverheadMessage(MessageType.Regular, 0x3B2, 1054025, from.NetState); return; } if (!(CheckMastery(from, creature) || from.Skills.AnimalTaming.Value >= creature.MinTameSkill)) { // You have no chance of taming this creature. creature.PrivateOverheadMessage(MessageType.Regular, 0x3B2, 502806, from.NetState); return; } if (creature is FactionWarHorse warHorse) { var faction = Faction.Find(from); if (faction == null || faction != warHorse.Faction) { // You cannot tame this creature. creature.PrivateOverheadMessage(MessageType.Regular, 0x3B2, 1042590, from.NetState); return; } } if (m_BeingTamed.Contains(creature)) { // Someone else is already taming this. creature.PrivateOverheadMessage(MessageType.Regular, 0x3B2, 502802, from.NetState); } else if (creature.CanAngerOnTame && Utility.RandomDouble() < 0.95) { // You seem to anger the beast! creature.PrivateOverheadMessage(MessageType.Regular, 0x3B2, 502805, from.NetState); creature.PlaySound(creature.GetAngerSound()); creature.Direction = creature.GetDirectionTo(from); if (creature.BardPacified && Utility.RandomDouble() < 0.75) { Timer.StartTimer(TimeSpan.FromSeconds(2.0), () => Pacify(creature)); } else { creature.BardEndTime = Core.Now; } creature.BardPacified = false; creature.AIObject?.DoMove(creature.Direction); if (from is PlayerMobile pm && !(VirtueSystem.GetVirtues(pm)?.HonorActive == true || TransformationSpellHelper.UnderTransformation(pm, typeof(EtherealVoyageSpell)))) { creature.Combatant = pm; } } else { m_BeingTamed.Add(creature); // You start to tame the creature. from.LocalOverheadMessage(MessageType.Emote, 0x59, 1010597); // *begins taming a creature.* from.NonlocalOverheadMessage(MessageType.Emote, 0x59, 1010598); new InternalTimer(from, creature, Utility.Random(3, 2)).Start(); m_SetSkillTime = false; } } private static void Pacify(BaseCreature bc) => bc.BardPacified = true; // Should use bc.Pacify with an end time? private class InternalTimer : Timer { private readonly BaseCreature m_Creature; private readonly int m_MaxCount; private readonly DateTime m_StartTime; private readonly Mobile m_Tamer; private int m_Count; private bool m_Paralyzed; public InternalTimer(Mobile tamer, BaseCreature creature, int count) : base( TimeSpan.FromSeconds(3.0), TimeSpan.FromSeconds(3.0), count ) { m_Tamer = tamer; m_Creature = creature; m_MaxCount = count; m_Paralyzed = creature.Paralyzed; m_StartTime = Core.Now; } protected override void OnTick() { m_Count++; var de = m_Creature.FindMostRecentDamageEntry(false); var alreadyOwned = m_Creature.Owners.Contains(m_Tamer); if (!m_Tamer.InRange(m_Creature, Core.AOS ? 7 : 6)) { m_BeingTamed.Remove(m_Creature); m_Tamer.NextSkillTime = Core.TickCount; // You are too far away to continue taming. m_Creature.PrivateOverheadMessage(MessageType.Regular, 0x3B2, 502795, m_Tamer.NetState); Stop(); } else if (!m_Tamer.CheckAlive()) { m_BeingTamed.Remove(m_Creature); m_Tamer.NextSkillTime = Core.TickCount; // You are dead, and cannot continue taming. m_Creature.PrivateOverheadMessage(MessageType.Regular, 0x3B2, 502796, m_Tamer.NetState); Stop(); } else if (!m_Tamer.CanSee(m_Creature) || !m_Tamer.InLOS(m_Creature) || !CanPath()) { m_BeingTamed.Remove(m_Creature); m_Tamer.NextSkillTime = Core.TickCount; // You do not have a clear path to the animal you are taming, and must cease your attempt. m_Tamer.SendLocalizedMessage(1049654); Stop(); } else if (!m_Creature.Tamable) { m_BeingTamed.Remove(m_Creature); m_Tamer.NextSkillTime = Core.TickCount; // That creature cannot be tamed. m_Creature.PrivateOverheadMessage(MessageType.Regular, 0x3B2, 1049655, m_Tamer.NetState); Stop(); } else if (m_Creature.Controlled) { m_BeingTamed.Remove(m_Creature); m_Tamer.NextSkillTime = Core.TickCount; // That animal looks tame already. m_Creature.PrivateOverheadMessage(MessageType.Regular, 0x3B2, 502804, m_Tamer.NetState); Stop(); } else if (m_Creature.Owners.Count >= BaseCreature.MaxOwners && !m_Creature.Owners.Contains(m_Tamer)) { m_BeingTamed.Remove(m_Creature); m_Tamer.NextSkillTime = Core.TickCount; // This animal has had too many owners and is too upset for you to tame. m_Creature.PrivateOverheadMessage(MessageType.Regular, 0x3B2, 1005615, m_Tamer.NetState); Stop(); } else if (MustBeSubdued(m_Creature)) { m_BeingTamed.Remove(m_Creature); m_Tamer.NextSkillTime = Core.TickCount; // You must subdue this creature before you can tame it! m_Creature.PrivateOverheadMessage(MessageType.Regular, 0x3B2, 1054025, m_Tamer.NetState); Stop(); } else if (de?.LastDamage > m_StartTime) { m_BeingTamed.Remove(m_Creature); m_Tamer.NextSkillTime = Core.TickCount; // The animal is too angry to continue taming. m_Creature.PrivateOverheadMessage(MessageType.Regular, 0x3B2, 502794, m_Tamer.NetState); Stop(); } else if (m_Count < m_MaxCount) { m_Tamer.RevealingAction(); switch (Utility.Random(3)) { case 0: { m_Tamer.PublicOverheadMessage(MessageType.Regular, 0x3B2, Utility.Random(502790, 4)); break; } case 1: { m_Tamer.PublicOverheadMessage(MessageType.Regular, 0x3B2, Utility.Random(1005608, 6)); break; } case 2: { m_Tamer.PublicOverheadMessage(MessageType.Regular, 0x3B2, Utility.Random(1010593, 4)); break; } } if (!alreadyOwned) // Passively check animal lore for gain { m_Tamer.CheckTargetSkill(SkillName.AnimalLore, m_Creature, 0.0, 120.0); } if (m_Creature.Paralyzed) { m_Paralyzed = true; } } else { m_Tamer.RevealingAction(); m_Tamer.NextSkillTime = Core.TickCount; m_BeingTamed.Remove(m_Creature); if (m_Creature.Paralyzed) { m_Paralyzed = true; } if (!alreadyOwned) // Passively check animal lore for gain { m_Tamer.CheckTargetSkill(SkillName.AnimalLore, m_Creature, 0.0, 120.0); } var minSkill = m_Creature.MinTameSkill + m_Creature.Owners.Count * 6.0; if (minSkill > -24.9 && CheckMastery(m_Tamer, m_Creature)) { minSkill = -24.9; // 50% at 0.0? } minSkill += 24.9; if (CheckMastery(m_Tamer, m_Creature) || alreadyOwned || m_Tamer.CheckTargetSkill(SkillName.AnimalTaming, m_Creature, minSkill - 25.0, minSkill + 25.0)) { if (m_Creature.Owners.Count == 0) // First tame { if (m_Creature is GreaterDragon) { ScaleSkills(m_Creature, 0.72, 0.90); // 72% of original skills trainable to 90% // Greater dragons have a 90% cap reduction and 90% skill reduction on magery m_Creature.Skills.Magery.Base = m_Creature.Skills.Magery.Cap; } else if (m_Paralyzed) { // 86% of original skills if they were paralyzed during the taming ScaleSkills(m_Creature, 0.86); } else { ScaleSkills(m_Creature, 0.90); // 90% of original skills } if (m_Creature.StatLossAfterTame) { ScaleStats(m_Creature, 0.50); } } if (alreadyOwned) { m_Tamer.SendLocalizedMessage(502797); // That wasn't even challenging. } else { // It seems to accept you as master. m_Creature.PrivateOverheadMessage(MessageType.Regular, 0x3B2, 502799, m_Tamer.NetState); m_Creature.Owners.Add(m_Tamer); } m_Creature.SetControlMaster(m_Tamer); m_Creature.IsBonded = false; m_Creature.ControlTarget = m_Tamer; m_Creature.ControlOrder = OrderType.Follow; } else { // You fail to tame the creature. m_Creature.PrivateOverheadMessage(MessageType.Regular, 0x3B2, 502798, m_Tamer.NetState); } } } private bool CanPath() { IPoint3D p = m_Tamer; return p != null && (m_Creature.InRange(new Point3D(p), 1) || new MovementPath(m_Creature, new Point3D(p)).Success); } } } } }
0
0.979386
1
0.979386
game-dev
MEDIA
0.970812
game-dev
0.963986
1
0.963986
PhoenixBladez/SpiritMod
2,135
Projectiles/DonatorItems/IceReflector.cs
using Microsoft.Xna.Framework; using System.Linq; using Terraria; using Terraria.ModLoader; using Terraria.ID; namespace SpiritMod.Projectiles.DonatorItems { public class IceReflector : ModProjectile { public override void SetStaticDefaults() { DisplayName.SetDefault("Ice Reflector"); } public override void SetDefaults() { projectile.width = 44; projectile.height = 60; projectile.ignoreWater = true; projectile.tileCollide = false; projectile.penetrate = -1; projectile.timeLeft = 360; } public override bool PreAI() { int dust = Dust.NewDust(projectile.position + projectile.velocity, projectile.width, projectile.height, DustID.IceTorch, projectile.velocity.X * 0.5f, projectile.velocity.Y * 0.5f); Main.dust[dust].scale = 0.5f; Main.dust[dust].noGravity = true; Main.dust[dust].noLight = true; return true; } public override void AI() { Player player = Main.player[projectile.owner]; projectile.Center = new Vector2(player.Center.X + (player.direction > 0 ? 0 : 0), player.position.Y + 30); // I dont know why I had to set it to -60 so that it would look right (change to -40 to 40 so that it's on the floor) var list = Main.projectile.Where(x => x.Hitbox.Intersects(projectile.Hitbox)); foreach (var proj in list) { if (projectile != proj && !proj.friendly) proj.Kill(); projectile.localAI[0] += 1f; if (projectile.localAI[0] >= 10f) { projectile.localAI[0] = 0f; int num416 = 0; int num417 = 0; float num418 = 0f; int num419 = projectile.type; for (int num420 = 0; num420 < 1000; num420++) { if (Main.projectile[num420].active && Main.projectile[num420].owner == projectile.owner && Main.projectile[num420].type == num419 && Main.projectile[num420].ai[1] < 3600f) { num416++; if (Main.projectile[num420].ai[1] > num418) { num417 = num420; num418 = Main.projectile[num420].ai[1]; } } } if (num416 > 2) { Main.projectile[num417].netUpdate = true; Main.projectile[num417].ai[1] = 36000f; return; } } } } } }
0
0.726484
1
0.726484
game-dev
MEDIA
0.993156
game-dev
0.970308
1
0.970308
lanedirt/OGameX
2,154
app/GameMissions/BattleEngine/Models/BattleResultRound.php
<?php namespace OGame\GameMissions\BattleEngine\Models; use OGame\GameObjects\Models\Units\UnitCollection; /** * Class BattleResultRound. * * Model class that represents result of a battle round. */ class BattleResultRound { /** * @var UnitCollection Unit losses of the attacker player until now which includes previous rounds. * TODO: now this only works for a single attacker. Support for multiple attackers should be added later. */ public UnitCollection $attackerLosses; /** * @var UnitCollection Unit losses of the player in this round. * TODO: now this only works for a single attacker. Support for multiple attackers should be added later. */ public UnitCollection $attackerLossesInRound; /** * @var UnitCollection Unit losses of the defender until now which includes previous rounds. */ public UnitCollection $defenderLosses; /** * @var UnitCollection Unit losses of the defender player in this round. */ public UnitCollection $defenderLossesInRound; /** * @var int Total amount of hits the attacker made this round. */ public int $hitsAttacker = 0; /** * @var int Total amount of hits the defender made this round. */ public int $hitsDefender = 0; /** * @var int Total amount of damage absorbed by the attacker this round. */ public int $absorbedDamageAttacker = 0; /** * @var int Total amount of damage absorbed by the defender this round. */ public int $absorbedDamageDefender = 0; /** * @var int Total amount of full strength of the attacker at the start of the round. */ public int $fullStrengthAttacker = 0; /** * @var int Total amount of full strength of the defender at the start of the round. */ public int $fullStrengthDefender = 0; /** * @var UnitCollection The units of the attacker remaining at the end of the round. */ public UnitCollection $attackerShips; /** * @var UnitCollection The units of the defender remaining at the end of the round. */ public UnitCollection $defenderShips; }
0
0.93361
1
0.93361
game-dev
MEDIA
0.959898
game-dev
0.520408
1
0.520408
techlabxe/game-programmer-book-build
3,397
src/20_Lighting/RoboFightWithDiffuseLighting/Pad.cpp
#include "Pad.h" #include "GameLib/GameLib.h" #include "GameLib/Input/Manager.h" #include "GameLib/Input/Keyboard.h" #include "GameLib/Input/Joystick.h" using namespace GameLib::Input; Pad* Pad::mInstance = 0; Pad::Pad(){ } Pad::~Pad(){ } void Pad::create(){ ASSERT( !mInstance ); mInstance = new Pad(); } void Pad::destroy(){ ASSERT( mInstance ); SAFE_DELETE( mInstance ); } Pad* Pad::instance(){ return mInstance; } bool Pad::isOn( Button b, int id ) const { bool r = false; //WCXeBbNH Manager m = Manager::instance(); if ( m.joystickNumber() > id ){ Joystick j = m.joystick( id ); switch ( b ){ case JUMP: r = ( j.isOn( 0 ) ) ? 1 : 0; //0ԃ{^Wv break; case FIRE: r = ( j.isOn( 1 ) ) ? 1 : 0; //1ԃ{^ break; case TURN: r = ( j.isOn( 2 ) ) ? 1 : 0; //2ԃ{^ break; case UP: r = ( j.isOn( Joystick::BUTTON_UP ) ) ? 1 : 0; break; case DOWN: r = ( j.isOn( Joystick::BUTTON_DOWN ) ) ? 1 : 0; break; case LEFT: r = ( j.isOn( Joystick::BUTTON_LEFT ) ) ? 1 : 0; break; case RIGHT: r = ( j.isOn( Joystick::BUTTON_RIGHT ) ) ? 1 : 0; break; default: ASSERT( false ); break; } } //L[{[hlj Keyboard k = m.keyboard(); if ( id == 0 ){ //1P char c = 0; switch ( b ){ case UP: c = 'w'; break; case DOWN: c = 'z'; break; case LEFT: c = 'a'; break; case RIGHT: c = 's'; break; case JUMP: c = 'd'; break; case FIRE: c = 'x'; break; case TURN: c = 'e'; break; default: ASSERT( false ); break; } r = r || k.isOn( c ); }else if ( id == 1 ){ //2P char c = 0; switch ( b ){ case UP: c = 'i'; break; case DOWN: c = 'm'; break; case LEFT: c = 'j'; break; case RIGHT: c = 'k'; break; case JUMP: c = 'l'; break; case FIRE: c = ','; break; case TURN: c = 'o'; break; default: ASSERT( false ); break; } r = r || k.isOn( c ); } return r; } bool Pad::isTriggered( Button b, int id ) const { bool r = false; //WCXeBbNH Manager m = Manager::instance(); if ( m.joystickNumber() > id ){ Joystick j = m.joystick( id ); switch ( b ){ case JUMP: r = ( j.isTriggered( 0 ) ) ? 1 : 0; //0ԃ{^Wv break; case FIRE: r = ( j.isTriggered( 1 ) ) ? 1 : 0; //1ԃ{^ break; case TURN: r = ( j.isTriggered( 2 ) ) ? 1 : 0; //2ԃ{^ break; case UP: r = ( j.isTriggered( Joystick::BUTTON_UP ) ) ? 1 : 0; break; case DOWN: r = ( j.isTriggered( Joystick::BUTTON_DOWN ) ) ? 1 : 0; break; case LEFT: r = ( j.isTriggered( Joystick::BUTTON_LEFT ) ) ? 1 : 0; break; case RIGHT: r = ( j.isTriggered( Joystick::BUTTON_RIGHT ) ) ? 1 : 0; break; default: ASSERT( false ); break; } } //L[{[hlj Keyboard k = m.keyboard(); if ( id == 0 ){ //1P char c = 0; switch ( b ){ case UP: c = 'w'; break; case DOWN: c = 'z'; break; case LEFT: c = 'a'; break; case RIGHT: c = 's'; break; case JUMP: c = 'd'; break; case FIRE: c = 'x'; break; case TURN: c = 'e'; break; default: ASSERT( false ); break; } r = r || k.isTriggered( c ); }else if ( id == 1 ){ //2P char c = 0; switch ( b ){ case UP: c = 'i'; break; case DOWN: c = 'm'; break; case LEFT: c = 'j'; break; case RIGHT: c = 'k'; break; case JUMP: c = 'l'; break; case FIRE: c = ','; break; case TURN: c = 'o'; break; default: ASSERT( false ); break; } r = r || k.isTriggered( c ); } return r; }
0
0.504888
1
0.504888
game-dev
MEDIA
0.783732
game-dev
0.674644
1
0.674644
planetchili/3D_Fundamentals
2,727
Engine/Keyboard.h
/****************************************************************************************** * Chili DirectX Framework Version 16.10.01 * * Keyboard.h * * Copyright 2016 PlanetChili.net <http://www.planetchili.net> * * * * This file is part of The Chili DirectX Framework. * * * * The Chili DirectX Framework is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * The Chili DirectX Framework is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with The Chili DirectX Framework. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************************/ #pragma once #include <queue> #include <bitset> class Keyboard { friend class MainWindow; public: class Event { public: enum Type { Press, Release, Invalid }; private: Type type; unsigned char code; public: Event() : type( Invalid ), code( 0u ) {} Event( Type type,unsigned char code ) : type( type ), code( code ) {} bool IsPress() const { return type == Press; } bool IsRelease() const { return type == Release; } bool IsValid() const { return type != Invalid; } unsigned char GetCode() const { return code; } }; public: Keyboard() = default; Keyboard( const Keyboard& ) = delete; Keyboard& operator=( const Keyboard& ) = delete; bool KeyIsPressed( unsigned char keycode ) const; Event ReadKey(); bool KeyIsEmpty() const; char ReadChar(); bool CharIsEmpty() const; void FlushKey(); void FlushChar(); void Flush(); void EnableAutorepeat(); void DisableAutorepeat(); bool AutorepeatIsEnabled() const; private: void OnKeyPressed( unsigned char keycode ); void OnKeyReleased( unsigned char keycode ); void OnChar( char character ); template<typename T> void TrimBuffer( std::queue<T>& buffer ); private: static constexpr unsigned int nKeys = 256u; static constexpr unsigned int bufferSize = 4u; bool autorepeatEnabled = false; std::bitset<nKeys> keystates; std::queue<Event> keybuffer; std::queue<char> charbuffer; };
0
0.656189
1
0.656189
game-dev
MEDIA
0.531155
game-dev
0.540831
1
0.540831
SourceEngine-CommunityEdition/source
1,194
game/server/lights.h
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // //=============================================================================// #ifndef LIGHTS_H #define LIGHTS_H #ifdef _WIN32 #pragma once #endif //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- class CLight : public CPointEntity { public: DECLARE_CLASS( CLight, CPointEntity ); bool KeyValue( const char *szKeyName, const char *szValue ); void Spawn( void ); void FadeThink( void ); void Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ); void TurnOn( void ); void TurnOff( void ); void Toggle( void ); // Input handlers void InputSetPattern( inputdata_t &inputdata ); void InputFadeToPattern( inputdata_t &inputdata ); void InputToggle( inputdata_t &inputdata ); void InputTurnOn( inputdata_t &inputdata ); void InputTurnOff( inputdata_t &inputdata ); DECLARE_DATADESC(); private: int m_iStyle; int m_iDefaultStyle; string_t m_iszPattern; char m_iCurrentFade; char m_iTargetFade; }; #endif // LIGHTS_H
0
0.915396
1
0.915396
game-dev
MEDIA
0.395493
game-dev
0.59094
1
0.59094
stohrendorf/CroftEngine
5,501
src/ui/text.cpp
#include "text.h" #include "core.h" #include "ui.h" #include "util.h" #include <array> #include <boost/algorithm/string/trim.hpp> #include <cstddef> #include <cstdint> #include <gl/pixel.h> #include <glm/vec2.hpp> #include <gsl/gsl-lite.hpp> #include <string> #include <tuple> #include <utility> #include <vector> namespace ui { namespace { constexpr int LetterSpacing = 1; constexpr int WordSpacing = 6; const std::array<const int, 110> charWidths{ 14, 11, 11, 11, 11, 11, 11, 13, 8, 11, 12, 11, 13, 13, 12, 11, 12, 12, 11, 12, 13, 13, 13, 12, 12, 11, 9, 9, 9, 9, 9, 9, 9, 9, 5, 9, 9, 5, 12, 10, 9, 9, 9, 8, 9, 8, 9, 9, 11, 9, 9, 9, 12, 8, 10, 10, 10, 10, 10, 9, 10, 10, 5, 5, 5, 11, 9, 10, 8, 6, 6, 7, 7, 3, /* szlig */ 7, 8, 13, 16, 9, 4, 12, 12, 7, 5, 7, 7, 7, 7, 7, 7, 7, 7, 16, 14, 14, 14, 16, 16, 16, 16, 16, 12, 14, 8, 8, 8, 8, 8, 8, 8}; const std::array<const uint8_t, 98> charToSprite{ 0, 64, 66, 78, 77, 74, 78, 79, 69, 70, 92, 72, 63, 71, 62, 68, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 73, 73, 66, 74, 75, 65, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 80, 76, 81, 97, 98, 77, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 100, 101, 102, 67, 0, 0, 0}; std::vector<std::tuple<glm::ivec2, uint8_t>> doLayout(const std::string& text, int* width = nullptr) { if(text.empty()) { if(width != nullptr) *width = 0; return {}; } std::vector<std::tuple<glm::ivec2, uint8_t>> layout; glm::ivec2 xy{0, 0}; bool isSpriteSelector = false; for(const uint8_t chr : text) { uint8_t sprite = chr; if(chr == SpriteSelector) { isSpriteSelector = true; continue; } if(isSpriteSelector) { isSpriteSelector = false; layout.emplace_back(xy, sprite); } else { if(chr > 15 && chr < 32) continue; if(chr == ' ') { xy.x += WordSpacing; if(width != nullptr) *width = xy.x; continue; } if(chr <= 10) sprite = chr + 81; else if(chr <= 15) sprite = chr + 91; else sprite = charToSprite.at(chr - 32); // cppcheck-suppress invalidFunctionArg layout.emplace_back(xy, sprite); if(chr == Acute1 || chr == Acute2 || chr == Gravis || chr == UmlautDots) continue; } xy.x += charWidths[sprite] + LetterSpacing; if(width != nullptr) *width = xy.x; } if(width != nullptr) *width -= LetterSpacing; return layout; } } // namespace std::string makeAmmoString(const std::string& str) { std::string result; for(const char c : str) { if(c == ' ') { result += c; continue; } if(c < 'A') { result += static_cast<char>(int(c) - int('0') + 1); } else { result += static_cast<char>(int(c) - int('A') + 12); } } return result; } void TRFont::draw(ui::Ui& ui, size_t sprite, const glm::ivec2& xy, float scale, float alpha) const { ui.draw(m_sprites[sprite], xy, scale, alpha); } Text::Text(const std::string& text) : m_layout{doLayout(text, &m_width)} { gsl_Ensures(m_width >= 0); } void Text::draw(Ui& ui, const TRFont& font, const glm::ivec2& position, float scale, float alpha) const { for(const auto& [xy, sprite] : m_layout) { font.draw(ui, sprite, xy + position, scale, alpha); } } void drawBox(const Text& text, Ui& ui, const glm::ivec2& pos, int padding, const gl::SRGBA8& color, float scale) { ui.drawBox(pos + glm::ivec2{-padding, padding}, glm::ivec2{text.getWidth() * scale + 2 * padding, -FontHeight * scale - 2 * padding - 2}, color); } std::vector<std::string> breakLines(const std::string& text, int maxWidth) { std::vector<std::string> words; size_t start = 0; while(start != std::string::npos) { const auto last = text.find_first_of("\n ", start); if(last == std::string::npos) { words.emplace_back(text.substr(start)); break; } if(last != start) words.emplace_back(text.substr(start, last - start)); words.emplace_back(text.substr(last, 1)); start = last + 1; } std::vector<std::string> lines; std::string candidate; bool hadImplicitLineBreak = false; for(const auto& word : words) { if(word == "\n") { // forced newline; trim trailing spaces boost::algorithm::trim_right(candidate); if(!hadImplicitLineBreak || !candidate.empty()) lines.emplace_back(candidate); candidate.clear(); hadImplicitLineBreak = false; continue; } else if(word == " ") { // skip spaces at start of line if(!candidate.empty()) candidate += ' '; hadImplicitLineBreak = false; continue; } auto nextCandidate = candidate + word; int width = 0; doLayout(nextCandidate, &width); if(width <= maxWidth) { candidate = std::move(nextCandidate); hadImplicitLineBreak = false; } else { // line would exceed max length, add previous lines.emplace_back(boost::algorithm::trim_right_copy(candidate)); candidate = word; hadImplicitLineBreak = true; } } candidate = boost::algorithm::trim_right_copy(candidate); if(!candidate.empty()) { lines.emplace_back(std::move(candidate)); } return lines; } } // namespace ui
0
0.93751
1
0.93751
game-dev
MEDIA
0.357252
game-dev
0.935735
1
0.935735
BlesseNtumble/GalaxySpace
4,113
src/main/java/galaxyspace/systems/SolarSystem/planets/mercury/blocks/MercuryBlocks.java
package galaxyspace.systems.SolarSystem.planets.mercury.blocks; import micdoodle8.mods.galacticraft.api.block.IDetectableResource; import micdoodle8.mods.galacticraft.api.block.ITerraformableBlock; import micdoodle8.mods.galacticraft.core.blocks.ISortableBlock; import micdoodle8.mods.galacticraft.core.util.EnumSortCategoryBlock; import net.minecraft.block.Block; import net.minecraft.block.SoundType; import net.minecraft.block.material.Material; import net.minecraft.block.properties.PropertyEnum; import net.minecraft.block.state.BlockStateContainer; import net.minecraft.block.state.IBlockState; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.IStringSerializable; import net.minecraft.util.NonNullList; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.RayTraceResult; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; public class MercuryBlocks extends Block implements ISortableBlock, ITerraformableBlock, IDetectableResource{ public static final PropertyEnum<EnumBlockMercury> BASIC_TYPE = PropertyEnum.create("type", EnumBlockMercury.class); public MercuryBlocks() { super(Material.ROCK); this.setTranslationKey("mercuryblocks"); this.setSoundType(SoundType.STONE); this.setHarvestLevel("pickaxe", 2); // GSBlocks.GS_BLOCKS.add(this); } @Override public ItemStack getPickBlock(IBlockState state, RayTraceResult target, World world, BlockPos pos, EntityPlayer player) { return new ItemStack(Item.getItemFromBlock(this), 1, this.getMetaFromState(state)); } @SideOnly(Side.CLIENT) @Override public void getSubBlocks(CreativeTabs tab, NonNullList<ItemStack> list) { for (EnumBlockMercury blockBasic : EnumBlockMercury.values()) { list.add(new ItemStack(this, 1, blockBasic.getMeta())); } } @Override public int damageDropped(IBlockState state) { EnumBlockMercury type = ((EnumBlockMercury) state.getValue(BASIC_TYPE)); switch (type) { default: return getMetaFromState(state); } } @Override public EnumSortCategoryBlock getCategory(int meta) { return EnumSortCategoryBlock.GENERAL; } @Override public boolean isValueable(IBlockState metadata) { return false; } @Override public boolean isTerraformable(World world, BlockPos pos) { if(world.getBlockState(pos) == this.getDefaultState().withProperty(BASIC_TYPE, EnumBlockMercury.SURFACE)) return true; return false; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public enum EnumBlockMercury implements IStringSerializable { SURFACE(0, "mercury_surface"), SUBSURFACE(1, "mercury_subsurface"), STONE(2, "mercury_stone"), NICKEL_ORE(3, "mercury_nickel_ore"), IRON_ORE(4, "mercury_iron_ore"), MAGNESIUM_ORE(5, "mercury_magnesium_ore"); private final int meta; private final String name; private EnumBlockMercury(int meta, String name) { this.meta = meta; this.name = name; } public int getMeta() { return this.meta; } private final static EnumBlockMercury[] values = values(); public static EnumBlockMercury byMetadata(int meta) { return values[meta % values.length]; } @Override public String getName() { return this.name; } } @Override public IBlockState getStateFromMeta(int meta) { return this.getDefaultState().withProperty(BASIC_TYPE, EnumBlockMercury.byMetadata(meta)); } @Override public int getMetaFromState(IBlockState state) { return ((EnumBlockMercury) state.getValue(BASIC_TYPE)).getMeta(); } @Override protected BlockStateContainer createBlockState() { return new BlockStateContainer(this, BASIC_TYPE); } }
0
0.767281
1
0.767281
game-dev
MEDIA
0.986223
game-dev
0.6571
1
0.6571
PassPar2/ss_playerstates
4,592
client/stress.lua
-- Stress Gain : Speeding local stressConfig = require 'config.states.stress' local stressData = stressConfig.effectData or {} local stressSpeed = stressData.stressSpeed local speedStressRange = stressData.speedStressRange local speedStressInterval = stressData.speedStressInterval local function isSpeedStressWhitelistedJob() local playerJob = QBX.PlayerData.job.name for _, v in pairs(stressData.speedStressWhitlistedJobs) do if playerJob == v then return true end end return false end CreateThread(function() while true do if LocalPlayer.state.isLoggedIn and not isSpeedStressWhitelistedJob() and not LocalPlayer.state.isDead then if cache.vehicle then local vehClass = GetVehicleClass(cache.vehicle) local speed = GetEntitySpeed(cache.vehicle) if vehClass ~= 13 and vehClass ~= 14 and vehClass ~= 15 and vehClass ~= 16 and vehClass ~= 21 then if speed >= stressSpeed then exports.ss_playerstates:AddToState('stress', math.random(speedStressRange.min, speedStressRange.max)) end end end end Wait(speedStressInterval) end end) -- Stress Gain : Shooting local hasWeapon = false local whitelistedWeapons = stressData.whitelistedWeapons local stressChance = stressData.stressChance local weaponStressRange = stressData.weaponStressRange local function isWhitelistedWeaponStress(weapon) if weapon then for _, v in pairs(whitelistedWeapons) do if type(v) == 'string' and type(weapon) == 'string' and weapon:lower() == v:lower() then return true end end end return false end local function startWeaponStressThread(weapon) if isWhitelistedWeaponStress(weapon) then return end hasWeapon = true CreateThread(function() while hasWeapon and not LocalPlayer.state.isDead do if IsPedShooting(cache.ped) then if math.random() <= stressChance then exports.ss_playerstates:AddToState('stress', math.random(weaponStressRange.min, weaponStressRange.max)) end end Wait(0) end end) end AddEventHandler('ox_inventory:currentWeapon', function(currentWeapon) hasWeapon = false Wait(0) if not currentWeapon then return end startWeaponStressThread(currentWeapon.name) end) -- Stress Effects -- local minForShaking = stressData.minForShaking local blurIntensity = stressData.blurIntensity local effectInterval = stressData.effectInterval local function getBlurIntensity(stresslevel) for _, v in pairs(blurIntensity) do if stresslevel >= v.min and stresslevel <= v.max then return v.intensity end end return 1500 end local function getEffectInterval(stresslevel) for _, v in pairs(effectInterval) do if stresslevel >= v.min and stresslevel <= v.max then return v.timeout end end return 60000 end CreateThread(function() while true do if LocalPlayer.state.isLoggedIn and not LocalPlayer.state.isDead and not LocalPlayer.state.onEffect then local stress = LocalPlayer.state.stress or stressConfig.value.default local effectWaitInterval = getEffectInterval(stress) if stress >= stressConfig.value.max then LocalPlayer.state.onEffect = true local blurIntensityInterval = getBlurIntensity(stress) local fallRepeat = math.random(2, 4) local ragdollTimeout = fallRepeat * 1750 TriggerScreenblurFadeIn(1000.0) Wait(blurIntensityInterval) TriggerScreenblurFadeOut(1000.0) if not IsPedRagdoll(cache.ped) and IsPedOnFoot(cache.ped) and not IsPedSwimming(cache.ped) then local forwardVector = GetEntityForwardVector(cache.ped) SetPedToRagdollWithFall(cache.ped, ragdollTimeout, ragdollTimeout, 1, forwardVector.x, forwardVector.y, forwardVector.z, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0) end Wait(1000) for _ = 1, fallRepeat, 1 do Wait(750) DoScreenFadeOut(200) Wait(1000) DoScreenFadeIn(200) TriggerScreenblurFadeIn(1000.0) Wait(blurIntensityInterval) TriggerScreenblurFadeOut(1000.0) end LocalPlayer.state.onEffect = false elseif stress >= minForShaking then LocalPlayer.state.onEffect = true local blurIntensityInterval = getBlurIntensity(stress) TriggerScreenblurFadeIn(1000.0) Wait(blurIntensityInterval) TriggerScreenblurFadeOut(1000.0) LocalPlayer.state.onEffect = false end Wait(effectWaitInterval) else Wait(1000) end end end)
0
0.899729
1
0.899729
game-dev
MEDIA
0.941571
game-dev
0.978488
1
0.978488
mozilla/arewefastyet
3,673
benchmarks/asmjs-apps/bullet/src/BulletCollision/CollisionDispatch/btCompoundCollisionAlgorithm.h
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef BT_COMPOUND_COLLISION_ALGORITHM_H #define BT_COMPOUND_COLLISION_ALGORITHM_H #include "btActivatingCollisionAlgorithm.h" #include "BulletCollision/BroadphaseCollision/btDispatcher.h" #include "BulletCollision/BroadphaseCollision/btBroadphaseInterface.h" #include "BulletCollision/NarrowPhaseCollision/btPersistentManifold.h" class btDispatcher; #include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h" #include "btCollisionCreateFunc.h" #include "LinearMath/btAlignedObjectArray.h" class btDispatcher; class btCollisionObject; /// btCompoundCollisionAlgorithm supports collision between CompoundCollisionShapes and other collision shapes class btCompoundCollisionAlgorithm : public btActivatingCollisionAlgorithm { btAlignedObjectArray<btCollisionAlgorithm*> m_childCollisionAlgorithms; bool m_isSwapped; class btPersistentManifold* m_sharedManifold; bool m_ownsManifold; int m_compoundShapeRevision;//to keep track of changes, so that childAlgorithm array can be updated void removeChildAlgorithms(); void preallocateChildAlgorithms(btCollisionObject* body0,btCollisionObject* body1); public: btCompoundCollisionAlgorithm( const btCollisionAlgorithmConstructionInfo& ci,btCollisionObject* body0,btCollisionObject* body1,bool isSwapped); virtual ~btCompoundCollisionAlgorithm(); virtual void processCollision (btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut); btScalar calculateTimeOfImpact(btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut); virtual void getAllContactManifolds(btManifoldArray& manifoldArray) { int i; for (i=0;i<m_childCollisionAlgorithms.size();i++) { if (m_childCollisionAlgorithms[i]) m_childCollisionAlgorithms[i]->getAllContactManifolds(manifoldArray); } } struct CreateFunc :public btCollisionAlgorithmCreateFunc { virtual btCollisionAlgorithm* CreateCollisionAlgorithm(btCollisionAlgorithmConstructionInfo& ci, btCollisionObject* body0,btCollisionObject* body1) { void* mem = ci.m_dispatcher1->allocateCollisionAlgorithm(sizeof(btCompoundCollisionAlgorithm)); return new(mem) btCompoundCollisionAlgorithm(ci,body0,body1,false); } }; struct SwappedCreateFunc :public btCollisionAlgorithmCreateFunc { virtual btCollisionAlgorithm* CreateCollisionAlgorithm(btCollisionAlgorithmConstructionInfo& ci, btCollisionObject* body0,btCollisionObject* body1) { void* mem = ci.m_dispatcher1->allocateCollisionAlgorithm(sizeof(btCompoundCollisionAlgorithm)); return new(mem) btCompoundCollisionAlgorithm(ci,body0,body1,true); } }; }; #endif //BT_COMPOUND_COLLISION_ALGORITHM_H
0
0.864438
1
0.864438
game-dev
MEDIA
0.994182
game-dev
0.685548
1
0.685548
shawwn/noh
17,710
src/hon_shared/i_visualentity.h
// (C)2007 S2 Games // i_visualentity.h // //============================================================================= #ifndef __I_VISUALENTITY_H__ #define __I_VISUALENTITY_H__ //============================================================================= // Headers //============================================================================= #include "i_gameentity.h" #include "c_entityevent.h" #include "c_player.h" #include "../k2/s_traceinfo.h" //============================================================================= //============================================================================= // Declarations //============================================================================= class IVisualEntity; class IPropEntity; class IProjectile; class ILight; class IGadgetEntity; class IBuildingEntity; class IUnitEntity; class CSceneEntity; class CBufferDynamic; class CSkeleton; class IEntityState; class CWorldEntity; class CSkeleton; class CEffectThread; //============================================================================= //============================================================================= // Definitions //============================================================================= const uint ENTITY_EVENT_BUFFER_LENGTH(4); const uint NUM_EFFECT_CHANNELS(4); // Effect channels const uint EFFECT_CHANNEL_PROJECTILE_TRAIL (0); const uint EFFECT_CHANNEL_PASSIVE (0); const uint EFFECT_CHANNEL_BUILDING_LOW_HEALTH (1); const uint EFFECT_CHANNEL_TRIGGER (3); const uint EFFECT_CHANNEL_VOICECOMMAND (3); //// enum EEntityStatus { ENTITY_STATUS_DORMANT, ENTITY_STATUS_ACTIVE, ENTITY_STATUS_DEAD, ENTITY_STATUS_CORPSE, ENTITY_STATUS_HIDDEN, NUM_ENTITY_STATUSES }; const byte NO_INTERPOLATE_MASK (BIT(0) | BIT(1)); const byte RESET_MASK (BIT(2) | BIT(3)); struct SWorkingMovementVars { float fFrameTime; CPlane plGround; float fRunSpeed; CVec3f v3OldPosition; CVec3f v3OldVelocity; CVec3f v3OldAngles; CVec3f v3Position; CVec3f v3Velocity; CVec3f v3Angles; CVec3f v3Intent; bool bGroundControl; int iMoveFlags; bool bLanded; }; const byte ENTITY_INVALID_ANIM (-1); const byte ENTITY_STOP_ANIM (-2); // Entity Client Render Flags const int ECRF_HALFTRANSPARENT (BIT(0)); const int MOVE_ON_GROUND (BIT(0)); const int MOVE_JUMP_HELD (BIT(1)); const int MOVE_JUMPING (BIT(2)); const int MOVE_ATTACK_HELD (BIT(3)); const uint ENT_LOCAL_DELETE_NEXT_FRAME (BIT(0)); const uint ENT_LOCAL_CHANGING_UNIT (BIT(1)); const uint ENT_LOCAL_SHOW_EFFECTS (BIT(2)); const uint ENT_LOCAL_RECIPE_EFFECT (BIT(3)); const uint ENT_LOCAL_FIXED_POSITION (BIT(4)); const uint ENT_BIND_TURN (BIT(0)); const uint ENT_BIND_UNBIND_ON_DEATH (BIT(1)); const uint ENT_BIND_NO_PUSH (BIT(2)); struct SEntityBind { uint uiEntityUID; CVec3f v3Offset; uint uiFlags; }; //============================================================================= //============================================================================= // IVisualEntity //============================================================================= class IVisualEntity : public IGameEntity { DECLARE_ENTITY_DESC protected: tstring m_sName; uint m_uiWorldIndex; uint m_uiTeamID; byte m_yStatus; byte m_ySequence; ushort m_unVisibilityFlags; // Physics CVec3f m_v3Position; CVec3f m_v3Velocity; CVec3f m_v3Angles; float m_fScale; CBBoxf m_bbBounds; uint m_uiGroundEntityIndex; uint m_uiBindTargetUID; vector<SEntityBind> m_vBinds; uivector m_vBindStateUIDs; // Events byte m_yNextEventSlot; byte m_yLastProcessedEvent; CEntityEvent m_aEvents[ENTITY_EVENT_BUFFER_LENGTH]; uint m_uiLocalFlags; // Never transmitted // Visual CSkeleton* m_pSkeleton; tstring m_asAnim[NUM_ANIM_CHANNELS]; byte m_ayAnim[NUM_ANIM_CHANNELS]; byte m_ayAnimSequence[NUM_ANIM_CHANNELS]; float m_afAnimSpeed[NUM_ANIM_CHANNELS]; uint m_auiAnimLockTime[NUM_ANIM_CHANNELS]; ResHandle m_ahEffect[NUM_EFFECT_CHANNELS]; byte m_ayEffectSequence[NUM_EFFECT_CHANNELS]; // Client-side only uint m_uiClientRenderFlags; uint m_uiSelectFrame; CVec4f m_v4HighlightColor; CAxis m_aAxis; CVec3f m_v3AxisAngles; tstring m_sTerrainType; uint m_uiLastTerrainTypeUpdateTime; uint m_uiOrderTime; CVec4f m_v4MinimapFlashColor; uint m_uiMinimapFlashEndTime; #ifdef __GNUC__ __attribute__ ((visibility("default"))) #endif // Slide-movement bool IsPositionValid(const CVec3f &v3Position); public: virtual ~IVisualEntity() {} IVisualEntity(); // Accessors SUB_ENTITY_ACCESSOR(IVisualEntity, Visual) const tstring& GetName() const { return m_sName; } void SetName(const tstring &sName) { m_sName = sName; } uint GetWorldIndex() const { return m_uiWorldIndex; } void SetWorldIndex(uint uiIndex) { m_uiWorldIndex = uiIndex; } uint GetTeam() const { return m_uiTeamID; } virtual void SetTeam(uint uiTeam) { m_uiTeamID = uiTeam; } byte GetStatus() const { return m_yStatus; } void SetStatus(byte yStatus) { m_yStatus = yStatus; } void ClearVisibilityFlags() { m_unVisibilityFlags = 0; } void ClearVisibilityFlagsDead() { m_unVisibilityFlags &= ~(REVEALED_FLAG_MASK | VISION_FLAG_MASK); } void RemoveVisibilityFlags(ushort unFlags) { m_unVisibilityFlags &= ~unFlags; } void SetVisibilityFlags(ushort unFlags) { m_unVisibilityFlags |= unFlags; } bool HasVisibilityFlags(ushort unFlags) const { return (m_unVisibilityFlags & unFlags) == unFlags; } ushort GetVisibilityFlags() const { return m_unVisibilityFlags; } void IncNoInterpolateSequence() { m_ySequence = (m_ySequence & ~NO_INTERPOLATE_MASK) | (NO_INTERPOLATE_MASK & ((m_ySequence | ~NO_INTERPOLATE_MASK) + 1)); } byte GetNoInterpolateSequence() const { return (m_ySequence & NO_INTERPOLATE_MASK); } void IncResetSequence() { m_ySequence = (m_ySequence & ~RESET_MASK) | (RESET_MASK & ((m_ySequence | ~RESET_MASK) + 1)); } byte GetResetSequence() const { return (m_ySequence & RESET_MASK); } const CVec3f& GetPosition() const { return m_v3Position; } void SetPosition(const CVec3f &v3Pos) { m_v3Position = v3Pos; } void SetPosition(float x, float y, float z) { m_v3Position = CVec3f(x, y, z); } const CVec3f& GetAngles() const { return m_v3Angles; } void SetAngles(const CVec3f &v3Angles) { m_v3Angles = v3Angles; } void SetAngles(float fPitch, float fRoll, float fYaw) { m_v3Angles = CVec3f(fPitch, fRoll, fYaw); } const CVec3f& GetVelocity() const { return m_v3Velocity; } void SetVelocity(const CVec3f &v3Velocity) { m_v3Velocity = v3Velocity; } void ApplyVelocity(const CVec3f &v3Velocity) { m_v3Velocity += v3Velocity; } virtual float GetBaseScale() const { return 1.0f; } virtual float GetScale() const { return m_fScale; } void SetScale(float fScale) { m_fScale = fScale; } virtual float GetEffectScale() const { return 1.0f; } virtual float GetModelScale() const { return 1.0f; } virtual ResHandle GetModel() const { return INVALID_RESOURCE; } void SetSkeleton(CSkeleton *pSkeleton) { m_pSkeleton = pSkeleton; } int GetAnim(int iChannel) { return m_ayAnim[iChannel]; } const tstring& GetAnimName(int iChannel) { return m_asAnim[iChannel]; } void SetAnim(int iChannel, int iAnim) { m_ayAnim[iChannel] = iAnim; } void SetAnim(int iChannel, int iAnim, float fAnimSpeed) { m_ayAnim[iChannel] = iAnim; m_afAnimSpeed[iChannel] = fAnimSpeed; } void SetAnim(int iChannel, const tstring &sAnim) { m_asAnim[iChannel] = sAnim; } void SetAnim(int iChannel, const tstring &sAnim, float fAnimSpeed) { m_asAnim[iChannel] = sAnim; m_afAnimSpeed[iChannel] = fAnimSpeed; } void SetAnim(int iChannel, const tstring &sAnim, float fAnimSpeed, byte ySequence) { m_asAnim[iChannel] = sAnim; m_afAnimSpeed[iChannel] = fAnimSpeed; m_ayAnimSequence[iChannel] = ySequence; } byte GetAnimSequence(int iChannel) { return m_ayAnimSequence[iChannel]; } void SetAnimSequence(int iChannel, byte ySequence) { m_ayAnimSequence[iChannel] = ySequence; } void IncAnimSequence(int iChannel) { ++m_ayAnimSequence[iChannel]; } float GetAnimSpeed(int iChannel) { return m_afAnimSpeed[iChannel]; } void SetAnimSpeed(int iChannel, float fAnimSpeed) { m_afAnimSpeed[iChannel] = fAnimSpeed; } virtual void GetAnimState(int iChannel, int &iAnim, byte &ySequence, float &fSpeed) { iAnim = m_ayAnim[iChannel]; ySequence = m_ayAnimSequence[iChannel]; fSpeed = m_afAnimSpeed[iChannel]; } ResHandle GetEffect(int iChannel) { return m_ahEffect[iChannel]; } void SetEffect(int iChannel, ResHandle hEffect) { m_ahEffect[iChannel] = hEffect; } byte GetEffectSequence(int iChannel) { return m_ayEffectSequence[iChannel]; } void IncEffectSequence(int iChannel) { ++m_ayEffectSequence[iChannel]; } const CBBoxf& GetBounds() { return m_bbBounds; } CSkeleton* GetSkeleton() { return m_pSkeleton; } uint GetGroundEntityIndex() const { return m_uiGroundEntityIndex; } // Network virtual void Baseline(); virtual void GetSnapshot(CEntitySnapshot &snapshot, uint uiFlags) const; virtual bool ReadSnapshot(CEntitySnapshot &snapshot, uint uiVersion); static void ClientPrecache(CEntityConfig *pConfig, EPrecacheScheme eScheme, const tstring &sModifier); static void ServerPrecache(CEntityConfig *pConfig, EPrecacheScheme eScheme, const tstring &sModifier); virtual void ApplyWorldEntity(const CWorldEntity &ent); // Local flags // Clients maintain local flags in m_pCurrentState only void CopyLocalFlags(IVisualEntity *pOther) { m_uiLocalFlags = pOther->m_uiLocalFlags; } void SetLocalFlags(uint uiFlags) { m_uiLocalFlags |= uiFlags; } void ToggleLocalFlags(uint uiFlags) { m_uiLocalFlags ^= uiFlags; } void RemoveLocalFlags(uint uiFlags) { m_uiLocalFlags &= ~uiFlags; } void ClearLocalFlags() { m_uiLocalFlags = 0; } bool HasLocalFlags(uint uiFlags) const { return (m_uiLocalFlags & uiFlags) != 0; } bool HasAllLocalFlags(uint uiFlags) const { return (m_uiLocalFlags & uiFlags) == uiFlags; } // Visual virtual CSkeleton* AllocateSkeleton() { return nullptr; } virtual void UpdateSkeleton(bool bPose); GAME_SHARED_API void StartAnimation(const tstring &sAnimName, int iChannel, float fSpeed = 1.0f, uint uiLength = 0); GAME_SHARED_API void StartRandomAnimation(const tstring &sAnimName, int iNumAnims, int iChannel, float fSpeed = 1.0f, uint uiLength = 0); GAME_SHARED_API void StopAnimation(int iChannel); GAME_SHARED_API void StopAnimation(const tstring &sAnimName, int iChannel); GAME_SHARED_API void LockAnimation(int iChannel, uint uiTime); GAME_SHARED_API int GetAnimIndex(const tstring &sAnimName); virtual bool AddToScene(const CVec4f &v4Color, int iFlags); // Events void AddEvent(EEntityEvent eEvent); virtual void Copy(const IGameEntity &B); // Physics virtual void Link() {} virtual void Unlink() {} // Client-side GAME_SHARED_API void MinimapFlash(const CVec4f &v4Color, uint uiDuration); void AddClientRenderFlags(uint uiFlags) { m_uiClientRenderFlags |= uiFlags; } void RemoveClientRenderFlags(uint uiFlags) { m_uiClientRenderFlags &= ~uiFlags; } uint GetClientRenderFlags() const { return m_uiClientRenderFlags; } void SetHighlightFrame() { m_uiSelectFrame = Host.GetFrame(); } bool IsHighlighted() const { return m_uiSelectFrame == Host.GetFrame(); } const CAxis& GetAxis() const { return m_aAxis; } void SetOrderTime(uint uiOrderTime) { m_uiOrderTime = uiOrderTime; } uint GetOrderTime() const { return m_uiOrderTime; } void SetShowEffects(bool bShowEffects) { if (bShowEffects) m_uiLocalFlags |= ENT_LOCAL_SHOW_EFFECTS; else m_uiLocalFlags &= ~ENT_LOCAL_SHOW_EFFECTS; } bool GetShowEffects() const { return (m_uiLocalFlags & ENT_LOCAL_SHOW_EFFECTS) != 0; } virtual CVec4f GetMapIconColor(CPlayer *pLocalPlayer) const { return WHITE; } virtual float GetMapIconSize(CPlayer *pLocalPlayer) const { return 0.0f; } virtual ResHandle GetMapIcon(CPlayer *pLocalPlayer) const { return INVALID_RESOURCE; } virtual bool IsVisibleOnMap(CPlayer *pLocalPlayer) const { return pLocalPlayer->CanSee(this) && GetStatus() == ENTITY_STATUS_ACTIVE; } virtual void DrawOnMap(class CUITrigger &minimap, CPlayer *pLocalPlayer) const; virtual void DrawOutlineOnMap(class CUITrigger &minimap, CPlayer *pLocalPlayer) const; void SetHighlightColor(const CVec4f &v4Color) { m_v4HighlightColor = v4Color; } const CVec4f& GetHighlightColor() const { return m_v4HighlightColor; } virtual void Interpolate(float fLerp, IVisualEntity *pPrevState, IVisualEntity *pNextState); virtual void UpdateEffectThreadSource(CEffectThread *pEffectThread); virtual void UpdateEffectThreadTarget(CEffectThread *pEffectThread); virtual CVec3f GetApproachPosition(const CVec3f &v3Start, const CBBoxf &bbBounds) { return m_v3Position; } GAME_SHARED_API const tstring& GetTerrainType(); virtual void Bind(IUnitEntity *pTarget, const CVec3f &v3Offset, uint uiFlags); virtual void ReleaseBinds(); virtual void ReleaseBind(uint uiUID); virtual uint GetBindFlags(uint uiUID); virtual uint GetBindFlags(); virtual bool HasBinds(); virtual void AddBindState(uint uiUID) { m_vBindStateUIDs.push_back(uiUID); } virtual void Unbind(); virtual bool ServerFrameMovement() { if (!ServerFrameMovementStart()) return false; return ServerFrameMovementEnd(); } virtual bool ServerFrameMovementStart() { return IGameEntity::ServerFrameMovement(); } virtual bool ServerFrameMovementEnd(); }; //============================================================================= #endif //__I_VISUALENTITY_H__
0
0.898447
1
0.898447
game-dev
MEDIA
0.547511
game-dev
0.884574
1
0.884574
Rosewood-Development/RoseStacker
1,270
NMS/v1_21_R4/src/main/java/dev/rosewood/rosestacker/nms/v1_21_R4/event/AsyncEntityDeathEventImpl.java
package dev.rosewood.rosestacker.nms.v1_21_R4.event; import dev.rosewood.rosestacker.event.AsyncEntityDeathEvent; import dev.rosewood.rosestacker.nms.util.ReflectionUtils; import java.lang.reflect.Field; import java.util.List; import org.bukkit.Bukkit; import org.bukkit.damage.DamageSource; import org.bukkit.damage.DamageType; import org.bukkit.entity.LivingEntity; import org.bukkit.event.Event; import org.bukkit.event.entity.EntityDeathEvent; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; public class AsyncEntityDeathEventImpl extends EntityDeathEvent implements AsyncEntityDeathEvent { private static Field asyncField; static { try { asyncField = ReflectionUtils.getFieldByPositionAndType(Event.class, 0, boolean.class); } catch (IllegalStateException e) { e.printStackTrace(); } } public AsyncEntityDeathEventImpl(@NotNull LivingEntity what, @NotNull List<ItemStack> drops, int droppedExp) { super(what, DamageSource.builder(DamageType.GENERIC_KILL).build(), drops, droppedExp); try { asyncField.set(this, !Bukkit.isPrimaryThread()); } catch (IllegalAccessException e) { e.printStackTrace(); } } }
0
0.812987
1
0.812987
game-dev
MEDIA
0.912497
game-dev
0.766494
1
0.766494
Dimbreath/AzurLaneData
2,248
zh-TW/view/snapshot/swichskinmediator.lua
slot0 = class("SwichSkinMediator", import("..base.ContextMediator")) slot0.CHANGE_SKIN = "SwichSkinMediator:CHANGE_SKIN" slot0.BUY_ITEM = "SwichSkinMediator:BUY_ITEM" slot0.UPDATE_SKINCONFIG = "SwichSkinMediator:UPDATE_SKINCONFIG" slot0.BUY_ITEM_BY_ACT = "SwichSkinMediator:BUY_ITEM_BY_ACT" function slot0.register(slot0) slot0.shipVO = slot0.contextData.shipVO if slot0.shipVO then slot0.viewComponent:setShip(slot0.shipVO) slot0.viewComponent:setSkinList(getProxy(ShipSkinProxy):getSkinList()) end slot0:bind(uv0.BUY_ITEM_BY_ACT, function (slot0, slot1, slot2) uv0:sendNotification(GAME.SKIN_COUPON_SHOPPING, { shopId = slot1, cnt = slot2 }) end) slot0:bind(uv0.CHANGE_SKIN, function (slot0, slot1, slot2) uv0:sendNotification(GAME.SET_SHIP_SKIN, { shipId = slot1, skinId = slot2 }) end) slot0:bind(uv0.BUY_ITEM, function (slot0, slot1, slot2) uv0:sendNotification(GAME.SHOPPING, { id = slot1, count = slot2 }) end) slot0:bind(uv0.UPDATE_SKINCONFIG, function (slot0, slot1) uv0:sendNotification(GAME.UPDATE_SKINCONFIG, { skinId = slot1 }) end) end function slot0.listNotificationInterests(slot0) return { ShipSkinProxy.SHIP_SKINS_UPDATE, GAME.SHOPPING_DONE, GAME.SKIN_COUPON_SHOPPING_DONE, BayProxy.SHIP_UPDATED } end function slot0.handleNotification(slot0, slot1) slot3 = slot1:getBody() if slot1:getName() == GAME.SHOPPING_DONE or slot2 == GAME.SKIN_COUPON_SHOPPING_DONE then if slot3.awards and #slot3.awards > 0 then slot0.viewComponent:emit(BaseUI.ON_AWARD, { items = slot3.awards }) end if pg.shop_template[slot3.id] and slot4.genre == ShopArgs.SkinShop then slot0:addSubLayers(Context.New({ mediator = NewSkinMediator, viewComponent = NewSkinLayer, data = { skinId = slot4.effect_args[1] } })) end elseif slot2 == ShipSkinProxy.SHIP_SKINS_UPDATE then slot0.viewComponent:setSkinList(getProxy(ShipSkinProxy):getSkinList()) slot0.viewComponent:openSelectSkinPanel() elseif slot2 == BayProxy.SHIP_UPDATED and slot3.id == slot0.shipVO.id then slot0.viewComponent:setShip(slot3) slot0.viewComponent:setSkinList(getProxy(ShipSkinProxy):getSkinList()) slot0.viewComponent:openSelectSkinPanel() end end return slot0
0
0.567817
1
0.567817
game-dev
MEDIA
0.897954
game-dev
0.852937
1
0.852937
cmangos/mangos-wotlk
5,601
src/game/AI/ScriptDevAI/scripts/northrend/naxxramas/boss_anubrekhan.cpp
/* This file is part of the ScriptDev2 Project. See AUTHORS file for Copyright information * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* ScriptData SDName: Boss_Anubrekhan SD%Complete: 95 SDComment: Intro text usage is not very clear. Requires additional research. SDCategory: Naxxramas EndScriptData */ #include "AI/ScriptDevAI/base/BossAI.h" #include "AI/ScriptDevAI/include/sc_common.h" #include "naxxramas.h" enum { SAY_GREET = 13004, SAY_AGGRO1 = 13000, SAY_AGGRO2 = 13002, SAY_AGGRO3 = 13003, SAY_TAUNT1 = 13006, SAY_TAUNT2 = 13007, SAY_TAUNT3 = 13008, SAY_TAUNT4 = 13009, SAY_SLAY = 13005, EMOTE_CRYPT_GUARD = 29887, EMOTE_INSECT_SWARM = 13443, EMOTE_CORPSE_SCARABS = 32796, SPELL_DOUBLE_ATTACK = 18943, SPELL_IMPALE = 28783, // May be wrong spell id. Causes more dmg than I expect SPELL_IMPALE_H = 56090, SPELL_LOCUSTSWARM = 28785, // This is a self buff that triggers the dmg debuff SPELL_LOCUSTSWARM_H = 54021, SPELL_SUMMON_GUARD = 29508, // Summons 1 crypt guard at targeted location SPELL_SUMMON_CORPSE_SCARABS_5 = 29105, // This spawns 5 corpse scarabs ontop of us (most likely the pPlayer casts this on death) SPELL_SUMMON_CORPSE_SCARABS_10 = 28864, // This is used by the crypt guards when they die // NPC_CRYPT_GUARD = 16573, SPELLSET_10N = 1595601, SPELLSET_25N = 2924901, }; enum AnubRekhanActions { ANUBREKHAN_ACTIONS_MAX, ANUBREKHAN_SUMMON, }; struct boss_anubrekhanAI : public BossAI { boss_anubrekhanAI(Creature* creature) : BossAI(creature, ANUBREKHAN_ACTIONS_MAX), m_instance(static_cast<instance_naxxramas*>(creature->GetInstanceData())), m_isRegularMode(creature->GetMap()->IsRegularDifficulty()), m_hasTaunted(false) { SetDataType(TYPE_ANUB_REKHAN); AddOnAggroText(SAY_AGGRO1, SAY_AGGRO2, SAY_AGGRO3); AddOnKillText(SAY_SLAY); AddCustomAction(ANUBREKHAN_SUMMON, true, [&]() { DoCastSpellIfCan(nullptr, SPELL_SUMMON_GUARD); }); } instance_naxxramas* m_instance; bool m_isRegularMode; bool m_hasTaunted; void Reset() override { BossAI::Reset(); m_creature->SetSpellList(m_isRegularMode ? SPELLSET_10N : SPELLSET_25N); DoCastSpellIfCan(nullptr, SPELL_DOUBLE_ATTACK, CAST_TRIGGERED | CAST_AURA_NOT_PRESENT); } void Aggro(Unit *who) override { BossAI::Aggro(who); if (m_isRegularMode) ResetTimer(ANUBREKHAN_SUMMON, 20s); } void KilledUnit(Unit* victim) override { BossAI::KilledUnit(victim); if (!victim) return; // Force the player to spawn corpse scarabs via spell if (victim->IsPlayer()) victim->CastSpell(nullptr, SPELL_SUMMON_CORPSE_SCARABS_5, TRIGGERED_OLD_TRIGGERED, nullptr, nullptr, m_creature->GetObjectGuid()); } void MoveInLineOfSight(Unit* who) override { if (!m_hasTaunted && who->GetTypeId() == TYPEID_PLAYER && m_creature->IsWithinDistInMap(who, 110.0f) && m_creature->IsWithinLOSInMap(who)) { switch (urand(0,4)) { case 0: DoBroadcastText(SAY_GREET, m_creature); break; case 1: DoBroadcastText(SAY_TAUNT1, m_creature); break; case 2: DoBroadcastText(SAY_TAUNT2, m_creature); break; case 3: DoBroadcastText(SAY_TAUNT3, m_creature); break; case 4: DoBroadcastText(SAY_TAUNT4, m_creature); break; } m_hasTaunted = true; } ScriptedAI::MoveInLineOfSight(who); } void JustSummoned(Creature* summoned) override { if (summoned->GetEntry() == NPC_CRYPT_GUARD) DoBroadcastText(EMOTE_CRYPT_GUARD, summoned); summoned->AI()->AttackClosestEnemy(); } void SummonedCreatureDespawn(Creature* summoned) override { // If creature despawns on out of combat, skip this if (!m_creature->IsInCombat()) return; if (summoned && summoned->GetEntry() == NPC_CRYPT_GUARD) { summoned->CastSpell(summoned, SPELL_SUMMON_CORPSE_SCARABS_10, TRIGGERED_OLD_TRIGGERED, nullptr, nullptr, m_creature->GetObjectGuid()); DoBroadcastText(EMOTE_CORPSE_SCARABS, summoned); } } }; void AddSC_boss_anubrekhan() { Script* pNewScript = new Script; pNewScript->Name = "boss_anubrekhan"; pNewScript->GetAI = &GetNewAIInstance<boss_anubrekhanAI>; pNewScript->RegisterSelf(); }
0
0.951858
1
0.951858
game-dev
MEDIA
0.988638
game-dev
0.991491
1
0.991491
Courseplay/courseplay
3,445
CpObject.lua
--[[ This file is part of Courseplay (https://github.com/Courseplay/courseplay) Copyright (C) 2018 Peter Vajko This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] -- Class implementation stolen from http://lua-users.org/wiki/SimpleLuaClasses function CpObject(base, init) local c = {} -- a new class instance if not init and type(base) == 'function' then init = base base = nil elseif type(base) == 'table' then -- our new class is a shallow copy of the base class! for i,v in pairs(base) do c[i] = v end c._base = base end -- the class will be the metatable for all its objects, -- and they will look up their methods in it. c.__index = c -- expose a constructor which can be called by <classname>(<args>) local mt = {} mt.__call = function(class_tbl, ...) local obj = {} setmetatable(obj,c) if class_tbl.init then class_tbl.init(obj,...) else -- make sure that any stuff from the base class is initialized! if base and base.init then base.init(obj, ...) end end return obj end c.init = init c.is_a = function(self, klass) local m = getmetatable(self) while m do if m == klass then return true end m = m._base end return false end setmetatable(c, mt) return c end --- Object with a time to live. ---@class CpTemporaryObject CpTemporaryObject = CpObject() function CpTemporaryObject:init(valueWhenExpired) self.valueWhenExpired = valueWhenExpired self.value = self.valueWhenExpired self.expiryTime = g_time end --- Set temporary value for object ---@value anything the temporary value ---@ttlMs Time To Live, for ttlMs milliseconds, CpTemporaryObject:get() will --- return this value, otherwise valueWhenExpired function CpTemporaryObject:set(value, ttlMs) self.value = value self.expiryTime = g_time + ttlMs end --- Get the value of the temporary object --- If expired, returns the default value function CpTemporaryObject:get() if g_time > self.expiryTime then -- value expired, reset it self.value = self.valueWhenExpired end return self.value end --- Object slowly adjusting its value ---@class CpSlowChangingObject CpSlowChangingObject = CpObject() function CpSlowChangingObject:init(targetValue, timeToReachTargetMs) self.value = targetValue self:set(targetValue, timeToReachTargetMs) end function CpSlowChangingObject:set(targetValue, timeToReachTargetMs) self.previousValue = self.value self.targetValue = targetValue self.targetValueMs = g_time self.timeToReachTargetMs = timeToReachTargetMs or 1 end function CpSlowChangingObject:get() local age = g_time - self.targetValueMs if age < self.timeToReachTargetMs then -- not reaped yet, return a value proportional to the time until ripe self.value = self.previousValue + (self.targetValue - self.previousValue) * age / self.timeToReachTargetMs else self.value = self.targetValue end return self.value end
0
0.857118
1
0.857118
game-dev
MEDIA
0.398371
game-dev
0.887757
1
0.887757
Eaglercraft-Archive/EaglercraftX-1.8-workspace
2,649
src/game/java/net/minecraft/block/state/pattern/BlockStateHelper.java
package net.minecraft.block.state.pattern; import java.util.Map; import java.util.Map.Entry; import com.google.common.base.Predicate; import com.google.common.collect.Maps; import net.minecraft.block.Block; import net.minecraft.block.properties.IProperty; import net.minecraft.block.state.BlockState; import net.minecraft.block.state.IBlockState; /**+ * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. * * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * * EaglercraftX 1.8 patch files (c) 2022-2025 lax1dude, ayunami2000. All Rights Reserved. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class BlockStateHelper implements Predicate<IBlockState> { private final BlockState blockstate; private final Map<IProperty, Predicate> propertyPredicates = Maps.newHashMap(); private BlockStateHelper(BlockState blockStateIn) { this.blockstate = blockStateIn; } public static BlockStateHelper forBlock(Block blockIn) { return new BlockStateHelper(blockIn.getBlockState()); } public boolean apply(IBlockState iblockstate) { if (iblockstate != null && iblockstate.getBlock().equals(this.blockstate.getBlock())) { for (Entry entry : this.propertyPredicates.entrySet()) { Comparable comparable = iblockstate.getValue((IProperty) entry.getKey()); if (!((Predicate) entry.getValue()).apply(comparable)) { return false; } } return true; } else { return false; } } public <V extends Comparable<V>> BlockStateHelper where(IProperty<V> property, Predicate<? extends V> is) { if (!this.blockstate.getProperties().contains(property)) { throw new IllegalArgumentException(this.blockstate + " cannot support property " + property); } else { this.propertyPredicates.put(property, is); return this; } } }
0
0.736928
1
0.736928
game-dev
MEDIA
0.992655
game-dev
0.919049
1
0.919049
mastercomfig/tf2-patches-old
3,165
src/gameui/OptionsSubMultiplayer.h
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ //=============================================================================// #ifndef OPTIONSSUBMULTIPLAYER_H #define OPTIONSSUBMULTIPLAYER_H #ifdef _WIN32 #pragma once #endif #include <vgui_controls/PropertyPage.h> #include <vgui_controls/ImagePanel.h> #include "imageutils.h" class CLabeledCommandComboBox; class CBitmapImagePanel; class CCvarToggleCheckButton; class CCvarTextEntry; class CCvarSlider; class CMultiplayerAdvancedDialog; class COptionsSubMultiplayer; class CrosshairImagePanelBase : public vgui::ImagePanel { DECLARE_CLASS_SIMPLE( CrosshairImagePanelBase, vgui::ImagePanel ); public: CrosshairImagePanelBase( Panel *parent, const char *name ) : BaseClass(parent, name) {} virtual void ResetData() {} virtual void ApplyChanges() {} virtual void UpdateVisibility() {} }; //----------------------------------------------------------------------------- // Purpose: multiplayer options property page //----------------------------------------------------------------------------- class COptionsSubMultiplayer : public vgui::PropertyPage { DECLARE_CLASS_SIMPLE( COptionsSubMultiplayer, vgui::PropertyPage ); public: COptionsSubMultiplayer(vgui::Panel *parent); ~COptionsSubMultiplayer(); virtual vgui::Panel *CreateControlByName(const char *controlName); MESSAGE_FUNC( OnControlModified, "ControlModified" ); protected: // Called when page is loaded. Data should be reloaded from document into controls. virtual void OnResetData(); // Called when the OK / Apply button is pressed. Changed data should be written into document. virtual void OnApplyChanges(); virtual void OnCommand( const char *command ); private: void InitModelList(CLabeledCommandComboBox *cb); void InitLogoList(CLabeledCommandComboBox *cb); void RemapModel(); void RemapLogo(); void ConversionError( ConversionErrorType nError ); MESSAGE_FUNC_PTR( OnTextChanged, "TextChanged", panel ); MESSAGE_FUNC_CHARPTR( OnFileSelected, "FileSelected", fullpath ); void ColorForName(char const *pszColorName, int &r, int &g, int &b); CBitmapImagePanel *m_pModelImage; CLabeledCommandComboBox *m_pModelList; char m_ModelName[128]; vgui::ImagePanel *m_pLogoImage; CLabeledCommandComboBox *m_pLogoList; char m_LogoName[128]; CCvarSlider *m_pPrimaryColorSlider; CCvarSlider *m_pSecondaryColorSlider; CCvarToggleCheckButton *m_pHighQualityModelCheckBox; // Mod specific general checkboxes vgui::Dar< CCvarToggleCheckButton * > m_cvarToggleCheckButtons; CCvarToggleCheckButton *m_pLockRadarRotationCheckbox; CrosshairImagePanelBase *m_pCrosshairImage; // --- client download filter vgui::ComboBox *m_pDownloadFilterCombo; // Begin Spray Import Functions ConversionErrorType WriteSprayVMT(const char *vtfPath); void SelectLogo(const char *logoName); // End Spray Import Functions int m_nLogoR; int m_nLogoG; int m_nLogoB; #ifndef _XBOX vgui::DHANDLE<CMultiplayerAdvancedDialog> m_hMultiplayerAdvancedDialog; #endif vgui::FileOpenDialog *m_hImportSprayDialog; }; #endif // OPTIONSSUBMULTIPLAYER_H
0
0.917894
1
0.917894
game-dev
MEDIA
0.579227
game-dev,desktop-app
0.61444
1
0.61444
disruptorbeam/trilleon
17,183
client/Library/PackageCache/com.unity.textmeshpro@3.0.1/Scripts/Runtime/TMP_DefaultControls.cs
using UnityEngine; using System.Collections; using UnityEngine.UI; #if UNITY_EDITOR using UnityEditor; #endif namespace TMPro { public static class TMP_DefaultControls { public struct Resources { public Sprite standard; public Sprite background; public Sprite inputField; public Sprite knob; public Sprite checkmark; public Sprite dropdown; public Sprite mask; } private const float kWidth = 160f; private const float kThickHeight = 30f; private const float kThinHeight = 20f; private static Vector2 s_TextElementSize = new Vector2(100f, 100f); private static Vector2 s_ThickElementSize = new Vector2(kWidth, kThickHeight); private static Vector2 s_ThinElementSize = new Vector2(kWidth, kThinHeight); //private static Vector2 s_ImageElementSize = new Vector2(100f, 100f); private static Color s_DefaultSelectableColor = new Color(1f, 1f, 1f, 1f); //private static Color s_PanelColor = new Color(1f, 1f, 1f, 0.392f); private static Color s_TextColor = new Color(50f / 255f, 50f / 255f, 50f / 255f, 1f); private static GameObject CreateUIElementRoot(string name, Vector2 size) { GameObject child = new GameObject(name); RectTransform rectTransform = child.AddComponent<RectTransform>(); rectTransform.sizeDelta = size; return child; } static GameObject CreateUIObject(string name, GameObject parent) { GameObject go = new GameObject(name); go.AddComponent<RectTransform>(); SetParentAndAlign(go, parent); return go; } private static void SetDefaultTextValues(TMP_Text lbl) { // Set text values we want across UI elements in default controls. // Don't set values which are the same as the default values for the Text component, // since there's no point in that, and it's good to keep them as consistent as possible. lbl.color = s_TextColor; lbl.fontSize = 14; } private static void SetDefaultColorTransitionValues(Selectable slider) { ColorBlock colors = slider.colors; colors.highlightedColor = new Color(0.882f, 0.882f, 0.882f); colors.pressedColor = new Color(0.698f, 0.698f, 0.698f); colors.disabledColor = new Color(0.521f, 0.521f, 0.521f); } private static void SetParentAndAlign(GameObject child, GameObject parent) { if (parent == null) return; child.transform.SetParent(parent.transform, false); SetLayerRecursively(child, parent.layer); } private static void SetLayerRecursively(GameObject go, int layer) { go.layer = layer; Transform t = go.transform; for (int i = 0; i < t.childCount; i++) SetLayerRecursively(t.GetChild(i).gameObject, layer); } // Actual controls public static GameObject CreateScrollbar(Resources resources) { // Create GOs Hierarchy GameObject scrollbarRoot = CreateUIElementRoot("Scrollbar", s_ThinElementSize); GameObject sliderArea = CreateUIObject("Sliding Area", scrollbarRoot); GameObject handle = CreateUIObject("Handle", sliderArea); Image bgImage = scrollbarRoot.AddComponent<Image>(); bgImage.sprite = resources.background; bgImage.type = Image.Type.Sliced; bgImage.color = s_DefaultSelectableColor; Image handleImage = handle.AddComponent<Image>(); handleImage.sprite = resources.standard; handleImage.type = Image.Type.Sliced; handleImage.color = s_DefaultSelectableColor; RectTransform sliderAreaRect = sliderArea.GetComponent<RectTransform>(); sliderAreaRect.sizeDelta = new Vector2(-20, -20); sliderAreaRect.anchorMin = Vector2.zero; sliderAreaRect.anchorMax = Vector2.one; RectTransform handleRect = handle.GetComponent<RectTransform>(); handleRect.sizeDelta = new Vector2(20, 20); Scrollbar scrollbar = scrollbarRoot.AddComponent<Scrollbar>(); scrollbar.handleRect = handleRect; scrollbar.targetGraphic = handleImage; SetDefaultColorTransitionValues(scrollbar); return scrollbarRoot; } public static GameObject CreateButton(Resources resources) { GameObject buttonRoot = CreateUIElementRoot("Button", s_ThickElementSize); GameObject childText = new GameObject("Text (TMP)"); childText.AddComponent<RectTransform>(); SetParentAndAlign(childText, buttonRoot); Image image = buttonRoot.AddComponent<Image>(); image.sprite = resources.standard; image.type = Image.Type.Sliced; image.color = s_DefaultSelectableColor; Button bt = buttonRoot.AddComponent<Button>(); SetDefaultColorTransitionValues(bt); TextMeshProUGUI text = childText.AddComponent<TextMeshProUGUI>(); text.text = "Button"; text.alignment = TextAlignmentOptions.Center; SetDefaultTextValues(text); RectTransform textRectTransform = childText.GetComponent<RectTransform>(); textRectTransform.anchorMin = Vector2.zero; textRectTransform.anchorMax = Vector2.one; textRectTransform.sizeDelta = Vector2.zero; return buttonRoot; } public static GameObject CreateText(Resources resources) { GameObject go = null; #if UNITY_EDITOR go = ObjectFactory.CreateGameObject("Text (TMP)"); #else go = CreateUIElementRoot("Text (TMP)", s_TextElementSize); #endif TextMeshProUGUI textComponent = null; #if UNITY_EDITOR textComponent = ObjectFactory.AddComponent<TextMeshProUGUI>(go); #else textComponent = go.AddComponent<TextMeshProUGUI>(); #endif return go; } public static GameObject CreateInputField(Resources resources) { GameObject root = CreateUIElementRoot("InputField (TMP)", s_ThickElementSize); GameObject textArea = CreateUIObject("Text Area", root); GameObject childPlaceholder = CreateUIObject("Placeholder", textArea); GameObject childText = CreateUIObject("Text", textArea); Image image = root.AddComponent<Image>(); image.sprite = resources.inputField; image.type = Image.Type.Sliced; image.color = s_DefaultSelectableColor; TMP_InputField inputField = root.AddComponent<TMP_InputField>(); SetDefaultColorTransitionValues(inputField); // Use UI.Mask for Unity 5.0 - 5.1 and 2D RectMask for Unity 5.2 and up RectMask2D rectMask = textArea.AddComponent<RectMask2D>(); rectMask.padding = new Vector4(-8, -5, -8, -5); RectTransform textAreaRectTransform = textArea.GetComponent<RectTransform>(); textAreaRectTransform.anchorMin = Vector2.zero; textAreaRectTransform.anchorMax = Vector2.one; textAreaRectTransform.sizeDelta = Vector2.zero; textAreaRectTransform.offsetMin = new Vector2(10, 6); textAreaRectTransform.offsetMax = new Vector2(-10, -7); TextMeshProUGUI text = childText.AddComponent<TextMeshProUGUI>(); text.text = ""; text.enableWordWrapping = false; text.extraPadding = true; text.richText = true; SetDefaultTextValues(text); TextMeshProUGUI placeholder = childPlaceholder.AddComponent<TextMeshProUGUI>(); placeholder.text = "Enter text..."; placeholder.fontSize = 14; placeholder.fontStyle = FontStyles.Italic; placeholder.enableWordWrapping = false; placeholder.extraPadding = true; // Make placeholder color half as opaque as normal text color. Color placeholderColor = text.color; placeholderColor.a *= 0.5f; placeholder.color = placeholderColor; // Add Layout component to placeholder. placeholder.gameObject.AddComponent<LayoutElement>().ignoreLayout = true; RectTransform textRectTransform = childText.GetComponent<RectTransform>(); textRectTransform.anchorMin = Vector2.zero; textRectTransform.anchorMax = Vector2.one; textRectTransform.sizeDelta = Vector2.zero; textRectTransform.offsetMin = new Vector2(0, 0); textRectTransform.offsetMax = new Vector2(0, 0); RectTransform placeholderRectTransform = childPlaceholder.GetComponent<RectTransform>(); placeholderRectTransform.anchorMin = Vector2.zero; placeholderRectTransform.anchorMax = Vector2.one; placeholderRectTransform.sizeDelta = Vector2.zero; placeholderRectTransform.offsetMin = new Vector2(0, 0); placeholderRectTransform.offsetMax = new Vector2(0, 0); inputField.textViewport = textAreaRectTransform; inputField.textComponent = text; inputField.placeholder = placeholder; inputField.fontAsset = text.font; return root; } public static GameObject CreateDropdown(Resources resources) { GameObject root = CreateUIElementRoot("Dropdown", s_ThickElementSize); GameObject label = CreateUIObject("Label", root); GameObject arrow = CreateUIObject("Arrow", root); GameObject template = CreateUIObject("Template", root); GameObject viewport = CreateUIObject("Viewport", template); GameObject content = CreateUIObject("Content", viewport); GameObject item = CreateUIObject("Item", content); GameObject itemBackground = CreateUIObject("Item Background", item); GameObject itemCheckmark = CreateUIObject("Item Checkmark", item); GameObject itemLabel = CreateUIObject("Item Label", item); // Sub controls. GameObject scrollbar = CreateScrollbar(resources); scrollbar.name = "Scrollbar"; SetParentAndAlign(scrollbar, template); Scrollbar scrollbarScrollbar = scrollbar.GetComponent<Scrollbar>(); scrollbarScrollbar.SetDirection(Scrollbar.Direction.BottomToTop, true); RectTransform vScrollbarRT = scrollbar.GetComponent<RectTransform>(); vScrollbarRT.anchorMin = Vector2.right; vScrollbarRT.anchorMax = Vector2.one; vScrollbarRT.pivot = Vector2.one; vScrollbarRT.sizeDelta = new Vector2(vScrollbarRT.sizeDelta.x, 0); // Setup item UI components. TextMeshProUGUI itemLabelText = itemLabel.AddComponent<TextMeshProUGUI>(); SetDefaultTextValues(itemLabelText); itemLabelText.alignment = TextAlignmentOptions.Left; Image itemBackgroundImage = itemBackground.AddComponent<Image>(); itemBackgroundImage.color = new Color32(245, 245, 245, 255); Image itemCheckmarkImage = itemCheckmark.AddComponent<Image>(); itemCheckmarkImage.sprite = resources.checkmark; Toggle itemToggle = item.AddComponent<Toggle>(); itemToggle.targetGraphic = itemBackgroundImage; itemToggle.graphic = itemCheckmarkImage; itemToggle.isOn = true; // Setup template UI components. Image templateImage = template.AddComponent<Image>(); templateImage.sprite = resources.standard; templateImage.type = Image.Type.Sliced; ScrollRect templateScrollRect = template.AddComponent<ScrollRect>(); templateScrollRect.content = (RectTransform)content.transform; templateScrollRect.viewport = (RectTransform)viewport.transform; templateScrollRect.horizontal = false; templateScrollRect.movementType = ScrollRect.MovementType.Clamped; templateScrollRect.verticalScrollbar = scrollbarScrollbar; templateScrollRect.verticalScrollbarVisibility = ScrollRect.ScrollbarVisibility.AutoHideAndExpandViewport; templateScrollRect.verticalScrollbarSpacing = -3; Mask scrollRectMask = viewport.AddComponent<Mask>(); scrollRectMask.showMaskGraphic = false; Image viewportImage = viewport.AddComponent<Image>(); viewportImage.sprite = resources.mask; viewportImage.type = Image.Type.Sliced; // Setup dropdown UI components. TextMeshProUGUI labelText = label.AddComponent<TextMeshProUGUI>(); SetDefaultTextValues(labelText); labelText.alignment = TextAlignmentOptions.Left; Image arrowImage = arrow.AddComponent<Image>(); arrowImage.sprite = resources.dropdown; Image backgroundImage = root.AddComponent<Image>(); backgroundImage.sprite = resources.standard; backgroundImage.color = s_DefaultSelectableColor; backgroundImage.type = Image.Type.Sliced; TMP_Dropdown dropdown = root.AddComponent<TMP_Dropdown>(); dropdown.targetGraphic = backgroundImage; SetDefaultColorTransitionValues(dropdown); dropdown.template = template.GetComponent<RectTransform>(); dropdown.captionText = labelText; dropdown.itemText = itemLabelText; // Setting default Item list. itemLabelText.text = "Option A"; dropdown.options.Add(new TMP_Dropdown.OptionData {text = "Option A" }); dropdown.options.Add(new TMP_Dropdown.OptionData {text = "Option B" }); dropdown.options.Add(new TMP_Dropdown.OptionData {text = "Option C" }); dropdown.RefreshShownValue(); // Set up RectTransforms. RectTransform labelRT = label.GetComponent<RectTransform>(); labelRT.anchorMin = Vector2.zero; labelRT.anchorMax = Vector2.one; labelRT.offsetMin = new Vector2(10, 6); labelRT.offsetMax = new Vector2(-25, -7); RectTransform arrowRT = arrow.GetComponent<RectTransform>(); arrowRT.anchorMin = new Vector2(1, 0.5f); arrowRT.anchorMax = new Vector2(1, 0.5f); arrowRT.sizeDelta = new Vector2(20, 20); arrowRT.anchoredPosition = new Vector2(-15, 0); RectTransform templateRT = template.GetComponent<RectTransform>(); templateRT.anchorMin = new Vector2(0, 0); templateRT.anchorMax = new Vector2(1, 0); templateRT.pivot = new Vector2(0.5f, 1); templateRT.anchoredPosition = new Vector2(0, 2); templateRT.sizeDelta = new Vector2(0, 150); RectTransform viewportRT = viewport.GetComponent<RectTransform>(); viewportRT.anchorMin = new Vector2(0, 0); viewportRT.anchorMax = new Vector2(1, 1); viewportRT.sizeDelta = new Vector2(-18, 0); viewportRT.pivot = new Vector2(0, 1); RectTransform contentRT = content.GetComponent<RectTransform>(); contentRT.anchorMin = new Vector2(0f, 1); contentRT.anchorMax = new Vector2(1f, 1); contentRT.pivot = new Vector2(0.5f, 1); contentRT.anchoredPosition = new Vector2(0, 0); contentRT.sizeDelta = new Vector2(0, 28); RectTransform itemRT = item.GetComponent<RectTransform>(); itemRT.anchorMin = new Vector2(0, 0.5f); itemRT.anchorMax = new Vector2(1, 0.5f); itemRT.sizeDelta = new Vector2(0, 20); RectTransform itemBackgroundRT = itemBackground.GetComponent<RectTransform>(); itemBackgroundRT.anchorMin = Vector2.zero; itemBackgroundRT.anchorMax = Vector2.one; itemBackgroundRT.sizeDelta = Vector2.zero; RectTransform itemCheckmarkRT = itemCheckmark.GetComponent<RectTransform>(); itemCheckmarkRT.anchorMin = new Vector2(0, 0.5f); itemCheckmarkRT.anchorMax = new Vector2(0, 0.5f); itemCheckmarkRT.sizeDelta = new Vector2(20, 20); itemCheckmarkRT.anchoredPosition = new Vector2(10, 0); RectTransform itemLabelRT = itemLabel.GetComponent<RectTransform>(); itemLabelRT.anchorMin = Vector2.zero; itemLabelRT.anchorMax = Vector2.one; itemLabelRT.offsetMin = new Vector2(20, 1); itemLabelRT.offsetMax = new Vector2(-10, -2); template.SetActive(false); return root; } } }
0
0.92311
1
0.92311
game-dev
MEDIA
0.915764
game-dev
0.988643
1
0.988643
pret/pokeplatinum
17,390
src/unk_0207A6DC.c
#include "unk_0207A6DC.h" #include <nitro.h> #include <string.h> #include "constants/battle.h" #include "struct_decls/battle_system.h" #include "struct_defs/chatot_cry.h" #include "struct_defs/struct_02039A58.h" #include "struct_defs/struct_0207A778.h" #include "struct_defs/struct_0207A81C.h" #include "struct_defs/struct_0207ACB4.h" #include "struct_defs/struct_0207AD40.h" #include "struct_defs/trainer.h" #include "battle/battle_io.h" #include "battle/ov16_0223DF00.h" #include "charcode_util.h" #include "communication_system.h" #include "heap.h" #include "pal_pad.h" #include "party.h" #include "sys_task.h" #include "sys_task_manager.h" #include "trainer_info.h" #include "unk_0202CC64.h" #include "unk_0202F1D4.h" #include "unk_02032798.h" #include "unk_020363E8.h" void sub_0207A81C(BattleSystem *battleSys, int param1, int param2, void *param3, u8 param4); BOOL sub_0207A8F4(UnkStruct_0207A778 *param0, u32 param1); BOOL sub_0207A960(UnkStruct_0207A778 *param0); BOOL sub_0207A988(UnkStruct_0207A778 *param0); BOOL sub_0207A9CC(UnkStruct_0207A778 *param0); BOOL sub_0207A9F8(UnkStruct_0207A778 *param0); BOOL sub_0207AA38(UnkStruct_0207A778 *param0); BOOL sub_0207AA5C(UnkStruct_0207A778 *param0); BOOL sub_0207AAA0(UnkStruct_0207A778 *param0); BOOL sub_0207AAC8(UnkStruct_0207A778 *param0); BOOL sub_0207AB9C(UnkStruct_0207A778 *param0, int param1); BOOL sub_0207ABD0(UnkStruct_0207A778 *param0, int param1, int param2); BOOL sub_0207AC28(UnkStruct_0207A778 *param0, int param1); BOOL sub_0207AC54(UnkStruct_0207A778 *param0, int param1, int param2); void sub_0207A744(void *param0); BOOL sub_0207AB58(UnkStruct_0207A778 *param0); BOOL sub_0207AAFC(UnkStruct_0207A778 *param0); static int sub_0207A758(void); static int sub_0207A75C(void); static int sub_0207A764(void); static int sub_0207A76C(void); static int sub_0207A774(void); static int sub_0207AE64(void); static u8 *sub_0207A778(int param0, void *param1, int param2); static u8 *sub_0207A798(int param0, void *param1, int param2); static u8 *sub_0207A7B8(int param0, void *param1, int param2); static u8 *sub_0207A7D4(int param0, void *param1, int param2); static u8 *sub_0207A7F4(int param0, void *param1, int param2); static u8 *sub_0207A7FC(int param0, void *param1, int param2); static u8 *sub_0207A804(int param0, void *param1, int param2); static u8 *sub_0207A80C(int param0, void *param1, int param2); static u8 *sub_0207A814(int param0, void *param1, int param2); static void sub_0207A8A8(int param0, int param1, void *param2, void *param3); static void sub_0207A934(int param0, int param1, void *param2, void *param3); static void sub_0207A9BC(int param0, int param1, void *param2, void *param3); static void sub_0207AA28(int param0, int param1, void *param2, void *param3); static void sub_0207AA90(int param0, int param1, void *param2, void *param3); static void sub_0207AB8C(int param0, int param1, void *param2, void *param3); static void sub_0207AC18(int param0, int param1, void *param2, void *param3); static void sub_0207ACA4(int param0, int param1, void *param2, void *param3); static void sub_0207ADB4(int param0, int param1, void *param2, void *param3); static void sub_0207ACB4(SysTask *param0, void *param1); static void sub_0207AD40(SysTask *param0, void *param1); static void sub_0207AE34(int param0, int param1, void *param2, void *param3); static void PalPad_CreateNetworkObject(TrainerInfo *param0, PalPad *param1, PalPad *param2); static const CommCmdTable Unk_020F099C[] = { { sub_0207ADB4, sub_02032944, NULL }, { sub_0207A8A8, sub_02032944, NULL }, { sub_0207A934, sub_0207A758, NULL }, { sub_0207A9BC, sub_0207A75C, sub_0207A778 }, { sub_0207AA28, sub_0207A774, sub_0207A798 }, { sub_0207AA90, sub_0207A764, sub_0207A7B8 }, { sub_0207AB8C, sub_0207A76C, sub_0207A7D4 }, { sub_0207AC18, sub_0207A774, sub_0207A7F4 }, { sub_0207AC18, sub_0207A774, sub_0207A7FC }, { sub_0207ACA4, sub_0207A764, sub_0207A804 }, { sub_0207ACA4, sub_0207A764, sub_0207A80C }, { sub_0207AE34, sub_0207AE64, sub_0207A814 } }; void sub_0207A6DC(void *param0) { int v0 = sizeof(Unk_020F099C) / sizeof(CommCmdTable); BattleSystem *v1; UnkStruct_0207ACB4 *v2; UnkStruct_0207AD40 *v3; v1 = (BattleSystem *)param0; if (BattleSystem_BattleStatus(v1) & 0x10) { return; } v2 = (UnkStruct_0207ACB4 *)Heap_Alloc(HEAP_ID_BATTLE, sizeof(UnkStruct_0207ACB4)); v3 = (UnkStruct_0207AD40 *)Heap_Alloc(HEAP_ID_BATTLE, sizeof(UnkStruct_0207AD40)); CommCmd_Init(Unk_020F099C, v0, param0); v2->unk_00 = v1; v2->unk_04 = 0; v3->unk_00 = v1; v3->unk_04 = 0; ov16_0223F320(v1, &v2->unk_04); ov16_0223F32C(v1, &v3->unk_04); SysTask_Start(sub_0207ACB4, v2, 0); SysTask_Start(sub_0207AD40, v3, 0); } void sub_0207A744(void *param0) { int v0 = sizeof(Unk_020F099C) / sizeof(CommCmdTable); CommCmd_Init(Unk_020F099C, v0, param0); } static int sub_0207A758(void) { return 4; } static int sub_0207A75C(void) { return TrainerInfo_Size(); } static int sub_0207A764(void) { return Party_SaveSize(); } static int sub_0207A76C(void) { return 1000; } static int sub_0207A774(void) { return sizeof(Trainer); } static u8 *sub_0207A778(int param0, void *param1, int param2) { UnkStruct_0207A778 *v0 = param1; if (v0->unk_00->battleType & BATTLE_TYPE_FRONTIER) { return (u8 *)v0->unk_00->trainerInfo[param0 * 2]; } else { return (u8 *)v0->unk_00->trainerInfo[param0]; } } static u8 *sub_0207A798(int param0, void *param1, int param2) { UnkStruct_0207A778 *v0 = param1; if (v0->unk_00->battleType & BATTLE_TYPE_FRONTIER) { return (u8 *)&v0->unk_00->trainer[param0 * 2]; } else { return (u8 *)&v0->unk_00->trainer[param0]; } } static u8 *sub_0207A7B8(int param0, void *param1, int param2) { UnkStruct_0207A778 *v0 = param1; if (v0->unk_00->battleType & BATTLE_TYPE_FRONTIER) { return (u8 *)v0->unk_00->parties[param0 * 2]; } else { return (u8 *)v0->unk_00->parties[param0]; } } static u8 *sub_0207A7D4(int param0, void *param1, int param2) { UnkStruct_0207A778 *v0 = param1; if (v0->unk_00->battleType & BATTLE_TYPE_FRONTIER) { return (u8 *)v0->unk_00->chatotCries[param0 * 2]; } else { return (u8 *)v0->unk_00->chatotCries[param0]; } } static u8 *sub_0207A7F4(int param0, void *param1, int param2) { UnkStruct_0207A778 *v0 = param1; return (u8 *)&v0->unk_00->trainer[1]; } static u8 *sub_0207A7FC(int param0, void *param1, int param2) { UnkStruct_0207A778 *v0 = param1; return (u8 *)&v0->unk_00->trainer[3]; } static u8 *sub_0207A804(int param0, void *param1, int param2) { UnkStruct_0207A778 *v0 = param1; return (u8 *)v0->unk_00->parties[1]; } static u8 *sub_0207A80C(int param0, void *param1, int param2) { UnkStruct_0207A778 *v0 = param1; return (u8 *)v0->unk_00->parties[3]; } static u8 *sub_0207A814(int param0, void *param1, int param2) { UnkStruct_0207A778 *v0 = param1; return (u8 *)v0->unk_10[param0]; } void sub_0207A81C(BattleSystem *battleSys, int param1, int param2, void *param3, u8 param4) { int v0; UnkStruct_0207A81C *v1; u8 *v2; u8 *v3; u16 *v4; u16 *v5; v1 = (UnkStruct_0207A81C *)Heap_Alloc(HEAP_ID_BATTLE, sizeof(UnkStruct_0207A81C)); v3 = ov16_0223E06C(battleSys); v4 = ov16_0223E08C(battleSys); v5 = ov16_0223E098(battleSys); if (v4[0] + sizeof(UnkStruct_0207A81C) + param4 + 1 > 0x1000) { v5[0] = v4[0]; v4[0] = 0; } v1->unk_00 = param1; v1->unk_01 = param2; v1->unk_02 = param4; v2 = (u8 *)v1; for (v0 = 0; v0 < sizeof(UnkStruct_0207A81C); v0++) { v3[v4[0]] = v2[v0]; v4[0]++; } v2 = (u8 *)param3; for (v0 = 0; v0 < param4; v0++) { v3[v4[0]] = v2[v0]; v4[0]++; } Heap_Free(v1); } static void sub_0207A8A8(int param0, int param1, void *param2, void *param3) { BattleSystem *v0 = (BattleSystem *)param3; int v1; u8 *v2 = (u8 *)param2; u8 *v3 = ov16_0223E074(v0); u16 *v4 = ov16_0223E0B0(v0); u16 *v5 = ov16_0223E0BC(v0); if (v4[0] + param1 + 1 > 0x1000) { v5[0] = v4[0]; v4[0] = 0; } for (v1 = 0; v1 < param1; v1++) { v3[v4[0]] = v2[v1]; v4[0]++; } } BOOL sub_0207A8F4(UnkStruct_0207A778 *param0, u32 param1) { Party *v0; if (CommSys_SendRingRemainingSize() != 264) { return 0; } if (CommTiming_IsSyncState(51) == 0) { return 0; } return CommSys_SendData(24, (void *)&param1, 4); } static void sub_0207A934(int param0, int param1, void *param2, void *param3) { UnkStruct_0207A778 *v0 = (UnkStruct_0207A778 *)param3; v0->unk_00->systemVersion[param0] = *((u32 *)param2); sub_0202FAA8(param0, v0->unk_00->systemVersion[param0]); v0->unk_1020++; } BOOL sub_0207A960(UnkStruct_0207A778 *param0) { TrainerInfo *v0; if (CommSys_SendRingRemainingSize() != 264) { return 0; } v0 = (TrainerInfo *)&param0->unk_20[0]; TrainerInfo_Copy(param0->unk_00->trainerInfo[0], v0); return 1; } BOOL sub_0207A988(UnkStruct_0207A778 *param0) { if (CommSys_SendRingRemainingSize() != 264) { return 0; } if (CommTiming_IsSyncState(52) == 0) { return 0; } return CommSys_SendDataHuge(25, (void *)&param0->unk_20[0], TrainerInfo_Size()); } static void sub_0207A9BC(int param0, int param1, void *param2, void *param3) { UnkStruct_0207A778 *v0 = (UnkStruct_0207A778 *)param3; v0->unk_1020++; } BOOL sub_0207A9CC(UnkStruct_0207A778 *param0) { Trainer *v0; if (CommSys_SendRingRemainingSize() != 264) { return 0; } v0 = (Trainer *)&param0->unk_20[0]; *v0 = param0->unk_00->trainer[0]; return 1; } BOOL sub_0207A9F8(UnkStruct_0207A778 *param0) { if (CommSys_SendRingRemainingSize() != 264) { return 0; } if (CommTiming_IsSyncState(53) == 0) { return 0; } return CommSys_SendDataHuge(26, (void *)&param0->unk_20[0], sizeof(Trainer)); } static void sub_0207AA28(int param0, int param1, void *param2, void *param3) { UnkStruct_0207A778 *v0 = (UnkStruct_0207A778 *)param3; v0->unk_1020++; } BOOL sub_0207AA38(UnkStruct_0207A778 *param0) { Party *v0; if (CommSys_SendRingRemainingSize() != 264) { return 0; } v0 = (Party *)&param0->unk_20[0]; Party_Copy(param0->unk_00->parties[0], v0); return 1; } BOOL sub_0207AA5C(UnkStruct_0207A778 *param0) { if (CommSys_SendRingRemainingSize() != 264) { return 0; } if (CommTiming_IsSyncState(54) == 0) { return 0; } return CommSys_SendDataHuge(27, (void *)&param0->unk_20[0], Party_SaveSize()); } static void sub_0207AA90(int param0, int param1, void *param2, void *param3) { UnkStruct_0207A778 *v0 = (UnkStruct_0207A778 *)param3; v0->unk_1020++; } BOOL sub_0207AAA0(UnkStruct_0207A778 *param0) { ChatotCry *v0; if (CommSys_SendRingRemainingSize() != 264) { return 0; } v0 = (ChatotCry *)&param0->unk_20[0]; CopyChatotCryData(v0, param0->unk_00->chatotCries[0]); return 1; } BOOL sub_0207AAC8(UnkStruct_0207A778 *param0) { if (CommSys_SendRingRemainingSize() != 264) { return 0; } if (CommTiming_IsSyncState(55) == 0) { return 0; } return CommSys_SendDataHuge(28, (void *)&param0->unk_20[0], 1000); } BOOL sub_0207AAFC(UnkStruct_0207A778 *param0) { PalPad *v0; TrainerInfo *v1; if (CommSys_SendRingRemainingSize() != 264) { return 0; } v0 = (PalPad *)&param0->unk_20[0]; if (param0->unk_00->battleType & BATTLE_TYPE_FRONTIER) { v1 = param0->unk_00->trainerInfo[CommSys_CurNetId() * 2]; } else { v1 = param0->unk_00->trainerInfo[CommSys_CurNetId()]; } PalPad_CreateNetworkObject(v1, param0->unk_00->palPad, (PalPad *)param0->unk_20); { int v2; for (v2 = 0; v2 < 4; v2++) { // 4 pal pads param0->unk_10[v2] = Heap_Alloc(HEAP_ID_BATTLE, 136); } } return 1; } BOOL sub_0207AB58(UnkStruct_0207A778 *param0) // SEND pal pad data?! { if (CommSys_SendRingRemainingSize() != 264) { return 0; } if (CommTiming_IsSyncState(56) == 0) { return 0; } return CommSys_SendDataHuge(33, (void *)param0->unk_20, 1000); } static void sub_0207AB8C(int param0, int param1, void *param2, void *param3) { UnkStruct_0207A778 *v0 = (UnkStruct_0207A778 *)param3; v0->unk_1020++; } BOOL sub_0207AB9C(UnkStruct_0207A778 *param0, int param1) { Trainer *v0; if (CommSys_SendRingRemainingSize() != 264) { return 0; } v0 = (Trainer *)&param0->unk_20[0]; *v0 = param0->unk_00->trainer[param1]; return 1; } BOOL sub_0207ABD0(UnkStruct_0207A778 *param0, int param1, int param2) { if (CommSys_SendRingRemainingSize() != 264) { return 0; } if (CommTiming_IsSyncState(param2) == 0) { return 0; } if (param1 == 1) { return CommSys_SendDataHuge(29, (void *)&param0->unk_20[0], sizeof(Trainer)); } else { return CommSys_SendDataHuge(30, (void *)&param0->unk_20[0], sizeof(Trainer)); } } static void sub_0207AC18(int param0, int param1, void *param2, void *param3) { UnkStruct_0207A778 *v0 = (UnkStruct_0207A778 *)param3; v0->unk_1020++; } BOOL sub_0207AC28(UnkStruct_0207A778 *param0, int param1) { Party *v0; if (CommSys_SendRingRemainingSize() != 264) { return 0; } v0 = (Party *)&param0->unk_20[0]; Party_Copy(param0->unk_00->parties[param1], v0); return 1; } BOOL sub_0207AC54(UnkStruct_0207A778 *param0, int param1, int param2) { if (CommSys_SendRingRemainingSize() != 264) { return 0; } if (CommTiming_IsSyncState(param2) == 0) { return 0; } if (param1 == 1) { return CommSys_SendDataHuge(31, (void *)&param0->unk_20[0], Party_SaveSize()); } else { return CommSys_SendDataHuge(32, (void *)&param0->unk_20[0], Party_SaveSize()); } } static void sub_0207ACA4(int param0, int param1, void *param2, void *param3) { UnkStruct_0207A778 *v0 = (UnkStruct_0207A778 *)param3; v0->unk_1020++; } void sub_0207ACB4(SysTask *param0, void *param1) { UnkStruct_0207ACB4 *v0 = (UnkStruct_0207ACB4 *)param1; u8 *v1; u16 *v2; u16 *v3; u16 *v4; int v5; v1 = ov16_0223E06C(v0->unk_00); v2 = ov16_0223E080(v0->unk_00); v3 = ov16_0223E08C(v0->unk_00); v4 = ov16_0223E098(v0->unk_00); switch (v0->unk_04) { case 0: if (CommSys_SendRingRemainingSize() != 264) { break; } if (v2[0] == v3[0]) { break; } if (v2[0] == v4[0]) { v2[0] = 0; v4[0] = 0; } v5 = sizeof(UnkStruct_0207A81C) + (v1[v2[0] + 2] | (v1[v2[0] + 3] << 8)); if (CommSys_SendData(23, (void *)&v1[v2[0]], v5) == 1) { v2[0] += v5; } break; default: case 255: Heap_Free(param1); SysTask_Done(param0); break; } } void sub_0207AD40(SysTask *param0, void *param1) { UnkStruct_0207AD40 *v0 = (UnkStruct_0207AD40 *)param1; u8 *v1; u16 *v2; u16 *v3; u16 *v4; int v5; v1 = ov16_0223E074(v0->unk_00); v2 = ov16_0223E0A4(v0->unk_00); v3 = ov16_0223E0B0(v0->unk_00); v4 = ov16_0223E0BC(v0->unk_00); switch (v0->unk_04) { case 0: if (v2[0] == v3[0]) { break; } if (v2[0] == v4[0]) { v2[0] = 0; v4[0] = 0; } if (ov16_02266AE4(v0->unk_00, (void *)&v1[v2[0]]) == 1) { v5 = sizeof(UnkStruct_0207A81C) + (v1[v2[0] + 2] | (v1[v2[0] + 3] << 8)); v2[0] += v5; } break; default: case 255: Heap_Free(param1); SysTask_Done(param0); break; } } static void sub_0207ADB4(int param0, int param1, void *param2, void *param3) { BattleSystem *v0 = (BattleSystem *)param3; ov16_0223F338(v0, 255); ov16_0223F344(v0, 255); ov16_0223F350(v0, 1); } static void PalPad_CreateNetworkObject(TrainerInfo *trainerInfo, PalPad *source, PalPad *destination) { CharCode_Copy(destination->trainerName, TrainerInfo_Name(trainerInfo)); destination->trainerId = TrainerInfo_ID(trainerInfo); destination->regionCode = TrainerInfo_RegionCode(trainerInfo); destination->gameCode = TrainerInfo_GameCode(trainerInfo); destination->gender = TrainerInfo_Gender(trainerInfo); for (int i = 0; i < PAL_PAD_ENTRIES; i++) { destination->associatedTrainerIds[i] = source[i].trainerId; destination->associatedTrainerGameCodes[i] = source[i].gameCode; destination->associatedTrainerRegionCodes[i] = source[i].regionCode; destination->associatedTrainerGenders[i] = source[i].gender; } } void sub_0207AE34(int param0, int param1, void *param2, void *param3) { UnkStruct_0207A778 *v0 = (UnkStruct_0207A778 *)param3; if (CommSys_CurNetId() != param0) { PalPad_PushEntries(v0->unk_00->palPad, (PalPad *)param2, 1, HEAP_ID_BATTLE); } v0->unk_1020++; } static int sub_0207AE64(void) { return 136; }
0
0.615132
1
0.615132
game-dev
MEDIA
0.506789
game-dev
0.78713
1
0.78713
magefree/mage
1,566
Mage.Sets/src/mage/cards/d/DeputyOfAcquittals.java
package mage.cards.d; import mage.MageInt; import mage.abilities.Ability; import mage.abilities.common.EntersBattlefieldTriggeredAbility; import mage.abilities.effects.common.ReturnToHandTargetEffect; import mage.abilities.keyword.FlashAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.SubType; import mage.filter.StaticFilters; import mage.target.Target; import mage.target.TargetPermanent; import java.util.UUID; /** * * @author LevelX2 */ public final class DeputyOfAcquittals extends CardImpl { public DeputyOfAcquittals(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{W}{U}"); this.subtype.add(SubType.HUMAN); this.subtype.add(SubType.WIZARD); this.power = new MageInt(2); this.toughness = new MageInt(2); // Flash this.addAbility(FlashAbility.getInstance()); // When Deputy of Acquittals enters the battlefield, you may return another target creature you control to its owner's hand. Ability ability = new EntersBattlefieldTriggeredAbility(new ReturnToHandTargetEffect(), true); Target target = new TargetPermanent(StaticFilters.FILTER_ANOTHER_TARGET_CREATURE_YOU_CONTROL); ability.addTarget(target); this.addAbility(ability); } private DeputyOfAcquittals(final DeputyOfAcquittals card) { super(card); } @Override public DeputyOfAcquittals copy() { return new DeputyOfAcquittals(this); } }
0
0.876444
1
0.876444
game-dev
MEDIA
0.984191
game-dev
0.993184
1
0.993184
ericraio/vanilla-wow-addons
2,308
o/OutfitDisplayFrame/localization.lua
-- Magic strings -- English OUTFITDISPLAYFRAME_NOTENOUGHFREESPACE = "Not enough free space in bags."; OUTFITDISPLAYFRAME_ITEMSNOTFOUND = "Outfit contains missing items."; OUTFITDISPLAYFRAME_INVALIDOUTFIT = "Invalid outfit format."; OUTFITDISPLAYFRAME_ITEMSINBANK = "Outfit contains banked items."; OUTFITDISPLAYFRAME_TOOFASTMSG = "Can't switch outfits that quickly."; OUTFITDISPLAYFRAME_ALTCLICK = "Alt-click will reset to an empty slot."; OUTFITDISPLAYFRAME_USECHECKBOX = "When checked, this slot is forced empty on switch."; OUTFITDISPLAYFRAME_OVERRIDEHELM = "When checked, override the value of \"Show Helm\" when this outfit is worn."; OUTFITDISPLAYFRAME_OVERRIDECLOAK = "When checked, override the value of \"Show Cloak\" when this outfit is worn."; -- German if ( GetLocale() == "deDE" ) then OUTFITDISPLAYFRAME_NOTENOUGHFREESPACE = "Nicht genug Platz in den Taschen"; OUTFITDISPLAYFRAME_ITEMSNOTFOUND = "Ausr\195\188stung enth\195\164lt fehlende Gegenst\195\164nde"; OUTFITDISPLAYFRAME_INVALIDOUTFIT = "Ung\195\188ltiges Ausr\195\188stungsformat"; OUTFITDISPLAYFRAME_ITEMSINBANK = "Ausstattung enth\195\164lt Gegenst\195\164nde, die auf der Bank sind."; OUTFITDISPLAYFRAME_TOOFASTMSG = "Sie k\195\182nnen nicht Ausstattungen schalten, die schnell."; OUTFITDISPLAYFRAME_USECHECKBOX = "Wenn H\195\164ckchen gesetzt, wird der Taschenplatz wird bim Ausr\195\188stungswechsel geleert."; end if ( GetLocale() == "frFR" ) then -- OUTFITDISPLAYFRAME_TWOHANDED = "Deux-mains"; OUTFITDISPLAYFRAME_NOTENOUGHFREESPACE = "Pas assez d'espace libre dans les sacs"; OUTFITDISPLAYFRAME_ITEMSNOTFOUND = "Articles manquants pour l'\195\169quipement choisi."; OUTFITDISPLAYFRAME_INVALIDOUTFIT = "Format d'\195\169quipement incorrect."; OUTFITDISPLAYFRAME_ITEMSINBANK = "L'\195\169quipement contient les articles en banque."; OUTFITDISPLAYFRAME_TOOFASTMSG = "On ne peut pas commuter les \195\169quipements aussi rapidement."; OUTFITDISPLAYFRAME_USECHECKBOX = "Si coch\195\169, ce slot est vid\195\169 lors de la commutation."; OUTFITDISPLAYFRAME_OVERRIDEHELM = "Si coch\195\169, force le \"Afficher le casque\" quand cette tenue est port\195\169e."; OUTFITDISPLAYFRAME_OVERRIDECLOAK = "Si coch\195\169, force le \"Afficher la cape\" quand cette tenue est port\195\169e."; end
0
0.583612
1
0.583612
game-dev
MEDIA
0.883167
game-dev
0.581538
1
0.581538
FancyInnovations/FancyPlugins
11,249
plugins/fancyholograms-v2/implementation_1_20_4/src/main/java/de/oliver/fancyholograms/hologram/version/Hologram1_20_4.java
package de.oliver.fancyholograms.hologram.version; import com.mojang.math.Transformation; import de.oliver.fancyholograms.api.data.*; import de.oliver.fancyholograms.api.events.HologramHideEvent; import de.oliver.fancyholograms.api.events.HologramShowEvent; import de.oliver.fancyholograms.api.hologram.Hologram; import de.oliver.fancylib.ReflectionUtils; import io.papermc.paper.adventure.PaperAdventure; import it.unimi.dsi.fastutil.ints.Int2ObjectMap; import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; import net.minecraft.network.protocol.game.ClientboundTeleportEntityPacket; import net.minecraft.network.syncher.EntityDataAccessor; import net.minecraft.network.syncher.SynchedEntityData.DataItem; import net.minecraft.network.syncher.SynchedEntityData.DataValue; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; import net.minecraft.util.Brightness; import net.minecraft.world.entity.Display; import net.minecraft.world.entity.Display.TextDisplay; import net.minecraft.world.entity.EntityType; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.block.Block; import org.bukkit.craftbukkit.v1_20_R3.CraftWorld; import org.bukkit.craftbukkit.v1_20_R3.entity.CraftPlayer; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.joml.Quaternionf; import java.util.ArrayList; import static de.oliver.fancylib.ReflectionUtils.getValue; public final class Hologram1_20_4 extends Hologram { @Nullable private Display display; public Hologram1_20_4(@NotNull final HologramData data) { super(data); } @Override public int getEntityId() { return display.getId(); } @Override public @Nullable org.bukkit.entity.Display getDisplayEntity() { return display != null ? (org.bukkit.entity.Display) display.getBukkitEntity() : null; } @Override public void create() { final var location = data.getLocation(); if (!location.isWorldLoaded()) { return; // no location data, cannot be created } ServerLevel world = ((CraftWorld) location.getWorld()).getHandle(); switch (data.getType()) { case TEXT -> this.display = new Display.TextDisplay(EntityType.TEXT_DISPLAY, world); case BLOCK -> this.display = new Display.BlockDisplay(EntityType.BLOCK_DISPLAY, world); case ITEM -> this.display = new Display.ItemDisplay(EntityType.ITEM_DISPLAY, world); } if (data instanceof DisplayHologramData dd) { final var DATA_TRANSFORMATION_INTERPOLATION_DURATION_ID = ReflectionUtils.getStaticValue(Display.class, MappingKeys1_20_4.DISPLAY__DATA_TRANSFORMATION_INTERPOLATION_DURATION_ID.getMapping()); display.getEntityData().set((EntityDataAccessor<Integer>) DATA_TRANSFORMATION_INTERPOLATION_DURATION_ID, dd.getInterpolationDuration()); final var DATA_TRANSFORMATION_INTERPOLATION_START_DELTA_TICKS_ID = ReflectionUtils.getStaticValue(Display.class, MappingKeys1_20_4.DISPLAY__DATA_TRANSFORMATION_INTERPOLATION_START_DELTA_TICKS_ID.getMapping()); display.getEntityData().set((EntityDataAccessor<Integer>) DATA_TRANSFORMATION_INTERPOLATION_START_DELTA_TICKS_ID, 0); } update(); } @Override public void delete() { this.display = null; } @Override public void update() { final var display = this.display; if (display == null) { return; // doesn't exist, nothing to update } // location data final var location = data.getLocation(); if (location.getWorld() == null || !location.isWorldLoaded()) { return; } else { display.setPosRaw(location.x(), location.y(), location.z()); display.setYRot(location.getYaw()); display.setXRot(location.getPitch()); } if (display instanceof TextDisplay textDisplay && data instanceof TextHologramData textData) { // line width final var DATA_LINE_WIDTH_ID = ReflectionUtils.getStaticValue(TextDisplay.class, MappingKeys1_20_4.TEXT_DISPLAY__DATA_LINE_WIDTH_ID.getMapping()); display.getEntityData().set((EntityDataAccessor<Integer>) DATA_LINE_WIDTH_ID, Hologram.LINE_WIDTH); // background final var DATA_BACKGROUND_COLOR_ID = ReflectionUtils.getStaticValue(TextDisplay.class, MappingKeys1_20_4.TEXT_DISPLAY__DATA_BACKGROUND_COLOR_ID.getMapping()); final var background = textData.getBackground(); if (background == null) { display.getEntityData().set((EntityDataAccessor<Integer>) DATA_BACKGROUND_COLOR_ID, TextDisplay.INITIAL_BACKGROUND); } else if (background == Hologram.TRANSPARENT) { display.getEntityData().set((EntityDataAccessor<Integer>) DATA_BACKGROUND_COLOR_ID, 0); } else { display.getEntityData().set((EntityDataAccessor<Integer>) DATA_BACKGROUND_COLOR_ID, background.asARGB()); } // text shadow if (textData.hasTextShadow()) { textDisplay.setFlags((byte) (textDisplay.getFlags() | TextDisplay.FLAG_SHADOW)); } else { textDisplay.setFlags((byte) (textDisplay.getFlags() & ~TextDisplay.FLAG_SHADOW)); } // text alignment if (textData.getTextAlignment() == org.bukkit.entity.TextDisplay.TextAlignment.LEFT) { textDisplay.setFlags((byte) (textDisplay.getFlags() | TextDisplay.FLAG_ALIGN_LEFT)); } else { textDisplay.setFlags((byte) (textDisplay.getFlags() & ~TextDisplay.FLAG_ALIGN_LEFT)); } // see through if (textData.isSeeThrough()) { textDisplay.setFlags((byte) (textDisplay.getFlags() | TextDisplay.FLAG_SEE_THROUGH)); } else { textDisplay.setFlags((byte) (textDisplay.getFlags() & ~TextDisplay.FLAG_SEE_THROUGH)); } if (textData.getTextAlignment() == org.bukkit.entity.TextDisplay.TextAlignment.RIGHT) { textDisplay.setFlags((byte) (textDisplay.getFlags() | TextDisplay.FLAG_ALIGN_RIGHT)); } else { textDisplay.setFlags((byte) (textDisplay.getFlags() & ~TextDisplay.FLAG_ALIGN_RIGHT)); } } else if (display instanceof Display.ItemDisplay itemDisplay && data instanceof ItemHologramData itemData) { // item itemDisplay.setItemStack(ItemStack.fromBukkitCopy(itemData.getItemStack())); } else if (display instanceof Display.BlockDisplay blockDisplay && data instanceof BlockHologramData blockData) { Block block = BuiltInRegistries.BLOCK.get(ResourceLocation.of("minecraft:" + blockData.getBlock().name().toLowerCase(), ':')); blockDisplay.setBlockState(block.defaultBlockState()); } if (data instanceof DisplayHologramData displayData) { // billboard data display.setBillboardConstraints(switch (displayData.getBillboard()) { case FIXED -> Display.BillboardConstraints.FIXED; case VERTICAL -> Display.BillboardConstraints.VERTICAL; case HORIZONTAL -> Display.BillboardConstraints.HORIZONTAL; case CENTER -> Display.BillboardConstraints.CENTER; }); // brightness if (displayData.getBrightness() != null) { display.setBrightnessOverride(new Brightness(displayData.getBrightness().getBlockLight(), displayData.getBrightness().getSkyLight())); } // entity scale AND MORE! display.setTransformation(new Transformation( displayData.getTranslation(), new Quaternionf(), displayData.getScale(), new Quaternionf()) ); // entity shadow display.setShadowRadius(displayData.getShadowRadius()); display.setShadowStrength(displayData.getShadowStrength()); // view range display.setViewRange(displayData.getVisibilityDistance()); } } @Override public boolean show(@NotNull final Player player) { if (!new HologramShowEvent(this, player).callEvent()) { return false; } if (this.display == null) { create(); // try to create it if it doesn't exist every time } final var display = this.display; if (display == null) { return false; // could not be created, nothing to show } if (!data.getLocation().getWorld().getName().equals(player.getLocation().getWorld().getName())) { return false; } ServerPlayer serverPlayer = ((CraftPlayer) player).getHandle(); // TODO: cache player protocol version // TODO: fix this // final var protocolVersion = FancyHologramsPlugin.get().isUsingViaVersion() ? Via.getAPI().getPlayerVersion(player.getUniqueId()) : MINIMUM_PROTOCOL_VERSION; // if (protocolVersion < MINIMUM_PROTOCOL_VERSION) { // System.out.println("nope protocol"); // return false; // } serverPlayer.connection.send(new ClientboundAddEntityPacket(display)); this.viewers.add(player.getUniqueId()); refreshHologram(player); return true; } @Override public boolean hide(@NotNull final Player player) { if (!new HologramHideEvent(this, player).callEvent()) { return false; } final var display = this.display; if (display == null) { return false; // doesn't exist, nothing to hide } ((CraftPlayer) player).getHandle().connection.send(new ClientboundRemoveEntitiesPacket(display.getId())); this.viewers.remove(player.getUniqueId()); return true; } @Override public void refresh(@NotNull final Player player) { final var display = this.display; if (display == null) { return; // doesn't exist, nothing to refresh } if (!isViewer(player)) { return; } ((CraftPlayer) player).getHandle().connection.send(new ClientboundTeleportEntityPacket(display)); if (display instanceof TextDisplay textDisplay) { textDisplay.setText(PaperAdventure.asVanilla(getShownText(player))); } final var values = new ArrayList<DataValue<?>>(); //noinspection unchecked for (final var item : ((Int2ObjectMap<DataItem<?>>) getValue(display.getEntityData(), "e")).values()) { values.add(item.value()); } ((CraftPlayer) player).getHandle().connection.send(new ClientboundSetEntityDataPacket(display.getId(), values)); } }
0
0.917885
1
0.917885
game-dev
MEDIA
0.811049
game-dev
0.967565
1
0.967565
AmProsius/gothic-1-community-patch
1,623
scriptbase/_work/Data/Scripts/Content/Story/NPC/VLK_5006_Buddler.d
instance VLK_5006_Buddler (Npc_Default) { //-------- primary data -------- name = Name_Buddler; npctype = npctype_mine_ambient; guild = GIL_VLK; level = 3; voice = 2; id = 5006; //-------- abilities -------- attribute[ATR_STRENGTH] = 15; attribute[ATR_DEXTERITY] = 10; attribute[ATR_MANA_MAX] = 0; attribute[ATR_MANA] = 0; attribute[ATR_HITPOINTS_MAX] = 76; attribute[ATR_HITPOINTS] = 76; //-------- visuals -------- // animations Mdl_SetVisual (self,"HUMANS.MDS"); Mdl_ApplyOverlayMds (self,"Humans_Tired.mds"); // body mesh, head mesh, hairmesh, face-tex, hair-tex, skin Mdl_SetVisualBody (self,"hum_body_Naked0",2,1,"Hum_Head_FatBald", 74, 1, VLK_ARMOR_L); B_Scale (self); Mdl_SetModelFatness (self, 0); fight_tactic = FAI_HUMAN_COWARD; //-------- Talents -------- Npc_SetTalentSkill (self, NPC_TALENT_1H,1); //-------- inventory -------- EquipItem (self, ItMw_1h_Nailmace_01); CreateInvItem (self, ItMwPickaxe); CreateInvItem (self, ItFoLoaf); CreateInvItem (self, ItFoBeer); CreateInvItem (self, ItLsTorch); //-------------Daily Routine------------- daily_routine = Rtn_FMstart_5006; }; FUNC VOID Rtn_FMstart_5006 () //FM { TA_PickOre (00,00,23,00,"FM_136"); TA_PickOre (23,00,24,00,"FM_136"); };
0
0.94618
1
0.94618
game-dev
MEDIA
0.9715
game-dev
0.941804
1
0.941804
JosefNemec/Playnite
7,125
source/Playnite/Database/Collections/PlatformsCollection.cs
using Playnite.Emulators; using Playnite.SDK; using Playnite.SDK.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Playnite.Database { public class PlatformsCollection : ItemCollection<Platform> { private readonly GameDatabase db; public PlatformsCollection(GameDatabase database, LiteDB.BsonMapper mapper) : base(mapper, type: GameDatabaseCollection.Platforms) { db = database; } public static void MapLiteDbEntities(LiteDB.BsonMapper mapper) { mapper.Entity<Platform>().Id(a => a.Id, false); } private void RemoveUsage(Guid platformId) { foreach (var game in db.Games.Where(a => a.PlatformIds?.Contains(platformId) == true)) { game.PlatformIds.Remove(platformId); db.Games.Update(game); } foreach (var emulator in db.Emulators) { if (!emulator.CustomProfiles.HasItems()) { continue; } var updated = false; foreach (var profile in emulator.CustomProfiles.Where(a => a.Platforms?.Contains(platformId) == true)) { profile.Platforms.Remove(platformId); updated = true; } if (updated) { db.Emulators.Update(emulator); } } } public override bool Remove(Guid id) { RemoveUsage(id); var dbItem = Get(id); db.RemoveFile(dbItem.Icon); db.RemoveFile(dbItem.Cover); db.RemoveFile(dbItem.Background); return base.Remove(id); } public override bool Remove(Platform item) { return Remove(item.Id); } public override bool Remove(IEnumerable<Platform> itemsToRemove) { if (itemsToRemove.HasItems()) { foreach (var item in itemsToRemove) { RemoveUsage(item.Id); var dbItem = Get(item.Id); db.RemoveFile(dbItem.Icon); db.RemoveFile(dbItem.Cover); db.RemoveFile(dbItem.Background); } } return base.Remove(itemsToRemove); } public override void Update(IEnumerable<Platform> items) { foreach (var item in items) { var dbItem = Get(item.Id); if (!dbItem.Icon.IsNullOrEmpty() && dbItem.Icon != item.Icon) { db.RemoveFile(dbItem.Icon); } if (!dbItem.Cover.IsNullOrEmpty() && dbItem.Cover != item.Cover) { db.RemoveFile(dbItem.Cover); } if (!dbItem.Background.IsNullOrEmpty() && dbItem.Background != item.Background) { db.RemoveFile(dbItem.Background); } } base.Update(items); } public override void Update(Platform item) { var dbItem = Get(item.Id); if (!dbItem.Icon.IsNullOrEmpty() && dbItem.Icon != item.Icon) { db.RemoveFile(dbItem.Icon); } if (!dbItem.Cover.IsNullOrEmpty() && dbItem.Cover != item.Cover) { db.RemoveFile(dbItem.Cover); } if (!dbItem.Background.IsNullOrEmpty() && dbItem.Background != item.Background) { db.RemoveFile(dbItem.Background); } base.Update(item); } public override Platform Add(MetadataProperty property) { if (property is MetadataSpecProperty specProp) { var exPlat = this.FirstOrDefault(a => a.SpecificationId == specProp.Id); if (exPlat != null) { return exPlat; } var plat = Emulation.Platforms.FirstOrDefault(a => a.Id == specProp.Id || a.Name == specProp.Id); if (plat != null) { exPlat = this.FirstOrDefault(a => a.SpecificationId == plat.Id); if (exPlat != null) { return exPlat; } else { var newPlat = new Platform(plat.Name) { SpecificationId = plat.Id }; Add(newPlat); return newPlat; } } else { var newPlat = new Platform(plat.Id); Add(newPlat); return newPlat; } } else { return base.Add(property); } } public override IEnumerable<Platform> Add(IEnumerable<MetadataProperty> properties) { foreach (var property in properties) { if (property is MetadataSpecProperty specProp) { yield return Add(specProp); } else { yield return base.Add(property); } } } public override Platform GetOrGenerate(MetadataProperty property) { if (property is MetadataSpecProperty specProp) { var exPlat = this.FirstOrDefault(a => a.SpecificationId == specProp.Id); if (exPlat != null) { return exPlat; } var plat = Emulation.Platforms.FirstOrDefault(a => a.Id == specProp.Id || a.Name == specProp.Id); if (plat != null) { exPlat = this.FirstOrDefault(a => a.SpecificationId == plat.Id); if (exPlat != null) { return exPlat; } else { return new Platform(plat.Name) { SpecificationId = plat.Id }; } } return null; } else { return base.GetOrGenerate(property); } } public override IEnumerable<Platform> GetOrGenerate(IEnumerable<MetadataProperty> properties) { foreach (var property in properties) { if (property is MetadataSpecProperty specProp) { yield return GetOrGenerate(specProp); } else { yield return base.GetOrGenerate(property); } } } } }
0
0.807805
1
0.807805
game-dev
MEDIA
0.684509
game-dev,databases
0.907184
1
0.907184
Soapwood/VXMusic
2,780
VXMusicOverlay/Library/PackageCache/com.unity.timeline@1.4.8/Editor/ControlTrack/ControlPlayableAssetEditor.cs
using System.Collections.Generic; using UnityEngine; using UnityEngine.Timeline; using UnityEngine.Playables; namespace UnityEditor.Timeline { [CustomTimelineEditor(typeof(ControlPlayableAsset))] class ControlPlayableAssetEditor : ClipEditor { static readonly Texture2D[] s_ParticleSystemIcon = {AssetPreview.GetMiniTypeThumbnail(typeof(ParticleSystem))}; public override ClipDrawOptions GetClipOptions(TimelineClip clip) { var asset = (ControlPlayableAsset)clip.asset; var options = base.GetClipOptions(clip); if (asset.updateParticle && TimelineEditor.inspectedDirector != null && asset.controllingParticles) options.icons = s_ParticleSystemIcon; return options; } public override void OnCreate(TimelineClip clip, TrackAsset track, TimelineClip clonedFrom) { var asset = (ControlPlayableAsset)clip.asset; GameObject sourceObject = null; // go by sourceObject first, then by prefab if (TimelineEditor.inspectedDirector != null) sourceObject = asset.sourceGameObject.Resolve(TimelineEditor.inspectedDirector); if (sourceObject == null && asset.prefabGameObject != null) sourceObject = asset.prefabGameObject; if (sourceObject) { var directors = asset.GetComponent<PlayableDirector>(sourceObject); var particleSystems = asset.GetComponent<ParticleSystem>(sourceObject); // update the duration and loop values (used for UI purposes) here // so they are tied to the latest gameObject bound asset.UpdateDurationAndLoopFlag(directors, particleSystems); clip.displayName = sourceObject.name; } } public override void GetSubTimelines(TimelineClip clip, PlayableDirector director, List<PlayableDirector> subTimelines) { var asset = (ControlPlayableAsset)clip.asset; // If there is a prefab, it will override the source GameObject if (!asset.updateDirector || asset.prefabGameObject != null || director == null) return; var go = asset.sourceGameObject.Resolve(director); if (go == null) return; foreach (var subTimeline in asset.GetComponent<PlayableDirector>(go)) { if (subTimeline == director || subTimeline == TimelineEditor.masterDirector || subTimeline == TimelineEditor.inspectedDirector) continue; if (subTimeline.playableAsset is TimelineAsset) subTimelines.Add(subTimeline); } } } }
0
0.865862
1
0.865862
game-dev
MEDIA
0.993299
game-dev
0.9505
1
0.9505
Akarin-project/Akarin
5,297
sources/src/main/java/co/aikar/timings/MinecraftTimings.java
package co.aikar.timings; import com.google.common.collect.MapMaker; import net.minecraft.server.*; import org.bukkit.plugin.Plugin; import org.bukkit.scheduler.BukkitTask; import org.bukkit.craftbukkit.scheduler.CraftTask; import java.util.Map; public final class MinecraftTimings { public static final Timing playerListTimer = Timings.ofSafe("Player List"); public static final Timing commandFunctionsTimer = Timings.ofSafe("Command Functions"); public static final Timing connectionTimer = Timings.ofSafe("Connection Handler"); public static final Timing tickablesTimer = Timings.ofSafe("Tickables"); public static final Timing minecraftSchedulerTimer = Timings.ofSafe("Minecraft Scheduler"); public static final Timing bukkitSchedulerTimer = Timings.ofSafe("Bukkit Scheduler"); public static final Timing bukkitSchedulerPendingTimer = Timings.ofSafe("Bukkit Scheduler - Pending"); public static final Timing bukkitSchedulerFinishTimer = Timings.ofSafe("Bukkit Scheduler - Finishing"); public static final Timing chunkIOTickTimer = Timings.ofSafe("ChunkIOTick"); public static final Timing timeUpdateTimer = Timings.ofSafe("Time Update"); public static final Timing serverCommandTimer = Timings.ofSafe("Server Command"); public static final Timing savePlayers = Timings.ofSafe("Save Players"); public static final Timing tickEntityTimer = Timings.ofSafe("## tickEntity"); public static final Timing tickTileEntityTimer = Timings.ofSafe("## tickTileEntity"); public static final Timing packetProcessTimer = Timings.ofSafe("## Packet Processing"); public static final Timing scheduledBlocksTimer = Timings.ofSafe("## Scheduled Blocks"); public static final Timing structureGenerationTimer = Timings.ofSafe("Structure Generation"); public static final Timing processQueueTimer = Timings.ofSafe("processQueue"); public static final Timing playerCommandTimer = Timings.ofSafe("playerCommand"); public static final Timing entityActivationCheckTimer = Timings.ofSafe("entityActivationCheck"); public static final Timing antiXrayUpdateTimer = Timings.ofSafe("anti-xray - update"); public static final Timing antiXrayObfuscateTimer = Timings.ofSafe("anti-xray - obfuscate"); private static final Map<Class<? extends Runnable>, String> taskNameCache = new MapMaker().weakKeys().makeMap(); private MinecraftTimings() {} /** * Gets a timer associated with a plugins tasks. * @param bukkitTask * @param period * @return */ public static Timing getPluginTaskTimings(BukkitTask bukkitTask, long period) { if (!bukkitTask.isSync()) { return NullTimingHandler.NULL; } Plugin plugin; Runnable task = ((CraftTask) bukkitTask).task; final Class<? extends Runnable> taskClass = task.getClass(); if (bukkitTask.getOwner() != null) { plugin = bukkitTask.getOwner(); } else { plugin = TimingsManager.getPluginByClassloader(taskClass); } final String taskname = taskNameCache.computeIfAbsent(taskClass, clazz -> clazz.isAnonymousClass() || clazz.isLocalClass() ? clazz.getName() : clazz.getCanonicalName()); StringBuilder name = new StringBuilder(64); name.append("Task: ").append(taskname); if (period > 0) { name.append(" (interval:").append(period).append(")"); } else { name.append(" (Single)"); } if (plugin == null) { return Timings.ofSafe(null, name.toString()); } return Timings.ofSafe(plugin, name.toString()); } /** * Get a named timer for the specified entity type to track type specific timings. * @param entity * @return */ public static Timing getEntityTimings(Entity entity) { String entityType = entity.getClass().getName(); return Timings.ofSafe("Minecraft", "## tickEntity - " + entityType, tickEntityTimer); } /** * Get a named timer for the specified tile entity type to track type specific timings. * @param entity * @return */ public static Timing getTileEntityTimings(TileEntity entity) { String entityType = entity.getClass().getName(); return Timings.ofSafe("Minecraft", "## tickTileEntity - " + entityType, tickTileEntityTimer); } public static Timing getCancelTasksTimer() { return Timings.ofSafe("Cancel Tasks"); } public static Timing getCancelTasksTimer(Plugin plugin) { return Timings.ofSafe(plugin, "Cancel Tasks"); } public static void stopServer() { TimingsManager.stopServer(); } public static Timing getBlockTiming(Block block) { return Timings.ofSafe("## Scheduled Block: " + block.getName(), scheduledBlocksTimer); } public static Timing getStructureTiming(StructureGenerator structureGenerator) { return Timings.ofSafe("Structure Generator - " + structureGenerator.getName(), structureGenerationTimer); } public static Timing getPacketTiming(Packet packet) { return Timings.ofSafe("## Packet - " + packet.getClass().getSimpleName(), packetProcessTimer); } }
0
0.881269
1
0.881269
game-dev
MEDIA
0.891187
game-dev
0.885406
1
0.885406
KKiiya/BedWars-HotbarManager
5,060
hotbarmanager-plugin/src/main/java/me/kiiya/hotbarmanager/listeners/InventoryListener.java
package me.kiiya.hotbarmanager.listeners; import me.kiiya.hotbarmanager.HotbarManager; import me.kiiya.hotbarmanager.api.support.VersionSupport; import me.kiiya.hotbarmanager.menu.GUIHolder; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.Event; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.inventory.InventoryAction; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.event.inventory.InventoryDragEvent; import org.bukkit.event.player.PlayerDropItemEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; public class InventoryListener implements Listener { private final VersionSupport vs; public InventoryListener() { vs = HotbarManager.getVersionSupport(); } @EventHandler(priority = EventPriority.HIGHEST) public void onInventoryClick(InventoryClickEvent e) { Player p = (Player) e.getWhoClicked(); Inventory inv = e.getInventory(); Inventory clickInv = e.getClickedInventory(); if (p == null) return; PlayerInventory pInv = p.getInventory(); if (inv == null) return; if (inv.getHolder() == null) return; if (inv.getHolder() instanceof GUIHolder && (e.getAction() == InventoryAction.DROP_ALL_CURSOR || e.getAction() == InventoryAction.DROP_ONE_CURSOR || e.getAction() == InventoryAction.DROP_ONE_SLOT || e.getAction() == InventoryAction.DROP_ALL_SLOT)) { e.setCancelled(true); return; } if (clickInv == null) return; if (clickInv.getHolder() == null) return; if ((clickInv.getHolder() instanceof Player && e.getInventory().getHolder() instanceof GUIHolder) || e.getAction() == InventoryAction.DROP_ALL_CURSOR || e.getAction() == InventoryAction.DROP_ONE_CURSOR || e.getAction() == InventoryAction.DROP_ONE_SLOT || e.getAction() == InventoryAction.DROP_ALL_SLOT) { e.setCancelled(true); ItemStack item = e.getCurrentItem(); if (item != null && item.getType() != Material.AIR) { String tag = vs.getItemTag(item, "hbm"); if (tag != null) { item.setType(Material.AIR); } } return; } if (!(clickInv.getHolder() instanceof GUIHolder)) return; if (e.getAction() == InventoryAction.MOVE_TO_OTHER_INVENTORY) { e.setCancelled(true); return; } else if (e.getAction() == InventoryAction.HOTBAR_SWAP) { e.setCancelled(true); return; } if (e.getInventory() != clickInv || clickInv == pInv) { e.setCursor(new ItemStack(Material.AIR)); e.setCancelled(true); return; } e.setCancelled(true); ((GUIHolder) clickInv.getHolder()).onInventoryClick(e); } @EventHandler public void onItemDrag(InventoryDragEvent e) { Player p = (Player) e.getWhoClicked(); Inventory inv = e.getInventory(); Inventory openInv = p.getOpenInventory().getTopInventory(); ItemStack oldCursor = e.getOldCursor(); String tag = vs.getItemTag(oldCursor, "hbm"); if (oldCursor == null) return; if (inv.getHolder() == null) return; if (openInv.getHolder() == null) return; if (tag == null) return; if (inv.getHolder() instanceof GUIHolder && openInv.getHolder() instanceof GUIHolder) { e.setResult(Event.Result.DENY); e.setCancelled(true); } } @EventHandler public void onInventoryDrop(PlayerDropItemEvent e) { Player p = e.getPlayer(); if (p == null) return; if (e.getPlayer().getOpenInventory() == null) return; Inventory inv = p.getOpenInventory().getTopInventory(); if (inv.getHolder() == null) return; if (inv.getHolder() instanceof GUIHolder) { ((GUIHolder) inv.getHolder()).onInventoryDrop(e); } } @EventHandler public void onInventoryClose(InventoryCloseEvent e) { Player p = (Player) e.getPlayer(); PlayerInventory inv = p.getInventory(); ItemStack itemOnCursor = p.getItemOnCursor(); if (itemOnCursor != null && itemOnCursor.getType() != Material.AIR) { String cTag = vs.getItemTag(itemOnCursor, "hbm"); if (cTag != null && itemOnCursor.getType() != Material.AIR) { p.setItemOnCursor(new ItemStack(Material.AIR)); } } for (ItemStack item : inv.getContents()) { if (item == null || item.getType() == Material.AIR) continue; String tag = vs.getItemTag(item, "hbm"); if (tag == null) continue; item.setType(Material.AIR); } } }
0
0.833602
1
0.833602
game-dev
MEDIA
0.945276
game-dev
0.954363
1
0.954363
opentibiabr/canary
1,892
data-otservbr-global/scripts/quests/the_secret_library_quest/library_area/creaturescripts_ghulosh.lua
local info = { stages = { { p = 75, v = 1 }, { p = 50, v = 2 }, { p = 25, v = 3 }, }, stg = Storage.Quest.U11_80.TheSecretLibrary.Library.Ghulosh, } local function nextStage(storage) if Game.getStorageValue(storage) < 1 then Game.setStorageValue(storage, 1) end Game.setStorageValue(storage, Game.getStorageValue(storage) + 1) end local creaturescripts_library_ghulosh = CreatureEvent("ghuloshThink") function creaturescripts_library_ghulosh.onThink(creature, interval) local stage = 0 for _, k in pairs(info.stages) do if Game.getStorageValue(info.stg) == k.v then stage = k.p end end local position = creature:getPosition() local cHealth = creature:getHealth() local percentageHealth = (cHealth / creature:getMaxHealth()) * 100 if percentageHealth <= stage then local monster = Game.createMonster("ghulosh' deathgaze", position, true) nextStage(info.stg) creature:remove() if monster then monster:addHealth(-(monster:getHealth() - cHealth)) monster:say("FEEL MY WRATH!!", TALKTYPE_MONSTER_SAY) end end end creaturescripts_library_ghulosh:register() local function doSpawn(monster, k, position) if k <= 4 then position:sendMagicEffect(CONST_ME_TELEPORT) k = k + 1 addEvent(doSpawn, 2 * 1000, monster, k, position) else local monster = Game.createMonster(monster, position) end end local creaturescripts_library_ghulosh = CreatureEvent("ghuloshDeath") function creaturescripts_library_ghulosh.onDeath(creature, corpse, killer, mostDamageKiller, unjustified, mostDamageUnjustified) local cPos = creature:getPosition() if creature:getName():lower() == "the book of death" then Game.createMonster("Concentrated Death", cPos) elseif creature:getName():lower() == "concentrated death" then addEvent(doSpawn, 4 * 1000, "The Book of Death", 1, Position(32755, 32716, 10)) end end creaturescripts_library_ghulosh:register()
0
0.79165
1
0.79165
game-dev
MEDIA
0.985492
game-dev
0.908392
1
0.908392
Tslat/Advent-Of-Ascension
2,081
source/content/entity/projectile/cannon/RPGEntity.java
package net.tslat.aoa3.content.entity.projectile.cannon; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.InteractionHand; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.ai.attributes.Attributes; import net.minecraft.world.entity.projectile.ThrowableProjectile; import net.minecraft.world.level.Level; import net.minecraft.world.phys.Vec3; import net.tslat.aoa3.common.registration.AoAExplosions; import net.tslat.aoa3.common.registration.entity.AoAProjectiles; import net.tslat.aoa3.content.entity.projectile.HardProjectile; import net.tslat.aoa3.content.entity.projectile.gun.BaseBullet; import net.tslat.aoa3.content.item.weapon.gun.BaseGun; import net.tslat.aoa3.library.object.explosion.StandardExplosion; public class RPGEntity extends BaseBullet implements HardProjectile { public RPGEntity(EntityType<? extends ThrowableProjectile> entityType, Level world) { super(entityType, world); } public RPGEntity(Level world) { super(AoAProjectiles.RPG.get(), world); } public RPGEntity(LivingEntity shooter, BaseGun gun, InteractionHand hand, int maxAge, int piercingValue) { super(AoAProjectiles.RPG.get(), shooter, gun, hand, maxAge, 1.0f, piercingValue); } public RPGEntity(Level world, double x, double y, double z) { super(AoAProjectiles.RPG.get(), world, x, y, z); } @Override public void doBlockImpact(Vec3 impactLocation, Direction face, BlockPos blockPos) { explode(impactLocation); } @Override public void doEntityImpact(Entity target, Vec3 impactLocation) { explode(impactLocation); } protected void explode(Vec3 position) { if (!level().isClientSide) { new StandardExplosion(AoAExplosions.rpg(target -> 1 + (float)(target.getAttributeValue(Attributes.ARMOR) * 1.5 + target.getAttributeValue(Attributes.ARMOR_TOUGHNESS) * 0.5f) / 100f), (ServerLevel) level(), this, getOwner(), position).explode(); } } }
0
0.728726
1
0.728726
game-dev
MEDIA
0.987634
game-dev
0.804452
1
0.804452
QianMo/Unity-Design-Pattern
1,898
Assets/Game Programming Patterns/Object Pool Pattern/Example/Script/Example/ObjectPoolExample.cs
using UnityEngine; using System.Collections; using System.Collections.Generic; namespace ObjectPoolPatternExample { public class ObjectPoolExample : MonoBehaviour { //池名称 public string poolName; //对象List // public List<GameObject> ObjectList = new List<GameObject>(); public List<PoolObject> ObjectList = new List<PoolObject>(); public void Start() { //初始化对象池 PoolManager.Instance.Init(); //开始运行时,先从池中取出一个对象 GetObjectFromPool(); } /// <summary> /// 从池中取出对象,并设置随机位置 /// </summary> public void GetObjectFromPool() { if (ObjectList == null) { return; } //设置随机位置 Vector3 pos = new Vector3(); pos.x = Random.Range(-5, 6); pos.y = 0f; pos.z = Random.Range(-5, 6); PoolObject po = PoolManager.Instance.GetObjectFromPool(poolName, pos, Quaternion.identity); if (po) { ObjectList.Add(po); } } /// <summary> /// 将索引为0的对象返回池中 /// </summary> public void ReturnOneObjectToPool() { if (ObjectList == null || ObjectList.Count <= 0) { return; } PoolManager.Instance.ReturnObjectToPool(ObjectList[0]); ObjectList.Remove(ObjectList[0]); } /// <summary> /// 将所有对象返回池中 /// </summary> public void ReturnAllObjectToPool() { if (ObjectList == null) { return; } foreach (PoolObject po in ObjectList) { PoolManager.Instance.ReturnObjectToPool(po); } ObjectList.Clear(); } } }
0
0.764469
1
0.764469
game-dev
MEDIA
0.862874
game-dev
0.823833
1
0.823833
SIsilicon/WorldEdit-BE
3,342
src/server/shapes/sphere.ts
import { Shape, shapeGenOptions, shapeGenVars } from "./base_shape.js"; import { Vector } from "@notbeer-api"; export class SphereShape extends Shape { private radii: [number, number, number] = [0, 0, 0]; private domeDirection?: Vector; protected customHollow = true; constructor(radiusX: number, radiusY?: number, radiusZ?: number, domeDirection?: Vector) { super(); this.radii[0] = radiusX; this.radii[1] = radiusY ?? this.radii[0]; this.radii[2] = radiusZ ?? this.radii[1]; this.domeDirection = domeDirection; } public getRegion(loc: Vector) { if (this.domeDirection?.x === 1) { return <[Vector, Vector]>[loc.offset(0, -this.radii[1], -this.radii[2]), loc.offset(this.radii[0], this.radii[1], this.radii[2])]; } else if (this.domeDirection?.x === -1) { return <[Vector, Vector]>[loc.offset(-this.radii[0], -this.radii[1], -this.radii[2]), loc.offset(0, this.radii[1], this.radii[2])]; } else if (this.domeDirection?.y === 1) { return <[Vector, Vector]>[loc.offset(-this.radii[0], 0, -this.radii[2]), loc.offset(this.radii[0], this.radii[1], this.radii[2])]; } else if (this.domeDirection?.y === -1) { return <[Vector, Vector]>[loc.offset(-this.radii[0], -this.radii[1], -this.radii[2]), loc.offset(this.radii[0], 0, this.radii[2])]; } else if (this.domeDirection?.z === 1) { return <[Vector, Vector]>[loc.offset(-this.radii[0], -this.radii[1], 0), loc.offset(this.radii[0], this.radii[1], this.radii[2])]; } else if (this.domeDirection?.z === -1) { return <[Vector, Vector]>[loc.offset(-this.radii[0], -this.radii[1], -this.radii[2]), loc.offset(this.radii[0], this.radii[1], 0)]; } else { return <[Vector, Vector]>[loc.offset(-this.radii[0], -this.radii[1], -this.radii[2]), loc.offset(this.radii[0], this.radii[1], this.radii[2])]; } } public getYRange(): null { throw new Error("getYRange not implemented!"); } public getOutline() { // TODO: Support oblique spheres const maxRadius = Math.max(...this.radii) + 0.5; return [...this.drawCircle(Vector.ZERO, maxRadius, "x"), ...this.drawCircle(Vector.ZERO, maxRadius, "y"), ...this.drawCircle(Vector.ZERO, maxRadius, "z")]; } protected prepGeneration(genVars: shapeGenVars, options?: shapeGenOptions) { genVars.isHollow = options?.hollow ?? false; genVars.radiiOff = this.radii.map((v) => v + 0.5); genVars.thickness = options?.hollowThickness ?? 1; } protected inShape(relLoc: Vector, genVars: shapeGenVars) { if (genVars.isHollow) { const thickness = genVars.thickness; const hLocal = [relLoc.x / (genVars.radiiOff[0] - thickness), relLoc.y / (genVars.radiiOff[1] - thickness), relLoc.z / (genVars.radiiOff[2] - thickness)]; if (hLocal[0] * hLocal[0] + hLocal[1] * hLocal[1] + hLocal[2] * hLocal[2] < 1.0) { return false; } } const local = [relLoc.x / genVars.radiiOff[0], relLoc.y / genVars.radiiOff[1], relLoc.z / genVars.radiiOff[2]]; if (local[0] * local[0] + local[1] * local[1] + local[2] * local[2] <= 1.0) { return true; } return false; } }
0
0.864894
1
0.864894
game-dev
MEDIA
0.35733
game-dev
0.953024
1
0.953024
Craftventure/open-plugin-parts
5,301
net/craftventure/core/feature/finalevent/FinaleTimer.kt
package net.craftventure.core.feature.finalevent import net.craftventure.bukkit.ktx.manager.FeatureManager import net.craftventure.bukkit.ktx.plugin.Environment import net.craftventure.chat.bungee.extension.plus import net.craftventure.chat.bungee.util.CVTextColor import net.craftventure.core.CraftventureCore import net.craftventure.core.async.executeAsync import net.craftventure.core.async.executeSync import net.craftventure.core.ktx.extension.utcMillis import net.craftventure.core.ktx.logging.logcat import net.craftventure.core.utils.GameTimeUtils import net.craftventure.database.MainRepositoryProvider import net.craftventure.database.type.RideState import org.bukkit.Bukkit import org.bukkit.GameRule import java.time.LocalDateTime import java.time.ZonedDateTime import java.util.concurrent.ScheduledFuture import java.util.concurrent.TimeUnit import kotlin.time.DurationUnit import kotlin.time.toDuration object FinaleTimer { val endingDate = ZonedDateTime.parse("2024-04-21T22:00:00+02:00").toLocalDateTime() private val endingEndDate = ZonedDateTime.parse("2024-04-28T22:00:00+02:00").toLocalDateTime() private var scheduledNextPlay: ScheduledFuture<*>? = null private var scheduledPrepare: ScheduledFuture<*>? = null private var hasStartedFinale = false var nextPlay: LocalDateTime? = null private set init { scheduleOrExecuteCinematicPrepare() scheduleNextPlay() } fun onCinematicCancelled() { scheduleNextPlay() } private fun scheduleOrExecuteCinematicPrepare() { val prepareAt = endingDate.minusMinutes(10) val now = LocalDateTime.now() if (now > endingEndDate) return if (prepareAt < now) { startFinaleMode() } else { scheduledPrepare?.cancel(false) scheduledPrepare = CraftventureCore.getScheduledExecutorService().schedule({ startFinaleMode() }, prepareAt.utcMillis - now.utcMillis, TimeUnit.MILLISECONDS) } } private fun calculateNextPlayTime(): LocalDateTime { val now = LocalDateTime.now() if (now > endingEndDate) return LocalDateTime.MAX var pickedDate: LocalDateTime = endingDate while (pickedDate < now) { pickedDate = pickedDate.plusMinutes(20) } return pickedDate } private fun scheduleNextPlay() { val nextPlay = calculateNextPlayTime() this.nextPlay = nextPlay val now = LocalDateTime.now() if (now > endingEndDate) return val offset = nextPlay.utcMillis - now.utcMillis if (offset <= 0) { runFinale() } else { logcat { "Scheduling next cinematic in ${offset.toDuration(DurationUnit.MILLISECONDS)} ($offset)" } scheduledNextPlay?.cancel(false) scheduledNextPlay = CraftventureCore.getScheduledExecutorService().schedule({ runFinale() }, offset, TimeUnit.MILLISECONDS) } } private fun runFinale() { executeSync { FinaleCinematic.prepareStart() } executeSync(20 * 4) { FinaleCinematic.start() } } fun setup() {} fun startFinaleMode() { logcat { "Starting CV2 finale mode" } Bukkit.getServer().worlds.first().setGameRule(GameRule.DO_DAYLIGHT_CYCLE, false) Bukkit.getServer().worlds.first().time = GameTimeUtils.hoursMinutesToTicks(12, 0) if (!hasStartedFinale) executeAsync { if (CraftventureCore.getInstance().environment == Environment.PRODUCTION) MainRepositoryProvider.rideRepository.cachedItems.forEach { if (it.state != RideState.CLOSED) MainRepositoryProvider.rideRepository.setState(it, RideState.CLOSED) } val message = CVTextColor.serverNoticeAccent + "The last ride dispatches have just commenced" Bukkit.getOnlinePlayers().forEach { it.sendMessage(message) } hasStartedFinale = true } FeatureManager.disableFeature(FeatureManager.Feature.KART_SPAWN_AS_USER) FeatureManager.disableFeature(FeatureManager.Feature.SPATIAL_SOUNDS) FeatureManager.disableFeature(FeatureManager.Feature.BALLOON_ACTIVATE) FeatureManager.disableFeature(FeatureManager.Feature.CLOTHING_PARTICLES) FeatureManager.disableFeature(FeatureManager.Feature.SKATES_ENABLED) FeatureManager.disableFeature(FeatureManager.Feature.VIEW_OTHER_PLAYERS) FeatureManager.disableFeature(FeatureManager.Feature.MINIGAME_JOIN) // FeatureManager.disableFeature(FeatureManager.Feature.AUDIOSERVER_TRACKING) // FeatureManager.disableFeature(FeatureManager.Feature.AUDIOSERVER_UPDATING) // FeatureManager.disableFeature(FeatureManager.Feature.SCENE_ACTION_SCHEMATIC_PASTING) FeatureManager.disableFeature(FeatureManager.Feature.AUTOMATED_SCHEMATIC_PASTING) FeatureManager.disableFeature(FeatureManager.Feature.SHOPS_PRESENTER) FeatureManager.disableFeature(FeatureManager.Feature.JUMP_PUZZLE_JOIN) FeatureManager.disableFeature(FeatureManager.Feature.DRESSING_ROOM) } }
0
0.928999
1
0.928999
game-dev
MEDIA
0.863054
game-dev
0.989472
1
0.989472
errai/errai
13,986
errai-data-binding/src/main/java/org/jboss/errai/databinding/client/BindableListWrapper.java
/* * Copyright (C) 2013 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.errai.databinding.client; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.IdentityHashMap; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Map; import org.jboss.errai.common.client.api.Assert; import org.jboss.errai.databinding.client.api.handler.list.BindableListChangeHandler; import org.jboss.errai.databinding.client.api.handler.property.PropertyChangeEvent; import org.jboss.errai.databinding.client.api.handler.property.PropertyChangeHandler; import com.google.gwt.event.shared.HandlerRegistration; /** * Wraps a List<M> to notify change handlers of all operations that mutate the underlying list. * * @author Christian Sadilek <csadilek@redhat.com> * @author Max Barkley <mbarkley@redhat.com> * * @param <M> */ @SuppressWarnings("unchecked") public class BindableListWrapper<M> implements List<M>, BindableProxy<List<M>> { private List<M> list; /* * Must be identity set so that ListWidget is not added as a handler twice when using declarative binding. */ private final Collection<BindableListChangeHandler<M>> handlers = Collections.newSetFromMap(new IdentityHashMap<>()); private final Map<BindableProxyAgent<?>, PropertyChangeHandler<?>> elementChangeHandlers = new HashMap<BindableProxyAgent<?>, PropertyChangeHandler<?>>(); private final Map<PropertyChangeHandler<?>, PropertyChangeUnsubscribeHandle> unsubscribeHandlesByHandler = new HashMap<PropertyChangeHandler<?>, PropertyChangeUnsubscribeHandle>(); private final BindableProxyAgent<List<M>> agent; public BindableListWrapper(List<M> list) { Assert.notNull(list); if (list instanceof BindableListWrapper) { throw new IllegalArgumentException("Wrap a BindableListWrapper in a BindableListWrapper."); } this.list = list; for (int i = 0; i < this.list.size(); i++) { this.list.set(i, (M) convertToProxy(this.list.get(i))); } agent = new BindableProxyAgent<List<M>>(this, list); agent.propertyTypes.put("this", new PropertyType(List.class, true, true)); } @Override public boolean add(M element) { final List<M> oldValue = new ArrayList<M>(list); element = (M) convertToProxy(element); boolean b = list.add(element); for (BindableListChangeHandler<M> handler : handlers) { handler.onItemAdded(oldValue, element); } return b; } @Override public void add(int index, M element) { final List<M> oldValue = new ArrayList<M>(list); element = (M) convertToProxy(element); list.add(index, element); for (BindableListChangeHandler<M> handler : handlers) { handler.onItemAddedAt(oldValue, index, element); } } @Override public boolean addAll(Collection<? extends M> c) { final List<M> oldValue = new ArrayList<M>(list); List<M> addedModels = new ArrayList<M>(); for (M model : c) { addedModels.add((M) convertToProxy(model)); } boolean b = list.addAll(addedModels); for (BindableListChangeHandler<M> handler : handlers) { handler.onItemsAdded(oldValue, addedModels); } return b; } @Override public boolean addAll(int index, Collection<? extends M> c) { final List<M> oldValue = new ArrayList<M>(list); int originalSize = list.size(); boolean b = list.addAll(index, c); int numAdded = list.size() - originalSize; for (int i = index; i < index + numAdded; i++) { list.set(i, (M) convertToProxy(list.get(i))); } for (BindableListChangeHandler<M> handler : handlers) { handler.onItemsAddedAt(oldValue, index, list.subList(index, index + c.size())); } return b; } @Override public void clear() { final List<M> oldValue = new ArrayList<M>(list); list.clear(); for (BindableListChangeHandler<M> handler : handlers) { handler.onItemsCleared(oldValue); } removeElementChangeHandlers(); } @Override public boolean contains(Object o) { return list.contains(convertToProxy(o)); } @Override public boolean containsAll(Collection<?> c) { boolean b = true; for (Object item : c) { if (!contains(item)) { b = false; break; } } return b; } @Override public M get(int index) { return list.get(index); } @Override public int indexOf(Object o) { return list.indexOf(convertToProxy(o)); } @Override public boolean isEmpty() { return list.isEmpty(); } @Override public Iterator<M> iterator() { return new BindableListIterator(); } @Override public int lastIndexOf(Object o) { return list.lastIndexOf(convertToProxy(o)); } @Override public ListIterator<M> listIterator() { return new BindableListIterator(); } @Override public ListIterator<M> listIterator(int index) { return new BindableListIterator(index); } @Override public boolean remove(Object o) { final List<M> oldValue = new ArrayList<M>(list); o = convertToProxy(o); int index = list.indexOf(o); boolean b = list.remove(o); if (b) { for (BindableListChangeHandler<M> handler : handlers) { handler.onItemRemovedAt(oldValue, index); } removeElementChangeHandler(oldValue.get(index)); } return b; } @Override public M remove(int index) { final List<M> oldValue = new ArrayList<M>(list); M m = list.remove(index); for (BindableListChangeHandler<M> handler : handlers) { handler.onItemRemovedAt(oldValue, index); } removeElementChangeHandler(m); return m; } @Override public boolean removeAll(Collection<?> c) { final List<M> oldValue = new ArrayList<M>(list); final List<Integer> indexes = new ArrayList<Integer>(); for (Object m : c) { m = convertToProxy(m); Integer index = list.indexOf(m); if (!indexes.contains(index)) { indexes.add(index); } } Collections.sort(indexes, Collections.reverseOrder()); final boolean b = list.removeAll(c); if (b) { for (BindableListChangeHandler<M> handler : handlers) { handler.onItemsRemovedAt(oldValue, indexes); } for (final Object m : c) { removeElementChangeHandler(convertToProxy(m)); } } return b; } @Override public boolean retainAll(Collection<?> c) { List<Object> proxies = new ArrayList<Object>(); for (Object item : c) { proxies.add(convertToProxy(item)); } return list.retainAll(c); } @Override public M set(int index, M element) { final List<M> oldValue = new ArrayList<M>(list); element = (M) convertToProxy(element); M m = list.set(index, element); for (BindableListChangeHandler<M> handler : handlers) { handler.onItemChanged(oldValue, index, element); } removeElementChangeHandler(m); return m; } @Override public int size() { return list.size(); } @Override public List<M> subList(int fromIndex, int toIndex) { return list.subList(fromIndex, toIndex); } @Override public Object[] toArray() { return list.toArray(); } @Override public <T> T[] toArray(T[] a) { return list.toArray(a); } /** * @param handler * If this handler has already been added, it will not be added again. */ public HandlerRegistration addChangeHandler(final BindableListChangeHandler<M> handler) { Assert.notNull(handler); handlers.add(handler); return () -> handlers.remove(handler); } private Object convertToProxy(Object element) { if (BindableProxyFactory.isBindableType(element)) { element = BindableProxyFactory.getBindableProxy(element); final BindableProxyAgent<?> agent = ((BindableProxy<?>) element).getBindableProxyAgent(); if (!elementChangeHandlers.containsKey(agent)) { // Register a property change handler on the element to fire a change // event for the list when the element changes PropertyChangeHandler<Object> handler = new PropertyChangeHandler<Object>() { @Override public void onPropertyChange(PropertyChangeEvent<Object> event) { final int index = list.indexOf(event.getSource()); final List<M> source = new ArrayList<M>(list); if (index == -1) return; // yikes! we do this to alter the source list (otherwise the change event won't get fired). source.add(null); for (BindableListChangeHandler<M> handler : handlers) { handler.onItemChanged(source, index, (M) event.getSource()); } } }; unsubscribeHandlesByHandler.put(handler, agent.addPropertyChangeHandler(handler)); elementChangeHandlers.put(agent, handler); } } return element; } private void removeElementChangeHandler(Object element) { if (!BindableProxyFactory.isBindableType(element)) { return; } final BindableProxyAgent<?> agent= ((BindableProxy<?>) element).getBindableProxyAgent(); removeElementChangeHandler(agent); } private void removeElementChangeHandler(BindableProxyAgent<?> agent) { Assert.notNull(agent); PropertyChangeHandler<?> handler = elementChangeHandlers.remove(agent); if (handler != null) { PropertyChangeUnsubscribeHandle unsubHandle = unsubscribeHandlesByHandler.remove(handler); if (unsubHandle == null) { throw new RuntimeException("No " + PropertyChangeUnsubscribeHandle.class.getSimpleName() + " was found for the removed handler."); } unsubHandle.unsubscribe(); } } private void removeElementChangeHandlers() { List<BindableProxyAgent<?>> agents = new ArrayList<BindableProxyAgent<?>>(elementChangeHandlers.keySet()); for (BindableProxyAgent<?> agent : agents) { removeElementChangeHandler(agent); } } @Override public int hashCode() { return list.hashCode(); } @Override public boolean equals(Object obj) { return list.equals(obj); } @Override public String toString() { return list.toString(); } /** * Wraps an Iterator or ListIterator to notify change handlers of all operations that mutate the * underlying list. */ public class BindableListIterator implements ListIterator<M>, Iterator<M> { private ListIterator<M> iterator; public BindableListIterator() { iterator = list.listIterator(); } public BindableListIterator(int index) { iterator = list.listIterator(index); } @Override public boolean hasNext() { return iterator.hasNext(); } @Override public M next() { return iterator.next(); } @Override public boolean hasPrevious() { return iterator.hasPrevious(); } @Override public M previous() { return iterator.previous(); } @Override public int nextIndex() { return iterator.nextIndex(); } @Override public int previousIndex() { return iterator.previousIndex(); } @Override public void remove() { List<M> oldValue = new ArrayList<M>(list); iterator.remove(); int index = iterator.previousIndex() + 1; for (BindableListChangeHandler<M> handler : handlers) { handler.onItemRemovedAt(oldValue, index); } removeElementChangeHandler(oldValue.get(index)); } @Override public void set(M e) { List<M> oldValue = new ArrayList<M>(list); e = (M) convertToProxy(e); iterator.set(e); int index = iterator.nextIndex() - 1; for (BindableListChangeHandler<M> handler : handlers) { handler.onItemChanged(oldValue, index, e); } removeElementChangeHandler(oldValue.get(index)); } @Override public void add(M e) { List<M> oldValue = new ArrayList<M>(list); e = (M) convertToProxy(e); int index = iterator.nextIndex(); iterator.add(e); for (BindableListChangeHandler<M> handler : handlers) { handler.onItemAddedAt(oldValue, index, e); } } } @Override public Object unwrap() { return list; } @Override public Object get(String propertyName) { if ("this".equals(propertyName)) { return list; } else { throw new NonExistingPropertyException("List", propertyName); } } @Override public void set(String propertyName, Object value) { if ("this".equals(propertyName)) { if (value instanceof BindableListWrapper) { throw new IllegalArgumentException("Cannot nest BindableListWrapper."); } list = (List<M>) value; } else { throw new NonExistingPropertyException("List", propertyName); } } @Override public Map<String, PropertyType> getBeanProperties() { return Collections.emptyMap(); } @Override public BindableProxyAgent<List<M>> getBindableProxyAgent() { return agent; } @Override public void updateWidgets() { agent.updateWidgetsAndFireEvents(); } @Override public List<M> deepUnwrap() { final List<M> unwrapped = new ArrayList<>(list.size()); for (M m : list) { if (m instanceof BindableProxy) { m = ((BindableProxy<M>) m).deepUnwrap(); } unwrapped.add(m); } return unwrapped; } }
0
0.95007
1
0.95007
game-dev
MEDIA
0.262166
game-dev
0.966484
1
0.966484
dviglo/dviglo
26,210
source/third-party/bullet/bullet/BulletSoftBody/btDeformableContactConstraint.cpp
/* Written by Xuchen Han <xuchenhan2015@u.northwestern.edu> Bullet Continuous Collision Detection and Physics Library Copyright (c) 2019 Google Inc. http://bulletphysics.org This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "btDeformableContactConstraint.h" /* ================ Deformable Node Anchor =================== */ btDeformableNodeAnchorConstraint::btDeformableNodeAnchorConstraint(const btSoftBody::DeformableNodeRigidAnchor& a, const btContactSolverInfo& infoGlobal) : m_anchor(&a), btDeformableContactConstraint(a.m_cti.m_normal, infoGlobal) { } btDeformableNodeAnchorConstraint::btDeformableNodeAnchorConstraint(const btDeformableNodeAnchorConstraint& other) : m_anchor(other.m_anchor), btDeformableContactConstraint(other) { } btVector3 btDeformableNodeAnchorConstraint::getVa() const { const btSoftBody::sCti& cti = m_anchor->m_cti; btVector3 va(0, 0, 0); if (cti.m_colObj->hasContactResponse()) { btRigidBody* rigidCol = 0; btMultiBodyLinkCollider* multibodyLinkCol = 0; // grab the velocity of the rigid body if (cti.m_colObj->getInternalType() == btCollisionObject::CO_RIGID_BODY) { rigidCol = (btRigidBody*)btRigidBody::upcast(cti.m_colObj); va = rigidCol ? (rigidCol->getVelocityInLocalPoint(m_anchor->m_c1)) : btVector3(0, 0, 0); } else if (cti.m_colObj->getInternalType() == btCollisionObject::CO_FEATHERSTONE_LINK) { multibodyLinkCol = (btMultiBodyLinkCollider*)btMultiBodyLinkCollider::upcast(cti.m_colObj); if (multibodyLinkCol) { const int ndof = multibodyLinkCol->m_multiBody->getNumDofs() + 6; const btScalar* J_n = &m_anchor->jacobianData_normal.m_jacobians[0]; const btScalar* J_t1 = &m_anchor->jacobianData_t1.m_jacobians[0]; const btScalar* J_t2 = &m_anchor->jacobianData_t2.m_jacobians[0]; const btScalar* local_v = multibodyLinkCol->m_multiBody->getVelocityVector(); const btScalar* local_dv = multibodyLinkCol->m_multiBody->getDeltaVelocityVector(); // add in the normal component of the va btScalar vel = 0.0; for (int k = 0; k < ndof; ++k) { vel += (local_v[k] + local_dv[k]) * J_n[k]; } va = cti.m_normal * vel; // add in the tangential components of the va vel = 0.0; for (int k = 0; k < ndof; ++k) { vel += (local_v[k] + local_dv[k]) * J_t1[k]; } va += m_anchor->t1 * vel; vel = 0.0; for (int k = 0; k < ndof; ++k) { vel += (local_v[k] + local_dv[k]) * J_t2[k]; } va += m_anchor->t2 * vel; } } } return va; } btScalar btDeformableNodeAnchorConstraint::solveConstraint(const btContactSolverInfo& infoGlobal) { const btSoftBody::sCti& cti = m_anchor->m_cti; btVector3 va = getVa(); btVector3 vb = getVb(); btVector3 vr = (vb - va); // + (m_anchor->m_node->m_x - cti.m_colObj->getWorldTransform() * m_anchor->m_local) * 10.0 const btScalar dn = btDot(vr, vr); // dn is the normal component of velocity diffrerence. Approximates the residual. // todo xuchenhan@: this prob needs to be scaled by dt btScalar residualSquare = dn * dn; btVector3 impulse = m_anchor->m_c0 * vr; // apply impulse to deformable nodes involved and change their velocities applyImpulse(impulse); // apply impulse to the rigid/multibodies involved and change their velocities if (cti.m_colObj->getInternalType() == btCollisionObject::CO_RIGID_BODY) { btRigidBody* rigidCol = 0; rigidCol = (btRigidBody*)btRigidBody::upcast(cti.m_colObj); if (rigidCol) { rigidCol->applyImpulse(impulse, m_anchor->m_c1); } } else if (cti.m_colObj->getInternalType() == btCollisionObject::CO_FEATHERSTONE_LINK) { btMultiBodyLinkCollider* multibodyLinkCol = 0; multibodyLinkCol = (btMultiBodyLinkCollider*)btMultiBodyLinkCollider::upcast(cti.m_colObj); if (multibodyLinkCol) { const btScalar* deltaV_normal = &m_anchor->jacobianData_normal.m_deltaVelocitiesUnitImpulse[0]; // apply normal component of the impulse multibodyLinkCol->m_multiBody->applyDeltaVeeMultiDof2(deltaV_normal, impulse.dot(cti.m_normal)); // apply tangential component of the impulse const btScalar* deltaV_t1 = &m_anchor->jacobianData_t1.m_deltaVelocitiesUnitImpulse[0]; multibodyLinkCol->m_multiBody->applyDeltaVeeMultiDof2(deltaV_t1, impulse.dot(m_anchor->t1)); const btScalar* deltaV_t2 = &m_anchor->jacobianData_t2.m_deltaVelocitiesUnitImpulse[0]; multibodyLinkCol->m_multiBody->applyDeltaVeeMultiDof2(deltaV_t2, impulse.dot(m_anchor->t2)); } } return residualSquare; } btVector3 btDeformableNodeAnchorConstraint::getVb() const { return m_anchor->m_node->m_v; } void btDeformableNodeAnchorConstraint::applyImpulse(const btVector3& impulse) { btVector3 dv = impulse * m_anchor->m_c2; m_anchor->m_node->m_v -= dv; } /* ================ Deformable vs. Rigid =================== */ btDeformableRigidContactConstraint::btDeformableRigidContactConstraint(const btSoftBody::DeformableRigidContact& c, const btContactSolverInfo& infoGlobal) : m_contact(&c), btDeformableContactConstraint(c.m_cti.m_normal, infoGlobal) { m_total_normal_dv.setZero(); m_total_tangent_dv.setZero(); // The magnitude of penetration is the depth of penetration. m_penetration = c.m_cti.m_offset; m_total_split_impulse = 0; m_binding = false; } btDeformableRigidContactConstraint::btDeformableRigidContactConstraint(const btDeformableRigidContactConstraint& other) : m_contact(other.m_contact), btDeformableContactConstraint(other), m_penetration(other.m_penetration), m_total_split_impulse(other.m_total_split_impulse), m_binding(other.m_binding) { m_total_normal_dv = other.m_total_normal_dv; m_total_tangent_dv = other.m_total_tangent_dv; } btVector3 btDeformableRigidContactConstraint::getVa() const { const btSoftBody::sCti& cti = m_contact->m_cti; btVector3 va(0, 0, 0); if (cti.m_colObj->hasContactResponse()) { btRigidBody* rigidCol = 0; btMultiBodyLinkCollider* multibodyLinkCol = 0; // grab the velocity of the rigid body if (cti.m_colObj->getInternalType() == btCollisionObject::CO_RIGID_BODY) { rigidCol = (btRigidBody*)btRigidBody::upcast(cti.m_colObj); va = rigidCol ? (rigidCol->getVelocityInLocalPoint(m_contact->m_c1)) : btVector3(0, 0, 0); } else if (cti.m_colObj->getInternalType() == btCollisionObject::CO_FEATHERSTONE_LINK) { multibodyLinkCol = (btMultiBodyLinkCollider*)btMultiBodyLinkCollider::upcast(cti.m_colObj); if (multibodyLinkCol) { const int ndof = multibodyLinkCol->m_multiBody->getNumDofs() + 6; const btScalar* J_n = &m_contact->jacobianData_normal.m_jacobians[0]; const btScalar* J_t1 = &m_contact->jacobianData_t1.m_jacobians[0]; const btScalar* J_t2 = &m_contact->jacobianData_t2.m_jacobians[0]; const btScalar* local_v = multibodyLinkCol->m_multiBody->getVelocityVector(); const btScalar* local_dv = multibodyLinkCol->m_multiBody->getDeltaVelocityVector(); // add in the normal component of the va btScalar vel = 0.0; for (int k = 0; k < ndof; ++k) { vel += (local_v[k] + local_dv[k]) * J_n[k]; } va = cti.m_normal * vel; // add in the tangential components of the va vel = 0.0; for (int k = 0; k < ndof; ++k) { vel += (local_v[k] + local_dv[k]) * J_t1[k]; } va += m_contact->t1 * vel; vel = 0.0; for (int k = 0; k < ndof; ++k) { vel += (local_v[k] + local_dv[k]) * J_t2[k]; } va += m_contact->t2 * vel; } } } return va; } btVector3 btDeformableRigidContactConstraint::getSplitVa() const { const btSoftBody::sCti& cti = m_contact->m_cti; btVector3 va(0, 0, 0); if (cti.m_colObj->hasContactResponse()) { btRigidBody* rigidCol = 0; btMultiBodyLinkCollider* multibodyLinkCol = 0; // grab the velocity of the rigid body if (cti.m_colObj->getInternalType() == btCollisionObject::CO_RIGID_BODY) { rigidCol = (btRigidBody*)btRigidBody::upcast(cti.m_colObj); va = rigidCol ? (rigidCol->getPushVelocityInLocalPoint(m_contact->m_c1)) : btVector3(0, 0, 0); } else if (cti.m_colObj->getInternalType() == btCollisionObject::CO_FEATHERSTONE_LINK) { multibodyLinkCol = (btMultiBodyLinkCollider*)btMultiBodyLinkCollider::upcast(cti.m_colObj); if (multibodyLinkCol) { const int ndof = multibodyLinkCol->m_multiBody->getNumDofs() + 6; const btScalar* J_n = &m_contact->jacobianData_normal.m_jacobians[0]; const btScalar* J_t1 = &m_contact->jacobianData_t1.m_jacobians[0]; const btScalar* J_t2 = &m_contact->jacobianData_t2.m_jacobians[0]; const btScalar* local_split_v = multibodyLinkCol->m_multiBody->getSplitVelocityVector(); // add in the normal component of the va btScalar vel = 0.0; for (int k = 0; k < ndof; ++k) { vel += local_split_v[k] * J_n[k]; } va = cti.m_normal * vel; // add in the tangential components of the va vel = 0.0; for (int k = 0; k < ndof; ++k) { vel += local_split_v[k] * J_t1[k]; } va += m_contact->t1 * vel; vel = 0.0; for (int k = 0; k < ndof; ++k) { vel += local_split_v[k] * J_t2[k]; } va += m_contact->t2 * vel; } } } return va; } btScalar btDeformableRigidContactConstraint::solveConstraint(const btContactSolverInfo& infoGlobal) { const btSoftBody::sCti& cti = m_contact->m_cti; btVector3 va = getVa(); btVector3 vb = getVb(); btVector3 vr = vb - va; btScalar dn = btDot(vr, cti.m_normal) + m_total_normal_dv.dot(cti.m_normal) * infoGlobal.m_deformable_cfm; if (m_penetration > 0) { dn += m_penetration / infoGlobal.m_timeStep; } if (!infoGlobal.m_splitImpulse) { dn += m_penetration * infoGlobal.m_deformable_erp / infoGlobal.m_timeStep; } // dn is the normal component of velocity diffrerence. Approximates the residual. // todo xuchenhan@: this prob needs to be scaled by dt btVector3 impulse = m_contact->m_c0 * (vr + m_total_normal_dv * infoGlobal.m_deformable_cfm + ((m_penetration > 0) ? m_penetration / infoGlobal.m_timeStep * cti.m_normal : btVector3(0, 0, 0))); if (!infoGlobal.m_splitImpulse) { impulse += m_contact->m_c0 * (m_penetration * infoGlobal.m_deformable_erp / infoGlobal.m_timeStep * cti.m_normal); } btVector3 impulse_normal = m_contact->m_c0 * (cti.m_normal * dn); btVector3 impulse_tangent = impulse - impulse_normal; if (dn > 0) { return 0; } m_binding = true; btScalar residualSquare = dn * dn; btVector3 old_total_tangent_dv = m_total_tangent_dv; // m_c5 is the inverse mass of the deformable node/face m_total_normal_dv -= m_contact->m_c5 * impulse_normal; m_total_tangent_dv -= m_contact->m_c5 * impulse_tangent; if (m_total_normal_dv.dot(cti.m_normal) < 0) { // separating in the normal direction m_binding = false; m_static = false; impulse_tangent.setZero(); } else { if (m_total_normal_dv.norm() * m_contact->m_c3 < m_total_tangent_dv.norm()) { // dynamic friction // with dynamic friction, the impulse are still applied to the two objects colliding, however, it does not pose a constraint in the cg solve, hence the change to dv merely serves to update velocity in the contact iterations. m_static = false; if (m_total_tangent_dv.safeNorm() < SIMD_EPSILON) { m_total_tangent_dv = btVector3(0, 0, 0); } else { m_total_tangent_dv = m_total_tangent_dv.normalized() * m_total_normal_dv.safeNorm() * m_contact->m_c3; } // impulse_tangent = -btScalar(1)/m_contact->m_c2 * (m_total_tangent_dv - old_total_tangent_dv); impulse_tangent = m_contact->m_c5.inverse() * (old_total_tangent_dv - m_total_tangent_dv); } else { // static friction m_static = true; } } impulse = impulse_normal + impulse_tangent; // apply impulse to deformable nodes involved and change their velocities applyImpulse(impulse); // apply impulse to the rigid/multibodies involved and change their velocities if (cti.m_colObj->getInternalType() == btCollisionObject::CO_RIGID_BODY) { btRigidBody* rigidCol = 0; rigidCol = (btRigidBody*)btRigidBody::upcast(cti.m_colObj); if (rigidCol) { rigidCol->applyImpulse(impulse, m_contact->m_c1); } } else if (cti.m_colObj->getInternalType() == btCollisionObject::CO_FEATHERSTONE_LINK) { btMultiBodyLinkCollider* multibodyLinkCol = 0; multibodyLinkCol = (btMultiBodyLinkCollider*)btMultiBodyLinkCollider::upcast(cti.m_colObj); if (multibodyLinkCol) { const btScalar* deltaV_normal = &m_contact->jacobianData_normal.m_deltaVelocitiesUnitImpulse[0]; // apply normal component of the impulse multibodyLinkCol->m_multiBody->applyDeltaVeeMultiDof2(deltaV_normal, impulse.dot(cti.m_normal)); if (impulse_tangent.norm() > SIMD_EPSILON) { // apply tangential component of the impulse const btScalar* deltaV_t1 = &m_contact->jacobianData_t1.m_deltaVelocitiesUnitImpulse[0]; multibodyLinkCol->m_multiBody->applyDeltaVeeMultiDof2(deltaV_t1, impulse.dot(m_contact->t1)); const btScalar* deltaV_t2 = &m_contact->jacobianData_t2.m_deltaVelocitiesUnitImpulse[0]; multibodyLinkCol->m_multiBody->applyDeltaVeeMultiDof2(deltaV_t2, impulse.dot(m_contact->t2)); } } } return residualSquare; } btScalar btDeformableRigidContactConstraint::solveSplitImpulse(const btContactSolverInfo& infoGlobal) { btScalar MAX_PENETRATION_CORRECTION = infoGlobal.m_deformable_maxErrorReduction; const btSoftBody::sCti& cti = m_contact->m_cti; btVector3 vb = getSplitVb(); btVector3 va = getSplitVa(); btScalar p = m_penetration; if (p > 0) { return 0; } btVector3 vr = vb - va; btScalar dn = btDot(vr, cti.m_normal) + p * infoGlobal.m_deformable_erp / infoGlobal.m_timeStep; if (dn > 0) { return 0; } if (m_total_split_impulse + dn > MAX_PENETRATION_CORRECTION) { dn = MAX_PENETRATION_CORRECTION - m_total_split_impulse; } if (m_total_split_impulse + dn < -MAX_PENETRATION_CORRECTION) { dn = -MAX_PENETRATION_CORRECTION - m_total_split_impulse; } m_total_split_impulse += dn; btScalar residualSquare = dn * dn; const btVector3 impulse = m_contact->m_c0 * (cti.m_normal * dn); applySplitImpulse(impulse); // apply split impulse to the rigid/multibodies involved and change their velocities if (cti.m_colObj->getInternalType() == btCollisionObject::CO_RIGID_BODY) { btRigidBody* rigidCol = 0; rigidCol = (btRigidBody*)btRigidBody::upcast(cti.m_colObj); if (rigidCol) { rigidCol->applyPushImpulse(impulse, m_contact->m_c1); } } else if (cti.m_colObj->getInternalType() == btCollisionObject::CO_FEATHERSTONE_LINK) { btMultiBodyLinkCollider* multibodyLinkCol = 0; multibodyLinkCol = (btMultiBodyLinkCollider*)btMultiBodyLinkCollider::upcast(cti.m_colObj); if (multibodyLinkCol) { const btScalar* deltaV_normal = &m_contact->jacobianData_normal.m_deltaVelocitiesUnitImpulse[0]; // apply normal component of the impulse multibodyLinkCol->m_multiBody->applyDeltaSplitVeeMultiDof(deltaV_normal, impulse.dot(cti.m_normal)); } } return residualSquare; } /* ================ Node vs. Rigid =================== */ btDeformableNodeRigidContactConstraint::btDeformableNodeRigidContactConstraint(const btSoftBody::DeformableNodeRigidContact& contact, const btContactSolverInfo& infoGlobal) : m_node(contact.m_node), btDeformableRigidContactConstraint(contact, infoGlobal) { } btDeformableNodeRigidContactConstraint::btDeformableNodeRigidContactConstraint(const btDeformableNodeRigidContactConstraint& other) : m_node(other.m_node), btDeformableRigidContactConstraint(other) { } btVector3 btDeformableNodeRigidContactConstraint::getVb() const { return m_node->m_v; } btVector3 btDeformableNodeRigidContactConstraint::getSplitVb() const { return m_node->m_splitv; } btVector3 btDeformableNodeRigidContactConstraint::getDv(const btSoftBody::Node* node) const { return m_total_normal_dv + m_total_tangent_dv; } void btDeformableNodeRigidContactConstraint::applyImpulse(const btVector3& impulse) { const btSoftBody::DeformableNodeRigidContact* contact = getContact(); btVector3 dv = contact->m_c5 * impulse; contact->m_node->m_v -= dv; } void btDeformableNodeRigidContactConstraint::applySplitImpulse(const btVector3& impulse) { const btSoftBody::DeformableNodeRigidContact* contact = getContact(); btVector3 dv = contact->m_c5 * impulse; contact->m_node->m_splitv -= dv; } /* ================ Face vs. Rigid =================== */ btDeformableFaceRigidContactConstraint::btDeformableFaceRigidContactConstraint(const btSoftBody::DeformableFaceRigidContact& contact, const btContactSolverInfo& infoGlobal, bool useStrainLimiting) : m_face(contact.m_face), m_useStrainLimiting(useStrainLimiting), btDeformableRigidContactConstraint(contact, infoGlobal) { } btDeformableFaceRigidContactConstraint::btDeformableFaceRigidContactConstraint(const btDeformableFaceRigidContactConstraint& other) : m_face(other.m_face), m_useStrainLimiting(other.m_useStrainLimiting), btDeformableRigidContactConstraint(other) { } btVector3 btDeformableFaceRigidContactConstraint::getVb() const { const btSoftBody::DeformableFaceRigidContact* contact = getContact(); btVector3 vb = m_face->m_n[0]->m_v * contact->m_bary[0] + m_face->m_n[1]->m_v * contact->m_bary[1] + m_face->m_n[2]->m_v * contact->m_bary[2]; return vb; } btVector3 btDeformableFaceRigidContactConstraint::getDv(const btSoftBody::Node* node) const { btVector3 face_dv = m_total_normal_dv + m_total_tangent_dv; const btSoftBody::DeformableFaceRigidContact* contact = getContact(); if (m_face->m_n[0] == node) { return face_dv * contact->m_weights[0]; } if (m_face->m_n[1] == node) { return face_dv * contact->m_weights[1]; } btAssert(node == m_face->m_n[2]); return face_dv * contact->m_weights[2]; } void btDeformableFaceRigidContactConstraint::applyImpulse(const btVector3& impulse) { const btSoftBody::DeformableFaceRigidContact* contact = getContact(); btVector3 dv = impulse * contact->m_c2; btSoftBody::Face* face = contact->m_face; btVector3& v0 = face->m_n[0]->m_v; btVector3& v1 = face->m_n[1]->m_v; btVector3& v2 = face->m_n[2]->m_v; const btScalar& im0 = face->m_n[0]->m_im; const btScalar& im1 = face->m_n[1]->m_im; const btScalar& im2 = face->m_n[2]->m_im; if (im0 > 0) v0 -= dv * contact->m_weights[0]; if (im1 > 0) v1 -= dv * contact->m_weights[1]; if (im2 > 0) v2 -= dv * contact->m_weights[2]; if (m_useStrainLimiting) { btScalar relaxation = 1. / btScalar(m_infoGlobal->m_numIterations); btScalar m01 = (relaxation / (im0 + im1)); btScalar m02 = (relaxation / (im0 + im2)); btScalar m12 = (relaxation / (im1 + im2)); #ifdef USE_STRAIN_RATE_LIMITING // apply strain limiting to prevent the new velocity to change the current length of the edge by more than 1%. btScalar p = 0.01; btVector3& x0 = face->m_n[0]->m_x; btVector3& x1 = face->m_n[1]->m_x; btVector3& x2 = face->m_n[2]->m_x; const btVector3 x_diff[3] = {x1 - x0, x2 - x0, x2 - x1}; const btVector3 v_diff[3] = {v1 - v0, v2 - v0, v2 - v1}; btVector3 u[3]; btScalar x_diff_dot_u, dn[3]; btScalar dt = m_infoGlobal->m_timeStep; for (int i = 0; i < 3; ++i) { btScalar x_diff_norm = x_diff[i].safeNorm(); btScalar x_diff_norm_new = (x_diff[i] + v_diff[i] * dt).safeNorm(); btScalar strainRate = x_diff_norm_new / x_diff_norm; u[i] = v_diff[i]; u[i].safeNormalize(); if (x_diff_norm == 0 || (1 - p <= strainRate && strainRate <= 1 + p)) { dn[i] = 0; continue; } x_diff_dot_u = btDot(x_diff[i], u[i]); btScalar s; if (1 - p > strainRate) { s = 1 / dt * (-x_diff_dot_u - btSqrt(x_diff_dot_u * x_diff_dot_u + (p * p - 2 * p) * x_diff_norm * x_diff_norm)); } else { s = 1 / dt * (-x_diff_dot_u + btSqrt(x_diff_dot_u * x_diff_dot_u + (p * p + 2 * p) * x_diff_norm * x_diff_norm)); } // x_diff_norm_new = (x_diff[i] + s * u[i] * dt).safeNorm(); // strainRate = x_diff_norm_new/x_diff_norm; dn[i] = s - v_diff[i].safeNorm(); } btVector3 dv0 = im0 * (m01 * u[0] * (-dn[0]) + m02 * u[1] * -(dn[1])); btVector3 dv1 = im1 * (m01 * u[0] * (dn[0]) + m12 * u[2] * (-dn[2])); btVector3 dv2 = im2 * (m12 * u[2] * (dn[2]) + m02 * u[1] * (dn[1])); #else // apply strain limiting to prevent undamped modes btVector3 dv0 = im0 * (m01 * (v1 - v0) + m02 * (v2 - v0)); btVector3 dv1 = im1 * (m01 * (v0 - v1) + m12 * (v2 - v1)); btVector3 dv2 = im2 * (m12 * (v1 - v2) + m02 * (v0 - v2)); #endif v0 += dv0; v1 += dv1; v2 += dv2; } } btVector3 btDeformableFaceRigidContactConstraint::getSplitVb() const { const btSoftBody::DeformableFaceRigidContact* contact = getContact(); btVector3 vb = (m_face->m_n[0]->m_splitv) * contact->m_bary[0] + (m_face->m_n[1]->m_splitv) * contact->m_bary[1] + (m_face->m_n[2]->m_splitv) * contact->m_bary[2]; return vb; } void btDeformableFaceRigidContactConstraint::applySplitImpulse(const btVector3& impulse) { const btSoftBody::DeformableFaceRigidContact* contact = getContact(); btVector3 dv = impulse * contact->m_c2; btSoftBody::Face* face = contact->m_face; btVector3& v0 = face->m_n[0]->m_splitv; btVector3& v1 = face->m_n[1]->m_splitv; btVector3& v2 = face->m_n[2]->m_splitv; const btScalar& im0 = face->m_n[0]->m_im; const btScalar& im1 = face->m_n[1]->m_im; const btScalar& im2 = face->m_n[2]->m_im; if (im0 > 0) { v0 -= dv * contact->m_weights[0]; } if (im1 > 0) { v1 -= dv * contact->m_weights[1]; } if (im2 > 0) { v2 -= dv * contact->m_weights[2]; } } /* ================ Face vs. Node =================== */ btDeformableFaceNodeContactConstraint::btDeformableFaceNodeContactConstraint(const btSoftBody::DeformableFaceNodeContact& contact, const btContactSolverInfo& infoGlobal) : m_node(contact.m_node), m_face(contact.m_face), m_contact(&contact), btDeformableContactConstraint(contact.m_normal, infoGlobal) { m_total_normal_dv.setZero(); m_total_tangent_dv.setZero(); } btVector3 btDeformableFaceNodeContactConstraint::getVa() const { return m_node->m_v; } btVector3 btDeformableFaceNodeContactConstraint::getVb() const { const btSoftBody::DeformableFaceNodeContact* contact = getContact(); btVector3 vb = m_face->m_n[0]->m_v * contact->m_bary[0] + m_face->m_n[1]->m_v * contact->m_bary[1] + m_face->m_n[2]->m_v * contact->m_bary[2]; return vb; } btVector3 btDeformableFaceNodeContactConstraint::getDv(const btSoftBody::Node* n) const { btVector3 dv = m_total_normal_dv + m_total_tangent_dv; if (n == m_node) return dv; const btSoftBody::DeformableFaceNodeContact* contact = getContact(); if (m_face->m_n[0] == n) { return dv * contact->m_weights[0]; } if (m_face->m_n[1] == n) { return dv * contact->m_weights[1]; } btAssert(n == m_face->m_n[2]); return dv * contact->m_weights[2]; } btScalar btDeformableFaceNodeContactConstraint::solveConstraint(const btContactSolverInfo& infoGlobal) { btVector3 va = getVa(); btVector3 vb = getVb(); btVector3 vr = vb - va; const btScalar dn = btDot(vr, m_contact->m_normal); // dn is the normal component of velocity diffrerence. Approximates the residual. // todo xuchenhan@: this prob needs to be scaled by dt btScalar residualSquare = dn * dn; btVector3 impulse = m_contact->m_c0 * vr; const btVector3 impulse_normal = m_contact->m_c0 * (m_contact->m_normal * dn); btVector3 impulse_tangent = impulse - impulse_normal; btVector3 old_total_tangent_dv = m_total_tangent_dv; // m_c2 is the inverse mass of the deformable node/face if (m_node->m_im > 0) { m_total_normal_dv -= impulse_normal * m_node->m_im; m_total_tangent_dv -= impulse_tangent * m_node->m_im; } else { m_total_normal_dv -= impulse_normal * m_contact->m_imf; m_total_tangent_dv -= impulse_tangent * m_contact->m_imf; } if (m_total_normal_dv.dot(m_contact->m_normal) > 0) { // separating in the normal direction m_static = false; m_total_tangent_dv = btVector3(0, 0, 0); impulse_tangent.setZero(); } else { if (m_total_normal_dv.norm() * m_contact->m_friction < m_total_tangent_dv.norm()) { // dynamic friction // with dynamic friction, the impulse are still applied to the two objects colliding, however, it does not pose a constraint in the cg solve, hence the change to dv merely serves to update velocity in the contact iterations. m_static = false; if (m_total_tangent_dv.safeNorm() < SIMD_EPSILON) { m_total_tangent_dv = btVector3(0, 0, 0); } else { m_total_tangent_dv = m_total_tangent_dv.normalized() * m_total_normal_dv.safeNorm() * m_contact->m_friction; } impulse_tangent = -btScalar(1) / m_node->m_im * (m_total_tangent_dv - old_total_tangent_dv); } else { // static friction m_static = true; } } impulse = impulse_normal + impulse_tangent; // apply impulse to deformable nodes involved and change their velocities applyImpulse(impulse); return residualSquare; } void btDeformableFaceNodeContactConstraint::applyImpulse(const btVector3& impulse) { const btSoftBody::DeformableFaceNodeContact* contact = getContact(); btVector3 dva = impulse * contact->m_node->m_im; btVector3 dvb = impulse * contact->m_imf; if (contact->m_node->m_im > 0) { contact->m_node->m_v += dva; } btSoftBody::Face* face = contact->m_face; btVector3& v0 = face->m_n[0]->m_v; btVector3& v1 = face->m_n[1]->m_v; btVector3& v2 = face->m_n[2]->m_v; const btScalar& im0 = face->m_n[0]->m_im; const btScalar& im1 = face->m_n[1]->m_im; const btScalar& im2 = face->m_n[2]->m_im; if (im0 > 0) { v0 -= dvb * contact->m_weights[0]; } if (im1 > 0) { v1 -= dvb * contact->m_weights[1]; } if (im2 > 0) { v2 -= dvb * contact->m_weights[2]; } }
0
0.953649
1
0.953649
game-dev
MEDIA
0.976266
game-dev
0.984034
1
0.984034
valence-rs/valence
1,358
crates/valence_lang/build.rs
use heck::ToShoutySnakeCase; use proc_macro2::TokenStream; use quote::quote; use serde::Deserialize; use valence_build_utils::{ident, rerun_if_changed, write_generated_file}; pub fn main() -> anyhow::Result<()> { write_generated_file(build()?, "translation_keys.rs") } fn build() -> anyhow::Result<TokenStream> { rerun_if_changed(["extracted/translation_keys.json"]); let translations = serde_json::from_str::<Vec<Translation>>(include_str!("extracted/translation_keys.json"))?; let translation_key_consts = translations .iter() .map(|translation| { let const_id = ident(translation.key.to_shouty_snake_case()); let key = &translation.key; let english_translation = &translation.english_translation; let doc = format!("\"{}\"", escape(english_translation)).replace('`', "\\`"); quote! { #[doc = #doc] pub const #const_id: &str = #key; } }) .collect::<Vec<TokenStream>>(); Ok(quote! { #(#translation_key_consts)* }) } #[derive(Deserialize, Clone, Debug)] struct Translation { key: String, english_translation: String, } /// Escapes characters that have special meaning inside docs. fn escape(text: &str) -> String { text.replace('[', "\\[").replace(']', "\\]") }
0
0.89738
1
0.89738
game-dev
MEDIA
0.398138
game-dev
0.90352
1
0.90352
pWn3d1337/Techguns2
14,680
src/main/java/techguns/tileentities/ChemLabTileEnt.java
package techguns.tileentities; import java.util.Random; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.EnumParticleTypes; import net.minecraft.util.SoundCategory; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.TextComponentTranslation; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidActionResult; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidTank; import net.minecraftforge.fluids.FluidUtil; import net.minecraftforge.fluids.capability.CapabilityFluidHandler; import net.minecraftforge.fluids.capability.FluidTankPropertiesWrapper; import net.minecraftforge.fluids.capability.IFluidHandler; import net.minecraftforge.fluids.capability.IFluidHandlerItem; import net.minecraftforge.fluids.capability.IFluidTankProperties; import net.minecraftforge.items.CapabilityItemHandler; import net.minecraftforge.items.IItemHandler; import net.minecraftforge.oredict.OreDictionary; import techguns.TGItems; import techguns.TGSounds; import techguns.Techguns; import techguns.gui.ButtonConstants; import techguns.tileentities.operation.ChemLabRecipes; import techguns.tileentities.operation.FluidTankPlus; import techguns.tileentities.operation.ITileEntityFluidTanks; import techguns.tileentities.operation.ItemStackHandlerPlus; import techguns.tileentities.operation.MachineOperation; import techguns.tileentities.operation.MachineSlotFluid; import techguns.tileentities.operation.MachineSlotItem; import techguns.util.ItemUtil; public class ChemLabTileEnt extends BasicMachineTileEnt implements ITileEntityFluidTanks{ private Random rng = new Random(); protected static final float SOUND_VOLUME=0.65f; public static final int BUTTON_ID_DUMP_INPUT = ButtonConstants.BUTTON_ID_REDSTONE+1; public static final int BUTTON_ID_DUMP_OUTPUT = ButtonConstants.BUTTON_ID_REDSTONE+2; public static final int BUTTON_ID_TOGGLE_DRAIN = ButtonConstants.BUTTON_ID_REDSTONE+3; public ChemLabFluidHandler fluidHandler; public FluidTank inputTank; public FluidTank outputTank; protected boolean drainInput=false; public static final int SLOT_INPUT1=0; public static final int SLOT_INPUT2=1; public static final int SLOT_BOTTLE=2; public static final int SLOT_OUTPUT=3; public static final int SLOT_UPGRADE=4; public MachineSlotItem input1; public MachineSlotItem input2; public MachineSlotItem input_bottle; public MachineSlotFluid input_fluid; public static final int CAPACITY_INPUT_TANK=8*Fluid.BUCKET_VOLUME; public static final int CAPACITY_OUTPUT_TANK=16*Fluid.BUCKET_VOLUME; public ChemLabTileEnt() { super(5, true, 20000); this.inputTank = new FluidTankPlus(this,CAPACITY_INPUT_TANK); this.inputTank.setTileEntity(this); this.outputTank = new FluidTankPlus(this,CAPACITY_OUTPUT_TANK); this.outputTank.setTileEntity(this); this.fluidHandler= new ChemLabFluidHandler(this); input1 = new MachineSlotItem(this, SLOT_INPUT1); input2 = new MachineSlotItem(this, SLOT_INPUT2); input_bottle = new MachineSlotItem(this, SLOT_BOTTLE); input_fluid = new MachineSlotFluid(inputTank); this.inventory = new ItemStackHandlerPlus(5) { @Override protected void onContentsChanged(int slot) { super.onContentsChanged(slot); setContentsChanged(true); } @Override protected boolean allowItemInSlot(int slot, ItemStack stack) { switch (slot) { case SLOT_INPUT1: case SLOT_INPUT2: case SLOT_BOTTLE: return isItemValidForSlot(slot, stack); case SLOT_OUTPUT: return false; case SLOT_UPGRADE: return TGItems.isMachineUpgrade(stack); } return false; } @Override protected boolean allowExtractFromSlot(int slot, int amount) { return slot == SLOT_OUTPUT; } }; } @Override public ITextComponent getDisplayName() { return new TextComponentTranslation(Techguns.MODID+".container.chemlab", new Object[0]); } @Override public boolean hasCapability(Capability<?> capability, EnumFacing facing) { return capability == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY || super.hasCapability(capability, facing); } @Override public <T> T getCapability(Capability<T> capability, EnumFacing facing) { return capability == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY ? (T)fluidHandler : super.getCapability(capability, facing); } public boolean isItemValidForSlot(int slot, ItemStack item) { if(slot==SLOT_BOTTLE){ return ChemLabRecipes.allowInFlaskSlot(item); } else if(slot==SLOT_INPUT1 && this.input1.get().isEmpty() && this.input2.get().isEmpty()){ return !ChemLabRecipes.allowInFlaskSlot(item) && ChemLabRecipes.hasRecipeUsing(item); } else if (slot==SLOT_INPUT1 && this.input1.get().isEmpty() && !this.input2.get().isEmpty()){ return !ChemLabRecipes.allowInFlaskSlot(item) && ChemLabRecipes.allowAsInput2(this.input2.get(), item); } else if (slot==SLOT_INPUT1 && !this.input1.get().isEmpty()){ return ItemUtil.isItemEqual(this.input1.get(), item); } else if (slot==SLOT_INPUT2 && !this.input1.get().isEmpty()){ return !ChemLabRecipes.allowInFlaskSlot(item) && ChemLabRecipes.allowAsInput2(this.input1.get(), item); } else if (slot==SLOT_INPUT2 && !this.input2.get().isEmpty()){ return ItemUtil.isItemEqual(this.input2.get(), item); } return false; } @Override public void readClientDataFromNBT(NBTTagCompound tags) { super.readClientDataFromNBT(tags); drainInput=tags.getBoolean("drainInput"); NBTTagCompound inputTankTags = tags.getCompoundTag("inputTank"); this.inputTank.readFromNBT(inputTankTags); NBTTagCompound outputTankTags = tags.getCompoundTag("outputTank"); this.outputTank.readFromNBT(outputTankTags); } @Override public void writeClientDataToNBT(NBTTagCompound tags) { super.writeClientDataToNBT(tags); tags.setBoolean("drainInput", this.drainInput); NBTTagCompound inputTankTags = new NBTTagCompound(); this.inputTank.writeToNBT(inputTankTags); tags.setTag("inputTank", inputTankTags); NBTTagCompound outputTankTags = new NBTTagCompound(); this.outputTank.writeToNBT(outputTankTags); tags.setTag("outputTank", outputTankTags); } @Override protected int getNeededPower() { if(this.currentOperation!=null) { return this.currentOperation.getPowerPerTick(); } return 0; } protected boolean canOutput(MachineOperation output) { if (this.canOutput(output.getItemOutput0(),SLOT_OUTPUT)){ // check liquid output FluidStack out = output.getFluidOutput0(); if (out==null) { return true; } else { return this.outputTank.canFillFluidType(out) && this.outputTank.fill(out, false)==out.amount; } } return false; } protected boolean canConsume(MachineOperation output) { int multi = output.getStackMultiplier(); ItemStack in1 = output.getInputs().get(0); ItemStack in2 = output.getInputs().get(1); ItemStack bottle = output.getInputs().get(2); FluidStack fluidIn =null; int amount=0; if (!output.getFluid_inputs().isEmpty()) { fluidIn = output.getFluid_inputs().get(0); if (fluidIn!=null) { amount=fluidIn.amount; } } return this.input1.canConsumeWithMultiplier(in1,multi) && this.input2.canConsumeWithMultiplier(in2,multi) && this.input_bottle.canConsumeWithMultiplier(bottle,multi) && this.input_fluid.canConsume(amount*multi); } protected void consume(MachineOperation output) { this.input1.consume(output.getNeededAmountItem(SLOT_INPUT1)); this.input2.consume(output.getNeededAmountItem(SLOT_INPUT2)); this.input_bottle.consume(output.getNeededAmountItem(SLOT_BOTTLE)); this.input_fluid.consume(output.getNeededAmountFluid(0)); } @Override protected void checkAndStartOperation() { this.setContentsChanged(false); MachineOperation op = ChemLabRecipes.getOutputFor(this); if (op != null && canOutput(op)) { //check multiplier int maxStack=this.getMaxMachineUpgradeMultiplier(SLOT_UPGRADE); int multiplier=1; //try higher stacksize int i; for (i=maxStack;i>1;--i){ op.setStackMultiplier(i); if(this.canOutput(op) && canConsume(op)){ multiplier=i; break; } } op.setStackMultiplier(multiplier); //drain this.consume(op); this.currentOperation = op; this.progress = 0; this.totaltime = 100; if (!this.world.isRemote) { this.needUpdate(); } } } @Override protected void finishedOperation() { ItemStack itemOut = this.currentOperation.getItemOutput0(); if (!itemOut.isEmpty()) { if (!this.inventory.getStackInSlot(SLOT_OUTPUT).isEmpty()) { this.inventory.insertItemNoCheck(SLOT_OUTPUT, itemOut, false); //this.inventory.getStackInSlot(SLOT_OUTPUT).grow(itemOut.getCount()); } else { this.inventory.setStackInSlot(SLOT_OUTPUT, itemOut); } } FluidStack fluidOut = this.currentOperation.getFluidOutput0(); if(fluidOut!=null) { this.outputTank.fillInternal(fluidOut, true); } } @Override protected void playAmbientSound() { int soundTick1 = 1; int halfTime = (Math.round((float) totaltime * 0.5f)); if (this.progress == soundTick1 || this.progress == soundTick1 + halfTime) { //worldObj.playSound(this.xCoord, this.yCoord, this.zCoord, "techguns:machines.chemlabWork", 1.0F, 1.0F, true); world.playSound(this.getPos().getX(), this.getPos().getY(), this.getPos().getZ(), TGSounds.CHEM_LAB_WORK,SoundCategory.BLOCKS, SOUND_VOLUME, 1.0F, true ); } if ( this.world.isRemote) { int delay = 10; if (this.progress % delay == 0) { world.spawnParticle(EnumParticleTypes.SPELL, this.getPos().getX()+0.5d + rng.nextFloat(), this.getPos().getY()+0.5d + rng.nextFloat(), this.getPos().getZ()+0.5d + rng.nextFloat(), 0, 1, 0); } } } public FluidStack getCurrentInputFluid() { return this.inputTank.getFluid(); } public FluidStack getCurrentOutputFluid() { return this.outputTank.getFluid(); } public int getValidSlotForItemInMachine(ItemStack item) { if (ChemLabRecipes.allowInFlaskSlot(item)) { if (this.input_bottle.get().isEmpty()) { return SLOT_BOTTLE; } else if (OreDictionary.itemMatches(this.input_bottle.get(), item, true)) { return SLOT_BOTTLE; } } else if (!this.input1.get().isEmpty() && OreDictionary.itemMatches(this.input1.get(), item, true)) { return SLOT_INPUT1; } else if (!this.input2.get().isEmpty() && OreDictionary.itemMatches(this.input2.get(), item, true)) { return SLOT_INPUT2; } else if (this.input1.get().isEmpty() && ChemLabRecipes.hasRecipeUsing(item)) { return SLOT_INPUT1; } else if (!this.input1.get().isEmpty() && this.input2.get().isEmpty() && (ChemLabRecipes.allowAsInput2(this.input1.get(), item))) { return SLOT_INPUT2; } else if (TGItems.isMachineUpgrade(item)) { return SLOT_UPGRADE; } return -1; } @Override public void saveTanksToNBT(NBTTagCompound tags) { NBTTagCompound inputTankTags = new NBTTagCompound(); this.inputTank.writeToNBT(inputTankTags); tags.setTag("inputTank", inputTankTags); NBTTagCompound outputTankTags = new NBTTagCompound(); this.outputTank.writeToNBT(outputTankTags); tags.setTag("outputTank", outputTankTags); } @Override public void loadTanksFromNBT(NBTTagCompound tags) { NBTTagCompound inputTank = tags.getCompoundTag("inputTank"); this.inputTank.readFromNBT(inputTank); NBTTagCompound outputTank = tags.getCompoundTag("outputTank"); this.outputTank.readFromNBT(outputTank); } public byte getDrainMode() { return (byte) (this.drainInput?1:0); } @Override public void buttonClicked(int id, EntityPlayer ply, String data) { if(id<BUTTON_ID_DUMP_INPUT){ super.buttonClicked(id, ply, data); } else { if (this.isUseableByPlayer(ply)){ switch(id){ case BUTTON_ID_DUMP_INPUT: //drain input this.inputTank.setFluid(null); this.needUpdate(); break; case BUTTON_ID_DUMP_OUTPUT: //drain output this.outputTank.setFluid(null); this.needUpdate(); break; case BUTTON_ID_TOGGLE_DRAIN: //toogle drain this.drainInput=!this.drainInput; this.needUpdate(); break; } } } } public static class ChemLabFluidHandler implements IFluidHandler { private ChemLabTileEnt tile; protected IFluidTankProperties[] tankProperties; public ChemLabFluidHandler(ChemLabTileEnt tile) { super(); this.tile = tile; } @Override public IFluidTankProperties[] getTankProperties() { if ( tankProperties == null) { this.tankProperties = new IFluidTankProperties[]{new FluidTankPropertiesWrapper(tile.inputTank), new FluidTankPropertiesWrapper(tile.outputTank)}; } return tankProperties; } @Override public int fill(FluidStack resource, boolean doFill) { return tile.inputTank.fill(resource, doFill); } @Override public FluidStack drain(FluidStack resource, boolean doDrain) { if(!tile.drainInput) { return tile.outputTank.drain(resource, doDrain); } else { return tile.inputTank.drain(resource, doDrain); } } @Override public FluidStack drain(int maxDrain, boolean doDrain) { if(!tile.drainInput) { return tile.outputTank.drain(maxDrain, doDrain); } else { return tile.inputTank.drain(maxDrain, doDrain); } } } @Override public boolean onFluidContainerInteract(EntityPlayer player, EnumHand hand, IFluidHandlerItem fluidhandleritem, ItemStack stack) { if(!this.isUseableByPlayer(player)) return false; boolean interacted = false; if(this.drainInput) { interacted = FluidUtil.interactWithFluidHandler(player, hand, this.inputTank); } else { IItemHandler playerInventory = player.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, null); if (playerInventory != null) { FluidActionResult fluidActionResult = FluidUtil.tryFillContainerAndStow(stack, this.outputTank, playerInventory, Integer.MAX_VALUE, player,true); if (!fluidActionResult.isSuccess()) { fluidActionResult = FluidUtil.tryEmptyContainerAndStow(stack, this.inputTank, playerInventory, Integer.MAX_VALUE, player, true); } if (fluidActionResult.isSuccess()) { player.setHeldItem(hand, fluidActionResult.getResult()); interacted=true; } } } return interacted; } }
0
0.900814
1
0.900814
game-dev
MEDIA
0.992985
game-dev
0.972999
1
0.972999
Cronus-Emulator/Cronus
290,133
src/map/battle.c
/*==================================================================\\ // _____ || // / __ \ || // | / \/_ __ ___ _ __ _ _ ___ || // | | | '__/ _ \| '_ \| | | / __| || // | \__/\ | | (_) | | | | |_| \__ \ || // \____/_| \___/|_| |_|\__,_|___/ || // Source - 2016 || //==================================================================|| // = Cdigo Base: || // - eAthena/Hercules/Cronus || //==================================================================|| // = Sobre: || // Este software livre: voc pode redistribu-lo e/ou modific-lo || // sob os termos da GNU General Public License conforme publicada || // pela Free Software Foundation, tanto a verso 3 da licena, ou || // (a seu critrio) qualquer verso posterior. || // || // Este programa distribudo na esperana de que possa ser til, || //mas SEM QUALQUER GARANTIA; mesmo sem a garantia implcita de || //COMERCIALIZAO ou ADEQUAO A UM DETERMINADO FIM. Veja a || //GNU General Public License para mais detalhes. || // || // Voc deve ter recebido uma cpia da Licena Pblica Geral GNU || // juntamente com este programa. Se no, veja: || // <http://www.gnu.org/licenses/>. || //==================================================================*/ #define CRONUS_CORE #include "config/core.h" // CELL_NOSTACK, CIRCULAR_AREA, CONSOLE_INPUT, HMAP_ZONE_DAMAGE_CAP_TYPE, OFFICIAL_WALKPATH, RENEWAL, RENEWAL_ASPD, RENEWAL_CAST, RENEWAL_DROP, RENEWAL_EDP, RENEWAL_EXP, RENEWAL_LVDMG, RE_LVL_DMOD(), RE_LVL_MDMOD(), RE_LVL_TMDMOD(), RE_SKILL_REDUCTION(), SCRIPT_CALLFUNC_CHECK, SECURE_NPCTIMEOUT, STATS_OPT_OUT #include "battle.h" #include "map/battleground.h" #include "map/chrif.h" #include "map/clif.h" #include "map/elemental.h" #include "map/guild.h" #include "map/homunculus.h" #include "map/itemdb.h" #include "map/map.h" #include "map/mercenary.h" #include "map/mob.h" #include "map/party.h" #include "map/path.h" #include "map/pc.h" #include "map/pet.h" #include "map/skill.h" #include "map/status.h" #include "common/HPM.h" #include "common/cbasetypes.h" #include "common/ers.h" #include "common/memmgr.h" #include "common/nullpo.h" #include "common/random.h" #include "common/showmsg.h" #include "common/socket.h" #include "common/strlib.h" #include "common/sysinfo.h" #include "common/timer.h" #include "common/utils.h" #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> struct Battle_Config battle_config; struct battle_interface battle_s; struct battle_interface *battle; int battle_getcurrentskill(struct block_list *bl) { //Returns the current/last skill in use by this bl. struct unit_data *ud; nullpo_ret(bl); if (bl->type == BL_SKILL) { struct skill_unit * su = (struct skill_unit*)bl; return su->group?su->group->skill_id:0; } ud = unit->bl2ud(bl); return ud?ud->skill_id:0; } /*========================================== * Get random targeting enemy *------------------------------------------*/ int battle_gettargeted_sub(struct block_list *bl, va_list ap) { struct block_list **bl_list; struct unit_data *ud; int target_id; int *c; nullpo_ret(bl); bl_list = va_arg(ap, struct block_list **); c = va_arg(ap, int *); target_id = va_arg(ap, int); if (bl->id == target_id) return 0; if (*c >= 24) return 0; if (!(ud = unit->bl2ud(bl))) return 0; if (ud->target == target_id || ud->skilltarget == target_id) { bl_list[(*c)++] = bl; return 1; } return 0; } struct block_list* battle_gettargeted(struct block_list *target) { struct block_list *bl_list[24]; int c = 0; nullpo_retr(NULL, target); memset(bl_list, 0, sizeof(bl_list)); map->foreachinrange(battle->get_targeted_sub, target, AREA_SIZE, BL_CHAR, bl_list, &c, target->id); if ( c == 0 ) return NULL; if( c > 24 ) c = 24; return bl_list[rnd()%c]; } //Returns the id of the current targeted character of the passed bl. [Skotlex] int battle_gettarget(struct block_list* bl) { nullpo_ret(bl); switch (bl->type) { case BL_PC: return ((struct map_session_data*)bl)->ud.target; case BL_MOB: return ((struct mob_data*)bl)->target_id; case BL_PET: return ((struct pet_data*)bl)->target_id; case BL_HOM: return ((struct homun_data*)bl)->ud.target; case BL_MER: return ((struct mercenary_data*)bl)->ud.target; case BL_ELEM: return ((struct elemental_data*)bl)->ud.target; } return 0; } int battle_getenemy_sub(struct block_list *bl, va_list ap) { struct block_list **bl_list; struct block_list *target; int *c; nullpo_ret(bl); bl_list = va_arg(ap, struct block_list **); c = va_arg(ap, int *); target = va_arg(ap, struct block_list *); if (bl->id == target->id) return 0; if (*c >= 24) return 0; if (status->isdead(bl)) return 0; if (battle->check_target(target, bl, BCT_ENEMY) > 0) { bl_list[(*c)++] = bl; return 1; } return 0; } // Picks a random enemy of the given type (BL_PC, BL_CHAR, etc) within the range given. [Skotlex] struct block_list* battle_getenemy(struct block_list *target, int type, int range) { struct block_list *bl_list[24]; int c = 0; nullpo_retr(NULL, target); memset(bl_list, 0, sizeof(bl_list)); map->foreachinrange(battle->get_enemy_sub, target, range, type, bl_list, &c, target); if ( c == 0 ) return NULL; if( c > 24 ) c = 24; return bl_list[rnd()%c]; } int battle_getenemyarea_sub(struct block_list *bl, va_list ap) { struct block_list **bl_list, *src; int *c, ignore_id; nullpo_ret(bl); bl_list = va_arg(ap, struct block_list **); nullpo_ret(bl_list); c = va_arg(ap, int *); nullpo_ret(c); src = va_arg(ap, struct block_list *); ignore_id = va_arg(ap, int); if( bl->id == src->id || bl->id == ignore_id ) return 0; // Ignores Caster and a possible pre-target if( *c >= 23 ) return 0; if( status->isdead(bl) ) return 0; if( battle->check_target(src, bl, BCT_ENEMY) > 0 ) {// Is Enemy!... bl_list[(*c)++] = bl; return 1; } return 0; } // Pick a random enemy struct block_list* battle_getenemyarea(struct block_list *src, int x, int y, int range, int type, int ignore_id) { struct block_list *bl_list[24]; int c = 0; nullpo_retr(NULL, src); memset(bl_list, 0, sizeof(bl_list)); map->foreachinarea(battle->get_enemy_area_sub, src->m, x - range, y - range, x + range, y + range, type, bl_list, &c, src, ignore_id); if( c == 0 ) return NULL; if( c >= 24 ) c = 23; return bl_list[rnd()%c]; } int battle_delay_damage_sub(int tid, int64 tick, int id, intptr_t data) { struct delay_damage *dat = (struct delay_damage *)data; if ( dat ) { struct block_list* src = NULL; struct block_list* target = map->id2bl(dat->target_id); if( !target || status->isdead(target) ) {/* nothing we can do */ if( dat->src_type == BL_PC && (src = map->id2bl(dat->src_id)) != NULL && --((TBL_PC*)src)->delayed_damage == 0 && ((TBL_PC*)src)->state.hold_recalc ) { ((TBL_PC*)src)->state.hold_recalc = 0; status_calc_pc(((TBL_PC*)src),SCO_FORCE); } ers_free(battle->delay_damage_ers, dat); return 0; } src = map->id2bl(dat->src_id); //Check to see if you haven't teleported. [Skotlex] if( src && (target->type != BL_PC || ((TBL_PC*)target)->invincible_timer == INVALID_TIMER) && (dat->skill_id == MO_EXTREMITYFIST || (target->m == src->m && check_distance_bl(src, target, dat->distance)) ) ) { map->freeblock_lock(); status_fix_damage(src, target, dat->damage, dat->delay); if( dat->attack_type && !status->isdead(target) && dat->additional_effects ) skill->additional_effect(src,target,dat->skill_id,dat->skill_lv,dat->attack_type,dat->dmg_lv,tick); if( dat->dmg_lv > ATK_BLOCK && dat->attack_type ) skill->counter_additional_effect(src,target,dat->skill_id,dat->skill_lv,dat->attack_type,tick); map->freeblock_unlock(); } else if( !src && dat->skill_id == CR_REFLECTSHIELD ) { /** * it was monster reflected damage, and the monster died, we pass the damage to the character as expected **/ map->freeblock_lock(); status_fix_damage(target, target, dat->damage, dat->delay); map->freeblock_unlock(); } if( src && src->type == BL_PC && --((TBL_PC*)src)->delayed_damage == 0 && ((TBL_PC*)src)->state.hold_recalc ) { ((TBL_PC*)src)->state.hold_recalc = 0; status_calc_pc(((TBL_PC*)src),SCO_FORCE); } } ers_free(battle->delay_damage_ers, dat); return 0; } int battle_delay_damage(int64 tick, int amotion, struct block_list *src, struct block_list *target, int attack_type, uint16 skill_id, uint16 skill_lv, int64 damage, enum damage_lv dmg_lv, int ddelay, bool additional_effects) { struct delay_damage *dat; struct status_change *sc; struct block_list *d_tbl = NULL; nullpo_ret(src); nullpo_ret(target); sc = status->get_sc(target); if (sc && sc->data[SC_DEVOTION] && sc->data[SC_DEVOTION]->val1) d_tbl = map->id2bl(sc->data[SC_DEVOTION]->val1); if (d_tbl && sc && check_distance_bl(target, d_tbl, sc->data[SC_DEVOTION]->val3) && damage > 0 && skill_id != PA_PRESSURE && skill_id != CR_REFLECTSHIELD) damage = 0; if ( !battle_config.delay_battle_damage || amotion <= 1 ) { map->freeblock_lock(); status_fix_damage(src, target, damage, ddelay); // We have to separate here between reflect damage and others [icescope] if( attack_type && !status->isdead(target) && additional_effects ) skill->additional_effect(src, target, skill_id, skill_lv, attack_type, dmg_lv, timer->gettick()); if( dmg_lv > ATK_BLOCK && attack_type ) skill->counter_additional_effect(src, target, skill_id, skill_lv, attack_type, timer->gettick()); map->freeblock_unlock(); return 0; } dat = ers_alloc(battle->delay_damage_ers, struct delay_damage); dat->src_id = src->id; dat->target_id = target->id; dat->skill_id = skill_id; dat->skill_lv = skill_lv; dat->attack_type = attack_type; dat->damage = damage; dat->dmg_lv = dmg_lv; dat->delay = ddelay; dat->distance = distance_bl(src, target) + (battle_config.snap_dodge ? 10 : battle_config.area_size); dat->additional_effects = additional_effects; dat->src_type = src->type; if (src->type != BL_PC && amotion > 1000) amotion = 1000; //Aegis places a damage-delay cap of 1 sec to non player attacks. [Skotlex] if( src->type == BL_PC ) { ((TBL_PC*)src)->delayed_damage++; } timer->add(tick+amotion, battle->delay_damage_sub, 0, (intptr_t)dat); return 0; } int battle_attr_ratio(int atk_elem,int def_type, int def_lv) { if (atk_elem < ELE_NEUTRAL || atk_elem >= ELE_MAX) return 100; if (def_type < ELE_NEUTRAL || def_type >= ELE_MAX || def_lv < 1 || def_lv > 4) return 100; return battle->attr_fix_table[def_lv-1][atk_elem][def_type]; } /*========================================== * Does attribute fix modifiers. * Added passing of the chars so that the status changes can affect it. [Skotlex] * Note: Passing src/target == NULL is perfectly valid, it skips SC_ checks. *------------------------------------------*/ int64 battle_attr_fix(struct block_list *src, struct block_list *target, int64 damage,int atk_elem,int def_type, int def_lv) { struct status_change *sc=NULL, *tsc=NULL; int ratio; if (src) sc = status->get_sc(src); if (target) tsc = status->get_sc(target); if (atk_elem < ELE_NEUTRAL || atk_elem >= ELE_MAX) atk_elem = rnd()%ELE_MAX; if (def_type < ELE_NEUTRAL || def_type >= ELE_MAX || def_lv < 1 || def_lv > 4) { ShowError("battle_attr_fix: tipo de atributo desconhecido: atk=%d def_type=%d def_lv=%d\n",atk_elem,def_type,def_lv); return damage; } ratio = battle->attr_fix_table[def_lv-1][atk_elem][def_type]; if (sc && sc->count) { if(sc->data[SC_VOLCANO] && atk_elem == ELE_FIRE) ratio += skill->enchant_eff[sc->data[SC_VOLCANO]->val1-1]; if(sc->data[SC_VIOLENTGALE] && atk_elem == ELE_WIND) ratio += skill->enchant_eff[sc->data[SC_VIOLENTGALE]->val1-1]; if(sc->data[SC_DELUGE] && atk_elem == ELE_WATER) ratio += skill->enchant_eff[sc->data[SC_DELUGE]->val1-1]; if(sc->data[SC_FIRE_CLOAK_OPTION] && atk_elem == ELE_FIRE) damage += damage * sc->data[SC_FIRE_CLOAK_OPTION]->val2 / 100; } if( target && target->type == BL_SKILL ) { if( atk_elem == ELE_FIRE && battle->get_current_skill(target) == GN_WALLOFTHORN ) { struct skill_unit *su = (struct skill_unit*)target; struct skill_unit_group *sg; struct block_list *sgsrc; if(!su->alive || (sg = su->group) == NULL || sg->val3 == -1 || (sgsrc = map->id2bl(sg->src_id)) == NULL || status->isdead(sgsrc) ) return 0; if( sg->unit_id != UNT_FIREWALL ) { int x,y; x = sg->val3 >> 16; y = sg->val3 & 0xffff; skill->unitsetting(sgsrc,su->group->skill_id,su->group->skill_lv,x,y,1); sg->val3 = -1; sg->limit = DIFF_TICK32(timer->gettick(),sg->tick)+300; } } } if( tsc && tsc->count ) { //since an atk can only have one type let's optimize this a bit switch(atk_elem){ case ELE_FIRE: if( tsc->data[SC_SPIDERWEB]) { tsc->data[SC_SPIDERWEB]->val1 = 0; // free to move now if( tsc->data[SC_SPIDERWEB]->val2-- > 0 ) damage <<= 1; // double damage if( tsc->data[SC_SPIDERWEB]->val2 == 0 ) status_change_end(target, SC_SPIDERWEB, INVALID_TIMER); } if( tsc->data[SC_THORNS_TRAP]) status_change_end(target, SC_THORNS_TRAP, INVALID_TIMER); if( tsc->data[SC_COLD] && target->type != BL_MOB) status_change_end(target, SC_COLD, INVALID_TIMER); if( tsc->data[SC_EARTH_INSIGNIA]) damage += damage/2; if( tsc->data[SC_FIRE_CLOAK_OPTION]) damage -= damage * tsc->data[SC_FIRE_CLOAK_OPTION]->val2 / 100; if( tsc->data[SC_VOLCANIC_ASH]) damage += damage/2; //150% break; case ELE_HOLY: if( tsc->data[SC_ORATIO]) ratio += tsc->data[SC_ORATIO]->val1 * 2; break; case ELE_POISON: if( tsc->data[SC_VENOMIMPRESS] && atk_elem == ELE_POISON ) ratio += tsc->data[SC_VENOMIMPRESS]->val2; break; case ELE_WIND: if( tsc->data[SC_COLD] && target->type != BL_MOB) damage += damage/2; if( tsc->data[SC_WATER_INSIGNIA]) damage += damage/2; break; case ELE_WATER: if( tsc->data[SC_FIRE_INSIGNIA]) damage += damage/2; break; case ELE_EARTH: if( tsc->data[SC_WIND_INSIGNIA]) damage += damage/2; break; } } //end tsc check if( ratio < 100 ) return damage - (damage * (100 - ratio) / 100); else return damage + (damage * (ratio - 100) / 100); } //FIXME: Missing documentation for flag, flag2 int64 battle_calc_weapon_damage(struct block_list *src, struct block_list *bl, uint16 skill_id, uint16 skill_lv, struct weapon_atk *watk, int nk, bool n_ele, short s_ele, short s_ele_, int size, int type, int flag, int flag2){ // [malufett] #ifdef RENEWAL int64 damage, eatk = 0; struct status_change *sc; struct map_session_data *sd; if( !src || !bl ) return 0; sc = status->get_sc(src); sd = BL_CAST(BL_PC, src); damage = status->get_weapon_atk(src, watk, flag); if ( sd ) { if ( type == EQI_HAND_R ) damage = battle->calc_sizefix(sd, damage, EQI_HAND_R, size, flag & 8); else damage = battle->calc_sizefix(sd, damage, EQI_HAND_L, size, flag & 8); if ( flag & 2 && sd->bonus.arrow_atk && skill_id != GN_CARTCANNON ) damage += sd->bonus.arrow_atk; if ( sd->battle_status.equip_atk != 0 ) eatk = sd->base_status.equip_atk; if ( sd->bonus.atk_rate ) damage += damage * sd->bonus.atk_rate / 100; } if ( skill_id == TF_POISON ) eatk += 15 * skill_lv; if ( skill_id != ASC_METEORASSAULT ) { if ( sc && sc->data[SC_SUB_WEAPONPROPERTY] ) // Temporary. [malufett] damage += damage * sc->data[SC_SUB_WEAPONPROPERTY]->val2 / 100; } if( sc && sc->count ){ if( sc->data[SC_ZENKAI] && watk->ele == sc->data[SC_ZENKAI]->val2 ) eatk += 200; } #ifdef RENEWAL_EDP if ( sc && sc->data[SC_EDP] && skill_id != AS_GRIMTOOTH && skill_id != AS_VENOMKNIFE && skill_id != ASC_BREAKER ) { struct status_data *tstatus; tstatus = status->get_status_data(bl); eatk += damage * 0x19 * battle->attr_fix_table[tstatus->ele_lv - 1][ELE_POISON][tstatus->def_ele] / 10000; damage += (eatk + damage) * sc->data[SC_EDP]->val3 / 100 + eatk; } else /* fall through */ #endif damage += eatk; damage = battle->calc_elefix(src, bl, skill_id, skill_lv, damage, nk, n_ele, s_ele, s_ele_, type == EQI_HAND_L, flag); /** * In RE Shield Boomerang takes weapon element only for damage calculation, * - resist calculation is always against neutral **/ if ( skill_id == CR_SHIELDBOOMERANG ) s_ele = s_ele_ = ELE_NEUTRAL; // attacker side damage = battle->calc_cardfix(BF_WEAPON, src, bl, nk, s_ele, s_ele_, damage, 2|(type == EQI_HAND_L), flag2); // target side damage = battle->calc_cardfix(BF_WEAPON, src, bl, nk, s_ele, s_ele_, damage, 0, flag2); return damage; #else return 0; #endif } /*========================================== * Calculates the standard damage of a normal attack assuming it hits, * it calculates nothing extra fancy, is needed for magnum breaks WATK_ELEMENT bonus. [Skotlex] *------------------------------------------ * Pass damage2 as NULL to not calc it. * Flag values: // TODO: Check whether these values are correct (the flag parameter seems to be passed through to other functions), and replace them with an enum. * &1: Critical hit * &2: Arrow attack * &4: Skill is Magic Crasher * &8: Skip target size adjustment (Extremity Fist?) *&16: Arrow attack but BOW, REVOLVER, RIFLE, SHOTGUN, GATLING or GRENADE type weapon not equipped (i.e. shuriken, kunai and venom knives not affected by DEX) */ /* 'battle_calc_base_damage' is used on renewal, 'battle_calc_base_damage2' otherwise. */ // FIXME: Missing documentation for flag2 int64 battle_calc_base_damage(struct block_list *src, struct block_list *bl, uint16 skill_id, uint16 skill_lv, int nk, bool n_ele, short s_ele, short s_ele_, int type, int flag, int flag2) { int64 damage; struct status_data *st = status->get_status_data(src); struct status_change *sc = status->get_sc(src); nullpo_retr(0, src); if ( !skill_id ) { s_ele = st->rhw.ele; s_ele_ = st->lhw.ele; if ( src->type == BL_PC ) { if ( ((TBL_PC*)src)->charm_type != CHARM_TYPE_NONE && ((TBL_PC*)src)->charm_count >= MAX_SPIRITCHARM ) { s_ele = s_ele_ = ((TBL_PC*)src)->charm_type; } if ( flag & 2 && ((TBL_PC*)src)->bonus.arrow_ele ) s_ele = ((TBL_PC*)src)->bonus.arrow_ele; } } if (src->type == BL_PC) { int64 batk; // Property from mild wind bypasses it if (sc && sc->data[SC_TK_SEVENWIND]) batk = battle->calc_elefix(src, bl, skill_id, skill_lv, status->calc_batk(bl, sc, st->batk, false), nk, n_ele, s_ele, s_ele_, false, flag); else batk = battle->calc_elefix(src, bl, skill_id, skill_lv, status->calc_batk(bl, sc, st->batk, false), nk, n_ele, ELE_NEUTRAL, ELE_NEUTRAL, false, flag); if (type == EQI_HAND_L) damage = batk + 3 * battle->calc_weapon_damage(src, bl, skill_id, skill_lv, &st->lhw, nk, n_ele, s_ele, s_ele_, status_get_size(bl), type, flag, flag2) / 4; else damage = (batk << 1) + battle->calc_weapon_damage(src, bl, skill_id, skill_lv, &st->rhw, nk, n_ele, s_ele, s_ele_, status_get_size(bl), type, flag, flag2); } else{ damage = st->batk + battle->calc_weapon_damage(src, bl, skill_id, skill_lv, &st->rhw, nk, n_ele, s_ele, s_ele_, status_get_size(bl), type, flag, flag2); } return damage; } int64 battle_calc_base_damage2(struct status_data *st, struct weapon_atk *wa, struct status_change *sc, unsigned short t_size, struct map_session_data *sd, int flag) { unsigned int atkmin=0, atkmax=0; short type = 0; int64 damage = 0; nullpo_retr(damage, st); nullpo_retr(damage, wa); if (!sd) { //Mobs/Pets if(flag&4) { atkmin = st->matk_min; atkmax = st->matk_max; } else { atkmin = wa->atk; atkmax = wa->atk2; } if (atkmin > atkmax) atkmin = atkmax; } else { //PCs atkmax = wa->atk; type = (wa == &st->lhw)?EQI_HAND_L:EQI_HAND_R; if (!(flag&1) || (flag&2)) { //Normal attacks atkmin = st->dex; if (sd->equip_index[type] >= 0 && sd->inventory_data[sd->equip_index[type]]) atkmin = atkmin*(80 + sd->inventory_data[sd->equip_index[type]]->wlv*20)/100; if (atkmin > atkmax) atkmin = atkmax; if(flag&2 && !(flag&16)) { //Bows atkmin = atkmin*atkmax/100; if (atkmin > atkmax) atkmax = atkmin; } } } if (sc && sc->data[SC_MAXIMIZEPOWER]) atkmin = atkmax; //Weapon Damage calculation if (!(flag&1)) damage = (atkmax>atkmin? rnd()%(atkmax-atkmin):0)+atkmin; else damage = atkmax; if (sd) { //rodatazone says the range is 0~arrow_atk-1 for non crit if (flag&2 && sd->bonus.arrow_atk) damage += ( (flag&1) ? sd->bonus.arrow_atk : rnd()%sd->bonus.arrow_atk ); //SizeFix only for players if (!(sd->special_state.no_sizefix || (flag&8))) damage = damage * ( type == EQI_HAND_L ? sd->left_weapon.atkmods[t_size] : sd->right_weapon.atkmods[t_size] ) / 100; } //Finally, add baseatk if(flag&4) damage += st->matk_min; else damage += st->batk; //rodatazone says that Overrefined bonuses are part of baseatk //Here we also apply the weapon_atk_rate bonus so it is correctly applied on left/right hands. if(sd) { if (type == EQI_HAND_L) { if(sd->left_weapon.overrefine) damage += rnd()%sd->left_weapon.overrefine+1; if (sd->weapon_atk_rate[sd->weapontype2]) damage += damage * sd->weapon_atk_rate[sd->weapontype2] / 100; } else { //Right hand if(sd->right_weapon.overrefine) damage += rnd()%sd->right_weapon.overrefine+1; if (sd->weapon_atk_rate[sd->weapontype1]) damage += damage * sd->weapon_atk_rate[sd->weapontype1] / 100; } } return damage; } int64 battle_calc_sizefix(struct map_session_data *sd, int64 damage, int type, int size, bool ignore){ //SizeFix only for players nullpo_retr(damage, sd); if (!(sd->special_state.no_sizefix || (ignore))) damage = damage * ( type == EQI_HAND_L ? sd->left_weapon.atkmods[size] : sd->right_weapon.atkmods[size] ) / 100; return damage; } /*========================================== * Passive skill damages increases *------------------------------------------*/ // FIXME: type is undocumented int64 battle_addmastery(struct map_session_data *sd,struct block_list *target,int64 dmg,int type) { int64 damage; struct status_data *st = status->get_status_data(target); int weapon, skill_lv; damage = dmg; nullpo_retr(damage, sd); nullpo_retr(damage, target); if((skill_lv = pc->checkskill(sd,AL_DEMONBANE)) > 0 && target->type == BL_MOB && //This bonus doesn't work against players. (battle->check_undead(st->race,st->def_ele) || st->race==RC_DEMON) ) damage += (int)(skill_lv*(3+sd->status.base_level/20.0)); //damage += (skill_lv * 3); if( (skill_lv = pc->checkskill(sd, RA_RANGERMAIN)) > 0 && (st->race == RC_BRUTE || st->race == RC_PLANT || st->race == RC_FISH) ) damage += (skill_lv * 5); if( (skill_lv = pc->checkskill(sd,NC_RESEARCHFE)) > 0 && (st->def_ele == ELE_FIRE || st->def_ele == ELE_EARTH) ) damage += (skill_lv * 10); if( pc_ismadogear(sd) ) damage += 15 * pc->checkskill(sd, NC_MADOLICENCE); #ifdef RENEWAL if( (skill_lv = pc->checkskill(sd,BS_WEAPONRESEARCH)) > 0 ) damage += (skill_lv * 2); #endif if((skill_lv = pc->checkskill(sd,HT_BEASTBANE)) > 0 && (st->race==RC_BRUTE || st->race==RC_INSECT) ) { damage += (skill_lv * 4); if (sd->sc.data[SC_SOULLINK] && sd->sc.data[SC_SOULLINK]->val2 == SL_HUNTER) damage += sd->status.str; } if(type == 0) weapon = sd->weapontype1; else weapon = sd->weapontype2; switch(weapon) { case W_1HSWORD: #ifdef RENEWAL if((skill_lv = pc->checkskill(sd,AM_AXEMASTERY)) > 0) damage += (skill_lv * 3); #endif case W_DAGGER: if((skill_lv = pc->checkskill(sd,SM_SWORD)) > 0) damage += (skill_lv * 4); if((skill_lv = pc->checkskill(sd,GN_TRAINING_SWORD)) > 0) damage += skill_lv * 10; break; case W_2HSWORD: #ifdef RENEWAL if((skill_lv = pc->checkskill(sd,AM_AXEMASTERY)) > 0) damage += (skill_lv * 3); #endif if((skill_lv = pc->checkskill(sd,SM_TWOHAND)) > 0) damage += (skill_lv * 4); break; case W_1HSPEAR: case W_2HSPEAR: if ((skill_lv = pc->checkskill(sd,KN_SPEARMASTERY)) > 0) { if (pc_isridingdragon(sd)) damage += (skill_lv * 10); else if (pc_isridingpeco(sd)) damage += (skill_lv * 5); else damage += (skill_lv * 4); } break; case W_1HAXE: case W_2HAXE: if((skill_lv = pc->checkskill(sd,AM_AXEMASTERY)) > 0) damage += (skill_lv * 3); if((skill_lv = pc->checkskill(sd,NC_TRAININGAXE)) > 0) damage += (skill_lv * 5); break; case W_MACE: case W_2HMACE: if((skill_lv = pc->checkskill(sd,PR_MACEMASTERY)) > 0) damage += (skill_lv * 3); if((skill_lv = pc->checkskill(sd,NC_TRAININGAXE)) > 0) damage += (skill_lv * 5); break; case W_FIST: if((skill_lv = pc->checkskill(sd,TK_RUN)) > 0) damage += (skill_lv * 10); // No break, fall through to Knuckles case W_KNUCKLE: if((skill_lv = pc->checkskill(sd,MO_IRONHAND)) > 0) damage += (skill_lv * 3); break; case W_MUSICAL: if((skill_lv = pc->checkskill(sd,BA_MUSICALLESSON)) > 0) damage += (skill_lv * 3); break; case W_WHIP: if((skill_lv = pc->checkskill(sd,DC_DANCINGLESSON)) > 0) damage += (skill_lv * 3); break; case W_BOOK: if((skill_lv = pc->checkskill(sd,SA_ADVANCEDBOOK)) > 0) damage += (skill_lv * 3); break; case W_KATAR: if((skill_lv = pc->checkskill(sd,AS_KATAR)) > 0) damage += (skill_lv * 3); break; } return damage; } /*========================================== * Calculates ATK masteries. *------------------------------------------*/ int64 battle_calc_masteryfix(struct block_list *src, struct block_list *target, uint16 skill_id, uint16 skill_lv, int64 damage, int div, bool left, bool weapon) { int skill2_lv, i; struct status_change *sc; struct map_session_data *sd; struct status_data *tstatus; nullpo_ret(src); nullpo_ret(target); sc = status->get_sc(src); sd = BL_CAST(BL_PC, src); tstatus = status->get_status_data(target); if ( !sd ) return damage; damage = battle->add_mastery(sd, target, damage, left); switch( skill_id ){ // specific skill masteries case MO_INVESTIGATE: case MO_EXTREMITYFIST: case CR_GRANDCROSS: case NJ_ISSEN: case CR_ACIDDEMONSTRATION: return damage; case NJ_SYURIKEN: if( (skill2_lv = pc->checkskill(sd,NJ_TOBIDOUGU)) > 0 #ifndef RENEWAL && weapon #endif ) damage += 3 * skill2_lv; break; #ifndef RENEWAL case NJ_KUNAI: if( weapon ) damage += 60; break; #endif case RA_WUGDASH://(Caster Current Weight x 10 / 8) if( sd->weight ) damage += sd->weight / 8; /* Fall through */ case RA_WUGSTRIKE: case RA_WUGBITE: damage += 30*pc->checkskill(sd, RA_TOOTHOFWUG); break; case HT_FREEZINGTRAP: damage += 40 * pc->checkskill(sd, RA_RESEARCHTRAP); break; default: battle->calc_masteryfix_unknown(src, target, &skill_id, &skill_lv, &damage, &div, &left, &weapon); break; } if( sc ){ // sc considered as masteries if(sc->data[SC_GN_CARTBOOST]) damage += 10 * sc->data[SC_GN_CARTBOOST]->val1; if(sc->data[SC_CAMOUFLAGE]) damage += 30 * ( 10 - sc->data[SC_CAMOUFLAGE]->val4 ); #ifdef RENEWAL if(sc->data[SC_NIBELUNGEN] && weapon) damage += sc->data[SC_NIBELUNGEN]->val2; if(sc->data[SC_IMPOSITIO]) damage += sc->data[SC_IMPOSITIO]->val2; if(sc->data[SC_DRUMBATTLE]){ if(tstatus->size == SZ_SMALL) damage += sc->data[SC_DRUMBATTLE]->val2; else if(tstatus->size == SZ_MEDIUM) damage += 10 * sc->data[SC_DRUMBATTLE]->val1; //else no bonus for large target } if(sc->data[SC_GS_MADNESSCANCEL]) damage += 100; if(sc->data[SC_GS_GATLINGFEVER]){ if(tstatus->size == SZ_SMALL) damage += 10 * sc->data[SC_GS_GATLINGFEVER]->val1; else if(tstatus->size == SZ_MEDIUM) damage += -5 * sc->data[SC_GS_GATLINGFEVER]->val1; else damage += sc->data[SC_GS_GATLINGFEVER]->val1; } #if 0 if(sc->data[SC_SPECIALZONE]) damage += sc->data[SC_SPECIALZONE]->val2 >> 4; #endif // 0 #endif // RENEWAL } // general skill masteries #ifdef RENEWAL if( div < 0 ) // div fix div = 1; if( skill_id == MO_FINGEROFFENSIVE )//The finger offensive spheres on moment of attack do count. [Skotlex] damage += div * sd->spiritball_old * 3; else damage += div * sd->spiritball * 3; if( skill_id != CR_SHIELDBOOMERANG ) // Only Shield boomerang doesn't takes the Star Crumbs bonus. damage += div * (left ? sd->left_weapon.star : sd->right_weapon.star); if( skill_id != MC_CARTREVOLUTION && (skill2_lv=pc->checkskill(sd,BS_HILTBINDING)) > 0 ) damage += 4; if(sd->status.party_id && (skill2_lv=pc->checkskill(sd,TK_POWER)) > 0) { if( (i = party->foreachsamemap(party->sub_count, sd, 0)) > 1 ) damage += 2 * skill2_lv * i * (damage /*+ unknown value*/) / 100 /*+ unknown value*/; } #else if( skill_id != ASC_BREAKER && weapon ) // Adv Katar Mastery is does not applies to ASC_BREAKER, but other masteries DO apply >_> if( sd->status.weapon == W_KATAR && (skill2_lv=pc->checkskill(sd,ASC_KATAR)) > 0 ) damage += damage * (10 + 2 * skill2_lv) / 100; #endif // percentage factor masteries if ( sc && sc->data[SC_MIRACLE] ) i = 2; //Star anger else ARR_FIND(0, MAX_PC_FEELHATE, i, status->get_class(target) == sd->hate_mob[i]); if (i < MAX_PC_FEELHATE && (skill2_lv=pc->checkskill(sd,pc->sg_info[i].anger_id)) > 0 && weapon) { int ratio = sd->status.base_level + status_get_dex(src) + status_get_luk(src); if ( i == 2 ) ratio += status_get_str(src); //Star Anger if (skill2_lv < 4 ) ratio /= (12 - 3 * skill2_lv); damage += damage * ratio / 100; } if( sd->status.class_ == JOB_ARCH_BISHOP_T || sd->status.class_ == JOB_ARCH_BISHOP ){ if((skill2_lv = pc->checkskill(sd,AB_EUCHARISTICA)) > 0 && (tstatus->race == RC_DEMON || tstatus->def_ele == ELE_DARK) ) damage += damage * skill2_lv / 100; } return damage; } void battle_calc_masteryfix_unknown(struct block_list *src, struct block_list *target, uint16 *skill_id, uint16 *skill_lv, int64 *damage, int *div, bool *left, bool *weapon) { } /*========================================== * Elemental attribute fix. *------------------------------------------*/ // FIXME: flag is undocumented int64 battle_calc_elefix(struct block_list *src, struct block_list *target, uint16 skill_id, uint16 skill_lv, int64 damage, int nk, int n_ele, int s_ele, int s_ele_, bool left, int flag){ struct status_data *tstatus; nullpo_ret(src); nullpo_ret(target); tstatus = status->get_status_data(target); if( (nk&NK_NO_ELEFIX) || n_ele ) return damage; if( damage > 0 ) { if( left ) damage = battle->attr_fix(src, target, damage, s_ele_, tstatus->def_ele, tstatus->ele_lv); else{ damage=battle->attr_fix(src, target, damage, s_ele, tstatus->def_ele, tstatus->ele_lv); if( skill_id == MC_CARTREVOLUTION ) //Cart Revolution applies the element fix once more with neutral element damage = battle->attr_fix(src,target,damage,ELE_NEUTRAL,tstatus->def_ele, tstatus->ele_lv); if( skill_id == NC_ARMSCANNON ) damage = battle->attr_fix(src,target,damage,ELE_NEUTRAL,tstatus->def_ele, tstatus->ele_lv); if( skill_id == GS_GROUNDDRIFT ) //Additional 50*lv Neutral damage. damage += battle->attr_fix(src,target,50*skill_lv,ELE_NEUTRAL,tstatus->def_ele, tstatus->ele_lv); } } #ifndef RENEWAL { struct status_data *sstatus; struct status_change *sc; sstatus = status->get_status_data(src); sc = status->get_sc(src); if( sc && sc->data[SC_SUB_WEAPONPROPERTY] ) { // Descriptions indicate this means adding a percent of a normal attack in another element. [Skotlex] int64 temp = battle->calc_base_damage2(sstatus, &sstatus->rhw, sc, tstatus->size, BL_CAST(BL_PC, src), (flag?2:0)) * sc->data[SC_SUB_WEAPONPROPERTY]->val2 / 100; damage += battle->attr_fix(src, target, temp, sc->data[SC_SUB_WEAPONPROPERTY]->val1, tstatus->def_ele, tstatus->ele_lv); if( left ) { temp = battle->calc_base_damage2(sstatus, &sstatus->lhw, sc, tstatus->size, BL_CAST(BL_PC, src), (flag?2:0)) * sc->data[SC_SUB_WEAPONPROPERTY]->val2 / 100; damage += battle->attr_fix(src, target, temp, sc->data[SC_SUB_WEAPONPROPERTY]->val1, tstatus->def_ele, tstatus->ele_lv); } } } #endif return damage; } int64 battle_calc_cardfix2(struct block_list *src, struct block_list *bl, int64 damage, int s_ele, int nk, int flag) { #ifdef RENEWAL struct map_session_data *tsd; struct status_data *sstatus; if ( !damage ) return 0; nullpo_ret(bl); nullpo_ret(src); tsd = BL_CAST(BL_PC, bl); sstatus = status->get_status_data(src); if ( tsd ) { if ( !(nk&NK_NO_CARDFIX_DEF) ) { // RaceAddTolerance damage -= damage * tsd->race_tolerance[sstatus->race] / 100; damage -= damage * tsd->race_tolerance[is_boss(src) ? RC_BOSS : RC_NONBOSS] / 100; if ( flag&BF_SHORT ) damage -= damage * tsd->bonus.near_attack_def_rate / 100; else // SubRangeAttackDamage or bLongAtkDef damage -= damage * tsd->bonus.long_attack_def_rate / 100; } if ( flag&BF_LONG && tsd->sc.data[SC_GS_ADJUSTMENT] ) { damage -= 20 * damage / 100; } } #endif return damage; } /*========================================== * Calculates card bonuses damage adjustments. * cflag(cardfix flag): * &1 - calc for left hand. * &2 - atker side cardfix(BF_WEAPON) otherwise target side(BF_WEAPON). *------------------------------------------*/ // FIXME: wflag is undocumented int64 battle_calc_cardfix(int attack_type, struct block_list *src, struct block_list *target, int nk, int s_ele, int s_ele_, int64 damage, int cflag, int wflag){ struct map_session_data *sd, *tsd; #ifdef RENEWAL short cardfix = 100; #else short cardfix = 1000; #endif short t_class, s_class, s_race2, t_race2; struct status_data *sstatus, *tstatus; int i; if( !damage ) return 0; nullpo_ret(src); nullpo_ret(target); sd = BL_CAST(BL_PC, src); tsd = BL_CAST(BL_PC, target); t_class = status->get_class(target); s_class = status->get_class(src); sstatus = status->get_status_data(src); tstatus = status->get_status_data(target); s_race2 = status->get_race2(src); switch(attack_type){ case BF_MAGIC: if ( sd && !(nk&NK_NO_CARDFIX_ATK) ) { cardfix = cardfix * (100 + sd->magic_addrace[tstatus->race]) / 100; if (!(nk&NK_NO_ELEFIX)) cardfix = cardfix*(100+sd->magic_addele[tstatus->def_ele]) / 100; cardfix = cardfix * (100 + sd->magic_addsize[tstatus->size]) / 100; cardfix = cardfix * (100 + sd->magic_addrace[is_boss(target)?RC_BOSS:RC_NONBOSS]) / 100; cardfix = cardfix * (100 + sd->magic_atk_ele[s_ele])/100; for(i=0; i< ARRAYLENGTH(sd->add_mdmg) && sd->add_mdmg[i].rate; i++) { if(sd->add_mdmg[i].class_ == t_class) { cardfix = cardfix * (100 + sd->add_mdmg[i].rate) / 100; break; } } } if( tsd && !(nk&NK_NO_CARDFIX_DEF) ) { // Target cards. if (!(nk&NK_NO_ELEFIX)) { int ele_fix = tsd->subele[s_ele]; for (i = 0; ARRAYLENGTH(tsd->subele2) > i && tsd->subele2[i].rate != 0; i++) { if(tsd->subele2[i].ele != s_ele) continue; if(!(tsd->subele2[i].flag&wflag&BF_WEAPONMASK && tsd->subele2[i].flag&wflag&BF_RANGEMASK && tsd->subele2[i].flag&wflag&BF_SKILLMASK)) continue; ele_fix += tsd->subele2[i].rate; } cardfix = cardfix * (100 - ele_fix) / 100; } cardfix = cardfix * (100 - tsd->subsize[sstatus->size]) / 100; cardfix = cardfix * (100 - tsd->subrace2[s_race2]) / 100; cardfix = cardfix * (100 - tsd->subrace[sstatus->race]) / 100; cardfix = cardfix * (100 - tsd->subrace[is_boss(src)?RC_BOSS:RC_NONBOSS]) / 100; for(i=0; i < ARRAYLENGTH(tsd->add_mdef) && tsd->add_mdef[i].rate;i++) { if(tsd->add_mdef[i].class_ == s_class) { cardfix = cardfix * (100-tsd->add_mdef[i].rate) / 100; break; } } #ifndef RENEWAL //It was discovered that ranged defense also counts vs magic! [Skotlex] if ( wflag&BF_SHORT ) cardfix = cardfix * ( 100 - tsd->bonus.near_attack_def_rate ) / 100; else cardfix = cardfix * ( 100 - tsd->bonus.long_attack_def_rate ) / 100; #endif cardfix = cardfix * ( 100 - tsd->bonus.magic_def_rate ) / 100; if( tsd->sc.data[SC_PROTECT_MDEF] ) cardfix = cardfix * ( 100 - tsd->sc.data[SC_PROTECT_MDEF]->val1 ) / 100; } #ifdef RENEWAL if ( cardfix != 100 ) damage += damage * (cardfix - 100) / 100; #else if ( cardfix != 1000 ) damage = damage * cardfix / 1000; #endif break; case BF_WEAPON: t_race2 = status->get_race2(target); if( cflag&2 ){ if( sd && !(nk&NK_NO_CARDFIX_ATK) ){ short cardfix_ = #ifdef RENEWAL 100; #else 1000; #endif if( sd->state.arrow_atk ){ cardfix = cardfix * (100 + sd->right_weapon.addrace[tstatus->race] + sd->arrow_addrace[tstatus->race]) / 100; if( !(nk&NK_NO_ELEFIX) ){ int ele_fix = sd->right_weapon.addele[tstatus->def_ele] + sd->arrow_addele[tstatus->def_ele]; for(i = 0; ARRAYLENGTH(sd->right_weapon.addele2) > i && sd->right_weapon.addele2[i].rate != 0; i++){ if (sd->right_weapon.addele2[i].ele != tstatus->def_ele) continue; if(!(sd->right_weapon.addele2[i].flag&wflag&BF_WEAPONMASK && sd->right_weapon.addele2[i].flag&wflag&BF_RANGEMASK && sd->right_weapon.addele2[i].flag&wflag&BF_SKILLMASK)) continue; ele_fix += sd->right_weapon.addele2[i].rate; } cardfix = cardfix * (100 + ele_fix) / 100; } cardfix = cardfix * (100 + sd->right_weapon.addsize[tstatus->size]+sd->arrow_addsize[tstatus->size]) / 100; cardfix = cardfix * (100 + sd->right_weapon.addrace2[t_race2]) / 100; cardfix = cardfix * (100 + sd->right_weapon.addrace[is_boss(target)?RC_BOSS:RC_NONBOSS] + sd->arrow_addrace[is_boss(target)?RC_BOSS:RC_NONBOSS]) / 100; }else{ // Melee attack if( !battle_config.left_cardfix_to_right ){ cardfix=cardfix*(100+sd->right_weapon.addrace[tstatus->race])/100; if( !(nk&NK_NO_ELEFIX) ){ int ele_fix = sd->right_weapon.addele[tstatus->def_ele]; for (i = 0; ARRAYLENGTH(sd->right_weapon.addele2) > i && sd->right_weapon.addele2[i].rate != 0; i++) { if (sd->right_weapon.addele2[i].ele != tstatus->def_ele) continue; if(!(sd->right_weapon.addele2[i].flag&wflag&BF_WEAPONMASK && sd->right_weapon.addele2[i].flag&wflag&BF_RANGEMASK && sd->right_weapon.addele2[i].flag&wflag&BF_SKILLMASK)) continue; ele_fix += sd->right_weapon.addele2[i].rate; } cardfix = cardfix * (100+ele_fix) / 100; } cardfix = cardfix * (100+sd->right_weapon.addsize[tstatus->size]) / 100; cardfix = cardfix * (100+sd->right_weapon.addrace2[t_race2]) / 100; cardfix = cardfix * (100+sd->right_weapon.addrace[is_boss(target)?RC_BOSS:RC_NONBOSS]) / 100; if( cflag&1 ){ cardfix_ = cardfix_*(100+sd->left_weapon.addrace[tstatus->race])/100; if (!(nk&NK_NO_ELEFIX)){ int ele_fix_lh = sd->left_weapon.addele[tstatus->def_ele]; for (i = 0; ARRAYLENGTH(sd->left_weapon.addele2) > i && sd->left_weapon.addele2[i].rate != 0; i++) { if (sd->left_weapon.addele2[i].ele != tstatus->def_ele) continue; if(!(sd->left_weapon.addele2[i].flag&wflag&BF_WEAPONMASK && sd->left_weapon.addele2[i].flag&wflag&BF_RANGEMASK && sd->left_weapon.addele2[i].flag&wflag&BF_SKILLMASK)) continue; ele_fix_lh += sd->left_weapon.addele2[i].rate; } cardfix = cardfix * (100+ele_fix_lh) / 100; } cardfix_ = cardfix_ * (100+sd->left_weapon.addsize[tstatus->size]) / 100; cardfix_ = cardfix_ * (100+sd->left_weapon.addrace2[t_race2]) / 100; cardfix_ = cardfix_ * (100+sd->left_weapon.addrace[is_boss(target)?RC_BOSS:RC_NONBOSS]) / 100; } }else{ int ele_fix = sd->right_weapon.addele[tstatus->def_ele] + sd->left_weapon.addele[tstatus->def_ele]; for (i = 0; ARRAYLENGTH(sd->right_weapon.addele2) > i && sd->right_weapon.addele2[i].rate != 0; i++){ if (sd->right_weapon.addele2[i].ele != tstatus->def_ele) continue; if(!(sd->right_weapon.addele2[i].flag&wflag&BF_WEAPONMASK && sd->right_weapon.addele2[i].flag&wflag&BF_RANGEMASK && sd->right_weapon.addele2[i].flag&wflag&BF_SKILLMASK)) continue; ele_fix += sd->right_weapon.addele2[i].rate; } for (i = 0; ARRAYLENGTH(sd->left_weapon.addele2) > i && sd->left_weapon.addele2[i].rate != 0; i++){ if (sd->left_weapon.addele2[i].ele != tstatus->def_ele) continue; if(!(sd->left_weapon.addele2[i].flag&wflag&BF_WEAPONMASK && sd->left_weapon.addele2[i].flag&wflag&BF_RANGEMASK && sd->left_weapon.addele2[i].flag&wflag&BF_SKILLMASK)) continue; ele_fix += sd->left_weapon.addele2[i].rate; } cardfix = cardfix * (100 + sd->right_weapon.addrace[tstatus->race] + sd->left_weapon.addrace[tstatus->race]) / 100; cardfix = cardfix * (100 + ele_fix) / 100; cardfix = cardfix * (100 + sd->right_weapon.addsize[tstatus->size] + sd->left_weapon.addsize[tstatus->size])/100; cardfix = cardfix * (100 + sd->right_weapon.addrace2[t_race2] + sd->left_weapon.addrace2[t_race2])/100; cardfix = cardfix * (100 + sd->right_weapon.addrace[is_boss(target)?RC_BOSS:RC_NONBOSS] + sd->left_weapon.addrace[is_boss(target)?RC_BOSS:RC_NONBOSS]) / 100; } } for( i = 0; i < ARRAYLENGTH(sd->right_weapon.add_dmg) && sd->right_weapon.add_dmg[i].rate; i++ ){ if( sd->right_weapon.add_dmg[i].class_ == t_class ){ cardfix = cardfix * (100 + sd->right_weapon.add_dmg[i].rate) / 100; break; } } if( cflag&1 ){ for( i = 0; i < ARRAYLENGTH(sd->left_weapon.add_dmg) && sd->left_weapon.add_dmg[i].rate; i++ ){ if( sd->left_weapon.add_dmg[i].class_ == t_class ){ cardfix_ = cardfix_ * (100 + sd->left_weapon.add_dmg[i].rate) / 100; break; } } } #ifndef RENEWAL if( wflag&BF_LONG ) cardfix = cardfix * (100 + sd->bonus.long_attack_atk_rate) / 100; if( (cflag&1) && cardfix_ != 1000 ) damage = damage * cardfix_ / 1000; else if( cardfix != 1000 ) damage = damage * cardfix / 1000; #else if ( (cflag & 1) && cardfix_ != 100 ) damage += damage * (cardfix - 100) / 100; else if ( cardfix != 100 ) damage += damage * (cardfix - 100) / 100; #endif } }else{ // Target side if( tsd && !(nk&NK_NO_CARDFIX_DEF) ){ if( !(nk&NK_NO_ELEFIX) ){ int ele_fix = tsd->subele[s_ele]; for (i = 0; ARRAYLENGTH(tsd->subele2) > i && tsd->subele2[i].rate != 0; i++) { if(tsd->subele2[i].ele != s_ele) continue; if(!(tsd->subele2[i].flag&wflag&BF_WEAPONMASK && tsd->subele2[i].flag&wflag&BF_RANGEMASK && tsd->subele2[i].flag&wflag&BF_SKILLMASK)) continue; ele_fix += tsd->subele2[i].rate; } cardfix = cardfix * (100-ele_fix) / 100; if( cflag&1 && s_ele_ != s_ele ){ int ele_fix_lh = tsd->subele[s_ele_]; for (i = 0; ARRAYLENGTH(tsd->subele2) > i && tsd->subele2[i].rate != 0; i++){ if(tsd->subele2[i].ele != s_ele_) continue; if(!(tsd->subele2[i].flag&wflag&BF_WEAPONMASK && tsd->subele2[i].flag&wflag&BF_RANGEMASK && tsd->subele2[i].flag&wflag&BF_SKILLMASK)) continue; ele_fix_lh += tsd->subele2[i].rate; } cardfix = cardfix * (100 - ele_fix_lh) / 100; } } cardfix = cardfix * (100-tsd->subsize[sstatus->size]) / 100; cardfix = cardfix * (100-tsd->subrace2[s_race2]) / 100; cardfix = cardfix * (100-tsd->subrace[sstatus->race]) / 100; cardfix = cardfix * (100-tsd->subrace[is_boss(src)?RC_BOSS:RC_NONBOSS]) / 100; for( i = 0; i < ARRAYLENGTH(tsd->add_def) && tsd->add_def[i].rate;i++ ){ if( tsd->add_def[i].class_ == s_class ) { cardfix = cardfix * (100 - tsd->add_def[i].rate) / 100; break; } } #ifndef RENEWAL if( wflag&BF_SHORT ) cardfix = cardfix * (100 - tsd->bonus.near_attack_def_rate) / 100; else // BF_LONG (there's no other choice) cardfix = cardfix * (100 - tsd->bonus.long_attack_def_rate) / 100; #endif if( tsd->sc.data[SC_PROTECT_DEF] ) cardfix = cardfix * (100 - tsd->sc.data[SC_PROTECT_DEF]->val1) / 100; #ifdef RENEWAL if ( cardfix != 100 ) damage += damage * (cardfix - 100) / 100; #else if( cardfix != 1000 ) damage = damage * cardfix / 1000; #endif } } break; case BF_MISC: if ( tsd && !(nk&NK_NO_CARDFIX_DEF) ) { // misc damage reduction from equipment #ifndef RENEWAL if ( !(nk&NK_NO_ELEFIX) ) { int ele_fix = tsd->subele[s_ele]; for (i = 0; ARRAYLENGTH(tsd->subele2) > i && tsd->subele2[i].rate != 0; i++) { if(tsd->subele2[i].ele != s_ele) continue; if(!(tsd->subele2[i].flag&wflag&BF_WEAPONMASK && tsd->subele2[i].flag&wflag&BF_RANGEMASK && tsd->subele2[i].flag&wflag&BF_SKILLMASK)) continue; ele_fix += tsd->subele2[i].rate; } cardfix = cardfix * (100 - ele_fix) / 100; } cardfix = cardfix*(100-tsd->subrace[sstatus->race]) / 100; cardfix = cardfix*(100-tsd->subrace[is_boss(src)?RC_BOSS:RC_NONBOSS]) / 100; if( wflag&BF_SHORT ) cardfix = cardfix * ( 100 - tsd->bonus.near_attack_def_rate ) / 100; else // BF_LONG (there's no other choice) cardfix = cardfix * ( 100 - tsd->bonus.long_attack_def_rate ) / 100; #endif cardfix = cardfix*(100 - tsd->subsize[sstatus->size]) / 100; cardfix = cardfix*(100 - tsd->subrace2[s_race2]) / 100; cardfix = cardfix * (100 - tsd->bonus.misc_def_rate) / 100; #ifdef RENEWAL if ( cardfix != 100 ) damage += damage * (cardfix - 100) / 100; #else if ( cardfix != 1000 ) damage = damage * cardfix / 1000; #endif } break; } return damage; } /*========================================== * Calculates defense reduction. [malufett] * flag: * &1 - idef/imdef(Ignore defense) * &2 - pdef(Pierce defense) * &4 - tdef(Total defense reduction) *------------------------------------------*/ // TODO: Add an enum for flag int64 battle_calc_defense(int attack_type, struct block_list *src, struct block_list *target, uint16 skill_id, uint16 skill_lv, int64 damage, int flag, int pdef){ struct status_data *sstatus, *tstatus; struct map_session_data *sd, *tsd; struct status_change *sc, *tsc; int i; if( !damage ) return 0; nullpo_ret(src); nullpo_ret(target); sd = BL_CAST(BL_PC, src); tsd = BL_CAST(BL_PC, target); sstatus = status->get_status_data(src); tstatus = status->get_status_data(target); sc = status->get_sc(src); tsc = status->get_sc(target); switch(attack_type){ case BF_WEAPON: { /* Take note in RE * def1 = equip def * def2 = status def */ defType def1 = status->get_def(target); //Don't use tstatus->def1 due to skill timer reductions. short def2 = tstatus->def2, vit_def; #ifdef RENEWAL def1 = status->calc_def2(target, tsc, def1, false); // equip def(RE) def2 = status->calc_def(target, tsc, def2, false); // status def(RE) #else def1 = status->calc_def(target, tsc, def1, false); // equip def(RE) def2 = status->calc_def2(target, tsc, def2, false); // status def(RE) #endif if ( sd ) { if ( sd->charm_type == CHARM_TYPE_LAND && sd->charm_count > 0 ) // hidden from status window def1 += 10 * def1 * sd->charm_count / 100; i = sd->ignore_def[is_boss(target) ? RC_BOSS : RC_NONBOSS]; i += sd->ignore_def[tstatus->race]; if ( i ) { if ( i > 100 ) i = 100; def1 -= def1 * i / 100; #ifndef RENEWAL def2 -= def2 * i / 100; #endif } } if( sc && sc->data[SC_EXPIATIO] ){ i = 5 * sc->data[SC_EXPIATIO]->val1; // 5% per level def1 -= def1 * i / 100; #ifndef RENEWAL def2 -= def2 * i / 100; #endif } if( battle_config.vit_penalty_type && battle_config.vit_penalty_target&target->type ) { unsigned char target_count; //256 max targets should be a sane max target_count = unit->counttargeted(target); if(target_count >= battle_config.vit_penalty_count) { if(battle_config.vit_penalty_type == 1) { if( !tsc || !tsc->data[SC_STEELBODY] ) def1 = (def1 * (100 - (target_count - (battle_config.vit_penalty_count - 1))*battle_config.vit_penalty_num))/100; def2 = (def2 * (100 - (target_count - (battle_config.vit_penalty_count - 1))*battle_config.vit_penalty_num))/100; } else { //Assume type 2 if( !tsc || !tsc->data[SC_STEELBODY] ) def1 -= (target_count - (battle_config.vit_penalty_count - 1))*battle_config.vit_penalty_num; def2 -= (target_count - (battle_config.vit_penalty_count - 1))*battle_config.vit_penalty_num; } } #ifndef RENEWAL if(skill_id == AM_ACIDTERROR) def1 = 0; //Acid Terror ignores only armor defense. [Skotlex] #endif if(def2 < 1) def2 = 1; } //Vitality reduction from rodatazone: http://rodatazone.simgaming.net/mechanics/substats.php#def if (tsd) { //Sd vit-eq #ifndef RENEWAL //[VIT*0.5] + rnd([VIT*0.3], max([VIT*0.3],[VIT^2/150]-1)) vit_def = def2*(def2-15)/150; vit_def = def2/2 + (vit_def>0?rnd()%vit_def:0); #else vit_def = def2; #endif if((battle->check_undead(sstatus->race,sstatus->def_ele) || sstatus->race==RC_DEMON) && //This bonus already doesn't work vs players src->type == BL_MOB && (i=pc->checkskill(tsd,AL_DP)) > 0) vit_def += i*(int)(3 +(tsd->status.base_level+1)*0.04); // [orn] if( src->type == BL_MOB && (i=pc->checkskill(tsd,RA_RANGERMAIN))>0 && (sstatus->race == RC_BRUTE || sstatus->race == RC_FISH || sstatus->race == RC_PLANT) ) vit_def += i*5; } else { //Mob-Pet vit-eq #ifndef RENEWAL //VIT + rnd(0,[VIT/20]^2-1) vit_def = (def2/20)*(def2/20); vit_def = def2 + (vit_def>0?rnd()%vit_def:0); #else vit_def = def2; #endif } if (battle_config.weapon_defense_type) { vit_def += def1*battle_config.weapon_defense_type; def1 = 0; } #ifdef RENEWAL /** * RE DEF Reduction * Pierce defense gains 1 atk per def/2 **/ if( def1 < -399 ) // it stops at -399 def1 = 399; // in aegis it set to 1 but in our case it may lead to exploitation so limit it to 399 //return 1; if( flag&2 ) damage += def1 >> 1; if( !(flag&1) && !(flag&2) ) { if( flag&4 ) damage -= (def1 + vit_def); else damage = (int)((100.0f - def1 / (def1 + 400.0f) * 90.0f) / 100.0f * damage - vit_def); } #else if( def1 > 100 ) def1 = 100; if( !(flag&1) ){ if( flag&2 ) damage = damage * pdef * (def1+vit_def) / 100; else damage = damage * (100-def1) / 100; } if( !(flag&1 || flag&2) ) damage -= vit_def; #endif } break; case BF_MAGIC: { defType mdef = tstatus->mdef; short mdef2= tstatus->mdef2; #ifdef RENEWAL mdef2 = status->calc_mdef(target, tsc, mdef2, false); // status mdef(RE) mdef = status->calc_mdef2(target, tsc, mdef, false); // equip mde(RE) #else mdef2 = status->calc_mdef2(target, tsc, mdef2, false); // status mdef(RE) mdef = status->calc_mdef(target, tsc, mdef, false); // equip mde(RE) #endif if( flag&1 ) mdef = 0; if(sd) { i = sd->ignore_mdef[is_boss(target)?RC_BOSS:RC_NONBOSS]; i += sd->ignore_mdef[tstatus->race]; if (i) { if (i > 100) i = 100; mdef -= mdef * i/100; //mdef2-= mdef2* i/100; } } #ifdef RENEWAL /** * RE MDEF Reduction **/ if( mdef < -99 ) // it stops at -99 mdef = 99; // in aegis it set to 1 but in our case it may lead to exploitation so limit it to 99 //return 1; damage = (int)((100.0f - mdef / (mdef + 100.0f) * 90.0f) / 100.0f * damage - mdef2); #else if(battle_config.magic_defense_type) damage = damage - mdef*battle_config.magic_defense_type - mdef2; else damage = damage * (100-mdef)/100 - mdef2; #endif } break; } return damage; } // Minstrel/Wanderer number check for chorus skills. int battle_calc_chorusbonus(struct map_session_data *sd) { int members = 0; if (!sd || !sd->status.party_id) return 0; members = party->foreachsamemap(party->sub_count_chorus, sd, 0); if (members < 3) return 0; // Bonus remains 0 unless 3 or more Minstrel's/Wanderer's are in the party. if (members > 7) return 5; // Maximum effect possible from 7 or more Minstrel's/Wanderer's return members - 2; // Effect bonus from additional Minstrel's/Wanderer's if not above the max possible } // FIXME: flag is undocumented int battle_calc_skillratio(int attack_type, struct block_list *src, struct block_list *target, uint16 skill_id, uint16 skill_lv, int skillratio, int flag){ int i; struct status_change *sc, *tsc; struct map_session_data *sd, *tsd; struct status_data *st, *tst, *bst; nullpo_ret(src); nullpo_ret(target); sd = BL_CAST(BL_PC, src); tsd = BL_CAST(BL_PC, target); sc = status->get_sc(src); tsc = status->get_sc(target); st = status->get_status_data(src); bst = status->get_base_status(src); tst = status->get_status_data(target); switch(attack_type){ case BF_MAGIC: switch(skill_id){ case MG_NAPALMBEAT: skillratio += skill_lv * 10 - 30; break; case MG_FIREBALL: #ifdef RENEWAL skillratio += 20 * skill_lv; #else skillratio += skill_lv * 10 - 30; #endif break; case MG_SOULSTRIKE: if (battle->check_undead(tst->race,tst->def_ele)) skillratio += 5*skill_lv; break; case MG_FIREWALL: skillratio -= 50; break; case MG_THUNDERSTORM: /** * in Renewal Thunder Storm boost is 100% (in pre-re, 80%) **/ #ifndef RENEWAL skillratio -= 20; #endif break; case MG_FROSTDIVER: skillratio += 10 * skill_lv; break; case AL_HOLYLIGHT: skillratio += 25; if (sc && sc->data[SC_SOULLINK] && sc->data[SC_SOULLINK]->val2 == SL_PRIEST) skillratio *= 5; //Does 5x damage include bonuses from other skills? break; case AL_RUWACH: skillratio += 45; break; case WZ_FROSTNOVA: skillratio += (100+skill_lv*10) * 2 / 3 - 100; break; case WZ_FIREPILLAR: if (skill_lv > 10) skillratio += 2300; //200% MATK each hit else skillratio += -60 + 20*skill_lv; //20% MATK each hit break; case WZ_SIGHTRASHER: skillratio += 20 * skill_lv; break; case WZ_WATERBALL: skillratio += 30 * skill_lv; break; case WZ_STORMGUST: skillratio += 40 * skill_lv; break; case HW_NAPALMVULCAN: skillratio += 10 * skill_lv - 30; break; case SL_STIN: skillratio += (tst->size!=SZ_SMALL?-99:10*skill_lv); //target size must be small (0) for full damage. break; case SL_STUN: skillratio += (tst->size!=SZ_BIG?5*skill_lv:-99); //Full damage is dealt on small/medium targets break; case SL_SMA: skillratio += -60 + status->get_lv(src); //Base damage is 40% + lv% break; case NJ_KOUENKA: skillratio -= 10; if (sd && sd->charm_type == CHARM_TYPE_FIRE && sd->charm_count > 0) skillratio += 20 * sd->charm_count; break; case NJ_KAENSIN: skillratio -= 50; if (sd && sd->charm_type == CHARM_TYPE_FIRE && sd->charm_count > 0) skillratio += 10 * sd->charm_count; break; case NJ_BAKUENRYU: skillratio += 50 * (skill_lv - 1); if (sd && sd->charm_type == CHARM_TYPE_FIRE && sd->charm_count > 0) skillratio += 15 * sd->charm_count; break; #ifdef RENEWAL case NJ_HYOUSENSOU: skillratio -= 30; if (sd && sd->charm_type == CHARM_TYPE_WATER && sd->charm_count > 0) skillratio += 5 * sd->charm_count; break; #endif case NJ_HYOUSYOURAKU: skillratio += 50 * skill_lv; if (sd && sd->charm_type == CHARM_TYPE_WATER && sd->charm_count > 0) skillratio += 25 * sd->charm_count; break; case NJ_RAIGEKISAI: skillratio += 60 + 40 * skill_lv; if (sd && sd->charm_type == CHARM_TYPE_WIND && sd->charm_count > 0) skillratio += 15 * sd->charm_count; break; case NJ_KAMAITACHI: if (sd && sd->charm_type == CHARM_TYPE_WIND && sd->charm_count > 0) skillratio += 10 * sd->charm_count; /* Fall through */ case NPC_ENERGYDRAIN: skillratio += 100 * skill_lv; break; #ifdef RENEWAL case WZ_HEAVENDRIVE: case WZ_METEOR: skillratio += 25; break; case WZ_VERMILION: { int interval = 0, per = interval, ratio = per; while( (per++) < skill_lv ){ ratio += interval; if(per%3==0) interval += 20; } if( skill_lv > 9 ) ratio -= 10; skillratio += ratio; } break; case NJ_HUUJIN: skillratio += 50; if (sd && sd->charm_type == CHARM_TYPE_WIND && sd->charm_count > 0) skillratio += 20 * sd->charm_count; break; #else case WZ_VERMILION: skillratio += 20*skill_lv-20; break; #endif /** * Arch Bishop **/ case AB_JUDEX: skillratio = 300 + 20 * skill_lv; RE_LVL_DMOD(100); break; case AB_ADORAMUS: skillratio = 500 + 100 * skill_lv; RE_LVL_DMOD(100); break; case AB_DUPLELIGHT_MAGIC: skillratio = 200 + 20 * skill_lv; break; /** * Warlock **/ case WL_SOULEXPANSION: // MATK [{( Skill Level + 4 ) x 100 ) + ( Caster's INT )} x ( Caster's Base Level / 100 )] % skillratio = 100 * (skill_lv + 4) + st->int_; RE_LVL_DMOD(100); break; case WL_FROSTMISTY: // MATK [{( Skill Level x 100 ) + 200 } x ( Caster's Base Level / 100 )] % skillratio += 100 + 100 * skill_lv; RE_LVL_DMOD(100); break; case WL_JACKFROST: if( tsc && tsc->data[SC_FROSTMISTY] ){ skillratio += 900 + 300 * skill_lv; RE_LVL_DMOD(100); }else{ skillratio += 400 + 100 * skill_lv; RE_LVL_DMOD(150); } break; case WL_DRAINLIFE: skillratio = 200 * skill_lv + status_get_int(src); RE_LVL_DMOD(100); break; case WL_CRIMSONROCK: skillratio = 300 * skill_lv; RE_LVL_DMOD(100); skillratio += 1300; break; case WL_HELLINFERNO: skillratio = 300 * skill_lv; RE_LVL_DMOD(100); // Shadow: MATK [{( Skill Level x 300 ) x ( Caster Base Level / 100 ) x 4/5 }] % // Fire : MATK [{( Skill Level x 300 ) x ( Caster Base Level / 100 ) /5 }] % if( flag&ELE_DARK ) skillratio *= 4; skillratio /= 5; break; case WL_COMET: i = ( sc ? distance_xy(target->x, target->y, sc->comet_x, sc->comet_y) : 8 ); if( i <= 3 ) skillratio += 2400 + 500 * skill_lv; // 7 x 7 cell else if( i <= 5 ) skillratio += 1900 + 500 * skill_lv; // 11 x 11 cell else if( i <= 7 ) skillratio += 1400 + 500 * skill_lv; // 15 x 15 cell else skillratio += 900 + 500 * skill_lv; // 19 x 19 cell if( sd && sd->status.party_id ){ struct map_session_data* psd; int p_sd[5] = {0, 0, 0, 0, 0}, c; // just limit it to 5 c = 0; memset (p_sd, 0, sizeof(p_sd)); party->foreachsamemap(skill->check_condition_char_sub, sd, 3, &sd->bl, &c, &p_sd, skill_id); c = ( c > 1 ? rnd()%c : 0 ); if( (psd = map->id2sd(p_sd[c])) && pc->checkskill(psd,WL_COMET) > 0 ){ skillratio = skill_lv * 400; //MATK [{( Skill Level x 400 ) x ( Caster's Base Level / 120 )} + 2500 ] % RE_LVL_DMOD(120); skillratio += 2500; status_zap(&psd->bl, 0, skill->get_sp(skill_id, skill_lv) / 2); } } break; case WL_CHAINLIGHTNING_ATK: skillratio += 400 + 100 * skill_lv; RE_LVL_DMOD(100); if(flag > 0) skillratio += 100 * flag; break; case WL_EARTHSTRAIN: skillratio = 2000 + 100 * skill_lv; RE_LVL_DMOD(100); break; case WL_TETRAVORTEX_FIRE: case WL_TETRAVORTEX_WATER: case WL_TETRAVORTEX_WIND: case WL_TETRAVORTEX_GROUND: skillratio += 400 + 500 * skill_lv; break; case WL_SUMMON_ATK_FIRE: case WL_SUMMON_ATK_WATER: case WL_SUMMON_ATK_WIND: case WL_SUMMON_ATK_GROUND: skillratio = (1 + skill_lv) / 2 * (status->get_lv(src) + (sd ? sd->status.job_level : 50)); RE_LVL_DMOD(100); break; case LG_RAYOFGENESIS: { uint16 lv = skill_lv; int bandingBonus = 0; if( sc && sc->data[SC_BANDING] ) bandingBonus = 200 * (sd ? skill->check_pc_partner(sd,skill_id,&lv,skill->get_splash(skill_id,skill_lv),0) : 1); skillratio = ((300 * skill_lv) + bandingBonus) * (sd ? sd->status.job_level : 1) / 25; } break; case LG_SHIELDSPELL: if ( sd && skill_lv == 2 ) // [(Casters Base Level x 4) + (Shield MDEF x 100) + (Casters INT x 2)] % skillratio = 4 * status->get_lv(src) + 100 * sd->bonus.shieldmdef + 2 * st->int_; else skillratio = 0; break; case WM_METALICSOUND: skillratio = 120 * skill_lv + 60 * ( sd? pc->checkskill(sd, WM_LESSON) : 10 ); RE_LVL_DMOD(100); break; case WM_REVERBERATION_MAGIC: skillratio = 100 * skill_lv + 100; RE_LVL_DMOD(100); break; case SO_FIREWALK: skillratio = 60 * skill_lv; RE_LVL_DMOD(100); if( sc && sc->data[SC_HEATER_OPTION] ) skillratio += sc->data[SC_HEATER_OPTION]->val3 / 2; break; case SO_ELECTRICWALK: skillratio = 60 * skill_lv; RE_LVL_DMOD(100); if( sc && sc->data[SC_BLAST_OPTION] ) skillratio += sc->data[SC_BLAST_OPTION]->val2 / 2; break; case SO_EARTHGRAVE: skillratio = st->int_ * skill_lv + 200 * (sd ? pc->checkskill(sd,SA_SEISMICWEAPON) : 1); RE_LVL_DMOD(100); if( sc && sc->data[SC_CURSED_SOIL_OPTION] ) skillratio += sc->data[SC_CURSED_SOIL_OPTION]->val3 * 5; break; case SO_DIAMONDDUST: skillratio = (st->int_ * skill_lv + 200 * (sd ? pc->checkskill(sd, SA_FROSTWEAPON) : 1)) * status->get_lv(src) / 100; if( sc && sc->data[SC_COOLER_OPTION] ) skillratio += sc->data[SC_COOLER_OPTION]->val3 * 5; break; case SO_POISON_BUSTER: skillratio += 900 + 300 * skill_lv; RE_LVL_DMOD(100); if( sc && sc->data[SC_CURSED_SOIL_OPTION] ) skillratio += sc->data[SC_CURSED_SOIL_OPTION]->val3 * 5; break; case SO_PSYCHIC_WAVE: skillratio = 70 * skill_lv + 3 * st->int_; RE_LVL_DMOD(100); if( sc && ( sc->data[SC_HEATER_OPTION] || sc->data[SC_COOLER_OPTION] || sc->data[SC_BLAST_OPTION] || sc->data[SC_CURSED_SOIL_OPTION] ) ) skillratio += skillratio * 20 / 100; break; case SO_VARETYR_SPEAR: skillratio = status_get_int(src) * skill_lv + ( sd ? pc->checkskill(sd, SA_LIGHTNINGLOADER) * 50 : 0 ); RE_LVL_DMOD(100); if( sc && sc->data[SC_BLAST_OPTION] ) skillratio += sc->data[SC_BLAST_OPTION]->val2 * 5; break; case SO_CLOUD_KILL: skillratio = 40 * skill_lv; RE_LVL_DMOD(100); if( sc && sc->data[SC_CURSED_SOIL_OPTION] ) skillratio += sc->data[SC_CURSED_SOIL_OPTION]->val3; break; case GN_DEMONIC_FIRE: { int fire_expansion_lv = skill_lv / 100; skill_lv = skill_lv % 100; skillratio = 110 + 20 * skill_lv; if ( fire_expansion_lv == 1 ) skillratio += status_get_int(src) + (sd?sd->status.job_level:50); else if ( fire_expansion_lv == 2 ) skillratio += status_get_int(src) * 10; } break; // Magical Elemental Spirits Attack Skills case EL_FIRE_MANTLE: case EL_WATER_SCREW: skillratio += 900; break; case EL_FIRE_ARROW: case EL_ROCK_CRUSHER_ATK: skillratio += 200; break; case EL_FIRE_BOMB: case EL_ICE_NEEDLE: case EL_HURRICANE_ATK: skillratio += 400; break; case EL_FIRE_WAVE: case EL_TYPOON_MIS_ATK: skillratio += 1100; break; case MH_ERASER_CUTTER: skillratio += 400 + 100 * skill_lv + (skill_lv%2 > 0 ? 0 : 300); break; case MH_XENO_SLASHER: if(skill_lv%2) skillratio += 350 + 50 * skill_lv; //500:600:700 else skillratio += 400 + 100 * skill_lv; //700:900 break; case MH_HEILIGE_STANGE: skillratio += 400 + 250 * skill_lv; break; case MH_POISON_MIST: skillratio += 100 * skill_lv; break; case KO_KAIHOU: if (sd && sd->charm_type != CHARM_TYPE_NONE && sd->charm_count > 0) { skillratio += -100 + 200 * sd->charm_count; RE_LVL_DMOD(100); pc->del_charm(sd, sd->charm_count, sd->charm_type); } break; default: battle->calc_skillratio_magic_unknown(&attack_type, src, target, &skill_id, &skill_lv, &skillratio, &flag); break; } break; case BF_WEAPON: switch( skill_id ) { case SM_BASH: case MS_BASH: skillratio += 30 * skill_lv; break; case SM_MAGNUM: case MS_MAGNUM: skillratio += 20 * skill_lv; break; case MC_MAMMONITE: skillratio += 50 * skill_lv; break; case HT_POWER: skillratio += -50 + 8 * status_get_str(src); break; case AC_DOUBLE: case MA_DOUBLE: skillratio += 10 * (skill_lv-1); break; case AC_SHOWER: case MA_SHOWER: #ifdef RENEWAL skillratio += 50 + 10 * skill_lv; #else skillratio += -25 + 5 * skill_lv; #endif break; case AC_CHARGEARROW: case MA_CHARGEARROW: skillratio += 50; break; #ifndef RENEWAL case HT_FREEZINGTRAP: case MA_FREEZINGTRAP: skillratio += -50 + 10 * skill_lv; break; #endif case KN_PIERCE: case ML_PIERCE: skillratio += 10 * skill_lv; break; case MER_CRASH: skillratio += 10 * skill_lv; break; case KN_SPEARSTAB: skillratio += 15 * skill_lv; break; case KN_SPEARBOOMERANG: skillratio += 50*skill_lv; break; case KN_BRANDISHSPEAR: case ML_BRANDISH: { int ratio = 100 + 20 * skill_lv; skillratio += ratio - 100; if(skill_lv>3 && flag==1) skillratio += ratio / 2; if(skill_lv>6 && flag==1) skillratio += ratio / 4; if(skill_lv>9 && flag==1) skillratio += ratio / 8; if(skill_lv>6 && flag==2) skillratio += ratio / 2; if(skill_lv>9 && flag==2) skillratio += ratio / 4; if(skill_lv>9 && flag==3) skillratio += ratio / 2; break; } case KN_BOWLINGBASH: case MS_BOWLINGBASH: skillratio+= 40 * skill_lv; break; case AS_GRIMTOOTH: skillratio += 20 * skill_lv; break; case AS_POISONREACT: skillratio += 30 * skill_lv; break; case AS_SONICBLOW: skillratio += 300 + 40 * skill_lv; break; case TF_SPRINKLESAND: skillratio += 30; break; case MC_CARTREVOLUTION: skillratio += 50; if( sd && sd->cart_weight ) skillratio += 100 * sd->cart_weight / sd->cart_weight_max; // +1% every 1% weight else if (!sd) skillratio += 100; //Max damage for non players. break; case NPC_RANDOMATTACK: skillratio += 100 * skill_lv; break; case NPC_WATERATTACK: case NPC_GROUNDATTACK: case NPC_FIREATTACK: case NPC_WINDATTACK: case NPC_POISONATTACK: case NPC_HOLYATTACK: case NPC_DARKNESSATTACK: case NPC_UNDEADATTACK: case NPC_TELEKINESISATTACK: case NPC_BLOODDRAIN: case NPC_ACIDBREATH: case NPC_DARKNESSBREATH: case NPC_FIREBREATH: case NPC_ICEBREATH: case NPC_THUNDERBREATH: case NPC_HELLJUDGEMENT: case NPC_PULSESTRIKE: skillratio += 100 * (skill_lv-1); break; case NPC_EARTHQUAKE: skillratio += 100 + 100 * skill_lv + 100 * (skill_lv / 2); break; case RG_BACKSTAP: if( sd && sd->status.weapon == W_BOW && battle_config.backstab_bow_penalty ) skillratio += (200 + 40 * skill_lv) / 2; else skillratio += 200 + 40 * skill_lv; break; case RG_RAID: skillratio += 40 * skill_lv; break; case RG_INTIMIDATE: skillratio += 30 * skill_lv; break; case CR_SHIELDCHARGE: skillratio += 20 * skill_lv; break; case CR_SHIELDBOOMERANG: skillratio += 30 * skill_lv; break; case NPC_DARKCROSS: case CR_HOLYCROSS: { int ratio = 35 * skill_lv; #ifdef RENEWAL if(sd && sd->status.weapon == W_2HSPEAR) ratio *= 2; #endif skillratio += ratio; break; } case AM_DEMONSTRATION: skillratio += 20 * skill_lv; break; case AM_ACIDTERROR: #ifdef RENEWAL skillratio += 80 * skill_lv + 100; #else skillratio += 40 * skill_lv; #endif break; case MO_FINGEROFFENSIVE: skillratio+= 50 * skill_lv; break; case MO_INVESTIGATE: skillratio += 75 * skill_lv; break; case MO_EXTREMITYFIST: #ifndef RENEWAL { //Overflow check. [Skotlex] unsigned int ratio = skillratio + 100*(8 + st->sp/10); //You'd need something like 6K SP to reach this max, so should be fine for most purposes. if (ratio > 60000) ratio = 60000; //We leave some room here in case skillratio gets further increased. skillratio = (unsigned short)ratio; } #endif break; case MO_TRIPLEATTACK: skillratio += 20 * skill_lv; break; case MO_CHAINCOMBO: skillratio += 50 + 50 * skill_lv; break; case MO_COMBOFINISH: skillratio += 140 + 60 * skill_lv; break; case BA_MUSICALSTRIKE: case DC_THROWARROW: skillratio += 25 + 25 * skill_lv; break; case CH_TIGERFIST: skillratio += 100 * skill_lv - 60; break; case CH_CHAINCRUSH: skillratio += 300 + 100 * skill_lv; break; case CH_PALMSTRIKE: skillratio += 100 + 100 * skill_lv; break; case LK_HEADCRUSH: skillratio += 40 * skill_lv; break; case LK_JOINTBEAT: i = 10 * skill_lv - 50; // Although not clear, it's being assumed that the 2x damage is only for the break neck ailment. if (flag&BREAK_NECK) i*=2; skillratio += i; break; case ASC_METEORASSAULT: skillratio += 40 * skill_lv - 60; break; case SN_SHARPSHOOTING: case MA_SHARPSHOOTING: skillratio += 100 + 50 * skill_lv; break; case CG_ARROWVULCAN: skillratio += 100 + 100 * skill_lv; break; case AS_SPLASHER: skillratio += 400 + 50 * skill_lv; if(sd) skillratio += 20 * pc->checkskill(sd,AS_POISONREACT); break; #ifndef RENEWAL case ASC_BREAKER: skillratio += 100*skill_lv-100; #else case LK_SPIRALPIERCE: case ML_SPIRALPIERCE: skillratio += 50 * skill_lv; #endif break; case PA_SACRIFICE: skillratio += 10 * skill_lv - 10; break; case PA_SHIELDCHAIN: skillratio += 30 * skill_lv; break; case WS_CARTTERMINATION: i = 10 * (16 - skill_lv); if (i < 1) i = 1; //Preserve damage ratio when max cart weight is changed. if(sd && sd->cart_weight) skillratio += sd->cart_weight/i * 80000/battle_config.max_cart_weight - 100; else if (!sd) skillratio += 80000 / i - 100; break; case TK_DOWNKICK: skillratio += 60 + 20 * skill_lv; break; case TK_STORMKICK: skillratio += 60 + 20 * skill_lv; break; case TK_TURNKICK: skillratio += 90 + 30 * skill_lv; break; case TK_COUNTER: skillratio += 90 + 30 * skill_lv; break; case TK_JUMPKICK: skillratio += -70 + 10*skill_lv; if (sc && sc->data[SC_COMBOATTACK] && sc->data[SC_COMBOATTACK]->val1 == skill_id) skillratio += 10 * status->get_lv(src) / 3; //Tumble bonus if (flag) { skillratio += 10 * status->get_lv(src) / 3; //Running bonus (TODO: What is the real bonus?) if( sc && sc->data[SC_STRUP] ) // Spurt bonus skillratio *= 2; } break; case GS_TRIPLEACTION: skillratio += 50 * skill_lv; break; case GS_BULLSEYE: //Only works well against brute/demi-humans non bosses. if((tst->race == RC_BRUTE || tst->race == RC_DEMIHUMAN) && !(tst->mode&MD_BOSS)) skillratio += 400; break; case GS_TRACKING: skillratio += 100 * (skill_lv+1); break; #ifndef RENEWAL case GS_PIERCINGSHOT: skillratio += 20 * skill_lv; break; #endif case GS_RAPIDSHOWER: skillratio += 10 * skill_lv; break; case GS_DESPERADO: skillratio += 50 * (skill_lv-1); break; case GS_DUST: skillratio += 50 * skill_lv; break; case GS_FULLBUSTER: skillratio += 100 * (skill_lv+2); break; case GS_SPREADATTACK: #ifdef RENEWAL skillratio += 20 * (skill_lv); #else skillratio += 20 * (skill_lv-1); #endif break; case NJ_HUUMA: skillratio += 50 + 150 * skill_lv; break; case NJ_TATAMIGAESHI: skillratio += 10 * skill_lv; break; case NJ_KASUMIKIRI: skillratio += 10 * skill_lv; break; case NJ_KIRIKAGE: skillratio += 100 * (skill_lv-1); break; case KN_CHARGEATK: { int k = (flag-1)/3; //+100% every 3 cells of distance if( k > 2 ) k = 2; // ...but hard-limited to 300%. skillratio += 100 * k; } break; case HT_PHANTASMIC: skillratio += 50; break; case MO_BALKYOUNG: skillratio += 200; break; case HFLI_MOON: //[orn] skillratio += 10 + 110 * skill_lv; break; case HFLI_SBR44: //[orn] skillratio += 100 * (skill_lv-1); break; case NPC_VAMPIRE_GIFT: skillratio += ((skill_lv-1)%5+1) * 100; break; case RK_SONICWAVE: skillratio = (skill_lv + 5) * 100; skillratio = skillratio * (100 + (status->get_lv(src)-100) / 2) / 100; break; case RK_HUNDREDSPEAR: skillratio += 500 + (80 * skill_lv); if( sd ){ short index = sd->equip_index[EQI_HAND_R]; if( index >= 0 && sd->inventory_data[index] && sd->inventory_data[index]->type == IT_WEAPON ) skillratio += (10000 - min(10000, sd->inventory_data[index]->weight)) / 10; skillratio = skillratio * (100 + (status->get_lv(src)-100) / 2) / 100 + 50 * pc->checkskill(sd,LK_SPIRALPIERCE); } break; case RK_WINDCUTTER: skillratio = (skill_lv + 2) * 50; RE_LVL_DMOD(100); break; case RK_IGNITIONBREAK: i = distance_bl(src,target); if( i < 2 ) skillratio = 300 * skill_lv; else if( i < 4 ) skillratio = 250 * skill_lv; else skillratio = 200 * skill_lv; skillratio = skillratio * status->get_lv(src) / 100; if( st->rhw.ele == ELE_FIRE ) skillratio += 100 * skill_lv; break; case RK_STORMBLAST: skillratio = ((sd ? pc->checkskill(sd,RK_RUNEMASTERY) : 1) + status_get_int(src) / 8) * 100; break; case RK_PHANTOMTHRUST: skillratio = 50 * skill_lv + 10 * (sd ? pc->checkskill(sd,KN_SPEARMASTERY) : 10); RE_LVL_DMOD(150); break; /** * GC Guillotine Cross **/ case GC_CROSSIMPACT: skillratio += 900 + 100 * skill_lv; RE_LVL_DMOD(120); break; case GC_PHANTOMMENACE: skillratio += 200; break; case GC_COUNTERSLASH: //ATK [{(Skill Level x 100) + 300} x Caster's Base Level / 120]% + ATK [(AGI x 2) + (Caster's Job Level x 4)]% skillratio += 200 + (100 * skill_lv); RE_LVL_DMOD(120); break; case GC_ROLLINGCUTTER: skillratio = 50 + 50 * skill_lv; RE_LVL_DMOD(100); break; case GC_CROSSRIPPERSLASHER: skillratio += 300 + 80 * skill_lv; RE_LVL_DMOD(100); if( sc && sc->data[SC_ROLLINGCUTTER] ) skillratio += sc->data[SC_ROLLINGCUTTER]->val1 * status_get_agi(src); break; case GC_DARKCROW: skillratio += 100 * (skill_lv - 1); break; /** * Arch Bishop **/ case AB_DUPLELIGHT_MELEE: skillratio += 10 * skill_lv; break; /** * Ranger **/ case RA_ARROWSTORM: skillratio += 900 + 80 * skill_lv; RE_LVL_DMOD(100); break; case RA_AIMEDBOLT: skillratio += 400 + 50 * skill_lv; RE_LVL_DMOD(100); break; case RA_CLUSTERBOMB: skillratio += 100 + 100 * skill_lv; break; case RA_WUGDASH:// ATK 300% skillratio = 300; if( sc && sc->data[SC_DANCE_WITH_WUG] ) skillratio += 10 * sc->data[SC_DANCE_WITH_WUG]->val1 * (2 + battle->calc_chorusbonus(sd)); break; case RA_WUGSTRIKE: skillratio = 200 * skill_lv; if( sc && sc->data[SC_DANCE_WITH_WUG] ) skillratio += 10 * sc->data[SC_DANCE_WITH_WUG]->val1 * (2 + battle->calc_chorusbonus(sd)); break; case RA_WUGBITE: skillratio += 300 + 200 * skill_lv; if ( skill_lv == 5 ) skillratio += 100; break; case RA_SENSITIVEKEEN: skillratio = 150 * skill_lv; break; /** * Mechanic **/ case NC_BOOSTKNUCKLE: skillratio = skill_lv * 100 + 200 + st->dex; RE_LVL_DMOD(120); break; case NC_PILEBUNKER: skillratio = skill_lv*100 + 300 + status_get_str(src); RE_LVL_DMOD(100); break; case NC_VULCANARM: skillratio = 70 * skill_lv + status_get_dex(src); RE_LVL_DMOD(120); break; case NC_FLAMELAUNCHER: case NC_COLDSLOWER: skillratio += 200 + 300 * skill_lv; RE_LVL_DMOD(150); break; case NC_ARMSCANNON: switch( tst->size ) { case SZ_SMALL: skillratio = 300 + 350 * skill_lv; break; // Medium case SZ_MEDIUM: skillratio = 300 + 400 * skill_lv; break; // Small case SZ_BIG: skillratio = 300 + 300 * skill_lv; break; // Large } RE_LVL_DMOD(120); break; case NC_AXEBOOMERANG: skillratio = 250 + 50 * skill_lv; if( sd ) { short index = sd->equip_index[EQI_HAND_R]; if( index >= 0 && sd->inventory_data[index] && sd->inventory_data[index]->type == IT_WEAPON ) skillratio += sd->inventory_data[index]->weight / 10; } RE_LVL_DMOD(100); break; case NC_POWERSWING: skillratio = 300 + 100*skill_lv + ( status_get_str(src)+status_get_dex(src) ) * status->get_lv(src) / 100; break; case NC_AXETORNADO: skillratio = 200 + 100 * skill_lv + st->vit; RE_LVL_DMOD(100); if( st->rhw.ele == ELE_WIND ) skillratio = skillratio * 125 / 100; if ( distance_bl(src, target) > 2 ) // Will deal 75% damage outside of 5x5 area. skillratio = skillratio * 75 / 100; break; case SC_FATALMENACE: skillratio = 100 * (skill_lv+1); RE_LVL_DMOD(100); break; case SC_TRIANGLESHOT: skillratio = ( 300 + (skill_lv-1) * status_get_agi(src)/2 ); RE_LVL_DMOD(120); break; case SC_FEINTBOMB: skillratio = (skill_lv+1) * (st->dex/2) * (sd?sd->status.job_level:50)/10; RE_LVL_DMOD(120); break; case LG_CANNONSPEAR: skillratio = (50 + st->str) * skill_lv; RE_LVL_DMOD(100); break; case LG_BANISHINGPOINT: skillratio = 50 * skill_lv + 30 * (sd ? pc->checkskill(sd,SM_BASH) : 10); RE_LVL_DMOD(100); break; case LG_SHIELDPRESS: skillratio = 150 * skill_lv + st->str; if( sd ) { short index = sd->equip_index[EQI_HAND_L]; if( index >= 0 && sd->inventory_data[index] && sd->inventory_data[index]->type == IT_ARMOR ) skillratio += sd->inventory_data[index]->weight / 10; } RE_LVL_DMOD(100); break; case LG_PINPOINTATTACK: skillratio = 100 * skill_lv + 5 * st->agi; RE_LVL_DMOD(120); break; case LG_RAGEBURST: if( sc ){ skillratio += -100 + (status_get_max_hp(src) - status_get_hp(src)) / 100 + sc->fv_counter * 200; clif->millenniumshield(src, (sc->fv_counter = 0)); } RE_LVL_DMOD(100); break; case LG_SHIELDSPELL: if ( sd && skill_lv == 1 ) { struct item_data *shield_data = sd->inventory_data[sd->equip_index[EQI_HAND_L]]; if( shield_data ) skillratio = 4 * status->get_lv(src) + 10 * shield_data->def + 2 * st->vit; } else skillratio = 0; // Prevents ATK damage from being done on LV 2 usage since LV 2 us MATK. [Rytech] break; case LG_MOONSLASHER: skillratio = 120 * skill_lv + 80 * (sd ? pc->checkskill(sd,LG_OVERBRAND) : 5); RE_LVL_DMOD(100); break; case LG_OVERBRAND: skillratio += -100 + 400 * skill_lv + 50 * ((sd) ? pc->checkskill(sd,CR_SPEARQUICKEN) : 1); RE_LVL_DMOD(100); break; case LG_OVERBRAND_BRANDISH: skillratio += -100 + 300 * skill_lv + status_get_str(src) + status_get_dex(src); RE_LVL_DMOD(100); break; case LG_OVERBRAND_PLUSATK: skillratio = 200 * skill_lv + rnd_value( 10, 100); RE_LVL_DMOD(100); break; case LG_RAYOFGENESIS: skillratio = 300 + 300 * skill_lv; RE_LVL_DMOD(100); break; case LG_EARTHDRIVE: if( sd ) { short index = sd->equip_index[EQI_HAND_L]; if( index >= 0 && sd->inventory_data[index] && sd->inventory_data[index]->type == IT_ARMOR ) skillratio = (1 + skill_lv) * sd->inventory_data[index]->weight / 10; } RE_LVL_DMOD(100); break; case LG_HESPERUSLIT: skillratio = 120 * skill_lv; if( sc && sc->data[SC_BANDING] ) skillratio += 200 * sc->data[SC_BANDING]->val2; if( sc && sc->data[SC_BANDING] && sc->data[SC_BANDING]->val2 > 5 ) skillratio = skillratio * 150 / 100; if( sc && sc->data[SC_INSPIRATION] ) skillratio += 600; RE_LVL_DMOD(100); break; case SR_DRAGONCOMBO: skillratio += 40 * skill_lv; RE_LVL_DMOD(100); break; case SR_SKYNETBLOW: if( sc && sc->data[SC_COMBOATTACK] && sc->data[SC_COMBOATTACK]->val1 == SR_DRAGONCOMBO )//ATK [{(Skill Level x 100) + (Caster AGI) + 150} x Caster Base Level / 100] % skillratio += 100 * skill_lv + status_get_agi(src) + 50; else //ATK [{(Skill Level x 80) + (Caster AGI)} x Caster Base Level / 100] % skillratio += -100 + 80 * skill_lv + status_get_agi(src); RE_LVL_DMOD(100); break; case SR_EARTHSHAKER: if( tsc && (tsc->data[SC_HIDING] || tsc->data[SC_CLOAKING] || // [(Skill Level x 150) x (Caster Base Level / 100) + (Caster INT x 3)] % tsc->data[SC_CHASEWALK] || tsc->data[SC_CLOAKINGEXCEED] || tsc->data[SC__INVISIBILITY]) ){ skillratio += -100 + 150 * skill_lv; RE_LVL_DMOD(100); skillratio += status_get_int(src) * 3; }else{ //[(Skill Level x 50) x (Caster Base Level / 100) + (Caster INT x 2)] % skillratio += 50 * (skill_lv-2); RE_LVL_DMOD(100); skillratio += status_get_int(src) * 2; } break; case SR_FALLENEMPIRE:// ATK [(Skill Level x 150 + 100) x Caster Base Level / 150] % skillratio += 150 *skill_lv; RE_LVL_DMOD(150); break; case SR_TIGERCANNON:// ATK [((Caster consumed HP + SP) / 4) x Caster Base Level / 100] % { int hp = status_get_max_hp(src) * (10 + 2 * skill_lv) / 100, sp = status_get_max_sp(src) * (6 + skill_lv) / 100; if( sc && sc->data[SC_COMBOATTACK] && sc->data[SC_COMBOATTACK]->val1 == SR_FALLENEMPIRE ) // ATK [((Caster consumed HP + SP) / 2) x Caster Base Level / 100] % skillratio += -100 + (hp+sp) / 2; else skillratio += -100 + (hp+sp) / 4; RE_LVL_DMOD(100); } break; case SR_RAMPAGEBLASTER: skillratio += 20 * skill_lv * (sd?sd->spiritball_old:5) - 100; if( sc && sc->data[SC_EXPLOSIONSPIRITS] ) { skillratio += sc->data[SC_EXPLOSIONSPIRITS]->val1 * 20; RE_LVL_DMOD(120); } else { RE_LVL_DMOD(150); } break; case SR_KNUCKLEARROW: if ( flag&4 || map->list[src->m].flag.gvg_castle || tst->mode&MD_BOSS ) { // ATK [(Skill Level x 150) + (1000 x Target current weight / Maximum weight) + (Target Base Level x 5) x (Caster Base Level / 150)] % skillratio = 150 * skill_lv + status->get_lv(target) * 5 * (status->get_lv(src) / 100) ; if( tsd && tsd->weight ) skillratio += 100 * (tsd->weight / tsd->max_weight); }else // ATK [(Skill Level x 100 + 500) x Caster Base Level / 100] % skillratio += 400 + (100 * skill_lv); RE_LVL_DMOD(100); break; case SR_WINDMILL: // ATK [(Caster Base Level + Caster DEX) x Caster Base Level / 100] % skillratio = status->get_lv(src) + status_get_dex(src); RE_LVL_DMOD(100); break; case SR_GATEOFHELL: if( sc && sc->data[SC_COMBOATTACK] && sc->data[SC_COMBOATTACK]->val1 == SR_FALLENEMPIRE ) skillratio += 800 * skill_lv -100; else skillratio += 500 * skill_lv -100; RE_LVL_DMOD(100); break; case SR_GENTLETOUCH_QUIET: skillratio += 100 * skill_lv - 100 + status_get_dex(src); RE_LVL_DMOD(100); break; case SR_HOWLINGOFLION: skillratio += 300 * skill_lv - 100; RE_LVL_DMOD(150); break; case SR_RIDEINLIGHTNING: // ATK [{(Skill Level x 200) + Additional Damage} x Caster Base Level / 100] % if( (st->rhw.ele) == ELE_WIND || (st->lhw.ele) == ELE_WIND ) skillratio += skill_lv * 50; skillratio += -100 + 200 * skill_lv; RE_LVL_DMOD(100); break; case WM_REVERBERATION_MELEE: skillratio += 200 + 100 * skill_lv; RE_LVL_DMOD(100); break; case WM_SEVERE_RAINSTORM_MELEE: skillratio = (st->agi + st->dex) * skill_lv / 5; RE_LVL_DMOD(100); break; case WM_GREAT_ECHO: { int chorusbonus = battle->calc_chorusbonus(sd); skillratio += 300 + 200 * skill_lv; //Chorus bonus don't count the first 2 Minstrel's/Wanderer's and only increases when their's 3 or more. [Rytech] if (chorusbonus >= 1 && chorusbonus <= 5) skillratio += 100<<(chorusbonus-1); // 1->100; 2->200; 3->400; 4->800; 5->1600 RE_LVL_DMOD(100); } break; case GN_CART_TORNADO: { int strbonus = bst->str; skillratio = 50 * skill_lv + (sd ? sd->cart_weight : battle_config.max_cart_weight) / 10 / max(150 - strbonus, 1) + 50 * (sd ? pc->checkskill(sd, GN_REMODELING_CART) : 5); } break; case GN_CARTCANNON: skillratio += -100 + (int)(50.0f * (sd ? pc->checkskill(sd, GN_REMODELING_CART) : 5) * (st->int_ / 40.0f) + 60.0f * skill_lv); break; case GN_SPORE_EXPLOSION: skillratio = 100 * skill_lv + (200 + st->int_) * status->get_lv(src) / 100; /* Fall through */ case GN_CRAZYWEED_ATK: skillratio += 400 + 100 * skill_lv; break; case GN_SLINGITEM_RANGEMELEEATK: if( sd ) { switch( sd->itemid ) { case ITEMID_APPLE_BOMB: skillratio = st->str + st->dex + 300; break; case ITEMID_MELON_BOMB: skillratio = st->str + st->dex + 500; break; case ITEMID_COCONUT_BOMB: case ITEMID_PINEAPPLE_BOMB: case ITEMID_BANANA_BOMB: skillratio = st->str + st->dex + 800; break; case ITEMID_BLACK_LUMP: skillratio = (st->str + st->agi + st->dex) / 3; // Black Lump break; case ITEMID_BLACK_HARD_LUMP: skillratio = (st->str + st->agi + st->dex) / 2; // Hard Black Lump break; case ITEMID_VERY_HARD_LUMP: skillratio = st->str + st->agi + st->dex; // Extremely Hard Black Lump break; } } break; case SO_VARETYR_SPEAR://ATK [{( Striking Level x 50 ) + ( Varetyr Spear Skill Level x 50 )} x Caster Base Level / 100 ] % skillratio += -100 + 50 * skill_lv + ( sd ? pc->checkskill(sd, SO_STRIKING) * 50 : 0 ); if( sc && sc->data[SC_BLAST_OPTION] ) skillratio += (sd ? sd->status.job_level * 5 : 0); break; // Physical Elemental Spirits Attack Skills case EL_CIRCLE_OF_FIRE: case EL_FIRE_BOMB_ATK: case EL_STONE_RAIN: skillratio += 200; break; case EL_FIRE_WAVE_ATK: skillratio += 500; break; case EL_TIDAL_WEAPON: skillratio += 1400; break; case EL_WIND_SLASH: skillratio += 100; break; case EL_HURRICANE: skillratio += 600; break; case EL_TYPOON_MIS: case EL_WATER_SCREW_ATK: skillratio += 900; break; case EL_STONE_HAMMER: skillratio += 400; break; case EL_ROCK_CRUSHER: skillratio += 700; break; case KO_JYUMONJIKIRI: skillratio += -100 + 150 * skill_lv; RE_LVL_DMOD(120); if( tsc && tsc->data[SC_KO_JYUMONJIKIRI] ) skillratio += status->get_lv(src) * skill_lv; break; case KO_HUUMARANKA: skillratio += -100 + 150 * skill_lv + status_get_agi(src) + status_get_dex(src) + 100 * (sd ? pc->checkskill(sd, NJ_HUUMA) : 0); break; case KO_SETSUDAN: skillratio += -100 + 100 * skill_lv; RE_LVL_DMOD(100); break; case MH_NEEDLE_OF_PARALYZE: skillratio += 600 + 100 * skill_lv; break; case MH_STAHL_HORN: skillratio += 400 + 100 * skill_lv; break; case MH_LAVA_SLIDE: skillratio += -100 + 70 * skill_lv; break; case MH_TINDER_BREAKER: case MH_MAGMA_FLOW: skillratio += -100 + 100 * skill_lv; break; default: battle->calc_skillratio_weapon_unknown(&attack_type, src, target, &skill_id, &skill_lv, &skillratio, &flag); break; } //Skill damage modifiers that stack linearly if(sc && skill_id != PA_SACRIFICE){ #ifdef RENEWAL_EDP if( sc->data[SC_EDP] ){ if( skill_id == AS_SONICBLOW || skill_id == GC_COUNTERSLASH || skill_id == GC_CROSSIMPACT ) skillratio >>= 1; } #endif if(sc->data[SC_OVERTHRUST]) skillratio += sc->data[SC_OVERTHRUST]->val3; if(sc->data[SC_OVERTHRUSTMAX]) skillratio += sc->data[SC_OVERTHRUSTMAX]->val2; if(sc->data[SC_BERSERK]) #ifndef RENEWAL skillratio += 100; #else skillratio += 200; if( sc->data[SC_TRUESIGHT] ) skillratio += 2*sc->data[SC_TRUESIGHT]->val1; if( sc->data[SC_LKCONCENTRATION] ) skillratio += sc->data[SC_LKCONCENTRATION]->val2; if( sd && sd->status.weapon == W_KATAR && (i=pc->checkskill(sd,ASC_KATAR)) > 0 ) skillratio += skillratio * (10 + 2 * i) / 100; #endif if( (!skill_id || skill_id == KN_AUTOCOUNTER) && sc->data[SC_CRUSHSTRIKE] ){ if( sd ) {//ATK [{Weapon Level * (Weapon Upgrade Level + 6) * 100} + (Weapon ATK) + (Weapon Weight)]% short index = sd->equip_index[EQI_HAND_R]; if( index >= 0 && sd->inventory_data[index] && sd->inventory_data[index]->type == IT_WEAPON ) skillratio += -100 + sd->inventory_data[index]->weight/10 + st->rhw.atk + 100 * sd->inventory_data[index]->wlv * (sd->status.inventory[index].refine + 6); } status_change_end(src, SC_CRUSHSTRIKE, INVALID_TIMER); skill->break_equip(src,EQP_WEAPON,2000,BCT_SELF); // 20% chance to destroy the weapon. } } } if( skillratio < 1 ) return 0; return skillratio; } void battle_calc_skillratio_magic_unknown(int *attack_type, struct block_list *src, struct block_list *target, uint16 *skill_id, uint16 *skill_lv, int *skillratio, int *flag) { } void battle_calc_skillratio_weapon_unknown(int *attack_type, struct block_list *src, struct block_list *target, uint16 *skill_id, uint16 *skill_lv, int *skillratio, int *flag) { } /*========================================== * Check damage trough status. * ATK may be MISS, BLOCKED FAIL, reduce, increase, end status... * After this we apply bg/gvg reduction *------------------------------------------*/ int64 battle_calc_damage(struct block_list *src,struct block_list *bl,struct Damage *d,int64 damage,uint16 skill_id,uint16 skill_lv) { struct map_session_data *sd = NULL; struct status_change *sc, *tsc; struct status_change_entry *sce; int div_, flag; nullpo_ret(bl); nullpo_ret(d); div_ = d->div_; flag = d->flag; // need check src for null pointer? if( !damage ) return 0; if( battle_config.ksprotection && mob->ksprotected(src, bl) ) return 0; if (bl->type == BL_PC) { sd=(struct map_session_data *)bl; //Special no damage states if(flag&BF_WEAPON && sd->special_state.no_weapon_damage) damage -= damage * sd->special_state.no_weapon_damage / 100; if(flag&BF_MAGIC && sd->special_state.no_magic_damage) damage -= damage * sd->special_state.no_magic_damage / 100; if(flag&BF_MISC && sd->special_state.no_misc_damage) damage -= damage * sd->special_state.no_misc_damage / 100; if(!damage) return 0; } sc = status->get_sc(bl); tsc = status->get_sc(src); if( sc && sc->data[SC_INVINCIBLE] && !sc->data[SC_INVINCIBLEOFF] ) return 1; if (skill_id == PA_PRESSURE) return damage; //This skill bypass everything else. if( sc && sc->count ) { //First, sc_*'s that reduce damage to 0. if( sc->data[SC_BASILICA] && !(status_get_mode(src)&MD_BOSS) ) { d->dmg_lv = ATK_BLOCK; return 0; } if( sc->data[SC_WHITEIMPRISON] && skill_id != HW_GRAVITATION ) { // Gravitation and Pressure do damage without removing the effect if( skill_id == MG_NAPALMBEAT || skill_id == MG_SOULSTRIKE || skill_id == WL_SOULEXPANSION || (skill_id && skill->get_ele(skill_id, skill_lv) == ELE_GHOST) || (!skill_id && (status->get_status_data(src))->rhw.ele == ELE_GHOST) ){ if( skill_id == WL_SOULEXPANSION ) damage <<= 1; // If used against a player in White Imprison, the skill deals double damage. status_change_end(bl,SC_WHITEIMPRISON,INVALID_TIMER); // Those skills do damage and removes effect }else{ d->dmg_lv = ATK_BLOCK; return 0; } } if( sc->data[SC_ZEPHYR] && ((flag&BF_LONG) || rnd()%100 < 10) ) { d->dmg_lv = ATK_BLOCK; return 0; } if( sc->data[SC_SAFETYWALL] && (flag&(BF_SHORT|BF_MAGIC))==BF_SHORT ) { struct skill_unit_group* group = skill->id2group(sc->data[SC_SAFETYWALL]->val3); uint16 src_skill_id = sc->data[SC_SAFETYWALL]->val2; if (group) { d->dmg_lv = ATK_BLOCK; if(src_skill_id == MH_STEINWAND){ if (--group->val2<=0) skill->del_unitgroup(group,ALC_MARK); if( (group->val3 - damage) > 0 ) group->val3 -= (int)cap_value(damage, INT_MIN, INT_MAX); else skill->del_unitgroup(group,ALC_MARK); return 0; } if( skill_id == SO_ELEMENTAL_SHIELD ) { if ( ( group->val2 - damage) > 0 ) { group->val2 -= (int)cap_value(damage,INT_MIN,INT_MAX); } else skill->del_unitgroup(group,ALC_MARK); return 0; } /** * in RE, SW possesses a lifetime equal to 3 times the caster's health **/ #ifdef RENEWAL if ( ( group->val2 - damage) > 0 ) { group->val2 -= (int)cap_value(damage,INT_MIN,INT_MAX); } else skill->del_unitgroup(group,ALC_MARK); if (--group->val3<=0) skill->del_unitgroup(group,ALC_MARK); #else if (--group->val2<=0) skill->del_unitgroup(group,ALC_MARK); #endif return 0; } status_change_end(bl, SC_SAFETYWALL, INVALID_TIMER); } if( ( sc->data[SC_PNEUMA] && (flag&(BF_MAGIC|BF_LONG)) == BF_LONG ) || sc->data[SC__MANHOLE] ) { d->dmg_lv = ATK_BLOCK; return 0; } if( sc->data[SC_NEUTRALBARRIER] && (flag&(BF_MAGIC|BF_LONG)) == BF_LONG && skill_id != CR_ACIDDEMONSTRATION ) { d->dmg_lv = ATK_BLOCK; return 0; } if( sc->data[SC__MAELSTROM] && (flag&BF_MAGIC) && skill_id && (skill->get_inf(skill_id)&INF_GROUND_SKILL) ) { // {(Maelstrom Skill LevelxAbsorbed Skill Level)+(Caster's Job/5)}/2 int sp = (sc->data[SC__MAELSTROM]->val1 * skill_lv + (sd ? sd->status.job_level / 5 : 0)) / 2; status->heal(bl, 0, sp, 3); d->dmg_lv = ATK_BLOCK; return 0; } if( sc->data[SC_WEAPONBLOCKING] && flag&(BF_SHORT|BF_WEAPON) && rnd()%100 < sc->data[SC_WEAPONBLOCKING]->val2 ) { clif->skill_nodamage(bl,src,GC_WEAPONBLOCKING,1,1); d->dmg_lv = ATK_BLOCK; sc_start2(src,bl,SC_COMBOATTACK,100,GC_WEAPONBLOCKING,src->id,2000); return 0; } if ((sce=sc->data[SC_AUTOGUARD]) && flag&BF_WEAPON && !(skill->get_nk(skill_id)&NK_NO_CARDFIX_ATK) && rnd()%100 < sce->val2) { int delay; struct status_change_entry *sce_d = sc->data[SC_DEVOTION]; // different delay depending on skill level [celest] if (sce->val1 <= 5) delay = 300; else if (sce->val1 > 5 && sce->val1 <= 9) delay = 200; else delay = 100; if (sce_d) { // If the target is too far away from the devotion caster, autoguard has no effect // Autoguard will be disabled later on struct block_list *d_bl = map->id2bl(sce_d->val1); if (d_bl && check_distance_bl(bl, d_bl, sce_d->val3) && ((d_bl->type == BL_MER && ((TBL_MER*)d_bl)->master && ((TBL_MER*)d_bl)->master->bl.id == bl->id) || (d_bl->type == BL_PC && ((TBL_PC*)d_bl)->devotion[sce_d->val2] == bl->id)) ) { // if player is target of devotion, show guard effect on the devotion caster rather than the target clif->skill_nodamage(d_bl, d_bl, CR_AUTOGUARD, sce->val1, 1); unit->set_walkdelay(d_bl, timer->gettick(), delay, 1); d->dmg_lv = ATK_MISS; return 0; } } else { clif->skill_nodamage(bl, bl, CR_AUTOGUARD, sce->val1, 1); unit->set_walkdelay(bl, timer->gettick(), delay, 1); if(sc->data[SC_CR_SHRINK] && rnd()%100<5*sce->val1) skill->blown(bl,src,skill->get_blewcount(CR_SHRINK,1),-1,0); d->dmg_lv = ATK_MISS; return 0; } } if( (sce = sc->data[SC_MILLENNIUMSHIELD]) && sce->val2 > 0 && damage > 0 ) { clif->skill_nodamage(bl, bl, RK_MILLENNIUMSHIELD, 1, 1); sce->val3 -= (int)cap_value(damage,INT_MIN,INT_MAX); // absorb damage d->dmg_lv = ATK_BLOCK; sc_start(src,bl,SC_STUN,15,0,skill->get_time2(RK_MILLENNIUMSHIELD,sce->val1)); // There is a chance to be stunned when one shield is broken. if( sce->val3 <= 0 ) { // Shield Down sce->val2--; if( sce->val2 > 0 ) { clif->millenniumshield(bl,sce->val2); sce->val3 = 1000; // Next Shield } else status_change_end(bl,SC_MILLENNIUMSHIELD,INVALID_TIMER); // All shields down } return 0; } if( (sce=sc->data[SC_PARRYING]) && flag&BF_WEAPON && skill_id != WS_CARTTERMINATION && rnd()%100 < sce->val2 ) { // attack blocked by Parrying clif->skill_nodamage(bl, bl, LK_PARRYING, sce->val1,1); return 0; } if(sc->data[SC_DODGE_READY] && ( !sc->opt1 || sc->opt1 == OPT1_BURNING ) && (flag&BF_LONG || sc->data[SC_STRUP]) && rnd()%100 < 20) { if (sd && pc_issit(sd)) pc->setstand(sd); //Stand it to dodge. clif->skill_nodamage(bl,bl,TK_DODGE,1,1); if (!sc->data[SC_COMBOATTACK]) sc_start4(src, bl, SC_COMBOATTACK, 100, TK_JUMPKICK, src->id, 1, 0, 2000); return 0; } if((sc->data[SC_HERMODE]) && flag&BF_MAGIC) return 0; if(sc->data[SC_NJ_TATAMIGAESHI] && (flag&(BF_MAGIC|BF_LONG)) == BF_LONG) return 0; if ((sce=sc->data[SC_KAUPE]) && rnd()%100 < sce->val2) { //Kaupe blocks damage (skill or otherwise) from players, mobs, homuns, mercenaries. clif->specialeffect(bl, 462, AREA); //Shouldn't end until Breaker's non-weapon part connects. if (skill_id != ASC_BREAKER || !(flag&BF_WEAPON)) if (--(sce->val3) <= 0) //We make it work like Safety Wall, even though it only blocks 1 time. status_change_end(bl, SC_KAUPE, INVALID_TIMER); return 0; } if (flag&BF_MAGIC && (sce=sc->data[SC_PRESTIGE]) != NULL && rnd()%100 < sce->val2) { clif->specialeffect(bl, 462, AREA); // Still need confirm it. return 0; } if (((sce=sc->data[SC_NJ_UTSUSEMI]) || sc->data[SC_NJ_BUNSINJYUTSU]) && flag&BF_WEAPON && !(skill->get_nk(skill_id)&NK_NO_CARDFIX_ATK)) { skill->additional_effect (src, bl, skill_id, skill_lv, flag, ATK_BLOCK, timer->gettick() ); if( !status->isdead(src) ) skill->counter_additional_effect( src, bl, skill_id, skill_lv, flag, timer->gettick() ); if (sce) { clif->specialeffect(bl, 462, AREA); skill->blown(src,bl,sce->val3,-1,0); } //Both need to be consumed if they are active. if (sce && --(sce->val2) <= 0) status_change_end(bl, SC_NJ_UTSUSEMI, INVALID_TIMER); if ((sce=sc->data[SC_NJ_BUNSINJYUTSU]) && --(sce->val2) <= 0) status_change_end(bl, SC_NJ_BUNSINJYUTSU, INVALID_TIMER); return 0; } //Now damage increasing effects if( sc->data[SC_LEXAETERNA] && skill_id != PF_SOULBURN #ifdef RENEWAL && skill_id != CR_ACIDDEMONSTRATION #endif ) { if( src->type != BL_MER || skill_id == 0 ) damage <<= 1; // Lex Aeterna only doubles damage of regular attacks from mercenaries if( skill_id != ASC_BREAKER || !(flag&BF_WEAPON) ) status_change_end(bl, SC_LEXAETERNA, INVALID_TIMER); //Shouldn't end until Breaker's non-weapon part connects. } #ifdef RENEWAL if( sc->data[SC_RAID] ) { damage += damage * 20 / 100; if (--sc->data[SC_RAID]->val1 == 0) status_change_end(bl, SC_RAID, INVALID_TIMER); } #endif if( damage ) { struct map_session_data *tsd = BL_CAST(BL_PC, src); if( sc->data[SC_DEEP_SLEEP] ) { damage += damage / 2; // 1.5 times more damage while in Deep Sleep. status_change_end(bl,SC_DEEP_SLEEP,INVALID_TIMER); } if( tsd && sd && sc->data[SC_COLD] && flag&BF_WEAPON ){ switch(tsd->status.weapon){ case W_MACE: case W_2HMACE: case W_1HAXE: case W_2HAXE: damage = damage * 150/100; break; case W_MUSICAL: case W_WHIP: if(!sd->state.arrow_atk) break; case W_BOW: case W_REVOLVER: case W_RIFLE: case W_GATLING: case W_SHOTGUN: case W_GRENADE: case W_DAGGER: case W_1HSWORD: case W_2HSWORD: damage = damage * 50/100; break; } } if( sc->data[SC_SIREN] ) status_change_end(bl,SC_SIREN,INVALID_TIMER); } //Finally damage reductions.... // Assumptio doubles the def & mdef on RE mode, otherwise gives a reduction on the final damage. [Igniz] #ifndef RENEWAL if( sc->data[SC_ASSUMPTIO] ) { if( map_flag_vs(bl->m) ) damage = damage*2/3; //Receive 66% damage else damage >>= 1; //Receive 50% damage } #endif if(sc->data[SC_DEFENDER] && #ifdef RENEWAL ((flag&(BF_LONG|BF_WEAPON)) == (BF_LONG|BF_WEAPON) || skill_id == CR_ACIDDEMONSTRATION)) #else (flag&(BF_LONG|BF_WEAPON)) == (BF_LONG|BF_WEAPON)) // In pre-re Defender doesn't reduce damage from Acid Demonstration #endif damage = damage * ( 100 - sc->data[SC_DEFENDER]->val2 ) / 100; #ifndef RENEWAL if(sc->data[SC_GS_ADJUSTMENT] && (flag&(BF_LONG|BF_WEAPON)) == (BF_LONG|BF_WEAPON)) damage -= damage * 20 / 100; #endif if(sc->data[SC_FOGWALL]) { if(flag&BF_SKILL) { //25% reduction if ( !(skill->get_inf(skill_id)&INF_GROUND_SKILL) && !(skill->get_nk(skill_id)&NK_SPLASH) ) damage -= 25*damage/100; } else if ((flag&(BF_LONG|BF_WEAPON)) == (BF_LONG|BF_WEAPON)) { damage >>= 2; //75% reduction } } if ( sc->data[SC_WATER_BARRIER] ) damage = damage * ( 100 - 20 ) / 100; if( sc->data[SC_FIRE_EXPANSION_SMOKE_POWDER] ) { if( (flag&(BF_SHORT|BF_WEAPON)) == (BF_SHORT|BF_WEAPON) ) damage -= 15 * damage / 100;//15% reduction to physical melee attacks else if( (flag&(BF_LONG|BF_WEAPON)) == (BF_LONG|BF_WEAPON) ) damage -= 50 * damage / 100;//50% reduction to physical ranged attacks } // Compressed code, fixed by map.h [Epoque] if (src->type == BL_MOB) { int i; if (sc->data[SC_MANU_DEF]) for (i=0;ARRAYLENGTH(mob->manuk)>i;i++) if (mob->manuk[i]==((TBL_MOB*)src)->class_) { damage -= damage * sc->data[SC_MANU_DEF]->val1 / 100; break; } if (sc->data[SC_SPL_DEF]) for (i=0;ARRAYLENGTH(mob->splendide)>i;i++) if (mob->splendide[i]==((TBL_MOB*)src)->class_) { damage -= damage * sc->data[SC_SPL_DEF]->val1 / 100; break; } } if((sce=sc->data[SC_ARMOR]) && //NPC_DEFENDER sce->val3&flag && sce->val4&flag) damage -= damage * sc->data[SC_ARMOR]->val2 / 100; if( sc->data[SC_ENERGYCOAT] && (skill_id == GN_HELLS_PLANT_ATK || #ifdef RENEWAL ((flag&BF_WEAPON || flag&BF_MAGIC) && skill_id != WS_CARTTERMINATION) #else (flag&BF_WEAPON && skill_id != WS_CARTTERMINATION) #endif ) ) { struct status_data *sstatus = status->get_status_data(bl); int per = 100*sstatus->sp / sstatus->max_sp -1; //100% should be counted as the 80~99% interval per /=20; //Uses 20% SP intervals. //SP Cost: 1% + 0.5% per every 20% SP if (!status->charge(bl, 0, (10+5*per)*sstatus->max_sp/1000)) status_change_end(bl, SC_ENERGYCOAT, INVALID_TIMER); //Reduction: 6% + 6% every 20% damage -= damage * (6 * (1+per)) / 100; } if(sc->data[SC_GRANITIC_ARMOR]){ damage -= damage * sc->data[SC_GRANITIC_ARMOR]->val2 / 100; } if(sc->data[SC_PAIN_KILLER]){ damage -= damage * sc->data[SC_PAIN_KILLER]->val3 / 100; } if((sce=sc->data[SC_MAGMA_FLOW]) && (rnd()%100 <= sce->val2) ){ skill->castend_damage_id(bl,src,MH_MAGMA_FLOW,sce->val1,timer->gettick(),0); } if( sc->data[SC_DARKCROW] && (flag&(BF_SHORT|BF_MAGIC)) == BF_SHORT ) damage += damage * sc->data[SC_DARKCROW]->val2 / 100; if( (sce = sc->data[SC_STONEHARDSKIN]) && flag&(BF_SHORT|BF_WEAPON) && damage > 0 ) { sce->val2 -= (int)cap_value(damage,INT_MIN,INT_MAX); if( src->type == BL_PC ) { TBL_PC *ssd = BL_CAST(BL_PC, src); if (ssd && ssd->status.weapon != W_BOW) skill->break_equip(src, EQP_WEAPON, 3000, BCT_SELF); } else skill->break_equip(src, EQP_WEAPON, 3000, BCT_SELF); // 30% chance to reduce monster's ATK by 25% for 10 seconds. if( src->type == BL_MOB ) sc_start(bl,src, SC_NOEQUIPWEAPON, 30, 0, skill->get_time2(RK_STONEHARDSKIN, sce->val1)); if( sce->val2 <= 0 ) status_change_end(bl, SC_STONEHARDSKIN, INVALID_TIMER); } /** * In renewal steel body reduces all incoming damage by 1/10 **/ #ifdef RENEWAL if( sc->data[SC_STEELBODY] ) { damage = damage > 10 ? damage / 10 : 1; } #endif //Finally added to remove the status of immobile when aimedbolt is used. [Jobbie] if( skill_id == RA_AIMEDBOLT && (sc->data[SC_WUGBITE] || sc->data[SC_ANKLESNARE] || sc->data[SC_ELECTRICSHOCKER]) ) { status_change_end(bl, SC_WUGBITE, INVALID_TIMER); status_change_end(bl, SC_ANKLESNARE, INVALID_TIMER); status_change_end(bl, SC_ELECTRICSHOCKER, INVALID_TIMER); } //Finally Kyrie because it may, or not, reduce damage to 0. if((sce = sc->data[SC_KYRIE]) && damage > 0){ sce->val2 -= (int)cap_value(damage,INT_MIN,INT_MAX); if(flag&BF_WEAPON || skill_id == TF_THROWSTONE){ if(sce->val2>=0) damage=0; else damage=-sce->val2; } if((--sce->val3)<=0 || (sce->val2<=0) || skill_id == AL_HOLYLIGHT) status_change_end(bl, SC_KYRIE, INVALID_TIMER); } if( sc->data[SC_MEIKYOUSISUI] && rnd()%100 < 40 ) // custom value damage = 0; if (!damage) return 0; if( (sce = sc->data[SC_LIGHTNINGWALK]) && flag&BF_LONG && rnd()%100 < sce->val1 ) { int dx[8]={0,-1,-1,-1,0,1,1,1}; int dy[8]={1,1,0,-1,-1,-1,0,1}; uint8 dir = map->calc_dir(bl, src->x, src->y); if( unit->movepos(bl, src->x-dx[dir], src->y-dy[dir], 1, 1) ) { clif->slide(bl,src->x-dx[dir],src->y-dy[dir]); unit->setdir(bl, dir); } d->dmg_lv = ATK_DEF; status_change_end(bl, SC_LIGHTNINGWALK, INVALID_TIMER); return 0; } //Probably not the most correct place, but it'll do here //(since battle_drain is strictly for players currently) if ((sce=sc->data[SC_HAMI_BLOODLUST]) && flag&BF_WEAPON && damage > 0 && rnd()%100 < sce->val3) status->heal(src, damage*sce->val4/100, 0, 3); if( (sce = sc->data[SC_FORCEOFVANGUARD]) && flag&BF_WEAPON && rnd()%100 < sce->val2 && sc->fv_counter <= sce->val3 ) clif->millenniumshield(bl, sc->fv_counter++); if (sc->data[SC_STYLE_CHANGE] && rnd()%2) { TBL_HOM *hd = BL_CAST(BL_HOM,bl); if (hd) homun->addspiritball(hd, 10); //add a sphere } if( sc->data[SC__DEADLYINFECT] && flag&BF_SHORT && damage > 0 && rnd()%100 < 30 + 10 * sc->data[SC__DEADLYINFECT]->val1 && !is_boss(src) ) status->change_spread(bl, src); // Deadly infect attacked side if (sd && damage > 0 && (sce = sc->data[SC_GENTLETOUCH_ENERGYGAIN]) != NULL) { if ( rnd() % 100 < sce->val2 ) pc->addspiritball(sd, skill->get_time(MO_CALLSPIRITS, 1), pc->getmaxspiritball(sd, 0)); } } //SC effects from caster side. if (tsc && tsc->count) { if( tsc->data[SC_INVINCIBLE] && !tsc->data[SC_INVINCIBLEOFF] ) damage += damage * 75 / 100; // [Epoque] if (bl->type == BL_MOB) { int i; if ( ((sce=tsc->data[SC_MANU_ATK]) && (flag&BF_WEAPON)) || ((sce=tsc->data[SC_MANU_MATK]) && (flag&BF_MAGIC)) ) for (i=0;ARRAYLENGTH(mob->manuk)>i;i++) if (((TBL_MOB*)bl)->class_==mob->manuk[i]) { damage += damage * sce->val1 / 100; break; } if ( ((sce=tsc->data[SC_SPL_ATK]) && (flag&BF_WEAPON)) || ((sce=tsc->data[SC_SPL_MATK]) && (flag&BF_MAGIC)) ) for (i=0;ARRAYLENGTH(mob->splendide)>i;i++) if (((TBL_MOB*)bl)->class_==mob->splendide[i]) { damage += damage * sce->val1 / 100; break; } } if( tsc->data[SC_POISONINGWEAPON] ) { struct status_data *tstatus = status->get_status_data(bl); if ( !(flag&BF_SKILL) && (flag&BF_WEAPON) && damage > 0 && rnd()%100 < tsc->data[SC_POISONINGWEAPON]->val3 ) { short rate = 100; if ( tsc->data[SC_POISONINGWEAPON]->val1 == 9 ) // Oblivion Curse gives a 2nd success chance after the 1st one passes which is reducible. [Rytech] rate = 100 - tstatus->int_ * 4 / 5; sc_start(src,bl,tsc->data[SC_POISONINGWEAPON]->val2,rate,tsc->data[SC_POISONINGWEAPON]->val1,skill->get_time2(GC_POISONINGWEAPON,1) - (tstatus->vit + tstatus->luk) / 2 * 1000); } } if( tsc->data[SC__DEADLYINFECT] && flag&BF_SHORT && damage > 0 && rnd()%100 < 30 + 10 * tsc->data[SC__DEADLYINFECT]->val1 && !is_boss(src) ) status->change_spread(src, bl); if (tsc->data[SC_SHIELDSPELL_REF] && tsc->data[SC_SHIELDSPELL_REF]->val1 == 1 && damage > 0) skill->break_equip(bl,EQP_ARMOR,10000,BCT_ENEMY ); if (tsc->data[SC_STYLE_CHANGE] && rnd()%2) { TBL_HOM *hd = BL_CAST(BL_HOM,bl); if (hd) homun->addspiritball(hd, 10); } if (src->type == BL_PC && damage > 0 && (sce = tsc->data[SC_GENTLETOUCH_ENERGYGAIN]) != NULL) { struct map_session_data *tsd = (struct map_session_data *)src; if ( tsd && rnd() % 100 < sce->val2 ) pc->addspiritball(tsd, skill->get_time(MO_CALLSPIRITS, 1), pc->getmaxspiritball(tsd, 0)); } } /* no data claims these settings affect anything other than players */ if( damage && sd && bl->type == BL_PC ) { switch( skill_id ) { //case PA_PRESSURE: /* pressure also belongs to this list but it doesn't reach this area -- so don't worry about it */ case HW_GRAVITATION: case NJ_ZENYNAGE: case KO_MUCHANAGE: break; default: if (flag & BF_SKILL) { //Skills get a different reduction than non-skills. [Skotlex] if (flag&BF_WEAPON) damage = damage * map->list[bl->m].weapon_damage_rate / 100; if (flag&BF_MAGIC) damage = damage * map->list[bl->m].magic_damage_rate / 100; if (flag&BF_MISC) damage = damage * map->list[bl->m].misc_damage_rate / 100; } else { //Normal attacks get reductions based on range. if (flag & BF_SHORT) damage = damage * map->list[bl->m].short_damage_rate / 100; if (flag & BF_LONG) damage = damage * map->list[bl->m].long_damage_rate / 100; } if(!damage) damage = 1; break; } } if(battle_config.skill_min_damage && damage > 0 && damage < div_) { if ((flag&BF_WEAPON && battle_config.skill_min_damage&1) || (flag&BF_MAGIC && battle_config.skill_min_damage&2) || (flag&BF_MISC && battle_config.skill_min_damage&4) ) damage = div_; } if( bl->type == BL_MOB && !status->isdead(bl) && src != bl) { if ( damage > 0 ) mob->skill_event((TBL_MOB*)bl,src,timer->gettick(),flag); if (skill_id) mob->skill_event((TBL_MOB*)bl,src,timer->gettick(),MSC_SKILLUSED|(skill_id<<16)); } if (sd && pc_ismadogear(sd) && rnd()%100 < 50) { int element = -1; if (!skill_id || (element = skill->get_ele(skill_id, skill_lv)) == -1) { // Take weapon's element struct status_data *sstatus = NULL; if (src->type == BL_PC && ((TBL_PC*)src)->bonus.arrow_ele) { element = ((TBL_PC*)src)->bonus.arrow_ele; } else if ((sstatus = status->get_status_data(src)) != NULL) { element = sstatus->rhw.ele; } } else if (element == -2) { // Use enchantment's element element = status_get_attack_sc_element(src,status->get_sc(src)); } else if (element == -3) { // Use random element element = rnd()%ELE_MAX; } if (element == ELE_FIRE) pc->overheat(sd, 1); else if (element == ELE_WATER) pc->overheat(sd, -1); } return damage; } /*========================================== * Calculates BG related damage adjustments. *------------------------------------------*/ // FIXME: flag is undocumented int64 battle_calc_bg_damage(struct block_list *src, struct block_list *bl, int64 damage, int div_, uint16 skill_id, uint16 skill_lv, int flag) { if( !damage ) return 0; nullpo_retr(damage, bl); if( bl->type == BL_MOB ) { struct mob_data* md = BL_CAST(BL_MOB, bl); if( flag&BF_SKILL && (md->class_ == MOBID_BLUE_CRYST || md->class_ == MOBID_PINK_CRYST) ) return 0; // Crystal cannot receive skill damage on battlegrounds } return damage; } /*========================================== * Calculates GVG related damage adjustments. *------------------------------------------*/ // FIXME: flag is undocumented int64 battle_calc_gvg_damage(struct block_list *src,struct block_list *bl,int64 damage,int div_,uint16 skill_id,uint16 skill_lv,int flag) { struct mob_data* md = BL_CAST(BL_MOB, bl); int class_ = status->get_class(bl); if (!damage) //No reductions to make. return 0; nullpo_retr(damage, src); nullpo_retr(damage, bl); if(md && md->guardian_data) { if(class_ == MOBID_EMPERIUM && flag&BF_SKILL) { //Skill immunity. switch (skill_id) { #ifndef RENEWAL case MO_TRIPLEATTACK: case HW_GRAVITATION: #endif case TF_DOUBLE: break; default: return 0; } } if(src->type != BL_MOB) { struct guild *g = src->type == BL_PC ? ((TBL_PC *)src)->guild : guild->search(status->get_guild_id(src)); if (class_ == MOBID_EMPERIUM && (!g || guild->checkskill(g,GD_APPROVAL) <= 0 )) return 0; if (g && battle_config.guild_max_castles && guild->checkcastles(g)>=battle_config.guild_max_castles) return 0; // [MouseJstr] } } switch (skill_id) { case PA_PRESSURE: case HW_GRAVITATION: case NJ_ZENYNAGE: case KO_MUCHANAGE: case NC_SELFDESTRUCTION: break; default: /* Uncomment if you want god-mode Emperiums at 100 defense. [Kisuka] if (md && md->guardian_data) { damage -= damage * (md->guardian_data->castle->defense/100) * battle_config.castle_defense_rate/100; } */ break; } return damage; } /*========================================== * HP/SP drain calculation *------------------------------------------*/ int battle_calc_drain(int64 damage, int rate, int per) { int64 diff = 0; if (per && rnd()%1000 < rate) { diff = (damage * per) / 100; if (diff == 0) { if (per > 0) diff = 1; else diff = -1; } } return (int)cap_value(diff,INT_MIN,INT_MAX); } /*========================================== * Consumes ammo for the given skill. *------------------------------------------*/ void battle_consume_ammo(TBL_PC*sd, int skill_id, int lv) { int qty=1; nullpo_retv(sd); if (!battle_config.arrow_decrement) return; if (skill_id && lv) { qty = skill->get_ammo_qty(skill_id, lv); if (!qty) qty = 1; } if(sd->equip_index[EQI_AMMO]>=0) //Qty check should have been done in skill_check_condition pc->delitem(sd, sd->equip_index[EQI_AMMO], qty, 0, DELITEM_SKILLUSE, LOG_TYPE_CONSUME); sd->state.arrow_atk = 0; } //Skill Range Criteria int battle_range_type(struct block_list *src, struct block_list *target, uint16 skill_id, uint16 skill_lv) { nullpo_retr(BF_SHORT, src); nullpo_retr(BF_SHORT, target); if (battle_config.skillrange_by_distance && (src->type&battle_config.skillrange_by_distance) ) { //based on distance between src/target [Skotlex] if (check_distance_bl(src, target, 5)) return BF_SHORT; return BF_LONG; } if (skill_id == SR_GATEOFHELL) { if (skill_lv < 5) return BF_SHORT; else return BF_LONG; } //based on used skill's range if (skill->get_range2(src, skill_id, skill_lv) < 5) return BF_SHORT; return BF_LONG; } int battle_adjust_skill_damage(int m, unsigned short skill_id) { if( map->list[m].skill_count ) { int i; ARR_FIND(0, map->list[m].skill_count, i, map->list[m].skills[i]->skill_id == skill_id ); if( i < map->list[m].skill_count ) { return map->list[m].skills[i]->modifier; } } return 0; } int battle_blewcount_bonus(struct map_session_data *sd, uint16 skill_id) { int i; nullpo_ret(sd); if (!sd->skillblown[0].id) return 0; //Apply the bonus blow count. [Skotlex] for (i = 0; i < ARRAYLENGTH(sd->skillblown) && sd->skillblown[i].id; i++) { if (sd->skillblown[i].id == skill_id) return sd->skillblown[i].val; } return 0; } //For quick div adjustment. #define damage_div_fix(dmg, div) do { if ((div) > 1) (dmg)*=(div); else if ((div) < 0) (div)*=-1; } while(0) /*========================================== * battle_calc_magic_attack [DracoRPG] *------------------------------------------*/ // FIXME: mflag is undocumented struct Damage battle_calc_magic_attack(struct block_list *src,struct block_list *target,uint16 skill_id,uint16 skill_lv,int mflag) { int nk; short s_ele = 0; unsigned int skillratio = 100; //Skill dmg modifiers. TBL_PC *sd; struct status_change *sc; struct Damage ad; struct status_data *sstatus = status->get_status_data(src); struct status_data *tstatus = status->get_status_data(target); struct { unsigned imdef : 2; unsigned infdef : 1; } flag; memset(&ad,0,sizeof(ad)); memset(&flag,0,sizeof(flag)); nullpo_retr(ad, src); nullpo_retr(ad, target); //Initial Values ad.damage = 1; ad.div_=skill->get_num(skill_id,skill_lv); ad.amotion = (skill->get_inf(skill_id)&INF_GROUND_SKILL) ? 0 : sstatus->amotion; //Amotion should be 0 for ground skills. ad.dmotion=tstatus->dmotion; ad.blewcount = skill->get_blewcount(skill_id,skill_lv); ad.flag=BF_MAGIC|BF_SKILL; ad.dmg_lv=ATK_DEF; nk = skill->get_nk(skill_id); flag.imdef = (nk&NK_IGNORE_DEF)? 1 : 0; sd = BL_CAST(BL_PC, src); sc = status->get_sc(src); //Initialize variables that will be used afterwards s_ele = skill->get_ele(skill_id, skill_lv); if (s_ele == -1){ // pl=-1 : the skill takes the weapon's element s_ele = sstatus->rhw.ele; if (sd && sd->charm_type != CHARM_TYPE_NONE && sd->charm_count >= MAX_SPIRITCHARM) { //Summoning 10 spiritcharm will endow your weapon s_ele = sd->charm_type; } }else if (s_ele == -2) //Use status element s_ele = status_get_attack_sc_element(src,status->get_sc(src)); else if( s_ele == -3 ) //Use random element s_ele = rnd()%ELE_MAX; if( skill_id == SO_PSYCHIC_WAVE ) { if( sc && sc->count ) { if( sc->data[SC_HEATER_OPTION] ) s_ele = sc->data[SC_HEATER_OPTION]->val4; else if( sc->data[SC_COOLER_OPTION] ) s_ele = sc->data[SC_COOLER_OPTION]->val4; else if( sc->data[SC_BLAST_OPTION] ) s_ele = sc->data[SC_BLAST_OPTION]->val3; else if( sc->data[SC_CURSED_SOIL_OPTION] ) s_ele = sc->data[SC_CURSED_SOIL_OPTION]->val4; } } //Set miscellaneous data that needs be filled if(sd) { sd->state.arrow_atk = 0; ad.blewcount += battle->blewcount_bonus(sd, skill_id); } //Skill Range Criteria ad.flag |= battle->range_type(src, target, skill_id, skill_lv); flag.infdef = (tstatus->mode&MD_PLANT) ? 1 : 0; if( !flag.infdef && target->type == BL_SKILL && ((TBL_SKILL*)target)->group->unit_id == UNT_REVERBERATION ) flag.infdef = 1; // Reverberation takes 1 damage switch(skill_id) { case MG_FIREWALL: if ( tstatus->def_ele == ELE_FIRE || battle->check_undead(tstatus->race, tstatus->def_ele) ) ad.blewcount = 0; //No knockback break; case NJ_KAENSIN: case PR_SANCTUARY: ad.dmotion = 0; //No flinch animation. break; case WL_HELLINFERNO: if( mflag&ELE_DARK ) s_ele = ELE_DARK; break; case KO_KAIHOU: if (sd && sd->charm_type != CHARM_TYPE_NONE && sd->charm_count > 0) { s_ele = sd->charm_type; } break; #ifdef RENEWAL case CR_ACIDDEMONSTRATION: case ASC_BREAKER: case HW_MAGICCRASHER: flag.imdef = 2; break; #endif } if (!flag.infdef) //No need to do the math for plants { int i; #ifdef RENEWAL ad.damage = 0; //reinitialize.. #endif //MATK_RATE scales the damage. 100 = no change. 50 is halved, 200 is doubled, etc #define MATK_RATE( a ) ( ad.damage= ad.damage*(a)/100 ) //Adds dmg%. 100 = +100% (double) damage. 10 = +10% damage #define MATK_ADDRATE( a ) ( ad.damage+= ad.damage*(a)/100 ) //Adds an absolute value to damage. 100 = +100 damage #define MATK_ADD( a ) ( ad.damage+= (a) ) switch (skill_id) { //Calc base damage according to skill case AL_HEAL: case PR_BENEDICTIO: case PR_SANCTUARY: ad.damage = skill->calc_heal(src, target, skill_id, skill_lv, false); break; /** * Arch Bishop **/ case AB_HIGHNESSHEAL: ad.damage = skill->calc_heal(src, target, AL_HEAL, 10, false) * ( 17 + 3 * skill_lv ) / 10; break; case PR_ASPERSIO: ad.damage = 40; break; case ALL_RESURRECTION: case PR_TURNUNDEAD: //Undead check is on skill_castend_damageid code. i = 20*skill_lv + sstatus->luk + sstatus->int_ + status->get_lv(src) + 200 - 200*tstatus->hp/tstatus->max_hp; // there is no changed in success chance in renewal. [malufett] if(i > 700) i = 700; if(rnd()%1000 < i && !(tstatus->mode&MD_BOSS)) ad.damage = tstatus->hp; else { #ifdef RENEWAL MATK_ADD(status->get_matk(src, 2)); #else ad.damage = status->get_lv(src) + sstatus->int_ + skill_lv * 10; #endif } break; case PF_SOULBURN: ad.damage = tstatus->sp * 2; break; /** * Arch Bishop **/ case AB_RENOVATIO: //Damage calculation from iRO wiki. [Jobbie] ad.damage = status->get_lv(src) * 10 + sstatus->int_; break; default: { MATK_ADD( status->get_matk(src, 2) ); #ifdef RENEWAL ad.damage = battle->calc_cardfix(BF_MAGIC, src, target, nk, s_ele, 0, ad.damage, 0, ad.flag); ad.damage = battle->calc_cardfix2(src, target, ad.damage, s_ele, nk, ad.flag); #endif if (nk&NK_SPLASHSPLIT) { // Divide MATK in case of multiple targets skill if(mflag>0) ad.damage/= mflag; else ShowError("0 inimigos alvejados por %d:%s, divisao por 0 evitada!\n", skill_id, skill->get_name(skill_id)); } if (sc){ if( sc->data[SC_TELEKINESIS_INTENSE] && s_ele == ELE_GHOST ) ad.damage += sc->data[SC_TELEKINESIS_INTENSE]->val3; } switch(skill_id){ case MG_FIREBOLT: case MG_COLDBOLT: case MG_LIGHTNINGBOLT: if ( sc && sc->data[SC_SPELLFIST] && mflag&BF_SHORT ) { skillratio = sc->data[SC_SPELLFIST]->val2 * 50 + sc->data[SC_SPELLFIST]->val4 * 100;// val4 = used bolt level, val2 = used spellfist level. [Rytech] ad.div_ = 1;// ad mods, to make it work similar to regular hits [Xazax] ad.flag = BF_WEAPON|BF_SHORT; ad.type = BDT_NORMAL; } /* Fall through */ default: MATK_RATE(battle->calc_skillratio(BF_MAGIC, src, target, skill_id, skill_lv, skillratio, mflag)); } //Constant/misc additions from skills if (skill_id == WZ_FIREPILLAR) MATK_ADD(100+50*skill_lv); if( sd && ( sd->status.class_ == JOB_ARCH_BISHOP_T || sd->status.class_ == JOB_ARCH_BISHOP ) && (i=pc->checkskill(sd,AB_EUCHARISTICA)) > 0 && (tstatus->race == RC_DEMON || tstatus->def_ele == ELE_DARK) ) MATK_ADDRATE(i); } } #ifndef HMAP_ZONE_DAMAGE_CAP_TYPE if (skill_id) { for(i = 0; i < map->list[target->m].zone->capped_skills_count; i++) { if( skill_id == map->list[target->m].zone->capped_skills[i]->nameid && (map->list[target->m].zone->capped_skills[i]->type & target->type) ) { if( target->type == BL_MOB && map->list[target->m].zone->capped_skills[i]->subtype != MZS_NONE ) { if( (((TBL_MOB*)target)->status.mode&MD_BOSS) && !(map->list[target->m].zone->disabled_skills[i]->subtype&MZS_BOSS) ) continue; if( ((TBL_MOB*)target)->special_state.clone && !(map->list[target->m].zone->disabled_skills[i]->subtype&MZS_CLONE) ) continue; } if( ad.damage > map->list[target->m].zone->capped_skills[i]->cap ) ad.damage = map->list[target->m].zone->capped_skills[i]->cap; if( ad.damage2 > map->list[target->m].zone->capped_skills[i]->cap ) ad.damage2 = map->list[target->m].zone->capped_skills[i]->cap; break; } } } #endif if(sd) { uint16 rskill;/* redirect skill */ //Damage bonuses if ((i = pc->skillatk_bonus(sd, skill_id))) ad.damage += ad.damage*i/100; switch(skill_id){ case WL_CHAINLIGHTNING_ATK: rskill = WL_CHAINLIGHTNING; break; case AB_DUPLELIGHT_MAGIC: rskill = AB_DUPLELIGHT; break; case WL_TETRAVORTEX_FIRE: case WL_TETRAVORTEX_WATER: case WL_TETRAVORTEX_WIND: case WL_TETRAVORTEX_GROUND: rskill = WL_TETRAVORTEX; break; case WL_SUMMON_ATK_FIRE: case WL_SUMMON_ATK_WIND: case WL_SUMMON_ATK_WATER: case WL_SUMMON_ATK_GROUND: rskill = WL_RELEASE; break; case WM_REVERBERATION_MAGIC: rskill = WM_REVERBERATION; break; default: rskill = skill_id; } if( (i = battle->adjust_skill_damage(src->m,rskill)) ) MATK_RATE(i); //Ignore Defense? if (!flag.imdef && ( sd->bonus.ignore_mdef_ele & ( 1 << tstatus->def_ele ) || sd->bonus.ignore_mdef_race & ( 1 << tstatus->race ) || sd->bonus.ignore_mdef_race & ( is_boss(target) ? 1 << RC_BOSS : 1 << RC_NONBOSS ) )) flag.imdef = 1; } ad.damage = battle->calc_defense(BF_MAGIC, src, target, skill_id, skill_lv, ad.damage, flag.imdef, 0); if(ad.damage<1) ad.damage=1; else if(sc){//only applies when hit // TODO: there is another factor that contribute with the damage and need to be formulated. [malufett] switch(skill_id){ case MG_LIGHTNINGBOLT: case MG_THUNDERSTORM: case MG_FIREBOLT: case MG_FIREWALL: case MG_COLDBOLT: case MG_FROSTDIVER: case WZ_EARTHSPIKE: case WZ_HEAVENDRIVE: if(sc->data[SC_GUST_OPTION] || sc->data[SC_PETROLOGY_OPTION] || sc->data[SC_PYROTECHNIC_OPTION] || sc->data[SC_AQUAPLAY_OPTION]) ad.damage += (6 + sstatus->int_/4) + max(sstatus->dex-10,0)/30; break; } } if (!(nk&NK_NO_ELEFIX)) ad.damage=battle->attr_fix(src, target, ad.damage, s_ele, tstatus->def_ele, tstatus->ele_lv); if( skill_id == CR_GRANDCROSS || skill_id == NPC_GRANDDARKNESS ) { //Apply the physical part of the skill's damage. [Skotlex] struct Damage wd = battle->calc_weapon_attack(src,target,skill_id,skill_lv,mflag); ad.damage = battle->attr_fix(src, target, wd.damage + ad.damage, s_ele, tstatus->def_ele, tstatus->ele_lv) * (100 + 40*skill_lv)/100; if( src == target ) { if( src->type == BL_PC ) ad.damage = ad.damage/2; else ad.damage = 0; } } #ifndef RENEWAL ad.damage = battle->calc_cardfix(BF_MAGIC, src, target, nk, s_ele, 0, ad.damage, 0, ad.flag); #endif } damage_div_fix(ad.damage, ad.div_); if (flag.infdef && ad.damage) ad.damage = ad.damage>0?1:-1; if (skill_id != ASC_BREAKER) ad.damage = battle->calc_damage(src, target, &ad, ad.damage, skill_id, skill_lv); if( map_flag_gvg2(target->m) ) ad.damage=battle->calc_gvg_damage(src,target,ad.damage,ad.div_,skill_id,skill_lv,ad.flag); else if( map->list[target->m].flag.battleground ) ad.damage=battle->calc_bg_damage(src,target,ad.damage,ad.div_,skill_id,skill_lv,ad.flag); switch( skill_id ) { /* post-calc modifiers */ case SO_VARETYR_SPEAR: { // Physical damage. struct Damage wd = battle->calc_weapon_attack(src,target,skill_id,skill_lv,mflag); if(!flag.infdef && ad.damage > 1) ad.damage += wd.damage; break; } //case HM_ERASER_CUTTER: } return ad; #undef MATK_RATE #undef MATK_ADDRATE #undef MATK_ADD } /*========================================== * Calculate Misc damage for skill_id *------------------------------------------*/ // FIXME: mflag is undocumented struct Damage battle_calc_misc_attack(struct block_list *src,struct block_list *target,uint16 skill_id,uint16 skill_lv,int mflag) { int temp; short i, nk; short s_ele; struct map_session_data *sd, *tsd; struct Damage md; //DO NOT CONFUSE with md of mob_data! struct status_data *sstatus = status->get_status_data(src); struct status_data *tstatus = status->get_status_data(target); struct status_change *tsc = status->get_sc(target); #ifdef RENEWAL struct status_change *sc = status->get_sc(src); #endif memset(&md,0,sizeof(md)); nullpo_retr(md, src); nullpo_retr(md, target); //Some initial values md.amotion = (skill->get_inf(skill_id)&INF_GROUND_SKILL) ? 0 : sstatus->amotion; md.dmotion=tstatus->dmotion; md.div_=skill->get_num( skill_id,skill_lv ); md.blewcount=skill->get_blewcount(skill_id,skill_lv); md.dmg_lv=ATK_DEF; md.flag=BF_MISC|BF_SKILL; nk = skill->get_nk(skill_id); sd = BL_CAST(BL_PC, src); tsd = BL_CAST(BL_PC, target); if(sd) { sd->state.arrow_atk = 0; md.blewcount += battle->blewcount_bonus(sd, skill_id); } s_ele = skill->get_ele(skill_id, skill_lv); if (s_ele < 0 && s_ele != -3) //Attack that takes weapon's element for misc attacks? Make it neutral [Skotlex] s_ele = ELE_NEUTRAL; else if (s_ele == -3) //Use random element s_ele = rnd()%ELE_MAX; //Skill Range Criteria md.flag |= battle->range_type(src, target, skill_id, skill_lv); switch( skill_id ) { #ifdef RENEWAL case HT_LANDMINE: case MA_LANDMINE: case HT_BLASTMINE: case HT_CLAYMORETRAP: md.damage = skill_lv * sstatus->dex * (3+status->get_lv(src)/100) * (1+sstatus->int_/35); md.damage += md.damage * (rnd()%20-10) / 100; md.damage += 40 * (sd?pc->checkskill(sd,RA_RESEARCHTRAP):0); break; #else case HT_LANDMINE: case MA_LANDMINE: md.damage=skill_lv*(sstatus->dex+75)*(100+sstatus->int_)/100; break; case HT_BLASTMINE: md.damage=skill_lv*(sstatus->dex/2+50)*(100+sstatus->int_)/100; break; case HT_CLAYMORETRAP: md.damage=skill_lv*(sstatus->dex/2+75)*(100+sstatus->int_)/100; break; #endif case HT_BLITZBEAT: case SN_FALCONASSAULT: //Blitz-beat Damage. if(!sd || (temp = pc->checkskill(sd,HT_STEELCROW)) <= 0) temp=0; md.damage=(sstatus->dex/10+sstatus->int_/2+temp*3+40)*2; if(mflag > 1) //Autocasted Blitz. nk|=NK_SPLASHSPLIT; if (skill_id == SN_FALCONASSAULT) { //Div fix of Blitzbeat temp = skill->get_num(HT_BLITZBEAT, 5); damage_div_fix(md.damage, temp); //Falcon Assault Modifier md.damage=md.damage*(150+70*skill_lv)/100; } break; case TF_THROWSTONE: md.damage=50; break; case BA_DISSONANCE: md.damage=30+skill_lv*10; if (sd) md.damage+= 3*pc->checkskill(sd,BA_MUSICALLESSON); break; case NPC_SELFDESTRUCTION: md.damage = sstatus->hp; break; case NPC_SMOKING: md.damage=3; break; case NPC_DARKBREATH: md.damage = 500 + (skill_lv-1)*1000 + rnd()%1000; if(md.damage > 9999) md.damage = 9999; break; case PA_PRESSURE: md.damage=500+300*skill_lv; break; case PA_GOSPEL: md.damage = 1+rnd()%9999; break; case CR_ACIDDEMONSTRATION: #ifdef RENEWAL {// [malufett] int64 matk=0, atk; short tdef = status->get_total_def(target); short tmdef = status->get_total_mdef(target); int targetVit = min(120, status_get_vit(target)); short totaldef = (tmdef + tdef - ((uint64)(tmdef + tdef) >> 32)) >> 1; // FIXME: What's the >> 32 supposed to do here? tmdef and tdef are both 16-bit... matk = battle->calc_magic_attack(src, target, skill_id, skill_lv, mflag).damage; atk = battle->calc_base_damage(src, target, skill_id, skill_lv, nk, false, s_ele, ELE_NEUTRAL, EQI_HAND_R, (sc && sc->data[SC_MAXIMIZEPOWER]?1:0)|(sc && sc->data[SC_WEAPONPERFECT]?8:0), md.flag); md.damage = matk + atk; if( src->type == BL_MOB ){ totaldef = (tdef + tmdef) >> 1; md.damage = 7 * targetVit * skill_lv * (atk + matk) / 100; /* // Pending [malufett] if( unknown condition ){ md.damage = 7 * md.damage % 20; md.damage = 7 * md.damage / 20; }*/ }else{ float vitfactor = 0.0f, ftemp; if( (vitfactor=(status_get_vit(target)-120.0f)) > 0) vitfactor = (vitfactor * (matk + atk) / 10) / status_get_vit(target); ftemp = max(0, vitfactor) + (targetVit * (matk + atk)) / 10; md.damage = (int64)(ftemp * 70 * skill_lv / 100); if (target->type == BL_PC) md.damage >>= 1; } md.damage -= totaldef; if( tsc && tsc->data[SC_LEXAETERNA] ) { md.damage <<= 1; status_change_end(target, SC_LEXAETERNA, INVALID_TIMER); } } #else // updated the formula based on a Japanese formula found to be exact [Reddozen] if(tstatus->vit+sstatus->int_) //crash fix md.damage = (int)(7*tstatus->vit*sstatus->int_*sstatus->int_ / (10*(tstatus->vit+sstatus->int_))); else md.damage = 0; if (tsd) md.damage>>=1; #endif // Some monsters have totaldef higher than md.damage in some cases, leading to md.damage < 0 if( md.damage < 0 ) md.damage = 0; if( md.damage > INT_MAX>>1 ) //Overflow prevention, will anyone whine if I cap it to a few billion? //Not capped to INT_MAX to give some room for further damage increase. md.damage = INT_MAX>>1; break; case KO_MUCHANAGE: md.damage = skill->get_zeny(skill_id ,skill_lv); md.damage = md.damage * (50 + rnd()%50) / 100; if ( is_boss(target) || (sd && !pc->checkskill(sd,NJ_TOBIDOUGU)) ) md.damage >>= 1; break; case NJ_ZENYNAGE: md.damage = skill->get_zeny(skill_id ,skill_lv); if (!md.damage) md.damage = 2; md.damage = rnd()%md.damage + md.damage; if (is_boss(target)) md.damage=md.damage / 3; else if (tsd) md.damage=md.damage / 2; break; case GS_FLING: md.damage = sd?sd->status.job_level:status->get_lv(src); break; case HVAN_EXPLOSION: //[orn] md.damage = sstatus->max_hp * (50 + 50 * skill_lv) / 100; break ; case ASC_BREAKER: { #ifndef RENEWAL md.damage = 500+rnd()%500 + 5*skill_lv * sstatus->int_; nk|=NK_IGNORE_FLEE|NK_NO_ELEFIX; //These two are not properties of the weapon based part. #else int ratio = 300 + 50 * skill_lv; int64 matk = battle->calc_magic_attack(src, target, skill_id, skill_lv, mflag).damage; short totaldef = status->get_total_def(target) + status->get_total_mdef(target); int64 atk = battle->calc_base_damage(src, target, skill_id, skill_lv, nk, false, s_ele, ELE_NEUTRAL, EQI_HAND_R, (sc && sc->data[SC_MAXIMIZEPOWER] ? 1 : 0) | (sc && sc->data[SC_WEAPONPERFECT] ? 8 : 0), md.flag); #ifdef RENEWAL_EDP if( sc && sc->data[SC_EDP] ) ratio >>= 1; #endif md.damage = (matk + atk) * ratio / 100; md.damage -= totaldef; #endif } break; case HW_GRAVITATION: md.damage = 200+200*skill_lv; md.dmotion = 0; //No flinch animation. break; case NPC_EVILLAND: md.damage = skill->calc_heal(src,target,skill_id,skill_lv,false); break; case RK_DRAGONBREATH: case RK_DRAGONBREATH_WATER: md.damage = ((status_get_hp(src) / 50) + (status_get_max_sp(src) / 4)) * skill_lv; RE_LVL_MDMOD(150); if (sd) md.damage = md.damage * (95 + 5 * pc->checkskill(sd,RK_DRAGONTRAINING)) / 100; md.flag |= BF_LONG|BF_WEAPON; break; /** * Ranger **/ case RA_CLUSTERBOMB: case RA_FIRINGTRAP: case RA_ICEBOUNDTRAP: md.damage = (int64)skill_lv * sstatus->dex + sstatus->int_ * 5 ; RE_LVL_TMDMOD(); if(sd) { int researchskill_lv = pc->checkskill(sd,RA_RESEARCHTRAP); if(researchskill_lv) md.damage = md.damage * 20 * researchskill_lv / (skill_id == RA_CLUSTERBOMB?50:100); else md.damage = 0; }else md.damage = md.damage * 200 / (skill_id == RA_CLUSTERBOMB?50:100); break; case WM_SOUND_OF_DESTRUCTION: md.damage = 1000 * (int64)skill_lv + sstatus->int_ * (sd ? pc->checkskill(sd,WM_LESSON) : 10); md.damage += md.damage * 10 * battle->calc_chorusbonus(sd) / 100; break; /** * Mechanic **/ case NC_SELFDESTRUCTION: { #ifdef RENEWAL short totaldef = status->get_total_def(target); #else short totaldef = tstatus->def2 + (short)status->get_def(target); #endif md.damage = ( (sd?pc->checkskill(sd,NC_MAINFRAME):10) + 8 ) * ( skill_lv + 1 ) * ( status_get_sp(src) + sstatus->vit ); RE_LVL_MDMOD(100); md.damage += status_get_hp(src) - totaldef; } break; case NC_MAGMA_ERUPTION: md.damage = 1200 + 400 * skill_lv; break; case GN_THORNS_TRAP: md.damage = 100 + 200 * skill_lv + sstatus->int_; break; case GN_HELLS_PLANT_ATK: md.damage = skill_lv * status->get_lv(target) * 10 + sstatus->int_ * 7 / 2 * (18 + (sd ? sd->status.job_level : 0) / 4) * (5 / (10 - (sd ? pc->checkskill(sd, AM_CANNIBALIZE) : 0))); md.damage = md.damage*(1000 + tstatus->mdef) / (1000 + tstatus->mdef * 10) - tstatus->mdef2; break; case KO_HAPPOKUNAI: { struct Damage wd = battle->calc_weapon_attack(src, target, 0, 1, mflag); #ifdef RENEWAL short totaldef = status->get_total_def(target); #else short totaldef = tstatus->def2 + (short)status->get_def(target); #endif if ( sd ) wd.damage += sd->bonus.arrow_atk; md.damage = (int)(3 * (1 + wd.damage) * (5 + skill_lv) / 5.0f); md.damage -= totaldef; } break; default: battle->calc_misc_attack_unknown(src, target, &skill_id, &skill_lv, &mflag, &md); break; } if (nk&NK_SPLASHSPLIT){ // Divide ATK among targets if(mflag>0) md.damage/= mflag; else ShowError("0 inimigos alvejados por %d:%s, devisao por 0 evitada!\n", skill_id, skill->get_name(skill_id)); } damage_div_fix(md.damage, md.div_); if (!(nk&NK_IGNORE_FLEE)) { i = 0; //Temp for "hit or no hit" if(tsc && tsc->opt1 && tsc->opt1 != OPT1_STONEWAIT && tsc->opt1 != OPT1_BURNING) i = 1; else { short flee = tstatus->flee, #ifdef RENEWAL hitrate = 0; //Default hitrate #else hitrate = 80; //Default hitrate #endif if(battle_config.agi_penalty_type && battle_config.agi_penalty_target&target->type) { unsigned char attacker_count; //256 max targets should be a sane max attacker_count = unit->counttargeted(target); if(attacker_count >= battle_config.agi_penalty_count) { if (battle_config.agi_penalty_type == 1) flee = (flee * (100 - (attacker_count - (battle_config.agi_penalty_count - 1))*battle_config.agi_penalty_num))/100; else // assume type 2: absolute reduction flee -= (attacker_count - (battle_config.agi_penalty_count - 1))*battle_config.agi_penalty_num; if(flee < 1) flee = 1; } } hitrate+= sstatus->hit - flee; #ifdef RENEWAL if( sd ) //in Renewal hit bonus from Vultures Eye is not anymore shown in status window hitrate += pc->checkskill(sd,AC_VULTURE); #endif if( skill_id == KO_MUCHANAGE ) hitrate = (int)((10 - ((float)1 / (status_get_dex(src) + status_get_luk(src))) * 500) * ((float)skill_lv / 2 + 5)); hitrate = cap_value(hitrate, battle_config.min_hitrate, battle_config.max_hitrate); if(rnd()%100 < hitrate) i = 1; } if (!i) { md.damage = 0; md.dmg_lv=ATK_FLEE; } } #ifndef HMAP_ZONE_DAMAGE_CAP_TYPE if (skill_id) { for(i = 0; i < map->list[target->m].zone->capped_skills_count; i++) { if( skill_id == map->list[target->m].zone->capped_skills[i]->nameid && (map->list[target->m].zone->capped_skills[i]->type & target->type) ) { if( target->type == BL_MOB && map->list[target->m].zone->capped_skills[i]->subtype != MZS_NONE ) { if( (((TBL_MOB*)target)->status.mode&MD_BOSS) && !(map->list[target->m].zone->disabled_skills[i]->subtype&MZS_BOSS) ) continue; if( ((TBL_MOB*)target)->special_state.clone && !(map->list[target->m].zone->disabled_skills[i]->subtype&MZS_CLONE) ) continue; } if( md.damage > map->list[target->m].zone->capped_skills[i]->cap ) md.damage = map->list[target->m].zone->capped_skills[i]->cap; if( md.damage2 > map->list[target->m].zone->capped_skills[i]->cap ) md.damage2 = map->list[target->m].zone->capped_skills[i]->cap; break; } } } #endif md.damage = battle->calc_cardfix(BF_MISC, src, target, nk, s_ele, 0, md.damage, 0, md.flag); md.damage = battle->calc_cardfix2(src, target, md.damage, s_ele, nk, md.flag); if(skill_id){ uint16 rskill;/* redirect skill id */ switch(skill_id){ case GN_HELLS_PLANT_ATK: rskill = GN_HELLS_PLANT; break; default: rskill = skill_id; } if (sd && (i = pc->skillatk_bonus(sd, rskill)) != 0) md.damage += md.damage*i/100; } if( (i = battle->adjust_skill_damage(src->m,skill_id)) ) md.damage = md.damage * i / 100; if(md.damage < 0) md.damage = 0; else if(md.damage && tstatus->mode&MD_PLANT){ switch(skill_id){ case HT_LANDMINE: case MA_LANDMINE: case HT_BLASTMINE: case HT_CLAYMORETRAP: case RA_CLUSTERBOMB: #ifdef RENEWAL break; #endif default: md.damage = 1; } } if(!(nk&NK_NO_ELEFIX)) md.damage=battle->attr_fix(src, target, md.damage, s_ele, tstatus->def_ele, tstatus->ele_lv); md.damage=battle->calc_damage(src,target,&md,md.damage,skill_id,skill_lv); if( map_flag_gvg2(target->m) ) md.damage=battle->calc_gvg_damage(src,target,md.damage,md.div_,skill_id,skill_lv,md.flag); else if( map->list[target->m].flag.battleground ) md.damage=battle->calc_bg_damage(src,target,md.damage,md.div_,skill_id,skill_lv,md.flag); switch( skill_id ) { case RA_FIRINGTRAP: case RA_ICEBOUNDTRAP: if( md.damage == 1 ) break; case RA_CLUSTERBOMB: { struct Damage wd; wd = battle->calc_weapon_attack(src,target,skill_id,skill_lv,mflag); md.damage += wd.damage; } break; case NJ_ZENYNAGE: if( sd ) { if ( md.damage > sd->status.zeny ) md.damage = sd->status.zeny; pc->payzeny(sd, (int)cap_value(md.damage,INT_MIN,INT_MAX),LOG_TYPE_STEAL,NULL); } break; } return md; } void battle_calc_misc_attack_unknown(struct block_list *src, struct block_list *target, uint16 *skill_id, uint16 *skill_lv, int *mflag, struct Damage *md) { } /*========================================== * battle_calc_weapon_attack (by Skotlex) *------------------------------------------*/ // FIXME: wflag is undocumented struct Damage battle_calc_weapon_attack(struct block_list *src,struct block_list *target,uint16 skill_id,uint16 skill_lv,int wflag) { unsigned int skillratio = 100; //Skill dmg modifiers. short temp=0; short s_ele, s_ele_; int i, nk; bool n_ele = false; // non-elemental struct map_session_data *sd, *tsd; struct Damage wd; struct status_change *sc = status->get_sc(src); struct status_change *tsc = status->get_sc(target); struct status_data *sstatus = status->get_status_data(src); struct status_data *tstatus = status->get_status_data(target); struct { unsigned hit : 1; ///< the attack Hit? (not a miss) unsigned cri : 1; ///< Critical hit unsigned idef : 1; ///< Ignore defense unsigned idef2 : 1; ///< Ignore defense (left weapon) unsigned pdef : 2; ///< Pierces defense (Investigate/Ice Pick) unsigned pdef2 : 2; ///< 1: Use def+def2/100, 2: Use def+def2/50 unsigned infdef : 1; ///< Infinite defense (plants) unsigned arrow : 1; ///< Attack is arrow-based unsigned rh : 1; ///< Attack considers right hand (wd.damage) unsigned lh : 1; ///< Attack considers left hand (wd.damage2) unsigned weapon : 1; ///< It's a weapon attack (consider VVS, and all that) #ifdef RENEWAL unsigned tdef : 1; ///< Total defense reduction unsigned distinct : 1; ///< Has its own battle calc formula #endif } flag; memset(&wd,0,sizeof(wd)); memset(&flag,0,sizeof(flag)); nullpo_retr(wd, src); nullpo_retr(wd, target); //Initial flag flag.rh=1; flag.weapon=1; flag.infdef=(tstatus->mode&MD_PLANT && skill_id != RA_CLUSTERBOMB #ifdef RENEWAL && skill_id != HT_FREEZINGTRAP #endif ?1:0); if( !flag.infdef && target->type == BL_SKILL && ((TBL_SKILL*)target)->group->unit_id == UNT_REVERBERATION ) flag.infdef = 1; // Reverberation takes 1 damage //Initial Values wd.type = BDT_NORMAL; wd.div_ = skill_id ? skill->get_num(skill_id,skill_lv) : 1; wd.amotion=(skill_id && skill->get_inf(skill_id)&INF_GROUND_SKILL)?0:sstatus->amotion; //Amotion should be 0 for ground skills. if(skill_id == KN_AUTOCOUNTER) wd.amotion >>= 1; wd.dmotion=tstatus->dmotion; wd.blewcount = skill_id ? skill->get_blewcount(skill_id,skill_lv) : 0; wd.flag = BF_WEAPON; //Initial Flag wd.flag |= (skill_id||wflag)?BF_SKILL:BF_NORMAL; // Baphomet card's splash damage is counted as a skill. [Inkfish] wd.dmg_lv=ATK_DEF; //This assumption simplifies the assignation later nk = skill->get_nk(skill_id); if( !skill_id && wflag ) //If flag, this is splash damage from Baphomet Card and it always hits. nk |= NK_NO_CARDFIX_ATK|NK_IGNORE_FLEE; flag.hit = (nk&NK_IGNORE_FLEE) ? 1 : 0; flag.idef = flag.idef2 = (nk&NK_IGNORE_DEF) ? 1 : 0; #ifdef RENEWAL flag.tdef = 0; #endif if (sc && !sc->count) sc = NULL; //Skip checking as there are no status changes active. if (tsc && !tsc->count) tsc = NULL; //Skip checking as there are no status changes active. sd = BL_CAST(BL_PC, src); tsd = BL_CAST(BL_PC, target); if(sd) wd.blewcount += battle->blewcount_bonus(sd, skill_id); //Set miscellaneous data that needs be filled regardless of hit/miss if( (sd && sd->state.arrow_atk) || (!sd && ((skill_id && skill->get_ammotype(skill_id)) || sstatus->rhw.range>3)) ) flag.arrow = 1; if(skill_id) { wd.flag |= battle->range_type(src, target, skill_id, skill_lv); switch(skill_id) { case MO_FINGEROFFENSIVE: if(sd) { if (battle_config.finger_offensive_type) wd.div_ = 1; else wd.div_ = sd->spiritball_old; } break; case HT_PHANTASMIC: //Since these do not consume ammo, they need to be explicitly set as arrow attacks. flag.arrow = 1; break; #ifndef RENEWAL case PA_SHIELDCHAIN: case CR_SHIELDBOOMERANG: #endif case LG_SHIELDPRESS: case LG_EARTHDRIVE: flag.weapon = 0; break; case KN_PIERCE: case ML_PIERCE: wd.div_= (wd.div_>0?tstatus->size+1:-(tstatus->size+1)); break; case TF_DOUBLE: //For NPC used skill. case GS_CHAINACTION: wd.type = BDT_MULTIHIT; break; case GS_GROUNDDRIFT: case KN_SPEARSTAB: case KN_BOWLINGBASH: case MS_BOWLINGBASH: case MO_BALKYOUNG: case TK_TURNKICK: wd.blewcount=0; break; case KN_AUTOCOUNTER: wd.flag=(wd.flag&~BF_SKILLMASK)|BF_NORMAL; break; case NPC_CRITICALSLASH: case LG_PINPOINTATTACK: flag.cri = 1; //Always critical skill. break; case LK_SPIRALPIERCE: if (!sd) wd.flag=(wd.flag&~(BF_RANGEMASK|BF_WEAPONMASK))|BF_LONG|BF_MISC; break; //When in banding, the number of hits is equal to the number of Royal Guards in banding. case LG_HESPERUSLIT: if( sc && sc->data[SC_BANDING] && sc->data[SC_BANDING]->val2 > 3 ) wd.div_ = sc->data[SC_BANDING]->val2; break; case MO_INVESTIGATE: flag.pdef = flag.pdef2 = 2; break; case RA_AIMEDBOLT: if( tsc && (tsc->data[SC_WUGBITE] || tsc->data[SC_ANKLESNARE] || tsc->data[SC_ELECTRICSHOCKER]) ) wd.div_ = tstatus->size + 2 + ( (rnd()%100 < 50-tstatus->size*10) ? 1 : 0 ); break; case NPC_EARTHQUAKE: wd.flag = (wd.flag&~(BF_WEAPON)) | BF_MAGIC; break; #ifdef RENEWAL case MO_EXTREMITYFIST: case GS_PIERCINGSHOT: case AM_ACIDTERROR: case AM_DEMONSTRATION: case NJ_ISSEN: case PA_SACRIFICE: flag.distinct = 1; break; case GN_CARTCANNON: case PA_SHIELDCHAIN: case GS_MAGICALBULLET: case NJ_SYURIKEN: case KO_BAKURETSU: flag.distinct = 1; /* Fall through */ case NJ_KUNAI: case HW_MAGICCRASHER: flag.tdef = 1; break; #endif } } else //Range for normal attacks. wd.flag |= flag.arrow?BF_LONG:BF_SHORT; if ((!skill_id || skill_id == PA_SACRIFICE) && tstatus->flee2 && rnd()%1000 < tstatus->flee2) { //Check for Lucky Dodge wd.type = BDT_PDODGE; wd.dmg_lv=ATK_LUCKY; if (wd.div_ < 0) wd.div_*=-1; return wd; } s_ele = s_ele_ = skill_id ? skill->get_ele(skill_id, skill_lv) : -1; if (s_ele == -1) { //Take weapon's element s_ele = sstatus->rhw.ele; s_ele_ = sstatus->lhw.ele; if (sd && sd->charm_type != CHARM_TYPE_NONE && sd->charm_count >= MAX_SPIRITCHARM) { //Summoning 10 spiritcharm will endow your weapon. s_ele = s_ele_ = sd->charm_type; } if( flag.arrow && sd && sd->bonus.arrow_ele ) s_ele = sd->bonus.arrow_ele; if( battle_config.attack_attr_none&src->type ) n_ele = true; //Weapon's element is "not elemental" } else if (s_ele == -2) { //Use enchantment's element s_ele = s_ele_ = status_get_attack_sc_element(src,sc); } else if (s_ele == -3) { //Use random element s_ele = s_ele_ = rnd()%ELE_MAX; } switch (skill_id) { case GS_GROUNDDRIFT: s_ele = s_ele_ = wflag; //element comes in flag. break; case LK_SPIRALPIERCE: if (!sd) n_ele = false; //forced neutral for monsters break; case LG_HESPERUSLIT: if ( sc && sc->data[SC_BANDING] && sc->data[SC_BANDING]->val2 == 5 ) s_ele = ELE_HOLY; // Banding with 5 RGs: change atk element to Holy. break; } if (!(nk & NK_NO_ELEFIX) && !n_ele) if (src->type == BL_HOM) n_ele = true; //skill is "not elemental" if (sc && sc->data[SC_GOLDENE_FERSE] && ((!skill_id && (rnd() % 100 < sc->data[SC_GOLDENE_FERSE]->val4)) || skill_id == MH_STAHL_HORN)) { s_ele = s_ele_ = ELE_HOLY; n_ele = false; } if(!skill_id) { //Skills ALWAYS use ONLY your right-hand weapon (tested on Aegis 10.2) if (sd && sd->weapontype1 == 0 && sd->weapontype2 > 0) { flag.rh=0; flag.lh=1; } if (sstatus->lhw.atk) flag.lh=1; } if (sd && !skill_id) { //Check for double attack. if (( (skill_lv=pc->checkskill(sd,TF_DOUBLE)) > 0 && sd->weapontype1 == W_DAGGER ) || ( sd->bonus.double_rate > 0 && sd->weapontype1 != W_FIST ) //Will fail bare-handed || ( sc && sc->data[SC_KAGEMUSYA] && sd->weapontype1 != W_FIST ) // Need confirmation ) { //Success chance is not added, the higher one is used [Skotlex] if( rnd()%100 < ( 5*skill_lv > sd->bonus.double_rate ? 5*skill_lv : sc && sc->data[SC_KAGEMUSYA]?sc->data[SC_KAGEMUSYA]->val1*3:sd->bonus.double_rate ) ) { wd.div_ = skill->get_num(TF_DOUBLE,skill_lv?skill_lv:1); wd.type = BDT_MULTIHIT; } } else if( sd->weapontype1 == W_REVOLVER && (skill_lv = pc->checkskill(sd,GS_CHAINACTION)) > 0 && rnd()%100 < 5*skill_lv ) { wd.div_ = skill->get_num(GS_CHAINACTION,skill_lv); wd.type = BDT_MULTIHIT; } else if(sc && sc->data[SC_FEARBREEZE] && sd->weapontype1==W_BOW && (i = sd->equip_index[EQI_AMMO]) >= 0 && sd->inventory_data[i] && sd->status.inventory[i].amount > 1){ int chance = rnd()%100; switch(sc->data[SC_FEARBREEZE]->val1){ case 5: if( chance < 3){// 3 % chance to attack 5 times. wd.div_ = 5; break; } case 4: if( chance < 7){// 6 % chance to attack 4 times. wd.div_ = 4; break; } case 3: if( chance < 10){// 9 % chance to attack 3 times. wd.div_ = 3; break; } case 2: case 1: if( chance < 13){// 12 % chance to attack 2 times. wd.div_ = 2; break; } } if ( wd.div_ > 1 ) { wd.div_ = min(wd.div_, sd->status.inventory[i].amount); sc->data[SC_FEARBREEZE]->val4 = wd.div_ - 1; wd.type = BDT_MULTIHIT; } } } //Check for critical if( !flag.cri && wd.type != BDT_MULTIHIT && sstatus->cri && (!skill_id || skill_id == KN_AUTOCOUNTER || skill_id == SN_SHARPSHOOTING || skill_id == MA_SHARPSHOOTING || skill_id == NJ_KIRIKAGE)) { short cri = sstatus->cri; if (sd) { // Check for katar here as katar crit bonus should not be displayed if (sd->status.weapon == W_KATAR) { cri <<= 1; } cri+= sd->critaddrace[tstatus->race]; if (flag.arrow) { cri += sd->bonus.arrow_cri; } } if (sc && sc->data[SC_CAMOUFLAGE]) cri += 10 * (10-sc->data[SC_CAMOUFLAGE]->val4); #ifndef RENEWAL //The official equation is *2, but that only applies when sd's do critical. //Therefore, we use the old value 3 on cases when an sd gets attacked by a mob cri -= tstatus->luk*(!sd&&tsd?3:2); #else cri -= status->get_lv(target) / 15 + 2 * status_get_luk(target); #endif if( tsc && tsc->data[SC_SLEEP] ) { cri <<= 1; } switch (skill_id) { case 0: if(!(sc && sc->data[SC_AUTOCOUNTER])) break; status_change_end(src, SC_AUTOCOUNTER, INVALID_TIMER); case KN_AUTOCOUNTER: if(battle_config.auto_counter_type && (battle_config.auto_counter_type&src->type)) flag.cri = 1; else cri <<= 1; break; case SN_SHARPSHOOTING: case MA_SHARPSHOOTING: cri += 200; break; case NJ_KIRIKAGE: cri += 250 + 50*skill_lv; break; } if(tsd && tsd->bonus.critical_def) cri = cri * ( 100 - tsd->bonus.critical_def ) / 100; if (rnd()%1000 < cri) flag.cri = 1; } if (flag.cri) { wd.type = BDT_CRIT; #ifndef RENEWAL flag.idef = flag.idef2 = #endif flag.hit = 1; } else { //Check for Perfect Hit if(sd && sd->bonus.perfect_hit > 0 && rnd()%100 < sd->bonus.perfect_hit) flag.hit = 1; if (sc && sc->data[SC_FUSION]) { flag.hit = 1; //SG_FUSION always hit [Komurka] flag.idef = flag.idef2 = 1; //def ignore [Komurka] } if( !flag.hit ) switch(skill_id) { case AS_SPLASHER: if( !wflag ) // Always hits the one exploding. flag.hit = 1; break; case CR_SHIELDBOOMERANG: if( sc && sc->data[SC_SOULLINK] && sc->data[SC_SOULLINK]->val2 == SL_CRUSADER ) flag.hit = 1; break; } if (tsc && !flag.hit && tsc->opt1 && tsc->opt1 != OPT1_STONEWAIT && tsc->opt1 != OPT1_BURNING) flag.hit = 1; } if (!flag.hit) { //Hit/Flee calculation short flee = tstatus->flee; #ifdef RENEWAL short hitrate = 0; //Default hitrate #else short hitrate = 80; //Default hitrate #endif if(battle_config.agi_penalty_type && battle_config.agi_penalty_target&target->type) { unsigned char attacker_count; //256 max targets should be a sane max attacker_count = unit->counttargeted(target); if(attacker_count >= battle_config.agi_penalty_count) { if (battle_config.agi_penalty_type == 1) flee = (flee * (100 - (attacker_count - (battle_config.agi_penalty_count - 1))*battle_config.agi_penalty_num))/100; else //asume type 2: absolute reduction flee -= (attacker_count - (battle_config.agi_penalty_count - 1))*battle_config.agi_penalty_num; if(flee < 1) flee = 1; } } hitrate+= sstatus->hit - flee; if(wd.flag&BF_LONG && !skill_id && //Fogwall's hit penalty is only for normal ranged attacks. tsc && tsc->data[SC_FOGWALL]) hitrate -= 50; if(sd && flag.arrow) hitrate += sd->bonus.arrow_hit; #ifdef RENEWAL if( sd ) //in Renewal hit bonus from Vultures Eye is not anymore shown in status window hitrate += pc->checkskill(sd,AC_VULTURE); #endif switch(skill_id) { //Hit skill modifiers //It is proven that bonus is applied on final hitrate, not hit. case SM_BASH: case MS_BASH: hitrate += hitrate * 5 * skill_lv / 100; break; case MS_MAGNUM: case SM_MAGNUM: hitrate += hitrate * 10 * skill_lv / 100; break; case KN_AUTOCOUNTER: case PA_SHIELDCHAIN: case NPC_WATERATTACK: case NPC_GROUNDATTACK: case NPC_FIREATTACK: case NPC_WINDATTACK: case NPC_POISONATTACK: case NPC_HOLYATTACK: case NPC_DARKNESSATTACK: case NPC_UNDEADATTACK: case NPC_TELEKINESISATTACK: case NPC_BLEEDING: case NPC_EARTHQUAKE: case NPC_FIREBREATH: case NPC_ICEBREATH: case NPC_THUNDERBREATH: case NPC_ACIDBREATH: case NPC_DARKNESSBREATH: hitrate += hitrate * 20 / 100; break; case KN_PIERCE: case ML_PIERCE: hitrate += hitrate * 5 * skill_lv / 100; break; case AS_SONICBLOW: if(sd && pc->checkskill(sd,AS_SONICACCEL)>0) hitrate += hitrate * 50 / 100; break; case MC_CARTREVOLUTION: case GN_CART_TORNADO: case GN_CARTCANNON: if( sd && pc->checkskill(sd, GN_REMODELING_CART) ) hitrate += pc->checkskill(sd, GN_REMODELING_CART) * 4; break; case GC_VENOMPRESSURE: hitrate += 10 + 4 * skill_lv; break; case SC_FATALMENACE: hitrate -= 35 - 5 * skill_lv; break; case LG_BANISHINGPOINT: hitrate += 3 * skill_lv; break; } if( sd ) { // Weaponry Research hidden bonus if ((temp = pc->checkskill(sd,BS_WEAPONRESEARCH)) > 0) hitrate += hitrate * ( 2 * temp ) / 100; if( (sd->status.weapon == W_1HSWORD || sd->status.weapon == W_DAGGER) && (temp = pc->checkskill(sd, GN_TRAINING_SWORD))>0 ) hitrate += 3 * temp; } hitrate = cap_value(hitrate, battle_config.min_hitrate, battle_config.max_hitrate); #ifdef RENEWAL if( !sd ) hitrate = cap_value(hitrate, 5, 95); #endif if(rnd()%100 >= hitrate){ wd.dmg_lv = ATK_FLEE; if (skill_id == SR_GATEOFHELL) flag.hit = 1;/* will hit with the special */ } else flag.hit = 1; } //End hit/miss calculation if (flag.hit && !flag.infdef) { //No need to do the math for plants //Hitting attack //Assuming that 99% of the cases we will not need to check for the flag.rh... we don't. //ATK_RATE scales the damage. 100 = no change. 50 is halved, 200 is doubled, etc #define ATK_RATE( a ) do { int64 temp__ = (a); wd.damage= wd.damage*temp__/100 ; if(flag.lh) wd.damage2= wd.damage2*temp__/100; } while(0) #define ATK_RATE2( a , b ) do { wd.damage= wd.damage*(a)/100 ; if(flag.lh) wd.damage2= wd.damage2*(b)/100; } while(0) #define ATK_RATER(a) ( wd.damage = wd.damage*(a)/100 ) #define ATK_RATEL(a) ( wd.damage2 = wd.damage2*(a)/100 ) //Adds dmg%. 100 = +100% (double) damage. 10 = +10% damage #define ATK_ADDRATE( a ) do { int64 temp__ = (a); wd.damage+= wd.damage*temp__/100; if(flag.lh) wd.damage2+= wd.damage2*temp__/100; } while(0) #define ATK_ADDRATE2( a , b ) do { wd.damage+= wd.damage*(a)/100 ; if(flag.lh) wd.damage2+= wd.damage2*(b)/100; } while(0) //Adds an absolute value to damage. 100 = +100 damage #define ATK_ADD( a ) do { int64 temp__ = (a); wd.damage += temp__; if (flag.lh) wd.damage2 += temp__; } while(0) #define ATK_ADD2( a , b ) do { wd.damage += (a); if (flag.lh) wd.damage2 += (b); } while(0) #ifdef RENEWAL #define GET_NORMAL_ATTACK( f , s ) ( wd.damage = battle->calc_base_damage(src, target, s, skill_lv, nk, n_ele, s_ele, s_ele_, EQI_HAND_R, (f), wd.flag) ) #define GET_NORMAL_ATTACK2( f , s ) ( wd.damage2 = battle->calc_base_damage(src, target, s, skill_lv, nk, n_ele, s_ele, s_ele_, EQI_HAND_L, (f), wd.flag) ) #endif switch (skill_id) { //Calc base damage according to skill case PA_SACRIFICE: wd.damage = sstatus->max_hp* 9/100; wd.damage2 = 0; #ifdef RENEWAL wd.damage = battle->calc_elefix(src, target, skill_id, skill_lv, wd.damage, nk, n_ele, s_ele, s_ele_, false, wd.flag); // temporary [malufett] #endif break; case NJ_ISSEN: // [malufett] #ifndef RENEWAL wd.damage = 40*sstatus->str +skill_lv*(sstatus->hp/10 + 35); wd.damage2 = 0; #else { short totaldef = status->get_total_def(target); i = 0; GET_NORMAL_ATTACK( (sc && sc->data[SC_MAXIMIZEPOWER]?1:0)|(sc && sc->data[SC_WEAPONPERFECT]?8:0), 0 ); if( sc && sc->data[SC_NJ_BUNSINJYUTSU] && (i=sc->data[SC_NJ_BUNSINJYUTSU]->val2) > 0 ) wd.div_ = ~( i++ + 2 ) + 1; if( wd.damage ){ wd.damage *= sstatus->hp * skill_lv; wd.damage = wd.damage / sstatus->max_hp + sstatus->hp + i * (wd.damage / sstatus->max_hp + sstatus->hp) / 5; } ATK_ADD(-totaldef); if( is_boss(target) ) ATK_RATE(50); } break; case NJ_SYURIKEN: // [malufett] GET_NORMAL_ATTACK( (sc && sc->data[SC_MAXIMIZEPOWER]?1:0)|(sc && sc->data[SC_WEAPONPERFECT]?8:0), 0); ATK_ADD(battle->calc_masteryfix(src, target, skill_id, skill_lv, 4 * skill_lv + (sd ? sd->bonus.arrow_atk : 0), wd.div_, 0, flag.weapon)); #endif break; #ifndef RENEWAL case LK_SPIRALPIERCE: case ML_SPIRALPIERCE: if (sd) { short index = sd->equip_index[EQI_HAND_R]; if (index >= 0 && sd->inventory_data[index] && sd->inventory_data[index]->type == IT_WEAPON) wd.damage = sd->inventory_data[index]->weight*8/100; //80% of weight ATK_ADDRATE(50*skill_lv); //Skill modifier applies to weight only. } else { wd.damage = battle->calc_base_damage2(sstatus, &sstatus->rhw, sc, tstatus->size, sd, 0); //Monsters have no weight and use ATK instead } i = sstatus->str/10; i*=i; ATK_ADD(i); //Add str bonus. switch (tstatus->size) { //Size-fix. Is this modified by weapon perfection? case SZ_SMALL: //Small: 125% ATK_RATE(125); break; //case SZ_MEDIUM: //Medium: 100% case SZ_BIG: //Large: 75% ATK_RATE(75); break; } break; case PA_SHIELDCHAIN: #endif case CR_SHIELDBOOMERANG: wd.damage = sstatus->batk; if (sd) { int damagevalue = 0; short index = sd->equip_index[EQI_HAND_L]; if( index >= 0 && sd->inventory_data[index] && sd->inventory_data[index]->type == IT_ARMOR ) damagevalue = sd->inventory_data[index]->weight/10; ATK_ADD(damagevalue); } else ATK_ADD(sstatus->rhw.atk2); //Else use Atk2 break; case HFLI_SBR44: //[orn] if(src->type == BL_HOM) { wd.damage = ((TBL_HOM*)src)->homunculus.intimacy ; break; } default: { i = (flag.cri #ifdef RENEWAL || (sc && sc->data[SC_MAXIMIZEPOWER]) #endif ?1:0)| (flag.arrow?2:0)| #ifndef RENEWAL (skill_id == HW_MAGICCRASHER?4:0)| (skill_id == MO_EXTREMITYFIST?8:0)| #endif (!skill_id && sc && sc->data[SC_HLIF_CHANGE]?4:0)| (sc && sc->data[SC_WEAPONPERFECT]?8:0); if (flag.arrow && sd) switch(sd->status.weapon) { case W_BOW: case W_REVOLVER: case W_GATLING: case W_SHOTGUN: case W_GRENADE: break; default: i |= 16; // for ex. shuriken must not be influenced by DEX } #ifdef RENEWAL GET_NORMAL_ATTACK( i, skill_id); wd.damage = battle->calc_masteryfix(src, target, skill_id, skill_lv, wd.damage, wd.div_, 0, flag.weapon); wd.damage = battle->calc_cardfix2(src, target, wd.damage, s_ele, nk, wd.flag); if (flag.lh){ GET_NORMAL_ATTACK2( i, skill_id ); wd.damage2 = battle->calc_masteryfix(src, target, skill_id, skill_lv, wd.damage2, wd.div_, 1, flag.weapon); wd.damage2 = battle->calc_cardfix2(src, target, wd.damage2, s_ele, nk, wd.flag); } #else wd.damage = battle->calc_base_damage2(sstatus, &sstatus->rhw, sc, tstatus->size, sd, i); if (flag.lh) wd.damage2 = battle->calc_base_damage2(sstatus, &sstatus->lhw, sc, tstatus->size, sd, i); #endif if (nk&NK_SPLASHSPLIT){ // Divide ATK among targets if(wflag>0) wd.damage/= wflag; else ShowError("0 inimigos alvejados por %d:%s, divisao por 0 evitada!\n", skill_id, skill->get_name(skill_id)); } //Add any bonuses that modify the base baseatk+watk (pre-skills) if(sd) { #ifndef RENEWAL if (sd->bonus.atk_rate) ATK_ADDRATE(sd->bonus.atk_rate); #endif if(flag.cri && sd->bonus.crit_atk_rate) ATK_ADDRATE(sd->bonus.crit_atk_rate); if(flag.cri && sc && sc->data[SC_MTF_CRIDAMAGE]) ATK_ADDRATE(25);// temporary it should be 'bonus.crit_atk_rate' #ifndef RENEWAL if(sd->status.party_id && (temp=pc->checkskill(sd,TK_POWER)) > 0){ if( (i = party->foreachsamemap(party->sub_count, sd, 0)) > 1 ) // exclude the player himself [Inkfish] ATK_ADDRATE(2*temp*i); } #endif } break; } //End default case } //End switch(skill_id) if( sc && skill_id != PA_SACRIFICE && sc->data[SC_UNLIMIT] && (wd.flag&(BF_LONG|BF_MAGIC)) == BF_LONG) { switch(skill_id) { case RA_WUGDASH: case RA_WUGSTRIKE: case RA_WUGBITE: break; default: ATK_ADDRATE( 50 * sc->data[SC_UNLIMIT]->val1 ); } } if ( sc && !skill_id && sc->data[SC_EXEEDBREAK] ) { ATK_ADDRATE(sc->data[SC_EXEEDBREAK]->val1); status_change_end(src, SC_EXEEDBREAK, INVALID_TIMER); } switch(skill_id){ case SR_GATEOFHELL: if (wd.dmg_lv != ATK_FLEE) ATK_RATE(battle->calc_skillratio(BF_WEAPON, src, target, skill_id, skill_lv, skillratio, wflag)); else wd.dmg_lv = ATK_DEF; break; case KO_BAKURETSU: { #ifdef RENEWAL GET_NORMAL_ATTACK((sc && sc->data[SC_MAXIMIZEPOWER] ? 1 : 0) | (sc && sc->data[SC_WEAPONPERFECT] ? 8 : 0), skill_id); #endif skillratio = skill_lv * (50 + status_get_dex(src) / 4); skillratio = (int)(skillratio * (sd ? pc->checkskill(sd, NJ_TOBIDOUGU) : 10) * 40.f / 100.0f * status->get_lv(src) / 120); ATK_RATE(skillratio + 10 * (sd ? sd->status.job_level : 0)); } break; #ifdef RENEWAL case GS_MAGICALBULLET: GET_NORMAL_ATTACK((sc && sc->data[SC_MAXIMIZEPOWER] ? 1 : 0) | (sc && sc->data[SC_WEAPONPERFECT] ? 8 : 0), skill_id); ATK_ADD(battle->attr_fix(src, target, battle->calc_cardfix(BF_MAGIC, src, target, nk, s_ele, 0, status->get_matk(src, 2), 0, wd.flag), ELE_NEUTRAL, tstatus->def_ele, tstatus->ele_lv)); break; case GS_PIERCINGSHOT: GET_NORMAL_ATTACK((sc && sc->data[SC_MAXIMIZEPOWER] ? 1 : 0) | (sc && sc->data[SC_WEAPONPERFECT] ? 8 : 0), 0); if ( wd.damage ) { if ( sd && sd->weapontype1 == W_RIFLE ) ATK_RATE(30 * (skill_lv + 5)); else ATK_RATE(20 * (skill_lv + 5)); } break; case MO_EXTREMITYFIST: // [malufett] { short totaldef = status->get_total_def(target); GET_NORMAL_ATTACK((sc && sc->data[SC_MAXIMIZEPOWER] ? 1 : 0) | 8, skill_id); if ( wd.damage ) { ATK_ADD(250 * (skill_lv + 1) + (10 * (status_get_sp(src) + 1) * wd.damage / 100) + (8 * wd.damage)); ATK_ADD(-totaldef); } } break; case PA_SHIELDCHAIN: GET_NORMAL_ATTACK((sc && sc->data[SC_MAXIMIZEPOWER] ? 1 : 0) | (sc && sc->data[SC_WEAPONPERFECT] ? 8 : 0), skill_id); if ( sd ) { short index = sd->equip_index[EQI_HAND_L]; if ( index >= 0 && sd->inventory_data[index] && sd->inventory_data[index]->type == IT_ARMOR ) { ATK_ADD(sd->inventory_data[index]->weight / 10 + 4 * sd->status.inventory[index].refine); } } else ATK_ADD(sstatus->rhw.atk2); //Else use Atk2 ATK_RATE(battle->calc_skillratio(BF_WEAPON, src, target, skill_id, skill_lv, skillratio, wflag)); break; case AM_DEMONSTRATION: case AM_ACIDTERROR: // [malufett/Hercules] { int64 matk; int totaldef = status->get_total_def(target) + status->get_total_mdef(target); matk = battle->calc_cardfix(BF_MAGIC, src, target, nk, s_ele, 0, status->get_matk(src, 2), 0, wd.flag); matk = battle->attr_fix(src, target, matk, ELE_NEUTRAL, tstatus->def_ele, tstatus->ele_lv); matk = matk * battle->calc_skillratio(BF_WEAPON, src, target, skill_id, skill_lv, skillratio, wflag) / 100; GET_NORMAL_ATTACK((sc && sc->data[SC_MAXIMIZEPOWER] ? 1 : 0) | (sc && sc->data[SC_WEAPONPERFECT] ? 8 : 0), 0); ATK_RATE(battle->calc_skillratio(BF_WEAPON, src, target, skill_id, skill_lv, skillratio, wflag)); ATK_ADD(matk); ATK_ADD(-totaldef); if ( skill_id == AM_ACIDTERROR && is_boss(target) ) ATK_RATE(50); if ( skill_id == AM_DEMONSTRATION ) wd.damage = max(wd.damage, 1); } break; case GN_CARTCANNON: GET_NORMAL_ATTACK((sc && sc->data[SC_MAXIMIZEPOWER] ? 1 : 0) | (sc && sc->data[SC_WEAPONPERFECT] ? 8 : 0), skill_id); ATK_ADD(sd ? sd->bonus.arrow_atk : 0); wd.damage = battle->calc_masteryfix(src, target, skill_id, skill_lv, wd.damage, wd.div_, 0, flag.weapon); ATK_RATE(battle->calc_skillratio(BF_WEAPON, src, target, skill_id, skill_lv, skillratio, wflag)); if ( sd && s_ele != sd->bonus.arrow_ele ) s_ele = sd->bonus.arrow_ele; break; case NJ_TATAMIGAESHI: ATK_RATE(200); /* Fall through */ case LK_SPIRALPIERCE: case ML_SPIRALPIERCE: // [malufett] if( skill_id != NJ_TATAMIGAESHI ){ short index = sd?sd->equip_index[EQI_HAND_R]:0; GET_NORMAL_ATTACK( (sc && sc->data[SC_MAXIMIZEPOWER]?1:0)|(sc && sc->data[SC_WEAPONPERFECT]?8:0), 0); wd.damage = wd.damage * 70 / 100; //n_ele = true; // FIXME: This is has no effect if it's after GET_NORMAL_ATTACK (was this intended, or was it supposed to be put above?) if (sd && index >= 0 && sd->inventory_data[index] && sd->inventory_data[index]->type == IT_WEAPON) ATK_ADD(sd->inventory_data[index]->weight * 7 / 100); switch (tstatus->size) { case SZ_SMALL: //Small: 115% ATK_RATE(115); break; case SZ_BIG: //Large: 85% ATK_RATE(85); } wd.damage = battle->calc_masteryfix(src, target, skill_id, skill_lv, wd.damage, wd.div_, 0, flag.weapon); wd.damage = battle->calc_cardfix2(src, target, wd.damage, s_ele, nk, wd.flag); } /* Fall through */ #endif default: ATK_RATE(battle->calc_skillratio(BF_WEAPON, src, target, skill_id, skill_lv, skillratio, wflag)); } //Constant/misc additions from skills switch (skill_id) { #ifdef RENEWAL case HW_MAGICCRASHER: ATK_ADD(battle->calc_magic_attack(src, target, skill_id, skill_lv, wflag).damage / 5); break; #else case MO_EXTREMITYFIST: ATK_ADD(250 + 150*skill_lv); break; #endif case TK_DOWNKICK: case TK_STORMKICK: case TK_TURNKICK: case TK_COUNTER: case TK_JUMPKICK: //TK_RUN kick damage bonus. if(sd && sd->weapontype1 == W_FIST && sd->weapontype2 == W_FIST) ATK_ADD(10*pc->checkskill(sd, TK_RUN)); break; #ifndef RENEWAL case GS_MAGICALBULLET: ATK_ADD( status->get_matk(src, 2) ); break; case NJ_SYURIKEN: ATK_ADD(4*skill_lv); #endif break; case GC_COUNTERSLASH: ATK_ADD( status_get_agi(src) * 2 + (sd?sd->status.job_level:0) * 4 ); break; case RA_WUGDASH: if( sc && sc->data[SC_DANCE_WITH_WUG] ) ATK_ADD(2 * sc->data[SC_DANCE_WITH_WUG]->val1 * (2 + battle->calc_chorusbonus(sd))); break; case SR_TIGERCANNON: ATK_ADD( skill_lv * 240 + status->get_lv(target) * 40 ); if( sc && sc->data[SC_COMBOATTACK] && sc->data[SC_COMBOATTACK]->val1 == SR_FALLENEMPIRE ) ATK_ADD( skill_lv * 500 + status->get_lv(target) * 40 ); break; case RA_WUGSTRIKE: case RA_WUGBITE: if(sd) ATK_ADD(30*pc->checkskill(sd, RA_TOOTHOFWUG)); if( sc && sc->data[SC_DANCE_WITH_WUG] ) ATK_ADD(2 * sc->data[SC_DANCE_WITH_WUG]->val1 * (2 + battle->calc_chorusbonus(sd))); break; case LG_SHIELDPRESS: if( sd ) { int damagevalue = 0; short index = sd->equip_index[EQI_HAND_L]; if( index >= 0 && sd->inventory_data[index] && sd->inventory_data[index]->type == IT_ARMOR ) damagevalue = sstatus->vit * sd->status.inventory[index].refine; ATK_ADD(damagevalue); } break; case SR_GATEOFHELL: ATK_ADD(sstatus->max_hp - status_get_hp(src)); if ( sc && sc->data[SC_COMBOATTACK] && sc->data[SC_COMBOATTACK]->val1 == SR_FALLENEMPIRE ) { ATK_ADD((sstatus->max_sp * (1 + skill_lv * 2 / 10)) + 40 * status->get_lv(src)); } else { ATK_ADD((sstatus->sp * (1 + skill_lv * 2 / 10)) + 10 * status->get_lv(src)); } break; case SR_FALLENEMPIRE:// [(Target Size value + Skill Level - 1) x Caster STR] + [(Target current weight x Caster DEX / 120)] ATK_ADD( ((tstatus->size+1)*2 + (int64)skill_lv - 1) * sstatus->str); if( tsd && tsd->weight ){ ATK_ADD( (tsd->weight/10) * sstatus->dex / 120 ); }else{ ATK_ADD( status->get_lv(target) * 50 ); //mobs } break; case KO_SETSUDAN: if( tsc && tsc->data[SC_SOULLINK] ){ ATK_ADDRATE(200*tsc->data[SC_SOULLINK]->val1); status_change_end(target,SC_SOULLINK,INVALID_TIMER); } break; case KO_MAKIBISHI: wd.damage = 20 * skill_lv; break; } #ifndef RENEWAL //Div fix. damage_div_fix(wd.damage, wd.div_); #endif //The following are applied on top of current damage and are stackable. if ( sc ) { #ifndef RENEWAL if( sc->data[SC_TRUESIGHT] ) ATK_ADDRATE(2*sc->data[SC_TRUESIGHT]->val1); #endif #ifndef RENEWAL_EDP if( sc->data[SC_EDP] ){ switch(skill_id){ case AS_SPLASHER: // Needs more info case ASC_BREAKER: case ASC_METEORASSAULT: break; default: ATK_ADDRATE(sc->data[SC_EDP]->val3); } } #endif if(sc->data[SC_STYLE_CHANGE]){ TBL_HOM *hd = BL_CAST(BL_HOM,src); if (hd) ATK_ADD(hd->homunculus.spiritball * 3); } } switch (skill_id) { case AS_SONICBLOW: if (sc && sc->data[SC_SOULLINK] && sc->data[SC_SOULLINK]->val2 == SL_ASSASIN) ATK_ADDRATE(map_flag_gvg(src->m)?25:100); //+25% dmg on woe/+100% dmg on nonwoe if(sd && pc->checkskill(sd,AS_SONICACCEL)>0) ATK_ADDRATE(10); break; case CR_SHIELDBOOMERANG: if(sc && sc->data[SC_SOULLINK] && sc->data[SC_SOULLINK]->val2 == SL_CRUSADER) ATK_ADDRATE(100); break; } if( skill_id ){ uint16 rskill;/* redirect skill id */ switch(skill_id){ case AB_DUPLELIGHT_MELEE: rskill = AB_DUPLELIGHT; break; case LG_OVERBRAND_BRANDISH: case LG_OVERBRAND_PLUSATK: rskill = LG_OVERBRAND; break; case WM_SEVERE_RAINSTORM_MELEE: rskill = WM_SEVERE_RAINSTORM; break; case WM_REVERBERATION_MELEE: rskill = WM_REVERBERATION; break; case GN_CRAZYWEED_ATK: rskill = GN_CRAZYWEED; break; case GN_SLINGITEM_RANGEMELEEATK: rskill = GN_SLINGITEM; break; case RL_R_TRIP_PLUSATK: rskill = RL_R_TRIP; break; case RL_B_FLICKER_ATK: rskill = RL_FLICKER; break; case RL_GLITTERING_GREED_ATK: rskill = RL_GLITTERING_GREED; break; default: rskill = skill_id; } if( (i = battle->adjust_skill_damage(src->m,rskill)) ) ATK_RATE(i); } if( sd ) { if (skill_id && (i = pc->skillatk_bonus(sd, skill_id))) ATK_ADDRATE(i); #ifdef RENEWAL if( wd.flag&BF_LONG ) ATK_ADDRATE(sd->bonus.long_attack_atk_rate); if( sc && sc->data[SC_MTF_RANGEATK] ) ATK_ADDRATE(25);// temporary it should be 'bonus.long_attack_atk_rate' #endif if( (i=pc->checkskill(sd,AB_EUCHARISTICA)) > 0 && (tstatus->race == RC_DEMON || tstatus->def_ele == ELE_DARK) ) ATK_ADDRATE(-i); if( skill_id != PA_SACRIFICE && skill_id != MO_INVESTIGATE && skill_id != CR_GRANDCROSS && skill_id != NPC_GRANDDARKNESS && skill_id != PA_SHIELDCHAIN && !flag.cri ) { //Elemental/Racial adjustments if( sd->right_weapon.def_ratio_atk_ele & (1<<tstatus->def_ele) || sd->right_weapon.def_ratio_atk_race & (1<<tstatus->race) || sd->right_weapon.def_ratio_atk_race & (1<<(is_boss(target)?RC_BOSS:RC_NONBOSS)) ) flag.pdef = 1; if( sd->left_weapon.def_ratio_atk_ele & (1<<tstatus->def_ele) || sd->left_weapon.def_ratio_atk_race & (1<<tstatus->race) || sd->left_weapon.def_ratio_atk_race & (1<<(is_boss(target)?RC_BOSS:RC_NONBOSS)) ) { //Pass effect onto right hand if configured so. [Skotlex] if (battle_config.left_cardfix_to_right && flag.rh) flag.pdef = 1; else flag.pdef2 = 1; } } if (skill_id != CR_GRANDCROSS && skill_id != NPC_GRANDDARKNESS) { //Ignore Defense? if (!flag.idef && ( sd->right_weapon.ignore_def_ele & (1<<tstatus->def_ele) || sd->right_weapon.ignore_def_race & (1<<tstatus->race) || sd->right_weapon.ignore_def_race & (is_boss(target)?1<<RC_BOSS:1<<RC_NONBOSS) )) flag.idef = 1; if (!flag.idef2 && ( sd->left_weapon.ignore_def_ele & (1<<tstatus->def_ele) || sd->left_weapon.ignore_def_race & (1<<tstatus->race) || sd->left_weapon.ignore_def_race & (is_boss(target)?1<<RC_BOSS:1<<RC_NONBOSS) )) { if(battle_config.left_cardfix_to_right && flag.rh) //Move effect to right hand. [Skotlex] flag.idef = 1; else flag.idef2 = 1; } } } if((!flag.idef || !flag.idef2) #ifdef RENEWAL && (!flag.distinct || flag.tdef) #endif ) { //Defense reduction wd.damage = battle->calc_defense(BF_WEAPON, src, target, skill_id, skill_lv, wd.damage, (flag.idef?1:0)|(flag.pdef?2:0) #ifdef RENEWAL |(flag.tdef?4:0) #endif , flag.pdef); if( wd.damage2 ) wd.damage2 = battle->calc_defense(BF_WEAPON, src, target, skill_id, skill_lv, wd.damage2, (flag.idef2?1:0)|(flag.pdef2?2:0) #ifdef RENEWAL |(flag.tdef?4:0) #endif , flag.pdef2); } #ifdef RENEWAL if ( flag.distinct ) { wd.damage = battle->calc_cardfix2(src, target, wd.damage, s_ele, nk, wd.flag); if ( flag.lh ) { wd.damage2 = battle->calc_cardfix2(src, target, wd.damage2, s_ele, nk, wd.flag); } } //Div fix. damage_div_fix(wd.damage, wd.div_); if ( skill_id > 0 && (skill->get_ele(skill_id, skill_lv) == ELE_NEUTRAL || flag.distinct) ) { // re-evaluate forced neutral skills wd.damage = battle->attr_fix(src, target, wd.damage, s_ele, tstatus->def_ele, tstatus->ele_lv); if ( flag.lh ) wd.damage2 = battle->attr_fix(src, target, wd.damage2, s_ele_, tstatus->def_ele, tstatus->ele_lv); } #endif #if 0 // Can't find any source about this one even in eagis if (skill_id == NPC_EARTHQUAKE) { //Adds atk2 to the damage, should be influenced by number of hits and skill-ratio, but not mdef reductions. [Skotlex] //Also divide the extra bonuses from atk2 based on the number in range [Kevin] if ( wflag>0 ) ATK_ADD((sstatus->rhw.atk2*skillratio / 100) / wflag); else ShowError("Zero alcance por %d:%s, divisao por 0 evitada!\n", skill_id, skill->get_name(skill_id)); } #endif //Post skill/vit reduction damage increases if (sc) { //SC skill damages if(sc->data[SC_AURABLADE] #ifndef RENEWAL && skill_id != LK_SPIRALPIERCE && skill_id != ML_SPIRALPIERCE #endif ){ int lv = sc->data[SC_AURABLADE]->val1; #ifdef RENEWAL lv *= ((skill_id == LK_SPIRALPIERCE || skill_id == ML_SPIRALPIERCE)?wd.div_:1); // +100 per hit in lv 5 #endif ATK_ADD(20*lv); } if( !skill_id ) { if( sc->data[SC_ENCHANTBLADE] ) { //[( ( Skill Lv x 20 ) + 100 ) x ( casterBaseLevel / 150 )] + casterInt i = ( sc->data[SC_ENCHANTBLADE]->val1 * 20 + 100 ) * status->get_lv(src) / 150 + status_get_int(src); i = i - status->get_total_mdef(target) + status->get_matk(src, 2); if( i ) ATK_ADD(i); } if( sc->data[SC_GIANTGROWTH] && rnd()%100 < 15 ) ATK_ADDRATE(200); // Triple Damage } } #ifndef RENEWAL //Refine bonus if( sd && flag.weapon && skill_id != MO_INVESTIGATE && skill_id != MO_EXTREMITYFIST ) { // Counts refine bonus multiple times if( skill_id == MO_FINGEROFFENSIVE ) { ATK_ADD2(wd.div_*sstatus->rhw.atk2, wd.div_*sstatus->lhw.atk2); } else { ATK_ADD2(sstatus->rhw.atk2, sstatus->lhw.atk2); } } //Set to min of 1 if (flag.rh && wd.damage < 1) wd.damage = 1; if (flag.lh && wd.damage2 < 1) wd.damage2 = 1; #else if (flag.rh && wd.damage < 1) wd.damage = 0; if (flag.lh && wd.damage2 < 1) wd.damage2 = 0; #endif #ifndef RENEWAL wd.damage = battle->calc_masteryfix(src, target, skill_id, skill_lv, wd.damage, wd.div_, 0, flag.weapon); if( flag.lh ) wd.damage2 = battle->calc_masteryfix(src, target, skill_id, skill_lv, wd.damage2, wd.div_, 1, flag.weapon); #else if( sd && flag.cri ) ATK_ADDRATE(40); #endif } //Here ends flag.hit section, the rest of the function applies to both hitting and missing attacks else if(wd.div_ < 0) //Since the attack missed... wd.div_ *= -1; #ifndef RENEWAL if(sd && (temp=pc->checkskill(sd,BS_WEAPONRESEARCH)) > 0) ATK_ADD(temp*2); #endif #ifndef RENEWAL wd.damage = battle->calc_elefix(src, target, skill_id, skill_lv, wd.damage, nk, n_ele, s_ele, s_ele_, false, flag.arrow); if( flag.lh ) wd.damage2 = battle->calc_elefix(src, target, skill_id, skill_lv, wd.damage2, nk, n_ele, s_ele, s_ele_, true, flag.arrow); #endif if(skill_id == CR_GRANDCROSS || skill_id == NPC_GRANDDARKNESS) return wd; //Enough, rest is not needed. #ifndef HMAP_ZONE_DAMAGE_CAP_TYPE if (skill_id) { for(i = 0; i < map->list[target->m].zone->capped_skills_count; i++) { if( skill_id == map->list[target->m].zone->capped_skills[i]->nameid && (map->list[target->m].zone->capped_skills[i]->type & target->type) ) { if( target->type == BL_MOB && map->list[target->m].zone->capped_skills[i]->subtype != MZS_NONE ) { if( (((TBL_MOB*)target)->status.mode&MD_BOSS) && !(map->list[target->m].zone->disabled_skills[i]->subtype&MZS_BOSS) ) continue; if( ((TBL_MOB*)target)->special_state.clone && !(map->list[target->m].zone->disabled_skills[i]->subtype&MZS_CLONE) ) continue; } if( wd.damage > map->list[target->m].zone->capped_skills[i]->cap ) wd.damage = map->list[target->m].zone->capped_skills[i]->cap; if( wd.damage2 > map->list[target->m].zone->capped_skills[i]->cap ) wd.damage2 = map->list[target->m].zone->capped_skills[i]->cap; break; } } } #endif #ifndef RENEWAL // Offensive damage increment in renewal is done somewhere else if (sd) { if (skill_id != CR_SHIELDBOOMERANG) //Only Shield boomerang doesn't takes the Star Crumbs bonus. ATK_ADD2(wd.div_*sd->right_weapon.star, wd.div_*sd->left_weapon.star); if (skill_id==MO_FINGEROFFENSIVE) { //The finger offensive spheres on moment of attack do count. [Skotlex] ATK_ADD(wd.div_*sd->spiritball_old*3); } else { ATK_ADD(wd.div_*sd->spiritball*3); } //Card Fix, sd side wd.damage = battle->calc_cardfix(BF_WEAPON, src, target, nk, s_ele, s_ele_, wd.damage, 2, wd.flag); if( flag.lh ) wd.damage2 = battle->calc_cardfix(BF_WEAPON, src, target, nk, s_ele, s_ele_, wd.damage2, 3, wd.flag); if( skill_id == CR_SHIELDBOOMERANG || skill_id == PA_SHIELDCHAIN ) { //Refine bonus applies after cards and elements. short index= sd->equip_index[EQI_HAND_L]; if( index >= 0 && sd->inventory_data[index] && sd->inventory_data[index]->type == IT_ARMOR ) ATK_ADD(10*sd->status.inventory[index].refine); } } //Card Fix, tsd side if ( tsd ) { //if player on player then it was already measured above wd.damage = battle->calc_cardfix(BF_WEAPON, src, target, nk, s_ele, s_ele_, wd.damage, (flag.lh ? 1 : 0), wd.flag); } #endif if( flag.infdef ) { //Plants receive 1 damage when hit short class_ = status->get_class(target); if( flag.hit || wd.damage > 0 ) wd.damage = wd.div_; // In some cases, right hand no need to have a weapon to increase damage if( flag.lh && (flag.hit || wd.damage2 > 0) ) wd.damage2 = wd.div_; if( flag.hit && class_ == MOBID_EMPERIUM ) { if(wd.damage2 > 0) { wd.damage2 = battle->attr_fix(src,target,wd.damage2,s_ele_,tstatus->def_ele, tstatus->ele_lv); wd.damage2 = battle->calc_gvg_damage(src,target,wd.damage2,wd.div_,skill_id,skill_lv,wd.flag); } else if(wd.damage > 0) { wd.damage = battle->attr_fix(src,target,wd.damage,s_ele_,tstatus->def_ele, tstatus->ele_lv); wd.damage = battle->calc_gvg_damage(src,target,wd.damage,wd.div_,skill_id,skill_lv,wd.flag); } return wd; } if( !(battle_config.skill_min_damage&1) ) //Do not return if you are supposed to deal greater damage to plants than 1. [Skotlex] return wd; } if (sd) { if (!flag.rh && flag.lh) { //Move lh damage to the rh wd.damage = wd.damage2; wd.damage2 = 0; flag.rh=1; flag.lh=0; } else if(flag.rh && flag.lh) { //Dual-wield if (wd.damage) { temp = pc->checkskill(sd,AS_RIGHT) * 10; if( (sd->class_&MAPID_UPPERMASK) == MAPID_KAGEROUOBORO ) temp = pc->checkskill(sd,KO_RIGHT) * 10 + 20; ATK_RATER( 50 + temp ); } if (wd.damage2) { temp = pc->checkskill(sd,AS_LEFT) * 10; if( (sd->class_&MAPID_UPPERMASK) == MAPID_KAGEROUOBORO ) temp = pc->checkskill(sd,KO_LEFT) * 10 + 20; ATK_RATEL( 30 + temp ); } #ifdef RENEWAL if(wd.damage < 0) wd.damage = 0; if(wd.damage2 < 0) wd.damage2 = 0; #else if(wd.damage < 1) wd.damage = 1; if(wd.damage2 < 1) wd.damage2 = 1; #endif } else if(sd->status.weapon == W_KATAR && !skill_id) { //Katars (offhand damage only applies to normal attacks, tested on Aegis 10.2) temp = pc->checkskill(sd,TF_DOUBLE); wd.damage2 = wd.damage * (1 + (temp * 2))/100; if(wd.damage && !wd.damage2) { #ifdef RENEWAL wd.damage2 = 0; #else wd.damage2 = 1; #endif } flag.lh = 1; } } if(!flag.rh && wd.damage) wd.damage=0; if(!flag.lh && wd.damage2) wd.damage2=0; if( sc && sc->data[SC_GLOOMYDAY] ) { switch( skill_id ) { case KN_BRANDISHSPEAR: case LK_SPIRALPIERCE: case CR_SHIELDCHARGE: case CR_SHIELDBOOMERANG: case PA_SHIELDCHAIN: case RK_HUNDREDSPEAR: case LG_SHIELDPRESS: wd.damage += wd.damage * sc->data[SC_GLOOMYDAY]->val2 / 100; } } if( sc ) { //SG_FUSION hp penalty [Komurka] if (sc->data[SC_FUSION]) { int hp= sstatus->max_hp; if (sd && tsd) { hp = 8*hp/100; if ((sstatus->hp * 100) <= (sstatus->max_hp * 20)) hp = sstatus->hp; } else hp = 2*hp/100; //2% hp loss per hit status_zap(src, hp, 0); } status_change_end(src,SC_CAMOUFLAGE, INVALID_TIMER); } switch(skill_id){ case LG_RAYOFGENESIS: { struct Damage md = battle->calc_magic_attack(src, target, skill_id, skill_lv, wflag); wd.damage += md.damage; break; } } if( wd.damage + wd.damage2 ) { //There is a total damage value int64 damage = wd.damage + wd.damage2; if (!wd.damage2) { #ifdef RENEWAL if (skill_id != ASC_BREAKER) #endif wd.damage = battle->calc_damage(src, target, &wd, wd.damage, skill_id, skill_lv); if( map_flag_gvg2(target->m) ) wd.damage=battle->calc_gvg_damage(src,target,wd.damage,wd.div_,skill_id,skill_lv,wd.flag); else if( map->list[target->m].flag.battleground ) wd.damage=battle->calc_bg_damage(src,target,wd.damage,wd.div_,skill_id,skill_lv,wd.flag); } else if (!wd.damage) { #ifdef RENEWAL if (skill_id != ASC_BREAKER) #endif wd.damage2 = battle->calc_damage(src, target, &wd, wd.damage2, skill_id, skill_lv); if (map_flag_gvg2(target->m)) wd.damage2 = battle->calc_gvg_damage(src, target, wd.damage2, wd.div_, skill_id, skill_lv, wd.flag); else if (map->list[target->m].flag.battleground) wd.damage = battle->calc_bg_damage(src, target, wd.damage2, wd.div_, skill_id, skill_lv, wd.flag); } else { #ifdef RENEWAL if( skill_id != ASC_BREAKER ){ wd.damage = battle->calc_damage(src, target, &wd, wd.damage, skill_id, skill_lv); wd.damage2 = battle->calc_damage(src, target, &wd, wd.damage2, skill_id, skill_lv); } #else int64 d1 = wd.damage + wd.damage2,d2 = wd.damage2; wd.damage = battle->calc_damage(src,target,&wd,d1,skill_id,skill_lv); #endif if( map_flag_gvg2(target->m) ) wd.damage = battle->calc_gvg_damage(src,target,wd.damage,wd.div_,skill_id,skill_lv,wd.flag); else if( map->list[target->m].flag.battleground ) wd.damage = battle->calc_bg_damage(src,target,wd.damage,wd.div_,skill_id,skill_lv,wd.flag); #ifndef RENEWAL wd.damage2 = d2*100/d1 * wd.damage/100; if(wd.damage > 1 && wd.damage2 < 1) wd.damage2 = 1; wd.damage-=wd.damage2; #endif } if( src != target ) { // Don't reflect your own damage (Grand Cross) if( wd.dmg_lv == ATK_MISS || wd.dmg_lv == ATK_BLOCK ) { int64 prev1 = wd.damage, prev2 = wd.damage2; wd.damage = damage; wd.damage2 = 0; battle->reflect_damage(target, src, &wd, skill_id); wd.damage = prev1; wd.damage2 = prev2; } else battle->reflect_damage(target, src, &wd, skill_id); } } //Reject Sword bugreport:4493 by Daegaladh if(wd.damage && tsc && tsc->data[SC_SWORDREJECT] && (src->type!=BL_PC || ( ((TBL_PC *)src)->weapontype1 == W_DAGGER || ((TBL_PC *)src)->weapontype1 == W_1HSWORD || ((TBL_PC *)src)->status.weapon == W_2HSWORD )) && rnd()%100 < tsc->data[SC_SWORDREJECT]->val2 ) { ATK_RATER(50); status_fix_damage(target,src,wd.damage,clif->damage(target,src,0,0,wd.damage,0,BDT_NORMAL,0)); clif->skill_nodamage(target,target,ST_REJECTSWORD,tsc->data[SC_SWORDREJECT]->val1,1); if( --(tsc->data[SC_SWORDREJECT]->val3) <= 0 ) status_change_end(target, SC_SWORDREJECT, INVALID_TIMER); } #ifndef RENEWAL if(skill_id == ASC_BREAKER) { //Breaker's int-based damage (a misc attack?) struct Damage md = battle->calc_misc_attack(src, target, skill_id, skill_lv, wflag); wd.damage += md.damage; } #endif return wd; } /*========================================== * Battle main entry, from skill->attack *------------------------------------------*/ struct Damage battle_calc_attack(int attack_type,struct block_list *bl,struct block_list *target,uint16 skill_id,uint16 skill_lv,int count) { struct Damage d; struct map_session_data *sd=BL_CAST(BL_PC,bl); switch(attack_type) { case BF_WEAPON: d = battle->calc_weapon_attack(bl,target,skill_id,skill_lv,count); break; case BF_MAGIC: d = battle->calc_magic_attack(bl,target,skill_id,skill_lv,count); break; case BF_MISC: d = battle->calc_misc_attack(bl,target,skill_id,skill_lv,count); break; default: ShowError("battle_calc_attack: tipo de ataque desconhecido! %d\n",attack_type); memset(&d,0,sizeof(d)); break; } nullpo_retr(d, target); #ifdef HMAP_ZONE_DAMAGE_CAP_TYPE if( target && skill_id ) { int i; for(i = 0; i < map->list[target->m].zone->capped_skills_count; i++) { if( skill_id == map->list[target->m].zone->capped_skills[i]->nameid && (map->list[target->m].zone->capped_skills[i]->type & target->type) ) { if( target->type == BL_MOB && map->list[target->m].zone->capped_skills[i]->subtype != MZS_NONE ) { if( (((TBL_MOB*)target)->status.mode&MD_BOSS) && !(map->list[target->m].zone->disabled_skills[i]->subtype&MZS_BOSS) ) continue; if( ((TBL_MOB*)target)->special_state.clone && !(map->list[target->m].zone->disabled_skills[i]->subtype&MZS_CLONE) ) continue; } if( d.damage > map->list[target->m].zone->capped_skills[i]->cap ) d.damage = map->list[target->m].zone->capped_skills[i]->cap; if( d.damage2 > map->list[target->m].zone->capped_skills[i]->cap ) d.damage2 = map->list[target->m].zone->capped_skills[i]->cap; break; } } } #endif if( d.damage + d.damage2 < 1 ) { //Miss/Absorbed //Weapon attacks should go through to cause additional effects. if (d.dmg_lv == ATK_DEF /*&& attack_type&(BF_MAGIC|BF_MISC)*/) // Isn't it that additional effects don't apply if miss? d.dmg_lv = ATK_MISS; d.dmotion = 0; } else // Some skills like Weaponry Research will cause damage even if attack is dodged d.dmg_lv = ATK_DEF; if(sd && d.damage+d.damage2>1) { if(sd->bonus.sp_vanish_rate && sd->bonus.sp_vanish_trigger && rnd()%10000<sd->bonus.sp_vanish_rate && ( (d.flag&sd->bonus.sp_vanish_trigger&BF_WEAPONMASK) || (d.flag&sd->bonus.sp_vanish_trigger&BF_RANGEMASK) || (d.flag&sd->bonus.sp_vanish_trigger&BF_SKILLMASK) )) status_percent_damage(&sd->bl,target,0,-sd->bonus.sp_vanish_per,false); } return d; } //Performs reflect damage (magic (maya) is performed over skill.c). void battle_reflect_damage(struct block_list *target, struct block_list *src, struct Damage *wd,uint16 skill_id) { int64 damage, rdamage = 0, trdamage = 0; struct map_session_data *sd, *tsd; struct status_change *sc; int64 tick = timer->gettick(); int delay = 50, rdelay = 0; #ifdef RENEWAL int max_reflect_damage; max_reflect_damage = max(status_get_max_hp(target), status_get_max_hp(target) * status->get_lv(target) / 100); #endif damage = wd->damage + wd->damage2; nullpo_retv(wd); sd = BL_CAST(BL_PC, src); tsd = BL_CAST(BL_PC, target); sc = status->get_sc(target); #ifdef RENEWAL #define NORMALIZE_RDAMAGE(d) ( trdamage += rdamage = max(1, min(max_reflect_damage, (d))) ) #else #define NORMALIZE_RDAMAGE(d) ( trdamage += rdamage = max(1, (d)) ) #endif if( sc && !sc->count ) sc = NULL; if( sc ) { if (wd->flag & BF_SHORT && !(skill->get_inf(skill_id) & (INF_GROUND_SKILL | INF_SELF_SKILL))) { if( sc->data[SC_CRESCENTELBOW] && !is_boss(src) && rnd()%100 < sc->data[SC_CRESCENTELBOW]->val2 ){ //ATK [{(Target HP / 100) x Skill Level} x Caster Base Level / 125] % + [Received damage x {1 + (Skill Level x 0.2)}] int ratio = (status_get_hp(src) / 100) * sc->data[SC_CRESCENTELBOW]->val1 * status->get_lv(target) / 125; if (ratio > 5000) ratio = 5000; // Maximum of 5000% ATK rdamage = ratio + (damage)* (10 + sc->data[SC_CRESCENTELBOW]->val1 * 20 / 10) / 10; skill->blown(target, src, skill->get_blewcount(SR_CRESCENTELBOW_AUTOSPELL, sc->data[SC_CRESCENTELBOW]->val1), unit->getdir(src), 0); clif->skill_damage(target, src, tick, status_get_amotion(src), 0, rdamage, 1, SR_CRESCENTELBOW_AUTOSPELL, sc->data[SC_CRESCENTELBOW]->val1, BDT_SKILL); // This is how official does clif->delay_damage(tick + delay, src, target,status_get_amotion(src)+1000,0, rdamage/10, 1, BDT_NORMAL); status->damage(src, target, status->damage(target, src, rdamage, 0, 0, 1)/10, 0, 0, 1); status_change_end(target, SC_CRESCENTELBOW, INVALID_TIMER); /* shouldn't this trigger skill->additional_effect? */ return; // Just put here to minimize redundancy } } if( wd->flag & BF_SHORT ) { if( !is_boss(src) ) { if( sc->data[SC_DEATHBOUND] && skill_id != WS_CARTTERMINATION ) { uint8 dir = map->calc_dir(target,src->x,src->y), t_dir = unit->getdir(target); if( !map->check_dir(dir,t_dir) ) { int64 rd1 = damage * sc->data[SC_DEATHBOUND]->val2 / 100; // Amplify damage. trdamage += rdamage = rd1 - (damage = rd1 * 30 / 100); // not normalized as intended. rdelay = clif->skill_damage(src, target, tick, status_get_amotion(src), status_get_dmotion(src), -3000, 1, RK_DEATHBOUND, sc->data[SC_DEATHBOUND]->val1, BDT_SKILL); skill->blown(target, src, skill->get_blewcount(RK_DEATHBOUND, sc->data[SC_DEATHBOUND]->val1), unit->getdir(src), 0); if( tsd ) /* is this right? rdamage as both left and right? */ battle->drain(tsd, src, rdamage, rdamage, status_get_race(src), 0); battle->delay_damage(tick, wd->amotion,target,src,0,CR_REFLECTSHIELD,0,rdamage,ATK_DEF,rdelay,true); delay += 100;/* gradual increase so the numbers don't clip in the client */ } wd->damage = wd->damage + wd->damage2; wd->damage2 = 0; status_change_end(target,SC_DEATHBOUND,INVALID_TIMER); } } } if( sc->data[SC_KYOMU] ){ // Nullify reflecting ability of the conditions onwards return; } } if( wd->flag & BF_SHORT ) { if ( tsd && tsd->bonus.short_weapon_damage_return ) { NORMALIZE_RDAMAGE(damage * tsd->bonus.short_weapon_damage_return / 100); rdelay = clif->delay_damage(tick+delay,src, src, status_get_amotion(src), status_get_dmotion(src), rdamage, 1, BDT_ENDURE); /* is this right? rdamage as both left and right? */ battle->drain(tsd, src, rdamage, rdamage, status_get_race(src), 0); battle->delay_damage(tick, wd->amotion,target,src,0,CR_REFLECTSHIELD,0,rdamage,ATK_DEF,rdelay,true); delay += 100;/* gradual increase so the numbers don't clip in the client */ } if( wd->dmg_lv >= ATK_BLOCK ) {/* yes block still applies, somehow gravity thinks it makes sense. */ struct status_change *ssc; if( sc ) { struct status_change_entry *sce_d = sc->data[SC_DEVOTION]; struct block_list *d_bl = NULL; if (sce_d && sce_d->val1) d_bl = map->id2bl(sce_d->val1); if( sc->data[SC_REFLECTSHIELD] && skill_id != WS_CARTTERMINATION && skill_id != GS_DESPERADO && !(d_bl && !(wd->flag&BF_SKILL)) // It should not be a basic attack if the target is under devotion && !(d_bl && sce_d && !check_distance_bl(target, d_bl, sce_d->val3)) // It should not be out of range if the target is under devotion ) { NORMALIZE_RDAMAGE(damage * sc->data[SC_REFLECTSHIELD]->val2 / 100); #ifndef RENEWAL rdelay = clif->delay_damage(tick+delay,src, src, status_get_amotion(src), status_get_dmotion(src), rdamage, 1, BDT_ENDURE); #else rdelay = clif->skill_damage(src, src, tick, delay, status_get_dmotion(src), rdamage, 1, CR_REFLECTSHIELD, 1, BDT_ENDURE); #endif /* is this right? rdamage as both left and right? */ if( tsd ) battle->drain(tsd, src, rdamage, rdamage, status_get_race(src), 0); battle->delay_damage(tick, wd->amotion,target,src,0,CR_REFLECTSHIELD,0,rdamage,ATK_DEF,rdelay,true); delay += 100;/* gradual increase so the numbers don't clip in the client */ } if( sc->data[SC_LG_REFLECTDAMAGE] && rnd()%100 < (30 + 10*sc->data[SC_LG_REFLECTDAMAGE]->val1) ) { bool change = false; NORMALIZE_RDAMAGE(damage * sc->data[SC_LG_REFLECTDAMAGE]->val2 / 100); trdamage -= rdamage;/* wont count towards total */ if( sd && !sd->state.autocast ) { change = true; sd->state.autocast = 1; } map->foreachinshootrange(battle->damage_area,target,skill->get_splash(LG_REFLECTDAMAGE,1),BL_CHAR,tick,target,delay,wd->dmotion,rdamage,status_get_race(target)); if( change ) sd->state.autocast = 0; delay += 150;/* gradual increase so the numbers don't clip in the client */ if( (--sc->data[SC_LG_REFLECTDAMAGE]->val3) <= 0 ) status_change_end(target, SC_LG_REFLECTDAMAGE, INVALID_TIMER); } if( sc->data[SC_SHIELDSPELL_DEF] && sc->data[SC_SHIELDSPELL_DEF]->val1 == 2 ){ NORMALIZE_RDAMAGE(damage * sc->data[SC_SHIELDSPELL_DEF]->val2 / 100); rdelay = clif->delay_damage(tick+delay,src, src, status_get_amotion(src), status_get_dmotion(src), rdamage, 1, BDT_ENDURE); /* is this right? rdamage as both left and right? */ if( tsd ) battle->drain(tsd, src, rdamage, rdamage, status_get_race(src), 0); battle->delay_damage(tick, wd->amotion,target,src,0,CR_REFLECTSHIELD,0,rdamage,ATK_DEF,rdelay,true); delay += 100;/* gradual increase so the numbers don't clip in the client */ } } if( ( ssc = status->get_sc(src) ) ) { if( ssc->data[SC_INSPIRATION] ) { NORMALIZE_RDAMAGE(damage / 100); rdelay = clif->delay_damage(tick+delay,target, target, status_get_amotion(target), status_get_dmotion(target), rdamage, 1, BDT_ENDURE); /* is this right? rdamage as both left and right? */ if( sd ) battle->drain(sd, target, rdamage, rdamage, status_get_race(target), 0); battle->delay_damage(tick, wd->amotion,src,target,0,CR_REFLECTSHIELD,0,rdamage,ATK_DEF,rdelay,true); delay += 100;/* gradual increase so the numbers don't clip in the client */ } } } } else {/* long */ if ( tsd && tsd->bonus.long_weapon_damage_return ) { NORMALIZE_RDAMAGE(damage * tsd->bonus.long_weapon_damage_return / 100); rdelay = clif->delay_damage(tick+delay,src, src, status_get_amotion(src), status_get_dmotion(src), rdamage, 1, BDT_ENDURE); /* is this right? rdamage as both left and right? */ battle->drain(tsd, src, rdamage, rdamage, status_get_race(src), 0); battle->delay_damage(tick, wd->amotion,target,src,0,CR_REFLECTSHIELD,0,rdamage,ATK_DEF,rdelay,true); delay += 100;/* gradual increase so the numbers don't clip in the client */ } } // Tell analyzers/compilers that we want to += it even the value is currently unused (it'd be used if we added new checks) (void)delay; /* something caused reflect */ if( trdamage ) { skill->additional_effect(target, src, CR_REFLECTSHIELD, 1, BF_WEAPON|BF_SHORT|BF_NORMAL,ATK_DEF,tick); } return; #undef NORMALIZE_RDAMAGE } void battle_drain(TBL_PC *sd, struct block_list *tbl, int64 rdamage, int64 ldamage, int race, int boss) { struct weapon_data *wd; int type, thp = 0, tsp = 0, rhp = 0, rsp = 0, hp, sp, i; int64 *damage; nullpo_retv(sd); for (i = 0; i < 4; i++) { //First two iterations: Right hand if (i < 2) { wd = &sd->right_weapon; damage = &rdamage; } else { wd = &sd->left_weapon; damage = &ldamage; } if (*damage <= 0) continue; //First and Third iterations: race, other two boss/nonboss state if (i == 0 || i == 2) type = race; else type = boss?RC_BOSS:RC_NONBOSS; hp = wd->hp_drain[type].value; if (wd->hp_drain[type].rate) hp += battle->calc_drain(*damage, wd->hp_drain[type].rate, wd->hp_drain[type].per); sp = wd->sp_drain[type].value; if (wd->sp_drain[type].rate) sp += battle->calc_drain(*damage, wd->sp_drain[type].rate, wd->sp_drain[type].per); if (hp) { if (wd->hp_drain[type].type) rhp += hp; thp += hp; } if (sp) { if (wd->sp_drain[type].type) rsp += sp; tsp += sp; } } if (sd->bonus.sp_vanish_rate && rnd()%1000 < sd->bonus.sp_vanish_rate && !sd->bonus.sp_vanish_trigger) status_percent_damage(&sd->bl, tbl, 0, (unsigned char)sd->bonus.sp_vanish_per, false); if( sd->sp_gain_race_attack[race] ) tsp += sd->sp_gain_race_attack[race]; if( sd->hp_gain_race_attack[race] ) thp += sd->hp_gain_race_attack[race]; if (!thp && !tsp) return; status->heal(&sd->bl, thp, tsp, battle_config.show_hp_sp_drain?3:1); if (rhp || rsp) status_zap(tbl, rhp, rsp); } // Deals the same damage to targets in area. [pakpil] int battle_damage_area(struct block_list *bl, va_list ap) { int64 tick; int amotion, dmotion, damage; struct block_list *src; nullpo_ret(bl); tick = va_arg(ap, int64); src=va_arg(ap,struct block_list *); amotion=va_arg(ap,int); dmotion=va_arg(ap,int); damage=va_arg(ap,int); if( bl->type == BL_MOB && ((TBL_MOB*)bl)->class_ == MOBID_EMPERIUM ) return 0; if( bl != src && battle->check_target(src,bl,BCT_ENEMY) > 0 ) { nullpo_ret(src); map->freeblock_lock(); if( src->type == BL_PC ) battle->drain((TBL_PC*)src, bl, damage, damage, status_get_race(bl), is_boss(bl)); if( amotion ) battle->delay_damage(tick, amotion,src,bl,0,CR_REFLECTSHIELD,0,damage,ATK_DEF,0,true); else status_fix_damage(src,bl,damage,0); clif->damage(bl,bl,amotion,dmotion,damage,1,BDT_ENDURE,0); if( !(src->type == BL_PC && ((TBL_PC*)src)->state.autocast) ) skill->additional_effect(src, bl, CR_REFLECTSHIELD, 1, BF_WEAPON|BF_SHORT|BF_NORMAL,ATK_DEF,tick); map->freeblock_unlock(); } return 0; } /*========================================== * Do a basic physical attack (call trough unit_attack_timer) *------------------------------------------*/ // FIXME: flag is undocumented enum damage_lv battle_weapon_attack(struct block_list* src, struct block_list* target, int64 tick, int flag) { struct map_session_data *sd = NULL, *tsd = NULL; struct status_data *sstatus, *tstatus; struct status_change *sc, *tsc; int64 damage; int skillv; struct Damage wd; nullpo_retr(ATK_NONE, src); nullpo_retr(ATK_NONE, target); if (src->prev == NULL || target->prev == NULL) return ATK_NONE; sd = BL_CAST(BL_PC, src); tsd = BL_CAST(BL_PC, target); sstatus = status->get_status_data(src); tstatus = status->get_status_data(target); sc = status->get_sc(src); tsc = status->get_sc(target); if (sc && !sc->count) //Avoid sc checks when there's none to check for. [Skotlex] sc = NULL; if (tsc && !tsc->count) tsc = NULL; if (sd) { sd->state.arrow_atk = (sd->status.weapon == W_BOW || (sd->status.weapon >= W_REVOLVER && sd->status.weapon <= W_GRENADE)); if (sd->state.arrow_atk) { int index = sd->equip_index[EQI_AMMO]; if (index<0) { if ( sd->weapontype1 > W_KATAR && sd->weapontype1 < W_HUUMA ) clif->skill_fail(sd, 0, USESKILL_FAIL_NEED_MORE_BULLET, 0); else clif->arrow_fail(sd, 0); return ATK_NONE; } //Ammo check by Ishizu-chan if (sd->inventory_data[index]) switch (sd->status.weapon) { case W_BOW: if (sd->inventory_data[index]->look != A_ARROW) { clif->arrow_fail(sd,0); return ATK_NONE; } break; case W_REVOLVER: case W_RIFLE: case W_GATLING: case W_SHOTGUN: if (sd->inventory_data[index]->look != A_BULLET) { clif->skill_fail(sd, 0, USESKILL_FAIL_NEED_MORE_BULLET, 0); return ATK_NONE; } break; case W_GRENADE: if (sd->inventory_data[index]->look != A_GRENADE) { clif->skill_fail(sd, 0, USESKILL_FAIL_NEED_MORE_BULLET, 0); return ATK_NONE; } break; } } } if (sc && sc->count) { if (sc->data[SC_CLOAKING] && !(sc->data[SC_CLOAKING]->val4 & 2)) status_change_end(src, SC_CLOAKING, INVALID_TIMER); else if (sc->data[SC_CLOAKINGEXCEED] && !(sc->data[SC_CLOAKINGEXCEED]->val4 & 2)) status_change_end(src, SC_CLOAKINGEXCEED, INVALID_TIMER); } if( tsc && tsc->data[SC_AUTOCOUNTER] && status->check_skilluse(target, src, KN_AUTOCOUNTER, 1) ) { uint8 dir = map->calc_dir(target,src->x,src->y); int t_dir = unit->getdir(target); int dist = distance_bl(src, target); if(dist <= 0 || (!map->check_dir(dir,t_dir) && dist <= tstatus->rhw.range+1)) { uint16 skill_lv = tsc->data[SC_AUTOCOUNTER]->val1; clif->skillcastcancel(target); //Remove the casting bar. [Skotlex] clif->damage(src, target, sstatus->amotion, 1, 0, 1, BDT_NORMAL, 0); //Display MISS. status_change_end(target, SC_AUTOCOUNTER, INVALID_TIMER); skill->attack(BF_WEAPON,target,target,src,KN_AUTOCOUNTER,skill_lv,tick,0); return ATK_BLOCK; } } if( tsc && tsc->data[SC_BLADESTOP_WAIT] && !is_boss(src) && (src->type == BL_PC || tsd == NULL || distance_bl(src, target) <= (tsd->status.weapon == W_FIST ? 1 : 2)) ) { uint16 skill_lv = tsc->data[SC_BLADESTOP_WAIT]->val1; int duration = skill->get_time2(MO_BLADESTOP,skill_lv); status_change_end(target, SC_BLADESTOP_WAIT, INVALID_TIMER); if(sc_start4(target, src, SC_BLADESTOP, 100, sd?pc->checkskill(sd, MO_BLADESTOP):5, 0, 0, target->id, duration)) { //Target locked. clif->damage(src, target, sstatus->amotion, 1, 0, 1, BDT_NORMAL, 0); //Display MISS. clif->bladestop(target, src->id, 1); sc_start4(target, target, SC_BLADESTOP, 100, skill_lv, 0, 0, src->id, duration); return ATK_BLOCK; } } if(sd && (skillv = pc->checkskill(sd,MO_TRIPLEATTACK)) > 0) { int triple_rate= 30 - skillv; //Base Rate if (sc && sc->data[SC_SKILLRATE_UP] && sc->data[SC_SKILLRATE_UP]->val1 == MO_TRIPLEATTACK) { triple_rate+= triple_rate*(sc->data[SC_SKILLRATE_UP]->val2)/100; status_change_end(src, SC_SKILLRATE_UP, INVALID_TIMER); } if (rnd()%100 < triple_rate) { if( skill->attack(BF_WEAPON,src,src,target,MO_TRIPLEATTACK,skillv,tick,0) ) return ATK_DEF; return ATK_MISS; } } if (sc) { if (sc->data[SC_SACRIFICE]) { uint16 skill_lv = sc->data[SC_SACRIFICE]->val1; damage_lv ret_val; if( --sc->data[SC_SACRIFICE]->val2 <= 0 ) status_change_end(src, SC_SACRIFICE, INVALID_TIMER); /** * We need to calculate the DMG before the hp reduction, because it can kill the source. * For further information: bugreport:4950 **/ ret_val = (damage_lv)skill->attack(BF_WEAPON,src,src,target,PA_SACRIFICE,skill_lv,tick,0); status_zap(src, sstatus->max_hp*9/100, 0);//Damage to self is always 9% if( ret_val == ATK_NONE ) return ATK_MISS; return ret_val; } if (sc->data[SC_MAGICALATTACK]) { if( skill->attack(BF_MAGIC,src,src,target,NPC_MAGICALATTACK,sc->data[SC_MAGICALATTACK]->val1,tick,0) ) return ATK_DEF; return ATK_MISS; } if( tsc && tsc->data[SC_MTF_MLEATKED] && rnd()%100 < 20 ) clif->skill_nodamage(target, target, SM_ENDURE, 5, sc_start(target,target, SC_ENDURE, 100, 5, skill->get_time(SM_ENDURE, 5))); } if(tsc && tsc->data[SC_KAAHI] && tsc->data[SC_KAAHI]->val4 == INVALID_TIMER && tstatus->hp < tstatus->max_hp) tsc->data[SC_KAAHI]->val4 = timer->add(tick + skill->get_time2(SL_KAAHI,tsc->data[SC_KAAHI]->val1), status->kaahi_heal_timer, target->id, SC_KAAHI); //Activate heal. wd = battle->calc_attack(BF_WEAPON, src, target, 0, 0, flag); if( sc && sc->count ) { if( sc->data[SC_SPELLFIST] ) { if( --(sc->data[SC_SPELLFIST]->val1) >= 0 ){ struct Damage ad = battle->calc_attack(BF_MAGIC,src,target,sc->data[SC_SPELLFIST]->val3,sc->data[SC_SPELLFIST]->val4,flag|BF_SHORT); wd.damage = ad.damage; damage_div_fix(wd.damage, wd.div_); }else status_change_end(src,SC_SPELLFIST,INVALID_TIMER); } if( sd && sc->data[SC_FEARBREEZE] && sc->data[SC_FEARBREEZE]->val4 > 0 && sd->status.inventory[sd->equip_index[EQI_AMMO]].amount >= sc->data[SC_FEARBREEZE]->val4 && battle_config.arrow_decrement){ pc->delitem(sd, sd->equip_index[EQI_AMMO], sc->data[SC_FEARBREEZE]->val4, 0, DELITEM_SKILLUSE, LOG_TYPE_CONSUME); sc->data[SC_FEARBREEZE]->val4 = 0; } } if (sd && sd->state.arrow_atk) //Consume arrow. battle->consume_ammo(sd, 0, 0); damage = wd.damage + wd.damage2; if( damage > 0 && src != target ) { if( sc && sc->data[SC_DUPLELIGHT] && (wd.flag&BF_SHORT) && rnd()%100 <= 10+2*sc->data[SC_DUPLELIGHT]->val1 ){ // Activates it only from melee damage uint16 skill_id; if( rnd()%2 == 1 ) skill_id = AB_DUPLELIGHT_MELEE; else skill_id = AB_DUPLELIGHT_MAGIC; skill->attack(skill->get_type(skill_id), src, src, target, skill_id, sc->data[SC_DUPLELIGHT]->val1, tick, SD_LEVEL); } } wd.dmotion = clif->damage(src, target, wd.amotion, wd.dmotion, wd.damage, wd.div_ , wd.type, wd.damage2); if (sd && sd->bonus.splash_range > 0 && damage > 0) skill->castend_damage_id(src, target, 0, 1, tick, 0); if ( target->type == BL_SKILL && damage > 0 ){ TBL_SKILL *su = (TBL_SKILL*)target; if( su->group && su->group->skill_id == HT_BLASTMINE) skill->blown(src, target, 3, -1, 0); } map->freeblock_lock(); if( skill->check_shadowform(target, damage, wd.div_) ){ if( !status->isdead(target) ) skill->additional_effect(src, target, 0, 0, wd.flag, wd.dmg_lv, tick); if( wd.dmg_lv > ATK_BLOCK) skill->counter_additional_effect(src, target, 0, 0, wd.flag,tick); }else battle->delay_damage(tick, wd.amotion, src, target, wd.flag, 0, 0, damage, wd.dmg_lv, wd.dmotion, true); if( tsc ) { if( tsc->data[SC_DEVOTION] ) { struct status_change_entry *sce = tsc->data[SC_DEVOTION]; struct block_list *d_bl = map->id2bl(sce->val1); if( d_bl && ( (d_bl->type == BL_MER && ((TBL_MER*)d_bl)->master && ((TBL_MER*)d_bl)->master->bl.id == target->id) || (d_bl->type == BL_PC && ((TBL_PC*)d_bl)->devotion[sce->val2] == target->id) ) && check_distance_bl(target, d_bl, sce->val3) ) { clif->damage(d_bl, d_bl, 0, 0, damage, 0, BDT_NORMAL, 0); status_fix_damage(NULL, d_bl, damage, 0); } else status_change_end(target, SC_DEVOTION, INVALID_TIMER); } else if( tsc->data[SC_CIRCLE_OF_FIRE_OPTION] && (wd.flag&BF_SHORT) && target->type == BL_PC ) { struct elemental_data *ed = ((TBL_PC*)target)->ed; if( ed ) { clif->skill_damage(&ed->bl, target, tick, status_get_amotion(src), 0, -30000, 1, EL_CIRCLE_OF_FIRE, tsc->data[SC_CIRCLE_OF_FIRE_OPTION]->val1, BDT_SKILL); skill->attack(BF_MAGIC,&ed->bl,&ed->bl,src,EL_CIRCLE_OF_FIRE,tsc->data[SC_CIRCLE_OF_FIRE_OPTION]->val1,tick,wd.flag); } } else if( tsc->data[SC_WATER_SCREEN_OPTION] && tsc->data[SC_WATER_SCREEN_OPTION]->val1 ) { struct block_list *e_bl = map->id2bl(tsc->data[SC_WATER_SCREEN_OPTION]->val1); if( e_bl && !status->isdead(e_bl) ) { clif->damage(e_bl,e_bl,wd.amotion,wd.dmotion,damage,wd.div_,wd.type,wd.damage2); status->damage(target,e_bl,damage,0,0,0); // Just show damage in target. clif->damage(src, target, wd.amotion, wd.dmotion, damage, wd.div_, wd.type, wd.damage2 ); map->freeblock_unlock(); return ATK_NONE; } } } if (sc && sc->data[SC_AUTOSPELL] && rnd()%100 < sc->data[SC_AUTOSPELL]->val4) { int sp = 0; uint16 skill_id = sc->data[SC_AUTOSPELL]->val2; uint16 skill_lv = sc->data[SC_AUTOSPELL]->val3; int i = rnd()%100; if (sc->data[SC_SOULLINK] && sc->data[SC_SOULLINK]->val2 == SL_SAGE) i = 0; //Max chance, no skill_lv reduction. [Skotlex] if (i >= 50) skill_lv -= 2; else if (i >= 15) skill_lv--; if (skill_lv < 1) skill_lv = 1; sp = skill->get_sp(skill_id,skill_lv) * 2 / 3; if (status->charge(src, 0, sp)) { switch (skill->get_casttype(skill_id)) { case CAST_GROUND: skill->castend_pos2(src, target->x, target->y, skill_id, skill_lv, tick, flag); break; case CAST_NODAMAGE: skill->castend_nodamage_id(src, target, skill_id, skill_lv, tick, flag); break; case CAST_DAMAGE: skill->castend_damage_id(src, target, skill_id, skill_lv, tick, flag); break; } } } if (sd) { if( wd.flag&BF_SHORT && sc && sc->data[SC__AUTOSHADOWSPELL] && rnd()%100 < sc->data[SC__AUTOSHADOWSPELL]->val3 && sd->status.skill[skill->get_index(sc->data[SC__AUTOSHADOWSPELL]->val1)].id != 0 && sd->status.skill[skill->get_index(sc->data[SC__AUTOSHADOWSPELL]->val1)].flag == SKILL_FLAG_PLAGIARIZED ) { int r_skill = sd->status.skill[skill->get_index(sc->data[SC__AUTOSHADOWSPELL]->val1)].id; int r_lv = sc->data[SC__AUTOSHADOWSPELL]->val2; if (r_skill != AL_HOLYLIGHT && r_skill != PR_MAGNUS) { int type; if( (type = skill->get_casttype(r_skill)) == CAST_GROUND ) { int maxcount = 0; if( !(BL_PC&battle_config.skill_reiteration) && skill->get_unit_flag(r_skill)&UF_NOREITERATION ) type = -1; if( BL_PC&battle_config.skill_nofootset && skill->get_unit_flag(r_skill)&UF_NOFOOTSET ) type = -1; if( BL_PC&battle_config.land_skill_limit && (maxcount = skill->get_maxcount(r_skill, r_lv)) > 0 ) { int v; for(v=0;v<MAX_SKILLUNITGROUP && sd->ud.skillunit[v] && maxcount;v++) { if(sd->ud.skillunit[v]->skill_id == r_skill) maxcount--; } if( maxcount == 0 ) type = -1; } if( type != CAST_GROUND ) { clif->skill_fail(sd,r_skill,USESKILL_FAIL_LEVEL,0); map->freeblock_unlock(); return wd.dmg_lv; } } sd->state.autocast = 1; skill->consume_requirement(sd,r_skill,r_lv,3); switch( type ) { case CAST_GROUND: skill->castend_pos2(src, target->x, target->y, r_skill, r_lv, tick, flag); break; case CAST_NODAMAGE: skill->castend_nodamage_id(src, target, r_skill, r_lv, tick, flag); break; case CAST_DAMAGE: skill->castend_damage_id(src, target, r_skill, r_lv, tick, flag); break; } sd->state.autocast = 0; sd->ud.canact_tick = tick + skill->delay_fix(src, r_skill, r_lv); clif->status_change(src, SI_POSTDELAY, 1, skill->delay_fix(src, r_skill, r_lv), 0, 0, 1); } } if (wd.flag & BF_WEAPON && src != target && damage > 0) { if (battle_config.left_cardfix_to_right) battle->drain(sd, target, wd.damage, wd.damage, tstatus->race, is_boss(target)); else battle->drain(sd, target, wd.damage, wd.damage2, tstatus->race, is_boss(target)); } } if (tsc) { if (tsc->data[SC_POISONREACT] && ( rnd()%100 < tsc->data[SC_POISONREACT]->val3 || sstatus->def_ele == ELE_POISON ) /* && check_distance_bl(src, target, tstatus->rhw.range+1) Doesn't check range! o.O; */ && status->check_skilluse(target, src, TF_POISON, 0) ) { //Poison React struct status_change_entry *sce = tsc->data[SC_POISONREACT]; if (sstatus->def_ele == ELE_POISON) { sce->val2 = 0; skill->attack(BF_WEAPON,target,target,src,AS_POISONREACT,sce->val1,tick,0); } else { skill->attack(BF_WEAPON,target,target,src,TF_POISON, 5, tick, 0); --sce->val2; } if (sce->val2 <= 0) status_change_end(target, SC_POISONREACT, INVALID_TIMER); } } map->freeblock_unlock(); return wd.dmg_lv; } #undef ATK_RATE #undef ATK_RATE2 #undef ATK_RATER #undef ATK_RATEL #undef ATK_ADDRATE #undef ATK_ADDRATE2 #undef ATK_ADD #undef ATK_ADD2 #undef GET_NORMAL_ATTACK #undef GET_NORMAL_ATTACK2 bool battle_check_undead(int race,int element) { if(battle_config.undead_detect_type == 0) { if(element == ELE_UNDEAD) return true; } else if(battle_config.undead_detect_type == 1) { if(race == RC_UNDEAD) return true; } else { if(element == ELE_UNDEAD || race == RC_UNDEAD) return true; } return false; } //Returns the upmost level master starting with the given object struct block_list* battle_get_master(struct block_list *src) { struct block_list *prev; //Used for infinite loop check (master of yourself?) nullpo_retr(NULL, src); do { prev = src; switch (src->type) { case BL_PET: if (((TBL_PET*)src)->msd) src = (struct block_list*)((TBL_PET*)src)->msd; break; case BL_MOB: if (((TBL_MOB*)src)->master_id) src = map->id2bl(((TBL_MOB*)src)->master_id); break; case BL_HOM: if (((TBL_HOM*)src)->master) src = (struct block_list*)((TBL_HOM*)src)->master; break; case BL_MER: if (((TBL_MER*)src)->master) src = (struct block_list*)((TBL_MER*)src)->master; break; case BL_ELEM: if (((TBL_ELEM*)src)->master) src = (struct block_list*)((TBL_ELEM*)src)->master; break; case BL_SKILL: if (((TBL_SKILL*)src)->group && ((TBL_SKILL*)src)->group->src_id) src = map->id2bl(((TBL_SKILL*)src)->group->src_id); break; } } while (src && src != prev); return prev; } /*========================================== * Checks the state between two targets (rewritten by Skotlex) * (enemy, friend, party, guild, etc) * See battle.h for possible values/combinations * to be used here (BCT_* constants) * Return value is: * 1: flag holds true (is enemy, party, etc) * -1: flag fails * 0: Invalid target (non-targetable ever) *------------------------------------------*/ int battle_check_target( struct block_list *src, struct block_list *target,int flag) { int16 m; //map int state = 0; //Initial state none int strip_enemy = 1; //Flag which marks whether to remove the BCT_ENEMY status if it's also friend/ally. struct block_list *s_bl = src, *t_bl = target; nullpo_ret(src); nullpo_ret(target); m = target->m; if (flag & BCT_ENEMY && (map->getcell(m, src, src->x, src->y, CELL_CHKBASILICA) || map->getcell(m, src, target->x, target->y, CELL_CHKBASILICA))) { return -1; } //t_bl/s_bl hold the 'master' of the attack, while src/target are the actual //objects involved. if( (t_bl = battle->get_master(target)) == NULL ) t_bl = target; if( (s_bl = battle->get_master(src)) == NULL ) s_bl = src; if ( s_bl->type == BL_PC ) { switch( t_bl->type ) { case BL_MOB: // Source => PC, Target => MOB if (pc_has_permission((TBL_PC*)s_bl, PC_PERM_DISABLE_PVM) ) return 0; break; case BL_PC: if (pc_has_permission((TBL_PC*)s_bl, PC_PERM_DISABLE_PVP)) return 0; break; default:/* anything else goes */ break; } } switch( target->type ) { // Checks on actual target case BL_PC: { struct status_change* sc = status->get_sc(src); if( ((TBL_PC*)target)->invincible_timer != INVALID_TIMER ) { switch( battle->get_current_skill(src) ) { /* TODO a proper distinction should be established bugreport:8397 */ case PR_SANCTUARY: case PR_MAGNIFICAT: break; default: return -1; } } if ( pc_isinvisible((TBL_PC*)target) ) return -1; //Cannot be targeted yet. if( sc && sc->count ) { if( sc->data[SC_SIREN] && sc->data[SC_SIREN]->val2 == target->id ) return -1; } } break; case BL_MOB: { TBL_MOB *md = BL_CAST(BL_MOB, target); if(( (md->special_state.ai == AI_SPHERE || (md->special_state.ai == AI_FLORA && battle_config.summon_flora&1)) && s_bl->type == BL_PC && src->type != BL_MOB ) || (md->special_state.ai == AI_ZANZOU && t_bl->id != s_bl->id) ) { //Targetable by players state |= BCT_ENEMY; strip_enemy = 0; } break; } case BL_SKILL: { TBL_SKILL *su = (TBL_SKILL*)target; if( !su->group ) return 0; if( skill->get_inf2(su->group->skill_id)&INF2_TRAP && su->group->unit_id != UNT_USED_TRAPS && su->group->unit_id != UNT_NETHERWORLD ) { //Only a few skills can target traps... switch( battle->get_current_skill(src) ) { case RK_DRAGONBREATH:// it can only hit traps in pvp/gvg maps case RK_DRAGONBREATH_WATER: if( !map->list[m].flag.pvp && !map->list[m].flag.gvg ) break; case 0://you can hit them without skills case MA_REMOVETRAP: case HT_REMOVETRAP: case AC_SHOWER: case MA_SHOWER: case WZ_SIGHTRASHER: case WZ_SIGHTBLASTER: case SM_MAGNUM: case MS_MAGNUM: case RA_DETONATOR: case RA_SENSITIVEKEEN: case RK_STORMBLAST: case SR_RAMPAGEBLASTER: case NC_COLDSLOWER: #ifdef RENEWAL case KN_BOWLINGBASH: case KN_SPEARSTAB: case LK_SPIRALPIERCE: case ML_SPIRALPIERCE: case MO_FINGEROFFENSIVE: case MO_INVESTIGATE: case MO_TRIPLEATTACK: case MO_EXTREMITYFIST: case CR_HOLYCROSS: case ASC_METEORASSAULT: case RG_RAID: case MC_CARTREVOLUTION: case HT_CLAYMORETRAP: case RA_ICEBOUNDTRAP: case RA_FIRINGTRAP: #endif state |= BCT_ENEMY; strip_enemy = 0; break; default: return 0; } } else if (su->group->skill_id==WZ_ICEWALL || su->group->skill_id == GN_WALLOFTHORN) { state |= BCT_ENEMY; strip_enemy = 0; } else { //Excepting traps and icewall, you should not be able to target skills. return 0; } } break; //Valid targets with no special checks here. case BL_MER: case BL_HOM: case BL_ELEM: break; //All else not specified is an invalid target. default: return 0; } //end switch actual target switch( t_bl->type ) { //Checks on target master case BL_PC: { struct map_session_data *sd; if( t_bl == s_bl ) break; sd = BL_CAST(BL_PC, t_bl); if( sd->state.monster_ignore && flag&BCT_ENEMY ) return 0; // Global immunity only to Attacks if( sd->status.karma && s_bl->type == BL_PC && ((TBL_PC*)s_bl)->status.karma ) state |= BCT_ENEMY; // Characters with bad karma may fight amongst them if( sd->state.killable ) { state |= BCT_ENEMY; // Everything can kill it strip_enemy = 0; } break; } case BL_MOB: { struct mob_data *md = BL_CAST(BL_MOB, t_bl); if( !((map->agit_flag || map->agit2_flag) && map->list[m].flag.gvg_castle) && md->guardian_data && (md->guardian_data->g || md->guardian_data->castle->guild_id) ) return 0; // Disable guardians/emperiums owned by Guilds on non-woe times. break; } default: break; //other type doesn't have slave yet } //end switch master target switch( src->type ) { //Checks on actual src type case BL_PET: if (t_bl->type != BL_MOB && flag&BCT_ENEMY) return 0; //Pet may not attack non-mobs. if (t_bl->type == BL_MOB && ((TBL_MOB*)t_bl)->guardian_data && flag&BCT_ENEMY) return 0; //pet may not attack Guardians/Emperium break; case BL_SKILL: { struct skill_unit *su = (struct skill_unit *)src; struct status_change* sc = status->get_sc(target); if (!su->group) return 0; if (su->group->src_id == target->id) { int inf2 = skill->get_inf2(su->group->skill_id); if (inf2&INF2_NO_TARGET_SELF) return -1; if (inf2&INF2_TARGET_SELF) return 1; } //Status changes that prevent traps from triggering if (sc && sc->count && skill->get_inf2(su->group->skill_id)&INF2_TRAP) { if( sc->data[SC_WZ_SIGHTBLASTER] && sc->data[SC_WZ_SIGHTBLASTER]->val2 > 0 && sc->data[SC_WZ_SIGHTBLASTER]->val4%2 == 0) return -1; } } break; case BL_MER: if (t_bl->type == BL_MOB && ((TBL_MOB*)t_bl)->class_ == MOBID_EMPERIUM && flag&BCT_ENEMY) return 0; //mercenary may not attack Emperium break; } //end switch actual src switch( s_bl->type ) { //Checks on source master case BL_PC: { struct map_session_data *sd = BL_CAST(BL_PC, s_bl); if( s_bl != t_bl ) { if( sd->state.killer ) { state |= BCT_ENEMY; // Can kill anything strip_enemy = 0; } else if( sd->duel_group && !((!battle_config.duel_allow_pvp && map->list[m].flag.pvp) || (!battle_config.duel_allow_gvg && map_flag_gvg(m))) ) { if( t_bl->type == BL_PC && (sd->duel_group == ((TBL_PC*)t_bl)->duel_group) ) return (BCT_ENEMY&flag)?1:-1; // Duel targets can ONLY be your enemy, nothing else. else if (src->type != BL_SKILL || (flag&BCT_ALL) != BCT_ALL) return 0; } } if( map_flag_gvg(m) && !sd->status.guild_id && t_bl->type == BL_MOB && ((TBL_MOB*)t_bl)->class_ == MOBID_EMPERIUM ) return 0; //If you don't belong to a guild, can't target emperium. if( t_bl->type != BL_PC ) state |= BCT_ENEMY; //Natural enemy. break; } case BL_MOB: { struct mob_data *md = BL_CAST(BL_MOB, s_bl); if( !((map->agit_flag || map->agit2_flag) && map->list[m].flag.gvg_castle) && md->guardian_data && (md->guardian_data->g || md->guardian_data->castle->guild_id) ) return 0; // Disable guardians/emperium owned by Guilds on non-woe times. if(md->state.killer) state |= BCT_ENEMY; //[SlexFire] else if (md->special_state.ai == AI_NONE) { //Normal mobs struct mob_data *target_md = BL_CAST(BL_MOB, target); if( (target_md && t_bl->type == BL_PC && target_md->special_state.ai != AI_ZANZOU && target_md->special_state.ai != AI_ATTACK) || (t_bl->type == BL_MOB && !((TBL_MOB*)t_bl)->special_state.ai) ) state |= BCT_PARTY; //Normal mobs with no ai are friends. else state |= BCT_ENEMY; //However, all else are enemies. } else { if (t_bl->type == BL_MOB && ((TBL_MOB*)t_bl)->special_state.ai == AI_NONE) state |= BCT_ENEMY; //Natural enemy for AI mobs are normal mobs. } break; } default: //Need some sort of default behavior for unhandled types. if (t_bl->type != s_bl->type) state |= BCT_ENEMY; break; } //end switch on src master if( (flag&BCT_ALL) == BCT_ALL ) { //All actually stands for all attackable chars if( target->type&BL_CHAR ) return 1; else return -1; } if( flag == BCT_NOONE ) //Why would someone use this? no clue. return -1; if( t_bl == s_bl ) { //No need for further testing. state |= BCT_SELF|BCT_PARTY|BCT_GUILD; if( state&BCT_ENEMY && strip_enemy ) state&=~BCT_ENEMY; return (flag&state)?1:-1; } if( map_flag_vs(m) ) { //Check rivalry settings. int sbg_id = 0, tbg_id = 0; if( map->list[m].flag.battleground ) { sbg_id = bg->team_get_id(s_bl); tbg_id = bg->team_get_id(t_bl); } if( flag&(BCT_PARTY|BCT_ENEMY) ) { int s_party = status->get_party_id(s_bl); int s_guild = status->get_guild_id(s_bl); if( s_party && s_party == status->get_party_id(t_bl) && !(map->list[m].flag.pvp && map->list[m].flag.pvp_noparty) && !(map_flag_gvg(m) && map->list[m].flag.gvg_noparty && !( s_guild && s_guild == status->get_guild_id(t_bl) )) && (!map->list[m].flag.battleground || sbg_id == tbg_id) ) state |= BCT_PARTY; else state |= BCT_ENEMY; } if( flag&(BCT_GUILD|BCT_ENEMY) ) { int s_guild = status->get_guild_id(s_bl); int t_guild = status->get_guild_id(t_bl); if( !(map->list[m].flag.pvp && map->list[m].flag.pvp_noguild) && s_guild && t_guild && (s_guild == t_guild || (!(flag&BCT_SAMEGUILD) && guild->isallied(s_guild, t_guild))) && (!map->list[m].flag.battleground || sbg_id == tbg_id) ) state |= BCT_GUILD; else state |= BCT_ENEMY; } if( state&BCT_ENEMY && map->list[m].flag.battleground && sbg_id && sbg_id == tbg_id ) state &= ~BCT_ENEMY; if( state&BCT_ENEMY && battle_config.pk_mode && !map_flag_gvg(m) && s_bl->type == BL_PC && t_bl->type == BL_PC ) { // Prevent novice engagement on pk_mode (feature by Valaris) TBL_PC *sd = (TBL_PC*)s_bl, *sd2 = (TBL_PC*)t_bl; if ( (sd->class_&MAPID_UPPERMASK) == MAPID_NOVICE || (sd2->class_&MAPID_UPPERMASK) == MAPID_NOVICE || (int)sd->status.base_level < battle_config.pk_min_level || (int)sd2->status.base_level < battle_config.pk_min_level || (battle_config.pk_level_range && abs((int)sd->status.base_level - (int)sd2->status.base_level) > battle_config.pk_level_range) ) state &= ~BCT_ENEMY; } }//end map_flag_vs chk rivality else { //Non pvp/gvg, check party/guild settings. if( flag&BCT_PARTY || state&BCT_ENEMY ) { int s_party = status->get_party_id(s_bl); if(s_party && s_party == status->get_party_id(t_bl)) state |= BCT_PARTY; } if( flag&BCT_GUILD || state&BCT_ENEMY ) { int s_guild = status->get_guild_id(s_bl); int t_guild = status->get_guild_id(t_bl); if(s_guild && t_guild && (s_guild == t_guild || (!(flag&BCT_SAMEGUILD) && guild->isallied(s_guild, t_guild)))) state |= BCT_GUILD; } } //end non pvp/gvg chk rivality if( !state ) //If not an enemy, nor a guild, nor party, nor yourself, it's neutral. state = BCT_NEUTRAL; //Alliance state takes precedence over enemy one. else if( state&BCT_ENEMY && strip_enemy && state&(BCT_SELF|BCT_PARTY|BCT_GUILD) ) state&=~BCT_ENEMY; return (flag&state)?1:-1; } /*========================================== * Check if can attack from this range * Basic check then calling path->search for obstacle etc.. *------------------------------------------*/ bool battle_check_range(struct block_list *src, struct block_list *bl, int range) { int d; nullpo_retr(false, src); nullpo_retr(false, bl); if( src->m != bl->m ) return false; #ifndef CIRCULAR_AREA if( src->type == BL_PC ) { // Range for players' attacks and skills should always have a circular check. [Angezerus] if ( !check_distance_client_bl(src, bl, range) ) return false; } else #endif if( !check_distance_bl(src, bl, range) ) return false; if( (d = distance_bl(src, bl)) < 2 ) return true; // No need for path checking. if( d > AREA_SIZE ) return false; // Avoid targeting objects beyond your range of sight. return path->search_long(NULL,src,src->m,src->x,src->y,bl->x,bl->y,CELL_CHKWALL); } static const struct battle_data { const char* str; int* val; int defval; int min; int max; } battle_data[] = { { "warp_point_debug", &battle_config.warp_point_debug, 0, 0, 1, }, { "enable_critical", &battle_config.enable_critical, BL_PC, BL_NUL, BL_ALL, }, { "mob_critical_rate", &battle_config.mob_critical_rate, 100, 0, INT_MAX, }, { "critical_rate", &battle_config.critical_rate, 100, 0, INT_MAX, }, { "enable_baseatk", &battle_config.enable_baseatk, BL_PC|BL_HOM, BL_NUL, BL_ALL, }, { "enable_perfect_flee", &battle_config.enable_perfect_flee, BL_PC|BL_PET, BL_NUL, BL_ALL, }, { "casting_rate", &battle_config.cast_rate, 100, 0, INT_MAX, }, { "delay_rate", &battle_config.delay_rate, 100, 0, INT_MAX, }, { "delay_dependon_dex", &battle_config.delay_dependon_dex, 0, 0, 1, }, { "delay_dependon_agi", &battle_config.delay_dependon_agi, 0, 0, 1, }, { "skill_delay_attack_enable", &battle_config.sdelay_attack_enable, 0, 0, 1, }, { "left_cardfix_to_right", &battle_config.left_cardfix_to_right, 0, 0, 1, }, { "skill_add_range", &battle_config.skill_add_range, 0, 0, INT_MAX, }, { "skill_out_range_consume", &battle_config.skill_out_range_consume, 1, 0, 1, }, { "skillrange_by_distance", &battle_config.skillrange_by_distance, ~BL_PC, BL_NUL, BL_ALL, }, { "skillrange_from_weapon", &battle_config.use_weapon_skill_range, BL_NUL, BL_NUL, BL_ALL, }, { "player_damage_delay_rate", &battle_config.pc_damage_delay_rate, 100, 0, INT_MAX, }, { "defunit_not_enemy", &battle_config.defnotenemy, 0, 0, 1, }, { "gvg_traps_target_all", &battle_config.vs_traps_bctall, BL_PC, BL_NUL, BL_ALL, }, { "traps_setting", &battle_config.traps_setting, 0, 0, 1, }, { "summon_flora_setting", &battle_config.summon_flora, 1|2, 0, 1|2, }, { "clear_skills_on_death", &battle_config.clear_unit_ondeath, BL_NUL, BL_NUL, BL_ALL, }, { "clear_skills_on_warp", &battle_config.clear_unit_onwarp, BL_ALL, BL_NUL, BL_ALL, }, { "random_monster_checklv", &battle_config.random_monster_checklv, 0, 0, 1, }, { "attribute_recover", &battle_config.attr_recover, 1, 0, 1, }, { "flooritem_lifetime", &battle_config.flooritem_lifetime, 60000, 1000, INT_MAX, }, { "item_auto_get", &battle_config.item_auto_get, 0, 0, 1, }, { "item_first_get_time", &battle_config.item_first_get_time, 3000, 0, INT_MAX, }, { "item_second_get_time", &battle_config.item_second_get_time, 1000, 0, INT_MAX, }, { "item_third_get_time", &battle_config.item_third_get_time, 1000, 0, INT_MAX, }, { "mvp_item_first_get_time", &battle_config.mvp_item_first_get_time, 10000, 0, INT_MAX, }, { "mvp_item_second_get_time", &battle_config.mvp_item_second_get_time, 10000, 0, INT_MAX, }, { "mvp_item_third_get_time", &battle_config.mvp_item_third_get_time, 2000, 0, INT_MAX, }, { "drop_rate0item", &battle_config.drop_rate0item, 0, 0, 1, }, { "base_exp_rate", &battle_config.base_exp_rate, 100, 0, INT_MAX, }, { "job_exp_rate", &battle_config.job_exp_rate, 100, 0, INT_MAX, }, { "pvp_exp", &battle_config.pvp_exp, 1, 0, 1, }, { "death_penalty_type", &battle_config.death_penalty_type, 0, 0, 2, }, { "death_penalty_base", &battle_config.death_penalty_base, 0, 0, INT_MAX, }, { "death_penalty_job", &battle_config.death_penalty_job, 0, 0, INT_MAX, }, { "zeny_penalty", &battle_config.zeny_penalty, 0, 0, INT_MAX, }, { "hp_rate", &battle_config.hp_rate, 100, 1, INT_MAX, }, { "sp_rate", &battle_config.sp_rate, 100, 1, INT_MAX, }, { "restart_hp_rate", &battle_config.restart_hp_rate, 0, 0, 100, }, { "restart_sp_rate", &battle_config.restart_sp_rate, 0, 0, 100, }, { "guild_aura", &battle_config.guild_aura, 31, 0, 31, }, { "mvp_hp_rate", &battle_config.mvp_hp_rate, 100, 1, INT_MAX, }, { "mvp_exp_rate", &battle_config.mvp_exp_rate, 100, 0, INT_MAX, }, { "monster_hp_rate", &battle_config.monster_hp_rate, 100, 1, INT_MAX, }, { "monster_max_aspd", &battle_config.monster_max_aspd, 199, 100, 199, }, { "view_range_rate", &battle_config.view_range_rate, 100, 0, INT_MAX, }, { "chase_range_rate", &battle_config.chase_range_rate, 100, 0, INT_MAX, }, { "gtb_sc_immunity", &battle_config.gtb_sc_immunity, 50, 0, INT_MAX, }, { "guild_max_castles", &battle_config.guild_max_castles, 0, 0, INT_MAX, }, { "guild_skill_relog_delay", &battle_config.guild_skill_relog_delay, 0, 0, 1, }, { "emergency_call", &battle_config.emergency_call, 11, 0, 31, }, { "atcommand_spawn_quantity_limit", &battle_config.atc_spawn_quantity_limit, 100, 0, INT_MAX, }, { "atcommand_slave_clone_limit", &battle_config.atc_slave_clone_limit, 25, 0, INT_MAX, }, { "partial_name_scan", &battle_config.partial_name_scan, 0, 0, 1, }, { "player_skillfree", &battle_config.skillfree, 0, 0, 1, }, { "player_skillup_limit", &battle_config.skillup_limit, 1, 0, 1, }, { "weapon_produce_rate", &battle_config.wp_rate, 100, 0, INT_MAX, }, { "potion_produce_rate", &battle_config.pp_rate, 100, 0, INT_MAX, }, { "monster_active_enable", &battle_config.monster_active_enable, 1, 0, 1, }, { "monster_damage_delay_rate", &battle_config.monster_damage_delay_rate, 100, 0, INT_MAX, }, { "monster_loot_type", &battle_config.monster_loot_type, 0, 0, 1, }, //{ "mob_skill_use", &battle_config.mob_skill_use, 1, 0, 1, }, //Deprecated { "mob_skill_rate", &battle_config.mob_skill_rate, 100, 0, INT_MAX, }, { "mob_skill_delay", &battle_config.mob_skill_delay, 100, 0, INT_MAX, }, { "mob_count_rate", &battle_config.mob_count_rate, 100, 0, INT_MAX, }, { "mob_spawn_delay", &battle_config.mob_spawn_delay, 100, 0, INT_MAX, }, { "plant_spawn_delay", &battle_config.plant_spawn_delay, 100, 0, INT_MAX, }, { "boss_spawn_delay", &battle_config.boss_spawn_delay, 100, 0, INT_MAX, }, { "no_spawn_on_player", &battle_config.no_spawn_on_player, 0, 0, 100, }, { "force_random_spawn", &battle_config.force_random_spawn, 0, 0, 1, }, { "slaves_inherit_mode", &battle_config.slaves_inherit_mode, 2, 0, 3, }, { "slaves_inherit_speed", &battle_config.slaves_inherit_speed, 3, 0, 3, }, { "summons_trigger_autospells", &battle_config.summons_trigger_autospells, 1, 0, 1, }, { "pc_damage_walk_delay_rate", &battle_config.pc_walk_delay_rate, 20, 0, INT_MAX, }, { "damage_walk_delay_rate", &battle_config.walk_delay_rate, 100, 0, INT_MAX, }, { "multihit_delay", &battle_config.multihit_delay, 80, 0, INT_MAX, }, { "quest_skill_learn", &battle_config.quest_skill_learn, 0, 0, 1, }, { "quest_skill_reset", &battle_config.quest_skill_reset, 0, 0, 1, }, { "basic_skill_check", &battle_config.basic_skill_check, 1, 0, 1, }, { "guild_emperium_check", &battle_config.guild_emperium_check, 1, 0, 1, }, { "guild_exp_limit", &battle_config.guild_exp_limit, 50, 0, 99, }, { "player_invincible_time", &battle_config.pc_invincible_time, 5000, 0, INT_MAX, }, { "pet_catch_rate", &battle_config.pet_catch_rate, 100, 0, INT_MAX, }, { "pet_rename", &battle_config.pet_rename, 0, 0, 1, }, { "pet_friendly_rate", &battle_config.pet_friendly_rate, 100, 0, INT_MAX, }, { "pet_hungry_delay_rate", &battle_config.pet_hungry_delay_rate, 100, 10, INT_MAX, }, { "pet_hungry_friendly_decrease", &battle_config.pet_hungry_friendly_decrease, 5, 0, INT_MAX, }, { "pet_status_support", &battle_config.pet_status_support, 0, 0, 1, }, { "pet_attack_support", &battle_config.pet_attack_support, 0, 0, 1, }, { "pet_damage_support", &battle_config.pet_damage_support, 0, 0, 1, }, { "pet_support_min_friendly", &battle_config.pet_support_min_friendly, 900, 0, 950, }, { "pet_equip_min_friendly", &battle_config.pet_equip_min_friendly, 900, 0, 950, }, { "pet_support_rate", &battle_config.pet_support_rate, 100, 0, INT_MAX, }, { "pet_attack_exp_to_master", &battle_config.pet_attack_exp_to_master, 0, 0, 1, }, { "pet_attack_exp_rate", &battle_config.pet_attack_exp_rate, 100, 0, INT_MAX, }, { "pet_lv_rate", &battle_config.pet_lv_rate, 0, 0, INT_MAX, }, { "pet_max_stats", &battle_config.pet_max_stats, 99, 0, INT_MAX, }, { "pet_max_atk1", &battle_config.pet_max_atk1, 750, 0, INT_MAX, }, { "pet_max_atk2", &battle_config.pet_max_atk2, 1000, 0, INT_MAX, }, { "pet_disable_in_gvg", &battle_config.pet_no_gvg, 0, 0, 1, }, { "skill_min_damage", &battle_config.skill_min_damage, 2|4, 0, 1|2|4, }, { "finger_offensive_type", &battle_config.finger_offensive_type, 0, 0, 1, }, { "heal_exp", &battle_config.heal_exp, 0, 0, INT_MAX, }, { "resurrection_exp", &battle_config.resurrection_exp, 0, 0, INT_MAX, }, { "shop_exp", &battle_config.shop_exp, 0, 0, INT_MAX, }, { "max_heal_lv", &battle_config.max_heal_lv, 11, 1, INT_MAX, }, { "max_heal", &battle_config.max_heal, 9999, 0, INT_MAX, }, { "combo_delay_rate", &battle_config.combo_delay_rate, 100, 0, INT_MAX, }, { "item_check", &battle_config.item_check, 0, 0, 1, }, { "item_use_interval", &battle_config.item_use_interval, 100, 0, INT_MAX, }, { "cashfood_use_interval", &battle_config.cashfood_use_interval, 60000, 0, INT_MAX, }, { "wedding_modifydisplay", &battle_config.wedding_modifydisplay, 0, 0, 1, }, { "wedding_ignorepalette", &battle_config.wedding_ignorepalette, 0, 0, 1, }, { "xmas_ignorepalette", &battle_config.xmas_ignorepalette, 0, 0, 1, }, { "summer_ignorepalette", &battle_config.summer_ignorepalette, 0, 0, 1, }, { "hanbok_ignorepalette", &battle_config.hanbok_ignorepalette, 0, 0, 1, }, { "natural_healhp_interval", &battle_config.natural_healhp_interval, 6000, NATURAL_HEAL_INTERVAL, INT_MAX, }, { "natural_healsp_interval", &battle_config.natural_healsp_interval, 8000, NATURAL_HEAL_INTERVAL, INT_MAX, }, { "natural_heal_skill_interval", &battle_config.natural_heal_skill_interval, 10000, NATURAL_HEAL_INTERVAL, INT_MAX, }, { "natural_heal_weight_rate", &battle_config.natural_heal_weight_rate, 50, 50, 101 }, { "arrow_decrement", &battle_config.arrow_decrement, 1, 0, 2, }, { "max_aspd", &battle_config.max_aspd, 190, 100, 199, }, { "max_third_aspd", &battle_config.max_third_aspd, 193, 100, 199, }, { "max_walk_speed", &battle_config.max_walk_speed, 300, 100, 100*DEFAULT_WALK_SPEED, }, { "max_lv", &battle_config.max_lv, 99, 0, MAX_LEVEL, }, { "aura_lv", &battle_config.aura_lv, 99, 0, INT_MAX, }, { "max_hp", &battle_config.max_hp, 32500, 100, 1000000000, }, { "max_sp", &battle_config.max_sp, 32500, 100, 1000000000, }, { "max_cart_weight", &battle_config.max_cart_weight, 8000, 100, 1000000, }, { "max_parameter", &battle_config.max_parameter, 99, 10, 10000, }, { "max_baby_parameter", &battle_config.max_baby_parameter, 80, 10, 10000, }, { "max_def", &battle_config.max_def, 99, 0, INT_MAX, }, { "over_def_bonus", &battle_config.over_def_bonus, 0, 0, 1000, }, { "skill_log", &battle_config.skill_log, BL_NUL, BL_NUL, BL_ALL, }, { "battle_log", &battle_config.battle_log, 0, 0, 1, }, { "etc_log", &battle_config.etc_log, 1, 0, 1, }, { "save_clothcolor", &battle_config.save_clothcolor, 1, 0, 1, }, { "undead_detect_type", &battle_config.undead_detect_type, 0, 0, 2, }, { "auto_counter_type", &battle_config.auto_counter_type, BL_ALL, BL_NUL, BL_ALL, }, { "min_hitrate", &battle_config.min_hitrate, 5, 0, 100, }, { "max_hitrate", &battle_config.max_hitrate, 100, 0, 100, }, { "agi_penalty_target", &battle_config.agi_penalty_target, BL_PC, BL_NUL, BL_ALL, }, { "agi_penalty_type", &battle_config.agi_penalty_type, 1, 0, 2, }, { "agi_penalty_count", &battle_config.agi_penalty_count, 3, 2, INT_MAX, }, { "agi_penalty_num", &battle_config.agi_penalty_num, 10, 0, INT_MAX, }, { "vit_penalty_target", &battle_config.vit_penalty_target, BL_PC, BL_NUL, BL_ALL, }, { "vit_penalty_type", &battle_config.vit_penalty_type, 1, 0, 2, }, { "vit_penalty_count", &battle_config.vit_penalty_count, 3, 2, INT_MAX, }, { "vit_penalty_num", &battle_config.vit_penalty_num, 5, 0, INT_MAX, }, { "weapon_defense_type", &battle_config.weapon_defense_type, 0, 0, INT_MAX, }, { "magic_defense_type", &battle_config.magic_defense_type, 0, 0, INT_MAX, }, { "skill_reiteration", &battle_config.skill_reiteration, BL_NUL, BL_NUL, BL_ALL, }, { "skill_nofootset", &battle_config.skill_nofootset, BL_PC, BL_NUL, BL_ALL, }, { "player_cloak_check_type", &battle_config.pc_cloak_check_type, 1, 0, 1|2|4, }, { "monster_cloak_check_type", &battle_config.monster_cloak_check_type, 4, 0, 1|2|4, }, { "sense_type", &battle_config.estimation_type, 1|2, 0, 1|2, }, { "gvg_flee_penalty", &battle_config.gvg_flee_penalty, 20, 0, INT_MAX, }, { "mob_changetarget_byskill", &battle_config.mob_changetarget_byskill, 0, 0, 1, }, { "attack_direction_change", &battle_config.attack_direction_change, BL_ALL, BL_NUL, BL_ALL, }, { "land_skill_limit", &battle_config.land_skill_limit, BL_ALL, BL_NUL, BL_ALL, }, { "monster_class_change_full_recover", &battle_config.monster_class_change_recover, 1, 0, 1, }, { "produce_item_name_input", &battle_config.produce_item_name_input, 0x1|0x2, 0, 0x9F, }, { "display_skill_fail", &battle_config.display_skill_fail, 2, 0, 1|2|4|8, }, { "chat_warpportal", &battle_config.chat_warpportal, 0, 0, 1, }, { "mob_warp", &battle_config.mob_warp, 0, 0, 1|2|4, }, { "dead_branch_active", &battle_config.dead_branch_active, 1, 0, 1, }, { "vending_max_value", &battle_config.vending_max_value, 10000000, 1, MAX_ZENY, }, { "vending_over_max", &battle_config.vending_over_max, 1, 0, 1, }, { "show_steal_in_same_party", &battle_config.show_steal_in_same_party, 0, 0, 1, }, { "party_hp_mode", &battle_config.party_hp_mode, 0, 0, 1, }, { "show_party_share_picker", &battle_config.party_show_share_picker, 1, 0, 1, }, { "show_picker.item_type", &battle_config.show_picker_item_type, 112, 0, INT_MAX, }, { "party_update_interval", &battle_config.party_update_interval, 1000, 100, INT_MAX, }, { "party_item_share_type", &battle_config.party_share_type, 0, 0, 1|2|3, }, { "attack_attr_none", &battle_config.attack_attr_none, ~BL_PC, BL_NUL, BL_ALL, }, { "gx_allhit", &battle_config.gx_allhit, 0, 0, 1, }, { "gx_disptype", &battle_config.gx_disptype, 1, 0, 1, }, { "devotion_level_difference", &battle_config.devotion_level_difference, 10, 0, INT_MAX, }, { "player_skill_partner_check", &battle_config.player_skill_partner_check, 1, 0, 1, }, { "invite_request_check", &battle_config.invite_request_check, 1, 0, 1, }, { "skill_removetrap_type", &battle_config.skill_removetrap_type, 0, 0, 1, }, { "disp_experience", &battle_config.disp_experience, 0, 0, 1, }, { "disp_zeny", &battle_config.disp_zeny, 0, 0, 1, }, { "castle_defense_rate", &battle_config.castle_defense_rate, 100, 0, 100, }, { "bone_drop", &battle_config.bone_drop, 0, 0, 2, }, { "buyer_name", &battle_config.buyer_name, 1, 0, 1, }, { "skill_wall_check", &battle_config.skill_wall_check, 1, 0, 1, }, { "official_cell_stack_limit", &battle_config.official_cell_stack_limit, 1, 0, 255, }, { "custom_cell_stack_limit", &battle_config.custom_cell_stack_limit, 1, 1, 255, }, { "dancing_weaponswitch_fix", &battle_config.dancing_weaponswitch_fix, 1, 0, 1, }, { "check_occupied_cells", &battle_config.check_occupied_cells, 1, 0, 1, }, // eAthena additions { "item_logarithmic_drops", &battle_config.logarithmic_drops, 0, 0, 1, }, { "item_drop_common_min", &battle_config.item_drop_common_min, 1, 1, 10000, }, { "item_drop_common_max", &battle_config.item_drop_common_max, 10000, 1, 10000, }, { "item_drop_equip_min", &battle_config.item_drop_equip_min, 1, 1, 10000, }, { "item_drop_equip_max", &battle_config.item_drop_equip_max, 10000, 1, 10000, }, { "item_drop_card_min", &battle_config.item_drop_card_min, 1, 1, 10000, }, { "item_drop_card_max", &battle_config.item_drop_card_max, 10000, 1, 10000, }, { "item_drop_mvp_min", &battle_config.item_drop_mvp_min, 1, 1, 10000, }, { "item_drop_mvp_max", &battle_config.item_drop_mvp_max, 10000, 1, 10000, }, { "item_drop_heal_min", &battle_config.item_drop_heal_min, 1, 1, 10000, }, { "item_drop_heal_max", &battle_config.item_drop_heal_max, 10000, 1, 10000, }, { "item_drop_use_min", &battle_config.item_drop_use_min, 1, 1, 10000, }, { "item_drop_use_max", &battle_config.item_drop_use_max, 10000, 1, 10000, }, { "item_drop_add_min", &battle_config.item_drop_adddrop_min, 1, 1, 10000, }, { "item_drop_add_max", &battle_config.item_drop_adddrop_max, 10000, 1, 10000, }, { "item_drop_treasure_min", &battle_config.item_drop_treasure_min, 1, 1, 10000, }, { "item_drop_treasure_max", &battle_config.item_drop_treasure_max, 10000, 1, 10000, }, { "item_rate_mvp", &battle_config.item_rate_mvp, 100, 0, 1000000, }, { "item_rate_common", &battle_config.item_rate_common, 100, 0, 1000000, }, { "item_rate_common_boss", &battle_config.item_rate_common_boss, 100, 0, 1000000, }, { "item_rate_equip", &battle_config.item_rate_equip, 100, 0, 1000000, }, { "item_rate_equip_boss", &battle_config.item_rate_equip_boss, 100, 0, 1000000, }, { "item_rate_card", &battle_config.item_rate_card, 100, 0, 1000000, }, { "item_rate_card_boss", &battle_config.item_rate_card_boss, 100, 0, 1000000, }, { "item_rate_heal", &battle_config.item_rate_heal, 100, 0, 1000000, }, { "item_rate_heal_boss", &battle_config.item_rate_heal_boss, 100, 0, 1000000, }, { "item_rate_use", &battle_config.item_rate_use, 100, 0, 1000000, }, { "item_rate_use_boss", &battle_config.item_rate_use_boss, 100, 0, 1000000, }, { "item_rate_adddrop", &battle_config.item_rate_adddrop, 100, 0, 1000000, }, { "item_rate_treasure", &battle_config.item_rate_treasure, 100, 0, 1000000, }, { "prevent_logout", &battle_config.prevent_logout, 10000, 0, 60000, }, { "alchemist_summon_reward", &battle_config.alchemist_summon_reward, 1, 0, 2, }, { "drops_by_luk", &battle_config.drops_by_luk, 0, 0, INT_MAX, }, { "drops_by_luk2", &battle_config.drops_by_luk2, 0, 0, INT_MAX, }, { "equip_natural_break_rate", &battle_config.equip_natural_break_rate, 0, 0, INT_MAX, }, { "equip_self_break_rate", &battle_config.equip_self_break_rate, 100, 0, INT_MAX, }, { "equip_skill_break_rate", &battle_config.equip_skill_break_rate, 100, 0, INT_MAX, }, { "pk_mode", &battle_config.pk_mode, 0, 0, 2, }, { "pk_level_range", &battle_config.pk_level_range, 0, 0, INT_MAX, }, { "manner_system", &battle_config.manner_system, 0xFFF, 0, 0xFFF, }, { "pet_equip_required", &battle_config.pet_equip_required, 0, 0, 1, }, { "multi_level_up", &battle_config.multi_level_up, 0, 0, 1, }, { "max_exp_gain_rate", &battle_config.max_exp_gain_rate, 0, 0, INT_MAX, }, { "backstab_bow_penalty", &battle_config.backstab_bow_penalty, 0, 0, 1, }, { "night_at_start", &battle_config.night_at_start, 0, 0, 1, }, { "show_mob_info", &battle_config.show_mob_info, 0, 0, 1|2|4, }, { "ban_hack_trade", &battle_config.ban_hack_trade, 0, 0, INT_MAX, }, { "min_hair_style", &battle_config.min_hair_style, 0, 0, INT_MAX, }, { "max_hair_style", &battle_config.max_hair_style, 23, 0, INT_MAX, }, { "min_hair_color", &battle_config.min_hair_color, 0, 0, INT_MAX, }, { "max_hair_color", &battle_config.max_hair_color, 9, 0, INT_MAX, }, { "min_cloth_color", &battle_config.min_cloth_color, 0, 0, INT_MAX, }, { "max_cloth_color", &battle_config.max_cloth_color, 4, 0, INT_MAX, }, { "pet_hair_style", &battle_config.pet_hair_style, 100, 0, INT_MAX, }, { "castrate_dex_scale", &battle_config.castrate_dex_scale, 150, 1, INT_MAX, }, { "vcast_stat_scale", &battle_config.vcast_stat_scale, 530, 1, INT_MAX, }, { "area_size", &battle_config.area_size, 14, 0, INT_MAX, }, { "zeny_from_mobs", &battle_config.zeny_from_mobs, 0, 0, 1, }, { "mobs_level_up", &battle_config.mobs_level_up, 0, 0, 1, }, { "mobs_level_up_exp_rate", &battle_config.mobs_level_up_exp_rate, 1, 1, INT_MAX, }, { "pk_min_level", &battle_config.pk_min_level, 55, 1, INT_MAX, }, { "skill_steal_max_tries", &battle_config.skill_steal_max_tries, 0, 0, UCHAR_MAX, }, { "exp_calc_type", &battle_config.exp_calc_type, 0, 0, 1, }, { "exp_bonus_attacker", &battle_config.exp_bonus_attacker, 25, 0, INT_MAX, }, { "exp_bonus_max_attacker", &battle_config.exp_bonus_max_attacker, 12, 2, INT_MAX, }, { "min_skill_delay_limit", &battle_config.min_skill_delay_limit, 100, 10, INT_MAX, }, { "default_walk_delay", &battle_config.default_walk_delay, 300, 0, INT_MAX, }, { "no_skill_delay", &battle_config.no_skill_delay, BL_MOB, BL_NUL, BL_ALL, }, { "attack_walk_delay", &battle_config.attack_walk_delay, BL_ALL, BL_NUL, BL_ALL, }, { "require_glory_guild", &battle_config.require_glory_guild, 0, 0, 1, }, { "idle_no_share", &battle_config.idle_no_share, 0, 0, INT_MAX, }, { "party_even_share_bonus", &battle_config.party_even_share_bonus, 0, 0, INT_MAX, }, { "delay_battle_damage", &battle_config.delay_battle_damage, 1, 0, 1, }, { "hide_woe_damage", &battle_config.hide_woe_damage, 0, 0, 1, }, { "display_version", &battle_config.display_version, 1, 0, 1, }, { "display_hallucination", &battle_config.display_hallucination, 1, 0, 1, }, { "use_statpoint_table", &battle_config.use_statpoint_table, 1, 0, 1, }, { "ignore_items_gender", &battle_config.ignore_items_gender, 1, 0, 1, }, { "copyskill_restrict", &battle_config.copyskill_restrict, 2, 0, 2, }, { "berserk_cancels_buffs", &battle_config.berserk_cancels_buffs, 0, 0, 1, }, { "monster_ai", &battle_config.mob_ai, 0x000, 0x000, 0x77F, }, { "hom_setting", &battle_config.hom_setting, 0xFFFF, 0x0000, 0xFFFF, }, { "dynamic_mobs", &battle_config.dynamic_mobs, 1, 0, 1, }, { "mob_remove_damaged", &battle_config.mob_remove_damaged, 1, 0, 1, }, { "show_hp_sp_drain", &battle_config.show_hp_sp_drain, 0, 0, 1, }, { "show_hp_sp_gain", &battle_config.show_hp_sp_gain, 1, 0, 1, }, { "mob_npc_event_type", &battle_config.mob_npc_event_type, 1, 0, 1, }, { "character_size", &battle_config.character_size, 1|2, 0, 1|2, }, { "retaliate_to_master", &battle_config.retaliate_to_master, 1, 0, 1, }, { "rare_drop_announce", &battle_config.rare_drop_announce, 0, 0, 10000, }, { "duel_allow_pvp", &battle_config.duel_allow_pvp, 0, 0, 1, }, { "duel_allow_gvg", &battle_config.duel_allow_gvg, 0, 0, 1, }, { "duel_allow_teleport", &battle_config.duel_allow_teleport, 0, 0, 1, }, { "duel_autoleave_when_die", &battle_config.duel_autoleave_when_die, 1, 0, 1, }, { "duel_time_interval", &battle_config.duel_time_interval, 60, 0, INT_MAX, }, { "duel_only_on_same_map", &battle_config.duel_only_on_same_map, 0, 0, 1, }, { "skip_teleport_lv1_menu", &battle_config.skip_teleport_lv1_menu, 0, 0, 1, }, { "mob_max_skilllvl", &battle_config.mob_max_skilllvl, 100, 1, INT_MAX, }, { "allow_skill_without_day", &battle_config.allow_skill_without_day, 0, 0, 1, }, { "allow_es_magic_player", &battle_config.allow_es_magic_pc, 0, 0, 1, }, { "skill_caster_check", &battle_config.skill_caster_check, 1, 0, 1, }, { "status_cast_cancel", &battle_config.sc_castcancel, BL_NUL, BL_NUL, BL_ALL, }, { "pc_status_def_rate", &battle_config.pc_sc_def_rate, 100, 0, INT_MAX, }, { "mob_status_def_rate", &battle_config.mob_sc_def_rate, 100, 0, INT_MAX, }, { "pc_max_status_def", &battle_config.pc_max_sc_def, 100, 0, INT_MAX, }, { "mob_max_status_def", &battle_config.mob_max_sc_def, 100, 0, INT_MAX, }, { "sg_miracle_skill_ratio", &battle_config.sg_miracle_skill_ratio, 1, 0, 10000, }, { "sg_angel_skill_ratio", &battle_config.sg_angel_skill_ratio, 10, 0, 10000, }, { "autospell_stacking", &battle_config.autospell_stacking, 0, 0, 1, }, { "override_mob_names", &battle_config.override_mob_names, 0, 0, 2, }, { "min_chat_delay", &battle_config.min_chat_delay, 0, 0, INT_MAX, }, { "friend_auto_add", &battle_config.friend_auto_add, 1, 0, 1, }, { "hom_rename", &battle_config.hom_rename, 0, 0, 1, }, { "homunculus_show_growth", &battle_config.homunculus_show_growth, 0, 0, 1, }, { "homunculus_friendly_rate", &battle_config.homunculus_friendly_rate, 100, 0, INT_MAX, }, { "vending_tax", &battle_config.vending_tax, 0, 0, 10000, }, { "day_duration", &battle_config.day_duration, 0, 0, INT_MAX, }, { "night_duration", &battle_config.night_duration, 0, 0, INT_MAX, }, { "mob_remove_delay", &battle_config.mob_remove_delay, 60000, 1000, INT_MAX, }, { "mob_active_time", &battle_config.mob_active_time, 0, 0, INT_MAX, }, { "boss_active_time", &battle_config.boss_active_time, 0, 0, INT_MAX, }, { "sg_miracle_skill_duration", &battle_config.sg_miracle_skill_duration, 3600000, 0, INT_MAX, }, { "hvan_explosion_intimate", &battle_config.hvan_explosion_intimate, 45000, 0, 100000, }, { "quest_exp_rate", &battle_config.quest_exp_rate, 100, 0, INT_MAX, }, { "at_mapflag", &battle_config.autotrade_mapflag, 0, 0, 1, }, { "at_timeout", &battle_config.at_timeout, 0, 0, INT_MAX, }, { "homunculus_autoloot", &battle_config.homunculus_autoloot, 0, 0, 1, }, { "idle_no_autoloot", &battle_config.idle_no_autoloot, 0, 0, INT_MAX, }, { "max_guild_alliance", &battle_config.max_guild_alliance, 3, 0, 3, }, { "ksprotection", &battle_config.ksprotection, 5000, 0, INT_MAX, }, { "auction_feeperhour", &battle_config.auction_feeperhour, 12000, 0, INT_MAX, }, { "auction_maximumprice", &battle_config.auction_maximumprice, 500000000, 0, MAX_ZENY, }, { "homunculus_auto_vapor", &battle_config.homunculus_auto_vapor, 1, 0, 1, }, { "display_status_timers", &battle_config.display_status_timers, 1, 0, 1, }, { "skill_add_heal_rate", &battle_config.skill_add_heal_rate, 7, 0, INT_MAX, }, { "eq_single_target_reflectable", &battle_config.eq_single_target_reflectable, 1, 0, 1, }, { "invincible.nodamage", &battle_config.invincible_nodamage, 0, 0, 1, }, { "mob_slave_keep_target", &battle_config.mob_slave_keep_target, 0, 0, 1, }, { "autospell_check_range", &battle_config.autospell_check_range, 0, 0, 1, }, { "knockback_left", &battle_config.knockback_left, 1, 0, 1, }, { "client_reshuffle_dice", &battle_config.client_reshuffle_dice, 0, 0, 1, }, { "client_sort_storage", &battle_config.client_sort_storage, 0, 0, 1, }, { "feature.buying_store", &battle_config.feature_buying_store, 1, 0, 1, }, { "feature.search_stores", &battle_config.feature_search_stores, 1, 0, 1, }, { "searchstore_querydelay", &battle_config.searchstore_querydelay, 10, 0, INT_MAX, }, { "searchstore_maxresults", &battle_config.searchstore_maxresults, 30, 1, INT_MAX, }, { "display_party_name", &battle_config.display_party_name, 0, 0, 1, }, { "cashshop_show_points", &battle_config.cashshop_show_points, 0, 0, 1, }, { "mail_show_status", &battle_config.mail_show_status, 0, 0, 2, }, { "client_limit_unit_lv", &battle_config.client_limit_unit_lv, 0, 0, BL_ALL, }, { "client_emblem_max_blank_percent", &battle_config.client_emblem_max_blank_percent, 100, 0, 100, }, // BattleGround Settings { "bg_update_interval", &battle_config.bg_update_interval, 1000, 100, INT_MAX, }, { "bg_flee_penalty", &battle_config.bg_flee_penalty, 20, 0, INT_MAX, }, /** * rAthena **/ { "max_third_parameter", &battle_config.max_third_parameter, 130, 10, 10000, }, { "max_baby_third_parameter", &battle_config.max_baby_third_parameter, 117, 10, 10000, }, { "max_extended_parameter", &battle_config.max_extended_parameter, 125, 10, 10000, }, { "atcommand_max_stat_bypass", &battle_config.atcommand_max_stat_bypass, 0, 0, 100, }, { "skill_amotion_leniency", &battle_config.skill_amotion_leniency, 90, 0, 300 }, { "mvp_tomb_enabled", &battle_config.mvp_tomb_enabled, 1, 0, 1 }, { "feature.atcommand_suggestions", &battle_config.atcommand_suggestions_enabled, 0, 0, 1 }, { "min_npc_vendchat_distance", &battle_config.min_npc_vendchat_distance, 3, 0, 100 }, { "atcommand_mobinfo_type", &battle_config.atcommand_mobinfo_type, 0, 0, 1 }, { "homunculus_max_level", &battle_config.hom_max_level, 99, 0, MAX_LEVEL, }, { "homunculus_S_max_level", &battle_config.hom_S_max_level, 150, 0, MAX_LEVEL, }, { "mob_size_influence", &battle_config.mob_size_influence, 0, 0, 1, }, { "bowling_bash_area", &battle_config.bowling_bash_area, 0, 0, 20, }, /** * Hercules **/ { "skill_trap_type", &battle_config.skill_trap_type, 0, 0, 1, }, { "item_restricted_consumption_type", &battle_config.item_restricted_consumption_type,1, 0, 1, }, { "unequip_restricted_equipment", &battle_config.unequip_restricted_equipment, 0, 0, 3, }, { "max_walk_path", &battle_config.max_walk_path, 17, 1, MAX_WALKPATH, }, { "item_enabled_npc", &battle_config.item_enabled_npc, 1, 0, 1, }, { "gm_ignore_warpable_area", &battle_config.gm_ignore_warpable_area, 0, 2, 100, }, { "packet_obfuscation", &battle_config.packet_obfuscation, 1, 0, 3, }, { "client_accept_chatdori", &battle_config.client_accept_chatdori, 0, 0, INT_MAX, }, { "snovice_call_type", &battle_config.snovice_call_type, 0, 0, 1, }, { "guild_notice_changemap", &battle_config.guild_notice_changemap, 2, 0, 2, }, { "feature.banking", &battle_config.feature_banking, 1, 0, 1, }, { "feature.auction", &battle_config.feature_auction, 0, 0, 2, }, { "idletime_criteria", &battle_config.idletime_criteria, 0x25, 1, INT_MAX, }, { "mon_trans_disable_in_gvg", &battle_config.mon_trans_disable_in_gvg, 0, 0, 1, }, { "case_sensitive_aegisnames", &battle_config.case_sensitive_aegisnames, 1, 0, 1, }, { "guild_castle_invite", &battle_config.guild_castle_invite, 0, 0, 1, }, { "guild_castle_expulsion", &battle_config.guild_castle_expulsion, 0, 0, 1, }, { "song_timer_reset", &battle_config.song_timer_reset, 0, 0, 1, }, { "snap_dodge", &battle_config.snap_dodge, 0, 0, 1, }, { "stormgust_knockback", &battle_config.stormgust_knockback, 1, 0, 1, }, { "monster_chase_refresh", &battle_config.mob_chase_refresh, 1, 0, 30, }, { "mob_icewall_walk_block", &battle_config.mob_icewall_walk_block, 75, 0, 255, }, { "boss_icewall_walk_block", &battle_config.boss_icewall_walk_block, 0, 0, 255, }, { "feature.roulette", &battle_config.feature_roulette, 1, 0, 1, }, { "show_monster_hp_bar", &battle_config.show_monster_hp_bar, 1, 0, 1, }, }; #ifndef STATS_OPT_OUT /** * Hercules anonymous statistic usage report -- packet is built here, and sent to char server to report. **/ void Hercules_report(char* date, char *time_c) { int i, bd_size = ARRAYLENGTH(battle_data); unsigned int config = 0; char timestring[25]; time_t curtime; char* buf; enum config_table { C_CIRCULAR_AREA = 0x0001, C_CELLNOSTACK = 0x0002, C_CONSOLE_INPUT = 0x0004, C_SCRIPT_CALLFUNC_CHECK = 0x0008, C_OFFICIAL_WALKPATH = 0x0010, C_RENEWAL = 0x0020, C_RENEWAL_CAST = 0x0040, C_RENEWAL_DROP = 0x0080, C_RENEWAL_EXP = 0x0100, C_RENEWAL_LVDMG = 0x0200, C_RENEWAL_EDP = 0x0400, C_RENEWAL_ASPD = 0x0800, C_SECURE_NPCTIMEOUT = 0x1000, //C_SQL_DB_ITEM = 0x2000, C_SQL_LOGS = 0x4000, C_MEMWATCH = 0x8000, C_DMALLOC = 0x10000, C_GCOLLECT = 0x20000, C_SEND_SHORTLIST = 0x40000, //C_SQL_DB_MOB = 0x80000, //C_SQL_DB_MOBSKILL = 0x100000, C_PACKETVER_RE = 0x200000, }; /* we get the current time */ time(&curtime); strftime(timestring, 24, "%Y-%m-%d %H:%M:%S", localtime(&curtime)); #ifdef CIRCULAR_AREA config |= C_CIRCULAR_AREA; #endif #ifdef CELL_NOSTACK config |= C_CELLNOSTACK; #endif #ifdef CONSOLE_INPUT config |= C_CONSOLE_INPUT; #endif #ifdef SCRIPT_CALLFUNC_CHECK config |= C_SCRIPT_CALLFUNC_CHECK; #endif #ifdef OFFICIAL_WALKPATH config |= C_OFFICIAL_WALKPATH; #endif #ifdef RENEWAL config |= C_RENEWAL; #endif #ifdef RENEWAL_CAST config |= C_RENEWAL_CAST; #endif #ifdef RENEWAL_DROP config |= C_RENEWAL_DROP; #endif #ifdef RENEWAL_EXP config |= C_RENEWAL_EXP; #endif #ifdef RENEWAL_LVDMG config |= C_RENEWAL_LVDMG; #endif #ifdef RENEWAL_EDP config |= C_RENEWAL_EDP; #endif #ifdef RENEWAL_ASPD config |= C_RENEWAL_ASPD; #endif #ifdef SECURE_NPCTIMEOUT config |= C_SECURE_NPCTIMEOUT; #endif #ifdef PACKETVER_RE config |= C_PACKETVER_RE; #endif /* non-define part */ if( logs->config.sql_logs ) config |= C_SQL_LOGS; #ifdef MEMWATCH config |= C_MEMWATCH; #endif #ifdef DMALLOC config |= C_DMALLOC; #endif #ifdef GCOLLECT config |= C_GCOLLECT; #endif #ifdef SEND_SHORTLIST config |= C_SEND_SHORTLIST; #endif #define BFLAG_LENGTH 35 CREATE(buf, char, 262 + ( bd_size * ( BFLAG_LENGTH + 4 ) ) + 1 ); /* build packet */ WBUFW(buf,0) = 0x3000; WBUFW(buf,2) = 262 + ( bd_size * ( BFLAG_LENGTH + 4 ) ); WBUFW(buf,4) = 0x9f; safestrncpy((char*)WBUFP(buf,6), date, 12); safestrncpy((char*)WBUFP(buf,18), time_c, 9); safestrncpy((char*)WBUFP(buf,27), timestring, 24); safestrncpy((char*)WBUFP(buf,51), sysinfo->platform(), 16); safestrncpy((char*)WBUFP(buf,67), sysinfo->osversion(), 50); safestrncpy((char*)WBUFP(buf,117), sysinfo->cpu(), 32); WBUFL(buf,149) = sysinfo->cpucores(); safestrncpy((char*)WBUFP(buf,153), sysinfo->arch(), 8); WBUFB(buf,161) = sysinfo->vcstypeid(); WBUFB(buf,162) = sysinfo->is64bit(); safestrncpy((char*)WBUFP(buf,163), sysinfo->vcsrevision_src(), 41); safestrncpy((char*)WBUFP(buf,204), sysinfo->vcsrevision_scripts(), 41); WBUFB(buf,245) = (sysinfo->is_superuser()? 1 : 0); WBUFL(buf,246) = map->getusers(); WBUFL(buf,250) = config; WBUFL(buf,254) = PACKETVER; WBUFL(buf,258) = bd_size; for( i = 0; i < bd_size; i++ ) { safestrncpy((char*)WBUFP(buf,262 + ( i * ( BFLAG_LENGTH + 4 ) ) ), battle_data[i].str, BFLAG_LENGTH); WBUFL(buf,262 + BFLAG_LENGTH + ( i * ( BFLAG_LENGTH + 4 ) ) ) = *battle_data[i].val; } chrif->send_report(buf, 262 + ( bd_size * ( BFLAG_LENGTH + 4 ) ) ); aFree(buf); #undef BFLAG_LENGTH } static int Hercules_report_timer(int tid, int64 tick, int id, intptr_t data) { if( chrif->isconnected() ) {/* char server relays it, so it must be online. */ Hercules_report(__DATE__,__TIME__); } return 0; } #endif int battle_set_value(const char* w1, const char* w2) { int val = config_switch(w2); int i; nullpo_retr(1, w1); nullpo_retr(1, w2); ARR_FIND(0, ARRAYLENGTH(battle_data), i, strcmpi(w1, battle_data[i].str) == 0); if (i == ARRAYLENGTH(battle_data)) { if( HPM->parseConf(w1,w2,HPCT_BATTLE) ) /* if plugin-owned, succeed */ return 1; return 0; // not found } if (val < battle_data[i].min || val > battle_data[i].max) { ShowWarning("Valor para ajuste '%s': %s e invalido (min:%i max:%i)! Padronizando para %i...\n", w1, w2, battle_data[i].min, battle_data[i].max, battle_data[i].defval); val = battle_data[i].defval; } *battle_data[i].val = val; return 1; } bool battle_get_value(const char *w1, int *value) { int i; nullpo_retr(false, w1); nullpo_retr(false, value); ARR_FIND(0, ARRAYLENGTH(battle_data), i, strcmpi(w1, battle_data[i].str) == 0); if (i == ARRAYLENGTH(battle_data)) { if (HPM->getBattleConf(w1,value)) return true; } else { *value = *battle_data[i].val; return true; } return false; } void battle_set_defaults(void) { int i; for (i = 0; i < ARRAYLENGTH(battle_data); i++) *battle_data[i].val = battle_data[i].defval; } void battle_adjust_conf(void) { battle_config.monster_max_aspd = 2000 - battle_config.monster_max_aspd*10; battle_config.max_aspd = 2000 - battle_config.max_aspd*10; battle_config.max_third_aspd = 2000 - battle_config.max_third_aspd*10; battle_config.max_walk_speed = 100*DEFAULT_WALK_SPEED/battle_config.max_walk_speed; battle_config.max_cart_weight *= 10; if(battle_config.max_def > 100 && !battle_config.weapon_defense_type) // added by [Skotlex] battle_config.max_def = 100; if(battle_config.min_hitrate > battle_config.max_hitrate) battle_config.min_hitrate = battle_config.max_hitrate; if(battle_config.pet_max_atk1 > battle_config.pet_max_atk2) //Skotlex battle_config.pet_max_atk1 = battle_config.pet_max_atk2; if (battle_config.day_duration && battle_config.day_duration < 60000) // added by [Yor] battle_config.day_duration = 60000; if (battle_config.night_duration && battle_config.night_duration < 60000) // added by [Yor] battle_config.night_duration = 60000; #if PACKETVER < 20100427 if( battle_config.feature_buying_store ) { ShowWarning("conf/battle/feature.conf buying_store esta ativado mas e necessario PACKETVER 2010-04-27 ou superior, desabilitando...\n"); battle_config.feature_buying_store = 0; } #endif #if PACKETVER < 20100803 if( battle_config.feature_search_stores ) { ShowWarning("conf/battle/feature.conf search_stores esta ativado mas e necessario PACKETVER 2010-08-03 ou superior, desabilitando...\n"); battle_config.feature_search_stores = 0; } #endif #if PACKETVER < 20130724 if( battle_config.feature_banking ) { ShowWarning("conf/battle/feature.conf banking esta ativado mas e necessario PACKETVER 2013-07-24 ou superior, desabilitando...\n"); battle_config.feature_banking = 0; } #endif #if PACKETVER < 20141022 if( battle_config.feature_roulette ) { ShowWarning("conf/battle/feature.conf roulette esta ativado mas e necessario PACKETVER 2014-10-22 ou superior, desabilitando...\n"); battle_config.feature_roulette = 0; } #endif #if PACKETVER > 20120000 && PACKETVER < 20130515 /* exact date (when it started) not known */ if( battle_config.feature_auction == 1 ) { ShowWarning("conf/battle/feature.conf:feature.auction esta ativado mas nao e estavel no PACKETVER "EXPAND_AND_QUOTE(PACKETVER)", desabilitando...\n"); ShowWarning("conf/battle/feature.conf:feature.auction mudar o valor para '2' para silenciar esse aviso e mante-lo desabilitado\n"); battle_config.feature_auction = 0; } #endif #ifndef CELL_NOSTACK if (battle_config.custom_cell_stack_limit != 1) ShowWarning("Configuracao de batalha 'custom_cell_stack_limit' nao tem efeito porque o servidor foi compilado sem suporte para o Cell Stack Limit.\n"); #endif } int battle_config_read(const char* cfgName) { FILE* fp; static int count = 0; nullpo_ret(cfgName); if (count == 0) battle->config_set_defaults(); count++; fp = fopen(cfgName,"r"); if (fp == NULL) ShowError("Arquivo nao encontrado: %s\n", cfgName); else { char line[1024], w1[1024], w2[1024]; while(fgets(line, sizeof(line), fp)) { if (line[0] == '/' && line[1] == '/') continue; if (sscanf(line, "%1023[^:]:%1023s", w1, w2) != 2) continue; if (strcmpi(w1, "import") == 0) battle->config_read(w2); else if (battle->config_set_value(w1, w2) == 0) ShowWarning("Configuracao desconhecida '%s' no arquivo %s\n", w1, cfgName); } fclose(fp); } count--; if (count == 0) { battle->config_adjust(); clif->bc_ready(); } return 0; } void do_init_battle(bool minimal) { if (minimal) return; battle->delay_damage_ers = ers_new(sizeof(struct delay_damage),"battle.c::delay_damage_ers",ERS_OPT_CLEAR); timer->add_func_list(battle->delay_damage_sub, "battle_delay_damage_sub"); #ifndef STATS_OPT_OUT timer->add_func_list(Hercules_report_timer, "Hercules_report_timer"); timer->add_interval(timer->gettick()+30000, Hercules_report_timer, 0, 0, 60000 * 30); #endif } void do_final_battle(void) { ers_destroy(battle->delay_damage_ers); } /* initialize the interface */ void battle_defaults(void) { battle = &battle_s; battle->bc = &battle_config; memset(battle->attr_fix_table, 0, sizeof(battle->attr_fix_table)); battle->delay_damage_ers = NULL; battle->init = do_init_battle; battle->final = do_final_battle; battle->calc_attack = battle_calc_attack; battle->calc_damage = battle_calc_damage; battle->calc_gvg_damage = battle_calc_gvg_damage; battle->calc_bg_damage = battle_calc_bg_damage; battle->weapon_attack = battle_weapon_attack; battle->calc_weapon_attack = battle_calc_weapon_attack; battle->delay_damage = battle_delay_damage; battle->drain = battle_drain; battle->reflect_damage = battle_reflect_damage; battle->attr_ratio = battle_attr_ratio; battle->attr_fix = battle_attr_fix; battle->calc_cardfix = battle_calc_cardfix; battle->calc_cardfix2 = battle_calc_cardfix2; battle->calc_elefix = battle_calc_elefix; battle->calc_masteryfix = battle_calc_masteryfix; battle->calc_chorusbonus = battle_calc_chorusbonus; battle->calc_skillratio = battle_calc_skillratio; battle->calc_sizefix = battle_calc_sizefix; battle->calc_weapon_damage = battle_calc_weapon_damage; battle->calc_defense = battle_calc_defense; battle->get_master = battle_get_master; battle->get_targeted = battle_gettargeted; battle->get_enemy = battle_getenemy; battle->get_target = battle_gettarget; battle->get_current_skill = battle_getcurrentskill; battle->check_undead = battle_check_undead; battle->check_target = battle_check_target; battle->check_range = battle_check_range; battle->consume_ammo = battle_consume_ammo; battle->get_targeted_sub = battle_gettargeted_sub; battle->get_enemy_sub = battle_getenemy_sub; battle->get_enemy_area_sub = battle_getenemyarea_sub; battle->delay_damage_sub = battle_delay_damage_sub; battle->blewcount_bonus = battle_blewcount_bonus; battle->range_type = battle_range_type; battle->calc_base_damage = battle_calc_base_damage; battle->calc_base_damage2 = battle_calc_base_damage2; battle->calc_misc_attack = battle_calc_misc_attack; battle->calc_magic_attack = battle_calc_magic_attack; battle->adjust_skill_damage = battle_adjust_skill_damage; battle->add_mastery = battle_addmastery; battle->calc_drain = battle_calc_drain; battle->config_read = battle_config_read; battle->config_set_defaults = battle_set_defaults; battle->config_set_value = battle_set_value; battle->config_get_value = battle_get_value; battle->config_adjust = battle_adjust_conf; battle->get_enemy_area = battle_getenemyarea; battle->damage_area = battle_damage_area; battle->calc_masteryfix_unknown = battle_calc_masteryfix_unknown; battle->calc_skillratio_magic_unknown = battle_calc_skillratio_magic_unknown; battle->calc_skillratio_weapon_unknown = battle_calc_skillratio_weapon_unknown; battle->calc_misc_attack_unknown = battle_calc_misc_attack_unknown; }
0
0.98766
1
0.98766
game-dev
MEDIA
0.729478
game-dev
0.98812
1
0.98812
KettleFoundation/Kettle
1,105
patches/net/minecraft/item/ItemDye.java.patch
--- ../src-base/minecraft/net/minecraft/item/ItemDye.java +++ ../src-work/minecraft/net/minecraft/item/ItemDye.java @@ -20,6 +20,7 @@ import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; +import org.bukkit.event.entity.SheepDyeWoolEvent; public class ItemDye extends Item { @@ -175,6 +176,15 @@ if (!entitysheep.getSheared() && entitysheep.getFleeceColor() != enumdyecolor) { + byte bColor = (byte) enumdyecolor.getMetadata(); + SheepDyeWoolEvent event = new SheepDyeWoolEvent((org.bukkit.entity.Sheep) entitysheep.getBukkitEntity(), org.bukkit.DyeColor.getByWoolData(bColor)); + entitysheep.world.getServer().getPluginManager().callEvent(event); + + if (event.isCancelled()) { + return false; + } + + enumdyecolor = EnumDyeColor.byMetadata(event.getColor().getWoolData()); entitysheep.setFleeceColor(enumdyecolor); stack.shrink(1); }
0
0.672757
1
0.672757
game-dev
MEDIA
0.990878
game-dev
0.761055
1
0.761055
wadackel/rs-monkey-lang
1,041
src/evaluator/env.rs
use evaluator::object::*; use std::cell::RefCell; use std::collections::HashMap; use std::rc::Rc; #[derive(PartialEq, Clone, Debug)] pub struct Env { store: HashMap<String, Object>, outer: Option<Rc<RefCell<Env>>>, } impl Env { pub fn new() -> Self { Env { store: HashMap::new(), outer: None, } } pub fn from(store: HashMap<String, Object>) -> Self { Env { store, outer: None } } pub fn new_with_outer(outer: Rc<RefCell<Env>>) -> Self { Env { store: HashMap::new(), outer: Some(outer), } } pub fn get(&mut self, name: String) -> Option<Object> { match self.store.get(&name) { Some(value) => Some(value.clone()), None => match self.outer { Some(ref outer) => outer.borrow_mut().get(name), None => None, }, } } pub fn set(&mut self, name: String, value: &Object) { self.store.insert(name, value.clone()); } }
0
0.665152
1
0.665152
game-dev
MEDIA
0.266863
game-dev
0.862271
1
0.862271
fortressforever/fortressforever
8,119
cl_dll/hl2_hud/c_vehicle_prisoner_pod.cpp
//========= Copyright 1996-2005, Valve Corporation, All rights reserved. ============// // // Purpose: // //=============================================================================// #include "cbase.h" #include "hud.h" #include "c_physicsprop.h" #include "IClientVehicle.h" #include <vgui_controls/Controls.h> #include <Color.h> // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" extern float RemapAngleRange( float startInterval, float endInterval, float value ); #define ROLL_CURVE_ZERO 5 // roll less than this is clamped to zero #define ROLL_CURVE_LINEAR 45 // roll greater than this is copied out #define PITCH_CURVE_ZERO 10 // pitch less than this is clamped to zero #define PITCH_CURVE_LINEAR 45 // pitch greater than this is copied out // spline in between #define POD_VIEW_FOV 90 #define POD_VIEW_YAW_MIN -60 #define POD_VIEW_YAW_MAX 60 #define POD_VIEW_PITCH_MIN -90 #define POD_VIEW_PITCH_MAX 38 // Don't let players look down and see that the pod is empty //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- class C_PropVehiclePrisonerPod : public C_PhysicsProp, public IClientVehicle { DECLARE_CLASS( C_PropVehiclePrisonerPod, C_PhysicsProp ); public: DECLARE_CLIENTCLASS(); DECLARE_DATADESC(); C_PropVehiclePrisonerPod(); void PreDataUpdate( DataUpdateType_t updateType ); void PostDataUpdate( DataUpdateType_t updateType ); public: // IClientVehicle overrides. virtual void GetVehicleViewPosition( int nRole, Vector *pOrigin, QAngle *pAngles ); virtual void GetVehicleFOV( float &flFOV ) { flFOV = m_flFOV; } virtual void DrawHudElements(); virtual bool IsPassengerUsingStandardWeapons( int nRole = VEHICLE_ROLE_DRIVER ) { return false; } virtual void UpdateViewAngles( C_BasePlayer *pLocalPlayer, CUserCmd *pCmd ); virtual C_BaseCombatCharacter* GetPassenger( int nRole ); virtual int GetPassengerRole( C_BaseCombatCharacter *pEnt ); virtual void GetVehicleClipPlanes( float &flZNear, float &flZFar ) const; virtual int GetPrimaryAmmoType() const { return -1; } virtual int GetPrimaryAmmoCount() const { return -1; } virtual int GetPrimaryAmmoClip() const { return -1; } virtual bool PrimaryAmmoUsesClips() const { return false; } public: // C_BaseEntity overrides. virtual IClientVehicle* GetClientVehicle() { return this; } virtual C_BaseEntity *GetVehicleEnt() { return this; } virtual void SetupMove( C_BasePlayer *player, CUserCmd *ucmd, IMoveHelper *pHelper, CMoveData *move ) {} virtual void ProcessMovement( C_BasePlayer *pPlayer, CMoveData *pMoveData ) {} virtual void FinishMove( C_BasePlayer *player, CUserCmd *ucmd, CMoveData *move ) {} virtual bool IsPredicted() const { return false; } virtual void ItemPostFrame( C_BasePlayer *pPlayer ) {} virtual bool IsSelfAnimating() { return false; }; private: CHandle<C_BasePlayer> m_hPlayer; CHandle<C_BasePlayer> m_hPrevPlayer; bool m_bEnterAnimOn; bool m_bExitAnimOn; Vector m_vecEyeExitEndpoint; float m_flFOV; // The current FOV (changes during entry/exit anims). ViewSmoothingData_t m_ViewSmoothingData; }; IMPLEMENT_CLIENTCLASS_DT(C_PropVehiclePrisonerPod, DT_PropVehiclePrisonerPod, CPropVehiclePrisonerPod) RecvPropEHandle( RECVINFO(m_hPlayer) ), RecvPropBool( RECVINFO( m_bEnterAnimOn ) ), RecvPropBool( RECVINFO( m_bExitAnimOn ) ), RecvPropVector( RECVINFO( m_vecEyeExitEndpoint ) ), END_RECV_TABLE() BEGIN_DATADESC( C_PropVehiclePrisonerPod ) DEFINE_EMBEDDED( m_ViewSmoothingData ), END_DATADESC() //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- C_PropVehiclePrisonerPod::C_PropVehiclePrisonerPod( void ) { memset( &m_ViewSmoothingData, 0, sizeof( m_ViewSmoothingData ) ); m_ViewSmoothingData.pVehicle = this; m_ViewSmoothingData.bClampEyeAngles = true; m_ViewSmoothingData.flPitchCurveZero = PITCH_CURVE_ZERO; m_ViewSmoothingData.flPitchCurveLinear = PITCH_CURVE_LINEAR; m_ViewSmoothingData.flRollCurveZero = ROLL_CURVE_ZERO; m_ViewSmoothingData.flRollCurveLinear = ROLL_CURVE_LINEAR; m_ViewSmoothingData.flFOV = POD_VIEW_FOV; m_flFOV = 0; } //----------------------------------------------------------------------------- // Purpose: // Input : updateType - //----------------------------------------------------------------------------- void C_PropVehiclePrisonerPod::PreDataUpdate( DataUpdateType_t updateType ) { BaseClass::PreDataUpdate( updateType ); m_hPrevPlayer = m_hPlayer; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void C_PropVehiclePrisonerPod::PostDataUpdate( DataUpdateType_t updateType ) { BaseClass::PostDataUpdate( updateType ); if ( !m_hPlayer && m_hPrevPlayer ) { // They have just exited the vehicle. // Sometimes we never reach the end of our exit anim, such as if the // animation doesn't have fadeout 0 specified in the QC, so we fail to // catch it in VehicleViewSmoothing. Catch it here instead. m_ViewSmoothingData.bWasRunningAnim = false; } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- C_BaseCombatCharacter *C_PropVehiclePrisonerPod::GetPassenger( int nRole ) { if ( nRole == VEHICLE_ROLE_DRIVER ) return m_hPlayer.Get(); return NULL; } //----------------------------------------------------------------------------- // Returns the role of the passenger //----------------------------------------------------------------------------- int C_PropVehiclePrisonerPod::GetPassengerRole( C_BaseCombatCharacter *pPassenger ) { if ( m_hPlayer.Get() == pPassenger ) return VEHICLE_ROLE_DRIVER; return VEHICLE_ROLE_NONE; } //----------------------------------------------------------------------------- // Purpose: Modify the player view/camera while in a vehicle //----------------------------------------------------------------------------- void C_PropVehiclePrisonerPod::GetVehicleViewPosition( int nRole, Vector *pAbsOrigin, QAngle *pAbsAngles ) { VehicleViewSmoothing( m_hPlayer, pAbsOrigin, pAbsAngles, m_bEnterAnimOn, m_bExitAnimOn, &m_vecEyeExitEndpoint, &m_ViewSmoothingData, &m_flFOV ); } //----------------------------------------------------------------------------- // Purpose: // Input : pLocalPlayer - // pCmd - //----------------------------------------------------------------------------- void C_PropVehiclePrisonerPod::UpdateViewAngles( C_BasePlayer *pLocalPlayer, CUserCmd *pCmd ) { int eyeAttachmentIndex = LookupAttachment( "vehicle_driver_eyes" ); Vector vehicleEyeOrigin; QAngle vehicleEyeAngles; GetAttachmentLocal( eyeAttachmentIndex, vehicleEyeOrigin, vehicleEyeAngles ); // Limit the yaw. float flAngleDiff = AngleDiff( pCmd->viewangles.y, vehicleEyeAngles.y ); flAngleDiff = clamp( flAngleDiff, POD_VIEW_YAW_MIN, POD_VIEW_YAW_MAX ); pCmd->viewangles.y = vehicleEyeAngles.y + flAngleDiff; // Limit the pitch -- don't let them look down into the empty pod! flAngleDiff = AngleDiff( pCmd->viewangles.x, vehicleEyeAngles.x ); flAngleDiff = clamp( flAngleDiff, POD_VIEW_PITCH_MIN, POD_VIEW_PITCH_MAX ); pCmd->viewangles.x = vehicleEyeAngles.x + flAngleDiff; } //----------------------------------------------------------------------------- // Futzes with the clip planes //----------------------------------------------------------------------------- void C_PropVehiclePrisonerPod::GetVehicleClipPlanes( float &flZNear, float &flZFar ) const { // Pod doesn't need to adjust the clip planes. //flZNear = 6; } //----------------------------------------------------------------------------- // Renders hud elements //----------------------------------------------------------------------------- void C_PropVehiclePrisonerPod::DrawHudElements( ) { }
0
0.989674
1
0.989674
game-dev
MEDIA
0.694907
game-dev
0.965741
1
0.965741
ProjectIgnis/CardScripts
3,249
official/c47172959.lua
--ユベル-Das Ewig Liebe Wächter --Yubel - The Loving Defender Forever --Scripted by Eerie Code local s,id=GetID() function s.initial_effect(c) c:EnableReviveLimit() --Fusion Summon procedure Fusion.AddProcMixRep(c,true,true,s.ffilter,1,99,aux.FilterBoolFunctionEx(Card.IsSetCard,SET_YUBEL)) --Inflict 500 damage to your opponent for each Fusion Material local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(id,0)) e1:SetCategory(CATEGORY_DAMAGE) e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e1:SetProperty(EFFECT_FLAG_DELAY+EFFECT_FLAG_PLAYER_TARGET) e1:SetCode(EVENT_SPSUMMON_SUCCESS) e1:SetCondition(function(e) return e:GetHandler():IsFusionSummoned() end) e1:SetTarget(s.damtg) e1:SetOperation(s.damop) c:RegisterEffect(e1) --Cannot be destroyed by battle or card effects local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_SINGLE) e2:SetProperty(EFFECT_FLAG_SINGLE_RANGE) e2:SetCode(EFFECT_INDESTRUCTABLE_BATTLE) e2:SetRange(LOCATION_MZONE) e2:SetValue(1) c:RegisterEffect(e2) local e3=e2:Clone() e3:SetCode(EFFECT_INDESTRUCTABLE_EFFECT) c:RegisterEffect(e3) --You take no battle damage from battles involving this card local e4=e2:Clone() e4:SetCode(EFFECT_AVOID_BATTLE_DAMAGE) c:RegisterEffect(e4) --Inflict damage to your opponent equal to their monster's ATK and banish that monster local e5=Effect.CreateEffect(c) e5:SetDescription(aux.Stringid(id,1)) e5:SetCategory(CATEGORY_DAMAGE+CATEGORY_REMOVE) e5:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F) e5:SetCode(EVENT_DAMAGE_STEP_END) e5:SetCondition(s.damrmcon) e5:SetTarget(s.damrmtg) e5:SetOperation(s.damrmop) c:RegisterEffect(e5) end s.listed_series={SET_YUBEL} s.material_location=LOCATION_ONFIELD function s.ffilter(c,fc,sumtype,tp) return c:IsType(TYPE_EFFECT,fc,sumtype,tp) and c:IsOnField() end function s.damtg(e,tp,eg,ep,ev,re,r,rp,chk) local mg=e:GetHandler():GetMaterial() if chk==0 then return mg and #mg>0 end local dmg=#mg*500 Duel.SetTargetPlayer(1-tp) Duel.SetTargetParam(dmg) Duel.SetOperationInfo(0,CATEGORY_DAMAGE,nil,0,1-tp,dmg) end function s.damop(e,tp,eg,ep,ev,re,r,rp) local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM) Duel.Damage(p,d,REASON_EFFECT) end function s.damrmcon(e,tp,eg,ep,ev,re,r,rp) local bc=e:GetHandler():GetBattleTarget() if not bc then return false end if bc:IsRelateToBattle() then return bc:IsControler(1-tp) else return bc:IsPreviousControler(1-tp) end end function s.damrmtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end local bc=e:GetHandler():GetBattleTarget() local dam=0 if bc:IsRelateToBattle() then dam=bc:GetAttack() Duel.SetOperationInfo(0,CATEGORY_REMOVE,bc,1,0,0) else dam=bc:GetPreviousAttackOnField() e:SetLabel(dam) end e:SetLabelObject(bc) Duel.SetOperationInfo(0,CATEGORY_DAMAGE,nil,0,1-tp,dam) end function s.damrmop(e,tp,eg,ep,ev,re,r,rp) local dam=0 local bc=e:GetLabelObject() local battle_relation=bc:IsRelateToBattle() if battle_relation and bc:IsFaceup() and bc:IsControler(1-tp) then dam=bc:GetAttack() elseif not battle_relation then dam=e:GetLabel() end if Duel.Damage(1-tp,dam,REASON_EFFECT)>0 and battle_relation then Duel.Remove(bc,POS_FACEUP,REASON_EFFECT) end end
0
0.845516
1
0.845516
game-dev
MEDIA
0.993068
game-dev
0.952488
1
0.952488
openmultiplayer/wiki
3,690
docs/translations/es/scripting/callbacks/OnPlayerEditAttachedObject.md
--- title: OnPlayerEditAttachedObject description: This callback is called when a player ends attached object edition mode. tags: ["player"] --- import T from '../../../src/components/templates.js' <T.VersionWarn name='callback' version='SA-MP 0.3e' /> ## Description This callback is called when a player ends attached object edition mode. | Name | Description | | -------------- | ------------------------------------------------------------- | | playerid | The ID of the player that ended edition mode | | response | 0 if they cancelled (ESC) or 1 if they clicked the save icon. | | modelid | The model of the attached object that was edited | | boneid | The bone of the attached object that was edited | | Float:fOffsetX | The X offset for the attached object that was edited | | Float:fOffsetY | The Y offset for the attached object that was edited | | Float:fOffsetZ | The Z offset for the attached object that was edited | | Float:fRotX | The X rotation for the attached object that was edited | | Float:fRotY | The Y rotation for the attached object that was edited | | Float:fRotZ | The Z rotation for the attached object that was edited | | Float:fScaleX | The X scale for the attached object that was edited | | Float:fScaleY | The Y scale for the attached object that was edited | | Float:fScaleZ | The Z scale for the attached object that was edited | ## Returns 1 - Will prevent other scripts from receiving this callback. 0 - Indicates that this callback will be passed to the next script. It is always called first in filterscripts. ## Examples ```c enum attached_object_data { Float:ao_x, Float:ao_y, Float:ao_z, Float:ao_rx, Float:ao_ry, Float:ao_rz, Float:ao_sx, Float:ao_sy, Float:ao_sz } new ao[MAX_PLAYERS][MAX_PLAYER_ATTACHED_OBJECTS][attached_object_data]; // The data should be stored in the above array when attached objects are attached. public OnPlayerEditAttachedObject(playerid, response, index, modelid, boneid, Float:fOffsetX, Float:fOffsetY, Float:fOffsetZ, Float:fRotX, Float:fRotY, Float:fRotZ, Float:fScaleX, Float:fScaleY, Float:fScaleZ) { if (response) { SendClientMessage(playerid, COLOR_GREEN, "Attached object edition saved."); ao[playerid][index][ao_x] = fOffsetX; ao[playerid][index][ao_y] = fOffsetY; ao[playerid][index][ao_z] = fOffsetZ; ao[playerid][index][ao_rx] = fRotX; ao[playerid][index][ao_ry] = fRotY; ao[playerid][index][ao_rz] = fRotZ; ao[playerid][index][ao_sx] = fScaleX; ao[playerid][index][ao_sy] = fScaleY; ao[playerid][index][ao_sz] = fScaleZ; } else { SendClientMessage(playerid, COLOR_RED, "Attached object edition not saved."); new i = index; SetPlayerAttachedObject(playerid, index, modelid, boneid, ao[playerid][i][ao_x], ao[playerid][i][ao_y], ao[playerid][i][ao_z], ao[playerid][i][ao_rx], ao[playerid][i][ao_ry], ao[playerid][i][ao_rz], ao[playerid][i][ao_sx], ao[playerid][i][ao_sy], ao[playerid][i][ao_sz]); } return 1; } ``` ## Notes :::warning Editions should be discarded if response was '0' (cancelled). This must be done by storing the offsets etc. in an array BEFORE using EditAttachedObject. ::: ## Related Functions - [EditAttachedObject](../functions/EditAttachedObject.md): Edit an attached object. - [SetPlayerAttachedObject](../functions/SetPlayerAttachedObject.md): Attach an object to a player
0
0.8543
1
0.8543
game-dev
MEDIA
0.918056
game-dev
0.687732
1
0.687732
Dark-Basic-Software-Limited/Dark-Basic-Pro
14,423
Dark Basic Public Shared/Official Plugins/3D Cloth & Particles/Install/Examples/Hall/hall.dba
`-------------------------------------------------------------------------------------------------------------------------- ` Dark Physics Hall Demo ` By Ravey (Dave Milton) `-------------------------------------------------------------------------------------------------------------------------- `-------------------------------------------------------------------------------------------------------------------------- ` Our types `tortches type t_fire fire_emit wind chaos endtype `smoke type t_vortex vort vort_emit x# y# z# endtype `drapes type t_drapes cloth x# y# z# one two three flip count# endtype `lightmap fading type t_fade direction value top bottom speed endtype `recording and playbacl of the camera type t_move forward forward_speed# back back_speed# left left_speed# right right_speed# endtype `-------------------------------------------------------------------------------------------------------------------------- `Let's create empty arrays of our types for later use dim fire() as t_fire empty array fire() dim vortex() as t_vortex empty array vortex() dim drapes() as t_drapes empty array drapes() `-------------------------------------------------------------------------------------------------------------------------- `our globals global move as t_move global fade as t_fade fade.top=50 fade.bottom=30 fade.speed=2 `if record is set to 1 then the app will record cursor key movement to the move.dat file which can be played bacl global record=0 `the acceleration speed of the camera global speed#=.005 `our object and img count - so we dont have to manually track object numbers global obj_count=3 global img_count=0 `our objects global hall=1 global lightmap=2 `for our images global fire global smoke global drape `-------------------------------------------------------------------------------------------------------------------------- setup() `disable the escape key so we can perform our cleaning up excersise disable escapekey `-------------------------------------------------------------------------------------------------------------------------- ` Main Loop - nice and simple while escapekey()=0 fade_lightmap() if record=1 record() else playback() endif UPDATE PHYSICS sync Endwhile cleanup() end `-------------------------------------------------------------------------------------------------------------------------- `Setup routine function setup() hide mouse sync on : sync rate 60 : autocam off hide light 0 set ambient light 65 color backdrop rgb(20,20,40) position camera -373,0,134 turn camera right 180 load object "Media\hall.x",hall load object "Media\hall_LM.x",lightmap ghost object on lightmap,1 `load in our images inc img_count drape=img_count load image "Media\drape.png",drape inc img_count fire=img_count load image "Media\fire.png",fire inc img_count smoke=img_count load image "Media\smoke.jpg",smoke `deal with the move.dat file which stores our camera movement if record=1 if file exist("Media\move.dat") delete file "Media\move.dat" endif open to write 1,"Media\move.dat" else open to read 1,"Media\move.dat" endif load music "Media\misty.mp3",1 loop music 1 `set the frame rate for nice smooth physics SET PHYSICS FRAME RATE 80 `lets add our physics objects add_drapes(-18,25,55,50) add_drapes(56,25,55,100) add_fire(48.25,3,-56,150) add_fire(-387.6,3,-104,150) add_vortex(20,30,-14,2500) add_vortex(-63,30,-14,2500) add_vortex(99,30,-14,2500) endfunction `-------------------------------------------------------------------------------------------------------------------------- function cleanup() `lets clean up everything nice and tidy `first the fires array index to top fire() while array index valid(fire()) delete emitter fire().fire_emit delete effector fire().wind delete effector fire().chaos next array index fire() endwhile empty array fire() `now the smoke array index to top vortex() while array index valid(vortex()) delete emitter vortex().vort_emit delete effector vortex().vort next array index vortex() endwhile empty array vortex() `the drapes array index to top drapes() while array index valid(drapes()) delete cloth drapes().cloth delete object drapes().one delete object drapes().two delete object drapes().three next array index drapes() endwhile empty array drapes() `free the objects delete object hall delete object lightmap `free the images delete image drape delete image fire delete image smoke endfunction `-------------------------------------------------------------------------------------------------------------------------- function fade_lightmap() `fade in and out the lightmap - varied to give a flickery flame look if fade.direction=0 inc fade.value,fade.speed if fade.value>=fade.top then fade.direction=1 else dec fade.value,fade.speed if fade.value<=fade.bottom fade.direction=0 fade.top=rnd(30)+30 fade.bottom=rnd(30)+5 fade.speed=rnd(4)+1 endif endif fade object lightmap,fade.value+50 endfunction `-------------------------------------------------------------------------------------------------------------------------- function record() `records the movement of the camera if upkey() if move.forward_speed#<.5 then inc move.forward_speed#,speed# if move.forward=0 move.forward=1 write byte 1,1 endif else if move.forward_speed#>0.0 then dec move.forward_speed#,speed# if move.forward_speed#<0.0 then move.forward_speed#=0 if move.forward=1 move.forward=0 write byte 1,1 endif endif `-------------------- if downkey() if move.back_speed#<.5 then inc move.back_speed#,speed# if move.back=0 move.back=1 write byte 1,2 endif else if move.back_speed#>0.0 then dec move.back_speed#,speed# if move.back_speed#<0.0 then move.back_speed#=0 if move.back=1 move.back=0 write byte 1,2 endif endif `-------------------- if leftkey() if move.left_speed#<.5 then inc move.left_speed#,speed# if move.left=0 move.left=1 write byte 1,3 endif else if move.left_speed#>0.0 then dec move.left_speed#,speed# if move.left_speed#<0.0 then move.left_speed#=0 if move.left=1 move.left=0 write byte 1,3 endif endif `-------------------- if rightkey() if move.right_speed#<.5 then inc move.right_speed#,speed# if move.right=0 move.right=1 write byte 1,4 endif else if move.right_speed#>0.0 then dec move.right_speed#,speed# if move.right_speed#<0.0 then move.right_speed#=0 if move.right=1 move.right=0 write byte 1,4 endif endif `-------------------- write byte 1,0 if lower$(inkey$())="f" close file 1 end endif move camera move.forward_speed# move camera -move.back_speed# turn camera left move.left_speed# turn camera right move.right_speed# endfunction `-------------------------------------------------------------------------------------------------------------------------- function playback() while done=0 read byte 1,dat if dat=0 then done=1 `-------------------- if dat=1 move.forward=1-move.forward endif if move.forward=1 if move.forward_speed#<.5 then inc move.forward_speed#,speed# else if move.forward_speed#>0.0 then dec move.forward_speed#,speed# if move.forward_speed#<0.0 then move.forward_speed#=0 endif `-------------------- if dat=2 move.back=1-move.back endif if move.back=1 if move.back_speed#<.5 then inc move.back_speed#,speed# else if move.back_speed#>0.0 then dec move.back_speed#,speed# if move.back_speed#<0.0 then move.back_speed#=0 endif `-------------------- if dat=3 move.left=1-move.left endif if move.left=1 if move.left_speed#<.5 then inc move.left_speed#,speed# else if move.left_speed#>0.0 then dec move.left_speed#,speed# if move.left_speed#<0.0 then move.left_speed#=0 endif `-------------------- if dat=4 move.right=1-move.right endif if move.right=1 if move.right_speed#<.5 then inc move.right_speed#,speed# else if move.right_speed#>0.0 then dec move.right_speed#,speed# if move.right_speed#<0.0 then move.right_speed#=0 endif endwhile move camera move.forward_speed# move camera -move.back_speed# turn camera left move.left_speed# turn camera right move.right_speed# endfunction `-------------------------------------------------------------------------------------------------------------------------- function add_drapes(x#,y#,z#,fade) array insert at bottom drapes() drapes().x#=x# drapes().y#=y# drapes().z#=z# `lets make 3 object to attach the cloth too (the objects will be hidden from view) inc obj_count make object cube obj_count, 0.4 position object obj_count, x#-15, y, z# drapes().one=obj_count inc obj_count make object cube obj_count, 0.4 position object obj_count, x#+15, y, z# drapes().two=obj_count inc obj_count make object cube obj_count, 0.4 position object obj_count, x#, y#, z# drapes().three=obj_count `hide the objects hide object obj_count-2 hide object obj_count-1 hide object obj_count inc obj_count cloth=obj_count `make a cloth object MAKE CLOTH obj_count `make the actual cloth GENERATE RECTANGULAR CLOTH obj_count,30,30,20,20,1 SET CLOTH MASS obj_count,2 SET CLOTH ELASTICITY obj_count,2 `lets fix the 3 objects we made earlier onto the top left, top middle and top right poinsts of the cloth FIX CLOTH POINT TO OBJECT obj_count,10,obj_count-1,0,0,0 FIX CLOTH POINT TO OBJECT obj_count,0,obj_count-2,0,0,0 FIX CLOTH POINT TO OBJECT obj_count,20,obj_count-3,0,0,0 `by positioning the objects we are also positioning the cloth since it is now attached position object drapes().one,object position x(drapes().one),drapes().y#,object position z(drapes().one) position object drapes().two,object position x(drapes().two),drapes().y#,object position z(drapes().two) position object drapes().three,object position x(drapes().three),drapes().y#,object position z(drapes().three) drapes().cloth=obj_count texture object obj_count,drape fade object obj_count,fade `lets add some gravity to our cloth by adding an effector inc obj_count MAKE GRAVITY EFFECTOR obj_count BIND EFFECTOR TO object obj_count,cloth SET GRAVITY EFFECTOR obj_count, 0, -15, 0 grav=obj_count `now a damping effector inc obj_count MAKE DAMPING EFFECTOR obj_count BIND EFFECTOR TO object obj_count,cloth SET DAMPING EFFECTOR obj_count,.0001 damp=obj_count `lets add a wind effect to blow in throw the window by way of a force effector inc obj_count Make Force Effector obj_count Set Force Effector obj_count , 0 , 0 , -20 BIND EFFECTOR TO object obj_count,cloth endfunction `-------------------------------------------------------------------------------------------------------------------------- function add_fire(x#,y#,z#,explode) array insert at bottom fire() inc obj_count fire().fire_emit=obj_count `make an emitter to produce our nice flame particles MAKE BASIC EMITTER fire().fire_emit,30 texture object fire().fire_emit, fire ghost object on fire().fire_emit position object fire().fire_emit,x#,y#,z# disable object zwrite fire().fire_emit `set up our emitter SET EMITTER RATE fire().fire_emit,10 SET EMITTER EXPLODE fire().fire_emit, explode*0.01 SET EMITTER PARTICLE VELOCITY fire().fire_emit,1.0,0 SET EMITTER PARTICLE LIFE fire().fire_emit,3,0 SET EMITTER PARTICLE MASS fire().fire_emit, 1, 30 SET EMITTER PARTICLE SIZE fire().fire_emit,16, 0 SET EMITTER PARTICLE COLOR fire().fire_emit,255,255,255,50 SET PARTICLE Z SORTING fire().fire_emit,1 `lets add a wind effector to blow the fire upwards inc obj_count fire().wind=obj_count MAKE WIND EFFECTOR fire().wind BIND EFFECTOR TO OBJECT fire().wind,fire().fire_emit SET WIND EFFECTOR fire().wind,0,5,0 `add a chaos effector to make the flame wave nicely inc obj_count fire().chaos=obj_count Make Chaos Effector fire().chaos Set Chaos Effector fire().chaos , 400 BIND EFFECTOR TO OBJECT fire().chaos,fire().fire_emit endfunction `-------------------------------------------------------------------------------------------------------------------------- function add_vortex(x#,y#,z#,explode) inc obj_count array insert at bottom vortex() vortex().vort_emit=obj_count `make our smoke emitter MAKE BASIC EMITTER vortex().vort_emit,40 texture object vortex().vort_emit, smoke ghost object on vortex().vort_emit position object vortex().vort_emit,x#,y#,z# disable object zwrite vortex().vort_emit `set up the emitter SET EMITTER RATE vortex().vort_emit,40 SET EMITTER EXPLODE vortex().vort_emit, explode*0.01 SET EMITTER PARTICLE VELOCITY vortex().vort_emit,1.0,0 SET EMITTER PARTICLE LIFE vortex().vort_emit,1.5,0 SET EMITTER PARTICLE MASS vortex().vort_emit, 1, 30 SET EMITTER PARTICLE SIZE vortex().vort_emit,18, 0 SET EMITTER PARTICLE COLOR vortex().vort_emit,255,255,255,255 SET PARTICLE Z SORTING vortex().vort_emit,1 `add a very cool vortex effector to make the smoke spin in a vortex inc obj_count vortex().vort=obj_count MAKE VORTEX EFFECTOR vortex().vort BIND EFFECTOR TO OBJECT vortex().vort,vortex().vort_emit SET VORTEX EFFECTOR vortex().vort,400.0 endfunction `--------------------------------------------------------------------------------------------------------------------------
0
0.575867
1
0.575867
game-dev
MEDIA
0.673443
game-dev
0.896536
1
0.896536
GenshinMatrix/Fischless
39,713
src/Desktop/Fischless.Fetch/Datas/Snap/SnapCharacterProvider.cs
using Fischless.Fetch.Datas.Core; using Fischless.Fetch.ReShade; namespace Fischless.Fetch.Datas.Snap; public static class SnapCharacterProvider { public static IEnumerable<SnapCharacterInfo> GetSnapCharacters() { yield return new SnapCharacterInfo() { Id = 10000021, Name = "Amber", Rarity = 4, Gender = 1, Element = ElementType.Pyro, WeaponType = WeaponType.Bow, FaceIcon = "UI_AvatarIcon_Ambor.png", SortId = 1601244000, TextureOverride = ReShadeIniMapper.Map(10000021), }; yield return new SnapCharacterInfo() { Id = 10000014, Name = "Barbara", Rarity = 4, Gender = 1, Element = ElementType.Hydro, WeaponType = WeaponType.Catalyst, FaceIcon = "UI_AvatarIcon_Barbara.png", SortId = 1601244000, TextureOverride = ReShadeIniMapper.Map(10000014), }; yield return new SnapCharacterInfo() { Id = 10000024, Name = "Beidou", Rarity = 4, Gender = 1, Element = ElementType.Electro, WeaponType = WeaponType.Claymore, FaceIcon = "UI_AvatarIcon_Beidou.png", SortId = 1601244000, TextureOverride = ReShadeIniMapper.Map(10000024), }; yield return new SnapCharacterInfo() { Id = 10000032, Name = "Bennett", Rarity = 4, Gender = 0, Element = ElementType.Pyro, WeaponType = WeaponType.Sword, FaceIcon = "UI_AvatarIcon_Bennett.png", SortId = 1601244000, TextureOverride = ReShadeIniMapper.Map(10000032), }; yield return new SnapCharacterInfo() { Id = 10000036, Name = "Chongyun", Rarity = 4, Gender = 0, Element = ElementType.Cryo, WeaponType = WeaponType.Claymore, FaceIcon = "UI_AvatarIcon_Chongyun.png", SortId = 1601244000, TextureOverride = ReShadeIniMapper.Map(10000036), }; yield return new SnapCharacterInfo() { Id = 10000016, Name = "Diluc", Rarity = 5, Gender = 0, Element = ElementType.Pyro, WeaponType = WeaponType.Claymore, FaceIcon = "UI_AvatarIcon_Diluc.png", SortId = 1601244000, TextureOverride = ReShadeIniMapper.Map(10000016), }; yield return new SnapCharacterInfo() { Id = 10000031, Name = "Fischl", Rarity = 4, Gender = 1, Element = ElementType.Electro, WeaponType = WeaponType.Bow, FaceIcon = "UI_AvatarIcon_Fischl.png", SortId = 1601244000, TextureOverride = ReShadeIniMapper.Map(10000031), }; yield return new SnapCharacterInfo() { Id = 10000003, Name = "Jean", Rarity = 5, Gender = 1, Element = ElementType.Anemo, WeaponType = WeaponType.Sword, FaceIcon = "UI_AvatarIcon_Qin.png", SortId = 1601244000, TextureOverride = ReShadeIniMapper.Map(10000003), }; yield return new SnapCharacterInfo() { Id = 10000015, Name = "Kaeya", Rarity = 4, Gender = 0, Element = ElementType.Cryo, WeaponType = WeaponType.Sword, FaceIcon = "UI_AvatarIcon_Kaeya.png", SortId = 1601244000, TextureOverride = ReShadeIniMapper.Map(10000015), }; yield return new SnapCharacterInfo() { Id = 10000042, Name = "Keqing", Rarity = 5, Gender = 1, Element = ElementType.Electro, WeaponType = WeaponType.Sword, FaceIcon = "UI_AvatarIcon_Keqing.png", SortId = 1601244000, TextureOverride = ReShadeIniMapper.Map(10000042), }; yield return new SnapCharacterInfo() { Id = 10000029, Name = "Klee", Rarity = 5, Gender = 1, Element = ElementType.Pyro, WeaponType = WeaponType.Catalyst, FaceIcon = "UI_AvatarIcon_Klee.png", SortId = 1601244000, TextureOverride = ReShadeIniMapper.Map(10000029), }; yield return new SnapCharacterInfo() { Id = 10000006, Name = "Lisa", Rarity = 4, Gender = 1, Element = ElementType.Electro, WeaponType = WeaponType.Catalyst, FaceIcon = "UI_AvatarIcon_Lisa.png", SortId = 1601244000, TextureOverride = ReShadeIniMapper.Map(10000006), }; yield return new SnapCharacterInfo() { Id = 10000041, Name = "Mona", Rarity = 5, Gender = 1, Element = ElementType.Hydro, WeaponType = WeaponType.Catalyst, FaceIcon = "UI_AvatarIcon_Mona.png", SortId = 1601244000, TextureOverride = ReShadeIniMapper.Map(10000041), }; yield return new SnapCharacterInfo() { Id = 10000027, Name = "Ningguang", Rarity = 4, Gender = 1, Element = ElementType.Geo, WeaponType = WeaponType.Catalyst, FaceIcon = "UI_AvatarIcon_Ningguang.png", SortId = 1601244000, TextureOverride = ReShadeIniMapper.Map(10000027), }; yield return new SnapCharacterInfo() { Id = 10000034, Name = "Noelle", Rarity = 4, Gender = 1, Element = ElementType.Geo, WeaponType = WeaponType.Claymore, FaceIcon = "UI_AvatarIcon_Noel.png", SortId = 1601244000, TextureOverride = ReShadeIniMapper.Map(10000034), }; yield return new SnapCharacterInfo() { Id = 10000035, Name = "Qiqi", Rarity = 5, Gender = 1, Element = ElementType.Cryo, WeaponType = WeaponType.Sword, FaceIcon = "UI_AvatarIcon_Qiqi.png", SortId = 1601244000, TextureOverride = ReShadeIniMapper.Map(10000035), }; yield return new SnapCharacterInfo() { Id = 10000020, Name = "Razor", Rarity = 4, Gender = 0, Element = ElementType.Electro, WeaponType = WeaponType.Claymore, FaceIcon = "UI_AvatarIcon_Razor.png", SortId = 1601244000, TextureOverride = ReShadeIniMapper.Map(10000020), }; yield return new SnapCharacterInfo() { Id = 10000043, Name = "Sucrose", Rarity = 4, Gender = 1, Element = ElementType.Anemo, WeaponType = WeaponType.Catalyst, FaceIcon = "UI_AvatarIcon_Sucrose.png", SortId = 1601244000, TextureOverride = ReShadeIniMapper.Map(10000043), }; yield return new SnapCharacterInfo() { Id = 10000022, Name = "Venti", Rarity = 5, Gender = 0, Element = ElementType.Anemo, WeaponType = WeaponType.Bow, FaceIcon = "UI_AvatarIcon_Venti.png", SortId = 1601244000, TextureOverride = ReShadeIniMapper.Map(10000022), }; yield return new SnapCharacterInfo() { Id = 10000023, Name = "Xiangling", Rarity = 4, Gender = 1, Element = ElementType.Pyro, WeaponType = WeaponType.Polearm, FaceIcon = "UI_AvatarIcon_Xiangling.png", SortId = 1601244000, TextureOverride = ReShadeIniMapper.Map(10000023), }; yield return new SnapCharacterInfo() { Id = 10000025, Name = "Xingqiu", Rarity = 4, Gender = 0, Element = ElementType.Hydro, WeaponType = WeaponType.Sword, FaceIcon = "UI_AvatarIcon_Xingqiu.png", SortId = 1601244000, TextureOverride = ReShadeIniMapper.Map(10000025), }; yield return new SnapCharacterInfo() { Id = 10000039, Name = "Diona", Rarity = 4, Gender = 1, Element = ElementType.Cryo, WeaponType = WeaponType.Bow, FaceIcon = "UI_AvatarIcon_Diona.png", SortId = 1605060000, TextureOverride = ReShadeIniMapper.Map(10000039), }; yield return new SnapCharacterInfo() { Id = 10000033, Name = "Tartaglia", Rarity = 5, Gender = 0, Element = ElementType.Hydro, WeaponType = WeaponType.Bow, FaceIcon = "UI_AvatarIcon_Tartaglia.png", SortId = 1605060000, TextureOverride = ReShadeIniMapper.Map(10000033), }; yield return new SnapCharacterInfo() { Id = 10000044, Name = "Xinyan", Rarity = 4, Gender = 1, Element = ElementType.Pyro, WeaponType = WeaponType.Claymore, FaceIcon = "UI_AvatarIcon_Xinyan.png", SortId = 1606874400, TextureOverride = ReShadeIniMapper.Map(10000044), }; yield return new SnapCharacterInfo() { Id = 10000030, Name = "Zhongli", Rarity = 5, Gender = 0, Element = ElementType.Geo, WeaponType = WeaponType.Polearm, FaceIcon = "UI_AvatarIcon_Zhongli.png", SortId = 1606874400, TextureOverride = ReShadeIniMapper.Map(10000030), }; yield return new SnapCharacterInfo() { Id = 10000038, Name = "Albedo", Rarity = 5, Gender = 0, Element = ElementType.Geo, WeaponType = WeaponType.Sword, FaceIcon = "UI_AvatarIcon_Albedo.png", SortId = 1608588000, TextureOverride = ReShadeIniMapper.Map(10000038), }; yield return new SnapCharacterInfo() { Id = 10000037, Name = "Ganyu", Rarity = 5, Gender = 1, Element = ElementType.Cryo, WeaponType = WeaponType.Bow, FaceIcon = "UI_AvatarIcon_Ganyu.png", SortId = 1610467200, TextureOverride = ReShadeIniMapper.Map(10000037), }; yield return new SnapCharacterInfo() { Id = 10000026, Name = "Xiao", Rarity = 5, Gender = 0, Element = ElementType.Anemo, WeaponType = WeaponType.Polearm, FaceIcon = "UI_AvatarIcon_Xiao.png", SortId = 1612216800, TextureOverride = ReShadeIniMapper.Map(10000026), }; yield return new SnapCharacterInfo() { Id = 10000046, Name = "Hu Tao", Rarity = 5, Gender = 1, Element = ElementType.Pyro, WeaponType = WeaponType.Polearm, FaceIcon = "UI_AvatarIcon_Hutao.png", SortId = 1614700800, TextureOverride = ReShadeIniMapper.Map(10000046), }; yield return new SnapCharacterInfo() { Id = 10000045, Name = "Rosaria", Rarity = 4, Gender = 1, Element = ElementType.Cryo, WeaponType = WeaponType.Polearm, FaceIcon = "UI_AvatarIcon_Rosaria.png", SortId = 1617721200, TextureOverride = ReShadeIniMapper.Map(10000045), }; yield return new SnapCharacterInfo() { Id = 10000048, Name = "Yanfei", Rarity = 4, Gender = 1, Element = ElementType.Pyro, WeaponType = WeaponType.Catalyst, FaceIcon = "UI_AvatarIcon_Feiyan.png", SortId = 1619470800, TextureOverride = ReShadeIniMapper.Map(10000048), }; yield return new SnapCharacterInfo() { Id = 10000051, Name = "Eula", Rarity = 5, Gender = 1, Element = ElementType.Cryo, WeaponType = WeaponType.Claymore, FaceIcon = "UI_AvatarIcon_Eula.png", SortId = 1621350000, TextureOverride = ReShadeIniMapper.Map(10000051), }; yield return new SnapCharacterInfo() { Id = 10000047, Name = "Kaedehara Kazuha", Rarity = 5, Gender = 0, Element = ElementType.Anemo, WeaponType = WeaponType.Sword, FaceIcon = "UI_AvatarIcon_Kazuha.png", SortId = 1624978800, TextureOverride = ReShadeIniMapper.Map(10000047), }; yield return new SnapCharacterInfo() { Id = 10000002, Name = "Kamisato Ayaka", Rarity = 5, Gender = 1, Element = ElementType.Cryo, WeaponType = WeaponType.Sword, FaceIcon = "UI_AvatarIcon_Ayaka.png", SortId = 1626814800, TextureOverride = ReShadeIniMapper.Map(10000002), }; yield return new SnapCharacterInfo() { Id = 10000053, Name = "Sayu", Rarity = 4, Gender = 1, Element = ElementType.Anemo, WeaponType = WeaponType.Claymore, FaceIcon = "UI_AvatarIcon_Sayu.png", SortId = 1628607600, TextureOverride = ReShadeIniMapper.Map(10000053), }; yield return new SnapCharacterInfo() { Id = 10000049, Name = "Yoimiya", Rarity = 5, Gender = 1, Element = ElementType.Pyro, WeaponType = WeaponType.Bow, FaceIcon = "UI_AvatarIcon_Yoimiya.png", SortId = 1628607600, TextureOverride = ReShadeIniMapper.Map(10000049), }; yield return new SnapCharacterInfo() { Id = 10000062, Name = "Aloy", Rarity = 5, Gender = 1, Element = ElementType.Cryo, WeaponType = WeaponType.Bow, FaceIcon = "UI_AvatarIcon_Aloy.png", SortId = 1630443600, TextureOverride = ReShadeIniMapper.Map(10000062), }; yield return new SnapCharacterInfo() { Id = 10000056, Name = "Kujou Sara", Rarity = 4, Gender = 1, Element = ElementType.Electro, WeaponType = WeaponType.Bow, FaceIcon = "UI_AvatarIcon_Sara.png", SortId = 1630443600, TextureOverride = ReShadeIniMapper.Map(10000056), }; yield return new SnapCharacterInfo() { Id = 10000052, Name = "Raiden Shogun", Rarity = 5, Gender = 1, Element = ElementType.Electro, WeaponType = WeaponType.Polearm, FaceIcon = "UI_AvatarIcon_Shougun.png", SortId = 1630443600, TextureOverride = ReShadeIniMapper.Map(10000052), }; yield return new SnapCharacterInfo() { Id = 10000054, Name = "Sangonomiya Kokomi", Rarity = 5, Gender = 1, Element = ElementType.Hydro, WeaponType = WeaponType.Catalyst, FaceIcon = "UI_AvatarIcon_Kokomi.png", SortId = 1632236400, TextureOverride = ReShadeIniMapper.Map(10000054), }; yield return new SnapCharacterInfo() { Id = 10000050, Name = "Thoma", Rarity = 4, Gender = 0, Element = ElementType.Pyro, WeaponType = WeaponType.Polearm, FaceIcon = "UI_AvatarIcon_Tohma.png", SortId = 1635868800, TextureOverride = ReShadeIniMapper.Map(10000050), }; yield return new SnapCharacterInfo() { Id = 10000057, Name = "Arataki Itto", Rarity = 5, Gender = 0, Element = ElementType.Geo, WeaponType = WeaponType.Claymore, FaceIcon = "UI_AvatarIcon_Itto.png", SortId = 1639497600, TextureOverride = ReShadeIniMapper.Map(10000057), }; yield return new SnapCharacterInfo() { Id = 10000055, Name = "Gorou", Rarity = 4, Gender = 0, Element = ElementType.Geo, WeaponType = WeaponType.Bow, FaceIcon = "UI_AvatarIcon_Gorou.png", SortId = 1639497600, TextureOverride = ReShadeIniMapper.Map(10000055), }; yield return new SnapCharacterInfo() { Id = 10000063, Name = "Shenhe", Rarity = 5, Gender = 1, Element = ElementType.Cryo, WeaponType = WeaponType.Polearm, FaceIcon = "UI_AvatarIcon_Shenhe.png", SortId = 1641333600, TextureOverride = ReShadeIniMapper.Map(10000063), }; yield return new SnapCharacterInfo() { Id = 10000064, Name = "Yun Jin", Rarity = 4, Gender = 1, Element = ElementType.Geo, WeaponType = WeaponType.Polearm, FaceIcon = "UI_AvatarIcon_Yunjin.png", SortId = 1641333600, TextureOverride = ReShadeIniMapper.Map(10000064), }; yield return new SnapCharacterInfo() { Id = 10000058, Name = "Yae Miko", Rarity = 5, Gender = 1, Element = ElementType.Electro, WeaponType = WeaponType.Catalyst, FaceIcon = "UI_AvatarIcon_Yae.png", SortId = 1644962400, TextureOverride = ReShadeIniMapper.Map(10000058), }; yield return new SnapCharacterInfo() { Id = 10000066, Name = "Kamisato Ayato", Rarity = 5, Gender = 0, Element = ElementType.Hydro, WeaponType = WeaponType.Sword, FaceIcon = "UI_AvatarIcon_Ayato.png", SortId = 1648587600, TextureOverride = ReShadeIniMapper.Map(10000066), }; yield return new SnapCharacterInfo() { Id = 10000060, Name = "Yelan", Rarity = 5, Gender = 1, Element = ElementType.Hydro, WeaponType = WeaponType.Bow, FaceIcon = "UI_AvatarIcon_Yelan.png", SortId = 1653944400, TextureOverride = ReShadeIniMapper.Map(10000060), }; yield return new SnapCharacterInfo() { Id = 10000065, Name = "Kuki Shinobu", Rarity = 4, Gender = 1, Element = ElementType.Electro, WeaponType = WeaponType.Sword, FaceIcon = "UI_AvatarIcon_Shinobu.png", SortId = 1655823600, TextureOverride = ReShadeIniMapper.Map(10000065), }; yield return new SnapCharacterInfo() { Id = 10000059, Name = "Shikanoin Heizou", Rarity = 4, Gender = 0, Element = ElementType.Anemo, WeaponType = WeaponType.Catalyst, FaceIcon = "UI_AvatarIcon_Heizo.png", SortId = 1657659600, TextureOverride = ReShadeIniMapper.Map(10000059), }; yield return new SnapCharacterInfo() { Id = 10000067, Name = "Collei", Rarity = 4, Gender = 1, Element = ElementType.Dendro, WeaponType = WeaponType.Bow, FaceIcon = "UI_AvatarIcon_Collei.png", SortId = 1661288400, TextureOverride = ReShadeIniMapper.Map(10000067), }; yield return new SnapCharacterInfo() { Id = 10000069, Name = "Tighnari", Rarity = 5, Gender = 0, Element = ElementType.Dendro, WeaponType = WeaponType.Bow, FaceIcon = "UI_AvatarIcon_Tighnari.png", SortId = 1661288400, TextureOverride = ReShadeIniMapper.Map(10000069), }; yield return new SnapCharacterInfo() { Id = 10000068, Name = "Dori", Rarity = 4, Gender = 1, Element = ElementType.Electro, WeaponType = WeaponType.Claymore, FaceIcon = "UI_AvatarIcon_Dori.png", SortId = 1662735600, TextureOverride = ReShadeIniMapper.Map(10000068), }; yield return new SnapCharacterInfo() { Id = 10000072, Name = "Candace", Rarity = 4, Gender = 1, Element = ElementType.Hydro, WeaponType = WeaponType.Polearm, FaceIcon = "UI_AvatarIcon_Candace.png", SortId = 1664226000, TextureOverride = ReShadeIniMapper.Map(10000072), }; yield return new SnapCharacterInfo() { Id = 10000071, Name = "Cyno", Rarity = 5, Gender = 0, Element = ElementType.Electro, WeaponType = WeaponType.Polearm, FaceIcon = "UI_AvatarIcon_Cyno.png", SortId = 1664226000, TextureOverride = ReShadeIniMapper.Map(10000071), }; yield return new SnapCharacterInfo() { Id = 10000070, Name = "Nilou", Rarity = 5, Gender = 1, Element = ElementType.Hydro, WeaponType = WeaponType.Sword, FaceIcon = "UI_AvatarIcon_Nilou.png", SortId = 1665759600, TextureOverride = ReShadeIniMapper.Map(10000070), }; yield return new SnapCharacterInfo() { Id = 10000073, Name = "Nahida", Rarity = 5, Gender = 1, Element = ElementType.Dendro, WeaponType = WeaponType.Catalyst, FaceIcon = "UI_AvatarIcon_Nahida.png", SortId = 1667253600, TextureOverride = ReShadeIniMapper.Map(10000073), }; yield return new SnapCharacterInfo() { Id = 10000074, Name = "Layla", Rarity = 4, Gender = 1, Element = ElementType.Cryo, WeaponType = WeaponType.Sword, FaceIcon = "UI_AvatarIcon_Layla.png", SortId = 1668787200, TextureOverride = ReShadeIniMapper.Map(10000074), }; yield return new SnapCharacterInfo() { Id = 10000076, Name = "Faruzan", Rarity = 4, Gender = 1, Element = ElementType.Anemo, WeaponType = WeaponType.Bow, FaceIcon = "UI_AvatarIcon_Faruzan.png", SortId = 1670277600, TextureOverride = ReShadeIniMapper.Map(10000076), }; yield return new SnapCharacterInfo() { Id = 10000075, Name = "Wanderer", Rarity = 5, Gender = 0, Element = ElementType.Anemo, WeaponType = WeaponType.Catalyst, FaceIcon = "UI_AvatarIcon_Wanderer.png", SortId = 1670277600, TextureOverride = ReShadeIniMapper.Map(10000075), }; yield return new SnapCharacterInfo() { Id = 10000078, Name = "Alhaitham", Rarity = 5, Gender = 0, Element = ElementType.Dendro, WeaponType = WeaponType.Sword, FaceIcon = "UI_AvatarIcon_Alhatham.png", SortId = 1673906400, TextureOverride = ReShadeIniMapper.Map(10000078), }; yield return new SnapCharacterInfo() { Id = 10000077, Name = "Yaoyao", Rarity = 4, Gender = 1, Element = ElementType.Dendro, WeaponType = WeaponType.Polearm, FaceIcon = "UI_AvatarIcon_Yaoyao.png", SortId = 1673906400, TextureOverride = ReShadeIniMapper.Map(10000077), }; yield return new SnapCharacterInfo() { Id = 10000079, Name = "Dehya", Rarity = 5, Gender = 1, Element = ElementType.Pyro, WeaponType = WeaponType.Claymore, FaceIcon = "UI_AvatarIcon_Dehya.png", SortId = 1677535200, TextureOverride = ReShadeIniMapper.Map(10000079), }; yield return new SnapCharacterInfo() { Id = 10000080, Name = "Mika", Rarity = 4, Gender = 0, Element = ElementType.Cryo, WeaponType = WeaponType.Polearm, FaceIcon = "UI_AvatarIcon_Mika.png", SortId = 1679414400, TextureOverride = ReShadeIniMapper.Map(10000080), }; yield return new SnapCharacterInfo() { Id = 10000082, Name = "Baizhu", Rarity = 5, Gender = 0, Element = ElementType.Dendro, WeaponType = WeaponType.Catalyst, FaceIcon = "UI_AvatarIcon_Baizhuer.png", SortId = 1683039600, TextureOverride = ReShadeIniMapper.Map(10000082), }; yield return new SnapCharacterInfo() { Id = 10000081, Name = "Kaveh", Rarity = 4, Gender = 0, Element = ElementType.Dendro, WeaponType = WeaponType.Claymore, FaceIcon = "UI_AvatarIcon_Kaveh.png", SortId = 1683039600, TextureOverride = ReShadeIniMapper.Map(10000081), }; yield return new SnapCharacterInfo() { Id = 10000061, Name = "Kirara", Rarity = 4, Gender = 1, Element = ElementType.Dendro, WeaponType = WeaponType.Sword, FaceIcon = "UI_AvatarIcon_Momoka.png", SortId = 1684789200, TextureOverride = ReShadeIniMapper.Map(10000061), }; yield return new SnapCharacterInfo() { Id = 10000083, Name = "Lynette", Rarity = 4, Gender = 1, Element = ElementType.Anemo, WeaponType = WeaponType.Sword, FaceIcon = "UI_AvatarIcon_Linette.png", SortId = 1692046800, TextureOverride = ReShadeIniMapper.Map(10000083), }; yield return new SnapCharacterInfo() { Id = 10000084, Name = "Lyney", Rarity = 5, Gender = 0, Element = ElementType.Pyro, WeaponType = WeaponType.Bow, FaceIcon = "UI_AvatarIcon_Liney.png", SortId = 1692046800, TextureOverride = ReShadeIniMapper.Map(10000084), }; yield return new SnapCharacterInfo() { Id = 10000085, Name = "Freminet", Rarity = 4, Gender = 0, Element = ElementType.Cryo, WeaponType = WeaponType.Claymore, FaceIcon = "UI_AvatarIcon_Freminet.png", SortId = 1693926000, TextureOverride = ReShadeIniMapper.Map(10000085), }; yield return new SnapCharacterInfo() { Id = 10000087, Name = "Neuvillette", Rarity = 5, Gender = 0, Element = ElementType.Hydro, WeaponType = WeaponType.Catalyst, FaceIcon = "UI_AvatarIcon_Neuvillette.png", SortId = 1695675600, TextureOverride = ReShadeIniMapper.Map(10000087), }; yield return new SnapCharacterInfo() { Id = 10000086, Name = "Wriothesley", Rarity = 5, Gender = 0, Element = ElementType.Cryo, WeaponType = WeaponType.Catalyst, FaceIcon = "UI_AvatarIcon_Wriothesley.png", SortId = 1697554800, TextureOverride = ReShadeIniMapper.Map(10000086), }; yield return new SnapCharacterInfo() { Id = 10000088, Name = "Charlotte", Rarity = 4, Gender = 1, Element = ElementType.Cryo, WeaponType = WeaponType.Catalyst, FaceIcon = "UI_AvatarIcon_Charlotte.png", SortId = 1699308000, TextureOverride = ReShadeIniMapper.Map(10000088), }; yield return new SnapCharacterInfo() { Id = 10000089, Name = "Furina", Rarity = 5, Gender = 1, Element = ElementType.Hydro, WeaponType = WeaponType.Sword, FaceIcon = "UI_AvatarIcon_Furina.png", SortId = 1699308000, TextureOverride = ReShadeIniMapper.Map(10000089), }; yield return new SnapCharacterInfo() { Id = 10000091, Name = "Navia", Rarity = 5, Gender = 1, Element = ElementType.Geo, WeaponType = WeaponType.Claymore, FaceIcon = "UI_AvatarIcon_Navia.png", SortId = 1702936800, TextureOverride = ReShadeIniMapper.Map(10000091), }; yield return new SnapCharacterInfo() { Id = 10000090, Name = "Chevreuse", Rarity = 4, Gender = 1, Element = ElementType.Pyro, WeaponType = WeaponType.Polearm, FaceIcon = "UI_AvatarIcon_Chevreuse.png", SortId = 1704816000, TextureOverride = ReShadeIniMapper.Map(10000090), }; yield return new SnapCharacterInfo() { Id = 10000092, Name = "Gaming", Rarity = 4, Gender = 0, Element = ElementType.Pyro, WeaponType = WeaponType.Claymore, FaceIcon = "UI_AvatarIcon_Gaming.png", SortId = 1706565600, TextureOverride = ReShadeIniMapper.Map(10000092), }; yield return new SnapCharacterInfo() { Id = 10000093, Name = "Xianyun", Rarity = 5, Gender = 1, Element = ElementType.Anemo, WeaponType = WeaponType.Catalyst, FaceIcon = "UI_AvatarIcon_Liuyun.png", SortId = 1706565600, TextureOverride = ReShadeIniMapper.Map(10000093), }; yield return new SnapCharacterInfo() { Id = 10000094, Name = "Chiori", Rarity = 5, Gender = 1, Element = ElementType.Geo, WeaponType = WeaponType.Sword, FaceIcon = "UI_AvatarIcon_Chiori.png", SortId = 1710194400, TextureOverride = ReShadeIniMapper.Map(10000094), }; yield return new SnapCharacterInfo() { Id = 10000096, Name = "Arlecchino", Rarity = 5, Gender = 1, Element = ElementType.Pyro, WeaponType = WeaponType.Polearm, FaceIcon = "UI_AvatarIcon_Arlecchino.png", SortId = 1713819600, TextureOverride = ReShadeIniMapper.Map(10000096), }; yield return new SnapCharacterInfo() { Id = 10000098, Name = "Clorinde", Rarity = 5, Gender = 1, Element = ElementType.Electro, WeaponType = WeaponType.Sword, FaceIcon = "UI_AvatarIcon_Clorinde.png", SortId = 1717448400, TextureOverride = ReShadeIniMapper.Map(10000098), }; yield return new SnapCharacterInfo() { Id = 10000097, Name = "Sethos", Rarity = 4, Gender = 0, Element = ElementType.Electro, WeaponType = WeaponType.Bow, FaceIcon = "UI_AvatarIcon_Sethos.png", SortId = 1717448400, TextureOverride = ReShadeIniMapper.Map(10000097), }; yield return new SnapCharacterInfo() { Id = 10000095, Name = "Sigewinne", Rarity = 5, Gender = 1, Element = ElementType.Hydro, WeaponType = WeaponType.Bow, FaceIcon = "UI_AvatarIcon_Sigewinne.png", SortId = 1719414000, TextureOverride = ReShadeIniMapper.Map(10000095), }; yield return new SnapCharacterInfo() { Id = 10000099, Name = "Emilie", Rarity = 5, Gender = 1, Element = ElementType.Dendro, WeaponType = WeaponType.Polearm, FaceIcon = "UI_AvatarIcon_Emilie.png", SortId = 1722956400, TextureOverride = ReShadeIniMapper.Map(10000099), }; yield return new SnapCharacterInfo() { Id = 10000100, Name = "Kachina", Rarity = 4, Gender = 1, Element = ElementType.Geo, WeaponType = WeaponType.Polearm, FaceIcon = "UI_AvatarIcon_Kachina.png", SortId = 1724706000, TextureOverride = ReShadeIniMapper.Map(10000100), }; yield return new SnapCharacterInfo() { Id = 10000102, Name = "Mualani", Rarity = 5, Gender = 1, Element = ElementType.Hydro, WeaponType = WeaponType.Catalyst, FaceIcon = "UI_AvatarIcon_Mualani.png", SortId = 1724706000, TextureOverride = ReShadeIniMapper.Map(10000102), }; yield return new SnapCharacterInfo() { Id = 10000101, Name = "Kinich", Rarity = 5, Gender = 0, Element = ElementType.Dendro, WeaponType = WeaponType.Claymore, FaceIcon = "UI_AvatarIcon_Kinich.png", SortId = 1726585200, TextureOverride = ReShadeIniMapper.Map(10000101), }; yield return new SnapCharacterInfo() { Id = 10000103, Name = "Xilonen", Rarity = 5, Gender = 1, Element = ElementType.Geo, WeaponType = WeaponType.Sword, FaceIcon = "UI_AvatarIcon_Xilonen.png", SortId = 1728334800, TextureOverride = ReShadeIniMapper.Map(10000103), }; yield return new SnapCharacterInfo() { Id = 10000104, Name = "Chasca", Rarity = 5, Gender = 1, Element = ElementType.Anemo, WeaponType = WeaponType.Bow, FaceIcon = "UI_AvatarIcon_Chasca.png", SortId = 1731967200, TextureOverride = ReShadeIniMapper.Map(10000104), }; yield return new SnapCharacterInfo() { Id = 10000105, Name = "Ororon", Rarity = 4, Gender = 0, Element = ElementType.Electro, WeaponType = WeaponType.Bow, FaceIcon = "UI_AvatarIcon_Olorun.png", SortId = 1731967200, TextureOverride = ReShadeIniMapper.Map(10000105), }; yield return new SnapCharacterInfo() { Id = 10000107, Name = "Citlali", Rarity = 5, Gender = 1, Element = ElementType.Cryo, WeaponType = WeaponType.Catalyst, FaceIcon = "UI_AvatarIcon_Citlali.png", SortId = 1735596000, TextureOverride = ReShadeIniMapper.Map(10000107), }; yield return new SnapCharacterInfo() { Id = 10000106, Name = "Mavuika", Rarity = 5, Gender = 1, Element = ElementType.Pyro, WeaponType = WeaponType.Claymore, FaceIcon = "UI_AvatarIcon_Mavuika.png", SortId = 1735596000, TextureOverride = ReShadeIniMapper.Map(10000106), }; yield return new SnapCharacterInfo() { Id = 10000108, Name = "Lan Yan", Rarity = 4, Gender = 1, Element = ElementType.Anemo, WeaponType = WeaponType.Catalyst, FaceIcon = "UI_AvatarIcon_LanYan.png", SortId = 1737475200, TextureOverride = ReShadeIniMapper.Map(10000108), }; yield return new SnapCharacterInfo() { Id = 10000109, Name = "Yumemizuki Mizuki", Rarity = 5, Gender = 1, Element = ElementType.Anemo, WeaponType = WeaponType.Catalyst, FaceIcon = "UI_AvatarIcon_Mizuki.png", SortId = 1739224800, TextureOverride = ReShadeIniMapper.Map(10000109), }; /// yield return new SnapCharacterInfo() { Id = 10000005, Name = "Aether", Rarity = 5, Gender = 0, Element = ElementType.None, WeaponType = WeaponType.Sword, FaceIcon = "UI_AvatarIcon_PlayerBoy.png", SortId = 0, TextureOverride = ReShadeIniMapper.Map(10000005), }; yield return new SnapCharacterInfo() { Id = 10000007, Name = "Lumine", Rarity = 5, Gender = 1, Element = ElementType.None, WeaponType = WeaponType.Sword, FaceIcon = "UI_AvatarIcon_PlayerGirl.png", SortId = 0, TextureOverride = ReShadeIniMapper.Map(10000007), }; /// yield return new SnapCharacterInfo() { Id = -1, Name = "Aozi", Rarity = 4, Gender = 2, Element = ElementType.None, WeaponType = WeaponType.None, FaceIcon = "UI_AvatarIcon_Aozi.png", SortId = int.MaxValue, TextureOverride = ReShadeIniMapper.Map(-1), }; yield return new SnapCharacterInfo() { Id = -2, Name = "Paimon", Rarity = 1, Gender = 2, Element = ElementType.None, WeaponType = WeaponType.None, FaceIcon = "UI_AvatarIcon_Paimon.png", SortId = -2, TextureOverride = ReShadeIniMapper.Map(-2), }; } }
0
0.615985
1
0.615985
game-dev
MEDIA
0.765261
game-dev
0.922962
1
0.922962
CreativeDesigner3D/BlenderSource
23,704
extern/bullet2/src/BulletCollision/CollisionShapes/btHeightfieldTerrainShape.cpp
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "btHeightfieldTerrainShape.h" #include "LinearMath/btTransformUtil.h" btHeightfieldTerrainShape::btHeightfieldTerrainShape( int heightStickWidth, int heightStickLength, const void* heightfieldData, btScalar heightScale, btScalar minHeight, btScalar maxHeight, int upAxis, PHY_ScalarType hdt, bool flipQuadEdges) :m_userIndex2(-1), m_userValue3(0), m_triangleInfoMap(0) { initialize(heightStickWidth, heightStickLength, heightfieldData, heightScale, minHeight, maxHeight, upAxis, hdt, flipQuadEdges); } btHeightfieldTerrainShape::btHeightfieldTerrainShape(int heightStickWidth, int heightStickLength, const void* heightfieldData, btScalar maxHeight, int upAxis, bool useFloatData, bool flipQuadEdges) :m_userIndex2(-1), m_userValue3(0), m_triangleInfoMap(0) { // legacy constructor: support only float or unsigned char, // and min height is zero PHY_ScalarType hdt = (useFloatData) ? PHY_FLOAT : PHY_UCHAR; btScalar minHeight = 0.0f; // previously, height = uchar * maxHeight / 65535. // So to preserve legacy behavior, heightScale = maxHeight / 65535 btScalar heightScale = maxHeight / 65535; initialize(heightStickWidth, heightStickLength, heightfieldData, heightScale, minHeight, maxHeight, upAxis, hdt, flipQuadEdges); } void btHeightfieldTerrainShape::initialize( int heightStickWidth, int heightStickLength, const void* heightfieldData, btScalar heightScale, btScalar minHeight, btScalar maxHeight, int upAxis, PHY_ScalarType hdt, bool flipQuadEdges) { // validation btAssert(heightStickWidth > 1); // && "bad width"); btAssert(heightStickLength > 1); // && "bad length"); btAssert(heightfieldData); // && "null heightfield data"); // btAssert(heightScale) -- do we care? Trust caller here btAssert(minHeight <= maxHeight); // && "bad min/max height"); btAssert(upAxis >= 0 && upAxis < 3); // && "bad upAxis--should be in range [0,2]"); btAssert(hdt != PHY_UCHAR || hdt != PHY_FLOAT || hdt != PHY_SHORT); // && "Bad height data type enum"); // initialize member variables m_shapeType = TERRAIN_SHAPE_PROXYTYPE; m_heightStickWidth = heightStickWidth; m_heightStickLength = heightStickLength; m_minHeight = minHeight; m_maxHeight = maxHeight; m_width = (btScalar)(heightStickWidth - 1); m_length = (btScalar)(heightStickLength - 1); m_heightScale = heightScale; m_heightfieldDataUnknown = heightfieldData; m_heightDataType = hdt; m_flipQuadEdges = flipQuadEdges; m_useDiamondSubdivision = false; m_useZigzagSubdivision = false; m_flipTriangleWinding = false; m_upAxis = upAxis; m_localScaling.setValue(btScalar(1.), btScalar(1.), btScalar(1.)); m_vboundsChunkSize = 0; m_vboundsGridWidth = 0; m_vboundsGridLength = 0; // determine min/max axis-aligned bounding box (aabb) values switch (m_upAxis) { case 0: { m_localAabbMin.setValue(m_minHeight, 0, 0); m_localAabbMax.setValue(m_maxHeight, m_width, m_length); break; } case 1: { m_localAabbMin.setValue(0, m_minHeight, 0); m_localAabbMax.setValue(m_width, m_maxHeight, m_length); break; }; case 2: { m_localAabbMin.setValue(0, 0, m_minHeight); m_localAabbMax.setValue(m_width, m_length, m_maxHeight); break; } default: { //need to get valid m_upAxis btAssert(0); // && "Bad m_upAxis"); } } // remember origin (defined as exact middle of aabb) m_localOrigin = btScalar(0.5) * (m_localAabbMin + m_localAabbMax); } btHeightfieldTerrainShape::~btHeightfieldTerrainShape() { clearAccelerator(); } void btHeightfieldTerrainShape::getAabb(const btTransform& t, btVector3& aabbMin, btVector3& aabbMax) const { btVector3 halfExtents = (m_localAabbMax - m_localAabbMin) * m_localScaling * btScalar(0.5); btVector3 localOrigin(0, 0, 0); localOrigin[m_upAxis] = (m_minHeight + m_maxHeight) * btScalar(0.5); localOrigin *= m_localScaling; btMatrix3x3 abs_b = t.getBasis().absolute(); btVector3 center = t.getOrigin(); btVector3 extent = halfExtents.dot3(abs_b[0], abs_b[1], abs_b[2]); extent += btVector3(getMargin(), getMargin(), getMargin()); aabbMin = center - extent; aabbMax = center + extent; } /// This returns the "raw" (user's initial) height, not the actual height. /// The actual height needs to be adjusted to be relative to the center /// of the heightfield's AABB. btScalar btHeightfieldTerrainShape::getRawHeightFieldValue(int x, int y) const { btScalar val = 0.f; switch (m_heightDataType) { case PHY_FLOAT: { val = m_heightfieldDataFloat[(y * m_heightStickWidth) + x]; break; } case PHY_UCHAR: { unsigned char heightFieldValue = m_heightfieldDataUnsignedChar[(y * m_heightStickWidth) + x]; val = heightFieldValue * m_heightScale; break; } case PHY_SHORT: { short hfValue = m_heightfieldDataShort[(y * m_heightStickWidth) + x]; val = hfValue * m_heightScale; break; } default: { btAssert(!"Bad m_heightDataType"); } } return val; } /// this returns the vertex in bullet-local coordinates void btHeightfieldTerrainShape::getVertex(int x, int y, btVector3& vertex) const { btAssert(x >= 0); btAssert(y >= 0); btAssert(x < m_heightStickWidth); btAssert(y < m_heightStickLength); btScalar height = getRawHeightFieldValue(x, y); switch (m_upAxis) { case 0: { vertex.setValue( height - m_localOrigin.getX(), (-m_width / btScalar(2.0)) + x, (-m_length / btScalar(2.0)) + y); break; } case 1: { vertex.setValue( (-m_width / btScalar(2.0)) + x, height - m_localOrigin.getY(), (-m_length / btScalar(2.0)) + y); break; }; case 2: { vertex.setValue( (-m_width / btScalar(2.0)) + x, (-m_length / btScalar(2.0)) + y, height - m_localOrigin.getZ()); break; } default: { //need to get valid m_upAxis btAssert(0); } } vertex *= m_localScaling; } static inline int getQuantized( btScalar x) { if (x < 0.0) { return (int)(x - 0.5); } return (int)(x + 0.5); } /// given input vector, return quantized version /** This routine is basically determining the gridpoint indices for a given input vector, answering the question: "which gridpoint is closest to the provided point?". "with clamp" means that we restrict the point to be in the heightfield's axis-aligned bounding box. */ void btHeightfieldTerrainShape::quantizeWithClamp(int* out, const btVector3& point, int /*isMax*/) const { btVector3 clampedPoint(point); clampedPoint.setMax(m_localAabbMin); clampedPoint.setMin(m_localAabbMax); out[0] = getQuantized(clampedPoint.getX()); out[1] = getQuantized(clampedPoint.getY()); out[2] = getQuantized(clampedPoint.getZ()); } /// process all triangles within the provided axis-aligned bounding box /** basic algorithm: - convert input aabb to local coordinates (scale down and shift for local origin) - convert input aabb to a range of heightfield grid points (quantize) - iterate over all triangles in that subset of the grid */ void btHeightfieldTerrainShape::processAllTriangles(btTriangleCallback* callback, const btVector3& aabbMin, const btVector3& aabbMax) const { // scale down the input aabb's so they are in local (non-scaled) coordinates btVector3 localAabbMin = aabbMin * btVector3(1.f / m_localScaling[0], 1.f / m_localScaling[1], 1.f / m_localScaling[2]); btVector3 localAabbMax = aabbMax * btVector3(1.f / m_localScaling[0], 1.f / m_localScaling[1], 1.f / m_localScaling[2]); // account for local origin localAabbMin += m_localOrigin; localAabbMax += m_localOrigin; //quantize the aabbMin and aabbMax, and adjust the start/end ranges int quantizedAabbMin[3]; int quantizedAabbMax[3]; quantizeWithClamp(quantizedAabbMin, localAabbMin, 0); quantizeWithClamp(quantizedAabbMax, localAabbMax, 1); // expand the min/max quantized values // this is to catch the case where the input aabb falls between grid points! for (int i = 0; i < 3; ++i) { quantizedAabbMin[i]--; quantizedAabbMax[i]++; } int startX = 0; int endX = m_heightStickWidth - 1; int startJ = 0; int endJ = m_heightStickLength - 1; switch (m_upAxis) { case 0: { if (quantizedAabbMin[1] > startX) startX = quantizedAabbMin[1]; if (quantizedAabbMax[1] < endX) endX = quantizedAabbMax[1]; if (quantizedAabbMin[2] > startJ) startJ = quantizedAabbMin[2]; if (quantizedAabbMax[2] < endJ) endJ = quantizedAabbMax[2]; break; } case 1: { if (quantizedAabbMin[0] > startX) startX = quantizedAabbMin[0]; if (quantizedAabbMax[0] < endX) endX = quantizedAabbMax[0]; if (quantizedAabbMin[2] > startJ) startJ = quantizedAabbMin[2]; if (quantizedAabbMax[2] < endJ) endJ = quantizedAabbMax[2]; break; }; case 2: { if (quantizedAabbMin[0] > startX) startX = quantizedAabbMin[0]; if (quantizedAabbMax[0] < endX) endX = quantizedAabbMax[0]; if (quantizedAabbMin[1] > startJ) startJ = quantizedAabbMin[1]; if (quantizedAabbMax[1] < endJ) endJ = quantizedAabbMax[1]; break; } default: { //need to get valid m_upAxis btAssert(0); } } // TODO If m_vboundsGrid is available, use it to determine if we really need to process this area for (int j = startJ; j < endJ; j++) { for (int x = startX; x < endX; x++) { btVector3 vertices[3]; int indices[3] = { 0, 1, 2 }; if (m_flipTriangleWinding) { indices[0] = 2; indices[2] = 0; } if (m_flipQuadEdges || (m_useDiamondSubdivision && !((j + x) & 1)) || (m_useZigzagSubdivision && !(j & 1))) { //first triangle getVertex(x, j, vertices[indices[0]]); getVertex(x, j + 1, vertices[indices[1]]); getVertex(x + 1, j + 1, vertices[indices[2]]); callback->processTriangle(vertices, 2 * x, j); //second triangle // getVertex(x,j,vertices[0]);//already got this vertex before, thanks to Danny Chapman getVertex(x + 1, j + 1, vertices[indices[1]]); getVertex(x + 1, j, vertices[indices[2]]); callback->processTriangle(vertices, 2 * x+1, j); } else { //first triangle getVertex(x, j, vertices[indices[0]]); getVertex(x, j + 1, vertices[indices[1]]); getVertex(x + 1, j, vertices[indices[2]]); callback->processTriangle(vertices, 2 * x, j); //second triangle getVertex(x + 1, j, vertices[indices[0]]); //getVertex(x,j+1,vertices[1]); getVertex(x + 1, j + 1, vertices[indices[2]]); callback->processTriangle(vertices, 2 * x+1, j); } } } } void btHeightfieldTerrainShape::calculateLocalInertia(btScalar, btVector3& inertia) const { //moving concave objects not supported inertia.setValue(btScalar(0.), btScalar(0.), btScalar(0.)); } void btHeightfieldTerrainShape::setLocalScaling(const btVector3& scaling) { m_localScaling = scaling; } const btVector3& btHeightfieldTerrainShape::getLocalScaling() const { return m_localScaling; } namespace { struct GridRaycastState { int x; // Next quad coords int z; int prev_x; // Previous quad coords int prev_z; btScalar param; // Exit param for previous quad btScalar prevParam; // Enter param for previous quad btScalar maxDistanceFlat; btScalar maxDistance3d; }; } // TODO Does it really need to take 3D vectors? /// Iterates through a virtual 2D grid of unit-sized square cells, /// and executes an action on each cell intersecting the given segment, ordered from begin to end. /// Initially inspired by http://www.cse.yorku.ca/~amana/research/grid.pdf template <typename Action_T> void gridRaycast(Action_T& quadAction, const btVector3& beginPos, const btVector3& endPos, int indices[3]) { GridRaycastState rs; rs.maxDistance3d = beginPos.distance(endPos); if (rs.maxDistance3d < 0.0001) { // Consider the ray is too small to hit anything return; } btScalar rayDirectionFlatX = endPos[indices[0]] - beginPos[indices[0]]; btScalar rayDirectionFlatZ = endPos[indices[2]] - beginPos[indices[2]]; rs.maxDistanceFlat = btSqrt(rayDirectionFlatX * rayDirectionFlatX + rayDirectionFlatZ * rayDirectionFlatZ); if (rs.maxDistanceFlat < 0.0001) { // Consider the ray vertical rayDirectionFlatX = 0; rayDirectionFlatZ = 0; } else { rayDirectionFlatX /= rs.maxDistanceFlat; rayDirectionFlatZ /= rs.maxDistanceFlat; } const int xiStep = rayDirectionFlatX > 0 ? 1 : rayDirectionFlatX < 0 ? -1 : 0; const int ziStep = rayDirectionFlatZ > 0 ? 1 : rayDirectionFlatZ < 0 ? -1 : 0; const float infinite = 9999999; const btScalar paramDeltaX = xiStep != 0 ? 1.f / btFabs(rayDirectionFlatX) : infinite; const btScalar paramDeltaZ = ziStep != 0 ? 1.f / btFabs(rayDirectionFlatZ) : infinite; // pos = param * dir btScalar paramCrossX; // At which value of `param` we will cross a x-axis lane? btScalar paramCrossZ; // At which value of `param` we will cross a z-axis lane? // paramCrossX and paramCrossZ are initialized as being the first cross // X initialization if (xiStep != 0) { if (xiStep == 1) { paramCrossX = (ceil(beginPos[indices[0]]) - beginPos[indices[0]]) * paramDeltaX; } else { paramCrossX = (beginPos[indices[0]] - floor(beginPos[indices[0]])) * paramDeltaX; } } else { paramCrossX = infinite; // Will never cross on X } // Z initialization if (ziStep != 0) { if (ziStep == 1) { paramCrossZ = (ceil(beginPos[indices[2]]) - beginPos[indices[2]]) * paramDeltaZ; } else { paramCrossZ = (beginPos[indices[2]] - floor(beginPos[indices[2]])) * paramDeltaZ; } } else { paramCrossZ = infinite; // Will never cross on Z } rs.x = static_cast<int>(floor(beginPos[indices[0]])); rs.z = static_cast<int>(floor(beginPos[indices[2]])); // Workaround cases where the ray starts at an integer position if (paramCrossX == 0.0) { paramCrossX += paramDeltaX; // If going backwards, we should ignore the position we would get by the above flooring, // because the ray is not heading in that direction if (xiStep == -1) { rs.x -= 1; } } if (paramCrossZ == 0.0) { paramCrossZ += paramDeltaZ; if (ziStep == -1) rs.z -= 1; } rs.prev_x = rs.x; rs.prev_z = rs.z; rs.param = 0; while (true) { rs.prev_x = rs.x; rs.prev_z = rs.z; rs.prevParam = rs.param; if (paramCrossX < paramCrossZ) { // X lane rs.x += xiStep; // Assign before advancing the param, // to be in sync with the initialization step rs.param = paramCrossX; paramCrossX += paramDeltaX; } else { // Z lane rs.z += ziStep; rs.param = paramCrossZ; paramCrossZ += paramDeltaZ; } if (rs.param > rs.maxDistanceFlat) { rs.param = rs.maxDistanceFlat; quadAction(rs); break; } else { quadAction(rs); } } } struct ProcessTrianglesAction { const btHeightfieldTerrainShape* shape; bool flipQuadEdges; bool useDiamondSubdivision; int width; int length; btTriangleCallback* callback; void exec(int x, int z) const { if (x < 0 || z < 0 || x >= width || z >= length) { return; } btVector3 vertices[3]; // TODO Since this is for raycasts, we could greatly benefit from an early exit on the first hit // Check quad if (flipQuadEdges || (useDiamondSubdivision && (((z + x) & 1) > 0))) { // First triangle shape->getVertex(x, z, vertices[0]); shape->getVertex(x + 1, z, vertices[1]); shape->getVertex(x + 1, z + 1, vertices[2]); callback->processTriangle(vertices, x, z); // Second triangle shape->getVertex(x, z, vertices[0]); shape->getVertex(x + 1, z + 1, vertices[1]); shape->getVertex(x, z + 1, vertices[2]); callback->processTriangle(vertices, x, z); } else { // First triangle shape->getVertex(x, z, vertices[0]); shape->getVertex(x, z + 1, vertices[1]); shape->getVertex(x + 1, z, vertices[2]); callback->processTriangle(vertices, x, z); // Second triangle shape->getVertex(x + 1, z, vertices[0]); shape->getVertex(x, z + 1, vertices[1]); shape->getVertex(x + 1, z + 1, vertices[2]); callback->processTriangle(vertices, x, z); } } void operator()(const GridRaycastState& bs) const { exec(bs.prev_x, bs.prev_z); } }; struct ProcessVBoundsAction { const btAlignedObjectArray<btHeightfieldTerrainShape::Range>& vbounds; int width; int length; int chunkSize; btVector3 rayBegin; btVector3 rayEnd; btVector3 rayDir; int* m_indices; ProcessTrianglesAction processTriangles; ProcessVBoundsAction(const btAlignedObjectArray<btHeightfieldTerrainShape::Range>& bnd, int* indices) : vbounds(bnd), m_indices(indices) { } void operator()(const GridRaycastState& rs) const { int x = rs.prev_x; int z = rs.prev_z; if (x < 0 || z < 0 || x >= width || z >= length) { return; } const btHeightfieldTerrainShape::Range chunk = vbounds[x + z * width]; btVector3 enterPos; btVector3 exitPos; if (rs.maxDistanceFlat > 0.0001) { btScalar flatTo3d = chunkSize * rs.maxDistance3d / rs.maxDistanceFlat; btScalar enterParam3d = rs.prevParam * flatTo3d; btScalar exitParam3d = rs.param * flatTo3d; enterPos = rayBegin + rayDir * enterParam3d; exitPos = rayBegin + rayDir * exitParam3d; // We did enter the flat projection of the AABB, // but we have to check if we intersect it on the vertical axis if (enterPos[1] > chunk.max && exitPos[m_indices[1]] > chunk.max) { return; } if (enterPos[1] < chunk.min && exitPos[m_indices[1]] < chunk.min) { return; } } else { // Consider the ray vertical // (though we shouldn't reach this often because there is an early check up-front) enterPos = rayBegin; exitPos = rayEnd; } gridRaycast(processTriangles, enterPos, exitPos, m_indices); // Note: it could be possible to have more than one grid at different levels, // to do this there would be a branch using a pointer to another ProcessVBoundsAction } }; // TODO How do I interrupt the ray when there is a hit? `callback` does not return any result /// Performs a raycast using a hierarchical Bresenham algorithm. /// Does not allocate any memory by itself. void btHeightfieldTerrainShape::performRaycast(btTriangleCallback* callback, const btVector3& raySource, const btVector3& rayTarget) const { // Transform to cell-local btVector3 beginPos = raySource / m_localScaling; btVector3 endPos = rayTarget / m_localScaling; beginPos += m_localOrigin; endPos += m_localOrigin; ProcessTrianglesAction processTriangles; processTriangles.shape = this; processTriangles.flipQuadEdges = m_flipQuadEdges; processTriangles.useDiamondSubdivision = m_useDiamondSubdivision; processTriangles.callback = callback; processTriangles.width = m_heightStickWidth - 1; processTriangles.length = m_heightStickLength - 1; // TODO Transform vectors to account for m_upAxis int indices[3] = { 0, 1, 2 }; if (m_upAxis == 2) { indices[1] = 2; indices[2] = 1; } int iBeginX = static_cast<int>(floor(beginPos[indices[0]])); int iBeginZ = static_cast<int>(floor(beginPos[indices[2]])); int iEndX = static_cast<int>(floor(endPos[indices[0]])); int iEndZ = static_cast<int>(floor(endPos[indices[2]])); if (iBeginX == iEndX && iBeginZ == iEndZ) { // The ray will never cross quads within the plane, // so directly process triangles within one quad // (typically, vertical rays should end up here) processTriangles.exec(iBeginX, iEndZ); return; } if (m_vboundsGrid.size()==0) { // Process all quads intersecting the flat projection of the ray gridRaycast(processTriangles, beginPos, endPos, &indices[0]); } else { btVector3 rayDiff = endPos - beginPos; btScalar flatDistance2 = rayDiff[indices[0]] * rayDiff[indices[0]] + rayDiff[indices[2]] * rayDiff[indices[2]]; if (flatDistance2 < m_vboundsChunkSize * m_vboundsChunkSize) { // Don't use chunks, the ray is too short in the plane gridRaycast(processTriangles, beginPos, endPos, &indices[0]); } ProcessVBoundsAction processVBounds(m_vboundsGrid, &indices[0]); processVBounds.width = m_vboundsGridWidth; processVBounds.length = m_vboundsGridLength; processVBounds.rayBegin = beginPos; processVBounds.rayEnd = endPos; processVBounds.rayDir = rayDiff.normalized(); processVBounds.processTriangles = processTriangles; processVBounds.chunkSize = m_vboundsChunkSize; // The ray is long, run raycast on a higher-level grid gridRaycast(processVBounds, beginPos / m_vboundsChunkSize, endPos / m_vboundsChunkSize, indices); } } /// Builds a grid data structure storing the min and max heights of the terrain in chunks. /// if chunkSize is zero, that accelerator is removed. /// If you modify the heights, you need to rebuild this accelerator. void btHeightfieldTerrainShape::buildAccelerator(int chunkSize) { if (chunkSize <= 0) { clearAccelerator(); return; } m_vboundsChunkSize = chunkSize; int nChunksX = m_heightStickWidth / chunkSize; int nChunksZ = m_heightStickLength / chunkSize; if (m_heightStickWidth % chunkSize > 0) { ++nChunksX; // In case terrain size isn't dividable by chunk size } if (m_heightStickLength % chunkSize > 0) { ++nChunksZ; } if (m_vboundsGridWidth != nChunksX || m_vboundsGridLength != nChunksZ) { clearAccelerator(); m_vboundsGridWidth = nChunksX; m_vboundsGridLength = nChunksZ; } if (nChunksX == 0 || nChunksZ == 0) { return; } // This data structure is only reallocated if the required size changed m_vboundsGrid.resize(nChunksX * nChunksZ); // Compute min and max height for all chunks for (int cz = 0; cz < nChunksZ; ++cz) { int z0 = cz * chunkSize; for (int cx = 0; cx < nChunksX; ++cx) { int x0 = cx * chunkSize; Range r; r.min = getRawHeightFieldValue(x0, z0); r.max = r.min; // Compute min and max height for this chunk. // We have to include one extra cell to account for neighbors. // Here is why: // Say we have a flat terrain, and a plateau that fits a chunk perfectly. // // Left Right // 0---0---0---1---1---1 // | | | | | | // 0---0---0---1---1---1 // | | | | | | // 0---0---0---1---1---1 // x // // If the AABB for the Left chunk did not share vertices with the Right, // then we would fail collision tests at x due to a gap. // for (int z = z0; z < z0 + chunkSize + 1; ++z) { if (z >= m_heightStickLength) { continue; } for (int x = x0; x < x0 + chunkSize + 1; ++x) { if (x >= m_heightStickWidth) { continue; } btScalar height = getRawHeightFieldValue(x, z); if (height < r.min) { r.min = height; } else if (height > r.max) { r.max = height; } } } m_vboundsGrid[cx + cz * nChunksX] = r; } } } void btHeightfieldTerrainShape::clearAccelerator() { m_vboundsGrid.clear(); }
0
0.981342
1
0.981342
game-dev
MEDIA
0.985897
game-dev
0.996622
1
0.996622
deepnight/ld40-catsAreAssholes
18,303
src/en/Cat.hx
package en; import hxd.Key; import en.inter.FoodTray; enum Job { Wait; Follow(e:Entity); Fight(e:Entity, ?reason:String); Lick; Eat(e:en.inter.FoodTray, ?done:Bool); EatHero(e:en.Hero); Shit; Vomit(frames:Float); Play(e:Entity); } class Cat extends Entity { public static var ALL : Array<Cat> = []; public var catIdx : Int; var skin : String; var job : Job; var jobDurationS = 0.; var ang = 0.; var dashAng = 0.; var shitStock = 0; var target : Null<CPoint>; var path : Null< Array<{ x:Int, y:Int }> >; var pathEnd : Null<{ x:Int, y:Int }>; var rebootF = 0.; public function new(x,y) { super(x,y); catIdx = game.catIdx++; ALL.push(this); path = null; radius = Const.GRID*0.4; enableShadow(1.6); skin = ALL.length%3==0 ? "wcat" : ALL.length%3==1 ? "bcat" : "ncat"; spr.anim.registerStateAnim(skin+"FearJump",21, function() return altitude>1 && cd.has("fear")); spr.anim.registerStateAnim(skin+"Fear",20, function() return cd.has("fear")); spr.anim.registerStateAnim(skin+"Vomit",10, 0.2, function() return cd.has("vomiting")); spr.anim.registerStateAnim(skin+"Shit",10, 0.2, function() return cd.has("shitting")); spr.anim.registerStateAnim(skin+"Dash",11, 0.2, function() return cd.has("dashing")); spr.anim.registerStateAnim(skin+"Charge",10, 0.2, function() return cd.has("dashCharge")); spr.anim.registerStateAnim(skin+"Eat",10, 0.2, function() return cd.has("eating")); spr.anim.registerStateAnim(skin+"LickLookBack",12, function() return atTarget() && job==Lick && cd.has("stareBack")); spr.anim.registerStateAnim(skin+"LickLook",11, function() return atTarget() && job==Lick && cd.has("stare")); spr.anim.registerStateAnim(skin+"Lick",10, 0.15, function() return atTarget() && job==Lick); spr.anim.registerStateAnim(skin+"AngryWalk",4, 0.25, function() return isAngry() && ( M.fabs(dx)>0 || M.fabs(dy)>0 ) ); spr.anim.registerStateAnim(skin+"Walk",3, 0.2, function() return M.fabs(dx)>0 || M.fabs(dy)>0 ); spr.anim.registerStateAnim(skin+"Fall",15, function() return altitude>=3); spr.anim.registerStateAnim(skin+"Observe",2, 0.5, function() return cd.has("observing")); spr.anim.registerStateAnim(skin+"IdleRecent",1, function() return cd.has("recentWalk")); spr.anim.registerStateAnim(skin+"IdleAngry",0, function() return isAngry()); spr.anim.registerStateAnim(skin+"Idle",0, function() return !isAngry()); spr.colorMatrix = dn.Color.getColorizeMatrixH2d( dn.Color.makeColorHsl(rnd(0,1), 0.5, 1), rnd(0,0.3)); shitStock = irnd(0,2); startWait(); cd.setS("love", rnd(15,40)); } override public function dispose() { super.dispose(); ALL.remove(this); } override function hasCircCollWith(e:Entity) { if( e.destroyed ) return false; if( isOnJob(Vomit(0)) ) return false; if( !e.is(Cat) || cd.has("dashing") || e.cd.has("dashing") ) return true; return M.radDistance(getMoveAng(), e.getMoveAng())<=0.7; } function get_pathEnd() { if( path==null ) return null; else return path[path.length-1]; } inline function atTarget() { return target==null || cx==target.cx && cy==target.cy; } function startRandom() { rebootF = 0; var rlist = new dn.RandList(); rlist.add( startShit, 5*shitStock ); rlist.add( startVomit, Std.int(shitStock * (catIdx==4 ? 3 : 0.5 )) ); rlist.add( startEat, 17-4*shitStock ); rlist.add( startHeroFollow, 2 ); rlist.add( startLick, 4 ); rlist.add( startPlay, 5 ); rlist.add( startWait.bind(), 2 ); rlist.add( startCatAttack.bind(), 2 ); if( !rlist.draw()() ) startWait(1); } function startJob(j:Job, d:Float) { stop(); job = j; jobDurationS = d; } public function startEat() { var e = FoodTray.pickOne(); startJob( Eat(e), rnd(5,8) ); return true; } function startEatHero() { startJob( EatHero(game.hero), 99999 ); return true; } public function startCatAttack(?e:Cat) { if( cd.hasSetS("atkLimit", 15) ) return false; if( e!=null ) { startJob( Fight(e), rnd(5,6) ); return true; } else { var dh = new DecisionHelper(ALL); dh.remove( function(e) return e==this || e.destroyed ); dh.score( function(e) return sightCheck(e) ? 5 : 0 ); dh.score( function(e) return -distCase(e) ); var e = dh.getBest(); if( e!=null ) { startJob( Fight(e), rnd(8,12) ); jump(1); cd.setS("lock", 1); return true; } else return false; } } function startHeroAttack(r:String) { emote(r, 6); lookAt(game.hero); startJob( Fight(hero,r), 999 ); cd.setS("lock", rnd(2.5,3.5)); return true; } public function startPlay() { var targets = Entity.ALL.filter( function(e) return e.is(en.inter.ItemDrop) || e.is(Furn) ); var e = targets[Std.random(targets.length)]; startJob(Play(e), rnd(5,7)); return true; } function startWait(?t:Float) { clearEmote(); var dh = new DecisionHelper( dn.Bresenham.getDisc(cx,cy, 2) ); dh.remove( function(pt) return level.hasColl(pt.x, pt.y) ); dh.score( function(pt) return -M.dist(cx,cy,pt.x,pt.y) ); dh.score( function(pt) return Entity.countNearby(pt.x,pt.y, 1)==0 ? 3 : 0 ); var pt = dh.getBest(); if( pt!=null ) goto(pt.x, pt.y); startJob( Wait, t!=null ? t : rnd(2,5) ); return true; } public function startHeroFollow() { startJob( Follow(hero), rnd(7,10) ); return true; } function startLick() { var dh = new DecisionHelper( dn.Bresenham.getDisc(cx,cy, 6) ); dh.remove( function(pt) return level.hasColl(pt.x, pt.y) ); dh.score( function(pt) return M.dist(cx,cy,pt.x,pt.y) ); dh.score( function(pt) return sightCheckCase(pt.x,pt.y) ? 0 : -3 ); dh.score( function(pt) return M.dist(cx,cy, pt.x,pt.y)<=3 ? -1 : 0 ); dh.score( function(pt) return Entity.countNearby(pt.x,pt.y, 2)==0 ? 3 : 0 ); var pt = dh.getBest(); startJob( Lick, rnd(3,8) ); goto(pt.x, pt.y); return true; } public function startShit() { if( shitStock<=0 ) return false; var all = en.inter.Litter.ALL.filter( function(e) return !e.isFull() ); //var all = en.inter.Litter.ALL.filter( function(e) return !sightCheck(e) || !e.isFull() ); if( all.length!=0 ) { var e = all[Std.random(all.length)]; startJob(Shit, rnd(1.5,2)); goto(e.cx, e.cy); return true; } else { // Shit on the ground var dh = new DecisionHelper( dn.Bresenham.getDisc(cx,cy, 8) ); dh.remove( function(pt) return level.hasColl(pt.x, pt.y) ); dh.score( function(pt) return M.dist(cx,cy,pt.x,pt.y) ); dh.score( function(pt) return sightCheckCase(pt.x,pt.y) ? 0 : -3 ); dh.score( function(pt) return M.dist(cx,cy, pt.x,pt.y)<=3 ? -1 : 0 ); dh.score( function(pt) return rnd(0,2) ); dh.score( function(pt) return Entity.countNearby(this, pt.x,pt.y, 2)==0 ? 3 : 0 ); var pt = dh.getBest(); startJob( Shit, rnd(1.5,2.5) ); goto(pt.x, pt.y); return true; } } public function startVomit() { if( shitStock<=0 ) return false; var dh = new DecisionHelper( dn.Bresenham.getDisc(cx,cy, 4) ); dh.remove( function(pt) return level.hasColl(pt.x, pt.y) ); dh.score( function(pt) return M.dist(cx,cy,pt.x,pt.y) ); dh.score( function(pt) return sightCheckCase(pt.x,pt.y) ? 0 : -3 ); dh.score( function(pt) return M.dist(cx,cy, pt.x,pt.y)<=2 ? -1 : 0 ); dh.score( function(pt) return rnd(0,1) ); dh.score( function(pt) return Entity.countNearby(this, pt.x,pt.y, 2)==0 ? 3 : 0 ); var pt = dh.getBest(); startJob( Vomit(0.5*Const.FPS), rnd(1.5,2.5) ); goto(pt.x, pt.y); return true; } public function flee(e:Entity) { var dh = new DecisionHelper( dn.Bresenham.getDisc(cx,cy, 10) ); dh.remove( function(pt) return level.hasColl(pt.x, pt.y) ); dh.score( function(pt) return M.dist(e.cx,e.cy,pt.x,pt.y) ); dh.score( function(pt) return !e.sightCheckCase(pt.x,pt.y) ? 2 : 0 ); dh.score( function(pt) return rnd(0,1) ); cd.setS("fleeing", 2); var pt = dh.getBest(); startJob( Lick, rnd(5,6) ); goto(pt.x, pt.y); return true; } function onJobComplete() { switch( job ) { case Shit : var e = en.inter.Litter.ALL.filter( function(e) return distCase(e)<=1 && !e.isFull() )[0]; cd.unset("shitting"); jump(0.4); if( e!=null ) { // In box game.moneyMan.trigger(this, PoopLitter); e.addShit(shitStock); } else { var e = new en.inter.ItemDrop(Shit, cx,cy); e.xr = xr; e.yr = yr; e.dx = -dir*0.2; e.altitude = 3; e.dalt = 2; e.dy = -0.1; fx.dirt(footX, footY, 30, 0x691D18, 0x723510); } shitStock = 0; cd.setS("lock", rnd(1,2)); case Vomit(_) : cd.unset("vomiting"); default : } startRandom(); } function stop() { path = null; target = null; } function goto(x,y) { setTarget(x,y); } function setTarget(x,y) { if( target==null ) target = new CPoint(x,y); else target.set(x,y); } function gotoNearby(e:Entity, minDist:Int, maxDist:Int) { var dh = new DecisionHelper( dn.Bresenham.getDisc(e.cx,e.cy, maxDist) ); dh.remove( function(pt) return level.hasColl(pt.x, pt.y) || !e.sightCheckCase(pt.x,pt.y) || M.dist(e.cx,e.cy,pt.x,pt.y)<=minDist ); dh.score( function(pt) return -M.dist(e.cx,e.cy,pt.x,pt.y) ); dh.score( function(pt) return rnd(0,2) ); var pt = dh.getBest(); if( pt!=null ) setTarget(pt.x, pt.y); else setTarget(e.cx,e.cy); } override function onTouch(e:Entity) { super.onTouch(e); switch( job ) { case Play(pe) : // Touch the entity he is playing with if( pe==e && e.onGround ) e.jump(rnd(0.6,1)); if( pe==e && !cd.hasSetS("playKick",0.4) ) { var a = Math.atan2(e.footY-footY, e.footX-footX) + rnd(0,0.3,true); var s = rnd(0.1,0.3); e.dx+=Math.cos(a)*s; e.dy+=Math.sin(a)*s; e.jump(rnd(0.3,0.5)); } default : } if( cd.has("dashing") && !e.cd.hasSetS("hit"+uid,1.5) ) { switch( job ) { case Fight(te) : if( te.is(Cat) && e.is(Cat) ) { Assets.SBANK.bleep0(0.4); Assets.SBANK.bleep1(1); var e : Cat = Std.downcast(e,Cat); e.flee(this); e.cd.setS("lock", rnd(1.2,1.6)); e.cd.setS("fear", e.cd.getS("lock")); e.jump(rnd(1,1.7)); game.moneyMan.trigger(this, FightCat); var a = Math.atan2(e.footY-footY, e.footX-footX); e.dx+=Math.cos(a)*0.3; e.dy+=Math.sin(a)*0.3; startWait(2); } default : } } } inline function isAngry() { return job!=null && job.getIndex()==Type.enumIndex(Fight(null)); } override public function postUpdate() { super.postUpdate(); if( isAngry() ) { //spr.x+=Math.cos(game.ftime*0.6)*1; spr.y+=Math.cos(game.ftime*0.6)*1; } } public inline function isOnJob(k:Job) { return job.getIndex() == k.getIndex(); } override public function update() { super.update(); if( !game.hasCinematic() ) { // Attack nanny when dead if( hero.isDead() && !isOnJob(EatHero(null)) ) startEatHero(); // Interrupt fight switch( job ) { case Fight(e,r) : switch( r ) { case "eReqFood" : for(e in en.inter.FoodTray.ALL) if( !e.isEmpty() && sightCheck(e) ) { clearEmote(); startEat(); break; } case "eReqShit" : for(e in en.inter.Litter.ALL) if( !e.isFull() && sightCheck(e) ) { clearEmote(); startWait(1); break; } } default : } // Job effects on paths switch( job ) { case Follow(e) : if( e.destroyed ) startRandom(); else { if( distCase(e)<=2 && sightCheck(e) ) { if( !cd.hasSetS("love",rnd(25,50)) ) { game.moneyMan.trigger(this, Love); emote("eLove", 1); } stop(); } else gotoNearby(e,1,3); } case Fight(e,r) : if( r!=null && distCase(e)<=6 ) emote(r, 2); if( e.destroyed ) startRandom(); else if( !cd.has("dashLock") && distCase(e)<=4 && sightCheck(e) ) { dashAng = Math.atan2(e.footY-footY, e.footX-footX); dx+=Math.cos(dashAng)*0.2; dy+=Math.sin(dashAng)*0.2; dir = dx>0 ? 1 : -1; cd.setS("dashLock", rnd(1.6,2)); cd.setS("lock", rnd(1.5,3.5)); cd.setS("dashCharge", 0.3, function() { cd.setS("dashing", 0.45); }); } else if( distCase(e)<=3 ) stop(); else goto(e.cx, e.cy); case Eat(e) : goto(e.cx,e.cy); case EatHero(e) : gotoNearby(e,0,1); case Play(e) : if( e.destroyed ) startWait(1); else { if( cd.has("observing") ) lookAt(e); if( distCase(e)>3 ) gotoNearby(e,1,2); else if( !cd.has("observeLock") ) { cd.setS("lock",1); cd.setS("observing", 1); cd.setS("observeLock", rnd(2,4)); lookAt(e); } else if( atTarget() ) { if( !cd.hasSetS("playDash",0.3) ) { var a = angTo(e); dx+=Math.cos(a)*0.2; dy+=Math.sin(a)*0.2; } gotoNearby(e, 2,3); } else goto(e.cx,e.cy); } case Wait : case Shit : case Vomit(_) : case Lick : } var spd = ( isAngry() || cd.has("fleeing") ? 0.05 : 0.03 ) * dt; // Dash movement if( cd.has("dashing") ) { rebootF = 0; switch( job ) { case Fight(e) : dashAng += M.radSubstract(Math.atan2(e.footY-footY, e.footX-footX), dashAng)*0.04; default : } dx+=Math.cos(dashAng)*0.08*dt; dy+=Math.sin(dashAng)*0.08*dt; } #if debug if( Console.ME.has("path") ) { if( target!=null ) fx.markerCase(target.cx,target.cy,0x0080FF,true); if( path!=null ) for(pt in path) fx.markerCase(pt.x,pt.y,true); } #end if( !cd.has("lock") && onGround ) { rebootF = 0; // Track target if( !atTarget() && target!=null ) { if( sightCheckCase(target.cx,target.cy) && target.distEnt(this)<=5 ) { // Target is on sight if( path!=null ) path = null; var a = Math.atan2((target.cy+0.5)-(cy+yr), (target.cx+0.5)-(cx+xr)); dx += Math.cos(a)*spd; dy += Math.sin(a)*spd; dir = Math.cos(a)>=0.1 ? 1 : Math.cos(a)<=-0.1 ? -1 : dir; cd.setS("recentWalk", 1); cd.setS("pfLock", rnd(0.2,0.6)); } else { // Find path if( path==null && !cd.has("pfLock") ) path = level.pf.getPath( cx, cy, target.cx, target.cy ); // Follow path if( path!=null ) { if( path.length>0 ) { var next = path[0]; if( cx==next.x && cy==next.y ) { path.shift(); next = path[0]; cd.setS("stareLock", rnd(0.5,1), true); } if( next!=null && ( cx!=next.x || cy!=next.y ) ) { var a = Math.atan2((next.y+0.5)-(cy+yr), (next.x+0.5)-(cx+xr)) + rnd(0,0.2,true); dx += Math.cos(a)*spd; dy += Math.sin(a)*spd; dir = Math.cos(a)>=0.1 ? 1 : Math.cos(a)<=-0.1 ? -1 : dir; cd.setS("recentWalk", 1); } } if( !atTarget() && path.length==0 ) path = null; } } } // Job update var doingIt = switch( job ) { case Follow(e) : distCase(e)<=6; case Lick : atTarget(); case Wait : atTarget(); case Shit : atTarget(); case Vomit(_) : atTarget(); case Eat(e, _) : distCase(e)<=1.8; case EatHero(e) : distCase(e)<=2; case Fight(e) : distCase(e)<=1; case Play(e) : distCase(e)<=5 && sightCheck(e); } if( doingIt ) { // Job effect when doing them switch( job ) { case Eat(e,done) : if( !done ) { if( e.eat() ) { shitStock++; job = Eat(e,true); cd.setS("eating",0.1); } else { if( en.inter.FoodTray.ALL.filter(function(e) return !e.isEmpty()).length==0 ) startHeroAttack("eReqFood"); else startEat(); } } if( cd.has("eating") ) { cd.setS("eating",0.3); e.cd.setS("eating",0.3); lookAt(e); } case EatHero(e) : stop(); cd.setS("eating",0.1); if( !cd.hasSetS("eatBumped",rnd(0.2,0.6)) ) { var a = angTo(e); dx-=Math.cos(a)*rnd(0,0.4); dy-=Math.sin(a)*rnd(0,0.4); } lookAt(e); case Fight(e) : case Follow(_) : case Wait : case Lick : game.moneyMan.trigger(this, Lick); case Play(_) : case Shit : cd.setS("shitting", 0.3); case Vomit(frames) : cd.setS("vomiting", 0.3); frames-=dt; if( frames<=0 ) { shitStock = 0; Assets.SBANK.error0(0.35); var e = new en.inter.ItemDrop(Vomit, cx,cy); e.hasColl = false; e.xr = xr+dir*0.45; e.skew = 1; e.yr = yr+0.4; e.dx = dir*0.05; e.dy = 0; e.altitude = 5; e.dalt = 0; fx.dirt(footX, footY, 10, 0x415A27, 0x2C9A34); frames = 99999; } job = Vomit(frames); } jobDurationS-=1/Const.FPS; if( !cd.has("stareLock") ) { cd.setS("stare", rnd(0.5,0.7)); if( Std.random(2)==0 ) cd.setS("stareBack", cd.getS("stare")); cd.setS("stareLock", rnd(2,4)); } if( jobDurationS<=0 ) onJobComplete(); } #if debug if( Console.ME.has("job") ) setLabel(job+"("+doingIt+") "+pretty(jobDurationS)+"s"); #end } else { #if debug if( Console.ME.has("job") ) setLabel("lock="+pretty(cd.getS("lock"))+"s onGround="+onGround+" alt="+altitude+" dalt="+dalt); #end rebootF+=dt; if( rebootF>=Const.FPS*5 ) { #if debug trace("Rebooted "+this); #end altitude = 0; dalt = 0; startRandom(); } } // Dash hit if( cd.has("dashing") && distCase(hero)<=1 && !hero.cd.hasSetS("hit",1) ) { hero.hit(this, 1); } } if( !cd.hasSetS("meow",rnd(3,8)) ) { var all = [ Assets.SBANK.kat0, Assets.SBANK.kat1, Assets.SBANK.kat2, Assets.SBANK.kat3, Assets.SBANK.kat4, Assets.SBANK.kat5, Assets.SBANK.kat6, Assets.SBANK.kat7, Assets.SBANK.kat8, ]; //var all = [ //Assets.SBANK.cat0, //Assets.SBANK.cat1, //Assets.SBANK.cat2, //Assets.SBANK.cat3, //Assets.SBANK.cat4, //]; var s = all[Std.random(all.length)](); s.play( (sightCheck(hero)?1:0.4) * ( 0.1 + 0.5 * M.fclamp(1-distCase(hero)/10,0,1) ) ); } } }
0
0.586536
1
0.586536
game-dev
MEDIA
0.434364
game-dev,testing-qa
0.898105
1
0.898105
OxideWaveLength/Minecraft-Hack-BaseClient
39,807
minecraft/net/minecraft/entity/player/EntityPlayerMP.java
package net.minecraft.entity.player; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Set; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.mojang.authlib.GameProfile; import io.netty.buffer.Unpooled; import net.minecraft.block.Block; import net.minecraft.block.BlockFence; import net.minecraft.block.BlockFenceGate; import net.minecraft.block.BlockWall; import net.minecraft.block.material.Material; import net.minecraft.crash.CrashReport; import net.minecraft.crash.CrashReportCategory; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityList; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.IMerchant; import net.minecraft.entity.passive.EntityHorse; import net.minecraft.entity.projectile.EntityArrow; import net.minecraft.init.Items; import net.minecraft.inventory.Container; import net.minecraft.inventory.ContainerChest; import net.minecraft.inventory.ContainerHorseInventory; import net.minecraft.inventory.ContainerMerchant; import net.minecraft.inventory.ICrafting; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.SlotCrafting; import net.minecraft.item.EnumAction; import net.minecraft.item.Item; import net.minecraft.item.ItemMapBase; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.NetHandlerPlayServer; import net.minecraft.network.Packet; import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.client.C15PacketClientSettings; import net.minecraft.network.play.server.S02PacketChat; import net.minecraft.network.play.server.S06PacketUpdateHealth; import net.minecraft.network.play.server.S0APacketUseBed; import net.minecraft.network.play.server.S0BPacketAnimation; import net.minecraft.network.play.server.S13PacketDestroyEntities; import net.minecraft.network.play.server.S19PacketEntityStatus; import net.minecraft.network.play.server.S1BPacketEntityAttach; import net.minecraft.network.play.server.S1DPacketEntityEffect; import net.minecraft.network.play.server.S1EPacketRemoveEntityEffect; import net.minecraft.network.play.server.S1FPacketSetExperience; import net.minecraft.network.play.server.S21PacketChunkData; import net.minecraft.network.play.server.S26PacketMapChunkBulk; import net.minecraft.network.play.server.S29PacketSoundEffect; import net.minecraft.network.play.server.S2BPacketChangeGameState; import net.minecraft.network.play.server.S2DPacketOpenWindow; import net.minecraft.network.play.server.S2EPacketCloseWindow; import net.minecraft.network.play.server.S2FPacketSetSlot; import net.minecraft.network.play.server.S30PacketWindowItems; import net.minecraft.network.play.server.S31PacketWindowProperty; import net.minecraft.network.play.server.S36PacketSignEditorOpen; import net.minecraft.network.play.server.S39PacketPlayerAbilities; import net.minecraft.network.play.server.S3FPacketCustomPayload; import net.minecraft.network.play.server.S42PacketCombatEvent; import net.minecraft.network.play.server.S43PacketCamera; import net.minecraft.network.play.server.S48PacketResourcePackSend; import net.minecraft.potion.PotionEffect; import net.minecraft.scoreboard.IScoreObjectiveCriteria; import net.minecraft.scoreboard.Score; import net.minecraft.scoreboard.ScoreObjective; import net.minecraft.scoreboard.Team; import net.minecraft.server.MinecraftServer; import net.minecraft.server.management.ItemInWorldManager; import net.minecraft.server.management.UserListOpsEntry; import net.minecraft.stats.AchievementList; import net.minecraft.stats.StatBase; import net.minecraft.stats.StatList; import net.minecraft.stats.StatisticsFile; import net.minecraft.tileentity.TileEntity; import net.minecraft.tileentity.TileEntitySign; import net.minecraft.util.BlockPos; import net.minecraft.util.ChatComponentTranslation; import net.minecraft.util.DamageSource; import net.minecraft.util.EntityDamageSource; import net.minecraft.util.IChatComponent; import net.minecraft.util.JsonSerializableSet; import net.minecraft.util.MathHelper; import net.minecraft.util.ReportedException; import net.minecraft.village.MerchantRecipeList; import net.minecraft.world.ChunkCoordIntPair; import net.minecraft.world.IInteractionObject; import net.minecraft.world.ILockableContainer; import net.minecraft.world.WorldServer; import net.minecraft.world.WorldSettings; import net.minecraft.world.biome.BiomeGenBase; import net.minecraft.world.chunk.Chunk; public class EntityPlayerMP extends EntityPlayer implements ICrafting { private static final Logger logger = LogManager.getLogger(); private String translator = "en_US"; /** * The NetServerHandler assigned to this player by the * ServerConfigurationManager. */ public NetHandlerPlayServer playerNetServerHandler; /** Reference to the MinecraftServer object. */ public final MinecraftServer mcServer; /** The ItemInWorldManager belonging to this player */ public final ItemInWorldManager theItemInWorldManager; /** player X position as seen by PlayerManager */ public double managedPosX; /** player Z position as seen by PlayerManager */ public double managedPosZ; public final List<ChunkCoordIntPair> loadedChunks = Lists.<ChunkCoordIntPair>newLinkedList(); private final List<Integer> destroyedItemsNetCache = Lists.<Integer>newLinkedList(); private final StatisticsFile statsFile; /** * the total health of the player, includes actual health and absorption health. * Updated every tick. */ private float combinedHealth = Float.MIN_VALUE; /** amount of health the client was last set to */ private float lastHealth = -1.0E8F; /** set to foodStats.GetFoodLevel */ private int lastFoodLevel = -99999999; /** set to foodStats.getSaturationLevel() == 0.0F each tick */ private boolean wasHungry = true; /** Amount of experience the client was last set to */ private int lastExperience = -99999999; private int respawnInvulnerabilityTicks = 60; private EntityPlayer.EnumChatVisibility chatVisibility; private boolean chatColours = true; private long playerLastActiveTime = System.currentTimeMillis(); /** The entity the player is currently spectating through. */ private Entity spectatingEntity = null; /** * The currently in use window ID. Incremented every time a window is opened. */ private int currentWindowId; /** * set to true when player is moving quantity of items from one inventory to * another(crafting) but item in either slot is not changed */ public boolean isChangingQuantityOnly; public int ping; /** * Set when a player beats the ender dragon, used to respawn the player at the * spawn point while retaining inventory and XP */ public boolean playerConqueredTheEnd; public EntityPlayerMP(MinecraftServer server, WorldServer worldIn, GameProfile profile, ItemInWorldManager interactionManager) { super(worldIn, profile); interactionManager.thisPlayerMP = this; this.theItemInWorldManager = interactionManager; BlockPos blockpos = worldIn.getSpawnPoint(); if (!worldIn.provider.getHasNoSky() && worldIn.getWorldInfo().getGameType() != WorldSettings.GameType.ADVENTURE) { int i = Math.max(5, server.getSpawnProtectionSize() - 6); int j = MathHelper.floor_double(worldIn.getWorldBorder().getClosestDistance((double) blockpos.getX(), (double) blockpos.getZ())); if (j < i) { i = j; } if (j <= 1) { i = 1; } blockpos = worldIn.getTopSolidOrLiquidBlock(blockpos.add(this.rand.nextInt(i * 2) - i, 0, this.rand.nextInt(i * 2) - i)); } this.mcServer = server; this.statsFile = server.getConfigurationManager().getPlayerStatsFile(this); this.stepHeight = 0.0F; this.moveToBlockPosAndAngles(blockpos, 0.0F, 0.0F); while (!worldIn.getCollidingBoundingBoxes(this, this.getEntityBoundingBox()).isEmpty() && this.posY < 255.0D) { this.setPosition(this.posX, this.posY + 1.0D, this.posZ); } } /** * (abstract) Protected helper method to read subclass entity data from NBT. */ public void readEntityFromNBT(NBTTagCompound tagCompund) { super.readEntityFromNBT(tagCompund); if (tagCompund.hasKey("playerGameType", 99)) { if (MinecraftServer.getServer().getForceGamemode()) { this.theItemInWorldManager.setGameType(MinecraftServer.getServer().getGameType()); } else { this.theItemInWorldManager.setGameType(WorldSettings.GameType.getByID(tagCompund.getInteger("playerGameType"))); } } } /** * (abstract) Protected helper method to write subclass entity data to NBT. */ public void writeEntityToNBT(NBTTagCompound tagCompound) { super.writeEntityToNBT(tagCompound); tagCompound.setInteger("playerGameType", this.theItemInWorldManager.getGameType().getID()); } /** * Add experience levels to this player. */ public void addExperienceLevel(int levels) { super.addExperienceLevel(levels); this.lastExperience = -1; } public void removeExperienceLevel(int levels) { super.removeExperienceLevel(levels); this.lastExperience = -1; } public void addSelfToInternalCraftingInventory() { this.openContainer.onCraftGuiOpened(this); } /** * Sends an ENTER_COMBAT packet to the client */ public void sendEnterCombat() { super.sendEnterCombat(); this.playerNetServerHandler.sendPacket(new S42PacketCombatEvent(this.getCombatTracker(), S42PacketCombatEvent.Event.ENTER_COMBAT)); } /** * Sends an END_COMBAT packet to the client */ public void sendEndCombat() { super.sendEndCombat(); this.playerNetServerHandler.sendPacket(new S42PacketCombatEvent(this.getCombatTracker(), S42PacketCombatEvent.Event.END_COMBAT)); } /** * Called to update the entity's position/logic. */ public void onUpdate() { this.theItemInWorldManager.updateBlockRemoving(); --this.respawnInvulnerabilityTicks; if (this.hurtResistantTime > 0) { --this.hurtResistantTime; } this.openContainer.detectAndSendChanges(); if (!this.worldObj.isRemote && !this.openContainer.canInteractWith(this)) { this.closeScreen(); this.openContainer = this.inventoryContainer; } while (!this.destroyedItemsNetCache.isEmpty()) { int i = Math.min(this.destroyedItemsNetCache.size(), Integer.MAX_VALUE); int[] aint = new int[i]; Iterator<Integer> iterator = this.destroyedItemsNetCache.iterator(); int j = 0; while (iterator.hasNext() && j < i) { aint[j++] = ((Integer) iterator.next()).intValue(); iterator.remove(); } this.playerNetServerHandler.sendPacket(new S13PacketDestroyEntities(aint)); } if (!this.loadedChunks.isEmpty()) { List<Chunk> list = Lists.<Chunk>newArrayList(); Iterator<ChunkCoordIntPair> iterator1 = this.loadedChunks.iterator(); List<TileEntity> list1 = Lists.<TileEntity>newArrayList(); while (iterator1.hasNext() && ((List) list).size() < 10) { ChunkCoordIntPair chunkcoordintpair = (ChunkCoordIntPair) iterator1.next(); if (chunkcoordintpair != null) { if (this.worldObj.isBlockLoaded(new BlockPos(chunkcoordintpair.chunkXPos << 4, 0, chunkcoordintpair.chunkZPos << 4))) { Chunk chunk = this.worldObj.getChunkFromChunkCoords(chunkcoordintpair.chunkXPos, chunkcoordintpair.chunkZPos); if (chunk.isPopulated()) { list.add(chunk); list1.addAll(((WorldServer) this.worldObj).getTileEntitiesIn(chunkcoordintpair.chunkXPos * 16, 0, chunkcoordintpair.chunkZPos * 16, chunkcoordintpair.chunkXPos * 16 + 16, 256, chunkcoordintpair.chunkZPos * 16 + 16)); iterator1.remove(); } } } else { iterator1.remove(); } } if (!list.isEmpty()) { if (list.size() == 1) { this.playerNetServerHandler.sendPacket(new S21PacketChunkData((Chunk) list.get(0), true, 65535)); } else { this.playerNetServerHandler.sendPacket(new S26PacketMapChunkBulk(list)); } for (TileEntity tileentity : list1) { this.sendTileEntityUpdate(tileentity); } for (Chunk chunk1 : list) { this.getServerForPlayer().getEntityTracker().func_85172_a(this, chunk1); } } } Entity entity = this.getSpectatingEntity(); if (entity != this) { if (!entity.isEntityAlive()) { this.setSpectatingEntity(this); } else { this.setPositionAndRotation(entity.posX, entity.posY, entity.posZ, entity.rotationYaw, entity.rotationPitch); this.mcServer.getConfigurationManager().serverUpdateMountedMovingPlayer(this); if (this.isSneaking()) { this.setSpectatingEntity(this); } } } } public void onUpdateEntity() { try { super.onUpdate(); for (int i = 0; i < this.inventory.getSizeInventory(); ++i) { ItemStack itemstack = this.inventory.getStackInSlot(i); if (itemstack != null && itemstack.getItem().isMap()) { Packet packet = ((ItemMapBase) itemstack.getItem()).createMapDataPacket(itemstack, this.worldObj, this); if (packet != null) { this.playerNetServerHandler.sendPacket(packet); } } } if (this.getHealth() != this.lastHealth || this.lastFoodLevel != this.foodStats.getFoodLevel() || this.foodStats.getSaturationLevel() == 0.0F != this.wasHungry) { this.playerNetServerHandler.sendPacket(new S06PacketUpdateHealth(this.getHealth(), this.foodStats.getFoodLevel(), this.foodStats.getSaturationLevel())); this.lastHealth = this.getHealth(); this.lastFoodLevel = this.foodStats.getFoodLevel(); this.wasHungry = this.foodStats.getSaturationLevel() == 0.0F; } if (this.getHealth() + this.getAbsorptionAmount() != this.combinedHealth) { this.combinedHealth = this.getHealth() + this.getAbsorptionAmount(); for (ScoreObjective scoreobjective : this.getWorldScoreboard().getObjectivesFromCriteria(IScoreObjectiveCriteria.health)) { this.getWorldScoreboard().getValueFromObjective(this.getName(), scoreobjective).func_96651_a(Arrays.<EntityPlayer>asList(new EntityPlayer[] { this })); } } if (this.experienceTotal != this.lastExperience) { this.lastExperience = this.experienceTotal; this.playerNetServerHandler.sendPacket(new S1FPacketSetExperience(this.experience, this.experienceTotal, this.experienceLevel)); } if (this.ticksExisted % 20 * 5 == 0 && !this.getStatFile().hasAchievementUnlocked(AchievementList.exploreAllBiomes)) { this.updateBiomesExplored(); } } catch (Throwable throwable) { CrashReport crashreport = CrashReport.makeCrashReport(throwable, "Ticking player"); CrashReportCategory crashreportcategory = crashreport.makeCategory("Player being ticked"); this.addEntityCrashInfo(crashreportcategory); throw new ReportedException(crashreport); } } /** * Updates all biomes that have been explored by this player and triggers * Adventuring Time if player qualifies. */ protected void updateBiomesExplored() { BiomeGenBase biomegenbase = this.worldObj.getBiomeGenForCoords(new BlockPos(MathHelper.floor_double(this.posX), 0, MathHelper.floor_double(this.posZ))); String s = biomegenbase.biomeName; JsonSerializableSet jsonserializableset = (JsonSerializableSet) this.getStatFile().func_150870_b(AchievementList.exploreAllBiomes); if (jsonserializableset == null) { jsonserializableset = (JsonSerializableSet) this.getStatFile().func_150872_a(AchievementList.exploreAllBiomes, new JsonSerializableSet()); } jsonserializableset.add(s); if (this.getStatFile().canUnlockAchievement(AchievementList.exploreAllBiomes) && jsonserializableset.size() >= BiomeGenBase.explorationBiomesList.size()) { Set<BiomeGenBase> set = Sets.newHashSet(BiomeGenBase.explorationBiomesList); for (String s1 : jsonserializableset) { Iterator<BiomeGenBase> iterator = set.iterator(); while (iterator.hasNext()) { BiomeGenBase biomegenbase1 = (BiomeGenBase) iterator.next(); if (biomegenbase1.biomeName.equals(s1)) { iterator.remove(); } } if (set.isEmpty()) { break; } } if (set.isEmpty()) { this.triggerAchievement(AchievementList.exploreAllBiomes); } } } /** * Called when the mob's health reaches 0. */ public void onDeath(DamageSource cause) { if (this.worldObj.getGameRules().getBoolean("showDeathMessages")) { Team team = this.getTeam(); if (team != null && team.getDeathMessageVisibility() != Team.EnumVisible.ALWAYS) { if (team.getDeathMessageVisibility() == Team.EnumVisible.HIDE_FOR_OTHER_TEAMS) { this.mcServer.getConfigurationManager().sendMessageToAllTeamMembers(this, this.getCombatTracker().getDeathMessage()); } else if (team.getDeathMessageVisibility() == Team.EnumVisible.HIDE_FOR_OWN_TEAM) { this.mcServer.getConfigurationManager().sendMessageToTeamOrEvryPlayer(this, this.getCombatTracker().getDeathMessage()); } } else { this.mcServer.getConfigurationManager().sendChatMsg(this.getCombatTracker().getDeathMessage()); } } if (!this.worldObj.getGameRules().getBoolean("keepInventory")) { this.inventory.dropAllItems(); } for (ScoreObjective scoreobjective : this.worldObj.getScoreboard().getObjectivesFromCriteria(IScoreObjectiveCriteria.deathCount)) { Score score = this.getWorldScoreboard().getValueFromObjective(this.getName(), scoreobjective); score.func_96648_a(); } EntityLivingBase entitylivingbase = this.func_94060_bK(); if (entitylivingbase != null) { EntityList.EntityEggInfo entitylist$entityegginfo = (EntityList.EntityEggInfo) EntityList.entityEggs.get(Integer.valueOf(EntityList.getEntityID(entitylivingbase))); if (entitylist$entityegginfo != null) { this.triggerAchievement(entitylist$entityegginfo.field_151513_e); } entitylivingbase.addToPlayerScore(this, this.scoreValue); } this.triggerAchievement(StatList.deathsStat); this.func_175145_a(StatList.timeSinceDeathStat); this.getCombatTracker().reset(); } /** * Called when the entity is attacked. */ public boolean attackEntityFrom(DamageSource source, float amount) { if (this.isEntityInvulnerable(source)) { return false; } else { boolean flag = this.mcServer.isDedicatedServer() && this.canPlayersAttack() && "fall".equals(source.damageType); if (!flag && this.respawnInvulnerabilityTicks > 0 && source != DamageSource.outOfWorld) { return false; } else { if (source instanceof EntityDamageSource) { Entity entity = source.getEntity(); if (entity instanceof EntityPlayer && !this.canAttackPlayer((EntityPlayer) entity)) { return false; } if (entity instanceof EntityArrow) { EntityArrow entityarrow = (EntityArrow) entity; if (entityarrow.shootingEntity instanceof EntityPlayer && !this.canAttackPlayer((EntityPlayer) entityarrow.shootingEntity)) { return false; } } } return super.attackEntityFrom(source, amount); } } } public boolean canAttackPlayer(EntityPlayer other) { return !this.canPlayersAttack() ? false : super.canAttackPlayer(other); } /** * Returns if other players can attack this player */ private boolean canPlayersAttack() { return this.mcServer.isPVPEnabled(); } /** * Teleports the entity to another dimension. Params: Dimension number to * teleport to */ public void travelToDimension(int dimensionId) { if (this.dimension == 1 && dimensionId == 1) { this.triggerAchievement(AchievementList.theEnd2); this.worldObj.removeEntity(this); this.playerConqueredTheEnd = true; this.playerNetServerHandler.sendPacket(new S2BPacketChangeGameState(4, 0.0F)); } else { if (this.dimension == 0 && dimensionId == 1) { this.triggerAchievement(AchievementList.theEnd); BlockPos blockpos = this.mcServer.worldServerForDimension(dimensionId).getSpawnCoordinate(); if (blockpos != null) { this.playerNetServerHandler.setPlayerLocation((double) blockpos.getX(), (double) blockpos.getY(), (double) blockpos.getZ(), 0.0F, 0.0F); } dimensionId = 1; } else { this.triggerAchievement(AchievementList.portal); } this.mcServer.getConfigurationManager().transferPlayerToDimension(this, dimensionId); this.lastExperience = -1; this.lastHealth = -1.0F; this.lastFoodLevel = -1; } } public boolean isSpectatedByPlayer(EntityPlayerMP player) { return player.isSpectator() ? this.getSpectatingEntity() == this : (this.isSpectator() ? false : super.isSpectatedByPlayer(player)); } private void sendTileEntityUpdate(TileEntity p_147097_1_) { if (p_147097_1_ != null) { Packet packet = p_147097_1_.getDescriptionPacket(); if (packet != null) { this.playerNetServerHandler.sendPacket(packet); } } } /** * Called whenever an item is picked up from walking over it. Args: * pickedUpEntity, stackSize */ public void onItemPickup(Entity p_71001_1_, int p_71001_2_) { super.onItemPickup(p_71001_1_, p_71001_2_); this.openContainer.detectAndSendChanges(); } public EntityPlayer.EnumStatus trySleep(BlockPos bedLocation) { EntityPlayer.EnumStatus entityplayer$enumstatus = super.trySleep(bedLocation); if (entityplayer$enumstatus == EntityPlayer.EnumStatus.OK) { Packet packet = new S0APacketUseBed(this, bedLocation); this.getServerForPlayer().getEntityTracker().sendToAllTrackingEntity(this, packet); this.playerNetServerHandler.setPlayerLocation(this.posX, this.posY, this.posZ, this.rotationYaw, this.rotationPitch); this.playerNetServerHandler.sendPacket(packet); } return entityplayer$enumstatus; } /** * Wake up the player if they're sleeping. */ public void wakeUpPlayer(boolean p_70999_1_, boolean updateWorldFlag, boolean setSpawn) { if (this.isPlayerSleeping()) { this.getServerForPlayer().getEntityTracker().func_151248_b(this, new S0BPacketAnimation(this, 2)); } super.wakeUpPlayer(p_70999_1_, updateWorldFlag, setSpawn); if (this.playerNetServerHandler != null) { this.playerNetServerHandler.setPlayerLocation(this.posX, this.posY, this.posZ, this.rotationYaw, this.rotationPitch); } } /** * Called when a player mounts an entity. e.g. mounts a pig, mounts a boat. */ public void mountEntity(Entity entityIn) { Entity entity = this.ridingEntity; super.mountEntity(entityIn); if (entityIn != entity) { this.playerNetServerHandler.sendPacket(new S1BPacketEntityAttach(0, this, this.ridingEntity)); this.playerNetServerHandler.setPlayerLocation(this.posX, this.posY, this.posZ, this.rotationYaw, this.rotationPitch); } } protected void updateFallState(double y, boolean onGroundIn, Block blockIn, BlockPos pos) { } /** * process player falling based on movement packet */ public void handleFalling(double p_71122_1_, boolean p_71122_3_) { int i = MathHelper.floor_double(this.posX); int j = MathHelper.floor_double(this.posY - 0.20000000298023224D); int k = MathHelper.floor_double(this.posZ); BlockPos blockpos = new BlockPos(i, j, k); Block block = this.worldObj.getBlockState(blockpos).getBlock(); if (block.getMaterial() == Material.air) { Block block1 = this.worldObj.getBlockState(blockpos.down()).getBlock(); if (block1 instanceof BlockFence || block1 instanceof BlockWall || block1 instanceof BlockFenceGate) { blockpos = blockpos.down(); block = this.worldObj.getBlockState(blockpos).getBlock(); } } super.updateFallState(p_71122_1_, p_71122_3_, block, blockpos); } public void openEditSign(TileEntitySign signTile) { signTile.setPlayer(this); this.playerNetServerHandler.sendPacket(new S36PacketSignEditorOpen(signTile.getPos())); } /** * get the next window id to use */ private void getNextWindowId() { this.currentWindowId = this.currentWindowId % 100 + 1; } public void displayGui(IInteractionObject guiOwner) { this.getNextWindowId(); this.playerNetServerHandler.sendPacket(new S2DPacketOpenWindow(this.currentWindowId, guiOwner.getGuiID(), guiOwner.getDisplayName())); this.openContainer = guiOwner.createContainer(this.inventory, this); this.openContainer.windowId = this.currentWindowId; this.openContainer.onCraftGuiOpened(this); } /** * Displays the GUI for interacting with a chest inventory. Args: chestInventory */ public void displayGUIChest(IInventory chestInventory) { if (this.openContainer != this.inventoryContainer) { this.closeScreen(); } if (chestInventory instanceof ILockableContainer) { ILockableContainer ilockablecontainer = (ILockableContainer) chestInventory; if (ilockablecontainer.isLocked() && !this.canOpen(ilockablecontainer.getLockCode()) && !this.isSpectator()) { this.playerNetServerHandler.sendPacket(new S02PacketChat(new ChatComponentTranslation("container.isLocked", new Object[] { chestInventory.getDisplayName() }), (byte) 2)); this.playerNetServerHandler.sendPacket(new S29PacketSoundEffect("random.door_close", this.posX, this.posY, this.posZ, 1.0F, 1.0F)); return; } } this.getNextWindowId(); if (chestInventory instanceof IInteractionObject) { this.playerNetServerHandler.sendPacket(new S2DPacketOpenWindow(this.currentWindowId, ((IInteractionObject) chestInventory).getGuiID(), chestInventory.getDisplayName(), chestInventory.getSizeInventory())); this.openContainer = ((IInteractionObject) chestInventory).createContainer(this.inventory, this); } else { this.playerNetServerHandler.sendPacket(new S2DPacketOpenWindow(this.currentWindowId, "minecraft:container", chestInventory.getDisplayName(), chestInventory.getSizeInventory())); this.openContainer = new ContainerChest(this.inventory, chestInventory, this); } this.openContainer.windowId = this.currentWindowId; this.openContainer.onCraftGuiOpened(this); } public void displayVillagerTradeGui(IMerchant villager) { this.getNextWindowId(); this.openContainer = new ContainerMerchant(this.inventory, villager, this.worldObj); this.openContainer.windowId = this.currentWindowId; this.openContainer.onCraftGuiOpened(this); IInventory iinventory = ((ContainerMerchant) this.openContainer).getMerchantInventory(); IChatComponent ichatcomponent = villager.getDisplayName(); this.playerNetServerHandler.sendPacket(new S2DPacketOpenWindow(this.currentWindowId, "minecraft:villager", ichatcomponent, iinventory.getSizeInventory())); MerchantRecipeList merchantrecipelist = villager.getRecipes(this); if (merchantrecipelist != null) { PacketBuffer packetbuffer = new PacketBuffer(Unpooled.buffer()); packetbuffer.writeInt(this.currentWindowId); merchantrecipelist.writeToBuf(packetbuffer); this.playerNetServerHandler.sendPacket(new S3FPacketCustomPayload("MC|TrList", packetbuffer)); } } public void displayGUIHorse(EntityHorse horse, IInventory horseInventory) { if (this.openContainer != this.inventoryContainer) { this.closeScreen(); } this.getNextWindowId(); this.playerNetServerHandler.sendPacket(new S2DPacketOpenWindow(this.currentWindowId, "EntityHorse", horseInventory.getDisplayName(), horseInventory.getSizeInventory(), horse.getEntityId())); this.openContainer = new ContainerHorseInventory(this.inventory, horseInventory, horse, this); this.openContainer.windowId = this.currentWindowId; this.openContainer.onCraftGuiOpened(this); } /** * Displays the GUI for interacting with a book. */ public void displayGUIBook(ItemStack bookStack) { Item item = bookStack.getItem(); if (item == Items.written_book) { this.playerNetServerHandler.sendPacket(new S3FPacketCustomPayload("MC|BOpen", new PacketBuffer(Unpooled.buffer()))); } } /** * Sends the contents of an inventory slot to the client-side Container. This * doesn't have to match the actual contents of that slot. Args: Container, slot * number, slot contents */ public void sendSlotContents(Container containerToSend, int slotInd, ItemStack stack) { if (!(containerToSend.getSlot(slotInd) instanceof SlotCrafting)) { if (!this.isChangingQuantityOnly) { this.playerNetServerHandler.sendPacket(new S2FPacketSetSlot(containerToSend.windowId, slotInd, stack)); } } } public void sendContainerToPlayer(Container p_71120_1_) { this.updateCraftingInventory(p_71120_1_, p_71120_1_.getInventory()); } /** * update the crafting window inventory with the items in the list */ public void updateCraftingInventory(Container containerToSend, List<ItemStack> itemsList) { this.playerNetServerHandler.sendPacket(new S30PacketWindowItems(containerToSend.windowId, itemsList)); this.playerNetServerHandler.sendPacket(new S2FPacketSetSlot(-1, -1, this.inventory.getItemStack())); } /** * Sends two ints to the client-side Container. Used for furnace burning time, * smelting progress, brewing progress, and enchanting level. Normally the first * int identifies which variable to update, and the second contains the new * value. Both are truncated to shorts in non-local SMP. */ public void sendProgressBarUpdate(Container containerIn, int varToUpdate, int newValue) { this.playerNetServerHandler.sendPacket(new S31PacketWindowProperty(containerIn.windowId, varToUpdate, newValue)); } public void func_175173_a(Container p_175173_1_, IInventory p_175173_2_) { for (int i = 0; i < p_175173_2_.getFieldCount(); ++i) { this.playerNetServerHandler.sendPacket(new S31PacketWindowProperty(p_175173_1_.windowId, i, p_175173_2_.getField(i))); } } /** * set current crafting inventory back to the 2x2 square */ public void closeScreen() { this.playerNetServerHandler.sendPacket(new S2EPacketCloseWindow(this.openContainer.windowId)); this.closeContainer(); } /** * updates item held by mouse */ public void updateHeldItem() { if (!this.isChangingQuantityOnly) { this.playerNetServerHandler.sendPacket(new S2FPacketSetSlot(-1, -1, this.inventory.getItemStack())); } } /** * Closes the container the player currently has open. */ public void closeContainer() { this.openContainer.onContainerClosed(this); this.openContainer = this.inventoryContainer; } public void setEntityActionState(float p_110430_1_, float p_110430_2_, boolean p_110430_3_, boolean sneaking) { if (this.ridingEntity != null) { if (p_110430_1_ >= -1.0F && p_110430_1_ <= 1.0F) { this.moveStrafing = p_110430_1_; } if (p_110430_2_ >= -1.0F && p_110430_2_ <= 1.0F) { this.moveForward = p_110430_2_; } this.isJumping = p_110430_3_; this.setSneaking(sneaking); } } /** * Adds a value to a statistic field. */ public void addStat(StatBase stat, int amount) { if (stat != null) { this.statsFile.increaseStat(this, stat, amount); for (ScoreObjective scoreobjective : this.getWorldScoreboard().getObjectivesFromCriteria(stat.func_150952_k())) { this.getWorldScoreboard().getValueFromObjective(this.getName(), scoreobjective).increseScore(amount); } if (this.statsFile.func_150879_e()) { this.statsFile.func_150876_a(this); } } } public void func_175145_a(StatBase p_175145_1_) { if (p_175145_1_ != null) { this.statsFile.unlockAchievement(this, p_175145_1_, 0); for (ScoreObjective scoreobjective : this.getWorldScoreboard().getObjectivesFromCriteria(p_175145_1_.func_150952_k())) { this.getWorldScoreboard().getValueFromObjective(this.getName(), scoreobjective).setScorePoints(0); } if (this.statsFile.func_150879_e()) { this.statsFile.func_150876_a(this); } } } public void mountEntityAndWakeUp() { if (this.riddenByEntity != null) { this.riddenByEntity.mountEntity(this); } if (this.sleeping) { this.wakeUpPlayer(true, false, false); } } /** * this function is called when a players inventory is sent to him, lastHealth * is updated on any dimension transitions, then reset. */ public void setPlayerHealthUpdated() { this.lastHealth = -1.0E8F; } public void addChatComponentMessage(IChatComponent chatComponent) { this.playerNetServerHandler.sendPacket(new S02PacketChat(chatComponent)); } /** * Used for when item use count runs out, ie: eating completed */ protected void onItemUseFinish() { this.playerNetServerHandler.sendPacket(new S19PacketEntityStatus(this, (byte) 9)); super.onItemUseFinish(); } /** * sets the itemInUse when the use item button is clicked. Args: itemstack, int * maxItemUseDuration */ public void setItemInUse(ItemStack stack, int duration) { super.setItemInUse(stack, duration); if (stack != null && stack.getItem() != null && stack.getItem().getItemUseAction(stack) == EnumAction.EAT) { this.getServerForPlayer().getEntityTracker().func_151248_b(this, new S0BPacketAnimation(this, 3)); } } /** * Copies the values from the given player into this player if boolean par2 is * true. Always clones Ender Chest Inventory. */ public void clonePlayer(EntityPlayer oldPlayer, boolean respawnFromEnd) { super.clonePlayer(oldPlayer, respawnFromEnd); this.lastExperience = -1; this.lastHealth = -1.0F; this.lastFoodLevel = -1; this.destroyedItemsNetCache.addAll(((EntityPlayerMP) oldPlayer).destroyedItemsNetCache); } protected void onNewPotionEffect(PotionEffect id) { super.onNewPotionEffect(id); this.playerNetServerHandler.sendPacket(new S1DPacketEntityEffect(this.getEntityId(), id)); } protected void onChangedPotionEffect(PotionEffect id, boolean p_70695_2_) { super.onChangedPotionEffect(id, p_70695_2_); this.playerNetServerHandler.sendPacket(new S1DPacketEntityEffect(this.getEntityId(), id)); } protected void onFinishedPotionEffect(PotionEffect p_70688_1_) { super.onFinishedPotionEffect(p_70688_1_); this.playerNetServerHandler.sendPacket(new S1EPacketRemoveEntityEffect(this.getEntityId(), p_70688_1_)); } /** * Sets the position of the entity and updates the 'last' variables */ public void setPositionAndUpdate(double x, double y, double z) { this.playerNetServerHandler.setPlayerLocation(x, y, z, this.rotationYaw, this.rotationPitch); } /** * Called when the player performs a critical hit on the Entity. Args: entity * that was hit critically */ public void onCriticalHit(Entity entityHit) { this.getServerForPlayer().getEntityTracker().func_151248_b(this, new S0BPacketAnimation(entityHit, 4)); } public void onEnchantmentCritical(Entity entityHit) { this.getServerForPlayer().getEntityTracker().func_151248_b(this, new S0BPacketAnimation(entityHit, 5)); } /** * Sends the player's abilities to the server (if there is one). */ public void sendPlayerAbilities() { if (this.playerNetServerHandler != null) { this.playerNetServerHandler.sendPacket(new S39PacketPlayerAbilities(this.capabilities)); this.updatePotionMetadata(); } } public WorldServer getServerForPlayer() { return (WorldServer) this.worldObj; } /** * Sets the player's game mode and sends it to them. */ public void setGameType(WorldSettings.GameType gameType) { this.theItemInWorldManager.setGameType(gameType); this.playerNetServerHandler.sendPacket(new S2BPacketChangeGameState(3, (float) gameType.getID())); if (gameType == WorldSettings.GameType.SPECTATOR) { this.mountEntity((Entity) null); } else { this.setSpectatingEntity(this); } this.sendPlayerAbilities(); this.markPotionsDirty(); } /** * Returns true if the player is in spectator mode. */ public boolean isSpectator() { return this.theItemInWorldManager.getGameType() == WorldSettings.GameType.SPECTATOR; } /** * Send a chat message to the CommandSender */ public void addChatMessage(IChatComponent component) { this.playerNetServerHandler.sendPacket(new S02PacketChat(component)); } /** * Returns {@code true} if the CommandSender is allowed to execute the command, * {@code false} if not */ public boolean canCommandSenderUseCommand(int permLevel, String commandName) { if ("seed".equals(commandName) && !this.mcServer.isDedicatedServer()) { return true; } else if (!"tell".equals(commandName) && !"help".equals(commandName) && !"me".equals(commandName) && !"trigger".equals(commandName)) { if (this.mcServer.getConfigurationManager().canSendCommands(this.getGameProfile())) { UserListOpsEntry userlistopsentry = (UserListOpsEntry) this.mcServer.getConfigurationManager().getOppedPlayers().getEntry(this.getGameProfile()); return userlistopsentry != null ? userlistopsentry.getPermissionLevel() >= permLevel : this.mcServer.getOpPermissionLevel() >= permLevel; } else { return false; } } else { return true; } } /** * Gets the player's IP address. Used in /banip. */ public String getPlayerIP() { String s = this.playerNetServerHandler.netManager.getRemoteAddress().toString(); s = s.substring(s.indexOf("/") + 1); s = s.substring(0, s.indexOf(":")); return s; } public void handleClientSettings(C15PacketClientSettings packetIn) { this.translator = packetIn.getLang(); this.chatVisibility = packetIn.getChatVisibility(); this.chatColours = packetIn.isColorsEnabled(); this.getDataWatcher().updateObject(10, Byte.valueOf((byte) packetIn.getModelPartFlags())); } public EntityPlayer.EnumChatVisibility getChatVisibility() { return this.chatVisibility; } public void loadResourcePack(String url, String hash) { this.playerNetServerHandler.sendPacket(new S48PacketResourcePackSend(url, hash)); } /** * Get the position in the world. <b>{@code null} is not allowed!</b> If you are * not an entity in the world, return the coordinates 0, 0, 0 */ public BlockPos getPosition() { return new BlockPos(this.posX, this.posY + 0.5D, this.posZ); } public void markPlayerActive() { this.playerLastActiveTime = MinecraftServer.getCurrentTimeMillis(); } /** * Gets the stats file for reading achievements */ public StatisticsFile getStatFile() { return this.statsFile; } /** * Sends a packet to the player to remove an entity. */ public void removeEntity(Entity p_152339_1_) { if (p_152339_1_ instanceof EntityPlayer) { this.playerNetServerHandler.sendPacket(new S13PacketDestroyEntities(new int[] { p_152339_1_.getEntityId() })); } else { this.destroyedItemsNetCache.add(Integer.valueOf(p_152339_1_.getEntityId())); } } /** * Clears potion metadata values if the entity has no potion effects. Otherwise, * updates potion effect color, ambience, and invisibility metadata values */ protected void updatePotionMetadata() { if (this.isSpectator()) { this.resetPotionEffectMetadata(); this.setInvisible(true); } else { super.updatePotionMetadata(); } this.getServerForPlayer().getEntityTracker().func_180245_a(this); } public Entity getSpectatingEntity() { return (Entity) (this.spectatingEntity == null ? this : this.spectatingEntity); } public void setSpectatingEntity(Entity entityToSpectate) { Entity entity = this.getSpectatingEntity(); this.spectatingEntity = (Entity) (entityToSpectate == null ? this : entityToSpectate); if (entity != this.spectatingEntity) { this.playerNetServerHandler.sendPacket(new S43PacketCamera(this.spectatingEntity)); this.setPositionAndUpdate(this.spectatingEntity.posX, this.spectatingEntity.posY, this.spectatingEntity.posZ); } } /** * Attacks for the player the targeted entity with the currently equipped item. * The equipped item has hitEntity called on it. Args: targetEntity */ public void attackTargetEntityWithCurrentItem(Entity targetEntity) { if (this.theItemInWorldManager.getGameType() == WorldSettings.GameType.SPECTATOR) { this.setSpectatingEntity(targetEntity); } else { super.attackTargetEntityWithCurrentItem(targetEntity); } } public long getLastActiveTime() { return this.playerLastActiveTime; } /** * Returns null which indicates the tab list should just display the player's * name, return a different value to display the specified text instead of the * player's name */ public IChatComponent getTabListDisplayName() { return null; } }
0
0.963373
1
0.963373
game-dev
MEDIA
0.9953
game-dev
0.828493
1
0.828493
OvercastNetwork/ProjectAres
1,859
Commons/bukkit/src/main/java/tc/oc/commons/bukkit/chat/CachingNameRenderer.java
package tc.oc.commons.bukkit.chat; import javax.annotation.Nullable; import javax.inject.Inject; import javax.inject.Singleton; import com.google.common.collect.HashBasedTable; import com.google.common.collect.Table; import net.md_5.bungee.api.chat.BaseComponent; import tc.oc.commons.bukkit.nick.Identity; /** * Caches rendered names, both component and legacy. The cache is keyed on * the {@link Identity} and {@link NameType} that the name is generated from. */ @Singleton public class CachingNameRenderer implements NameRenderer { private final NameRenderer nameRenderer; private final Table<Identity, NameType, BaseComponent> components = HashBasedTable.create(); private final Table<Identity, NameType, String> legacy = HashBasedTable.create(); @Inject public CachingNameRenderer(NameRenderer nameRenderer) { this.nameRenderer = nameRenderer; } @Override public String getLegacyName(Identity identity, NameType type) { String rendered = legacy.get(identity, type); if(rendered == null) { rendered = nameRenderer.getLegacyName(identity, type); legacy.put(identity, type, rendered); } return rendered; } @Override public BaseComponent getComponentName(Identity identity, NameType type) { BaseComponent rendered = components.get(identity, type); if(rendered == null) { rendered = nameRenderer.getComponentName(identity, type); components.put(identity, type, rendered); } return rendered; } public void invalidateCache(@Nullable Identity identity) { if(identity == null) { components.clear(); legacy.clear(); } else { components.rowKeySet().remove(identity); legacy.rowKeySet().remove(identity); } } }
0
0.811093
1
0.811093
game-dev
MEDIA
0.418552
game-dev
0.84081
1
0.84081
DeltaV-Station/Delta-v
1,720
Content.Server/Magic/MagicSystem.cs
using Content.Server.Chat.Systems; using Content.Server.GameTicking; using Content.Server.GameTicking.Rules.Components; using Content.Shared.Magic; using Content.Shared.Magic.Events; using Content.Shared.Mind; using Content.Shared.Tag; using Robust.Shared.Prototypes; namespace Content.Server.Magic; public sealed class MagicSystem : SharedMagicSystem { [Dependency] private readonly ChatSystem _chat = default!; [Dependency] private readonly GameTicker _gameTicker = default!; [Dependency] private readonly TagSystem _tag = default!; [Dependency] private readonly SharedMindSystem _mind = default!; private static readonly ProtoId<TagPrototype> InvalidForSurvivorAntagTag = "InvalidForSurvivorAntag"; public override void Initialize() { base.Initialize(); } public override void OnVoidApplause(VoidApplauseSpellEvent ev) { base.OnVoidApplause(ev); _chat.TryEmoteWithChat(ev.Performer, ev.Emote); var perfXForm = Transform(ev.Performer); var targetXForm = Transform(ev.Target); Spawn(ev.Effect, perfXForm.Coordinates); Spawn(ev.Effect, targetXForm.Coordinates); } protected override void OnRandomGlobalSpawnSpell(RandomGlobalSpawnSpellEvent ev) { base.OnRandomGlobalSpawnSpell(ev); if (!ev.MakeSurvivorAntagonist) return; if (_mind.TryGetMind(ev.Performer, out var mind, out _) && !_tag.HasTag(mind, InvalidForSurvivorAntagTag)) _tag.AddTag(mind, InvalidForSurvivorAntagTag); EntProtoId survivorRule = "Survivor"; if (!_gameTicker.IsGameRuleActive<SurvivorRuleComponent>()) _gameTicker.StartGameRule(survivorRule); } }
0
0.893887
1
0.893887
game-dev
MEDIA
0.905261
game-dev
0.883359
1
0.883359
liyunfan1223/mod-playerbots
1,722
src/strategy/dungeons/wotlk/draktharonkeep/DrakTharonKeepMultipliers.cpp
#include "DrakTharonKeepMultipliers.h" #include "DrakTharonKeepActions.h" #include "GenericSpellActions.h" #include "ChooseTargetActions.h" #include "MovementActions.h" #include "DrakTharonKeepTriggers.h" #include "Action.h" float NovosMultiplier::GetValue(Action* action) { Unit* boss = AI_VALUE2(Unit*, "find target", "novos the summoner"); if (!boss) { return 1.0f; } if (boss->FindCurrentSpellBySpellId(SPELL_ARCANE_FIELD) && bot->GetTarget()) { if (dynamic_cast<DpsAssistAction*>(action) || dynamic_cast<TankAssistAction*>(action)) { return 0.0f; } } return 1.0f; } float TharonjaMultiplier::GetValue(Action* action) { if (!bot->HasAura(SPELL_GIFT_OF_THARONJA)) { return 1.0f; } // Suppress all skills that are not enabled in skeleton form. // Still allow non-ability actions such as movement if (dynamic_cast<CastSpellAction*>(action) && !dynamic_cast<CastSlayingStrikeAction*>(action) && !dynamic_cast<CastTauntAction*>(action) && !dynamic_cast<CastBoneArmorAction*>(action) && !dynamic_cast<CastTouchOfLifeAction*>(action)) { return 0.0f; } // Also suppress FleeAction to prevent ranged characters from avoiding melee range if (dynamic_cast<FleeAction*>(action)) { return 0.0f; } // Tanks should only taunt, no slaying strike if (botAI->IsTank(bot)) { if (dynamic_cast<CastSlayingStrikeAction*>(action)) { return 0.0f; } } // Dps & healer should not taunt else { if (dynamic_cast<CastTauntAction*>(action)) { return 0.0f; } } return 1.0f; }
0
0.948733
1
0.948733
game-dev
MEDIA
0.979635
game-dev
0.97921
1
0.97921
shiptest-ss13/Shiptest
8,109
code/controllers/subsystem/points_of_interest.dm
/// Subsystem for managing all POIs. SUBSYSTEM_DEF(points_of_interest) name = "Points of Interest" flags = SS_NO_FIRE | SS_NO_INIT /// List of mob POIs. This list is automatically sorted. var/list/datum/point_of_interest/mob_poi/mob_points_of_interest = list() /// List of non-mob POIs. This list is automatically sorted. var/list/datum/point_of_interest/other_points_of_interest = list() /// List of all value:POI datums by their key:target refs. var/list/datum/point_of_interest/points_of_interest_by_target_ref = list() /** * Turns new_poi into a new point of interest by adding the /datum/element/point_of_interest element to it. */ /datum/controller/subsystem/points_of_interest/proc/make_point_of_interest(atom/new_poi) new_poi.AddElement(/datum/element/point_of_interest) /** * Stops old_poi from being a point of interest by removing the /datum/element/point_of_interest element from it. */ /datum/controller/subsystem/points_of_interest/proc/remove_point_of_interest(atom/old_poi) old_poi.RemoveElement(/datum/element/point_of_interest) /** * Called by [/datum/element/point_of_interest] when it gets removed from old_poi. */ /datum/controller/subsystem/points_of_interest/proc/on_poi_element_added(atom/new_poi) var/datum/point_of_interest/new_poi_datum if(ismob(new_poi)) new_poi_datum = new /datum/point_of_interest/mob_poi(new_poi) BINARY_INSERT_PROC_COMPARE(new_poi_datum, mob_points_of_interest, /datum/point_of_interest/mob_poi, new_poi_datum, compare_to, COMPARE_KEY) points_of_interest_by_target_ref[REF(new_poi)] = new_poi_datum else new_poi_datum = new /datum/point_of_interest(new_poi) BINARY_INSERT_PROC_COMPARE(new_poi_datum, other_points_of_interest, /datum/point_of_interest, new_poi_datum, compare_to, COMPARE_KEY) points_of_interest_by_target_ref[REF(new_poi)] = new_poi_datum SEND_SIGNAL(src, COMSIG_ADDED_POINT_OF_INTEREST, new_poi) /** * Called by [/datum/element/point_of_interest] when it gets removed from old_poi. */ /datum/controller/subsystem/points_of_interest/proc/on_poi_element_removed(atom/old_poi) var/poi_ref = REF(old_poi) var/datum/point_of_interest/poi_to_remove = points_of_interest_by_target_ref[poi_ref] if(!poi_to_remove) return if(ismob(old_poi)) mob_points_of_interest -= poi_to_remove else other_points_of_interest -= poi_to_remove points_of_interest_by_target_ref -= poi_ref poi_to_remove.target = null SEND_SIGNAL(src, COMSIG_REMOVED_POINT_OF_INTEREST, old_poi) /** * If there is a valid POI for a given reference, it returns that POI's associated atom. Otherwise, it returns null. */ /datum/controller/subsystem/points_of_interest/proc/get_poi_atom_by_ref(reference) return points_of_interest_by_target_ref[reference]?.target /** * Returns a list of mob POIs with names as keys and mobs as values. * * If multiple POIs have the same name, then avoid_assoc_duplicate_keys is used alongside used_name_list to * tag them as Mob Name (1), Mob Name (2), Mob Name (3) etc. * * Arguments: * * poi_validation_override - [OPTIONAL] Callback to a proc that takes a single argument for the POI and returns TRUE if this POI should be included. Overrides standard POI validation. * * append_dead_role - [OPTIONAL] If TRUE, adds a ghost tag to the end of observer names and a dead tag to the end of any other mob which is not alive. */ /datum/controller/subsystem/points_of_interest/proc/get_mob_pois(datum/callback/poi_validation_override = null, append_dead_role = TRUE) var/list/pois = list() var/list/used_name_list = list() for(var/datum/point_of_interest/mob_poi/mob_poi as anything in mob_points_of_interest) if(poi_validation_override) if(!poi_validation_override.Invoke(mob_poi)) continue else if(!mob_poi.validate()) continue var/mob/target_mob = mob_poi.target var/name = avoid_assoc_duplicate_keys(target_mob.name, used_name_list) + target_mob.get_realname_string() // Add the ghost/dead tag to the end of dead mob POIs. if(append_dead_role && target_mob.stat == DEAD) if(isobserver(target_mob)) name += " \[ghost\]" else name += " \[dead\]" pois[name] = target_mob return pois /** * Returns a list of non-mob POIs with names as keys and atoms as values. * * If multiple POIs have the same name, then avoid_assoc_duplicate_keys is used alongside used_name_list to * tag them as Object Name (1), Object Name (2), Object Name (3) etc. * * Arguments: * * poi_validation_override - [OPTIONAL] Callback to a proc that takes a single argument for the POI and returns TRUE if this POI should be included. Overrides standard POI validation. */ /datum/controller/subsystem/points_of_interest/proc/get_other_pois(datum/callback/poi_validation_override = null) var/list/pois = list() var/list/used_name_list = list() for(var/datum/point_of_interest/other_poi as anything in other_points_of_interest) if(poi_validation_override) if(!poi_validation_override.Invoke(other_poi)) continue else if(!other_poi.validate()) continue var/atom/target_poi = other_poi.target pois[avoid_assoc_duplicate_keys(target_poi.name, used_name_list)] = target_poi return pois /// Returns TRUE if potential_poi has an associated poi_datum that validates. /datum/controller/subsystem/points_of_interest/proc/is_valid_poi(atom/potential_poi, datum/callback/poi_validation_override = null) var/datum/point_of_interest/poi_datum = points_of_interest_by_target_ref[REF(potential_poi)] if(!poi_datum) return FALSE if(poi_validation_override) return poi_validation_override.Invoke(poi_datum) return poi_datum.validate() /// Simple helper datum for points of interest. /datum/point_of_interest /// The specific point of interest this datum references. This won't hard del as the POI element will be removed from the target when it qdels, which will clear this reference. var/atom/target /// The type of POI this datum references. var/poi_type = /atom /datum/point_of_interest/New(poi_target) if(!istype(poi_target, poi_type)) CRASH("Incorrect target type provided to /datum/point_of_interest/New: Expected \[[poi_type]\]") target = poi_target /// Validates the POI. Returns TRUE if the POI has valid state, returns FALSE if the POI has invalid state. /datum/point_of_interest/proc/validate() // In nullspace, invalid as a POI. if(!target.loc) return FALSE return TRUE /// Comparison proc used to sort POIs. Override to implement logic used doing binary sort insertions. /datum/point_of_interest/proc/compare_to(datum/point_of_interest/rhs) return cmp_name_asc(target, rhs.target) /datum/point_of_interest/mob_poi poi_type = /mob /// Validation for mobs is expanded to invalidate stealthmins and /mob/dead/new_player as POIs. /datum/point_of_interest/mob_poi/validate() . = ..() if(!.) return var/mob/poi_mob = target // Stealthmin, invalid as a POI. if(poi_mob.client?.holder?.fakekey) return FALSE /* // POI is a /mob/dead/new_player, players in the lobby are invalid as POIs. if(isnewplayer(poi_mob)) return FALSE */ return TRUE /// Mob POIs are sorted by a simple priority list depending on their type. When their type priority is identical, they're sub-sorted by name. /datum/point_of_interest/mob_poi/compare_to(datum/point_of_interest/mob_poi/rhs) var/sort_difference = get_type_sort_priority() - rhs.get_type_sort_priority() // If they're equal in priority, call parent to sort by name. if(sort_difference == 0) return ..() // Else sort by priority. else return sort_difference /// Priority list broadly stolen from /proc/sortmobs(). Lower numbers are higher priorities when sorted and appear closer to the top or start of lists. /datum/point_of_interest/mob_poi/proc/get_type_sort_priority() if(isAI(target)) return 0 if(iscameramob(target)) return 1 if(ispAI(target)) return 2 if(iscyborg(target)) return 3 if(ishuman(target)) return 4 if(isbrain(target)) return 5 if(isalien(target)) return 6 if(isobserver(target)) return 7 if(isnewplayer(target)) return 8 if(isslime(target)) return 9 if(isanimal(target)) return 10 return 11
0
0.707264
1
0.707264
game-dev
MEDIA
0.512761
game-dev
0.838484
1
0.838484
blackducksoftware/detect
1,071
detectable/src/main/java/com/blackduck/integration/detectable/detectables/bitbake/model/BitbakeGraph.java
package com.blackduck.integration.detectable.detectables.bitbake.model; import java.util.ArrayList; import java.util.List; import java.util.Optional; import org.jetbrains.annotations.Nullable; public class BitbakeGraph { private final List<BitbakeNode> nodes = new ArrayList<>(); private BitbakeNode getOrCreate(String name) { Optional<BitbakeNode> existingNode = nodes.stream() .filter(node -> node.getName().equals(name)) .findFirst(); if (existingNode.isPresent()) { return existingNode.get(); } BitbakeNode newNode = new BitbakeNode(name); nodes.add(newNode); return newNode; } public void addNode(String name, @Nullable String version, @Nullable String layer) { BitbakeNode node = getOrCreate(name); node.setVersion(version); node.setLayer(layer); } public void addChild(String parent, String child) { getOrCreate(parent).addChild(child); } public List<BitbakeNode> getNodes() { return nodes; } }
0
0.862762
1
0.862762
game-dev
MEDIA
0.404357
game-dev
0.909158
1
0.909158
fulpstation/fulpstation
4,117
fulp_modules/features/antagonists/bloodsuckers/code/bloodsucker/subsystem_sunlight.dm
///How long Sol will last until it's night again. #define TIME_BLOODSUCKER_DAY 60 ///Base time nighttime should be in for, until Sol rises. #define TIME_BLOODSUCKER_NIGHT 600 ///Time left to send an alert to Bloodsuckers about an incoming Sol. #define TIME_BLOODSUCKER_DAY_WARN 90 ///Time left to send an urgent alert to Bloodsuckers about an incoming Sol. #define TIME_BLOODSUCKER_DAY_FINAL_WARN 30 ///Time left to alert that Sol is rising. #define TIME_BLOODSUCKER_BURN_INTERVAL 5 ///How much time Sol can be 'off' by, keeping the time inconsistent. #define TIME_BLOODSUCKER_SOL_DELAY 120 SUBSYSTEM_DEF(sunlight) name = "Sol" can_fire = FALSE wait = 2 SECONDS flags = SS_NO_INIT | SS_BACKGROUND | SS_TICKER ///If the Sun is currently out our not. var/sunlight_active = FALSE ///The time between the next cycle, randomized every night. var/time_til_cycle = TIME_BLOODSUCKER_NIGHT ///If Bloodsucker levels for the night has been given out yet. var/issued_XP = FALSE /datum/controller/subsystem/sunlight/fire(resumed = FALSE) time_til_cycle-- if(sunlight_active) if(time_til_cycle > 0) SEND_SIGNAL(src, COMSIG_SOL_RISE_TICK) if(!issued_XP && time_til_cycle <= 15) issued_XP = TRUE SEND_SIGNAL(src, COMSIG_SOL_RANKUP_BLOODSUCKERS) if(time_til_cycle <= 1) sunlight_active = FALSE issued_XP = FALSE //randomize the next sol timer time_til_cycle = round(rand((TIME_BLOODSUCKER_NIGHT-TIME_BLOODSUCKER_SOL_DELAY), (TIME_BLOODSUCKER_NIGHT+TIME_BLOODSUCKER_SOL_DELAY)), 60) message_admins("BLOODSUCKER NOTICE: Daylight Ended. Resetting to night (Lasts for [time_til_cycle / 60] minutes.") SEND_SIGNAL(src, COMSIG_SOL_END) warn_daylight( danger_level = DANGER_LEVEL_SOL_ENDED, vampire_warning_message = span_announce("The solar flare has ended, and the daylight danger has passed... for now."), vassal_warning_message = span_announce("The solar flare has ended, and the daylight danger has passed... for now."), ) return switch(time_til_cycle) if(TIME_BLOODSUCKER_DAY_WARN) SEND_SIGNAL(src, COMSIG_SOL_NEAR_START) warn_daylight( danger_level = DANGER_LEVEL_FIRST_WARNING, vampire_warning_message = span_danger("Solar flares will bombard the station with dangerous UV radiation in [TIME_BLOODSUCKER_DAY_WARN / 60] minutes. <b>Prepare to seek cover in a coffin or closet.</b>"), ) if(TIME_BLOODSUCKER_DAY_FINAL_WARN) message_admins("BLOODSUCKER NOTICE: Daylight beginning in [TIME_BLOODSUCKER_DAY_FINAL_WARN] seconds.)") warn_daylight( danger_level = DANGER_LEVEL_SECOND_WARNING, vampire_warning_message = span_userdanger("Solar flares are about to bombard the station! You have [TIME_BLOODSUCKER_DAY_FINAL_WARN] seconds to find cover!"), vassal_warning_message = span_danger("In [TIME_BLOODSUCKER_DAY_FINAL_WARN] seconds, your master will be at risk of burning under a solar flare. Make sure they find cover!"), ) if(TIME_BLOODSUCKER_BURN_INTERVAL) warn_daylight( danger_level = DANGER_LEVEL_THIRD_WARNING, vampire_warning_message = span_userdanger("Seek cover, for Sol rises!"), ) if(NONE) sunlight_active = TRUE //set the timer to countdown daytime now. time_til_cycle = TIME_BLOODSUCKER_DAY message_admins("BLOODSUCKER NOTICE: Daylight Beginning (Lasts for [TIME_BLOODSUCKER_DAY / 60] minutes.)") warn_daylight( danger_level = DANGER_LEVEL_SOL_ROSE, vampire_warning_message = span_userdanger("Solar flares bombard the station with deadly UV light! Stay in cover for the next [TIME_BLOODSUCKER_DAY / 60] minutes or risk Final Death!"), vassal_warning_message = span_userdanger("Solar flares bombard the station with UV light!"), ) /datum/controller/subsystem/sunlight/proc/warn_daylight(danger_level, vampire_warning_message, vassal_warning_message) SEND_SIGNAL(src, COMSIG_SOL_WARNING_GIVEN, danger_level, vampire_warning_message, vassal_warning_message) #undef TIME_BLOODSUCKER_SOL_DELAY #undef TIME_BLOODSUCKER_DAY #undef TIME_BLOODSUCKER_NIGHT #undef TIME_BLOODSUCKER_DAY_WARN #undef TIME_BLOODSUCKER_DAY_FINAL_WARN #undef TIME_BLOODSUCKER_BURN_INTERVAL
0
0.91315
1
0.91315
game-dev
MEDIA
0.795679
game-dev
0.893201
1
0.893201
b0LBwZ7r5HOeh6CBMuQIhVu3-s-random-fork/PCL2
95,052
pcl2_full/Plain Craft Launcher 2/PageDownloadInstall.cs
using Microsoft.VisualBasic.CompilerServices; using Newtonsoft.Json.Linq; using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using System.Text.RegularExpressions; using System.Threading; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Markup; using System.Windows.Media; using System.Windows.Shapes; namespace PCL { // Token: 0x02000086 RID: 134 [DesignerGenerated] public class PageDownloadInstall : AdornerDecorator, IComponentConnector { // Token: 0x060003B5 RID: 949 RVA: 0x00024998 File Offset: 0x00022B98 public PageDownloadInstall() { base.Loaded += delegate(object sender, RoutedEventArgs e) { this.Init(); }; this._ListenerVal = false; this.importerVal = false; this._TemplateVal = false; this.regVal = null; this.definitionVal = null; this._ParamVal = null; this.m_MockVal = null; this.specificationVal = null; this.m_DicVal = false; this._SchemaVal = false; this.InitializeComponent(); } // Token: 0x060003B6 RID: 950 RVA: 0x00024A0C File Offset: 0x00022C0C private void Init() { this.PanBack.ScrollToHome(); ModDownload._AlgoIterator.Start(PageDownloadClient._IndexerUtils, false); ModDownload.issuerIterator.Start(PageDownloadOptiFine.writerIterator, false); ModDownload.m_BridgeIterator.Start(PageDownloadLiteLoader.LoadInput, false); ModDownload.m_ObjectIterator.Start(PageDownloadFabric.watcherVal, false); ModDownload._VisitorIterator.Start(PageDownloadFabric.watcherVal, false); this.TextSelectName.ValidateRules = new Collection<Validate> { new ValidateFolderName(ModMinecraft.m_ResolverIterator + "versions", true, true) }; this.TextSelectName.Validate(); this.SelectReload(); if (!this._ListenerVal) { this._ListenerVal = true; ModDownloadLib.McDownloadForgeRecommendedRefresh(); this.LoadMinecraft.State = ModDownload._AlgoIterator; this.LoadOptiFine.State = ModDownload.issuerIterator; this.LoadLiteLoader.State = ModDownload.m_BridgeIterator; this.LoadFabric.State = ModDownload.m_ObjectIterator; this.LoadFabricApi.State = ModDownload._VisitorIterator; } } // Token: 0x060003B7 RID: 951 RVA: 0x00024B18 File Offset: 0x00022D18 private void EnterSelectPage() { if (!this.importerVal) { this.importerVal = true; this.m_DicVal = false; this.PanSelect.Visibility = Visibility.Visible; this.PanMinecraft.IsHitTestVisible = false; this.PanSelect.IsHitTestVisible = true; this.PanBack.IsHitTestVisible = false; this.PanBack.ScrollToHome(); this.CardMinecraft.LoadAnimation = false; this.CardMinecraft.IsSwaped = true; this.CardOptiFine.LoadAnimation = false; this.CardOptiFine.IsSwaped = true; this.CardLiteLoader.LoadAnimation = false; this.CardLiteLoader.IsSwaped = true; this.CardForge.LoadAnimation = false; this.CardForge.IsSwaped = true; this.CardFabric.LoadAnimation = false; this.CardFabric.IsSwaped = true; this.CardFabricApi.LoadAnimation = false; this.CardFabricApi.IsSwaped = true; if (Conversions.ToBoolean(Operators.NotObject(ModBase._BaseRule.Get("HintInstallBack", null)))) { ModBase._BaseRule.Set("HintInstallBack", true, false, null); ModMain.Hint("点击 Minecraft 项即可返回游戏主版本选择页面!", ModMain.HintType.Info, true); } if (this._AdapterVal.StartsWith("1.")) { ModLoader.LoaderTask<string, List<ModDownload.DlForgeVersionEntry>> loaderTask = new ModLoader.LoaderTask<string, List<ModDownload.DlForgeVersionEntry>>("DlForgeVersion " + this._AdapterVal, new ModLoader.LoaderTask<string, List<ModDownload.DlForgeVersionEntry>>.LoadDelegateSub(ModDownload.DlForgeVersionMain), null, ThreadPriority.Normal); this.LoadForge.State = loaderTask; loaderTask.Start(this._AdapterVal, false); } ModAni.AniStart(new ModAni.AniData[] { ModAni.AaOpacity(this.PanMinecraft, -this.PanMinecraft.Opacity, 0x64, 0xA, null, false), ModAni.AaTranslateX(this.PanMinecraft, -50.0 - ((TranslateTransform)this.PanMinecraft.RenderTransform).X, 0x6E, 0xA, null, false), ModAni.AaCode(delegate { this.PanBack.ScrollToHome(); this.TextSelectName.Validate(); this.OptiFine_Loaded(); this.LiteLoader_Loaded(); this.Forge_Loaded(); this.Fabric_Loaded(); this.FabricApi_Loaded(); this.SelectReload(); }, 0, true), ModAni.AaOpacity(this.PanSelect, 1.0 - this.PanSelect.Opacity, 0x96, 0x64, null, false), ModAni.AaTranslateX(this.PanSelect, -((TranslateTransform)this.PanSelect.RenderTransform).X, 0x140, 0x64, new ModAni.AniEaseOutBack(ModAni.AniEasePower.Weak), false), ModAni.AaCode(delegate { this.PanMinecraft.Visibility = Visibility.Collapsed; this.CardMinecraft.LoadAnimation = true; this.CardOptiFine.LoadAnimation = true; this.CardLiteLoader.LoadAnimation = true; this.CardForge.LoadAnimation = true; this.CardFabric.LoadAnimation = true; this.CardFabricApi.LoadAnimation = true; this.PanBack.IsHitTestVisible = true; if (!this._TemplateVal) { this._TemplateVal = true; this.BtnOptiFineClearInner.SetBinding(Shape.FillProperty, new Binding("Foreground") { Source = this.CardOptiFine.m_Bridge, Mode = BindingMode.OneWay }); this.BtnLiteLoaderClearInner.SetBinding(Shape.FillProperty, new Binding("Foreground") { Source = this.CardLiteLoader.m_Bridge, Mode = BindingMode.OneWay }); this.BtnForgeClearInner.SetBinding(Shape.FillProperty, new Binding("Foreground") { Source = this.CardForge.m_Bridge, Mode = BindingMode.OneWay }); this.BtnFabricClearInner.SetBinding(Shape.FillProperty, new Binding("Foreground") { Source = this.CardFabric.m_Bridge, Mode = BindingMode.OneWay }); this.BtnFabricApiClearInner.SetBinding(Shape.FillProperty, new Binding("Foreground") { Source = this.CardFabricApi.m_Bridge, Mode = BindingMode.OneWay }); } }, 0, true) }, "FrmDownloadInstall SelectPageSwitch", true); } } // Token: 0x060003B8 RID: 952 RVA: 0x00024DA0 File Offset: 0x00022FA0 public void ExitSelectPage() { if (this.importerVal) { this.importerVal = false; this.PanMinecraft.Visibility = Visibility.Visible; this.PanSelect.IsHitTestVisible = false; this.PanMinecraft.IsHitTestVisible = true; this.SelectClear(); this.PanBack.IsHitTestVisible = false; this.PanBack.ScrollToHome(); this.CardMinecraft.LoadAnimation = false; this.CardOptiFine.LoadAnimation = false; this.CardLiteLoader.LoadAnimation = false; this.CardForge.LoadAnimation = false; this.CardFabric.LoadAnimation = false; this.CardFabricApi.LoadAnimation = false; ModAni.AniStart(new ModAni.AniData[] { ModAni.AaOpacity(this.PanSelect, -this.PanSelect.Opacity, 0x5A, 0xA, null, false), ModAni.AaTranslateX(this.PanSelect, 50.0 - ((TranslateTransform)this.PanSelect.RenderTransform).X, 0x64, 0xA, null, false), ModAni.AaCode(delegate { this.PanBack.ScrollToHome(); }, 0, true), ModAni.AaOpacity(this.PanMinecraft, 1.0 - this.PanMinecraft.Opacity, 0x78, 0xA, null, false), ModAni.AaTranslateX(this.PanMinecraft, -((TranslateTransform)this.PanMinecraft.RenderTransform).X, 0xFA, 0xA, new ModAni.AniEaseOutBack(ModAni.AniEasePower.Weak), false), ModAni.AaCode(delegate { this.PanSelect.Visibility = Visibility.Collapsed; this.CardMinecraft.LoadAnimation = true; this.CardOptiFine.LoadAnimation = true; this.CardLiteLoader.LoadAnimation = true; this.CardForge.LoadAnimation = true; this.CardFabric.LoadAnimation = true; this.CardFabricApi.LoadAnimation = true; this.PanBack.IsHitTestVisible = true; }, 0, true) }, "FrmDownloadInstall SelectPageSwitch", false); } } // Token: 0x060003B9 RID: 953 RVA: 0x00024F4C File Offset: 0x0002314C public void MinecraftSelected(MyListItem sender, object e) { this._AdapterVal = sender.Title; this.annotationVal = NewLateBinding.LateIndexGet(sender.Tag, new object[] { "url" }, null).ToString(); this._ReaderVal = sender.Logo; this.EnterSelectPage(); } // Token: 0x060003BA RID: 954 RVA: 0x00004399 File Offset: 0x00002599 private void CardMinecraft_PreviewSwap(object sender, ModBase.RouteEventArgs e) { this.ExitSelectPage(); e._HelperMapper = true; } // Token: 0x060003BB RID: 955 RVA: 0x00024F9C File Offset: 0x0002319C private void SetOptiFineInfoShow(string IsShow) { if (!Operators.ConditionalCompareObjectEqual(this.PanOptiFineInfo.Tag, IsShow, true)) { this.PanOptiFineInfo.Tag = IsShow; if (Operators.CompareString(IsShow, "True", true) == 0) { ModAni.AniStart(new ModAni.AniData[] { ModAni.AaTranslateY(this.PanOptiFineInfo, -((TranslateTransform)this.PanOptiFineInfo.RenderTransform).Y, 0x10E, 0x64, new ModAni.AniEaseOutBack(ModAni.AniEasePower.Middle), false), ModAni.AaOpacity(this.PanOptiFineInfo, 1.0 - this.PanOptiFineInfo.Opacity, 0x64, 0x5A, null, false) }, "SetOptiFineInfoShow", false); return; } ModAni.AniStart(new ModAni.AniData[] { ModAni.AaTranslateY(this.PanOptiFineInfo, 6.0 - ((TranslateTransform)this.PanOptiFineInfo.RenderTransform).Y, 0xC8, 0, null, false), ModAni.AaOpacity(this.PanOptiFineInfo, -this.PanOptiFineInfo.Opacity, 0x64, 0, null, false) }, "SetOptiFineInfoShow", false); } } // Token: 0x060003BC RID: 956 RVA: 0x000250BC File Offset: 0x000232BC private void SetLiteLoaderInfoShow(string IsShow) { if (!Operators.ConditionalCompareObjectEqual(this.PanLiteLoaderInfo.Tag, IsShow, true)) { this.PanLiteLoaderInfo.Tag = IsShow; if (Operators.CompareString(IsShow, "True", true) == 0) { ModAni.AniStart(new ModAni.AniData[] { ModAni.AaTranslateY(this.PanLiteLoaderInfo, -((TranslateTransform)this.PanLiteLoaderInfo.RenderTransform).Y, 0x10E, 0x64, new ModAni.AniEaseOutBack(ModAni.AniEasePower.Middle), false), ModAni.AaOpacity(this.PanLiteLoaderInfo, 1.0 - this.PanLiteLoaderInfo.Opacity, 0x64, 0x5A, null, false) }, "SetLiteLoaderInfoShow", false); return; } ModAni.AniStart(new ModAni.AniData[] { ModAni.AaTranslateY(this.PanLiteLoaderInfo, 6.0 - ((TranslateTransform)this.PanLiteLoaderInfo.RenderTransform).Y, 0xC8, 0, null, false), ModAni.AaOpacity(this.PanLiteLoaderInfo, -this.PanLiteLoaderInfo.Opacity, 0x64, 0, null, false) }, "SetLiteLoaderInfoShow", false); } } // Token: 0x060003BD RID: 957 RVA: 0x000251DC File Offset: 0x000233DC private void SetForgeInfoShow(string IsShow) { if (!Operators.ConditionalCompareObjectEqual(this.PanForgeInfo.Tag, IsShow, true)) { this.PanForgeInfo.Tag = IsShow; if (Operators.CompareString(IsShow, "True", true) == 0) { ModAni.AniStart(new ModAni.AniData[] { ModAni.AaTranslateY(this.PanForgeInfo, -((TranslateTransform)this.PanForgeInfo.RenderTransform).Y, 0x10E, 0x64, new ModAni.AniEaseOutBack(ModAni.AniEasePower.Middle), false), ModAni.AaOpacity(this.PanForgeInfo, 1.0 - this.PanForgeInfo.Opacity, 0x64, 0x5A, null, false) }, "SetForgeInfoShow", false); return; } ModAni.AniStart(new ModAni.AniData[] { ModAni.AaTranslateY(this.PanForgeInfo, 6.0 - ((TranslateTransform)this.PanForgeInfo.RenderTransform).Y, 0xC8, 0, null, false), ModAni.AaOpacity(this.PanForgeInfo, -this.PanForgeInfo.Opacity, 0x64, 0, null, false) }, "SetForgeInfoShow", false); } } // Token: 0x060003BE RID: 958 RVA: 0x000252FC File Offset: 0x000234FC private void SetFabricInfoShow(string IsShow) { if (!Operators.ConditionalCompareObjectEqual(this.PanFabricInfo.Tag, IsShow, true)) { this.PanFabricInfo.Tag = IsShow; if (Operators.CompareString(IsShow, "True", true) == 0) { ModAni.AniStart(new ModAni.AniData[] { ModAni.AaTranslateY(this.PanFabricInfo, -((TranslateTransform)this.PanFabricInfo.RenderTransform).Y, 0x10E, 0x64, new ModAni.AniEaseOutBack(ModAni.AniEasePower.Middle), false), ModAni.AaOpacity(this.PanFabricInfo, 1.0 - this.PanFabricInfo.Opacity, 0x64, 0x5A, null, false) }, "SetFabricInfoShow", false); return; } ModAni.AniStart(new ModAni.AniData[] { ModAni.AaTranslateY(this.PanFabricInfo, 6.0 - ((TranslateTransform)this.PanFabricInfo.RenderTransform).Y, 0xC8, 0, null, false), ModAni.AaOpacity(this.PanFabricInfo, -this.PanFabricInfo.Opacity, 0x64, 0, null, false) }, "SetFabricInfoShow", false); } } // Token: 0x060003BF RID: 959 RVA: 0x0002541C File Offset: 0x0002361C private void SetFabricApiInfoShow(string IsShow) { if (!Operators.ConditionalCompareObjectEqual(this.PanFabricApiInfo.Tag, IsShow, true)) { this.PanFabricApiInfo.Tag = IsShow; if (Operators.CompareString(IsShow, "True", true) == 0) { ModAni.AniStart(new ModAni.AniData[] { ModAni.AaTranslateY(this.PanFabricApiInfo, -((TranslateTransform)this.PanFabricApiInfo.RenderTransform).Y, 0x10E, 0x64, new ModAni.AniEaseOutBack(ModAni.AniEasePower.Middle), false), ModAni.AaOpacity(this.PanFabricApiInfo, 1.0 - this.PanFabricApiInfo.Opacity, 0x64, 0x5A, null, false) }, "SetFabricApiInfoShow", false); return; } ModAni.AniStart(new ModAni.AniData[] { ModAni.AaTranslateY(this.PanFabricApiInfo, 6.0 - ((TranslateTransform)this.PanFabricApiInfo.RenderTransform).Y, 0xC8, 0, null, false), ModAni.AaOpacity(this.PanFabricApiInfo, -this.PanFabricApiInfo.Opacity, 0x64, 0, null, false) }, "SetFabricApiInfoShow", false); } } // Token: 0x060003C0 RID: 960 RVA: 0x0002553C File Offset: 0x0002373C private void SelectReload() { if (this._AdapterVal != null) { this.SelectNameUpdate(); this.ItemSelect.Title = this.TextSelectName.Text; this.ItemSelect.Info = this.GetSelectInfo(); this.ItemSelect.Logo = this.GetSelectLogo(); this.LabMinecraft.Text = this._AdapterVal; this.ImgMinecraft.Source = new ModBitmap.MyBitmap(this._ReaderVal); string text = this.LoadOptiFineGetError(); this.CardOptiFine.singleton.Visibility = ((text == null) ? Visibility.Visible : Visibility.Collapsed); if (text != null) { this.CardOptiFine.IsSwaped = true; } this.SetOptiFineInfoShow(Conversions.ToString(this.CardOptiFine.IsSwaped)); if (this.regVal == null) { this.BtnOptiFineClear.Visibility = Visibility.Collapsed; this.ImgOptiFine.Visibility = Visibility.Collapsed; this.LabOptiFine.Text = (text ?? "点击选择"); this.LabOptiFine.Foreground = ModMain._EventFilter; } else { this.BtnOptiFineClear.Visibility = Visibility.Visible; this.ImgOptiFine.Visibility = Visibility.Visible; this.LabOptiFine.Text = this.regVal.m_RepositoryAlgo.Replace(this._AdapterVal + " ", ""); this.LabOptiFine.Foreground = ModMain.proxyFilter; } this.HintOptiFine.Visibility = ((this.m_MockVal != null) ? Visibility.Visible : Visibility.Collapsed); string text2 = this.LoadLiteLoaderGetError(); this.CardLiteLoader.singleton.Visibility = ((text2 == null) ? Visibility.Visible : Visibility.Collapsed); if (text2 != null) { this.CardLiteLoader.IsSwaped = true; } this.SetLiteLoaderInfoShow(Conversions.ToString(this.CardLiteLoader.IsSwaped)); if (this.definitionVal == null) { this.BtnLiteLoaderClear.Visibility = Visibility.Collapsed; this.ImgLiteLoader.Visibility = Visibility.Collapsed; this.LabLiteLoader.Text = (text2 ?? "点击选择"); this.LabLiteLoader.Foreground = ModMain._EventFilter; } else { this.BtnLiteLoaderClear.Visibility = Visibility.Visible; this.ImgLiteLoader.Visibility = Visibility.Visible; this.LabLiteLoader.Text = this.definitionVal.Inherit; this.LabLiteLoader.Foreground = ModMain.proxyFilter; } string text3 = this.LoadForgeGetError(); this.CardForge.singleton.Visibility = ((text3 == null) ? Visibility.Visible : Visibility.Collapsed); if (text3 != null) { this.CardForge.IsSwaped = true; } this.SetForgeInfoShow(Conversions.ToString(this.CardForge.IsSwaped)); if (this._ParamVal == null) { this.BtnForgeClear.Visibility = Visibility.Collapsed; this.ImgForge.Visibility = Visibility.Collapsed; this.LabForge.Text = (text3 ?? "点击选择"); this.LabForge.Foreground = ModMain._EventFilter; } else { this.BtnForgeClear.Visibility = Visibility.Visible; this.ImgForge.Visibility = Visibility.Visible; this.LabForge.Text = this._ParamVal._ConfigurationAlgo; this.LabForge.Foreground = ModMain.proxyFilter; } string text4 = this.LoadFabricGetError(); this.CardFabric.singleton.Visibility = ((text4 == null) ? Visibility.Visible : Visibility.Collapsed); if (text4 != null) { this.CardFabric.IsSwaped = true; } this.SetFabricInfoShow(Conversions.ToString(this.CardFabric.IsSwaped)); if (this.m_MockVal == null) { this.BtnFabricClear.Visibility = Visibility.Collapsed; this.ImgFabric.Visibility = Visibility.Collapsed; this.LabFabric.Text = (text4 ?? "点击选择"); this.LabFabric.Foreground = ModMain._EventFilter; } else { this.BtnFabricClear.Visibility = Visibility.Visible; this.ImgFabric.Visibility = Visibility.Visible; this.LabFabric.Text = this.m_MockVal.Replace("+build", ""); this.LabFabric.Foreground = ModMain.proxyFilter; } this.HintFabric.Visibility = ((this.regVal != null) ? Visibility.Visible : Visibility.Collapsed); string text5 = this.LoadFabricApiGetError(); this.CardFabricApi.singleton.Visibility = ((text5 == null) ? Visibility.Visible : Visibility.Collapsed); if (text5 != null || this.m_MockVal == null) { this.CardFabricApi.IsSwaped = true; } this.SetFabricApiInfoShow(Conversions.ToString(this.CardFabricApi.IsSwaped)); if (this.specificationVal == null) { this.BtnFabricApiClear.Visibility = Visibility.Collapsed; this.ImgFabricApi.Visibility = Visibility.Collapsed; this.LabFabricApi.Text = (text5 ?? "点击选择"); this.LabFabricApi.Foreground = ModMain._EventFilter; } else { this.BtnFabricApiClear.Visibility = Visibility.Visible; this.ImgFabricApi.Visibility = Visibility.Visible; this.LabFabricApi.Text = this.specificationVal.m_InterceptorAlgo.Split(new char[] { ']' })[1].Replace("Fabric API ", "").Replace(" build ", ".").Trim(); this.LabFabricApi.Foreground = ModMain.proxyFilter; } this.HintFabricAPI.Visibility = ((this.m_MockVal == null || this.specificationVal != null) ? Visibility.Collapsed : Visibility.Visible); } } // Token: 0x060003C1 RID: 961 RVA: 0x000043A8 File Offset: 0x000025A8 private void SelectClear() { this._AdapterVal = null; this.annotationVal = null; this._ReaderVal = null; this.regVal = null; this.definitionVal = null; this._ParamVal = null; this.m_MockVal = null; this.specificationVal = null; } // Token: 0x060003C2 RID: 962 RVA: 0x00025A8C File Offset: 0x00023C8C private string GetSelectName() { string text = this._AdapterVal; if (this.m_MockVal != null) { text = text + "-Fabric " + this.m_MockVal.Replace("+build", ""); } if (this._ParamVal != null) { text = text + "-Forge_" + this._ParamVal._ConfigurationAlgo; } if (this.definitionVal != null) { text += "-LiteLoader"; } if (this.regVal != null) { text = text + "-OptiFine_" + this.regVal.m_RepositoryAlgo.Replace(this._AdapterVal + " ", "").Replace(" ", "_"); } return text; } // Token: 0x060003C3 RID: 963 RVA: 0x00025B48 File Offset: 0x00023D48 private string GetSelectInfo() { string text = ""; if (this.m_MockVal != null) { text = text + ", Fabric " + this.m_MockVal.Replace("+build", ""); } if (this._ParamVal != null) { text = text + ", Forge " + this._ParamVal._ConfigurationAlgo; } if (this.definitionVal != null) { text += ", LiteLoader"; } if (this.regVal != null) { text = text + ", OptiFine " + this.regVal.m_RepositoryAlgo.Replace(this._AdapterVal + " ", ""); } if (Operators.CompareString(text, "", true) == 0) { text = ", 无附加安装"; } return text.TrimStart(", ".ToCharArray()); } // Token: 0x060003C4 RID: 964 RVA: 0x00025C14 File Offset: 0x00023E14 private string GetSelectLogo() { string result; if (this.m_MockVal != null) { result = "pack://application:,,,/images/Blocks/Fabric.png"; } else if (this._ParamVal != null) { result = "pack://application:,,,/images/Blocks/Anvil.png"; } else if (this.definitionVal != null) { result = "pack://application:,,,/images/Blocks/Egg.png"; } else if (this.regVal != null) { result = "pack://application:,,,/images/Blocks/GrassPath.png"; } else { result = this._ReaderVal; } return result; } // Token: 0x060003C5 RID: 965 RVA: 0x000043E2 File Offset: 0x000025E2 private void SelectNameUpdate() { if (!this.m_DicVal && !this._SchemaVal) { this._SchemaVal = true; this.TextSelectName.Text = this.GetSelectName(); this._SchemaVal = false; } } // Token: 0x060003C6 RID: 966 RVA: 0x00004413 File Offset: 0x00002613 private void TextSelectName_TextChanged(object sender, TextChangedEventArgs e) { if (!this._SchemaVal) { this.m_DicVal = true; this.SelectReload(); } } // Token: 0x060003C7 RID: 967 RVA: 0x0000442A File Offset: 0x0000262A private void TextSelectName_ValidateChanged(object sender, EventArgs e) { this.BtnSelectStart.IsEnabled = (Operators.CompareString(this.TextSelectName.ValidateResult, "", true) == 0); } // Token: 0x060003C8 RID: 968 RVA: 0x00004450 File Offset: 0x00002650 private void LoadMinecraft_Click(object sender, MouseButtonEventArgs e) { if (this.LoadMinecraft.State.LoadingState == MyLoading.MyLoadingState.Error) { PageDownloadClient.RefreshLoader(); } } // Token: 0x060003C9 RID: 969 RVA: 0x00025C6C File Offset: 0x00023E6C private void LoadMinecraft_State(object sender, MyLoading.MyLoadingState state) { object left = NewLateBinding.LateGet(this.LoadMinecraft.State, null, "State", new object[0], null, null, null); if (Operators.ConditionalCompareObjectEqual(left, ModBase.LoadState.Loading, true)) { this.LoadMinecraft_OnStart(); return; } if (Operators.ConditionalCompareObjectEqual(left, ModBase.LoadState.Finished, true)) { this.LoadMinecraft_OnFinish(); } } // Token: 0x060003CA RID: 970 RVA: 0x00025CC4 File Offset: 0x00023EC4 private void LoadMinecraft_OnStart() { this.PanLoad.Visibility = Visibility.Visible; this.ExitSelectPage(); ModAni.AniStart(new ModAni.AniData[] { ModAni.AaOpacity(this.PanLoad, 1.0 - this.PanLoad.Opacity, 0x96, 0, null, false), ModAni.AaOpacity(this.PanBack, -this.PanBack.Opacity, 0x96, 0, null, false), ModAni.AaCode(delegate { this.PanBack.Visibility = Visibility.Collapsed; this.PanMinecraft.Children.Clear(); }, 0, true) }, "FrmDownloadInstall LoadMain Switch", false); } // Token: 0x060003CB RID: 971 RVA: 0x00025D64 File Offset: 0x00023F64 private void LoadMinecraft_OnFinish() { checked { try { Dictionary<string, List<JObject>> dictionary = new Dictionary<string, List<JObject>> { { "正式版", new List<JObject>() }, { "预览版", new List<JObject>() }, { "远古版", new List<JObject>() }, { "愚人节版", new List<JObject>() } }; JArray jarray = (JArray)ModDownload._AlgoIterator.Output.Value["versions"]; try { foreach (JToken jtoken in jarray) { JObject jobject = (JObject)jtoken; string text = (string)jobject["type"]; string left = text; if (Operators.CompareString(left, "release", true) == 0) { text = "正式版"; } else if (Operators.CompareString(left, "snapshot", true) == 0) { text = "预览版"; if (jobject["id"].ToString().StartsWith("1.") && !jobject["id"].ToString().ToLower().Contains("combat") && !jobject["id"].ToString().ToLower().Contains("rc") && !jobject["id"].ToString().ToLower().Contains("experimental") && !jobject["id"].ToString().ToLower().Contains("pre")) { text = "正式版"; jobject["type"] = "release"; } string left2 = jobject["id"].ToString().ToLower(); if (Operators.CompareString(left2, "20w14infinite", true) != 0 && Operators.CompareString(left2, "20w14∞", true) != 0) { if (Operators.CompareString(left2, "3d shareware v1.34", true) == 0 || Operators.CompareString(left2, "1.rv-pre1", true) == 0 || Operators.CompareString(left2, "15w14a", true) == 0 || Operators.CompareString(left2, "2.0", true) == 0) { text = "愚人节版"; jobject["type"] = "special"; jobject.Add("lore", ModMinecraft.GetMcFoolName((string)jobject["id"])); } } else { text = "愚人节版"; jobject["id"] = "20w14∞"; jobject["type"] = "special"; jobject.Add("lore", ModMinecraft.GetMcFoolName((string)jobject["id"])); } } else if (Operators.CompareString(left, "special", true) == 0) { text = "愚人节版"; } else { text = "远古版"; } dictionary[text].Add(jobject); } } finally { IEnumerator<JToken> enumerator; if (enumerator != null) { enumerator.Dispose(); } } int num = dictionary.Keys.Count - 1; for (int i = 0; i <= num; i++) { dictionary[dictionary.Keys.ElementAtOrDefault(i)] = ModBase.Sort<JObject>(dictionary.Values.ElementAtOrDefault(i), (PageDownloadInstall._Closure$__.$IR35-2 == null) ? (PageDownloadInstall._Closure$__.$IR35-2 = ((object a0, object a1) => ((PageDownloadInstall._Closure$__.$I35-0 == null) ? (PageDownloadInstall._Closure$__.$I35-0 = ((JObject Left, JObject Right) => DateTime.Compare(Left["releaseTime"].Value<DateTime>(), Right["releaseTime"].Value<DateTime>()) > 0)) : PageDownloadInstall._Closure$__.$I35-0)((JObject)a0, (JObject)a1))) : PageDownloadInstall._Closure$__.$IR35-2); } this.PanMinecraft.Children.Clear(); MyCard myCard = new MyCard(); myCard.Title = "最新版本"; myCard.Margin = new Thickness(0.0, 15.0, 0.0, 15.0); myCard.InitFactory(2); MyCard myCard2 = myCard; List<JObject> list = new List<JObject>(); JObject jobject2 = (JObject)dictionary["正式版"][0].DeepClone(); jobject2["lore"] = "最新正式版,发布于 " + jobject2["releaseTime"].ToString(); list.Add(jobject2); if (DateTime.Compare(dictionary["正式版"][0]["releaseTime"].Value<DateTime>(), dictionary["预览版"][0]["releaseTime"].Value<DateTime>()) < 0) { JObject jobject3 = (JObject)dictionary["预览版"][0].DeepClone(); jobject3["lore"] = "最新预览版,发布于 " + jobject3["releaseTime"].ToString(); list.Add(jobject3); } StackPanel element = new StackPanel { Margin = new Thickness(20.0, 40.0, 18.0, 0.0), VerticalAlignment = VerticalAlignment.Top, RenderTransform = new TranslateTransform(0.0, 0.0), Tag = list }; MyCard.StackInstall(ref element, 7, ""); myCard2.Children.Add(element); this.PanMinecraft.Children.Insert(0, myCard2); try { foreach (KeyValuePair<string, List<JObject>> keyValuePair in dictionary) { if (keyValuePair.Value.Count != 0) { MyCard myCard3 = new MyCard(); myCard3.Title = keyValuePair.Key + " (" + Conversions.ToString(keyValuePair.Value.Count) + ")"; myCard3.Margin = new Thickness(0.0, 0.0, 0.0, 15.0); myCard3.InitFactory(7); MyCard myCard4 = myCard3; StackPanel stackPanel = new StackPanel { Margin = new Thickness(20.0, 40.0, 18.0, 0.0), VerticalAlignment = VerticalAlignment.Top, RenderTransform = new TranslateTransform(0.0, 0.0), Tag = keyValuePair.Value }; myCard4.Children.Add(stackPanel); myCard4.thread = stackPanel; myCard4.IsSwaped = true; this.PanMinecraft.Children.Add(myCard4); } } } finally { Dictionary<string, List<JObject>>.Enumerator enumerator2; ((IDisposable)enumerator2).Dispose(); } } catch (Exception ex) { ModBase.Log(ex, "可视化安装版本列表出错", ModBase.LogLevel.Feedback, "出现错误"); } this.PanBack.Visibility = Visibility.Visible; } ModAni.AniStart(new ModAni.AniData[] { ModAni.AaOpacity(this.PanLoad, -this.PanLoad.Opacity, 0x96, 0, null, false), ModAni.AaOpacity(this.PanBack, 1.0 - this.PanBack.Opacity, 0x96, 0, null, false), ModAni.AaCode(delegate { this.PanLoad.Visibility = Visibility.Collapsed; }, 0, true) }, "FrmDownloadInstall LoadMain Switch", false); } // Token: 0x060003CC RID: 972 RVA: 0x000264EC File Offset: 0x000246EC private string LoadOptiFineGetError() { string result; if (this.LoadOptiFine.State.LoadingState == MyLoading.MyLoadingState.Run) { result = "正在获取版本列表……"; } else if (this.LoadOptiFine.State.LoadingState == MyLoading.MyLoadingState.Error) { result = Conversions.ToString(Operators.ConcatenateObject("获取版本列表失败:", NewLateBinding.LateGet(NewLateBinding.LateGet(this.LoadOptiFine.State, null, "Error", new object[0], null, null, null), null, "Message", new object[0], null, null, null))); } else { try { List<ModDownload.DlOptiFineListEntry>.Enumerator enumerator = ModDownload.issuerIterator.Output.Value.GetEnumerator(); while (enumerator.MoveNext()) { if (enumerator.Current.m_RepositoryAlgo.StartsWith(this._AdapterVal + " ")) { if (this._ParamVal != null && ModMinecraft.VersionSortInteger(this._AdapterVal, "1.13") >= 0 && ModMinecraft.VersionSortInteger("1.14.3", this._AdapterVal) >= 0) { return "与 Forge 不兼容"; } return null; } } } finally { List<ModDownload.DlOptiFineListEntry>.Enumerator enumerator; ((IDisposable)enumerator).Dispose(); } result = "没有可用版本"; } return result; } // Token: 0x060003CD RID: 973 RVA: 0x0000446A File Offset: 0x0000266A private void CardOptiFine_PreviewSwap(object sender, ModBase.RouteEventArgs e) { if (this.LoadOptiFineGetError() != null) { e._HelperMapper = true; } } // Token: 0x060003CE RID: 974 RVA: 0x00026618 File Offset: 0x00024818 private void OptiFine_Loaded() { try { if (ModDownload.issuerIterator.State == ModBase.LoadState.Finished) { List<ModDownload.DlOptiFineListEntry> list = new List<ModDownload.DlOptiFineListEntry>(); try { foreach (ModDownload.DlOptiFineListEntry dlOptiFineListEntry in ModDownload.issuerIterator.Output.Value) { if (dlOptiFineListEntry.m_RepositoryAlgo.StartsWith(this._AdapterVal + " ")) { list.Add(dlOptiFineListEntry); } } } finally { List<ModDownload.DlOptiFineListEntry>.Enumerator enumerator; ((IDisposable)enumerator).Dispose(); } if (list.Count != 0) { list = ModBase.Sort<ModDownload.DlOptiFineListEntry>(list, (PageDownloadInstall._Closure$__.$IR38-3 == null) ? (PageDownloadInstall._Closure$__.$IR38-3 = ((object a0, object a1) => ((PageDownloadInstall._Closure$__.$I38-0 == null) ? (PageDownloadInstall._Closure$__.$I38-0 = ((ModDownload.DlOptiFineListEntry Left, ModDownload.DlOptiFineListEntry Right) => ModMinecraft.VersionSortBoolean(Left.m_RepositoryAlgo, Right.m_RepositoryAlgo))) : PageDownloadInstall._Closure$__.$I38-0)((ModDownload.DlOptiFineListEntry)a0, (ModDownload.DlOptiFineListEntry)a1))) : PageDownloadInstall._Closure$__.$IR38-3); this.PanOptiFine.Children.Clear(); try { foreach (ModDownload.DlOptiFineListEntry entry in list) { this.PanOptiFine.Children.Add(ModDownloadLib.OptiFineDownloadListItem(entry, delegate(object sender, MouseButtonEventArgs e) { this.OptiFine_Selected((MyListItem)sender, e); }, false)); } } finally { List<ModDownload.DlOptiFineListEntry>.Enumerator enumerator2; ((IDisposable)enumerator2).Dispose(); } } } } catch (Exception ex) { ModBase.Log(ex, "可视化 OptiFine 安装版本列表出错", ModBase.LogLevel.Feedback, "出现错误"); } } // Token: 0x060003CF RID: 975 RVA: 0x0000447B File Offset: 0x0000267B private void OptiFine_Selected(MyListItem sender, EventArgs e) { this.regVal = (ModDownload.DlOptiFineListEntry)sender.Tag; this.CardOptiFine.IsSwaped = true; this.SelectReload(); } // Token: 0x060003D0 RID: 976 RVA: 0x000044A0 File Offset: 0x000026A0 private void OptiFine_Clear(object sender, MouseButtonEventArgs e) { this.regVal = null; this.CardOptiFine.IsSwaped = true; e.Handled = true; this.SelectReload(); } // Token: 0x060003D1 RID: 977 RVA: 0x000267A0 File Offset: 0x000249A0 private string LoadLiteLoaderGetError() { string result; if (this._AdapterVal.Contains("1.") && ModBase.Val(this._AdapterVal.Split(new char[] { '.' })[1]) <= 12.0) { if (this.LoadLiteLoader.State.LoadingState == MyLoading.MyLoadingState.Run) { result = "正在获取版本列表……"; } else if (this.LoadLiteLoader.State.LoadingState == MyLoading.MyLoadingState.Error) { result = Conversions.ToString(Operators.ConcatenateObject("获取版本列表失败:", NewLateBinding.LateGet(NewLateBinding.LateGet(this.LoadLiteLoader.State, null, "Error", new object[0], null, null, null), null, "Message", new object[0], null, null, null))); } else { try { List<ModDownload.DlLiteLoaderListEntry>.Enumerator enumerator = ModDownload.m_BridgeIterator.Output.Value.GetEnumerator(); while (enumerator.MoveNext()) { if (Operators.CompareString(enumerator.Current.Inherit, this._AdapterVal, true) == 0) { return null; } } } finally { List<ModDownload.DlLiteLoaderListEntry>.Enumerator enumerator; ((IDisposable)enumerator).Dispose(); } result = "没有可用版本"; } } else { result = "没有可用版本"; } return result; } // Token: 0x060003D2 RID: 978 RVA: 0x000044C2 File Offset: 0x000026C2 private void CardLiteLoader_PreviewSwap(object sender, ModBase.RouteEventArgs e) { if (this.LoadLiteLoaderGetError() != null) { e._HelperMapper = true; } } // Token: 0x060003D3 RID: 979 RVA: 0x000268D0 File Offset: 0x00024AD0 private void LiteLoader_Loaded() { try { if (ModDownload.m_BridgeIterator.State == ModBase.LoadState.Finished) { List<ModDownload.DlLiteLoaderListEntry> list = new List<ModDownload.DlLiteLoaderListEntry>(); try { foreach (ModDownload.DlLiteLoaderListEntry dlLiteLoaderListEntry in ModDownload.m_BridgeIterator.Output.Value) { if (Operators.CompareString(dlLiteLoaderListEntry.Inherit, this._AdapterVal, true) == 0) { list.Add(dlLiteLoaderListEntry); } } } finally { List<ModDownload.DlLiteLoaderListEntry>.Enumerator enumerator; ((IDisposable)enumerator).Dispose(); } if (list.Count != 0) { this.PanLiteLoader.Children.Clear(); try { foreach (ModDownload.DlLiteLoaderListEntry entry in list) { this.PanLiteLoader.Children.Add(ModDownloadLib.LiteLoaderDownloadListItem(entry, delegate(object sender, MouseButtonEventArgs e) { this.LiteLoader_Selected((MyListItem)sender, e); }, false)); } } finally { List<ModDownload.DlLiteLoaderListEntry>.Enumerator enumerator2; ((IDisposable)enumerator2).Dispose(); } } } } catch (Exception ex) { ModBase.Log(ex, "可视化 LiteLoader 安装版本列表出错", ModBase.LogLevel.Feedback, "出现错误"); } } // Token: 0x060003D4 RID: 980 RVA: 0x000044D3 File Offset: 0x000026D3 private void LiteLoader_Selected(MyListItem sender, EventArgs e) { this.definitionVal = (ModDownload.DlLiteLoaderListEntry)sender.Tag; this.CardLiteLoader.IsSwaped = true; this.SelectReload(); } // Token: 0x060003D5 RID: 981 RVA: 0x000044F8 File Offset: 0x000026F8 private void LiteLoader_Clear(object sender, MouseButtonEventArgs e) { this.definitionVal = null; this.CardLiteLoader.IsSwaped = true; e.Handled = true; this.SelectReload(); } // Token: 0x060003D6 RID: 982 RVA: 0x00026A00 File Offset: 0x00024C00 private string LoadForgeGetError() { string result; if (!this._AdapterVal.StartsWith("1.")) { result = "没有可用版本"; } else if (!this.LoadForge.State.IsLoader) { result = "正在获取版本列表……"; } else { ModLoader.LoaderTask<string, List<ModDownload.DlForgeVersionEntry>> loaderTask = (ModLoader.LoaderTask<string, List<ModDownload.DlForgeVersionEntry>>)this.LoadForge.State; if (Operators.CompareString(this._AdapterVal, loaderTask.Input, true) != 0) { result = "正在获取版本列表……"; } else if (loaderTask.State == ModBase.LoadState.Loading) { result = "正在获取版本列表……"; } else if (loaderTask.State == ModBase.LoadState.Failed) { string message = loaderTask.Error.Message; if (message.Contains("没有可用版本")) { result = "没有可用版本"; } else { result = "获取版本列表失败:" + message; } } else if (loaderTask.State != ModBase.LoadState.Finished) { result = "获取版本列表失败:未知错误,状态为 " + ModBase.GetStringFromEnum(loaderTask.State); } else { try { foreach (ModDownload.DlForgeVersionEntry dlForgeVersionEntry in loaderTask.Output) { if (Operators.CompareString(dlForgeVersionEntry._CollectionAlgo, "universal", true) != 0 && Operators.CompareString(dlForgeVersionEntry._CollectionAlgo, "client", true) != 0) { if (this.m_MockVal != null) { return "与 Fabric 不兼容"; } if (this.regVal != null && ModMinecraft.VersionSortInteger(this._AdapterVal, "1.13") >= 0 && ModMinecraft.VersionSortInteger("1.14.3", this._AdapterVal) >= 0) { return "与 OptiFine 不兼容"; } return null; } } } finally { List<ModDownload.DlForgeVersionEntry>.Enumerator enumerator; ((IDisposable)enumerator).Dispose(); } result = "该版本不支持自动安装"; } } return result; } // Token: 0x060003D7 RID: 983 RVA: 0x0000451A File Offset: 0x0000271A private void CardForge_PreviewSwap(object sender, ModBase.RouteEventArgs e) { if (this.LoadForgeGetError() != null) { e._HelperMapper = true; } } // Token: 0x060003D8 RID: 984 RVA: 0x00026BAC File Offset: 0x00024DAC private void Forge_Loaded() { try { if (this.LoadForge.State.IsLoader) { ModLoader.LoaderTask<string, List<ModDownload.DlForgeVersionEntry>> loaderTask = (ModLoader.LoaderTask<string, List<ModDownload.DlForgeVersionEntry>>)this.LoadForge.State; if (Operators.CompareString(this._AdapterVal, loaderTask.Input, true) == 0) { if (loaderTask.State == ModBase.LoadState.Finished) { List<ModDownload.DlForgeVersionEntry> list = new List<ModDownload.DlForgeVersionEntry>(); list.AddRange(loaderTask.Output); if (loaderTask.Output.Count != 0) { this.PanForge.Children.Clear(); list = ModBase.Sort<ModDownload.DlForgeVersionEntry>(list, (PageDownloadInstall._Closure$__.$IR48-6 == null) ? (PageDownloadInstall._Closure$__.$IR48-6 = ((object a0, object a1) => ((PageDownloadInstall._Closure$__.$I48-0 == null) ? (PageDownloadInstall._Closure$__.$I48-0 = ((ModDownload.DlForgeVersionEntry Left, ModDownload.DlForgeVersionEntry Right) => new Version(Left._ConfigurationAlgo) > new Version(Right._ConfigurationAlgo))) : PageDownloadInstall._Closure$__.$I48-0)((ModDownload.DlForgeVersionEntry)a0, (ModDownload.DlForgeVersionEntry)a1))) : PageDownloadInstall._Closure$__.$IR48-6); ModDownloadLib.ForgeDownloadListItemPreload(this.PanForge, list, delegate(object sender, MouseButtonEventArgs e) { this.Forge_Selected((MyListItem)sender, e); }, false); try { foreach (ModDownload.DlForgeVersionEntry dlForgeVersionEntry in list) { if (Operators.CompareString(dlForgeVersionEntry._CollectionAlgo, "universal", true) != 0 && Operators.CompareString(dlForgeVersionEntry._CollectionAlgo, "client", true) != 0) { this.PanForge.Children.Add(ModDownloadLib.ForgeDownloadListItem(dlForgeVersionEntry, delegate(object sender, MouseButtonEventArgs e) { this.Forge_Selected((MyListItem)sender, e); }, false)); } } } finally { List<ModDownload.DlForgeVersionEntry>.Enumerator enumerator; ((IDisposable)enumerator).Dispose(); } } } } } } catch (Exception ex) { ModBase.Log(ex, "可视化 Forge 安装版本列表出错", ModBase.LogLevel.Feedback, "出现错误"); } } // Token: 0x060003D9 RID: 985 RVA: 0x0000452B File Offset: 0x0000272B private void Forge_Selected(MyListItem sender, EventArgs e) { this._ParamVal = (ModDownload.DlForgeVersionEntry)sender.Tag; this.CardForge.IsSwaped = true; this.SelectReload(); } // Token: 0x060003DA RID: 986 RVA: 0x00004550 File Offset: 0x00002750 private void Forge_Clear(object sender, MouseButtonEventArgs e) { this._ParamVal = null; this.CardForge.IsSwaped = true; e.Handled = true; this.SelectReload(); } // Token: 0x060003DB RID: 987 RVA: 0x00026D4C File Offset: 0x00024F4C private string LoadFabricGetError() { string result; if (this.LoadFabric.State.LoadingState == MyLoading.MyLoadingState.Run) { result = "正在获取版本列表……"; } else if (this.LoadFabric.State.LoadingState == MyLoading.MyLoadingState.Error) { result = Conversions.ToString(Operators.ConcatenateObject("获取版本列表失败:", NewLateBinding.LateGet(NewLateBinding.LateGet(this.LoadFabric.State, null, "Error", new object[0], null, null, null), null, "Message", new object[0], null, null, null))); } else { try { IEnumerator<JToken> enumerator = ((IEnumerable<JToken>)ModDownload.m_ObjectIterator.Output.Value["game"]).GetEnumerator(); while (enumerator.MoveNext()) { if (Operators.CompareString(((JObject)enumerator.Current)["version"].ToString(), this._AdapterVal, true) == 0) { if (this._ParamVal != null) { return "与 Forge 不兼容"; } return null; } } } finally { IEnumerator<JToken> enumerator; if (enumerator != null) { enumerator.Dispose(); } } result = "没有可用版本"; } return result; } // Token: 0x060003DC RID: 988 RVA: 0x00004572 File Offset: 0x00002772 private void CardFabric_PreviewSwap(object sender, ModBase.RouteEventArgs e) { if (this.LoadFabricGetError() != null) { e._HelperMapper = true; } } // Token: 0x060003DD RID: 989 RVA: 0x00026E58 File Offset: 0x00025058 private void Fabric_Loaded() { try { if (ModDownload.m_ObjectIterator.State == ModBase.LoadState.Finished) { JArray jarray = (JArray)ModDownload.m_ObjectIterator.Output.Value["loader"]; if (jarray.Count != 0) { this.PanFabric.Children.Clear(); try { foreach (JToken jtoken in jarray) { this.PanFabric.Children.Add(ModDownloadLib.FabricDownloadListItem((JObject)jtoken, delegate(object sender, MouseButtonEventArgs e) { this.Fabric_Selected((MyListItem)sender, e); })); } } finally { IEnumerator<JToken> enumerator; if (enumerator != null) { enumerator.Dispose(); } } } } } catch (Exception ex) { ModBase.Log(ex, "可视化 Fabric 安装版本列表出错", ModBase.LogLevel.Feedback, "出现错误"); } } // Token: 0x060003DE RID: 990 RVA: 0x00026F3C File Offset: 0x0002513C private void Fabric_Selected(MyListItem sender, EventArgs e) { this.m_MockVal = NewLateBinding.LateIndexGet(sender.Tag, new object[] { "version" }, null).ToString(); this.FabricApi_Loaded(); this.CardFabric.IsSwaped = true; this.SelectReload(); if (Conversions.ToBoolean(Operators.NotObject(ModBase._BaseRule.Get("HintInstallFabricApi", null)))) { ModBase._BaseRule.Set("HintInstallFabricApi", true, false, null); ModMain.Hint("安装 Fabric 时通常还需要安装 Fabric API,在选择 Fabric 后就会显示其安装选项!", ModMain.HintType.Info, true); } } // Token: 0x060003DF RID: 991 RVA: 0x00004583 File Offset: 0x00002783 private void Fabric_Clear(object sender, MouseButtonEventArgs e) { this.m_MockVal = null; this.specificationVal = null; this.CardFabric.IsSwaped = true; e.Handled = true; this.SelectReload(); } // Token: 0x060003E0 RID: 992 RVA: 0x00026FC8 File Offset: 0x000251C8 private bool IsSuitableFabricApi(string DisplayName, string MinecraftVersion) { checked { bool result; try { if (DisplayName != null && MinecraftVersion != null) { DisplayName = DisplayName.ToLower(); MinecraftVersion = MinecraftVersion.ToLower(); if (DisplayName.StartsWith("[" + MinecraftVersion + "]")) { result = true; } else if (!DisplayName.Contains("/")) { result = false; } else { List<string> list = ModBase.RegexSearch(DisplayName.Split(new char[] { ']' })[0], "[a-z/]+|[0-9/]+", RegexOptions.None); List<string> list2 = ModBase.RegexSearch(MinecraftVersion.Split(new char[] { ']' })[0], "[a-z/]+|[0-9/]+", RegexOptions.None); int num = 0; while (list.Count - 1 >= num || list2.Count - 1 >= num) { string text = (list.Count - 1 < num) ? "-1" : list[num]; string text2 = (list2.Count - 1 < num) ? "-1" : list2[num]; if (!text.Contains("/")) { if (Operators.CompareString(text, text2, true) != 0) { return false; } } else if (!text.Contains(text2)) { return false; } num++; } result = true; } } else { result = false; } } catch (Exception ex) { ModBase.Log(ex, string.Concat(new string[] { "判断 Fabric API 版本适配性出错(", DisplayName, ", ", MinecraftVersion, ")" }), ModBase.LogLevel.Debug, "出现错误"); result = false; } return result; } } // Token: 0x060003E1 RID: 993 RVA: 0x0002715C File Offset: 0x0002535C private string LoadFabricApiGetError() { string result; if (this.LoadFabricApi.State.LoadingState == MyLoading.MyLoadingState.Run) { result = "正在获取版本列表……"; } else if (this.LoadFabricApi.State.LoadingState == MyLoading.MyLoadingState.Error) { result = Conversions.ToString(Operators.ConcatenateObject("获取版本列表失败:", NewLateBinding.LateGet(NewLateBinding.LateGet(this.LoadFabricApi.State, null, "Error", new object[0], null, null, null), null, "Message", new object[0], null, null, null))); } else if (this.m_MockVal == null) { result = "需要安装 Fabric"; } else { try { foreach (ModDownload.DlCfFile dlCfFile in ModDownload._VisitorIterator.Output) { if (this.IsSuitableFabricApi(dlCfFile.m_InterceptorAlgo, this._AdapterVal)) { return null; } } } finally { List<ModDownload.DlCfFile>.Enumerator enumerator; ((IDisposable)enumerator).Dispose(); } result = "没有可用版本"; } return result; } // Token: 0x060003E2 RID: 994 RVA: 0x000045AC File Offset: 0x000027AC private void CardFabricApi_PreviewSwap(object sender, ModBase.RouteEventArgs e) { if (this.LoadFabricApiGetError() != null) { e._HelperMapper = true; } } // Token: 0x060003E3 RID: 995 RVA: 0x00027254 File Offset: 0x00025454 private void FabricApi_Loaded() { try { if (ModDownload._VisitorIterator.State == ModBase.LoadState.Finished) { if (this._AdapterVal != null && this.m_MockVal != null) { List<ModDownload.DlCfFile> list = new List<ModDownload.DlCfFile>(); try { foreach (ModDownload.DlCfFile dlCfFile in ModDownload._VisitorIterator.Output) { if (this.IsSuitableFabricApi(dlCfFile.m_InterceptorAlgo, this._AdapterVal)) { if (!dlCfFile.m_InterceptorAlgo.StartsWith("[")) { ModBase.Log("[Download] 已特判修改 Fabric API 显示名:" + dlCfFile.m_InterceptorAlgo, ModBase.LogLevel.Debug, "出现错误"); dlCfFile.m_InterceptorAlgo = "[" + this._AdapterVal + "] " + dlCfFile.m_InterceptorAlgo; } list.Add(dlCfFile); } } } finally { List<ModDownload.DlCfFile>.Enumerator enumerator; ((IDisposable)enumerator).Dispose(); } if (list.Count != 0) { list = ModBase.Sort<ModDownload.DlCfFile>(list, (PageDownloadInstall._Closure$__.$IR59-10 == null) ? (PageDownloadInstall._Closure$__.$IR59-10 = ((object a0, object a1) => ((PageDownloadInstall._Closure$__.$I59-0 == null) ? (PageDownloadInstall._Closure$__.$I59-0 = ((ModDownload.DlCfFile Left, ModDownload.DlCfFile Right) => DateTime.Compare(Left.invocationAlgo, Right.invocationAlgo) > 0)) : PageDownloadInstall._Closure$__.$I59-0)((ModDownload.DlCfFile)a0, (ModDownload.DlCfFile)a1))) : PageDownloadInstall._Closure$__.$IR59-10); this.PanFabricApi.Children.Clear(); try { foreach (ModDownload.DlCfFile dlCfFile2 in list) { if (this.IsSuitableFabricApi(dlCfFile2.m_InterceptorAlgo, this._AdapterVal)) { this.PanFabricApi.Children.Add(ModDownloadLib.FabricApiDownloadListItem(dlCfFile2, delegate(object sender, MouseButtonEventArgs e) { this.FabricApi_Selected((MyListItem)sender, e); })); } } } finally { List<ModDownload.DlCfFile>.Enumerator enumerator2; ((IDisposable)enumerator2).Dispose(); } } } } } catch (Exception ex) { ModBase.Log(ex, "可视化 Fabric API 安装版本列表出错", ModBase.LogLevel.Feedback, "出现错误"); } } // Token: 0x060003E4 RID: 996 RVA: 0x000045BD File Offset: 0x000027BD private void FabricApi_Selected(MyListItem sender, EventArgs e) { this.specificationVal = (ModDownload.DlCfFile)sender.Tag; this.CardFabricApi.IsSwaped = true; this.SelectReload(); } // Token: 0x060003E5 RID: 997 RVA: 0x000045E2 File Offset: 0x000027E2 private void FabricApi_Clear(object sender, MouseButtonEventArgs e) { this.specificationVal = null; this.CardFabricApi.IsSwaped = true; e.Handled = true; this.SelectReload(); } // Token: 0x060003E6 RID: 998 RVA: 0x00027448 File Offset: 0x00025648 private void BtnSelectStart_Click(object sender, EventArgs e) { if (((this._ParamVal == null && this.m_MockVal == null) || (!Operators.ConditionalCompareObjectEqual(ModBase._BaseRule.Get("LaunchArgumentIndie", null), 0, true) && !Operators.ConditionalCompareObjectEqual(ModBase._BaseRule.Get("LaunchArgumentIndie", null), 2, true)) || ModMain.MyMsgBox("你尚未开启版本隔离,这会导致多个 MC 共用同一个 Mod 文件夹。\r\n因此在切换 MC 版本时,MC 会因为读取到与当前版本不符的 Mod 而崩溃。\r\nPCL2 推荐你在开始下载前,在 设置 → 版本隔离 中开启版本隔离选项!", "版本隔离提示", "取消下载", "继续", "", false, true, false) != 1) && ModDownloadLib.McInstall(new ModDownloadLib.McInstallRequest { m_CandidateRule = this.TextSelectName.Text, contextRule = this.annotationVal, m_DescriptorRule = this._AdapterVal, _TokenizerRule = this.regVal, tagRule = this._ParamVal, _InitializerRule = this.m_MockVal, _PropertyRule = this.specificationVal, m_WatcherRule = this.definitionVal })) { this.ExitSelectPage(); } } // Token: 0x17000077 RID: 119 // (get) Token: 0x060003E7 RID: 999 RVA: 0x00004604 File Offset: 0x00002804 // (set) Token: 0x060003E8 RID: 1000 RVA: 0x0000460C File Offset: 0x0000280C internal virtual MyScrollViewer PanBack { get; [MethodImpl(MethodImplOptions.Synchronized)] set; } // Token: 0x17000078 RID: 120 // (get) Token: 0x060003E9 RID: 1001 RVA: 0x00004615 File Offset: 0x00002815 // (set) Token: 0x060003EA RID: 1002 RVA: 0x0000461D File Offset: 0x0000281D internal virtual VirtualizingStackPanel PanMinecraft { get; [MethodImpl(MethodImplOptions.Synchronized)] set; } // Token: 0x17000079 RID: 121 // (get) Token: 0x060003EB RID: 1003 RVA: 0x00004626 File Offset: 0x00002826 // (set) Token: 0x060003EC RID: 1004 RVA: 0x0000462E File Offset: 0x0000282E internal virtual StackPanel PanSelect { get; [MethodImpl(MethodImplOptions.Synchronized)] set; } // Token: 0x1700007A RID: 122 // (get) Token: 0x060003ED RID: 1005 RVA: 0x00004637 File Offset: 0x00002837 // (set) Token: 0x060003EE RID: 1006 RVA: 0x0000463F File Offset: 0x0000283F internal virtual MyHint HintFabricAPI { get; [MethodImpl(MethodImplOptions.Synchronized)] set; } // Token: 0x1700007B RID: 123 // (get) Token: 0x060003EF RID: 1007 RVA: 0x00004648 File Offset: 0x00002848 // (set) Token: 0x060003F0 RID: 1008 RVA: 0x00004650 File Offset: 0x00002850 internal virtual MyListItem ItemSelect { get; [MethodImpl(MethodImplOptions.Synchronized)] set; } // Token: 0x1700007C RID: 124 // (get) Token: 0x060003F1 RID: 1009 RVA: 0x00004659 File Offset: 0x00002859 // (set) Token: 0x060003F2 RID: 1010 RVA: 0x0002753C File Offset: 0x0002573C internal virtual MyButton BtnSelectStart { [CompilerGenerated] get { return this._RulesVal; } [CompilerGenerated] [MethodImpl(MethodImplOptions.Synchronized)] set { MyButton.ClickEventHandler obj = new MyButton.ClickEventHandler(this.BtnSelectStart_Click); MyButton rulesVal = this._RulesVal; if (rulesVal != null) { rulesVal.CancelModel(obj); } this._RulesVal = value; rulesVal = this._RulesVal; if (rulesVal != null) { rulesVal.ValidateModel(obj); } } } // Token: 0x1700007D RID: 125 // (get) Token: 0x060003F3 RID: 1011 RVA: 0x00004661 File Offset: 0x00002861 // (set) Token: 0x060003F4 RID: 1012 RVA: 0x00027580 File Offset: 0x00025780 internal virtual MyTextBox TextSelectName { [CompilerGenerated] get { return this.classVal; } [CompilerGenerated] [MethodImpl(MethodImplOptions.Synchronized)] set { TextChangedEventHandler value2 = new TextChangedEventHandler(this.TextSelectName_TextChanged); MyTextBox.ValidateChangedEventHandler obj = new MyTextBox.ValidateChangedEventHandler(this.TextSelectName_ValidateChanged); MyTextBox myTextBox = this.classVal; if (myTextBox != null) { myTextBox.TextChanged -= value2; MyTextBox.EnableVal(obj); } this.classVal = value; myTextBox = this.classVal; if (myTextBox != null) { myTextBox.TextChanged += value2; MyTextBox.ManageVal(obj); } } } // Token: 0x1700007E RID: 126 // (get) Token: 0x060003F5 RID: 1013 RVA: 0x00004669 File Offset: 0x00002869 // (set) Token: 0x060003F6 RID: 1014 RVA: 0x000275DC File Offset: 0x000257DC internal virtual MyCard CardMinecraft { [CompilerGenerated] get { return this.m_ServerVal; } [CompilerGenerated] [MethodImpl(MethodImplOptions.Synchronized)] set { MyCard.PreviewSwapEventHandler obj = new MyCard.PreviewSwapEventHandler(this.CardMinecraft_PreviewSwap); MyCard serverVal = this.m_ServerVal; if (serverVal != null) { serverVal.RemoveFactory(obj); } this.m_ServerVal = value; serverVal = this.m_ServerVal; if (serverVal != null) { serverVal.DeleteFactory(obj); } } } // Token: 0x1700007F RID: 127 // (get) Token: 0x060003F7 RID: 1015 RVA: 0x00004671 File Offset: 0x00002871 // (set) Token: 0x060003F8 RID: 1016 RVA: 0x00004679 File Offset: 0x00002879 internal virtual Grid PanMinecraftInfo { get; [MethodImpl(MethodImplOptions.Synchronized)] set; } // Token: 0x17000080 RID: 128 // (get) Token: 0x060003F9 RID: 1017 RVA: 0x00004682 File Offset: 0x00002882 // (set) Token: 0x060003FA RID: 1018 RVA: 0x0000468A File Offset: 0x0000288A internal virtual Image ImgMinecraft { get; [MethodImpl(MethodImplOptions.Synchronized)] set; } // Token: 0x17000081 RID: 129 // (get) Token: 0x060003FB RID: 1019 RVA: 0x00004693 File Offset: 0x00002893 // (set) Token: 0x060003FC RID: 1020 RVA: 0x0000469B File Offset: 0x0000289B internal virtual TextBlock LabMinecraft { get; [MethodImpl(MethodImplOptions.Synchronized)] set; } // Token: 0x17000082 RID: 130 // (get) Token: 0x060003FD RID: 1021 RVA: 0x000046A4 File Offset: 0x000028A4 // (set) Token: 0x060003FE RID: 1022 RVA: 0x00027620 File Offset: 0x00025820 internal virtual MyCard CardOptiFine { [CompilerGenerated] get { return this.identifierVal; } [CompilerGenerated] [MethodImpl(MethodImplOptions.Synchronized)] set { MyCard.SwapEventHandler obj = delegate(object sender, ModBase.RouteEventArgs e) { this.SelectReload(); }; MyCard.PreviewSwapEventHandler obj2 = new MyCard.PreviewSwapEventHandler(this.CardOptiFine_PreviewSwap); MyCard myCard = this.identifierVal; if (myCard != null) { myCard.PushFactory(obj); myCard.RemoveFactory(obj2); } this.identifierVal = value; myCard = this.identifierVal; if (myCard != null) { myCard.QueryFactory(obj); myCard.DeleteFactory(obj2); } } } // Token: 0x17000083 RID: 131 // (get) Token: 0x060003FF RID: 1023 RVA: 0x000046AC File Offset: 0x000028AC // (set) Token: 0x06000400 RID: 1024 RVA: 0x000046B4 File Offset: 0x000028B4 internal virtual MyHint HintOptiFine { get; [MethodImpl(MethodImplOptions.Synchronized)] set; } // Token: 0x17000084 RID: 132 // (get) Token: 0x06000401 RID: 1025 RVA: 0x000046BD File Offset: 0x000028BD // (set) Token: 0x06000402 RID: 1026 RVA: 0x000046C5 File Offset: 0x000028C5 internal virtual StackPanel PanOptiFine { get; [MethodImpl(MethodImplOptions.Synchronized)] set; } // Token: 0x17000085 RID: 133 // (get) Token: 0x06000403 RID: 1027 RVA: 0x000046CE File Offset: 0x000028CE // (set) Token: 0x06000404 RID: 1028 RVA: 0x000046D6 File Offset: 0x000028D6 internal virtual Grid PanOptiFineInfo { get; [MethodImpl(MethodImplOptions.Synchronized)] set; } // Token: 0x17000086 RID: 134 // (get) Token: 0x06000405 RID: 1029 RVA: 0x000046DF File Offset: 0x000028DF // (set) Token: 0x06000406 RID: 1030 RVA: 0x000046E7 File Offset: 0x000028E7 internal virtual Image ImgOptiFine { get; [MethodImpl(MethodImplOptions.Synchronized)] set; } // Token: 0x17000087 RID: 135 // (get) Token: 0x06000407 RID: 1031 RVA: 0x000046F0 File Offset: 0x000028F0 // (set) Token: 0x06000408 RID: 1032 RVA: 0x000046F8 File Offset: 0x000028F8 internal virtual TextBlock LabOptiFine { get; [MethodImpl(MethodImplOptions.Synchronized)] set; } // Token: 0x17000088 RID: 136 // (get) Token: 0x06000409 RID: 1033 RVA: 0x00004701 File Offset: 0x00002901 // (set) Token: 0x0600040A RID: 1034 RVA: 0x00027680 File Offset: 0x00025880 internal virtual Grid BtnOptiFineClear { [CompilerGenerated] get { return this.m_TokenVal; } [CompilerGenerated] [MethodImpl(MethodImplOptions.Synchronized)] set { MouseButtonEventHandler value2 = new MouseButtonEventHandler(this.OptiFine_Clear); Grid tokenVal = this.m_TokenVal; if (tokenVal != null) { tokenVal.MouseLeftButtonUp -= value2; } this.m_TokenVal = value; tokenVal = this.m_TokenVal; if (tokenVal != null) { tokenVal.MouseLeftButtonUp += value2; } } } // Token: 0x17000089 RID: 137 // (get) Token: 0x0600040B RID: 1035 RVA: 0x00004709 File Offset: 0x00002909 // (set) Token: 0x0600040C RID: 1036 RVA: 0x00004711 File Offset: 0x00002911 internal virtual Path BtnOptiFineClearInner { get; [MethodImpl(MethodImplOptions.Synchronized)] set; } // Token: 0x1700008A RID: 138 // (get) Token: 0x0600040D RID: 1037 RVA: 0x0000471A File Offset: 0x0000291A // (set) Token: 0x0600040E RID: 1038 RVA: 0x000276C4 File Offset: 0x000258C4 internal virtual MyCard CardForge { [CompilerGenerated] get { return this.factoryContainer; } [CompilerGenerated] [MethodImpl(MethodImplOptions.Synchronized)] set { MyCard.SwapEventHandler obj = delegate(object sender, ModBase.RouteEventArgs e) { this.SelectReload(); }; MyCard.PreviewSwapEventHandler obj2 = new MyCard.PreviewSwapEventHandler(this.CardForge_PreviewSwap); MyCard myCard = this.factoryContainer; if (myCard != null) { myCard.PushFactory(obj); myCard.RemoveFactory(obj2); } this.factoryContainer = value; myCard = this.factoryContainer; if (myCard != null) { myCard.QueryFactory(obj); myCard.DeleteFactory(obj2); } } } // Token: 0x1700008B RID: 139 // (get) Token: 0x0600040F RID: 1039 RVA: 0x00004722 File Offset: 0x00002922 // (set) Token: 0x06000410 RID: 1040 RVA: 0x0000472A File Offset: 0x0000292A internal virtual StackPanel PanForge { get; [MethodImpl(MethodImplOptions.Synchronized)] set; } // Token: 0x1700008C RID: 140 // (get) Token: 0x06000411 RID: 1041 RVA: 0x00004733 File Offset: 0x00002933 // (set) Token: 0x06000412 RID: 1042 RVA: 0x0000473B File Offset: 0x0000293B internal virtual Grid PanForgeInfo { get; [MethodImpl(MethodImplOptions.Synchronized)] set; } // Token: 0x1700008D RID: 141 // (get) Token: 0x06000413 RID: 1043 RVA: 0x00004744 File Offset: 0x00002944 // (set) Token: 0x06000414 RID: 1044 RVA: 0x0000474C File Offset: 0x0000294C internal virtual Image ImgForge { get; [MethodImpl(MethodImplOptions.Synchronized)] set; } // Token: 0x1700008E RID: 142 // (get) Token: 0x06000415 RID: 1045 RVA: 0x00004755 File Offset: 0x00002955 // (set) Token: 0x06000416 RID: 1046 RVA: 0x0000475D File Offset: 0x0000295D internal virtual TextBlock LabForge { get; [MethodImpl(MethodImplOptions.Synchronized)] set; } // Token: 0x1700008F RID: 143 // (get) Token: 0x06000417 RID: 1047 RVA: 0x00004766 File Offset: 0x00002966 // (set) Token: 0x06000418 RID: 1048 RVA: 0x00027724 File Offset: 0x00025924 internal virtual Grid BtnForgeClear { [CompilerGenerated] get { return this.expressionContainer; } [CompilerGenerated] [MethodImpl(MethodImplOptions.Synchronized)] set { MouseButtonEventHandler value2 = new MouseButtonEventHandler(this.Forge_Clear); Grid grid = this.expressionContainer; if (grid != null) { grid.MouseLeftButtonUp -= value2; } this.expressionContainer = value; grid = this.expressionContainer; if (grid != null) { grid.MouseLeftButtonUp += value2; } } } // Token: 0x17000090 RID: 144 // (get) Token: 0x06000419 RID: 1049 RVA: 0x0000476E File Offset: 0x0000296E // (set) Token: 0x0600041A RID: 1050 RVA: 0x00004776 File Offset: 0x00002976 internal virtual Path BtnForgeClearInner { get; [MethodImpl(MethodImplOptions.Synchronized)] set; } // Token: 0x17000091 RID: 145 // (get) Token: 0x0600041B RID: 1051 RVA: 0x0000477F File Offset: 0x0000297F // (set) Token: 0x0600041C RID: 1052 RVA: 0x00027768 File Offset: 0x00025968 internal virtual MyCard CardFabric { [CompilerGenerated] get { return this.m_BaseContainer; } [CompilerGenerated] [MethodImpl(MethodImplOptions.Synchronized)] set { MyCard.SwapEventHandler obj = delegate(object sender, ModBase.RouteEventArgs e) { this.SelectReload(); }; MyCard.PreviewSwapEventHandler obj2 = new MyCard.PreviewSwapEventHandler(this.CardFabric_PreviewSwap); MyCard baseContainer = this.m_BaseContainer; if (baseContainer != null) { baseContainer.PushFactory(obj); baseContainer.RemoveFactory(obj2); } this.m_BaseContainer = value; baseContainer = this.m_BaseContainer; if (baseContainer != null) { baseContainer.QueryFactory(obj); baseContainer.DeleteFactory(obj2); } } } // Token: 0x17000092 RID: 146 // (get) Token: 0x0600041D RID: 1053 RVA: 0x00004787 File Offset: 0x00002987 // (set) Token: 0x0600041E RID: 1054 RVA: 0x0000478F File Offset: 0x0000298F internal virtual MyHint HintFabric { get; [MethodImpl(MethodImplOptions.Synchronized)] set; } // Token: 0x17000093 RID: 147 // (get) Token: 0x0600041F RID: 1055 RVA: 0x00004798 File Offset: 0x00002998 // (set) Token: 0x06000420 RID: 1056 RVA: 0x000047A0 File Offset: 0x000029A0 internal virtual StackPanel PanFabric { get; [MethodImpl(MethodImplOptions.Synchronized)] set; } // Token: 0x17000094 RID: 148 // (get) Token: 0x06000421 RID: 1057 RVA: 0x000047A9 File Offset: 0x000029A9 // (set) Token: 0x06000422 RID: 1058 RVA: 0x000047B1 File Offset: 0x000029B1 internal virtual Grid PanFabricInfo { get; [MethodImpl(MethodImplOptions.Synchronized)] set; } // Token: 0x17000095 RID: 149 // (get) Token: 0x06000423 RID: 1059 RVA: 0x000047BA File Offset: 0x000029BA // (set) Token: 0x06000424 RID: 1060 RVA: 0x000047C2 File Offset: 0x000029C2 internal virtual Image ImgFabric { get; [MethodImpl(MethodImplOptions.Synchronized)] set; } // Token: 0x17000096 RID: 150 // (get) Token: 0x06000425 RID: 1061 RVA: 0x000047CB File Offset: 0x000029CB // (set) Token: 0x06000426 RID: 1062 RVA: 0x000047D3 File Offset: 0x000029D3 internal virtual TextBlock LabFabric { get; [MethodImpl(MethodImplOptions.Synchronized)] set; } // Token: 0x17000097 RID: 151 // (get) Token: 0x06000427 RID: 1063 RVA: 0x000047DC File Offset: 0x000029DC // (set) Token: 0x06000428 RID: 1064 RVA: 0x000277C8 File Offset: 0x000259C8 internal virtual Grid BtnFabricClear { [CompilerGenerated] get { return this.paramsContainer; } [CompilerGenerated] [MethodImpl(MethodImplOptions.Synchronized)] set { MouseButtonEventHandler value2 = new MouseButtonEventHandler(this.Fabric_Clear); Grid grid = this.paramsContainer; if (grid != null) { grid.MouseLeftButtonUp -= value2; } this.paramsContainer = value; grid = this.paramsContainer; if (grid != null) { grid.MouseLeftButtonUp += value2; } } } // Token: 0x17000098 RID: 152 // (get) Token: 0x06000429 RID: 1065 RVA: 0x000047E4 File Offset: 0x000029E4 // (set) Token: 0x0600042A RID: 1066 RVA: 0x000047EC File Offset: 0x000029EC internal virtual Path BtnFabricClearInner { get; [MethodImpl(MethodImplOptions.Synchronized)] set; } // Token: 0x17000099 RID: 153 // (get) Token: 0x0600042B RID: 1067 RVA: 0x000047F5 File Offset: 0x000029F5 // (set) Token: 0x0600042C RID: 1068 RVA: 0x0002780C File Offset: 0x00025A0C internal virtual MyCard CardFabricApi { [CompilerGenerated] get { return this._IssuerContainer; } [CompilerGenerated] [MethodImpl(MethodImplOptions.Synchronized)] set { MyCard.SwapEventHandler obj = delegate(object sender, ModBase.RouteEventArgs e) { this.SelectReload(); }; MyCard.PreviewSwapEventHandler obj2 = new MyCard.PreviewSwapEventHandler(this.CardFabricApi_PreviewSwap); MyCard issuerContainer = this._IssuerContainer; if (issuerContainer != null) { issuerContainer.PushFactory(obj); issuerContainer.RemoveFactory(obj2); } this._IssuerContainer = value; issuerContainer = this._IssuerContainer; if (issuerContainer != null) { issuerContainer.QueryFactory(obj); issuerContainer.DeleteFactory(obj2); } } } // Token: 0x1700009A RID: 154 // (get) Token: 0x0600042D RID: 1069 RVA: 0x000047FD File Offset: 0x000029FD // (set) Token: 0x0600042E RID: 1070 RVA: 0x00004805 File Offset: 0x00002A05 internal virtual StackPanel PanFabricApi { get; [MethodImpl(MethodImplOptions.Synchronized)] set; } // Token: 0x1700009B RID: 155 // (get) Token: 0x0600042F RID: 1071 RVA: 0x0000480E File Offset: 0x00002A0E // (set) Token: 0x06000430 RID: 1072 RVA: 0x00004816 File Offset: 0x00002A16 internal virtual Grid PanFabricApiInfo { get; [MethodImpl(MethodImplOptions.Synchronized)] set; } // Token: 0x1700009C RID: 156 // (get) Token: 0x06000431 RID: 1073 RVA: 0x0000481F File Offset: 0x00002A1F // (set) Token: 0x06000432 RID: 1074 RVA: 0x00004827 File Offset: 0x00002A27 internal virtual Image ImgFabricApi { get; [MethodImpl(MethodImplOptions.Synchronized)] set; } // Token: 0x1700009D RID: 157 // (get) Token: 0x06000433 RID: 1075 RVA: 0x00004830 File Offset: 0x00002A30 // (set) Token: 0x06000434 RID: 1076 RVA: 0x00004838 File Offset: 0x00002A38 internal virtual TextBlock LabFabricApi { get; [MethodImpl(MethodImplOptions.Synchronized)] set; } // Token: 0x1700009E RID: 158 // (get) Token: 0x06000435 RID: 1077 RVA: 0x00004841 File Offset: 0x00002A41 // (set) Token: 0x06000436 RID: 1078 RVA: 0x0002786C File Offset: 0x00025A6C internal virtual Grid BtnFabricApiClear { [CompilerGenerated] get { return this.m_MappingContainer; } [CompilerGenerated] [MethodImpl(MethodImplOptions.Synchronized)] set { MouseButtonEventHandler value2 = new MouseButtonEventHandler(this.FabricApi_Clear); Grid mappingContainer = this.m_MappingContainer; if (mappingContainer != null) { mappingContainer.MouseLeftButtonUp -= value2; } this.m_MappingContainer = value; mappingContainer = this.m_MappingContainer; if (mappingContainer != null) { mappingContainer.MouseLeftButtonUp += value2; } } } // Token: 0x1700009F RID: 159 // (get) Token: 0x06000437 RID: 1079 RVA: 0x00004849 File Offset: 0x00002A49 // (set) Token: 0x06000438 RID: 1080 RVA: 0x00004851 File Offset: 0x00002A51 internal virtual Path BtnFabricApiClearInner { get; [MethodImpl(MethodImplOptions.Synchronized)] set; } // Token: 0x170000A0 RID: 160 // (get) Token: 0x06000439 RID: 1081 RVA: 0x0000485A File Offset: 0x00002A5A // (set) Token: 0x0600043A RID: 1082 RVA: 0x000278B0 File Offset: 0x00025AB0 internal virtual MyCard CardLiteLoader { [CompilerGenerated] get { return this._SingletonContainer; } [CompilerGenerated] [MethodImpl(MethodImplOptions.Synchronized)] set { MyCard.SwapEventHandler obj = delegate(object sender, ModBase.RouteEventArgs e) { this.SelectReload(); }; MyCard.PreviewSwapEventHandler obj2 = new MyCard.PreviewSwapEventHandler(this.CardLiteLoader_PreviewSwap); MyCard singletonContainer = this._SingletonContainer; if (singletonContainer != null) { singletonContainer.PushFactory(obj); singletonContainer.RemoveFactory(obj2); } this._SingletonContainer = value; singletonContainer = this._SingletonContainer; if (singletonContainer != null) { singletonContainer.QueryFactory(obj); singletonContainer.DeleteFactory(obj2); } } } // Token: 0x170000A1 RID: 161 // (get) Token: 0x0600043B RID: 1083 RVA: 0x00004862 File Offset: 0x00002A62 // (set) Token: 0x0600043C RID: 1084 RVA: 0x0000486A File Offset: 0x00002A6A internal virtual StackPanel PanLiteLoader { get; [MethodImpl(MethodImplOptions.Synchronized)] set; } // Token: 0x170000A2 RID: 162 // (get) Token: 0x0600043D RID: 1085 RVA: 0x00004873 File Offset: 0x00002A73 // (set) Token: 0x0600043E RID: 1086 RVA: 0x0000487B File Offset: 0x00002A7B internal virtual Grid PanLiteLoaderInfo { get; [MethodImpl(MethodImplOptions.Synchronized)] set; } // Token: 0x170000A3 RID: 163 // (get) Token: 0x0600043F RID: 1087 RVA: 0x00004884 File Offset: 0x00002A84 // (set) Token: 0x06000440 RID: 1088 RVA: 0x0000488C File Offset: 0x00002A8C internal virtual Image ImgLiteLoader { get; [MethodImpl(MethodImplOptions.Synchronized)] set; } // Token: 0x170000A4 RID: 164 // (get) Token: 0x06000441 RID: 1089 RVA: 0x00004895 File Offset: 0x00002A95 // (set) Token: 0x06000442 RID: 1090 RVA: 0x0000489D File Offset: 0x00002A9D internal virtual TextBlock LabLiteLoader { get; [MethodImpl(MethodImplOptions.Synchronized)] set; } // Token: 0x170000A5 RID: 165 // (get) Token: 0x06000443 RID: 1091 RVA: 0x000048A6 File Offset: 0x00002AA6 // (set) Token: 0x06000444 RID: 1092 RVA: 0x00027910 File Offset: 0x00025B10 internal virtual Grid BtnLiteLoaderClear { [CompilerGenerated] get { return this.visitorContainer; } [CompilerGenerated] [MethodImpl(MethodImplOptions.Synchronized)] set { MouseButtonEventHandler value2 = new MouseButtonEventHandler(this.LiteLoader_Clear); Grid grid = this.visitorContainer; if (grid != null) { grid.MouseLeftButtonUp -= value2; } this.visitorContainer = value; grid = this.visitorContainer; if (grid != null) { grid.MouseLeftButtonUp += value2; } } } // Token: 0x170000A6 RID: 166 // (get) Token: 0x06000445 RID: 1093 RVA: 0x000048AE File Offset: 0x00002AAE // (set) Token: 0x06000446 RID: 1094 RVA: 0x000048B6 File Offset: 0x00002AB6 internal virtual Path BtnLiteLoaderClearInner { get; [MethodImpl(MethodImplOptions.Synchronized)] set; } // Token: 0x170000A7 RID: 167 // (get) Token: 0x06000447 RID: 1095 RVA: 0x000048BF File Offset: 0x00002ABF // (set) Token: 0x06000448 RID: 1096 RVA: 0x000048C7 File Offset: 0x00002AC7 internal virtual MyCard PanLoad { get; [MethodImpl(MethodImplOptions.Synchronized)] set; } // Token: 0x170000A8 RID: 168 // (get) Token: 0x06000449 RID: 1097 RVA: 0x000048D0 File Offset: 0x00002AD0 // (set) Token: 0x0600044A RID: 1098 RVA: 0x00027954 File Offset: 0x00025B54 internal virtual MyLoading LoadMinecraft { [CompilerGenerated] get { return this._DatabaseContainer; } [CompilerGenerated] [MethodImpl(MethodImplOptions.Synchronized)] set { MyLoading.ClickEventHandler obj = new MyLoading.ClickEventHandler(this.LoadMinecraft_Click); MyLoading.StateChangedEventHandler obj2 = new MyLoading.StateChangedEventHandler(this.LoadMinecraft_State); MyLoading databaseContainer = this._DatabaseContainer; if (databaseContainer != null) { databaseContainer.UpdateVal(obj); databaseContainer.InitVal(obj2); } this._DatabaseContainer = value; databaseContainer = this._DatabaseContainer; if (databaseContainer != null) { databaseContainer.PrepareVal(obj); databaseContainer.FillVal(obj2); } } } // Token: 0x170000A9 RID: 169 // (get) Token: 0x0600044B RID: 1099 RVA: 0x000048D8 File Offset: 0x00002AD8 // (set) Token: 0x0600044C RID: 1100 RVA: 0x000279B4 File Offset: 0x00025BB4 internal virtual MyLoading LoadOptiFine { [CompilerGenerated] get { return this.attrContainer; } [CompilerGenerated] [MethodImpl(MethodImplOptions.Synchronized)] set { MyLoading.StateChangedEventHandler obj = delegate(object a0, MyLoading.MyLoadingState a1) { this.SelectReload(); }; MyLoading.StateChangedEventHandler obj2 = delegate(object a0, MyLoading.MyLoadingState a1) { this.OptiFine_Loaded(); }; MyLoading myLoading = this.attrContainer; if (myLoading != null) { myLoading.InitVal(obj); myLoading.InitVal(obj2); } this.attrContainer = value; myLoading = this.attrContainer; if (myLoading != null) { myLoading.FillVal(obj); myLoading.FillVal(obj2); } } } // Token: 0x170000AA RID: 170 // (get) Token: 0x0600044D RID: 1101 RVA: 0x000048E0 File Offset: 0x00002AE0 // (set) Token: 0x0600044E RID: 1102 RVA: 0x00027A14 File Offset: 0x00025C14 internal virtual MyLoading LoadForge { [CompilerGenerated] get { return this.m_ThreadContainer; } [CompilerGenerated] [MethodImpl(MethodImplOptions.Synchronized)] set { MyLoading.StateChangedEventHandler obj = delegate(object a0, MyLoading.MyLoadingState a1) { this.SelectReload(); }; MyLoading.StateChangedEventHandler obj2 = delegate(object a0, MyLoading.MyLoadingState a1) { this.Forge_Loaded(); }; MyLoading threadContainer = this.m_ThreadContainer; if (threadContainer != null) { threadContainer.InitVal(obj); threadContainer.InitVal(obj2); } this.m_ThreadContainer = value; threadContainer = this.m_ThreadContainer; if (threadContainer != null) { threadContainer.FillVal(obj); threadContainer.FillVal(obj2); } } } // Token: 0x170000AB RID: 171 // (get) Token: 0x0600044F RID: 1103 RVA: 0x000048E8 File Offset: 0x00002AE8 // (set) Token: 0x06000450 RID: 1104 RVA: 0x00027A74 File Offset: 0x00025C74 internal virtual MyLoading LoadLiteLoader { [CompilerGenerated] get { return this.m_ManagerContainer; } [CompilerGenerated] [MethodImpl(MethodImplOptions.Synchronized)] set { MyLoading.StateChangedEventHandler obj = delegate(object a0, MyLoading.MyLoadingState a1) { this.SelectReload(); }; MyLoading.StateChangedEventHandler obj2 = delegate(object a0, MyLoading.MyLoadingState a1) { this.LiteLoader_Loaded(); }; MyLoading managerContainer = this.m_ManagerContainer; if (managerContainer != null) { managerContainer.InitVal(obj); managerContainer.InitVal(obj2); } this.m_ManagerContainer = value; managerContainer = this.m_ManagerContainer; if (managerContainer != null) { managerContainer.FillVal(obj); managerContainer.FillVal(obj2); } } } // Token: 0x170000AC RID: 172 // (get) Token: 0x06000451 RID: 1105 RVA: 0x000048F0 File Offset: 0x00002AF0 // (set) Token: 0x06000452 RID: 1106 RVA: 0x00027AD4 File Offset: 0x00025CD4 internal virtual MyLoading LoadFabric { [CompilerGenerated] get { return this.m_ItemContainer; } [CompilerGenerated] [MethodImpl(MethodImplOptions.Synchronized)] set { MyLoading.StateChangedEventHandler obj = delegate(object a0, MyLoading.MyLoadingState a1) { this.SelectReload(); }; MyLoading.StateChangedEventHandler obj2 = delegate(object a0, MyLoading.MyLoadingState a1) { this.Fabric_Loaded(); }; MyLoading itemContainer = this.m_ItemContainer; if (itemContainer != null) { itemContainer.InitVal(obj); itemContainer.InitVal(obj2); } this.m_ItemContainer = value; itemContainer = this.m_ItemContainer; if (itemContainer != null) { itemContainer.FillVal(obj); itemContainer.FillVal(obj2); } } } // Token: 0x170000AD RID: 173 // (get) Token: 0x06000453 RID: 1107 RVA: 0x000048F8 File Offset: 0x00002AF8 // (set) Token: 0x06000454 RID: 1108 RVA: 0x00027B34 File Offset: 0x00025D34 internal virtual MyLoading LoadFabricApi { [CompilerGenerated] get { return this.m_SerializerContainer; } [CompilerGenerated] [MethodImpl(MethodImplOptions.Synchronized)] set { MyLoading.StateChangedEventHandler obj = delegate(object a0, MyLoading.MyLoadingState a1) { this.SelectReload(); }; MyLoading.StateChangedEventHandler obj2 = delegate(object a0, MyLoading.MyLoadingState a1) { this.FabricApi_Loaded(); }; MyLoading serializerContainer = this.m_SerializerContainer; if (serializerContainer != null) { serializerContainer.InitVal(obj); serializerContainer.InitVal(obj2); } this.m_SerializerContainer = value; serializerContainer = this.m_SerializerContainer; if (serializerContainer != null) { serializerContainer.FillVal(obj); serializerContainer.FillVal(obj2); } } } // Token: 0x06000455 RID: 1109 RVA: 0x00027B94 File Offset: 0x00025D94 [DebuggerNonUserCode] [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] public void InitializeComponent() { if (!this._InfoContainer) { this._InfoContainer = true; Uri resourceLocator = new Uri("/Plain Craft Launcher 2;component/pages/pagedownload/pagedownloadinstall.xaml", UriKind.Relative); Application.LoadComponent(this, resourceLocator); } } // Token: 0x06000456 RID: 1110 RVA: 0x00003037 File Offset: 0x00001237 [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] [DebuggerNonUserCode] internal Delegate _CreateDelegate(Type delegateType, string handler) { return Delegate.CreateDelegate(delegateType, this, handler); } // Token: 0x06000457 RID: 1111 RVA: 0x00027BC4 File Offset: 0x00025DC4 [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] [DebuggerNonUserCode] [EditorBrowsable(EditorBrowsableState.Never)] public void System_Windows_Markup_IComponentConnector_Connect(int connectionId, object target) { if (connectionId == 1) { this.PanBack = (MyScrollViewer)target; return; } if (connectionId == 2) { this.PanMinecraft = (VirtualizingStackPanel)target; return; } if (connectionId == 3) { this.PanSelect = (StackPanel)target; return; } if (connectionId == 4) { this.HintFabricAPI = (MyHint)target; return; } if (connectionId == 5) { this.ItemSelect = (MyListItem)target; return; } if (connectionId == 6) { this.BtnSelectStart = (MyButton)target; return; } if (connectionId == 7) { this.TextSelectName = (MyTextBox)target; return; } if (connectionId == 8) { this.CardMinecraft = (MyCard)target; return; } if (connectionId == 9) { this.PanMinecraftInfo = (Grid)target; return; } if (connectionId == 0xA) { this.ImgMinecraft = (Image)target; return; } if (connectionId == 0xB) { this.LabMinecraft = (TextBlock)target; return; } if (connectionId == 0xC) { this.CardOptiFine = (MyCard)target; return; } if (connectionId == 0xD) { this.HintOptiFine = (MyHint)target; return; } if (connectionId == 0xE) { this.PanOptiFine = (StackPanel)target; return; } if (connectionId == 0xF) { this.PanOptiFineInfo = (Grid)target; return; } if (connectionId == 0x10) { this.ImgOptiFine = (Image)target; return; } if (connectionId == 0x11) { this.LabOptiFine = (TextBlock)target; return; } if (connectionId == 0x12) { this.BtnOptiFineClear = (Grid)target; return; } if (connectionId == 0x13) { this.BtnOptiFineClearInner = (Path)target; return; } if (connectionId == 0x14) { this.CardForge = (MyCard)target; return; } if (connectionId == 0x15) { this.PanForge = (StackPanel)target; return; } if (connectionId == 0x16) { this.PanForgeInfo = (Grid)target; return; } if (connectionId == 0x17) { this.ImgForge = (Image)target; return; } if (connectionId == 0x18) { this.LabForge = (TextBlock)target; return; } if (connectionId == 0x19) { this.BtnForgeClear = (Grid)target; return; } if (connectionId == 0x1A) { this.BtnForgeClearInner = (Path)target; return; } if (connectionId == 0x1B) { this.CardFabric = (MyCard)target; return; } if (connectionId == 0x1C) { this.HintFabric = (MyHint)target; return; } if (connectionId == 0x1D) { this.PanFabric = (StackPanel)target; return; } if (connectionId == 0x1E) { this.PanFabricInfo = (Grid)target; return; } if (connectionId == 0x1F) { this.ImgFabric = (Image)target; return; } if (connectionId == 0x20) { this.LabFabric = (TextBlock)target; return; } if (connectionId == 0x21) { this.BtnFabricClear = (Grid)target; return; } if (connectionId == 0x22) { this.BtnFabricClearInner = (Path)target; return; } if (connectionId == 0x23) { this.CardFabricApi = (MyCard)target; return; } if (connectionId == 0x24) { this.PanFabricApi = (StackPanel)target; return; } if (connectionId == 0x25) { this.PanFabricApiInfo = (Grid)target; return; } if (connectionId == 0x26) { this.ImgFabricApi = (Image)target; return; } if (connectionId == 0x27) { this.LabFabricApi = (TextBlock)target; return; } if (connectionId == 0x28) { this.BtnFabricApiClear = (Grid)target; return; } if (connectionId == 0x29) { this.BtnFabricApiClearInner = (Path)target; return; } if (connectionId == 0x2A) { this.CardLiteLoader = (MyCard)target; return; } if (connectionId == 0x2B) { this.PanLiteLoader = (StackPanel)target; return; } if (connectionId == 0x2C) { this.PanLiteLoaderInfo = (Grid)target; return; } if (connectionId == 0x2D) { this.ImgLiteLoader = (Image)target; return; } if (connectionId == 0x2E) { this.LabLiteLoader = (TextBlock)target; return; } if (connectionId == 0x2F) { this.BtnLiteLoaderClear = (Grid)target; return; } if (connectionId == 0x30) { this.BtnLiteLoaderClearInner = (Path)target; return; } if (connectionId == 0x31) { this.PanLoad = (MyCard)target; return; } if (connectionId == 0x32) { this.LoadMinecraft = (MyLoading)target; return; } if (connectionId == 0x33) { this.LoadOptiFine = (MyLoading)target; return; } if (connectionId == 0x34) { this.LoadForge = (MyLoading)target; return; } if (connectionId == 0x35) { this.LoadLiteLoader = (MyLoading)target; return; } if (connectionId == 0x36) { this.LoadFabric = (MyLoading)target; return; } if (connectionId == 0x37) { this.LoadFabricApi = (MyLoading)target; return; } this._InfoContainer = true; } // Token: 0x040001F4 RID: 500 private bool _ListenerVal; // Token: 0x040001F5 RID: 501 private bool importerVal; // Token: 0x040001F6 RID: 502 private bool _TemplateVal; // Token: 0x040001F7 RID: 503 private string _AdapterVal; // Token: 0x040001F8 RID: 504 private string annotationVal; // Token: 0x040001F9 RID: 505 private string _ReaderVal; // Token: 0x040001FA RID: 506 private ModDownload.DlOptiFineListEntry regVal; // Token: 0x040001FB RID: 507 private ModDownload.DlLiteLoaderListEntry definitionVal; // Token: 0x040001FC RID: 508 private ModDownload.DlForgeVersionEntry _ParamVal; // Token: 0x040001FD RID: 509 private string m_MockVal; // Token: 0x040001FE RID: 510 private ModDownload.DlCfFile specificationVal; // Token: 0x040001FF RID: 511 private bool m_DicVal; // Token: 0x04000200 RID: 512 private bool _SchemaVal; // Token: 0x04000201 RID: 513 [CompilerGenerated] [AccessedThroughProperty("PanBack")] private MyScrollViewer _HelperVal; // Token: 0x04000202 RID: 514 [AccessedThroughProperty("PanMinecraft")] [CompilerGenerated] private VirtualizingStackPanel _ConsumerVal; // Token: 0x04000203 RID: 515 [CompilerGenerated] [AccessedThroughProperty("PanSelect")] private StackPanel queueVal; // Token: 0x04000204 RID: 516 [AccessedThroughProperty("HintFabricAPI")] [CompilerGenerated] private MyHint _ProducerVal; // Token: 0x04000205 RID: 517 [CompilerGenerated] [AccessedThroughProperty("ItemSelect")] private MyListItem m_ExceptionVal; // Token: 0x04000206 RID: 518 [CompilerGenerated] [AccessedThroughProperty("BtnSelectStart")] private MyButton _RulesVal; // Token: 0x04000207 RID: 519 [CompilerGenerated] [AccessedThroughProperty("TextSelectName")] private MyTextBox classVal; // Token: 0x04000208 RID: 520 [AccessedThroughProperty("CardMinecraft")] [CompilerGenerated] private MyCard m_ServerVal; // Token: 0x04000209 RID: 521 [AccessedThroughProperty("PanMinecraftInfo")] [CompilerGenerated] private Grid m_ConfigVal; // Token: 0x0400020A RID: 522 [CompilerGenerated] [AccessedThroughProperty("ImgMinecraft")] private Image m_ConnectionVal; // Token: 0x0400020B RID: 523 [CompilerGenerated] [AccessedThroughProperty("LabMinecraft")] private TextBlock reponseVal; // Token: 0x0400020C RID: 524 [CompilerGenerated] [AccessedThroughProperty("CardOptiFine")] private MyCard identifierVal; // Token: 0x0400020D RID: 525 [CompilerGenerated] [AccessedThroughProperty("HintOptiFine")] private MyHint policyVal; // Token: 0x0400020E RID: 526 [CompilerGenerated] [AccessedThroughProperty("PanOptiFine")] private StackPanel clientVal; // Token: 0x0400020F RID: 527 [CompilerGenerated] [AccessedThroughProperty("PanOptiFineInfo")] private Grid composerVal; // Token: 0x04000210 RID: 528 [CompilerGenerated] [AccessedThroughProperty("ImgOptiFine")] private Image m_PublisherVal; // Token: 0x04000211 RID: 529 [CompilerGenerated] [AccessedThroughProperty("LabOptiFine")] private TextBlock m_MessageVal; // Token: 0x04000212 RID: 530 [AccessedThroughProperty("BtnOptiFineClear")] [CompilerGenerated] private Grid m_TokenVal; // Token: 0x04000213 RID: 531 [CompilerGenerated] [AccessedThroughProperty("BtnOptiFineClearInner")] private Path procVal; // Token: 0x04000214 RID: 532 [CompilerGenerated] [AccessedThroughProperty("CardForge")] private MyCard factoryContainer; // Token: 0x04000215 RID: 533 [AccessedThroughProperty("PanForge")] [CompilerGenerated] private StackPanel valContainer; // Token: 0x04000216 RID: 534 [AccessedThroughProperty("PanForgeInfo")] [CompilerGenerated] private Grid _ContainerContainer; // Token: 0x04000217 RID: 535 [CompilerGenerated] [AccessedThroughProperty("ImgForge")] private Image modelContainer; // Token: 0x04000218 RID: 536 [AccessedThroughProperty("LabForge")] [CompilerGenerated] private TextBlock m_IteratorContainer; // Token: 0x04000219 RID: 537 [AccessedThroughProperty("BtnForgeClear")] [CompilerGenerated] private Grid expressionContainer; // Token: 0x0400021A RID: 538 [CompilerGenerated] [AccessedThroughProperty("BtnForgeClearInner")] private Path _UtilsContainer; // Token: 0x0400021B RID: 539 [CompilerGenerated] [AccessedThroughProperty("CardFabric")] private MyCard m_BaseContainer; // Token: 0x0400021C RID: 540 [AccessedThroughProperty("HintFabric")] [CompilerGenerated] private MyHint m_DecoratorContainer; // Token: 0x0400021D RID: 541 [CompilerGenerated] [AccessedThroughProperty("PanFabric")] private StackPanel _FilterContainer; // Token: 0x0400021E RID: 542 [CompilerGenerated] [AccessedThroughProperty("PanFabricInfo")] private Grid ruleContainer; // Token: 0x0400021F RID: 543 [CompilerGenerated] [AccessedThroughProperty("ImgFabric")] private Image algoContainer; // Token: 0x04000220 RID: 544 [AccessedThroughProperty("LabFabric")] [CompilerGenerated] private TextBlock _MapperContainer; // Token: 0x04000221 RID: 545 [CompilerGenerated] [AccessedThroughProperty("BtnFabricClear")] private Grid paramsContainer; // Token: 0x04000222 RID: 546 [CompilerGenerated] [AccessedThroughProperty("BtnFabricClearInner")] private Path _GlobalContainer; // Token: 0x04000223 RID: 547 [AccessedThroughProperty("CardFabricApi")] [CompilerGenerated] private MyCard _IssuerContainer; // Token: 0x04000224 RID: 548 [CompilerGenerated] [AccessedThroughProperty("PanFabricApi")] private StackPanel orderContainer; // Token: 0x04000225 RID: 549 [AccessedThroughProperty("PanFabricApiInfo")] [CompilerGenerated] private Grid serviceContainer; // Token: 0x04000226 RID: 550 [CompilerGenerated] [AccessedThroughProperty("ImgFabricApi")] private Image m_FacadeContainer; // Token: 0x04000227 RID: 551 [CompilerGenerated] [AccessedThroughProperty("LabFabricApi")] private TextBlock m_CodeContainer; // Token: 0x04000228 RID: 552 [AccessedThroughProperty("BtnFabricApiClear")] [CompilerGenerated] private Grid m_MappingContainer; // Token: 0x04000229 RID: 553 [AccessedThroughProperty("BtnFabricApiClearInner")] [CompilerGenerated] private Path bridgeContainer; // Token: 0x0400022A RID: 554 [AccessedThroughProperty("CardLiteLoader")] [CompilerGenerated] private MyCard _SingletonContainer; // Token: 0x0400022B RID: 555 [AccessedThroughProperty("PanLiteLoader")] [CompilerGenerated] private StackPanel m_ErrorContainer; // Token: 0x0400022C RID: 556 [AccessedThroughProperty("PanLiteLoaderInfo")] [CompilerGenerated] private Grid m_ObjectContainer; // Token: 0x0400022D RID: 557 [AccessedThroughProperty("ImgLiteLoader")] [CompilerGenerated] private Image _CallbackContainer; // Token: 0x0400022E RID: 558 [AccessedThroughProperty("LabLiteLoader")] [CompilerGenerated] private TextBlock _WorkerContainer; // Token: 0x0400022F RID: 559 [AccessedThroughProperty("BtnLiteLoaderClear")] [CompilerGenerated] private Grid visitorContainer; // Token: 0x04000230 RID: 560 [AccessedThroughProperty("BtnLiteLoaderClearInner")] [CompilerGenerated] private Path _IndexerContainer; // Token: 0x04000231 RID: 561 [AccessedThroughProperty("PanLoad")] [CompilerGenerated] private MyCard _MethodContainer; // Token: 0x04000232 RID: 562 [AccessedThroughProperty("LoadMinecraft")] [CompilerGenerated] private MyLoading _DatabaseContainer; // Token: 0x04000233 RID: 563 [AccessedThroughProperty("LoadOptiFine")] [CompilerGenerated] private MyLoading attrContainer; // Token: 0x04000234 RID: 564 [CompilerGenerated] [AccessedThroughProperty("LoadForge")] private MyLoading m_ThreadContainer; // Token: 0x04000235 RID: 565 [AccessedThroughProperty("LoadLiteLoader")] [CompilerGenerated] private MyLoading m_ManagerContainer; // Token: 0x04000236 RID: 566 [CompilerGenerated] [AccessedThroughProperty("LoadFabric")] private MyLoading m_ItemContainer; // Token: 0x04000237 RID: 567 [CompilerGenerated] [AccessedThroughProperty("LoadFabricApi")] private MyLoading m_SerializerContainer; // Token: 0x04000238 RID: 568 private bool _InfoContainer; } }
0
0.88435
1
0.88435
game-dev
MEDIA
0.638987
game-dev,graphics-rendering
0.947902
1
0.947902
Sigma-Skidder-Team/SigmaRemap
19,239
src/main/java/com/mentalfrostbyte/jello/gui/screens/AltManagerScreen.java
package com.mentalfrostbyte.jello.gui.screens; import com.mentalfrostbyte.Client; import com.mentalfrostbyte.jello.account.Account; import com.mentalfrostbyte.jello.account.AccountManager; import com.mentalfrostbyte.jello.gui.Screen; import com.mentalfrostbyte.jello.resource.ResourceRegistry; import com.mentalfrostbyte.jello.unmapped.CustomGuiScreen; import com.mentalfrostbyte.jello.unmapped.ResourceList; import com.mentalfrostbyte.jello.util.MathUtils; import com.mentalfrostbyte.jello.util.MultiUtilities; import com.mentalfrostbyte.jello.util.render.animation.Animation; import com.mentalfrostbyte.jello.util.ClientColors; import org.newdawn.slick.opengl.Texture; import mapped.*; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.ServerData; import net.minecraft.client.multiplayer.ServerList; import totalcross.json.JSONObject; import java.util.ArrayList; import java.util.List; public class AltManagerScreen extends Screen { private int field21005; private float field21006; private float field21007 = 0.75F; private boolean field21008 = true; public UIButton field21009; private Class4339 field21010; private Class4339 field21011; private AlertPanel field21012; private AlertPanel field21013; private float field21014 = 0.65F; private float field21015 = 1.0F - this.field21014; private int field21016 = 30; private Class4298 field21017; private Class4296 field21018; public AccountManager accountManager = Client.getInstance().accountManager; private Texture field21020; private float field21021; private UIButton field21022; private Class2209 field21023 = Class2209.field14448; private String field21024 = ""; private boolean field21025 = false; private UIInput field21026; public AltManagerScreen() { super("Alt Manager"); this.method13300(false); ArrayList var3 = new ArrayList(); var3.add("Alphabetical"); var3.add("Bans"); var3.add("Date Added"); var3.add("Last Used"); var3.add("Use count"); ArrayList<String> var4 = new ArrayList(); ServerList var5 = new ServerList(Minecraft.getInstance()); var5.loadServerList(); int var6 = var5.countServers(); for (int var7 = 0; var7 < var6; var7++) { ServerData var8 = var5.getServerData(var7); if (!var4.contains(var8.serverIP)) { var4.add(var8.serverIP); } } this.method13362(); this.method13363(); this.addToList( this.field21010 = new Class4339( this, "alts", 0, 114, (int) ((float) Minecraft.getInstance().mainWindow.getWidth() * this.field21014) - 4, Minecraft.getInstance().mainWindow.getHeight() - 119 - this.field21016)); this.addToList( this.field21011 = new Class4339( this, "altView", (int) ((float) Minecraft.getInstance().mainWindow.getWidth() * this.field21014), 114, (int) ((float) Minecraft.getInstance().mainWindow.getWidth() * this.field21015) - this.field21016, Minecraft.getInstance().mainWindow.getHeight() - 119 - this.field21016)); this.field21010.method13300(false); this.field21011.method13300(false); this.field21010.method13515(false); this.field21011 .addToList( this.field21017 = new Class4298( this.field21011, "", (int) ((float) Minecraft.getInstance().mainWindow.getWidth() * this.field21015 - (float) ((int) ((float) Minecraft.getInstance().mainWindow.getWidth() * this.field21015))) / 2 - 10, Minecraft.getInstance().mainWindow.getHeight() / 12, (int) ((float) Minecraft.getInstance().mainWindow.getWidth() * this.field21015), 350, "steve")); this.field21011 .addToList( this.field21018 = new Class4296( this.field21011, "info", (int) ((float) Minecraft.getInstance().mainWindow.getWidth() * this.field21015 - (float) ((int) ((float) Minecraft.getInstance().mainWindow.getWidth() * this.field21015))) / 2 - 10, this.method13374(), (int) ((float) Minecraft.getInstance().mainWindow.getWidth() * this.field21015), 500)); Class4363 var9 = new Class4363(this, "drop", (int) ((float) Minecraft.getInstance().mainWindow.getWidth() * this.field21014) - 220, 44, 200, 32, var3, 0); var9.method13643(var4, 1); var9.method13656(2); this.addToList(var9); var9.method13036(var2 -> { switch (var9.method13655()) { case 0: this.field21023 = Class2209.field14446; break; case 1: this.field21023 = Class2209.field14447; this.field21024 = var9.method13645(1).method13636().get(var9.method13645(1).method13640()); break; case 2: this.field21023 = Class2209.field14448; break; case 3: this.field21023 = Class2209.field14449; break; case 4: this.field21023 = Class2209.field14450; } this.method13372(false); }); this.addToList( this.field21026 = new UIInput( this, "textbox", (int) ((float) Minecraft.getInstance().mainWindow.getWidth() * this.field21014), 44, 150, 32, UIInput.field20741, "", "Search...", ResourceRegistry.JelloLightFont18)); this.field21026.setFont(ResourceRegistry.JelloLightFont18); this.field21026.method13151(var1 -> this.method13372(false)); this.addToList(this.field21022 = new UIButton(this, "btnt", this.getWidthA() - 90, 43, 70, 30, ColorHelper.field27961, "Add +", ResourceRegistry.JelloLightFont25)); this.field21010.method13242(); this.field21022.doThis((var1, var2) -> { if (this.method13369()) { this.field21012.method13603(!this.field21012.isHovered()); } }); } private void method13360(Account var1, boolean var2) { Class4294 var5; this.field21010 .addToList( var5 = new Class4294( this.field21010, var1.getEmail(), this.field21016, (100 + this.field21016 / 2) * this.method13370(), this.field21010.getWidthA() - this.field21016 * 2 + 4, 100, var1)); if (!var2) { var5.field20805 = new Animation(0, 0); } if (this.accountManager.method36779(var1)) { var5.method13172(true); } var5.method13247((var2x, var3) -> { if (var3 != 0) { this.field21013.method13036(var2xx -> { this.accountManager.removeAccountDirectly(var5.selectedAccount); this.field21018.method13178(null); this.field21017.method13181(null); this.method13372(false); }); this.field21013.method13145(true); this.field21013.method13603(true); } else { if (this.field21017.account == var5.selectedAccount && var5.method13168()) { this.method13361(var5); } else { this.field21011.method13512(0); } this.field21017.method13181(var5.selectedAccount); this.field21018.method13178(var5.selectedAccount); for (CustomGuiScreen var7 : this.field21010.method13241()) { if (!(var7 instanceof Class4292)) { for (CustomGuiScreen var9 : var7.method13241()) { ((Class4294) var9).method13166(false); } } } var5.method13166(true); } }); if (Client.getInstance().accountManager.method36779(var1)) { this.field21017.method13181(var5.selectedAccount); this.field21018.method13178(var5.selectedAccount); var5.method13167(true, true); } } private void method13361(Class4294 var1) { var1.method13174(true); new Thread(() -> { if (!this.accountManager.login(var1.selectedAccount)) { var1.method13173(114); Client.getInstance().soundManager.play("error"); } else { this.method13368(); var1.method13172(true); Client.getInstance().soundManager.play("connect"); this.method13372(false); } var1.method13174(false); }).start(); } private void method13362() { MiniAlert var3 = new MiniAlert(AlertType.HEADER, "Add Alt", 50); MiniAlert var4 = new MiniAlert(AlertType.FIRSTLINE, "Login with your minecraft", 15); MiniAlert var5 = new MiniAlert(AlertType.FIRSTLINE, "account here!", 25); MiniAlert var6 = new MiniAlert(AlertType.SEKONDLINE, "Email", 50); MiniAlert var7 = new MiniAlert(AlertType.SEKONDLINE, "Password", 50); MiniAlert var8 = new MiniAlert(AlertType.TEXTBOX, "", 15); MiniAlert var9 = new MiniAlert(AlertType.BUTTON, "Add alt", 50); this.addToList(this.field21012 = new AlertPanel(this, "Testt", true, "Add Alt", var3, var4, var5, var6, var7, var8, var9)); this.field21012.method13036(var1 -> { if (!this.field21012.method13600().get("Email").contains(":")) { Account var11 = new Account(this.field21012.method13600().get("Email"), this.field21012.method13600().get("Password")); if (!this.accountManager.containsAccount(var11)) { this.accountManager.updateAccount(var11); } this.method13372(false); } else { String[] var4x = this.field21012.method13600().get("Email").replace("\r", "\n").replace("\n\n", "\n") .split("\n"); for (String var8x : var4x) { String[] var9x = var8x.split(":"); if (var9x.length == 2) { Account var10 = new Account(var9x[0], var9x[1]); if (!this.accountManager.containsAccount(var10)) { this.accountManager.updateAccount(var10); } } } this.method13372(false); } }); } private void method13363() { MiniAlert var3 = new MiniAlert(AlertType.HEADER, "Delete?", 50); MiniAlert var4 = new MiniAlert(AlertType.FIRSTLINE, "Are you sure you want", 15); MiniAlert var5 = new MiniAlert(AlertType.FIRSTLINE, "to delete this alt?", 40); MiniAlert var6 = new MiniAlert(AlertType.BUTTON, "Delete", 50); this.addToList(this.field21013 = new AlertPanel(this, "delete", true, "Delete", var3, var4, var5, var6)); } @Override public void draw(float partialTicks) { this.drawBackground(); RenderUtil.method11465( (int) ((float) Minecraft.getInstance().mainWindow.getWidth() * this.field21014), 114, (int) ((float) Minecraft.getInstance().mainWindow.getWidth() * this.field21015) - this.field21016, Minecraft.getInstance().mainWindow.getHeight() - 119 - this.field21016, ClientColors.LIGHT_GREYISH_BLUE.getColor()); this.emptyMethod(); this.method13367(); this.drawTitle(); super.draw(partialTicks); } /** * Hell yeah */ private void emptyMethod() { } private void drawTitle() { int var3 = this.xA + this.field21016; int var4 = this.yA + this.field21016; int var5 = MultiUtilities.applyAlpha(ClientColors.DEEP_TEAL.getColor(), 0.8F); RenderUtil.drawString(ResourceRegistry.JelloLightFont40, (float) var3, (float) var4, "Jello", var5); RenderUtil.drawString(ResourceRegistry.JelloLightFont25, (float) (var3 + 87), (float) (var4 + 15), "Alt Manager", var5); } private void method13367() { float var3 = 1.0F; for (CustomGuiScreen var5 : this.field21010.method13241()) { if (!(var5 instanceof Class4292)) { for (CustomGuiScreen var7 : var5.method13241()) { if (var7 instanceof Class4294) { Class4294 var8 = (Class4294) var7; if (var7.getYA() <= Minecraft.getInstance().mainWindow.getHeight() && this.field21010.method13513() == 0) { if (var3 > 0.2F) { var8.field20805.changeDirection(Animation.Direction.FORWARDS); } float var9 = MathUtils.lerp(var8.field20805.calcPercent(), 0.51, 0.82, 0.0, 0.99); var8.method13284((int) (-((1.0F - var9) * (float) (var7.getWidthA() + 30)))); var3 = var8.field20805.calcPercent(); } else { var8.method13284(0); var8.field20805.changeDirection(Animation.Direction.FORWARDS); } } } } } } private void method13368() { boolean var3 = false; for (CustomGuiScreen var5 : this.field21010.method13241()) { if (!(var5 instanceof Class4292)) { for (CustomGuiScreen var7 : var5.method13241()) { Class4294 var8 = (Class4294) var7; var8.method13172(false); } } } } private boolean method13369() { boolean var3 = false; for (CustomGuiScreen var5 : this.field21010.method13241()) { if (!(var5 instanceof Class4292)) { for (CustomGuiScreen var7 : var5.method13241()) { if (var7.method13280() != 0 && var7.getXA() > this.widthA) { return false; } } } } return true; } private int method13370() { int var3 = 0; for (CustomGuiScreen var5 : this.field21010.method13241()) { if (!(var5 instanceof Class4292)) { for (CustomGuiScreen var7 : var5.method13241()) { var3++; } } } return var3; } private void drawBackground() { int var3 = this.getHeightO() * -1; float var4 = (float) this.getWidthO() / (float) this.getWidthA() * -114.0F; if (this.field21008) { this.field21006 = (float) ((int) var4); this.field21005 = var3; this.field21008 = false; } float var5 = var4 - this.field21006; float var6 = (float) (var3 - this.field21005); RenderUtil.method11455((float) this.field21005, this.field21006, (float) (this.getWidthA() * 2), (float) (this.getHeightA() + 114), ResourceList.panoramaPNG); float var7 = 0.5F; if (var4 != this.field21006) { this.field21006 += var5 * var7; } if (var3 != this.field21005) { this.field21005 = (int) ((float) this.field21005 + var6 * var7); } RenderUtil.drawRect(0.0F, 0.0F, (float) this.getWidthA(), (float) this.getHeightA(), MultiUtilities.applyAlpha(ClientColors.LIGHT_GREYISH_BLUE.getColor(), 0.95F)); } @Override public void keyPressed(int keyCode) { super.keyPressed(keyCode); if (keyCode == 256) { Minecraft.getInstance().displayGuiScreen(new VanillaMainMenuScreen()); } } @Override public JSONObject method13160(JSONObject var1) { this.accountManager.saveAlts(); return var1; } @Override public void loadConfig(JSONObject var1) { for (CustomGuiScreen var5 : this.field21010.method13241()) { if (!(var5 instanceof Class4292)) { for (CustomGuiScreen var7 : var5.method13241()) { this.field21010.method13234(var7); } } } this.method13372(true); } public void method13372(boolean var1) { List<Account> var5 = Class8270.method28878(this.accountManager.getAccounts(), this.field21023, this.field21024, this.field21026.getTypedText()); this.runThisOnDimensionUpdate(new Class1428(this, this, var5, var1)); } private void method13373(Object var1) { } public int method13374() { return Minecraft.getInstance().mainWindow.getHeight() / 12 + 280 + Minecraft.getInstance().mainWindow.getHeight() / 12; } // $VF: synthetic method public static Class4339 method13382(AltManagerScreen var0) { return var0.field21010; } // $VF: synthetic method public static Class4339 method13383(AltManagerScreen var0, Class4339 var1) { return var0.field21010 = var1; } // $VF: synthetic method public static float method13384(AltManagerScreen var0) { return var0.field21014; } // $VF: synthetic method public static int method13385(AltManagerScreen var0) { return var0.field21016; } // $VF: synthetic method public static void method13386(AltManagerScreen var0, Account var1, boolean var2) { var0.method13360(var1, var2); } }
0
0.848672
1
0.848672
game-dev
MEDIA
0.792929
game-dev
0.878102
1
0.878102
Swofty-Developments/HypixelSkyBlock
3,198
type.skyblockgeneric/src/main/java/net/swofty/type/skyblockgeneric/event/actions/player/authentication/PlayerChatAuthentication.java
package net.swofty.type.skyblockgeneric.event.actions.player.authentication; import net.minestom.server.event.player.PlayerChatEvent; import net.swofty.commons.ServerType; import net.swofty.type.generic.data.mongodb.AuthenticationDatabase; import net.swofty.type.generic.event.EventNodes; import net.swofty.type.generic.event.HypixelEvent; import net.swofty.type.generic.event.HypixelEventClass; import net.swofty.type.skyblockgeneric.user.SkyBlockPlayer; import java.util.HashMap; import java.util.Map; import java.util.UUID; public class PlayerChatAuthentication implements HypixelEventClass { private static Map<UUID, Long> cooldowns = new HashMap<>(); @HypixelEvent(node = EventNodes.PLAYER, requireDataLoaded = false) public void run(PlayerChatEvent event) { SkyBlockPlayer player = (SkyBlockPlayer) event.getPlayer(); if (player.hasAuthenticated) return; if (cooldowns.containsKey(player.getUuid())) { if (System.currentTimeMillis() - cooldowns.get(player.getUuid()) < 1000) { player.sendMessage("§cPlease wait before sending another message."); return; } } cooldowns.put(player.getUuid(), System.currentTimeMillis()); event.setCancelled(true); String[] args = event.getRawMessage().split(" "); AuthenticationDatabase.AuthenticationData data = new AuthenticationDatabase(player.getUuid()).getAuthenticationData(); if (data == null) { if (args.length != 3) { player.sendMessage("§cYou must first sign-up to play this server!"); player.sendMessage("§cIn the Minecraft chat, type §6signup <password> <password>§c."); player.sendMessage("§cIt is not a command, it's just a message. Nobody else can see it."); return; } if (!args[1].equals(args[2])) { player.sendMessage("§cYour passwords do not match."); return; } AuthenticationDatabase.AuthenticationData newData = AuthenticationDatabase.makeFromPassword(args[1]); new AuthenticationDatabase(player.getUuid()).setAuthenticationData(newData); player.sendMessage("§aYou have successfully signed up!"); player.sendMessage("§aNow, in the Minecraft chat, type §6login <password>§a."); player.sendMessage("§aIt is not a command, it's just a message. Nobody else can see it."); player.sendMessage("§8Salt: §7" + newData.salt()); } else { if (args.length != 2) { player.sendMessage("§cIn the Minecraft chat, type §6login <password>§c."); player.sendMessage("§cIt is not a command, it's just a message. Nobody else can see it."); return; } if (data.matches(args[1])) { player.sendMessage("§aYou have successfully logged in!"); player.sendTo(ServerType.SKYBLOCK_ISLAND, true); } else { player.sendMessage("§cYour password is incorrect."); player.sendMessage("§8Salt: §7" + data.salt()); } } } }
0
0.889849
1
0.889849
game-dev
MEDIA
0.746908
game-dev
0.934489
1
0.934489
fullwaywang/QlRules
1,921
libpng/d9006f6/png_check_keyword-autogen.ql
/** * @name libpng-d9006f683c641793252d92254a75ae9b815b42ed-png_check_keyword * @id cpp/libpng/d9006f683c641793252d92254a75ae9b815b42ed/png-check-keyword * @description libpng-d9006f683c641793252d92254a75ae9b815b42ed-png_check_keyword CVE-2015-8540 * @kind problem * @problem.severity error * @tags security */ import cpp predicate func_0(Variable vkey_len_1530) { exists(LogicalAndExpr target_0 | target_0.getAnOperand().(VariableAccess).getTarget()=vkey_len_1530 and target_0.getAnOperand() instanceof EqualityOperation) } predicate func_1(Variable vkp_1532) { exists(EqualityOperation target_1 | target_1.getAnOperand().(PointerDereferenceExpr).getOperand().(VariableAccess).getTarget()=vkp_1532 and target_1.getAnOperand().(CharLiteral).getValue()="32") } predicate func_2(Parameter vnew_key_1528, Variable vkey_len_1530, Variable vkp_1532) { exists(AssignExpr target_2 | target_2.getLValue().(VariableAccess).getTarget()=vkp_1532 and target_2.getRValue().(PointerArithmeticOperation).getLeftOperand().(PointerArithmeticOperation).getAnOperand().(PointerDereferenceExpr).getOperand().(VariableAccess).getTarget()=vnew_key_1528 and target_2.getRValue().(PointerArithmeticOperation).getLeftOperand().(PointerArithmeticOperation).getAnOperand().(VariableAccess).getTarget()=vkey_len_1530 and target_2.getRValue().(PointerArithmeticOperation).getRightOperand().(Literal).getValue()="1") } from Function func, Parameter vnew_key_1528, Variable vkey_len_1530, Variable vkp_1532 where not func_0(vkey_len_1530) and func_1(vkp_1532) and vkey_len_1530.getType().hasName("png_size_t") and func_2(vnew_key_1528, vkey_len_1530, vkp_1532) and vkp_1532.getType().hasName("png_charp") and vnew_key_1528.getParentScope+() = func and vkey_len_1530.getParentScope+() = func and vkp_1532.getParentScope+() = func select func, func.getFile().toString() + ":" + func.getLocation().getStartLine().toString()
0
0.72993
1
0.72993
game-dev
MEDIA
0.451026
game-dev,security-crypto
0.519275
1
0.519275
star4droid/Star2D
51,204
app/src/main/assets/files/examples/CarsExample/java/com/star4droid/Game/main.java
package com.star4droid.Game; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.physics.box2d.World; import com.badlogic.gdx.physics.box2d.joints.*; import com.badlogic.gdx.utils.viewport.FitViewport; import com.badlogic.gdx.utils.Timer; import com.star4droid.star2d.ElementDefs.*; import com.star4droid.star2d.Helpers.Project; import com.star4droid.template.Items.*; import com.star4droid.template.Utils.PlayerItem; import com.star4droid.template.Utils.ProjectAssetLoader; import com.badlogic.gdx.scenes.scene2d.InputEvent; import box2dLight.*; import box2dLight.RayHandler; // import .....script_here; public class main extends StageImp { PlayerItem background, Car4, Car2, Car1, Car, BW4, BW5, BW2, Car5, BW1, FW5, BW, FW4, FW2, FW1, FW, txt, Box2, Box3, Custom1, Box4, clouds, back, front, coin8, coin7, coin6, coin5, coin4, coin3, coin2, coin1; WheelJoint fwj; WheelJoint bwj; WheelJoint bwj1; WheelJoint bwj2; WheelJoint bwj5; WheelJoint bwj4; WheelJoint fwj1; WheelJoint fwj2; WheelJoint fwj4; WheelJoint fwj5; @Override public void onCreate() { BoxDef background_def = new BoxDef(); background_def.type = "UI"; background_def.Collider_Width = 719.976f; background_def.height = 1548.6714f; background_def.Script = "background"; background_def.image = "/blue_grass.png"; background_def.Collider_Height = 1548.6714f; background_def.name = "background"; background_def.width = 719.976f; background_def.Tint = "#FFFFFF"; background_def.elementEvents = new ElementEvent() { @Override public void onClick(PlayerItem current) {} @Override public void onTouchStart(PlayerItem current, InputEvent event) {} @Override public void onTouchEnd(PlayerItem current, InputEvent event) {} @Override public void onBodyCreated(PlayerItem current) {} @Override public void onBodyUpdate(PlayerItem current) {} @Override public void onCollisionBegin(PlayerItem current, PlayerItem body2) {} @Override public void onCollisionEnd(PlayerItem current, PlayerItem body2) {} @Override public String getName() { return "background"; } }; background = (PlayerItem) (background_def.build(this)); BoxDef Car4_def = new BoxDef(); Car4_def.Collider_Width = 183.22594f; Car4_def.Visible = false; Car4_def.height = 100.22926f; Car4_def.Script = "Car"; Car4_def.image = "/vehicles/v4.png"; Car4_def.density = 0.1f; Car4_def.Collider_Height = 100.22926f; Car4_def.Active = false; Car4_def.x = 177.30434f; Car4_def.name = "Car4"; Car4_def.width = 183.22594f; Car4_def.y = 988.5397f; Car4_def.z = 1f; Car4_def.Tint = "#FFFFFF"; Car4_def.elementEvents = new ElementEvent() { @Override public void onClick(PlayerItem current) {} @Override public void onTouchStart(PlayerItem current, InputEvent event) {} @Override public void onTouchEnd(PlayerItem current, InputEvent event) {} @Override public void onBodyCreated(PlayerItem current) {} @Override public void onBodyUpdate(PlayerItem current) {} @Override public void onCollisionBegin(PlayerItem current, PlayerItem body2) {} @Override public void onCollisionEnd(PlayerItem current, PlayerItem body2) {} @Override public String getName() { return "Car4"; } }; Car4 = (PlayerItem) (Car4_def.build(this)); Car4.setScript( new com.star4droid.Game.Scripts.main.CarScript().setItem(Car4).setStage(this)); BoxDef Car2_def = new BoxDef(); Car2_def.Collider_Width = 263.57828f; Car2_def.Visible = false; Car2_def.height = 94.142f; Car2_def.Script = "Car"; Car2_def.image = "/vehicles/v2.png"; Car2_def.density = 0.1f; Car2_def.Collider_Height = 94.142f; Car2_def.Active = false; Car2_def.x = 177.30434f; Car2_def.name = "Car2"; Car2_def.width = 263.57828f; Car2_def.y = 751.08276f; Car2_def.z = 3f; Car2_def.Tint = "#FFFFFF"; Car2_def.elementEvents = new ElementEvent() { @Override public void onClick(PlayerItem current) {} @Override public void onTouchStart(PlayerItem current, InputEvent event) {} @Override public void onTouchEnd(PlayerItem current, InputEvent event) {} @Override public void onBodyCreated(PlayerItem current) {} @Override public void onBodyUpdate(PlayerItem current) {} @Override public void onCollisionBegin(PlayerItem current, PlayerItem body2) {} @Override public void onCollisionEnd(PlayerItem current, PlayerItem body2) {} @Override public String getName() { return "Car2"; } }; Car2 = (PlayerItem) (Car2_def.build(this)); Car2.setScript( new com.star4droid.Game.Scripts.main.CarScript().setItem(Car2).setStage(this)); BoxDef Car1_def = new BoxDef(); Car1_def.Collider_Width = 263.57828f; Car1_def.Visible = false; Car1_def.height = 94.142f; Car1_def.Script = "Car"; Car1_def.image = "/vehicles/v1.png"; Car1_def.density = 0.1f; Car1_def.Collider_Height = 94.142f; Car1_def.Active = false; Car1_def.x = 177.30434f; Car1_def.name = "Car1"; Car1_def.width = 263.57828f; Car1_def.y = 988.5397f; Car1_def.z = 4f; Car1_def.Tint = "#FFFFFF"; Car1_def.Scale_X = -1.0f; Car1_def.elementEvents = new ElementEvent() { @Override public void onClick(PlayerItem current) {} @Override public void onTouchStart(PlayerItem current, InputEvent event) {} @Override public void onTouchEnd(PlayerItem current, InputEvent event) {} @Override public void onBodyCreated(PlayerItem current) {} @Override public void onBodyUpdate(PlayerItem current) {} @Override public void onCollisionBegin(PlayerItem current, PlayerItem body2) {} @Override public void onCollisionEnd(PlayerItem current, PlayerItem body2) {} @Override public String getName() { return "Car1"; } }; Car1 = (PlayerItem) (Car1_def.build(this)); Car1.setScript( new com.star4droid.Game.Scripts.main.CarScript().setItem(Car1).setStage(this)); BoxDef Car_def = new BoxDef(); Car_def.Collider_Width = 263.57828f; Car_def.Visible = false; Car_def.height = 94.142f; Car_def.Script = "Car"; Car_def.image = "/vehicles/v3.png"; Car_def.density = 0.1f; Car_def.Collider_Height = 94.142f; Car_def.Active = false; Car_def.x = 177.30434f; Car_def.name = "Car"; Car_def.width = 263.57828f; Car_def.y = 988.5397f; Car_def.z = 5f; Car_def.Tint = "#FFFFFF"; Car_def.elementEvents = new ElementEvent() { @Override public void onClick(PlayerItem current) {} @Override public void onTouchStart(PlayerItem current, InputEvent event) {} @Override public void onTouchEnd(PlayerItem current, InputEvent event) {} @Override public void onBodyCreated(PlayerItem current) {} @Override public void onBodyUpdate(PlayerItem current) {} @Override public void onCollisionBegin(PlayerItem current, PlayerItem body2) {} @Override public void onCollisionEnd(PlayerItem current, PlayerItem body2) {} @Override public String getName() { return "Car"; } }; Car = (PlayerItem) (Car_def.build(this)); Car.setScript(new com.star4droid.Game.Scripts.main.CarScript().setItem(Car).setStage(this)); CircleDef BW4_def = new CircleDef(); BW4_def.Visible = false; BW4_def.radius = 25.729733f; BW4_def.Script = "Circle1"; BW4_def.image = "/wheels/wheel1.png"; BW4_def.friction = 1.0f; BW4_def.Active = false; BW4_def.Collider_Radius = 25.729733f; BW4_def.restitution = 0.0f; BW4_def.x = 183.83943f; BW4_def.name = "BW4"; BW4_def.y = 1055.7869f; BW4_def.z = 6f; BW4_def.Tint = "#FFFFFF"; BW4_def.elementEvents = new ElementEvent() { @Override public void onClick(PlayerItem current) {} @Override public void onTouchStart(PlayerItem current, InputEvent event) {} @Override public void onTouchEnd(PlayerItem current, InputEvent event) {} @Override public void onBodyCreated(PlayerItem current) {} @Override public void onBodyUpdate(PlayerItem current) {} @Override public void onCollisionBegin(PlayerItem current, PlayerItem body2) {} @Override public void onCollisionEnd(PlayerItem current, PlayerItem body2) {} @Override public String getName() { return "BW4"; } }; BW4 = (PlayerItem) (BW4_def.build(this)); CircleDef BW5_def = new CircleDef(); BW5_def.Visible = false; BW5_def.radius = 18.5f; BW5_def.Script = "Circle1"; BW5_def.image = "/wheels/wheel1.png"; BW5_def.friction = 1.0f; BW5_def.Active = false; BW5_def.Collider_Radius = 18.5f; BW5_def.restitution = 0.0f; BW5_def.x = 203.82123f; BW5_def.name = "BW5"; BW5_def.y = 965.4272f; BW5_def.z = 7f; BW5_def.Tint = "#FFFFFF"; BW5_def.elementEvents = new ElementEvent() { @Override public void onClick(PlayerItem current) {} @Override public void onTouchStart(PlayerItem current, InputEvent event) {} @Override public void onTouchEnd(PlayerItem current, InputEvent event) {} @Override public void onBodyCreated(PlayerItem current) {} @Override public void onBodyUpdate(PlayerItem current) {} @Override public void onCollisionBegin(PlayerItem current, PlayerItem body2) {} @Override public void onCollisionEnd(PlayerItem current, PlayerItem body2) {} @Override public String getName() { return "BW5"; } }; BW5 = (PlayerItem) (BW5_def.build(this)); CircleDef BW2_def = new CircleDef(); BW2_def.Visible = false; BW2_def.radius = 25.729733f; BW2_def.Script = "Circle1"; BW2_def.image = "/wheels/wheel1.png"; BW2_def.friction = 1.0f; BW2_def.Active = false; BW2_def.Collider_Radius = 25.729733f; BW2_def.restitution = 0.0f; BW2_def.x = 204.85124f; BW2_def.name = "BW2"; BW2_def.y = 819.0303f; BW2_def.z = 8f; BW2_def.Tint = "#FFFFFF"; BW2_def.elementEvents = new ElementEvent() { @Override public void onClick(PlayerItem current) {} @Override public void onTouchStart(PlayerItem current, InputEvent event) {} @Override public void onTouchEnd(PlayerItem current, InputEvent event) {} @Override public void onBodyCreated(PlayerItem current) {} @Override public void onBodyUpdate(PlayerItem current) {} @Override public void onCollisionBegin(PlayerItem current, PlayerItem body2) {} @Override public void onCollisionEnd(PlayerItem current, PlayerItem body2) {} @Override public String getName() { return "BW2"; } }; BW2 = (PlayerItem) (BW2_def.build(this)); BoxDef Car5_def = new BoxDef(); Car5_def.Collider_Width = 190.83786f; Car5_def.Visible = false; Car5_def.height = 99.12422f; Car5_def.Script = "Car"; Car5_def.image = "/vehicles/v5.png"; Car5_def.density = 0.1f; Car5_def.Collider_Height = 99.12422f; Car5_def.Active = false; Car5_def.x = 185.54419f; Car5_def.name = "Car5"; Car5_def.width = 190.83786f; Car5_def.y = 876.59155f; Car5_def.z = 9f; Car5_def.Tint = "#FFFFFF"; Car5_def.elementEvents = new ElementEvent() { @Override public void onClick(PlayerItem current) {} @Override public void onTouchStart(PlayerItem current, InputEvent event) {} @Override public void onTouchEnd(PlayerItem current, InputEvent event) {} @Override public void onBodyCreated(PlayerItem current) {} @Override public void onBodyUpdate(PlayerItem current) {} @Override public void onCollisionBegin(PlayerItem current, PlayerItem body2) {} @Override public void onCollisionEnd(PlayerItem current, PlayerItem body2) {} @Override public String getName() { return "Car5"; } }; Car5 = (PlayerItem) (Car5_def.build(this)); Car5.setScript( new com.star4droid.Game.Scripts.main.CarScript().setItem(Car5).setStage(this)); CircleDef BW1_def = new CircleDef(); BW1_def.Visible = false; BW1_def.radius = 25.729733f; BW1_def.Script = "Circle1"; BW1_def.image = "/wheels/wheel1.png"; BW1_def.friction = 1.0f; BW1_def.Active = false; BW1_def.Collider_Radius = 25.729733f; BW1_def.restitution = 0.0f; BW1_def.x = 202.9971f; BW1_def.name = "BW1"; BW1_def.y = 1062.9982f; BW1_def.z = 10f; BW1_def.Tint = "#FFFFFF"; BW1_def.elementEvents = new ElementEvent() { @Override public void onClick(PlayerItem current) {} @Override public void onTouchStart(PlayerItem current, InputEvent event) {} @Override public void onTouchEnd(PlayerItem current, InputEvent event) {} @Override public void onBodyCreated(PlayerItem current) {} @Override public void onBodyUpdate(PlayerItem current) {} @Override public void onCollisionBegin(PlayerItem current, PlayerItem body2) {} @Override public void onCollisionEnd(PlayerItem current, PlayerItem body2) {} @Override public String getName() { return "BW1"; } }; BW1 = (PlayerItem) (BW1_def.build(this)); CircleDef FW5_def = new CircleDef(); FW5_def.Visible = false; FW5_def.radius = 18.519806f; FW5_def.Script = "Circle1"; FW5_def.image = "/wheels/wheel1.png"; FW5_def.friction = 1.0f; FW5_def.Active = false; FW5_def.Collider_Radius = 18.519806f; FW5_def.restitution = 0.0f; FW5_def.x = 312.92255f; FW5_def.name = "FW5"; FW5_def.y = 968.0736f; FW5_def.z = 11f; FW5_def.Tint = "#FFFFFF"; FW5_def.elementEvents = new ElementEvent() { @Override public void onClick(PlayerItem current) {} @Override public void onTouchStart(PlayerItem current, InputEvent event) {} @Override public void onTouchEnd(PlayerItem current, InputEvent event) {} @Override public void onBodyCreated(PlayerItem current) {} @Override public void onBodyUpdate(PlayerItem current) {} @Override public void onCollisionBegin(PlayerItem current, PlayerItem body2) {} @Override public void onCollisionEnd(PlayerItem current, PlayerItem body2) {} @Override public String getName() { return "FW5"; } }; FW5 = (PlayerItem) (FW5_def.build(this)); CircleDef BW_def = new CircleDef(); BW_def.Visible = false; BW_def.radius = 25.729733f; BW_def.Script = "Circle1"; BW_def.image = "/wheels/wheel1.png"; BW_def.friction = 1.0f; BW_def.Collider_Radius = 25.729733f; BW_def.restitution = 0.0f; BW_def.x = 196.81729f; BW_def.name = "BW"; BW_def.y = 1055.7869f; BW_def.z = 12f; BW_def.Tint = "#FFFFFF"; BW_def.elementEvents = new ElementEvent() { @Override public void onClick(PlayerItem current) {} @Override public void onTouchStart(PlayerItem current, InputEvent event) {} @Override public void onTouchEnd(PlayerItem current, InputEvent event) {} @Override public void onBodyCreated(PlayerItem current) {} @Override public void onBodyUpdate(PlayerItem current) {} @Override public void onCollisionBegin(PlayerItem current, PlayerItem body2) {} @Override public void onCollisionEnd(PlayerItem current, PlayerItem body2) {} @Override public String getName() { return "BW"; } }; BW = (PlayerItem) (BW_def.build(this)); CircleDef FW4_def = new CircleDef(); FW4_def.Visible = false; FW4_def.radius = 25.729733f; FW4_def.Script = "Circle1"; FW4_def.image = "/wheels/wheel1.png"; FW4_def.friction = 1.0f; FW4_def.Active = false; FW4_def.Collider_Radius = 25.729733f; FW4_def.restitution = 0.0f; FW4_def.x = 304.8703f; FW4_def.name = "FW4"; FW4_def.y = 1055.0137f; FW4_def.z = 13f; FW4_def.Tint = "#FFFFFF"; FW4_def.elementEvents = new ElementEvent() { @Override public void onClick(PlayerItem current) {} @Override public void onTouchStart(PlayerItem current, InputEvent event) {} @Override public void onTouchEnd(PlayerItem current, InputEvent event) {} @Override public void onBodyCreated(PlayerItem current) {} @Override public void onBodyUpdate(PlayerItem current) {} @Override public void onCollisionBegin(PlayerItem current, PlayerItem body2) {} @Override public void onCollisionEnd(PlayerItem current, PlayerItem body2) {} @Override public String getName() { return "FW4"; } }; FW4 = (PlayerItem) (FW4_def.build(this)); CircleDef FW2_def = new CircleDef(); FW2_def.Visible = false; FW2_def.radius = 25.729733f; FW2_def.Script = "Circle1"; FW2_def.image = "/wheels/wheel1.png"; FW2_def.friction = 1.0f; FW2_def.Active = false; FW2_def.Collider_Radius = 25.729733f; FW2_def.restitution = 0.0f; FW2_def.x = 342.38058f; FW2_def.name = "FW2"; FW2_def.y = 821.26514f; FW2_def.z = 14f; FW2_def.Tint = "#FFFFFF"; FW2_def.elementEvents = new ElementEvent() { @Override public void onClick(PlayerItem current) {} @Override public void onTouchStart(PlayerItem current, InputEvent event) {} @Override public void onTouchEnd(PlayerItem current, InputEvent event) {} @Override public void onBodyCreated(PlayerItem current) {} @Override public void onBodyUpdate(PlayerItem current) {} @Override public void onCollisionBegin(PlayerItem current, PlayerItem body2) {} @Override public void onCollisionEnd(PlayerItem current, PlayerItem body2) {} @Override public String getName() { return "FW2"; } }; FW2 = (PlayerItem) (FW2_def.build(this)); CircleDef FW1_def = new CircleDef(); FW1_def.Visible = false; FW1_def.radius = 25.729733f; FW1_def.Script = "Circle1"; FW1_def.image = "/wheels/wheel1.png"; FW1_def.friction = 1.0f; FW1_def.Active = false; FW1_def.Collider_Radius = 25.729733f; FW1_def.restitution = 0.0f; FW1_def.x = 367.3062f; FW1_def.name = "FW1"; FW1_def.y = 1063.6664f; FW1_def.z = 15f; FW1_def.Tint = "#FFFFFF"; FW1_def.elementEvents = new ElementEvent() { @Override public void onClick(PlayerItem current) {} @Override public void onTouchStart(PlayerItem current, InputEvent event) {} @Override public void onTouchEnd(PlayerItem current, InputEvent event) {} @Override public void onBodyCreated(PlayerItem current) {} @Override public void onBodyUpdate(PlayerItem current) {} @Override public void onCollisionBegin(PlayerItem current, PlayerItem body2) {} @Override public void onCollisionEnd(PlayerItem current, PlayerItem body2) {} @Override public String getName() { return "FW1"; } }; FW1 = (PlayerItem) (FW1_def.build(this)); CircleDef FW_def = new CircleDef(); FW_def.Visible = false; FW_def.radius = 25.729733f; FW_def.Script = "Circle1"; FW_def.image = "/wheels/wheel1.png"; FW_def.friction = 1.0f; FW_def.Active = false; FW_def.Collider_Radius = 25.729733f; FW_def.restitution = 0.0f; FW_def.x = 368.13013f; FW_def.name = "FW"; FW_def.y = 1055.0137f; FW_def.z = 16f; FW_def.Tint = "#FFFFFF"; FW_def.elementEvents = new ElementEvent() { @Override public void onClick(PlayerItem current) {} @Override public void onTouchStart(PlayerItem current, InputEvent event) {} @Override public void onTouchEnd(PlayerItem current, InputEvent event) {} @Override public void onBodyCreated(PlayerItem current) {} @Override public void onBodyUpdate(PlayerItem current) {} @Override public void onCollisionBegin(PlayerItem current, PlayerItem body2) {} @Override public void onCollisionEnd(PlayerItem current, PlayerItem body2) {} @Override public String getName() { return "FW"; } }; FW = (PlayerItem) (FW_def.build(this)); TextDef txt_def = new TextDef(); txt_def.Script = "txt"; txt_def.Font_Scale = 5.0f; txt_def.Text = "coins : 0"; txt_def.name = "txt"; txt_def.width = 495.31616f; txt_def.z = 17f; txt_def.height = 190.41243f; txt_def.elementEvents = new ElementEvent() { @Override public void onClick(PlayerItem current) {} @Override public void onTouchStart(PlayerItem current, InputEvent event) {} @Override public void onTouchEnd(PlayerItem current, InputEvent event) {} @Override public void onBodyCreated(PlayerItem current) {} @Override public void onBodyUpdate(PlayerItem current) {} @Override public void onCollisionBegin(PlayerItem current, PlayerItem body2) {} @Override public void onCollisionEnd(PlayerItem current, PlayerItem body2) {} @Override public String getName() { return "txt"; } }; txt = (PlayerItem) (txt_def.build(this)); BoxDef Box2_def = new BoxDef(); Box2_def.type = "STATIC"; Box2_def.Collider_Width = 50f; Box2_def.Script = "Box2"; Box2_def.image = "/ground.png"; Box2_def.Collider_Height = 50f; Box2_def.rotation = 160.86105800866983f; Box2_def.x = 500.10446f; Box2_def.name = "Box2"; Box2_def.y = 1106.7452f; Box2_def.z = 18f; Box2_def.Tint = "#FFFFFF"; Box2_def.elementEvents = new ElementEvent() { @Override public void onClick(PlayerItem current) {} @Override public void onTouchStart(PlayerItem current, InputEvent event) {} @Override public void onTouchEnd(PlayerItem current, InputEvent event) {} @Override public void onBodyCreated(PlayerItem current) {} @Override public void onBodyUpdate(PlayerItem current) {} @Override public void onCollisionBegin(PlayerItem current, PlayerItem body2) {} @Override public void onCollisionEnd(PlayerItem current, PlayerItem body2) {} @Override public String getName() { return "Box2"; } }; Box2 = (PlayerItem) (Box2_def.build(this)); BoxDef Box3_def = new BoxDef(); Box3_def.type = "STATIC"; Box3_def.Collider_Width = 50f; Box3_def.Script = "Box2"; Box3_def.image = "/ground.png"; Box3_def.Collider_Height = 50f; Box3_def.rotation = 22.46123698746362f; Box3_def.x = 836.4872f; Box3_def.name = "Box3"; Box3_def.y = 1107.0741f; Box3_def.z = 19f; Box3_def.Tint = "#FFFFFF"; Box3_def.elementEvents = new ElementEvent() { @Override public void onClick(PlayerItem current) {} @Override public void onTouchStart(PlayerItem current, InputEvent event) {} @Override public void onTouchEnd(PlayerItem current, InputEvent event) {} @Override public void onBodyCreated(PlayerItem current) {} @Override public void onBodyUpdate(PlayerItem current) {} @Override public void onCollisionBegin(PlayerItem current, PlayerItem body2) {} @Override public void onCollisionEnd(PlayerItem current, PlayerItem body2) {} @Override public String getName() { return "Box3"; } }; Box3 = (PlayerItem) (Box3_def.build(this)); CustomDef Custom1_def = new CustomDef(); Custom1_def.type = "STATIC"; Custom1_def.Points = "0.0025252525,0.119802654-0.09343434,0.17383134-0.21464646,0.19191921-0.28282827,0.16960305-0.3989899,0.13436693-0.59090906,0.16020674-0.6388889,0.1484614-0.7929293,0.087385535-0.85353535,0.05919665-0.92676765,0.06506932-1.0,0.107352614-0.05050505,0.9765093"; Custom1_def.height = 120.62603f; Custom1_def.Script = "Custom1"; Custom1_def.image = "/others/SceneBG.png"; Custom1_def.x = 539.3039f; Custom1_def.name = "Custom1"; Custom1_def.width = 311.06378f; Custom1_def.y = 1085.6296f; Custom1_def.z = 20f; Custom1_def.Tint = "#FFFFFF"; Custom1_def.elementEvents = new ElementEvent() { @Override public void onClick(PlayerItem current) {} @Override public void onTouchStart(PlayerItem current, InputEvent event) {} @Override public void onTouchEnd(PlayerItem current, InputEvent event) {} @Override public void onBodyCreated(PlayerItem current) {} @Override public void onBodyUpdate(PlayerItem current) {} @Override public void onCollisionBegin(PlayerItem current, PlayerItem body2) {} @Override public void onCollisionEnd(PlayerItem current, PlayerItem body2) {} @Override public String getName() { return "Custom1"; } }; Custom1 = (PlayerItem) (Custom1_def.build(this)); BoxDef Box4_def = new BoxDef(); Box4_def.type = "STATIC"; Box4_def.Collider_Width = 2800.0f; Box4_def.Script = "Box4"; Box4_def.image = "/ground.png"; Box4_def.Collider_Height = 50f; Box4_def.friction = 1.0f; Box4_def.x = 6.205269f; Box4_def.name = "Box4"; Box4_def.width = 2800.0f; Box4_def.y = 1108.0842f; Box4_def.z = 2f; Box4_def.Tint = "#FFFFFF"; Box4_def.tileX = 1.038f; Box4_def.elementEvents = new ElementEvent() { @Override public void onClick(PlayerItem current) {} @Override public void onTouchStart(PlayerItem current, InputEvent event) {} @Override public void onTouchEnd(PlayerItem current, InputEvent event) {} @Override public void onBodyCreated(PlayerItem current) {} @Override public void onBodyUpdate(PlayerItem current) {} @Override public void onCollisionBegin(PlayerItem current, PlayerItem body2) {} @Override public void onCollisionEnd(PlayerItem current, PlayerItem body2) {} @Override public String getName() { return "Box4"; } }; Box4 = (PlayerItem) (Box4_def.build(this)); BoxDef clouds_def = new BoxDef(); clouds_def.type = "STATIC"; clouds_def.Collider_Width = 676.0719f; clouds_def.height = 434.0807f; clouds_def.Script = "clouds"; clouds_def.image = "/others/Clouds.png"; clouds_def.Collider_Height = 434.0807f; clouds_def.Active = false; clouds_def.x = 1.1100509f; clouds_def.name = "clouds"; clouds_def.width = 676.0719f; clouds_def.y = 147.63751f; clouds_def.z = 21f; clouds_def.Tint = "#FFFFFF"; clouds_def.elementEvents = new ElementEvent() { @Override public void onClick(PlayerItem current) {} @Override public void onTouchStart(PlayerItem current, InputEvent event) {} @Override public void onTouchEnd(PlayerItem current, InputEvent event) {} @Override public void onBodyCreated(PlayerItem current) {} @Override public void onBodyUpdate(PlayerItem current) {} @Override public void onCollisionBegin(PlayerItem current, PlayerItem body2) {} @Override public void onCollisionEnd(PlayerItem current, PlayerItem body2) {} @Override public String getName() { return "clouds"; } }; clouds = (PlayerItem) (clouds_def.build(this)); BoxDef back_def = new BoxDef(); back_def.type = "UI"; back_def.Collider_Width = 134.36433f; back_def.height = 145.4649f; back_def.Script = "back"; back_def.image = "/btn.png"; back_def.Collider_Height = 145.4649f; back_def.rotation = 270.0f; back_def.x = 28.861483f; back_def.name = "back"; back_def.width = 134.36433f; back_def.y = 818.1119f; back_def.z = 22f; back_def.Tint = "#FFFFFF"; back_def.elementEvents = new ElementEvent() { @Override public void onClick(PlayerItem current) {} @Override public void onTouchStart(PlayerItem current, InputEvent event) { bwj.setMotorSpeed(80); bwj.enableMotor(true); } @Override public void onTouchEnd(PlayerItem current, InputEvent event) { bwj.enableMotor(false); } @Override public void onBodyCreated(PlayerItem current) {} @Override public void onBodyUpdate(PlayerItem current) {} @Override public void onCollisionBegin(PlayerItem current, PlayerItem body2) {} @Override public void onCollisionEnd(PlayerItem current, PlayerItem body2) {} @Override public String getName() { return "back"; } }; back = (PlayerItem) (back_def.build(this)); BoxDef front_def = new BoxDef(); front_def.type = "UI"; front_def.Collider_Width = 134.36433f; front_def.height = 145.4649f; front_def.Script = "front"; front_def.image = "/btn.png"; front_def.Collider_Height = 145.4649f; front_def.rotation = 90.0f; front_def.x = 533.93726f; front_def.name = "front"; front_def.width = 134.36433f; front_def.y = 818.1119f; front_def.z = 23f; front_def.Tint = "#FFFFFF"; front_def.elementEvents = new ElementEvent() { @Override public void onClick(PlayerItem current) {} @Override public void onTouchStart(PlayerItem current, InputEvent event) { bwj.enableMotor(true); bwj.setMotorSpeed(-80); } @Override public void onTouchEnd(PlayerItem current, InputEvent event) { bwj.enableMotor(false); pauseSound("EngineSound.ogg"); } @Override public void onBodyCreated(PlayerItem current) {} @Override public void onBodyUpdate(PlayerItem current) {} @Override public void onCollisionBegin(PlayerItem current, PlayerItem body2) {} @Override public void onCollisionEnd(PlayerItem current, PlayerItem body2) {} @Override public String getName() { return "front"; } }; front = (PlayerItem) (front_def.build(this)); BoxDef coin8_def = new BoxDef(); coin8_def.type = "STATIC"; coin8_def.Collider_Width = 75.91301f; coin8_def.height = 67.568146f; coin8_def.Script = "coin1"; coin8_def.image = "/others/Coin5.png"; coin8_def.Collider_Height = 67.568146f; coin8_def.isSensor = true; coin8_def.x = 564.23206f; coin8_def.name = "coin8"; coin8_def.width = 75.91301f; coin8_def.y = 1032.09f; coin8_def.z = 24f; coin8_def.Tint = "#FFFFFF"; coin8_def.elementEvents = new ElementEvent() { @Override public void onClick(PlayerItem current) {} @Override public void onTouchStart(PlayerItem current, InputEvent event) {} @Override public void onTouchEnd(PlayerItem current, InputEvent event) {} @Override public void onBodyCreated(PlayerItem current) {} @Override public void onBodyUpdate(PlayerItem current) {} @Override public void onCollisionBegin(PlayerItem current, PlayerItem body2) {} @Override public void onCollisionEnd(PlayerItem current, PlayerItem body2) {} @Override public String getName() { return "coin8"; } }; coin8 = (PlayerItem) (coin8_def.build(this)); BoxDef coin7_def = new BoxDef(); coin7_def.type = "STATIC"; coin7_def.Collider_Width = 75.91301f; coin7_def.height = 67.568146f; coin7_def.Script = "coin1"; coin7_def.image = "/others/Coin5.png"; coin7_def.Collider_Height = 67.568146f; coin7_def.isSensor = true; coin7_def.x = 1445.7921f; coin7_def.name = "coin7"; coin7_def.width = 75.91301f; coin7_def.y = 1037.6859f; coin7_def.z = 25f; coin7_def.Tint = "#FFFFFF"; coin7_def.elementEvents = new ElementEvent() { @Override public void onClick(PlayerItem current) {} @Override public void onTouchStart(PlayerItem current, InputEvent event) {} @Override public void onTouchEnd(PlayerItem current, InputEvent event) {} @Override public void onBodyCreated(PlayerItem current) {} @Override public void onBodyUpdate(PlayerItem current) {} @Override public void onCollisionBegin(PlayerItem current, PlayerItem body2) {} @Override public void onCollisionEnd(PlayerItem current, PlayerItem body2) {} @Override public String getName() { return "coin7"; } }; coin7 = (PlayerItem) (coin7_def.build(this)); BoxDef coin6_def = new BoxDef(); coin6_def.type = "STATIC"; coin6_def.Collider_Width = 75.91301f; coin6_def.height = 67.568146f; coin6_def.Script = "coin1"; coin6_def.image = "/others/Coin5.png"; coin6_def.Collider_Height = 67.568146f; coin6_def.isSensor = true; coin6_def.x = 1301.7496f; coin6_def.name = "coin6"; coin6_def.width = 75.91301f; coin6_def.y = 1037.6859f; coin6_def.z = 26f; coin6_def.Tint = "#FFFFFF"; coin6_def.elementEvents = new ElementEvent() { @Override public void onClick(PlayerItem current) {} @Override public void onTouchStart(PlayerItem current, InputEvent event) {} @Override public void onTouchEnd(PlayerItem current, InputEvent event) {} @Override public void onBodyCreated(PlayerItem current) {} @Override public void onBodyUpdate(PlayerItem current) {} @Override public void onCollisionBegin(PlayerItem current, PlayerItem body2) {} @Override public void onCollisionEnd(PlayerItem current, PlayerItem body2) {} @Override public String getName() { return "coin6"; } }; coin6 = (PlayerItem) (coin6_def.build(this)); BoxDef coin5_def = new BoxDef(); coin5_def.type = "STATIC"; coin5_def.Collider_Width = 75.91301f; coin5_def.height = 67.568146f; coin5_def.Script = "coin1"; coin5_def.image = "/others/Coin5.png"; coin5_def.Collider_Height = 67.568146f; coin5_def.isSensor = true; coin5_def.x = 1172.1495f; coin5_def.name = "coin5"; coin5_def.width = 75.91301f; coin5_def.y = 1037.6859f; coin5_def.z = 27f; coin5_def.Tint = "#FFFFFF"; coin5_def.elementEvents = new ElementEvent() { @Override public void onClick(PlayerItem current) {} @Override public void onTouchStart(PlayerItem current, InputEvent event) {} @Override public void onTouchEnd(PlayerItem current, InputEvent event) {} @Override public void onBodyCreated(PlayerItem current) {} @Override public void onBodyUpdate(PlayerItem current) {} @Override public void onCollisionBegin(PlayerItem current, PlayerItem body2) {} @Override public void onCollisionEnd(PlayerItem current, PlayerItem body2) {} @Override public String getName() { return "coin5"; } }; coin5 = (PlayerItem) (coin5_def.build(this)); BoxDef coin4_def = new BoxDef(); coin4_def.type = "STATIC"; coin4_def.Collider_Width = 75.91301f; coin4_def.height = 67.568146f; coin4_def.Script = "coin1"; coin4_def.image = "/others/Coin5.png"; coin4_def.Collider_Height = 67.568146f; coin4_def.isSensor = true; coin4_def.x = 1043.1292f; coin4_def.name = "coin4"; coin4_def.width = 75.91301f; coin4_def.y = 1037.6859f; coin4_def.z = 28f; coin4_def.Tint = "#FFFFFF"; coin4_def.elementEvents = new ElementEvent() { @Override public void onClick(PlayerItem current) {} @Override public void onTouchStart(PlayerItem current, InputEvent event) {} @Override public void onTouchEnd(PlayerItem current, InputEvent event) {} @Override public void onBodyCreated(PlayerItem current) {} @Override public void onBodyUpdate(PlayerItem current) {} @Override public void onCollisionBegin(PlayerItem current, PlayerItem body2) {} @Override public void onCollisionEnd(PlayerItem current, PlayerItem body2) {} @Override public String getName() { return "coin4"; } }; coin4 = (PlayerItem) (coin4_def.build(this)); BoxDef coin3_def = new BoxDef(); coin3_def.type = "STATIC"; coin3_def.Collider_Width = 75.91301f; coin3_def.height = 67.568146f; coin3_def.Script = "coin1"; coin3_def.image = "/others/Coin5.png"; coin3_def.Collider_Height = 67.568146f; coin3_def.isSensor = true; coin3_def.x = 916.2543f; coin3_def.name = "coin3"; coin3_def.width = 75.91301f; coin3_def.y = 1037.6859f; coin3_def.z = 29f; coin3_def.Tint = "#FFFFFF"; coin3_def.elementEvents = new ElementEvent() { @Override public void onClick(PlayerItem current) {} @Override public void onTouchStart(PlayerItem current, InputEvent event) {} @Override public void onTouchEnd(PlayerItem current, InputEvent event) {} @Override public void onBodyCreated(PlayerItem current) {} @Override public void onBodyUpdate(PlayerItem current) {} @Override public void onCollisionBegin(PlayerItem current, PlayerItem body2) {} @Override public void onCollisionEnd(PlayerItem current, PlayerItem body2) {} @Override public String getName() { return "coin3"; } }; coin3 = (PlayerItem) (coin3_def.build(this)); BoxDef coin2_def = new BoxDef(); coin2_def.type = "STATIC"; coin2_def.Collider_Width = 75.91301f; coin2_def.height = 67.568146f; coin2_def.Script = "coin1"; coin2_def.image = "/others/Coin5.png"; coin2_def.Collider_Height = 67.568146f; coin2_def.isSensor = true; coin2_def.x = 795.3418f; coin2_def.name = "coin2"; coin2_def.width = 75.91301f; coin2_def.y = 1014.7426f; coin2_def.z = 30f; coin2_def.Tint = "#FFFFFF"; coin2_def.elementEvents = new ElementEvent() { @Override public void onClick(PlayerItem current) {} @Override public void onTouchStart(PlayerItem current, InputEvent event) {} @Override public void onTouchEnd(PlayerItem current, InputEvent event) {} @Override public void onBodyCreated(PlayerItem current) {} @Override public void onBodyUpdate(PlayerItem current) {} @Override public void onCollisionBegin(PlayerItem current, PlayerItem body2) {} @Override public void onCollisionEnd(PlayerItem current, PlayerItem body2) {} @Override public String getName() { return "coin2"; } }; coin2 = (PlayerItem) (coin2_def.build(this)); BoxDef coin1_def = new BoxDef(); coin1_def.type = "STATIC"; coin1_def.Collider_Width = 75.91301f; coin1_def.height = 67.568146f; coin1_def.Script = "coin1"; coin1_def.image = "/others/Coin5.png"; coin1_def.Collider_Height = 67.568146f; coin1_def.isSensor = true; coin1_def.x = 676.84644f; coin1_def.name = "coin1"; coin1_def.width = 75.91301f; coin1_def.y = 1023.69586f; coin1_def.z = 31f; coin1_def.Tint = "#FFFFFF"; coin1_def.elementEvents = new ElementEvent() { @Override public void onClick(PlayerItem current) {} @Override public void onTouchStart(PlayerItem current, InputEvent event) {} @Override public void onTouchEnd(PlayerItem current, InputEvent event) {} @Override public void onBodyCreated(PlayerItem current) {} @Override public void onBodyUpdate(PlayerItem current) {} @Override public void onCollisionBegin(PlayerItem current, PlayerItem body2) {} @Override public void onCollisionEnd(PlayerItem current, PlayerItem body2) {} @Override public String getName() { return "coin1"; } }; coin1 = (PlayerItem) (coin1_def.build(this)); background.getActor().setZIndex((int) (background_def.z)); Car4.getActor().setZIndex((int) (Car4_def.z)); Car2.getActor().setZIndex((int) (Car2_def.z)); Car1.getActor().setZIndex((int) (Car1_def.z)); Car.getActor().setZIndex((int) (Car_def.z)); BW4.getActor().setZIndex((int) (BW4_def.z)); BW5.getActor().setZIndex((int) (BW5_def.z)); BW2.getActor().setZIndex((int) (BW2_def.z)); Car5.getActor().setZIndex((int) (Car5_def.z)); BW1.getActor().setZIndex((int) (BW1_def.z)); FW5.getActor().setZIndex((int) (FW5_def.z)); BW.getActor().setZIndex((int) (BW_def.z)); FW4.getActor().setZIndex((int) (FW4_def.z)); FW2.getActor().setZIndex((int) (FW2_def.z)); FW1.getActor().setZIndex((int) (FW1_def.z)); FW.getActor().setZIndex((int) (FW_def.z)); txt.getActor().setZIndex((int) (txt_def.z)); Box2.getActor().setZIndex((int) (Box2_def.z)); Box3.getActor().setZIndex((int) (Box3_def.z)); Custom1.getActor().setZIndex((int) (Custom1_def.z)); Box4.getActor().setZIndex((int) (Box4_def.z)); clouds.getActor().setZIndex((int) (clouds_def.z)); back.getActor().setZIndex((int) (back_def.z)); front.getActor().setZIndex((int) (front_def.z)); coin8.getActor().setZIndex((int) (coin8_def.z)); coin7.getActor().setZIndex((int) (coin7_def.z)); coin6.getActor().setZIndex((int) (coin6_def.z)); coin5.getActor().setZIndex((int) (coin5_def.z)); coin4.getActor().setZIndex((int) (coin4_def.z)); coin3.getActor().setZIndex((int) (coin3_def.z)); coin2.getActor().setZIndex((int) (coin2_def.z)); coin1.getActor().setZIndex((int) (coin1_def.z)); Car4.addChild(BW4); Car5.addChild(BW5); Car2.addChild(BW2); Car1.addChild(BW1); Car5.addChild(FW5); Car.addChild(BW); Car4.addChild(FW4); Car2.addChild(FW2); Car1.addChild(FW1); Car.addChild(FW); WheelJointDef fwj_Def = new WheelJointDef(); fwj_Def.dampingRatio = 0.7f; fwj_Def.enableMotor = false; fwj_Def.frequencyHz = 10.0f; fwj_Def.localAnchorA.set(new Vector2(0.0f * 0.25f, 0.0f * 0.25f)); fwj_Def.localAnchorB.set(new Vector2(0.0f * 0.25f, 0.0f * 0.25f)); fwj_Def.localAxisA.set(new Vector2(1.0f * 0.25f, 0.0f * 0.25f)); fwj_Def.maxMotorTorque = 0.0f; fwj_Def.motorSpeed = 0.0f; fwj_Def.collideConnected = false; fwj_Def.initialize( Car.getBody(), FW.getBody(), FW.getBody().getWorldCenter(), new Vector2(0f * 0.25f, 1f * 0.25f)); fwj = (WheelJoint) (this.world.createJoint(fwj_Def)); addJoint("fwj", fwj); WheelJointDef bwj_Def = new WheelJointDef(); bwj_Def.dampingRatio = 0.7f; bwj_Def.enableMotor = false; bwj_Def.frequencyHz = 10.0f; bwj_Def.localAnchorA.set(new Vector2(0.0f * 0.25f, 0.0f * 0.25f)); bwj_Def.localAnchorB.set(new Vector2(0.0f * 0.25f, 0.0f * 0.25f)); bwj_Def.localAxisA.set(new Vector2(1.0f * 0.25f, 0.0f * 0.25f)); bwj_Def.maxMotorTorque = 9999.0f; bwj_Def.motorSpeed = -80.0f; bwj_Def.collideConnected = false; bwj_Def.initialize( Car.getBody(), BW.getBody(), BW.getBody().getWorldCenter(), new Vector2(0f * 0.25f, 1f * 0.25f)); bwj = (WheelJoint) (this.world.createJoint(bwj_Def)); addJoint("bwj", bwj); WheelJointDef bwj1_Def = new WheelJointDef(); bwj1_Def.dampingRatio = 0.7f; bwj1_Def.enableMotor = false; bwj1_Def.frequencyHz = 10.0f; bwj1_Def.localAnchorA.set(new Vector2(0.0f * 0.25f, 0.0f * 0.25f)); bwj1_Def.localAnchorB.set(new Vector2(0.0f * 0.25f, 0.0f * 0.25f)); bwj1_Def.localAxisA.set(new Vector2(1.0f * 0.25f, 0.0f * 0.25f)); bwj1_Def.maxMotorTorque = 9999.0f; bwj1_Def.motorSpeed = -80.0f; bwj1_Def.collideConnected = false; bwj1_Def.initialize( Car1.getBody(), BW1.getBody(), BW1.getBody().getWorldCenter(), new Vector2(0f * 0.25f, 1f * 0.25f)); bwj1 = (WheelJoint) (this.world.createJoint(bwj1_Def)); addJoint("bwj1", bwj1); WheelJointDef bwj2_Def = new WheelJointDef(); bwj2_Def.dampingRatio = 0.7f; bwj2_Def.enableMotor = false; bwj2_Def.frequencyHz = 10.0f; bwj2_Def.localAnchorA.set(new Vector2(0.0f * 0.25f, 0.0f * 0.25f)); bwj2_Def.localAnchorB.set(new Vector2(0.0f * 0.25f, 0.0f * 0.25f)); bwj2_Def.localAxisA.set(new Vector2(1.0f * 0.25f, 0.0f * 0.25f)); bwj2_Def.maxMotorTorque = 9999.0f; bwj2_Def.motorSpeed = -80.0f; bwj2_Def.collideConnected = false; bwj2_Def.initialize( Car2.getBody(), BW2.getBody(), BW2.getBody().getWorldCenter(), new Vector2(0f * 0.25f, 1f * 0.25f)); bwj2 = (WheelJoint) (this.world.createJoint(bwj2_Def)); addJoint("bwj2", bwj2); WheelJointDef bwj5_Def = new WheelJointDef(); bwj5_Def.dampingRatio = 0.7f; bwj5_Def.enableMotor = false; bwj5_Def.frequencyHz = 10.0f; bwj5_Def.localAnchorA.set(new Vector2(0.0f * 0.25f, 0.0f * 0.25f)); bwj5_Def.localAnchorB.set(new Vector2(0.0f * 0.25f, 0.0f * 0.25f)); bwj5_Def.localAxisA.set(new Vector2(1.0f * 0.25f, 0.0f * 0.25f)); bwj5_Def.maxMotorTorque = 9999.0f; bwj5_Def.motorSpeed = -80.0f; bwj5_Def.collideConnected = false; bwj5_Def.initialize( Car5.getBody(), BW5.getBody(), BW5.getBody().getWorldCenter(), new Vector2(0f * 0.25f, 1f * 0.25f)); bwj5 = (WheelJoint) (this.world.createJoint(bwj5_Def)); addJoint("bwj5", bwj5); WheelJointDef bwj4_Def = new WheelJointDef(); bwj4_Def.dampingRatio = 0.7f; bwj4_Def.enableMotor = false; bwj4_Def.frequencyHz = 10.0f; bwj4_Def.localAnchorA.set(new Vector2(0.0f * 0.25f, 0.0f * 0.25f)); bwj4_Def.localAnchorB.set(new Vector2(0.0f * 0.25f, 0.0f * 0.25f)); bwj4_Def.localAxisA.set(new Vector2(1.0f * 0.25f, 0.0f * 0.25f)); bwj4_Def.maxMotorTorque = 9999.0f; bwj4_Def.motorSpeed = -80.0f; bwj4_Def.collideConnected = false; bwj4_Def.initialize( Car4.getBody(), BW4.getBody(), BW4.getBody().getWorldCenter(), new Vector2(0f * 0.25f, 1f * 0.25f)); bwj4 = (WheelJoint) (this.world.createJoint(bwj4_Def)); addJoint("bwj4", bwj4); WheelJointDef fwj1_Def = new WheelJointDef(); fwj1_Def.dampingRatio = 0.7f; fwj1_Def.enableMotor = false; fwj1_Def.frequencyHz = 10.0f; fwj1_Def.localAnchorA.set(new Vector2(0.0f * 0.25f, 0.0f * 0.25f)); fwj1_Def.localAnchorB.set(new Vector2(0.0f * 0.25f, 0.0f * 0.25f)); fwj1_Def.localAxisA.set(new Vector2(1.0f * 0.25f, 0.0f * 0.25f)); fwj1_Def.maxMotorTorque = 0.0f; fwj1_Def.motorSpeed = 0.0f; fwj1_Def.collideConnected = false; fwj1_Def.initialize( Car1.getBody(), FW1.getBody(), FW1.getBody().getWorldCenter(), new Vector2(0f * 0.25f, 1f * 0.25f)); fwj1 = (WheelJoint) (this.world.createJoint(fwj1_Def)); addJoint("fwj1", fwj1); WheelJointDef fwj2_Def = new WheelJointDef(); fwj2_Def.dampingRatio = 0.7f; fwj2_Def.enableMotor = false; fwj2_Def.frequencyHz = 10.0f; fwj2_Def.localAnchorA.set(new Vector2(0.0f * 0.25f, 0.0f * 0.25f)); fwj2_Def.localAnchorB.set(new Vector2(0.0f * 0.25f, 0.0f * 0.25f)); fwj2_Def.localAxisA.set(new Vector2(1.0f * 0.25f, 0.0f * 0.25f)); fwj2_Def.maxMotorTorque = 0.0f; fwj2_Def.motorSpeed = 0.0f; fwj2_Def.collideConnected = false; fwj2_Def.initialize( Car2.getBody(), FW2.getBody(), FW2.getBody().getWorldCenter(), new Vector2(0f * 0.25f, 1f * 0.25f)); fwj2 = (WheelJoint) (this.world.createJoint(fwj2_Def)); addJoint("fwj2", fwj2); WheelJointDef fwj4_Def = new WheelJointDef(); fwj4_Def.dampingRatio = 0.7f; fwj4_Def.enableMotor = false; fwj4_Def.frequencyHz = 10.0f; fwj4_Def.localAnchorA.set(new Vector2(0.0f * 0.25f, 0.0f * 0.25f)); fwj4_Def.localAnchorB.set(new Vector2(0.0f * 0.25f, 0.0f * 0.25f)); fwj4_Def.localAxisA.set(new Vector2(1.0f * 0.25f, 0.0f * 0.25f)); fwj4_Def.maxMotorTorque = 0.0f; fwj4_Def.motorSpeed = 0.0f; fwj4_Def.collideConnected = false; fwj4_Def.initialize( Car4.getBody(), FW4.getBody(), FW4.getBody().getWorldCenter(), new Vector2(0f * 0.25f, 1f * 0.25f)); fwj4 = (WheelJoint) (this.world.createJoint(fwj4_Def)); addJoint("fwj4", fwj4); WheelJointDef fwj5_Def = new WheelJointDef(); fwj5_Def.dampingRatio = 0.7f; fwj5_Def.enableMotor = false; fwj5_Def.frequencyHz = 10.0f; fwj5_Def.localAnchorA.set(new Vector2(0.0f * 0.25f, 0.0f * 0.25f)); fwj5_Def.localAnchorB.set(new Vector2(0.0f * 0.25f, 0.0f * 0.25f)); fwj5_Def.localAxisA.set(new Vector2(1.0f * 0.25f, 0.0f * 0.25f)); fwj5_Def.maxMotorTorque = 0.0f; fwj5_Def.motorSpeed = 0.0f; fwj5_Def.collideConnected = false; fwj5_Def.initialize( Car5.getBody(), FW5.getBody(), FW5.getBody().getWorldCenter(), new Vector2(0f * 0.25f, 1f * 0.25f)); fwj5 = (WheelJoint) (this.world.createJoint(fwj5_Def)); addJoint("fwj5", fwj5); String car = getValue("car").replace("c", ""); int cn = 3; if (!car.equals("")) { cn = toInt(car); } switch (cn) { case 1: Car = Car1; BW = BW1; FW = FW1; bwj = bwj1; break; case 2: Car = Car2; BW = BW2; FW = FW2; bwj = bwj2; break; case 4: Car = Car4; BW = BW4; FW = FW4; bwj = bwj4; break; case 5: Car = Car5; BW = BW5; FW = FW5; bwj = bwj5; break; } Car.getActor().setVisible(true); FW.getActor().setVisible(true); BW.getActor().setVisible(true); Car.getBody().setActive(true); FW.getBody().setActive(true); BW.getBody().setActive(true); String wheel = getValue("wheel"); if (!wheel.equals("")) { setImage(BW, wheel); setImage(FW, wheel); } setScript(new com.star4droid.game.SceneScript.mainScript().setStage(this)); } @Override public void onPause() {} @Override public void onResume() {} @Override public void onDraw() { setCameraXY(Car); } @Override public void onCollisionBegin(PlayerItem body1, PlayerItem body2) {} @Override public void onCollisionEnd(PlayerItem body1, PlayerItem body2) {} // scripts goes here ... }
0
0.918408
1
0.918408
game-dev
MEDIA
0.779372
game-dev
0.967023
1
0.967023
Lil-Isma/tttdamagelogs
2,160
lua/damagelogs/shared/sync.lua
-- I heard using an entity to sync variables with all players is good -- this is what sandbox does (edit_sky, edit_sun, ..) local ENT = { Type = "anim", base = "base_anim", SetupDataTables = function(self) self:NetworkVar("Int", 0, "PlayedRounds") self:NetworkVar("Bool", 0, "LastRoundMapExists") self:NetworkVar("Int", 1, "PendingReports") end, UpdateTransmitState = function() return TRANSMIT_ALWAYS end, Draw = function() end, Initialize = function(self) self:DrawShadow(false) end } scripted_ents.Register(ENT, "dmglog_sync_ent") -- Getting the entity serverside or clientside -- Then all we'll have to do is using Get* and Set* functions we create using NetworkVar() function Damagelog:GetSyncEnt() if SERVER then return self.sync_ent else return ents.FindByClass("dmglog_sync_ent")[1] end end -- TTT cleans up all entities -- fuck it local CleanUpMap = game.CleanUpMap function game.CleanUpMap(send_to_clients, filters) filters = filters or {} table.insert(filters, "dmglog_sync_ent") local res = CleanUpMap(send_to_clients, filters) return res end if SERVER then -- Creating the entity on InitPostEntity hook.Add("InitPostEntity", "InitPostEntity_Damagelog", function() Damagelog.sync_ent = ents.Create("dmglog_sync_ent") Damagelog.sync_ent:Spawn() Damagelog.sync_ent:Activate() Damagelog.sync_ent:SetLastRoundMapExists(Damagelog.last_round_map and true or false) if Damagelog.RDM_Manager_Enabled then for _, v in pairs(Damagelog.Reports.Current) do if v.status == RDM_MANAGER_WAITING and not v.adminReport then Damagelog.sync_ent:SetPendingReports(Damagelog.sync_ent:GetPendingReports() + 1) end end for _, v in pairs(Damagelog.Reports.Previous) do if v.status == RDM_MANAGER_WAITING and not v.adminReport then Damagelog.sync_ent:SetPendingReports(Damagelog.sync_ent:GetPendingReports() + 1) end end end end) end
0
0.951409
1
0.951409
game-dev
MEDIA
0.785873
game-dev
0.926424
1
0.926424
ratrecommends/dice-heroes
1,836
main/src/com/vlaaad/dice/game/actions/imp/RandomTeleportSelf.java
/* * Dice heroes is a turn based rpg-strategy game where characters are dice. * Copyright (C) 2016 Vladislav Protsenko * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.vlaaad.dice.game.actions.imp; import com.badlogic.gdx.utils.Array; import com.vlaaad.common.util.Grid2D; import com.vlaaad.common.util.futures.Future; import com.vlaaad.common.util.futures.IFuture; import com.vlaaad.dice.game.actions.results.IActionResult; import com.vlaaad.dice.game.config.abilities.Ability; import com.vlaaad.dice.game.objects.Creature; import com.vlaaad.dice.game.world.World; import com.vlaaad.dice.game.world.controllers.RandomController; /** * Created 18.03.14 by vlaaad */ public class RandomTeleportSelf extends TeleportSelf { public RandomTeleportSelf(Ability owner) { super(owner); } @Override public IFuture<? extends IActionResult> apply(final Creature creature, World world) { Array<Grid2D.Coordinate> coordinates = Teleport.gatherCoordinates(creature, radius); if (coordinates.size == 0) return Future.completed(IActionResult.NOTHING); return Future.completed(calcResult(creature, world.getController(RandomController.class).random(coordinates))); } }
0
0.514959
1
0.514959
game-dev
MEDIA
0.934178
game-dev
0.790594
1
0.790594
sweeperxz/FullyExternalCS2
3,427
Data/Entity/Entity.cs
using System.Collections.Concurrent; using CS2Cheat.Data.Game; using CS2Cheat.Utils; using SharpDX; namespace CS2Cheat.Data.Entity; public class Entity : EntityBase { private readonly ConcurrentDictionary<string, Vector3> _bonePositions; private bool _dormant = true; public Entity(int index) { Id = index; _bonePositions = new ConcurrentDictionary<string, Vector3>(Offsets.Bones.ToDictionary( bone => bone.Key, _ => Vector3.Zero )); } protected internal bool IsSpotted { get; private set; } protected internal string Name { get; private set; } = string.Empty; protected internal int IsInScope { get; private set; } protected internal int FlashAlpha { get; private set; } public IReadOnlyDictionary<string, Vector3> BonePos => _bonePositions; public int Id { get; } public override bool IsAlive() { return base.IsAlive() && !_dormant; } protected override IntPtr ReadControllerBase(GameProcess gameProcess) { var entryIndex = (Id & 0x7FFF) >> 9; if (gameProcess?.Process == null) return IntPtr.Zero; var listEntry = gameProcess.Process.Read<IntPtr>(EntityList + 8 * entryIndex + 16); return listEntry != IntPtr.Zero ? gameProcess.Process.Read<IntPtr>(listEntry + 120 * (Id & 0x1FF)) : IntPtr.Zero; } protected override IntPtr ReadAddressBase(GameProcess gameProcess) { if (gameProcess?.Process == null) return IntPtr.Zero; var playerPawn = gameProcess.Process.Read<int>(ControllerBase + Offsets.m_hPawn); var pawnIndex = (playerPawn & 0x7FFF) >> 9; var listEntry = gameProcess.Process.Read<IntPtr>(EntityList + 0x8 * pawnIndex + 16); return listEntry != IntPtr.Zero ? gameProcess.Process.Read<IntPtr>(listEntry + 120 * (playerPawn & 0x1FF)) : IntPtr.Zero; } public override bool Update(GameProcess gameProcess) { if (!base.Update(gameProcess)) return false; _dormant = gameProcess.Process != null && gameProcess.Process.Read<bool>(AddressBase + Offsets.m_bDormant); IsSpotted = gameProcess.Process?.Read<bool>(AddressBase + Offsets.m_entitySpottedState + 0x8) ?? false; IsInScope = gameProcess.Process?.Read<int>(AddressBase + Offsets.m_bIsScoped) ?? 0; FlashAlpha = gameProcess.Process?.Read<int>(AddressBase + Offsets.m_flFlashDuration) ?? 0; Name = gameProcess.Process != null ? gameProcess.Process.ReadString(ControllerBase + Offsets.m_iszPlayerName) : string.Empty; return !IsAlive() || UpdateBonePositions(gameProcess); } private bool UpdateBonePositions(GameProcess gameProcess) { try { if (gameProcess?.Process == null) return false; var gameSceneNode = gameProcess.Process.Read<IntPtr>(AddressBase + Offsets.m_pGameSceneNode); var boneArray = gameProcess.Process.Read<IntPtr>(gameSceneNode + Offsets.m_modelState + 128); foreach (var (boneName, boneIndex) in Offsets.Bones) { var bonePos = gameProcess.Process.Read<Vector3>(boneArray + boneIndex * 32); _bonePositions.AddOrUpdate(boneName, bonePos, (_, _) => bonePos); } return true; } catch { return false; } } }
0
0.919257
1
0.919257
game-dev
MEDIA
0.929963
game-dev
0.700936
1
0.700936
Telegram4J/Telegram4J
8,894
core/src/main/java/telegram4j/core/spec/markup/ReplyMarkupSpec.java
/* * Copyright 2023 Telegram4J * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package telegram4j.core.spec.markup; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.util.annotation.Nullable; import telegram4j.core.MTProtoTelegramClient; import telegram4j.mtproto.internal.Preconditions; import telegram4j.core.object.markup.ReplyMarkup; import telegram4j.core.util.ImmutableEnumSet; import telegram4j.tl.*; import telegram4j.tl.api.TlEncodingUtil; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.StreamSupport; public final class ReplyMarkupSpec { private final ReplyMarkup.Type type; private final ImmutableEnumSet<ReplyMarkup.Flag> flags; @Nullable private final List<List<KeyboardButtonSpec>> rows; @Nullable private final String placeholder; private ReplyMarkupSpec(ReplyMarkup.Type type, @Nullable List<List<KeyboardButtonSpec>> rows, ImmutableEnumSet<ReplyMarkup.Flag> flags, @Nullable String placeholder) { this.type = type; this.rows = rows; this.flags = flags; this.placeholder = placeholder; } public ReplyMarkup.Type type() { return type; } public Optional<List<List<KeyboardButtonSpec>>> rows() { return Optional.ofNullable(rows); } public ImmutableEnumSet<ReplyMarkup.Flag> flags() { return flags; } public Optional<String> placeholder() { return Optional.ofNullable(placeholder); } public ReplyMarkupSpec withRows(@Nullable Iterable<? extends Iterable<? extends KeyboardButtonSpec>> values) { if (rows == values) return this; var newRows = values == null ? null : StreamSupport.stream(values.spliterator(), false) .map(TlEncodingUtil::<KeyboardButtonSpec>copyList) .collect(Collectors.toUnmodifiableList()); if (rows == newRows) return this; return new ReplyMarkupSpec(type, newRows, flags, placeholder); } public ReplyMarkupSpec withPlaceholder(@Nullable String value) { if (Objects.equals(placeholder, value)) return this; return new ReplyMarkupSpec(type, rows, flags, value); } public ReplyMarkupSpec withPlaceholder(Optional<String> opt) { return withPlaceholder(opt.orElse(null)); } public ReplyMarkupSpec withFlags(ReplyMarkup.Flag... values) { Objects.requireNonNull(values); var flagsCopy = ImmutableEnumSet.of(values); if (flags.getValue() == flagsCopy.getValue()) return this; return new ReplyMarkupSpec(type, rows, flagsCopy, placeholder); } public ReplyMarkupSpec withFlags(Iterable<ReplyMarkup.Flag> values) { Objects.requireNonNull(values); if (flags == values) return this; var flagsCopy = ImmutableEnumSet.of(ReplyMarkup.Flag.class, values); if (flags.getValue() == flagsCopy.getValue()) return this; return new ReplyMarkupSpec(type, rows, flagsCopy, placeholder); } public Mono<telegram4j.tl.ReplyMarkup> asData(MTProtoTelegramClient client) { return Mono.defer(() -> switch (type()) { case KEYBOARD -> Flux.fromIterable(rows().orElseThrow()) .flatMap(list -> Flux.fromIterable(list) .flatMap(s -> s.asData(client)) .collect(Collectors.toUnmodifiableList()) .map(ImmutableKeyboardButtonRow::of)) .collect(Collectors.toUnmodifiableList()) .map(rows -> ReplyKeyboardMarkup.builder() .flags(flags.getValue()) .placeholder(placeholder) .rows(rows) .build()); case HIDE -> Mono.just(ImmutableReplyKeyboardHide.of(flags.getValue())); case FORCE_REPLY -> Mono.just(ReplyKeyboardForceReply.builder() .flags(flags.getValue()) .placeholder(placeholder) .build()); case INLINE -> Flux.fromIterable(rows().orElseThrow()) .flatMap(list -> Flux.fromIterable(list) .flatMap(s -> s.asData(client)) .collect(Collectors.toUnmodifiableList()) .map(ImmutableKeyboardButtonRow::of)) .collect(Collectors.toUnmodifiableList()) .map(ImmutableReplyInlineMarkup::of); }); } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof ReplyMarkupSpec that)) return false; return type.equals(that.type) && Objects.equals(rows, that.rows) && flags.equals(that.flags) && Objects.equals(placeholder, that.placeholder); } @Override public int hashCode() { int h = 5381; h += (h << 5) + type.hashCode(); h += (h << 5) + Objects.hashCode(rows); h += (h << 5) + flags.hashCode(); h += (h << 5) + Objects.hashCode(placeholder); return h; } @Override public String toString() { return "ReplyMarkupSpec{" + "type=" + type + ", flags=" + flags + ", rows=" + rows + ", placeholder='" + placeholder + '\'' + '}'; } public static ReplyMarkupSpec inlineKeyboard(Iterable<? extends Iterable<InlineButtonSpec>> rows) { var rowsCopy = StreamSupport.stream(rows.spliterator(), false) .map(TlEncodingUtil::<KeyboardButtonSpec>copyList) .collect(Collectors.toUnmodifiableList()); return new ReplyMarkupSpec(ReplyMarkup.Type.INLINE, rowsCopy, ImmutableEnumSet.of(ReplyMarkup.Flag.class, 0), null); } public static ReplyMarkupSpec forceReplyKeyboard(Iterable<ReplyMarkup.Flag> flags) { var flagsCopy = ImmutableEnumSet.of(ReplyMarkup.Flag.class, flags); Preconditions.requireArgument(!flagsCopy.contains(ReplyMarkup.Flag.RESIZE), "Reply keyboards can't have resize option"); return new ReplyMarkupSpec(ReplyMarkup.Type.FORCE_REPLY, null, flagsCopy, null); } public static ReplyMarkupSpec forceReplyKeyboard(ReplyMarkup.Flag... flags) { var flagsCopy = ImmutableEnumSet.of(flags); Preconditions.requireArgument(!flagsCopy.contains(ReplyMarkup.Flag.RESIZE), "Reply keyboards can't have resize option"); return new ReplyMarkupSpec(ReplyMarkup.Type.FORCE_REPLY, null, flagsCopy, null); } public static ReplyMarkupSpec hideKeyboard() { return hideKeyboard(false); } public static ReplyMarkupSpec hideKeyboard(boolean selective) { var flags = ImmutableEnumSet.of(ReplyMarkup.Flag.class, selective ? ReplyKeyboardMarkup.SELECTIVE_MASK : 0); return new ReplyMarkupSpec(ReplyMarkup.Type.HIDE, null, flags, null); } public static ReplyMarkupSpec keyboard(Iterable<? extends Iterable<ReplyButtonSpec>> rows) { return keyboard(null, rows, Set.of()); } public static ReplyMarkupSpec keyboard(@Nullable String placeholder, Iterable<? extends Iterable<ReplyButtonSpec>> rows, Iterable<ReplyMarkup.Flag> flags) { var flagsCopy = ImmutableEnumSet.of(ReplyMarkup.Flag.class, flags); var rowsCopy = StreamSupport.stream(rows.spliterator(), false) .map(TlEncodingUtil::<KeyboardButtonSpec>copyList) .collect(Collectors.toUnmodifiableList()); return new ReplyMarkupSpec(ReplyMarkup.Type.KEYBOARD, rowsCopy, flagsCopy, placeholder); } public static ReplyMarkupSpec keyboard(@Nullable String placeholder, Iterable<? extends Iterable<ReplyButtonSpec>> rows, ReplyMarkup.Flag... flags) { var flagsCopy = ImmutableEnumSet.of(flags); var rowsCopy = StreamSupport.stream(rows.spliterator(), false) .map(TlEncodingUtil::<KeyboardButtonSpec>copyList) .collect(Collectors.toUnmodifiableList()); return new ReplyMarkupSpec(ReplyMarkup.Type.KEYBOARD, rowsCopy, flagsCopy, placeholder); } }
0
0.891275
1
0.891275
game-dev
MEDIA
0.390095
game-dev
0.882827
1
0.882827
MrFast-js/Skyblock-Tweaks
3,666
src/main/java/mrfast/sbt/features/auctionHouse/AuctionNotifications.kt
package mrfast.sbt.features.auctionHouse import mrfast.sbt.SkyblockTweaks import mrfast.sbt.config.categories.AuctionHouseConfig import mrfast.sbt.config.categories.CustomizationConfig import mrfast.sbt.customevents.PacketEvent import mrfast.sbt.managers.TickManager import mrfast.sbt.utils.ChatUtils import mrfast.sbt.utils.Utils import mrfast.sbt.utils.Utils.abbreviateNumber import mrfast.sbt.utils.Utils.clean import net.minecraft.network.play.client.C01PacketChatMessage import net.minecraft.util.ChatComponentText import net.minecraftforge.client.event.ClientChatReceivedEvent import net.minecraftforge.fml.common.eventhandler.SubscribeEvent import net.minecraftforge.fml.common.gameevent.TickEvent import net.minecraftforge.fml.common.gameevent.TickEvent.ClientTickEvent @SkyblockTweaks.EventComponent object AuctionNotifications { private val ignoredAuctionIDs = mutableListOf<String>() private val outbidRegex = """§6\[Auction\] (.*) §eoutbid you by (.*) coins §efor (.*) §e§lCLICK""".toRegex() private var lastOpenedAuctionID: String? = null fun capturedAuctionID(): Boolean { return lastOpenedAuctionID != null && lastOpenedAuctionID!!.isNotEmpty() } fun ignoreCurrentAuction() { val currentAuctionID = lastOpenedAuctionID ?: return ignoredAuctionIDs.add(currentAuctionID) } @SubscribeEvent fun onTick(event: ClientTickEvent) { if(TickManager.tickCount % 20 != 0) return if(event.phase == TickEvent.Phase.START && Utils.getCurrentScreen() == null && lastOpenedAuctionID != null) { lastOpenedAuctionID = null } } @SubscribeEvent fun onChatSent(event: PacketEvent.Sending) { if (event.packet is C01PacketChatMessage) { val message = event.packet.message if (message.startsWith("/viewauction")) { val auctionID = message.split(" ")[1].replace("-","") lastOpenedAuctionID = auctionID } } } @SubscribeEvent fun onChat(event: ClientChatReceivedEvent) { if (event.type.toInt() == 2) return if(event.message.chatStyle != null && event.message.chatStyle.chatClickEvent != null && ignoredAuctionIDs.isNotEmpty()) { ignoredAuctionIDs.forEach { if (event.message.chatStyle.chatClickEvent.value.replace("-","").contains(it)) { event.isCanceled = true } } if (event.isCanceled) return } val matchResult = outbidRegex.find(event.message.formattedText) if (matchResult != null) { val (user, amount, itemName) = matchResult.destructured val amountNumber = amount.clean().replace(",","").toLong() if (AuctionHouseConfig.customOutbidNotifications) { event.isCanceled = true val customNotification = AuctionHouseConfig.customOutbidNotificationsText .replace("{bidder}", user) .replace("{amount}", if(AuctionHouseConfig.customOutbidNotificationsAbbreviation) (amountNumber.abbreviateNumber()) else amount) .replace("{item}", itemName) .replace("&", "§") val chatComponentText = ChatComponentText(customNotification) chatComponentText.chatStyle.chatClickEvent = event.message.chatStyle.chatClickEvent if (AuctionHouseConfig.customOutbidNotificationsPlaySound) { Utils.playSound("note.harp", 0.3) } ChatUtils.sendClientMessage(chatComponentText, false) } } } }
0
0.875582
1
0.875582
game-dev
MEDIA
0.839899
game-dev
0.945351
1
0.945351
lua9520/source-engine-2018-hl2_src
34,836
game/shared/ragdoll_shared.cpp
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // //=============================================================================// #include "cbase.h" #include "ragdoll_shared.h" #include "bone_setup.h" #include "vphysics/constraints.h" #include "vphysics/collision_set.h" #include "vcollide_parse.h" #include "vphysics_interface.h" #include "tier0/vprof.h" #include "engine/ivdebugoverlay.h" #include "solidsetdefaults.h" //CLIENT #ifdef CLIENT_DLL #include "c_fire_smoke.h" #include "c_entitydissolve.h" #include "engine/IEngineSound.h" #endif //SERVER #if !defined( CLIENT_DLL ) #include "util.h" #include "EntityFlame.h" #include "EntityDissolve.h" #endif // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" CRagdollLowViolenceManager g_RagdollLVManager; void CRagdollLowViolenceManager::SetLowViolence( const char *pMapName ) { // set the value using the engine's low violence settings m_bLowViolence = UTIL_IsLowViolence(); #if !defined( CLIENT_DLL ) // the server doesn't worry about low violence during multiplayer games if ( g_pGameRules && g_pGameRules->IsMultiplayer() ) { m_bLowViolence = false; } #endif // Turn the low violence ragdoll stuff off if we're in the HL2 Citadel maps because // the player has the super gravity gun and fading ragdolls will break things. if( hl2_episodic.GetBool() ) { if ( Q_stricmp( pMapName, "ep1_citadel_02" ) == 0 || Q_stricmp( pMapName, "ep1_citadel_02b" ) == 0 || Q_stricmp( pMapName, "ep1_citadel_03" ) == 0 ) { m_bLowViolence = false; } } else { if ( Q_stricmp( pMapName, "d3_citadel_03" ) == 0 || Q_stricmp( pMapName, "d3_citadel_04" ) == 0 || Q_stricmp( pMapName, "d3_citadel_05" ) == 0 || Q_stricmp( pMapName, "d3_breen_01" ) == 0 ) { m_bLowViolence = false; } } } class CRagdollCollisionRules : public IVPhysicsKeyHandler { public: CRagdollCollisionRules( IPhysicsCollisionSet *pSet ) { m_pSet = pSet; m_bSelfCollisions = true; } virtual void ParseKeyValue( void *pData, const char *pKey, const char *pValue ) { if ( !strcmpi( pKey, "selfcollisions" ) ) { // keys disabled by default Assert( atoi(pValue) == 0 ); m_bSelfCollisions = false; } else if ( !strcmpi( pKey, "collisionpair" ) ) { if ( m_bSelfCollisions ) { char szToken[256]; const char *pStr = nexttoken(szToken, pValue, ','); int index0 = atoi(szToken); nexttoken( szToken, pStr, ',' ); int index1 = atoi(szToken); m_pSet->EnableCollisions( index0, index1 ); } else { Assert(0); } } } virtual void SetDefaults( void *pData ) {} private: IPhysicsCollisionSet *m_pSet; bool m_bSelfCollisions; }; class CRagdollAnimatedFriction : public IVPhysicsKeyHandler { public: CRagdollAnimatedFriction( ragdoll_t *ragdoll ) { m_ragdoll = ragdoll; } virtual void ParseKeyValue( void *pData, const char *pKey, const char *pValue ) { if ( !strcmpi( pKey, "animfrictionmin" ) ) { m_ragdoll->animfriction.iMinAnimatedFriction = atoi( pValue ); } else if ( !strcmpi( pKey, "animfrictionmax" ) ) { m_ragdoll->animfriction.iMaxAnimatedFriction = atoi( pValue ); } else if ( !strcmpi( pKey, "animfrictiontimein" ) ) { m_ragdoll->animfriction.flFrictionTimeIn = atof( pValue ); } else if ( !strcmpi( pKey, "animfrictiontimeout" ) ) { m_ragdoll->animfriction.flFrictionTimeOut = atof( pValue ); } else if ( !strcmpi( pKey, "animfrictiontimehold" ) ) { m_ragdoll->animfriction.flFrictionTimeHold = atof( pValue ); } } virtual void SetDefaults( void *pData ) {} private: ragdoll_t *m_ragdoll; }; void RagdollSetupAnimatedFriction( IPhysicsEnvironment *pPhysEnv, ragdoll_t *ragdoll, int iModelIndex ) { vcollide_t* pCollide = modelinfo->GetVCollide( iModelIndex ); if ( pCollide ) { IVPhysicsKeyParser *pParse = physcollision->VPhysicsKeyParserCreate( pCollide->pKeyValues ); while ( !pParse->Finished() ) { const char *pBlock = pParse->GetCurrentBlockName(); if ( !strcmpi( pBlock, "animatedfriction") ) { CRagdollAnimatedFriction friction( ragdoll ); pParse->ParseCustom( (void*)&friction, &friction ); } else { pParse->SkipBlock(); } } physcollision->VPhysicsKeyParserDestroy( pParse ); } } static void RagdollAddSolid( IPhysicsEnvironment *pPhysEnv, ragdoll_t &ragdoll, const ragdollparams_t &params, solid_t &solid ) { if ( solid.index >= 0 && solid.index < params.pCollide->solidCount) { Assert( ragdoll.listCount == solid.index ); int boneIndex = Studio_BoneIndexByName( params.pStudioHdr, solid.name ); ragdoll.boneIndex[ragdoll.listCount] = boneIndex; if ( boneIndex >= 0 ) { if ( params.fixedConstraints ) { solid.params.mass = 1000.f; } solid.params.rotInertiaLimit = 0.1; solid.params.pGameData = params.pGameData; int surfaceData = physprops->GetSurfaceIndex( solid.surfaceprop ); if ( surfaceData < 0 ) surfaceData = physprops->GetSurfaceIndex( "default" ); solid.params.pName = params.pStudioHdr->pszName(); ragdoll.list[ragdoll.listCount].pObject = pPhysEnv->CreatePolyObject( params.pCollide->solids[solid.index], surfaceData, vec3_origin, vec3_angle, &solid.params ); ragdoll.list[ragdoll.listCount].pObject->SetPositionMatrix( params.pCurrentBones[boneIndex], true ); ragdoll.list[ragdoll.listCount].parentIndex = -1; ragdoll.list[ragdoll.listCount].pObject->SetGameIndex( ragdoll.listCount ); ragdoll.listCount++; } else { Msg( "CRagdollProp::CreateObjects: Couldn't Lookup Bone %s\n", solid.name ); } } } static void RagdollAddConstraint( IPhysicsEnvironment *pPhysEnv, ragdoll_t &ragdoll, const ragdollparams_t &params, constraint_ragdollparams_t &constraint ) { if( constraint.childIndex == constraint.parentIndex ) { DevMsg( 1, "Bogus constraint on ragdoll %s\n", params.pStudioHdr->pszName() ); constraint.childIndex = -1; constraint.parentIndex = -1; } if ( constraint.childIndex >= 0 && constraint.parentIndex >= 0 ) { Assert(constraint.childIndex<ragdoll.listCount); ragdollelement_t &childElement = ragdoll.list[constraint.childIndex]; // save parent index childElement.parentIndex = constraint.parentIndex; if ( params.jointFrictionScale > 0 ) { for ( int k = 0; k < 3; k++ ) { constraint.axes[k].torque *= params.jointFrictionScale; } } // this parent/child pair is not usually a parent/child pair in the skeleton. There // are often bones in between that are collapsed for simulation. So we need to compute // the transform. Studio_CalcBoneToBoneTransform( params.pStudioHdr, ragdoll.boneIndex[constraint.childIndex], ragdoll.boneIndex[constraint.parentIndex], constraint.constraintToAttached ); MatrixGetColumn( constraint.constraintToAttached, 3, childElement.originParentSpace ); // UNDONE: We could transform the constraint limit axes relative to the bone space // using this data. Do we need that feature? SetIdentityMatrix( constraint.constraintToReference ); if ( params.fixedConstraints ) { // Makes the ragdoll a statue... constraint_fixedparams_t fixed; fixed.Defaults(); fixed.InitWithCurrentObjectState( childElement.pObject, ragdoll.list[constraint.parentIndex].pObject ); fixed.constraint.Defaults(); childElement.pConstraint = pPhysEnv->CreateFixedConstraint( childElement.pObject, ragdoll.list[constraint.parentIndex].pObject, ragdoll.pGroup, fixed ); } else { childElement.pConstraint = pPhysEnv->CreateRagdollConstraint( childElement.pObject, ragdoll.list[constraint.parentIndex].pObject, ragdoll.pGroup, constraint ); } } } static void RagdollCreateObjects( IPhysicsEnvironment *pPhysEnv, ragdoll_t &ragdoll, const ragdollparams_t &params ) { ragdoll.listCount = 0; ragdoll.pGroup = NULL; ragdoll.allowStretch = params.allowStretch; memset( ragdoll.list, 0, sizeof(ragdoll.list) ); memset( &ragdoll.animfriction, 0, sizeof(ragdoll.animfriction) ); if ( !params.pCollide || params.pCollide->solidCount > RAGDOLL_MAX_ELEMENTS ) return; constraint_groupparams_t group; group.Defaults(); ragdoll.pGroup = pPhysEnv->CreateConstraintGroup( group ); IVPhysicsKeyParser *pParse = physcollision->VPhysicsKeyParserCreate( params.pCollide->pKeyValues ); while ( !pParse->Finished() ) { const char *pBlock = pParse->GetCurrentBlockName(); if ( !strcmpi( pBlock, "solid" ) ) { solid_t solid; pParse->ParseSolid( &solid, &g_SolidSetup ); RagdollAddSolid( pPhysEnv, ragdoll, params, solid ); } else if ( !strcmpi( pBlock, "ragdollconstraint" ) ) { constraint_ragdollparams_t constraint; pParse->ParseRagdollConstraint( &constraint, NULL ); RagdollAddConstraint( pPhysEnv, ragdoll, params, constraint ); } else if ( !strcmpi( pBlock, "collisionrules" ) ) { IPhysicsCollisionSet *pSet = physics->FindOrCreateCollisionSet( params.modelIndex, ragdoll.listCount ); CRagdollCollisionRules rules(pSet); pParse->ParseCustom( (void *)&rules, &rules ); } else if ( !strcmpi( pBlock, "animatedfriction") ) { CRagdollAnimatedFriction friction( &ragdoll ); pParse->ParseCustom( (void*)&friction, &friction ); } else { pParse->SkipBlock(); } } physcollision->VPhysicsKeyParserDestroy( pParse ); } void RagdollSetupCollisions( ragdoll_t &ragdoll, vcollide_t *pCollide, int modelIndex ) { Assert(pCollide); if (!pCollide) return; IPhysicsCollisionSet *pSet = physics->FindCollisionSet( modelIndex ); if ( !pSet ) { pSet = physics->FindOrCreateCollisionSet( modelIndex, ragdoll.listCount ); if ( !pSet ) return; bool bFoundRules = false; IVPhysicsKeyParser *pParse = physcollision->VPhysicsKeyParserCreate( pCollide->pKeyValues ); while ( !pParse->Finished() ) { const char *pBlock = pParse->GetCurrentBlockName(); if ( !strcmpi( pBlock, "collisionrules" ) ) { IPhysicsCollisionSet *pSetRules = physics->FindOrCreateCollisionSet( modelIndex, ragdoll.listCount ); CRagdollCollisionRules rules( pSetRules ); pParse->ParseCustom( (void *)&rules, &rules ); bFoundRules = true; } else { pParse->SkipBlock(); } } physcollision->VPhysicsKeyParserDestroy( pParse ); if ( !bFoundRules ) { // these are the default rules - each piece collides with everything // except immediate parent/constrained object. int i; for ( i = 0; i < ragdoll.listCount; i++ ) { for ( int j = i+1; j < ragdoll.listCount; j++ ) { pSet->EnableCollisions( i, j ); } } for ( i = 0; i < ragdoll.listCount; i++ ) { int parent = ragdoll.list[i].parentIndex; if ( parent >= 0 ) { Assert( ragdoll.list[i].pObject ); Assert( ragdoll.list[i].pConstraint ); pSet->DisableCollisions( i, parent ); } } } } } void RagdollActivate( ragdoll_t &ragdoll, vcollide_t *pCollide, int modelIndex, bool bForceWake ) { RagdollSetupCollisions( ragdoll, pCollide, modelIndex ); for ( int i = 0; i < ragdoll.listCount; i++ ) { ragdoll.list[i].pObject->SetGameIndex( i ); PhysSetGameFlags( ragdoll.list[i].pObject, FVPHYSICS_MULTIOBJECT_ENTITY ); // now that the relationships are set, activate the collision system ragdoll.list[i].pObject->EnableCollisions( true ); if ( bForceWake == true ) { ragdoll.list[i].pObject->Wake(); } } if ( ragdoll.pGroup ) { // NOTE: This also wakes the objects ragdoll.pGroup->Activate(); // so if we didn't want that, we'll need to put them back to sleep here if ( !bForceWake ) { for ( int i = 0; i < ragdoll.listCount; i++ ) { ragdoll.list[i].pObject->Sleep(); } } } } bool RagdollCreate( ragdoll_t &ragdoll, const ragdollparams_t &params, IPhysicsEnvironment *pPhysEnv ) { RagdollCreateObjects( pPhysEnv, ragdoll, params ); if ( !ragdoll.listCount ) return false; int forceBone = params.forceBoneIndex; int i; float totalMass = 0; for ( i = 0; i < ragdoll.listCount; i++ ) { totalMass += ragdoll.list[i].pObject->GetMass(); } totalMass = MAX(totalMass,1); // apply force to the model Vector nudgeForce = params.forceVector; Vector forcePosition = params.forcePosition; // UNDONE: Test scaling the force by total mass on all bones Assert( forceBone < ragdoll.listCount ); if ( forceBone >= 0 && forceBone < ragdoll.listCount ) { ragdoll.list[forceBone].pObject->ApplyForceCenter( nudgeForce ); //nudgeForce *= 0.5; ragdoll.list[forceBone].pObject->GetPosition( &forcePosition, NULL ); } for ( i = 0; i < ragdoll.listCount; i++ ) { PhysSetGameFlags( ragdoll.list[i].pObject, FVPHYSICS_PART_OF_RAGDOLL ); } if ( forcePosition != vec3_origin ) { for ( i = 0; i < ragdoll.listCount; i++ ) { if ( forceBone != i ) { float scale = ragdoll.list[i].pObject->GetMass() / totalMass; ragdoll.list[i].pObject->ApplyForceOffset( scale * nudgeForce, forcePosition ); } } } return true; } void RagdollApplyAnimationAsVelocity( ragdoll_t &ragdoll, const matrix3x4_t *pPrevBones, const matrix3x4_t *pCurrentBones, float dt ) { for ( int i = 0; i < ragdoll.listCount; i++ ) { Vector velocity; AngularImpulse angVel; int boneIndex = ragdoll.boneIndex[i]; CalcBoneDerivatives( velocity, angVel, pPrevBones[boneIndex], pCurrentBones[boneIndex], dt ); AngularImpulse localAngVelocity; // Angular velocity is always applied in local space in vphysics ragdoll.list[i].pObject->WorldToLocalVector( &localAngVelocity, angVel ); ragdoll.list[i].pObject->AddVelocity( &velocity, &localAngVelocity ); } } void RagdollApplyAnimationAsVelocity( ragdoll_t &ragdoll, const matrix3x4_t *pBoneToWorld ) { for ( int i = 0; i < ragdoll.listCount; i++ ) { matrix3x4_t inverse; MatrixInvert( pBoneToWorld[i], inverse ); Quaternion q; Vector pos; MatrixAngles( inverse, q, pos ); Vector velocity; AngularImpulse angVel; float flSpin; Vector localVelocity; AngularImpulse localAngVelocity; QuaternionAxisAngle( q, localAngVelocity, flSpin ); localAngVelocity *= flSpin; localVelocity = pos; // move those bone-local coords back to world space using the ragdoll transform ragdoll.list[i].pObject->LocalToWorldVector( &velocity, localVelocity ); ragdoll.list[i].pObject->AddVelocity( &velocity, &localAngVelocity ); } } void RagdollDestroy( ragdoll_t &ragdoll ) { if ( !ragdoll.listCount ) return; int i; for ( i = 0; i < ragdoll.listCount; i++ ) { physenv->DestroyConstraint( ragdoll.list[i].pConstraint ); ragdoll.list[i].pConstraint = NULL; } for ( i = 0; i < ragdoll.listCount; i++ ) { // during level transitions these can get temporarily loaded without physics objects // purely for the purpose of testing for PVS of transition. If they fail they get // deleted before the physics objects are loaded. The list count will be nonzero // since that is saved separately. if ( ragdoll.list[i].pObject ) { physenv->DestroyObject( ragdoll.list[i].pObject ); } ragdoll.list[i].pObject = NULL; } physenv->DestroyConstraintGroup( ragdoll.pGroup ); ragdoll.pGroup = NULL; ragdoll.listCount = 0; } // Parse the ragdoll and obtain the mapping from each physics element index to a bone index // returns num phys elements int RagdollExtractBoneIndices( int *boneIndexOut, CStudioHdr *pStudioHdr, vcollide_t *pCollide ) { int elementCount = 0; IVPhysicsKeyParser *pParse = physcollision->VPhysicsKeyParserCreate( pCollide->pKeyValues ); while ( !pParse->Finished() ) { const char *pBlock = pParse->GetCurrentBlockName(); if ( !strcmpi( pBlock, "solid" ) ) { solid_t solid; pParse->ParseSolid( &solid, NULL ); if ( elementCount < RAGDOLL_MAX_ELEMENTS ) { boneIndexOut[elementCount] = Studio_BoneIndexByName( pStudioHdr, solid.name ); elementCount++; } } else { pParse->SkipBlock(); } } physcollision->VPhysicsKeyParserDestroy( pParse ); return elementCount; } bool RagdollGetBoneMatrix( const ragdoll_t &ragdoll, CBoneAccessor &pBoneToWorld, int objectIndex ) { int boneIndex = ragdoll.boneIndex[objectIndex]; if ( boneIndex < 0 ) return false; const ragdollelement_t &element = ragdoll.list[objectIndex]; // during restore if a model has changed since the file was saved, this could be NULL if ( !element.pObject ) return false; element.pObject->GetPositionMatrix( &pBoneToWorld.GetBoneForWrite( boneIndex ) ); if ( element.parentIndex >= 0 && !ragdoll.allowStretch ) { // overwrite the position from physics to force rigid attachment // UNDONE: If we support other types of constraints (or multiple constraints per object) // make sure these don't fight ! int parentBoneIndex = ragdoll.boneIndex[element.parentIndex]; Vector out; VectorTransform( element.originParentSpace, pBoneToWorld.GetBone( parentBoneIndex ), out ); MatrixSetColumn( out, 3, pBoneToWorld.GetBoneForWrite( boneIndex ) ); } return true; } void RagdollComputeExactBbox( const ragdoll_t &ragdoll, const Vector &origin, Vector &outMins, Vector &outMaxs ) { outMins = origin; outMaxs = origin; for ( int i = 0; i < ragdoll.listCount; i++ ) { Vector mins, maxs; Vector objectOrg; QAngle objectAng; IPhysicsObject *pObject = ragdoll.list[i].pObject; pObject->GetPosition( &objectOrg, &objectAng ); physcollision->CollideGetAABB( &mins, &maxs, pObject->GetCollide(), objectOrg, objectAng ); for ( int j = 0; j < 3; j++ ) { if ( mins[j] < outMins[j] ) { outMins[j] = mins[j]; } if ( maxs[j] > outMaxs[j] ) { outMaxs[j] = maxs[j]; } } } } bool RagdollIsAsleep( const ragdoll_t &ragdoll ) { for ( int i = 0; i < ragdoll.listCount; i++ ) { if ( ragdoll.list[i].pObject && !ragdoll.list[i].pObject->IsAsleep() ) return false; } return true; } void RagdollSolveSeparation( ragdoll_t &ragdoll, CBaseEntity *pEntity ) { byte needsFix[256]; int fixCount = 0; Assert(ragdoll.listCount<=ARRAYSIZE(needsFix)); for ( int i = 0; i < ragdoll.listCount; i++ ) { needsFix[i] = 0; const ragdollelement_t &element = ragdoll.list[i]; if ( element.pConstraint && element.parentIndex >= 0 ) { Vector start, target; element.pObject->GetPosition( &start, NULL ); ragdoll.list[element.parentIndex].pObject->LocalToWorld( &target, element.originParentSpace ); if ( needsFix[element.parentIndex] ) { needsFix[i] = 1; ++fixCount; continue; } Vector dir = target-start; if ( dir.LengthSqr() > 1.0f ) { // this fixes a bug in ep2 with antlion grubs, but causes problems in TF2 - revisit, but disable for TF now #if !defined(TF_CLIENT_DLL) // heuristic: guess that anything separated and small mass ratio is in some state that's // keeping the solver from fixing it float mass = element.pObject->GetMass(); float massParent = ragdoll.list[element.parentIndex].pObject->GetMass(); if ( mass*2.0f < massParent ) { // if this is <0.5 mass of parent and still separated it's attached to something heavy or // in a bad state needsFix[i] = 1; ++fixCount; continue; } #endif if ( PhysHasContactWithOtherInDirection(element.pObject, dir) ) { Ray_t ray; trace_t tr; ray.Init( target, start ); UTIL_TraceRay( ray, MASK_SOLID, pEntity, COLLISION_GROUP_NONE, &tr ); if ( tr.DidHit() ) { needsFix[i] = 1; ++fixCount; } } } } } if ( fixCount ) { for ( int i = 0; i < ragdoll.listCount; i++ ) { if ( !needsFix[i] ) continue; const ragdollelement_t &element = ragdoll.list[i]; Vector target, velocity; ragdoll.list[element.parentIndex].pObject->LocalToWorld( &target, element.originParentSpace ); ragdoll.list[element.parentIndex].pObject->GetVelocityAtPoint( target, &velocity ); matrix3x4_t xform; element.pObject->GetPositionMatrix( &xform ); MatrixSetColumn( target, 3, xform ); element.pObject->SetPositionMatrix( xform, true ); element.pObject->SetVelocity( &velocity, &vec3_origin ); } DevMsg(2, "TICK:%5d:Ragdoll separation count: %d\n", gpGlobals->tickcount, fixCount ); } else { ragdoll.pGroup->ClearErrorState(); } } //----------------------------------------------------------------------------- // LRU //----------------------------------------------------------------------------- #ifdef _XBOX // xbox defaults to 4 ragdolls max ConVar g_ragdoll_maxcount("g_ragdoll_maxcount", "4", FCVAR_REPLICATED ); #else ConVar g_ragdoll_maxcount("g_ragdoll_maxcount", "8", FCVAR_REPLICATED ); #endif ConVar g_debug_ragdoll_removal("g_debug_ragdoll_removal", "0", FCVAR_REPLICATED |FCVAR_CHEAT ); CRagdollLRURetirement s_RagdollLRU( "CRagdollLRURetirement" ); void CRagdollLRURetirement::LevelInitPreEntity( void ) { m_iMaxRagdolls = -1; m_LRUImportantRagdolls.RemoveAll(); m_LRU.RemoveAll(); } bool ShouldRemoveThisRagdoll( CBaseAnimating *pRagdoll ) { if ( g_RagdollLVManager.IsLowViolence() ) { return true; } #ifdef CLIENT_DLL /* we no longer ignore enemies just because they are on fire -- a ragdoll in front of me is always a higher priority for retention than a flaming zombie behind me. At the time I put this in, the ragdolls do clean up their own effects if culled via SUB_Remove(). If you're encountering trouble with ragdolls leaving effects behind, try renabling the code below. ///////////////////// //Just ignore it until we're done burning/dissolving. if ( pRagdoll->GetEffectEntity() ) return false; */ // Bail if we have a null ragdoll pointer. if ( !pRagdoll->m_pRagdoll ) return true; Vector vMins, vMaxs; Vector origin = pRagdoll->m_pRagdoll->GetRagdollOrigin(); pRagdoll->m_pRagdoll->GetRagdollBounds( vMins, vMaxs ); if( engine->IsBoxInViewCluster( vMins + origin, vMaxs + origin) == false ) { if ( g_debug_ragdoll_removal.GetBool() ) { if ( debugoverlay ) { debugoverlay->AddBoxOverlay( origin, vMins, vMaxs, QAngle( 0, 0, 0 ), 0, 255, 0, 16, 5 ); debugoverlay->AddLineOverlay( origin, origin + Vector( 0, 0, 64 ), 0, 255, 0, true, 5 ); } } return true; } else if( engine->CullBox( vMins + origin, vMaxs + origin ) == true ) { if ( g_debug_ragdoll_removal.GetBool() ) { if ( debugoverlay ) { debugoverlay->AddBoxOverlay( origin, vMins, vMaxs, QAngle( 0, 0, 0 ), 0, 0, 255, 16, 5 ); debugoverlay->AddLineOverlay( origin, origin + Vector( 0, 0, 64 ), 0, 0, 255, true, 5 ); } } return true; } #else CBasePlayer *pPlayer = UTIL_GetLocalPlayer(); if( !UTIL_FindClientInPVS( pRagdoll->edict() ) ) { if ( g_debug_ragdoll_removal.GetBool() ) NDebugOverlay::Line( pRagdoll->GetAbsOrigin(), pRagdoll->GetAbsOrigin() + Vector( 0, 0, 64 ), 0, 255, 0, true, 5 ); return true; } else if( !pPlayer->FInViewCone( pRagdoll ) ) { if ( g_debug_ragdoll_removal.GetBool() ) NDebugOverlay::Line( pRagdoll->GetAbsOrigin(), pRagdoll->GetAbsOrigin() + Vector( 0, 0, 64 ), 0, 0, 255, true, 5 ); return true; } #endif return false; } //----------------------------------------------------------------------------- // Cull stale ragdolls. There is an ifdef here: one version for episodic, // one for everything else. //----------------------------------------------------------------------------- #if HL2_EPISODIC void CRagdollLRURetirement::Update( float frametime ) // EPISODIC VERSION { VPROF( "CRagdollLRURetirement::Update" ); // Compress out dead items int i, next; int iMaxRagdollCount = m_iMaxRagdolls; if ( iMaxRagdollCount == -1 ) { iMaxRagdollCount = g_ragdoll_maxcount.GetInt(); } // fade them all for the low violence version if ( g_RagdollLVManager.IsLowViolence() ) { iMaxRagdollCount = 0; } m_iRagdollCount = 0; m_iSimulatedRagdollCount = 0; // First, find ragdolls that are good candidates for deletion because they are not // visible at all, or are in a culled visibility box for ( i = m_LRU.Head(); i < m_LRU.InvalidIndex(); i = next ) { next = m_LRU.Next(i); CBaseAnimating *pRagdoll = m_LRU[i].Get(); if ( pRagdoll ) { m_iRagdollCount++; IPhysicsObject *pObject = pRagdoll->VPhysicsGetObject(); if (pObject && !pObject->IsAsleep()) { m_iSimulatedRagdollCount++; } if ( m_LRU.Count() > iMaxRagdollCount ) { //Found one, we're done. if ( ShouldRemoveThisRagdoll( m_LRU[i] ) == true ) { #ifdef CLIENT_DLL m_LRU[ i ]->SUB_Remove(); #else m_LRU[ i ]->SUB_StartFadeOut( 0 ); #endif m_LRU.Remove(i); return; } } } else { m_LRU.Remove(i); } } ////////////////////////////// /// EPISODIC ALGORITHM /// ////////////////////////////// // If we get here, it means we couldn't find a suitable ragdoll to remove, // so just remove the furthest one. int furthestOne = m_LRU.Head(); float furthestDistSq = 0; #ifdef CLIENT_DLL C_BasePlayer *pPlayer = C_BasePlayer::GetLocalPlayer(); #else CBasePlayer *pPlayer = UTIL_GetLocalPlayer(); #endif if (pPlayer && m_LRU.Count() > iMaxRagdollCount) // find the furthest one algorithm { Vector PlayerOrigin = pPlayer->GetAbsOrigin(); // const CBasePlayer *pPlayer = UTIL_GetLocalPlayer(); for ( i = m_LRU.Head(); i < m_LRU.InvalidIndex(); i = next ) { CBaseAnimating *pRagdoll = m_LRU[i].Get(); next = m_LRU.Next(i); IPhysicsObject *pObject = pRagdoll->VPhysicsGetObject(); if ( pRagdoll && (pRagdoll->GetEffectEntity() || ( pObject && !pObject->IsAsleep()) ) ) continue; if ( pRagdoll ) { // float distToPlayer = (pPlayer->GetAbsOrigin() - pRagdoll->GetAbsOrigin()).LengthSqr(); float distToPlayer = (PlayerOrigin - pRagdoll->GetAbsOrigin()).LengthSqr(); if (distToPlayer > furthestDistSq) { furthestOne = i; furthestDistSq = distToPlayer; } } else // delete bad rags first. { furthestOne = i; break; } } #ifdef CLIENT_DLL m_LRU[ furthestOne ]->SUB_Remove(); #else m_LRU[ furthestOne ]->SUB_StartFadeOut( 0 ); #endif } else // fall back on old-style pick the oldest one algorithm { for ( i = m_LRU.Head(); i < m_LRU.InvalidIndex(); i = next ) { if ( m_LRU.Count() <= iMaxRagdollCount ) break; next = m_LRU.Next(i); CBaseAnimating *pRagdoll = m_LRU[i].Get(); //Just ignore it until we're done burning/dissolving. IPhysicsObject *pObject = pRagdoll->VPhysicsGetObject(); if ( pRagdoll && (pRagdoll->GetEffectEntity() || ( pObject && !pObject->IsAsleep()) ) ) continue; #ifdef CLIENT_DLL m_LRU[ i ]->SUB_Remove(); #else m_LRU[ i ]->SUB_StartFadeOut( 0 ); #endif m_LRU.Remove(i); } } } #else void CRagdollLRURetirement::Update( float frametime ) // Non-episodic version { VPROF( "CRagdollLRURetirement::Update" ); // Compress out dead items int i, next; int iMaxRagdollCount = m_iMaxRagdolls; if ( iMaxRagdollCount == -1 ) { iMaxRagdollCount = g_ragdoll_maxcount.GetInt(); } // fade them all for the low violence version if ( g_RagdollLVManager.IsLowViolence() ) { iMaxRagdollCount = 0; } m_iRagdollCount = 0; m_iSimulatedRagdollCount = 0; for ( i = m_LRU.Head(); i < m_LRU.InvalidIndex(); i = next ) { next = m_LRU.Next(i); CBaseAnimating *pRagdoll = m_LRU[i].Get(); if ( pRagdoll ) { m_iRagdollCount++; IPhysicsObject *pObject = pRagdoll->VPhysicsGetObject(); if (pObject && !pObject->IsAsleep()) { m_iSimulatedRagdollCount++; } if ( m_LRU.Count() > iMaxRagdollCount ) { //Found one, we're done. if ( ShouldRemoveThisRagdoll( m_LRU[i] ) == true ) { #ifdef CLIENT_DLL m_LRU[ i ]->SUB_Remove(); #else m_LRU[ i ]->SUB_StartFadeOut( 0 ); #endif m_LRU.Remove(i); return; } } } else { m_LRU.Remove(i); } } ////////////////////////////// /// ORIGINAL ALGORITHM /// ////////////////////////////// // not episodic -- this is the original mechanism for ( i = m_LRU.Head(); i < m_LRU.InvalidIndex(); i = next ) { if ( m_LRU.Count() <= iMaxRagdollCount ) break; next = m_LRU.Next(i); CBaseAnimating *pRagdoll = m_LRU[i].Get(); //Just ignore it until we're done burning/dissolving. if ( pRagdoll && pRagdoll->GetEffectEntity() ) continue; #ifdef CLIENT_DLL m_LRU[ i ]->SUB_Remove(); #else m_LRU[ i ]->SUB_StartFadeOut( 0 ); #endif m_LRU.Remove(i); } } #endif // HL2_EPISODIC //This is pretty hacky, it's only called on the server so it just calls the update method. void CRagdollLRURetirement::FrameUpdatePostEntityThink( void ) { Update( 0 ); } ConVar g_ragdoll_important_maxcount( "g_ragdoll_important_maxcount", "2", FCVAR_REPLICATED ); //----------------------------------------------------------------------------- // Move it to the top of the LRU //----------------------------------------------------------------------------- void CRagdollLRURetirement::MoveToTopOfLRU( CBaseAnimating *pRagdoll, bool bImportant ) { if ( bImportant ) { m_LRUImportantRagdolls.AddToTail( pRagdoll ); if ( m_LRUImportantRagdolls.Count() > g_ragdoll_important_maxcount.GetInt() ) { int iIndex = m_LRUImportantRagdolls.Head(); CBaseAnimating *pRagdollLRU = m_LRUImportantRagdolls[iIndex].Get(); if ( pRagdollLRU ) { #ifdef CLIENT_DLL pRagdollLRU->SUB_Remove(); #else pRagdollLRU->SUB_StartFadeOut( 0 ); #endif m_LRUImportantRagdolls.Remove(iIndex); } } return; } for ( int i = m_LRU.Head(); i < m_LRU.InvalidIndex(); i = m_LRU.Next(i) ) { if ( m_LRU[i].Get() == pRagdoll ) { m_LRU.Remove(i); break; } } m_LRU.AddToTail( pRagdoll ); } //EFFECT/ENTITY TRANSFERS //CLIENT #ifdef CLIENT_DLL #define DEFAULT_FADE_START 2.0f #define DEFAULT_MODEL_FADE_START 1.9f #define DEFAULT_MODEL_FADE_LENGTH 0.1f #define DEFAULT_FADEIN_LENGTH 1.0f C_EntityDissolve *DissolveEffect( C_BaseEntity *pTarget, float flTime ) { C_EntityDissolve *pDissolve = new C_EntityDissolve; if ( pDissolve->InitializeAsClientEntity( "sprites/blueglow1.vmt", RENDER_GROUP_TRANSLUCENT_ENTITY ) == false ) { pDissolve->Release(); return NULL; } if ( pDissolve != NULL ) { pTarget->AddFlag( FL_DISSOLVING ); pDissolve->SetParent( pTarget ); pDissolve->OnDataChanged( DATA_UPDATE_CREATED ); pDissolve->SetAbsOrigin( pTarget->GetAbsOrigin() ); pDissolve->m_flStartTime = flTime; pDissolve->m_flFadeOutStart = DEFAULT_FADE_START; pDissolve->m_flFadeOutModelStart = DEFAULT_MODEL_FADE_START; pDissolve->m_flFadeOutModelLength = DEFAULT_MODEL_FADE_LENGTH; pDissolve->m_flFadeInLength = DEFAULT_FADEIN_LENGTH; pDissolve->m_nDissolveType = 0; pDissolve->m_flNextSparkTime = 0.0f; pDissolve->m_flFadeOutLength = 0.0f; pDissolve->m_flFadeInStart = 0.0f; // Let this entity know it needs to delete itself when it's done pDissolve->SetServerLinkState( false ); pTarget->SetEffectEntity( pDissolve ); } return pDissolve; } C_EntityFlame *FireEffect( C_BaseAnimating *pTarget, C_BaseEntity *pServerFire, float *flScaleEnd, float *flTimeStart, float *flTimeEnd ) { C_EntityFlame *pFire = new C_EntityFlame; if ( pFire->InitializeAsClientEntity( NULL, RENDER_GROUP_TRANSLUCENT_ENTITY ) == false ) { pFire->Release(); return NULL; } if ( pFire != NULL ) { pFire->RemoveFromLeafSystem(); pTarget->AddFlag( FL_ONFIRE ); pFire->SetParent( pTarget ); pFire->m_hEntAttached = (C_BaseEntity *) pTarget; pFire->OnDataChanged( DATA_UPDATE_CREATED ); pFire->SetAbsOrigin( pTarget->GetAbsOrigin() ); #ifdef HL2_EPISODIC if ( pServerFire ) { if ( pServerFire->IsEffectActive(EF_DIMLIGHT) ) { pFire->AddEffects( EF_DIMLIGHT ); } if ( pServerFire->IsEffectActive(EF_BRIGHTLIGHT) ) { pFire->AddEffects( EF_BRIGHTLIGHT ); } } #endif //Play a sound CPASAttenuationFilter filter( pTarget ); pTarget->EmitSound( filter, pTarget->GetSoundSourceIndex(), "General.BurningFlesh" ); pFire->SetNextClientThink( gpGlobals->curtime + 7.0f ); } return pFire; } void C_BaseAnimating::IgniteRagdoll( C_BaseAnimating *pSource ) { C_BaseEntity *pChild = pSource->GetEffectEntity(); if ( pChild ) { C_EntityFlame *pFireChild = dynamic_cast<C_EntityFlame *>( pChild ); C_ClientRagdoll *pRagdoll = dynamic_cast< C_ClientRagdoll * > ( this ); if ( pFireChild ) { pRagdoll->SetEffectEntity ( FireEffect( pRagdoll, pFireChild, NULL, NULL, NULL ) ); } } } void C_BaseAnimating::TransferDissolveFrom( C_BaseAnimating *pSource ) { C_BaseEntity *pChild = pSource->GetEffectEntity(); if ( pChild ) { C_EntityDissolve *pDissolveChild = dynamic_cast<C_EntityDissolve *>( pChild ); if ( pDissolveChild ) { C_ClientRagdoll *pRagdoll = dynamic_cast< C_ClientRagdoll * > ( this ); if ( pRagdoll ) { pRagdoll->m_flEffectTime = pDissolveChild->m_flStartTime; C_EntityDissolve *pDissolve = DissolveEffect( pRagdoll, pRagdoll->m_flEffectTime ); if ( pDissolve ) { pDissolve->SetRenderMode( pDissolveChild->GetRenderMode() ); pDissolve->m_nRenderFX = pDissolveChild->m_nRenderFX; pDissolve->SetRenderColor( 255, 255, 255, 255 ); pDissolveChild->SetRenderColorA( 0 ); pDissolve->m_vDissolverOrigin = pDissolveChild->m_vDissolverOrigin; pDissolve->m_nDissolveType = pDissolveChild->m_nDissolveType; if ( pDissolve->m_nDissolveType == ENTITY_DISSOLVE_CORE ) { pDissolve->m_nMagnitude = pDissolveChild->m_nMagnitude; pDissolve->m_flFadeOutStart = CORE_DISSOLVE_FADE_START; pDissolve->m_flFadeOutModelStart = CORE_DISSOLVE_MODEL_FADE_START; pDissolve->m_flFadeOutModelLength = CORE_DISSOLVE_MODEL_FADE_LENGTH; pDissolve->m_flFadeInLength = CORE_DISSOLVE_FADEIN_LENGTH; } } } } } } #endif //SERVER #if !defined( CLIENT_DLL ) //----------------------------------------------------------------------------- // Transfer dissolve //----------------------------------------------------------------------------- void CBaseAnimating::TransferDissolveFrom( CBaseAnimating *pAnim ) { if ( !pAnim || !pAnim->IsDissolving() ) return; CEntityDissolve *pDissolve = CEntityDissolve::Create( this, pAnim ); if (pDissolve) { AddFlag( FL_DISSOLVING ); m_flDissolveStartTime = pAnim->m_flDissolveStartTime; CEntityDissolve *pDissolveFrom = dynamic_cast < CEntityDissolve * > (pAnim->GetEffectEntity()); if ( pDissolveFrom ) { pDissolve->SetDissolverOrigin( pDissolveFrom->GetDissolverOrigin() ); pDissolve->SetDissolveType( pDissolveFrom->GetDissolveType() ); if ( pDissolveFrom->GetDissolveType() == ENTITY_DISSOLVE_CORE ) { pDissolve->SetMagnitude( pDissolveFrom->GetMagnitude() ); pDissolve->m_flFadeOutStart = CORE_DISSOLVE_FADE_START; pDissolve->m_flFadeOutModelStart = CORE_DISSOLVE_MODEL_FADE_START; pDissolve->m_flFadeOutModelLength = CORE_DISSOLVE_MODEL_FADE_LENGTH; pDissolve->m_flFadeInLength = CORE_DISSOLVE_FADEIN_LENGTH; } } } } #endif
0
0.911086
1
0.911086
game-dev
MEDIA
0.938057
game-dev
0.757639
1
0.757639
nfrechette/acl-ue4-plugin
1,887
ACLPlugin/Source/ACLPluginEditor/Private/ACLPluginEditorModule.cpp
// Copyright 2020 Nicholas Frechette. All Rights Reserved. #include "CoreMinimal.h" #include "IACLPluginEditorModule.h" #include "Modules/ModuleManager.h" #include "AssetToolsModule.h" #include "AssetTypeActions_AnimationCompressionLibraryDatabase.h" class FACLPluginEditor final : public IACLPluginEditor { private: /** IModuleInterface implementation */ virtual void StartupModule() override; virtual void ShutdownModule() override; void OnPostEngineInit(); void RegisterAssetTypeAction(IAssetTools& AssetTools, TSharedRef<IAssetTypeActions> Action); TArray<TSharedPtr<IAssetTypeActions>> RegisteredAssetTypeActions; }; IMPLEMENT_MODULE(FACLPluginEditor, ACLPluginEditor) ////////////////////////////////////////////////////////////////////////// void FACLPluginEditor::StartupModule() { FCoreDelegates::OnPostEngineInit.AddRaw(this, &FACLPluginEditor::OnPostEngineInit); } void FACLPluginEditor::ShutdownModule() { FCoreDelegates::OnPostEngineInit.RemoveAll(this); // Unregister our asset types if (FModuleManager::Get().IsModuleLoaded("AssetTools")) { IAssetTools& AssetTools = FModuleManager::GetModuleChecked<FAssetToolsModule>("AssetTools").Get(); for (int32 Index = 0; Index < RegisteredAssetTypeActions.Num(); ++Index) { AssetTools.UnregisterAssetTypeActions(RegisteredAssetTypeActions[Index].ToSharedRef()); } } RegisteredAssetTypeActions.Empty(); } void FACLPluginEditor::OnPostEngineInit() { // Register our asset types IAssetTools& AssetTools = FModuleManager::LoadModuleChecked<FAssetToolsModule>("AssetTools").Get(); RegisterAssetTypeAction(AssetTools, MakeShareable(new FAssetTypeActions_AnimationCompressionLibraryDatabase)); } void FACLPluginEditor::RegisterAssetTypeAction(IAssetTools& AssetTools, TSharedRef<IAssetTypeActions> Action) { AssetTools.RegisterAssetTypeActions(Action); RegisteredAssetTypeActions.Add(Action); }
0
0.91418
1
0.91418
game-dev
MEDIA
0.959528
game-dev
0.58396
1
0.58396
IcyRelic/SpookSuite
18,223
SpookSuite/Settings.cs
using Newtonsoft.Json.Linq; using Newtonsoft.Json; using SpookSuite.Cheats; using SpookSuite.Util; using System; using System.Collections.Generic; using System.IO; using System.Reflection; using UnityEngine; using SpookSuite.Cheats.Core; namespace SpookSuite { internal class Settings { /* * * Menu Settings * */ public static bool b_isMenuOpen = false; public static int i_menuFontSize = 14; public static int i_menuWidth = 810; public static int i_menuHeight = 410; public static int i_sliderWidth = 100; public static int i_textboxWidth = 85; public static float f_menuAlpha = 1f; /* * * Color Settings * */ public static RGBAColor c_primary = new RGBAColor(165, 55, 253, 1f); public static RGBAColor c_menuText = new RGBAColor(255, 255, 255, 1f); public static RGBAColor c_espPlayers = new RGBAColor(0, 255, 0, 1f); public static RGBAColor c_espItems = new RGBAColor(255, 255, 255, 1f); public static RGBAColor c_espMonsters = new RGBAColor(255, 0, 0, 1f); public static RGBAColor c_espDivingBells = new RGBAColor(0, 0, 255, 1f); //public static RGBAColor c_chams = new RGBAColor(238, 111, 255, 0.1f); public static RGBAColor c_chamItems = new RGBAColor(238, 111, 255, 0.1f); public static RGBAColor c_chamMonsters = new RGBAColor(238, 111, 255, 0.1f); public static RGBAColor c_chamPlayers = new RGBAColor(238, 111, 255, 0.1f); public static RGBAColor c_chamDivingBell = new RGBAColor(238, 111, 255, 0.1f); /* * * Reaction Settings * */ public static RPCReactions.reactionType reaction_makesound = RPCReactions.reactionType.none; public static RPCReactions.reactionType reaction_dronespawn = RPCReactions.reactionType.none; public static RPCReactions.reactionType reaction_speedmanipulation = RPCReactions.reactionType.none; public static RPCReactions.reactionType reaction_kick = RPCReactions.reactionType.none; public static RPCReactions.reactionType reaction_shadowrealm = RPCReactions.reactionType.none; public static RPCReactions.reactionType reaction_crash = RPCReactions.reactionType.none; public static RPCReactions.reactionType reaction_blackscreen = RPCReactions.reactionType.none; internal class Changelog { public static List<string> changes; public static void ReadChanges() { changes = new List<string>(); using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("SpookSuite.Resources.Changelog.txt")) using (StreamReader reader = new StreamReader(stream)) { while (!reader.EndOfStream) { changes.Add(reader.ReadLine()); } } } } internal class Config { private static string config = "spooksuite.config.json"; private static string defaultConf = "spooksuite.default.config.json"; public static void CreateConfigIfNotExists() { if (HasConfig()) return; SaveConfig(); } public static void SaveDefaultConfig() { SaveConfig(defaultConf); } public static bool HasConfig() { return config != null && File.Exists(config); } public static void SaveConfig() { SaveConfig(config); } public static void SaveConfig(string conf) { Dictionary<string, string> keybinds = new Dictionary<string, string>(); Dictionary<string, string> toggles = new Dictionary<string, string>(); Dictionary<string, string> cheatValues = new Dictionary<string, string>(); Cheat.instances.FindAll(c => !c.Hidden).ForEach(c => { if(c.HasKeybind) keybinds.Add(c.GetType().Name, c.keybind.ToString()); if(c is ToggleCheat) toggles.Add(c.GetType().Name, ((ToggleCheat)c).Enabled.ToString()); if (c.GetType().GetInterface(typeof(IVariableCheat<>).FullName) != null) { FieldInfo valueField = c.GetType().GetField("Value", BindingFlags.Static | BindingFlags.Public); cheatValues.Add(c.GetType().Name, valueField.GetValue(c).ToString()); } }); JObject json = new JObject(); JObject settings = new JObject(); JObject colors = new JObject(); JObject cheatSettings = new JObject(); JObject reactions = new JObject(); colors["MenuText"] = JsonConvert.SerializeObject(c_menuText); colors["ESPPlayers"] = JsonConvert.SerializeObject(c_espPlayers); colors["ESPItems"] = JsonConvert.SerializeObject(c_espItems); colors["ESPMonsters"] = JsonConvert.SerializeObject(c_espMonsters); colors["ESPDivingBells"] = JsonConvert.SerializeObject(c_espDivingBells); colors["ChamPlayers"] = JsonConvert.SerializeObject(c_chamPlayers); colors["ChamItems"] = JsonConvert.SerializeObject(c_chamItems); colors["ChamMonsters"] = JsonConvert.SerializeObject(c_chamMonsters); colors["ChamDivingBell"] = JsonConvert.SerializeObject(c_chamDivingBell); reactions["ReactionMakeSound"] = JsonConvert.SerializeObject(reaction_makesound); reactions["ReactionDroneSpawn"] = JsonConvert.SerializeObject(reaction_dronespawn); reactions["ReactionSpeedManipulation"] = JsonConvert.SerializeObject(reaction_speedmanipulation); reactions["ReactionKick"] = JsonConvert.SerializeObject(reaction_kick); reactions["ReactionShadowRealm"] = JsonConvert.SerializeObject(reaction_shadowrealm); reactions["ReactionCrash"] = JsonConvert.SerializeObject(reaction_crash); reactions["ReactionBlackScreen"] = JsonConvert.SerializeObject(reaction_blackscreen); settings["MenuFontSize"] = i_menuFontSize.ToString(); settings["MenuWidth"] = i_menuWidth.ToString(); settings["MenuHeight"] = i_menuHeight.ToString(); settings["SliderWidth"] = i_sliderWidth.ToString(); settings["TextboxWidth"] = i_textboxWidth.ToString(); settings["MenuAlpha"] = f_menuAlpha.ToString(); cheatSettings["ESPPlayers"] = ESP.displayPlayers.ToString(); cheatSettings["ESPEnemies"] = ESP.displayEnemies.ToString(); cheatSettings["ESPItems"] = ESP.displayItems.ToString(); cheatSettings["ESPDivingBell"] = ESP.displayDivingBell.ToString(); cheatSettings["ESPLasers"] = ESP.displayLasers.ToString(); cheatSettings["ChamsPlayers"] = ChamESP.displayPlayers.ToString(); cheatSettings["ChamsEnemies"] = ChamESP.displayEnemies.ToString(); cheatSettings["ChamsItems"] = ChamESP.displayItems.ToString(); cheatSettings["ChamsDivingBell"] = ChamESP.displayDivingBell.ToString(); cheatSettings["ChamsLasers"] = ChamESP.displayLasers.ToString(); json["KeyBinds"] = JObject.FromObject(keybinds); json["Toggles"] = JObject.FromObject(toggles); json["Values"] = JObject.FromObject(cheatValues); json["CheatSettings"] = cheatSettings; json["Colors"] = colors; json["MenuSettings"] = settings; json["Reactions"] = reactions; File.WriteAllText(conf, json.ToString()); } public static void LoadConfig() { CreateConfigIfNotExists(); string jsonStr = File.ReadAllText(config); JObject json = JObject.Parse(jsonStr); Debug.Log("Loading Keybinds..."); if (json.TryGetValue("KeyBinds", out JToken keybindsToken)) { Cheat.instances.ForEach(c => c.keybind = c.defaultKeybind); foreach (var item in keybindsToken.ToObject<Dictionary<string, string>>()) { string s_cheat = item.Key; string s_bind = item.Value; KeyCode bind = Enum.Parse<KeyCode>(s_bind); Cheat.instances.Find(c => c.GetType().Name == s_cheat).keybind = bind; } } Debug.Log("Loading Toggles..."); if (json.TryGetValue("Toggles", out JToken togglesToken)) { foreach (var item in togglesToken.ToObject<Dictionary<string, string>>()) { string s_cheat = item.Key; string s_bind = item.Value; bool toggle = bool.TryParse(s_bind, out bool result) ? result : false; if (toggle) { ToggleCheat c = Cheat.instances.Find(c => c.GetType().Name == s_cheat && c is ToggleCheat) as ToggleCheat; if (!c.Enabled) c.Toggle(); } } } Debug.Log("Loading Values..."); if (json.TryGetValue("Values", out JToken valuesToken)) { foreach (var item in valuesToken.ToObject<Dictionary<string, string>>()) { string s_cheat = item.Key; string s_value = item.Value; Cheat c = Cheat.instances.Find(c => c.GetType().Name == s_cheat); if (c.GetType().GetInterface(typeof(IVariableCheat<>).FullName) != null) { FieldInfo valueField = c.GetType().GetField("Value", BindingFlags.Static | BindingFlags.Public); valueField.SetValue(c, Convert.ChangeType(s_value, valueField.FieldType)); } } } Debug.Log("Loading Cheat Settings..."); if(json.TryGetValue("CheatSettings", out JToken cSettingsToken)) { JObject cheatSettings = cSettingsToken.ToObject<JObject>(); if(cheatSettings.TryGetValue("ESPPlayers", out JToken espPlayersToken)) ESP.displayPlayers = bool.Parse(espPlayersToken.ToString()); if (cheatSettings.TryGetValue("ESPEnemies", out JToken espEnemiesToken)) ESP.displayEnemies = bool.Parse(espEnemiesToken.ToString()); if (cheatSettings.TryGetValue("ESPItems", out JToken espItemsToken)) ESP.displayItems = bool.Parse(espItemsToken.ToString()); if (cheatSettings.TryGetValue("ESPDivingBell", out JToken espDivingBellToken)) ESP.displayDivingBell = bool.Parse(espDivingBellToken.ToString()); if (cheatSettings.TryGetValue("ESPLasers", out JToken espLasersToken)) ESP.displayLasers = bool.Parse(espLasersToken.ToString()); if (cheatSettings.TryGetValue("ChamsPlayers", out JToken chamsPlayersToken)) ChamESP.displayPlayers = bool.Parse(chamsPlayersToken.ToString()); if (cheatSettings.TryGetValue("ChamsEnemies", out JToken chamsEnemiesToken)) ChamESP.displayEnemies = bool.Parse(chamsEnemiesToken.ToString()); if (cheatSettings.TryGetValue("ChamsItems", out JToken chamsItemsToken)) ChamESP.displayItems = bool.Parse(chamsItemsToken.ToString()); if (cheatSettings.TryGetValue("ChamsDivingBell", out JToken chamsDivingBellToken)) ChamESP.displayDivingBell = bool.Parse(chamsDivingBellToken.ToString()); if (cheatSettings.TryGetValue("ChamsLasers", out JToken chamsLasersToken)) ChamESP.displayLasers = bool.Parse(chamsLasersToken.ToString()); } Debug.Log("Loading Colors..."); if (json.TryGetValue("Colors", out JToken colorsToken)) { JObject colors = colorsToken.ToObject<JObject>(); if (colors.TryGetValue("MenuText", out JToken menuTextToken)) c_menuText = JsonConvert.DeserializeObject<RGBAColor>(menuTextToken.ToString()); if (colors.TryGetValue("ESPPlayers", out JToken espPlayersToken)) c_espPlayers = JsonConvert.DeserializeObject<RGBAColor>(espPlayersToken.ToString()); if (colors.TryGetValue("ESPItems", out JToken espItemsToken)) c_espItems = JsonConvert.DeserializeObject<RGBAColor>(espItemsToken.ToString()); if (colors.TryGetValue("ESPMonsters", out JToken espMonstersToken)) c_espMonsters = JsonConvert.DeserializeObject<RGBAColor>(espMonstersToken.ToString()); if (colors.TryGetValue("ESPDivingBells", out JToken espDivingBellsToken)) c_espDivingBells = JsonConvert.DeserializeObject<RGBAColor>(espDivingBellsToken.ToString()); if (colors.TryGetValue("ChamPlayers", out JToken chamPlayersToken)) c_chamPlayers = JsonConvert.DeserializeObject<RGBAColor>(chamPlayersToken.ToString()); if (colors.TryGetValue("ChamItems", out JToken chamItemsToken)) c_chamItems = JsonConvert.DeserializeObject<RGBAColor>(espDivingBellsToken.ToString()); if (colors.TryGetValue("ChamMonsters", out JToken chamMonstersToken)) c_chamMonsters = JsonConvert.DeserializeObject<RGBAColor>(espDivingBellsToken.ToString()); if (colors.TryGetValue("ChamDivingBell", out JToken chamDivingBellToken)) c_chamDivingBell = JsonConvert.DeserializeObject<RGBAColor>(espDivingBellsToken.ToString()); } Debug.Log("Loading Menu Settings..."); if (json.TryGetValue("MenuSettings", out JToken settingsToken)) { JObject settings = settingsToken.ToObject<JObject>(); if (settings.TryGetValue("MenuFontSize", out JToken menuFontSizeToken)) i_menuFontSize = int.Parse(menuFontSizeToken.ToString()); if (settings.TryGetValue("MenuWidth", out JToken menuWidthToken)) i_menuWidth = int.Parse(menuWidthToken.ToString()); if (settings.TryGetValue("MenuHeight", out JToken menuHeightToken)) i_menuHeight = int.Parse(menuHeightToken.ToString()); if (settings.TryGetValue("SliderWidth", out JToken sliderWidthToken)) i_sliderWidth = int.Parse(sliderWidthToken.ToString()); if (settings.TryGetValue("TextboxWidth", out JToken textboxWidthToken)) i_textboxWidth = int.Parse(textboxWidthToken.ToString()); if (settings.TryGetValue("MenuAlpha", out JToken menuAlphaToken)) f_menuAlpha = float.Parse(menuAlphaToken.ToString()); } Debug.Log("Loading Reaction Settings..."); if (json.TryGetValue("Reactions", out JToken reactionsToken)) { JObject reactions = reactionsToken.ToObject<JObject>(); if (reactions.TryGetValue("ReactionMakeSound", out JToken reactionMakeSoundToken)) reaction_makesound = JsonConvert.DeserializeObject<RPCReactions.reactionType>(reactionMakeSoundToken.ToString()); if (reactions.TryGetValue("ReactionDroneSpawn", out JToken reactionDroneSpawnToken)) reaction_dronespawn = JsonConvert.DeserializeObject<RPCReactions.reactionType>(reactionDroneSpawnToken.ToString()); if (reactions.TryGetValue("ReactionSpeedManipulation", out JToken reactionSpeedManipulationToken)) reaction_speedmanipulation = JsonConvert.DeserializeObject<RPCReactions.reactionType>(reactionSpeedManipulationToken.ToString()); if (reactions.TryGetValue("ReactionKick", out JToken reactionKickToken)) reaction_kick = JsonConvert.DeserializeObject<RPCReactions.reactionType>(reactionKickToken.ToString()); if (reactions.TryGetValue("ReactionShadowRealm", out JToken reactionShadowRealmToken)) reaction_shadowrealm = JsonConvert.DeserializeObject<RPCReactions.reactionType>(reactionShadowRealmToken.ToString()); if (reactions.TryGetValue("ReactionCrash", out JToken reactionCrashToken)) reaction_crash = JsonConvert.DeserializeObject<RPCReactions.reactionType>(reactionCrashToken.ToString()); if (reactions.TryGetValue("ReactionBlackScreen", out JToken reactionBlackScreen)) reaction_blackscreen = JsonConvert.DeserializeObject<RPCReactions.reactionType>(reactionBlackScreen.ToString()); } } public static void RegenerateConfig() { if (HasConfig()) File.Delete(config); File.Copy(defaultConf, config); Cheat.instances.ForEach(c => c.keybind = c.defaultKeybind); LoadConfig(); } } } }
0
0.846664
1
0.846664
game-dev
MEDIA
0.772206
game-dev
0.745542
1
0.745542
MohistMC/Youer
2,140
patches/net/minecraft/world/entity/projectile/AbstractHurtingProjectile.java.patch
--- a/net/minecraft/world/entity/projectile/AbstractHurtingProjectile.java +++ b/net/minecraft/world/entity/projectile/AbstractHurtingProjectile.java @@ -17,11 +_,14 @@ import net.minecraft.world.level.Level; import net.minecraft.world.phys.HitResult; import net.minecraft.world.phys.Vec3; +import org.bukkit.craftbukkit.event.CraftEventFactory; public abstract class AbstractHurtingProjectile extends Projectile { public static final double INITAL_ACCELERATION_POWER = 0.1; public static final double DEFLECTION_SCALE = 0.5; public double accelerationPower = 0.1; + public float bukkitYield = 1; // CraftBukkit + public boolean isIncendiary = true; // CraftBukkit protected AbstractHurtingProjectile(EntityType<? extends AbstractHurtingProjectile> p_36833_, Level p_36834_) { super(p_36833_, p_36834_); @@ -78,8 +_,14 @@ } HitResult hitresult = ProjectileUtil.getHitResultOnMoveVector(this, this::canHitEntity, this.getClipType()); - if (hitresult.getType() != HitResult.Type.MISS) { - this.hitTargetOrDeflectSelf(hitresult); + if (hitresult.getType() != HitResult.Type.MISS && !net.neoforged.neoforge.event.EventHooks.onProjectileImpact(this, hitresult)) { + this.preHitTargetOrDeflectSelf(hitresult); // CraftBukkit - projectile hit event + + // CraftBukkit start - Fire ProjectileHitEvent + if (this.isRemoved()) { + CraftEventFactory.callProjectileHitEvent(this, hitresult); + } + // CraftBukkit end } this.checkInsideBlocks(); @@ -108,7 +_,7 @@ this.setPos(d0, d1, d2); } else { - this.discard(); + this.discard(org.bukkit.event.entity.EntityRemoveEvent.Cause.DESPAWN); // CraftBukkit - add Bukkit remove cause } } @@ -118,7 +_,7 @@ } @Override - protected boolean canHitEntity(Entity p_36842_) { + public boolean canHitEntity(Entity p_36842_) { return super.canHitEntity(p_36842_) && !p_36842_.noPhysics; }
0
0.542478
1
0.542478
game-dev
MEDIA
0.988647
game-dev
0.832366
1
0.832366
RavinMaddHatter/Structura
4,539
animation_class.py
import json import os class animations: def __init__(self, path_to_default="Vanilla_Resource_Pack"): self.default_size = {"format_version": "1.8.0", "animations": { "animation.armor_stand.ghost_blocks.scale": { "loop": True, "bones": { "ghost_blocks": {"scale": 16.0}}}}} pathtofile = "{}/animations/armor_stand.animation.json".format( path_to_default) with open(pathtofile) as f: self.sizing = json.load(f) self.poses = {} self.poses[0] = "animation.armor_stand.default_pose" self.poses[1] = "animation.armor_stand.no_pose" self.poses[2] = "animation.armor_stand.solemn_pose" self.poses[3] = "animation.armor_stand.athena_pose" self.poses[4] = "animation.armor_stand.brandish_pose" self.poses[5] = "animation.armor_stand.honor_pose" self.poses[6] = "animation.armor_stand.entertain_pose" self.poses[7] = "animation.armor_stand.salute_pose" self.poses[8] = "animation.armor_stand.riposte_pose" self.poses[9] = "animation.armor_stand.zombie_pose" self.poses[10] = "animation.armor_stand.cancan_a_pose" self.poses[11] = "animation.armor_stand.cancan_b_pose" self.poses[12] = "animation.armor_stand.hero_pose" def insert_layer(self, y): name = "layer_{}".format(y) self.sizing["animations"][self.poses[0]]["bones"][name] = {"scale": 16} for i in range(12): if y % (12) != i: self.sizing["animations"][self.poses[i+1]]["bones"][name] = {"scale": 1} else: self.sizing["animations"][self.poses[i+1]]["bones"][name] = {"scale": 16} def export(self, pack_name): path_to_ani = "{}/animations/armor_stand.animation.json".format( pack_name) try: os.makedirs(os.path.dirname(path_to_ani), exist_ok=True) except: pass with open(path_to_ani, "w+") as json_file: json.dump(self.sizing, json_file, indent=2) path_to_rc = "{}/animations/armor_stand.ghost_blocks.scale.animation.json".format( pack_name) try: os.makedirs(os.path.dirname(path_to_rc), exist_ok=True) except: pass with open(path_to_rc, "w+") as json_file: json.dump(self.default_size, json_file, indent=2) def export_big(self,pack_name,offset): print(offset) self.default_size["animations"]["animation.armor_stand.ghost_blocks.scale"]["bones"]["ghost_blocks"]["rotation"]=[0,"-query.body_y_rotation", 0] self.default_size["animations"]["animation.armor_stand.ghost_blocks.scale"]["bones"]["ghost_blocks"]["position"]=[ f"(-(query.position(0)-{int(offset[0])})*math.cos(query.body_y_rotation)-(query.position(2)-{int(offset[2])})*math.sin(query.body_y_rotation))*16", f"({int(offset[1])}-query.position(1))*16", f"((query.position(2)-{int(offset[2])})*math.cos(query.body_y_rotation)-(query.position(0)-{int(offset[0])})*math.sin(query.body_y_rotation))*16"] ## for i in range(12): ## name = "layer_{}".format(i) ## self.sizing["animations"][self.poses[i+1]]["bones"][name]={"position":[f"{offset[0]}-query.position(0)", ## f"{offset[1]}-query.position(1)", ## f"{offset[2]}-query.position(2)"]} ## self.sizing["animations"][self.poses[i+1]]["bones"][name]["rotation"]=["0", f"-query.body_y_rotation", "0"] ## self.sizing["animations"][self.poses[i+1]]["bones"][name]["scale"] = 16.0 path_to_ani = f"{pack_name}/animations/armor_stand.animation.json" try: os.makedirs(os.path.dirname(path_to_ani), exist_ok=True) except: pass with open(path_to_ani, "w+") as json_file: json.dump(self.sizing, json_file, indent=2) path_to_rc = f"{pack_name}/animations/armor_stand.ghost_blocks.scale.animation.json" try: os.makedirs(os.path.dirname(path_to_rc), exist_ok=True) except: pass with open(path_to_rc, "w+") as json_file: json.dump(self.default_size, json_file, indent=2)
0
0.698035
1
0.698035
game-dev
MEDIA
0.860635
game-dev
0.946375
1
0.946375
OvermindDL1/bucklescript-tea
1,061
src-ocaml/tea_program.ml
type 'msg processMsg = | PushMsg of 'msg | Kill let spawn initState update shutdown = let state = ref (Some initState) in let onMessage procMsg = match !state with | None -> () | Some model -> ( match procMsg with | PushMsg msg -> let () = state := (update model msg) in () | Kill -> let () = shutdown model in let () = state := None in () ) in onMessage (* let testing0 = let s = spawn 42 (fun model -> let () = Js.log model in function | `Inc -> Some (model + 1) | `Dec -> Some (model - 1) ) (fun _ -> ()) in let () = s (PushMsg `Dec) in let () = s (PushMsg `Dec) in let () = s Kill in let () = s (PushMsg `Dec) in () *) module type Process = sig (* This module should be `import`ed into a module that will become a persistent process. That process should have a handleMsg callback to handle its own message types. It should call itself *) type msg val handleMsg : msg -> unit end let testing1 = 42
0
0.80639
1
0.80639
game-dev
MEDIA
0.422008
game-dev
0.879886
1
0.879886
Trantor2098/hot_node
1,751
utils/reporter.py
from typing import TYPE_CHECKING if TYPE_CHECKING: from bpy.types import Operator class Reporter: active_ops: 'Operator' = None is_active_ops_warning_thrown: bool = False is_active_ops_error_thrown: bool = False @classmethod def set_active_ops(cls, ops: 'Operator|None'): cls.active_ops = ops if ops is None: cls.is_active_ops_warning_thrown = False cls.is_active_ops_error_thrown = False @classmethod def get_active_ops(cls): return cls.active_ops @classmethod def report_finish(cls, success_msg: str = "", warning_msg: str = "", error_msg: str = ""): """Report a success message which can change with the warning/error situation.""" if cls.active_ops is not None: if cls.is_active_ops_error_thrown: cls.active_ops.report({'INFO'}, error_msg) cls.is_active_ops_error_thrown = False return 2 elif cls.is_active_ops_warning_thrown: cls.active_ops.report({'INFO'}, warning_msg) cls.is_active_ops_warning_thrown = False return 1 cls.active_ops.report({'INFO'}, success_msg) return 0 @classmethod def report_warning(cls, message: str): """Report an operation warning.""" if cls.active_ops is not None: cls.is_active_ops_warning_thrown: bool = True cls.active_ops.report({'WARNING'}, message) @classmethod def report_error(cls, message: str): """Report an operation error.""" if cls.active_ops is not None: cls.is_active_ops_error_thrown = True cls.active_ops.report({'ERROR'}, message)
0
0.77139
1
0.77139
game-dev
MEDIA
0.214442
game-dev
0.747257
1
0.747257
QYhB05/FinalTECH-Changed
6,703
src/main/java/io/taraxacum/finaltech/core/item/machine/range/line/pile/AbstractElectricityShootPile.java
package io.taraxacum.finaltech.core.item.machine.range.line.pile; import io.github.thebusybiscuit.slimefun4.api.items.ItemGroup; import io.github.thebusybiscuit.slimefun4.api.items.SlimefunItem; import io.github.thebusybiscuit.slimefun4.api.items.SlimefunItemStack; import io.github.thebusybiscuit.slimefun4.api.recipes.RecipeType; import io.github.thebusybiscuit.slimefun4.core.attributes.EnergyNetComponent; import io.github.thebusybiscuit.slimefun4.core.handlers.BlockBreakHandler; import io.github.thebusybiscuit.slimefun4.core.handlers.BlockPlaceHandler; import io.github.thebusybiscuit.slimefun4.core.networks.energy.EnergyNetComponentType; import io.taraxacum.common.util.JavaUtil; import io.taraxacum.common.util.StringNumberUtil; import io.taraxacum.finaltech.FinalTechChanged; import io.taraxacum.finaltech.core.interfaces.LocationMachine; import io.taraxacum.finaltech.core.interfaces.MenuUpdater; import io.taraxacum.finaltech.core.interfaces.RecipeItem; import io.taraxacum.finaltech.core.item.machine.range.AbstractRangeMachine; import io.taraxacum.finaltech.core.item.machine.range.line.AbstractLineMachine; import io.taraxacum.finaltech.core.menu.AbstractMachineMenu; import io.taraxacum.finaltech.core.menu.unit.StatusMenu; import io.taraxacum.finaltech.util.BlockTickerUtil; import io.taraxacum.finaltech.util.ConfigUtil; import io.taraxacum.finaltech.util.MachineUtil; import io.taraxacum.libs.plugin.util.ItemStackUtil; import io.taraxacum.libs.slimefun.dto.LocationInfo; import io.taraxacum.libs.slimefun.util.EnergyUtil; import me.mrCookieSlime.CSCoreLibPlugin.Configuration.Config; import me.mrCookieSlime.Slimefun.api.BlockStorage; import me.mrCookieSlime.Slimefun.api.inventory.BlockMenu; import org.bukkit.Location; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.block.data.BlockData; import org.bukkit.block.data.Directional; import org.bukkit.inventory.ItemStack; import javax.annotation.Nonnull; import java.util.HashSet; import java.util.Set; /** * @author Final_ROOT * @since 1.0 */ public abstract class AbstractElectricityShootPile extends AbstractLineMachine implements RecipeItem, MenuUpdater, LocationMachine { protected final Set<String> notAllowedId = new HashSet<>(ConfigUtil.getItemStringList(this, "not-allowed-id")); public AbstractElectricityShootPile(ItemGroup itemGroup, SlimefunItemStack item, RecipeType recipeType, ItemStack[] recipe) { super(itemGroup, item, recipeType, recipe); } @Nonnull @Override protected BlockPlaceHandler onBlockPlace() { return MachineUtil.BLOCK_PLACE_HANDLER_PLACER_DENY; } @Nonnull @Override protected BlockBreakHandler onBlockBreak() { return MachineUtil.simpleBlockBreakerHandler(this); } @Nonnull @Override protected AbstractMachineMenu setMachineMenu() { return new StatusMenu(this); } @Override protected void tick(@Nonnull Block block, @Nonnull SlimefunItem slimefunItem, @Nonnull Config config) { BlockData blockData = block.getBlockData(); if (blockData instanceof Directional directional) { Runnable runnable = () -> { int count = 0; Summary summary = new Summary(); LocationInfo locationInfo = LocationInfo.get(block.getRelative(directional.getFacing().getOppositeFace()).getLocation()); if (locationInfo != null && !this.notAllowedId.contains(locationInfo.getId()) && locationInfo.getSlimefunItem() instanceof EnergyNetComponent energyNetComponent && JavaUtil.matchOnce(energyNetComponent.getEnergyComponentType(), EnergyNetComponentType.CAPACITOR, EnergyNetComponentType.GENERATOR)) { int capacitorEnergy = Integer.parseInt(EnergyUtil.getCharge(locationInfo.getLocation())); summary.capacitorEnergy = capacitorEnergy; count = this.lineFunction(block, this.getRange(), this.doFunction(summary)); if (capacitorEnergy != summary.capacitorEnergy) { EnergyUtil.setCharge(locationInfo.getLocation(), summary.capacitorEnergy); } } BlockMenu blockMenu = BlockStorage.getInventory(block); if (blockMenu.hasViewer()) { this.updateMenu(blockMenu, StatusMenu.STATUS_SLOT, this, String.valueOf(count), summary.getEnergyCharge(), String.valueOf(summary.capacitorEnergy)); } }; BlockTickerUtil.runTask(FinalTechChanged.getLocationRunnableFactory(), FinalTechChanged.isAsyncSlimefunItem(this.getId()), runnable, () -> this.getLocations(block.getLocation())); } } @Override protected final boolean isSynchronized() { return false; } protected void updateMenu(@Nonnull BlockMenu blockMenu, int count, @Nonnull Summary summary) { ItemStack item = blockMenu.getItemInSlot(StatusMenu.STATUS_SLOT); ItemStackUtil.setLore(item, ConfigUtil.getStatusMenuLore(FinalTechChanged.getLanguageManager(), this, String.valueOf(count), summary.getEnergyCharge())); } public abstract int getRange(); @Override public Location[] getLocations(@Nonnull Location sourceLocation) { Block block = sourceLocation.getBlock(); BlockData blockData = block.getBlockData(); if (blockData instanceof Directional directional) { BlockFace blockFace = directional.getFacing(); Location[] locations = new Location[this.getRange() + 1]; int i = 0; locations[i++] = sourceLocation; while (i < locations.length) { locations[i++] = block.getRelative(blockFace, i - 1).getLocation(); } return locations; } return new Location[0]; } @Nonnull protected abstract AbstractRangeMachine.RangeFunction doFunction(@Nonnull Summary summary); protected static class Summary { private String energyCharge; private int capacitorEnergy; Summary() { this.energyCharge = StringNumberUtil.ZERO; } public String getEnergyCharge() { return energyCharge; } public void setEnergyCharge(String energyCharge) { this.energyCharge = energyCharge; } public int getCapacitorEnergy() { return capacitorEnergy; } public void setCapacitorEnergy(int capacitorEnergy) { this.capacitorEnergy = capacitorEnergy; } } }
0
0.926862
1
0.926862
game-dev
MEDIA
0.907251
game-dev
0.917043
1
0.917043
magicleap/UnityGLTF-Interactivity
10,576
Assets/Interactivity/Frontend/Scripts/NodeSpecs/Math/TwoOperands.cs
using System; using Unity.Mathematics; using UnityEngine; namespace UnityGLTF.Interactivity.Playback { public abstract class MathTwoOperandsSpecBase : NodeSpecifications { protected string _resultDescription; protected string _op1Description; protected string _op2Description; public MathTwoOperandsSpecBase(string resultDescription = "Result", string op1Description = "Operand 1", string op2Description = "Operand 2") { _op1Description = op1Description; _op2Description = op2Description; _resultDescription = resultDescription; } } public class MathTwoOperandsSpec<T, T1, T2, T3> : MathTwoOperandsSpecBase { public MathTwoOperandsSpec(string resultDescription = "Result", string op1Description = "Operand 1", string op2Description = "Operand 2") : base(resultDescription, op1Description, op2Description) {} protected override (NodeFlow[] flows, NodeValue[] values) GenerateInputs() { var values = new NodeValue[] { new NodeValue(ConstStrings.A, _op1Description, new Type[] { typeof(T), typeof(T1), typeof(T2), typeof(T3) }), new NodeValue(ConstStrings.B, _op2Description, new Type[] { typeof(T), typeof(T1), typeof(T2), typeof(T3) }), }; return (null, values); } protected override (NodeFlow[] flows, NodeValue[] values) GenerateOutputs() { var values = new NodeValue[] { new NodeValue(ConstStrings.VALUE, _resultDescription, new Type[] { typeof(T), typeof(T1), typeof(T2), typeof(T3)}), }; return (null, values); } } public class MathTwoOperandsSpec<T, T1, T2, T3, T4> : MathTwoOperandsSpecBase { public MathTwoOperandsSpec(string resultDescription = "Result", string op1Description = "Operand 1", string op2Description = "Operand 2") : base(resultDescription, op1Description, op2Description) {} protected override (NodeFlow[] flows, NodeValue[] values) GenerateInputs() { var values = new NodeValue[] { new NodeValue(ConstStrings.A, _op1Description, new Type[] { typeof(T), typeof(T1), typeof(T2), typeof(T3), typeof(T4) }), new NodeValue(ConstStrings.B, _op2Description, new Type[] { typeof(T), typeof(T1), typeof(T2), typeof(T3), typeof(T4) }), }; return (null, values); } protected override (NodeFlow[] flows, NodeValue[] values) GenerateOutputs() { var values = new NodeValue[] { new NodeValue(ConstStrings.VALUE, _resultDescription, new Type[] { typeof(T), typeof(T1), typeof(T2), typeof(T3), typeof(T4) }), }; return (null, values); } } public class MathTwoOperandsSpec<T, T1, T2, T3, T4, T5> : MathTwoOperandsSpecBase { public MathTwoOperandsSpec(string resultDescription = "Result", string op1Description = "Operand 1", string op2Description = "Operand 2") : base(resultDescription, op1Description, op2Description) {} protected override (NodeFlow[] flows, NodeValue[] values) GenerateInputs() { var values = new NodeValue[] { new NodeValue(ConstStrings.A, _op1Description, new Type[] { typeof(T), typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5) }), new NodeValue(ConstStrings.B, _op2Description, new Type[] { typeof(T), typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5) }), }; return (null, values); } protected override (NodeFlow[] flows, NodeValue[] values) GenerateOutputs() { var values = new NodeValue[] { new NodeValue(ConstStrings.VALUE, _resultDescription, new Type[] { typeof(T), typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5) }), }; return (null, values); } } public class MathTwoOperandsRetSpec<T, T1, T2, T3, T4, T5, TRes> : MathTwoOperandsSpecBase { public MathTwoOperandsRetSpec(string resultDescription = "Result", string op1Description = "Operand 1", string op2Description = "Operand 2") : base(resultDescription, op1Description, op2Description) {} protected override (NodeFlow[] flows, NodeValue[] values) GenerateInputs() { var values = new NodeValue[] { new NodeValue(ConstStrings.A, _op1Description, new Type[] { typeof(T), typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5) }), new NodeValue(ConstStrings.B, _op2Description, new Type[] { typeof(T), typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5) }), }; return (null, values); } protected override (NodeFlow[] flows, NodeValue[] values) GenerateOutputs() { var values = new NodeValue[] { new NodeValue(ConstStrings.VALUE, _resultDescription, new Type[] { typeof(TRes) }), }; return (null, values); } } public class MathTwoOperandsSpec<T> : MathTwoOperandsSpecBase { public MathTwoOperandsSpec(string resultDescription = "Result", string op1Description = "Operand 1", string op2Description = "Operand 2") : base(resultDescription, op1Description, op2Description) {} protected override (NodeFlow[] flows, NodeValue[] values) GenerateInputs() { var values = new NodeValue[] { new NodeValue(ConstStrings.A, _op1Description, new Type[] { typeof(T)}), new NodeValue(ConstStrings.B, _op2Description, new Type[] { typeof(T)}), }; return (null, values); } protected override (NodeFlow[] flows, NodeValue[] values) GenerateOutputs() { var values = new NodeValue[] { new NodeValue(ConstStrings.VALUE, _resultDescription, new Type[] { typeof(T) }), }; return (null, values); } } public class MathTwoOperandsSpec<T, T1> : MathTwoOperandsSpecBase { public MathTwoOperandsSpec(string resultDescription = "Result", string op1Description = "Operand 1", string op2Description = "Operand 2") : base(resultDescription, op1Description, op2Description) {} protected override (NodeFlow[] flows, NodeValue[] values) GenerateInputs() { var values = new NodeValue[] { new NodeValue(ConstStrings.A, _op1Description, new Type[] { typeof(T), typeof(T1)}), new NodeValue(ConstStrings.B, _op2Description, new Type[] { typeof(T), typeof(T1)}), }; return (null, values); } protected override (NodeFlow[] flows, NodeValue[] values) GenerateOutputs() { var values = new NodeValue[] { new NodeValue(ConstStrings.VALUE, _resultDescription, new Type[] { typeof(T), typeof(T1) }), }; return (null, values); } } public class MathTwoOperandsSpec<T, T1, T2> : MathTwoOperandsSpecBase { public MathTwoOperandsSpec(string resultDescription = "Result", string op1Description = "Operand 1", string op2Description = "Operand 2") : base(resultDescription, op1Description, op2Description) {} protected override (NodeFlow[] flows, NodeValue[] values) GenerateInputs() { var values = new NodeValue[] { new NodeValue(ConstStrings.A, _op1Description, new Type[] { typeof(T), typeof(T1), typeof(T2)}), new NodeValue(ConstStrings.B, _op2Description, new Type[] { typeof(T), typeof(T1), typeof(T2)}), }; return (null, values); } protected override (NodeFlow[] flows, NodeValue[] values) GenerateOutputs() { var values = new NodeValue[] { new NodeValue(ConstStrings.VALUE, _resultDescription, new Type[] { typeof(T), typeof(T1), typeof(T2)}), }; return (null, values); } } public class MathTwoOperandsRetSpec<T, T1, T2> : MathTwoOperandsSpecBase { public MathTwoOperandsRetSpec(string resultDescription = "Result", string op1Description = "Operand 1", string op2Description = "Operand 2") : base(resultDescription, op1Description, op2Description) {} protected override (NodeFlow[] flows, NodeValue[] values) GenerateInputs() { var values = new NodeValue[] { new NodeValue(ConstStrings.A, _op1Description, new Type[] { typeof(T), typeof(T1)}), new NodeValue(ConstStrings.B, _op2Description, new Type[] { typeof(T), typeof(T1)}), }; return (null, values); } protected override (NodeFlow[] flows, NodeValue[] values) GenerateOutputs() { var values = new NodeValue[] { new NodeValue(ConstStrings.VALUE, _resultDescription, new Type[] { typeof(T2) }), }; return (null, values); } } public class MathTwoOperandsRetSpec<T, T1, T2, T3> : MathTwoOperandsSpecBase { public MathTwoOperandsRetSpec(string resultDescription = "Result", string op1Description = "Operand 1", string op2Description = "Operand 2") : base(resultDescription, op1Description, op2Description) {} protected override (NodeFlow[] flows, NodeValue[] values) GenerateInputs() { var values = new NodeValue[] { new NodeValue(ConstStrings.A, _op1Description, new Type[] { typeof(T), typeof(T1), typeof(T2)}), new NodeValue(ConstStrings.B, _op2Description, new Type[] { typeof(T), typeof(T1), typeof(T2)}), }; return (null, values); } protected override (NodeFlow[] flows, NodeValue[] values) GenerateOutputs() { var values = new NodeValue[] { new NodeValue(ConstStrings.VALUE, _resultDescription, new Type[] { typeof(T3) }), }; return (null, values); } } public class MathTwoOperandsSpec : MathTwoOperandsSpec<int, float, float2, float3, float4> { } public class MathTwoOperandsFloatSpec : MathTwoOperandsSpec<float, float2, float3, float4> { } }
0
0.9426
1
0.9426
game-dev
MEDIA
0.315212
game-dev
0.935041
1
0.935041
ihmcrobotics/ihmc-open-robotics-software
14,768
ihmc-common-walking-control-modules/src/main/java/us/ihmc/commonWalkingControlModules/highLevelHumanoidControl/highLevelStates/walkingController/states/TransferToWalkingSingleSupportState.java
package us.ihmc.commonWalkingControlModules.highLevelHumanoidControl.highLevelStates.walkingController.states; import org.apache.commons.math3.util.Precision; import us.ihmc.commonWalkingControlModules.configurations.WalkingControllerParameters; import us.ihmc.commonWalkingControlModules.controlModules.WalkingFailureDetectionControlModule; import us.ihmc.commonWalkingControlModules.highLevelHumanoidControl.factories.HighLevelControlManagerFactory; import us.ihmc.commonWalkingControlModules.highLevelHumanoidControl.highLevelStates.walkingController.TouchdownErrorCompensator; import us.ihmc.commonWalkingControlModules.messageHandlers.WalkingMessageHandler; import us.ihmc.commonWalkingControlModules.momentumBasedController.HighLevelHumanoidControllerToolbox; import us.ihmc.commonWalkingControlModules.momentumBasedController.ParameterProvider; import us.ihmc.euclid.referenceFrame.FramePose3D; import us.ihmc.euclid.referenceFrame.FrameQuaternion; import us.ihmc.euclid.referenceFrame.FrameVector3D; import us.ihmc.euclid.referenceFrame.ReferenceFrame; import us.ihmc.humanoidRobotics.footstep.Footstep; import us.ihmc.humanoidRobotics.footstep.FootstepTiming; import us.ihmc.mecano.frames.MovingReferenceFrame; import us.ihmc.robotics.math.trajectories.trajectorypoints.FrameSE3TrajectoryPoint; import us.ihmc.robotics.robotSide.RobotSide; import us.ihmc.robotics.trajectories.TrajectoryType; import us.ihmc.yoVariables.parameters.BooleanParameter; import us.ihmc.yoVariables.providers.BooleanProvider; import us.ihmc.yoVariables.providers.DoubleProvider; import us.ihmc.yoVariables.registry.YoRegistry; import us.ihmc.yoVariables.variable.YoBoolean; import us.ihmc.yoVariables.variable.YoDouble; public class TransferToWalkingSingleSupportState extends TransferState { private static final ReferenceFrame worldFrame = ReferenceFrame.getWorldFrame(); private final int numberOfFootstepsToConsider; private final Footstep[] footsteps; private final FootstepTiming[] footstepTimings; private final DoubleProvider minimumTransferTime; private final YoDouble currentTransferDuration = new YoDouble("CurrentTransferDuration", registry); private final YoBoolean resubmitStepsInTransferEveryTick = new YoBoolean("resubmitStepsInTransferEveryTick", registry); private final YoDouble originalTransferTime = new YoDouble("OriginalTransferTime", registry); private final BooleanProvider minimizeAngularMomentumRateZDuringTransfer; private final DoubleProvider icpErrorThresholdForSlowTransfer; private final DoubleProvider minimumSlowTransferDuration; private final FramePose3D actualFootPositionInWorld = new FramePose3D(); private final FrameVector3D tempAngularVelocity = new FrameVector3D(); private final FrameQuaternion tempOrientation = new FrameQuaternion(); private final TouchdownErrorCompensator touchdownErrorCompensator; // This flag indicates whether or not its the first tick in the transfer state. This is used to avoid double-computing some of the calls. private boolean firstTickInState = true; protected final RobotSide swingSide; public TransferToWalkingSingleSupportState(WalkingStateEnum stateEnum, WalkingMessageHandler walkingMessageHandler, TouchdownErrorCompensator touchdownErrorCompensator, HighLevelHumanoidControllerToolbox controllerToolbox, HighLevelControlManagerFactory managerFactory, WalkingControllerParameters walkingControllerParameters, WalkingFailureDetectionControlModule failureDetectionControlModule, DoubleProvider minimumTransferTime, DoubleProvider unloadFraction, DoubleProvider rhoMin, YoRegistry parentRegistry) { super(stateEnum, walkingMessageHandler, controllerToolbox, managerFactory, failureDetectionControlModule, unloadFraction, rhoMin, parentRegistry); this.minimumTransferTime = minimumTransferTime; this.touchdownErrorCompensator = touchdownErrorCompensator; minimizeAngularMomentumRateZDuringTransfer = new BooleanParameter("minimizeAngularMomentumRateZDuringTransfer", registry, walkingControllerParameters.minimizeAngularMomentumRateZDuringTransfer()); icpErrorThresholdForSlowTransfer = ParameterProvider.getOrCreateParameter(parentRegistry.getName(), getClass().getSimpleName(), "icpErrorThresholdForSlowTransfer", registry, walkingControllerParameters.getInitialICPErrorToSlowDownTransfer()); minimumSlowTransferDuration = ParameterProvider.getOrCreateParameter(parentRegistry.getName(), getClass().getSimpleName(), "minimumSlowTransferDuration", registry, walkingControllerParameters.getMinimumSlowTransferDuration()); resubmitStepsInTransferEveryTick.set(walkingControllerParameters.resubmitStepsInTransferEveryTick()); numberOfFootstepsToConsider = balanceManager.getMaxNumberOfStepsToConsider(); footsteps = Footstep.createFootsteps(numberOfFootstepsToConsider); footstepTimings = FootstepTiming.createTimings(numberOfFootstepsToConsider); swingSide = transferToSide.getOppositeSide(); } @Override protected void updateICPPlan() { super.updateICPPlan(); // This needs to check `TO_STANDING` as well as messages could be received on the very first controller tick at which point // the robot is not in the standing state but not yet walking either. if (getPreviousWalkingStateEnum() == WalkingStateEnum.STANDING || getPreviousWalkingStateEnum() == WalkingStateEnum.TO_STANDING) { walkingMessageHandler.reportWalkingStarted(); } double finalTransferTime = walkingMessageHandler.getFinalTransferTime(); balanceManager.setFinalTransferTime(finalTransferTime); int stepsToAdd = Math.min(numberOfFootstepsToConsider, walkingMessageHandler.getCurrentNumberOfFootsteps()); if (stepsToAdd < 1) { throw new RuntimeException("Can not go to walking single support if there are no upcoming footsteps."); } for (int i = 0; i < stepsToAdd; i++) { Footstep footstep = footsteps[i]; FootstepTiming timing = footstepTimings[i]; walkingMessageHandler.peekFootstep(i, footstep); walkingMessageHandler.peekTiming(i, timing); if (i == 0) { adjustTiming(timing); walkingMessageHandler.adjustTiming(timing.getSwingTime(), timing.getTransferTime()); } balanceManager.addFootstepToPlan(footstep, timing); } FootstepTiming firstTiming = footstepTimings[0]; currentTransferDuration.set(firstTiming.getTransferTime()); balanceManager.setFinalTransferTime(finalTransferTime); balanceManager.initializeICPPlanForTransfer(); } @Override public void doAction(double timeInState) { // Beomyeong: This is triggered, so that means, if walkingMessageHandler is updated when new VR stepping is delivered. // We don't need to add something to calculate & update the ICP , CMP if (resubmitStepsInTransferEveryTick.getBooleanValue() && balanceManager.getNumberOfStepsBeingConsidered() < walkingMessageHandler.getCurrentNumberOfFootsteps()) { int stepsToAdd = Math.min(numberOfFootstepsToConsider, walkingMessageHandler.getCurrentNumberOfFootsteps()); for (int i = balanceManager.getNumberOfStepsBeingConsidered() - 1; i < stepsToAdd; i++) { Footstep footstep = footsteps[i]; FootstepTiming timing = footstepTimings[i]; walkingMessageHandler.peekFootstep(i, footstep); walkingMessageHandler.peekTiming(i, timing); balanceManager.addFootstepToPlan(footstep, timing); } } // RobotSide swingSide = transferToSide.getOppositeSide(); if (!firstTickInState) feetManager.updateSwingTrajectoryPreview(swingSide); balanceManager.setSwingFootTrajectory(swingSide, feetManager.getSwingTrajectory(swingSide)); balanceManager.computeICPPlan(); updateWalkingTrajectoryPath(); if (!doManualLiftOff()) { if (switchToToeOffIfPossible()) feetManager.initializeSwingTrajectoryPreview(swingSide, footsteps[0], footstepTimings[0].getSwingTime()); } super.doAction(timeInState); double transferDuration = currentTransferDuration.getDoubleValue(); updateFootPlanOffset(); double toeOffDuration = footstepTimings[0].getLiftoffDuration(); if (doManualLiftOff() && transferDuration - timeInState < toeOffDuration) { Footstep upcomingFootstep = footsteps[0]; FrameSE3TrajectoryPoint firstWaypoint = upcomingFootstep.getSwingTrajectory().get(0); MovingReferenceFrame soleZUpFrame = controllerToolbox.getReferenceFrames().getSoleZUpFrame(transferToSide.getOppositeSide()); tempOrientation.setIncludingFrame(firstWaypoint.getOrientation()); tempOrientation.changeFrame(soleZUpFrame); tempAngularVelocity.setIncludingFrame(firstWaypoint.getAngularVelocity()); tempAngularVelocity.changeFrame(soleZUpFrame); // The y component is equivalent to the pitch rate since the yaw and roll rate are 0.0 feetManager.liftOff(transferToSide.getOppositeSide(), tempOrientation.getPitch(), tempAngularVelocity.getY(), toeOffDuration); } firstTickInState = false; } private void updateWalkingTrajectoryPath() { walkingTrajectoryPath.clearFootsteps(); walkingTrajectoryPath.addFootsteps(walkingMessageHandler); walkingTrajectoryPath.updateTrajectory(feetManager.getCurrentConstraintType(RobotSide.LEFT), feetManager.getCurrentConstraintType(RobotSide.RIGHT)); } private boolean doManualLiftOff() { Footstep upcomingFootstep = footsteps[0]; return upcomingFootstep.getTrajectoryType() == TrajectoryType.WAYPOINTS && Precision.equals(upcomingFootstep.getSwingTrajectory().get(0).getTime(), 0.0); } @Override public void onEntry() { firstTickInState = true; if (balanceManager.getICPErrorMagnitude() > icpErrorThresholdForSlowTransfer.getValue()) { walkingMessageHandler.peekTiming(0, footstepTimings[0]); double transferDuration = Math.max(minimumSlowTransferDuration.getValue(), 2.0 * footstepTimings[0].getTransferTime()); walkingMessageHandler.setUpcomingFootstepTransferDuration(transferDuration); } super.onEntry(); feetManager.initializeSwingTrajectoryPreview(transferToSide.getOppositeSide(), footsteps[0], footstepTimings[0].getSwingTime()); balanceManager.minimizeAngularMomentumRateZ(minimizeAngularMomentumRateZDuringTransfer.getValue()); updateFootPlanOffset(); } @Override public boolean isDone(double timeInState) { return super.isDone(timeInState) || feetManager.isFootToeingOffSlipping(transferToSide.getOppositeSide()); } @Override public void onExit(double timeInState) { super.onExit(timeInState); touchdownErrorCompensator.commitToFootTouchdownError(transferToSide); touchdownErrorCompensator.clear(); firstTickInState = true; balanceManager.minimizeAngularMomentumRateZ(false); } /** * This method checks if the upcoming step has a desired absolute start time. If that is the case * the transfer time is adjusted such that the swing starts at the correct time. */ private void adjustTiming(FootstepTiming stepTiming) { if (!stepTiming.hasAbsoluteTime()) { originalTransferTime.setToNaN(); return; } double originalSwingTime = stepTiming.getSwingTime(); double originalTransferTime = stepTiming.getTransferTime(); this.originalTransferTime.set(originalTransferTime); double currentTime = controllerToolbox.getYoTime().getDoubleValue(); double timeInFootstepPlan = currentTime - stepTiming.getExecutionStartTime(); double adjustedTransferTime = stepTiming.getSwingStartTime() - timeInFootstepPlan; // make sure transfer does not get too short adjustedTransferTime = Math.max(adjustedTransferTime, minimumTransferTime.getValue()); // GW TODO - possible improvement: // If the adjustment is capped by the minimum transfer time adjust also the upcoming transfer times here. That // would make the ICP plan for the upcoming steps more accurate. However, if the given original transfer times // are correctly set this might be a minimal improvement that makes step timing more complicated and difficult // to debug. If we have big adjustments a lot we should revisit this. // keep swing times and only adjust transfers for now stepTiming.setTimings(originalSwingTime, adjustedTransferTime); } private void updateFootPlanOffset() { WalkingStateEnum previousStateEnum = getPreviousWalkingStateEnum(); if (previousStateEnum == null) return; RobotSide previousSupportSide = previousStateEnum.getSupportSide(); if (previousSupportSide == null) return; RobotSide previousSwingSide = previousSupportSide.getOppositeSide(); if (touchdownErrorCompensator.planShouldBeOffsetFromStep(previousSwingSide) && touchdownErrorCompensator.isFootPositionTrusted(previousSwingSide)) { actualFootPositionInWorld.setToZero(controllerToolbox.getReferenceFrames().getSoleFrame(previousSwingSide)); actualFootPositionInWorld.changeFrame(worldFrame); touchdownErrorCompensator.updateFootTouchdownError(previousSwingSide, actualFootPositionInWorld); } } }
0
0.962133
1
0.962133
game-dev
MEDIA
0.218457
game-dev
0.96533
1
0.96533
Darkrp-community/OpenKeep
6,187
code/game/objects/items/rogueweapons/ranged/crossbows.dm
/obj/item/gun/ballistic/revolver/grenadelauncher/crossbow name = "crossbow" desc = "A mechanical ranged weapon of simple design, affixed with a stirrup and fired via trigger." icon = 'icons/roguetown/weapons/bows.dmi' // icon = 'icons/roguetown/weapons/32.dmi' icon_state = "crossbow0" item_state = "crossbow" possible_item_intents = list(/datum/intent/shoot/crossbow, /datum/intent/arc/crossbow, INTENT_GENERIC) mag_type = /obj/item/ammo_box/magazine/internal/shot/xbow slot_flags = ITEM_SLOT_BACK w_class = WEIGHT_CLASS_BULKY randomspread = 1 spread = 0 can_parry = TRUE pin = /obj/item/firing_pin force = 10 var/cocked = FALSE cartridge_wording = "bolt" load_sound = 'sound/foley/nockarrow.ogg' fire_sound = 'sound/combat/Ranged/crossbow-small-shot-02.ogg' associated_skill = /datum/skill/combat/crossbows /obj/item/gun/ballistic/revolver/grenadelauncher/crossbow/getonmobprop(tag) . = ..() if(tag) switch(tag) if("gen") return list("shrink" = 0.5,"sx" = -4,"sy" = -6,"nx" = 9,"ny" = -6,"wx" = -6,"wy" = -4,"ex" = 4,"ey" = -6,"northabove" = 0,"southabove" = 1,"eastabove" = 1,"westabove" = 0,"nturn" = 0,"sturn" = 90,"wturn" = 93,"eturn" = -12,"nflip" = 0,"sflip" = 1,"wflip" = 0,"eflip" = 0) if("onbelt") return list("shrink" = 0.3,"sx" = -2,"sy" = -5,"nx" = 4,"ny" = -5,"wx" = 0,"wy" = -5,"ex" = 2,"ey" = -5,"nturn" = 0,"sturn" = 0,"wturn" = 0,"eturn" = 0,"nflip" = 0,"sflip" = 0,"wflip" = 0,"eflip" = 0,"northabove" = 0,"southabove" = 1,"eastabove" = 1,"westabove" = 0) /datum/intent/shoot/crossbow chargedrain = 0 //no drain to aim a crossbow /datum/intent/shoot/crossbow/get_chargetime() if(mastermob && chargetime) var/newtime = chargetime //skill block newtime = newtime + 18 newtime = newtime - (mastermob.mind.get_skill_level(/datum/skill/combat/crossbows) * 3) //per block newtime = newtime + 20 newtime = newtime - (mastermob.STAPER) if(newtime > 0) return newtime else return 0.1 return chargetime /datum/intent/shoot/musket chargedrain = 0 //no drain to aim a gun charging_slowdown = 4 warnoffset = 20 chargetime = 10 /datum/intent/shoot/musket/arc name = "arc" icon_state = "inarc" chargedrain = 1 charging_slowdown = 3 warnoffset = 20 /datum/intent/shoot/musket/arc/arc_check() return TRUE /datum/intent/shoot/musket/get_chargetime() if(mastermob && chargetime) var/newtime = chargetime //skill block newtime = newtime + 18 newtime = newtime - (mastermob.mind.get_skill_level(/datum/skill/combat/firearms) * 3.5) //per block newtime = newtime + 20 // Perception aint gonna help you with loading a musket, bud //newtime = newtime - (mastermob.STAPER) if(newtime > 0) return newtime else return 0.1 return chargetime /datum/intent/shoot/musket/pistol/get_chargetime() if(mastermob && chargetime) var/newtime = chargetime //skill block newtime = newtime + 18 newtime = newtime - (mastermob.mind.get_skill_level(/datum/skill/combat/firearms) * 3) //per block newtime = newtime + 20 newtime = newtime - (mastermob.STAPER) if(newtime > 0) return newtime else return 1 return chargetime /datum/intent/arc/crossbow chargetime = 1 chargedrain = 0 //no drain to aim a crossbow /datum/intent/arc/crossbow/get_chargetime() if(mastermob && chargetime) var/newtime = chargetime //skill block newtime = newtime + 18 newtime = newtime - (mastermob.mind.get_skill_level(/datum/skill/combat/crossbows) * 3) //per block newtime = newtime + 20 newtime = newtime - (mastermob.STAPER) if(newtime > 0) return newtime else return 1 return chargetime /obj/item/gun/ballistic/revolver/grenadelauncher/crossbow/shoot_with_empty_chamber() if(cocked) playsound(src.loc, 'sound/combat/Ranged/crossbow-small-shot-02.ogg', 100, FALSE) cocked = FALSE update_icon() /obj/item/gun/ballistic/revolver/grenadelauncher/crossbow/attack_self(mob/living/user) if(chambered) ..() else if(!cocked) to_chat(user, "<span class='info'>I step on the stirrup and use all my might...</span>") if(do_after(user, 40 - user.STASTR, target = user)) playsound(user, 'sound/combat/Ranged/crossbow_medium_reload-01.ogg', 100, FALSE) cocked = TRUE else to_chat(user, "<span class='warning'>I carefully de-cock the crossbow.</span>") cocked = FALSE update_icon() /obj/item/gun/ballistic/revolver/grenadelauncher/crossbow/attackby(obj/item/A, mob/user, params) if(istype(A, /obj/item/ammo_box) || istype(A, /obj/item/ammo_casing)) if(cocked) ..() else to_chat(user, "<span class='warning'>I need to cock the crossbow first.</span>") /obj/item/gun/ballistic/revolver/grenadelauncher/crossbow/process_fire(atom/target, mob/living/user, message = TRUE, params = null, zone_override = "", bonus_spread = 0) if(user.client) if(user.client.chargedprog >= 100) spread = 0 else spread = 150 - (150 * (user.client.chargedprog / 100)) else spread = 0 for(var/obj/item/ammo_casing/CB in get_ammo_list(FALSE, TRUE)) var/obj/projectile/BB = CB.BB if(user.client) if(user.client.chargedprog >= 100) BB.accuracy += 15 //better accuracy for fully aiming if(user.STAPER > 8) BB.accuracy += (user.STAPER - 8) * 4 //each point of perception above 8 increases standard accuracy by 4. BB.bonus_accuracy += (user.STAPER - 8) //Also, increases bonus accuracy by 1, which cannot fall off due to distance. if(user.STAPER > 10) BB.damage = BB.damage * (user.STAPER / 10) BB.damage *= damfactor // Apply damfactor multiplier regardless of PER. BB.bonus_accuracy += (user.mind.get_skill_level(/datum/skill/combat/crossbows) * 3) //+3 accuracy per level in crossbows cocked = FALSE ..() /obj/item/gun/ballistic/revolver/grenadelauncher/crossbow/update_icon() . = ..() if(cocked) icon_state = "crossbow1" else icon_state = "crossbow0" cut_overlays() if(chambered) var/obj/item/I = chambered I.pixel_x = 0 I.pixel_y = 0 add_overlay(new /mutable_appearance(I)) if(ismob(loc)) var/mob/M = loc M.update_inv_hands() /obj/item/ammo_box/magazine/internal/shot/xbow ammo_type = /obj/item/ammo_casing/caseless/rogue/bolt caliber = "regbolt" max_ammo = 1 start_empty = TRUE
0
0.836855
1
0.836855
game-dev
MEDIA
0.970669
game-dev
0.972372
1
0.972372