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
thnewlands/unity-deformablesnow
2,761
Assets/Standard Assets/Utility/PlatformSpecificContent.cs
using System; using UnityEngine; #if UNITY_EDITOR using UnityEditor; #endif namespace UnityStandardAssets.Utility { #if UNITY_EDITOR [ExecuteInEditMode] #endif public class PlatformSpecificContent : MonoBehaviour #if UNITY_EDITOR , UnityEditor.Build.IActiveBuildTargetChanged #endif { private enum BuildTargetGroup { Standalone, Mobile } [SerializeField] private BuildTargetGroup m_BuildTargetGroup; [SerializeField] private GameObject[] m_Content = new GameObject[0]; [SerializeField] private MonoBehaviour[] m_MonoBehaviours = new MonoBehaviour[0]; [SerializeField] private bool m_ChildrenOfThisObject; #if !UNITY_EDITOR void OnEnable() { CheckEnableContent(); } #else public int callbackOrder { get { return 1; } } #endif #if UNITY_EDITOR private void OnEnable() { EditorApplication.update += Update; } private void OnDisable() { EditorApplication.update -= Update; } public void OnActiveBuildTargetChanged(BuildTarget previousTarget, BuildTarget newTarget) { CheckEnableContent(); } private void Update() { CheckEnableContent(); } #endif private void CheckEnableContent() { #if (UNITY_IPHONE || UNITY_ANDROID || UNITY_WP8 || UNITY_TIZEN || UNITY_STV ) if (m_BuildTargetGroup == BuildTargetGroup.Mobile) { EnableContent(true); } else { EnableContent(false); } #endif #if !(UNITY_IPHONE || UNITY_ANDROID || UNITY_WP8 || UNITY_TIZEN || UNITY_STV ) if (m_BuildTargetGroup == BuildTargetGroup.Mobile) { EnableContent(false); } else { EnableContent(true); } #endif } private void EnableContent(bool enabled) { if (m_Content.Length > 0) { foreach (var g in m_Content) { if (g != null) { g.SetActive(enabled); } } } if (m_ChildrenOfThisObject) { foreach (Transform t in transform) { t.gameObject.SetActive(enabled); } } if (m_MonoBehaviours.Length > 0) { foreach (var monoBehaviour in m_MonoBehaviours) { monoBehaviour.enabled = enabled; } } } } }
1
0.80992
1
0.80992
game-dev
MEDIA
0.973966
game-dev
0.616054
1
0.616054
decentraland/unity-renderer
8,836
unity-renderer/Assets/Scripts/MainScripts/DCL/AvatarSystem/Loader/AvatarSystemUtils.cs
using System; using System.Collections.Generic; using System.Linq; using DCL; using DCL.Helpers; using DCL.Shaders; using UnityEngine; using Object = UnityEngine.Object; namespace AvatarSystem { public static class AvatarSystemUtils { public const float AVATAR_Y_OFFSET = 0.75f; private const string AB_FEATURE_FLAG_NAME = "wearable_asset_bundles"; public static bool IsCategoryRequired(string category) { return WearableLiterals.Categories.REQUIRED_CATEGORIES.Contains(category); } public static bool UseAssetBundles() { var featureFlags = DataStore.i.featureFlags.flags.Get(); return featureFlags != null && featureFlags.IsFeatureEnabled(AB_FEATURE_FLAG_NAME); } public static (string mainTextureUrl, string maskTextureUrl) GetFacialFeatureTexturesUrls(string bodyshapeId, WearableItem facialFeature) { if (facialFeature.data.category != WearableLiterals.Categories.EYES && facialFeature.data.category == WearableLiterals.Categories.EYEBROWS && facialFeature.data.category == WearableLiterals.Categories.MOUTH) return (null, null); var representation = facialFeature.GetRepresentation(bodyshapeId); string mainTextureHash = representation?.contents?.FirstOrDefault(x => x.key == representation?.mainFile)?.hash; if (string.IsNullOrEmpty(mainTextureHash)) mainTextureHash = representation?.contents?.FirstOrDefault(x => !x.key.ToLower().Contains("_mask.png"))?.hash; if (string.IsNullOrEmpty(mainTextureHash)) return (null, null); string maskTextureHash = representation?.contents?.FirstOrDefault(x => x.key.ToLower().Contains("_mask.png"))?.hash; string mainTextureUrl = facialFeature.baseUrl + mainTextureHash; string maskTextureUrl = maskTextureHash == null ? null : facialFeature.baseUrl + maskTextureHash; return (mainTextureUrl, maskTextureUrl); } public static void CopyBones(Transform rootBone, Transform[] bones, IEnumerable<SkinnedMeshRenderer> targets) { if (rootBone == null || bones == null) return; foreach (SkinnedMeshRenderer skinnedMeshRenderer in targets) { CopyBones(rootBone, bones, skinnedMeshRenderer); } } public static void CopyBones(Transform rootBone, Transform[] bones, SkinnedMeshRenderer skinnedMeshRenderer) { if (rootBone == null || bones == null || skinnedMeshRenderer == null) return; skinnedMeshRenderer.rootBone = rootBone; skinnedMeshRenderer.bones = bones; } public static void PrepareMaterialColors(Rendereable rendereable, Color skinColor, Color hairColor) { foreach (Renderer renderer in rendereable.renderers) { foreach (Material material in renderer.materials) { // If this is modified, check DecentralandMaterialGenerator.SetMaterialName, // its important for the asset bundles materials to have normalized names but this functionality should work too string name = material.name.ToLower(); if (name.Contains("skin")) material.SetColor(ShaderUtils.BaseColor, skinColor); else if (name.Contains("hair")) material.SetColor(ShaderUtils.BaseColor, hairColor); } } } /// <summary> /// Extract bodyparts of a Rendereable. /// /// Using this on a Rendereable that doesn't comes from a bodyshape might result in unexpected result /// </summary> /// <param name="rendereable"></param> /// <returns></returns> // TODO: The list of body shapes that need to be extracted should come from an external source, // in order to make this scalable we should return a Dictionary<string, SkinnedMeshRenderer> with the results public static ( SkinnedMeshRenderer head, SkinnedMeshRenderer upperBody, SkinnedMeshRenderer lowerBody, SkinnedMeshRenderer feet, SkinnedMeshRenderer eyes, SkinnedMeshRenderer eyebrows, SkinnedMeshRenderer mouth, SkinnedMeshRenderer hands, List<SkinnedMeshRenderer> extraParts ) ExtractBodyShapeParts(Rendereable rendereable) { SkinnedMeshRenderer head = null; SkinnedMeshRenderer upperBody = null; SkinnedMeshRenderer lowerBody = null; SkinnedMeshRenderer feet = null; SkinnedMeshRenderer eyes = null; SkinnedMeshRenderer eyebrows = null; SkinnedMeshRenderer mouth = null; SkinnedMeshRenderer hands = null; var extraParts = new List<SkinnedMeshRenderer>(); foreach (Renderer r in rendereable.renderers) { if (r is not SkinnedMeshRenderer renderer) continue; string name = renderer.name.ToLower(); // we still support the old gltf hierarchy for ABs if (name.Contains("primitive")) name = renderer.transform.parent.name.ToLower(); if (name.Contains("head")) head = renderer; else if (name.Contains("ubody")) upperBody = renderer; else if (name.Contains("lbody")) lowerBody = renderer; else if (name.Contains("hands")) hands = renderer; else if (name.Contains("feet")) feet = renderer; else if (name.Contains("eyes")) eyes = renderer; else if (name.Contains("eyebrows")) eyebrows = renderer; else if (name.Contains("mouth")) mouth = renderer; else { Debug.LogWarning($"{name} has not been set-up as a valid body part", r); extraParts.Add(renderer); } } return (head, upperBody, lowerBody, feet, eyes, eyebrows, mouth, hands, extraParts); } public static List<SkinnedMeshRenderer> GetActiveBodyPartsRenderers(IBodyshapeLoader bodyshapeLoader, string bodyShapeId, IEnumerable<WearableItem> wearables) { HashSet<string> hiddenList = new HashSet<string>(); HashSet<string> usedCategories = new HashSet<string>(); foreach (WearableItem wearable in wearables) { usedCategories.Add(wearable.data.category); string[] hiddenByThisWearable = wearable.GetHidesList(bodyShapeId); if (hiddenByThisWearable != null) hiddenList.UnionWith(hiddenByThisWearable); } List<SkinnedMeshRenderer> result = new List<SkinnedMeshRenderer>(); if (!hiddenList.Contains(WearableLiterals.Categories.HEAD) && !usedCategories.Contains(WearableLiterals.Categories.HEAD)) result.Add(bodyshapeLoader.headRenderer); if (!hiddenList.Contains(WearableLiterals.Categories.UPPER_BODY) && !usedCategories.Contains(WearableLiterals.Categories.UPPER_BODY)) result.Add(bodyshapeLoader.upperBodyRenderer); if (!hiddenList.Contains(WearableLiterals.Categories.LOWER_BODY) && !usedCategories.Contains(WearableLiterals.Categories.LOWER_BODY)) result.Add(bodyshapeLoader.lowerBodyRenderer); if (!hiddenList.Contains(WearableLiterals.Categories.FEET) && !usedCategories.Contains(WearableLiterals.Categories.FEET)) result.Add(bodyshapeLoader.feetRenderer); if (!hiddenList.Contains(WearableLiterals.Categories.HANDS) && !usedCategories.Contains(WearableLiterals.Categories.HANDS)) result.Add(bodyshapeLoader.handsRenderer); // We dont want to hide new body parts that are not configured yet result.AddRange(bodyshapeLoader.extraRenderers); return result; } public static void SpawnAvatarLoadedParticles(Transform avatarContainer, GameObject particlePrefab) { if (!particlePrefab.TryGetComponent(out DestroyParticlesOnFinish _)) throw new Exception("A self destructive particles prefab is expected"); GameObject particles = Object.Instantiate(particlePrefab); particles.transform.position = avatarContainer.position + particlePrefab.transform.position; } } }
1
0.751849
1
0.751849
game-dev
MEDIA
0.864017
game-dev,graphics-rendering
0.924626
1
0.924626
ProjectIgnis/CardScripts
1,382
unofficial/c500000149.lua
--魂縛門 local s,id=GetID() function s.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) c:RegisterEffect(e1) local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(id,0)) e2:SetCategory(CATEGORY_DESTROY+CATEGORY_DAMAGE) e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F) e2:SetRange(LOCATION_SZONE) e2:SetCode(EVENT_SUMMON_SUCCESS) e2:SetCountLimit(1,0,EFFECT_COUNT_CODE_SINGLE) e2:SetTarget(s.tg) e2:SetOperation(s.op) c:RegisterEffect(e2) local e3=e2:Clone() e3:SetCode(EVENT_SPSUMMON_SUCCESS) c:RegisterEffect(e3) local e4=e2:Clone() e4:SetCode(EVENT_FLIP_SUMMON_SUCCESS) c:RegisterEffect(e4) end function s.filter(c,e,tp) local lp=Duel.GetLP(tp) return c:IsFaceup() and c:IsDestructable() and c:GetAttack()<=lp and (not e or c:IsRelateToEffect(e)) end function s.tg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return eg:IsExists(s.filter,1,nil,nil,tp) end local g=eg:Filter(s.filter,nil,nil,tp) Duel.SetTargetCard(eg) Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,#g,0,0) Duel.SetOperationInfo(0,CATEGORY_DAMAGE,nil,0,PLAYER_ALL,800) end function s.op(e,tp,eg,ep,ev,re,r,rp) local g=eg:Filter(s.filter,nil,e,tp) if #g>0 and Duel.Destroy(g,REASON_EFFECT)>0 then Duel.Damage(1-tp,800,REASON_EFFECT,true) Duel.Damage(tp,800,REASON_EFFECT,true) Duel.RDComplete() end end
1
0.809385
1
0.809385
game-dev
MEDIA
0.986091
game-dev
0.93812
1
0.93812
IAmBatby/LethalLevelLoader
5,888
LethalLevelLoader/Modules/ExtendedUnlockableItem/UnlockableItemManager.cs
using LethalFoundation; using Steamworks.Ugc; using System.Collections.Generic; using System.Linq; using Unity.Netcode; namespace LethalLevelLoader { public class UnlockableItemManager : ExtendedContentManager<ExtendedUnlockableItem, UnlockableItem> { protected override List<UnlockableItem> GetVanillaContent() => OriginalContent.UnlockableItems; protected override ExtendedUnlockableItem ExtendVanillaContent(UnlockableItem content) => ExtendedUnlockableItem.Create(content); protected override void PatchGame() { DebugHelper.Log(GetType().Name + " Patching Game!", DebugType.User); StartOfRound.unlockablesList.unlockables = [.. ExtendedContents.Select(u => u.UnlockableItem)]; for (int i = 0; i < ExtendedContents.Count; i++) { ExtendedContents[i].SetGameID(i); Refs.Keywords.Buy.TryAdd(ExtendedContents[i].BuyKeyword, ExtendedContents[i].BuyNode); Refs.Keywords.Info.TryAdd(ExtendedContents[i].BuyKeyword, ExtendedContents[i].BuyInfoNode); } } protected override void UnpatchGame() { DebugHelper.Log(GetType().Name + " Unpatching Game!", DebugType.User); } protected override (bool result, string log) ValidateExtendedContent(ExtendedUnlockableItem content) { UnlockableItem unlock = content.Content; if (unlock.unlockableType == 0 && unlock.suitMaterial == null) return (false, "Unlockable Suit Is Missing Suit Material"); else if (unlock.unlockableType == 1 && !unlock.alreadyUnlocked) { if (unlock.prefabObject == null) return (false, "Unlockable Item Prefab Was Null Or Empty"); else if (!unlock.prefabObject.TryGetComponent(out NetworkObject _)) return (false, "Unlockable Item Prefab Is Missing NetworkObject Component"); else if (!unlock.prefabObject.TryGetComponent(out AutoParentToShip _)) return (false, "Unlockable Item Prefab Is Missing AutoParentToShip Component"); } return (true, string.Empty); } protected override void PopulateContentTerminalData(ExtendedUnlockableItem content) { TerminalKeyword keyword = null; TerminalNode buyNode = null; TerminalNode buyConfirmNode = null; TerminalNode infoNode = null; if (content.UnlockableItem.shopSelectionNode != null) { buyNode = content.UnlockableItem.shopSelectionNode; buyConfirmNode = buyNode?.terminalOptions[1].result; if (Keywords.Buy.compatibleNouns.TryGet(buyNode, out TerminalKeyword noun)) keyword = noun; if (Keywords.Info.compatibleNouns.TryGet(keyword, out TerminalNode node)) infoNode = node; } else { string sanitisedName = content.UnlockableItem.unlockableName.StripSpecialCharacters().Sanitized(); keyword = TerminalManager.CreateNewTerminalKeyword(sanitisedName + "Keyword", sanitisedName, Keywords.Buy); buyNode = TerminalManager.CreateNewTerminalNode(sanitisedName + "Buy"); buyNode.itemCost = content.ItemCost; buyNode.isConfirmationNode = false; buyNode.overrideOptions = true; buyNode.clearPreviousText = true; buyNode.maxCharactersToType = 15; buyNode.creatureName = content.UnlockableItem.unlockableName; if (!string.IsNullOrEmpty(content.OverrideBuyNodeDescription)) buyNode.displayText = content.OverrideBuyNodeDescription; else { buyNode.displayText = $"You have requested to order the {buyNode.creatureName}."; buyNode.displayText += "\n Total cost of item: [totalCost]."; buyNode.displayText += "\n" + "\n" + "Please CONFIRM or DENY." + "\n" + "\n"; } buyConfirmNode = TerminalManager.CreateNewTerminalNode(sanitisedName + "BuyConfirm"); buyConfirmNode.itemCost = content.ItemCost; buyConfirmNode.isConfirmationNode = true; buyConfirmNode.clearPreviousText = true; buyConfirmNode.buyUnlockable = true; buyConfirmNode.maxCharactersToType = 35; buyConfirmNode.playSyncedClip = 0; buyConfirmNode.creatureName = content.UnlockableItem.unlockableName; if (!string.IsNullOrEmpty(content.OverrideBuyConfirmNodeDescription)) buyConfirmNode.displayText = content.OverrideBuyConfirmNodeDescription; else { buyConfirmNode.displayText = $"Ordered the {buyConfirmNode.creatureName}! "; buyConfirmNode.displayText += "Your new balance is [playerCredits]"; } infoNode = TerminalManager.CreateNewTerminalNode(sanitisedName + "Info"); infoNode.clearPreviousText = true; infoNode.maxCharactersToType = 35; infoNode.creatureName = content.UnlockableItem.unlockableName; infoNode.displayText = content.OverrideInfoNodeDescription; buyNode.AddNoun(Keywords.Confirm, buyConfirmNode); buyNode.AddNoun(Keywords.Deny, Nodes.CancelBuy); } content.BuyKeyword = keyword; content.UnlockableItem.shopSelectionNode = buyNode; content.BuyNode = buyNode; content.BuyConfirmNode = buyConfirmNode; content.BuyInfoNode = infoNode; } } }
1
0.829497
1
0.829497
game-dev
MEDIA
0.803916
game-dev
0.766699
1
0.766699
goonstation/goonstation
4,888
code/modules/telescience/teleport_jammer.dm
TYPEINFO(/obj/machinery/telejam) mats = 9 /obj/machinery/telejam name = "teleportation jammer" desc = "Generates a force field interferes with teleportation devices." icon = 'icons/obj/shield_gen.dmi' icon_state = "meteor_gen" density = 1 opacity = 0 anchored = UNANCHORED var/obj/item/cell/PCEL = null var/coveropen = 0 var/active = 0 var/range = 3 var/image/display_active = null var/image/display_battery = null var/image/display_panel = null var/battery_level = 3 var/sound/sound_on = 'sound/effects/shielddown.ogg' var/sound/sound_off = 'sound/effects/shielddown2.ogg' var/sound/sound_battwarning = 'sound/machines/pod_alarm.ogg' New() PCEL = new /obj/item/cell/supercell(src) PCEL.charge = PCEL.maxcharge src.display_active = image('icons/obj/shield_gen.dmi', "") src.display_battery = image('icons/obj/shield_gen.dmi', "") src.display_panel = image('icons/obj/shield_gen.dmi', "") ..() disposing() turn_off() if (PCEL) PCEL.dispose() PCEL = null display_active = null display_battery = null sound_on = null sound_off = null sound_battwarning = null REMOVE_ATOM_PROPERTY(src, PROP_ATOM_TELEPORT_JAMMER, src) ..() get_desc(dist, mob/user) . = ..() if(user.client) var/charge_percentage = 0 if (PCEL?.charge > 0 && PCEL.maxcharge > 0) charge_percentage = round((PCEL.charge/PCEL.maxcharge)*100) . += "It has [PCEL.charge]/[PCEL.maxcharge] ([charge_percentage]%) battery power left." . += "The jammer's range is [src.range] units of distance." . += "The unit will consume [5 * src.range] power a second." else . += "It seems to be missing a usable battery." process() if (src.active) if(!PCEL) turn_off() return PCEL.use(5 * src.range) var/charge_percentage = 0 var/current_battery_level = 0 if (PCEL?.charge > 0 && PCEL.maxcharge > 0) charge_percentage = round((PCEL.charge/PCEL.maxcharge)*100) switch(charge_percentage) if (75 to 100) current_battery_level = 3 if (35 to 74) current_battery_level = 2 else current_battery_level = 1 if (current_battery_level != src.battery_level) src.battery_level = current_battery_level src.build_icon() if (src.battery_level == 1) playsound(src.loc, src.sound_battwarning, 50, 1) src.visible_message(SPAN_ALERT("<b>[src] emits a low battery alarm!</b>")) if (PCEL.charge < 0) src.visible_message("<b>[src]</b> runs out of power and shuts down.") src.turn_off() return attack_hand(mob/user) if (src.coveropen && src.PCEL) src.PCEL.set_loc(src.loc) src.PCEL = null boutput(user, "You remove the power cell.") else if (src.active) turn_off() src.visible_message("<b>[user.name]</b> powers down the [src].") else if (PCEL) if (PCEL.charge > 0) turn_on() src.visible_message("<b>[user.name]</b> powers up the [src].") else boutput(user, "[src]'s battery light flickers briefly.") else boutput(user, "Nothing happens.") build_icon() attackby(obj/item/W, mob/user) if (isscrewingtool(W)) src.coveropen = !src.coveropen src.visible_message("<b>[user.name]</b> [src.coveropen ? "opens" : "closes"] [src]'s cell cover.") if (istype(W,/obj/item/cell/) && src.coveropen && !src.PCEL) user.drop_item() W.set_loc(src) src.PCEL = W boutput(user, "You insert the power cell.") else ..() build_icon() attack_ai(mob/user as mob) return attack_hand(user) proc/build_icon() src.overlays = null if (src.coveropen) if (istype(src.PCEL,/obj/item/cell/)) src.display_panel.icon_state = "panel-batt" else src.display_panel.icon_state = "panel-nobatt" src.overlays += src.display_panel if (src.active) src.display_active.icon_state = "on" src.overlays += src.display_active if (istype(src.PCEL,/obj/item/cell)) var/charge_percentage = null if (PCEL.charge > 0 && PCEL.maxcharge > 0) charge_percentage = round((PCEL.charge/PCEL.maxcharge)*100) switch(charge_percentage) if (75 to 100) src.display_battery.icon_state = "batt-3" if (35 to 74) src.display_battery.icon_state = "batt-2" else src.display_battery.icon_state = "batt-1" else src.display_battery.icon_state = "batt-3" src.overlays += src.display_battery proc/turn_on() if (!PCEL) return if (PCEL.charge < 0) return src.anchored = ANCHORED src.active = 1 APPLY_ATOM_PROPERTY(src, PROP_ATOM_TELEPORT_JAMMER, src, src.range) playsound(src.loc, src.sound_on, 50, 1) build_icon() proc/turn_off() src.anchored = UNANCHORED src.active = 0 REMOVE_ATOM_PROPERTY(src, PROP_ATOM_TELEPORT_JAMMER, src) playsound(src.loc, src.sound_off, 50, 1) build_icon() Exited(Obj, newloc) . = ..() if(Obj == src.PCEL) src.PCEL = null active New() ..() turn_on()
1
0.975908
1
0.975908
game-dev
MEDIA
0.853591
game-dev
0.961536
1
0.961536
ringtailsoftware/zoridor
4,480
src/main.zig
const std = @import("std"); const Display = @import("display.zig").Display; const clock = @import("clock.zig"); const config = @import("config.zig"); const GameState = @import("gamestate.zig").GameState; const Move = @import("gamestate.zig").Move; const UiAgent = @import("ui.zig").UiAgent; const UiAgentHuman = @import("uiagenthuman.zig").UiAgentHuman; const UiAgentMachine = @import("uiagentmachine.zig").UiAgentMachine; const drawGame = @import("ui.zig").drawGame; const emitMoves = @import("ui.zig").emitMoves; const GameRecord = @import("record.zig").GameRecord; const buildopts = @import("buildopts"); pub fn main() !void { var exitReq = false; // default to human vs machine config.players[0] = try UiAgent.make("human"); config.players[1] = try UiAgent.make("machine"); config.parseCommandLine() catch { std.process.exit(1); }; clock.initTime(); // loop for terminal while (!exitReq) { var display = try Display.init(); defer display.destroy(); const sz = try Display.getSize(); if (config.mini) { if (sz.width < 80 or sz.height < 24) { std.debug.print("Display too small, must be 80x24 or larger\r\n", .{}); return; } } else { if (sz.width < 80 or sz.height < 29) { std.debug.print("Display too small, must be 80x29 or larger\r\n", .{}); return; } } display.cls(); try display.paint(); var timeout: i32 = 0; // default to not pausing, let machine agents run fast var turnN: usize = 0; var gameOver = false; var lastMoves: [config.NUM_PAWNS]Move = undefined; var gs = GameState.init(); var pi: usize = 0; // whose turn is it if (config.b64GameStart) |b64s| { // setup initial gamestate from provided b64 string const rec = try GameRecord.initFromBase64(std.heap.page_allocator, b64s); gs = try rec.toGameState(true); } try config.players[pi].selectMoveInteractive(&gs, pi); var gameRecord = try GameRecord.init(std.heap.page_allocator); defer gameRecord.deinit(); while (!gameOver) { const next = try display.getEvent(timeout); try config.players[pi].process(&gs, pi); if (try config.players[pi].handleEvent(next, &gs, pi)) { timeout = 100; // increase timeout if events being used for interaction } if (config.players[pi].getCompletedMove()) |move| { // apply the move try gs.applyMove(pi, move); try gameRecord.append(move.move); lastMoves[pi] = move.move; if (pi == config.NUM_PAWNS - 1) { // final player to take turn try emitMoves(turnN, lastMoves); turnN += 1; } if (gs.hasWon(pi)) { config.wins[pi] += 1; gameOver = true; } // select next player to make a move pi = (pi + 1) % config.NUM_PAWNS; try config.players[pi].selectMoveInteractive(&gs, pi); } switch (next) { .key => |k| switch (k) { .char => |c| switch (c) { 'q' => { exitReq = true; break; }, else => {}, }, else => {}, }, else => {}, } display.cls(); try drawGame(&display, &gs, pi); try config.players[pi].paint(&display); try display.paint(); } if (!config.playForever) { exitReq = true; // end terminal display and print game summary display.destroy(); const writer = std.io.getStdOut().writer(); const glend = try gameRecord.printGlendenningAlloc(std.heap.page_allocator); defer std.heap.page_allocator.free(glend); _ = try writer.print("{s}\n", .{glend}); const b64 = try gameRecord.toStringBase64Alloc(std.heap.page_allocator); defer std.heap.page_allocator.free(b64); _ = try writer.print("{s}\n", .{b64}); } } }
1
0.612624
1
0.612624
game-dev
MEDIA
0.560433
game-dev
0.871953
1
0.871953
kodecocodes/met-materials
2,796
26-gpu-driven-rendering/projects/challenge/GPUDriven/GPUDriven/Animation/TransformComponent.swift
///// Copyright (c) 2023 Kodeco Inc. /// /// Permission is hereby granted, free of charge, to any person obtaining a copy /// of this software and associated documentation files (the "Software"), to deal /// in the Software without restriction, including without limitation the rights /// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell /// copies of the Software, and to permit persons to whom the Software is /// furnished to do so, subject to the following conditions: /// /// The above copyright notice and this permission notice shall be included in /// all copies or substantial portions of the Software. /// /// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish, /// distribute, sublicense, create a derivative work, and/or sell copies of the /// Software in any work that is designed, intended, or marketed for pedagogical or /// instructional purposes related to programming, coding, application development, /// or information technology. Permission for such use, copying, modification, /// merger, publication, distribution, sublicensing, creation of derivative works, /// or sale is expressly withheld. /// /// This project and source code may use libraries or frameworks that are /// released under various Open-Source licenses. Use of those libraries and /// frameworks are governed by their own individual licenses. /// /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR /// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, /// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE /// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER /// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, /// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN /// THE SOFTWARE. import ModelIO struct TransformComponent { let keyTransforms: [float4x4] let duration: Float var currentTransform: float4x4 = .identity init( object: MDLObject, startTime: TimeInterval, endTime: TimeInterval ) { duration = Float(endTime - startTime) let timeStride = stride( from: startTime, to: endTime, by: 1 / TimeInterval(GameController.fps)) keyTransforms = Array(timeStride).map { time in MDLTransform.globalTransform( with: object, atTime: time) } } mutating func getCurrentTransform(at time: Float) { guard duration > 0 else { currentTransform = .identity return } let frame = Int(fmod(time, duration) * Float(GameController.fps)) if frame < keyTransforms.count { currentTransform = keyTransforms[frame] } else { currentTransform = keyTransforms.last ?? .identity } } }
1
0.907282
1
0.907282
game-dev
MEDIA
0.533506
game-dev
0.631584
1
0.631584
long-war-2/lwotc
4,365
LongWarOfTheChosen/Src/LW_PerkPack_Integrated/Classes/X2Effect_MeristLayeredArmorV2.uc
//--------------------------------------------------------------------------------------- // FILE: X2Effect_MeristLayeredArmorV2.uc // AUTHOR: Merist // PURPOSE: Reduce all incoming damage for the rest of the turn // whenever a unit takes damage above a percent of their // max HP in a single turn //--------------------------------------------------------------------------------------- class X2Effect_MeristLayeredArmorV2 extends X2Effect_MeristLayeredArmor; // Damage cap per round: // var float PrcDamageCap; // var bool bUseDifficulySettings; // var array<float> PrcDamageCapDifficulty; // var protectedwrite array<AdditionalDamageCapInfo> AdditionalPrcDamageCap; // Not used for this effect // var private string strFlyoverMessage; // var private string strFlyoverIcon; // Damage reduction IN PERCENTS above the cap var float FinalPrcDamageModifier; var array<float> FinalPrcDamageModifierDifficulty; function float GetFinalDamageModifierPercent(XComGameState_Unit Unit) { local float DamageModifier; if (bUseDifficulySettings) DamageModifier = FinalPrcDamageModifierDifficulty[`TACTICALDIFFICULTYSETTING]; else DamageModifier = FinalPrcDamageModifier; return DamageModifier; } function float GetPostDefaultDefendingDamageModifier_CH( XComGameState_Effect EffectState, XComGameState_Unit SourceUnit, XComGameState_Unit TargetUnit, XComGameState_Ability AbilityState, const out EffectAppliedData ApplyEffectParameters, float WeaponDamage, X2Effect_ApplyWeaponDamage WeaponDamageEffect, XComGameState NewGameState) { local X2AbilityTemplate AbilityTemplate; local X2AbilityMultiTarget_BurstFire BurstFire; local int MaxHealth; local int DamageTaken; local int MaxDamage; local int DamageOverflow; local int BurstFullDamage; local int BurstFireOverflow; local UnitValue UValue; if (class'XComGameStateContext_Ability'.static.IsHitResultHit(ApplyEffectParameters.AbilityResultContext.HitResult)) { if (WeaponDamage > 0) { if (TargetUnit != none) { MaxHealth = TargetUnit.GetMaxStat(eStat_HP); TargetUnit.GetUnitValue('DamageThisTurn', UValue); DamageTaken = int(UValue.fValue); MaxDamage = Max(Round(MaxHealth * GetPercentDamageCap(TargetUnit) / 100) - DamageTaken, 0); `LOG("==================================================", bLog, 'X2Effect_MeristLayeredArmorV2'); `LOG("Remaining damage: " $ MaxDamage, bLog, 'X2Effect_MeristLayeredArmorV2'); AbilityTemplate = AbilityState.GetMyTemplate(); BurstFire = X2AbilityMultiTarget_BurstFire(AbilityTemplate.AbilityMultiTargetStyle); if (BurstFire == none || !bCapBurstFire) { DamageOverflow = Clamp(WeaponDamage - MaxDamage, 0, WeaponDamage); `LOG("Overflow: " $ DamageOverflow, bLog, 'X2Effect_MeristLayeredArmorV2'); return -1 * Round(DamageOverflow * GetFinalDamageModifierPercent(TargetUnit) / 100); } else { // Each of Burst Fire shots applies at the same time, // causing Layred Armor to not apply. // Use full Burst Fire damage to figure out how much of each shot should be ignored BurstFullDamage = WeaponDamage * (1 + BurstFire.NumExtraShots); DamageOverflow = Clamp(BurstFullDamage - MaxDamage, 0, BurstFullDamage); `LOG("Expected Burst Fire DamageOverflow: " $ DamageOverflow, bLog, 'X2Effect_MeristLayeredArmorV2'); BurstFireOverflow = Clamp(Round(DamageOverflow / (1 + BurstFire.NumExtraShots)), 0, WeaponDamage); `LOG("DamageOverflow per shot: " $ BurstFireOverflow, bLog, 'X2Effect_MeristLayeredArmorV2'); return -1 * Round(BurstFireOverflow * GetFinalDamageModifierPercent(TargetUnit) / 100); } `LOG("==================================================", bLog, 'X2Effect_MeristLayeredArmorV2'); } } } return 0; } defaultproperties { bDisplayInSpecialDamageMessageUI = true; }
1
0.875645
1
0.875645
game-dev
MEDIA
0.976634
game-dev
0.862724
1
0.862724
KazWolfe/XIVDeck
2,904
SDPlugin/src/button/buttons/ActionButton.ts
import { BaseButton } from "../BaseButton"; import { KeyDownEvent, WillAppearEvent } from "@rweich/streamdeck-events/dist/Events/Received/Plugin"; import plugin from "../../plugin"; import { FFXIVAction, StateMessage } from "../../link/ffxivplugin/GameTypes"; import { FFXIVApi } from "../../link/ffxivplugin/FFXIVApi"; import { DidReceiveSettingsEvent } from "@rweich/streamdeck-events/dist/Events/Received"; export type ActionButtonSettings = { actionType?: string, actionId?: number, actionName?: string, cache?: FFXIVAction payload?: unknown } export class ActionButton extends BaseButton { settings?: ActionButtonSettings; useGameIcon: boolean = true; constructor(event: WillAppearEvent) { super(event.context); this._xivEventListeners.add(plugin.xivPluginLink.on("_ready", this.render.bind(this))); this._xivEventListeners.add(plugin.xivPluginLink.on("stateUpdate", this.stateUpdate.bind(this))); this._sdEventListeners.set("keyDown", this.onKeyDown.bind(this)); this.onReceivedSettings(event); } async onReceivedSettings(event: DidReceiveSettingsEvent | WillAppearEvent): Promise<void> { this.settings = event.settings as ActionButtonSettings; await this.render(); } async onKeyDown(event: KeyDownEvent): Promise<void> { if (this.settings?.actionType == undefined || this.settings?.actionId == undefined) { throw Error("Not action type/ID was defined for this button!"); } await FFXIVApi.Action.executeAction(this.settings.actionType, this.settings.actionId, this.settings.payload); } async render() { if (!this.useGameIcon) { this.setImage(""); return; } if (!plugin.xivPluginLink.isReady()) { return; } if (this.settings?.actionType == undefined || this.settings?.actionId == undefined) { return; } // Migration again. // TODO: Remove eventually. if (this.settings.actionType == "Collection") { this.settings.actionType = "McGuffin"; this.setSettings(this.settings); } let actionInfo = await FFXIVApi.Action.getAction(this.settings.actionType, this.settings.actionId); this.setImage(await FFXIVApi.getIcon(actionInfo.iconId)); // Populate cache if it isn't already set if (this.settings.cache == null) { this.settings.cache = actionInfo; // ToDo: Remove this migration eventually this.settings.actionName = undefined; console.log("MIGRATION PERFORMED!!"); this.setSettings(this.settings); } } private stateUpdate(message: StateMessage) { if (this.settings?.actionType == "GearSet" && message.type == "GearSet") { this.render(); } } }
1
0.947332
1
0.947332
game-dev
MEDIA
0.91214
game-dev
0.982857
1
0.982857
crownengine/crown
2,784
3rdparty/bullet3/src/BulletCollision/CollisionShapes/btSphereShape.h
/* 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. */ #ifndef BT_SPHERE_MINKOWSKI_H #define BT_SPHERE_MINKOWSKI_H #include "btConvexInternalShape.h" #include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h" // for the types ///The btSphereShape implements an implicit sphere, centered around a local origin with radius. ATTRIBUTE_ALIGNED16(class) btSphereShape : public btConvexInternalShape { public: BT_DECLARE_ALIGNED_ALLOCATOR(); btSphereShape(btScalar radius) : btConvexInternalShape() { m_shapeType = SPHERE_SHAPE_PROXYTYPE; m_localScaling.setValue(1.0, 1.0, 1.0); m_implicitShapeDimensions.setZero(); m_implicitShapeDimensions.x = (radius); m_collisionMargin = radius; m_padding = 0; } virtual btVector3 localGetSupportingVertex(const btVector3& vec) const; virtual btVector3 localGetSupportingVertexWithoutMargin(const btVector3& vec) const; //notice that the vectors should be unit length virtual void batchedUnitVectorGetSupportingVertexWithoutMargin(const btVector3* vectors, btVector3* supportVerticesOut, int numVectors) const; virtual void calculateLocalInertia(btScalar mass, btVector3 & inertia) const; virtual void getAabb(const btTransform& t, btVector3& aabbMin, btVector3& aabbMax) const; btScalar getRadius() const { return m_implicitShapeDimensions.x * m_localScaling.x; } void setUnscaledRadius(btScalar radius) { m_implicitShapeDimensions.x = (radius); btConvexInternalShape::setMargin(radius); } //debugging virtual const char* getName() const { return "SPHERE"; } virtual void setMargin(btScalar margin) { btConvexInternalShape::setMargin(margin); } virtual btScalar getMargin() const { //to improve gjk behaviour, use radius+margin as the full margin, so never get into the penetration case //this means, non-uniform scaling is not supported anymore return getRadius(); } }; #endif //BT_SPHERE_MINKOWSKI_H
1
0.849553
1
0.849553
game-dev
MEDIA
0.994106
game-dev
0.886461
1
0.886461
mandarine3ds/mandarine
2,515
src/android/app/src/main/java/io/github/mandarine3ds/mandarine/utils/EmulationMenuSettings.kt
// Copyright 2025 Citra Project / Mandarine Project // Licensed under GPLv2 or any later version // Refer to the license.txt file included. package io.github.mandarine3ds.mandarine.utils import androidx.drawerlayout.widget.DrawerLayout import androidx.preference.PreferenceManager import io.github.mandarine3ds.mandarine.MandarineApplication object EmulationMenuSettings { private val preferences = PreferenceManager.getDefaultSharedPreferences(MandarineApplication.appContext) var joystickRelCenter: Boolean get() = preferences.getBoolean("EmulationMenuSettings_JoystickRelCenter", true) set(value) { preferences.edit() .putBoolean("EmulationMenuSettings_JoystickRelCenter", value) .apply() } var dpadSlide: Boolean get() = preferences.getBoolean("EmulationMenuSettings_DpadSlideEnable", true) set(value) { preferences.edit() .putBoolean("EmulationMenuSettings_DpadSlideEnable", value) .apply() } var showStatsOvelray: Boolean get() = preferences.getBoolean("EmulationMenuSettings_showStatsOvelray", false) set(value) { preferences.edit() .putBoolean("EmulationMenuSettings_showStatsOvelray", value) .apply() } var hapticFeedback: Boolean get() = preferences.getBoolean("EmulationMenuSettings_HapticFeedback", true) set(value) { preferences.edit() .putBoolean("EmulationMenuSettings_HapticFeedback", value) .apply() } var swapScreens: Boolean get() = preferences.getBoolean("EmulationMenuSettings_SwapScreens", false) set(value) { preferences.edit() .putBoolean("EmulationMenuSettings_SwapScreens", value) .apply() } var showOverlay: Boolean get() = preferences.getBoolean("EmulationMenuSettings_ShowOverlay", true) set(value) { preferences.edit() .putBoolean("EmulationMenuSettings_ShowOverlay", value) .apply() } var drawerLockMode: Int get() = preferences.getInt( "EmulationMenuSettings_DrawerLockMode", DrawerLayout.LOCK_MODE_LOCKED_CLOSED ) set(value) { preferences.edit() .putInt("EmulationMenuSettings_DrawerLockMode", value) .apply() } }
1
0.631567
1
0.631567
game-dev
MEDIA
0.294343
game-dev
0.555963
1
0.555963
FabricMC/fabric
3,536
fabric-registry-sync-v0/src/main/java/net/fabricmc/fabric/impl/registry/sync/DynamicRegistriesImpl.java
/* * Copyright (c) 2016, 2017, 2018, 2019 FabricMC * * 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 net.fabricmc.fabric.impl.registry.sync; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.Set; import com.mojang.serialization.Codec; import org.jetbrains.annotations.Unmodifiable; import net.minecraft.registry.Registry; import net.minecraft.registry.RegistryKey; import net.minecraft.registry.RegistryLoader; import net.minecraft.registry.SerializableRegistries; import net.fabricmc.fabric.api.event.registry.DynamicRegistries; public final class DynamicRegistriesImpl { private static final List<RegistryLoader.Entry<?>> DYNAMIC_REGISTRIES = new ArrayList<>(RegistryLoader.DYNAMIC_REGISTRIES); public static final Set<RegistryKey<?>> FABRIC_DYNAMIC_REGISTRY_KEYS = new HashSet<>(); public static final Set<RegistryKey<? extends Registry<?>>> DYNAMIC_REGISTRY_KEYS = new HashSet<>(); public static final Set<RegistryKey<? extends Registry<?>>> SKIP_EMPTY_SYNC_REGISTRIES = new HashSet<>(); static { for (RegistryLoader.Entry<?> vanillaEntry : RegistryLoader.DYNAMIC_REGISTRIES) { DYNAMIC_REGISTRY_KEYS.add(vanillaEntry.key()); } } private DynamicRegistriesImpl() { } public static @Unmodifiable List<RegistryLoader.Entry<?>> getDynamicRegistries() { return List.copyOf(DYNAMIC_REGISTRIES); } public static <T> RegistryLoader.Entry<T> register(RegistryKey<? extends Registry<T>> key, Codec<T> serverCodec) { Objects.requireNonNull(key, "Registry key cannot be null"); Objects.requireNonNull(serverCodec, "Server codec cannot be null"); if (!DYNAMIC_REGISTRY_KEYS.add(key)) { throw new IllegalArgumentException("Dynamic registry " + key + " has already been registered!"); } var entry = new RegistryLoader.Entry<>(key, serverCodec, false); DYNAMIC_REGISTRIES.add(entry); FABRIC_DYNAMIC_REGISTRY_KEYS.add(key); return entry; } public static <T> void addSyncedRegistry(RegistryKey<? extends Registry<T>> key, Codec<T> clientCodec, DynamicRegistries.SyncOption... options) { Objects.requireNonNull(key, "Registry key cannot be null"); Objects.requireNonNull(clientCodec, "Client codec cannot be null"); Objects.requireNonNull(options, "Options cannot be null"); if (!(RegistryLoader.SYNCED_REGISTRIES instanceof ArrayList<RegistryLoader.Entry<?>>)) { RegistryLoader.SYNCED_REGISTRIES = new ArrayList<>(RegistryLoader.SYNCED_REGISTRIES); } RegistryLoader.SYNCED_REGISTRIES.add(new RegistryLoader.Entry<>(key, clientCodec, false)); if (!(SerializableRegistries.SYNCED_REGISTRIES instanceof HashSet<RegistryKey<? extends Registry<?>>>)) { SerializableRegistries.SYNCED_REGISTRIES = new HashSet<>(SerializableRegistries.SYNCED_REGISTRIES); } SerializableRegistries.SYNCED_REGISTRIES.add(key); for (DynamicRegistries.SyncOption option : options) { if (option == DynamicRegistries.SyncOption.SKIP_WHEN_EMPTY) { SKIP_EMPTY_SYNC_REGISTRIES.add(key); } } } }
1
0.708045
1
0.708045
game-dev
MEDIA
0.428685
game-dev
0.827328
1
0.827328
followingthefasciaplane/source-engine-diff-check
2,784
misc/public/demo_polish/demo_polish_recorder.h
//===== Copyright 1996-2008, Valve Corporation, All rights reserved. ======// // // Purpose: // //===========================================================================// #ifndef C_DEMO_POLISH_RECORDER_H #define C_DEMO_POLISH_RECORDER_H #ifdef _WIN32 #pragma once #endif //------------------------------------------------------------------------------------------------------------------------ class CUserCmd; class CIntDemoPolishFile; class CFinalDemoPolishFile; class FinalPolishElementData; class CPathManager; class CBonePolishData; class CIntDemoPolishFile; class CAnimDataFile; class CDemoPolishFile; class CUserInputDataFile; class CHeadingDataFile; class CHeadingData; class CBoneAccessor; //------------------------------------------------------------------------------------------------------------------------ // // Records to intermediate polish files. These files are then analyzed (on shutdown) // and converted into a final set of polish data, which can be interpreted during demo // playback. // class CDemoPolishRecorder { public: static CDemoPolishRecorder& Instance(); bool Init( char const* pDemoBaseFileName ); bool Shutdown(); void Think( float flTime ); void RecordAnimData( int iPlayerEntIndex, CStudioHdr* pStudioHdr, float fCycle, matrix3x4_t const& renderTransform, Vector pos[], Quaternion q[], int iBoneMask, CBoneAccessor const& boneAccessor ); void RecordStandingHeadingChange( int iPlayerEntIndex, float flCurrentHeading, float flGoalHeading ); void RecordJumpEvent( int iPlayerEntIndex ); void RecordUserInput( CUserCmd const* pUserCmd ); public: bool m_bInit; private: CDemoPolishRecorder(); ~CDemoPolishRecorder(); enum EFileType { kAnim, kEvents, kNumFileTypes }; bool InitLocalFileSystem(); bool SetupFiles(); bool WriteHeader(); bool InitUserInputFile(); bool SetupFile( char const* pFilenameStem, int iPlayerIndex, int iEntIndex, CUtlVector< CDemoPolishFile* >& vFiles, int iFileType ); bool ClosePolishFiles( EFileType iFileType ); CDemoPolishFile* GetFileForPlayerAt( int iPlayerEntIndex, EFileType iFileType ); float GetTime() const; void FlushQueuedTurnEvents(); char m_szDemoBaseFileName[MAX_PATH]; CUtlVector< CDemoPolishFile* >* m_vFileLists[kNumFileTypes]; CUtlVector< CDemoPolishFile* > m_vAnimFiles; CUtlVector< CDemoPolishFile* > m_vEventFiles; CUtlVector< int > m_vPlayerEntIndexMap; // Maps from player lookup index to entity index CUtlVector< CHeadingData* > m_standingHeadingEvents; // In-place turn events that will be filtered out before written to disk CPathManager* m_pPathManager; }; //------------------------------------------------------------------------------------------------------------------------ #endif // C_DEMO_POLISH_RECORDER_H
1
0.864412
1
0.864412
game-dev
MEDIA
0.435319
game-dev
0.797574
1
0.797574
pphdsny/Leetcode-Java
1,035
src/pp/arithmetic/leetcode/_206_ReverseList_2.java
package pp.arithmetic.leetcode; import pp.arithmetic.Util; import pp.arithmetic.model.ListNode; /** * Created by wangpeng on 2018/7/9. * 递归实现 */ public class _206_ReverseList_2 { public static void main(String[] args) { ListNode listNode1 = Util.generateListNodeBySize(10); Util.printListNode(listNode1); ListNode retList = reverseList(listNode1); Util.printListNode(retList); } /** * 递归实现 * * @param listNode * @return */ private static ListNode reverseList(ListNode listNode) { if (listNode.next == null) { return listNode; } ListNode dummy = new ListNode(0); generate(dummy, listNode); return dummy.next; } private static void generate(ListNode dummp, ListNode node) { if (node == null) { return; } ListNode temp = dummp.next; ListNode next = node.next; dummp.next = node; node.next = temp; generate(dummp, next); } }
1
0.554442
1
0.554442
game-dev
MEDIA
0.226123
game-dev
0.862835
1
0.862835
Logicalshift/flowbetween
1,120
animation/src/traits/edit/motion_edit.rs
use super::element_id::*; use super::super::motion::*; use super::super::time_path::*; use smallvec::*; /// /// Represents an edit that creates a motion description on a layer /// #[derive(Clone, PartialEq, Debug)] pub enum MotionEdit { /// Creates a new motion with this element ID /// /// A new motion is created with a type of `None`, an origin at 0,0 and an empty time curve Create, /// Deletes the motion with this ID Delete, /// Sets the type of this motion SetType(MotionType), /// Changes the origin point for this motion SetOrigin(f32, f32), /// Sets the time curve for this motion SetPath(TimeCurve), } impl MotionEdit { /// /// Retrieves the element IDs used by this edit /// #[inline] pub fn used_element_ids(&self) -> SmallVec<[ElementId; 4]> { use MotionEdit::*; match self { Create => smallvec![], Delete => smallvec![], SetType(_) => smallvec![], SetOrigin(_, _) => smallvec![], SetPath(_) => smallvec![], } } }
1
0.922903
1
0.922903
game-dev
MEDIA
0.781752
game-dev
0.672558
1
0.672558
tb771/backwater_bassin
3,889
fish_swarm.py
import pygame import random import math FISH_COLOR = (218, 165, 32) # Gold-orange FISH_TURN_CHANCE = 0.02 IDLE_CHANCE = 0.01 TAIL_WAG_SPEED = 0.15 # Define fisherman zone globally for reuse FISHERMAN_ZONE = pygame.Rect(325, 500, 150, 100) class Fish: def __init__(self, screen_width, screen_height): self.screen_width = screen_width self.screen_height = screen_height self.size = random.choice([10, 14, 18]) while True: self.x = random.randint(0, screen_width) self.y = random.randint(0, screen_height) fish_rect = pygame.Rect(self.x, self.y, self.size, self.size // 2) if not fish_rect.colliderect(FISHERMAN_ZONE): break base_speed = max(0.4, 10 / self.size) self.dx = random.choice([-1, 1]) * random.uniform(base_speed * 0.5, base_speed) self.dy = random.choice([-1, 1]) * random.uniform(base_speed * 0.5, base_speed) self.tail_phase = random.uniform(0, 2 * math.pi) self.idle_frames = 0 def update(self): if self.idle_frames > 0: self.idle_frames -= 1 return self.x += self.dx self.y += self.dy # Bounce at edges if self.x < 0 or self.x > self.screen_width: self.dx *= -1 if self.y < 0 or self.y > self.screen_height: self.dy *= -1 # Avoid fisherman zone during movement fish_rect = pygame.Rect(self.x, self.y, self.size, self.size // 2) if fish_rect.colliderect(FISHERMAN_ZONE): # Reverse direction and steer away if self.x < FISHERMAN_ZONE.centerx: self.dx = -abs(self.dx) else: self.dx = abs(self.dx) if self.y < FISHERMAN_ZONE.centery: self.dy = -abs(self.dy) else: self.dy = abs(self.dy) self.x += self.dx * 2 self.y += self.dy * 2 # Random turning if random.random() < FISH_TURN_CHANCE: base_speed = max(0.4, 10 / self.size) self.dx = random.choice([-1, 1]) * random.uniform(base_speed * 0.5, base_speed) self.dy = random.choice([-1, 1]) * random.uniform(base_speed * 0.5, base_speed) # Occasional idle if random.random() < IDLE_CHANCE: self.idle_frames = random.randint(60, 120) self.tail_phase += TAIL_WAG_SPEED def draw(self, screen): body_width = self.size body_height = self.size // 2 body_rect = pygame.Rect(int(self.x), int(self.y), body_width, body_height) pygame.draw.ellipse(screen, FISH_COLOR, body_rect) # Tail wag animation tail_length = body_width // 2 tail_angle = math.sin(self.tail_phase) * 5 tail_center_x = self.x tail_center_y = self.y + body_height // 2 tail_points = [ (tail_center_x, tail_center_y), (tail_center_x - tail_length, tail_center_y - tail_length // 2), (tail_center_x - tail_length, tail_center_y + tail_length // 2), ] rotated_tail = [] for px, py in tail_points: dx = px - tail_center_x dy = py - tail_center_y angle = math.radians(tail_angle) rx = dx * math.cos(angle) - dy * math.sin(angle) ry = dx * math.sin(angle) + dy * math.cos(angle) rotated_tail.append((tail_center_x + rx, tail_center_y + ry)) pygame.draw.polygon(screen, FISH_COLOR, rotated_tail) class FishSwarm: def __init__(self, count, screen_width, screen_height): self.fish_list = [Fish(screen_width, screen_height) for _ in range(count)] def update(self): for fish in self.fish_list: fish.update() def draw(self, screen): for fish in self.fish_list: fish.draw(screen)
1
0.876687
1
0.876687
game-dev
MEDIA
0.377776
game-dev
0.925153
1
0.925153
mahbarahona/tiles
14,306
src/actors/player.actor.ts
import { Actor, Animation, Collider, CollisionContact, CollisionType, Engine, Input, Side, SpriteSheet, range, vec, } from "excalibur"; import { assetManager } from "../managers/asset.manager"; import { eventBus, gameManager } from "../managers/game.manager"; import { ACTOR_TYPE, PLAYER_STATE, SCENE_EVENTS, SCENE_STATE, PLAYER_TOOLS, } from "../models"; import { uiManager } from "../managers/ui.manager"; import { SceneArea } from "./Areas/scene-area.actor"; const ANIM = { IDLE_FRONT: "IDLE_FRONT", IDLE_LEFT: "IDLE_LEFT", IDLE_RIGHT: "IDLE_RIGHT", IDLE_BACK: "IDLE_BACK", WALK_FRONT: "WALK_IDLE", WALK_BACK: "WALK_BACK", WALK_LEFT: "WALK_LEFT", WALK_RIGHT: "WALK_RIGHT", SHOVEL_FRONT: "SHOVEL_FRONT", SHOVEL_BACK: "SHOVEL_BACK", PICKAXE_LEFT: "PICKAXE_LEFT", PICKAXE_RIGHT: "PICKAXE_RIGHT", AXE_FRONT: "AXE_FRONT", AXE_BACK: "AXE_BACK", AXE_LEFT: "AXE_LEFT", AXE_RIGHT: "AXE_RIGHT", WATERING_CAN_FRONT: "WATERING_CAN_FRONT", WATERING_CAN_BACK: "WATERING_CAN_BACK", WATERING_CAN_LEFT: "WATERING_CAN_LEFT", WATERING_CAN_RIGHT: "WATERING_CAN_RIGHT", }; function get_animations() { // sprites const sprite_movements = SpriteSheet.fromImageSource({ image: assetManager.images.character, grid: { rows: 4, columns: 4, spriteWidth: 48, spriteHeight: 48, }, }); const sprite_actions = SpriteSheet.fromImageSource({ image: assetManager.images.character_actions, grid: { rows: 12, columns: 2, spriteWidth: 48, spriteHeight: 48, }, }); const anim_idle_front = Animation.fromSpriteSheet( sprite_movements, range(0, 1), 400 ); const anim_idle_back = Animation.fromSpriteSheet( sprite_movements, range(4, 5), 400 ); const anim_idle_left = Animation.fromSpriteSheet( sprite_movements, range(8, 9), 400 ); const anim_idle_right = Animation.fromSpriteSheet( sprite_movements, range(12, 13), 400 ); // movements const anim_walk_front = Animation.fromSpriteSheet( sprite_movements, range(0, 3), 200 ); const anim_walk_back = Animation.fromSpriteSheet( sprite_movements, range(4, 7), 200 ); const anim_walk_left = Animation.fromSpriteSheet( sprite_movements, range(8, 11), 200 ); const anim_walk_right = Animation.fromSpriteSheet( sprite_movements, range(12, 15), 200 ); //shovel const anim_shovel_front = Animation.fromSpriteSheet( sprite_actions, range(0, 1), 300 ); const anim_shovel_back = Animation.fromSpriteSheet( sprite_actions, range(2, 3), 300 ); // pickaxe const anim_pickaxe_left = Animation.fromSpriteSheet( sprite_actions, range(4, 5), 300 ); const anim_pickaxe_right = Animation.fromSpriteSheet( sprite_actions, range(6, 7), 300 ); //axe const anim_axe_front = Animation.fromSpriteSheet( sprite_actions, range(8, 9), 300 ); const anim_axe_back = Animation.fromSpriteSheet( sprite_actions, range(10, 11), 300 ); const anim_axe_left = Animation.fromSpriteSheet( sprite_actions, range(12, 13), 300 ); const anim_axe_right = Animation.fromSpriteSheet( sprite_actions, range(14, 15), 300 ); // watering const anim_watering_can_front = Animation.fromSpriteSheet( sprite_actions, range(16, 17), 300 ); const anim_watering_can_back = Animation.fromSpriteSheet( sprite_actions, range(18, 19), 300 ); const anim_watering_can_left = Animation.fromSpriteSheet( sprite_actions, range(20, 21), 300 ); const anim_watering_can_right = Animation.fromSpriteSheet( sprite_actions, range(22, 23), 300 ); return { anim_idle_front, anim_idle_back, anim_idle_left, anim_idle_right, // anim_walk_front, anim_walk_back, anim_walk_left, anim_walk_right, // anim_shovel_front, anim_shovel_back, // anim_pickaxe_left, anim_pickaxe_right, // anim_axe_front, anim_axe_back, anim_axe_left, anim_axe_right, // anim_watering_can_front, anim_watering_can_back, anim_watering_can_left, anim_watering_can_right, }; } enum FACING { FRONT = "FRONT", BACK = "BACK", LEFT = "LEFT", RIGHT = "RIGHT", } export class Player extends Actor { current_anim: any; private facing!: FACING; private map_bounds: any; public in_action = false; public nearToNPC: any; public current_tool = "axe" || "wateringcan" || "axe" || "pickaxe" || "shovel" || ""; public player_state!: PLAYER_STATE; constructor({ x, y, map_bounds }: any) { super({ name: "Player", x, y, z: 5, width: 16, height: 16, collisionType: CollisionType.Active, }); this.facing = FACING.FRONT; this.scale = vec(0.8, 0.8); this.map_bounds = map_bounds; this.current_tool = "wateringcan"; this.set_state(PLAYER_STATE.IDLE); this.scale = vec(0.8, 0.8); } onInitialize(): void { this.set_animations(); this.set_anim(ANIM.IDLE_FRONT); } onPreUpdate(engine: Engine): void { const keyboard = engine.input.keyboard; const pressed_space = keyboard.wasPressed(Input.Keys.Space); const pressed_escape = keyboard.wasPressed(Input.Keys.Esc); // const pressed_enter = keyboard.wasReleased(Input.Keys.Enter); const pressed_menu = keyboard.wasReleased(Input.Keys.M); const released_change_tool = keyboard.wasReleased(Input.Keys.E) || keyboard.wasReleased(Input.Keys.T) || keyboard.wasReleased(Input.Keys.F); this.vel.x = 0; this.vel.y = 0; switch (this.player_state) { case PLAYER_STATE.TALKING: if (pressed_space) { gameManager.continue_talking(); } break; case PLAYER_STATE.IDLE: if (pressed_space) { if (this.nearToNPC) { this.set_state(PLAYER_STATE.TALKING); gameManager.start_talk(this.nearToNPC); return; } // const prev_anim = this.current_anim; // this.in_action = true; // switch (this.current_tool) { // case 'axe': // switch (this.facing) { // case FACING.BACK: // this.set_anim(ANIM.AXE_BACK); // break; // case FACING.FRONT: // this.set_anim(ANIM.AXE_FRONT); // break; // case FACING.LEFT: // this.set_anim(ANIM.AXE_LEFT); // break; // case FACING.RIGHT: // this.set_anim(ANIM.AXE_RIGHT); // break; // } // setTimeout(() => { // this.set_anim(prev_anim); // this.in_action = false; // }, 300 * 4); // break; // case 'wateringcan': // switch (this.facing) { // case FACING.BACK: // this.set_anim(ANIM.WATERING_CAN_BACK); // break; // case FACING.FRONT: // this.set_anim(ANIM.WATERING_CAN_FRONT); // break; // case FACING.LEFT: // this.set_anim(ANIM.WATERING_CAN_LEFT); // break; // case FACING.RIGHT: // this.set_anim(ANIM.WATERING_CAN_RIGHT); // break; // } // setTimeout(() => { // this.set_anim(prev_anim); // this.in_action = false; // }, 300 * 4); // break; // } } if (pressed_menu) { this.set_state(PLAYER_STATE.MENU); gameManager.scene_state.next(SCENE_STATE.MENU); return; } this.update_movement(engine); if (released_change_tool) { let nextIndex = PLAYER_TOOLS.indexOf(this.current_tool) + 1; if (!PLAYER_TOOLS[nextIndex]) { nextIndex = 0; } const next = PLAYER_TOOLS[nextIndex]; this.current_tool = next; eventBus.emit(SCENE_EVENTS.SWITCH_TOOL, this.current_tool); } break; case PLAYER_STATE.MENU: if (pressed_escape) { uiManager.cancel_menu(); return; } if (pressed_menu) { this.set_state(PLAYER_STATE.IDLE); gameManager.scene_state.next(SCENE_STATE.PLAYING); return; } if (pressed_space) { uiManager.open_submenu(); return; } // const isLEFT = // keyboard.wasReleased(Input.Keys.Left) || // keyboard.wasReleased(Input.Keys.A); // const isRIGHT = // keyboard.wasReleased(Input.Keys.Right) || // keyboard.wasReleased(Input.Keys.D); const isUP = keyboard.wasReleased(Input.Keys.Up) || keyboard.wasReleased(Input.Keys.W); const isDOWN = keyboard.wasReleased(Input.Keys.Down) || keyboard.wasReleased(Input.Keys.S); if (isUP) { uiManager.menu_item_up(); } else if (isDOWN) { uiManager.menu_item_down(); } break; case PLAYER_STATE.IN_ACTION: this.vel.x = 0; this.vel.y = 0; break; } } // COLLISIONS onPreCollisionResolve( _self: Collider, _other: Collider, _side: Side, _contact: CollisionContact ): void { const other: any = _other; switch (other.owner.name) { case ACTOR_TYPE.SCENE_NEXT: const area: SceneArea | any = other.owner; if (area.activated) { area.activated = false; gameManager.go_to(area.toScene); } break; case ACTOR_TYPE.NPC: this.nearToNPC = other.owner; break; } } onCollisionEnd(_self: Collider, other: Collider): void { switch (other.owner.name) { case ACTOR_TYPE.SCENE_NEXT: const area: SceneArea | any = other.owner; area.activated = true; break; } } // private set_anim(new_anim: any) { this.current_anim = new_anim; this.graphics.use(new_anim); } private set_animations() { const animations = get_animations(); this.graphics.add(ANIM.IDLE_FRONT, animations.anim_idle_front); this.graphics.add(ANIM.IDLE_BACK, animations.anim_idle_back); this.graphics.add(ANIM.IDLE_LEFT, animations.anim_idle_left); this.graphics.add(ANIM.IDLE_RIGHT, animations.anim_idle_right); // movements this.graphics.add(ANIM.WALK_FRONT, animations.anim_walk_front); this.graphics.add(ANIM.WALK_BACK, animations.anim_walk_back); this.graphics.add(ANIM.WALK_LEFT, animations.anim_walk_left); this.graphics.add(ANIM.WALK_RIGHT, animations.anim_walk_right); // shovel this.graphics.add(ANIM.SHOVEL_FRONT, animations.anim_shovel_front); this.graphics.add(ANIM.SHOVEL_BACK, animations.anim_shovel_back); // pickaxe this.graphics.add(ANIM.PICKAXE_LEFT, animations.anim_pickaxe_left); this.graphics.add(ANIM.PICKAXE_RIGHT, animations.anim_pickaxe_right); // axe this.graphics.add(ANIM.AXE_FRONT, animations.anim_axe_front); this.graphics.add(ANIM.AXE_BACK, animations.anim_axe_back); this.graphics.add(ANIM.AXE_LEFT, animations.anim_axe_left); this.graphics.add(ANIM.AXE_RIGHT, animations.anim_axe_right); // watering can this.graphics.add( ANIM.WATERING_CAN_FRONT, animations.anim_watering_can_front ); this.graphics.add( ANIM.WATERING_CAN_BACK, animations.anim_watering_can_back ); this.graphics.add( ANIM.WATERING_CAN_LEFT, animations.anim_watering_can_left ); this.graphics.add( ANIM.WATERING_CAN_RIGHT, animations.anim_watering_can_right ); } private update_movement(engine: Engine) { const keyboard = engine.input.keyboard; const WALKING_SPEED = 100; // 160 const isLEFT = keyboard.isHeld(Input.Keys.Left) || keyboard.isHeld(Input.Keys.A); const isRIGHT = keyboard.isHeld(Input.Keys.Right) || keyboard.isHeld(Input.Keys.D); const isUP = keyboard.isHeld(Input.Keys.Up) || keyboard.isHeld(Input.Keys.W); const isDOWN = keyboard.isHeld(Input.Keys.Down) || keyboard.isHeld(Input.Keys.S); const hit_bounds = { left: this.pos.x < 0 + this.width / 2, top: this.pos.y < 0 + this.height / 2, right: this.pos.x > this.map_bounds.right - this.width / 2, bottom: this.pos.y > this.map_bounds.bottom - this.height / 2, }; this.vel.x = 0; this.vel.y = 0; if (isLEFT && !hit_bounds.left) { this.vel.x = -1; this.facing = FACING.LEFT; } if (isRIGHT && !hit_bounds.right) { this.vel.x = 1; this.facing = FACING.RIGHT; } if (isUP && !hit_bounds.top) { this.vel.y = -1; this.facing = FACING.BACK; } if (isDOWN && !hit_bounds.bottom) { this.vel.y = 1; this.facing = FACING.FRONT; } // Normalize walking speed if (this.vel.x !== 0 || this.vel.y !== 0) { this.nearToNPC = false; this.vel = this.vel.normalize(); this.vel.x = this.vel.x * WALKING_SPEED; this.vel.y = this.vel.y * WALKING_SPEED; switch (this.facing) { case FACING.LEFT: this.graphics.use(ANIM.WALK_LEFT); break; case FACING.RIGHT: this.graphics.use(ANIM.WALK_RIGHT); break; case FACING.FRONT: this.graphics.use(ANIM.WALK_FRONT); break; case FACING.BACK: this.graphics.use(ANIM.WALK_BACK); break; } } else { switch (this.facing) { case FACING.LEFT: this.graphics.use(ANIM.IDLE_LEFT); break; case FACING.RIGHT: this.graphics.use(ANIM.IDLE_RIGHT); break; case FACING.FRONT: this.graphics.use(ANIM.IDLE_FRONT); break; case FACING.BACK: this.graphics.use(ANIM.IDLE_BACK); break; } } } set_state(new_state: PLAYER_STATE) { this.player_state = new_state; gameManager.player = this; } }
1
0.906424
1
0.906424
game-dev
MEDIA
0.98739
game-dev
0.97091
1
0.97091
CalamityTeam/CalamityModPublic
4,378
Projectiles/Rogue/TotalityFlask.cs
using Microsoft.Xna.Framework; using Terraria; using Terraria.Audio; using Terraria.ID; using Terraria.ModLoader; namespace CalamityMod.Projectiles.Rogue { public class TotalityFlask : ModProjectile, ILocalizedModType { public new string LocalizationCategory => "Projectiles.Rogue"; public override string Texture => "CalamityMod/Items/Weapons/Rogue/TotalityBreakers"; public override void SetDefaults() { Projectile.width = 20; Projectile.height = 20; Projectile.friendly = true; Projectile.penetrate = 1; Projectile.aiStyle = ProjAIStyleID.MolotovCocktail; Projectile.timeLeft = 180; Projectile.DamageType = RogueDamageClass.Instance; } public override void AI() { if (Projectile.Calamity().stealthStrike) { if (Projectile.timeLeft % 20 == 0) { if (Projectile.owner == Main.myPlayer) { Projectile.NewProjectile(Projectile.GetSource_FromThis(), Projectile.Center, Vector2.Zero, ModContent.ProjectileType<TotalityTar>(), (int)(Projectile.damage * 0.6), Projectile.knockBack, Projectile.owner, 0f, 0f); } } } Vector2 spinningpoint = new Vector2(4f, -8f); float rotation = Projectile.rotation; if (Projectile.direction == -1) spinningpoint.X = -4f; Vector2 vector2 = spinningpoint.RotatedBy((double)rotation, new Vector2()); for (int index1 = 0; index1 < 1; ++index1) { int index2 = Dust.NewDust(Projectile.Center + vector2 - Vector2.One * 5f, 4, 4, DustID.Torch, 0.0f, 0.0f, 0, new Color(), 1f); Main.dust[index2].scale = 1.5f; Main.dust[index2].noGravity = true; Main.dust[index2].velocity = Main.dust[index2].velocity * 0.25f + Vector2.Normalize(vector2) * 1f; Main.dust[index2].velocity = Main.dust[index2].velocity.RotatedBy(-MathHelper.PiOver2 * (double)Projectile.direction, new Vector2()); } } public override void OnKill(int timeLeft) { if (Projectile.owner != Main.myPlayer) return; //glass-pot break sound SoundEngine.PlaySound(SoundID.Shatter, Projectile.position); int meltdown = Projectile.NewProjectile(Projectile.GetSource_FromThis(), Projectile.Center, Vector2.Zero, ModContent.ProjectileType<TotalMeltdown>(), Projectile.damage, Projectile.knockBack, Projectile.owner, 0f, 0f); Main.projectile[meltdown].Center = Projectile.Center; //makes it centered because it's not without this Vector2 vector2 = new Vector2(20f, 20f); for (int d = 0; d < 5; ++d) Dust.NewDust(Projectile.Center - vector2 / 2f, (int)vector2.X, (int)vector2.Y, DustID.SpookyWood, 0.0f, 0.0f, 0, Color.Red, 1f); for (int d = 0; d < 10; ++d) { int index2 = Dust.NewDust(Projectile.Center - vector2 / 2f, (int)vector2.X, (int)vector2.Y, DustID.Smoke, 0.0f, 0.0f, 100, new Color(), 1.5f); Dust dust = Main.dust[index2]; dust.velocity *= 1.4f; } for (int d = 0; d < 20; ++d) { int index2 = Dust.NewDust(Projectile.Center - vector2 / 2f, (int)vector2.X, (int)vector2.Y, DustID.Torch, 0.0f, 0.0f, 100, new Color(), 2.5f); Dust dust1 = Main.dust[index2]; dust1.noGravity = true; dust1.velocity *= 5f; int index3 = Dust.NewDust(Projectile.Center - vector2 / 2f, (int)vector2.X, (int)vector2.Y, DustID.Torch, 0.0f, 0.0f, 100, new Color(), 1.5f); Dust dust2 = Main.dust[index3]; dust2.velocity *= 3f; } int tarAmt = Main.rand.Next(2, 4); for (int t = 0; t < tarAmt; t++) { Vector2 velocity = CalamityUtils.RandomVelocity(100f, 70f, 100f); Projectile.NewProjectile(Projectile.GetSource_FromThis(), Projectile.Center, velocity, ModContent.ProjectileType<TotalityTar>(), (int)(Projectile.damage * 0.3), 0f, Main.myPlayer, 0f, 0f); } } } }
1
0.791212
1
0.791212
game-dev
MEDIA
0.991303
game-dev
0.890225
1
0.890225
squell/id3
2,569
getid3.cpp
#include <vector> #include <cstdio> #include <cstring> #include "getid3.h" /* copyright (c) 2004, 2005 squell <info@squell.net> use, modification, copying and distribution of this software is permitted under the conditions described in the file 'COPYING'. */ using namespace std; using namespace charset; using tag::read::ID3; using tag::ID3field; namespace { inline ID3v1 readtag(const char *fn) { struct ID3v1 tag = { { 0, } }; if( FILE* f = fopen(fn, "rb") ) { fseek(f, -128, SEEK_END) == 0 && fread(&tag, 1, 128, f) == 128 && memcmp(tag.TAG, "TAG", 3) == 0 || (tag.TAG[0] = 0); fclose(f); } return tag; } } ID3::ID3(const char* fn) : tag(readtag(fn)) { } ID3::value_string ID3::operator[](ID3field field) const { char buf[31] = { 0, }; // enough to hold largest ID3 field+1 if(*tag.TAG) switch( field ) { case title: strncpy(buf, tag.title, sizeof tag.title); break; case artist: strncpy(buf, tag.artist, sizeof tag.artist); break; case album: strncpy(buf, tag.album, sizeof tag.album); break; case year: strncpy(buf, tag.year, sizeof tag.year); break; case cmnt: strncpy(buf, tag.cmnt, sizeof tag.cmnt + (tag.zero?2:0)); break; case track: if(tag.zero == 0 && tag.track != 0) sprintf(buf, "%u", tag.track & 0xFF); break; case genre: if(tag.genre < ID3v1_numgenres) return conv<latin1>(ID3v1_genre[tag.genre]); break; case FIELD_MAX: char ver[] = "ID3v1._"; ver[6] = '0'+!tag.zero; return ver; } return conv<latin1>(buf); } /* ====================================================== */ namespace { // don't display in the order of of ID3field using namespace tag; const char* desc[] = { "Title", "Artist", "Album", "Track", "Year", "Genre", "Comment" }; const ID3field tab[] = { title, artist, album, track, year, genre, cmnt }; } ID3::array ID3::listing() const { array vec; vec.push_back( array::value_type("ID3", tag.zero? "1.0" : "1.1") ); for(int x = 0; x < FIELD_MAX; ++x) { conv<> s = operator[](tab[x]); if(!s.empty()) vec.push_back( array::value_type(desc[x], s) ); } return vec; }
1
0.950142
1
0.950142
game-dev
MEDIA
0.207899
game-dev
0.983839
1
0.983839
AndnixSH/Free-Shared-Mod-Codes-Collections
2,068
Unity DLL modding (C#)/Dragon Knight: Plane.cs
//Game: Dragon Knight: Plane //Version: 1.0.0 //APK: https://apkpure.com/dragon-knight%EF%BC%9A-plane/com.morenewgame.lqs //Calling Mod menu //mscorelib //Locale public static string GetText(string msg) { ModMenu.StartMenu(); return msg; } //Class: HurtHelper public static AmountInfo CalcHurt(UnitSkill skill, UnitObject unitDef, int hurtPct, int hurtAdd) { DelegateBridge _Hotfix0_CalcHurt = HurtHelper.__Hotfix0_CalcHurt; if (_Hotfix0_CalcHurt != null) { return _Hotfix0_CalcHurt.__Gen_Delegate_Imp324(skill, unitDef, hurtPct, hurtAdd); } AmountType type = (skill.CfgSkill.type != 1) ? AmountType.SkillDamage : AmountType.AttackDamage; AmountInfo result = new AmountInfo(type, 0, true, false); if (unitDef.State.HasState(UnitStateKey.God)) { result.isGod = true; return result; } UnitObject caster = skill.Caster; int val; if (caster is PlayerObject) { val = caster.Prop.GetProp("Atk") * Menu.AtkMul; //Attack multiplier } else { val = caster.Prop.GetProp("Atk") / Menu.DefMul; //Defense multiplier } MnDouble skillHurt = HurtHelper.GetSkillHurt(caster, unitDef, skill, hurtPct, hurtAdd); MnDouble critPct = HurtHelper.GetCritPct(caster, unitDef, skill, ref result); MnDouble rhs = 1 + unitDef.Prop.GetProp("AmlifyDamage") / 10000; MnDouble rhs2 = 1 + GlobalParamConfig.hurtFloatRatio * (Singleton<StageRandom>.Instance.NextDouble() * 2 - 1); int num = Math.Max((int)(skillHurt * critPct * rhs * rhs2), val); if (caster is PlayerObject) { num = Math.Max((int)(skillHurt * critPct * rhs * rhs2), val) * Menu.AtkMul; } else { num = Math.Max((int)(skillHurt * critPct * rhs * rhs2), val) / Menu.DefMul; } if (UnitHelper.IsSkillArmorNotMatch(skill, caster, unitDef, true, true)) { result.isSkillArmorNotMatch = true; num = (int)((float)num * GlobalParamConfig.armorAntiPct); } if (BattleLogicModule.Instance.IsPVP) { num = (int)(GlobalParamConfig.damageCoefficient * num); } result.amount = num; result.skillHurtPct = hurtPct; HurtHelper.CalcCombatVerify(unitDef, caster, ref result); return result; }
1
0.896421
1
0.896421
game-dev
MEDIA
0.987115
game-dev
0.93245
1
0.93245
Fluorohydride/ygopro-scripts
1,674
c66235877.lua
--デス・デーモン・ドラゴン function c66235877.initial_effect(c) --fusion material c:EnableReviveLimit() aux.AddFusionProcCode2(c,93220472,16475472,false,false) --disable local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_FIELD) e1:SetCode(EFFECT_DISABLE) e1:SetRange(LOCATION_MZONE) e1:SetTargetRange(LOCATION_MZONE,LOCATION_MZONE) e1:SetTarget(c66235877.distg) c:RegisterEffect(e1) --disable effect local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS) e2:SetCode(EVENT_CHAIN_SOLVING) e2:SetRange(LOCATION_MZONE) e2:SetOperation(c66235877.disop) c:RegisterEffect(e2) --disable local e3=Effect.CreateEffect(c) e3:SetType(EFFECT_TYPE_FIELD) e3:SetCode(EFFECT_DISABLE) e3:SetRange(LOCATION_MZONE) e3:SetTargetRange(LOCATION_SZONE,LOCATION_SZONE) e3:SetTarget(c66235877.distg2) c:RegisterEffect(e3) --self destroy local e4=Effect.CreateEffect(c) e4:SetType(EFFECT_TYPE_FIELD) e4:SetCode(EFFECT_SELF_DESTROY) e4:SetRange(LOCATION_MZONE) e4:SetTargetRange(LOCATION_SZONE,LOCATION_SZONE) e4:SetTarget(c66235877.distg2) c:RegisterEffect(e4) end function c66235877.distg(e,c) return c:IsType(TYPE_FLIP) end function c66235877.disop(e,tp,eg,ep,ev,re,r,rp) if re:IsActiveType(TYPE_FLIP) then Duel.NegateEffect(ev) end if e:GetHandler():IsRelateToEffect(re) and re:IsActiveType(TYPE_TRAP) and re:IsHasProperty(EFFECT_FLAG_CARD_TARGET) then local g=Duel.GetChainInfo(ev,CHAININFO_TARGET_CARDS) if g and g:IsContains(e:GetHandler()) then Duel.NegateEffect(ev) end end end function c66235877.distg2(e,c) return c:GetCardTargetCount()>0 and c:IsType(TYPE_TRAP) and c:GetCardTarget():IsContains(e:GetHandler()) end
1
0.681496
1
0.681496
game-dev
MEDIA
0.977593
game-dev
0.54577
1
0.54577
bitburner-official/bitburner-src
13,468
src/BitNode/ui/BitnodeMultipliersDescription.tsx
import React from "react"; import { Box, Collapse, ListItemButton, ListItemText, Paper, Table, TableBody, Tooltip, Typography, } from "@mui/material"; import ExpandLess from "@mui/icons-material/ExpandLess"; import ExpandMore from "@mui/icons-material/ExpandMore"; import { Player } from "@player"; import { SpecialServers } from "../../Server/data/SpecialServers"; import { Settings } from "../../Settings/Settings"; import { StatsRow } from "../../ui/React/StatsRow"; import { defaultMultipliers, getBitNodeMultipliers } from "../BitNode"; import { BitNodeMultipliers } from "../BitNodeMultipliers"; import { PartialRecord, getRecordEntries } from "../../Types/Record"; import { canAccessBitNodeFeature } from "../BitNodeUtils"; interface IProps { n: number; level?: number; hideMultsIfCannotAccessFeature: boolean; } export function BitNodeMultiplierDescription({ n, level, hideMultsIfCannotAccessFeature }: IProps): React.ReactElement { const [open, setOpen] = React.useState(false); if (n === 1) { return <></>; } return ( <Box component={Paper} sx={{ mt: 1, p: 1 }}> <ListItemButton disableGutters onClick={() => setOpen((old) => !old)} sx={{ padding: "4px 8px" }}> <ListItemText primary={<Typography variant="h6">Bitnode Multipliers</Typography>} /> {open ? <ExpandLess color="primary" /> : <ExpandMore color="primary" />} </ListItemButton> <Collapse in={open}> <BitNodeMultipliersDisplay n={n} level={level} hideMultsIfCannotAccessFeature={hideMultsIfCannotAccessFeature} /> </Collapse> </Box> ); } export const BitNodeMultipliersDisplay = ({ n, level, hideMultsIfCannotAccessFeature }: IProps): React.ReactElement => { // If a level argument has been provided, use that as the multiplier level // If not, then we have to assume that we want the next level up from the // current node's source file, so we get the min of that, the SF's max level, // or if it's BN12, ∞ const maxSfLevel = n === 12 ? Number.MAX_VALUE : 3; const mults = getBitNodeMultipliers(n, level ?? Math.min(Player.activeSourceFileLvl(n) + 1, maxSfLevel)); return ( <Box sx={{ columnCount: 2, columnGap: 1, mb: n === 1 ? 0 : -2 }}> <GeneralMults n={n} mults={mults} /> <SkillMults n={n} mults={mults} /> <FactionMults n={n} mults={mults} /> <AugmentationMults n={n} mults={mults} /> <HackingMults n={n} mults={mults} /> <PurchasedServersMults n={n} mults={mults} /> <StockMults n={n} mults={mults} /> <CrimeMults n={n} mults={mults} /> <InfiltrationMults n={n} mults={mults} /> <CompanyMults n={n} mults={mults} /> <GangMults n={n} mults={mults} hideMultsIfCannotAccessFeature={hideMultsIfCannotAccessFeature} /> <CorporationMults n={n} mults={mults} hideMultsIfCannotAccessFeature={hideMultsIfCannotAccessFeature} /> <BladeburnerMults n={n} mults={mults} hideMultsIfCannotAccessFeature={hideMultsIfCannotAccessFeature} /> <StanekMults n={n} mults={mults} hideMultsIfCannotAccessFeature={hideMultsIfCannotAccessFeature} /> <GoMults n={n} mults={mults} /> </Box> ); }; type IBNMultRows = PartialRecord< keyof BitNodeMultipliers, { name: string; content?: string; color?: string; tooltipText?: string; } >; interface IBNMultTableProps { sectionName: string; rowData: IBNMultRows; mults: BitNodeMultipliers; } const BNMultTable = (props: IBNMultTableProps): React.ReactElement => { const rowsArray = getRecordEntries(props.rowData) .filter(([key]) => props.mults[key] !== defaultMultipliers[key]) .map(([key, value]) => { const name = value.tooltipText ? ( <Tooltip title={<span>{value.tooltipText}</span>}> <span> {value.name} <sup>(*)</sup> </span> </Tooltip> ) : ( value.name ); return ( <StatsRow key={`${props.sectionName}-${value.name}`} name={name} data={{ content: value.content ?? `${(props.mults[key] * 100).toFixed(3)}%` }} color={value.color ?? Settings.theme.primary} /> ); }); return rowsArray.length > 0 ? ( <span style={{ display: "inline-block", width: "100%", marginBottom: "16px" }}> <Typography variant="h6">{props.sectionName}</Typography> <Table> <TableBody>{rowsArray}</TableBody> </Table> </span> ) : ( <></> ); }; interface IMultsProps { n: number; mults: BitNodeMultipliers; } interface IEndGameMultsProps extends IMultsProps { hideMultsIfCannotAccessFeature: boolean; } function GeneralMults({ mults }: IMultsProps): React.ReactElement { const rows: IBNMultRows = { WorldDaemonDifficulty: { name: `${SpecialServers.WorldDaemon} Difficulty` }, DaedalusAugsRequirement: { name: "Daedalus Augs Requirement", content: String(mults.DaedalusAugsRequirement), }, HacknetNodeMoney: { name: "Hacknet Production" }, CodingContractMoney: { name: "Coding Contract Reward" }, ClassGymExpGain: { name: "Class/Gym Exp" }, }; return <BNMultTable sectionName="General" rowData={rows} mults={mults} />; } function AugmentationMults({ mults }: IMultsProps): React.ReactElement { const rows: IBNMultRows = { AugmentationMoneyCost: { name: "Money Cost" }, AugmentationRepCost: { name: "Reputation Cost", color: Settings.theme.rep, }, }; return <BNMultTable sectionName="Augmentations" rowData={rows} mults={mults} />; } function CompanyMults({ mults }: IMultsProps): React.ReactElement { const rows: IBNMultRows = { CompanyWorkMoney: { name: "Work Money", color: Settings.theme.money, }, CompanyWorkRepGain: { name: "Work Reputation", color: Settings.theme.rep, }, CompanyWorkExpGain: { name: "Work Exp" }, }; return <BNMultTable sectionName="Company" rowData={rows} mults={mults} />; } function StockMults({ mults }: IMultsProps): React.ReactElement { const rows: IBNMultRows = { FourSigmaMarketDataCost: { name: "Market Data Cost" }, FourSigmaMarketDataApiCost: { name: "Market Data API Cost" }, }; return <BNMultTable sectionName="Stock Market" rowData={rows} mults={mults} />; } function FactionMults({ mults }: IMultsProps): React.ReactElement { const rows: IBNMultRows = { FavorToDonateToFaction: { name: "Favor to Donate" }, FactionWorkRepGain: { name: "Work Reputation", color: Settings.theme.rep, }, FactionWorkExpGain: { name: "Work Exp" }, FactionPassiveRepGain: { name: "Passive Rep", color: Settings.theme.rep, }, }; return <BNMultTable sectionName="Faction" rowData={rows} mults={mults} />; } function CrimeMults({ mults }: IMultsProps): React.ReactElement { const rows: IBNMultRows = { CrimeExpGain: { name: "Crime Exp", }, CrimeMoney: { name: "Crime Money", color: Settings.theme.money, }, CrimeSuccessRate: { name: "Crime Success Rate", }, }; return <BNMultTable sectionName="Crime" rowData={rows} mults={mults} />; } function SkillMults({ mults }: IMultsProps): React.ReactElement { const rows: IBNMultRows = { HackingLevelMultiplier: { name: "Hacking Level", color: Settings.theme.hack, }, StrengthLevelMultiplier: { name: "Strength Level", color: Settings.theme.combat, }, DefenseLevelMultiplier: { name: "Defense Level", color: Settings.theme.combat, }, DexterityLevelMultiplier: { name: "Dexterity Level", color: Settings.theme.combat, }, AgilityLevelMultiplier: { name: "Agility Level", color: Settings.theme.combat, }, CharismaLevelMultiplier: { name: "Charisma Level", color: Settings.theme.cha, }, }; return <BNMultTable sectionName="Skills" rowData={rows} mults={mults} />; } function HackingMults({ mults }: IMultsProps): React.ReactElement { const rows: IBNMultRows = { HackExpGain: { name: "Hacking Exp", color: Settings.theme.hack, }, HackingSpeedMultiplier: { name: "Hacking Speed", color: Settings.theme.hack, }, ServerGrowthRate: { name: "Server Growth Rate" }, ServerMaxMoney: { name: "Server Max Money", color: Settings.theme.money }, ServerStartingMoney: { name: "Server Starting Money", color: Settings.theme.money }, ServerStartingSecurity: { name: "Server Starting Security" }, ServerWeakenRate: { name: "Server Weaken Rate" }, ManualHackMoney: { name: "Money Gained From Manual Hack", color: Settings.theme.money, tooltipText: `Influences how much money the player actually gains when they hack a server via the terminal. This is different from "Stolen Money From Hack". When the player hacks a server via the terminal, the amount of money in that server is reduced, but they do not gain that same amount.`, }, ScriptHackMoney: { name: "Stolen Money From Hack", color: Settings.theme.money, tooltipText: "Influences how much money is stolen from a server when the player performs a hack against it.", }, ScriptHackMoneyGain: { name: "Money Gained From Script Hack", color: Settings.theme.money, tooltipText: `Influences how much money the player actually gains when a script hacks a server. This is different from "Stolen Money From Hack". When a script hacks a server, the amount of money in that server is reduced, but the player does not gain that same amount.`, }, }; return <BNMultTable sectionName="Hacking" rowData={rows} mults={mults} />; } function PurchasedServersMults({ mults }: IMultsProps): React.ReactElement { const rows: IBNMultRows = { PurchasedServerCost: { name: "Base Cost", content: mults.PurchasedServerCost.toFixed(3), }, PurchasedServerSoftcap: { name: "Softcap Cost", content: mults.PurchasedServerSoftcap.toFixed(3), }, PurchasedServerLimit: { name: "Server Limit" }, PurchasedServerMaxRam: { name: "Max RAM" }, HomeComputerRamCost: { name: "Home RAM Cost" }, }; return <BNMultTable sectionName="Purchased Servers" rowData={rows} mults={mults} />; } function InfiltrationMults({ mults }: IMultsProps): React.ReactElement { const rows: IBNMultRows = { InfiltrationMoney: { name: "Infiltration Money", color: Settings.theme.money, }, InfiltrationRep: { name: "Infiltration Reputation", color: Settings.theme.rep, }, }; return <BNMultTable sectionName="Infiltration" rowData={rows} mults={mults} />; } function BladeburnerMults({ mults, hideMultsIfCannotAccessFeature }: IEndGameMultsProps): React.ReactElement { if (!Player.canAccessBladeburner() && hideMultsIfCannotAccessFeature) { return <></>; } if (mults.BladeburnerRank === 0) { const rows: IBNMultRows = { BladeburnerRank: { name: "Disabled", content: "" }, }; return <BNMultTable sectionName="Bladeburner" rowData={rows} mults={mults} />; } const rows: IBNMultRows = { BladeburnerRank: { name: "Rank Gain" }, BladeburnerSkillCost: { name: "Skill Cost" }, }; return <BNMultTable sectionName="Bladeburner" rowData={rows} mults={mults} />; } function StanekMults({ mults, hideMultsIfCannotAccessFeature }: IEndGameMultsProps): React.ReactElement { if (!Player.canAccessCotMG() && hideMultsIfCannotAccessFeature) { return <></>; } const extraSize = mults.StaneksGiftExtraSize.toFixed(5); const rows: IBNMultRows = { StaneksGiftPowerMultiplier: { name: "Gift Power" }, StaneksGiftExtraSize: { name: "Base Size Modifier", content: `${mults.StaneksGiftExtraSize > defaultMultipliers.StaneksGiftExtraSize ? `+${extraSize}` : extraSize}`, }, }; return <BNMultTable sectionName="Stanek's Gift" rowData={rows} mults={mults} />; } function GangMults({ mults, hideMultsIfCannotAccessFeature }: IEndGameMultsProps): React.ReactElement { if (!canAccessBitNodeFeature(2) && hideMultsIfCannotAccessFeature) { return <></>; } const rows: IBNMultRows = { GangSoftcap: { name: "Gang Softcap", content: mults.GangSoftcap.toFixed(3), }, GangUniqueAugs: { name: "Unique Augmentations" }, }; return <BNMultTable sectionName="Gang" rowData={rows} mults={mults} />; } function CorporationMults({ mults, hideMultsIfCannotAccessFeature }: IEndGameMultsProps): React.ReactElement { if (!Player.canAccessCorporation() && hideMultsIfCannotAccessFeature) { return <></>; } if (mults.CorporationSoftcap < 0.15) { const rows: IBNMultRows = { CorporationSoftcap: { name: "Disabled", content: "", }, }; return <BNMultTable sectionName="Corporation" rowData={rows} mults={mults} />; } const rows: IBNMultRows = { CorporationSoftcap: { name: "Corporation Softcap", content: mults.CorporationSoftcap.toFixed(3), }, CorporationValuation: { name: "Valuation" }, CorporationDivisions: { name: "Division limit" }, }; return <BNMultTable sectionName="Corporation" rowData={rows} mults={mults} />; } function GoMults({ mults }: IMultsProps): React.ReactElement { const rows: IBNMultRows = { GoPower: { name: "IPvGO Node Power bonus" }, }; return <BNMultTable sectionName="IPvGO Subnet Takeover" rowData={rows} mults={mults} />; }
1
0.854981
1
0.854981
game-dev
MEDIA
0.454658
game-dev
0.837013
1
0.837013
canonical/ubuntu-desktop-provision
1,389
apps/ubuntu_bootstrap/lib/pages/autoinstall/autoinstall_model.dart
import 'package:flutter/foundation.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart'; import 'package:ubuntu_bootstrap/app/installer_model.dart'; import 'package:ubuntu_bootstrap/pages/loading/loading_provider.dart'; import 'package:ubuntu_bootstrap/ubuntu_bootstrap.dart'; part 'autoinstall_model.freezed.dart'; part 'autoinstall_model.g.dart'; enum AutoinstallType { none, direct, landscape, } @freezed class AutoinstallState with _$AutoinstallState { factory AutoinstallState({ required AutoinstallType type, }) = _AutoinstallState; } @Riverpod(keepAlive: true) class AutoinstallModel extends _$AutoinstallModel { late final _service = getService<AutoinstallService>(); @override AutoinstallState build() { return AutoinstallState(type: AutoinstallType.none); } void setType(AutoinstallType? type) { if (type == null) return; state = state.copyWith(type: type); } AutoinstallType? getType() { return state.type; } Future<void> restart() async { await _service.restartSubiquity(); ref.read(restartProvider.notifier).state++; ref.invalidate(loadingProvider); } Future<String> getFileContent() => _service.getFileContent(); bool get showLandscape => getService<InstallerService>().experimentalFeatures.contains('landscape'); }
1
0.730955
1
0.730955
game-dev
MEDIA
0.243525
game-dev
0.933399
1
0.933399
2004Scape/Server
7,989
data/src/scripts/areas/area_alkharid/scripts/shantay.rs2
[opnpc1,shantay] //guess based on osrs. Averaged about 100 talks between each drop. if(random(100) = 0) { mes("Something drops out of Shantay's pocket onto the floor."); mes("It looks like a piece of paper."); obj_add(npc_coord, thkebabinstructs, 1, ^lootdrop_duration); } if (%shantay_jail_progress = ^not_talked_to_shantay) { ~chatnpc("<p,neutral>Hello effendi, I am Shantay."); ~chatnpc("<p,neutral>I see you're new. Please read the billboard poster|before going into the desert. It'll give yer details on the|dangers you can face."); %shantay_jail_progress = ^talked_to_shantay; } else { ~chatnpc("<p,neutral>Hello again friend. Please read the billboard poster|before going into the desert. It'll give yer details on the|dangers you can face."); } @multi4("What is this place?", shantay_what_is_this_place, "Can I see what you have to sell please?", shantay_can_i_see_what_you_have_to_sell_please, "I must be going.", shantay_i_must_be_going, "I want to buy a shantay pass for 5 gold coins.", shantay_buy_shantay_pass); [opnpc3,shantay] if (map_members = ^false) { mes(^mes_members_store_owner); // guess return; } ~openshop_activenpc; [label,shantay_what_is_this_place] if (%shantay_jail_progress = ^put_in_shantay_jail) { %shantay_jail_progress = ^talked_to_shantay; ~chatnpc("<p,neutral>You should be in jail! Well, no doubt the authorities in|Port Sarim know what they're doing. But if you get|into any more trouble, you'll be stuck back in jail."); return; } ~chatplayer("<p,neutral>What is this place?"); ~chatnpc("<p,neutral>This is the pass of Shantay. I guard this area with my|men. I am responsible for keeping this pass open and|repaired."); ~chatnpc("<p,neutral>My men and I prevent outlaws from getting out of the|desert. And we stop the inexperienced from a dry death|in the sands. Which would you say you were?"); def_int $choice = ~p_choice3("I am definitely an outlaw, prepare to die!", 1, "I am a little inexperienced.", 2, "Er, neither, I'm an adventurer.", 3); if ($choice = 1) { ~chatplayer("<p,neutral>I am definitely an outlaw, prepare to die!"); ~chatnpc("<p,neutral>Ha, very funny....."); ~chatnpc("<p,neutral>Guards arrest <text_gender("him", "her")>!"); if_close; mes("The guards arrest you and place you in the jail."); p_delay(2); %shantay_jail_progress = ^put_in_shantay_jail; p_telejump(0_51_48_32_52); ~chatnpc("<p,neutral>You'll have to stay in there until you pay the fine of|five gold pieces. Do you want to pay now?"); @multi2("Yes, okay.", shantay_yes_okay_ill_pay_the_fine, "No thanks, you're not having my money.", shantay_no_thanks_youre_not_having_my_money); } if ($choice = 2) { ~chatplayer("<p,neutral>I am a little inexperienced."); ~chatnpc("<p,neutral>Can I recommend that you purchase a full waterskin|and a knife! These items will no doubt save your life. A|waterskin will keep water from evaporating in the desert."); ~chatnpc("<p,neutral>And a keen woodsman with a knife can extract the juice|from a cactus. Before you go into the desert, it's|advisable to wear desert clothes. It's very hot in the|desert and you'll surely cook if you wear armour."); ~chatnpc("<p,neutral>To keep the pass bandit free, we charge a small toll of|five gold pieces. You can buy a desert pass from me,|just ask me to open the shop. You can also use our|free banking services by clicking on the chest."); } if ($choice = 3) { ~chatplayer("<p,neutral>Er, neither, I'm an adventurer."); ~chatnpc("<p,neutral>Great, I have just the thing for the desert adventurer.|I sell desert clothes which will keep you cool in the heat|of the desert. I also sell waterskins so that you won't|die in the desert."); ~chatnpc("<p,neutral>A waterskin and a knife help you survive from the juice|of a cactus. Use the chest to store your items, we'll take|them to the bank. It's hot in the desert, you'll bake in|all that armour."); ~chatnpc("<p,neutral>To keep the pass open we ask for 5 gold pieces. And|we give you a Shantay Pass, just ask to see what I sell|to buy one."); } @multi3("Can I see what you have to sell please?", shantay_can_i_see_what_you_have_to_sell_please, "I must be going.", shantay_i_must_be_going, "Why do I have to pay to go into the desert?", shantay_pay_for_desert); [label,shantay_pay_for_desert] ~chatplayer("<p,neutral>Why do I have to pay to go into the desert?"); if_close; mes("Shantay opens his arms wide as if to embrace you."); p_delay(3); ~chatnpc("<p,neutral>Effendi, you insult me! I am not interested in making|a profit from you! I merely seek to cover my expenses|in keeping this pass open."); ~chatnpc("<p,neutral>There is repair work to carry out and also the men's|wages to consider. For the paltry sum of 5 Gold pieces,|I think we offer a great service."); @multi2("Can I see what you have to sell please?", shantay_can_i_see_what_you_have_to_sell_please, "I must be going.", shantay_i_must_be_going); [label,shantay_ill_pay_the_fine] ~chatplayer("<p,neutral>I'll pay the fine."); // comma is NOT a typo, its from osrs // Message(type = DIALOG, text = "Shantay|Okay then..., you'll need access to your bank.") ~chatnpc("<p,neutral>Okay then..., you'll need access to your bank."); @openbank; [label,shantay_no_thanks_youre_not_having_my_money] ~chatplayer("<p,neutral>No thanks, you're not having my money."); // https://storage.googleapis.com/tannerdino/images/rstransport13.gif ~chatnpc("<p,neutral>You have a choice.|You can either pay five gold pieces or...|You can be transported to a maximum security prison|in Port Sarim."); ~chatnpc("<p,neutral>Will you pay the five gold pieces?"); def_int $choice = ~p_choice2("Yes, okay.", 1, "No, do your worst!", 2); if ($choice = 1) { @shantay_ill_pay_the_fine; } ~chatnpc("<p,neutral>You are to be transported to a maximum security|prison in Port Sarim. I hope you've learnt an important|lesson from this."); @shantay_send_player_to_port_sarim; [label,shantay_yes_okay_ill_pay_the_fine] ~chatplayer("<p,neutral>Yes, okay."); ~chatnpc("<p,neutral>Good, I see that you have come to your senses."); if (inv_total(inv, coins) < 5) { ~chatnpc("<p,neutral>You don't have that kind of cash on you I see."); if (inv_total(bank, coins) >= 5) { ~chatnpc("<p,neutral>But perhaps you have some in your bank? Or would you prefer the maximum security prison in Port Sarim."); ~chatnpc("<p,neutral>Which is it going to be?"); @multi2("I'll pay the fine.", shantay_ill_pay_the_fine, "No thanks, you're not having my money.", shantay_no_thanks_youre_not_having_my_money); } @shantay_send_player_to_port_sarim; } inv_del(inv, coins, 5); %shantay_jail_progress = ^paid_shantay_jail_fine; mes("You hand over five gold pieces to Shantay."); ~chatnpc("<p,neutral>Great Effendi, now please try to keep the peace."); mes("Shantay unlocks the door to the cell."); [label,shantay_send_player_to_port_sarim] mes("You find yourself in a prison."); p_telejump(0_47_49_9_46); facesquare(movecoord(coord, -1, 0, 0)); [label,shantay_can_i_see_what_you_have_to_sell_please] ~chatplayer("<p,neutral>Can I see what you have to sell please?"); ~chatnpc("<p,neutral>Absolutely Effendi!"); if (map_members = ^false) { mes(^mes_members_store_owner); // guess return; } ~openshop_activenpc; [label,shantay_i_must_be_going] ~chatplayer("<p,neutral>I must be going."); ~chatnpc("<p,neutral>So long..."); [label,shantay_buy_shantay_pass] if (map_members = ^false) { ~chatnpc("<p,neutral>Sorry effendi, I can't offer this service right now."); return; } ~chatplayer("<p,neutral>I want to buy a shantay pass for 5 gold coins."); if (inv_total(inv, coins) < 5) { ~chatnpc("<p,neutral>Sorry friend, the Shantay Pass is 5 gold coins. You|don't seem to have enough money!"); return; } inv_add(inv, shantay_pass, 1); inv_del(inv, coins, 5); ~objbox(shantay_pass, "You purchase a Shantay Pass.", 250, 0, divide(^objbox_height, 2));
1
0.673181
1
0.673181
game-dev
MEDIA
0.887762
game-dev,web-backend
0.509131
1
0.509131
lua9520/source-engine-2018-hl2_src
9,954
game/client/tf2/c_obj_powerpack.cpp
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ //=============================================================================// #include "cbase.h" #include "c_baseobject.h" #include "ObjectControlPanel.h" #include "tf_shareddefs.h" #include "tempent.h" #include "c_te_legacytempents.h" #include "iviewrender_beams.h" #include "beamdraw.h" #include "view.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" #define NUM_POWERPACK_GLOWS 6 //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- class C_ObjectPowerPack : public C_BaseObject { DECLARE_CLASS( C_ObjectPowerPack, C_BaseObject ); public: DECLARE_CLIENTCLASS(); C_ObjectPowerPack(); ~C_ObjectPowerPack(); int SocketsLeft() const { return (MAX_OBJECTS_PER_PACK - m_iObjectsAttached); } // Since we have material proxies to show building amount, don't offset origin virtual bool OffsetObjectOrigin( Vector& origin ) { return false; } virtual void OnGoActive( void ); virtual void OnGoInactive( void ); void RemoveGlows( void ); virtual void ClientThink( void ); virtual int DrawModel( int flags ); private: int m_iObjectsAttached; int m_iGlowModelIndex; C_LocalTempEntity *m_pGlowSprites[ NUM_POWERPACK_GLOWS ]; // Jacob's laddder Beam_t *m_pJacobsLadderBeam; float m_flJacobsLeftPoint; float m_flJacobsRightPoint; Vector m_vecJacobsStart; Vector m_vecJacobsEnd; CMaterialReference m_hJacobsPointMaterial; private: C_ObjectPowerPack( const C_ObjectPowerPack & ); // not defined, not accessible }; IMPLEMENT_CLIENTCLASS_DT(C_ObjectPowerPack, DT_ObjectPowerPack, CObjectPowerPack) RecvPropInt( RECVINFO(m_iObjectsAttached) ), END_RECV_TABLE() //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- C_ObjectPowerPack::C_ObjectPowerPack() { for ( int i = 0; i < NUM_POWERPACK_GLOWS; i++ ) { m_pGlowSprites[i] = NULL; } m_iGlowModelIndex = PrecacheModel( "effects/human_object_glow.vmt" ); m_pJacobsLadderBeam = NULL; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- C_ObjectPowerPack::~C_ObjectPowerPack( void ) { RemoveGlows(); } //----------------------------------------------------------------------------- // Purpose: We've just gone active //----------------------------------------------------------------------------- void C_ObjectPowerPack::OnGoActive( void ) { // Turn on our glows for ( int i = 0; i < NUM_POWERPACK_GLOWS; i++ ) { // Find the attachment point int iAttachment = LookupAttachment( VarArgs("glow_%d",(i+1)) ); Vector vecOrigin; QAngle vecAngles; if ( GetAttachment( iAttachment, vecOrigin, vecAngles ) ) { Vector vecForward; AngleVectors( vecAngles, &vecForward ); m_pGlowSprites[i] = tempents->TempSprite( vecOrigin, vec3_origin, 0.35, m_iGlowModelIndex, kRenderTransAdd, 0, 0.5, 1, FTENT_PERSIST | FTENT_NEVERDIE | FTENT_BEOCCLUDED, vecForward ); } } m_flJacobsLeftPoint = 0; m_flJacobsRightPoint = 0; m_hJacobsPointMaterial.Init( "sprites/blueflare2", TEXTURE_GROUP_CLIENT_EFFECTS ); } //----------------------------------------------------------------------------- // Purpose: We've just gone inactive //----------------------------------------------------------------------------- void C_ObjectPowerPack::OnGoInactive( void ) { // Turn off our glows RemoveGlows(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void C_ObjectPowerPack::RemoveGlows( void ) { for ( int i = 0; i < NUM_POWERPACK_GLOWS; i++ ) { if ( m_pGlowSprites[i] ) { m_pGlowSprites[i]->die = 0; m_pGlowSprites[i] = NULL; } } // Stop the jacob's ladder if ( m_pJacobsLadderBeam ) { m_pJacobsLadderBeam->flags &= ~FBEAM_FOREVER; m_pJacobsLadderBeam->die = gpGlobals->curtime; m_pJacobsLadderBeam = NULL; } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void C_ObjectPowerPack::ClientThink( void ) { // Create the jacob's ladder if ( !m_pJacobsLadderBeam ) { BeamInfo_t beamInfo; beamInfo.m_vecStart.Init(); beamInfo.m_vecEnd.Init(); beamInfo.m_pszModelName = "sprites/physbeam.vmt"; beamInfo.m_flHaloScale = 0.0f; beamInfo.m_flLife = 0.0f; beamInfo.m_flWidth = 8.0f; beamInfo.m_flEndWidth = 4.0f; beamInfo.m_flFadeLength = 0.0f; beamInfo.m_flAmplitude = 20.0f; beamInfo.m_flBrightness = 255.0f; beamInfo.m_flSpeed = 0.0f; beamInfo.m_nStartFrame = 0; beamInfo.m_flFrameRate = 0.0f; beamInfo.m_flRed = 206.0f; beamInfo.m_flGreen = 181.0f; beamInfo.m_flBlue = 127.0f; beamInfo.m_nSegments = 5; beamInfo.m_bRenderable = true; m_pJacobsLadderBeam = beams->CreateBeamPoints( beamInfo ); } // Update the position of the jacob's ladder BeamInfo_t beamInfo; QAngle vecAngle; int iAttachment; // Setup a color reflecting the amount of power being used color32 color; color.r = 206; color.g = 182; color.b = 127; color.a = 255; // Tesla Effect Vector vecRightTop, vecRightBottom; Vector vecLeftTop, vecLeftBottom; iAttachment = LookupAttachment( "Tesla_ll" ); GetAttachment( iAttachment, vecLeftBottom, vecAngle ); iAttachment = LookupAttachment( "Tesla_ul" ); GetAttachment( iAttachment, vecLeftTop, vecAngle ); iAttachment = LookupAttachment( "Tesla_lr" ); GetAttachment( iAttachment, vecRightBottom, vecAngle ); iAttachment = LookupAttachment( "Tesla_ur" ); GetAttachment( iAttachment, vecRightTop, vecAngle ); float flSpeed = 0.02; m_flJacobsLeftPoint += random->RandomFloat( flSpeed * 0.25, flSpeed * 2); m_flJacobsRightPoint += random->RandomFloat( flSpeed * 0.25, flSpeed * 2); // If they've both hit the end, break the ladder if ( m_flJacobsLeftPoint >= 1.0f && m_flJacobsRightPoint >= 1.0f ) { // Snap! m_flJacobsLeftPoint = 0.0f; m_flJacobsRightPoint = 0.0f; } else if ( m_flJacobsLeftPoint > 1.0f ) { // Only the left point's made it m_flJacobsLeftPoint = 1.0f; } else if ( m_flJacobsRightPoint > 1.0f ) { // Only the right point's made it m_flJacobsRightPoint = 1.0f; } Vector vecLeft = vecLeftTop - vecLeftBottom; Vector vecRight = vecRightTop - vecRightBottom; m_vecJacobsStart = vecLeftBottom + ( m_flJacobsLeftPoint * vecLeft ); m_vecJacobsEnd = vecRightBottom + ( m_flJacobsRightPoint * vecRight ); beamInfo.m_vecStart = m_vecJacobsStart; beamInfo.m_vecEnd = m_vecJacobsEnd; beamInfo.m_flRed = color.r; beamInfo.m_flGreen = color.g; beamInfo.m_flBlue = color.b; beams->UpdateBeamInfo( m_pJacobsLadderBeam, beamInfo ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- int C_ObjectPowerPack::DrawModel( int flags ) { if ( BaseClass::DrawModel( flags ) ) { if ( ShouldBeActive() ) { // Get the distance to the view float flDistance = (GetAbsOrigin() - MainViewOrigin()).LengthSqr(); if ( flDistance < (1024 * 1024) ) { // Draw a sprite at the tips. color32 color; color.r = 255; color.g = 255; color.b = 255; color.a = 255; float flSize = 25.0f; materials->Bind( m_hJacobsPointMaterial, this ); DrawSprite( m_vecJacobsStart, flSize, flSize, color ); DrawSprite( m_vecJacobsEnd, flSize, flSize, color ); } } return true; } return false; } //----------------------------------------------------------------------------- // Control screen //----------------------------------------------------------------------------- class CPowerPackControlPanel : public CObjectControlPanel { DECLARE_CLASS( CPowerPackControlPanel, CObjectControlPanel ); public: CPowerPackControlPanel( vgui::Panel *parent, const char *panelName ); virtual bool Init( KeyValues* pKeyValues, VGuiScreenInitData_t* pInitData ); virtual void OnTick(); private: vgui::Label *m_pSocketsLabel; }; DECLARE_VGUI_SCREEN_FACTORY( CPowerPackControlPanel, "powerpack_control_panel" ); //----------------------------------------------------------------------------- // Constructor: //----------------------------------------------------------------------------- CPowerPackControlPanel::CPowerPackControlPanel( vgui::Panel *parent, const char *panelName ) : BaseClass( parent, "CPowerPackControlPanel" ) { } //----------------------------------------------------------------------------- // Initialization //----------------------------------------------------------------------------- bool CPowerPackControlPanel::Init( KeyValues* pKeyValues, VGuiScreenInitData_t* pInitData ) { m_pSocketsLabel = new vgui::Label( GetActivePanel(), "SocketReadout", "" ); if (!BaseClass::Init(pKeyValues, pInitData)) return false; return true; } //----------------------------------------------------------------------------- // Frame-based update //----------------------------------------------------------------------------- void CPowerPackControlPanel::OnTick() { BaseClass::OnTick(); C_BaseObject *pObj = GetOwningObject(); if (!pObj) return; Assert( dynamic_cast<C_ObjectPowerPack*>(pObj) ); C_ObjectPowerPack *pPowerPack = static_cast<C_ObjectPowerPack*>(pObj); char buf[256]; int nSocketsLeft = pPowerPack->SocketsLeft(); if (nSocketsLeft > 0) { Q_snprintf( buf, sizeof( buf ), "%d sockets left", pPowerPack->SocketsLeft() ); } else { Q_strncpy( buf, "No sockets left", sizeof( buf ) ); } m_pSocketsLabel->SetText( buf ); }
1
0.939194
1
0.939194
game-dev
MEDIA
0.802387
game-dev
0.942917
1
0.942917
ServUO/ServUO
7,945
Scripts/Mobiles/Normal/PlagueBeast.cs
using System; using Server.Items; using Server.Network; namespace Server.Mobiles { [CorpseName("a plague beast corpse")] public class PlagueBeast : BaseCreature, IDevourer { private int m_DevourTotal; private int m_DevourGoal; private bool m_HasMetalChest = false; [CommandProperty(AccessLevel.GameMaster)] public int TotalDevoured { get { return m_DevourTotal; } set { m_DevourTotal = value; } } [CommandProperty(AccessLevel.GameMaster)] public int DevourGoal { get { return (IsParagon ? m_DevourGoal + 25 : m_DevourGoal); } set { m_DevourGoal = value; } } [CommandProperty(AccessLevel.GameMaster)] public bool HasMetalChest { get { return m_HasMetalChest; } } [Constructable] public PlagueBeast() : base(AIType.AI_Melee, FightMode.Closest, 10, 1, 0.2, 0.4) { Name = "a plague beast"; Body = 775; SetStr(302, 500); SetDex(80); SetInt(16, 20); SetHits(318, 404); SetDamage(20, 24); SetDamageType(ResistanceType.Physical, 60); SetDamageType(ResistanceType.Poison, 40); SetResistance(ResistanceType.Physical, 45, 55); SetResistance(ResistanceType.Fire, 40, 50); SetResistance(ResistanceType.Cold, 25, 35); SetResistance(ResistanceType.Poison, 65, 75); SetResistance(ResistanceType.Energy, 25, 35); SetSkill(SkillName.MagicResist, 35.0); SetSkill(SkillName.Tactics, 100.0); SetSkill(SkillName.Wrestling, 100.0); Fame = 13000; Karma = -13000; VirtualArmor = 30; if (Utility.RandomDouble() < 0.80) PackItem(new PlagueBeastGland()); if (Core.ML && Utility.RandomDouble() < 0.33) PackItem(Engines.Plants.Seed.RandomPeculiarSeed(2)); m_DevourTotal = 0; m_DevourGoal = Utility.RandomMinMax(15, 25); // How many corpses must be devoured before a metal chest is awarded SetSpecialAbility(SpecialAbility.PoisonSpit); } public override void GenerateLoot() { AddLoot(LootPack.FilthyRich); AddLoot(LootPack.Gems, Utility.Random(1, 3)); } public override void OnDamagedBySpell(Mobile caster) { if (Map != null && caster != this && 0.25 > Utility.RandomDouble()) { BaseCreature spawn = new PlagueSpawn(this); spawn.Team = Team; spawn.MoveToWorld(Location, Map); spawn.Combatant = caster; Say(1053034); // * The plague beast creates another beast from its flesh! * } base.OnDamagedBySpell(caster); } public override bool AutoDispel { get { return true; } } public override Poison PoisonImmune { get { return Poison.Lethal; } } public override void OnGotMeleeAttack(Mobile attacker) { if (Map != null && attacker != this && 0.25 > Utility.RandomDouble()) { BaseCreature spawn = new PlagueSpawn(this); spawn.Team = Team; spawn.MoveToWorld(Location, Map); spawn.Combatant = attacker; Say(1053034); // * The plague beast creates another beast from its flesh! * } base.OnGotMeleeAttack(attacker); } public PlagueBeast(Serial serial) : base(serial) { } public override int GetIdleSound() { return 0x1BF; } public override int GetAttackSound() { return 0x1C0; } public override int GetHurtSound() { return 0x1C1; } public override int GetDeathSound() { return 0x1C2; } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.Write((int)1); writer.Write(m_HasMetalChest); writer.Write(m_DevourTotal); writer.Write(m_DevourGoal); } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadInt(); switch( version ) { case 1: { m_HasMetalChest = reader.ReadBool(); m_DevourTotal = reader.ReadInt(); m_DevourGoal = reader.ReadInt(); break; } } } public override void OnThink() { base.OnThink(); // Check to see if we need to devour any corpses IPooledEnumerable eable = GetItemsInRange(3); // Get all corpses in range foreach (Item item in eable) { if (item is Corpse) // For each Corpse { Corpse corpse = item as Corpse; // Ensure that the corpse was killed by us if (corpse != null && corpse.Killer == this && corpse.Owner != null) { if (!corpse.DevourCorpse() && !corpse.Devoured) PublicOverheadMessage(MessageType.Emote, 0x3B2, 1053032); // * The plague beast attempts to absorb the remains, but cannot! * } } } eable.Free(); } #region IDevourer Members public bool Devour(Corpse corpse) { if (corpse == null || corpse.Owner == null) // sorry we can't devour because the corpse's owner is null return false; if (corpse.Owner.Body.IsHuman) corpse.TurnToBones(); // Not bones yet, and we are a human body therefore we turn to bones. IncreaseHits((int)Math.Ceiling((double)corpse.Owner.HitsMax * 0.75)); m_DevourTotal++; PublicOverheadMessage(MessageType.Emote, 0x3B2, 1053033); // * The plague beast absorbs the fleshy remains of the corpse * if (!m_HasMetalChest && m_DevourTotal >= DevourGoal) { PackItem(new MetalChest()); m_HasMetalChest = true; } return true; } #endregion private void IncreaseHits(int hp) { int maxhits = 2000; if (IsParagon) maxhits = (int)(maxhits * Paragon.HitsBuff); if (hp < 1000 && !Core.AOS) hp = (hp * 100) / 60; if (HitsMaxSeed >= maxhits) { HitsMaxSeed = maxhits; int newHits = Hits + hp + Utility.RandomMinMax(10, 20); // increase the hp until it hits if it goes over it'll max at 2000 Hits = Math.Min(maxhits, newHits); // Also provide heal for each devour on top of the hp increase } else { int min = (hp / 2) + 10; int max = hp + 20; int hpToIncrease = Utility.RandomMinMax(min, max); HitsMaxSeed += hpToIncrease; Hits += hpToIncrease; // Also provide heal for each devour } } } }
1
0.979228
1
0.979228
game-dev
MEDIA
0.986167
game-dev
0.919447
1
0.919447
bowser0000/SkyblockMod
1,431
src/main/java/me/Danker/features/StopSalvagingStarredItems.java
package me.Danker.features; import me.Danker.config.ModConfig; import me.Danker.events.ChestSlotClickedEvent; import net.minecraft.client.Minecraft; import net.minecraft.item.ItemStack; import net.minecraft.util.ChatComponentText; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; public class StopSalvagingStarredItems { @SubscribeEvent public void onSlotClick(ChestSlotClickedEvent event) { ItemStack item = event.item; if (ModConfig.stopSalvageStarred && event.inventoryName.startsWith("Salvage")) { if (item == null) return; boolean inSalvageGui = false; if (item.getDisplayName().contains("Salvage") || item.getDisplayName().contains("Essence")) { ItemStack salvageItem = event.inventory.getStackInSlot(13); if (salvageItem == null) return; item = salvageItem; inSalvageGui = true; } if (item.getDisplayName().contains("✪") && (event.slot.slotNumber > 53 || inSalvageGui)) { Minecraft.getMinecraft().thePlayer.playSound("note.bass", 1, 0.5f); Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText(ModConfig.getColour(ModConfig.errorColour) + "Danker's Skyblock Mod has stopped you from salvaging that item!")); event.setCanceled(true); return; } } } }
1
0.961959
1
0.961959
game-dev
MEDIA
0.986766
game-dev
0.940497
1
0.940497
CGandGameEngineLearner/IronAngel
1,942
Assets/Behavior Designer/Runtime/Tasks/Unity/Animator/WaitForState.cs
using UnityEngine; namespace BehaviorDesigner.Runtime.Tasks.Unity.UnityAnimator { [TaskCategory("Unity/Animator")] [TaskDescription("Waits for the Animator to reach the specified state.")] public class WaitForState : Action { [Tooltip("The GameObject that the task operates on. If null the task GameObject is used.")] public SharedGameObject targetGameObject; [Tooltip("The name of the state")] public SharedString stateName; [Tooltip("The layer where the state is")] public SharedInt layer = -1; private Animator animator; private GameObject prevGameObject; private int stateHash; public override void OnAwake() { stateHash = Animator.StringToHash(stateName.Value); } public override void OnStart() { var currentGameObject = GetDefaultGameObject(targetGameObject.Value); if (currentGameObject != prevGameObject) { animator = currentGameObject.GetComponent<Animator>(); prevGameObject = currentGameObject; if (!animator.HasState(layer.Value, stateHash)) { Debug.LogError("Error: The Animator does not have the state " + stateName.Value + " on layer " + layer.Value); } } } public override TaskStatus OnUpdate() { if (animator == null) { Debug.LogWarning("Animator is null"); return TaskStatus.Failure; } var state = animator.GetCurrentAnimatorStateInfo(layer.Value); if (state.shortNameHash == stateHash) { return TaskStatus.Success; } return TaskStatus.Running; } public override void OnReset() { targetGameObject = null; stateName = ""; layer = -1; } } }
1
0.620151
1
0.620151
game-dev
MEDIA
0.987454
game-dev
0.789952
1
0.789952
Picovoice/picovoice
17,920
demo/unity-video-player/Assets/Scripts/VideoController.cs
using System; using System.IO; using System.Linq; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Video; using UnityEngine.Networking; using Pv.Unity; using System.Text; using TMPro; using UnityEngine.UI; public class VideoController : MonoBehaviour { private static string ACCESS_KEY = "${YOUR_ACCESS_KEY_HERE}"; // AccessKey obtained from Picovoice Console (https://console.picovoice.ai/) VideoPlayer _videoPlayer; PicovoiceManager _picovoiceManager; MeshRenderer _screenOverlay; MeshRenderer _border; TextMeshPro _playbackSpeedText; Text _notificationText; Image _notificationPanel; Canvas _helpCanvas; Component _timeline; Component _timelineFull; Component _volume; Component _volumeFull; Dictionary<string, SpriteRenderer> _stateIcons; VoiceProcessor _voiceProcessor; private bool isListening; private string _platform; private string _keywordPath; private string _contextPath; private readonly Color picoBlue = new Color(0.21568627451f, 0.49019607843f, 1f, 0.5f); void Start() { try { _platform = GetPlatform(); _keywordPath = GetKeywordPath(); _contextPath = GetContextPath(); _voiceProcessor = VoiceProcessor.Instance; _voiceProcessor.OnFrameCaptured += AnalyzeMicSignal; _videoPlayer = gameObject.GetComponentInChildren<VideoPlayer>(); MeshRenderer[] meshes = gameObject.GetComponentsInChildren<MeshRenderer>(); _border = meshes.First(x => x.name == "Border"); _screenOverlay = meshes.First(x => x.name == "ScreenOverlay"); Component[] objs = gameObject.GetComponentsInChildren<Component>(); _timeline = objs.First(x => x.name == "TimelinePivot"); _timelineFull = objs.First(x => x.name == "TimelineFullPivot"); _timeline.transform.localScale = new Vector3(0, 0.2f, 1); _timelineFull.transform.localScale = new Vector3(1, 0.2f, 1); _volume = objs.First(x => x.name == "VolumePivot"); _volumeFull = objs.First(x => x.name == "VolumeFullPivot"); _volume.transform.localScale = new Vector3(1, 0, 1); _volumeFull.transform.localScale = new Vector3(1, 0, 1); _stateIcons = gameObject.GetComponentsInChildren<SpriteRenderer>().ToDictionary(x => x.name); _playbackSpeedText = gameObject.GetComponentsInChildren<TextMeshPro>().First(x => x.name == "PlaybackSpeed"); _notificationText = gameObject.GetComponentsInChildren<Text>().First(x => x.name == "NotificationText"); _notificationText.text = "Say 'Porcupine, what can I say?' for help"; _notificationPanel = gameObject.GetComponentsInChildren<Image>().First(x => x.name == "NotificationPanel"); _helpCanvas = gameObject.GetComponentsInChildren<Canvas>().First(x => x.name == "HelpCanvas"); StartCoroutine(FadeIntroNotification()); _picovoiceManager = PicovoiceManager.Create(ACCESS_KEY, _keywordPath, OnWakeWordDetected, _contextPath, OnInferenceResult); } catch (Exception e) { ShowError(e.Message); } } IEnumerator FadeIntroNotification() { yield return new WaitForSeconds(3); Color _alphaSubtract = new Color(0, 0, 0, 0.008f); while (_notificationText.color.a > 0) { _notificationPanel.color -= _alphaSubtract; _notificationText.color -= _alphaSubtract; yield return null; } } void Update() { if (!_picovoiceManager.IsRecording) { if (_picovoiceManager.IsAudioDeviceAvailable()) { try { _picovoiceManager.Start(); } catch (PicovoiceInvalidArgumentException ex) { ShowError($"{ex.Message}\nEnsure your access key '{ACCESS_KEY}' is a valid access key."); } catch (PicovoiceActivationException) { ShowError("AccessKey activation error"); } catch (PicovoiceActivationLimitException) { ShowError("AccessKey reached its device limit"); } catch (PicovoiceActivationRefusedException) { ShowError("AccessKey refused"); } catch (PicovoiceActivationThrottledException) { ShowError("AccessKey has been throttled"); } catch (PicovoiceException ex) { ShowError("PicovoiceManager was unable to initialize: " + ex.Message); } } else { ShowError("No audio recording device available!"); } } float timelineScaleX = (float)(_videoPlayer.time / _videoPlayer.length); _timeline.transform.localScale = new Vector3(timelineScaleX, _timeline.transform.localScale.y, _timeline.transform.localScale.z); } void OnApplicationQuit() { _voiceProcessor.OnFrameCaptured -= AnalyzeMicSignal; if (_picovoiceManager != null) { _picovoiceManager.Stop(); } } void ShowError(string error) { _notificationText.text = error; _notificationText.color = Color.red; Debug.Log(error); } private void OnWakeWordDetected() { isListening = true; Debug.Log("Listening..."); _border.material.SetColor("_EmissionColor", picoBlue * 0.5f); } private void OnInferenceResult(Inference inference) { if (inference.IsUnderstood) { PrintInference(inference); if (inference.Intent == "changeVideoState") { ChangeVideoState(inference.Slots); } else if (inference.Intent == "seek") { SeekVideo(inference.Slots); } else if (inference.Intent == "changeVolume") { ChangeVolume(inference.Slots); } else if (inference.Intent == "changePlaybackSpeed") { ChangePlaybackSpeed(inference.Slots); } else if (inference.Intent == "help") { ToggleHelp(inference.Slots); } } else { Debug.Log("Didn't understand the command.\n"); _notificationText.text = "Didn't understand the command"; StartCoroutine(FadeNotification()); } isListening = false; _border.material.SetColor("_EmissionColor", picoBlue * 0f); } IEnumerator FadeNotification() { _notificationPanel.color = new Color(0.3f, 0.3f, 0.3f, 0.8f); _notificationText.color = Color.white; yield return new WaitForSeconds(1); Color _alphaSubtract = new Color(0, 0, 0, 0.008f); while (_notificationText.color.a > 0) { _notificationPanel.color -= _alphaSubtract; _notificationText.color -= _alphaSubtract; yield return null; } } private void PrintInference(Inference inference) { StringBuilder str = new StringBuilder(); str.Append("{\n"); str.Append($" intent : '{inference.Intent}'\n"); str.Append(" slots : {\n"); foreach (KeyValuePair<string, string> slot in inference.Slots) str.Append($" {slot.Key} : '{slot.Value}'\n"); str.Append(" }\n"); str.Append("}\n"); Debug.Log(str.ToString()); } private void ChangeVideoState(Dictionary<string, string> slots) { if (slots.ContainsKey("action")) { string action = slots["action"]; if (action == "play") { if (!_videoPlayer.isPlaying) _videoPlayer.Play(); } else if (action == "pause") { if (!_videoPlayer.isPaused) _videoPlayer.Pause(); } else if (action == "stop") { if (_videoPlayer.isPlaying || _videoPlayer.isPaused) _videoPlayer.Stop(); } else if (action == "mute") { _videoPlayer.SetDirectAudioMute(0, true); } else if (action == "unmute") { _videoPlayer.SetDirectAudioMute(0, false); } else if (action == "resume") { if (!_videoPlayer.isPlaying) _videoPlayer.Play(); } else if (action == "restart") { if (_videoPlayer.isPlaying) _videoPlayer.Stop(); else _videoPlayer.time = 0; _videoPlayer.Play(); } _stateIcons[action].color = Color.white; _screenOverlay.material.color = new Color(0, 0, 0, 0.5f); StartCoroutine(FadeStateIcon(_stateIcons[action])); StartCoroutine(FadeOverlay()); } } IEnumerator FadeStateIcon(SpriteRenderer icon) { Color _alphaSubtract = new Color(0, 0, 0, 0.008f); while (icon.color.a > 0) { icon.color -= _alphaSubtract; yield return null; } } IEnumerator FadeOverlay() { Color _alphaSubtract = new Color(0, 0, 0, 0.004f); while (_screenOverlay.material.color.a > 0) { _screenOverlay.material.color -= _alphaSubtract; yield return null; } } private void SeekVideo(Dictionary<string, string> slots) { int hours = 0; int minutes = 0; int seconds = 0; if (slots.ContainsKey("hours")) { hours = int.Parse(slots["hours"]); hours *= 3600; } if (slots.ContainsKey("minutes")) { minutes = int.Parse(slots["minutes"]); minutes *= 60; } if (slots.ContainsKey("seconds")) { seconds = int.Parse(slots["seconds"]); } if (slots.ContainsKey("direction")) { if (slots["direction"] == "forward" || slots["direction"] == "forwards" || slots["direction"] == "ahead") { _videoPlayer.time += hours + minutes + seconds; } else { _videoPlayer.time -= hours + minutes + seconds; } } else { _videoPlayer.time = hours + minutes + seconds; } _timeline.transform.localScale = new Vector3(_timeline.transform.localScale.x, 1, _timeline.transform.localScale.z); _timelineFull.transform.localScale = new Vector3(_timelineFull.transform.localScale.x, 1, _timelineFull.transform.localScale.z); StartCoroutine(ShrinkTimeline()); } IEnumerator ShrinkTimeline() { yield return new WaitForSeconds(3); _timeline.transform.localScale = new Vector3(_timeline.transform.localScale.x, 0.2f, _timeline.transform.localScale.z); _timelineFull.transform.localScale = new Vector3(_timelineFull.transform.localScale.x, 0.2f, _timelineFull.transform.localScale.z); } private void ChangeVolume(Dictionary<string, string> slots) { if (slots.ContainsKey("volumePercent")) { float volumePercent = float.Parse(slots["volumePercent"].Replace("%", "")) * 0.01f; _videoPlayer.SetDirectAudioVolume(0, volumePercent); _volume.transform.localScale = new Vector3(volumePercent, 1, _volume.transform.localScale.z); _volumeFull.transform.localScale = new Vector3(_volumeFull.transform.localScale.x, 1, _volumeFull.transform.localScale.z); StartCoroutine(ShrinkVolume()); } } IEnumerator ShrinkVolume() { yield return new WaitForSeconds(4); _volume.transform.localScale = new Vector3(_volume.transform.localScale.x, 0, _volume.transform.localScale.z); _volumeFull.transform.localScale = new Vector3(_volumeFull.transform.localScale.x, 0, _volumeFull.transform.localScale.z); } private void ChangePlaybackSpeed(Dictionary<string, string> slots) { float playbackSpeed = 1f; if (slots.ContainsKey("playbackSpeedInt")) { playbackSpeed = float.Parse(slots["playbackSpeedInt"]); } if (slots.ContainsKey("playbackSpeedDecimal")) { playbackSpeed += float.Parse(slots["playbackSpeedDecimal"]) * 0.1f; } if (slots.ContainsKey("playbackSpeedTenth")) { playbackSpeed += float.Parse(slots["playbackSpeedTenth"]) * 0.1f; } if (slots.ContainsKey("playbackSpeedHundredth")) { playbackSpeed += float.Parse(slots["playbackSpeedHundredth"]) * 0.01f; } if (slots.ContainsKey("playbackSpeedPercent")) { playbackSpeed = float.Parse(slots["playbackSpeedPercent"].Replace("%", "")) * 0.01f; } _videoPlayer.playbackSpeed = playbackSpeed; _playbackSpeedText.text = string.Format("{0}x", playbackSpeed); _playbackSpeedText.color = Color.white; _screenOverlay.material.color = new Color(0, 0, 0, 0.5f); StartCoroutine(FadePlaybackSpeed()); StartCoroutine(FadeOverlay()); } IEnumerator FadePlaybackSpeed() { Color _alphaSubtract = new Color(0, 0, 0, 0.008f); while (_playbackSpeedText.color.a > 0) { _playbackSpeedText.color -= _alphaSubtract; yield return null; } } private void ToggleHelp(Dictionary<string, string> slots) { bool showHelp = true; if (slots.ContainsKey("toggleHelp")) { showHelp = slots["toggleHelp"] == "show"; } _helpCanvas.enabled = showHelp; } private readonly Queue rmsQueue = new Queue(7); private void AnalyzeMicSignal(short[] audio) { if (!isListening) return; // calculate RMS of frame double rmsSum = 0; for (int i = 0; i < audio.Length; i++) rmsSum += Math.Pow(audio[i], 2); double rms = Math.Sqrt(rmsSum / audio.Length) / 32767.0f; // average past values for smoothing effect if (rmsQueue.Count == 7) rmsQueue.Dequeue(); rmsQueue.Enqueue(rms); double rmsAvg = 0; foreach (double rmsVal in rmsQueue) { rmsAvg += rmsVal; } rmsAvg /= rmsQueue.Count; // convert to dBFS double dBFS = 20 * Math.Log10(rmsAvg); float normalizedDbfs = (float)(dBFS + 50) / 50.0f; _border.material.SetColor("_EmissionColor", picoBlue * normalizedDbfs); } private string GetPlatform() { switch (Application.platform) { case RuntimePlatform.WindowsEditor: case RuntimePlatform.WindowsPlayer: return "windows"; case RuntimePlatform.OSXEditor: case RuntimePlatform.OSXPlayer: return "mac"; case RuntimePlatform.LinuxEditor: case RuntimePlatform.LinuxPlayer: return "linux"; case RuntimePlatform.IPhonePlayer: return "ios"; case RuntimePlatform.Android: return "android"; default: throw new NotSupportedException(string.Format("Platform '{0}' not supported by Picovoice Unity binding", Application.platform)); } } public string GetKeywordPath() { string fileName = string.Format("porcupine_{0}.ppn", _platform); string srcPath = Path.Combine(Application.streamingAssetsPath, string.Format("keyword_files/{0}/{1}", _platform, fileName)); #if !UNITY_EDITOR && UNITY_ANDROID string dstPath = Path.Combine(Application.persistentDataPath, string.Format("keyword_files/{0}", _platform)); if (!Directory.Exists(dstPath)) { Directory.CreateDirectory(dstPath); } dstPath = Path.Combine(dstPath, fileName); return ExtractResource(srcPath, dstPath); #else return srcPath; #endif } public string GetContextPath() { string fileName = string.Format("video_player_{0}.rhn", _platform); string srcPath = Path.Combine(Application.streamingAssetsPath, string.Format("contexts/{0}/{1}", _platform, fileName)); #if !UNITY_EDITOR && UNITY_ANDROID string dstPath = Path.Combine(Application.persistentDataPath, string.Format("contexts/{0}", _platform)); if (!Directory.Exists(dstPath)) { Directory.CreateDirectory(dstPath); } dstPath = Path.Combine(dstPath, fileName); return ExtractResource(srcPath, dstPath); #else return srcPath; #endif } #if !UNITY_EDITOR && UNITY_ANDROID public string ExtractResource(string srcPath, string dstPath) { var loadingRequest = UnityWebRequest.Get(srcPath); loadingRequest.SendWebRequest(); while (!loadingRequest.isDone) { if (loadingRequest.isNetworkError || loadingRequest.isHttpError) { break; } } if (!(loadingRequest.isNetworkError || loadingRequest.isHttpError)) { File.WriteAllBytes(dstPath, loadingRequest.downloadHandler.data); } return dstPath; } #endif }
1
0.97034
1
0.97034
game-dev
MEDIA
0.905677
game-dev
0.99535
1
0.99535
IAFEnvoy/IceAndFire-Fabric
2,378
src/main/java/com/iafenvoy/iceandfire/util/trade/offer/TradeOfferInternals.java
package com.iafenvoy.iceandfire.util.trade.offer; import it.unimi.dsi.fastutil.ints.Int2ObjectMap; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import net.minecraft.village.TradeOffers; import net.minecraft.village.VillagerProfession; import org.apache.commons.lang3.ArrayUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.function.Consumer; // From object builder api v1 public final class TradeOfferInternals { private static final Logger LOGGER = LoggerFactory.getLogger("fabric-villager-api-v1"); private TradeOfferInternals() { } // synchronized guards against concurrent modifications - Vanilla does not mutate the underlying arrays (as of 1.16), // so reads will be fine without locking. public static synchronized void registerVillagerOffers(VillagerProfession profession, int level, Consumer<List<TradeOffers.Factory>> factory) { Objects.requireNonNull(profession, "VillagerProfession may not be null."); registerOffers(TradeOffers.PROFESSION_TO_LEVELED_TRADE.computeIfAbsent(profession, key -> new Int2ObjectOpenHashMap<>()), level, factory); } public static synchronized void registerWanderingTraderOffers(int level, Consumer<List<TradeOffers.Factory>> factory) { registerOffers(TradeOffers.WANDERING_TRADER_TRADES, level, factory); } // Shared code to register offers for both villagers and wandering traders. private static void registerOffers(Int2ObjectMap<TradeOffers.Factory[]> leveledTradeMap, int level, Consumer<List<TradeOffers.Factory>> factory) { final List<TradeOffers.Factory> list = new ArrayList<>(); factory.accept(list); final TradeOffers.Factory[] originalEntries = leveledTradeMap.computeIfAbsent(level, key -> new TradeOffers.Factory[0]); final TradeOffers.Factory[] addedEntries = list.toArray(new TradeOffers.Factory[0]); final TradeOffers.Factory[] allEntries = ArrayUtils.addAll(originalEntries, addedEntries); leveledTradeMap.put(level, allEntries); } public static void printRefreshOffersWarning() { Throwable loggingThrowable = new Throwable(); LOGGER.warn("TradeOfferHelper#refreshOffers does not do anything, yet it was called! Stack trace:", loggingThrowable); } }
1
0.701996
1
0.701996
game-dev
MEDIA
0.913756
game-dev
0.715681
1
0.715681
linuxmint/warpinator
10,981
src/grpcio-1.73.1/third_party/upb/upb/reflection/enum_def.c
// Protocol Buffers - Google's data interchange format // Copyright 2023 Google LLC. All rights reserved. // // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file or at // https://developers.google.com/open-source/licenses/bsd #include "upb/reflection/internal/enum_def.h" #include <stddef.h> #include <stdint.h> #include <string.h> #include "upb/base/status.h" #include "upb/base/string_view.h" #include "upb/hash/common.h" #include "upb/hash/int_table.h" #include "upb/hash/str_table.h" #include "upb/mem/arena.h" #include "upb/mini_descriptor/decode.h" #include "upb/mini_descriptor/internal/encode.h" #include "upb/mini_table/enum.h" #include "upb/mini_table/file.h" #include "upb/reflection/def.h" #include "upb/reflection/def_type.h" #include "upb/reflection/internal/def_builder.h" #include "upb/reflection/internal/desc_state.h" #include "upb/reflection/internal/enum_reserved_range.h" #include "upb/reflection/internal/enum_value_def.h" #include "upb/reflection/internal/file_def.h" #include "upb/reflection/internal/strdup2.h" // Must be last. #include "upb/port/def.inc" struct upb_EnumDef { UPB_ALIGN_AS(8) const UPB_DESC(EnumOptions*) opts; const UPB_DESC(FeatureSet*) resolved_features; const upb_MiniTableEnum* layout; // Only for proto2. const upb_FileDef* file; const upb_MessageDef* containing_type; // Could be merged with "file". const char* full_name; upb_strtable ntoi; upb_inttable iton; const upb_EnumValueDef* values; const upb_EnumReservedRange* res_ranges; const upb_StringView* res_names; int value_count; int res_range_count; int res_name_count; int32_t defaultval; bool is_sorted; // Whether all of the values are defined in ascending order. #if UINTPTR_MAX == 0xffffffff uint32_t padding; // Increase size to a multiple of 8. #endif }; upb_EnumDef* _upb_EnumDef_At(const upb_EnumDef* e, int i) { return (upb_EnumDef*)&e[i]; } const upb_MiniTableEnum* _upb_EnumDef_MiniTable(const upb_EnumDef* e) { return e->layout; } bool _upb_EnumDef_Insert(upb_EnumDef* e, upb_EnumValueDef* v, upb_Arena* a) { const char* name = upb_EnumValueDef_Name(v); const upb_value val = upb_value_constptr(v); bool ok = upb_strtable_insert(&e->ntoi, name, strlen(name), val, a); if (!ok) return false; // Multiple enumerators can have the same number, first one wins. const int number = upb_EnumValueDef_Number(v); if (!upb_inttable_lookup(&e->iton, number, NULL)) { return upb_inttable_insert(&e->iton, number, val, a); } return true; } const UPB_DESC(EnumOptions) * upb_EnumDef_Options(const upb_EnumDef* e) { return e->opts; } bool upb_EnumDef_HasOptions(const upb_EnumDef* e) { return e->opts != (void*)kUpbDefOptDefault; } const UPB_DESC(FeatureSet) * upb_EnumDef_ResolvedFeatures(const upb_EnumDef* e) { return e->resolved_features; } const char* upb_EnumDef_FullName(const upb_EnumDef* e) { return e->full_name; } const char* upb_EnumDef_Name(const upb_EnumDef* e) { return _upb_DefBuilder_FullToShort(e->full_name); } const upb_FileDef* upb_EnumDef_File(const upb_EnumDef* e) { return e->file; } const upb_MessageDef* upb_EnumDef_ContainingType(const upb_EnumDef* e) { return e->containing_type; } int32_t upb_EnumDef_Default(const upb_EnumDef* e) { UPB_ASSERT(upb_EnumDef_FindValueByNumber(e, e->defaultval)); return e->defaultval; } int upb_EnumDef_ReservedRangeCount(const upb_EnumDef* e) { return e->res_range_count; } const upb_EnumReservedRange* upb_EnumDef_ReservedRange(const upb_EnumDef* e, int i) { UPB_ASSERT(0 <= i && i < e->res_range_count); return _upb_EnumReservedRange_At(e->res_ranges, i); } int upb_EnumDef_ReservedNameCount(const upb_EnumDef* e) { return e->res_name_count; } upb_StringView upb_EnumDef_ReservedName(const upb_EnumDef* e, int i) { UPB_ASSERT(0 <= i && i < e->res_name_count); return e->res_names[i]; } int upb_EnumDef_ValueCount(const upb_EnumDef* e) { return e->value_count; } const upb_EnumValueDef* upb_EnumDef_FindValueByName(const upb_EnumDef* e, const char* name) { return upb_EnumDef_FindValueByNameWithSize(e, name, strlen(name)); } const upb_EnumValueDef* upb_EnumDef_FindValueByNameWithSize( const upb_EnumDef* e, const char* name, size_t size) { upb_value v; return upb_strtable_lookup2(&e->ntoi, name, size, &v) ? upb_value_getconstptr(v) : NULL; } const upb_EnumValueDef* upb_EnumDef_FindValueByNumber(const upb_EnumDef* e, int32_t num) { upb_value v; return upb_inttable_lookup(&e->iton, num, &v) ? upb_value_getconstptr(v) : NULL; } bool upb_EnumDef_CheckNumber(const upb_EnumDef* e, int32_t num) { // We could use upb_EnumDef_FindValueByNumber(e, num) != NULL, but we expect // this to be faster (especially for small numbers). return upb_MiniTableEnum_CheckValue(e->layout, num); } const upb_EnumValueDef* upb_EnumDef_Value(const upb_EnumDef* e, int i) { UPB_ASSERT(0 <= i && i < e->value_count); return _upb_EnumValueDef_At(e->values, i); } bool upb_EnumDef_IsClosed(const upb_EnumDef* e) { if (UPB_TREAT_CLOSED_ENUMS_LIKE_OPEN) return false; return upb_EnumDef_IsSpecifiedAsClosed(e); } bool upb_EnumDef_IsSpecifiedAsClosed(const upb_EnumDef* e) { return UPB_DESC(FeatureSet_enum_type)(e->resolved_features) == UPB_DESC(FeatureSet_CLOSED); } bool upb_EnumDef_MiniDescriptorEncode(const upb_EnumDef* e, upb_Arena* a, upb_StringView* out) { upb_DescState s; _upb_DescState_Init(&s); const upb_EnumValueDef** sorted = NULL; if (!e->is_sorted) { sorted = _upb_EnumValueDefs_Sorted(e->values, e->value_count, a); if (!sorted) return false; } if (!_upb_DescState_Grow(&s, a)) return false; s.ptr = upb_MtDataEncoder_StartEnum(&s.e, s.ptr); // Duplicate values are allowed but we only encode each value once. uint32_t previous = 0; for (int i = 0; i < e->value_count; i++) { const uint32_t current = upb_EnumValueDef_Number(sorted ? sorted[i] : upb_EnumDef_Value(e, i)); if (i != 0 && previous == current) continue; if (!_upb_DescState_Grow(&s, a)) return false; s.ptr = upb_MtDataEncoder_PutEnumValue(&s.e, s.ptr, current); previous = current; } if (!_upb_DescState_Grow(&s, a)) return false; s.ptr = upb_MtDataEncoder_EndEnum(&s.e, s.ptr); // There will always be room for this '\0' in the encoder buffer because // kUpb_MtDataEncoder_MinSize is overkill for upb_MtDataEncoder_EndEnum(). UPB_ASSERT(s.ptr < s.buf + s.bufsize); *s.ptr = '\0'; out->data = s.buf; out->size = s.ptr - s.buf; return true; } static upb_MiniTableEnum* create_enumlayout(upb_DefBuilder* ctx, const upb_EnumDef* e) { upb_StringView sv; bool ok = upb_EnumDef_MiniDescriptorEncode(e, ctx->tmp_arena, &sv); if (!ok) _upb_DefBuilder_Errf(ctx, "OOM while building enum MiniDescriptor"); upb_Status status; upb_MiniTableEnum* layout = upb_MiniTableEnum_Build(sv.data, sv.size, ctx->arena, &status); if (!layout) _upb_DefBuilder_Errf(ctx, "Error building enum MiniTable: %s", status.msg); return layout; } static upb_StringView* _upb_EnumReservedNames_New( upb_DefBuilder* ctx, int n, const upb_StringView* protos) { upb_StringView* sv = UPB_DEFBUILDER_ALLOCARRAY(ctx, upb_StringView, n); for (int i = 0; i < n; i++) { sv[i].data = upb_strdup2(protos[i].data, protos[i].size, _upb_DefBuilder_Arena(ctx)); sv[i].size = protos[i].size; } return sv; } static void create_enumdef(upb_DefBuilder* ctx, const char* prefix, const UPB_DESC(EnumDescriptorProto) * enum_proto, const UPB_DESC(FeatureSet*) parent_features, upb_EnumDef* e) { const UPB_DESC(EnumValueDescriptorProto)* const* values; const UPB_DESC(EnumDescriptorProto_EnumReservedRange)* const* res_ranges; const upb_StringView* res_names; upb_StringView name; size_t n_value, n_res_range, n_res_name; UPB_DEF_SET_OPTIONS(e->opts, EnumDescriptorProto, EnumOptions, enum_proto); e->resolved_features = _upb_DefBuilder_ResolveFeatures( ctx, parent_features, UPB_DESC(EnumOptions_features)(e->opts)); // Must happen before _upb_DefBuilder_Add() e->file = _upb_DefBuilder_File(ctx); name = UPB_DESC(EnumDescriptorProto_name)(enum_proto); e->full_name = _upb_DefBuilder_MakeFullName(ctx, prefix, name); _upb_DefBuilder_Add(ctx, e->full_name, _upb_DefType_Pack(e, UPB_DEFTYPE_ENUM)); values = UPB_DESC(EnumDescriptorProto_value)(enum_proto, &n_value); bool ok = upb_strtable_init(&e->ntoi, n_value, ctx->arena); if (!ok) _upb_DefBuilder_OomErr(ctx); ok = upb_inttable_init(&e->iton, ctx->arena); if (!ok) _upb_DefBuilder_OomErr(ctx); e->defaultval = 0; e->value_count = n_value; e->values = _upb_EnumValueDefs_New(ctx, prefix, n_value, values, e->resolved_features, e, &e->is_sorted); if (n_value == 0) { _upb_DefBuilder_Errf(ctx, "enums must contain at least one value (%s)", e->full_name); } res_ranges = UPB_DESC(EnumDescriptorProto_reserved_range)(enum_proto, &n_res_range); e->res_range_count = n_res_range; e->res_ranges = _upb_EnumReservedRanges_New(ctx, n_res_range, res_ranges, e); res_names = UPB_DESC(EnumDescriptorProto_reserved_name)(enum_proto, &n_res_name); e->res_name_count = n_res_name; e->res_names = _upb_EnumReservedNames_New(ctx, n_res_name, res_names); if (!upb_inttable_compact(&e->iton, ctx->arena)) _upb_DefBuilder_OomErr(ctx); if (upb_EnumDef_IsClosed(e)) { if (ctx->layout) { e->layout = upb_MiniTableFile_Enum(ctx->layout, ctx->enum_count++); } else { e->layout = create_enumlayout(ctx, e); } } else { e->layout = NULL; } } upb_EnumDef* _upb_EnumDefs_New(upb_DefBuilder* ctx, int n, const UPB_DESC(EnumDescriptorProto*) const* protos, const UPB_DESC(FeatureSet*) parent_features, const upb_MessageDef* containing_type) { _upb_DefType_CheckPadding(sizeof(upb_EnumDef)); // If a containing type is defined then get the full name from that. // Otherwise use the package name from the file def. const char* name = containing_type ? upb_MessageDef_FullName(containing_type) : _upb_FileDef_RawPackage(ctx->file); upb_EnumDef* e = UPB_DEFBUILDER_ALLOCARRAY(ctx, upb_EnumDef, n); for (int i = 0; i < n; i++) { create_enumdef(ctx, name, protos[i], parent_features, &e[i]); e[i].containing_type = containing_type; } return e; }
1
0.896167
1
0.896167
game-dev
MEDIA
0.493239
game-dev
0.922666
1
0.922666
franshej/CustomMatPlot
9,606
extras/source/cmp_extras.cpp
#include "cmp_extras.hpp" #include "cmp_utils.h" namespace cmp { //////////////////////////////////////////////////////////////////////////////// ///////////////////////// PlotLookAndFeelTimeline ////////////////////////////// //////////////////////////////////////////////////////////////////////////////// PlotLookAndFeelTimeline::PlotLookAndFeelTimeline() : PlotLookAndFeel() { overridePlotColours(); } juce::Rectangle<int> PlotLookAndFeelTimeline::getGraphBounds( const juce::Rectangle<int> bounds, const juce::Component* const plot_comp) const noexcept { const auto estimated_grid_label_width = getGridLabelFont().getStringWidth( std::string(getMaximumAllowedCharacterGridLabel(), 'W')); auto graph_bounds = juce::Rectangle<int>(); if (const auto* plot = dynamic_cast<const Plot*>(plot_comp)) { const auto are_labels_set = areLabelsSet(plot); const auto [x_grid_label_width, y_grid_label_width] = getMaxGridLabelWidth(plot); auto top = getMarginSmall() * 2 + getGridLabelFont().getHeight(); const auto is_x_axis_label_below_graph = isXAxisLabelsBelowGraph(); auto bottom = is_x_axis_label_below_graph ? bounds.getHeight() - (getGridLabelFont().getHeight() + getMargin() + getXGridLabelDistanceFromGraphBound()) : bounds.getHeight() - (getMargin() + getXGridLabelDistanceFromGraphBound()); if (are_labels_set.x_label) { bottom -= (getXYTitleFont().getHeight() + getMargin()); } if (are_labels_set.title_label) { top += getXYTitleFont().getHeight() + getMargin(); } graph_bounds.setLeft(0); graph_bounds.setTop(int(top)); graph_bounds.setRight(bounds.getWidth()); graph_bounds.setBottom(bounds.getHeight()); } return std::move(graph_bounds); } void PlotLookAndFeelTimeline::drawFrame(juce::Graphics& g [[maybe_unused]], const juce::Rectangle<int> bounds [[maybe_unused]]) {} void PlotLookAndFeelTimeline::updateGridLabels( const CommonPlotParameterView common_plot_params, const std::vector<GridLine>& grid_lines, StringVector& x_custom_label_ticks, StringVector& y_custom_label_ticks, LabelVector& x_axis_labels_out, LabelVector& y_axis_labels_out) { const auto [x, y, width, height] = getRectangleMeasures<int>(common_plot_params.graph_bounds); const auto font = getGridLabelFont(); const std::size_t num_horizonal_lines = std::count_if(grid_lines.begin(), grid_lines.end(), [](const auto& gl) { return gl.direction == GridLine::Direction::horizontal; }); const std::size_t num_vertical_lines = std::count_if(grid_lines.begin(), grid_lines.end(), [](const auto& gl) { return gl.direction == GridLine::Direction::vertical; }); juce::Rectangle<int>* x_last_label_bound = nullptr; juce::Rectangle<int>* y_last_label_bound = nullptr; x_axis_labels_out.clear(); y_axis_labels_out.clear(); const auto use_custom_x_labels = x_custom_label_ticks.size() > 0u; const auto use_custom_y_labels = y_custom_label_ticks.size() > 0u; auto custom_x_labels_reverse_it = x_custom_label_ticks.rbegin(); if (use_custom_x_labels) { if (x_custom_label_ticks.size() >= num_vertical_lines) { custom_x_labels_reverse_it = x_custom_label_ticks.rbegin() + x_custom_label_ticks.size() - num_vertical_lines; } else { x_custom_label_ticks.resize(num_vertical_lines); custom_x_labels_reverse_it = x_custom_label_ticks.rbegin(); } } auto custom_y_labels_reverse_it = y_custom_label_ticks.rbegin(); if (use_custom_y_labels) { if (y_custom_label_ticks.size() >= num_horizonal_lines) { custom_y_labels_reverse_it = y_custom_label_ticks.rbegin() + y_custom_label_ticks.size() - num_horizonal_lines; } else { y_custom_label_ticks.resize(num_horizonal_lines); custom_y_labels_reverse_it = y_custom_label_ticks.rbegin(); } } const auto checkInterectionWithLastLabelAndAdd = [&](auto& last_rect, auto& axis_labels, const auto& label, const auto& bound) { if (!last_rect) { axis_labels.push_back({label, bound}); last_rect = &axis_labels.back().second; } else { if (!last_rect->intersects(bound)) { axis_labels.push_back({label, bound}); last_rect = &axis_labels.back().second; } } }; const auto getLabelWidthAndHeight = [](const auto& font, const auto& label) -> std::pair<int, int> { return std::make_pair(font.getStringWidth(label), int(font.getHeightInPoints())); }; for (auto it = grid_lines.rbegin(); it != grid_lines.rend(); it++) { const auto position = it->position; const auto direction = it->direction; const auto tick = it->tick; switch (direction) { case GridLine::Direction::vertical: { const auto label = use_custom_x_labels ? getNextCustomLabel(custom_x_labels_reverse_it, x_custom_label_ticks.rend()) : valueToStringWithoutTrailingZeros(tick); const auto [label_width, label_height] = getLabelWidthAndHeight(font, label); const auto is_x_axis_label_below_graph = isXAxisLabelsBelowGraph(); const auto bound_y = is_x_axis_label_below_graph ? common_plot_params.graph_bounds.getBottom() + getXGridLabelDistanceFromGraphBound() : common_plot_params.graph_bounds.getTopLeft().y - label_height - getMarginSmall() / 2; const auto bound = juce::Rectangle<int>(int(position.x) - label_width / 2, bound_y, label_width, label_height); checkInterectionWithLastLabelAndAdd(x_last_label_bound, x_axis_labels_out, label, bound); } break; case GridLine::Direction::horizontal: { const auto label = use_custom_y_labels ? getNextCustomLabel(custom_y_labels_reverse_it, y_custom_label_ticks.rend()) : valueToStringWithoutTrailingZeros(tick); const auto [label_width, label_height] = getLabelWidthAndHeight(font, label); const auto bound = juce::Rectangle<int>( x + getMarginSmall() * 2, int(position.y) - label_height / 2, label_width, label_height); checkInterectionWithLastLabelAndAdd(y_last_label_bound, y_axis_labels_out, label, bound); } break; default: break; } } } bool PlotLookAndFeelTimeline::isXAxisLabelsBelowGraph() const noexcept { return false; } void PlotLookAndFeelTimeline::drawGridLabels(juce::Graphics& g, const LabelVector& x_axis_labels, const LabelVector& y_axis_labels) { g.setColour(findColour(Plot::x_grid_label_colour)); g.setFont(getGridLabelFont()); for (const auto& x_axis_text : x_axis_labels) { g.drawText(x_axis_text.first, x_axis_text.second, juce::Justification::centred); } g.setColour(findColour(Plot::y_grid_label_colour)); for (const auto& y_axis_text : y_axis_labels) { g.drawText(y_axis_text.first, y_axis_text.second, juce::Justification::centredLeft); } } juce::Font PlotLookAndFeelTimeline::getGridLabelFont() const noexcept { return juce::Font("Arial Rounded MT", 10.f, juce::Font::plain); } void PlotLookAndFeelTimeline::updateVerticalGridLineTicksAuto( const juce::Rectangle<int>& bounds, const CommonPlotParameterView& common_plot_parameter_view, const GridType grid_type, const std::vector<float>& previous_ticks, std::vector<float>& x_ticks) noexcept { x_ticks.clear(); const auto x_min = common_plot_parameter_view.x_lim.min; const auto x_max = common_plot_parameter_view.x_lim.max; const auto dx = x_max - x_min > 100.f ? 10.f : 5.f; const auto start_value = floor(x_min / dx) * dx; const auto end_value = ceil(x_max / dx) * dx; for (auto x = start_value; x <= end_value; x += dx) { x_ticks.push_back(x); } } void PlotLookAndFeelTimeline::updateHorizontalGridLineTicksAuto( const juce::Rectangle<int>& bounds, const CommonPlotParameterView& common_plot_parameter_view, const GridType grid_type, const std::vector<float>& previous_ticks, std::vector<float>& y_ticks) noexcept { y_ticks.clear(); const auto y_min = common_plot_parameter_view.y_lim.min; const auto y_max = common_plot_parameter_view.y_lim.max; const auto dy = y_max - y_min > 100.f ? 10.f : 5.f; const auto start_value = floor(y_min / dy) * dy; const auto end_value = ceil(y_max / dy) * dy; for (auto y = start_value; y <= end_value; y += dy) { y_ticks.push_back(y); } } std::size_t PlotLookAndFeelTimeline::getMarginSmall() const noexcept { return 2u; } void PlotLookAndFeelTimeline::drawBackground( juce::Graphics& g, const juce::Rectangle<int>& bounds) {} void PlotLookAndFeelTimeline::overridePlotColours() noexcept { setColour(Plot::grid_colour, juce::Colour(0xff181818)); setColour(Plot::transluent_grid_colour, juce::Colour(0xff252525)); } } // namespace cmp
1
0.911907
1
0.911907
game-dev
MEDIA
0.432985
game-dev,graphics-rendering
0.942371
1
0.942371
jarjin/LuaFramework_UGUI
1,413
Assets/LuaFramework/ToLua/Lua/UnityEngine/Ray.lua
-------------------------------------------------------------------------------- -- Copyright (c) 2015 - 2016 , 蒙占志(topameng) topameng@gmail.com -- All rights reserved. -- Use, modification and distribution are subject to the "MIT License" -------------------------------------------------------------------------------- local rawget = rawget local setmetatable = setmetatable local Vector3 = Vector3 local Ray = { direction = Vector3.zero, origin = Vector3.zero, } local get = tolua.initget(Ray) Ray.__index = function(t,k) local var = rawget(Ray, k) if var == nil then var = rawget(get, k) if var ~= nil then return var(t) end end return var end Ray.__call = function(t, direction, origin) return Ray.New(direction, origin) end function Ray.New(direction, origin) local ray = {} ray.direction = direction:Normalize() ray.origin = origin setmetatable(ray, Ray) return ray end function Ray:GetPoint(distance) local dir = self.direction * distance dir:Add(self.origin) return dir end function Ray:Get() local o = self.origin local d = self.direction return o.x, o.y, o.z, d.x, d.y, d.z end Ray.__tostring = function(self) return string.format("Origin:(%f,%f,%f),Dir:(%f,%f, %f)", self.origin.x, self.origin.y, self.origin.z, self.direction.x, self.direction.y, self.direction.z) end UnityEngine.Ray = Ray setmetatable(Ray, Ray) return Ray
1
0.556749
1
0.556749
game-dev
MEDIA
0.766509
game-dev
0.633795
1
0.633795
bearlikelion/BoomerShooter
5,084
Player/Player.gd
class_name Player extends CharacterBody3D signal shoot(origin: Vector3, normal: Vector3, gun_end_position: Vector3) signal weapon_changed(weapon_data: WeaponData) signal player_ready signal player_hurt signal player_died signal enemy_killed signal kills_changed @export var FPS_ARMS: Node3D @export var MOUSE_SENSITIVITY: float = 0.33 @export var TILT_LOWER_LIMIT: float = deg_to_rad(-90.0) @export var TILT_UPPER_LIMIT: float = deg_to_rad(90.0) @export var ANIMATIONPLAYER: AnimationPlayer @export var CAMERA_CONTROLLER: Camera3D @export var ROLL_ANGLE: float = 0.65 @export var ROLL_SPEED: int = 300 @export var WEAPON_DATA: WeaponData = null var health: int = 100 var kills: int = 0 var last_firing_time: int = 0 var _mouse_input: bool = false var _camera_rotation: Vector3 var _player_rotation: Vector3 var _mouse_rotation: Vector3 var _current_rotation: float var _rotation_input: float var _tilt_input: float # Get the gravity from the project settings to be synced with RigidBody nodes. # var gravity: float = ProjectSettings.get_setting("physics/3d/default_gravity") var gravity: float = 12.0 var been_hurt: bool = false var hurt_timer: Timer = Timer.new() @onready var aimcast: RayCast3D = %AimCast func _ready() -> void: Global.player = self Input.mouse_mode = Input.MOUSE_MODE_CAPTURED enemy_killed.connect(_on_enemy_killed) # Hurt Timer hurt_timer.wait_time = 1.0 hurt_timer.autostart = true hurt_timer.timeout.connect(_on_hurt_timer_timeout) hurt_timer.name = "HurtTimer" add_child(hurt_timer) player_ready.emit() func _physics_process(delta: float) -> void: update_camera(delta) CAMERA_CONTROLLER.rotation.z = _calc_roll(ROLL_ANGLE, ROLL_SPEED) * 2 func _input(event: InputEvent) -> void: if event.is_action_pressed("exit"): if Input.mouse_mode == Input.MOUSE_MODE_CAPTURED: Input.mouse_mode = Input.MOUSE_MODE_VISIBLE elif Input.mouse_mode == Input.MOUSE_MODE_VISIBLE: get_tree().quit() if event.is_action_pressed("attack"): if Input.mouse_mode == Input.MOUSE_MODE_VISIBLE: Input.mouse_mode = Input.MOUSE_MODE_CAPTURED func _unhandled_input(event: InputEvent) -> void: _mouse_input = event is InputEventMouseMotion and Input.get_mouse_mode() == Input.MOUSE_MODE_CAPTURED if _mouse_input: _rotation_input = -event.relative.x * MOUSE_SENSITIVITY _tilt_input = -event.relative.y * MOUSE_SENSITIVITY func update_camera(delta: float) -> void: _current_rotation = _rotation_input _mouse_rotation.x += _tilt_input * delta _mouse_rotation.x = clamp(_mouse_rotation.x, TILT_LOWER_LIMIT, TILT_UPPER_LIMIT) _mouse_rotation.y += _rotation_input * delta _player_rotation = Vector3(0.0,_mouse_rotation.y,0.0) _camera_rotation = Vector3(_mouse_rotation.x,0.0,0.0) CAMERA_CONTROLLER.transform.basis = Basis.from_euler(_camera_rotation) global_transform.basis = Basis.from_euler(_player_rotation) CAMERA_CONTROLLER.rotation.z = 0.0 _rotation_input = 0.0 _tilt_input = 0.0 func update_input(speed: float, acceleration: float, deceleration: float) -> void: var input_dir: Vector2 = Input.get_vector("move_left", "move_right", "move_forward", "move_backward") var direction: Vector3 = (transform.basis * Vector3(input_dir.x, 0, input_dir.y)).normalized() if direction: velocity.x = lerp(velocity.x, direction.x * speed, acceleration) velocity.z = lerp(velocity.z, direction.z * speed, acceleration) else: velocity.x = move_toward(velocity.x, 0, deceleration) velocity.z = move_toward(velocity.z, 0, deceleration) func update_gravity(delta: float) -> void: velocity.y -= gravity * delta func update_velocity() -> void: move_and_slide() # Returns a value for how much the Camera Mount should tilt to the side. # TODO Fix rotation side func _calc_roll(rollangle: float, rollspeed: float) -> float: if rollangle == 0.0 or rollspeed == 0: return 0 var side: float = velocity.dot(CAMERA_CONTROLLER.transform.basis.x) # print("Side: %s" % side) var roll_sign: float = 1.0 if side < 0.0 else -1.0 side = absf(side) var value: float = rollangle if (side < rollspeed): side = side * value / rollspeed else: side = value return side * roll_sign func set_weapon(weapon_data: WeaponData) -> void: # print("Weapon changed! %s" % str(weapon_data)) WEAPON_DATA = weapon_data weapon_changed.emit() func can_fire() -> bool: if FPS_ARMS.is_reloading: return false var shoot_time_diff: int = Time.get_ticks_msec() - last_firing_time if shoot_time_diff < WEAPON_DATA.fire_rate: return false return true func take_damage(damage: int) -> void: if !been_hurt: been_hurt = true health -= damage if !%OuchSound.playing: %OuchSound.play() if health <= 0: player_died.emit() else: player_hurt.emit() func _on_hurt_box_body_entered(body: Node3D) -> void: if body.owner.is_in_group("enemy"): take_damage(body.owner.damage) #print("Body name: %s" % body.name) #print("Body is enemy, player should take damage") func _on_hurt_timer_timeout() -> void: if been_hurt: been_hurt = false func _on_enemy_killed() -> void: kills += 1 kills_changed.emit()
1
0.93108
1
0.93108
game-dev
MEDIA
0.966052
game-dev
0.969301
1
0.969301
Laupetin/OpenAssetTools
2,424
tools/scripts/source_templating.lua
function useSourceTemplating(projectName) local projectFolder = path.join(ProjectFolder(), projectName) local templateFiles = os.matchfiles(path.join(projectFolder, "**.template")) local createdFiles = {} for i = 1, #templateFiles do local templateFile = templateFiles[i] local relativeTemplatePath = path.getrelative(projectFolder, templateFile) local relativeResultPath = path.replaceextension(relativeTemplatePath, "") local resultExtension = path.getextension(relativeResultPath) local data = io.readfile(templateFile) local gameOptionsStart, gameOptionsCount = string.find(data, "#options%s+GAME%s*%(") if gameOptionsStart == nil then error("Source template " .. relativeTemplatePath .. " must define an option called GAME") end local gameOptionsPos, gameOptionsLenPlusOne = string.find(data, "[%a%d%s,]+%)", gameOptionsStart + gameOptionsCount) if gameOptionsPos ~= gameOptionsStart + gameOptionsCount then error("Source template " .. relativeTemplatePath .. " must define an option called GAME") end local gameOptions = string.sub(data, gameOptionsPos, gameOptionsLenPlusOne - 1) local games = string.explode(gameOptions, ",%s*") files { templateFile } filter("files:" .. templateFile) buildmessage("Templating source file " .. relativeTemplatePath) buildinputs { TargetDirectoryBuildTools .. "/" .. ExecutableByOs('RawTemplater') } buildcommands { '"' .. TargetDirectoryBuildTools .. '/' .. ExecutableByOs('RawTemplater') .. '"' .. ' -o "%{prj.location}/"' .. " %{file.relpath}" } for i = 1, #games do local gameName = games[i] local outputFileName = path.replaceextension(path.replaceextension(relativeResultPath, "") .. gameName, resultExtension) local outputFile = "%{prj.location}/Game/" .. gameName .. "/" .. outputFileName table.insert(createdFiles, outputFile) buildoutputs { outputFile } end filter {} includedirs { "%{prj.location}" } files { createdFiles } RawTemplater:use() end end
1
0.840666
1
0.840666
game-dev
MEDIA
0.390058
game-dev
0.718808
1
0.718808
SkyblockerMod/Skyblocker
12,200
src/main/java/de/hysky/skyblocker/skyblock/dungeon/CroesusProfit.java
package de.hysky.skyblocker.skyblock.dungeon; import de.hysky.skyblocker.config.SkyblockerConfigManager; import de.hysky.skyblocker.utils.Constants; import de.hysky.skyblocker.utils.Formatters; import de.hysky.skyblocker.utils.ItemUtils; import de.hysky.skyblocker.utils.container.SimpleContainerSolver; import de.hysky.skyblocker.utils.container.TooltipAdder; import de.hysky.skyblocker.utils.render.gui.ColorHighlight; import it.unimi.dsi.fastutil.ints.Int2ObjectMap; import net.minecraft.item.ItemStack; import net.minecraft.item.Items; import net.minecraft.screen.slot.Slot; import net.minecraft.text.Text; import net.minecraft.text.TextColor; import net.minecraft.util.Formatting; import net.minecraft.util.Util; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; public class CroesusProfit extends SimpleContainerSolver implements TooltipAdder { public static CroesusProfit INSTANCE = new CroesusProfit(); private static final Pattern ESSENCE_PATTERN = Pattern.compile("(?<type>[A-Za-z]+) Essence x(?<amount>\\d+)"); public CroesusProfit() { super(".*The Catacombs - Flo.*"); } @Override public boolean isEnabled() { return SkyblockerConfigManager.get().dungeons.dungeonChestProfit.croesusProfit; } @Override public List<ColorHighlight> getColors(Int2ObjectMap<ItemStack> slots) { List<ColorHighlight> highlights = new ArrayList<>(); ItemStack bestChest = null, secondBestChest = null; double bestValue = 0, secondBestValue = 0; // If negative value of chest - it is out of the question double dungeonKeyPriceData = getItemPrice("DUNGEON_CHEST_KEY") * 2; // lesser ones are not worth the hassle for (Int2ObjectMap.Entry<ItemStack> entry : slots.int2ObjectEntrySet()) { ItemStack stack = entry.getValue(); if (stack.getName().getString().contains("Chest")) { double value = getChestValue(stack); if (value <= 0) continue; if (value > bestValue) { secondBestChest = bestChest; secondBestValue = bestValue; bestChest = stack; bestValue = value; } else if (value > secondBestValue) { secondBestChest = stack; secondBestValue = value; } } } for (Int2ObjectMap.Entry<ItemStack> entry : slots.int2ObjectEntrySet()) { ItemStack stack = entry.getValue(); if (stack != null) { if (stack.equals(bestChest)) { highlights.add(ColorHighlight.green(entry.getIntKey())); } else if (stack.equals(secondBestChest) && secondBestValue > dungeonKeyPriceData) { highlights.add(ColorHighlight.yellow(entry.getIntKey())); } } } return highlights; } @Override public void addToTooltip(@Nullable Slot focusedSlot, ItemStack stack, List<Text> lines) { if (focusedSlot == null || !focusedSlot.hasStack()) return; if (!focusedSlot.getStack().isOf(Items.PLAYER_HEAD)) return; double value = getChestValue(focusedSlot.getStack()); lines.add(Constants.PREFIX.get().append( Text.translatable("skyblocker.dungeons.croesusHelper.chestValue", Formatters.INTEGER_NUMBERS.format(value)) )); } @Override public int getPriority() { return 16; } private double getChestValue(@NotNull ItemStack chest) { double chestValue = 0; int chestPrice = 0; boolean processingContents = false; for (Text line : ItemUtils.getLore(chest)) { String lineString = line.getString(); if (lineString.contains("Contents")) { processingContents = true; continue; } else if (lineString.isEmpty()) { processingContents = false; } else if (lineString.contains("Coins") && !processingContents) { chestPrice = Integer.parseInt(lineString.replace(",", "").replaceAll("\\D", "")); } if (processingContents) { if (lineString.contains("Essence") && SkyblockerConfigManager.get().dungeons.dungeonChestProfit.includeEssence) { Matcher matcher = ESSENCE_PATTERN.matcher(lineString); if (matcher.matches()) { // add to chest value result of multiplying price of essence on it's amount chestValue += getItemPrice(("ESSENCE_" + matcher.group("type")).toUpperCase(Locale.ENGLISH)) * Integer.parseInt(matcher.group("amount")); } } else if (lineString.equals("Spirit") && line.getStyle().getColor() == TextColor.fromFormatting(Formatting.DARK_PURPLE)) { // TODO: make code like this to detect recombed gear (it can drop with 1% chance, according to wiki, tho I never saw any?) chestValue += getItemPrice("Spirit Epic"); } else { chestValue += getItemPrice(lineString); } } } return chestValue - chestPrice; } /** * @param itemName The item's display name or API Id * The API id is used for Essences and the Dungeon Chest Key. */ private double getItemPrice(String itemName) { return ItemUtils.getItemPrice(dungeonDropsNameToApiId.getOrDefault(itemName, itemName)).leftDouble(); } // I did a thing :( private final Map<String, String> dungeonDropsNameToApiId = Util.make(new HashMap<>(), map -> { map.put("Enchanted Book (Ultimate Jerry I)", "ENCHANTMENT_ULTIMATE_JERRY_1"); // ultimate books start map.put("Enchanted Book (Ultimate Jerry II)", "ENCHANTMENT_ULTIMATE_JERRY_2"); map.put("Enchanted Book (Ultimate Jerry III)", "ENCHANTMENT_ULTIMATE_JERRY_3"); map.put("Enchanted Book (Bank I)", "ENCHANTMENT_ULTIMATE_BANK_1"); map.put("Enchanted Book (Bank II)", "ENCHANTMENT_ULTIMATE_BANK_2"); map.put("Enchanted Book (Bank III)", "ENCHANTMENT_ULTIMATE_BANK_3"); map.put("Enchanted Book (Combo I)", "ENCHANTMENT_ULTIMATE_COMBO_1"); map.put("Enchanted Book (Combo II)", "ENCHANTMENT_ULTIMATE_COMBO_2"); map.put("Enchanted Book (No Pain No Gain I)", "ENCHANTMENT_ULTIMATE_NO_PAIN_NO_GAIN_1"); map.put("Enchanted Book (No Pain No Gain II)", "ENCHANTMENT_ULTIMATE_NO_PAIN_NO_GAIN_2"); map.put("Enchanted Book (Ultimate Wise I)", "ENCHANTMENT_ULTIMATE_WISE_1"); map.put("Enchanted Book (Ultimate Wise II)", "ENCHANTMENT_ULTIMATE_WISE_2"); map.put("Enchanted Book (Wisdom I)", "ENCHANTMENT_ULTIMATE_WISDOM_1"); map.put("Enchanted Book (Wisdom II)", "ENCHANTMENT_ULTIMATE_WISDOM_2"); map.put("Enchanted Book (Last Stand I)", "ENCHANTMENT_ULTIMATE_LAST_STAND_1"); map.put("Enchanted Book (Last Stand II)", "ENCHANTMENT_ULTIMATE_LAST_STAND_2"); map.put("Enchanted Book (Rend I)", "ENCHANTMENT_ULTIMATE_REND_1"); map.put("Enchanted Book (Rend II)", "ENCHANTMENT_ULTIMATE_REND_2"); map.put("Enchanted Book (Legion I)", "ENCHANTMENT_ULTIMATE_LEGION_1"); map.put("Enchanted Book (Swarm I)", "ENCHANTMENT_ULTIMATE_SWARM_1"); map.put("Enchanted Book (One For All I)", "ENCHANTMENT_ULTIMATE_ONE_FOR_ALL_1"); map.put("Enchanted Book (Soul Eater I)", "ENCHANTMENT_ULTIMATE_SOUL_EATER_1"); // ultimate books end map.put("Enchanted Book (Infinite Quiver VI)", "ENCHANTMENT_INFINITE_QUIVER_6"); // enchanted books start map.put("Enchanted Book (Infinite Quiver VII)", "ENCHANTMENT_INFINITE_QUIVER_7"); map.put("Enchanted Book (Feather Falling VI)", "ENCHANTMENT_FEATHER_FALLING_6"); map.put("Enchanted Book (Feather Falling VII)", "ENCHANTMENT_FEATHER_FALLING_7"); map.put("Enchanted Book (Rejuvenate I)", "ENCHANTMENT_REJUVENATE_1"); map.put("Enchanted Book (Rejuvenate II)", "ENCHANTMENT_REJUVENATE_2"); map.put("Enchanted Book (Rejuvenate III)", "ENCHANTMENT_REJUVENATE_3"); map.put("Enchanted Book (Overload I)", "ENCHANTMENT_OVERLOAD_1"); map.put("Enchanted Book (Lethality VI)", "ENCHANTMENT_LETHALITY_6"); map.put("Enchanted Book (Thunderlord VII)", "ENCHANTMENT_THUNDERLORD_7"); // enchanted books end map.put("Hot Potato Book", "HOT_POTATO_BOOK"); // HPB, FPB, Recomb (universal drops) map.put("Fuming Potato Book", "FUMING_POTATO_BOOK"); map.put("Recombobulator 3000", "RECOMBOBULATOR_3000"); map.put("Necromancer's Brooch", "NECROMANCER_BROOCH"); // F1 to F4 map.put("Bonzo's Staff", "BONZO_STAFF"); // F1 M1 map.put("Master Skull - Tier 1", "MASTER_SKULL_TIER_1"); map.put("Bonzo's Mask", "BONZO_MASK"); map.put("Balloon Snake", "BALLOON_SNAKE"); map.put("Red Nose", "RED_NOSE"); map.put("Red Scarf", "RED_SCARF"); // F2 M2 map.put("Adaptive Blade", "STONE_BLADE"); map.put("Master Skull - Tier 2", "MASTER_SKULL_TIER_2"); map.put("Adaptive Belt", "ADAPTIVE_BELT"); map.put("Scarf's Studies", "SCARF_STUDIES"); map.put("First Master Star", "FIRST_MASTER_STAR"); // F3 M3 map.put("Adaptive Helmet", "ADAPTIVE_HELMET"); map.put("Adaptive Chestplate", "ADAPTIVE_CHESTPLATE"); map.put("Adaptive Leggings", "ADAPTIVE_LEGGINGS"); map.put("Adaptive Boots", "ADAPTIVE_BOOTS"); map.put("Master Skull - Tier 3", "MASTER_SKULL_TIER_3"); map.put("Suspicious Vial", "SUSPICIOUS_VIAL"); map.put("Spirit Sword", "SPIRIT_SWORD"); // F4 M4 map.put("Spirit Shortbow", "ITEM_SPIRIT_BOW"); map.put("Spirit Boots", "THORNS_BOOTS"); map.put("Spirit", "LVL_1_LEGENDARY_SPIRIT"); // Spirit pet (Legendary) map.put("Spirit Epic", "LVL_1_EPIC_SPIRIT"); map.put("Second Master Star", "SECOND_MASTER_STAR"); map.put("Spirit Wing", "SPIRIT_WING"); map.put("Spirit Bone", "SPIRIT_BONE"); map.put("Spirit Stone", "SPIRIT_DECOY"); map.put("Shadow Fury", "SHADOW_FURY"); // F5 M5 map.put("Last Breath", "LAST_BREATH"); map.put("Third Master Star", "THIRD_MASTER_STAR"); map.put("Warped Stone", "AOTE_STONE"); map.put("Livid Dagger", "LIVID_DAGGER"); map.put("Shadow Assassin Helmet", "SHADOW_ASSASSIN_HELMET"); map.put("Shadow Assassin Chestplate", "SHADOW_ASSASSIN_CHESTPLATE"); map.put("Shadow Assassin Leggings", "SHADOW_ASSASSIN_LEGGINGS"); map.put("Shadow Assassin Boots", "SHADOW_ASSASSIN_BOOTS"); map.put("Shadow Assassin Cloak", "SHADOW_ASSASSIN_CLOAK"); map.put("Master Skull - Tier 4", "MASTER_SKULL_TIER_4"); map.put("Dark Orb", "DARK_ORB"); map.put("Precursor Eye", "PRECURSOR_EYE"); // F6 M6 map.put("Giant's Sword", "GIANTS_SWORD"); map.put("Necromancer Lord Helmet", "NECROMANCER_LORD_HELMET"); map.put("Necromancer Lord Chestplate", "NECROMANCER_LORD_CHESTPLATE"); map.put("Necromancer Lord Leggings", "NECROMANCER_LORD_LEGGINGS"); map.put("Necromancer Lord Boots", "NECROMANCER_LORD_BOOTS"); map.put("Fourth Master Star", "FOURTH_MASTER_STAR"); map.put("Summoning Ring", "SUMMONING_RING"); map.put("Fel Skull", "FEL_SKULL"); map.put("Necromancer Sword", "NECROMANCER_SWORD"); map.put("Soulweaver Gloves", "SOULWEAVER_GLOVES"); map.put("Sadan's Brooch", "SADAN_BROOCH"); map.put("Giant Tooth", "GIANT_TOOTH"); map.put("Precursor Gear", "PRECURSOR_GEAR"); // F7 M7 map.put("Necron Dye", "DYE_NECRON"); map.put("Storm the Fish", "STORM_THE_FISH"); map.put("Maxor the Fish", "MAXOR_THE_FISH"); map.put("Goldor the Fish", "GOLDOR_THE_FISH"); map.put("Dark Claymore", "DARK_CLAYMORE"); map.put("Necron's Handle", "NECRON_HANDLE"); map.put("Master Skull - Tier 5", "MASTER_SKULL_TIER_5"); map.put("Shadow Warp", "SHADOW_WARP_SCROLL"); map.put("Wither Shield", "WITHER_SHIELD_SCROLL"); map.put("Implosion", "IMPLOSION_SCROLL"); map.put("Fifth Master Star", "FIFTH_MASTER_STAR"); map.put("Auto Recombobulator", "AUTO_RECOMBOBULATOR"); map.put("Wither Helmet", "WITHER_HELMET"); map.put("Wither Chestplate", "WITHER_CHESTPLATE"); map.put("Wither Leggings", "WITHER_LEGGINGS"); map.put("Wither Boots", "WITHER_BOOTS"); map.put("Wither Catalyst", "WITHER_CATALYST"); map.put("Wither Cloak Sword", "WITHER_CLOAK"); map.put("Wither Blood", "WITHER_BLOOD"); map.put("Shiny Wither Helmet", "SHINY_WITHER_HELMET"); // M7 shiny drops map.put("Shiny Wither Chestplate", "SHINY_WITHER_CHESTPLATE"); map.put("Shiny Wither Leggings", "SHINY_WITHER_LEGGINGS"); map.put("Shiny Wither Boots", "SHINY_WITHER_BOOTS"); map.put("Shiny Necron's Handle", "SHINY_NECRON_HANDLE"); // cool thing map.put("Dungeon Disc", "DUNGEON_DISC_1"); map.put("Clown Disc", "DUNGEON_DISC_2"); map.put("Watcher Disc", "DUNGEON_DISC_3"); map.put("Old Disc", "DUNGEON_DISC_4"); map.put("Necron Disc", "DUNGEON_DISC_5"); map.put("Wither", "SHARD_WITHER"); map.put("Apex Dragon", "SHARD_APEX_DRAGON"); map.put("Power Dragon", "SHARD_POWER_DRAGON"); }); }
1
0.873681
1
0.873681
game-dev
MEDIA
0.831393
game-dev
0.97883
1
0.97883
icsharpcode/NRefactory
66,864
ICSharpCode.NRefactory.CSharp/Parser/mcs/import.cs
// // import.cs: System.Reflection conversions // // Authors: Marek Safar (marek.safar@gmail.com) // // Dual licensed under the terms of the MIT X11 or GNU GPL // // Copyright 2009-2011 Novell, Inc // Copyright 2011-2012 Xamarin, Inc (http://www.xamarin.com) // using System; using System.Runtime.CompilerServices; using System.Linq; using System.Collections.Generic; #if STATIC using MetaType = IKVM.Reflection.Type; using IKVM.Reflection; using IKVM.Reflection.Emit; #else using MetaType = System.Type; using System.Reflection; using System.Reflection.Emit; #endif namespace ICSharpCode.NRefactory.MonoCSharp { public abstract class MetadataImporter { // // Dynamic types reader with additional logic to reconstruct a dynamic // type using DynamicAttribute values // protected struct DynamicTypeReader { static readonly bool[] single_attribute = { true }; public int Position; bool[] flags; // There is no common type for CustomAttributeData and we cannot // use ICustomAttributeProvider object provider; // // A member provider which can be used to get CustomAttributeData // public DynamicTypeReader (object provider) { Position = 0; flags = null; this.provider = provider; } // // Returns true when object at local position has dynamic attribute flag // public bool IsDynamicObject () { if (provider != null) ReadAttribute (); return flags != null && Position < flags.Length && flags[Position]; } // // Returns true when DynamicAttribute exists // public bool HasDynamicAttribute () { if (provider != null) ReadAttribute (); return flags != null; } IList<CustomAttributeData> GetCustomAttributes () { var mi = provider as MemberInfo; if (mi != null) return CustomAttributeData.GetCustomAttributes (mi); var pi = provider as ParameterInfo; if (pi != null) return CustomAttributeData.GetCustomAttributes (pi); provider = null; return null; } void ReadAttribute () { var cad = GetCustomAttributes (); if (cad == null) { return; } if (cad.Count > 0) { foreach (var ca in cad) { var dt = ca.Constructor.DeclaringType; if (dt.Name != "DynamicAttribute" || dt.Namespace != CompilerServicesNamespace) continue; if (ca.ConstructorArguments.Count == 0) { flags = single_attribute; break; } var arg_type = ca.ConstructorArguments[0].ArgumentType; if (arg_type.IsArray && MetaType.GetTypeCode (arg_type.GetElementType ()) == TypeCode.Boolean) { var carg = (IList<CustomAttributeTypedArgument>) ca.ConstructorArguments[0].Value; flags = new bool[carg.Count]; for (int i = 0; i < flags.Length; ++i) { if (MetaType.GetTypeCode (carg[i].ArgumentType) == TypeCode.Boolean) flags[i] = (bool) carg[i].Value; } break; } } } provider = null; } } protected readonly Dictionary<MetaType, TypeSpec> import_cache; protected readonly Dictionary<MetaType, TypeSpec> compiled_types; protected readonly Dictionary<Assembly, IAssemblyDefinition> assembly_2_definition; protected readonly ModuleContainer module; public static readonly string CompilerServicesNamespace = "System.Runtime.CompilerServices"; protected MetadataImporter (ModuleContainer module) { this.module = module; import_cache = new Dictionary<MetaType, TypeSpec> (1024, ReferenceEquality<MetaType>.Default); compiled_types = new Dictionary<MetaType, TypeSpec> (40, ReferenceEquality<MetaType>.Default); assembly_2_definition = new Dictionary<Assembly, IAssemblyDefinition> (ReferenceEquality<Assembly>.Default); IgnorePrivateMembers = true; } #region Properties public ICollection<IAssemblyDefinition> Assemblies { get { return assembly_2_definition.Values; } } public bool IgnorePrivateMembers { get; set; } #endregion public abstract void AddCompiledType (TypeBuilder builder, TypeSpec spec); protected abstract MemberKind DetermineKindFromBaseType (MetaType baseType); protected abstract bool HasVolatileModifier (MetaType[] modifiers); public FieldSpec CreateField (FieldInfo fi, TypeSpec declaringType) { Modifiers mod; var fa = fi.Attributes; switch (fa & FieldAttributes.FieldAccessMask) { case FieldAttributes.Public: mod = Modifiers.PUBLIC; break; case FieldAttributes.Assembly: mod = Modifiers.INTERNAL; break; case FieldAttributes.Family: mod = Modifiers.PROTECTED; break; case FieldAttributes.FamORAssem: mod = Modifiers.PROTECTED | Modifiers.INTERNAL; break; default: // Ignore private fields (even for error reporting) to not require extra dependencies if ((IgnorePrivateMembers && !declaringType.IsStruct) || HasAttribute (CustomAttributeData.GetCustomAttributes (fi), "CompilerGeneratedAttribute", CompilerServicesNamespace)) return null; mod = Modifiers.PRIVATE; break; } TypeSpec field_type; try { field_type = ImportType (fi.FieldType, new DynamicTypeReader (fi)); // // Private field has private type which is not fixed buffer // if (field_type == null) return null; } catch (Exception e) { // TODO: I should construct fake TypeSpec based on TypeRef signature // but there is no way to do it with System.Reflection throw new InternalErrorException (e, "Cannot import field `{0}.{1}' referenced in assembly `{2}'", declaringType.GetSignatureForError (), fi.Name, declaringType.MemberDefinition.DeclaringAssembly); } var definition = new ImportedMemberDefinition (fi, field_type, this); if ((fa & FieldAttributes.Literal) != 0) { Constant c = field_type.Kind == MemberKind.MissingType ? new NullConstant (InternalType.ErrorType, Location.Null) : Constant.CreateConstantFromValue (field_type, fi.GetRawConstantValue (), Location.Null); return new ConstSpec (declaringType, definition, field_type, fi, mod, c); } if ((fa & FieldAttributes.InitOnly) != 0) { if (field_type.BuiltinType == BuiltinTypeSpec.Type.Decimal) { var dc = ReadDecimalConstant (CustomAttributeData.GetCustomAttributes (fi)); if (dc != null) return new ConstSpec (declaringType, definition, field_type, fi, mod, dc); } mod |= Modifiers.READONLY; } else { var req_mod = fi.GetRequiredCustomModifiers (); if (req_mod.Length > 0 && HasVolatileModifier (req_mod)) mod |= Modifiers.VOLATILE; } if ((fa & FieldAttributes.Static) != 0) { mod |= Modifiers.STATIC; } else { // Fixed buffers cannot be static if (declaringType.IsStruct && field_type.IsStruct && field_type.IsNested && HasAttribute (CustomAttributeData.GetCustomAttributes (fi), "FixedBufferAttribute", CompilerServicesNamespace)) { // TODO: Sanity check on field_type (only few types are allowed) var element_field = CreateField (fi.FieldType.GetField (FixedField.FixedElementName), declaringType); return new FixedFieldSpec (module, declaringType, definition, fi, element_field, mod); } } return new FieldSpec (declaringType, definition, field_type, fi, mod); } public EventSpec CreateEvent (EventInfo ei, TypeSpec declaringType, MethodSpec add, MethodSpec remove) { add.IsAccessor = true; remove.IsAccessor = true; if (add.Modifiers != remove.Modifiers) throw new NotImplementedException ("Different accessor modifiers " + ei.Name); var event_type = ImportType (ei.EventHandlerType, new DynamicTypeReader (ei)); var definition = new ImportedMemberDefinition (ei, event_type, this); return new EventSpec (declaringType, definition, event_type, add.Modifiers, add, remove); } TypeParameterSpec[] CreateGenericParameters (MetaType type, TypeSpec declaringType) { var tparams = type.GetGenericArguments (); int parent_owned_count; if (type.IsNested) { parent_owned_count = type.DeclaringType.GetGenericArguments ().Length; // // System.Reflection duplicates parent type parameters for each // nested type with slightly modified properties (eg. different owner) // This just makes things more complicated (think of cloned constraints) // therefore we remap any nested type owned by parent using `type_cache' // to the single TypeParameterSpec // if (declaringType != null && parent_owned_count > 0) { int read_count = 0; while (read_count != parent_owned_count) { var tparams_count = declaringType.Arity; if (tparams_count != 0) { var parent_tp = declaringType.MemberDefinition.TypeParameters; read_count += tparams_count; for (int i = 0; i < tparams_count; i++) { import_cache.Add (tparams[parent_owned_count - read_count + i], parent_tp[i]); } } declaringType = declaringType.DeclaringType; } } } else { parent_owned_count = 0; } if (tparams.Length - parent_owned_count == 0) return null; return CreateGenericParameters (parent_owned_count, tparams); } TypeParameterSpec[] CreateGenericParameters (int first, MetaType[] tparams) { var tspec = new TypeParameterSpec[tparams.Length - first]; for (int pos = first; pos < tparams.Length; ++pos) { var type = tparams[pos]; int index = pos - first; tspec[index] = (TypeParameterSpec) CreateType (type, new DynamicTypeReader (), false); } return tspec; } TypeSpec[] CreateGenericArguments (int first, MetaType[] tparams, DynamicTypeReader dtype) { ++dtype.Position; var tspec = new TypeSpec [tparams.Length - first]; for (int pos = first; pos < tparams.Length; ++pos) { var type = tparams[pos]; int index = pos - first; TypeSpec spec; if (type.HasElementType) { var element = type.GetElementType (); ++dtype.Position; spec = ImportType (element, dtype); if (!type.IsArray) { throw new NotImplementedException ("Unknown element type " + type.ToString ()); } spec = ArrayContainer.MakeType (module, spec, type.GetArrayRank ()); } else { spec = CreateType (type, dtype, true); // // We treat nested generic types as inflated internally where // reflection uses type definition // // class A<T> { // IFoo<A<T>> foo; // A<T> is definition in this case // } // if (!IsMissingType (type) && type.IsGenericTypeDefinition) { var start_pos = spec.DeclaringType == null ? 0 : spec.DeclaringType.MemberDefinition.TypeParametersCount; var targs = CreateGenericArguments (start_pos, type.GetGenericArguments (), dtype); spec = spec.MakeGenericType (module, targs); } } if (spec == null) return null; ++dtype.Position; tspec[index] = spec; } return tspec; } public MethodSpec CreateMethod (MethodBase mb, TypeSpec declaringType) { Modifiers mod = ReadMethodModifiers (mb, declaringType); TypeParameterSpec[] tparams; var parameters = CreateParameters (declaringType, mb.GetParameters (), mb); if (mb.IsGenericMethod) { if (!mb.IsGenericMethodDefinition) throw new NotSupportedException ("assert"); tparams = CreateGenericParameters (0, mb.GetGenericArguments ()); } else { tparams = null; } MemberKind kind; TypeSpec returnType; if (mb.MemberType == MemberTypes.Constructor) { kind = MemberKind.Constructor; returnType = module.Compiler.BuiltinTypes.Void; } else { // // Detect operators and destructors // string name = mb.Name; kind = MemberKind.Method; if (tparams == null && !mb.DeclaringType.IsInterface && name.Length > 6) { if ((mod & (Modifiers.STATIC | Modifiers.PUBLIC)) == (Modifiers.STATIC | Modifiers.PUBLIC)) { if (name[2] == '_' && name[1] == 'p' && name[0] == 'o' && (mb.Attributes & MethodAttributes.SpecialName) != 0) { var op_type = Operator.GetType (name); if (op_type.HasValue && parameters.Count > 0 && parameters.Count < 3) { kind = MemberKind.Operator; } } } else if (parameters.IsEmpty && name == Destructor.MetadataName) { kind = MemberKind.Destructor; if (declaringType.BuiltinType == BuiltinTypeSpec.Type.Object) { mod &= ~Modifiers.OVERRIDE; mod |= Modifiers.VIRTUAL; } } } var mi = (MethodInfo) mb; returnType = ImportType (mi.ReturnType, new DynamicTypeReader (mi.ReturnParameter)); // Cannot set to OVERRIDE without full hierarchy checks // this flag indicates that the method could be override // but further validation is needed if ((mod & Modifiers.OVERRIDE) != 0) { bool is_real_override = false; if (kind == MemberKind.Method && declaringType.BaseType != null) { var btype = declaringType.BaseType; if (IsOverrideMethodBaseTypeAccessible (btype)) { var filter = MemberFilter.Method (name, tparams != null ? tparams.Length : 0, parameters, null); var candidate = MemberCache.FindMember (btype, filter, BindingRestriction.None); // // For imported class method do additional validation to be sure that metadata // override flag was correct // // Difference between protected internal and protected is ok // const Modifiers conflict_mask = Modifiers.AccessibilityMask & ~Modifiers.INTERNAL; if (candidate != null && (candidate.Modifiers & conflict_mask) == (mod & conflict_mask) && !candidate.IsStatic) { is_real_override = true; } } } if (!is_real_override) { mod &= ~Modifiers.OVERRIDE; if ((mod & Modifiers.SEALED) != 0) mod &= ~Modifiers.SEALED; else mod |= Modifiers.VIRTUAL; } } else if (parameters.HasExtensionMethodType) { mod |= Modifiers.METHOD_EXTENSION; } } IMethodDefinition definition; if (tparams != null) { var gmd = new ImportedGenericMethodDefinition ((MethodInfo) mb, returnType, parameters, tparams, this); foreach (var tp in gmd.TypeParameters) { ImportTypeParameterTypeConstraints (tp, tp.GetMetaInfo ()); } definition = gmd; } else { definition = new ImportedMethodDefinition (mb, returnType, parameters, this); } MethodSpec ms = new MethodSpec (kind, declaringType, definition, returnType, parameters, mod); if (tparams != null) ms.IsGeneric = true; return ms; } bool IsOverrideMethodBaseTypeAccessible (TypeSpec baseType) { switch (baseType.Modifiers & Modifiers.AccessibilityMask) { case Modifiers.PUBLIC: return true; case Modifiers.INTERNAL: // // Check whether imported method in base type is accessible from compiled // context // return baseType.MemberDefinition.IsInternalAsPublic (module.DeclaringAssembly); case Modifiers.PRIVATE: return false; default: // protected // protected internal // // Method accessibility checks will be done later based on context // where the method is called (CS0122 error will be reported for inaccessible) // return true; } } // // Imports System.Reflection parameters // AParametersCollection CreateParameters (TypeSpec parent, ParameterInfo[] pi, MethodBase method) { int varargs = method != null && (method.CallingConvention & CallingConventions.VarArgs) != 0 ? 1 : 0; if (pi.Length == 0 && varargs == 0) return ParametersCompiled.EmptyReadOnlyParameters; TypeSpec[] types = new TypeSpec[pi.Length + varargs]; IParameterData[] par = new IParameterData[pi.Length + varargs]; bool is_params = false; for (int i = 0; i < pi.Length; i++) { ParameterInfo p = pi[i]; Parameter.Modifier mod = 0; Expression default_value = null; if (p.ParameterType.IsByRef) { if ((p.Attributes & (ParameterAttributes.Out | ParameterAttributes.In)) == ParameterAttributes.Out) mod = Parameter.Modifier.OUT; else mod = Parameter.Modifier.REF; // // Strip reference wrapping // var el = p.ParameterType.GetElementType (); types[i] = ImportType (el, new DynamicTypeReader (p)); // TODO: 1-based positio to be csc compatible } else if (i == 0 && method.IsStatic && (parent.Modifiers & Modifiers.METHOD_EXTENSION) != 0 && HasAttribute (CustomAttributeData.GetCustomAttributes (method), "ExtensionAttribute", CompilerServicesNamespace)) { mod = Parameter.Modifier.This; types[i] = ImportType (p.ParameterType, new DynamicTypeReader (p)); } else { types[i] = ImportType (p.ParameterType, new DynamicTypeReader (p)); if (i >= pi.Length - 2 && types[i] is ArrayContainer) { if (HasAttribute (CustomAttributeData.GetCustomAttributes (p), "ParamArrayAttribute", "System")) { mod = Parameter.Modifier.PARAMS; is_params = true; } } if (!is_params && p.IsOptional) { object value = p.RawDefaultValue; var ptype = types[i]; if ((p.Attributes & ParameterAttributes.HasDefault) != 0 && ptype.Kind != MemberKind.TypeParameter && (value != null || TypeSpec.IsReferenceType (ptype))) { if (value == null) { default_value = Constant.CreateConstantFromValue (ptype, null, Location.Null); } else { default_value = ImportParameterConstant (value); if (ptype.IsEnum) { default_value = new EnumConstant ((Constant) default_value, ptype); } } var attrs = CustomAttributeData.GetCustomAttributes (p); for (int ii = 0; ii < attrs.Count; ++ii) { var attr = attrs[ii]; var dt = attr.Constructor.DeclaringType; if (dt.Namespace != CompilerServicesNamespace) continue; if (dt.Name == "CallerLineNumberAttribute" && (ptype.BuiltinType == BuiltinTypeSpec.Type.Int || Convert.ImplicitNumericConversionExists (module.Compiler.BuiltinTypes.Int, ptype))) mod |= Parameter.Modifier.CallerLineNumber; else if (dt.Name == "CallerFilePathAttribute" && Convert.ImplicitReferenceConversionExists (module.Compiler.BuiltinTypes.String, ptype)) mod |= Parameter.Modifier.CallerFilePath; else if (dt.Name == "CallerMemberNameAttribute" && Convert.ImplicitReferenceConversionExists (module.Compiler.BuiltinTypes.String, ptype)) mod |= Parameter.Modifier.CallerMemberName; } } else if (value == Missing.Value) { default_value = EmptyExpression.MissingValue; } else if (value == null) { default_value = new DefaultValueExpression (new TypeExpression (ptype, Location.Null), Location.Null); } else if (ptype.BuiltinType == BuiltinTypeSpec.Type.Decimal) { default_value = ImportParameterConstant (value); } } } par[i] = new ParameterData (p.Name, mod, default_value); } if (varargs != 0) { par[par.Length - 1] = new ArglistParameter (Location.Null); types[types.Length - 1] = InternalType.Arglist; } return method != null ? new ParametersImported (par, types, varargs != 0, is_params) : new ParametersImported (par, types, is_params); } // // Returns null when the property is not valid C# property // public PropertySpec CreateProperty (PropertyInfo pi, TypeSpec declaringType, MethodSpec get, MethodSpec set) { Modifiers mod = 0; AParametersCollection param = null; TypeSpec type = null; if (get != null) { mod = get.Modifiers; param = get.Parameters; type = get.ReturnType; } bool is_valid_property = true; if (set != null) { if (set.ReturnType.Kind != MemberKind.Void) is_valid_property = false; var set_param_count = set.Parameters.Count - 1; if (set_param_count < 0) { set_param_count = 0; is_valid_property = false; } var set_type = set.Parameters.Types[set_param_count]; if (mod == 0) { AParametersCollection set_based_param; if (set_param_count == 0) { set_based_param = ParametersCompiled.EmptyReadOnlyParameters; } else { // // Create indexer parameters based on setter method parameters (the last parameter has to be removed) // var data = new IParameterData[set_param_count]; var types = new TypeSpec[set_param_count]; Array.Copy (set.Parameters.FixedParameters, data, set_param_count); Array.Copy (set.Parameters.Types, types, set_param_count); set_based_param = new ParametersImported (data, types, set.Parameters.HasParams); } mod = set.Modifiers; param = set_based_param; type = set_type; } else { if (set_param_count != get.Parameters.Count) is_valid_property = false; if (get.ReturnType != set_type) is_valid_property = false; // Possible custom accessor modifiers if ((mod & Modifiers.AccessibilityMask) != (set.Modifiers & Modifiers.AccessibilityMask)) { var get_acc = mod & Modifiers.AccessibilityMask; if (get_acc != Modifiers.PUBLIC) { var set_acc = set.Modifiers & Modifiers.AccessibilityMask; // If the accessor modifiers are not same, do extra restriction checks if (get_acc != set_acc) { var get_restr = ModifiersExtensions.IsRestrictedModifier (get_acc, set_acc); var set_restr = ModifiersExtensions.IsRestrictedModifier (set_acc, get_acc); if (get_restr && set_restr) { is_valid_property = false; // Neither is more restrictive } if (get_restr) { mod &= ~Modifiers.AccessibilityMask; mod |= set_acc; } } } } } } PropertySpec spec = null; if (!param.IsEmpty) { if (is_valid_property) { var index_name = declaringType.MemberDefinition.GetAttributeDefaultMember (); if (index_name == null) { is_valid_property = false; } else { if (get != null) { if (get.IsStatic) is_valid_property = false; if (get.Name.IndexOf (index_name, StringComparison.Ordinal) != 4) is_valid_property = false; } if (set != null) { if (set.IsStatic) is_valid_property = false; if (set.Name.IndexOf (index_name, StringComparison.Ordinal) != 4) is_valid_property = false; } } if (is_valid_property) { spec = new IndexerSpec (declaringType, new ImportedParameterMemberDefinition (pi, type, param, this), type, param, pi, mod); } else if (declaringType.MemberDefinition.IsComImport && param.FixedParameters[0].HasDefaultValue) { // // Enables support for properties with parameters (must have default value) of COM-imported types // is_valid_property = true; for (int i = 0; i < param.FixedParameters.Length; ++i) { if (!param.FixedParameters[i].HasDefaultValue) { is_valid_property = false; break; } } } } } if (spec == null) spec = new PropertySpec (MemberKind.Property, declaringType, new ImportedMemberDefinition (pi, type, this), type, pi, mod); if (!is_valid_property) { spec.IsNotCSharpCompatible = true; return spec; } if (set != null) spec.Set = set; if (get != null) spec.Get = get; return spec; } public TypeSpec CreateType (MetaType type) { return CreateType (type, new DynamicTypeReader (), true); } public TypeSpec CreateNestedType (MetaType type, TypeSpec declaringType) { return CreateType (type, declaringType, new DynamicTypeReader (type), false); } TypeSpec CreateType (MetaType type, DynamicTypeReader dtype, bool canImportBaseType) { TypeSpec declaring_type; if (type.IsNested && !type.IsGenericParameter) declaring_type = CreateType (type.DeclaringType, new DynamicTypeReader (type.DeclaringType), true); else declaring_type = null; return CreateType (type, declaring_type, dtype, canImportBaseType); } protected TypeSpec CreateType (MetaType type, TypeSpec declaringType, DynamicTypeReader dtype, bool canImportBaseType) { TypeSpec spec; if (import_cache.TryGetValue (type, out spec)) { if (spec.BuiltinType == BuiltinTypeSpec.Type.Object) { if (dtype.IsDynamicObject ()) return module.Compiler.BuiltinTypes.Dynamic; return spec; } if (!spec.IsGeneric || type.IsGenericTypeDefinition) return spec; if (!dtype.HasDynamicAttribute ()) return spec; // We've found same object in the cache but this one has a dynamic custom attribute // and it's most likely dynamic version of same type IFoo<object> agains IFoo<dynamic> // Do type resolve process again in that case // TODO: Handle cases where they still unify } if (IsMissingType (type)) { spec = new TypeSpec (MemberKind.MissingType, declaringType, new ImportedTypeDefinition (type, this), type, Modifiers.PUBLIC); spec.MemberCache = MemberCache.Empty; import_cache.Add (type, spec); return spec; } if (type.IsGenericType && !type.IsGenericTypeDefinition) { var type_def = type.GetGenericTypeDefinition (); // Generic type definition can also be forwarded if (compiled_types.TryGetValue (type_def, out spec)) return spec; var targs = CreateGenericArguments (0, type.GetGenericArguments (), dtype); if (targs == null) return null; if (declaringType == null) { // Simple case, no nesting spec = CreateType (type_def, null, new DynamicTypeReader (), canImportBaseType); spec = spec.MakeGenericType (module, targs); } else { // // Nested type case, converting .NET types like // A`1.B`1.C`1<int, long, string> to typespec like // A<int>.B<long>.C<string> // var nested_hierarchy = new List<TypeSpec> (); while (declaringType.IsNested) { nested_hierarchy.Add (declaringType); declaringType = declaringType.DeclaringType; } int targs_pos = 0; if (declaringType.Arity > 0) { spec = declaringType.MakeGenericType (module, targs.Skip (targs_pos).Take (declaringType.Arity).ToArray ()); targs_pos = spec.Arity; } else { spec = declaringType; } for (int i = nested_hierarchy.Count; i != 0; --i) { var t = nested_hierarchy [i - 1]; if (t.Kind == MemberKind.MissingType) spec = t; else spec = MemberCache.FindNestedType (spec, t.Name, t.Arity); if (t.Arity > 0) { spec = spec.MakeGenericType (module, targs.Skip (targs_pos).Take (spec.Arity).ToArray ()); targs_pos += t.Arity; } } if (spec.Kind == MemberKind.MissingType) { spec = new TypeSpec (MemberKind.MissingType, spec, new ImportedTypeDefinition (type_def, this), type_def, Modifiers.PUBLIC); spec.MemberCache = MemberCache.Empty; } else { if ((type_def.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && IgnorePrivateMembers) return null; string name = type.Name; int index = name.IndexOf ('`'); if (index > 0) name = name.Substring (0, index); spec = MemberCache.FindNestedType (spec, name, targs.Length - targs_pos); if (spec.Arity > 0) { spec = spec.MakeGenericType (module, targs.Skip (targs_pos).ToArray ()); } } } // Don't add generic type with dynamic arguments, they can interfere with same type // using object type arguments if (!spec.HasDynamicElement) { // Add to reading cache to speed up reading if (!import_cache.ContainsKey (type)) import_cache.Add (type, spec); } return spec; } Modifiers mod; MemberKind kind; var ma = type.Attributes; switch (ma & TypeAttributes.VisibilityMask) { case TypeAttributes.Public: case TypeAttributes.NestedPublic: mod = Modifiers.PUBLIC; break; case TypeAttributes.NestedPrivate: mod = Modifiers.PRIVATE; break; case TypeAttributes.NestedFamily: mod = Modifiers.PROTECTED; break; case TypeAttributes.NestedFamORAssem: mod = Modifiers.PROTECTED | Modifiers.INTERNAL; break; default: mod = Modifiers.INTERNAL; break; } if ((ma & TypeAttributes.Interface) != 0) { kind = MemberKind.Interface; } else if (type.IsGenericParameter) { kind = MemberKind.TypeParameter; } else { var base_type = type.BaseType; if (base_type == null || (ma & TypeAttributes.Abstract) != 0) { kind = MemberKind.Class; } else { kind = DetermineKindFromBaseType (base_type); if (kind == MemberKind.Struct || kind == MemberKind.Delegate) { mod |= Modifiers.SEALED; } } if (kind == MemberKind.Class) { if ((ma & TypeAttributes.Sealed) != 0) { if ((ma & TypeAttributes.Abstract) != 0) mod |= Modifiers.STATIC; else mod |= Modifiers.SEALED; } else if ((ma & TypeAttributes.Abstract) != 0) { mod |= Modifiers.ABSTRACT; } } } var definition = new ImportedTypeDefinition (type, this); TypeSpec pt; if (kind == MemberKind.Enum) { const BindingFlags underlying_member = BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; var type_members = type.GetFields (underlying_member); foreach (var type_member in type_members) { spec = new EnumSpec (declaringType, definition, CreateType (type_member.FieldType), type, mod); break; } if (spec == null) kind = MemberKind.Class; } else if (kind == MemberKind.TypeParameter) { spec = CreateTypeParameter (type, declaringType); } else if (type.IsGenericTypeDefinition) { definition.TypeParameters = CreateGenericParameters (type, declaringType); } else if (compiled_types.TryGetValue (type, out pt)) { // // Same type was found in inside compiled types. It's // either build-in type or forward referenced typed // which point into just compiled assembly. // spec = pt; BuiltinTypeSpec bts = pt as BuiltinTypeSpec; if (bts != null) bts.SetDefinition (definition, type, mod); } if (spec == null) spec = new TypeSpec (kind, declaringType, definition, type, mod); import_cache.Add (type, spec); if (kind == MemberKind.TypeParameter) { if (canImportBaseType) ImportTypeParameterTypeConstraints ((TypeParameterSpec) spec, type); return spec; } // // Two stage setup as the base type can be inflated declaring type or // another nested type inside same declaring type which has not been // loaded, therefore we can import a base type of nested types once // the types have been imported // if (canImportBaseType) ImportTypeBase (spec, type); return spec; } public IAssemblyDefinition GetAssemblyDefinition (Assembly assembly) { IAssemblyDefinition found; if (!assembly_2_definition.TryGetValue (assembly, out found)) { // This can happen in dynamic context only var def = new ImportedAssemblyDefinition (assembly); assembly_2_definition.Add (assembly, def); def.ReadAttributes (); found = def; } return found; } public void ImportTypeBase (MetaType type) { TypeSpec spec = import_cache[type]; if (spec != null) ImportTypeBase (spec, type); } TypeParameterSpec CreateTypeParameter (MetaType type, TypeSpec declaringType) { Variance variance; switch (type.GenericParameterAttributes & GenericParameterAttributes.VarianceMask) { case GenericParameterAttributes.Covariant: variance = Variance.Covariant; break; case GenericParameterAttributes.Contravariant: variance = Variance.Contravariant; break; default: variance = Variance.None; break; } SpecialConstraint special = SpecialConstraint.None; var import_special = type.GenericParameterAttributes & GenericParameterAttributes.SpecialConstraintMask; if ((import_special & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0) { special |= SpecialConstraint.Struct; } else if ((import_special & GenericParameterAttributes.DefaultConstructorConstraint) != 0) { special = SpecialConstraint.Constructor; } if ((import_special & GenericParameterAttributes.ReferenceTypeConstraint) != 0) { special |= SpecialConstraint.Class; } TypeParameterSpec spec; var def = new ImportedTypeParameterDefinition (type, this); if (type.DeclaringMethod != null) { spec = new TypeParameterSpec (type.GenericParameterPosition, def, special, variance, type); } else { spec = new TypeParameterSpec (declaringType, type.GenericParameterPosition, def, special, variance, type); } return spec; } // // Test for a custom attribute type match. Custom attributes are not really predefined globaly // they can be assembly specific therefore we do check based on names only // public static bool HasAttribute (IList<CustomAttributeData> attributesData, string attrName, string attrNamespace) { if (attributesData.Count == 0) return false; foreach (var attr in attributesData) { var dt = attr.Constructor.DeclaringType; if (dt.Name == attrName && dt.Namespace == attrNamespace) return true; } return false; } void ImportTypeBase (TypeSpec spec, MetaType type) { if (spec.Kind == MemberKind.Interface) spec.BaseType = module.Compiler.BuiltinTypes.Object; else if (type.BaseType != null) { TypeSpec base_type; if (!IsMissingType (type.BaseType) && type.BaseType.IsGenericType) base_type = CreateType (type.BaseType, new DynamicTypeReader (type), true); else base_type = CreateType (type.BaseType); spec.BaseType = base_type; } if (spec.MemberDefinition.TypeParametersCount > 0) { foreach (var tp in spec.MemberDefinition.TypeParameters) { ImportTypeParameterTypeConstraints (tp, tp.GetMetaInfo ()); } } } protected void ImportTypes (MetaType[] types, Namespace targetNamespace, bool importExtensionTypes) { Namespace ns = targetNamespace; string prev_namespace = null; foreach (var t in types) { if (t == null) continue; // Be careful not to trigger full parent type loading if (t.MemberType == MemberTypes.NestedType) continue; if (t.Name[0] == '<') continue; var it = CreateType (t, null, new DynamicTypeReader (t), true); if (it == null) continue; if (prev_namespace != t.Namespace) { ns = t.Namespace == null ? targetNamespace : targetNamespace.GetNamespace (t.Namespace, true); prev_namespace = t.Namespace; } // Cannot rely on assembly level Extension attribute or static modifier because they // are not followed by other compilers (e.g. F#). if (it.IsClass && it.Arity == 0 && importExtensionTypes && HasAttribute (CustomAttributeData.GetCustomAttributes (t), "ExtensionAttribute", CompilerServicesNamespace)) { it.SetExtensionMethodContainer (); } ns.AddType (module, it); } } void ImportTypeParameterTypeConstraints (TypeParameterSpec spec, MetaType type) { var constraints = type.GetGenericParameterConstraints (); List<TypeSpec> tparams = null; foreach (var ct in constraints) { if (ct.IsGenericParameter) { if (tparams == null) tparams = new List<TypeSpec> (); tparams.Add (CreateType (ct)); continue; } var constraint_type = CreateType (ct); if (constraint_type.IsClass) { spec.BaseType = constraint_type; continue; } spec.AddInterface (constraint_type); } if (spec.BaseType == null) spec.BaseType = module.Compiler.BuiltinTypes.Object; if (tparams != null) spec.TypeArguments = tparams.ToArray (); } Constant ImportParameterConstant (object value) { // // Get type of underlying value as int constant can be used for object // parameter type. This is not allowed in C# but other languages can do that // var types = module.Compiler.BuiltinTypes; switch (System.Type.GetTypeCode (value.GetType ())) { case TypeCode.Boolean: return new BoolConstant (types, (bool) value, Location.Null); case TypeCode.Byte: return new ByteConstant (types, (byte) value, Location.Null); case TypeCode.Char: return new CharConstant (types, (char) value, Location.Null); case TypeCode.Decimal: return new DecimalConstant (types, (decimal) value, Location.Null); case TypeCode.Double: return new DoubleConstant (types, (double) value, Location.Null); case TypeCode.Int16: return new ShortConstant (types, (short) value, Location.Null); case TypeCode.Int32: return new IntConstant (types, (int) value, Location.Null); case TypeCode.Int64: return new LongConstant (types, (long) value, Location.Null); case TypeCode.SByte: return new SByteConstant (types, (sbyte) value, Location.Null); case TypeCode.Single: return new FloatConstant (types, (float) value, Location.Null); case TypeCode.String: return new StringConstant (types, (string) value, Location.Null); case TypeCode.UInt16: return new UShortConstant (types, (ushort) value, Location.Null); case TypeCode.UInt32: return new UIntConstant (types, (uint) value, Location.Null); case TypeCode.UInt64: return new ULongConstant (types, (ulong) value, Location.Null); } throw new NotImplementedException (value.GetType ().ToString ()); } public TypeSpec ImportType (MetaType type) { return ImportType (type, new DynamicTypeReader (type)); } TypeSpec ImportType (MetaType type, DynamicTypeReader dtype) { if (type.HasElementType) { var element = type.GetElementType (); ++dtype.Position; var spec = ImportType (element, dtype); if (type.IsArray) return ArrayContainer.MakeType (module, spec, type.GetArrayRank ()); if (type.IsByRef) return ReferenceContainer.MakeType (module, spec); if (type.IsPointer) return PointerContainer.MakeType (module, spec); throw new NotImplementedException ("Unknown element type " + type.ToString ()); } TypeSpec compiled_type; if (compiled_types.TryGetValue (type, out compiled_type)) { if (compiled_type.BuiltinType == BuiltinTypeSpec.Type.Object && dtype.IsDynamicObject ()) return module.Compiler.BuiltinTypes.Dynamic; return compiled_type; } return CreateType (type, dtype, true); } static bool IsMissingType (MetaType type) { #if STATIC return type.__IsMissing; #else return false; #endif } // // Decimal constants cannot be encoded in the constant blob, and thus are marked // as IsInitOnly ('readonly' in C# parlance). We get its value from the // DecimalConstantAttribute metadata. // Constant ReadDecimalConstant (IList<CustomAttributeData> attrs) { if (attrs.Count == 0) return null; foreach (var ca in attrs) { var dt = ca.Constructor.DeclaringType; if (dt.Name != "DecimalConstantAttribute" || dt.Namespace != CompilerServicesNamespace) continue; var value = new decimal ( (int) (uint) ca.ConstructorArguments[4].Value, (int) (uint) ca.ConstructorArguments[3].Value, (int) (uint) ca.ConstructorArguments[2].Value, (byte) ca.ConstructorArguments[1].Value != 0, (byte) ca.ConstructorArguments[0].Value); return new DecimalConstant (module.Compiler.BuiltinTypes, value, Location.Null); } return null; } static Modifiers ReadMethodModifiers (MethodBase mb, TypeSpec declaringType) { Modifiers mod; var ma = mb.Attributes; switch (ma & MethodAttributes.MemberAccessMask) { case MethodAttributes.Public: mod = Modifiers.PUBLIC; break; case MethodAttributes.Assembly: mod = Modifiers.INTERNAL; break; case MethodAttributes.Family: mod = Modifiers.PROTECTED; break; case MethodAttributes.FamORAssem: mod = Modifiers.PROTECTED | Modifiers.INTERNAL; break; default: mod = Modifiers.PRIVATE; break; } if ((ma & MethodAttributes.Static) != 0) { mod |= Modifiers.STATIC; return mod; } if ((ma & MethodAttributes.Abstract) != 0 && declaringType.IsClass) { mod |= Modifiers.ABSTRACT; return mod; } // It can be sealed and override if ((ma & MethodAttributes.Final) != 0) mod |= Modifiers.SEALED; if ((ma & MethodAttributes.Virtual) != 0) { // Not every member can be detected based on MethodAttribute, we // set virtual or non-virtual only when we are certain. Further checks // to really find out what `virtual' means for this member are done // later if ((ma & MethodAttributes.NewSlot) != 0) { if ((mod & Modifiers.SEALED) != 0) { mod &= ~Modifiers.SEALED; } else { mod |= Modifiers.VIRTUAL; } } else { mod |= Modifiers.OVERRIDE; } } return mod; } } abstract class ImportedDefinition : IMemberDefinition { protected class AttributesBag { public static readonly AttributesBag Default = new AttributesBag (); public AttributeUsageAttribute AttributeUsage; public ObsoleteAttribute Obsolete; public string[] Conditionals; public string DefaultIndexerName; public bool? CLSAttributeValue; public TypeSpec CoClass; static bool HasMissingType (ConstructorInfo ctor) { #if STATIC // // Mimic odd csc behaviour where missing type on predefined // attributes means the attribute is silently ignored. This can // happen with PCL facades // foreach (var p in ctor.GetParameters ()) { if (p.ParameterType.__ContainsMissingType) return true; } #endif return false; } public static AttributesBag Read (MemberInfo mi, MetadataImporter importer) { AttributesBag bag = null; List<string> conditionals = null; // It should not throw any loading exception IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (mi); foreach (var a in attrs) { var dt = a.Constructor.DeclaringType; string name = dt.Name; if (name == "ObsoleteAttribute") { if (dt.Namespace != "System") continue; if (bag == null) bag = new AttributesBag (); var args = a.ConstructorArguments; if (args.Count == 1) { bag.Obsolete = new ObsoleteAttribute ((string) args[0].Value); } else if (args.Count == 2) { bag.Obsolete = new ObsoleteAttribute ((string) args[0].Value, (bool) args[1].Value); } else { bag.Obsolete = new ObsoleteAttribute (); } continue; } if (name == "ConditionalAttribute") { if (dt.Namespace != "System.Diagnostics") continue; if (bag == null) bag = new AttributesBag (); if (conditionals == null) conditionals = new List<string> (2); conditionals.Add ((string) a.ConstructorArguments[0].Value); continue; } if (name == "CLSCompliantAttribute") { if (dt.Namespace != "System") continue; if (bag == null) bag = new AttributesBag (); bag.CLSAttributeValue = (bool) a.ConstructorArguments[0].Value; continue; } // Type only attributes if (mi.MemberType == MemberTypes.TypeInfo || mi.MemberType == MemberTypes.NestedType) { if (name == "DefaultMemberAttribute") { if (dt.Namespace != "System.Reflection") continue; if (bag == null) bag = new AttributesBag (); bag.DefaultIndexerName = (string) a.ConstructorArguments[0].Value; continue; } if (name == "AttributeUsageAttribute") { if (dt.Namespace != "System") continue; if (HasMissingType (a.Constructor)) continue; if (bag == null) bag = new AttributesBag (); bag.AttributeUsage = new AttributeUsageAttribute ((AttributeTargets) a.ConstructorArguments[0].Value); foreach (var named in a.NamedArguments) { if (named.MemberInfo.Name == "AllowMultiple") bag.AttributeUsage.AllowMultiple = (bool) named.TypedValue.Value; else if (named.MemberInfo.Name == "Inherited") bag.AttributeUsage.Inherited = (bool) named.TypedValue.Value; } continue; } // Interface only attribute if (name == "CoClassAttribute") { if (dt.Namespace != "System.Runtime.InteropServices") continue; if (HasMissingType (a.Constructor)) continue; if (bag == null) bag = new AttributesBag (); bag.CoClass = importer.ImportType ((MetaType) a.ConstructorArguments[0].Value); continue; } } } if (bag == null) return Default; if (conditionals != null) bag.Conditionals = conditionals.ToArray (); return bag; } } protected readonly MemberInfo provider; protected AttributesBag cattrs; protected readonly MetadataImporter importer; protected ImportedDefinition (MemberInfo provider, MetadataImporter importer) { this.provider = provider; this.importer = importer; } #region Properties public bool IsImported { get { return true; } } public virtual string Name { get { return provider.Name; } } #endregion public string[] ConditionalConditions () { if (cattrs == null) ReadAttributes (); return cattrs.Conditionals; } public ObsoleteAttribute GetAttributeObsolete () { if (cattrs == null) ReadAttributes (); return cattrs.Obsolete; } public bool? CLSAttributeValue { get { if (cattrs == null) ReadAttributes (); return cattrs.CLSAttributeValue; } } protected void ReadAttributes () { cattrs = AttributesBag.Read (provider, importer); } public void SetIsAssigned () { // Unused for imported members } public void SetIsUsed () { // Unused for imported members } } public class ImportedModuleDefinition { readonly Module module; bool cls_compliant; public ImportedModuleDefinition (Module module) { this.module = module; } #region Properties public bool IsCLSCompliant { get { return cls_compliant; } } public string Name { get { return module.Name; } } #endregion public void ReadAttributes () { IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (module); foreach (var a in attrs) { var dt = a.Constructor.DeclaringType; if (dt.Name == "CLSCompliantAttribute") { if (dt.Namespace != "System") continue; cls_compliant = (bool) a.ConstructorArguments[0].Value; continue; } } } // // Reads assembly attributes which where attached to a special type because // module does have assembly manifest // public List<Attribute> ReadAssemblyAttributes () { var t = module.GetType (AssemblyAttributesPlaceholder.GetGeneratedName (Name)); if (t == null) return null; var field = t.GetField (AssemblyAttributesPlaceholder.AssemblyFieldName, BindingFlags.NonPublic | BindingFlags.Static); if (field == null) return null; // TODO: implement, the idea is to fabricate specil Attribute class and // add it to OptAttributes before resolving the source code attributes // Need to build module location as well for correct error reporting //var assembly_attributes = CustomAttributeData.GetCustomAttributes (field); //var attrs = new List<Attribute> (assembly_attributes.Count); //foreach (var a in assembly_attributes) //{ // var type = metaImporter.ImportType (a.Constructor.DeclaringType); // var ctor = metaImporter.CreateMethod (a.Constructor, type); // foreach (var carg in a.ConstructorArguments) { // carg.Value // } // attrs.Add (new Attribute ("assembly", ctor, null, Location.Null, true)); //} return null; } } public class ImportedAssemblyDefinition : IAssemblyDefinition { readonly Assembly assembly; readonly AssemblyName aname; bool cls_compliant; List<AssemblyName> internals_visible_to; Dictionary<IAssemblyDefinition, AssemblyName> internals_visible_to_cache; public ImportedAssemblyDefinition (Assembly assembly) { this.assembly = assembly; this.aname = assembly.GetName (); } #region Properties public Assembly Assembly { get { return assembly; } } public string FullName { get { return aname.FullName; } } public bool HasStrongName { get { return aname.GetPublicKey ().Length != 0; } } public bool IsMissing { get { #if STATIC return assembly.__IsMissing; #else return false; #endif } } public bool IsCLSCompliant { get { return cls_compliant; } } public string Location { get { return assembly.Location; } } public string Name { get { return aname.Name; } } #endregion public byte[] GetPublicKeyToken () { return aname.GetPublicKeyToken (); } public AssemblyName GetAssemblyVisibleToName (IAssemblyDefinition assembly) { return internals_visible_to_cache [assembly]; } public bool IsFriendAssemblyTo (IAssemblyDefinition assembly) { if (internals_visible_to == null) return false; AssemblyName is_visible = null; if (internals_visible_to_cache == null) { internals_visible_to_cache = new Dictionary<IAssemblyDefinition, AssemblyName> (); } else { if (internals_visible_to_cache.TryGetValue (assembly, out is_visible)) return is_visible != null; } var token = assembly.GetPublicKeyToken (); if (token != null && token.Length == 0) token = null; foreach (var internals in internals_visible_to) { if (internals.Name != assembly.Name) continue; if (token == null && assembly is AssemblyDefinition) { is_visible = internals; break; } if (!ArrayComparer.IsEqual (token, internals.GetPublicKeyToken ())) continue; is_visible = internals; break; } internals_visible_to_cache.Add (assembly, is_visible); return is_visible != null; } public void ReadAttributes () { #if STATIC if (assembly.__IsMissing) return; #endif IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (assembly); foreach (var a in attrs) { var dt = a.Constructor.DeclaringType; var name = dt.Name; if (name == "CLSCompliantAttribute") { if (dt.Namespace == "System") { cls_compliant = (bool) a.ConstructorArguments[0].Value; } continue; } if (name == "InternalsVisibleToAttribute") { if (dt.Namespace != MetadataImporter.CompilerServicesNamespace) continue; string s = a.ConstructorArguments[0].Value as string; if (s == null) continue; var an = new AssemblyName (s); if (internals_visible_to == null) internals_visible_to = new List<AssemblyName> (); internals_visible_to.Add (an); continue; } } } public override string ToString () { return FullName; } } class ImportedMemberDefinition : ImportedDefinition { readonly TypeSpec type; public ImportedMemberDefinition (MemberInfo member, TypeSpec type, MetadataImporter importer) : base (member, importer) { this.type = type; } #region Properties public TypeSpec MemberType { get { return type; } } #endregion } class ImportedParameterMemberDefinition : ImportedMemberDefinition, IParametersMember { readonly AParametersCollection parameters; protected ImportedParameterMemberDefinition (MethodBase provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer) : base (provider, type, importer) { this.parameters = parameters; } public ImportedParameterMemberDefinition (PropertyInfo provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer) : base (provider, type, importer) { this.parameters = parameters; } #region Properties public AParametersCollection Parameters { get { return parameters; } } #endregion } class ImportedMethodDefinition : ImportedParameterMemberDefinition, IMethodDefinition { public ImportedMethodDefinition (MethodBase provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer) : base (provider, type, parameters, importer) { } MethodBase IMethodDefinition.Metadata { get { return (MethodBase) provider; } } } class ImportedGenericMethodDefinition : ImportedMethodDefinition, IGenericMethodDefinition { readonly TypeParameterSpec[] tparams; public ImportedGenericMethodDefinition (MethodInfo provider, TypeSpec type, AParametersCollection parameters, TypeParameterSpec[] tparams, MetadataImporter importer) : base (provider, type, parameters, importer) { this.tparams = tparams; } #region Properties public TypeParameterSpec[] TypeParameters { get { return tparams; } } public int TypeParametersCount { get { return tparams.Length; } } #endregion } class ImportedTypeDefinition : ImportedDefinition, ITypeDefinition { TypeParameterSpec[] tparams; string name; public ImportedTypeDefinition (MetaType type, MetadataImporter importer) : base (type, importer) { } #region Properties public IAssemblyDefinition DeclaringAssembly { get { return importer.GetAssemblyDefinition (provider.Module.Assembly); } } bool ITypeDefinition.IsComImport { get { return ((MetaType) provider).IsImport; } } bool ITypeDefinition.IsPartial { get { return false; } } bool ITypeDefinition.IsTypeForwarder { get { #if STATIC return ((MetaType) provider).__IsTypeForwarder; #else return false; #endif } } bool ITypeDefinition.IsCyclicTypeForwarder { get { #if STATIC return ((MetaType) provider).__IsCyclicTypeForwarder; #else return false; #endif } } public override string Name { get { if (name == null) { name = base.Name; if (tparams != null) { int arity_start = name.IndexOf ('`'); if (arity_start > 0) name = name.Substring (0, arity_start); } } return name; } } public string Namespace { get { return ((MetaType) provider).Namespace; } } public int TypeParametersCount { get { return tparams == null ? 0 : tparams.Length; } } public TypeParameterSpec[] TypeParameters { get { return tparams; } set { tparams = value; } } #endregion public void DefineInterfaces (TypeSpec spec) { var type = (MetaType) provider; MetaType[] ifaces; #if STATIC ifaces = type.__GetDeclaredInterfaces (); if (ifaces.Length != 0) { foreach (var iface in ifaces) { var it = importer.CreateType (iface); if (it == null) continue; spec.AddInterfaceDefined (it); // Unfortunately not all languages expand inherited interfaces var bifaces = it.Interfaces; if (bifaces != null) { foreach (var biface in bifaces) { spec.AddInterfaceDefined (biface); } } } } // // It's impossible to get declared interfaces only using System.Reflection // hence we need to mimic the behavior with ikvm-reflection too to keep // our type look-up logic same // if (spec.BaseType != null) { var bifaces = spec.BaseType.Interfaces; if (bifaces != null) { // // Before adding base class interfaces close defined interfaces // on type parameter // var tp = spec as TypeParameterSpec; if (tp != null && tp.InterfacesDefined == null) { tp.InterfacesDefined = TypeSpec.EmptyTypes; } foreach (var iface in bifaces) spec.AddInterfaceDefined (iface); } } #else ifaces = type.GetInterfaces (); if (ifaces.Length > 0) { foreach (var iface in ifaces) { spec.AddInterface (importer.CreateType (iface)); } } #endif } public static void Error_MissingDependency (IMemberContext ctx, List<MissingTypeSpecReference> missing, Location loc) { // // Report details about missing type and most likely cause of the problem. // csc reports 1683, 1684 as warnings but we report them only when used // or referenced from the user core in which case compilation error has to // be reported because compiler cannot continue anyway // var report = ctx.Module.Compiler.Report; for (int i = 0; i < missing.Count; ++i) { var t = missing [i].Type; // // Report missing types only once // if (report.Printer.MissingTypeReported (t.MemberDefinition)) continue; string name = t.GetSignatureForError (); var caller = missing[i].Caller; if (caller.Kind != MemberKind.MissingType) report.SymbolRelatedToPreviousError (caller); var definition = t.MemberDefinition; if (definition.DeclaringAssembly == ctx.Module.DeclaringAssembly) { report.Error (1683, loc, "Reference to type `{0}' claims it is defined in this assembly, but it is not defined in source or any added modules", name); } else if (definition.DeclaringAssembly.IsMissing) { if (definition.IsTypeForwarder) { report.Error (1070, loc, "The type `{0}' has been forwarded to an assembly that is not referenced. Consider adding a reference to assembly `{1}'", name, definition.DeclaringAssembly.FullName); } else { report.Error (12, loc, "The type `{0}' is defined in an assembly that is not referenced. Consider adding a reference to assembly `{1}'", name, definition.DeclaringAssembly.FullName); } } else if (definition.IsTypeForwarder) { report.Error (731, loc, "The type forwarder for type `{0}' in assembly `{1}' has circular dependency", name, definition.DeclaringAssembly.FullName); } else { report.Error (1684, loc, "Reference to type `{0}' claims it is defined assembly `{1}', but it could not be found", name, t.MemberDefinition.DeclaringAssembly.FullName); } } } public TypeSpec GetAttributeCoClass () { if (cattrs == null) ReadAttributes (); return cattrs.CoClass; } public string GetAttributeDefaultMember () { if (cattrs == null) ReadAttributes (); return cattrs.DefaultIndexerName; } public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa) { if (cattrs == null) ReadAttributes (); return cattrs.AttributeUsage; } bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly) { var a = importer.GetAssemblyDefinition (provider.Module.Assembly); return a == assembly || a.IsFriendAssemblyTo (assembly); } public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache) { // // Not interested in members of nested private types unless the importer needs them // if (declaringType.IsPrivate && importer.IgnorePrivateMembers) { cache = MemberCache.Empty; return; } var loading_type = (MetaType) provider; const BindingFlags all_members = BindingFlags.DeclaredOnly | BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; const MethodAttributes explicit_impl = MethodAttributes.NewSlot | MethodAttributes.Virtual | MethodAttributes.HideBySig | MethodAttributes.Final; Dictionary<MethodBase, MethodSpec> possible_accessors = null; List<EventSpec> imported_events = null; EventSpec event_spec; MemberSpec imported; MethodInfo m; MemberInfo[] all; try { all = loading_type.GetMembers (all_members); } catch (Exception e) { throw new InternalErrorException (e, "Could not import type `{0}' from `{1}'", declaringType.GetSignatureForError (), declaringType.MemberDefinition.DeclaringAssembly.FullName); } if (cache == null) { cache = new MemberCache (all.Length); // // Do the types first as they can be referenced by the members before // they are found or inflated // foreach (var member in all) { if (member.MemberType != MemberTypes.NestedType) continue; var t = (MetaType) member; // Ignore compiler generated types, mostly lambda containers if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && importer.IgnorePrivateMembers) continue; try { imported = importer.CreateNestedType (t, declaringType); } catch (Exception e) { throw new InternalErrorException (e, "Could not import nested type `{0}' from `{1}'", t.FullName, declaringType.MemberDefinition.DeclaringAssembly.FullName); } cache.AddMemberImported (imported); } foreach (var member in all) { if (member.MemberType != MemberTypes.NestedType) continue; var t = (MetaType) member; if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && importer.IgnorePrivateMembers) continue; importer.ImportTypeBase (t); } } // // Load base interfaces first to minic behaviour of compiled members // if (declaringType.IsInterface && declaringType.Interfaces != null) { foreach (var iface in declaringType.Interfaces) { cache.AddInterface (iface); } } if (!onlyTypes) { // // The logic here requires methods to be returned first which seems to work for both Mono and .NET // foreach (var member in all) { switch (member.MemberType) { case MemberTypes.Constructor: if (declaringType.IsInterface) continue; goto case MemberTypes.Method; case MemberTypes.Method: MethodBase mb = (MethodBase) member; var attrs = mb.Attributes; if ((attrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Private) { if (importer.IgnorePrivateMembers) continue; // Ignore explicitly implemented members if ((attrs & explicit_impl) == explicit_impl) continue; // Ignore compiler generated methods if (MetadataImporter.HasAttribute (CustomAttributeData.GetCustomAttributes (mb), "CompilerGeneratedAttribute", MetadataImporter.CompilerServicesNamespace)) continue; } imported = importer.CreateMethod (mb, declaringType); if (imported.Kind == MemberKind.Method && !imported.IsGeneric) { if (possible_accessors == null) possible_accessors = new Dictionary<MethodBase, MethodSpec> (ReferenceEquality<MethodBase>.Default); // There are no metadata rules for accessors, we have to consider any method as possible candidate possible_accessors.Add (mb, (MethodSpec) imported); } break; case MemberTypes.Property: if (possible_accessors == null) continue; var p = (PropertyInfo) member; // // Links possible accessors with property // MethodSpec get, set; m = p.GetGetMethod (true); if (m == null || !possible_accessors.TryGetValue (m, out get)) get = null; m = p.GetSetMethod (true); if (m == null || !possible_accessors.TryGetValue (m, out set)) set = null; // No accessors registered (e.g. explicit implementation) if (get == null && set == null) continue; try { imported = importer.CreateProperty (p, declaringType, get, set); } catch (Exception ex) { throw new InternalErrorException (ex, "Could not import property `{0}' inside `{1}'", p.Name, declaringType.GetSignatureForError ()); } if (imported == null) continue; break; case MemberTypes.Event: if (possible_accessors == null) continue; var e = (EventInfo) member; // // Links accessors with event // MethodSpec add, remove; m = e.GetAddMethod (true); if (m == null || !possible_accessors.TryGetValue (m, out add)) add = null; m = e.GetRemoveMethod (true); if (m == null || !possible_accessors.TryGetValue (m, out remove)) remove = null; // Both accessors are required if (add == null || remove == null) continue; event_spec = importer.CreateEvent (e, declaringType, add, remove); if (!importer.IgnorePrivateMembers) { if (imported_events == null) imported_events = new List<EventSpec> (); imported_events.Add (event_spec); } imported = event_spec; break; case MemberTypes.Field: var fi = (FieldInfo) member; imported = importer.CreateField (fi, declaringType); if (imported == null) continue; // // For dynamic binder event has to be fully restored to allow operations // within the type container to work correctly // if (imported_events != null) { // The backing event field should be private but it may not int i; for (i = 0; i < imported_events.Count; ++i) { var ev = imported_events[i]; if (ev.Name == fi.Name) { ev.BackingField = (FieldSpec) imported; imported_events.RemoveAt (i); i = -1; break; } } if (i < 0) continue; } break; case MemberTypes.NestedType: // Already in the cache from the first pass continue; default: throw new NotImplementedException (member.ToString ()); } if (imported.IsStatic && declaringType.IsInterface) continue; cache.AddMemberImported (imported); } } } } class ImportedTypeParameterDefinition : ImportedDefinition, ITypeDefinition { public ImportedTypeParameterDefinition (MetaType type, MetadataImporter importer) : base (type, importer) { } #region Properties public IAssemblyDefinition DeclaringAssembly { get { throw new NotImplementedException (); } } bool ITypeDefinition.IsComImport { get { return false; } } bool ITypeDefinition.IsPartial { get { return false; } } bool ITypeDefinition.IsTypeForwarder { get { return false; } } bool ITypeDefinition.IsCyclicTypeForwarder { get { return false; } } public string Namespace { get { return null; } } public int TypeParametersCount { get { return 0; } } public TypeParameterSpec[] TypeParameters { get { return null; } } #endregion public TypeSpec GetAttributeCoClass () { return null; } public string GetAttributeDefaultMember () { throw new NotSupportedException (); } public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa) { throw new NotSupportedException (); } bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly) { throw new NotImplementedException (); } public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache) { throw new NotImplementedException (); } } }
1
0.981817
1
0.981817
game-dev
MEDIA
0.158698
game-dev
0.974377
1
0.974377
pwnsky/squick
2,918
src/core/map.h
#pragma once #include "map_ex.h" #include <iostream> #include <list> #include <map> #include <string> #include <typeinfo> template <typename T, typename TD> class Map { public: typedef std::map<T, TD *> MapOBJECT; Map(){}; virtual ~Map(){ // mObjectList.clear(); // DeleteAllElement(); }; virtual bool AddElement(const T &name, TD *data) { typename MapOBJECT::iterator itr = mObjectList.find(name); if (itr == mObjectList.end()) { mObjectList.insert(typename MapOBJECT::value_type(name, data)); // mObjectList[name] = data; return true; } return false; } virtual TD *RemoveElement(const T &name) { TD *pData = NULL; typename MapOBJECT::iterator itr = mObjectList.find(name); if (itr != mObjectList.end()) { pData = itr->second; mObjectList.erase(itr); } return pData; } virtual TD *GetElement(const T &name) { typename MapOBJECT::iterator itr = mObjectList.find(name); if (itr != mObjectList.end()) { return itr->second; } else { return NULL; } } virtual bool ExistElement(const T &name) { typename MapOBJECT::iterator itr = mObjectList.find(name); if (itr != mObjectList.end()) { return true; } return false; } virtual TD *First() { if (mObjectList.size() <= 0) { return NULL; } mObjectCurIter = mObjectList.begin(); if (mObjectCurIter != mObjectList.end()) { return mObjectCurIter->second; } else { return NULL; } } virtual TD *Next() { if (mObjectCurIter == mObjectList.end()) { return NULL; } ++mObjectCurIter; if (mObjectCurIter != mObjectList.end()) { return mObjectCurIter->second; } else { return NULL; } } virtual TD *First(T &name) { if (mObjectList.size() <= 0) { return NULL; } mObjectCurIter = mObjectList.begin(); if (mObjectCurIter != mObjectList.end()) { name = mObjectCurIter->first; return mObjectCurIter->second; } else { return NULL; } } virtual TD *Next(T &name) { if (mObjectCurIter == mObjectList.end()) { return NULL; } mObjectCurIter++; if (mObjectCurIter != mObjectList.end()) { name = mObjectCurIter->first; return mObjectCurIter->second; } else { return NULL; } } int Count() { return mObjectList.size(); } bool ClearAll() { mObjectList.clear(); return true; } private: MapOBJECT mObjectList; typename MapOBJECT::iterator mObjectCurIter; };
1
0.918721
1
0.918721
game-dev
MEDIA
0.819705
game-dev
0.859651
1
0.859651
TaiyitistMC/Taiyitist
11,634
modules/taiyitist-server/src/main/java/org/bukkit/craftbukkit/CraftParticle.java
package org.bukkit.craftbukkit; import com.google.common.base.Preconditions; import java.util.HashMap; import java.util.Map; import java.util.function.BiFunction; import net.minecraft.core.particles.BlockParticleOption; import net.minecraft.core.particles.ColorParticleOption; import net.minecraft.core.particles.DustColorTransitionOptions; import net.minecraft.core.particles.DustParticleOptions; import net.minecraft.core.particles.ItemParticleOption; import net.minecraft.core.particles.ParticleOptions; import net.minecraft.core.particles.SculkChargeParticleOptions; import net.minecraft.core.particles.ShriekParticleOption; import net.minecraft.core.particles.SimpleParticleType; import net.minecraft.core.particles.VibrationParticleOption; import net.minecraft.core.registries.Registries; import net.minecraft.world.entity.Entity; import net.minecraft.world.level.gameevent.BlockPositionSource; import net.minecraft.world.level.gameevent.EntityPositionSource; import net.minecraft.world.level.gameevent.PositionSource; import org.bukkit.Color; import org.bukkit.Keyed; import org.bukkit.Location; import org.bukkit.NamespacedKey; import org.bukkit.Particle; import org.bukkit.Registry; import org.bukkit.Vibration; import org.bukkit.block.data.BlockData; import org.bukkit.craftbukkit.block.data.CraftBlockData; import org.bukkit.craftbukkit.entity.CraftEntity; import org.bukkit.craftbukkit.inventory.CraftItemStack; import org.bukkit.craftbukkit.legacy.FieldRename; import org.bukkit.craftbukkit.util.CraftLocation; import org.bukkit.craftbukkit.util.CraftMagicNumbers; import org.bukkit.craftbukkit.util.CraftNamespacedKey; import org.bukkit.inventory.ItemStack; import org.bukkit.material.MaterialData; import org.joml.Vector3f; public abstract class CraftParticle<D> implements Keyed { private static final Registry<CraftParticle<?>> CRAFT_PARTICLE_REGISTRY = new CraftParticleRegistry(CraftRegistry.getMinecraftRegistry(Registries.PARTICLE_TYPE)); public static Particle minecraftToBukkit(net.minecraft.core.particles.ParticleType<?> minecraft) { Preconditions.checkArgument(minecraft != null); net.minecraft.core.Registry<net.minecraft.core.particles.ParticleType<?>> registry = CraftRegistry.getMinecraftRegistry(Registries.PARTICLE_TYPE); Particle bukkit = Registry.PARTICLE_TYPE.get(CraftNamespacedKey.fromMinecraft(registry.getResourceKey(minecraft).orElseThrow().location())); Preconditions.checkArgument(bukkit != null); return bukkit; } public static net.minecraft.core.particles.ParticleType<?> bukkitToMinecraft(Particle bukkit) { Preconditions.checkArgument(bukkit != null); return CraftRegistry.getMinecraftRegistry(Registries.PARTICLE_TYPE) .getOptional(CraftNamespacedKey.toMinecraft(bukkit.getKey())).orElseThrow(); } public static <D> ParticleOptions createParticleParam(Particle particle, D data) { Preconditions.checkArgument(particle != null, "particle cannot be null"); data = CraftParticle.convertLegacy(data); if (particle.getDataType() != Void.class) { Preconditions.checkArgument(data != null, "missing required data %s", particle.getDataType()); } if (data != null) { Preconditions.checkArgument(particle.getDataType().isInstance(data), "data (%s) should be %s", data.getClass(), particle.getDataType()); } CraftParticle<D> craftParticle = (CraftParticle<D>) CraftParticle.CRAFT_PARTICLE_REGISTRY.get(particle.getKey()); Preconditions.checkArgument(craftParticle != null); return craftParticle.createParticleParam(data); } public static <T> T convertLegacy(T object) { if (object instanceof MaterialData mat) { return (T) CraftBlockData.fromData(CraftMagicNumbers.getBlock(mat)); } return object; } private final NamespacedKey key; private final net.minecraft.core.particles.ParticleType<?> particle; private final Class<D> clazz; public CraftParticle(NamespacedKey key, net.minecraft.core.particles.ParticleType<?> particle, Class<D> clazz) { this.key = key; this.particle = particle; this.clazz = clazz; } public net.minecraft.core.particles.ParticleType<?> getHandle() { return this.particle; } public abstract ParticleOptions createParticleParam(D data); @Override public NamespacedKey getKey() { return this.key; } public static class CraftParticleRegistry extends CraftRegistry<CraftParticle<?>, net.minecraft.core.particles.ParticleType<?>> { private static final Map<NamespacedKey, BiFunction<NamespacedKey, net.minecraft.core.particles.ParticleType<?>, CraftParticle<?>>> PARTICLE_MAP = new HashMap<>(); private static final BiFunction<NamespacedKey, net.minecraft.core.particles.ParticleType<?>, CraftParticle<?>> VOID_FUNCTION = (name, particle) -> new CraftParticle<>(name, particle, Void.class) { @Override public ParticleOptions createParticleParam(Void data) { return (SimpleParticleType) this.getHandle(); } }; static { BiFunction<NamespacedKey, net.minecraft.core.particles.ParticleType<?>, CraftParticle<?>> dustOptionsFunction = (name, particle) -> new CraftParticle<>(name, particle, Particle.DustOptions.class) { @Override public ParticleOptions createParticleParam(Particle.DustOptions data) { Color color = data.getColor(); return new DustParticleOptions(new Vector3f(color.getRed() / 255.0f, color.getGreen() / 255.0f, color.getBlue() / 255.0f), data.getSize()); } }; BiFunction<NamespacedKey, net.minecraft.core.particles.ParticleType<?>, CraftParticle<?>> itemStackFunction = (name, particle) -> new CraftParticle<>(name, particle, ItemStack.class) { @Override public ParticleOptions createParticleParam(ItemStack data) { return new ItemParticleOption((net.minecraft.core.particles.ParticleType<ItemParticleOption>) this.getHandle(), CraftItemStack.asNMSCopy(data)); } }; BiFunction<NamespacedKey, net.minecraft.core.particles.ParticleType<?>, CraftParticle<?>> blockDataFunction = (name, particle) -> new CraftParticle<>(name, particle, BlockData.class) { @Override public ParticleOptions createParticleParam(BlockData data) { return new BlockParticleOption((net.minecraft.core.particles.ParticleType<BlockParticleOption>) this.getHandle(), ((CraftBlockData) data).getState()); } }; BiFunction<NamespacedKey, net.minecraft.core.particles.ParticleType<?>, CraftParticle<?>> dustTransitionFunction = (name, particle) -> new CraftParticle<>(name, particle, Particle.DustTransition.class) { @Override public ParticleOptions createParticleParam(Particle.DustTransition data) { Color from = data.getColor(); Color to = data.getToColor(); return new DustColorTransitionOptions(new Vector3f(from.getRed() / 255.0f, from.getGreen() / 255.0f, from.getBlue() / 255.0f), new Vector3f(to.getRed() / 255.0f, to.getGreen() / 255.0f, to.getBlue() / 255.0f), data.getSize()); } }; BiFunction<NamespacedKey, net.minecraft.core.particles.ParticleType<?>, CraftParticle<?>> vibrationFunction = (name, particle) -> new CraftParticle<>(name, particle, Vibration.class) { @Override public ParticleOptions createParticleParam(Vibration data) { PositionSource source; if (data.getDestination() instanceof Vibration.Destination.BlockDestination) { Location destination = ((Vibration.Destination.BlockDestination) data.getDestination()).getLocation(); source = new BlockPositionSource(CraftLocation.toBlockPosition(destination)); } else if (data.getDestination() instanceof Vibration.Destination.EntityDestination) { Entity destination = ((CraftEntity) ((Vibration.Destination.EntityDestination) data.getDestination()).getEntity()).getHandle(); source = new EntityPositionSource(destination, destination.getEyeHeight()); } else { throw new IllegalArgumentException("Unknown vibration destination " + data.getDestination()); } return new VibrationParticleOption(source, data.getArrivalTime()); } }; BiFunction<NamespacedKey, net.minecraft.core.particles.ParticleType<?>, CraftParticle<?>> floatFunction = (name, particle) -> new CraftParticle<>(name, particle, Float.class) { @Override public ParticleOptions createParticleParam(Float data) { return new SculkChargeParticleOptions(data); } }; BiFunction<NamespacedKey, net.minecraft.core.particles.ParticleType<?>, CraftParticle<?>> integerFunction = (name, particle) -> new CraftParticle<>(name, particle, Integer.class) { @Override public ParticleOptions createParticleParam(Integer data) { return new ShriekParticleOption(data); } }; BiFunction<NamespacedKey, net.minecraft.core.particles.ParticleType<?>, CraftParticle<?>> colorFunction = (name, particle) -> new CraftParticle<>(name, particle, Color.class) { @Override public ParticleOptions createParticleParam(Color color) { return ColorParticleOption.create((net.minecraft.core.particles.ParticleType<ColorParticleOption>) particle, color.asARGB()); } }; add("dust", dustOptionsFunction); add("item", itemStackFunction); add("block", blockDataFunction); add("falling_dust", blockDataFunction); add("dust_color_transition", dustTransitionFunction); add("vibration", vibrationFunction); add("sculk_charge", floatFunction); add("shriek", integerFunction); add("block_marker", blockDataFunction); add("entity_effect", colorFunction); add("dust_pillar", blockDataFunction); } private static void add(String name, BiFunction<NamespacedKey, net.minecraft.core.particles.ParticleType<?>, CraftParticle<?>> function) { CraftParticleRegistry.PARTICLE_MAP.put(NamespacedKey.fromString(name), function); } public CraftParticleRegistry(net.minecraft.core.Registry<net.minecraft.core.particles.ParticleType<?>> minecraftRegistry) { super(CraftParticle.class, minecraftRegistry, null, FieldRename.PARTICLE_TYPE_RENAME); } @Override public CraftParticle<?> createBukkit(NamespacedKey namespacedKey, net.minecraft.core.particles.ParticleType<?> particle) { if (particle == null) { return null; } BiFunction<NamespacedKey, net.minecraft.core.particles.ParticleType<?>, CraftParticle<?>> function = CraftParticleRegistry.PARTICLE_MAP.getOrDefault(namespacedKey, CraftParticleRegistry.VOID_FUNCTION); return function.apply(namespacedKey, particle); } } }
1
0.859288
1
0.859288
game-dev
MEDIA
0.992609
game-dev
0.880161
1
0.880161
Planimeter/hl2sb-src
10,180
src/game/server/sdk/sdk_player.cpp
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: Player for HL1. // // $NoKeywords: $ //=============================================================================// #include "cbase.h" #include "sdk_player.h" #include "sdk_gamerules.h" #include "weapon_sdkbase.h" #include "predicted_viewmodel.h" #include "iservervehicle.h" #include "viewport_panel_names.h" extern int gEvilImpulse101; ConVar sv_motd_unload_on_dismissal( "sv_motd_unload_on_dismissal", "0", 0, "If enabled, the MOTD contents will be unloaded when the player closes the MOTD." ); #define SDK_PLAYER_MODEL "models/player/terror.mdl" // -------------------------------------------------------------------------------- // // Player animation event. Sent to the client when a player fires, jumps, reloads, etc.. // -------------------------------------------------------------------------------- // class CTEPlayerAnimEvent : public CBaseTempEntity { public: DECLARE_CLASS( CTEPlayerAnimEvent, CBaseTempEntity ); DECLARE_SERVERCLASS(); CTEPlayerAnimEvent( const char *name ) : CBaseTempEntity( name ) { } CNetworkHandle( CBasePlayer, m_hPlayer ); CNetworkVar( int, m_iEvent ); CNetworkVar( int, m_nData ); }; #define THROWGRENADE_COUNTER_BITS 3 IMPLEMENT_SERVERCLASS_ST_NOBASE( CTEPlayerAnimEvent, DT_TEPlayerAnimEvent ) SendPropEHandle( SENDINFO( m_hPlayer ) ), SendPropInt( SENDINFO( m_iEvent ), Q_log2( PLAYERANIMEVENT_COUNT ) + 1, SPROP_UNSIGNED ), SendPropInt( SENDINFO( m_nData ), 32 ) END_SEND_TABLE() static CTEPlayerAnimEvent g_TEPlayerAnimEvent( "PlayerAnimEvent" ); void TE_PlayerAnimEvent( CBasePlayer *pPlayer, PlayerAnimEvent_t event, int nData ) { CPVSFilter filter( (const Vector&)pPlayer->EyePosition() ); g_TEPlayerAnimEvent.m_hPlayer = pPlayer; g_TEPlayerAnimEvent.m_iEvent = event; g_TEPlayerAnimEvent.m_nData = nData; g_TEPlayerAnimEvent.Create( filter, 0 ); } // -------------------------------------------------------------------------------- // // Tables. // -------------------------------------------------------------------------------- // BEGIN_DATADESC( CSDKPlayer ) DEFINE_THINKFUNC( SDKPushawayThink ), END_DATADESC() LINK_ENTITY_TO_CLASS( player, CSDKPlayer ); PRECACHE_REGISTER(player); BEGIN_SEND_TABLE_NOBASE( CSDKPlayer, DT_SDKLocalPlayerExclusive ) SendPropInt( SENDINFO( m_iShotsFired ), 8, SPROP_UNSIGNED ), END_SEND_TABLE() IMPLEMENT_SERVERCLASS_ST( CSDKPlayer, DT_SDKPlayer ) SendPropExclude( "DT_BaseAnimating", "m_flPoseParameter" ), SendPropExclude( "DT_BaseAnimating", "m_flPlaybackRate" ), SendPropExclude( "DT_BaseAnimating", "m_nSequence" ), SendPropExclude( "DT_BaseEntity", "m_angRotation" ), SendPropExclude( "DT_BaseAnimatingOverlay", "overlay_vars" ), // playeranimstate and clientside animation takes care of these on the client SendPropExclude( "DT_ServerAnimationData" , "m_flCycle" ), SendPropExclude( "DT_AnimTimeMustBeFirst" , "m_flAnimTime" ), // Data that only gets sent to the local player. SendPropDataTable( "sdklocaldata", 0, &REFERENCE_SEND_TABLE(DT_SDKLocalPlayerExclusive), SendProxy_SendLocalDataTable ), SendPropAngle( SENDINFO_VECTORELEM(m_angEyeAngles, 0), 11 ), SendPropAngle( SENDINFO_VECTORELEM(m_angEyeAngles, 1), 11 ), SendPropEHandle( SENDINFO( m_hRagdoll ) ), SendPropInt( SENDINFO( m_iThrowGrenadeCounter ), THROWGRENADE_COUNTER_BITS, SPROP_UNSIGNED ), END_SEND_TABLE() class CSDKRagdoll : public CBaseAnimatingOverlay { public: DECLARE_CLASS( CSDKRagdoll, CBaseAnimatingOverlay ); DECLARE_SERVERCLASS(); // Transmit ragdolls to everyone. virtual int UpdateTransmitState() { return SetTransmitState( FL_EDICT_ALWAYS ); } public: // In case the client has the player entity, we transmit the player index. // In case the client doesn't have it, we transmit the player's model index, origin, and angles // so they can create a ragdoll in the right place. CNetworkHandle( CBaseEntity, m_hPlayer ); // networked entity handle CNetworkVector( m_vecRagdollVelocity ); CNetworkVector( m_vecRagdollOrigin ); }; LINK_ENTITY_TO_CLASS( sdk_ragdoll, CSDKRagdoll ); IMPLEMENT_SERVERCLASS_ST_NOBASE( CSDKRagdoll, DT_SDKRagdoll ) SendPropVector( SENDINFO(m_vecRagdollOrigin), -1, SPROP_COORD ), SendPropEHandle( SENDINFO( m_hPlayer ) ), SendPropModelIndex( SENDINFO( m_nModelIndex ) ), SendPropInt ( SENDINFO(m_nForceBone), 8, 0 ), SendPropVector ( SENDINFO(m_vecForce), -1, SPROP_NOSCALE ), SendPropVector( SENDINFO( m_vecRagdollVelocity ) ) END_SEND_TABLE() // -------------------------------------------------------------------------------- // void cc_CreatePredictionError_f() { CBaseEntity *pEnt = CBaseEntity::Instance( 1 ); pEnt->SetAbsOrigin( pEnt->GetAbsOrigin() + Vector( 63, 0, 0 ) ); } ConCommand cc_CreatePredictionError( "CreatePredictionError", cc_CreatePredictionError_f, "Create a prediction error", FCVAR_CHEAT ); CSDKPlayer::CSDKPlayer() { m_PlayerAnimState = CreatePlayerAnimState( this, this, LEGANIM_9WAY, true ); UseClientSideAnimation(); m_angEyeAngles.Init(); SetViewOffset( SDK_PLAYER_VIEW_OFFSET ); m_iThrowGrenadeCounter = 0; } CSDKPlayer::~CSDKPlayer() { m_PlayerAnimState->Release(); } CSDKPlayer *CSDKPlayer::CreatePlayer( const char *className, edict_t *ed ) { CSDKPlayer::s_PlayerEdict = ed; return (CSDKPlayer*)CreateEntityByName( className ); } void CSDKPlayer::LeaveVehicle( const Vector &vecExitPoint, const QAngle &vecExitAngles ) { BaseClass::LeaveVehicle( vecExitPoint, vecExitAngles ); //teleport physics shadow too // Vector newPos = GetAbsOrigin(); // QAngle newAng = GetAbsAngles(); // Teleport( &newPos, &newAng, &vec3_origin ); } void CSDKPlayer::PreThink(void) { // Riding a vehicle? if ( IsInAVehicle() ) { // make sure we update the client, check for timed damage and update suit even if we are in a vehicle UpdateClientData(); CheckTimeBasedDamage(); // Allow the suit to recharge when in the vehicle. CheckSuitUpdate(); WaterMove(); return; } BaseClass::PreThink(); } void CSDKPlayer::PostThink() { BaseClass::PostThink(); QAngle angles = GetLocalAngles(); angles[PITCH] = 0; SetLocalAngles( angles ); // Store the eye angles pitch so the client can compute its animation state correctly. m_angEyeAngles = EyeAngles(); m_PlayerAnimState->Update( m_angEyeAngles[YAW], m_angEyeAngles[PITCH] ); } void CSDKPlayer::Precache() { PrecacheModel( SDK_PLAYER_MODEL ); BaseClass::Precache(); } void CSDKPlayer::Spawn() { SetModel( SDK_PLAYER_MODEL ); SetMoveType( MOVETYPE_WALK ); RemoveSolidFlags( FSOLID_NOT_SOLID ); m_hRagdoll = NULL; BaseClass::Spawn(); } void CSDKPlayer::InitialSpawn( void ) { BaseClass::InitialSpawn(); const ConVar *hostname = cvar->FindVar( "hostname" ); const char *title = (hostname) ? hostname->GetString() : "MESSAGE OF THE DAY"; // open info panel on client showing MOTD: KeyValues *data = new KeyValues("data"); data->SetString( "title", title ); // info panel title data->SetString( "type", "1" ); // show userdata from stringtable entry data->SetString( "msg", "motd" ); // use this stringtable entry data->SetInt( "cmd", TEXTWINDOW_CMD_IMPULSE101 );// exec this command if panel closed data->SetBool( "unload", sv_motd_unload_on_dismissal.GetBool() ); ShowViewPortPanel( PANEL_INFO, true, data ); data->deleteThis(); } void CSDKPlayer::Event_Killed( const CTakeDamageInfo &info ) { // Note: since we're dead, it won't draw us on the client, but we don't set EF_NODRAW // because we still want to transmit to the clients in our PVS. BaseClass::Event_Killed( info ); CreateRagdollEntity(); } void CSDKPlayer::CreateRagdollEntity() { // If we already have a ragdoll, don't make another one. CSDKRagdoll *pRagdoll = dynamic_cast< CSDKRagdoll* >( m_hRagdoll.Get() ); if ( !pRagdoll ) { // create a new one pRagdoll = dynamic_cast< CSDKRagdoll* >( CreateEntityByName( "sdk_ragdoll" ) ); } if ( pRagdoll ) { pRagdoll->m_hPlayer = this; pRagdoll->m_vecRagdollOrigin = GetAbsOrigin(); pRagdoll->m_vecRagdollVelocity = GetAbsVelocity(); pRagdoll->m_nModelIndex = m_nModelIndex; pRagdoll->m_nForceBone = m_nForceBone; pRagdoll->m_vecForce = Vector(0,0,0); } // ragdolls will be removed on round restart automatically m_hRagdoll = pRagdoll; } void CSDKPlayer::DoAnimationEvent( PlayerAnimEvent_t event, int nData ) { if ( event == PLAYERANIMEVENT_THROW_GRENADE ) { // Grenade throwing has to synchronize exactly with the player's grenade weapon going away, // and events get delayed a bit, so we let CCSPlayerAnimState pickup the change to this // variable. m_iThrowGrenadeCounter = (m_iThrowGrenadeCounter+1) % (1<<THROWGRENADE_COUNTER_BITS); } else { m_PlayerAnimState->DoAnimationEvent( event, nData ); TE_PlayerAnimEvent( this, event, nData ); // Send to any clients who can see this guy. } } CWeaponSDKBase* CSDKPlayer::GetActiveSDKWeapon() const { return dynamic_cast< CWeaponSDKBase* >( GetActiveWeapon() ); } void CSDKPlayer::CreateViewModel( int index /*=0*/ ) { Assert( index >= 0 && index < MAX_VIEWMODELS ); if ( GetViewModel( index ) ) return; CPredictedViewModel *vm = ( CPredictedViewModel * )CreateEntityByName( "predicted_viewmodel" ); if ( vm ) { vm->SetAbsOrigin( GetAbsOrigin() ); vm->SetOwner( this ); vm->SetIndex( index ); DispatchSpawn( vm ); vm->FollowEntity( this, false ); m_hViewModel.Set( index, vm ); } } void CSDKPlayer::CheatImpulseCommands( int iImpulse ) { if ( iImpulse != 101 ) { BaseClass::CheatImpulseCommands( iImpulse ); return ; } gEvilImpulse101 = true; EquipSuit(); GiveNamedItem( "weapon_mp5" ); GiveNamedItem( "weapon_grenade" ); GiveNamedItem( "weapon_shotgun" ); // Give the player everything! GiveAmmo( 90, AMMO_BULLETS ); GiveAmmo( 3, AMMO_GRENADE ); if ( GetHealth() < 100 ) { TakeHealth( 25, DMG_GENERIC ); } gEvilImpulse101 = false; } void CSDKPlayer::FlashlightTurnOn( void ) { AddEffects( EF_DIMLIGHT ); } void CSDKPlayer::FlashlightTurnOff( void ) { RemoveEffects( EF_DIMLIGHT ); } int CSDKPlayer::FlashlightIsOn( void ) { return IsEffectActive( EF_DIMLIGHT ); }
1
0.951586
1
0.951586
game-dev
MEDIA
0.948454
game-dev
0.823804
1
0.823804
apalache-mc/apalache
14,083
tla-bmcmt/src/main/scala/at/forsyte/apalache/tla/bmcmt/Arena.scala
package at.forsyte.apalache.tla.bmcmt import at.forsyte.apalache.tla.bmcmt.smt.SolverContext import at.forsyte.apalache.tla.bmcmt.types._ import at.forsyte.apalache.tla.lir.oper.TlaBoolOper import at.forsyte.apalache.tla.lir.{BoolT1, IntT1, NameEx, OperEx, SetT1, TlaEx, TlaType1} import at.forsyte.apalache.tla.lir.UntypedPredefs._ import at.forsyte.apalache.tla.lir.convenience.tla import scala.collection.immutable.HashMap object Arena { /** * The prefix of all cells. */ val namePrefix = "$C$" val falseName: String = namePrefix + "0" val trueName: String = namePrefix + "1" val booleanSetName: String = namePrefix + "2" val natSetName: String = namePrefix + "3" val intSetName: String = namePrefix + "4" def create(solverContext: SolverContext): Arena = { var arena = new Arena( solverContext, 0, new ArenaCell(-1, UnknownT()), HashMap(), new HashMap(), new HashMap(), new HashMap(), ) ///// // by convention, the first cells have the following semantics: // 0 stores FALSE, 1 stores TRUE, 2 stores BOOLEAN, 3 stores Nat, 4 stores Int arena = arena .appendCellNoSmt(CellTFrom(BoolT1)) .appendCellNoSmt(CellTFrom(BoolT1)) .appendCellNoSmt(CellTFrom(SetT1(BoolT1))) .appendCellNoSmt(InfSetT(CellTFrom(IntT1))) .appendCellNoSmt(InfSetT(CellTFrom(IntT1))) // declare Boolean cells in SMT val cellFalse = arena.cellFalse() val cellTrue = arena.cellTrue() val cellBoolean = arena.cellBooleanSet() val cellNat = arena.cellNatSet() val cellInt = arena.cellIntSet() solverContext.declareCell(cellFalse) solverContext.declareCell(cellTrue) solverContext.declareCell(cellBoolean) solverContext.declareCell(cellNat) solverContext.declareCell(cellInt) solverContext.assertGroundExpr(OperEx(TlaBoolOper.not, cellFalse.toNameEx)) solverContext.assertGroundExpr(cellTrue.toNameEx) // link c_BOOLEAN to c_FALSE and c_TRUE arena = arena.appendHas(cellBoolean, cellFalse).appendHas(cellBoolean, cellTrue) // assert in(c_FALSE, c_BOOLEAN) and in(c_TRUE, c_BOOLEAN) solverContext.assertGroundExpr(tla.apalacheStoreInSet(cellFalse.toNameEx, cellBoolean.toNameEx)) solverContext.assertGroundExpr(tla.apalacheStoreInSet(cellTrue.toNameEx, cellBoolean.toNameEx)) arena } } /** * <p>A memory arena represents a memory layout. The arena is dynamically populated, when new objects are created. * Currently, an arena is a directed acyclic graph, where edges are pointing from a container object to the associated * cells, e.g., a set cell points to the cells that store its elements.</p> * * <p>Do not use solverContext, as it is going to be removed in the future.</p> * * @author * Igor Konnov */ class Arena private ( val solverContext: SolverContext, val cellCount: Int, val topCell: ArenaCell, val cellMap: Map[String, ArenaCell], private val hasEdges: Map[ArenaCell, List[ArenaCell]], private val domEdges: Map[ArenaCell, ArenaCell], private val cdmEdges: Map[ArenaCell, ArenaCell]) extends Serializable { // TODO: remove solverContext from Arena, see issue #105 def setSolver(newSolverContext: SolverContext): Arena = { // this is a temporary solution new Arena(newSolverContext, cellCount, topCell, cellMap, hasEdges, domEdges, cdmEdges) } /** * A fixed cell that equals to false in the Boolean theory. * * @return * the false cell */ def cellFalse(): ArenaCell = { cellMap(Arena.falseName) } /** * A fixed cell that equals to true in the Boolean theory * * @return * the true cell */ def cellTrue(): ArenaCell = { cellMap(Arena.trueName) } /** * A fixed cell that stores the set {false, true}, that is, the set BOOLEAN in TLA+. * * @return * the cell for the BOOLEAN set */ def cellBooleanSet(): ArenaCell = { cellMap(Arena.booleanSetName) } /** * A fixed cell that stores the set Nat. As this set is infinite, it is not pointing to any other cells. * * @return * the cell for the Nat cell */ def cellNatSet(): ArenaCell = { cellMap(Arena.natSetName) } /** * A fixed cell that stores the set Int. As this set is infinite, it is not pointing to any other cells. * * @return * the cell for the Int cell */ def cellIntSet(): ArenaCell = { cellMap(Arena.intSetName) } /** * Find a cell by its name. * * @param name * the name returned by ArenaCell.toString * @return * the cell, if it exists * @throws java.util.NoSuchElementException * when no cell is found */ def findCellByName(name: String): ArenaCell = { cellMap(name) } /** * Find a cell by the name contained in a name expression. * * @param nameEx * a name expression that follows the cell naming convention. * @return * the found cell * @throws InvalidTlaExException * if the name does not follow the convention * @throws java.util.NoSuchElementException * when no cell is found */ def findCellByNameEx(nameEx: TlaEx): ArenaCell = { nameEx match { case NameEx(name) if ArenaCell.isValidName(name) => cellMap(name) case _ => throw new CheckerException("Expected NameEx with a cell name, found: %s".format(nameEx), nameEx) } } /** * Append a new cell to arena. This method returns a new arena, not the new cell. The new cell can be accessed with * topCell. This method will be removed, when we fully migrate from {{{CellT}}} to {{{TlaType1}}}. * * @param cellType * a cell type * @param isUnconstrained * a flag defining if the SMT representation of the cell is unconstrained, default is false. * @return * new arena */ def appendCellOld(cellType: CellT, isUnconstrained: Boolean = false): Arena = { val newArena = appendCellNoSmt(cellType, isUnconstrained) val newCell = newArena.topCell solverContext.declareCell(newCell) newArena } /** * Append a new cell to arena. This method returns a new arena, not the new cell. The new cell can be accessed with * topCell. * * @param cellType * a cell type * @param isUnconstrained * a flag defining if the SMT representation of the cell is unconstrained, default is false. * @return * new arena */ def appendCell(cellType: TlaType1, isUnconstrained: Boolean = false): Arena = { appendCellOld(CellT.fromType1(cellType), isUnconstrained) } /** * Append a sequence of cells to arena. This method returns a new arena and a sequence of the freshly created cells * (the cells are ordered the same way as the sequence of types). This method provides us with a handy alternative to * appendCell, when several cells should be created. * * @param types * a sequence of cell types * @return * a pair: the new arena and a sequence of new cells */ def appendCellSeq(types: CellT*): (Arena, Seq[ArenaCell]) = { def create(arena: Arena, ts: Seq[CellT]): (Arena, Seq[ArenaCell]) = ts match { case Seq() => (arena, Seq()) case hd +: tl => val (tailArena: Arena, tailCells: Seq[ArenaCell]) = create(arena, tl) val headArena = tailArena.appendCellOld(hd) (headArena, headArena.topCell +: tailCells) } create(this, types) } /** * Append a new cell to arena. This method returns a new arena, not the new cell. The new cell can be accessed with * topCell. This method does not generate SMT constraints. * * @param cellType * a cell type * @param isUnconstrained * a flag defining if the SMT representation of the cell is unconstrained, default is false. * @return * new arena */ def appendCellNoSmt(cellType: CellT, isUnconstrained: Boolean = false): Arena = { val newCell = new ArenaCell(cellCount, cellType, isUnconstrained) assert(!cellMap.contains(newCell.toString)) // this might happen, if we messed up arenas new Arena( solverContext, cellCount + 1, newCell, cellMap + (newCell.toString -> newCell), hasEdges, domEdges, cdmEdges, ) } /** * Append 'has' edges that connect the first cell to the other cells, in the given order. The previously added edges * come first. When this method is called as appendHas(X, Y1, ..., Ym), it adds a Boolean constant in_X_Yi for each i: * 1 <= i <= m. * * @param parentCell * the cell that points to the children cells * @param childrenCells * the cells that are pointed by the parent cell * @return * the updated arena */ def appendHas(parentCell: ArenaCell, childrenCells: ArenaCell*): Arena = { childrenCells.foldLeft(this) { (a, c) => a.appendOneHasEdge(addInPred = true, parentCell, c) } } /** * Append 'has' edges that connect the first cell to the other cells, in the given order. The previously added edges * come first. In contrast to appendHas, this method does not add any constants in SMT. * * @param parentCell * the cell that points to the children cells * @param childrenCells * the cells that are pointed by the parent cell * @return * the updated arena */ def appendHasNoSmt(parentCell: ArenaCell, childrenCells: ArenaCell*): Arena = { childrenCells.foldLeft(this) { (a, c) => a.appendOneHasEdge(addInPred = false, parentCell, c) } } /** * Append a 'has' edge to connect a cell that corresponds to a set with a cell that corresponds to its element. * * @param setCell * a set cell * @param elemCell * an element cell * @param addInPred * indicates whether the in_X_Y constant should be added in SMT. * @return * a new arena */ private def appendOneHasEdge(addInPred: Boolean, setCell: ArenaCell, elemCell: ArenaCell): Arena = { if (addInPred) { solverContext.declareInPredIfNeeded(setCell, elemCell) } val es = hasEdges.get(setCell) match { case Some(list) => list :+ elemCell case None => List(elemCell) } new Arena( solverContext, cellCount, topCell, cellMap, hasEdges + (setCell -> es), domEdges, cdmEdges, ) } /** * Get all the edges that are labelled with 'has'. * * @param setCell * a set cell * @return * all element cells that were added with appendHas, or an empty list, if none were added */ def getHas(setCell: ArenaCell): List[ArenaCell] = { hasEdges.get(setCell) match { case Some(list) => list case None => List() } } /** * Set a function domain. * * @param funCell * a function cell. * @param domCell * a set cell * @return * a new arena */ def setDom(funCell: ArenaCell, domCell: ArenaCell): Arena = { if (domEdges.contains(funCell)) throw new IllegalStateException("Trying to set function domain, whereas one is already set") new Arena( solverContext, cellCount, topCell, cellMap, hasEdges, domEdges + (funCell -> domCell), cdmEdges, ) } /** * Set a function co-domain. * * @param funCell * a function cell. * @param cdmCell * a set cell * @return * a new arena */ def setCdm(funCell: ArenaCell, cdmCell: ArenaCell): Arena = { if (cdmEdges.contains(funCell)) throw new IllegalStateException("Trying to set function co-domain, whereas one is already set") new Arena( solverContext, cellCount, topCell, cellMap, hasEdges, domEdges, cdmEdges + (funCell -> cdmCell), ) } /** * Get the domain cell associated with a function. * * @param funCell * a function cell. * @return * the domain cell */ def getDom(funCell: ArenaCell): ArenaCell = { domEdges.apply(funCell) } /** * Get the co-domain cell associated with a function. * * @param funCell * a function cell. * @return * the co-domain cell */ def getCdm(funCell: ArenaCell): ArenaCell = { cdmEdges.apply(funCell) } /** * Check, whether a cell has an associated domain edge. * * @param cell * a cell * @return * true, if cell has an edge labelled with 'dom' */ def hasDom(cell: ArenaCell): Boolean = { domEdges.contains(cell) } /** * Check, whether a cell has an associated co-domain edge. * * @param cell * a cell * @return * true, if cell has an edge labelled with 'cdm' */ def hasCdm(cell: ArenaCell): Boolean = { cdmEdges.contains(cell) } /** * Check, whether two cells are connected with a 'has' edge. * * @param src * an edge origin * @param dst * an edge destination * @return * true, if src has an edge to dst labelled with 'has' */ def isLinkedViaHas(src: ArenaCell, dst: ArenaCell): Boolean = { def default: ArenaCell => List[ArenaCell] = _ => List() hasEdges.applyOrElse(src, default).contains(dst) } /** * Find all the cells of a given type. * * @return * all the cells that have exactly the same type as the argument (no unification involved) */ def findCellsByType(cellType: CellT): List[ArenaCell] = { cellMap.values.filter(_.cellType == cellType).toList } /** * Print the graph structure induced by 'has' edges starting with root. * * @param root * a cell to start from */ def subgraphToString(root: ArenaCell): String = { val builder = new StringBuilder() def print(cell: ArenaCell): Unit = { builder.append(cell.id) builder.append(" ") val cells = getHas(cell) if (cells.nonEmpty) { builder.append("has:(") for (c <- cells) print(c) builder.append(")") } } print(root) builder.mkString } }
1
0.902173
1
0.902173
game-dev
MEDIA
0.833071
game-dev
0.887087
1
0.887087
ikimiler/MobikeTags
8,648
MobikeLibrary/src/main/java/org/jbox2d/dynamics/ContactManager.java
/******************************************************************************* * Copyright (c) 2013, Daniel Murphy * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 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. ******************************************************************************/ package org.jbox2d.dynamics; import org.jbox2d.callbacks.ContactFilter; import org.jbox2d.callbacks.ContactListener; import org.jbox2d.callbacks.PairCallback; import org.jbox2d.collision.broadphase.BroadPhase; import org.jbox2d.dynamics.contacts.Contact; import org.jbox2d.dynamics.contacts.ContactEdge; /** * Delegate of World. * * @author Daniel Murphy */ public class ContactManager implements PairCallback { public BroadPhase m_broadPhase; public Contact m_contactList; public int m_contactCount; public ContactFilter m_contactFilter; public ContactListener m_contactListener; private final World pool; public ContactManager(World argPool, BroadPhase broadPhase) { m_contactList = null; m_contactCount = 0; m_contactFilter = new ContactFilter(); m_contactListener = null; m_broadPhase = broadPhase; pool = argPool; } /** * Broad-phase callback. * * @param proxyUserDataA * @param proxyUserDataB */ public void addPair(Object proxyUserDataA, Object proxyUserDataB) { FixtureProxy proxyA = (FixtureProxy) proxyUserDataA; FixtureProxy proxyB = (FixtureProxy) proxyUserDataB; Fixture fixtureA = proxyA.fixture; Fixture fixtureB = proxyB.fixture; int indexA = proxyA.childIndex; int indexB = proxyB.childIndex; Body bodyA = fixtureA.getBody(); Body bodyB = fixtureB.getBody(); // Are the fixtures on the same body? if (bodyA == bodyB) { return; } // TODO_ERIN use a hash table to remove a potential bottleneck when both // bodies have a lot of contacts. // Does a contact already exist? ContactEdge edge = bodyB.getContactList(); while (edge != null) { if (edge.other == bodyA) { Fixture fA = edge.contact.getFixtureA(); Fixture fB = edge.contact.getFixtureB(); int iA = edge.contact.getChildIndexA(); int iB = edge.contact.getChildIndexB(); if (fA == fixtureA && iA == indexA && fB == fixtureB && iB == indexB) { // A contact already exists. return; } if (fA == fixtureB && iA == indexB && fB == fixtureA && iB == indexA) { // A contact already exists. return; } } edge = edge.next; } // Does a joint override collision? is at least one body dynamic? if (bodyB.shouldCollide(bodyA) == false) { return; } // Check user filtering. if (m_contactFilter != null && m_contactFilter.shouldCollide(fixtureA, fixtureB) == false) { return; } // Call the factory. Contact c = pool.popContact(fixtureA, indexA, fixtureB, indexB); if (c == null) { return; } // Contact creation may swap fixtures. fixtureA = c.getFixtureA(); fixtureB = c.getFixtureB(); indexA = c.getChildIndexA(); indexB = c.getChildIndexB(); bodyA = fixtureA.getBody(); bodyB = fixtureB.getBody(); // Insert into the world. c.m_prev = null; c.m_next = m_contactList; if (m_contactList != null) { m_contactList.m_prev = c; } m_contactList = c; // Connect to island graph. // Connect to body A c.m_nodeA.contact = c; c.m_nodeA.other = bodyB; c.m_nodeA.prev = null; c.m_nodeA.next = bodyA.m_contactList; if (bodyA.m_contactList != null) { bodyA.m_contactList.prev = c.m_nodeA; } bodyA.m_contactList = c.m_nodeA; // Connect to body B c.m_nodeB.contact = c; c.m_nodeB.other = bodyA; c.m_nodeB.prev = null; c.m_nodeB.next = bodyB.m_contactList; if (bodyB.m_contactList != null) { bodyB.m_contactList.prev = c.m_nodeB; } bodyB.m_contactList = c.m_nodeB; // wake up the bodies if (!fixtureA.isSensor() && !fixtureB.isSensor()) { bodyA.setAwake(true); bodyB.setAwake(true); } ++m_contactCount; } public void findNewContacts() { m_broadPhase.updatePairs(this); } public void destroy(Contact c) { Fixture fixtureA = c.getFixtureA(); Fixture fixtureB = c.getFixtureB(); Body bodyA = fixtureA.getBody(); Body bodyB = fixtureB.getBody(); if (m_contactListener != null && c.isTouching()) { m_contactListener.endContact(c); } // Remove from the world. if (c.m_prev != null) { c.m_prev.m_next = c.m_next; } if (c.m_next != null) { c.m_next.m_prev = c.m_prev; } if (c == m_contactList) { m_contactList = c.m_next; } // Remove from body 1 if (c.m_nodeA.prev != null) { c.m_nodeA.prev.next = c.m_nodeA.next; } if (c.m_nodeA.next != null) { c.m_nodeA.next.prev = c.m_nodeA.prev; } if (c.m_nodeA == bodyA.m_contactList) { bodyA.m_contactList = c.m_nodeA.next; } // Remove from body 2 if (c.m_nodeB.prev != null) { c.m_nodeB.prev.next = c.m_nodeB.next; } if (c.m_nodeB.next != null) { c.m_nodeB.next.prev = c.m_nodeB.prev; } if (c.m_nodeB == bodyB.m_contactList) { bodyB.m_contactList = c.m_nodeB.next; } // Call the factory. pool.pushContact(c); --m_contactCount; } /** * This is the top level collision call for the time step. Here all the narrow phase collision is * processed for the world contact list. */ public void collide() { // Update awake contacts. Contact c = m_contactList; while (c != null) { Fixture fixtureA = c.getFixtureA(); Fixture fixtureB = c.getFixtureB(); int indexA = c.getChildIndexA(); int indexB = c.getChildIndexB(); Body bodyA = fixtureA.getBody(); Body bodyB = fixtureB.getBody(); // is this contact flagged for filtering? if ((c.m_flags & Contact.FILTER_FLAG) == Contact.FILTER_FLAG) { // Should these bodies collide? if (bodyB.shouldCollide(bodyA) == false) { Contact cNuke = c; c = cNuke.getNext(); destroy(cNuke); continue; } // Check user filtering. if (m_contactFilter != null && m_contactFilter.shouldCollide(fixtureA, fixtureB) == false) { Contact cNuke = c; c = cNuke.getNext(); destroy(cNuke); continue; } // Clear the filtering flag. c.m_flags &= ~Contact.FILTER_FLAG; } boolean activeA = bodyA.isAwake() && bodyA.m_type != BodyType.STATIC; boolean activeB = bodyB.isAwake() && bodyB.m_type != BodyType.STATIC; // At least one body must be awake and it must be dynamic or kinematic. if (activeA == false && activeB == false) { c = c.getNext(); continue; } int proxyIdA = fixtureA.m_proxies[indexA].proxyId; int proxyIdB = fixtureB.m_proxies[indexB].proxyId; boolean overlap = m_broadPhase.testOverlap(proxyIdA, proxyIdB); // Here we destroy contacts that cease to overlap in the broad-phase. if (overlap == false) { Contact cNuke = c; c = cNuke.getNext(); destroy(cNuke); continue; } // The contact persists. c.update(m_contactListener); c = c.getNext(); } } }
1
0.956665
1
0.956665
game-dev
MEDIA
0.248857
game-dev
0.983382
1
0.983382
Kenny-Haworth/Harvest-Moon-2.0
19,895
Harvest Moon 2.0/areas/Farm.gd
#The player may interact with dirt and crops (such as tilling and watering #soil or planting crops), but may not interact with the background. Objects #require interaction to prevent the player from moving to squares with objects #on them, so all object tilemaps are added to the main grid. extends Node2D #get the master node onready var Game = get_node("/root/Game") #get the sound manager for playing sounds onready var SoundManager = get_node("/root/Game/Sound") #for removing seeds from the inventory once planted #must be initialized during runtime var Inventory #get all the necessary tilemaps for this area (in top draw order) onready var Crops = get_node("Crops") onready var Dirt = get_node("Dirt") onready var Junk = get_node("Junk") onready var Objects1 = get_node("Objects1") onready var Objects2 = get_node("Objects2") onready var Background2 = get_node("Background2") #location of other areas to teleport to const teleport_areas = [Vector2(19,8), Vector2(19,-1)] #declare the size of this area and the tile sizes of this area const grid_size = Vector2(39, 23) #39 tiles x 23 tiles (x,y) var tile_size #32 pixels x 32 pixels, inherited from Game var half_tile_size var grid = [] func _ready(): tile_size = Game.tile_size half_tile_size = Game.half_tile_size #add all objects to the grid for this area for x in range(grid_size.x): grid.append([]) for y in range(grid_size.y): if Objects1.get_cell(x, y) != -1 or Objects2.get_cell(x,y) != -1: #add all objects to the grid grid[x].append(1) else: grid[x].append(null) #this function tells the player if they are about to be teleported to a new area func teleport(position): if teleport_areas.has(Objects1.world_to_map(position)): #the player is going into their house or into the town return true return false #checks if this cell is vacant func is_cell_vacant(pos, direction): var grid_pos = Objects1.world_to_map(pos) + direction if teleport_areas.has(grid_pos): return true if grid_pos.x < grid_size.x and grid_pos.x >= 0: if grid_pos.y < grid_size.y and grid_pos.y >= 0: if grid[grid_pos.x][grid_pos.y] != 1: return true return false #updates the grid position for the player func update_child_pos(child_node): var grid_pos = Objects1.world_to_map(child_node.position) grid[grid_pos.x][grid_pos.y] = null var new_grid_pos = grid_pos + child_node.direction var target_pos = Objects1.map_to_world(new_grid_pos) + half_tile_size return target_pos #simulate plant growth (or decay) for the day func sleep(): for x in range(grid_size.x): for y in range(grid_size.y): #each crop must be watered for it to progress to the next growth cycle #after the day, the crop must be watered again #grow turnips if Crops.get_cell(x,y) == 0 and Dirt.get_cell(x,y) == 2: Crops.set_cellv(Vector2(x, y), 1) Dirt.set_cell(x,y,0) elif Crops.get_cell(x,y) == 1 and Dirt.get_cell(x,y) == 2: Crops.set_cellv(Vector2(x, y), 2) Dirt.set_cell(x,y,0) elif Crops.get_cell(x,y) == 2 and Dirt.get_cell(x,y) == 2: Crops.set_cellv(Vector2(x, y), 3) Dirt.set_cell(x,y,0) elif Crops.get_cell(x,y) == 3 and Dirt.get_cell(x,y) == 2: Crops.set_cellv(Vector2(x, y), 4) Dirt.set_cell(x,y,0) elif Crops.get_cell(x,y) == 4 and Dirt.get_cell(x,y) == 2: Crops.set_cellv(Vector2(x, y), 5) Dirt.set_cell(x,y,0) #grow strawberries elif Crops.get_cell(x,y) == 30 and Dirt.get_cell(x,y) == 2: Crops.set_cellv(Vector2(x, y), 31) Dirt.set_cell(x,y,0) elif Crops.get_cell(x,y) == 31 and Dirt.get_cell(x,y) == 2: Crops.set_cellv(Vector2(x, y), 32) Dirt.set_cell(x,y,0) elif Crops.get_cell(x,y) == 32 and Dirt.get_cell(x,y) == 2: Crops.set_cellv(Vector2(x, y), 33) Dirt.set_cell(x,y,0) elif Crops.get_cell(x,y) == 33 and Dirt.get_cell(x,y) == 2: Crops.set_cellv(Vector2(x, y), 34) Dirt.set_cell(x,y,0) elif Crops.get_cell(x,y) == 34 and Dirt.get_cell(x,y) == 2: Crops.set_cellv(Vector2(x, y), 35) Dirt.set_cell(x,y,0) #grow eggplants elif Crops.get_cell(x,y) == 12 and Dirt.get_cell(x,y) == 2: Crops.set_cellv(Vector2(x, y), 13) Dirt.set_cell(x,y,0) elif Crops.get_cell(x,y) == 13 and Dirt.get_cell(x,y) == 2: Crops.set_cellv(Vector2(x, y), 14) Dirt.set_cell(x,y,0) elif Crops.get_cell(x,y) == 14 and Dirt.get_cell(x,y) == 2: Crops.set_cellv(Vector2(x, y), 15) Dirt.set_cell(x,y,0) elif Crops.get_cell(x,y) == 15 and Dirt.get_cell(x,y) == 2: Crops.set_cellv(Vector2(x, y), 16) Dirt.set_cell(x,y,0) elif Crops.get_cell(x,y) == 16 and Dirt.get_cell(x,y) == 2: Crops.set_cellv(Vector2(x, y), 17) Dirt.set_cell(x,y,0) #any watered dirt without crops should become unwatered at the end of the day elif Dirt.get_cell(x,y) == 2: Dirt.set_cell(x,y,0) #chance to spawn wood, weeds, or stone at the end of the day, #conditions: it is a soil cell, it is not tilled, it does not already have junk on it #5% chance to spawn junk if Background2.get_cell(x,y) == 15 and Dirt.get_cell(x,y) == -1 and Junk.get_cell(x,y) == -1 and randi()%20 + 1 == 1: var junk_type = randi()%3 + 1 #1-3 if junk_type == 1: Junk.set_cell(x,y,4) #weeds elif junk_type == 2: if randi()%2+1 == 1: Junk.set_cell(x,y,2) #rock 1 else: Junk.set_cell(x,y,3) #rock 2 elif junk_type == 3: Junk.set_cell(x,y,0) #wood #change the tile the player has swung their hammer towards func smash_hammer(pos, orientation): if orientation == "up": pos.y -= tile_size.x elif orientation == "down": pos.y += tile_size.x elif orientation == "right": pos.x += tile_size.x elif orientation == "left": pos.x -= tile_size.x #un-till the tile of dirt if there are no crops on it, and it is tilled or tilled and watered if (Crops.get_cellv(Crops.world_to_map(pos)) == -1) and (Dirt.get_cellv(Dirt.world_to_map(pos)) == 0 or Dirt.get_cellv(Dirt.world_to_map(pos)) == 2): Dirt.set_cellv(Dirt.world_to_map(pos), -1) if not SoundManager.is_playing("hammer"): #do not overlap this sound SoundManager.play_tool("hammer") use_energy() elif (Junk.get_cellv(Junk.world_to_map(pos)) == 2) or (Junk.get_cellv(Junk.world_to_map(pos)) == 3): Junk.set_cellv(Junk.world_to_map(pos), -1) if not SoundManager.is_playing("hammer"): SoundManager.play_tool("hammer") use_energy() #spread seeds around the player func spread_seeds(pos, seedType): #get the inventory once if Inventory == null: Inventory = $Player.get_node("UI/Inventory") #the number of seeds currently in the inventory var num_seeds = Inventory.get_amount(Inventory.equippedItem) #TODO lots of repeated logic here, should be some way of simplifying it #only spread seeds if the tile is already tilled or watered (0 or 2) #also, there must not already be seeds or crops on this tile if (Dirt.get_cellv(Dirt.world_to_map(Vector2(pos.x+tile_size.x, pos.y))) >= 0) and (Crops.get_cellv(Crops.world_to_map(Vector2(pos.x+tile_size.x, pos.y))) == -1) and num_seeds > 0: Crops.set_cellv(Crops.world_to_map(Vector2(pos.x+tile_size.x, pos.y)), seedType) num_seeds -= 1 Inventory.remove(Inventory.equippedItem) if not SoundManager.is_playing("seeds"): #TODO overlap these sounds SoundManager.play_tool("seeds") use_energy() if (Dirt.get_cellv(Dirt.world_to_map(Vector2(pos.x-tile_size.x, pos.y))) >= 0) and (Crops.get_cellv(Crops.world_to_map(Vector2(pos.x-tile_size.x, pos.y))) == -1) and num_seeds > 0: Crops.set_cellv(Crops.world_to_map(Vector2(pos.x-tile_size.x, pos.y)), seedType) num_seeds -= 1 Inventory.remove(Inventory.equippedItem) if not SoundManager.is_playing("seeds"): SoundManager.play_tool("seeds") use_energy() if (Dirt.get_cellv(Dirt.world_to_map(Vector2(pos.x, pos.y+tile_size.x))) >= 0) and (Crops.get_cellv(Crops.world_to_map(Vector2(pos.x, pos.y+tile_size.x))) == -1) and num_seeds > 0: Crops.set_cellv(Crops.world_to_map(Vector2(pos.x, pos.y+tile_size.x)), seedType) num_seeds -= 1 Inventory.remove(Inventory.equippedItem) if not SoundManager.is_playing("seeds"): SoundManager.play_tool("seeds") use_energy() if (Dirt.get_cellv(Dirt.world_to_map(Vector2(pos.x, pos.y-tile_size.x))) >= 0) and (Crops.get_cellv(Crops.world_to_map(Vector2(pos.x, pos.y-tile_size.x))) == -1) and num_seeds > 0: Crops.set_cellv(Crops.world_to_map(Vector2(pos.x, pos.y-tile_size.x)), seedType) num_seeds -= 1 Inventory.remove(Inventory.equippedItem) if not SoundManager.is_playing("seeds"): SoundManager.play_tool("seeds") use_energy() if (Dirt.get_cellv(Dirt.world_to_map(Vector2(pos.x+tile_size.x, pos.y+tile_size.x))) >= 0) and (Crops.get_cellv(Crops.world_to_map(Vector2(pos.x+tile_size.x, pos.y+tile_size.x))) == -1) and num_seeds > 0: Crops.set_cellv(Crops.world_to_map(Vector2(pos.x+tile_size.x, pos.y+tile_size.x)), seedType) num_seeds -= 1 Inventory.remove(Inventory.equippedItem) if not SoundManager.is_playing("seeds"): SoundManager.play_tool("seeds") use_energy() if (Dirt.get_cellv(Dirt.world_to_map(Vector2(pos.x+tile_size.x, pos.y-tile_size.x))) >= 0) and (Crops.get_cellv(Crops.world_to_map(Vector2(pos.x+tile_size.x, pos.y-tile_size.x))) == -1) and num_seeds > 0: Crops.set_cellv(Crops.world_to_map(Vector2(pos.x+tile_size.x, pos.y-tile_size.x)), seedType) num_seeds -= 1 Inventory.remove(Inventory.equippedItem) if not SoundManager.is_playing("seeds"): SoundManager.play_tool("seeds") if (Dirt.get_cellv(Dirt.world_to_map(Vector2(pos.x-tile_size.x, pos.y+tile_size.x))) >= 0) and (Crops.get_cellv(Crops.world_to_map(Vector2(pos.x-tile_size.x, pos.y+tile_size.x))) == -1) and num_seeds > 0: Crops.set_cellv(Crops.world_to_map(Vector2(pos.x-tile_size.x, pos.y+tile_size.x)), seedType) num_seeds -= 1 Inventory.remove(Inventory.equippedItem) if not SoundManager.is_playing("seeds"): SoundManager.play_tool("seeds") use_energy() if (Dirt.get_cellv(Dirt.world_to_map(Vector2(pos.x-tile_size.x, pos.y-tile_size.x))) >= 0) and (Crops.get_cellv(Crops.world_to_map(Vector2(pos.x-tile_size.x, pos.y-tile_size.x))) == -1) and num_seeds > 0: Crops.set_cellv(Crops.world_to_map(Vector2(pos.x-tile_size.x, pos.y-tile_size.x)), seedType) num_seeds -= 1 Inventory.remove(Inventory.equippedItem) if not SoundManager.is_playing("seeds"): SoundManager.play_tool("seeds") use_energy() if (Dirt.get_cellv(Dirt.world_to_map(pos)) >= 0) and (Crops.get_cellv(Crops.world_to_map(pos)) == -1) and num_seeds > 0: Crops.set_cellv(Crops.world_to_map(pos), seedType) num_seeds -= 1 Inventory.remove(Inventory.equippedItem) if not SoundManager.is_playing("seeds"): SoundManager.play_tool("seeds") use_energy() #tills 3 tiles of soil the player is facing towards func swing_hoe(pos, orientation): var x1 = 0 var y1 = 0 var x2 = 0 var y2 = 0 if orientation == "up": pos.y -= tile_size.x x1 += tile_size.x x2 -= tile_size.x elif orientation == "down": pos.y += tile_size.x x1 += tile_size.x x2 -= tile_size.x elif orientation == "right": pos.x += tile_size.x y1 += tile_size.x y2 -= tile_size.x elif orientation == "left": pos.x -= tile_size.x y1 += tile_size.x y2 -= tile_size.x #create tilled soil #check that the square is first a soil square and that it isn't already watered or hoed. It also must have no junk on it if Background2.get_cellv(Background2.world_to_map(pos)) == 15 and Dirt.get_cellv(Dirt.world_to_map(pos)) == -1 and Junk.get_cellv(Junk.world_to_map(pos)) == -1: Dirt.set_cellv(Dirt.world_to_map(pos), 0) if not SoundManager.is_playing("hoe"): SoundManager.play_tool("hoe") use_energy() if Background2.get_cellv(Background2.world_to_map(Vector2(pos.x+x1,pos.y+y1))) == 15 and Dirt.get_cellv(Dirt.world_to_map(Vector2(pos.x+x1,pos.y+y1))) == -1 and Junk.get_cellv(Junk.world_to_map(Vector2(pos.x+x1,pos.y+y1))) == -1: Dirt.set_cellv(Dirt.world_to_map(Vector2(pos.x+x1,pos.y+y1)), 0) if not SoundManager.is_playing("hoe"): SoundManager.play_tool("hoe") use_energy() if Background2.get_cellv(Background2.world_to_map(Vector2(pos.x+x2,pos.y+y2))) == 15 and Dirt.get_cellv(Dirt.world_to_map(Vector2(pos.x+x2,pos.y+y2))) == -1 and Junk.get_cellv(Junk.world_to_map(Vector2(pos.x+x2,pos.y+y2))) == -1: Dirt.set_cellv(Dirt.world_to_map(Vector2(pos.x+x2,pos.y+y2)), 0) if not SoundManager.is_playing("hoe"): SoundManager.play_tool("hoe") use_energy() #deletes logs func swing_axe(pos, orientation): if orientation == "up": pos.y -= tile_size.x elif orientation == "down": pos.y += tile_size.x elif orientation == "right": pos.x += tile_size.x elif orientation == "left": pos.x -= tile_size.x if (Junk.get_cellv(Junk.world_to_map(pos)) == 0): Junk.set_cellv(Junk.world_to_map(pos), 1) if not SoundManager.is_playing("axe"): #do not overlap this sound SoundManager.play_tool("axe") use_energy() elif (Junk.get_cellv(Junk.world_to_map(pos)) == 1) and not SoundManager.is_playing("axe"): #TODO temporary fix for running code twice Junk.set_cellv(Junk.world_to_map(pos), -1) if not SoundManager.is_playing("axe"): #do not overlap this sound SoundManager.play_tool("axe") use_energy() #deletes weeds func swing_sickle(pos, orientation): if orientation == "up": pos.y -= tile_size.x elif orientation == "down": pos.y += tile_size.x elif orientation == "right": pos.x += tile_size.x elif orientation == "left": pos.x -= tile_size.x if (Junk.get_cellv(Junk.world_to_map(pos)) == 4): Junk.set_cellv(Junk.world_to_map(pos), -1) if not SoundManager.is_playing("sickle"): #do not overlap this sound SoundManager.play_tool("sickle") use_energy() #deletes weeds all around func swing_sickle_circle(pos): if (Junk.get_cellv(Junk.world_to_map(Vector2(pos.x+tile_size.x, pos.y))) == 4): Junk.set_cellv(Junk.world_to_map(Vector2(pos.x+tile_size.x, pos.y)), -1) if not SoundManager.is_playing("sickle"): #do not overlap this sound SoundManager.play_tool("sickle") use_energy() if (Junk.get_cellv(Junk.world_to_map(Vector2(pos.x-tile_size.x, pos.y))) == 4): Junk.set_cellv(Junk.world_to_map(Vector2(pos.x-tile_size.x, pos.y)), -1) if not SoundManager.is_playing("sickle"): SoundManager.play_tool("sickle") use_energy() if (Junk.get_cellv(Junk.world_to_map(Vector2(pos.x, pos.y+tile_size.x))) == 4): Junk.set_cellv(Junk.world_to_map(Vector2(pos.x, pos.y+tile_size.x)), -1) if not SoundManager.is_playing("sickle"): SoundManager.play_tool("sickle") use_energy() if (Junk.get_cellv(Junk.world_to_map(Vector2(pos.x, pos.y-tile_size.x))) == 4): Junk.set_cellv(Junk.world_to_map(Vector2(pos.x, pos.y-tile_size.x)), -1) if not SoundManager.is_playing("sickle"): SoundManager.play_tool("sickle") use_energy() if (Junk.get_cellv(Junk.world_to_map(Vector2(pos.x+tile_size.x, pos.y+tile_size.x))) == 4): Junk.set_cellv(Junk.world_to_map(Vector2(pos.x+tile_size.x, pos.y+tile_size.x)), -1) if not SoundManager.is_playing("sickle"): SoundManager.play_tool("sickle") use_energy() if (Junk.get_cellv(Junk.world_to_map(Vector2(pos.x+tile_size.x, pos.y-tile_size.x))) == 4): Junk.set_cellv(Junk.world_to_map(Vector2(pos.x+tile_size.x, pos.y-tile_size.x)), -1) if not SoundManager.is_playing("sickle"): SoundManager.play_tool("sickle") use_energy() if (Junk.get_cellv(Junk.world_to_map(Vector2(pos.x-tile_size.x, pos.y+tile_size.x))) == 4): Junk.set_cellv(Junk.world_to_map(Vector2(pos.x-tile_size.x, pos.y+tile_size.x)), -1) if not SoundManager.is_playing("sickle"): SoundManager.play_tool("sickle") use_energy() if (Junk.get_cellv(Junk.world_to_map(Vector2(pos.x-tile_size.x, pos.y-tile_size.x))) == 4): Junk.set_cellv(Junk.world_to_map(Vector2(pos.x-tile_size.x, pos.y-tile_size.x)), -1) if not SoundManager.is_playing("sickle"): SoundManager.play_tool("sickle") use_energy() if (Junk.get_cellv(Junk.world_to_map(pos)) == 4): Junk.set_cellv(Junk.world_to_map(pos), -1) if not SoundManager.is_playing("sickle"): SoundManager.play_tool("sickle") use_energy() func water_square(pos, orientation): if orientation == "up": pos.y -= tile_size.x elif orientation == "down": pos.y += tile_size.x elif orientation == "right": pos.x += tile_size.x elif orientation == "left": pos.x -= tile_size.x #the cell must be tilled before it can be watered if (Dirt.get_cellv(Dirt.world_to_map(pos)) == 0): Dirt.set_cellv(Dirt.world_to_map(pos), 2) if not SoundManager.is_playing("watering"): SoundManager.play_tool("watering") use_energy() #checks to make sure that there is a fully grown crop on this cell that is ready to harvest #the id number of this crop is returned, or -1 if there is no crop ready for harvest on this square func check_square_for_harvest(pos, orientation): if orientation == "up": pos.y -= tile_size.x elif orientation == "down": pos.y += tile_size.x elif orientation == "right": pos.x += tile_size.x elif orientation == "left": pos.x -= tile_size.x #the cell is a turnip if Crops.get_cellv(Crops.world_to_map(pos)) == 5: return 5 #the cell is a strawberry elif Crops.get_cellv(Crops.world_to_map(pos)) == 35: return 35 #the cell is an eggplant elif Crops.get_cellv(Crops.world_to_map(pos)) == 17: return 17 return -1 #there is no crop ready for harvest on this square #this is a "safe" function; it is only called if check_square_for_harvest() was called in the player script first #thus, checking does not need to occur within this function to ensure the square is ready for harvest func harvest_crop(pos, orientation): if orientation == "up": pos.y -= tile_size.x elif orientation == "down": pos.y += tile_size.x elif orientation == "right": pos.x += tile_size.x elif orientation == "left": pos.x -= tile_size.x #remove the crop from this tile Crops.set_cellv(Crops.world_to_map(pos), -1) if not SoundManager.is_playing("harvest"): SoundManager.play_effect("harvest") #checks to make sure that there is nothing else on this square, so that the player may drop a harvested crop they are holding on this square #returns true if the player may drop their item, returns false otherwise func check_square_for_drop(pos, orientation): if orientation == "up": pos.y -= tile_size.x elif orientation == "down": pos.y += tile_size.x elif orientation == "right": pos.x += tile_size.x elif orientation == "left": pos.x -= tile_size.x #ensures there are no crops or non-passable objects on this tile if Crops.get_cellv(Crops.world_to_map(pos)) != -1: return false elif Objects1.get_cellv(Objects1.world_to_map(pos)) != -1: return false elif Objects2.get_cellv(Objects2.world_to_map(pos)) != -1: return false elif teleport_areas.has(Objects2.world_to_map(pos)): #the player is trying to drop a crop on a teleport tile return false return true #this is a "safe" function; it is only called if check_square_for_drop() was called in the player script first #thus, checking does not need to occur within this function to ensure the square is clear for a harvested crop to be dropped on func drop_crop(pos, orientation, crop_number): if orientation == "up": pos.y -= tile_size.x elif orientation == "down": pos.y += tile_size.x elif orientation == "right": pos.x += tile_size.x elif orientation == "left": pos.x -= tile_size.x Crops.set_cellv(Crops.world_to_map(pos), crop_number) if not SoundManager.is_playing("drop"): SoundManager.play_effect("drop") #waters all unwatered, tilled soil func simulate_rain(): for x in range(grid_size.x): for y in range(grid_size.y): #the cell must be tilled and unwatered to be watered by rain if (Dirt.get_cell(x,y) == 0): Dirt.set_cell(x,y,2) func use_energy(): var UI = get_node("Player/UI/Energy Bar") #TODO do not access this node each time, save it somewhere and access it TODO its also labeled wrong UI.take_action()
1
0.563732
1
0.563732
game-dev
MEDIA
0.629161
game-dev
0.79844
1
0.79844
analgesicproductions/Anodyne-1-Repo
12,706
intra/src/org/flixel/FlxSound.as
package org.flixel { import flash.events.Event; import flash.media.Sound; import flash.media.SoundChannel; import flash.media.SoundTransform; import flash.net.URLRequest; import flash.events.SampleDataEvent; import flash.utils.ByteArray; /** * This is the universal flixel sound object, used for streaming, music, and sound effects. * * EMBEDDED SEAMLESS LOOPING MODIFICATION BY MAX "GETI" CAHILL. */ public class FlxSound extends FlxObject { /** * Whether or not this sound should be automatically destroyed when you switch states. */ public var survive:Boolean; /** * Whether the sound is currently playing or not. */ public var playing:Boolean; /** * The ID3 song name. Defaults to null. Currently only works for streamed sounds. */ public var name:String; /** * The ID3 artist name. Defaults to null. Currently only works for streamed sounds. */ public var artist:String; public var fixed:Boolean; /* * A bunch of looping variables follow. */ protected const MAGIC_DELAY:Number = 2766.0; //THE MAGIC NUMBER protected const bufferSize:int = 4096; //this gives stable playback protected var samplesTotal:int = 0; //this _must_ be known about the song to be looped public var loop_start:int = 0; protected var samplesPosition:int = 0; //helper for reading the sound protected var _streaming:Boolean; //whether we're streaming the audio or not /* * The default FlxSound variables */ protected var _init:Boolean; public var _sound:Sound; protected var _in:Sound; public var _channel:SoundChannel; protected var _transform:SoundTransform; public var _position:Number; protected var _volume:Number; protected var _volumeAdjust:Number; protected var _looped:Boolean; protected var _core:FlxObject; protected var _radius:Number; protected var _pan:Boolean; protected var _fadeOutTimer:Number; protected var _fadeOutTotal:Number; protected var _pauseOnFadeOut:Boolean; protected var _fadeInTimer:Number; protected var _fadeInTotal:Number; protected var _point2:FlxPoint; /** * The FlxSound constructor gets all the variables initialized, but NOT ready to play a sound yet. */ public function FlxSound() { super(); _point2 = new FlxPoint(); _transform = new SoundTransform(); init(); fixed = true; //no movement usually } /** * An internal function for clearing all the variables used by sounds. */ protected function init():void { _transform.pan = 0; _sound = null; _in = null; _position = 0; _volume = 1.0; _volumeAdjust = 1.0; _looped = false; _core = null; _radius = 0; _pan = false; _fadeOutTimer = 0; _fadeOutTotal = 0; _pauseOnFadeOut = false; _fadeInTimer = 0; _fadeInTotal = 0; active = false; visible = false; solid = false; playing = false; name = null; artist = null; } /** * One of two main setup functions for sounds, this function loads a sound from an embedded MP3. * * @param EmbeddedSound An embedded Class object representing an MP3 file. * @param Looped Whether or not this sound should loop endlessly. * @param totalSamples If looped is true, the number of samples is needed. * * @return This <code>FlxSound</code> instance (nice for chaining stuff together, if you're into that). */ public function loadEmbedded(EmbeddedSound:Class, Looped:Boolean=false, totalSamples:int = 0, _loop_start:int=0):FlxSound { stop(); init(); if (Looped) { _in = new EmbeddedSound; _sound = new Sound(); _sound.addEventListener( SampleDataEvent.SAMPLE_DATA, sampleData ); samplesTotal = totalSamples - MAGIC_DELAY; //prevents any delay at the end of the track as well. loop_start = _loop_start; } else _sound = new EmbeddedSound; //NOTE: can't pull ID3 info from embedded sound currently _streaming = false; _looped = Looped; updateTransform(); active = true; return this; } /** * One of two main setup functions for sounds, this function loads a sound from a URL. * * @param EmbeddedSound A string representing the URL of the MP3 file you want to play. * @param Looped Whether or not this sound should loop endlessly. * * @return This <code>FlxSound</code> instance (nice for chaining stuff together, if you're into that). */ public function loadStream(SoundURL:String, Looped:Boolean=false):FlxSound { stop(); init(); _sound = new Sound(); _sound.addEventListener(Event.ID3, gotID3); _sound.load(new URLRequest(SoundURL)); _streaming = true; _looped = Looped; updateTransform(); active = true; return this; } /** * Call this function if you want this sound's volume to change * based on distance from a particular FlxCore object. * * @param X The X position of the sound. * @param Y The Y position of the sound. * @param Core The object you want to track. * @param Radius The maximum distance this sound can travel. * * @return This FlxSound instance (nice for chaining stuff together, if you're into that). */ public function proximity(X:Number,Y:Number,Core:FlxObject,Radius:Number,Pan:Boolean=true):FlxSound { x = X; y = Y; _core = Core; _radius = Radius; _pan = Pan; return this; } /** * Call this function to play the sound. */ public function play():void { volume = FlxG.volume; if(_position < 0) return; if(_looped) { if (!_streaming) { if (_channel == null) _channel = _sound.play(0,9999,_transform); if(_channel == null) active = false; } else { if(_position == 0) { if(_channel == null) _channel = _sound.play(0,9999,_transform); if(_channel == null) active = false; } else { _channel = _sound.play(_position,0,_transform); if(_channel == null) active = false; else _channel.addEventListener(Event.SOUND_COMPLETE, looped); } } } else { if(_position == 0) { if(_channel == null) { _channel = _sound.play(0,0,_transform); if(_channel == null) active = false; else _channel.addEventListener(Event.SOUND_COMPLETE, stopped); } } else { _channel = _sound.play(_position,0,_transform); if(_channel == null) active = false; } } playing = (_channel != null); _position = 0; } /** * Call this function to pause this sound. */ public function pause():void { if(_channel == null) { _position = -1; return; } _position = _channel.position; _channel.stop(); if(_looped) { while(_position >= _sound.length) _position -= _sound.length; } _channel = null; playing = false; } /** * Call this function to stop this sound. */ public function stop():void { _position = 0; if(_channel != null) { _channel.stop(); stopped(); } } /** * Call this function to make this sound fade out over a certain time interval. * * @param Seconds The amount of time the fade out operation should take. * @param PauseInstead Tells the sound to pause on fadeout, instead of stopping. */ public function fadeOut(Seconds:Number,PauseInstead:Boolean=false):void { _pauseOnFadeOut = PauseInstead; _fadeInTimer = 0; _fadeOutTimer = Seconds; _fadeOutTotal = _fadeOutTimer; } /** * Call this function to make a sound fade in over a certain * time interval (calls <code>play()</code> automatically). * * @param Seconds The amount of time the fade-in operation should take. */ public function fadeIn(Seconds:Number):void { _fadeOutTimer = 0; _fadeInTimer = Seconds; _fadeInTotal = _fadeInTimer; play(); } /** * Set <code>volume</code> to a value between 0 and 1 to change how this sound is. */ public function get volume():Number { return _volume; } /** * @private */ public function set volume(Volume:Number):void { _volume = Volume; if(_volume < 0) _volume = 0; else if(_volume > 1) _volume = 1; updateTransform(); } /** * Internal function that performs the actual logical updates to the sound object. * Doesn't do much except optional proximity and fade calculations. */ protected function updateSound():void { if(_position != 0) return; var radial:Number = 1.0; var fade:Number = 1.0; //Distance-based volume control if(_core != null) { var _point:FlxPoint = new FlxPoint(); var _point2:FlxPoint = new FlxPoint(); _core.getScreenXY(_point); getScreenXY(_point2); var dx:Number = _point.x - _point2.x; var dy:Number = _point.y - _point2.y; radial = (_radius - Math.sqrt(dx*dx + dy*dy))/_radius; if(radial < 0) radial = 0; if(radial > 1) radial = 1; if(_pan) { var d:Number = -dx/_radius; if(d < -1) d = -1; else if(d > 1) d = 1; _transform.pan = d; } } //Cross-fading volume control if(_fadeOutTimer > 0) { _fadeOutTimer -= FlxG.elapsed; if(_fadeOutTimer <= 0) { if(_pauseOnFadeOut) pause(); else stop(); } fade = _fadeOutTimer/_fadeOutTotal; if(fade < 0) fade = 0; } else if(_fadeInTimer > 0) { _fadeInTimer -= FlxG.elapsed; fade = _fadeInTimer/_fadeInTotal; if(fade < 0) fade = 0; fade = 1 - fade; } _volumeAdjust = radial*fade; updateTransform(); } /** * The basic game loop update function. Just calls <code>updateSound()</code>. */ override public function update():void { super.update(); updateSound(); } /** * The basic class destructor, stops the music and removes any leftover events. */ override public function destroy():void { if(active) stop(); } /** * An internal function used to help organize and change the volume of the sound. */ internal function updateTransform():void { //_transform.volume = FlxG.getMuteValue()*FlxG.volume*_volume*_volumeAdjust; _transform.volume = FlxG.volume*_volume*_volumeAdjust; if(_channel != null) _channel.soundTransform = _transform; } /** * An internal helper function used to help Flash resume playing a looped sound. * * @param event An <code>Event</code> object. */ protected function looped(event:Event=null):void { if (_channel == null) return; _channel.removeEventListener(Event.SOUND_COMPLETE,looped); _channel = null; play(); } /** * An internal helper function used to help Flash clean up and re-use finished sounds. * * @param event An <code>Event</code> object. */ protected function stopped(event:Event=null):void { if(!_looped) _channel.removeEventListener(Event.SOUND_COMPLETE,stopped); else _channel.removeEventListener(Event.SOUND_COMPLETE,looped); _channel = null; active = false; playing = false; } /** * Internal event handler for ID3 info (i.e. fetching the song name). * * @param event An <code>Event</code> object. */ protected function gotID3(event:Event=null):void { FlxG.log("got ID3 info!"); if(_sound.id3.songName.length > 0) name = _sound.id3.songName; if(_sound.id3.artist.length > 0) artist = _sound.id3.artist; _sound.removeEventListener(Event.ID3, gotID3); } //this is just forwarding the event and bufferSize to the extraction function. protected function sampleData( event:SampleDataEvent ):void { extract( event.data, bufferSize ); } /** * This methods extracts audio data from the mp3 and wraps it automatically with respect to encoder delay * * @param target The ByteArray where to write the audio data * @param length The amount of samples to be read */ protected function extract( target: ByteArray, length:int ):void { if (samplesTotal == 0) return; while( 0 < length ) { if( samplesPosition + length > samplesTotal ) { var read: int = samplesTotal - samplesPosition; _in.extract( target, read, samplesPosition + MAGIC_DELAY ); samplesPosition += read; length -= read; } else { _in.extract( target, length, samplesPosition + MAGIC_DELAY ); samplesPosition += length; length = 0; } if( samplesPosition == samplesTotal ) // WE ARE AT THE END OF THE LOOP > WRAP { samplesPosition = loop_start; } } } } }
1
0.864033
1
0.864033
game-dev
MEDIA
0.675242
game-dev,audio-video-media
0.983021
1
0.983021
SOUI2/soui.backup
20,592
demos/SouiEditor/propgrid/SPropertyGrid.cpp
#include "StdAfx.h" #include "SPropertyGrid.h" #include "propitem/SPropertyItem-Text.h" #include "propitem/SPropertyItem-Option.h" #include "propitem/SPropertyItem-Color.h" #include "propitem/SPropertyItem-Size.h" const int KPropItemIndent = 10; const COLORREF KColorHead = RGBA(128,128,128,255); //ͷɫ ɫ const COLORREF KColorGroup = RGBA(128,128,128,255); //ɫ ɫ const COLORREF KColorItem = RGBA(255,255,255,255); //δѡеɫ ɫ const COLORREF KColorItemSel = RGBA(0,0,128,255); //ѡʱitemɫ const COLORREF KColorBorder = RGBA(0,0,0,255); //߿ɫ ɫ namespace SOUI { ////////////////////////////////////////////////////////////////////////// void SPropertyGroup::DrawItem( IRenderTarget *pRT,CRect rc ) { pRT->FillSolidRect(rc,KColorGroup); } ////////////////////////////////////////////////////////////////////////// SPropItemMap SPropItemMap::s_mapPropItem; SPropItemMap::SPropItemMap() { //עÿһItemͺItemĴʽ // /* <groups> <propgroup name="group1" description="desc of group1"> <propcolor name="color2.1" value="#00ff00" format="#%02x%02x%02x%02x"/> <propsize name="size2.1" value="200,300" childrenNames="|"/> <proptext name="text2.2" value="value 2.2"></proptext> <propoption name="option2.1" value="1" options="true|false|empty"/> </propgroup </groups> */ //xmlNode.name = propcolor propsize proptextʱֱöӦCreatePropItem SetAt(SPropertyItemText::GetClassName(),SPropertyItemText::CreatePropItem); SetAt(SPropertyItemOption::GetClassName(),SPropertyItemOption::CreatePropItem); SetAt(SPropertyItemColor::GetClassName(),SPropertyItemColor::CreatePropItem); SetAt(SPropertyItemSize::GetClassName(),SPropertyItemSize::CreatePropItem); SetAt(SPropertyGroup::GetClassName(),SPropertyGroup::CreatePropItem); } void SPropItemMap::RegPropItem( const SStringW & strName, FunCreatePropItem funCreate ) { s_mapPropItem.SetAt(strName,funCreate); } IPropertyItem * SPropItemMap::CreatePropItem( const SStringW & strName ,SPropertyGrid *pOwner ) { if(!s_mapPropItem.Lookup(strName)) return NULL; return s_mapPropItem[strName](pOwner); } ////////////////////////////////////////////////////////////////////////// SPropertyGrid::SPropertyGrid(void) :m_nIndent(KPropItemIndent) ,m_nNameWidth(100) ,m_switchSkin(NULL) ,m_bDraging(FALSE) ,m_pInplaceActiveWnd(NULL) ,m_crGroup(CR_INVALID) ,m_crItem(CR_INVALID) ,m_crItemText(CR_INVALID) ,m_crItemSel(CR_INVALID) ,m_strEditBkgndColor(_T("#FFFFFF00")) ,m_strEditTextColor(_T("#FFFFFF")) ,m_crBorder(RGBA(255,255,255,70)) ,m_strEnableAutoWordSel(_T("1")) { //ע¼ //1itemֵıʱӦ //2SelıʱӦ GetEventSet()->addEvent(EVENTID(EventPropGridValueChanged)); GetEventSet()->addEvent(EVENTID(EventPropGridItemClick)); GetEventSet()->addEvent(EVENTID(EventPropGridItemActive)); GetEventSet()->subscribeEvent(EventLBSelChanged::EventID,Subscriber(&SPropertyGrid::OnSelChanged,this)); } SPropertyGrid::~SPropertyGrid(void) { SPOSITION pos = m_lstGroup.GetHeadPosition(); while(pos) { SPropertyGroup * pGroup = m_lstGroup.GetNext(pos); pGroup->Release(); } m_lstGroup.RemoveAll(); } int SPropertyGrid::GetIndent() { return m_nIndent; } void SPropertyGrid::OnItemExpanded( IPropertyItem *pItem) { int iInsert = IndexOfPropertyItem(pItem); if(pItem->IsExpand()) { ExpandChildren(pItem,iInsert); }else { CollapseChildren(pItem,iInsert); } } int SPropertyGrid::IndexOfPropertyItem( const IPropertyItem *pItem ) const { for(int i=0;i<GetCount();i++) { if(pItem == (IPropertyItem *)GetItemData(i)) return i; } return -1; } CRect SPropertyGrid::GetItemRect( IPropertyItem *pItem ) const { int idx = IndexOfPropertyItem(pItem); SASSERT(idx != -1); int iTopIdx = GetTopIndex(); int nItemHei = m_itemHeight.toPixelSize(GetScale()); int nPageItems = (m_rcClient.Height()+nItemHei-1)/nItemHei+1; if(iTopIdx + nPageItems > GetCount()) nPageItems = GetCount() - iTopIdx; CRect rcItem; if(idx >= iTopIdx && idx <= iTopIdx+nPageItems) { rcItem = CRect(0,0,m_rcClient.Width(),nItemHei); rcItem.OffsetRect(0,nItemHei*idx-m_ptOrigin.y); rcItem.OffsetRect(m_rcClient.TopLeft()); } return rcItem; } void SPropertyGrid::SortInsert( IPropertyItem *pItem ) { int iInsert = -1; for(int i=0;i<GetCount();i++) { IPropertyItem *p = (IPropertyItem *)GetItemData(i); if(pItem->GetName()<p->GetName()) { iInsert = i; break; } } InsertString(iInsert,NULL,-1,(LPARAM)pItem); } BOOL SPropertyGrid::InsertGroup( SPropertyGroup * pGroup,SPropertyGroup* pInertAfter/*=IG_LAST*/ ) { SPOSITION pos = m_lstGroup.Find(pGroup); if(pos) return FALSE; if(pInertAfter == IG_FIRST) { m_lstGroup.InsertBefore(0,pGroup); }else if(pInertAfter == IG_LAST) { m_lstGroup.InsertAfter(0,pGroup); }else { pos = m_lstGroup.Find(pInertAfter); if(!pos) return FALSE; m_lstGroup.InsertAfter(pos,pGroup); } pGroup->AddRef(); switch(m_orderType) { case OT_NULL: { IPropertyItem *pChild=pGroup->GetItem(IPropertyItem::GPI_FIRSTCHILD); while(pChild) { InsertString(-1,NULL,-1,(LPARAM)pChild); pChild = pChild->GetItem(IPropertyItem::GPI_NEXTSIBLING); } //չs pChild=pGroup->GetItem(IPropertyItem::GPI_FIRSTCHILD); while(pChild) { if(pChild->ChildrenCount() && pChild->IsExpand()) { int iInsert = IndexOfPropertyItem(pChild); ExpandChildren(pChild,iInsert); } pChild = pChild->GetItem(IPropertyItem::GPI_NEXTSIBLING); } } break; case OT_GROUP: { int iInserted = InsertString(-1,NULL,-1,(LPARAM)pGroup); if(pGroup->IsExpand()) { ExpandChildren(pGroup,iInserted); } } break; case OT_NAME: { IPropertyItem *pChild=pGroup->GetItem(IPropertyItem::GPI_FIRSTCHILD); while(pChild) { SortInsert(pChild); pChild = pChild->GetItem(IPropertyItem::GPI_NEXTSIBLING); } //չs pChild=pGroup->GetItem(IPropertyItem::GPI_FIRSTCHILD); while(pChild) { if(pChild->ChildrenCount() && pChild->IsExpand()) { int iInsert = IndexOfPropertyItem(pChild); ExpandChildren(pChild,iInsert); } pChild = pChild->GetItem(IPropertyItem::GPI_NEXTSIBLING); } } break; } return TRUE; } int SPropertyGrid::ExpandChildren( const IPropertyItem *pItem,int iInsert ) { SASSERT(pItem->IsExpand()); SASSERT(iInsert != -1); int nRet =0; SList<IPropertyItem*> lstChilds; IPropertyItem *pChild = pItem->GetItem(IPropertyItem::GPI_FIRSTCHILD); while(pChild) { lstChilds.AddTail(pChild); pChild = pChild->GetItem(IPropertyItem::GPI_NEXTSIBLING); } if(m_orderType == OT_NAME) { SortItems(lstChilds); } SPOSITION pos = lstChilds.GetHeadPosition(); while(pos) { IPropertyItem *pChild = lstChilds.GetNext(pos); InsertString(++iInsert,NULL,-1,(LPARAM)pChild); nRet ++; if(pChild->ChildrenCount() && pChild->IsExpand()) { int nAdded = ExpandChildren(pChild,iInsert); nRet += nAdded; iInsert += nAdded; } } return nRet; } void SPropertyGrid::CollapseChildren( const IPropertyItem *pItem,int idx) { int nChilds = pItem->ChildrenCount(); for(int i=0;i<nChilds;i++) { IPropertyItem *pChild = (IPropertyItem *)GetItemData(idx+1); if(pChild->ChildrenCount() && pChild->IsExpand()) { CollapseChildren(pChild,idx+1); } DeleteString(idx+1); } } void SPropertyGrid::DrawItem( IRenderTarget *pRT, CRect &rc, int iItem ) { IPropertyItem *pItem = (IPropertyItem*)GetItemData(iItem); CRect rcSwitch = rc; CRect rcNameBack = rc; rcSwitch.right = rcSwitch.left +rcSwitch.Height(); rcNameBack.left = rcSwitch.right; rcNameBack.right = rcNameBack.left + m_nNameWidth; pRT->FillSolidRect(rcSwitch,m_crGroup); pRT->FillSolidRect(rcNameBack,iItem == SListBox::GetCurSel()? m_crItemSel:(pItem->IsGroup()?m_crGroup:m_crItem)); int iLevel = pItem->GetLevel(); if(iLevel>1) rcSwitch.OffsetRect(rcSwitch.Width()*(iLevel-1),0); if(pItem->ChildrenCount() && m_switchSkin) { int iState = pItem->IsExpand()?GROUP_EXPANDED:GROUP_COLLAPSED; if(!pItem->IsGroup()) iState += 2; CRect rcDraw = rcSwitch; rcDraw.DeflateRect((rcSwitch.Size()-m_switchSkin->GetSkinSize())/2); m_switchSkin->Draw(pRT,rcDraw,iState); } CRect rcName = rcNameBack; rcName.left = rcSwitch.right; SStringT strName = S_CW2T(pItem->GetName1()); pRT->DrawText(strName,strName.GetLength(),rcName,DT_SINGLELINE|DT_VCENTER); CRect rcItem = rc; rcItem.left= rcNameBack.right; if(pItem->HasButton()) rcItem.right -= rcItem.Height(); pItem->DrawItem(pRT,rcItem); //Item CAutoRefPtr<IPen> pen,oldPen; pRT->CreatePen(PS_SOLID,m_crBorder,1,&pen); pRT->SelectObject(pen,(IRenderObj**)&oldPen); CPoint pts[2]={CPoint(rc.left+rc.Height(),rc.bottom-1),CPoint(rc.right,rc.bottom-1)}; pRT->DrawLines(pts,2); CPoint pts2[2]={CPoint(rcNameBack.right,rcNameBack.top),rcNameBack.BottomRight()}; pRT->DrawLines(pts2,2); pRT->SelectObject(oldPen); } void SPropertyGrid::OnLButtonDbClick( UINT nFlags, CPoint point ) { SListBox::OnLButtonDbClick(nFlags,point); int iItem = SListBox::HitTest(point); if(iItem != -1) { IPropertyItem *pItem = (IPropertyItem*)GetItemData(iItem); if(pItem->ChildrenCount()) { pItem->Expand(!pItem->IsExpand()); }else if(!pItem->IsGroup() && !pItem->IsInplaceActive()) { pItem->OnInplaceActive(true); } } } BOOL SPropertyGrid::CreateChildren( pugi::xml_node xmlNode ) { pugi::xml_node xmlCmdBtn = xmlNode.child(L"cmdbtnstyle"); SASSERT(xmlCmdBtn); m_pCmdBtn = SApplication::getSingleton().CreateWindowByName(SWindow::GetClassName()); InsertChild(m_pCmdBtn); m_pCmdBtn->InitFromXml(xmlCmdBtn); m_pCmdBtn->SetVisible(FALSE); m_pCmdBtn->GetEventSet()->subscribeEvent(EventCmd::EventID,Subscriber(&SPropertyGrid::OnCmdBtnClicked,this)); pugi::xml_node xmlGroups = xmlNode.child(L"groups"); if(xmlGroups) { pugi::xml_node xmlChild = xmlGroups.child(SPropertyGroup::GetClassName()); while(xmlChild) { SPropertyGroup *pGroup = (SPropertyGroup *)SPropertyGroup::CreatePropItem(this); pGroup->InitFromXml(xmlChild); InsertGroup(pGroup); pGroup->Release(); xmlChild = xmlChild.next_sibling(SPropertyGroup::GetClassName()); } } return TRUE; } void SPropertyGrid::OnSize( UINT nType, CSize size ) { __super::OnSize(nType,size); UpdateChildrenPos(); } SPropertyGrid::ITEMPART SPropertyGrid::HitTest(int iItem,const CPoint &pt ) { if(iItem==-1) return IP_NULL; IPropertyItem *pItem = (IPropertyItem*)GetItemData(iItem); CRect rcItem=GetItemRect(pItem); int iLevel = pItem->GetLevel(); CRect rcSwitch = rcItem; rcSwitch.right = rcSwitch.left+ rcSwitch.Height(); if(iLevel>1) rcSwitch.OffsetRect(rcSwitch.Width()*(iLevel-1),0); if(pt.x<rcSwitch.left) return IP_NULL; if(pt.x<rcSwitch.right && pItem->ChildrenCount()) return IP_SWITCH; CRect rcName = rcItem; rcName.right = rcItem.left + m_nNameWidth + rcItem.Height(); if(pt.x<rcName.right) return IP_NAME; return IP_VALUE; } void SPropertyGrid::OnLButtonDown( UINT nFlags,CPoint pt ) { CRect rcClient; GetClientRect(&rcClient); int nItemHei = m_itemHeight.toPixelSize(GetScale()); if(pt.x-rcClient.left>=nItemHei+m_nNameWidth-1 && pt.x-rcClient.left<=nItemHei+m_nNameWidth+1) { SWindow::OnLButtonDown(nFlags,pt); m_ptDrag = pt; m_bDraging = TRUE; }else { SListBox::OnLButtonDown(nFlags,pt); int iItem = SListBox::HitTest(CPoint(pt)); if(iItem!=-1) { ITEMPART ip = HitTest(iItem,pt); if (ip == IP_SWITCH) { IPropertyItem *pItem = (IPropertyItem*)GetItemData(iItem); if (pItem->ChildrenCount()) { pItem->Expand(!pItem->IsExpand()); } }else if (ip == IP_VALUE) { IPropertyItem *pItem = (IPropertyItem*)GetItemData(iItem); EventPropGridItemActive evt(this); evt.pItem = pItem; FireEvent(evt); pItem->OnInplaceActive(true); }else if (ip == IP_NAME) { IPropertyItem *pItem = (IPropertyItem*)GetItemData(iItem); EventPropGridItemActive evt(this); evt.pItem = pItem; FireEvent(evt); } } } } void SPropertyGrid::SortItems( SList<IPropertyItem*> & lstItems ) { SList<IPropertyItem*> lstCpy; SPOSITION pos = lstItems.GetHeadPosition(); while(pos) { IPropertyItem *pItem = lstItems.GetNext(pos); SPOSITION pos2 = lstCpy.GetHeadPosition(); while(pos2) { IPropertyItem* pItem2=lstCpy.GetAt(pos2); if(pItem->GetName()<pItem2->GetName()) { lstCpy.InsertBefore(pos2,pItem); break; } lstCpy.GetNext(pos2); } if(!pos2) { lstCpy.InsertAfter(NULL,pItem); } } lstItems.RemoveAll(); pos = lstCpy.GetHeadPosition(); while(pos) { IPropertyItem *pItem = lstItems.GetNext(pos); lstItems.InsertAfter(NULL,pItem); } } BOOL SPropertyGrid::OnSetCursor( const CPoint &pt ) { CRect rcClient; GetClientRect(&rcClient); int nItemHei = m_itemHeight.toPixelSize(GetScale()); if(m_bDraging || (pt.x-rcClient.left>=nItemHei+m_nNameWidth-1 && pt.x-rcClient.left<=nItemHei+m_nNameWidth+1)) { SetCursor(SApplication::getSingleton().LoadCursor(MAKEINTRESOURCE(IDC_SIZEWE))); }else { int iItem = SListBox::HitTest(CPoint(pt)); if(iItem<0) return FALSE; ITEMPART ip = HitTest(iItem,pt); if(ip==IP_SWITCH) SetCursor(SApplication::getSingleton().LoadCursor(MAKEINTRESOURCE(IDC_HAND))); else return FALSE; } return TRUE; } void SPropertyGrid::OnLButtonUp( UINT nFlags,CPoint pt ) { if(m_bDraging) { m_bDraging = FALSE; SWindow::OnLButtonUp(nFlags,pt); }else { SListBox::OnLButtonUp(nFlags,pt); } } void SPropertyGrid::OnMouseMove( UINT nFlags,CPoint pt ) { SListBox::OnMouseMove(nFlags,pt); if(m_bDraging) { m_nNameWidth += pt.x-m_ptDrag.x; m_ptDrag = pt; Invalidate(); } } bool SPropertyGrid::OnSelChanged( EventArgs *pEvt ) { UpdateChildrenPos(CHILD_CMDBTN); return true; } bool SPropertyGrid::OnCmdBtnClicked( EventArgs *pEvt ) { int nCurSel = GetCurSel(); SASSERT(nCurSel!=-1); IPropertyItem *pItem =(IPropertyItem*)GetItemData(nCurSel); SASSERT(pItem->HasButton()); pItem->OnButtonClick(); return true; } BOOL SPropertyGrid::OnScroll( BOOL bVertical,UINT uCode,int nPos ) { BOOL bRet = SListBox::OnScroll(bVertical,uCode,nPos); UpdateChildrenPos(); return bRet; } void SPropertyGrid::OnInplaceActiveWndCreate( IPropertyItem *pItem,SWindow *pWnd ,pugi::xml_node xmlInit) { xmlInit.attribute(L"colorBkgnd").set_value(m_strEditBkgndColor); xmlInit.append_attribute(L"autoWordSel").set_value(m_strEnableAutoWordSel); SASSERT(m_pInplaceActiveWnd == NULL); InsertChild(pWnd); pWnd->InitFromXml(xmlInit); CRect rcItem = GetItemRect(pItem); CRect rcValue= rcItem; rcValue.left += rcItem.Height()+m_nNameWidth; if(pItem->HasButton()) rcValue.right -= rcValue.Height(); pItem->AdjustInplaceActiveWndRect(rcValue); pWnd->Move(rcValue); //pWnd->SetFocus();///////////////////////////// m_pInplaceActiveWnd = pWnd; } void SPropertyGrid::OnInplaceActiveWndDestroy( IPropertyItem *pItem,SWindow *pWnd ) { SASSERT(m_pInplaceActiveWnd == pWnd); RemoveChild(pWnd); m_pInplaceActiveWnd = NULL; } void SPropertyGrid::UpdateChildrenPos(UINT childs) { int nCurSel = GetCurSel(); if(nCurSel==-1) return; IPropertyItem * pItem = (IPropertyItem*)GetItemData(nCurSel); CRect rcItem = GetItemRect(pItem); rcItem.left += rcItem.Height()+m_nNameWidth; CRect rcValue = rcItem; if(pItem->HasButton()) { rcValue.right -= rcValue.Height(); } if(m_pInplaceActiveWnd && childs&CHILD_INPLACEWND) { pItem->AdjustInplaceActiveWndRect(rcValue); m_pInplaceActiveWnd->Move(rcValue); } if(childs & CHILD_CMDBTN) { m_pCmdBtn->SetVisible(FALSE); if(pItem->HasButton()) { CRect rcBtn = rcItem; rcBtn.left = rcBtn.right-rcBtn.Height(); m_pCmdBtn->Move(&rcBtn); m_pCmdBtn->SetVisible(TRUE,TRUE); } } } void SPropertyGrid::OnItemValueChanged( IPropertyItem *pItem ) { EventPropGridValueChanged evt(this); evt.pItem = pItem; FireEvent(evt); } } //add BOOL SPropertyGrid::AddGridItem(IPropertyItem* Item) { m_mapItem[Item->GetName2().MakeLower()] = Item; return TRUE; } BOOL SPropertyGrid::RemoveGridItem(IPropertyItem *Item) { m_mapItem.RemoveKey(Item->GetName2().MakeLower()); return TRUE; } BOOL SPropertyGrid::RemoveAllGridItem() { m_mapItem.RemoveAll(); return TRUE; } //SMap<SStringT, IPropertyItem*>* SPropertyGrid::GetItemMap() //{ // return &m_mapItem; //} void SPropertyGrid::ClearAllGridItemValue() { SPOSITION pos = m_mapItem.GetStartPosition(); IPropertyItem* pItem; while (pos) { SMap<SStringT, IPropertyItem*>::CPair *p = m_mapItem.GetNext(pos); pItem = p->m_value; pItem->SetStringOnly(_T("")); } } IPropertyItem * SPropertyGrid::GetGridItem(SStringT strName2) { SMap<SStringT, IPropertyItem*>::CPair *p = m_mapItem.Lookup(strName2.MakeLower()); if (p) { return p->m_value; } return NULL; } void SPropertyGrid::OnItemButtonClick(IPropertyItem *pItem, SStringT strType) { EventPropGridItemClick evt(this); evt.pItem = pItem; evt.strType = strType; FireEvent(evt); }
1
0.964101
1
0.964101
game-dev
MEDIA
0.768724
game-dev
0.990975
1
0.990975
plantuml/plantuml-core
1,432
plantuml-core/src/main/java/net/sourceforge/plantuml/command/CommandSkinParamMultilines.java
// THIS FILE HAS BEEN GENERATED BY A PREPROCESSOR. package net.sourceforge.plantuml.command; import net.sourceforge.plantuml.StringUtils; import net.sourceforge.plantuml.TitledDiagram; import net.sourceforge.plantuml.regex.Matcher2; import net.sourceforge.plantuml.regex.MyPattern; import net.sourceforge.plantuml.utils.BlocLines; public class CommandSkinParamMultilines extends CommandMultilinesBracket<TitledDiagram> { public static final CommandSkinParamMultilines ME = new CommandSkinParamMultilines(); private CommandSkinParamMultilines() { super("^skinparam[%s]*(?:[%s]+([\\w.]*(?:\\<\\<.*\\>\\>)?[\\w.]*))?[%s]*\\{$"); } @Override protected boolean isLineConsistent(String line, int level) { line = StringUtils.trin(line); if (hasStartingQuote(line)) return true; return SkinLoader.p1.matcher(line).matches(); } private boolean hasStartingQuote(CharSequence line) { // return MyPattern.mtches(line, "[%s]*[%q].*"); return MyPattern.mtches(line, CommandMultilinesComment.COMMENT_SINGLE_LINE); } public CommandExecutionResult execute(TitledDiagram diagram, BlocLines lines) { final SkinLoader skinLoader = new SkinLoader(diagram); final Matcher2 mStart = getStartingPattern().matcher(lines.getFirst().getTrimmed().getString()); if (mStart.find() == false) throw new IllegalStateException(); final String group1 = mStart.group(1); return skinLoader.execute(lines, group1); } }
1
0.884459
1
0.884459
game-dev
MEDIA
0.60829
game-dev
0.817751
1
0.817751
Samsung/GearVRf
2,081
GVRf/Framework/framework/src/main/jni/objects/components/sphere_collider.h
/* Copyright 2015 Samsung Electronics Co., LTD * * 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. */ /*************************************************************************** * Collider made from a sphere. ***************************************************************************/ #ifndef SPHERE_COLLIDER_H_ #define SPHERE_COLLIDER_H_ #include <memory> #include "collider.h" namespace gvr { class SphereCollider: public Collider { public: SphereCollider() : Collider(), center_(0, 0, 0), radius_(0) { } virtual ~SphereCollider() { } long shape_type() { return COLLIDER_SHAPE_SPHERE; } void set_radius(float r) { radius_ = r; } float get_radius() { return radius_; } ColliderData isHit(SceneObject* owner, const glm::vec3& rayStart, const glm::vec3& rayDir); ColliderData isHit(SceneObject* owner, const float sphere[]); static ColliderData isHit(Mesh& mesh, const glm::mat4& model_matrix, const glm::vec3& rayStart, const glm::vec3& rayDir); static ColliderData isHit(const glm::mat4& model_matrix, const glm::vec3& center, float radius, const glm::vec3& rayStart, const glm::vec3& rayDir); private: SphereCollider(const SphereCollider& mesh_collider) = delete; SphereCollider(SphereCollider&& mesh_collider) = delete; SphereCollider& operator=(const SphereCollider& mesh_collider) = delete; SphereCollider& operator=(SphereCollider&& mesh_collider) = delete; private: glm::vec3 center_; float radius_; }; } #endif
1
0.746857
1
0.746857
game-dev
MEDIA
0.727404
game-dev,graphics-rendering
0.775164
1
0.775164
smearle/gym-city
6,982
gym_city/envs/micropolis/micropolis-java/src/micropolisj/engine/CityEval.java
// This file is part of MicropolisJ. // Copyright (C) 2013 Jason Long // Portions Copyright (C) 1989-2007 Electronic Arts Inc. // // MicropolisJ is free software; you can redistribute it and/or modify // it under the terms of the GNU GPLv3, with additional terms. // See the README file, included in this distribution, for details. package micropolisj.engine; import java.util.*; /** * Contains the code for performing a city evaluation. */ public class CityEval { private final Micropolis engine; private final Random PRNG; public CityEval(Micropolis engine) { this.engine = engine; this.PRNG = engine.PRNG; assert PRNG != null; } /** Percentage of population "approving" the mayor. Derived from cityScore. */ public int cityYes; /** Percentage of population "disapproving" the mayor. Derived from cityScore. */ public int cityNo; /** City assessment value. */ public int cityAssValue; /** Player's score, 0-1000. */ public int cityScore; /** Change in cityScore since last evaluation. */ public int deltaCityScore; /** City population as of current evaluation. */ public int cityPop; /** Change in cityPopulation since last evaluation. */ public int deltaCityPop; /** Classification of city size. 0==village, 1==town, etc. */ public int cityClass; // 0..5 /** City's top 4 (or fewer) problems as reported by citizens. */ public CityProblem [] problemOrder = new CityProblem[0]; /** Number of votes given for the various problems identified by problemOrder[]. */ public EnumMap<CityProblem,Integer> problemVotes = new EnumMap<CityProblem,Integer>(CityProblem.class); /** Score for various problems. */ public EnumMap<CityProblem,Integer> problemTable = new EnumMap<CityProblem,Integer>(CityProblem.class); /** * Perform an evaluation. */ void cityEvaluation() { if (engine.totalPop != 0) { calculateAssValue(); doPopNum(); doProblems(); calculateScore(); doVotes(); } else { evalInit(); } engine.fireEvaluationChanged(); } /** Evaluate an empty city. */ void evalInit() { cityYes = 0; cityNo = 0; cityAssValue = 0; cityClass = 0; cityScore = 500; deltaCityScore = 0; problemVotes.clear(); problemOrder = new CityProblem[0]; } void calculateAssValue() { int z = 0; z += engine.roadTotal * 5; z += engine.railTotal * 10; z += engine.policeCount * 1000; z += engine.fireStationCount * 1000; z += engine.hospitalCount * 400; z += engine.stadiumCount * 3000; z += engine.seaportCount * 5000; z += engine.airportCount * 10000; z += engine.coalCount * 3000; z += engine.nuclearCount * 6000; cityAssValue = z * 1000; } void doPopNum() { int oldCityPop = cityPop; cityPop = engine.getCityPopulation(); deltaCityPop = cityPop - oldCityPop; cityClass = cityPop > 500000 ? 5 : //megalopolis cityPop > 100000 ? 4 : //metropolis cityPop > 50000 ? 3 : //capital cityPop > 10000 ? 2 : //city cityPop > 2000 ? 1 : //town 0; //village } void doProblems() { problemTable.clear(); problemTable.put(CityProblem.CRIME, engine.crimeAverage); problemTable.put(CityProblem.POLLUTION, engine.pollutionAverage); problemTable.put(CityProblem.HOUSING, (int)Math.round(engine.landValueAverage * 0.7)); problemTable.put(CityProblem.TAXES, engine.cityTax * 10); problemTable.put(CityProblem.TRAFFIC, averageTrf()); problemTable.put(CityProblem.UNEMPLOYMENT, getUnemployment()); problemTable.put(CityProblem.FIRE, getFire()); problemVotes = voteProblems(problemTable); CityProblem [] probOrder = CityProblem.values(); Arrays.sort(probOrder, new Comparator<CityProblem>() { public int compare(CityProblem a, CityProblem b) { return -(problemVotes.get(a).compareTo(problemVotes.get(b))); }}); int c = 0; while (c < probOrder.length && problemVotes.get(probOrder[c]).intValue() != 0 && c < 4) c++; problemOrder = new CityProblem[c]; for (int i = 0; i < c; i++) { problemOrder[i] = probOrder[i]; } } EnumMap<CityProblem,Integer> voteProblems(Map<CityProblem,Integer> probTab) { CityProblem [] pp = CityProblem.values(); int [] votes = new int[pp.length]; int countVotes = 0; for (int i = 0; i < 600; i++) { if (PRNG.nextInt(301) < probTab.get(pp[i%pp.length])) { votes[i%pp.length]++; countVotes++; if (countVotes >= 100) break; } } EnumMap<CityProblem,Integer> rv = new EnumMap<CityProblem,Integer>(CityProblem.class); for (int i = 0; i < pp.length; i++) { rv.put(pp[i], votes[i]); } return rv; } int averageTrf() { int count = 1; int total = 0; for (int y = 0; y < engine.getHeight(); y++) { for (int x = 0; x < engine.getWidth(); x++) { // only consider tiles that have nonzero landvalue if (engine.getLandValue(x, y) != 0) { total += engine.getTrafficDensity(x, y); count++; } } } engine.trafficAverage = (int)Math.round(((double)total / (double)count) * 2.4); return engine.trafficAverage; } int getUnemployment() { int b = (engine.comPop + engine.indPop) * 8; if (b == 0) return 0; double r = (double)engine.resPop / (double)b; b = (int)Math.floor((r-1.0)*255); if (b > 255) { b = 255; } return b; } int getFire() { int z = engine.firePop * 5; return Math.min(255, z); } static double clamp(double x, double min, double max) { return Math.max(min, Math.min(max, x)); } void calculateScore() { int oldCityScore = cityScore; int x = 0; for (Integer z : problemTable.values()) { x += z.intValue(); } x /= 3; x = Math.min(256, x); double z = clamp((256 - x) * 4, 0, 1000); if (engine.resCap) { z = 0.85 * z; } if (engine.comCap) { z = 0.85 * z; } if (engine.indCap) { z = 0.85 * z; } if (engine.roadEffect < 32) { z -= (32 - engine.roadEffect); } if (engine.policeEffect < 1000) { z *= (0.9 + (engine.policeEffect / 10000.1)); } if (engine.fireEffect < 1000) { z *= (0.9 + (engine.fireEffect / 10000.1)); } if (engine.resValve < -1000) { z *= 0.85; } if (engine.comValve < -1000) { z *= 0.85; } if (engine.indValve < -1000) { z *= 0.85; } double SM = 1.0; if (cityPop == 0 && deltaCityPop == 0) { SM = 1.0; } else if (deltaCityPop == cityPop) { SM = 1.0; } else if (deltaCityPop > 0) { SM = (double)deltaCityPop / (double)cityPop + 1.0; } else if (deltaCityPop < 0) { SM = 0.95 + ((double)deltaCityPop / (double)(cityPop-deltaCityPop)); } z *= SM; z -= getFire(); z -= engine.cityTax; int TM = engine.unpoweredZoneCount + engine.poweredZoneCount; SM = TM != 0 ? ((double)engine.poweredZoneCount / (double)TM) : 1.0; z *= SM; z = clamp(z, 0, 1000); cityScore = (int)Math.round((cityScore + z) / 2.0); deltaCityScore = cityScore - oldCityScore; } void doVotes() { cityYes = cityNo = 0; for (int i = 0; i < 100; i++) { if (PRNG.nextInt(1001) < cityScore) { cityYes++; } else { cityNo++; } } } }
1
0.591024
1
0.591024
game-dev
MEDIA
0.823571
game-dev
0.812061
1
0.812061
PacktPublishing/Mastering-Cpp-Game-Development
5,591
Chapter11/Include/bullet/BulletSoftBody/btSoftBodyConcaveCollisionAlgorithm.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_SOFT_BODY_CONCAVE_COLLISION_ALGORITHM_H #define BT_SOFT_BODY_CONCAVE_COLLISION_ALGORITHM_H #include "BulletCollision/BroadphaseCollision/btCollisionAlgorithm.h" #include "BulletCollision/BroadphaseCollision/btDispatcher.h" #include "BulletCollision/BroadphaseCollision/btBroadphaseInterface.h" #include "BulletCollision/CollisionShapes/btTriangleCallback.h" #include "BulletCollision/NarrowPhaseCollision/btPersistentManifold.h" class btDispatcher; #include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h" #include "BulletCollision/CollisionDispatch/btCollisionCreateFunc.h" class btSoftBody; class btCollisionShape; #include "LinearMath/btHashMap.h" #include "BulletCollision/BroadphaseCollision/btQuantizedBvh.h" //for definition of MAX_NUM_PARTS_IN_BITS struct btTriIndex { int m_PartIdTriangleIndex; class btCollisionShape* m_childShape; btTriIndex(int partId,int triangleIndex,btCollisionShape* shape) { m_PartIdTriangleIndex = (partId<<(31-MAX_NUM_PARTS_IN_BITS)) | triangleIndex; m_childShape = shape; } int getTriangleIndex() const { // Get only the lower bits where the triangle index is stored unsigned int x = 0; unsigned int y = (~(x&0))<<(31-MAX_NUM_PARTS_IN_BITS); return (m_PartIdTriangleIndex&~(y)); } int getPartId() const { // Get only the highest bits where the part index is stored return (m_PartIdTriangleIndex>>(31-MAX_NUM_PARTS_IN_BITS)); } int getUid() const { return m_PartIdTriangleIndex; } }; ///For each triangle in the concave mesh that overlaps with the AABB of a soft body (m_softBody), processTriangle is called. class btSoftBodyTriangleCallback : public btTriangleCallback { btSoftBody* m_softBody; const btCollisionObject* m_triBody; btVector3 m_aabbMin; btVector3 m_aabbMax ; btManifoldResult* m_resultOut; btDispatcher* m_dispatcher; const btDispatcherInfo* m_dispatchInfoPtr; btScalar m_collisionMarginTriangle; btHashMap<btHashKey<btTriIndex>,btTriIndex> m_shapeCache; public: int m_triangleCount; // btPersistentManifold* m_manifoldPtr; btSoftBodyTriangleCallback(btDispatcher* dispatcher,const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap,bool isSwapped); void setTimeStepAndCounters(btScalar collisionMarginTriangle,const btCollisionObjectWrapper* triObjWrap,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut); virtual ~btSoftBodyTriangleCallback(); virtual void processTriangle(btVector3* triangle, int partId, int triangleIndex); void clearCache(); SIMD_FORCE_INLINE const btVector3& getAabbMin() const { return m_aabbMin; } SIMD_FORCE_INLINE const btVector3& getAabbMax() const { return m_aabbMax; } }; /// btSoftBodyConcaveCollisionAlgorithm supports collision between soft body shapes and (concave) trianges meshes. class btSoftBodyConcaveCollisionAlgorithm : public btCollisionAlgorithm { bool m_isSwapped; btSoftBodyTriangleCallback m_btSoftBodyTriangleCallback; public: btSoftBodyConcaveCollisionAlgorithm( const btCollisionAlgorithmConstructionInfo& ci,const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap,bool isSwapped); virtual ~btSoftBodyConcaveCollisionAlgorithm(); virtual void processCollision (const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut); btScalar calculateTimeOfImpact(btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut); virtual void getAllContactManifolds(btManifoldArray& manifoldArray) { //we don't add any manifolds } void clearCache(); struct CreateFunc :public btCollisionAlgorithmCreateFunc { virtual btCollisionAlgorithm* CreateCollisionAlgorithm(btCollisionAlgorithmConstructionInfo& ci, const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap) { void* mem = ci.m_dispatcher1->allocateCollisionAlgorithm(sizeof(btSoftBodyConcaveCollisionAlgorithm)); return new(mem) btSoftBodyConcaveCollisionAlgorithm(ci,body0Wrap,body1Wrap,false); } }; struct SwappedCreateFunc :public btCollisionAlgorithmCreateFunc { virtual btCollisionAlgorithm* CreateCollisionAlgorithm(btCollisionAlgorithmConstructionInfo& ci, const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap) { void* mem = ci.m_dispatcher1->allocateCollisionAlgorithm(sizeof(btSoftBodyConcaveCollisionAlgorithm)); return new(mem) btSoftBodyConcaveCollisionAlgorithm(ci,body0Wrap,body1Wrap,true); } }; }; #endif //BT_SOFT_BODY_CONCAVE_COLLISION_ALGORITHM_H
1
0.913386
1
0.913386
game-dev
MEDIA
0.993985
game-dev
0.769071
1
0.769071
MrCheeze/botw-tools
7,049
event/Npc_HatenoGate003.c
-------- EventFlow: Npc_HatenoGate003 -------- Actor: Npc_HatenoGate003 entrypoint: None() actions: ['Demo_Talk', 'Demo_TalkASync'] queries: ['CheckActorAction13'] params: {'CreateMode': 0, 'IsGrounding': False, 'IsWorld': False, 'PosX': 0.0, 'PosY': 0.0, 'PosZ': 0.0, 'RotX': 0.0, 'RotY': 0.0, 'RotZ': 0.0} Actor: EventSystemActor entrypoint: None() actions: ['Demo_FlagON'] queries: ['CheckWeather', 'CheckFlag', 'GeneralChoice2', 'RandomChoice4'] params: {'CreateMode': 0, 'IsGrounding': False, 'IsWorld': False, 'PosX': 0.0, 'PosY': 0.0, 'PosZ': 0.0, 'RotX': 0.0, 'RotY': 0.0, 'RotZ': 0.0} Actor: GameROMPlayer entrypoint: None() actions: ['Demo_PlayASAdapt'] queries: [] params: {'Weapon': '', 'DisableWeapon': False, 'Shield': '', 'DisableShield': False, 'Bow': '', 'DisableBow': False, 'DisableSheikPad': False, 'ArmorHead': '', 'ArmorUpper': '', 'ArmorLower': '', 'CreateMode': 0, 'IsGrounding': False, 'IsWorld': False, 'PosX': 0.0, 'PosY': 0.0, 'PosZ': 0.0, 'RotX': 0.0, 'RotY': 0.0, 'RotZ': 0.0} void Talk() { call InitTalk.InitTalk({'Arg_Turn': 0, 'Arg_Greeting': 'FollowAISchedule'}) if EventSystemActor.CheckFlag({'FlagName': 'Npc_HatenoGate003_First'}) { if EventSystemActor.CheckFlag({'FlagName': 'Npc_HatenoGate003_second'}) { switch Npc_HatenoGate003.CheckActorAction13() { case [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13]: switch EventSystemActor.CheckWeather() { case [0, 2, 3]: switch EventSystemActor.RandomChoice4() { case 0: Npc_HatenoGate003.Demo_Talk({'MessageId': 'EventFlowMsg/Npc_HatenoGate003:Talk01', 'IsWaitFinish': True, 'IsCloseMessageDialog': False, 'ASName': '', 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False}) case 1: Npc_HatenoGate003.Demo_Talk({'IsWaitFinish': True, 'IsCloseMessageDialog': False, 'ASName': '', 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False, 'MessageId': 'EventFlowMsg/Npc_HatenoGate003:Talk04'}) case 2: Npc_HatenoGate003.Demo_Talk({'IsWaitFinish': True, 'IsCloseMessageDialog': False, 'ASName': '', 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False, 'MessageId': 'EventFlowMsg/Npc_HatenoGate003:Talk21'}) case 3: Npc_HatenoGate003.Demo_Talk({'IsWaitFinish': True, 'IsCloseMessageDialog': False, 'ASName': '', 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False, 'MessageId': 'EventFlowMsg/Npc_HatenoGate003:Talk22'}) } case 1: Npc_HatenoGate003.Demo_Talk({'IsWaitFinish': True, 'IsCloseMessageDialog': False, 'ASName': '', 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False, 'MessageId': 'EventFlowMsg/Npc_HatenoGate003:Talk08'}) } case 11: Event11: Npc_HatenoGate003.Demo_Talk({'IsWaitFinish': True, 'IsCloseMessageDialog': False, 'ASName': '', 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False, 'MessageId': 'EventFlowMsg/Npc_HatenoGate003:Talk06'}) } } else switch Npc_HatenoGate003.CheckActorAction13() { case [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13]: Npc_HatenoGate003.Demo_Talk({'IsWaitFinish': True, 'IsCloseMessageDialog': False, 'ASName': '', 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False, 'MessageId': 'EventFlowMsg/Npc_HatenoGate003:Talk18'}) if !EventSystemActor.GeneralChoice2() { Npc_HatenoGate003.Demo_Talk({'IsWaitFinish': True, 'IsCloseMessageDialog': False, 'ASName': '', 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False, 'MessageId': 'EventFlowMsg/Npc_HatenoGate003:Talk19'}) } else { Npc_HatenoGate003.Demo_Talk({'IsWaitFinish': True, 'IsCloseMessageDialog': False, 'ASName': '', 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False, 'MessageId': 'EventFlowMsg/Npc_HatenoGate003:Talk20'}) } EventSystemActor.Demo_FlagON({'FlagName': 'Npc_HatenoGate003_second', 'IsWaitFinish': True}) case 11: goto Event11 } } else switch Npc_HatenoGate003.CheckActorAction13() { case [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13]: Npc_HatenoGate003.Demo_Talk({'IsWaitFinish': True, 'ASName': '', 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False, 'MessageId': 'EventFlowMsg/Npc_HatenoGate003:Talk12', 'IsCloseMessageDialog': True}) if !EventSystemActor.GeneralChoice2() { GameROMPlayer.Demo_PlayASAdapt({'ASName': 'TalkYes', 'IsWaitFinish': True, 'IsOneTimeEndKeep': False, 'TargetIndex': -1, 'SeqBank': 0, 'IsIgnoreSame': False, 'IsEnabledAnimeDriven': -1, 'ClothWarpMode': -2, 'MorphingFrame': -1.0, 'NoErrorCheck': False}) Npc_HatenoGate003.Demo_Talk({'IsWaitFinish': True, 'IsCloseMessageDialog': False, 'ASName': '', 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False, 'MessageId': 'EventFlowMsg/Npc_HatenoGate003:Talk14'}) Event34: EventSystemActor.Demo_FlagON({'FlagName': 'Npc_HatenoGate003_First', 'IsWaitFinish': True}) } else { Npc_HatenoGate003.Demo_Talk({'IsWaitFinish': True, 'IsCloseMessageDialog': False, 'ASName': '', 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False, 'MessageId': 'EventFlowMsg/Npc_HatenoGate003:Talk15'}) goto Event34 } case 11: Npc_HatenoGate003.Demo_Talk({'IsWaitFinish': True, 'IsCloseMessageDialog': False, 'ASName': '', 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False, 'MessageId': 'EventFlowMsg/Npc_HatenoGate003:Talk13'}) if !EventSystemActor.GeneralChoice2() { Npc_HatenoGate003.Demo_Talk({'IsWaitFinish': True, 'IsCloseMessageDialog': False, 'ASName': '', 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False, 'MessageId': 'EventFlowMsg/Npc_HatenoGate003:Talk17'}) } else { Npc_HatenoGate003.Demo_Talk({'IsWaitFinish': True, 'IsCloseMessageDialog': False, 'ASName': '', 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False, 'MessageId': 'EventFlowMsg/Npc_HatenoGate003:Talk16'}) } goto Event34 } } void Near() { switch Npc_HatenoGate003.CheckActorAction13() { case 1: if !EventSystemActor.CheckWeather() { Npc_HatenoGate003.Demo_TalkASync({'IsWaitFinish': True, 'MessageId': 'EventFlowMsg/Npc_HatenoGate003:near00', 'DispFrame': 90, 'IsChecked': False}) } case 3: if !EventSystemActor.CheckWeather() { Npc_HatenoGate003.Demo_TalkASync({'IsWaitFinish': True, 'MessageId': 'EventFlowMsg/Npc_HatenoGate003:near01', 'DispFrame': 90, 'IsChecked': False}) } case 11: Npc_HatenoGate003.Demo_TalkASync({'IsWaitFinish': True, 'MessageId': 'EventFlowMsg/Npc_HatenoGate003:near02', 'DispFrame': 90, 'IsChecked': False}) } }
1
0.785513
1
0.785513
game-dev
MEDIA
0.903544
game-dev
0.666531
1
0.666531
CesiumGS/cesium-unreal
2,240
Source/CesiumRuntime/Public/CesiumWebMapServiceRasterOverlay.h
// Copyright 2020-2024 CesiumGS, Inc. and Contributors #pragma once #include "CesiumRasterOverlay.h" #include "Components/ActorComponent.h" #include "CoreMinimal.h" #include "CesiumWebMapServiceRasterOverlay.generated.h" /** * A raster overlay that directly accesses a Web Map Service (WMS) server. * https://www.ogc.org/standards/wms */ UCLASS(ClassGroup = Cesium, meta = (BlueprintSpawnableComponent)) class CESIUMRUNTIME_API UCesiumWebMapServiceRasterOverlay : public UCesiumRasterOverlay { GENERATED_BODY() public: /** * The base url of the Web Map Service (WMS). * e.g. * https://services.ga.gov.au/gis/services/NM_Culture_and_Infrastructure/MapServer/WMSServer */ UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Cesium") FString BaseUrl; /** * Comma-separated layer names to request from the server. */ UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Cesium") FString Layers; /** * Image width */ UPROPERTY( EditAnywhere, BlueprintReadWrite, Category = "Cesium", meta = (ClampMin = 64, ClampMax = 2048)) int32 TileWidth = 256; /** * Image height */ UPROPERTY( EditAnywhere, BlueprintReadWrite, Category = "Cesium", meta = (ClampMin = 64, ClampMax = 2048)) int32 TileHeight = 256; /** * Minimum zoom level. * * Take care when specifying this that the number of tiles at the minimum * level is small, such as four or less. A larger number is likely to * result in rendering problems. */ UPROPERTY( EditAnywhere, BlueprintReadWrite, Category = "Cesium", meta = (ClampMin = 0)) int32 MinimumLevel = 0; /** * Maximum zoom level. */ UPROPERTY( EditAnywhere, BlueprintReadWrite, Category = "Cesium", meta = (ClampMin = 0)) int32 MaximumLevel = 14; /** * HTTP headers to be attached to each request made for this raster overlay. */ UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Cesium") TMap<FString, FString> RequestHeaders; protected: virtual std::unique_ptr<CesiumRasterOverlays::RasterOverlay> CreateOverlay( const CesiumRasterOverlays::RasterOverlayOptions& options = {}) override; };
1
0.894442
1
0.894442
game-dev
MEDIA
0.242378
game-dev
0.741444
1
0.741444
GlowstoneMC/Glowstone
2,403
src/main/java/net/glowstone/generator/decorators/nether/GlowstoneDecorator.java
package net.glowstone.generator.decorators.nether; import net.glowstone.generator.decorators.BlockDecorator; import org.bukkit.Chunk; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.block.BlockState; import java.util.Random; public class GlowstoneDecorator extends BlockDecorator { private static final BlockFace[] SIDES = new BlockFace[]{BlockFace.EAST, BlockFace.WEST, BlockFace.DOWN, BlockFace.UP, BlockFace.SOUTH, BlockFace.NORTH}; private boolean variableAmount; public GlowstoneDecorator() { this(false); } public GlowstoneDecorator(boolean variableAmount) { this.variableAmount = variableAmount; } @Override public void decorate(World world, Random random, Chunk source) { int amount = variableAmount ? 1 + random.nextInt(1 + random.nextInt(10)) : 10; for (int i = 0; i < amount; i++) { int sourceX = (source.getX() << 4) + random.nextInt(16); int sourceZ = (source.getZ() << 4) + random.nextInt(16); int sourceY = 4 + random.nextInt(120); Block block = world.getBlockAt(sourceX, sourceY, sourceZ); if (!block.isEmpty() || block.getRelative(BlockFace.UP).getType() != Material.NETHERRACK) { continue; } BlockState state = block.getState(); state.setType(Material.GLOWSTONE); state.update(true); for (int j = 0; j < 1500; j++) { int x = sourceX + random.nextInt(8) - random.nextInt(8); int z = sourceZ + random.nextInt(8) - random.nextInt(8); int y = sourceY - random.nextInt(12); block = world.getBlockAt(x, y, z); if (!block.isEmpty()) { continue; } int glowstoneBlockCount = 0; for (BlockFace face : SIDES) { if (block.getRelative(face).getType() == Material.GLOWSTONE) { glowstoneBlockCount++; } } if (glowstoneBlockCount == 1) { state = block.getState(); state.setType(Material.GLOWSTONE); state.update(true); } } } } }
1
0.843602
1
0.843602
game-dev
MEDIA
0.972012
game-dev
0.920839
1
0.920839
kierkat10/Cryptposting
25,269
items/tag.lua
SMODS.Tag { key = "common_tag", name = "Common Tag", atlas = "crp_tag", pos = { x = 0, y = 0 }, config = { type = "store_joker_create" }, apply = function(self, tag, context) if context.type == "store_joker_create" then local rares_in_posession = { 0 } for k, v in ipairs(G.jokers.cards) do if v.config.center.rarity == 1 and not rares_in_posession[v.config.center.key] then rares_in_posession[1] = rares_in_posession[1] + 1 rares_in_posession[v.config.center.key] = true end end local card if #G.P_JOKER_RARITY_POOLS[1] > rares_in_posession[1] then card = create_card('Joker', context.area, nil, 0, nil, nil, nil, 'uta') create_shop_card_ui(card, "Joker", context.area) card.states.visible = false tag:yep("+", G.C.RARITY.Common, function() card:start_materialize() card.misprint_cost_fac = 0 card:set_cost() return true end) else tag:nope() end tag.triggered = true return card end end, crp_credits = { idea = { "Unknown" }, art = { "Glitchkat10" }, code = { "Glitchkat10" } } } SMODS.Tag { key = "legendary_tag", name = "Legendary Tag", atlas = "crp_tag", pos = { x = 1, y = 0 }, min_ante = 3, config = { type = "store_joker_create" }, apply = function(self, tag, context) if context.type == "store_joker_create" then local rares_in_posession = { 0 } for k, v in ipairs(G.jokers.cards) do if v.config.center.rarity == 4 and not rares_in_posession[v.config.center.key] then rares_in_posession[1] = rares_in_posession[1] + 1 rares_in_posession[v.config.center.key] = true end end local card if #G.P_JOKER_RARITY_POOLS[4] > rares_in_posession[1] then card = create_card("Joker", context.area, true, 4, nil, nil, nil, "uta") create_shop_card_ui(card, "Joker", context.area) card.states.visible = false tag:yep("+", G.C.RARITY.Legendary, function() card:start_materialize() card.misprint_cost_fac = 1 card:set_cost() return true end) else tag:nope() end tag.triggered = true return card end end, crp_credits = { idea = { "Unknown" }, art = { "Glitchkat10" }, code = { "Glitchkat10" } } } SMODS.Tag { key = "exotic_tag", name = "Exotic Tag", atlas = "crp_tag", pos = { x = 2, y = 0 }, min_ante = 4, config = { type = "store_joker_create" }, apply = function(self, tag, context) if context.type == "store_joker_create" then local rares_in_posession = { 0 } for k, v in ipairs(G.jokers.cards) do if v.config.center.rarity == "cry_exotic" and not rares_in_posession[v.config.center.key] then rares_in_posession[1] = rares_in_posession[1] + 1 rares_in_posession[v.config.center.key] = true end end local card if #G.P_JOKER_RARITY_POOLS.cry_exotic > rares_in_posession[1] then card = create_card("Joker", context.area, nil, "cry_exotic", nil, nil, nil, "cry_eta") create_shop_card_ui(card, "Joker", context.area) card.states.visible = false tag:yep("+", G.C.RARITY.cry_exotic, function() card:start_materialize() card.misprint_cost_fac = 2 card:set_cost() return true end) else tag:nope() end tag.triggered = true return card end end, crp_credits = { idea = { "Unknown" }, art = { "Glitchkat10" }, code = { "Glitchkat10" } } } SMODS.Tag { key = "mythic_tag", name = "Mythic Tag", atlas = "crp_tag", pos = { x = 7, y = 0 }, min_ante = 5, config = { type = "store_joker_create" }, apply = function(self, tag, context) if context.type == "store_joker_create" then local rares_in_posession = { 0 } for k, v in ipairs(G.jokers.cards) do if v.config.center.rarity == "crp_mythic" and not rares_in_posession[v.config.center.key] then rares_in_posession[1] = rares_in_posession[1] + 1 rares_in_posession[v.config.center.key] = true end end local card if #G.P_JOKER_RARITY_POOLS.crp_mythic > rares_in_posession[1] then card = create_card("Joker", context.area, nil, "crp_mythic", nil, nil, nil, "cry_eta") create_shop_card_ui(card, "Joker", context.area) card.states.visible = false tag:yep("+", HEX("ffb300"), function() card:start_materialize() card.misprint_cost_fac = 4 card:set_cost() return true end) else tag:nope() end tag.triggered = true return card end end, crp_credits = { idea = { "Unknown" }, art = { "Glitchkat10" }, code = { "Glitchkat10" } } } SMODS.Tag { key = "better_better_top-up_tag", name = "Better Better Top-Up Tag", atlas = "crp_tag", pos = { x = 0, y = 1 }, config = { extra = { amount = 2 } }, min_ante = 8, loc_vars = function(self, info_queue, tag) return { vars = { lenient_bignum(tag.config.extra.amount) } } end, apply = function(self, tag, context) if context.type == "immediate" then tag:yep("+", G.C.RED, function() for i = 1, lenient_bignum(tag.config.extra.amount) do if G.jokers and #G.jokers.cards < G.jokers.config.card_limit then local hittable = { set = "Joker", rarity = 1 } SMODS.add_card(hittable) end end return true end) tag.triggered = true return true end end, crp_credits = { idea = { "Grahkon" }, art = { "Grahkon" }, code = { "ScarredOut" } } } SMODS.Tag { key = "better_better_better_top-up_tag", name = "Better Better Better Top-Up Tag", atlas = "crp_tag", pos = { x = 1, y = 1 }, min_ante = 13, config = { extra = { amount = 2 } }, loc_vars = function(self, info_queue, tag) return { vars = { lenient_bignum(tag.config.extra.amount) } } end, apply = function(self, tag, context) if context.type == "immediate" then tag:yep("+", G.C.RED, function() for i = 1, lenient_bignum(tag.config.extra.amount) do if G.jokers and #G.jokers.cards < G.jokers.config.card_limit then local hittable = { set = "Joker", rarity = "cry_epic" } SMODS.add_card(hittable) end end return true end) tag.triggered = true return true end end, crp_credits = { idea = { "Grahkon" }, art = { "Grahkon" }, code = { "ScarredOut" } } } SMODS.Tag { key = "better_better_better_better_top-up_tag", name = "Better Better Better Better Top-Up Tag", atlas = "crp_tag", pos = { x = 2, y = 1 }, min_ante = 27, config = { extra = { amount = 1 } }, loc_vars = function(self, info_queue, tag) return { vars = { lenient_bignum(tag.config.extra.amount) } } end, apply = function(self, tag, context) if context.type == "immediate" then tag:yep("+", G.C.RED, function() for i = 1, lenient_bignum(tag.config.extra.amount) do if G.jokers and #G.jokers.cards < G.jokers.config.card_limit then local hittable = { set = "Joker", legendary = true } SMODS.add_card(hittable) end end return true end) tag.triggered = true return true end end, crp_credits = { idea = { "Grahkon" }, art = { "Grahkon" }, code = { "ScarredOut" } } } SMODS.Tag { key = "better_better_better_better_better_top-up_tag", name = "Better Better Better Better Better Top-Up Tag", atlas = "crp_tag", pos = { x = 3, y = 1 }, min_ante = 39, config = { extra = { amount = 1 } }, loc_vars = function(self, info_queue, tag) return { vars = { lenient_bignum(tag.config.extra.amount) } } end, apply = function(self, tag, context) if context.type == "immediate" then tag:yep("+", G.C.RED, function() for i = 1, lenient_bignum(tag.config.extra.amount) do if G.jokers and #G.jokers.cards < G.jokers.config.card_limit then local hittable = { set = "Joker", rarity = "cry_exotic" } SMODS.add_card(hittable) end end return true end) tag.triggered = true return true end end, crp_credits = { idea = { "Grahkon" }, art = { "Grahkon" }, code = { "ScarredOut" } } } SMODS.Tag { key = "better_better_better_better_better_better_top-up_tag", name = "Better Better Better Better Better Better Top-Up Tag", atlas = "crp_tag", pos = { x = 5, y = 1 }, min_ante = 69, config = { extra = { amount = 1 } }, loc_vars = function(self, info_queue, tag) return { vars = { lenient_bignum(tag.config.extra.amount) } } end, apply = function(self, tag, context) if context.type == "immediate" then tag:yep("+", G.C.RED, function() for i = 1, lenient_bignum(tag.config.extra.amount) do if G.jokers and #G.jokers.cards < G.jokers.config.card_limit then local hittable = { set = "Joker", rarity = "crp_mythic" } SMODS.add_card(hittable) end end return true end) tag.triggered = true return true end end, crp_credits = { idea = { "Grahkon" }, art = { "Grahkon" }, code = { "ScarredOut" } } } SMODS.Tag { key = "better_better_better_better_better_better_better_top-up_tag", name = "Better Better Better Better Better Better Better Top-Up Tag", atlas = "crp_tag", pos = { x = 2, y = 2 }, min_ante = 98, config = { extra = { amount = 1 } }, loc_vars = function(self, info_queue, tag) return { vars = { lenient_bignum(tag.config.extra.amount) } } end, apply = function(self, tag, context) if context.type == "immediate" then tag:yep("+", G.C.RED, function() for i = 1, lenient_bignum(tag.config.extra.amount) do if G.jokers and #G.jokers.cards < G.jokers.config.card_limit then local hittable = { set = "Joker", rarity = "crp_exomythic" } SMODS.add_card(hittable) end end return true end) tag.triggered = true return true end end, crp_credits = { idea = { "Grahkon" }, art = { "Grahkon" }, code = { "ScarredOut" } } } SMODS.Tag { key = "better_better_better_better_better_better_better_better_top-up_tag", name = "Better Better Better Better Better Better Better Better Top-Up Tag", atlas = "crp_tag", pos = { x = 4, y = 2 }, min_ante = 270, config = { extra = { amount = 1 } }, loc_vars = function(self, info_queue, tag) return { vars = { lenient_bignum(tag.config.extra.amount) } } end, apply = function(self, tag, context) if context.type == "immediate" then tag:yep("+", G.C.RED, function() for i = 1, lenient_bignum(tag.config.extra.amount) do if G.jokers and #G.jokers.cards < G.jokers.config.card_limit then local hittable = { set = "Joker", rarity = "crp_2exomythic4me" } SMODS.add_card(hittable) end end return true end) tag.triggered = true return true end end, crp_credits = { idea = { "Grahkon" }, art = { "Grahkon" }, code = { "ScarredOut" } }, } SMODS.Tag { key = "better_better_better_better_better_better_better_better_better_top-up_tag", name = "Better Better Better Better Better Better Better Better Better Top-Up Tag", atlas = "crp_tag", pos = { x = 0, y = 2 }, min_ante = 420, config = { extra = { amount = 1 } }, loc_vars = function(self, info_queue, tag) return { vars = { lenient_bignum(tag.config.extra.amount) } } end, apply = function(self, tag, context) if context.type == "immediate" then tag:yep("+", G.C.RED, function() for i = 1, lenient_bignum(tag.config.extra.amount) do if G.jokers and #G.jokers.cards < G.jokers.config.card_limit then local hittable = { set = "Joker", rarity = "crp_22exomythic4mecipe" } SMODS.add_card(hittable) end end return true end) tag.triggered = true return true end end, crp_credits = { idea = { "Grahkon" }, art = { "Grahkon" }, code = { "ScarredOut" } }, } SMODS.Tag { key = ":3_top-up_tag", name = ":3 Top-Up Tag", atlas = "crp_tag", pos = { x = 0, y = 3 }, min_ante = 0, config = { extra = { amount = 2 } }, loc_vars = function(self, info_queue, tag) return { vars = { lenient_bignum(tag.config.extra.amount) } } end, apply = function(self, tag, context) if context.type == "immediate" then tag:yep("+", G.C.RED, function() for i = 1, lenient_bignum(tag.config.extra.amount) do if G.jokers and #G.jokers.cards < G.jokers.config.card_limit then local hittable = { set = "Joker", rarity = "crp_:3" } SMODS.add_card(hittable) end end return true end) tag.triggered = true return true end end, crp_credits = { idea = { "Grahkon" }, art = { "Grahkon" }, code = { "Glitchkat10" } } } SMODS.Tag { key = "candy_top-up_tag", name = "Candy Top-up Tag", atlas = "crp_tag", pos = { x = 4, y = 1 }, min_ante = 8, config = { extra = { amount = 2 } }, loc_vars = function(self, info_queue, tag) return { vars = { lenient_bignum(tag.config.extra.amount) } } end, apply = function(self, tag, context) if context.type == "immediate" then tag:yep("+", G.C.RED, function() for i = 1, lenient_bignum(tag.config.extra.amount) do if G.jokers and #G.jokers.cards < G.jokers.config.card_limit then local hittable = { set = "Joker", rarity = "cry_candy" } SMODS.add_card(hittable) end end return true end) tag.triggered = true return true end end, crp_credits = { idea = { "Grahkon" }, art = { "Grahkon" }, code = { "ScarredOut" } } } SMODS.Tag { key = "top-down_tag", name = "Top-down Tag", atlas = "crp_tag", pos = { x = 7, y = 2 }, min_ante = -1, config = { extra = { amount = 2 } }, loc_vars = function(self, info_queue, tag) return { vars = { lenient_bignum(tag.config.extra.amount) } } end, apply = function(self, tag, context) if context.type == "immediate" then tag:yep("+", G.C.RED, function() for i = 1, lenient_bignum(tag.config.extra.amount) do if G.jokers and #G.jokers.cards < G.jokers.config.card_limit then local hittable = { set = "Joker", rarity = "cry_cursed" } SMODS.add_card(hittable) end end return true end) tag.triggered = true return true end end, crp_credits = { idea = { "Glitchkat10" }, art = { "aqrlr", "Glitchkat10" }, code = { "Glitchkat10" } } } SMODS.Tag { key = "worse_top-up_tag", atlas = "crp_tag", pos = { x = 5, y = 2 }, config = { extra = { amount = 2 } }, loc_vars = function(self, info_queue, tag) return { vars = { lenient_bignum(tag.config.extra.amount) } } end, apply = function(self, tag, context) if context.type == "immediate" then tag:yep("+", G.C.RED, function() for i = 1, lenient_bignum(tag.config.extra.amount) do if G.jokers and #G.jokers.cards < G.jokers.config.card_limit then local hittable = { set = "Joker", rarity = "crp_abysmal" } SMODS.add_card(hittable) end end return true end) tag.triggered = true return true end end, crp_credits = { idea = { "Grahkon" }, art = { "Grahkon" }, code = { "ScarredOut" } }, } SMODS.Tag { key = "trash_top-up_tag", name = "Trash Top-Up Tag", atlas = "crp_tag", pos = { x = 1, y = 3 }, min_ante = 0, config = { extra = { amount = 2 } }, loc_vars = function(self, info_queue, tag) return { vars = { lenient_bignum(tag.config.extra.amount) } } end, apply = function(self, tag, context) if context.type == "immediate" then tag:yep("+", G.C.RED, function() for i = 1, lenient_bignum(tag.config.extra.amount) do if G.jokers and #G.jokers.cards < G.jokers.config.card_limit then local hittable = { set = "Joker", rarity = "crp_trash" } SMODS.add_card(hittable) end end return true end) tag.triggered = true return true end end, crp_credits = { idea = { "Glitchkat10" }, art = { "Glitchkat10" }, code = { "Glitchkat10" } } } SMODS.Tag { key = "overloaded_tag", name = "Overloaded Tag", atlas = "crp_tag", pos = { x = 2, y = 3 }, config = { type = "store_joker_modify", edition = "crp_overloaded" }, min_ante = 8, loc_vars = function(self, info_queue) info_queue[#info_queue + 1] = G.P_CENTERS.e_crp_overloaded return { vars = {} } end, apply = function(self, tag, context) if context.type == "store_joker_modify" then local _applied = nil if Cryptid.forced_edition() then tag:nope() end if not context.card.edition and not context.card.temp_edition and context.card.ability.set == "Joker" then local lock = tag.ID G.CONTROLLER.locks[lock] = true context.card.temp_edition = true tag:yep("+", G.C.DARK_EDITION, function() context.card:set_edition({ crp_overloaded = true }, true) context.card.ability.couponed = true context.card:set_cost() context.card.temp_edition = nil G.CONTROLLER.locks[lock] = nil return true end) _applied = true tag.triggered = true end end end, crp_credits = { idea = { "Glitchkat10" }, art = { "Glitchkat10" }, code = { "Glitchkat10" } } } SMODS.Tag { key = "four-dimensional_tag", name = "Four-Dimensional Tag", atlas = "crp_tag", pos = { x = 3, y = 3 }, config = { type = "store_joker_modify", edition = "crp_four-dimensional" }, min_ante = 6, loc_vars = function(self, info_queue) info_queue[#info_queue + 1] = G.P_CENTERS["e_crp_four-dimensional"] return { vars = { } } end, apply = function(self, tag, context) if context.type == "store_joker_modify" then local _applied = nil if Cryptid.forced_edition() then tag:nope() end if not context.card.edition and not context.card.temp_edition and context.card.ability.set == "Joker" then local lock = tag.ID G.CONTROLLER.locks[lock] = true context.card.temp_edition = true tag:yep("+", G.C.DARK_EDITION, function() context.card:set_edition({ ["crp_four-dimensional"] = true }, true) context.card.ability.couponed = true context.card:set_cost() context.card.temp_edition = nil G.CONTROLLER.locks[lock] = nil return true end) _applied = true tag.triggered = true end end end, crp_credits = { idea = { "Glitchkat10" }, art = { "Glitchkat10" }, code = { "Glitchkat10" } } } SMODS.Tag { key = "top-up_everything", name = "Top-up Everything", atlas = "crp_tag", pos = { x = 5, y = 3 }, min_ante = 2798, config = { }, loc_vars = function(self, info_queue, tag) info_queue[#info_queue + 1] = G.P_CENTERS.j_crp_all return { vars = { } } end, apply = function(self, tag, context) if context.type == "immediate" then tag:yep("+", G.C.RED, function() if G.jokers and #G.jokers.cards < G.jokers.config.card_limit then local hittable = { set = "Joker", rarity = "crp_all" } SMODS.add_card(hittable) end return true end) tag.triggered = true return true end end, crp_credits = { idea = { "aqrlr" }, art = { "Grahkon", "aqrlr" }, code = { "Glitchkat10" } }, } --[[ SMODS.Tag { key = "unplentiful_tag", atlas = "crp_tag", pos = { x = 3, y = 0 }, min_ante = 0, config = { type = "store_joker_create" }, apply = function(self, tag, context) if context.type == "store_joker_create" then local rares_in_posession = { 0 } for k, v in ipairs(G.jokers.cards) do if v.config.center.rarity == "crp_unplentiful" and not rares_in_posession[v.config.center.key] then rares_in_posession[1] = rares_in_posession[1] + 1 rares_in_posession[v.config.center.key] = true end end local card if #G.P_JOKER_RARITY_POOLS.crp_unplentiful > rares_in_posession[1] then card = create_card("Joker", context.area, nil, "crp_unplentiful", nil, nil, nil, "cry_eta") create_shop_card_ui(card, "Joker", context.area) card.states.visible = false tag:yep("+", G.C.RARITY.Uncommon, function() card:start_materialize() card.misprint_cost_fac = 0 card:set_cost() return true end) else tag:nope() end tag.triggered = true return card end end, crp_credits = { idea = { "Unknown" }, art = { "lord.ruby" }, code = { "lord.ruby" } } } SMODS.Tag { key = "well-done_tag", atlas = "crp_tag", pos = { x = 4, y = 0 }, min_ante = 0, config = { type = "store_joker_create" }, apply = function(self, tag, context) if context.type == "store_joker_create" then local rares_in_posession = { 0 } for k, v in ipairs(G.jokers.cards) do if v.config.center.rarity == "crp_well-done" and not rares_in_posession[v.config.center.key] then rares_in_posession[1] = rares_in_posession[1] + 1 rares_in_posession[v.config.center.key] = true end end local card if #G.P_JOKER_RARITY_POOLS.crp_well-done > rares_in_posession[1] then card = create_card("Joker", context.area, nil, "crp_well-done", nil, nil, nil, "cry_eta") create_shop_card_ui(card, "Joker", context.area) card.states.visible = false tag:yep("+", G.C.RARITY.Rare, function() card:start_materialize() card.misprint_cost_fac = 0 card:set_cost() return true end) else tag:nope() end tag.triggered = true return card end end, crp_credits = { idea = { "Unknown" }, art = { "lord.ruby"}, code = { "lord.ruby" } } } --[[ SMODS.Tag { key = "awesome_tag", atlas = "crp_tag", pos = { x = 5, y = 0 }, min_ante = 0, config = { type = "store_joker_create" }, apply = function(self, tag, context) if context.type == "store_joker_create" then local rares_in_posession = { 0 } for k, v in ipairs(G.jokers.cards) do if v.config.center.rarity == "crp_awesome" and not rares_in_posession[v.config.center.key] then rares_in_posession[1] = rares_in_posession[1] + 1 rares_in_posession[v.config.center.key] = true end end local card if #G.P_JOKER_RARITY_POOLS.crp_awesome > rares_in_posession[1] then card = create_card("Joker", context.area, nil, "crp_awesome", nil, nil, nil, "cry_eta") create_shop_card_ui(card, "Joker", context.area) card.states.visible = false tag:yep("+", G.C.RARITY.crp_awesome, function() card:start_materialize() card.misprint_cost_fac = 0.5 card:set_cost() return true end) else tag:nope() end tag.triggered = true return card end end, } SMODS.Tag { key = "m_tag", atlas = "crp_tag", pos = { x = 6, y = 0 }, min_ante = 0, config = { type = "store_joker_create" }, apply = function(self, tag, context) if context.type == "store_joker_create" then local rares_in_posession = { 0 } for k, v in ipairs(G.jokers.cards) do if v.config.center.rarity == "crp_m" and not rares_in_posession[v.config.center.key] then rares_in_posession[1] = rares_in_posession[1] + 1 rares_in_posession[v.config.center.key] = true end end local card if #G.P_JOKER_RARITY_POOLS.crp_m > rares_in_posession[1] then card = create_card("Joker", context.area, nil, "crp_m", nil, nil, nil, "cry_eta") create_shop_card_ui(card, "Joker", context.area) card.states.visible = false tag:yep("+", G.C.RARITY.cry_exotic, function() card:start_materialize() card.misprint_cost_fac = 0 card:set_cost() return true end) else tag:nope() end tag.triggered = true return card end end, ]]-- --[[ SMODS.Tag { key = "besttopuptag", atlas = "crp_tag", pos = { x = 7, y = 1 }, config = { extra = { amount = 2 } }, loc_txt = { name = "Best Top-up Tag", text = { "Create up to #1#", "{C:crp_exomythicepicawesomeuncommon2mexotic22exomythic4mecipe}ExoMythicEpicAwesomeUncommon2MExotic22ExoMythic4meCipe{} {C:attention}Jokers{}", "{C:inactive}(Must have room){}" } }, loc_vars = function(self, info_queue, tag) return { vars = { lenient_bignum(tag.config.extra.amount) } } end, crp_credits = { idea = { "Grahkon" }, art = { "Grahkon" }, code = { "ScarredOut" } }, apply = function(self, tag, context) if context.type == "immediate" then tag:yep("+", G.C.RED, function() for i = 1, lenient_bignum(tag.config.extra.amount) do if G.jokers and #G.jokers.cards < G.jokers.config.card_limit then local hittable = { set = "Joker", rarity = "crp_exomythicepicawesomeuncommon2mexotic22exomythic4mecipe" } SMODS.add_card(hittable) end end return true end) tag.triggered = true return true end end } ]]-- op tag commentation ends here
1
0.949577
1
0.949577
game-dev
MEDIA
0.848578
game-dev
0.972079
1
0.972079
MoSync/MoSync
60,392
examples/cpp/wolf3d/wl_menu.c
//////////////////////////////////////////////////////////////////// // // WL_MENU.C // by John Romero (C) 1992 Id Software, Inc. // //////////////////////////////////////////////////////////////////// #include "wl_def.h" // // PRIVATE PROTOTYPES // enum {MOUSE,JOYSTICK,KEYBOARDBTNS,KEYBOARDMOVE}; // FOR INPUT TYPES void CP_ReadThis(); #ifdef UPLOAD #define STARTITEM readthis #else #define STARTITEM newgame #endif #define HAVE_FFBLK static const char endStrings[9][80]= { ENDSTR1, ENDSTR2, ENDSTR3, ENDSTR4, ENDSTR5, ENDSTR6, ENDSTR7, ENDSTR8, ENDSTR9 }; CP_iteminfo #ifdef UPLOAD MainItems={MENU_X,MENU_Y,10,STARTITEM,24}, #else MainItems={MENU_X,MENU_Y, 9,STARTITEM,24}, #endif SndItems={SM_X,SM_Y1,12,0,52}, LSItems={LSM_X,LSM_Y,10,0,24}, CtlItems={CTL_X,CTL_Y,6,-1,56}, CusItems={8,CST_Y+13*2,9,-1,0}, NewEitems={NE_X,NE_Y,11,0,88}, NewItems={NM_X,NM_Y,4,2,24}; CP_itemtype MainMenu[]= { {1,STR_NG,(MenuFunc)CP_NewGame}, {1,STR_SD,(MenuFunc)CP_Sound}, {1,STR_CL,(MenuFunc)CP_Control}, {1,STR_LG,(MenuFunc)CP_LoadGame}, {0,STR_SG,(MenuFunc)CP_SaveGame}, {1,STR_CV,(MenuFunc)CP_ChangeView}, #ifdef UPLOAD {2,"Read This!",(MenuFunc)CP_ReadThis}, #endif {1,STR_VS,(MenuFunc)CP_ViewScores}, {1,STR_BD,0}, {1,STR_QT,0} }, SndMenu[]= { {1,STR_NONE,0}, {1,STR_PC,0}, {1,STR_ALSB,0}, {0,"",0}, {0,"",0}, {1,STR_NONE,0}, {1,STR_DISNEY,0}, {1,STR_SB,0}, {0,"",0}, {0,"",0}, {1,STR_NONE,0}, {1,STR_ALSB,0} }, CtlMenu[]= { {0,STR_MOUSEEN,0}, {0,STR_JOYEN,0}, {0,STR_PORT2,0}, {0,STR_GAMEPAD,0}, {0,STR_SENS,(MenuFunc)MouseSensitivity}, {1,STR_CUSTOM,(MenuFunc)CustomControls} }, #ifndef SPEAR NewEmenu[]= { {1,"Episode 1\n" "Escape from Wolfenstein",0}, {0,"",0}, {3,"Episode 2\n" "Operation: Eisenfaust",0}, {0,"",0}, {3,"Episode 3\n" "Die, Fuhrer, Die!",0}, {0,"",0}, {3,"Episode 4\n" "A Dark Secret",0}, {0,"",0}, {3,"Episode 5\n" "Trail of the Madman",0}, {0,"",0}, {3,"Episode 6\n" "Confrontation",0} }, #endif NewMenu[]= { {1,STR_DADDY,0}, {1,STR_HURTME,0}, {1,STR_BRINGEM,0}, {1,STR_DEATH,0} }, LSMenu[]= { {1,"",0}, {1,"",0}, {1,"",0}, {1,"",0}, {1,"",0}, {1,"",0}, {1,"",0}, {1,"",0}, {1,"",0}, {1,"",0} }, CusMenu[]= { {1,"",0}, {0,"",0}, {0,"",0}, {1,"",0}, {0,"",0}, {0,"",0}, {1,"",0}, {0,"",0}, {1,"",0} }; static const int color_hlite[] = { DEACTIVE, HIGHLIGHT, READHCOLOR, 0x67 }; static const int color_norml[] = { DEACTIVE, TEXTCOLOR, READCOLOR, 0x6b }; #ifndef SPEAR static int EpisodeSelect[6] = { 1 }; #endif static int SaveGamesAvail[10],StartGame,SoundStatus=1,pickquick; static char SaveGameNames[10][32],SaveName[13]="savegam?."; //////////////////////////////////////////////////////////////////// // // INPUT MANAGER SCANCODE TABLES and // // IN_GetScanName() - Returns a string containing the name of the // specified scan code // //////////////////////////////////////////////////////////////////// static const char *ScanNames[] = // Scan code names with single chars { "?","?","1","2","3","4","5","6","7","8","9","0","-","+","?","?", "Q","W","E","R","T","Y","U","I","O","P","[","]","|","?","A","S", "D","F","G","H","J","K","L",";","\"","?","?","?","Z","X","C","V", "B","N","M",",",".","/","?","?","?","?","?","?","?","?","?","?", "?","?","?","?","?","?","?","?","\xf","?","-","\x15","5","\x11","+","?", "\x13","?","?","?","?","?","?","?","?","?","?","?","?","?","?","?", "?","?","?","?","?","?","?","?","?","?","?","?","?","?","?","?", "?","?","?","?","?","?","?","?","?","?","?","?","?","?","?","?" }, // DEBUG - consolidate these *ExtScanNames[] = // Names corresponding to ExtScanCodes { "Esc","BkSp","Tab","Ctrl","LShft","Space","CapsLk","F1","F2","F3","F4", "F5","F6","F7","F8","F9","F10","F11","F12","ScrlLk","Enter","RShft", "PrtSc","Alt","Home","PgUp","End","PgDn","Ins","Del","NumLk","Up", "Down","Left","Right","" }; static const ScanCode ExtScanCodes[] = // Scan codes with >1 char names { 1,0xe,0xf,0x1d,sc_LShift,0x39,0x3a,0x3b,0x3c,0x3d,0x3e, 0x3f,0x40,0x41,0x42,0x43,0x44,0x57,0x59,0x46,0x1c,sc_RShift, 0x37,0x38,sc_Home,sc_PgUp,sc_End,sc_PgDn,sc_Insert,sc_Delete,0x45,sc_UpArrow, sc_DownArrow,sc_LeftArrow,sc_RightArrow,0x00 }; const char *IN_GetScanName(ScanCode scan) { const char **p; const ScanCode *s; for (s = ExtScanCodes, p = ExtScanNames; *s; p++, s++) if (*s == scan) return *p; return ScanNames[scan]; } //////////////////////////////////////////////////////////////////// // // Wolfenstein Control Panel! Ta Da! // //////////////////////////////////////////////////////////////////// void US_ControlPanel(byte scancode) { int which; if (ingame) if (CP_CheckQuick(scancode)) return; StartCPMusic(MENUSONG); SetupControlPanel(); // // F-KEYS FROM WITHIN GAME // switch(scancode) { case sc_F1: #ifdef UPLOAD HelpScreens(); #else BossKey(); #endif goto finishup; case sc_F2: CP_SaveGame(0); goto finishup; case sc_F3: CP_LoadGame(0); goto finishup; case sc_F4: CP_Sound(); goto finishup; case sc_F5: CP_ChangeView(); goto finishup; case sc_F6: CP_Control(); goto finishup; finishup: CleanupControlPanel(); #ifdef SPEAR UnCacheLump (OPTIONS_LUMP_START,OPTIONS_LUMP_END); #endif return; } #ifdef SPEAR CacheLump (OPTIONS_LUMP_START,OPTIONS_LUMP_END); #endif DrawMainMenu(); MenuFadeIn(); StartGame=0; // // MAIN MENU LOOP // do { which=HandleMenu(&MainItems,&MainMenu[0],NULL); #if defined(SPEAR) && !defined(SPEARDEMO) // // EASTER EGG FOR SPEAR OF DESTINY! // if (IN_KeyDown(sc_I) && IN_KeyDown(sc_D)) { VW_FadeOut(); StartCPMusic (XJAZNAZI_MUS); UnCacheLump(OPTIONS_LUMP_START,OPTIONS_LUMP_END); UnCacheLump(BACKDROP_LUMP_START,BACKDROP_LUMP_END); MM_SortMem(); ClearMemory(); CA_CacheGrChunk (IDGUYS1PIC); VWB_DrawPic(0,0,IDGUYS1PIC); CA_UnCacheGrChunk(IDGUYS1PIC); CA_CacheGrChunk (IDGUYS2PIC); VWB_DrawPic(0,80,IDGUYS2PIC); CA_UnCacheGrChunk(IDGUYS2PIC); VW_UpdateScreen(); CA_CacheGrChunk(IDGUYSPALETTE); VL_FadeIn(0, 255, grsegs[IDGUYSPALETTE], 30); CA_UnCacheGrChunk(IDGUYSPALETTE); while (IN_KeyDown(sc_I) || IN_KeyDown(sc_D)) IN_CheckAck(); IN_ClearKeysDown(); IN_Ack(); VW_FadeOut(); CacheLump(BACKDROP_LUMP_START,BACKDROP_LUMP_END); CacheLump(OPTIONS_LUMP_START,OPTIONS_LUMP_END); DrawMainMenu(); StartCPMusic (MENUSONG); MenuFadeIn(); } #endif switch(which) { case viewscores: if (MainMenu[viewscores].routine == NULL) if (CP_EndGame()) StartGame=1; DrawMainMenu(); MenuFadeIn(); break; case backtodemo: MM_SortMem(); StartGame=1; if (!ingame) StartCPMusic(INTROSONG); VL_FadeOut(0,255,0,0,0,10); break; case -1: case quit: CP_Quit(); break; default: if (!StartGame) { DrawMainMenu(); MenuFadeIn(); } } // // "EXIT OPTIONS" OR "NEW GAME" EXITS // } while(!StartGame); // // DEALLOCATE EVERYTHING // CleanupControlPanel(); // // CHANGE MAINMENU ITEM // if (startgame || loadedgame) { MainMenu[viewscores].routine = NULL; strcpy(MainMenu[viewscores].string,STR_EG); } // RETURN/START GAME EXECUTION #ifdef SPEAR UnCacheLump(OPTIONS_LUMP_START, OPTIONS_LUMP_END); MM_SortMem(); #endif } //////////////////////// // // DRAW MAIN MENU SCREEN // void DrawMainMenu() { ClearMScreen(); VWB_DrawPic(112,184,C_MOUSELBACKPIC); DrawStripes(10); VWB_DrawPic(84,0,C_OPTIONSPIC); DrawWindow(MENU_X-8,MENU_Y-3,MENU_W,MENU_H,BKGDCOLOR); // // CHANGE "GAME" AND "DEMO" // if (ingame) { strcpy(&MainMenu[backtodemo].string[8],STR_GAME); MainMenu[backtodemo].active=2; } else { strcpy(&MainMenu[backtodemo].string[8],STR_DEMO); MainMenu[backtodemo].active=1; } DrawMenu(&MainItems,&MainMenu[0]); VW_UpdateScreen(); } #ifdef UPLOAD //////////////////////////////////////////////////////////////////// // // READ THIS! // //////////////////////////////////////////////////////////////////// void CP_ReadThis() { StartCPMusic(CORNER_MUS); HelpScreens(); StartCPMusic(MENUSONG); } #else //////////////////////////////////////////////////////////////////// // // BOSS KEY // //////////////////////////////////////////////////////////////////// void BossKey() { } #endif //////////////////////////////////////////////////////////////////// // // CHECK QUICK-KEYS & QUIT (WHILE IN A GAME) // //////////////////////////////////////////////////////////////////// int CP_CheckQuick(unsigned scancode) { switch(scancode) { // // END GAME // case sc_F7: CA_CacheGrChunk(STARTFONT+1); WindowH=160; if (Confirm(ENDGAMESTR)) { playstate = ex_died; pickquick = gamestate.lives = 0; } DrawPlayBorder(); WindowH=200; fontnumber=0; MainMenu[savegame].active = 0; return 1; // // QUICKSAVE // case sc_F8: if (SaveGamesAvail[LSItems.curpos] && pickquick) { CA_CacheGrChunk(STARTFONT+1); fontnumber = 1; Message(STR_SAVING"..."); CP_SaveGame(1); fontnumber=0; } else { #ifndef SPEAR CA_CacheGrChunk(STARTFONT+1); CA_CacheGrChunk(C_CURSOR1PIC); CA_CacheGrChunk(C_CURSOR2PIC); CA_CacheGrChunk(C_DISKLOADING1PIC); CA_CacheGrChunk(C_DISKLOADING2PIC); CA_CacheGrChunk(C_SAVEGAMEPIC); CA_CacheGrChunk(C_MOUSELBACKPIC); #else CacheLump(BACKDROP_LUMP_START,BACKDROP_LUMP_END); CA_CacheGrChunk(C_CURSOR1PIC); #endif VW_FadeOut(); StartCPMusic(MENUSONG); pickquick=CP_SaveGame(0); SETFONTCOLOR(0,15); IN_ClearKeysDown(); DrawPlayScreen (); if (!startgame && !loadedgame) { VW_FadeIn (); StartMusic (); } if (loadedgame) playstate = ex_abort; lasttimecount = get_TimeCount(); IN_GetMouseDelta(NULL, NULL); // Clear accumulated mouse movement #ifndef SPEAR CA_UnCacheGrChunk(C_CURSOR1PIC); CA_UnCacheGrChunk(C_CURSOR2PIC); CA_UnCacheGrChunk(C_DISKLOADING1PIC); CA_UnCacheGrChunk(C_DISKLOADING2PIC); CA_UnCacheGrChunk(C_SAVEGAMEPIC); CA_UnCacheGrChunk(C_MOUSELBACKPIC); #else UnCacheLump (BACKDROP_LUMP_START,BACKDROP_LUMP_END); #endif } return 1; /* QUICKLOAD */ case sc_F9: if (SaveGamesAvail[LSItems.curpos] && pickquick) { char string[100]=STR_LGC; CA_CacheGrChunk(STARTFONT+1); fontnumber = 1; strcat(string,SaveGameNames[LSItems.curpos]); strcat(string,"\"?"); if (Confirm(string)) CP_LoadGame(1); DrawPlayBorder(); fontnumber=0; } else { #ifndef SPEAR CA_CacheGrChunk(STARTFONT+1); CA_CacheGrChunk(C_CURSOR1PIC); CA_CacheGrChunk(C_CURSOR2PIC); CA_CacheGrChunk(C_DISKLOADING1PIC); CA_CacheGrChunk(C_DISKLOADING2PIC); CA_CacheGrChunk(C_LOADGAMEPIC); CA_CacheGrChunk(C_MOUSELBACKPIC); #else CA_CacheGrChunk(C_CURSOR1PIC); CacheLump (BACKDROP_LUMP_START,BACKDROP_LUMP_END); #endif VW_FadeOut (); StartCPMusic(MENUSONG); pickquick=CP_LoadGame(0); SETFONTCOLOR(0,15); IN_ClearKeysDown(); DrawPlayScreen (); if (!startgame && !loadedgame) { VW_FadeIn (); StartMusic (); } if (loadedgame) playstate = ex_abort; lasttimecount = get_TimeCount(); IN_GetMouseDelta(NULL, NULL); // Clear accumulated mouse movement #ifndef SPEAR CA_UnCacheGrChunk(C_CURSOR1PIC); CA_UnCacheGrChunk(C_CURSOR2PIC); CA_UnCacheGrChunk(C_DISKLOADING1PIC); CA_UnCacheGrChunk(C_DISKLOADING2PIC); CA_UnCacheGrChunk(C_LOADGAMEPIC); CA_UnCacheGrChunk(C_MOUSELBACKPIC); #else UnCacheLump (BACKDROP_LUMP_START,BACKDROP_LUMP_END); #endif } return 1; // // QUIT // case sc_F10: CA_CacheGrChunk(STARTFONT+1); WindowX=WindowY=0; WindowW=320; WindowH=160; if (Confirm(endStrings[(US_RndT()&0x7)+(US_RndT()&1)])) { VW_UpdateScreen(); SD_MusicOff(); SD_StopSound(); MenuFadeOut(); Quit(NULL); } DrawPlayBorder(); WindowH=200; fontnumber=0; return 1; } return 0; } //////////////////////////////////////////////////////////////////// // // END THE CURRENT GAME // //////////////////////////////////////////////////////////////////// int CP_EndGame() { if (!Confirm(ENDGAMESTR)) return 0; pickquick = gamestate.lives = 0; playstate = ex_died; MainMenu[savegame].active = 0; MainMenu[viewscores].routine = (MenuFunc)CP_ViewScores; strcpy(MainMenu[viewscores].string,STR_VS); return 1; } //////////////////////////////////////////////////////////////////// // // VIEW THE HIGH SCORES // //////////////////////////////////////////////////////////////////// void CP_ViewScores() { fontnumber=0; #ifdef SPEAR UnCacheLump(OPTIONS_LUMP_START,OPTIONS_LUMP_END); StartCPMusic(XAWARD_MUS); #else StartCPMusic(ROSTER_MUS); #endif DrawHighScores(); VW_UpdateScreen(); MenuFadeIn(); fontnumber=1; IN_Ack(); StartCPMusic(MENUSONG); MenuFadeOut(); #ifdef SPEAR CacheLump (BACKDROP_LUMP_START,BACKDROP_LUMP_END); CacheLump (OPTIONS_LUMP_START,OPTIONS_LUMP_END); #endif } //////////////////////////////////////////////////////////////////// // // START A NEW GAME // //////////////////////////////////////////////////////////////////// void CP_NewGame() { int which,episode; #ifdef SPEAR UnCacheLump (OPTIONS_LUMP_START,OPTIONS_LUMP_END); #endif episode = 0; #ifndef SPEAR firstpart: DrawNewEpisode(); do { which=HandleMenu(&NewEitems,&NewEmenu[0],NULL); switch(which) { case -1: MenuFadeOut(); return; default: if (!EpisodeSelect[which/2]) { SD_PlaySound (NOWAYSND); Message("Please select \"Read This!\"\n" "from the Options menu to\n" "find out how to order this\n" "episode from Apogee."); IN_ClearKeysDown(); IN_Ack(); DrawNewEpisode(); which = 0; } else { episode = which/2; which = 1; } break; } } while (!which); ShootSnd(); // // ALREADY IN A GAME? // if (ingame) if (!Confirm(CURGAME)) { MenuFadeOut(); return; } MenuFadeOut(); #else // // ALREADY IN A GAME? // CacheLump (NEWGAME_LUMP_START,NEWGAME_LUMP_END); DrawNewGame(); if (ingame) if (!Confirm(CURGAME)) { MenuFadeOut(); UnCacheLump (NEWGAME_LUMP_START,NEWGAME_LUMP_END); CacheLump (OPTIONS_LUMP_START,OPTIONS_LUMP_END); return; } #endif DrawNewGame(); which=HandleMenu(&NewItems,&NewMenu[0],DrawNewGameDiff); if (which<0) { MenuFadeOut(); #ifndef SPEAR goto firstpart; #else UnCacheLump (NEWGAME_LUMP_START,NEWGAME_LUMP_END); CacheLump (OPTIONS_LUMP_START,OPTIONS_LUMP_END); return; #endif } ShootSnd(); NewGame(which,episode); StartGame=1; MenuFadeOut(); // // CHANGE "READ THIS!" TO NORMAL COLOR // #ifdef UPLOAD MainMenu[readthis].active=1; #endif pickquick = 0; #ifdef SPEAR UnCacheLump (NEWGAME_LUMP_START,NEWGAME_LUMP_END); CacheLump (OPTIONS_LUMP_START,OPTIONS_LUMP_END); #endif } #ifndef SPEAR ///////////////////// // // DRAW NEW EPISODE MENU // void DrawNewEpisode(void) { int i; ClearMScreen(); VWB_DrawPic(112,184,C_MOUSELBACKPIC); DrawWindow(NE_X-4,NE_Y-4,NE_W+8,NE_H+8,BKGDCOLOR); SETFONTCOLOR(READHCOLOR,BKGDCOLOR); PrintY=2; WindowX=0; US_CPrint("Which episode to play?"); SETFONTCOLOR(TEXTCOLOR,BKGDCOLOR); DrawMenu(&NewEitems,&NewEmenu[0]); for (i=0;i<6;i++) VWB_DrawPic(NE_X+32,NE_Y+i*26,C_EPISODE1PIC+i); VW_UpdateScreen(); MenuFadeIn(); WaitKeyUp(); } #endif ///////////////////// // // DRAW NEW GAME MENU // void DrawNewGame(void) { ClearMScreen(); VWB_DrawPic(112,184,C_MOUSELBACKPIC); SETFONTCOLOR(READHCOLOR,BKGDCOLOR); PrintX=NM_X+20; PrintY=NM_Y-32; #ifndef SPEAR US_Print("How tough are you?"); #else VWB_DrawPic (PrintX,PrintY,C_HOWTOUGHPIC); #endif DrawWindow(NM_X-5,NM_Y-10,NM_W,NM_H,BKGDCOLOR); DrawMenu(&NewItems,&NewMenu[0]); DrawNewGameDiff(NewItems.curpos); VW_UpdateScreen(); MenuFadeIn(); WaitKeyUp(); } //////////////////////// // // DRAW NEW GAME GRAPHIC // void DrawNewGameDiff(int w) { VWB_DrawPic(NM_X+185,NM_Y+7,w+C_BABYMODEPIC); } //////////////////////////////////////////////////////////////////// // // HANDLE SOUND MENU // //////////////////////////////////////////////////////////////////// void CP_Sound() { int which; #ifdef SPEAR UnCacheLump (OPTIONS_LUMP_START,OPTIONS_LUMP_END); CacheLump (SOUND_LUMP_START,SOUND_LUMP_END); #endif DrawSoundMenu(); MenuFadeIn(); WaitKeyUp(); do { which=HandleMenu(&SndItems,&SndMenu[0],NULL); // // HANDLE MENU CHOICES // switch(which) { // // SOUND EFFECTS // case 0: if (SoundMode!=sdm_Off) { SD_WaitSoundDone(); SD_SetSoundMode(sdm_Off); DrawSoundMenu(); } break; case 1: if (SoundMode!=sdm_PC) { SD_WaitSoundDone(); SD_SetSoundMode(sdm_PC); CA_LoadAllSounds(); DrawSoundMenu(); ShootSnd(); } break; case 2: if (SoundMode!=sdm_AdLib) { SD_WaitSoundDone(); SD_SetSoundMode(sdm_AdLib); CA_LoadAllSounds(); DrawSoundMenu(); ShootSnd(); } break; // // DIGITIZED SOUND // case 5: if (DigiMode!=sds_Off) { SD_SetDigiDevice(sds_Off); DrawSoundMenu(); } break; case 6: break; case 7: if (DigiMode!=sds_SoundBlaster) { SD_SetDigiDevice(sds_SoundBlaster); DrawSoundMenu(); ShootSnd(); } break; // // MUSIC // case 10: if (MusicMode!=smm_Off) { SD_SetMusicMode(smm_Off); DrawSoundMenu(); ShootSnd(); } break; case 11: if (MusicMode!=smm_AdLib) { SD_SetMusicMode(smm_AdLib); DrawSoundMenu(); ShootSnd(); StartCPMusic(MENUSONG); } break; } } while(which>=0); MenuFadeOut(); #ifdef SPEAR UnCacheLump (SOUND_LUMP_START,SOUND_LUMP_END); CacheLump (OPTIONS_LUMP_START,OPTIONS_LUMP_END); #endif } ////////////////////// // // DRAW THE SOUND MENU // void DrawSoundMenu(void) { int i,on; // // DRAW SOUND MENU // ClearMScreen(); VWB_DrawPic(112,184,C_MOUSELBACKPIC); DrawWindow(SM_X-8,SM_Y1-3,SM_W,SM_H1,BKGDCOLOR); DrawWindow(SM_X-8,SM_Y2-3,SM_W,SM_H2,BKGDCOLOR); DrawWindow(SM_X-8,SM_Y3-3,SM_W,SM_H3,BKGDCOLOR); // // IF NO ADLIB, NON-CHOOSENESS! // if (!AdLibPresent && !SoundBlasterPresent) { SndMenu[2].active=SndMenu[10].active=SndMenu[11].active=0; } SndMenu[6].active = 0; if (!SoundBlasterPresent) SndMenu[7].active=0; if (!SoundBlasterPresent) SndMenu[5].active=0; DrawMenu(&SndItems,&SndMenu[0]); VWB_DrawPic(100,SM_Y1-20,C_FXTITLEPIC); VWB_DrawPic(100,SM_Y2-20,C_DIGITITLEPIC); VWB_DrawPic(100,SM_Y3-20,C_MUSICTITLEPIC); for (i=0;i<SndItems.amount;i++) if (SndMenu[i].string[0]) { // // DRAW SELECTED/NOT SELECTED GRAPHIC BUTTONS // on=0; switch(i) { // // SOUND EFFECTS // case 0: if (SoundMode==sdm_Off) on=1; break; case 1: if (SoundMode==sdm_PC) on=1; break; case 2: if (SoundMode==sdm_AdLib) on=1; break; // // DIGITIZED SOUND // case 5: if (DigiMode==sds_Off) on=1; break; case 6: break; case 7: if (DigiMode==sds_SoundBlaster) on=1; break; // // MUSIC // case 10: if (MusicMode==smm_Off) on=1; break; case 11: if (MusicMode==smm_AdLib) on=1; break; } if (on) VWB_DrawPic(SM_X+24,SM_Y1+i*13+2,C_SELECTEDPIC); else VWB_DrawPic(SM_X+24,SM_Y1+i*13+2,C_NOTSELECTEDPIC); } DrawMenuGun(&SndItems); VW_UpdateScreen(); } // // DRAW LOAD/SAVE IN PROGRESS // void DrawLSAction(int which) { #define LSA_X 96 #define LSA_Y 80 #define LSA_W 130 #define LSA_H 42 DrawWindow(LSA_X,LSA_Y,LSA_W,LSA_H,TEXTCOLOR); DrawOutline(LSA_X,LSA_Y,LSA_W,LSA_H,0,HIGHLIGHT); VWB_DrawPic(LSA_X+8,LSA_Y+5,C_DISKLOADING1PIC); fontnumber=1; SETFONTCOLOR(0,TEXTCOLOR); PrintX=LSA_X+46; PrintY=LSA_Y+13; if (!which) US_Print(STR_LOADING"..."); else US_Print(STR_SAVING"..."); VW_UpdateScreen(); } //////////////////////////////////////////////////////////////////// // // LOAD SAVED GAMES // //////////////////////////////////////////////////////////////////// int CP_LoadGame(int quick) { int which, exit=0; char name[13]; strcpy(name, SaveName); // // QUICKLOAD? // if (quick) { which=LSItems.curpos; if (SaveGamesAvail[which]) { name[7]=which+'0'; loadedgame=true; LoadTheGame(name, 0, 0); loadedgame=false; DrawStatusBar(); return 1; } } #ifdef SPEAR UnCacheLump (OPTIONS_LUMP_START,OPTIONS_LUMP_END); CacheLump (LOADSAVE_LUMP_START,LOADSAVE_LUMP_END); #endif DrawLoadSaveScreen(0); do { which=HandleMenu(&LSItems,&LSMenu[0],TrackWhichGame); if (which>=0 && SaveGamesAvail[which]) { ShootSnd(); name[7]=which+'0'; DrawLSAction(0); loadedgame=true; LoadTheGame(name, LSA_X+8, LSA_Y+5); StartGame=1; ShootSnd(); // // CHANGE "READ THIS!" TO NORMAL COLOR // #ifdef UPLOAD MainMenu[readthis].active=1; #endif exit=1; break; } } while(which>=0); MenuFadeOut(); #ifdef SPEAR UnCacheLump (LOADSAVE_LUMP_START,LOADSAVE_LUMP_END); CacheLump (OPTIONS_LUMP_START,OPTIONS_LUMP_END); #endif return exit; } /////////////////////////////////// // // HIGHLIGHT CURRENT SELECTED ENTRY // void TrackWhichGame(int w) { static int lastgameon=0; PrintLSEntry(lastgameon,TEXTCOLOR); PrintLSEntry(w,HIGHLIGHT); lastgameon=w; } //////////////////////////// // // DRAW THE LOAD/SAVE SCREEN // void DrawLoadSaveScreen(int loadsave) { #define DISKX 100 #define DISKY 0 int i; ClearMScreen(); fontnumber=1; VWB_DrawPic(112,184,C_MOUSELBACKPIC); DrawWindow(LSM_X-10,LSM_Y-5,LSM_W,LSM_H,BKGDCOLOR); DrawStripes(10); if (!loadsave) VWB_DrawPic(60,0,C_LOADGAMEPIC); else VWB_DrawPic(60,0,C_SAVEGAMEPIC); for (i=0;i<10;i++) PrintLSEntry(i,TEXTCOLOR); DrawMenu(&LSItems,&LSMenu[0]); VW_UpdateScreen(); MenuFadeIn(); WaitKeyUp(); } /////////////////////////////////////////// // // PRINT LOAD/SAVE GAME ENTRY W/BOX OUTLINE // void PrintLSEntry(int w,int color) { SETFONTCOLOR(color,BKGDCOLOR); DrawOutline(LSM_X+LSItems.indent,LSM_Y+w*13,LSM_W-LSItems.indent-15,11,color,color); PrintX=LSM_X+LSItems.indent+2; PrintY=LSM_Y+w*13+1; fontnumber=0; if (SaveGamesAvail[w]) US_Print(SaveGameNames[w]); else US_Print(" - "STR_EMPTY" -"); fontnumber=1; } //////////////////////////////////////////////////////////////////// // // SAVE CURRENT GAME // //////////////////////////////////////////////////////////////////// int CP_SaveGame(int quick) { int which, exit=0; char name[13], input[32]; strcpy(name,SaveName); // // QUICKSAVE? // if (quick) { which=LSItems.curpos; if (SaveGamesAvail[which]) { name[7] = which+'0'; SaveTheGame(name, &SaveGameNames[which][0], 0, 0); return 1; } } #ifdef SPEAR UnCacheLump (OPTIONS_LUMP_START,OPTIONS_LUMP_END); CacheLump (LOADSAVE_LUMP_START,LOADSAVE_LUMP_END); #endif DrawLoadSaveScreen(1); do { which=HandleMenu(&LSItems,&LSMenu[0],TrackWhichGame); if (which>=0) { // // OVERWRITE EXISTING SAVEGAME? // if (SaveGamesAvail[which]) { if (!Confirm(GAMESVD)) { DrawLoadSaveScreen(1); continue; } else { DrawLoadSaveScreen(1); PrintLSEntry(which,HIGHLIGHT); VW_UpdateScreen(); } } ShootSnd(); strcpy(input,&SaveGameNames[which][0]); name[7]=which+'0'; fontnumber=0; if (!SaveGamesAvail[which]) VW_Bar(LSM_X+LSItems.indent+1,LSM_Y+which*13+1,LSM_W-LSItems.indent-16,10,BKGDCOLOR); VW_UpdateScreen(); if (US_LineInput(LSM_X+LSItems.indent+2,LSM_Y+which*13+1,input,input,true,31,LSM_W-LSItems.indent-30)) { SaveGamesAvail[which] = 1; DrawLSAction(1); strcpy(&SaveGameNames[which][0],input); SaveTheGame(name, input, LSA_X+8, LSA_Y+5); ShootSnd(); exit=1; } else { VW_Bar(LSM_X+LSItems.indent+1,LSM_Y+which*13+1,LSM_W-LSItems.indent-16,10,BKGDCOLOR); PrintLSEntry(which,HIGHLIGHT); VW_UpdateScreen(); SD_PlaySound(ESCPRESSEDSND); continue; } fontnumber=1; break; } } while(which>=0); MenuFadeOut(); #ifdef SPEAR UnCacheLump (LOADSAVE_LUMP_START,LOADSAVE_LUMP_END); CacheLump (OPTIONS_LUMP_START,OPTIONS_LUMP_END); #endif return exit; } //////////////////////////////////////////////////////////////////// // // CALIBRATE JOYSTICK // //////////////////////////////////////////////////////////////////// int CalibrateJoystick() { #define CALX 85 #define CALY 40 #define CALW 158 #define CALH 140 word xmin,ymin,xmax,ymax,jb; DrawWindow(CALX-5,CALY-5,CALW,CALH,TEXTCOLOR); DrawOutline(CALX-5,CALY-5,CALW,CALH,0,HIGHLIGHT); SETFONTCOLOR(0,TEXTCOLOR); WindowX = PrintX = CALX; WindowW = CALW; WindowH = CALH; WindowY = PrintY = CALY; US_Print(" "STR_CALIB"\n "STR_JOYST"\n"); VWB_DrawPic(CALX+40,CALY+30,C_JOY1PIC); PrintY = CALY+80; US_Print(STR_MOVEJOY); SETFONTCOLOR(BKGDCOLOR,TEXTCOLOR); US_Print(" "STR_ESCEXIT); VW_UpdateScreen(); do { jb=IN_JoyButtons(); IN_CheckAck(); /* force update */ if (IN_KeyDown(sc_Escape)) return 0; if (IN_KeyDown(sc_Tab) && IN_KeyDown(sc_P) && MS_CheckParm("debugmode")) PicturePause(); } while(!(jb&1)); SD_PlaySound(SHOOTSND); IN_GetJoyAbs(joystickport, &xmin, &ymin); DrawWindow(CALX-5,CALY-5,CALW,CALH,TEXTCOLOR); DrawOutline(CALX-5,CALY-5,CALW,CALH,0,HIGHLIGHT); SETFONTCOLOR(0,TEXTCOLOR); PrintX = CALX; PrintY = CALY; US_Print(" "STR_CALIB"\n "STR_JOYST"\n"); VWB_DrawPic(CALX+40,CALY+30,C_JOY2PIC); PrintY = CALY+80; US_Print(STR_MOVEJOY2); SETFONTCOLOR(BKGDCOLOR,TEXTCOLOR); US_Print(" "STR_ESCEXIT); VW_UpdateScreen(); do { jb = IN_JoyButtons(); IN_CheckAck(); /* force update */ if (IN_KeyDown(sc_Escape)) return 0; if (IN_KeyDown(sc_Tab) && IN_KeyDown(sc_P) && MS_CheckParm("debugmode")) PicturePause(); } while(!(jb&2)); IN_GetJoyAbs(joystickport,&xmax,&ymax); SD_PlaySound(SHOOTSND); while (IN_JoyButtons()); // // ASSIGN ACTUAL VALUES HERE // if ((xmin != xmax) && (ymin != ymax)) IN_SetupJoy(joystickport,xmin,xmax,ymin,ymax); else return 0; return 1; } //////////////////////////////////////////////////////////////////// // // DEFINE CONTROLS // //////////////////////////////////////////////////////////////////// void CP_Control() { enum {MOUSEENABLE,JOYENABLE,USEPORT2,PADENABLE,MOUSESENS,CUSTOMIZE}; int which; #ifdef SPEAR UnCacheLump (OPTIONS_LUMP_START,OPTIONS_LUMP_END); CacheLump (CONTROL_LUMP_START,CONTROL_LUMP_END); #endif DrawCtlScreen(); MenuFadeIn(); WaitKeyUp(); do { which=HandleMenu(&CtlItems,&CtlMenu[0],NULL); switch(which) { case MOUSEENABLE: mouseenabled^=1; DrawCtlScreen(); CusItems.curpos=-1; ShootSnd(); break; case JOYENABLE: joystickenabled^=1; DrawCtlScreen(); CusItems.curpos=-1; ShootSnd(); break; case USEPORT2: joystickport^=1; DrawCtlScreen(); ShootSnd(); break; case PADENABLE: joypadenabled^=1; DrawCtlScreen(); ShootSnd(); break; case MOUSESENS: case CUSTOMIZE: DrawCtlScreen(); MenuFadeIn(); WaitKeyUp(); break; } } while(which>=0); MenuFadeOut(); #ifdef SPEAR UnCacheLump (CONTROL_LUMP_START,CONTROL_LUMP_END); CacheLump (OPTIONS_LUMP_START,OPTIONS_LUMP_END); #endif } //////////////////////////////// // // DRAW MOUSE SENSITIVITY SCREEN // void DrawMouseSens() { ClearMScreen(); VWB_DrawPic(112,184,C_MOUSELBACKPIC); DrawWindow(10,80,300,30,BKGDCOLOR); WindowX=0; WindowW=320; PrintY=82; SETFONTCOLOR(READCOLOR,BKGDCOLOR); US_CPrint(STR_MOUSEADJ); SETFONTCOLOR(TEXTCOLOR,BKGDCOLOR); PrintX=14; PrintY=95; US_Print(STR_SLOW); PrintX=269; US_Print(STR_FAST); VW_Bar(60,97,200,10,TEXTCOLOR); DrawOutline(60,97,200,10,0,HIGHLIGHT); DrawOutline(60+20*mouseadjustment,97,20,10,0,READCOLOR); VW_Bar(61+20*mouseadjustment,98,19,9,READHCOLOR); VW_UpdateScreen(); MenuFadeIn(); } /////////////////////////// // // ADJUST MOUSE SENSITIVITY // void MouseSensitivity() { ControlInfo ci; int exit=0,oldMA; oldMA=mouseadjustment; DrawMouseSens(); do { ReadAnyControl(&ci); switch(ci.dir) { case dir_North: case dir_West: if (mouseadjustment) { mouseadjustment--; VW_Bar(60,97,200,10,TEXTCOLOR); DrawOutline(60,97,200,10,0,HIGHLIGHT); DrawOutline(60+20*mouseadjustment,97,20,10,0,READCOLOR); VW_Bar(61+20*mouseadjustment,98,19,9,READHCOLOR); VW_UpdateScreen(); SD_PlaySound(MOVEGUN1SND); while(IN_KeyDown(sc_LeftArrow)) IN_CheckAck(); WaitKeyUp(); } break; case dir_South: case dir_East: if (mouseadjustment<9) { mouseadjustment++; VW_Bar(60,97,200,10,TEXTCOLOR); DrawOutline(60,97,200,10,0,HIGHLIGHT); DrawOutline(60+20*mouseadjustment,97,20,10,0,READCOLOR); VW_Bar(61+20*mouseadjustment,98,19,9,READHCOLOR); VW_UpdateScreen(); SD_PlaySound(MOVEGUN1SND); while(IN_KeyDown(sc_RightArrow)) IN_CheckAck(); WaitKeyUp(); } break; default: /* ignore */ break; } if (IN_KeyDown(sc_Tab) && IN_KeyDown(sc_P) && MS_CheckParm("debugmode")) PicturePause(); if (ci.button0 || IN_KeyDown(sc_Space) || IN_KeyDown(sc_Enter)) exit = 1; else if (ci.button1 || IN_KeyDown(sc_Escape)) exit = 2; } while(!exit); if (exit == 2) { mouseadjustment = oldMA; SD_PlaySound(ESCPRESSEDSND); } else SD_PlaySound(SHOOTSND); WaitKeyUp(); MenuFadeOut(); } /////////////////////////// // // DRAW CONTROL MENU SCREEN // void DrawCtlScreen() { int i, x, y; ClearMScreen(); DrawStripes(10); VWB_DrawPic(80,0,C_CONTROLPIC); VWB_DrawPic(112,184,C_MOUSELBACKPIC); DrawWindow(CTL_X-8,CTL_Y-5,CTL_W,CTL_H,BKGDCOLOR); WindowX=0; WindowW=320; SETFONTCOLOR(TEXTCOLOR,BKGDCOLOR); if (JoysPresent[0]) CtlMenu[1].active= CtlMenu[2].active= CtlMenu[3].active=1; CtlMenu[2].active=CtlMenu[3].active=joystickenabled; if (MousePresent) { CtlMenu[4].active= CtlMenu[0].active=1; } CtlMenu[4].active=mouseenabled; DrawMenu(&CtlItems,&CtlMenu[0]); x=CTL_X+CtlItems.indent-24; y=CTL_Y+3; if (mouseenabled) VWB_DrawPic(x,y,C_SELECTEDPIC); else VWB_DrawPic(x,y,C_NOTSELECTEDPIC); y=CTL_Y+16; if (joystickenabled) VWB_DrawPic(x,y,C_SELECTEDPIC); else VWB_DrawPic(x,y,C_NOTSELECTEDPIC); y=CTL_Y+29; if (joystickport) VWB_DrawPic(x,y,C_SELECTEDPIC); else VWB_DrawPic(x,y,C_NOTSELECTEDPIC); y=CTL_Y+42; if (joypadenabled) VWB_DrawPic(x,y,C_SELECTEDPIC); else VWB_DrawPic(x,y,C_NOTSELECTEDPIC); // // PICK FIRST AVAILABLE SPOT // if (CtlItems.curpos<0 || !CtlMenu[CtlItems.curpos].active) for (i=0;i<6;i++) if (CtlMenu[i].active) { CtlItems.curpos=i; break; } DrawMenuGun(&CtlItems); VW_UpdateScreen(); } //////////////////////////////////////////////////////////////////// // // CUSTOMIZE CONTROLS // //////////////////////////////////////////////////////////////////// enum {FIRE,STRAFE,RUN,OPEN}; char mbarray[4][3]={"b0","b1","b2","b3"}; int order[4]={RUN,OPEN,FIRE,STRAFE}; void CustomControls(void) { int which; DrawCustomScreen(); do { which=HandleMenu(&CusItems,&CusMenu[0],FixupCustom); switch(which) { case 0: DefineMouseBtns(); DrawCustMouse(1); break; case 3: DefineJoyBtns(); DrawCustJoy(0); break; case 6: DefineKeyBtns(); DrawCustKeybd(0); break; case 8: DefineKeyMove(); DrawCustKeys(0); } } while(which>=0); MenuFadeOut(); } //////////////////////// // // DEFINE THE MOUSE BUTTONS // void DefineMouseBtns(void) { CustomCtrls mouseallowed={ {0,1,1,1} }; EnterCtrlData(2,&mouseallowed,DrawCustMouse,PrintCustMouse,MOUSE); } //////////////////////// // // DEFINE THE JOYSTICK BUTTONS // void DefineJoyBtns(void) { CustomCtrls joyallowed={ {1,1,1,1} }; EnterCtrlData(5,&joyallowed,DrawCustJoy,PrintCustJoy,JOYSTICK); } //////////////////////// // // DEFINE THE KEYBOARD BUTTONS // void DefineKeyBtns(void) { CustomCtrls keyallowed={ {1,1,1,1} }; EnterCtrlData(8,&keyallowed,DrawCustKeybd,PrintCustKeybd,KEYBOARDBTNS); } //////////////////////// // // DEFINE THE KEYBOARD BUTTONS // void DefineKeyMove(void) { CustomCtrls keyallowed={ {1,1,1,1} }; EnterCtrlData(10,&keyallowed,DrawCustKeys,PrintCustKeys,KEYBOARDMOVE); } //////////////////////// // // ENTER CONTROL DATA FOR ANY TYPE OF CONTROL // enum {FWRD,RIGHT,BKWD,LEFT}; int moveorder[4]={LEFT,RIGHT,FWRD,BKWD}; void EnterCtrlData(int index,CustomCtrls *cust,void (*DrawRtn)(int),void (*PrintRtn)(int),int type) { int j,exit,tick,redraw,which = 0,x = 0,picked; ControlInfo ci; ShootSnd(); PrintY=CST_Y+13*index; IN_ClearKeysDown(); exit=0; redraw=1; // // FIND FIRST SPOT IN ALLOWED ARRAY // for (j=0;j<4;j++) if (cust->allowed[j]) { which=j; break; } do { if (redraw) { x=CST_START+CST_SPC*which; DrawWindow(5,PrintY-1,310,13,BKGDCOLOR); DrawRtn(1); DrawWindow(x-2,PrintY,CST_SPC,11,TEXTCOLOR); DrawOutline(x-2,PrintY,CST_SPC,11,0,HIGHLIGHT); SETFONTCOLOR(0,TEXTCOLOR); PrintRtn(which); PrintX=x; SETFONTCOLOR(TEXTCOLOR,BKGDCOLOR); VW_UpdateScreen(); WaitKeyUp(); redraw=0; } ReadAnyControl(&ci); if (type==MOUSE || type==JOYSTICK) if (IN_KeyDown(sc_Enter) || IN_KeyDown(sc_Control) || IN_KeyDown(sc_Alt)) { IN_ClearKeysDown(); ci.button0=ci.button1=false; } // // CHANGE BUTTON VALUE? // if ((ci.button0|ci.button1|ci.button2|ci.button3)|| ((type==KEYBOARDBTNS||type==KEYBOARDMOVE) && LastScan==sc_Enter)) { tick = picked = 0; set_TimeCount(0); SETFONTCOLOR(0,TEXTCOLOR); do { int button,result=0; if (type==KEYBOARDBTNS||type==KEYBOARDMOVE) IN_ClearKeysDown(); IN_CheckAck(); /* force update */ // // FLASH CURSOR // if (get_TimeCount() >10) { switch(tick) { case 0: VW_Bar(x,PrintY+1,CST_SPC-2,10,TEXTCOLOR); break; case 1: PrintX=x; US_Print("?"); SD_PlaySound(HITWALLSND); } tick^=1; set_TimeCount(0); VW_UpdateScreen(); } // // WHICH TYPE OF INPUT DO WE PROCESS? // switch(type) { case MOUSE: button = IN_MouseButtons(); switch(button) { case 1: result=1; break; case 2: result=2; break; case 4: result=3; break; } if (result) { int z; for (z=0;z<4;z++) if (order[which]==buttonmouse[z]) { buttonmouse[z]=bt_nobutton; break; } buttonmouse[result-1]=order[which]; picked=1; SD_PlaySound(SHOOTDOORSND); } break; case JOYSTICK: if (ci.button0) result=1; else if (ci.button1) result=2; else if (ci.button2) result=3; else if (ci.button3) result=4; if (result) { int z; for (z=0;z<4;z++) if (order[which]==buttonjoy[z]) { buttonjoy[z]=bt_nobutton; break; } buttonjoy[result-1]=order[which]; picked=1; SD_PlaySound(SHOOTDOORSND); } break; case KEYBOARDBTNS: if (LastScan) { buttonscan[order[which]]=LastScan; picked=1; ShootSnd(); IN_ClearKeysDown(); } break; case KEYBOARDMOVE: if (LastScan) { dirscan[moveorder[which]]=LastScan; picked=1; ShootSnd(); IN_ClearKeysDown(); } break; } // // EXIT INPUT? // if (IN_KeyDown(sc_Escape)) { picked=1; continue; } } while(!picked); SETFONTCOLOR(TEXTCOLOR,BKGDCOLOR); redraw=1; WaitKeyUp(); continue; } if (ci.button1 || IN_KeyDown(sc_Escape)) exit=1; // // MOVE TO ANOTHER SPOT? // switch(ci.dir) { case dir_West: do { which--; if (which<0) which=3; } while(!cust->allowed[which]); redraw=1; SD_PlaySound(MOVEGUN1SND); while(ReadAnyControl(&ci),ci.dir!=dir_None); IN_ClearKeysDown(); break; case dir_East: do { which++; if (which>3) which=0; } while(!cust->allowed[which]); redraw=1; SD_PlaySound(MOVEGUN1SND); while(ReadAnyControl(&ci),ci.dir!=dir_None); IN_ClearKeysDown(); break; case dir_North: case dir_South: exit=1; default: break; } } while(!exit); SD_PlaySound(ESCPRESSEDSND); WaitKeyUp(); DrawWindow(5,PrintY-1,310,13,BKGDCOLOR); } //////////////////////// // // FIXUP GUN CURSOR OVERDRAW SHIT // void FixupCustom(int w) { static int lastwhich=-1; int y=CST_Y+26+w*13; VW_Hlin(7,32,y-1,DEACTIVE); VW_Hlin(7,32,y+12,BORD2COLOR); #ifndef SPEAR VW_Hlin(7,32,y-2,BORDCOLOR); VW_Hlin(7,32,y+13,BORDCOLOR); #else VW_Hlin(7,32,y-2,BORD2COLOR); VW_Hlin(7,32,y+13,BORD2COLOR); #endif switch(w) { case 0: DrawCustMouse(1); break; case 3: DrawCustJoy(1); break; case 6: DrawCustKeybd(1); break; case 8: DrawCustKeys(1); } if (lastwhich>=0) { y=CST_Y+26+lastwhich*13; VW_Hlin(7,32,y-1,DEACTIVE); VW_Hlin(7,32,y+12,BORD2COLOR); #ifndef SPEAR VW_Hlin(7,32,y-2,BORDCOLOR); VW_Hlin(7,32,y+13,BORDCOLOR); #else VW_Hlin(7,32,y-2,BORD2COLOR); VW_Hlin(7,32,y+13,BORD2COLOR); #endif if (lastwhich!=w) switch(lastwhich) { case 0: DrawCustMouse(0); break; case 3: DrawCustJoy(0); break; case 6: DrawCustKeybd(0); break; case 8: DrawCustKeys(0); } } lastwhich=w; } //////////////////////// // // DRAW CUSTOMIZE SCREEN // void DrawCustomScreen(void) { int i; ClearMScreen(); WindowX=0; WindowW=320; VWB_DrawPic(112,184,C_MOUSELBACKPIC); DrawStripes(10); VWB_DrawPic(80,0,C_CUSTOMIZEPIC); // // MOUSE // SETFONTCOLOR(READCOLOR,BKGDCOLOR); WindowX=0; WindowW=320; #ifndef SPEAR PrintY=CST_Y; US_CPrint("Mouse\n"); #else PrintY = CST_Y+13; VWB_DrawPic (128,48,C_MOUSEPIC); #endif SETFONTCOLOR(TEXTCOLOR,BKGDCOLOR); PrintX=CST_START; US_Print(STR_CRUN); PrintX=CST_START+CST_SPC*1; US_Print(STR_COPEN); PrintX=CST_START+CST_SPC*2; US_Print(STR_CFIRE); PrintX=CST_START+CST_SPC*3; US_Print(STR_CSTRAFE"\n"); DrawWindow(5,PrintY-1,310,13,BKGDCOLOR); DrawCustMouse(0); US_Print("\n"); // // JOYSTICK/PAD // #ifndef SPEAR SETFONTCOLOR(READCOLOR,BKGDCOLOR); US_CPrint("Joystick/Gravis GamePad\n"); #else PrintY += 13; VWB_DrawPic (40,88,C_JOYSTICKPIC); #endif #ifdef SPEAR VWB_DrawPic (112,120,C_KEYBOARDPIC); #endif SETFONTCOLOR(TEXTCOLOR,BKGDCOLOR); PrintX=CST_START; US_Print(STR_CRUN); PrintX=CST_START+CST_SPC*1; US_Print(STR_COPEN); PrintX=CST_START+CST_SPC*2; US_Print(STR_CFIRE); PrintX=CST_START+CST_SPC*3; US_Print(STR_CSTRAFE"\n"); DrawWindow(5,PrintY-1,310,13,BKGDCOLOR); DrawCustJoy(0); US_Print("\n"); // // KEYBOARD // #ifndef SPEAR SETFONTCOLOR(READCOLOR,BKGDCOLOR); US_CPrint("Keyboard\n"); #else PrintY += 13; #endif SETFONTCOLOR(TEXTCOLOR,BKGDCOLOR); PrintX=CST_START; US_Print(STR_CRUN); PrintX=CST_START+CST_SPC*1; US_Print(STR_COPEN); PrintX=CST_START+CST_SPC*2; US_Print(STR_CFIRE); PrintX=CST_START+CST_SPC*3; US_Print(STR_CSTRAFE"\n"); DrawWindow(5,PrintY-1,310,13,BKGDCOLOR); DrawCustKeybd(0); US_Print("\n"); // // KEYBOARD MOVE KEYS // SETFONTCOLOR(TEXTCOLOR,BKGDCOLOR); PrintX=CST_START; US_Print(STR_LEFT); PrintX=CST_START+CST_SPC*1; US_Print(STR_RIGHT); PrintX=CST_START+CST_SPC*2; US_Print(STR_FRWD); PrintX=CST_START+CST_SPC*3; US_Print(STR_BKWD"\n"); DrawWindow(5,PrintY-1,310,13,BKGDCOLOR); DrawCustKeys(0); // // PICK STARTING POINT IN MENU // if (CusItems.curpos<0) for (i=0;i<CusItems.amount;i++) if (CusMenu[i].active) { CusItems.curpos=i; break; } VW_UpdateScreen(); MenuFadeIn(); } void PrintCustMouse(int i) { int j; for (j=0;j<4;j++) if (order[i]==buttonmouse[j]) { PrintX=CST_START+CST_SPC*i; US_Print(mbarray[j]); break; } } void DrawCustMouse(int hilight) { int i,color; color=TEXTCOLOR; if (hilight) color=HIGHLIGHT; SETFONTCOLOR(color,BKGDCOLOR); if (!mouseenabled) { SETFONTCOLOR(DEACTIVE,BKGDCOLOR); CusMenu[0].active=0; } else CusMenu[0].active=1; PrintY=CST_Y+13*2; for (i=0;i<4;i++) PrintCustMouse(i); } void PrintCustJoy(int i) { int j; for (j=0;j<4;j++) if (order[i]==buttonjoy[j]) { PrintX=CST_START+CST_SPC*i; US_Print(mbarray[j]); break; } } void DrawCustJoy(int hilight) { int i,color; color=TEXTCOLOR; if (hilight) color=HIGHLIGHT; SETFONTCOLOR(color,BKGDCOLOR); if (!joystickenabled) { SETFONTCOLOR(DEACTIVE,BKGDCOLOR); CusMenu[3].active=0; } else CusMenu[3].active=1; PrintY=CST_Y+13*5; for (i=0;i<4;i++) PrintCustJoy(i); } void PrintCustKeybd(int i) { PrintX=CST_START+CST_SPC*i; US_Print(IN_GetScanName(buttonscan[order[i]])); } void DrawCustKeybd(int hilight) { int i,color; color=TEXTCOLOR; if (hilight) color=HIGHLIGHT; SETFONTCOLOR(color,BKGDCOLOR); PrintY=CST_Y+13*8; for (i=0;i<4;i++) PrintCustKeybd(i); } void PrintCustKeys(int i) { PrintX=CST_START+CST_SPC*i; US_Print(IN_GetScanName(dirscan[moveorder[i]])); } void DrawCustKeys(int hilight) { int i,color; color=TEXTCOLOR; if (hilight) color=HIGHLIGHT; SETFONTCOLOR(color,BKGDCOLOR); PrintY=CST_Y+13*10; for (i=0;i<4;i++) PrintCustKeys(i); } //////////////////////////////////////////////////////////////////// // // CHANGE SCREEN VIEWING SIZE // //////////////////////////////////////////////////////////////////// void CP_ChangeView() { int exit = 0, oldview, newview; ControlInfo ci; WindowX=WindowY=0; WindowW=320; WindowH=200; newview=oldview=viewsize; DrawChangeView(oldview); do { CheckPause(); ReadAnyControl(&ci); switch(ci.dir) { case dir_South: case dir_West: newview--; if (newview<4) newview=4; ShowViewSize(newview); VW_UpdateScreen(); SD_PlaySound(HITWALLSND); TicDelay(10); break; case dir_North: case dir_East: newview++; if (newview>20) newview=20; ShowViewSize(newview); VW_UpdateScreen(); SD_PlaySound(HITWALLSND); TicDelay(10); break; default: break; } if (IN_KeyDown(sc_Tab) && IN_KeyDown(sc_P) && MS_CheckParm("debugmode")) PicturePause(); if (ci.button0 || IN_KeyDown(sc_Enter)) exit = 1; else if (ci.button1 || IN_KeyDown(sc_Escape)) { SD_PlaySound(ESCPRESSEDSND); MenuFadeOut(); return; } } while(!exit); if (oldview != newview) { SD_PlaySound(SHOOTSND); Message(STR_THINK"..."); NewViewSize(newview); } ShootSnd(); MenuFadeOut(); } ///////////////////////////// // // DRAW THE CHANGEVIEW SCREEN // void DrawChangeView(int view) { VW_Bar(0,160,320,40,VIEWCOLOR); ShowViewSize(view); PrintY=161; WindowX=0; WindowY=320; SETFONTCOLOR(HIGHLIGHT,BKGDCOLOR); US_CPrint(STR_SIZE1"\n"); US_CPrint(STR_SIZE2"\n"); US_CPrint(STR_SIZE3); VW_UpdateScreen(); MenuFadeIn(); } //////////////////////////////////////////////////////////////////// // // QUIT THIS INFERNAL GAME! // //////////////////////////////////////////////////////////////////// void CP_Quit() { if (Confirm(endStrings[(US_RndT()&0x7)+(US_RndT()&1)])) { VW_UpdateScreen(); SD_MusicOff(); SD_StopSound(); MenuFadeOut(); Quit(NULL); } DrawMainMenu(); } //////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////// // // SUPPORT ROUTINES // //////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////// // // Clear Menu screens to dark red // //////////////////////////////////////////////////////////////////// void ClearMScreen(void) { #ifndef SPEAR VW_Bar(0,0,320,200,BORDCOLOR); #else VWB_DrawPic(0,0,C_BACKDROPPIC); #endif } //////////////////////////////////////////////////////////////////// // // Un/Cache a LUMP of graphics // //////////////////////////////////////////////////////////////////// void CacheLump(int lumpstart, int lumpend) { int i; for (i=lumpstart;i<=lumpend;i++) CA_CacheGrChunk(i); } void UnCacheLump(int lumpstart, int lumpend) { int i; for (i=lumpstart;i<=lumpend;i++) CA_UnCacheGrChunk(i); } //////////////////////////////////////////////////////////////////// // // Draw a window for a menu // //////////////////////////////////////////////////////////////////// void DrawWindow(int x,int y,int w,int h,int wcolor) { VW_Bar(x,y,w,h,wcolor); DrawOutline(x,y,w,h,BORD2COLOR,DEACTIVE); } void DrawOutline(int x,int y,int w,int h,int color1,int color2) { VW_Hlin(x,x+w,y,color2); VW_Vlin(y,y+h,x,color2); VW_Hlin(x,x+w,y+h,color1); VW_Vlin(y,y+h,x+w,color1); } //////////////////////////////////////////////////////////////////// // // Setup Control Panel stuff - graphics, etc. // //////////////////////////////////////////////////////////////////// void SetupControlPanel() { int which; // // CACHE GRAPHICS & SOUNDS // CA_CacheGrChunk(STARTFONT+1); #ifndef SPEAR CacheLump(CONTROLS_LUMP_START,CONTROLS_LUMP_END); #else CacheLump(BACKDROP_LUMP_START,BACKDROP_LUMP_END); #endif SETFONTCOLOR(TEXTCOLOR,BKGDCOLOR); fontnumber=1; WindowH=200; if (!ingame) CA_LoadAllSounds(); else MainMenu[savegame].active=1; // // SEE WHICH SAVE GAME FILES ARE AVAILABLE & READ STRING IN // { #if defined(HAVE_FFBLK) struct ffblk f; // todo: fix /* if (!findfirst(SaveName,&f,0)) do { which=f.ff_name[7]-'0'; if (which<10) { char temp[32]; if (ReadSaveTag(f.ff_name, temp) != -1) { SaveGamesAvail[which]=1; strcpy(&SaveGameNames[which][0],temp); } } } while(!findnext(&f)); */ #elif defined(HAVE_FINDDATA) struct _finddata_t f; long hand; if ((hand = _findfirst(SaveName, &f)) != -1) do { which=f.name[7]-'0'; if (which<10) { char temp[32]; if (ReadSaveTag(f.name, temp) != -1) { SaveGamesAvail[which]=1; strcpy(&SaveGameNames[which][0],temp); } } } while(_findnext(hand, &f) != -1); #else glob_t globbuf; int x; if (glob(SaveName, 0, NULL, &globbuf)) return; for (x = 0; x < globbuf.gl_pathc; x++) { which = globbuf.gl_pathv[x][7] - '0'; if (which < 10) { char temp[32]; if (ReadSaveTag(globbuf.gl_pathv[x], temp) != -1) { SaveGamesAvail[which]=1; strcpy(&SaveGameNames[which][0],temp); } } } globfree(&globbuf); #endif } } //////////////////////////////////////////////////////////////////// // // Clean up all the Control Panel stuff // //////////////////////////////////////////////////////////////////// void CleanupControlPanel() { #ifndef SPEAR UnCacheLump(CONTROLS_LUMP_START,CONTROLS_LUMP_END); #else UnCacheLump (BACKDROP_LUMP_START,BACKDROP_LUMP_END); #endif fontnumber = 0; } //////////////////////////////////////////////////////////////////// // // Handle moving gun around a menu // //////////////////////////////////////////////////////////////////// int HandleMenu(CP_iteminfo *item_i,CP_itemtype *items,void (*routine)(int w)) { char key; static int redrawitem=1,lastitem=-1; int i,x,y,basey,exit,which,shape,timer; ControlInfo ci; which=item_i->curpos; x=item_i->x&-8; basey=item_i->y-2; y=basey+which*13; VWB_DrawPic(x,y,C_CURSOR1PIC); SetMenuTextColor(items+which,1); if (redrawitem) { PrintX=item_i->x+item_i->indent; PrintY=item_i->y+which*13; US_Print((items+which)->string); } // // CALL CUSTOM ROUTINE IF IT IS NEEDED // if (routine) routine(which); VW_UpdateScreen(); shape=C_CURSOR1PIC; timer=8; exit=0; set_TimeCount(0); IN_ClearKeysDown(); do { // // CHANGE GUN SHAPE // if (get_TimeCount() > timer) { set_TimeCount(0); if (shape==C_CURSOR1PIC) { shape=C_CURSOR2PIC; timer=8; } else { shape=C_CURSOR1PIC; timer=70; } VWB_DrawPic(x,y,shape); if (routine) routine(which); VW_UpdateScreen(); } CheckPause(); // // SEE IF ANY KEYS ARE PRESSED FOR INITIAL CHAR FINDING // key=LastASCII; if (key) { int ok=0; // // CHECK FOR SCREEN CAPTURE // if (IN_KeyDown(sc_Tab) && IN_KeyDown(sc_P) && MS_CheckParm("debugmode")) PicturePause(); if (key>='a') key-='a'-'A'; for (i=which+1;i<item_i->amount;i++) if ((items+i)->active && (items+i)->string[0]==key) { EraseGun(item_i,items,x,y,which); which=i; DrawGun(item_i,items,x,&y,which,basey,routine); ok=1; IN_ClearKeysDown(); break; } // // DIDN'T FIND A MATCH FIRST TIME THRU. CHECK AGAIN. // if (!ok) { for (i=0;i<which;i++) if ((items+i)->active && (items+i)->string[0]==key) { EraseGun(item_i,items,x,y,which); which=i; DrawGun(item_i,items,x,&y,which,basey,routine); IN_ClearKeysDown(); break; } } } // // GET INPUT // ReadAnyControl(&ci); switch(ci.dir) { //////////////////////////////////////////////// // // MOVE UP // case dir_North: case dir_East: EraseGun(item_i,items,x,y,which); // // ANIMATE HALF-STEP // if (which && (items+which-1)->active) { y-=6; DrawHalfStep(x,y); } // // MOVE TO NEXT AVAILABLE SPOT // do { if (!which) which=item_i->amount-1; else which--; } while(!(items+which)->active); DrawGun(item_i,items,x,&y,which,basey,routine); // // WAIT FOR BUTTON-UP OR DELAY NEXT MOVE // TicDelay(20); break; //////////////////////////////////////////////// // // MOVE DOWN // case dir_South: case dir_West: EraseGun(item_i,items,x,y,which); // // ANIMATE HALF-STEP // if (which!=item_i->amount-1 && (items+which+1)->active) { y+=6; DrawHalfStep(x,y); } do { if (which==item_i->amount-1) which=0; else which++; } while(!(items+which)->active); DrawGun(item_i,items,x,&y,which,basey,routine); // // WAIT FOR BUTTON-UP OR DELAY NEXT MOVE // TicDelay(20); break; default: break; } if (ci.button0 || IN_KeyDown(sc_Space) || IN_KeyDown(sc_Enter)) exit = 1; if (ci.button1 || IN_KeyDown(sc_Escape)) exit = 2; } while(!exit); IN_ClearKeysDown(); // // ERASE EVERYTHING // if (lastitem!=which) { VW_Bar(x-1,y,25,16,BKGDCOLOR); PrintX=item_i->x+item_i->indent; PrintY=item_i->y+which*13; US_Print((items+which)->string); redrawitem=1; } else redrawitem=0; if (routine) routine(which); VW_UpdateScreen(); item_i->curpos=which; lastitem=which; switch(exit) { case 1: // // CALL THE ROUTINE // if ((items+which)->routine!=NULL) { ShootSnd(); MenuFadeOut(); (items+which)->routine(0); } return which; case 2: SD_PlaySound(ESCPRESSEDSND); return -1; } return 0; // JUST TO SHUT UP THE ERROR MESSAGES! } // // ERASE GUN & DE-HIGHLIGHT STRING // void EraseGun(CP_iteminfo *item_i,CP_itemtype *items,int x,int y,int which) { VW_Bar(x-1,y,25,16,BKGDCOLOR); SetMenuTextColor(items+which,0); PrintX=item_i->x+item_i->indent; PrintY=item_i->y+which*13; US_Print((items+which)->string); VW_UpdateScreen(); } // // DRAW HALF STEP OF GUN TO NEXT POSITION // void DrawHalfStep(int x,int y) { VWB_DrawPic(x,y,C_CURSOR1PIC); VW_UpdateScreen(); SD_PlaySound(MOVEGUN1SND); set_TimeCount(0); while(get_TimeCount() < 8); } // // DRAW GUN AT NEW POSITION // void DrawGun(CP_iteminfo *item_i,CP_itemtype *items,int x,int *y,int which,int basey,void (*routine)(int w)) { VW_Bar(x-1,*y,25,16,BKGDCOLOR); *y=basey+which*13; VWB_DrawPic(x,*y,C_CURSOR1PIC); SetMenuTextColor(items+which,1); PrintX=item_i->x+item_i->indent; PrintY=item_i->y+which*13; US_Print((items+which)->string); // // CALL CUSTOM ROUTINE IF IT IS NEEDED // if (routine) routine(which); VW_UpdateScreen(); SD_PlaySound(MOVEGUN2SND); } //////////////////////////////////////////////////////////////////// // // DELAY FOR AN AMOUNT OF TICS OR UNTIL CONTROLS ARE INACTIVE // //////////////////////////////////////////////////////////////////// void TicDelay(int count) { ControlInfo ci; set_TimeCount(0); do { ReadAnyControl(&ci); } while( (get_TimeCount() < count) && (ci.dir!=dir_None) ); } //////////////////////////////////////////////////////////////////// // // Draw a menu // //////////////////////////////////////////////////////////////////// void DrawMenu(CP_iteminfo *item_i,CP_itemtype *items) { int i,which=item_i->curpos; WindowX=PrintX=item_i->x+item_i->indent; WindowY=PrintY=item_i->y; WindowW=320; WindowH=200; for (i=0;i<item_i->amount;i++) { SetMenuTextColor(items+i,which==i); PrintY=item_i->y+i*13; if ((items+i)->active) US_Print((items+i)->string); else { SETFONTCOLOR(DEACTIVE,BKGDCOLOR); US_Print((items+i)->string); SETFONTCOLOR(TEXTCOLOR,BKGDCOLOR); } US_Print("\n"); } } //////////////////////////////////////////////////////////////////// // // SET TEXT COLOR (HIGHLIGHT OR NO) // //////////////////////////////////////////////////////////////////// void SetMenuTextColor(CP_itemtype *items,int hlight) { if (hlight) {SETFONTCOLOR(color_hlite[items->active],BKGDCOLOR);} else {SETFONTCOLOR(color_norml[items->active],BKGDCOLOR);} } //////////////////////////////////////////////////////////////////// // // WAIT FOR CTRLKEY-UP OR BUTTON-UP // //////////////////////////////////////////////////////////////////// void WaitKeyUp(void) { ControlInfo ci; while(ReadAnyControl(&ci), ci.button0|ci.button1|ci.button2|ci.button3| IN_KeyDown(sc_Space)|IN_KeyDown(sc_Enter)|IN_KeyDown(sc_Escape)); } //////////////////////////////////////////////////////////////////// // // READ KEYBOARD, JOYSTICK AND MOUSE FOR INPUT // //////////////////////////////////////////////////////////////////// void ReadAnyControl(ControlInfo *ci) { int mouseactive=0; IN_ReadControl(0,ci); if (mouseenabled) { } if (joystickenabled && !mouseactive) { } } //////////////////////////////////////////////////////////////////// // // DRAW DIALOG AND CONFIRM YES OR NO TO QUESTION // //////////////////////////////////////////////////////////////////// int Confirm(const char *string) { int xit=0,x,y,tick=0,whichsnd[2]={ESCPRESSEDSND,SHOOTSND}; Message(string); IN_ClearKeysDown(); // // BLINK CURSOR // x=PrintX; y=PrintY; set_TimeCount(0); do { IN_CheckAck(); /* force update */ if (get_TimeCount() >= 10) { switch(tick) { case 0: VW_Bar(x,y,8,13,TEXTCOLOR); break; case 1: PrintX=x; PrintY=y; US_Print("_"); } VW_UpdateScreen(); tick^=1; set_TimeCount(0); } if (IN_KeyDown(sc_Tab) && IN_KeyDown(sc_P) && MS_CheckParm("debugmode")) PicturePause(); } while(!IN_KeyDown(sc_Y) && !IN_KeyDown(sc_N) && !IN_KeyDown(sc_Escape) && !IN_KeyDown(sc_Enter)); if (IN_KeyDown(sc_Y) || IN_KeyDown(sc_Enter)) { xit=1; ShootSnd(); } while(IN_KeyDown(sc_Y) || IN_KeyDown(sc_N) || IN_KeyDown(sc_Escape) || IN_KeyDown(sc_Enter)) IN_CheckAck(); IN_ClearKeysDown(); SD_PlaySound(whichsnd[xit]); return xit; } //////////////////////////////////////////////////////////////////// // // PRINT A MESSAGE IN A WINDOW // //////////////////////////////////////////////////////////////////// void Message(const char *string) { word h=0, mw=0; CA_CacheGrChunk(STARTFONT+1); fontnumber=1; VW_MeasurePropString(string, &mw, &h); mw += 4; PrintY=(WindowH/2)-h/2; PrintX=WindowX=160-mw/2; DrawWindow(WindowX-5,PrintY-5,mw+10,h+10,TEXTCOLOR); DrawOutline(WindowX-5,PrintY-5,mw+10,h+10,0,HIGHLIGHT); SETFONTCOLOR(0,TEXTCOLOR); US_Print(string); VW_UpdateScreen(); } static int lastmusic = -1; void StartCPMusic(int song) { FreeMusic(); lastmusic = song; SD_StartMusic(song); } void FreeMusic() { SD_MusicOff(); } /////////////////////////////////////////////////////////////////////////// // // CHECK FOR PAUSE KEY (FOR MUSIC ONLY) // /////////////////////////////////////////////////////////////////////////// void CheckPause() { if (Paused) { switch(SoundStatus) { case 0: SD_MusicOn(); break; case 1: SD_MusicOff(); break; } SoundStatus^=1; VW_WaitVBL(3); IN_ClearKeysDown(); Paused=false; } } /////////////////////////////////////////////////////////////////////////// // // DRAW GUN CURSOR AT CORRECT POSITION IN MENU // /////////////////////////////////////////////////////////////////////////// void DrawMenuGun(CP_iteminfo *iteminfo) { int x, y; x = iteminfo->x; y = iteminfo->y+iteminfo->curpos*13-2; VWB_DrawPic(x,y,C_CURSOR1PIC); } /////////////////////////////////////////////////////////////////////////// // // DRAW SCREEN TITLE STRIPES // /////////////////////////////////////////////////////////////////////////// void DrawStripes(int y) { #ifndef SPEAR VW_Bar(0,y,320,24,0); VW_Hlin(0,319,y+22,STRIPE); #else VW_Bar(0,y,320,22,0); VW_Hlin(0,319,y+23,0); #endif } void ShootSnd() { SD_PlaySound(SHOOTSND); } /////////////////////////////////////////////////////////////////////////// // // CHECK FOR EPISODES // /////////////////////////////////////////////////////////////////////////// void CheckForEpisodes() { #if defined(HAVE_FFBLK) struct ffblk f; // // ENGLISH // #ifndef UPLOAD #ifndef SPEAR if (!findfirst("*.wl6", &f, FA_ARCH)) { strcpy(extension, "wl6"); NewEmenu[2].active = NewEmenu[4].active = NewEmenu[6].active = NewEmenu[8].active = NewEmenu[10].active = EpisodeSelect[1] = EpisodeSelect[2] = EpisodeSelect[3] = EpisodeSelect[4] = EpisodeSelect[5] = 1; } else if (!findfirst("*.wl3", &f, FA_ARCH)) { strcpy(extension, "wl3"); NewEmenu[2].active = NewEmenu[4].active = EpisodeSelect[1] = EpisodeSelect[2] = 1; } else #endif /* SPEAR */ #endif /* UPLOAD */ #ifdef SPEAR #ifndef SPEARDEMO if (!findfirst("*.sod", &f, FA_ARCH)) { strcpy(extension, "sod"); } else Quit("NO SPEAR OF DESTINY DATA FILES TO BE FOUND!"); #else /* SPEARDEMO */ if (!findfirst("*.sdm",&f,FA_ARCH)) { strcpy(extension, "sdm"); } else Quit("NO SPEAR OF DESTINY DEMO DATA FILES TO BE FOUND!"); #endif /* SPEARDEMO */ #else /* SPEAR */ if (!findfirst("*.wl1",&f,FA_ARCH)) { strcpy(extension, "wl1"); } else Quit("NO WOLFENSTEIN 3-D DATA FILES TO BE FOUND!"); #endif /* SPEAR */ #elif defined(HAVE_FINDDATA) struct _finddata_t f; // // ENGLISH // #ifndef UPLOAD #ifndef SPEAR if (_findfirst("*.wl6", &f) != -1) { strcpy(extension, "wl6"); NewEmenu[2].active = NewEmenu[4].active = NewEmenu[6].active = NewEmenu[8].active = NewEmenu[10].active = EpisodeSelect[1] = EpisodeSelect[2] = EpisodeSelect[3] = EpisodeSelect[4] = EpisodeSelect[5] = 1; } else if (_findfirst("*.wl3",&f) != -1) { strcpy(extension, "wl3"); NewEmenu[2].active = NewEmenu[4].active = EpisodeSelect[1] = EpisodeSelect[2] = 1; } else #endif /* SPEAR */ #endif /* UPLOAD */ #ifdef SPEAR #ifndef SPEARDEMO if (_findfirst("*.sod", &f) != -1) { strcpy(extension, "sod"); } else Quit("NO SPEAR OF DESTINY DATA FILES TO BE FOUND!"); #else /* SPEARDEMO */ if (_findfirst("*.sdm", &f) != -1) { strcpy(extension, "sdm"); } else Quit("NO SPEAR OF DESTINY DEMO DATA FILES TO BE FOUND!"); #endif /* SPEARDEMO */ #else /* SPEAR */ if (_findfirst("*.wl1",&f) != -1) { strcpy(extension, "wl1"); } else Quit("NO WOLFENSTEIN 3-D DATA FILES TO BE FOUND!"); #endif /* SPEAR */ #else glob_t globbuf; // // ENGLISH // #ifndef UPLOAD #ifndef SPEAR if (glob("*.wl6", 0, NULL, &globbuf) == 0) { strcpy(extension, "wl6"); NewEmenu[2].active = NewEmenu[4].active = NewEmenu[6].active = NewEmenu[8].active = NewEmenu[10].active = EpisodeSelect[1] = EpisodeSelect[2] = EpisodeSelect[3] = EpisodeSelect[4] = EpisodeSelect[5] = 1; } else if (glob("*.wl3", 0, NULL, &globbuf) == 0) { strcpy(extension, "wl3"); NewEmenu[2].active = NewEmenu[4].active = EpisodeSelect[1] = EpisodeSelect[2] = 1; } else #endif /* SPEAR */ #endif /* UPLOAD */ #ifdef SPEAR #ifndef SPEARDEMO if (glob("*.sod", 0, NULL, &globbuf) == 0) { strcpy(extension, "sod"); } else Quit("NO SPEAR OF DESTINY DATA FILES TO BE FOUND!"); #else /* SPEARDEMO */ if (glob("*.sdm", 0, NULL, &globbuf) == 0) { strcpy(extension, "sdm"); } else Quit("NO SPEAR OF DESTINY DEMO DATA FILES TO BE FOUND!"); #endif /* SPEARDEMO */ #else /* SPEAR */ if (glob("*.wl1", 0, NULL, &globbuf) == 0) { strcpy(extension, "wl1"); } else Quit("NO WOLFENSTEIN 3-D DATA FILES TO BE FOUND!"); #endif /* SPEAR */ globfree(&globbuf); #endif strcat(configname, extension); strcat(SaveName, extension); }
1
0.579898
1
0.579898
game-dev
MEDIA
0.764588
game-dev
0.922529
1
0.922529
shxp3/CrossSine
2,201
src/main/java/net/ccbluex/liquidbounce/features/module/modules/other/disablers/other/BoatDisabler.kt
/* * FDPClient Hacked Client * A free open source mixin-based injection hacked client for Minecraft using Minecraft Forge by LiquidBounce. * https://github.com/SkidderMC/FDPClient/ */ package net.ccbluex.liquidbounce.features.module.modules.other.disablers.other import net.ccbluex.liquidbounce.event.PacketEvent import net.ccbluex.liquidbounce.event.UpdateEvent import net.ccbluex.liquidbounce.event.WorldEvent import net.ccbluex.liquidbounce.features.module.modules.other.disablers.DisablerMode import net.ccbluex.liquidbounce.features.value.BoolValue import net.minecraft.entity.Entity import net.minecraft.entity.item.EntityBoat import net.minecraft.network.play.client.C03PacketPlayer class BoatDisabler : DisablerMode("Boat") { private var canModify = false private val noGroundValue = BoolValue("${valuePrefix}NoGround", false) override fun onUpdate(event: UpdateEvent) { if (mc.thePlayer.ridingEntity != null) { mc.thePlayer.rotationPitch = (90.0).toFloat() mc.thePlayer.swingItem() mc.playerController.attackEntity(mc.thePlayer, mc.thePlayer.ridingEntity) mc.thePlayer.swingItem() mc.playerController.attackEntity(mc.thePlayer, getNearBoat()) canModify = true disabler.debugMessage("Destroy Boat") } } override fun onPacket(event: PacketEvent) { val packet = event.packet if (mc.thePlayer.ridingEntity != null) { canModify = true } if (canModify && packet is C03PacketPlayer) { packet.onGround = !noGroundValue.get() } } override fun onWorld(event: WorldEvent) { canModify = false } override fun onEnable() { disabler.debugMessage("Place 2 Boats Next To Each other And Right Click To Use It!") canModify = false } private fun getNearBoat():Entity? { val entities = mc.theWorld.loadedEntityList for (entity_ in entities) { if (entity_ is EntityBoat) { if (entity_ != mc.thePlayer.ridingEntity) { return entity_ } } } return null } }
1
0.848548
1
0.848548
game-dev
MEDIA
0.948112
game-dev
0.790379
1
0.790379
hlrs-vis/covise
15,147
src/module/general/BlockCollect/BlockCollect.cpp
/* This file is part of COVISE. You can use it under the terms of the GNU Lesser General Public License version 2.1 or later, see lgpl-2.1.txt. * License: LGPL 2+ */ /**************************************************************************\ ** (C)1997 RUS ** ** (C)2001 VirCinity GmbH ** ** Description: BlockCollect ** ** ** ** ** ** ** ** ** ** ** ** (C) 1997 ** ** Computer Center University of Stuttgart ** ** Allmandring 30a ** ** 70550 Stuttgart ** ** ** ** ** ** Author: Uwe Woessner ** ** ** ** ** ** Date: 26.09.97 ** ** 03.04.2001 Sven Kufer: changed to new API ** ** 27.09.2002 Sven Kufer: redesign \**************************************************************************/ #include <do/coDoGeometry.h> #include <do/coDoSet.h> #include "BlockCollect.h" using namespace covise; BlockCollect::BlockCollect(int argc, char *argv[]) : coModule(argc, argv, "create one big set out of many many little ones") { int i; char portname[20]; for (i = 0; i < NUM_PORTS; i++) { sprintf(portname, "inport_%d", i); p_inport[i] = addInputPort(portname, "coDistributedObject", "input object"); if (i > 0) p_inport[i]->setRequired(0); } p_outport = addOutputPort("set_out", "coDistributedObject", "output object"); p_mode = addChoiceParam("mode", "mode"); const char *choLabels[] = { "Set of Elements", "Cat Timesteps", "Merge Blocks", "Set of Timesteps", "Set of Blocks", "Cat Blocks" }; p_mode->setValue(6, choLabels, SetOfElements); } int BlockCollect::NoTimeSteps() { int i, j, res = 0; const coDistributedObject *tmp_obj; aktivePorts = 0; int no_elements; if (mode == SetOfBlocks) { tmp_obj = p_inport[0]->getCurrentObject(); if (dynamic_cast<const coDoSet *>(tmp_obj)) { res = (static_cast<const coDoSet *>(tmp_obj))->getNumElements(); } for (i = 0; i < NUM_PORTS; ++i) { tmp_obj = p_inport[i]->getCurrentObject(); if (tmp_obj) aktivePorts++; } } else if (mode == CatBlocks) { for (i = 0; i < NUM_PORTS; ++i) { tmp_obj = p_inport[i]->getCurrentObject(); if (!tmp_obj) continue; if (dynamic_cast<const coDoSet *>(tmp_obj)) { const coDistributedObject *const *setList = ((coDoSet *)(tmp_obj))->getAllElements(&no_elements); for (j = 0; j < no_elements; ++j) { if (dynamic_cast<const coDoSet *>(setList[j])) { res += (static_cast<const coDoSet *>(setList[j]))->getNumElements(); } else { res++; } } } else { res++; } } } else { for (i = 0; i < NUM_PORTS; ++i) { tmp_obj = p_inport[i]->getCurrentObject(); if (!tmp_obj) continue; if (dynamic_cast<const coDoGeometry *>(tmp_obj)) return 0; // handle objects always as static if one of them is a geometry object if (dynamic_cast<const coDoSet *>(tmp_obj) && mode != SetOfElements && mode != SetOfTimesteps) { // we have transient data res += (static_cast<const coDoSet *>(tmp_obj))->getNumElements(); } else { // we have static data if (mode == MergeBlocks) { return -1; // we have static data but also transient data } res++; } } } return res; } int BlockCollect::compute(const char *) { int i; mode = (CollectMode)p_mode->getValue(); const coDistributedObject *tmp_obj; const coDistributedObject *real_obj; coDoSet *set_output; real_obj = p_inport[0]->getCurrentObject(); if (real_obj == NULL) { sendError("Object at inport_0 not found"); return STOP_PIPELINE; } int nume = 0; const coDistributedObject **outobjs; const coDistributedObject *p_ForAttributes = NULL; // 1 if all elements int time_steps = NoTimeSteps(); // -1 : mix of static and transient data if (mode == SetOfBlocks) { outobjs = new const coDistributedObject *[time_steps + 1]; outobjs[time_steps] = NULL; int numSets = time_steps * aktivePorts; const coDistributedObject **tmpobjs = new const coDistributedObject *[numSets + 1]; tmpobjs[numSets] = NULL; char name[256]; // now go through all ports for (i = 0; i < NUM_PORTS; i++) { tmp_obj = p_inport[i]->getCurrentObject(); if (tmp_obj) { if (dynamic_cast<const coDoSet *>(tmp_obj)) { int j, no_elements; const coDistributedObject *const *setList = ((coDoSet *)(tmp_obj))->getAllElements(&no_elements); for (j = 0; j < no_elements; ++j) { tmpobjs[nume++] = setList[j]; setList[j]->incRefCount(); } } /*else { tmpobjs[nume++] = tmp_obj; tmp_obj->incRefCount(); }*/ } } const coDistributedObject **tmp_blocks; coDoSet *tmp_set; int att = 0; for (int step = 0; step < time_steps; step++) { int number = 0; int count = 0; for (i = step; i < numSets; i += time_steps) { if (dynamic_cast<const coDoSet *>(tmpobjs[i])) { number += (static_cast<const coDoSet *>(tmpobjs[i]))->getNumElements(); } } tmp_blocks = new const coDistributedObject *[number + 1]; tmp_blocks[number] = NULL; for (i = step; i < numSets; i += time_steps) { if (dynamic_cast<const coDoSet *>(tmpobjs[i])) { int elem, k; const coDistributedObject *const *blockList = ((coDoSet *)(tmpobjs[i]))->getAllElements(&elem); if (att == 0) { p_ForAttributes = tmpobjs[i]; att = -1; } for (k = 0; k < elem; ++k) { tmp_blocks[count++] = blockList[k]; blockList[k]->incRefCount(); } } } //in ein set packen sprintf(name, "%s_%d", p_outport->getObjName(), step); tmp_set = new coDoSet(name, tmp_blocks); //set in outobjs an stelle step outobjs[step] = tmp_set; } } else if (mode == CatBlocks) { outobjs = new const coDistributedObject *[time_steps + 1]; outobjs[time_steps] = NULL; // now go through all ports for (i = 0; i < NUM_PORTS; i++) { tmp_obj = p_inport[i]->getCurrentObject(); if (tmp_obj) { if (dynamic_cast<const coDoSet *>(tmp_obj)) { int j, no_elements; const coDistributedObject *const *setList = ((coDoSet *)(tmp_obj))->getAllElements(&no_elements); if (nume == 0) p_ForAttributes = tmp_obj; for (j = 0; j < no_elements; ++j) { if (dynamic_cast<const coDoSet *>(setList[j])) { int k, no_elements2; const coDistributedObject *const *setList2 = ((coDoSet *)(setList[j]))->getAllElements(&no_elements2); for (k = 0; k < no_elements2; k++) { outobjs[nume++] = setList2[k]; setList2[k]->incRefCount(); } } else { outobjs[nume++] = setList[j]; setList[j]->incRefCount(); } } } else { outobjs[nume++] = tmp_obj; tmp_obj->incRefCount(); } } } } else if (time_steps < 0 && mode == MergeBlocks) { // inconsistent data sendError("You may not mix static and transient data"); return STOP_PIPELINE; } else if (time_steps == 0 || mode == SetOfElements || mode == SetOfTimesteps) { time_steps = 0; if (mode == MergeBlocks) { sendError("You need a set if you want to merge"); return STOP_PIPELINE; } // static data outobjs = new const coDistributedObject *[NUM_PORTS + 1]; // now go through all ports for (i = 0; i < NUM_PORTS; i++) { tmp_obj = p_inport[i]->getCurrentObject(); if (tmp_obj != NULL) { outobjs[nume] = tmp_obj; outobjs[nume]->incRefCount(); nume++; } outobjs[nume] = NULL; if (mode == CatTimesteps) { time_steps = nume; } p_ForAttributes = NULL; } } else { // transient data if (mode != MergeBlocks) { outobjs = new const coDistributedObject *[time_steps + 1]; outobjs[time_steps] = NULL; // now go through all ports for (i = 0; i < NUM_PORTS; i++) { tmp_obj = p_inport[i]->getCurrentObject(); if (tmp_obj) { if (dynamic_cast<const coDoSet *>(tmp_obj)) { int j, no_elements; const coDistributedObject *const *setList = ((coDoSet *)(tmp_obj))->getAllElements(&no_elements); if (nume == 0) p_ForAttributes = tmp_obj; for (j = 0; j < no_elements; ++j) { outobjs[nume++] = setList[j]; setList[j]->incRefCount(); } } else { outobjs[nume++] = tmp_obj; tmp_obj->incRefCount(); } } } } else { const coDistributedObject *const *setList[NUM_PORTS]; int dummy; for (i = 0; i < NUM_PORTS; i++) { tmp_obj = p_inport[i]->getCurrentObject(); if (tmp_obj != NULL) { setList[i] = ((coDoSet *)(tmp_obj))->getAllElements(&dummy); } } int real_steps = ((coDoSet *)p_inport[0]->getCurrentObject())->getNumElements(); outobjs = new const coDistributedObject *[real_steps + 1]; outobjs[real_steps] = NULL; int j; for (j = 0; j < real_steps; j++) { // assume all input objects have the same structure int used_ports = time_steps / real_steps; int part_num = 0; const coDistributedObject **parts = new const coDistributedObject *[used_ports + 1]; parts[used_ports] = NULL; for (i = 0; i < NUM_PORTS; i++) { tmp_obj = p_inport[i]->getCurrentObject(); if (tmp_obj != NULL) { parts[part_num++] = setList[i][j]; setList[i][j]->incRefCount(); } } char objname[512]; sprintf(objname, "%s_%d", p_outport->getObjName(), j); outobjs[nume++] = new coDoSet(objname, parts); } if ((p_inport[0]->getCurrentObject())->getAttribute("TIMESTEP")) { time_steps = real_steps; } else //merge of blocks { time_steps = 0; } } } set_output = new coDoSet(p_outport->getObjName(), outobjs); if ((mode != CatBlocks) && (time_steps > 0 || mode == CatTimesteps || mode == SetOfTimesteps || ((p_inport[0]->getCurrentObject())->getAttribute("TIMESTEP") && mode == MergeBlocks))) { // put timestep attribute char buf[16]; sprintf(buf, "1 %d", time_steps); set_output->addAttribute("TIMESTEP", buf); // use p_ForAttributes to add additional attibutes if (p_ForAttributes) { const char **attributes; const char **values; int no_attributes = p_ForAttributes->getAllAttributes(&attributes, &values); int j; // add all attributes but do not repeat TIMESTEP for (j = 0; j < no_attributes; ++j) { if (strcmp("TIMESTEP", attributes[j]) != 0) { set_output->addAttribute(attributes[j], values[j]); } } } } p_outport->setCurrentObject(set_output); delete[] outobjs; return CONTINUE_PIPELINE; } MODULE_MAIN(Tools, BlockCollect)
1
0.555469
1
0.555469
game-dev
MEDIA
0.176767
game-dev
0.841802
1
0.841802
hoangminh5210119/deauther
13,854
lib/SSD1306/src/OLEDDisplayUi.cpp
/** * The MIT License (MIT) * * Copyright (c) 2018 by ThingPulse, Daniel Eichhorn * Copyright (c) 2018 by Fabrice Weinberg * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * ThingPulse invests considerable time and money to develop these open source libraries. * Please support us by buying our products (and not the clones) from * https://thingpulse.com * */ #include "OLEDDisplayUi.h" OLEDDisplayUi::OLEDDisplayUi(OLEDDisplay *display) { this->display = display; } void OLEDDisplayUi::init() { this->display->init(); } void OLEDDisplayUi::setTargetFPS(uint8_t fps){ float oldInterval = this->updateInterval; this->updateInterval = ((float) 1.0 / (float) fps) * 1000; // Calculate new ticksPerFrame float changeRatio = oldInterval / (float) this->updateInterval; this->ticksPerFrame *= changeRatio; this->ticksPerTransition *= changeRatio; } // -/------ Automatic controll ------\- void OLEDDisplayUi::enableAutoTransition(){ this->autoTransition = true; } void OLEDDisplayUi::disableAutoTransition(){ this->autoTransition = false; } void OLEDDisplayUi::setAutoTransitionForwards(){ this->state.frameTransitionDirection = 1; this->lastTransitionDirection = 1; } void OLEDDisplayUi::setAutoTransitionBackwards(){ this->state.frameTransitionDirection = -1; this->lastTransitionDirection = -1; } void OLEDDisplayUi::setTimePerFrame(uint16_t time){ this->ticksPerFrame = (uint16_t) ( (float) time / (float) updateInterval); } void OLEDDisplayUi::setTimePerTransition(uint16_t time){ this->ticksPerTransition = (uint16_t) ( (float) time / (float) updateInterval); } // -/------ Customize indicator position and style -------\- void OLEDDisplayUi::enableIndicator(){ this->state.isIndicatorDrawen = true; } void OLEDDisplayUi::disableIndicator(){ this->state.isIndicatorDrawen = false; } void OLEDDisplayUi::enableAllIndicators(){ this->shouldDrawIndicators = true; } void OLEDDisplayUi::disableAllIndicators(){ this->shouldDrawIndicators = false; } void OLEDDisplayUi::setIndicatorPosition(IndicatorPosition pos) { this->indicatorPosition = pos; } void OLEDDisplayUi::setIndicatorDirection(IndicatorDirection dir) { this->indicatorDirection = dir; } void OLEDDisplayUi::setActiveSymbol(const uint8_t* symbol) { this->activeSymbol = symbol; } void OLEDDisplayUi::setInactiveSymbol(const uint8_t* symbol) { this->inactiveSymbol = symbol; } // -/----- Frame settings -----\- void OLEDDisplayUi::setFrameAnimation(AnimationDirection dir) { this->frameAnimationDirection = dir; } void OLEDDisplayUi::setFrames(FrameCallback* frameFunctions, uint8_t frameCount) { this->frameFunctions = frameFunctions; this->frameCount = frameCount; this->resetState(); } // -/----- Overlays ------\- void OLEDDisplayUi::setOverlays(OverlayCallback* overlayFunctions, uint8_t overlayCount){ this->overlayFunctions = overlayFunctions; this->overlayCount = overlayCount; } // -/----- Loading Process -----\- void OLEDDisplayUi::setLoadingDrawFunction(LoadingDrawFunction loadingDrawFunction) { this->loadingDrawFunction = loadingDrawFunction; } void OLEDDisplayUi::runLoadingProcess(LoadingStage* stages, uint8_t stagesCount) { uint8_t progress = 0; uint8_t increment = 100 / stagesCount; for (uint8_t i = 0; i < stagesCount; i++) { display->clear(); this->loadingDrawFunction(this->display, &stages[i], progress); display->display(); stages[i].callback(); progress += increment; yield(); } display->clear(); this->loadingDrawFunction(this->display, &stages[stagesCount-1], progress); display->display(); delay(150); } // -/----- Manuel control -----\- void OLEDDisplayUi::nextFrame() { if (this->state.frameState != IN_TRANSITION) { this->state.manuelControll = true; this->state.frameState = IN_TRANSITION; this->state.ticksSinceLastStateSwitch = 0; this->lastTransitionDirection = this->state.frameTransitionDirection; this->state.frameTransitionDirection = 1; } } void OLEDDisplayUi::previousFrame() { if (this->state.frameState != IN_TRANSITION) { this->state.manuelControll = true; this->state.frameState = IN_TRANSITION; this->state.ticksSinceLastStateSwitch = 0; this->lastTransitionDirection = this->state.frameTransitionDirection; this->state.frameTransitionDirection = -1; } } void OLEDDisplayUi::switchToFrame(uint8_t frame) { if (frame >= this->frameCount) return; this->state.ticksSinceLastStateSwitch = 0; if (frame == this->state.currentFrame) return; this->state.frameState = FIXED; this->state.currentFrame = frame; this->state.isIndicatorDrawen = true; } void OLEDDisplayUi::transitionToFrame(uint8_t frame) { if (frame >= this->frameCount) return; this->state.ticksSinceLastStateSwitch = 0; if (frame == this->state.currentFrame) return; this->nextFrameNumber = frame; this->lastTransitionDirection = this->state.frameTransitionDirection; this->state.manuelControll = true; this->state.frameState = IN_TRANSITION; this->state.frameTransitionDirection = frame < this->state.currentFrame ? -1 : 1; } // -/----- State information -----\- OLEDDisplayUiState* OLEDDisplayUi::getUiState(){ return &this->state; } int8_t OLEDDisplayUi::update(){ unsigned long frameStart = millis(); int8_t timeBudget = this->updateInterval - (frameStart - this->state.lastUpdate); if ( timeBudget <= 0) { // Implement frame skipping to ensure time budget is keept if (this->autoTransition && this->state.lastUpdate != 0) this->state.ticksSinceLastStateSwitch += ceil(-timeBudget / this->updateInterval); this->state.lastUpdate = frameStart; this->tick(); } return this->updateInterval - (millis() - frameStart); } void OLEDDisplayUi::tick() { this->state.ticksSinceLastStateSwitch++; switch (this->state.frameState) { case IN_TRANSITION: if (this->state.ticksSinceLastStateSwitch >= this->ticksPerTransition){ this->state.frameState = FIXED; this->state.currentFrame = getNextFrameNumber(); this->state.ticksSinceLastStateSwitch = 0; this->nextFrameNumber = -1; } break; case FIXED: // Revert manuelControll if (this->state.manuelControll) { this->state.frameTransitionDirection = this->lastTransitionDirection; this->state.manuelControll = false; } if (this->state.ticksSinceLastStateSwitch >= this->ticksPerFrame){ if (this->autoTransition){ this->state.frameState = IN_TRANSITION; } this->state.ticksSinceLastStateSwitch = 0; } break; } this->display->clear(); this->drawFrame(); if (shouldDrawIndicators) { this->drawIndicator(); } this->drawOverlays(); this->display->display(); } void OLEDDisplayUi::resetState() { this->state.lastUpdate = 0; this->state.ticksSinceLastStateSwitch = 0; this->state.frameState = FIXED; this->state.currentFrame = 0; this->state.isIndicatorDrawen = true; } void OLEDDisplayUi::drawFrame(){ switch (this->state.frameState){ case IN_TRANSITION: { float progress = (float) this->state.ticksSinceLastStateSwitch / (float) this->ticksPerTransition; int16_t x = 0, y = 0, x1 = 0, y1 = 0; switch(this->frameAnimationDirection){ case SLIDE_LEFT: x = -this->display->width() * progress; y = 0; x1 = x + this->display->width(); y1 = 0; break; case SLIDE_RIGHT: x = this->display->width() * progress; y = 0; x1 = x - this->display->width(); y1 = 0; break; case SLIDE_UP: x = 0; y = -this->display->height() * progress; x1 = 0; y1 = y + this->display->height(); break; case SLIDE_DOWN: default: x = 0; y = this->display->height() * progress; x1 = 0; y1 = y - this->display->height(); break; } // Invert animation if direction is reversed. int8_t dir = this->state.frameTransitionDirection >= 0 ? 1 : -1; x *= dir; y *= dir; x1 *= dir; y1 *= dir; bool drawenCurrentFrame; // Prope each frameFunction for the indicator Drawen state this->enableIndicator(); (this->frameFunctions[this->state.currentFrame])(this->display, &this->state, x, y); drawenCurrentFrame = this->state.isIndicatorDrawen; this->enableIndicator(); (this->frameFunctions[this->getNextFrameNumber()])(this->display, &this->state, x1, y1); // Build up the indicatorDrawState if (drawenCurrentFrame && !this->state.isIndicatorDrawen) { // Drawen now but not next this->indicatorDrawState = 2; } else if (!drawenCurrentFrame && this->state.isIndicatorDrawen) { // Not drawen now but next this->indicatorDrawState = 1; } else if (!drawenCurrentFrame && !this->state.isIndicatorDrawen) { // Not drawen in both frames this->indicatorDrawState = 3; } // If the indicator isn't draw in the current frame // reflect it in state.isIndicatorDrawen if (!drawenCurrentFrame) this->state.isIndicatorDrawen = false; break; } case FIXED: // Always assume that the indicator is drawn! // And set indicatorDrawState to "not known yet" this->indicatorDrawState = 0; this->enableIndicator(); (this->frameFunctions[this->state.currentFrame])(this->display, &this->state, 0, 0); break; } } void OLEDDisplayUi::drawIndicator() { // Only draw if the indicator is invisible // for both frames or // the indiactor is shown and we are IN_TRANSITION if (this->indicatorDrawState == 3 || (!this->state.isIndicatorDrawen && this->state.frameState != IN_TRANSITION)) { return; } uint8_t posOfHighlightFrame = 0; float indicatorFadeProgress = 0; // if the indicator needs to be slided in we want to // highlight the next frame in the transition uint8_t frameToHighlight = this->indicatorDrawState == 1 ? this->getNextFrameNumber() : this->state.currentFrame; // Calculate the frame that needs to be highlighted // based on the Direction the indiactor is drawn switch (this->indicatorDirection){ case LEFT_RIGHT: posOfHighlightFrame = frameToHighlight; break; case RIGHT_LEFT: default: posOfHighlightFrame = this->frameCount - frameToHighlight; break; } switch (this->indicatorDrawState) { case 1: // Indicator was not drawn in this frame but will be in next // Slide IN indicatorFadeProgress = 1 - ((float) this->state.ticksSinceLastStateSwitch / (float) this->ticksPerTransition); break; case 2: // Indicator was drawn in this frame but not in next // Slide OUT indicatorFadeProgress = ((float) this->state.ticksSinceLastStateSwitch / (float) this->ticksPerTransition); break; } //Space between indicators - reduce for small screen sizes uint16_t indicatorSpacing = 12; if (this->display->getHeight() < 64 && (this->indicatorPosition == RIGHT || this->indicatorPosition == LEFT)) { indicatorSpacing = 6; } uint16_t frameStartPos = (indicatorSpacing * frameCount / 2); const uint8_t *image; uint16_t x = 0,y = 0; for (byte i = 0; i < this->frameCount; i++) { switch (this->indicatorPosition){ case TOP: y = 0 - (8 * indicatorFadeProgress); x = (this->display->width() / 2) - frameStartPos + 12 * i; break; case BOTTOM: y = (this->display->height() - 8) + (8 * indicatorFadeProgress); x = (this->display->width() / 2) - frameStartPos + 12 * i; break; case RIGHT: x = (this->display->width() - 8) + (8 * indicatorFadeProgress); y = (this->display->height() / 2) - frameStartPos + 2 + 12 * i; break; case LEFT: default: x = 0 - (8 * indicatorFadeProgress); y = (this->display->height() / 2) - frameStartPos + 2 + indicatorSpacing * i; break; } if (posOfHighlightFrame == i) { image = this->activeSymbol; } else { image = this->inactiveSymbol; } this->display->drawFastImage(x, y, 8, 8, image); } } void OLEDDisplayUi::drawOverlays() { for (uint8_t i=0;i<this->overlayCount;i++){ (this->overlayFunctions[i])(this->display, &this->state); } } uint8_t OLEDDisplayUi::getNextFrameNumber(){ if (this->nextFrameNumber != -1) return this->nextFrameNumber; return (this->state.currentFrame + this->frameCount + this->state.frameTransitionDirection) % this->frameCount; }
1
0.963333
1
0.963333
game-dev
MEDIA
0.61546
game-dev
0.990685
1
0.990685
Vek17/TabletopTweaks-Base
49,365
TabletopTweaks-Base/MechanicsChanges/DRRework.cs
using HarmonyLib; using Kingmaker; using Kingmaker.Blueprints; using Kingmaker.Blueprints.Classes; using Kingmaker.Blueprints.Facts; using Kingmaker.Blueprints.Items.Equipment; using Kingmaker.Blueprints.JsonSystem; using Kingmaker.Blueprints.Root; using Kingmaker.Designers.Mechanics.Buffs; using Kingmaker.ElementsSystem; using Kingmaker.EntitySystem; using Kingmaker.EntitySystem.Entities; using Kingmaker.Enums.Damage; using Kingmaker.Items; using Kingmaker.RuleSystem; using Kingmaker.RuleSystem.Rules.Damage; using Kingmaker.Tutorial; using Kingmaker.Tutorial.Solvers; using Kingmaker.Tutorial.Triggers; using Kingmaker.UI.Common; using Kingmaker.UI.MVVM._VM.ServiceWindows.CharacterInfo.Sections.Martial.DamageReduction; using Kingmaker.UI.MVVM._VM.ServiceWindows.CharacterInfo.Sections.Martial.EnergyResistance; using Kingmaker.UI.MVVM._VM.Tooltip.Templates; using Kingmaker.UI.ServiceWindow.CharacterScreen; using Kingmaker.UI.Tooltip; using Kingmaker.UnitLogic; using Kingmaker.UnitLogic.Abilities.Blueprints; using Kingmaker.UnitLogic.Buffs.Blueprints; using Kingmaker.UnitLogic.FactLogic; using Kingmaker.UnitLogic.Mechanics.Actions; using Kingmaker.UnitLogic.Mechanics.Components; using Kingmaker.UnitLogic.Mechanics.Properties; using Kingmaker.Utility; using Kingmaker.Utility.UnitDescription; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Reflection.Emit; using TabletopTweaks.Core.NewComponents.OwlcatReplacements.DamageResistance; using TabletopTweaks.Core.NewComponents.Prerequisites; using TabletopTweaks.Core.NewUnitParts; using TabletopTweaks.Core.Utilities; using static TabletopTweaks.Base.Main; namespace TabletopTweaks.Base.MechanicsChanges { internal class DRRework { [HarmonyPatch(typeof(AddDamageResistancePhysical), nameof(AddDamageResistancePhysical.IsStackable), MethodType.Getter)] static class AddDamageResistancePhysical_IsStackable_Patch { static void Postfix(ref bool __result) { if (Main.TTTContext.Fixes.BaseFixes.IsEnabled("DamageReductionRework")) { __result = false; } } } #if DEBUG [HarmonyPatch(typeof(AddDamageResistanceBase.ComponentRuntime), nameof(AddDamageResistanceBase.ComponentRuntime.OnTurnOn))] static class AddDamageResistanceBase_OnTurnOn_LogPatch { static bool Prefix(AddDamageResistanceBase.ComponentRuntime __instance) { if (Main.TTTContext.Fixes.BaseFixes.IsEnabled("DamageReductionRework")) { TTTContext.Logger.LogVerbose($"WARNING: Vanilla Damage Resistance turned on for fact: {__instance.Fact.Blueprint.AssetGuid} - {__instance.Fact.Blueprint.NameSafe()}"); } return true; } } #endif [HarmonyPatch(typeof(BlueprintFact), nameof(BlueprintFact.CollectComponents))] static class BlueprintFact_CollectComponents_Patch { static void Postfix(ref List<BlueprintComponent> __result) { if (Main.TTTContext.Fixes.BaseFixes.IsDisabled("DamageReductionRework")) { return; } for (int i = 0; i < __result.Count; i++) { BlueprintComponent component = __result[i]; if (component is AddDamageResistanceBase resistanceComponent) { TTAddDamageResistanceBase replacementComponent = CreateFromVanillaDamageResistance(resistanceComponent); // https://c.tenor.com/eqLNYv0A9TQAAAAC/swap-indiana-jones.gif __result[i] = replacementComponent; TTTContext.Logger.LogVerbose("Replaced " + resistanceComponent.GetType().ToString() + " with " + replacementComponent.GetType().ToString()); } } } static TTAddDamageResistanceBase CreateFromVanillaDamageResistance(AddDamageResistanceBase vanillaResistance) { TTAddDamageResistanceBase result = null; switch (vanillaResistance) { case ResistEnergy: result = Helpers.Create<TTResistEnergy>(); break; case ResistEnergyContext: result = Helpers.Create<TTResistEnergyContext>(); break; case ProtectionFromEnergy: result = Helpers.Create<TTProtectionFromEnergy>(); break; case WizardAbjurationResistance: result = Helpers.Create<TTWizardAbjurationResistance>(); break; case WizardEnergyAbsorption: result = Helpers.Create<TTWizardEnergyAbsorption>(); break; case AddDamageResistancePhysical: result = Helpers.Create<TTAddDamageResistancePhysical>(); break; case AddDamageResistanceEnergy: result = Helpers.Create<TTAddDamageResistanceEnergy>(); break; case AddDamageResistanceForce: result = Helpers.Create<TTAddDamageResistanceForce>(); break; case AddDamageResistanceHardness: result = Helpers.Create<TTAddDamageResistanceHardness>(); break; default: TTTContext.Logger.Log("ERROR: Called CreateFromVanillaDamageResistance for unsupported type: " + vanillaResistance.GetType().ToString()); return null; } result.InitFromVanillaDamageResistance(vanillaResistance); return result; } } [HarmonyPatch(typeof(ReduceDamageReduction), nameof(ReduceDamageReduction.OnTurnOn))] static class ReduceDamageReduction_OnTurnOn_Patch { static bool Prefix(ReduceDamageReduction __instance) { if (Main.TTTContext.Fixes.BaseFixes.IsDisabled("DamageReductionRework")) { return true; } int penalty = __instance.Value.Calculate(__instance.Context) * __instance.Multiplier; __instance.Owner.Ensure<TTUnitPartDamageReduction>().AddPenaltyEntry(penalty, __instance.Fact); return false; } } [HarmonyPatch(typeof(ReduceDamageReduction), nameof(ReduceDamageReduction.OnTurnOff))] static class ReduceDamageReduction_OnTurnOff_Patch { static bool Prefix(ReduceDamageReduction __instance) { if (Main.TTTContext.Fixes.BaseFixes.IsDisabled("DamageReductionRework")) { return true; } __instance.Owner.Ensure<TTUnitPartDamageReduction>().RemovePenaltyEntry(__instance.Fact); return false; } } [HarmonyPatch(typeof(CharInfoDamageReductionVM), nameof(CharInfoDamageReductionVM.GetDamageReduction))] static class CharInfoDamageReductionVM_GetDamageReduction_Patch { static void Postfix(CharInfoDamageReductionVM __instance, UnitDescriptor unit, ref List<CharInfoDamageReductionEntryVM> __result) { if (Main.TTTContext.Fixes.BaseFixes.IsDisabled("DamageReductionRework")) { return; } List<CharInfoDamageReductionEntryVM> reductionEntryVmList = new List<CharInfoDamageReductionEntryVM>(); IEnumerable<TTUnitPartDamageReduction.ReductionDisplay> allSources = unit.Get<TTUnitPartDamageReduction>()?.AllSources; LocalizedTexts ls = Game.Instance.BlueprintRoot.LocalizedTexts; foreach (TTUnitPartDamageReduction.ReductionDisplay reduction in allSources.EmptyIfNull()) { if (reduction.ReferenceDamageResistance is TTAddDamageResistancePhysical settings1) { CharInfoDamageReductionEntryVM reductionEntryVm = new CharInfoDamageReductionEntryVM() { Value = reduction.TotalReduction.ToString() }; if (settings1.BypassedByAlignment) reductionEntryVm.Exceptions.Add(ls.DamageAlignment.GetTextFlags(settings1.Alignment)); if (settings1.BypassedByForm) reductionEntryVm.Exceptions.AddRange(settings1.Form.Components().Select<PhysicalDamageForm, string>(f => ls.DamageForm.GetText(f))); if (settings1.BypassedByMagic) reductionEntryVm.Exceptions.Add(Game.Instance.BlueprintRoot.LocalizedTexts.UserInterfacesText.CharacterSheet.MagicDRDescriptor); if (settings1.BypassedByMaterial) reductionEntryVm.Exceptions.Add(ls.DamageMaterial.GetTextFlags(settings1.Material)); if (settings1.BypassedByReality) reductionEntryVm.Exceptions.Add(ls.DamageReality.GetText(settings1.Reality)); if (settings1.BypassedByMeleeWeapon) reductionEntryVm.Exceptions.Add(Game.Instance.BlueprintRoot.LocalizedTexts.UserInterfacesText.CharacterSheet.MeleeDRDescriptor); if (settings1.BypassedByWeaponType) reductionEntryVm.Exceptions.Add(settings1.WeaponType.TypeName); if (reductionEntryVm.Exceptions.Count == 0) reductionEntryVm.Exceptions.Add("-"); reductionEntryVmList.Add(reductionEntryVm); } } __result = reductionEntryVmList; } } [HarmonyPatch(typeof(CharInfoEnergyResistanceVM), nameof(CharInfoEnergyResistanceVM.GetEnergyResistance))] static class CharInfoEnergyResistanceVM_GetEnergyResistance_Patch { static bool Prefix(CharInfoEnergyResistanceVM __instance, UnitDescriptor unit, ref List<CharInfoEnergyResistanceEntryVM> __result) { if (Main.TTTContext.Fixes.BaseFixes.IsDisabled("DamageReductionRework")) { return true; } IEnumerable<BlueprintComponentAndRuntime<TTAddDamageResistanceEnergy>> componentAndRuntimes = unit.Facts.List.SelectMany(i => i.SelectComponentsWithRuntime<TTAddDamageResistanceEnergy>()); LocalizedTexts localizedTexts = Game.Instance.BlueprintRoot.LocalizedTexts; Dictionary<DamageEnergyType, CharInfoEnergyResistanceEntryVM> dictionary = new Dictionary<DamageEnergyType, CharInfoEnergyResistanceEntryVM>(); foreach (BlueprintComponentAndRuntime<TTAddDamageResistanceEnergy> componentAndRuntime in componentAndRuntimes) { TTAddDamageResistanceBase.ComponentRuntime runtime = (TTAddDamageResistanceBase.ComponentRuntime)componentAndRuntime.Runtime; CharInfoEnergyResistanceEntryVM resistanceEntryVm = new CharInfoEnergyResistanceEntryVM() { Value = runtime.GetValue(), Type = localizedTexts.DamageEnergy.GetText(componentAndRuntime.Component.Type) }; if (!dictionary.ContainsKey(componentAndRuntime.Component.Type) || dictionary[componentAndRuntime.Component.Type].Value < resistanceEntryVm.Value) dictionary[componentAndRuntime.Component.Type] = resistanceEntryVm; } __result = dictionary.Values.ToList(); return false; } /*static void Postfix(CharInfoEnergyResistanceVM __instance, UnitDescriptor unit, ref List<CharInfoEnergyResistanceEntryVM> __result) { if (Context.Fixes.BaseFixes.IsDisabled("DamageReductionRework")) { return; } List<CharInfoEnergyResistanceEntryVM> resistanceEntryVMList = new List<CharInfoEnergyResistanceEntryVM>(); LocalizedTexts localizedTexts = Game.Instance.BlueprintRoot.LocalizedTexts; foreach (TTUnitPartDamageReduction.ReductionDisplay reduction in unit.Get<TTUnitPartDamageReduction>()?.AllSources?.EmptyIfNull().OrderByDescending(rd => rd.ReferenceDamageResistance?.Priority ?? TTAddDamageResistanceBase.DRPriority.Normal)) { if (reduction.ReferenceDamageResistance is TTAddDamageResistanceEnergy settings1) { CharInfoEnergyResistanceEntryVM resistanceEntryVM = new CharInfoEnergyResistanceEntryVM() { Value = reduction.TotalReduction, Type = localizedTexts.DamageEnergy.GetText(settings1.Type) }; resistanceEntryVMList.Add(resistanceEntryVM); } } __result = resistanceEntryVMList; }*/ } [HarmonyPatch(typeof(CharSMartial), nameof(CharSMartial.GetDamageReduction))] static class CharSMartial_GetDamageReduction_Patch { static void Postfix(CharSMartial __instance, UnitDescriptor unit, ref List<CharSMartial.DRdata> __result) { if (Main.TTTContext.Fixes.BaseFixes.IsDisabled("DamageReductionRework")) { return; } List<CharSMartial.DRdata> drdataList = new List<CharSMartial.DRdata>(); TTUnitPartDamageReduction partDamageReduction = unit.Get<TTUnitPartDamageReduction>(); IEnumerable<TTUnitPartDamageReduction.ReductionDisplay> list = partDamageReduction != null ? partDamageReduction.AllSources.Where(c => c.ReferenceDamageResistance is TTAddDamageResistancePhysical) : null; LocalizedTexts ls = Game.Instance.BlueprintRoot.LocalizedTexts; foreach (TTUnitPartDamageReduction.ReductionDisplay reduction in list.EmptyIfNull()) { TTAddDamageResistancePhysical settings = (TTAddDamageResistancePhysical)reduction.ReferenceDamageResistance; CharSMartial.DRdata drdata = new CharSMartial.DRdata(); drdata.value = reduction.TotalReduction.ToString(); if (settings.BypassedByAlignment) drdata.exceptions.Add(ls.DamageAlignment.GetTextFlags(settings.Alignment)); if (settings.BypassedByForm) drdata.exceptions.AddRange(settings.Form.Components().Select<PhysicalDamageForm, string>(f => ls.DamageForm.GetText(f))); if (settings.BypassedByMagic) drdata.exceptions.Add(Game.Instance.BlueprintRoot.LocalizedTexts.UserInterfacesText.CharacterSheet.MagicDRDescriptor); if (settings.BypassedByMaterial) drdata.exceptions.Add(ls.DamageMaterial.GetTextFlags(settings.Material)); if (settings.BypassedByReality) drdata.exceptions.Add(ls.DamageReality.GetText(settings.Reality)); if (settings.BypassedByMeleeWeapon) drdata.exceptions.Add(Game.Instance.BlueprintRoot.LocalizedTexts.UserInterfacesText.CharacterSheet.MeleeDRDescriptor); if (settings.BypassedByWeaponType) drdata.exceptions.Add(settings.WeaponType.TypeName); if (drdata.exceptions.Count == 0) drdata.exceptions.Add("-"); drdataList.Add(drdata); } __result = drdataList; } } [HarmonyPatch(typeof(CharSMartial), nameof(CharSMartial.GetEnergyResistance))] static class CharSMartial_GetEnergyResistance_Patch { static void Postfix(CharSMartial __instance, UnitDescriptor unit, List<CharSMartial.ERdata> __result) { if (Main.TTTContext.Fixes.BaseFixes.IsDisabled("DamageReductionRework")) { return; } List<CharSMartial.ERdata> erdataList = new List<CharSMartial.ERdata>(); LocalizedTexts localizedTexts = Game.Instance.BlueprintRoot.LocalizedTexts; foreach (TTUnitPartDamageReduction.ReductionDisplay reduction in unit.Get<TTUnitPartDamageReduction>()?.AllSources?.EmptyIfNull().OrderByDescending(rd => rd.ReferenceDamageResistance?.Priority ?? TTAddDamageResistanceBase.DRPriority.Normal)) { if (reduction.ReferenceDamageResistance is TTAddDamageResistanceEnergy settings1) { CharSMartial.ERdata erdata = new CharSMartial.ERdata(); erdata.value = reduction.TotalReduction.ToString(); erdata.type = localizedTexts.DamageEnergy.GetText(settings1.Type); erdataList.Add(erdata); } } __result = erdataList; } } [HarmonyPatch(typeof(TutorialTriggerDamageReduction), nameof(TutorialTriggerDamageReduction.ShouldTrigger))] static class TutorialTriggerDamageReduction_ShouldTrigger_Patch { static void Postfix(TutorialTriggerDamageReduction __instance, RuleDealDamage rule, ref bool __result) { if (Main.TTTContext.Fixes.BaseFixes.IsDisabled("DamageReductionRework")) { return; } if (!__result && !rule.IgnoreDamageReduction) { TTUnitPartDamageReduction partDamageReduction = rule.Target.Get<TTUnitPartDamageReduction>(); if (partDamageReduction != null && rule.ResultList != null && __instance.AbsoluteDR == partDamageReduction.HasAbsolutePhysicalDR) { foreach (DamageValue res in rule.ResultList) { if (res.Source is PhysicalDamage && res.Reduction > 0) { __result = true; return; } } } } } } [HarmonyPatch(typeof(AddEnergyImmunity), nameof(AddEnergyImmunity.OnTurnOn))] static class AddEnergyImmunity_OnTurnOn_Patch { static bool Prefix(AddEnergyImmunity __instance) { if (Main.TTTContext.Fixes.BaseFixes.IsDisabled("DamageReductionRework")) { return true; } __instance.Owner.Ensure<TTUnitPartDamageReduction>().AddImmunity(__instance.Fact, __instance, __instance.Type); return false; } } [HarmonyPatch(typeof(AddEnergyImmunity), nameof(AddEnergyImmunity.OnTurnOff))] static class AddEnergyImmunity_OnTurnOff_Patch { static bool Prefix(AddEnergyImmunity __instance) { if (Main.TTTContext.Fixes.BaseFixes.IsDisabled("DamageReductionRework")) { return true; } __instance.Owner.Get<TTUnitPartDamageReduction>()?.RemoveImmunity(__instance.Fact, __instance); return false; } } [HarmonyPatch(typeof(TutorialSolverSpellWithDamage), nameof(TutorialSolverSpellWithDamage.GetBasePriority))] static class TutorialSolverSpellWithDamage_GetBasePriority_Patch { static void Postfix(TutorialSolverSpellWithDamage __instance, BlueprintAbility ability, UnitEntityData caster, ref int __result) { if (Main.TTTContext.Fixes.BaseFixes.IsDisabled("DamageReductionRework")) { return; } if (__result != -1) { TTUnitPartDamageReduction partDamageReduction = ContextData<TutorialContext>.Current.TargetUnit.Get<TTUnitPartDamageReduction>(); if (partDamageReduction != null) { foreach (Element elements in ability.ElementsArray) { if (elements is ContextActionDealDamage actionDealDamage) { if (actionDealDamage.DamageType.Type == DamageType.Energy && partDamageReduction.IsImmune(actionDealDamage.DamageType.Energy)) { __result = -1; return; } BaseDamage damage = actionDealDamage.DamageType.CreateDamage(DiceFormula.Zero, 0); if (!partDamageReduction.CanBypass(damage, null)) { __result = -1; return; } } } } } } } [HarmonyPatch] //[HarmonyDebug] static class UIUtilityItem_Patches { static IEnumerable<MethodBase> TargetMethods() { yield return AccessTools.Method( typeof(UIUtilityItem), nameof(UIUtilityItem.FillShieldEnchantments), new Type[] { typeof(ItemTooltipData), typeof(ItemEntityShield), typeof(string) }); yield return AccessTools.Method( typeof(UIUtilityItem), nameof(UIUtilityItem.FillShieldEnchantments), new Type[] { typeof(TooltipData), typeof(ItemEntityShield), typeof(string) }); yield return AccessTools.Method( typeof(UIUtilityItem), nameof(UIUtilityItem.FillArmorEnchantments), new Type[] { typeof(ItemTooltipData), typeof(ItemEntityArmor), typeof(string) }); yield return AccessTools.Method( typeof(UIUtilityItem), nameof(UIUtilityItem.FillArmorEnchantments), new Type[] { typeof(TooltipData), typeof(ItemEntityArmor), typeof(string) }); } private static Dictionary<Type, Type> _typeMapping = new Dictionary<Type, Type>() { { typeof(AddDamageResistanceEnergy), typeof(TTAddDamageResistanceEnergy) }, { typeof(BlueprintComponentAndRuntime<AddDamageResistanceEnergy>), typeof(BlueprintComponentAndRuntime<TTAddDamageResistanceEnergy>) }, { typeof(AddDamageResistanceBase.ComponentRuntime), typeof(TTAddDamageResistanceBase.ComponentRuntime) } }; private static Dictionary<MethodInfo, MethodInfo> _staticCallMapping = new Dictionary<MethodInfo, MethodInfo> { { AccessTools.Method(typeof(UIUtilityItem), nameof(UIUtilityItem.GetEnergyResistanceText)), AccessTools.Method(typeof(UIUtilityItem_Patches), nameof(UIUtilityItem_Patches.TTGetEnergyResistanceText)) } }; static IEnumerable<CodeInstruction> Transpiler(MethodBase original, IEnumerable<CodeInstruction> codes, ILGenerator il) { return new TypeReplaceTranspiler(_typeMapping, _staticCallMapping).Transpiler(original, codes, il); } private static string TTGetEnergyResistanceText(TTAddDamageResistanceBase.ComponentRuntime damageEnergyResist) { return damageEnergyResist == null ? "" : "+" + damageEnergyResist.GetValue(); } } [HarmonyPatch(typeof(UnitDescriptionHelper), nameof(UnitDescriptionHelper.ExtractDamageReductions))] static class UnitDescriptionHelper_ExtractDamageReductions_Patch { static bool Prefix(UnitEntityData unit, ref UnitDescription.DamageReduction[] __result) { if (Main.TTTContext.Fixes.BaseFixes.IsDisabled("DamageReductionRework")) { return true; } List<UnitDescription.DamageReduction> result = new List<UnitDescription.DamageReduction>(); unit.VisitComponents<TTAddDamageResistancePhysical>((c, f) => result.Add(TTExtractDamageReduction(c, f))); __result = result.ToArray(); return false; } static UnitDescription.DamageReduction TTExtractDamageReduction( TTAddDamageResistancePhysical dr, EntityFact fact) { TTAddDamageResistanceBase.ComponentRuntime componentRuntime = (TTAddDamageResistanceBase.ComponentRuntime)fact.Components.First(c => c.SourceBlueprintComponent == dr && c.SourceBlueprintComponentName == dr.name); return new UnitDescription.DamageReduction() { Or = dr.Or, Value = componentRuntime.GetValue(), BypassedByMaterial = dr.BypassedByMaterial, Material = dr.Material, BypassedByForm = dr.BypassedByForm, Form = dr.Form, BypassedByMagic = dr.BypassedByMagic, MinEnhancementBonus = dr.MinEnhancementBonus, BypassedByAlignment = dr.BypassedByAlignment, Alignment = dr.Alignment, BypassedByReality = dr.BypassedByReality, Reality = dr.Reality, BypassedByWeapon = dr.BypassedByWeaponType ? dr.WeaponType : null, BypassedByMeleeWeapon = dr.BypassedByMeleeWeapon }; } } [HarmonyPatch(typeof(UnitDescriptionHelper), nameof(UnitDescriptionHelper.ExtractEnergyResistances))] static class UnitDescriptionHelper_ExtractEnergyResistances_Patch { static bool Prefix(UnitEntityData unit, ref UnitDescription.EnergyResistanceData[] __result) { if (Main.TTTContext.Fixes.BaseFixes.IsDisabled("DamageReductionRework")) { return true; } List<UnitDescription.EnergyResistanceData> result = new List<UnitDescription.EnergyResistanceData>(); unit.VisitComponents<TTAddDamageResistanceEnergy>((c, f) => result.Add(TTExtractEnergyResistance(c, f))); __result = result.ToArray(); return false; } static UnitDescription.EnergyResistanceData TTExtractEnergyResistance( TTAddDamageResistanceEnergy er, EntityFact fact) { TTAddDamageResistanceBase.ComponentRuntime componentRuntime = (TTAddDamageResistanceBase.ComponentRuntime)fact.Components.First(c => c.SourceBlueprintComponent == er && c.SourceBlueprintComponentName == er.name); return new UnitDescription.EnergyResistanceData() { Value = componentRuntime.GetValue(), Energy = er.Type }; } } [HarmonyPatch(typeof(BlueprintsCache), "Init")] static class BlueprintsCache_Init_Patch { static bool Initialized; [HarmonyPriority(Priority.Last)] static void Postfix() { if (Initialized) return; Initialized = true; if (Main.TTTContext.Fixes.BaseFixes.IsDisabled("DamageReductionRework")) { return; } TTTContext.Logger.LogHeader("Patching Blueprints for DR Rework"); PatchArmorDR(); PatchStalwartDefender(); PatchBarbariansDR(); PatchWildEffigyDR(); PatchInevitableFateDR(); PatchLichIndestructibleBonesDR(); PatchAngelUnbrokenDR(); PatchAspectOfOmoxDR(); PatchBrokenDRSettings(); PatchArmorMastery(); PatchArmoredJuggernaut(); PatchThroneKeeper(); PatchMythicArmorFocus(); } static void PatchArmorDR() { BlueprintUnitFact[] armorFactsWithPhysicalDR = new BlueprintUnitFact[] { BlueprintTools.GetBlueprint<BlueprintFeature>("e93a376547629e2478d6f50e5f162efb"), // AdamantineArmorLightFeature BlueprintTools.GetBlueprint<BlueprintFeature>("74a80c42774045f4d916dc0d990b7738"), // AdamantineArmorMediumFeature BlueprintTools.GetBlueprint<BlueprintFeature>("dbbf704bfcc78854ab149597ef9aae7c"), // AdamantineArmorHeavyFeature BlueprintTools.GetBlueprint<BlueprintFeature>("b99c50dd771a36d4f913bf1f56ba77a2"), // ArmorOfWealthFeature BlueprintTools.GetBlueprint<BlueprintFeature>("a8ea2027afa333246a86b8085c23fbfd"), // BeaconOfCarnageFeature BlueprintTools.GetBlueprint<BlueprintBuff>("42ab909d597f1734cb9bf65a74db7424"), // BeaconOfCarnageEffectBuff BlueprintTools.GetBlueprint<BlueprintFeature>("06d2f00616ad40c3b136d06dffc8f0b5"), // ColorlessRemainsBreastplate_SolidFeature BlueprintTools.GetBlueprint<BlueprintFeature>("ff2d26e87b5f2bc4ba1823e242f10890"), // ForMounted_HalfplateOfSynergyFeature BlueprintTools.GetBlueprint<BlueprintFeature>("e19008b823a221043b9184ef3c271db1"), // RealmProtectorFeature BlueprintTools.GetBlueprint<BlueprintFeature>("79babe38a7306ba4c81f2fa3c88d1bae"), // StuddedArmorOfTrinityFeature BlueprintTools.GetBlueprint<BlueprintFeature>("8c7de3b7d51a4b49a46990d8dbc84853") // ThroneKeeperFeature }; foreach (BlueprintUnitFact armorBlueprint in armorFactsWithPhysicalDR) { armorBlueprint.ConvertVanillaDamageResistanceToRework<AddDamageResistancePhysical, TTAddDamageResistancePhysical>(TTTContext, newRes => { newRes.SourceIsArmor = true; }); } } static void PatchBarbariansDR() { BlueprintFeature barbarianDR = BlueprintTools.GetBlueprint<BlueprintFeature>("cffb5cddefab30140ac133699d52a8f8"); BlueprintFeature invulnerableRagerDR = BlueprintTools.GetBlueprint<BlueprintFeature>("e71bd204a2579b1438ebdfbf75aeefae"); BlueprintFeature madDogMasterDamageReduction = BlueprintTools.GetBlueprint<BlueprintFeature>("a0d4a3295224b8f4387464a4447c31d5"); BlueprintFeature madDogPetDamageReduction = BlueprintTools.GetBlueprint<BlueprintFeature>("2edbf059fd033974bbff67960f15974d"); BlueprintFeature bloodragerDR = BlueprintTools.GetBlueprint<BlueprintFeature>("07eba4bb72c2e3845bb442dce85d3b58"); BlueprintFeature skaldDR = BlueprintTools.GetBlueprint<BlueprintFeature>("d9446a35d1401cf418bb9b5e0e199d57"); BlueprintFeature increasedDamageReductionRagePower = BlueprintTools.GetBlueprint<BlueprintFeature>("ddaee203ee4dcb24c880d633fbd77db6"); BlueprintBuff manglingFrenzyBuff = BlueprintTools.GetBlueprint<BlueprintBuff>("1581c5ceea24418cadc9f26ce4d391a9"); barbarianDR.ConvertVanillaDamageResistanceToRework<AddDamageResistancePhysical, TTAddDamageResistancePhysical>(TTTContext, newRes => { newRes.SourceIsClassFeature = true; }); invulnerableRagerDR.ConvertVanillaDamageResistanceToRework<AddDamageResistancePhysical, TTAddDamageResistancePhysical>(TTTContext, newRes => { newRes.SourceIsClassFeature = true; }); madDogMasterDamageReduction.ConvertVanillaDamageResistanceToRework<AddDamageResistancePhysical, TTAddDamageResistancePhysical>(TTTContext, newRes => { newRes.SourceIsClassFeature = true; }); bloodragerDR.ConvertVanillaDamageResistanceToRework<AddDamageResistancePhysical, TTAddDamageResistancePhysical>(TTTContext, newRes => { newRes.SourceIsClassFeature = true; }); skaldDR.ConvertVanillaDamageResistanceToRework<AddDamageResistancePhysical, TTAddDamageResistancePhysical>(TTTContext, newRes => { newRes.SourceIsClassFeature = true; }); // Fix Skald DR not increasing with Increased Damage ResistanCce Rage Power ContextRankConfig barbarianDRConfig = barbarianDR.GetComponent<ContextRankConfig>(); ContextRankConfig skaldDRRankConfig = Helpers.CreateCopy(barbarianDRConfig, crc => { crc.m_FeatureList = new BlueprintFeatureReference[] { skaldDR.ToReference<BlueprintFeatureReference>(), increasedDamageReductionRagePower.ToReference<BlueprintFeatureReference>(), increasedDamageReductionRagePower.ToReference<BlueprintFeatureReference>() }; }); skaldDR.RemoveComponents<ContextRankConfig>(); skaldDR.AddComponent(skaldDRRankConfig); TTTContext.Logger.Log($"Patched: ContextRankConfig on {skaldDR.AssetGuid} - {skaldDR.NameSafe()}"); // Allow Mangling Frenzy to stack with Barbarian DR's manglingFrenzyBuff.ConvertVanillaDamageResistanceToRework<AddDamageResistancePhysical, TTAddDamageResistancePhysical>(TTTContext, newRes => { newRes.StacksWithFacts = new BlueprintUnitFactReference[] { barbarianDR.ToReference<BlueprintUnitFactReference>(), invulnerableRagerDR.ToReference<BlueprintUnitFactReference>(), madDogMasterDamageReduction.ToReference<BlueprintUnitFactReference>(), madDogPetDamageReduction.ToReference<BlueprintUnitFactReference>(), bloodragerDR.ToReference<BlueprintUnitFactReference>(), skaldDR.ToReference<BlueprintUnitFactReference>() }; }); // Fix Bloodrager (Primalist) DR not being increased by the Improved Damage Reduction rage power bloodragerDR.AddComponent(Helpers.CreateContextRankConfig(crc => { crc.m_BaseValueType = ContextRankBaseValueType.FeatureListRanks; crc.m_FeatureList = new BlueprintFeatureReference[] { bloodragerDR.ToReference<BlueprintFeatureReference>(), increasedDamageReductionRagePower.ToReference<BlueprintFeatureReference>(), increasedDamageReductionRagePower.ToReference<BlueprintFeatureReference>() }; })); // Fix Mad Dog's pet DR not being improved by master's Increased Damage Resistance Rage Power(s) BlueprintUnitProperty madDogPetDRProperty = BlueprintTools.GetModBlueprint<BlueprintUnitProperty>(TTTContext, "MadDogPetDRProperty"); madDogPetDamageReduction.ConvertVanillaDamageResistanceToRework<AddDamageResistancePhysical, TTAddDamageResistancePhysical>(TTTContext, newRes => { newRes.SourceIsClassFeature = true; }); madDogPetDamageReduction.RemoveComponents<ContextRankConfig>(); madDogPetDamageReduction.AddContextRankConfig(c => { c.m_BaseValueType = ContextRankBaseValueType.CustomProperty; c.m_CustomProperty = madDogPetDRProperty.ToReference<BlueprintUnitPropertyReference>(); }); // Fix Increased Damage Reduction Rage Power not checking if the character actual has the DamageReduction class feature increasedDamageReductionRagePower.AddComponent<PrerequisiteFeaturesFromListFormatted>(p => { p.m_Features = new BlueprintFeatureReference[] { barbarianDR.ToReference<BlueprintFeatureReference>(), invulnerableRagerDR.ToReference<BlueprintFeatureReference>(), madDogMasterDamageReduction.ToReference<BlueprintFeatureReference>(), bloodragerDR.ToReference<BlueprintFeatureReference>(), skaldDR.ToReference<BlueprintFeatureReference>() }; p.Amount = 1; }); } static void PatchWildEffigyDR() { var ArmorPlatingShifterBuff = BlueprintTools.GetBlueprint<BlueprintBuff>("b00fbc84b7ae4a45883c0ac8bb070db6"); ArmorPlatingShifterBuff.ConvertVanillaDamageResistanceToRework<AddDamageResistancePhysical, TTAddDamageResistancePhysical>(TTTContext, newRes => { newRes.SourceIsClassFeature = true; }); } static void PatchStalwartDefender() { BlueprintFeature stalwartDefenderDamageReductionFeature = BlueprintTools.GetBlueprint<BlueprintFeature>("4d4f48f401d5d8b408c2e7a973fba9ea"); stalwartDefenderDamageReductionFeature.ConvertVanillaDamageResistanceToRework<AddDamageResistancePhysical, TTAddDamageResistancePhysical>(TTTContext, newRes => { newRes.SourceIsClassFeature = true; newRes.IsIncreasedByArmor = true; }); BlueprintFeature increasedDamageReductionDefensivePower = BlueprintTools.GetBlueprint<BlueprintFeature>("d10496e92d0799a40bb3930b8f4fda0d"); increasedDamageReductionDefensivePower.ConvertVanillaDamageResistanceToRework<AddDamageResistancePhysical, TTAddDamageResistancePhysical>(TTTContext, newRes => { newRes.SourceIsClassFeature = true; newRes.IncreasesFacts = new BlueprintUnitFactReference[] { stalwartDefenderDamageReductionFeature.ToReference<BlueprintUnitFactReference>() }; }); } static void PatchLichIndestructibleBonesDR() { var lichIndestructibleBonesFeature = BlueprintTools.GetBlueprint<BlueprintFeature>("42274a4428cb43b40acf771a7f5ddfac"); lichIndestructibleBonesFeature.ConvertVanillaDamageResistanceToRework<AddDamageResistancePhysical, TTAddDamageResistancePhysical>(TTTContext, newRes => { newRes.AddToAllStacks = true; }); } static void PatchMythicArmorFocus() { var ArmorFocusHeavyMythicFeatureVar1Buff = BlueprintTools.GetBlueprint<BlueprintBuff>("af7a83e16d1442cb87e84f879bf2141b"); ArmorFocusHeavyMythicFeatureVar1Buff.ConvertVanillaDamageResistanceToRework<AddDamageResistancePhysical, TTAddDamageResistancePhysical>(TTTContext, newRes => { newRes.AddToAllStacks = true; }); } static void PatchInevitableFateDR() { var MythicPowersFromDLC1EffectBuff = BlueprintTools.GetBlueprint<BlueprintBuff>("08eba577806847ac9a814694013f7783"); MythicPowersFromDLC1EffectBuff.ConvertVanillaDamageResistanceToRework<AddDamageResistancePhysical, TTAddDamageResistancePhysical>(TTTContext, newRes => { newRes.AddToAllStacks = true; }); } static void PatchAngelUnbrokenDR() { BlueprintBuff AngelUnbrokenEffectBuff = BlueprintTools.GetBlueprint<BlueprintBuff>("2249da3de0da48f19bc205de2d7fc97f"); AngelUnbrokenEffectBuff.ConvertVanillaDamageResistanceToRework<AddDamageResistancePhysical, TTAddDamageResistancePhysical>(TTTContext, newRes => { newRes.AddToAllStacks = true; }); } static void PatchAspectOfOmoxDR() { BlueprintFeature OmoxAspectFeature = BlueprintTools.GetBlueprint<BlueprintFeature>("daf030c7563b2664eb1031d91eaae7ab"); OmoxAspectFeature.ConvertVanillaDamageResistanceToRework<AddDamageResistancePhysical, TTAddDamageResistancePhysical>(TTTContext, newRes => { newRes.AddToAllStacks = true; }); } static void PatchBrokenDRSettings() { // Fix: Winter Oracle Ice Armor revelation should be DR 5/piercing, but is DR 5/- due to missing BypassedByForm flag BlueprintBuff oracleRevelationIceArmorDRBuff = BlueprintTools.GetBlueprint<BlueprintBuff>("448e35444e80e24438a5ad0a3114aee3"); oracleRevelationIceArmorDRBuff.ConvertVanillaDamageResistanceToRework<AddDamageResistancePhysical, TTAddDamageResistancePhysical>(TTTContext, newRes => { newRes.BypassedByForm = true; }); // Fix: Bruiser's Chainshirt DR should be DR 3/piercing, but is DR 3/- due to missing BypassedByForm flag BlueprintFeature bruisersChainshirtFeature = BlueprintTools.GetBlueprint<BlueprintFeature>("2f08e4d39c1c568478c43aba81c42525"); bruisersChainshirtFeature.ConvertVanillaDamageResistanceToRework<AddDamageResistancePhysical, TTAddDamageResistancePhysical>(TTTContext, newRes => { newRes.BypassedByForm = true; }); // Fix: Warden of Darkness (Tower Shield) should be DR 5/good, but was DR 5/- BlueprintFeature towerShieldWardenOfDarknessShieldFeature = BlueprintTools.GetBlueprint<BlueprintFeature>("4211cdbf0bf04a540a366ba1d1c7dcc2"); towerShieldWardenOfDarknessShieldFeature.ConvertVanillaDamageResistanceToRework<AddDamageResistancePhysical, TTAddDamageResistancePhysical>(TTTContext, newRes => { newRes.BypassedByAlignment = true; }); // Fix: Artifact_AzataCloakEnchantment should stack with existing DR var Artifact_AzataCloakItem = BlueprintTools.GetBlueprint<BlueprintItemEquipmentShoulders>("78cd50deada655e4cbe49765c0bbb7e4"); Artifact_AzataCloakItem.m_DescriptionText = Helpers.CreateString(TTTContext, $"{Artifact_AzataCloakItem.name}.key", "Azata shares a bond with her dragon. 50% damage is redirected to Aivu. " + "In addition, Aivu gets additional DR N/Lawful where N is equal to Azata's mythic rank."); BlueprintFeature Artifact_AzataCloakPetFeature = BlueprintTools.GetBlueprint<BlueprintFeature>("af6f1ca38fe54e5baf67adfb9b731ae8"); Artifact_AzataCloakPetFeature.TemporaryContext(bp => { bp.ConvertVanillaDamageResistanceToRework<AddDamageResistancePhysical, TTAddDamageResistancePhysical>(TTTContext, newRes => { newRes.Alignment = DamageAlignment.Lawful; newRes.BypassedByAlignment = true; newRes.Value = new Kingmaker.UnitLogic.Mechanics.ContextValue() { ValueType = Kingmaker.UnitLogic.Mechanics.ContextValueType.Rank, }; }); bp.AddContextRankConfig(c => { c.m_BaseValueType = ContextRankBaseValueType.MasterMythicLevel; c.m_Progression = ContextRankProgression.AsIs; }); }); // Fix: DragonAzataFeatureTierII should be DR 5/lawful, but was DR 5/- BlueprintFeature DragonAzataFeatureTierII = BlueprintTools.GetBlueprint<BlueprintFeature>("fc2aeb954e13811488d38dc1af72ef9c"); DragonAzataFeatureTierII.ConvertVanillaDamageResistanceToRework<AddDamageResistancePhysical, TTAddDamageResistancePhysical>(TTTContext, newRes => { newRes.BypassedByAlignment = true; newRes.IncreasedByFacts = new BlueprintUnitFactReference[] { Artifact_AzataCloakPetFeature.ToReference<BlueprintUnitFactReference>() }; }); // Fix: DragonAzataFeatureTierIII should be DR 15/lawful, but was DR 15/- BlueprintFeature DragonAzataFeatureTierIII = BlueprintTools.GetBlueprint<BlueprintFeature>("fd8c12d3c29189d4c81d88ee6aaba636"); DragonAzataFeatureTierIII.ConvertVanillaDamageResistanceToRework<AddDamageResistancePhysical, TTAddDamageResistancePhysical>(TTTContext, newRes => { newRes.BypassedByAlignment = true; newRes.IncreasedByFacts = new BlueprintUnitFactReference[] { Artifact_AzataCloakPetFeature.ToReference<BlueprintUnitFactReference>() }; }); // Fix: DragonAzataFeatureTierIV should be DR 20/lawful, but was DR 20/- BlueprintFeature DragonAzataFeatureTierIV = BlueprintTools.GetBlueprint<BlueprintFeature>("ee1bac8c71df3f9408bad5ca3a19eb23"); DragonAzataFeatureTierIV.ConvertVanillaDamageResistanceToRework<AddDamageResistancePhysical, TTAddDamageResistancePhysical>(TTTContext, newRes => { newRes.BypassedByAlignment = true; newRes.IncreasedByFacts = new BlueprintUnitFactReference[] { Artifact_AzataCloakPetFeature.ToReference<BlueprintUnitFactReference>() }; }); } static void PatchArmorMastery() { BlueprintBuff armorMasteryBuff = BlueprintTools.GetBlueprint<BlueprintBuff>("0794e96a6c5da8f41979d809bb4a9a8c"); armorMasteryBuff.ConvertVanillaDamageResistanceToRework<AddDamageResistancePhysical, TTAddDamageResistancePhysical>(TTTContext, newRes => { newRes.SourceIsClassFeature = true; }); } static void PatchArmoredJuggernaut() { BlueprintFeature armoredJuggernautFeature = BlueprintTools.GetBlueprint<BlueprintFeature>(Main.TTTContext.Blueprints.GetGUID("ArmoredJuggernautFeature")); BlueprintUnitFactReference[] adamantineArmorFeatures = new BlueprintUnitFactReference[] { BlueprintTools.GetBlueprint<BlueprintFeature>("e93a376547629e2478d6f50e5f162efb").ToReference<BlueprintUnitFactReference>(), // AdamantineArmorLightFeature BlueprintTools.GetBlueprint<BlueprintFeature>("74a80c42774045f4d916dc0d990b7738").ToReference<BlueprintUnitFactReference>(), // AdamantineArmorMediumFeature BlueprintTools.GetBlueprint<BlueprintFeature>("dbbf704bfcc78854ab149597ef9aae7c").ToReference<BlueprintUnitFactReference>(), // AdamantineArmorHeavyFeature }; BlueprintUnitFactReference armorMasteryBuff = BlueprintTools.GetBlueprint<BlueprintBuff>("0794e96a6c5da8f41979d809bb4a9a8c").ToReference<BlueprintUnitFactReference>(); armoredJuggernautFeature.ConvertVanillaDamageResistanceToRework<AddDamageResistancePhysical, TTAddDamageResistancePhysical>(TTTContext, newRes => { newRes.SourceIsClassFeature = true; newRes.StacksWithFacts = adamantineArmorFeatures; newRes.IncreasedByFacts = new BlueprintUnitFactReference[] { armorMasteryBuff }; }); armoredJuggernautFeature.SetDescription(TTTContext, "When wearing heavy armor, the fighter gains DR 1/—. At 7th level, the fighter gains DR 1/— when wearing medium armor, " + "and DR 2/— when wearing heavy armor. At 11th level, the fighter gains DR 1/— when wearing light armor, DR 2/— when wearing medium armor, " + "and DR 3/— when wearing heavy armor. If the fighter is 19th level and has the armor mastery class feature, these DR values increase by 5. " + "The DR from this ability stacks with that provided by adamantine armor, but not with other forms of damage reduction."); } static void PatchThroneKeeper() { var ThroneKeeperFeature = BlueprintTools.GetBlueprint<BlueprintFeature>("8c7de3b7d51a4b49a46990d8dbc84853"); // ThroneKeeperFeature BlueprintUnitFactReference[] adamantineArmorFeatures = new BlueprintUnitFactReference[] { BlueprintTools.GetBlueprint<BlueprintFeature>("e93a376547629e2478d6f50e5f162efb").ToReference<BlueprintUnitFactReference>(), // AdamantineArmorLightFeature BlueprintTools.GetBlueprint<BlueprintFeature>("74a80c42774045f4d916dc0d990b7738").ToReference<BlueprintUnitFactReference>(), // AdamantineArmorMediumFeature BlueprintTools.GetBlueprint<BlueprintFeature>("dbbf704bfcc78854ab149597ef9aae7c").ToReference<BlueprintUnitFactReference>(), // AdamantineArmorHeavyFeature }; BlueprintUnitFactReference armorMasteryBuff = BlueprintTools.GetBlueprint<BlueprintBuff>("0794e96a6c5da8f41979d809bb4a9a8c").ToReference<BlueprintUnitFactReference>(); adamantineArmorFeatures.ForEach(feature => { var component = feature.Get().GetComponent<TTAddDamageResistancePhysical>(); if (component) { component.IncreasedByFacts = component.IncreasedByFacts.AppendToArray(ThroneKeeperFeature.ToReference<BlueprintUnitFactReference>()); } }); ThroneKeeperFeature.TemporaryContext(bp => { bp.GetComponent<TTAddDamageResistancePhysical>().Value = 7; bp.AddComponent<AddFacts>(c => { c.m_Facts = new BlueprintUnitFactReference[] { BlueprintTools.GetBlueprintReference<BlueprintUnitFactReference>("dbbf704bfcc78854ab149597ef9aae7c") }; }); }); } } } }
1
0.765617
1
0.765617
game-dev
MEDIA
0.912476
game-dev
0.971803
1
0.971803
Vineflower/vineflower
4,377
testData/obfuscated/n.java
import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; public class n<F, S> { private F a; private S b; public static boolean c; private static final String d; public n() { } public n(F var1) { this.a = var1; } public n(F var1, S var2) { this.a = var1; this.b = var2; } public F a() { return this.a; } public void a(F var1) { this.a = var1; } public S b() { return this.b; } public void b(S var1) { this.b = var1; } public boolean equals(Object param1) { // $VF: Couldn't be decompiled } private boolean a(Object param1, Object param2) { // $VF: Couldn't be decompiled } public String toString() { return this.a + d + this.b; } public int hashCode() { Object var10000; label28: { try { if (this.a == null) { var10000 = ""; break label28; } } catch (a_ var2) { throw var2; } var10000 = this.a; } Object var10001; int var3; try { var3 = var10000.hashCode() / 2; if (this.b == null) { var10001 = ""; return var3 + var10001.hashCode() / 2; } } catch (a_ var1) { throw var1; } var10001 = this.b; return var3 + var10001.hashCode() / 2; } public static <T extends n<K, V>, K, V> List<K> a(Collection<T> var0) { ArrayList var1 = new ArrayList(var0.size()); Iterator var2 = var0.iterator(); while(var2.hasNext()) { n var3 = (n)var2.next(); var1.add(var3.a()); } return var1; } public static <T extends n<K, V>, K, V> List<V> b(Collection<T> param0) { // $VF: Couldn't be decompiled } public static <K, V> List<n<K, V>> a(Map<K, V> var0) { boolean var4 = c; ArrayList var1 = new ArrayList(var0.size()); Iterator var2 = var0.entrySet().iterator(); ArrayList var10000; while(true) { if (var2.hasNext()) { Entry var3 = (Entry)var2.next(); try { var10000 = var1; if (var4) { break; } var1.add(new n(var3.getKey(), var3.getValue())); if (!var4) { continue; } } catch (a_ var6) { throw var6; } int var5 = ap.c; ++var5; ap.c = var5; } var10000 = var1; break; } return var10000; } public static <K, V> Map<K, V> c(Collection<n<K, V>> var0) { HashMap var1 = new HashMap(); Iterator var2 = var0.iterator(); while(var2.hasNext()) { n var3 = (n)var2.next(); var1.put(var3.a(), var3.b()); } return var1; } static { char[] var10000 = "p\u001c".toCharArray(); int var10002 = var10000.length; int var1 = 0; char[] var10001 = var10000; int var2 = var10002; int var10003; char[] var4; if (var10002 <= 1) { var4 = var10000; var10003 = var1; } else { var10001 = var10000; var2 = var10002; if (var10002 <= var1) { d = (new String(var10000)).intern(); return; } var4 = var10000; var10003 = var1; } while(true) { char var10004 = var4[var10003]; byte var10005; switch(var1 % 5) { case 0: var10005 = 74; break; case 1: var10005 = 60; break; case 2: var10005 = 116; break; case 3: var10005 = 28; break; default: var10005 = 38; } var4[var10003] = (char)(var10004 ^ var10005); ++var1; if (var2 == 0) { var10003 = var2; var4 = var10001; } else { if (var2 <= var1) { d = (new String(var10001)).intern(); return; } var4 = var10001; var10003 = var1; } } } }
1
0.619699
1
0.619699
game-dev
MEDIA
0.310493
game-dev
0.765828
1
0.765828
arpg/Gazebo
5,282
gazebo/physics/Contact.cc
/* * Copyright (C) 2012-2014 Open Source Robotics Foundation * * 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. * */ /* Desc: Specification of a contact * Author: Nate Koenig * Date: 10 Nov 2009 */ #include "gazebo/physics/physics.hh" #include "gazebo/physics/Collision.hh" #include "gazebo/physics/Contact.hh" using namespace gazebo; using namespace physics; ////////////////////////////////////////////////// Contact::Contact() { this->count = 0; } ////////////////////////////////////////////////// Contact::Contact(const Contact &_c) { *this = _c; } ////////////////////////////////////////////////// Contact::~Contact() { } ////////////////////////////////////////////////// Contact &Contact::operator =(const Contact &_contact) { this->world = _contact.world; this->collision1 = _contact.collision1; this->collision2 = _contact.collision2; this->count = _contact.count; for (int i = 0; i < MAX_CONTACT_JOINTS; i++) { this->wrench[i] = _contact.wrench[i]; this->positions[i] = _contact.positions[i]; this->normals[i] = _contact.normals[i]; this->depths[i] = _contact.depths[i]; } this->time = _contact.time; return *this; } ////////////////////////////////////////////////// Contact &Contact::operator =(const msgs::Contact &_contact) { this->count = 0; this->world = physics::get_world(_contact.world()); if (world) { this->collision1 = boost::dynamic_pointer_cast<Collision>( this->world->GetEntity(_contact.collision1())).get(); this->collision2 = boost::dynamic_pointer_cast<Collision>( this->world->GetEntity(_contact.collision2())).get(); } else { gzwarn << "World: " << _contact.world() << " not found," << "contact collision pointers will be NULL"; } for (int j = 0; j < _contact.position_size(); ++j) { this->positions[j] = msgs::Convert(_contact.position(j)); this->normals[j] = msgs::Convert(_contact.normal(j)); this->depths[j] = _contact.depth(j); this->wrench[j].body1Force = msgs::Convert(_contact.wrench(j).body_1_wrench().force()); this->wrench[j].body2Force = msgs::Convert(_contact.wrench(j).body_2_wrench().force()); this->wrench[j].body1Torque = msgs::Convert(_contact.wrench(j).body_1_wrench().torque()); this->wrench[j].body2Torque = msgs::Convert(_contact.wrench(j).body_2_wrench().torque()); this->count++; } this->time = msgs::Convert(_contact.time()); return *this; } ////////////////////////////////////////////////// void Contact::Reset() { this->count = 0; } ////////////////////////////////////////////////// std::string Contact::DebugString() const { std::ostringstream stream; stream << "World [" << this->world->GetName() << "]\n" << "Collision 1[" << this->collision1->GetScopedName() << "]\n" << "Collision 2[" << this->collision2->GetScopedName() << "]\n" << "Time[" << this->time << "]\n" << "Contact Count[" << this->count << "]\n"; for (int i = 0; i < this->count; ++i) { stream << "--- Contact[" << i << "]\n"; stream << " Depth[" << this->depths[i] << "]\n" << " Position[" << this->positions[i] << "]\n" << " Normal[" << this->normals[i] << "]\n" << " Force1[" << this->wrench[i].body1Force << "]\n" << " Force2[" << this->wrench[i].body2Force << "]\n" << " Torque1[" << this->wrench[i].body1Torque << "]\n" << " Torque2[" << this->wrench[i].body2Torque << "]\n"; } return stream.str(); } ////////////////////////////////////////////////// void Contact::FillMsg(msgs::Contact &_msg) const { _msg.set_world(this->world->GetName()); _msg.set_collision1(this->collision1->GetScopedName()); _msg.set_collision2(this->collision2->GetScopedName()); msgs::Set(_msg.mutable_time(), this->time); for (int j = 0; j < this->count; ++j) { _msg.add_depth(this->depths[j]); msgs::Set(_msg.add_position(), this->positions[j]); msgs::Set(_msg.add_normal(), this->normals[j]); msgs::JointWrench *jntWrench = _msg.add_wrench(); jntWrench->set_body_1_name(this->collision1->GetScopedName()); jntWrench->set_body_1_id(this->collision1->GetId()); jntWrench->set_body_2_name(this->collision2->GetScopedName()); jntWrench->set_body_2_id(this->collision2->GetId()); msgs::Wrench *wrenchMsg = jntWrench->mutable_body_1_wrench(); msgs::Set(wrenchMsg->mutable_force(), this->wrench[j].body1Force); msgs::Set(wrenchMsg->mutable_torque(), this->wrench[j].body1Torque); wrenchMsg = jntWrench->mutable_body_2_wrench(); msgs::Set(wrenchMsg->mutable_force(), this->wrench[j].body2Force); msgs::Set(wrenchMsg->mutable_torque(), this->wrench[j].body2Torque); } }
1
0.93013
1
0.93013
game-dev
MEDIA
0.688553
game-dev
0.899812
1
0.899812
BlueLightJapan/BlueLight
4,779
src/pocketmine/entity/FishingHook.php
<?php /* * * _____ _____ __ _ _ _____ __ __ _____ * / ___| | ____| | \ | | | | / ___/ \ \ / / / ___/ * | | | |__ | \| | | | | |___ \ \/ / | |___ * | | _ | __| | |\ | | | \___ \ \ / \___ \ * | |_| | | |___ | | \ | | | ___| | / / ___| | * \_____/ |_____| |_| \_| |_| /_____/ /_/ /_____/ * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * @author iTX Technologies * @link https://itxtech.org * */ namespace pocketmine\entity; use pocketmine\event\player\PlayerFishEvent; use pocketmine\level\Level; use pocketmine\nbt\tag\CompoundTag; use pocketmine\Player; use pocketmine\item\Item as ItemItem; use pocketmine\network\mcpe\protocol\EntityEventPacket; use pocketmine\network\mcpe\protocol\AddEntityPacket; use pocketmine\Server; class FishingHook extends Projectile{ const NETWORK_ID = 77; public $width = 0.25; public $length = 0.25; public $height = 0.25; protected $gravity = 0.1; protected $drag = 0.05; public $data = 0; public $attractTimer = 100; public $coughtTimer = 0; public $damageRod = false; public function initEntity(){ parent::initEntity(); if(isset($this->namedtag->Data)){ $this->data = $this->namedtag["Data"]; } } public function __construct(Level $level, CompoundTag $nbt, Entity $shootingEntity = null){ parent::__construct($level, $nbt, $shootingEntity); } public function setData($id){ $this->data = $id; } public function getData(){ return $this->data; } public function onUpdate(int $currentTick) : bool{ if($this->closed){ return false; } $this->timings->startTiming(); $hasUpdate = parent::onUpdate($currentTick); if($this->isCollidedVertically && $this->isInsideOfWater()){ $this->motionX = 0; $this->motionY += 0.01; $this->motionZ = 0; $this->motionChanged = true; $hasUpdate = true; }elseif($this->isCollided && $this->keepMovement === true){ $this->motionX = 0; $this->motionY = 0; $this->motionZ = 0; $this->motionChanged = true; $this->keepMovement = false; $hasUpdate = true; } if($this->attractTimer === 0 && mt_rand(0, 100) <= 30){ // chance, that a fish bites $this->coughtTimer = mt_rand(5, 10) * 20; // random delay to catch fish $this->attractTimer = mt_rand(30, 100) * 20; // reset timer $this->attractFish(); if($this->shootingEntity instanceof Player) $this->shootingEntity->sendTip("A fish bites!"); }elseif($this->attractTimer > 0){ $this->attractTimer--; } if($this->coughtTimer > 0){ $this->coughtTimer--; $this->fishBites(); } $this->timings->stopTiming(); return $hasUpdate; } public function fishBites(){ if($this->shootingEntity instanceof Player){ $pk = new EntityEventPacket(); $pk->entityRuntimeId = $this->shootingEntity->getId();//$this or $this->shootingEntity $pk->event = EntityEventPacket::FISH_HOOK_HOOK; Server::broadcastPacket($this->shootingEntity->hasSpawned, $pk); } } public function attractFish(){ if($this->shootingEntity instanceof Player){ $pk = new EntityEventPacket(); $pk->entityRuntimeId = $this->shootingEntity->getId();//$this or $this->shootingEntity $pk->event = EntityEventPacket::FISH_HOOK_BUBBLE; Server::broadcastPacket($this->shootingEntity->hasSpawned, $pk); } } public function reelLine(){ $this->damageRod = false; if($this->shootingEntity instanceof Player && $this->coughtTimer > 0){ $fishes = [ItemItem::RAW_FISH, ItemItem::RAW_SALMON, ItemItem::CLOWN_FISH, ItemItem::PUFFER_FISH]; $fish = array_rand($fishes, 1); $item = ItemItem::get($fishes[$fish]); $this->getLevel()->getServer()->getPluginManager()->callEvent($ev = new PlayerFishEvent($this->shootingEntity, $item, $this)); if(!$ev->isCancelled()){ $this->shootingEntity->getInventory()->addItem($item); $this->shootingEntity->addExperience(mt_rand(1, 6)); $this->damageRod = true; } } if($this->shootingEntity instanceof Player){ $this->shootingEntity->unlinkHookFromPlayer(); } if(!$this->closed){ $this->kill(); $this->close(); } return $this->damageRod; } public function spawnTo(Player $player){ $pk = new AddEntityPacket(); $pk->entityRuntimeId = $this->getId(); $pk->type = FishingHook::NETWORK_ID; $pk->position = $this->asVector3(); $pk->speedX = $this->motionX; $pk->speedY = $this->motionY; $pk->speedZ = $this->motionZ; $pk->yaw = $this->yaw; $pk->pitch = $this->pitch; $pk->metadata = $this->dataProperties; $player->dataPacket($pk); parent::spawnTo($player); } }
1
0.932157
1
0.932157
game-dev
MEDIA
0.956312
game-dev
0.970465
1
0.970465
bes2008/easyjson
9,254
jettison-to-easyjson/src/main/java/org/codehaus/jettison/mapped/MappedXMLStreamReader.java
/** * Copyright 2006 Envoi Solutions LLC * * 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.codehaus.jettison.mapped; import java.util.Set; import javax.xml.namespace.NamespaceContext; import javax.xml.stream.XMLStreamException; import org.codehaus.jettison.AbstractXMLStreamReader; import org.codehaus.jettison.Node; import org.codehaus.jettison.json.JSONArray; import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; import org.codehaus.jettison.util.FastStack; public class MappedXMLStreamReader extends AbstractXMLStreamReader { private FastStack nodes; private String currentValue; private MappedNamespaceConvention convention; private String valueKey = "$"; private NamespaceContext ctx; private int popArrayNodes; public MappedXMLStreamReader(JSONObject obj) throws JSONException, XMLStreamException { this(obj, new MappedNamespaceConvention()); } public MappedXMLStreamReader(JSONObject obj, MappedNamespaceConvention con) throws JSONException, XMLStreamException { String rootName = (String) obj.keys().next(); this.convention = con; this.nodes = new FastStack(); this.ctx = con; Object top = obj.get(rootName); if (top instanceof JSONObject) { this.node = new Node(null, rootName, (JSONObject)top, convention); } else if (top instanceof JSONArray && !(((JSONArray)top).length() == 1 && ((JSONArray)top).get(0).equals(""))) { this.node = new Node(null, rootName, obj, convention); } else { node = new Node(rootName, convention); convention.processAttributesAndNamespaces(node, obj); currentValue = JSONObject.NULL.equals(top) ? null : top.toString(); } nodes.push(node); event = START_DOCUMENT; } public int next() throws XMLStreamException { if (event == START_DOCUMENT) { event = START_ELEMENT; } else if (event == CHARACTERS) { event = END_ELEMENT; node = (Node) nodes.pop(); currentValue = null; } else if (event == START_ELEMENT || event == END_ELEMENT) { if (event == END_ELEMENT && nodes.size() > 0) { node = (Node) nodes.peek(); if (popArrayNodes > 0) { nodes.pop(); if (node.getArray() != null) { popArrayNodes--; event = END_ELEMENT; return event; } } } if (currentValue != null) { event = CHARACTERS; } else if ((node.getKeys() != null && node.getKeys().hasNext()) || node.getArray() != null) { processElement(); } else { if (nodes.size() > 0) { event = END_ELEMENT; node = (Node) nodes.pop(); } else { event = END_DOCUMENT; } } } // handle value in nodes with attributes if (nodes.size() > 0) { Node next = (Node)nodes.peek(); if (event == START_ELEMENT && next.getName().getLocalPart().equals(valueKey)) { event = CHARACTERS; node = (Node)nodes.pop(); } } return event; } private void processElement() throws XMLStreamException { try { Object newObj = null; String nextKey = null; if (node.getArray() != null) { int index = node.getArrayIndex(); if (index >= node.getArray().length()) { nodes.pop(); node = (Node) nodes.peek(); if (node == null) { event = END_DOCUMENT; return; } if ((node.getKeys() != null && node.getKeys().hasNext()) || node.getArray() != null) { if (popArrayNodes > 0) { node = (Node) nodes.pop(); } processElement(); } else { event = END_ELEMENT; node = (Node) nodes.pop(); } return; } newObj = node.getArray().get(index++); nextKey = node.getName().getLocalPart(); if (!"".equals(node.getName().getNamespaceURI())) { nextKey = this.convention.getPrefix(node.getName().getNamespaceURI()) + this.getConvention().getNamespaceSeparator() + nextKey; } node.setArrayIndex(index); } else { nextKey = (String) node.getKeys().next(); newObj = node.getObject().get(nextKey); } if (newObj instanceof String) { node = new Node(nextKey, convention); nodes.push(node); currentValue = (String) newObj; event = START_ELEMENT; return; } else if (newObj instanceof JSONArray) { JSONArray array = (JSONArray) newObj; if (!processUniformArrayIfPossible(nextKey, array)) { node = new Node(nextKey, convention); node.setArray(array); node.setArrayIndex(0); nodes.push(node); processElement(); } return; } else if (newObj instanceof JSONObject) { node = new Node((Node)nodes.peek(), nextKey, (JSONObject) newObj, convention); nodes.push(node); event = START_ELEMENT; return; } else { node = new Node(nextKey, convention); nodes.push(node); currentValue = JSONObject.NULL.equals(newObj) ? null : newObj.toString(); event = START_ELEMENT; return; } } catch (JSONException e) { throw new XMLStreamException(e); } } private boolean processUniformArrayIfPossible(String arrayKey, JSONArray array) throws JSONException, XMLStreamException { if (!isAvoidArraySpecificEvents(arrayKey)) { return false; } int arrayLength = array.length(); int depth = 0; String lastKey = null; int parentIndex = nodes.size(); boolean isRoot = ((Node)nodes.get(0)).getName().getLocalPart().equals(arrayKey); Node parent = !isRoot ? new Node(arrayKey, convention) : node; for (int i = arrayLength - 1; i >= 0; i--) { Object object = array.get(i); if (object instanceof JSONObject) { JSONObject jsonObject = (JSONObject)object; // lets limit to single key JSONObjects for now if (jsonObject.length() == 1) { String theKey = jsonObject.keys().next().toString(); if (lastKey == null || lastKey.equals(theKey)) { lastKey = theKey; depth++; Node theNode = new Node(parent, theKey, jsonObject, convention); nodes.push(theNode); } else { lastKey = null; break; } } } } if (lastKey == null) { for (int i = 0; i < depth; i++) { nodes.pop(); } return false; } parent.setArray(array); parent.setArrayIndex(arrayLength); if (!isRoot) { nodes.add(parentIndex, parent); nodes.push(parent); node = parent; event = START_ELEMENT; } else { node = (Node)nodes.pop(); processElement(); } popArrayNodes++; return true; } public void close() throws XMLStreamException { } public String getElementText() throws XMLStreamException { event = CHARACTERS; return currentValue; } public NamespaceContext getNamespaceContext() { return ctx; } public String getText() { if (currentValue != null && "null".equals(currentValue) && !convention.isReadNullAsString()) { return null; } return currentValue; } public void setValueKey(String valueKey) { this.valueKey = valueKey; } public boolean isAvoidArraySpecificEvents(String key) { Set<?> keys = convention.getPrimitiveArrayKeys(); return keys != null && keys.contains(key); } public MappedNamespaceConvention getConvention() { return convention; } }
1
0.874222
1
0.874222
game-dev
MEDIA
0.129136
game-dev
0.958196
1
0.958196
OpenNefia/OpenNefia
1,553
OpenNefia.Content/Maps/MapGenUtils.cs
using OpenNefia.Core.Maths; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OpenNefia.Content.Maps { public static class MapGenUtils { public static IEnumerable<Vector2i> EnumerateBorder(UIBox2i bounds) { var start = bounds.TopLeft; var end = bounds.BottomRight; var pos = start; while (pos.Y <= end.Y) { yield return pos; if (pos.Y == start.Y || pos.Y == end.Y - 1) { if (pos.X == end.X - 1) { pos.X = start.X; pos.Y++; } else { pos.X++; } } else { if (pos.X == start.X) { pos.X = end.X - 1; } else { pos.X = start.X; pos.Y++; } } } } public static IEnumerable<Vector2i> EnumerateBounds(UIBox2i bounds) { for (var x = bounds.Left; x < bounds.Right; x++) { for (var y = bounds.Top; y < bounds.Bottom; y++) { yield return (x, y); } } } } }
1
0.72191
1
0.72191
game-dev
MEDIA
0.465947
game-dev
0.90101
1
0.90101
magefree/mage
2,716
Mage/src/main/java/mage/abilities/effects/common/continuous/BecomesColorSourceEffect.java
package mage.abilities.effects.common.continuous; import mage.MageObject; import mage.ObjectColor; import mage.abilities.Ability; import mage.abilities.Mode; import mage.abilities.effects.ContinuousEffectImpl; import mage.choices.ChoiceColor; import mage.constants.Duration; import mage.constants.Layer; import mage.constants.Outcome; import mage.constants.SubLayer; import mage.game.Game; import mage.players.Player; /** * @author LoneFox */ public class BecomesColorSourceEffect extends ContinuousEffectImpl { private ObjectColor setColor; public BecomesColorSourceEffect(Duration duration) { this(null, duration); } public BecomesColorSourceEffect(ObjectColor setColor, Duration duration) { super(duration, Layer.ColorChangingEffects_5, SubLayer.NA, Outcome.Benefit); this.setColor = setColor; } protected BecomesColorSourceEffect(final BecomesColorSourceEffect effect) { super(effect); this.setColor = effect.setColor; } @Override public BecomesColorSourceEffect copy() { return new BecomesColorSourceEffect(this); } @Override public void init(Ability source, Game game) { super.init(source, game); Player controller = game.getPlayer(source.getControllerId()); if (controller == null) { discard(); return; } if (setColor == null) { ChoiceColor choice = new ChoiceColor(); if (!controller.choose(Outcome.PutManaInPool, choice, game)) { discard(); return; } setColor = choice.getColor(); if (!game.isSimulation()) { game.informPlayers(controller.getLogName() + " has chosen the color: " + setColor.toString()); } } } @Override public boolean apply(Game game, Ability source) { Player controller = game.getPlayer(source.getControllerId()); if (controller == null) { return false; } if (setColor != null) { MageObject sourceObject = game.getObject(source); if (sourceObject != null) { sourceObject.getColor(game).setColor(setColor); } else { this.discard(); } return true; } return false; } @Override public String getText(Mode mode) { if (staticText != null && !staticText.isEmpty()) { return staticText; } return "{this} becomes " + (setColor == null ? "the color of your choice" : setColor.getDescription()) + (duration.toString().isEmpty() ? "" : " " + duration.toString()); } }
1
0.741494
1
0.741494
game-dev
MEDIA
0.658388
game-dev,desktop-app
0.979353
1
0.979353
MergHQ/CRYENGINE
16,881
Code/GameSDK/GameDll/Turret/Turret/ProceduralContextTurretAimPose.cpp
// Copyright 2001-2016 Crytek GmbH / Crytek Group. All rights reserved. #include "StdAfx.h" #include "ProceduralContextTurretAimPose.h" #include "TurretHelpers.h" CRYREGISTER_CLASS( CProceduralContextTurretAimPose ); #define DEFAULT_HORIZONTAL_AIM_LAYER 4 #define DEFAULT_VERTICAL_AIM_LAYER ( DEFAULT_HORIZONTAL_AIM_LAYER + 1 ) #define DEFAULT_CHARACTER_SLOT 0 #define HARDCODED_WEAPON_JOINT_NAME "weaponjoint" #define HARDCODED_HORIZONTAL_AIM_JOINT_NAME "arcjoint" #define HARDCODED_AIMPOSES_ORIGIN_JOINT_NAME "weaponjoint_ref" #define ABS_PITCH_LIMIT_RADIANS ( DEG2RAD( 89 ) ) #define YAW_THRESHOLD_RADIANS ( DEG2RAD( 10 ) ) namespace { float ClampValueDelta( const float value, const float targetValue, const float absMaxDeltaValue ) { const float deltaValue = targetValue - value; const float absDeltaValue = abs( deltaValue ); const float absClampedDeltaValue = min( absMaxDeltaValue, absDeltaValue ); const float signDeltaValue = ( 0 <= deltaValue ) ? 1.0f : -1.0f; const float clampedDeltaValue = signDeltaValue * absClampedDeltaValue; const float clampedValue = value + clampedDeltaValue; return clampedValue; } float VelocityClampValue( const float value, const float targetValue, const float velocity, const float elapsedSeconds ) { assert( 0 <= velocity ); assert( 0 <= elapsedSeconds ); const float absMaxDeltaValue = velocity * elapsedSeconds; const float clampedValue = ClampValueDelta( value, targetValue, absMaxDeltaValue ); return clampedValue; } } CProceduralContextTurretAimPose::CProceduralContextTurretAimPose() : m_pCharacterInstance( NULL ) , m_pSkeletonAnim( NULL ) , m_pSkeletonPose( NULL ) , m_pIDefaultSkeleton( NULL ) , m_pVerticalAim( NULL ) , m_horizontalAimLayer( DEFAULT_HORIZONTAL_AIM_LAYER ) , m_verticalAimLayer( DEFAULT_VERTICAL_AIM_LAYER ) , m_horizontalAimSmoothTime( 0 ) , m_verticalAimSmoothTime( 0 ) , m_maxYawDegreesPerSecond( 0 ) , m_maxPitchDegreesPerSecond( 0 ) , m_horizontalAimJointId( -1 ) , m_weaponJointId( -1 ) , m_aimPosesOriginJointId( -1 ) , m_targetMinDistanceClamp( 0 ) , m_minDistanceClampHeight( 0 ) , m_requestedTurretOrientation( STurretOrientation() ) , m_smoothedTargetWorldPosition( 0, 0, 0 ) , m_pitchRadians( 0 ) , m_yawRadians( 0 ) , m_invertedWorldTM( IDENTITY ) { } CProceduralContextTurretAimPose::~CProceduralContextTurretAimPose() { } void CProceduralContextTurretAimPose::Initialise( IEntity& entity, IActionController& actionController ) { IProceduralContext::Initialise( entity, actionController ); const Matrix34& worldTM = m_entity->GetWorldTM(); m_invertedWorldTM = worldTM.GetInverted(); const bool initialiseCharacterSuccess = InitialiseCharacter( DEFAULT_CHARACTER_SLOT ); if ( ! initialiseCharacterSuccess ) { CryWarning( VALIDATOR_MODULE_GAME, VALIDATOR_WARNING, "ProceduralContext TurretAimPose: Could not initialise character in slot '%d' for entity with name '%s'.", DEFAULT_CHARACTER_SLOT, entity.GetName() ); return; } InitialiseHorizontalAim(); InitialiseVerticalAim(); SetWeaponJointName( HARDCODED_WEAPON_JOINT_NAME ); SetHorizontalAimJointName( HARDCODED_HORIZONTAL_AIM_JOINT_NAME ); SetAimPosesOriginJointName( HARDCODED_AIMPOSES_ORIGIN_JOINT_NAME ); m_smoothedTargetWorldPosition = m_entity->GetWorldPos() + m_entity->GetForwardDir(); } void CProceduralContextTurretAimPose::Update( float timePassedSeconds ) { if ( m_pSkeletonAnim == NULL || m_pSkeletonPose == NULL ) { return; } const Matrix34& worldTM = m_entity->GetWorldTM(); m_invertedWorldTM = worldTM.GetInverted(); UpdateSmoothedTargetWorldPosition( timePassedSeconds ); const Vec3& targetWorldPosition = m_smoothedTargetWorldPosition; const Vec3 targetLocalPosition = m_invertedWorldTM * targetWorldPosition; UpdateHorizontalAim( targetLocalPosition, timePassedSeconds ); UpdateVerticalAim( targetWorldPosition, timePassedSeconds ); UpdateFallbackAim( targetLocalPosition ); } float CProceduralContextTurretAimPose::VelocityClampYaw( const float yaw, const float targetYaw, const float threshold, const float velocity, const float elapsedSeconds ) { using namespace TurretHelpers; assert( -gf_PI <= yaw ); assert( yaw <= gf_PI ); assert( -gf_PI <= targetYaw ); assert( targetYaw <= gf_PI ); assert( 0 <= velocity ); assert( 0 <= elapsedSeconds ); const float deltaYawA = Wrap( targetYaw - yaw, -gf_PI, gf_PI ); const float deltaYawB = Wrap( yaw - targetYaw, -gf_PI, gf_PI ); const float absDeltaYawA = abs( deltaYawA ); const float absDeltaYawB = abs( deltaYawB ); const float absDeltaYawBWithThreshold = absDeltaYawB + threshold; const float deltaYaw = ( absDeltaYawA <= absDeltaYawBWithThreshold ) ? deltaYawA : deltaYawB; const float absDeltaYaw = abs( deltaYaw ); const float absMaxDeltaYaw = velocity * elapsedSeconds; const float absClampedDeltaYaw = min( absMaxDeltaYaw, absDeltaYaw ); const float signDeltaYaw = ( 0 <= deltaYaw ) ? 1.0f : -1.0f; const float clampedDeltaYaw = signDeltaYaw * absClampedDeltaYaw; const float clampedYaw = yaw + clampedDeltaYaw; const float wrappedClampYaw = Wrap( clampedYaw, -gf_PI, gf_PI ); return wrappedClampYaw; } float CProceduralContextTurretAimPose::VelocityClampPitch( const float pitch, const float targetPitch, const float velocity, const float elapsedSeconds ) { const float clampedTargetPitch = clamp_tpl( targetPitch, -ABS_PITCH_LIMIT_RADIANS, ABS_PITCH_LIMIT_RADIANS ); const float clampedPitch = VelocityClampValue( pitch, clampedTargetPitch, velocity, elapsedSeconds ); return clampedPitch; } void CProceduralContextTurretAimPose::UpdateSmoothedTargetWorldPosition( const float timePassedSeconds ) { assert( m_pSkeletonPose != NULL ); const int16 originJointId = m_aimPosesOriginJointId; const QuatT originJointLocation = m_pSkeletonPose->GetAbsJointByID( originJointId ); const Matrix34& worldTM = m_entity->GetWorldTM(); const Vec3 oldTargetLocalPosition = m_invertedWorldTM * m_smoothedTargetWorldPosition; const float oldYawRadians = m_yawRadians; const float oldPitchRadians = m_pitchRadians; static const STurretOrientation s_zeroTurretOrientation; static const STurretOrientation s_defaultTurretOrientation; const STurretOrientation turretOrientation = m_requestedTurretOrientation.Update( timePassedSeconds, s_zeroTurretOrientation, s_defaultTurretOrientation ); const float yawRadians = turretOrientation.yawRadians; const float pitchRadians = turretOrientation.pitchRadians; const float pitchDistance = turretOrientation.pitchDistance; const float yawDistance = turretOrientation.yawDistance; const float uncheckedMaxYawDegreesPerSecond = m_maxYawDegreesPerSecond.Update( timePassedSeconds, 0, 0 ); const float uncheckedMaxPitchDegreesPerSecond = m_maxPitchDegreesPerSecond.Update( timePassedSeconds, 0, 0 ); const float maxYawDegreesPerSecond = max( 0.0f, uncheckedMaxYawDegreesPerSecond ); const float maxPitchDegreesPerSeconds = max( 0.0f, uncheckedMaxPitchDegreesPerSecond ); const float clampedYawRadians = VelocityClampYaw( oldYawRadians, yawRadians, YAW_THRESHOLD_RADIANS, DEG2RAD( maxYawDegreesPerSecond ), timePassedSeconds ); const float clampedPitchRadians = VelocityClampPitch( oldPitchRadians, pitchRadians, DEG2RAD( maxPitchDegreesPerSeconds ), timePassedSeconds ); const Vec3 clampedTargetLocalPosition = TurretHelpers::CalculateTargetLocalPosition( originJointLocation, clampedYawRadians, clampedPitchRadians, yawDistance, pitchDistance ); const Vec3 clampedTargetWorldPosition = worldTM.TransformPoint( clampedTargetLocalPosition ); #ifdef DEBUGDRAW_PROCEDURAL_CONTEXT_TURRET_AIM_POSE { const float color[ 4 ] = { 1, 1, 1, 1 }; const Vec3 reconstructedTargetLocalPosition = TurretHelpers::CalculateTargetLocalPosition( originJointLocation, yawRadians, pitchRadians, yawDistance, pitchDistance ); const Vec3 reconstructedTargetWorldPosition = worldTM.TransformPoint( reconstructedTargetLocalPosition ); float textY = 10; gEnv->pRenderer->Draw2dLabel( 5, textY, 1.2f, color, false, "turret <%f, %f > <%f, %f>", RAD2DEG( pitchRadians ), RAD2DEG( yawRadians ), RAD2DEG( clampedPitchRadians ), RAD2DEG( clampedYawRadians ) ); textY += 15; gEnv->pRenderer->Draw2dLabel( 5, textY, 1.2f, color, false, "reconstruct world pos <%f, %f, %f>", reconstructedTargetWorldPosition.x, reconstructedTargetWorldPosition.y, reconstructedTargetWorldPosition.z ); textY += 15; gEnv->pRenderer->GetIRenderAuxGeom()->DrawSphere( reconstructedTargetWorldPosition, 0.5f, Col_Red ); gEnv->pRenderer->Draw2dLabel( 5, textY, 1.2f, color, false, "clamped world pos <%f, %f, %f>", clampedTargetWorldPosition.x, clampedTargetWorldPosition.y, clampedTargetWorldPosition.z ); textY += 15; gEnv->pRenderer->GetIRenderAuxGeom()->DrawSphere( clampedTargetWorldPosition, 0.5f, Col_Blue ); } #endif m_smoothedTargetWorldPosition = clampedTargetWorldPosition; m_pitchRadians = clampedPitchRadians; m_yawRadians = clampedYawRadians; } bool CProceduralContextTurretAimPose::InitialiseCharacter( const int characterSlot ) { if ( m_entity == NULL ) { return false; } ICharacterInstance* pCharacterInstance = m_entity->GetCharacter( characterSlot ); if ( pCharacterInstance == NULL ) { return false; } ISkeletonAnim* pSkeletonAnim = pCharacterInstance->GetISkeletonAnim(); if ( pSkeletonAnim == NULL ) { return false; } ISkeletonPose* pSkeletonPose = pCharacterInstance->GetISkeletonPose(); if ( pSkeletonPose == NULL ) { return false; } IDefaultSkeleton& rIDefaultSkeleton = pCharacterInstance->GetIDefaultSkeleton(); m_pCharacterInstance = pCharacterInstance; m_pSkeletonAnim = pSkeletonAnim; m_pSkeletonPose = pSkeletonPose; m_pIDefaultSkeleton = &rIDefaultSkeleton; return true; } void CProceduralContextTurretAimPose::InitialiseHorizontalAim() { CryCreateClassInstance( "AnimationPoseModifier_OperatorQueue", m_pHorizontalAim ); } void CProceduralContextTurretAimPose::InitialiseVerticalAim() { assert( m_pSkeletonPose != NULL ); m_pVerticalAim = m_pSkeletonPose->GetIPoseBlenderAim(); if ( m_pVerticalAim == NULL ) { return; } const Vec3 defaultTargetWorldPosition = m_entity->GetWorldPos() + m_entity->GetForwardDir(); m_pVerticalAim->SetTarget( defaultTargetWorldPosition ); m_pVerticalAim->SetPolarCoordinatesMaxRadiansPerSecond( Vec2( gf_PI * 10.f, gf_PI * 10.f ) ); // Yaw/pitch smoothing is handled outside m_pVerticalAim->SetPolarCoordinatesSmoothTimeSeconds( 1 ); m_pVerticalAim->SetState( false ); m_pVerticalAim->SetLayer( m_verticalAimLayer ); } void CProceduralContextTurretAimPose::SetRequestedTargetWorldPosition( const Vec3& targetWorldPosition, const float weight, const float blendOutTime ) { const int16 originJointId = m_aimPosesOriginJointId; const QuatT& originJointLocation = m_pSkeletonPose->GetAbsJointByID( originJointId ); const Vec3 targetLocalPosition = m_invertedWorldTM * targetWorldPosition; STurretOrientation targetOrientation; TurretHelpers::CalculateTargetOrientation( targetLocalPosition, originJointLocation, targetOrientation.yawRadians, targetOrientation.pitchRadians, targetOrientation.yawDistance, targetOrientation.pitchDistance ); m_requestedTurretOrientation.AddTimedValue( targetOrientation, weight, blendOutTime ); } void CProceduralContextTurretAimPose::SetVerticalSmoothTime( const float verticalSmoothTimeSeconds, const float weight, const float blendOutTime ) { m_verticalAimSmoothTime.AddTimedValue( verticalSmoothTimeSeconds, weight, blendOutTime ); } void CProceduralContextTurretAimPose::SetMaxYawDegreesPerSecond( const float maxYawDegreesPerSecond, const float weight, const float blendOutTime ) { m_maxYawDegreesPerSecond.AddTimedValue( maxYawDegreesPerSecond, weight, blendOutTime ); } void CProceduralContextTurretAimPose::SetMaxPitchDegreesPerSecond( const float maxPitchDegreesPerSecond, const float weight, const float blendOutTime ) { m_maxPitchDegreesPerSecond.AddTimedValue( maxPitchDegreesPerSecond, weight, blendOutTime ); } void CProceduralContextTurretAimPose::UpdateHorizontalAim( const Vec3& targetLocalPosition, const float timePassedSeconds ) { assert( m_pSkeletonAnim != NULL ); if ( ! m_pHorizontalAim ) { return; } if ( m_horizontalAimJointId < 0 ) { return; } m_pHorizontalAim->Clear(); const Vec3 forwardLocalDirection( 0, 1, 0 ); const Vec3 targetLocalDirection = targetLocalPosition.GetNormalizedSafe( forwardLocalDirection ); const Vec3 targetDirection2d = Vec3( targetLocalDirection.x, targetLocalDirection.y, 0 ).GetNormalizedSafe( forwardLocalDirection ); const Quat desiredOrientation = Quat::CreateRotationV0V1( forwardLocalDirection, targetDirection2d ); m_pHorizontalAim->PushOrientation( m_horizontalAimJointId, IAnimationOperatorQueue::eOp_Override, desiredOrientation ); m_pSkeletonAnim->PushPoseModifier( m_horizontalAimLayer, cryinterface_cast< IAnimationPoseModifier >( m_pHorizontalAim ), "TurretAimPose" ); } void CProceduralContextTurretAimPose::UpdateVerticalAim( const Vec3& targetWorldPosition, const float timePassedSeconds ) { assert( m_pSkeletonAnim != NULL ); assert( m_pSkeletonPose != NULL ); if ( m_pVerticalAim == NULL ) { return; } const float verticalAimSmoothTime = m_verticalAimSmoothTime.Update( timePassedSeconds, 0, 0 ); m_pVerticalAim->SetPolarCoordinatesSmoothTimeSeconds( verticalAimSmoothTime ); m_pVerticalAim->SetState( true ); m_pVerticalAim->SetLayer( m_verticalAimLayer ); m_pVerticalAim->SetTarget( targetWorldPosition ); } void CProceduralContextTurretAimPose::UpdateFallbackAim( const Vec3& targetLocalPosition ) { assert( m_pSkeletonPose != NULL ); const bool needFallbackAim = ( m_pVerticalAim == NULL ); if ( ! needFallbackAim ) { return; } if ( ! m_pHorizontalAim ) { return; } const int16 fallbackJointId = m_weaponJointId; if ( fallbackJointId < 0 ) { return; } const Vec3 forwardLocalDirection( 0, 1, 0 ); const QuatT& lastFrameJointLocation = m_pSkeletonPose->GetAbsJointByID( fallbackJointId ); const Vec3 targetJointLocalPosition = targetLocalPosition - lastFrameJointLocation.t; const Vec3 targetJointLocalDirection = targetJointLocalPosition.GetNormalizedSafe( forwardLocalDirection ); const Quat desiredOrientation = Quat::CreateRotationV0V1( forwardLocalDirection, targetJointLocalDirection ); m_pHorizontalAim->PushOrientation( fallbackJointId, IAnimationOperatorQueue::eOp_Override, desiredOrientation ); } void CProceduralContextTurretAimPose::SetHorizontalAimJointName( const char* horizontalAimJointName ) { assert( horizontalAimJointName ); assert( horizontalAimJointName[ 0 ] != 0 ); assert( m_pSkeletonPose != NULL ); if ( m_pSkeletonPose == NULL ) { CryWarning( VALIDATOR_MODULE_GAME, VALIDATOR_WARNING, "ProceduralContext TurretAimPose: Could not initialise horizontal joint with name '%s' for entity named '%s'.", horizontalAimJointName, m_entity->GetName() ); SetHorizontalAimJointId( -1 ); return; } const int16 horizontalAimJointId = m_pIDefaultSkeleton->GetJointIDByName( horizontalAimJointName ); SetHorizontalAimJointId( horizontalAimJointId ); } void CProceduralContextTurretAimPose::SetWeaponJointName( const char* weaponJointName ) { assert( weaponJointName ); assert( weaponJointName[ 0 ] != 0 ); assert( m_pSkeletonPose != NULL ); if ( m_pSkeletonPose == NULL ) { CryWarning( VALIDATOR_MODULE_GAME, VALIDATOR_WARNING, "ProceduralContext TurretAimPose: Could not initialise weapon joint with name '%s' for entity named '%s'.", weaponJointName, m_entity->GetName() ); SetWeaponJointId( -1 ); return; } const int16 weaponJointId = m_pIDefaultSkeleton->GetJointIDByName( weaponJointName ); SetWeaponJointId( weaponJointId ); } void CProceduralContextTurretAimPose::SetAimPosesOriginJointName( const char* aimPosesOriginJointName ) { assert( aimPosesOriginJointName ); assert( aimPosesOriginJointName[ 0 ] != 0 ); assert( m_pSkeletonPose != NULL ); if ( m_pSkeletonPose == NULL ) { CryWarning( VALIDATOR_MODULE_GAME, VALIDATOR_WARNING, "ProceduralContext TurretAimPose: Could not initialise aim poses origin joint with name '%s' for entity named '%s'.", aimPosesOriginJointName, m_entity->GetName() ); SetAimPosesOriginJointId( -1 ); return; } const int16 aimPosesOriginJointId = m_pIDefaultSkeleton->GetJointIDByName( aimPosesOriginJointName ); SetAimPosesOriginJointId( aimPosesOriginJointId ); } void CProceduralContextTurretAimPose::SetHorizontalAimJointId( const int16 horizontalAimJointId ) { m_horizontalAimJointId = horizontalAimJointId; } void CProceduralContextTurretAimPose::SetWeaponJointId( const int16 weaponJointId ) { m_weaponJointId = weaponJointId; } void CProceduralContextTurretAimPose::SetAimPosesOriginJointId( const int16 aimPosesOriginJointId ) { m_aimPosesOriginJointId = aimPosesOriginJointId; } int CProceduralContextTurretAimPose::GetVerticalAimLayer() const { return m_verticalAimLayer; }
1
0.810452
1
0.810452
game-dev
MEDIA
0.898403
game-dev
0.83845
1
0.83845
lua9520/source-engine-2018-cstrike15_src
7,766
game/shared/igamesystem.h
//========= Copyright 1996-2005, Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ //=============================================================================// #ifndef IGAMESYSTEM_H #define IGAMESYSTEM_H #ifdef _WIN32 #pragma once #endif //----------------------------------------------------------------------------- // Game systems are singleton objects in the client + server codebase responsible for // various tasks // The order in which the server systems appear in this list are the // order in which they are initialized and updated. They are shut down in // reverse order from which they are initialized. //----------------------------------------------------------------------------- #ifdef GAME_DLL class CBasePlayer; class CUserCmd; #endif // UNDONE: Do these need GameInit/GameShutdown as well? // UNDONE: Remove the Pre/Post entity semantics and rely on system ordering? // FIXME: Remove all ifdef CLIENT_DLL if we can... abstract_class IGameSystem { public: // GameSystems are expected to implement these methods. virtual char const *Name() = 0; // Init, shutdown // return true on success. false to abort DLL init! virtual bool Init() = 0; virtual void PostInit() = 0; virtual void Shutdown() = 0; // Level init, shutdown virtual void LevelInitPreEntity() = 0; // entities are created / spawned / precached here virtual void LevelInitPostEntity() = 0; virtual void LevelShutdownPreEntity() = 0; // Entities are deleted / released here... virtual void LevelShutdownPostEntity() = 0; // end of level shutdown // Called during game save virtual void OnSave() = 0; // Called during game restore, after the local player has connected and entities have been fully restored virtual void OnRestore() = 0; // Called every frame. It's safe to remove an igamesystem from within this callback. virtual void SafeRemoveIfDesired() = 0; virtual bool IsPerFrame() = 0; // destructor, cleans up automagically.... virtual ~IGameSystem(); // Client systems can use this to get at the map name static char const* MapName(); // These methods are used to add and remove server systems from the // main server loop. The systems are invoked in the order in which // they are added. static void Add ( IGameSystem* pSys ); static void Remove ( IGameSystem* pSys ); static void RemoveAll ( ); // These methods are used to initialize, shutdown, etc all systems static bool InitAllSystems(); static void PostInitAllSystems(); static void ShutdownAllSystems(); static void LevelInitPreEntityAllSystems( char const* pMapName ); static void LevelInitPostEntityAllSystems(); static void LevelShutdownPreEntityAllSystems(); static void LevelShutdownPostEntityAllSystems(); static void OnSaveAllSystems(); static void OnRestoreAllSystems(); static void SafeRemoveIfDesiredAllSystems(); #ifdef CLIENT_DLL static void PreRenderAllSystems(); static void UpdateAllSystems( float frametime ); static void PostRenderAllSystems(); #else static void FrameUpdatePreEntityThinkAllSystems(); static void FrameUpdatePostEntityThinkAllSystems(); static void PreClientUpdateAllSystems(); // Accessors for the above function #ifdef GAME_DLL static CBasePlayer *RunCommandPlayer(); static CUserCmd *RunCommandUserCmd(); #endif #endif }; class IGameSystemPerFrame : public IGameSystem { public: // destructor, cleans up automagically.... virtual ~IGameSystemPerFrame(); #ifdef CLIENT_DLL // Called before rendering virtual void PreRender() = 0; // Gets called each frame virtual void Update( float frametime ) = 0; // Called after rendering virtual void PostRender() = 0; #else // Called each frame before entities think virtual void FrameUpdatePreEntityThink() = 0; // called after entities think virtual void FrameUpdatePostEntityThink() = 0; virtual void PreClientUpdate() = 0; #endif }; // Quick and dirty server system for users who don't care about precise ordering // and usually only want to implement a few of the callbacks class CBaseGameSystem : public IGameSystem { public: virtual char const *Name() { return "unnamed"; } // Init, shutdown // return true on success. false to abort DLL init! virtual bool Init() { return true; } virtual void PostInit() {} virtual void Shutdown() {} // Level init, shutdown virtual void LevelInitPreEntity() {} virtual void LevelInitPostEntity() {} virtual void LevelShutdownPreEntity() {} virtual void LevelShutdownPostEntity() {} virtual void OnSave() {} virtual void OnRestore() {} virtual void SafeRemoveIfDesired() {} virtual bool IsPerFrame() { return false; } private: // Prevent anyone derived from CBaseGameSystem from implementing these, they need // to derive from CBaseGameSystemPerFrame below!!! #ifdef CLIENT_DLL // Called before rendering virtual void PreRender() {} // Gets called each frame virtual void Update( float frametime ) {} // Called after rendering virtual void PostRender() {} #else // Called each frame before entities think virtual void FrameUpdatePreEntityThink() {} // called after entities think virtual void FrameUpdatePostEntityThink() {} virtual void PreClientUpdate() {} #endif }; // Quick and dirty server system for users who don't care about precise ordering // and usually only want to implement a few of the callbacks class CBaseGameSystemPerFrame : public IGameSystemPerFrame { public: virtual char const *Name() { return "unnamed"; } // Init, shutdown // return true on success. false to abort DLL init! virtual bool Init() { return true; } virtual void PostInit() {} virtual void Shutdown() {} // Level init, shutdown virtual void LevelInitPreEntity() {} virtual void LevelInitPostEntity() {} virtual void LevelShutdownPreEntity() {} virtual void LevelShutdownPostEntity() {} virtual void OnSave() {} virtual void OnRestore() {} virtual void SafeRemoveIfDesired() {} virtual bool IsPerFrame() { return true; } #ifdef CLIENT_DLL // Called before rendering virtual void PreRender () { } // Gets called each frame virtual void Update( float frametime ) { } // Called after rendering virtual void PostRender () { } #else // Called each frame before entities think virtual void FrameUpdatePreEntityThink() { } // called after entities think virtual void FrameUpdatePostEntityThink() { } virtual void PreClientUpdate() { } #endif }; // Quick and dirty server system for users who don't care about precise ordering // and usually only want to implement a few of the callbacks class CAutoGameSystem : public CBaseGameSystem { public: CAutoGameSystem( char const *name = NULL ); // hooks in at startup, no need to explicitly add CAutoGameSystem *m_pNext; virtual char const *Name() { return m_pszName ? m_pszName : "unnamed"; } private: char const *m_pszName; }; //----------------------------------------------------------------------------- // Purpose: This is a CAutoGameSystem which also cares about the "per frame" hooks //----------------------------------------------------------------------------- class CAutoGameSystemPerFrame : public CBaseGameSystemPerFrame { public: CAutoGameSystemPerFrame( char const *name = NULL ); CAutoGameSystemPerFrame *m_pNext; virtual char const *Name() { return m_pszName ? m_pszName : "unnamed"; } private: char const *m_pszName; }; //----------------------------------------------------------------------------- // Purpose: This interface is here to add more hooks than IGameSystemPerFrame exposes, // so we don't pollute it with hooks that only the tool cares about //----------------------------------------------------------------------------- class IToolFrameworkServer { public: virtual void PreSetupVisibility() = 0; }; #endif // IGAMESYSTEM_H
1
0.928206
1
0.928206
game-dev
MEDIA
0.964162
game-dev
0.668931
1
0.668931
Ezzz-dev/OTHire
2,381
data/npc/scripts/lib/npcsystem/queue.lua
-- This file is part of Jiddo's advanced NpcSystem v3.0x. This npcsystem is free to use by anyone, for any purpuse. -- Initial release date: 2007-02-21 -- Credits: Jiddo, honux(I'm using a modified version of his Find function). -- Please include full credits whereever you use this system, or parts of it. -- For support, questions and updates, please consult the following thread: -- http://opentibia.net/topic/59592-release-advanced-npc-system-v30a/ if(Queue == nil) then Queue = { customers = nil, handler = nil, } -- Creates a new queue, connected to the given NpcHandler handler function Queue:new(handler) local obj = {} obj.handler = handler obj.customers = {} setmetatable(obj, self) self.__index = self return obj end -- Assigns a new handler to this queue. function Queue:setHandler(newHandler) self.handler = newHandler end -- Pushes a new cid onto the tail of this queue. function Queue:push(cid) if(isPlayer(cid)) then table.insert(self.customers, cid) end end -- Returns true if the given cid is already in the queue. function Queue:isInQueue(cid) return (isInArray(self.customers, cid) == true) end -- Removes and returns the first cid from the queue function Queue:pop() return table.remove(self.customers, 1) end -- Returns the first cid in the queue, but does not remove it! function Queue:peek() return self.customers[1] end -- Returns true if htis queue is empty. function Queue:empty() return(self:peek() == nil) end -- Returns the amount of players currently in the queue. function Queue:getSize() return table.maxn(self.customers) end -- Returns true if the creature with the given cid can be greeted by this npc. function Queue:canGreet(cid) if(isPlayer(cid)) then return self.handler:isInRange(cid) else return false end end -- Greets the player with the given cid. function Queue:greet(cid) if(self.handler ~= nil) then self.handler:greet(cid) else error('No handler assigned to queue!') end end -- Makes sure the next greetable player in the queue is greeted. function Queue:greetNext() while (not self:empty()) do local nextPlayer = self:pop() if(self:canGreet(nextPlayer)) then if(callback == nil or callback(nextPlayer)) then self:greet(nextPlayer) return true end end end return false end end
1
0.86252
1
0.86252
game-dev
MEDIA
0.163812
game-dev
0.850023
1
0.850023
open-toontown/open-toontown
26,233
toontown/cogdominium/CogdoFlyingLegalEagle.py
import math from direct.showbase.DirectObject import DirectObject from direct.directnotify import DirectNotifyGlobal from direct.fsm.FSM import FSM from direct.task.Task import Task from direct.interval.IntervalGlobal import Sequence, Parallel, LerpScaleInterval, LerpFunctionInterval, Func, Wait, LerpFunc, SoundInterval, ParallelEndTogether, LerpPosInterval, ActorInterval, LerpPosHprInterval, LerpHprInterval from direct.directutil import Mopath from direct.showbase.PythonUtil import bound as clamp from panda3d.core import CollisionSphere, CollisionNode, CollisionTube, CollisionPolygon, Vec3, Point3 from toontown.suit import Suit from toontown.suit import SuitDNA from toontown.toonbase import ToontownGlobals from toontown.battle import BattleProps from .CogdoFlyingUtil import swapAvatarShadowPlacer from . import CogdoUtil from . import CogdoFlyingGameGlobals as Globals class CogdoFlyingLegalEagle(FSM, DirectObject): CollSphereName = 'CogdoFlyingLegalEagleSphere' CollisionEventName = 'CogdoFlyingLegalEagleCollision' InterestCollName = 'CogdoFlyingLegalEagleInterestCollision' RequestAddTargetEventName = 'CogdoFlyingLegalEagleRequestTargetEvent' RequestAddTargetAgainEventName = 'CogdoFlyingLegalEagleRequestTargetAgainEvent' RequestRemoveTargetEventName = 'CogdoFlyingLegalEagleRemoveTargetEvent' ForceRemoveTargetEventName = 'CogdoFlyingLegalEagleForceRemoveTargetEvent' EnterLegalEagle = 'CogdoFlyingLegalEagleDamageToon' ChargingToAttackEventName = 'LegalEagleChargingToAttack' LockOnToonEventName = 'LegalEagleLockOnToon' CooldownEventName = 'LegalEagleCooldown' notify = DirectNotifyGlobal.directNotify.newCategory('CogdoFlyingLegalEagle') def __init__(self, nest, index, suitDnaName = 'le'): FSM.__init__(self, 'CogdoFlyingLegalEagle') self.defaultTransitions = {'Off': ['Roost'], 'Roost': ['TakeOff', 'Off'], 'TakeOff': ['LockOnToon', 'LandOnNest', 'Off'], 'LockOnToon': ['RetreatToNest', 'ChargeUpAttack', 'Off'], 'ChargeUpAttack': ['RetreatToNest', 'Attack', 'Off'], 'Attack': ['RetreatToSky', 'Off'], 'RetreatToSky': ['Cooldown', 'Off'], 'Cooldown': ['LockOnToon', 'LandOnNest', 'Off'], 'RetreatToNest': ['LandOnNest', 'Off'], 'LandOnNest': ['Roost', 'Off']} self.index = index self.nest = nest self.target = None self.isEagleInterested = False self.collSphere = None self.suit = Suit.Suit() d = SuitDNA.SuitDNA() d.newSuit(suitDnaName) self.suit.setDNA(d) self.suit.reparentTo(render) swapAvatarShadowPlacer(self.suit, 'legalEagle-%sShadowPlacer' % index) self.suit.setPos(self.nest.getPos(render)) self.suit.setHpr(-180, 0, 0) self.suit.stash() self.prop = None self.attachPropeller() head = self.suit.find('**/joint_head') self.interestConeOrigin = self.nest.attachNewNode('fakeHeadNodePath') self.interestConeOrigin.setPos(render, head.getPos(render) + Vec3(0, Globals.LegalEagle.InterestConeOffset, 0)) self.attackTargetPos = None self.startOfRetreatToSkyPos = None pathModel = CogdoUtil.loadFlyingModel('legalEaglePaths') self.chargeUpMotionPath = Mopath.Mopath(name='chargeUpMotionPath-%i' % self.index) self.chargeUpMotionPath.loadNodePath(pathModel.find('**/charge_path')) self.retreatToSkyMotionPath = Mopath.Mopath(name='retreatToSkyMotionPath-%i' % self.index) self.retreatToSkyMotionPath.loadNodePath(pathModel.find('**/retreat_path')) audioMgr = base.cogdoGameAudioMgr self._screamSfx = audioMgr.createSfx('legalEagleScream', self.suit) self.initIntervals() return def attachPropeller(self): if self.prop == None: self.prop = BattleProps.globalPropPool.getProp('propeller') head = self.suit.find('**/joint_head') self.prop.reparentTo(head) return def detachPropeller(self): if self.prop: self.prop.cleanup() self.prop.removeNode() self.prop = None return def _getAnimationIval(self, animName, startFrame = 0, endFrame = None, duration = 1): if endFrame == None: self.suit.getNumFrames(animName) - 1 frames = endFrame - startFrame frameRate = self.suit.getFrameRate(animName) newRate = frames / duration playRate = newRate / frameRate ival = Sequence(ActorInterval(self.suit, animName, playRate=playRate)) return ival def initIntervals(self): dur = Globals.LegalEagle.LiftOffTime nestPos = self.nest.getPos(render) airPos = nestPos + Vec3(0.0, 0.0, Globals.LegalEagle.LiftOffHeight) self.takeOffSeq = Sequence(Parallel(Sequence(Wait(dur * 0.6), LerpPosInterval(self.suit, dur * 0.4, startPos=nestPos, pos=airPos, blendType='easeInOut'))), Wait(1.5), Func(self.request, 'next'), name='%s.takeOffSeq-%i' % (self.__class__.__name__, self.index)) self.landOnNestPosLerp = LerpPosInterval(self.suit, 1.0, startPos=airPos, pos=nestPos, blendType='easeInOut') self.landingSeq = Sequence(Func(self.updateLandOnNestPosLerp), Parallel(self.landOnNestPosLerp), Func(self.request, 'next'), name='%s.landingSeq-%i' % (self.__class__.__name__, self.index)) dur = Globals.LegalEagle.ChargeUpTime self.chargeUpPosLerp = LerpFunc(self.moveAlongChargeUpMopathFunc, fromData=0.0, toData=self.chargeUpMotionPath.getMaxT(), duration=dur, blendType='easeInOut') self.chargeUpAttackSeq = Sequence(Func(self.updateChargeUpPosLerp), self.chargeUpPosLerp, Func(self.request, 'next'), name='%s.chargeUpAttackSeq-%i' % (self.__class__.__name__, self.index)) dur = Globals.LegalEagle.RetreatToNestTime self.retreatToNestPosLerp = LerpPosInterval(self.suit, dur, startPos=Vec3(0, 0, 0), pos=airPos, blendType='easeInOut') self.retreatToNestSeq = Sequence(Func(self.updateRetreatToNestPosLerp), self.retreatToNestPosLerp, Func(self.request, 'next'), name='%s.retreatToNestSeq-%i' % (self.__class__.__name__, self.index)) dur = Globals.LegalEagle.RetreatToSkyTime self.retreatToSkyPosLerp = LerpFunc(self.moveAlongRetreatMopathFunc, fromData=0.0, toData=self.retreatToSkyMotionPath.getMaxT(), duration=dur, blendType='easeOut') self.retreatToSkySeq = Sequence(Func(self.updateRetreatToSkyPosLerp), self.retreatToSkyPosLerp, Func(self.request, 'next'), name='%s.retreatToSkySeq-%i' % (self.__class__.__name__, self.index)) dur = Globals.LegalEagle.PreAttackTime self.preAttackLerpXY = LerpFunc(self.updateAttackXY, fromData=0.0, toData=1.0, duration=dur) self.preAttackLerpZ = LerpFunc(self.updateAttackZ, fromData=0.0, toData=1.0, duration=dur, blendType='easeOut') dur = Globals.LegalEagle.PostAttackTime self.postAttackPosLerp = LerpPosInterval(self.suit, dur, startPos=Vec3(0, 0, 0), pos=Vec3(0, 0, 0)) self.attackSeq = Sequence(Parallel(self.preAttackLerpXY, self.preAttackLerpZ), Func(self.updatePostAttackPosLerp), self.postAttackPosLerp, Func(self.request, 'next'), name='%s.attackSeq-%i' % (self.__class__.__name__, self.index)) dur = Globals.LegalEagle.CooldownTime self.cooldownSeq = Sequence(Wait(dur), Func(self.request, 'next'), name='%s.cooldownSeq-%i' % (self.__class__.__name__, self.index)) self.propTrack = Sequence(ActorInterval(self.prop, 'propeller', startFrame=0, endFrame=14)) self.hoverOverNestSeq = Sequence(ActorInterval(self.suit, 'landing', startFrame=10, endFrame=20, playRate=0.5), ActorInterval(self.suit, 'landing', startFrame=20, endFrame=10, playRate=0.5)) def initCollision(self): self.collSphere = CollisionSphere(0, 0, 0, 0) self.collSphere.setTangible(0) self.collNode = CollisionNode('%s-%s' % (self.CollSphereName, self.index)) self.collNode.setIntoCollideMask(ToontownGlobals.WallBitmask) self.collNode.addSolid(self.collSphere) self.collNodePath = self.suit.attachNewNode(self.collNode) self.collNodePath.hide() self.accept('enter%s-%s' % (self.CollSphereName, self.index), self.handleEnterSphere) self.setCollSphereToNest() def getInterestConeLength(self): return Globals.LegalEagle.InterestConeLength + Globals.LegalEagle.InterestConeOffset def isToonInView(self, toon): distanceThreshold = self.getInterestConeLength() angleThreshold = Globals.LegalEagle.InterestConeAngle toonPos = toon.getPos(render) nestPos = self.nest.getPos(render) distance = toon.getDistance(self.interestConeOrigin) if distance > distanceThreshold: return False if toonPos[1] > nestPos[1]: return False a = toon.getPos(render) - self.interestConeOrigin.getPos(render) a.normalize() b = Vec3(0, -1, 0) dotProduct = a.dot(b) angle = math.degrees(math.acos(dotProduct)) if angle <= angleThreshold / 2.0: return True else: return False def update(self, dt, localPlayer): if Globals.Dev.NoLegalEagleAttacks: return inView = self.isToonInView(localPlayer.toon) if inView and not self.isEagleInterested: self.handleEnterInterest() elif inView and self.isEagleInterested: self.handleAgainInterest() elif not inView and self.isEagleInterested: self.handleExitInterest() def updateLockOnTask(self): dt = globalClock.getDt() targetPos = self.target.getPos(render) suitPos = self.suit.getPos(render) nestPos = self.nest.getPos(render) attackPos = Vec3(targetPos) attackPos[1] = nestPos[1] + Globals.LegalEagle.LockOnDistanceFromNest attackPos[2] += Globals.LegalEagle.VerticalOffset if attackPos[2] < nestPos[2]: attackPos[2] = nestPos[2] attackChangeVec = (attackPos - suitPos) * Globals.LegalEagle.LockOnSpeed self.suit.setPos(suitPos + attackChangeVec * dt) return Task.cont def updateAttackXY(self, value): if Globals.LegalEagle.EagleAttackShouldXCorrect: x = self.readyToAttackPos.getX() + (self.attackTargetPos.getX() - self.readyToAttackPos.getX()) * value self.suit.setX(x) y = self.readyToAttackPos.getY() + (self.attackTargetPos.getY() - self.readyToAttackPos.getY()) * value self.suit.setY(y) def updateAttackZ(self, value): z = self.readyToAttackPos.getZ() + (self.attackTargetPos.getZ() - self.readyToAttackPos.getZ()) * value self.suit.setZ(z) def moveAlongChargeUpMopathFunc(self, value): self.chargeUpMotionPath.goTo(self.suit, value) self.suit.setPos(self.suit.getPos() + self.startOfChargeUpPos) def moveAlongRetreatMopathFunc(self, value): self.retreatToSkyMotionPath.goTo(self.suit, value) self.suit.setPos(self.suit.getPos() + self.startOfRetreatToSkyPos) def updateChargeUpPosLerp(self): self.startOfChargeUpPos = self.suit.getPos(render) def updateLandOnNestPosLerp(self): self.landOnNestPosLerp.setStartPos(self.suit.getPos()) def updateRetreatToNestPosLerp(self): self.retreatToNestPosLerp.setStartPos(self.suit.getPos()) def updateRetreatToSkyPosLerp(self): self.startOfRetreatToSkyPos = self.suit.getPos(render) def updatePostAttackPosLerp(self): suitPos = self.suit.getPos(render) finalPos = suitPos + Vec3(0, -Globals.LegalEagle.PostAttackLength, 0) self.postAttackPosLerp.setStartPos(suitPos) self.postAttackPosLerp.setEndPos(finalPos) def handleEnterSphere(self, collEntry): self.notify.debug('handleEnterSphere:%i' % self.index) messenger.send(CogdoFlyingLegalEagle.EnterLegalEagle, [self, collEntry]) def handleEnterInterest(self): self.notify.debug('handleEnterInterestColl:%i' % self.index) self.isEagleInterested = True messenger.send(CogdoFlyingLegalEagle.RequestAddTargetEventName, [self.index]) def handleAgainInterest(self): self.isEagleInterested = True messenger.send(CogdoFlyingLegalEagle.RequestAddTargetAgainEventName, [self.index]) def handleExitInterest(self): self.notify.debug('handleExitInterestSphere:%i' % self.index) self.isEagleInterested = False messenger.send(CogdoFlyingLegalEagle.RequestRemoveTargetEventName, [self.index]) def hasTarget(self): if self.target != None: return True else: return False return def setTarget(self, toon, elapsedTime = 0.0): self.notify.debug('Setting eagle %i to target: %s, elapsed time: %s' % (self.index, toon.getName(), elapsedTime)) self.target = toon if self.state == 'Roost': self.request('next', elapsedTime) if self.state == 'ChargeUpAttack': messenger.send(CogdoFlyingLegalEagle.ChargingToAttackEventName, [self.target.doId]) def clearTarget(self, elapsedTime = 0.0): self.notify.debug('Clearing target from eagle %i, elapsed time: %s' % (self.index, elapsedTime)) messenger.send(CogdoFlyingLegalEagle.CooldownEventName, [self.target.doId]) self.target = None if self.state in ['LockOnToon']: self.request('next', elapsedTime) return def leaveCooldown(self, elapsedTime = 0.0): if self.state in ['Cooldown']: self.request('next', elapsedTime) def shouldBeInFrame(self): if self.state in ['TakeOff', 'LockOnToon', 'ChargeUpAttack']: return True elif self.state == 'Attack': distance = self.suit.getDistance(self.target) threshold = Globals.LegalEagle.EagleAndTargetDistCameraTrackThreshold suitPos = self.suit.getPos(render) targetPos = self.target.getPos(render) if distance > threshold and suitPos[1] > targetPos[1]: return True return False def getTarget(self): return self.target def onstage(self): self.suit.unstash() self.request('Roost') def offstage(self): self.suit.stash() self.request('Off') def gameStart(self, gameStartTime): self.gameStartTime = gameStartTime self.initCollision() def gameEnd(self): self.shutdownCollisions() def shutdownCollisions(self): self.ignoreAll() if self.collSphere != None: del self.collSphere self.collSphere = None if self.collNodePath != None: self.collNodePath.removeNode() del self.collNodePath self.collNodePath = None if self.collNode != None: del self.collNode self.collNode = None return def destroy(self): self.request('Off') self.detachPropeller() del self._screamSfx self.suit.cleanup() self.suit.removeNode() self.suit.delete() self.interestConeOrigin.removeNode() del self.interestConeOrigin self.nest = None self.target = None taskMgr.remove('updateLockOnTask-%i' % self.index) taskMgr.remove('exitLockOnToon-%i' % self.index) self.propTrack.clearToInitial() del self.propTrack del self.chargeUpMotionPath del self.retreatToSkyMotionPath self.takeOffSeq.clearToInitial() del self.takeOffSeq del self.landOnNestPosLerp self.landingSeq.clearToInitial() del self.landingSeq del self.chargeUpPosLerp self.chargeUpAttackSeq.clearToInitial() del self.chargeUpAttackSeq del self.retreatToNestPosLerp self.retreatToNestSeq.clearToInitial() del self.retreatToNestSeq del self.retreatToSkyPosLerp self.retreatToSkySeq.clearToInitial() del self.retreatToSkySeq del self.postAttackPosLerp self.attackSeq.clearToInitial() del self.attackSeq self.cooldownSeq.clearToInitial() del self.cooldownSeq self.hoverOverNestSeq.clearToInitial() del self.hoverOverNestSeq del self.preAttackLerpXY del self.preAttackLerpZ return def requestNext(self): self.request('next') def setCollSphereToNest(self): if hasattr(self, 'collSphere') and self.collSphere is not None: radius = Globals.LegalEagle.OnNestDamageSphereRadius self.collSphere.setCenter(Point3(0.0, -Globals.Level.LaffPowerupNestOffset[1], self.suit.getHeight() / 2.0)) self.collSphere.setRadius(radius) return def setCollSphereToTargeting(self): if hasattr(self, 'collSphere') and self.collSphere is not None: radius = Globals.LegalEagle.DamageSphereRadius self.collSphere.setCenter(Point3(0, 0, radius * 2)) self.collSphere.setRadius(radius) return def enterRoost(self): self.notify.info("enter%s: '%s' -> '%s'" % (self.newState, self.oldState, self.newState)) self.hoverOverNestSeq.loop() self.propTrack.loop() self.setCollSphereToNest() def filterRoost(self, request, args): self.notify.debug("filter%s( '%s', '%s' )" % (self.state, request, args)) if request == self.state: return None elif request == 'next': return 'TakeOff' else: return self.defaultFilter(request, args) return None def exitRoost(self): self.notify.debug("exit%s: '%s' -> '%s'" % (self.oldState, self.oldState, self.newState)) self.hoverOverNestSeq.pause() self.setCollSphereToTargeting() def enterTakeOff(self, elapsedTime = 0.0): self.notify.info("enter%s: '%s' -> '%s', elapsedTime:%s" % (self.newState, self.oldState, self.newState, elapsedTime)) self.takeOffSeq.start(elapsedTime) self.hoverOverNestSeq.loop() def filterTakeOff(self, request, args): self.notify.debug("filter%s( '%s', '%s' )" % (self.state, request, args)) if request == self.state: return None elif request == 'next': if self.hasTarget(): return 'LockOnToon' else: return 'LandOnNest' else: return self.defaultFilter(request, args) return None def exitTakeOff(self): self.notify.debug("exit%s: '%s' -> '%s'" % (self.oldState, self.oldState, self.newState)) self.takeOffSeq.clearToInitial() self.hoverOverNestSeq.pause() def enterLockOnToon(self, elapsedTime = 0.0): self.notify.info("enter%s: '%s' -> '%s', elapsedTime:%s" % (self.newState, self.oldState, self.newState, elapsedTime)) taskName = 'updateLockOnTask-%i' % self.index taskMgr.add(self.updateLockOnTask, taskName, 45, extraArgs=[]) messenger.send(CogdoFlyingLegalEagle.LockOnToonEventName, [self.target.doId]) range = self.target.getDistance(self.interestConeOrigin) / self.getInterestConeLength() range = clamp(range, 0.0, 1.0) dur = Globals.LegalEagle.LockOnTime if self.oldState == 'TakeOff': dur *= range else: dur += Globals.LegalEagle.ExtraPostCooldownTime taskName = 'exitLockOnToon-%i' % self.index taskMgr.doMethodLater(dur, self.requestNext, taskName, extraArgs=[]) def filterLockOnToon(self, request, args): self.notify.debug("filter%s( '%s', '%s' )" % (self.state, request, args)) if request == self.state: return None elif request == 'next': if self.hasTarget(): return 'ChargeUpAttack' else: return 'RetreatToNest' else: return self.defaultFilter(request, args) return None def exitLockOnToon(self): self.notify.debug("exit%s: '%s' -> '%s'" % (self.oldState, self.oldState, self.newState)) taskMgr.remove('updateLockOnTask-%i' % self.index) taskMgr.remove('exitLockOnToon-%i' % self.index) def enterChargeUpAttack(self, elapsedTime = 0.0): self.notify.info("enter%s: '%s' -> '%s', elapsedTime:%s" % (self.newState, self.oldState, self.newState, elapsedTime)) self.chargeUpAttackSeq.start(elapsedTime) messenger.send(CogdoFlyingLegalEagle.ChargingToAttackEventName, [self.target.doId]) def filterChargeUpAttack(self, request, args): self.notify.debug("filter%s( '%s', '%s' )" % (self.state, request, args)) if request == self.state: return None elif request == 'next': if self.hasTarget(): return 'Attack' else: return 'RetreatToNest' else: return self.defaultFilter(request, args) return None def exitChargeUpAttack(self): self.notify.debug("exit%s: '%s' -> '%s'" % (self.oldState, self.oldState, self.newState)) self.chargeUpAttackSeq.clearToInitial() def enterAttack(self, elapsedTime = 0.0): self.notify.info("enter%s: '%s' -> '%s', elapsedTime:%s" % (self.newState, self.oldState, self.newState, elapsedTime)) self.attackTargetPos = self.target.getPos(render) targetState = self.target.animFSM.getCurrentState().getName() self._screamSfx.play() if targetState == 'jumpAirborne': self.attackTargetPos[2] += Globals.LegalEagle.VerticalOffset else: self.attackTargetPos[2] += Globals.LegalEagle.PlatformVerticalOffset self.readyToAttackPos = self.suit.getPos(render) self.attackSeq.start(elapsedTime) def filterAttack(self, request, args): self.notify.debug("filter%s( '%s', '%s' )" % (self.state, request, args)) if request == self.state: return None elif request == 'next': return 'RetreatToSky' else: return self.defaultFilter(request, args) return None def exitAttack(self): self.notify.debug("exit%s: '%s' -> '%s'" % (self.oldState, self.oldState, self.newState)) self.attackSeq.clearToInitial() taskMgr.remove('updateAttackPosTask-%i' % self.index) def enterRetreatToSky(self, elapsedTime = 0.0): self.notify.info("enter%s: '%s' -> '%s', elapsedTime:%s" % (self.newState, self.oldState, self.newState, elapsedTime)) self.retreatToSkySeq.start(elapsedTime) def filterRetreatToSky(self, request, args): self.notify.debug("filter%s( '%s', '%s' )" % (self.state, request, args)) if request == self.state: return None elif request == 'next': return 'Cooldown' else: return self.defaultFilter(request, args) return None def exitRetreatToSky(self): self.notify.debug("exit%s: '%s' -> '%s'" % (self.oldState, self.oldState, self.newState)) self.retreatToSkySeq.clearToInitial() def enterCooldown(self): if self.target != None: messenger.send(CogdoFlyingLegalEagle.CooldownEventName, [self.target.doId]) self.suit.stash() self.notify.info("enter%s: '%s' -> '%s'" % (self.newState, self.oldState, self.newState)) return def filterCooldown(self, request, args): self.notify.debug("filter%s( '%s', '%s' )" % (self.state, request, args)) if request == self.state: return None elif request == 'next': if self.hasTarget(): return 'LockOnToon' else: return 'LandOnNest' else: return self.defaultFilter(request, args) return None def exitCooldown(self): self.notify.debug("exit%s: '%s' -> '%s'" % (self.oldState, self.oldState, self.newState)) self.suit.unstash() self.cooldownSeq.clearToInitial() if self.newState != 'Off': heightOffNest = Globals.LegalEagle.PostCooldownHeightOffNest nestPos = self.nest.getPos(render) if self.newState in ['LandOnNest']: self.suit.setPos(nestPos + Vec3(0, 0, heightOffNest)) else: targetPos = self.target.getPos(render) attackPos = Vec3(targetPos) attackPos[1] = nestPos[1] attackPos[2] = nestPos[2] + heightOffNest self.suit.setPos(attackPos) def enterRetreatToNest(self, elapsedTime = 0.0): self.notify.info("enter%s: '%s' -> '%s', elapsedTime:%s" % (self.newState, self.oldState, self.newState, elapsedTime)) self.retreatToNestSeq.start(elapsedTime) def filterRetreatToNest(self, request, args): self.notify.debug("filter%s( '%s', '%s' )" % (self.state, request, args)) if request == self.state: return None elif request == 'next': return 'LandOnNest' else: return self.defaultFilter(request, args) return None def exitRetreatToNest(self): self.retreatToNestSeq.clearToInitial() def enterLandOnNest(self, elapsedTime = 0.0): self.notify.info("enter%s: '%s' -> '%s', elapsedTime:%s" % (self.newState, self.oldState, self.newState, elapsedTime)) self.landingSeq.start(elapsedTime) def filterLandOnNest(self, request, args): self.notify.debug("filter%s( '%s', '%s' )" % (self.state, request, args)) if request == self.state: return None elif request == 'next': if self.hasTarget(): return 'TakeOff' else: return 'Roost' else: return self.defaultFilter(request, args) return None def exitLandOnNest(self): self.landingSeq.clearToInitial()
1
0.688552
1
0.688552
game-dev
MEDIA
0.874013
game-dev
0.898045
1
0.898045
ShenZhenAccelerationTechCo/Tdrone
2,205
software/OpenPilot-RELEASE-15.02.02/ground/openpilotgcs/src/plugins/opmap/modeluavoproxy.h
/** ****************************************************************************** * * @file modeluavproxy.h * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2012. * @addtogroup GCSPlugins GCS Plugins * @{ * @addtogroup OPMapPlugin OpenPilot Map Plugin * @{ * @brief The OpenPilot Map plugin *****************************************************************************/ /* * 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, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef MODELUAVOPROXY_H #define MODELUAVOPROXY_H #include "flightdatamodel.h" #include "pathplan.h" #include "pathaction.h" #include "waypoint.h" #include <QObject> class ModelUavoProxy : public QObject { Q_OBJECT public: explicit ModelUavoProxy(QObject *parent, flightDataModel *model); public slots: void sendPathPlan(); void receivePathPlan(); private: UAVObjectManager *objMngr; flightDataModel *myModel; bool modelToObjects(); bool objectsToModel(); Waypoint *createWaypoint(int index, Waypoint *newWaypoint); PathAction *createPathAction(int index, PathAction *newAction); PathAction *findPathAction(const PathAction::DataFields & actionFields, int actionCount); void modelToWaypoint(int i, Waypoint::DataFields &data); void modelToPathAction(int i, PathAction::DataFields &data); void waypointToModel(int i, Waypoint::DataFields &data); void pathActionToModel(int i, PathAction::DataFields &data); quint8 computePathPlanCrc(int waypointCount, int actionCount); }; #endif // MODELUAVOPROXY_H
1
0.828784
1
0.828784
game-dev
MEDIA
0.133627
game-dev
0.523094
1
0.523094
hakan-krgn/hCore
5,913
hCore-bukkit/nms/v1_9_R2/src/main/java/com/hakan/core/border/versions/Border_v1_9_R2.java
package com.hakan.core.border.versions; import com.hakan.core.HCore; import com.hakan.core.border.Border; import com.hakan.core.border.BorderHandler; import com.hakan.core.border.color.BorderColor; import com.hakan.core.scheduler.Scheduler; import com.hakan.core.utils.Validate; import net.minecraft.server.v1_9_R2.PacketPlayOutWorldBorder; import net.minecraft.server.v1_9_R2.WorldBorder; import org.bukkit.Location; import org.bukkit.craftbukkit.v1_9_R2.CraftWorld; import org.bukkit.entity.Player; import javax.annotation.Nonnull; import java.util.concurrent.TimeUnit; /** * {@inheritDoc} */ public final class Border_v1_9_R2 implements Border { private final Player viewer; private final WorldBorder border; private final Scheduler scheduler; private BorderColor color; private boolean transition; /** * {@inheritDoc} */ private Border_v1_9_R2(@Nonnull Player viewer, @Nonnull Location location, @Nonnull BorderColor color, double size, double damageAmount, double damageBuffer, int warningDistance, int warningTime) { this.scheduler = HCore.syncScheduler(); this.viewer = Validate.notNull(viewer, "viewer cannot be null!"); this.color = Validate.notNull(color, "border color cannot be null!"); this.border = new WorldBorder(); this.border.world = ((CraftWorld) location.getWorld()).getHandle(); this.border.setSize(size); this.border.setWarningTime(warningTime); this.border.setDamageAmount(damageAmount); this.border.setDamageBuffer(damageBuffer); this.border.setWarningDistance(warningDistance); this.border.setCenter(location.getX(), location.getZ()); this.border.world = ((CraftWorld) location.getWorld()).getHandle(); this.update(); } /** * {@inheritDoc} */ @Nonnull @Override public Player getViewer() { return this.viewer; } /** * {@inheritDoc} */ @Nonnull @Override public Location getCenter() { return new Location(this.border.world.getWorld(), this.border.getCenterX(), 64, this.border.getCenterZ()); } /** * {@inheritDoc} */ @Override public void setCenter(@Nonnull Location location) { Validate.notNull(location, "location cannot be null!"); this.border.setCenter(location.getX(), location.getZ()); } /** * {@inheritDoc} */ @Nonnull @Override public BorderColor getColor() { return this.color; } /** * {@inheritDoc} */ @Override public void setColor(@Nonnull BorderColor borderColor) { this.color = Validate.notNull(borderColor, "border color cannot be null!"); } /** * {@inheritDoc} */ @Override public double getDamageAmount() { return this.border.getDamageAmount(); } /** * {@inheritDoc} */ @Override public void setDamageAmount(double damageAmount) { this.border.setDamageAmount(damageAmount); } /** * {@inheritDoc} */ @Override public double getDamageBuffer() { return this.border.getDamageBuffer(); } /** * {@inheritDoc} */ @Override public void setDamageBuffer(double damageBuffer) { this.border.setDamageBuffer(damageBuffer); } /** * {@inheritDoc} */ @Override public int getWarningDistance() { return this.border.getWarningDistance(); } /** * {@inheritDoc} */ @Override public void setWarningDistance(int warningDistance) { this.border.setWarningDistance(warningDistance); } /** * {@inheritDoc} */ @Override public int getWarningTime() { return this.border.getWarningTime(); } /** * {@inheritDoc} */ @Override public void setWarningTime(int warningTime) { this.border.setWarningTime(warningTime); } /** * {@inheritDoc} */ @Override public double getSize() { return this.border.getSize(); } /** * {@inheritDoc} */ @Override public void setSize(double size, long time) { if (this.transition) this.scheduler.cancel(); this.scheduler.after(time, TimeUnit.MILLISECONDS) .run(() -> this.transition = false); this.transition = true; this.border.transitionSizeBetween(this.getSize(), size, time); } /** * {@inheritDoc} */ @Override public void update() { if (!this.transition) if (this.color == BorderColor.BLUE) this.border.transitionSizeBetween(this.getSize(), this.getSize(), Long.MAX_VALUE); else if (this.color == BorderColor.GREEN) this.border.transitionSizeBetween(this.getSize(), this.getSize() + 0.1, Long.MAX_VALUE); else if (this.color == BorderColor.RED) this.border.transitionSizeBetween(this.getSize(), this.getSize() - 0.1, Long.MAX_VALUE); HCore.sendPacket(this.viewer, new PacketPlayOutWorldBorder(this.border, PacketPlayOutWorldBorder.EnumWorldBorderAction.INITIALIZE)); } /** * {@inheritDoc} */ @Override public void delete() { this.setSize(6.0E7); this.setWarningTime(15); this.setDamageAmount(0.2); this.setDamageBuffer(5.0); this.setWarningDistance(5); this.setCenter(new Location(this.border.world.getWorld(), 0, 64, 0)); HCore.sendPacket(this.viewer, new PacketPlayOutWorldBorder(this.border, PacketPlayOutWorldBorder.EnumWorldBorderAction.INITIALIZE)); BorderHandler.getContent().remove(this.viewer); } }
1
0.92237
1
0.92237
game-dev
MEDIA
0.382721
game-dev
0.881665
1
0.881665
Rockbox/rockbox
30,716
apps/plugins/doom/p_saveg.c
/* Emacs style mode select -*- C++ -*- *----------------------------------------------------------------------------- * * * PrBoom a Doom port merged with LxDoom and LSDLDoom * based on BOOM, a modified and improved DOOM engine * Copyright (C) 1999 by * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman * Copyright (C) 1999-2000 by * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze * * 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. * * DESCRIPTION: * Archiving: SaveGame I/O. * *-----------------------------------------------------------------------------*/ #include "doomstat.h" #include "r_main.h" #include "p_maputl.h" #include "p_spec.h" #include "p_tick.h" #include "p_saveg.h" #include "m_random.h" #include "am_map.h" #include "p_enemy.h" #include "i_system.h" #include "rockmacros.h" byte *save_p; // Pads save_p to a 4-byte boundary // so that the load/save works on SGI&Gecko. #define PADSAVEP() do { save_p += (4 - ((intptr_t) save_p & 3)) & 3; } while (0) // // P_ArchivePlayers // void P_ArchivePlayers (void) { int i; CheckSaveGame(sizeof(player_t) * MAXPLAYERS); // killough for (i=0 ; i<MAXPLAYERS ; i++) if (playeringame[i]) { int j; player_t *dest; PADSAVEP(); dest = (player_t *) save_p; memcpy(dest, &players[i], sizeof(player_t)); save_p += sizeof(player_t); for (j=0; j<NUMPSPRITES; j++) if (dest->psprites[j].state) dest->psprites[j].state = (state_t *)(dest->psprites[j].state-states); } } // // P_UnArchivePlayers // void P_UnArchivePlayers (void) { int i; for (i=0 ; i<MAXPLAYERS ; i++) if (playeringame[i]) { int j; PADSAVEP(); memcpy(&players[i], save_p, sizeof(player_t)); save_p += sizeof(player_t); // will be set when unarc thinker players[i].mo = NULL; players[i].message = NULL; players[i].attacker = NULL; for (j=0 ; j<NUMPSPRITES ; j++) if (players[i]. psprites[j].state) players[i]. psprites[j].state = &states[ (intptr_t)players[i].psprites[j].state ]; } } // // P_ArchiveWorld // void P_ArchiveWorld (void) { int i; const sector_t *sec; const line_t *li; const side_t *si; short *put; // killough 3/22/98: fix bug caused by hoisting save_p too early // killough 10/98: adjust size for changes below size_t size = (sizeof(short)*5 + sizeof sec->floorheight + sizeof sec->ceilingheight) * numsectors + sizeof(short)*3*numlines + 4; for (i=0; i<numlines; i++) { if (lines[i].sidenum[0] != -1) size += sizeof(short)*3 + sizeof si->textureoffset + sizeof si->rowoffset; if (lines[i].sidenum[1] != -1) size += sizeof(short)*3 + sizeof si->textureoffset + sizeof si->rowoffset; } CheckSaveGame(size); // killough PADSAVEP(); // killough 3/22/98 put = (short *)save_p; // do sectors for (i=0, sec = sectors ; i<numsectors ; i++,sec++) { // killough 10/98: save full floor & ceiling heights, including fraction memcpy(put, &sec->floorheight, sizeof sec->floorheight); put = (void *)((char *) put + sizeof sec->floorheight); memcpy(put, &sec->ceilingheight, sizeof sec->ceilingheight); put = (void *)((char *) put + sizeof sec->ceilingheight); *put++ = sec->floorpic; *put++ = sec->ceilingpic; *put++ = sec->lightlevel; *put++ = sec->special; // needed? yes -- transfer types *put++ = sec->tag; // needed? need them -- killough } // do lines for (i=0, li = lines ; i<numlines ; i++,li++) { int j; *put++ = li->flags; *put++ = li->special; *put++ = li->tag; for (j=0; j<2; j++) if (li->sidenum[j] != -1) { si = &sides[li->sidenum[j]]; // killough 10/98: save full sidedef offsets, // preserving fractional scroll offsets memcpy(put, &si->textureoffset, sizeof si->textureoffset); put = (void *)((char *) put + sizeof si->textureoffset); memcpy(put, &si->rowoffset, sizeof si->rowoffset); put = (void *)((char *) put + sizeof si->rowoffset); *put++ = si->toptexture; *put++ = si->bottomtexture; *put++ = si->midtexture; } } save_p = (byte *) put; } // // P_UnArchiveWorld // void P_UnArchiveWorld (void) { int i; sector_t *sec; line_t *li; const short *get; PADSAVEP(); // killough 3/22/98 get = (short *) save_p; // do sectors for (i=0, sec = sectors ; i<numsectors ; i++,sec++) { // killough 10/98: load full floor & ceiling heights, including fractions memcpy(&sec->floorheight, get, sizeof sec->floorheight); get = (void *)((char *) get + sizeof sec->floorheight); memcpy(&sec->ceilingheight, get, sizeof sec->ceilingheight); get = (void *)((char *) get + sizeof sec->ceilingheight); sec->floorpic = *get++; sec->ceilingpic = *get++; sec->lightlevel = *get++; sec->special = *get++; sec->tag = *get++; sec->ceilingdata = 0; //jff 2/22/98 now three thinker fields, not two sec->floordata = 0; sec->lightingdata = 0; sec->soundtarget = 0; } // do lines for (i=0, li = lines ; i<numlines ; i++,li++) { int j; li->flags = *get++; li->special = *get++; li->tag = *get++; for (j=0 ; j<2 ; j++) if (li->sidenum[j] != -1) { side_t *si = &sides[li->sidenum[j]]; // killough 10/98: load full sidedef offsets, including fractions memcpy(&si->textureoffset, get, sizeof si->textureoffset); get = (void *)((char *) get + sizeof si->textureoffset); memcpy(&si->rowoffset, get, sizeof si->rowoffset); get = (void *)((char *) get + sizeof si->rowoffset); si->toptexture = *get++; si->bottomtexture = *get++; si->midtexture = *get++; } } save_p = (byte *) get; } // // Thinkers // enum { tc_end, tc_mobj }; typedef unsigned thinkerclass_t; // phares 9/13/98: Moved this code outside of P_ArchiveThinkers so the // thinker indices could be used by the code that saves sector info. static int number_of_thinkers; void P_ThinkerToIndex(void) { thinker_t *th; // killough 2/14/98: // count the number of thinkers, and mark each one with its index, using // the prev field as a placeholder, since it can be restored later. number_of_thinkers = 0; for (th = thinkercap.next ; th != &thinkercap ; th=th->next) if (th->function == P_MobjThinker) th->prev = (thinker_t *)(intptr_t)(++number_of_thinkers); } // phares 9/13/98: Moved this code outside of P_ArchiveThinkers so the // thinker indices could be used by the code that saves sector info. void P_IndexToThinker(void) { // killough 2/14/98: restore prev pointers thinker_t *th; thinker_t *prev = &thinkercap; for (th = thinkercap.next ; th != &thinkercap ; prev=th, th=th->next) th->prev = prev; } // // P_ArchiveThinkers // // 2/14/98 killough: substantially modified to fix savegame bugs void P_ArchiveThinkers (void) { thinker_t *th; CheckSaveGame(sizeof brain); // killough 3/26/98: Save boss brain state memcpy(save_p, &brain, sizeof brain); save_p += sizeof brain; /* check that enough room is available in savegame buffer * - killough 2/14/98 * cph - use number_of_thinkers saved by P_ThinkerToIndex above */ CheckSaveGame(number_of_thinkers*(sizeof(mobj_t)+4)); // save off the current thinkers for (th = thinkercap.next ; th != &thinkercap ; th=th->next) if (th->function == P_MobjThinker) { mobj_t *mobj; *save_p++ = tc_mobj; PADSAVEP(); mobj = (mobj_t *)save_p; memcpy (mobj, th, sizeof(*mobj)); save_p += sizeof(*mobj); mobj->state = (state_t *)(mobj->state - states); // killough 2/14/98: convert pointers into indices. // Fixes many savegame problems, by properly saving // target and tracer fields. Note: we store NULL if // the thinker pointed to by these fields is not a // mobj thinker. if (mobj->target) mobj->target = mobj->target->thinker.function == P_MobjThinker ? (mobj_t *) mobj->target->thinker.prev : NULL; if (mobj->tracer) mobj->tracer = mobj->tracer->thinker.function == P_MobjThinker ? (mobj_t *) mobj->tracer->thinker.prev : NULL; // killough 2/14/98: new field: save last known enemy. Prevents // monsters from going to sleep after killing monsters and not // seeing player anymore. if (mobj->lastenemy) mobj->lastenemy = mobj->lastenemy->thinker.function == P_MobjThinker ? (mobj_t *) mobj->lastenemy->thinker.prev : NULL; // killough 2/14/98: end changes if (mobj->above_thing) // phares mobj->above_thing = mobj->above_thing->thinker.function == P_MobjThinker ? (mobj_t *) mobj->above_thing->thinker.prev : NULL; if (mobj->below_thing) mobj->below_thing = mobj->below_thing->thinker.function == P_MobjThinker ? (mobj_t *) mobj->below_thing->thinker.prev : NULL; // phares if (mobj->player) mobj->player = (player_t *)((mobj->player-players) + 1); } // add a terminating marker *save_p++ = tc_end; // killough 9/14/98: save soundtargets { int i; CheckSaveGame(numsectors * sizeof(mobj_t *)); // killough 9/14/98 for (i = 0; i < numsectors; i++) { mobj_t *target = sectors[i].soundtarget; if (target) target = (mobj_t *) target->thinker.prev; memcpy(save_p, &target, sizeof target); save_p += sizeof target; } } } /* * killough 11/98 * * Same as P_SetTarget() in p_tick.c, except that the target is nullified * first, so that no old target's reference count is decreased (when loading * savegames, old targets are indices, not really pointers to targets). */ static void P_SetNewTarget(mobj_t **mop, mobj_t *targ) { *mop = NULL; P_SetTarget(mop, targ); } // // P_UnArchiveThinkers // // 2/14/98 killough: substantially modified to fix savegame bugs // void P_UnArchiveThinkers (void) { thinker_t *th; mobj_t **mobj_p; // killough 2/14/98: Translation table size_t size; // killough 2/14/98: size of or index into table totallive = 0; // killough 3/26/98: Load boss brain state memcpy(&brain, save_p, sizeof brain); save_p += sizeof brain; // remove all the current thinkers for (th = thinkercap.next; th != &thinkercap; ) { thinker_t *next = th->next; if (th->function == P_MobjThinker) P_RemoveMobj ((mobj_t *) th); else Z_Free (th); th = next; } P_InitThinkers (); // killough 2/14/98: count number of thinkers by skipping through them { byte *sp = save_p; // save pointer and skip header for (size = 1; *save_p++ == tc_mobj; size++) // killough 2/14/98 { // skip all entries, adding up count PADSAVEP(); save_p += sizeof(mobj_t); } if (*--save_p != tc_end) I_Error ("P_UnArchiveThinkers: Unknown tclass %i in savegame", *save_p); // first table entry special: 0 maps to NULL *(mobj_p = malloc(size * sizeof *mobj_p)) = 0; // table of pointers save_p = sp; // restore save pointer } // read in saved thinkers for (size = 1; *save_p++ == tc_mobj; size++) // killough 2/14/98 { mobj_t *mobj = Z_Malloc(sizeof(mobj_t), PU_LEVEL, NULL); // killough 2/14/98 -- insert pointers to thinkers into table, in order: mobj_p[size] = mobj; PADSAVEP(); memcpy (mobj, save_p, sizeof(mobj_t)); save_p += sizeof(mobj_t); mobj->state = states + (intptr_t) mobj->state; if (mobj->player) (mobj->player = &players[(intptr_t) mobj->player - 1]) -> mo = mobj; P_SetThingPosition (mobj); mobj->info = &mobjinfo[mobj->type]; // killough 2/28/98: // Fix for falling down into a wall after savegame loaded: // mobj->floorz = mobj->subsector->sector->floorheight; // mobj->ceilingz = mobj->subsector->sector->ceilingheight; mobj->thinker.function = P_MobjThinker; P_AddThinker (&mobj->thinker); if (!((mobj->flags ^ MF_COUNTKILL) & (MF_FRIEND | MF_COUNTKILL | MF_CORPSE))) totallive++; } // killough 2/14/98: adjust target and tracer fields, plus // lastenemy field, to correctly point to mobj thinkers. // NULL entries automatically handled by first table entry. // // killough 11/98: use P_SetNewTarget() to set fields for (th = thinkercap.next ; th != &thinkercap ; th=th->next) { P_SetNewTarget(&((mobj_t *) th)->target, mobj_p[(size_t)((mobj_t *)th)->target]); P_SetNewTarget(&((mobj_t *) th)->tracer, mobj_p[(size_t)((mobj_t *)th)->tracer]); P_SetNewTarget(&((mobj_t *) th)->lastenemy, mobj_p[(size_t)((mobj_t *)th)->lastenemy]); // phares: added two new fields for Sprite Height problem P_SetNewTarget(&((mobj_t *) th)->above_thing, mobj_p[(size_t)((mobj_t *)th)->above_thing]); P_SetNewTarget(&((mobj_t *) th)->below_thing, mobj_p[(size_t)((mobj_t *)th)->below_thing]); } { // killough 9/14/98: restore soundtargets int i; for (i = 0; i < numsectors; i++) { mobj_t *target; memcpy(&target, save_p, sizeof target); save_p += sizeof target; P_SetNewTarget(&sectors[i].soundtarget, mobj_p[(size_t) target]); } } free(mobj_p); // free translation table // killough 3/26/98: Spawn icon landings: if (gamemode == commercial) P_SpawnBrainTargets(); } // // P_ArchiveSpecials // enum { tc_ceiling, tc_door, tc_floor, tc_plat, tc_flash, tc_strobe, tc_glow, tc_elevator, //jff 2/22/98 new elevator type thinker tc_scroll, // killough 3/7/98: new scroll effect thinker tc_pusher, // phares 3/22/98: new push/pull effect thinker tc_flicker, // killough 10/4/98 tc_endspecials }; unsigned specials_e; // // Things to handle: // // T_MoveCeiling, (ceiling_t: sector_t * swizzle), - active list // T_VerticalDoor, (vldoor_t: sector_t * swizzle), // T_MoveFloor, (floormove_t: sector_t * swizzle), // T_LightFlash, (lightflash_t: sector_t * swizzle), // T_StrobeFlash, (strobe_t: sector_t *), // T_Glow, (glow_t: sector_t *), // T_PlatRaise, (plat_t: sector_t *), - active list // T_MoveElevator, (plat_t: sector_t *), - active list // jff 2/22/98 // T_Scroll // killough 3/7/98 // T_Pusher // phares 3/22/98 // T_FireFlicker // killough 10/4/98 // void P_ArchiveSpecials (void) { thinker_t *th; size_t size = 0; // killough // save off the current thinkers (memory size calculation -- killough) for (th = thinkercap.next ; th != &thinkercap ; th=th->next) if (!th->function) { platlist_t *pl; ceilinglist_t *cl; //jff 2/22/98 need this for ceilings too now for (pl=activeplats; pl; pl=pl->next) if (pl->plat == (plat_t *) th) // killough 2/14/98 { size += 4+sizeof(plat_t); goto end; } for (cl=activeceilings; cl; cl=cl->next) // search for activeceiling if (cl->ceiling == (ceiling_t *) th) //jff 2/22/98 { size += 4+sizeof(ceiling_t); goto end; } end:; } else size += th->function==T_MoveCeiling ? 4+sizeof(ceiling_t) : th->function==T_VerticalDoor ? 4+sizeof(vldoor_t) : th->function==T_MoveFloor ? 4+sizeof(floormove_t): th->function==T_PlatRaise ? 4+sizeof(plat_t) : th->function==T_LightFlash ? 4+sizeof(lightflash_t): th->function==T_StrobeFlash ? 4+sizeof(strobe_t) : th->function==T_Glow ? 4+sizeof(glow_t) : th->function==T_MoveElevator ? 4+sizeof(elevator_t): th->function==T_Scroll ? 4+sizeof(scroll_t) : th->function==T_Pusher ? 4+sizeof(pusher_t) : th->function==T_FireFlicker? 4+sizeof(fireflicker_t) : 0; CheckSaveGame(size); // killough // save off the current thinkers for (th=thinkercap.next; th!=&thinkercap; th=th->next) { if (!th->function) { platlist_t *pl; ceilinglist_t *cl; //jff 2/22/98 add iter variable for ceilings // killough 2/8/98: fix plat original height bug. // Since acv==NULL, this could be a plat in stasis. // so check the active plats list, and save this // plat (jff: or ceiling) even if it is in stasis. for (pl=activeplats; pl; pl=pl->next) if (pl->plat == (plat_t *) th) // killough 2/14/98 goto plat; for (cl=activeceilings; cl; cl=cl->next) if (cl->ceiling == (ceiling_t *) th) //jff 2/22/98 goto ceiling; continue; } if (th->function == T_MoveCeiling) { ceiling_t *ceiling; ceiling: // killough 2/14/98 *save_p++ = tc_ceiling; PADSAVEP(); ceiling = (ceiling_t *)save_p; memcpy (ceiling, th, sizeof(*ceiling)); save_p += sizeof(*ceiling); ceiling->sector = (sector_t *)(ceiling->sector - sectors); continue; } if (th->function == T_VerticalDoor) { vldoor_t *door; *save_p++ = tc_door; PADSAVEP(); door = (vldoor_t *) save_p; memcpy (door, th, sizeof *door); save_p += sizeof(*door); door->sector = (sector_t *)(door->sector - sectors); //jff 1/31/98 archive line remembered by door as well door->line = (line_t *) (door->line ? door->line-lines : -1); continue; } if (th->function == T_MoveFloor) { floormove_t *floor; *save_p++ = tc_floor; PADSAVEP(); floor = (floormove_t *)save_p; memcpy (floor, th, sizeof(*floor)); save_p += sizeof(*floor); floor->sector = (sector_t *)(floor->sector - sectors); continue; } if (th->function == T_PlatRaise) { plat_t *plat; plat: // killough 2/14/98: added fix for original plat height above *save_p++ = tc_plat; PADSAVEP(); plat = (plat_t *)save_p; memcpy (plat, th, sizeof(*plat)); save_p += sizeof(*plat); plat->sector = (sector_t *)(plat->sector - sectors); continue; } if (th->function == T_LightFlash) { lightflash_t *flash; *save_p++ = tc_flash; PADSAVEP(); flash = (lightflash_t *)save_p; memcpy (flash, th, sizeof(*flash)); save_p += sizeof(*flash); flash->sector = (sector_t *)(flash->sector - sectors); continue; } if (th->function == T_StrobeFlash) { strobe_t *strobe; *save_p++ = tc_strobe; PADSAVEP(); strobe = (strobe_t *)save_p; memcpy (strobe, th, sizeof(*strobe)); save_p += sizeof(*strobe); strobe->sector = (sector_t *)(strobe->sector - sectors); continue; } if (th->function == T_Glow) { glow_t *glow; *save_p++ = tc_glow; PADSAVEP(); glow = (glow_t *)save_p; memcpy (glow, th, sizeof(*glow)); save_p += sizeof(*glow); glow->sector = (sector_t *)(glow->sector - sectors); continue; } // killough 10/4/98: save flickers if (th->function == T_FireFlicker) { fireflicker_t *flicker; *save_p++ = tc_flicker; PADSAVEP(); flicker = (fireflicker_t *)save_p; memcpy (flicker, th, sizeof(*flicker)); save_p += sizeof(*flicker); flicker->sector = (sector_t *)(flicker->sector - sectors); continue; } //jff 2/22/98 new case for elevators if (th->function == T_MoveElevator) { elevator_t *elevator; //jff 2/22/98 *save_p++ = tc_elevator; PADSAVEP(); elevator = (elevator_t *)save_p; memcpy (elevator, th, sizeof(*elevator)); save_p += sizeof(*elevator); elevator->sector = (sector_t *)(elevator->sector - sectors); continue; } // killough 3/7/98: Scroll effect thinkers if (th->function == T_Scroll) { *save_p++ = tc_scroll; memcpy (save_p, th, sizeof(scroll_t)); save_p += sizeof(scroll_t); continue; } // phares 3/22/98: Push/Pull effect thinkers if (th->function == T_Pusher) { *save_p++ = tc_pusher; memcpy (save_p, th, sizeof(pusher_t)); save_p += sizeof(pusher_t); continue; } } // add a terminating marker *save_p++ = tc_endspecials; } // // P_UnArchiveSpecials // void P_UnArchiveSpecials (void) { byte tclass; // read in saved thinkers while ((tclass = *save_p++) != tc_endspecials) // killough 2/14/98 switch (tclass) { case tc_ceiling: PADSAVEP(); { ceiling_t *ceiling = Z_Malloc (sizeof(*ceiling), PU_LEVEL, NULL); memcpy (ceiling, save_p, sizeof(*ceiling)); save_p += sizeof(*ceiling); ceiling->sector = &sectors[(intptr_t)ceiling->sector]; ceiling->sector->ceilingdata = ceiling; //jff 2/22/98 if (ceiling->thinker.function) ceiling->thinker.function = T_MoveCeiling; P_AddThinker (&ceiling->thinker); P_AddActiveCeiling(ceiling); break; } case tc_door: PADSAVEP(); { vldoor_t *door = Z_Malloc (sizeof(*door), PU_LEVEL, NULL); memcpy (door, save_p, sizeof(*door)); save_p += sizeof(*door); door->sector = &sectors[(intptr_t)door->sector]; //jff 1/31/98 unarchive line remembered by door as well door->line = (intptr_t)door->line!=-1? &lines[(intptr_t)door->line] : NULL; door->sector->ceilingdata = door; //jff 2/22/98 door->thinker.function = T_VerticalDoor; P_AddThinker (&door->thinker); break; } case tc_floor: PADSAVEP(); { floormove_t *floor = Z_Malloc (sizeof(*floor), PU_LEVEL, NULL); memcpy (floor, save_p, sizeof(*floor)); save_p += sizeof(*floor); floor->sector = &sectors[(intptr_t)floor->sector]; floor->sector->floordata = floor; //jff 2/22/98 floor->thinker.function = T_MoveFloor; P_AddThinker (&floor->thinker); break; } case tc_plat: PADSAVEP(); { plat_t *plat = Z_Malloc (sizeof(*plat), PU_LEVEL, NULL); memcpy (plat, save_p, sizeof(*plat)); save_p += sizeof(*plat); plat->sector = &sectors[(intptr_t)plat->sector]; plat->sector->floordata = plat; //jff 2/22/98 if (plat->thinker.function) plat->thinker.function = T_PlatRaise; P_AddThinker (&plat->thinker); P_AddActivePlat(plat); break; } case tc_flash: PADSAVEP(); { lightflash_t *flash = Z_Malloc (sizeof(*flash), PU_LEVEL, NULL); memcpy (flash, save_p, sizeof(*flash)); save_p += sizeof(*flash); flash->sector = &sectors[(intptr_t)flash->sector]; flash->thinker.function = T_LightFlash; P_AddThinker (&flash->thinker); break; } case tc_strobe: PADSAVEP(); { strobe_t *strobe = Z_Malloc (sizeof(*strobe), PU_LEVEL, NULL); memcpy (strobe, save_p, sizeof(*strobe)); save_p += sizeof(*strobe); strobe->sector = &sectors[(intptr_t)strobe->sector]; strobe->thinker.function = T_StrobeFlash; P_AddThinker (&strobe->thinker); break; } case tc_glow: PADSAVEP(); { glow_t *glow = Z_Malloc (sizeof(*glow), PU_LEVEL, NULL); memcpy (glow, save_p, sizeof(*glow)); save_p += sizeof(*glow); glow->sector = &sectors[(intptr_t)glow->sector]; glow->thinker.function = T_Glow; P_AddThinker (&glow->thinker); break; } case tc_flicker: // killough 10/4/98 PADSAVEP(); { fireflicker_t *flicker = Z_Malloc (sizeof(*flicker), PU_LEVEL, NULL); memcpy (flicker, save_p, sizeof(*flicker)); save_p += sizeof(*flicker); flicker->sector = &sectors[(intptr_t)flicker->sector]; flicker->thinker.function = T_FireFlicker; P_AddThinker (&flicker->thinker); break; } //jff 2/22/98 new case for elevators case tc_elevator: PADSAVEP(); { elevator_t *elevator = Z_Malloc (sizeof(*elevator), PU_LEVEL, NULL); memcpy (elevator, save_p, sizeof(*elevator)); save_p += sizeof(*elevator); elevator->sector = &sectors[(intptr_t)elevator->sector]; elevator->sector->floordata = elevator; //jff 2/22/98 elevator->sector->ceilingdata = elevator; //jff 2/22/98 elevator->thinker.function = T_MoveElevator; P_AddThinker (&elevator->thinker); break; } case tc_scroll: // killough 3/7/98: scroll effect thinkers { scroll_t *scroll = Z_Malloc (sizeof(scroll_t), PU_LEVEL, NULL); memcpy (scroll, save_p, sizeof(scroll_t)); save_p += sizeof(scroll_t); scroll->thinker.function = T_Scroll; P_AddThinker(&scroll->thinker); break; } case tc_pusher: // phares 3/22/98: new Push/Pull effect thinkers { pusher_t *pusher = Z_Malloc (sizeof(pusher_t), PU_LEVEL, NULL); memcpy (pusher, save_p, sizeof(pusher_t)); save_p += sizeof(pusher_t); pusher->thinker.function = T_Pusher; pusher->source = P_GetPushThing(pusher->affectee); P_AddThinker(&pusher->thinker); break; } default: I_Error("P_UnarchiveSpecials: Unknown tclass %i in savegame", tclass); } } // killough 2/16/98: save/restore random number generator state information void P_ArchiveRNG(void) { CheckSaveGame(sizeof rng); memcpy(save_p, &rng, sizeof rng); save_p += sizeof rng; } void P_UnArchiveRNG(void) { memcpy(&rng, save_p, sizeof rng); save_p += sizeof rng; } // killough 2/22/98: Save/restore automap state // killough 2/22/98: Save/restore automap state void P_ArchiveMap(void) { int zero = 0, one = 1; CheckSaveGame(2 * sizeof zero + sizeof markpointnum + markpointnum * sizeof *markpoints + sizeof automapmode + sizeof one); memcpy(save_p, &automapmode, sizeof automapmode); save_p += sizeof automapmode; memcpy(save_p, &one, sizeof one); // CPhipps - used to be viewactive, now save_p += sizeof one; // that's worked out locally by D_Display memcpy(save_p, &zero, sizeof zero); // CPhipps - used to be followplayer save_p += sizeof zero; // that is now part of automapmode memcpy(save_p, &zero, sizeof zero); // CPhipps - used to be automap_grid, ditto save_p += sizeof zero; memcpy(save_p, &markpointnum, sizeof markpointnum); save_p += sizeof markpointnum; if (markpointnum) { memcpy(save_p, markpoints, sizeof *markpoints * markpointnum); save_p += markpointnum * sizeof *markpoints; } } void P_UnArchiveMap(void) { int unused; memcpy(&automapmode, save_p, sizeof automapmode); save_p += sizeof automapmode; memcpy(&unused, save_p, sizeof unused); save_p += sizeof unused; memcpy(&unused, save_p, sizeof unused); save_p += sizeof unused; memcpy(&unused, save_p, sizeof unused); save_p += sizeof unused; if (automapmode & am_active) AM_Start(); memcpy(&markpointnum, save_p, sizeof markpointnum); save_p += sizeof markpointnum; if (markpointnum) { while (markpointnum >= markpointnum_max) markpoints = realloc(markpoints, sizeof *markpoints * (markpointnum_max = markpointnum_max ? markpointnum_max*2 : 16)); memcpy(markpoints, save_p, markpointnum * sizeof *markpoints); save_p += markpointnum * sizeof *markpoints; } }
1
0.895028
1
0.895028
game-dev
MEDIA
0.663548
game-dev
0.949302
1
0.949302
MrCrayfish/MrCrayfishFurnitureMod-Refurbished
8,980
common/src/main/java/com/mrcrayfish/furniture/refurbished/blockentity/MicrowaveBlockEntity.java
package com.mrcrayfish.furniture.refurbished.blockentity; import com.mojang.serialization.Codec; import com.mrcrayfish.furniture.refurbished.Constants; import com.mrcrayfish.furniture.refurbished.block.MicrowaveBlock; import com.mrcrayfish.furniture.refurbished.client.audio.AudioManager; import com.mrcrayfish.furniture.refurbished.core.ModBlockEntities; import com.mrcrayfish.furniture.refurbished.core.ModRecipeTypes; import com.mrcrayfish.furniture.refurbished.core.ModSounds; import com.mrcrayfish.furniture.refurbished.crafting.ProcessingRecipe; import com.mrcrayfish.furniture.refurbished.inventory.BuildableContainerData; import com.mrcrayfish.furniture.refurbished.inventory.IContainerHolder; import com.mrcrayfish.furniture.refurbished.platform.Services; import com.mrcrayfish.furniture.refurbished.util.BlockEntityHelper; import com.mrcrayfish.furniture.refurbished.util.Utils; import net.minecraft.core.BlockPos; import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.chat.Component; import net.minecraft.sounds.SoundEvent; import net.minecraft.sounds.SoundSource; import net.minecraft.util.Mth; import net.minecraft.util.ProblemReporter; import net.minecraft.world.Nameable; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.StackedItemContents; import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.inventory.ContainerData; import net.minecraft.world.inventory.StackedContentsCompatible; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.RecipeType; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.storage.TagValueOutput; import net.minecraft.world.level.storage.ValueInput; import net.minecraft.world.level.storage.ValueOutput; import net.minecraft.world.phys.Vec3; /** * Author: MrCrayfish */ public class MicrowaveBlockEntity extends ElectricityModuleProcessingLootBlockEntity implements IPowerSwitch, IHomeControlDevice, ILevelAudio, Nameable, StackedContentsCompatible { public static final int[] INPUT_SLOTS = new int[]{0}; public static final int[] OUTPUT_SLOTS = new int[]{1}; public static final int DATA_POWERED = 0; public static final int DATA_ENABLED = 1; public static final int DATA_PROCESS_TIME = 2; public static final int DATA_MAX_PROCESS_TIME = 3; public static final double MAX_AUDIO_DISTANCE = Mth.square(3.5); protected final Vec3 audioPosition; protected boolean enabled; protected boolean processing; protected final ContainerData data = new BuildableContainerData(builder -> { builder.add(DATA_POWERED, () -> powered ? 1 : 0, value -> {}); builder.add(DATA_ENABLED, () -> enabled ? 1 : 0, value -> {}); builder.add(DATA_PROCESS_TIME, () -> processingTime, value -> processingTime = value); builder.add(DATA_MAX_PROCESS_TIME, () -> totalProcessingTime, value -> totalProcessingTime = value); }); public MicrowaveBlockEntity(BlockPos pos, BlockState state) { this(ModBlockEntities.MICROWAVE.get(), pos, state, ModRecipeTypes.MICROWAVE_HEATING.get()); } public MicrowaveBlockEntity(BlockEntityType<?> type, BlockPos pos, BlockState state, RecipeType<? extends ProcessingRecipe> recipeType) { super(type, pos, state, 2, recipeType); this.audioPosition = pos.getCenter(); } @Override protected Component getDefaultName() { return Utils.translation("container", "microwave"); } @Override protected AbstractContainerMenu createMenu(int windowId, Inventory playerInventory) { return Services.MENU.createMicrowaveMenu(windowId, playerInventory, this, this.data); } @Override public boolean isMatchingContainerMenu(AbstractContainerMenu menu) { return menu instanceof IContainerHolder holder && holder.container() == this; } @Override public int[] getInputSlots() { return INPUT_SLOTS; } @Override public int[] getOutputSlots() { return OUTPUT_SLOTS; } @Override public int[] getEnergySlots() { return NO_SLOTS; } @Override public boolean canProcess() { return super.canProcess() && this.enabled; } @Override public void onOpen(Level level, BlockPos pos, BlockState state) { level.playSound(null, this.worldPosition, ModSounds.BLOCK_MICROWAVE_OPEN.get(), SoundSource.BLOCKS, 1.0F, 0.9F + 0.1F * level.random.nextFloat()); this.setDoorState(state, true); } @Override public void onClose(Level level, BlockPos pos, BlockState state) { level.playSound(null, this.worldPosition, ModSounds.BLOCK_MICROWAVE_CLOSE.get(), SoundSource.BLOCKS, 1.0F, 0.9F + 0.1F * level.random.nextFloat()); this.setDoorState(state, false); } private void setDoorState(BlockState state, boolean open) { Level level = this.getLevel(); if(level != null) { level.setBlock(this.getBlockPos(), state.setValue(MicrowaveBlock.OPEN, open), Block.UPDATE_ALL); } } @Override public void togglePower() { this.enabled = !this.enabled; this.setChanged(); BlockEntityHelper.sendCustomUpdate(this, BlockEntity::getUpdateTag); } @Override public void loadAdditional(ValueInput input) { super.loadAdditional(input); input.read("Enabled", Codec.BOOL).ifPresent(value -> this.enabled = value); input.read("Processing", Codec.BOOL).ifPresent(value -> this.processing = value); } @Override protected void saveAdditional(ValueOutput output) { super.saveAdditional(output); output.store("Enabled", Codec.BOOL, this.enabled); output.store("Processing", Codec.BOOL, this.processing); } @Override public CompoundTag getUpdateTag(HolderLookup.Provider provider) { try(ProblemReporter.ScopedCollector collector = new ProblemReporter.ScopedCollector(this.problemPath(), Constants.LOG)) { TagValueOutput output = TagValueOutput.createWithContext(collector, provider); this.writeNodeNbt(output); output.store("Powered", Codec.BOOL, this.powered); output.store("Enabled", Codec.BOOL, this.enabled); output.store("Processing", Codec.BOOL, this.processing); BlockEntityHelper.saveCustomName(output, this.getCustomName()); return output.buildResult(); } } @Override public BlockPos getDevicePos() { return this.worldPosition; } @Override public boolean isDeviceEnabled() { return this.enabled; } @Override public void toggleDeviceState() { this.enabled = !this.enabled; this.setChanged(); this.syncDataToTrackingClients(); } @Override public void setDeviceState(boolean enabled) { this.enabled = enabled; this.setChanged(); this.syncDataToTrackingClients(); } @Override public Component getDeviceName() { if(this.hasCustomName()) { return this.getCustomName(); } return this.getDefaultName(); } @Override public SoundEvent getSound() { return ModSounds.BLOCK_MICROWAVE_FAN.get(); } @Override public SoundSource getSource() { return SoundSource.BLOCKS; } @Override public Vec3 getAudioPosition() { return this.audioPosition; } @Override public boolean canPlayAudio() { return this.isNodePowered() && this.processing && this.enabled && !this.isRemoved(); } @Override public int getAudioHash() { return this.worldPosition.hashCode(); } @Override public boolean isAudioEqual(ILevelAudio other) { return this == other; } @Override public double getAudioRadiusSqr() { return MAX_AUDIO_DISTANCE; } @Override public void moduleTick(Level level) { super.moduleTick(level); if(!level.isClientSide) { boolean processing = this.processTick(); if(this.processing != processing) { this.processing = processing; this.syncDataToTrackingClients(); } } else { AudioManager.get().playLevelAudio(this); } } @Override public void fillStackedContents(StackedItemContents contents) { for(ItemStack stack : this.items) { contents.accountStack(stack); } } }
1
0.855334
1
0.855334
game-dev
MEDIA
0.98744
game-dev
0.934847
1
0.934847
Mervill/Unity3D-NLua
45,799
Assets/NLua/Metatables.cs
/* * This file is part of NLua. * Copyright (C) 2014 Vinicius Jarina. * Copyright (C) 2003-2005 Fabio Mascarenhas de Queiroz. * Copyright (C) 2012 Megax <http://megax.yeahunter.hu/> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Linq; using System.IO; using System.Collections; using System.Reflection; using System.Diagnostics; using System.Collections.Generic; using System.Runtime.InteropServices; using NLua.Method; using NLua.Extensions; #if MONOTOUCH using ObjCRuntime; #endif namespace NLua { #if USE_KOPILUA using LuaCore = KopiLua.Lua; using LuaState = KopiLua.LuaState; using LuaNativeFunction = KopiLua.LuaNativeFunction; #else using LuaCore = KeraLua.Lua; using LuaState = KeraLua.LuaState; using LuaNativeFunction = KeraLua.LuaNativeFunction; #endif /* * Functions used in the metatables of userdata representing * CLR objects * */ public class MetaFunctions { public LuaNativeFunction GcFunction { get; private set; } public LuaNativeFunction IndexFunction { get; private set; } public LuaNativeFunction NewIndexFunction { get; private set; } public LuaNativeFunction BaseIndexFunction { get; private set; } public LuaNativeFunction ClassIndexFunction { get; private set; } public LuaNativeFunction ClassNewindexFunction { get; private set; } public LuaNativeFunction ExecuteDelegateFunction { get; private set; } public LuaNativeFunction CallConstructorFunction { get; private set; } public LuaNativeFunction ToStringFunction { get; private set; } public LuaNativeFunction CallDelegateFunction { get; private set; } public LuaNativeFunction AddFunction { get; private set; } public LuaNativeFunction SubtractFunction { get; private set; } public LuaNativeFunction MultiplyFunction { get; private set; } public LuaNativeFunction DivisionFunction { get; private set; } public LuaNativeFunction ModulosFunction { get; private set; } public LuaNativeFunction UnaryNegationFunction { get; private set; } public LuaNativeFunction EqualFunction { get; private set; } public LuaNativeFunction LessThanFunction { get; private set; } public LuaNativeFunction LessThanOrEqualFunction { get; private set; } Dictionary<object, object> memberCache = new Dictionary<object, object> (); ObjectTranslator translator; /* * __index metafunction for CLR objects. Implemented in Lua. */ static string luaIndexFunction = @"local function index(obj,name) local meta = getmetatable(obj) local cached = meta.cache[name] if cached ~= nil then return cached else local value,isFunc = get_object_member(obj,name) if isFunc then meta.cache[name]=value end return value end end return index"; public static string LuaIndexFunction { get { return luaIndexFunction; } } public MetaFunctions (ObjectTranslator translator) { this.translator = translator; GcFunction = new LuaNativeFunction (MetaFunctions.CollectObject); ToStringFunction = new LuaNativeFunction (MetaFunctions.ToStringLua); IndexFunction = new LuaNativeFunction (MetaFunctions.GetMethod); NewIndexFunction = new LuaNativeFunction (MetaFunctions.SetFieldOrProperty); BaseIndexFunction = new LuaNativeFunction (MetaFunctions.GetBaseMethod); CallConstructorFunction = new LuaNativeFunction (MetaFunctions.CallConstructor); ClassIndexFunction = new LuaNativeFunction (MetaFunctions.GetClassMethod); ClassNewindexFunction = new LuaNativeFunction (MetaFunctions.SetClassFieldOrProperty); ExecuteDelegateFunction = new LuaNativeFunction (MetaFunctions.RunFunctionDelegate); CallDelegateFunction = new LuaNativeFunction (MetaFunctions.CallDelegate); AddFunction = new LuaNativeFunction (MetaFunctions.AddLua); SubtractFunction = new LuaNativeFunction (MetaFunctions.SubtractLua); MultiplyFunction = new LuaNativeFunction (MetaFunctions.MultiplyLua); DivisionFunction = new LuaNativeFunction (MetaFunctions.DivideLua); ModulosFunction = new LuaNativeFunction (MetaFunctions.ModLua); UnaryNegationFunction = new LuaNativeFunction (MetaFunctions.UnaryNegationLua); EqualFunction = new LuaNativeFunction (MetaFunctions.EqualLua); LessThanFunction = new LuaNativeFunction (MetaFunctions.LessThanLua); LessThanOrEqualFunction = new LuaNativeFunction (MetaFunctions.LessThanOrEqualLua); } /* * __call metafunction of CLR delegates, retrieves and calls the delegate. */ #if MONOTOUCH [MonoPInvokeCallback (typeof (LuaNativeFunction))] #endif private static int RunFunctionDelegate (LuaState luaState) { var translator = ObjectTranslatorPool.Instance.Find (luaState); return RunFunctionDelegate (luaState, translator); } private static int RunFunctionDelegate (LuaState luaState, ObjectTranslator translator) { LuaNativeFunction func = (LuaNativeFunction)translator.GetRawNetObject (luaState, 1); LuaLib.LuaRemove (luaState, 1); return func (luaState); } /* * __gc metafunction of CLR objects. */ #if MONOTOUCH [MonoPInvokeCallback (typeof (LuaNativeFunction))] #endif private static int CollectObject (LuaState luaState) { var translator = ObjectTranslatorPool.Instance.Find (luaState); return CollectObject (luaState, translator); } private static int CollectObject (LuaState luaState, ObjectTranslator translator) { int udata = LuaLib.LuaNetRawNetObj (luaState, 1); if (udata != -1) translator.CollectObject (udata); return 0; } /* * __tostring metafunction of CLR objects. */ #if MONOTOUCH [MonoPInvokeCallback (typeof (LuaNativeFunction))] #endif private static int ToStringLua (LuaState luaState) { var translator = ObjectTranslatorPool.Instance.Find (luaState); return ToStringLua (luaState, translator); } private static int ToStringLua (LuaState luaState, ObjectTranslator translator) { object obj = translator.GetRawNetObject (luaState, 1); if (obj != null) translator.Push (luaState, obj.ToString () + ": " + obj.GetHashCode ().ToString()); else LuaLib.LuaPushNil (luaState); return 1; } /* * __add metafunction of CLR objects. */ #if MONOTOUCH [MonoPInvokeCallback (typeof (LuaNativeFunction))] #endif static int AddLua (LuaState luaState) { var translator = ObjectTranslatorPool.Instance.Find (luaState); return MatchOperator (luaState, "op_Addition", translator); } /* * __sub metafunction of CLR objects. */ #if MONOTOUCH [MonoPInvokeCallback (typeof (LuaNativeFunction))] #endif static int SubtractLua (LuaState luaState) { var translator = ObjectTranslatorPool.Instance.Find (luaState); return MatchOperator (luaState, "op_Subtraction", translator); } /* * __mul metafunction of CLR objects. */ #if MONOTOUCH [MonoPInvokeCallback (typeof (LuaNativeFunction))] #endif static int MultiplyLua (LuaState luaState) { var translator = ObjectTranslatorPool.Instance.Find (luaState); return MatchOperator (luaState, "op_Multiply", translator); } /* * __div metafunction of CLR objects. */ #if MONOTOUCH [MonoPInvokeCallback (typeof (LuaNativeFunction))] #endif static int DivideLua (LuaState luaState) { var translator = ObjectTranslatorPool.Instance.Find (luaState); return MatchOperator (luaState, "op_Division", translator); } /* * __mod metafunction of CLR objects. */ #if MONOTOUCH [MonoPInvokeCallback (typeof (LuaNativeFunction))] #endif static int ModLua (LuaState luaState) { var translator = ObjectTranslatorPool.Instance.Find (luaState); return MatchOperator (luaState, "op_Modulus", translator); } /* * __unm metafunction of CLR objects. */ #if MONOTOUCH [MonoPInvokeCallback (typeof (LuaNativeFunction))] #endif static int UnaryNegationLua (LuaState luaState) { var translator = ObjectTranslatorPool.Instance.Find (luaState); return UnaryNegationLua (luaState, translator); } static int UnaryNegationLua (LuaState luaState, ObjectTranslator translator) { object obj1 = translator.GetRawNetObject (luaState, 1); if (obj1 == null) { translator.ThrowError (luaState, "Cannot negate a nil object"); LuaLib.LuaPushNil (luaState); return 1; } Type type = obj1.GetType (); MethodInfo opUnaryNegation = type.GetMethod ("op_UnaryNegation"); if (opUnaryNegation == null) { translator.ThrowError (luaState, "Cannot negate object (" + type.Name + " does not overload the operator -)"); LuaLib.LuaPushNil (luaState); return 1; } obj1 = opUnaryNegation.Invoke (obj1, new object [] { obj1 }); translator.Push (luaState, obj1); return 1; } /* * __eq metafunction of CLR objects. */ #if MONOTOUCH [MonoPInvokeCallback (typeof (LuaNativeFunction))] #endif static int EqualLua (LuaState luaState) { var translator = ObjectTranslatorPool.Instance.Find (luaState); return MatchOperator (luaState, "op_Equality", translator); } /* * __lt metafunction of CLR objects. */ #if MONOTOUCH [MonoPInvokeCallback (typeof (LuaNativeFunction))] #endif static int LessThanLua (LuaState luaState) { var translator = ObjectTranslatorPool.Instance.Find (luaState); return MatchOperator (luaState, "op_LessThan", translator); } /* * __le metafunction of CLR objects. */ #if MONOTOUCH [MonoPInvokeCallback (typeof (LuaNativeFunction))] #endif static int LessThanOrEqualLua (LuaState luaState) { var translator = ObjectTranslatorPool.Instance.Find (luaState); return MatchOperator (luaState, "op_LessThanOrEqual", translator); } /// <summary> /// Debug tool to dump the lua stack /// </summary> /// FIXME, move somewhere else public static void DumpStack (ObjectTranslator translator, LuaState luaState) { int depth = LuaLib.LuaGetTop (luaState); #if WINDOWS_PHONE || NETFX_CORE Debug.WriteLine("lua stack depth: {0}", depth); #elif UNITY_3D UnityEngine.Debug.Log(string.Format("lua stack depth: {0}", depth)); #elif !SILVERLIGHT Debug.Print ("lua stack depth: {0}", depth); #endif for (int i = 1; i <= depth; i++) { var type = LuaLib.LuaType (luaState, i); // we dump stacks when deep in calls, calling typename while the stack is in flux can fail sometimes, so manually check for key types string typestr = (type == LuaTypes.Table) ? "table" : LuaLib.LuaTypeName (luaState, type); string strrep = LuaLib.LuaToString (luaState, i).ToString (); if (type == LuaTypes.UserData) { object obj = translator.GetRawNetObject (luaState, i); strrep = obj.ToString (); } #if WINDOWS_PHONE || NETFX_CORE Debug.WriteLine("{0}: ({1}) {2}", i, typestr, strrep); #elif UNITY_3D UnityEngine.Debug.Log(string.Format("{0}: ({1}) {2}", i, typestr, strrep)); #elif !SILVERLIGHT Debug.Print ("{0}: ({1}) {2}", i, typestr, strrep); #endif } } /* * Called by the __index metafunction of CLR objects in case the * method is not cached or it is a field/property/event. * Receives the object and the member name as arguments and returns * either the value of the member or a delegate to call it. * If the member does not exist returns nil. */ #if MONOTOUCH [MonoPInvokeCallback (typeof (LuaNativeFunction))] #endif private static int GetMethod (LuaState luaState) { var translator = ObjectTranslatorPool.Instance.Find (luaState); var instance = translator.MetaFunctionsInstance; return instance.GetMethodInternal (luaState); } private int GetMethodInternal (LuaState luaState) { object obj = translator.GetRawNetObject (luaState, 1); if (obj == null) { translator.ThrowError (luaState, "trying to index an invalid object reference"); LuaLib.LuaPushNil (luaState); return 1; } object index = translator.GetObject (luaState, 2); //var indexType = index.GetType(); string methodName = index as string; // will be null if not a string arg var objType = obj.GetType (); var proxyType = new ProxyType (objType); // Handle the most common case, looking up the method by name. // CP: This will fail when using indexers and attempting to get a value with the same name as a property of the object, // ie: xmlelement['item'] <- item is a property of xmlelement try { if (!string.IsNullOrEmpty(methodName) && IsMemberPresent (proxyType, methodName)) return GetMember (luaState, proxyType, obj, methodName, BindingFlags.Instance); } catch { } // Try to access by array if the type is right and index is an int (lua numbers always come across as double) if (objType.IsArray && index is double) { int intIndex = (int)((double)index); #if NETFX_CORE Type type = objType; #else Type type = objType.UnderlyingSystemType; #endif if (type == typeof(float[])) { float[] arr = ((float[])obj); translator.Push (luaState, arr [intIndex]); } else if (type == typeof(double[])) { double[] arr = ((double[])obj); translator.Push (luaState, arr [intIndex]); } else if (type == typeof(int[])) { int[] arr = ((int[])obj); translator.Push (luaState, arr [intIndex]); } else { object[] arr = (object[])obj; translator.Push (luaState, arr [intIndex]); } } else { if (!string.IsNullOrEmpty (methodName) && IsExtensionMethodPresent (objType, methodName)) { return GetExtensionMethod (luaState, objType, obj, methodName); } // Try to use get_Item to index into this .net object var methods = objType.GetMethods (); foreach (var mInfo in methods) { if (mInfo.Name == "get_Item") { //check if the signature matches the input if (mInfo.GetParameters ().Length == 1) { var getter = mInfo; var actualParms = (getter != null) ? getter.GetParameters () : null; if (actualParms == null || actualParms.Length != 1) { translator.ThrowError (luaState, "method not found (or no indexer): " + index); LuaLib.LuaPushNil (luaState); } else { // Get the index in a form acceptable to the getter index = translator.GetAsType (luaState, 2, actualParms [0].ParameterType); object[] args = new object[1]; // Just call the indexer - if out of bounds an exception will happen args [0] = index; try { object result = getter.Invoke (obj, args); translator.Push (luaState, result); } catch (TargetInvocationException e) { // Provide a more readable description for the common case of key not found if (e.InnerException is KeyNotFoundException) translator.ThrowError (luaState, "key '" + index + "' not found "); else translator.ThrowError (luaState, "exception indexing '" + index + "' " + e.Message); LuaLib.LuaPushNil (luaState); } } } } } } LuaLib.LuaPushBoolean (luaState, false); return 2; } /* * __index metafunction of base classes (the base field of Lua tables). * Adds a prefix to the method name to call the base version of the method. */ #if MONOTOUCH [MonoPInvokeCallback (typeof (LuaNativeFunction))] #endif private static int GetBaseMethod (LuaState luaState) { var translator = ObjectTranslatorPool.Instance.Find (luaState); var instance = translator.MetaFunctionsInstance; return instance.GetBaseMethodInternal (luaState); } private int GetBaseMethodInternal (LuaState luaState) { object obj = translator.GetRawNetObject (luaState, 1); if (obj == null) { translator.ThrowError (luaState, "trying to index an invalid object reference"); LuaLib.LuaPushNil (luaState); LuaLib.LuaPushBoolean (luaState, false); return 2; } string methodName = LuaLib.LuaToString (luaState, 2).ToString (); if (string.IsNullOrEmpty(methodName)) { LuaLib.LuaPushNil (luaState); LuaLib.LuaPushBoolean (luaState, false); return 2; } GetMember (luaState, new ProxyType(obj.GetType ()), obj, "__luaInterface_base_" + methodName, BindingFlags.Instance); LuaLib.LuaSetTop (luaState, -2); if (LuaLib.LuaType (luaState, -1) == LuaTypes.Nil) { LuaLib.LuaSetTop (luaState, -2); return GetMember (luaState, new ProxyType(obj.GetType ()), obj, methodName, BindingFlags.Instance); } LuaLib.LuaPushBoolean (luaState, false); return 2; } /// <summary> /// Does this method exist as either an instance or static? /// </summary> /// <param name="objType"></param> /// <param name="methodName"></param> /// <returns></returns> bool IsMemberPresent (ProxyType objType, string methodName) { object cachedMember = CheckMemberCache (memberCache, objType, methodName); if (cachedMember != null) return true; var members = objType.GetMember (methodName, BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public); return (members.Length > 0); } bool IsExtensionMethodPresent (Type type, string name) { object cachedMember = CheckMemberCache (memberCache, type, name); if (cachedMember != null) return true; return translator.IsExtensionMethodPresent (type, name); } int GetExtensionMethod (LuaState luaState, Type type, object obj, string name) { object cachedMember = CheckMemberCache (memberCache, type, name); if (cachedMember != null && cachedMember is LuaNativeFunction) { translator.PushFunction (luaState, (LuaNativeFunction)cachedMember); translator.Push (luaState, true); return 2; } MethodInfo methodInfo = translator.GetExtensionMethod (type, name); var wrapper = new LuaNativeFunction ((new LuaMethodWrapper (translator, obj,new ProxyType(type), methodInfo)).invokeFunction); SetMemberCache (memberCache, type, name, wrapper); translator.PushFunction (luaState, wrapper); translator.Push (luaState, true); return 2; } /* * Pushes the value of a member or a delegate to call it, depending on the type of * the member. Works with static or instance members. * Uses reflection to find members, and stores the reflected MemberInfo object in * a cache (indexed by the type of the object and the name of the member). */ int GetMember (LuaState luaState, ProxyType objType, object obj, string methodName, BindingFlags bindingType) { bool implicitStatic = false; MemberInfo member = null; object cachedMember = CheckMemberCache (memberCache, objType, methodName); if (cachedMember is LuaNativeFunction) { translator.PushFunction (luaState, (LuaNativeFunction)cachedMember); translator.Push (luaState, true); return 2; } else if (cachedMember != null) member = (MemberInfo)cachedMember; else { var members = objType.GetMember (methodName, bindingType | BindingFlags.Public); if (members.Length > 0) member = members [0]; else { // If we can't find any suitable instance members, try to find them as statics - but we only want to allow implicit static members = objType.GetMember (methodName, bindingType | BindingFlags.Static | BindingFlags.Public); if (members.Length > 0) { member = members [0]; implicitStatic = true; } } } if (member != null) { #if NETFX_CORE if (member is FieldInfo) { #else if (member.MemberType == MemberTypes.Field) { #endif var field = (FieldInfo)member; if (cachedMember == null) SetMemberCache (memberCache, objType, methodName, member); try { var value = field.GetValue (obj); translator.Push (luaState, value); } catch { LuaLib.LuaPushNil (luaState); } #if NETFX_CORE } else if (member is PropertyInfo) { #else } else if (member.MemberType == MemberTypes.Property) { #endif var property = (PropertyInfo)member; if (cachedMember == null) SetMemberCache (memberCache, objType, methodName, member); try { object value = property.GetValue (obj, null); translator.Push (luaState, value); } catch (ArgumentException) { // If we can't find the getter in our class, recurse up to the base class and see // if they can help. if (objType.UnderlyingSystemType != typeof(object)) #if NETFX_CORE return GetMember (luaState, new ProxyType(objType.UnderlyingSystemType.GetTypeInfo().BaseType), obj, methodName, bindingType); #else return GetMember (luaState, new ProxyType(objType.UnderlyingSystemType.BaseType), obj, methodName, bindingType); #endif else LuaLib.LuaPushNil (luaState); } catch (TargetInvocationException e) { // Convert this exception into a Lua error ThrowError (luaState, e); LuaLib.LuaPushNil (luaState); } #if NETFX_CORE } else if (member is EventInfo) { #else } else if (member.MemberType == MemberTypes.Event) { #endif var eventInfo = (EventInfo)member; if (cachedMember == null) SetMemberCache (memberCache, objType, methodName, member); translator.Push (luaState, new RegisterEventHandler (translator.pendingEvents, obj, eventInfo)); } else if (!implicitStatic) { #if NETFX_CORE var typeInfo = member as TypeInfo; if (typeInfo != null && !typeInfo.IsPublic && !typeInfo.IsNotPublic) { #else if (member.MemberType == MemberTypes.NestedType) { #endif // kevinh - added support for finding nested types- // cache us if (cachedMember == null) SetMemberCache (memberCache, objType, methodName, member); // Find the name of our class string name = member.Name; var dectype = member.DeclaringType; // Build a new long name and try to find the type by name string longname = dectype.FullName + "+" + name; var nestedType = translator.FindType (longname); translator.PushType (luaState, nestedType); } else { // Member type must be 'method' var wrapper = new LuaNativeFunction ((new LuaMethodWrapper (translator, objType, methodName, bindingType)).invokeFunction); if (cachedMember == null) SetMemberCache (memberCache, objType, methodName, wrapper); translator.PushFunction (luaState, wrapper); translator.Push (luaState, true); return 2; } } else { // If we reach this point we found a static method, but can't use it in this context because the user passed in an instance translator.ThrowError (luaState, "can't pass instance to static method " + methodName); LuaLib.LuaPushNil (luaState); } } else { if (objType.UnderlyingSystemType != typeof(object)) { #if NETFX_CORE return GetMember (luaState, new ProxyType(objType.UnderlyingSystemType.GetTypeInfo().BaseType), obj, methodName, bindingType); #else return GetMember (luaState, new ProxyType(objType.UnderlyingSystemType.BaseType), obj, methodName, bindingType); #endif } // kevinh - we want to throw an exception because meerly returning 'nil' in this case // is not sufficient. valid data members may return nil and therefore there must be some // way to know the member just doesn't exist. translator.ThrowError (luaState, "unknown member name " + methodName); LuaLib.LuaPushNil (luaState); } // push false because we are NOT returning a function (see luaIndexFunction) translator.Push (luaState, false); return 2; } /* * Checks if a MemberInfo object is cached, returning it or null. */ object CheckMemberCache (Dictionary<object, object> memberCache, Type objType, string memberName) { return CheckMemberCache (memberCache, new ProxyType (objType), memberName); } object CheckMemberCache (Dictionary<object, object> memberCache, ProxyType objType, string memberName) { object members = null; if (memberCache.TryGetValue(objType, out members)) { var membersDict = members as Dictionary<object, object>; object memberValue = null; if (members != null && membersDict.TryGetValue(memberName, out memberValue)) { return memberValue; } } return null; } /* * Stores a MemberInfo object in the member cache. */ void SetMemberCache (Dictionary<object, object> memberCache, Type objType, string memberName, object member) { SetMemberCache (memberCache, new ProxyType (objType), memberName, member); } void SetMemberCache (Dictionary<object, object> memberCache, ProxyType objType, string memberName, object member) { Dictionary<object, object> members = null; object memberCacheValue = null; if (memberCache.TryGetValue(objType, out memberCacheValue)) { members = (Dictionary<object, object>)memberCacheValue; } else { members = new Dictionary<object, object>(); memberCache[objType] = members; } members [memberName] = member; } /* * __newindex metafunction of CLR objects. Receives the object, * the member name and the value to be stored as arguments. Throws * and error if the assignment is invalid. */ #if MONOTOUCH [MonoPInvokeCallback (typeof (LuaNativeFunction))] #endif private static int SetFieldOrProperty (LuaState luaState) { var translator = ObjectTranslatorPool.Instance.Find (luaState); var instance = translator.MetaFunctionsInstance; return instance.SetFieldOrPropertyInternal (luaState); } private int SetFieldOrPropertyInternal (LuaState luaState) { object target = translator.GetRawNetObject (luaState, 1); if (target == null) { translator.ThrowError (luaState, "trying to index and invalid object reference"); return 0; } var type = target.GetType (); // First try to look up the parameter as a property name string detailMessage; bool didMember = TrySetMember (luaState, new ProxyType(type), target, BindingFlags.Instance, out detailMessage); if (didMember) return 0; // Must have found the property name // We didn't find a property name, now see if we can use a [] style this accessor to set array contents try { if (type.IsArray && LuaLib.LuaIsNumber (luaState, 2)) { int index = (int)LuaLib.LuaToNumber (luaState, 2); var arr = (Array)target; object val = translator.GetAsType (luaState, 3, arr.GetType ().GetElementType ()); arr.SetValue (val, index); } else { // Try to see if we have a this[] accessor var setter = type.GetMethod ("set_Item"); if (setter != null) { var args = setter.GetParameters (); var valueType = args [1].ParameterType; // The new val ue the user specified object val = translator.GetAsType (luaState, 3, valueType); var indexType = args [0].ParameterType; object index = translator.GetAsType (luaState, 2, indexType); object[] methodArgs = new object[2]; // Just call the indexer - if out of bounds an exception will happen methodArgs [0] = index; methodArgs [1] = val; setter.Invoke (target, methodArgs); } else translator.ThrowError (luaState, detailMessage); // Pass the original message from trySetMember because it is probably best } #if !SILVERLIGHT } catch (SEHException) { // If we are seeing a C++ exception - this must actually be for Lua's private use. Let it handle it throw; #endif } catch (Exception e) { ThrowError (luaState, e); } return 0; } /// <summary> /// Tries to set a named property or field /// </summary> /// <param name="luaState"></param> /// <param name="targetType"></param> /// <param name="target"></param> /// <param name="bindingType"></param> /// <returns>false if unable to find the named member, true for success</returns> bool TrySetMember (LuaState luaState, ProxyType targetType, object target, BindingFlags bindingType, out string detailMessage) { detailMessage = null; // No error yet // If not already a string just return - we don't want to call tostring - which has the side effect of // changing the lua typecode to string // Note: We don't use isstring because the standard lua C isstring considers either strings or numbers to // be true for isstring. if (LuaLib.LuaType (luaState, 2) != LuaTypes.String) { detailMessage = "property names must be strings"; return false; } // We only look up property names by string string fieldName = LuaLib.LuaToString (luaState, 2).ToString (); if (fieldName == null || fieldName.Length < 1 || !(char.IsLetter (fieldName [0]) || fieldName [0] == '_')) { detailMessage = "invalid property name"; return false; } // Find our member via reflection or the cache var member = (MemberInfo)CheckMemberCache (memberCache, targetType, fieldName); if (member == null) { var members = targetType.GetMember (fieldName, bindingType | BindingFlags.Public); if (members.Length > 0) { member = members [0]; SetMemberCache (memberCache, targetType, fieldName, member); } else { detailMessage = "field or property '" + fieldName + "' does not exist"; return false; } } #if NETFX_CORE if (member is FieldInfo) { #else if (member.MemberType == MemberTypes.Field) { #endif var field = (FieldInfo)member; object val = translator.GetAsType (luaState, 3, field.FieldType); try { field.SetValue (target, val); } catch (Exception e) { ThrowError (luaState, e); } // We did a call return true; #if NETFX_CORE } else if (member is PropertyInfo) { #else } else if (member.MemberType == MemberTypes.Property) { #endif var property = (PropertyInfo)member; object val = translator.GetAsType (luaState, 3, property.PropertyType); try { property.SetValue (target, val, null); } catch (Exception e) { ThrowError (luaState, e); } // We did a call return true; } detailMessage = "'" + fieldName + "' is not a .net field or property"; return false; } /* * Writes to fields or properties, either static or instance. Throws an error * if the operation is invalid. */ private int SetMember (LuaState luaState, ProxyType targetType, object target, BindingFlags bindingType) { string detail; bool success = TrySetMember (luaState, targetType, target, bindingType, out detail); if (!success) translator.ThrowError (luaState, detail); return 0; } /// <summary> /// Convert a C# exception into a Lua error /// </summary> /// <param name="e"></param> /// We try to look into the exception to give the most meaningful description void ThrowError (LuaState luaState, Exception e) { // If we got inside a reflection show what really happened var te = e as TargetInvocationException; if (te != null) e = te.InnerException; translator.ThrowError (luaState, e); } /* * __index metafunction of type references, works on static members. */ #if MONOTOUCH [MonoPInvokeCallback (typeof (LuaNativeFunction))] #endif private static int GetClassMethod (LuaState luaState) { var translator = ObjectTranslatorPool.Instance.Find (luaState); var instance = translator.MetaFunctionsInstance; return instance.GetClassMethodInternal (luaState); } private int GetClassMethodInternal (LuaState luaState) { ProxyType klass; object obj = translator.GetRawNetObject (luaState, 1); if (obj == null || !(obj is ProxyType)) { translator.ThrowError (luaState, "trying to index an invalid type reference"); LuaLib.LuaPushNil (luaState); return 1; } else klass = (ProxyType)obj; if (LuaLib.LuaIsNumber (luaState, 2)) { int size = (int)LuaLib.LuaToNumber (luaState, 2); translator.Push (luaState, Array.CreateInstance (klass.UnderlyingSystemType, size)); return 1; } else { string methodName = LuaLib.LuaToString (luaState, 2).ToString (); if (string.IsNullOrEmpty(methodName)) { LuaLib.LuaPushNil (luaState); return 1; } else return GetMember (luaState, klass, null, methodName, BindingFlags.Static); } } /* * __newindex function of type references, works on static members. */ #if MONOTOUCH [MonoPInvokeCallback (typeof (LuaNativeFunction))] #endif private static int SetClassFieldOrProperty (LuaState luaState) { var translator = ObjectTranslatorPool.Instance.Find (luaState); var instance = translator.MetaFunctionsInstance; return instance.SetClassFieldOrPropertyInternal (luaState); } private int SetClassFieldOrPropertyInternal (LuaState luaState) { ProxyType target; object obj = translator.GetRawNetObject (luaState, 1); if (obj == null || !(obj is ProxyType)) { translator.ThrowError (luaState, "trying to index an invalid type reference"); return 0; } else target = (ProxyType)obj; return SetMember (luaState, target, null, BindingFlags.Static); } /* * __call metafunction of Delegates. */ #if MONOTOUCH [MonoPInvokeCallback (typeof (LuaNativeFunction))] #endif static int CallDelegate (LuaState luaState) { var translator = ObjectTranslatorPool.Instance.Find (luaState); var instance = translator.MetaFunctionsInstance; return instance.CallDelegateInternal (luaState); } int CallDelegateInternal (LuaState luaState) { object objDelegate = translator.GetRawNetObject (luaState, 1); if (objDelegate == null || !(objDelegate is Delegate)) { translator.ThrowError (luaState, "trying to invoke a not delegate or callable value"); LuaLib.LuaPushNil (luaState); return 1; } LuaLib.LuaRemove (luaState, 1); var validDelegate = new MethodCache (); Delegate del = (Delegate)objDelegate; #if NETFX_CORE || WP80 || NET45 || PCL MethodBase methodDelegate = del.GetMethodInfo (); #else MethodBase methodDelegate = del.Method; #endif bool isOk = MatchParameters (luaState, methodDelegate, ref validDelegate); if (isOk) { object result; if (methodDelegate.IsStatic) result = methodDelegate.Invoke (null, validDelegate.args); else result = methodDelegate.Invoke (del.Target, validDelegate.args); translator.Push (luaState, result); return 1; } translator.ThrowError (luaState, "Cannot invoke delegate (invalid arguments for " + methodDelegate.Name + ")"); LuaLib.LuaPushNil (luaState); return 1; } /* * __call metafunction of type references. Searches for and calls * a constructor for the type. Returns nil if the constructor is not * found or if the arguments are invalid. Throws an error if the constructor * generates an exception. */ #if MONOTOUCH [MonoPInvokeCallback (typeof (LuaNativeFunction))] #endif private static int CallConstructor (LuaState luaState) { var translator = ObjectTranslatorPool.Instance.Find (luaState); var instance = translator.MetaFunctionsInstance; return instance.CallConstructorInternal (luaState); } private int CallConstructorInternal (LuaState luaState) { var validConstructor = new MethodCache (); ProxyType klass; object obj = translator.GetRawNetObject (luaState, 1); if (obj == null || !(obj is ProxyType)) { translator.ThrowError (luaState, "trying to call constructor on an invalid type reference"); LuaLib.LuaPushNil (luaState); return 1; } else klass = (ProxyType)obj; LuaLib.LuaRemove (luaState, 1); var constructors = klass.UnderlyingSystemType.GetConstructors (); foreach (var constructor in constructors) { bool isConstructor = MatchParameters (luaState, constructor, ref validConstructor); if (isConstructor) { try { translator.Push (luaState, constructor.Invoke (validConstructor.args)); } catch (TargetInvocationException e) { ThrowError (luaState, e); LuaLib.LuaPushNil (luaState); } catch { LuaLib.LuaPushNil (luaState); } return 1; } } #if NETFX_CORE if (klass.UnderlyingSystemType.GetTypeInfo ().IsValueType) { #else if (klass.UnderlyingSystemType.IsValueType) { #endif int numLuaParams = LuaLib.LuaGetTop (luaState); if (numLuaParams == 0) { translator.Push (luaState, Activator.CreateInstance (klass.UnderlyingSystemType)); return 1; } } string constructorName = (constructors.Length == 0) ? "unknown" : constructors [0].Name; translator.ThrowError (luaState, String.Format ("{0} does not contain constructor({1}) argument match", klass.UnderlyingSystemType, constructorName)); LuaLib.LuaPushNil (luaState); return 1; } static bool IsInteger(double x) { return Math.Ceiling(x) == x; } static object GetTargetObject (LuaState luaState, string operation, ObjectTranslator translator) { Type t; object target = translator.GetRawNetObject (luaState, 1); if (target != null) { t = target.GetType (); if (t.HasMethod (operation)) return target; } target = translator.GetRawNetObject (luaState, 2); if (target != null) { t = target.GetType (); if (t.HasMethod (operation)) return target; } return null; } static int MatchOperator (LuaState luaState, string operation, ObjectTranslator translator) { var validOperator = new MethodCache (); object target = GetTargetObject (luaState, operation, translator); if (target == null) { translator.ThrowError (luaState, "Cannot call " + operation + " on a nil object"); LuaLib.LuaPushNil (luaState); return 1; } Type type = target.GetType (); var operators = type.GetMethods (operation, BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static); foreach (var op in operators) { bool isOk = translator.MatchParameters (luaState, op, ref validOperator); if (!isOk) continue; object result; if (op.IsStatic) result = op.Invoke (null, validOperator.args); else result = op.Invoke (target, validOperator.args); translator.Push (luaState, result); return 1; } translator.ThrowError (luaState, "Cannot call (" + operation + ") on object type " + type.Name); LuaLib.LuaPushNil (luaState); return 1; } internal Array TableToArray (Func<int, object> luaParamValueExtractor, Type paramArrayType, int startIndex, int count) { Array paramArray; if (count == 0) return Array.CreateInstance (paramArrayType, 0); var luaParamValue = luaParamValueExtractor (startIndex); if (luaParamValue is LuaTable) { LuaTable table = (LuaTable)luaParamValue; IDictionaryEnumerator tableEnumerator = table.GetEnumerator (); tableEnumerator.Reset (); paramArray = Array.CreateInstance (paramArrayType, table.Values.Count); int paramArrayIndex = 0; while (tableEnumerator.MoveNext ()) { object value = tableEnumerator.Value; if (paramArrayType == typeof (object)) { if (value != null && value.GetType () == typeof (double) && IsInteger ((double)value)) value = Convert.ToInt32 ((double)value); } #if SILVERLIGHT paramArray.SetValue (Convert.ChangeType (value, paramArrayType, System.Globalization.CultureInfo.InvariantCulture), paramArrayIndex); #else paramArray.SetValue (Convert.ChangeType (value, paramArrayType), paramArrayIndex); #endif paramArrayIndex++; } } else { paramArray = Array.CreateInstance (paramArrayType, count); paramArray.SetValue (luaParamValue, 0); for (int i = 1; i < count; i++) { startIndex++; var value = luaParamValueExtractor (startIndex); paramArray.SetValue (value, i); } } return paramArray; } /* * Matches a method against its arguments in the Lua stack. Returns * if the match was successful. It it was also returns the information * necessary to invoke the method. */ internal bool MatchParameters (LuaState luaState, MethodBase method, ref MethodCache methodCache) { ExtractValue extractValue; bool isMethod = true; var paramInfo = method.GetParameters (); int currentLuaParam = 1; int nLuaParams = LuaLib.LuaGetTop (luaState); var paramList = new List<object> (); var outList = new List<int> (); var argTypes = new List<MethodArgs> (); foreach (var currentNetParam in paramInfo) { #if !SILVERLIGHT if (!currentNetParam.IsIn && currentNetParam.IsOut) // Skips out params #else if (currentNetParam.IsOut) // Skips out params #endif { paramList.Add (null); outList.Add (paramList.LastIndexOf (null)); } else if (IsTypeCorrect (luaState, currentLuaParam, currentNetParam, out extractValue)) { // Type checking var value = extractValue (luaState, currentLuaParam); paramList.Add (value); int index = paramList.LastIndexOf (value); var methodArg = new MethodArgs (); methodArg.index = index; methodArg.extractValue = extractValue; argTypes.Add (methodArg); if (currentNetParam.ParameterType.IsByRef) outList.Add (index); currentLuaParam++; } // Type does not match, ignore if the parameter is optional else if (IsParamsArray (luaState, nLuaParams, currentLuaParam, currentNetParam, out extractValue)) { int count = (nLuaParams - currentLuaParam) + 1; Type paramArrayType = currentNetParam.ParameterType.GetElementType (); Func<int, object> extractDelegate = (currentParam) => { currentLuaParam++; return extractValue (luaState, currentParam); }; Array paramArray = TableToArray (extractDelegate, paramArrayType, currentLuaParam, count); paramList.Add (paramArray); int index = paramList.LastIndexOf (paramArray); var methodArg = new MethodArgs (); methodArg.index = index; methodArg.extractValue = extractValue; methodArg.isParamsArray = true; methodArg.paramsArrayType = paramArrayType; argTypes.Add (methodArg); } else if (currentLuaParam > nLuaParams) { // Adds optional parameters if (currentNetParam.IsOptional) paramList.Add (currentNetParam.DefaultValue); else { isMethod = false; break; } } else if (currentNetParam.IsOptional) paramList.Add (currentNetParam.DefaultValue); else { // No match isMethod = false; break; } } if (currentLuaParam != nLuaParams + 1) // Number of parameters does not match isMethod = false; if (isMethod) { methodCache.args = paramList.ToArray (); methodCache.cachedMethod = method; methodCache.outList = outList.ToArray (); methodCache.argTypes = argTypes.ToArray (); } return isMethod; } /// <summary> /// CP: Fix for operator overloading failure /// Returns true if the type is set and assigns the extract value /// </summary> /// <param name="luaState"></param> /// <param name="currentLuaParam"></param> /// <param name="currentNetParam"></param> /// <param name="extractValue"></param> /// <returns></returns> private bool IsTypeCorrect (LuaState luaState, int currentLuaParam, ParameterInfo currentNetParam, out ExtractValue extractValue) { try { return (extractValue = translator.typeChecker.CheckLuaType (luaState, currentLuaParam, currentNetParam.ParameterType)) != null; } catch { extractValue = null; Debug.WriteLine ("Type wasn't correct"); return false; } } private bool IsParamsArray (LuaState luaState, int nLuaParams, int currentLuaParam, ParameterInfo currentNetParam, out ExtractValue extractValue) { extractValue = null; bool isParamArray = false; if (currentNetParam.GetCustomAttributes (typeof(ParamArrayAttribute), false).Any ()) { isParamArray = nLuaParams < currentLuaParam; LuaTypes luaType; try { luaType = LuaLib.LuaType (luaState, currentLuaParam); } catch (Exception ex) { Debug.WriteLine ("Could not retrieve lua type while attempting to determine params Array Status."); Debug.WriteLine (ex.Message); extractValue = null; return false; } if (luaType == LuaTypes.Table) { try { extractValue = translator.typeChecker.GetExtractor (typeof(LuaTable)); } catch (Exception/* ex*/) { Debug.WriteLine ("An error occurred during an attempt to retrieve a LuaTable extractor while checking for params array status."); } if (extractValue != null) { return true; } } else { var paramElementType = currentNetParam.ParameterType.GetElementType (); try { extractValue = translator.typeChecker.CheckLuaType (luaState, currentLuaParam, paramElementType); } catch (Exception/* ex*/) { Debug.WriteLine (string.Format ("An error occurred during an attempt to retrieve an extractor ({0}) while checking for params array status.", paramElementType.FullName)); } if (extractValue != null) { return true; } } } return isParamArray; } } }
1
0.91537
1
0.91537
game-dev
MEDIA
0.308767
game-dev
0.552276
1
0.552276
magefree/mage
1,496
Mage.Sets/src/mage/cards/d/Damn.java
package mage.cards.d; import mage.abilities.costs.mana.ManaCostsImpl; import mage.abilities.effects.common.DestroyAllEffect; import mage.abilities.effects.common.DestroyTargetEffect; import mage.abilities.keyword.OverloadAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.filter.StaticFilters; import mage.target.common.TargetCreaturePermanent; import java.util.UUID; /** * @author jmharmon */ public final class Damn extends CardImpl { public Damn(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.SORCERY}, "{B}{B}"); // Destroy target creature. A creature destroyed this way can’t be regenerated. this.getSpellAbility().addTarget(new TargetCreaturePermanent()); this.getSpellAbility().addEffect(new DestroyTargetEffect(true) .setText("destroy target creature. A creature destroyed this way can't be regenerated")); // Overload {2}{W}{W} (You may cast this spell for its overload cost. If you do, change its text by replacing all instances of “target” with “each.”) this.addAbility(new OverloadAbility( this, new DestroyAllEffect(StaticFilters.FILTER_PERMANENT_CREATURES, true), new ManaCostsImpl<>("{2}{W}{W}") )); } private Damn(final Damn card) { super(card); } @Override public Damn copy() { return new Damn(this); } }
1
0.950083
1
0.950083
game-dev
MEDIA
0.969453
game-dev
0.983612
1
0.983612
NEZNAMY/TAB
1,725
shared/src/main/java/me/neznamy/tab/shared/features/injection/PipelineInjector.java
package me.neznamy.tab.shared.features.injection; import me.neznamy.tab.shared.TAB; import me.neznamy.tab.shared.features.types.JoinListener; import me.neznamy.tab.shared.features.types.Loadable; import me.neznamy.tab.shared.features.types.TabFeature; import me.neznamy.tab.shared.features.types.UnLoadable; import me.neznamy.tab.shared.platform.TabPlayer; import org.jetbrains.annotations.NotNull; /** * Packet intercepting to secure proper functionality of some features: * TabList names - anti-override * NameTags - anti-override * Scoreboard - disabling tab's scoreboard to prevent conflict * PingSpoof - full feature functionality * NickCompatibility - Detect name changes from other plugins */ public abstract class PipelineInjector extends TabFeature implements JoinListener, Loadable, UnLoadable { @NotNull @Override public String getFeatureName() { return "Pipeline injection"; } /** * Injects handler into player's channel. * * @param player * Player to inject */ public abstract void inject(@NotNull TabPlayer player); /** * Un-injects handler from player's channel. * * @param player * Player to remove handler from */ public abstract void uninject(@NotNull TabPlayer player); @Override public void load() { for (TabPlayer p : TAB.getInstance().getOnlinePlayers()) { inject(p); } } @Override public void unload() { for (TabPlayer p : TAB.getInstance().getOnlinePlayers()) { uninject(p); } } @Override public void onJoin(@NotNull TabPlayer connectedPlayer) { inject(connectedPlayer); } }
1
0.739134
1
0.739134
game-dev
MEDIA
0.594857
game-dev,mobile
0.694812
1
0.694812
coop-deluxe/sm64coopdx
216,593
data/behavior_data.c
#define OBJECT_FIELDS_INDEX_DIRECTLY #include "sm64.h" #include "object_constants.h" #include "game/object_list_processor.h" #include "game/interaction.h" #include "game/behavior_actions.h" #include "game/mario_actions_cutscene.h" #include "game/mario_misc.h" #include "game/object_helpers.h" #include "game/debug.h" #include "menu/file_select.h" #include "engine/surface_load.h" #include "actors/common0.h" #include "actors/common1.h" #include "actors/custom0.h" #include "actors/group1.h" #include "actors/group2.h" #include "actors/group3.h" #include "actors/group4.h" #include "actors/group5.h" #include "actors/group6.h" #include "actors/group7.h" #include "actors/group8.h" #include "actors/group9.h" #include "actors/group10.h" #include "actors/group11.h" #include "actors/group12.h" #include "actors/group13.h" #include "actors/group14.h" #include "actors/group15.h" #include "actors/group16.h" #include "actors/group17.h" #include "actors/zcustom0.h" #include "levels/bbh/header.h" #include "levels/castle_inside/header.h" #include "levels/hmc/header.h" #include "levels/ssl/header.h" #include "levels/bob/header.h" #include "levels/sl/header.h" #include "levels/wdw/header.h" #include "levels/jrb/header.h" #include "levels/thi/header.h" #include "levels/ttc/header.h" #include "levels/rr/header.h" #include "levels/castle_grounds/header.h" #include "levels/bitdw/header.h" #include "levels/lll/header.h" #include "levels/sa/header.h" #include "levels/bitfs/header.h" #include "levels/ddd/header.h" #include "levels/wf/header.h" #include "levels/bowser_2/header.h" #include "levels/ttm/header.h" #include "make_const_nonconst.h" #include "behavior_data.h" #include "behavior_table.h" #include "behavior_commands.h" const BehaviorScript bhvStarDoor[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvStarDoor), SET_INT(oInteractType, INTERACT_DOOR), LOAD_COLLISION_DATA(inside_castle_seg7_collision_star_door), SET_INT(oInteractionSubtype, INT_SUBTYPE_STAR_DOOR), OR_INT(oFlags, (OBJ_FLAG_ACTIVE_FROM_AFAR | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), SET_HITBOX(/*Radius*/ 80, /*Height*/ 100), SET_HOME(), SET_FLOAT(oDrawingDistance, 20000), CALL_NATIVE(bhv_door_init), SET_INT(oIntangibleTimer, 0), BEGIN_LOOP(), CALL_NATIVE(bhv_star_door_loop), CALL_NATIVE(bhv_star_door_loop_2), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvMrI[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvMrI), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_MOVE_XZ_USING_FVEL | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), SET_HOME(), SPAWN_CHILD(/*Model*/ MODEL_MR_I_IRIS, /*Behavior*/ bhvMrIBody), SET_MODEL(MODEL_MR_I), BILLBOARD(), CALL_NATIVE(bhv_init_room), BEGIN_LOOP(), CALL_NATIVE(bhv_mr_i_loop), END_LOOP(), }; const BehaviorScript bhvMrIBody[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvMrIBody), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), CALL_NATIVE(bhv_init_room), BEGIN_LOOP(), CALL_NATIVE(bhv_mr_i_body_loop), END_LOOP(), }; const BehaviorScript bhvMrIParticle[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhvMrIParticle), BILLBOARD(), OR_INT(oFlags, (OBJ_FLAG_MOVE_XZ_USING_FVEL | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), SET_INT(oIntangibleTimer, 0), SET_HITBOX(50, 50), SET_INT(oDamageOrCoinValue, 1), SET_INT(oInteractType, INTERACT_DAMAGE), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 30, /*Gravity*/ 0, /*Bounciness*/ 0, /*Drag strength*/ 0, /*Friction*/ 0, /*Buoyancy*/ 0, /*Unused*/ 0, 0), CALL_NATIVE(bhv_init_room), BEGIN_LOOP(), CALL_NATIVE(bhv_mr_i_particle_loop), END_LOOP(), }; const BehaviorScript bhvPurpleParticle[] = { BEGIN(OBJ_LIST_UNIMPORTANT), ID(id_bhvPurpleParticle), BILLBOARD(), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), BEGIN_REPEAT(10), CALL_NATIVE(bhv_piranha_particle_loop), END_REPEAT(), DEACTIVATE(), }; const BehaviorScript bhvGiantPole[] = { BEGIN(OBJ_LIST_POLELIKE), ID(id_bhvGiantPole), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), SET_INT(oInteractType, INTERACT_POLE), SET_HITBOX(/*Radius*/ 80, /*Height*/ 2100), SET_HOME(), SET_INT(oIntangibleTimer, 0), BEGIN_LOOP(), CALL_NATIVE(bhv_giant_pole_loop), END_LOOP(), }; const BehaviorScript bhvPoleGrabbing[] = { BEGIN(OBJ_LIST_POLELIKE), ID(id_bhvPoleGrabbing), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), SET_INT(oInteractType, INTERACT_POLE), SET_HITBOX(/*Radius*/ 80, /*Height*/ 1500), CALL_NATIVE(bhv_pole_init), SET_INT(oIntangibleTimer, 0), BEGIN_LOOP(), CALL_NATIVE(bhv_pole_base_loop), END_LOOP(), }; const BehaviorScript bhvThiHugeIslandTop[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvThiHugeIslandTop), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), LOAD_COLLISION_DATA(thi_seg7_collision_top_trap), BEGIN_LOOP(), CALL_NATIVE(bhv_thi_huge_island_top_loop), END_LOOP(), }; const BehaviorScript bhvThiTinyIslandTop[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvThiTinyIslandTop), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), BEGIN_LOOP(), CALL_NATIVE(bhv_thi_tiny_island_top_loop), END_LOOP(), }; const BehaviorScript bhvCapSwitchBase[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvCapSwitchBase), OR_INT(oFlags, (OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_COLLISION_DATA(capswitch_collision_05003448), BEGIN_LOOP(), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvCapSwitch[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvCapSwitch), OR_INT(oFlags, (OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_COLLISION_DATA(capswitch_collision_050033D0), BEGIN_LOOP(), CALL_NATIVE(bhv_cap_switch_loop), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvKingBobomb[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvKingBobomb), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_ACTIVE_FROM_AFAR | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_ANIMATIONS(oAnimations, &king_bobomb_seg5_anims_0500FE30), SET_INT(oInteractType, INTERACT_GRABBABLE), SET_HITBOX(/*Radius*/ 100, /*Height*/ 100), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 30, /*Gravity*/ -400, /*Bounciness*/ -50, /*Drag strength*/ 1000, /*Friction*/ 1000, /*Buoyancy*/ 200, /*Unused*/ 0, 0), SET_INT(oIntangibleTimer, 0), DROP_TO_FLOOR(), SET_HOME(), SPAWN_OBJ(/*Model*/ MODEL_NONE, /*Behavior*/ bhvBobombAnchorMario), SET_INT(oHealth, 3), SET_INT(oDamageOrCoinValue, 1), BEGIN_LOOP(), CALL_NATIVE(bhv_king_bobomb_loop), END_LOOP(), }; const BehaviorScript bhvBobombAnchorMario[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvBobombAnchorMario), OR_INT(oFlags, (OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), BILLBOARD(), SET_FLOAT(oParentRelativePosX, 100), SET_FLOAT(oParentRelativePosZ, 150), BEGIN_LOOP(), CALL_NATIVE(bhv_bobomb_anchor_mario_loop), END_LOOP(), }; const BehaviorScript bhvBetaChestBottom[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvBetaChestBottom), OR_INT(oFlags, (OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), DROP_TO_FLOOR(), CALL_NATIVE(bhv_beta_chest_bottom_init), BEGIN_LOOP(), CALL_NATIVE(bhv_beta_chest_bottom_loop), END_LOOP(), }; const BehaviorScript bhvBetaChestLid[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvBetaChestLid), OR_INT(oFlags, (OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), SET_HOME(), BEGIN_LOOP(), CALL_NATIVE(bhv_beta_chest_lid_loop), END_LOOP(), }; const BehaviorScript bhvBubbleParticleSpawner[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvBubbleParticleSpawner), DISABLE_RENDERING(), SET_RANDOM_INT(oWaterObjUnkF4, /*Minimum*/ 2, /*Range*/ 9), DELAY_VAR(oWaterObjUnkF4), SPAWN_CHILD(/*Model*/ MODEL_BUBBLE, /*Behavior*/ bhvSmallWaterWave), PARENT_BIT_CLEAR(oActiveParticleFlags, ACTIVE_PARTICLE_BUBBLE), DEACTIVATE(), }; const BehaviorScript bhvBubbleMaybe[] = { BEGIN(OBJ_LIST_UNIMPORTANT), ID(id_bhvBubbleMaybe), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), BILLBOARD(), CALL_NATIVE(bhv_bubble_wave_init), SET_RANDOM_FLOAT(oWaterObjUnkF4, /*Minimum*/ -75, /*Range*/ 150), SET_RANDOM_FLOAT(oWaterObjUnkF8, /*Minimum*/ -75, /*Range*/ 150), SET_RANDOM_FLOAT(oWaterObjUnkFC, /*Minimum*/ -75, /*Range*/ 150), SUM_FLOAT(/*Dest*/ oPosX, /*Value 1*/ oPosX, /*Value 2*/ oWaterObjUnkF4), SUM_FLOAT(/*Dest*/ oPosZ, /*Value 1*/ oPosZ, /*Value 2*/ oWaterObjUnkF8), SUM_FLOAT(/*Dest*/ oPosY, /*Value 1*/ oPosY, /*Value 2*/ oWaterObjUnkFC), SET_INT(oAnimState, -1), BEGIN_REPEAT(60), ADD_INT(oAnimState, 1), CALL_NATIVE(bhv_bubble_maybe_loop), END_REPEAT(), DEACTIVATE(), }; const BehaviorScript bhvBubblePlayer[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvBubblePlayer), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), BEGIN_LOOP(), CALL_NATIVE(bhv_bubble_player_loop), END_LOOP(), }; const BehaviorScript bhvSmallWaterWave[] = { BEGIN(OBJ_LIST_UNIMPORTANT), ID(id_bhvSmallWaterWave), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), BILLBOARD(), CALL_NATIVE(bhv_bubble_wave_init), SET_RANDOM_FLOAT(oWaterObjUnkF4, /*Minimum*/ -50, /*Range*/ 100), SET_RANDOM_FLOAT(oWaterObjUnkF8, /*Minimum*/ -50, /*Range*/ 100), SUM_FLOAT(/*Dest*/ oPosX, /*Value 1*/ oPosX, /*Value 2*/ oWaterObjUnkF4), SUM_FLOAT(/*Dest*/ oPosZ, /*Value 1*/ oPosZ, /*Value 2*/ oWaterObjUnkF8), SET_RANDOM_FLOAT(oWaterObjUnkFC, /*Minimum*/ 0, /*Range*/ 50), SUM_FLOAT(/*Dest*/ oPosY, /*Value 1*/ oPosY, /*Value 2*/ oWaterObjUnkFC), SET_INT(oAnimState, -1), CALL(bhvSmallWaterWave398), BEGIN_REPEAT(60), CALL(bhvSmallWaterWave398), CALL_NATIVE(bhv_small_water_wave_loop), END_REPEAT(), DEACTIVATE(), }; const BehaviorScript bhvSmallWaterWave398[] = { ADD_INT(oAnimState, 1), ADD_FLOAT(oPosY, 7), SET_RANDOM_FLOAT(oWaterObjUnkF4, /*Minimum*/ -2, /*Range*/ 5), SET_RANDOM_FLOAT(oWaterObjUnkF8, /*Minimum*/ -2, /*Range*/ 5), SUM_FLOAT(/*Dest*/ oPosX, /*Value 1*/ oPosX, /*Value 2*/ oWaterObjUnkF4), SUM_FLOAT(/*Dest*/ oPosZ, /*Value 1*/ oPosZ, /*Value 2*/ oWaterObjUnkF8), RETURN(), }; const BehaviorScript bhvWaterAirBubble[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhvWaterAirBubble), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), BILLBOARD(), SET_HITBOX_WITH_OFFSET(/*Radius*/ 400, /*Height*/ 150, /*Downwards offset*/ -150), SET_INT(oIntangibleTimer, 0), SET_INTERACT_TYPE(INTERACT_WATER_RING), SET_INT(oDamageOrCoinValue, 5), CALL_NATIVE(bhv_water_air_bubble_init), SET_INT(oAnimState, -1), BEGIN_LOOP(), CALL_NATIVE(bhv_water_air_bubble_loop), END_LOOP(), }; const BehaviorScript bhvSmallParticle[] = { BEGIN(OBJ_LIST_UNIMPORTANT), ID(id_bhvSmallParticle), BILLBOARD(), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), CALL_NATIVE(bhv_particle_init), BEGIN_REPEAT(70), CALL_NATIVE(bhv_particle_loop), END_REPEAT(), DEACTIVATE(), }; const BehaviorScript bhvPlungeBubble[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvPlungeBubble), PARENT_BIT_CLEAR(oActiveParticleFlags, ACTIVE_PARTICLE_PLUNGE_BUBBLE), DISABLE_RENDERING(), CALL_NATIVE(bhv_water_waves_init), DEACTIVATE(), }; const BehaviorScript bhvSmallParticleSnow[] = { BEGIN(OBJ_LIST_UNIMPORTANT), ID(id_bhvSmallParticleSnow), BILLBOARD(), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), CALL_NATIVE(bhv_particle_init), BEGIN_REPEAT(30), CALL_NATIVE(bhv_particle_loop), END_REPEAT(), DEACTIVATE(), }; const BehaviorScript bhvSmallParticleBubbles[] = { BEGIN(OBJ_LIST_UNIMPORTANT), ID(id_bhvSmallParticleBubbles), BILLBOARD(), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), CALL_NATIVE(bhv_particle_init), BEGIN_REPEAT(70), CALL_NATIVE(bhv_small_bubbles_loop), END_REPEAT(), DEACTIVATE(), }; const BehaviorScript bhvFishGroup[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvFishGroup), BEGIN_LOOP(), CALL_NATIVE(bhv_fish_group_loop), END_LOOP(), }; const BehaviorScript bhvCannon[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhvCannon), OR_INT(oFlags, (OBJ_FLAG_ACTIVE_FROM_AFAR | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), SPAWN_CHILD(/*Model*/ MODEL_CANNON_BARREL, /*Behavior*/ bhvCannonBarrel), SET_INT(oInteractType, INTERACT_CANNON_BASE), ADD_FLOAT(oPosY, -340), SET_HOME(), SET_HITBOX(/*Radius*/ 150, /*Height*/ 150), SET_INT(oIntangibleTimer, 0), BEGIN_LOOP(), CALL_NATIVE(bhv_cannon_base_loop), END_LOOP(), }; const BehaviorScript bhvCannonBarrel[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvCannonBarrel), OR_INT(oFlags, (OBJ_FLAG_ACTIVE_FROM_AFAR | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), DROP_TO_FLOOR(), BEGIN_LOOP(), CALL_NATIVE(bhv_cannon_barrel_loop), END_LOOP(), }; const BehaviorScript bhvCannonBaseUnused[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvCannonBaseUnused), OR_INT(oFlags, (OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_MOVE_XZ_USING_FVEL | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), BILLBOARD(), SET_INT(oAnimState, -1), BEGIN_REPEAT(8), CALL_NATIVE(bhv_cannon_base_unused_loop), ADD_INT(oAnimState, 1), END_REPEAT(), DEACTIVATE(), }; const BehaviorScript bhvChuckya[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvChuckya), OR_INT(oFlags, (OBJ_FLAG_HOLDABLE | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_ANIMATIONS(oAnimations, &chuckya_seg8_anims_0800C070), ANIMATE(5), SET_INT(oInteractType, INTERACT_GRABBABLE), SET_HITBOX(/*Radius*/ 150, /*Height*/ 100), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 30, /*Gravity*/ -400, /*Bounciness*/ -50, /*Drag strength*/ 1000, /*Friction*/ 1000, /*Buoyancy*/ 200, /*Unused*/ 0, 0), SPAWN_OBJ(/*Model*/ MODEL_NONE, /*Behavior*/ bhvChuckyaAnchorMario), SET_INT(oNumLootCoins, 5), SET_INT(oIntangibleTimer, 0), SET_HOME(), BEGIN_LOOP(), CALL_NATIVE(bhv_chuckya_loop), END_LOOP(), }; const BehaviorScript bhvChuckyaAnchorMario[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvChuckyaAnchorMario), OR_INT(oFlags, (OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), BILLBOARD(), SET_FLOAT(oParentRelativePosY, -60), SET_FLOAT(oParentRelativePosZ, 150), BEGIN_LOOP(), CALL_NATIVE(bhv_chuckya_anchor_mario_loop), END_LOOP(), }; const BehaviorScript bhvUnused05A8[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvUnused05A8), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), BREAK(), }; const BehaviorScript bhvRotatingPlatform[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvRotatingPlatform), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), SET_HOME(), BEGIN_LOOP(), CALL_NATIVE(bhv_rotating_platform_loop), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvTower[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvTower), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), LOAD_COLLISION_DATA(wf_seg7_collision_tower), SET_FLOAT(oCollisionDistance, 3000), SET_FLOAT(oDrawingDistance, 20000), BEGIN_LOOP(), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvBulletBillCannon[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvBulletBillCannon), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), LOAD_COLLISION_DATA(wf_seg7_collision_bullet_bill_cannon), SET_FLOAT(oCollisionDistance, 300), BEGIN_LOOP(), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvWfBreakableWallRight[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvWfBreakableWallRight), LOAD_COLLISION_DATA(wf_seg7_collision_breakable_wall), GOTO(bhvWfBreakableWallLeft + 1 + 2 + 1), }; const BehaviorScript bhvWfBreakableWallLeft[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvWfBreakableWallLeft), LOAD_COLLISION_DATA(wf_seg7_collision_breakable_wall_2), // WF breakable walls - common: OR_INT(oFlags, (OBJ_FLAG_ACTIVE_FROM_AFAR | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), SET_HITBOX(/*Radius*/ 300, /*Height*/ 400), SET_INT(oIntangibleTimer, 0), BEGIN_LOOP(), CALL_NATIVE(bhv_wf_breakable_wall_loop), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvKickableBoard[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvKickableBoard), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_ACTIVE_FROM_AFAR | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_COLLISION_DATA(wf_seg7_collision_kickable_board), SET_HITBOX(/*Radius*/ 100, /*Height*/ 1200), SET_HURTBOX(/*Radius*/ 1, /*Height*/ 1), SET_FLOAT(oCollisionDistance, 1500), SET_INT(oIntangibleTimer, 0), BEGIN_LOOP(), CALL_NATIVE(bhv_kickable_board_loop), END_LOOP(), }; const BehaviorScript bhvTowerDoor[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvTowerDoor), OR_INT(oFlags, (OBJ_FLAG_ACTIVE_FROM_AFAR | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_COLLISION_DATA(wf_seg7_collision_tower_door), SET_HITBOX(/*Radius*/ 100, /*Height*/ 100), SET_INT(oIntangibleTimer, 0), BEGIN_LOOP(), CALL_NATIVE(bhv_tower_door_loop), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvRotatingCounterClockwise[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvRotatingCounterClockwise), BREAK(), }; const BehaviorScript bhvWfRotatingWoodenPlatform[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvWfRotatingWoodenPlatform), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), CALL_NATIVE(bhv_wf_rotating_wooden_platform_init), LOAD_COLLISION_DATA(wf_seg7_collision_clocklike_rotation), BEGIN_LOOP(), CALL_NATIVE(bhv_wf_rotating_wooden_platform_loop), END_LOOP(), }; const BehaviorScript bhvKoopaShellUnderwater[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvKoopaShellUnderwater), OR_INT(oFlags, (OBJ_FLAG_HOLDABLE | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), BEGIN_LOOP(), CALL_NATIVE(bhv_koopa_shell_underwater_loop), END_LOOP(), }; const BehaviorScript bhvExitPodiumWarp[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvExitPodiumWarp), OR_INT(oFlags, (OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), SET_INT(oInteractType, INTERACT_WARP), DROP_TO_FLOOR(), SET_FLOAT(oCollisionDistance, 8000), LOAD_COLLISION_DATA(ttm_seg7_collision_podium_warp), SET_INT(oIntangibleTimer, 0), SET_HITBOX(/*Radius*/ 50, /*Height*/ 50), BEGIN_LOOP(), CALL_NATIVE(load_object_collision_model), SET_INT(oInteractStatus, 0), END_LOOP(), }; const BehaviorScript bhvFadingWarp[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhvFadingWarp), SET_INT(oInteractionSubtype, INT_SUBTYPE_FADING_WARP), OR_INT(oFlags, (OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), SET_INT(oInteractType, INTERACT_WARP), SET_INT(oIntangibleTimer, 0), BEGIN_LOOP(), CALL_NATIVE(bhv_fading_warp_loop), END_LOOP(), }; const BehaviorScript bhvWarp[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhvWarp), OR_INT(oFlags, (OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), SET_INT(oInteractType, INTERACT_WARP), SET_INT(oIntangibleTimer, 0), BEGIN_LOOP(), CALL_NATIVE(bhv_warp_loop), END_LOOP(), }; const BehaviorScript bhvWarpPipe[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvWarpPipe), OR_INT(oFlags, (OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), SET_INT(oInteractType, INTERACT_WARP), LOAD_COLLISION_DATA(warp_pipe_seg3_collision_03009AC8), SET_FLOAT(oDrawingDistance, 16000), SET_INT(oIntangibleTimer, 0), SET_HITBOX(/*Radius*/ 70, /*Height*/ 50), BEGIN_LOOP(), CALL_NATIVE(bhv_warp_loop), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvWhitePuffExplosion[] = { BEGIN(OBJ_LIST_UNIMPORTANT), ID(id_bhvWhitePuffExplosion), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), BILLBOARD(), BEGIN_LOOP(), CALL_NATIVE(bhv_white_puff_exploding_loop), END_LOOP(), }; const BehaviorScript bhvSpawnedStar[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhvSpawnedStar), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), SET_INT(oBehParams2ndByte, 1), GOTO(bhvSpawnedStarNoLevelExit + 1 + 1 + 1), }; const BehaviorScript bhvSpawnedStarNoLevelExit[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhvSpawnedStarNoLevelExit), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), // Spawned star - common: SET_HOME(), CALL_NATIVE(bhv_spawned_star_init), BEGIN_LOOP(), CALL_NATIVE(bhv_spawned_star_loop), END_LOOP(), }; const BehaviorScript bhvMrIBlueCoin[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhvMrIBlueCoin), SET_INT(oInteractType, INTERACT_COIN), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), BILLBOARD(), SET_INT(oIntangibleTimer, 0), SET_FLOAT(oMrIUnk110, 20), SET_INT(oAnimState, -1), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 30, /*Gravity*/ -400, /*Bounciness*/ -70, /*Drag strength*/ 1000, /*Friction*/ 1000, /*Buoyancy*/ 200, /*Unused*/ 0, 0), CALL_NATIVE(bhv_coin_init), SET_INT(oDamageOrCoinValue, 5), SET_HITBOX(/*Radius*/ 120, /*Height*/ 64), BEGIN_LOOP(), CALL_NATIVE(bhv_coin_loop), ADD_INT(oAnimState, 1), END_LOOP(), }; const BehaviorScript bhvCoinInsideBoo[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhvCoinInsideBoo), SET_HITBOX(/*Radius*/ 100, /*Height*/ 64), SET_INT(oInteractType, INTERACT_COIN), OR_INT(oFlags, (OBJ_FLAG_ACTIVE_FROM_AFAR | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 30, /*Gravity*/ -400, /*Bounciness*/ -70, /*Drag strength*/ 1000, /*Friction*/ 1000, /*Buoyancy*/ 200, /*Unused*/ 0, 0), BILLBOARD(), CALL_NATIVE(bhv_init_room), BEGIN_LOOP(), CALL_NATIVE(bhv_coin_inside_boo_loop), ADD_INT(oAnimState, 1), END_LOOP(), }; const BehaviorScript bhvCoinFormationSpawn[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhvCoinFormationSpawn), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), BILLBOARD(), BEGIN_LOOP(), CALL_NATIVE(bhv_coin_formation_spawn_loop), END_LOOP(), }; const BehaviorScript bhvCoinFormation[] = { BEGIN(OBJ_LIST_SPAWNER), ID(id_bhvCoinFormation), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), CALL_NATIVE(bhv_coin_formation_init), BEGIN_LOOP(), CALL_NATIVE(bhv_coin_formation_loop), END_LOOP(), }; const BehaviorScript bhvOneCoin[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhvOneCoin), SET_INT(oBehParams2ndByte, 1), GOTO(bhvYellowCoin + 1 + 1), }; const BehaviorScript bhvYellowCoin[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhvYellowCoin), // Yellow coin - common: BILLBOARD(), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), CALL_NATIVE(bhv_yellow_coin_init), BEGIN_LOOP(), CALL_NATIVE(bhv_yellow_coin_loop), END_LOOP(), }; const BehaviorScript bhvTemporaryYellowCoin[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhvTemporaryYellowCoin), BILLBOARD(), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), CALL_NATIVE(bhv_yellow_coin_init), BEGIN_LOOP(), CALL_NATIVE(bhv_temp_coin_loop), END_LOOP(), }; const BehaviorScript bhvThreeCoinsSpawn[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvThreeCoinsSpawn), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), BEGIN_REPEAT(3), SPAWN_CHILD(/*Model*/ MODEL_YELLOW_COIN, /*Behavior*/ bhvSingleCoinGetsSpawned), END_REPEAT(), DEACTIVATE(), }; const BehaviorScript bhvTenCoinsSpawn[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvTenCoinsSpawn), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), BEGIN_REPEAT(10), SPAWN_CHILD(/*Model*/ MODEL_YELLOW_COIN, /*Behavior*/ bhvSingleCoinGetsSpawned), END_REPEAT(), DEACTIVATE(), }; const BehaviorScript bhvSingleCoinGetsSpawned[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhvSingleCoinGetsSpawned), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), BILLBOARD(), CALL_NATIVE(bhv_coin_init), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 30, /*Gravity*/ -400, /*Bounciness*/ -70, /*Drag strength*/ 1000, /*Friction*/ 1000, /*Buoyancy*/ 200, /*Unused*/ 0, 0), BEGIN_LOOP(), CALL_NATIVE(bhv_coin_loop), ADD_INT(oAnimState, 1), END_LOOP(), }; const BehaviorScript bhvCoinSparkles[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvCoinSparkles), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), BILLBOARD(), SET_FLOAT(oGraphYOffset, 25), SET_INT(oAnimState, -1), BEGIN_REPEAT(8), ADD_INT(oAnimState, 1), END_REPEAT(), BEGIN_REPEAT(2), CALL_NATIVE(bhv_coin_sparkles_loop), END_REPEAT(), DEACTIVATE(), }; const BehaviorScript bhvGoldenCoinSparkles[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvGoldenCoinSparkles), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), DISABLE_RENDERING(), BEGIN_REPEAT(3), CALL_NATIVE(bhv_golden_coin_sparkles_loop), END_REPEAT(), DEACTIVATE(), }; const BehaviorScript bhvWallTinyStarParticle[] = { BEGIN(OBJ_LIST_UNIMPORTANT), ID(id_bhvWallTinyStarParticle), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), BILLBOARD(), BEGIN_REPEAT(10), CALL_NATIVE(bhv_wall_tiny_star_particle_loop), END_REPEAT(), DEACTIVATE(), }; const BehaviorScript bhvVertStarParticleSpawner[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvVertStarParticleSpawner), DISABLE_RENDERING(), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), PARENT_BIT_CLEAR(oActiveParticleFlags, ACTIVE_PARTICLE_V_STAR), CALL_NATIVE(bhv_tiny_star_particles_init), DELAY(1), DEACTIVATE(), }; const BehaviorScript bhvPoundTinyStarParticle[] = { BEGIN(OBJ_LIST_UNIMPORTANT), ID(id_bhvPoundTinyStarParticle), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), BILLBOARD(), BEGIN_REPEAT(10), CALL_NATIVE(bhv_pound_tiny_star_particle_loop), END_REPEAT(), DEACTIVATE(), }; const BehaviorScript bhvHorStarParticleSpawner[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvHorStarParticleSpawner), DISABLE_RENDERING(), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), PARENT_BIT_CLEAR(oActiveParticleFlags, ACTIVE_PARTICLE_H_STAR), CALL_NATIVE(bhv_pound_tiny_star_particle_init), DELAY(1), DEACTIVATE(), }; const BehaviorScript bhvPunchTinyTriangle[] = { BEGIN(OBJ_LIST_UNIMPORTANT), ID(id_bhvPunchTinyTriangle), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), BILLBOARD(), BEGIN_LOOP(), CALL_NATIVE(bhv_punch_tiny_triangle_loop), END_LOOP(), }; const BehaviorScript bhvTriangleParticleSpawner[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvTriangleParticleSpawner), DISABLE_RENDERING(), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), PARENT_BIT_CLEAR(oActiveParticleFlags, ACTIVE_PARTICLE_TRIANGLE), CALL_NATIVE(bhv_punch_tiny_triangle_init), DELAY(1), DEACTIVATE(), }; const BehaviorScript bhvDoorWarp[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvDoorWarp), SET_INT(oInteractType, INTERACT_WARP_DOOR), GOTO(bhvDoor + 1 + 1 + 1), }; const BehaviorScript bhvDoor[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvDoor), SET_INT(oInteractType, INTERACT_DOOR), // Door - common: OR_INT(oFlags, (OBJ_FLAG_ACTIVE_FROM_AFAR | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_ANIMATIONS(oAnimations, &door_seg3_anims_030156C0), ANIMATE(0), LOAD_COLLISION_DATA(door_seg3_collision_0301CE78), SET_HITBOX(/*Radius*/ 80, /*Height*/ 100), SET_INT(oIntangibleTimer, 0), SET_FLOAT(oCollisionDistance, 1000), SET_HOME(), CALL_NATIVE(bhv_door_init), BEGIN_LOOP(), CALL_NATIVE(bhv_door_loop), END_LOOP(), }; const BehaviorScript bhvGrindel[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvGrindel), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_COLLISION_DATA(ssl_seg7_collision_grindel), DROP_TO_FLOOR(), ADD_FLOAT(oPosY, 1), SET_HOME(), BEGIN_LOOP(), CALL_NATIVE(bhv_grindel_thwomp_loop), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvThwomp2[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvThwomp2), LOAD_COLLISION_DATA(thwomp_seg5_collision_0500B92C), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), DROP_TO_FLOOR(), ADD_FLOAT(oPosY, 1), SET_HOME(), SCALE(/*Unused*/ 0, /*Field*/ 140), SET_FLOAT(oDrawingDistance, 4000), BEGIN_LOOP(), CALL_NATIVE(bhv_grindel_thwomp_loop), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvThwomp[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvThwomp), LOAD_COLLISION_DATA(thwomp_seg5_collision_0500B7D0), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), DROP_TO_FLOOR(), ADD_FLOAT(oPosY, 1), SCALE(/*Unused*/ 0, /*Field*/ 140), SET_HOME(), SET_FLOAT(oDrawingDistance, 4000), BEGIN_LOOP(), CALL_NATIVE(bhv_grindel_thwomp_loop), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvTumblingBridgePlatform[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvTumblingBridgePlatform), OR_INT(oFlags, (OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), SET_FLOAT(oCollisionDistance, 300), BEGIN_LOOP(), CALL_NATIVE(bhv_tumbling_bridge_platform_loop), END_LOOP(), }; const BehaviorScript bhvWfTumblingBridge[] = { BEGIN(OBJ_LIST_SPAWNER), ID(id_bhvWfTumblingBridge), OR_INT(oFlags, (OBJ_FLAG_ACTIVE_FROM_AFAR | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), SET_HOME(), BEGIN_LOOP(), CALL_NATIVE(bhv_tumbling_bridge_loop), END_LOOP(), }; const BehaviorScript bhvBbhTumblingBridge[] = { BEGIN(OBJ_LIST_SPAWNER), ID(id_bhvBbhTumblingBridge), OR_INT(oFlags, (OBJ_FLAG_ACTIVE_FROM_AFAR | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), SET_HOME(), SET_INT(oBehParams2ndByte, 1), BEGIN_LOOP(), CALL_NATIVE(bhv_tumbling_bridge_loop), END_LOOP(), }; const BehaviorScript bhvLllTumblingBridge[] = { BEGIN(OBJ_LIST_SPAWNER), ID(id_bhvLllTumblingBridge), OR_INT(oFlags, (OBJ_FLAG_ACTIVE_FROM_AFAR | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), SET_HOME(), SET_INT(oBehParams2ndByte, 2), BEGIN_LOOP(), CALL_NATIVE(bhv_tumbling_bridge_loop), END_LOOP(), }; const BehaviorScript bhvFlame[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhvFlame), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), BILLBOARD(), SET_HOME(), SCALE(/*Unused*/ 0, /*Field*/ 700), SET_INTERACT_TYPE(INTERACT_FLAME), SET_HITBOX_WITH_OFFSET(/*Radius*/ 50, /*Height*/ 25, /*Downwards offset*/ 25), SET_INT(oIntangibleTimer, 0), CALL_NATIVE(bhv_init_room), BEGIN_LOOP(), SET_INT(oInteractStatus, 0), ANIMATE_TEXTURE(oAnimState, 2), END_LOOP(), }; const BehaviorScript bhvAnotherElavator[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvAnotherElavator), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_COLLISION_DATA(hmc_seg7_collision_elevator), SET_HOME(), CALL_NATIVE(bhv_elevator_init), BEGIN_LOOP(), CALL_NATIVE(bhv_elevator_loop), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvRrElevatorPlatform[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvRrElevatorPlatform), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_COLLISION_DATA(rr_seg7_collision_elevator_platform), SET_HOME(), CALL_NATIVE(bhv_elevator_init), BEGIN_LOOP(), CALL_NATIVE(bhv_elevator_loop), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvHmcElevatorPlatform[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvHmcElevatorPlatform), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_COLLISION_DATA(hmc_seg7_collision_elevator), SET_HOME(), CALL_NATIVE(bhv_elevator_init), CALL_NATIVE(bhv_init_room), BEGIN_LOOP(), CALL_NATIVE(bhv_elevator_loop), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvWaterMist[] = { BEGIN(OBJ_LIST_UNIMPORTANT), ID(id_bhvWaterMist), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), BILLBOARD(), SET_INT(oOpacity, 254), SET_FLOAT(oForwardVel, 20), SET_FLOAT(oVelY, -8), ADD_FLOAT(oPosY, 62), BEGIN_LOOP(), CALL_NATIVE(bhv_water_mist_loop), END_LOOP(), }; const BehaviorScript bhvBreathParticleSpawner[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvBreathParticleSpawner), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), BEGIN_REPEAT(8), CALL_NATIVE(bhv_water_mist_spawn_loop), END_REPEAT(), DEACTIVATE(), }; const BehaviorScript bhvBreakBoxTriangle[] = { BEGIN(OBJ_LIST_UNIMPORTANT), ID(id_bhvBreakBoxTriangle), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), BEGIN_REPEAT(18), CALL_NATIVE(cur_obj_rotate_face_angle_using_vel), CALL_NATIVE(cur_obj_move_using_fvel_and_gravity), END_REPEAT(), DEACTIVATE(), }; const BehaviorScript bhvWaterMist2[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvWaterMist2), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), SET_HOME(), SET_INT(oFaceAnglePitch, 0xC000), SCALE(/*Unused*/ 0, /*Field*/ 2100), BEGIN_LOOP(), CALL_NATIVE(bhv_water_mist_2_loop), END_LOOP(), }; const BehaviorScript bhvUnused0DFC[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvUnused0DFC), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), SET_INT(oAnimState, -1), SET_FLOAT(oFaceAnglePitch, 0), SET_FLOAT(oFaceAngleYaw, 0), SET_FLOAT(oFaceAngleRoll, 0), BEGIN_REPEAT(6), ADD_INT(oAnimState, 1), END_REPEAT(), DEACTIVATE(), }; const BehaviorScript bhvMistCircParticleSpawner[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvMistCircParticleSpawner), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), CALL_NATIVE(bhv_pound_white_puffs_init), DELAY(1), DEACTIVATE(), }; const BehaviorScript bhvDirtParticleSpawner[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvDirtParticleSpawner), BEGIN(OBJ_LIST_DEFAULT), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), CALL_NATIVE(bhv_ground_sand_init), DELAY(1), DEACTIVATE(), }; const BehaviorScript bhvSnowParticleSpawner[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvSnowParticleSpawner), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), CALL_NATIVE(bhv_ground_snow_init), DELAY(1), DEACTIVATE(), }; const BehaviorScript bhvWind[] = { BEGIN(OBJ_LIST_UNIMPORTANT), ID(id_bhvWind), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), BEGIN_LOOP(), CALL_NATIVE(bhv_wind_loop), END_LOOP(), }; const BehaviorScript bhvEndToad[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvEndToad), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), LOAD_ANIMATIONS(oAnimations, &toad_seg6_anims_0600FB58), ANIMATE(0), BEGIN_LOOP(), CALL_NATIVE(bhv_end_toad_loop), END_LOOP(), }; const BehaviorScript bhvEndPeach[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvEndPeach), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), LOAD_ANIMATIONS(oAnimations, &peach_seg5_anims_0501C41C), ANIMATE(0), BEGIN_LOOP(), CALL_NATIVE(bhv_end_peach_loop), END_LOOP(), }; const BehaviorScript bhvUnusedParticleSpawn[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvUnusedParticleSpawn), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 30, /*Gravity*/ -400, /*Bounciness*/ -50, /*Drag strength*/ 1000, /*Friction*/ 1000, /*Buoyancy*/ 200, /*Unused*/ 0, 0), SET_INT(oIntangibleTimer, 0), SET_HITBOX(/*Radius*/ 40, /*Height*/ 40), BEGIN_LOOP(), CALL_NATIVE(bhv_unused_particle_spawn_loop), END_LOOP(), }; const BehaviorScript bhvUkiki[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvUkiki), GOTO(bhvMacroUkiki + 1 + 1), }; const BehaviorScript bhvUkikiCageChild[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvUkikiCageChild), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), SET_FLOAT(oPosX, 2560), SET_FLOAT(oPosY, 1457), SET_FLOAT(oPosZ, 1898), BREAK(), }; const BehaviorScript bhvUkikiCageStar[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvUkikiCageStar), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), SET_HOME(), BEGIN_LOOP(), CALL_NATIVE(bhv_ukiki_cage_star_loop), END_LOOP(), }; const BehaviorScript bhvUkikiCage[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvUkikiCage), OR_INT(oFlags, (OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), SET_HOME(), LOAD_COLLISION_DATA(ttm_seg7_collision_ukiki_cage), SPAWN_CHILD(/*Model*/ MODEL_STAR, /*Behavior*/ bhvUkikiCageStar), SPAWN_CHILD(/*Model*/ MODEL_NONE, /*Behavior*/ bhvUkikiCageChild), SET_FLOAT(oCollisionDistance, 20000), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 30, /*Gravity*/ -400, /*Bounciness*/ -50, /*Drag strength*/ 1000, /*Friction*/ 1000, /*Buoyancy*/ 200, /*Unused*/ 0, 0), BEGIN_LOOP(), CALL_NATIVE(bhv_ukiki_cage_loop), END_LOOP(), }; const BehaviorScript bhvBitfsSinkingPlatforms[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvBitfsSinkingPlatforms), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), LOAD_COLLISION_DATA(bitfs_seg7_collision_sinking_platform), SET_HOME(), BEGIN_LOOP(), CALL_NATIVE(bhv_bitfs_sinking_platform_loop), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvBitfsSinkingCagePlatform[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvBitfsSinkingCagePlatform), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), LOAD_COLLISION_DATA(bitfs_seg7_collision_sinking_cage_platform), SET_HOME(), SPAWN_CHILD(/*Model*/ MODEL_BITFS_BLUE_POLE, /*Behavior*/ bhvDddMovingPole), BEGIN_LOOP(), CALL_NATIVE(bhv_bitfs_sinking_cage_platform_loop), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvDddMovingPole[] = { BEGIN(OBJ_LIST_POLELIKE), ID(id_bhvDddMovingPole), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), SET_INT(oInteractType, INTERACT_POLE), SET_HITBOX(/*Radius*/ 80, /*Height*/ 710), SET_INT(oIntangibleTimer, 0), BEGIN_LOOP(), CALL_NATIVE(bhv_ddd_moving_pole_loop), CALL_NATIVE(bhv_pole_base_loop), END_LOOP(), }; const BehaviorScript bhvBitfsTiltingInvertedPyramid[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvBitfsTiltingInvertedPyramid), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_COLLISION_DATA(bitfs_seg7_collision_inverted_pyramid), SET_HOME(), CALL_NATIVE(bhv_platform_normals_init), BEGIN_LOOP(), CALL_NATIVE(bhv_tilting_inverted_pyramid_loop), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvSquishablePlatform[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvSquishablePlatform), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_COLLISION_DATA(bitfs_seg7_collision_squishable_platform), SET_FLOAT(oCollisionDistance, 10000), CALL_NATIVE(bhv_platform_normals_init), BEGIN_LOOP(), CALL_NATIVE(bhv_squishable_platform_loop), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvCutOutObject[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvCutOutObject), DISABLE_RENDERING(), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), BREAK(), }; const BehaviorScript bhvBetaMovingFlamesSpawn[] = { BEGIN_LOOP(), CALL_NATIVE(bhv_beta_moving_flames_spawn_loop), END_LOOP(), }; const BehaviorScript bhvBetaMovingFlames[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhvBetaMovingFlames), OR_INT(oFlags, (OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_MOVE_XZ_USING_FVEL | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), BILLBOARD(), BEGIN_LOOP(), CALL_NATIVE(bhv_beta_moving_flames_loop), ADD_INT(oAnimState, 1), END_LOOP(), }; const BehaviorScript bhvRrRotatingBridgePlatform[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvRrRotatingBridgePlatform), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_COLLISION_DATA(rr_seg7_collision_rotating_platform_with_fire), SET_FLOAT(oCollisionDistance, 1500), SET_HOME(), BEGIN_LOOP(), CALL_NATIVE(bhv_rr_rotating_bridge_platform_loop), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvFlamethrower[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvFlamethrower), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), SET_HOME(), BEGIN_LOOP(), CALL_NATIVE(bhv_flamethrower_loop), END_LOOP(), }; const BehaviorScript bhvFlamethrowerFlame[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvFlamethrowerFlame), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), SET_INTERACT_TYPE(INTERACT_FLAME), SET_HITBOX_WITH_OFFSET(/*Radius*/ 50, /*Height*/ 25, /*Downwards offset*/ 25), BILLBOARD(), SET_HOME(), SET_INT(oIntangibleTimer, 0), CALL_NATIVE(bhv_init_room), BEGIN_LOOP(), CALL_NATIVE(bhv_flamethrower_flame_loop), ADD_INT(oAnimState, 1), END_LOOP(), }; const BehaviorScript bhvBouncingFireball[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvBouncingFireball), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), DISABLE_RENDERING(), BEGIN_LOOP(), CALL_NATIVE(bhv_bouncing_fireball_loop), END_LOOP(), }; const BehaviorScript bhvBouncingFireballFlame[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvBouncingFireballFlame), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), SET_INTERACT_TYPE(INTERACT_FLAME), SET_FLOAT(oGraphYOffset, 30), SET_HITBOX_WITH_OFFSET(/*Radius*/ 50, /*Height*/ 25, /*Downwards offset*/ 25), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 30, /*Gravity*/ -400, /*Bounciness*/ -70, /*Drag strength*/ 1000, /*Friction*/ 1000, /*Buoyancy*/ 200, /*Unused*/ 0, 0), BILLBOARD(), BEGIN_LOOP(), CALL_NATIVE(bhv_bouncing_fireball_flame_loop), ADD_INT(oAnimState, 1), END_LOOP(), }; const BehaviorScript bhvBowserShockWave[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvBowserShockWave), OR_INT(oFlags, (OBJ_FLAG_ACTIVE_FROM_AFAR | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), SET_INT(oOpacity, 255), BEGIN_LOOP(), CALL_NATIVE(bhv_bowser_shock_wave_loop), END_LOOP(), }; const BehaviorScript bhvFireParticleSpawner[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvFireParticleSpawner), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), BILLBOARD(), SET_FLOAT(oGraphYOffset, 70), SET_INT(oAnimState, -1), BEGIN_LOOP(), ADD_INT(oAnimState, 1), CALL_NATIVE(bhv_flame_mario_loop), END_LOOP(), }; const BehaviorScript bhvBlackSmokeMario[] = { BEGIN(OBJ_LIST_UNIMPORTANT), ID(id_bhvBlackSmokeMario), OR_INT(oFlags, (OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_MOVE_XZ_USING_FVEL | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), BILLBOARD(), SET_INT(oAnimState, 4), SET_FLOAT(oGraphYOffset, 50), BEGIN_REPEAT(8), CALL_NATIVE(bhv_black_smoke_mario_loop), DELAY(1), CALL_NATIVE(bhv_black_smoke_mario_loop), DELAY(1), CALL_NATIVE(bhv_black_smoke_mario_loop), END_REPEAT(), DEACTIVATE(), }; const BehaviorScript bhvBlackSmokeBowser[] = { BEGIN(OBJ_LIST_UNIMPORTANT), ID(id_bhvBlackSmokeBowser), OR_INT(oFlags, (OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_MOVE_XZ_USING_FVEL | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), BILLBOARD(), SET_FLOAT(oGraphYOffset, 0), BEGIN_REPEAT(8), CALL_NATIVE(bhv_black_smoke_bowser_loop), ANIMATE_TEXTURE(oAnimState, 4), END_REPEAT(), DEACTIVATE(), }; const BehaviorScript bhvBlackSmokeUpward[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvBlackSmokeUpward), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), BEGIN_REPEAT(4), CALL_NATIVE(bhv_black_smoke_upward_loop), END_REPEAT(), DEACTIVATE(), }; const BehaviorScript bhvBetaFishSplashSpawner[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvBetaFishSplashSpawner), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), DISABLE_RENDERING(), BEGIN_LOOP(), CALL_NATIVE(bhv_beta_fish_splash_spawner_loop), END_LOOP(), }; const BehaviorScript bhvSpindrift[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvSpindrift), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_ANIMATIONS(oAnimations, &spindrift_seg5_anims_05002D68), ANIMATE(0), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 30, /*Gravity*/ -400, /*Bounciness*/ 0, /*Drag strength*/ 0, /*Friction*/ 0, /*Buoyancy*/ 200, /*Unused*/ 0, 0), SET_HOME(), SET_INT(oInteractionSubtype, INT_SUBTYPE_TWIRL_BOUNCE), BEGIN_LOOP(), CALL_NATIVE(bhv_spindrift_loop), END_LOOP(), }; const BehaviorScript bhvTowerPlatformGroup[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvTowerPlatformGroup), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), DISABLE_RENDERING(), ADD_FLOAT(oPosY, 300), SET_HOME(), CALL_NATIVE(bhv_tower_platform_group_init), BEGIN_LOOP(), CALL_NATIVE(bhv_tower_platform_group_loop), END_LOOP(), }; const BehaviorScript bhvWfSlidingTowerPlatform[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvWfSlidingTowerPlatform), OR_INT(oFlags, (OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_COLLISION_DATA(wf_seg7_collision_platform), BEGIN_LOOP(), CALL_NATIVE(bhv_wf_sliding_tower_platform_loop), END_LOOP(), }; const BehaviorScript bhvWfElevatorTowerPlatform[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvWfElevatorTowerPlatform), OR_INT(oFlags, (OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_COLLISION_DATA(wf_seg7_collision_platform), BEGIN_LOOP(), CALL_NATIVE(bhv_wf_elevator_tower_platform_loop), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvWfSolidTowerPlatform[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvWfSolidTowerPlatform), OR_INT(oFlags, (OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_COLLISION_DATA(wf_seg7_collision_platform), BEGIN_LOOP(), CALL_NATIVE(bhv_wf_solid_tower_platform_loop), END_LOOP(), }; const BehaviorScript bhvLeafParticleSpawner[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvLeafParticleSpawner), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), CALL_NATIVE(bhv_snow_leaf_particle_spawn_init), DELAY(1), DEACTIVATE(), }; const BehaviorScript bhvTreeSnow[] = { BEGIN(OBJ_LIST_UNIMPORTANT), ID(id_bhvTreeSnow), OR_INT(oFlags, (OBJ_FLAG_MOVE_XZ_USING_FVEL | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), BILLBOARD(), BEGIN_LOOP(), CALL_NATIVE(bhv_tree_snow_or_leaf_loop), END_LOOP(), }; const BehaviorScript bhvTreeLeaf[] = { BEGIN(OBJ_LIST_UNIMPORTANT), ID(id_bhvTreeLeaf), OR_INT(oFlags, (OBJ_FLAG_MOVE_XZ_USING_FVEL | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), BEGIN_LOOP(), CALL_NATIVE(bhv_tree_snow_or_leaf_loop), END_LOOP(), }; const BehaviorScript bhvAnotherTiltingPlatform[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvAnotherTiltingPlatform), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), SET_HOME(), CALL_NATIVE(bhv_platform_normals_init), BEGIN_LOOP(), CALL_NATIVE(bhv_tilting_inverted_pyramid_loop), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvSquarishPathParent[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvSquarishPathParent), CALL_NATIVE(bhv_squarish_path_parent_init), BEGIN_LOOP(), CALL_NATIVE(bhv_squarish_path_parent_loop), END_LOOP(), }; const BehaviorScript bhvSquarishPathMoving[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvSquarishPathMoving), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), LOAD_COLLISION_DATA(bitdw_seg7_collision_moving_pyramid), SET_HOME(), BEGIN_LOOP(), CALL_NATIVE(bhv_squarish_path_moving_loop), END_LOOP(), }; const BehaviorScript bhvPiranhaPlantBubble[] = { BEGIN(OBJ_LIST_UNIMPORTANT), ID(id_bhvPiranhaPlantBubble), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), BILLBOARD(), BEGIN_LOOP(), CALL_NATIVE(bhv_piranha_plant_bubble_loop), END_LOOP(), }; const BehaviorScript bhvPiranhaPlantWakingBubbles[] = { BEGIN(OBJ_LIST_UNIMPORTANT), ID(id_bhvPiranhaPlantWakingBubbles), BILLBOARD(), OR_INT(oFlags, (OBJ_FLAG_ACTIVE_FROM_AFAR | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), BEGIN_REPEAT(10), CALL_NATIVE(bhv_piranha_plant_waking_bubbles_loop), END_REPEAT(), DEACTIVATE(), }; const BehaviorScript bhvFloorSwitchAnimatesObject[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvFloorSwitchAnimatesObject), SET_INT(oBehParams2ndByte, 1), GOTO(bhvFloorSwitchHardcodedModel + 1 + 1), }; const BehaviorScript bhvFloorSwitchGrills[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvFloorSwitchGrills), GOTO(bhvFloorSwitchHardcodedModel + 1 + 1), }; const BehaviorScript bhvFloorSwitchHardcodedModel[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvFloorSwitchHardcodedModel), // Floor switch - common: OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), LOAD_COLLISION_DATA(purple_switch_seg8_collision_0800C7A8), BEGIN_LOOP(), CALL_NATIVE(bhv_purple_switch_loop), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvFloorSwitchHiddenObjects[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvFloorSwitchHiddenObjects), SET_INT(oBehParams2ndByte, 2), GOTO(bhvFloorSwitchHardcodedModel + 1 + 1), }; const BehaviorScript bhvHiddenObject[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvHiddenObject), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), LOAD_COLLISION_DATA(breakable_box_seg8_collision_08012D70), SET_FLOAT(oCollisionDistance, 300), BEGIN_LOOP(), CALL_NATIVE(bhv_hidden_object_loop), END_LOOP(), }; const BehaviorScript bhvBreakableBox[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvBreakableBox), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), LOAD_COLLISION_DATA(breakable_box_seg8_collision_08012D70), SET_FLOAT(oCollisionDistance, 500), CALL_NATIVE(bhv_init_room), BEGIN_LOOP(), CALL_NATIVE(bhv_breakable_box_loop), CALL_NATIVE(load_object_collision_model), END_LOOP(), BREAK(), }; const BehaviorScript bhvPushableMetalBox[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvPushableMetalBox), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), LOAD_COLLISION_DATA(metal_box_seg8_collision_08024C28), SET_FLOAT(oCollisionDistance, 500), SET_HOME(), BEGIN_LOOP(), CALL_NATIVE(bhv_pushable_loop), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvHeaveHo[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvHeaveHo), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_HOLDABLE | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_ANIMATIONS(oAnimations, &heave_ho_seg5_anims_0501534C), ANIMATE(0), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 200, /*Gravity*/ -400, /*Bounciness*/ -50, /*Drag strength*/ 1000, /*Friction*/ 1000, /*Buoyancy*/ 600, /*Unused*/ 0, 0), SPAWN_OBJ(/*Model*/ MODEL_NONE, /*Behavior*/ bhvHeaveHoThrowMario), SET_INT(oInteractType, INTERACT_GRABBABLE), SET_INT(oInteractionSubtype, INT_SUBTYPE_NOT_GRABBABLE | INT_SUBTYPE_GRABS_MARIO), SET_HITBOX(/*Radius*/ 120, /*Height*/ 100), SET_HOME(), SET_INT(oIntangibleTimer, 0), BEGIN_LOOP(), CALL_NATIVE(bhv_heave_ho_loop), END_LOOP(), }; const BehaviorScript bhvHeaveHoThrowMario[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvHeaveHoThrowMario), OR_INT(oFlags, (OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), BILLBOARD(), BEGIN_LOOP(), CALL_NATIVE(bhv_heave_ho_throw_mario_loop), END_LOOP(), }; const BehaviorScript bhvCcmTouchedStarSpawn[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhvCcmTouchedStarSpawn), OR_INT(oFlags, (OBJ_FLAG_PERSISTENT_RESPAWN | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), SET_HITBOX(/*Radius*/ 500, /*Height*/ 500), SET_INT(oIntangibleTimer, 0), BEGIN_LOOP(), CALL_NATIVE(bhv_ccm_touched_star_spawn_loop), END_LOOP(), }; const BehaviorScript bhvUnusedPoundablePlatform[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvUnusedPoundablePlatform), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), LOAD_COLLISION_DATA(sl_seg7_collision_pound_explodes), SET_HOME(), BEGIN_LOOP(), CALL_NATIVE(bhv_unused_poundable_platform), END_LOOP(), }; const BehaviorScript bhvBetaTrampolineTop[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvBetaTrampolineTop), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), LOAD_COLLISION_DATA(springboard_collision_05001A28), SET_HOME(), BEGIN_LOOP(), CALL_NATIVE(bhv_beta_trampoline_top_loop), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvBetaTrampolineSpring[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvBetaTrampolineSpring), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), SET_HOME(), BEGIN_LOOP(), CALL_NATIVE(bhv_beta_trampoline_spring_loop), END_LOOP(), }; const BehaviorScript bhvJumpingBox[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvJumpingBox), OR_INT(oFlags, (OBJ_FLAG_HOLDABLE | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 30, /*Gravity*/ -400, /*Bounciness*/ -50, /*Drag strength*/ 1000, /*Friction*/ 1000, /*Buoyancy*/ 600, /*Unused*/ 0, 0), BEGIN_LOOP(), CALL_NATIVE(bhv_jumping_box_loop), END_LOOP(), }; const BehaviorScript bhvBooCage[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvBooCage), OR_INT(oFlags, (OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), SET_FLOAT(oGraphYOffset, 10), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 30, /*Gravity*/ -400, /*Bounciness*/ -50, /*Drag strength*/ 0, /*Friction*/ 0, /*Buoyancy*/ 200, /*Unused*/ 0, 0), CALL_NATIVE(bhv_boo_cage_init), BEGIN_LOOP(), CALL_NATIVE(bhv_boo_cage_loop), END_LOOP(), }; const BehaviorScript bhvStub[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvStub), DISABLE_RENDERING(), BREAK(), }; const BehaviorScript bhvIgloo[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhvIgloo), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), SET_INTERACT_TYPE(INTERACT_IGLOO_BARRIER), SET_HITBOX(/*Radius*/ 100, /*Height*/ 200), SET_INT(oIntangibleTimer, 0), SET_HOME(), BEGIN_LOOP(), SET_INT(oInteractStatus, 0), END_LOOP(), }; const BehaviorScript bhvBowserKey[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhvBowserKey), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), SET_HOME(), CALL_NATIVE(bhv_bowser_key_init), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 30, /*Gravity*/ -400, /*Bounciness*/ -70, /*Drag strength*/ 1000, /*Friction*/ 1000, /*Buoyancy*/ 200, /*Unused*/ 0, 0), BEGIN_LOOP(), CALL_NATIVE(bhv_bowser_key_loop), END_LOOP(), }; const BehaviorScript bhvGrandStar[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhvGrandStar), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), SET_INTERACT_TYPE(INTERACT_STAR_OR_KEY), SET_INT(oInteractionSubtype, INT_SUBTYPE_GRAND_STAR), SET_HITBOX(/*Radius*/ 160, /*Height*/ 100), SET_HOME(), CALL_NATIVE(bhv_grand_star_init), BEGIN_LOOP(), CALL_NATIVE(bhv_grand_star_loop), END_LOOP(), }; const BehaviorScript bhvBetaBooKey[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhvBetaBooKey), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), SET_HITBOX(/*Radius*/ 32, /*Height*/ 64), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 30, /*Gravity*/ -400, /*Bounciness*/ -70, /*Drag strength*/ 1000, /*Friction*/ 1000, /*Buoyancy*/ 200, /*Unused*/ 0, 0), BEGIN_LOOP(), CALL_NATIVE(bhv_beta_boo_key_loop), END_LOOP(), }; const BehaviorScript bhvAlphaBooKey[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhvAlphaBooKey), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), SET_HITBOX(/*Radius*/ 32, /*Height*/ 64), SET_INT(oIntangibleTimer, 0), BEGIN_LOOP(), CALL_NATIVE(bhv_alpha_boo_key_loop), END_LOOP(), }; const BehaviorScript bhvBulletBill[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvBulletBill), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_MOVE_XZ_USING_FVEL | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), SET_HOME(), SET_HITBOX_WITH_OFFSET(/*Radius*/ 50, /*Height*/ 50, /*Downwards offset*/ 50), SET_INTERACT_TYPE(INTERACT_DAMAGE), SET_INT(oDamageOrCoinValue, 3), SCALE(/*Unused*/ 0, /*Field*/ 40), SET_INT(oIntangibleTimer, 0), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 30, /*Gravity*/ 0, /*Bounciness*/ 0, /*Drag strength*/ 0, /*Friction*/ 0, /*Buoyancy*/ 0, /*Unused*/ 0, 0), CALL_NATIVE(bhv_bullet_bill_init), BEGIN_LOOP(), CALL_NATIVE(bhv_bullet_bill_loop), END_LOOP(), }; const BehaviorScript bhvWhitePuffSmoke[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvWhitePuffSmoke), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), BILLBOARD(), ADD_FLOAT(oPosY, -100), CALL_NATIVE(bhv_white_puff_smoke_init), SET_INT(oAnimState, -1), BEGIN_REPEAT(10), ADD_INT(oAnimState, 1), END_REPEAT(), DEACTIVATE(), }; const BehaviorScript bhvUnused1820[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvUnused1820), BREAK(), }; const BehaviorScript bhvBowserTailAnchor[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvBowserTailAnchor), SET_HITBOX_WITH_OFFSET(/*Radius*/ 100, /*Height*/ 50, /*Downwards offset*/ -50), SET_INT(oIntangibleTimer, 0), DISABLE_RENDERING(), CALL_NATIVE(bhv_bowser_tail_anchor_init), BEGIN_LOOP(), CALL_NATIVE(bhv_bowser_tail_anchor_loop), END_LOOP(), }; const BehaviorScript bhvBowser[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvBowser), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_HOLDABLE | OBJ_FLAG_ACTIVE_FROM_AFAR | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), SET_INT(oInteractType, INTERACT_GRABBABLE), SET_HITBOX(/*Radius*/ 400, /*Height*/ 400), DROP_TO_FLOOR(), SET_HOME(), LOAD_ANIMATIONS(oAnimations, &bowser_seg6_anims_06057690), SPAWN_CHILD(/*Model*/ MODEL_NONE, /*Behavior*/ bhvBowserBodyAnchor), SPAWN_CHILD(/*Model*/ MODEL_BOWSER_BOMB_CHILD_OBJ, /*Behavior*/ bhvBowserFlameSpawn), SPAWN_OBJ(/*Model*/ MODEL_NONE, /*Behavior*/ bhvBowserTailAnchor), SET_INT(oNumLootCoins, 50), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 0, /*Gravity*/ -400, /*Bounciness*/ -70, /*Drag strength*/ 1000, /*Friction*/ 1000, /*Buoyancy*/ 200, /*Unused*/ 0, 0), SET_HOME(), CALL_NATIVE(bhv_bowser_init), BEGIN_LOOP(), CALL_NATIVE(bhv_bowser_loop), END_LOOP(), }; const BehaviorScript bhvBowserBodyAnchor[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvBowserBodyAnchor), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), SET_HITBOX(/*Radius*/ 100, /*Height*/ 300), SET_INTERACT_TYPE(INTERACT_DAMAGE), SET_INT(oInteractionSubtype, INT_SUBTYPE_BIG_KNOCKBACK), DISABLE_RENDERING(), SET_INT(oDamageOrCoinValue, 2), SET_INT(oIntangibleTimer, 0), CALL_NATIVE(bhv_bowser_body_anchor_init), BEGIN_LOOP(), CALL_NATIVE(bhv_bowser_body_anchor_loop), END_LOOP(), }; const BehaviorScript bhvBowserFlameSpawn[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvBowserFlameSpawn), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), SET_MODEL(MODEL_NONE), BEGIN_LOOP(), CALL_NATIVE(bhv_bowser_flame_spawn_loop), END_LOOP(), }; const BehaviorScript bhvTiltingBowserLavaPlatform[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvTiltingBowserLavaPlatform), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_COLLISION_DATA(bowser_2_seg7_collision_tilting_platform), SET_FLOAT(oDrawingDistance, 20000), SET_FLOAT(oCollisionDistance, 20000), SET_INT(oFaceAngleYaw, 0), SET_HOME(), CALL_NATIVE(bhv_tilting_bowser_lava_platform_init), BEGIN_LOOP(), CALL_NATIVE(cur_obj_rotate_face_angle_using_vel), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvFallingBowserPlatform[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvFallingBowserPlatform), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), SET_FLOAT(oDrawingDistance, 20000), SET_FLOAT(oCollisionDistance, 20000), SET_HOME(), BEGIN_LOOP(), CALL_NATIVE(bhv_falling_bowser_platform_loop), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvBlueBowserFlame[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhvBlueBowserFlame), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), SET_INTERACT_TYPE(INTERACT_FLAME), BILLBOARD(), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 0, /*Gravity*/ -400, /*Bounciness*/ -70, /*Drag strength*/ 1000, /*Friction*/ 1000, /*Buoyancy*/ 200, /*Unused*/ 0, 0), CALL_NATIVE(bhv_blue_bowser_flame_init), BEGIN_LOOP(), CALL_NATIVE(bhv_blue_bowser_flame_loop), ANIMATE_TEXTURE(oAnimState, 2), END_LOOP(), }; const BehaviorScript bhvFlameFloatingLanding[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhvFlameFloatingLanding), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), SET_INTERACT_TYPE(INTERACT_FLAME), BILLBOARD(), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 0, /*Gravity*/ -400, /*Bounciness*/ -70, /*Drag strength*/ 1000, /*Friction*/ 1000, /*Buoyancy*/ 200, /*Unused*/ 0, 0), CALL_NATIVE(bhv_flame_floating_landing_init), BEGIN_LOOP(), CALL_NATIVE(bhv_flame_floating_landing_loop), ANIMATE_TEXTURE(oAnimState, 2), END_LOOP(), }; const BehaviorScript bhvBlueFlamesGroup[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhvBlueFlamesGroup), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), SET_INTERACT_TYPE(INTERACT_FLAME), BILLBOARD(), BEGIN_LOOP(), CALL_NATIVE(bhv_blue_flames_group_loop), END_LOOP(), }; const BehaviorScript bhvFlameBouncing[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhvFlameBouncing), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), SET_INTERACT_TYPE(INTERACT_FLAME), BILLBOARD(), CALL_NATIVE(bhv_flame_bouncing_init), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 0, /*Gravity*/ -400, /*Bounciness*/ -70, /*Drag strength*/ 0, /*Friction*/ 0, /*Buoyancy*/ 200, /*Unused*/ 0, 0), BEGIN_LOOP(), CALL_NATIVE(bhv_flame_bouncing_loop), ANIMATE_TEXTURE(oAnimState, 2), END_LOOP(), }; const BehaviorScript bhvFlameMovingForwardGrowing[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhvFlameMovingForwardGrowing), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), SET_INTERACT_TYPE(INTERACT_FLAME), BILLBOARD(), CALL_NATIVE(bhv_flame_moving_forward_growing_init), BEGIN_LOOP(), CALL_NATIVE(bhv_flame_moving_forward_growing_loop), ANIMATE_TEXTURE(oAnimState, 2), END_LOOP(), }; const BehaviorScript bhvFlameBowser[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhvFlameBowser), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), SET_INTERACT_TYPE(INTERACT_FLAME), BILLBOARD(), CALL_NATIVE(bhv_flame_bowser_init), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 0, /*Gravity*/ -400, /*Bounciness*/ -70, /*Drag strength*/ 1000, /*Friction*/ 1000, /*Buoyancy*/ 200, /*Unused*/ 0, 0), BEGIN_LOOP(), CALL_NATIVE(bhv_flame_bowser_loop), ANIMATE_TEXTURE(oAnimState, 2), END_LOOP(), }; const BehaviorScript bhvFlameLargeBurningOut[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhvFlameLargeBurningOut), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), SET_INTERACT_TYPE(INTERACT_FLAME), BILLBOARD(), CALL_NATIVE(bhv_flame_large_burning_out_init), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 0, /*Gravity*/ -400, /*Bounciness*/ -70, /*Drag strength*/ 1000, /*Friction*/ 1000, /*Buoyancy*/ 200, /*Unused*/ 0, 0), BEGIN_LOOP(), CALL_NATIVE(bhv_flame_bowser_loop), ANIMATE_TEXTURE(oAnimState, 2), END_LOOP(), }; const BehaviorScript bhvBlueFish[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvBlueFish), OR_INT(oFlags, (OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), SET_HOME(), LOAD_ANIMATIONS(oAnimations, &blue_fish_seg3_anims_0301C2B0), ANIMATE(0), BEGIN_LOOP(), CALL_NATIVE(bhv_blue_fish_movement_loop), END_LOOP(), }; const BehaviorScript bhvTankFishGroup[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvTankFishGroup), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), SET_HOME(), BEGIN_LOOP(), CALL_NATIVE(bhv_tank_fish_group_loop), END_LOOP(), }; const BehaviorScript bhvCheckerboardElevatorGroup[] = { BEGIN(OBJ_LIST_SPAWNER), ID(id_bhvCheckerboardElevatorGroup), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), CALL_NATIVE(bhv_checkerboard_elevator_group_init), BEGIN_LOOP(), CALL_NATIVE(bhv_checkerboard_elevator_group_loop), END_LOOP(), DEACTIVATE(), }; const BehaviorScript bhvCheckerboardPlatformSub[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvCheckerboardPlatformSub), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_COLLISION_DATA(checkerboard_platform_seg8_collision_0800D710), CALL_NATIVE(bhv_checkerboard_platform_init), SET_HOME(), BEGIN_LOOP(), CALL_NATIVE(bhv_checkerboard_platform_loop), END_LOOP(), }; const BehaviorScript bhvBowserKeyUnlockDoor[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvBowserKeyUnlockDoor), LOAD_ANIMATIONS(oAnimations, &bowser_key_seg3_anims_list), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), BEGIN_LOOP(), CALL_NATIVE(bhv_bowser_key_unlock_door_loop), END_LOOP(), }; const BehaviorScript bhvBowserKeyCourseExit[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvBowserKeyCourseExit), LOAD_ANIMATIONS(oAnimations, &bowser_key_seg3_anims_list), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), BEGIN_LOOP(), CALL_NATIVE(bhv_bowser_key_course_exit_loop), END_LOOP(), }; const BehaviorScript bhvInvisibleObjectsUnderBridge[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvInvisibleObjectsUnderBridge), CALL_NATIVE(bhv_invisible_objects_under_bridge_init), BEGIN_LOOP(), CALL_NATIVE(bhv_invisible_objects_under_bridge_loop), END_LOOP(), }; const BehaviorScript bhvWaterLevelPillar[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvWaterLevelPillar), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), LOAD_COLLISION_DATA(inside_castle_seg7_collision_water_level_pillar), CALL_NATIVE(bhv_water_level_pillar_init), BEGIN_LOOP(), CALL_NATIVE(bhv_water_level_pillar_loop), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvDddWarp[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvDddWarp), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), SET_FLOAT(oCollisionDistance, 30000), BEGIN_LOOP(), CALL_NATIVE(bhv_ddd_warp_loop), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvMoatGrills[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvMoatGrills), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), LOAD_COLLISION_DATA(castle_grounds_seg7_collision_moat_grills), SET_FLOAT(oCollisionDistance, 30000), BEGIN_LOOP(), CALL_NATIVE(bhv_moat_grills_loop), END_LOOP(), }; const BehaviorScript bhvClockMinuteHand[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvClockMinuteHand), SET_INT(oAngleVelRoll, -0x180), GOTO(bhvClockHourHand + 1 + 1 + 1), }; const BehaviorScript bhvClockHourHand[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvClockHourHand), SET_INT(oAngleVelRoll, -0x20), // Clock hand - common: OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), CALL_NATIVE(bhv_init_room), BEGIN_LOOP(), CALL_NATIVE(bhv_rotating_clock_arm_loop), END_LOOP(), }; const BehaviorScript bhvMacroUkiki[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvMacroUkiki), // Ukiki - common: OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_HOLDABLE | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), SET_INT(oInteractType, INTERACT_GRABBABLE), SET_INT(oInteractionSubtype, INT_SUBTYPE_HOLDABLE_NPC), SET_HITBOX(/*Radius*/ 40, /*Height*/ 40), SET_INT(oIntangibleTimer, 0), DROP_TO_FLOOR(), LOAD_ANIMATIONS(oAnimations, &ukiki_seg5_anims_05015784), ANIMATE(0), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 30, /*Gravity*/ -400, /*Bounciness*/ -50, /*Drag strength*/ 0, /*Friction*/ 0, /*Buoyancy*/ 200, /*Unused*/ 0, 0), SET_HOME(), CALL_NATIVE(bhv_ukiki_init), BEGIN_LOOP(), CALL_NATIVE(bhv_ukiki_loop), END_LOOP(), }; const BehaviorScript bhvStub1D0C[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvStub1D0C), DEACTIVATE(), }; const BehaviorScript bhvLllRotatingHexagonalPlatform[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvLllRotatingHexagonalPlatform), OR_INT(oFlags, (OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_COLLISION_DATA(lll_seg7_collision_hexagonal_platform), SET_HOME(), BEGIN_LOOP(), SET_INT(oAngleVelYaw, 0x100), ADD_INT(oMoveAngleYaw, 0x100), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvLllSinkingRockBlock[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvLllSinkingRockBlock), OR_INT(oFlags, (OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_COLLISION_DATA(lll_seg7_collision_floating_block), ADD_FLOAT(oPosY, -50), SET_HOME(), BEGIN_LOOP(), CALL_NATIVE(bhv_lll_sinking_rock_block_loop), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvStub1D70[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvStub1D70), BREAK(), }; const BehaviorScript bhvLllMovingOctagonalMeshPlatform[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvLllMovingOctagonalMeshPlatform), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), ADD_FLOAT(oPosY, -50), LOAD_COLLISION_DATA(lll_seg7_collision_octagonal_moving_platform), BEGIN_LOOP(), CALL_NATIVE(bhv_lll_moving_octagonal_mesh_platform_loop), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvSnowBall[] = { BREAK(), }; const BehaviorScript bhvLllRotatingBlockWithFireBars[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvLllRotatingBlockWithFireBars), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_COLLISION_DATA(lll_seg7_collision_rotating_fire_bars), SET_FLOAT(oCollisionDistance, 4000), BEGIN_LOOP(), CALL_NATIVE(bhv_lll_rotating_block_fire_bars_loop), END_LOOP(), }; const BehaviorScript bhvLllRotatingHexFlame[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhvLllRotatingHexFlame), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), SET_INTERACT_TYPE(INTERACT_FLAME), SET_HITBOX_WITH_OFFSET(/*Radius*/ 50, /*Height*/ 100, /*Downwards offset*/ 50), SET_INT(oIntangibleTimer, 0), BILLBOARD(), BEGIN_LOOP(), CALL_NATIVE(bhv_lll_rotating_hex_flame_loop), ADD_INT(oAnimState, 1), END_LOOP(), }; const BehaviorScript bhvLllWoodPiece[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvLllWoodPiece), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_COLLISION_DATA(lll_seg7_collision_wood_piece), SET_HOME(), BEGIN_LOOP(), CALL_NATIVE(bhv_lll_wood_piece_loop), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvLllFloatingWoodBridge[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvLllFloatingWoodBridge), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), SET_MODEL(MODEL_NONE), BEGIN_LOOP(), CALL_NATIVE(bhv_lll_floating_wood_bridge_loop), END_LOOP(), }; const BehaviorScript bhvVolcanoFlames[] = { BEGIN(OBJ_LIST_UNIMPORTANT), ID(id_bhvVolcanoFlames), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), BILLBOARD(), BEGIN_LOOP(), ADD_INT(oAnimState, 1), CALL_NATIVE(bhv_volcano_flames_loop), END_LOOP(), }; const BehaviorScript bhvLllRotatingHexagonalRing[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvLllRotatingHexagonalRing), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_COLLISION_DATA(lll_seg7_collision_rotating_platform), BEGIN_LOOP(), CALL_NATIVE(bhv_lll_rotating_hexagonal_ring_loop), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvLllSinkingRectangularPlatform[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvLllSinkingRectangularPlatform), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_COLLISION_DATA(lll_seg7_collision_slow_tilting_platform), SET_FLOAT(oCollisionDistance, 2000), SET_HOME(), BEGIN_LOOP(), CALL_NATIVE(bhv_lll_sinking_rectangular_platform_loop), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvLllSinkingSquarePlatforms[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvLllSinkingSquarePlatforms), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_COLLISION_DATA(lll_seg7_collision_sinking_pyramids), ADD_FLOAT(oPosY, 5), SET_FLOAT(oCollisionDistance, 2000), SET_HOME(), BEGIN_LOOP(), CALL_NATIVE(bhv_lll_sinking_square_platforms_loop), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvLllTiltingInvertedPyramid[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvLllTiltingInvertedPyramid), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_COLLISION_DATA(lll_seg7_collision_inverted_pyramid), ADD_FLOAT(oPosY, 5), SET_HOME(), CALL_NATIVE(bhv_platform_normals_init), BEGIN_LOOP(), CALL_NATIVE(bhv_tilting_inverted_pyramid_loop), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvUnused1F30[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvUnused1F30), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), BREAK(), }; const BehaviorScript bhvKoopaShell[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhvKoopaShell), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 30, /*Gravity*/ -400, /*Bounciness*/ -50, /*Drag strength*/ 1000, /*Friction*/ 1000, /*Buoyancy*/ 200, /*Unused*/ 0, 0), BEGIN_LOOP(), CALL_NATIVE(bhv_koopa_shell_loop), END_LOOP(), }; const BehaviorScript bhvKoopaShellFlame[] = { BEGIN(OBJ_LIST_UNIMPORTANT), ID(id_bhvKoopaShellFlame), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), SET_INTERACT_TYPE(INTERACT_FLAME), BILLBOARD(), BEGIN_LOOP(), CALL_NATIVE(bhv_koopa_shell_flame_loop), ANIMATE_TEXTURE(oAnimState, 2), END_LOOP(), }; const BehaviorScript bhvToxBox[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvToxBox), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_COLLISION_DATA(ssl_seg7_collision_tox_box), ADD_FLOAT(oPosY, 256), SET_FLOAT(oDrawingDistance, 8000), SET_HOME(), BEGIN_LOOP(), CALL_NATIVE(bhv_tox_box_loop), END_LOOP(), }; const BehaviorScript bhvPiranhaPlant[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvPiranhaPlant), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_ANIMATIONS(oAnimations, &piranha_plant_seg6_anims_0601C31C), ANIMATE(0), SET_INTERACT_TYPE(INTERACT_DAMAGE), SET_HITBOX(/*Radius*/ 100, /*Height*/ 200), SET_HURTBOX(/*Radius*/ 50, /*Height*/ 200), SET_INT(oIntangibleTimer, 0), SET_INT(oDamageOrCoinValue, 3), SET_INT(oNumLootCoins, 5), SPAWN_CHILD(/*Model*/ MODEL_BUBBLE, /*Behavior*/ bhvPiranhaPlantBubble), SET_FLOAT(oDrawingDistance, 2000), SET_HOME(), BEGIN_LOOP(), CALL_NATIVE(bhv_piranha_plant_loop), END_LOOP(), }; const BehaviorScript bhvLllHexagonalMesh[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvLllHexagonalMesh), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), LOAD_COLLISION_DATA(lll_hexagonal_mesh_seg3_collision_0301CECC), BEGIN_LOOP(), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvLllBowserPuzzlePiece[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvLllBowserPuzzlePiece), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_COLLISION_DATA(lll_seg7_collision_puzzle_piece), SET_HOME(), SET_FLOAT(oCollisionDistance, 3000), BEGIN_LOOP(), CALL_NATIVE(bhv_lll_bowser_puzzle_piece_loop), END_LOOP(), }; const BehaviorScript bhvLllBowserPuzzle[] = { BEGIN(OBJ_LIST_SPAWNER), ID(id_bhvLllBowserPuzzle), DISABLE_RENDERING(), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), ADD_FLOAT(oPosZ, -50), BEGIN_LOOP(), CALL_NATIVE(bhv_lll_bowser_puzzle_loop), END_LOOP(), }; const BehaviorScript bhvTuxiesMother[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvTuxiesMother), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_ANIMATIONS(oAnimations, &penguin_seg5_anims_05008B74), ANIMATE(3), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 30, /*Gravity*/ -400, /*Bounciness*/ -50, /*Drag strength*/ 0, /*Friction*/ 0, /*Buoyancy*/ 0, /*Unused*/ 0, 0), SET_HOME(), SET_INTERACT_TYPE(INTERACT_TEXT), SET_HITBOX(/*Radius*/ 200, /*Height*/ 300), SET_INT(oIntangibleTimer, 0), BEGIN_LOOP(), CALL_NATIVE(bhv_tuxies_mother_loop), END_LOOP(), }; const BehaviorScript bhvPenguinBaby[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvPenguinBaby), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_HOLDABLE | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), DROP_TO_FLOOR(), LOAD_ANIMATIONS(oAnimations, &penguin_seg5_anims_05008B74), ANIMATE(0), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 30, /*Gravity*/ -400, /*Bounciness*/ -50, /*Drag strength*/ 0, /*Friction*/ 0, /*Buoyancy*/ 200, /*Unused*/ 0, 0), SET_INT(oInteractType, INTERACT_GRABBABLE), SET_INT(oInteractionSubtype, INT_SUBTYPE_HOLDABLE_NPC), SET_INT(oIntangibleTimer, 0), SET_HITBOX(/*Radius*/ 40, /*Height*/ 40), SET_HOME(), BREAK(), }; const BehaviorScript bhvUnused20E0[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvUnused20E0), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_HOLDABLE | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), DROP_TO_FLOOR(), LOAD_ANIMATIONS(oAnimations, &penguin_seg5_anims_05008B74), ANIMATE(0), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 30, /*Gravity*/ -400, /*Bounciness*/ -50, /*Drag strength*/ 0, /*Friction*/ 0, /*Buoyancy*/ 200, /*Unused*/ 0, 0), SET_INT(oInteractType, INTERACT_GRABBABLE), SET_INT(oInteractionSubtype, INT_SUBTYPE_HOLDABLE_NPC), SET_INT(oIntangibleTimer, 0), SET_HITBOX(/*Radius*/ 40, /*Height*/ 40), SET_HOME(), BREAK(), }; const BehaviorScript bhvSmallPenguin[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvSmallPenguin), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_HOLDABLE | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), DROP_TO_FLOOR(), LOAD_ANIMATIONS(oAnimations, &penguin_seg5_anims_05008B74), ANIMATE(0), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 30, /*Gravity*/ -400, /*Bounciness*/ -50, /*Drag strength*/ 0, /*Friction*/ 0, /*Buoyancy*/ 200, /*Unused*/ 0, 0), SET_INT(oInteractType, INTERACT_GRABBABLE), SET_INT(oInteractionSubtype, INT_SUBTYPE_HOLDABLE_NPC), SET_INT(oIntangibleTimer, 0), SET_HITBOX(/*Radius*/ 40, /*Height*/ 40), SET_HOME(), BEGIN_LOOP(), CALL_NATIVE(bhv_small_penguin_loop), END_LOOP(), }; const BehaviorScript bhvManyBlueFishSpawner[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvManyBlueFishSpawner), SET_INT(oBehParams2ndByte, 0), GOTO(bhvFishSpawner + 1 + 1), }; const BehaviorScript bhvFewBlueFishSpawner[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvFewBlueFishSpawner), SET_INT(oBehParams2ndByte, 1), GOTO(bhvFishSpawner + 1 + 1), }; const BehaviorScript bhvFishSpawner[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvFishSpawner), // Fish Spawner - common: DISABLE_RENDERING(), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), BEGIN_LOOP(), CALL_NATIVE(bhv_fish_spawner_loop), END_LOOP(), }; const BehaviorScript bhvFish[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvFish), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), SET_HOME(), BEGIN_LOOP(), CALL_NATIVE(bhv_fish_loop), END_LOOP(), }; const BehaviorScript bhvWdwExpressElevator[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvWdwExpressElevator), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_COLLISION_DATA(wdw_seg7_collision_express_elevator_platform), SET_HOME(), BEGIN_LOOP(), CALL_NATIVE(bhv_wdw_express_elevator_loop), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvWdwExpressElevatorPlatform[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvWdwExpressElevatorPlatform), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_COLLISION_DATA(wdw_seg7_collision_express_elevator_platform), SET_HOME(), BEGIN_LOOP(), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvChirpChirp[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvChirpChirp), SET_INT(oBirdChirpChirpUnkF4, 1), GOTO(bhvChirpChirpUnused), }; const BehaviorScript bhvChirpChirpUnused[] = { DISABLE_RENDERING(), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), BEGIN_LOOP(), CALL_NATIVE(bhv_bub_spawner_loop), END_LOOP(), }; const BehaviorScript bhvBub[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvBub), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_ANIMATIONS(oAnimations, &bub_seg6_anims_06012354), ANIMATE(0), SET_HITBOX_WITH_OFFSET(/*Radius*/ 20, /*Height*/ 10, /*Downwards offset*/ 10), SET_INTERACT_TYPE(INTERACT_DAMAGE), SET_INT(oDamageOrCoinValue, 1), SET_HOME(), SET_INT(oIntangibleTimer, 0), BEGIN_LOOP(), CALL_NATIVE(bhv_bub_loop), END_LOOP(), }; const BehaviorScript bhvExclamationBox[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvExclamationBox), OR_INT(oFlags, (OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_COLLISION_DATA(exclamation_box_outline_seg8_collision_08025F78), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), SET_FLOAT(oCollisionDistance, 300), SET_HOME(), CALL_NATIVE(bhv_exclamation_box_init), BEGIN_LOOP(), CALL_NATIVE(bhv_exclamation_box_loop), END_LOOP(), }; const BehaviorScript bhvRotatingExclamationMark[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvRotatingExclamationMark), OR_INT(oFlags, (OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), SCALE(/*Unused*/ 0, /*Field*/ 200), BEGIN_LOOP(), CALL_NATIVE(bhv_rotating_exclamation_box_loop), ADD_INT(oMoveAngleYaw, 0x800), END_LOOP(), }; const BehaviorScript bhvSoundSpawner[] = { BEGIN(OBJ_LIST_UNIMPORTANT), ID(id_bhvSoundSpawner), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), DELAY(3), CALL_NATIVE(bhv_sound_spawner_init), DELAY(30), DEACTIVATE(), }; const BehaviorScript bhvRockSolid[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvRockSolid), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_COLLISION_DATA(jrb_seg7_collision_rock_solid), BEGIN_LOOP(), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvBowserSubDoor[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvBowserSubDoor), OR_INT(oFlags, (OBJ_FLAG_ACTIVE_FROM_AFAR | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_COLLISION_DATA(ddd_seg7_collision_bowser_sub_door), SET_FLOAT(oDrawingDistance, 20000), SET_FLOAT(oCollisionDistance, 20000), BEGIN_LOOP(), CALL_NATIVE(bhv_bowsers_sub_loop), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvBowsersSub[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvBowsersSub), OR_INT(oFlags, (OBJ_FLAG_ACTIVE_FROM_AFAR | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), SET_FLOAT(oDrawingDistance, 20000), SET_FLOAT(oCollisionDistance, 20000), LOAD_COLLISION_DATA(ddd_seg7_collision_submarine), BEGIN_LOOP(), CALL_NATIVE(bhv_bowsers_sub_loop), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvSushiShark[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvSushiShark), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_ANIMATIONS(oAnimations, &sushi_seg5_anims_0500AE54), SPAWN_OBJ(/*Model*/ MODEL_NONE, /*Behavior*/ bhvSushiSharkCollisionChild), SET_HITBOX_WITH_OFFSET(/*Radius*/ 100, /*Height*/ 50, /*Downwards offset*/ 50), SET_INTERACT_TYPE(INTERACT_DAMAGE), SET_INT(oDamageOrCoinValue, 3), SET_HOME(), ANIMATE(0), SET_INT(oIntangibleTimer, 0), BEGIN_LOOP(), CALL_NATIVE(bhv_sushi_shark_loop), END_LOOP(), }; const BehaviorScript bhvSushiSharkCollisionChild[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvSushiSharkCollisionChild), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), DISABLE_RENDERING(), BEGIN_LOOP(), CALL_NATIVE(bhv_sushi_shark_collision_loop), END_LOOP(), }; const BehaviorScript bhvJrbSlidingBox[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvJrbSlidingBox), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), LOAD_COLLISION_DATA(jrb_seg7_collision_floating_box), SET_HOME(), BEGIN_LOOP(), CALL_NATIVE(bhv_jrb_sliding_box_loop), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvShipPart3[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvShipPart3), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), SET_HOME(), BEGIN_LOOP(), CALL_NATIVE(bhv_ship_part_3_loop), END_LOOP(), }; const BehaviorScript bhvInSunkenShip3[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvInSunkenShip3), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), LOAD_COLLISION_DATA(jrb_seg7_collision_in_sunken_ship_3), SET_HOME(), SET_FLOAT(oCollisionDistance, 4000), BEGIN_LOOP(), CALL_NATIVE(bhv_ship_part_3_loop), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvSunkenShipPart[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvSunkenShipPart), OR_INT(oFlags, (OBJ_FLAG_ACTIVE_FROM_AFAR | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), SCALE(/*Unused*/ 0, /*Field*/ 50), SET_HOME(), BEGIN_LOOP(), CALL_NATIVE(bhv_sunken_ship_part_loop), END_LOOP(), }; const BehaviorScript bhvSunkenShipSetRotation[] = { SET_INT(oFaceAnglePitch, 0xE958), SET_INT(oFaceAngleYaw, 0xEE6C), SET_INT(oFaceAngleRoll, 0x0C80), RETURN(), }; const BehaviorScript bhvSunkenShipPart2[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvSunkenShipPart2), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), SCALE(/*Unused*/ 0, /*Field*/ 100), SET_FLOAT(oDrawingDistance, 6000), SET_HOME(), CALL(bhvSunkenShipSetRotation), BREAK(), }; const BehaviorScript bhvInSunkenShip[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvInSunkenShip), LOAD_COLLISION_DATA(jrb_seg7_collision_in_sunken_ship), GOTO(bhvInSunkenShip2 + 1 + 2 + 1), }; const BehaviorScript bhvInSunkenShip2[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvInSunkenShip2), LOAD_COLLISION_DATA(jrb_seg7_collision_in_sunken_ship_2), // Sunken ship - common: OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), SET_FLOAT(oCollisionDistance, 4000), CALL(bhvSunkenShipSetRotation), BEGIN_LOOP(), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvMistParticleSpawner[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvMistParticleSpawner), PARENT_BIT_CLEAR(oActiveParticleFlags, ACTIVE_PARTICLE_DUST), DISABLE_RENDERING(), SPAWN_CHILD(/*Model*/ MODEL_MIST, /*Behavior*/ bhvWhitePuff1), SPAWN_CHILD(/*Model*/ MODEL_SMOKE, /*Behavior*/ bhvWhitePuff2), DELAY(1), DEACTIVATE(), }; const BehaviorScript bhvWhitePuff1[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvWhitePuff1), PARENT_BIT_CLEAR(oActiveParticleFlags, ACTIVE_PARTICLE_DUST), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), BILLBOARD(), BEGIN_LOOP(), CALL_NATIVE(bhv_white_puff_1_loop), END_LOOP(), }; const BehaviorScript bhvWhitePuff2[] = { BEGIN(OBJ_LIST_UNIMPORTANT), ID(id_bhvWhitePuff2), OR_INT(oFlags, (OBJ_FLAG_MOVE_XZ_USING_FVEL | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), BILLBOARD(), SET_INT(oAnimState, -1), BEGIN_REPEAT(7), CALL_NATIVE(bhv_white_puff_2_loop), ADD_INT(oAnimState, 1), END_REPEAT(), DEACTIVATE(), }; const BehaviorScript bhvWhitePuffSmoke2[] = { BEGIN(OBJ_LIST_UNIMPORTANT), ID(id_bhvWhitePuffSmoke2), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), BILLBOARD(), SET_INT(oAnimState, -1), BEGIN_REPEAT(7), CALL_NATIVE(bhv_white_puff_2_loop), CALL_NATIVE(cur_obj_move_using_fvel_and_gravity), ADD_INT(oAnimState, 1), END_REPEAT(), DEACTIVATE(), }; const BehaviorScript bhvPurpleSwitchHiddenBoxes[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvPurpleSwitchHiddenBoxes), SET_INT(oBehParams2ndByte, 2), GOTO(bhvFloorSwitchHardcodedModel + 1 + 1), }; const BehaviorScript bhvBlueCoinNumber[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvBlueCoinNumber), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), BILLBOARD(), BEGIN_LOOP(), CALL_NATIVE(bhv_blue_coin_number_loop), END_LOOP(), }; const BehaviorScript bhvBlueCoinSwitch[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvBlueCoinSwitch), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), LOAD_COLLISION_DATA(blue_coin_switch_seg8_collision_08000E98), CALL_NATIVE(bhv_blue_coin_switch_init), BEGIN_LOOP(), CALL_NATIVE(bhv_blue_coin_switch_loop), END_LOOP(), }; const BehaviorScript bhvHiddenBlueCoin[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhvHiddenBlueCoin), SET_INT(oInteractType, INTERACT_COIN), OR_INT(oFlags, (OBJ_FLAG_ACTIVE_FROM_AFAR | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), BILLBOARD(), SET_HITBOX(/*Radius*/ 100, /*Height*/ 64), SET_INT(oDamageOrCoinValue, 5), SET_INT(oIntangibleTimer, 0), SET_INT(oAnimState, -1), BEGIN_LOOP(), CALL_NATIVE(bhv_hidden_blue_coin_loop), ADD_INT(oAnimState, 1), END_LOOP(), }; const BehaviorScript bhvOpenableCageDoor[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvOpenableCageDoor), OR_INT(oFlags, (OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), BEGIN_LOOP(), CALL_NATIVE(bhv_openable_cage_door_loop), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvOpenableGrill[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvOpenableGrill), OR_INT(oFlags, (OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), BEGIN_LOOP(), CALL_NATIVE(bhv_openable_grill_loop), END_LOOP(), }; const BehaviorScript bhvWaterLevelDiamond[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvWaterLevelDiamond), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), SET_HITBOX(/*Radius*/ 70, /*Height*/ 30), SET_FLOAT(oCollisionDistance, 200), SET_INT(oIntangibleTimer, 0), BEGIN_LOOP(), CALL_NATIVE(bhv_water_level_diamond_loop), END_LOOP(), }; const BehaviorScript bhvInitializeChangingWaterLevel[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvInitializeChangingWaterLevel), BEGIN_LOOP(), CALL_NATIVE(bhv_init_changing_water_level_loop), END_LOOP(), }; const BehaviorScript bhvTweesterSandParticle[] = { BEGIN(OBJ_LIST_UNIMPORTANT), ID(id_bhvTweesterSandParticle), OR_INT(oFlags, (OBJ_FLAG_MOVE_XZ_USING_FVEL | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), BILLBOARD(), BEGIN_LOOP(), CALL_NATIVE(bhv_tweester_sand_particle_loop), END_LOOP(), }; const BehaviorScript bhvTweester[] = { BEGIN(OBJ_LIST_POLELIKE), ID(id_bhvTweester), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_ACTIVE_FROM_AFAR | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 30, /*Gravity*/ -400, /*Bounciness*/ 0, /*Drag strength*/ 0, /*Friction*/ 0, /*Buoyancy*/ 200, /*Unused*/ 0, 0), DROP_TO_FLOOR(), SET_HOME(), BEGIN_LOOP(), CALL_NATIVE(bhv_tweester_loop), END_LOOP(), }; const BehaviorScript bhvMerryGoRoundBooManager[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvMerryGoRoundBooManager), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), BEGIN_LOOP(), CALL_NATIVE(bhv_merry_go_round_boo_manager_loop), END_LOOP(), }; const BehaviorScript bhvAnimatedTexture[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvAnimatedTexture), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 30, /*Gravity*/ -400, /*Bounciness*/ -70, /*Drag strength*/ 1000, /*Friction*/ 1000, /*Buoyancy*/ 200, /*Unused*/ 0, 0), BILLBOARD(), BEGIN_LOOP(), CALL_NATIVE(bhv_animated_texture_loop), ADD_INT(oAnimState, 1), ANIMATE_TEXTURE(oAnimState, 2), END_LOOP(), }; const BehaviorScript bhvBooInCastle[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvBooInCastle), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), SET_HOME(), SET_FLOAT(oGraphYOffset, 60), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 30, /*Gravity*/ 0, /*Bounciness*/ -50, /*Drag strength*/ 1000, /*Friction*/ 1000, /*Buoyancy*/ 200, /*Unused*/ 0, 0), CALL_NATIVE(bhv_init_room), BEGIN_LOOP(), CALL_NATIVE(bhv_boo_in_castle_loop), END_LOOP(), }; const BehaviorScript bhvBooWithCage[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvBooWithCage), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), SET_HOME(), SET_INT(oDamageOrCoinValue, 3), SET_HURTBOX(/*Radius*/ 80, /*Height*/ 120), SET_HITBOX(/*Radius*/ 180, /*Height*/ 140), SET_FLOAT(oGraphYOffset, 60), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 30, /*Gravity*/ 0, /*Bounciness*/ -50, /*Drag strength*/ 1000, /*Friction*/ 1000, /*Buoyancy*/ 200, /*Unused*/ 0, 0), CALL_NATIVE(bhv_boo_with_cage_init), CALL_NATIVE(bhv_init_room), BEGIN_LOOP(), CALL_NATIVE(bhv_boo_with_cage_loop), END_LOOP(), }; const BehaviorScript bhvBalconyBigBoo[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvBalconyBigBoo), SET_INT(oBehParams2ndByte, 2), SET_INT(oBigBooNumMinionBoosKilled, 10), GOTO(bhvGhostHuntBigBoo + 1 + 1), }; const BehaviorScript bhvMerryGoRoundBigBoo[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvMerryGoRoundBigBoo), SET_INT(oBehParams2ndByte, 1), // Set number of minion boos killed to 10, which is greater than 5 so that the boo always loads without needing to kill any boos. SET_INT(oBigBooNumMinionBoosKilled, 10), GOTO(bhvGhostHuntBigBoo + 1 + 1), }; const BehaviorScript bhvGhostHuntBigBoo[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvGhostHuntBigBoo), // Big boo - common: OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), SET_HOME(), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 30, /*Gravity*/ 0, /*Bounciness*/ -50, /*Drag strength*/ 1000, /*Friction*/ 1000, /*Buoyancy*/ 200, /*Unused*/ 0, 0), CALL_NATIVE(bhv_init_room), CALL_NATIVE(bhv_boo_init), BEGIN_LOOP(), CALL_NATIVE(bhv_big_boo_loop), END_LOOP(), }; const BehaviorScript bhvCourtyardBooTriplet[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvCourtyardBooTriplet), DISABLE_RENDERING(), CALL_NATIVE(bhv_courtyard_boo_triplet_init), DEACTIVATE(), }; const BehaviorScript bhvBoo[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvBoo), SET_INT(oBehParams2ndByte, 1), GOTO(bhvGhostHuntBoo + 1 + 1), }; const BehaviorScript bhvMerryGoRoundBoo[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvMerryGoRoundBoo), SET_INT(oBehParams2ndByte, 2), GOTO(bhvGhostHuntBoo + 1 + 1), }; const BehaviorScript bhvGhostHuntBoo[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvGhostHuntBoo), // Boo - common: OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), SET_INT(oIntangibleTimer, 0), SET_HOME(), SET_INT(oDamageOrCoinValue, 2), SET_HITBOX(/*Radius*/ 140, /*Height*/ 80), SET_HURTBOX(/*Radius*/ 40, /*Height*/ 60), SET_FLOAT(oGraphYOffset, 30), CALL_NATIVE(bhv_init_room), SPAWN_CHILD(/*Model*/ MODEL_YELLOW_COIN, /*Behavior*/ bhvCoinInsideBoo), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 30, /*Gravity*/ 0, /*Bounciness*/ -50, /*Drag strength*/ 1000, /*Friction*/ 1000, /*Buoyancy*/ 200, /*Unused*/ 0, 0), CALL_NATIVE(bhv_boo_init), BEGIN_LOOP(), CALL_NATIVE(bhv_boo_loop), END_LOOP(), }; const BehaviorScript bhvHiddenStaircaseStep[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvHiddenStaircaseStep), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), LOAD_COLLISION_DATA(bbh_seg7_collision_staircase_step), SET_INT(oRoom, 1), SET_FLOAT(oCollisionDistance, 1000), SET_HOME(), BEGIN_LOOP(), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvBooBossSpawnedBridge[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvBooBossSpawnedBridge), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), LOAD_COLLISION_DATA(bbh_seg7_collision_staircase_step), SET_INT(oRoom, 1), SET_FLOAT(oCollisionDistance, 1000), SET_HOME(), BEGIN_LOOP(), CALL_NATIVE(bhv_boo_boss_spawned_bridge_loop), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvBbhTiltingTrapPlatform[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvBbhTiltingTrapPlatform), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_COLLISION_DATA(bbh_seg7_collision_tilt_floor_platform), SET_HOME(), SET_INT(oRoom, 2), BEGIN_LOOP(), CALL_NATIVE(bhv_bbh_tilting_trap_platform_loop), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvHauntedBookshelf[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvHauntedBookshelf), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), LOAD_COLLISION_DATA(bbh_seg7_collision_haunted_bookshelf), SET_HOME(), SET_INT(oRoom, 6), BEGIN_LOOP(), CALL_NATIVE(bhv_haunted_bookshelf_loop), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvMeshElevator[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvMeshElevator), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), LOAD_COLLISION_DATA(bbh_seg7_collision_mesh_elevator), SET_HOME(), SET_INT(oRoom, 12), SET_INT(oBehParams2ndByte, 4), CALL_NATIVE(bhv_elevator_init), BEGIN_LOOP(), CALL_NATIVE(bhv_elevator_loop), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvMerryGoRound[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvMerryGoRound), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_COLLISION_DATA(bbh_seg7_collision_merry_go_round), SET_FLOAT(oCollisionDistance, 2000), SET_INT(oRoom, 10), BEGIN_LOOP(), CALL_NATIVE(bhv_merry_go_round_loop), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; #ifndef VERSION_JP const BehaviorScript bhvPlaysMusicTrackWhenTouched[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvPlaysMusicTrackWhenTouched), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), BEGIN_LOOP(), CALL_NATIVE(bhv_play_music_track_when_touched_loop), END_LOOP(), }; #endif const BehaviorScript bhvInsideCannon[] = { BREAK(), }; const BehaviorScript bhvBetaBowserAnchor[] = { BEGIN(OBJ_LIST_DESTRUCTIVE), ID(id_bhvBetaBowserAnchor), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), BILLBOARD(), SET_HOME(), SET_HITBOX(/*Radius*/ 100, /*Height*/ 300), SET_INT(oIntangibleTimer, 0), BEGIN_LOOP(), ADD_INT(oAnimState, 1), CALL_NATIVE(bhv_beta_bowser_anchor_loop), END_LOOP(), }; const BehaviorScript bhvStaticCheckeredPlatform[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvStaticCheckeredPlatform), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), LOAD_COLLISION_DATA(checkerboard_platform_seg8_collision_0800D710), SET_HOME(), BEGIN_LOOP(), CALL_NATIVE(bhv_static_checkered_platform_loop), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvUnused2A10[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvUnused2A10), BILLBOARD(), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), BREAK(), }; const BehaviorScript bhvUnusedFakeStar[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvUnusedFakeStar), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), BEGIN_LOOP(), ADD_INT(oFaceAnglePitch, 0x100), ADD_INT(oFaceAngleYaw, 0x100), END_LOOP(), }; // What is this? UNUSED static const BehaviorScript unused_1[] = { BREAK(), BREAK(), BREAK(), BREAK(), }; const BehaviorScript bhvStaticObject[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvStaticObject), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), BREAK(), }; const BehaviorScript bhvUnused2A54[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvUnused2A54), BREAK(), }; const BehaviorScript bhvCastleFloorTrap[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvCastleFloorTrap), DISABLE_RENDERING(), CALL_NATIVE(bhv_castle_floor_trap_init), BEGIN_LOOP(), CALL_NATIVE(bhv_castle_floor_trap_loop), END_LOOP(), }; const BehaviorScript bhvFloorTrapInCastle[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvFloorTrapInCastle), OR_INT(oFlags, (OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_COLLISION_DATA(inside_castle_seg7_collision_floor_trap), BEGIN_LOOP(), CALL_NATIVE(bhv_floor_trap_in_castle_loop), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvTree[] = { BEGIN(OBJ_LIST_POLELIKE), ID(id_bhvTree), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), SET_INT(oInteractType, INTERACT_POLE), SET_HITBOX(/*Radius*/ 80, /*Height*/ 500), SET_INT(oIntangibleTimer, 0), BEGIN_LOOP(), CALL_NATIVE(cur_obj_set_billboard_if_vanilla_cam), CALL_NATIVE(bhv_pole_base_loop), END_LOOP(), }; const BehaviorScript bhvSparkle[] = { BEGIN(OBJ_LIST_UNIMPORTANT), ID(id_bhvSparkle), BILLBOARD(), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), SET_INT(oAnimState, -1), BEGIN_REPEAT(9), ADD_INT(oAnimState, 1), END_REPEAT(), DEACTIVATE(), }; const BehaviorScript bhvSparkleSpawn[] = { BEGIN(OBJ_LIST_UNIMPORTANT), ID(id_bhvSparkleSpawn), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), BEGIN_LOOP(), CALL_NATIVE(bhv_sparkle_spawn_loop), END_LOOP(), }; const BehaviorScript bhvSparkleParticleSpawner[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvSparkleParticleSpawner), PARENT_BIT_CLEAR(oActiveParticleFlags, ACTIVE_PARTICLE_SPARKLES), BEGIN(OBJ_LIST_UNIMPORTANT), BILLBOARD(), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), SET_FLOAT(oGraphYOffset, 25), SET_RANDOM_FLOAT(oMarioParticleFlags, /*Minimum*/ -50, /*Range*/ 100), SUM_FLOAT(/*Dest*/ oPosX, /*Value 1*/ oPosX, /*Value 2*/ oMarioParticleFlags), SET_RANDOM_FLOAT(oMarioParticleFlags, /*Minimum*/ -50, /*Range*/ 100), SUM_FLOAT(/*Dest*/ oPosZ, /*Value 1*/ oPosZ, /*Value 2*/ oMarioParticleFlags), SET_RANDOM_FLOAT(oMarioParticleFlags, /*Minimum*/ -50, /*Range*/ 100), SUM_FLOAT(/*Dest*/ oPosY, /*Value 1*/ oPosY, /*Value 2*/ oMarioParticleFlags), SET_INT(oAnimState, -1), BEGIN_REPEAT(12), ADD_INT(oAnimState, 1), END_REPEAT(), DEACTIVATE(), }; const BehaviorScript bhvScuttlebug[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvScuttlebug), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_ANIMATIONS(oAnimations, &scuttlebug_seg6_anims_06015064), ANIMATE(0), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 80, /*Gravity*/ -400, /*Bounciness*/ -50, /*Drag strength*/ 0, /*Friction*/ 0, /*Buoyancy*/ 200, /*Unused*/ 0, 0), SET_HOME(), CALL_NATIVE(bhv_init_room), BEGIN_LOOP(), CALL_NATIVE(bhv_scuttlebug_loop), END_LOOP(), }; const BehaviorScript bhvScuttlebugSpawn[] = { BEGIN(OBJ_LIST_SPAWNER), ID(id_bhvScuttlebugSpawn), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), BEGIN_LOOP(), CALL_NATIVE(bhv_scuttlebug_spawn_loop), END_LOOP(), }; const BehaviorScript bhvWhompKingBoss[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvWhompKingBoss), SET_INT(oBehParams2ndByte, 1), SET_INT(oHealth, 3), GOTO(bhvSmallWhomp + 1 + 1 + 1), }; const BehaviorScript bhvSmallWhomp[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvSmallWhomp), SET_INT(oNumLootCoins, 5), // Whomp - common: OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_ANIMATIONS(oAnimations, &whomp_seg6_anims_06020A04), LOAD_COLLISION_DATA(whomp_seg6_collision_06020A0C), ANIMATE(0), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 0, /*Gravity*/ -400, /*Bounciness*/ -50, /*Drag strength*/ 0, /*Friction*/ 0, /*Buoyancy*/ 200, /*Unused*/ 0, 0), SET_HOME(), BEGIN_LOOP(), CALL_NATIVE(bhv_whomp_loop), END_LOOP(), }; // The large splash Mario makes when he jumps into a pool of water. const BehaviorScript bhvWaterSplash[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvWaterSplash), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), BILLBOARD(), SET_INT(oAnimState, -1), BEGIN_REPEAT(3), ADD_INT(oAnimState, 1), CALL_NATIVE(bhv_water_splash_spawn_droplets), DELAY(1), CALL_NATIVE(bhv_water_splash_spawn_droplets), END_REPEAT(), BEGIN_REPEAT(5), ADD_INT(oAnimState, 1), DELAY(1), END_REPEAT(), PARENT_BIT_CLEAR(oActiveParticleFlags, ACTIVE_PARTICLE_WATER_SPLASH), DEACTIVATE(), }; // Droplets of water that spawn as a result of various water splashes. const BehaviorScript bhvWaterDroplet[] = { BEGIN(OBJ_LIST_UNIMPORTANT), ID(id_bhvWaterDroplet), OR_INT(oFlags, (OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_MOVE_XZ_USING_FVEL | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), BILLBOARD(), BEGIN_LOOP(), CALL_NATIVE(bhv_water_droplet_loop), END_LOOP(), }; // Small splashes that are seen when a water droplet lands back into the water. const BehaviorScript bhvWaterDropletSplash[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvWaterDropletSplash), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), #ifndef VERSION_JP SET_INT(oFaceAnglePitch, 0), SET_INT(oFaceAngleYaw, 0), SET_INT(oFaceAngleRoll, 0), #endif CALL_NATIVE(bhv_water_droplet_splash_init), ADD_FLOAT(oPosY, 5), SET_INT(oAnimState, -1), BEGIN_REPEAT(6), ADD_INT(oAnimState, 1), END_REPEAT(), DEACTIVATE(), }; // The splash created when an air bubble hits the surface of the water. const BehaviorScript bhvBubbleSplash[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvBubbleSplash), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), #ifdef VERSION_JP SET_FLOAT(oFaceAnglePitch, 0), SET_FLOAT(oFaceAngleYaw, 0), SET_FLOAT(oFaceAngleRoll, 0), #endif #ifndef VERSION_JP SET_INT(oFaceAnglePitch, 0), SET_INT(oFaceAngleYaw, 0), SET_INT(oFaceAngleRoll, 0), #endif SET_INT(oAnimState, -1), CALL_NATIVE(bhv_bubble_splash_init), BEGIN_REPEAT(6), ADD_INT(oAnimState, 1), END_REPEAT(), DEACTIVATE(), }; // The water wave surrounding Mario when he is idle in a pool of water. const BehaviorScript bhvIdleWaterWave[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvIdleWaterWave), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), #ifdef VERSION_JP SET_FLOAT(oFaceAnglePitch, 0), SET_FLOAT(oFaceAngleYaw, 0), SET_FLOAT(oFaceAngleRoll, 0), #endif #ifndef VERSION_JP SET_INT(oFaceAnglePitch, 0), SET_INT(oFaceAngleYaw, 0), SET_INT(oFaceAngleRoll, 0), #endif SET_INT(oAnimState, -1), ADD_INT(oAnimState, 1), BEGIN_LOOP(), CALL_NATIVE(bhv_idle_water_wave_loop), ADD_INT(oAnimState, 1), BEGIN_REPEAT(6), CALL_NATIVE(bhv_idle_water_wave_loop), END_REPEAT(), CALL_NATIVE(bhv_idle_water_wave_loop), END_LOOP(), }; // Water splashes similar to the splashes created by water droplets, but are created by other objects. // Unlike water droplet splashes, they are unimportant objects. const BehaviorScript bhvObjectWaterSplash[] = { BEGIN(OBJ_LIST_UNIMPORTANT), ID(id_bhvObjectWaterSplash), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), #ifdef VERSION_JP SET_FLOAT(oFaceAnglePitch, 0), SET_FLOAT(oFaceAngleYaw, 0), SET_FLOAT(oFaceAngleRoll, 0), #endif #ifndef VERSION_JP SET_INT(oFaceAnglePitch, 0), SET_INT(oFaceAngleYaw, 0), SET_INT(oFaceAngleRoll, 0), #endif SET_INT(oAnimState, -1), BEGIN_REPEAT(6), ADD_INT(oAnimState, 1), END_REPEAT(), DEACTIVATE(), }; // Waves that are generated when running in shallow water. const BehaviorScript bhvShallowWaterWave[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvShallowWaterWave), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), DISABLE_RENDERING(), BEGIN_REPEAT(5), SPAWN_WATER_DROPLET(&gShallowWaterWaveDropletParams), END_REPEAT_CONTINUE(), DELAY(1), PARENT_BIT_CLEAR(oActiveParticleFlags, ACTIVE_PARTICLE_SHALLOW_WATER_WAVE), DEACTIVATE(), }; // A small water splash that occurs when jumping in and out of shallow water. // Unlike the larger water splash it has no visible model of its own. // It has a 1 in 256 chance of spawning the fish particle easter egg. const BehaviorScript bhvShallowWaterSplash[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvShallowWaterSplash), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), DISABLE_RENDERING(), BEGIN_REPEAT(18), SPAWN_WATER_DROPLET(&gShallowWaterSplashDropletParams), END_REPEAT_CONTINUE(), CALL_NATIVE(bhv_shallow_water_splash_init), DELAY(1), PARENT_BIT_CLEAR(oActiveParticleFlags, ACTIVE_PARTICLE_SHALLOW_WATER_SPLASH), DEACTIVATE(), }; // Waves created by other objects along the water's surface, specifically the koopa shell and Sushi. // Unlike Mario's waves, they are unimportant objects. const BehaviorScript bhvObjectWaveTrail[] = { BEGIN(OBJ_LIST_UNIMPORTANT), ID(id_bhvObjectWaveTrail), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), GOTO(bhvWaveTrail + 1 + 1 + 2 + 1), // Wave trail - common }; // The waves created by Mario while he is swimming. const BehaviorScript bhvWaveTrail[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvWaveTrail), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), PARENT_BIT_CLEAR(oActiveParticleFlags, ACTIVE_PARTICLE_WAVE_TRAIL), // Wave trail - common: SET_FLOAT(oFaceAnglePitch, 0), SET_FLOAT(oFaceAngleYaw, 0), SET_FLOAT(oFaceAngleRoll, 0), SET_INT(oAnimState, -1), BEGIN_REPEAT(8), ADD_INT(oAnimState, 1), CALL_NATIVE(bhv_wave_trail_shrink), DELAY(1), CALL_NATIVE(bhv_wave_trail_shrink), END_REPEAT(), DEACTIVATE(), }; // Tiny wind particles that provide aesthetics to the strong winds generated by the Snowman and Fwoosh. // As they are unimportant objects, they don't have collision with Mario. const BehaviorScript bhvTinyStrongWindParticle[] = { BEGIN(OBJ_LIST_UNIMPORTANT), ID(id_bhvTinyStrongWindParticle), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), BILLBOARD(), BEGIN_LOOP(), CALL_NATIVE(bhv_strong_wind_particle_loop), END_LOOP(), }; // Strong wind particles generated by the Snowman and Fwoosh that blow Mario back and knock his cap off. const BehaviorScript bhvStrongWindParticle[] = { BEGIN(OBJ_LIST_POLELIKE), ID(id_bhvStrongWindParticle), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), BILLBOARD(), BEGIN_LOOP(), CALL_NATIVE(bhv_strong_wind_particle_loop), END_LOOP(), }; // The handler for the strong wind blown by the Snowman in SL. Triggers dialog and then aims towards Mario. const BehaviorScript bhvSLSnowmanWind[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvSLSnowmanWind), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), SET_HOME(), BEGIN_LOOP(), CALL_NATIVE(bhv_sl_snowman_wind_loop), END_LOOP(), }; // The penguin that walks erratically along the ice bridge in front of the Snowman in SL. // Blocks strong wind particles, allowing Mario to walk behind it. const BehaviorScript bhvSLWalkingPenguin[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvSLWalkingPenguin), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_COLLISION_DATA(penguin_seg5_collision_05008B88), LOAD_ANIMATIONS(oAnimations, &penguin_seg5_anims_05008B74), ANIMATE(0), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 0, /*Gravity*/ -400, /*Bounciness*/ -50, /*Drag strength*/ 0, /*Friction*/ 0, /*Buoyancy*/ 200, /*Unused*/ 0, 0), SCALE(/*Unused*/ 0, /*Field*/ 600), SET_HOME(), BEGIN_LOOP(), CALL_NATIVE(bhv_sl_walking_penguin_loop), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvYellowBall[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvYellowBall), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), BILLBOARD(), BREAK(), }; UNUSED static const u64 behavior_data_unused_0 = 0; const BehaviorScript bhvMario[] = { BEGIN(OBJ_LIST_PLAYER), ID(id_bhvMario), SET_INT(oIntangibleTimer, 0), OR_INT(oFlags, OBJ_FLAG_0100), OR_INT(oUnk94, 0x0001), SET_HITBOX(/*Radius*/ 37, /*Height*/ 160), SET_INTERACT_TYPE(INTERACT_PLAYER), BEGIN_LOOP(), CALL_NATIVE(try_print_debug_mario_level_info), CALL_NATIVE(bhv_mario_update), CALL_NATIVE(try_do_mario_debug_object_spawn), END_LOOP(), }; const BehaviorScript bhvToadMessage[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvToadMessage), OR_INT(oFlags, (OBJ_FLAG_PERSISTENT_RESPAWN | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_ANIMATIONS(oAnimations, &toad_seg6_anims_0600FB58), ANIMATE(6), SET_INTERACT_TYPE(INTERACT_TEXT), SET_HITBOX(/*Radius*/ 80, /*Height*/ 100), SET_INT(oIntangibleTimer, 0), CALL_NATIVE(bhv_init_room), CALL_NATIVE(bhv_toad_message_init), BEGIN_LOOP(), CALL_NATIVE(bhv_toad_message_loop), END_LOOP(), }; const BehaviorScript bhvUnlockDoorStar[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhvUnlockDoorStar), OR_INT(oFlags, (OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), CALL_NATIVE(bhv_unlock_door_star_init), BEGIN_LOOP(), CALL_NATIVE(bhv_unlock_door_star_loop), END_LOOP(), }; const BehaviorScript bhvInstantActiveWarp[] = { BREAK(), }; const BehaviorScript bhvAirborneWarp[] = { BREAK(), }; const BehaviorScript bhvHardAirKnockBackWarp[] = { BREAK(), }; const BehaviorScript bhvSpinAirborneCircleWarp[] = { BREAK(), }; const BehaviorScript bhvDeathWarp[] = { BREAK(), }; const BehaviorScript bhvSpinAirborneWarp[] = { BREAK(), }; const BehaviorScript bhvFlyingWarp[] = { BREAK(), }; const BehaviorScript bhvPaintingStarCollectWarp[] = { BREAK(), }; const BehaviorScript bhvPaintingDeathWarp[] = { BREAK(), }; const BehaviorScript bhvAirborneDeathWarp[] = { BREAK(), }; const BehaviorScript bhvAirborneStarCollectWarp[] = { BREAK(), }; const BehaviorScript bhvLaunchStarCollectWarp[] = { BREAK(), }; const BehaviorScript bhvLaunchDeathWarp[] = { BREAK(), }; const BehaviorScript bhvSwimmingWarp[] = { BREAK(), }; UNUSED static const u64 behavior_data_unused_1 = 0; const BehaviorScript bhvRandomAnimatedTexture[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhvRandomAnimatedTexture), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), SET_FLOAT(oGraphYOffset, -16), BILLBOARD(), SET_INT(oAnimState, -1), BEGIN_LOOP(), ADD_INT(oAnimState, 1), END_LOOP(), }; const BehaviorScript bhvYellowBackgroundInMenu[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhvYellowBackgroundInMenu), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), CALL_NATIVE(beh_yellow_background_menu_init), BEGIN_LOOP(), SET_INT(oIntangibleTimer, 0), CALL_NATIVE(beh_yellow_background_menu_loop), END_LOOP(), }; const BehaviorScript bhvMenuButton[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhvMenuButton), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), CALL_NATIVE(bhv_menu_button_init), BEGIN_LOOP(), SET_INT(oIntangibleTimer, 0), CALL_NATIVE(bhv_menu_button_loop), END_LOOP(), }; const BehaviorScript bhvMenuButtonManager[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhvMenuButtonManager), OR_INT(oFlags, (OBJ_FLAG_SET_THROW_MATRIX_FROM_TRANSFORM | OBJ_FLAG_0020 | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), CALL_NATIVE(bhv_menu_button_manager_init), BEGIN_LOOP(), SET_INT(oIntangibleTimer, 0), CALL_NATIVE(bhv_menu_button_manager_loop), END_LOOP(), }; const BehaviorScript bhvActSelectorStarType[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvActSelectorStarType), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), SET_HOME(), BEGIN_LOOP(), CALL_NATIVE(bhv_act_selector_star_type_loop), END_LOOP(), }; const BehaviorScript bhvActSelector[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvActSelector), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), CALL_NATIVE(bhv_act_selector_init), BEGIN_LOOP(), CALL_NATIVE(bhv_act_selector_loop), END_LOOP(), }; const BehaviorScript bhvMovingYellowCoin[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhvMovingYellowCoin), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), BILLBOARD(), SET_HITBOX(/*Radius*/ 100, /*Height*/ 64), SET_INT(oInteractType, INTERACT_COIN), SET_INT(oIntangibleTimer, 0), SET_INT(oAnimState, -1), CALL_NATIVE(bhv_moving_yellow_coin_init), BEGIN_LOOP(), CALL_NATIVE(bhv_moving_yellow_coin_loop), ADD_INT(oAnimState, 1), END_LOOP(), }; const BehaviorScript bhvMovingBlueCoin[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhvMovingBlueCoin), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), BILLBOARD(), SET_INT(oIntangibleTimer, 0), SET_INT(oAnimState, -1), CALL_NATIVE(bhv_moving_blue_coin_init), BEGIN_LOOP(), CALL_NATIVE(bhv_moving_blue_coin_loop), ADD_INT(oAnimState, 1), END_LOOP(), }; const BehaviorScript bhvBlueCoinSliding[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvBlueCoinSliding), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), BILLBOARD(), SET_INT(oIntangibleTimer, 0), SET_INT(oAnimState, -1), CALL_NATIVE(bhv_blue_coin_sliding_jumping_init), BEGIN_LOOP(), CALL_NATIVE(bhv_blue_coin_sliding_loop), ADD_INT(oAnimState, 1), END_LOOP(), }; const BehaviorScript bhvBlueCoinJumping[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvBlueCoinJumping), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), BILLBOARD(), SET_INT(oIntangibleTimer, 0), SET_INT(oAnimState, -1), CALL_NATIVE(bhv_blue_coin_sliding_jumping_init), BEGIN_LOOP(), CALL_NATIVE(bhv_blue_coin_jumping_loop), ADD_INT(oAnimState, 1), END_LOOP(), }; const BehaviorScript bhvSeaweed[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhvSeaweed), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), LOAD_ANIMATIONS(oAnimations, &seaweed_seg6_anims_0600A4D4), ANIMATE(0), CALL_NATIVE(bhv_seaweed_init), BEGIN_LOOP(), END_LOOP(), }; const BehaviorScript bhvSeaweedBundle[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhvSeaweedBundle), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), DROP_TO_FLOOR(), CALL_NATIVE(bhv_seaweed_bundle_init), BEGIN_LOOP(), END_LOOP(), }; const BehaviorScript bhvBobomb[] = { BEGIN(OBJ_LIST_DESTRUCTIVE), ID(id_bhvBobomb), OR_INT(oFlags, (OBJ_FLAG_PERSISTENT_RESPAWN | OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_HOLDABLE | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_ANIMATIONS(oAnimations, &bobomb_seg8_anims_0802396C), DROP_TO_FLOOR(), ANIMATE(0), SET_INT(oIntangibleTimer, 0), SET_HOME(), CALL_NATIVE(bhv_bobomb_init), BEGIN_LOOP(), CALL_NATIVE(bhv_bobomb_loop), END_LOOP(), }; const BehaviorScript bhvBobombFuseSmoke[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvBobombFuseSmoke), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), BILLBOARD(), SET_INT(oAnimState, -1), CALL_NATIVE(bhv_bobomb_fuse_smoke_init), DELAY(1), BEGIN_LOOP(), CALL_NATIVE(bhv_dust_smoke_loop), ADD_INT(oAnimState, 1), END_LOOP(), }; const BehaviorScript bhvBobombBuddy[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvBobombBuddy), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_HOLDABLE | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_ANIMATIONS(oAnimations, &bobomb_seg8_anims_0802396C), SET_INTERACT_TYPE(INTERACT_TEXT), DROP_TO_FLOOR(), SET_HITBOX(/*Radius*/ 100, /*Height*/ 60), ANIMATE(0), SET_INT(oBobombBuddyRole, 0), SET_HOME(), CALL_NATIVE(bhv_bobomb_buddy_init), BEGIN_LOOP(), SET_INT(oIntangibleTimer, 0), CALL_NATIVE(bhv_bobomb_buddy_loop), END_LOOP(), }; // The only difference between this and the previous behavior are what oFlags and oBobombBuddyRole are set to, why didn't they just use a jump? const BehaviorScript bhvBobombBuddyOpensCannon[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvBobombBuddyOpensCannon), OR_INT(oFlags, (OBJ_FLAG_PERSISTENT_RESPAWN | OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_HOLDABLE | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_ANIMATIONS(oAnimations, &bobomb_seg8_anims_0802396C), SET_INTERACT_TYPE(INTERACT_TEXT), DROP_TO_FLOOR(), SET_HITBOX(/*Radius*/ 100, /*Height*/ 60), ANIMATE(0), SET_INT(oBobombBuddyRole, 1), SET_HOME(), CALL_NATIVE(bhv_bobomb_buddy_init), BEGIN_LOOP(), SET_INT(oIntangibleTimer, 0), CALL_NATIVE(bhv_bobomb_buddy_loop), END_LOOP(), }; const BehaviorScript bhvCannonClosed[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvCannonClosed), OR_INT(oFlags, (OBJ_FLAG_PERSISTENT_RESPAWN | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_COLLISION_DATA(cannon_lid_seg8_collision_08004950), SET_HOME(), CALL_NATIVE(bhv_cannon_closed_init), BEGIN_LOOP(), CALL_NATIVE(bhv_cannon_closed_loop), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvWhirlpool[] = { BEGIN(OBJ_LIST_POLELIKE), ID(id_bhvWhirlpool), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), CALL_NATIVE(bhv_whirlpool_init), BEGIN_LOOP(), CALL_NATIVE(bhv_whirlpool_loop), END_LOOP(), }; const BehaviorScript bhvJetStream[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvJetStream), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), BEGIN_LOOP(), CALL_NATIVE(bhv_jet_stream_loop), END_LOOP(), }; const BehaviorScript bhvMessagePanel[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvMessagePanel), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), LOAD_COLLISION_DATA(wooden_signpost_seg3_collision_0302DD80), SET_INTERACT_TYPE(INTERACT_TEXT), SET_INT(oInteractionSubtype, INT_SUBTYPE_SIGN), DROP_TO_FLOOR(), SET_HITBOX(/*Radius*/ 150, /*Height*/ 80), SET_INT(oWoodenPostTotalMarioAngle, 0), BEGIN_LOOP(), SET_INT(oIntangibleTimer, 0), CALL_NATIVE(load_object_collision_model), SET_INT(oInteractStatus, 0), END_LOOP(), }; const BehaviorScript bhvSignOnWall[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvSignOnWall), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), SET_INTERACT_TYPE(INTERACT_TEXT), SET_INT(oInteractionSubtype, INT_SUBTYPE_SIGN), SET_HITBOX(/*Radius*/ 150, /*Height*/ 80), SET_INT(oWoodenPostTotalMarioAngle, 0), BEGIN_LOOP(), SET_INT(oIntangibleTimer, 0), SET_INT(oInteractStatus, 0), END_LOOP(), }; const BehaviorScript bhvHomingAmp[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvHomingAmp), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_MOVE_XZ_USING_FVEL | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_ANIMATIONS(oAnimations, &amp_seg8_anims_08004034), ANIMATE(0), SET_FLOAT(oGraphYOffset, 40), SET_INT(oIntangibleTimer, 0), CALL_NATIVE(bhv_homing_amp_init), BEGIN_LOOP(), CALL_NATIVE(bhv_homing_amp_loop), END_LOOP(), }; const BehaviorScript bhvCirclingAmp[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvCirclingAmp), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_MOVE_XZ_USING_FVEL | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_ANIMATIONS(oAnimations, &amp_seg8_anims_08004034), ANIMATE(0), SET_FLOAT(oGraphYOffset, 40), SET_INT(oIntangibleTimer, 0), CALL_NATIVE(bhv_circling_amp_init), BEGIN_LOOP(), CALL_NATIVE(bhv_circling_amp_loop), END_LOOP(), }; const BehaviorScript bhvButterfly[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvButterfly), OR_INT(oFlags, (OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_ANIMATIONS(oAnimations, &butterfly_seg3_anims_030056B0), DROP_TO_FLOOR(), SET_FLOAT(oGraphYOffset, 5), CALL_NATIVE(bhv_butterfly_init), BEGIN_LOOP(), CALL_NATIVE(bhv_butterfly_loop), END_LOOP(), }; const BehaviorScript bhvHoot[] = { BEGIN(OBJ_LIST_POLELIKE), ID(id_bhvHoot), OR_INT(oFlags, (OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_ANIMATIONS(oAnimations, &hoot_seg5_anims_05005768), SET_INT(oInteractType, INTERACT_HOOT), SET_HITBOX(/*Radius*/ 75, /*Height*/ 75), CALL_NATIVE(bhv_hoot_init), BEGIN_LOOP(), CALL_NATIVE(bhv_hoot_loop), END_LOOP(), }; const BehaviorScript bhvBetaHoldableObject[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvBetaHoldableObject), OR_INT(oFlags, (OBJ_FLAG_HOLDABLE | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), SET_INT(oInteractType, INTERACT_GRABBABLE), DROP_TO_FLOOR(), SET_HITBOX(/*Radius*/ 40, /*Height*/ 50), CALL_NATIVE(bhv_beta_holdable_object_init), BEGIN_LOOP(), SET_INT(oIntangibleTimer, 0), CALL_NATIVE(bhv_beta_holdable_object_loop), END_LOOP(), }; const BehaviorScript bhvCarrySomething1[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvCarrySomething1), BREAK(), }; const BehaviorScript bhvCarrySomething2[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvCarrySomething2), BREAK(), }; const BehaviorScript bhvCarrySomething3[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvCarrySomething3), BREAK(), }; const BehaviorScript bhvCarrySomething4[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvCarrySomething4), BREAK(), }; const BehaviorScript bhvCarrySomething5[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvCarrySomething5), BREAK(), }; const BehaviorScript bhvCarrySomething6[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvCarrySomething6), BREAK(), }; const BehaviorScript bhvObjectBubble[] = { BEGIN(OBJ_LIST_UNIMPORTANT), ID(id_bhvObjectBubble), OR_INT(oFlags, (OBJ_FLAG_MOVE_Y_WITH_TERMINAL_VEL | OBJ_FLAG_MOVE_XZ_USING_FVEL | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), BILLBOARD(), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), SET_INT(oAnimState, -1), CALL_NATIVE(bhv_object_bubble_init), SET_RANDOM_FLOAT(oVelY, /*Minimum*/ 3, /*Range*/ 6), SET_INT_RAND_RSHIFT(oMoveAngleYaw, /*Minimum*/ 0, /*Right shift*/ 0), DELAY(1), BEGIN_LOOP(), CALL_NATIVE(bhv_object_bubble_loop), END_LOOP(), }; const BehaviorScript bhvObjectWaterWave[] = { BEGIN(OBJ_LIST_UNIMPORTANT), ID(id_bhvObjectWaterWave), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), SET_FLOAT(oFaceAnglePitch, 0), SET_FLOAT(oFaceAngleYaw, 0), SET_FLOAT(oFaceAngleRoll, 0), SET_INT(oAnimState, -1), CALL_NATIVE(bhv_object_water_wave_init), ADD_INT(oAnimState, 1), DELAY(6), BEGIN_LOOP(), CALL_NATIVE(bhv_object_water_wave_loop), ADD_INT(oAnimState, 1), BEGIN_REPEAT(6), CALL_NATIVE(bhv_object_water_wave_loop), END_REPEAT(), END_LOOP(), }; const BehaviorScript bhvExplosion[] = { BEGIN(OBJ_LIST_DESTRUCTIVE), ID(id_bhvExplosion), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), BILLBOARD(), SET_INTERACT_TYPE(INTERACT_DAMAGE), SET_INT(oDamageOrCoinValue, 2), SET_INT(oIntangibleTimer, 0), SET_HITBOX_WITH_OFFSET(/*Radius*/ 150, /*Height*/ 150, /*Downwards offset*/ 150), SET_INT(oAnimState, -1), CALL_NATIVE(bhv_explosion_init), BEGIN_LOOP(), CALL_NATIVE(bhv_explosion_loop), ADD_INT(oAnimState, 1), END_LOOP(), }; const BehaviorScript bhvBobombBullyDeathSmoke[] = { BEGIN(OBJ_LIST_UNIMPORTANT), ID(id_bhvBobombBullyDeathSmoke), OR_INT(oFlags, (OBJ_FLAG_MOVE_Y_WITH_TERMINAL_VEL | OBJ_FLAG_MOVE_XZ_USING_FVEL | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), BILLBOARD(), SET_INT(oAnimState, -1), CALL_NATIVE(bhv_bobomb_bully_death_smoke_init), DELAY(1), BEGIN_LOOP(), CALL_NATIVE(bhv_dust_smoke_loop), ADD_INT(oAnimState, 1), END_LOOP(), }; const BehaviorScript bhvSmoke[] = { BEGIN(OBJ_LIST_UNIMPORTANT), ID(id_bhvSmoke), OR_INT(oFlags, (OBJ_FLAG_MOVE_Y_WITH_TERMINAL_VEL | OBJ_FLAG_MOVE_XZ_USING_FVEL | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), BILLBOARD(), SET_INT(oAnimState, -1), DELAY(1), BEGIN_LOOP(), CALL_NATIVE(bhv_dust_smoke_loop), ADD_INT(oAnimState, 1), END_LOOP(), }; const BehaviorScript bhvBobombExplosionBubble[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvBobombExplosionBubble), BILLBOARD(), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), CALL_NATIVE(bhv_bobomb_explosion_bubble_init), ADD_RANDOM_FLOAT(oPosX, /*Minimum*/ -50, /*Range*/ 100), ADD_RANDOM_FLOAT(oPosY, /*Minimum*/ -50, /*Range*/ 100), ADD_RANDOM_FLOAT(oPosZ, /*Minimum*/ -50, /*Range*/ 100), CALL(bhvBobombExplosionBubble3600), DELAY(1), BEGIN_LOOP(), CALL(bhvBobombExplosionBubble3600), CALL_NATIVE(bhv_bobomb_explosion_bubble_loop), END_LOOP(), }; const BehaviorScript bhvBobombExplosionBubble3600[] = { ADD_RANDOM_FLOAT(oPosX, /*Minimum*/ -2, /*Range*/ 4), ADD_RANDOM_FLOAT(oPosZ, /*Minimum*/ -2, /*Range*/ 4), RETURN(), }; const BehaviorScript bhvRespawner[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvRespawner), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), BEGIN_LOOP(), CALL_NATIVE(bhv_respawner_loop), END_LOOP(), }; const BehaviorScript bhvSmallBully[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvSmallBully), OR_INT(oFlags, (OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_ANIMATIONS(oAnimations, &bully_seg5_anims_0500470C), DROP_TO_FLOOR(), SET_HOME(), CALL_NATIVE(bhv_small_bully_init), BEGIN_LOOP(), SET_INT(oIntangibleTimer, 0), CALL_NATIVE(bhv_bully_loop), END_LOOP(), }; const BehaviorScript bhvBigBully[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvBigBully), OR_INT(oFlags, (OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_ANIMATIONS(oAnimations, &bully_seg5_anims_0500470C), DROP_TO_FLOOR(), SET_HOME(), CALL_NATIVE(bhv_big_bully_init), BEGIN_LOOP(), SET_INT(oIntangibleTimer, 0), CALL_NATIVE(bhv_bully_loop), END_LOOP(), }; const BehaviorScript bhvBigBullyWithMinions[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvBigBullyWithMinions), OR_INT(oFlags, (OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_ANIMATIONS(oAnimations, &bully_seg5_anims_0500470C), SET_HOME(), CALL_NATIVE(bhv_big_bully_init), CALL_NATIVE(bhv_big_bully_with_minions_init), BEGIN_LOOP(), CALL_NATIVE(bhv_big_bully_with_minions_loop), END_LOOP(), }; const BehaviorScript bhvSmallChillBully[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvSmallChillBully), OR_INT(oFlags, (OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_ANIMATIONS(oAnimations, &chilly_chief_seg6_anims_06003994), DROP_TO_FLOOR(), SET_HOME(), SET_INT(oBullySubtype, 0x0010), CALL_NATIVE(bhv_small_bully_init), BEGIN_LOOP(), SET_INT(oIntangibleTimer, 0), CALL_NATIVE(bhv_bully_loop), END_LOOP(), }; const BehaviorScript bhvBigChillBully[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvBigChillBully), OR_INT(oFlags, (OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_ANIMATIONS(oAnimations, &chilly_chief_seg6_anims_06003994), DROP_TO_FLOOR(), SET_HOME(), SET_INT(oBullySubtype, 0x0010), CALL_NATIVE(bhv_big_bully_init), BEGIN_LOOP(), SET_INT(oIntangibleTimer, 0), CALL_NATIVE(bhv_bully_loop), END_LOOP(), }; const BehaviorScript bhvJetStreamRingSpawner[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvJetStreamRingSpawner), HIDE(), BEGIN_LOOP(), CALL_NATIVE(bhv_jet_stream_ring_spawner_loop), END_LOOP(), }; const BehaviorScript bhvJetStreamWaterRing[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhvJetStreamWaterRing), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), LOAD_ANIMATIONS(oAnimations, &water_ring_seg6_anims_06013F7C), SET_HITBOX_WITH_OFFSET(/*Radius*/ 75, /*Height*/ 20, /*Downwards offset*/ 20), SET_INTERACT_TYPE(INTERACT_WATER_RING), SET_INT(oDamageOrCoinValue, 2), SET_INT(oIntangibleTimer, 0), CALL_NATIVE(bhv_jet_stream_water_ring_init), BEGIN_LOOP(), SET_INT(oIntangibleTimer, 0), CALL_NATIVE(bhv_jet_stream_water_ring_loop), END_LOOP(), }; const BehaviorScript bhvMantaRayWaterRing[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhvMantaRayWaterRing), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), LOAD_ANIMATIONS(oAnimations, &water_ring_seg6_anims_06013F7C), SET_HITBOX_WITH_OFFSET(/*Radius*/ 75, /*Height*/ 20, /*Downwards offset*/ 20), SET_INTERACT_TYPE(INTERACT_WATER_RING), SET_INT(oDamageOrCoinValue, 2), SET_INT(oIntangibleTimer, 0), CALL_NATIVE(bhv_manta_ray_water_ring_init), BEGIN_LOOP(), SET_INT(oIntangibleTimer, 0), CALL_NATIVE(bhv_manta_ray_water_ring_loop), END_LOOP(), }; const BehaviorScript bhvMantaRayRingManager[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvMantaRayRingManager), BEGIN_LOOP(), END_LOOP(), }; const BehaviorScript bhvBowserBomb[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvBowserBomb), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), SET_INT(oIntangibleTimer, 0), SET_HITBOX_WITH_OFFSET(/*Radius*/ 40, /*Height*/ 40, /*Downwards offset*/ 40), DELAY(1), BEGIN_LOOP(), SET_INT(oIntangibleTimer, 0), CALL_NATIVE(bhv_bowser_bomb_loop), END_LOOP(), }; const BehaviorScript bhvBowserBombExplosion[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvBowserBombExplosion), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), BILLBOARD(), SET_FLOAT(oGraphYOffset, -288), SET_INT(oAnimState, -1), BEGIN_LOOP(), CALL_NATIVE(bhv_bowser_bomb_explosion_loop), END_LOOP(), }; const BehaviorScript bhvBowserBombSmoke[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvBowserBombSmoke), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), BILLBOARD(), SET_FLOAT(oGraphYOffset, -288), SET_INT(oOpacity, 255), SET_INT(oAnimState, -1), BEGIN_LOOP(), CALL_NATIVE(bhv_bowser_bomb_smoke_loop), END_LOOP(), }; const BehaviorScript bhvCelebrationStar[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhvCelebrationStar), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), CALL_NATIVE(bhv_celebration_star_init), BEGIN_LOOP(), CALL_NATIVE(bhv_celebration_star_loop), END_LOOP(), }; const BehaviorScript bhvCelebrationStarSparkle[] = { BEGIN(OBJ_LIST_UNIMPORTANT), ID(id_bhvCelebrationStarSparkle), BILLBOARD(), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), SET_FLOAT(oGraphYOffset, 25), SET_INT(oAnimState, -1), BEGIN_LOOP(), ADD_INT(oAnimState, 1), CALL_NATIVE(bhv_celebration_star_sparkle_loop), END_LOOP(), }; const BehaviorScript bhvStarKeyCollectionPuffSpawner[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvStarKeyCollectionPuffSpawner), BILLBOARD(), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), SET_INT(oAnimState, -1), BEGIN_LOOP(), CALL_NATIVE(bhv_star_key_collection_puff_spawner_loop), END_LOOP(), }; const BehaviorScript bhvLllDrawbridgeSpawner[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvLllDrawbridgeSpawner), HIDE(), CALL_NATIVE(bhv_lll_drawbridge_spawner_init), BEGIN_LOOP(), CALL_NATIVE(bhv_lll_drawbridge_spawner_loop), END_LOOP(), }; const BehaviorScript bhvLllDrawbridge[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvLllDrawbridge), OR_INT(oFlags, (OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_COLLISION_DATA(lll_seg7_collision_drawbridge), BEGIN_LOOP(), CALL_NATIVE(bhv_lll_drawbridge_loop), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvSmallBomp[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvSmallBomp), OR_INT(oFlags, (OBJ_FLAG_MOVE_XZ_USING_FVEL | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_COLLISION_DATA(wf_seg7_collision_small_bomp), CALL_NATIVE(bhv_small_bomp_init), BEGIN_LOOP(), CALL_NATIVE(bhv_small_bomp_loop), END_LOOP(), }; const BehaviorScript bhvLargeBomp[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvLargeBomp), OR_INT(oFlags, (OBJ_FLAG_MOVE_XZ_USING_FVEL | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_COLLISION_DATA(wf_seg7_collision_large_bomp), CALL_NATIVE(bhv_large_bomp_init), BEGIN_LOOP(), CALL_NATIVE(bhv_large_bomp_loop), END_LOOP(), }; const BehaviorScript bhvWfSlidingPlatform[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvWfSlidingPlatform), OR_INT(oFlags, (OBJ_FLAG_MOVE_XZ_USING_FVEL | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_COLLISION_DATA(wf_seg7_collision_sliding_brick_platform), CALL_NATIVE(bhv_wf_sliding_platform_init), BEGIN_LOOP(), CALL_NATIVE(bhv_wf_sliding_platform_loop), END_LOOP(), }; const BehaviorScript bhvMoneybag[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvMoneybag), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_ANIMATIONS(oAnimations, &moneybag_seg6_anims_06005E5C), DROP_TO_FLOOR(), SET_HOME(), SET_INT(oIntangibleTimer, -1), CALL_NATIVE(bhv_moneybag_init), BEGIN_LOOP(), CALL_NATIVE(bhv_moneybag_loop), END_LOOP(), }; const BehaviorScript bhvMoneybagHidden[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhvMoneybagHidden), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), SET_FLOAT(oGraphYOffset, 27), BILLBOARD(), SET_HITBOX(/*Radius*/ 110, /*Height*/ 100), SET_INT(oIntangibleTimer, 0), SET_INT(oAnimState, -1), BEGIN_LOOP(), ADD_INT(oAnimState, 1), CALL_NATIVE(bhv_moneybag_hidden_loop), END_LOOP(), }; const BehaviorScript bhvPitBowlingBall[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvPitBowlingBall), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), BILLBOARD(), SET_FLOAT(oGraphYOffset, 130), CALL_NATIVE(bhv_bob_pit_bowling_ball_init), BEGIN_LOOP(), CALL_NATIVE(bhv_bob_pit_bowling_ball_loop), END_LOOP(), }; const BehaviorScript bhvFreeBowlingBall[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvFreeBowlingBall), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), BILLBOARD(), SET_FLOAT(oGraphYOffset, 130), CALL_NATIVE(bhv_free_bowling_ball_init), BEGIN_LOOP(), CALL_NATIVE(bhv_free_bowling_ball_loop), END_LOOP(), }; const BehaviorScript bhvBowlingBall[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvBowlingBall), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), BILLBOARD(), SET_FLOAT(oGraphYOffset, 130), CALL_NATIVE(bhv_bowling_ball_init), BEGIN_LOOP(), CALL_NATIVE(bhv_bowling_ball_loop), END_LOOP(), }; const BehaviorScript bhvTtmBowlingBallSpawner[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvTtmBowlingBallSpawner), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), SET_INT(oBBallSpawnerPeriodMinus1, 63), CALL_NATIVE(bhv_generic_bowling_ball_spawner_init), BEGIN_LOOP(), CALL_NATIVE(bhv_generic_bowling_ball_spawner_loop), END_LOOP(), }; const BehaviorScript bhvBobBowlingBallSpawner[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvBobBowlingBallSpawner), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), SET_INT(oBBallSpawnerPeriodMinus1, 127), CALL_NATIVE(bhv_generic_bowling_ball_spawner_init), BEGIN_LOOP(), CALL_NATIVE(bhv_generic_bowling_ball_spawner_loop), END_LOOP(), }; const BehaviorScript bhvThiBowlingBallSpawner[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvThiBowlingBallSpawner), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), BEGIN_LOOP(), CALL_NATIVE(bhv_thi_bowling_ball_spawner_loop), END_LOOP(), }; const BehaviorScript bhvRrCruiserWing[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvRrCruiserWing), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), CALL_NATIVE(bhv_rr_cruiser_wing_init), BEGIN_LOOP(), CALL_NATIVE(bhv_rr_cruiser_wing_loop), END_LOOP(), }; const BehaviorScript bhvSpindel[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvSpindel), OR_INT(oFlags, (OBJ_FLAG_SET_FACE_ANGLE_TO_MOVE_ANGLE | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_COLLISION_DATA(ssl_seg7_collision_spindel), CALL_NATIVE(bhv_spindel_init), BEGIN_LOOP(), CALL_NATIVE(bhv_spindel_loop), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvSslMovingPyramidWall[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvSslMovingPyramidWall), OR_INT(oFlags, (OBJ_FLAG_SET_FACE_ANGLE_TO_MOVE_ANGLE | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_COLLISION_DATA(ssl_seg7_collision_0702808C), CALL_NATIVE(bhv_ssl_moving_pyramid_wall_init), BEGIN_LOOP(), CALL_NATIVE(bhv_ssl_moving_pyramid_wall_loop), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvPyramidElevator[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvPyramidElevator), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), LOAD_COLLISION_DATA(ssl_seg7_collision_pyramid_elevator), SET_HOME(), SET_FLOAT(oCollisionDistance, 20000), CALL_NATIVE(bhv_pyramid_elevator_init), BEGIN_LOOP(), CALL_NATIVE(bhv_pyramid_elevator_loop), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvPyramidElevatorTrajectoryMarkerBall[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvPyramidElevatorTrajectoryMarkerBall), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), BILLBOARD(), BEGIN_LOOP(), CALL_NATIVE(bhv_pyramid_elevator_trajectory_marker_ball_loop), END_LOOP(), }; const BehaviorScript bhvPyramidTop[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvPyramidTop), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), LOAD_COLLISION_DATA(ssl_seg7_collision_pyramid_top), SET_HOME(), SET_FLOAT(oCollisionDistance, 20000), CALL_NATIVE(bhv_pyramid_top_init), BEGIN_LOOP(), CALL_NATIVE(bhv_pyramid_top_loop), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvPyramidTopFragment[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvPyramidTopFragment), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), CALL_NATIVE(bhv_pyramid_top_fragment_init), BEGIN_LOOP(), CALL_NATIVE(bhv_pyramid_top_fragment_loop), END_LOOP(), }; const BehaviorScript bhvPyramidPillarTouchDetector[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhvPyramidPillarTouchDetector), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), SET_HITBOX(/*Radius*/ 50, /*Height*/ 50), SET_INT(oIntangibleTimer, 0), BEGIN_LOOP(), CALL_NATIVE(bhv_pyramid_pillar_touch_detector_loop), END_LOOP(), }; const BehaviorScript bhvWaterfallSoundLoop[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvWaterfallSoundLoop), BEGIN_LOOP(), CALL_NATIVE(bhv_waterfall_sound_loop), END_LOOP(), }; const BehaviorScript bhvVolcanoSoundLoop[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvVolcanoSoundLoop), BEGIN_LOOP(), CALL_NATIVE(bhv_volcano_sound_loop), END_LOOP(), }; const BehaviorScript bhvCastleFlagWaving[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvCastleFlagWaving), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), LOAD_ANIMATIONS(oAnimations, &castle_grounds_seg7_anims_flags), ANIMATE(0), CALL_NATIVE(bhv_castle_flag_init), BEGIN_LOOP(), END_LOOP(), }; const BehaviorScript bhvBirdsSoundLoop[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvBirdsSoundLoop), BEGIN_LOOP(), CALL_NATIVE(bhv_birds_sound_loop), END_LOOP(), }; const BehaviorScript bhvAmbientSounds[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvAmbientSounds), CALL_NATIVE(bhv_ambient_sounds_init), BEGIN_LOOP(), END_LOOP(), }; const BehaviorScript bhvSandSoundLoop[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvSandSoundLoop), BEGIN_LOOP(), CALL_NATIVE(bhv_sand_sound_loop), END_LOOP(), }; const BehaviorScript bhvHiddenAt120Stars[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvHiddenAt120Stars), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), LOAD_COLLISION_DATA(castle_grounds_seg7_collision_cannon_grill), SET_FLOAT(oCollisionDistance, 4000), CALL_NATIVE(bhv_castle_cannon_grate_init), BEGIN_LOOP(), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvSnowmansBottom[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvSnowmansBottom), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), DROP_TO_FLOOR(), SET_INT(oIntangibleTimer, 0), CALL_NATIVE(bhv_snowmans_bottom_init), BEGIN_LOOP(), CALL_NATIVE(bhv_snowmans_bottom_loop), END_LOOP(), }; const BehaviorScript bhvSnowmansHead[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvSnowmansHead), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), DROP_TO_FLOOR(), SET_FLOAT(oGraphYOffset, 110), CALL_NATIVE(bhv_snowmans_head_init), BEGIN_LOOP(), CALL_NATIVE(bhv_snowmans_head_loop), END_LOOP(), }; const BehaviorScript bhvSnowmansBodyCheckpoint[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvSnowmansBodyCheckpoint), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), BEGIN_LOOP(), CALL_NATIVE(bhv_snowmans_body_checkpoint_loop), END_LOOP(), }; const BehaviorScript bhvBigSnowmanWhole[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvBigSnowmanWhole), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), SET_FLOAT(oGraphYOffset, 180), SET_INTERACT_TYPE(INTERACT_TEXT), SET_HITBOX(/*Radius*/ 210, /*Height*/ 550), BEGIN_LOOP(), SET_INT(oIntangibleTimer, 0), END_LOOP(), }; const BehaviorScript bhvBigBoulder[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvBigBoulder), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), SET_FLOAT(oGraphYOffset, 180), CALL_NATIVE(bhv_big_boulder_init), SET_FLOAT(oCollisionDistance, 20000), BEGIN_LOOP(), SET_INT(oIntangibleTimer, 0), CALL_NATIVE(bhv_big_boulder_loop), END_LOOP(), }; const BehaviorScript bhvBigBoulderGenerator[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvBigBoulderGenerator), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), BEGIN_LOOP(), CALL_NATIVE(bhv_big_boulder_generator_loop), END_LOOP(), }; const BehaviorScript bhvWingCap[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhvWingCap), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), CALL_NATIVE(bhv_wing_cap_init), BEGIN_LOOP(), CALL_NATIVE(bhv_wing_vanish_cap_loop), END_LOOP(), }; const BehaviorScript bhvMetalCap[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhvMetalCap), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), CALL_NATIVE(bhv_metal_cap_init), BEGIN_LOOP(), CALL_NATIVE(bhv_metal_cap_loop), END_LOOP(), }; const BehaviorScript bhvNormalCap[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhvNormalCap), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), CALL_NATIVE(bhv_normal_cap_init), BEGIN_LOOP(), SET_INT(oIntangibleTimer, 0), CALL_NATIVE(bhv_normal_cap_loop), END_LOOP(), }; const BehaviorScript bhvVanishCap[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhvVanishCap), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), CALL_NATIVE(bhv_vanish_cap_init), BEGIN_LOOP(), CALL_NATIVE(bhv_wing_vanish_cap_loop), END_LOOP(), }; const BehaviorScript bhvStarNumber[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvStarNumber), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), BILLBOARD(), BEGIN_LOOP(), CALL_NATIVE(bhv_star_number_loop), END_LOOP(), }; const BehaviorScript bhvStar[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhvStar), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), CALL_NATIVE(bhv_init_room), CALL_NATIVE(bhv_collect_star_init), BEGIN_LOOP(), CALL_NATIVE(bhv_collect_star_loop), END_LOOP(), }; const BehaviorScript bhvStarSpawnCoordinates[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhvStarSpawnCoordinates), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), CALL_NATIVE(bhv_collect_star_init), CALL_NATIVE(bhv_star_spawn_init), BEGIN_LOOP(), CALL_NATIVE(bhv_star_spawn_loop), END_LOOP(), }; const BehaviorScript bhvHiddenRedCoinStar[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhvHiddenRedCoinStar), OR_INT(oFlags, (OBJ_FLAG_PERSISTENT_RESPAWN | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), CALL_NATIVE(bhv_hidden_red_coin_star_init), BEGIN_LOOP(), CALL_NATIVE(bhv_hidden_red_coin_star_loop), END_LOOP(), }; const BehaviorScript bhvRedCoin[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhvRedCoin), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), BILLBOARD(), SET_INT(oIntangibleTimer, 0), SET_INT(oAnimState, -1), CALL_NATIVE(bhv_init_room), CALL_NATIVE(bhv_red_coin_init), BEGIN_LOOP(), CALL_NATIVE(bhv_red_coin_loop), ADD_INT(oAnimState, 1), END_LOOP(), }; const BehaviorScript bhvBowserCourseRedCoinStar[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhvBowserCourseRedCoinStar), OR_INT(oFlags, (OBJ_FLAG_PERSISTENT_RESPAWN | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), BEGIN_LOOP(), CALL_NATIVE(bhv_bowser_course_red_coin_star_loop), END_LOOP(), }; const BehaviorScript bhvHiddenStar[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhvHiddenStar), OR_INT(oFlags, (OBJ_FLAG_PERSISTENT_RESPAWN | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), CALL_NATIVE(bhv_hidden_star_init), BEGIN_LOOP(), CALL_NATIVE(bhv_hidden_star_loop), END_LOOP(), }; const BehaviorScript bhvHiddenStarTrigger[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhvHiddenStarTrigger), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), SET_HITBOX(/*Radius*/ 100, /*Height*/ 100), SET_INT(oIntangibleTimer, 0), BEGIN_LOOP(), CALL_NATIVE(bhv_hidden_star_trigger_loop), END_LOOP(), }; const BehaviorScript bhvTtmRollingLog[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvTtmRollingLog), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), LOAD_COLLISION_DATA(ttm_seg7_collision_pitoune_2), SET_HOME(), SET_FLOAT(oCollisionDistance, 2000), CALL_NATIVE(bhv_ttm_rolling_log_init), BEGIN_LOOP(), CALL_NATIVE(bhv_rolling_log_loop), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvLllVolcanoFallingTrap[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvLllVolcanoFallingTrap), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), LOAD_COLLISION_DATA(lll_seg7_collision_falling_wall), SET_HOME(), BEGIN_LOOP(), CALL_NATIVE(bhv_volcano_trap_loop), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvLllRollingLog[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvLllRollingLog), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), LOAD_COLLISION_DATA(lll_seg7_collision_pitoune), SET_HOME(), SET_FLOAT(oCollisionDistance, 2000), CALL_NATIVE(bhv_lll_rolling_log_init), BEGIN_LOOP(), CALL_NATIVE(bhv_rolling_log_loop), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhv1upWalking[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhv1upWalking), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), BILLBOARD(), SET_HITBOX_WITH_OFFSET(/*Radius*/ 30, /*Height*/ 30, /*Downwards offset*/ 0), SET_FLOAT(oGraphYOffset, 30), CALL_NATIVE(bhv_1up_common_init), BEGIN_LOOP(), CALL_NATIVE(bhv_1up_walking_loop), END_LOOP(), }; const BehaviorScript bhv1upRunningAway[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhv1upRunningAway), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), BILLBOARD(), SET_HITBOX_WITH_OFFSET(/*Radius*/ 30, /*Height*/ 30, /*Downwards offset*/ 0), SET_FLOAT(oGraphYOffset, 30), CALL_NATIVE(bhv_1up_common_init), BEGIN_LOOP(), CALL_NATIVE(bhv_1up_running_away_loop), END_LOOP(), }; const BehaviorScript bhv1upSliding[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhv1upSliding), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), BILLBOARD(), SET_HITBOX_WITH_OFFSET(/*Radius*/ 30, /*Height*/ 30, /*Downwards offset*/ 0), SET_FLOAT(oGraphYOffset, 30), CALL_NATIVE(bhv_1up_common_init), BEGIN_LOOP(), SET_INT(oIntangibleTimer, 0), CALL_NATIVE(bhv_1up_sliding_loop), END_LOOP(), }; const BehaviorScript bhv1Up[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhv1Up), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), BILLBOARD(), SET_HITBOX_WITH_OFFSET(/*Radius*/ 30, /*Height*/ 30, /*Downwards offset*/ 0), SET_FLOAT(oGraphYOffset, 30), CALL_NATIVE(bhv_1up_init), BEGIN_LOOP(), SET_INT(oIntangibleTimer, 0), CALL_NATIVE(bhv_1up_loop), END_LOOP(), }; const BehaviorScript bhv1upJumpOnApproach[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhv1upJumpOnApproach), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), BILLBOARD(), SET_HITBOX_WITH_OFFSET(/*Radius*/ 30, /*Height*/ 30, /*Downwards offset*/ 0), SET_FLOAT(oGraphYOffset, 30), CALL_NATIVE(bhv_1up_common_init), BEGIN_LOOP(), SET_INT(oIntangibleTimer, 0), CALL_NATIVE(bhv_1up_jump_on_approach_loop), END_LOOP(), }; const BehaviorScript bhvHidden1up[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhvHidden1up), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), BILLBOARD(), SET_HITBOX_WITH_OFFSET(/*Radius*/ 30, /*Height*/ 30, /*Downwards offset*/ 0), SET_FLOAT(oGraphYOffset, 30), CALL_NATIVE(bhv_1up_common_init), BEGIN_LOOP(), SET_INT(oIntangibleTimer, 0), CALL_NATIVE(bhv_1up_hidden_loop), END_LOOP(), }; const BehaviorScript bhvHidden1upTrigger[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhvHidden1upTrigger), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), SET_HITBOX(/*Radius*/ 100, /*Height*/ 100), SET_INT(oIntangibleTimer, 0), CALL_NATIVE(bhv_1up_trigger_init), BEGIN_LOOP(), CALL_NATIVE(bhv_1up_hidden_trigger_loop), END_LOOP(), }; const BehaviorScript bhvHidden1upInPole[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhvHidden1upInPole), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), BILLBOARD(), SET_HITBOX_WITH_OFFSET(/*Radius*/ 30, /*Height*/ 30, /*Downwards offset*/ 0), SET_FLOAT(oGraphYOffset, 30), CALL_NATIVE(bhv_1up_common_init), BEGIN_LOOP(), SET_INT(oIntangibleTimer, 0), CALL_NATIVE(bhv_1up_hidden_in_pole_loop), END_LOOP(), }; const BehaviorScript bhvHidden1upInPoleTrigger[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhvHidden1upInPoleTrigger), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), SET_HITBOX(/*Radius*/ 100, /*Height*/ 100), SET_INT(oIntangibleTimer, 0), CALL_NATIVE(bhv_1up_trigger_init), BEGIN_LOOP(), CALL_NATIVE(bhv_1up_hidden_in_pole_trigger_loop), END_LOOP(), }; const BehaviorScript bhvHidden1upInPoleSpawner[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhvHidden1upInPoleSpawner), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), CALL_NATIVE(bhv_1up_trigger_init), BEGIN_LOOP(), CALL_NATIVE(bhv_1up_hidden_in_pole_spawner_loop), END_LOOP(), }; const BehaviorScript bhvControllablePlatform[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvControllablePlatform), OR_INT(oFlags, (OBJ_FLAG_SET_THROW_MATRIX_FROM_TRANSFORM | OBJ_FLAG_0020 | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_COLLISION_DATA(hmc_seg7_collision_controllable_platform), SET_HOME(), CALL_NATIVE(bhv_controllable_platform_init), BEGIN_LOOP(), CALL_NATIVE(bhv_controllable_platform_loop), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvControllablePlatformSub[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvControllablePlatformSub), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), LOAD_COLLISION_DATA(hmc_seg7_collision_controllable_platform_sub), BEGIN_LOOP(), CALL_NATIVE(bhv_controllable_platform_sub_loop), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvBreakableBoxSmall[] = { BEGIN(OBJ_LIST_DESTRUCTIVE), ID(id_bhvBreakableBoxSmall), OR_INT(oFlags, (OBJ_FLAG_HOLDABLE | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), DROP_TO_FLOOR(), SET_HOME(), CALL_NATIVE(bhv_breakable_box_small_init), BEGIN_LOOP(), SET_INT(oIntangibleTimer, 0), CALL_NATIVE(bhv_breakable_box_small_loop), END_LOOP(), }; const BehaviorScript bhvSlidingSnowMound[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvSlidingSnowMound), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), LOAD_COLLISION_DATA(sl_seg7_collision_sliding_snow_mound), SET_HOME(), BEGIN_LOOP(), CALL_NATIVE(bhv_sliding_snow_mound_loop), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvSnowMoundSpawn[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvSnowMoundSpawn), BEGIN_LOOP(), CALL_NATIVE(bhv_snow_mound_spawn_loop), END_LOOP(), }; const BehaviorScript bhvWdwSquareFloatingPlatform[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvWdwSquareFloatingPlatform), OR_INT(oFlags, (OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_COLLISION_DATA(wdw_seg7_collision_square_floating_platform), SET_FLOAT(oFloatingPlatformUnkFC, 64), SET_HOME(), BEGIN_LOOP(), CALL_NATIVE(bhv_floating_platform_loop), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvWdwRectangularFloatingPlatform[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvWdwRectangularFloatingPlatform), OR_INT(oFlags, (OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_COLLISION_DATA(wdw_seg7_collision_rect_floating_platform), SET_FLOAT(oFloatingPlatformUnkFC, 64), SET_HOME(), BEGIN_LOOP(), CALL_NATIVE(bhv_floating_platform_loop), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvJrbFloatingPlatform[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvJrbFloatingPlatform), OR_INT(oFlags, (OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_COLLISION_DATA(jrb_seg7_collision_floating_platform), SET_FLOAT(oFloatingPlatformUnkFC, 64), SET_HOME(), BEGIN_LOOP(), CALL_NATIVE(bhv_floating_platform_loop), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvArrowLift[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvArrowLift), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), LOAD_COLLISION_DATA(wdw_seg7_collision_arrow_lift), SET_INT_RAND_RSHIFT(oArrowLiftUnk100, /*Minimum*/ 1, /*Right shift*/ 32), SET_HOME(), BEGIN_LOOP(), CALL_NATIVE(bhv_arrow_lift_loop), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvOrangeNumber[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhvOrangeNumber), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), BILLBOARD(), SET_HOME(), CALL_NATIVE(bhv_orange_number_init), BEGIN_LOOP(), CALL_NATIVE(bhv_orange_number_loop), END_LOOP(), }; const BehaviorScript bhvMantaRay[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvMantaRay), OR_INT(oFlags, (OBJ_FLAG_SET_FACE_ANGLE_TO_MOVE_ANGLE | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_ANIMATIONS(oAnimations, &manta_seg5_anims_05008EB4), ANIMATE(0), CALL_NATIVE(bhv_manta_ray_init), BEGIN_LOOP(), SET_INT(oIntangibleTimer, 0), CALL_NATIVE(bhv_manta_ray_loop), END_LOOP(), }; const BehaviorScript bhvFallingPillar[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvFallingPillar), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), SET_HOME(), CALL_NATIVE(bhv_falling_pillar_init), BEGIN_LOOP(), CALL_NATIVE(bhv_falling_pillar_loop), END_LOOP(), }; const BehaviorScript bhvFallingPillarHitbox[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvFallingPillarHitbox), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), SET_HOME(), BEGIN_LOOP(), CALL_NATIVE(bhv_falling_pillar_hitbox_loop), END_LOOP(), }; const BehaviorScript bhvPillarBase[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvPillarBase), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), LOAD_COLLISION_DATA(jrb_seg7_collision_pillar_base), BEGIN_LOOP(), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvJrbFloatingBox[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvJrbFloatingBox), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), LOAD_COLLISION_DATA(jrb_seg7_collision_floating_box), SET_HOME(), BEGIN_LOOP(), CALL_NATIVE(bhv_jrb_floating_box_loop), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvDecorativePendulum[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvDecorativePendulum), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), CALL_NATIVE(bhv_decorative_pendulum_init), BEGIN_LOOP(), CALL_NATIVE(bhv_decorative_pendulum_loop), END_LOOP(), }; const BehaviorScript bhvTreasureChestsShip[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvTreasureChestsShip), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), DROP_TO_FLOOR(), CALL_NATIVE(bhv_treasure_chest_ship_init), BEGIN_LOOP(), CALL_NATIVE(bhv_treasure_chest_ship_loop), END_LOOP(), }; const BehaviorScript bhvTreasureChestsJrb[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvTreasureChestsJrb), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), DROP_TO_FLOOR(), CALL_NATIVE(bhv_treasure_chest_jrb_init), BEGIN_LOOP(), CALL_NATIVE(bhv_treasure_chest_jrb_loop), END_LOOP(), }; const BehaviorScript bhvTreasureChests[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvTreasureChests), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), DROP_TO_FLOOR(), CALL_NATIVE(bhv_treasure_chest_init), BEGIN_LOOP(), CALL_NATIVE(bhv_treasure_chest_loop), END_LOOP(), }; const BehaviorScript bhvTreasureChestBottom[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvTreasureChestBottom), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), DROP_TO_FLOOR(), CALL_NATIVE(bhv_treasure_chest_bottom_init), SET_INT(oIntangibleTimer, -1), BEGIN_LOOP(), CALL_NATIVE(bhv_treasure_chest_bottom_loop), END_LOOP(), }; const BehaviorScript bhvTreasureChestTop[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvTreasureChestTop), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), SET_HOME(), BEGIN_LOOP(), CALL_NATIVE(bhv_treasure_chest_top_loop), END_LOOP(), }; const BehaviorScript bhvMips[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvMips), OR_INT(oFlags, (OBJ_FLAG_HOLDABLE | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_ANIMATIONS(oAnimations, &mips_seg6_anims_06015634), SET_INT(oInteractType, INTERACT_GRABBABLE), DROP_TO_FLOOR(), SET_HITBOX(/*Radius*/ 50, /*Height*/ 75), SET_INT(oIntangibleTimer, 0), CALL_NATIVE(bhv_mips_init), BEGIN_LOOP(), CALL_NATIVE(bhv_mips_loop), END_LOOP(), }; const BehaviorScript bhvYoshi[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvYoshi), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_ANIMATIONS(oAnimations, &yoshi_seg5_anims_05024100), SET_INTERACT_TYPE(INTERACT_TEXT), DROP_TO_FLOOR(), SET_HITBOX(/*Radius*/ 160, /*Height*/ 150), ANIMATE(0), SET_HOME(), CALL_NATIVE(bhv_yoshi_init), BEGIN_LOOP(), SET_INT(oIntangibleTimer, 0), CALL_NATIVE(bhv_yoshi_loop), END_LOOP(), }; const BehaviorScript bhvKoopa[] = { BEGIN(OBJ_LIST_PUSHABLE), ID(id_bhvKoopa), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), DROP_TO_FLOOR(), LOAD_ANIMATIONS(oAnimations, &koopa_seg6_anims_06011364), ANIMATE(9), SET_HOME(), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 50, /*Gravity*/ -400, /*Bounciness*/ 0, /*Drag strength*/ 0, /*Friction*/ 1000, /*Buoyancy*/ 200, /*Unused*/ 0, 0), SCALE(/*Unused*/ 0, /*Field*/ 150), SET_FLOAT(oKoopaAgility, 1), CALL_NATIVE(bhv_koopa_init), BEGIN_LOOP(), CALL_NATIVE(bhv_koopa_update), END_LOOP(), }; const BehaviorScript bhvKoopaRaceEndpoint[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvKoopaRaceEndpoint), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), DROP_TO_FLOOR(), SPAWN_CHILD_WITH_PARAM(/*Bhv param*/ 0, /*Model*/ MODEL_KOOPA_FLAG, /*Behavior*/ bhvKoopaFlag), BEGIN_LOOP(), CALL_NATIVE(bhv_koopa_race_endpoint_update), END_LOOP(), }; const BehaviorScript bhvKoopaFlag[] = { BEGIN(OBJ_LIST_POLELIKE), ID(id_bhvKoopaFlag), SET_INTERACT_TYPE(INTERACT_POLE), SET_HITBOX(/*Radius*/ 80, /*Height*/ 700), SET_INT(oIntangibleTimer, 0), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), DROP_TO_FLOOR(), LOAD_ANIMATIONS(oAnimations, &koopa_flag_seg6_anims_06001028), ANIMATE(0), BEGIN_LOOP(), CALL_NATIVE(bhv_pole_base_loop), END_LOOP(), }; const BehaviorScript bhvPokey[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvPokey), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), DROP_TO_FLOOR(), SET_HOME(), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 60, /*Gravity*/ -400, /*Bounciness*/ 0, /*Drag strength*/ 1000, /*Friction*/ 1000, /*Buoyancy*/ 200, /*Unused*/ 0, 0), BEGIN_LOOP(), CALL_NATIVE(bhv_pokey_update), END_LOOP(), }; const BehaviorScript bhvPokeyBodyPart[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvPokeyBodyPart), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 60, /*Gravity*/ -400, /*Bounciness*/ 0, /*Drag strength*/ 1000, /*Friction*/ 1000, /*Buoyancy*/ 200, /*Unused*/ 0, 0), BILLBOARD(), BEGIN_LOOP(), CALL_NATIVE(bhv_pokey_body_part_update), END_LOOP(), }; const BehaviorScript bhvSwoop[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvSwoop), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_ANIMATIONS(oAnimations, &swoop_seg6_anims_060070D0), SET_HOME(), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 50, /*Gravity*/ 0, /*Bounciness*/ -50, /*Drag strength*/ 0, /*Friction*/ 0, /*Buoyancy*/ 0, /*Unused*/ 0, 0), CALL_NATIVE(bhv_init_room), SCALE(/*Unused*/ 0, /*Field*/ 0), BEGIN_LOOP(), CALL_NATIVE(bhv_swoop_update), END_LOOP(), }; const BehaviorScript bhvFlyGuy[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvFlyGuy), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_ANIMATIONS(oAnimations, &flyguy_seg8_anims_08011A64), ANIMATE(0), SET_HOME(), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 50, /*Gravity*/ 0, /*Bounciness*/ 0, /*Drag strength*/ 0, /*Friction*/ 1000, /*Buoyancy*/ 600, /*Unused*/ 0, 0), CALL_NATIVE(bhv_init_room), SET_INT(oInteractionSubtype, INT_SUBTYPE_TWIRL_BOUNCE), SET_FLOAT(oGraphYOffset, 30), SCALE(/*Unused*/ 0, /*Field*/ 150), BEGIN_LOOP(), CALL_NATIVE(bhv_fly_guy_update), END_LOOP(), }; const BehaviorScript bhvGoomba[] = { BEGIN(OBJ_LIST_PUSHABLE), ID(id_bhvGoomba), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), DROP_TO_FLOOR(), LOAD_ANIMATIONS(oAnimations, &goomba_seg8_anims_0801DA4C), SET_HOME(), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 40, /*Gravity*/ -400, /*Bounciness*/ -50, /*Drag strength*/ 1000, /*Friction*/ 1000, /*Buoyancy*/ 0, /*Unused*/ 0, 0), CALL_NATIVE(bhv_goomba_init), BEGIN_LOOP(), CALL_NATIVE(bhv_goomba_update), END_LOOP(), }; const BehaviorScript bhvGoombaTripletSpawner[] = { BEGIN(OBJ_LIST_PUSHABLE), ID(id_bhvGoombaTripletSpawner), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), DROP_TO_FLOOR(), BEGIN_LOOP(), CALL_NATIVE(bhv_goomba_triplet_spawner_update), END_LOOP(), }; const BehaviorScript bhvChainChomp[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvChainChomp), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_ACTIVE_FROM_AFAR | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), DROP_TO_FLOOR(), LOAD_ANIMATIONS(oAnimations, &chain_chomp_seg6_anims_06025178), ANIMATE(0), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 0, /*Gravity*/ -400, /*Bounciness*/ -50, /*Drag strength*/ 0, /*Friction*/ 1000, /*Buoyancy*/ 200, /*Unused*/ 0, 0), HIDE(), SET_HOME(), SET_FLOAT(oGraphYOffset, 240), SCALE(/*Unused*/ 0, /*Field*/ 200), SPAWN_CHILD_WITH_PARAM(/*Bhv param*/ 0, /*Model*/ MODEL_WOODEN_POST, /*Behavior*/ bhvWoodenPost), BEGIN_LOOP(), CALL_NATIVE(bhv_chain_chomp_update), END_LOOP(), }; const BehaviorScript bhvChainChompChainPart[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvChainChompChainPart), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), BILLBOARD(), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 0, /*Gravity*/ -400, /*Bounciness*/ -50, /*Drag strength*/ 1000, /*Friction*/ 1000, /*Buoyancy*/ 200, /*Unused*/ 0, 0), SET_FLOAT(oGraphYOffset, 40), SCALE(/*Unused*/ 0, /*Field*/ 200), BEGIN_LOOP(), CALL_NATIVE(bhv_chain_chomp_chain_part_update), END_LOOP(), }; const BehaviorScript bhvWoodenPost[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvWoodenPost), LOAD_COLLISION_DATA(poundable_pole_collision_06002490), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 0, /*Gravity*/ -400, /*Bounciness*/ -50, /*Drag strength*/ 1000, /*Friction*/ 1000, /*Buoyancy*/ 200, /*Unused*/ 0, 0), SET_INT(oNumLootCoins, 5), DROP_TO_FLOOR(), SET_HOME(), SCALE(/*Unused*/ 0, /*Field*/ 50), BEGIN_LOOP(), CALL_NATIVE(bhv_wooden_post_update), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvChainChompGate[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvChainChompGate), LOAD_COLLISION_DATA(bob_seg7_collision_chain_chomp_gate), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), CALL_NATIVE(bhv_chain_chomp_gate_init), BEGIN_LOOP(), CALL_NATIVE(bhv_chain_chomp_gate_update), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvWigglerHead[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvWigglerHead), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), DROP_TO_FLOOR(), LOAD_ANIMATIONS(oAnimations, &wiggler_seg5_anims_0500EC8C), SET_HOME(), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 60, /*Gravity*/ -400, /*Bounciness*/ 0, /*Drag strength*/ 1000, /*Friction*/ 1000, /*Buoyancy*/ 200, /*Unused*/ 0, 0), HIDE(), SCALE(/*Unused*/ 0, /*Field*/ 400), SET_FLOAT(oWigglerFallThroughFloorsHeight, 5000), BEGIN_LOOP(), CALL_NATIVE(bhv_wiggler_update), END_LOOP(), }; const BehaviorScript bhvWigglerBody[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvWigglerBody), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), LOAD_ANIMATIONS(oAnimations, &wiggler_seg5_anims_0500C874), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 0, /*Gravity*/ -400, /*Bounciness*/ 0, /*Drag strength*/ 1000, /*Friction*/ 1000, /*Buoyancy*/ 200, /*Unused*/ 0, 0), SCALE(/*Unused*/ 0, /*Field*/ 400), BEGIN_LOOP(), CALL_NATIVE(bhv_wiggler_body_part_update), END_LOOP(), }; const BehaviorScript bhvEnemyLakitu[] = { BEGIN(OBJ_LIST_PUSHABLE), ID(id_bhvEnemyLakitu), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_ANIMATIONS(oAnimations, &lakitu_enemy_seg5_anims_050144D4), ANIMATE(0), SET_HOME(), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 40, /*Gravity*/ 0, /*Bounciness*/ -50, /*Drag strength*/ 0, /*Friction*/ 0, /*Buoyancy*/ 200, /*Unused*/ 0, 0), BEGIN_LOOP(), CALL_NATIVE(bhv_enemy_lakitu_update), END_LOOP(), }; const BehaviorScript bhvCameraLakitu[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvCameraLakitu), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_ANIMATIONS(oAnimations, &lakitu_seg6_anims_060058F8), ANIMATE(0), CALL_NATIVE(bhv_init_room), CALL_NATIVE(bhv_camera_lakitu_init), BEGIN_LOOP(), CALL_NATIVE(bhv_camera_lakitu_update), END_LOOP(), }; const BehaviorScript bhvCloud[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvCloud), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), BILLBOARD(), SET_HOME(), SET_INT(oOpacity, 240), BEGIN_LOOP(), CALL_NATIVE(bhv_cloud_update), END_LOOP(), }; const BehaviorScript bhvCloudPart[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvCloudPart), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), SET_INT(oOpacity, 240), BEGIN_LOOP(), CALL_NATIVE(bhv_cloud_part_update), END_LOOP(), }; const BehaviorScript bhvSpiny[] = { BEGIN(OBJ_LIST_PUSHABLE), ID(id_bhvSpiny), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_ANIMATIONS(oAnimations, &spiny_seg5_anims_05016EAC), ANIMATE(0), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 40, /*Gravity*/ -400, /*Bounciness*/ -50, /*Drag strength*/ 1000, /*Friction*/ 1000, /*Buoyancy*/ 200, /*Unused*/ 0, 0), BEGIN_LOOP(), CALL_NATIVE(bhv_spiny_update), END_LOOP(), }; const BehaviorScript bhvMontyMole[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvMontyMole), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), DROP_TO_FLOOR(), LOAD_ANIMATIONS(oAnimations, &monty_mole_seg5_anims_05007248), ANIMATE(3), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 30, /*Gravity*/ 0, /*Bounciness*/ -50, /*Drag strength*/ 1000, /*Friction*/ 1000, /*Buoyancy*/ 200, /*Unused*/ 0, 0), HIDE(), SET_INT(oIntangibleTimer, -1), SET_FLOAT(oGraphYOffset, -60), SCALE(/*Unused*/ 0, /*Field*/ 150), DELAY(1), CALL_NATIVE(bhv_monty_mole_init), BEGIN_LOOP(), CALL_NATIVE(bhv_monty_mole_update), END_LOOP(), }; const BehaviorScript bhvMontyMoleHole[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvMontyMoleHole), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), DROP_TO_FLOOR(), SCALE(/*Unused*/ 0, /*Field*/ 150), BEGIN_LOOP(), CALL_NATIVE(bhv_monty_mole_hole_update), END_LOOP(), }; const BehaviorScript bhvMontyMoleRock[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvMontyMoleRock), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), BILLBOARD(), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 30, /*Gravity*/ -400, /*Bounciness*/ -50, /*Drag strength*/ 1000, /*Friction*/ 1000, /*Buoyancy*/ 200, /*Unused*/ 0, 0), SET_FLOAT(oGraphYOffset, 10), SCALE(/*Unused*/ 0, /*Field*/ 200), BEGIN_LOOP(), CALL_NATIVE(bhv_monty_mole_rock_update), END_LOOP(), }; const BehaviorScript bhvPlatformOnTrack[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvPlatformOnTrack), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 50, /*Gravity*/ -100, /*Bounciness*/ -50, /*Drag strength*/ 100, /*Friction*/ 1000, /*Buoyancy*/ 200, /*Unused*/ 0, 0), CALL_NATIVE(bhv_init_room), CALL_NATIVE(bhv_platform_on_track_init), BEGIN_LOOP(), CALL_NATIVE(bhv_platform_on_track_update), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvTrackBall[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvTrackBall), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), BILLBOARD(), CALL_NATIVE(bhv_init_room), SCALE(/*Unused*/ 0, /*Field*/ 15), BEGIN_LOOP(), CALL_NATIVE(bhv_track_ball_update), END_LOOP(), }; const BehaviorScript bhvSeesawPlatform[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvSeesawPlatform), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), CALL_NATIVE(bhv_seesaw_platform_init), BEGIN_LOOP(), CALL_NATIVE(bhv_seesaw_platform_update), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvFerrisWheelAxle[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvFerrisWheelAxle), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), ADD_INT(oMoveAngleYaw, 0x4000), CALL_NATIVE(bhv_ferris_wheel_axle_init), BEGIN_LOOP(), ADD_INT(oFaceAngleRoll, 400), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvFerrisWheelPlatform[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvFerrisWheelPlatform), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), CALL_NATIVE(bhv_ferris_wheel_platform_init), BEGIN_LOOP(), CALL_NATIVE(bhv_ferris_wheel_platform_update), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvWaterBombSpawner[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvWaterBombSpawner), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), DROP_TO_FLOOR(), BEGIN_LOOP(), CALL_NATIVE(bhv_water_bomb_spawner_update), END_LOOP(), }; const BehaviorScript bhvWaterBomb[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvWaterBomb), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 120, /*Gravity*/ -400, /*Bounciness*/ 0, /*Drag strength*/ 1000, /*Friction*/ 1000, /*Buoyancy*/ 200, /*Unused*/ 0, 0), BEGIN_LOOP(), CALL_NATIVE(bhv_water_bomb_update), END_LOOP(), }; const BehaviorScript bhvWaterBombShadow[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvWaterBombShadow), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), SCALE(/*Unused*/ 0, /*Field*/ 150), BEGIN_LOOP(), CALL_NATIVE(bhv_water_bomb_shadow_update), END_LOOP(), }; const BehaviorScript bhvTTCRotatingSolid[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvTTCRotatingSolid), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), SET_HOME(), SET_FLOAT(oCollisionDistance, 450), CALL_NATIVE(bhv_ttc_rotating_solid_init), SET_INT(oTTCRotatingSolidNumTurns, 1), BEGIN_LOOP(), CALL_NATIVE(bhv_ttc_rotating_solid_update), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvTTCPendulum[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvTTCPendulum), LOAD_COLLISION_DATA(ttc_seg7_collision_clock_pendulum), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), SET_FLOAT(oCollisionDistance, 1500), CALL_NATIVE(bhv_ttc_pendulum_init), SET_FLOAT(oTTCPendulumAccelDir, 1), BEGIN_LOOP(), CALL_NATIVE(bhv_ttc_pendulum_update), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvTTCTreadmill[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvTTCTreadmill), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), SET_FLOAT(oCollisionDistance, 750), CALL_NATIVE(bhv_ttc_treadmill_init), DELAY(1), BEGIN_LOOP(), CALL_NATIVE(bhv_ttc_treadmill_update), CALL_NATIVE(cur_obj_compute_vel_xz), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvTTCMovingBar[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvTTCMovingBar), LOAD_COLLISION_DATA(ttc_seg7_collision_sliding_surface), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), SET_HOME(), SET_FLOAT(oCollisionDistance, 550), CALL_NATIVE(bhv_ttc_moving_bar_init), BEGIN_LOOP(), CALL_NATIVE(bhv_ttc_moving_bar_update), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvTTCCog[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvTTCCog), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), SET_FLOAT(oCollisionDistance, 400), CALL_NATIVE(bhv_ttc_cog_init), BEGIN_LOOP(), CALL_NATIVE(bhv_ttc_cog_update), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvTTCPitBlock[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvTTCPitBlock), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), SET_HOME(), SET_FLOAT(oCollisionDistance, 350), CALL_NATIVE(bhv_ttc_pit_block_init), BEGIN_LOOP(), CALL_NATIVE(bhv_ttc_pit_block_update), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvTTCElevator[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvTTCElevator), LOAD_COLLISION_DATA(ttc_seg7_collision_clock_platform), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), SET_HOME(), SET_FLOAT(oCollisionDistance, 400), CALL_NATIVE(bhv_ttc_elevator_init), SET_FLOAT(oTTCElevatorDir, 1), BEGIN_LOOP(), CALL_NATIVE(bhv_ttc_elevator_update), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvTTC2DRotator[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvTTC2DRotator), LOAD_COLLISION_DATA(ttc_seg7_collision_clock_main_rotation), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), SET_FLOAT(oCollisionDistance, 1800), CALL_NATIVE(bhv_ttc_2d_rotator_init), BEGIN_LOOP(), CALL_NATIVE(bhv_ttc_2d_rotator_update), END_LOOP(), }; const BehaviorScript bhvTTCSpinner[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvTTCSpinner), LOAD_COLLISION_DATA(ttc_seg7_collision_rotating_clock_platform2), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), SET_FLOAT(oCollisionDistance, 450), BEGIN_LOOP(), CALL_NATIVE(bhv_ttc_spinner_update), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvMrBlizzard[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvMrBlizzard), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), DROP_TO_FLOOR(), LOAD_ANIMATIONS(oAnimations, &snowman_seg5_anims_0500D118), ANIMATE(0), SET_HOME(), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 30, /*Gravity*/ -400, /*Bounciness*/ 0, /*Drag strength*/ 1000, /*Friction*/ 1000, /*Buoyancy*/ 200, /*Unused*/ 0, 0), CALL_NATIVE(bhv_mr_blizzard_init), SET_FLOAT(oMrBlizzardScale, 1), BEGIN_LOOP(), CALL_NATIVE(bhv_mr_blizzard_update), END_LOOP(), }; const BehaviorScript bhvMrBlizzardSnowball[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvMrBlizzardSnowball), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), BILLBOARD(), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 30, /*Gravity*/ -300, /*Bounciness*/ -50, /*Drag strength*/ 1000, /*Friction*/ 1000, /*Buoyancy*/ 200, /*Unused*/ 0, 0), SCALE(/*Unused*/ 0, /*Field*/ 200), ADD_INT(oMoveAngleYaw, -0x5B58), SET_FLOAT(oForwardVel, 5), SET_FLOAT(oVelY, -1), SET_FLOAT(oGraphYOffset, 10), BEGIN_LOOP(), CALL_NATIVE(bhv_mr_blizzard_snowball), END_LOOP(), }; const BehaviorScript bhvSlidingPlatform2[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvSlidingPlatform2), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), SET_HOME(), CALL_NATIVE(bhv_sliding_plat_2_init), BEGIN_LOOP(), CALL_NATIVE(bhv_sliding_plat_2_loop), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvOctagonalPlatformRotating[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvOctagonalPlatformRotating), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), CALL_NATIVE(bhv_rotating_octagonal_plat_init), BEGIN_LOOP(), CALL_NATIVE(bhv_rotating_octagonal_plat_loop), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvAnimatesOnFloorSwitchPress[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvAnimatesOnFloorSwitchPress), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), SET_FLOAT(oCollisionDistance, 8000), CALL_NATIVE(bhv_animates_on_floor_switch_press_init), BEGIN_LOOP(), CALL_NATIVE(bhv_animates_on_floor_switch_press_loop), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvActivatedBackAndForthPlatform[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvActivatedBackAndForthPlatform), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), SET_HOME(), CALL_NATIVE(bhv_activated_back_and_forth_platform_init), BEGIN_LOOP(), CALL_NATIVE(bhv_activated_back_and_forth_platform_update), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvRecoveryHeart[] = { BEGIN(OBJ_LIST_LEVEL), ID(id_bhvRecoveryHeart), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), BEGIN_LOOP(), CALL_NATIVE(bhv_recovery_heart_loop), END_LOOP(), }; const BehaviorScript bhvWaterBombCannon[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvWaterBombCannon), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), BEGIN_LOOP(), CALL_NATIVE(bhv_water_bomb_cannon_loop), END_LOOP(), }; const BehaviorScript bhvCannonBarrelBubbles[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvCannonBarrelBubbles), OR_INT(oFlags, (OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), BEGIN_LOOP(), CALL_NATIVE(bhv_bubble_cannon_barrel_loop), END_LOOP(), }; const BehaviorScript bhvUnagi[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvUnagi), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_ANIMATIONS(oAnimations, &unagi_seg5_anims_05012824), ANIMATE(6), SET_HOME(), SCALE(/*Unused*/ 0, /*Field*/ 300), SET_FLOAT(oDrawingDistance, 6000), CALL_NATIVE(bhv_unagi_init), BEGIN_LOOP(), CALL_NATIVE(bhv_unagi_loop), END_LOOP(), }; const BehaviorScript bhvUnagiSubobject[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvUnagiSubobject), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), BEGIN_LOOP(), CALL_NATIVE(bhv_unagi_subobject_loop), END_LOOP(), }; const BehaviorScript bhvDorrie[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvDorrie), LOAD_COLLISION_DATA(dorrie_seg6_collision_0600F644), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_ANIMATIONS(oAnimations, &dorrie_seg6_anims_0600F638), SET_HOME(), SET_FLOAT(oCollisionDistance, 30000), ADD_FLOAT(oPosX, 2000), CALL_NATIVE(bhv_init_room), BEGIN_LOOP(), CALL_NATIVE(bhv_dorrie_update), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvHauntedChair[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvHauntedChair), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), DROP_TO_FLOOR(), LOAD_ANIMATIONS(oAnimations, &chair_seg5_anims_05005784), ANIMATE(0), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 40, /*Gravity*/ 0, /*Bounciness*/ -50, /*Drag strength*/ 1000, /*Friction*/ 1000, /*Buoyancy*/ 200, /*Unused*/ 0, 0), SET_HOME(), CALL_NATIVE(bhv_init_room), CALL_NATIVE(bhv_haunted_chair_init), BEGIN_LOOP(), CALL_NATIVE(bhv_haunted_chair_loop), END_LOOP(), }; const BehaviorScript bhvMadPiano[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvMadPiano), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), DROP_TO_FLOOR(), LOAD_ANIMATIONS(oAnimations, &mad_piano_seg5_anims_05009B14), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 40, /*Gravity*/ 0, /*Bounciness*/ -50, /*Drag strength*/ 1000, /*Friction*/ 1000, /*Buoyancy*/ 200, /*Unused*/ 0, 0), SET_HOME(), ADD_INT(oMoveAngleYaw, 0x4000), CALL_NATIVE(bhv_init_room), BEGIN_LOOP(), CALL_NATIVE(bhv_mad_piano_update), END_LOOP(), }; const BehaviorScript bhvFlyingBookend[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvFlyingBookend), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_ANIMATIONS(oAnimations, &bookend_seg5_anims_05002540), ANIMATE(0), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 60, /*Gravity*/ 0, /*Bounciness*/ -50, /*Drag strength*/ 1000, /*Friction*/ 1000, /*Buoyancy*/ 200, /*Unused*/ 0, 0), SET_INT(oMoveFlags, 0), SCALE(/*Unused*/ 0, /*Field*/ 70), CALL_NATIVE(bhv_init_room), BEGIN_LOOP(), CALL_NATIVE(bhv_flying_bookend_loop), END_LOOP(), }; const BehaviorScript bhvBookendSpawn[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvBookendSpawn), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), CALL_NATIVE(bhv_init_room), BEGIN_LOOP(), CALL_NATIVE(bhv_bookend_spawn_loop), END_LOOP(), }; const BehaviorScript bhvHauntedBookshelfManager[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvHauntedBookshelfManager), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), CALL_NATIVE(bhv_init_room), BEGIN_LOOP(), CALL_NATIVE(bhv_haunted_bookshelf_manager_loop), END_LOOP(), }; const BehaviorScript bhvBookSwitch[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvBookSwitch), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), SET_HOME(), SET_FLOAT(oGraphYOffset, 30), ADD_INT(oMoveAngleYaw, 0x4000), CALL_NATIVE(bhv_init_room), BEGIN_LOOP(), CALL_NATIVE(bhv_book_switch_loop), END_LOOP(), }; const BehaviorScript bhvFirePiranhaPlant[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvFirePiranhaPlant), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), DROP_TO_FLOOR(), LOAD_ANIMATIONS(oAnimations, &piranha_plant_seg6_anims_0601C31C), ANIMATE(0), SET_HOME(), HIDE(), CALL_NATIVE(bhv_fire_piranha_plant_init), BEGIN_LOOP(), CALL_NATIVE(bhv_fire_piranha_plant_update), END_LOOP(), }; const BehaviorScript bhvSmallPiranhaFlame[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvSmallPiranhaFlame), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), BILLBOARD(), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 30, /*Gravity*/ 0, /*Bounciness*/ -50, /*Drag strength*/ 1000, /*Friction*/ 1000, /*Buoyancy*/ 200, /*Unused*/ 0, 0), BEGIN_LOOP(), CALL_NATIVE(bhv_small_piranha_flame_loop), ADD_INT(oAnimState, 1), END_LOOP(), }; const BehaviorScript bhvFireSpitter[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvFireSpitter), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), BILLBOARD(), SCALE(/*Unused*/ 0, /*Field*/ 40), BEGIN_LOOP(), CALL_NATIVE(bhv_fire_spitter_update), END_LOOP(), }; const BehaviorScript bhvFlyguyFlame[] = { BEGIN(OBJ_LIST_UNIMPORTANT), ID(id_bhvFlyguyFlame), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), BILLBOARD(), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 0, /*Gravity*/ 200, /*Bounciness*/ 0, /*Drag strength*/ 1000, /*Friction*/ 1000, /*Buoyancy*/ 200, /*Unused*/ 0, 0), BEGIN_LOOP(), CALL_NATIVE(bhv_fly_guy_flame_loop), ADD_INT(oAnimState, 1), END_LOOP(), }; const BehaviorScript bhvSnufit[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvSnufit), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), SET_HOME(), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 30, /*Gravity*/ 0, /*Bounciness*/ -50, /*Drag strength*/ 0, /*Friction*/ 0, /*Buoyancy*/ 0, /*Unused*/ 0, 0), CALL_NATIVE(bhv_init_room), BEGIN_LOOP(), SET_INT(oSnufitRecoil, 0), CALL_NATIVE(bhv_snufit_loop), END_LOOP(), }; const BehaviorScript bhvSnufitBalls[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvSnufitBalls), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), BILLBOARD(), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 10, /*Gravity*/ 0, /*Bounciness*/ -50, /*Drag strength*/ 1000, /*Friction*/ 1000, /*Buoyancy*/ 200, /*Unused*/ 0, 0), CALL_NATIVE(bhv_init_room), SET_FLOAT(oGraphYOffset, 10), SCALE(/*Unused*/ 0, /*Field*/ 10), BEGIN_LOOP(), CALL_NATIVE(bhv_snufit_balls_loop), END_LOOP(), }; const BehaviorScript bhvHorizontalGrindel[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvHorizontalGrindel), LOAD_COLLISION_DATA(ssl_seg7_collision_grindel), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), DROP_TO_FLOOR(), SET_HOME(), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 40, /*Gravity*/ -400, /*Bounciness*/ 0, /*Drag strength*/ 1000, /*Friction*/ 1000, /*Buoyancy*/ 200, /*Unused*/ 0, 0), SCALE(/*Unused*/ 0, /*Field*/ 90), CALL_NATIVE(bhv_horizontal_grindel_init), BEGIN_LOOP(), CALL_NATIVE(cur_obj_update_floor_and_walls), CALL_NATIVE(bhv_horizontal_grindel_update), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvEyerokBoss[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvEyerokBoss), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), SET_HOME(), CALL_NATIVE(bhv_eyerok_boss_init), BEGIN_LOOP(), CALL_NATIVE(bhv_eyerok_boss_loop), END_LOOP(), }; const BehaviorScript bhvEyerokHand[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvEyerokHand), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_ANIMATIONS(oAnimations, &eyerok_seg5_anims_050116E4), ANIMATE(6), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 150, /*Gravity*/ 0, /*Bounciness*/ 0, /*Drag strength*/ 0, /*Friction*/ 1000, /*Buoyancy*/ 200, /*Unused*/ 0, 0), SET_HOME(), SET_INT(oAnimState, 3), BEGIN_LOOP(), CALL_NATIVE(bhv_eyerok_hand_loop), END_LOOP(), }; const BehaviorScript bhvKlepto[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvKlepto), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_ACTIVE_FROM_AFAR | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_ANIMATIONS(oAnimations, &klepto_seg5_anims_05008CFC), ANIMATE(0), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 100, /*Gravity*/ 0, /*Bounciness*/ -20, /*Drag strength*/ 1000, /*Friction*/ 1000, /*Buoyancy*/ 200, /*Unused*/ 0, 0), SET_HOME(), CALL_NATIVE(bhv_klepto_init), BEGIN_LOOP(), CALL_NATIVE(bhv_klepto_update), END_LOOP(), }; const BehaviorScript bhvBird[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvBird), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_ANIMATIONS(oAnimations, &birds_seg5_anims_050009E8), ANIMATE(0), HIDE(), SCALE(/*Unused*/ 0, /*Field*/ 70), BEGIN_LOOP(), CALL_NATIVE(bhv_bird_update), END_LOOP(), }; const BehaviorScript bhvRacingPenguin[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvRacingPenguin), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_ACTIVE_FROM_AFAR | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_ANIMATIONS(oAnimations, &penguin_seg5_anims_05008B74), ANIMATE(3), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 300, /*Gravity*/ -800, /*Bounciness*/ -5, /*Drag strength*/ 0, /*Friction*/ 0, /*Buoyancy*/ 0, /*Unused*/ 0, 0), SCALE(/*Unused*/ 0, /*Field*/ 400), CALL_NATIVE(bhv_racing_penguin_init), BEGIN_LOOP(), CALL_NATIVE(bhv_racing_penguin_update), END_LOOP(), }; const BehaviorScript bhvPenguinRaceFinishLine[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvPenguinRaceFinishLine), OR_INT(oFlags, (OBJ_FLAG_ACTIVE_FROM_AFAR | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), BEGIN_LOOP(), CALL_NATIVE(bhv_penguin_race_finish_line_update), END_LOOP(), }; const BehaviorScript bhvPenguinRaceShortcutCheck[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvPenguinRaceShortcutCheck), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), BEGIN_LOOP(), CALL_NATIVE(bhv_penguin_race_shortcut_check_update), END_LOOP(), }; const BehaviorScript bhvCoffinSpawner[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvCoffinSpawner), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), CALL_NATIVE(bhv_init_room), BEGIN_LOOP(), CALL_NATIVE(bhv_coffin_spawner_loop), END_LOOP(), }; const BehaviorScript bhvCoffin[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvCoffin), LOAD_COLLISION_DATA(bbh_seg7_collision_coffin), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), SET_HOME(), CALL_NATIVE(bhv_init_room), BEGIN_LOOP(), CALL_NATIVE(bhv_coffin_loop), END_LOOP(), }; const BehaviorScript bhvClamShell[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvClamShell), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), DROP_TO_FLOOR(), LOAD_ANIMATIONS(oAnimations, &clam_shell_seg5_anims_05001744), SET_FLOAT(oGraphYOffset, 10), BEGIN_LOOP(), CALL_NATIVE(bhv_clam_loop), END_LOOP(), }; const BehaviorScript bhvSkeeter[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvSkeeter), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_ANIMATIONS(oAnimations, &skeeter_seg6_anims_06007DE0), SET_HOME(), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 180, /*Gravity*/ -400, /*Bounciness*/ -50, /*Drag strength*/ 1000, /*Friction*/ 1000, /*Buoyancy*/ 1200, /*Unused*/ 0, 0), BEGIN_LOOP(), CALL_NATIVE(bhv_skeeter_update), END_LOOP(), }; const BehaviorScript bhvSkeeterWave[] = { BEGIN(OBJ_LIST_UNIMPORTANT), ID(id_bhvSkeeterWave), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), BEGIN_LOOP(), CALL_NATIVE(bhv_skeeter_wave_update), END_LOOP(), }; const BehaviorScript bhvSwingPlatform[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvSwingPlatform), LOAD_COLLISION_DATA(rr_seg7_collision_pendulum), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), SET_FLOAT(oCollisionDistance, 2000), CALL_NATIVE(bhv_swing_platform_init), BEGIN_LOOP(), CALL_NATIVE(bhv_swing_platform_update), CALL_NATIVE(load_object_collision_model), END_LOOP(), }; const BehaviorScript bhvDonutPlatformSpawner[] = { BEGIN(OBJ_LIST_SPAWNER), ID(id_bhvDonutPlatformSpawner), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), BEGIN_LOOP(), CALL_NATIVE(bhv_donut_platform_spawner_update), END_LOOP(), }; const BehaviorScript bhvDonutPlatform[] = { BEGIN(OBJ_LIST_SURFACE), ID(id_bhvDonutPlatform), LOAD_COLLISION_DATA(rr_seg7_collision_donut_platform), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), SET_HOME(), BEGIN_LOOP(), CALL_NATIVE(bhv_donut_platform_update), END_LOOP(), }; const BehaviorScript bhvDDDPole[] = { BEGIN(OBJ_LIST_POLELIKE), ID(id_bhvDDDPole), SET_INTERACT_TYPE(INTERACT_POLE), SET_HITBOX(/*Radius*/ 80, /*Height*/ 800), SET_INT(oIntangibleTimer, 0), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), SET_HOME(), CALL_NATIVE(bhv_ddd_pole_init), SET_FLOAT(oDDDPoleVel, 10), BEGIN_LOOP(), CALL_NATIVE(bhv_ddd_pole_update), END_LOOP(), }; const BehaviorScript bhvRedCoinStarMarker[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvRedCoinStarMarker), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), DROP_TO_FLOOR(), SCALE(/*Unused*/ 0, /*Field*/ 150), SET_INT(oFaceAnglePitch, 0x4000), ADD_FLOAT(oPosY, 60), CALL_NATIVE(bhv_red_coin_star_marker_init), BEGIN_LOOP(), ADD_INT(oFaceAngleYaw, 0x100), END_LOOP(), }; const BehaviorScript bhvTripletButterfly[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvTripletButterfly), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_ANIMATIONS(oAnimations, &butterfly_seg3_anims_030056B0), ANIMATE(0), HIDE(), SET_HOME(), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 0, /*Gravity*/ 0, /*Bounciness*/ 0, /*Drag strength*/ 0, /*Friction*/ 1000, /*Buoyancy*/ 200, /*Unused*/ 0, 0), SET_FLOAT(oTripletButterflyScale, 1), BEGIN_LOOP(), CALL_NATIVE(bhv_triplet_butterfly_update), END_LOOP(), }; const BehaviorScript bhvBubba[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_bhvBubba), OR_INT(oFlags, (OBJ_FLAG_COMPUTE_ANGLE_TO_MARIO | OBJ_FLAG_COMPUTE_DIST_TO_MARIO | OBJ_FLAG_SET_FACE_YAW_TO_MOVE_YAW | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), SET_HOME(), SET_OBJ_PHYSICS(/*Wall hitbox radius*/ 200, /*Gravity*/ -400, /*Bounciness*/ -50, /*Drag strength*/ 1000, /*Friction*/ 1000, /*Buoyancy*/ 0, /*Unused*/ 0, 0), SCALE(/*Unused*/ 0, /*Field*/ 50), BEGIN_LOOP(), CALL_NATIVE(bhv_bubba_loop), END_LOOP(), }; const BehaviorScript bhvBeginningLakitu[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvBeginningLakitu), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), LOAD_ANIMATIONS(oAnimations, &lakitu_seg6_anims_060058F8), ANIMATE(0), SET_FLOAT(oOpacity, 0), BEGIN_LOOP(), CALL_NATIVE(bhv_intro_lakitu_loop), END_LOOP(), }; const BehaviorScript bhvBeginningPeach[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvBeginningPeach), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), LOAD_ANIMATIONS(oAnimations, &peach_seg5_anims_0501C41C), ANIMATE(0), BEGIN_LOOP(), CALL_NATIVE(bhv_intro_peach_loop), END_LOOP(), }; const BehaviorScript bhvEndBirds1[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvEndBirds1), OR_INT(oFlags, (OBJ_FLAG_SET_FACE_ANGLE_TO_MOVE_ANGLE | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_ANIMATIONS(oAnimations, &birds_seg5_anims_050009E8), ANIMATE(0), BEGIN_LOOP(), CALL_NATIVE(bhv_end_birds_1_loop), END_LOOP(), }; const BehaviorScript bhvEndBirds2[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvEndBirds2), OR_INT(oFlags, (OBJ_FLAG_SET_FACE_ANGLE_TO_MOVE_ANGLE | OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE)), LOAD_ANIMATIONS(oAnimations, &birds_seg5_anims_050009E8), ANIMATE(0), BEGIN_LOOP(), CALL_NATIVE(bhv_end_birds_2_loop), END_LOOP(), }; const BehaviorScript bhvIntroScene[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvIntroScene), OR_INT(oFlags, OBJ_FLAG_UPDATE_GFX_POS_AND_ANGLE), BEGIN_LOOP(), CALL_NATIVE(bhv_intro_scene_loop), END_LOOP(), }; const BehaviorScript RM_Scroll_Texture[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_RM_Scroll_Texture), BEGIN_LOOP(), CALL_NATIVE(uv_update_scroll), END_LOOP(), }; const BehaviorScript editor_Scroll_Texture[] = { BEGIN(OBJ_LIST_GENACTOR), ID(id_editor_Scroll_Texture), BEGIN_LOOP(), CALL_NATIVE(uv_update_scroll), END_LOOP(), }; const BehaviorScript bhvAmbientLight[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvAmbientLight), BEGIN_LOOP(), CALL_NATIVE(bhv_ambient_light_update), END_LOOP(), }; const BehaviorScript bhvPointLight[] = { BEGIN(OBJ_LIST_DEFAULT), ID(id_bhvPointLight), SET_HOME(), CALL_NATIVE(bhv_point_light_init), BEGIN_LOOP(), CALL_NATIVE(bhv_point_light_loop), END_LOOP(), };
1
0.801242
1
0.801242
game-dev
MEDIA
0.772164
game-dev
0.596539
1
0.596539
solarus-games/solarus
1,917
include/solarus/movements/PathFindingMovement.h
/* * Copyright (C) 2006-2018 Christopho, Solarus - http://www.solarus-games.org * * Solarus 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. * * Solarus 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/>. */ #ifndef SOLARUS_PATH_FINDING_MOVEMENT_H #define SOLARUS_PATH_FINDING_MOVEMENT_H #include "solarus/core/Common.h" #include "solarus/entities/EntityPtr.h" #include "solarus/movements/PathMovement.h" #include <cstdint> #include <string> namespace Solarus { /** * \brief Movement for an entity that looks for a path to another entity. * * This movement is typically used by enemies that try to reach the hero. * The entity tries to find a path and to avoid the obstacles on the way. * To this end, the PathFinding class (i.e. an implementation of the A* algorithm) is used. * If the target entity is too far or not reachable, the movement is a random walk. */ class SOLARUS_API PathFindingMovement: public PathMovement { public: explicit PathFindingMovement(int speed); void set_target(const EntityPtr& target); virtual bool is_finished() const override; virtual const std::string& get_lua_type_name() const override; protected: virtual void update() override; void recompute_movement(); private: EntityPtr target; /**< the entity targeted by this movement (usually the hero) */ uint32_t next_recomputation_date; }; } #endif
1
0.556433
1
0.556433
game-dev
MEDIA
0.526827
game-dev
0.51264
1
0.51264
TeamTwilight/twilightforest-fabric
2,260
src/main/java/twilightforest/world/components/feature/FoundationFeature.java
package twilightforest.world.components.feature; import com.mojang.serialization.Codec; import net.minecraft.util.RandomSource; import net.minecraft.world.level.block.Blocks; import net.minecraft.core.Direction; import net.minecraft.core.BlockPos; import net.minecraft.world.level.WorldGenLevel; import net.minecraft.world.level.levelgen.feature.Feature; import net.minecraft.world.level.levelgen.feature.FeaturePlaceContext; import net.minecraft.world.level.levelgen.feature.configurations.NoneFeatureConfiguration; import twilightforest.loot.TFLootTables; import twilightforest.util.FeatureLogic; import twilightforest.util.FeatureUtil; public class FoundationFeature extends Feature<NoneFeatureConfiguration> { public FoundationFeature(Codec<NoneFeatureConfiguration> configIn) { super(configIn); } @Override public boolean place(FeaturePlaceContext<NoneFeatureConfiguration> ctx) { WorldGenLevel world = ctx.level(); BlockPos pos = ctx.origin(); RandomSource rand = ctx.random(); int sx = 5 + rand.nextInt(5); int sz = 5 + rand.nextInt(5); if (!FeatureUtil.isAreaSuitable(world, pos, sx + 1, 4, sz + 1)) { return false; } //okay! for (int cx = 0; cx <= sx; cx++) { for (int cz = 0; cz <= sz; cz++) { if (cx == 0 || cx == sx || cz == 0 || cz == sz) { // stone on the edges int ht = rand.nextInt(4) + 1; for (int cy = 0; cy <= ht; cy++) { world.setBlock(pos.offset(cx, cy - 1, cz), FeatureLogic.randStone(rand, cy + 1), 3); } } else { // destroyed wooden plank floor if (rand.nextInt(3) != 0) { world.setBlock(pos.offset(cx, -1, cz), Blocks.OAK_PLANKS.defaultBlockState(), 3); } } } } //TODO: chimney? // 50% basement chance! if (rand.nextInt(2) == 0) { // clear basement for (int cx = 1; cx < sx; cx++) { for (int cz = 1; cz < sz; cz++) { world.setBlock(pos.offset(cx, -3, cz), Blocks.AIR.defaultBlockState(), 3); world.setBlock(pos.offset(cx, -4, cz), Blocks.AIR.defaultBlockState(), 3); } } // make chest int cx = rand.nextInt(sx - 1) + 1; int cz = rand.nextInt(sz - 1) + 1; TFLootTables.FOUNDATION_BASEMENT.generateChest(world, pos.offset(cx, -4, cz), Direction.NORTH, false); } return true; } }
1
0.87963
1
0.87963
game-dev
MEDIA
0.990075
game-dev
0.730715
1
0.730715
wtfblub/NetspherePirates
7,040
src/Netsphere.Server.Game/Commands/GameRuleCommands.cs
using System; using System.Linq; using System.Threading.Tasks; using BlubLib.Collections.Generic; using Netsphere.Network.Message.GameRule; using Netsphere.Server.Game.Services; namespace Netsphere.Server.Game.Commands { internal class GameRuleCommands : ICommandHandler { [Command( CommandUsage.Player, SecurityLevel.Developer, "Usage: teamscore <team> <score>" )] public async Task<bool> TeamScore(Player plr, string[] args) { if (args.Length != 2) return false; if (plr.Room == null) { this.ReplyError(plr, "You need to be a in a room"); return false; } if (!byte.TryParse(args[0], out var teamId)) return false; if (!uint.TryParse(args[1], out var score)) return false; var team = plr.Room.TeamManager[(TeamId)teamId]; if (team == null) { this.ReplyError(plr, "Invalid team. Valid teams are: " + string.Join(", ", plr.Room.TeamManager.Select(x => (int)x.Key)) ); return false; } team.Score = score; plr.Room.BroadcastBriefing(); return true; } [Command( CommandUsage.Player, SecurityLevel.Developer, "Usage: gamestate <gamestate>" )] public async Task<bool> GameState(Player plr, string[] args) { if (args.Length != 1) return false; if (plr.Room == null) { this.ReplyError(plr, "You need to be a in a room"); return false; } var room = plr.Room; var gameRule = room.GameRule; var stateMachine = gameRule.StateMachine; switch (args[0].ToLower()) { case "start": if (stateMachine.GameState != Netsphere.GameState.Waiting) this.ReplyError(plr, "This state is currently not possible"); if (!stateMachine.StartGame()) { GameRuleBase.CanStartGameHook += CanStartGameHook; stateMachine.StartGame(); GameRuleBase.CanStartGameHook -= CanStartGameHook; bool CanStartGameHook(CanStartGameHookEventArgs e) { if (e.GameRule == room.GameRule) e.Result = true; return true; } } break; case "halftime": if (!plr.Room.GameRule.StateMachine.StartHalfTime()) this.ReplyError(plr, "This state is currently not possible"); break; case "result": if (!plr.Room.GameRule.StateMachine.StartResult()) this.ReplyError(plr, "This state is currently not possible"); break; default: this.ReplyError( plr, "Invalid state. Valid values are: start, halftime, result" ); return false; } return true; } [Command( CommandUsage.Player, SecurityLevel.Developer, "Usage: briefing" )] public async Task<bool> Briefing(Player plr, string[] args) { if (plr.Room == null) { this.ReplyError(plr, "You need to be a in a room"); return false; } plr.Room.BroadcastBriefing(); return true; } [Command( CommandUsage.Player, SecurityLevel.Developer, "Usage: changehp <value> [target nickname or id]" )] public async Task<bool> ChangeHP(Player plr, string[] args) { if (args.Length < 1) return false; if (plr.Room == null) { this.ReplyError(plr, "You need to be in a room"); return true; } if (!float.TryParse(args[0], out var value)) return false; var target = plr; if (args.Length > 1) { if (ulong.TryParse(args[1], out var id)) { target = plr.Room.Players.GetValueOrDefault(id); if (target == null) { this.ReplyError(plr, "Target not found in current room"); return true; } } else { target = plr.Room.Players.Values.FirstOrDefault(x => x.Account.Nickname.Equals(args[1], StringComparison.OrdinalIgnoreCase)); if (target == null) { this.ReplyError(plr, "Target not found in current room"); return true; } } } target.Session.Send(new SChangeHPAckMessage(value)); return true; } [Command( CommandUsage.Player, SecurityLevel.Developer, "Usage: changesp <value> [target nickname or id]" )] public async Task<bool> ChangeSP(Player plr, string[] args) { if (args.Length < 1) return false; if (plr.Room == null) { this.ReplyError(plr, "You need to be in a room"); return true; } if (!float.TryParse(args[0], out var value)) return false; var target = plr; if (args.Length > 1) { if (ulong.TryParse(args[1], out var id)) { target = plr.Room.Players.GetValueOrDefault(id); if (target == null) { this.ReplyError(plr, "Target not found in current room"); return true; } } else { target = plr.Room.Players.Values.FirstOrDefault(x => x.Account.Nickname.Equals(args[1], StringComparison.OrdinalIgnoreCase)); if (target == null) { this.ReplyError(plr, "Target not found in current room"); return true; } } } target.Session.Send(new SChangeMPAckMessage(value)); return true; } } }
1
0.716517
1
0.716517
game-dev
MEDIA
0.603272
game-dev
0.826115
1
0.826115
isledecomp/isle-portable
3,597
LEGO1/lego/legoomni/include/legoanimactor.h
#ifndef LEGOANIMACTOR_H #define LEGOANIMACTOR_H #include "decomp.h" #include "legopathactor.h" class LegoAnim; // SIZE 0x20 struct LegoAnimActorStruct { LegoAnimActorStruct(float p_worldSpeed, LegoAnim* p_AnimTreePtr, LegoROI** p_roiMap, MxU32 p_numROIs); ~LegoAnimActorStruct(); float GetDuration(); // FUNCTION: BETA10 0x1000fb10 float GetWorldSpeed() { return m_worldSpeed; } // FUNCTION: BETA10 0x10012210 LegoAnim* GetAnimTreePtr() { return m_AnimTreePtr; } // FUNCTION: BETA10 0x10012240 LegoROI** GetROIMap() { return m_roiMap; } // TODO: Possibly private float m_worldSpeed; // 0x00 LegoAnim* m_AnimTreePtr; // 0x04 LegoROI** m_roiMap; // 0x08 MxU32 m_numROIs; // 0x0c vector<undefined*> m_unk0x10; // 0x10 }; // VTABLE: LEGO1 0x100d5440 LegoPathActor // VTABLE: LEGO1 0x100d5510 LegoAnimActor // VTABLE: BETA10 0x101b81d8 LegoPathActor // VTABLE: BETA10 0x101b82c8 LegoAnimActor // SIZE 0x174 class LegoAnimActor : public virtual LegoPathActor { public: // FUNCTION: BETA10 0x1000f6c0 LegoAnimActor() { m_curAnim = -1; } ~LegoAnimActor() override; void ParseAction(char* p_extra) override; // vtable+0x20 void SetWorldSpeed(MxFloat p_worldSpeed) override; // vtable+0x30 void Animate(float p_time) override; // vtable+0x70 void VTable0x74(Matrix4& p_transform) override; // vtable+0x74 virtual MxResult GetTimeInCycle(float& p_timeInCycle); virtual MxResult AnimateWithTransform(float p_time, Matrix4& p_transform); virtual MxResult CreateAnimActorStruct( LegoAnim* p_AnimTreePtr, float p_worldSpeed, LegoROI** p_roiMap, MxU32 p_numROIs ); virtual void ClearMaps(); // FUNCTION: LEGO1 0x1000fba0 // FUNCTION: BETA10 0x10012400 const char* ClassName() const override // vtable+0x0c { // STRING: LEGO1 0x100f057c return "LegoAnimActor"; } // FUNCTION: LEGO1 0x1000fbc0 // FUNCTION: BETA10 0x10012440 MxBool IsA(const char* p_name) const override // vtable+0x10 { return !strcmp(p_name, LegoAnimActor::ClassName()) || LegoPathActor::IsA(p_name); } // SYNTHETIC: LEGO1 0x1000fb60 // LegoAnimActor::`scalar deleting destructor' protected: vector<LegoAnimActorStruct*> m_animMaps; // 0x08 MxS16 m_curAnim; // 0x18 }; // clang-format off // GLOBAL: LEGO1 0x100d5438 // LegoAnimActor::`vbtable' // TEMPLATE: LEGO1 0x1000da20 // vector<LegoAnimActorStruct *,allocator<LegoAnimActorStruct *> >::~vector<LegoAnimActorStruct *,allocator<LegoAnimActorStruct *> > // TEMPLATE: LEGO1 0x1000da60 // Vector<LegoAnimActorStruct *>::~Vector<LegoAnimActorStruct *> // SYNTHETIC: LEGO1 0x10012b90 // SYNTHETIC: BETA10 0x1000fad0 // LegoAnimActor::`vbase destructor' // TEMPLATE: LEGO1 0x1001c010 // vector<unsigned char *,allocator<unsigned char *> >::~vector<unsigned char *,allocator<unsigned char *> > // TEMPLATE: LEGO1 0x1001c050 // Vector<unsigned char *>::~Vector<unsigned char *> // TEMPLATE: LEGO1 0x1001c7c0 // TEMPLATE: BETA10 0x1000fb40 // vector<LegoAnimActorStruct *,allocator<LegoAnimActorStruct *> >::size // TEMPLATE: BETA10 0x1000fb90 // vector<LegoAnimActorStruct *,allocator<LegoAnimActorStruct *> >::operator[] // TEMPLATE: LEGO1 0x1001c7e0 // vector<LegoAnimActorStruct *,allocator<LegoAnimActorStruct *> >::_Destroy // TEMPLATE: BETA10 0x1000fbc0 // vector<LegoAnimActorStruct *,allocator<LegoAnimActorStruct *> >::begin // TEMPLATE: LEGO1 0x1001c9e0 // uninitialized_fill_n // TEMPLATE: LEGO1 0x1001ca10 // ?uninitialized_copy@@YAPAPAULegoAnimActorStruct@@PAPAU1@00@Z // clang-format on #endif // LEGOANIMACTOR_H
1
0.722231
1
0.722231
game-dev
MEDIA
0.461294
game-dev
0.64798
1
0.64798
catboost/catboost
1,563
catboost/libs/train_interface/catboost_wrapper.h
#pragma once #include "catboost_api.h" #include <vector> #include <string> #include <cstddef> struct TSymmetricTree { std::vector<int> Features; std::vector<float> Conditions; std::vector<float> Leaves; std::vector<float> Weights; int OutputDim() const { return Weights.size() ? Leaves.size() / Weights.size() : 0; } }; struct TEnsemble { std::vector<TSymmetricTree> Trees; }; inline TEnsemble Train(const TDataSet& learn, const TDataSet& test, const std::string& paramsJson) { ResultHandle handle; TrainCatBoost(&learn, &test, paramsJson.data(), &handle); if (!handle) { throw std::exception(); } TEnsemble ensemble; ensemble.Trees.resize(TreesCount(handle)); int outputDim = OutputDim(handle); int numTrees = ensemble.Trees.size(); for (int tree = 0; tree < numTrees; ++tree) { auto depth = TreeDepth(handle, tree); auto& currentTree = ensemble.Trees[tree]; currentTree.Features.resize(depth); currentTree.Conditions.resize(depth); currentTree.Leaves.resize(outputDim * (1 << depth)); currentTree.Weights.resize((1 << depth)); CopyTree(handle, tree, currentTree.Features.data(), currentTree.Conditions.data(), currentTree.Leaves.data(), currentTree.Weights.data() ); } FreeHandle(&handle); return ensemble; }
1
0.832487
1
0.832487
game-dev
MEDIA
0.337348
game-dev
0.85122
1
0.85122
Rolisteam/rolisteam
4,563
src/libraries/charactersheet/src/charactersheet/charactersheetitem.cpp
/*************************************************************************** * Copyright (C) 2014 by Renaud Guezennec * * https://rolisteam.org/ * * * * This file is part of rcse * * * * rcse 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. * * * * rcse 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. * ***************************************************************************/ #include "charactersheet/charactersheetitem.h" #include <QDebug> ////////////////////////////// // Item ///////////////////////////// TreeSheetItem::TreeSheetItem(TreeSheetItem::TreeItemType type, QObject* parent) : QObject(parent), m_itemType(type), m_parent(nullptr) { connect(this, &TreeSheetItem::idChanged, this, [this] { emit characterSheetItemChanged(this); }); } bool TreeSheetItem::hasChildren() { return false; } int TreeSheetItem::childrenCount() const { return 0; } TreeSheetItem* TreeSheetItem::childFromId(const QString& id) const { return nullptr; } void TreeSheetItem::changeKeyChild(const QString& oldkey, const QString& newKey, TreeSheetItem* child) { Q_UNUSED(oldkey); Q_UNUSED(newKey); Q_UNUSED(child); } TreeSheetItem::TreeItemType TreeSheetItem::itemType() const { return m_itemType; } bool TreeSheetItem::removeChild(TreeSheetItem*) { return false; } bool TreeSheetItem::deleteChild(TreeSheetItem*) { return false; } int TreeSheetItem::rowInParent() { if(nullptr == m_parent) return -1; return m_parent->indexOfChild(this); } bool TreeSheetItem::mayHaveChildren() const { switch(m_itemType) { case TreeItemType::SectionItem: case TreeItemType::TableItem: return true; break; case TreeItemType::FieldItem: case TreeItemType::CellValue: case TreeItemType::SliderItem: return false; break; } return false; } TreeSheetItem* TreeSheetItem::childAt(int) const { return nullptr; } QString TreeSheetItem::id() const { return m_id; } void TreeSheetItem::setFormula(const QString& formula) { Q_UNUSED(formula) } QString TreeSheetItem::path() const { QString path; if(nullptr != m_parent) { path= m_parent->path(); if(!path.isEmpty()) { path.append('.'); } } return path.append(m_id); } void TreeSheetItem::appendChild(TreeSheetItem*) { // nothing } TreeSheetItem* TreeSheetItem::parentTreeItem() const { return m_parent; } void TreeSheetItem::setParent(TreeSheetItem* parent) { m_parent= parent; } int TreeSheetItem::indexOfChild(TreeSheetItem* itm) { Q_UNUSED(itm); return 0; } void TreeSheetItem::setId(const QString& newPath) { if(m_id == newPath) return; auto old= m_id; m_id= newPath; emit idChanged(old, m_id); } bool TreeSheetItem::readOnly() const { return m_readOnly; } void TreeSheetItem::setReadOnly(bool newReadOnly) { if(m_readOnly == newReadOnly) return; m_readOnly= newReadOnly; emit readOnlyChanged(); } bool TreeSheetItem::updateFromNetwork() const { return m_updateFromNetwork; } void TreeSheetItem::setUpdateFromNetwork(bool newUpdateFromNetwork) { if(m_updateFromNetwork == newUpdateFromNetwork) return; m_updateFromNetwork= newUpdateFromNetwork; emit updateFromNetworkChanged(); }
1
0.953054
1
0.953054
game-dev
MEDIA
0.166363
game-dev
0.959814
1
0.959814
francisconeves97/jxscout
2,123
pkg/ast-analyzer/tree-analyzers/local-storage.ts
import { Node, MemberExpression } from "acorn"; import { Analyzer, AnalyzerMatch, AnalyzerParams } from "../types"; import { Visitor } from "../walker"; export const LOCAL_STORAGE_ANALYZER_NAME = "local-storage"; const localStorageAnalyzerBuilder = ( args: AnalyzerParams, matchesReturn: AnalyzerMatch[] ): Visitor => { return { CallExpression(node, ancestors) { if (!node.loc) { return; } // Check for localStorage method calls const isLocalStorageCall = (node: Node) => { if (node.type !== "MemberExpression") return false; const memberNode = node as MemberExpression; // Check for direct localStorage usage if ( memberNode.object.type === "Identifier" && memberNode.object.name === "localStorage" && memberNode.property.type === "Identifier" && ["getItem", "setItem"].includes(memberNode.property.name) ) { return true; } // Check for window.localStorage usage if ( memberNode.object.type === "MemberExpression" && memberNode.object.object.type === "Identifier" && memberNode.object.object.name === "window" && memberNode.object.property.type === "Identifier" && memberNode.object.property.name === "localStorage" && memberNode.property.type === "Identifier" && ["getItem", "setItem"].includes(memberNode.property.name) ) { return true; } return false; }; if (isLocalStorageCall(node.callee)) { const callee = node.callee as MemberExpression; const match: AnalyzerMatch = { filePath: args.filePath, analyzerName: LOCAL_STORAGE_ANALYZER_NAME, value: args.source.slice(node.start, node.end), start: node.loc.start, end: node.loc.end, tags: { "local-storage": true, [`property-${(callee.property as any).name}`]: true, }, }; matchesReturn.push(match); } }, }; }; export { localStorageAnalyzerBuilder };
1
0.880356
1
0.880356
game-dev
MEDIA
0.589683
game-dev
0.961028
1
0.961028
ReikaKalseki/ChromatiCraft
8,815
Items/Tools/ItemKillAuraGun.java
/******************************************************************************* * @author Reika Kalseki * * Copyright 2017 * * All rights reserved. * Distribution of the software in any form is only allowed with * explicit, prior permission from the owner. ******************************************************************************/ package Reika.ChromatiCraft.Items.Tools; import java.util.List; import net.minecraft.client.Minecraft; import net.minecraft.client.particle.EntityFX; import net.minecraft.enchantment.Enchantment; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Items; import net.minecraft.item.EnumAction; import net.minecraft.item.ItemStack; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.DamageSource; import net.minecraft.util.MathHelper; import net.minecraft.util.Vec3; import net.minecraft.world.World; import Reika.ChromatiCraft.Base.ItemProgressGatedTool; import Reika.ChromatiCraft.Registry.ChromaEnchants; import Reika.ChromatiCraft.Registry.ChromaIcons; import Reika.ChromatiCraft.Registry.ChromaSounds; import Reika.ChromatiCraft.Render.Particle.EntityCCBlurFX; import Reika.ChromatiCraft.Render.Particle.EntityCCFloatingSeedsFX; import Reika.DragonAPI.Instantiable.Effects.EntityFloatingSeedsFX; import Reika.DragonAPI.Instantiable.ParticleController.CollectingPositionController; import Reika.DragonAPI.Interfaces.PositionController; import Reika.DragonAPI.Libraries.ReikaAABBHelper; import Reika.DragonAPI.Libraries.ReikaEnchantmentHelper; import Reika.DragonAPI.Libraries.ReikaEntityHelper; import Reika.DragonAPI.Libraries.Java.ReikaRandomHelper; import Reika.DragonAPI.Libraries.MathSci.ReikaMathLibrary; import Reika.DragonAPI.Libraries.MathSci.ReikaPhysicsHelper; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; public class ItemKillAuraGun extends ItemProgressGatedTool { public static final int CHARGE_TIME = 100; public static final int BASE_DAMAGE = 12; public static final int MAX_DAMAGE = 18; public static final int RANGE = 12; public static final float RANGE_FALLOFF = BASE_DAMAGE/2F/RANGE; public static final float ANGLE_FALLOFF = BASE_DAMAGE*0.875F/180F; public static final float CHARGE_FALLOFF = BASE_DAMAGE/(float)CHARGE_TIME; private static int useTick; private static int useTickUnbounded; public ItemKillAuraGun(int index) { super(index, UseResult.PUNISH); } private static boolean fire(ItemStack is, EntityPlayer ep, int power) { power = power+1; //since never reaches 100 AxisAlignedBB box = ReikaAABBHelper.getEntityCenteredAABB(ep, RANGE); List<EntityLivingBase> li = ep.worldObj.getEntitiesWithinAABB(EntityLivingBase.class, box); for (Entity e : li) { if (e != ep) { float dmg = getWallAttackDamage(is, ep, e, power); if (dmg > 0) { e.attackEntityFrom(new ReikaEntityHelper.WrappedDamageSource(DamageSource.magic, ep), dmg); } } } ChromaSounds.KILLAURA.playSound(ep, 1, 0.4F+0.6F*power/CHARGE_TIME); if (ep.worldObj.isRemote) { doFireParticles(ep, power); } return false; } private static float getFalloffFactor(ItemStack is) { return 1-ReikaEnchantmentHelper.getEnchantmentLevel(ChromaEnchants.WEAPONAOE.getEnchantment(), is)/10F; } private static float getRawDamage(ItemStack is) { float f = (MAX_DAMAGE-BASE_DAMAGE)/10F; return BASE_DAMAGE+ReikaEnchantmentHelper.getEnchantmentLevel(Enchantment.power, is)*f; } @SideOnly(Side.CLIENT) private static void doFireParticles(EntityPlayer ep, int power) { int n = (128+itemRand.nextInt(128))*power/CHARGE_TIME; Vec3 vec = ep.getLookVec(); double r = 0.5; double lx = ep.posX+(vec.xCoord)*r; double ly = ep.posY+(vec.yCoord)*r; double lz = ep.posZ+(vec.zCoord)*r; for (int i = 0; i < n; i++) { double phi = itemRand.nextDouble()*360; double theta = itemRand.nextDouble()*360; boolean flag = false; int d = itemRand.nextInt(4); if (d > 0) { double b = d%2 == 0 ? 10 : 5; phi = ReikaRandomHelper.getRandomPlusMinus(90+ep.rotationYawHead, b); theta = ReikaRandomHelper.getRandomPlusMinus(-ep.rotationPitch, b); flag = true; } float s = (float)ReikaRandomHelper.getRandomPlusMinus(2D, 1D); if (!flag) s *= 2; ChromaIcons ico = ChromaIcons.FLARE; switch(itemRand.nextInt(3)) { case 0: ico = ChromaIcons.CENTER; break; case 1: ico = ChromaIcons.NODE2; break; } EntityFloatingSeedsFX fx = (EntityFloatingSeedsFX)new EntityCCFloatingSeedsFX(ep.worldObj, lx, ly, lz, phi, theta, ico).setColor(0xffffff).setNoSlowdown().setScale(s); fx.particleVelocity *= 2*ReikaRandomHelper.getRandomPlusMinus(4D, 1.5D); fx.freedom *= ReikaRandomHelper.getRandomPlusMinus(1.5D, 0.5D); fx.angleVelocity *= ReikaRandomHelper.getRandomPlusMinus(1D, 0.75D); Minecraft.getMinecraft().effectRenderer.addEffect(fx); } } private static float getWallAttackDamage(ItemStack is, EntityPlayer ep, Entity e, int power) { double d = e.getDistanceToEntity(ep); if (d <= RANGE) { double[] angs = ReikaPhysicsHelper.cartesianToPolar(e.posX-ep.posX, e.posY-ep.posY, e.posZ-ep.posZ); angs[1] = angs[1]-90-ep.rotationPitch; angs[2] = 180-angs[2]-ep.rotationYawHead; angs[1] = Math.abs(MathHelper.wrapAngleTo180_double(angs[1])); angs[2] = Math.abs(MathHelper.wrapAngleTo180_double(angs[2])); //ReikaJavaLibrary.pConsole(ep.rotationYawHead+":"+ep.rotationPitch+":"+Arrays.toString(angs), Side.SERVER); double da = ReikaMathLibrary.py3d(angs[2], 0, angs[1]); //ReikaJavaLibrary.pConsole(power+":"+((CHARGE_TIME-power)*CHARGE_FALLOFF)); float f = getFalloffFactor(is); double dmg = getRawDamage(is)-RANGE_FALLOFF*f*Math.max(0, (d-2))-ANGLE_FALLOFF*f*da-(CHARGE_TIME-power)*CHARGE_FALLOFF; return (float)Math.max(1F, dmg); } else { return 0; } } @Override public void onPlayerStoppedUsing(ItemStack is, World world, EntityPlayer ep, int count) { count = MathHelper.clamp_int(this.getMaxItemUseDuration(is)-count, 0, CHARGE_TIME); //ReikaChatHelper.write(power+" -> "+charge); if (count > 10) this.fire(is, ep, count); useTick = 0; useTickUnbounded = 0; ep.setItemInUse(null, 0); } @Override public ItemStack onEaten(ItemStack is, World world, EntityPlayer ep) { return is; } @Override public int getMaxItemUseDuration(ItemStack is) { return 72000;//CHARGE_TIME; } @Override public EnumAction getItemUseAction(ItemStack is) { return EnumAction.bow; } @Override public ItemStack onItemRightClick(ItemStack is, World world, EntityPlayer ep) { if (!this.handleUseAllowance(ep)) ep.setItemInUse(is, this.getMaxItemUseDuration(is)); return is; } @Override public void onUsingTick(ItemStack is, EntityPlayer ep, int count) { //ReikaJavaLibrary.pConsole(count); count = this.getMaxItemUseDuration(is)-count; useTickUnbounded = count; count = MathHelper.clamp_int(count, 0, CHARGE_TIME); if (ep.worldObj.isRemote) { this.doChargingParticles(ep, count); useTick = count; } if (!ep.worldObj.isRemote) ChromaSounds.KILLAURA_CHARGE.playSound(ep, 0.25F+2F*count/CHARGE_TIME, MathHelper.clamp_float(0.5F, 2F*count/CHARGE_TIME, 2F)); /* if (count >= CHARGE_TIME-1) { useTick = 0; this.fire(ep, count); ep.setItemInUse(null, 0); } */ } @SideOnly(Side.CLIENT) public static int getUseTick() { return useTick; } @SideOnly(Side.CLIENT) public static int getUnboundedUseTick() { return useTickUnbounded; } @SideOnly(Side.CLIENT) private void doChargingParticles(EntityPlayer ep, int power) { double f = Math.pow(0.125F+2F*power/CHARGE_TIME, 2); int n = (int)f; if (ReikaRandomHelper.doWithChance(f-n)) n++; Vec3 vec = ep.getLookVec(); double r = 0.5; double lx = ep.posX+(vec.xCoord)*r; double ly = ep.posY+(vec.yCoord)*r; double lz = ep.posZ+(vec.zCoord)*r; for (int i = 0; i < n; i++) { double dx = ReikaRandomHelper.getRandomPlusMinus(0, 0.25); double dy = ReikaRandomHelper.getRandomPlusMinus(0, 0.25); double dz = ReikaRandomHelper.getRandomPlusMinus(0, 0.25); double px = lx+dx; double py = ly+dy; double pz = lz+dz; double v = ReikaRandomHelper.getRandomPlusMinus(0.0625, 0.03125); double vx = -v*dx; double vy = -v*dx; double vz = -v*dx; int t = 6+itemRand.nextInt(5); PositionController p = new CollectingPositionController(px, py, pz, lx, ly, lz, t); EntityFX fx = new EntityCCBlurFX(ep.worldObj, px, py, pz).setIcon(ChromaIcons.FLARE).setLife(t).setScale(0.5F).setPositionController(p); Minecraft.getMinecraft().effectRenderer.addEffect(fx); } } @Override public int getItemEnchantability(ItemStack is) { return Items.stone_pickaxe.getItemEnchantability(is); } }
1
0.932955
1
0.932955
game-dev
MEDIA
0.960345
game-dev
0.977699
1
0.977699
Mimi8298/Supercell.Magic
26,559
Supercell.Magic.Logic/GameObject/Component/LogicHeroBaseComponent.cs
namespace Supercell.Magic.Logic.GameObject.Component { using Supercell.Magic.Logic.Avatar; using Supercell.Magic.Logic.Data; using Supercell.Magic.Logic.Level; using Supercell.Magic.Logic.Time; using Supercell.Magic.Logic.Util; using Supercell.Magic.Titan.Debug; using Supercell.Magic.Titan.Json; using Supercell.Magic.Titan.Math; using Supercell.Magic.Titan.Util; public sealed class LogicHeroBaseComponent : LogicComponent { public const int PATROL_PATHS = 8; private LogicTimer m_timer; private LogicArrayList<LogicVector2> m_patrolPath; private readonly LogicHeroData m_hero; private int m_healthTime; private int m_upgLevel; private bool m_sharedHeroCombatData; public LogicHeroBaseComponent(LogicGameObject gameObject, LogicHeroData data) : base(gameObject) { this.m_hero = data; } public override void Destruct() { base.Destruct(); if (this.m_timer != null) { this.m_timer.Destruct(); this.m_timer = null; } } public override void Tick() { this.m_healthTime += 64; int regenTime = 1000; if (this.m_parent.GetRemainingBoostTime() > 0 && !this.m_parent.IsBoostPaused()) { regenTime /= LogicDataTables.GetGlobals().GetHeroRestBoostMultiplier(); } if (this.m_parent.GetLevel().GetRemainingClockTowerBoostTime() > 0) { LogicGameObjectData data = this.m_parent.GetData(); if (data.GetDataType() == LogicDataType.BUILDING && data.GetVillageType() == 1) { regenTime /= LogicDataTables.GetGlobals().GetClockTowerBoostMultiplier(); if (this.m_timer != null) { this.m_timer.SetFastForward(this.m_timer.GetFastForward() + 4 * LogicDataTables.GetGlobals().GetClockTowerBoostMultiplier() - 4); } } } if (this.m_healthTime > regenTime) { if (this.m_parent.GetLevel().GetPlayerAvatar().FastForwardHeroHealth(this.m_hero, 1) && this.GetParentListener() != null) { // LOAD EFFECT. } this.m_healthTime -= regenTime; } if (this.m_timer != null) { if (this.m_timer.GetRemainingSeconds(this.m_parent.GetLevel().GetLogicTime()) == 0) { this.FinishUpgrading(true); } } } public override LogicComponentType GetComponentType() { return LogicComponentType.HERO_BASE; } public void FinishUpgrading(bool tick) { if (this.m_timer != null) { LogicAvatar homeOwnerAvatar = this.m_parent.GetLevel().GetHomeOwnerAvatar(); if (homeOwnerAvatar.GetUnitUpgradeLevel(this.m_hero) < this.m_upgLevel || this.m_upgLevel == 0) { homeOwnerAvatar.CommodityCountChangeHelper(1, this.m_hero, 1); } this.m_parent.GetLevel().GetWorkerManagerAt(this.m_parent.GetData().GetVillageType()).DeallocateWorker(this.m_parent); homeOwnerAvatar.SetHeroState(this.m_hero, 3); homeOwnerAvatar.GetChangeListener().CommodityCountChanged(2, this.m_hero, 3); this.SetFullHealth(); this.m_timer.Destruct(); this.m_timer = null; } else { Debugger.Warning("LogicHeroBaseComponent::finishUpgrading called and m_pHero is NULL"); } } public bool IsUpgrading() { return this.m_timer != null; } public void SetFullHealth() { LogicAvatar homeOwnerAvatar = this.m_parent.GetLevel().GetHomeOwnerAvatar(); homeOwnerAvatar.SetHeroHealth(this.m_hero, 0); homeOwnerAvatar.GetChangeListener().CommodityCountChanged(0, this.m_hero, 0); } public int GetRemainingUpgradeSeconds() { if (this.m_timer != null) { return this.m_timer.GetRemainingSeconds(this.m_parent.GetLevel().GetLogicTime()); } return 0; } public int GetRemainingMS() { if (this.m_timer != null) { return this.m_timer.GetRemainingMS(this.m_parent.GetLevel().GetLogicTime()); } return 0; } public int GetTotalSeconds() { if (this.m_timer != null) { return this.m_hero.GetUpgradeTime(this.m_parent.GetLevel().GetHomeOwnerAvatar().GetUnitUpgradeLevel(this.m_hero)); } return 0; } public LogicHeroData GetHeroData() { return this.m_hero; } public void SetSharedHeroCombatData(bool value) { this.m_sharedHeroCombatData = value; } public override void Save(LogicJSONObject root, int villageType) { if (this.m_timer != null && this.m_hero != null) { LogicJSONObject jsonObject = new LogicJSONObject(); jsonObject.Put("level", new LogicJSONNumber(this.m_upgLevel)); jsonObject.Put("t", new LogicJSONNumber(this.m_timer.GetRemainingSeconds(this.m_parent.GetLevel().GetLogicTime()))); if (this.m_timer.GetEndTimestamp() != -1) { jsonObject.Put("t_end", new LogicJSONNumber(this.m_timer.GetEndTimestamp())); } if (this.m_timer.GetFastForward() > 0) { jsonObject.Put("t_ff", new LogicJSONNumber(this.m_timer.GetFastForward())); } root.Put("hero_upg", jsonObject); } } public override void SaveToSnapshot(LogicJSONObject root, int layoutId) { if (this.m_timer != null && this.m_hero != null) { LogicJSONObject jsonObject = new LogicJSONObject(); jsonObject.Put("level", new LogicJSONNumber(this.m_upgLevel)); jsonObject.Put("t", new LogicJSONNumber(this.m_timer.GetRemainingSeconds(this.m_parent.GetLevel().GetLogicTime()))); root.Put("hero_upg", jsonObject); } } public override void Load(LogicJSONObject root) { if (this.m_timer != null) { this.m_timer.Destruct(); this.m_timer = null; } LogicJSONObject jsonObject = root.GetJSONObject("hero_upg"); if (jsonObject != null) { LogicJSONNumber levelObject = jsonObject.GetJSONNumber("level"); LogicJSONNumber timerObject = jsonObject.GetJSONNumber("t"); LogicJSONNumber timerEndObject = jsonObject.GetJSONNumber("t_end"); LogicJSONNumber timerFastForwardObject = jsonObject.GetJSONNumber("t_ff"); if (levelObject != null) { this.m_upgLevel = levelObject.GetIntValue(); } if (timerObject != null) { this.m_timer = new LogicTimer(); this.m_timer.StartTimer(timerObject.GetIntValue(), this.m_parent.GetLevel().GetLogicTime(), false, -1); if (timerEndObject != null) { this.m_timer.SetEndTimestamp(timerEndObject.GetIntValue()); } if (timerFastForwardObject != null) { this.m_timer.SetFastForward(timerFastForwardObject.GetIntValue()); } this.m_parent.GetLevel().GetWorkerManagerAt(this.m_parent.GetVillageType()).AllocateWorker(this.m_parent); } } } public override void LoadFromSnapshot(LogicJSONObject root) { if (this.m_timer != null) { this.m_timer.Destruct(); this.m_timer = null; } LogicJSONObject jsonObject = root.GetJSONObject("hero_upg"); if (jsonObject != null) { LogicJSONNumber levelObject = jsonObject.GetJSONNumber("level"); if (levelObject != null) { this.m_upgLevel = levelObject.GetIntValue(); } } } public override void LoadingFinished() { if (this.m_parent.GetLevel().IsInCombatState()) { if (this.m_parent.GetVillageType() == this.m_parent.GetLevel().GetVillageType()) { if (this.m_parent.GetLevel().GetVillageType() == this.m_parent.GetVillageType()) { this.m_patrolPath = this.CreatePatrolPath(); } } } LogicAvatar homeOwnerAvatar = this.m_parent.GetLevel().GetHomeOwnerAvatar(); LogicBuilding building = (LogicBuilding) this.m_parent; if (!building.IsLocked() && homeOwnerAvatar.GetHeroState(this.m_hero) == 0) { homeOwnerAvatar.SetHeroState(this.m_hero, 3); homeOwnerAvatar.GetChangeListener().CommodityCountChanged(2, this.m_hero, 3); } if (this.m_timer != null) { int remainingSecs = this.m_timer.GetRemainingSeconds(this.m_parent.GetLevel().GetLogicTime()); int totalSecs = this.GetTotalSeconds(); if (LogicDataTables.GetGlobals().ClampUpgradeTimes()) { if (remainingSecs > totalSecs) { this.m_timer.StartTimer(totalSecs, this.m_parent.GetLevel().GetLogicTime(), true, this.m_parent.GetLevel().GetHomeOwnerAvatarChangeListener().GetCurrentTimestamp()); } } else { this.m_timer.StartTimer(LogicMath.Min(remainingSecs, totalSecs), this.m_parent.GetLevel().GetLogicTime(), false, -1); } if (!building.IsLocked() && homeOwnerAvatar.GetHeroState(this.m_hero) != 1) { homeOwnerAvatar.SetHeroState(this.m_hero, 1); homeOwnerAvatar.GetChangeListener().CommodityCountChanged(2, this.m_hero, 1); } } else { if (!building.IsLocked() && homeOwnerAvatar.GetHeroState(this.m_hero) == 1) { homeOwnerAvatar.SetHeroState(this.m_hero, 3); homeOwnerAvatar.GetChangeListener().CommodityCountChanged(2, this.m_hero, 3); } } if (this.m_hero.HasNoDefence() && !this.m_parent.GetLevel().IsInCombatState() && homeOwnerAvatar.GetHeroState(this.m_hero) == 3) { homeOwnerAvatar.SetHeroState(this.m_hero, 2); homeOwnerAvatar.GetChangeListener().CommodityCountChanged(2, this.m_hero, 2); } if (homeOwnerAvatar.GetHeroState(this.m_hero) == 3) { if (this.m_parent.GetLevel().IsInCombatState()) { if (!this.m_sharedHeroCombatData && !this.m_hero.HasNoDefence()) { if (this.m_parent.GetVillageType() == this.m_parent.GetLevel().GetVillageType()) { this.AddDefendingHero(); } } } } int heroHealth = homeOwnerAvatar.GetHeroHealth(this.m_hero); int fullRegenerationTime = this.m_hero.GetFullRegenerationTimeSec(homeOwnerAvatar.GetUnitUpgradeLevel(this.m_hero)); if (fullRegenerationTime < heroHealth) { homeOwnerAvatar.GetChangeListener().CommodityCountChanged(0, this.m_hero, fullRegenerationTime); homeOwnerAvatar.SetHeroHealth(this.m_hero, fullRegenerationTime); } } public override void FastForwardTime(int time) { int heroHealthTime = time; int constructionBoostTime = 0; int remainingBoostTime = this.m_parent.GetRemainingBoostTime(); if (remainingBoostTime > 0) { if (!this.m_parent.IsBoostPaused()) { heroHealthTime += LogicMath.Min(remainingBoostTime, time) * (LogicDataTables.GetGlobals().GetHeroRestBoostMultiplier() - 1); } } int clockTowerBoostTime = this.m_parent.GetLevel().GetUpdatedClockTowerBoostTime(); if (clockTowerBoostTime > 0 && this.m_parent.GetLevel().IsClockTowerBoostPaused()) { LogicGameObjectData data = this.m_parent.GetData(); if (data.GetDataType() == LogicDataType.BUILDING && data.GetVillageType() == 1) { int boost = LogicMath.Min(clockTowerBoostTime, time) * (LogicDataTables.GetGlobals().GetClockTowerBoostMultiplier() - 1); heroHealthTime += boost; constructionBoostTime += boost; } } this.m_parent.GetLevel().GetHomeOwnerAvatar().FastForwardHeroHealth(this.m_hero, heroHealthTime); if (this.m_timer != null) { if (this.m_timer.GetEndTimestamp() == -1) { this.m_timer.StartTimer(this.m_timer.GetRemainingSeconds(this.m_parent.GetLevel().GetLogicTime()) - time, this.m_parent.GetLevel().GetLogicTime(), false, -1); } else { this.m_timer.AdjustEndSubtick(this.m_parent.GetLevel()); } if (constructionBoostTime > 0) { this.m_timer.SetFastForward(this.m_timer.GetFastForward() + 60 * constructionBoostTime); } } } public LogicArrayList<LogicVector2> GetPatrolPath() { return this.m_patrolPath; } public LogicArrayList<LogicVector2> CreatePatrolPath() { int parentWidth = this.m_parent.GetWidthInTiles() << 8; int parentHeight = this.m_parent.GetHeightInTiles() << 8; int patrolRadius = this.m_hero.GetPatrolRadius(); if (patrolRadius * patrolRadius >= parentWidth * parentWidth + parentHeight * parentHeight) { LogicVector2 tmp1 = new LogicVector2(); LogicVector2 tmp2 = new LogicVector2(); LogicVector2 tmp3 = new LogicVector2(); LogicVector2 tmp4 = new LogicVector2(); int parentMidX = this.m_parent.GetMidX(); int parentMidY = this.m_parent.GetMidY(); tmp2.Set(parentMidX, parentMidY); LogicArrayList<LogicVector2> wayPoints = new LogicArrayList<LogicVector2>(LogicHeroBaseComponent.PATROL_PATHS); for (int i = 0, j = 22; i < LogicHeroBaseComponent.PATROL_PATHS; i++, j += 45) { tmp1.Set(parentMidX + LogicMath.Cos(j, patrolRadius), parentMidY + LogicMath.Sin(j, patrolRadius)); LogicHeroBaseComponent.FindPoint(this.m_parent.GetLevel().GetTileMap(), tmp3, tmp2, tmp1, tmp4); wayPoints.Add(new LogicVector2(tmp4.m_x, tmp4.m_y)); } tmp1.Destruct(); tmp2.Destruct(); tmp3.Destruct(); tmp4.Destruct(); return wayPoints; } else { int startX = this.m_parent.GetX() + (this.m_parent.GetWidthInTiles() << 9) - 128; int startY = this.m_parent.GetY() + (this.m_parent.GetWidthInTiles() << 9) - 128; int endX = this.m_parent.GetX() + 128; int endY = this.m_parent.GetY() + 128; LogicArrayList<LogicVector2> wayPoints = new LogicArrayList<LogicVector2>(4); wayPoints.Add(new LogicVector2(startX, startY)); wayPoints.Add(new LogicVector2(endX, startY)); wayPoints.Add(new LogicVector2(endX, endY)); wayPoints.Add(new LogicVector2(startX, endY)); return wayPoints; } } public void AddDefendingHero() { LogicAvatar visitorAvatar = this.m_parent.GetLevel().GetVisitorAvatar(); LogicAvatar homeOwnerAvatar = this.m_parent.GetLevel().GetHomeOwnerAvatar(); int randomPatrolPoint = visitorAvatar != null ? (int) (((visitorAvatar.GetResourceCount(LogicDataTables.GetGoldData()) + 10 * this.m_hero.GetGlobalID()) & 0x7FFFFFFFu) % this.m_patrolPath.Size()) : 0; int upgLevel = homeOwnerAvatar.GetUnitUpgradeLevel(this.m_hero); int heroHitpoints = this.m_hero.GetHeroHitpoints(homeOwnerAvatar.GetHeroHealth(this.m_hero), upgLevel); if (this.m_hero.HasEnoughHealthForAttack(heroHitpoints, upgLevel)) { LogicVector2 patrolPoint = this.m_patrolPath[randomPatrolPoint]; LogicCharacter hero = (LogicCharacter) LogicGameObjectFactory.CreateGameObject(this.m_hero, this.m_parent.GetLevel(), this.m_parent.GetVillageType()); hero.GetMovementComponent().SetBaseBuilding((LogicBuilding) this.m_parent); hero.GetHitpointComponent().SetTeam(1); hero.SetUpgradeLevel(upgLevel); hero.GetHitpointComponent().SetHitpoints(heroHitpoints); hero.SetInitialPosition(patrolPoint.m_x, patrolPoint.m_y); this.m_parent.GetGameObjectManager().AddGameObject(hero, -1); hero.GetCombatComponent().SetSearchRadius(this.m_hero.GetMaxSearchRadiusForDefender() / 512); if (LogicDataTables.GetGlobals().EnableDefendingAllianceTroopJump()) { hero.GetMovementComponent().EnableJump(3600000); } } } public bool SpeedUp() { if (this.m_timer != null) { int remainingSecs = this.m_timer.GetRemainingSeconds(this.m_parent.GetLevel().GetLogicTime()); int speedUpCost = LogicGamePlayUtil.GetSpeedUpCost(remainingSecs, 0, this.m_parent.GetVillageType()); LogicAvatar homeOwnerAvatar = this.m_parent.GetLevel().GetHomeOwnerAvatar(); if (homeOwnerAvatar.IsClientAvatar()) { LogicClientAvatar clientAvatar = (LogicClientAvatar) homeOwnerAvatar; if (clientAvatar.HasEnoughDiamonds(speedUpCost, true, this.m_parent.GetLevel())) { clientAvatar.UseDiamonds(speedUpCost); clientAvatar.GetChangeListener().DiamondPurchaseMade(10, this.m_hero.GetGlobalID(), clientAvatar.GetUnitUpgradeLevel(this.m_hero) + 1, speedUpCost, this.m_parent.GetLevel().GetVillageType()); this.FinishUpgrading(true); return true; } } } return false; } public void CancelUpgrade() { if (this.m_timer != null) { LogicAvatar homeOwnerAvatar = this.m_parent.GetLevel().GetHomeOwnerAvatar(); int upgradeLevel = homeOwnerAvatar.GetUnitUpgradeLevel(this.m_hero); int upgradeCost = this.m_hero.GetUpgradeCost(upgradeLevel); LogicResourceData upgradeResourceData = this.m_hero.GetUpgradeResource(upgradeLevel); homeOwnerAvatar.CommodityCountChangeHelper(0, upgradeResourceData, LogicDataTables.GetGlobals().GetHeroUpgradeCancelMultiplier() * upgradeCost / 100); this.m_parent.GetLevel().GetWorkerManagerAt(this.m_parent.GetData().GetVillageType()).DeallocateWorker(this.m_parent); homeOwnerAvatar.SetHeroState(this.m_hero, 3); homeOwnerAvatar.GetChangeListener().CommodityCountChanged(2, this.m_hero, 3); this.m_timer.Destruct(); this.m_timer = null; } else { Debugger.Warning("LogicHeroBaseComponent::cancelUpgrade called even upgrade is not on going!"); } } public bool CanStartUpgrading(bool callListener) { if (this.m_timer == null) { if (!this.IsMaxLevel()) { LogicAvatar homeOwnerAvatar = this.m_parent.GetLevel().GetHomeOwnerAvatar(); int requiredTownHallLevel = this.m_hero.GetRequiredTownHallLevel(homeOwnerAvatar.GetUnitUpgradeLevel(this.m_hero) + 1); int townHallLevel = this.m_parent.GetLevel().GetTownHallLevel(this.m_parent.GetLevel().GetVillageType()); if (townHallLevel >= requiredTownHallLevel) { return true; } } } return false; } public void StartUpgrading() { if (this.CanStartUpgrading(true)) { ((LogicBuilding) this.m_parent).DestructBoost(); if (this.m_timer != null) { this.m_timer.Destruct(); this.m_timer = null; } LogicAvatar homeOwnerAvatar = this.m_parent.GetLevel().GetHomeOwnerAvatar(); this.m_parent.GetLevel().GetWorkerManagerAt(this.m_parent.GetData().GetVillageType()).AllocateWorker(this.m_parent); this.m_timer = new LogicTimer(); this.m_timer.StartTimer(this.GetTotalSeconds(), this.m_parent.GetLevel().GetLogicTime(), true, this.m_parent.GetLevel().GetHomeOwnerAvatarChangeListener().GetCurrentTimestamp()); this.m_upgLevel = homeOwnerAvatar.GetUnitUpgradeLevel(this.m_hero) + 1; homeOwnerAvatar.SetHeroState(this.m_hero, 1); homeOwnerAvatar.GetChangeListener().CommodityCountChanged(2, this.m_hero, 1); } } public bool IsMaxLevel() { return this.m_parent.GetLevel().GetHomeOwnerAvatar().GetUnitUpgradeLevel(this.m_hero) >= this.m_hero.GetUpgradeLevelCount() - 1; } public int GetSpeedUpHealthCost() { LogicAvatar homeOwnerAvatar = this.m_parent.GetLevel().GetHomeOwnerAvatar(); if (homeOwnerAvatar.IsClientAvatar()) { return homeOwnerAvatar.GetHeroHealCost(this.m_hero); } return 0; } public bool SpeedUpHealth() { LogicAvatar homeOwnerAvatar = this.m_parent.GetLevel().GetHomeOwnerAvatar(); if (homeOwnerAvatar.IsClientAvatar()) { LogicClientAvatar clientAvatar = (LogicClientAvatar) homeOwnerAvatar; int speedUpCost = this.GetSpeedUpHealthCost(); if (clientAvatar.HasEnoughDiamonds(speedUpCost, true, this.m_parent.GetLevel())) { clientAvatar.UseDiamonds(speedUpCost); clientAvatar.GetChangeListener().DiamondPurchaseMade(9, this.m_hero.GetGlobalID(), clientAvatar.GetUnitUpgradeLevel(this.m_hero) + 1, speedUpCost, this.m_parent.GetLevel().GetVillageType()); this.SetFullHealth(); return true; } } return false; } public bool SetSleep(bool enabled) { LogicAvatar homeOwnerAvatar = this.m_parent.GetLevel().GetHomeOwnerAvatar(); int state = homeOwnerAvatar.GetHeroState(this.m_hero); if (state != 0) { int newState = enabled ? 2 : 3; if (state != newState) { homeOwnerAvatar.SetHeroState(this.m_hero, newState); homeOwnerAvatar.GetChangeListener().CommodityCountChanged(2, this.m_hero, newState); return true; } } return false; } public bool SetHeroMode(int mode) { LogicAvatar homeOwnerAvatar = this.m_parent.GetLevel().GetHomeOwnerAvatar(); if (homeOwnerAvatar.GetHeroMode(this.m_hero) == mode) { return false; } homeOwnerAvatar.SetHeroMode(this.m_hero, mode); homeOwnerAvatar.GetChangeListener().CommodityCountChanged(3, this.m_hero, mode); return true; } public static bool FindPoint(LogicTileMap tileMap, LogicVector2 pos1, LogicVector2 pos2, LogicVector2 pos3, LogicVector2 pos4) { pos1.Set(pos2.m_x, pos2.m_y); pos1.Substract(pos3); int length = pos1.GetLength(); pos1.m_x = (pos1.m_x << 7) / length; pos1.m_y = (pos1.m_y << 7) / length; pos4.Set(pos3.m_x, pos3.m_y); int radius = LogicMath.Clamp(length / 128, 10, 25); for (int i = 0; i < radius; i++) { if (tileMap.IsPassablePathFinder(pos4.m_x >> 8, pos4.m_y >> 8)) { pos4.m_x = (int) ((pos4.m_x & 0xFFFFFF00) | 128); pos4.m_y = (int) ((pos4.m_y & 0xFFFFFF00) | 128); return true; } pos4.Add(pos1); } return false; } } }
1
0.927626
1
0.927626
game-dev
MEDIA
0.912935
game-dev
0.96593
1
0.96593
fsstudio-team/ZeroSimROSUnity
1,524
Runtime/Scripts/Controllers/ZOLinearActuator.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; using ZO.Physics; namespace ZO.Controllers { public class ZOLinearActuator : MonoBehaviour { public ConfigurableJoint _prismaticJoint; public ZOPIDController _pidController; public enum Axis { X = 0, Y = 1, Z = 2 } public Axis _driveAxis; public float SetPosition { set {_pidController.SetPoint = value; } get { return _pidController.SetPoint; } } // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { } private void FixedUpdate() { Rigidbody slideBody = _prismaticJoint.gameObject.GetComponent<Rigidbody>(); float currentPosition = slideBody.transform.localPosition[(int)_driveAxis]; float force = _pidController.Update(currentPosition, Time.deltaTime); Vector3 globalUpForce = new Vector3(0, 0, 0); globalUpForce[(int)_driveAxis] = force; Vector3 localUpForce = slideBody.transform.worldToLocalMatrix.MultiplyVector(globalUpForce); slideBody.AddRelativeForce(localUpForce, ForceMode.Force); // add equal and opposite force Rigidbody opposingBody = _prismaticJoint.connectedBody; localUpForce = -1.0f * localUpForce; // flip opposingBody.AddRelativeForce(localUpForce, ForceMode.Force); } } }
1
0.828171
1
0.828171
game-dev
MEDIA
0.932293
game-dev
0.994444
1
0.994444
lenmus/lenmus
23,395
lomse/trunk/include/lomse_document_cursor.h
//--------------------------------------------------------------------------------------- // This file is part of the Lomse library. // Lomse is copyrighted work (c) 2010-2020. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, this // list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // 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. // // For any comment, suggestion or feature request, please contact the manager of // the project at cecilios@users.sourceforge.net //--------------------------------------------------------------------------------------- #ifndef __LOMSE_DOCUMENT_CURSOR_H__ #define __LOMSE_DOCUMENT_CURSOR_H__ #include <stack> #include "lomse_document_iterator.h" #include "lomse_staffobjs_table.h" #include "lomse_time.h" using namespace std; namespace lomse { //forward declarations class Document; class ImoObj; class StaffObjsIterator; class ImoScore; //--------------------------------------------------------------------------------------- // some constants for the ID of pointed object const ImoId k_cursor_pos_undefined = k_no_imoid; //-1 const ImoId k_cursor_before_start = -2; const ImoId k_cursor_at_end = -3; const ImoId k_cursor_at_end_of_child = -4; const ImoId k_cursor_at_empty_place = -5; const ImoId k_cursor_before_start_of_child = -6; const ImoId k_cursor_at_end_of_staff = -7; //======================================================================================= // Helper classes for converting TimeUnits to time code or real time //======================================================================================= class Timecode { public: int bar; int beat; int n16th; int ticks; Timecode(int br, int bt, int n16, int tck) : bar(br), beat(bt), n16th(n16), ticks(tck) { } Timecode() : bar(1), beat(0), n16th(0), ticks(0) { } }; //--------------------------------------------------------------------------------------- // Helper class for computing time and time code class TimeInfo { private: TimeUnits m_totalDuration; //score total duration TimeUnits m_beatDuration; //duration of a beat, for current time signature // Will be 0 if not time signature yet found TimeUnits m_startOfBarTimepos; //timepos at start of current measure TimeUnits m_curTimepos; //current timepos int m_bar; //current bar number (1..n) public: TimeInfo(TimeUnits curTimepos, TimeUnits totalDuration, TimeUnits curBeatDuration, TimeUnits startOfBarTimepos, int iMeasure); //accessors inline TimeUnits get_timepos() { return m_curTimepos; } inline TimeUnits get_current_beat_duration() { return m_beatDuration; } inline TimeUnits get_current_measure_start_timepos() { return m_startOfBarTimepos; } inline TimeUnits get_score_total_duration() { return m_totalDuration; } //! convert current timepos to millisecons for a given metronome speed long to_millisecs(int mm); //! determine metronome speed to force a given total duration float get_metronome_mm_for_lasting(long millisecs); //! Returns current position expressed as percentage of total score duration //! Returned number: 0.00 - 100.00 float played_percentage(); float remaining_percentage(); //! timecode for current position Timecode get_timecode(); }; //======================================================================================= // Helper classes to save cursor state //======================================================================================= //--------------------------------------------------------------------------------------- //base class for any cursor state class class ElementCursorState { protected: ElementCursorState() {} public: virtual ~ElementCursorState() {} virtual ImoId pointee_id()=0; }; typedef std::shared_ptr<ElementCursorState> SpElementCursorState; //--------------------------------------------------------------------------------------- class ScoreCursorState : public ElementCursorState { protected: int m_instr; //instrument (0..n-1) int m_staff; //staff (0..n-1) int m_measure; //measure number (0..n-1) TimeUnits m_time; //timepos TimeUnits m_refTime;//timepos of ref.object or 0.0f if no ref obj ImoId m_id; //id of pointed object or k_cursor_at_empty_place if none ImoId m_refId; //id of ref.object or k_cursor_at_end_of_child if at end. int m_refStaff; //staff (0..n-1) of ref.object or 0 if no ref obj //values representing "end of score" position #define k_at_end_of_score 1000000 #define k_time_at_end_of_score 100000000.0 //values representing "before start" position #define k_before_start_of_score -1 #define k_time_before_start_of_score -1.0 public: ScoreCursorState(int instr, int staff, int measure, TimeUnits time, ImoId id, ImoId refId, TimeUnits refTime, int refStaff) : ElementCursorState(), m_instr(instr), m_staff(staff), m_measure(measure) , m_time(time), m_refTime(refTime), m_id(id), m_refId(refId) , m_refStaff(refStaff) { } ScoreCursorState() : ElementCursorState() { set_at_end_of_score(); } ~ScoreCursorState() override {} //mandatory overrides ImoId pointee_id() override { return id(); } //getters inline int instrument() { return m_instr; } inline int staff() { return m_staff; } inline int measure() { return m_measure; } inline TimeUnits time() { return m_time; } inline ImoId id() { return m_id; } inline ImoId ref_obj_id() { return m_refId; } inline TimeUnits ref_obj_time() { return m_refTime; } inline int ref_obj_staff() { return m_refStaff; } //setters inline ScoreCursorState& instrument(int instr) { m_instr = instr; return *this; } inline ScoreCursorState& staff(int staff) { m_staff = staff; return *this; } inline ScoreCursorState& measure(int measure) { m_measure = measure; return *this; } inline ScoreCursorState& time(TimeUnits time) { m_time = time; return *this; } inline ScoreCursorState& id(ImoId id) { m_id = id; return *this; } inline ScoreCursorState& ref_obj_id(ImoId id) { m_refId = id; return *this; } inline ScoreCursorState& ref_obj_time(TimeUnits time) { m_refTime = time; return *this; } inline ScoreCursorState& ref_obj_staff(int iStaff) { m_refStaff = iStaff; return *this; } inline void set_at_end_of_score() { m_instr = k_at_end_of_score; m_staff = k_at_end_of_score; m_measure = k_at_end_of_score; m_time = k_time_at_end_of_score; m_id = k_cursor_at_end_of_child; m_refId = k_no_imoid; m_refTime = 0.0; m_refStaff = 0; } inline void set_before_start_of_score() { m_instr = k_before_start_of_score; m_staff = k_before_start_of_score; m_measure = k_before_start_of_score; m_time = k_time_before_start_of_score; m_id = k_cursor_before_start_of_child; m_refId = k_before_start_of_score; m_refTime = 0.0; m_refStaff = 0; } //checking position inline bool is_before_start_of_score() { return m_id == k_cursor_before_start_of_child; } inline bool is_at_end_of_staff() { return m_id == k_cursor_at_end_of_staff || m_id == k_cursor_at_end_of_child; } inline bool is_at_end_of_score() { return m_id == k_cursor_at_end_of_child; } }; typedef std::shared_ptr<ScoreCursorState> SpScoreCursorState; //--------------------------------------------------------------------------------------- class DocCursorState { protected: ImoId m_id; //id of top level pointed object or -1 if none SpElementCursorState m_spState; //delegated class state public: DocCursorState(ImoId nTopLevelId, SpElementCursorState spState) : m_id(nTopLevelId) , m_spState(spState) { } DocCursorState() : m_id(k_no_imoid) {} ~DocCursorState() {} inline bool is_inside_terminal_node() { return m_spState.get() != nullptr; } inline ImoId get_parent_level_id() { return m_id; } inline SpElementCursorState get_delegate_state() { return m_spState; } ImoId pointee_id() { if (is_inside_terminal_node()) return m_spState->pointee_id(); else return m_id; } }; //======================================================================================= // Cursor clases //======================================================================================= //--------------------------------------------------------------------------------------- // ElementCursor: base class for any specific element cursor class ElementCursor { protected: Document* m_pDoc; ElementCursor(Document* pDoc) : m_pDoc(pDoc) {} public: virtual ~ElementCursor() {} //interface: all operations/info refers to logical traversing, that is, traversing //following the logical,visual path that user would expect. //positioning inline void operator ++() { move_next(); } inline void operator --() { move_prev(); } virtual void point_to(ImoObj* pImo)=0; virtual void point_to(ImoId nId)=0; // virtual ElementCursor* enter_element() { return this; } virtual void move_next()=0; virtual void move_prev()=0; virtual void move_up()=0; virtual void move_down()=0; //saving/restoring state virtual SpElementCursorState get_state()=0; virtual void restore_state(SpElementCursorState spState)=0; //info virtual ImoObj* get_pointee()=0; virtual ImoId get_pointee_id()=0; //virtual bool is_at_start()=0; inline ImoObj* operator *() { return get_pointee(); } inline Document* get_document() { return m_pDoc; } virtual SpElementCursorState find_previous_pos_state()=0; //special operations for restoring cursor validity after Document modification virtual void reset_and_point_to(ImoId nId)=0; virtual void reset_and_point_after(ImoId id)=0; //debug virtual string dump_cursor()=0; }; //--------------------------------------------------------------------------------------- // DocContentCursor // A cursor to traverse the non-terminal nodes of a document class DocContentCursor { protected: Document* m_pDoc; ImoObj* m_pCurItem; ImoObj* m_parent; public: DocContentCursor(Document* pDoc); virtual ~DocContentCursor() {} //positioning: inline void operator ++() { move_next(); } inline void operator --() { move_prev(); } void point_to(ImoObj* pImo); void point_to(ImoId nId); void move_next(); void move_prev(); void move_up() { move_prev(); } void move_down() { move_next(); } //info inline ImoObj* operator *() { return get_pointee(); } inline Document* get_document() { return m_pDoc; } bool parent_is_root_node(); //specific void start_of_content(); void last_of_content(); void to_end(); ImoId get_prev_id(); inline ImoObj* get_parent_object() { return m_parent; } //saving/restoring state: mandatory overrides SpElementCursorState get_state(); void restore_state(SpElementCursorState spState); //access to current position: mandatory overrides ImoObj* get_pointee() { return m_pCurItem; } ImoId get_pointee_id() { return m_pCurItem != nullptr ? m_pCurItem->get_id() : k_cursor_at_end; } //previous state info SpElementCursorState find_previous_pos_state(); protected: void point_to_current(); void find_parent(); void do_move_next(); void down_to_last(); void do_move_prev(); bool is_at_start(); }; //--------------------------------------------------------------------------------------- // ScoreCursor: A cursor for traversing a score class ScoreCursor : public ElementCursor { protected: ImoScore* m_pScore; ImoId m_scoreId; ColStaffObjs* m_pColStaffObjs; TimeUnits m_timeStep; int m_curVoice; //state variables ScoreCursorState m_currentState; ColStaffObjsIterator m_it; //iterator pointing to ref.object //variables for providing time information TimeUnits m_totalDuration; //score total duration TimeUnits m_curBeatDuration; //duration of a beat, for current time signature TimeUnits m_startOfBarTimepos; //timepos at start of current measure public: ScoreCursor(Document* pDoc, ImoScore* pScore); ~ScoreCursor() override; //mandatory overrides from ElementCursor //positioning void point_to(ImoObj* pImo) override; void point_to(ImoId nId) override; void move_next() override { to_next_staffobj(); } void move_prev() override { to_prev_staffobj(); } void move_up() override; void move_down() override; //saving/restoring state SpElementCursorState get_state() override; void restore_state(SpElementCursorState spState) override; //info inline ImoObj* operator *() { return staffobj(); } ImoObj* get_pointee() override { return staffobj(); } ImoId get_pointee_id() override { return staffobj_id(); } SpElementCursorState find_previous_pos_state() override; //special operations for restoring cursor validity after Document modification void reset_and_point_to(ImoId nId) override; void reset_and_point_after(ImoId id) override; //specific methods //positioning: void to_time(int instr, int staff, TimeUnits timepos); void to_state(int instr, int staff, int measure, TimeUnits time, ImoId id=k_no_imoid); void point_to_barline(ImoId id, int staff); void to_next_staffobj(bool fSkipInChord=true); void to_prev_staffobj(bool fSkipInChord=true); // //void to_start_of_instrument(int nInstr); // //void to_start_of_measure(int nMeasure, int nStaff); // void skip_clef_key_time(); void to_measure(int measure, int instr, int staff); void point_to_end(); //info for curent position inline int instrument() { return m_currentState.instrument(); } inline int measure() { return m_currentState.measure(); } inline int staff() { return m_currentState.staff(); } inline TimeUnits time() { return m_currentState.time(); } inline ImoId id() { return m_currentState.id(); } ImoStaffObj* staffobj(); inline ImoId staffobj_id() { return m_currentState.id(); } inline ImoId staffobj_id_internal() { return m_currentState.ref_obj_id(); } inline TimeUnits ref_obj_time() { return m_currentState.ref_obj_time(); } inline int ref_obj_staff() { return m_currentState.ref_obj_staff(); } ImoObj* staffobj_internal(); TimeInfo get_time_info(); //boolean info. about current position //Score is not empty and cursor is pointing an staffobj inline bool is_pointing_object() { return m_currentState.id() >= 0L; } //Cursor is between two staffobjs, on a free time position inline bool is_at_empty_place() { return m_currentState.id() == k_cursor_at_empty_place; } //Cursor is at end of score but score is empty inline bool is_at_end_of_empty_score() { return is_at_end_of_score() && m_pColStaffObjs->num_entries() == 0; } //Cursor is at end of last staff in score. Score could be empty or not. inline bool is_at_end_of_score() { return m_currentState.id() == k_cursor_at_end_of_child; } //Cursor is at end of a staff. There could be more staves or not (end of score). //Score could be empty or not. inline bool is_at_end_of_staff() { return m_currentState.id() == k_cursor_at_end_of_staff || m_currentState.id() == k_cursor_at_end_of_child; } //at start of score (score is not empty, otherwise cursor will be at end) inline bool is_at_start_of_score() { return m_currentState.ref_obj_id() >= 0L && m_it == m_pColStaffObjs->begin(); } //other inline void set_time_step(TimeUnits step) { m_timeStep = step; } inline void set_current_voice(int voice) { m_curVoice = voice; } void change_voice_to(int voice); //debug & unit tests string dump_cursor() override; protected: //support: related to time info void p_determine_total_duration(); void p_find_start_of_measure_and_time_signature(); //support: point_to void p_move_iterator_to(ImoId id); //support: to_next_staffobj void p_to_next_staff(); void p_to_next_position(bool fSkipInChord); void p_move_iterator_to_next(); void p_if_chord_move_to_last_note(); void p_skip_fwd_implicit_key_time_signatures(); void p_to_next_in_this_staff(); void p_advance_if_not_right_staff(); void p_to_start_of_next_staff(); void p_to_start_of_next_instrument(); void p_to_start_of_staff(int instr, int staff); void p_forward_to_instr_with_time_not_lower_than(TimeUnits rTargetTime); void p_forward_to_instr_staff_with_time_not_lower_than(TimeUnits rTargetTime); void p_advance_to_current_voice(); //support: to_prev_staffobj void p_to_prev_staff(); void p_to_prev_position(bool fSkipInChord); void p_to_prev_in_this_staff(bool fSkipInChord); void p_move_iterator_to_prev(); void p_go_back_if_not_right_staff(); void p_skip_back_current_chord_if_any(); void p_skip_back_implicit_key_time_signatures(); void p_to_end_of_prev_staff(); void p_to_end_of_prev_instrument(); void p_to_end_of_staff(); void p_to_last_object_in_staff(bool fSkipInChord); void p_back_to_current_voice(); //support: other void p_update_state_from_iterator(); void p_set_state_from_iterator(); void p_set_state_as_end_of_score(); void p_update_as_end_of_staff(); void p_update_pointed_object(); bool p_more_staves_in_instrument(); bool p_more_instruments(); void p_to_nearest_position_in_current_voice(); //helper: checks inline bool p_is_iterator_at_start_of_score() { return m_it == m_pColStaffObjs->begin(); } bool p_is_at_start_of_staff(); inline bool p_is_first_staff_of_current_instrument() { return m_currentState.staff() == 0; } inline bool p_is_first_instrument() { return m_currentState.instrument() == 0; } //helper: dealing with ref.object inline ImoStaffObj* p_iter_object() { return (*m_it)->imo_object(); } inline int p_iter_object_id() { return (*m_it)->element_id(); } inline TimeUnits p_iter_object_time() { return (*m_it)->time(); } inline int p_iter_object_measure() { return (*m_it)->measure(); } inline int p_iter_object_staff() { return (*m_it)->staff(); } inline int p_iter_object_instrument() { return (*m_it)->num_instrument(); } inline bool p_there_is_iter_object() { return m_it != m_pColStaffObjs->end() && (*m_it != nullptr); } inline bool p_there_is_not_iter_object() { return m_it != m_pColStaffObjs->end() || (*m_it == nullptr); } inline bool p_iter_is_at_end() { return m_it == m_pColStaffObjs->end(); } inline bool p_iter_object_is_on_measure(int measure) { return p_iter_object_measure() == measure; } inline bool p_iter_object_is_on_staff(int staff) { return p_iter_object_staff() == staff || p_iter_object_is_barline(); } inline bool p_iter_object_is_on_instrument(int instr) { return p_iter_object_instrument() == instr; } inline bool p_iter_object_is_on_time(TimeUnits rTime) { return is_equal_time(rTime, p_iter_object_time()); } TimeUnits p_iter_object_duration(); bool p_iter_object_is_barline(); bool p_iter_object_is_clef(); bool p_iter_object_is_key(); bool p_iter_object_is_time(); }; //--------------------------------------------------------------------------------------- // DocCursor // facade object to enclose all specific cursors for traversing a document //--------------------------------------------------------------------------------------- class DocCursor { protected: Document* m_pDoc; ElementCursor* m_pInnerCursor; DocContentCursor m_outerCursor; ImoId m_idJailer; public: DocCursor(Document* pDoc); virtual ~DocCursor(); DocCursor(DocCursor* cursor); DocCursor(DocCursor& cursor); //info inline ImoObj* operator *() { return get_pointee(); } ImoObj* get_pointee(); ImoObj* get_parent_object(); ImoId get_pointee_id(); ImoId get_parent_id(); inline bool is_inside_terminal_node() { return m_pInnerCursor != nullptr; } // inline bool is_at_top_level() { return m_pInnerCursor == nullptr; } inline Document* get_document() { return m_pDoc; } inline ElementCursor* get_inner_cursor() { return m_pInnerCursor; } DocCursorState find_previous_pos_state(); //positioning inline void operator ++() { move_next(); } inline void operator --() { move_prev(); } void move_next(); void move_prev(); void move_up(); void move_down(); void enter_element(); void exit_element(); void point_to(ImoId nId); void point_to(ImoObj* pImo); void to_start(); void to_end(); void to_last_top_level(); bool jailed_mode_in(ImoId id); inline void terminate_jailed_mode() { m_idJailer = k_no_imoid; } //special operations for restoring cursor validity after Document modification void reset_and_point_to(ImoId id); void reset_and_point_after(ImoId id); //saving/restoring state DocCursorState get_state(); void restore_state(DocCursorState& state); //debug string dump_cursor(); static string id_to_string(ImoId id); protected: void start_delegation(); void stop_delegation(); bool is_out_of_jailer(ImoObj* pImo); inline bool is_jailed() { return m_idJailer != k_no_imoid; } void do_point_to(ImoObj* pImo); }; } //namespace lomse #endif //__LOMSE_DOCUMENT_CURSOR_H__
1
0.906903
1
0.906903
game-dev
MEDIA
0.249649
game-dev
0.904287
1
0.904287
Catacomb-Snatch/Catacomb-Snatch
3,026
Library/PackageCache/com.unity.2d.animation@2.2.1-preview.2/Editor/SkinningModule/IMGUI/ISkeletonView.cs
using UnityEngine; namespace UnityEditor.Experimental.U2D.Animation { internal enum SkeletonAction { None = 0, Select = 1 << 0, RotateBone = 1 << 2, MoveBone = 1 << 3, FreeMoveBone = 1 << 4, MoveEndPosition = 1 << 5, MoveJoint = 1 << 6, ChangeLength = 1 << 7, CreateBone = 1 << 8, SplitBone = 1 << 9, Remove = 1 << 10, } internal enum SkeletonMode { Disabled = SkeletonAction.None, Selection = SkeletonAction.Select, EditPose = Selection | SkeletonAction.RotateBone | SkeletonAction.MoveBone, EditJoints = Selection | SkeletonAction.FreeMoveBone | SkeletonAction.MoveEndPosition | SkeletonAction.MoveJoint | SkeletonAction.Remove, CreateBone = Selection | SkeletonAction.MoveJoint | SkeletonAction.Remove | SkeletonAction.CreateBone, SplitBone = Selection | SkeletonAction.MoveEndPosition | SkeletonAction.MoveJoint | SkeletonAction.Remove | SkeletonAction.SplitBone, } internal interface ISkeletonView { int InvalidID { get; set; } SkeletonMode mode { get; set; } int defaultControlID { get; set; } int hoveredBoneID { get; } int hoveredJointID { get; } int hoveredBodyID { get; } int hoveredTailID { get; } int hotBoneID { get; } void BeginLayout(); void EndLayout(); bool CanLayout(); Vector3 GetMouseWorldPosition(Vector3 planeNormal, Vector3 planePosition); void LayoutBone(int id, Vector3 position, Vector3 endPosition, Vector3 forward, Vector3 up, Vector3 right, bool isChainEnd); bool DoSelectBone(out int id, out bool additive); bool DoRotateBone(Vector3 pivot, Vector3 normal, out float deltaAngle); bool DoMoveBone(out Vector3 deltaPosition); bool DoFreeMoveBone(out Vector3 deltaPosition); bool DoMoveJoint(out Vector3 deltaPosition); bool DoMoveEndPosition(out Vector3 endPosition); bool DoChangeLength(out Vector3 endPosition); bool DoCreateBoneStart(out Vector3 position); bool DoCreateBone(out Vector3 position); bool DoSplitBone(out int id, out Vector3 position); bool DoRemoveBone(); bool DoCancelMultistepAction(bool force); bool IsActionActive(SkeletonAction action); bool IsActionHot(SkeletonAction action); bool IsActionTriggering(SkeletonAction action); bool IsActionFinishing(SkeletonAction action); bool IsRepainting(); void DrawBone(Vector3 position, Vector3 right, Vector3 forward, float length, Color color, bool isChained, bool isSelected, bool isJointHovered, bool isTailHovered, bool isHot); void DrawBoneParentLink(Vector3 parentPosition, Vector3 position, Vector3 forward, Color color); void DrawBoneOutline(Vector3 position, Vector3 right, Vector3 forward, float length, Color color, float outlineScale); void DrawCursors(bool canBeActive); } }
1
0.875826
1
0.875826
game-dev
MEDIA
0.920901
game-dev
0.736063
1
0.736063
nasa/Rigid-Geometric-Algebra
4,559
wahba.m
function Q = wahba(M,N) %WAHBA Q = wahba(M,N) finds motor Q such that N = Q*M*~Q % M and N are corresonding arrays of multivectors containing any % combination of points, lines, planes, and/or motors. % If all objects in M & N are the same multivector type, e.g. they are all % planes, all points, etc. then M & N can be ordinary arrays. If there are % mixed types within M & N, then M & N must be cell arrays. % This function requires the rga class. if nargin < 1 wahba_test return end lenM = length(M); C = 0; Cw = 0; for i = 1:lenM B = Psi(N{i}.m) - Xi(M{i}.m); Bw = Psi(weight(N{i}).m) - Xi(weight(M{i}).m); C = C + B'*B; Cw = Cw + Bw'*Bw; end %% Solve for rotational part of motor Hw(16,4) = 1; Hw(11:-1:9,1:3) = eye(3); Aw = Hw'*Cw*Hw; [~,Sw,Vw] = svd(Aw,'vector'); tol = max(size(Aw))*eps(norm(Aw)); k = find(Sw<tol); if length(k) > 1 warning('Rotational solution may be inaccurate') end qw = Hw*Vw(:,end); % min since svd returns in decreasing order if qw(end)<0 qw = -qw; % conventional to make scalar part positive end %% Solve for remaining part of motor Hb(16,4) = 0; Hb([6:8 1],:) = eye(4); % s = Hb'*qb %Cb = C*Hb; qwhat = Hw'*qw; A = [Hb'*C*Hb qwhat; qwhat' 0]; d = [-Hb'*C*Hw*qwhat; 0]; %A = [Cb'*Cb qwhat; qwhat' 0]; %d = [-Hb'*C'*C*Hw*qwhat; 0]; x = A\d; qb = Hb*x(1:4); %% Create output motor Q = unitize(rgamotor(qw([11 10 9 16]),qb([6:8 1]))); end %% Helper functions function A = Psi(m) % Psi(Q.m) is the productmat such that Psi(Q.m)*x.m' = Q*x, where * is the % antiwedgedot product. arguments m (1,16) end I = eye(3); J = fliplr(I); skew = @(x) [0,-x(3),x(2);x(3),0,-x(1);-x(2),x(1),0]; weks = @(x) fliplr(skew(x)); s = m(1); v3 = m(2:4); v3f = flipud(v3(:)); v4 = m(5); b3 = m(6:8); b3f = flipud(b3(:)); b4 = m(9:11); b4f = flipud(b4(:)); t3 = m(12); t4 = m(13:15); t4f = flipud(t4(:)); p = m(16); v3 = v3(:); b3 = b3(:); b4 = b4(:); t4 = t4(:); O33 = zeros(3,3); O31 = zeros(3,1); O13 = O31'; A = [p, -t4f', -t3, -b4f', -b3f', v4, v3f', s; -t4f, p*I+skew(b4f), b3, -v4*I-skew(t4f), t3*J+weks(v3), b4f, s*J+weks(b3), v3; 0, O13, p, O13, -t4', 0, -b4', v4; b4f, v4*I+skew(t4f), -v3, p*I+skew(b4f), s*J+weks(b3), t4f, -t3*J-weks(v3), b3; O31, O33, -t4, O33, p*I-skew(b4), O31, -v4*I+skew(t4), b4; -v4, -b4f', s, t4f', -v3f', p, -b3f', t3; O31, O33, b4, O33, v4*I-skew(t4), O31, p*I-skew(b4), t4; 0, O13, -v4, O13, -b4', 0, t4', p]; end function B = Xi(m,tilde) % Xi(Q.m) is commutor productmat s/t Xi(Q.m)*x.m' is equal to x*Q where * % is the antiwedgedot product. % Xi(Q.m,true) applies an antireverse to the input so that % Xi(Q.m,true)*x.m' = Xi(antirev(Q).m)*x.m' = x*~Q; % Note that Xi(Q.m)' = rga.productmat(lcomp(Q),'wedgedot') arguments m (1,16) tilde logical = false end if ~tilde % This logic seems b/ward b/c B below was originally def'd for the case % when a single call to rga.productmat returned both Psi & Xi and the % use case was sandwich products Q*x*~Q = Psi(Q.m)*Xi(Q.m)*x.m, ie % there was an implicit assumption that input had already had % antireverse applied to it. So we need to take out here: m = diag([1 -ones(1,10), ones(1,5)])*m'; end I = eye(3); J = fliplr(I); skew = @(x) [0,-x(3),x(2);x(3),0,-x(1);-x(2),x(1),0]; weks = @(x) fliplr(skew(x)); s = m(1); v3 = m(2:4); v3f = flipud(v3(:)); v4 = m(5); b3 = m(6:8); b3f = flipud(b3(:)); b4 = m(9:11); b4f = flipud(b4(:)); t3 = m(12); t4 = m(13:15); t4f = flipud(t4(:)); p = m(16); v3 = v3(:); b3 = b3(:); b4 = b4(:); t4 = t4(:); O33 = zeros(3,3); O31 = zeros(3,1); O13 = O31'; B = [p, t4f', t3, b4f', b3f', v4, v3f', s; t4f, p*I+skew(b4f), b3, -v4*I-skew(t4f), t3*J+weks(v3), -b4f, -s*J-weks(b3), -v3; 0, O13, p, O13, -t4', 0, b4', -v4; -b4f, v4*I+skew(t4f), -v3, p*I+skew(b4f), s*J+weks(b3), -t4f, t3*J+weks(v3), -b3; O31, O33, -t4, O33, p*I-skew(b4), O31, v4*I-skew(t4), -b4; -v4, b4f', -s, -t4f', v3f', p, -b3f', t3; O31, O33, -b4, O33, -v4*I+skew(t4), O31, p*I-skew(b4), t4; 0, O13, v4, O13, b4', 0, t4', p]; end
1
0.906809
1
0.906809
game-dev
MEDIA
0.473066
game-dev,graphics-rendering
0.969679
1
0.969679
Sigma-Skidder-Team/SigmaRemap
4,486
src/main/java/net/minecraft/client/gui/ScreenManager.java
package net.minecraft.client.gui; import com.google.common.collect.Maps; import java.util.Map; import javax.annotation.Nullable; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.screen.Screen; import net.minecraft.client.gui.screen.inventory.*; import net.minecraft.entity.player.PlayerInventory; import net.minecraft.inventory.container.Container; import net.minecraft.inventory.container.ContainerType; import net.minecraft.util.registry.Registry; import net.minecraft.util.text.ITextComponent; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class ScreenManager { private static final Logger LOG = LogManager.getLogger(); private static final Map<ContainerType<?>, ScreenManager.IScreenFactory<?, ?>> FACTORIES = Maps.newHashMap(); public static <T extends Container> void openScreen(ContainerType<T> var0, Minecraft var1, int var2, ITextComponent var3) { if (var0 != null) { ScreenManager.IScreenFactory< T, ? > iscreenfactory = getFactory(var0); if (iscreenfactory != null) { iscreenfactory.createScreen(var3, var0, var1, var2); } else { LOG.warn("Failed to create screen for menu type: {}", Registry.MENU.getKey(var0)); } } else { LOG.warn("Trying to open invalid screen with name: {}", var3.getString()); } } @Nullable private static <T extends Container> ScreenManager.IScreenFactory<T, ?> getFactory(ContainerType<T> var0) { return (ScreenManager.IScreenFactory<T, ?>) FACTORIES.get(var0); } private static <M extends Container, U extends Screen & IHasContainer<M>> void registerFactory(ContainerType<? extends M> var0, ScreenManager.IScreenFactory<M, U> var1) { ScreenManager.IScreenFactory iscreenfactory = FACTORIES.put(var0, var1); if (iscreenfactory != null) { throw new IllegalStateException("Duplicate registration for " + Registry.MENU.getKey(var0)); } } public static boolean isMissingScreen() { boolean flag = false; for (ContainerType<?> containertype : Registry.MENU) { if (!FACTORIES.containsKey(containertype)) { LOG.debug("Menu {} has no matching screen", Registry.MENU.getKey(containertype)); flag = true; } } return flag; } static { registerFactory(ContainerType.GENERIC_9X1, ChestScreen::new); registerFactory(ContainerType.GENERIC_9X2, ChestScreen::new); registerFactory(ContainerType.GENERIC_9X3, ChestScreen::new); registerFactory(ContainerType.GENERIC_9X4, ChestScreen::new); registerFactory(ContainerType.GENERIC_9X5, ChestScreen::new); registerFactory(ContainerType.GENERIC_9X6, ChestScreen::new); registerFactory(ContainerType.GENERIC_3X3, DispenserScreen::new); registerFactory(ContainerType.ANVIL, AnvilScreen::new); registerFactory(ContainerType.BEACON, BeaconScreen::new); registerFactory(ContainerType.BLAST_FURNACE, BlastFurnaceScreen::new); registerFactory(ContainerType.BREWING_STAND, BrewingStandScreen::new); registerFactory(ContainerType.CRAFTING, CraftingScreen::new); registerFactory(ContainerType.ENCHANTMENT, EnchantmentScreen::new); registerFactory(ContainerType.FURNACE, FurnaceScreen::new); registerFactory(ContainerType.GRINDSTONE, GrindstoneScreen::new); registerFactory(ContainerType.HOPPER, HopperScreen::new); registerFactory(ContainerType.LECTERN, LecternScreen::new); registerFactory(ContainerType.LOOM, LoomScreen::new); registerFactory(ContainerType.MERCHANT, MerchantScreen::new); registerFactory(ContainerType.SHULKER_BOX, ShulkerBoxScreen::new); registerFactory(ContainerType.SMITHING, SmithingTableScreen::new); registerFactory(ContainerType.SMOKER, SmokerScreen::new); registerFactory(ContainerType.CARTOGRAPHY_TABLE, CartographyTableScreen::new); registerFactory(ContainerType.STONECUTTER, StonecutterScreen::new); } interface IScreenFactory<T extends Container, U extends Screen & IHasContainer<T>> { default void createScreen(ITextComponent var1, ContainerType<T> var2, Minecraft mc, int var4) { U u = this.create(var2.create(var4, mc.player.inventory), mc.player.inventory, var1); mc.player.openContainer = u.getContainer(); mc.displayGuiScreen(u); } U create(T var1, PlayerInventory var2, ITextComponent var3); } }
1
0.597561
1
0.597561
game-dev
MEDIA
0.982373
game-dev
0.642006
1
0.642006
simonoliver/InputSystemActionPrompts
1,708
Runtime/InputSystemActionPrompts/PromptText.cs
using System; using TMPro; using UnityEngine; using UnityEngine.InputSystem; namespace InputSystemActionPrompts { [RequireComponent(typeof(TextMeshProUGUI))] public class PromptText : MonoBehaviour { [SerializeField] private InputActionAsset m_InputActionAsset; /// <summary> /// Cached TextMeshProUGUI component that we'll apply the prompt sprites to /// </summary> private TextMeshProUGUI m_TextField; /// <summary> /// Cached original text, so we can reapply it if the input device changes /// </summary> private string m_OriginalText; void Start() { m_TextField = GetComponent<TextMeshProUGUI>(); if (m_TextField == null) return; m_OriginalText=m_TextField.text; RefreshText(); // Listen to device changing InputDevicePromptSystem.OnActiveDeviceChanged+= DeviceChanged; } private void OnDestroy() { // Remove listener InputDevicePromptSystem.OnActiveDeviceChanged-= DeviceChanged; } /// <summary> /// Called when active input device changed /// </summary> /// <param name="obj"></param> private void DeviceChanged(InputDevice device) { RefreshText(); } /// <summary> /// Applies text with prompt sprites to the TextMeshProUGUI component /// </summary> private void RefreshText() { if (m_TextField == null) return; m_TextField.text = InputDevicePromptSystem.InsertPromptSprites(m_OriginalText); } } }
1
0.756025
1
0.756025
game-dev
MEDIA
0.683056
game-dev
0.883406
1
0.883406
google/google-ctf
3,364
2023/hackceler8/game/components/weapon_systems/base.py
# Copyright 2023 Google LLC # # 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 # # https://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. import arcade.key import engine.generics as generics import engine.hitbox as hitbox class Weapon(generics.GenericObject): def __init__(self, coords, name, display_name, flipped, weapon_type, damage_type, damage_algo, tileset_path=None, collectable=True, outline=None): super().__init__(coords, nametype="Weapon", tileset_path=tileset_path, outline=outline, can_flash=True, can_flip=True) self.weapon_type = weapon_type self.damage_type = damage_type self.damage_algo = damage_algo self.name = name self.display_name = display_name self.cool_down_timer = 0 self.charging = False if flipped: self.sprite.set_flipped(True) # Weapons start as inactive and are activated by default self.active = False # If ai_controlled, weapons behave according to algo self.ai_controlled = True # If collectable, player can pick it up self.collectable = collectable # If destroyable, the player can destroy it (assuming it's AI controlled) self.destroyable = True # The player can only use (equip) one weapon at a time self.equipped = False def draw(self): if not self.ai_controlled and not self.equipped: return super().draw() def tick(self, pressed_keys, newly_pressed_keys, tics, player, origin="player"): super().tick() if self.cool_down_timer > 0: self.cool_down_timer -= 1 self.player = player if not self.active: return None if not self.ai_controlled: if not self.equipped: return None self.move_to_player() if not self.player.dead: if arcade.key.SPACE in newly_pressed_keys: return self.fire(tics, self.player.face_towards, origin) if arcade.key.SPACE in pressed_keys: self.charge() return None if self.charging and arcade.key.SPACE not in pressed_keys: return self.release_charged_shot(origin) # For AI controlled we pass the players to accommodate for aimbots else: return self.fire(tics, self.player, "AI") def move_to_player(self): self.place_at(self.player.x, self.player.y) if self.player.direction == self.player.DIR_W: self.sprite.set_flipped(True) elif self.player.direction == self.player.DIR_E: self.sprite.set_flipped(False) def charge(self): pass # Overridden by chargeable sub-classes. def release_charged_shot(self, origin): return None # Overridden by chargeable sub-classes.
1
0.812485
1
0.812485
game-dev
MEDIA
0.936042
game-dev
0.940803
1
0.940803
Grimrukh/soulstruct
4,306
src/soulstruct/eldenring/events/vanilla/m60_48_37_00.evs.py
""" South Caelid (SW) (NW) linked: 0 82 strings: 0: N:\\GR\\data\\Param\\event\\common_func.emevd 82: N:\\GR\\data\\Param\\event\\common_macro.emevd 166: 168: 170: 172: 174: """ # [COMMON_FUNC] from .common_func import * from soulstruct.eldenring.events import * from soulstruct.eldenring.events.instructions import * from soulstruct.eldenring.game_types import * from .enums.m60_48_37_00_enums import * @ContinueOnRest(0) def Constructor(): """Event 0""" RegisterGrace(grace_flag=1048370000, asset=Assets.AEG099_060_9000) CommonFunc_90005100( 0, flag=76458, flag_1=76405, asset=Assets.AEG099_090_9000, source_flag=77410, value=0, flag_2=78410, flag_3=78411, flag_4=78412, flag_5=78413, flag_6=78414, flag_7=78415, flag_8=78416, flag_9=78417, flag_10=78418, flag_11=78419, ) CommonFunc_90005201( 0, character=Characters.DecayingEkzykes, animation_id=30000, animation_id_1=20000, radius=50.0, seconds=0.0, left=0, left_1=0, left_2=0, left_3=0, ) CommonFunc_90005870(0, character=Characters.DecayingEkzykes, name=904501600, npc_threat_level=25) CommonFunc_90005861( 0, flag=1048370800, left=0, character=Characters.DecayingEkzykes, left_1=1, item_lot=30400, text=30064, seconds=0.0, ) Event_1048372200( 0, character=Characters.Scarab, special_effect=12603, region=1048372299, region_1=1048372298, region_2=1048372297, ) CommonFunc_90005300(0, flag=1048370299, character=Characters.Scarab, item_lot=40406, seconds=0.0, left=0) @ContinueOnRest(50) def Preconstructor(): """Event 50""" DisableBackread(1048370700) @ContinueOnRest(1048372200) def Event_1048372200(_, character: uint, special_effect: int, region: uint, region_1: uint, region_2: uint): """Event 1048372200""" AND_1.Add(CharacterDead(character)) if AND_1: return AND_2.Add(CharacterHasSpecialEffect(character, special_effect)) AND_2.Add(CharacterAlive(character)) MAIN.Await(AND_2) DisableFlag(1048372201) DisableFlag(1048372202) WaitFrames(frames=1) EnableRandomFlagInRange(flag_range=(1048372201, 1048372202)) WaitFrames(frames=1) GotoIfCharacterInsideRegion(Label.L1, character=character, region=region) GotoIfCharacterInsideRegion(Label.L2, character=character, region=region_1) GotoIfCharacterInsideRegion(Label.L3, character=character, region=region_2) # --- Label 1 --- # DefineLabel(1) SkipLinesIfFlagEnabled(1, 1048372201) SkipLines(3) Move(character, destination=region_1, destination_type=CoordEntityType.Region, copy_draw_parent=character) ForceAnimation(character, 20025, loop=True, wait_for_completion=True) Goto(Label.L0) Move(character, destination=region_2, destination_type=CoordEntityType.Region, copy_draw_parent=character) ForceAnimation(character, 20025, loop=True, wait_for_completion=True) Goto(Label.L0) # --- Label 2 --- # DefineLabel(2) SkipLinesIfFlagEnabled(1, 1048372201) SkipLines(3) Move(character, destination=region, destination_type=CoordEntityType.Region, copy_draw_parent=character) ForceAnimation(character, 20025, loop=True, wait_for_completion=True) Goto(Label.L0) Move(character, destination=region_2, destination_type=CoordEntityType.Region, copy_draw_parent=character) ForceAnimation(character, 20025, loop=True, wait_for_completion=True) Goto(Label.L0) # --- Label 3 --- # DefineLabel(3) SkipLinesIfFlagEnabled(1, 1048372201) SkipLines(3) Move(character, destination=region, destination_type=CoordEntityType.Region, copy_draw_parent=character) ForceAnimation(character, 20025, loop=True, wait_for_completion=True) Goto(Label.L0) Move(character, destination=region_1, destination_type=CoordEntityType.Region, copy_draw_parent=character) ForceAnimation(character, 20025, loop=True, wait_for_completion=True) Goto(Label.L0) # --- Label 0 --- # DefineLabel(0) ReplanAI(character) Wait(1.0) Restart()
1
0.797089
1
0.797089
game-dev
MEDIA
0.735908
game-dev
0.95459
1
0.95459
JuUnland/Chess
3,453
src/Pawn.cpp
#include "Pawn.h" #include <iostream> #include <list> Pawn::Pawn(Team team, std::pair<int, int> pos, SDL_Handler* handler) :Piece(team, pos, handler, PAWN), m_enPassant(std::pair<bool, int>(false, 0)) { std::string filename; if (team == BLACK) { filename = "../res/Chess_pdt60.png"; } else { filename = "../res/Chess_plt60.png"; } m_handler = handler; m_texture = handler->loadImage(filename); if (team == BLACK) { m_dy = -1; } else { m_dy = 1; } render(); } void Pawn::sayMyName() { if (m_team == BLACK) { std::cout << "BLACK PAWN" << std::endl; } else { std::cout << "WHITE PAWN" << std::endl; } } void Pawn::calcPossibleMoves(Piece* field[8][8], bool checkCheck) { std::vector<std::tuple<int, int, Piece::MoveType>> moves; if (m_pos.second + m_dy == 0 || m_pos.second + m_dy == 7) { if (field[m_pos.first][m_pos.second + m_dy] == nullptr) { moves = pushMove(moves, std::tuple<int, int, Piece::MoveType>(m_pos.first, m_pos.second + m_dy, Piece::NEWPIECE), getOwnKing(field), field, checkCheck); } } else { if (field[m_pos.first][m_pos.second + m_dy] == nullptr) { moves = pushMove(moves, std::tuple<int, int, Piece::MoveType>(m_pos.first, m_pos.second + m_dy, Piece::NORMAL), getOwnKing(field), field, checkCheck); } } if ((m_pos.second + 2 * m_dy >= 0) && (m_pos.second + 2 * m_dy <= 7)) { if (field[m_pos.first][m_pos.second + 2 * m_dy] == nullptr && !m_hasMoved) { moves = pushMove(moves, std::tuple<int, int, Piece::MoveType>(m_pos.first, m_pos.second + 2 * m_dy, Piece::NORMAL), getOwnKing(field), field, checkCheck); } } if (m_pos.first + 1 <= 7) { if (field[m_pos.first + 1][m_pos.second + m_dy] != nullptr) { if (field[m_pos.first + 1][m_pos.second + m_dy]->getTeam() != m_team) { if (m_pos.second + m_dy == 0 || m_pos.second + m_dy == 7) { moves = pushMove(moves, std::tuple<int, int, Piece::MoveType>(m_pos.first + 1, m_pos.second + m_dy, Piece::NEWPIECE), getOwnKing(field), field, checkCheck); } else { moves = pushMove(moves, std::tuple<int, int, Piece::MoveType>(m_pos.first + 1, m_pos.second + m_dy, Piece::NORMAL), getOwnKing(field), field, checkCheck); } } } } if (m_pos.first - 1 >= 0) { if (field[m_pos.first - 1][m_pos.second + m_dy] != nullptr) { if (field[m_pos.first - 1][m_pos.second + m_dy]->getTeam() != m_team) { if (m_pos.second + m_dy == 0 || m_pos.second + m_dy == 7) { moves = pushMove(moves, std::tuple<int, int, Piece::MoveType>(m_pos.first - 1, m_pos.second + m_dy, Piece::NEWPIECE), getOwnKing(field), field, checkCheck); } else { moves = pushMove(moves, std::tuple<int, int, Piece::MoveType>(m_pos.first - 1, m_pos.second + m_dy, Piece::NORMAL), getOwnKing(field), field, checkCheck); } } } } if (m_enPassant == std::pair<bool, int>(true, -1)) { moves = pushMove(moves, std::tuple<int, int, Piece::MoveType>(m_pos.first + 1, m_pos.second + m_dy, Piece::ENPASSANT), getOwnKing(field), field, checkCheck); } if (m_enPassant == std::pair<bool, int>(true, 1)) { moves = pushMove(moves, std::tuple<int, int, Piece::MoveType>(m_pos.first - 1, m_pos.second + m_dy, Piece::ENPASSANT), getOwnKing(field), field, checkCheck); } m_possibleMoves = moves; }
1
0.939623
1
0.939623
game-dev
MEDIA
0.556471
game-dev
0.982522
1
0.982522
SteamDatabase/GameTracking-CS2
11,110
game/csgo/pak01_dir/panorama/scripts/friendlobby.js
"use strict"; /// <reference path="csgo.d.ts" /> /// <reference path="rating_emblem.ts" /> /// <reference path="common/commonutil.ts" /> var friendLobby; (function (friendLobby) { let _m_xuid = ''; let _m_isInPopup = false; function Init(elTile) { const _m_isPerfectWorld = MyPersonaAPI.GetLauncherType() === "perfectworld" ? true : false; _m_xuid = elTile.GetAttributeString('xuid', '(not found)'); if (_m_xuid === '(not found)') { return; } _m_isInPopup = elTile.GetAttributeString('showinpopup', 'false') === 'true' ? true : false; let lobbyType = PartyBrowserAPI.GetPartyType(_m_xuid); let gameMode = PartyBrowserAPI.GetPartySessionSetting(_m_xuid, 'game/mode'); elTile.SetHasClass('playerforhire', (lobbyType === 'nearby')); _SetLobbyLeaderNameAvatar(elTile, lobbyType); _SetGroupNameLink(elTile, lobbyType); _SetPrime(elTile); if (!_m_isPerfectWorld) { _SetRegion(elTile); } _SetSkillGroup(elTile, gameMode); _SetLobbySettings(elTile, gameMode); _SetLobbyPlayerSlots(elTile, gameMode, lobbyType); _SetUpJoinBtn(elTile, lobbyType); _SetUpLobbiesPopupBtn(elTile); _SetDismissButton(elTile, lobbyType); elTile.SetHasClass('friendlobby--is-in-popup', _m_isInPopup); } friendLobby.Init = Init; function _SetLobbyLeaderNameAvatar(elTile, lobbyType) { let xuidLobbyLeader = PartyBrowserAPI.GetPartyMemberXuid(_m_xuid, 0); let rawName = FriendsListAPI.GetFriendName(xuidLobbyLeader); elTile.SetDialogVariable('friendname', $.HTMLEscape(rawName)); let nameString = (lobbyType === 'invited') ? '#tooltip_friend_invited_you' : "#tooltip_lobby_leader_name"; elTile.FindChildTraverse('JsFriendLobbyLeaderName').text = nameString; elTile.FindChildTraverse('JsFriendLobbyLeaderAvatar').PopulateFromSteamID(xuidLobbyLeader); elTile.FindChildTraverse('JsFriendLobbyLeaderBtn').SetPanelEvent('onactivate', () => _OpenContextMenu(xuidLobbyLeader)); } function _SetPrime(elTile) { let primeValue = PartyBrowserAPI.GetPartySessionSetting(_m_xuid, 'game/apr'); elTile.FindChildTraverse('JsFriendLobbyPrime').visible = (primeValue && primeValue != '0') ? true : false; } function _SetRegion(elTile) { let countryCode = PartyBrowserAPI.GetPartySessionSetting(_m_xuid, 'game/loc'); CommonUtil.SetRegionOnLabel(countryCode, elTile); } function _SetSkillGroup(elTile, gameMode) { let szSkillGroupType = "Competitive"; if (gameMode === 'scrimcomp2v2') { szSkillGroupType = 'Wingman'; } else { szSkillGroupType = 'Premier'; } let score = Number(PartyBrowserAPI.GetPartySessionSetting(_m_xuid, 'game/ark')); score = Math.floor(score / 10); const options = { root_panel: elTile.FindChildTraverse('jsRatingEmblem'), do_fx: true, full_details: false, rating_type: szSkillGroupType, leaderboard_details: { score: score }, local_player: _m_xuid === MyPersonaAPI.GetXuid() }; RatingEmblem.SetXuid(options); } function _SetLobbySettings(elTile, gameMode) { let gameModeType = GameTypesAPI.GetGameModeType(gameMode); let gameModeDisplay = GameTypesAPI.GetGameModeAttribute(gameModeType, gameMode, 'nameID'); elTile.SetDialogVariable('lobby-mode', $.Localize(gameModeDisplay)); elTile.SetDialogVariable('lobby-maps', _GetMapNames(gameMode)); } function _GetMapNames(gameMode) { let mapGroups = PartyBrowserAPI.GetPartySessionSetting(_m_xuid, 'game/mapgroupname'); if (mapGroups == 'workshop') return $.Localize('#SFUI_Groups_workshop'); if (!mapGroups) mapGroups = ''; let mapsList = mapGroups.split(','); let mapsNiceNamesList = []; for (let i = 0; i < mapsList.length; i++) { if (i < 4) { let mapNiceName = GameTypesAPI.GetMapGroupAttribute(mapsList[i], 'nameID'); mapsNiceNamesList.push($.Localize(mapNiceName)); } } return mapsNiceNamesList.join(', '); } function _SetLobbyPlayerSlots(elTile, gameMode, lobbyType) { if (lobbyType === 'nearby') return; let numSlotsToShow = SessionUtil.GetMaxLobbySlotsForGameMode(gameMode) - 1; let elAvatarRow = elTile.FindChildTraverse('JsFriendLobbyAvatars'); for (let i = 1; i <= numSlotsToShow; i++) { let xuid = PartyBrowserAPI.GetPartyMemberXuid(_m_xuid, i); let slotId = _m_xuid + ':' + i; let playerSlot = elAvatarRow.FindChild(slotId); if (!playerSlot) { playerSlot = $.CreatePanel('Panel', elAvatarRow, slotId); playerSlot.BLoadLayoutSnippet('FriendLobbyAvatarSlot'); } if (i === 1) playerSlot.AddClass('friendlobby__slot--first'); let elEmpty = playerSlot.FindChildTraverse('JsFriendAvatarEmpty'); let elAvatar = playerSlot.FindChildTraverse('JsFriendAvatar'); if (xuid) { elAvatar.PopulateFromSteamID(xuid); playerSlot.FindChild('JsFriendAvatarBtn').SetPanelEvent('onactivate', () => _OpenContextMenu(xuid)); elEmpty.visible = false; elAvatar.visible = true; } else { elEmpty.visible = true; elAvatar.visible = false; } } } function _SetUpJoinBtn(elTile, lobbyType) { let elJoinBtn = elTile.FindChildInLayoutFile('JsFriendLobbyJoinBtn'); let clientInLobby = false; let clientXuid = MyPersonaAPI.GetXuid(); let count = PartyBrowserAPI.GetPartyMembersCount(_m_xuid); for (let i = 0; i <= count; i++) { if (clientXuid === PartyBrowserAPI.GetPartyMemberXuid(_m_xuid, i)) { clientInLobby = true; break; } } if (clientInLobby || lobbyType === 'suggested') { elJoinBtn.AddClass('hidden'); return; } elJoinBtn.RemoveClass('hidden'); let tooltipText = $.Localize((lobbyType === 'invited') ? '#tooltip_accept_invite' : '#tooltip_join_public_lobby'); elJoinBtn.SetPanelEvent('onmouseover', () => UiToolkitAPI.ShowTextTooltip('JsFriendLobbyJoinBtn', tooltipText)); elJoinBtn.SetPanelEvent('onmouseout', () => UiToolkitAPI.HideTextTooltip()); let lobbyLeaderXuid = _m_xuid; elJoinBtn.SetPanelEvent('onactivate', () => { $.DispatchEvent('CSGOPlaySoundEffectMuteBypass', 'PanoramaUI.Lobby.Joined', 'MOUSE', 1.0); PartyBrowserAPI.ActionJoinParty(lobbyLeaderXuid); }); } function _SetGroupNameLink(elTile, lobbyType) { let elGroupLBtn = elTile.FindChildTraverse('JsFriendLobbyGroupBtn'); let elGroupLabel = elTile.FindChildTraverse('JsFriendLobbyGroupTxt'); if (lobbyType === 'invited') { elGroupLabel.visible = false; elGroupLBtn.visible = false; } if (lobbyType === 'nearby') { elGroupLabel.text = $.Localize('#SFUI_Lobby_GroupsNearby'); elGroupLBtn.enabled = false; } else { let clanId = PartyBrowserAPI.GetPartySessionSetting(_m_xuid, "game/clanid"); let clanName = PartyBrowserAPI.GetPartySessionSetting(_m_xuid, "game/clantag"); if (lobbyType === 'suggested') { elGroupLabel.SetDialogVariable('group', clanName); elGroupLabel.text = $.Localize('#FriendsLobby_GroupsSuggested', elGroupLabel); } else { elGroupLabel.SetDialogVariable('group', clanName); elGroupLabel.text = $.Localize('#FriendsLobby_GroupName', elGroupLabel); } let onActivate = _GetClanLink(clanId); elGroupLBtn.SetPanelEvent('onactivate', onActivate); elGroupLBtn.enabled = true; } } function _SetDismissButton(elTile, lobbyType) { if (lobbyType === 'invited') { var elCloseButton = elTile.FindChildInLayoutFile('FriendLobbyCloseButton'); elCloseButton.RemoveClass('hidden'); elCloseButton.SetPanelEvent("onactivate", function () { $.DispatchEvent('CSGOPlaySoundEffectMuteBypass', 'PanoramaUI.Lobby.Left', 'MOUSE', 1.0); PartyBrowserAPI.ClearInvite(elTile.GetAttributeString('xuid', '(not found)')); }); elCloseButton.SetPanelEvent('onmouseover', () => { UiToolkitAPI.ShowTextTooltip('FriendLobbyCloseButton', $.Localize('#tooltip_discard_invite')); }); elCloseButton.SetPanelEvent('onmouseout', () => { UiToolkitAPI.HideTextTooltip(); }); } } function _SetUpLobbiesPopupBtn(elTile) { let elAlert = elTile.FindChildInLayoutFile('JsFriendLobbyCount'); let nLobbies = PartyBrowserAPI.GetInvitesCount(); if (nLobbies < 2) { elTile.FindChildInLayoutFile('JsFriendLobbySeeAllInvites').visible = false; return; } if (elAlert && elAlert.IsValid()) { elAlert.SetDialogVariable("lobby_count", (nLobbies - 1).toString()); elAlert.SetDialogVariable("alert_value", $.Localize('#friends_lobby_count', elAlert)); } let elBtn = elTile.FindChildInLayoutFile('JsFriendLobbySeeAllInvitesBtn'); elBtn.SetPanelEvent('onmouseover', () => { UiToolkitAPI.ShowTextTooltip('JsFriendLobbySeeAllInvitesBtn', $.Localize('#tooltip_lobby_count')); }); elBtn.SetPanelEvent('onmouseout', () => { UiToolkitAPI.HideTextTooltip(); }); elBtn.SetPanelEvent('onactivate', OpenLobbiesContextMenu); } function OpenLobbiesContextMenu() { var contextMenuPanel = UiToolkitAPI.ShowCustomLayoutContextMenu('', '', 'file://{resources}/layout/context_menus/context_menu_lobbies.xml'); contextMenuPanel.AddClass("ContextMenu_NoArrow"); } function _GetClanLink(clanId) { return () => { let link = ''; if (SteamOverlayAPI.GetAppID() == 710) link = "http://beta.steamcommunity.com/gid/" + clanId; else link = "http://steamcommunity.com/gid/" + clanId; SteamOverlayAPI.OpenURL(link); }; } function _OpenContextMenu(xuid) { $.DispatchEvent('SidebarContextMenuActive', true); var contextMenuPanel = UiToolkitAPI.ShowCustomLayoutContextMenuParametersDismissEvent('', '', 'file://{resources}/layout/context_menus/context_menu_playercard.xml', 'xuid=' + xuid, () => $.DispatchEvent('SidebarContextMenuActive', false)); contextMenuPanel.AddClass("ContextMenu_NoArrow"); } })(friendLobby || (friendLobby = {}));
1
0.83842
1
0.83842
game-dev
MEDIA
0.80835
game-dev,desktop-app
0.817655
1
0.817655
MovingBlocks/Terasology
3,374
engine/src/main/java/org/terasology/engine/logic/console/ui/UICommandEntry.java
// Copyright 2021 The Terasology Foundation // SPDX-License-Identifier: Apache-2.0 package org.terasology.engine.logic.console.ui; import com.google.common.collect.Lists; import org.terasology.input.Keyboard; import org.terasology.nui.databinding.Binding; import org.terasology.nui.databinding.DefaultBinding; import org.terasology.nui.events.NUIKeyEvent; import org.terasology.nui.widgets.UIText; import java.util.List; public class UICommandEntry extends UIText { private Binding<List<String>> commandHistory = new DefaultBinding<>(Lists.<String>newArrayList()); private int index; private TabCompletionEngine tabCompletionEngine; public UICommandEntry() { subscribe((int oldPosition, int newPosition) -> { if (tabCompletionEngine == null) { return; } tabCompletionEngine.reset(); }); } @Override public boolean onKeyEvent(NUIKeyEvent event) { if (event.isDown()) { int id = event.getKey().getId(); if (id != Keyboard.KeyId.TAB && tabCompletionEngine != null) { tabCompletionEngine.reset(); } switch (id) { case Keyboard.KeyId.UP: if (index > 0) { index--; if (getCommandHistory().size() > index) { setText(getCommandHistory().get(index)); } setCursorPosition(getText().length()); } return true; case Keyboard.KeyId.DOWN: if (index < getCommandHistory().size()) { index++; if (index == getCommandHistory().size()) { setText(""); } else { setText(getCommandHistory().get(index)); setCursorPosition(getText().length()); } } return true; case Keyboard.KeyId.TAB: if (tabCompletionEngine != null) { setText(tabCompletionEngine.complete(getText())); setCursorPosition(getText().length(), true, false); return true; } break; case Keyboard.KeyId.ENTER: boolean consumed = super.onKeyEvent(event); setText(""); index = getCommandHistory().size(); return consumed; default: return super.onKeyEvent(event); } } return false; } public void bindCommandHistory(Binding<List<String>> binding) { commandHistory = binding; index = commandHistory.get().size(); } public List<String> getCommandHistory() { return commandHistory.get(); } public void setCommandHistory(List<String> val) { commandHistory.set(val); } public TabCompletionEngine getTabCompletionEngine() { return tabCompletionEngine; } public void setTabCompletionEngine(TabCompletionEngine tabCompletionEngine) { this.tabCompletionEngine = tabCompletionEngine; } }
1
0.931797
1
0.931797
game-dev
MEDIA
0.24423
game-dev
0.899691
1
0.899691
lostdecade/onslaught_arena
1,901
htdocs/js/rect.js
(function define_horde_Rect () { /** * Object for dealing with rectangles * @param {number} left Left coordinate of the rectangle * @param {number} top Top coordinate of the rectangle * @param {number} width Width of the rectangle * @param {number} height Height of the rectangle * @constructor */ horde.Rect = function horde_Rect (left, top, width, height) { this.left = Number(left) || 0; this.top = Number(top) || 0; this.width = Number(width) || 0; this.height = Number(height) || 0; }; var Rect = horde.Rect; var proto = Rect.prototype; /** * Checks for intersection of two rectangles * @param {horde.Rect} a First rectangle * @param {horde.Rect} b Second rectangle * @return {boolean} True if a and b intersect otherwise false */ Rect.intersects = function horde_Rect_intersects (a, b) { return ( a.left <= (b.left + b.width) && b.left <= (a.left + a.width) && a.top <= (b.top + b.height) && b.top <= (a.top + a.height) ); }; /** * Returns the center of the rectangle as a vector * @return {horde.Vector2} Vector representing the center point of this rectangle */ proto.center = function horde_Rect_proto_center () { var sizev = new horde.Vector2(this.width, this.height); return new horde.Vector2(this.left, this.top).add(sizev.scale(0.5)); }; /** * Checks for intersection of this rectangle and another * @param {horde.Rect} rect Rectangle to check * @return {boolean} True if rect intersects with this rectangle otherwise false */ proto.intersects = function horde_Rect_proto_intersects (rect) { return Rect.intersects(this, rect); }; /** * Reduces the size of this rect by a given amount * @param {number} amount Amount to reduce on each side * @return {void} */ proto.reduce = function horde_Rect_proto_reduce (amount) { this.left += amount; this.top += amount; this.width -= amount * 2; this.height -= amount * 2; return this; }; }());
1
0.807443
1
0.807443
game-dev
MEDIA
0.461589
game-dev
0.726188
1
0.726188
ostef/Vk-Engine
19,255
Modules/SDL/SDL_keyboard.jai
// SDL_keyboard.h /* SDL_Scancode :: enum s32 { Unknown :: 0; A :: 4; B :: 5; C :: 6; D :: 7; E :: 8; F :: 9; G :: 10; H :: 11; I :: 12; J :: 13; K :: 14; L :: 15; M :: 16; N :: 17; O :: 18; P :: 19; Q :: 20; R :: 21; S :: 22; T :: 23; U :: 24; V :: 25; W :: 26; X :: 27; Y :: 28; Z :: 29; // Number row Nr1 :: 30; Nr2 :: 31; Nr3 :: 32; Nr4 :: 33; Nr5 :: 34; Nr6 :: 35; Nr7 :: 36; Nr8 :: 37; Nr9 :: 38; Nr0 :: 39; Return :: 40; Escape :: 41; Backspace :: 42; Tab :: 43; Space :: 44; Minus :: 45; Equals :: 46; Leftbracket :: 47; Rightbracket :: 48; Backslash :: 49; Nonushash :: 50; // ??; Semicolon :: 51; Apostrophe :: 52; Grave :: 53; Comma :: 54; Period :: 55; Slash :: 56; Caps_Lock :: 57; F1 :: 58; F2 :: 59; F3 :: 60; F4 :: 61; F5 :: 62; F6 :: 63; F7 :: 64; F8 :: 65; F9 :: 66; F10 :: 67; F11 :: 68; F12 :: 69; Print_Screen :: 70; Scroll_Lock :: 71; Pause :: 72; Insert :: 73; Home :: 74; Page_Up :: 75; Delete :: 76; End :: 77; Page_Down :: 78; Right :: 79; Left :: 80; Down :: 81; Up :: 82; Num_Lock_Clear :: 83; Kp_Divide :: 84; Kp_Multiply :: 85; Kp_Minus :: 86; Kp_Plus :: 87; Kp_Enter :: 88; Kp_1 :: 89; Kp_2 :: 90; Kp_3 :: 91; Kp_4 :: 92; Kp_5 :: 93; Kp_6 :: 94; Kp_7 :: 95; Kp_8 :: 96; Kp_9 :: 97; Kp_0 :: 98; Kp_Period :: 99; Non_US_Backslash :: 100; Application :: 101; Power :: 102; Kp_Equals :: 103; F13 :: 104; F14 :: 105; F15 :: 106; F16 :: 107; F17 :: 108; F18 :: 109; F19 :: 110; F20 :: 111; F21 :: 112; F22 :: 113; F23 :: 114; F24 :: 115; Execute :: 116; Help :: 117; Menu :: 118; Select :: 119; Stop :: 120; Again :: 121; Undo :: 122; Cut :: 123; Copy :: 124; Paste :: 125; Find :: 126; Mute :: 127; Volume_Up :: 128; Volume_Down :: 129; Kp_Comma :: 133; Kp_Equals_AS400 :: 134; International1 :: 135; International2 :: 136; International3 :: 137; International4 :: 138; International5 :: 139; International6 :: 140; International7 :: 141; International8 :: 142; International9 :: 143; Lang1 :: 144; Lang2 :: 145; Lang3 :: 146; Lang4 :: 147; Lang5 :: 148; Lang6 :: 149; Lang7 :: 150; Lang8 :: 151; Lang9 :: 152; Alt_Erase :: 153; Sys_Req :: 154; Cancel :: 155; Clear :: 156; Prior :: 157; Return2 :: 158; Separator :: 159; Out :: 160; Oper :: 161; Clear_Again :: 162; Cr_Sel :: 163; Ex_Sel :: 164; Kp_00 :: 176; Kp_000 :: 177; Thousands_Separator :: 178; Decimal_Separator :: 179; Currency_Unit :: 180; Currency_Sub_Unit :: 181; Kp_Left_Paren :: 182; Kp_Right_Paren :: 183; Kp_Left_Brace :: 184; Kp_Right_Brace :: 185; Kp_Tab :: 186; Kp_Backspace :: 187; Kp_A :: 188; Kp_B :: 189; Kp_C :: 190; Kp_D :: 191; Kp_E :: 192; Kp_F :: 193; Kp_Xor :: 194; Kp_Power :: 195; Kp_Percent :: 196; Kp_Less :: 197; Kp_Greater :: 198; Kp_Ampersand :: 199; Kp_Dbl_Ampersand :: 200; Kp_Vertical_Bar :: 201; Kp_Dbl_Vertical_Bar :: 202; Kp_Colon :: 203; Kp_Hash :: 204; Kp_Space :: 205; Kp_At :: 206; Kp_Exclam :: 207; Kp_Mem_Store :: 208; Kp_Mem_Recall :: 209; Kp_Mem_Clear :: 210; Kp_Mem_Add :: 211; Kp_Mem_Subtract :: 212; Kp_Mem_Multiply :: 213; Kp_Mem_Divide :: 214; Kp_Plus_Minus :: 215; Kp_Clear :: 216; Kp_Clear_Entry :: 217; Kp_Binary :: 218; Kp_Octal :: 219; Kp_Decimal :: 220; Kp_Hexadecimal :: 221; LCtrl :: 224; LShift :: 225; LAlt :: 226; LGui :: 227; RCtrl :: 228; RShift :: 229; RAlt :: 230; RGui :: 231; Mode :: 257; Audio_Next :: 258; Audio_Prev :: 259; Audio_Stop :: 260; Audio_Play :: 261; Audio_Mute :: 262; Media_Select :: 263; WWW :: 264; Mail :: 265; Calculator :: 266; Computer :: 267; Ac_Search :: 268; Ac_Home :: 269; Ac_Back :: 270; Ac_Forward :: 271; Ac_Stop :: 272; Ac_Refresh :: 273; Ac_Bookmarks :: 274; Brightness_Down :: 275; Brightness_Up :: 276; Display_Switch :: 277; Kb_Dillum_Toggle :: 278; Kb_Dillum_Down :: 279; Kb_Dillum_Up :: 280; Eject :: 281; Sleep :: 282; App1 :: 283; App2 :: 284; Num_Scancodes :: 512; } */ //SDLK_SCANCODE_MASK :: 1 << 30; SDL_SCANCODE_TO_KEYCODE :: inline (scancode: SDL_Scancode) -> s32 { //return scancode | SDLK_SCANCODE_MASK; return (cast(s32)scancode) | (1 << 30); } Hack :: struct { // This is a @Temporary hack to get around the circular dependency thing that // is happening with #run and overloads if you just call SDL_SCANCODE_TO_KEYCODE. // I need to do something to resolve this. My only idea so far is to have name-inclusion // be a separate phase from typechecking. (Right now we wait on something being inferred // to kick off a 'using', but this is not necessary if we know all the names and can // just insert import_links to them, and then we wait for those import links to typecheck.) K :: inline (scancode: SDL_Scancode) -> s32 { //return scancode | SDLK_SCANCODE_MASK; return (cast(s32)scancode) | (1 << 30); } } using SDL_Keycode :: enum s32 { SDLK_UNKNOWN :: 0; SDLK_RETURN :: #char "\r"; SDLK_ESCAPE :: 27; // 0o33 SDLK_BACKSPACE :: 8; // '\b'; SDLK_TAB :: #char "\t"; SDLK_SPACE :: #char " "; SDLK_EXCLAIM :: #char "!"; SDLK_QUOTEDBL :: #char "\""; SDLK_HASH :: #char "#"; SDLK_PERCENT :: #char "%"; SDLK_DOLLAR :: #char "$"; SDLK_AMPERSAND :: #char "&"; SDLK_QUOTE :: #char "'"; SDLK_LEFTPAREN :: #char "("; SDLK_RIGHTPAREN :: #char ")"; SDLK_ASTERISK :: #char "*"; SDLK_PLUS :: #char "+"; SDLK_COMMA :: #char ","; SDLK_MINUS :: #char "-"; SDLK_PERIOD :: #char "."; SDLK_SLASH :: #char "/"; SDLK_0 :: #char "0"; SDLK_1 :: #char "1"; SDLK_2 :: #char "2"; SDLK_3 :: #char "3"; SDLK_4 :: #char "4"; SDLK_5 :: #char "5"; SDLK_6 :: #char "6"; SDLK_7 :: #char "7"; SDLK_8 :: #char "8"; SDLK_9 :: #char "9"; SDLK_COLON :: #char ":"; SDLK_SEMICOLON :: #char ";"; SDLK_LESS :: #char "<"; SDLK_EQUALS :: #char "="; SDLK_GREATER :: #char ">"; SDLK_QUESTION :: #char "?"; SDLK_AT :: #char "@"; /* Skip uppercase letters */ SDLK_LEFTBRACKET :: #char "["; SDLK_BACKSLASH :: #char "\\"; SDLK_RIGHTBRACKET :: #char "]"; SDLK_CARET :: #char "^"; SDLK_UNDERSCORE :: #char "_"; SDLK_BACKQUOTE :: #char "`"; SDLK_a :: #char "a"; SDLK_b :: #char "b"; SDLK_c :: #char "c"; SDLK_d :: #char "d"; SDLK_e :: #char "e"; SDLK_f :: #char "f"; SDLK_g :: #char "g"; SDLK_h :: #char "h"; SDLK_i :: #char "i"; SDLK_j :: #char "j"; SDLK_k :: #char "k"; SDLK_l :: #char "l"; SDLK_m :: #char "m"; SDLK_n :: #char "n"; SDLK_o :: #char "o"; SDLK_p :: #char "p"; SDLK_q :: #char "q"; SDLK_r :: #char "r"; SDLK_s :: #char "s"; SDLK_t :: #char "t"; SDLK_u :: #char "u"; SDLK_v :: #char "v"; SDLK_w :: #char "w"; SDLK_x :: #char "x"; SDLK_y :: #char "y"; SDLK_z :: #char "z"; SDLK_SCANCODE_MASK :: 1 << 30; // // Note: All this #run SDL_SCANCODE_TO_KEYCODE is crazy in terms of // expense required to do simple things. Eventually we will probably be // able to substitute a macro here (when we have macros) but that will // still be perhaps a bit more expensive than I'd like. // SDLK_CAPSLOCK :: #run Hack.K(SDL_SCANCODE_CAPSLOCK); SDLK_F1 :: #run Hack.K(SDL_SCANCODE_F1); SDLK_F2 :: #run Hack.K(SDL_SCANCODE_F2); SDLK_F3 :: #run Hack.K(SDL_SCANCODE_F3); SDLK_F4 :: #run Hack.K(SDL_SCANCODE_F4); SDLK_F5 :: #run Hack.K(SDL_SCANCODE_F5); SDLK_F6 :: #run Hack.K(SDL_SCANCODE_F6); SDLK_F7 :: #run Hack.K(SDL_SCANCODE_F7); SDLK_F8 :: #run Hack.K(SDL_SCANCODE_F8); SDLK_F9 :: #run Hack.K(SDL_SCANCODE_F9); SDLK_F10 :: #run Hack.K(SDL_SCANCODE_F10); SDLK_F11 :: #run Hack.K(SDL_SCANCODE_F11); SDLK_F12 :: #run Hack.K(SDL_SCANCODE_F12); SDLK_PRINTSCREEN :: #run Hack.K(SDL_SCANCODE_PRINTSCREEN); SDLK_SCROLLLOCK :: #run Hack.K(SDL_SCANCODE_SCROLLLOCK); SDLK_PAUSE :: #run Hack.K(SDL_SCANCODE_PAUSE); SDLK_INSERT :: #run Hack.K(SDL_SCANCODE_INSERT); SDLK_HOME :: #run Hack.K(SDL_SCANCODE_HOME); SDLK_PAGEUP :: #run Hack.K(SDL_SCANCODE_PAGEUP); SDLK_DELETE :: 127;// #run Hack.K(SDL_SCANCODE_DELETE); // 177? @@ Why is this one different ??? SDLK_END :: #run Hack.K(SDL_SCANCODE_END); SDLK_PAGEDOWN :: #run Hack.K(SDL_SCANCODE_PAGEDOWN); SDLK_RIGHT :: #run Hack.K(SDL_SCANCODE_RIGHT); SDLK_LEFT :: #run Hack.K(SDL_SCANCODE_LEFT); SDLK_DOWN :: #run Hack.K(SDL_SCANCODE_DOWN); SDLK_UP :: #run Hack.K(SDL_SCANCODE_UP); SDLK_NUMLOCKCLEAR :: #run Hack.K(SDL_SCANCODE_NUMLOCKCLEAR); SDLK_KP_DIVIDE :: #run Hack.K(SDL_SCANCODE_KP_DIVIDE); SDLK_KP_MULTIPLY :: #run Hack.K(SDL_SCANCODE_KP_MULTIPLY); SDLK_KP_MINUS :: #run Hack.K(SDL_SCANCODE_KP_MINUS); SDLK_KP_PLUS :: #run Hack.K(SDL_SCANCODE_KP_PLUS); SDLK_KP_ENTER :: #run Hack.K(SDL_SCANCODE_KP_ENTER); SDLK_KP_1 :: #run Hack.K(SDL_SCANCODE_KP_1); SDLK_KP_2 :: #run Hack.K(SDL_SCANCODE_KP_2); SDLK_KP_3 :: #run Hack.K(SDL_SCANCODE_KP_3); SDLK_KP_4 :: #run Hack.K(SDL_SCANCODE_KP_4); SDLK_KP_5 :: #run Hack.K(SDL_SCANCODE_KP_5); SDLK_KP_6 :: #run Hack.K(SDL_SCANCODE_KP_6); SDLK_KP_7 :: #run Hack.K(SDL_SCANCODE_KP_7); SDLK_KP_8 :: #run Hack.K(SDL_SCANCODE_KP_8); SDLK_KP_9 :: #run Hack.K(SDL_SCANCODE_KP_9); SDLK_KP_0 :: #run Hack.K(SDL_SCANCODE_KP_0); SDLK_KP_PERIOD :: #run Hack.K(SDL_SCANCODE_KP_PERIOD); SDLK_APPLICATION :: #run Hack.K(SDL_SCANCODE_APPLICATION); SDLK_POWER :: #run Hack.K(SDL_SCANCODE_POWER); SDLK_KP_EQUALS :: #run Hack.K(SDL_SCANCODE_KP_EQUALS); SDLK_F13 :: #run Hack.K(SDL_SCANCODE_F13); SDLK_F14 :: #run Hack.K(SDL_SCANCODE_F14); SDLK_F15 :: #run Hack.K(SDL_SCANCODE_F15); SDLK_F16 :: #run Hack.K(SDL_SCANCODE_F16); SDLK_F17 :: #run Hack.K(SDL_SCANCODE_F17); SDLK_F18 :: #run Hack.K(SDL_SCANCODE_F18); SDLK_F19 :: #run Hack.K(SDL_SCANCODE_F19); SDLK_F20 :: #run Hack.K(SDL_SCANCODE_F20); SDLK_F21 :: #run Hack.K(SDL_SCANCODE_F21); SDLK_F22 :: #run Hack.K(SDL_SCANCODE_F22); SDLK_F23 :: #run Hack.K(SDL_SCANCODE_F23); SDLK_F24 :: #run Hack.K(SDL_SCANCODE_F24); SDLK_EXECUTE :: #run Hack.K(SDL_SCANCODE_EXECUTE); SDLK_HELP :: #run Hack.K(SDL_SCANCODE_HELP); SDLK_MENU :: #run Hack.K(SDL_SCANCODE_MENU); SDLK_SELECT :: #run Hack.K(SDL_SCANCODE_SELECT); SDLK_STOP :: #run Hack.K(SDL_SCANCODE_STOP); SDLK_AGAIN :: #run Hack.K(SDL_SCANCODE_AGAIN); SDLK_UNDO :: #run Hack.K(SDL_SCANCODE_UNDO); SDLK_CUT :: #run Hack.K(SDL_SCANCODE_CUT); SDLK_COPY :: #run Hack.K(SDL_SCANCODE_COPY); SDLK_PASTE :: #run Hack.K(SDL_SCANCODE_PASTE); SDLK_FIND :: #run Hack.K(SDL_SCANCODE_FIND); SDLK_MUTE :: #run Hack.K(SDL_SCANCODE_MUTE); SDLK_VOLUMEUP :: #run Hack.K(SDL_SCANCODE_VOLUMEUP); SDLK_VOLUMEDOWN :: #run Hack.K(SDL_SCANCODE_VOLUMEDOWN); SDLK_KP_COMMA :: #run Hack.K(SDL_SCANCODE_KP_COMMA); SDLK_KP_EQUALSAS400 :: #run Hack.K(SDL_SCANCODE_KP_EQUALSAS400); SDLK_ALTERASE :: #run Hack.K(SDL_SCANCODE_ALTERASE); SDLK_SYSREQ :: #run Hack.K(SDL_SCANCODE_SYSREQ); SDLK_CANCEL :: #run Hack.K(SDL_SCANCODE_CANCEL); SDLK_CLEAR :: #run Hack.K(SDL_SCANCODE_CLEAR); SDLK_PRIOR :: #run Hack.K(SDL_SCANCODE_PRIOR); SDLK_RETURN2 :: #run Hack.K(SDL_SCANCODE_RETURN2); SDLK_SEPARATOR :: #run Hack.K(SDL_SCANCODE_SEPARATOR); SDLK_OUT :: #run Hack.K(SDL_SCANCODE_OUT); SDLK_OPER :: #run Hack.K(SDL_SCANCODE_OPER); SDLK_CLEARAGAIN :: #run Hack.K(SDL_SCANCODE_CLEARAGAIN); SDLK_CRSEL :: #run Hack.K(SDL_SCANCODE_CRSEL); SDLK_EXSEL :: #run Hack.K(SDL_SCANCODE_EXSEL); SDLK_KP_00 :: #run Hack.K(SDL_SCANCODE_KP_00); SDLK_KP_000 :: #run Hack.K(SDL_SCANCODE_KP_000); SDLK_THOUSANDSSEPARATOR :: #run Hack.K(SDL_SCANCODE_THOUSANDSSEPARATOR); SDLK_DECIMALSEPARATOR :: #run Hack.K(SDL_SCANCODE_DECIMALSEPARATOR); SDLK_CURRENCYUNIT :: #run Hack.K(SDL_SCANCODE_CURRENCYUNIT); SDLK_CURRENCYSUBUNIT :: #run Hack.K(SDL_SCANCODE_CURRENCYSUBUNIT); SDLK_KP_LEFTPAREN :: #run Hack.K(SDL_SCANCODE_KP_LEFTPAREN); SDLK_KP_RIGHTPAREN :: #run Hack.K(SDL_SCANCODE_KP_RIGHTPAREN); SDLK_KP_LEFTBRACE :: #run Hack.K(SDL_SCANCODE_KP_LEFTBRACE); SDLK_KP_RIGHTBRACE :: #run Hack.K(SDL_SCANCODE_KP_RIGHTBRACE); SDLK_KP_TAB :: #run Hack.K(SDL_SCANCODE_KP_TAB); SDLK_KP_BACKSPACE :: #run Hack.K(SDL_SCANCODE_KP_BACKSPACE); SDLK_KP_A :: #run Hack.K(SDL_SCANCODE_KP_A); SDLK_KP_B :: #run Hack.K(SDL_SCANCODE_KP_B); SDLK_KP_C :: #run Hack.K(SDL_SCANCODE_KP_C); SDLK_KP_D :: #run Hack.K(SDL_SCANCODE_KP_D); SDLK_KP_E :: #run Hack.K(SDL_SCANCODE_KP_E); SDLK_KP_F :: #run Hack.K(SDL_SCANCODE_KP_F); SDLK_KP_XOR :: #run Hack.K(SDL_SCANCODE_KP_XOR); SDLK_KP_POWER :: #run Hack.K(SDL_SCANCODE_KP_POWER); SDLK_KP_PERCENT :: #run Hack.K(SDL_SCANCODE_KP_PERCENT); SDLK_KP_LESS :: #run Hack.K(SDL_SCANCODE_KP_LESS); SDLK_KP_GREATER :: #run Hack.K(SDL_SCANCODE_KP_GREATER); SDLK_KP_AMPERSAND :: #run Hack.K(SDL_SCANCODE_KP_AMPERSAND); SDLK_KP_DBLAMPERSAND :: #run Hack.K(SDL_SCANCODE_KP_DBLAMPERSAND); SDLK_KP_VERTICALBAR :: #run Hack.K(SDL_SCANCODE_KP_VERTICALBAR); SDLK_KP_DBLVERTICALBAR :: #run Hack.K(SDL_SCANCODE_KP_DBLVERTICALBAR); SDLK_KP_COLON :: #run Hack.K(SDL_SCANCODE_KP_COLON); SDLK_KP_HASH :: #run Hack.K(SDL_SCANCODE_KP_HASH); SDLK_KP_SPACE :: #run Hack.K(SDL_SCANCODE_KP_SPACE); SDLK_KP_AT :: #run Hack.K(SDL_SCANCODE_KP_AT); SDLK_KP_EXCLAM :: #run Hack.K(SDL_SCANCODE_KP_EXCLAM); SDLK_KP_MEMSTORE :: #run Hack.K(SDL_SCANCODE_KP_MEMSTORE); SDLK_KP_MEMRECALL :: #run Hack.K(SDL_SCANCODE_KP_MEMRECALL); SDLK_KP_MEMCLEAR :: #run Hack.K(SDL_SCANCODE_KP_MEMCLEAR); SDLK_KP_MEMADD :: #run Hack.K(SDL_SCANCODE_KP_MEMADD); SDLK_KP_MEMSUBTRACT :: #run Hack.K(SDL_SCANCODE_KP_MEMSUBTRACT); SDLK_KP_MEMMULTIPLY :: #run Hack.K(SDL_SCANCODE_KP_MEMMULTIPLY); SDLK_KP_MEMDIVIDE :: #run Hack.K(SDL_SCANCODE_KP_MEMDIVIDE); SDLK_KP_PLUSMINUS :: #run Hack.K(SDL_SCANCODE_KP_PLUSMINUS); SDLK_KP_CLEAR :: #run Hack.K(SDL_SCANCODE_KP_CLEAR); SDLK_KP_CLEARENTRY :: #run Hack.K(SDL_SCANCODE_KP_CLEARENTRY); SDLK_KP_BINARY :: #run Hack.K(SDL_SCANCODE_KP_BINARY); SDLK_KP_OCTAL :: #run Hack.K(SDL_SCANCODE_KP_OCTAL); SDLK_KP_DECIMAL :: #run Hack.K(SDL_SCANCODE_KP_DECIMAL); SDLK_KP_HEXADECIMAL :: #run Hack.K(SDL_SCANCODE_KP_HEXADECIMAL); SDLK_LCTRL :: #run Hack.K(SDL_SCANCODE_LCTRL); SDLK_LSHIFT :: #run Hack.K(SDL_SCANCODE_LSHIFT); SDLK_LALT :: #run Hack.K(SDL_SCANCODE_LALT); SDLK_LGUI :: #run Hack.K(SDL_SCANCODE_LGUI); SDLK_RCTRL :: #run Hack.K(SDL_SCANCODE_RCTRL); SDLK_RSHIFT :: #run Hack.K(SDL_SCANCODE_RSHIFT); SDLK_RALT :: #run Hack.K(SDL_SCANCODE_RALT); SDLK_RGUI :: #run Hack.K(SDL_SCANCODE_RGUI); SDLK_MODE :: #run Hack.K(SDL_SCANCODE_MODE); SDLK_AUDIONEXT :: #run Hack.K(SDL_SCANCODE_AUDIONEXT); SDLK_AUDIOPREV :: #run Hack.K(SDL_SCANCODE_AUDIOPREV); SDLK_AUDIOSTOP :: #run Hack.K(SDL_SCANCODE_AUDIOSTOP); SDLK_AUDIOPLAY :: #run Hack.K(SDL_SCANCODE_AUDIOPLAY); SDLK_AUDIOMUTE :: #run Hack.K(SDL_SCANCODE_AUDIOMUTE); SDLK_MEDIASELECT :: #run Hack.K(SDL_SCANCODE_MEDIASELECT); SDLK_WWW :: #run Hack.K(SDL_SCANCODE_WWW); SDLK_MAIL :: #run Hack.K(SDL_SCANCODE_MAIL); SDLK_CALCULATOR :: #run Hack.K(SDL_SCANCODE_CALCULATOR); SDLK_COMPUTER :: #run Hack.K(SDL_SCANCODE_COMPUTER); SDLK_AC_SEARCH :: #run Hack.K(SDL_SCANCODE_AC_SEARCH); SDLK_AC_HOME :: #run Hack.K(SDL_SCANCODE_AC_HOME); SDLK_AC_BACK :: #run Hack.K(SDL_SCANCODE_AC_BACK); SDLK_AC_FORWARD :: #run Hack.K(SDL_SCANCODE_AC_FORWARD); SDLK_AC_STOP :: #run Hack.K(SDL_SCANCODE_AC_STOP); SDLK_AC_REFRESH :: #run Hack.K(SDL_SCANCODE_AC_REFRESH); SDLK_AC_BOOKMARKS :: #run Hack.K(SDL_SCANCODE_AC_BOOKMARKS); SDLK_BRIGHTNESSDOWN :: #run Hack.K(SDL_SCANCODE_BRIGHTNESSDOWN); SDLK_BRIGHTNESSUP :: #run Hack.K(SDL_SCANCODE_BRIGHTNESSUP); SDLK_DISPLAYSWITCH :: #run Hack.K(SDL_SCANCODE_DISPLAYSWITCH); SDLK_KBDILLUMTOGGLE :: #run Hack.K(SDL_SCANCODE_KBDILLUMTOGGLE); SDLK_KBDILLUMDOWN :: #run Hack.K(SDL_SCANCODE_KBDILLUMDOWN); SDLK_KBDILLUMUP :: #run Hack.K(SDL_SCANCODE_KBDILLUMUP); SDLK_EJECT :: #run Hack.K(SDL_SCANCODE_EJECT); SDLK_SLEEP :: #run Hack.K(SDL_SCANCODE_SLEEP); SDLK_APP1 :: #run Hack.K(SDL_SCANCODE_APP1); SDLK_APP2 :: #run Hack.K(SDL_SCANCODE_APP2); //SDLK_AUDIOREWIND :: #run Hack.K(SDL_SCANCODE_AUDIOREWIND); //SDLK_AUDIOFASTFORWARD :: #run Hack.K(SDL_SCANCODE_AUDIOFASTFORWARD); } using SDL_Keymod :: enum u16 { KMOD_NONE :: 0x0000; KMOD_LSHIFT :: 0x0001; KMOD_RSHIFT :: 0x0002; KMOD_SHIFT :: KMOD_LSHIFT|KMOD_RSHIFT; KMOD_LCTRL :: 0x0040; KMOD_RCTRL :: 0x0080; KMOD_CTRL :: KMOD_LCTRL|KMOD_RCTRL; KMOD_LALT :: 0x0100; KMOD_RALT :: 0x0200; KMOD_ALT :: KMOD_LALT|KMOD_RALT; KMOD_LGUI :: 0x0400; KMOD_RGUI :: 0x0800; KMOD_GUI :: KMOD_LGUI|KMOD_RGUI; KMOD_NUM :: 0x1000; KMOD_CAPS :: 0x2000; KMOD_MODE :: 0x4000; KMOD_RESERVED :: 0x8000; } SDL_Keysym :: struct { scancode: SDL_Scancode; // SDL physical key code - see ::SDL_Scancode for details sym: SDL_Keycode; // SDL virtual key code - see ::SDL_Keycode for details mod: SDL_Keymod; // current key modifiers unused: u16; } SDL_GetKeyboardFocus :: () -> *SDL_Window #foreign SDL2; SDL_GetKeyboardState :: (numkeys: *s32) -> *u8 #foreign SDL2; SDL_GetModState :: () -> SDL_Keymod #foreign SDL2; SDL_SetModState :: (modstate: SDL_Keymod) #foreign SDL2; SDL_GetKeyFromScancode :: (scancode: SDL_Scancode) -> SDL_Keycode #foreign SDL2; SDL_GetScancodeFromKey :: (key: SDL_Keycode) -> SDL_Scancode #foreign SDL2; SDL_GetScancodeName :: (scancode: SDL_Scancode) -> *u8 #foreign SDL2; SDL_GetScancodeFromName :: (name: *u8) -> SDL_Scancode #foreign SDL2; SDL_GetKeyName :: (key: SDL_Keycode) -> *u8 #foreign SDL2; SDL_GetKeyFromName :: (name: *u8) -> SDL_Keycode #foreign SDL2; SDL_StartTextInput :: () #foreign SDL2; SDL_IsTextInputActive :: () -> SDL_bool #foreign SDL2; SDL_StopTextInput :: () #foreign SDL2; SDL_SetTextInputRect :: (rect: *SDL_Rect) #foreign SDL2; SDL_HasScreenKeyboardSupport :: () -> SDL_bool #foreign SDL2; SDL_IsScreenKeyboardShown :: (window: *SDL_Window) -> SDL_bool #foreign SDL2;
1
0.756462
1
0.756462
game-dev
MEDIA
0.430286
game-dev
0.766125
1
0.766125
Secrets-of-Sosaria/World
2,784
Data/Scripts/Custom/animal broker/Rewards/Advanced Colors/PinkPetDye.cs
using Server.Targeting; using System; using Server; using Server.Gumps; using Server.Network; using Server.Menus; using Server.Menus.Questions; using Server.Mobiles; using System.Collections; namespace Server.Items { public class PinkPetDye : Item { [Constructable] public PinkPetDye() : base( 0xE2B ) { Weight = 1.0; Movable = true; Hue = 1166; Name="pet dye (Pink)"; } public PinkPetDye( Serial serial ) : base( serial ) { } public override void OnDoubleClick( Mobile from ) { if ( !IsChildOf( from.Backpack ) ) { from.SendLocalizedMessage( 1042001 ); // That must be in your pack for you to use it. } else if( from.InRange( this.GetWorldLocation(), 1 ) ) { from.SendMessage( "What do you wish to dye?" ); from.Target = new PinkDyeTarget( this ); } else { from.SendLocalizedMessage( 500446 ); // That is too far away. } } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 0 ); } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); } private class PinkDyeTarget : Target { private Mobile m_Owner; private PinkPetDye m_Powder; public PinkDyeTarget( PinkPetDye charge ) : base ( 10, false, TargetFlags.None ) { m_Powder=charge; } protected override void OnTarget( Mobile from, object target ) { if ( target == from ) from.SendMessage( "This can only be used on pets." ); else if ( target is PlayerMobile ) from.SendMessage( "You cannot dye them." ); else if ( target is Item ) from.SendMessage( "You cannot dye that." ); else if ( target is BaseCreature ) { BaseCreature c = (BaseCreature)target; if ( c.BodyValue == 400 || c.BodyValue == 401 && c.Controlled == false ) { from.SendMessage( "You cannot dye them." ); } else if ( c.ControlMaster != from && c.Controlled == false ) { from.SendMessage( "This is not your pet." ); } else if ( c.Controlled == true && c.ControlMaster == from) { c.Hue = 1166; from.SendMessage( 53, "Your pet has now been dyed." ); from.PlaySound( 0x23E ); m_Powder.Delete(); } } } } } }
1
0.834528
1
0.834528
game-dev
MEDIA
0.922192
game-dev
0.702955
1
0.702955
hydro-sdk/hydro-sdk
21,108
lib/cfr/builtins/libs/dart/typed_data/int16List.dart
import 'dart:core'; import 'dart:math'; import 'dart:typed_data'; import 'package:hydro_sdk/cfr/runtimeSupport.dart'; class VMManagedInt16List extends VMManagedBox<Int16List> { VMManagedInt16List( {required this.table, required this.vmObject, required this.hydroState}) : super( table: table, vmObject: vmObject, hydroState: hydroState, ) { table['sublist'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) { return [ maybeBoxObject<Int16List>( object: vmObject.sublist(luaCallerArguments[1], luaCallerArguments[2]), hydroState: hydroState, table: HydroTable()), ]; }); table['cast'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) { return [ maybeBoxObject<List<dynamic>>( object: vmObject.cast(), hydroState: hydroState, table: HydroTable()), ]; }); table['add'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) { vmObject.add(luaCallerArguments[1]); return []; }); table['addAll'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) { vmObject.addAll(maybeUnBoxAndBuildArgument<Iterable<int>, int>( luaCallerArguments[1], parentState: hydroState)); return []; }); table['sort'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) { Closure? unpackedcompare = luaCallerArguments[1]; vmObject.sort(unpackedcompare != null ? (a, b) => unpackedcompare.dispatch( [luaCallerArguments[0], a, b], parentState: hydroState, )[0] : null); return []; }); table['shuffle'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) { vmObject.shuffle(maybeUnBoxAndBuildArgument<Random?, dynamic>( luaCallerArguments[1], parentState: hydroState)); return []; }); table['indexOf'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) { return [ vmObject.indexOf(luaCallerArguments[1], luaCallerArguments[2]), ]; }); table['indexWhere'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) { Closure unpackedtest = luaCallerArguments[1]; return [ vmObject.indexWhere( (element) => unpackedtest.dispatch( [luaCallerArguments[0], element], parentState: hydroState, )[0], luaCallerArguments[2]), ]; }); table['lastIndexWhere'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) { Closure unpackedtest = luaCallerArguments[1]; return [ vmObject.lastIndexWhere( (element) => unpackedtest.dispatch( [luaCallerArguments[0], element], parentState: hydroState, )[0], luaCallerArguments[2]), ]; }); table['lastIndexOf'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) { return [ vmObject.lastIndexOf(luaCallerArguments[1], luaCallerArguments[2]), ]; }); table['clear'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) { vmObject.clear(); return []; }); table['insert'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) { vmObject.insert(luaCallerArguments[1], luaCallerArguments[2]); return []; }); table['insertAll'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) { vmObject.insertAll( luaCallerArguments[1], maybeUnBoxAndBuildArgument<Iterable<int>, int>(luaCallerArguments[2], parentState: hydroState)); return []; }); table['setAll'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) { vmObject.setAll( luaCallerArguments[1], maybeUnBoxAndBuildArgument<Iterable<int>, int>(luaCallerArguments[2], parentState: hydroState)); return []; }); table['remove'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) { return [ vmObject.remove(maybeUnBoxAndBuildArgument<Object?, dynamic>( luaCallerArguments[1], parentState: hydroState)), ]; }); table['removeAt'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) { return [ vmObject.removeAt(luaCallerArguments[1]), ]; }); table['removeLast'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) { return [ vmObject.removeLast(), ]; }); table['removeWhere'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) { Closure unpackedtest = luaCallerArguments[1]; vmObject.removeWhere((element) => unpackedtest.dispatch( [luaCallerArguments[0], element], parentState: hydroState, )[0]); return []; }); table['retainWhere'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) { Closure unpackedtest = luaCallerArguments[1]; vmObject.retainWhere((element) => unpackedtest.dispatch( [luaCallerArguments[0], element], parentState: hydroState, )[0]); return []; }); table['getRange'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) { return [ maybeBoxObject<Iterable>( object: vmObject.getRange(luaCallerArguments[1], luaCallerArguments[2]), hydroState: hydroState, table: HydroTable()), ]; }); table['setRange'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) { vmObject.setRange( luaCallerArguments[1], luaCallerArguments[2], maybeUnBoxAndBuildArgument<Iterable<int>, int>(luaCallerArguments[3], parentState: hydroState), luaCallerArguments[4]); return []; }); table['removeRange'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) { vmObject.removeRange(luaCallerArguments[1], luaCallerArguments[2]); return []; }); table['fillRange'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) { vmObject.fillRange( luaCallerArguments[1], luaCallerArguments[2], luaCallerArguments[3]); return []; }); table['replaceRange'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) { vmObject.replaceRange( luaCallerArguments[1], luaCallerArguments[2], maybeUnBoxAndBuildArgument<Iterable<int>, int>(luaCallerArguments[3], parentState: hydroState)); return []; }); table['asMap'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) { return [ maybeBoxObject<Map>( object: vmObject.asMap(), hydroState: hydroState, table: HydroTable()), ]; }); table['setFirst'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) { vmObject.first = (luaCallerArguments[1]); return []; }); table['setLast'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) { vmObject.last = (luaCallerArguments[1]); return []; }); table['getLength'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) { return [ vmObject.length, ]; }); table['setLength'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) { vmObject.length = (luaCallerArguments[1]); return []; }); table['getReversed'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) { return [ maybeBoxObject<Iterable>( object: vmObject.reversed, hydroState: hydroState, table: HydroTable()), ]; }); table['followedBy'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) { return [ maybeBoxObject<Iterable>( object: vmObject.followedBy( maybeUnBoxAndBuildArgument<Iterable<int>, int>( luaCallerArguments[1], parentState: hydroState)), hydroState: hydroState, table: HydroTable()), ]; }); table['map'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) { Closure unpackedf = luaCallerArguments[1]; return [ maybeBoxObject<Iterable>( object: vmObject.map((e) => unpackedf.dispatch( [luaCallerArguments[0], e], parentState: hydroState, )[0]), hydroState: hydroState, table: HydroTable()), ]; }); table['where'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) { Closure unpackedtest = luaCallerArguments[1]; return [ maybeBoxObject<Iterable>( object: vmObject.where((element) => unpackedtest.dispatch( [luaCallerArguments[0], element], parentState: hydroState, )[0]), hydroState: hydroState, table: HydroTable()), ]; }); table['whereType'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) { return [ maybeBoxObject<Iterable>( object: vmObject.whereType(), hydroState: hydroState, table: HydroTable()), ]; }); table['expand'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) { Closure unpackedf = luaCallerArguments[1]; return [ maybeBoxObject<Iterable>( object: vmObject.expand((element) => maybeUnBoxAndBuildArgument<Iterable<dynamic>, dynamic>( unpackedf.dispatch( [luaCallerArguments[0], element], parentState: hydroState, )[0], parentState: hydroState)), hydroState: hydroState, table: HydroTable()), ]; }); table['contains'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) { return [ vmObject.contains(maybeUnBoxAndBuildArgument<Object?, dynamic>( luaCallerArguments[1], parentState: hydroState)), ]; }); table['forEach'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) { Closure unpackedf = luaCallerArguments[1]; vmObject.forEach((element) => unpackedf.dispatch( [luaCallerArguments[0], element], parentState: hydroState, )); return []; }); table['reduce'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) { Closure unpackedcombine = luaCallerArguments[1]; return [ vmObject.reduce((value, element) => unpackedcombine.dispatch( [luaCallerArguments[0], value, element], parentState: hydroState, )[0]), ]; }); table['fold'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) { Closure unpackedcombine = luaCallerArguments[2]; return [ vmObject.fold( luaCallerArguments[1], (previousValue, element) => unpackedcombine.dispatch( [luaCallerArguments[0], previousValue, element], parentState: hydroState, )[0]), ]; }); table['every'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) { Closure unpackedtest = luaCallerArguments[1]; return [ vmObject.every((element) => unpackedtest.dispatch( [luaCallerArguments[0], element], parentState: hydroState, )[0]), ]; }); table['join'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) { return [ vmObject.join(luaCallerArguments[1]), ]; }); table['any'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) { Closure unpackedtest = luaCallerArguments[1]; return [ vmObject.any((element) => unpackedtest.dispatch( [luaCallerArguments[0], element], parentState: hydroState, )[0]), ]; }); table['toList'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) { return [ maybeBoxObject<List<dynamic>>( object: vmObject.toList( growable: luaCallerArguments.length >= 2 ? luaCallerArguments[1]['growable'] : null), hydroState: hydroState, table: HydroTable()), ]; }); table['toSet'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) { return [ maybeBoxObject<Set>( object: vmObject.toSet(), hydroState: hydroState, table: HydroTable()), ]; }); table['take'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) { return [ maybeBoxObject<Iterable>( object: vmObject.take(luaCallerArguments[1]), hydroState: hydroState, table: HydroTable()), ]; }); table['takeWhile'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) { Closure unpackedtest = luaCallerArguments[1]; return [ maybeBoxObject<Iterable>( object: vmObject.takeWhile((value) => unpackedtest.dispatch( [luaCallerArguments[0], value], parentState: hydroState, )[0]), hydroState: hydroState, table: HydroTable()), ]; }); table['skip'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) { return [ maybeBoxObject<Iterable>( object: vmObject.skip(luaCallerArguments[1]), hydroState: hydroState, table: HydroTable()), ]; }); table['skipWhile'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) { Closure unpackedtest = luaCallerArguments[1]; return [ maybeBoxObject<Iterable>( object: vmObject.skipWhile((value) => unpackedtest.dispatch( [luaCallerArguments[0], value], parentState: hydroState, )[0]), hydroState: hydroState, table: HydroTable()), ]; }); table['firstWhere'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) { Closure unpackedtest = luaCallerArguments[1]; Closure? unpackedorElse = luaCallerArguments.length >= 3 ? luaCallerArguments[2]['orElse'] : null; return [ vmObject.firstWhere( (element) => unpackedtest.dispatch( [luaCallerArguments[0], element], parentState: hydroState, )[0], orElse: unpackedorElse != null ? () => unpackedorElse.dispatch( [ luaCallerArguments[0], ], parentState: hydroState, )[0] : null), ]; }); table['lastWhere'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) { Closure unpackedtest = luaCallerArguments[1]; Closure? unpackedorElse = luaCallerArguments.length >= 3 ? luaCallerArguments[2]['orElse'] : null; return [ vmObject.lastWhere( (element) => unpackedtest.dispatch( [luaCallerArguments[0], element], parentState: hydroState, )[0], orElse: unpackedorElse != null ? () => unpackedorElse.dispatch( [ luaCallerArguments[0], ], parentState: hydroState, )[0] : null), ]; }); table['singleWhere'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) { Closure unpackedtest = luaCallerArguments[1]; Closure? unpackedorElse = luaCallerArguments.length >= 3 ? luaCallerArguments[2]['orElse'] : null; return [ vmObject.singleWhere( (element) => unpackedtest.dispatch( [luaCallerArguments[0], element], parentState: hydroState, )[0], orElse: unpackedorElse != null ? () => unpackedorElse.dispatch( [ luaCallerArguments[0], ], parentState: hydroState, )[0] : null), ]; }); table['elementAt'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) { return [ vmObject.elementAt(luaCallerArguments[1]), ]; }); table['toString'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) { return [ vmObject.toString(), ]; }); table['getIterator'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) { return [ maybeBoxObject<Iterator>( object: vmObject.iterator, hydroState: hydroState, table: HydroTable()), ]; }); table['getIsEmpty'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) { return [ vmObject.isEmpty, ]; }); table['getIsNotEmpty'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) { return [ vmObject.isNotEmpty, ]; }); table['getFirst'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) { return [ vmObject.first, ]; }); table['getLast'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) { return [ vmObject.last, ]; }); table['getSingle'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) { return [ vmObject.single, ]; }); table['getHashCode'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) { return [ vmObject.hashCode, ]; }); table['getElementSizeInBytes'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) { return [ vmObject.elementSizeInBytes, ]; }); table['getOffsetInBytes'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) { return [ vmObject.offsetInBytes, ]; }); table['getLengthInBytes'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) { return [ vmObject.lengthInBytes, ]; }); table['getBuffer'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) { return [ maybeBoxObject<ByteBuffer>( object: vmObject.buffer, hydroState: hydroState, table: HydroTable()), ]; }); } final HydroTable table; final HydroState hydroState; final Int16List vmObject; } void loadInt16List( {required HydroState hydroState, required HydroTable table}) { table['int16List'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) { return [ maybeBoxObject<Int16List>( object: Int16List(luaCallerArguments[1]), hydroState: hydroState, table: luaCallerArguments[0]) ]; }); table['int16ListFromList'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) { return [ maybeBoxObject<Int16List>( object: Int16List.fromList(maybeUnBoxAndBuildArgument<List<int>, int>( luaCallerArguments[1], parentState: hydroState)), hydroState: hydroState, table: HydroTable()), ]; }); table['int16ListView'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) { return [ maybeBoxObject<Int16List>( object: Int16List.view( maybeUnBoxAndBuildArgument<ByteBuffer, dynamic>( luaCallerArguments[1], parentState: hydroState), luaCallerArguments[2], luaCallerArguments[3]), hydroState: hydroState, table: HydroTable()), ]; }); table['int16ListSublistView'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) { return [ maybeBoxObject<Int16List>( object: Int16List.sublistView( maybeUnBoxAndBuildArgument<TypedData, dynamic>( luaCallerArguments[1], parentState: hydroState), luaCallerArguments[2], luaCallerArguments[3]), hydroState: hydroState, table: HydroTable()), ]; }); registerBoxer<Int16List>(boxer: ( {required Int16List vmObject, required HydroState hydroState, required HydroTable table}) { return VMManagedInt16List( vmObject: vmObject, hydroState: hydroState, table: table); }); }
1
0.776821
1
0.776821
game-dev
MEDIA
0.509744
game-dev
0.95208
1
0.95208