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
Team-Beef-Studios/JKXR
6,342
Projects/Android/jni/OpenJK/codeJK2/game/wp_repeater.cpp
/* =========================================================================== Copyright (C) 2000 - 2013, Raven Software, Inc. Copyright (C) 2001 - 2013, Activision, Inc. Copyright (C) 2013 - 2015, OpenJK contributors This file is part of the OpenJK source code. OpenJK is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. =========================================================================== */ #include "g_headers.h" #include "b_local.h" #include "g_local.h" #include "wp_saber.h" #include "w_local.h" #include "g_functions.h" #include "bg_local.h" #include <VrClientInfo.h> #include <VrTBDC.h> extern cvar_t *g_TeamBeefDirectorsCut; //------------------- // Heavy Repeater //------------------- //--------------------------------------------------------- static void WP_RepeaterMainFire( gentity_t *ent, vec3_t dir, vec3_t start ) //--------------------------------------------------------- { int damage = weaponData[WP_REPEATER].damage; WP_TraceSetStart( ent, start, vec3_origin, vec3_origin );//make sure our start point isn't on the other side of a wall float velocity = REPEATER_VELOCITY; if(ent->client && ent->client->ps.clientNum == 0 && g_TeamBeefDirectorsCut->integer == 1) { velocity = TBDC_REPEATER_VELOCITY; } gentity_t *missile = CreateMissile( start, dir, velocity, 10000, ent ); missile->classname = "repeater_proj"; missile->s.weapon = WP_REPEATER; // Do the damages if ( ent->s.number != 0 ) { if ( g_spskill->integer == 0 ) { damage = REPEATER_NPC_DAMAGE_EASY; } else if ( g_spskill->integer == 1 ) { damage = REPEATER_NPC_DAMAGE_NORMAL; } else { damage = REPEATER_NPC_DAMAGE_HARD; } } // if ( ent->client && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > 0 && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > cg.time ) // { // // in overcharge mode, so doing double damage // missile->flags |= FL_OVERCHARGED; // damage *= 2; // } missile->damage = damage; missile->dflags = DAMAGE_DEATH_KNOCKBACK; missile->methodOfDeath = MOD_REPEATER; missile->clipmask = MASK_SHOT | CONTENTS_LIGHTSABER; // we don't want it to bounce forever missile->bounceCount = 8; } //--------------------------------------------------------- static void WP_RepeaterAltFire( gentity_t *ent ) //--------------------------------------------------------- { int damage = weaponData[WP_REPEATER].altDamage; gentity_t *missile = NULL; vec3_t forward, start, angs; if ( BG_UseVRPosition(ent)) { BG_CalculateVRWeaponPosition(start, angs); AngleVectors(angs, forward, NULL, NULL); } else { VectorCopy( wpFwd, forward ); VectorCopy( wpMuzzle, start ); } WP_TraceSetStart( ent, start, vec3_origin, vec3_origin );//make sure our start point isn't on the other side of a wall if ( ent->client && ent->client->NPC_class == CLASS_GALAKMECH ) { missile = CreateMissile( start, ent->client->hiddenDir, ent->client->hiddenDist, 10000, ent, qtrue ); } else { float velocity = REPEATER_ALT_VELOCITY; if(ent->client && ent->client->ps.clientNum == 0 && g_TeamBeefDirectorsCut->integer == 1) { velocity = TBDC_REPEATER_ALT_VELOCITY; } missile = CreateMissile( start, forward, velocity, 10000, ent, qtrue ); } missile->classname = "repeater_alt_proj"; missile->s.weapon = WP_REPEATER; missile->mass = 10; // Do the damages if ( ent->s.number != 0 ) { if ( g_spskill->integer == 0 ) { damage = REPEATER_ALT_NPC_DAMAGE_EASY; } else if ( g_spskill->integer == 1 ) { damage = REPEATER_ALT_NPC_DAMAGE_NORMAL; } else { damage = REPEATER_ALT_NPC_DAMAGE_HARD; } } VectorSet( missile->maxs, REPEATER_ALT_SIZE, REPEATER_ALT_SIZE, REPEATER_ALT_SIZE ); VectorScale( missile->maxs, -1, missile->mins ); missile->s.pos.trType = TR_GRAVITY; missile->s.pos.trDelta[2] += 40.0f; //give a slight boost in the upward direction // if ( ent->client && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > 0 && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > cg.time ) // { // // in overcharge mode, so doing double damage // missile->flags |= FL_OVERCHARGED; // damage *= 2; // } missile->damage = damage; missile->dflags = DAMAGE_DEATH_KNOCKBACK; missile->methodOfDeath = MOD_REPEATER_ALT; missile->splashMethodOfDeath = MOD_REPEATER_ALT; missile->clipmask = MASK_SHOT | CONTENTS_LIGHTSABER; missile->splashDamage = weaponData[WP_REPEATER].altSplashDamage; missile->splashRadius = weaponData[WP_REPEATER].altSplashRadius; // we don't want it to bounce forever missile->bounceCount = 8; } //--------------------------------------------------------- void WP_FireRepeater( gentity_t *ent, qboolean alt_fire ) //--------------------------------------------------------- { vec3_t dir, angs; vec3_t forward, start; if ( BG_UseVRPosition(ent)) { BG_CalculateVRWeaponPosition(start, angs); } else { vectoangles( wpFwd, angs ); VectorCopy( wpMuzzle, start ); } if ( alt_fire ) { WP_RepeaterAltFire( ent ); } else { // Troopers use their aim values as well as the gun's inherent inaccuracy // so check for all classes of stormtroopers and anyone else that has aim error if ( ent->client && ent->NPC && ( ent->client->NPC_class == CLASS_STORMTROOPER || ent->client->NPC_class == CLASS_SWAMPTROOPER || ent->client->NPC_class == CLASS_SHADOWTROOPER ) ) { angs[PITCH] += ( Q_flrand(-1.0f, 1.0f) * (REPEATER_NPC_SPREAD+(6-ent->NPC->currentAim)*0.25f) ); angs[YAW] += ( Q_flrand(-1.0f, 1.0f) * (REPEATER_NPC_SPREAD+(6-ent->NPC->currentAim)*0.25f) ); } else { // add some slop to the alt-fire direction angs[PITCH] += Q_flrand(-1.0f, 1.0f) * REPEATER_SPREAD; angs[YAW] += Q_flrand(-1.0f, 1.0f) * REPEATER_SPREAD; } AngleVectors( angs, dir, NULL, NULL ); // FIXME: if temp_org does not have clear trace to inside the bbox, don't shoot! WP_RepeaterMainFire( ent, dir, start ); } }
412
0.963056
1
0.963056
game-dev
MEDIA
0.989061
game-dev
0.967661
1
0.967661
LiteLDev/LeviLamina
2,764
src-server/mc/scripting/modules/minecraft/events/ScriptPlayerHotbarSelectedSlotChangeAfterEvent.h
#pragma once #include "mc/_HeaderOutputPredefine.h" // auto generated inclusion list #include "mc/deps/scripting/lifetime_registry/StrongTypedObjectHandle.h" // auto generated forward declare list // clang-format off class Player; namespace ScriptModuleMinecraft { class ScriptItemStack; } namespace ScriptModuleMinecraft { class ScriptPlayer; } namespace Scripting { class WeakLifetimeScope; } namespace Scripting { struct ClassBinding; } // clang-format on namespace ScriptModuleMinecraft { struct ScriptPlayerHotbarSelectedSlotChangeAfterEvent { public: // member variables // NOLINTBEGIN ::ll::TypedStorage<8, 32, ::Scripting::StrongTypedObjectHandle<::ScriptModuleMinecraft::ScriptPlayer>> mPlayerHandle; ::ll::TypedStorage<4, 4, int> mPreviousSlotSelected; ::ll::TypedStorage<4, 4, int> mNewSlotSelected; ::ll::TypedStorage< 8, 40, ::std::optional<::Scripting::StrongTypedObjectHandle<::ScriptModuleMinecraft::ScriptItemStack>>> mItemStack; // NOLINTEND public: // prevent constructor by default ScriptPlayerHotbarSelectedSlotChangeAfterEvent& operator=(ScriptPlayerHotbarSelectedSlotChangeAfterEvent const&); ScriptPlayerHotbarSelectedSlotChangeAfterEvent(); public: // member functions // NOLINTBEGIN MCAPI ScriptPlayerHotbarSelectedSlotChangeAfterEvent( ::ScriptModuleMinecraft::ScriptPlayerHotbarSelectedSlotChangeAfterEvent const& ); MCAPI ScriptPlayerHotbarSelectedSlotChangeAfterEvent( ::Player const& player, int previousSlotSelected, int newSlotSelected, ::std::optional<::Scripting::StrongTypedObjectHandle<::ScriptModuleMinecraft::ScriptItemStack>> item, ::Scripting::WeakLifetimeScope const& scope ); MCAPI ~ScriptPlayerHotbarSelectedSlotChangeAfterEvent(); // NOLINTEND public: // static functions // NOLINTBEGIN MCAPI static ::Scripting::ClassBinding bind(); // NOLINTEND public: // constructor thunks // NOLINTBEGIN MCAPI void* $ctor(::ScriptModuleMinecraft::ScriptPlayerHotbarSelectedSlotChangeAfterEvent const&); MCAPI void* $ctor( ::Player const& player, int previousSlotSelected, int newSlotSelected, ::std::optional<::Scripting::StrongTypedObjectHandle<::ScriptModuleMinecraft::ScriptItemStack>> item, ::Scripting::WeakLifetimeScope const& scope ); // NOLINTEND public: // destructor thunk // NOLINTBEGIN MCAPI void $dtor(); // NOLINTEND }; } // namespace ScriptModuleMinecraft
412
0.531717
1
0.531717
game-dev
MEDIA
0.911382
game-dev
0.581231
1
0.581231
OpenXRay/xray-15
4,747
cs/engine/xrGame/group_hierarchy_holder.cpp
//////////////////////////////////////////////////////////////////////////// // Module : group_hierarchy_holder.cpp // Created : 12.11.2001 // Modified : 03.09.2004 // Author : Dmitriy Iassenev, Oles Shishkovtsov, Aleksandr Maksimchuk // Description : Group hierarchy holder //////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "group_hierarchy_holder.h" #include "squad_hierarchy_holder.h" #include "entity.h" #include "agent_manager.h" #include "agent_member_manager.h" #include "agent_memory_manager.h" #include "ai/stalker/ai_stalker.h" #include "memory_manager.h" #include "visual_memory_manager.h" #include "sound_memory_manager.h" #include "hit_memory_manager.h" CGroupHierarchyHolder::~CGroupHierarchyHolder () { VERIFY (m_members.empty()); VERIFY (!m_visible_objects); VERIFY (!m_sound_objects); VERIFY (!m_hit_objects); VERIFY (!m_agent_manager); } #ifdef SQUAD_HIERARCHY_HOLDER_USE_LEADER void CGroupHierarchyHolder::update_leader () { m_leader = 0; MEMBER_REGISTRY::iterator I = m_members.begin(); MEMBER_REGISTRY::iterator E = m_members.end(); for ( ; I != E; ++I) if ((*I)->g_Alive()) { m_leader = *I; break; } } #endif // SQUAD_HIERARCHY_HOLDER_USE_LEADER void CGroupHierarchyHolder::register_in_group (CEntity *member) { VERIFY (member); MEMBER_REGISTRY::iterator I = std::find(m_members.begin(),m_members.end(),member); VERIFY3 (I == m_members.end(),"Specified group member has already been found",*member->cName()); if (m_members.empty()) { m_visible_objects = new VISIBLE_OBJECTS(); m_sound_objects = new SOUND_OBJECTS(); m_hit_objects = new HIT_OBJECTS(); // m_visible_objects->reserve (128); // m_sound_objects->reserve (128); // m_hit_objects->reserve (128); } m_members.push_back (member); } void CGroupHierarchyHolder::register_in_squad (CEntity *member) { #ifdef SQUAD_HIERARCHY_HOLDER_USE_LEADER if (!leader() && member->g_Alive()) { m_leader = member; if (!squad().leader()) squad().leader (member); } #endif // SQUAD_HIERARCHY_HOLDER_USE_LEADER } void CGroupHierarchyHolder::register_in_agent_manager (CEntity *member) { if (!get_agent_manager() && smart_cast<CAI_Stalker*>(member)) { m_agent_manager = new CAgentManager(); agent_manager().memory().set_squad_objects (&visible_objects()); agent_manager().memory().set_squad_objects (&sound_objects()); agent_manager().memory().set_squad_objects (&hit_objects()); } if (get_agent_manager()) agent_manager().member().add (member); } void CGroupHierarchyHolder::register_in_group_senses (CEntity *member) { CCustomMonster *monster = smart_cast<CCustomMonster*>(member); if (monster) { monster->memory().visual().set_squad_objects(&visible_objects()); monster->memory().sound().set_squad_objects (&sound_objects()); monster->memory().hit().set_squad_objects (&hit_objects()); } } void CGroupHierarchyHolder::unregister_in_group (CEntity *member) { VERIFY (member); MEMBER_REGISTRY::iterator I = std::find(m_members.begin(),m_members.end(),member); VERIFY3 (I != m_members.end(),"Specified group member cannot be found",*member->cName()); m_members.erase (I); } void CGroupHierarchyHolder::unregister_in_squad (CEntity *member) { #ifdef SQUAD_HIERARCHY_HOLDER_USE_LEADER if (leader() && (leader()->ID() == member->ID())) { update_leader (); if (squad().leader()->ID() == member->ID()) if (leader()) squad().leader (leader()); else squad().update_leader (); } #endif // SQUAD_HIERARCHY_HOLDER_USE_LEADER } void CGroupHierarchyHolder::unregister_in_agent_manager (CEntity *member) { if (get_agent_manager()) { agent_manager().member().remove (member); if (agent_manager().member().members().empty()) xr_delete (m_agent_manager); } if (m_members.empty()) { xr_delete (m_visible_objects); xr_delete (m_sound_objects); xr_delete (m_hit_objects); } } void CGroupHierarchyHolder::unregister_in_group_senses (CEntity *member) { CCustomMonster *monster = smart_cast<CCustomMonster*>(member); if (monster) { monster->memory().visual().set_squad_objects(0); monster->memory().sound().set_squad_objects (0); monster->memory().hit().set_squad_objects (0); } } void CGroupHierarchyHolder::register_member (CEntity *member) { register_in_group (member); register_in_squad (member); register_in_agent_manager (member); register_in_group_senses (member); } void CGroupHierarchyHolder::unregister_member (CEntity *member) { unregister_in_group (member); unregister_in_squad (member); unregister_in_agent_manager (member); unregister_in_group_senses (member); }
412
0.91172
1
0.91172
game-dev
MEDIA
0.905154
game-dev
0.849931
1
0.849931
LucilleKarma/WrathOfTheGodsPublic
1,694
Content/Items/SolynBooks/CloverManualObtainment.cs
using NoxusBoss.Core.Autoloaders.SolynBooks; using Terraria; using Terraria.DataStructures; using Terraria.ID; using Terraria.ModLoader; namespace NoxusBoss.Content.Items; public partial class SolynBooksSystem : ModSystem { /// <summary> /// A cooldown timer that ensures that clover manuals cannot spawn in rapid succession. /// </summary> public static int CloverManualSpawnCooldown { get; set; } /// <summary> /// The chance of a Clover Manual appearing atop a player this frame, assuming other conditions are valid. This is affected by the luck stat, and is just the base probability. /// </summary> public static int CloverManualObtainmentBaseSpawnChance => 7777777; private static void TryToSpawnCloverManual() { if (CloverManualSpawnCooldown >= 1) { CloverManualSpawnCooldown--; return; } foreach (Player player in Main.ActivePlayers) TryToSpawnCloverManualForPlayer(player); } private static void TryToSpawnCloverManualForPlayer(Player player) { float luckInterpolant = InverseLerp(0f, 1.33f, player.luck); float luckBoost = 1f + Pow(luckInterpolant, 3.77f) * 27.777f; if (luckBoost < 1f) luckBoost = 1f; float obtainmentChance = luckBoost / CloverManualObtainmentBaseSpawnChance; if (Main.netMode != NetmodeID.MultiplayerClient && Main.rand.NextBool(obtainmentChance)) { Item.NewItem(new EntitySource_WorldEvent(), player.Center, SolynBookAutoloader.Books["CloverManual"].Type); CloverManualSpawnCooldown = MinutesToFrames(120f); } } }
412
0.956424
1
0.956424
game-dev
MEDIA
0.975138
game-dev
0.969531
1
0.969531
esmf-org/esmf
6,794
src/Infrastructure/Mesh/src/Moab/mesquite/Mesh/IdealElements.cpp
/* ***************************************************************** MESQUITE -- The Mesh Quality Improvement Toolkit Copyright 2006 Sandia National Laboratories. Developed at the University of Wisconsin--Madison under SNL contract number 624796. The U.S. Government and the University of Wisconsin retain certain rights to this software. This library 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 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License (lgpl.txt) along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA (2006) kraftche@cae.wisc.edu ***************************************************************** */ /** \file IdealElements.cpp * \brief * \author Jason Kraftcheck */ #include "Mesquite.hpp" #include "IdealElements.hpp" #include "Vector3D.hpp" namespace MBMesquite { static Vector3D unit_quad[4] = { Vector3D( -0.5, -0.5, 0.0 ), Vector3D( 0.5, -0.5, 0.0 ), Vector3D( 0.5, 0.5, 0.0 ), Vector3D( -0.5, 0.5, 0.0 ) }; static Vector3D unit_hex[8] = { Vector3D( 0.5, -0.5, -0.5 ), Vector3D( 0.5, 0.5, -0.5 ), Vector3D( -0.5, 0.5, -0.5 ), Vector3D( -0.5, -0.5, -0.5 ), Vector3D( 0.5, -0.5, 0.5 ), Vector3D( 0.5, 0.5, 0.5 ), Vector3D( -0.5, 0.5, 0.5 ), Vector3D( -0.5, -0.5, 0.5 ) }; static Vector3D unit_edge_tri[3]; static Vector3D unit_edge_tet[4]; static Vector3D unit_edge_pyr[5]; static Vector3D unit_edge_wdg[6]; static Vector3D unit_height_pyr[5]; static Vector3D unit_tri[3]; static Vector3D unit_tet[4]; static Vector3D unit_pyr[5]; static Vector3D unit_wdg[6]; static Vector3D unit_hex_pyr[5]; static void init_tri( Vector3D* coords, double side ); static void init_tet( Vector3D* coords, double side ); static void init_pyr( Vector3D* coords, double side ); static void init_wdg( Vector3D* coords, double side ); static void init_hex_pyr( Vector3D* coords, double height ); static const Vector3D* const* init_unit_edge( Vector3D** ); static const Vector3D* const* init_unit_elem( Vector3D** ); const Vector3D* unit_edge_element( EntityTopology ptype, bool punit_pyr ) { static Vector3D* values[MIXED + 1]; static const Vector3D* const* data = init_unit_edge( values ); return ( ptype == PYRAMID && punit_pyr ) ? data[MIXED] : data[ptype]; } const Vector3D* unit_element( EntityTopology ptype, bool punit_pyr ) { static Vector3D* values[MIXED + 1]; static const Vector3D* const* data = init_unit_elem( values ); return ( ptype == PYRAMID && punit_pyr ) ? data[MIXED] : data[ptype]; } static const Vector3D* const* init_unit_edge( Vector3D** ptr ) { for( unsigned i = 0; i < MIXED; ++i ) ptr[i] = 0; init_tri( unit_edge_tri, 1.0 ); init_tet( unit_edge_tet, 1.0 ); init_pyr( unit_edge_pyr, 1.0 ); init_wdg( unit_edge_wdg, 1.0 ); init_hex_pyr( unit_height_pyr, 1.0 ); ptr[TRIANGLE] = unit_edge_tri; ptr[QUADRILATERAL] = unit_quad; ptr[TETRAHEDRON] = unit_edge_tet; ptr[PYRAMID] = unit_edge_pyr; ptr[PRISM] = unit_edge_wdg; ptr[HEXAHEDRON] = unit_hex; ptr[MIXED] = unit_height_pyr; return ptr; } static const Vector3D* const* init_unit_elem( Vector3D** ptr ) { for( unsigned i = 0; i < MIXED; ++i ) ptr[i] = 0; init_tri( unit_tri, 2.0 * pow( 3.0, -0.25 ) ); init_tet( unit_tet, MBMesquite::cbrt( 3.0 ) * sqrt( 2.0 ) ); init_pyr( unit_pyr, pow( 18.0, 1.0 / 6.0 ) ); init_wdg( unit_wdg, MBMesquite::cbrt( 4.0 ) * pow( 3.0, -1.0 / 6.0 ) ); init_hex_pyr( unit_hex_pyr, MBMesquite::cbrt( 3.0 ) ); ptr[TRIANGLE] = unit_tri; ptr[QUADRILATERAL] = unit_quad; ptr[TETRAHEDRON] = unit_tet; ptr[PYRAMID] = unit_pyr; ptr[PRISM] = unit_wdg; ptr[HEXAHEDRON] = unit_hex; ptr[MIXED] = unit_hex_pyr; return ptr; } static void init_tri( Vector3D* coords, double side ) { const double third_height = side * sqrt( 3.0 ) / 6.0; coords[1] = Vector3D( -0.5 * side, -third_height, 0.0 ); coords[2] = Vector3D( 0.5 * side, -third_height, 0.0 ); coords[0] = Vector3D( 0.0, 2 * third_height, 0.0 ); } static void init_tet( Vector3D* coords, double side ) { const double height = side * sqrt( 2.0 / 3.0 ); const double third_base = side * sqrt( 3.0 ) / 6.0; coords[0] = Vector3D( -0.5 * side, -third_base, -0.25 * height ); coords[1] = Vector3D( 0.5 * side, -third_base, -0.25 * height ); coords[2] = Vector3D( 0.0, 2 * third_base, -0.25 * height ); coords[3] = Vector3D( 0.0, 0.0, 0.75 * height ); } static void init_pyr( Vector3D* coords, double side ) { const double height = side * sqrt( 2.0 ) * 0.5; coords[0] = Vector3D( 0.5 * side, -0.5 * side, -0.25 * height ); coords[1] = Vector3D( 0.5 * side, 0.5 * side, -0.25 * height ); coords[2] = Vector3D( -0.5 * side, 0.5 * side, -0.25 * height ); coords[3] = Vector3D( -0.5 * side, -0.5 * side, -0.25 * height ); coords[4] = Vector3D( 0.0, 0.0, 0.75 * height ); } static void init_wdg( Vector3D* coords, double side ) { const double third_height = side * sqrt( 3.0 ) / 6.0; coords[0] = Vector3D( -0.5 * side, -third_height, -0.5 * side ); coords[1] = Vector3D( 0.5 * side, -third_height, -0.5 * side ); coords[2] = Vector3D( 0.0, 2 * third_height, -0.5 * side ); coords[3] = Vector3D( -0.5 * side, -third_height, 0.5 * side ); coords[4] = Vector3D( 0.5 * side, -third_height, 0.5 * side ); coords[5] = Vector3D( 0.0, 2 * third_height, 0.5 * side ); } static void init_hex_pyr( Vector3D* coords, double side ) { coords[0] = Vector3D( 0.5 * side, -0.5 * side, -0.25 * side ); coords[1] = Vector3D( 0.5 * side, 0.5 * side, -0.25 * side ); coords[2] = Vector3D( -0.5 * side, 0.5 * side, -0.25 * side ); coords[3] = Vector3D( -0.5 * side, -0.5 * side, -0.25 * side ); coords[4] = Vector3D( 0.0, 0.0, 0.75 * side ); } } // namespace MBMesquite
412
0.899895
1
0.899895
game-dev
MEDIA
0.477735
game-dev
0.946281
1
0.946281
ProjectIgnis/CardScripts
2,654
official/c40450317.lua
--同胞の絆 --Ties of the Brethren local s,id=GetID() function s.initial_effect(c) --Special Summon 2 monster from the Deck local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(id,0)) e1:SetCategory(CATEGORY_SPECIAL_SUMMON) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetProperty(EFFECT_FLAG_CARD_TARGET) e1:SetCode(EVENT_FREE_CHAIN) e1:SetCost(s.cost) e1:SetTarget(s.target) e1:SetOperation(s.activate) c:RegisterEffect(e1) end function s.cost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.CheckLPCost(tp,2000) and Duel.GetActivityCount(tp,ACTIVITY_BATTLE_PHASE)==0 end Duel.PayLPCost(tp,2000) local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_FIELD) e1:SetCode(EFFECT_CANNOT_BP) e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET+EFFECT_FLAG_OATH) e1:SetTargetRange(1,0) e1:SetReset(RESET_PHASE|PHASE_END) Duel.RegisterEffect(e1,tp) end function s.filter(c,e,tp) if not c:IsFaceup() or not c:IsLevelBelow(4) then return false end local g=Duel.GetMatchingGroup(s.filter2,tp,LOCATION_DECK,0,nil,e,tp,c) return g:GetClassCount(Card.GetCode)>1 end function s.filter2(c,e,tp,tc) return c:GetLevel()==tc:GetLevel() and c:IsRace(tc:GetRace()) and c:IsAttribute(tc:GetAttribute()) and not c:IsCode(tc:GetCode()) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function s.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(tp) and s.filter(chkc,e,tp) end if chk==0 then return not Duel.IsPlayerAffectedByEffect(tp,CARD_BLUEEYES_SPIRIT) and Duel.GetLocationCount(tp,LOCATION_MZONE)>1 and Duel.IsExistingTarget(s.filter,tp,LOCATION_MZONE,0,1,nil,e,tp) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TARGET) Duel.SelectTarget(tp,s.filter,tp,LOCATION_MZONE,0,1,1,nil,e,tp) Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,2,tp,LOCATION_DECK) end function s.activate(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() local g=Duel.GetMatchingGroup(s.filter2,tp,LOCATION_DECK,0,nil,e,tp,tc) if not Duel.IsPlayerAffectedByEffect(tp,CARD_BLUEEYES_SPIRIT) and tc:IsRelateToEffect(e) and tc:IsFaceup() and #g>=2 then local sg=aux.SelectUnselectGroup(g,e,tp,2,2,aux.dncheck,1,tp,HINTMSG_SPSUMMON) if #sg==2 then Duel.SpecialSummon(sg,0,tp,tp,false,false,POS_FACEUP) end end if e:IsHasType(EFFECT_TYPE_ACTIVATE) then local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_FIELD) e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET+EFFECT_FLAG_CLIENT_HINT) e1:SetDescription(aux.Stringid(id,1)) e1:SetCode(EFFECT_CANNOT_SPECIAL_SUMMON) e1:SetReset(RESET_PHASE|PHASE_END) e1:SetTargetRange(1,0) Duel.RegisterEffect(e1,tp) end end
412
0.945106
1
0.945106
game-dev
MEDIA
0.990359
game-dev
0.947097
1
0.947097
ehsan/ogre
3,757
SDK/OSX/Xcode Templates/Xcode4/Project Templates/Ogre/iOS Application.xctemplate/OgreDemoApp.h
//||||||||||||||||||||||||||||||||||||||||||||||| #ifndef OGRE_DEMO_H #define OGRE_DEMO_H //||||||||||||||||||||||||||||||||||||||||||||||| #include "OgreFramework.h" //||||||||||||||||||||||||||||||||||||||||||||||| #ifdef USE_RTSHADER_SYSTEM #include "OgreRTShaderSystem.h" /** This class demonstrates basic usage of the RTShader system. It sub class the material manager listener class and when a target scheme callback is invoked with the shader generator scheme it tries to create an equivalent shader based technique based on the default technique of the given material. */ class ShaderGeneratorTechniqueResolverListener : public Ogre::MaterialManager::Listener { public: ShaderGeneratorTechniqueResolverListener(Ogre::RTShader::ShaderGenerator* pShaderGenerator) { mShaderGenerator = pShaderGenerator; } /** This is the hook point where shader based technique will be created. It will be called whenever the material manager won't find appropriate technique that satisfy the target scheme name. If the scheme name is out target RT Shader System scheme name we will try to create shader generated technique for it. */ virtual Ogre::Technique* handleSchemeNotFound(unsigned short schemeIndex, const Ogre::String& schemeName, Ogre::Material* originalMaterial, unsigned short lodIndex, const Ogre::Renderable* rend) { Ogre::Technique* generatedTech = NULL; // Case this is the default shader generator scheme. if (schemeName == Ogre::RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME) { bool techniqueCreated; // Create shader generated technique for this material. techniqueCreated = mShaderGenerator->createShaderBasedTechnique( originalMaterial->getName(), Ogre::MaterialManager::DEFAULT_SCHEME_NAME, schemeName); // Case technique registration succeeded. if (techniqueCreated) { // Force creating the shaders for the generated technique. mShaderGenerator->validateMaterial(schemeName, originalMaterial->getName()); // Grab the generated technique. Ogre::Material::TechniqueIterator itTech = originalMaterial->getTechniqueIterator(); while (itTech.hasMoreElements()) { Ogre::Technique* curTech = itTech.getNext(); if (curTech->getSchemeName() == schemeName) { generatedTech = curTech; break; } } } } return generatedTech; } protected: Ogre::RTShader::ShaderGenerator* mShaderGenerator; // The shader generator instance. }; #endif class DemoApp : public OIS::KeyListener { public: DemoApp(); ~DemoApp(); void startDemo(); bool keyPressed(const OIS::KeyEvent &keyEventRef); bool keyReleased(const OIS::KeyEvent &keyEventRef); private: void setupDemoScene(); void runDemo(); bool initializeRTShaderSystem(Ogre::SceneManager* sceneMgr); void finalizeRTShaderSystem(); Ogre::SceneNode* m_pCubeNode; Ogre::Entity* m_pCubeEntity; bool m_bShutdown; #ifdef USE_RTSHADER_SYSTEM Ogre::RTShader::ShaderGenerator* mShaderGenerator; // The Shader generator instance. ShaderGeneratorTechniqueResolverListener* mMaterialMgrListener; // Shader generator material manager listener. #endif // USE_RTSHADER_SYSTEM }; //||||||||||||||||||||||||||||||||||||||||||||||| #endif //|||||||||||||||||||||||||||||||||||||||||||||||
412
0.720476
1
0.720476
game-dev
MEDIA
0.947816
game-dev
0.721885
1
0.721885
smokin-guns/SmokinGuns
2,947
code/sys/con_log.c
/* =========================================================================== Copyright (C) 1999-2005 Id Software, Inc. This file is part of Quake III Arena source code. Quake III Arena source code 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. Quake III Arena source code 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 Quake III Arena source code; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA =========================================================================== */ #include "../qcommon/q_shared.h" #include "../qcommon/qcommon.h" #include "sys_local.h" #define MAX_LOG 32768 static char consoleLog[ MAX_LOG ]; static unsigned int writePos = 0; static unsigned int readPos = 0; /* ================== CON_LogSize ================== */ unsigned int CON_LogSize( void ) { if( readPos <= writePos ) return writePos - readPos; else return writePos + MAX_LOG - readPos; } /* ================== CON_LogFree ================== */ static unsigned int CON_LogFree( void ) { return MAX_LOG - CON_LogSize( ) - 1; } /* ================== CON_LogWrite ================== */ unsigned int CON_LogWrite( const char *in ) { unsigned int length = strlen( in ); unsigned int firstChunk; unsigned int secondChunk; while( CON_LogFree( ) < length && CON_LogSize( ) > 0 ) { // Free enough space while( consoleLog[ readPos ] != '\n' && CON_LogSize( ) > 1 ) readPos = ( readPos + 1 ) % MAX_LOG; // Skip past the '\n' readPos = ( readPos + 1 ) % MAX_LOG; } if( CON_LogFree( ) < length ) return 0; if( writePos + length > MAX_LOG ) { firstChunk = MAX_LOG - writePos; secondChunk = length - firstChunk; } else { firstChunk = length; secondChunk = 0; } Com_Memcpy( consoleLog + writePos, in, firstChunk ); Com_Memcpy( consoleLog, in + firstChunk, secondChunk ); writePos = ( writePos + length ) % MAX_LOG; return length; } /* ================== CON_LogRead ================== */ unsigned int CON_LogRead( char *out, unsigned int outSize ) { unsigned int firstChunk; unsigned int secondChunk; if( CON_LogSize( ) < outSize ) outSize = CON_LogSize( ); if( readPos + outSize > MAX_LOG ) { firstChunk = MAX_LOG - readPos; secondChunk = outSize - firstChunk; } else { firstChunk = outSize; secondChunk = 0; } Com_Memcpy( out, consoleLog + readPos, firstChunk ); Com_Memcpy( out + firstChunk, out, secondChunk ); readPos = ( readPos + outSize ) % MAX_LOG; return outSize; }
412
0.613491
1
0.613491
game-dev
MEDIA
0.24661
game-dev
0.572922
1
0.572922
CCEMT/Emilia-Kit
1,676
Assets/Emilia/Kit/Core.Editor/Odin/OdinProEditorWindow.cs
using System; using Sirenix.OdinInspector; using Sirenix.OdinInspector.Editor; using Sirenix.Serialization; using UnityEditor; using UnityEngine; using Object = UnityEngine.Object; namespace Emilia.Kit.Editor { [ShowOdinSerializedPropertiesInInspector] public class OdinProEditorWindow : EditorWindow, ISerializationCallbackReceiver { [SerializeField, HideInInspector] private SerializationData serializationData; [NonSerialized, OdinSerialize] private PropertyTreeContainer _drawerContainer = new PropertyTreeContainer(); [NonSerialized, OdinSerialize] private UnityEditorContainer _editorContainer = new UnityEditorContainer(); void ISerializationCallbackReceiver.OnBeforeSerialize() { UnitySerializationUtility.SerializeUnityObject((Object) this, ref this.serializationData); OnBeforeSerialize(); } void ISerializationCallbackReceiver.OnAfterDeserialize() { UnitySerializationUtility.DeserializeUnityObject((Object) this, ref this.serializationData); OnAfterDeserialize(); } protected void DrawTarget(object target, Action<PropertyTree, InspectorProperty> onCheck = null) { _drawerContainer.DrawTargetCheck(target, onCheck); } protected void DrawEditor(Object target) { _editorContainer.OnInspectorGUI(target); } protected virtual void OnDestroy() { _drawerContainer.Dispose(); } protected virtual void OnBeforeSerialize() { } protected virtual void OnAfterDeserialize() { } } }
412
0.882183
1
0.882183
game-dev
MEDIA
0.925727
game-dev
0.923444
1
0.923444
darwinbeing/HPServerPSUHack
20,447
references/ex_boot_app_blink_dual_partition/ezbl_integration/ezbl_tools_source_from_jdcore/ezbl_tools_source_from_jdcore/com/microchip/apps/ezbl/Section.java
package com.microchip.apps.ezbl; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.io.PrintStream; import java.io.Serializable; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; public class Section implements Serializable, Cloneable, Comparable<Section> { static final long serialVersionUID = 1L; public int id = 0; public String name = ""; public String combinedName = ""; public String sourceFile = ""; public long size = -1L; public long virtualMemoryAddress = -1L; public long loadMemoryAddress = -1L; public long fileOffset = 0L; public int alignment = 2; public SectionFlags flags = new SectionFlags(); public List<Symbol> symbols = null; public Map<Long, Symbol> symbolsByAddr = null; public Map<String, Symbol> symbolsByName = null; public DataRecord data = null; public boolean isROM = false; public boolean isRAM = false; public boolean isDebug = false; public MemoryRegion mappedMemoryRegion = null; public Section Clone() { Section ret = new Section(); alignment = alignment; combinedName = combinedName; if (data != null) { data = data.Clone(); } fileOffset = fileOffset; flags = flags.Clone(); id = id; isDebug = isDebug; isRAM = isRAM; isROM = isROM; loadMemoryAddress = loadMemoryAddress; name = name; size = size; sourceFile = sourceFile; if (symbols != null) { symbols = new ArrayList(symbols.size()); symbolsByAddr = new HashMap(symbols.size()); symbolsByName = new HashMap(symbols.size()); for (int i = 0; i < symbols.size(); i++) { Symbol s = ((Symbol)symbols.get(i)).Clone(); symbolsByAddr.put(Long.valueOf(address), s); symbolsByName.put(name, s); symbols.add(s); } } virtualMemoryAddress = virtualMemoryAddress; mappedMemoryRegion = (mappedMemoryRegion == null ? null : mappedMemoryRegion.clone()); return ret; } public Section() {} public Section(String obj_dump_line) { try { String[] dump = obj_dump_line.split("[\\s]+?"); List<String> allFlags = new ArrayList(); int i = 0; for (String s : dump) { if (s.length() != 0) { switch (i++) { case 0: id = Integer.decode(s).intValue(); break; case 1: name = s; break; case 2: size = Long.parseLong(s, 16); break; case 3: virtualMemoryAddress = Long.parseLong(s, 16); break; case 4: loadMemoryAddress = Long.parseLong(s, 16); break; case 5: fileOffset = Long.parseLong(s, 16); break; case 6: alignment = (0x2 ^ Integer.parseInt(s.substring(s.lastIndexOf('*') + 1))); break; default: s = s.toUpperCase(); allFlags.add(s + " "); if (s.endsWith(",")) { s = s.substring(0, s.length() - 1); } switch (s) { case "CONTENTS": flags.CONTENTS = true; break; case "ALLOC": flags.ALLOC = true; break; case "LOAD": flags.LOAD = true; break; case "CODE": flags.CODE = true; break; case "ABSOLUTE": flags.ABSOLUTE = true; break; case "DEBUGGING": flags.DEBUGGING = true; break; case "DATA": flags.DATA = true; break; case "NEVER_LOAD": flags.NEVER_LOAD = true; break; case "PERSIST": flags.PERSIST = true; break; case "PSV": flags.PSV = true; break; case "PAGE": flags.PAGE = true; break; case "READONLY": flags.READONLY = true; break; case "EDS": flags.EDS = true; break; case "RELOC": flags.RELOC = true; break; case "NEAR": flags.NEAR = true; break; case "REVERSE": flags.REVERSE = true; break; case "SECURE": flags.SECURE = true; break; case "XMEMORY": flags.XMEMORY = true; break; case "YMEMORY": flags.YMEMORY = true; break; case "MEMORY": flags.MEMORY = true; break; case "PACKEDFLASH": flags.PACKEDFLASH = true; break; case "PRESERVED": flags.PRESERVED = true; break; case "UPDATE": flags.UPDATE = true; break; case "LINK_ONCE_SAME_SIZE": flags.LINK_ONCE_SAME_SIZE = true; break; default: SectionFlags tmp1379_1376 = flags;13791376unknown = (13791376unknown + "," + s); } break; } } } if (!flags.unknown.isEmpty()) { flags.unknown = flags.unknown.substring(1); } flags.wholeString = Multifunction.CatStringList(allFlags); if (flags.wholeString.endsWith(" ")) { flags.wholeString = flags.wholeString.substring(0, flags.wholeString.length() - 1); } isDebug = ((flags.DEBUGGING) || ((loadMemoryAddress == 0L) && (virtualMemoryAddress == 0L) && (size == 0L)) || (name.equals(".mdebug.abi32")) || (name.equals(".gnu.attributes")) || (name.equals(".reginfo")) || (name.equals(".comment")) || (name.equals(".info.EZBL_KeepSYM"))); isROM = ((!flags.DEBUGGING) && (((flags.CODE) && (flags.READONLY)) || (flags.PSV) || (flags.PAGE) || (flags.PACKEDFLASH) || ((loadMemoryAddress & 0xFFC00000) == 486539264L) || ((loadMemoryAddress & 0xFFC00000) == 532676608L) || ((loadMemoryAddress & 0xFFC00000) == 2634022912L) || ((loadMemoryAddress & 0xFFC00000) == 2680160256L))); isRAM = ((!isROM) && ((flags.DATA) || (flags.NEAR) || (flags.EDS) || (flags.MEMORY) || (flags.PERSIST) || (flags.XMEMORY) || (flags.YMEMORY) || (flags.REVERSE) || ((loadMemoryAddress & 0xFFC00000) == 2147483648L) || ((loadMemoryAddress & 0xFFC00000) == 2684354560L))); if ((!isDebug) && (!isROM) && (!isRAM) && ((flags.CODE) || (name.startsWith(".text")) || (name.startsWith(".ivt")) || (name.startsWith(".const")) || (name.startsWith("reserve_boot_")))) isROM = true; if ((!isDebug) && (!isROM) && (!isRAM) && ((name.startsWith(".bss")) || (name.startsWith(".pbss")) || (name.startsWith(".nbss")) || (name.startsWith(".data")) || (name.startsWith("reserve_data_")) || ((flags.ALLOC) && (!flags.CONTENTS)))) isRAM = true; if ((!isDebug) && (!isROM) && (!isRAM)) { isDebug = true; } if ((flags.READONLY) && (((loadMemoryAddress & 0x1FC00000) == 532676608L) || ((loadMemoryAddress & 0x1FC00000) == 486539264L))) { isRAM = false; isROM = true; flags.DATA = false; flags.CODE = true; } } catch (NumberFormatException ex) { name = null; } } public int compareTo(Section y) { return loadMemoryAddress == loadMemoryAddress ? 0 : loadMemoryAddress < loadMemoryAddress ? -1 : 1; } public MemoryRegion mapToDeviceRegion(List<MemoryRegion> deviceRegions, MemoryRegion.Partition sectionPartition) { MemoryRegion ret = new MemoryRegion(loadMemoryAddress, loadMemoryAddress + size); partition = sectionPartition; if (data != null) { name = data.assignedMemory; endAddr = data.getEndAddress(); } if ((isDebug) || (isRAM) || (sectionPartition == null)) { sectionPartition = MemoryRegion.Partition.single; } if ((startAddr & 0xFFC00000) == 2684354560L) { startAddr ^= 0x20000000; endAddr ^= 0x20000000; } if ((startAddr & 0xFFC00000) == 486539264L) { startAddr |= 0x80000000; endAddr |= 0x80000000; } if (((startAddr & 0x7FC00000) == 532676608L) || ((startAddr & 0x7FC00000) == 528482304L)) { startAddr |= 0xA0000000; endAddr |= 0xA0000000; } MemoryRegion.Partition p = sectionPartition; for (;;) { for (MemoryRegion mr : deviceRegions) { if ((startAddr < endAddr) && (endAddr > startAddr) && (partition == p)) { if (((isDebug) && (mr.isDebugSpace())) || ((isRAM) && (mr.isDataSpace())) || ((isROM) && (mr.isProgSpace()))) { ret.copyMetaData(mr); if ((data != null) && (data.getEndAddress() > endAddr)) endAddr = endAddr; if (startAddr >= startAddr) { return ret; } } } } for (MemoryRegion mr : deviceRegions) { if (partition == p) { if (((isDebug) && (mr.isDebugSpace())) || ((isRAM) && (mr.isDataSpace())) || ((isROM) && (mr.isProgSpace()))) { if ((endAddr > startAddr) && (startAddr < endAddr)) { endAddr = startAddr; } if (startAddr == endAddr) { ret.copyMetaData(mr); comment = "no-device-mem-defined"; } } } } if (isDebug) type = MemoryRegion.MemType.DEBUG; if ((isRAM) && (!ret.isDataSpace())) { type = MemoryRegion.MemType.RAM; eraseAlign = 1; programAlign = 1; } if ((isROM) && (!ret.isProgSpace())) { type = MemoryRegion.MemType.ROM; } if (p == MemoryRegion.Partition.single) break; p = MemoryRegion.Partition.single; } return ret; } public void normalizePIC32Addresses() { if ((loadMemoryAddress & 0xFFC00000) == 2684354560L) { loadMemoryAddress ^= 0x20000000; } if ((loadMemoryAddress & 0x7FC00000) == 486539264L) { loadMemoryAddress |= 0x80000000; } if ((loadMemoryAddress & 0x7FC00000) == 532676608L) { loadMemoryAddress |= 0xA0000000; } if (symbols != null) { for (Symbol s : symbols) { if ((address & 0xFFC00000) == 2684354560L) { address ^= 0x20000000; } if ((address & 0x7FC00000) == 486539264L) { address |= 0x80000000; } if ((address & 0x7FC00000) == 532676608L) { address |= 0xA0000000; } } for (Symbol s : symbolsByAddr.values()) { symbolsByAddr.put(Long.valueOf(address), s); } } } public boolean nameMatchesRegEx(List<String> regExpressions) { if (regExpressions == null) { return false; } for (String regEx : regExpressions) { if (name.matches(regEx)) { return true; } } return false; } public static List<AddressRange> convertToAddressRanges(List<Section> sections) { List<AddressRange> ret = new ArrayList(); for (Section sec : sections) { ret.add(new AddressRange(loadMemoryAddress, loadMemoryAddress + size)); } return ret; } public static List<DataRecord> convertToDataRecords(List<Section> sections) { List<DataRecord> ret = new ArrayList(); boolean architectureIs16Bit = false; for (Section sec : sections) { if (data != null) { if (data.architecture16Bit) { architectureIs16Bit = true; break; } } } for (Section sec : sections) { DataRecord dr = data; if (dr == null) { dr = new DataRecord(); address = loadMemoryAddress; architecture16Bit = architectureIs16Bit; data = new byte[(int)((isROM) && (architecture16Bit) ? size / 2L * 3L : size)]; Arrays.fill(data, (byte)-1); } ret.add(dr); } return ret; } public long getLoadMemoryAddress() { return loadMemoryAddress; } public void setLoadMemoryAddress(long loadMemoryAddress) { this.loadMemoryAddress = loadMemoryAddress; } public DataRecord getData() { return data; } public void setData(DataRecord data) { this.data = data; } public Section Split(long splitAddress) { if (loadMemoryAddress + size > splitAddress) { Section newRight = Clone(); if (data != null) { data = data.SplitAtAddress(splitAddress); } size = (loadMemoryAddress + size - splitAddress); size -= size; loadMemoryAddress += size; virtualMemoryAddress += size; return newRight; } return null; } void LoadSymbols(List<Symbol> symbols) { this.symbols = new ArrayList(); symbolsByAddr = new TreeMap(); symbolsByName = new TreeMap(); for (Symbol sym : symbols) { if (((data != null) && (!data.architecture16Bit)) || ((address & 0xFF000000) != 0L)) { sym.normalizePIC32Addresses(); } if (section.equals(name)) { if (name.matches("[_A-Za-z0-9]*$")) { symbolsByAddr.put(Long.valueOf(address), sym); symbolsByName.put(name, sym); this.symbols.add(sym); } } if (flags.debugging) { if (sourceFile == null) { if (address == virtualMemoryAddress) { sourceFile = probableFile; } } } } } void addSymbol(Symbol sym) { if (!symbols.contains(sym)) symbols.add(sym); symbolsByAddr.put(Long.valueOf(address), sym); symbolsByName.put(name, sym); } void addAllSymbols(Collection<Symbol> symbols) { for (Symbol s : symbols) { addSymbol(s); } } boolean LoadSectionContents(String elfSectionDump) { List<DataRecord> lines = new ArrayList(); String searchString = "Contents of section " + name + ":\n"; int possibleSectionStartIndex = 0; for (;;) { possibleSectionStartIndex = elfSectionDump.indexOf(searchString, possibleSectionStartIndex); if (possibleSectionStartIndex < 0) { break; } possibleSectionStartIndex += searchString.length(); int endOffset = elfSectionDump.indexOf("\nC", possibleSectionStartIndex); if (endOffset < 0) { endOffset = elfSectionDump.length(); } String sectionContents = elfSectionDump.substring(possibleSectionStartIndex, endOffset); int startIndex = 1; int eolIndex = 0; while (eolIndex >= 0) { int dataSeperatorIndex = sectionContents.indexOf(' ', startIndex + 1); if (dataSeperatorIndex < 0) { break; } int asciiPrintIndex = sectionContents.indexOf(" ", dataSeperatorIndex + 1); if (asciiPrintIndex < 0) { break; } int wordByteCount = (sectionContents.indexOf(' ', dataSeperatorIndex + 1) - dataSeperatorIndex) / 2; eolIndex = sectionContents.indexOf('\n', asciiPrintIndex + 2); long address = Integer.decode("0x" + sectionContents.substring(startIndex, dataSeperatorIndex)).intValue(); startIndex = eolIndex + 2; if ((loadMemoryAddress > address) || (loadMemoryAddress + size < address)) { break; } String encodedData = sectionContents.substring(dataSeperatorIndex + 1, asciiPrintIndex); encodedData = encodedData.replaceAll(" ", ""); int dataCount = encodedData.length() / 2; byte[] data = new byte[dataCount]; for (int i = 0; i < dataCount; i++) { data[i] = ((byte)(Integer.decode("0x" + encodedData.substring(i * 2, i * 2 + 2)).intValue() & 0xFF)); } DataRecord dr = new DataRecord(address, data, wordByteCount == 3); lines.add(dr); } } DataRecord.CoalesceRecords(lines); if (lines.isEmpty()) { return false; } this.data = ((DataRecord)lines.get(0)); return lines.size() == 1; } byte[] GetHash() { Section cleanSection = Clone(); id = 0; fileOffset = 0L; sourceFile = null; combinedName = null; ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); ObjectOutput objectOut = null; try { objectOut = new ObjectOutputStream(byteStream); objectOut.writeObject(this); byte[] thisClassBytes = byteStream.toByteArray(); objectOut.close(); try { MessageDigest hashComputer = MessageDigest.getInstance("SHA-256"); return hashComputer.digest(thisClassBytes); } catch (NoSuchAlgorithmException ex) { System.err.println(" EZBL: ERROR! Can't find 'SHA-256' hash algorithm. Make sure your JRE includes SHA-256 support."); return null; } return null; } catch (IOException ex) {} } public static List<MemoryRegion> getMappedMemoryRegions(List<Section> sectionList) { List<MemoryRegion> ret = new ArrayList(); for (Section s : sectionList) { ret.add(mappedMemoryRegion); } return ret; } public AddressRange GetLoadAddressRange() { return new AddressRange(loadMemoryAddress, loadMemoryAddress + getSize()); } public AddressRange GetVirtualAddressRange() { return new AddressRange(virtualMemoryAddress, virtualMemoryAddress + getSize()); } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCombinedName() { return combinedName; } public void setCombinedName(String combinedName) { this.combinedName = combinedName; } public String getSourceFile() { return sourceFile; } public void setSourceFile(String sourceFile) { this.sourceFile = sourceFile; } public long getSize() { return size; } public void setSize(long size) { this.size = size; } public long getVirtualMemoryAddress() { return virtualMemoryAddress; } public void setVirtualMemoryAddress(long virtualMemoryAddress) { this.virtualMemoryAddress = virtualMemoryAddress; } public long getloadMemoryAddress() { return loadMemoryAddress; } public void setloadMemoryAddress(long loadMemoryAddress) { this.loadMemoryAddress = loadMemoryAddress; } public long getFileOffset() { return fileOffset; } public void setFileOffset(long fileOffset) { this.fileOffset = fileOffset; } public int getAlignment() { return alignment; } public void setAlignment(int alignment) { this.alignment = alignment; } public SectionFlags getFlags() { return flags; } public void setFlags(SectionFlags flags) { this.flags = flags; } public List<Symbol> getSymbols() { return symbols; } public void setSymbols(List<Symbol> symbols) { this.symbols = symbols; } public boolean isIsROM() { return isROM; } public void setIsROM(boolean isROM) { this.isROM = isROM; } public boolean isIsRAM() { return isRAM; } public void setIsRAM(boolean isRAM) { this.isRAM = isRAM; } public boolean isIsDebug() { return isDebug; } public void setIsDebug(boolean isDebug) { this.isDebug = isDebug; } }
412
0.948255
1
0.948255
game-dev
MEDIA
0.198111
game-dev
0.954468
1
0.954468
ParadiseSS13/Paradise
1,545
code/modules/projectiles/guns/energy/telegun.dm
// Telegun for Tator RDs /obj/item/gun/energy/telegun name = "teleporter gun" desc = "An extremely high-tech energy gun that utilizes jury-rigged bluespace technology to teleport away living targets." icon_state = "telegun" inhand_icon_state = "telegun" origin_tech = "combat=6;materials=7;powerstorage=5;bluespace=5;syndicate=4" ammo_type = list(/obj/item/ammo_casing/energy/teleport) shaded_charge = TRUE var/teleport_target = null /obj/item/gun/energy/telegun/Destroy() teleport_target = null return ..() /obj/item/gun/energy/telegun/attack_self__legacy__attackchain(mob/living/user) var/list/L = list() var/list/areaindex = list() for(var/obj/item/beacon/R in GLOB.beacons) var/turf/T = get_turf(R) var/turf/M = get_turf(user) if(!T) continue if(!is_teleport_allowed(T.z)) continue if(T.z != M.z && !R.emagged) continue var/tmpname = T.loc.name if(areaindex[tmpname]) tmpname = "[tmpname] ([++areaindex[tmpname]])" else areaindex[tmpname] = 1 L[tmpname] = R var/desc = tgui_input_list(user, "Please select a location to lock in.", "Telegun Target Selection", L) if(!desc) return teleport_target = L[desc] to_chat(user, "<span class='notice'>The [src] is now set to [desc].</span>") //Process the shot without draining the cell if(chambered) if(chambered.BB) qdel(chambered.BB) chambered.BB = null chambered = null newshot() /obj/item/gun/energy/telegun/newshot() var/obj/item/ammo_casing/energy/teleport/T = ammo_type[select] T.teleport_target = teleport_target ..()
412
0.978508
1
0.978508
game-dev
MEDIA
0.986766
game-dev
0.991311
1
0.991311
ecilasun/tinysys
11,274
software/samples/quake/winquake/cl_input.c
/* Copyright (C) 1996-1997 Id Software, Inc. 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. */ // cl.input.c -- builds an intended movement command to send to the server // Quake is a trademark of Id Software, Inc., (c) 1996 Id Software, Inc. All // rights reserved. #include "quakedef.h" /* =============================================================================== KEY BUTTONS Continuous button event tracking is complicated by the fact that two different input sources (say, mouse button 1 and the control key) can both press the same button, but the button should only be released when both of the pressing key have been released. When a key event issues a button command (+forward, +attack, etc), it appends its key number as a parameter to the command so it can be matched up with the release. state bit 0 is the current state of the key state bit 1 is edge triggered on the up to down transition state bit 2 is edge triggered on the down to up transition =============================================================================== */ kbutton_t in_mlook, in_klook; kbutton_t in_left, in_right, in_forward, in_back; kbutton_t in_lookup, in_lookdown, in_moveleft, in_moveright; kbutton_t in_strafe, in_speed, in_use, in_jump, in_attack; kbutton_t in_up, in_down; int in_impulse; void KeyDown (kbutton_t *b) { int k; char *c; c = Cmd_Argv(1); if (c[0]) k = atoi(c); else k = -1; // typed manually at the console for continuous down if (k == b->down[0] || k == b->down[1]) return; // repeating key if (!b->down[0]) b->down[0] = k; else if (!b->down[1]) b->down[1] = k; else { Con_Printf ("Three keys down for a button!\n"); return; } if (b->state & 1) return; // still down b->state |= 1 + 2; // down + impulse down } void KeyUp (kbutton_t *b) { int k; char *c; c = Cmd_Argv(1); if (c[0]) k = atoi(c); else { // typed manually at the console, assume for unsticking, so clear all b->down[0] = b->down[1] = 0; b->state = 4; // impulse up return; } if (b->down[0] == k) b->down[0] = 0; else if (b->down[1] == k) b->down[1] = 0; else return; // key up without coresponding down (menu pass through) if (b->down[0] || b->down[1]) return; // some other key is still holding it down if (!(b->state & 1)) return; // still up (this should not happen) b->state &= ~1; // now up b->state |= 4; // impulse up } void IN_KLookDown (void) {KeyDown(&in_klook);} void IN_KLookUp (void) {KeyUp(&in_klook);} void IN_MLookDown (void) {KeyDown(&in_mlook);} void IN_MLookUp (void) { KeyUp(&in_mlook); if ( !(in_mlook.state&1) && lookspring.value) V_StartPitchDrift(); } void IN_UpDown(void) {KeyDown(&in_up);} void IN_UpUp(void) {KeyUp(&in_up);} void IN_DownDown(void) {KeyDown(&in_down);} void IN_DownUp(void) {KeyUp(&in_down);} void IN_LeftDown(void) {KeyDown(&in_left);} void IN_LeftUp(void) {KeyUp(&in_left);} void IN_RightDown(void) {KeyDown(&in_right);} void IN_RightUp(void) {KeyUp(&in_right);} void IN_ForwardDown(void) {KeyDown(&in_forward);} void IN_ForwardUp(void) {KeyUp(&in_forward);} void IN_BackDown(void) {KeyDown(&in_back);} void IN_BackUp(void) {KeyUp(&in_back);} void IN_LookupDown(void) {KeyDown(&in_lookup);} void IN_LookupUp(void) {KeyUp(&in_lookup);} void IN_LookdownDown(void) {KeyDown(&in_lookdown);} void IN_LookdownUp(void) {KeyUp(&in_lookdown);} void IN_MoveleftDown(void) {KeyDown(&in_moveleft);} void IN_MoveleftUp(void) {KeyUp(&in_moveleft);} void IN_MoverightDown(void) {KeyDown(&in_moveright);} void IN_MoverightUp(void) {KeyUp(&in_moveright);} void IN_SpeedDown(void) {KeyDown(&in_speed);} void IN_SpeedUp(void) {KeyUp(&in_speed);} void IN_StrafeDown(void) {KeyDown(&in_strafe);} void IN_StrafeUp(void) {KeyUp(&in_strafe);} void IN_AttackDown(void) {KeyDown(&in_attack);} void IN_AttackUp(void) {KeyUp(&in_attack);} void IN_UseDown (void) {KeyDown(&in_use);} void IN_UseUp (void) {KeyUp(&in_use);} void IN_JumpDown (void) {KeyDown(&in_jump);} void IN_JumpUp (void) {KeyUp(&in_jump);} void IN_Impulse (void) {in_impulse=Q_atoi(Cmd_Argv(1));} /* =============== CL_KeyState Returns 0.25 if a key was pressed and released during the frame, 0.5 if it was pressed and held 0 if held then released, and 1.0 if held for the entire time =============== */ float CL_KeyState (kbutton_t *key) { float val; qboolean impulsedown, impulseup, down; impulsedown = key->state & 2; impulseup = key->state & 4; down = key->state & 1; val = 0; if (impulsedown && !impulseup) { if (down) val = 0.5; // pressed and held this frame else val = 0; // I_Error (); } if (impulseup && !impulsedown) { if (down) val = 0; // I_Error (); else val = 0; // released this frame } if (!impulsedown && !impulseup) { if (down) val = 1.0; // held the entire frame else val = 0; // up the entire frame } if (impulsedown && impulseup) { if (down) val = 0.75; // released and re-pressed this frame else val = 0.25; // pressed and released this frame } key->state &= 1; // clear impulses return val; } //========================================================================== cvar_t cl_upspeed = {"cl_upspeed","200"}; cvar_t cl_forwardspeed = {"cl_forwardspeed","200", true}; cvar_t cl_backspeed = {"cl_backspeed","200", true}; cvar_t cl_sidespeed = {"cl_sidespeed","350"}; cvar_t cl_movespeedkey = {"cl_movespeedkey","2.0"}; cvar_t cl_yawspeed = {"cl_yawspeed","140"}; cvar_t cl_pitchspeed = {"cl_pitchspeed","150"}; cvar_t cl_anglespeedkey = {"cl_anglespeedkey","1.5"}; /* ================ CL_AdjustAngles Moves the local angle positions ================ */ void CL_AdjustAngles (void) { float speed; float up, down; float _host_frametime = host_frametime; if (in_speed.state & 1) speed = _host_frametime * cl_anglespeedkey.value; else speed = _host_frametime; if (!(in_strafe.state & 1)) { cl.viewangles[YAW] -= speed*cl_yawspeed.value*CL_KeyState (&in_right); cl.viewangles[YAW] += speed*cl_yawspeed.value*CL_KeyState (&in_left); cl.viewangles[YAW] = anglemod(cl.viewangles[YAW]); } if (in_klook.state & 1) { V_StopPitchDrift (); cl.viewangles[PITCH] -= speed*cl_pitchspeed.value * CL_KeyState (&in_forward); cl.viewangles[PITCH] += speed*cl_pitchspeed.value * CL_KeyState (&in_back); } up = CL_KeyState (&in_lookup); down = CL_KeyState(&in_lookdown); cl.viewangles[PITCH] -= speed*cl_pitchspeed.value * up; cl.viewangles[PITCH] += speed*cl_pitchspeed.value * down; if (up || down) V_StopPitchDrift (); if (cl.viewangles[PITCH] > 80) cl.viewangles[PITCH] = 80; if (cl.viewangles[PITCH] < -70) cl.viewangles[PITCH] = -70; if (cl.viewangles[ROLL] > 50) cl.viewangles[ROLL] = 50; if (cl.viewangles[ROLL] < -50) cl.viewangles[ROLL] = -50; } /* ================ CL_BaseMove Send the intended movement message to the server ================ */ void CL_BaseMove (usercmd_t *cmd) { if (cls.signon != SIGNONS) return; CL_AdjustAngles (); Q_memset (cmd, 0, sizeof(*cmd)); if (in_strafe.state & 1) { cmd->sidemove += cl_sidespeed.value * CL_KeyState (&in_right); cmd->sidemove -= cl_sidespeed.value * CL_KeyState (&in_left); } cmd->sidemove += cl_sidespeed.value * CL_KeyState (&in_moveright); cmd->sidemove -= cl_sidespeed.value * CL_KeyState (&in_moveleft); cmd->upmove += cl_upspeed.value * CL_KeyState (&in_up); cmd->upmove -= cl_upspeed.value * CL_KeyState (&in_down); if (! (in_klook.state & 1) ) { cmd->forwardmove += cl_forwardspeed.value * CL_KeyState (&in_forward); cmd->forwardmove -= cl_backspeed.value * CL_KeyState (&in_back); } // // adjust for speed key // if (in_speed.state & 1) { cmd->forwardmove *= cl_movespeedkey.value; cmd->sidemove *= cl_movespeedkey.value; cmd->upmove *= cl_movespeedkey.value; } #ifdef QUAKE2 cmd->lightlevel = cl.light_level; #endif } /* ============== CL_SendMove ============== */ void CL_SendMove (usercmd_t *cmd) { int i; int bits; sizebuf_t buf; byte data[128]; buf.maxsize = 128; buf.cursize = 0; buf.data = data; cl.cmd = *cmd; // // send the movement message // MSG_WriteByte (&buf, clc_move); MSG_WriteFloat (&buf, cl.mtime[0]); // so server can get ping times for (i=0 ; i<3 ; i++) MSG_WriteAngle (&buf, cl.viewangles[i]); MSG_WriteShort (&buf, cmd->forwardmove); MSG_WriteShort (&buf, cmd->sidemove); MSG_WriteShort (&buf, cmd->upmove); // // send button bits // bits = 0; if ( in_attack.state & 3 ) bits |= 1; in_attack.state &= ~2; if (in_jump.state & 3) bits |= 2; in_jump.state &= ~2; MSG_WriteByte (&buf, bits); MSG_WriteByte (&buf, in_impulse); in_impulse = 0; #ifdef QUAKE2 // // light level // MSG_WriteByte (&buf, cmd->lightlevel); #endif // // deliver the message // if (cls.demoplayback) return; // // allways dump the first two message, because it may contain leftover inputs // from the last level // if (++cl.movemessages <= 2) return; if (NET_SendUnreliableMessage (cls.netcon, &buf) == -1) { Con_Printf ("CL_SendMove: lost server connection\n"); CL_Disconnect (); } } /* ============ CL_InitInput ============ */ void CL_InitInput (void) { Cmd_AddCommand ("+moveup",IN_UpDown); Cmd_AddCommand ("-moveup",IN_UpUp); Cmd_AddCommand ("+movedown",IN_DownDown); Cmd_AddCommand ("-movedown",IN_DownUp); Cmd_AddCommand ("+left",IN_LeftDown); Cmd_AddCommand ("-left",IN_LeftUp); Cmd_AddCommand ("+right",IN_RightDown); Cmd_AddCommand ("-right",IN_RightUp); Cmd_AddCommand ("+forward",IN_ForwardDown); Cmd_AddCommand ("-forward",IN_ForwardUp); Cmd_AddCommand ("+back",IN_BackDown); Cmd_AddCommand ("-back",IN_BackUp); Cmd_AddCommand ("+lookup", IN_LookupDown); Cmd_AddCommand ("-lookup", IN_LookupUp); Cmd_AddCommand ("+lookdown", IN_LookdownDown); Cmd_AddCommand ("-lookdown", IN_LookdownUp); Cmd_AddCommand ("+strafe", IN_StrafeDown); Cmd_AddCommand ("-strafe", IN_StrafeUp); Cmd_AddCommand ("+moveleft", IN_MoveleftDown); Cmd_AddCommand ("-moveleft", IN_MoveleftUp); Cmd_AddCommand ("+moveright", IN_MoverightDown); Cmd_AddCommand ("-moveright", IN_MoverightUp); Cmd_AddCommand ("+speed", IN_SpeedDown); Cmd_AddCommand ("-speed", IN_SpeedUp); Cmd_AddCommand ("+attack", IN_AttackDown); Cmd_AddCommand ("-attack", IN_AttackUp); Cmd_AddCommand ("+use", IN_UseDown); Cmd_AddCommand ("-use", IN_UseUp); Cmd_AddCommand ("+jump", IN_JumpDown); Cmd_AddCommand ("-jump", IN_JumpUp); Cmd_AddCommand ("impulse", IN_Impulse); Cmd_AddCommand ("+klook", IN_KLookDown); Cmd_AddCommand ("-klook", IN_KLookUp); Cmd_AddCommand ("+mlook", IN_MLookDown); Cmd_AddCommand ("-mlook", IN_MLookUp); }
412
0.859265
1
0.859265
game-dev
MEDIA
0.880001
game-dev
0.988698
1
0.988698
forcedotcom/aura
10,698
aura-components/src/main/components/ui/menuList/menuListHelper.js
/* * Copyright (C) 2013 salesforce.com, inc. * * 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. */ ({ setEventHandlersOnChildren: function(component) { var concrete = component.getConcreteComponent(); var children = []; var existingChildren = concrete.get("v.childMenuItems") || []; this.setHandlersOnMenuItems(concrete, concrete.get("v.body"), children, existingChildren); var items = component.find("item"); if (items && $A.util.isArray(items)) { this.setHandlersOnMenuItems(concrete, items, children, existingChildren); } concrete.set("v.childMenuItems", children); }, setHandlersOnMenuItems: function(component, items, children, existingChildren) { for (var i = 0; i < items.length; i++) { var child = items[i]; if (child.isInstanceOf("ui:menuItem")) { if (existingChildren && existingChildren.indexOf(child) === -1) { child.addHandler("menuSelect", component, "c.onMenuItemSelected"); } children.push(child); } else if (child.isInstanceOf("aura:iteration") || child.isInstanceOf("aura:if")) { this.setHandlersOnMenuItems(component, child.get("v.body"), children, existingChildren); } else if (child.isInstanceOf("ui:menuListProvider")) { this.setHandlersOnMenuItems(component, child.getSuper().get("v.body"), children, existingChildren); } else if (child.isInstanceOf("aura:expression")) { this.setHandlersOnMenuItems(component, child.get("v.value"), children, existingChildren); } } }, getMenuItem: function(component, index) { var menuItems = component.get("v.childMenuItems"); if (menuItems) { return menuItems[index]; } }, handleVisible : function(component) { var elements = this.getElementCache(component), visible = elements.target.get("v.visible"); if ($A.util.hasClass(elements.targetElement, "visible") === visible) { return; } if (visible === true) { $A.util.addClass(elements.targetElement, "visible"); elements.target.get("e.menuExpand").fire(); } else { $A.util.removeClass(elements.targetElement, "visible"); elements.target.get("e.menuCollapse").fire(); } }, setMenuItemFocus: function(component, index) { var menuItem = this.getMenuItem(component, index); if (menuItem && menuItem.isValid() && menuItem.getElement()) { // We have to set a timeout here, so that // the menu items get positioned before we set focus. // for more info see : W-4319141 setTimeout($A.getCallback(function setFocus() { menuItem.setFocus(); this.fireMenuFocusChangeEvent(component, null, menuItem); }).bind(this), 5); } }, setKeyboardEventHandlers: function(component) { var el = component.find("datalist").getElement(); $A.util.on(el, "keydown", this.getKeyboardInteractionHandler(component)); }, removeKeyboardEventHandlers: function(component) { var el = component.find("datalist").getElement(); $A.util.removeOn(el, "keydown", this.getKeyboardInteractionHandler(component)); delete component._keyboardEventHandler; }, /** * Handle keyboard interactions * */ getKeyboardInteractionHandler: function(component) { var helper = this; if (!component._keyboardEventHandler) { component._keyboardEventHandler = function(event) { // @dval: There a multiple corner cases // were we might endup in the wrong branch // Make this more robust once we refactor this component var concreteCmp = component.getConcreteComponent(); if (event.type === "keydown") { if (event.keyCode === 40) { // down arrow key event.preventDefault(); helper.setFocusToNextItem(concreteCmp, event); } else if (event.keyCode === 38) { // up arrow key event.preventDefault(); helper.setFocusToPreviousItem(concreteCmp, event); } else if (event.keyCode === 27) { // Esc key event.stopPropagation(); helper.handleEsckeydown(concreteCmp, event); } else if (event.keyCode === 9) { // tab key: dismiss the menu helper.handleTabkeydown(concreteCmp, event); } else { helper.setFocusToTypingChars(concreteCmp, event); } } }; } return component._keyboardEventHandler; }, handleEsckeydown: function(component) { component.getConcreteComponent().get("e.doClose").fire(); // put the focus back to menu trigger this.setFocusToTrigger(component); }, setFocusToTrigger: function(component) { var action = component.get("v.focusTrigger"); if (action) { action.runDeprecated(); } }, setFocusToNextItem: function(component, event) { var nextIndex = 0; var menuItems = component.get("v.childMenuItems"); if (event) { var srcComponent = this.getComponentForElement(event.target || event.srcElement); for (var i = 0; i < menuItems.length; i++) { if (srcComponent === menuItems[i]) { nextIndex = ++i; break; } } if (nextIndex >= menuItems.length) { nextIndex = 0; } } var nextFocusCmp = menuItems[nextIndex]; nextFocusCmp.setFocus(); this.fireMenuFocusChangeEvent(component, srcComponent, nextFocusCmp); }, setFocusToPreviousItem: function(component, event) { var previousIndex = 0; var srcComponent = this.getComponentForElement(event.target || event.srcElement); var menuItems = component.get("v.childMenuItems"); for (var i = 0; i < menuItems.length; i++) { if (srcComponent === menuItems[i]) { previousIndex = --i; break; } } if (previousIndex < 0) { previousIndex = menuItems.length - 1; } var previousFocusCmp = menuItems[previousIndex]; previousFocusCmp.setFocus(); this.fireMenuFocusChangeEvent(component, srcComponent, previousFocusCmp); }, fireMenuFocusChangeEvent: function(component, previousItem, currentItem) { var event = component.getEvent("menuFocusChange"); event.setParams({ "previousItem": previousItem, "currentItem": currentItem }); event.fire(); }, /** * Dismiss the menu when tab key is pressed. */ handleTabkeydown: function(component) { var closeOnTab = component.get('v.closeOnTabKey'); var concreteComponent = component.getConcreteComponent(); if (concreteComponent && closeOnTab) { if (component.get("v.attachToBody")) { this.setFocusToTrigger(component); } concreteComponent.get("e.doClose").fire(); } }, /** * Focus on the item whose starting character(s) are what the end user types. * Copied from Accentjs dropdown component. */ setFocusToTypingChars: function(component, event) { // If we were going to clear what keys were typed, don't yet. if (!$A.util.isUndefinedOrNull(component._clearBufferId)) { clearTimeout(component._clearBufferId); } // Store the letter. var letter = String.fromCharCode(event.keyCode); component._keyBuffer = component._keyBuffer || []; component._keyBuffer.push(letter); // Try to select var srcComponent = this.getComponentForElement(event.target || event.srcElement); var matchText = component._keyBuffer.join("").toLowerCase(); var menuItems = component.get("v.childMenuItems"); for(var i = 0; i < menuItems.length; i++) { var c = menuItems[i]; var text = c.get("v.label"); if(text && text.toLowerCase().indexOf(matchText) === 0) { c.setFocus(); this.fireMenuFocusChangeEvent(component, srcComponent, c); break; } } component._clearBufferId = setTimeout(function clearKeyBuffer() { component._keyBuffer = []; }, 700); }, deselectSiblings: function(component, selectedItem) { var children = component.get("v.childMenuItems"); for (var i = 0; i < children.length; i++) { var c = children[i]; if (c.isInstanceOf("ui:radioMenuItem") && $A.util.getBooleanValue(c.get("v.selected")) && c.getGlobalId() !== selectedItem.getGlobalId()) { c.set("v.selected", false); break; } } }, onMenuItemSelected: function(component, event) { var concrete = component.getConcreteComponent(); var deselectSiblings = event.getParam("deselectSiblings"); if (deselectSiblings === true) { this.deselectSiblings(component, event.getSource()); } var hideMenu = event.getParam("hideMenu"); if (hideMenu === true) { concrete.set("v.visible", false); } var focusTrigger = event.getParam("focusTrigger"); if (focusTrigger === true) { this.setFocusToTrigger(component); } if (component.isValid()) { component.get("e.menuSelect").fire(event.getParams()); } }, /** * TODO: Need to walk up the tree to find the menuItem. menuItem could contain other components. */ getComponentForElement: function(element) { var htmlCmp = $A.componentService.getRenderingComponentForElement(element); return htmlCmp ? htmlCmp.getComponentValueProvider().getConcreteComponent() : null; } })// eslint-disable-line semi
412
0.939539
1
0.939539
game-dev
MEDIA
0.71675
game-dev,web-frontend
0.971028
1
0.971028
anatawa12/ForgeGradle-1.2
3,227
src/main/java/net/minecraftforge/gradle/json/JsonFactory.java
package net.minecraftforge.gradle.json; import com.google.common.base.Strings; import com.google.gson.*; import net.minecraftforge.gradle.json.LiteLoaderJson.VersionObject; import net.minecraftforge.gradle.json.version.AssetIndex; import net.minecraftforge.gradle.json.version.Version; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.Date; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; public class JsonFactory { public static final Gson GSON; static { GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapterFactory(new EnumAdaptorFactory()); builder.registerTypeAdapter(Date.class, new DateAdapter()); builder.registerTypeAdapter(File.class, new FileAdapter()); builder.registerTypeAdapter(VersionObject.class, new LiteLoaderJson.VersionAdapter()); builder.enableComplexMapKeySerialization(); builder.setPrettyPrinting(); GSON = builder.create(); } public static Version loadVersion(File json, File inheritanceDir) throws JsonSyntaxException, JsonIOException, IOException { FileReader reader = new FileReader(json); Version v = GSON.fromJson(reader, Version.class); reader.close(); if (!Strings.isNullOrEmpty(v.inheritsFrom)) { File parentFile = new File(inheritanceDir, v.inheritsFrom + ".json"); if (!parentFile.exists()) { throw new FileNotFoundException("Inherited json file (" + v.inheritsFrom + ") not found! Myabe you are running in offline mode?"); } Version parent = loadVersion(new File(inheritanceDir, v.inheritsFrom + ".json"), inheritanceDir); v.extendFrom(parent); } return v; } public static AssetIndex loadAssetsIndex(File json) throws JsonSyntaxException, JsonIOException, IOException { FileReader reader = new FileReader(json); AssetIndex a = GSON.fromJson(reader, AssetIndex.class); reader.close(); return a; } public static LiteLoaderJson loadLiteLoaderJson(File json) throws JsonSyntaxException, JsonIOException, IOException { FileReader reader = new FileReader(json); LiteLoaderJson a = GSON.fromJson(reader, LiteLoaderJson.class); reader.close(); return a; } public static MCVersionManifest loadMCVersionManifest(File json) throws JsonSyntaxException, JsonIOException, IOException { FileReader reader = new FileReader(json); MCVersionManifest a = GSON.fromJson(reader, MCVersionManifest.class); reader.close(); return a; } public static Map<String, MCInjectorStruct> loadMCIJson(File json) throws IOException { FileReader reader = new FileReader(json); Map<String, MCInjectorStruct> ret = new LinkedHashMap<>(); JsonObject object = (JsonObject) JsonParser.parseReader(reader); reader.close(); for (Entry<String, JsonElement> entry : object.entrySet()) { ret.put(entry.getKey(), GSON.fromJson(entry.getValue(), MCInjectorStruct.class)); } return ret; } }
412
0.873819
1
0.873819
game-dev
MEDIA
0.270854
game-dev
0.937113
1
0.937113
magefree/mage
2,044
Mage.Sets/src/mage/cards/s/SaprazzanCove.java
package mage.cards.s; import java.util.UUID; import mage.Mana; import mage.abilities.Ability; import mage.abilities.common.EntersBattlefieldTappedAbility; import mage.abilities.common.SimpleActivatedAbility; import mage.abilities.costs.common.RemoveVariableCountersSourceCost; import mage.abilities.costs.common.TapSourceCost; import mage.abilities.dynamicvalue.common.CountersSourceCount; import mage.abilities.dynamicvalue.common.GetXValue; import mage.abilities.effects.common.counter.AddCountersSourceEffect; import mage.abilities.mana.DynamicManaAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.Zone; import mage.counters.CounterType; /** * * @author anonymous */ public final class SaprazzanCove extends CardImpl { public SaprazzanCove(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.LAND},""); // Saprazzan Cove enters the battlefield tapped. this.addAbility(new EntersBattlefieldTappedAbility()); // {tap}: Put a storage counter on Saprazzan Cove. this.addAbility(new SimpleActivatedAbility(new AddCountersSourceEffect(CounterType.STORAGE.createInstance()), new TapSourceCost())); // {tap}, Remove any number of storage counters from Saprazzan Cove: Add {U} for each storage counter removed this way. Ability ability = new DynamicManaAbility( Mana.BlueMana(1), GetXValue.instance, new TapSourceCost(), "Add {U} for each storage counter removed this way", true, new CountersSourceCount(CounterType.STORAGE)); ability.addCost(new RemoveVariableCountersSourceCost(CounterType.STORAGE, "Remove any number of storage counters from {this}")); this.addAbility(ability); } private SaprazzanCove(final SaprazzanCove card) { super(card); } @Override public SaprazzanCove copy() { return new SaprazzanCove(this); } }
412
0.965543
1
0.965543
game-dev
MEDIA
0.876838
game-dev
0.9956
1
0.9956
Eranziel/foundryvtt-lancer
8,560
src/module/combat/lancer-combat.ts
/** * Overrides and extends the Combat class to use an activation model instead of * the standard ordered list of turns. {@link LancerCombat#activateCombatant} * is added to the interface. */ export class LancerCombat extends Combat { protected override _sortCombatants(a: LancerCombatant, b: LancerCombatant): number { // Sort by Players then Neutrals then Hostiles const dc = b.disposition - a.disposition; if (dc !== 0) return dc; return super._sortCombatants(a, b); } protected override async _preCreate( ...[data, options, user]: Parameters<Combat["_preCreate"]> ): Promise<boolean | void> { this.updateSource({ turn: null }); return super._preCreate(data, options, user); } async _manageTurnEvents(adjustedTurn: any) { // Avoid the Foundry bug where this is called on create, before this.previous is set. if (!this.previous) return; super._manageTurnEvents(adjustedTurn); } /** * Set all combatants to their max activations */ async resetActivations(): Promise<LancerCombatant[]> { const skipDefeated = "skipDefeated" in this.settings && this.settings.skipDefeated; const updates = this.combatants.map(c => { return { _id: c.id, [`flags.${game.system.id}.activations.value`]: skipDefeated && c.isDefeated ? 0 : (<LancerCombatant>c).activations.max ?? 0, }; }); return <Promise<LancerCombatant[]>>this.updateEmbeddedDocuments("Combatant", updates); } override async startCombat(): Promise<this> { this._playCombatSound("startEncounter"); const updateData = { round: 1, turn: null }; Hooks.callAll("combatStart", this, updateData); await this.resetActivations(); await this.update(updateData); return this; } override async nextRound(): Promise<this> { await this.resetActivations(); const updateData = { round: this.round + 1, turn: null }; let advanceTime = Math.max(this.turns.length - (this.turn || 0), 0) * CONFIG.time.turnTime; advanceTime += CONFIG.time.roundTime; const updateOptions = { advanceTime, direction: 1 }; Hooks.callAll("combatRound", this, updateData, updateOptions); await this.update(updateData, updateOptions as any); return this; } /** * Ends the current turn without starting a new one */ override async nextTurn(): Promise<this> { const updateData = { turn: null }; const updateOptions = { advanceTime: 0, direction: 0 }; Hooks.callAll("combatTurn", this, updateData, updateOptions); await this.update(updateData, updateOptions as any); return this; } override async previousRound(): Promise<this> { await this.resetActivations(); const round = Math.max(this.round - 1, 0); let advanceTime = 0; if (round > 0) advanceTime -= CONFIG.time.roundTime; const updateData = { round, turn: null }; const updateOptions = { advanceTime, direction: -1 }; Hooks.callAll("combatRound", this, updateData, updateOptions); await this.update(updateData, updateOptions as any); return this; } /** * End the current turn and refund the activation */ override async previousTurn() { if (this.turn === null) return this; const updateData = { turn: null }; const updateOptions = { advanceTime: -CONFIG.time.turnTime, direction: -1 }; await this.combatant?.modifyCurrentActivations(1); Hooks.callAll("combatTurn", this, updateData, updateOptions); await this.update(updateData, updateOptions as any); return this; } override async resetAll(): Promise<this> { await this.resetActivations(); this.combatants.forEach(c => c.updateSource({ initiative: null })); await this.update({ turn: null, combatants: this.combatants.toObject() }, { diff: false }); return this; } /** * Filter out next up turn notifications sound since the next up isn't deterministic */ override _playCombatSound(...[announcement]: Parameters<Combat["_playCombatSound"]>) { if (announcement === "nextUp") return; return super._playCombatSound(announcement); } /** * Sets the active turn to the combatant passed by id or calls * {@link LancerCombat#requestActivation()} if the user does not have * permission to modify the combat */ async activateCombatant(id: string, override = false): Promise<this | undefined> { if (!(game.user?.isGM || (this.turn == null && this.combatants.get(id)?.isOwner) || override)) return this.requestActivation(id); const combatant = <LancerCombatant | undefined>this.getEmbeddedDocument("Combatant", id, {}); if (!combatant?.activations.value) return this; await combatant?.modifyCurrentActivations(-1); const turn = this.turns.findIndex(t => t.id === id); const updateData = { turn }; const updateOptions = { advanceTime: CONFIG.time.turnTime, direction: 1 }; Hooks.callAll("combatTurn", this, updateData, updateOptions); return this.update(updateData, updateOptions as any); } /** * Sets the active turn back to 0 (no active unit) if the passed id * corresponds to the current turn and the user has ownership of the * combatant. */ async deactivateCombatant(id: string) { const turn = this.turns.findIndex(t => t.id === id); if (turn !== this.turn) return this; if (!this.turns[turn].testUserPermission(game.user!, "OWNER") && !game.user?.isGM) return this; return this.nextTurn(); } /** * Calls any Hooks registered for "LancerCombatRequestActivate". */ protected async requestActivation(id: string): Promise<this> { Hooks.callAll("LancerCombatRequestActivate", this, id); return this; } } export class LancerCombatant extends Combatant { /** * This just fixes a bug in foundry 0.8.x that prevents Combatants with no * associated token or actor from being modified, even by the GM */ override testUserPermission(...[user, permission, options]: Parameters<Combatant["testUserPermission"]>): boolean { return this.actor?.testUserPermission(user, permission, options) ?? user.isGM; } override prepareBaseData(): void { super.prepareBaseData(); if (this.flags?.[game.system.id]?.activations?.max === undefined && canvas?.ready) { const activations = foundry.utils.getProperty(this.actor?.getRollData() ?? {}, "activations") ?? 1; this.updateSource({ [`flags.${game.system.id}.activations`]: { max: activations, value: (this.parent?.round ?? 0) > 0 ? activations : 0, }, }); } this.initiative ??= 0; } /** * The current activation data for the combatant. */ get activations(): Activations { // @ts-expect-error FlagConfig not working return this.getFlag(game.system.id, "activations") ?? {}; } /** * The disposition for this combatant. In order, manually specified for this * combatant, token disposition, token disposition for the associated actor, * -2. */ get disposition(): number { const disposition = // @ts-expect-error FlagConfig not working <number>this.getFlag(game.system.id, "disposition") ?? this.token?.disposition ?? this.actor?.prototypeToken.disposition ?? -2; if (disposition === CONST.TOKEN_DISPOSITIONS.FRIENDLY && this.hasPlayerOwner) return 2; return disposition; } /** * Adjusts the number of activations that a combatant can take * @param num - The number of maximum activations to add (can be negative) */ async addActivations(num: number): Promise<this | undefined> { if (num === 0) return this; return this.update({ [`flags.${game.system.id}.activations`]: { max: Math.max((this.activations.max ?? 1) + num, 1), value: Math.max((this.activations.value ?? 0) + num, 0), }, }); } /** * Adjusts the number of current activations that a combatant has * @param num - The number of current activations to add (can be negative) */ async modifyCurrentActivations(num: number): Promise<this | undefined> { if (num === 0) return this; return this.update({ [`flags.${game.system.id}.activations`]: { value: Math.clamp((this.activations?.value ?? 0) + num, 0, this.activations?.max ?? 1), }, }); } } /** * Interface for the activations object */ interface Activations { max?: number; value?: number; } declare global { interface FlagConfig { Combatant: { lancer: { activations: Activations; disposition?: number; tour: string; }; }; } }
412
0.938855
1
0.938855
game-dev
MEDIA
0.639708
game-dev
0.955284
1
0.955284
spacechase0/StardewValleyMods
3,828
_archived/Terraforming/Mod.cs
using SpaceShared; using StardewModdingAPI; using StardewValley; using Terraforming.Framework; using xTile; using xTile.Layers; using xTile.Tiles; namespace Terraforming { internal class Mod : StardewModdingAPI.Mod { public static Mod Instance; public override void Entry(IModHelper helper) { Mod.Instance = this; Log.Monitor = this.Monitor; helper.ConsoleCommands.Add("terraform", "TODO", this.TerraformCommand); } private void TerraformCommand(string cmd, string[] args) { if (!Context.IsWorldReady) { Log.Info("World must be ready"); return; } if (Game1.eventUp) { Log.Info("Probably shouldn't do this during an event"); } Log.Info("Starting up..."); Mod.SterilizeMap(); Game1.activeClickableMenu = new TerraformingMenu(); } internal static void SterilizeMap(GameLocation loc = null) { loc ??= Game1.currentLocation; /* if (!loc.IsOutdoors) throw new NotSupportedException("Location must be outdoors"); */ Log.Trace("Creating sterile map..."); Map map = new Map { Id = loc.Map.Id + ".Terraform" }; foreach (var prop in loc.Map.Properties) map.Properties.Add(prop.Key, prop.Value); foreach (var ts in Game1.getFarm().Map.TileSheets) { var newTs = new TileSheet(ts.Id, map, ts.ImageSource, ts.SheetSize, ts.TileSize); foreach (var tsProp in ts.Properties) newTs.Properties.Add(tsProp.Key, tsProp.Value); for (int i = 0; i < ts.TileCount; ++i) foreach (var tileProp in ts.TileIndexProperties[i]) newTs.TileIndexProperties[i].Add(tileProp.Key, tileProp.Value); map.AddTileSheet(newTs); } foreach (var layer in loc.Map.Layers) { var newLayer = new Layer(layer.Id, map, layer.LayerSize, layer.TileSize); if (newLayer.Id is "Back" or "Buildings" or "Front" or "AlwaysFront") newLayer.AfterDraw += Mod.DrawTerraformLayer; if (newLayer.Id == "Back") { for (int ix = 0; ix < newLayer.LayerWidth; ix++) { for (int iy = 0; iy < newLayer.LayerHeight; iy++) { var tile = new StaticTile(newLayer, map.TileSheets[1], BlendMode.Alpha, 587); newLayer.Tiles[ix, iy] = tile; } } } map.AddLayer(newLayer); } Log.Trace("Replacing location's map with sterile map."); loc.Map = map; loc.Map.LoadTileSheets(Game1.mapDisplayDevice); if (loc.waterTiles != null) { int w = loc.waterTiles.waterTiles.GetLength(0); for (int i = 0; i < loc.waterTiles.waterTiles.Length; ++i) { int ix = i % w, iy = i / w; loc.waterTiles[ix, iy] = false; } } } private static void DrawTerraformLayer(object sender, LayerEventArgs e) { foreach (var layer in e.Layer.Map.Layers) { if (layer.Id.StartsWith(e.Layer.Id + "Terraform")) layer.Draw(Game1.mapDisplayDevice, Game1.viewport, xTile.Dimensions.Location.Origin, false, Game1.pixelZoom); } } } }
412
0.911108
1
0.911108
game-dev
MEDIA
0.974683
game-dev
0.985204
1
0.985204
catachiii/rambo
5,568
source/isaaclab/test/assets/check_fixed_base_assets.py
# Copyright (c) 2022-2025, The Isaac Lab Project Developers. # All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause """ This script demonstrates fixed-base API for different robots. .. code-block:: bash # Usage ./isaaclab.sh -p source/isaaclab/test/assets/check_fixed_base_assets.py """ """Launch Isaac Sim Simulator first.""" import argparse from isaaclab.app import AppLauncher # add argparse arguments parser = argparse.ArgumentParser(description="This script checks the fixed-base API for different robots.") # append AppLauncher cli args AppLauncher.add_app_launcher_args(parser) # parse the arguments args_cli = parser.parse_args() # launch omniverse app app_launcher = AppLauncher(args_cli) simulation_app = app_launcher.app """Rest everything follows.""" import numpy as np import torch import isaacsim.core.utils.prims as prim_utils import isaaclab.sim as sim_utils from isaaclab.assets import Articulation ## # Pre-defined configs ## from isaaclab_assets import ANYMAL_C_CFG, FRANKA_PANDA_CFG # isort:skip def define_origins(num_origins: int, spacing: float) -> list[list[float]]: """Defines the origins of the the scene.""" # create tensor based on number of environments env_origins = torch.zeros(num_origins, 3) # create a grid of origins num_cols = np.floor(np.sqrt(num_origins)) num_rows = np.ceil(num_origins / num_cols) xx, yy = torch.meshgrid(torch.arange(num_rows), torch.arange(num_cols), indexing="xy") env_origins[:, 0] = spacing * xx.flatten()[:num_origins] - spacing * (num_rows - 1) / 2 env_origins[:, 1] = spacing * yy.flatten()[:num_origins] - spacing * (num_cols - 1) / 2 env_origins[:, 2] = 0.0 # return the origins return env_origins.tolist() def design_scene() -> tuple[dict, list[list[float]]]: """Designs the scene.""" # Ground-plane cfg = sim_utils.GroundPlaneCfg() cfg.func("/World/defaultGroundPlane", cfg) # Lights cfg = sim_utils.DomeLightCfg(intensity=2000.0, color=(0.75, 0.75, 0.75)) cfg.func("/World/Light", cfg) # Create separate groups called "Origin1", "Origin2", "Origin3" # Each group will have a mount and a robot on top of it origins = define_origins(num_origins=4, spacing=2.0) # Origin 1 with Franka Panda prim_utils.create_prim("/World/Origin1", "Xform", translation=origins[0]) # -- Robot franka = Articulation(FRANKA_PANDA_CFG.replace(prim_path="/World/Origin1/Robot")) # Origin 2 with Anymal C prim_utils.create_prim("/World/Origin2", "Xform", translation=origins[1]) # -- Robot robot_cfg = ANYMAL_C_CFG.replace(prim_path="/World/Origin2/Robot") robot_cfg.spawn.articulation_props.fix_root_link = True anymal_c = Articulation(robot_cfg) # return the scene information scene_entities = { "franka": franka, "anymal_c": anymal_c, } return scene_entities, origins def run_simulator(sim: sim_utils.SimulationContext, entities: dict[str, Articulation], origins: torch.Tensor): """Runs the simulation loop.""" # Define simulation stepping sim_dt = sim.get_physics_dt() sim_time = 0.0 count = 0 # Simulate physics while simulation_app.is_running(): # reset if count % 200 == 0: # reset counters sim_time = 0.0 count = 0 # reset robots for index, robot in enumerate(entities.values()): # root state root_state = robot.data.default_root_state.clone() root_state[:, :3] += origins[index] root_state[:, :2] += torch.randn_like(root_state[:, :2]) * 0.25 robot.write_root_pose_to_sim(root_state[:, :7]) robot.write_root_velocity_to_sim(root_state[:, 7:]) # joint state joint_pos, joint_vel = robot.data.default_joint_pos.clone(), robot.data.default_joint_vel.clone() robot.write_joint_state_to_sim(joint_pos, joint_vel) # reset the internal state robot.reset() print("[INFO]: Resetting robots state...") # apply default actions to the quadrupedal robots for name, robot in entities.items(): if count % 200 == 0: print("Name: ", name, "is_fixed_base: ", robot.is_fixed_base) # generate random joint positions joint_pos_target = robot.data.default_joint_pos + torch.randn_like(robot.data.joint_pos) * 0.1 # apply action to the robot robot.set_joint_position_target(joint_pos_target) # write data to sim robot.write_data_to_sim() # perform step sim.step() # update sim-time sim_time += sim_dt count += 1 # update buffers for robot in entities.values(): robot.update(sim_dt) def main(): """Main function.""" # Initialize the simulation context sim = sim_utils.SimulationContext(sim_utils.SimulationCfg(dt=0.01)) # Set main camera sim.set_camera_view(eye=[2.5, 2.5, 2.5], target=[0.0, 0.0, 0.0]) # design scene scene_entities, scene_origins = design_scene() scene_origins = torch.tensor(scene_origins, device=sim.device) # Play the simulator sim.reset() # Now we are ready! print("[INFO]: Setup complete...") # Run the simulator run_simulator(sim, scene_entities, scene_origins) if __name__ == "__main__": # run the main function main() # close sim app simulation_app.close()
412
0.828769
1
0.828769
game-dev
MEDIA
0.364448
game-dev
0.587079
1
0.587079
Joshua-F/osrs-dumps
2,744
script/[clientscript,league_side_panel_init].cs2
// 3225 [clientscript,league_side_panel_init](component $component0, component $component1, component $component2, component $component3, component $component4, component $component5) cc_deleteall($component0); cc_deleteall($component1); cc_deleteall($component2); cc_deleteall($component3); if_settext(~league_get_league_name_short, $component4); ~v2_stone_button_filled($component0); if (~on_mobile = false) { if_setonmouseleave("league_side_panel_button_hover($component0, 0)", $component0); if_setonmouseover("league_side_panel_button_hover($component0, 1)", $component0); } if_setonop("button_select_sound", $component0); ~v2_stone_button_filled($component1); if (~on_mobile = false) { if_setonmouseleave("league_side_panel_button_hover($component1, 0)", $component1); if_setonmouseover("league_side_panel_button_hover($component1, 1)", $component1); } if_setonop("button_select_sound", $component1); ~v2_stone_button_filled($component2); if (~on_mobile = false) { if_setonmouseleave("league_side_panel_button_hover($component2, 0)", $component2); if_setonmouseover("league_side_panel_button_hover($component2, 1)", $component2); } if_setonop("button_select_sound", $component2); ~v2_stone_button_filled($component3); if (~on_mobile = false) { if_setonmouseleave("league_side_panel_button_hover($component3, 0)", $component3); if_setonmouseover("league_side_panel_button_hover($component3, 1)", $component3); } if_setonop("button_select_sound", $component3); def_struct $struct6 = enum(int, struct, enum_2670, %league_type); def_int $rgb7 = 0xff981f; if ($struct6 ! null) { if_setgraphic(struct_param($struct6, param_1024), league_side_panel:fill); if_setgraphic(struct_param($struct6, param_1025), league_side_panel:bkg); if_setgraphic(struct_param($struct6, param_2055), league_side_panel:relic); $rgb7 = struct_param($struct6, param_1027); } if_setcolour($rgb7, league_side_panel:header); if_setcolour($rgb7, league_side_panel:points_next_area); if_setcolour($rgb7, league_side_panel:points_next_relic); if_setcolour($rgb7, league_side_panel:total_tasks_text); if_setcolour($rgb7, league_side_panel:total_points_text); def_component $component8 = league_side_panel:tooltip; ~league_side_panel_rank($component8, $rgb7); ~league_side_panel_summary($component8, $rgb7); def_string $string0 = "Open League Info"; if (~on_mobile = false) { if_setonmouserepeat("tooltip_mouserepeat($component5, 0, $component8, $string0, 25, 190)", $component5); if_setonmouseleave("deltooltip($component8)", $component5); } if_setonop("script7753", $component5); if_setopbase("<col=ff981f>League Info</col>", $component5); ~league_side_panel_update_bar(league_side_panel:fill, %league_points_claimed);
412
0.792132
1
0.792132
game-dev
MEDIA
0.409833
game-dev
0.830149
1
0.830149
ioBroker/ioBroker.javascript
1,502
src-editor/public/vs/configure.js
// THIS FILE IS NOT PART OF THE DISTRIBUTED MONACO EDITOR // DON'T DELETE IT WHEN UPDATING!!! // it has to be loaded after monaco-editor/loader.js // Set the correct root path require.config({ paths: { 'vs': 'vs' }}); // Allow localization // All languages in monaco-editor const availableLanguages = ['de', 'en', 'fr', 'es', 'it', 'ru', 'zh-cn']; // find the best match function findLanguage() { if (window.sysLang !== undefined && availableLanguages.includes(window.sysLang)) { return window.sysLang; // this variable will be set via info.js } if (navigator.languages && Array.isArray(navigator.languages)) { return navigator.languages.find(lang => availableLanguages.includes(lang)) || 'en'; } let lang = navigator.language || navigator.userLanguage; if (typeof lang === 'string') { // first try the long version if (availableLanguages.includes(lang)) { return lang; } // then the short one lang = lang.substring(0, 2); if (availableLanguages.includes(lang)) { return lang; } } return 'en'; } const language = findLanguage(); // if we have a match, configure the editor if (language !== undefined && language !== null && language !== 'en') { require.config({ 'vs/nls': { availableLanguages: { '*': language } } }); } // And load the editor itself require(['vs/editor/editor.main'], function () { });
412
0.778974
1
0.778974
game-dev
MEDIA
0.493921
game-dev,web-frontend
0.877261
1
0.877261
magefree/mage
1,370
Mage.Sets/src/mage/cards/s/ShrewdStoryteller.java
package mage.cards.s; import mage.MageInt; import mage.abilities.Ability; import mage.abilities.abilityword.SurvivalAbility; import mage.abilities.effects.common.counter.AddCountersTargetEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.SubType; import mage.counters.CounterType; import mage.target.common.TargetCreaturePermanent; import java.util.UUID; /** * @author TheElk801 */ public final class ShrewdStoryteller extends CardImpl { public ShrewdStoryteller(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{1}{G}{W}"); this.subtype.add(SubType.HUMAN); this.subtype.add(SubType.SURVIVOR); this.power = new MageInt(3); this.toughness = new MageInt(3); // Survival -- At the beginning of your second main phase, if Shrewd Storyteller is tapped, put a +1/+1 counter on target creature. Ability ability = new SurvivalAbility(new AddCountersTargetEffect(CounterType.P1P1.createInstance())); ability.addTarget(new TargetCreaturePermanent()); this.addAbility(ability); } private ShrewdStoryteller(final ShrewdStoryteller card) { super(card); } @Override public ShrewdStoryteller copy() { return new ShrewdStoryteller(this); } }
412
0.916985
1
0.916985
game-dev
MEDIA
0.967365
game-dev
0.991381
1
0.991381
ParrotDevelopers/WebOasis
1,561
src/arcade/3dcity/src/zone/Stadia.js
/* micropolisJS. Adapted by Graeme McCutcheon from Micropolis. * * This code is released under the GNU GPL v3, with some additional terms. * Please see the files LICENSE and COPYING for details. Alternatively, * consult http://micropolisjs.graememcc.co.uk/LICENSE and * http://micropolisjs.graememcc.co.uk/COPYING * */ Micro.Stadia = function (SIM) { var sim = SIM; var emptyStadiumFound = function(map, x, y, simData) { sim.census.stadiumPop += 1; if (map.getTile(x, y).isPowered()) { // Occasionally start the big game if (((sim.cityTime + x + y) & 31) === 0) { map.putZone(x, y, Tile.FULLSTADIUM, 4); map.addTileFlags(x, y, Tile.POWERBIT); map.setTo(x + 1, y, new Micro.Tile(Tile.FOOTBALLGAME1, Tile.ANIMBIT)); map.setTo(x + 1, y + 1, new Micro.Tile(Tile.FOOTBALLGAME2, Tile.ANIMBIT)); } } } var fullStadiumFound = function(map, x, y, simData) { sim.census.stadiumPop += 1; var isPowered = map.getTile(x, y).isPowered(); if (((sim.cityTime + x + y) & 7) === 0) { map.putZone(x, y, Tile.STADIUM, 4); if (isPowered) map.addTileFlags(x, y, Tile.POWERBIT); } } return { registerHandlers: function(mapScanner, repairManager) { mapScanner.addAction(Tile.STADIUM, emptyStadiumFound); mapScanner.addAction(Tile.FULLSTADIUM, fullStadiumFound); repairManager.addAction(Tile.STADIUM, 15, 4); } } };
412
0.506055
1
0.506055
game-dev
MEDIA
0.481473
game-dev
0.528745
1
0.528745
libgdx/gdx-ai
6,922
gdx-ai/src/com/badlogic/gdx/ai/steer/behaviors/Arrive.java
/******************************************************************************* * Copyright 2014 See AUTHORS file. * * 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 com.badlogic.gdx.ai.steer.behaviors; import com.badlogic.gdx.ai.steer.Limiter; import com.badlogic.gdx.ai.steer.Steerable; import com.badlogic.gdx.ai.steer.SteeringAcceleration; import com.badlogic.gdx.ai.steer.SteeringBehavior; import com.badlogic.gdx.ai.utils.Location; import com.badlogic.gdx.math.Vector; /** {@code Arrive} behavior moves the agent towards a target position. It is similar to seek but it attempts to arrive at the target * position with a zero velocity. * <p> * {@code Arrive} behavior uses two radii. The {@code arrivalTolerance} lets the owner get near enough to the target without * letting small errors keep it in motion. The {@code decelerationRadius}, usually much larger than the previous one, specifies * when the incoming character will begin to slow down. The algorithm calculates an ideal speed for the owner. At the slowing-down * radius, this is equal to its maximum linear speed. At the target point, it is zero (we want to have zero speed when we arrive). * In between, the desired speed is an interpolated intermediate value, controlled by the distance from the target. * <p> * The direction toward the target is calculated and combined with the desired speed to give a target velocity. The algorithm * looks at the current velocity of the character and works out the acceleration needed to turn it into the target velocity. We * can't immediately change velocity, however, so the acceleration is calculated based on reaching the target velocity in a fixed * time scale known as {@code timeToTarget}. This is usually a small value; it defaults to 0.1 seconds which is a good starting * point. * * @param <T> Type of vector, either 2D or 3D, implementing the {@link Vector} interface * * @author davebaol */ public class Arrive<T extends Vector<T>> extends SteeringBehavior<T> { /** The target to arrive to. */ protected Location<T> target; /** The tolerance for arriving at the target. It lets the owner get near enough to the target without letting small errors keep * it in motion. */ protected float arrivalTolerance; /** The radius for beginning to slow down */ protected float decelerationRadius; /** The time over which to achieve target speed */ protected float timeToTarget = 0.1f; /** Creates an {@code Arrive} behavior for the specified owner. * @param owner the owner of this behavior */ public Arrive (Steerable<T> owner) { this(owner, null); } /** Creates an {@code Arrive} behavior for the specified owner and target. * @param owner the owner of this behavior * @param target the target of this behavior */ public Arrive (Steerable<T> owner, Location<T> target) { super(owner); this.target = target; } @Override protected SteeringAcceleration<T> calculateRealSteering (SteeringAcceleration<T> steering) { return arrive(steering, target.getPosition()); } protected SteeringAcceleration<T> arrive (SteeringAcceleration<T> steering, T targetPosition) { // Get the direction and distance to the target T toTarget = steering.linear.set(targetPosition).sub(owner.getPosition()); float distance = toTarget.len(); // Check if we are there, return no steering if (distance <= arrivalTolerance) return steering.setZero(); Limiter actualLimiter = getActualLimiter(); // Go max speed float targetSpeed = actualLimiter.getMaxLinearSpeed(); // If we are inside the slow down radius calculate a scaled speed if (distance <= decelerationRadius) targetSpeed *= distance / decelerationRadius; // Target velocity combines speed and direction T targetVelocity = toTarget.scl(targetSpeed / distance); // Optimized code for: toTarget.nor().scl(targetSpeed) // Acceleration tries to get to the target velocity without exceeding max acceleration // Notice that steering.linear and targetVelocity are the same vector targetVelocity.sub(owner.getLinearVelocity()).scl(1f / timeToTarget).limit(actualLimiter.getMaxLinearAcceleration()); // No angular acceleration steering.angular = 0f; // Output the steering return steering; } /** Returns the target to arrive to. */ public Location<T> getTarget () { return target; } /** Sets the target to arrive to. * @return this behavior for chaining. */ public Arrive<T> setTarget (Location<T> target) { this.target = target; return this; } /** Returns the tolerance for arriving at the target. It lets the owner get near enough to the target without letting small * errors keep it in motion. */ public float getArrivalTolerance () { return arrivalTolerance; } /** Sets the tolerance for arriving at the target. It lets the owner get near enough to the target without letting small errors * keep it in motion. * @return this behavior for chaining. */ public Arrive<T> setArrivalTolerance (float arrivalTolerance) { this.arrivalTolerance = arrivalTolerance; return this; } /** Returns the radius for beginning to slow down. */ public float getDecelerationRadius () { return decelerationRadius; } /** Sets the radius for beginning to slow down. * @return this behavior for chaining. */ public Arrive<T> setDecelerationRadius (float decelerationRadius) { this.decelerationRadius = decelerationRadius; return this; } /** Returns the time over which to achieve target speed. */ public float getTimeToTarget () { return timeToTarget; } /** Sets the time over which to achieve target speed. * @return this behavior for chaining. */ public Arrive<T> setTimeToTarget (float timeToTarget) { this.timeToTarget = timeToTarget; return this; } // // Setters overridden in order to fix the correct return type for chaining // @Override public Arrive<T> setOwner (Steerable<T> owner) { this.owner = owner; return this; } @Override public Arrive<T> setEnabled (boolean enabled) { this.enabled = enabled; return this; } /** Sets the limiter of this steering behavior. The given limiter must at least take care of the maximum linear speed and * acceleration. * @return this behavior for chaining. */ @Override public Arrive<T> setLimiter (Limiter limiter) { this.limiter = limiter; return this; } }
412
0.960031
1
0.960031
game-dev
MEDIA
0.857252
game-dev
0.981288
1
0.981288
GPUOpen-LibrariesAndSDKs/Schola
5,748
Source/Schola/Private/Training/AbstractTrainer.cpp
// Copyright (c) 2023 Advanced Micro Devices, Inc. All Rights Reserved. #include "Training/AbstractTrainer.h" #include "Subsystem/ScholaManagerSubsystem.h" #include "Agent/AgentComponents/SensorComponent.h" const FString AGENT_ACTION_ID = FString("__AGENT__"); void AAbstractTrainer::OnPossess(APawn* InPawn) { Super::OnPossess(InPawn); if (this->HasAgentClass()) { // If we have attached before, check if the class is the same as the attached pawn if (this->AgentClass != InPawn->GetClass()) { UE_LOG(LogSchola, Warning, TEXT("Agent %s has attached to a different pawn class than before. This may cause issues."), *this->GetName()) } } else //We haven't attached before, so set the class to the attached pawn { this->AgentClass = InPawn->GetClass(); } this->State.bExists = true; this->SetTrainingStatus(EAgentTrainingStatus::Running); } void AAbstractTrainer::PawnPendingDestroy(APawn* inPawn) { //Code is based on AActor::PawnPendingDestroy but we don't destroy the trainer at the end if (IsInState(NAME_Inactive)) { UE_LOG(LogController, Log, TEXT("PawnPendingDestroy while inactive %s"), *GetName()); } if (inPawn != this->GetPawn()) { return; } UnPossess(); ChangeState(NAME_Inactive); //Normally we would destroy ourselves here, but Trainers persist beyond their pawns } void AAbstractTrainer::OnUnPossess() { //We directly set here, so that in the event of UnPossess->Possess in one tick we can continue. Super::OnUnPossess(); this->State.bExists = false; } AAbstractTrainer::AAbstractTrainer() { } bool AAbstractTrainer::Initialize(int EnvId, int AgentId, APawn* TargetPawn) { UE_LOG(LogSchola, Log, TEXT("Starting Initialization of Agent %s"), *this->GetName()) this->AgentClass = TargetPawn->GetClass(); //UE_LOG(LogSchola, Log, TEXT("Agent is Controlling Pawn %s "), *this->TargetPawn->GetName()); // Collect all the observers and actuators TArray<UActuatorComponent*> ActuatorComponentsTemp; TArray<UActuator*> AllActuators = this->Actuators; this->GetPawn()->GetComponents(ActuatorComponentsTemp); for (UActuatorComponent* Actuator : ActuatorComponentsTemp) { AllActuators.Add(Actuator->Actuator); } ActuatorComponentsTemp.Reset(); this->GetComponents(ActuatorComponentsTemp); for (UActuatorComponent* Actuator : ActuatorComponentsTemp) { AllActuators.Add(Actuator->Actuator); } TArray<USensor*> SensorsTemp; TArray<UAbstractObserver*> AllObservers = this->Observers; this->GetPawn()->GetComponents(SensorsTemp); for (USensor* Sensor : SensorsTemp) { AllObservers.Add(Sensor->Observer); } SensorsTemp.Reset(); this->GetComponents(SensorsTemp); for (USensor* Sensor : SensorsTemp) { AllObservers.Add(Sensor->Observer); } // Initialize the Interaction Manager with the Observers and Actuators this->InteractionManager->Initialize(AllObservers, AllActuators); // Set the agent state's observation as a pointer to the Interaction Manager's observation this->State.Observations = &this->InteractionManager->Observations; // Set the ID for the Agent UAgentUIDSubsystem* UIDManager = GetWorld()->GetSubsystem<UAgentUIDSubsystem>(); this->TrainerDefn.Id = {UIDManager->GetId(), EnvId, AgentId}; if (this->TrainerConfiguration.bUseCustomName) { this->TrainerDefn.Name = this->TrainerConfiguration.Name; } else { this->GetName(this->TrainerDefn.Name); } this->TrainerDefn.PolicyDefinition = &this->InteractionManager->InteractionDefn; UE_LOG(LogSchola, Warning, TEXT("Initialization finished")); return true; } FTrainerState* AAbstractTrainer::Think() { TRACE_CPUPROFILER_EVENT_SCOPE_STR("Schola: Agent Thinking"); // If we entered the think done, we can skip if (this->IsDone()) { // Set the training status so that, LastStatus now shows a terminal status as well this->SetTrainingStatus(this->State.TrainingStatus); } else { if(this->State.bExists) { this->SetTrainingStatus(this->ComputeStatus()); // Set the reward. this->State.Reward = this->ComputeReward(); // Update the info field this->State.Info.Reset(); this->GetInfo(this->State.Info); this->InteractionManager->AggregateObservations(); } else { //We entered this think and the agent no longer exists, so reuse the last obs/reward and complete this->SetTrainingStatus(EAgentTrainingStatus::Completed); } if (this->IsDone()) { OnCompletion(); } } return &State; } void AAbstractTrainer::Act(const FAction& Action) { TRACE_CPUPROFILER_EVENT_SCOPE_STR("Schola: Agent Acting"); this->InteractionManager->DistributeActions(Action.Values); this->IncrementStep(); } void AAbstractTrainer::Reset() { this->ResetTrainer(); State.Observations->Reset(); State.Info.Reset(); State.Step = 0; this->InteractionManager->Reset(); this->InteractionManager->AggregateObservations(); this->GetInfo(this->State.Info); this->SetTrainingStatus(EAgentTrainingStatus::Running); } void AAbstractTrainer::SetTrainingStatus(EAgentTrainingStatus NewStatus) { this->State.LastStatus = this->State.TrainingStatus; this->State.TrainingStatus = NewStatus; } EAgentTrainingStatus AAbstractTrainer::GetTrainingStatus() { return this->State.TrainingStatus; } bool AAbstractTrainer::IsRunning() { return this->State.TrainingStatus == EAgentTrainingStatus::Running; } bool AAbstractTrainer::IsDone() const { return this->State.IsDone(); } bool AAbstractTrainer::IsActionStep() { return this->IsDecisionStep() || this->TrainerConfiguration.bTakeActionBetweenDecisions; } bool AAbstractTrainer::IsDecisionStep(int StepToCheck) { return (StepToCheck % this->TrainerConfiguration.DecisionRequestFrequency) == 0; } bool AAbstractTrainer::IsDecisionStep() { return this->IsDecisionStep(this->State.Step); }
412
0.912147
1
0.912147
game-dev
MEDIA
0.838583
game-dev
0.883115
1
0.883115
geode-sdk/geode
2,853
loader/include/Geode/cocos/tilemap_parallax_nodes/CCParallaxNode.h
/**************************************************************************** Copyright (c) 2010-2012 cocos2d-x.org Copyright (c) 2009-2010 Ricardo Quesada Copyright (c) 2011 Zynga Inc. http://www.cocos2d-x.org 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. ****************************************************************************/ #ifndef __CCPARALLAX_NODE_H__ #define __CCPARALLAX_NODE_H__ #include "../base_nodes/CCNode.h" /*#include "../support/data_support/ccCArray.h"*/ NS_CC_BEGIN struct _ccArray; /** * @addtogroup tilemap_parallax_nodes * @{ */ /** @brief CCParallaxNode: A node that simulates a parallax scroller The children will be moved faster / slower than the parent according the the parallax ratio. */ class CC_DLL CCParallaxNode : public CCNode { GEODE_FRIEND_MODIFY /** array that holds the offset / ratio of the children */ CC_SYNTHESIZE_NV(struct _ccArray *, m_pParallaxArray, ParallaxArray) public: GEODE_CUSTOM_CONSTRUCTOR_COCOS(CCParallaxNode, CCNode) /** Adds a child to the container with a z-order, a parallax ratio and a position offset It returns self, so you can chain several addChilds. @since v0.8 @js ctor */ CCParallaxNode(); /** * @js NA * @lua NA */ virtual ~CCParallaxNode(); static CCParallaxNode * create(); virtual void addChild(CCNode * child, unsigned int z, const CCPoint& parallaxRatio, const CCPoint& positionOffset); // super methods virtual void addChild(CCNode * child, unsigned int zOrder, int tag); virtual void removeChild(CCNode* child, bool cleanup); virtual void removeAllChildrenWithCleanup(bool cleanup); virtual void visit(void); private: CCPoint absolutePosition(); public: CCPoint m_tLastPosition; }; // end of tilemap_parallax_nodes group /// @} NS_CC_END #endif //__CCPARALLAX_NODE_H__
412
0.907635
1
0.907635
game-dev
MEDIA
0.743905
game-dev,graphics-rendering
0.809254
1
0.809254
discosultan/penumbra
8,972
Samples/Shared/FarseerPhysics Source/Farseer Physics Engine 3.5/Common/TextureTools/Terrain.cs
using System.Collections.Generic; using FarseerPhysics.Collision; using FarseerPhysics.Common.Decomposition; using FarseerPhysics.Common.PolygonManipulation; using FarseerPhysics.Dynamics; using FarseerPhysics.Factories; using Microsoft.Xna.Framework; namespace FarseerPhysics.Common.TextureTools { /// <summary> /// Simple class to maintain a terrain. It can keep track /// </summary> public class Terrain { /// <summary> /// World to manage terrain in. /// </summary> public World World; /// <summary> /// Center of terrain in world units. /// </summary> public Vector2 Center; /// <summary> /// Width of terrain in world units. /// </summary> public float Width; /// <summary> /// Height of terrain in world units. /// </summary> public float Height; /// <summary> /// Points per each world unit used to define the terrain in the point cloud. /// </summary> public int PointsPerUnit; /// <summary> /// Points per cell. /// </summary> public int CellSize; /// <summary> /// Points per sub cell. /// </summary> public int SubCellSize; /// <summary> /// Number of iterations to perform in the Marching Squares algorithm. /// Note: More then 3 has almost no effect on quality. /// </summary> public int Iterations = 2; /// <summary> /// Decomposer to use when regenerating terrain. Can be changed on the fly without consequence. /// Note: Some decomposerers are unstable. /// </summary> public TriangulationAlgorithm Decomposer; /// <summary> /// Point cloud defining the terrain. /// </summary> private sbyte[,] _terrainMap; /// <summary> /// Generated bodies. /// </summary> private List<Body>[,] _bodyMap; private float _localWidth; private float _localHeight; private int _xnum; private int _ynum; private AABB _dirtyArea; private Vector2 _topLeft; /// <summary> /// Creates a new terrain. /// </summary> /// <param name="world">The World</param> /// <param name="area">The area of the terrain.</param> public Terrain(World world, AABB area) { World = world; Width = area.Width; Height = area.Height; Center = area.Center; } /// <summary> /// Creates a new terrain /// </summary> /// <param name="world">The World</param> /// <param name="position">The position (center) of the terrain.</param> /// <param name="width">The width of the terrain.</param> /// <param name="height">The height of the terrain.</param> public Terrain(World world, Vector2 position, float width, float height) { World = world; Width = width; Height = height; Center = position; } /// <summary> /// Initialize the terrain for use. /// </summary> public void Initialize() { // find top left of terrain in world space _topLeft = new Vector2(Center.X - (Width * 0.5f), Center.Y - (-Height * 0.5f)); // convert the terrains size to a point cloud size _localWidth = Width * PointsPerUnit; _localHeight = Height * PointsPerUnit; _terrainMap = new sbyte[(int)_localWidth + 1, (int)_localHeight + 1]; for (int x = 0; x < _localWidth; x++) { for (int y = 0; y < _localHeight; y++) { _terrainMap[x, y] = 1; } } _xnum = (int)(_localWidth / CellSize); _ynum = (int)(_localHeight / CellSize); _bodyMap = new List<Body>[_xnum, _ynum]; // make sure to mark the dirty area to an infinitely small box _dirtyArea = new AABB(new Vector2(float.MaxValue, float.MaxValue), new Vector2(float.MinValue, float.MinValue)); } /// <summary> /// Apply the specified texture data to the terrain. /// </summary> /// <param name="data"></param> /// <param name="offset"></param> public void ApplyData(sbyte[,] data, Vector2 offset = default(Vector2)) { for (int x = 0; x < data.GetUpperBound(0); x++) { for (int y = 0; y < data.GetUpperBound(1); y++) { if (x + offset.X >= 0 && x + offset.X < _localWidth && y + offset.Y >= 0 && y + offset.Y < _localHeight) { _terrainMap[(int)(x + offset.X), (int)(y + offset.Y)] = data[x, y]; } } } RemoveOldData(0, _xnum, 0, _ynum); } /// <summary> /// Modify a single point in the terrain. /// </summary> /// <param name="location">World location to modify. Automatically clipped.</param> /// <param name="value">-1 = inside terrain, 1 = outside terrain</param> public void ModifyTerrain(Vector2 location, sbyte value) { // find local position // make position local to map space Vector2 p = location - _topLeft; // find map position for each axis p.X = p.X * _localWidth / Width; p.Y = p.Y * -_localHeight / Height; if (p.X >= 0 && p.X < _localWidth && p.Y >= 0 && p.Y < _localHeight) { _terrainMap[(int)p.X, (int)p.Y] = value; // expand dirty area if (p.X < _dirtyArea.LowerBound.X) _dirtyArea.LowerBound.X = p.X; if (p.X > _dirtyArea.UpperBound.X) _dirtyArea.UpperBound.X = p.X; if (p.Y < _dirtyArea.LowerBound.Y) _dirtyArea.LowerBound.Y = p.Y; if (p.Y > _dirtyArea.UpperBound.Y) _dirtyArea.UpperBound.Y = p.Y; } } /// <summary> /// Regenerate the terrain. /// </summary> public void RegenerateTerrain() { //iterate effected cells int xStart = (int)(_dirtyArea.LowerBound.X / CellSize); if (xStart < 0) xStart = 0; int xEnd = (int)(_dirtyArea.UpperBound.X / CellSize) + 1; if (xEnd > _xnum) xEnd = _xnum; int yStart = (int)(_dirtyArea.LowerBound.Y / CellSize); if (yStart < 0) yStart = 0; int yEnd = (int)(_dirtyArea.UpperBound.Y / CellSize) + 1; if (yEnd > _ynum) yEnd = _ynum; RemoveOldData(xStart, xEnd, yStart, yEnd); _dirtyArea = new AABB(new Vector2(float.MaxValue, float.MaxValue), new Vector2(float.MinValue, float.MinValue)); } private void RemoveOldData(int xStart, int xEnd, int yStart, int yEnd) { for (int x = xStart; x < xEnd; x++) { for (int y = yStart; y < yEnd; y++) { //remove old terrain object at grid cell if (_bodyMap[x, y] != null) { for (int i = 0; i < _bodyMap[x, y].Count; i++) { World.RemoveBody(_bodyMap[x, y][i]); } } _bodyMap[x, y] = null; //generate new one GenerateTerrain(x, y); } } } private void GenerateTerrain(int gx, int gy) { float ax = gx * CellSize; float ay = gy * CellSize; List<Vertices> polys = MarchingSquares.DetectSquares(new AABB(new Vector2(ax, ay), new Vector2(ax + CellSize, ay + CellSize)), SubCellSize, SubCellSize, _terrainMap, Iterations, true); if (polys.Count == 0) return; _bodyMap[gx, gy] = new List<Body>(); // create the scale vector Vector2 scale = new Vector2(1f / PointsPerUnit, 1f / -PointsPerUnit); // create physics object for this grid cell foreach (Vertices item in polys) { // does this need to be negative? item.Scale(ref scale); item.Translate(ref _topLeft); Vertices simplified = SimplifyTools.CollinearSimplify(item); List<Vertices> decompPolys = Triangulate.ConvexPartition(simplified, Decomposer); foreach (Vertices poly in decompPolys) { if (poly.Count > 2) _bodyMap[gx, gy].Add(BodyFactory.CreatePolygon(World, poly, 1)); } } } } }
412
0.883943
1
0.883943
game-dev
MEDIA
0.946692
game-dev
0.989045
1
0.989045
TerjeBruoygard/TerjeModsScripting
4,410
TerjeCore/Scripts/3_Game/Xml/TerjeXmlBase.c
// <copyright file="TerjeXmlBase.c" author="Terje Bruoygard"> // This repository does not provide full code of our mods need to be fully functional. // That's just interfaces and simple logic that may be helpful to other developers while using our mods as dependencies. // Modification, repackaging, distribution or any other use of the code from this file except as specified in the LICENSE.md is strictly prohibited. // Copyright (c) TerjeMods. All rights reserved. // </copyright> class TerjeXmlBase { protected ref array<ref TerjeXmlObject> m_Children = null; void DeleteComments(bool recursive = true) { int i = 0; while (i < GetChildrenCount()) { TerjeXmlObject child = GetChild(i); if (child != null) { if (child.IsCommentNode()) { RemoveChild(i); continue; } else if (recursive) { child.DeleteComments(recursive); } } i = i + 1; } } void ClearChildren() { m_Children = null; } TerjeXmlObject CreateChild(string name) { if (m_Children == null) { m_Children = new array<ref TerjeXmlObject>; } ref TerjeXmlObject child = new TerjeXmlObject; child.SetName(name); m_Children.Insert(child); return child; } TerjeXmlObject CreateChildAt(string name, int index) { if (m_Children == null) { m_Children = new array<ref TerjeXmlObject>; } ref TerjeXmlObject child = new TerjeXmlObject; child.SetName(name); m_Children.InsertAt(child, index); return child; } void RemoveChild(int index) { if (m_Children != null) { m_Children.RemoveOrdered(index); } } void RemoveAllChildrenWithName(string name) { if (m_Children != null) { int index = 0; while (index < m_Children.Count()) { TerjeXmlObject child = m_Children.Get(index); if ((child != null) && (child.IsObjectNode()) && (child.GetName() == name)) { m_Children.RemoveOrdered(index); } else { index++; } } } } int GetChildrenCount() { if (m_Children != null) { return m_Children.Count(); } return 0; } TerjeXmlObject GetChild(int index) { if (m_Children != null) { return m_Children.Get(index); } return null; } TerjeXmlObject GetChildByNodeName(string nodeName) { int index = FindChildIndexByNodeName(nodeName); if (index != -1) { return GetChild(index); } return null; } int FindChildIndexByNodeName(string nodeName, int startIndex = 0) { if (m_Children != null) { for (int i = startIndex; i < m_Children.Count(); i++) { TerjeXmlObject node = m_Children.Get(i); if ((node.IsObjectNode()) && (node.GetName() == nodeName)) { return i; } } } return -1; } TerjeXmlObject GetChildByAttrName(string nodeName, string attrName) { int index = FindChildIndexByAttrName(nodeName, attrName); if (index != -1) { return GetChild(index); } return null; } int FindChildIndexByAttrName(string nodeName, string attrName, int startIndex = 0) { if (m_Children != null) { for (int i = startIndex; i < m_Children.Count(); i++) { TerjeXmlObject node = m_Children.Get(i); if ((node.IsObjectNode()) && (node.GetName() == nodeName) && (node.HasAttribute(attrName))) { return i; } } } return -1; } TerjeXmlObject GetChildByAttrPair(string nodeName, string attrName, string attrValue) { int index = FindChildIndexByAttrPair(nodeName, attrName, attrValue); if (index != -1) { return GetChild(index); } return null; } int FindChildIndexByAttrPair(string nodeName, string attrName, string attrValue, int startIndex = 0) { if (m_Children != null) { for (int i = startIndex; i < m_Children.Count(); i++) { string value; TerjeXmlObject node = m_Children.Get(i); if ((node.IsObjectNode()) && (node.GetName() == nodeName) && (node.FindAttribute(attrName, value)) && (value == attrValue)) { return i; } } } return -1; } bool FindValueByNodeName(string nodeName, out string value) { TerjeXmlObject node = GetChildByNodeName(nodeName); if ((node != null) && (node.IsObjectNode()) && (node.HasValue())) { value = node.GetValue(); return true; } return false; } bool HasChildren() { return m_Children != null && m_Children.Count() > 0; } array<ref TerjeXmlObject> GetChildren() { return m_Children; } }
412
0.843083
1
0.843083
game-dev
MEDIA
0.231775
game-dev
0.974547
1
0.974547
magarena/magarena
1,189
release/Magarena/scripts/Cairn_Wanderer.groovy
def CAIRN_WANDERER_FLAGS = MagicAbility.of( MagicAbility.Flying, MagicAbility.Fear, MagicAbility.FirstStrike, MagicAbility.DoubleStrike, MagicAbility.Deathtouch, MagicAbility.Haste, MagicAbility.Lifelink, MagicAbility.Reach, MagicAbility.Trample, MagicAbility.Shroud, MagicAbility.Vigilance ); CAIRN_WANDERER_FLAGS.addAll(MagicAbility.LANDWALK_FLAGS); CAIRN_WANDERER_FLAGS.addAll(MagicAbility.PROTECTION_FLAGS); [ new MagicStatic(MagicLayer.Ability) { @Override public void modAbilityFlags(final MagicPermanent source,final MagicPermanent permanent,final Set<MagicAbility> flags) { final MagicGame game = source.getGame(); for (final MagicPlayer player : game.getAPNAP()) { for (final MagicCard card : player.getGraveyard()) { if (card.hasType(MagicType.Creature)) { final Set<MagicAbility> creatureAbilities = card.getAbilityFlags(); creatureAbilities.retainAll(CAIRN_WANDERER_FLAGS); flags.addAll(creatureAbilities); } } } } } ]
412
0.829685
1
0.829685
game-dev
MEDIA
0.946095
game-dev
0.729565
1
0.729565
Sandern/lambdawars
7,538
src/game/server/swarm/asw_playermove.cpp
//========= Copyright 1996-2001, Valve LLC, All rights reserved. ============ // // Purpose: // // $NoKeywords: $ //============================================================================= #include "cbase.h" #include "player_command.h" #include "igamemovement.h" #include "in_buttons.h" #include "ipredictionsystem.h" #include "asw_player.h" #include "asw_marine.h" #include "asw_marine_command.h" #include "asw_imarinegamemovement.h" #include "asw_marine_gamemovement.h" #include "ilagcompensationmanager.h" #include "asw_lag_compensation.h" #include "iservervehicle.h" #include "asw_movedata.h" static CASW_MoveData g_MoveData; CMoveData *g_pMoveData = &g_MoveData; IPredictionSystem *IPredictionSystem::g_pPredictionSystems = NULL; extern IGameMovement *g_pGameMovement; extern ConVar sv_noclipduringpause; extern IMarineGameMovement *g_pMarineGameMovement; extern ConVar asw_allow_detach; ConVar asw_move_marine("asw_move_marine", "1", FCVAR_CHEAT, "Activate remote control of named entity"); void CommentarySystem_PePlayerRunCommand( CBasePlayer *player, CUserCmd *ucmd ); //----------------------------------------------------------------------------- // Sets up the move data for Infested //----------------------------------------------------------------------------- class CASW_PlayerMove : public CPlayerMove { DECLARE_CLASS( CASW_PlayerMove, CPlayerMove ); public: virtual void SetupMove( CBasePlayer *player, CUserCmd *ucmd, IMoveHelper *pHelper, CMoveData *move ); virtual void RunCommand( CBasePlayer *player, CUserCmd *ucmd, IMoveHelper *moveHelper ); }; // PlayerMove Interface static CASW_PlayerMove g_PlayerMove; //----------------------------------------------------------------------------- // Singleton accessor //----------------------------------------------------------------------------- CPlayerMove *PlayerMove() { return &g_PlayerMove; } //----------------------------------------------------------------------------- // Purpose: This is called pre player movement and copies all the data necessary // from the player for movement. (Server-side, the client-side version // of this code can be found in prediction.cpp.) //----------------------------------------------------------------------------- void CASW_PlayerMove::SetupMove( CBasePlayer *player, CUserCmd *ucmd, IMoveHelper *pHelper, CMoveData *move ) { player->AvoidPhysicsProps( ucmd ); BaseClass::SetupMove( player, ucmd, pHelper, move ); // this forces horizontal movement CASW_Player *pASWPlayer = dynamic_cast<CASW_Player*>(player); if (pASWPlayer && pASWPlayer->GetMarine() && !asw_allow_detach.GetBool()) { move->m_vecAngles.x = 0; move->m_vecViewAngles.x = 0; CBaseEntity *pMoveParent = player->GetMoveParent(); if (!pMoveParent) { move->m_vecAbsViewAngles = move->m_vecViewAngles; } else { matrix3x4_t viewToParent, viewToWorld; AngleMatrix( move->m_vecViewAngles, viewToParent ); ConcatTransforms( pMoveParent->EntityToWorldTransform(), viewToParent, viewToWorld ); MatrixAngles( viewToWorld, move->m_vecAbsViewAngles ); } } CASW_MoveData *pASWMove = static_cast<CASW_MoveData*>( move ); pASWMove->m_iForcedAction = ucmd->forced_action; // setup trace optimization g_pGameMovement->SetupMovementBounds( move ); } extern void DiffPrint( bool bServer, int nCommandNumber, char const *fmt, ... ); extern ConVar asw_rts_controls; void CASW_PlayerMove::RunCommand( CBasePlayer *player, CUserCmd *ucmd, IMoveHelper *moveHelper ) { CASW_Player *pASWPlayer = static_cast<CASW_Player*>( player ); Assert( pASWPlayer ); StartCommand( player, ucmd ); pASWPlayer->SetHighlightEntity( CBaseEntity::Instance( ucmd->crosshair_entity ) ); // Set globals appropriately gpGlobals->curtime = player->m_nTickBase * TICK_INTERVAL; gpGlobals->frametime = player->m_bGamePaused ? 0 : TICK_INTERVAL; // Add and subtract buttons we're forcing on the player ucmd->buttons |= player->m_afButtonForced; ucmd->buttons &= ~player->m_afButtonDisabled; if ( player->m_bGamePaused ) { // If no clipping and cheats enabled and noclipduring game enabled, then leave // forwardmove and angles stuff in usercmd if ( player->GetMoveType() == MOVETYPE_NOCLIP && sv_cheats->GetBool() && sv_noclipduringpause.GetBool() ) { gpGlobals->frametime = TICK_INTERVAL; } } /* // TODO: We can check whether the player is sending more commands than elapsed real time cmdtimeremaining -= ucmd->msec; if ( cmdtimeremaining < 0 ) { // return; } */ g_pGameMovement->StartTrackPredictionErrors( player ); CommentarySystem_PePlayerRunCommand( player, ucmd ); // Do weapon selection if ( ucmd->weaponselect != 0 ) { CBaseCombatWeapon *weapon = dynamic_cast< CBaseCombatWeapon * >( CBaseEntity::Instance( ucmd->weaponselect ) ); if (weapon) pASWPlayer->ASWSelectWeapon(weapon, 0); // ucmd->weaponsubtype); // infested - subtype var used for sending marine profile index instead } IServerVehicle *pVehicle = player->GetVehicle(); // Latch in impulse. if ( ucmd->impulse ) { // Discard impulse commands unless the vehicle allows them. // FIXME: UsingStandardWeapons seems like a bad filter for this. The flashlight is an impulse command, for example. if ( !pVehicle || player->UsingStandardWeaponsInVehicle() ) { player->m_nImpulse = ucmd->impulse; } } // Update player input button states VPROF_SCOPE_BEGIN( "player->UpdateButtonState" ); player->UpdateButtonState( ucmd->buttons ); VPROF_SCOPE_END(); CheckMovingGround( player, TICK_INTERVAL ); g_pMoveData->m_vecOldAngles = player->pl.v_angle; // Copy from command to player unless game .dll has set angle using fixangle if ( player->pl.fixangle == FIXANGLE_NONE ) { player->pl.v_angle = ucmd->viewangles; } else if( player->pl.fixangle == FIXANGLE_RELATIVE ) { player->pl.v_angle = ucmd->viewangles + player->pl.anglechange; } // TrackIR player->SetEyeAngleOffset(ucmd->headangles); player->SetEyeOffset(ucmd->headoffset); // TrackIR // Call standard client pre-think RunPreThink( player ); // Call Think if one is set RunThink( player, TICK_INTERVAL ); // Setup input. SetupMove( player, ucmd, moveHelper, g_pMoveData ); // Let the game do the movement. if (asw_allow_detach.GetBool()) { if ( !pVehicle ) { VPROF( "g_pGameMovement->ProcessMovement()" ); Assert( g_pGameMovement ); g_pGameMovement->ProcessMovement( player, g_pMoveData ); } else { VPROF( "pVehicle->ProcessMovement()" ); pVehicle->ProcessMovement( player, g_pMoveData ); } } if ( asw_rts_controls.GetBool() ) { Vector vecNewPos = g_pMoveData->GetAbsOrigin(); vecNewPos.y += ucmd->forwardmove * gpGlobals->frametime * 2; vecNewPos.x += ucmd->sidemove * gpGlobals->frametime * 2; g_pMoveData->SetAbsOrigin( vecNewPos ); } pASWPlayer->SetCrosshairTracePos( ucmd->crosshairtrace ); // Copy output FinishMove( player, ucmd, g_pMoveData ); // Let server invoke any needed impact functions VPROF_SCOPE_BEGIN( "moveHelper->ProcessImpacts" ); moveHelper->ProcessImpacts(); VPROF_SCOPE_END(); // put lag compensation here so it affects weapons lagcompensation->StartLagCompensation( player, LAG_COMPENSATE_BOUNDS ); RunPostThink( player ); lagcompensation->FinishLagCompensation( player ); // let the player drive marine movement here pASWPlayer->DriveMarineMovement( ucmd, moveHelper ); g_pGameMovement->FinishTrackPredictionErrors( player ); FinishCommand( player ); // Let time pass player->m_nTickBase++; }
412
0.80715
1
0.80715
game-dev
MEDIA
0.958975
game-dev
0.942823
1
0.942823
spurious/SDL-mirror
10,066
test/testjoystick.c
/* Copyright (C) 1997-2021 Sam Lantinga <slouken@libsdl.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. */ /* Simple program to test the SDL joystick routines */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "SDL.h" #ifdef __EMSCRIPTEN__ #include <emscripten/emscripten.h> #endif #ifndef SDL_JOYSTICK_DISABLED #ifdef __IPHONEOS__ #define SCREEN_WIDTH 320 #define SCREEN_HEIGHT 480 #else #define SCREEN_WIDTH 640 #define SCREEN_HEIGHT 480 #endif static SDL_Window *window = NULL; static SDL_Renderer *screen = NULL; static SDL_Joystick *joystick = NULL; static SDL_bool done = SDL_FALSE; static void PrintJoystick(SDL_Joystick *joystick) { const char *type; char guid[64]; SDL_assert(SDL_JoystickFromInstanceID(SDL_JoystickInstanceID(joystick)) == joystick); SDL_JoystickGetGUIDString(SDL_JoystickGetGUID(joystick), guid, sizeof (guid)); switch (SDL_JoystickGetType(joystick)) { case SDL_JOYSTICK_TYPE_GAMECONTROLLER: type = "Game Controller"; break; case SDL_JOYSTICK_TYPE_WHEEL: type = "Wheel"; break; case SDL_JOYSTICK_TYPE_ARCADE_STICK: type = "Arcade Stick"; break; case SDL_JOYSTICK_TYPE_FLIGHT_STICK: type = "Flight Stick"; break; case SDL_JOYSTICK_TYPE_DANCE_PAD: type = "Dance Pad"; break; case SDL_JOYSTICK_TYPE_GUITAR: type = "Guitar"; break; case SDL_JOYSTICK_TYPE_DRUM_KIT: type = "Drum Kit"; break; case SDL_JOYSTICK_TYPE_ARCADE_PAD: type = "Arcade Pad"; break; case SDL_JOYSTICK_TYPE_THROTTLE: type = "Throttle"; break; default: type = "Unknown"; break; } SDL_Log("Joystick\n"); SDL_Log(" name: %s\n", SDL_JoystickName(joystick)); SDL_Log(" type: %s\n", type); SDL_Log(" axes: %d\n", SDL_JoystickNumAxes(joystick)); SDL_Log(" balls: %d\n", SDL_JoystickNumBalls(joystick)); SDL_Log(" hats: %d\n", SDL_JoystickNumHats(joystick)); SDL_Log(" buttons: %d\n", SDL_JoystickNumButtons(joystick)); SDL_Log("instance id: %d\n", SDL_JoystickInstanceID(joystick)); SDL_Log(" guid: %s\n", guid); SDL_Log(" VID/PID: 0x%.4x/0x%.4x\n", SDL_JoystickGetVendor(joystick), SDL_JoystickGetProduct(joystick)); } static void DrawRect(SDL_Renderer *r, const int x, const int y, const int w, const int h) { const SDL_Rect area = { x, y, w, h }; SDL_RenderFillRect(r, &area); } void loop(void *arg) { SDL_Event event; int i; /* blank screen, set up for drawing this frame. */ SDL_SetRenderDrawColor(screen, 0x0, 0x0, 0x0, SDL_ALPHA_OPAQUE); SDL_RenderClear(screen); while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_JOYDEVICEADDED: SDL_Log("Joystick device %d added.\n", (int) event.jdevice.which); if (!joystick) { joystick = SDL_JoystickOpen(event.jdevice.which); if (joystick) { PrintJoystick(joystick); } else { SDL_Log("Couldn't open joystick: %s\n", SDL_GetError()); } } break; case SDL_JOYDEVICEREMOVED: SDL_Log("Joystick device %d removed.\n", (int) event.jdevice.which); if (event.jdevice.which == SDL_JoystickInstanceID(joystick)) { SDL_JoystickClose(joystick); joystick = SDL_JoystickOpen(0); } break; case SDL_JOYAXISMOTION: SDL_Log("Joystick %d axis %d value: %d\n", event.jaxis.which, event.jaxis.axis, event.jaxis.value); break; case SDL_JOYHATMOTION: SDL_Log("Joystick %d hat %d value:", event.jhat.which, event.jhat.hat); if (event.jhat.value == SDL_HAT_CENTERED) SDL_Log(" centered"); if (event.jhat.value & SDL_HAT_UP) SDL_Log(" up"); if (event.jhat.value & SDL_HAT_RIGHT) SDL_Log(" right"); if (event.jhat.value & SDL_HAT_DOWN) SDL_Log(" down"); if (event.jhat.value & SDL_HAT_LEFT) SDL_Log(" left"); SDL_Log("\n"); break; case SDL_JOYBALLMOTION: SDL_Log("Joystick %d ball %d delta: (%d,%d)\n", event.jball.which, event.jball.ball, event.jball.xrel, event.jball.yrel); break; case SDL_JOYBUTTONDOWN: SDL_Log("Joystick %d button %d down\n", event.jbutton.which, event.jbutton.button); /* First button triggers a 0.5 second full strength rumble */ if (event.jbutton.button == 0) { SDL_JoystickRumble(joystick, 0xFFFF, 0xFFFF, 500); } break; case SDL_JOYBUTTONUP: SDL_Log("Joystick %d button %d up\n", event.jbutton.which, event.jbutton.button); break; case SDL_KEYDOWN: /* Press the L key to lag for 3 seconds, to see what happens when SDL doesn't service the event loop quickly. */ if (event.key.keysym.sym == SDLK_l) { SDL_Log("Lagging for 3 seconds...\n"); SDL_Delay(3000); break; } if ((event.key.keysym.sym != SDLK_ESCAPE) && (event.key.keysym.sym != SDLK_AC_BACK)) { break; } /* Fall through to signal quit */ case SDL_FINGERDOWN: case SDL_MOUSEBUTTONDOWN: case SDL_QUIT: done = SDL_TRUE; break; default: break; } } if (joystick) { /* Update visual joystick state */ SDL_SetRenderDrawColor(screen, 0x00, 0xFF, 0x00, SDL_ALPHA_OPAQUE); for (i = 0; i < SDL_JoystickNumButtons(joystick); ++i) { if (SDL_JoystickGetButton(joystick, i) == SDL_PRESSED) { DrawRect(screen, (i%20) * 34, SCREEN_HEIGHT - 68 + (i/20) * 34, 32, 32); } } SDL_SetRenderDrawColor(screen, 0xFF, 0x00, 0x00, SDL_ALPHA_OPAQUE); for (i = 0; i < SDL_JoystickNumAxes(joystick); ++i) { /* Draw the X/Y axis */ int x, y; x = (((int) SDL_JoystickGetAxis(joystick, i)) + 32768); x *= SCREEN_WIDTH; x /= 65535; if (x < 0) { x = 0; } else if (x > (SCREEN_WIDTH - 16)) { x = SCREEN_WIDTH - 16; } ++i; if (i < SDL_JoystickNumAxes(joystick)) { y = (((int) SDL_JoystickGetAxis(joystick, i)) + 32768); } else { y = 32768; } y *= SCREEN_HEIGHT; y /= 65535; if (y < 0) { y = 0; } else if (y > (SCREEN_HEIGHT - 16)) { y = SCREEN_HEIGHT - 16; } DrawRect(screen, x, y, 16, 16); } SDL_SetRenderDrawColor(screen, 0x00, 0x00, 0xFF, SDL_ALPHA_OPAQUE); for (i = 0; i < SDL_JoystickNumHats(joystick); ++i) { /* Derive the new position */ int x = SCREEN_WIDTH/2; int y = SCREEN_HEIGHT/2; const Uint8 hat_pos = SDL_JoystickGetHat(joystick, i); if (hat_pos & SDL_HAT_UP) { y = 0; } else if (hat_pos & SDL_HAT_DOWN) { y = SCREEN_HEIGHT-8; } if (hat_pos & SDL_HAT_LEFT) { x = 0; } else if (hat_pos & SDL_HAT_RIGHT) { x = SCREEN_WIDTH-8; } DrawRect(screen, x, y, 8, 8); } } SDL_RenderPresent(screen); #ifdef __EMSCRIPTEN__ if (done) { emscripten_cancel_main_loop(); } #endif } int main(int argc, char *argv[]) { SDL_SetHint(SDL_HINT_ACCELEROMETER_AS_JOYSTICK, "0"); /* Enable standard application logging */ SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO); /* Initialize SDL (Note: video is required to start event loop) */ if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s\n", SDL_GetError()); exit(1); } /* Create a window to display joystick axis position */ window = SDL_CreateWindow("Joystick Test", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH, SCREEN_HEIGHT, 0); if (window == NULL) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create window: %s\n", SDL_GetError()); return SDL_FALSE; } screen = SDL_CreateRenderer(window, -1, 0); if (screen == NULL) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create renderer: %s\n", SDL_GetError()); SDL_DestroyWindow(window); return SDL_FALSE; } SDL_SetRenderDrawColor(screen, 0x00, 0x00, 0x00, SDL_ALPHA_OPAQUE); SDL_RenderClear(screen); SDL_RenderPresent(screen); /* Loop, getting joystick events! */ #ifdef __EMSCRIPTEN__ emscripten_set_main_loop_arg(loop, NULL, 0, 1); #else while (!done) { loop(NULL); } #endif SDL_DestroyRenderer(screen); SDL_DestroyWindow(window); SDL_QuitSubSystem(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK); return 0; } #else int main(int argc, char *argv[]) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL compiled without Joystick support.\n"); return 1; } #endif /* vi: set ts=4 sw=4 expandtab: */
412
0.726483
1
0.726483
game-dev
MEDIA
0.804216
game-dev
0.662298
1
0.662298
andrewbenington/OpenHome
5,984
src/types/SAVTypes/Gen89/SwShSAV.ts
import { PK8 } from '@pokemon-files/pkm' import { utf16BytesToString } from '@pokemon-files/util' import { GameOfOrigin, GameOfOriginData, Languages } from 'pokemon-resources' import { NationalDex, PokemonData } from 'pokemon-species-data' import { SWSH_TRANSFER_RESTRICTIONS_BASE, SWSH_TRANSFER_RESTRICTIONS_CT, SWSH_TRANSFER_RESTRICTIONS_IOA, } from '../../../consts/TransferRestrictions' import { isRestricted } from '../../TransferRestrictions' import { PathData } from '../path' import { G89BlockName, G89SAV } from './G8SAV' import { SCBlock, SCObjectBlock } from './SwishCrypto/SCBlock' import { SwishCrypto } from './SwishCrypto/SwishCrypto' const SAVE_SIZE_BYTES_MIN = 0x171500 const SAVE_SIZE_BYTES_MAX = 0x187800 export type SWSH_SAVE_REVISION = 'Base Game' | 'Isle Of Armor' | 'Crown Tundra' export class SwShSAV extends G89SAV<PK8> { static boxSizeBytes = PK8.getBoxSize() * 30 static pkmType = PK8 static saveTypeAbbreviation = 'SwSh' static saveTypeName = 'Pokémon Sword/Shield' static saveTypeID = 'SwShSAV' trainerBlock: TrainerBlock constructor(path: PathData, bytes: Uint8Array) { super(path, bytes) this.trainerBlock = new TrainerBlock(this.getBlockMust('TrainerCard', 'object')) this.name = this.trainerBlock.getName() const fullTrainerID = this.trainerBlock.getFullID() this.tid = fullTrainerID % 1000000 this.sid = this.trainerBlock.getSID() this.displayID = this.tid.toString().padStart(6, '0') this.origin = this.trainerBlock.getGame() } getBoxCount(): number { return 30 } monConstructor(bytes: ArrayBuffer, encrypted: boolean): PK8 { return new PK8(bytes, encrypted) } getBlockKey(blockName: G89BlockName | keyof typeof BlockKeys): number { return BlockKeys[blockName] } getBlock(blockName: G89BlockName | keyof typeof BlockKeys): SCBlock | undefined { const key = this.getBlockKey(blockName) return this.scBlocks.find((b) => b.key === key) } getBlockMust<T extends SCBlock = SCBlock>( blockName: G89BlockName | keyof typeof BlockKeys, type?: T['blockType'] ): T { const block = this.getBlock(blockName) if (!block) { throw Error(`Missing block ${blockName}`) } if (type && block.blockType !== type) { throw Error(`Block ${blockName} is type ${block.blockType} (expected ${type})`) } return block as T } getMonBoxSizeBytes(): number { return PK8.getBoxSize() } getBoxSizeBytes(): number { return SwShSAV.boxSizeBytes } supportsMon(dexNumber: number, formeNumber: number): boolean { const revision = this.scBlocks ? this.getSaveRevision() : 'Crown Tundra' const restrictions = revision === 'Base Game' ? SWSH_TRANSFER_RESTRICTIONS_BASE : revision === 'Isle Of Armor' ? SWSH_TRANSFER_RESTRICTIONS_IOA : SWSH_TRANSFER_RESTRICTIONS_CT return !isRestricted(restrictions, dexNumber, formeNumber) } getCurrentBox() { return this.boxes[this.currentPCBox] } getGameName() { const gameOfOrigin = GameOfOriginData[this.origin] return gameOfOrigin ? `Pokémon ${gameOfOrigin.name}` : '(Unknown Game)' } getSaveRevision(): SWSH_SAVE_REVISION { return this.getBlock('ZukanR2') ? 'Crown Tundra' : this.getBlock('ZukanR1') ? 'Isle Of Armor' : 'Base Game' } getDisplayData() { const trainerBlock = this.trainerBlock const pokedexOwned = trainerBlock.getPokeDexOwned() if (pokedexOwned === 0xffff) { return { Status: 'New Save File' } } return { 'Player Character': trainerBlock.getGender() ? 'Gloria' : 'Victor', 'Save Version': this.getSaveRevision(), Language: Languages[trainerBlock.getLanguage()], Pokédex: pokedexOwned, 'Shiny Pokémon Found': trainerBlock.getShinyPokemonFound(), Starter: trainerBlock.getStarter(), } } static fileIsSave(bytes: Uint8Array): boolean { if (bytes.length < SAVE_SIZE_BYTES_MIN || bytes.length > SAVE_SIZE_BYTES_MAX) { return false } return SwishCrypto.getIsHashValid(bytes) } static includesOrigin(origin: GameOfOrigin) { return origin === GameOfOrigin.Sword || origin === GameOfOrigin.Shield } } const BlockKeys = { TeamNames: 0x1920c1e4, TeamIndexes: 0x33f39467, BoxLayout: 0x19722c89, BoxWallpapers: 0x2eb1b190, MenuButtons: 0xb1dddca8, Box: 0x0d66012c, MysteryGift: 0x112d5141, Item: 0x1177c2c4, Coordinates: 0x16aaa7fa, Misc: 0x1b882b09, Party: 0x2985fe5d, Daycare: 0x2d6fba6a, Record: 0x37da95a3, Zukan: 0x4716c404, ZukanR1: 0x3f936ba9, ZukanR2: 0x3c9366f0, PokedexRecommendation: 0xc3fb9e77, CurryDex: 0x6eb72940, TrainerCard: 0x874da6fa, PlayTime: 0x8cbbfd90, CurrentBox: 0x017c3cbb, BoxesUnlocked: 0x71825204, } class TrainerBlock { dataView: DataView<ArrayBuffer> constructor(scBlock: SCObjectBlock) { this.dataView = new DataView(scBlock.raw) } public getName(): string { return utf16BytesToString(this.dataView.buffer, 0, 24) } public getLanguage(): number { return this.dataView.getUint8(0x1b) } public getFullID(): number { return this.dataView.getUint32(0x1c, true) } public getSID(): number { return this.dataView.getUint16(0x1e, true) } public getPokeDexOwned(): number { return this.dataView.getUint16(0x20, true) } public getShinyPokemonFound(): number { return this.dataView.getUint16(0x22, true) } public getGame(): GameOfOrigin { const origin = this.dataView.getUint8(0x24) return origin === 0 ? GameOfOrigin.Sword : origin === 1 ? GameOfOrigin.Shield : GameOfOrigin.INVALID_0 } public getGender(): boolean { return !!(this.dataView.getUint8(0x38) & 1) } public getStarter(): string { const index = this.dataView.getUint8(0x25) if (index === 0xff) { return 'Not Selected' } return PokemonData[index * 3 + NationalDex.Grookey].name } }
412
0.793954
1
0.793954
game-dev
MEDIA
0.839714
game-dev
0.875226
1
0.875226
Sigma-Skidder-Team/SigmaRebase
1,771
src/main/java/net/minecraft/world/gen/layer/Layer.java
package net.minecraft.world.gen.layer; import net.minecraft.util.RegistryKey; import net.minecraft.util.SharedConstants; import net.minecraft.util.Util; import net.minecraft.util.registry.Registry; import net.minecraft.world.biome.Biome; import net.minecraft.world.biome.BiomeRegistry; import net.minecraft.world.gen.area.IAreaFactory; import net.minecraft.world.gen.area.LazyArea; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class Layer { private static final Logger LOGGER = LogManager.getLogger(); private final LazyArea field_215742_b; public Layer(IAreaFactory<LazyArea> lazyAreaFactoryIn) { this.field_215742_b = lazyAreaFactoryIn.make(); } public Biome func_242936_a(Registry<Biome> p_242936_1_, int p_242936_2_, int p_242936_3_) { int i = this.field_215742_b.getValue(p_242936_2_, p_242936_3_); RegistryKey<Biome> registrykey = BiomeRegistry.getKeyFromID(i); if (registrykey == null) { throw new IllegalStateException("Unknown biome id emitted by layers: " + i); } else { Biome biome = p_242936_1_.getValueForKey(registrykey); if (biome == null) { if (SharedConstants.developmentMode) { throw(IllegalStateException)Util.pauseDevMode(new IllegalStateException("Unknown biome id: " + i)); } else { LOGGER.warn("Unknown biome id: ", (int)i); return p_242936_1_.getValueForKey(BiomeRegistry.getKeyFromID(0)); } } else { return biome; } } } }
412
0.66626
1
0.66626
game-dev
MEDIA
0.944533
game-dev
0.672046
1
0.672046
alliedmodders/hl2sdk
2,371
game/client/c_te_basebeam.cpp
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $Workfile: $ // $Date: $ // //----------------------------------------------------------------------------- // $Log: $ // // $NoKeywords: $ //=============================================================================// #include "cbase.h" #include "c_te_basebeam.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" //----------------------------------------------------------------------------- // Purpose: Contains common variables for all beam TEs //----------------------------------------------------------------------------- C_TEBaseBeam::C_TEBaseBeam( void ) { m_nModelIndex = 0; m_nHaloIndex = 0; m_nStartFrame = 0; m_nFrameRate = 0; m_fLife = 0.0; m_fWidth = 0; m_fEndWidth = 0; m_nFadeLength = 0; m_fAmplitude = 0; r = g = b = a = 0; m_nSpeed = 0; m_nFlags = 0; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- C_TEBaseBeam::~C_TEBaseBeam( void ) { } //----------------------------------------------------------------------------- // Purpose: // Input : bool - //----------------------------------------------------------------------------- void C_TEBaseBeam::PreDataUpdate( DataUpdateType_t updateType ) { } //----------------------------------------------------------------------------- // Purpose: // Input : bool - //----------------------------------------------------------------------------- void C_TEBaseBeam::PostDataUpdate( DataUpdateType_t updateType ) { Assert( 0 ); } IMPLEMENT_CLIENTCLASS(C_TEBaseBeam, DT_BaseBeam, CTEBaseBeam); BEGIN_RECV_TABLE_NOBASE( C_TEBaseBeam, DT_BaseBeam ) RecvPropInt( RECVINFO(m_nModelIndex)), RecvPropInt( RECVINFO(m_nHaloIndex)), RecvPropInt( RECVINFO(m_nStartFrame)), RecvPropInt( RECVINFO(m_nFrameRate)), RecvPropFloat( RECVINFO(m_fLife)), RecvPropFloat( RECVINFO(m_fWidth)), RecvPropFloat( RECVINFO(m_fEndWidth)), RecvPropInt( RECVINFO(m_nFadeLength)), RecvPropFloat( RECVINFO(m_fAmplitude)), RecvPropInt( RECVINFO(m_nSpeed)), RecvPropInt( RECVINFO(r)), RecvPropInt( RECVINFO(g)), RecvPropInt( RECVINFO(b)), RecvPropInt( RECVINFO(a)), RecvPropInt( RECVINFO(m_nFlags)), END_RECV_TABLE()
412
0.905747
1
0.905747
game-dev
MEDIA
0.258184
game-dev
0.930393
1
0.930393
mojontwins/MK2
3,072
examples/hobbit_v2/dev/mainloop/level_init.h
#if defined (ENEMY_BACKUP) && defined (COMPRESSED_LEVELS) backup_baddies (); #endif playing = 1; #ifdef ENABLE_SIM sim_init (); #endif #ifndef COMPRESSED_LEVELS #ifndef DISABLE_HOTSPOTS init_hotspots (); #endif #ifdef ACTIVATE_SCRIPTING #ifdef MODE_128K main_script_offset = (unsigned int) (SCRIPT_INIT); #else main_script_offset = (unsigned int) (main_script); #endif #endif #ifndef DEACTIVATE_KEYS init_bolts (); #endif #ifdef RESTORE_ON_INIT restore_baddies (); #endif #if defined (PLAYER_KILLS_ENEMIES) || defined (PLAYER_CAN_FIRE) init_baddies (); #endif #endif #ifdef PLAYER_CAN_FIRE init_bullets (); #endif #ifdef ENABLE_SHOOTERS init_cocos (); #endif #ifndef COMPRESSED_LEVELS n_pant = SCR_INI; #endif player_init (); maincounter = 0; #ifdef ACTIVATE_SCRIPTING script_result = 0; #ifdef CLEAR_FLAGS msc_init_all (); #endif #ifdef EXTENDED_LEVELS if (level_data.activate_scripting) #endif { // Entering game script run_script (MAP_W * MAP_H * 2); } #endif #ifdef ENABLE_LAVA init_lava (); #endif do_respawn = 1; #ifdef PLAYER_KILLS_ENEMIES #ifdef SHOW_TOTAL // Show total of enemies next to the killed amount. //sp_PrintAtInv (KILLED_Y, 2 + KILLED_X, 71, 15); //sp_PrintAtInv (KILLED_Y, 3 + KILLED_X, 71, 16 + BADDIES_COUNT / 10); //sp_PrintAtInv (KILLED_Y, 4 + KILLED_X, 71, 16 + BADDIES_COUNT % 10); rda = 16 + (BADDIES_COUNT / 10); rdb = 16 + (BADDIES_COUNT % 10); #asm ld a, KILLED_Y ld c, KILLED_X + 2 ld d, 71 ld e, 15 call SPPrintAtInv ld a, (_rda) ld e, a ld a, KILLED_Y ld c, KILLED_X + 3 ld d, 71 call SPPrintAtInv ld a, (_rdb) ld e, a ld a, KILLED_Y ld c, KILLED_X + 4 ld d, 71 call SPPrintAtInv #endasm #endif #endif objs_old = keys_old = life_old = killed_old = 0xff; #ifdef MAX_AMMO ammo_old = 0xff; #endif #if defined (TIMER_ENABLE) && defined (PLAYER_SHOW_TIMER) timer_old = 0; #endif #ifdef PLAYER_SHOW_FLAG flag_old = 99; #endif #if defined (PLAYER_HAS_JETPAC) && defined (JETPAC_DEPLETES) && defined (PLAYER_SHOW_FUEL) fuel_old = 99; #endif #if defined (ENABLE_KILL_SLOWLY) && defined (PLAYER_SHOW_KILL_SLOWLY_GAUGE) ks_gauge_old = 99; #endif success = 0; #if defined (BREAKABLE_WALLS) || defined (BREAKABLE_WALLS_SIMPLE) #ifdef BREAKABLE_ANIM do_process_breakable = 0; gen_pt = breaking_f; for (gpit = 0; gpit < MAX_BREAKABLE; gpit ++) *gen_pt ++ = 0; #endif #endif #ifdef MODE_128K // Play music #if !defined (HANNA_LEVEL_MANAGER) && !defined (SIMPLE_LEVEL_MANAGER) #ifdef COMPRESSED_LEVELS #ifdef EXTENDED_LEVELS _AY_PL_MUS (level_data.music_id); #else _AY_PL_MUS (levels [level].music_id); #endif #else //_AY_PL_MUS (0); #endif #endif #endif o_pant = 0xff; #if defined (MSC_MAXITEMS) || defined (ENABLE_SIM) display_items (); #endif no_draw = 0; #ifdef CUSTOM_HIT was_hit_by_type = 0xff; #endif
412
0.822334
1
0.822334
game-dev
MEDIA
0.967217
game-dev
0.66497
1
0.66497
dotnet/runtime
8,901
src/libraries/Common/src/System/Text/OSEncoding.Windows.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Text; namespace System.Text { internal sealed class OSEncoding : Encoding { private readonly int _codePage; private string? _encodingName; internal OSEncoding(int codePage) : base(codePage) { _codePage = codePage; } public override unsafe int GetByteCount(char[] chars, int index, int count) { ArgumentNullException.ThrowIfNull(chars); ArgumentOutOfRangeException.ThrowIfNegative(index); ArgumentOutOfRangeException.ThrowIfNegative(count); if (chars.Length - index < count) throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer); if (count == 0) return 0; fixed (char* pChar = chars) { return WideCharToMultiByte(_codePage, pChar + index, count, null, 0); } } public override unsafe int GetByteCount(string s) { ArgumentNullException.ThrowIfNull(s); if (s.Length == 0) return 0; fixed (char* pChars = s) { return WideCharToMultiByte(_codePage, pChars, s.Length, null, 0); } } public override unsafe int GetBytes(string s, int charIndex, int charCount, byte[] bytes, int byteIndex) { ArgumentNullException.ThrowIfNull(s); ArgumentNullException.ThrowIfNull(bytes); ArgumentOutOfRangeException.ThrowIfNegative(charIndex); ArgumentOutOfRangeException.ThrowIfNegative(charCount); if (s.Length - charIndex < charCount) throw new ArgumentOutOfRangeException(nameof(s), SR.ArgumentOutOfRange_IndexCount); if (byteIndex < 0 || byteIndex > bytes.Length) throw new ArgumentOutOfRangeException(nameof(byteIndex), SR.ArgumentOutOfRange_IndexMustBeLessOrEqual); if (charCount == 0) return 0; if (bytes.Length == 0) { throw new ArgumentOutOfRangeException(SR.Argument_EncodingConversionOverflowBytes); } fixed (char* pChars = s) fixed (byte* pBytes = &bytes[0]) { return WideCharToMultiByte(_codePage, pChars + charIndex, charCount, pBytes + byteIndex, bytes.Length - byteIndex); } } public override unsafe int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { ArgumentNullException.ThrowIfNull(chars); ArgumentNullException.ThrowIfNull(bytes); ArgumentOutOfRangeException.ThrowIfNegative(charIndex); ArgumentOutOfRangeException.ThrowIfNegative(charCount); if (chars.Length - charIndex < charCount) throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer); if (byteIndex < 0 || byteIndex > bytes.Length) throw new ArgumentOutOfRangeException(nameof(byteIndex), SR.ArgumentOutOfRange_IndexMustBeLessOrEqual); if (charCount == 0) return 0; if (bytes.Length == 0) { throw new ArgumentOutOfRangeException(SR.Argument_EncodingConversionOverflowBytes); } fixed (char* pChars = chars) fixed (byte* pBytes = &bytes[0]) { return WideCharToMultiByte(_codePage, pChars + charIndex, charCount, pBytes + byteIndex, bytes.Length - byteIndex); } } public override unsafe int GetCharCount(byte[] bytes, int index, int count) { ArgumentNullException.ThrowIfNull(bytes); ArgumentOutOfRangeException.ThrowIfNegative(index); ArgumentOutOfRangeException.ThrowIfNegative(count); if (bytes.Length - index < count) throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); if (count == 0) return 0; fixed (byte* pBytes = bytes) { return MultiByteToWideChar(_codePage, pBytes + index, count, null, 0); } } public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { ArgumentNullException.ThrowIfNull(bytes); ArgumentNullException.ThrowIfNull(chars); ArgumentOutOfRangeException.ThrowIfNegative(byteIndex); ArgumentOutOfRangeException.ThrowIfNegative(byteCount); if (bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); if (charIndex < 0 || charIndex > chars.Length) throw new ArgumentOutOfRangeException(nameof(charIndex), SR.ArgumentOutOfRange_IndexMustBeLessOrEqual); if (byteCount == 0) return 0; if (chars.Length == 0) throw new ArgumentOutOfRangeException(SR.Argument_EncodingConversionOverflowChars); fixed (byte* pBytes = bytes) fixed (char* pChars = &chars[0]) { return MultiByteToWideChar(_codePage, pBytes + byteIndex, byteCount, pChars + charIndex, chars.Length - charIndex); } } public override int GetMaxByteCount(int charCount) { ArgumentOutOfRangeException.ThrowIfNegative(charCount); long byteCount = (long)charCount * 14; // Max possible value for all encodings if (byteCount > 0x7fffffff) throw new ArgumentOutOfRangeException(nameof(charCount), SR.ArgumentOutOfRange_GetByteCountOverflow); return (int)byteCount; } public override int GetMaxCharCount(int byteCount) { ArgumentOutOfRangeException.ThrowIfNegative(byteCount); long charCount = (long)byteCount * 4; // Max possible value for all encodings if (charCount > 0x7fffffff) throw new ArgumentOutOfRangeException(nameof(byteCount), SR.ArgumentOutOfRange_GetCharCountOverflow); return (int)charCount; } public override string EncodingName => _encodingName ??= $"Codepage - {_codePage}"; public override string WebName { get { return EncodingName; } } public override Encoder GetEncoder() { return new OSEncoder(this); } public override Decoder GetDecoder() { switch (CodePage) { case 932: // Japanese (Shift-JIS) case 936: // Chinese Simplified (GB2312) case 949: // Korean case 950: // Chinese Traditional (Big5) case 1361: // Korean (Johab) case 10001: // Japanese (Mac) case 10002: // Chinese Traditional (Mac) case 10003: // Korean (Mac) case 10008: // Chinese Simplified (Mac) case 20000: // Chinese Traditional (CNS) case 20001: // TCA Taiwan case 20002: // Chinese Traditional (Eten) case 20003: // IBM5550 Taiwan case 20004: // TeleText Taiwan case 20005: // Wang Taiwan case 20261: // T.61 case 20932: // Japanese (JIS 0208-1990 and 0212-1990) case 20936: // Chinese Simplified (GB2312-80) case 51949: // Korean (EUC) return new DecoderDBCS(this); default: return base.GetDecoder(); } } internal static unsafe int WideCharToMultiByte(int codePage, char* pChars, int count, byte* pBytes, int byteCount) { int result = Interop.Kernel32.WideCharToMultiByte((uint)codePage, 0, pChars, count, pBytes, byteCount, null, null); if (result <= 0) throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex); return result; } internal static unsafe int MultiByteToWideChar(int codePage, byte* pBytes, int byteCount, char* pChars, int count) { int result = Interop.Kernel32.MultiByteToWideChar((uint)codePage, 0, pBytes, byteCount, pChars, count); if (result <= 0) throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex); return result; } } }
412
0.876997
1
0.876997
game-dev
MEDIA
0.094742
game-dev
0.881318
1
0.881318
sm64js/sm64js
4,609
src/game/behaviors/blue_coin.inc.js
/** * Behavior for bhvHiddenBlueCoin and bhvBlueCoinSwitch. * bhvHiddenBlueCoin are the stationary blue coins that appear when * you press a blue coin switch (a.k.a. bhvBlueCoinSwitch). */ import { gGlobalSoundSource, play_sound } from "../../audio/external" import { MODEL_SPARKLES } from "../../include/model_ids" import { BLUE_COIN_SWITCH_ACT_IDLE, BLUE_COIN_SWITCH_ACT_RECEDING, BLUE_COIN_SWITCH_ACT_TICKING, HIDDEN_BLUE_COIN_ACT_ACTIVE, HIDDEN_BLUE_COIN_ACT_INACTIVE, HIDDEN_BLUE_COIN_ACT_WAITING, oAction, oGravity, oHiddenBlueCoinSwitch, oInteractStatus, oPosY, oTimer, oVelY } from "../../include/object_constants" import { SOUND_GENERAL2_SWITCH_TICK_FAST, SOUND_GENERAL2_SWITCH_TICK_SLOW, SOUND_GENERAL_SWITCH_DOOR_OPEN } from "../../include/sounds" import { spawn_mist_particles_variable } from "../BehaviorActions" import { bhvBlueCoinSwitch, bhvGoldenCoinSparkles, bhvHiddenBlueCoin } from "../BehaviorData" import { INT_STATUS_INTERACTED } from "../Interaction" import { ACT_GROUND_POUND_LAND } from "../Mario" import { cur_obj_become_intangible, cur_obj_become_tangible, cur_obj_disable_rendering, cur_obj_enable_rendering, cur_obj_hide, cur_obj_move_using_fvel_and_gravity, cur_obj_nearest_object_with_behavior, cur_obj_scale, cur_obj_wait_then_blink, obj_mark_for_deletion, spawn_object } from "../ObjectHelpers" import { cur_obj_play_sound_2 } from "../SpawnSound" /** * Update function for bhvHiddenBlueCoin. */ export const bhv_hidden_blue_coin_loop = () => { const o = gLinker.ObjectListProcessor.gCurrentObject switch (o.rawData[oAction]) { case HIDDEN_BLUE_COIN_ACT_INACTIVE: cur_obj_disable_rendering() cur_obj_become_intangible() o.rawData[oHiddenBlueCoinSwitch] = cur_obj_nearest_object_with_behavior(o, bhvBlueCoinSwitch) if (o.rawData[oHiddenBlueCoinSwitch] != null) { o.rawData[oAction]++ } break case HIDDEN_BLUE_COIN_ACT_WAITING: // const blueCoinSwitch = o.rawData[oHiddenBlueCoinSwitch] if (o.rawData[oHiddenBlueCoinSwitch].rawData[oAction] == BLUE_COIN_SWITCH_ACT_TICKING) { o.rawData[oAction]++ } break case HIDDEN_BLUE_COIN_ACT_ACTIVE: cur_obj_enable_rendering() cur_obj_become_tangible() if (o.rawData[oInteractStatus] & INT_STATUS_INTERACTED) { spawn_object(o, MODEL_SPARKLES, bhvGoldenCoinSparkles) obj_mark_for_deletion(o) } if (cur_obj_wait_then_blink(200, 20)) { obj_mark_for_deletion(o) } break } o.rawData[oInteractStatus] = 0 } /** * Update function for bhvBlueCoinSwitch. */ export const bhv_blue_coin_switch_loop = () => { const o = gLinker.ObjectListProcessor.gCurrentObject const gMarioObject = gLinker.ObjectListProcessor.gMarioObject const gMarioStates = [ gLinker.LevelUpdate.gMarioState ] cur_obj_scale(3.0) switch (o.rawData[oAction]) { case BLUE_COIN_SWITCH_ACT_IDLE: if (gMarioObject.platform == o) { if (gMarioStates[0].action == ACT_GROUND_POUND_LAND) { o.rawData[oAction]++ o.rawData[oVelY] = -20.0 o.rawData[oGravity] = 0.0 cur_obj_play_sound_2(SOUND_GENERAL_SWITCH_DOOR_OPEN) } } gLinker.SurfaceLoad.load_object_collision_model() break case BLUE_COIN_SWITCH_ACT_RECEDING: if (o.rawData[oTimer] > 5) { cur_obj_hide() o.rawData[oAction]++ o.rawData[oPosY] = gMarioObject.rawData[oPosY] - 40.0 spawn_mist_particles_variable(0, 0, 46.0) } else { gLinker.SurfaceLoad.load_object_collision_model() cur_obj_move_using_fvel_and_gravity() } case BLUE_COIN_SWITCH_ACT_TICKING: if (o.rawData[oTimer] < 200) { play_sound(SOUND_GENERAL2_SWITCH_TICK_FAST, gGlobalSoundSource) } else { play_sound(SOUND_GENERAL2_SWITCH_TICK_SLOW, gGlobalSoundSource) } if (cur_obj_nearest_object_with_behavior(o, bhvHiddenBlueCoin) == null || o.rawData[oTimer] > 240) { obj_mark_for_deletion(o) } break } } gLinker.bhv_hidden_blue_coin_loop = bhv_hidden_blue_coin_loop gLinker.bhv_blue_coin_switch_loop = bhv_blue_coin_switch_loop
412
0.891654
1
0.891654
game-dev
MEDIA
0.646242
game-dev
0.758842
1
0.758842
Mogara/QSanguosha-For-Hegemony
7,069
extension-doc/6-Applications.lua
--技能讲解5:基本技能类型的组合和复杂技能的实现(一) --[[ 在游戏中,对于有些技能来说,我们不可能仅仅通过写一个技能来实现这些效果。 因此,基本技能的组合对于国战(也包括身份)来说是非常重要的。 在这个文档中,我们会介绍两种技能组合的形式。 第一种是并列式,也就是两个技能是并列存在的。 先来看这样一个技能: ]] --[[ 奇心:锁定技,你的手牌上限增加X,X为你当前的体力;你的攻击范围增加X,X为你损失的体力。 ]] --[[ 分析:通过技能描述,我们可以看出这个技能是由两个基本技能组成: 1.手牌上限 2.攻击范围 因此,我们需要写两个技能就能完成任务。 代码如下: ]] devQixin = sgs.CreateMaxCardsSkill{ name = "devQixin", extra_func = function(self, target) if target:hasSkill(self:objectName()) and (target:hasShownSkill(self) or target:askForSkillInvoke(self:objectName())) then --别忘了,手牌上限技在国战里面可是在服务器执行的,所以可以询问发动技能。 return target:getHp() end end } devQixinAttackRange = sgs.CreateAttackRangeSkill{ name = "#devQixin_attack", --技能名以#开头的技能会隐藏起来(没有按钮),但是仍然有效果 extra_func = function(self, target) if target:hasSkill(self:objectName()) and target:hasShownSkill(self) then return target:getLostHp() end end } sgs.insertRelatedSkills(extension,"devQixin","#devQixin_attack") --最后一句是把两个小技能组合起来,其中extension参数是扩展包,第二个参数是主技能(即不隐藏的技能),后面的是附加技能。 --附加技能可以有很多,如果有很多,可以这样写: sgs.insertRelatedSkills(extension,"main","#related1","#related2","#related3") --这里的字符串也可以换成技能对象,比如说: sgs.insertRelatedSkills(extension,devQixin,devQixinAttackRange) --[[ 看完上面的技能,你是否对技能组合有了一定的初步认识? 这些在身份局的相关教程也被介绍过。 我们再来看另外一种组合方式:嵌入式 对于嵌入式技能来说,一般是一个视为技+一个触发技的组合,二者用触发技的view_as_skill成员连接。 有些情况下,还需要技能卡的参与。 来看这样一个技能: ]] --[[ 奸雄:出牌阶段限一次,你可以将一张牌当作本出牌阶段上次使用的牌使用。(杀需要考虑限制) 其实就是英雄杀的曹操的技能。 ]] --[[ 我们可以把这个技能分成两个小部分: 1.在使用完基本牌后,记录一下基本牌的id 2.在视为技中获取id,然后制造出这样一张牌。 ]] devJiaoxiongVS = sgs.CreateViewAsSkill{ --这里可以换成OneCardViewAsSkill name = "devJiaoxiong", --这里的name要和下面触发技的保持一致。 n = 1, enabled_at_play = function(self, player) if player:getMark(self:objectName()) >= 0 then return not player:hasFlag("hasUsed"..self:objectName()) end end, view_filter = function(self, selected, to_select) return not to_select:isEquipped() end, view_as = function(self, cards) if #cards == 1 then local acard = sgs.Sanguosha:cloneCard(sgs.Sanguosha:getCard(sgs.Self:getMark(self:objectName())):objectName()) --sgs.Self也可以获取Mark,前提是使用Room的setPlayerMark设置。 assert(acard) --assert函数将会在后面的章节介绍 acard:addSubcard(cards[1]:getId()) acard:setSkillName(self:objectName()) acard:setShowSkill(self:objectName()) return acard end end, } devJiaoxiong = sgs.CreateTriggerSkill{ name = "devJiaoxiong", view_as_skill = devJiaoxiongVS, events = {sgs.CardFinished,sgs.EventPhaseStart}, can_trigger = function(self, event, room, player, data) if player and player:isAlive() and player:hasSkill(self:objectName()) then if player:getPhase() ~= sgs.Player_Play then return "" end if event == sgs.CardFinished then local use = data:toCardUse() local card = use.card if card:getSkillName() ~= self:objectName() and (not card:isKindOf("EquipCard")) then room:setPlayerMark(player,self:objectName(),card:getId()) --这里通过Mark来传递ID elseif card:getSkillName() == self:objectName() then room:setPlayerFlag(player,"hasUsed"..self:objectName()) room:setPlayerMark(player,self:objectName(),-1) --貌似有Id为0的Card,所以使用-1 end else room:setPlayerMark(player,self:objectName(),-1) end end return "" end } --[[ 这个技能由一个触发技和一个视为技组成,之间用view_as_skill连接起来。 其实这种方式和并列式差不多,当然这种方式比并列式更简洁,尤其是在处理提示使用(askForUseCard)的时候相当有效。 再来看一个相对复杂的技能: ]] --[[ 箭矢:每当你的黑色牌因弃置而失去时,你可将这些牌置于你的武将牌上称为“箭”。回合外你可将两张“箭”当成【无懈可击】使用。 ]] --[[ 分析:通过技能描述,我们可以看出这个技能是由两个基本技能组成的,一个是将被弃置的黑色牌置于牌堆上,另一种则是视为无懈可击。 这个技能有新旧两种形式,为了便于教学,我们这里使用旧式的技能作为范例。(新式的技能将会在后面用到) 代码如下: ]] devJianshiCard = sgs.CreateSkillCard{ name = "devJianshiCard", target_fixed = true, will_throw = false, skill_name = "devJianshi", on_validate = function(self, carduse) --这两个函数到下面再解释。 local source = cardUse.from local room = source:getRoom() local ncard = sgs.Sanguosha:cloneCard("nullification") ncard:setSkillName("devJianshi") local ids = source:getPile("devJianshi") for i = 0, 1, 1 do room:fillAG(ids, source) local id = room:askForAG(source, ids, false, "devJianshi") ncard:addSubcard(id) ids:removeOne(id) room:clearAG(source) end return ncard end, on_validate_in_response = function(self, source) --同理 local room = source:getRoom() local ncard = sgs.Sanguosha:cloneCard("nullification") ncard:setSkillName("devJianshi") local ids = source:getPile("devJianshi") for i = 0,1,1 do room:fillAG(ids, source) local id = room:askForAG(source, ids, false, "devJianshi") ncard:addSubcard(id) ids:removeOne(id) room:clearAG(source) end return ncard end, } devJianshiVS = sgs.CreateZeroCardViewAsSkill{ --详细定义可以参考lua\sgs_ex.lua name = "devJianshi", view_as = function(self) local ac = devJianshiCard:clone() ac:setSkillName("devJianshi") ac:setShowSkill("devJianshi") return ac end, enabled_at_play = function(self, player) return false end, enabled_at_response = function(self, player, pattern) return pattern == "nullification" and player:getPile("devJianshi"):length() > 1 end, enabled_at_nullification = function(self, player) return player:getPile("devJianshi"):length() > 1 end } devJianshi = sgs.CreateTriggerSkill{ name = "devJianshi", view_as_skill = devJianshiVS, events = {sgs.BeforeCardsMove}, can_trigger = function(self, event, room, player, data) if player and player:isAlive() and player:hasSkill(self:objectName()) then local move = data:toMoveOneTime() if move.from and move.from:objectName() ~= player:objectName() then return "" end if bit32.band(move.reason.m_reason, sgs.CardMoveReason_S_MASK_BASIC_REASON) == sgs.CardMoveReason_S_REASON_DISCARD then for i = 0, move.card_ids:length()-1, 1 do local id = move.card_ids:at(i) card = sgs.Sanguosha:getCard(id) if move.from_places:at(i) == sgs.Player_PlaceHand or move.from_places:at(i) == sgs.Player_PlaceEquip then if card:isBlack() then return self:objectName() end end end end return "" end end, on_cost = function(self, event, room, player, data) if player:askForSkillInvoke(self:objectName(), data) then return true end return false end , on_effect = function(self, event, room, player, data) local move = data:toMoveOneTime() local card local dummy = sgs.Sanguosha:cloneCard("jink") for i = 0, move.card_ids:length()-1, 1 do local id = move.card_ids:at(i) card = sgs.Sanguosha:getCard(id) if move.from_places:at(i) == sgs.Player_PlaceHand or move.from_places:at(i) == sgs.Player_PlaceEquip then if card:isBlack() then dummy:addSubcard(id) end end end for _,id in sgs.qlist(dummy:getSubcards()) do move.card_ids:removeOne(id) end data:setValue(move) --如果对data做过更变一定不要忘记setValue player:addToPile("devJianshi", dummy:getSubcards()) dummy:deleteLater() --记住,DummyCard不用一定要删除,否则会造成内存泄漏。 end, } --[[ 仔细研究一下这个技能,也有很多值得学习的地方,这里我们就不深入研究了。 通过以上几个例子发现,当一个技能在我们面前的时候,我们可以按照这样的步骤去完成技能代码: 1.分析技能,如果技能用一个基本技能就可以解决,就用一个技能解决;否则的话考虑使用两个或多个技能 2.分清职责,什么技能处理什么效果一定要明白。必要时可以使用注视。 3.撰写代码,这一步没有什么说的 4.组合,千万别忘记sgs.insertRelatedSkills或者view_as_skill ]]
412
0.796589
1
0.796589
game-dev
MEDIA
0.865725
game-dev
0.605123
1
0.605123
angular/react-native-renderer
10,049
src/renderer/renderer.ts
import { RendererFactory2, Renderer2, RendererType2, RendererStyleFlags2, InjectionToken, Inject, Injectable, NgZone, Sanitizer, SecurityContext, AnimationPlayer, SchemaMetadata, Compiler } from "@angular/core"; import {ElementSchemaRegistry} from "@angular/compiler"; import {Node, ElementNode, TextNode, nodeMap, CommentNode} from "./node"; import {ReactNativeWrapper} from "./../wrapper/wrapper"; import { NativeCommand, NativeCommandCreate, NativeCommandUpdate, NativeCommandAttach, NativeCommandDetach, NativeCommandAttachAfter } from "./native_command"; export const REACT_NATIVE_WRAPPER: InjectionToken<string> = new InjectionToken("ReactNativeWrapper"); export class ReactNativeElementSchemaRegistry extends ElementSchemaRegistry { getDefaultComponentElementName(): string { return 'def-cpt'; } hasProperty(tagName: string, propName: string): boolean { return true; } hasElement(tagName: string, schemaMetas: SchemaMetadata[]): boolean { return true; } getMappedPropName(propName: string): string { return propName; } securityContext(tagName: string, propName: string): any { return 0; } validateProperty(name: string): {error: boolean; msg?: string} { return {error: false}; } validateAttribute(name: string): {error: boolean; msg?: string} { return {error: false}; } allKnownElementNames(): string[] { return []; } normalizeAnimationStyleProperty(propName: string): string { return propName; } normalizeAnimationStyleValue( camelCaseProp: string, userProvidedProp: string, val: string|number): {error: string, value: string} { return {error: null, value: '' + val} } } export class ReactNativeSanitizer implements Sanitizer { sanitize(ctx: SecurityContext, value: any): string { return value; } } @Injectable() export class ReactNativeRootRenderer implements RendererFactory2 { public zone: NgZone; public wrapper: ReactNativeWrapper; private _registeredComponents: Map<string, ReactNativeRenderer> = new Map<string, ReactNativeRenderer>(); private _createCommands: Map<Node, NativeCommandCreate> = new Map<Node, NativeCommandCreate>(); private _updateCommands: Map<Node, NativeCommandUpdate> = new Map<Node, NativeCommandUpdate>(); private _attachCommands: Map<Node, NativeCommandAttach> = new Map<Node, NativeCommandAttach>(); private _attachAfterCommands: Map<Node, NativeCommandAttachAfter> = new Map<Node, NativeCommandAttachAfter>(); private _detachCommands: Map<Node, NativeCommandDetach> = new Map<Node, NativeCommandDetach>(); constructor(@Inject(REACT_NATIVE_WRAPPER) _wrapper: ReactNativeWrapper) { this.wrapper = _wrapper; this.wrapper.patchReactNativeEventEmitter(nodeMap); } createRenderer(hostElement: any, type: RendererType2 | any): Renderer2 { return new ReactNativeRenderer(this); } addCreateCommand(node: Node, props: {[s: string]: any } = null) { var cmd = new NativeCommandCreate(node); if (props) { cmd.props = props; } this._createCommands.set(node, cmd); } addUpdateCommand(node: Node, key: string, value: any) { var propEater: NativeCommandCreate | NativeCommandUpdate = <NativeCommandCreate | NativeCommandUpdate>this._createCommands.get(node) || this._updateCommands.get(node); if (propEater) { propEater.props[key] = value; } else { this._updateCommands.set(node, new NativeCommandUpdate(node, key, value)); } } addAttachCommand(node: Node, toRoot: boolean) { this._attachCommands.set(node, new NativeCommandAttach(node, toRoot)); } addAttachAfterCommand(node: Node, anchor: Node) { this._attachAfterCommands.set(node, new NativeCommandAttachAfter(node, anchor)); } addDetachCommand(node: Node) { this._detachCommands.set(node, new NativeCommandDetach(node)); } executeCommands(): void { this._detachCommands.forEach((command: NativeCommandDetach) => command.execute(this.wrapper)); this._createCommands.forEach((command: NativeCommandCreate) => command.execute(this.wrapper)); this._updateCommands.forEach((command: NativeCommandUpdate) => command.execute(this.wrapper)); this._attachCommands.forEach((command: NativeCommandAttach) => command.execute(this.wrapper)); var counters: Map<Node,number> = new Map<Node, number>(); this._attachAfterCommands.forEach((command: NativeCommandAttachAfter) => command.executeWithCounters(this.wrapper, counters)); counters.clear(); NativeCommand.mergeAndApply(this.wrapper); this._detachCommands.clear(); this._createCommands.clear(); this._updateCommands.clear(); this._attachCommands.clear(); this._attachAfterCommands.clear(); } } export class ReactNativeRenderer implements Renderer2 { data: {[key: string]: any;} = {}; constructor(private _rootRenderer: ReactNativeRootRenderer) {} selectRootElement(selector: string): Node { const root = this.createElement(selector.startsWith('#root') ? 'test-cmp' : selector); this._createElementCommand(root); this._rootRenderer.addAttachCommand(root, true); return root; } createElement(name: string, namespace?: string | any): Node { //console.log('createElement:' + name); return new ElementNode(name, this._rootRenderer.wrapper, this._rootRenderer); } createComment(value: string): any { return new CommentNode(this._rootRenderer.wrapper, this._rootRenderer); } createText(value: string): Node { //console.log('createText:' + value); return new TextNode(value, this._rootRenderer.wrapper, this._rootRenderer); } destroyNode(node: Node): any { node.toBeDestroyed = true; } destroy(): void { //console.log('NOT IMPLEMENTED: destroy', arguments); } appendChild(parent: Node, newChild: Node): void { //console.log('appendChild'); newChild.attachTo(parent); if (newChild.getAncestorWithNativeCreated()) { if (this._createNativeRecursively(newChild)) { this._rootRenderer.addAttachCommand(newChild, false); } } } insertBefore(parent: any, newChild: any, refChild: any): void { //console.log('insertBefore'); const index = parent.children.indexOf(refChild); newChild.attachToAt(parent, index); if (newChild.getAncestorWithNativeCreated()) { if (this._createNativeRecursively(newChild)) { this._rootRenderer.addAttachCommand(newChild, false); } } } removeChild(parent: any, oldChild: any): void { const index = parent.children.indexOf(oldChild); parent.children.splice(index, 1); this._rootRenderer.addDetachCommand(oldChild); } parentNode(node: Node): Node { return node.parent; } nextSibling(node: Node): any { let res = null; const parent = node.parent; if (parent) { const index = parent.children.indexOf(node) + 1; if (parent.children.length > index) { res = parent.children[index]; } } return res; } setAttribute(el: Node, name: string, value: string, namespace?: string | any): void { var val: any = value; if (name == "ng-version") return; if (value == "false") val = false; if (value == "true") val = true; if (value == "null") val = null; if (!isNaN(parseInt(val))) val = parseInt(val); if (value.startsWith('#')) val = this._rootRenderer.wrapper.processColor(value); this.setProperty(el, name, val); } removeAttribute(el: any, name: string, namespace?: string | any): void { } addClass(el: any, name: string): void { console.error('NOT IMPLEMENTED: addClass', arguments); } removeClass(el: any, name: string): void { console.error('NOT IMPLEMENTED: removeClass', arguments); } setStyle(el: any, style: string, value: any, flags?: RendererStyleFlags2): void { console.error('NOT IMPLEMENTED: setStyle', arguments); } removeStyle(el: any, style: string, flags?: RendererStyleFlags2): void { console.error('NOT IMPLEMENTED: removeStyle', arguments); } setProperty(el: Node, name: string, value: any): void { if (typeof value !== 'undefined') { const cleanPropertyName = name.startsWith('_on') ? name.substr(1) : name; el.setProperty(cleanPropertyName, value, false); if (el.isCreated) { this._rootRenderer.addUpdateCommand(el, cleanPropertyName, value); } } } setValue(node: Node, value: string): void { if (node instanceof TextNode) { const trimedText = node.setText(value); this.setProperty(node, 'text', trimedText); } } listen(target: 'window' | 'document' | 'body' | Node, eventName: string, callback: (event: any) => boolean | void): () => void { if (target === 'window' || target == 'document' || target == 'body') { console.error('NOT IMPLEMENTED: listen on ' + target, arguments); return () => {}; } else { target.addEventListener(eventName, callback); return () => {target.removeEventListener(eventName, callback);}; } } private _createElementCommand(node: Node): void { this._rootRenderer.addCreateCommand(node); node.isCreated = true; } private _createTextCommand(node: TextNode): void { this._rootRenderer.addCreateCommand(node, {text: node.properties['text']}); var cmd = new NativeCommandCreate(node); node.isCreated = true; } private _createNativeRecursively(node: Node, isRoot: boolean = true): boolean { var didCreate: boolean = false; if (!node.isCreated) { if (!node.isVirtual) { node instanceof TextNode ? this._createTextCommand(node) : this._createElementCommand(node); didCreate = !(node instanceof TextNode) || isRoot; } for (var i = 0; i < node.children.length; i++) { var child = node.children[i]; didCreate = this._createNativeRecursively(child, false) || didCreate; if (!child.isVirtual && !(isRoot && node.isVirtual)) { this._rootRenderer.addAttachCommand(child, false); } } } return didCreate; } }
412
0.898985
1
0.898985
game-dev
MEDIA
0.839892
game-dev
0.954643
1
0.954643
NetCodersX/Unity-Script
1,705
GOAP项目演示/Assets/GOAP/Scripts/Example/Performance/TestNumAi.cs
using UnityEngine; using System.Collections; public class TestNumAi : MonoBehaviour { public GameObject Target; public int MaxNum; void Start () { StartCoroutine(GenerateAi()); } private IEnumerator GenerateAi() { Target.SetActive(false); for (int i = 0; i < MaxNum; i++) { GameObject go = Instantiate(Target); go.name = i.ToString(); go.SetActive(true); AddRandomWork(go); yield return new WaitForSeconds(0.01f); } } public Material MatMiner; public Material MatLogger; public Material MatBlacksmith; public Material MatWoodCutter; private void AddRandomWork(GameObject go) { MeshRenderer mr = go.GetComponentInChildren<MeshRenderer>(); float r = Random.Range(0f, 1f); if (r < 0.2f) { go.AddComponent<MineOreAction>(); go.AddComponent<DropOffOreAction>(); mr.sharedMaterial = MatMiner; } else if (r < 0.4f) { go.AddComponent<ChopTreeAction>(); go.AddComponent<DropOffLogsAction>(); mr.sharedMaterial = MatLogger; } else if (r < 0.6f) { go.AddComponent<PickUpOreAction>(); go.AddComponent<ForgeToolAction>(); go.AddComponent<DropOffToolsAction>(); mr.sharedMaterial = MatBlacksmith; } else if (r < 0.8f) { go.AddComponent<ChopFirewoodAction>(); go.AddComponent<DropOffFirewoodAction>(); mr.sharedMaterial = MatWoodCutter; } else { //nothing } } }
412
0.834687
1
0.834687
game-dev
MEDIA
0.940947
game-dev
0.93497
1
0.93497
CrankBoyHQ/crankboy-app
7,845
src/utility.h
// // utility.h // CrankBoy // // Created by Matteo D'Ignazio on 14/05/22. // Maintained and developed by the CrankBoy dev team. // #ifndef utility_h #define utility_h #include "array.h" #include "pd_api.h" #include <stdbool.h> #include <stdint.h> #include <stdio.h> extern PlaydateAPI* playdate; #define CB_DEBUG false #define CB_DEBUG_UPDATED_ROWS false #define ENABLE_RENDER_PROFILER false /* Enables (1) or disables (0) CPU validation in the Simulator. * Use this if you make changes to the optimized CPU instructions * and want to test them agains the unoptimized path. * Note: use this for debugging only. */ #define ENABLE_CPU_VALIDATION 0 #define CB_LCD_WIDTH 320 #define CB_LCD_HEIGHT 240 #define CB_LCD_ROWSIZE 40 #define CB_LCD_X 40 // multiple of 8 #define CB_LCD_Y 0 #define CB_MAX(x, y) (((x) > (y)) ? (x) : (y)) #define CB_MIN(x, y) (((x) < (y)) ? (x) : (y)) #define CRC_CACHE_FILE "crc_cache.json" #define LOGO_TEXT_VERTICAL_GAP 20 extern const uint8_t CB_patterns[4][4][4]; extern const char* CB_savesPath; extern const char* CB_gamesPath; extern const char* CB_coversPath; extern const char* CB_statesPath; extern const char* CB_settingsPath; extern const char* CB_globalPrefsPath; extern const char* CB_patchesPath; typedef struct { char* short_name; char* detailed_name; uint32_t crc32; bool failedToOpenROM; } CB_FetchedNames; typedef enum { CB_UISound_Navigate, // For up/down movement CB_UISound_Confirm // For selection/changing a value } CB_UISound; typedef enum { CB_COVER_ART_SUCCESS, CB_COVER_ART_ERROR_LOADING, CB_COVER_ART_INVALID_IMAGE, CB_COVER_ART_FILE_NOT_FOUND } CB_CoverArtStatus; typedef struct { LCDBitmap* bitmap; int original_width; int original_height; int scaled_width; int scaled_height; CB_CoverArtStatus status; } CB_LoadedCoverArt; typedef enum { PROGRESS_STYLE_PERCENT, PROGRESS_STYLE_FRACTION } CB_ProgressStyle; char* cb_strdup(const char* string); char* cb_basename(const char* filename, bool stripExtension); char* cb_save_filename(const char* filename, bool isRecovery); char* cb_extract_fs_error_code(const char* filename); char* common_article_form(const char* input); float cb_easeInOutQuad(float x); // like playdate->file->listfiles, but can filter by file type (pdx/data) int cb_listfiles( const char* path, void (*callback)(const char* filename, void* userdata), void* userdata, int showhidden, FileOptions fopts ); int cb_file_exists(const char* path, FileOptions fopts); int cb_compare_games_by_display_name(const void* a, const void* b); int cb_compare_strings(const void* a, const void* b); int cb_calculate_progress_max_width(LCDFont* font, CB_ProgressStyle style, size_t total_items); void cb_sanitize_string_for_filename(char* str); void cb_sort_games_array(CB_Array* games_array); void cb_draw_logo_screen_and_display(LCDFont* font, const char* message); void cb_draw_logo_screen_to_buffer(LCDFont* font, const char* message); void cb_draw_logo_screen_centered_split( LCDFont* font, const char* static_text, const char* dynamic_text, int dynamic_text_max_width ); void cb_fillRoundRect(PDRect rect, int radius, LCDColor color); void cb_drawRoundRect(PDRect rect, int radius, int lineWidth, LCDColor color); // result must be user-free'd. returns NULL on error. char* cb_read_entire_file(const char* path, size_t* o_size, unsigned flags); // returns false on error bool cb_write_entire_file(const char* path, const void* data, size_t size); void* cb_malloc(size_t size); void* cb_realloc(void* ptr, size_t size); void* cb_calloc(size_t count, size_t size); void cb_free(void* ptr); size_t cb_strlen(const char* s); char* cb_strrchr(const char* s, int c); int cb_strcmp(const char* s1, const char* s2); // returns false on failure bool cb_calculate_crc32(const char* filepath, FileOptions fopts, uint32_t* crc); uint32_t crc32_for_buffer(const unsigned char* buf, size_t len); char* cb_find_cover_art_path_from_list( const CB_Array* available_covers, const char* rom_basename_no_ext, const char* rom_clean_basename_no_ext ); CB_FetchedNames cb_get_titles_from_db(const char* fullpath); CB_FetchedNames cb_get_titles_from_db_by_crc(uint32_t crc); char* cb_url_encode_for_github_raw(const char* str); char* cb_game_config_path(const char* rom_filename); // allocate-print-to-string char* aprintf(const char* fmt, ...); // caller-freed char* en_human_time(unsigned seconds); bool string_has_descenders(const char* str); CB_LoadedCoverArt cb_load_and_scale_cover_art_from_path( const char* cover_path, int max_target_width, int max_target_height ); void cb_free_loaded_cover_art_bitmap(CB_LoadedCoverArt* art_result); void cb_clear_global_cover_cache(void); void cb_play_ui_sound(CB_UISound sound); char* strltrim(const char* str); static inline float toward(float x, float dst, float step) { if (dst > x) { x += step; if (x > dst) x = dst; } else { x -= step; if (x < dst) x = dst; } return x; }; #define TOWARD(x, dst, step) \ do \ { \ float* a = &(x); \ *a = toward(*a, dst, step); \ } while (0) #ifdef TARGET_PLAYDATE #define __section__(x) __attribute__((section(x))) #else #define __section__(x) #endif #define likely(x) (__builtin_expect(!!(x), 1)) #define unlikely(x) (__builtin_expect(!!(x), 0)) #ifdef TARGET_SIMULATOR #define clalign #else #define clalign __attribute__((aligned(32))) #endif #ifdef TARGET_SIMULATOR #define CPU_VALIDATE ENABLE_CPU_VALIDATION #if CPU_VALIDATE == 1 #define CB_ASSERT(x) \ if (!(x)) \ playdate->system->error("ASSERTION FAILED: %s", #x); #else #define CB_ASSERT(x) ((void)0) #endif #else #define CPU_VALIDATE 0 #define CB_ASSERT(x) ((void)0) #endif // compute the next highest power of 2 of 32-bit v, // or v if v is a power of 2 // https://stackoverflow.com/a/466242 static inline unsigned next_pow2(unsigned v) { --v; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; return ++v; } #define LAMBDA(_RESULT_TYPE_, _ARGS_, _BODY_) \ ({ \ _RESULT_TYPE_ _fn_ _ARGS_ \ { \ _BODY_; \ }; \ _fn_; \ }) #ifndef MIN #define MIN(a, b) ((a) < (b) ? (a) : (b)) #endif #ifndef MAX #define MAX(a, b) ((a) > (b) ? (a) : (b)) #endif #define FLOAT_AS_UINT32(_f) \ (((union { \ float f; \ uint32_t u; \ }){.f = (_f)}) \ .u) #define UINT32_AS_FLOAT(_u) \ (((union { \ float f; \ uint32_t u; \ }){.u = (_u)}) \ .f) #define STRINGIFY_(x) #x #define STRINGIFY(x) STRINGIFY_(x) bool startswith(const char* str, const char* prefix); bool startswithi(const char* str, const char* prefix); bool endswith(const char* str, const char* suffix); bool endswithi(const char* str, const char* suffix); void setCrankSoundsEnabled(bool enabled); // queue an error to show the user later void spoolError(const char* fmt, ...); size_t getSpooledErrors(void); const char* getSpooledErrorMessage(void); void freeSpool(void); // malloc and memset to zero void* mallocz(size_t size); #define allocz(Type) ((Type*)mallocz(sizeof(Type))) // malloc array and memset to zero #define allocza(Type, N) ((Type*)mallocz(sizeof(Type) * (N))); // non-negative floating-point modulo float nnfmodf(float a, float b); void memswap(void* a, void* b, size_t size); #endif /* utility_h */
412
0.860728
1
0.860728
game-dev
MEDIA
0.260299
game-dev
0.610271
1
0.610271
jetdog8808/Avatar-Armature-Collider
7,434
Editor/AvatarArmatureColliderManagerEditor.cs
using UnityEngine; using UnityEditor; using UdonSharpEditor; namespace JetDog.UserCollider { [CustomEditor(typeof(AvatarArmatureColliderManager))] public class AvatarArmatureColliderManagerEditor : Editor { #region Fields SerializedProperty prefabRefProperty; SerializedProperty remoteCollidersEnabledProperty, localCollidersEnabledProperty; SerializedProperty localCollisionTransferOwnershipProperty; SerializedProperty remoteIsTriggerProperty, localIstriggerProperty; SerializedProperty localLayerProperty, remoteLayerProperty; SerializedProperty remoteIncludeLayersProperty, localIncludeLayersProperty, remoteExcludeLayersProperty, localExcludeLayersProperty; SerializedProperty fingerCollisionProperty, handCollisionProperty, armCollisionProperty, legCollisionProperty, torsoCollisionProperty, headCollisionProperty; SerializedProperty distanceFactors, distanceUpdateRates; bool lodDropdown = false; bool remoteLayerOverrideDropdown = false, localLayerOverrideDropdown = false; bool enabledSectionsDropdown = false; #endregion Fields #region Methods private void OnEnable() { prefabRefProperty = serializedObject.FindProperty("prefabRef"); localCollisionTransferOwnershipProperty = serializedObject.FindProperty("localCollisionTransferOwnership"); remoteCollidersEnabledProperty = serializedObject.FindProperty("_remoteCollidersEnabled"); localCollidersEnabledProperty = serializedObject.FindProperty("_localCollidersEnabled"); remoteIsTriggerProperty = serializedObject.FindProperty("remoteIsTrigger"); localIstriggerProperty = serializedObject.FindProperty("localIsTrigger"); localLayerProperty = serializedObject.FindProperty("localLayer"); remoteLayerProperty = serializedObject.FindProperty("remoteLayer"); remoteIncludeLayersProperty = serializedObject.FindProperty("remoteIncludeLayers"); localIncludeLayersProperty = serializedObject.FindProperty("localIncludeLayers"); remoteExcludeLayersProperty = serializedObject.FindProperty("remoteExcludeLayers"); localExcludeLayersProperty = serializedObject.FindProperty("localExcludeLayers"); fingerCollisionProperty = serializedObject.FindProperty("fingerCollision"); handCollisionProperty = serializedObject.FindProperty("handCollision"); armCollisionProperty = serializedObject.FindProperty("armCollision"); legCollisionProperty = serializedObject.FindProperty("legCollision"); torsoCollisionProperty = serializedObject.FindProperty("torsoCollision"); headCollisionProperty = serializedObject.FindProperty("headCollision"); distanceFactors = serializedObject.FindProperty("distanceFactors"); distanceUpdateRates = serializedObject.FindProperty("distanceUpdateRates"); } public override void OnInspectorGUI() { if (UdonSharpGUI.DrawDefaultUdonSharpBehaviourHeader(target)) return; EditorGUILayout.PropertyField(prefabRefProperty); EditorGUILayout.Space(); EditorGUILayout.PropertyField(localCollidersEnabledProperty); EditorGUILayout.PropertyField(localCollisionTransferOwnershipProperty); EditorGUILayout.PropertyField(localIstriggerProperty); localLayerProperty.intValue = EditorGUILayout.LayerField("Local Collider Layer", localLayerProperty.intValue); localLayerOverrideDropdown = EditorGUILayout.BeginFoldoutHeaderGroup(localLayerOverrideDropdown, "Layer Overrides"); if (localLayerOverrideDropdown) { EditorGUILayout.PropertyField(localIncludeLayersProperty); EditorGUILayout.PropertyField(localExcludeLayersProperty); } EditorGUILayout.EndFoldoutHeaderGroup(); EditorGUILayout.Space(); EditorGUILayout.PropertyField(remoteCollidersEnabledProperty); EditorGUILayout.PropertyField(remoteIsTriggerProperty); remoteLayerProperty.intValue = EditorGUILayout.LayerField("Remote Collider Layer", remoteLayerProperty.intValue); remoteLayerOverrideDropdown = EditorGUILayout.BeginFoldoutHeaderGroup(remoteLayerOverrideDropdown, "Layer Overrides"); if (remoteLayerOverrideDropdown) { EditorGUILayout.PropertyField(remoteIncludeLayersProperty); EditorGUILayout.PropertyField(remoteExcludeLayersProperty); } EditorGUILayout.EndFoldoutHeaderGroup(); EditorGUILayout.Space(); enabledSectionsDropdown = EditorGUILayout.BeginFoldoutHeaderGroup(enabledSectionsDropdown, "Enabled collider sections"); if (enabledSectionsDropdown) { EditorGUILayout.PropertyField(fingerCollisionProperty); EditorGUILayout.PropertyField(handCollisionProperty); EditorGUILayout.PropertyField(armCollisionProperty); EditorGUILayout.PropertyField(legCollisionProperty); EditorGUILayout.PropertyField(torsoCollisionProperty); EditorGUILayout.PropertyField(headCollisionProperty); } EditorGUILayout.EndFoldoutHeaderGroup(); EditorGUILayout.Space(); lodDropdown = EditorGUILayout.BeginFoldoutHeaderGroup(lodDropdown, "LOD"); if (lodDropdown) { EditorGUI.BeginChangeCheck(); EditorGUILayout.LabelField("Lod 0", EditorStyles.boldLabel); float distance_x = EditorGUILayout.FloatField("Meters", distanceFactors.vector3Value.x); int rate_x = EditorGUILayout.IntSlider("Update frame", distanceUpdateRates.vector3IntValue.x, 1, 15); EditorGUILayout.Space(); EditorGUILayout.LabelField("Lod 1", EditorStyles.boldLabel); float distance_y = EditorGUILayout.FloatField("Meters", distanceFactors.vector3Value.y); int rate_y = EditorGUILayout.IntSlider("Update frame", distanceUpdateRates.vector3IntValue.y, 1, 15); EditorGUILayout.Space(); EditorGUILayout.LabelField("Lod 2", EditorStyles.boldLabel); float distance_z = EditorGUILayout.FloatField("Meters", distanceFactors.vector3Value.z); int rate_z = EditorGUILayout.IntSlider("Update frame", distanceUpdateRates.vector3IntValue.z, 1, 15); if (EditorGUI.EndChangeCheck()) { if ((distance_x + 1f) > distance_y) distance_y = distance_x + 1f; if ((distance_y + 1f) > distance_z) distance_z = distance_y + 1f; distanceFactors.vector3Value = new Vector3(distance_x, distance_y, distance_z); distanceUpdateRates.vector3IntValue = new Vector3Int(rate_x, rate_y, rate_z); } } EditorGUILayout.EndFoldoutHeaderGroup(); serializedObject.ApplyModifiedProperties(); } #endregion Methods } }
412
0.852913
1
0.852913
game-dev
MEDIA
0.909507
game-dev
0.774908
1
0.774908
erengy/taiga
7,077
src/v1/media/anime_filter.cpp
/** * Taiga * Copyright (C) 2010-2024, Eren Okka * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include <algorithm> #include <map> #include <regex> #include "media/anime_filter.h" #include "base/string.h" #include "media/anime_item.h" #include "media/anime_util.h" #include "ui/translate.h" namespace anime { enum class SearchField { None, Id, Episodes, Title, Genre, Producer, Tag, Note, Type, Season, Year, Rewatch, Duration, Score, Debug, }; enum class SearchOperator { EQ, GE, GT, LE, LT, }; struct SearchTerm { SearchField field = SearchField::None; SearchOperator op = SearchOperator::EQ; std::wstring value; }; SearchTerm GetSearchTerm(const std::wstring& str) { SearchTerm term; term.value = str; static const std::wregex pattern{LR"(([a-z]+):([!<=>]+)?(.+))"}; static const std::map<std::wstring, SearchField> prefixes{ {L"id", SearchField::Id}, {L"eps", SearchField::Episodes}, {L"title", SearchField::Title}, {L"genre", SearchField::Genre}, {L"producer", SearchField::Producer}, {L"tag", SearchField::Tag}, {L"note", SearchField::Note}, {L"type", SearchField::Type}, {L"season", SearchField::Season}, {L"year", SearchField::Year}, {L"rewatch", SearchField::Rewatch}, {L"duration", SearchField::Duration}, {L"score", SearchField::Score}, {L"debug", SearchField::Debug}, }; static const std::map<std::wstring, SearchOperator> operators{ {L"=", SearchOperator::EQ}, {L">=", SearchOperator::GE}, {L">", SearchOperator::GT}, {L"<=", SearchOperator::LE}, {L"<", SearchOperator::LT}, }; std::wsmatch matches; if (std::regex_match(str, matches, pattern)) { const auto it = prefixes.find(matches[1].str()); if (it != prefixes.end()) { term.field = it->second; term.value = matches[3].str(); if (matches[2].matched) { const auto it = operators.find(matches[2].str()); if (it != operators.end()) { term.op = it->second; } } } } return term; } bool CheckNumber(const SearchOperator op, const int a, const int b) { switch (op) { default: case SearchOperator::EQ: return a == b; case SearchOperator::GE: return a >= b; case SearchOperator::GT: return a > b; case SearchOperator::LE: return a <= b; case SearchOperator::LT: return a < b; } } bool CheckString(const std::wstring& a, const std::wstring& b) { return InStr(a, b, 0, true) > -1; } bool CheckStrings(const std::vector<std::wstring>& v, const std::wstring& w) { for (const auto& s : v) { if (InStr(s, w, 0, true) > -1) return true; } return false; }; //////////////////////////////////////////////////////////////////////////////// bool Filters::CheckItem(const Item& item, int text_index) const { const auto it = text.find(text_index); if (it == text.end() || it->second.empty()) return true; std::vector<std::wstring> words; Split(it->second, L" ", words); RemoveEmptyStrings(words); std::vector<std::wstring> titles; GetAllTitles(item.GetId(), titles); const auto& genres = item.GetGenres(); const auto& tags = item.GetTags(); const auto& producers = item.GetProducers(); const auto& studios = item.GetStudios(); const auto& notes = item.GetMyNotes(); std::vector<SearchTerm> search_terms; for (const auto& word : words) { search_terms.push_back(GetSearchTerm(word)); } for (const auto& term : search_terms) { switch (term.field) { case SearchField::None: if (!CheckStrings(titles, term.value) && !CheckStrings(genres, term.value) && !CheckStrings(tags, term.value) && !CheckString(notes, term.value)) { return false; } break; case SearchField::Id: if (!CheckNumber(term.op, item.GetId(), ToInt(term.value))) return false; break; case SearchField::Episodes: if (!CheckNumber(term.op, item.GetEpisodeCount(), ToInt(term.value))) return false; break; case SearchField::Title: if (!CheckStrings(titles, term.value)) return false; break; case SearchField::Genre: if (!CheckStrings(genres, term.value)) return false; break; case SearchField::Producer: if (!CheckStrings(producers, term.value) && !CheckStrings(studios, term.value)) { return false; } break; case SearchField::Tag: if (!CheckStrings(tags, term.value)) { return false; } break; case SearchField::Note: if (!CheckString(notes, term.value)) return false; break; case SearchField::Type: if (item.GetType() != ui::TranslateType(term.value)) return false; break; case SearchField::Season: { const auto season = ui::TranslateDateToSeasonString(item.GetDateStart()); if (!CheckString(season, term.value)) return false; break; } case SearchField::Year: { const auto year = item.GetDateStart().year(); if (!CheckNumber(term.op, year, ToInt(term.value))) return false; break; } case SearchField::Rewatch: { const auto rewatches = item.GetMyRewatchedTimes(); if (!CheckNumber(term.op, rewatches, ToInt(term.value))) return false; break; } case SearchField::Duration: { const auto duration = item.GetEpisodeLength(); if (!CheckNumber(term.op, duration, ToInt(term.value))) return false; break; } case SearchField::Score: { const auto score = item.GetMyScore(); if (!CheckNumber(term.op, score, ToInt(term.value))) return false; break; } case SearchField::Debug: { if (term.value == L"watched") { const int eps_watched = item.GetMyLastWatchedEpisode(); const int eps_total = item.GetEpisodeCount(); if (!anime::IsValidEpisodeNumber(eps_watched, eps_total) || (eps_watched < eps_total && item.GetMyStatus() == anime::MyStatus::Completed)) { continue; } else { return false; } } else { return false; } break; } } } return true; } } // namespace anime
412
0.885451
1
0.885451
game-dev
MEDIA
0.243822
game-dev
0.987069
1
0.987069
taherfattahi/turtlesim-astar-nvidia-llm
7,438
scripts/astar_algorithm.py
#!/usr/bin/env python import sys import rospy import math import random import heapq from turtlesim.msg import Pose from geometry_msgs.msg import Twist from std_srvs.srv import Empty from turtlesim.srv import Kill, Spawn, TeleportAbsolute, SetPen # Grid dimensions (turtlesim default is 11x11 units) GRID_WIDTH = 11 GRID_HEIGHT = 11 GRID_RESOLUTION = 1 # 1 unit per grid cell num_obstacles = 4 # Choose how many obstacles you want # Obstacles (list of (x, y) tuples) OBSTACLES = [] while len(OBSTACLES) < num_obstacles: x = random.randint(0, GRID_WIDTH - 1) y = random.randint(0, GRID_WIDTH - 1) if (x, y) not in OBSTACLES: OBSTACLES.append((x, y)) print("OBSTACLES =", OBSTACLES) class AStarPlanner: def __init__(self, start, goal, obstacles): self.start = self.grid_coord(start) self.goal = self.grid_coord(goal) self.obstacles = set(obstacles) self.open_set = [] heapq.heappush(self.open_set, (0, self.start)) self.came_from = {} self.g_score = {self.start: 0} self.f_score = {self.start: self.heuristic(self.start, self.goal)} def grid_coord(self, pos): x, y = pos return (int(x), int(y)) def heuristic(self, a, b): # Euclidean distance return math.hypot(b[0] - a[0], b[1] - a[1]) def neighbors(self, node): neighbors = [] for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]: x2, y2 = node[0] + dx, node[1] + dy if 0 <= x2 < GRID_WIDTH and 0 <= y2 < GRID_HEIGHT: if (x2, y2) not in self.obstacles: neighbors.append((x2, y2)) return neighbors def reconstruct_path(self): node = self.goal path = [node] while node in self.came_from: node = self.came_from[node] path.append(node) path.reverse() return path def search(self): while self.open_set: _, current = heapq.heappop(self.open_set) if current == self.goal: return self.reconstruct_path() for neighbor in self.neighbors(current): tentative_g_score = self.g_score[current] + 1 if neighbor not in self.g_score or tentative_g_score < self.g_score[neighbor]: self.came_from[neighbor] = current self.g_score[neighbor] = tentative_g_score f_score = tentative_g_score + self.heuristic(neighbor, self.goal) self.f_score[neighbor] = f_score heapq.heappush(self.open_set, (f_score, neighbor)) return None class TurtleController: def __init__(self): rospy.init_node('turtle_astar_controller', anonymous=True) self.pose_subscriber = rospy.Subscriber('/turtle1/pose', Pose, self.update_pose) self.velocity_publisher = rospy.Publisher('/turtle1/cmd_vel', Twist, queue_size=10) self.spawn_service = rospy.ServiceProxy('/spawn', Spawn) self.kill_service = rospy.ServiceProxy('/kill', Kill) self.clear_service = rospy.ServiceProxy('/clear', Empty) self.pose = Pose() self.rate = rospy.Rate(10) # self.goal = (8.0, 8.0) # Goal position self.obstacles = OBSTACLES self.path = [] self.path_index = 0 # Proportional control gains self.K_linear = 1.5 self.K_angular = 4.0 # Parse command-line arguments for goal position if len(sys.argv) >= 3: try: self.goal = (float(sys.argv[1]), float(sys.argv[2])) except ValueError: rospy.logerr("Invalid goal coordinates. Using default goal (8.0, 8.0).") self.goal = (8.0, 8.0) else: self.goal = (8.0, 8.0) # Default goal position def update_pose(self, data): self.pose = data def move_to_goal(self): # Wait until the pose is received rospy.wait_for_message('/turtle1/pose', Pose) # Clear existing obstacle turtles self.clear_obstacle_turtles() # Spawn obstacle turtles on the screen self.spawn_obstacle_turtles() # Plan the path start = (self.pose.x, self.pose.y) planner = AStarPlanner(start, self.goal, self.obstacles) path = planner.search() if path is None: rospy.loginfo("No path found!") return else: rospy.loginfo("Path found: {}".format(path)) self.path = path self.follow_path() def follow_path(self): twist = Twist() for node in self.path[1:]: target_x = node[0] + 0.5 # Move to the center of the grid cell target_y = node[1] + 0.5 while not rospy.is_shutdown(): distance = math.hypot(target_x - self.pose.x, target_y - self.pose.y) angle_to_goal = math.atan2(target_y - self.pose.y, target_x - self.pose.x) angle_diff = self.normalize_angle(angle_to_goal - self.pose.theta) # Proportional Controller linear_speed = self.K_linear * distance angular_speed = self.K_angular * angle_diff twist.linear.x = linear_speed twist.angular.z = angular_speed self.velocity_publisher.publish(twist) if distance < 0.1: break self.rate.sleep() # Stop the turtle after reaching the goal twist.linear.x = 0 twist.angular.z = 0 self.velocity_publisher.publish(twist) rospy.loginfo("Goal reached!") def normalize_angle(self, angle): if abs(angle) > math.pi: angle = angle - (2 * math.pi * angle) / abs(angle) return angle def spawn_obstacle_turtles(self): rospy.wait_for_service('/spawn') rospy.wait_for_service('/clear') # Clear the screen self.clear_service() # Spawn turtles at obstacle positions for idx, obstacle in enumerate(self.obstacles): x = obstacle[0] + 0.5 # Center of the grid cell y = obstacle[1] + 0.5 name = 'obstacle{}'.format(idx) try: self.spawn_service(x, y, 0, name) rospy.loginfo("Spawned obstacle turtle '{}' at ({}, {})".format(name, x, y)) except rospy.ServiceException as e: rospy.logerr("Service call failed: {}".format(e)) def clear_obstacle_turtles(self): rospy.wait_for_service('/kill') try: # Get the list of all turtles turtles = rospy.get_param('/turtlesim_node/turtles', []) for idx, obstacle in enumerate(self.obstacles): turtle_name = 'obstacle{}'.format(idx) if turtle_name.startswith('obstacle'): self.kill_service(turtle_name) rospy.loginfo("Killed obstacle turtle '{}'".format(turtle_name)) except rospy.ServiceException as e: rospy.logerr("Service call failed: {}".format(e)) except KeyError: rospy.logwarn("No turtles found to kill.") if __name__ == '__main__': try: controller = TurtleController() controller.move_to_goal() except rospy.ROSInterruptException: pass
412
0.901308
1
0.901308
game-dev
MEDIA
0.441689
game-dev,ml-ai
0.963105
1
0.963105
chaitu-ycr/py_canoe
3,352
src/py_canoe/core/child_elements/nodes.py
import win32com.client from py_canoe.core.child_elements.modules import Modules from py_canoe.core.child_elements.signals import Signals class Nodes: """The Nodes object represents all nodes of the Simulation Setup / System and Communication Setup of the CANoe application.""" def __init__(self, nodes_com_obj): self.com_object = nodes_com_obj @property def count(self) -> int: return self.com_object.Count def item(self, index: int) -> 'Node': return Node(self.com_object.Item(index)) def add(self, name: str) -> 'Node': return Node(self.com_object.Add(name)) def add_test_module_ex(self, name:str, type: int) -> 'Node': return Node(self.com_object.AddTestModuleEx(name, type)) def add_with_title(self, name: str) -> 'Node': return Node(self.com_object.AddWithTitle(name)) def add_test_module(self, name: str) -> 'Node': return Node(self.com_object.AddTestModule(name)) def remove(self, index: int): self.com_object.Remove(index) class Node: """The Node object represents a node of the Simulation Setup / System and Communication Setup of the CANoe application.""" def __init__(self, node_com_obj): self.com_object = win32com.client.Dispatch(node_com_obj) @property def active(self) -> bool: return self.com_object.Active @property def full_name(self) -> str: return self.com_object.FullName @property def inputs(self) -> 'Signals': return Signals(self.com_object.Inputs) @property def is_gateway(self) -> bool: return self.com_object.IsGateway @property def modules(self) -> 'Modules': return Modules(self.com_object.Modules) @property def name(self) -> str: return self.com_object.Name @property def outputs(self) -> 'Signals': return Signals(self.com_object.Outputs) @property def path(self) -> str: return self.com_object.Path @property def port_creation(self) -> int: return self.com_object.PortCreation @port_creation.setter def port_creation(self, value: int): self.com_object.PortCreation = value @property def start_delay(self) -> int: return self.com_object.StartDelay @start_delay.setter def start_delay(self, value: int): self.com_object.StartDelay = value @property def start_delay_active(self) -> bool: return self.com_object.StartDelayActive @start_delay_active.setter def start_delay_active(self, value: bool): self.com_object.StartDelayActive = value @property def start_delay_from_db(self) -> bool: return self.com_object.StartDelayFromDb @start_delay_from_db.setter def start_delay_from_db(self, value: bool): self.com_object.StartDelayFromDb = value @property def tcp_ip_stack_setting(self): return self.com_object.TcpIpStackSetting @property def test_module(self) -> bool: return self.com_object.TestModule def attach_bus(self, bus_com_obj): self.com_object.AttachBus(bus_com_obj) def detach_bus(self, bus_com_obj): self.com_object.DetachBus(bus_com_obj) def is_bus_attached(self, bus_com_obj) -> bool: return self.com_object.IsBusAttached(bus_com_obj)
412
0.838352
1
0.838352
game-dev
MEDIA
0.419068
game-dev
0.738563
1
0.738563
ParchmentMC/Parchment
2,585
data/net/minecraft/world/SimpleContainer.mapping
CLASS net/minecraft/world/SimpleContainer METHOD <init> (I)V ARG 1 size METHOD <init> ([Lnet/minecraft/world/item/ItemStack;)V ARG 1 items METHOD addItem (Lnet/minecraft/world/item/ItemStack;)Lnet/minecraft/world/item/ItemStack; ARG 1 stack METHOD addListener (Lnet/minecraft/world/ContainerListener;)V COMMENT Add a listener that will be notified when any item in this inventory is modified. ARG 1 listener METHOD canAddItem (Lnet/minecraft/world/item/ItemStack;)Z ARG 1 stack METHOD fromItemList (Lnet/minecraft/world/level/storage/ValueInput$TypedInputList;)V ARG 1 input METHOD getContainerSize ()I COMMENT Returns the number of slots in the inventory. METHOD getItem (I)Lnet/minecraft/world/item/ItemStack; COMMENT Returns the stack in the given slot. ARG 1 index METHOD lambda$removeAllItems$0 (Lnet/minecraft/world/item/ItemStack;)Z ARG 0 stack METHOD lambda$toString$1 (Lnet/minecraft/world/item/ItemStack;)Z ARG 0 stack METHOD moveItemToEmptySlots (Lnet/minecraft/world/item/ItemStack;)V ARG 1 stack METHOD moveItemToOccupiedSlotsWithSameType (Lnet/minecraft/world/item/ItemStack;)V ARG 1 stack METHOD moveItemsBetweenStacks (Lnet/minecraft/world/item/ItemStack;Lnet/minecraft/world/item/ItemStack;)V ARG 1 stack ARG 2 other METHOD removeItem (II)Lnet/minecraft/world/item/ItemStack; COMMENT Removes up to a specified number of items from an inventory slot and returns them in a new stack. ARG 1 index ARG 2 count METHOD removeItemNoUpdate (I)Lnet/minecraft/world/item/ItemStack; COMMENT Removes a stack from the given slot and returns it. ARG 1 index METHOD removeItemType (Lnet/minecraft/world/item/Item;I)Lnet/minecraft/world/item/ItemStack; ARG 1 item ARG 2 amount METHOD removeListener (Lnet/minecraft/world/ContainerListener;)V COMMENT Removes the specified {@link net.minecraft.world.ContainerListener} from receiving further change notices. ARG 1 listener METHOD setChanged ()V COMMENT For block entities, ensures the chunk containing the block entity is saved to disk later - the game won't think it hasn't changed and skip it. METHOD setItem (ILnet/minecraft/world/item/ItemStack;)V COMMENT Sets the given item stack to the specified slot in the inventory (can be crafting or armor sections). ARG 1 index ARG 2 stack METHOD stillValid (Lnet/minecraft/world/entity/player/Player;)Z COMMENT Don't rename this method to canInteractWith due to conflicts with Container ARG 1 player METHOD storeAsItemList (Lnet/minecraft/world/level/storage/ValueOutput$TypedOutputList;)V ARG 1 output
412
0.689536
1
0.689536
game-dev
MEDIA
0.998692
game-dev
0.557141
1
0.557141
iPortalTeam/ImmersivePortalsMod
8,296
src/main/java/qouteall/imm_ptl/core/chunk_loading/ChunkVisibility.java
package qouteall.imm_ptl.core.chunk_loading; import net.minecraft.core.BlockPos; import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.level.ChunkPos; import net.minecraft.world.level.Level; import net.minecraft.world.phys.Vec3; import qouteall.imm_ptl.core.IPGlobal; import qouteall.imm_ptl.core.McHelper; import qouteall.imm_ptl.core.portal.Portal; import qouteall.imm_ptl.core.portal.global_portals.GlobalPortalStorage; import qouteall.q_misc_util.my_util.LimitedLogger; import java.util.Comparator; import java.util.List; import java.util.Optional; import java.util.function.Consumer; import java.util.function.Predicate; public class ChunkVisibility { private static final LimitedLogger limitedLogger = new LimitedLogger(10); private static final int portalLoadingRange = 48; public static final int secondaryPortalLoadingRange = 16; public static ChunkLoader playerDirectLoader(ServerPlayer player) { return new ChunkLoader( new DimensionalChunkPos( player.level().dimension(), player.chunkPosition() ), McHelper.getPlayerLoadDistance(player) ); } private static int getDirectLoadingDistance(int renderDistance, double distanceToPortal) { if (distanceToPortal < 5) { return renderDistance; } if (distanceToPortal < 15) { return (renderDistance * 2) / 3; } return renderDistance / 3; } private static int getCappedLoadingDistance( Portal portal, ServerPlayer player, int targetLoadingDistance ) { PerformanceLevel performanceLevel = ImmPtlChunkTracking.getPlayerInfo(player).performanceLevel; int cap1 = PerformanceLevel.getIndirectLoadingRadiusCap(performanceLevel); int cap2 = IPGlobal.indirectLoadingRadiusCap; int cap3 = PerformanceLevel.getIndirectLoadingRadiusCap(ServerPerformanceMonitor.getLevel()); int cap = Math.min(cap1, cap2); // load more for scaling portal if (portal.getScale() > 2) { cap *= 2; } int cappedLoadingDistance = Math.min(targetLoadingDistance, cap); return cappedLoadingDistance; } public static List<Portal> getNearbyPortals( ServerLevel world, Vec3 pos, Predicate<Portal> predicate, int radiusChunks, int radiusChunksForGlobalPortals ) { List<Portal> result = McHelper.findEntitiesRough( Portal.class, world, pos, radiusChunks, predicate ); for (Portal globalPortal : GlobalPortalStorage.getGlobalPortals(world)) { double distance = globalPortal.getDistanceToNearestPointInPortal(pos); if (distance < radiusChunksForGlobalPortals * 16) { result.add(globalPortal); } } if (result.size() > 100) { limitedLogger.err("too many portal nearby " + world + pos); Optional<Portal> nearest = result.stream().min(Comparator.comparingDouble(p -> p.getDistanceToNearestPointInPortal(pos))); return List.of(nearest.get()); } return result; } private static ChunkLoader getGeneralDirectPortalLoader( ServerPlayer player, Portal portal ) { if (portal.getIsGlobal()) { int renderDistance = Math.min( IPGlobal.indirectLoadingRadiusCap * 2, //load a little more to make dimension stack more complete Math.max( 2, McHelper.getPlayerLoadDistance(player) - Math.floorDiv((int) portal.getDistanceToNearestPointInPortal(player.position()), 16) ) ); return new ChunkLoader( new DimensionalChunkPos( portal.getDestDim(), new ChunkPos(BlockPos.containing( portal.transformPoint(player.position()) )) ), renderDistance ); } else { int loadDistance = McHelper.getPlayerLoadDistance(player); double distance = portal.getDistanceToNearestPointInPortal(player.position()); // load more for up scaling portal if (portal.getScaling() > 2 && distance < 5) { loadDistance = (int) ((portal.getDestAreaRadiusEstimation() * 1.4) / 16); } return new ChunkLoader( new DimensionalChunkPos( portal.getDestDim(), new ChunkPos(BlockPos.containing(portal.getDestPos())) ), getCappedLoadingDistance( portal, player, getDirectLoadingDistance(loadDistance, distance) ) ); } } private static ChunkLoader getGeneralPortalIndirectLoader( ServerPlayer player, Vec3 transformedPos, Portal portal ) { int loadDistance = McHelper.getPlayerLoadDistance(player); if (portal.getIsGlobal()) { int renderDistance = Math.min( IPGlobal.indirectLoadingRadiusCap, loadDistance / 3 ); return new ChunkLoader( new DimensionalChunkPos( portal.getDestDim(), new ChunkPos(BlockPos.containing(transformedPos)) ), renderDistance ); } else { return new ChunkLoader( new DimensionalChunkPos( portal.getDestDim(), new ChunkPos(BlockPos.containing(portal.getDestPos())) ), getCappedLoadingDistance( portal, player, loadDistance / 4 ) ); } } //includes: //1.player direct loader //2.loaders from the portals that are directly visible //3.loaders from the portals that are indirectly visible through portals public static void foreachBaseChunkLoaders( ServerPlayer player, Consumer<ChunkLoader> func ) { PerformanceLevel perfLevel = ImmPtlChunkTracking.getPlayerInfo(player).performanceLevel; int visiblePortalRangeChunks = PerformanceLevel.getVisiblePortalRangeChunks(perfLevel); int indirectVisiblePortalRangeChunks = PerformanceLevel.getIndirectVisiblePortalRangeChunks(perfLevel); ChunkLoader playerDirectLoader = playerDirectLoader(player); func.accept(playerDirectLoader); List<Portal> nearbyPortals = getNearbyPortals( ((ServerLevel) player.level()), player.position(), portal -> portal.broadcastToPlayer(player), visiblePortalRangeChunks, 256 ); for (Portal portal : nearbyPortals) { Level destinationWorld = portal.getDestinationWorld(); if (destinationWorld == null) { continue; } Vec3 transformedPlayerPos = portal.transformPoint(player.position()); func.accept(getGeneralDirectPortalLoader(player, portal)); if (!isShrinkLoading()) { List<Portal> indirectNearbyPortals = getNearbyPortals( ((ServerLevel) destinationWorld), transformedPlayerPos, p -> p.broadcastToPlayer(player), indirectVisiblePortalRangeChunks, 32 ); for (Portal innerPortal : indirectNearbyPortals) { func.accept(getGeneralPortalIndirectLoader( player, transformedPlayerPos, innerPortal )); } } } } public static boolean isShrinkLoading() { return ServerPerformanceMonitor.getLevel() != PerformanceLevel.good; } }
412
0.852131
1
0.852131
game-dev
MEDIA
0.798998
game-dev
0.88812
1
0.88812
Razzmatazzz/RemnantSaveGuardian
8,032
RemnantSaveGuardian/RemnantCharacter.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.IO; namespace RemnantSaveGuardian { public class RemnantCharacter { public List<string> Archetypes { get; set; } public string SecondArchetype { get; set; } public List<string> Inventory { get; set; } public List<RemnantWorldEvent> CampaignEvents { get; } public List<RemnantWorldEvent> AdventureEvents { get; } public RemnantSave Save { get; } public int WorldIndex { get; } = -1; public int Progression { get { return this.Inventory.Count; } } private List<RemnantItem> missingItems; public enum ProcessMode { Campaign, Adventure }; public override string ToString() { return string.Join(", ", Archetypes.Select(arch => Loc.GameT(arch))) + " (" + this.Progression + ")"; } public string ToFullString() { string str = "CharacterData{ Archetypes: [" + string.Join(", ", Archetypes.Select(arch => Loc.T(arch))) + "], Inventory: [" + string.Join(", ", this.Inventory) + "], CampaignEvents: [" + string.Join(", ", this.CampaignEvents) + "], AdventureEvents: [" + string.Join(", ", this.AdventureEvents) + "] }"; return str; } public RemnantCharacter(RemnantSave remnantSave, int index) { this.Archetypes = new List<string>(); this.Inventory = new List<string>(); this.CampaignEvents = new List<RemnantWorldEvent>(); this.AdventureEvents = new List<RemnantWorldEvent>(); this.missingItems = new List<RemnantItem>(); this.Save = remnantSave; this.WorldIndex = index; } public enum CharacterProcessingMode { All, NoEvents }; public static List<RemnantCharacter> GetCharactersFromSave(RemnantSave remnantSave) { return GetCharactersFromSave(remnantSave, CharacterProcessingMode.All); } public static List<RemnantCharacter> GetCharactersFromSave(RemnantSave remnantSave, CharacterProcessingMode mode) { List<RemnantCharacter> charData = new List<RemnantCharacter>(); try { string profileData = remnantSave.GetProfileData(); #if DEBUG File.WriteAllText(remnantSave.SaveProfilePath.Replace(".sav", ".txt"), profileData); #endif var archetypes = Regex.Matches(profileData, @"/Game/World_(Base|DLC\d+)/Items/Archetypes/(?<archetype>\w+)/Archetype_\w+_UI\.Archetype_\w+_UI_C"); var inventoryStarts = Regex.Matches(profileData, "/Game/Characters/Player/Base/Character_Master_Player.Character_Master_Player_C"); var inventoryEnds = Regex.Matches(profileData, "[^.]Character_Master_Player_C"); for (var i = 0; i < inventoryStarts.Count; i++) { //Debug.WriteLine($"character {i}"); Match invMatch = inventoryStarts[i]; Match invEndMatch = inventoryEnds.First(m => m.Index > invMatch.Index); var inventory = profileData.Substring(invMatch.Index, invEndMatch.Index - invMatch.Index); RemnantCharacter cd = new RemnantCharacter(remnantSave, i); for (var m = 0; m < archetypes.Count; m++) { Match archMatch = archetypes[m]; int prevCharEnd = 0; if (i > 0) { Match prevInvStart = inventoryStarts[i - 1]; prevCharEnd = inventoryEnds.First(m => m.Index > prevInvStart.Index).Index; } if (archMatch.Index > prevCharEnd && archMatch.Index < invMatch.Index) { cd.Archetypes.Add(archMatch.Groups["archetype"].Value); } } if (cd.Archetypes.Count == 0) { cd.Archetypes.Add("Unknown"); } foreach (string pattern in RemnantItem.ItemKeyPatterns) { var itemMatches = new Regex(pattern).Matches(inventory); foreach (Match itemMatch in itemMatches) { cd.Inventory.Add(itemMatch.Value.Replace(".", "").ToLower()); } } /*rx = new Regex(@"/Items/QuestItems(/[a-zA-Z0-9_]+)+/[a-zA-Z0-9_]+"); matches = rx.Matches(inventory); foreach (Match match in matches) { saveItems.Add(match.Value); } rx = new Regex(@"/Quests/[a-zA-Z0-9_]+/[a-zA-Z0-9_]+"); matches = rx.Matches(inventory); foreach (Match match in matches) { saveItems.Add(match.Value); } rx = new Regex(@"/Player/Emotes/Emote_[a-zA-Z0-9]+"); matches = rx.Matches(inventory); foreach (Match match in matches) { saveItems.Add(match.Value); }*/ if (mode == CharacterProcessingMode.All) { cd.LoadWorldData(); } charData.Add(cd); } } catch (IOException ex) { if (ex.Message.Contains("being used by another process")) { if (Views.Pages.BackupsPage.isDataLoaded == true) { Logger.Warn(Loc.T("Save file in use; waiting 0.5 seconds and retrying.")); } System.Threading.Thread.Sleep(500); charData = GetCharactersFromSave(remnantSave, mode); } } return charData; } public void LoadWorldData() { if (this.Save == null) { return; } /*if (this.CampaignEvents.Count != 0) { return; }*/ if (this.WorldIndex >= Save.WorldSaves.Length) { return; } try { RemnantWorldEvent.ProcessEvents(this); missingItems.Clear(); foreach (List <RemnantItem> eventItems in GameInfo.EventItem.Values) { foreach (RemnantItem item in eventItems) { if (!this.Inventory.Contains(item.Key.ToLower())) { if (!missingItems.Contains(item)) { missingItems.Add(item); } } } } missingItems.Sort(); } catch (IOException ex) { if (ex.Message.Contains("being used by another process")) { Logger.Warn(Loc.T("Save file in use; waiting 0.5 seconds and retrying.")); System.Threading.Thread.Sleep(500); LoadWorldData(); } } catch (Exception ex) { Logger.Error($"Error loading world Data in CharacterData.LoadWorldData: {ex.Message} {ex.StackTrace}"); } } public List<RemnantItem> GetMissingItems() { return missingItems; } } }
412
0.951426
1
0.951426
game-dev
MEDIA
0.898803
game-dev
0.983702
1
0.983702
DynamoDS/Dynamo
2,022
src/Engine/ProtoCore/Parser/AST.cs
namespace ProtoCore.AST { using System.Collections.Generic; public abstract class Node { private static int sID; public int line { get; set; } public int col { get; set; } public int endLine { get; set; } public int endCol { get; set; } public int charPos { get; set; } public int endCharPos { get; set; } public string Name { get; set; } public int ID { get; private set; } public bool skipMe { get; set; } internal static readonly string BuiltinGetValueAtIndexTypeName = typeof(DesignScript.Builtin.Get).FullName; internal static readonly string BuiltinValueAtIndexMethodName = nameof(DesignScript.Builtin.Get.ValueAtIndex); internal static readonly string BuiltinValueAtIndexInForLoopMethodName = nameof(DesignScript.Builtin.Get.ValueAtIndexInForLoop); public Node() { ID = ++sID; line = ProtoCore.DSASM.Constants.kInvalidIndex; col = ProtoCore.DSASM.Constants.kInvalidIndex; endLine = ProtoCore.DSASM.Constants.kInvalidIndex; endCol = ProtoCore.DSASM.Constants.kInvalidIndex; charPos = ProtoCore.DSASM.Constants.kInvalidIndex; endCharPos = ProtoCore.DSASM.Constants.kInvalidIndex; skipMe = false; Name = string.Empty; } public Node(Node rhs) { ID = rhs.ID; line = rhs.line; col = rhs.col; endLine = rhs.endLine; endCol = rhs.endCol; charPos = rhs.charPos; endCharPos = rhs.charPos; Name = rhs.Name; skipMe = rhs.skipMe; } /// <summary> /// An explicit mechanism to manually set the ID of an AST node /// </summary> /// <param name="id"></param> public void InheritID(int id) { ID = id; } public abstract IEnumerable<Node> Children(); } }
412
0.852064
1
0.852064
game-dev
MEDIA
0.317496
game-dev
0.669427
1
0.669427
ice1000/jimgui
3,308
buildSrc/src/GenFontAtlasTask.kt
@file:Suppress("unused") package org.ice1000.gradle import org.intellij.lang.annotations.Language /** * @author ice1000 */ open class GenFontAtlasTask : GenTask("JImGuiFontAtlasGen", "imgui_font_atlas") { init { description = "Generate binding for ImGui::GetFont()->ContainerAtlas" } @Language("JAVA", prefix = "class A{", suffix = "}") override val userCode = """protected long nativeObjectPtr; /** package-private by design */ $className(long nativeObjectPtr) { this.nativeObjectPtr = nativeObjectPtr; } """ override fun java(javaCode: StringBuilder) { imVec2Members.forEach { genJavaObjectiveXYAccessor(javaCode, it, "float") } primitiveMembers.forEach { (type, name, annotation) -> genSimpleJavaObjectivePrimitiveMembers(javaCode, name, type, annotation) } functions.forEach { genJavaFun(javaCode, it) } } override fun `c++`(cppCode: StringBuilder) { imVec2Members.joinLinesTo(cppCode) { `c++XYAccessor`(it, "float", "jlong nativeObjectPtr") } primitiveMembers.joinLinesTo(cppCode) { (type, name) -> `c++PrimitiveAccessor`(type, name, "jlong nativeObjectPtr") } functions.forEach { (name, type, params) -> `genC++Fun`(params.dropLast(1), name, type, cppCode, "jlong nativeObjectPtr") } } override val `c++Expr` = "PTR_J2C(ImFontAtlas, nativeObjectPtr)->" private val imVec2Members = listOf("TexUvScale", "TexUvWhitePixel") private val functions = listOf( Fun.protected("addFont", "long", configPtr("fontConfig"), nativeObjectPtr), Fun.protected("addFontDefault", "long", configPtr("fontConfig", nullable = true), nativeObjectPtr), Fun.protected("addFontFromMemoryCompressedBase85TTF", "long", string("compressedFontDataBase85"), float("sizePixels"), nativeObjectPtr), Fun.private("build", "boolean", nativeObjectPtr), Fun.private("isBuilt", "boolean", nativeObjectPtr), Fun.private("clearInputData", nativeObjectPtr), Fun.private("clearTexData", nativeObjectPtr), Fun.private("clearFonts", nativeObjectPtr), Fun.private("clear", nativeObjectPtr), Fun.private("setTexID", texture("id"), nativeObjectPtr), Fun.protected("getGlyphRangesDefault", "long", nativeObjectPtr), Fun.protected("getGlyphRangesKorean", "long", nativeObjectPtr), Fun.protected("getGlyphRangesJapanese", "long", nativeObjectPtr), Fun.protected("getGlyphRangesChineseFull", "long", nativeObjectPtr), Fun.protected("getGlyphRangesChineseSimplifiedCommon", "long", nativeObjectPtr), Fun.protected("getGlyphRangesCyrillic", "long", nativeObjectPtr), Fun.protected("getGlyphRangesVietnamese", "long", nativeObjectPtr), Fun.protected("getGlyphRangesThai", "long", nativeObjectPtr), Fun.private("addCustomRectRegular", int("width"), int("height"), nativeObjectPtr), Fun.protected("addCustomRectFontGlyph", font(), p("id", "short"), int("width"), int("height"), float("advanceX"), pos("offset", default = "0,0"), nativeObjectPtr)) private val primitiveMembers = listOf( PPT("int", "Flags", annotation = "@MagicConstant(flagsFromClass = JImFontAtlasFlags.class)"), PPT("int", "TexWidth"), PPT("int", "TexHeight"), PPT("int", "TexDesiredWidth"), PPT("int", "TexGlyphPadding") ) }
412
0.523249
1
0.523249
game-dev
MEDIA
0.773062
game-dev
0.698139
1
0.698139
hojat72elect/libgdx_games
2,733
2D_Adventure/core/src/main/kotlin/com/github/quillraven/quillysadventure/ecs/system/TutorialSystem.kt
package com.github.quillraven.quillysadventure.ecs.system import com.badlogic.ashley.core.Engine import com.badlogic.ashley.core.Entity import com.badlogic.ashley.systems.IteratingSystem import com.github.quillraven.quillysadventure.ecs.component.PlayerComponent import com.github.quillraven.quillysadventure.ecs.component.RemoveComponent import com.github.quillraven.quillysadventure.ecs.component.playerCmp import com.github.quillraven.quillysadventure.event.GameEventListener import com.github.quillraven.quillysadventure.event.GameEventManager import ktx.ashley.allOf import ktx.ashley.exclude import ktx.ashley.get private const val WELCOME_TUTORIAL_DELAY = 2.0f enum class TutorialType { None, Welcome, Attack, Damaged, LevelUp, NewSkill, Checkpoint } class TutorialSystem(private val gameEventManager: GameEventManager) : IteratingSystem(allOf(PlayerComponent::class).exclude(RemoveComponent::class).get()), GameEventListener { private var welcomeDelay = WELCOME_TUTORIAL_DELAY private var showTutorialType = TutorialType.None override fun addedToEngine(engine: Engine?) { super.addedToEngine(engine) gameEventManager.addGameEventListener(this) } override fun removedFromEngine(engine: Engine?) { super.removedFromEngine(engine) gameEventManager.removeGameEventListener(this) } override fun processEntity(entity: Entity, deltaTime: Float) { if (welcomeDelay > 0f) { welcomeDelay -= deltaTime if (welcomeDelay <= 0f) { showTutorialType = TutorialType.Welcome } } if (showTutorialType != TutorialType.None && entity.playerCmp.tutorials.add(showTutorialType)) { // tutorial hint not yet shown -> show it gameEventManager.dispatchShowDialogEvent("tutorial.$showTutorialType") showTutorialType = TutorialType.None } } override fun characterAttack(character: Entity) { if (character[PlayerComponent.mapper] != null) { showTutorialType = TutorialType.Attack } } override fun characterDamaged(character: Entity, damage: Float, life: Float, maxLife: Float) { if (character[PlayerComponent.mapper] != null) { showTutorialType = TutorialType.Damaged } } override fun characterLevelUp(character: Entity, level: Int, xp: Int, xpNeeded: Int) { showTutorialType = when (level) { 2 -> TutorialType.LevelUp 3 -> TutorialType.NewSkill else -> TutorialType.None } } override fun activateSavepoint(savepoint: Entity) { showTutorialType = TutorialType.Checkpoint } }
412
0.793479
1
0.793479
game-dev
MEDIA
0.983621
game-dev
0.964969
1
0.964969
The-Evil-Pickle/Replay-the-Spire
5,849
src/main/java/com/megacrit/cardcrawl/mod/replay/relics/HoneyJar.java
package com.megacrit.cardcrawl.mod.replay.relics; import com.megacrit.cardcrawl.dungeons.*; import com.megacrit.cardcrawl.actions.common.ApplyPowerAction; import com.megacrit.cardcrawl.actions.common.RelicAboveCreatureAction; import com.megacrit.cardcrawl.characters.*; import basemod.BaseMod; import replayTheSpire.ReplayAbstractRelic; import replayTheSpire.ReplayTheSpireMod; import replayTheSpire.panelUI.ReplayBooleanSetting; import replayTheSpire.panelUI.ReplayIntSliderSetting; import replayTheSpire.panelUI.ReplayRelicSetting; import com.megacrit.cardcrawl.core.*; import com.megacrit.cardcrawl.potions.PotionSlot; import com.megacrit.cardcrawl.powers.RetainCardPower; import com.megacrit.cardcrawl.relics.*; import com.megacrit.cardcrawl.rooms.AbstractRoom; import com.megacrit.cardcrawl.rooms.MonsterRoomBoss; import com.megacrit.cardcrawl.rooms.TreasureRoomBoss; import java.util.*; public class HoneyJar extends ReplayAbstractRelic { public static final String ID = "Honey Jar"; public static final ReplayIntSliderSetting SETTING_DRAW = new ReplayIntSliderSetting("Honeyjar_Draw", "Cards Drawn", 1, 3); public static final ReplayIntSliderSetting SETTING_RETAIN = new ReplayIntSliderSetting("Honeyjar_Retain", "Cards Retained", 1, 3); public static final ReplayBooleanSetting SETTING_CHOICE = new ReplayBooleanSetting("Honeyjar_Choice", "Extra Card Reward Choice", true); public static final ReplayIntSliderSetting SETTING_POTION = new ReplayIntSliderSetting("Honeyjar_Potion", "Potion Slots", 1, 3); public static final ReplayIntSliderSetting SETTING_HAND = new ReplayIntSliderSetting("Honeyjar_Hand", "Max Hand Size Bonus", 0, 5); public static final ReplayIntSliderSetting SETTING_ENERGY = new ReplayIntSliderSetting("Honeyjar_Energy", "Energy Per Turn", 0, 2); public static final ReplayIntSliderSetting SETTING_UPGRADE = new ReplayIntSliderSetting("Honeyjar_Upgrade", "Upgrade random card every __ rooms", 0, 5); public static final ReplayBooleanSetting SETTING_FLOOR = new ReplayBooleanSetting("Honeyjar_Floor", "Downside lasts only 1 floor.", false); public ArrayList<ReplayRelicSetting> BuildRelicSettings() { ArrayList<ReplayRelicSetting> settings = new ArrayList<ReplayRelicSetting>(); settings.add(SETTING_FLOOR); settings.add(SETTING_DRAW); settings.add(SETTING_RETAIN); settings.add(SETTING_HAND); settings.add(SETTING_CHOICE); settings.add(SETTING_POTION); settings.add(SETTING_ENERGY); return settings; } public HoneyJar() { super("Honey Jar", "honeyJar.png", RelicTier.BOSS, LandingSound.FLAT); this.counter = -3; } @Override public void justEnteredRoom(final AbstractRoom room) { if (this.counter == -3 && room instanceof TreasureRoomBoss) { this.counter = -2; } else if (this.counter == -2 && !(room instanceof TreasureRoomBoss) && !(room instanceof MonsterRoomBoss)) { this.counter = -1; } } @Override public String getUpdatedDescription() { String desc = (SETTING_FLOOR.value) ? DESCRIPTIONS[1] : DESCRIPTIONS[0]; if (SETTING_POTION.value > 0) { desc = DESCRIPTIONS[8] + SETTING_POTION.value + DESCRIPTIONS[(SETTING_POTION.value > 1) ? 10 : 9] + " NL " + desc; } if (SETTING_CHOICE.value) { desc = DESCRIPTIONS[7] + " NL " + desc; } if (SETTING_HAND.value > 0) { desc = DESCRIPTIONS[11] + SETTING_HAND.value + ". NL " + desc; } if (SETTING_RETAIN.value > 0) { desc = DESCRIPTIONS[6] + SETTING_RETAIN.value + DESCRIPTIONS[(SETTING_RETAIN.value > 1) ? 5 : 4] + " NL " + desc; } if (SETTING_DRAW.value > 0) { desc = DESCRIPTIONS[2] + SETTING_DRAW.value + DESCRIPTIONS[3] + DESCRIPTIONS[(SETTING_DRAW.value > 1) ? 5 : 4] + " NL " + desc; } if (SETTING_ENERGY.value > 0) { String estring = ""; for (int i=0; i < SETTING_ENERGY.value; i++) { estring += "[E]"; } desc = DESCRIPTIONS[12] + estring + DESCRIPTIONS[13] + " NL " + desc; } return desc; } @Override public AbstractRelic makeCopy() { return new HoneyJar(); } @Override public void atBattleStart() { if (SETTING_RETAIN.value > 0) { this.flash(); AbstractDungeon.actionManager.addToTop(new ApplyPowerAction(AbstractDungeon.player, AbstractDungeon.player, new RetainCardPower(AbstractDungeon.player, SETTING_RETAIN.value), SETTING_RETAIN.value)); AbstractDungeon.actionManager.addToTop(new RelicAboveCreatureAction(AbstractDungeon.player, this)); } } @Override public void onEquip() { final AbstractPlayer player = AbstractDungeon.player; player.masterHandSize += SETTING_DRAW.value; for (int i=0; i < SETTING_POTION.value; i++) { player.potionSlots += 1; AbstractDungeon.player.potions.add(new PotionSlot(AbstractDungeon.player.potionSlots - 1)); } BaseMod.MAX_HAND_SIZE += SETTING_HAND.value; if (SETTING_ENERGY.value > 0) { final EnergyManager energy = AbstractDungeon.player.energy; energy.energyMaster += SETTING_ENERGY.value; } ReplayTheSpireMod.noSkipRewardsRoom = true; } @Override public void onUnequip() { final AbstractPlayer player = AbstractDungeon.player; player.masterHandSize -= SETTING_DRAW.value; BaseMod.MAX_HAND_SIZE -= SETTING_HAND.value; if (SETTING_ENERGY.value > 0) { final EnergyManager energy = AbstractDungeon.player.energy; energy.energyMaster -= SETTING_ENERGY.value; } } @Override public int changeNumberOfCardsInReward(final int numberOfCards) { return ((SETTING_CHOICE.value) ? numberOfCards + 1 : numberOfCards); } }
412
0.982124
1
0.982124
game-dev
MEDIA
0.976272
game-dev
0.990757
1
0.990757
Courseplay/courseplay
11,577
signs.lua
courseplay.signs = {}; local deg, rad = math.deg, math.rad; --[[ TODO - run updateWaypointSigns() when course has been saved ]] local signData = { normal = { 10000, 'current', 4.5 }, -- orig height=5 start = { 500, 'current', 4.5 }, -- orig height=3 stop = { 500, 'current', 4.5 }, -- orig height=3 wait = { 1000, 'current', 4.5 }, -- orig height=3 unload = { 2000, 'current', 4.0 }, cross = { 2000, 'crossing', 4.0 } }; local waypointColors = { regular = { 1.000, 0.212, 0.000, 1.000 }; -- orange turnStart = { 0.200, 0.900, 0.000, 1.000 }; -- green turnEnd = { 0.896, 0.000, 0.000, 1.000 }; -- red }; function courseplay.signs:setup() print('## Courseplay: setting up signs'); local globalRootNode = getRootNode(); self.buffer = {}; self.bufferMax = {}; self.sections = {}; self.heightPos = {}; self.protoTypes = {}; for signType,data in pairs(signData) do self.buffer[signType] = {}; self.bufferMax[signType] = data[1]; self.sections[signType] = data[2]; self.heightPos[signType] = data[3]; local i3dNode = g_i3DManager:loadSharedI3DFile( 'img/signs/' .. signType .. '.i3d' , courseplay.path); local itemNode = getChildAt(i3dNode, 0); link(globalRootNode, itemNode); setRigidBodyType(itemNode, 'NoRigidBody'); setTranslation(itemNode, 0, 0, 0); setVisibility(itemNode, false); delete(i3dNode); self.protoTypes[signType] = itemNode; end; end; function courseplay.signs:addSign(vehicle, signType, x, z, rotX, rotY, insertIndex, distanceToNext, diamondColor) signType = signType or 'normal'; local sign; local signFromBuffer = {}; local receivedSignFromBuffer = courseplay.utils.table.move(self.buffer[signType], signFromBuffer); if receivedSignFromBuffer then sign = signFromBuffer[1].sign; else sign = clone(self.protoTypes[signType], true); end; self:setTranslation(sign, signType, x, z); rotX = rotX or 0; rotY = rotY or 0; setRotation(sign, rad(rotX), rad(rotY), 0); if signType == 'normal' or signType == 'start' or signType == 'wait' then if signType == 'start' or signType == 'wait' then local signPart = getChildAt(sign, 1); setRotation(signPart, rad(-rotX), 0, 0); end; if distanceToNext and distanceToNext > 0.01 then self:setWaypointSignLine(sign, distanceToNext, true); else self:setWaypointSignLine(sign, nil, false); end; end; setVisibility(sign, true); local signData = { type = signType, sign = sign, posX = x, posZ = z, rotY = rotY }; if diamondColor and signType ~= 'cross' then self:setSignColor(signData, diamondColor); end; local section = self.sections[signType]; insertIndex = insertIndex or (#vehicle.cp.signs[section] + 1); table.insert(vehicle.cp.signs[section], insertIndex, signData); end; function courseplay.signs:moveToBuffer(vehicle, vehicleIndex, signData) -- self = courseplay.signs local signType = signData.type; local section = self.sections[signType]; if #self.buffer[signType] < self.bufferMax[signType] then setVisibility(signData.sign, false); courseplay.utils.table.move(vehicle.cp.signs[section], self.buffer[signType], vehicleIndex); else self:deleteSign(signData.sign); vehicle.cp.signs[section][vehicleIndex] = nil; end; end; function courseplay.signs:setTranslation(sign, signType, x, z) local terrainHeight = getTerrainHeightAtWorldPos(g_currentMission.terrainRootNode, x, 300, z); setTranslation(sign, x, terrainHeight + self.heightPos[signType], z); end; function courseplay.signs:changeSignType(vehicle, vehicleIndex, oldType, newType) local section = self.sections[oldType]; local signData = vehicle.cp.signs[section][vehicleIndex]; self:moveToBuffer(vehicle, vehicleIndex, signData); self:addSign(vehicle, newType, signData.posX, signData.posZ, signData.rotX, signData.rotY, vehicleIndex, nil, 'regular'); end; function courseplay.signs:setWaypointSignLine(sign, distance, vis) local line = getChildAt(sign, 0); if line ~= 0 then if vis and distance ~= nil then setScale(line, 1, 1, distance); end; if vis ~= nil then setVisibility(line, vis); end; end; end; function courseplay.signs:updateWaypointSigns(vehicle, section, idx) local waypoints = vehicle.Waypoints section = section or 'all'; --section: 'all', 'crossing', 'current' courseplay.debugVehicle(courseplay.DBG_COURSES, vehicle, 'Updating waypoint display for %s', section) vehicle.cp.numWaitPoints = 0; vehicle.cp.numCrossingPoints = 0; vehicle:setCpVar('numWaypoints', #waypoints, courseplay.isClient); if section == 'all' or section == 'current' then local neededPoints = #waypoints; --move not needed ones to buffer if #vehicle.cp.signs.current > neededPoints then for j=#vehicle.cp.signs.current, neededPoints+1, -1 do --go backwards so we can safely move/delete local signData = vehicle.cp.signs.current[j]; self:moveToBuffer(vehicle, j, signData); end; end; local np; for i,wp in pairs(waypoints) do if idx == nil or i == idx then -- add this for courseEditor local neededSignType = 'normal'; if i == 1 then neededSignType = 'start'; elseif i == #waypoints then neededSignType = 'stop'; elseif wp.wait or wp.interact then neededSignType = 'wait'; elseif wp.unload then neededSignType = 'unload'; end; -- TODO: remove this once we get rid of the terrible cx/cz notation -- make sure we have cx and cz wp.cx = wp.cx or wp.x wp.cy = wp.cy or wp.y wp.cz = wp.cz or wp.z -- direction + angle if wp.rotX == nil then wp.rotX = 0; end; if wp.cy == nil or wp.cy == 0 then wp.cy = getTerrainHeightAtWorldPos(g_currentMission.terrainRootNode, wp.cx, 0, wp.cz); end; if i < #waypoints then np = waypoints[i + 1]; -- TODO: remove this once we get rid of the terrible cx/cz notation np.cx = np.cx or np.x np.cy = np.cy or np.y np.cz = np.cz or np.z if np.cy == nil or np.cy == 0 then np.cy = getTerrainHeightAtWorldPos(g_currentMission.terrainRootNode, np.cx, 0, np.cz); end; wp.dirX, wp.dirY, wp.dirZ, wp.distToNextPoint = courseplay:getWorldDirection(wp.cx, wp.cy, wp.cz, np.cx, np.cy, np.cz); if wp.distToNextPoint <= 0.01 and i > 1 then local pp = waypoints[i - 1]; wp.dirX, wp.dirY, wp.dirZ = pp.dirX, pp.dirY, pp.dirZ; end; wp.rotY = MathUtil.getYRotationFromDirection(wp.dirX, wp.dirZ); wp.angle = deg(wp.rotY); local dy = np.cy - wp.cy; local dist2D = MathUtil.vector2Length(np.cx - wp.cx, np.cz - wp.cz); wp.rotX = -MathUtil.getYRotationFromDirection(dy, dist2D); else local pp = waypoints[i - 1]; if pp then wp.dirX, wp.dirY, wp.dirZ, wp.distToNextPoint = pp.dirX, pp.dirY, pp.dirZ, 0; wp.rotX = 0; wp.rotY = pp.rotY; end end; local diamondColor = 'regular'; if wp.turnStart then diamondColor = 'turnStart'; elseif wp.turnEnd then diamondColor = 'turnEnd'; end; local existingSignData = vehicle.cp.signs.current[i]; if existingSignData ~= nil then if existingSignData.type == neededSignType then self:setTranslation(existingSignData.sign, existingSignData.type, wp.cx, wp.cz); if wp.rotX and wp.rotY then setRotation(existingSignData.sign, wp.rotX, wp.rotY, 0); if neededSignType == 'normal' or neededSignType == 'start' or neededSignType == 'wait' or neededSignType == 'unload' then if neededSignType == 'start' or neededSignType == 'wait' or neededSignType == 'unload' then local signPart = getChildAt(existingSignData.sign, 1); setRotation(signPart, -wp.rotX, 0, 0); end; self:setWaypointSignLine(existingSignData.sign, wp.distToNextPoint, true); end; if neededSignType ~= 'cross' then self:setSignColor(existingSignData, diamondColor); end; end; else self:moveToBuffer(vehicle, i, existingSignData); self:addSign(vehicle, neededSignType, wp.cx, wp.cz, deg(wp.rotX), wp.angle, i, wp.distToNextPoint, diamondColor); end; else self:addSign(vehicle, neededSignType, wp.cx, wp.cz, deg(wp.rotX), wp.angle, i, wp.distToNextPoint, diamondColor); end; if wp.wait then vehicle.cp.numWaitPoints = vehicle.cp.numWaitPoints + 1; end; if wp.crossing then vehicle.cp.numCrossingPoints = vehicle.cp.numCrossingPoints + 1; end; end end; end; if section == 'all' or section == 'crossing' then --TODO: adapt to MP if g_currentMission.cp_courses ~= nil then -- ??? MP Ready ??? if #vehicle.cp.signs.crossing > 0 then for i=#vehicle.cp.signs.crossing, 1, -1 do --go backwards so we can safely move/delete local signData = vehicle.cp.signs.crossing[i]; self:moveToBuffer(vehicle, i, signData); end; end; for _,course in pairs(g_currentMission.cp_courses) do if course.waypoints then for _,wp in pairs(course.waypoints) do if wp.crossing then self:addSign(vehicle, 'cross', wp.cx, wp.cz, nil, wp.angle); end; end; end; end end; end; self:setSignsVisibility(vehicle); end; function courseplay.signs:setSignColor(signData, colorName) if signData.type ~= 'cross' and (signData.color == nil or signData.color ~= colorName) then local x,y,z,w = unpack(waypointColors[colorName]); -- print(('setSignColor (%q): sign=%s, x=%.3f, y=%.3f, z=%.3f, w=%d'):format(colorName, tostring(signData.sign), x, y, z, w)); setShaderParameter(signData.sign, 'shapeColor', x,y,z,w, false); signData.color = colorName; end; end; function courseplay.signs:deleteSign(sign) unlink(sign); delete(sign); end; function courseplay.signs:setSignsVisibility(vehicle, forceHide) if vehicle.cp == nil or vehicle.cp.signs == nil or (#vehicle.cp.signs.current == 0 and #vehicle.cp.signs.crossing == 0) then return; end; local showVisualWaypointsState = vehicle.cp.settings.showVisualWaypoints:get() local numSigns = #vehicle.cp.signs.current; courseplay.debugVehicle(courseplay.DBG_COURSES, vehicle, 'Setting visibility for %d waypoints, start/end=%s all=%s, xing=%s', numSigns, tostring(vehicle.cp.visualWaypointsStartEnd), tostring(vehicle.cp.visualWaypointsAll), tostring(vehicle.cp.visualWaypointsCrossing)) local vis, isStartEndPoint; for k,signData in pairs(vehicle.cp.signs.current) do vis = false; isStartEndPoint = k <= 2 or k >= (numSigns - 2); if (signData.type == 'wait' or signData.type == 'unload') and showVisualWaypointsState>=ShowVisualWaypointsSetting.START_STOP then vis = true; local line = getChildAt(signData.sign, 0); if showVisualWaypointsState==ShowVisualWaypointsSetting.START_STOP then setVisibility(line, isStartEndPoint); else setVisibility(line, true); end; else if showVisualWaypointsState==ShowVisualWaypointsSetting.ALL then vis = true; elseif showVisualWaypointsState>=ShowVisualWaypointsSetting.START_STOP and isStartEndPoint then vis = true; end; end; if vehicle.cp.isRecording then vis = true; elseif forceHide or not vehicle:getIsEntered() then vis = false; end; setVisibility(signData.sign, vis); end; for _,signData in pairs(vehicle.cp.signs.crossing) do local vis = vehicle.cp.settings.showVisualWaypointsCrossPoint:get() if forceHide or not vehicle:getIsEntered() then vis = false; end; setVisibility(signData.sign, vis); end; end;
412
0.823247
1
0.823247
game-dev
MEDIA
0.488304
game-dev
0.745077
1
0.745077
biggestmannest/CS2StratRoulette
2,058
CS2StratRoulette/Strategies/DecoyDodgeball.cs
using System.Diagnostics.CodeAnalysis; using CounterStrikeSharp.API; using CounterStrikeSharp.API.Core; using CounterStrikeSharp.API.Modules.Entities.Constants; using CounterStrikeSharp.API.Modules.Timers; using CS2StratRoulette.Extensions; using CS2StratRoulette.Helpers; namespace CS2StratRoulette.Strategies { [SuppressMessage("ReSharper", "UnusedType.Global")] public sealed class DecoyDodgeball : Strategy { public override string Name => "Decoy Dodgeball"; public override string Description => "1 HP + Infinite Decoys"; public override bool Start(ref CS2StratRoulettePlugin plugin) { if (!base.Start(ref plugin)) { return false; } Player.ForEach((controller) => { if (!controller.TryGetPlayerPawn(out var pawn)) { return; } Server.NextFrame(() => controller.EquipKnife()); Server.NextFrame(() => controller.RemoveWeapons()); controller.GiveNamedItem(CsItem.Decoy); Server.NextFrame(() => { pawn.Health = 1; pawn.MaxHealth = 1; pawn.ArmorValue = 0; }); Server.NextFrame(() => { Utilities.SetStateChanged(pawn, "CBaseEntity", "m_iMaxHealth"); Utilities.SetStateChanged(pawn, "CBaseEntity", "m_iMaxHealth"); Utilities.SetStateChanged(pawn, "CCSPlayerPawn", "m_ArmorValue"); }); }); plugin.RegisterEventHandler<EventWeaponFire>(this.OnWeaponFire); return true; } public override bool Stop(ref CS2StratRoulettePlugin plugin) { if (!base.Stop(ref plugin)) { return false; } plugin.DeregisterEventHandler<EventWeaponFire>(this.OnWeaponFire); return true; } private HookResult OnWeaponFire(EventWeaponFire @event, GameEventInfo _) { var controller = @event.Userid; if (controller is null) { return HookResult.Continue; } var weapon = @event.Weapon; var isGrenade = Weapon.IsGrenade(weapon); if (!isGrenade) { return HookResult.Continue; } Server.NextFrame(() => { controller.GiveNamedItem(weapon); }); return HookResult.Continue; } } }
412
0.935593
1
0.935593
game-dev
MEDIA
0.960465
game-dev
0.644043
1
0.644043
piruzhaolu/ActionFlow
2,191
Packages/lipi.action-flow/Runtime/Nodes/BehaviorTree/BTLoopUntilFailureAsset.cs
using UnityEngine; using System.Collections; namespace ActionFlow { /// <summary> /// 子节点执行失败则返回成功,否则一直处理Running状态 /// </summary> [System.Serializable] [NodeInfo("BT/LoopUntilFailure")] public class BTLoopUntilFailure : StatusNodeBase<NullStatus>, IBehaviorCompositeNode { [HideInInspector] public int _i; //无意义,暂时处理无数据类型序列化出错 [NodeOutputBT] public BehaviorStatus BehaviorInput(ref Context context) { var res = context.BTNodeOutput(); switch (res) { case BehaviorStatus.Running: context.Inactive(this); return BehaviorStatus.Running; case BehaviorStatus.Failure: return BehaviorStatus.Success; default: context.Active(this); return BehaviorStatus.Running; } } public (bool, BehaviorStatus) Completed(ref Context context, int childIndex, BehaviorStatus result) { switch (result) { case BehaviorStatus.Failure: return (true, BehaviorStatus.Success); case BehaviorStatus.Success: context.Active(this); return (false, BehaviorStatus.None); default: return (false, BehaviorStatus.None); } } public override void OnTick(ref Context context) { var res = context.BTNodeOutput(); switch (res) { case BehaviorStatus.Running: context.Inactive(this); break; case BehaviorStatus.Failure: context.Inactive(this); context.BehaviorRunningCompleted(BehaviorStatus.Success); break; default: context.Active(this); break; } } } //[NodeInfo("BT/LoopUntilFailure")] //public class BTLoopUntilFailureAsset : NodeAsset<BTLoopUntilFailure> //{ //} }
412
0.776661
1
0.776661
game-dev
MEDIA
0.648758
game-dev
0.70923
1
0.70923
terrafx/terrafx.interop.windows
7,090
sources/Interop/Windows/Windows/um/sapi/ISpPhoneticAlphabetConverter.cs
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/sapi.h in the Windows SDK for Windows 10.0.26100.0 // Original source is Copyright © Microsoft. All rights reserved. using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using static TerraFX.Interop.Windows.IID; namespace TerraFX.Interop.Windows; /// <include file='ISpPhoneticAlphabetConverter.xml' path='doc/member[@name="ISpPhoneticAlphabetConverter"]/*' /> [Guid("133ADCD4-19B4-4020-9FDC-842E78253B17")] [NativeTypeName("struct ISpPhoneticAlphabetConverter : IUnknown")] [NativeInheritance("IUnknown")] public unsafe partial struct ISpPhoneticAlphabetConverter : ISpPhoneticAlphabetConverter.Interface, INativeGuid { static Guid* INativeGuid.NativeGuid => (Guid*)Unsafe.AsPointer(in IID_ISpPhoneticAlphabetConverter); public void** lpVtbl; /// <inheritdoc cref="IUnknown.QueryInterface" /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(0)] public HRESULT QueryInterface([NativeTypeName("const IID &")] Guid* riid, void** ppvObject) { return ((delegate* unmanaged[MemberFunction]<ISpPhoneticAlphabetConverter*, Guid*, void**, int>)(lpVtbl[0]))((ISpPhoneticAlphabetConverter*)Unsafe.AsPointer(ref this), riid, ppvObject); } /// <inheritdoc cref="IUnknown.AddRef" /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(1)] [return: NativeTypeName("ULONG")] public uint AddRef() { return ((delegate* unmanaged[MemberFunction]<ISpPhoneticAlphabetConverter*, uint>)(lpVtbl[1]))((ISpPhoneticAlphabetConverter*)Unsafe.AsPointer(ref this)); } /// <inheritdoc cref="IUnknown.Release" /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(2)] [return: NativeTypeName("ULONG")] public uint Release() { return ((delegate* unmanaged[MemberFunction]<ISpPhoneticAlphabetConverter*, uint>)(lpVtbl[2]))((ISpPhoneticAlphabetConverter*)Unsafe.AsPointer(ref this)); } /// <include file='ISpPhoneticAlphabetConverter.xml' path='doc/member[@name="ISpPhoneticAlphabetConverter.GetLangId"]/*' /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(3)] public HRESULT GetLangId([NativeTypeName("WORD *")] ushort* pLangID) { return ((delegate* unmanaged[MemberFunction]<ISpPhoneticAlphabetConverter*, ushort*, int>)(lpVtbl[3]))((ISpPhoneticAlphabetConverter*)Unsafe.AsPointer(ref this), pLangID); } /// <include file='ISpPhoneticAlphabetConverter.xml' path='doc/member[@name="ISpPhoneticAlphabetConverter.SetLangId"]/*' /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(4)] public HRESULT SetLangId([NativeTypeName("WORD")] ushort LangID) { return ((delegate* unmanaged[MemberFunction]<ISpPhoneticAlphabetConverter*, ushort, int>)(lpVtbl[4]))((ISpPhoneticAlphabetConverter*)Unsafe.AsPointer(ref this), LangID); } /// <include file='ISpPhoneticAlphabetConverter.xml' path='doc/member[@name="ISpPhoneticAlphabetConverter.SAPI2UPS"]/*' /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(5)] public HRESULT SAPI2UPS([NativeTypeName("const SPPHONEID *")] char* pszSAPIId, [NativeTypeName("SPPHONEID *")] char* pszUPSId, [NativeTypeName("DWORD")] uint cMaxLength) { return ((delegate* unmanaged[MemberFunction]<ISpPhoneticAlphabetConverter*, char*, char*, uint, int>)(lpVtbl[5]))((ISpPhoneticAlphabetConverter*)Unsafe.AsPointer(ref this), pszSAPIId, pszUPSId, cMaxLength); } /// <include file='ISpPhoneticAlphabetConverter.xml' path='doc/member[@name="ISpPhoneticAlphabetConverter.UPS2SAPI"]/*' /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(6)] public HRESULT UPS2SAPI([NativeTypeName("const SPPHONEID *")] char* pszUPSId, [NativeTypeName("SPPHONEID *")] char* pszSAPIId, [NativeTypeName("DWORD")] uint cMaxLength) { return ((delegate* unmanaged[MemberFunction]<ISpPhoneticAlphabetConverter*, char*, char*, uint, int>)(lpVtbl[6]))((ISpPhoneticAlphabetConverter*)Unsafe.AsPointer(ref this), pszUPSId, pszSAPIId, cMaxLength); } /// <include file='ISpPhoneticAlphabetConverter.xml' path='doc/member[@name="ISpPhoneticAlphabetConverter.GetMaxConvertLength"]/*' /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(7)] public HRESULT GetMaxConvertLength([NativeTypeName("DWORD")] uint cSrcLength, BOOL bSAPI2UPS, [NativeTypeName("DWORD *")] uint* pcMaxDestLength) { return ((delegate* unmanaged[MemberFunction]<ISpPhoneticAlphabetConverter*, uint, BOOL, uint*, int>)(lpVtbl[7]))((ISpPhoneticAlphabetConverter*)Unsafe.AsPointer(ref this), cSrcLength, bSAPI2UPS, pcMaxDestLength); } public interface Interface : IUnknown.Interface { [VtblIndex(3)] HRESULT GetLangId([NativeTypeName("WORD *")] ushort* pLangID); [VtblIndex(4)] HRESULT SetLangId([NativeTypeName("WORD")] ushort LangID); [VtblIndex(5)] HRESULT SAPI2UPS([NativeTypeName("const SPPHONEID *")] char* pszSAPIId, [NativeTypeName("SPPHONEID *")] char* pszUPSId, [NativeTypeName("DWORD")] uint cMaxLength); [VtblIndex(6)] HRESULT UPS2SAPI([NativeTypeName("const SPPHONEID *")] char* pszUPSId, [NativeTypeName("SPPHONEID *")] char* pszSAPIId, [NativeTypeName("DWORD")] uint cMaxLength); [VtblIndex(7)] HRESULT GetMaxConvertLength([NativeTypeName("DWORD")] uint cSrcLength, BOOL bSAPI2UPS, [NativeTypeName("DWORD *")] uint* pcMaxDestLength); } public partial struct Vtbl<TSelf> where TSelf : unmanaged, Interface { [NativeTypeName("HRESULT (const IID &, void **) __attribute__((stdcall))")] public delegate* unmanaged[MemberFunction]<TSelf*, Guid*, void**, int> QueryInterface; [NativeTypeName("ULONG () __attribute__((stdcall))")] public delegate* unmanaged[MemberFunction]<TSelf*, uint> AddRef; [NativeTypeName("ULONG () __attribute__((stdcall))")] public delegate* unmanaged[MemberFunction]<TSelf*, uint> Release; [NativeTypeName("HRESULT (WORD *) __attribute__((stdcall))")] public delegate* unmanaged[MemberFunction]<TSelf*, ushort*, int> GetLangId; [NativeTypeName("HRESULT (WORD) __attribute__((stdcall))")] public delegate* unmanaged[MemberFunction]<TSelf*, ushort, int> SetLangId; [NativeTypeName("HRESULT (const SPPHONEID *, SPPHONEID *, DWORD) __attribute__((stdcall))")] public delegate* unmanaged[MemberFunction]<TSelf*, char*, char*, uint, int> SAPI2UPS; [NativeTypeName("HRESULT (const SPPHONEID *, SPPHONEID *, DWORD) __attribute__((stdcall))")] public delegate* unmanaged[MemberFunction]<TSelf*, char*, char*, uint, int> UPS2SAPI; [NativeTypeName("HRESULT (DWORD, BOOL, DWORD *) __attribute__((stdcall))")] public delegate* unmanaged[MemberFunction]<TSelf*, uint, BOOL, uint*, int> GetMaxConvertLength; } }
412
0.732075
1
0.732075
game-dev
MEDIA
0.401966
game-dev
0.523267
1
0.523267
smallbasic/SmallBASIC
14,030
samples/distro-examples/games/sokoban.bas
' ' $Id$ ' option predef grmode 700x500 const bl_w = 25 const bl_h = 25 const bl_x = 45 const bl_y = 45 ' ' draw the game boundary ' sub draw_walls(x, y) local px = bl_x + (x * bl_w) local py = bl_y + (y * bl_h) rect px, py, step bl_w, bl_h, 1 filled rect px, py, step bl_w, bl_h, 2 end ' ' draw the block target ' sub draw_target(x, y) local px = bl_x + (x * bl_w) local py = bl_y + (y * bl_h) rect px, py, step bl_w, bl_h, 3 filled rect px, py, step bl_w, bl_h, 4 end ' ' draw the movable block ' sub draw_block(x, y) local px = bl_x + (x * bl_w) + 1 local py = bl_y + (y * bl_h) + 1 rect px, py, step bl_w - 1, bl_h - 1, 5 filled rect px, py, step bl_w - 2, bl_h - 2, 6 end ' ' draw the empty space within the grid ' sub draw_space(x, y) local px = bl_x + (x * bl_w) + 1 local py = bl_y + (y * bl_h) + 1 rect px, py, step bl_w - 1, bl_h - 1, 8 filled end ' ' draw the sokoban man ' sub draw_soko(x, y, direction) local bx = bl_x + (x * bl_w) local by = bl_y + (y * bl_h) local dx, dy, PolyArray dx = bl_w / 5 dy = bl_w / 5 PolyArray = [[3 * dx, 1 * dy], & [5 * dx, 2 * dy], & [4 * dx, 2 * dy], & [4 * dx, 4 * dy], & [3 * dx, 3 * dy], & [2 * dx, 4 * dy], & [2 * dx, 2 * dy], & [1 * dx, 2 * dy], & [3 * dx, 1 * dy]] DrawPoly PolyArray, bx, by Color 9 filled Circle dx * 3 + bx, by + 5, 3 color 9 filled end ' ' show the game status ' sub game_status(byref game) local help, num_over ' count the number of blocks over the targts local bl_len = len(game.blocks) - 1 num_over = 0 for i = 0 to bl_len local block = game.blocks(i) local x = block(0) local y = block(1) if (mid(game.grid(y), x, 1) == ".") then num_over++ fi next i if (num_over == bl_len + 1) then local y_loc = 5 + txth("T") for i = 0 to 10 at 10, y_loc if (i mod 2 == 0) then ? "*** GAME OVER ***" else ? spc(20) fi delay 300 next i game.game_over = true fi color 1,8 help = " [e]=exit, [u]=undo" at 10, 5: ? cat(1); "Moves: "; game.moves; " Pushes: "; game.pushes; cat(-1); help ; spc(20) end ' ' whether there is a block at the x/y location ' func get_block(byref blocks, x, y) local i local result = false local bl_len = len(game.blocks) - 1 for i = 0 to bl_len local block = game.blocks(i) if (block(0) = x && block(1) = y) then result = true i = bl_len fi next i get_block = result end ' ' draw the game board ' sub init_game(grid, byref game) local row, col, row_len, x, y, ch dim blocks ' cls rect 0, 0, xmax, ymax, 8 filled erase game y = 0 for row in grid row_len = len(row) for x = 1 to row_len ch = mid(row, x, 1) select case ch case "#"' ' border draw_walls x, y case "@" ' sokoban man draw_soko x, y, 1 game.soko_x = x game.soko_y = y case "." ' block target draw_target x, y case "$" ' moveable block draw_block x, y blocks << [x,y] end select next i y++ next row game.blocks = blocks game.grid = grid game.undo_top = 0 dim game.undo end ' ' return whether the x/y location touches the border ' func is_border(byref grid, x, y) is_border = mid(grid(y), x, 1) == "#" end ' ' whether soko is current over a drop target ' func is_target(byref game, x, y) local grid = game.grid is_target = mid(grid(y), x, 1) == "." end ' ' loads any sokoban games found in filename ' for more games see: http://www.sourcecode.se/sokoban/levels.php ' func loadGame(filename) tload filename, buffer local blockFound = false local gameName = "" local buffLen = len(buffer) - 1 local nextLine, i, firstChar, games, nextGame dim nextGame local games={} for i = 0 to buffLen nextLine = buffer(i) firstChar = left(trim(nextLine), 1) if (firstChar == "#") then ' now visiting a game block blockFound = true else if firstChar == ";" then ' now visiting a comment if blockFound then ' store the previously visited game block games(gameName) = nextGame fi blockFound = false if (len(nextLine) > 2) then ' comment names the next game gameName = trim(mid(nextLine, 2)) erase nextGame fi fi if (blockFound) then ' append to the next game block nextGame << nextLine fi next i if blockFound then ' store the last game block games(gameName) = nextGame fi loadGame = games end sub mk_button(byref f, fgc, bgc, x, y, w, h, type) local button button.foreground = fgc button.background = bgc button.x = x button.y = y button.width = w button.height = h button.type = type f.inputs << button end ' ' returns a selected file name ' func openFile local dir_list, file_list, frm, form_var, selected_file selected_file = "" ' ' get the file list using the current directory ' sub get_files local list, f ' empty the arrays erase dir_list erase file_list ' re-create as arrays dim dir_list dim file_list if (exist(cwd + "/..")) then dir_list << ".." fi list = files("*") for f in list if (!isdir(f)) then file_list << f else dir_list << f fi next f sort dir_list sort file_list ' sync with first pre-selected file list item selected_file = iff(empty(file_list), "", file_list(0)) end sub refresh_form get_files frm.inputs(0).label = cwd frm.inputs(1).value = dir_list frm.inputs(2).value = file_list frm.refresh() end ' prime the initial files arrays get_files ' define the interface mk_button(frm, 1, 7, 35, 10, 600, -1, "label") mk_button(frm, 1, 7, 35, 35, 150, 200, "listbox") mk_button(frm, 1, 7, -5, 35, 150, 200, "listbox") mk_button(frm, 1, 7, -5, 35, -5, -5, "button") mk_button(frm, 1, 7, -5, 35, -5, -5, "button") frm.inputs(0).label = cwd frm.inputs(1).value = dir_list frm.inputs(2).value = file_list frm.inputs(3).label = "OK" frm.inputs(4).label = "Cancel" frm = form(frm) ' run the interface while 1 frm.doEvents() form_var = frm.value select case form_var case "OK" exit loop case "Cancel" selected_file = "" exit loop case ".." chdir cwd + "/.." refresh_form case else if (isdir(form_var)) then chdir form_var refresh_form else selected_file = form_var fi end select wend ' close the form frm.close() ' apply result openFile = selected_file end ' ' main game loop ' sub main local filename, games, sel_game, game, game_names, i, frm, game_file, start_dir ' remember the starting directory start_dir = cwd sub open_game games = loadGame(game_file) if (len(games) = 0 && game_file != "sokoban.levels") then ' revert back to the default game file ? " Levels file was empty - reverting to 'sokoban.levels' (Press any key...)" pause game_file = start_dir + "sokoban.levels" games = loadGame(game_file) fi if (len(games) > 0) then ' get the sorted list of game names dim game_names for i in games game_names << i next i sort game_names sel_game = game_names(0) init_game games(sel_game), game fi ' build the gui erase frm mk_button(frm, 1, 7, 5, 1, 100, 20, "choice") mk_button(frm, 1, 7, -1, 1, -1, 20, "button") mk_button(frm, 1, 7, -1, 1, -1, 20, "button") frm.inputs(0).value = game_names frm.inputs(1).label = "Open" frm.inputs(2).label = "Play" frm.focus = 0 frm = form(frm) end cls game_file = "sokoban.levels" open_game while 1 frm.doEvents() select case frm.value case "Open" frm.close() rect 0, 0, xmax, ymax, 8 filled new_file = openFile if (len(new_file) > 0 && exist(cwd + new_file)) then game_file = cwd + new_file end if open_game case "Play" frm.close() play_game game open_game case else sel_game = frm.value init_game games(sel_game), game end select wend end ' ' move the block covered by soko ' sub move_block(byref game, xdir, ydir, x, y) local i local bl_len = len(game.blocks) - 1 for i = 0 to bl_len local block = game.blocks(i) if (block(0) = x && block(1) = y) then block(0) = block(0) + xdir block(1) = block(1) + ydir draw_block block(0), block(1) game.blocks(i) = block i = bl_len fi next i end ' ' erase soko from the current position before a move ' sub move_erase(byref game) if (is_target(game, game.soko_x, game.soko_y)) then ' redraw the now empty target draw_target game.soko_x, game.soko_y else draw_space game.soko_x, game.soko_y fi end ' ' move up ' sub move_up(byref game, is_push) move_erase game game.soko_y-- move_erase game game.moves++ draw_soko game.soko_x, game.soko_y, 1 if is_push then move_block game, 0, -1, game.soko_x, game.soko_y game.pushes++ fi end ' ' move down ' sub move_down(byref game, is_push) move_erase game game.soko_y++ move_erase game game.moves++ draw_soko game.soko_x, game.soko_y, 2 if is_push then move_block game, 0, 1, game.soko_x, game.soko_y game.pushes++ fi end ' ' move left ' sub move_left(byref game, is_push) move_erase game game.soko_x-- move_erase game game.moves++ draw_soko game.soko_x, game.soko_y, 3 if is_push then move_block game, -1, 0, game.soko_x, game.soko_y game.pushes++ fi end ' ' move right ' sub move_right(byref game, is_push) move_erase game game.soko_x++ move_erase game game.moves++ draw_soko game.soko_x, game.soko_y, 4 if is_push then move_block game, 1, 0, game.soko_x, game.soko_y game.pushes++ fi end ' ' play the game ' sub play_game(byref game) local k, ch repeat: until len(inkey) = 0 game.game_over = false while game.game_over = false k = inkey(1) if len(k) = 2 then ch = asc(right(k,1)) select case ch case "4" 'left arrow" if (is_border(game.grid, game.soko_x-1, game.soko_y) = false) then if (get_block(game.blocks, game.soko_x-1, game.soko_y) = false) then move_left game, false undo_push game, "R", 0, 0 elif (is_border(game.grid, game.soko_x-2, game.soko_y) = false) then if (get_block(game.blocks, game.soko_x-2, game.soko_y) = false) then move_left game, true undo_push game, "R", game.soko_x-1, game.soko_y fi fi fi case "5" 'right arrow" if (is_border(game.grid, game.soko_x+1, game.soko_y) = false) then if (get_block(game.blocks, game.soko_x+1, game.soko_y) = false) then move_right game, false undo_push game, "L", 0, 0 elif (is_border(game.grid, game.soko_x+2, game.soko_y) = false) then if (get_block(game.blocks, game.soko_x+2, game.soko_y) = false) then move_right game, true undo_push game, "L", game.soko_x+1, game.soko_y fi fi fi case "9" 'up arrow" if (is_border(game.grid, game.soko_x, game.soko_y-1) = false) then if (get_block(game.blocks, game.soko_x, game.soko_y-1) = false) then move_up game, false undo_push game, "D", 0, 0 elif (is_border(game.grid, game.soko_x, game.soko_y-2) = false) then if (get_block(game.blocks, game.soko_x, game.soko_y-2) = false) then move_up game, true undo_push game, "D", game.soko_x, game.soko_y-1 fi fi fi case "10" 'down arrow" if (is_border(game.grid, game.soko_x, game.soko_y+1) = false) then if (get_block(game.blocks, game.soko_x, game.soko_y+1) = false) then move_down game, false undo_push game, "U", 0, 0 elif (is_border(game.grid, game.soko_x, game.soko_y+2) = false) then if (get_block(game.blocks, game.soko_x, game.soko_y+2) = false) then move_down game, true undo_push game, "U", game.soko_x, game.soko_y+1 fi fi fi end select else select case k case "r" restart game case "u" undo game case "e" game.game_over = true end select fi game_status game wend end ' ' restart the game ' sub restart(byref game) end ' ' undo the last move ' sub undo(byref game) local top = len(game.undo) - 1 if (top != -1) then local undo_el = game.undo(top) local soko_dir = undo_el.soko_dir local block_x = undo_el.block_x local block_y = undo_el.block_y delete game.undo, top select case soko_dir case "U": move_up game, false case "D": move_down game, false case "L": move_left game, false case "R": move_right game, false end select if (block_x != 0 && block_y != 0) then ' erase the previous cell if (is_target(game, block_x, block_y)) then draw_target block_x, block_y else draw_space block_x, block_y fi ' move to the previous position select case soko_dir case "U": move_block game, 0, -1, block_x, block_y case "D": move_block game, 0, 1, block_x, block_y case "L": move_block game, -1, 0, block_x, block_y case "R": move_block game, 1, 0, block_x, block_y end select fi fi end ' ' add an element to the undo stack ' sub undo_push(byref game, soko_dir, block_x, block_y) local undo_el undo_el.soko_dir = soko_dir undo_el.block_x = block_x undo_el.block_y = block_y game.undo << undo_el end ' ' program entry point ' main
412
0.689273
1
0.689273
game-dev
MEDIA
0.81915
game-dev
0.893009
1
0.893009
oculus-samples/Unreal-HandGameplay
1,443
Plugins/OculusUtils/Source/OculusUtils/Public/OculusDeveloperTelemetry.h
// Copyright (c) Facebook, Inc. and its affiliates. #pragma once #include "CoreMinimal.h" #if WITH_EDITOR #include "IDetailCustomization.h" #endif #include "OculusDeveloperTelemetry.generated.h" UCLASS(Config=EditorPerProjectUserSettings, meta=(DisplayName="Oculus Developer Telemetry")) class OCULUSUTILS_API UOculusDeveloperTelemetry : public UObject { GENERATED_BODY() DECLARE_MULTICAST_DELEGATE(FOnFlushEvent); FOnFlushEvent OnFlush; public: #if WITH_EDITOR virtual void PostEditChangeProperty(FPropertyChangedEvent& PropertyChangedEvent) override; #endif UPROPERTY(EditAnywhere, Config, meta=(Tooltip="Enabling telemetry will transmit data to Oculus about your usage of its samples and tools.")) bool bIsEnabled = false; UPROPERTY(Config) bool bHasPrompted = false; void SendEvent(const char* eventName, const char* param, const char* source); void Flush(); }; #if WITH_EDITOR class FOculusTelemetrySettingsCustomization : public IDetailCustomization { public: virtual void CustomizeDetails(IDetailLayoutBuilder& DetailBuilder) override; }; #endif #if WITH_EDITOR #define OCULUS_TELEMETRY_LOAD_MODULE(ModuleName) \ static FDelayedAutoRegisterHelper ANONYMOUS_VARIABLE(GMetricsHelper) (EDelayedRegisterRunPhase::EndOfEngineInit, [] \ { \ GetMutableDefault<UOculusDeveloperTelemetry>()->SendEvent("module_loaded", ModuleName, "integration"); \ }); #else #define OCULUS_TELEMETRY_LOAD_MODULE(...) #endif
412
0.923237
1
0.923237
game-dev
MEDIA
0.366649
game-dev
0.6466
1
0.6466
amethyst/rustrogueliketutorial
4,941
chapter-54-xp/src/saveload_system.rs
use specs::prelude::*; use specs::saveload::{SimpleMarker, SimpleMarkerAllocator, SerializeComponents, DeserializeComponents, MarkedBuilder}; use specs::error::NoError; use super::components::*; use std::fs::File; use std::path::Path; use std::fs; macro_rules! serialize_individually { ($ecs:expr, $ser:expr, $data:expr, $( $type:ty),*) => { $( SerializeComponents::<NoError, SimpleMarker<SerializeMe>>::serialize( &( $ecs.read_storage::<$type>(), ), &$data.0, &$data.1, &mut $ser, ) .unwrap(); )* }; } #[cfg(target_arch = "wasm32")] pub fn save_game(_ecs : &mut World) { } #[cfg(not(target_arch = "wasm32"))] pub fn save_game(ecs : &mut World) { // Create helper let mapcopy = ecs.get_mut::<super::map::Map>().unwrap().clone(); let savehelper = ecs .create_entity() .with(SerializationHelper{ map : mapcopy }) .marked::<SimpleMarker<SerializeMe>>() .build(); // Actually serialize { let data = ( ecs.entities(), ecs.read_storage::<SimpleMarker<SerializeMe>>() ); let writer = File::create("./savegame.json").unwrap(); let mut serializer = serde_json::Serializer::new(writer); serialize_individually!(ecs, serializer, data, Position, Renderable, Player, Viewshed, Monster, Name, BlocksTile, SufferDamage, WantsToMelee, Item, Consumable, Ranged, InflictsDamage, AreaOfEffect, Confusion, ProvidesHealing, InBackpack, WantsToPickupItem, WantsToUseItem, WantsToDropItem, SerializationHelper, Equippable, Equipped, MeleeWeapon, Wearable, WantsToRemoveItem, ParticleLifetime, HungerClock, ProvidesFood, MagicMapper, Hidden, EntryTrigger, EntityMoved, SingleActivation, BlocksVisibility, Door, Bystander, Vendor, Quips, Attributes, Skills, Pools, NaturalAttackDefense, LootTable, Carnivore, Herbivore ); } // Clean up ecs.delete_entity(savehelper).expect("Crash on cleanup"); } pub fn does_save_exist() -> bool { Path::new("./savegame.json").exists() } macro_rules! deserialize_individually { ($ecs:expr, $de:expr, $data:expr, $( $type:ty),*) => { $( DeserializeComponents::<NoError, _>::deserialize( &mut ( &mut $ecs.write_storage::<$type>(), ), &$data.0, // entities &mut $data.1, // marker &mut $data.2, // allocater &mut $de, ) .unwrap(); )* }; } pub fn load_game(ecs: &mut World) { { // Delete everything let mut to_delete = Vec::new(); for e in ecs.entities().join() { to_delete.push(e); } for del in to_delete.iter() { ecs.delete_entity(*del).expect("Deletion failed"); } } let data = fs::read_to_string("./savegame.json").unwrap(); let mut de = serde_json::Deserializer::from_str(&data); { let mut d = (&mut ecs.entities(), &mut ecs.write_storage::<SimpleMarker<SerializeMe>>(), &mut ecs.write_resource::<SimpleMarkerAllocator<SerializeMe>>()); deserialize_individually!(ecs, de, d, Position, Renderable, Player, Viewshed, Monster, Name, BlocksTile, SufferDamage, WantsToMelee, Item, Consumable, Ranged, InflictsDamage, AreaOfEffect, Confusion, ProvidesHealing, InBackpack, WantsToPickupItem, WantsToUseItem, WantsToDropItem, SerializationHelper, Equippable, Equipped, MeleeWeapon, Wearable, WantsToRemoveItem, ParticleLifetime, HungerClock, ProvidesFood, MagicMapper, Hidden, EntryTrigger, EntityMoved, SingleActivation, BlocksVisibility, Door, Bystander, Vendor, Quips, Attributes, Skills, Pools, NaturalAttackDefense, LootTable, Carnivore, Herbivore ); } let mut deleteme : Option<Entity> = None; { let entities = ecs.entities(); let helper = ecs.read_storage::<SerializationHelper>(); let player = ecs.read_storage::<Player>(); let position = ecs.read_storage::<Position>(); for (e,h) in (&entities, &helper).join() { let mut worldmap = ecs.write_resource::<super::map::Map>(); *worldmap = h.map.clone(); worldmap.tile_content = vec![Vec::new(); (worldmap.height * worldmap.width) as usize]; deleteme = Some(e); } for (e,_p,pos) in (&entities, &player, &position).join() { let mut ppos = ecs.write_resource::<rltk::Point>(); *ppos = rltk::Point::new(pos.x, pos.y); let mut player_resource = ecs.write_resource::<Entity>(); *player_resource = e; } } ecs.delete_entity(deleteme.unwrap()).expect("Unable to delete helper"); } pub fn delete_save() { if Path::new("./savegame.json").exists() { std::fs::remove_file("./savegame.json").expect("Unable to delete file"); } }
412
0.914734
1
0.914734
game-dev
MEDIA
0.765566
game-dev
0.966817
1
0.966817
simeonradivoev/Code-Node-Editor
1,752
Assets/Editor/Scripts/Util/UIUtilities.cs
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using UnityEngine.Experimental.UIElements; namespace NodeEditor.Util { public static class UIUtilities { public static bool ItemsReferenceEquals<T>(this IList<T> first, IList<T> second) { if (first.Count != second.Count) { return false; } for (int i = 0; i < first.Count; i++) { if (!ReferenceEquals(first[i], second[i])) { return false; } } return true; } public static int GetHashCode(params object[] objects) { return GetHashCode(objects.AsEnumerable()); } public static int GetHashCode<T>(IEnumerable<T> objects) { var hashCode = 17; foreach (var @object in objects) { hashCode = hashCode * 31 + (@object == null ? 79 : @object.GetHashCode()); } return hashCode; } public static IEnumerable<T> ToEnumerable<T>(this T item) { yield return item; } public static void Add<T>(this VisualElement visualElement, T elementToAdd, Action<T> action) where T : VisualElement { visualElement.Add(elementToAdd); action(elementToAdd); } public static IEnumerable<Type> GetTypesOrNothing(this Assembly assembly) { try { return assembly.GetTypes(); } catch { return Enumerable.Empty<Type>(); } } } }
412
0.830582
1
0.830582
game-dev
MEDIA
0.269737
game-dev
0.946654
1
0.946654
michalzalobny/creativeprojects
4,047
frontend/src/containers/CardLeaderPage/classes/Scenes/FollowScene.ts
import * as THREE from 'three'; import { UpdateInfo, FollowItemProps, Bounds } from '../types'; import { Scroll } from '../Singletons/Scroll'; import { CardScene } from './CardScene'; import { MouseMove } from '../Singletons/MouseMove'; import { HTMLComponent } from '../HTMLComponents/HTMLComponent'; import { CardItem3DAnimated } from '../Components/CardItem3DAnimated'; interface Constructor { camera: THREE.PerspectiveCamera; scroll: Scroll; mouseMove: MouseMove; setIsFollowing: React.Dispatch<React.SetStateAction<boolean>>; } export class FollowScene extends CardScene { static respawnTimeout = 90; //ms _scroll: Scroll; _HTMLComponents: HTMLComponent[] = []; _lastAddedTime = 0; _canAddItems = false; _areItemsAnimatedIn = false; _updateAnimateTimeout: ReturnType<typeof setTimeout> | null = null; _setIsFollowing: React.Dispatch<React.SetStateAction<boolean>>; constructor({ setIsFollowing, camera, mouseMove, scroll }: Constructor) { super({ camera, mouseMove }); this._scroll = scroll; this._addListeners(); this._intersectiveBackground3D.setPlaneDepth(0); this._initHtmlComponents(); this._setIsFollowing = setIsFollowing; } _passMouseValues(x: number, y: number) { this._items3D.forEach(item => { item.targetMouse = { x, y }; }); } _animateInItems() { super._animateInItems(); this._canAddItems = true; this._updateAnimateTimeout = setTimeout(() => { this._areItemsAnimatedIn = true; }, FollowScene.respawnTimeout * (this._items.length - 1) + CardItem3DAnimated.defaultDuration); } _onMouseDown = (e: THREE.Event) => { if (!this._areItemsAnimatedIn) { return; } this._setIsFollowing(true); this._items3D.forEach((item, key) => { item.toggleFollowing(true); item.resetLerp(); item.resetDepth(); }); const firstItem = this._items3D.find(el => el.followItem.reverseKey === 1); if (this._focusedObject && this._focusedObject._mesh) { const focusItemLerp = this._focusedObject._lerpEase; const focusItemPositionZ = this._focusedObject._mesh.position.z; if (firstItem && firstItem._mesh) { firstItem._mesh.position.z = focusItemPositionZ; firstItem._lerpEase = focusItemLerp; } this._focusedObject.boostLerp(); this._focusedObject.boostDepth(); } }; _onMouseUp = (e: THREE.Event) => { this._setIsFollowing(false); this._items3D.forEach((item, key) => { item.toggleFollowing(false); }); }; _addListeners() { super._addListeners(); this._mouseMove.addEventListener('down', this._onMouseDown); this._mouseMove.addEventListener('up', this._onMouseUp); } _removeListeners() { super._removeListeners(); this._mouseMove.removeEventListener('down', this._onMouseDown); this._mouseMove.removeEventListener('up', this._onMouseUp); } _passIntersectPoint() { this._items3D.forEach(item => { item.intersectPoint = this._intersectPointLerp; }); } _initHtmlComponents() {} _addItems() { if (!this._canAddItems) { return; } const currentTime = window.performance.now(); const timeDifference = currentTime - this._lastAddedTime; if (timeDifference > FollowScene.respawnTimeout) { super.addItem(); this._lastAddedTime = window.performance.now(); } } update(updateInfo: UpdateInfo) { super.update(updateInfo); this._passIntersectPoint(); this._addItems(); this._HTMLComponents.forEach(el => { el.update(updateInfo); }); } destroy() { super.destroy(); if (this._updateAnimateTimeout) { clearTimeout(this._updateAnimateTimeout); } this._HTMLComponents.forEach(el => { el.destroy(); }); } set rendererBounds(bounds: Bounds) { super.rendererBounds = bounds; this._HTMLComponents.forEach(el => { el.rendererBounds = this._rendererBounds; }); } set items(items: FollowItemProps[]) { super.items = items; } }
412
0.912817
1
0.912817
game-dev
MEDIA
0.654075
game-dev,web-frontend
0.98619
1
0.98619
emilianavt/OpenSeeFaceSample
1,842
Assets/FastIK/Assets/FastIK/Scripts/Sample/SampleProcedualAnimation.cs
using UnityEngine; namespace DitzelGames.FastIK { class SampleProcedualAnimation : MonoBehaviour { public Transform[] FootTarget; public Transform LookTarget; public Transform HandTarget; public Transform HandPole; public Transform Step; public Transform Attraction; public void LateUpdate() { //move step & attraction Step.Translate(Vector3.forward * Time.deltaTime * 0.7f); if (Step.position.z > 1f) Step.position = Step.position + Vector3.forward * -2f; Attraction.Translate(Vector3.forward * Time.deltaTime * 0.5f); if (Attraction.position.z > 1f) Attraction.position = Attraction.position + Vector3.forward * -2f; //footsteps for(int i = 0; i < FootTarget.Length; i++) { var foot = FootTarget[i]; var ray = new Ray(foot.transform.position + Vector3.up * 0.5f, Vector3.down); var hitInfo = new RaycastHit(); if(Physics.SphereCast(ray, 0.05f, out hitInfo, 0.50f)) foot.position = hitInfo.point + Vector3.up * 0.05f; } //hand and look var normDist = Mathf.Clamp((Vector3.Distance(LookTarget.position, Attraction.position) - 0.3f) / 1f, 0, 1); HandTarget.rotation = Quaternion.Lerp(Quaternion.Euler(90, 0, 0), HandTarget.rotation, normDist); HandTarget.position = Vector3.Lerp(Attraction.position, HandTarget.position, normDist); HandPole.position = Vector3.Lerp(HandTarget.position + Vector3.down * 2, HandTarget.position + Vector3.forward * 2f, normDist); LookTarget.position = Vector3.Lerp(Attraction.position, LookTarget.position, normDist); } } }
412
0.951717
1
0.951717
game-dev
MEDIA
0.977408
game-dev
0.977372
1
0.977372
Ormael13/CoCX
13,205
classes/classes/Scenes/Monsters/FeralImps.as
/** * ... * @author Ormael */ package classes.Scenes.Monsters { import classes.*; import classes.BodyParts.Butt; import classes.BodyParts.Hips; import classes.BodyParts.LowerBody; import classes.BodyParts.Wings; import classes.GlobalFlags.kFLAGS; import classes.Items.DynamicItems; import classes.Scenes.Dungeons.RiverDungeon; import classes.Scenes.SceneLib; import classes.internals.*; public class FeralImps extends Monster { public var floor1:RiverDungeon = new RiverDungeon(); public function clawAttack():void { if (flags[kFLAGS.FERAL_EXTRAS] == 4) outputText(this.capitalA + this.short + " charges at you with their claws ready! "); else outputText("The " + this.short + " charges at you with his claws ready! "); if (player.getEvasionRoll()) { if (flags[kFLAGS.FERAL_EXTRAS] == 4) outputText("You manage to avoid their claws thanks to your reaction!"); else outputText("You manage to avoid his claws thanks to your reaction!"); return; } else { if (flags[kFLAGS.FERAL_EXTRAS] == 4) { outputText(this.capitalA + this.short + " manages to swipe you! You let out a cry in pain. "); var damage1:int = rand(50) + str + weaponAttack; damage1 *= 5; if (damage1 < 100) damage1 = 100; player.takePhysDamage(damage1, true); } else { outputText("The " + this.short + " manages to swipe you! You let out a cry in pain. "); var damage2:int = rand(50) + str + weaponAttack; if (damage2 < 20) damage2 = 20; player.takePhysDamage(damage2, true); } } } public function doubleAttack():void { if (flags[kFLAGS.FERAL_EXTRAS] == 4) outputText(this.capitalA + this.short + " charges at you with their claws ready and sword raised! "); else outputText("The " + this.short + " charges at you with his claws ready and sword raised! "); if (player.getEvasionRoll()) { if (flags[kFLAGS.FERAL_EXTRAS] == 4) outputText("You manage to dodge their deadly attacks!"); else outputText("You manage to dodge his deadly attack!"); return; } else { if (flags[kFLAGS.FERAL_EXTRAS] == 4) { outputText(this.capitalA + this.short + " manages to slash you with their sword and deadly claws!"); var damage1:int = rand(50) + str + weaponAttack; damage1 *= 5; if (damage1 < 100) damage1 = 100; //Min-cap damage. if (damage1 >= 250 && !player.immuneToBleed()) { outputText("You let out a cry in pain and you swear you could see your wounds bleeding. "); player.createStatusEffect(StatusEffects.IzmaBleed, 2, 0, 0, 0); } else outputText("Thankfully the wounds aren't that serious. "); player.takePhysDamage(damage1, true); } else { outputText("The " + this.short + " manages to slash you with his sword and deadly claws!"); var damage2:int = rand(50) + str + weaponAttack; if (damage2 < 20) damage2 = 20; //Min-cap damage. if (damage2 >= 50 && !player.immuneToBleed()) { outputText("You let out a cry in pain and you swear you could see your wounds bleeding. "); player.createStatusEffect(StatusEffects.IzmaBleed, 2, 0, 0, 0); } else outputText("Thankfully the wounds aren't that serious. "); player.takePhysDamage(damage2, true); } } } override protected function performCombatAction():void { this.wrath += 100; if (flags[kFLAGS.FERAL_EXTRAS] < 3 || flags[kFLAGS.FERAL_EXTRAS] == 5) { var choice1:Number = rand(3); if (choice1 < 2) eAttack(); if (choice1 == 2) clawAttack(); } else if (flags[kFLAGS.FERAL_EXTRAS] == 3) { var choice2:Number = rand(4); if (choice2 < 2) eAttack(); if (choice2 == 2) clawAttack(); if (choice2 == 3) doubleAttack(); } else if (flags[kFLAGS.FERAL_EXTRAS] == 4) { var choice3:Number = rand(4); if (choice3 < 2) eAttack(); if (choice3 == 2) clawAttack(); if (choice3 == 3) doubleAttack(); } } override public function defeated(hpVictory:Boolean):void { game.flags[kFLAGS.DEMONS_DEFEATED]++; if (flags[kFLAGS.FERAL_EXTRAS] == 5) SceneLib.combat.cleanupAfterCombatImpl(); else { SceneLib.impScene.impVictory2(); } } override public function won(hpVictory:Boolean, pcCameWorms:Boolean):void { if (flags[kFLAGS.FERAL_EXTRAS] == 5) floor1.defeatedByFeralImp(); else if (flags[kFLAGS.FERAL_EXTRAS] == 4) SceneLib.impScene.impRapesYou2(); else SceneLib.impScene.impRapesYou(); } //flags[kFLAGS.FERAL_EXTRAS] >>> 1 - feral imp, 2 - feral imp lord, 3 - feral imp warlord, 4 - feral imps, 5 - river dungeon feral imp public function FeralImps() { if (flags[kFLAGS.FERAL_EXTRAS] == 1) { this.a = "the "; this.short = "feral imp"; this.imageName = "imp"; this.long = "An feral imp is short, only a few feet tall. An unkempt mane of shaggy black hair hangs from his head, parted by two short curved horns. His eyes are solid black, save for tiny red irises which glow with evil intent. His skin is bright red, and unencumbered by clothing or armor, save for a small loincloth at his belt, and he's extremely well-muscled. His feet are covered by tiny wooden sandals, and his hands tipped with sharp claws. A pair of tiny but functional wings occasionally flap from his back."; this.plural = false; this.tallness = rand(24) + 25; initStrTouSpeInte(36, 5, 10, 7); initWisLibSensCor(7, 45, 35, 100); this.weaponName = "claws"; this.weaponVerb = "claw-slash"; this.weaponAttack = 2; this.armorName = "leathery skin"; this.armorDef = 1; this.armorMDef = 0; this.bonusWrath = 50; this.bonusLust = 81; this.lust = 40; this.level = 1; this.gems = rand(5) + 5; this.special1 = clawAttack; this.createPerk(PerkLib.EnemyForBeginnersType, 0, 0, 0, 0); this.createPerk(PerkLib.OverMaxHP, 1, 0, 0, 0); } if (flags[kFLAGS.FERAL_EXTRAS] == 2) { this.a = "the "; this.short = "feral imp lord"; this.imageName = "implord"; this.long = "The feral imp lord has an angular face, complete with curved nose and burnt red skin typical of imps. He has no hair on his head, leaving his cold, wrath-clouded, black eyes unobstructed. Just above his long pointed ears are two curved bovine horns. While still short, he's much taller then the average imp, being nearly four feet tall, and grotesque overdeveloped muscles. A pair of powerful wings extends out from his shoulders, however, you suspect he wouldn't be able to fly for long due to his extreme bulk. A thick coating of fur starts at his well toned hips and works its way down his powerful legs. His legs end in a pair of oddly jointed, demonic hooves. His demonic figure is completed by a thin tail that has an arrowhead shaped tip.\n\nThe feral imp lord, like most feral imps wear very little clothing; only a simple loincloth and satchel hang from his waist. You also note that the imp has two barbell piercings in his nipples. The creature doesn't seem to have any weapons, aside from his sharp black finger nails."; this.plural = false; this.tallness = rand(14) + 40; this.lowerBody = LowerBody.HOOFED; initStrTouSpeInte(110, 20, 25, 22); initWisLibSensCor(22, 55, 35, 100); this.weaponName = "fist"; this.weaponVerb="punch"; this.weaponAttack = 15; this.armorName = "leathery skin"; this.armorDef = 5; this.armorMDef = 1; this.bonusHP = 100; this.bonusWrath = 150; this.bonusLust = 97; this.lust = 30; this.lustVuln = .65; this.level = 7; this.gems = rand(15) + 25; this.special1 = clawAttack; this.createPerk(PerkLib.OverMaxHP, 7, 0, 0, 0); } if (flags[kFLAGS.FERAL_EXTRAS] == 3) { this.a = "the "; this.short = "feral imp warlord"; this.imageName = "impwarlord"; this.long = "The greater feral imp has an angular face, complete with curved nose and burnt red skin typical of imps. He has a black hair on his head and his eyes are deep black. Just above his long pointed ears are two curved bovine horns. While still short, he's much taller than the average feral imp, being nearly four feet tall, and with grotesque overgrown muscles. A pair of powerful wings extends out from his shoulders, however, you suspect he wouldn't be able to fly for long due to his extreme bulk. A thick coating of fur starts at his well toned hips and works its way down his powerful legs. His legs end in a pair of oddly jointed, demonic hooves. His demonic figure is completed by a thin tail that has an arrowhead shaped tip.\n\nUnlike most feral imps, he is wearing a metal chestplate and bracers for protection. He doesn't appear to be wearing anything other than his armor and loincloth. He wields a sword in his right hand and he doesn't appear to wield anything in his left hand, suggesting that he also attacks with his claws."; this.plural = false; this.tallness = rand(14) + 40; this.lowerBody = LowerBody.HOOFED; initStrTouSpeInte(160, 41, 45, 36); initWisLibSensCor(36, 71, 35, 100); this.weaponName = "sword"; this.weaponVerb="slash"; this.weaponAttack = 30; this.armorName = "platemail"; this.armorDef = 17; this.armorMDef = 1; this.bonusHP = 350; this.bonusWrath = 250; this.bonusLust = 122; this.lust = 30; this.lustVuln = .4; this.level = 16; this.gems = rand(20) + 40; this.special1 = clawAttack; this.special2 = doubleAttack; this.createPerk(PerkLib.OverMaxHP, 16, 0, 0, 0); } if (flags[kFLAGS.FERAL_EXTRAS] == 4) { this.a = "a "; this.short = "pack of feral imps"; this.long = "Feral imps stand anywhere from two to four feet tall, with scrawny builds and tiny demonic wings. Their red and orange skin is dirty, and their dark hair looks greasy. Some are naked, but most are dressed in ragged loincloths that do little to hide their groins. They all have a rather disproportionately-sized members."; this.pronoun1 = "they"; this.pronoun2 = "them"; this.pronoun3 = "their"; this.plural = true; //this.removeStatuses(); //this.removePerks(); //this.removeCock(0, this.cocks.length); //this.removeVagina(0, this.vaginas.length); //this.removeBreastRow(0, this.breastRows.length); this.createBreastRow(); this.createCock(12,1.5); this.createCock(25,2.5); this.createCock(25,2.5); this.cocks[2].cockType = CockTypesEnum.DOG; this.cocks[2].knotMultiplier = 2; this.balls = 2; this.ballSize = 3; this.tallness = 36; initStrTouSpeInte(140, 20, 25, 21); initWisLibSensCor(21, 55, 35, 100); this.weaponName = "claws"; this.weaponVerb="claw"; this.weaponAttack = 24; this.armorName = "leathery skin"; this.armorDef = 10; this.armorMDef = 1; this.bonusHP = 500; this.bonusWrath = 250; this.bonusLust = 105; this.lust = 30; this.lustVuln = .6; this.level = 15; this.gems = rand(20) + 30; this.createPerk(PerkLib.EnemyGroupType, 0, 0, 0, 0); this.createPerk(PerkLib.OverMaxHP, 15, 0, 0, 0); } if (flags[kFLAGS.FERAL_EXTRAS] == 5) { this.a = "the "; this.short = "feral imp"; this.imageName = "imp"; this.long = "An feral imp is short, only a few feet tall. An unkempt mane of shaggy black hair hangs from his head, parted by two short curved horns. His eyes are solid black, save for tiny red irises which glow with evil intent. His skin is bright red, and unencumbered by clothing or armor, save for a small loincloth at his belt, and he's extremely well-muscled. His feet are covered by tiny wooden sandals, and his hands tipped with sharp claws. A pair of tiny but functional wings occasionally flap from his back."; this.plural = false; this.tallness = rand(24) + 25; initStrTouSpeInte(50, 10, 15, 12); initWisLibSensCor(12, 55, 35, 100); this.weaponName = "claws"; this.weaponVerb = "claw-slash"; this.weaponAttack = 5; this.armorName = "leathery skin"; this.armorDef = 4; this.armorMDef = 1; this.bonusHP = 100; this.bonusWrath = 150; this.bonusLust = 92; this.lust = 40; this.level = 2; this.gems = rand(5) + 5; this.special1 = clawAttack; this.createPerk(PerkLib.OverMaxHP, 2, 0, 0, 0); } if (flags[kFLAGS.FERAL_EXTRAS] != 4) { this.createCock(4, 1, CockTypesEnum.DEMON); this.balls = 2; this.ballSize = 1; } createBreastRow(0); this.ass.analLooseness = AssClass.LOOSENESS_STRETCHED; this.ass.analWetness = AssClass.WETNESS_NORMAL; this.hips.type = Hips.RATING_BOYISH; this.butt.type = Butt.RATING_TIGHT; this.bodyColor = "red"; this.hairColor = "black"; this.hairLength = 5; this.randomDropChance = 0.1; this.randomDropParams = { rarity: DynamicItems.RARITY_CHANCES_LESSER }; this.drop = new WeightedDrop(). add(consumables.LABOVA_,2). add(consumables.MINOBLO,1). add(consumables.SUCMILK,3). add(consumables.INCUBID,3). add(consumables.IMPFOOD,4). add(jewelries.POWRRNG,1); this.wings.type = Wings.IMP; this.createPerk(PerkLib.EnemyFeralType, 0, 0, 0, 0); this.createPerk(PerkLib.EnemyTrueDemon, 0, 0, 0, 0); checkMonster(); } } }
412
0.927208
1
0.927208
game-dev
MEDIA
0.99957
game-dev
0.990712
1
0.990712
ill-inc/biomes-game
2,316
src/shared/game/buffs.ts
import type { Buff, Item } from "@/shared/ecs/gen/types"; import type { BuffType } from "@/shared/game/buff_specs"; import { anItem } from "@/shared/game/item"; import type { BiomesId } from "@/shared/ids"; import { log } from "@/shared/logging"; import { ok } from "assert"; import { clamp, first } from "lodash"; function buffDuration(buff: Buff) { const duration = anItem(buff.item_id).duration; if (duration === undefined) { log.warn(`No duration set for buff where item_id=${buff.item_id}.`); } return duration ?? 0; } export function buffTimeRemaining(buff: Buff, time: number) { if (!buff.start_time) { return Number.POSITIVE_INFINITY; } const duration = buffDuration(buff); return clamp(buff.start_time + duration - time, 0, duration); } export function buffExpirationTime(buff: Buff) { if (!buff.start_time) { return Number.POSITIVE_INFINITY; } return buff.start_time + buffDuration(buff); } export function buffType(buff: Buff): BuffType { const buffType = anItem(buff.item_id).buffType; ok(buffType, `Unknown buff type for ${buff.item_id}`); return buffType; } export function buffDescription(buffItemId: BiomesId) { return ( anItem(buffItemId).displayDescription || anItem(buffItemId).displayName ); } export function itemBuffWeights(item: Item) { return item.buffs ?? []; } export function itemBuffType(item: Item) { const buffId = first(itemBuffWeights(item))?.[0]; return buffId ? buffType({ item_id: buffId, start_time: 0, from_id: undefined, is_disabled: undefined, }) : undefined; } export function itemBuffSuspicious(item: Item) { const buffWeights = itemBuffWeights(item); return buffWeights.length > 1; } export function itemBuffDescription( item: Item ): [string | undefined, BuffType | undefined] { const buffWeights = itemBuffWeights(item); let description: string | undefined; let type: BuffType | undefined; if (buffWeights.length === 1) { const buffId = buffWeights[0][0]; description = buffDescription(buffId); type = anItem(buffId).buffType; } else if (buffWeights.length > 1) { description = `Consume suspicious ${ item.action === "eat" ? "food" : "drinks" } at your own risk`; type = "debuff"; } return [description, type]; }
412
0.641141
1
0.641141
game-dev
MEDIA
0.284899
game-dev
0.605821
1
0.605821
Ruin0x11/OpenNefia
5,746
src/mod/elona/data/dialog/unique/strange_scientist.lua
local I18N = require("api.I18N") local Chara = require("api.Chara") local Item = require("api.Item") local Gui = require("api.Gui") local Sidequest = require("mod.elona_sys.sidequest.api.Sidequest") local Inventory = require("api.Inventory") local Rand = require("api.Rand") local ItemMemory = require("mod.elona_sys.api.ItemMemory") local Calc = require("mod.elona.api.Calc") local Enum = require("api.Enum") local Itemgen = require("mod.elona.api.Itemgen") local Input = require("api.Input") local function can_receive_reward() local saved_count = save.elona.little_sisters_saved local gifts_given = save.elona.strange_scientist_gifts_given local required_saved = save.elona.little_sisters_killed for i=1,gifts_given+1 do required_saved = required_saved + i end return saved_count >= required_saved end local function turn_over_little_sister() Gui.mes("talk.unique.strange_scientist.turn_over.text") save.elona.little_sisters_saved = save.elona.little_sisters_saved + 1 Gui.mes_c("talk.unique.strange_scientist.saved_count", "Green", save.elona.little_sisters_saved, save.elona.little_sisters_killed) Chara.find("elona.little_sister", "allies"):vanquish() Gui.play_sound("base.complete1") end local function can_pick_reward_even_if_unknown(item_id) if item_id == "elona.magic_fruit" then return Sidequest.is_complete("elona.kamikaze_attack") end if item_id == "elona.hero_cheese" then return Sidequest.is_complete("elona.rare_books") end if item_id == "elona.happy_apple" then return Sidequest.is_complete("elona.pael_and_her_mom") end return false end local function pick_reward() -- >>>>>>>> shade2/chat.hsp:2014 beginTempInv:mode=mode_shop ... local is_known = function(i, proto) if proto._id == "elona.secret_treasure" then return false end if ItemMemory.is_known(proto._id) then return true end if can_pick_reward_even_if_unknown(proto._id) then return true end return false end local day = save.base.date.day local gen_filter = { level = Chara.player():calc("level") * 3 / 2, ownerless = true } local function gen_item(i, item_proto) local seed = day + i - 1 Rand.set_seed(seed) gen_filter.id = item_proto._id gen_filter.quality = Calc.calc_object_quality(Enum.Quality.Good) return Itemgen.create(nil, nil, gen_filter) end local function is_great_quality_or_better(item) return item and item.quality >= Enum.Quality.Great end local function put_in_inv(inv, item) inv:take_object(item) return inv end local inv = data["base.item"]:iter():enumerate() :filter(is_known) :map(gen_item) :filter(is_great_quality_or_better) :foldl(put_in_inv, Inventory:new(math.huge)) Item.create("elona.suitcase", nil, nil, {}, inv) Item.create("elona.wallet", nil, nil, {}, inv) Rand.set_seed() local player = Chara.player() Input.query_inventory(player, "elona.inv_take_strange_scientist", { container = inv }, nil) -- <<<<<<<< shade2/chat.hsp:2033 exitTempInv:mode=mode_main .. end data:add { _type = "elona_sys.dialog", _id = "strange_scientist", nodes = { __start = function() local flag = Sidequest.progress("elona.little_sister") if flag == 0 then return "first" elseif flag > 0 then return "dialog" end return "elona_sys.ignores_you:__start" end, first = { text = "talk.unique.strange_scientist.first", choices = { {"__END__", "ui.more"}, }, on_finish = function() local player = Chara.player() local map = player:current_map() Item.create("elona.little_ball", player.x, player.y, {}, map) Gui.mes("common.something_is_put_on_the_ground") Sidequest.update_journal() Sidequest.set_progress("elona.little_sister", 1) end }, dialog = { text = "talk.unique.strange_scientist.dialog", choices = function() local choices = { {"reward_check", "talk.unique.strange_scientist.choices.reward"}, {"replenish", "talk.unique.strange_scientist.choices.replenish"} } if Chara.find("elona.little_sister", "allies") ~= nil then table.insert(choices, {"turn_over", "talk.unique.strange_scientist.choices.turn_over"}) end table.insert(choices, {"__END__", "ui.bye"}) return choices end }, reward_check = function() if can_receive_reward() then return "reward_pick" end return "reward_not_enough" end, reward_pick = { text = { "talk.unique.strange_scientist.reward.dialog", pick_reward, "talk.unique.strange_scientist.reward.find", }, }, reward_not_enough = { text = "talk.unique.strange_scientist.reward.not_enough", }, replenish = { text = "talk.unique.strange_scientist.replenish", on_finish = function() local player = Chara.player() local map = player:current_map() Item.create("elona.little_ball", player.x, player.y, {}, map) Gui.mes("common.something_is_put_on_the_ground") end }, turn_over = { on_start = turn_over_little_sister, text = "talk.unique.strange_scientist.turn_over.dialog", choices = { {"__END__", "ui.more"}, } }, } }
412
0.859091
1
0.859091
game-dev
MEDIA
0.96708
game-dev
0.9382
1
0.9382
quiverteam/Engine
51,434
src/utils/hammer/mapsolid.cpp
//========= Copyright 1996-2005, Valve Corporation, All rights reserved. ============// // // Purpose: // //=============================================================================// #include "stdafx.h" #include "Box3D.h" #include "BrushOps.h" #include "GlobalFunctions.h" #include "MapDefs.h" // dvs: For COORD_NOTINIT #include "MapView2D.h" // dvs FIXME: For HitTest2D implementation #include "MapWorld.h" #include "MapSolid.h" #include "Options.h" #include "Render2D.h" #include "Render3D.h" #include "SaveInfo.h" #include "MapDoc.h" #include "MapDisp.h" #include "camera.h" #include "ssolid.h" // memdbgon must be the last include file in a .cpp file!!! #include <tier0/memdbgon.h> IMPLEMENT_MAPCLASS(CMapSolid) #define CENTER_HANDLE_RADIUS 3 int CMapSolid::g_nBadSolidCount = 0; //----------------------------------------------------------------------------- // Purpose: Constructor. Sets this solid's color to a random blue-green color. // Input : Parent0 - The parent of this solid. Typically this is the world. //----------------------------------------------------------------------------- CMapSolid::CMapSolid(CMapClass *Parent0) : m_bValid(FALSE) // well, no faces { m_pParent = Parent0; m_eSolidType = btSolid; m_bIsCordonBrush = false; PickRandomColor(); } //----------------------------------------------------------------------------- // Purpose: Destructor. //----------------------------------------------------------------------------- CMapSolid::~CMapSolid(void) { Faces.SetCount(0); } //----------------------------------------------------------------------------- // Purpose: Adds the plane to the given solid. // Input : pSolid - Solid to which the plane is being added. // p - Plane to add to the solid. // Output : Returns true if the solid is still valid after the addition of the // plane, false if it was entirely behind the plane. //----------------------------------------------------------------------------- bool CMapSolid::AddPlane(const CMapFace *p) { CMapFace NewFace; // // Copy the info from the carving face, including the plane, but not the points. // NewFace.CopyFrom(p, COPY_FACE_PLANE); // // Use texture from our first face - this function adds a plane // from the subtraction brush itself. // const CMapFace *pSolidFace = GetFace(0); NewFace.SetTexture(pSolidFace->texture.texture); NewFace.texture.q2contents = pSolidFace->texture.q2contents; NewFace.texture.q2surface = pSolidFace->texture.q2surface; NewFace.texture.nLightmapScale = pSolidFace->texture.nLightmapScale; // // Set up the texture axes for the new face. // NewFace.InitializeTextureAxes(Options.GetTextureAlignment(), INIT_TEXTURE_ALL | INIT_TEXTURE_FORCE); // // Add the face to the solid and rebuild the solid. // AddFace(&NewFace); CreateFromPlanes(); SetValid(TRUE); PostUpdate(Notify_Changed); RemoveEmptyFaces(); return(GetFaceCount() >= 4); } //----------------------------------------------------------------------------- // Purpose: Carves this solid using another. // Input : Inside - Receives the pieces of this solid that were inside the carver. // Outside - Receives the pieces of this solid that were outside the carver. // pCarver - The solid that is being subtracted from us. //----------------------------------------------------------------------------- bool CMapSolid::Carve(CMapObjectList *pInside, CMapObjectList *pOutside, CMapSolid *pCarver) { int i; CMapSolid *front = NULL; CMapSolid *back = NULL; Vector bmins, bmaxs; Vector carvemins, carvemaxs; GetRender2DBox(bmins, bmaxs); pCarver->GetRender2DBox(carvemins, carvemaxs); // // If this solid doesn't intersect the carving solid at all, add a copy // to the outside list and exit. // for (i=0 ; i<3 ; i++) { if ((bmins[i] >= carvemaxs[i]) || (bmaxs[i] <= carvemins[i])) { if (pOutside != NULL) { CMapSolid *pCopy = (CMapSolid *)Copy(false); pOutside->AddToTail(pCopy); } return(false); } } // // Build a duplicate of this solid to carve from. // CMapSolid CarveFrom; CarveFrom.CopyFrom(this, false); // // Carve the solid by the faces in the carving solid. // for (i = 0; i < pCarver->GetFaceCount(); i++) { const CMapFace *pFace = pCarver->GetFace(i); // // Split the solid by this face, into a front and a back piece. // CarveFrom.ClipByFace(pFace, pOutside != NULL ? &front : NULL, &back); // // If there was a front piece, add it to the outside list. // if ((front != NULL) && (pOutside != NULL)) { pOutside->AddToTail(front); } else { delete front; } // // If there was no back piece, we have found a face the solid is completely in front of. // Per the separating axis theorem, the two solids cannot intersect, so we are done. // if (back == NULL) { return(false); } // // The next clip uses the back piece from this clip to prevent the carve results // from overlapping. // CarveFrom.CopyFrom(back, false); // // Add the back piece of the carved solid to the inside list. // if (pInside != NULL) { pInside->AddToTail(back); } else { delete back; } } return(true); } //----------------------------------------------------------------------------- // Purpose: Clips the given solid by the given face, returning the results. // Input : pSolid - Solid to clip. // fa - Face to use for the clipping operation. // f - Returns the part of the solid that was in front of the clipping // face (in the direction of the face normal). // b - Returns the part of the solid that was in back of the clipping // face (in the opposite direction of the face normal). //----------------------------------------------------------------------------- void CMapSolid::ClipByFace(const CMapFace *fa, CMapSolid **f, CMapSolid **b) { CMapSolid *front = new CMapSolid; CMapSolid *back = new CMapSolid; CMapFace fb; // // Build a back facing version of the clip face by reversing the plane points // and recalculate the plane normal and distance. // fb.CopyFrom(fa); Vector temp = fb.plane.planepts[0]; fb.plane.planepts[0] = fb.plane.planepts[2]; fb.plane.planepts[2] = temp; fb.CalcPlane(); front->CopyFrom(this, false); front->SetParent(NULL); back->CopyFrom(this, false); back->SetParent(NULL); if (!back->AddPlane(fa)) { delete back; back = NULL; } if (!front->AddPlane(&fb)) { delete front; front = NULL; } if (f != NULL) { *f = front; } else { delete front; } if (b != NULL) { *b = back; } else { delete back; } } //----------------------------------------------------------------------------- // Purpose: Returns true if this solid contains a face with the given ID, false if not. // Input : nFaceID - unique face ID to look for. //----------------------------------------------------------------------------- CMapFace *CMapSolid::FindFaceID(int nFaceID) { int nFaceCount = GetFaceCount(); for (int nFace = 0; nFace < nFaceCount; nFace++) { CMapFace *pFace = GetFace(nFace); if (pFace->GetFaceID() == nFaceID) { return(pFace); } } return(NULL); } //----------------------------------------------------------------------------- // Purpose: // Input : pWorld - //----------------------------------------------------------------------------- void CMapSolid::GenerateNewFaceIDs(CMapWorld *pWorld) { int nFaceCount = GetFaceCount(); for (int nFace = 0; nFace < nFaceCount; nFace++) { CMapFace *pFace = GetFace(nFace); pFace->SetFaceID(pWorld->FaceID_GetNext()); } } //----------------------------------------------------------------------------- // Purpose: Allows the solid to generate new face IDs before being added to the // world because of a clone. // Input : pClone - The clone of this object that is being added to the world. // pWorld - The world that the clone is being added to. // OriginalList - The list of objects that were cloned. // NewList - The list of clones. //----------------------------------------------------------------------------- void CMapSolid::OnPreClone(CMapClass *pClone, CMapWorld *pWorld, const CMapObjectList &OriginalList, CMapObjectList &NewList) { ((CMapSolid *)pClone)->GenerateNewFaceIDs(pWorld); } //----------------------------------------------------------------------------- // Purpose: Notifies the object that a copy of it is being pasted from the // clipboard before the copy is added to the world. // Input : pCopy - The copy of this object that is being added to the world. // pSourceWorld - The world that the originals were in. // pDestWorld - The world that the copies are being added to. // OriginalList - The list of original objects that were copied. // NewList - The list of copied. //----------------------------------------------------------------------------- void CMapSolid::OnPrePaste(CMapClass *pCopy, CMapWorld *pSourceWorld, CMapWorld *pDestWorld, const CMapObjectList &OriginalList, CMapObjectList &NewList) { ((CMapSolid *)pCopy)->GenerateNewFaceIDs(pDestWorld); } //----------------------------------------------------------------------------- // Purpose: to split the solid by the given plane into frontside and backside // solids; memory is allocated in the function for the solids; // solids are only generated for (pointers to) CMapSolid pointers that // exist -- if a pointer is NULL that sidedness is ignored; the // function returns whether or not an actual split happened (TRUE/FALSE) // Input: pPlane - the plane to split the solid with // pFront - the front sided solid (if any) // pBack - the back sided solid (if any) // Output: 0 - on front side // 1 - on back side // 2 - split //----------------------------------------------------------------------------- int CMapSolid::Split( PLANE *pPlane, CMapSolid **pFront, CMapSolid **pBack ) { const float SPLIT_DIST_EPSILON = 0.001f; CMapSolid *pFrontSolid = NULL; CMapSolid *pBackSolid = NULL; CMapFace face; // // The newly added face should get its texture from face zero of the solid. // CMapFace *pFirstFace = GetFace(0); if (pFirstFace != NULL) { face.SetTexture(pFirstFace->GetTexture()); } // // check for plane intersection with solid // int frontCount = 0; int backCount = 0; int faceCount = GetFaceCount(); for( int i = 0; i < faceCount; i++ ) { CMapFace *pFace = GetFace( i ); for( int j = 0; j < pFace->nPoints; j++ ) { float dist = DotProduct( pFace->Points[j], pPlane->normal ) - pPlane->dist; if( dist > SPLIT_DIST_EPSILON ) { frontCount++; } else if( dist < -SPLIT_DIST_EPSILON ) { backCount++; } } } // // If we're all on one side of the splitting plane, copy ourselves into the appropriate // destination solid. // if ((frontCount == 0) || (backCount == 0)) { CMapSolid **pReturn; if (frontCount == 0) { pReturn = pBack; } else { pReturn = pFront; } if (pReturn == NULL) { return -1; } // // The returned solid is just a copy of ourselves. // CMapSolid *pReturnSolid = new CMapSolid; pReturnSolid->CopyFrom(this, false); pReturnSolid->SetParent(NULL); pReturnSolid->SetTemporary(TRUE); // // Rebuild the solid because mappers are accustomed to using the clipper tool as a way of // verifying that geometry is valid. // if (pReturnSolid->CreateFromPlanes( CREATE_FROM_PLANES_CLIPPING )) { // Initialize the texture axes only of the newly created faces. Leave the others alone. pReturnSolid->InitializeTextureAxes(Options.GetTextureAlignment(), INIT_TEXTURE_ALL); pReturnSolid->PostUpdate(Notify_Changed); } *pReturn = pReturnSolid; return 1; } // // split the solid and create the "front" solid // if( pFront ) { // // copy the original solid info // pFrontSolid = new CMapSolid; pFrontSolid->CopyFrom(this, false); pFrontSolid->SetParent(NULL); pFrontSolid->SetTemporary( TRUE ); face.plane.normal = pPlane->normal; VectorNegate( face.plane.normal ); face.plane.dist = -pPlane->dist; pFrontSolid->AddFace( &face ); // // The new face doesn't have plane points, only a normal and a distance, so we tell CreateFromPlanes // to generate new plane points for us after creation. // if (pFrontSolid->CreateFromPlanes(CREATE_BUILD_PLANE_POINTS | CREATE_FROM_PLANES_CLIPPING)) { // Initialize the texture axes only of the newly created faces. Leave the others alone. pFrontSolid->InitializeTextureAxes( Options.GetTextureAlignment(), INIT_TEXTURE_ALL ); pFrontSolid->PostUpdate(Notify_Clipped_Intermediate); *pFront = pFrontSolid; } } // // split the solid and create the "back" solid // if( pBack ) { // // copy the original solid info // pBackSolid = new CMapSolid; pBackSolid->CopyFrom(this, false); pBackSolid->SetParent(NULL); pBackSolid->SetTemporary( TRUE ); face.plane.normal = pPlane->normal; face.plane.dist = pPlane->dist; pBackSolid->AddFace( &face ); // // The new face doesn't have plane points, only a normal and a distance, so we tell CreateFromPlanes // to generate new plane points for us after creation. // if (pBackSolid->CreateFromPlanes(CREATE_BUILD_PLANE_POINTS | CREATE_FROM_PLANES_CLIPPING)) { // Initialize the texture axes only of the newly created faces. Leave the others alone. pBackSolid->InitializeTextureAxes( Options.GetTextureAlignment(), INIT_TEXTURE_ALL ); pBackSolid->PostUpdate(Notify_Clipped_Intermediate); *pBack = pBackSolid; } } return 2; } //----------------------------------------------------------------------------- // Purpose: Returns the index (you could use it with GetFace) or -1 if the face doesn't exist in this solid. //----------------------------------------------------------------------------- int CMapSolid::GetFaceIndex( CMapFace *pFace ) { for ( int i=0; i < Faces.GetCount(); i++ ) { if ( pFace == &Faces[i] ) return i; } return -1; } //----------------------------------------------------------------------------- // Purpose: Adds a face to this solid. // Input : pFace - The face to add. The face is copied into this solid's face // array, so it can be safely freed when AddFace returns. //----------------------------------------------------------------------------- void CMapSolid::AddFace(CMapFace *pFace) { int nFaces = Faces.GetCount(); Faces.SetCount(nFaces + 1); CMapFace *pNewFace = &Faces[nFaces]; pNewFace->CopyFrom(pFace, COPY_FACE_POINTS); pNewFace->SetRenderColor(r, g, b); pNewFace->SetCordonFace( m_bIsCordonBrush ); pNewFace->SetParent(this); } //----------------------------------------------------------------------------- // Purpose: // Output : CMapClass //----------------------------------------------------------------------------- CMapClass *CMapSolid::Copy(bool bUpdateDependencies) { CMapSolid *pNew = new CMapSolid; pNew->CopyFrom(this, bUpdateDependencies); return pNew; } //----------------------------------------------------------------------------- // Purpose: Turns this solid into a duplicate of the given solid. // Input : pobj - Object to copy, must be a CMapSolid. // Output : Returns a pointer to this object. //----------------------------------------------------------------------------- CMapClass *CMapSolid::CopyFrom(CMapClass *pobj, bool bUpdateDependencies) { Assert(pobj->IsMapClass(MAPCLASS_TYPE(CMapSolid))); CMapSolid *pFrom = (CMapSolid *)pobj; CMapClass::CopyFrom(pobj, bUpdateDependencies); m_eSolidType = pFrom->GetHL1SolidType(); m_bIsCordonBrush = pFrom->m_bIsCordonBrush; int nFaces = pFrom->Faces.GetCount(); Faces.SetCount(nFaces); // copy faces CMapFace *pFromFace; CMapFace *pToFace; for (int i = nFaces - 1; i >= 0; i--) { pToFace = &Faces[i]; pFromFace = &pFrom->Faces[i]; if (!pToFace) { continue; } pToFace->SetParent(this); pToFace->CopyFrom(pFromFace, COPY_FACE_POINTS, bUpdateDependencies); Assert(pToFace->GetPointCount() != 0); } return(this); } //----------------------------------------------------------------------------- // Purpose: Walks the faces of a solid for debugging. //----------------------------------------------------------------------------- #ifdef _DEBUG #pragma warning (disable:4189) void CMapSolid::DebugSolid(void) { int nFaceCount = Faces.GetCount(); for (int nFace = 0; nFace < nFaceCount; nFace++) { CMapFace *pFace = GetFace(nFace); } } #pragma warning (default:4189) #endif // _DEBUG //----------------------------------------------------------------------------- // Purpose: // Input : iIndex - //----------------------------------------------------------------------------- void CMapSolid::DeleteFace(int iIndex) { // shifts 'em down. int nFaces = Faces.GetCount(); for(int j = iIndex; j < nFaces-1; j++) { Faces[j].CopyFrom(&Faces[j+1]); } Faces.SetCount(nFaces-1); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- const char* CMapSolid::GetDescription(void) { static char szBuf[128]; sprintf(szBuf, "solid with %d faces", Faces.GetCount()); return szBuf; } //----------------------------------------------------------------------------- // Purpose: Calculates this solid's axis aligned bounding box. // Input : bFullUpdate - Whether to evaluate all children when calculating. //----------------------------------------------------------------------------- void CMapSolid::CalcBounds(BOOL bFullUpdate) { CMapClass::CalcBounds(bFullUpdate); // // Update mins/maxes based on our faces. // int nFaces = Faces.GetCount(); for( int i = 0; i < nFaces; i++ ) { // check for valid face if (!Faces[i].Points) continue; // // Get the 2d render bounds of this face and update the solid. 2D render bounds // can be different from 3D culling bounds because the 2D bounds do not consider // displacement faces. // Vector mins, maxs; bool result = Faces[i].GetRender2DBox( mins, maxs ); if( result ) { m_Render2DBox.UpdateBounds( mins, maxs ); } // // Get the culling bounds and update the solid // result = Faces[i].GetCullBox( mins, maxs ); if( result ) { m_CullBox.UpdateBounds( mins, maxs ); } } m_Render2DBox.GetBoundsCenter(m_Origin); } //----------------------------------------------------------------------------- // Purpose: // Input : t - //----------------------------------------------------------------------------- void CMapSolid::DoTransform(const VMatrix &matrix) { // get all points, transform them int nFaces = Faces.GetCount(); for (int i = 0; i < nFaces; i++) { Faces[i].DoTransform( matrix ); } BaseClass::DoTransform(matrix); } //----------------------------------------------------------------------------- // Purpose: Sets the render color of all of our faces when our render color is set. //----------------------------------------------------------------------------- void CMapSolid::SetRenderColor(color32 rgbColor) { CMapClass::SetRenderColor(rgbColor); int nFaces = Faces.GetCount(); for (int i = 0; i < nFaces; i++) { Faces[i].SetRenderColor(rgbColor); } } //----------------------------------------------------------------------------- // Purpose: Sets the render color of all of our faces when our render color is set. //----------------------------------------------------------------------------- void CMapSolid::SetRenderColor(unsigned char uchRed, unsigned char uchGreen, unsigned char uchBlue) { CMapClass::SetRenderColor(uchRed, uchGreen, uchBlue); int nFaces = Faces.GetCount(); for (int i = 0; i < nFaces; i++) { Faces[i].SetRenderColor(uchRed, uchGreen, uchBlue); } } //----------------------------------------------------------------------------- // Purpose: // Input : // Output : size_t //----------------------------------------------------------------------------- size_t CMapSolid::GetSize(void) { size_t size = CMapClass::GetSize(); size += sizeof *this; int nFaces = Faces.GetCount(); for( int i = 0; i < nFaces; i++ ) { size += Faces[i].GetDataSize(); } return size; } //----------------------------------------------------------------------------- // Purpose: Sets the texture for a given face. // Input : pszTex - Texture name. // iFace - Index of face for which to set texture. //----------------------------------------------------------------------------- void CMapSolid::SetTexture(LPCTSTR pszTex, int iFace) { if(iFace == -1) { int nFaces = Faces.GetCount(); for(int i = 0 ; i < nFaces; i++) { Faces[i].SetTexture(pszTex); } } else { Faces[iFace].SetTexture(pszTex); } } //----------------------------------------------------------------------------- // Purpose: Returns the texture name of a given face. // Input : iFace - Index of face. If -1, returns the texture of face 0. // Output : Returns the texture name. //----------------------------------------------------------------------------- LPCTSTR CMapSolid::GetTexture(int iFace) { return Faces[iFace == -1 ? 0 : iFace].texture.texture; } //----------------------------------------------------------------------------- // Purpose: Creates the solid using the plane information from the solid's faces. // // ASSUMPTIONS: This solid's faces are assumed to have valid plane points. // // Input : dwFlags - Can be any or none of the following flags: // // CREATE_BUILD_PLANE_POINTS - if this flag is set, the 3-point // definition of each face plane will be regenerated based // on the face points after the solid is generated. // // Output : Returns TRUE if the solid is valid, FALSE if not. // // dvs: this should really use the public API of CMapSolid to add faces so that // parentage and render color are set automatically. //----------------------------------------------------------------------------- int CMapSolid::CreateFromPlanes( DWORD dwFlags ) { int i, j, k; BOOL useplane[MAPSOLID_MAX_FACES]; m_Render2DBox.SetBounds(Vector(COORD_NOTINIT, COORD_NOTINIT, COORD_NOTINIT), Vector(-COORD_NOTINIT, -COORD_NOTINIT, -COORD_NOTINIT)); m_bValid = TRUE; // // Free all points from all faces and assign parentage. // int nFaces = GetFaceCount(); for (i = 0; i < nFaces; i++) { CMapFace *pFace = GetFace(i); pFace->AllocatePoints(0); pFace->SetParent(this); pFace->SetRenderColor(r, g, b); } memset(useplane, 0, sizeof useplane); // // For every face that is not set to be ignored, check the plane and make sure // it is unique. We mark each plane that we intend to keep with a TRUE in the // 'useplane' array. // for (i = 0; i < nFaces; i++) { CMapFace *pFace = GetFace(i); PLANE *f = &pFace->plane; // // Don't use this plane if it has a zero-length normal. // if (VectorCompare(f->normal, vec3_origin)) { useplane[i] = FALSE; continue; } // // If the plane duplicates another plane, don't use it (assume it is a brush // being edited that will be fixed). // useplane[i] = TRUE; for (j = 0; j < i; j++) { CMapFace *pFaceCheck = GetFace(j); Vector& f1 = f->normal; Vector& f2 = pFaceCheck->plane.normal; // // Check for duplicate plane within some tolerance. // if ((DotProduct(f1, f2) > 0.999) && (fabs(f->dist - pFaceCheck->plane.dist) < 0.01)) { useplane[j] = FALSE; break; } } } // // Now we have a set of planes, indicated by TRUE values in the 'useplanes' array, // from which we will build a solid. // BOOL bGotFaces = FALSE; for (i = 0; i < nFaces; i++) { CMapFace *pFace = GetFace(i); if (!useplane[i]) continue; // // Create a huge winding from this face's plane, then clip it by all other // face planes. // winding_t *w = CreateWindingFromPlane(&pFace->plane); for (j = 0; j < nFaces && w; j++) { CMapFace *pFaceClip = GetFace(j); // // Flip the plane, because we want to keep the back side // if (j != i) { PLANE plane; VectorSubtract(vec3_origin, pFaceClip->plane.normal, plane.normal); plane.dist = -pFaceClip->plane.dist; w = ClipWinding(w, &plane); } } // // If we still have a winding after all that clipping, build a face from // the winding. // if (w != NULL) { // // Round all points in the winding that are within ROUND_VERTEX_EPSILON of // integer values. // for (j = 0; j < w->numpoints; j++) { for (k = 0; k < 3; k++) { float v = w->p[j][k]; float v1 = rint(v); if ((v != v1) && (fabs(v - v1) < ROUND_VERTEX_EPSILON)) { w->p[j][k] = v1; } } } // // The above rounding process may have created duplicate points. Eliminate them. // RemoveDuplicateWindingPoints(w, MIN_EDGE_LENGTH_EPSILON); bGotFaces = TRUE; // // Create a face from this winding. Leave the face plane // alone because we are still in the process of building our solid. // if ( dwFlags & CREATE_FROM_PLANES_CLIPPING ) { pFace->CreateFace( w, CREATE_FACE_PRESERVE_PLANE | CREATE_FACE_CLIPPING ); } else { pFace->CreateFace(w, CREATE_FACE_PRESERVE_PLANE); } // // Done with the winding, we can free it now. // FreeWinding(w); } } if (!bGotFaces) { m_bValid = FALSE; m_Render2DBox.SetBounds(vec3_origin, vec3_origin); } else { // // Remove faces that don't contribute to this solid. // int nFace = GetFaceCount(); while (nFace > 0) { nFace--; CMapFace *pFace = GetFace(nFace); if ((!useplane[nFace]) || (pFace->GetPointCount() == 0)) { DeleteFace(nFace); memcpy(useplane + nFace, useplane + nFace + 1, MAPSOLID_MAX_FACES - (nFace + 1)); } } } // // Now that we have built the faces from the planes that we were given, // calculate the plane normals, distances, and texture coordinates. // nFaces = GetFaceCount(); for (i = 0; i < nFaces; i++) { CMapFace *pFace = GetFace(i); if (dwFlags & CREATE_BUILD_PLANE_POINTS) { pFace->CalcPlaneFromFacePoints(); } else { pFace->CalcPlane(); } pFace->CalcTextureCoords(); // // Make sure the face is valid. // if (!pFace->CheckFace()) { m_bValid = FALSE; } } // // remove faces that do not contribute -- not just "unused or ignored" faces // int faceCount = Faces.GetCount(); for( i = 0; i < faceCount; i++ ) { if( Faces[i].nPoints == 0 ) { DeleteFace( i ); i--; faceCount--; } } return(m_bValid ? TRUE : FALSE); } //----------------------------------------------------------------------------- // Purpose: Initializes the texture axes for all faces in the solid. // Input : eAlignment - See CMapFace::InitializeTextureAxes // dwFlags - See CMapFace::InitializeTextureAxes //----------------------------------------------------------------------------- void CMapSolid::InitializeTextureAxes(TextureAlignment_t eAlignment, DWORD dwFlags) { int nFaces = Faces.GetCount(); for (int i = 0; i < nFaces; i++) { Faces[i].InitializeTextureAxes(eAlignment, dwFlags); } } //----------------------------------------------------------------------------- // Purpose: // Input : *pLoadInfo - // *pSolid - // Output : ChunkFileResult_t //----------------------------------------------------------------------------- ChunkFileResult_t CMapSolid::LoadSideCallback(CChunkFile *pFile, CMapSolid *pSolid) { ChunkFileResult_t eResult = ChunkFile_Ok; // // this is hear in place of the AddFace -- may want to handle this better later!!! // int faceCount = pSolid->Faces.GetCount(); pSolid->Faces.SetCount( faceCount + 1 ); CMapFace *pFace = &pSolid->Faces[faceCount]; eResult = pFace->LoadVMF(pFile); if (eResult == ChunkFile_Ok) { pFace->SetRenderColor( pSolid->r, pSolid->g, pSolid->b ); pFace->SetParent( pSolid ); } else { // UNDONE: need a better solution for user errors. AfxMessageBox("Out of memory loading solid."); eResult = ChunkFile_OutOfMemory; } return(eResult); } //----------------------------------------------------------------------------- // Purpose: // Input : pFile - // pData - // Output : ChunkFileResult_t //----------------------------------------------------------------------------- ChunkFileResult_t CMapSolid::LoadVMF(CChunkFile *pFile, bool &bValid) { // // Set up handlers for the subchunks that we are interested in. // CChunkHandlerMap Handlers; Handlers.AddHandler("side", (ChunkHandler_t)LoadSideCallback, this); Handlers.AddHandler("editor", (ChunkHandler_t)LoadEditorCallback, this); pFile->PushHandlers(&Handlers); ChunkFileResult_t eResult = pFile->ReadChunk((KeyHandler_t)LoadEditorKeyCallback, this); pFile->PopHandlers(); bValid = false; if (eResult == ChunkFile_Ok) { // // Create the solid using the planes that were read from the MAP file. // if (CreateFromPlanes()) { bValid = true; CalcBounds(); // // Set solid type based on texture name. // m_eSolidType = HL1SolidTypeFromTextureName(Faces[0].texture.texture); // // create all of the displacement surfaces for faces with the displacement property // int faceCount = GetFaceCount(); for( int i = 0; i < faceCount; i++ ) { CMapFace *pFace = GetFace( i ); if( !pFace->HasDisp() ) continue; EditDispHandle_t handle = pFace->GetDisp(); CMapDisp *pMapDisp = EditDispMgr()->GetDisp( handle ); pMapDisp->InitDispSurfaceData( pFace, false ); pMapDisp->Create(); pMapDisp->PostLoad(); } // There once was a bug that caused black solids. Fix it here. if ((r == 0) && (g == 0) || (b == 0)) { PickRandomColor(); } } else { g_nBadSolidCount++; } } return(eResult); } //----------------------------------------------------------------------------- // Purpose: Picks a random shade of blue/green for this solid. //----------------------------------------------------------------------------- void CMapSolid::PickRandomColor() { SetRenderColor(0, 100 + (random() % 156), 100 + (random() % 156)); } //----------------------------------------------------------------------------- // Purpose: Called before loading a map file. //----------------------------------------------------------------------------- void CMapSolid::PreloadWorld(void) { g_nBadSolidCount = 0; } //----------------------------------------------------------------------------- // Purpose: Returns the number of solids that could not be loaded due to errors // in the VMF file. This should only occur after the first load of an // old RMF file. //----------------------------------------------------------------------------- int CMapSolid::GetBadSolidCount(void) { return(g_nBadSolidCount); } //----------------------------------------------------------------------------- // Purpose: Called after this object is added to the world. // // NOTE: This function is NOT called during serialization. Use PostloadWorld // to do similar bookkeeping after map load. // // Input : pWorld - The world that we have been added to. //----------------------------------------------------------------------------- void CMapSolid::OnAddToWorld(CMapWorld *pWorld) { CMapClass::OnAddToWorld(pWorld); // // First, the common case: all our face IDs are zero. Assign new IDs to all faces // with zero IDs. Add unhandled faces to a list. Those we will need to check against // the world for uniqueness. // CMapFaceList CheckList; int nFaceCount = GetFaceCount(); for (int i = 0; i < nFaceCount; i++) { CMapFace *pFace = GetFace(i); if (pFace->GetFaceID() == 0) { pFace->SetFaceID(pWorld->FaceID_GetNext()); } else { CheckList.AddToTail(pFace); } } if (CheckList.Count() > 0) { // // The less common case: make sure all our face IDs are unique in this world. // We do it here instead of in CMapFace in order to save world tree traversals. // EnumChildrenPos_t pos; CMapClass *pChild = pWorld->GetFirstDescendent(pos); while (pChild != NULL) { CMapSolid *pSolid = dynamic_cast<CMapSolid *>(pChild); if ( pSolid && pSolid != this ) { CUtlRBTree<int,int> faceIDs; SetDefLessFunc( faceIDs ); int nFaceCount = GetFaceCount(); for (int nFace = 0; nFace < nFaceCount; nFace++) { CMapFace *pFace = GetFace(nFace); faceIDs.Insert( pFace->GetFaceID() ); } for (int i = CheckList.Count() - 1; i >= 0; i--) { CMapFace *pFace = CheckList.Element(i); // If this face ID is not unique, assign it a new unique face ID // and remove it from our list. if ( faceIDs.Find( pFace->GetFaceID() ) != faceIDs.InvalidIndex() ) { pFace->SetFaceID(pWorld->FaceID_GetNext()); CheckList.FastRemove(i); } } if (CheckList.Count() <= 0) { // We've handled all the faces in our list, early out. break; } } pChild = pWorld->GetNextDescendent(pos); } } // // Notify all faces that we are being added to the world. // for (int i = 0; i < nFaceCount; i++) { CMapFace *pFace = GetFace(i); pFace->OnAddToWorld(pWorld); } } //----------------------------------------------------------------------------- // Purpose: Called after the entire map has been loaded. This allows the object // to perform any linking with other map objects or to do other operations // that require all world objects to be present. // Input : pWorld - The world that we are in. //----------------------------------------------------------------------------- void CMapSolid::PostloadWorld(CMapWorld *pWorld) { CMapClass::PostloadWorld(pWorld); // // Make sure all our faces have nonzero IDs. They might if the map was created // before unique IDs were added. // int nFaces = GetFaceCount(); for (int i = 0; i < nFaces; i++) { CMapFace *pFace = GetFace(i); if (pFace->GetFaceID() == 0) { pFace->SetFaceID(pWorld->FaceID_GetNext()); } } } //----------------------------------------------------------------------------- // Purpose: // Input : eSelectMode - // Output : CMapClass //----------------------------------------------------------------------------- CMapClass *CMapSolid::PrepareSelection(SelectMode_t eSelectMode) { // // If we have a parent who is not the world object, consider whether we should // select it instead. // if ((eSelectMode != selectSolids) && (m_pParent != NULL) && !IsWorldObject(m_pParent) ) { // // If we are in group selection mode or our parent is an entity, select our // parent. // if ( (eSelectMode == selectGroups) || (dynamic_cast <CMapEntity *>(m_pParent) != NULL)) { return GetParent()->PrepareSelection(eSelectMode); } } return this; } //----------------------------------------------------------------------------- // Purpose: Called just after this object has been removed from the world so // that it can unlink itself from other objects in the world. // Input : pWorld - The world that we were just removed from. // bNotifyChildren - Whether we should forward notification to our children. //----------------------------------------------------------------------------- void CMapSolid::OnRemoveFromWorld(CMapWorld *pWorld, bool bNotifyChildren) { CMapClass::OnRemoveFromWorld(pWorld, bNotifyChildren); // // Notify all faces that we are being removed from the world. // int nFaces = GetFaceCount(); for (int i = 0; i < nFaces; i++) { CMapFace *pFace = GetFace(i); pFace->OnRemoveFromWorld(); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CMapSolid::RemoveEmptyFaces(void) { int nFaces = GetFaceCount(); for (int i = 0; i < nFaces; i++) { // // If this face has no points, delete it. // const CMapFace *pFace = GetFace(i); if (pFace->Points == NULL) { DeleteFace(i); i--; nFaces--; } } if (nFaces >= 4) { // dvs: test to verify that the SetFaceCount below is unnecessary int nTest = GetFaceCount(); Assert(nTest == nFaces); SetFaceCount(nFaces); } } //----------------------------------------------------------------------------- // for sorting //----------------------------------------------------------------------------- bool CMapSolid::ShouldRenderLast() { for (int nFace = 0; nFace < GetFaceCount(); nFace++) { CMapFace *pFace = GetFace(nFace); if (pFace->ShouldRenderLast()) return true; } return false; } void CMapSolid::AddShadowingTriangles( CUtlVector<Vector> &tri_list ) { for (int nFace = 0; nFace < GetFaceCount(); nFace++) { CMapFace *pFace = GetFace(nFace); pFace->AddShadowingTriangles( tri_list ); if( pFace->HasDisp() ) { EditDispHandle_t handle = pFace->GetDisp(); CMapDisp *pMapDisp = EditDispMgr()->GetDisp( handle ); pMapDisp->AddShadowingTriangles( tri_list ); } } } //----------------------------------------------------------------------------- // Purpose: Renders the solid using the default render mode. If the solid is // currently selected, it will be rendered with a yellow wireframe // in a second pass. // Input : pRender - Rendering interface. //----------------------------------------------------------------------------- void CMapSolid::Render3D(CRender3D *pRender) { // // determine whether or not this is a displacement solid - i.e. one of the faces // on this solid is displaced // CMapDoc *pDoc = CMapDoc::GetActiveMapDoc(); if( !pDoc ) return; bool bMaskFaces = pDoc->IsDispSolidDrawMask() && HasDisp(); // // Determine whether we need to render in one or two passes. If we are selected, // and rendering in flat or textured mode, we need to render using two passes. // int nPasses = 1; int iStartPass = 1; SelectionState_t eSolidSelectionState = GetSelectionState(); EditorRenderMode_t eDefaultRenderMode = pRender->GetDefaultRenderMode(); if ((eSolidSelectionState != SELECT_NONE) && (eDefaultRenderMode != RENDER_MODE_WIREFRAME)) { nPasses = 2; } if ( (eSolidSelectionState == SELECT_MODIFY) ) { nPasses = 2; iStartPass = 2; } for (int nPass = iStartPass; nPass <= nPasses; nPass++) { // // Render the second pass in wireframe. // if (nPass == 1) { pRender->PushRenderMode(RENDER_MODE_CURRENT); } else { pRender->PushRenderMode(RENDER_MODE_WIREFRAME); } for (int nFace = 0; nFace < GetFaceCount(); nFace++) { CMapFace *pFace = GetFace(nFace); // only render displaced faces on a displaced solid when the displacement // solid render mask is set if( bMaskFaces && !pFace->HasDisp() ) continue; if( pRender->IsInLightingPreview() ) { if( nPass == 1 ) { if( pFace->GetSelectionState() != SELECT_NONE ) { pRender->BeginRenderHitTarget(this, nFace); pFace->Render3D(pRender); pRender->EndRenderHitTarget(); } } else { pFace->Render3D(pRender); } } else { pRender->BeginRenderHitTarget(this, nFace); pFace->Render3D(pRender); pRender->EndRenderHitTarget(); } } pRender->PopRenderMode(); } } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- bool CMapSolid::HasDisp( void ) { for( int ndxFace = 0; ndxFace < GetFaceCount(); ndxFace++ ) { CMapFace *pFace = GetFace( ndxFace ); if( pFace->HasDisp() ) return true; } return false; } //----------------------------------------------------------------------------- // Purpose: Returns a solid type for the given texture name. // Input : pszTexture - //----------------------------------------------------------------------------- HL1_SolidType_t CMapSolid::HL1SolidTypeFromTextureName(const char *pszTexture) { HL1_SolidType_t eSolidType; if (pszTexture[0] == '*') { if (!strncmp(pszTexture + 1, "slime", 5)) { eSolidType = btSlime; } else if (!strncmp(pszTexture + 1, "lava", 4)) { eSolidType = btLava; } else { eSolidType = btWater; } } else { eSolidType = btSolid; } return(eSolidType); } //----------------------------------------------------------------------------- // Purpose: // Input : *pFile - // Output : ChunkFileResult_t //----------------------------------------------------------------------------- ChunkFileResult_t CMapSolid::SaveVMF(CChunkFile *pFile, CSaveInfo *pSaveInfo) { // // Check rules before saving this object. // if (!pSaveInfo->ShouldSaveObject(this)) { return(ChunkFile_Ok); } ChunkFileResult_t eResult = ChunkFile_Ok; // // If we are hidden, place this object inside of a hidden chunk. // if (!IsVisible()) { eResult = pFile->BeginChunk("hidden"); } // // Begin the solid chunk. // if (eResult == ChunkFile_Ok) { eResult = pFile->BeginChunk("solid"); } if (eResult == ChunkFile_Ok) { // // Save the solid's ID. // if (eResult == ChunkFile_Ok) { eResult = pFile->WriteKeyValueInt("id", GetID()); } // // Save all the brush faces. // int nFaceCount = GetFaceCount(); for (int nFace = 0; nFace < nFaceCount; nFace++) { CMapFace *pFace = GetFace(nFace); eResult = pFace->SaveVMF(pFile, pSaveInfo); if (eResult != ChunkFile_Ok) { break; } } // // Save our base class' information within our chunk. // if (eResult == ChunkFile_Ok) { eResult = CMapClass::SaveVMF(pFile, pSaveInfo); } if (eResult == ChunkFile_Ok) { eResult = pFile->EndChunk(); } } // // End the hidden chunk if we began it. // if (!IsVisible()) { eResult = pFile->EndChunk(); } return(eResult); } bool CMapSolid::ShouldAppearInLightingPreview(void) { return true; } bool CMapSolid::ShouldAppearInRaytracedLightingPreview(void) { return true; } //----------------------------------------------------------------------------- // Purpose: // Input : *pFile - // Output : ChunkFileResult_t //----------------------------------------------------------------------------- ChunkFileResult_t CMapSolid::SaveEditorData(CChunkFile *pFile) { if (m_bIsCordonBrush) { return(pFile->WriteKeyValueBool("cordonsolid", true)); } return(ChunkFile_Ok); } //----------------------------------------------------------------------------- // Purpose: Sets whether this brush was created by the cordon tool. Brushes that // were created by the cordon tool are not loaded. // Input : bSet - true to set, false to clear. //----------------------------------------------------------------------------- void CMapSolid::SetCordonBrush(bool bSet) { m_bIsCordonBrush = bSet; for ( int i = 0; i < GetFaceCount(); i++ ) { CMapFace *pFace = GetFace( i ); pFace->SetCordonFace( bSet ); } } //----------------------------------------------------------------------------- // Purpose: Subtracts one solid from another. // Input : pSubtraction - Solid (or group of solids) to subtract with. // pOther - Solid (or group of solids) to subtract from. // pSubParent - Receives the results of the subtraction as children. // Output : Returns true if the objects intersected (subtraction was performed), // false if the objects did not intersect (no subtraction was performed). //----------------------------------------------------------------------------- bool CMapSolid::Subtract(CMapObjectList *pInside, CMapObjectList *pOutside, CMapClass *pSubtractWith) { // // Build a list of solids to subtract with. // CMapObjectList SubList; if (pSubtractWith->IsMapClass(MAPCLASS_TYPE(CMapSolid))) { SubList.AddToTail(pSubtractWith); } EnumChildrenPos_t pos; CMapClass *pChild = pSubtractWith->GetFirstDescendent(pos); while (pChild != NULL) { CMapSolid *pSolid = dynamic_cast <CMapSolid *> (pChild); if (pSolid != NULL) { SubList.AddToTail(pSolid); } pChild = pSubtractWith->GetNextDescendent(pos); } // // For every solid that we are subtracting with... // bool bIntersected = false; FOR_EACH_OBJ( SubList, p ) { CMapSolid *pCarver = (CMapSolid *)SubList.Element(p); // // Subtract the 'with' solid from the 'from' solid, and place the // results in the carve_in and carve_out lists. // CMapObjectList carve_in; CMapObjectList carve_out; CMapObjectList *pCarveIn = NULL; CMapObjectList *pCarveOut = NULL; if (pInside != NULL) { pCarveIn = &carve_in; } if (pOutside != NULL) { pCarveOut = &carve_out; } bIntersected |= Carve(pCarveIn, pCarveOut, pCarver); if (pInside != NULL) { pInside->AddVectorToTail(carve_in); carve_in.RemoveAll(); } if (pOutside != NULL) { pOutside->AddVectorToTail(carve_out); carve_out.RemoveAll(); } } return(bIntersected); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- color32 CMapSolid::GetLineColor() { // // If the solid is not selected, determine the appropriate pen color. // if (!IsSelected()) { // // If this is a solid entity, use the entity pen color. // CMapEntity *pEntity = dynamic_cast<CMapEntity *>(GetParent()); if (pEntity != NULL) { GDclass *pClass = pEntity->GetClass(); if (pClass) { return pClass->GetColor(); } else { color32 clr; clr.r = GetRValue(Options.colors.clrEntity); clr.g = GetGValue(Options.colors.clrEntity); clr.b = GetBValue(Options.colors.clrEntity); clr.a = 255; return clr; } } // // Otherwise, use the solid color. // else { if (Options.view2d.bUsegroupcolors) { return GetRenderColor(); } else { color32 clr; clr.r = GetRValue(Options.colors.clrBrush); clr.g = GetGValue(Options.colors.clrBrush); clr.b = GetBValue(Options.colors.clrBrush); clr.a = 255; return clr; } } } // // The solid is selected, use the selected pen color. // else { color32 clr; clr.r = GetRValue(Options.colors.clrSelection); clr.g = GetGValue(Options.colors.clrSelection); clr.b = GetBValue(Options.colors.clrSelection); clr.a = 255; return clr; } } //----------------------------------------------------------------------------- // Purpose: // Input : pRender - //----------------------------------------------------------------------------- void CMapSolid::Render2D(CRender2D *pRender) { Vector vecMins, vecMaxs, vViewNormal; GetRender2DBox(vecMins, vecMaxs); pRender->GetCamera()->GetViewForward( vViewNormal ); Vector2D pt, pt2; pRender->TransformPoint(pt, vecMins); pRender->TransformPoint(pt2, vecMaxs); int sizex = abs(pt2.x-pt.x)+1; int sizey = abs(pt2.y-pt.y)+1; color32 rgbLineColor = GetLineColor(); // check if we should draw handles & vertices bool bIsSmall = sizex < (HANDLE_RADIUS*2) || sizey < (HANDLE_RADIUS*2); bool bIsTiny = sizex < 2 || sizey < 2; bool bDrawHandles = pRender->IsActiveView() && !bIsSmall; bool bDrawVertices = Options.view2d.bDrawVertices && !bIsTiny; pRender->SetDrawColor( rgbLineColor.r, rgbLineColor.g, rgbLineColor.b ); // // Draw center handle if the solid is larger than the handle along either axis. // if ( bDrawHandles ) { // draw center handle as cross pRender->SetHandleStyle( HANDLE_RADIUS, CRender::HANDLE_CROSS ); pRender->SetHandleColor( rgbLineColor.r, rgbLineColor.g, rgbLineColor.b ); pRender->DrawHandle( (vecMins+vecMaxs)/2 ); } if ( bDrawVertices ) { // set handle style for upcoming vertex drawing pRender->SetHandleStyle( 2, CRender::HANDLE_SQUARE ); pRender->SetHandleColor( GetRValue(Options.colors.clrVertex), GetGValue(Options.colors.clrVertex), GetBValue(Options.colors.clrVertex) ); } // is solid projection is too small, draw simple line if ( bIsTiny ) { pRender->DrawLine( vecMins, vecMaxs ); } else { int nFaces = GetFaceCount(); for ( int i = 0; i < nFaces; i++) { CMapFace *pFace = GetFace(i); pFace->Render2D( pRender ); } if ( bDrawVertices ) { bool bPop = pRender->BeginClientSpace(); for ( int i = 0; i < nFaces; i++) { CMapFace *pFace = GetFace(i); pFace->RenderVertices( pRender ); } if ( bPop ) pRender->EndClientSpace(); } } } //----------------------------------------------------------------------------- // Purpose: // Input : pView - // vecPoint - // nHitData - // Output : //----------------------------------------------------------------------------- bool CMapSolid::HitTest2D(CMapView2D *pView, const Vector2D &point, HitInfo_t &HitData) { if (!IsVisible()) return false; // // First check center X. // Vector vecCenter, vecViewPoint; GetBoundsCenter(vecCenter); Vector2D vecClientCenter; pView->WorldToClient(vecClientCenter, vecCenter); pView->GetCamera()->GetViewPoint( vecViewPoint ); HitData.pObject = this; HitData.nDepth = vecViewPoint[pView->axThird]-vecCenter[pView->axThird]; HitData.uData = 0; if (pView->CheckDistance(point, vecClientCenter, HANDLE_RADIUS)) { return true; } else if (!Options.view2d.bSelectbyhandles) { // // See if any edges are within certain distance from the the point. // int iSelUnits = 2; int x1 = point.x - iSelUnits; int x2 = point.x + iSelUnits; int y1 = point.y - iSelUnits; int y2 = point.y + iSelUnits; int nFaces = GetFaceCount(); for (int i = 0; i < nFaces; i++) { CMapFace *pFace = GetFace(i); int nPoints = pFace->nPoints; if (nPoints > 0) { Vector *pPoints = pFace->Points; Vector2D vec1; pView->WorldToClient(vec1, pPoints[0]); for (int j = 1; j < nPoints; j++) { Vector2D vec2; pView->WorldToClient(vec2, pPoints[j]); if (IsLineInside(vec1, vec2, x1, y1, x2, y2)) { return true; } else { vec1 = vec2; } } } } } HitData.pObject = NULL; return false; } bool CMapSolid::SaveDXF(ExportDXFInfo_s *pInfo) { if (pInfo->bVisOnly) { if (!IsVisible()) { return true; } } CSSolid *pStrucSolid = new CSSolid; pStrucSolid->Attach(this); pStrucSolid->Convert( true, true ); pStrucSolid->SerializeDXF(pInfo->fp, pInfo->nObject++); delete pStrucSolid; // Serialize displacements for (int i = 0; i < GetFaceCount(); ++i) { CMapFace *pMapFace = GetFace( i ); if (pMapFace->HasDisp()) { EditDispHandle_t hDisp = pMapFace->GetDisp(); CMapDisp *pDisp = EditDispMgr()->GetDisp( hDisp ); if (!pDisp->SaveDXF( pInfo )) return FALSE; } } return TRUE; } //----------------------------------------------------------------------------- // Called any time this object is modified by Undo or Redo. //----------------------------------------------------------------------------- void CMapSolid::OnUndoRedo() { int nFaces = GetFaceCount(); for (int i = 0; i < nFaces; i++) { CMapFace *pFace = GetFace(i); pFace->OnUndoRedo(); } }
412
0.983811
1
0.983811
game-dev
MEDIA
0.687871
game-dev,graphics-rendering
0.966446
1
0.966446
Jeija/spheretest
40,094
src/script/common/c_content.cpp
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> 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 2.1 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "common/c_content.h" #include "common/c_converter.h" #include "common/c_types.h" #include "nodedef.h" #include "itemdef.h" #include "object_properties.h" #include "cpp_api/s_node.h" #include "lua_api/l_object.h" #include "lua_api/l_item.h" #include "common/c_internal.h" #include "server.h" #include "log.h" #include "tool.h" #include "serverobject.h" #include "porting.h" #include "mg_schematic.h" #include "noise.h" #include <json/json.h> struct EnumString es_TileAnimationType[] = { {TAT_NONE, "none"}, {TAT_VERTICAL_FRAMES, "vertical_frames"}, {0, NULL}, }; /******************************************************************************/ ItemDefinition read_item_definition(lua_State* L,int index, ItemDefinition default_def) { if(index < 0) index = lua_gettop(L) + 1 + index; // Read the item definition ItemDefinition def = default_def; def.type = (ItemType)getenumfield(L, index, "type", es_ItemType, ITEM_NONE); getstringfield(L, index, "name", def.name); getstringfield(L, index, "description", def.description); getstringfield(L, index, "inventory_image", def.inventory_image); getstringfield(L, index, "wield_image", def.wield_image); lua_getfield(L, index, "wield_scale"); if(lua_istable(L, -1)){ def.wield_scale = check_v3f(L, -1); } lua_pop(L, 1); int stack_max = getintfield_default(L, index, "stack_max", def.stack_max); def.stack_max = rangelim(stack_max, 1, U16_MAX); lua_getfield(L, index, "on_use"); def.usable = lua_isfunction(L, -1); lua_pop(L, 1); getboolfield(L, index, "liquids_pointable", def.liquids_pointable); warn_if_field_exists(L, index, "tool_digging_properties", "Deprecated; use tool_capabilities"); lua_getfield(L, index, "tool_capabilities"); if(lua_istable(L, -1)){ def.tool_capabilities = new ToolCapabilities( read_tool_capabilities(L, -1)); } // If name is "" (hand), ensure there are ToolCapabilities // because it will be looked up there whenever any other item has // no ToolCapabilities if(def.name == "" && def.tool_capabilities == NULL){ def.tool_capabilities = new ToolCapabilities(); } lua_getfield(L, index, "groups"); read_groups(L, -1, def.groups); lua_pop(L, 1); lua_getfield(L, index, "sounds"); if(lua_istable(L, -1)){ lua_getfield(L, -1, "place"); read_soundspec(L, -1, def.sound_place); lua_pop(L, 1); lua_getfield(L, -1, "place_failed"); read_soundspec(L, -1, def.sound_place_failed); lua_pop(L, 1); } lua_pop(L, 1); def.range = getfloatfield_default(L, index, "range", def.range); // Client shall immediately place this node when player places the item. // Server will update the precise end result a moment later. // "" = no prediction getstringfield(L, index, "node_placement_prediction", def.node_placement_prediction); return def; } /******************************************************************************/ void read_object_properties(lua_State *L, int index, ObjectProperties *prop) { if(index < 0) index = lua_gettop(L) + 1 + index; if(!lua_istable(L, index)) return; prop->hp_max = getintfield_default(L, -1, "hp_max", 10); getboolfield(L, -1, "physical", prop->physical); getboolfield(L, -1, "collide_with_objects", prop->collideWithObjects); getfloatfield(L, -1, "weight", prop->weight); lua_getfield(L, -1, "collisionbox"); if(lua_istable(L, -1)) prop->collisionbox = read_aabb3f(L, -1, 1.0); lua_pop(L, 1); getstringfield(L, -1, "visual", prop->visual); getstringfield(L, -1, "mesh", prop->mesh); lua_getfield(L, -1, "visual_size"); if(lua_istable(L, -1)) prop->visual_size = read_v2f(L, -1); lua_pop(L, 1); lua_getfield(L, -1, "textures"); if(lua_istable(L, -1)){ prop->textures.clear(); int table = lua_gettop(L); lua_pushnil(L); while(lua_next(L, table) != 0){ // key at index -2 and value at index -1 if(lua_isstring(L, -1)) prop->textures.push_back(lua_tostring(L, -1)); else prop->textures.push_back(""); // removes value, keeps key for next iteration lua_pop(L, 1); } } lua_pop(L, 1); lua_getfield(L, -1, "colors"); if (lua_istable(L, -1)) { int table = lua_gettop(L); prop->colors.clear(); for (lua_pushnil(L); lua_next(L, table); lua_pop(L, 1)) { video::SColor color(255, 255, 255, 255); read_color(L, -1, &color); prop->colors.push_back(color); } } lua_pop(L, 1); lua_getfield(L, -1, "spritediv"); if(lua_istable(L, -1)) prop->spritediv = read_v2s16(L, -1); lua_pop(L, 1); lua_getfield(L, -1, "initial_sprite_basepos"); if(lua_istable(L, -1)) prop->initial_sprite_basepos = read_v2s16(L, -1); lua_pop(L, 1); getboolfield(L, -1, "is_visible", prop->is_visible); getboolfield(L, -1, "makes_footstep_sound", prop->makes_footstep_sound); getfloatfield(L, -1, "automatic_rotate", prop->automatic_rotate); if (getfloatfield(L, -1, "stepheight", prop->stepheight)) prop->stepheight *= BS; lua_getfield(L, -1, "automatic_face_movement_dir"); if (lua_isnumber(L, -1)) { prop->automatic_face_movement_dir = true; prop->automatic_face_movement_dir_offset = luaL_checknumber(L, -1); } else if (lua_isboolean(L, -1)) { prop->automatic_face_movement_dir = lua_toboolean(L, -1); prop->automatic_face_movement_dir_offset = 0.0; } lua_pop(L, 1); getboolfield(L, -1, "backface_culling", prop->backface_culling); getstringfield(L, -1, "nametag", prop->nametag); lua_getfield(L, -1, "nametag_color"); if (!lua_isnil(L, -1)) { video::SColor color = prop->nametag_color; if (read_color(L, -1, &color)) prop->nametag_color = color; } lua_pop(L, 1); lua_getfield(L, -1, "automatic_face_movement_max_rotation_per_sec"); if (lua_isnumber(L, -1)) { prop->automatic_face_movement_max_rotation_per_sec = luaL_checknumber(L, -1); } lua_pop(L, 1); getstringfield(L, -1, "infotext", prop->infotext); } /******************************************************************************/ void push_object_properties(lua_State *L, ObjectProperties *prop) { lua_newtable(L); lua_pushnumber(L, prop->hp_max); lua_setfield(L, -2, "hp_max"); lua_pushboolean(L, prop->physical); lua_setfield(L, -2, "physical"); lua_pushboolean(L, prop->collideWithObjects); lua_setfield(L, -2, "collide_with_objects"); lua_pushnumber(L, prop->weight); lua_setfield(L, -2, "weight"); push_aabb3f(L, prop->collisionbox); lua_setfield(L, -2, "collisionbox"); lua_pushlstring(L, prop->visual.c_str(), prop->visual.size()); lua_setfield(L, -2, "visual"); lua_pushlstring(L, prop->mesh.c_str(), prop->mesh.size()); lua_setfield(L, -2, "mesh"); push_v2f(L, prop->visual_size); lua_setfield(L, -2, "visual_size"); lua_newtable(L); u16 i = 1; for (std::vector<std::string>::iterator it = prop->textures.begin(); it != prop->textures.end(); ++it) { lua_pushlstring(L, it->c_str(), it->size()); lua_rawseti(L, -2, i); } lua_setfield(L, -2, "textures"); lua_newtable(L); i = 1; for (std::vector<video::SColor>::iterator it = prop->colors.begin(); it != prop->colors.end(); ++it) { push_ARGB8(L, *it); lua_rawseti(L, -2, i); } lua_setfield(L, -2, "colors"); push_v2s16(L, prop->spritediv); lua_setfield(L, -2, "spritediv"); push_v2s16(L, prop->initial_sprite_basepos); lua_setfield(L, -2, "initial_sprite_basepos"); lua_pushboolean(L, prop->is_visible); lua_setfield(L, -2, "is_visible"); lua_pushboolean(L, prop->makes_footstep_sound); lua_setfield(L, -2, "makes_footstep_sound"); lua_pushnumber(L, prop->automatic_rotate); lua_setfield(L, -2, "automatic_rotate"); lua_pushnumber(L, prop->stepheight / BS); lua_setfield(L, -2, "stepheight"); if (prop->automatic_face_movement_dir) lua_pushnumber(L, prop->automatic_face_movement_dir_offset); else lua_pushboolean(L, false); lua_setfield(L, -2, "automatic_face_movement_dir"); lua_pushboolean(L, prop->backface_culling); lua_setfield(L, -2, "backface_culling"); lua_pushlstring(L, prop->nametag.c_str(), prop->nametag.size()); lua_setfield(L, -2, "nametag"); push_ARGB8(L, prop->nametag_color); lua_setfield(L, -2, "nametag_color"); lua_pushnumber(L, prop->automatic_face_movement_max_rotation_per_sec); lua_setfield(L, -2, "automatic_face_movement_max_rotation_per_sec"); lua_pushlstring(L, prop->infotext.c_str(), prop->infotext.size()); lua_setfield(L, -2, "infotext"); } /******************************************************************************/ TileDef read_tiledef(lua_State *L, int index, u8 drawtype) { if(index < 0) index = lua_gettop(L) + 1 + index; TileDef tiledef; bool default_tiling = true; bool default_culling = true; switch (drawtype) { case NDT_PLANTLIKE: case NDT_FIRELIKE: default_tiling = false; // "break" is omitted here intentionaly, as PLANTLIKE // FIRELIKE drawtype both should default to having // backface_culling to false. case NDT_MESH: case NDT_LIQUID: default_culling = false; break; default: break; } // key at index -2 and value at index if(lua_isstring(L, index)){ // "default_lava.png" tiledef.name = lua_tostring(L, index); tiledef.tileable_vertical = default_tiling; tiledef.tileable_horizontal = default_tiling; tiledef.backface_culling = default_culling; } else if(lua_istable(L, index)) { // {name="default_lava.png", animation={}} tiledef.name = ""; getstringfield(L, index, "name", tiledef.name); getstringfield(L, index, "image", tiledef.name); // MaterialSpec compat. tiledef.backface_culling = getboolfield_default( L, index, "backface_culling", default_culling); tiledef.tileable_horizontal = getboolfield_default( L, index, "tileable_horizontal", default_tiling); tiledef.tileable_vertical = getboolfield_default( L, index, "tileable_vertical", default_tiling); // animation = {} lua_getfield(L, index, "animation"); if(lua_istable(L, -1)){ // {type="vertical_frames", aspect_w=16, aspect_h=16, length=2.0} tiledef.animation.type = (TileAnimationType) getenumfield(L, -1, "type", es_TileAnimationType, TAT_NONE); tiledef.animation.aspect_w = getintfield_default(L, -1, "aspect_w", 16); tiledef.animation.aspect_h = getintfield_default(L, -1, "aspect_h", 16); tiledef.animation.length = getfloatfield_default(L, -1, "length", 1.0); } lua_pop(L, 1); } return tiledef; } /******************************************************************************/ ContentFeatures read_content_features(lua_State *L, int index) { if(index < 0) index = lua_gettop(L) + 1 + index; ContentFeatures f; /* Cache existence of some callbacks */ lua_getfield(L, index, "on_construct"); if(!lua_isnil(L, -1)) f.has_on_construct = true; lua_pop(L, 1); lua_getfield(L, index, "on_destruct"); if(!lua_isnil(L, -1)) f.has_on_destruct = true; lua_pop(L, 1); lua_getfield(L, index, "after_destruct"); if(!lua_isnil(L, -1)) f.has_after_destruct = true; lua_pop(L, 1); lua_getfield(L, index, "on_rightclick"); f.rightclickable = lua_isfunction(L, -1); lua_pop(L, 1); /* Name */ getstringfield(L, index, "name", f.name); /* Groups */ lua_getfield(L, index, "groups"); read_groups(L, -1, f.groups); lua_pop(L, 1); /* Visual definition */ f.drawtype = (NodeDrawType)getenumfield(L, index, "drawtype", ScriptApiNode::es_DrawType,NDT_NORMAL); getfloatfield(L, index, "visual_scale", f.visual_scale); /* Meshnode model filename */ getstringfield(L, index, "mesh", f.mesh); // tiles = {} lua_getfield(L, index, "tiles"); // If nil, try the deprecated name "tile_images" instead if(lua_isnil(L, -1)){ lua_pop(L, 1); warn_if_field_exists(L, index, "tile_images", "Deprecated; new name is \"tiles\"."); lua_getfield(L, index, "tile_images"); } if(lua_istable(L, -1)){ int table = lua_gettop(L); lua_pushnil(L); int i = 0; while(lua_next(L, table) != 0){ // Read tiledef from value f.tiledef[i] = read_tiledef(L, -1, f.drawtype); // removes value, keeps key for next iteration lua_pop(L, 1); i++; if(i==6){ lua_pop(L, 1); break; } } // Copy last value to all remaining textures if(i >= 1){ TileDef lasttile = f.tiledef[i-1]; while(i < 6){ f.tiledef[i] = lasttile; i++; } } } lua_pop(L, 1); // special_tiles = {} lua_getfield(L, index, "special_tiles"); // If nil, try the deprecated name "special_materials" instead if(lua_isnil(L, -1)){ lua_pop(L, 1); warn_if_field_exists(L, index, "special_materials", "Deprecated; new name is \"special_tiles\"."); lua_getfield(L, index, "special_materials"); } if(lua_istable(L, -1)){ int table = lua_gettop(L); lua_pushnil(L); int i = 0; while(lua_next(L, table) != 0){ // Read tiledef from value f.tiledef_special[i] = read_tiledef(L, -1, f.drawtype); // removes value, keeps key for next iteration lua_pop(L, 1); i++; if(i==CF_SPECIAL_COUNT){ lua_pop(L, 1); break; } } } lua_pop(L, 1); f.alpha = getintfield_default(L, index, "alpha", 255); bool usealpha = getboolfield_default(L, index, "use_texture_alpha", false); if (usealpha) f.alpha = 0; /* Other stuff */ lua_getfield(L, index, "post_effect_color"); read_color(L, -1, &f.post_effect_color); lua_pop(L, 1); f.param_type = (ContentParamType)getenumfield(L, index, "paramtype", ScriptApiNode::es_ContentParamType, CPT_NONE); f.param_type_2 = (ContentParamType2)getenumfield(L, index, "paramtype2", ScriptApiNode::es_ContentParamType2, CPT2_NONE); // Warn about some deprecated fields warn_if_field_exists(L, index, "wall_mounted", "Deprecated; use paramtype2 = 'wallmounted'"); warn_if_field_exists(L, index, "light_propagates", "Deprecated; determined from paramtype"); warn_if_field_exists(L, index, "dug_item", "Deprecated; use 'drop' field"); warn_if_field_exists(L, index, "extra_dug_item", "Deprecated; use 'drop' field"); warn_if_field_exists(L, index, "extra_dug_item_rarity", "Deprecated; use 'drop' field"); warn_if_field_exists(L, index, "metadata_name", "Deprecated; use on_add and metadata callbacks"); // True for all ground-like things like stone and mud, false for eg. trees getboolfield(L, index, "is_ground_content", f.is_ground_content); f.light_propagates = (f.param_type == CPT_LIGHT); getboolfield(L, index, "sunlight_propagates", f.sunlight_propagates); // This is used for collision detection. // Also for general solidness queries. getboolfield(L, index, "walkable", f.walkable); // Player can point to these getboolfield(L, index, "pointable", f.pointable); // Player can dig these getboolfield(L, index, "diggable", f.diggable); // Player can climb these getboolfield(L, index, "climbable", f.climbable); // Player can build on these getboolfield(L, index, "buildable_to", f.buildable_to); // Liquids flow into and replace node getboolfield(L, index, "floodable", f.floodable); // Whether the node is non-liquid, source liquid or flowing liquid f.liquid_type = (LiquidType)getenumfield(L, index, "liquidtype", ScriptApiNode::es_LiquidType, LIQUID_NONE); // If the content is liquid, this is the flowing version of the liquid. getstringfield(L, index, "liquid_alternative_flowing", f.liquid_alternative_flowing); // If the content is liquid, this is the source version of the liquid. getstringfield(L, index, "liquid_alternative_source", f.liquid_alternative_source); // Viscosity for fluid flow, ranging from 1 to 7, with // 1 giving almost instantaneous propagation and 7 being // the slowest possible f.liquid_viscosity = getintfield_default(L, index, "liquid_viscosity", f.liquid_viscosity); f.liquid_range = getintfield_default(L, index, "liquid_range", f.liquid_range); f.leveled = getintfield_default(L, index, "leveled", f.leveled); getboolfield(L, index, "liquid_renewable", f.liquid_renewable); f.drowning = getintfield_default(L, index, "drowning", f.drowning); // Amount of light the node emits f.light_source = getintfield_default(L, index, "light_source", f.light_source); f.damage_per_second = getintfield_default(L, index, "damage_per_second", f.damage_per_second); lua_getfield(L, index, "node_box"); if(lua_istable(L, -1)) f.node_box = read_nodebox(L, -1); lua_pop(L, 1); lua_getfield(L, index, "connects_to"); if (lua_istable(L, -1)) { int table = lua_gettop(L); lua_pushnil(L); while (lua_next(L, table) != 0) { // Value at -1 f.connects_to.push_back(lua_tostring(L, -1)); lua_pop(L, 1); } } lua_pop(L, 1); lua_getfield(L, index, "connect_sides"); if (lua_istable(L, -1)) { int table = lua_gettop(L); lua_pushnil(L); while (lua_next(L, table) != 0) { // Value at -1 std::string side(lua_tostring(L, -1)); // Note faces are flipped to make checking easier if (side == "top") f.connect_sides |= 2; else if (side == "bottom") f.connect_sides |= 1; else if (side == "front") f.connect_sides |= 16; else if (side == "left") f.connect_sides |= 32; else if (side == "back") f.connect_sides |= 4; else if (side == "right") f.connect_sides |= 8; else warningstream << "Unknown value for \"connect_sides\": " << side << std::endl; lua_pop(L, 1); } } lua_pop(L, 1); lua_getfield(L, index, "selection_box"); if(lua_istable(L, -1)) f.selection_box = read_nodebox(L, -1); lua_pop(L, 1); lua_getfield(L, index, "collision_box"); if(lua_istable(L, -1)) f.collision_box = read_nodebox(L, -1); lua_pop(L, 1); f.waving = getintfield_default(L, index, "waving", f.waving); // Set to true if paramtype used to be 'facedir_simple' getboolfield(L, index, "legacy_facedir_simple", f.legacy_facedir_simple); // Set to true if wall_mounted used to be set to true getboolfield(L, index, "legacy_wallmounted", f.legacy_wallmounted); // Sound table lua_getfield(L, index, "sounds"); if(lua_istable(L, -1)){ lua_getfield(L, -1, "footstep"); read_soundspec(L, -1, f.sound_footstep); lua_pop(L, 1); lua_getfield(L, -1, "dig"); read_soundspec(L, -1, f.sound_dig); lua_pop(L, 1); lua_getfield(L, -1, "dug"); read_soundspec(L, -1, f.sound_dug); lua_pop(L, 1); } lua_pop(L, 1); return f; } /******************************************************************************/ void read_server_sound_params(lua_State *L, int index, ServerSoundParams &params) { if(index < 0) index = lua_gettop(L) + 1 + index; // Clear params = ServerSoundParams(); if(lua_istable(L, index)){ getfloatfield(L, index, "gain", params.gain); getstringfield(L, index, "to_player", params.to_player); lua_getfield(L, index, "pos"); if(!lua_isnil(L, -1)){ v3f p = read_v3f(L, -1)*BS; params.pos = p; params.type = ServerSoundParams::SSP_POSITIONAL; } lua_pop(L, 1); lua_getfield(L, index, "object"); if(!lua_isnil(L, -1)){ ObjectRef *ref = ObjectRef::checkobject(L, -1); ServerActiveObject *sao = ObjectRef::getobject(ref); if(sao){ params.object = sao->getId(); params.type = ServerSoundParams::SSP_OBJECT; } } lua_pop(L, 1); params.max_hear_distance = BS*getfloatfield_default(L, index, "max_hear_distance", params.max_hear_distance/BS); getboolfield(L, index, "loop", params.loop); } } /******************************************************************************/ void read_soundspec(lua_State *L, int index, SimpleSoundSpec &spec) { if(index < 0) index = lua_gettop(L) + 1 + index; if(lua_isnil(L, index)){ } else if(lua_istable(L, index)){ getstringfield(L, index, "name", spec.name); getfloatfield(L, index, "gain", spec.gain); } else if(lua_isstring(L, index)){ spec.name = lua_tostring(L, index); } } /******************************************************************************/ NodeBox read_nodebox(lua_State *L, int index) { NodeBox nodebox; if(lua_istable(L, -1)){ nodebox.type = (NodeBoxType)getenumfield(L, index, "type", ScriptApiNode::es_NodeBoxType, NODEBOX_REGULAR); #define NODEBOXREAD(n, s) \ do { \ lua_getfield(L, index, (s)); \ if (lua_istable(L, -1)) \ (n) = read_aabb3f(L, -1, BS); \ lua_pop(L, 1); \ } while (0) #define NODEBOXREADVEC(n, s) \ do { \ lua_getfield(L, index, (s)); \ if (lua_istable(L, -1)) \ (n) = read_aabb3f_vector(L, -1, BS); \ lua_pop(L, 1); \ } while (0) NODEBOXREADVEC(nodebox.fixed, "fixed"); NODEBOXREAD(nodebox.wall_top, "wall_top"); NODEBOXREAD(nodebox.wall_bottom, "wall_bottom"); NODEBOXREAD(nodebox.wall_side, "wall_side"); NODEBOXREADVEC(nodebox.connect_top, "connect_top"); NODEBOXREADVEC(nodebox.connect_bottom, "connect_bottom"); NODEBOXREADVEC(nodebox.connect_front, "connect_front"); NODEBOXREADVEC(nodebox.connect_left, "connect_left"); NODEBOXREADVEC(nodebox.connect_back, "connect_back"); NODEBOXREADVEC(nodebox.connect_right, "connect_right"); } return nodebox; } /******************************************************************************/ MapNode readnode(lua_State *L, int index, INodeDefManager *ndef) { lua_getfield(L, index, "name"); if (!lua_isstring(L, -1)) throw LuaError("Node name is not set or is not a string!"); const char *name = lua_tostring(L, -1); lua_pop(L, 1); u8 param1 = 0; lua_getfield(L, index, "param1"); if (!lua_isnil(L, -1)) param1 = lua_tonumber(L, -1); lua_pop(L, 1); u8 param2 = 0; lua_getfield(L, index, "param2"); if (!lua_isnil(L, -1)) param2 = lua_tonumber(L, -1); lua_pop(L, 1); return MapNode(ndef, name, param1, param2); } /******************************************************************************/ void pushnode(lua_State *L, const MapNode &n, INodeDefManager *ndef) { lua_newtable(L); lua_pushstring(L, ndef->get(n).name.c_str()); lua_setfield(L, -2, "name"); lua_pushnumber(L, n.getParam1()); lua_setfield(L, -2, "param1"); lua_pushnumber(L, n.getParam2()); lua_setfield(L, -2, "param2"); } /******************************************************************************/ void warn_if_field_exists(lua_State *L, int table, const char *name, const std::string &message) { lua_getfield(L, table, name); if (!lua_isnil(L, -1)) { warningstream << "Field \"" << name << "\": " << message << std::endl; infostream << script_get_backtrace(L) << std::endl; } lua_pop(L, 1); } /******************************************************************************/ int getenumfield(lua_State *L, int table, const char *fieldname, const EnumString *spec, int default_) { int result = default_; string_to_enum(spec, result, getstringfield_default(L, table, fieldname, "")); return result; } /******************************************************************************/ bool string_to_enum(const EnumString *spec, int &result, const std::string &str) { const EnumString *esp = spec; while(esp->str){ if(str == std::string(esp->str)){ result = esp->num; return true; } esp++; } return false; } /******************************************************************************/ ItemStack read_item(lua_State* L, int index,Server* srv) { if(index < 0) index = lua_gettop(L) + 1 + index; if(lua_isnil(L, index)) { return ItemStack(); } else if(lua_isuserdata(L, index)) { // Convert from LuaItemStack LuaItemStack *o = LuaItemStack::checkobject(L, index); return o->getItem(); } else if(lua_isstring(L, index)) { // Convert from itemstring std::string itemstring = lua_tostring(L, index); IItemDefManager *idef = srv->idef(); try { ItemStack item; item.deSerialize(itemstring, idef); return item; } catch(SerializationError &e) { warningstream<<"unable to create item from itemstring" <<": "<<itemstring<<std::endl; return ItemStack(); } } else if(lua_istable(L, index)) { // Convert from table IItemDefManager *idef = srv->idef(); std::string name = getstringfield_default(L, index, "name", ""); int count = getintfield_default(L, index, "count", 1); int wear = getintfield_default(L, index, "wear", 0); std::string metadata = getstringfield_default(L, index, "metadata", ""); return ItemStack(name, count, wear, metadata, idef); } else { throw LuaError("Expecting itemstack, itemstring, table or nil"); } } /******************************************************************************/ void push_tool_capabilities(lua_State *L, const ToolCapabilities &toolcap) { lua_newtable(L); setfloatfield(L, -1, "full_punch_interval", toolcap.full_punch_interval); setintfield(L, -1, "max_drop_level", toolcap.max_drop_level); // Create groupcaps table lua_newtable(L); // For each groupcap for (ToolGCMap::const_iterator i = toolcap.groupcaps.begin(); i != toolcap.groupcaps.end(); i++) { // Create groupcap table lua_newtable(L); const std::string &name = i->first; const ToolGroupCap &groupcap = i->second; // Create subtable "times" lua_newtable(L); for (UNORDERED_MAP<int, float>::const_iterator i = groupcap.times.begin(); i != groupcap.times.end(); i++) { lua_pushinteger(L, i->first); lua_pushnumber(L, i->second); lua_settable(L, -3); } // Set subtable "times" lua_setfield(L, -2, "times"); // Set simple parameters setintfield(L, -1, "maxlevel", groupcap.maxlevel); setintfield(L, -1, "uses", groupcap.uses); // Insert groupcap table into groupcaps table lua_setfield(L, -2, name.c_str()); } // Set groupcaps table lua_setfield(L, -2, "groupcaps"); //Create damage_groups table lua_newtable(L); // For each damage group for (DamageGroup::const_iterator i = toolcap.damageGroups.begin(); i != toolcap.damageGroups.end(); i++) { // Create damage group table lua_pushinteger(L, i->second); lua_setfield(L, -2, i->first.c_str()); } lua_setfield(L, -2, "damage_groups"); } /******************************************************************************/ void push_inventory_list(lua_State *L, Inventory *inv, const char *name) { InventoryList *invlist = inv->getList(name); if(invlist == NULL){ lua_pushnil(L); return; } std::vector<ItemStack> items; for(u32 i=0; i<invlist->getSize(); i++) items.push_back(invlist->getItem(i)); push_items(L, items); } /******************************************************************************/ void read_inventory_list(lua_State *L, int tableindex, Inventory *inv, const char *name, Server* srv, int forcesize) { if(tableindex < 0) tableindex = lua_gettop(L) + 1 + tableindex; // If nil, delete list if(lua_isnil(L, tableindex)){ inv->deleteList(name); return; } // Otherwise set list std::vector<ItemStack> items = read_items(L, tableindex,srv); int listsize = (forcesize != -1) ? forcesize : items.size(); InventoryList *invlist = inv->addList(name, listsize); int index = 0; for(std::vector<ItemStack>::const_iterator i = items.begin(); i != items.end(); i++){ if(forcesize != -1 && index == forcesize) break; invlist->changeItem(index, *i); index++; } while(forcesize != -1 && index < forcesize){ invlist->deleteItem(index); index++; } } /******************************************************************************/ ToolCapabilities read_tool_capabilities( lua_State *L, int table) { ToolCapabilities toolcap; getfloatfield(L, table, "full_punch_interval", toolcap.full_punch_interval); getintfield(L, table, "max_drop_level", toolcap.max_drop_level); lua_getfield(L, table, "groupcaps"); if(lua_istable(L, -1)){ int table_groupcaps = lua_gettop(L); lua_pushnil(L); while(lua_next(L, table_groupcaps) != 0){ // key at index -2 and value at index -1 std::string groupname = luaL_checkstring(L, -2); if(lua_istable(L, -1)){ int table_groupcap = lua_gettop(L); // This will be created ToolGroupCap groupcap; // Read simple parameters getintfield(L, table_groupcap, "maxlevel", groupcap.maxlevel); getintfield(L, table_groupcap, "uses", groupcap.uses); // DEPRECATED: maxwear float maxwear = 0; if (getfloatfield(L, table_groupcap, "maxwear", maxwear)){ if (maxwear != 0) groupcap.uses = 1.0/maxwear; else groupcap.uses = 0; warningstream << "Field \"maxwear\" is deprecated; " << "replace with uses=1/maxwear" << std::endl; infostream << script_get_backtrace(L) << std::endl; } // Read "times" table lua_getfield(L, table_groupcap, "times"); if(lua_istable(L, -1)){ int table_times = lua_gettop(L); lua_pushnil(L); while(lua_next(L, table_times) != 0){ // key at index -2 and value at index -1 int rating = luaL_checkinteger(L, -2); float time = luaL_checknumber(L, -1); groupcap.times[rating] = time; // removes value, keeps key for next iteration lua_pop(L, 1); } } lua_pop(L, 1); // Insert groupcap into toolcap toolcap.groupcaps[groupname] = groupcap; } // removes value, keeps key for next iteration lua_pop(L, 1); } } lua_pop(L, 1); lua_getfield(L, table, "damage_groups"); if(lua_istable(L, -1)){ int table_damage_groups = lua_gettop(L); lua_pushnil(L); while(lua_next(L, table_damage_groups) != 0){ // key at index -2 and value at index -1 std::string groupname = luaL_checkstring(L, -2); u16 value = luaL_checkinteger(L, -1); toolcap.damageGroups[groupname] = value; // removes value, keeps key for next iteration lua_pop(L, 1); } } lua_pop(L, 1); return toolcap; } /******************************************************************************/ void push_dig_params(lua_State *L,const DigParams &params) { lua_newtable(L); setboolfield(L, -1, "diggable", params.diggable); setfloatfield(L, -1, "time", params.time); setintfield(L, -1, "wear", params.wear); } /******************************************************************************/ void push_hit_params(lua_State *L,const HitParams &params) { lua_newtable(L); setintfield(L, -1, "hp", params.hp); setintfield(L, -1, "wear", params.wear); } /******************************************************************************/ bool getflagsfield(lua_State *L, int table, const char *fieldname, FlagDesc *flagdesc, u32 *flags, u32 *flagmask) { lua_getfield(L, table, fieldname); bool success = read_flags(L, -1, flagdesc, flags, flagmask); lua_pop(L, 1); return success; } bool read_flags(lua_State *L, int index, FlagDesc *flagdesc, u32 *flags, u32 *flagmask) { if (lua_isstring(L, index)) { std::string flagstr = lua_tostring(L, index); *flags = readFlagString(flagstr, flagdesc, flagmask); } else if (lua_istable(L, index)) { *flags = read_flags_table(L, index, flagdesc, flagmask); } else { return false; } return true; } u32 read_flags_table(lua_State *L, int table, FlagDesc *flagdesc, u32 *flagmask) { u32 flags = 0, mask = 0; char fnamebuf[64] = "no"; for (int i = 0; flagdesc[i].name; i++) { bool result; if (getboolfield(L, table, flagdesc[i].name, result)) { mask |= flagdesc[i].flag; if (result) flags |= flagdesc[i].flag; } strlcpy(fnamebuf + 2, flagdesc[i].name, sizeof(fnamebuf) - 2); if (getboolfield(L, table, fnamebuf, result)) mask |= flagdesc[i].flag; } if (flagmask) *flagmask = mask; return flags; } void push_flags_string(lua_State *L, FlagDesc *flagdesc, u32 flags, u32 flagmask) { std::string flagstring = writeFlagString(flags, flagdesc, flagmask); lua_pushlstring(L, flagstring.c_str(), flagstring.size()); } /******************************************************************************/ /* Lua Stored data! */ /******************************************************************************/ /******************************************************************************/ void read_groups(lua_State *L, int index, ItemGroupList &result) { if (!lua_istable(L,index)) return; result.clear(); lua_pushnil(L); if(index < 0) index -= 1; while(lua_next(L, index) != 0){ // key at index -2 and value at index -1 std::string name = luaL_checkstring(L, -2); int rating = luaL_checkinteger(L, -1); result[name] = rating; // removes value, keeps key for next iteration lua_pop(L, 1); } } /******************************************************************************/ void push_groups(lua_State *L, const ItemGroupList &groups) { lua_newtable(L); for (ItemGroupList::const_iterator it = groups.begin(); it != groups.end(); ++it) { lua_pushnumber(L, it->second); lua_setfield(L, -2, it->first.c_str()); } } /******************************************************************************/ void push_items(lua_State *L, const std::vector<ItemStack> &items) { lua_createtable(L, items.size(), 0); for (u32 i = 0; i != items.size(); i++) { LuaItemStack::create(L, items[i]); lua_rawseti(L, -2, i + 1); } } /******************************************************************************/ std::vector<ItemStack> read_items(lua_State *L, int index, Server *srv) { if(index < 0) index = lua_gettop(L) + 1 + index; std::vector<ItemStack> items; luaL_checktype(L, index, LUA_TTABLE); lua_pushnil(L); while (lua_next(L, index)) { s32 key = luaL_checkinteger(L, -2); if (key < 1) { throw LuaError("Invalid inventory list index"); } if (items.size() < (u32) key) { items.resize(key); } items[key - 1] = read_item(L, -1, srv); lua_pop(L, 1); } return items; } /******************************************************************************/ void luaentity_get(lua_State *L, u16 id) { // Get luaentities[i] lua_getglobal(L, "core"); lua_getfield(L, -1, "luaentities"); luaL_checktype(L, -1, LUA_TTABLE); lua_pushnumber(L, id); lua_gettable(L, -2); lua_remove(L, -2); // Remove luaentities lua_remove(L, -2); // Remove core } /******************************************************************************/ bool read_noiseparams(lua_State *L, int index, NoiseParams *np) { if (index < 0) index = lua_gettop(L) + 1 + index; if (!lua_istable(L, index)) return false; getfloatfield(L, index, "offset", np->offset); getfloatfield(L, index, "scale", np->scale); getfloatfield(L, index, "persist", np->persist); getfloatfield(L, index, "persistence", np->persist); getfloatfield(L, index, "lacunarity", np->lacunarity); getintfield(L, index, "seed", np->seed); getintfield(L, index, "octaves", np->octaves); u32 flags = 0; u32 flagmask = 0; np->flags = getflagsfield(L, index, "flags", flagdesc_noiseparams, &flags, &flagmask) ? flags : NOISE_FLAG_DEFAULTS; lua_getfield(L, index, "spread"); np->spread = read_v3f(L, -1); lua_pop(L, 1); return true; } void push_noiseparams(lua_State *L, NoiseParams *np) { lua_newtable(L); lua_pushnumber(L, np->offset); lua_setfield(L, -2, "offset"); lua_pushnumber(L, np->scale); lua_setfield(L, -2, "scale"); lua_pushnumber(L, np->persist); lua_setfield(L, -2, "persistence"); lua_pushnumber(L, np->lacunarity); lua_setfield(L, -2, "lacunarity"); lua_pushnumber(L, np->seed); lua_setfield(L, -2, "seed"); lua_pushnumber(L, np->octaves); lua_setfield(L, -2, "octaves"); push_flags_string(L, flagdesc_noiseparams, np->flags, np->flags); lua_setfield(L, -2, "flags"); push_v3f(L, np->spread); lua_setfield(L, -2, "spread"); } /******************************************************************************/ // Returns depth of json value tree static int push_json_value_getdepth(const Json::Value &value) { if (!value.isArray() && !value.isObject()) return 1; int maxdepth = 0; for (Json::Value::const_iterator it = value.begin(); it != value.end(); ++it) { int elemdepth = push_json_value_getdepth(*it); if (elemdepth > maxdepth) maxdepth = elemdepth; } return maxdepth + 1; } // Recursive function to convert JSON --> Lua table static bool push_json_value_helper(lua_State *L, const Json::Value &value, int nullindex) { switch(value.type()) { case Json::nullValue: default: lua_pushvalue(L, nullindex); break; case Json::intValue: lua_pushinteger(L, value.asInt()); break; case Json::uintValue: lua_pushinteger(L, value.asUInt()); break; case Json::realValue: lua_pushnumber(L, value.asDouble()); break; case Json::stringValue: { const char *str = value.asCString(); lua_pushstring(L, str ? str : ""); } break; case Json::booleanValue: lua_pushboolean(L, value.asInt()); break; case Json::arrayValue: lua_newtable(L); for (Json::Value::const_iterator it = value.begin(); it != value.end(); ++it) { push_json_value_helper(L, *it, nullindex); lua_rawseti(L, -2, it.index() + 1); } break; case Json::objectValue: lua_newtable(L); for (Json::Value::const_iterator it = value.begin(); it != value.end(); ++it) { #ifndef JSONCPP_STRING const char *str = it.memberName(); lua_pushstring(L, str ? str : ""); #else std::string str = it.name(); lua_pushstring(L, str.c_str()); #endif push_json_value_helper(L, *it, nullindex); lua_rawset(L, -3); } break; } return true; } // converts JSON --> Lua table; returns false if lua stack limit exceeded // nullindex: Lua stack index of value to use in place of JSON null bool push_json_value(lua_State *L, const Json::Value &value, int nullindex) { if(nullindex < 0) nullindex = lua_gettop(L) + 1 + nullindex; int depth = push_json_value_getdepth(value); // The maximum number of Lua stack slots used at each recursion level // of push_json_value_helper is 2, so make sure there a depth * 2 slots if (lua_checkstack(L, depth * 2)) return push_json_value_helper(L, value, nullindex); else return false; } // Converts Lua table --> JSON void read_json_value(lua_State *L, Json::Value &root, int index, u8 recursion) { if (recursion > 16) { throw SerializationError("Maximum recursion depth exceeded"); } int type = lua_type(L, index); if (type == LUA_TBOOLEAN) { root = (bool) lua_toboolean(L, index); } else if (type == LUA_TNUMBER) { root = lua_tonumber(L, index); } else if (type == LUA_TSTRING) { size_t len; const char *str = lua_tolstring(L, index, &len); root = std::string(str, len); } else if (type == LUA_TTABLE) { lua_pushnil(L); while (lua_next(L, index)) { // Key is at -2 and value is at -1 Json::Value value; read_json_value(L, value, lua_gettop(L), recursion + 1); Json::ValueType roottype = root.type(); int keytype = lua_type(L, -1); if (keytype == LUA_TNUMBER) { lua_Number key = lua_tonumber(L, -1); if (roottype != Json::nullValue && roottype != Json::arrayValue) { throw SerializationError("Can't mix array and object values in JSON"); } else if (key < 1) { throw SerializationError("Can't use zero-based or negative indexes in JSON"); } else if (floor(key) != key) { throw SerializationError("Can't use indexes with a fractional part in JSON"); } root[(Json::ArrayIndex) key - 1] = value; } else if (keytype == LUA_TSTRING) { if (roottype != Json::nullValue && roottype != Json::objectValue) { throw SerializationError("Can't mix array and object values in JSON"); } root[lua_tostring(L, -1)] = value; } else { throw SerializationError("Lua key to convert to JSON is not a string or number"); } } } else if (type == LUA_TNIL) { root = Json::nullValue; } else { throw SerializationError("Can only store booleans, numbers, strings, objects, arrays, and null in JSON"); } lua_pop(L, 1); // Pop value }
412
0.943973
1
0.943973
game-dev
MEDIA
0.529919
game-dev
0.92445
1
0.92445
google/google-ctf
3,364
2023/hackceler8/rounds/7_sunday/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.
412
0.812485
1
0.812485
game-dev
MEDIA
0.936042
game-dev
0.940803
1
0.940803
ChengF3ng233/Untitled
1,679
src/main/java/net/minecraft/entity/boss/EntityDragonPart.java
package net.minecraft.entity.boss; import net.minecraft.entity.Entity; import net.minecraft.entity.IEntityMultiPart; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.DamageSource; public class EntityDragonPart extends Entity { /** * The dragon entity this dragon part belongs to */ public final IEntityMultiPart entityDragonObj; public final String partName; public EntityDragonPart(IEntityMultiPart parent, String partName, float base, float sizeHeight) { super(parent.getWorld()); this.setSize(base, sizeHeight); this.entityDragonObj = parent; this.partName = partName; } protected void entityInit() { } /** * (abstract) Protected helper method to read subclass entity data from NBT. */ protected void readEntityFromNBT(NBTTagCompound tagCompund) { } /** * (abstract) Protected helper method to write subclass entity data to NBT. */ protected void writeEntityToNBT(NBTTagCompound tagCompound) { } /** * Returns true if other Entities should be prevented from moving through this Entity. */ public boolean canBeCollidedWith() { return true; } /** * Called when the entity is attacked. */ public boolean attackEntityFrom(DamageSource source, float amount) { return !this.isEntityInvulnerable(source) && this.entityDragonObj.attackEntityFromPart(this, source, amount); } /** * Returns true if Entity argument is equal to this Entity */ public boolean isEntityEqual(Entity entityIn) { return this == entityIn || this.entityDragonObj == entityIn; } }
412
0.84112
1
0.84112
game-dev
MEDIA
0.994249
game-dev
0.912411
1
0.912411
ClementDreptin/X360PluginManager
1,056
src/Config.cpp
#include "pch.h" #include "Config.h" #include "Console.h" Config::Config() : m_File("game:\\config.ini") { } HRESULT Config::LoadFromDisk() { // Load the config from disk bool canReadFile = m_File.read(m_Structure); if (!canReadFile) { g_Console.Error("Could not read config from disk."); return E_FAIL; } // Make sure the file format is correct if (!m_Structure.has("plugins_directory")) { g_Console.Error("Incorrect config file format. Expected to find a 'plugins_directory' section."); return E_FAIL; } if (!m_Structure["plugins_directory"].has("path")) { g_Console.Error("Incorrect config file format. Expected to find a 'path' key under the 'plugins_directory' section."); return E_FAIL; } if (m_Structure["plugins_directory"]["path"].empty()) { g_Console.Error("Incorrect config file format. 'path' cannot be empty."); return E_FAIL; } m_PluginsDir = m_Structure["plugins_directory"]["path"]; return S_OK; }
412
0.88247
1
0.88247
game-dev
MEDIA
0.575587
game-dev,testing-qa
0.727447
1
0.727447
RobotLocomotion/drake
1,243
systems/framework/event_collection.cc
#include "drake/systems/framework/event_collection.h" DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS( class ::drake::systems::CompositeEventCollection); DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS( class ::drake::systems::LeafCompositeEventCollection); DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS( class ::drake::systems::DiagramCompositeEventCollection); // Due to a circular dependency (the various event types depend on the // collection types and vice versa) it's not possible to instantiate the event // types without the collections available. For that reason, we create the // instances for both in this file. DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS( class ::drake::systems::WitnessTriggeredEventData); DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS( class ::drake::systems::Event); DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS( class ::drake::systems::PublishEvent); DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS( class ::drake::systems::DiscreteUpdateEvent); DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS( class ::drake::systems::UnrestrictedUpdateEvent);
412
0.715198
1
0.715198
game-dev
MEDIA
0.394123
game-dev
0.546791
1
0.546791
ProjectEQ/projecteqquests
1,754
oggok/Emissary_Glib.pl
# items: 13369, 13370, 17928, 13371 sub EVENT_SAY { if ($text=~/hail/i) { quest::say("Gloop.. Are you the one? Who sent you?"); } if ($text=~/the greenblood shaman sent me/i) { quest::say("Gloop.. Good. I am the secret emissary of the frogloks of Guk. I have come to help your community, provided, that is, that you help mine. Gloop.. I want you to track down and kill the troll hunters called 'slayers.' They are capturing our foragers in the swamps. Return their slayer necklaces to me and I shall pay you, but most important, find the slayer captain. Bring me his captain's necklace and I shall give you a secret. I must leave soon. If you need me, just ask Marda where I am."); } } sub EVENT_ITEM { if (plugin::check_handin(\%itemcount, 13369 => 1)) { quest::say("Good work. That is one less troll slayer. My people shall learn of your good deed. Please search for the slayer captain. He must be stopped."); quest::faction(374,20); # Faction: Oggok Resident quest::exp(200); quest::givecash(0,0,7,5); } if (plugin::check_handin(\%itemcount, 13370 => 1)) { quest::say("'Oooh!! .. You have dispatched the slayer captain. It will take them time to reorganize the slayers. During this time the froglok foragers can gather more provisions for Guk. Please take this as a token of my people's appreciation. Your standing with my brethren has grown. As for Marda's information.. within Grobb lies my aide, Groak. He was captured. Tell him Glib sent you."); quest::faction(374,20); # Faction: Oggok Resident quest::exp(200); quest::givecash(0,0,1,0); quest::summonitem(quest::ChooseRandom(17928,13371)); # Item(s): Forager Bag (17928), Hopper Spear (13371) } plugin::return_items(\%itemcount); }
412
0.806493
1
0.806493
game-dev
MEDIA
0.815038
game-dev
0.80698
1
0.80698
aa2g/AA2Unlimited
2,260
AAUnlimited/Texts/mod/butthurt.lua
--@INFO Limit the rate of NPC interruptions local _M = {} local c = require 'const' local opts = { {"cooldown", 30, "Cooldown seconds: %i[1,300]{Disable interruptions for this much seconds}"}, {"stacking", 1, "Stacking cooldown: %b{Cooldowns will stack with each interupt}"}, {"chancecd", 10, "Intr chance w/ cooldown: %i[0,100]{When cooldown is active, allow this % of interruptions}"}, {"chancencd", 100, "Intr chance w/o cooldown: %i[0,100]{When cooldown is inactive, allow this % of interruptions}"}, } local butthurt_actions = { [c.INTERRUPT_COMPETE] = true, [c.INTERRUPT_STOP_QUARREL] = true, [c.INTERRUPT_WHAT_ARE_YOU_DOING] = true, [c.BREAK_CHAT] = true, [c.BREAK_H] = true, } local convo_chars = {} function on.char_spawn_end(status, char) info("butthurt: Adding convo char #%d" % char.m_seat) convo_chars[char] = true return status end function on.convo(state) if not state then info("butthurt: Resetting convo chars") convo_chars = {} end end function on.end_h() convo_chars = {} end local cooldown = 0 function on.plan(ok,e,who) if not ok then return end if not butthurt_actions[e.conversationId] then return ok end local target = (e.target1 or e.target2 or {}).m_thisChar or GetPlayerCharacter() if (target == GetPlayerCharacter()) or convo_chars[target] then info("butthurt: Character #%d got butthurt about us, target = %d" % {who.m_seat,target.m_seat}) local now = os.time() local oldcd = cooldown if cooldown < now then cooldown = now end if opts.stacking == 1 then cooldown = cooldown + opts.cooldown else cooldown = now + opts.cooldown end local chance = opts.chancencd if oldcd > now then info("butthurt: cooldown active") chance = opts.chancecd end info("butthurt: New cooldown: %.2f seconds" % (cooldown - now)) if (math.random() * 100) > chance then info("butthurt: cancelled, chance was %d" % chance) e.conversationId = -1 ok = false end else info("butthurt: Character #%d got butthurt about somebody else, target = %d" % {who.m_seat,target.m_seat}) end return ok end function _M:load() mod_load_config(self, opts) end function _M:config() mod_edit_config(self, opts, "Set butthurt limiter options") end function _M.unload() end return _M
412
0.910933
1
0.910933
game-dev
MEDIA
0.558676
game-dev
0.9601
1
0.9601
UOX3DevTeam/UOX3
175,841
source/cScript.cpp
#include "uox3.h" #include "cScript.h" #include "power.h" #include "UOXJSClasses.h" #include "SEFunctions.h" #include "UOXJSMethods.h" #include "UOXJSPropertySpecs.h" #include "CJSMapping.h" #include "CPacketReceive.h" #include "CJSEngine.h" #include "JSEncapsulate.h" #include "cSpawnRegion.h" #include "StringUtility.hpp" #include "osunique.hpp" //o------------------------------------------------------------------------------------------------o //| File - cScript.cpp //| Date - August 26th, 2000 //o------------------------------------------------------------------------------------------------o //| Purpose - Handles JS events //o------------------------------------------------------------------------------------------------o //| Changes - Version History //| 1.0 26th August, 2000 //| Initial implementation //| The basic event model is in, along with some fairly simple error handling //| Note that parameters for each event is NOT correct at all, it was just to get the basic layout right //| Support for CS type stuff with IsFiring(), Firing(), and Stop() //| //| 1.1 6th September, 2000 //| Each function has params and passes it along into the the script as required //| //| 1.2 18th September, 2000 //| Addition of a number of more events, not all with params //| More functions added to the functions table //| Support for dynamic reloading of scripts //| //| 1.3 2nd November, 2000 //| Addition of a number of events. Caching of function presence added //| All functions assumed present, only failure on a call will flag not present //| //| 1.4 1st July, 2004 //| Added private property of SCRIPTTYPE to store which type of script we've got //| Preparation for JS scriptable spells //o------------------------------------------------------------------------------------------------o static JSFunctionSpec my_functions[] = { // ScriptName, Func Ptr, num args, ?, ? { "StringToNum", SE_StringToNum, 1, 0, 0 }, // This function will be depreciated { "NumToString", SE_NumToString, 1, 0, 0 }, // This function will be depreciated { "NumToHexString", SE_NumToHexString, 1, 0, 0 }, // This function will be depreciated { "DoMovingEffect", SE_DoMovingEffect, 6, 0, 0 }, { "DoStaticEffect", SE_DoStaticEffect, 7, 0, 0 }, { "BroadcastMessage", SE_BroadcastMessage, 1, 0, 0 }, { "RandomNumber", SE_RandomNumber, 2, 0, 0 }, { "CalcCharFromSer", SE_CalcCharFromSer, 1, 0, 0 }, { "CalcItemFromSer", SE_CalcItemFromSer, 1, 0, 0 }, { "CalcMultiFromSer", SE_CalcMultiFromSer, 1, 0, 0 }, { "CheckTimeSinceLastCombat", SE_CheckTimeSinceLastCombat,2, 0, 0 }, { "CheckInstaLog", SE_CheckInstaLog, 4, 0, 0 }, { "GetHour", SE_GetHour, 0, 0, 0 }, { "GetMinute", SE_GetMinute, 0, 0, 0 }, { "GetDay", SE_GetDay, 0, 0, 0 }, { "SecondsPerUOMinute", SE_SecondsPerUOMinute, 0, 0, 0 }, { "GetCurrentClock", SE_GetCurrentClock, 0, 0, 0 }, { "GetStartTime", SE_GetStartTime, 0, 0, 0 }, { "GetMurderThreshold", SE_GetMurderThreshold, 0, 0, 0 }, { "RollDice", SE_RollDice, 3, 0, 0 }, { "RaceCompareByRace", SE_RaceCompareByRace, 2, 0, 0 }, { "GetRandomSOSArea", SE_GetRandomSOSArea, 2, 0, 0 }, { "DoTempEffect", SE_DoTempEffect, 7, 0, 0 }, { "MakeItem", SE_MakeItem, 3, 0, 0 }, { "FindMulti", SE_FindMulti, 4, 0, 0 }, { "GetItem", SE_GetItem, 4, 0, 0 }, { "FindItem", SE_FindItem, 5, 0, 0 }, { "PossessTown", SE_PossessTown, 2, 0, 0 }, { "IsRaceWeakToWeather", SE_IsRaceWeakToWeather, 2, 0, 0 }, { "GetRaceSkillAdjustment", SE_GetRaceSkillAdjustment, 2, 0, 0 }, { "UseItem", SE_UseItem, 2, 0, 0 }, { "TriggerTrap", SE_TriggerTrap, 2, 0, 0 }, { "CompareGuildByGuild", SE_CompareGuildByGuild, 2, 0, 0 }, { "CommandLevelReq", SE_CommandLevelReq, 1, 0, 0 }, { "CommandExists", SE_CommandExists, 1, 0, 0 }, { "FirstCommand", SE_FirstCommand, 0, 0, 0 }, { "NextCommand", SE_NextCommand, 0, 0, 0 }, { "FinishedCommandList", SE_FinishedCommandList, 0, 0, 0 }, { "CreateDFNItem", SE_CreateDFNItem, 3, 0, 0 }, { "CreateBlankItem", SE_CreateBlankItem, 8, 0, 0 }, { "CreateHouse", SE_CreateHouse, 8, 0, 0 }, { "CreateBaseMulti", SE_CreateBaseMulti, 8, 0, 0 }, { "SpawnNPC", SE_SpawnNPC, 6, 0, 0 }, { "GetPackOwner", SE_GetPackOwner, 2, 0, 0 }, { "FindRootContainer", SE_FindRootContainer, 2, 0, 0 }, { "CalcTargetedItem", SE_CalcTargetedItem, 1, 0, 0 }, { "CalcTargetedChar", SE_CalcTargetedChar, 1, 0, 0 }, { "GetTileIDAtMapCoord", SE_GetTileIdAtMapCoord, 3, 0, 0 }, { "GetDictionaryEntry", SE_GetDictionaryEntry, 2, 0, 0 }, { "Yell", SE_Yell, 3, 0, 0 }, { "GetRaceCount", SE_GetRaceCount, 0, 0, 0 }, { "WorldBrightLevel", SE_WorldBrightLevel, 0, 0, 0 }, { "WorldDarkLevel", SE_WorldDarkLevel, 0, 0, 0 }, { "WorldDungeonLevel", SE_WorldDungeonLevel, 0, 0, 0 }, { "GetSpawnRegionFacetStatus", SE_GetSpawnRegionFacetStatus, 1, 0, 0 }, { "SetSpawnRegionFacetStatus", SE_SetSpawnRegionFacetStatus, 2, 0, 0 }, { "GetMoongateFacetStatus", SE_GetMoongateFacetStatus, 1, 0, 0 }, { "SetMoongateFacetStatus", SE_SetMoongateFacetStatus, 2, 0, 0 }, { "AreaCharacterFunction", SE_AreaCharacterFunction, 3, 0, 0 }, { "AreaItemFunction", SE_AreaItemFunction, 3, 0, 0 }, { "TriggerEvent", SE_TriggerEvent, 3, 0, 0 }, { "DoesEventExist", SE_DoesEventExist, 2, 0, 0 }, { "Reload", SE_Reload, 1, 0, 0 }, { "SendStaticStats", SE_SendStaticStats, 1, 0, 0 }, { "GetTileHeight", SE_GetTileHeight, 1, 0, 0 }, { "IterateOver", SE_IterateOver, 1, 0, 0 }, { "IterateOverSpawnRegions", SE_IterateOverSpawnRegions, 1, 0, 0 }, { "GetSocketFromIndex", SE_GetSocketFromIndex, 1, 0, 0 }, { "StaticAt", SE_StaticAt, 4, 0, 0 }, { "StaticInRange", SE_StaticInRange, 5, 0, 0 }, { "GetMapElevation", SE_GetMapElevation, 3, 0, 0 }, { "IsInBuilding", SE_IsInBuilding, 6, 0, 0 }, { "CheckStaticFlag", SE_CheckStaticFlag, 5, 0, 0 }, { "CheckDynamicFlag", SE_CheckDynamicFlag, 6, 0, 0 }, { "CheckTileFlag", SE_CheckTileFlag, 2, 0, 0 }, { "DoesDynamicBlock", SE_DoesDynamicBlock, 9, 0, 0 }, { "DoesStaticBlock", SE_DoesStaticBlock, 5, 0, 0 }, { "DoesMapBlock", SE_DoesMapBlock, 8, 0, 0 }, { "DoesCharacterBlock", SE_DoesCharacterBlock, 5, 0, 0 }, { "DistanceBetween", SE_DistanceBetween, 4, 0, 0 }, { "ResourceArea", SE_ResourceArea, 2, 0, 0 }, { "ResourceAmount", SE_ResourceAmount, 2, 0, 0 }, { "ResourceTime", SE_ResourceTime, 2, 0, 0 }, { "ResourceRegion", SE_ResourceRegion, 3, 0, 0 }, { "Moon", SE_Moon, 2, 0, 0 }, { "GetTownRegion", SE_GetTownRegion, 1, 0, 0 }, { "GetTownRegionFromXY", SE_GetTownRegionFromXY, 4, 0, 0 }, { "GetSpawnRegion", SE_GetSpawnRegion, 4, 0, 0 }, { "GetSpawnRegionCount", SE_GetSpawnRegionCount, 0, 0, 0 }, { "RegisterCommand", SE_RegisterCommand, 3, 0, 0 }, { "DisableCommand", SE_DisableCommand, 1, 0, 0 }, { "EnableCommand", SE_EnableCommand, 1, 0, 0 }, { "RegisterKey", SE_RegisterKey, 2, 0, 0 }, { "DisableKey", SE_DisableKey, 1, 0, 0 }, { "EnableKey", SE_EnableKey, 1, 0, 0 }, { "RegisterConsoleFunc", SE_RegisterConsoleFunc, 2, 0, 0 }, { "DisableConsoleFunc", SE_DisableConsoleFunc, 1, 0, 0 }, { "EnableConsoleFunc", SE_EnableConsoleFunc, 1, 0, 0 }, { "RegisterSpell", SE_RegisterSpell, 2, 0, 0 }, { "DisableSpell", SE_DisableSpell, 1, 0, 0 }, { "EnableSpell", SE_EnableSpell, 1, 0, 0 }, { "RegisterSkill", SE_RegisterSkill, 2, 0, 0 }, { "RegisterPacket", SE_RegisterPacket, 2, 0, 0 }, { "ReloadJSFile", SE_ReloadJSFile, 1, 0, 0 }, { "ValidateObject", SE_ValidateObject, 1, 0, 0 }, { "ApplyDamageBonuses", SE_ApplyDamageBonuses, 6, 0, 0 }, { "ApplyDefenseModifiers", SE_ApplyDefenseModifiers, 7, 0, 0 }, { "WillResultInCriminal", SE_WillResultInCriminal, 2, 0, 0 }, { "CreateParty", SE_CreateParty, 1, 0, 0 }, { "GetClientFeature", SE_GetClientFeature, 1, 0, 0 }, { "GetServerFeature", SE_GetServerFeature, 1, 0, 0 }, { "GetServerSetting", SE_GetServerSetting, 1, 0, 0 }, { "DeleteFile", SE_DeleteFile, 2, 0, 0 }, { "GetAccountCount", SE_GetAccountCount, 0, 0, 0 }, { "GetPlayerCount", SE_GetPlayerCount, 0, 0, 0 }, { "GetItemCount", SE_GetItemCount, 0, 0, 0 }, { "GetMultiCount", SE_GetMultiCount, 0, 0, 0 }, { "GetCharacterCount", SE_GetCharacterCount, 0, 0, 0 }, { "GetServerVersionString", SE_GetServerVersionString, 0, 0, 0 }, { "EraStringToNum", SE_EraStringToNum, 1, 0, 0 }, { "GetCommandLevelVal", SE_GetCommandLevelVal, 1, 0, 0 }, { "BASEITEMSERIAL", SE_BASEITEMSERIAL, 0, 0, 0 }, { "INVALIDSERIAL", SE_INVALIDSERIAL, 0, 0, 0 }, { "INVALIDID", SE_INVALIDID, 0, 0, 0 }, { "INVALIDCOLOUR", SE_INVALIDCOLOUR, 0, 0, 0 }, { nullptr, nullptr, 0, 0, 0 }, }; void UOX3ErrorReporter( JSContext *cx, const char *message, JSErrorReport *report ) { JSErrorInfo* errorInfo = ( JSErrorInfo *)JS_GetContextPrivate( cx ); if( errorInfo != nullptr ) { // Silently populate errorInfo for cScript constructor during compilation if( report == nullptr || report->filename == nullptr ) { errorInfo->message = "No detailed data"; return; } if( report->linebuf != nullptr ) { errorInfo->lineSource = report->linebuf; } if( report->tokenptr != nullptr ) { errorInfo->tokenPointer = report->tokenptr; } errorInfo->message = message; errorInfo->filename = report->filename; errorInfo->lineNum = report->lineno; } else { // Output errors directly here, triggered by runtime execution of scripts UI16 scriptNum = JSMapping->GetScriptId( JS_GetGlobalObject( cx )); Console.Error( oldstrutil::format( "JS script failure: Script Number (%u) Message (%s)", scriptNum, message )); if( report == nullptr || report->filename == nullptr ) { Console.Error( "No detailed data" ); return; } Console.Error( oldstrutil::format( "Filename: %s", report->filename )); Console.Error( oldstrutil::format( "Line Number: %i", report->lineno )); if( report->linebuf != nullptr ) { Console.Error( oldstrutil::format( "Erroneous Line: %s", oldstrutil::trim( report->linebuf ).c_str() )); } if( report->tokenptr != nullptr ) { Console.Error( oldstrutil::format( "Token Ptr: %s", report->tokenptr )); } } } // Global error message variable used to pass error message from MethodError() to the custom JSError callback function std::string g_errorMessage; //o------------------------------------------------------------------------------------------------o //| Function - ScriptErrorCallback() //o------------------------------------------------------------------------------------------------o //| Purpose - Callback for custom JSError //| Notes - Relies on global variable g_errorMessage to pass in error message from //| MethodError function. //o------------------------------------------------------------------------------------------------o const JSErrorFormatString* ScriptErrorCallback( [[maybe_unused]] void *userRef, [[maybe_unused]] const char *locale, [[maybe_unused]] const uintN errorNumber ) { // Return a pointer to a JSErrorFormatString, to the UOX3ErrorReporter function in cScript.cpp static JSErrorFormatString errorFormat; errorFormat.format = g_errorMessage.c_str(); errorFormat.argCount = 0; errorFormat.exnType = JSEXN_ERR; return &errorFormat; } //o------------------------------------------------------------------------------------------------o //| Function - ScriptError() //o------------------------------------------------------------------------------------------------o //| Purpose - Spit out a custom error message related to JS Methods or their parameters //| Notes - Piggybacks on the internal error reporting mechanism in SpiderMonkey to get //| the filename and relevant line number from associated script //o------------------------------------------------------------------------------------------------o void ScriptError( JSContext *cx, const char *txt, ... ) { // Combine error message with any potential additional arguments provided, store in g_errorMessage va_list argptr; va_start( argptr, txt ); g_errorMessage = oldstrutil::format( txt, argptr ); va_end( argptr ); // Define a custom error number. Needed, but not really used for anything const uintN customErrorNumber = 1000; // Manually trigger an error using SpiderMonkey's internal error reporting, // which makes use of JSErrorFormatString from ScriptErrorCallback function // to call upon UOX3ErrorReporter function in cScript.cpp JS_ReportErrorNumber( cx, ScriptErrorCallback, nullptr, customErrorNumber, "" ); } //o------------------------------------------------------------------------------------------------o //| Function - SI32 TryParseJSVal( jsval toParse ) //o------------------------------------------------------------------------------------------------o //| Purpose - Helper function to parse jsval returned from script //o------------------------------------------------------------------------------------------------o SI32 TryParseJSVal( jsval toParse ) { if( JSVAL_IS_NULL( toParse ) || ( !JSVAL_IS_BOOLEAN( toParse ) && !JSVAL_IS_INT( toParse ))) { // jsval is neither a bool nor an int - possibly an object! return 0; } else if( JSVAL_IS_BOOLEAN( toParse ) == JS_FALSE && JSVAL_IS_INT( toParse )) { // jsval is an int! return static_cast<SI32>( JSVAL_TO_INT( toParse )); } else if( JSVAL_IS_BOOLEAN( toParse ) == JS_TRUE ) { // jsval is a bool! convert it to int if( JSVAL_TO_BOOLEAN( toParse ) == JS_TRUE ) { return 1; } else { return 0; } } else { return -1; } } cScript::cScript( std::string targFile, UI08 rT ) : isFiring( false ), runTime( rT ) { for( SI32 i = 0; i < 3; ++i ) { eventPresence[i].set(); needsChecking[i].set(); } targContext = JSEngine->GetContext( runTime ); //JS_NewContext( JSEngine->GetRuntime( runTime ), 0x2000 ); if( targContext == nullptr ) return; targObject = JS_NewObject( targContext, &uox_class, nullptr, nullptr ); if( targObject == nullptr ) return; JS_LockGCThing( targContext, targObject ); //JS_AddRoot( targContext, &targObject ); // Moved here so it reports errors during script-startup too JS_SetErrorReporter( targContext, UOX3ErrorReporter ); JS_SetGlobalObject( targContext, targObject ); //JS_InitStandardClasses( targContext, targObject ); JS_DefineFunctions( targContext, targObject, my_functions ); // Let's fetch some error details when we compile the script JSErrorInfo errorDetails; JS_SetContextPrivate( targContext, &errorDetails ); targScript = JS_CompileFile( targContext, targObject, targFile.c_str() ); JS_SetContextPrivate( targContext, nullptr ); if( targScript == nullptr ) { std::string errorMessage, errorFile, errorLineStr, tokenPtrLine; uint32 errorLine = 0; UI16 scriptNum = 0xFFFF; // Script Number is unknown at this stage if( !errorDetails.message.empty() ) { // Triggered during compilation of scripts at startup, or upon full reload of script engine at runtime errorMessage = errorDetails.message; errorFile = errorDetails.filename; errorLine = errorDetails.lineNum; errorLineStr = errorDetails.lineSource; tokenPtrLine = errorDetails.tokenPointer; } else { // Triggered when reloading individual scripts at runtime jsval pendingException; if( JS_GetPendingException( targContext, &pendingException ) == JS_TRUE ) { if( JSVAL_IS_OBJECT( pendingException ) && !JSVAL_IS_NULL( pendingException )) { JSObject *errObj = JSVAL_TO_OBJECT( pendingException ); // Get error message from pending exception jsval messageVal; if( JS_GetProperty( targContext, errObj, "message", &messageVal ) == JS_TRUE ) { JSString *tempStr = JS_ValueToString( targContext, messageVal ); if( tempStr ) { errorMessage = JS_GetStringBytes( tempStr ); } } // Get line number from pending exception jsval lineVal; if( JS_GetProperty( targContext, errObj, "lineNumber", &lineVal ) == JS_TRUE ) { JS_ValueToECMAUint32( targContext, lineVal, &errorLine ); } // Get filename from pending exception jsval fileVal; if( JS_GetProperty( targContext, errObj, "fileName", &fileVal ) == JS_TRUE ) { JSString *tempStr = JS_ValueToString( targContext, fileVal ); if( tempStr ) { errorFile = JS_GetStringBytes( tempStr ); } } } JS_ClearPendingException( targContext ); } } // Spit out the distinct parts of the error message line by line Console.Error( oldstrutil::format( "JS script failure: Script Number (%u) Message (%s)", scriptNum, errorMessage.c_str() )); Console.Error( oldstrutil::format( "Filename: %s", errorFile.c_str() )); Console.Error( oldstrutil::format( "Line Number: %i", errorLine )); if( !errorLineStr.empty() ) { Console.Error( oldstrutil::format( "Erroneous Line: %s", oldstrutil::trim( errorLineStr ).c_str() )); } if( !tokenPtrLine.empty() ) { Console.Error( oldstrutil::format( "Token Ptr: %s", tokenPtrLine.c_str() )); } throw std::runtime_error( "Error during JS Compilation" ); } jsval rval; JSBool ok = JS_ExecuteScript( targContext, targObject, targScript, &rval ); if( ok != JS_TRUE ) { JSString *str = JS_ValueToString( targContext, rval ); Console << "script result: " << JS_GetStringBytes( str ) << myendl; } } void cScript::Cleanup( void ) { size_t i = 0; for( i = 0; i < gumpDisplays.size(); ++i ) { delete gumpDisplays[i]; } gumpDisplays.resize( 0 ); JS_UnlockGCThing( targContext, targObject ); //JS_RemoveRoot( targContext, &targObject ); } void cScript::CollectGarbage( void ) { Cleanup(); JS_LockGCThing( targContext, targObject ); } cScript::~cScript() { //JS_GC( targContext ); if( targScript != nullptr ) { JS_DestroyScript( targContext, targScript ); targScript = nullptr; } Cleanup(); //JS_GC( targContext ); // if( targContext != nullptr ) // JS_DestroyContext( targContext ); } bool cScript::IsFiring( void ) { return isFiring; } void cScript::Firing( void ) { isFiring = true; } void cScript::Stop( void ) { isFiring = false; } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnStart() //| Date - 8/16/2003 3:44:50 AM //o------------------------------------------------------------------------------------------------o //| Purpose - The OnStart event is provided to allow a script to process //| and read in any state information that has been saved from //| a previous server shut down. If a a script come with an //| OnStart event the code that is provided will be executed //| just following the loading of the script. //o------------------------------------------------------------------------------------------------o bool cScript::OnStart( void ) { return false; } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnStop() //| Date - 8/16/2003 3:44:44 AM //o------------------------------------------------------------------------------------------------o //| Purpose - The OnStop event is provided to allow a script to perform //| any special cleanup, or state saving as a server shuts //| down. If a script has an OnStop event then any code that //| is provided will be executed just prior to the JSE shut //| down. //o------------------------------------------------------------------------------------------------o bool cScript::OnStop( void ) { return false; } //o------------------------------------------------------------------------------------------------o //| Function - cScript::DoesEventExist() //o------------------------------------------------------------------------------------------------o //| Purpose - Allows scripters to check if a particular JS event (or function) exists in a //| script before attempting to call it via TriggerEvent //o------------------------------------------------------------------------------------------------o bool cScript::DoesEventExist( char *eventToFind ) { jsval Func = JSVAL_NULL; JS_GetProperty( targContext, targObject, eventToFind, &Func ); if( Func == JSVAL_VOID ) { return false; } return true; } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnCreate() //o------------------------------------------------------------------------------------------------o //| Purpose - Runs when an object is added/created //| Notes - Checks for the presence of onCreateDFN by default, but onCreateTile can also //| be used to intercept creation of items directly from tiles/harditems.dfn //o------------------------------------------------------------------------------------------------o bool cScript::OnCreate( CBaseObject *thingCreated, bool dfnCreated, bool isPlayer) { if( !ValidateObject( thingCreated )) return false; std::string functionName = "onCreateDFN"; if( isPlayer ) { functionName = "onCreatePlayer"; if( !ExistAndVerify( seOnCreatePlayer, functionName )) return false; } else if( !dfnCreated ) { functionName = "onCreateTile"; if( !ExistAndVerify( seOnCreateTile, functionName )) return false; } else { if( !ExistAndVerify( seOnCreateDFN, functionName )) return false; } jsval rval, params[2]; UI08 paramType = 0; JSObject *myObj; if( thingCreated->GetObjType() == OT_CHAR ) { myObj = JSEngine->AcquireObject( IUE_CHAR, thingCreated, runTime ); paramType = 1; } else { myObj = JSEngine->AcquireObject( IUE_ITEM, thingCreated, runTime ); } params[0] = OBJECT_TO_JSVAL( myObj ); params[1] = INT_TO_JSVAL( paramType ); JSBool retVal = JS_CallFunctionName( targContext, targObject, functionName.c_str(), 2, params, &rval ); if( retVal == JS_FALSE ) { if( isPlayer ) { SetEventExists( seOnCreatePlayer, false ); } else if( !dfnCreated ) { SetEventExists( seOnCreateTile, false ); } else { SetEventExists( seOnCreateDFN, false ); } } return ( retVal == JS_TRUE ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnDelete() //o------------------------------------------------------------------------------------------------o //| Purpose - Runs when an object is deleted //o------------------------------------------------------------------------------------------------o bool cScript::OnDelete( CBaseObject *thingDestroyed ) { if( !ValidateObject( thingDestroyed )) return false; if( !ExistAndVerify( seOnDelete, "onDelete" )) return false; jsval rval, params[2]; UI08 paramType = 0; JSObject *myObj; if( thingDestroyed->GetObjType() != OT_CHAR ) { myObj = JSEngine->AcquireObject( IUE_ITEM, thingDestroyed, runTime ); } else { myObj = JSEngine->AcquireObject( IUE_CHAR, thingDestroyed, runTime ); paramType = 1; } params[0] = OBJECT_TO_JSVAL( myObj ); params[1] = INT_TO_JSVAL( paramType ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onDelete", 2, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnDelete, false ); } return ( retVal == JS_TRUE ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnSpeech() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers when a character talks in range of the character with event attached //o------------------------------------------------------------------------------------------------o //| Notes - The function returns 4 possible values //| -1 => No such function or bad call //| 0 => Let other NPCs and PCs see it //| 1 => Let other PCs see it //| 2 => Let no one else see it //| If JS returns non-int and non-bool, default to 0 //| If JS returns bool, true == 2, false == 0 //o------------------------------------------------------------------------------------------------o //| Changes - 22 June, 2003 17:30 (making it version 3) //| Changed return values from bool to SI08 //o------------------------------------------------------------------------------------------------o SI08 cScript::OnSpeech( const char *speech, CChar *personTalking, CBaseObject *talkingTo ) { const SI08 RV_NOFUNC = -1; if( speech == nullptr || !ValidateObject( personTalking ) || !ValidateObject( talkingTo )) return RV_NOFUNC; if( !ExistAndVerify( seOnSpeech, "onSpeech" )) return RV_NOFUNC; jsval params[3], rval; JSString *strSpeech = nullptr; std::string lwrSpeech = speech; strSpeech = JS_NewStringCopyZ( targContext, oldstrutil::lower( lwrSpeech ).c_str() ); JSObject *ptObj = JSEngine->AcquireObject( IUE_CHAR, personTalking, runTime ); JSObject *ttObj = nullptr; if( talkingTo->CanBeObjType( OT_CHAR )) { ttObj = JSEngine->AcquireObject( IUE_CHAR, talkingTo, runTime ); } else if( talkingTo->CanBeObjType( OT_ITEM )) { ttObj = JSEngine->AcquireObject( IUE_ITEM, talkingTo, runTime ); } params[0] = STRING_TO_JSVAL( strSpeech ); params[1] = OBJECT_TO_JSVAL( ptObj ); params[2] = OBJECT_TO_JSVAL( ttObj ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onSpeech", 3, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnSpeech, false ); return RV_NOFUNC; } if( !( JSVAL_IS_NULL( rval ))) // They returned some sort of value { if( JSVAL_IS_INT( rval )) { return static_cast<SI08>(JSVAL_TO_INT( rval )); } else if( JSVAL_IS_BOOLEAN( rval )) { if( JSVAL_TO_BOOLEAN( rval ) == JS_TRUE ) return 2; } } return 0; // return default } //o------------------------------------------------------------------------------------------------o //| Function - cScript::InRange() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers when an object comes in range of a character with the event attached //o------------------------------------------------------------------------------------------------o //| Notes - A third parameter is provided to let script know whether object that comes into //| range is a character or an item (Multi not supported yet) //o------------------------------------------------------------------------------------------------o bool cScript::InRange( CBaseObject *srcObj, CBaseObject *objInRange ) { if( !ValidateObject( srcObj ) || !ValidateObject( objInRange )) return false; if( !ExistAndVerify( seInRange, "inRange" )) return false; jsval params[3], rval; JSObject *myObj; if( srcObj->CanBeObjType( OT_CHAR )) { myObj = JSEngine->AcquireObject( IUE_CHAR, srcObj, runTime ); } else { myObj = JSEngine->AcquireObject( IUE_ITEM, srcObj, runTime ); } JSObject *myObj2; if( objInRange->CanBeObjType( OT_CHAR )) { myObj2 = JSEngine->AcquireObject( IUE_CHAR, objInRange, runTime ); } else { myObj2 = JSEngine->AcquireObject( IUE_ITEM, objInRange, runTime ); } params[0] = OBJECT_TO_JSVAL( myObj ); params[1] = OBJECT_TO_JSVAL( myObj2 ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "inRange", 2, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seInRange, false ); } return ( retVal == JS_TRUE ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnCollide() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for object event is attached to when a character collides with it //o------------------------------------------------------------------------------------------------o SI08 cScript::OnCollide( CSocket *tSock, CChar *objColliding, CBaseObject *objCollideWith ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( objColliding ) || !ValidateObject( objCollideWith )) return RV_NOFUNC; if( !ExistAndVerify( seOnCollide, "onCollide" )) return RV_NOFUNC; jsval rval, params[3]; JSObject *myObj = JSEngine->AcquireObject( IUE_SOCK, tSock, runTime ); JSObject *charObj = JSEngine->AcquireObject( IUE_CHAR, objColliding, runTime ); JSObject *myObj2 = nullptr; if( objCollideWith->GetObjType() == OT_CHAR ) { myObj2 = JSEngine->AcquireObject( IUE_CHAR, objCollideWith, runTime ); } else { myObj2 = JSEngine->AcquireObject( IUE_ITEM, objCollideWith, runTime ); } params[0] = OBJECT_TO_JSVAL( myObj ); params[1] = OBJECT_TO_JSVAL( charObj ); params[2] = OBJECT_TO_JSVAL( myObj2 ); if( JS_CallFunctionName( targContext, targObject, "onCollide", 3, params, &rval ) == JS_FALSE ) { SetEventExists( seOnCollide, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnMoveDetect() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for object event is attached to when movement is detected within 5 tiles //o------------------------------------------------------------------------------------------------o SI08 cScript::OnMoveDetect( CBaseObject *sourceObj, CChar *charInRange, UI08 rangeToChar, UI16 oldCharX, UI16 oldCharY ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( sourceObj ) || !ValidateObject( charInRange )) return RV_NOFUNC; if( !ExistAndVerify( seOnMoveDetect, "onMoveDetect" )) return RV_NOFUNC; jsval rval, params[5]; JSObject *myObj = nullptr; if( sourceObj->GetObjType() == OT_CHAR ) { myObj = JSEngine->AcquireObject( IUE_CHAR, sourceObj, runTime ); } else { myObj = JSEngine->AcquireObject( IUE_ITEM, sourceObj, runTime ); } JSObject *charObj = JSEngine->AcquireObject( IUE_CHAR, charInRange, runTime ); params[0] = OBJECT_TO_JSVAL( myObj ); params[1] = OBJECT_TO_JSVAL( charObj ); params[2] = INT_TO_JSVAL( rangeToChar ); params[3] = INT_TO_JSVAL( oldCharX ); params[4] = INT_TO_JSVAL( oldCharY ); if( JS_CallFunctionName( targContext, targObject, "onMoveDetect", 5, params, &rval ) == JS_FALSE ) { SetEventExists( seOnMoveDetect, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnSteal() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for item with event attached when stolen //o------------------------------------------------------------------------------------------------o SI08 cScript::OnSteal( CChar *thief, CItem *theft, CChar *victim ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( thief ) || !ValidateObject( theft ) || !ValidateObject( victim )) return RV_NOFUNC; if( !ExistAndVerify( seOnSteal, "onSteal" )) return RV_NOFUNC; JSObject *thiefCharObj = JSEngine->AcquireObject( IUE_CHAR, thief, runTime ); JSObject *itemObj = JSEngine->AcquireObject( IUE_ITEM, theft, runTime ); JSObject *victimCharObj = JSEngine->AcquireObject( IUE_CHAR, victim, runTime ); jsval params[3], rval; params[0] = OBJECT_TO_JSVAL( thiefCharObj ); params[1] = OBJECT_TO_JSVAL( itemObj ); params[2] = OBJECT_TO_JSVAL( victimCharObj ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onSteal", 3, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnSteal, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnDispel() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for object with event attached when dispelled //o------------------------------------------------------------------------------------------------o SI08 cScript::OnDispel( CBaseObject *dispelled ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( dispelled )) return RV_NOFUNC; if( !ExistAndVerify( seOnDispel, "onDispel" )) return RV_NOFUNC; jsval params[2], rval; JSObject *myObj; if( dispelled->GetObjType() == OT_CHAR ) { myObj = JSEngine->AcquireObject( IUE_CHAR, dispelled, runTime ); params[1] = INT_TO_JSVAL( 0 ); } else { myObj = JSEngine->AcquireObject( IUE_ITEM, dispelled, runTime ); params[1] = INT_TO_JSVAL( 1 ); } params[0] = OBJECT_TO_JSVAL( myObj ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onDispel", 2, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnDispel, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnSkill() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for object with event attached when using a skill //o------------------------------------------------------------------------------------------------o //| Notes - If used WITH RegisterSkill() in a script listed under SKILLUSE_SCRIPTS in //| JSE_FILEASSOCIATIONS.SCP, event will trigger for only the specified skill. //| If used WITHOUT RegisterSkill() in a general purpose script listed under //| SCRIPT_LIST instead, event will be a global listener for ALL skills used //o------------------------------------------------------------------------------------------------o bool cScript::OnSkill( CBaseObject *skillUse, SI08 skillUsed ) { if( !ValidateObject( skillUse )) return false; if( !ExistAndVerify( seOnSkill, "onSkill" )) return false; jsval rval, params[3]; JSObject *myObj; if( skillUse->GetObjType() == OT_CHAR ) { myObj = JSEngine->AcquireObject( IUE_CHAR, skillUse, runTime ); params[2] = INT_TO_JSVAL( 0 ); } else { myObj = JSEngine->AcquireObject( IUE_ITEM, skillUse, runTime ); params[2] = INT_TO_JSVAL( 1 ); } params[0] = OBJECT_TO_JSVAL( myObj ); params[1] = INT_TO_JSVAL( skillUsed ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onSkill", 3, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnSkill, false ); } return ( retVal == JS_TRUE ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnTooltip() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for objects which server is about to send tooltip to client for //o------------------------------------------------------------------------------------------------o std::string cScript::OnTooltip( CBaseObject *myObj, CSocket *pSocket ) { if( !ValidateObject( myObj )) return ""; if( !ExistAndVerify( seOnTooltip, "onTooltip" )) return ""; jsval rval, params[2]; JSObject *tooltipObj = nullptr; if( myObj->CanBeObjType( OT_CHAR )) { tooltipObj = JSEngine->AcquireObject( IUE_CHAR, myObj, runTime ); } else if( myObj->CanBeObjType( OT_ITEM )) { tooltipObj = JSEngine->AcquireObject( IUE_ITEM, myObj, runTime ); } JSObject *sockObj = JSEngine->AcquireObject( IUE_SOCK, pSocket, runTime ); params[0] = OBJECT_TO_JSVAL( tooltipObj ); params[1] = OBJECT_TO_JSVAL( sockObj ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onTooltip", 2, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnTooltip, false ); } // If rval is negative, it's possible some other function/method called from within Ontooltip() encountered // an error. Abort attempt to turn it into a string - it might crash the server! if( rval < 0 ) { Console.Error( "Handled exception in cScript.cpp OnTooltip() - invalid return value/error encountered!" ); return ""; } try { JSString *str = JS_ValueToString( targContext, rval ); std::string returnString = JS_GetStringBytes( str ); return returnString; } catch( ... ) { Console.Error( "Handled exception in cScript.cpp OnTooltip()" ); return ""; } } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnNameRequest() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for objects which client has requested the name for //o------------------------------------------------------------------------------------------------o std::string cScript::OnNameRequest( CBaseObject *myObj, CChar *nameRequester, UI08 requestSource ) { if( !ValidateObject( myObj )) return ""; if( !ExistAndVerify( seOnNameRequest, "onNameRequest" )) return ""; // Prevent infinite loop if( myObj->NameRequestActive() ) return ""; // Mark object as having an active name lookup via onNameRequest myObj->NameRequestActive( true ); try { jsval rval, params[3]; // Create JS object reference for myObj, based on whether it's an item or character JSObject *nameRequestObj = nullptr; if( myObj->CanBeObjType( OT_CHAR )) { nameRequestObj = JSEngine->AcquireObject( IUE_CHAR, myObj, runTime ); } else if( myObj->CanBeObjType( OT_ITEM )) { nameRequestObj = JSEngine->AcquireObject( IUE_ITEM, myObj, runTime ); } // Create JS object reference for the name requester (which might be nullptr!) JSObject *nameRequesterObj = nullptr; if( nameRequester != nullptr ) { nameRequesterObj = JSEngine->AcquireObject( IUE_CHAR, nameRequester, runTime ); } params[0] = OBJECT_TO_JSVAL( nameRequestObj ); params[1] = OBJECT_TO_JSVAL( nameRequesterObj ); params[2] = INT_TO_JSVAL( requestSource ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onNameRequest", 3, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnNameRequest, false ); } // If rval is negative, it's possible some other function/method called from within onNameRequest() encountered // an error. Abort attempt to turn it into a string - it might crash the server! if( rval < 0 ) { Console.Error( "Handled exception in cScript.cpp OnNameRequest() - invalid return value/error encountered!" ); return ""; } JSString *str = JS_ValueToString( targContext, rval ); std::string returnString = JS_GetStringBytes( str ); // If no string was returned from the event, make sure we return an empty string instead of "undefined", "false" or "true" if( returnString == "undefined" || returnString == "false" || returnString == "true" ) { returnString = ""; } // Clear flag that marks object as having an active name lookup via onNameRequest myObj->NameRequestActive( false ); return returnString; } catch(...) { Console.Error( "Handled exception in cScript.cpp OnNameRequest()" ); // Clear flag that marks object as having an active name lookup via onNameRequest myObj->NameRequestActive( false ); } return ""; } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnAttack() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for character with event attached when attacking someone //| Will also trigger the onDefense event for the character being attacked //o------------------------------------------------------------------------------------------------o bool cScript::OnAttack( CChar *attacker, CChar *defender, bool hitStatus, SI08 hitLoc, UI16 damageDealt ) { if( !ValidateObject( attacker ) || !ValidateObject( defender )) return false; if( !ExistAndVerify( seOnAttack, "onAttack" )) return false; jsval rval, params[5]; JSObject *attObj = JSEngine->AcquireObject( IUE_CHAR, attacker, runTime ); JSObject *defObj = JSEngine->AcquireObject( IUE_CHAR, defender, runTime ); params[0] = OBJECT_TO_JSVAL( attObj ); params[1] = OBJECT_TO_JSVAL( defObj ); params[2] = BOOLEAN_TO_JSVAL( hitStatus ); params[3] = INT_TO_JSVAL( hitLoc ); params[4] = INT_TO_JSVAL( damageDealt ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onAttack", 5, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnAttack, false ); } return ( retVal == JS_TRUE ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnDefense() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for character with event attached when being attacked //o------------------------------------------------------------------------------------------------o bool cScript::OnDefense( CChar *attacker, CChar *defender, bool hitStatus, SI08 hitLoc, UI16 damageReceived ) { if( !ValidateObject( attacker ) || !ValidateObject( defender )) return false; if( !ExistAndVerify( seOnDefense, "onDefense" )) return false; jsval rval, params[5]; JSObject *attObj = JSEngine->AcquireObject( IUE_CHAR, attacker, runTime ); JSObject *defObj = JSEngine->AcquireObject( IUE_CHAR, defender, runTime ); params[0] = OBJECT_TO_JSVAL( attObj ); params[1] = OBJECT_TO_JSVAL( defObj ); params[2] = BOOLEAN_TO_JSVAL( hitStatus ); params[3] = INT_TO_JSVAL( hitLoc ); params[4] = INT_TO_JSVAL( damageReceived ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onDefense", 5, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnDefense, false ); } return ( retVal == JS_TRUE ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnSkillGain() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for character with event attached when gaining skillpoints //o------------------------------------------------------------------------------------------------o SI08 cScript::OnSkillGain( CChar *player, SI08 skill, UI32 skillGainAmount ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( player )) return RV_NOFUNC; if( !ExistAndVerify( seOnSkillGain, "onSkillGain" )) return RV_NOFUNC; jsval params[3], rval; JSObject *charObj = JSEngine->AcquireObject( IUE_CHAR, player, runTime ); params[0] = OBJECT_TO_JSVAL( charObj ); params[1] = INT_TO_JSVAL( skill ); params[2] = INT_TO_JSVAL( skillGainAmount ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onSkillGain", 3, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnSkillGain, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnStatGained() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for character with event attached when gaining stats //o------------------------------------------------------------------------------------------------o SI08 cScript::OnStatGained( CChar *player, UI32 stat, SI08 skill, UI32 statGainedAmount ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( player )) return RV_NOFUNC; if( !ExistAndVerify( seOnStatGained, "onStatGained" )) return RV_NOFUNC; jsval rval, params[4]; JSObject *charObj = JSEngine->AcquireObject( IUE_CHAR, player, runTime ); params[0] = OBJECT_TO_JSVAL( charObj ); params[1] = INT_TO_JSVAL( stat ); params[2] = INT_TO_JSVAL( skill ); params[3] = INT_TO_JSVAL( statGainedAmount ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onStatGained", 4, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnStatGained, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnStatGain() //o------------------------------------------------------------------------------------------------o //| Purpose - UNUSED //o------------------------------------------------------------------------------------------------o bool cScript::OnStatGain( CChar *player, UI32 stat, SI08 skill, UI32 statGainAmount ) { if( !ValidateObject( player )) return false; if( !ExistAndVerify( seOnStatGain, "onStatGain" )) return false; jsval rval, params[4]; JSObject *charObj = JSEngine->AcquireObject( IUE_CHAR, player, runTime ); params[0] = OBJECT_TO_JSVAL( charObj ); params[1] = INT_TO_JSVAL( stat ); params[2] = INT_TO_JSVAL( skill ); params[3] = INT_TO_JSVAL( statGainAmount ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onStatGain", 4, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnStatGain, false ); } return ( retVal == JS_TRUE ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnVirtueGumpPress() //| Date - 19/01/2020 //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for character with event attached when activating Virtue Gump icon //o------------------------------------------------------------------------------------------------o SI08 cScript::OnVirtueGumpPress( CChar *mChar, CChar *tChar, UI16 buttonId ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( mChar ) || !ValidateObject( tChar )) return RV_NOFUNC; if( !ExistAndVerify( seOnVirtueGumpPress, "onVirtueGumpPress" )) return RV_NOFUNC; jsval rval, params[3]; JSObject *charObj = JSEngine->AcquireObject( IUE_CHAR, mChar, runTime ); JSObject *targObj = JSEngine->AcquireObject( IUE_CHAR, tChar, runTime ); params[0] = OBJECT_TO_JSVAL( charObj ); params[1] = OBJECT_TO_JSVAL( targObj ); params[2] = INT_TO_JSVAL( buttonId ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onVirtueGumpPress", 3, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnVirtueGumpPress, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnQuestGump() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for character who activate Quest button in paperdoll //| Return true to prevent additional onQuestGump events from triggering //o------------------------------------------------------------------------------------------------o SI08 cScript::OnQuestGump( CChar *mChar ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( mChar )) return RV_NOFUNC; if( !ExistAndVerify( seOnQuestGump, "onQuestGump" )) return RV_NOFUNC; jsval rval, params[1]; JSObject *charObj = JSEngine->AcquireObject( IUE_CHAR, mChar, runTime ); params[0] = OBJECT_TO_JSVAL( charObj ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onQuestGump", 1, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnQuestGump, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnHelpButton() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for character who activate Help button in paperdoll //| Return false to prevent additional onHelpButton events from triggering //o------------------------------------------------------------------------------------------------o SI08 cScript::OnHelpButton( CChar *mChar ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( mChar )) return RV_NOFUNC; if( !ExistAndVerify( seOnHelpButton, "onHelpButton" )) return RV_NOFUNC; jsval rval, params[1]; JSObject *charObj = JSEngine->AcquireObject( IUE_CHAR, mChar, runTime ); params[0] = OBJECT_TO_JSVAL( charObj ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onHelpButton", 1, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnHelpButton, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnContextMenuRequest() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers when player activates context menu on another character //| Return false to prevent additional onContextMenu events from triggering //o------------------------------------------------------------------------------------------------o SI08 cScript::OnContextMenuRequest( CSocket *tSock, CBaseObject *baseObj ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( baseObj ) || tSock == nullptr ) return RV_NOFUNC; if( !ExistAndVerify( seOnContextMenuRequest, "onContextMenuRequest" )) return RV_NOFUNC; jsval rval, params[2]; JSObject *mySockObj = JSEngine->AcquireObject( IUE_SOCK, tSock, runTime ); JSObject *myObj = nullptr; if( baseObj->GetObjType() == OT_CHAR ) { myObj = JSEngine->AcquireObject( IUE_CHAR, baseObj, runTime ); } else { myObj = JSEngine->AcquireObject( IUE_ITEM, baseObj, runTime ); } params[0] = OBJECT_TO_JSVAL( mySockObj ); params[1] = OBJECT_TO_JSVAL( myObj ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onContextMenuRequest", 2, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnContextMenuRequest, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnContextMenuSelect() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers when player selects an entry from a popup context menu //| Return false to prevent additional onContextMenuSelect events from triggering //o------------------------------------------------------------------------------------------------o SI08 cScript::OnContextMenuSelect( CSocket *tSock, CBaseObject *baseObj, UI16 popupEntry ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( baseObj ) || tSock == nullptr ) return RV_NOFUNC; if( !ExistAndVerify( seOnContextMenuSelect, "onContextMenuSelect" )) return RV_NOFUNC; jsval rval, params[3]; JSObject *mySockObj = JSEngine->AcquireObject( IUE_SOCK, tSock, runTime ); JSObject *myObj = nullptr; if( baseObj->GetObjType() == OT_CHAR ) { myObj = JSEngine->AcquireObject( IUE_CHAR, baseObj, runTime ); } else { myObj = JSEngine->AcquireObject( IUE_ITEM, baseObj, runTime ); } params[0] = OBJECT_TO_JSVAL( mySockObj ); params[1] = OBJECT_TO_JSVAL( myObj ); params[2] = INT_TO_JSVAL( popupEntry ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onContextMenuSelect", 3, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnContextMenuSelect, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnWarModeToggle() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for character who toggle War Mode //| Return false to prevent character from entering War Mode //o------------------------------------------------------------------------------------------------o SI08 cScript::OnWarModeToggle( CChar *mChar ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( mChar )) return RV_NOFUNC; if( !ExistAndVerify( seOnWarModeToggle, "onWarModeToggle" )) return RV_NOFUNC; jsval rval, params[1]; JSObject *charObj = JSEngine->AcquireObject( IUE_CHAR, mChar, runTime ); params[0] = OBJECT_TO_JSVAL( charObj ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onWarModeToggle", 1, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnWarModeToggle, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::SI08() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for character who activate special abilities in combat books etc //o------------------------------------------------------------------------------------------------o SI08 cScript::OnSpecialMove( CChar *mChar, UI08 abilityId ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( mChar )) return RV_NOFUNC; if( !ExistAndVerify( seOnSpecialMove, "onSpecialMove" )) return RV_NOFUNC; jsval rval, params[2]; JSObject *charObj = JSEngine->AcquireObject( IUE_CHAR, mChar, runTime ); params[0] = OBJECT_TO_JSVAL( charObj ); params[1] = INT_TO_JSVAL( abilityId ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onSpecialMove", 2, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnSpecialMove, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnDrop() //| Date - 02/07/2004 //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for item with event attached when dropped by character //o------------------------------------------------------------------------------------------------o SI08 cScript::OnDrop( CItem *item, CChar *dropper ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( item ) || !ValidateObject( dropper )) return RV_NOFUNC; if( !ExistAndVerify( seOnDrop, "onDrop" )) return RV_NOFUNC; jsval params[2], rval; JSObject *charObj = JSEngine->AcquireObject( IUE_CHAR, dropper, runTime ); JSObject *itemObj = JSEngine->AcquireObject( IUE_ITEM, item, runTime ); params[0] = OBJECT_TO_JSVAL( itemObj ); params[1] = OBJECT_TO_JSVAL( charObj ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onDrop", 2, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnDrop, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnDropItemOnItem() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for item with event attached when dropping it on another item, or when //| another item is dropped on said item //o------------------------------------------------------------------------------------------------o SI08 cScript::OnDropItemOnItem( CItem *item, CChar *dropper, CItem *dest ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( item ) || !ValidateObject( dropper ) || !ValidateObject( dest )) return RV_NOFUNC; if( !ExistAndVerify( seOnDropItemOnItem, "onDropItemOnItem" )) return RV_NOFUNC; jsval params[3], rval; JSObject *charObj = JSEngine->AcquireObject( IUE_CHAR, dropper, runTime ); JSObject *itemObj = JSEngine->AcquireObject( IUE_ITEM, item, runTime ); JSObject *destObj = JSEngine->AcquireObject( IUE_ITEM, dest, runTime ); params[0] = OBJECT_TO_JSVAL( itemObj ); params[1] = OBJECT_TO_JSVAL( charObj ); params[2] = OBJECT_TO_JSVAL( destObj ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onDropItemOnItem", 3, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnDropItemOnItem, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnPickup() //| Date - 25/01/2007 //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for item with event attached when picked up by character //o------------------------------------------------------------------------------------------------o //| Changes - 16/07/2008 //| Adjustments made to fix event, which didn't trigger //o------------------------------------------------------------------------------------------------o SI08 cScript::OnPickup( CItem *item, CChar *pickerUpper, CBaseObject *objCont ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( item ) || !ValidateObject( pickerUpper )) return RV_NOFUNC; if( !ExistAndVerify( seOnPickup, "onPickup" )) return RV_NOFUNC; jsval params[3], rval; JSObject *charObj = JSEngine->AcquireObject( IUE_CHAR, pickerUpper, runTime ); JSObject *itemObj = JSEngine->AcquireObject( IUE_ITEM, item, runTime ); JSObject *objContObj = nullptr; if( objCont != nullptr ) { if( objCont->GetObjType() == OT_CHAR ) { objContObj = JSEngine->AcquireObject( IUE_CHAR, objCont, runTime ); } else { objContObj = JSEngine->AcquireObject( IUE_ITEM, objCont, runTime ); } } params[0] = OBJECT_TO_JSVAL( itemObj ); params[1] = OBJECT_TO_JSVAL( charObj ); params[2] = OBJECT_TO_JSVAL( objContObj ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onPickup", 3, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnPickup, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnContRemoveItem() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers on containers after an item has been removed from it //o------------------------------------------------------------------------------------------------o bool cScript::OnContRemoveItem( CItem *contItem, CItem *item, CChar *itemRemover ) { if( !ValidateObject( contItem ) || !ValidateObject( item )) return false; if( !ExistAndVerify( seOnContRemoveItem, "onContRemoveItem" )) return false; jsval params[3], rval; JSObject *contObj = JSEngine->AcquireObject( IUE_ITEM, contItem, runTime ); JSObject *itemObj = JSEngine->AcquireObject( IUE_ITEM, item, runTime ); JSObject *charObj = JSEngine->AcquireObject( IUE_CHAR, itemRemover, runTime ); params[0] = OBJECT_TO_JSVAL( contObj ); params[1] = OBJECT_TO_JSVAL( itemObj ); params[2] = OBJECT_TO_JSVAL( charObj ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onContRemoveItem", 3, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnContRemoveItem, false ); } return ( retVal == JS_TRUE ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnSwing() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for item event is attached to when swung in combat //o------------------------------------------------------------------------------------------------o SI08 cScript::OnSwing( CItem *swinging, CChar *swinger, CChar *swingTarg ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( swinger ) || !ValidateObject( swingTarg )) return RV_NOFUNC; if( !ExistAndVerify( seOnSwing, "onSwing" )) return RV_NOFUNC; JSObject *itemObj = ( ValidateObject( swinging ) ? JSEngine->AcquireObject( IUE_ITEM, swinging, runTime ) : nullptr ); JSObject *attObj = JSEngine->AcquireObject( IUE_CHAR, swinger, runTime ); JSObject *defObj = JSEngine->AcquireObject( IUE_CHAR, swingTarg, runTime ); jsval params[3], rval; params[0] = OBJECT_TO_JSVAL( itemObj ); params[1] = OBJECT_TO_JSVAL( attObj ); params[2] = OBJECT_TO_JSVAL( defObj ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onSwing", 3, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnSwing, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnDecay() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for item event is attached to when about to decay //o------------------------------------------------------------------------------------------------o SI08 cScript::OnDecay( CItem *decaying ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( decaying )) return RV_NOFUNC; if( !ExistAndVerify( seOnDecay, "onDecay" )) return RV_NOFUNC; jsval params[1], rval; JSObject *myObj = JSEngine->AcquireObject( IUE_ITEM, decaying, runTime ); params[0] = OBJECT_TO_JSVAL( myObj ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onDecay", 1, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnDecay, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnReleasePet() //| Purpose - Script trigger for when a player tries to release a pet //o------------------------------------------------------------------------------------------------o SI08 cScript::OnReleasePet( CChar *owner, CChar *pet ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( owner ) || !ValidateObject( pet )) return RV_NOFUNC; if( !ExistAndVerify( seOnReleasePet, "onReleasePet" )) return RV_NOFUNC; jsval params[2], rval; JSObject *ownerObj = JSEngine->AcquireObject( IUE_CHAR, owner, runTime ); JSObject *petObj = JSEngine->AcquireObject( IUE_CHAR, pet, runTime ); params[0] = OBJECT_TO_JSVAL( ownerObj ); params[1] = OBJECT_TO_JSVAL( petObj ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onReleasePet", 2, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnReleasePet, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnLeaving() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for character with event attached when leaving a multi //o------------------------------------------------------------------------------------------------o SI08 cScript::OnLeaving( CMultiObj *left, CBaseObject *leaving ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( left ) || !ValidateObject( leaving )) return RV_NOFUNC; if( !ExistAndVerify( seOnLeaving, "onLeaving" )) return RV_NOFUNC; jsval params[3], rval; JSObject *myObj; JSObject *myItem = JSEngine->AcquireObject( IUE_ITEM, left, runTime ); if( leaving->GetObjType() == OT_CHAR ) { myObj = JSEngine->AcquireObject( IUE_CHAR, leaving, runTime ); params[2] = INT_TO_JSVAL( 0 ); } else { myObj = JSEngine->AcquireObject( IUE_ITEM, leaving, runTime ); params[2] = INT_TO_JSVAL( 1 ); } params[0] = OBJECT_TO_JSVAL( myItem ); params[1] = OBJECT_TO_JSVAL( myObj ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onLeaving", 3, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnLeaving, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnMultiLogout() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for multi when a player logs out inside the multi //o------------------------------------------------------------------------------------------------o SI08 cScript::OnMultiLogout( CMultiObj *iMulti, CChar *cPlayer ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( iMulti ) || !ValidateObject( cPlayer )) return RV_NOFUNC; if( !ExistAndVerify( seOnMultiLogout, "onMultiLogout" )) return RV_NOFUNC; jsval params[2], rval; JSObject *myMulti = JSEngine->AcquireObject( IUE_ITEM, iMulti, runTime ); JSObject *myPlayer = JSEngine->AcquireObject( IUE_CHAR, cPlayer, runTime ); params[0] = OBJECT_TO_JSVAL( myMulti ); params[1] = OBJECT_TO_JSVAL( myPlayer ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onMultiLogout", 2, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnMultiLogout, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnBoatTurn() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for Boat after it has turned successfully //o------------------------------------------------------------------------------------------------o SI08 cScript::OnBoatTurn( CBoatObj *iBoat, UI08 oldDir, UI08 newDir, CItem *iTiller ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( iBoat )) return RV_NOFUNC; if( !ExistAndVerify( seOnBoatTurn, "onBoatTurn" )) return RV_NOFUNC; jsval params[4], rval; JSObject *myBoat = JSEngine->AcquireObject( IUE_ITEM, iBoat, runTime ); JSObject *myTiller = JSEngine->AcquireObject( IUE_ITEM, iTiller, runTime ); params[0] = OBJECT_TO_JSVAL( myBoat ); params[1] = INT_TO_JSVAL( oldDir ); params[2] = INT_TO_JSVAL( newDir ); params[3] = OBJECT_TO_JSVAL( myTiller ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onBoatTurn", 4, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnBoatTurn, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnEquipAttempt() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for item with event attached when character tries to equip it //o------------------------------------------------------------------------------------------------o SI08 cScript::OnEquipAttempt( CChar *equipper, CItem *equipping ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( equipper ) || !ValidateObject( equipping )) return RV_NOFUNC; if( !ExistAndVerify( seOnEquipAttempt, "onEquipAttempt" )) return RV_NOFUNC; jsval rval, params[2]; JSObject *charObj = JSEngine->AcquireObject( IUE_CHAR, equipper, runTime ); JSObject *itemObj = JSEngine->AcquireObject( IUE_ITEM, equipping, runTime ); params[0] = OBJECT_TO_JSVAL( charObj ); params[1] = OBJECT_TO_JSVAL( itemObj ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onEquipAttempt", 2, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnEquipAttempt, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnEquip() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for item with event attached when equipped by a character //o------------------------------------------------------------------------------------------------o SI08 cScript::OnEquip( CChar *equipper, CItem *equipping ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( equipper ) || !ValidateObject( equipping )) return RV_NOFUNC; if( !ExistAndVerify( seOnEquip, "onEquip" )) return RV_NOFUNC; jsval rval, params[2]; JSObject *charObj = JSEngine->AcquireObject( IUE_CHAR, equipper, runTime ); JSObject *itemObj = JSEngine->AcquireObject( IUE_ITEM, equipping, runTime ); params[0] = OBJECT_TO_JSVAL( charObj ); params[1] = OBJECT_TO_JSVAL( itemObj ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onEquip", 2, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnEquip, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnUnequipAttempt() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for item with event attached when unequipped by a character //o------------------------------------------------------------------------------------------------o SI08 cScript::OnUnequipAttempt( CChar *equipper, CItem *equipping ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( equipper ) || !ValidateObject( equipping )) return RV_NOFUNC; if( !ExistAndVerify( seOnUnequipAttempt, "onUnequipAttempt" )) return RV_NOFUNC; jsval rval, params[2]; JSObject *charObj = JSEngine->AcquireObject( IUE_CHAR, equipper, runTime ); JSObject *itemObj = JSEngine->AcquireObject( IUE_ITEM, equipping, runTime ); params[0] = OBJECT_TO_JSVAL( charObj ); params[1] = OBJECT_TO_JSVAL( itemObj ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onUnequipAttempt", 2, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnUnequipAttempt, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnUnequip() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for item with event attached when unequipped by a character //o------------------------------------------------------------------------------------------------o SI08 cScript::OnUnequip( CChar *equipper, CItem *equipping ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( equipper ) || !ValidateObject( equipping )) return RV_NOFUNC; if( !ExistAndVerify( seOnUnequip, "onUnequip" )) return RV_NOFUNC; jsval rval, params[2]; JSObject *charObj = JSEngine->AcquireObject( IUE_CHAR, equipper, runTime ); JSObject *itemObj = JSEngine->AcquireObject( IUE_ITEM, equipping, runTime ); params[0] = OBJECT_TO_JSVAL( charObj ); params[1] = OBJECT_TO_JSVAL( itemObj ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onUnequip", 2, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnUnequip, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnUseChecked() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers (after hardcoded checks) for item with event attached, when used //o------------------------------------------------------------------------------------------------o //| Notes - The function returns 3 possible values //| -1 => No such function or bad call //| 0 => Don't execute hard coded implementation //| 1 => Execute hard coded implementations as well //o------------------------------------------------------------------------------------------------o //| Changes - 31 July, 2003 15:39 ( making it version 3) //| Changed return values from bool to SI08 //| 27 October, 2007 //| Split onUse into onUseChecked and onUseUnChecked //o------------------------------------------------------------------------------------------------o SI08 cScript::OnUseChecked( CChar *user, CItem *iUsing ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( user ) || !ValidateObject( iUsing )) return RV_NOFUNC; if( !ExistAndVerify( seOnUseChecked, "onUseChecked" )) return RV_NOFUNC; jsval rval, params[2]; JSObject *charObj = JSEngine->AcquireObject( IUE_CHAR, user, runTime ); JSObject *itemObj = JSEngine->AcquireObject( IUE_ITEM, iUsing, runTime ); params[0] = OBJECT_TO_JSVAL( charObj ); params[1] = OBJECT_TO_JSVAL( itemObj ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onUseChecked", 2, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnUseChecked, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnUseUnChecked() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers (before hardcoded checks) for item with event attached, when used //o------------------------------------------------------------------------------------------------o //| Notes - The function returns 3 possible values //| -1 => No such function or bad call //| 0 => Don't execute hard coded implementation //| 1 => Execute hard coded implementations as well //o------------------------------------------------------------------------------------------------o //| Changes - 31 July, 2003 15:39 ( making it version 3) //| Changed return values from bool to SI08 //| 27 October, 2007 //| Split onUse into onUseChecked and onUseUnChecked //o------------------------------------------------------------------------------------------------o SI08 cScript::OnUseUnChecked( CChar *user, CItem *iUsing ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( user ) || !ValidateObject( iUsing )) return RV_NOFUNC; if( !ExistAndVerify( seOnUseUnChecked, "onUseUnChecked" )) return RV_NOFUNC; jsval rval, params[2]; JSObject *charObj = JSEngine->AcquireObject( IUE_CHAR, user, runTime ); JSObject *itemObj = JSEngine->AcquireObject( IUE_ITEM, iUsing, runTime ); params[0] = OBJECT_TO_JSVAL( charObj ); params[1] = OBJECT_TO_JSVAL( itemObj ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onUseUnChecked", 2, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnUseUnChecked, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnDropItemOnNpc() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for item with event attached when dropped on an NPC, and for NPC with //| event attached if item is dropped on it and doesn't bounce in item's script //o------------------------------------------------------------------------------------------------o //| Changes - V2 - //| Returns //| -1 if no function exists //| 0 if should bounce //| 1 if should not bounce and use code //| 2 if should not bounce and not use code //o------------------------------------------------------------------------------------------------o SI08 cScript::OnDropItemOnNpc( CChar *srcChar, CChar *dstChar, CItem *item ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( srcChar ) || !ValidateObject( dstChar ) || !ValidateObject( item )) return RV_NOFUNC; if( !ExistAndVerify( seOnDropItemOnNpc, "onDropItemOnNpc" )) return RV_NOFUNC; jsval rval, params[3]; JSObject *srcObj = JSEngine->AcquireObject( IUE_CHAR, srcChar, runTime ); JSObject *dstObj = JSEngine->AcquireObject( IUE_CHAR, dstChar, runTime ); JSObject *itemObj = JSEngine->AcquireObject( IUE_ITEM, item, runTime ); params[0] = OBJECT_TO_JSVAL( srcObj ); params[1] = OBJECT_TO_JSVAL( dstObj ); params[2] = OBJECT_TO_JSVAL( itemObj ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onDropItemOnNpc", 3, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnDropItemOnNpc, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnEntrance() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for character with event attached when entering a multi //o------------------------------------------------------------------------------------------------o SI08 cScript::OnEntrance( CMultiObj *left, CBaseObject *leaving ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( left ) || !ValidateObject( leaving )) return RV_NOFUNC; if( !ExistAndVerify( seOnEntrance, "onEntrance" )) return RV_NOFUNC; jsval params[3], rval; JSObject *myObj; JSObject *myItem = JSEngine->AcquireObject( IUE_ITEM, left, runTime ); if( leaving->GetObjType() == OT_CHAR ) { myObj = JSEngine->AcquireObject( IUE_CHAR, leaving, runTime ); params[2] = INT_TO_JSVAL( 0 ); } else { myObj = JSEngine->AcquireObject( IUE_ITEM, leaving, runTime ); params[2] = INT_TO_JSVAL( 1 ); } params[0] = OBJECT_TO_JSVAL( myItem ); params[1] = OBJECT_TO_JSVAL( myObj ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onEntrance", 3, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnEntrance, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OutOfRange() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for character with event attached when objects go out of range //| Notes - A third parameter in the event can be used to determine whether the object //| going out of range is an ITEM or a CHARACTER //o------------------------------------------------------------------------------------------------o bool cScript::OutOfRange( CBaseObject *srcObj, CBaseObject *objVanish ) { if( !ValidateObject( srcObj ) || !ValidateObject( objVanish )) return false; if( !ExistAndVerify( seOutOfRange, "outOfRange" )) return false; jsval params[2], rval; JSObject *myObj; if( srcObj->GetObjType() == OT_CHAR ) { myObj = JSEngine->AcquireObject( IUE_CHAR, srcObj, runTime ); } else { myObj = JSEngine->AcquireObject( IUE_ITEM, srcObj, runTime ); } JSObject *myObj2; if( objVanish->GetObjType() == OT_CHAR ) { myObj2 = JSEngine->AcquireObject( IUE_CHAR, objVanish, runTime ); } else { myObj2 = JSEngine->AcquireObject( IUE_ITEM, objVanish, runTime ); } params[0] = OBJECT_TO_JSVAL( myObj ); params[1] = OBJECT_TO_JSVAL( myObj2 ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "outOfRange", 2, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOutOfRange, false ); } return ( retVal == JS_TRUE ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnLogin() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for character with event attached when logging on to server //o------------------------------------------------------------------------------------------------o bool cScript::OnLogin( CSocket *sockPlayer, CChar *pPlayer ) { if( !ValidateObject( pPlayer )) return false; if( !ExistAndVerify( seOnLogin, "onLogin" )) return false; jsval params[2], rval; JSObject *sockObj = JSEngine->AcquireObject( IUE_SOCK, sockPlayer, runTime ); JSObject *charObj = JSEngine->AcquireObject( IUE_CHAR, pPlayer, runTime ); params[0] = OBJECT_TO_JSVAL( sockObj ); params[1] = OBJECT_TO_JSVAL( charObj ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onLogin", 2, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnLogin, false ); } return ( retVal == JS_TRUE ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnLogout() //| Date - 10/06/2002 //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for character with event attached when logging out of server //o------------------------------------------------------------------------------------------------o bool cScript::OnLogout( CSocket *sockPlayer, CChar *pPlayer ) { if( !ValidateObject( pPlayer )) return false; if( !ExistAndVerify( seOnLogout, "onLogout" )) return false; jsval params[2], rval; JSObject *sockObj = JSEngine->AcquireObject( IUE_SOCK, sockPlayer, runTime ); JSObject *charObj = JSEngine->AcquireObject( IUE_CHAR, pPlayer, runTime ); params[0] = OBJECT_TO_JSVAL( sockObj ); params[1] = OBJECT_TO_JSVAL( charObj ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onLogout", 2, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnLogout, false ); } return ( retVal == JS_TRUE ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnClick() //| Date - 10/06/2002 //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for item with event attached when a player single-clicks on it //o------------------------------------------------------------------------------------------------o SI08 cScript::OnClick( CSocket *sockPlayer, CBaseObject *objClicked ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( objClicked )) return false; if( !ExistAndVerify( seOnClick, "onClick" )) return RV_NOFUNC; JSObject *sockObj = JSEngine->AcquireObject( IUE_SOCK, sockPlayer, runTime ); JSObject *myObj; if( objClicked->GetObjType() == OT_CHAR ) { myObj = JSEngine->AcquireObject( IUE_CHAR, objClicked, runTime ); } else { myObj = JSEngine->AcquireObject( IUE_ITEM, objClicked, runTime ); } jsval params[2], rval; params[0] = OBJECT_TO_JSVAL( sockObj ); params[1] = OBJECT_TO_JSVAL( myObj ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onClick", 2, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnClick, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnFall() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for character with event attached when fallDistance is over 20 //o------------------------------------------------------------------------------------------------o bool cScript::OnFall( CChar *pFall, SI08 fallDistance ) { if( !ValidateObject( pFall )) return false; if( !ExistAndVerify( seOnFall, "onFall" )) return false; jsval params[2], rval; JSObject *charObj = JSEngine->AcquireObject( IUE_CHAR, pFall, runTime ); params[0] = OBJECT_TO_JSVAL( charObj ); params[1] = INT_TO_JSVAL( fallDistance ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onFall", 2, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnFall, false ); } return ( retVal == JS_TRUE ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnAISliver() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers on every AI loop for character with event attached //o------------------------------------------------------------------------------------------------o SI08 cScript::OnAISliver( CChar *pSliver ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( pSliver )) return RV_NOFUNC; if( !ExistAndVerify( seOnAISliver, "onAISliver" )) return RV_NOFUNC; jsval params[1], rval; JSObject *charObj = JSEngine->AcquireObject( IUE_CHAR, pSliver, runTime ); params[0] = OBJECT_TO_JSVAL( charObj ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onAISliver", 1, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnAISliver, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnSystemSlice() //o------------------------------------------------------------------------------------------------o //| Purpose - UNUSED //o------------------------------------------------------------------------------------------------o bool cScript::OnSystemSlice( void ) { if( !ExistAndVerify( seOnSystemSlice, "onSystemSlice" )) return false; jsval rval; JSBool retVal = JS_CallFunctionName( targContext, targObject, "onSystemSlice", 0, nullptr, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnSystemSlice, false ); } return false; } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnLightChange() //| Date - 17/02/2006 //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for object with event attached when lightlevel changes //o------------------------------------------------------------------------------------------------o SI08 cScript::OnLightChange( CBaseObject *tObject, UI08 lightLevel ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( tObject )) return RV_NOFUNC; if( !ExistAndVerify( seOnLightChange, "onLightChange" )) return RV_NOFUNC; jsval rval, params[2]; JSObject *myObj; if( tObject->GetObjType() == OT_CHAR ) { myObj = JSEngine->AcquireObject( IUE_CHAR, tObject, runTime ); } else { myObj = JSEngine->AcquireObject( IUE_ITEM, tObject, runTime ); } params[0] = OBJECT_TO_JSVAL( myObj ); params[1] = INT_TO_JSVAL( lightLevel ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onLightChange", 2, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnLightChange, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnWeatherChange() //| Date - 17/02/2006 //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for object with event attached when weather changes //o------------------------------------------------------------------------------------------------o bool cScript::OnWeatherChange( CBaseObject *tObject, WeatherType element ) { if( !ValidateObject( tObject )) return false; if( !ExistAndVerify( seOnWeatherChange, "onWeatherChange" )) return false; jsval rval, params[2]; JSObject *myObj; if( tObject->GetObjType() == OT_CHAR ) { myObj = JSEngine->AcquireObject( IUE_CHAR, tObject, runTime ); } else { myObj = JSEngine->AcquireObject( IUE_ITEM, tObject, runTime ); } params[0] = OBJECT_TO_JSVAL( myObj ); params[1] = INT_TO_JSVAL( element ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onWeatherChange", 2, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnWeatherChange, false ); } return ( retVal == JS_TRUE ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::cScript::OnTempChange() //| Date - 17/02/2006 //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for object with event attached when temperature changes //o------------------------------------------------------------------------------------------------o bool cScript::OnTempChange( CBaseObject *tObject, SI08 temp ) { if( !ValidateObject( tObject )) return false; if( !ExistAndVerify( seOnTempChange, "onTempChange" )) return false; jsval rval, params[2]; JSObject *myObj; if( tObject->GetObjType() == OT_CHAR ) { myObj = JSEngine->AcquireObject( IUE_CHAR, tObject, runTime ); } else { myObj = JSEngine->AcquireObject( IUE_ITEM, tObject, runTime ); } params[0] = OBJECT_TO_JSVAL( myObj ); params[1] = INT_TO_JSVAL( temp ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onTempChange", 2, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnTempChange, false ); } return ( retVal == JS_TRUE ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnTimer() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for object with event attached, when custom timers started on said //| object using StartTimer function update //o------------------------------------------------------------------------------------------------o bool cScript::OnTimer( CBaseObject *tObject, UI16 timerId ) { if( !ValidateObject( tObject )) return false; if( !ExistAndVerify( seOnTimer, "onTimer" )) return false; jsval rval, params[2]; JSObject *myObj; if( tObject->GetObjType() == OT_CHAR ) { myObj = JSEngine->AcquireObject( IUE_CHAR, tObject, runTime ); } else { myObj = JSEngine->AcquireObject( IUE_ITEM, tObject, runTime ); } params[0] = OBJECT_TO_JSVAL( myObj ); params[1] = INT_TO_JSVAL( timerId ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onTimer", 2, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnTimer, false ); } return ( retVal == JS_TRUE ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnStatLoss() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for characters with event attached when losing stats //o------------------------------------------------------------------------------------------------o SI08 cScript::OnStatLoss( CChar *player, UI32 stat, UI32 statLossAmount ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( player )) return RV_NOFUNC; if( !ExistAndVerify( seOnStatLoss, "onStatLoss" )) return RV_NOFUNC; jsval rval, params[3]; JSObject *charObj = JSEngine->AcquireObject( IUE_CHAR, player, runTime ); params[0] = OBJECT_TO_JSVAL( charObj ); params[1] = INT_TO_JSVAL( stat ); params[2] = INT_TO_JSVAL( statLossAmount ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onStatLoss", 3, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnStatLoss, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnStatChange() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for characters with event attached when stats change //o------------------------------------------------------------------------------------------------o bool cScript::OnStatChange( CChar *player, UI32 stat, SI32 statChangeAmount ) { if( !ValidateObject( player )) return false; if( !ExistAndVerify( seOnStatChange, "onStatChange" )) return false; jsval rval, params[3]; JSObject *charObj = JSEngine->AcquireObject( IUE_CHAR, player, runTime ); params[0] = OBJECT_TO_JSVAL( charObj ); params[1] = INT_TO_JSVAL( stat ); params[2] = INT_TO_JSVAL( statChangeAmount ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onStatChange", 3, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnStatChange, false ); } return ( retVal == JS_TRUE ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnSkillLoss() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for characters with event attached when losing skillpoints //o------------------------------------------------------------------------------------------------o SI08 cScript::OnSkillLoss( CChar *player, SI08 skill, UI32 skillLossAmount ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( player )) return RV_NOFUNC; if( !ExistAndVerify( seOnSkillLoss, "onSkillLoss" )) return RV_NOFUNC; jsval params[3], rval; JSObject *charObj = JSEngine->AcquireObject( IUE_CHAR, player, runTime ); params[0] = OBJECT_TO_JSVAL( charObj ); params[1] = INT_TO_JSVAL( skill ); params[2] = INT_TO_JSVAL( skillLossAmount ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onSkillLoss", 3, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnSkillLoss, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnSkillChange() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for characters with event attached when skillpoints change //o------------------------------------------------------------------------------------------------o bool cScript::OnSkillChange( CChar *player, SI08 skill, SI32 skillChangeAmount ) { if( !ValidateObject( player )) return false; if( !ExistAndVerify( seOnSkillChange, "onSkillChange" )) return false; jsval params[3], rval; JSObject *charObj = JSEngine->AcquireObject( IUE_CHAR, player, runTime ); params[0] = OBJECT_TO_JSVAL( charObj ); params[1] = INT_TO_JSVAL( skill ); params[2] = INT_TO_JSVAL( skillChangeAmount ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onSkillChange", 3, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnSkillChange, false ); } return ( retVal == JS_TRUE ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnDeath() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for character with event attached after dying //o------------------------------------------------------------------------------------------------o SI08 cScript::OnDeath( CChar *pDead, CItem *iCorpse ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( pDead ) || !ValidateObject( iCorpse )) return RV_NOFUNC; if( !ExistAndVerify( seOnDeath, "onDeath" )) return RV_NOFUNC; jsval params[2], rval; JSObject *charObj = JSEngine->AcquireObject( IUE_CHAR, pDead, runTime ); JSObject *corpseObj = JSEngine->AcquireObject( IUE_ITEM, iCorpse, runTime ); params[0] = OBJECT_TO_JSVAL( charObj ); params[1] = OBJECT_TO_JSVAL( corpseObj ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onDeath", 2, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnDeath, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnResurrect() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for character with event attached when being resurrected //| Notes - If script returns false when event triggers, resurrection is blocked //o------------------------------------------------------------------------------------------------o SI08 cScript::OnResurrect( CChar *pAlive ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( pAlive )) return RV_NOFUNC; if( !ExistAndVerify( seOnResurrect, "onResurrect" )) return RV_NOFUNC; jsval params[1], rval; JSObject *charObj = JSEngine->AcquireObject( IUE_CHAR, pAlive, runTime ); params[0] = OBJECT_TO_JSVAL( charObj ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onResurrect", 1, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnResurrect, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnFlagChange() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for character with event attached when the flag status changes //o------------------------------------------------------------------------------------------------o SI08 cScript::OnFlagChange( CChar *pChanging, UI08 newStatus, UI08 oldStatus ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( pChanging )) return RV_NOFUNC; if( !ExistAndVerify( seOnFlagChange, "onFlagChange" )) return RV_NOFUNC; jsval params[3], rval; JSObject *charObj = JSEngine->AcquireObject( IUE_CHAR, pChanging, runTime ); params[0] = OBJECT_TO_JSVAL( charObj ); params[1] = INT_TO_JSVAL( newStatus ); params[2] = INT_TO_JSVAL( oldStatus ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onFlagChange", 3, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnFlagChange, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::DoCallback() //o------------------------------------------------------------------------------------------------o //| Purpose - Handles callbacks for custom target cursors triggered from scripts //o------------------------------------------------------------------------------------------------o bool cScript::DoCallback( CSocket *tSock, SERIAL targeted, UI08 callNum ) { if( tSock == nullptr ) return false; jsval params[2], rval; SI32 objType = 2; // 2 == null, 1 == char, 0 == item CBaseObject *mObj = nullptr; JSObject *myObj2 = nullptr; try { JSObject *myObj = JSEngine->AcquireObject( IUE_SOCK, tSock, runTime ); if( myObj == nullptr ) return false; params[0] = OBJECT_TO_JSVAL( myObj ); if( targeted >= BASEITEMSERIAL ) { mObj = CalcItemObjFromSer( targeted ); objType = 0; } else { mObj = CalcCharObjFromSer( targeted ); objType = 1; } if( !ValidateObject( mObj )) { objType = 2; params[1] = JSVAL_NULL; } else { if( objType == 0 ) { myObj2 = JSEngine->AcquireObject( IUE_ITEM, mObj, runTime ); } else { myObj2 = JSEngine->AcquireObject( IUE_CHAR, mObj, runTime ); } params[1] = OBJECT_TO_JSVAL( myObj2 ); } // ExistAndVerify() normally sets our Global Object, but not on custom named functions. JS_SetGlobalObject( targContext, targObject ); JSBool retVal = JS_CallFunctionName( targContext, targObject, oldstrutil::format( "onCallback%i", callNum ).c_str(), 2, params, &rval ); return ( retVal == JS_TRUE ); } catch( ... ) { Console.Error( "Handled exception in cScript.cpp DoCallback()" ); } return false; } JSObject *cScript::Object( void ) const { return targObject; } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnLoyaltyChange() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for NPC character with event attached when loyalty level changes //o------------------------------------------------------------------------------------------------o SI08 cScript::OnLoyaltyChange( CChar *pChanging, SI08 newStatus ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( pChanging )) return RV_NOFUNC; if( !ExistAndVerify( seOnLoyaltyChange, "onLoyaltyChange" )) return RV_NOFUNC; jsval params[2], rval; JSObject *charObj = JSEngine->AcquireObject( IUE_CHAR, pChanging, runTime ); params[0] = OBJECT_TO_JSVAL( charObj ); params[1] = INT_TO_JSVAL( newStatus ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onLoyaltyChange", 2, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnLoyaltyChange, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnHungerChange() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for character with event attached when hunger level changes //o------------------------------------------------------------------------------------------------o SI08 cScript::OnHungerChange( CChar *pChanging, SI08 newStatus ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( pChanging )) return RV_NOFUNC; if( !ExistAndVerify( seOnHungerChange, "onHungerChange" )) return RV_NOFUNC; jsval params[2], rval; JSObject *charObj = JSEngine->AcquireObject( IUE_CHAR, pChanging, runTime ); params[0] = OBJECT_TO_JSVAL( charObj ); params[1] = INT_TO_JSVAL( newStatus ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onHungerChange", 2, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnHungerChange, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnThirstChange() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for character with event attached when thirst level changes //o------------------------------------------------------------------------------------------------o bool cScript::OnThirstChange( CChar* pChanging, SI08 newStatus ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( pChanging )) return RV_NOFUNC; if( !ExistAndVerify( seOnThirstChange, "onThirstChange" )) return RV_NOFUNC; jsval params[2], rval; JSObject* charObj = JSEngine->AcquireObject( IUE_CHAR, pChanging, runTime ); params[0] = OBJECT_TO_JSVAL( charObj ); params[1] = INT_TO_JSVAL( newStatus ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onThirstChange", 2, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnThirstChange, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnStolenFrom() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for character with event attached when being stolen from //o------------------------------------------------------------------------------------------------o SI08 cScript::OnStolenFrom( CChar *stealing, CChar *stolenFrom, CItem *stolen ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( stealing ) || !ValidateObject( stolenFrom ) || !ValidateObject( stolen )) return RV_NOFUNC; if( !ExistAndVerify( seOnStolenFrom, "onStolenFrom" )) return RV_NOFUNC; jsval params[3], rval; JSObject *thiefObj = JSEngine->AcquireObject( IUE_CHAR, stealing, runTime ); JSObject *victimObj = JSEngine->AcquireObject( IUE_CHAR, stolenFrom, runTime ); JSObject *itemObj = JSEngine->AcquireObject( IUE_ITEM, stolen, runTime ); params[0] = OBJECT_TO_JSVAL( thiefObj ); params[1] = OBJECT_TO_JSVAL( victimObj ); params[2] = OBJECT_TO_JSVAL( itemObj ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onStolenFrom", 3, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnStolenFrom, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnSnooped() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for character with event attached when someone snoops their backpack //o------------------------------------------------------------------------------------------------o SI08 cScript::OnSnooped( CChar *snooped, CChar *snooper, bool success ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( snooped ) || !ValidateObject( snooper )) return RV_NOFUNC; if( !ExistAndVerify( seOnSnooped, "onSnooped" )) return RV_NOFUNC; jsval params[3], rval; JSObject *thiefObj = JSEngine->AcquireObject( IUE_CHAR, snooped, runTime ); JSObject *victimObj = JSEngine->AcquireObject( IUE_CHAR, snooper, runTime ); params[0] = OBJECT_TO_JSVAL( thiefObj ); params[1] = OBJECT_TO_JSVAL( victimObj ); params[2] = BOOLEAN_TO_JSVAL( success ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onSnooped", 3, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnSnooped, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnSnoopAttempt() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for character with event attached if they attempt to snoop someone's backpack //o------------------------------------------------------------------------------------------------o SI08 cScript::OnSnoopAttempt( CChar *snooped, CItem *pack, CChar *snooper ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( snooped ) || !ValidateObject( pack ) || !ValidateObject( snooper )) return RV_NOFUNC; if( !ExistAndVerify( seOnSnoopAttempt, "onSnoopAttempt" )) return RV_NOFUNC; jsval params[3], rval; JSObject *thiefObj = JSEngine->AcquireObject( IUE_CHAR, snooped, runTime ); JSObject *packObj = JSEngine->AcquireObject( IUE_ITEM, pack, runTime ); JSObject *victimObj = JSEngine->AcquireObject( IUE_CHAR, snooper, runTime ); params[0] = OBJECT_TO_JSVAL( thiefObj ); params[1] = OBJECT_TO_JSVAL( packObj ); params[2] = OBJECT_TO_JSVAL( victimObj ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onSnoopAttempt", 3, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnSnoopAttempt, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::NewGumpList() //o------------------------------------------------------------------------------------------------o //| Purpose - UNUSED //o------------------------------------------------------------------------------------------------o size_t cScript::NewGumpList( void ) { size_t retVal = gumpDisplays.size(); SEGump_st *toAdd = new SEGump_st; toAdd->one = new std::vector<std::string>(); toAdd->two = new std::vector<std::string>(); gumpDisplays.push_back( toAdd ); return retVal; } //o------------------------------------------------------------------------------------------------o //| Function - cScript::GetGumpList() //o------------------------------------------------------------------------------------------------o //| Purpose - UNUSED //o------------------------------------------------------------------------------------------------o SEGump_st * cScript::GetGumpList( SI32 index ) { if( index < 0 || static_cast<size_t>( index ) >= gumpDisplays.size() ) return nullptr; return gumpDisplays[index]; } //o------------------------------------------------------------------------------------------------o //| Function - cScript::RemoveGumpList() //o------------------------------------------------------------------------------------------------o //| Purpose - UNUSED //o------------------------------------------------------------------------------------------------o void cScript::RemoveGumpList( SI32 index ) { if( index < 0 || static_cast<size_t>( index ) >= gumpDisplays.size() ) return; delete gumpDisplays[index]->one; delete gumpDisplays[index]->two; delete gumpDisplays[index]; gumpDisplays.erase( gumpDisplays.begin() + index ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::SendGumpList() //o------------------------------------------------------------------------------------------------o //| Purpose - UNUSED //o------------------------------------------------------------------------------------------------o void cScript::SendGumpList( SI32 index, CSocket *toSendTo ) { if( index < 0 || static_cast<size_t>( index ) >= gumpDisplays.size() ) return; UI32 gumpId = (0xFFFF + JSMapping->GetScriptId( targObject )); SendVecsAsGump( toSendTo, *( gumpDisplays[index]->one ), *( gumpDisplays[index]->two ), gumpId, INVALIDSERIAL ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::HandleGumpPress() //o------------------------------------------------------------------------------------------------o //| Purpose - Process a gump button press //o------------------------------------------------------------------------------------------------o //| Changes - 1/21/2003 - Implemented the code needed to support enhanced //| gump response processing //o------------------------------------------------------------------------------------------------o void cScript::HandleGumpPress( CPIGumpMenuSelect *packet ) { if( !ExistAndVerify( seOnGumpPress, "onGumpPress" )) return; if( packet == nullptr ) return; CSocket *pressing = packet->GetSocket(); if( pressing == nullptr ) return; UI32 button = packet->ButtonId(); UI16 nButtons = static_cast<UI16>( packet->SwitchCount() ); UI16 nText = static_cast<UI16>( packet->TextCount() ); SEGumpData_st *segdGumpData = new SEGumpData_st; JSObject *jsoObject = JS_NewObject( targContext, &UOXGumpData_class, nullptr, nullptr ); JS_DefineFunctions( targContext, jsoObject, CGumpData_Methods ); JS_DefineProperties( targContext, jsoObject, CGumpDataProperties ); JS_SetPrivate( targContext, jsoObject, segdGumpData ); JS_LockGCThing( targContext, jsoObject ); //JS_AddRoot( targContext, &jsoObject ); UI16 i; // Loop through Buttons for( i = 0; i < nButtons; ++i ) { segdGumpData->nButtons.push_back( packet->SwitchValue( i )); } // Process text for the buttons? // Loop grabbing text for( i = 0; i < nText; ++i ) { segdGumpData->nIDs.push_back( packet->GetTextId( i )); segdGumpData->sEdits.push_back( packet->GetTextString( i )); } jsval jsvParams[3], jsvRVal; JSObject *myObj = JSEngine->AcquireObject( IUE_SOCK, pressing, runTime ); jsvParams[0] = OBJECT_TO_JSVAL( myObj ); jsvParams[1] = INT_TO_JSVAL( button ); jsvParams[2] = OBJECT_TO_JSVAL( jsoObject ); [[maybe_unused]] JSBool retVal = JS_CallFunctionName( targContext, targObject, "onGumpPress", 3, jsvParams, &jsvRVal ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::HandleGumpInput() //o------------------------------------------------------------------------------------------------o //| Purpose - Handle gump inputs? //o------------------------------------------------------------------------------------------------o void cScript::HandleGumpInput( CPIGumpInput *pressing ) { if( pressing == nullptr ) return; if( !ExistAndVerify( seOnGumpInput, "onGumpInput" )) return; jsval params[3], rval; JSObject *myObj = JSEngine->AcquireObject( IUE_SOCK, pressing->GetSocket(), runTime ); JSString *gumpReply = nullptr; gumpReply = JS_NewStringCopyZ( targContext, pressing->Reply().c_str() ); params[0] = OBJECT_TO_JSVAL( myObj ); params[1] = INT_TO_JSVAL( pressing->Index() ); params[2] = STRING_TO_JSVAL( gumpReply ); [[maybe_unused]] JSBool retVal = JS_CallFunctionName( targContext, targObject, "onGumpInput", 3, params, &rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnScrollingGumpPress() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for character with event attached when clicking the old school horizontally scrolling gump //| if ID of this gump is 0 //o------------------------------------------------------------------------------------------------o SI08 cScript::OnScrollingGumpPress( CSocket *tSock, UI16 gumpId, UI16 buttonId ) { const SI08 RV_NOFUNC = -1; if( tSock == nullptr ) return RV_NOFUNC; if( !ExistAndVerify( seOnScrollingGumpPress, "onScrollingGumpPress" )) return RV_NOFUNC; jsval params[3], rval; JSObject *myObj = JSEngine->AcquireObject( IUE_SOCK, tSock, runTime ); params[0] = OBJECT_TO_JSVAL( myObj ); params[1] = INT_TO_JSVAL( gumpId ); params[2] = INT_TO_JSVAL( buttonId ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onScrollingGumpPress", 3, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnScrollingGumpPress, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnEnterRegion() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for character with event attached when entering a region //o------------------------------------------------------------------------------------------------o bool cScript::OnEnterRegion( CChar *entering, UI16 region ) { if( !ValidateObject( entering )) return false; if( !ExistAndVerify( seOnEnterRegion, "onEnterRegion" )) return false; jsval params[2], rval; JSObject *charObj = JSEngine->AcquireObject( IUE_CHAR, entering, runTime ); params[0] = OBJECT_TO_JSVAL( charObj ); params[1] = INT_TO_JSVAL( region ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onEnterRegion", 2, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnEnterRegion, false ); } return ( retVal == JS_TRUE ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnLeaveRegion() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for character with event attached when leaving a region //o------------------------------------------------------------------------------------------------o bool cScript::OnLeaveRegion( CChar *leaving, UI16 region ) { if( !ValidateObject( leaving )) return false; if( !ExistAndVerify( seOnLeaveRegion, "onLeaveRegion" )) return false; jsval params[2], rval; JSObject *charObj = JSEngine->AcquireObject( IUE_CHAR, leaving, runTime ); params[0] = OBJECT_TO_JSVAL( charObj ); params[1] = INT_TO_JSVAL( region ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onLeaveRegion", 2, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnLeaveRegion, false ); } return ( retVal == JS_TRUE ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnFacetChange() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for characters with event attached when switching to a different facet //o------------------------------------------------------------------------------------------------o SI08 cScript::OnFacetChange( CChar *mChar, const UI08 oldFacet, const UI08 newFacet ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( mChar )) return RV_NOFUNC; if( !ExistAndVerify( seOnFacetChange, "onFacetChange" )) return RV_NOFUNC; jsval params[3], rval; JSObject *charObj = JSEngine->AcquireObject( IUE_CHAR, mChar, runTime ); params[0] = OBJECT_TO_JSVAL( charObj ); params[1] = INT_TO_JSVAL( oldFacet ); params[2] = INT_TO_JSVAL( newFacet ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onFacetChange", 3, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnFacetChange, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnSpellTargetSelect() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for character with event attached who targets someone with a spell //o------------------------------------------------------------------------------------------------o SI08 cScript::OnSpellTargetSelect( CChar *caster, CBaseObject *target, UI08 spellNum ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( target ) || !ValidateObject( caster )) return RV_NOFUNC; if( !ExistAndVerify( seOnSpellTargetSelect, "onSpellTargetSelect" )) return RV_NOFUNC; jsval params[4], rval; JSObject *castObj = JSEngine->AcquireObject( IUE_CHAR, caster, runTime ); JSObject *targObj; if( target->CanBeObjType( OT_CHAR )) { targObj = JSEngine->AcquireObject( IUE_CHAR, target, runTime ); } else { targObj = JSEngine->AcquireObject( IUE_ITEM, target, runTime ); } params[0] = OBJECT_TO_JSVAL( targObj ); params[1] = OBJECT_TO_JSVAL( castObj ); params[2] = INT_TO_JSVAL( spellNum ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onSpellTargetSelect", 3, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnSpellTargetSelect, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnSpellTarget() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for character with event attached who is the target of a spell //o------------------------------------------------------------------------------------------------o SI08 cScript::OnSpellTarget( CBaseObject *target, CChar *caster, UI08 spellNum ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( target ) || !ValidateObject( caster )) return RV_NOFUNC; if( !ExistAndVerify( seOnSpellTarget, "onSpellTarget" )) return RV_NOFUNC; jsval params[4], rval; JSObject *castObj = JSEngine->AcquireObject( IUE_CHAR, caster, runTime ); JSObject *targObj; if( target->CanBeObjType( OT_CHAR )) { targObj = JSEngine->AcquireObject( IUE_CHAR, target, runTime ); } else { targObj = JSEngine->AcquireObject( IUE_ITEM, target, runTime ); } params[0] = OBJECT_TO_JSVAL( targObj ); params[1] = OBJECT_TO_JSVAL( castObj ); params[2] = INT_TO_JSVAL( spellNum ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onSpellTarget", 3, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnSpellTarget, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::CallParticularEvent() //| Date - 20th December, 2001 //o------------------------------------------------------------------------------------------------o //| Purpose - Calls a particular script event, passing parameters //o------------------------------------------------------------------------------------------------o bool cScript::CallParticularEvent( const char *eventToCall, jsval *params, SI32 numParams, jsval *eventRetVal ) { if( eventToCall == nullptr ) return false; // ExistAndVerify() normally sets our Global Object, but not on custom named functions. JS_SetGlobalObject( targContext, targObject ); JSBool retVal = JS_CallFunctionName( targContext, targObject, eventToCall, numParams, params, eventRetVal ); if( retVal == JS_FALSE ) { SetEventExists( seOnSpellSuccess, false ); return false; } return true; } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnSpellCast() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers when character with event attached casts a spell //| Notes - Return value table //| -2: use NORMAL non-JS casting //| -1: CANCEL spellcasting //| 0->inf: Spell delay in ms //o------------------------------------------------------------------------------------------------o SI16 cScript::OnSpellCast( CChar *tChar, UI08 SpellId ) { if( !ValidateObject( tChar )) return -2; if( !ExistAndVerify( seOnSpellCast, "onSpellCast" )) return -2; jsval params[2], rval; JSObject *charObj = JSEngine->AcquireObject( IUE_CHAR, tChar, runTime ); params[0] = OBJECT_TO_JSVAL( charObj ); params[1] = INT_TO_JSVAL( SpellId ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onSpellCast", 2, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnSpellCast, false ); return -2; } return static_cast<SI16>( JSVAL_TO_INT( rval )); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnScrollCast() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers when character with event attached casts a spell through a scroll //| Notes - Return value table //| -2: use NORMAL non-JS casting //| -1: CANCEL spellcasting //| 0->inf: Spell delay in ms //o------------------------------------------------------------------------------------------------o SI16 cScript::OnScrollCast( CChar *tChar, UI08 SpellId ) { if( !ValidateObject( tChar )) return -2; if( !ExistAndVerify( seOnScrollCast, "onScrollCast" )) return -2; jsval params[2], rval; JSObject *charObj = JSEngine->AcquireObject( IUE_CHAR, tChar, runTime ); params[0] = OBJECT_TO_JSVAL( charObj ); params[1] = INT_TO_JSVAL( SpellId ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onScrollCast", 2, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnScrollCast, false ); return -2; } return static_cast<SI16>( JSVAL_TO_INT( rval )); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnSpellSuccess() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers after character with event attached successfully casts a spell //o------------------------------------------------------------------------------------------------o SI08 cScript::OnSpellSuccess( CChar *tChar, UI08 SpellId ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( tChar )) return RV_NOFUNC; if( !ExistAndVerify( seOnSpellSuccess, "onSpellSuccess" )) return RV_NOFUNC; jsval params[2], rval; JSObject *charObj = JSEngine->AcquireObject( IUE_CHAR, tChar, runTime ); params[0] = OBJECT_TO_JSVAL( charObj ); params[1] = INT_TO_JSVAL( SpellId ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onSpellSuccess", 2, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnSpellSuccess, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnTalk() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers when character with event attached says something //o------------------------------------------------------------------------------------------------o SI08 cScript::OnTalk( CChar *myChar, const char *mySpeech ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( myChar )) return RV_NOFUNC; if( !ExistAndVerify( seOnTalk, "onTalk" )) return RV_NOFUNC; jsval params[2], rval; JSString *strSpeech = nullptr; std::string lwrSpeech = mySpeech; strSpeech = JS_NewStringCopyZ( targContext, oldstrutil::lower( lwrSpeech ).c_str() ); JSObject *charObj = JSEngine->AcquireObject( IUE_CHAR, myChar, runTime ); params[0] = OBJECT_TO_JSVAL( charObj ); params[1] = STRING_TO_JSVAL( strSpeech ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onTalk", 2, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnTalk, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnSpeechInput() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers after player with event attached inputs speech after a request for //| speech input has been made. //| Notes - This function is called out of network.cpp if a speechmode(9) was previously set //o------------------------------------------------------------------------------------------------o bool cScript::OnSpeechInput( CChar *myChar, CItem *myItem, const char *mySpeech ) { if( !ValidateObject( myChar )) return true; if( !ExistAndVerify( seOnSpeechInput, "onSpeechInput" )) return true; jsval params[4], rval; JSString *strSpeech = nullptr; char *lwrSpeech = new char[strlen( mySpeech ) + 1]; strcopy( lwrSpeech, strlen( mySpeech ) + 1, mySpeech ); strSpeech = JS_NewStringCopyZ( targContext, lwrSpeech ); delete[] lwrSpeech; JSObject *charObj = JSEngine->AcquireObject( IUE_CHAR, myChar, runTime ); params[0] = OBJECT_TO_JSVAL( charObj ); if( !ValidateObject( myItem )) { params[1] = JSVAL_NULL; } else { JSObject *itemObj = JSEngine->AcquireObject( IUE_ITEM, myItem, runTime ); params[1] = OBJECT_TO_JSVAL( itemObj ); } params[2] = STRING_TO_JSVAL( strSpeech ); params[3] = INT_TO_JSVAL( myChar->GetSpeechId() ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onSpeechInput", 4, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnSpeechInput, false ); return true; } return ( rval == JSVAL_TRUE ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnSpellGain() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for spellbooks with event attached when spells are added to them //o------------------------------------------------------------------------------------------------o SI08 cScript::OnSpellGain( CItem *book, const UI08 spellNum ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( book )) return RV_NOFUNC; if( !ExistAndVerify( seOnSpellGain, "onSpellGain" )) return RV_NOFUNC; jsval params[2], rval; JSObject *itemObj = JSEngine->AcquireObject( IUE_ITEM, book, runTime ); params[0] = OBJECT_TO_JSVAL( itemObj ); params[1] = INT_TO_JSVAL( spellNum ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onSpellGain", 2, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnSpellGain, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnSpellLoss() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for spellbooks with event attached when spells are removed from them //o------------------------------------------------------------------------------------------------o SI08 cScript::OnSpellLoss( CItem *book, const UI08 spellNum ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( book )) return RV_NOFUNC; if( !ExistAndVerify( seOnSpellLoss, "onSpellLoss" )) return RV_NOFUNC; jsval params[2], rval; JSObject *itemObj = JSEngine->AcquireObject( IUE_ITEM, book, runTime ); params[0] = OBJECT_TO_JSVAL( itemObj ); params[1] = INT_TO_JSVAL( spellNum ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onSpellLoss", 2, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnSpellLoss, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnSkillCheck() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for character with event attached when a skillcheck is performed //o------------------------------------------------------------------------------------------------o SI08 cScript::OnSkillCheck( CChar *myChar, const UI08 skill, const UI16 lowSkill, const UI16 highSkill, bool isCraftSkill, SI08 overrideOutcome ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( myChar ) || skill > ALLSKILLS ) return RV_NOFUNC; if( !ExistAndVerify( seOnSkillCheck, "onSkillCheck" )) return RV_NOFUNC; jsval params[6], rval; JSObject *charObj = JSEngine->AcquireObject( IUE_CHAR, myChar, runTime ); params[0] = OBJECT_TO_JSVAL( charObj ); params[1] = INT_TO_JSVAL( skill ); params[2] = INT_TO_JSVAL( lowSkill ); params[3] = INT_TO_JSVAL( highSkill ); params[4] = BOOLEAN_TO_JSVAL( isCraftSkill ); params[5] = INT_TO_JSVAL( overrideOutcome ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onSkillCheck", 6, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnSkillCheck, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::AreaObjFunc() //| Date - January 27, 2003 //| Changes - August 17 2005 //| Renamed to AreaObjFunc from AreaCharFunc //| Added support for other object types //o------------------------------------------------------------------------------------------------o //| Purpose - Calls the function represented in funcName for the script //| - passing in two character parameters //o------------------------------------------------------------------------------------------------o bool cScript::AreaObjFunc( char *funcName, CBaseObject *srcObject, CBaseObject *tmpObject, CSocket *s ) { if( !ValidateObject( srcObject ) || !ValidateObject( tmpObject ) || funcName == nullptr ) return false; jsval params[3], rval; JSObject *srcObj = nullptr; JSObject *tmpObj = nullptr; if( srcObject == nullptr || tmpObject == nullptr ) return false; if( srcObject->CanBeObjType( OT_ITEM )) { srcObj = JSEngine->AcquireObject( IUE_ITEM, srcObject, runTime ); } else if( srcObject->CanBeObjType( OT_CHAR )) { srcObj = JSEngine->AcquireObject( IUE_CHAR, srcObject, runTime ); } if( tmpObject->CanBeObjType( OT_ITEM )) { tmpObj = JSEngine->AcquireObject( IUE_ITEM, tmpObject, runTime ); } else if( tmpObject->CanBeObjType( OT_CHAR )) { tmpObj = JSEngine->AcquireObject( IUE_CHAR, tmpObject, runTime ); } if( srcObj == nullptr || tmpObj == nullptr ) { return false; } params[0] = OBJECT_TO_JSVAL( srcObj ); params[1] = OBJECT_TO_JSVAL( tmpObj ); if( s != nullptr ) { JSObject *sockObj = nullptr; sockObj = JSEngine->AcquireObject( IUE_SOCK, s, runTime ); params[2] = OBJECT_TO_JSVAL( sockObj ); } else { params[2] = JSVAL_NULL; } // ExistAndVerify() normally sets our Global Object, but not on custom named functions. JS_SetGlobalObject( targContext, targObject ); //FIXME === do we need this retvalue? //JSBool retVal = JS_CallFunctionName( targContext, targObject, funcName, 3, params, &rval ); try { [[maybe_unused]] JSBool retVal = JS_CallFunctionName( targContext, targObject, funcName, 3, params, &rval ); } catch( ... ) { Console.Error( "Some error!" ); } return ( JSVAL_TO_BOOLEAN( rval ) == JS_TRUE ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnCommand() //o------------------------------------------------------------------------------------------------o //| Purpose - Quick and dirty way to setup custom commands //o------------------------------------------------------------------------------------------------o SI08 cScript::OnCommand( CSocket *mSock, std::string command ) { const SI08 RV_NOFUNC = -1; if( mSock == nullptr || command == "" ) return RV_NOFUNC; if( !ExistAndVerify( seOnCommand, "onCommand" )) return RV_NOFUNC; jsval params[2], rval; JSObject *myObj = JSEngine->AcquireObject( IUE_SOCK, mSock, runTime ); JSString *strCmd = nullptr; strCmd = JS_NewStringCopyZ( targContext, oldstrutil::lower( command ).c_str() ); params[0] = OBJECT_TO_JSVAL( myObj ); params[1] = STRING_TO_JSVAL( strCmd ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onCommand", 2, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnCommand, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnProfileRequest() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers in global script on requests for paperdoll profiles of other players //o------------------------------------------------------------------------------------------------o std::string cScript::OnProfileRequest( CSocket *mSock, CChar *profileOwner ) { if( mSock == nullptr || !ValidateObject( profileOwner )) return ""; if( !ExistAndVerify( seOnProfileRequest, "onProfileRequest" )) return ""; jsval params[2], rval; JSObject *myObj = JSEngine->AcquireObject( IUE_SOCK, mSock, runTime ); JSObject *profOwnerObj = JSEngine->AcquireObject( IUE_CHAR, profileOwner, runTime ); params[0] = OBJECT_TO_JSVAL( myObj ); params[1] = STRING_TO_JSVAL( profOwnerObj ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onProfileRequest", 2, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnProfileRequest, false ); } if( rval < 0 ) { Console.Error( "Handled exception in cScript.cpp OnProfileRequest() - invalid return value/error encountered!" ); return ""; } try { JSString *str = JS_ValueToString( targContext, rval ); std::string returnString = JS_GetStringBytes( str ); return returnString; } catch( ... ) { Console.Error( "Handled exception in cScript.cpp OnProfileRequest()" ); return ""; } } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnProfileUpdate() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers in global script on attempts to update paperdoll profile text //o------------------------------------------------------------------------------------------------o SI08 cScript::OnProfileUpdate( CSocket *mSock, std::string profileText ) { if( mSock == nullptr || profileText.empty() ) return false; if( !ExistAndVerify( seOnProfileUpdate, "onProfileUpdate" )) return false; jsval params[2], rval; JSObject *myObj = JSEngine->AcquireObject( IUE_SOCK, mSock, runTime ); JSString *strProfileText = nullptr; strProfileText = JS_NewStringCopyZ( targContext, profileText.c_str() ); params[0] = OBJECT_TO_JSVAL( myObj ); params[1] = STRING_TO_JSVAL( strProfileText ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onProfileUpdate", 2, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnProfileUpdate, false ); } return ( retVal == JS_TRUE ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::ExistAndVerify() //o------------------------------------------------------------------------------------------------o //| Purpose - ??? //o------------------------------------------------------------------------------------------------o bool cScript::ExistAndVerify( ScriptEvent eventNum, std::string functionName ) { if( !EventExists( eventNum )) return false; if( NeedsChecking( eventNum )) { SetNeedsChecking( eventNum, false ); jsval Func = JSVAL_NULL; JS_GetProperty( targContext, targObject, functionName.c_str(), &Func ); if( Func == JSVAL_VOID ) { SetEventExists( eventNum, false ); return false; } } JS_SetGlobalObject( targContext, targObject ); return true; } //o------------------------------------------------------------------------------------------------o //| Function - cScript::ScriptRegistration() //| Date - 20th December, 2001 //o------------------------------------------------------------------------------------------------o //| Purpose - Registers a script with the JS engine //| Notes - Also requires a <scriptType>Registration() event with a Register<scriptType>() //| function, and an onSkill() event, both in the same script //o------------------------------------------------------------------------------------------------o bool cScript::ScriptRegistration( std::string scriptType ) { scriptType += "Registration"; jsval params[1], rval; // ExistAndVerify() normally sets our Global Object, but not on custom named functions. JS_SetGlobalObject( targContext, targObject ); jsval Func = JSVAL_NULL; JS_GetProperty( targContext, targObject, scriptType.c_str(), &Func ); if( Func == JSVAL_VOID ) { Console.Warning( oldstrutil::format( "Script Number (%u) does not have a %s function", JSMapping->GetScriptId( targObject ), scriptType.c_str() )); return false; } JSBool retVal = JS_CallFunctionName( targContext, targObject, scriptType.c_str(), 0, params, &rval ); return ( retVal == JS_TRUE ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::executeCommand() //o------------------------------------------------------------------------------------------------o //| Purpose - Execute a player-initiated JS-based command //o------------------------------------------------------------------------------------------------o bool cScript::executeCommand( CSocket *s, std::string funcName, std::string executedString ) { jsval params[2], rval; JSString *execString = JS_NewStringCopyZ( targContext, executedString.c_str() ); JSObject *myObj = JSEngine->AcquireObject( IUE_SOCK, s, runTime ); params[0] = OBJECT_TO_JSVAL( myObj ); params[1] = STRING_TO_JSVAL( execString ); // ExistAndVerify() normally sets our Global Object, but not on custom named functions. JS_SetGlobalObject( targContext, targObject ); JSBool retVal = JS_CallFunctionName( targContext, targObject, funcName.c_str(), 2, params, &rval ); return ( retVal == JS_TRUE ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::MagicSpellCast() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers before a spellcast attempt for characters with onSpellCast event attached //o------------------------------------------------------------------------------------------------o bool cScript::MagicSpellCast( CSocket *mSock, CChar *tChar, bool directCast, SI32 spellNum ) { if( !ValidateObject( tChar )) return false; if( !ExistAndVerify( seOnSpellCast, "onSpellCast" )) return false; jsval params[4], rval; JSObject *charObj = JSEngine->AcquireObject( IUE_CHAR, tChar, runTime ); JSObject *sockObj = JSEngine->AcquireObject( IUE_SOCK, mSock, runTime ); params[0] = OBJECT_TO_JSVAL( sockObj ); params[1] = OBJECT_TO_JSVAL( charObj ); params[2] = BOOLEAN_TO_JSVAL( directCast ); params[3] = INT_TO_JSVAL( spellNum ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onSpellCast", 4, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnSpellCast, false ); return false; } return ( JSVAL_TO_BOOLEAN( rval ) == JS_TRUE ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnIterate() //o------------------------------------------------------------------------------------------------o //| Purpose - Called after IterateOver JS function is used, and iterates over all items or //| characters (as specified) in the game //o------------------------------------------------------------------------------------------------o bool cScript::OnIterate( CBaseObject *a, UI32 &b, CSocket *mSock ) { if( !ValidateObject( a )) return true; if( !ExistAndVerify( seOnIterate, "onIterate" )) return false; jsval params[2], rval; JSObject *myObj = nullptr; if( a->GetObjType() == OT_CHAR ) { myObj = JSEngine->AcquireObject( IUE_CHAR, a, runTime ); } else { myObj = JSEngine->AcquireObject( IUE_ITEM, a, runTime ); } JSObject *sockObj = nullptr; if( mSock ) { sockObj = JSEngine->AcquireObject( IUE_SOCK, mSock, runTime ); } params[0] = OBJECT_TO_JSVAL( myObj ); params[1] = OBJECT_TO_JSVAL( sockObj ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onIterate", 2, params, &rval ); /* if( ValidateObject( a )) { if( a->GetObjType() == OT_CHAR ) { JSEngine->ReleaseObject( IUE_CHAR, a ); } else { JSEngine->ReleaseObject( IUE_ITEM, a ); } } */ if( retVal == JS_FALSE ) { SetEventExists( seOnIterate, false ); } else if( JSVAL_TO_BOOLEAN( rval )) { ++b; } return ( retVal == JS_TRUE ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnIterateSpawnRegions() //o------------------------------------------------------------------------------------------------o //| Purpose - Called after IterateOverSpawnRegions JS function is used, and iterates over //| all spawn regions in game //o------------------------------------------------------------------------------------------------o bool cScript::OnIterateSpawnRegions( CSpawnRegion *a, UI32 &b ) { if( a == nullptr ) return true; if( !ExistAndVerify( seOnIterateSpawnRegions, "onIterateSpawnRegions" )) return false; jsval params[1], rval; JSObject *myObj = nullptr; myObj = JSEngine->AcquireObject( IUE_SPAWNREGION, a, runTime ); params[0] = OBJECT_TO_JSVAL( myObj ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onIterateSpawnRegions", 1, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnIterateSpawnRegions, false ); } else if( JSVAL_TO_BOOLEAN( rval )) { ++b; } return ( retVal == JS_TRUE ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnPacketReceive() //o------------------------------------------------------------------------------------------------o //| Purpose - "Packet hook" event that allows interception of incoming network packets //| Notes - Requires OVERLOADPACKETS ini setting to be enabled, and incoming packet must //| be registered in JSE_FILEASSOCIATIONS.SCP under the [PACKET_SCRIPTS] section //o------------------------------------------------------------------------------------------------o bool cScript::OnPacketReceive( CSocket *mSock, UI16 packetNum ) { if( mSock == nullptr ) return false; if( !ExistAndVerify( seOnPacketReceive, "onPacketReceive" )) return false; jsval rval, params[3]; JSObject *myObj = JSEngine->AcquireObject( IUE_SOCK, mSock, runTime ); params[0] = OBJECT_TO_JSVAL( myObj ); params[1] = INT_TO_JSVAL( static_cast<UI08>( packetNum % 256 )); params[2] = INT_TO_JSVAL( static_cast<UI08>( packetNum >> 8 )); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onPacketReceive", 3, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnPacketReceive, false ); } return ( retVal == JS_TRUE ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnCharDoubleClick() //| Date - 23rd January, 2006 //o------------------------------------------------------------------------------------------------o //| Purpose - Allows overriding events that happen when doubleclicking characters, such as //| open paperdoll, mounting horses, etc //o------------------------------------------------------------------------------------------------o SI08 cScript::OnCharDoubleClick( CChar *currChar, CChar *targChar ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( currChar ) || !ValidateObject( targChar )) return RV_NOFUNC; if( !ExistAndVerify( seOnCharDoubleClick, "onCharDoubleClick" )) return RV_NOFUNC; jsval params[2], rval; JSObject *srcObj = JSEngine->AcquireObject( IUE_CHAR, currChar, runTime ); JSObject *trgObj = JSEngine->AcquireObject( IUE_CHAR, targChar, runTime ); params[0] = OBJECT_TO_JSVAL( srcObj ); params[1] = OBJECT_TO_JSVAL( trgObj ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onCharDoubleClick", 2, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnCharDoubleClick, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnDismount() //o------------------------------------------------------------------------------------------------o //| Purpose - Allows triggering effects upon dismounting a mount //o------------------------------------------------------------------------------------------------o SI08 cScript::OnDismount( CChar *pChar, CChar *npcMount ) { if( !ValidateObject( pChar ) || !ValidateObject( npcMount )) return false; if( !ExistAndVerify( seOnDismount, "onDismount" )) return false; jsval params[2], rval; JSObject *pObj = JSEngine->AcquireObject( IUE_CHAR, pChar, runTime ); JSObject *npcObj = JSEngine->AcquireObject( IUE_CHAR, npcMount, runTime ); params[0] = OBJECT_TO_JSVAL( pObj ); params[1] = OBJECT_TO_JSVAL( npcObj ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onDismount", 2, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnDismount, false ); } return ( retVal == JS_TRUE ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnSkillGump() //| Date - 23rd January, 2006 //o------------------------------------------------------------------------------------------------o //| Purpose - Allows overriding the client's request to open the default skillgump, and //| instead do something else (like opening a custom skillgump instead). //o------------------------------------------------------------------------------------------------o SI08 cScript::OnSkillGump( CChar *currChar ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( currChar )) return RV_NOFUNC; if( !ExistAndVerify( seOnSkillGump, "onSkillGump" )) return RV_NOFUNC; jsval params[1], rval; JSObject *charObj = JSEngine->AcquireObject( IUE_CHAR, currChar, runTime ); params[0] = OBJECT_TO_JSVAL( charObj ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onSkillGump", 1, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnSkillGump, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnUseBandageMacro() //| Date - 12th May, 2020 //o------------------------------------------------------------------------------------------------o //| Purpose - Expose bandage macro usage to JS engine so server admins can override the effects //o------------------------------------------------------------------------------------------------o SI08 cScript::OnUseBandageMacro( CSocket *mSock, CChar *targChar, CItem *bandageItem ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( targChar ) || mSock == nullptr ) return RV_NOFUNC; if( !ExistAndVerify( seOnUseBandageMacro, "onUseBandageMacro" )) return RV_NOFUNC; jsval params[3], rval; JSObject *mSockObj = JSEngine->AcquireObject( IUE_SOCK, mSock, runTime ); JSObject *targCharObj = JSEngine->AcquireObject( IUE_CHAR, targChar, runTime ); JSObject *bandageItemObj = JSEngine->AcquireObject( IUE_ITEM, bandageItem, runTime ); params[0] = OBJECT_TO_JSVAL( mSockObj ); params[1] = OBJECT_TO_JSVAL( targCharObj ); params[2] = OBJECT_TO_JSVAL( bandageItemObj ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onUseBandageMacro", 3, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnUseBandageMacro, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnAICombatTarget() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for characters with event attached when selecting a target as part of //| default AI behaviour //| Notes - Returning FALSE will deem a target invalid, and it will be skipped //| Returning TRUE will deem a target valid, and it will be selected //o------------------------------------------------------------------------------------------------o SI08 cScript::OnAICombatTarget( CChar *attacker, CChar *target ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( attacker ) || !ValidateObject( target )) return RV_NOFUNC; if( !ExistAndVerify( seOnAICombatTarget, "onAICombatTarget" )) return RV_NOFUNC; jsval params[2], rval; JSObject *attObj = JSEngine->AcquireObject( IUE_CHAR, attacker, runTime ); JSObject *targObj = JSEngine->AcquireObject( IUE_CHAR, target, runTime ); params[0] = OBJECT_TO_JSVAL( attObj ); params[1] = OBJECT_TO_JSVAL( targObj ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onAICombatTarget", 2, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnAICombatTarget, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnCombatStart() //| Date - 23rd January, 2006 //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for characters with event attached when initiating combat //| Notes - Returning FALSE will also run hard code for this scenario //| Returning TRUE will override code's default handling of this scenario //o------------------------------------------------------------------------------------------------o SI08 cScript::OnCombatStart( CChar *attacker, CChar *defender ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( attacker ) || !ValidateObject( defender )) return RV_NOFUNC; if( !ExistAndVerify( seOnCombatStart, "onCombatStart" )) return RV_NOFUNC; jsval params[2], rval; JSObject *attObj = JSEngine->AcquireObject( IUE_CHAR, attacker, runTime ); JSObject *defObj = JSEngine->AcquireObject( IUE_CHAR, defender, runTime ); params[0] = OBJECT_TO_JSVAL( attObj ); params[1] = OBJECT_TO_JSVAL( defObj ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onCombatStart", 2, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnCombatStart, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnCombatEnd() //| Date - 23rd January, 2006 //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for characters with event attached when combat ends //| Notes - Returning FALSE will also run hard code for this scenario //| Returning TRUE will override code's default handling of this scenario //o------------------------------------------------------------------------------------------------o SI08 cScript::OnCombatEnd( CChar *currChar, CChar *targChar ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( currChar )) return RV_NOFUNC; if( !ExistAndVerify( seOnCombatEnd, "onCombatEnd" )) return RV_NOFUNC; jsval params[2], rval; JSObject *attObj = JSEngine->AcquireObject( IUE_CHAR, currChar, runTime ); JSObject *defObj = JSEngine->AcquireObject( IUE_CHAR, targChar, runTime ); params[0] = OBJECT_TO_JSVAL( attObj ); params[1] = OBJECT_TO_JSVAL( defObj ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onCombatEnd", 2, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnCombatEnd, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnDeathBlow() //| Date - 8th February, 2006 //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for characters with event attached when performing a death blow in combat //| Notes - Returning FALSE will also run hard code for this scenario //| Returning TRUE will override code's default handling of this scenario //o------------------------------------------------------------------------------------------------o SI08 cScript::OnDeathBlow( CChar *mKilled, CChar *mKiller ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( mKilled )) // || !ValidateObject( mKiller )) return RV_NOFUNC; if( !ExistAndVerify( seOnDeathBlow, "onDeathBlow" )) return RV_NOFUNC; jsval rval, params[2]; JSObject *killedObj = JSEngine->AcquireObject( IUE_CHAR, mKilled, runTime ); JSObject *killerObj = JSEngine->AcquireObject( IUE_CHAR, mKiller, runTime ); params[0] = OBJECT_TO_JSVAL( killedObj ); params[1] = OBJECT_TO_JSVAL( killerObj ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onDeathBlow", 2, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnDeathBlow, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnCombatDamageCalc() //| Date - 21st March, 2006 //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for characters with event attached every time combat damage is calculated //| Notes - Returning -1 will default to hard code handling of event //| Returning another value will override code's default handling of event //o------------------------------------------------------------------------------------------------o SI16 cScript::OnCombatDamageCalc( CChar *attacker, CChar *defender, UI08 getFightSkill, UI08 hitLoc ) { const SI16 RV_NOFUNC = -1; if( !ValidateObject( attacker ) || !ValidateObject( defender )) return RV_NOFUNC; if( !ExistAndVerify( seOnCombatDamageCalc, "onCombatDamageCalc" )) return RV_NOFUNC; SI16 funcRetVal = -1; jsval rval, params[4]; JSObject *attackerObj = JSEngine->AcquireObject( IUE_CHAR, attacker, runTime ); JSObject *defenderObj = JSEngine->AcquireObject( IUE_CHAR, defender, runTime ); params[0] = OBJECT_TO_JSVAL( attackerObj ); params[1] = OBJECT_TO_JSVAL( defenderObj ); params[2] = INT_TO_JSVAL( getFightSkill ); params[3] = INT_TO_JSVAL( hitLoc ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onCombatDamageCalc", 4, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnCombatDamageCalc, false ); return RV_NOFUNC; } JSEncapsulate damage( targContext, &rval ); if( damage.isType( JSOT_INT ) || damage.isType( JSOT_DOUBLE )) // They returned some sort of value { return static_cast<SI16>( damage.toInt() ); } else { funcRetVal = -1; // default to hard code } return funcRetVal; } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnDamage() //| Date - 22nd March, 2006 //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers when character with event attached takes damage //o------------------------------------------------------------------------------------------------o SI08 cScript::OnDamage( CChar *damaged, CChar *attacker, SI16 damageValue, WeatherType damageType ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( damaged )) return RV_NOFUNC; if( !ExistAndVerify( seOnDamage, "onDamage" )) return RV_NOFUNC; jsval rval, params[4]; JSObject *damagedObj = JSEngine->AcquireObject( IUE_CHAR, damaged, runTime ); params[0] = OBJECT_TO_JSVAL( damagedObj ); if( ValidateObject( attacker )) { JSObject *attackerObj = JSEngine->AcquireObject( IUE_CHAR, attacker, runTime ); params[1] = OBJECT_TO_JSVAL( attackerObj ); } else { params[1] = JSVAL_NULL; } params[2] = INT_TO_JSVAL( damageValue ); params[3] = INT_TO_JSVAL( damageType ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onDamage", 4, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnDamage, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnDamageDeal() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers when character with event attached deals damage //o------------------------------------------------------------------------------------------------o SI08 cScript::OnDamageDeal( CChar *attacker, CChar *damaged, SI16 damageValue, WeatherType damageType ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( damaged )) return RV_NOFUNC; if( !ExistAndVerify( seOnDamageDeal, "onDamageDeal" )) return RV_NOFUNC; jsval rval, params[4]; JSObject *attackerObj = JSEngine->AcquireObject( IUE_CHAR, attacker, runTime ); params[0] = OBJECT_TO_JSVAL( attackerObj ); JSObject *damagedObj = JSEngine->AcquireObject( IUE_CHAR, damaged, runTime ); params[1] = OBJECT_TO_JSVAL( damagedObj ); params[2] = INT_TO_JSVAL( damageValue ); params[3] = INT_TO_JSVAL( damageType ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onDamageDeal", 4, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnDamageDeal, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnBuy() //| Date - 26th November, 2011 //o------------------------------------------------------------------------------------------------o //| Purpose - Runs on vendors, triggered before vendor trade-gump is opened //o------------------------------------------------------------------------------------------------o SI08 cScript::OnBuy( CSocket *tSock, CChar *objVendor ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( objVendor ) || tSock == nullptr ) return RV_NOFUNC; if( !ExistAndVerify( seOnBuy, "onBuy" )) return RV_NOFUNC; jsval rval, params[3]; JSObject *myObj = JSEngine->AcquireObject( IUE_SOCK, tSock, runTime ); JSObject *charObj = JSEngine->AcquireObject( IUE_CHAR, objVendor, runTime ); params[0] = OBJECT_TO_JSVAL( myObj ); params[1] = OBJECT_TO_JSVAL( charObj ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onBuy", 2, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnBuy, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnSell() //| Date - 26th November, 2011 //o------------------------------------------------------------------------------------------------o //| Purpose - Runs on vendors, triggered before vendor trade-gump is opened //o------------------------------------------------------------------------------------------------o SI08 cScript::OnSell( CSocket *tSock, CChar *objVendor ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( objVendor ) || tSock == nullptr ) return RV_NOFUNC; if( !ExistAndVerify( seOnSell, "onSell" )) return RV_NOFUNC; jsval rval, params[3]; JSObject *myObj = JSEngine->AcquireObject( IUE_SOCK, tSock, runTime ); JSObject *charObj = JSEngine->AcquireObject( IUE_CHAR, objVendor, runTime ); params[0] = OBJECT_TO_JSVAL( myObj ); params[1] = OBJECT_TO_JSVAL( charObj ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onSell", 2, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnSell, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnBuyFromVendor() //| Date - 26th November, 2011 //o------------------------------------------------------------------------------------------------o //| Purpose - Allows determining what happens when an item is in the process of being bought //| from an NPC vendor. Returning false/0 from the script will halt the purchase //o------------------------------------------------------------------------------------------------o SI08 cScript::OnBuyFromVendor( CSocket *tSock, CChar *objVendor, CBaseObject *objItemBought, UI16 numItemsBuying ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( objVendor ) || !ValidateObject( objItemBought ) || tSock == nullptr || numItemsBuying == 0 ) return RV_NOFUNC; if( !ExistAndVerify( seOnBuyFromVendor, "onBuyFromVendor" )) return RV_NOFUNC; jsval rval, params[4]; JSObject *myObj = JSEngine->AcquireObject( IUE_SOCK, tSock, runTime ); JSObject *charObj = JSEngine->AcquireObject( IUE_CHAR, objVendor, runTime ); JSObject *myObj2 = nullptr; if( objItemBought->GetObjType() == OT_ITEM ) { myObj2 = JSEngine->AcquireObject( IUE_ITEM, objItemBought, runTime ); } params[0] = OBJECT_TO_JSVAL( myObj ); params[1] = OBJECT_TO_JSVAL( charObj ); params[2] = OBJECT_TO_JSVAL( myObj2 ); params[3] = INT_TO_JSVAL( numItemsBuying ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onBuyFromVendor", 4, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnBuyFromVendor, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnSellToVendor() //| Date - 26th November, 2011 //o------------------------------------------------------------------------------------------------o //| Purpose - Allows determining what happens when an item is in the process of being sold to //| an NPC vendor. Returning false/0 from script will halt the sale //o------------------------------------------------------------------------------------------------o SI08 cScript::OnSellToVendor( CSocket *tSock, CChar *objVendor, CBaseObject *objItemSold, UI16 numItemsSelling ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( objVendor ) || !ValidateObject( objItemSold ) || tSock == nullptr || numItemsSelling == 0 ) return RV_NOFUNC; if( !ExistAndVerify( seOnSellToVendor, "onSellToVendor" )) return RV_NOFUNC; jsval rval, params[4]; JSObject *myObj = JSEngine->AcquireObject( IUE_SOCK, tSock, runTime ); JSObject *charObj = JSEngine->AcquireObject( IUE_CHAR, objVendor, runTime ); JSObject *myObj2 = nullptr; if( objItemSold->GetObjType() == OT_ITEM ) { myObj2 = JSEngine->AcquireObject( IUE_ITEM, objItemSold, runTime ); } params[0] = OBJECT_TO_JSVAL( myObj ); params[1] = OBJECT_TO_JSVAL( charObj ); params[2] = OBJECT_TO_JSVAL( myObj2 ); params[3] = INT_TO_JSVAL( numItemsSelling ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onSellToVendor", 4, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnSellToVendor, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnBoughtFromVendor() //| Date - 26th November, 2011 //o------------------------------------------------------------------------------------------------o //| Purpose - Allows determining what happens AFTER an item has been //| bought from an NPC vendor //o------------------------------------------------------------------------------------------------o SI08 cScript::OnBoughtFromVendor( CSocket *tSock, CChar *objVendor, CBaseObject *objItemBought, UI16 numItemsBought ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( objVendor ) || !ValidateObject( objItemBought ) || tSock == nullptr ) return RV_NOFUNC; if( !ExistAndVerify( seOnBoughtFromVendor, "onBoughtFromVendor" )) return RV_NOFUNC; jsval rval, params[4]; JSObject *myObj = JSEngine->AcquireObject( IUE_SOCK, tSock, runTime ); JSObject *charObj = JSEngine->AcquireObject( IUE_CHAR, objVendor, runTime ); JSObject *myObj2 = nullptr; if( objItemBought->GetObjType() == OT_ITEM ) { myObj2 = JSEngine->AcquireObject( IUE_ITEM, objItemBought, runTime ); } params[0] = OBJECT_TO_JSVAL( myObj ); params[1] = OBJECT_TO_JSVAL( charObj ); params[2] = OBJECT_TO_JSVAL( myObj2 ); params[3] = INT_TO_JSVAL( numItemsBought ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onBoughtFromVendor", 4, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnBoughtFromVendor, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnSoldToVendor() //| Date - 26th November, 2011 //o------------------------------------------------------------------------------------------------o //| Purpose - Allows determining what happens AFTER an item has been //| sold to an NPC vendor //o------------------------------------------------------------------------------------------------o SI08 cScript::OnSoldToVendor( CSocket *tSock, CChar *objVendor, CBaseObject *objItemSold, UI16 numItemsSold ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( objVendor ) || !ValidateObject( objItemSold ) || tSock == nullptr ) return RV_NOFUNC; if( !ExistAndVerify( seOnSoldToVendor, "onSoldToVendor" )) return RV_NOFUNC; jsval rval, params[4]; JSObject *myObj = JSEngine->AcquireObject( IUE_SOCK, tSock, runTime ); JSObject *charObj = JSEngine->AcquireObject( IUE_CHAR, objVendor, runTime ); JSObject *myObj2 = nullptr; if( objItemSold->GetObjType() == OT_ITEM ) { myObj2 = JSEngine->AcquireObject( IUE_ITEM, objItemSold, runTime ); } params[0] = OBJECT_TO_JSVAL( myObj ); params[1] = OBJECT_TO_JSVAL( charObj ); params[2] = OBJECT_TO_JSVAL( myObj2 ); params[3] = INT_TO_JSVAL( numItemsSold ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onSoldToVendor", 4, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnSoldToVendor, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnHouseCommand() //o------------------------------------------------------------------------------------------------o //| Purpose - Allows overriding house commands via JS script attached to multi //o------------------------------------------------------------------------------------------------o SI08 cScript::OnHouseCommand( CSocket *tSock, CMultiObj *objMulti, UI08 cmdId ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( objMulti ) || tSock == nullptr ) return RV_NOFUNC; if( !ExistAndVerify( seOnHouseCommand, "onHouseCommand" )) return RV_NOFUNC; jsval rval, params[3]; JSObject *myObj = JSEngine->AcquireObject( IUE_SOCK, tSock, runTime ); JSObject *multiObj = JSEngine->AcquireObject( IUE_ITEM, objMulti, runTime ); params[0] = OBJECT_TO_JSVAL( myObj ); params[1] = OBJECT_TO_JSVAL( multiObj ); params[2] = INT_TO_JSVAL( cmdId ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onHouseCommand", 3, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnHouseCommand, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnMakeItem() //o------------------------------------------------------------------------------------------------o //| Purpose - Allows doing additional stuff with newly crafted items //o------------------------------------------------------------------------------------------------o SI08 cScript::OnMakeItem( CSocket *mSock, CChar *objChar, CItem *objItem, UI16 createEntryId ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( objChar ) || mSock == nullptr ) return RV_NOFUNC; if( !ExistAndVerify( seOnMakeItem, "onMakeItem" )) return RV_NOFUNC; jsval rval, params[4]; JSObject *mySock = JSEngine->AcquireObject( IUE_SOCK, mSock, runTime ); JSObject *myChar = JSEngine->AcquireObject( IUE_CHAR, objChar, runTime ); JSObject *myItem = JSEngine->AcquireObject( IUE_ITEM, objItem, runTime ); params[0] = OBJECT_TO_JSVAL( mySock ); params[1] = OBJECT_TO_JSVAL( myChar ); params[2] = OBJECT_TO_JSVAL( myItem ); params[3] = INT_TO_JSVAL( createEntryId ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onMakeItem", 4, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnMakeItem, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnPathfindEnd() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for NPCs after their pathfinding efforts come to and end //| Notes - pathfindResult gives a value that represents how the pathfinding ended //o------------------------------------------------------------------------------------------------o SI08 cScript::OnPathfindEnd( CChar *npc, SI08 pathfindResult ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( npc )) return RV_NOFUNC; if( !ExistAndVerify( seOnPathfindEnd, "onPathfindEnd" )) return RV_NOFUNC; JSObject *charObj = JSEngine->AcquireObject( IUE_CHAR, npc, runTime ); jsval params[2], rval; params[0] = OBJECT_TO_JSVAL( charObj ); params[1] = INT_TO_JSVAL( pathfindResult ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onPathfindEnd", 2, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnPathfindEnd, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnEnterEvadeState() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for NPCs when they enter the evade state after failing to pathfind to //| a target in combat //o------------------------------------------------------------------------------------------------o SI08 cScript::OnEnterEvadeState( CChar *npc, CChar *enemy ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( npc ) || !ValidateObject( enemy )) return RV_NOFUNC; if( !ExistAndVerify( seOnEnterEvadeState, "onEnterEvadeState" )) return RV_NOFUNC; JSObject *charObj = JSEngine->AcquireObject( IUE_CHAR, npc, runTime ); JSObject *enemyObj = JSEngine->AcquireObject( IUE_CHAR, enemy, runTime ); jsval params[2], rval; params[0] = OBJECT_TO_JSVAL( charObj ); params[1] = OBJECT_TO_JSVAL( enemyObj ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onEnterEvadeState", 2, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnEnterEvadeState, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnCarveCorpse() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for corpse of character when player attempts to carve said corpse //o------------------------------------------------------------------------------------------------o SI08 cScript::OnCarveCorpse( CChar *player, CItem *corpse ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( player ) || !ValidateObject( corpse )) return RV_NOFUNC; if( !ExistAndVerify( seOnCarveCorpse, "onCarveCorpse" )) return RV_NOFUNC; JSObject *charObj = JSEngine->AcquireObject( IUE_CHAR, player, runTime ); JSObject *corpseObj = JSEngine->AcquireObject( IUE_ITEM, corpse, runTime ); jsval params[2], rval; params[0] = OBJECT_TO_JSVAL( charObj ); params[1] = OBJECT_TO_JSVAL( corpseObj ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onCarveCorpse", 2, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnCarveCorpse, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } //o------------------------------------------------------------------------------------------------o //| Function - cScript::OnDyeTarget() //o------------------------------------------------------------------------------------------------o //| Purpose - Triggers for dye tub when player attempts to dye something with it //o------------------------------------------------------------------------------------------------o SI08 cScript::OnDyeTarget( CChar *player, CItem *dyeTub, CItem *target ) { const SI08 RV_NOFUNC = -1; if( !ValidateObject( player ) || !ValidateObject( dyeTub ) || !ValidateObject( target )) return RV_NOFUNC; if( !ExistAndVerify( seOnDyeTarget, "onDyeTarget" )) return RV_NOFUNC; JSObject *charObj = JSEngine->AcquireObject( IUE_CHAR, player, runTime ); JSObject *dyeTubObj = JSEngine->AcquireObject( IUE_ITEM, dyeTub, runTime ); JSObject *targObj = JSEngine->AcquireObject( IUE_ITEM, target, runTime ); jsval params[3], rval; params[0] = OBJECT_TO_JSVAL( charObj ); params[1] = OBJECT_TO_JSVAL( dyeTubObj ); params[2] = OBJECT_TO_JSVAL( targObj ); JSBool retVal = JS_CallFunctionName( targContext, targObject, "onDyeTarget", 3, params, &rval ); if( retVal == JS_FALSE ) { SetEventExists( seOnDyeTarget, false ); return RV_NOFUNC; } return TryParseJSVal( rval ); } bool cScript::EventExists( ScriptEvent eventNum ) const { UI32 index = eventNum / 64; if( index > 2 ) return false; return eventPresence[index].test(( eventNum % 64 )); } void cScript::SetEventExists( ScriptEvent eventNum, bool status ) { UI32 index = eventNum / 64; if( index > 2 ) return; eventPresence[index].set(( eventNum % 64 ), status ); } bool cScript::NeedsChecking( ScriptEvent eventNum ) const { UI32 index = eventNum / 64; if( index > 2 ) return false; return needsChecking[index].test(( eventNum % 64 )); } void cScript::SetNeedsChecking( ScriptEvent eventNum, bool status ) { UI32 index = eventNum / 64; if( index > 2 ) return; needsChecking[index].set(( eventNum % 64 ), status ); }
412
0.858715
1
0.858715
game-dev
MEDIA
0.852742
game-dev
0.668472
1
0.668472
mcedit/mcedit2
7,313
src/mceditlib/blocktypes/blockdumper/1.9/BlockDumper.java
package net.mcedit; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.client.renderer.BlockModelShapes; import net.minecraft.client.renderer.block.statemap.BlockStateMapper; import net.minecraft.client.renderer.block.model.ModelManager; import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; public class BlockDumper extends Block { private static final Logger logger = LogManager.getLogger(); public BlockDumper(Material par2Material) { super(par2Material); // TODO Auto-generated constructor stub } static String join(Collection<String> s, String delimiter) { StringBuilder builder = new StringBuilder(); Iterator<String> iter = s.iterator(); while (iter.hasNext()) { builder.append(iter.next()); if (!iter.hasNext()) { break; } builder.append(delimiter); } return builder.toString(); } public static void dump(ModelManager modelManager) { BlockModelShapes shapes = modelManager.getBlockModelShapes(); BlockStateMapper mapper = shapes.getBlockStateMapper(); Map<IBlockState, ModelResourceLocation> stateMap = mapper.putAllStateModelLocations(); HashSet<String> seenStates = new HashSet<String>(); try { // -- open streams -- FileOutputStream idMappingStream = new FileOutputStream(new File("idmapping_raw_19.json")); PrintWriter idMappingWriter = new PrintWriter(idMappingStream); idMappingWriter.print("[\n"); FileOutputStream blockDumpStream = new FileOutputStream(new File("minecraft_raw_19.json")); PrintWriter wri = new PrintWriter(blockDumpStream); wri.format("[\n"); FileOutputStream hiddenStatesStream = new FileOutputStream(new File("hiddenstates_19.json")); PrintWriter hiddenStatesWriter = new PrintWriter(hiddenStatesStream); hiddenStatesWriter.print("[\n"); ArrayList<String> hiddens = new ArrayList<String>(); ArrayList<String> idMapping = new ArrayList<String>(); ArrayList<String> blocks = new ArrayList<String>(); for (Block b : Block.REGISTRY) { int id = Block.REGISTRY.getIDForObject(b); ArrayList<String> attrs = new ArrayList<String>(); String internalName = Block.REGISTRY.getNameForObject(b).toString(); IBlockState defaultState = b.getDefaultState(); for (Object vso : b.getBlockState().getValidStates()) { IBlockState vs = (IBlockState) vso; ModelResourceLocation mrl = (ModelResourceLocation) stateMap.get(vs); if (vs != null && mrl != null) hiddens.add(String.format( "{\"blockState\":\"%s\", \"resourcePath\": \"%s\", \"resourceVariant\": \"%s\"}", vs.toString(), mrl.getResourcePath(), mrl.getVariant())); } attrs.add(String.format("\"internalName\": \"%s\"", internalName)); CreativeTabs creativeTabToDisplayOn = b.getCreativeTabToDisplayOn(); if (creativeTabToDisplayOn != null) { attrs.add(String.format("\"creativeTab\": \"%s\"", creativeTabToDisplayOn.getTabLabel())); } attrs.add(String.format("\"opaqueCube\": %s", defaultState.isOpaqueCube())); attrs.add(String.format("\"collidable\": %s", b.isCollidable())); attrs.add(String.format("\"hasEntity\": %s", b.hasTileEntity())); attrs.add(String.format("\"opacity\": %s", defaultState.getLightOpacity())); attrs.add(String.format("\"brightness\": %s", defaultState.getLightValue())); attrs.add(String.format("\"useNeighborBrightness\": %s", defaultState.useNeighborBrightness())); attrs.add(String.format("\"renderLayer\": \"%s\"", b.getBlockLayer())); ArrayList<ItemStack> subBlocks = new ArrayList<ItemStack>(); Map<Integer, ItemStack> subBlocksByMeta = new HashMap<Integer, ItemStack>(); ItemStack i; try { i = b.getItem(null, null, defaultState); b.getSubBlocks(i.getItem(), null, subBlocks); for (ItemStack stack : subBlocks) { int itemMeta = stack.getMetadata(); subBlocksByMeta.put(itemMeta, stack); } } catch (Exception e) { logger.warn(String.format("Failed to get subBlocks for block %s (error was %s)", b, e)); e.printStackTrace(); } int defaultMeta = b.getMetaFromState(defaultState); boolean hasItems = false; for (int meta = 0; meta < 16; meta++) { ArrayList<String> metaAttrs = (ArrayList<String>) attrs.clone(); try { IBlockState bs = b.getStateFromMeta(meta); String bsString = bs.toString(); if (seenStates.contains(bsString)) { continue; } seenStates.add(bsString); idMapping.add(String.format("[%d, %d, \"%s\"]", id, meta, bsString)); if (meta == defaultMeta) { metaAttrs.add("\"defaultState\": 1"); } metaAttrs.add(String.format("\"materialMapColor\": %d", bs.getMapColor().colorValue)); metaAttrs.add(String.format("\"blockState\": \"%s\"", bs.toString())); metaAttrs.add(String.format("\"renderType\": %d", bs.getRenderType().ordinal())); ModelResourceLocation loc = stateMap.get(bs); if (loc != null) { metaAttrs.add(String.format("\"resourcePath\": \"%s\"", loc.getResourcePath())); metaAttrs.add(String.format("\"resourceVariant\": \"%s\"", loc.getVariant())); } /* * block names aren't displayed so not all blocks * have a localizedName. we have to go through the * ItemStack for a displayName */ ItemStack stack = subBlocksByMeta.get(meta); try { metaAttrs.add(String.format("\"unlocalizedName\": \"%s\"", stack.getUnlocalizedName())); metaAttrs.add(String.format("\"displayName\": \"%s\"", stack.getDisplayName())); hasItems = true; } catch (NullPointerException e) { metaAttrs.add(String.format("\"unlocalizedName\": \"%s\"", b.getUnlocalizedName())); metaAttrs.add(String.format("\"displayName\": \"%s\"", b.getLocalizedName())); } blocks.add("{" + join(metaAttrs, ", ") + "}"); } catch (Exception e) { logger.warn(String.format("Failed to get meta %d for block %s (error was %s)", meta, b, e)); e.printStackTrace(); } } } idMappingWriter.println(join(idMapping, ",\n")); idMappingWriter.format("]\n"); idMappingWriter.close(); wri.println(join(blocks, ",\n")); wri.format("]\n"); wri.close(); blockDumpStream.close(); hiddenStatesWriter.println(join(hiddens, ",\n")); hiddenStatesWriter.format("]\n"); hiddenStatesWriter.close(); } catch (FileNotFoundException e) { } catch (IOException e) { } } // private static void addIcons(Block b, int damage, ArrayList<String> // attrs) { // for (int j = 0; j < 6; j++) { // Icon icon = b.getIcon(j, damage); // if(icon != null) { // attrs.add(String.format("\"iconName%d\": \"%s\"", j, // icon.getIconName())); // } // } // } }
412
0.857123
1
0.857123
game-dev
MEDIA
0.719746
game-dev
0.966886
1
0.966886
oot-pc-port/oot-pc-port
5,331
asm/non_matchings/overlays/actors/ovl_En_Ge1/func_80A32078.s
glabel func_80A32078 /* 01708 80A32078 27BDFFC0 */ addiu $sp, $sp, 0xFFC0 ## $sp = FFFFFFC0 /* 0170C 80A3207C AFBF002C */ sw $ra, 0x002C($sp) /* 01710 80A32080 AFB00028 */ sw $s0, 0x0028($sp) /* 01714 80A32084 AFA50044 */ sw $a1, 0x0044($sp) /* 01718 80A32088 848E008A */ lh $t6, 0x008A($a0) ## 0000008A /* 0171C 80A3208C 00808025 */ or $s0, $a0, $zero ## $s0 = 00000000 /* 01720 80A32090 24060006 */ addiu $a2, $zero, 0x0006 ## $a2 = 00000006 /* 01724 80A32094 AFAE0030 */ sw $t6, 0x0030($sp) /* 01728 80A32098 849800B6 */ lh $t8, 0x00B6($a0) ## 000000B6 /* 0172C 80A3209C 260400B6 */ addiu $a0, $s0, 0x00B6 ## $a0 = 000000B6 /* 01730 80A320A0 87A50032 */ lh $a1, 0x0032($sp) /* 01734 80A320A4 01D81023 */ subu $v0, $t6, $t8 /* 01738 80A320A8 00021400 */ sll $v0, $v0, 16 /* 0173C 80A320AC 00021403 */ sra $v0, $v0, 16 /* 01740 80A320B0 04400003 */ bltz $v0, .L80A320C0 /* 01744 80A320B4 00021823 */ subu $v1, $zero, $v0 /* 01748 80A320B8 10000001 */ beq $zero, $zero, .L80A320C0 /* 0174C 80A320BC 00401825 */ or $v1, $v0, $zero ## $v1 = 00000000 .L80A320C0: /* 01750 80A320C0 28614001 */ slti $at, $v1, 0x4001 /* 01754 80A320C4 10200013 */ beq $at, $zero, .L80A32114 /* 01758 80A320C8 24070FA0 */ addiu $a3, $zero, 0x0FA0 ## $a3 = 00000FA0 /* 0175C 80A320CC 24190064 */ addiu $t9, $zero, 0x0064 ## $t9 = 00000064 /* 01760 80A320D0 0C01E1A7 */ jal Math_SmoothScaleMaxMinS /* 01764 80A320D4 AFB90010 */ sw $t9, 0x0010($sp) /* 01768 80A320D8 860800B6 */ lh $t0, 0x00B6($s0) ## 000000B6 /* 0176C 80A320DC 8E0A0038 */ lw $t2, 0x0038($s0) ## 00000038 /* 01770 80A320E0 02002825 */ or $a1, $s0, $zero ## $a1 = 00000000 /* 01774 80A320E4 A6080032 */ sh $t0, 0x0032($s0) ## 00000032 /* 01778 80A320E8 AFAA0010 */ sw $t2, 0x0010($sp) /* 0177C 80A320EC 8E09003C */ lw $t1, 0x003C($s0) ## 0000003C /* 01780 80A320F0 8FA40044 */ lw $a0, 0x0044($sp) /* 01784 80A320F4 2606029C */ addiu $a2, $s0, 0x029C ## $a2 = 0000029C /* 01788 80A320F8 AFA90014 */ sw $t1, 0x0014($sp) /* 0178C 80A320FC 8E0A0040 */ lw $t2, 0x0040($s0) ## 00000040 /* 01790 80A32100 260702A2 */ addiu $a3, $s0, 0x02A2 ## $a3 = 000002A2 /* 01794 80A32104 0C00E0A4 */ jal func_80038290 /* 01798 80A32108 AFAA0018 */ sw $t2, 0x0018($sp) /* 0179C 80A3210C 1000001C */ beq $zero, $zero, .L80A32180 /* 017A0 80A32110 8FBF002C */ lw $ra, 0x002C($sp) .L80A32114: /* 017A4 80A32114 0441000A */ bgez $v0, .L80A32140 /* 017A8 80A32118 2604029E */ addiu $a0, $s0, 0x029E ## $a0 = 0000029E /* 017AC 80A3211C 240B0100 */ addiu $t3, $zero, 0x0100 ## $t3 = 00000100 /* 017B0 80A32120 AFAB0010 */ sw $t3, 0x0010($sp) /* 017B4 80A32124 2604029E */ addiu $a0, $s0, 0x029E ## $a0 = 0000029E /* 017B8 80A32128 2405E000 */ addiu $a1, $zero, 0xE000 ## $a1 = FFFFE000 /* 017BC 80A3212C 24060006 */ addiu $a2, $zero, 0x0006 ## $a2 = 00000006 /* 017C0 80A32130 0C01E1A7 */ jal Math_SmoothScaleMaxMinS /* 017C4 80A32134 24071838 */ addiu $a3, $zero, 0x1838 ## $a3 = 00001838 /* 017C8 80A32138 10000008 */ beq $zero, $zero, .L80A3215C /* 017CC 80A3213C 8605008A */ lh $a1, 0x008A($s0) ## 0000008A .L80A32140: /* 017D0 80A32140 240C0100 */ addiu $t4, $zero, 0x0100 ## $t4 = 00000100 /* 017D4 80A32144 AFAC0010 */ sw $t4, 0x0010($sp) /* 017D8 80A32148 24052000 */ addiu $a1, $zero, 0x2000 ## $a1 = 00002000 /* 017DC 80A3214C 24060006 */ addiu $a2, $zero, 0x0006 ## $a2 = 00000006 /* 017E0 80A32150 0C01E1A7 */ jal Math_SmoothScaleMaxMinS /* 017E4 80A32154 24071838 */ addiu $a3, $zero, 0x1838 ## $a3 = 00001838 /* 017E8 80A32158 8605008A */ lh $a1, 0x008A($s0) ## 0000008A .L80A3215C: /* 017EC 80A3215C 240D0064 */ addiu $t5, $zero, 0x0064 ## $t5 = 00000064 /* 017F0 80A32160 AFAD0010 */ sw $t5, 0x0010($sp) /* 017F4 80A32164 260400B6 */ addiu $a0, $s0, 0x00B6 ## $a0 = 000000B6 /* 017F8 80A32168 2406000C */ addiu $a2, $zero, 0x000C ## $a2 = 0000000C /* 017FC 80A3216C 0C01E1A7 */ jal Math_SmoothScaleMaxMinS /* 01800 80A32170 240703E8 */ addiu $a3, $zero, 0x03E8 ## $a3 = 000003E8 /* 01804 80A32174 860E00B6 */ lh $t6, 0x00B6($s0) ## 000000B6 /* 01808 80A32178 A60E0032 */ sh $t6, 0x0032($s0) ## 00000032 /* 0180C 80A3217C 8FBF002C */ lw $ra, 0x002C($sp) .L80A32180: /* 01810 80A32180 8FB00028 */ lw $s0, 0x0028($sp) /* 01814 80A32184 27BD0040 */ addiu $sp, $sp, 0x0040 ## $sp = 00000000 /* 01818 80A32188 03E00008 */ jr $ra /* 0181C 80A3218C 00000000 */ nop
412
0.690795
1
0.690795
game-dev
MEDIA
0.971217
game-dev
0.545268
1
0.545268
SaltieRL/DistributedReplays
4,491
backend/blueprints/spa_api/service_layers/replay/visibility.py
import time from datetime import datetime from backend.blueprints.spa_api.errors.errors import PlayerNotFound, ReplayNotFound, AuthorizationException, \ CalculatedError from backend.blueprints.spa_api.service_layers.utils import with_session from backend.database.objects import Player, GameVisibility, Game, Playlist from backend.blueprints.spa_api.utils.decorators import require_user from backend.database.objects import GameVisibilitySetting from backend.database.wrapper.player_wrapper import PlayerWrapper from backend.utils.logger import ErrorLogger class ReplayVisibility: def __init__(self, id_: str, visibility: GameVisibilitySetting): self.id = id_ self.visibility = visibility.value @staticmethod @require_user def change_replay_visibility(game_hash: str, visibility: GameVisibilitySetting, user_id='', release_date=None) -> 'ReplayVisibility': can_change = PlayerWrapper.have_permission_to_change_game(game_hash, user_id) if can_change: try: apply_game_visibility_explicit(user_id, visibility, release_date, game_hash) except CalculatedError as e: ErrorLogger.log_error(e) raise e else: ErrorLogger.log_error(AuthorizationException()) return ReplayVisibility(game_hash, visibility) def apply_game_visibility(query_params=None, game_id=None, game_exists=True, proto_game=None) -> Exception: # if it is a custom lobby we should try and fake it being a private game so scrims are not published. if (not game_exists and proto_game is not None and proto_game.game_metadata.playlist == Playlist.CUSTOM_LOBBY.value and query_params is not None and 'player_id' in query_params): query_params = {'player_id': query_params['player_id'], 'visibility': GameVisibilitySetting.PRIVATE} if query_params is None: return None if 'visibility' not in query_params: return None player_id = query_params['player_id'] visibility = query_params['visibility'] try: release_date = query_params['release_date'] except KeyError: release_date = None try: can_change = PlayerWrapper.have_permission_to_change_game(game_id, player_id) except ReplayNotFound: can_change = not game_exists if can_change: return apply_game_visibility_explicit(player_id, visibility, release_date, game_id) raise AuthorizationException() @with_session def apply_game_visibility_explicit(player_id, visibility: GameVisibilitySetting, release_date: datetime, game_id, session=None, retry=False): entry = session.query(GameVisibility).filter(GameVisibility.player == player_id, GameVisibility.game == game_id).first() if entry is not None and entry.visibility != visibility: entry.visibility = visibility session.commit() return update_game_visibility(game_id, session, visibility) player = session.query(Player).filter(Player.platformid == player_id).first() if player is not None: game_visibility_entry = GameVisibility(game=game_id, player=player_id, visibility=visibility) if release_date is not None: game_visibility_entry.release_date = release_date update_game_visibility(game_id, session, visibility) session.add(game_visibility_entry) # GameVisibility fails silently - does not do anything if player_id does not exist. session.commit() return None elif not retry: time.sleep(1) return apply_game_visibility_explicit(player_id, visibility, release_date, game_id=game_id, session=session, retry=True) raise PlayerNotFound() def update_game_visibility(game_id, session, visibility: GameVisibilitySetting, retry=False): game = session.query(Game).filter(Game.hash == game_id).first() if game is None: if not retry: time.sleep(1) return update_game_visibility(game_id=game_id, session=session, visibility=visibility, retry=True) raise ReplayNotFound() if game.visibility == visibility: return game.visibility = visibility session.commit() return
412
0.870854
1
0.870854
game-dev
MEDIA
0.435655
game-dev
0.896311
1
0.896311
Aspw-w/NightX-Client
5,562
src/main/java/net/aspw/client/features/module/impl/player/CivBreak.kt
package net.aspw.client.features.module.impl.player import net.aspw.client.Launch import net.aspw.client.event.* import net.aspw.client.features.module.Module import net.aspw.client.features.module.ModuleCategory import net.aspw.client.features.module.ModuleInfo import net.aspw.client.features.module.impl.visual.SilentRotations import net.aspw.client.utils.PacketUtils import net.aspw.client.utils.RotationUtils import net.aspw.client.utils.block.BlockUtils import net.aspw.client.utils.render.RenderUtils import net.aspw.client.value.BoolValue import net.aspw.client.value.FloatValue import net.aspw.client.value.IntegerValue import net.aspw.client.value.ListValue import net.minecraft.block.BlockAir import net.minecraft.network.play.client.C07PacketPlayerDigging import net.minecraft.network.play.client.C0APacketAnimation import net.minecraft.util.BlockPos import net.minecraft.util.EnumFacing import java.awt.Color import java.util.* @ModuleInfo(name = "CivBreak", spacedName = "Civ Break", category = ModuleCategory.PLAYER) class CivBreak : Module() { private var blockPos: BlockPos? = null private var enumFacing: EnumFacing? = null private var isBreaking = false private val modeValue = ListValue("Mode", arrayOf("Instant", "Legit"), "Instant") private val delayValue = IntegerValue("Instant-Delay", 1, 1, 20) { modeValue.get().equals("instant", true) } private val range = FloatValue("Range", 5F, 1F, 6F) private val rotationsValue = BoolValue("Rotations", true) private val swingValue = ListValue("Swing", arrayOf("Normal", "Packet", "None"), "Packet") private val airResetValue = BoolValue("Air-Reset", false) private val rangeResetValue = BoolValue("Range-Reset", false) private val redValue = IntegerValue("R", 255, 0, 255) private val greenValue = IntegerValue("G", 255, 0, 255) private val blueValue = IntegerValue("B", 255, 0, 255) private val outLine = BoolValue("Outline", true) override val tag: String get() = modeValue.get() @EventTarget fun onBlockClick(event: ClickBlockEvent) { blockPos = event.clickedBlock enumFacing = event.enumFacing } override fun onDisable() { blockPos ?: return blockPos = null isBreaking = false } @EventTarget fun onJump(event: JumpEvent) { if (blockPos != null && rotationsValue.get() && Launch.moduleManager.getModule( SilentRotations::class.java )?.state!! && Launch.moduleManager.getModule(SilentRotations::class.java)?.customStrafe?.get()!! ) event.yaw = RotationUtils.cameraYaw } @EventTarget fun onStrafe(event: StrafeEvent) { if (blockPos != null && rotationsValue.get() && Launch.moduleManager.getModule( SilentRotations::class.java )?.state!! && Launch.moduleManager.getModule(SilentRotations::class.java)?.customStrafe?.get()!! ) event.yaw = RotationUtils.cameraYaw } @EventTarget fun onUpdate(event: UpdateEvent) { if (blockPos !== null) { if (modeValue.get().equals("legit", true)) { mc.playerController.onPlayerDamageBlock(blockPos, enumFacing) when (swingValue.get().lowercase(Locale.getDefault())) { "normal" -> mc.thePlayer.swingItem() "packet" -> mc.netHandler.addToSendQueue(C0APacketAnimation()) } } } } @EventTarget fun onMotion(event: MotionEvent) { val pos = blockPos ?: return if (airResetValue.get() && BlockUtils.getBlock(pos) is BlockAir || rangeResetValue.get() && BlockUtils.getCenterDistance(pos) > range.get() ) { blockPos = null isBreaking = false return } if (BlockUtils.getBlock(pos) is BlockAir || BlockUtils.getCenterDistance(pos) > range.get()) { isBreaking = false return } if (blockPos !== null) { isBreaking = true } if (blockPos == null) { isBreaking = false } when (event.eventState) { EventState.PRE -> { if (rotationsValue.get()) { RotationUtils.setTargetRotation(RotationUtils.faceBlock(pos)?.rotation!!) } } EventState.POST -> { if (modeValue.get().equals("instant", true)) { if (mc.thePlayer.ticksExisted % delayValue.get() == 0) { when (swingValue.get().lowercase(Locale.getDefault())) { "normal" -> mc.thePlayer.swingItem() "packet" -> mc.netHandler.addToSendQueue(C0APacketAnimation()) } repeat(2) { PacketUtils.sendPacketNoEvent( C07PacketPlayerDigging( C07PacketPlayerDigging.Action.STOP_DESTROY_BLOCK, blockPos, enumFacing ) ) } } } } } } @EventTarget fun onRender3D(event: Render3DEvent) { RenderUtils.drawBlockBox( blockPos ?: return, Color(redValue.get(), greenValue.get(), blueValue.get()), outLine.get() ) } }
412
0.914325
1
0.914325
game-dev
MEDIA
0.747439
game-dev
0.952912
1
0.952912
LiamKenneth/ArchaicQuest
2,787
MIMWebClient/Core/Events/Harvest.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace MIMWebClient.Core.Events { public class Harvest { public static void Body(PlayerSetup.Player player, Room.Room room, string commandOptions) { if (string.IsNullOrEmpty(commandOptions)) { return; } var foundCorpse = room.items.FirstOrDefault(x => x.name.ToLower().Contains(commandOptions.ToLower())); if (foundCorpse == null) { HubContext.Instance.SendToClient("No corpse found.", player.HubGuid); return; } var corpseName = foundCorpse.name.ToLower(); var corpse = string.Empty; if (corpseName.Contains("decayed")) { corpse = corpseName.Replace("the decayed corpse of ", ""); } else if (corpseName.Contains("rotting")) { corpse = corpseName.Replace("the rotting corpse of ", ""); } else { corpse = corpseName.Replace("the corpse of ", ""); } var carveMessage = "You carve " + corpse + " retrieving "; var bodyPart = GetBodyPart(); HubContext.Instance.SendToClient(carveMessage + Helpers.ReturnName(null, null, bodyPart).ToLower() + ".", player.HubGuid); if (bodyPart == "nothing") { return; } if (foundCorpse.KnownByName) { } var bodybit = new Item.Item() { name = corpse + " " + bodyPart, location = Item.Item.ItemLocation.Inventory, slot = Item.Item.EqSlot.Held, eqSlot = Item.Item.EqSlot.Held, equipable = true, }; if (foundCorpse.KnownByName) { bodybit.KnownByName = true; } PlayerSetup.Player.AddItem(player, bodybit); Score.UpdateUiInventory(player); if (room.items.FirstOrDefault(x => x.name.ToLower().Contains(commandOptions)) != null) { room.items.Remove(foundCorpse); } } public static string GetBodyPart() { var rand = Helpers.Rand(1, 5); switch (rand) { case 1: return "eyeball"; case 2: return "ear"; case 3: return "tooth"; case 4: return "rib bone"; } return "nothing"; } } }
412
0.83587
1
0.83587
game-dev
MEDIA
0.879207
game-dev
0.842643
1
0.842643
remmintan/minefortress
2,978
src/networking/java/net/remmintan/mods/minefortress/networking/c2s/ServerboundBlueprintTaskPacket.java
package net.remmintan.mods.minefortress.networking.c2s; import net.minecraft.network.PacketByteBuf; import net.minecraft.server.MinecraftServer; import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.util.BlockRotation; import net.minecraft.util.math.BlockPos; import net.remmintan.mods.minefortress.core.interfaces.networking.FortressC2SPacket; import net.remmintan.mods.minefortress.core.utils.ServerPlayerEntityExtensionsKt; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.List; import java.util.UUID; public class ServerboundBlueprintTaskPacket implements FortressC2SPacket { private final String blueprintId; private final BlockPos startPos; private final BlockRotation rotation; private final int floorLevel; private final List<Integer> selectedPawns; private final BlockPos upgradedBuildingPos; public ServerboundBlueprintTaskPacket(String blueprintId, BlockPos startPos, BlockRotation rotation, int floorLevel, List<Integer> selectedPawns, BlockPos upgradedBuildingPos) { this.blueprintId = blueprintId; this.startPos = startPos; this.rotation = rotation; this.floorLevel = floorLevel; this.selectedPawns = selectedPawns; this.upgradedBuildingPos = upgradedBuildingPos; } public ServerboundBlueprintTaskPacket(PacketByteBuf buf) { this.blueprintId = buf.readString(); this.startPos = buf.readBlockPos(); this.rotation = buf.readEnumConstant(BlockRotation.class); this.floorLevel = buf.readInt(); this.selectedPawns = new ArrayList<>(); final int size = buf.readInt(); for (int i = 0; i < size; i++) { selectedPawns.add(buf.readInt()); } this.upgradedBuildingPos = buf.readNullable(PacketByteBuf::readBlockPos); } @Override public void write(PacketByteBuf buf) { buf.writeString(blueprintId); buf.writeBlockPos(startPos); buf.writeEnumConstant(rotation); buf.writeInt(floorLevel); buf.writeInt(selectedPawns.size()); for (Integer selectedPawn : selectedPawns) { buf.writeInt(selectedPawn); } buf.writeNullable(upgradedBuildingPos, PacketByteBuf::writeBlockPos); } @Override public void handle(@NotNull MinecraftServer server, @NotNull ServerPlayerEntity player) { final var provider = getManagersProvider(player); final var blueprintManager = ServerPlayerEntityExtensionsKt.getManagersProvider(player).get_BlueprintManager(); if (upgradedBuildingPos != null) { provider.getBuildingsManager().destroyBuilding(upgradedBuildingPos); } final var taskId = UUID.randomUUID(); final var task = blueprintManager.createAreaBasedTask(taskId, blueprintId, startPos, rotation, server.getOverworld()); provider.getTaskManager().addTask(task, selectedPawns, player); } }
412
0.742859
1
0.742859
game-dev
MEDIA
0.968601
game-dev,networking
0.959358
1
0.959358
Shestak/ShestakUI
19,498
ShestakUI/Libs/oUF/Elements/Tags.lua
-- Credits: Vika, Cladhaire, Tekkub local _, ns = ... local oUF = ns.oUF local Private = oUF.Private local nierror = Private.nierror local unitExists = Private.unitExists local xpcall = Private.xpcall local _PATTERN = '%[..-%]+' local _ENV = { Hex = function(r, g, b) if(type(r) == 'table') then if(r.r) then r, g, b = r.r, r.g, r.b else r, g, b = unpack(r) end end return string.format('|cff%02x%02x%02x', r * 255, g * 255, b * 255) end, } _ENV.ColorGradient = function(...) return _ENV._FRAME:ColorGradient(...) end local _PROXY = setmetatable(_ENV, {__index = _G}) local tagStrings = { ['affix'] = [[function(u) local c = UnitClassification(u) if(c == 'minus') then return 'Affix' end end]], ['arcanecharges'] = [[function() if(GetSpecialization() == SPEC_MAGE_ARCANE) then local num = UnitPower('player', Enum.PowerType.ArcaneCharges) if(num > 0) then return num end end end]], ['arenaspec'] = [[function(u) local id = u:match('arena(%d)$') if(id) then local specID = GetArenaOpponentSpec(tonumber(id)) if(specID and specID > 0) then local _, specName = GetSpecializationInfoByID(specID) return specName end end end]], ['chi'] = [[function() if(GetSpecialization() == SPEC_MONK_WINDWALKER) then local num = UnitPower('player', Enum.PowerType.Chi) if(num > 0) then return num end end end]], ['classification'] = [[function(u) local c = UnitClassification(u) if(c == 'rare') then return 'Rare' elseif(c == 'rareelite') then return 'Rare Elite' elseif(c == 'elite') then return 'Elite' elseif(c == 'worldboss') then return 'Boss' elseif(c == 'minus') then return 'Affix' end end]], ['cpoints'] = [[function(u) local cp = UnitPower(u, Enum.PowerType.ComboPoints) if(cp > 0) then return cp end end]], ['creature'] = [[function(u) return UnitCreatureFamily(u) or UnitCreatureType(u) end]], ['curmana'] = [[function(unit) return UnitPower(unit, Enum.PowerType.Mana) end]], ['dead'] = [[function(u) if(UnitIsDead(u)) then return 'Dead' elseif(UnitIsGhost(u)) then return 'Ghost' end end]], ['deficit:name'] = [[function(u) local missinghp = _TAGS['missinghp'](u) if(missinghp) then return '-' .. missinghp else return _TAGS['name'](u) end end]], ['difficulty'] = [[function(u) if UnitCanAttack('player', u) then local l = UnitEffectiveLevel(u) return Hex(GetCreatureDifficultyColor((l > 0) and l or 999)) end end]], ['group'] = [[function(unit) local name, server = UnitName(unit) if(server and server ~= '') then name = string.format('%s-%s', name, server) end for i=1, GetNumGroupMembers() do local raidName, _, group = GetRaidRosterInfo(i) if( raidName == name ) then return group end end end]], ['holypower'] = [[function() if(GetSpecialization() == SPEC_PALADIN_RETRIBUTION) then local num = UnitPower('player', Enum.PowerType.HolyPower) if(num > 0) then return num end end end]], ['leader'] = [[function(u) if(UnitIsGroupLeader(u)) then return 'L' end end]], ['leaderlong'] = [[function(u) if(UnitIsGroupLeader(u)) then return 'Leader' end end]], ['level'] = [[function(u) local l = UnitEffectiveLevel(u) if(UnitIsWildBattlePet(u) or UnitIsBattlePetCompanion(u)) then l = UnitBattlePetLevel(u) end if(l > 0) then return l else return '??' end end]], ['maxmana'] = [[function(unit) return UnitPowerMax(unit, Enum.PowerType.Mana) end]], ['missinghp'] = [[function(u) local current = UnitHealthMax(u) - UnitHealth(u) if(current > 0) then return current end end]], ['missingpp'] = [[function(u) local current = UnitPowerMax(u) - UnitPower(u) if(current > 0) then return current end end]], ['name'] = [[function(u, r) return UnitName(r or u) end]], ['offline'] = [[function(u) if(not UnitIsConnected(u)) then return 'Offline' end end]], ['perhp'] = [[function(u) local m = UnitHealthMax(u) if(m == 0) then return 0 else return math.floor(UnitHealth(u) / m * 100 + .5) end end]], ['perpp'] = [[function(u) local m = UnitPowerMax(u) if(m == 0) then return 0 else return math.floor(UnitPower(u) / m * 100 + .5) end end]], ['plus'] = [[function(u) local c = UnitClassification(u) if(c == 'elite' or c == 'rareelite') then return '+' end end]], ['powercolor'] = [[function(u) local pType, pToken, altR, altG, altB = UnitPowerType(u) local t = _COLORS.power[pToken] if(not t) then if(altR) then if(altR > 1 or altG > 1 or altB > 1) then return Hex(altR / 255, altG / 255, altB / 255) else return Hex(altR, altG, altB) end else return Hex(_COLORS.power[pType] or _COLORS.power.MANA) end end return Hex(t) end]], ['pvp'] = [[function(u) if(UnitIsPVP(u)) then return 'PvP' end end]], ['raidcolor'] = [[function(u) local _, class = UnitClass(u) if(class) then return Hex(_COLORS.class[class]) else local id = u:match('arena(%d)$') if(id) then local specID = GetArenaOpponentSpec(tonumber(id)) if(specID and specID > 0) then _, _, _, _, _, class = GetSpecializationInfoByID(specID) return Hex(_COLORS.class[class]) end end end end]], ['rare'] = [[function(u) local c = UnitClassification(u) if(c == 'rare' or c == 'rareelite') then return 'Rare' end end]], ['resting'] = [[function(u) if(u == 'player' and IsResting()) then return 'zzz' end end]], ['runes'] = [[function() local amount = 0 for i = 1, 6 do local _, _, ready = GetRuneCooldown(i) if(ready) then amount = amount + 1 end end return amount end]], ['sex'] = [[function(u) local s = UnitSex(u) if(s == 2) then return 'Male' elseif(s == 3) then return 'Female' end end]], ['shortclassification'] = [[function(u) local c = UnitClassification(u) if(c == 'rare') then return 'R' elseif(c == 'rareelite') then return 'R+' elseif(c == 'elite') then return '+' elseif(c == 'worldboss') then return 'B' elseif(c == 'minus') then return '-' end end]], ['smartclass'] = [[function(u) if(UnitIsPlayer(u)) then return _TAGS['class'](u) end return _TAGS['creature'](u) end]], ['smartlevel'] = [[function(u) local c = UnitClassification(u) if(c == 'worldboss') then return 'Boss' else local plus = _TAGS['plus'](u) local level = _TAGS['level'](u) if(plus) then return level .. plus else return level end end end]], ['soulshards'] = [[function() local num = UnitPower('player', Enum.PowerType.SoulShards) if(num > 0) then return num end end]], ['status'] = [[function(u) if(UnitIsDead(u)) then return 'Dead' elseif(UnitIsGhost(u)) then return 'Ghost' elseif(not UnitIsConnected(u)) then return 'Offline' else return _TAGS['resting'](u) end end]], ['threat'] = [[function(u) local s = UnitThreatSituation(u) if(s == 1) then return '++' elseif(s == 2) then return '--' elseif(s == 3) then return 'Aggro' end end]], ['threatcolor'] = [[function(u) return Hex(GetThreatStatusColor(UnitThreatSituation(u))) end]], } local tags = setmetatable( { curhp = UnitHealth, curpp = UnitPower, maxhp = UnitHealthMax, maxpp = UnitPowerMax, class = UnitClass, faction = UnitFactionGroup, race = UnitRace, }, { __index = function(self, key) local tagString = tagStrings[key] if(tagString) then self[key] = tagString tagStrings[key] = nil end return rawget(self, key) end, __newindex = function(self, key, val) if(type(val) == 'string') then local func, err = loadstring('return ' .. val) if(func) then val = func() else error(err, 3) end end assert(type(val) == 'function', 'Tag function must be a function or a string that evaluates to a function.') -- We don't want to clash with any custom envs if(getfenv(val) == _G) then -- pcall is needed for cases when Blizz functions are passed as -- strings, for intance, 'UnitPowerMax', an attempt to set a -- custom env will result in an error pcall(setfenv, val, _PROXY) end rawset(self, key, val) end, } ) _ENV._TAGS = tags local vars = setmetatable({}, { __newindex = function(self, key, val) if(type(val) == 'string') then local func = loadstring('return ' .. val) if(func) then val = func() or val end end rawset(self, key, val) end, }) _ENV._VARS = vars local tagEvents = { ['affix'] = 'UNIT_CLASSIFICATION_CHANGED', ['arcanecharges'] = 'UNIT_POWER_UPDATE PLAYER_TALENT_UPDATE', ['arenaspec'] = 'ARENA_PREP_OPPONENT_SPECIALIZATIONS', ['chi'] = 'UNIT_POWER_UPDATE PLAYER_TALENT_UPDATE', ['classification'] = 'UNIT_CLASSIFICATION_CHANGED', ['cpoints'] = 'UNIT_POWER_FREQUENT PLAYER_TARGET_CHANGED', ['curhp'] = 'UNIT_HEALTH UNIT_MAXHEALTH', ['curmana'] = 'UNIT_POWER_UPDATE UNIT_MAXPOWER', ['curpp'] = 'UNIT_POWER_UPDATE UNIT_MAXPOWER', ['dead'] = 'UNIT_HEALTH', ['deficit:name'] = 'UNIT_HEALTH UNIT_MAXHEALTH UNIT_NAME_UPDATE', ['difficulty'] = 'UNIT_FACTION', ['faction'] = 'NEUTRAL_FACTION_SELECT_RESULT', ['group'] = 'GROUP_ROSTER_UPDATE', ['holypower'] = 'UNIT_POWER_UPDATE PLAYER_TALENT_UPDATE', ['leader'] = 'PARTY_LEADER_CHANGED', ['leaderlong'] = 'PARTY_LEADER_CHANGED', ['level'] = 'UNIT_LEVEL PLAYER_LEVEL_UP', ['maxhp'] = 'UNIT_MAXHEALTH', ['maxmana'] = 'UNIT_POWER_UPDATE UNIT_MAXPOWER', ['maxpp'] = 'UNIT_MAXPOWER', ['missinghp'] = 'UNIT_HEALTH UNIT_MAXHEALTH', ['missingpp'] = 'UNIT_MAXPOWER UNIT_POWER_UPDATE', ['name'] = 'UNIT_NAME_UPDATE', ['offline'] = 'UNIT_HEALTH UNIT_CONNECTION', ['perhp'] = 'UNIT_HEALTH UNIT_MAXHEALTH', ['perpp'] = 'UNIT_MAXPOWER UNIT_POWER_UPDATE', ['plus'] = 'UNIT_CLASSIFICATION_CHANGED', ['powercolor'] = 'UNIT_DISPLAYPOWER', ['pvp'] = 'UNIT_FACTION', ['rare'] = 'UNIT_CLASSIFICATION_CHANGED', ['resting'] = 'PLAYER_UPDATE_RESTING', ['runes'] = 'RUNE_POWER_UPDATE', ['shortclassification'] = 'UNIT_CLASSIFICATION_CHANGED', ['smartlevel'] = 'UNIT_LEVEL PLAYER_LEVEL_UP UNIT_CLASSIFICATION_CHANGED', ['soulshards'] = 'UNIT_POWER_UPDATE', ['status'] = 'UNIT_HEALTH PLAYER_UPDATE_RESTING UNIT_CONNECTION', ['threat'] = 'UNIT_THREAT_SITUATION_UPDATE', ['threatcolor'] = 'UNIT_THREAT_SITUATION_UPDATE', } local unitlessEvents = { ARENA_PREP_OPPONENT_SPECIALIZATIONS = true, GROUP_ROSTER_UPDATE = true, NEUTRAL_FACTION_SELECT_RESULT = true, PARTY_LEADER_CHANGED = true, PLAYER_LEVEL_UP = true, PLAYER_TALENT_UPDATE = true, PLAYER_TARGET_CHANGED = true, PLAYER_UPDATE_RESTING = true, RUNE_POWER_UPDATE = true, } local events = {} local eventFrame = CreateFrame('Frame') eventFrame:SetScript('OnEvent', function(self, event, unit) local strings = events[event] if(strings) then for _, fs in next, strings do if(fs:IsVisible() and (unitlessEvents[event] or fs.parent.unit == unit or (fs.extraUnits and fs.extraUnits[unit]))) then fs:UpdateTag() end end end end) local onUpdates = {} local eventlessUnits = {} local function createOnUpdate(timer) if(not onUpdates[timer]) then local total = timer local frame = CreateFrame('Frame') local strings = eventlessUnits[timer] frame:SetScript('OnUpdate', function(self, elapsed) if(total >= timer) then for _, fs in next, strings do if(fs.parent:IsShown() and unitExists(fs.parent.unit)) then fs:UpdateTag() end end total = 0 end total = total + elapsed end) onUpdates[timer] = frame end end --[[ Tags: frame:UpdateTags() Used to update all tags on a frame. * self - the unit frame from which to update the tags --]] local function Update(self) if(self.__tags) then for fs in next, self.__tags do fs:UpdateTag() end end end local tagPool = {} local funcPool = {} local tmp = {} -- full tag syntax: '[prefix$>tag-name<$suffix(a,r,g,s)]' -- for a small test case see https://github.com/oUF-wow/oUF/pull/602 local function getBracketData(tag) local prefixEnd, prefixOffset = tag:match('()$>'), 1 if(not prefixEnd) then prefixEnd = 1 else prefixEnd = prefixEnd - 1 prefixOffset = 3 end local suffixEnd = (tag:match('()%(', prefixOffset + 1) or -1) - 1 local suffixStart, suffixOffset = tag:match('<$()', prefixEnd), 1 if(not suffixStart) then suffixStart = suffixEnd + 1 else suffixOffset = 3 end return tag:sub(prefixEnd + prefixOffset, suffixStart - suffixOffset), prefixEnd, suffixStart, suffixEnd, tag:match('%((.-)%)', suffixOffset + 1) end local function getTagFunc(tagstr) local func = tagPool[tagstr] if(not func) then local format, numTags = tagstr:gsub('%%', '%%%%'):gsub(_PATTERN, '%%s') local args = {} local idx = 1 local format_ = {} for i = 1, numTags do format_[i] = '%s' end for bracket in tagstr:gmatch(_PATTERN) do local tagFunc = funcPool[bracket] or tags[bracket:sub(2, -2)] if(not tagFunc) then local tagName, prefixEnd, suffixStart, suffixEnd, customArgs = getBracketData(bracket) local tag = tags[tagName] if(tag) then if(prefixEnd ~= 1 or suffixStart - suffixEnd ~= 1) then local prefix = prefixEnd ~= 1 and bracket:sub(2, prefixEnd) or '' local suffix = suffixStart - suffixEnd ~= 1 and bracket:sub(suffixStart, suffixEnd) or '' tagFunc = function(unit, realUnit) local str if(customArgs) then str = tag(unit, realUnit, string.split(',', customArgs)) else str = tag(unit, realUnit) end if(str and str ~= '') then return prefix .. str .. suffix end end else tagFunc = function(unit, realUnit) local str if(customArgs) then str = tag(unit, realUnit, string.split(',', customArgs)) else str = tag(unit, realUnit) end if(str and str ~= '') then return str end end end funcPool[bracket] = tagFunc end end if(tagFunc) then table.insert(args, tagFunc) idx = idx + 1 else nierror(string.format('Attempted to use invalid tag %s.', bracket)) format_[idx] = bracket format = format:format(unpack(format_, 1, numTags)) format_[idx] = '%s' numTags = numTags - 1 end end func = function(self) local parent = self.parent local unit = parent.unit local realUnit if(self.overrideUnit) then realUnit = parent.realUnit end _ENV._COLORS = parent.colors _ENV._FRAME = parent for i, f in next, args do tmp[i] = f(unit, realUnit) or '' end -- We do 1, numTags because tmp can hold several unneeded variables. return self:SetFormattedText(format, unpack(tmp, 1, numTags)) end tagPool[tagstr] = func end return func end local function registerEvent(fontstr, event) if(not events[event]) then events[event] = {} end local isOK = xpcall(eventFrame.RegisterEvent, eventFrame, event) if(isOK) then table.insert(events[event], fontstr) end end local function registerEvents(fontstr, tagstr) for tag in tagstr:gmatch(_PATTERN) do tag = getBracketData(tag) local tagevents = tagEvents[tag] if(tagevents) then for event in tagevents:gmatch('%S+') do registerEvent(fontstr, event) end end end end local function unregisterEvents(fontstr) for event, data in next, events do local index = 1 local tagfsstr = data[index] while tagfsstr do if(tagfsstr == fontstr) then if(#data == 1) then eventFrame:UnregisterEvent(event) end table.remove(data, index) else index = index + 1 end tagfsstr = data[index] end end end local taggedFS = {} --[[ Tags: frame:Tag(fs, tagstr, ...) Used to register a tag on a unit frame. * self - the unit frame on which to register the tag * fs - the font string to display the tag (FontString) * tagstr - the tag string (string) * ... - additional optional unitID(s) the tag should update for --]] local function Tag(self, fs, tagstr, ...) if(not fs or not tagstr) then return end if(not self.__tags) then self.__tags = {} table.insert(self.__elements, Update) elseif(self.__tags[fs]) then -- We don't need to remove it from the __tags table as Untag handles -- that for us. self:Untag(fs) end fs.parent = self fs.UpdateTag = getTagFunc(tagstr) if(self.__eventless or fs.frequentUpdates) then local timer if(type(fs.frequentUpdates) == 'number') then timer = fs.frequentUpdates else timer = .5 end if(not eventlessUnits[timer]) then eventlessUnits[timer] = {} end table.insert(eventlessUnits[timer], fs) createOnUpdate(timer) else registerEvents(fs, tagstr) if(...) then if(not fs.extraUnits) then fs.extraUnits = {} end for index = 1, select('#', ...) do fs.extraUnits[select(index, ...)] = true end end end taggedFS[fs] = tagstr self.__tags[fs] = true end --[[ Tags: frame:Untag(fs) Used to unregister a tag from a unit frame. * self - the unit frame from which to unregister the tag * fs - the font string holding the tag (FontString) --]] local function Untag(self, fs) if(not fs or not self.__tags) then return end unregisterEvents(fs) for _, timers in next, eventlessUnits do local index = 1 local fontstr = timers[index] while fontstr do if(fs == fontstr) then table.remove(timers, index) else index = index + 1 end fontstr = timers[index] end end fs.UpdateTag = nil taggedFS[fs] = nil self.__tags[fs] = nil end local function strip(tag) -- remove prefix, custom args, and suffix return tag:gsub('%[.-$>', '['):gsub('%(.-%)%]', ']'):gsub('<$.-%]', ']') end oUF.Tags = { Methods = tags, Events = tagEvents, SharedEvents = unitlessEvents, Vars = vars, RefreshMethods = function(self, tag) if(not tag) then return end -- If a tag's name contains magic chars, there's a chance that -- string.match will fail to find the match. tag = '%[' .. tag:gsub('[%^%$%(%)%%%.%*%+%-%?]', '%%%1') .. '%]' for func in next, funcPool do if(strip(func):match(tag)) then funcPool[func] = nil end end for tagstr, func in next, tagPool do if(strip(tagstr):match(tag)) then tagPool[tagstr] = nil for fs in next, taggedFS do if(fs.UpdateTag == func) then fs.UpdateTag = getTagFunc(tagstr) if(fs:IsVisible()) then fs:UpdateTag() end end end end end end, RefreshEvents = function(self, tag) if(not tag) then return end -- If a tag's name contains magic chars, there's a chance that -- string.match will fail to find the match. tag = '%[' .. tag:gsub('[%^%$%(%)%%%.%*%+%-%?]', '%%%1') .. '%]' for tagstr in next, tagPool do if(strip(tagstr):match(tag)) then for fs, ts in next, taggedFS do if(ts == tagstr) then unregisterEvents(fs) registerEvents(fs, tagstr) end end end end end, } oUF:RegisterMetaFunction('Tag', Tag) oUF:RegisterMetaFunction('Untag', Untag) oUF:RegisterMetaFunction('UpdateTags', Update)
412
0.785736
1
0.785736
game-dev
MEDIA
0.576052
game-dev
0.982078
1
0.982078
b-crawl/bcrawl
18,389
crawl-ref/source/quiver.cc
/** * @file * @brief Player quiver functionality * * - Only change last_used when actually using * - Not changing Qv; nobody knows about internals * - Track last_used of each type so each weapon can do the right thing **/ #include "AppHdr.h" #include "quiver.h" #include <algorithm> #include "env.h" #include "invent.h" #include "item-prop.h" #include "items.h" #include "options.h" #include "player.h" #include "prompt.h" #include "sound.h" #include "stringutil.h" #include "tags.h" #include "throw.h" static int _get_pack_slot(const item_def&); static ammo_t _get_weapon_ammo_type(const item_def*); static bool _item_matches(const item_def &item, fire_type types, const item_def* launcher, bool manual); static bool _items_similar(const item_def& a, const item_def& b, bool force = true); // ---------------------------------------------------------------------- // player_quiver // ---------------------------------------------------------------------- player_quiver::player_quiver() : m_last_used_type(AMMO_THROW) { COMPILE_CHECK(ARRAYSZ(m_last_used_of_type) == NUM_AMMO); } // Return: // *slot_out filled in with the inv slot of the item we would like // to fire by default. If -1, the inv doesn't contain our desired // item. // // *item_out filled in with item we would like to fire by default. // This can be returned even if the item is not in inv (although if // it is in inv, a reference to the inv item, with accurate count, // is returned) // // This is the item that will be displayed in Qv: // void player_quiver::get_desired_item(const item_def** item_out, int* slot_out) const { const int slot = _get_pack_slot(m_last_used_of_type[m_last_used_type]); if (slot == -1) { // Not in inv, but caller can at least get the type of the item. if (item_out) *item_out = &m_last_used_of_type[m_last_used_type]; } else { // Return the item in inv, since it will have an accurate count. if (item_out) *item_out = &you.inv[slot]; } if (slot_out) *slot_out = slot; } // Return inv slot of item that should be fired by default. // This differs from get_desired_item; that method can return // an item that is not in inventory, while this one cannot. // If no item can be found, return the reason why. int player_quiver::get_fire_item(string* no_item_reason) const { // Felids have no use for the quiver. if (you.species == SP_FELID) { if (no_item_reason != nullptr) *no_item_reason = "You can't grasp things well enough to throw them."; return -1; } int slot; const item_def* desired_item; get_desired_item(&desired_item, &slot); // If not in inv, try the head of the fire order. if (slot == -1) { vector<int> order; _get_fire_order(order, false, you.weapon(), false); if (!order.empty()) slot = order[0]; } // If we can't find anything, tell caller why. if (slot == -1) { vector<int> full_fire_order; _get_fire_order(full_fire_order, true, you.weapon(), false); if (no_item_reason == nullptr) { // nothing } else if (full_fire_order.empty()) *no_item_reason = "No suitable missiles."; else { const int skipped_item = full_fire_order[0]; if (skipped_item < Options.fire_items_start) { *no_item_reason = make_stringf( "Nothing suitable (fire_items_start = '%c').", index_to_letter(Options.fire_items_start)); } else { *no_item_reason = make_stringf( "Nothing suitable (ignored '=f'-inscribed item on '%c').", index_to_letter(skipped_item)); } } } return slot; } void player_quiver::set_quiver(const item_def &item, ammo_t ammo_type) { m_last_used_of_type[ammo_type] = item; m_last_used_of_type[ammo_type].quantity = 1; m_last_used_type = ammo_type; you.redraw_quiver = true; } void player_quiver::empty_quiver(ammo_t ammo_type) { m_last_used_of_type[ammo_type] = item_def(); m_last_used_of_type[ammo_type].quantity = 0; m_last_used_type = ammo_type; you.redraw_quiver = true; } void quiver_item(int slot) { const item_def item = you.inv[slot]; ASSERT(item.defined()); ammo_t t = AMMO_THROW; const item_def *weapon = you.weapon(); if (weapon && item.launched_by(*weapon)) t = _get_weapon_ammo_type(weapon); you.m_quiver.set_quiver(you.inv[slot], t); #ifdef USE_SOUND parse_sound(CHANGE_QUIVER_SOUND); #endif mprf("Quivering %s for %s.", you.inv[slot].name(DESC_INVENTORY).c_str(), t == AMMO_THROW ? "throwing" : t == AMMO_BLOWGUN ? "blowguns" : t == AMMO_SLING ? "slings" : t == AMMO_BOW ? "bows" : "crossbows"); } void choose_item_for_quiver() { if (you.species == SP_FELID) { mpr("You can't grasp things well enough to throw them."); return; } int slot = prompt_invent_item("Quiver which item? (- for none, * to show all)", MT_INVLIST, OSEL_THROWABLE, OPER_QUIVER, invprompt_flag::hide_known, '-'); if (prompt_failed(slot)) return; if (slot == PROMPT_GOT_SPECIAL) // '-' or empty quiver { ammo_t t = _get_weapon_ammo_type(you.weapon()); you.m_quiver.empty_quiver(t); mprf("Reset %s quiver to default.\nInscribe items with \"=f\" to prevent quivering.", t == AMMO_THROW ? "throwing" : t == AMMO_BLOWGUN ? "blowgun" : t == AMMO_SLING ? "sling" : t == AMMO_BOW ? "bow" : "crossbow"); return; } else { for (int i = EQ_MIN_ARMOUR; i <= EQ_MAX_WORN; i++) { if (you.equip[i] == slot) { mpr("You can't quiver worn items."); return; } } } quiver_item(slot); } // Notification that item was fired with 'f'. void player_quiver::on_item_fired(const item_def& item, bool explicitly_chosen) { if (!explicitly_chosen) { // If the item was not actively chosen, i.e. just automatically // passed into the quiver, don't change any of the quiver settings. you.redraw_quiver = true; return; } // If item matches the launcher, put it in that launcher's last-used item. // Otherwise, it goes into last hand-thrown item. const item_def *weapon = you.weapon(); if (weapon && item.launched_by(*weapon)) { const ammo_t t = _get_weapon_ammo_type(weapon); m_last_used_of_type[t] = item; m_last_used_of_type[t].quantity = 1; // 0 makes it invalid :( m_last_used_type = t; } else { const launch_retval projected = is_launched(&you, you.weapon(), item); // Don't do anything if this item is not really fit for throwing. if (projected == launch_retval::FUMBLED) return; #ifdef DEBUG_QUIVER mprf(MSGCH_DIAGNOSTICS, "item %s is for throwing", item.name(DESC_PLAIN).c_str()); #endif m_last_used_of_type[AMMO_THROW] = item; m_last_used_of_type[AMMO_THROW].quantity = 1; m_last_used_type = AMMO_THROW; } you.redraw_quiver = true; } // Notification that item was fired with 'f' 'i' void player_quiver::on_item_fired_fi(const item_def& item) { // Currently no difference. on_item_fired(item); } // Called when the player might have switched weapons, or might have // picked up something interesting. void player_quiver::on_weapon_changed() { // Only switch m_last_used_type if weapon really changed const item_def* weapon = you.weapon(); if (weapon == nullptr) { if (m_last_weapon.base_type != OBJ_UNASSIGNED) { m_last_weapon.base_type = OBJ_UNASSIGNED; m_last_used_type = AMMO_THROW; } } else { if (!_items_similar(*weapon, m_last_weapon)) { // Weapon type changed. m_last_weapon = *weapon; m_last_used_type = _get_weapon_ammo_type(weapon); } } _maybe_fill_empty_slot(); } void player_quiver::on_inv_quantity_changed(int slot, int amt) { if (m_last_used_of_type[m_last_used_type].base_type == OBJ_UNASSIGNED) { // Empty quiver. Maybe we can fill it now? _maybe_fill_empty_slot(); you.redraw_quiver = true; } else { // We might need to update the quiver... int qv_slot = get_fire_item(); if (qv_slot == slot) you.redraw_quiver = true; } } // If current quiver slot is empty, fill it with something useful. void player_quiver::_maybe_fill_empty_slot() { // Felids have no use for the quiver. if (you.species == SP_FELID) return; const item_def* weapon = you.weapon(); const ammo_t slot = _get_weapon_ammo_type(weapon); #ifdef DEBUG_QUIVER mprf(MSGCH_DIAGNOSTICS, "last quiver item: %s; link %d, wpn: %d", m_last_used_of_type[slot].name(DESC_PLAIN).c_str(), m_last_used_of_type[slot].link, you.equip[EQ_WEAPON]); #endif bool unquiver_weapon = false; if (m_last_used_of_type[slot].defined()) { // If we're wielding an item previously quivered, the quiver may need // to be cleared. Else, any already quivered item is valid and we // don't need to do anything else. if (m_last_used_of_type[slot].link == you.equip[EQ_WEAPON] && you.equip[EQ_WEAPON] != -1) { unquiver_weapon = true; } else return; } #ifdef DEBUG_QUIVER mprf(MSGCH_DIAGNOSTICS, "Recalculating fire order..."); #endif const launch_retval desired_ret = (weapon && is_range_weapon(*weapon)) ? launch_retval::LAUNCHED : launch_retval::THROWN; vector<int> order; _get_fire_order(order, false, weapon, false); if (unquiver_weapon && order.empty()) { // Setting the quantity to zero will force the quiver to be empty, // should nothing else be found. We also set the base type to // OBJ_UNASSIGNED so this is not an invalid object with a real type, // as that would trigger an assertion on saving. m_last_used_of_type[slot].base_type = OBJ_UNASSIGNED; m_last_used_of_type[slot].quantity = 0; } else { for (int ord : order) { if (is_launched(&you, weapon, you.inv[ord]) == desired_ret) { m_last_used_of_type[slot] = you.inv[ord]; m_last_used_of_type[slot].quantity = 1; break; } } } } void player_quiver::get_fire_order(vector<int>& v, bool manual) const { _get_fire_order(v, false, you.weapon(), manual); } // Get a sorted list of items to show in the fire interface. // // If ignore_inscription_etc, ignore =f and Options.fire_items_start. // This is used for generating informational error messages, when the // fire order is empty. // // launcher determines what items match the 'launcher' fire_order type. void player_quiver::_get_fire_order(vector<int>& order, bool ignore_inscription_etc, const item_def* launcher, bool manual) const { const int inv_start = (ignore_inscription_etc ? 0 : Options.fire_items_start); // If in a net, cannot throw anything, and can only launch from blowgun. if (you.attribute[ATTR_HELD]) { if (launcher && launcher->sub_type == WPN_BLOWGUN) { for (int i_inv = inv_start; i_inv < ENDOFPACK; i_inv++) if (you.inv[i_inv].defined() && you.inv[i_inv].launched_by(*launcher)) { order.push_back(i_inv); } } return; } for (int i_inv = inv_start; i_inv < ENDOFPACK; i_inv++) { const item_def& item = you.inv[i_inv]; if (!item.defined()) continue; // Don't do anything if this item is not really fit for throwing. if (is_launched(&you, you.weapon(), item) == launch_retval::FUMBLED) continue; // =f prevents item from being in fire order. if (!ignore_inscription_etc && strstr(item.inscription.c_str(), manual ? "=F" : "=f")) { continue; } for (unsigned int i_flags = 0; i_flags < Options.fire_order.size(); i_flags++) { if (_item_matches(item, (fire_type) Options.fire_order[i_flags], launcher, manual)) { order.push_back((i_flags<<16) | (i_inv & 0xffff)); break; } } } sort(order.begin(), order.end()); for (unsigned int i = 0; i < order.size(); i++) order[i] &= 0xffff; } // ---------------------------------------------------------------------- // Save/load // ---------------------------------------------------------------------- static const short QUIVER_COOKIE = short(0xb015); void player_quiver::save(writer& outf) const { marshallShort(outf, QUIVER_COOKIE); marshallItem(outf, m_last_weapon); marshallInt(outf, m_last_used_type); marshallInt(outf, ARRAYSZ(m_last_used_of_type)); for (unsigned int i = 0; i < ARRAYSZ(m_last_used_of_type); i++) marshallItem(outf, m_last_used_of_type[i]); } void player_quiver::load(reader& inf) { const short cooky = unmarshallShort(inf); ASSERT(cooky == QUIVER_COOKIE); (void)cooky; unmarshallItem(inf, m_last_weapon); m_last_used_type = (ammo_t)unmarshallInt(inf); ASSERT_RANGE(m_last_used_type, AMMO_THROW, NUM_AMMO); const unsigned int count = unmarshallInt(inf); ASSERT(count <= ARRAYSZ(m_last_used_of_type)); for (unsigned int i = 0; i < count; i++) unmarshallItem(inf, m_last_used_of_type[i]); } // ---------------------------------------------------------------------- // Identify helper // ---------------------------------------------------------------------- preserve_quiver_slots::preserve_quiver_slots() { COMPILE_CHECK(ARRAYSZ(m_last_used_of_type) == ARRAYSZ(you.m_quiver.m_last_used_of_type)); for (unsigned int i = 0; i < ARRAYSZ(m_last_used_of_type); i++) { m_last_used_of_type[i] = _get_pack_slot(you.m_quiver.m_last_used_of_type[i]); } } preserve_quiver_slots::~preserve_quiver_slots() { for (unsigned int i = 0; i < ARRAYSZ(m_last_used_of_type); i++) { const int slot = m_last_used_of_type[i]; if (slot != -1) { you.m_quiver.m_last_used_of_type[i] = you.inv[slot]; you.m_quiver.m_last_used_of_type[i].quantity = 1; } } you.redraw_quiver = true; } // ---------------------------------------------------------------------- // Helpers // ---------------------------------------------------------------------- // Helper for _get_fire_order. // Types may actually contain more than one fire_type. static bool _item_matches(const item_def &item, fire_type types, const item_def* launcher, bool manual) { ASSERT(item.defined()); if (types & FIRE_INSCRIBED) if (item.inscription.find(manual ? "+F" : "+f", 0) != string::npos) return true; if (item.base_type != OBJ_MISSILES) return false; if ((types & FIRE_STONE) && item.sub_type == MI_STONE) return true; if ((types & FIRE_JAVELIN) && item.sub_type == MI_JAVELIN) return true; if ((types & FIRE_ROCK) && item.sub_type == MI_LARGE_ROCK) return true; if ((types & FIRE_NET) && item.sub_type == MI_THROWING_NET) return true; if ((types & FIRE_TOMAHAWK) && item.sub_type == MI_TOMAHAWK) return true; if (types & FIRE_LAUNCHER) { if (launcher && item.launched_by(*launcher)) return true; } return false; } // Returns inv slot that contains an item that looks like item, // or -1 if not in inv. static int _get_pack_slot(const item_def& item) { if (!item.defined()) return -1; if (in_inventory(item) && _items_similar(item, you.inv[item.link], false)) return item.link; // First try to find the exact same item. for (int i = 0; i < ENDOFPACK; i++) { const item_def &inv_item = you.inv[i]; if (inv_item.quantity && _items_similar(item, inv_item, false)) return i; } // If that fails, try to find an item sufficiently similar. for (int i = 0; i < ENDOFPACK; i++) { const item_def &inv_item = you.inv[i]; if (inv_item.quantity && _items_similar(item, inv_item, true)) { // =f prevents item from being in fire order. if (strstr(inv_item.inscription.c_str(), "=f")) return -1; return i; } } return -1; } // Returns the type of ammo used by the player's equipped weapon, // or AMMO_THROW if it's not a launcher. static ammo_t _get_weapon_ammo_type(const item_def* weapon) { if (weapon == nullptr) return AMMO_THROW; if (weapon->base_type != OBJ_WEAPONS) return AMMO_THROW; switch (weapon->sub_type) { case WPN_BLOWGUN: return AMMO_BLOWGUN; case WPN_HUNTING_SLING: case WPN_FUSTIBALUS: return AMMO_SLING; case WPN_SHORTBOW: case WPN_LONGBOW: return AMMO_BOW; case WPN_HAND_CROSSBOW: case WPN_ARBALEST: case WPN_TRIPLE_CROSSBOW: return AMMO_CROSSBOW; default: return AMMO_THROW; } } static bool _items_similar(const item_def& a, const item_def& b, bool force) { return items_similar(a, b) && (force || a.slot == b.slot); }
412
0.947995
1
0.947995
game-dev
MEDIA
0.945009
game-dev
0.867904
1
0.867904
Fluorohydride/ygopro-scripts
3,009
c45906428.lua
--ミラクル・フュージョン function c45906428.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_REMOVE+CATEGORY_SPECIAL_SUMMON+CATEGORY_FUSION_SUMMON) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetTarget(c45906428.target) e1:SetOperation(c45906428.activate) c:RegisterEffect(e1) end function c45906428.filter0(c) return c:IsOnField() and c:IsAbleToRemove() end function c45906428.filter1(c,e) return c:IsOnField() and c:IsAbleToRemove() and not c:IsImmuneToEffect(e) end function c45906428.filter2(c,e,tp,m,f,chkf) return c:IsType(TYPE_FUSION) and c:IsSetCard(0x3008) and (not f or f(c)) and c:IsCanBeSpecialSummoned(e,SUMMON_TYPE_FUSION,tp,false,false) and c:CheckFusionMaterial(m,nil,chkf) end function c45906428.filter3(c) return c:IsType(TYPE_MONSTER) and c:IsCanBeFusionMaterial() and c:IsAbleToRemove() end function c45906428.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then local chkf=tp local mg1=Duel.GetFusionMaterial(tp):Filter(c45906428.filter0,nil) local mg2=Duel.GetMatchingGroup(c45906428.filter3,tp,LOCATION_GRAVE,0,nil) mg1:Merge(mg2) local res=Duel.IsExistingMatchingCard(c45906428.filter2,tp,LOCATION_EXTRA,0,1,nil,e,tp,mg1,nil,chkf) if not res then local ce=Duel.GetChainMaterial(tp) if ce~=nil then local fgroup=ce:GetTarget() local mg3=fgroup(ce,e,tp) local mf=ce:GetValue() res=Duel.IsExistingMatchingCard(c45906428.filter2,tp,LOCATION_EXTRA,0,1,nil,e,tp,mg3,mf,chkf) end end return res end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_EXTRA) Duel.SetOperationInfo(0,CATEGORY_REMOVE,nil,1,tp,LOCATION_ONFIELD+LOCATION_GRAVE) end function c45906428.activate(e,tp,eg,ep,ev,re,r,rp) local chkf=tp local mg1=Duel.GetFusionMaterial(tp):Filter(c45906428.filter1,nil,e) local mg2=Duel.GetMatchingGroup(c45906428.filter3,tp,LOCATION_GRAVE,0,nil) mg1:Merge(mg2) local sg1=Duel.GetMatchingGroup(c45906428.filter2,tp,LOCATION_EXTRA,0,nil,e,tp,mg1,nil,chkf) local mg3=nil local sg2=nil local ce=Duel.GetChainMaterial(tp) if ce~=nil then local fgroup=ce:GetTarget() mg3=fgroup(ce,e,tp) local mf=ce:GetValue() sg2=Duel.GetMatchingGroup(c45906428.filter2,tp,LOCATION_EXTRA,0,nil,e,tp,mg3,mf,chkf) end if sg1:GetCount()>0 or (sg2~=nil and sg2:GetCount()>0) then local sg=sg1:Clone() if sg2 then sg:Merge(sg2) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local tg=sg:Select(tp,1,1,nil) local tc=tg:GetFirst() if sg1:IsContains(tc) and (sg2==nil or not sg2:IsContains(tc) or not Duel.SelectYesNo(tp,ce:GetDescription())) then local mat1=Duel.SelectFusionMaterial(tp,tc,mg1,nil,chkf) tc:SetMaterial(mat1) Duel.Remove(mat1,POS_FACEUP,REASON_EFFECT+REASON_MATERIAL+REASON_FUSION) Duel.BreakEffect() Duel.SpecialSummon(tc,SUMMON_TYPE_FUSION,tp,tp,false,false,POS_FACEUP) else local mat2=Duel.SelectFusionMaterial(tp,tc,mg3,nil,chkf) local fop=ce:GetOperation() fop(ce,e,tp,tc,mat2) end tc:CompleteProcedure() end end
412
0.939443
1
0.939443
game-dev
MEDIA
0.843627
game-dev
0.965496
1
0.965496
magefree/mage
1,372
Mage.Sets/src/mage/cards/i/IridescentVinelasher.java
package mage.cards.i; import mage.MageInt; import mage.abilities.Ability; import mage.abilities.common.LandfallAbility; import mage.abilities.effects.common.DamageTargetEffect; import mage.abilities.keyword.OffspringAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.SubType; import mage.target.common.TargetOpponent; import java.util.UUID; /** * @author TheElk801 */ public final class IridescentVinelasher extends CardImpl { public IridescentVinelasher(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{B}"); this.subtype.add(SubType.LIZARD); this.subtype.add(SubType.ASSASSIN); this.power = new MageInt(1); this.toughness = new MageInt(2); // Offspring {2} this.addAbility(new OffspringAbility("{2}")); // Landfall -- Whenever a land you control enters, this creature deals 1 damage to target opponent. Ability ability = new LandfallAbility(new DamageTargetEffect(1)); ability.addTarget(new TargetOpponent()); this.addAbility(ability); } private IridescentVinelasher(final IridescentVinelasher card) { super(card); } @Override public IridescentVinelasher copy() { return new IridescentVinelasher(this); } }
412
0.891549
1
0.891549
game-dev
MEDIA
0.969815
game-dev
0.988422
1
0.988422
Eaglercraft-Archive/EaglercraftX-1.8-workspace
10,040
src/main/java/net/optifine/Config.java
package net.optifine; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; import net.lax1dude.eaglercraft.v1_8.log4j.Logger; import net.minecraft.client.Minecraft; import net.minecraft.client.resources.DefaultResourcePack; import net.minecraft.client.resources.IResourcePack; import net.minecraft.client.resources.ResourcePackRepository; import net.minecraft.client.settings.GameSettings; import net.minecraft.util.BlockPos; import net.minecraft.util.ResourceLocation; import net.optifine.util.TextureUtils; public class Config { private static final Logger logger = LogManager.getLogger("OptiFine"); private static Minecraft mc; private static GameSettings gameSettings; public static void setGameObj(Minecraft mc) { Config.mc = mc; Config.gameSettings = mc.gameSettings; } public static String[] tokenize(String p_tokenize_0_, String p_tokenize_1_) { StringTokenizer stringtokenizer = new StringTokenizer(p_tokenize_0_, p_tokenize_1_); List list = new ArrayList(); while (stringtokenizer.hasMoreTokens()) { String s = stringtokenizer.nextToken(); list.add(s); } String[] astring = (String[]) list.toArray(new String[list.size()]); return astring; } public static boolean isCustomSky() { return gameSettings.customSkyOF; } public static boolean isBetterGrass() { return gameSettings.betterGrassOF != 0; } public static boolean isBetterGrassFancy() { return gameSettings.betterGrassOF == 2; } public static boolean isBetterSnow() { return gameSettings.betterGrassOF != 0; } public static boolean isConnectedTextures() { return gameSettings.connectedTexturesOF != 0; } public static boolean isConnectedTexturesFancy() { return gameSettings.connectedTexturesOF == 2; } public static boolean isTreesFancy() { return gameSettings.fancyGraphics || gameSettings.shaders; } public static boolean isTreesSmart() { return (gameSettings.fancyGraphics || gameSettings.shaders) && gameSettings.smartLeavesOF; } public static boolean isCullFacesLeaves() { return !gameSettings.fancyGraphics || gameSettings.shaders; } public static boolean isCustomItems() { return gameSettings.customItemsOF; } public static void dbg(String string) { logger.debug(string); } public static void warn(String string) { logger.warn(string); } public static void error(String string) { logger.error(string); } public static int limit(int p_limit_0_, int p_limit_1_, int p_limit_2_) { return p_limit_0_ < p_limit_1_ ? p_limit_1_ : (p_limit_0_ > p_limit_2_ ? p_limit_2_ : p_limit_0_); } public static float limit(float p_limit_0_, float p_limit_1_, float p_limit_2_) { return p_limit_0_ < p_limit_1_ ? p_limit_1_ : (p_limit_0_ > p_limit_2_ ? p_limit_2_ : p_limit_0_); } public static double limit(double p_limit_0_, double p_limit_2_, double p_limit_4_) { return p_limit_0_ < p_limit_2_ ? p_limit_2_ : (p_limit_0_ > p_limit_4_ ? p_limit_4_ : p_limit_0_); } public static int parseInt(String p_parseInt_0_, int p_parseInt_1_) { try { if (p_parseInt_0_ == null) { return p_parseInt_1_; } else { p_parseInt_0_ = p_parseInt_0_.trim(); return Integer.parseInt(p_parseInt_0_); } } catch (NumberFormatException var3) { return p_parseInt_1_; } } public static float parseFloat(String p_parseFloat_0_, float p_parseFloat_1_) { try { if (p_parseFloat_0_ == null) { return p_parseFloat_1_; } else { p_parseFloat_0_ = p_parseFloat_0_.trim(); return Float.parseFloat(p_parseFloat_0_); } } catch (NumberFormatException var3) { return p_parseFloat_1_; } } public static boolean parseBoolean(String p_parseBoolean_0_, boolean p_parseBoolean_1_) { try { if (p_parseBoolean_0_ == null) { return p_parseBoolean_1_; } else { p_parseBoolean_0_ = p_parseBoolean_0_.trim(); return Boolean.parseBoolean(p_parseBoolean_0_); } } catch (NumberFormatException var3) { return p_parseBoolean_1_; } } public static int[] addIntToArray(int[] p_addIntToArray_0_, int p_addIntToArray_1_) { if (p_addIntToArray_0_ != null) { int[] ret = new int[p_addIntToArray_0_.length + 1]; System.arraycopy(p_addIntToArray_0_, 0, ret, 0, p_addIntToArray_0_.length); ret[p_addIntToArray_0_.length] = p_addIntToArray_1_; return ret; } else { throw new NullPointerException("The given array is NULL"); } } public static int[] addIntsToArray(int[] p_addIntsToArray_0_, int[] p_addIntsToArray_1_) { if (p_addIntsToArray_0_ != null && p_addIntsToArray_1_ != null) { int i = p_addIntsToArray_0_.length; int j = i + p_addIntsToArray_1_.length; int[] aint = new int[j]; System.arraycopy(p_addIntsToArray_0_, 0, aint, 0, i); for (int k = 0; k < p_addIntsToArray_1_.length; ++k) { aint[k + i] = p_addIntsToArray_1_[k]; } return aint; } else { throw new NullPointerException("The given array is NULL"); } } public static String arrayToString(Object[] p_arrayToString_0_) { return arrayToString(p_arrayToString_0_, ", "); } public static String arrayToString(Object[] p_arrayToString_0_, String p_arrayToString_1_) { if (p_arrayToString_0_ == null) { return ""; } else { StringBuffer stringbuffer = new StringBuffer(p_arrayToString_0_.length * 5); for (int i = 0; i < p_arrayToString_0_.length; ++i) { Object object = p_arrayToString_0_[i]; if (i > 0) { stringbuffer.append(p_arrayToString_1_); } stringbuffer.append(String.valueOf(object)); } return stringbuffer.toString(); } } public static String arrayToString(int[] p_arrayToString_0_) { return arrayToString(p_arrayToString_0_, ", "); } public static String arrayToString(int[] p_arrayToString_0_, String p_arrayToString_1_) { if (p_arrayToString_0_ == null) { return ""; } else { StringBuffer stringbuffer = new StringBuffer(p_arrayToString_0_.length * 5); for (int i = 0; i < p_arrayToString_0_.length; ++i) { int j = p_arrayToString_0_[i]; if (i > 0) { stringbuffer.append(p_arrayToString_1_); } stringbuffer.append(String.valueOf(j)); } return stringbuffer.toString(); } } public static int[] toPrimitive(Integer[] p_toPrimitive_0_) { if (p_toPrimitive_0_ == null) { return null; } else if (p_toPrimitive_0_.length == 0) { return new int[0]; } else { int[] aint = new int[p_toPrimitive_0_.length]; for (int i = 0; i < aint.length; ++i) { aint[i] = p_toPrimitive_0_[i].intValue(); } return aint; } } public static boolean isSameOne(Object p_isSameOne_0_, Object[] p_isSameOne_1_) { if (p_isSameOne_1_ == null) { return false; } else { for (int i = 0; i < p_isSameOne_1_.length; ++i) { Object object = p_isSameOne_1_[i]; if (p_isSameOne_0_ == object) { return true; } } return false; } } public static boolean equals(Object p_equals_0_, Object p_equals_1_) { return p_equals_0_ == p_equals_1_ ? true : (p_equals_0_ == null ? false : p_equals_0_.equals(p_equals_1_)); } public static boolean isFromDefaultResourcePack(ResourceLocation p_isFromDefaultResourcePack_0_) { IResourcePack iresourcepack = getDefiningResourcePack(p_isFromDefaultResourcePack_0_); return iresourcepack == mc.getDefaultResourcePack(); } public static IResourcePack getDefiningResourcePack(ResourceLocation p_getDefiningResourcePack_0_) { ResourcePackRepository resourcepackrepository = mc.getResourcePackRepository(); IResourcePack iresourcepack = resourcepackrepository.getResourcePackInstance(); if (iresourcepack != null && iresourcepack.resourceExists(p_getDefiningResourcePack_0_)) { return iresourcepack; } else { List<ResourcePackRepository.Entry> list = resourcepackrepository.getRepositoryEntries(); for (int i = list.size() - 1; i >= 0; --i) { ResourcePackRepository.Entry resourcepackrepository$entry = (ResourcePackRepository.Entry) list.get(i); IResourcePack iresourcepack1 = resourcepackrepository$entry.getResourcePack(); if (iresourcepack1.resourceExists(p_getDefiningResourcePack_0_)) { return iresourcepack1; } } DefaultResourcePack res = mc.getDefaultResourcePack(); if (res.resourceExists(p_getDefiningResourcePack_0_)) { return res; } else { return null; } } } public static boolean hasResource(ResourceLocation p_hasResource_0_) { if (p_hasResource_0_ == null) { return false; } else { IResourcePack iresourcepack = getDefiningResourcePack(p_hasResource_0_); return iresourcepack != null; } } public static IResourcePack[] getResourcePacks() { ResourcePackRepository resourcepackrepository = mc.getResourcePackRepository(); List list = resourcepackrepository.getRepositoryEntries(); List list1 = new ArrayList(); for (Object resourcepackrepository$entry0 : list) { ResourcePackRepository.Entry resourcepackrepository$entry = (ResourcePackRepository.Entry) resourcepackrepository$entry0; list1.add(resourcepackrepository$entry.getResourcePack()); } if (resourcepackrepository.getResourcePackInstance() != null) { list1.add(resourcepackrepository.getResourcePackInstance()); } IResourcePack[] airesourcepack = (IResourcePack[]) ((IResourcePack[]) list1 .toArray(new IResourcePack[list1.size()])); return airesourcepack; } public static int intHash(int p_intHash_0_) { p_intHash_0_ = p_intHash_0_ ^ 61 ^ p_intHash_0_ >> 16; p_intHash_0_ = p_intHash_0_ + (p_intHash_0_ << 3); p_intHash_0_ = p_intHash_0_ ^ p_intHash_0_ >> 4; p_intHash_0_ = p_intHash_0_ * 668265261; p_intHash_0_ = p_intHash_0_ ^ p_intHash_0_ >> 15; return p_intHash_0_; } public static int getRandom(BlockPos p_getRandom_0_, int p_getRandom_1_) { int i = intHash(p_getRandom_1_ + 37); i = intHash(i + p_getRandom_0_.getX()); i = intHash(i + p_getRandom_0_.getZ()); i = intHash(i + p_getRandom_0_.getY()); return i; } public static void frameInitHook() { TextureUtils.registerResourceListener(); } }
412
0.792851
1
0.792851
game-dev
MEDIA
0.917282
game-dev
0.898835
1
0.898835
jealouscloud/linerider-advanced
10,921
src/Game/Timeline.cs
// Author: // Noah Ablaseau <nablaseau@hotmail.com> // // Copyright (c) 2017 // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. using linerider.Rendering; using OpenTK; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Drawing; using System.Threading; using linerider.Game; using linerider.Utils; using System.Diagnostics; namespace linerider.Game { public partial class Timeline { struct frameinfo { public Rider Rider; public int TriggerLineID; public int TriggerHitFrame; public float Zoom; } private HitTestManager _hittest = new HitTestManager(); private ResourceSync _framesync = new ResourceSync(); private AutoArray<frameinfo> _frames = new AutoArray<frameinfo>(); private Track _track; public event EventHandler<int> FrameInvalidated; public Timeline(Track track) { _track = track; var start = _track.GetStart(); _savedcells.BaseGrid = _track.Grid; Restart(track.GetStart(), Constants.DefaultZoom); } /// <summary> /// Returns true if the line id is hit by the current "working" frame /// </summary> public bool IsLineHit(int id) { using (_framesync.AcquireWrite()) { return _hittest.IsHit(id); } } /// <summary> /// Returns true if the line id is hit by the specifed frame /// </summary> public bool IsLineHit(int id, int frame) { using (_framesync.AcquireWrite()) { UnsafeEnsureFrameValid(frame); return _hittest.IsHitBy(id, frame); } } /// <summary> /// Sets the specified frame to be the "working" frame and returns the /// list of lines that may need to be updated by the renderer. /// </summary> /// <returns>A collection of line IDs to be redrawn</returns> public HashSet<int> RequestFrameForRender(int frameid) { using (_framesync.AcquireWrite()) { UnsafeEnsureFrameValid(frameid); return _hittest.GetChangesForFrame(frameid); } } /// <summary> /// Clears the timeline of pre-calculated frames and starts at the /// new provided state. /// </summary> /// <param name="state">The start position, frame 0</param> public void Restart(Rider state, float zoom) { using (_framesync.AcquireWrite()) { _hittest.Reset(); _frames.Clear(); _frames.Add(new frameinfo() { Rider = state, TriggerHitFrame = -1, TriggerLineID = -1, Zoom = zoom }); using (changesync.AcquireWrite()) { _first_invalid_frame = _frames.Count; } } } /// <summary> /// Extracts the rider and death details of the specified frame. /// </summary> public RiderFrame ExtractFrame(int frame, int iteration = 6) { Rider rider; List<int> diagnosis = null; using (_track.Grid.Sync.AcquireRead()) { diagnosis = DiagnoseFrame(frame, iteration); rider = GetFrame(frame, iteration); } return new RiderFrame(frame, rider, diagnosis, iteration); } /// <summary> /// Gets an up to date diagnosis state for the frame, recomputing if /// necessary. /// </summary> public List<int> DiagnoseFrame(int frame, int iteration = 6) { bool isiteration = iteration != 6 && frame > 0; frame = isiteration ? frame - 1 : frame; var next = GetFrame(frame + 1); var rider = GetFrame(frame); if (next.Crashed == rider.Crashed) return new List<int>(); return rider.Diagnose( _track.Grid, _track.Bones, Math.Min(6, iteration + 1)); } /// <summary> /// Gets an up to date rider state for the frame, recomputing if /// necessary. /// </summary> public Rider GetFrame(int frame, int iteration = 6) { bool isiteration = iteration != 6 && frame > 0; if (iteration != 6 && frame > 0) { int trig = 0; return GetFrame(frame - 1).Simulate( _track.Grid, _track.Bones, ref trig, null, iteration, frameid: frame); } return GetFrame(frame); } /// <summary> /// Gets an up to date rider state for the frame, recomputing if /// necessary /// </summary> public Rider GetFrame(int frame) { using (_framesync.AcquireWrite()) { UnsafeEnsureFrameValid(frame); return _frames[frame].Rider; } } /// <summary> /// Gets an up to date rider state for the frame, recomputing if /// necessary /// </summary> public float GetFrameZoom(int frame) { using (_framesync.AcquireWrite()) { UnsafeEnsureFrameValid(frame); return _frames[frame].Zoom; } } /// <summary> /// Gets an up to date array of rider states, recomputing if necessary /// </summary> public Rider[] GetFrames(int framestart, int count) { using (_framesync.AcquireWrite()) { Rider[] ret = new Rider[count]; for (int i = count - 1; i >= 0; i--) { ret[i] = GetFrame(framestart + i); } return ret; } } public void TriggerChanged(GameLine line) { int framehit; using (_framesync.AcquireWrite()) { framehit = _hittest.GetHitFrame(line.ID); } if (framehit != -1) { using (changesync.AcquireWrite()) { _first_invalid_frame = Math.Min(framehit, _first_invalid_frame); } } } private void UnsafeEnsureFrameValid(int frame) { int start; int count; int invalid; using (changesync.AcquireRead()) { invalid = _first_invalid_frame; start = Math.Min(_frames.Count, invalid); count = frame - (start - 1); _first_invalid_frame = Math.Max(invalid, frame + 1); } if (count > 0) { ThreadUnsafeRunFrames(start, count); } } /// <summary> /// The meat of the recompute engine, updating hit test and the /// cached frames. /// </summary> private void ThreadUnsafeRunFrames(int start, int count) { var steps = new frameinfo[count]; var collisionlist = new List<LinkedList<int>>(count); frameinfo current = _frames[start - 1]; int framecount = _frames.Count; var bones = _track.Bones; using (changesync.AcquireWrite()) { // we use the savedcells buffer exactly so runframes can // be completely consistent with the track state at the // time of running // we could also get a lock on the track grid, but that would // block user input on the track until we finish running. _savedcells.Clear(); } using (var sync = changesync.AcquireRead()) { _hittest.MarkFirstInvalid(start); for (int i = 0; i < count; i++) { int currentframe = start + i; var collisions = new LinkedList<int>(); var oldtrigid = current.TriggerLineID; var zoom = current.Rider = current.Rider.Simulate( _savedcells, bones, ref current.TriggerLineID, collisions, frameid: currentframe); if (current.TriggerLineID != oldtrigid) { current.TriggerHitFrame = currentframe; } if (current.TriggerLineID != -1) { var std = (StandardLine)_track.LineLookup[current.TriggerLineID]; Debug.Assert(std.Trigger != null, "Trigger line proc on line with no trigger"); var delta = currentframe - current.TriggerHitFrame; if (!std.Trigger.Activate(delta, ref current.Zoom)) { current.TriggerLineID = -1; current.TriggerHitFrame = -1; } } steps[i] = current; collisionlist.Add(collisions); // 10 seconds of frames, // couldnt hurt to check? if ((i + 1) % 400 == 0) { sync.ReleaseWaiting(); } } _hittest.AddFrames(collisionlist); } if (start + count > framecount) { _frames.EnsureCapacity(start + count); _frames.UnsafeSetCount(start + count); } for (int i = 0; i < steps.Length; i++) { _frames.unsafe_array[start + i] = steps[i]; } FrameInvalidated?.Invoke(this, start); } } }
412
0.8289
1
0.8289
game-dev
MEDIA
0.449091
game-dev
0.977497
1
0.977497
Mojang/minecraft-creator-tools
5,203
app/src/app/DeploymentStorageMinecraft.ts
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. import Carto, { CartoMinecraftErrorStatus, CartoMinecraftState } from "./Carto"; import IMinecraft, { IMinecraftMessage, PrepareAndStartResultType } from "./IMinecraft"; import AppServiceProxy from "../core/AppServiceProxy"; import { EventDispatcher } from "ste-events"; import Utilities from "../core/Utilities"; import Project from "./Project"; import MinecraftPush from "./MinecraftPush"; import GameStateManager from "../minecraft/GameStateManager"; import Log from "../core/Log"; import IFolder from "../storage/IFolder"; import { MinecraftGameConnectionMode } from "./ICartoData"; import ProjectExporter from "./ProjectExporter"; export default class DeploymentStorageMinecraft implements IMinecraft { private _carto: Carto; state: CartoMinecraftState; private _onStateChanged = new EventDispatcher<IMinecraft, CartoMinecraftState>(); private _onRefreshed = new EventDispatcher<IMinecraft, CartoMinecraftState>(); private _project: Project | undefined; private _gameStateManager: GameStateManager; errorStatus?: CartoMinecraftErrorStatus; errorMessage?: string; worldFolder: IFolder | undefined; projectFolder: IFolder | undefined; private _onWorldFolderReady = new EventDispatcher<IMinecraft, IFolder>(); private _onProjectFolderReady = new EventDispatcher<IMinecraft, IFolder>(); private _onMessage = new EventDispatcher<IMinecraft, IMinecraftMessage>(); public get onWorldFolderReady() { return this._onWorldFolderReady.asEvent(); } public get onProjectFolderReady() { return this._onProjectFolderReady.asEvent(); } public get onMessage() { return this._onMessage.asEvent(); } get canDeployFiles() { return true; } public get onRefreshed() { return this._onRefreshed.asEvent(); } public get onStateChanged() { return this._onStateChanged.asEvent(); } constructor(carto: Carto) { this._carto = carto; this._gameStateManager = new GameStateManager(this._carto); this.state = CartoMinecraftState.none; } async updateStatus() { return this.state; } get activeProject() { return this._project; } set activeProject(newProject: Project | undefined) { this._project = newProject; } public get gameStateManager() { return this._gameStateManager; } public notifyStateChanged(newVal: CartoMinecraftState) { this.state = newVal; this._onStateChanged.dispatch(this, newVal); } async initialize() { await this.start(); } async prepare(force?: boolean): Promise<void> { return; } async runCommand(command: string): Promise<string | undefined> { return undefined; } processExternalMessage(command: string, data: string) {} async pushWorld() { if (!this._carto || this._carto.deploymentStorage === null || !this._project) { return; } let name = this._project.name + "_mct"; const worldsFolder = await ProjectExporter.ensureMinecraftWorldsFolder(this._carto); if (!worldsFolder) { Log.debug("Could not find a Minecraft world."); return; } const worldFolder = worldsFolder.ensureFolder(name); await worldFolder.ensureExists(); // Log.debugAlert("Exporting folder to '" + worldFolder.storageRelativePath + "'"); await ProjectExporter.syncFlatPackRefWorldTo(this._carto, this._project, worldFolder, name); name = Utilities.getSimpleString(this._project.name) + "_mct"; await worldFolder.saveAll(); return name; } async syncWithDeployment() { if ( this._carto.deploymentStorage == null || this._carto.deployBehaviorPacksFolder == null || this._carto.minecraftGameMode === MinecraftGameConnectionMode.remoteMinecraft ) { throw new Error("This instance doesn't support deployment"); } if (!this._project) { return; } let isAvailable = this._carto.deploymentStorage.available; if (isAvailable === undefined) { isAvailable = await this._carto.deploymentStorage.getAvailable(); } if (!isAvailable) { return; } const deployFolderExists = await this._carto.deployBehaviorPacksFolder.exists(); if (deployFolderExists) { await ProjectExporter.deployProject(this._carto, this._project, this._carto.deploymentStorage.rootFolder); } } canPrepare() { return true; } async prepareAndStart(push: MinecraftPush) { let worldName = undefined; if (push.project) { this._project = push.project; await this.syncWithDeployment(); } if (push.worldType) { worldName = await this.pushWorld(); } await this.start(); return { type: PrepareAndStartResultType.started, worldName: worldName, }; } async stop() {} async start() { if (!AppServiceProxy.hasAppService && Utilities.isDebug) { this.notifyStateChanged(CartoMinecraftState.stopped); } else if ( this.state === CartoMinecraftState.none || this.state === CartoMinecraftState.error || this.state === CartoMinecraftState.disconnected ) { this.notifyStateChanged(CartoMinecraftState.initializing); } } }
412
0.966012
1
0.966012
game-dev
MEDIA
0.838465
game-dev
0.954787
1
0.954787
udacity/ud406
1,983
2.6.05-Solution-HitDetection/core/src/com/udacity/gamedev/gigagal/entities/Bullet.java
package com.udacity.gamedev.gigagal.entities; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.math.Vector2; import com.udacity.gamedev.gigagal.Level; import com.udacity.gamedev.gigagal.util.Assets; import com.udacity.gamedev.gigagal.util.Constants; import com.udacity.gamedev.gigagal.util.Enums.Direction; import com.udacity.gamedev.gigagal.util.Utils; public class Bullet { private final Direction direction; private final Level level; public boolean active; private Vector2 position; public Bullet(Level level, Vector2 position, Direction direction) { this.level = level; this.position = position; this.direction = direction; active = true; } public void update(float delta) { switch (direction) { case LEFT: position.x -= delta * Constants.BULLET_MOVE_SPEED; break; case RIGHT: position.x += delta * Constants.BULLET_MOVE_SPEED; break; } for (Enemy enemy : level.getEnemies()) { // TODO: Check if the bullet is within the enemy hit detection radius if (position.dst(enemy.position) < Constants.ENEMY_SHOT_RADIUS) { // TODO: If so, set active = false active = false; // TODO: And decrement enemy health enemy.health -= 1; } } final float worldWidth = level.getViewport().getWorldWidth(); final float cameraX = level.getViewport().getCamera().position.x; if (position.x < cameraX - worldWidth / 2 || position.x > cameraX + worldWidth / 2) { active = false; } } public void render(SpriteBatch batch) { TextureRegion region = Assets.instance.bulletAssets.bullet; Utils.drawTextureRegion(batch, region, position, Constants.BULLET_CENTER); } }
412
0.772465
1
0.772465
game-dev
MEDIA
0.922894
game-dev
0.955178
1
0.955178
ben/foundry-ironsworn
2,638
src/module/datasworn2/import/foe-description.ts
/* { "_id": "npc:starforged/sample_npcs/chiton", "type": "npc", "name": "Chiton", "rank": 2, "nature": "Monster", "summary": "Insectoid horde", "features": [ "Arachnid monsters with blade-like limbs", "Plated exoskeleton", "Dripping mucus", "Ripping, tearing maw" ], "drives": [ "Build and expand the nest", "Feed and protect the queen", "Snuff out intelligent life" ], "tactics": [ "Attack with lightning reflexes", "Impale with bladed limbs", "Drag victims back to the nest" ], "variants": { "chiton_drone_pack": { "_id": "npc.variant:starforged/sample_npcs/chiton.chiton_drone_pack", "name": "Chiton drone pack", "rank": 3, "nature": "Monster", "description": "Chiton drones rarely operate independently..." }, "chiton_queen": { "_id": "npc.variant:starforged/sample_npcs/chiton.chiton_queen", "name": "Chiton queen", "rank": 4, "nature": "Monster", "description": "The chiton queen is a massive creature with ..." } }, "description": "The chiton are not native to any single planet...", "quest_starter": "At a remote facility, researchers are studying ...", "_source": { "title": "Ironsworn: Starforged Rulebook", "authors": [ { "name": "Shawn Tomkin" } ], "date": "2022-05-06", "license": "https://creativecommons.org/licenses/by/4.0", "page": 259, "url": "https://ironswornrpg.com" } } */ import type { Npc } from '@datasworn/core/dist/Datasworn' import { renderLinksInStr, renderText } from './rendering' export function renderNpcDescription(npc: Npc): string { const tickList = (name: string, list: string[]) => ` <div class="flexcol box" style="justify-content: flex-start;"> <h4 class="nogrow" style="margin: 0.5em;">${name}</h4> ${list.map((item) => `<p class="nogrow">${item}</p>`).join('\n')} </div> `.trim() const questStarter = renderText(npc.quest_starter ?? '') const variants = Object.values(npc.variants) const variantLinks = variants.map((variant) => renderLinksInStr(`[${variant.name}](datasworn:${variant._id})`) ) const variantList = variants.length > 0 ? ` <h2>Variants</h2> <ul> ${variantLinks.map((link) => `<li>${link}</li>`).join('\n')} </ul> `.trim() : '' return ` <div class="boxgroup flexrow boxrow" style="margin-bottom: 0.5rem;"> ${tickList('Features', npc.features)} ${tickList('Drives', npc.drives)} ${tickList('Tactics', npc.tactics)} </div> ${renderText(npc.description)} <blockquote>Quest Starter: ${questStarter}</blockquote> ${variantList} `.trim() }
412
0.832624
1
0.832624
game-dev
MEDIA
0.980283
game-dev
0.796468
1
0.796468
ScutGame/Scut-samples
5,173
Koudai/Server/release/Script/CsScript/Action/Action1262.cs
/**************************************************************************** Copyright (c) 2013-2015 scutgame.com http://www.scutgame.com 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.Collections.Generic; using System.Data; using ZyGames.Framework.Collection; using ZyGames.Framework.Common; using ZyGames.Framework.Cache.Generic; using ZyGames.Framework.Game.Service; using ZyGames.Tianjiexing.BLL.Base; using ZyGames.Tianjiexing.Lang; using ZyGames.Tianjiexing.Model; using ZyGames.Tianjiexing.Model.Config; using ZyGames.Framework.Cache; using ZyGames.Tianjiexing.Model.Enum; namespace ZyGames.Tianjiexing.BLL.Action { /// <summary> /// 1261_可合成附魔符列表接口 /// </summary> public class Action1262 : BaseAction { private int pageIndex; private int pageSize; private string userEnchantID; private int PageCount; private string abilityNum; private UserEnchantInfo[] enchantArray = new UserEnchantInfo[0]; public Action1262(ZyGames.Framework.Game.Contract.HttpGet httpGet) : base(ActionIDDefine.Cst_Action1262, httpGet) { } public override void BuildPacket() { PushIntoStack(PageCount); PushIntoStack(enchantArray.Length); foreach (var enchant in enchantArray) { EnchantInfo enchantInfo = new ShareCacheStruct<EnchantInfo>().FindKey(enchant.EnchantID); abilityNum = EnchantHelper.EnchantAbilityStr(enchant.EnchantID, enchant.EnchantLv); DataStruct dsItem = new DataStruct(); dsItem.PushIntoStack(enchant.UserEnchantID.ToNotNullString()); dsItem.PushIntoStack(enchantInfo == null ? string.Empty : enchantInfo.EnchantName.ToNotNullString()); dsItem.PushIntoStack(enchantInfo == null ? string.Empty : enchantInfo.HeadID.ToNotNullString()); dsItem.PushIntoStack((short)enchant.EnchantLv); dsItem.PushIntoStack(enchantInfo == null ? (short)0 : (short)enchantInfo.ColorType); dsItem.PushIntoStack(enchantInfo == null ? (short)0 : (short)enchantInfo.AbilityType); dsItem.PushIntoStack(abilityNum.ToNotNullString()); PushIntoStack(dsItem); } } public override bool GetUrlElement() { if (httpGet.GetInt("PageIndex", ref pageIndex) && httpGet.GetInt("PageSize", ref pageSize) && httpGet.GetString("UserEnchantID", ref userEnchantID)) { return true; } return false; } public override bool TakeAction() { var package = UserEnchant.Get(ContextUser.UserID); if (package == null) return false; var userEnchantInfo = package.EnchantPackage.Find(m => m.UserEnchantID == userEnchantID); if (userEnchantInfo == null) { ErrorCode = LanguageManager.GetLang().ErrorCode; ErrorInfo = LanguageManager.GetLang().St1256_EnchantNotEnough; return false; } List<UserEnchantInfo> enchantList = new List<UserEnchantInfo>(); var enchantInfoArray = package.EnchantPackage.FindAll(m => string.IsNullOrEmpty(m.UserItemID) && m.EnchantLv <= userEnchantInfo.EnchantLv); if (enchantInfoArray.Count == 0) { ErrorCode = LanguageManager.GetLang().ErrorCode; ErrorInfo = LanguageManager.GetLang().St1262_EnchantSynthesisNotEnough; return false; } foreach (var info in enchantInfoArray) { if (info.UserEnchantID == userEnchantID || info.CurrExprience > userEnchantInfo.CurrExprience) { continue; } enchantList.Add(info); } enchantArray = enchantList.GetPaging(pageIndex, pageSize, out PageCount).ToArray(); return true; } } }
412
0.941769
1
0.941769
game-dev
MEDIA
0.936775
game-dev
0.960355
1
0.960355
Samsung/GearVRf
4,887
GVRf/Extensions/gvrf-physics/src/main/jni/engine/bullet/bullet_conetwistconstraint.cpp
/* 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. */ // // Created by c.bozzetto on 06/06/2017. // #include "bullet_conetwistconstraint.h" #include "bullet_rigidbody.h" #include <BulletDynamics/ConstraintSolver/btConeTwistConstraint.h> #include <LinearMath/btScalar.h> const char tag[] = "BulletConeTwistConstrN"; namespace gvr { BulletConeTwistConstraint::BulletConeTwistConstraint(PhysicsRigidBody *rigidBodyB, PhysicsVec3 pivot, PhysicsMat3x3 const &bodyRotation, PhysicsMat3x3 const &coneRotation) { mConeTwistConstraint = 0; mRigidBodyB = reinterpret_cast<BulletRigidBody*>(rigidBodyB); mBreakingImpulse = SIMD_INFINITY; mPivot = pivot; mBodyRotation = bodyRotation; mConeRotation = coneRotation; mSwingLimit = SIMD_PI * 0.25f; mTwistLimit = SIMD_PI; } BulletConeTwistConstraint::BulletConeTwistConstraint(btConeTwistConstraint *constraint) { mConeTwistConstraint = constraint; mRigidBodyB = static_cast<BulletRigidBody*>(constraint->getRigidBodyB().getUserPointer()); constraint->setUserConstraintPtr(this); } BulletConeTwistConstraint::~BulletConeTwistConstraint() { if (0 != mConeTwistConstraint) { delete mConeTwistConstraint; } } void BulletConeTwistConstraint::setSwingLimit(float limit) { if (0 != mConeTwistConstraint) { mConeTwistConstraint->setLimit(4, limit); mConeTwistConstraint->setLimit(5, limit); } else { mSwingLimit = limit; } } float BulletConeTwistConstraint::getSwingLimit() const { if (0 != mConeTwistConstraint) { return mConeTwistConstraint->getLimit(4); } else { return mSwingLimit; } } void BulletConeTwistConstraint::setTwistLimit(float limit) { if (0 != mConeTwistConstraint) { mConeTwistConstraint->setLimit(3, limit); } else { mTwistLimit = limit; } } float BulletConeTwistConstraint::getTwistLimit() const { if (0 != mConeTwistConstraint) { return mConeTwistConstraint->getLimit(3); } else { return mTwistLimit; } } void BulletConeTwistConstraint::setBreakingImpulse(float impulse) { if (0 != mConeTwistConstraint) { mConeTwistConstraint->setBreakingImpulseThreshold(impulse); } else { mBreakingImpulse = impulse; } } float BulletConeTwistConstraint::getBreakingImpulse() const { if (0 != mConeTwistConstraint) { return mConeTwistConstraint->getBreakingImpulseThreshold(); } else { return mBreakingImpulse; } } void BulletConeTwistConstraint::updateConstructionInfo() { if (mConeTwistConstraint != nullptr) { return; } btRigidBody *rbA = reinterpret_cast<BulletRigidBody*>(owner_object() ->getComponent(COMPONENT_TYPE_PHYSICS_RIGID_BODY))->getRigidBody(); // Original pivot is relative to body A (the one that swings) btVector3 p(mPivot.x, mPivot.y, mPivot.z); btMatrix3x3 m(mBodyRotation.vec[0], mBodyRotation.vec[1], mBodyRotation.vec[2], mBodyRotation.vec[3], mBodyRotation.vec[4], mBodyRotation.vec[5], mBodyRotation.vec[6], mBodyRotation.vec[7], mBodyRotation.vec[8]); btTransform fA(m, p); m.setValue(mConeRotation.vec[0], mConeRotation.vec[1], mConeRotation.vec[2], mConeRotation.vec[3], mConeRotation.vec[4], mConeRotation.vec[5], mConeRotation.vec[6], mConeRotation.vec[7], mConeRotation.vec[8]); // Pivot for body B must be calculated p = rbA->getWorldTransform().getOrigin() + p; p -= mRigidBodyB->getRigidBody()->getWorldTransform().getOrigin(); btTransform fB(m, p); mConeTwistConstraint = new btConeTwistConstraint(*rbA, *mRigidBodyB->getRigidBody(), fA, fB); mConeTwistConstraint->setLimit(mSwingLimit, mSwingLimit, mTwistLimit); mConeTwistConstraint->setBreakingImpulseThreshold(mBreakingImpulse); } }
412
0.932776
1
0.932776
game-dev
MEDIA
0.990169
game-dev
0.934047
1
0.934047
dotnet/runtime
98,357
src/coreclr/System.Private.CoreLib/src/System/Reflection/RuntimeCustomAttributeData.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Buffers.Binary; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; namespace System.Reflection { internal sealed class RuntimeCustomAttributeData : CustomAttributeData { #region Internal Static Members internal static IList<CustomAttributeData> GetCustomAttributesInternal(RuntimeType target) { Debug.Assert(target is not null); IList<CustomAttributeData> cad = GetCustomAttributes(target.GetRuntimeModule(), target.MetadataToken); RuntimeType.ListBuilder<Attribute> pcas = default; PseudoCustomAttribute.GetCustomAttributes(target, (RuntimeType)typeof(object), ref pcas); return pcas.Count > 0 ? GetCombinedList(cad, ref pcas) : cad; } internal static IList<CustomAttributeData> GetCustomAttributesInternal(RuntimeFieldInfo target) { Debug.Assert(target is not null); IList<CustomAttributeData> cad = GetCustomAttributes(target.GetRuntimeModule(), target.MetadataToken); RuntimeType.ListBuilder<Attribute> pcas = default; PseudoCustomAttribute.GetCustomAttributes(target, (RuntimeType)typeof(object), ref pcas); return pcas.Count > 0 ? GetCombinedList(cad, ref pcas) : cad; } internal static IList<CustomAttributeData> GetCustomAttributesInternal(RuntimeMethodInfo target) { Debug.Assert(target is not null); IList<CustomAttributeData> cad = GetCustomAttributes(target.GetRuntimeModule(), target.MetadataToken); RuntimeType.ListBuilder<Attribute> pcas = default; PseudoCustomAttribute.GetCustomAttributes(target, (RuntimeType)typeof(object), ref pcas); return pcas.Count > 0 ? GetCombinedList(cad, ref pcas) : cad; } internal static IList<CustomAttributeData> GetCustomAttributesInternal(RuntimeConstructorInfo target) { Debug.Assert(target is not null); return GetCustomAttributes(target.GetRuntimeModule(), target.MetadataToken); } internal static IList<CustomAttributeData> GetCustomAttributesInternal(RuntimeEventInfo target) { Debug.Assert(target is not null); return GetCustomAttributes(target.GetRuntimeModule(), target.MetadataToken); } internal static IList<CustomAttributeData> GetCustomAttributesInternal(RuntimePropertyInfo target) { Debug.Assert(target is not null); return GetCustomAttributes(target.GetRuntimeModule(), target.MetadataToken); } internal static IList<CustomAttributeData> GetCustomAttributesInternal(RuntimeModule target) { Debug.Assert(target is not null); if (target.IsResource()) return new List<CustomAttributeData>(); return GetCustomAttributes(target, target.MetadataToken); } internal static IList<CustomAttributeData> GetCustomAttributesInternal(RuntimeAssembly target) { Debug.Assert(target is not null); // No pseudo attributes for RuntimeAssembly return GetCustomAttributes((RuntimeModule)target.ManifestModule, RuntimeAssembly.GetToken(target)); } internal static IList<CustomAttributeData> GetCustomAttributesInternal(RuntimeParameterInfo target) { Debug.Assert(target is not null); RuntimeType.ListBuilder<Attribute> pcas = default; IList<CustomAttributeData> cad = GetCustomAttributes(target.GetRuntimeModule()!, target.MetadataToken); PseudoCustomAttribute.GetCustomAttributes(target, (RuntimeType)typeof(object), ref pcas); return pcas.Count > 0 ? GetCombinedList(cad, ref pcas) : cad; } private static ReadOnlyCollection<CustomAttributeData> GetCombinedList(IList<CustomAttributeData> customAttributes, ref RuntimeType.ListBuilder<Attribute> pseudoAttributes) { Debug.Assert(pseudoAttributes.Count != 0); CustomAttributeData[] pca = new CustomAttributeData[customAttributes.Count + pseudoAttributes.Count]; customAttributes.CopyTo(pca, pseudoAttributes.Count); for (int i = 0; i < pseudoAttributes.Count; i++) { pca[i] = new RuntimeCustomAttributeData(pseudoAttributes[i]); } return Array.AsReadOnly(pca); } #endregion internal static CustomAttributeEncoding TypeToCustomAttributeEncoding(RuntimeType type) { if (type == typeof(int)) return CustomAttributeEncoding.Int32; if (type.IsActualEnum) return CustomAttributeEncoding.Enum; if (type == typeof(string)) return CustomAttributeEncoding.String; if (type == typeof(Type)) return CustomAttributeEncoding.Type; if (type == typeof(object)) return CustomAttributeEncoding.Object; if (type.IsArray) return CustomAttributeEncoding.Array; if (type == typeof(char)) return CustomAttributeEncoding.Char; if (type == typeof(bool)) return CustomAttributeEncoding.Boolean; if (type == typeof(byte)) return CustomAttributeEncoding.Byte; if (type == typeof(sbyte)) return CustomAttributeEncoding.SByte; if (type == typeof(short)) return CustomAttributeEncoding.Int16; if (type == typeof(ushort)) return CustomAttributeEncoding.UInt16; if (type == typeof(uint)) return CustomAttributeEncoding.UInt32; if (type == typeof(long)) return CustomAttributeEncoding.Int64; if (type == typeof(ulong)) return CustomAttributeEncoding.UInt64; if (type == typeof(float)) return CustomAttributeEncoding.Float; if (type == typeof(double)) return CustomAttributeEncoding.Double; // System.Enum is neither an Enum nor a Class if (type == typeof(Enum)) return CustomAttributeEncoding.Object; if (type.IsClass) return CustomAttributeEncoding.Object; if (type.IsActualInterface) return CustomAttributeEncoding.Object; if (type.IsActualValueType) return CustomAttributeEncoding.Undefined; throw new ArgumentException(SR.Argument_InvalidKindOfTypeForCA, nameof(type)); } #region Private Static Methods private static IList<CustomAttributeData> GetCustomAttributes(RuntimeModule module, int tkTarget) { CustomAttributeRecord[] records = GetCustomAttributeRecords(module, tkTarget); if (records.Length == 0) { return Array.Empty<CustomAttributeData>(); } CustomAttributeData[] customAttributes = new CustomAttributeData[records.Length]; for (int i = 0; i < records.Length; i++) customAttributes[i] = new RuntimeCustomAttributeData(module, records[i].tkCtor, in records[i].blob); return Array.AsReadOnly(customAttributes); } #endregion #region Internal Static Members internal static CustomAttributeRecord[] GetCustomAttributeRecords(RuntimeModule module, int targetToken) { MetadataImport scope = module.MetadataImport; scope.EnumCustomAttributes(targetToken, out MetadataEnumResult tkCustomAttributeTokens); if (tkCustomAttributeTokens.Length == 0) { return Array.Empty<CustomAttributeRecord>(); } CustomAttributeRecord[] records = new CustomAttributeRecord[tkCustomAttributeTokens.Length]; for (int i = 0; i < records.Length; i++) { scope.GetCustomAttributeProps(tkCustomAttributeTokens[i], out records[i].tkCtor.Value, out records[i].blob); } GC.KeepAlive(module); return records; } internal static CustomAttributeTypedArgument Filter(IList<CustomAttributeData> attrs, Type? caType, int parameter) { for (int i = 0; i < attrs.Count; i++) { if (attrs[i].Constructor.DeclaringType == caType) { return attrs[i].ConstructorArguments[parameter]; } } return default; } #endregion private ConstructorInfo m_ctor = null!; private readonly RuntimeModule m_scope = null!; private readonly CustomAttributeCtorParameter[] m_ctorParams = null!; private readonly CustomAttributeNamedParameter[] m_namedParams = null!; private IList<CustomAttributeTypedArgument> m_typedCtorArgs = null!; private IList<CustomAttributeNamedArgument> m_namedArgs = null!; #region Constructor [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2075:UnrecognizedReflectionPattern", Justification = "Property setters and fields which are accessed by any attribute instantiation which is present in the code linker has analyzed." + "As such enumerating all fields and properties may return different results after trimming" + "but all those which are needed to actually have data will be there.")] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", Justification = "We're getting a MethodBase of a constructor that we found in the metadata. The attribute constructor won't be trimmed.")] private RuntimeCustomAttributeData(RuntimeModule scope, MetadataToken caCtorToken, in ConstArray blob) { m_scope = scope; m_ctor = (RuntimeConstructorInfo)RuntimeType.GetMethodBase(m_scope, caCtorToken)!; if (m_ctor.DeclaringType!.IsGenericType) { MetadataImport metadataScope = m_scope.MetadataImport; Type attributeType = m_scope.ResolveType(metadataScope.GetParentToken(caCtorToken), null, null); m_ctor = (RuntimeConstructorInfo)m_scope.ResolveMethod(caCtorToken, attributeType.GenericTypeArguments, null)!.MethodHandle.GetMethodInfo(); } ReadOnlySpan<ParameterInfo> parameters = m_ctor.GetParametersAsSpan(); if (parameters.Length != 0) { m_ctorParams = new CustomAttributeCtorParameter[parameters.Length]; for (int i = 0; i < parameters.Length; i++) m_ctorParams[i] = new CustomAttributeCtorParameter(new CustomAttributeType((RuntimeType)parameters[i].ParameterType)); } else { m_ctorParams = Array.Empty<CustomAttributeCtorParameter>(); } FieldInfo[] fields = m_ctor.DeclaringType!.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); PropertyInfo[] properties = m_ctor.DeclaringType.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); // Allocate collections for members and names params. m_namedParams = new CustomAttributeNamedParameter[properties.Length + fields.Length]; int idx = 0; foreach (FieldInfo fi in fields) { m_namedParams[idx++] = new CustomAttributeNamedParameter( fi, CustomAttributeEncoding.Field, new CustomAttributeType((RuntimeType)fi.FieldType)); } foreach (PropertyInfo pi in properties) { m_namedParams[idx++] = new CustomAttributeNamedParameter( pi, CustomAttributeEncoding.Property, new CustomAttributeType((RuntimeType)pi.PropertyType)); } CustomAttributeEncodedArgument.ParseAttributeArguments(blob, m_ctorParams, m_namedParams, m_scope); } #endregion #region Pseudo Custom Attribute Constructor internal RuntimeCustomAttributeData(Attribute attribute) { if (attribute is DllImportAttribute dllImportAttribute) Init(dllImportAttribute); else if (attribute is FieldOffsetAttribute fieldOffsetAttribute) Init(fieldOffsetAttribute); else if (attribute is MarshalAsAttribute marshalAsAttribute) Init(marshalAsAttribute); else if (attribute is TypeForwardedToAttribute typeForwardedToAttribute) Init(typeForwardedToAttribute); else Init(attribute); } private void Init(DllImportAttribute dllImport) { Type type = typeof(DllImportAttribute); m_ctor = type.GetConstructors(BindingFlags.Public | BindingFlags.Instance)[0]; m_typedCtorArgs = Array.AsReadOnly(new CustomAttributeTypedArgument[] { new CustomAttributeTypedArgument(dllImport.Value), }); m_namedArgs = Array.AsReadOnly(new CustomAttributeNamedArgument[] { new CustomAttributeNamedArgument(type.GetField("EntryPoint")!, dllImport.EntryPoint), new CustomAttributeNamedArgument(type.GetField("CharSet")!, dllImport.CharSet), new CustomAttributeNamedArgument(type.GetField("ExactSpelling")!, dllImport.ExactSpelling), new CustomAttributeNamedArgument(type.GetField("SetLastError")!, dllImport.SetLastError), new CustomAttributeNamedArgument(type.GetField("PreserveSig")!, dllImport.PreserveSig), new CustomAttributeNamedArgument(type.GetField("CallingConvention")!, dllImport.CallingConvention), new CustomAttributeNamedArgument(type.GetField("BestFitMapping")!, dllImport.BestFitMapping), new CustomAttributeNamedArgument(type.GetField("ThrowOnUnmappableChar")!, dllImport.ThrowOnUnmappableChar) }); } private void Init(FieldOffsetAttribute fieldOffset) { m_ctor = typeof(FieldOffsetAttribute).GetConstructors(BindingFlags.Public | BindingFlags.Instance)[0]; m_typedCtorArgs = Array.AsReadOnly(new CustomAttributeTypedArgument[] { new CustomAttributeTypedArgument(fieldOffset.Value) }); m_namedArgs = Array.Empty<CustomAttributeNamedArgument>(); } private void Init(MarshalAsAttribute marshalAs) { Type type = typeof(MarshalAsAttribute); m_ctor = type.GetConstructors(BindingFlags.Public | BindingFlags.Instance)[0]; m_typedCtorArgs = Array.AsReadOnly(new CustomAttributeTypedArgument[] { new CustomAttributeTypedArgument(marshalAs.Value), }); int i = 3; // ArraySubType, SizeParamIndex, SizeConst if (marshalAs.MarshalType is not null) i++; if (marshalAs.MarshalTypeRef is not null) i++; if (marshalAs.MarshalCookie is not null) i++; i++; // IidParameterIndex i++; // SafeArraySubType if (marshalAs.SafeArrayUserDefinedSubType is not null) i++; CustomAttributeNamedArgument[] namedArgs = new CustomAttributeNamedArgument[i]; // For compatibility with previous runtimes, we always include the following 5 attributes, regardless // of if they apply to the UnmanagedType being marshaled or not. i = 0; namedArgs[i++] = new CustomAttributeNamedArgument(type.GetField("ArraySubType")!, marshalAs.ArraySubType); namedArgs[i++] = new CustomAttributeNamedArgument(type.GetField("SizeParamIndex")!, marshalAs.SizeParamIndex); namedArgs[i++] = new CustomAttributeNamedArgument(type.GetField("SizeConst")!, marshalAs.SizeConst); namedArgs[i++] = new CustomAttributeNamedArgument(type.GetField("IidParameterIndex")!, marshalAs.IidParameterIndex); namedArgs[i++] = new CustomAttributeNamedArgument(type.GetField("SafeArraySubType")!, marshalAs.SafeArraySubType); if (marshalAs.MarshalType is not null) namedArgs[i++] = new CustomAttributeNamedArgument(type.GetField("MarshalType")!, marshalAs.MarshalType); if (marshalAs.MarshalTypeRef is not null) namedArgs[i++] = new CustomAttributeNamedArgument(type.GetField("MarshalTypeRef")!, marshalAs.MarshalTypeRef); if (marshalAs.MarshalCookie is not null) namedArgs[i++] = new CustomAttributeNamedArgument(type.GetField("MarshalCookie")!, marshalAs.MarshalCookie); if (marshalAs.SafeArrayUserDefinedSubType is not null) namedArgs[i++] = new CustomAttributeNamedArgument(type.GetField("SafeArrayUserDefinedSubType")!, marshalAs.SafeArrayUserDefinedSubType); m_namedArgs = Array.AsReadOnly(namedArgs); } private void Init(TypeForwardedToAttribute forwardedTo) { Type type = typeof(TypeForwardedToAttribute); Type[] sig = [typeof(Type)]; m_ctor = type.GetConstructor(BindingFlags.Public | BindingFlags.Instance, null, sig, null)!; CustomAttributeTypedArgument[] typedArgs = [new CustomAttributeTypedArgument(typeof(Type), forwardedTo.Destination)]; m_typedCtorArgs = Array.AsReadOnly(typedArgs); m_namedArgs = Array.Empty<CustomAttributeNamedArgument>(); } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2075:UnrecognizedReflectionPattern", Justification = "The pca object had to be created by the single ctor on the Type. So the ctor couldn't have been trimmed.")] private void Init(object pca) { Type type = pca.GetType(); #if DEBUG // Ensure there is only a single constructor for 'pca', so it is safe to suppress IL2075 ConstructorInfo[] allCtors = type.GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); Debug.Assert(allCtors.Length == 1); Debug.Assert(allCtors[0].GetParametersAsSpan().Length == 0); #endif m_ctor = type.GetConstructors(BindingFlags.Public | BindingFlags.Instance)[0]; m_typedCtorArgs = Array.Empty<CustomAttributeTypedArgument>(); m_namedArgs = Array.Empty<CustomAttributeNamedArgument>(); } #endregion #region Public Members public override ConstructorInfo Constructor => m_ctor; public override IList<CustomAttributeTypedArgument> ConstructorArguments { get { if (m_typedCtorArgs is null) { if (m_ctorParams.Length != 0) { CustomAttributeTypedArgument[] typedCtorArgs = new CustomAttributeTypedArgument[m_ctorParams.Length]; for (int i = 0; i < typedCtorArgs.Length; i++) { CustomAttributeEncodedArgument encodedArg = m_ctorParams[i].EncodedArgument!; typedCtorArgs[i] = new CustomAttributeTypedArgument(m_scope, encodedArg); } m_typedCtorArgs = Array.AsReadOnly(typedCtorArgs); } else { m_typedCtorArgs = Array.Empty<CustomAttributeTypedArgument>(); } } return m_typedCtorArgs; } } public override IList<CustomAttributeNamedArgument> NamedArguments { get { if (m_namedArgs is null) { int cNamedArgs = 0; if (m_namedParams is not null) { foreach (CustomAttributeNamedParameter p in m_namedParams) { if (p.EncodedArgument is not null && p.EncodedArgument.CustomAttributeType.EncodedType != CustomAttributeEncoding.Undefined) { cNamedArgs++; } } } if (cNamedArgs != 0) { CustomAttributeNamedArgument[] namedArgs = new CustomAttributeNamedArgument[cNamedArgs]; int j = 0; foreach (CustomAttributeNamedParameter p in m_namedParams!) { if (p.EncodedArgument is not null && p.EncodedArgument.CustomAttributeType.EncodedType != CustomAttributeEncoding.Undefined) { Debug.Assert(p.MemberInfo is not null); namedArgs[j++] = new CustomAttributeNamedArgument( p.MemberInfo, new CustomAttributeTypedArgument(m_scope, p.EncodedArgument)); } } m_namedArgs = Array.AsReadOnly(namedArgs); } else { m_namedArgs = Array.Empty<CustomAttributeNamedArgument>(); } } return m_namedArgs; } } #endregion } public readonly partial struct CustomAttributeTypedArgument { #region Private Static Methods private static Type CustomAttributeEncodingToType(CustomAttributeEncoding encodedType) { return encodedType switch { CustomAttributeEncoding.Enum => typeof(Enum), CustomAttributeEncoding.Int32 => typeof(int), CustomAttributeEncoding.String => typeof(string), CustomAttributeEncoding.Type => typeof(Type), CustomAttributeEncoding.Array => typeof(Array), CustomAttributeEncoding.Char => typeof(char), CustomAttributeEncoding.Boolean => typeof(bool), CustomAttributeEncoding.SByte => typeof(sbyte), CustomAttributeEncoding.Byte => typeof(byte), CustomAttributeEncoding.Int16 => typeof(short), CustomAttributeEncoding.UInt16 => typeof(ushort), CustomAttributeEncoding.UInt32 => typeof(uint), CustomAttributeEncoding.Int64 => typeof(long), CustomAttributeEncoding.UInt64 => typeof(ulong), CustomAttributeEncoding.Float => typeof(float), CustomAttributeEncoding.Double => typeof(double), CustomAttributeEncoding.Object => typeof(object), _ => throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, (int)encodedType), nameof(encodedType)), }; } private static object EncodedValueToRawValue(PrimitiveValue val, CustomAttributeEncoding encodedType) { return encodedType switch { CustomAttributeEncoding.Boolean => (byte)val.Byte4 != 0, CustomAttributeEncoding.Char => (char)val.Byte4, CustomAttributeEncoding.Byte => (byte)val.Byte4, CustomAttributeEncoding.SByte => (sbyte)val.Byte4, CustomAttributeEncoding.Int16 => (short)val.Byte4, CustomAttributeEncoding.UInt16 => (ushort)val.Byte4, CustomAttributeEncoding.Int32 => val.Byte4, CustomAttributeEncoding.UInt32 => (uint)val.Byte4, CustomAttributeEncoding.Int64 => val.Byte8, CustomAttributeEncoding.UInt64 => (ulong)val.Byte8, CustomAttributeEncoding.Float => BitConverter.Int32BitsToSingle(val.Byte4), CustomAttributeEncoding.Double => BitConverter.Int64BitsToDouble(val.Byte8), _ => throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, val.Byte8), nameof(val)) }; } private static RuntimeType ResolveType(RuntimeModule scope, string typeName) { RuntimeType type = TypeNameResolver.GetTypeReferencedByCustomAttribute(typeName, scope); Debug.Assert(type is not null); return type; } #endregion internal CustomAttributeTypedArgument(RuntimeModule scope, CustomAttributeEncodedArgument encodedArg) { CustomAttributeEncoding encodedType = encodedArg.CustomAttributeType.EncodedType; if (encodedType == CustomAttributeEncoding.Undefined) throw new ArgumentException(null, nameof(encodedArg)); if (encodedType == CustomAttributeEncoding.Enum) { _argumentType = encodedArg.CustomAttributeType.EnumType!; _value = EncodedValueToRawValue(encodedArg.PrimitiveValue, encodedArg.CustomAttributeType.EncodedEnumType); } else if (encodedType == CustomAttributeEncoding.String) { _argumentType = typeof(string); _value = encodedArg.StringValue; } else if (encodedType == CustomAttributeEncoding.Type) { _argumentType = typeof(Type); _value = null; if (encodedArg.StringValue is not null) _value = ResolveType(scope, encodedArg.StringValue); } else if (encodedType == CustomAttributeEncoding.Array) { encodedType = encodedArg.CustomAttributeType.EncodedArrayType; Type elementType; if (encodedType == CustomAttributeEncoding.Enum) { elementType = encodedArg.CustomAttributeType.EnumType!; } else { elementType = CustomAttributeEncodingToType(encodedType); } _argumentType = elementType.MakeArrayType(); if (encodedArg.ArrayValue is null) { _value = null; } else { CustomAttributeTypedArgument[] arrayValue = new CustomAttributeTypedArgument[encodedArg.ArrayValue.Length]; for (int i = 0; i < arrayValue.Length; i++) arrayValue[i] = new CustomAttributeTypedArgument(scope, encodedArg.ArrayValue[i]); _value = Array.AsReadOnly(arrayValue); } } else { _argumentType = CustomAttributeEncodingToType(encodedType); _value = EncodedValueToRawValue(encodedArg.PrimitiveValue, encodedType); } } } internal struct CustomAttributeRecord { internal ConstArray blob; internal MetadataToken tkCtor; public CustomAttributeRecord(int token, ConstArray blob) { tkCtor = new MetadataToken(token); this.blob = blob; } } // See CorSerializationType in corhdr.h internal enum CustomAttributeEncoding : int { Undefined = 0, Boolean = CorElementType.ELEMENT_TYPE_BOOLEAN, Char = CorElementType.ELEMENT_TYPE_CHAR, SByte = CorElementType.ELEMENT_TYPE_I1, Byte = CorElementType.ELEMENT_TYPE_U1, Int16 = CorElementType.ELEMENT_TYPE_I2, UInt16 = CorElementType.ELEMENT_TYPE_U2, Int32 = CorElementType.ELEMENT_TYPE_I4, UInt32 = CorElementType.ELEMENT_TYPE_U4, Int64 = CorElementType.ELEMENT_TYPE_I8, UInt64 = CorElementType.ELEMENT_TYPE_U8, Float = CorElementType.ELEMENT_TYPE_R4, Double = CorElementType.ELEMENT_TYPE_R8, String = CorElementType.ELEMENT_TYPE_STRING, Array = CorElementType.ELEMENT_TYPE_SZARRAY, Type = 0x50, Object = 0x51, Field = 0x53, Property = 0x54, Enum = 0x55 } [StructLayout(LayoutKind.Explicit)] internal struct PrimitiveValue { [FieldOffset(0)] public int Byte4; [FieldOffset(0)] public long Byte8; } internal sealed class CustomAttributeEncodedArgument { internal static void ParseAttributeArguments( ConstArray attributeBlob, CustomAttributeCtorParameter[] customAttributeCtorParameters, CustomAttributeNamedParameter[] customAttributeNamedParameters, RuntimeModule customAttributeModule) { ArgumentNullException.ThrowIfNull(customAttributeModule); Debug.Assert(customAttributeCtorParameters is not null); Debug.Assert(customAttributeNamedParameters is not null); if (customAttributeCtorParameters.Length != 0 || customAttributeNamedParameters.Length != 0) { CustomAttributeDataParser parser = new CustomAttributeDataParser(attributeBlob); try { if (!parser.ValidateProlog()) { throw new BadImageFormatException(SR.Arg_CustomAttributeFormatException); } ParseCtorArgs(ref parser, customAttributeCtorParameters, customAttributeModule); ParseNamedArgs(ref parser, customAttributeNamedParameters, customAttributeModule); } catch (Exception ex) when (ex is not OutOfMemoryException) { throw new CustomAttributeFormatException(ex.Message, ex); } } } internal CustomAttributeEncodedArgument(CustomAttributeType type) { CustomAttributeType = type; } public CustomAttributeType CustomAttributeType { get; } public PrimitiveValue PrimitiveValue { get; set; } public CustomAttributeEncodedArgument[]? ArrayValue { get; set; } public string? StringValue { get; set; } private static void ParseCtorArgs( ref CustomAttributeDataParser parser, CustomAttributeCtorParameter[] customAttributeCtorParameters, RuntimeModule module) { foreach (CustomAttributeCtorParameter p in customAttributeCtorParameters) { p.EncodedArgument = ParseCustomAttributeValue( ref parser, p.CustomAttributeType, module); } } private static void ParseNamedArgs( ref CustomAttributeDataParser parser, CustomAttributeNamedParameter[] customAttributeNamedParameters, RuntimeModule module) { // Parse the named arguments in the custom attribute. int argCount = parser.GetI2(); for (int i = 0; i < argCount; ++i) { // Determine if a field or property. CustomAttributeEncoding namedArgFieldOrProperty = parser.GetTag(); if (namedArgFieldOrProperty is not CustomAttributeEncoding.Field && namedArgFieldOrProperty is not CustomAttributeEncoding.Property) { throw new BadImageFormatException(SR.Arg_CustomAttributeFormatException); } // Parse the encoded type for the named argument. CustomAttributeType argType = ParseCustomAttributeType(ref parser, module); string? argName = parser.GetString(); // Argument name must be non-null and non-empty. if (string.IsNullOrEmpty(argName)) { throw new BadImageFormatException(SR.Arg_CustomAttributeFormatException); } // Update the appropriate named argument element. CustomAttributeNamedParameter? parameterToUpdate = null; foreach (CustomAttributeNamedParameter namedParam in customAttributeNamedParameters) { CustomAttributeType namedArgType = namedParam.CustomAttributeType; if (namedArgType.EncodedType != CustomAttributeEncoding.Object) { if (namedArgType.EncodedType != argType.EncodedType) { continue; } // Match array type if (argType.EncodedType is CustomAttributeEncoding.Array && namedArgType.EncodedArrayType is not CustomAttributeEncoding.Object && argType.EncodedArrayType != namedArgType.EncodedArrayType) { continue; } } // Match name if (!namedParam.MemberInfo.Name.Equals(argName)) { continue; } // If enum, match enum name. if (namedArgType.EncodedType is CustomAttributeEncoding.Enum || (namedArgType.EncodedType is CustomAttributeEncoding.Array && namedArgType.EncodedArrayType is CustomAttributeEncoding.Enum)) { if (!ReferenceEquals(argType.EnumType, namedArgType.EnumType)) { continue; } Debug.Assert(namedArgType.EncodedEnumType == argType.EncodedEnumType); } // Found a match parameterToUpdate = namedParam; break; } if (parameterToUpdate is null) { throw new BadImageFormatException(SR.Arg_CustomAttributeUnknownNamedArgument); } if (parameterToUpdate.EncodedArgument is not null) { throw new BadImageFormatException(SR.Arg_CustomAttributeDuplicateNamedArgument); } parameterToUpdate.EncodedArgument = ParseCustomAttributeValue(ref parser, argType, module); } } private static CustomAttributeEncodedArgument ParseCustomAttributeValue( ref CustomAttributeDataParser parser, CustomAttributeType type, RuntimeModule module) { CustomAttributeType attributeType = type.EncodedType == CustomAttributeEncoding.Object ? ParseCustomAttributeType(ref parser, module) : type; CustomAttributeEncodedArgument arg = new(attributeType); CustomAttributeEncoding underlyingType = attributeType.EncodedType == CustomAttributeEncoding.Enum ? attributeType.EncodedEnumType : attributeType.EncodedType; switch (underlyingType) { case CustomAttributeEncoding.Boolean: case CustomAttributeEncoding.Byte: case CustomAttributeEncoding.SByte: arg.PrimitiveValue = new PrimitiveValue() { Byte4 = parser.GetU1() }; break; case CustomAttributeEncoding.Char: case CustomAttributeEncoding.Int16: case CustomAttributeEncoding.UInt16: arg.PrimitiveValue = new PrimitiveValue() { Byte4 = parser.GetU2() }; break; case CustomAttributeEncoding.Int32: case CustomAttributeEncoding.UInt32: arg.PrimitiveValue = new PrimitiveValue() { Byte4 = parser.GetI4() }; break; case CustomAttributeEncoding.Int64: case CustomAttributeEncoding.UInt64: arg.PrimitiveValue = new PrimitiveValue() { Byte8 = parser.GetI8() }; break; case CustomAttributeEncoding.Float: arg.PrimitiveValue = new PrimitiveValue() { Byte4 = BitConverter.SingleToInt32Bits(parser.GetR4()) }; break; case CustomAttributeEncoding.Double: arg.PrimitiveValue = new PrimitiveValue() { Byte8 = BitConverter.DoubleToInt64Bits(parser.GetR8()) }; break; case CustomAttributeEncoding.String: case CustomAttributeEncoding.Type: arg.StringValue = parser.GetString(); break; case CustomAttributeEncoding.Array: { arg.ArrayValue = null; int len = parser.GetI4(); if (len != -1) // indicates array is null - ECMA-335 II.23.3. { attributeType = new CustomAttributeType( attributeType.EncodedArrayType, CustomAttributeEncoding.Undefined, // Array type attributeType.EncodedEnumType, attributeType.EnumType); arg.ArrayValue = new CustomAttributeEncodedArgument[len]; for (int i = 0; i < len; ++i) { arg.ArrayValue[i] = ParseCustomAttributeValue(ref parser, attributeType, module); } } break; } default: throw new BadImageFormatException(); } return arg; } private static CustomAttributeType ParseCustomAttributeType(ref CustomAttributeDataParser parser, RuntimeModule module) { CustomAttributeEncoding arrayTag = CustomAttributeEncoding.Undefined; CustomAttributeEncoding enumTag = CustomAttributeEncoding.Undefined; Type? enumType = null; CustomAttributeEncoding tag = parser.GetTag(); if (tag is CustomAttributeEncoding.Array) { arrayTag = parser.GetTag(); } // Load the enum type if needed. if (tag is CustomAttributeEncoding.Enum || (tag is CustomAttributeEncoding.Array && arrayTag is CustomAttributeEncoding.Enum)) { // We cannot determine the underlying type without loading the enum. string enumTypeMaybe = parser.GetString() ?? throw new BadImageFormatException(); enumType = TypeNameResolver.GetTypeReferencedByCustomAttribute(enumTypeMaybe, module); if (!enumType.IsEnum) { throw new BadImageFormatException(); } enumTag = RuntimeCustomAttributeData.TypeToCustomAttributeEncoding((RuntimeType)enumType.GetEnumUnderlyingType()); } return new CustomAttributeType(tag, arrayTag, enumTag, enumType); } /// <summary> /// Used to parse CustomAttribute data. See ECMA-335 II.23.3. /// </summary> private ref struct CustomAttributeDataParser { private int _curr; private ReadOnlySpan<byte> _blob; public CustomAttributeDataParser(ConstArray attributeBlob) { unsafe { _blob = new ReadOnlySpan<byte>((void*)attributeBlob.Signature, attributeBlob.Length); } _curr = 0; } private ReadOnlySpan<byte> PeekData(int size) => _blob.Slice(_curr, size); private ReadOnlySpan<byte> ReadData(int size) { ReadOnlySpan<byte> tmp = PeekData(size); Debug.Assert(size <= (_blob.Length - _curr)); _curr += size; return tmp; } public byte GetU1() { ReadOnlySpan<byte> tmp = ReadData(sizeof(byte)); return tmp[0]; } public sbyte GetI1() => (sbyte)GetU1(); public ushort GetU2() { ReadOnlySpan<byte> tmp = ReadData(sizeof(ushort)); return BinaryPrimitives.ReadUInt16LittleEndian(tmp); } public short GetI2() => (short)GetU2(); public uint GetU4() { ReadOnlySpan<byte> tmp = ReadData(sizeof(uint)); return BinaryPrimitives.ReadUInt32LittleEndian(tmp); } public int GetI4() => (int)GetU4(); public ulong GetU8() { ReadOnlySpan<byte> tmp = ReadData(sizeof(ulong)); return BinaryPrimitives.ReadUInt64LittleEndian(tmp); } public long GetI8() => (long)GetU8(); public float GetR4() { ReadOnlySpan<byte> tmp = ReadData(sizeof(float)); return BinaryPrimitives.ReadSingleLittleEndian(tmp); } public CustomAttributeEncoding GetTag() { return (CustomAttributeEncoding)GetI1(); } public double GetR8() { ReadOnlySpan<byte> tmp = ReadData(sizeof(double)); return BinaryPrimitives.ReadDoubleLittleEndian(tmp); } public ushort GetProlog() => GetU2(); public bool ValidateProlog() { ushort val = GetProlog(); return val == 0x0001; } public string? GetString() { byte packedLengthBegin = PeekData(sizeof(byte))[0]; // Check if the embedded string indicates a 'null' string (0xff). if (packedLengthBegin == 0xff) // ECMA 335- II.23.3 { // Consume the indicator. ReadData(1); return null; } // Not a null string, return a non-null string value. // The embedded string a UTF-8 prefixed by an ECMA-335 packed integer. int length = GetPackedLength(packedLengthBegin); if (length == 0) { return string.Empty; } ReadOnlySpan<byte> utf8ByteSpan = ReadData(length); return Encoding.UTF8.GetString(utf8ByteSpan); } private int GetPackedLength(byte firstByte) { if ((firstByte & 0x80) == 0) { // Consume one byte. ReadData(1); return firstByte & 0x7f; } int len; ReadOnlySpan<byte> data; if ((firstByte & 0xC0) == 0x80) { // Consume the bytes. data = ReadData(2); len = (data[0] & 0x3f) << 8; return len + data[1]; } if ((firstByte & 0xE0) == 0xC0) { // Consume the bytes. data = ReadData(4); len = (data[0] & 0x1f) << 24; len += data[1] << 16; len += data[2] << 8; return len + data[3]; } throw new OverflowException(); } } } internal sealed class CustomAttributeCtorParameter(CustomAttributeType type) { public CustomAttributeType CustomAttributeType => type; public CustomAttributeEncodedArgument? EncodedArgument { get; set; } } internal sealed class CustomAttributeNamedParameter(MemberInfo memberInfo, CustomAttributeEncoding fieldOrProperty, CustomAttributeType type) { public MemberInfo MemberInfo => memberInfo; public CustomAttributeType CustomAttributeType => type; public CustomAttributeEncoding FieldOrProperty => fieldOrProperty; public CustomAttributeEncodedArgument? EncodedArgument { get; set; } } internal sealed class CustomAttributeType { public CustomAttributeType( CustomAttributeEncoding encodedType, CustomAttributeEncoding encodedArrayType, CustomAttributeEncoding encodedEnumType, Type? enumType) { EncodedType = encodedType; EncodedArrayType = encodedArrayType; EncodedEnumType = encodedEnumType; EnumType = enumType; } public CustomAttributeType(RuntimeType parameterType) { Debug.Assert(parameterType is not null); CustomAttributeEncoding encodedType = RuntimeCustomAttributeData.TypeToCustomAttributeEncoding(parameterType); CustomAttributeEncoding encodedArrayType = CustomAttributeEncoding.Undefined; CustomAttributeEncoding encodedEnumType = CustomAttributeEncoding.Undefined; Type? enumType = null; if (encodedType == CustomAttributeEncoding.Array) { parameterType = (RuntimeType)parameterType.GetElementType()!; encodedArrayType = RuntimeCustomAttributeData.TypeToCustomAttributeEncoding(parameterType); } if (encodedType == CustomAttributeEncoding.Enum || encodedArrayType == CustomAttributeEncoding.Enum) { enumType = parameterType; encodedEnumType = RuntimeCustomAttributeData.TypeToCustomAttributeEncoding((RuntimeType)Enum.GetUnderlyingType(parameterType)); } EncodedType = encodedType; EncodedArrayType = encodedArrayType; EncodedEnumType = encodedEnumType; EnumType = enumType; } public CustomAttributeEncoding EncodedType { get; } public CustomAttributeEncoding EncodedEnumType { get; } public CustomAttributeEncoding EncodedArrayType { get; } /// The most complicated type is an enum[] in which case... public Type? EnumType { get; } } internal static unsafe partial class CustomAttribute { #region Internal Static Members internal static bool IsDefined(RuntimeType type, RuntimeType? caType, bool inherit) { Debug.Assert(type is not null); if (type.GetElementType() is not null) return false; if (PseudoCustomAttribute.IsDefined(type, caType)) return true; if (IsCustomAttributeDefined(type.GetRuntimeModule(), type.MetadataToken, caType)) return true; if (!inherit) return false; type = (type.BaseType as RuntimeType)!; while (type is not null) { if (IsCustomAttributeDefined(type.GetRuntimeModule(), type.MetadataToken, caType, 0, inherit)) return true; type = (type.BaseType as RuntimeType)!; } return false; } internal static bool IsDefined(RuntimeMethodInfo method, RuntimeType caType, bool inherit) { Debug.Assert(method is not null); Debug.Assert(caType is not null); if (PseudoCustomAttribute.IsDefined(method, caType)) return true; if (IsCustomAttributeDefined(method.GetRuntimeModule(), method.MetadataToken, caType)) return true; if (!inherit) return false; method = method.GetParentDefinition()!; while (method is not null) { if (IsCustomAttributeDefined(method.GetRuntimeModule(), method.MetadataToken, caType, 0, inherit)) return true; method = method.GetParentDefinition()!; } return false; } internal static bool IsDefined(RuntimeConstructorInfo ctor, RuntimeType caType) { Debug.Assert(ctor is not null); Debug.Assert(caType is not null); // No pseudo attributes for RuntimeConstructorInfo return IsCustomAttributeDefined(ctor.GetRuntimeModule(), ctor.MetadataToken, caType); } internal static bool IsDefined(RuntimePropertyInfo property, RuntimeType caType) { Debug.Assert(property is not null); Debug.Assert(caType is not null); // No pseudo attributes for RuntimePropertyInfo return IsCustomAttributeDefined(property.GetRuntimeModule(), property.MetadataToken, caType); } internal static bool IsDefined(RuntimeEventInfo e, RuntimeType caType) { Debug.Assert(e is not null); Debug.Assert(caType is not null); // No pseudo attributes for RuntimeEventInfo return IsCustomAttributeDefined(e.GetRuntimeModule(), e.MetadataToken, caType); } internal static bool IsDefined(RuntimeFieldInfo field, RuntimeType caType) { Debug.Assert(field is not null); Debug.Assert(caType is not null); if (PseudoCustomAttribute.IsDefined(field, caType)) return true; return IsCustomAttributeDefined(field.GetRuntimeModule(), field.MetadataToken, caType); } internal static bool IsDefined(RuntimeParameterInfo parameter, RuntimeType caType) { Debug.Assert(parameter is not null); Debug.Assert(caType is not null); if (PseudoCustomAttribute.IsDefined(parameter, caType)) return true; return IsCustomAttributeDefined(parameter.GetRuntimeModule()!, parameter.MetadataToken, caType); } internal static bool IsDefined(RuntimeAssembly assembly, RuntimeType caType) { Debug.Assert(assembly is not null); Debug.Assert(caType is not null); // No pseudo attributes for RuntimeAssembly return IsCustomAttributeDefined((assembly.ManifestModule as RuntimeModule)!, RuntimeAssembly.GetToken(assembly), caType); } internal static bool IsDefined(RuntimeModule module, RuntimeType caType) { Debug.Assert(module is not null); Debug.Assert(caType is not null); // No pseudo attributes for RuntimeModule return IsCustomAttributeDefined(module, module.MetadataToken, caType); } internal static object[] GetCustomAttributes(RuntimeType type, RuntimeType caType, bool inherit) { Debug.Assert(type is not null); Debug.Assert(caType is not null); if (type.GetElementType() is not null) return CreateAttributeArrayHelper(caType, 0); if (type.IsGenericType && !type.IsGenericTypeDefinition) type = (type.GetGenericTypeDefinition() as RuntimeType)!; RuntimeType.ListBuilder<Attribute> pcas = default; PseudoCustomAttribute.GetCustomAttributes(type, caType, ref pcas); // if we are asked to go up the hierarchy chain we have to do it now and regardless of the // attribute usage for the specific attribute because a derived attribute may override the usage... // ... however if the attribute is sealed we can rely on the attribute usage if (!inherit || (caType.IsSealed && !GetAttributeUsage(caType).Inherited)) { object[] attributes = GetCustomAttributes(type.GetRuntimeModule(), type.MetadataToken, pcas.Count, caType); if (pcas.Count > 0) pcas.CopyTo(attributes, attributes.Length - pcas.Count); return attributes; } RuntimeType.ListBuilder<object> result = default; bool mustBeInheritable = false; for (int i = 0; i < pcas.Count; i++) result.Add(pcas[i]); do { AddCustomAttributes(ref result, type.GetRuntimeModule(), type.MetadataToken, caType, mustBeInheritable, result); mustBeInheritable = true; type = (type.BaseType as RuntimeType)!; } while (type != (RuntimeType)typeof(object) && type != null); object[] typedResult = CreateAttributeArrayHelper(caType, result.Count); for (int i = 0; i < result.Count; i++) { typedResult[i] = result[i]; } return typedResult; } internal static object[] GetCustomAttributes(RuntimeMethodInfo method, RuntimeType caType, bool inherit) { Debug.Assert(method is not null); Debug.Assert(caType is not null); if (method.IsGenericMethod && !method.IsGenericMethodDefinition) method = (method.GetGenericMethodDefinition() as RuntimeMethodInfo)!; RuntimeType.ListBuilder<Attribute> pcas = default; PseudoCustomAttribute.GetCustomAttributes(method, caType, ref pcas); // if we are asked to go up the hierarchy chain we have to do it now and regardless of the // attribute usage for the specific attribute because a derived attribute may override the usage... // ... however if the attribute is sealed we can rely on the attribute usage if (!inherit || (caType.IsSealed && !GetAttributeUsage(caType).Inherited)) { object[] attributes = GetCustomAttributes(method.GetRuntimeModule(), method.MetadataToken, pcas.Count, caType); if (pcas.Count > 0) pcas.CopyTo(attributes, attributes.Length - pcas.Count); return attributes; } RuntimeType.ListBuilder<object> result = default; bool mustBeInheritable = false; for (int i = 0; i < pcas.Count; i++) result.Add(pcas[i]); while (method != null) { AddCustomAttributes(ref result, method.GetRuntimeModule(), method.MetadataToken, caType, mustBeInheritable, result); mustBeInheritable = true; method = method.GetParentDefinition()!; } object[] typedResult = CreateAttributeArrayHelper(caType, result.Count); for (int i = 0; i < result.Count; i++) { typedResult[i] = result[i]; } return typedResult; } internal static object[] GetCustomAttributes(RuntimeConstructorInfo ctor, RuntimeType caType) { Debug.Assert(ctor != null); Debug.Assert(caType != null); // No pseudo attributes for RuntimeConstructorInfo return GetCustomAttributes(ctor.GetRuntimeModule(), ctor.MetadataToken, 0, caType); } internal static object[] GetCustomAttributes(RuntimePropertyInfo property, RuntimeType caType) { Debug.Assert(property is not null); Debug.Assert(caType is not null); // No pseudo attributes for RuntimePropertyInfo return GetCustomAttributes(property.GetRuntimeModule(), property.MetadataToken, 0, caType); } internal static object[] GetCustomAttributes(RuntimeEventInfo e, RuntimeType caType) { Debug.Assert(e is not null); Debug.Assert(caType is not null); // No pseudo attributes for RuntimeEventInfo return GetCustomAttributes(e.GetRuntimeModule(), e.MetadataToken, 0, caType); } internal static object[] GetCustomAttributes(RuntimeFieldInfo field, RuntimeType caType) { Debug.Assert(field is not null); Debug.Assert(caType is not null); RuntimeType.ListBuilder<Attribute> pcas = default; PseudoCustomAttribute.GetCustomAttributes(field, caType, ref pcas); object[] attributes = GetCustomAttributes(field.GetRuntimeModule(), field.MetadataToken, pcas.Count, caType); if (pcas.Count > 0) pcas.CopyTo(attributes, attributes.Length - pcas.Count); return attributes; } internal static object[] GetCustomAttributes(RuntimeParameterInfo parameter, RuntimeType caType) { Debug.Assert(parameter is not null); Debug.Assert(caType is not null); RuntimeType.ListBuilder<Attribute> pcas = default; PseudoCustomAttribute.GetCustomAttributes(parameter, caType, ref pcas); object[] attributes = GetCustomAttributes(parameter.GetRuntimeModule()!, parameter.MetadataToken, pcas.Count, caType); if (pcas.Count > 0) pcas.CopyTo(attributes, attributes.Length - pcas.Count); return attributes; } internal static object[] GetCustomAttributes(RuntimeAssembly assembly, RuntimeType caType) { Debug.Assert(assembly is not null); Debug.Assert(caType is not null); // No pseudo attributes for RuntimeAssembly int assemblyToken = RuntimeAssembly.GetToken(assembly); return GetCustomAttributes((assembly.ManifestModule as RuntimeModule)!, assemblyToken, 0, caType); } internal static object[] GetCustomAttributes(RuntimeModule module, RuntimeType caType) { Debug.Assert(module is not null); Debug.Assert(caType is not null); // No pseudo attributes for RuntimeModule return GetCustomAttributes(module, module.MetadataToken, 0, caType); } internal static bool IsAttributeDefined(RuntimeModule decoratedModule, int decoratedMetadataToken, int attributeCtorToken) { return IsCustomAttributeDefined(decoratedModule, decoratedMetadataToken, null, attributeCtorToken, false); } internal static bool IsCustomAttributeDefined( RuntimeModule decoratedModule, int decoratedMetadataToken, RuntimeType? attributeFilterType) { return IsCustomAttributeDefined(decoratedModule, decoratedMetadataToken, attributeFilterType, 0, false); } private static bool IsCustomAttributeDefined( RuntimeModule decoratedModule, int decoratedMetadataToken, RuntimeType? attributeFilterType, int attributeCtorToken, bool mustBeInheritable) { MetadataImport scope = decoratedModule.MetadataImport; scope.EnumCustomAttributes(decoratedMetadataToken, out MetadataEnumResult attributeTokens); if (attributeTokens.Length == 0) { return false; } CustomAttributeRecord record = default; if (attributeFilterType is not null) { Debug.Assert(attributeCtorToken == 0); RuntimeType.ListBuilder<object> derivedAttributes = default; for (int i = 0; i < attributeTokens.Length; i++) { scope.GetCustomAttributeProps(attributeTokens[i], out record.tkCtor.Value, out record.blob); if (FilterCustomAttributeRecord(record.tkCtor, in scope, decoratedModule, decoratedMetadataToken, attributeFilterType, mustBeInheritable, ref derivedAttributes, out _, out _, out _)) { return true; } } } else { Debug.Assert(attributeFilterType is null); Debug.Assert(!MetadataToken.IsNullToken(attributeCtorToken)); for (int i = 0; i < attributeTokens.Length; i++) { scope.GetCustomAttributeProps(attributeTokens[i], out record.tkCtor.Value, out record.blob); if (record.tkCtor == attributeCtorToken) { return true; } } } GC.KeepAlive(decoratedModule); return false; } private static object[] GetCustomAttributes( RuntimeModule decoratedModule, int decoratedMetadataToken, int pcaCount, RuntimeType attributeFilterType) { RuntimeType.ListBuilder<object> attributes = default; AddCustomAttributes(ref attributes, decoratedModule, decoratedMetadataToken, attributeFilterType, false, default); object[] result = CreateAttributeArrayHelper(attributeFilterType, attributes.Count + pcaCount); for (int i = 0; i < attributes.Count; i++) { result[i] = attributes[i]; } return result; } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2070:MethodParameterDoesntMeetThisParameterRequirements", Justification = "Linker guarantees presence of all the constructor parameters, property setters and fields which are accessed by any " + "attribute instantiation which is present in the code linker has analyzed." + "As such the reflection usage in this method will never fail as those methods/fields will be present.")] private static void AddCustomAttributes( ref RuntimeType.ListBuilder<object> attributes, RuntimeModule decoratedModule, int decoratedMetadataToken, RuntimeType? attributeFilterType, bool mustBeInheritable, // The derivedAttributes list must be passed by value so that it is not modified with the discovered attributes RuntimeType.ListBuilder<object> derivedAttributes) { CustomAttributeRecord[] car = RuntimeCustomAttributeData.GetCustomAttributeRecords(decoratedModule, decoratedMetadataToken); if (attributeFilterType is null && car.Length == 0) { return; } MetadataImport scope = decoratedModule.MetadataImport; for (int i = 0; i < car.Length; i++) { ref CustomAttributeRecord caRecord = ref car[i]; IntPtr blobStart = caRecord.blob.Signature; IntPtr blobEnd = (IntPtr)((byte*)blobStart + caRecord.blob.Length); if (!FilterCustomAttributeRecord(caRecord.tkCtor, in scope, decoratedModule, decoratedMetadataToken, attributeFilterType!, mustBeInheritable, ref derivedAttributes, out RuntimeType attributeType, out IRuntimeMethodInfo? ctorWithParameters, out bool isVarArg)) { continue; } // Leverage RuntimeConstructorInfo standard .ctor verification RuntimeConstructorInfo.CheckCanCreateInstance(attributeType, isVarArg); // Create custom attribute object int cNamedArgs; object attribute; if (ctorWithParameters is not null) { attribute = CreateCustomAttributeInstance(decoratedModule, attributeType, ctorWithParameters, ref blobStart, blobEnd, out cNamedArgs); } else { attribute = attributeType.CreateInstanceDefaultCtor(publicOnly: false, wrapExceptions: false)!; // It is allowed by the ECMA spec to have an empty signature blob int blobLen = (int)((byte*)blobEnd - (byte*)blobStart); if (blobLen == 0) { cNamedArgs = 0; } else { int data = Unsafe.ReadUnaligned<int>((void*)blobStart); if (!BitConverter.IsLittleEndian) { // Metadata is always written in little-endian format. Must account for this on // big-endian platforms. data = BinaryPrimitives.ReverseEndianness(data); } const int CustomAttributeVersion = 0x0001; if ((data & 0xffff) != CustomAttributeVersion) { throw new CustomAttributeFormatException(); } cNamedArgs = data >> 16; blobStart = (IntPtr)((byte*)blobStart + 4); // skip version and namedArgs count } } for (int j = 0; j < cNamedArgs; j++) { GetPropertyOrFieldData(decoratedModule, ref blobStart, blobEnd, out string name, out bool isProperty, out RuntimeType? type, out object? value); try { if (isProperty) { if (type is null && value is not null) { type = (RuntimeType)value.GetType(); if (type == typeof(RuntimeType)) { type = (RuntimeType)typeof(Type); } } RuntimePropertyInfo? property = (RuntimePropertyInfo?)(type is null ? attributeType.GetProperty(name) : attributeType.GetProperty(name, type, [])) ?? throw new CustomAttributeFormatException(SR.Format(SR.RFLCT_InvalidPropFail, name)); RuntimeMethodInfo setMethod = property.GetSetMethod(true)!; // Public properties may have non-public setter methods if (!setMethod.IsPublic) { continue; } setMethod.InvokePropertySetter(attribute, BindingFlags.Default, null, value, null); } else { FieldInfo field = attributeType.GetField(name)!; field.SetValue(attribute, value, BindingFlags.Default, Type.DefaultBinder, null); } } catch (Exception e) { throw new CustomAttributeFormatException( SR.Format(isProperty ? SR.RFLCT_InvalidPropFail : SR.RFLCT_InvalidFieldFail, name), e); } } if (blobStart != blobEnd) { throw new CustomAttributeFormatException(); } attributes.Add(attribute); } GC.KeepAlive(decoratedModule); } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "Module.ResolveMethod and Module.ResolveType are marked as RequiresUnreferencedCode because they rely on tokens" + "which are not guaranteed to be stable across trimming. So if somebody hardcodes a token it could break." + "The usage here is not like that as all these tokens come from existing metadata loaded from some IL" + "and so trimming has no effect (the tokens are read AFTER trimming occurred).")] private static bool FilterCustomAttributeRecord( MetadataToken caCtorToken, in MetadataImport scope, RuntimeModule decoratedModule, MetadataToken decoratedToken, RuntimeType attributeFilterType, bool mustBeInheritable, ref RuntimeType.ListBuilder<object> derivedAttributes, out RuntimeType attributeType, out IRuntimeMethodInfo? ctorWithParameters, out bool isVarArg) { ctorWithParameters = null; isVarArg = false; // Resolve attribute type from ctor parent token found in decorated decoratedModule scope attributeType = (decoratedModule.ResolveType(scope.GetParentToken(caCtorToken), null, null) as RuntimeType)!; // Test attribute type against user provided attribute type filter if (!MatchesTypeFilter(attributeType, attributeFilterType)) return false; // Ensure if attribute type must be inheritable that it is inheritable // Ensure that to consider a duplicate attribute type AllowMultiple is true if (!AttributeUsageCheck(attributeType, mustBeInheritable, ref derivedAttributes)) return false; // Resolve the attribute ctor ConstArray ctorSig = scope.GetMethodSignature(caCtorToken); isVarArg = (ctorSig[0] & 0x05) != 0; bool ctorHasParameters = ctorSig[1] != 0; if (ctorHasParameters) { // Resolve method ctor token found in decorated decoratedModule scope // See https://github.com/dotnet/runtime/issues/11637 for why we fast-path non-generics here (fewer allocations) if (attributeType.IsGenericType) { ctorWithParameters = decoratedModule.ResolveMethod(caCtorToken, attributeType.GenericTypeArguments, null)!.MethodHandle.GetMethodInfo(); } else { ctorWithParameters = new ModuleHandle(decoratedModule).ResolveMethodHandle(caCtorToken).GetMethodInfo(); } } // Visibility checks MetadataToken tkParent = default; if (decoratedToken.IsParamDef) { tkParent = new MetadataToken(scope.GetParentToken(decoratedToken)); tkParent = new MetadataToken(scope.GetParentToken(tkParent)); } else if (decoratedToken.IsMethodDef || decoratedToken.IsProperty || decoratedToken.IsEvent || decoratedToken.IsFieldDef) { tkParent = new MetadataToken(scope.GetParentToken(decoratedToken)); } else if (decoratedToken.IsTypeDef) { tkParent = decoratedToken; } else if (decoratedToken.IsGenericPar) { tkParent = new MetadataToken(scope.GetParentToken(decoratedToken)); // decoratedToken is a generic parameter on a method. Get the declaring Type of the method. if (tkParent.IsMethodDef) tkParent = new MetadataToken(scope.GetParentToken(tkParent)); } else { // We need to relax this when we add support for other types of decorated tokens. Debug.Assert(decoratedToken.IsModule || decoratedToken.IsAssembly, "The decoratedToken must be either an assembly, a module, a type, or a member."); } // If the attribute is on a type, member, or parameter we check access against the (declaring) type, // otherwise we check access against the module. RuntimeTypeHandle parentTypeHandle = tkParent.IsTypeDef ? decoratedModule.ModuleHandle.ResolveTypeHandle(tkParent) : default; RuntimeTypeHandle attributeTypeHandle = attributeType.TypeHandle; bool result = RuntimeMethodHandle.IsCAVisibleFromDecoratedType(new QCallTypeHandle(ref attributeTypeHandle), ctorWithParameters is not null ? ctorWithParameters.Value : RuntimeMethodHandleInternal.EmptyHandle, new QCallTypeHandle(ref parentTypeHandle), new QCallModule(ref decoratedModule)) != Interop.BOOL.FALSE; GC.KeepAlive(ctorWithParameters); return result; } private static bool MatchesTypeFilter(RuntimeType attributeType, RuntimeType attributeFilterType) { if (attributeFilterType.IsGenericTypeDefinition) { for (RuntimeType? type = attributeType; type != null; type = (RuntimeType?)type.BaseType) { if (type.IsConstructedGenericType && type.GetGenericTypeDefinition() == attributeFilterType) { return true; } } return false; } return attributeFilterType.IsAssignableFrom(attributeType); } #endregion #region Private Static Methods private static bool AttributeUsageCheck( RuntimeType attributeType, bool mustBeInheritable, ref RuntimeType.ListBuilder<object> derivedAttributes) { AttributeUsageAttribute? attributeUsageAttribute = null; if (mustBeInheritable) { attributeUsageAttribute = GetAttributeUsage(attributeType); if (!attributeUsageAttribute.Inherited) return false; } // Legacy: AllowMultiple ignored for none inheritable attributes if (derivedAttributes.Count == 0) return true; for (int i = 0; i < derivedAttributes.Count; i++) { if (derivedAttributes[i].GetType() == attributeType) { attributeUsageAttribute ??= GetAttributeUsage(attributeType); return attributeUsageAttribute.AllowMultiple; } } return true; } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "Module.ResolveType is marked as RequiresUnreferencedCode because it relies on tokens" + "which are not guaranteed to be stable across trimming. So if somebody hardcodes a token it could break." + "The usage here is not like that as all these tokens come from existing metadata loaded from some IL" + "and so trimming has no effect (the tokens are read AFTER trimming occurred).")] internal static AttributeUsageAttribute GetAttributeUsage(RuntimeType decoratedAttribute) { RuntimeModule decoratedModule = decoratedAttribute.GetRuntimeModule(); MetadataImport scope = decoratedModule.MetadataImport; CustomAttributeRecord[] car = RuntimeCustomAttributeData.GetCustomAttributeRecords(decoratedModule, decoratedAttribute.MetadataToken); AttributeUsageAttribute? attributeUsageAttribute = null; for (int i = 0; i < car.Length; i++) { ref CustomAttributeRecord caRecord = ref car[i]; RuntimeType? attributeType = decoratedModule.ResolveType(scope.GetParentToken(caRecord.tkCtor), null, null) as RuntimeType; if (attributeType != (RuntimeType)typeof(AttributeUsageAttribute)) continue; if (attributeUsageAttribute is not null) throw new FormatException(SR.Format(SR.Format_AttributeUsage, attributeType)); if (!ParseAttributeUsageAttribute( caRecord.blob, out AttributeTargets attrTargets, out bool allowMultiple, out bool inherited)) { throw new CustomAttributeFormatException(); } attributeUsageAttribute = new AttributeUsageAttribute(attrTargets, allowMultiple: allowMultiple, inherited: inherited); } return attributeUsageAttribute ?? AttributeUsageAttribute.Default; } internal static object[] CreateAttributeArrayHelper(RuntimeType caType, int elementCount) { bool useAttributeArray = false; bool useObjectArray = false; if (caType == typeof(Attribute)) { useAttributeArray = true; } else if (caType.IsActualValueType) { useObjectArray = true; } else if (caType.ContainsGenericParameters) { if (caType.IsSubclassOf(typeof(Attribute))) { useAttributeArray = true; } else { useObjectArray = true; } } if (useAttributeArray) { return elementCount == 0 ? Array.Empty<Attribute>() : new Attribute[elementCount]; } if (useObjectArray) { return elementCount == 0 ? Array.Empty<object>() : new object[elementCount]; } return elementCount == 0 ? caType.GetEmptyArray() : (object[])Array.CreateInstance(caType, elementCount); } #endregion [LibraryImport(RuntimeHelpers.QCall, EntryPoint = "CustomAttribute_ParseAttributeUsageAttribute")] [SuppressGCTransition] private static partial int ParseAttributeUsageAttribute( IntPtr pData, int cData, int* pTargets, int* pAllowMultiple, int* pInherited); private static bool ParseAttributeUsageAttribute( ConstArray blob, out AttributeTargets attrTargets, out bool allowMultiple, out bool inherited) { int attrTargetsLocal = 0; int allowMultipleLocal = 0; int inheritedLocal = 0; int result = ParseAttributeUsageAttribute(blob.Signature, blob.Length, &attrTargetsLocal, &allowMultipleLocal, &inheritedLocal); attrTargets = (AttributeTargets)attrTargetsLocal; allowMultiple = allowMultipleLocal != 0; inherited = inheritedLocal != 0; return result != 0; } [LibraryImport(RuntimeHelpers.QCall, EntryPoint = "CustomAttribute_CreateCustomAttributeInstance")] private static partial void CreateCustomAttributeInstance( QCallModule pModule, ObjectHandleOnStack type, ObjectHandleOnStack pCtor, ref IntPtr ppBlob, IntPtr pEndBlob, out int pcNamedArgs, ObjectHandleOnStack instance); private static object CreateCustomAttributeInstance(RuntimeModule module, RuntimeType type, IRuntimeMethodInfo ctor, ref IntPtr blob, IntPtr blobEnd, out int namedArgs) { if (module is null) { throw new ArgumentNullException(null, SR.Arg_InvalidHandle); } object? result = null; CreateCustomAttributeInstance( new QCallModule(ref module), ObjectHandleOnStack.Create(ref type), ObjectHandleOnStack.Create(ref ctor), ref blob, blobEnd, out namedArgs, ObjectHandleOnStack.Create(ref result)); return result!; } [LibraryImport(RuntimeHelpers.QCall, EntryPoint = "CustomAttribute_CreatePropertyOrFieldData", StringMarshalling = StringMarshalling.Utf16)] private static partial void CreatePropertyOrFieldData( QCallModule pModule, ref IntPtr ppBlobStart, IntPtr pBlobEnd, StringHandleOnStack name, [MarshalAs(UnmanagedType.Bool)] out bool bIsProperty, ObjectHandleOnStack type, ObjectHandleOnStack value); private static void GetPropertyOrFieldData( RuntimeModule module, ref IntPtr blobStart, IntPtr blobEnd, out string name, out bool isProperty, out RuntimeType? type, out object? value) { if (module is null) { throw new ArgumentNullException(null, SR.Arg_InvalidHandle); } string? nameLocal = null; RuntimeType? typeLocal = null; object? valueLocal = null; CreatePropertyOrFieldData( new QCallModule(ref module), ref blobStart, blobEnd, new StringHandleOnStack(ref nameLocal), out isProperty, ObjectHandleOnStack.Create(ref typeLocal), ObjectHandleOnStack.Create(ref valueLocal)); name = nameLocal!; type = typeLocal; value = valueLocal; } } internal static class PseudoCustomAttribute { #region Private Static Data Members // Here we can avoid the need to take a lock when using Dictionary by rearranging // the only method that adds values to the Dictionary. For more details on // Dictionary versus Hashtable thread safety: // See code:Dictionary#DictionaryVersusHashtableThreadSafety private static readonly HashSet<RuntimeType> s_pca = CreatePseudoCustomAttributeHashSet(); #endregion #region Static Constructor private static HashSet<RuntimeType> CreatePseudoCustomAttributeHashSet() { Type[] pcas = [ // See https://github.com/dotnet/runtime/blob/main/src/coreclr/md/compiler/custattr_emit.cpp typeof(FieldOffsetAttribute), // field typeof(SerializableAttribute), // class, struct, enum, delegate typeof(MarshalAsAttribute), // parameter, field, return-value typeof(ComImportAttribute), // class, interface typeof(NonSerializedAttribute), // field, inherited typeof(InAttribute), // parameter typeof(OutAttribute), // parameter typeof(OptionalAttribute), // parameter typeof(DllImportAttribute), // method typeof(PreserveSigAttribute), // method typeof(TypeForwardedToAttribute), // assembly ]; HashSet<RuntimeType> set = new HashSet<RuntimeType>(pcas.Length); foreach (RuntimeType runtimeType in pcas) { VerifyPseudoCustomAttribute(runtimeType); set.Add(runtimeType); } return set; } [Conditional("DEBUG")] private static void VerifyPseudoCustomAttribute(RuntimeType pca) { // If any of these are invariants are no longer true will have to // re-architect the PCA product logic and test cases. Debug.Assert(pca.BaseType == typeof(Attribute), "Pseudo CA Error - Incorrect base type"); AttributeUsageAttribute usage = CustomAttribute.GetAttributeUsage(pca); Debug.Assert(!usage.Inherited, "Pseudo CA Error - Unexpected Inherited value"); if (pca == typeof(TypeForwardedToAttribute)) { Debug.Assert(usage.AllowMultiple, "Pseudo CA Error - Unexpected AllowMultiple value"); } else { Debug.Assert(!usage.AllowMultiple, "Pseudo CA Error - Unexpected AllowMultiple value"); } } #endregion #region Internal Static internal static void GetCustomAttributes(RuntimeType type, RuntimeType caType, ref RuntimeType.ListBuilder<Attribute> pcas) { Debug.Assert(type is not null); Debug.Assert(caType is not null); bool all = caType == typeof(object) || caType == typeof(Attribute); if (!all && !s_pca.Contains(caType)) return; #pragma warning disable SYSLIB0050 // Legacy serialization infrastructure is obsolete if (all || caType == typeof(SerializableAttribute)) { if ((type.Attributes & TypeAttributes.Serializable) != 0) pcas.Add(new SerializableAttribute()); } #pragma warning restore SYSLIB0050 if (all || caType == typeof(ComImportAttribute)) { if ((type.Attributes & TypeAttributes.Import) != 0) pcas.Add(new ComImportAttribute()); } } internal static bool IsDefined(RuntimeType type, RuntimeType? caType) { bool all = caType == typeof(object) || caType == typeof(Attribute); if (!all && !s_pca.Contains(caType!)) return false; #pragma warning disable SYSLIB0050 // Legacy serialization infrastructure is obsolete if (all || caType == typeof(SerializableAttribute)) { if ((type.Attributes & TypeAttributes.Serializable) != 0) return true; } #pragma warning restore SYSLIB0050 if (all || caType == typeof(ComImportAttribute)) { if ((type.Attributes & TypeAttributes.Import) != 0) return true; } return false; } internal static void GetCustomAttributes(RuntimeMethodInfo method, RuntimeType caType, ref RuntimeType.ListBuilder<Attribute> pcas) { Debug.Assert(method is not null); Debug.Assert(caType is not null); bool all = caType == typeof(object) || caType == typeof(Attribute); if (!all && !s_pca.Contains(caType)) return; if (all || caType == typeof(DllImportAttribute)) { Attribute? pca = GetDllImportCustomAttribute(method); if (pca is not null) pcas.Add(pca); } if (all || caType == typeof(PreserveSigAttribute)) { if ((method.GetMethodImplementationFlags() & MethodImplAttributes.PreserveSig) != 0) pcas.Add(new PreserveSigAttribute()); } } internal static bool IsDefined(RuntimeMethodInfo method, RuntimeType? caType) { bool all = caType == typeof(object) || caType == typeof(Attribute); if (!all && !s_pca.Contains(caType!)) return false; if (all || caType == typeof(DllImportAttribute)) { if ((method.Attributes & MethodAttributes.PinvokeImpl) != 0) return true; } if (all || caType == typeof(PreserveSigAttribute)) { if ((method.GetMethodImplementationFlags() & MethodImplAttributes.PreserveSig) != 0) return true; } return false; } internal static void GetCustomAttributes(RuntimeParameterInfo parameter, RuntimeType caType, ref RuntimeType.ListBuilder<Attribute> pcas) { Debug.Assert(parameter is not null); Debug.Assert(caType is not null); bool all = caType == typeof(object) || caType == typeof(Attribute); if (!all && !s_pca.Contains(caType)) return; if (all || caType == typeof(InAttribute)) { if (parameter.IsIn) pcas.Add(new InAttribute()); } if (all || caType == typeof(OutAttribute)) { if (parameter.IsOut) pcas.Add(new OutAttribute()); } if (all || caType == typeof(OptionalAttribute)) { if (parameter.IsOptional) pcas.Add(new OptionalAttribute()); } if (all || caType == typeof(MarshalAsAttribute)) { Attribute? pca = GetMarshalAsCustomAttribute(parameter); if (pca is not null) pcas.Add(pca); } } internal static bool IsDefined(RuntimeParameterInfo parameter, RuntimeType? caType) { bool all = caType == typeof(object) || caType == typeof(Attribute); if (!all && !s_pca.Contains(caType!)) return false; if (all || caType == typeof(InAttribute)) { if (parameter.IsIn) return true; } if (all || caType == typeof(OutAttribute)) { if (parameter.IsOut) return true; } if (all || caType == typeof(OptionalAttribute)) { if (parameter.IsOptional) return true; } if (all || caType == typeof(MarshalAsAttribute)) { if (GetMarshalAsCustomAttribute(parameter) is not null) return true; } return false; } internal static void GetCustomAttributes(RuntimeFieldInfo field, RuntimeType caType, ref RuntimeType.ListBuilder<Attribute> pcas) { Debug.Assert(field is not null); Debug.Assert(caType is not null); bool all = caType == typeof(object) || caType == typeof(Attribute); if (!all && !s_pca.Contains(caType)) return; Attribute? pca; if (all || caType == typeof(MarshalAsAttribute)) { pca = GetMarshalAsCustomAttribute(field); if (pca is not null) pcas.Add(pca); } if (all || caType == typeof(FieldOffsetAttribute)) { pca = GetFieldOffsetCustomAttribute(field); if (pca is not null) pcas.Add(pca); } #pragma warning disable SYSLIB0050 // Legacy serialization infrastructure is obsolete if (all || caType == typeof(NonSerializedAttribute)) { if ((field.Attributes & FieldAttributes.NotSerialized) != 0) pcas.Add(new NonSerializedAttribute()); } #pragma warning restore SYSLIB0050 } internal static bool IsDefined(RuntimeFieldInfo field, RuntimeType? caType) { bool all = caType == typeof(object) || caType == typeof(Attribute); if (!all && !s_pca.Contains(caType!)) return false; if (all || caType == typeof(MarshalAsAttribute)) { if (GetMarshalAsCustomAttribute(field) is not null) return true; } if (all || caType == typeof(FieldOffsetAttribute)) { if (GetFieldOffsetCustomAttribute(field) is not null) return true; } #pragma warning disable SYSLIB0050 // Legacy serialization infrastructure is obsolete if (all || caType == typeof(NonSerializedAttribute)) { if ((field.Attributes & FieldAttributes.NotSerialized) != 0) return true; } #pragma warning restore SYSLIB0050 return false; } #endregion private static DllImportAttribute? GetDllImportCustomAttribute(RuntimeMethodInfo method) { if ((method.Attributes & MethodAttributes.PinvokeImpl) == 0) return null; RuntimeModule module = method.Module.ModuleHandle.GetRuntimeModule(); MetadataImport scope = module.MetadataImport; int token = method.MetadataToken; scope.GetPInvokeMap(token, out PInvokeAttributes flags, out string entryPoint, out string dllName); GC.KeepAlive(module); CharSet charSet = CharSet.None; switch (flags & PInvokeAttributes.CharSetMask) { case PInvokeAttributes.CharSetNotSpec: charSet = CharSet.None; break; case PInvokeAttributes.CharSetAnsi: charSet = CharSet.Ansi; break; case PInvokeAttributes.CharSetUnicode: charSet = CharSet.Unicode; break; case PInvokeAttributes.CharSetAuto: charSet = CharSet.Auto; break; // Invalid: default to CharSet.None default: break; } CallingConvention callingConvention = CallingConvention.Cdecl; switch (flags & PInvokeAttributes.CallConvMask) { case PInvokeAttributes.CallConvWinapi: callingConvention = CallingConvention.Winapi; break; case PInvokeAttributes.CallConvCdecl: callingConvention = CallingConvention.Cdecl; break; case PInvokeAttributes.CallConvStdcall: callingConvention = CallingConvention.StdCall; break; case PInvokeAttributes.CallConvThiscall: callingConvention = CallingConvention.ThisCall; break; case PInvokeAttributes.CallConvFastcall: callingConvention = CallingConvention.FastCall; break; // Invalid: default to CallingConvention.Cdecl default: break; } DllImportAttribute attribute = new DllImportAttribute(dllName); attribute.EntryPoint = entryPoint; attribute.CharSet = charSet; attribute.SetLastError = (flags & PInvokeAttributes.SupportsLastError) != 0; attribute.ExactSpelling = (flags & PInvokeAttributes.NoMangle) != 0; attribute.PreserveSig = (method.GetMethodImplementationFlags() & MethodImplAttributes.PreserveSig) != 0; attribute.CallingConvention = callingConvention; attribute.BestFitMapping = (flags & PInvokeAttributes.BestFitMask) == PInvokeAttributes.BestFitEnabled; attribute.ThrowOnUnmappableChar = (flags & PInvokeAttributes.ThrowOnUnmappableCharMask) == PInvokeAttributes.ThrowOnUnmappableCharEnabled; return attribute; } private static MarshalAsAttribute? GetMarshalAsCustomAttribute(RuntimeParameterInfo parameter) { return GetMarshalAsCustomAttribute(parameter.MetadataToken, parameter.GetRuntimeModule()!); } private static MarshalAsAttribute? GetMarshalAsCustomAttribute(RuntimeFieldInfo field) { return GetMarshalAsCustomAttribute(field.MetadataToken, field.GetRuntimeModule()); } private static MarshalAsAttribute? GetMarshalAsCustomAttribute(int token, RuntimeModule scope) { ConstArray nativeType = scope.MetadataImport.GetFieldMarshal(token); if (nativeType.Length == 0) return null; return MetadataImport.GetMarshalAs(nativeType, scope); } private static FieldOffsetAttribute? GetFieldOffsetCustomAttribute(RuntimeFieldInfo field) { if (field.DeclaringType is not null) { RuntimeModule module = field.GetRuntimeModule(); if (module.MetadataImport.GetFieldOffset(field.DeclaringType.MetadataToken, field.MetadataToken, out int fieldOffset)) { return new FieldOffsetAttribute(fieldOffset); } GC.KeepAlive(module); } return null; } internal static StructLayoutAttribute? GetStructLayoutCustomAttribute(RuntimeType type) { if (type.IsActualInterface || type.HasElementType || type.IsGenericParameter) return null; LayoutKind layoutKind = LayoutKind.Auto; switch (type.Attributes & TypeAttributes.LayoutMask) { case TypeAttributes.ExplicitLayout: layoutKind = LayoutKind.Explicit; break; case TypeAttributes.AutoLayout: layoutKind = LayoutKind.Auto; break; case TypeAttributes.SequentialLayout: layoutKind = LayoutKind.Sequential; break; case TypeAttributes.ExtendedLayout: layoutKind = LayoutKind.Extended; break; default: Debug.Fail("Unreachable code"); break; } CharSet charSet = CharSet.None; switch (type.Attributes & TypeAttributes.StringFormatMask) { case TypeAttributes.AnsiClass: charSet = CharSet.Ansi; break; case TypeAttributes.AutoClass: charSet = CharSet.Auto; break; case TypeAttributes.UnicodeClass: charSet = CharSet.Unicode; break; default: Debug.Fail("Unreachable code"); break; } RuntimeModule module = type.GetRuntimeModule(); module.MetadataImport.GetClassLayout(type.MetadataToken, out int pack, out int size); GC.KeepAlive(module); StructLayoutAttribute attribute = new StructLayoutAttribute(layoutKind); attribute.Pack = pack; attribute.Size = size; attribute.CharSet = charSet; return attribute; } } }
412
0.820852
1
0.820852
game-dev
MEDIA
0.459407
game-dev
0.898643
1
0.898643
FPSMasterTeam/FPSMaster
13,143
shared/java/top/fpsmaster/ui/mc/GuiMultiplayer.java
package top.fpsmaster.ui.mc; import com.google.common.collect.Lists; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import net.minecraft.client.gui.GuiScreenAddServer; import net.minecraft.client.gui.GuiScreenServerList; import net.minecraft.client.gui.GuiYesNo; import net.minecraft.client.multiplayer.ServerData; import net.minecraft.client.network.OldServerPinger; import net.minecraft.client.resources.I18n; import net.minecraft.nbt.CompressedStreamTools; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraftforge.fml.client.FMLClientHandler; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.lwjgl.opengl.GL11; import top.fpsmaster.FPSMaster; import top.fpsmaster.font.impl.UFontRenderer; import top.fpsmaster.modules.client.thread.ClientThreadPool; import top.fpsmaster.ui.click.component.ScrollContainer; import top.fpsmaster.ui.common.GuiButton; import top.fpsmaster.ui.screens.mainmenu.MainMenu; import top.fpsmaster.utils.math.MathTimer; import top.fpsmaster.utils.os.HttpRequest; import top.fpsmaster.utils.render.Render2DUtils; import top.fpsmaster.utils.render.ScaledGuiScreen; import java.awt.*; import java.io.File; import java.io.IOException; import java.util.List; public class GuiMultiplayer extends ScaledGuiScreen { private ServerData selectedServer; private static final Logger logger = LogManager.getLogger(); private final List<ServerData> servers = Lists.newArrayList(); private final List<ServerListEntry> serverListDisplay = Lists.newArrayList(); private final List<ServerListEntry> serverListInternet = Lists.newArrayList(); private static final List<ServerListEntry> serverListRecommended = Lists.newArrayList(); public final OldServerPinger oldServerPinger = new OldServerPinger(); private final Gson gson = new GsonBuilder().setPrettyPrinting().create(); String action = ""; MathTimer timer = new MathTimer(); GuiButton join = new GuiButton("加入服务器", () -> { if (selectedServer == null) return; FMLClientHandler.instance().connectToServer(this, selectedServer); }, new Color(0, 0, 0, 140), new Color(113, 127, 254)); GuiButton connect = new GuiButton("直接连接", () -> { this.mc.displayGuiScreen(new GuiScreenServerList(this, this.selectedServer = new ServerData(I18n.format("selectServer.defaultName"), "", false))); action = "connect"; }, new Color(0, 0, 0, 140), new Color(113, 127, 254)); GuiButton add = new GuiButton("添加服务器", () -> { action = "add"; this.mc.displayGuiScreen(new GuiScreenAddServer(this, this.selectedServer = new ServerData(I18n.format("selectServer.defaultName"), "", false))); }, new Color(0, 0, 0, 140), new Color(113, 127, 254)); GuiButton edit = new GuiButton("编辑", () -> { if (selectedServer == null) return; action = "edit"; mc.displayGuiScreen(new GuiScreenAddServer(this, selectedServer)); }, new Color(0, 0, 0, 140), new Color(113, 127, 254)); GuiButton remove = new GuiButton("删除", () -> { if (selectedServer == null) return; action = "remove"; String s4 = selectedServer.serverName; if (s4 != null) { String s = I18n.format("selectServer.deleteQuestion"); String s1 = "'" + s4 + "' " + I18n.format("selectServer.deleteWarning"); String s2 = I18n.format("selectServer.deleteButton"); String s3 = I18n.format("gui.cancel"); GuiYesNo guiyesno = new GuiYesNo(this, s, s1, s2, s3, servers.indexOf(selectedServer)); this.mc.displayGuiScreen(guiyesno); } }, new Color(0, 0, 0, 140), new Color(113, 127, 254)); GuiButton refresh = new GuiButton("刷新", () -> mc.displayGuiScreen(new GuiMultiplayer()), new Color(0, 0, 0, 140), new Color(113, 127, 254)); GuiButton back = new GuiButton("返回", () -> mc.displayGuiScreen(new MainMenu()), new Color(0, 0, 0, 140), new Color(113, 127, 254)); @Override public void initGui() { super.initGui(); tab = 0; loadServerList(); serverListInternet.clear(); for (ServerData server : servers) { this.serverListInternet.add(new ServerListEntry(this, server)); } serverListDisplay.clear(); serverListDisplay.addAll(serverListInternet); if (serverListRecommended.isEmpty()) { FPSMaster.async.runnable(() -> { String s; try { s = HttpRequest.get("https://service.fpsmaster.top/api/client/servers").getBody(); } catch (IOException e) { throw new RuntimeException(e); } JsonObject jsonObject = gson.fromJson(s, JsonObject.class); jsonObject.get("data").getAsJsonArray().forEach(e -> serverListRecommended.add(new ServerListEntry(this, new ServerData(e.getAsJsonObject().get("name").getAsString() + " - " + e.getAsJsonObject().get("description").getAsString(), e.getAsJsonObject().get("address").getAsString(), false)))); }); } } @Override public void confirmClicked(boolean result, int id) { super.confirmClicked(result, id); if (result) { switch (action) { case "add": servers.add(selectedServer); saveServerList(); selectedServer = null; break; case "edit": saveServerList(); break; case "remove": servers.remove(selectedServer); saveServerList(); break; case "connect": FMLClientHandler.instance().connectToServer(this, selectedServer); break; } action = ""; } mc.displayGuiScreen(this); } public void saveServerList() { try { NBTTagList nBTTagList = new NBTTagList(); for (ServerData serverData : this.servers) { nBTTagList.appendTag(serverData.getNBTCompound()); } NBTTagCompound nBTTagCompound = new NBTTagCompound(); nBTTagCompound.setTag("servers", nBTTagList); CompressedStreamTools.safeWrite(nBTTagCompound, new File(this.mc.mcDataDir, "servers.dat")); } catch (Exception exception) { logger.error("Couldn't save server list", exception); } } ScrollContainer scrollContainer = new ScrollContainer(); int tab = 0; @Override public void render(int mouseX, int mouseY, float partialTicks) { super.render(mouseX, mouseY, partialTicks); Render2DUtils.drawBackground((int) guiWidth, (int) guiHeight, mouseX, mouseY, partialTicks, (int) zLevel); UFontRenderer title = FPSMaster.fontManager.s22; UFontRenderer font = FPSMaster.fontManager.s18; title.drawCenteredString("多人游戏", guiWidth / 2f, 16, -1); Render2DUtils.drawOptimizedRoundedRect((guiWidth - 180) / 2f, 30, 180, 24, 3, new Color(0, 0, 0, 80).getRGB()); Render2DUtils.drawOptimizedRoundedRect((guiWidth - 176) / 2f + 90 * tab, 32, 86, 20, 3, -1); FPSMaster.fontManager.s16.drawCenteredString("服务器列表", (guiWidth - 90) / 2f, 36, tab == 0 ? new Color(50, 50, 50).getRGB() : -1); FPSMaster.fontManager.s16.drawCenteredString("推荐服务器", (guiWidth + 90) / 2f, 36, tab == 1 ? new Color(50, 50, 50).getRGB() : -1); GL11.glPushMatrix(); GL11.glEnable(GL11.GL_SCISSOR_TEST); Render2DUtils.doGlScissor((guiWidth - 400) / 2f, 60f, 400f, guiHeight - 120, scaleFactor); scrollContainer.draw((guiWidth - 400) / 2f, 60, 396, guiHeight - 120, mouseX, mouseY, () -> { float y = 70 + scrollContainer.getScroll(); Render2DUtils.drawOptimizedRoundedRect((guiWidth - 400) / 2f, y - 10, 400, guiHeight - y, 5, new Color(0, 0, 0, 100).getRGB()); for (ServerListEntry server : serverListDisplay) { if (server.getServerData() == null) { return; } Render2DUtils.drawOptimizedRoundedRect((guiWidth - 340) / 2f, y, 340, 54, new Color(0, 0, 0, 120)); if (Render2DUtils.isHovered((guiWidth - 340) / 2f, y, 340, 54, mouseX, mouseY)) { Render2DUtils.drawOptimizedRoundedRect((guiWidth - 340) / 2f, y, 340, 54, new Color(0, 0, 0, 50)); } if (selectedServer != null && selectedServer == server.getServerData()) { Render2DUtils.drawOptimizedRoundedRect((guiWidth - 340) / 2f, y, 340, 54, new Color(255, 255, 255, 50)); } server.drawEntry(0, (int) ((guiWidth - 340) / 2), (int) y, 340, 54, mouseX, mouseY, false); y += 58; } scrollContainer.setHeight(y - 50 - scrollContainer.getScroll()); }); GL11.glDisable(GL11.GL_SCISSOR_TEST); GL11.glPopMatrix(); join.render((guiWidth - 400) / 2f + 20, guiHeight - 56, 380f / 3 - 20, 20, mouseX, mouseY); connect.render((guiWidth - 400) / 2f + 20 + 380f / 3, guiHeight - 56, 380f / 3 - 20, 20, mouseX, mouseY); add.render((guiWidth - 400) / 2f + 20 + 380f / 3 * 2, guiHeight - 56, 380f / 3 - 20, 20, mouseX, mouseY); edit.render((guiWidth - 400) / 2f + 20, guiHeight - 26, 380f / 4 - 20, 20, mouseX, mouseY); remove.render((guiWidth - 400) / 2f + 20 + 380f / 4, guiHeight - 26, 380f / 4 - 20, 20, mouseX, mouseY); refresh.render((guiWidth - 400) / 2f + 20 + 380f / 4 * 2, guiHeight - 26, 380f / 4 - 20, 20, mouseX, mouseY); back.render((guiWidth - 400) / 2f + 20 + 380f / 4 * 3, guiHeight - 26, 380f / 4 - 20, 20, mouseX, mouseY); } @Override public void updateScreen() { super.updateScreen(); FMLClientHandler.instance().setupServerList(); this.oldServerPinger.pingPendingNetworks(); } @Override public void onGuiClosed() { super.onGuiClosed(); this.oldServerPinger.clearPendingNetworks(); } @Override public void onClick(int mouseX, int mouseY, int mouseButton) { super.onClick(mouseX, mouseY, mouseButton); join.mouseClick(mouseX, mouseY, mouseButton); connect.mouseClick(mouseX, mouseY, mouseButton); add.mouseClick(mouseX, mouseY, mouseButton); edit.mouseClick(mouseX, mouseY, mouseButton); remove.mouseClick(mouseX, mouseY, mouseButton); refresh.mouseClick(mouseX, mouseY, mouseButton); back.mouseClick(mouseX, mouseY, mouseButton); Render2DUtils.drawOptimizedRoundedRect((guiWidth - 180) / 2f, 30, 180, 24, 3, new Color(255, 255, 255, 80).getRGB()); Render2DUtils.drawOptimizedRoundedRect((guiWidth - 176) / 2f, 32, 86, 20, 3, new Color(113, 127, 254).getRGB()); FPSMaster.fontManager.s16.drawCenteredString("服务器列表", (guiWidth - 90) / 2f, 36, -1); FPSMaster.fontManager.s16.drawCenteredString("推荐服务器", (guiWidth + 90) / 2f, 36, -1); if (Render2DUtils.isHovered((guiWidth - 180) / 2f, 30, 90, 24, mouseX, mouseY)) { tab = 0; serverListDisplay.clear(); serverListDisplay.addAll(serverListInternet); } else if (Render2DUtils.isHovered((guiWidth) / 2f, 30, 90, 24, mouseX, mouseY)) { tab = 1; serverListDisplay.clear(); serverListDisplay.addAll(serverListRecommended); } float y = 70 + scrollContainer.getScroll(); for (ServerListEntry server : serverListDisplay) { if (server.getServerData() == null) { return; } if (Render2DUtils.isHovered((guiWidth - 340) / 2f, y, 340, 54, mouseX, mouseY)) { if (selectedServer != server.getServerData()) { selectedServer = server.getServerData(); timer.reset(); } else { if (timer.delay(200)) { selectedServer = null; } else { FMLClientHandler.instance().connectToServer(this, selectedServer); } } } y += 58; } } public void loadServerList() { try { this.servers.clear(); NBTTagCompound nBTTagCompound = CompressedStreamTools.read(new File(this.mc.mcDataDir, "servers.dat")); if (nBTTagCompound == null) { return; } NBTTagList nBTTagList = nBTTagCompound.getTagList("servers", 10); for (int i = 0; i < nBTTagList.tagCount(); ++i) { this.servers.add(ServerData.getServerDataFromNBTCompound(nBTTagList.getCompoundTagAt(i))); } } catch (Exception exception) { logger.error("Couldn't load server list", exception); } } }
412
0.874721
1
0.874721
game-dev
MEDIA
0.471742
game-dev
0.957494
1
0.957494
Pugstorm/CoreKeeperModSDK
5,626
Packages/com.unity.entities/Unity.Entities.Editor/Inspector/Elements/ComponentElementBase.cs
using Unity.Entities.Editor.Inspectors; using Unity.Entities.UI; using Unity.Properties; using UnityEditor; using UnityEditor.UIElements; using UnityEngine.UIElements; namespace Unity.Entities.Editor { abstract class ComponentElementBase : BindableElement { public int TypeIndex { get; private set; } public ComponentPropertyType Type { get; private set; } [CreateProperty] public string Path { get; private set; } protected string DisplayName { get; private set; } protected EntityInspectorContext Context { get; private set; } protected EntityContainer Container { get; private set; } protected ComponentElementBase(IComponentProperty property, EntityInspectorContext context) { TypeIndex = property.TypeIndex; Type = property.Type; Path = property.Name; DisplayName = ComponentsUtility.GetComponentDisplayName(property.Name); Context = context; Container = Context.EntityContainer; } protected PropertyElement CreateContent<TValue>(IComponentProperty property, ref TValue value) { Resources.Templates.Inspector.InspectorStyle.AddStyles(this); InspectorUtility.CreateComponentHeader(this, property.Type, DisplayName); var foldout = this.Q<Foldout>(className: UssClasses.Inspector.Component.Header); foldout.Q<Toggle>().AddManipulator(new ContextualMenuManipulator(evt => { OnPopulateMenu(evt.menu); })); if (!Context.IsReadOnly) { if (Type == ComponentPropertyType.ChunkComponent) foldout.contentContainer.Add(new HelpBox("Chunk component data is shared between multiple entities", HelpBoxMessageType.Info)); if (Type == ComponentPropertyType.SharedComponent) foldout.contentContainer.Add(new HelpBox("Changing shared values will move entities between chunks", HelpBoxMessageType.Info)); } var content = new PropertyElement(); // We set user data to this root PropertyElement to indicate this is a live property displaying runtime data. // So that we can draw this property field with runtime bar being added. if (EditorApplication.isPlaying) content.userData = content; foldout.contentContainer.Add(content); content.AddContext(Context); content.SetTarget(value); content.OnChanged += OnComponentChanged; foldout.contentContainer.AddToClassList(UssClasses.Inspector.Component.Container); var container = Container; if (container.IsReadOnly) { SetReadonly(foldout); foldout.RegisterCallback<ClickEvent, EntityInspectorContext>(OnClicked, Context, TrickleDown.TrickleDown); } return content; } protected virtual void SetReadonly(VisualElement root) { root.contentContainer.SetEnabled(false); root.Q<Toggle>(className: UssClasses.Inspector.Component.Enabled).SetEnabled(false); } protected abstract void OnComponentChanged(BindingContextElement element, PropertyPath path); protected abstract void OnPopulateMenu(DropdownMenu menu); static void OnClicked(ClickEvent evt, EntityInspectorContext context) { var element = (VisualElement)evt.currentTarget; OnClicked(evt, context, element); } static void OnClicked(ClickEvent evt, EntityInspectorContext context, VisualElement current) { switch (current) { case Foldout foldout: if (foldout.enabledInHierarchy || !foldout.Q<Toggle>().worldBound.Contains(evt.position)) break; foldout.value = !foldout.value; break; case ObjectField objectField: var display = objectField.Q(className: UssClasses.UIToolkit.ObjectField.Display); if (null == display) break; if (!display.worldBound.Contains(evt.position)) break; if (evt.clickCount == 1) EditorGUIUtility.PingObject(objectField.value); else { var value = objectField.value; if (null != value && value) Selection.activeObject = value; } break; case EntityField entityField: var input = entityField.Q(className: "unity-entity-field__input"); if (null == input) break; if (!input.worldBound.Contains(evt.position)) break; if (evt.clickCount > 1) { var world = context.World; if (null == world || !world.IsCreated) break; if (!context.EntityManager.SafeExists(entityField.value)) break; EntitySelectionProxy.SelectEntity(context.World, entityField.value); } break; } for (var i = 0; i < current.childCount; ++i) { OnClicked(evt, context, current[i]); } } } }
412
0.910781
1
0.910781
game-dev
MEDIA
0.656211
game-dev
0.962393
1
0.962393
TTT-2/TTT2
1,061
lua/terrortown/entities/items/item_ttt_noenergydmg.lua
if SERVER then AddCSLuaFile() end ITEM.EquipMenuData = { type = "item_passive", name = "item_no_energy_damage", desc = "item_no_energy_damage_desc", } ITEM.CanBuy = { ROLE_TRAITOR, ROLE_DETECTIVE } ITEM.hud = Material("vgui/ttt/perks/hud_noenergydmg.png") ITEM.material = "vgui/ttt/icon_noenergydmg" ITEM.builtin = true if SERVER then hook.Add("EntityTakeDamage", "TTT2NoEnergyDmg", function(target, dmginfo) if not IsValid(target) or not target:IsPlayer() or not ( dmginfo:IsDamageType(DMG_SHOCK) or dmginfo:IsDamageType(DMG_SONIC) or dmginfo:IsDamageType(DMG_ENERGYBEAM) or dmginfo:IsDamageType(DMG_PHYSGUN) or dmginfo:IsDamageType(DMG_PLASMA) ) then return end if target:Alive() and target:IsTerror() and target:HasEquipmentItem("item_ttt_noenergydmg") then dmginfo:ScaleDamage(0) end end) end
412
0.859617
1
0.859617
game-dev
MEDIA
0.674056
game-dev,desktop-app
0.732861
1
0.732861
Ilya3point999K/ThaumicConcilium
6,628
src/main/java/com/ilya3point999k/thaumicconcilium/common/blocks/QuicksilverCrucibleBlock.java
package com.ilya3point999k.thaumicconcilium.common.blocks; import com.ilya3point999k.thaumicconcilium.common.ThaumicConcilium; import com.ilya3point999k.thaumicconcilium.common.registry.TCBlockRegistry; import com.ilya3point999k.thaumicconcilium.common.tiles.QuicksilverCrucibleTile; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.block.Block; import net.minecraft.block.BlockContainer; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.item.EntityItem; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.DamageSource; import net.minecraft.util.IIcon; import net.minecraft.util.MathHelper; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import thaumcraft.api.aspects.Aspect; import thaumcraft.common.entities.EntitySpecialItem; import java.util.List; import java.util.Random; public class QuicksilverCrucibleBlock extends BlockContainer { public IIcon[] icon = new IIcon[7]; private int delay = 0; public QuicksilverCrucibleBlock() { super(Material.iron); this.setHardness(3.0F); this.setResistance(17.0F); this.setStepSound(Block.soundTypeMetal); this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); this.setCreativeTab(ThaumicConcilium.tabTC); } @Override public void registerBlockIcons(IIconRegister ir) { for(int a = 0; a <= 5; ++a) { this.icon[a] = ir.registerIcon("thaumcraft:crucible" + (a + 1)); } this.icon[2] = ir.registerIcon(ThaumicConcilium.MODID+":quicksilver_crucible"); this.icon[6] = ir.registerIcon(ThaumicConcilium.MODID+":quicksilver"); } public IIcon getIcon(IBlockAccess iblockaccess, int i, int j, int k, int side) { if (side == 1) { return this.icon[0]; } else if (side == 0) { return this.icon[1]; } else { return this.icon[2]; } } @Override public IIcon getIcon(int side, int meta) { if (meta == 10){ return icon[6]; } return super.getIcon(side, meta); } @Override @SideOnly(Side.CLIENT) public void randomDisplayTick(World w, int i, int j, int k, Random r) { if (r.nextInt(10) == 0) { TileEntity te = w.getTileEntity(i, j, k); if (te instanceof QuicksilverCrucibleTile && ((QuicksilverCrucibleTile)te).aspects.getAmount(Aspect.EXCHANGE) > 0) { w.playSound((double)i, (double)j, (double)k, ThaumicConcilium.MODID + ":melted", 1.1F + r.nextFloat() * 0.1F, 1.2F + r.nextFloat() * 0.2F, false); } } } public void onEntityCollidedWithBlock(World world, int i, int j, int k, Entity entity) { if (!world.isRemote) { QuicksilverCrucibleTile tile = (QuicksilverCrucibleTile)world.getTileEntity(i, j, k); if (tile != null && entity instanceof EntityItem && !(entity instanceof EntitySpecialItem)) { tile.attemptSmelt((EntityItem)entity); } else { ++this.delay; if (this.delay < 10) { return; } this.delay = 0; if (entity instanceof EntityLivingBase && tile != null) { entity.attackEntityFrom(DamageSource.inFire, 1.0F); world.playSoundEffect((double)i, (double)j, (double)k, "random.fizz", 0.4F, 2.0F + world.rand.nextFloat() * 0.4F); } } } } public void addCollisionBoxesToList(World p_149743_1_, int p_149743_2_, int p_149743_3_, int p_149743_4_, AxisAlignedBB p_149743_5_, List p_149743_6_, Entity p_149743_7_) { this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.3125F, 1.0F); super.addCollisionBoxesToList(p_149743_1_, p_149743_2_, p_149743_3_, p_149743_4_, p_149743_5_, p_149743_6_, p_149743_7_); float f = 0.125F; this.setBlockBounds(0.0F, 0.0F, 0.0F, f, 1.0F, 1.0F); super.addCollisionBoxesToList(p_149743_1_, p_149743_2_, p_149743_3_, p_149743_4_, p_149743_5_, p_149743_6_, p_149743_7_); this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, f); super.addCollisionBoxesToList(p_149743_1_, p_149743_2_, p_149743_3_, p_149743_4_, p_149743_5_, p_149743_6_, p_149743_7_); this.setBlockBounds(1.0F - f, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); super.addCollisionBoxesToList(p_149743_1_, p_149743_2_, p_149743_3_, p_149743_4_, p_149743_5_, p_149743_6_, p_149743_7_); this.setBlockBounds(0.0F, 0.0F, 1.0F - f, 1.0F, 1.0F, 1.0F); super.addCollisionBoxesToList(p_149743_1_, p_149743_2_, p_149743_3_, p_149743_4_, p_149743_5_, p_149743_6_, p_149743_7_); this.setBlockBoundsForItemRender(); } public boolean hasComparatorInputOverride() { return true; } public int getComparatorInputOverride(World world, int x, int y, int z, int rs) { TileEntity te = world.getTileEntity(x, y, z); if (te != null && te instanceof QuicksilverCrucibleTile) { float var10000 = (float)((QuicksilverCrucibleTile)te).aspects.visSize(); ((QuicksilverCrucibleTile)te).getClass(); float r = var10000 / 100.0F; return MathHelper.floor_float(r * 14.0F) + (((QuicksilverCrucibleTile)te).aspects.visSize() > 0 ? 1 : 0); } return 0; } public void onNeighborBlockChange(World world, int x, int y, int z, Block nbid) { TileEntity te = world.getTileEntity(x, y, z); if (te != null && te instanceof QuicksilverCrucibleTile) { ((QuicksilverCrucibleTile)te).getBellows(); } super.onNeighborBlockChange(world, x, y, z, nbid); } public void setBlockBoundsForItemRender() { this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); } public boolean isOpaqueCube() { return false; } public boolean renderAsNormalBlock() { return false; } @Override public int getRenderType() { return TCBlockRegistry.quicksilverCrucibleID; } @Override public TileEntity createTileEntity(World world, int metadata) { return new QuicksilverCrucibleTile(); } @Override public TileEntity createNewTileEntity(World p_149915_1_, int p_149915_2_) { return null; } }
412
0.864285
1
0.864285
game-dev
MEDIA
0.984749
game-dev
0.968384
1
0.968384
CombatExtended-Continued/CombatExtended
19,771
Source/CombatExtended/CombatExtended/Loadouts/Loadout.cs
using System.Text.RegularExpressions; using System; using System.Collections.Generic; using System.Linq; using Verse; using RimWorld; namespace CombatExtended; /// <summary> /// Contains a series of LoadoutSlot slots which define what a pawn using this loadout should try to keep in their inventory. /// </summary> public class Loadout : IExposable, ILoadReferenceable, IComparable { #region Fields public bool canBeDeleted = true; public bool defaultLoadout = false; //NOTE: assumed that there is only ever one loadout which is marked default. public string label; internal int uniqueID; public bool dropUndefined = true; public bool adHoc = false; public int adHocMags = 4; public int adHocMass = 0; public int adHocBulk = 0; private int _parentID = 0; #nullable enable private Loadout? _parent = null; #nullable disable private List<LoadoutSlot> _slots = new List<LoadoutSlot>(); #endregion Fields #region Constructors public Loadout() { // this constructor is also used by the scribe, in which case defaults generated here will get overwritten. // create a unique default name. label = LoadoutManager.GetUniqueLabel(); // create a unique ID. uniqueID = LoadoutManager.GetUniqueLoadoutID(); } public Loadout(string label) { this.label = label; // create a unique ID. uniqueID = LoadoutManager.GetUniqueLoadoutID(); } /// <summary> /// CAUTION: This constructor allows setting the uniqueID and goes unchecked for collisions. /// </summary> /// <param name="label">string label of new Loadout, preferably unique but not required.</param> /// <param name="uniqueID">int ID of new Loadout. This should be unique to avoid bugs.</param> public Loadout(string label, int uniqueID) { this.label = label; this.uniqueID = uniqueID; } /// <summary> /// Handles adding any LoadoutGenercDef as LoadoutSlots if they are flagged as basic. /// </summary> public void AddBasicSlots() { IEnumerable<LoadoutGenericDef> defs = DefDatabase<LoadoutGenericDef>.AllDefs.Where(d => d.isBasic); foreach (LoadoutGenericDef def in defs) { LoadoutSlot slot = new LoadoutSlot(def); AddSlot(slot); } } #endregion Constructors #region Properties public int parentID { get { return _parentID; } set { _parent = null; _parentID = value; } } #nullable enable public Loadout? ParentLoadout { get { if (_parent == null && _parentID > 0) { var p = LoadoutManager.GetLoadoutById(parentID); if (p is Loadout) { if (p != this && (p._parent == null || (!p.Ancestors.Contains(this)))) { _parent = p; } else { _parentID = 0; } } } return _parent; } } public List<LoadoutSlot> OwnSlots { get { return _slots; } } public IEnumerable<Loadout> Ancestors { get { Loadout? parent = ParentLoadout; while (parent is Loadout) { yield return parent; parent = parent.ParentLoadout; } } } #nullable disable public IEnumerable<LoadoutSlot> ParentSlots { get { foreach (Loadout ancestor in Ancestors) { foreach (var slot in ancestor.OwnSlots) { yield return slot; } } } } //TODO 1.6: Turn this into an IEnumerable public List<LoadoutSlot> Slots { get { if (ParentLoadout is Loadout parent) { return _slots.Concat(ParentSlots).ToList(); } return _slots; } } public float Bulk { get { return Slots.Sum(slot => slot.bulk * slot.count); } } public string LabelCap { get { return label.CapitalizeFirst(); } } public int SlotCount { get { return _slots.Count; } } public float Weight { get { return Slots.Sum(slot => slot.mass * slot.count); } } public int UniqueID { get { return uniqueID; } } #endregion Properties #region Methods // Returns a copy of this loadout slot with a new unique ID and a label based on the original name. // LoadoutSlots need to be copied. /// <summary> /// Handles copying one Loadout to a new Loadout object. /// </summary> /// <param name="source">Loadout from which to copy properties/fields from.</param> /// <returns>new Loadout with copied properties from 'source'</returns> /// <remarks> /// uniqueID will be different as required. /// label will be different as required, but related to original. /// Slots are copied (not the same object) but have the same properties as source.Slots. /// </remarks> static Loadout Copy(Loadout source) { Loadout dest = new Loadout(UniqueLabel(source.label)); dest.defaultLoadout = source.defaultLoadout; dest.canBeDeleted = source.canBeDeleted; dest.dropUndefined = source.dropUndefined; dest.adHoc = source.adHoc; dest.adHocMags = source.adHocMags; dest.adHocMass = source.adHocMass; dest.adHocBulk = source.adHocBulk; dest.parentID = source.parentID; dest._slots = new List<LoadoutSlot>(); foreach (LoadoutSlot slot in source.OwnSlots) { dest.AddSlot(slot.Copy()); } return dest; } /// <summary> /// Translates the label into a unique label, adding an appropriate suffix if necessary /// </summary> /// <returns>New unique label</returns> static string UniqueLabel(string label) { Regex reNum = new Regex(@"^(.*?)\d+$"); if (reNum.IsMatch(label)) { label = reNum.Replace(label, @"$1"); } return LoadoutManager.GetUniqueLabel(label); } /// <summary> /// Copies self to a new Loadout. <see cref="Copy(Loadout)"/>. /// </summary> /// <returns>new Loadout with copied properties from self.</returns> public Loadout Copy() { return Copy(this); } /// <summary> /// Handles adding a new LoadoutSlot to self. If self already has the same slot (based on Def) then increment the already present slot.count. /// </summary> /// <param name="slot">LoadoutSlot to add to this Loadout.</param> public void AddSlot(LoadoutSlot slot) { LoadoutSlot old = _slots.FirstOrDefault(slot.isSameDef); if (old != null) { old.count += slot.count; } else { _slots.Add(slot); } } /// <summary> /// Factory method to create a Loadout object from a serializable LoadoutConfig loaded from a loadout save file /// </summary> /// <remarks> /// Note that the logic should be different to scribing data to/from a save file since /// additional validation related logic must exist and in some cases certain fields should not be serialized /// </remarks> /// <param name="loadoutConfig">The LoadoutConfig config object.</param> /// <returns>A Loadout object</returns> public static Loadout FromConfig(LoadoutConfig loadoutConfig, out List<string> unloadableDefNames) { // Create the new loadout, preventing name clashes if the loadout already exists string uniqueLabel = LoadoutManager.IsUniqueLabel(loadoutConfig.label) ? loadoutConfig.label : UniqueLabel(loadoutConfig.label); Loadout loadout = new Loadout(uniqueLabel); unloadableDefNames = new List<string>(); loadout.dropUndefined = loadoutConfig.dropUndefined; loadout.adHoc = loadoutConfig.adHoc; loadout.adHocMass = loadoutConfig.adHocMass; loadout.adHocMags = loadoutConfig.adHocMags; loadout.adHocBulk = loadoutConfig.adHocBulk; loadout.parentID = LoadoutManager.GetLoadoutByLabel(loadoutConfig.parentLabel)?.uniqueID ?? 0; // TODO: Display warning when there's a parent specified but we don't find it. // Now create each of the slots foreach (LoadoutSlotConfig loadoutSlotConfig in loadoutConfig.slots) { LoadoutSlot loadoutSlot = LoadoutSlot.FromConfig(loadoutSlotConfig); // If the LoadoutSlot could not be loaded then continue loading the others as this most likely means // that the current game does not have the mod loaded that was used to create the initial loadout. if (loadoutSlot == null) { unloadableDefNames.Add(loadoutSlotConfig.defName); continue; } loadout.AddSlot(LoadoutSlot.FromConfig(loadoutSlotConfig)); } return loadout; } /// <summary> /// Factory method to create a serializable LoadoutConfig object from this Loadout object /// </summary> /// <remarks> /// Note that the logic should be different to scribing data to/from a save file since /// additional validation related logic must exist and in some cases certain fields should not be serialized /// </remarks> /// <returns>A LoadoutConfig object that can be serialized to a loadout config file.</returns> public LoadoutConfig ToConfig() { List<LoadoutSlotConfig> loadoutSlotConfigList = new List<LoadoutSlotConfig>(); foreach (LoadoutSlot loadoutSlot in _slots) { loadoutSlotConfigList.Add(loadoutSlot.ToConfig()); } return new LoadoutConfig { label = label, slots = loadoutSlotConfigList.ToArray(), dropUndefined = dropUndefined, adHoc = adHoc, adHocMags = adHocMags, adHocBulk = adHocBulk, adHocMass = adHocMass, parentLabel = ParentLoadout?.label ?? String.Empty }; } /// <summary> /// Handles the save/load process as part of IExplosable. /// </summary> public void ExposeData() { // basic info about this loadout Scribe_Values.Look(ref label, "label"); Scribe_Values.Look(ref uniqueID, "uniqueID"); Scribe_Values.Look(ref canBeDeleted, "canBeDeleted", true); Scribe_Values.Look(ref defaultLoadout, "defaultLoadout", false); Scribe_Values.Look(ref dropUndefined, "dropUndefined", true); Scribe_Values.Look(ref adHoc, "adHoc", false); Scribe_Values.Look(ref _parentID, "parentID", 0); Scribe_Values.Look(ref adHocMags, "adHocMags", 3); Scribe_Values.Look(ref adHocMass, "adHocMass", 0); Scribe_Values.Look(ref adHocBulk, "adHocBulk", 0); _parent = null; // slots Scribe_Collections.Look(ref _slots, "slots", LookMode.Deep); if (Scribe.mode == LoadSaveMode.PostLoadInit) { _slots?.RemoveAll(slot => slot == null || (slot.thingDef == null && slot.genericDef == null)); } } public string GetUniqueLoadID() { return "Loadout_" + label + "_" + uniqueID; } /// <summary> /// Used to move a slot in this Loadout to a different position in the List. /// </summary> /// <param name="slot">LoadoutSlot being moved.</param> /// <param name="toIndex">int position (index) to move slot to.</param> public void MoveSlot(LoadoutSlot slot, int toIndex) { int fromIndex = _slots.IndexOf(slot); MoveTo(fromIndex, toIndex); } /// <summary> /// Used to remove a LoadoutSlot from this Loadout. /// </summary> /// <param name="slot">LoadoutSlot to remove.</param> public void RemoveSlot(LoadoutSlot slot) { _slots.Remove(slot); } /// <summary> /// Used to remove a LoadoutSlot by index from this Loadout. Usually used when moving slots around (ie drag and drop). /// </summary> /// <param name="index">int index of this Loadout's Slot List to remove.</param> public void RemoveSlot(int index) { _slots.RemoveAt(index); } /// <summary> /// Used to move one LoadoutSlot into a different position in this Loadout's List. Generally connected to drag and drop activities by user. /// </summary> /// <param name="fromIndex">int index (source) in List to move from.</param> /// <param name="toIndex">int index (target) in List to move to.</param> /// <returns></returns> private int MoveTo(int fromIndex, int toIndex) { if (fromIndex < 0 || fromIndex >= _slots.Count || toIndex < 0 || toIndex >= _slots.Count) { throw new Exception("Attempted to move i " + fromIndex + " to " + toIndex + ", bounds are [0," + (_slots.Count - 1) + "]."); } // fetch the filter we're moving LoadoutSlot temp = _slots[fromIndex]; // remove from old location _slots.RemoveAt(fromIndex); // this may have changed the toIndex if (fromIndex + 1 < toIndex) { toIndex--; } // insert at new location _slots.Insert(toIndex, temp); return toIndex; } /// <summary> /// Used to iterate over all slots, including virtual slots, for a specific pawn. /// In the trivial case, where this is not an ad-hoc loadout, we can simply yield from our slots /// </summary> /// <param name="pawn">The pawn to use when generating ad-hoc slots.</param> public IEnumerable<LoadoutSlot> GetSlotsFor(Pawn pawn) { bool weaponInLoadout = true; // assume all needed weapons are already in loadout bool ammoInLoadout = true; // assume all needed ammo is already in loadout int magSize = 1; HashSet<ThingDef> ammoTypes = new HashSet<ThingDef>(); if (adHoc && ((pawn.Faction?.IsPlayer ?? false) && pawn.equipment?.Primary is Thing primary)) { // ad-hoc, so don't assume the weapon is in the loadout CompAmmoUser primaryAmmoUser = primary.TryGetComp<CompAmmoUser>(); weaponInLoadout = false; if (primaryAmmoUser?.UseAmmo ?? false) { /// We are an ad-hoc loadout, with an ammo-using primary weapon /// So figure out what kind of ammo it needs, and check if that ammo is in our slots /// if it isn't, provide a virtual slot for it ammoInLoadout = false; magSize = primaryAmmoUser.Props.magazineSize; foreach (AmmoLink link in primaryAmmoUser.Props.ammoSet.ammoTypes) { ammoTypes.Add(link.ammo); } } } foreach (var slot in Slots) { yield return slot; if (!ammoInLoadout) { ammoInLoadout = ammoTypes.Contains(slot.thingDef); } if (!weaponInLoadout) { weaponInLoadout = pawn.equipment.Primary.def == slot.thingDef; } } if (!weaponInLoadout) { yield return new LoadoutSlot(pawn.equipment.Primary.def, 1); } if (!ammoInLoadout) { // Check if we have ammo in inventory, if so only ask for the same or more of that Dictionary<ThingDef, Integer> inventory = pawn.GetStorageByThingDef(); Dictionary<ThingDef, int> haveAmmo = new Dictionary<ThingDef, int>(); int totalAmmo = 0; foreach (ThingDef def in inventory.Keys) { if (ammoTypes.Contains(def)) { haveAmmo[def] = inventory[def].value; totalAmmo += inventory[def].value; } } if (totalAmmo > 0) { foreach (var ammo in haveAmmo.Keys) { int magLimit = adHocMags * magSize; if (adHocMass > 0) { magLimit = Math.Min(magLimit, (int)(adHocMass / ammo.GetStatValueAbstract(StatDefOf.Mass))); } if (adHocBulk > 0) { magLimit = Math.Min(magLimit, (int)(adHocBulk / ammo.GetStatValueAbstract(CE_StatDefOf.Bulk))); } magLimit -= (totalAmmo - haveAmmo[ammo]); // reduce mag limit by total of all other ammo types we already have int magCount = magLimit / magSize; int minMags = (int)(magCount * 0.75f); // works out to 3 out of 4 mags with default settings int minAmmo = minMags * magSize; if (magCount < 2) { minAmmo = magSize; } else if (minMags < 4) { minAmmo = (magCount - 1) * magSize; } if (haveAmmo[ammo] < minAmmo || haveAmmo[ammo] > magLimit) { yield return new LoadoutSlot(ammo, magLimit); } else { yield return new LoadoutSlot(ammo, haveAmmo[ammo]); } } } else { foreach (var ammo in ammoTypes) { int magLimit = adHocMags * magSize; if (adHocMass > 0) { magLimit = Math.Min(magLimit, (int)(adHocMass / ammo.GetStatValueAbstract(StatDefOf.Mass))); } if (adHocBulk > 0) { magLimit = Math.Min(magLimit, (int)(adHocBulk / ammo.GetStatValueAbstract(CE_StatDefOf.Bulk))); } yield return new LoadoutSlot(ammo, magLimit); } } } } #endregion Methods #region IComparable implementation /// <summary> /// Used when sorting lists of Loadouts. /// </summary> /// <param name="obj">other object to compare to.</param> /// <returns>int -1 indicating this is before obj, 0 indicates this is the same as obj, 1 indicates this is after obj.</returns> public int CompareTo(object obj) { Loadout other = obj as Loadout; if (other == null) { throw new ArgumentException("Loadout.CompareTo(obj), obj is not of type Loadout."); } // initial case, default comes first. Currently there aren't more than one default and should never be. if (this.defaultLoadout && other.defaultLoadout) { return 0; } if (this.defaultLoadout) { return -1; } if (other.defaultLoadout) { return 1; } // now we just compare by name of loadout... return this.label.CompareTo(other.label); } #endregion }
412
0.827306
1
0.827306
game-dev
MEDIA
0.689171
game-dev
0.901307
1
0.901307
openai/atari-py
3,952
atari_py/ale_interface/src/games/supported/Pitfall.cpp
/* ***************************************************************************** * The lines 62, 116, 124 and 132 are based on Xitari's code, from Google Inc. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version 2 * as published by the Free Software Foundation. * * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************** * A.L.E (Arcade Learning Environment) * Copyright (c) 2009-2013 by Yavar Naddaf, Joel Veness, Marc G. Bellemare and * the Reinforcement Learning and Artificial Intelligence Laboratory * Released under the GNU General Public License; see License.txt for details. * * Based on: Stella -- "An Atari 2600 VCS Emulator" * Copyright (c) 1995-2007 by Bradford W. Mott and the Stella team * * ***************************************************************************** */ #include "Pitfall.hpp" #include "../RomUtils.hpp" PitfallSettings::PitfallSettings() { reset(); } /* create a new instance of the rom */ RomSettings* PitfallSettings::clone() const { RomSettings* rval = new PitfallSettings(); *rval = *this; return rval; } /* process the latest information from ALE */ void PitfallSettings::step(const System& system) { // update the reward int score = getDecimalScore(0xD7, 0xD6, 0xD5, &system); int reward = score - m_score; m_reward = reward; m_score = score; // update terminal status int lives_byte = readRam(&system, 0x80) >> 4; // The value at 09xE will be nonzero if we cannot control the player int logo_timer = readRam(&system, 0x9E); m_terminal = lives_byte == 0 && logo_timer != 0; m_lives = (lives_byte == 0xA) ? 3 : ((lives_byte == 0x8) ? 2 : 1); } /* is end of game */ bool PitfallSettings::isTerminal() const { return m_terminal; }; /* get the most recently observed reward */ reward_t PitfallSettings::getReward() const { return m_reward; } /* is an action part of the minimal set? */ bool PitfallSettings::isMinimal(const Action &a) const { switch (a) { case PLAYER_A_NOOP: case PLAYER_A_FIRE: case PLAYER_A_UP: case PLAYER_A_RIGHT: case PLAYER_A_LEFT: case PLAYER_A_DOWN: case PLAYER_A_UPRIGHT: case PLAYER_A_UPLEFT: case PLAYER_A_DOWNRIGHT: case PLAYER_A_DOWNLEFT: case PLAYER_A_UPFIRE: case PLAYER_A_RIGHTFIRE: case PLAYER_A_LEFTFIRE: case PLAYER_A_DOWNFIRE: case PLAYER_A_UPRIGHTFIRE: case PLAYER_A_UPLEFTFIRE: case PLAYER_A_DOWNRIGHTFIRE: case PLAYER_A_DOWNLEFTFIRE: return true; default: return false; } } /* reset the state of the game */ void PitfallSettings::reset() { m_reward = 0; m_score = 2000; m_terminal = false; m_lives = 3; } /* saves the state of the rom settings */ void PitfallSettings::saveState(Serializer & ser) { ser.putInt(m_reward); ser.putInt(m_score); ser.putBool(m_terminal); ser.putInt(m_lives); } // loads the state of the rom settings void PitfallSettings::loadState(Deserializer & ser) { m_reward = ser.getInt(); m_score = ser.getInt(); m_terminal = ser.getBool(); m_lives = ser.getInt(); } ActionVect PitfallSettings::getStartingActions() { ActionVect startingActions; startingActions.push_back(PLAYER_A_UP); return startingActions; }
412
0.962058
1
0.962058
game-dev
MEDIA
0.79895
game-dev
0.90997
1
0.90997
Kelmatou/LeagueAPI
2,036
LeagueAPI/LeagueAPI/Models/RiotModels/ClashTeam.swift
// // ClashTeam.swift // LeagueAPI // // Created by Antoine Clop on 3/28/20. // Copyright © 2020 Antoine Clop. All rights reserved. // import Foundation public class ClashTeam: Decodable { public var teamId: TeamId public var tournamentId: TournamentId public var name: String public var iconId: ProfileIconId public var tier: Int public var captainId: SummonerId public var abbreviation: String public var players: [ClashPlayer] enum CodingKeys: String, CodingKey { case teamId = "id" case tournamentId = "tournamentId" case name = "name" case iconId = "iconId" case tier = "tier" case captainId = "captain" case abbreviation = "abbreviation" case players = "players" } public init(teamId: TeamId, tournamentId: TournamentId, name: String, iconId: ProfileIconId, tier: Int, captainId: SummonerId, abbreviation: String, players: [ClashPlayer]) { self.teamId = teamId self.tournamentId = tournamentId self.name = name self.iconId = iconId self.tier = tier self.captainId = captainId self.abbreviation = abbreviation self.players = players } public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.teamId = try TeamId(container.decode(String.self, forKey: .teamId)) self.tournamentId = try TournamentId(container.decode(Long.self, forKey: .tournamentId)) self.name = try container.decode(String.self, forKey: .name) self.iconId = try ProfileIconId(container.decode(Long.self, forKey: .iconId)) self.tier = try container.decode(Int.self, forKey: .tier) self.captainId = try SummonerId(container.decode(String.self, forKey: .captainId)) self.abbreviation = try container.decode(String.self, forKey: .abbreviation) self.players = try container.decode([ClashPlayer].self, forKey: .players) } }
412
0.880996
1
0.880996
game-dev
MEDIA
0.378718
game-dev
0.970903
1
0.970903
ellermister/MapleStory
1,485
scripts/npc/1072001.js
/* MAGICIAN Job Instructor (OUTSIDE) Magician 2nd Job Advancement 101020000 */ /** Made by xQuasar **/ var status = 0; function start() { status = -1; action(1, 0, 0); } function action(mode, type, selection) { if (mode == -1) { cm.dispose(); } else if ((status == 0 || status == 1) && mode == 0) { cm.sendOk("I suggest you stock up on supplies before entering."); cm.dispose(); } else if (status == -1) { if (cm.haveItem(4031009) && (!cm.haveItem(4031013))) { status = 0; cm.sendNext("Ah, Grendel the Really Old sent you here?"); } else if (cm.haveItem(4031009) && cm.haveItem(4031013)) { cm.sendOk("Hmm? You already have Dark Marbles in your inventory... please drop them all before talking to me again."); cm.dispose(); } else { cm.sendOk("The path of a Magician is a path of utmost danger..."); cm.dispose(); } } else if (status == 0) { status = 1; cm.sendYesNo("Would you like to go and attempt the test now? Inside are monsters that you will have to defeat to gain Dark Marbles from. Once you have collected 30, talk to the other instructor inside to gain the Proof of a Hero and complete the test."); } else if (status == 1) { status = 2; cm.sendOk("Alright, in you go. Good luck! If you die or disconnect while doing the test, you'll have to go back to Grendel the Really Old for another Letter."); } else if (status == 2) { cm.gainItem(4031009,-1); cm.warp(108000200,0); cm.dispose(); } else { cm.dispose(); } }
412
0.627562
1
0.627562
game-dev
MEDIA
0.983997
game-dev
0.848514
1
0.848514
cmangos/mangos-wotlk
34,064
src/game/World/World.h
/* * This file is part of the CMaNGOS Project. See AUTHORS file for Copyright information * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /// \addtogroup world The World /// @{ /// \file #ifndef __WORLD_H #define __WORLD_H #include "Common.h" #include "Util/Timer.h" #include "Globals/Locales.h" #include "Globals/SharedDefines.h" #include "Entities/Object.h" #include "Multithreading/Messager.h" #include "Globals/GraveyardManager.h" #include "LFG/LFG.h" #include "LFG/LFGQueue.h" #include "BattleGround/BattleGroundQueue.h" #include <set> #include <list> #include <deque> #include <mutex> #include <functional> #include <utility> #include <vector> #include <array> #include <thread> class Object; class ObjectGuid; class WorldPacket; class WorldSession; class Player; class QueryResult; class WorldSocket; // ServerMessages.dbc enum ServerMessageType { SERVER_MSG_SHUTDOWN_TIME = 1, SERVER_MSG_RESTART_TIME = 2, SERVER_MSG_CUSTOM = 3, SERVER_MSG_SHUTDOWN_CANCELLED = 4, SERVER_MSG_RESTART_CANCELLED = 5, SERVER_MSG_BG_SHUTDOWN_TIME = 6, SERVER_MSG_BG_RESTART_TIME = 7, SERVER_MSG_INSTANCE_SHUTDOWN_TIME = 8, SERVER_MSG_INSTANCE_RESTART_TIME = 9, }; enum ShutdownMask { SHUTDOWN_MASK_RESTART = 1, SHUTDOWN_MASK_IDLE = 2, }; enum ShutdownExitCode { SHUTDOWN_EXIT_CODE = 0, ERROR_EXIT_CODE = 1, RESTART_EXIT_CODE = 2, }; /// Timers for different object refresh rates enum WorldTimers { WUPDATE_AUCTIONS = 0, WUPDATE_UPTIME = 1, WUPDATE_CORPSES = 2, WUPDATE_EVENTS = 3, WUPDATE_DELETECHARS = 4, WUPDATE_AHBOT = 5, WUPDATE_GROUPS = 6, WUPDATE_RAID_BROWSER= 7, WUPDATE_METRICS = 8, // not used if BUILD_METRICS is not set WUPDATE_COUNT = 9 }; /// Configuration elements enum eConfigUInt32Values { CONFIG_UINT32_COMPRESSION = 0, CONFIG_UINT32_INTERVAL_SAVE, CONFIG_UINT32_INTERVAL_GRIDCLEAN, CONFIG_UINT32_INTERVAL_MAPUPDATE, CONFIG_UINT32_INTERVAL_CHANGEWEATHER, CONFIG_UINT32_PORT_WORLD, CONFIG_UINT32_GAME_TYPE, CONFIG_UINT32_REALM_ZONE, CONFIG_UINT32_STRICT_PLAYER_NAMES, CONFIG_UINT32_STRICT_CHARTER_NAMES, CONFIG_UINT32_STRICT_PET_NAMES, CONFIG_UINT32_MIN_PLAYER_NAME, CONFIG_UINT32_MIN_CHARTER_NAME, CONFIG_UINT32_MIN_PET_NAME, CONFIG_UINT32_CHARACTERS_CREATING_DISABLED, CONFIG_UINT32_CHARACTERS_PER_ACCOUNT, CONFIG_UINT32_CHARACTERS_PER_REALM, CONFIG_UINT32_HEROIC_CHARACTERS_PER_REALM, CONFIG_UINT32_MIN_LEVEL_FOR_HEROIC_CHARACTER_CREATING, CONFIG_UINT32_SKIP_CINEMATICS, CONFIG_UINT32_MAX_PLAYER_LEVEL, CONFIG_UINT32_START_PLAYER_LEVEL, CONFIG_UINT32_START_HEROIC_PLAYER_LEVEL, CONFIG_UINT32_START_PLAYER_MONEY, CONFIG_UINT32_MAX_HONOR_POINTS, CONFIG_UINT32_START_HONOR_POINTS, CONFIG_UINT32_MAX_ARENA_POINTS, CONFIG_UINT32_START_ARENA_POINTS, CONFIG_UINT32_INSTANCE_RESET_TIME_HOUR, CONFIG_UINT32_INSTANCE_UNLOAD_DELAY, CONFIG_UINT32_MAX_SPELL_CASTS_IN_CHAIN, CONFIG_UINT32_BIRTHDAY_TIME, CONFIG_UINT32_RABBIT_DAY, CONFIG_UINT32_MAX_PRIMARY_TRADE_SKILL, CONFIG_UINT32_TRADE_SKILL_GMIGNORE_MAX_PRIMARY_COUNT, CONFIG_UINT32_TRADE_SKILL_GMIGNORE_LEVEL, CONFIG_UINT32_TRADE_SKILL_GMIGNORE_SKILL, CONFIG_UINT32_MIN_PETITION_SIGNS, CONFIG_UINT32_GM_LOGIN_STATE, CONFIG_UINT32_GM_VISIBLE_STATE, CONFIG_UINT32_GM_ACCEPT_TICKETS, CONFIG_UINT32_GM_LEVEL_ACCEPT_TICKETS, CONFIG_UINT32_GM_CHAT, CONFIG_UINT32_GM_LEVEL_CHAT, CONFIG_UINT32_GM_LEVEL_CHANNEL_MODERATION, CONFIG_UINT32_GM_LEVEL_CHANNEL_SILENT_JOIN, CONFIG_UINT32_GM_WISPERING_TO, CONFIG_UINT32_GM_LEVEL_IN_GM_LIST, CONFIG_UINT32_GM_LEVEL_IN_WHO_LIST, CONFIG_UINT32_START_GM_LEVEL, CONFIG_UINT32_GM_INVISIBLE_AURA, CONFIG_UINT32_MAIL_DELIVERY_DELAY, CONFIG_UINT32_MASS_MAILER_SEND_PER_TICK, CONFIG_UINT32_UPTIME_UPDATE, CONFIG_UINT32_NUM_MAP_THREADS, CONFIG_UINT32_AUCTION_DEPOSIT_MIN, CONFIG_UINT32_SKILL_CHANCE_ORANGE, CONFIG_UINT32_SKILL_CHANCE_YELLOW, CONFIG_UINT32_SKILL_CHANCE_GREEN, CONFIG_UINT32_SKILL_CHANCE_GREY, CONFIG_UINT32_SKILL_CHANCE_MINING_STEPS, CONFIG_UINT32_SKILL_CHANCE_SKINNING_STEPS, CONFIG_UINT32_SKILL_GAIN_CRAFTING, CONFIG_UINT32_SKILL_GAIN_DEFENSE, CONFIG_UINT32_SKILL_GAIN_GATHERING, CONFIG_UINT32_SKILL_GAIN_WEAPON, CONFIG_UINT32_MAX_OVERSPEED_PINGS, CONFIG_UINT32_EXPANSION, CONFIG_UINT32_CHATFLOOD_MESSAGE_COUNT, CONFIG_UINT32_CHATFLOOD_MESSAGE_DELAY, CONFIG_UINT32_CHATFLOOD_MUTE_TIME, CONFIG_UINT32_CREATURE_FAMILY_ASSISTANCE_DELAY, CONFIG_UINT32_CREATURE_FAMILY_FLEE_DELAY, CONFIG_UINT32_WORLD_BOSS_LEVEL_DIFF, CONFIG_UINT32_QUEST_DAILY_RESET_HOUR, CONFIG_UINT32_QUEST_WEEKLY_RESET_WEEK_DAY, CONFIG_UINT32_QUEST_WEEKLY_RESET_HOUR, CONFIG_UINT32_CHAT_STRICT_LINK_CHECKING_SEVERITY, CONFIG_UINT32_CHAT_STRICT_LINK_CHECKING_KICK, CONFIG_UINT32_CHANNEL_RESTRICTED_LANGUAGE_MODE, CONFIG_UINT32_CORPSE_DECAY_NORMAL, CONFIG_UINT32_CORPSE_DECAY_RARE, CONFIG_UINT32_CORPSE_DECAY_ELITE, CONFIG_UINT32_CORPSE_DECAY_RAREELITE, CONFIG_UINT32_CORPSE_DECAY_WORLDBOSS, CONFIG_UINT32_INSTANT_LOGOUT, CONFIG_UINT32_BATTLEGROUND_INVITATION_TYPE, CONFIG_UINT32_BATTLEGROUND_PREMATURE_FINISH_TIMER, CONFIG_UINT32_BATTLEGROUND_PREMADE_GROUP_WAIT_FOR_MATCH, CONFIG_UINT32_BATTLEGROUND_QUEUE_ANNOUNCER_JOIN, CONFIG_UINT32_BATTLEGROUND_RANDOM_RESET_HOUR, CONFIG_UINT32_ARENA_MAX_RATING_DIFFERENCE, CONFIG_UINT32_ARENA_RATING_DISCARD_TIMER, CONFIG_UINT32_ARENA_AUTO_DISTRIBUTE_INTERVAL_DAYS, CONFIG_UINT32_ARENA_SEASON_ID, CONFIG_UINT32_ARENA_FIRST_RESET_DAY, CONFIG_UINT32_ARENA_SEASON_PREVIOUS_ID, CONFIG_UINT32_GROUP_OFFLINE_LEADER_DELAY, CONFIG_UINT32_BATTLEFIELD_COOLDOWN_DURATION, CONFIG_UINT32_BATTLEFIELD_BATTLE_DURATION, CONFIG_UINT32_BATTLEFIELD_MAX_PLAYERS_PER_TEAM, CONFIG_UINT32_CLIENTCACHE_VERSION, CONFIG_UINT32_GUILD_EVENT_LOG_COUNT, CONFIG_UINT32_GUILD_BANK_EVENT_LOG_COUNT, CONFIG_UINT32_MIRRORTIMER_FATIGUE_MAX, CONFIG_UINT32_MIRRORTIMER_BREATH_MAX, CONFIG_UINT32_MIRRORTIMER_ENVIRONMENTAL_MAX, CONFIG_UINT32_ENVIRONMENTAL_DAMAGE_MIN, CONFIG_UINT32_ENVIRONMENTAL_DAMAGE_MAX, CONFIG_UINT32_INTERACTION_PAUSE_TIMER, CONFIG_UINT32_MIN_LEVEL_STAT_SAVE, CONFIG_UINT32_CHARDELETE_KEEP_DAYS, CONFIG_UINT32_CHARDELETE_METHOD, CONFIG_UINT32_CHARDELETE_MIN_LEVEL, CONFIG_UINT32_GUID_RESERVE_SIZE_CREATURE, CONFIG_UINT32_GUID_RESERVE_SIZE_GAMEOBJECT, CONFIG_UINT32_MIN_LEVEL_FOR_RAID, CONFIG_UINT32_CREATURE_RESPAWN_AGGRO_DELAY, CONFIG_UINT32_CREATURE_CHECK_FOR_HELP_AGGRO_DELAY, CONFIG_UINT32_CREATURE_LINKING_AGGRO_DELAY, CONFIG_UINT32_MAX_WHOLIST_RETURNS, CONFIG_UINT32_FOGOFWAR_STEALTH, CONFIG_UINT32_FOGOFWAR_HEALTH, CONFIG_UINT32_FOGOFWAR_STATS, CONFIG_UINT32_CREATURE_PICKPOCKET_RESTOCK_DELAY, CONFIG_UINT32_CHANNEL_STATIC_AUTO_TRESHOLD, CONFIG_UINT32_MAX_RECRUIT_A_FRIEND_BONUS_PLAYER_LEVEL, CONFIG_UINT32_MAX_RECRUIT_A_FRIEND_BONUS_PLAYER_LEVEL_DIFFERENCE, CONFIG_UINT32_SUNSREACH_COUNTER, CONFIG_UINT32_VALUE_COUNT }; /// Configuration elements enum eConfigInt32Values { CONFIG_INT32_DEATH_SICKNESS_LEVEL = 0, CONFIG_INT32_ARENA_STARTRATING, CONFIG_INT32_ARENA_STARTPERSONALRATING, CONFIG_INT32_QUEST_LOW_LEVEL_HIDE_DIFF, CONFIG_INT32_QUEST_HIGH_LEVEL_HIDE_DIFF, CONFIG_INT32_VALUE_COUNT }; /// Server config enum eConfigFloatValues { CONFIG_FLOAT_RATE_HEALTH = 0, CONFIG_FLOAT_RATE_POWER_MANA, CONFIG_FLOAT_RATE_POWER_RAGE_INCOME, CONFIG_FLOAT_RATE_POWER_RAGE_LOSS, CONFIG_FLOAT_RATE_POWER_RUNICPOWER_INCOME, CONFIG_FLOAT_RATE_POWER_RUNICPOWER_LOSS, CONFIG_FLOAT_RATE_POWER_FOCUS, CONFIG_FLOAT_RATE_POWER_ENERGY, CONFIG_FLOAT_RATE_SKILL_DISCOVERY, CONFIG_FLOAT_RATE_DROP_ITEM_POOR, CONFIG_FLOAT_RATE_DROP_ITEM_NORMAL, CONFIG_FLOAT_RATE_DROP_ITEM_UNCOMMON, CONFIG_FLOAT_RATE_DROP_ITEM_RARE, CONFIG_FLOAT_RATE_DROP_ITEM_EPIC, CONFIG_FLOAT_RATE_DROP_ITEM_LEGENDARY, CONFIG_FLOAT_RATE_DROP_ITEM_ARTIFACT, CONFIG_FLOAT_RATE_DROP_ITEM_REFERENCED, CONFIG_FLOAT_RATE_DROP_ITEM_QUEST, CONFIG_FLOAT_RATE_DROP_MONEY, CONFIG_FLOAT_RATE_PET_XP_KILL, CONFIG_FLOAT_RATE_PET_XP_KILL_VANILLA, CONFIG_FLOAT_RATE_PET_XP_KILL_BC, CONFIG_FLOAT_RATE_PET_XP_KILL_WOTLK, CONFIG_FLOAT_RATE_XP_KILL, CONFIG_FLOAT_RATE_XP_KILL_VANILLA, CONFIG_FLOAT_RATE_XP_KILL_BC, CONFIG_FLOAT_RATE_XP_KILL_WOTLK, CONFIG_FLOAT_RATE_XP_QUEST, CONFIG_FLOAT_RATE_XP_QUEST_VANILLA, CONFIG_FLOAT_RATE_XP_QUEST_BC, CONFIG_FLOAT_RATE_XP_QUEST_WOTLK, CONFIG_FLOAT_RATE_XP_EXPLORE, CONFIG_FLOAT_RATE_XP_EXPLORE_VANILLA, CONFIG_FLOAT_RATE_XP_EXPLORE_BC, CONFIG_FLOAT_RATE_XP_EXPLORE_WOTLK, CONFIG_FLOAT_RATE_REPUTATION_GAIN, CONFIG_FLOAT_RATE_REPUTATION_LOWLEVEL_KILL, CONFIG_FLOAT_RATE_REPUTATION_LOWLEVEL_QUEST, CONFIG_FLOAT_RATE_CREATURE_NORMAL_HP, CONFIG_FLOAT_RATE_CREATURE_ELITE_ELITE_HP, CONFIG_FLOAT_RATE_CREATURE_ELITE_RAREELITE_HP, CONFIG_FLOAT_RATE_CREATURE_ELITE_WORLDBOSS_HP, CONFIG_FLOAT_RATE_CREATURE_ELITE_RARE_HP, CONFIG_FLOAT_RATE_CREATURE_NORMAL_DAMAGE, CONFIG_FLOAT_RATE_CREATURE_ELITE_ELITE_DAMAGE, CONFIG_FLOAT_RATE_CREATURE_ELITE_RAREELITE_DAMAGE, CONFIG_FLOAT_RATE_CREATURE_ELITE_WORLDBOSS_DAMAGE, CONFIG_FLOAT_RATE_CREATURE_ELITE_RARE_DAMAGE, CONFIG_FLOAT_RATE_CREATURE_NORMAL_SPELLDAMAGE, CONFIG_FLOAT_RATE_CREATURE_ELITE_ELITE_SPELLDAMAGE, CONFIG_FLOAT_RATE_CREATURE_ELITE_RAREELITE_SPELLDAMAGE, CONFIG_FLOAT_RATE_CREATURE_ELITE_WORLDBOSS_SPELLDAMAGE, CONFIG_FLOAT_RATE_CREATURE_ELITE_RARE_SPELLDAMAGE, CONFIG_FLOAT_RATE_CREATURE_AGGRO, CONFIG_FLOAT_RATE_REST_INGAME, CONFIG_FLOAT_RATE_REST_OFFLINE_IN_TAVERN_OR_CITY, CONFIG_FLOAT_RATE_REST_OFFLINE_IN_WILDERNESS, CONFIG_FLOAT_RATE_DAMAGE_FALL, CONFIG_FLOAT_RATE_AUCTION_TIME, CONFIG_FLOAT_RATE_AUCTION_DEPOSIT, CONFIG_FLOAT_RATE_AUCTION_CUT, CONFIG_FLOAT_RATE_HONOR, CONFIG_FLOAT_RATE_MINING_AMOUNT, CONFIG_FLOAT_RATE_MINING_NEXT, CONFIG_FLOAT_RATE_TALENT, CONFIG_FLOAT_RATE_CORPSE_DECAY_LOOTED, CONFIG_FLOAT_RATE_INSTANCE_RESET_TIME, CONFIG_FLOAT_RATE_DURABILITY_LOSS_DAMAGE, CONFIG_FLOAT_RATE_DURABILITY_LOSS_PARRY, CONFIG_FLOAT_RATE_DURABILITY_LOSS_ABSORB, CONFIG_FLOAT_RATE_DURABILITY_LOSS_BLOCK, CONFIG_FLOAT_SIGHT_GUARDER, CONFIG_FLOAT_SIGHT_MONSTER, CONFIG_FLOAT_LISTEN_RANGE_SAY, CONFIG_FLOAT_LISTEN_RANGE_YELL, CONFIG_FLOAT_LISTEN_RANGE_TEXTEMOTE, CONFIG_FLOAT_CREATURE_FAMILY_FLEE_ASSISTANCE_RADIUS, CONFIG_FLOAT_CREATURE_FAMILY_ASSISTANCE_RADIUS, CONFIG_FLOAT_CREATURE_CHECK_FOR_HELP_RADIUS, CONFIG_FLOAT_GROUP_XP_DISTANCE, CONFIG_FLOAT_GHOST_RUN_SPEED_WORLD, CONFIG_FLOAT_GHOST_RUN_SPEED_BG, CONFIG_FLOAT_LEASH_RADIUS, CONFIG_FLOAT_MOD_DISCOUNT_REPUTATION_FRIENDLY, // TODO CONFIG_FLOAT_MOD_DISCOUNT_REPUTATION_HONORED, CONFIG_FLOAT_MOD_DISCOUNT_REPUTATION_REVERED, CONFIG_FLOAT_MOD_DISCOUNT_REPUTATION_EXALTED, CONFIG_FLOAT_MOD_INCREASED_XP, CONFIG_FLOAT_MOD_INCREASED_GOLD, CONFIG_FLOAT_MAX_RECRUIT_A_FRIEND_DISTANCE, CONFIG_FLOAT_VALUE_COUNT }; /// Configuration elements enum eConfigBoolValues { CONFIG_BOOL_GRID_UNLOAD = 0, CONFIG_BOOL_SAVE_RESPAWN_TIME_IMMEDIATELY, CONFIG_BOOL_OFFHAND_CHECK_AT_TALENTS_RESET, CONFIG_BOOL_ALLOW_TWO_SIDE_ACCOUNTS, CONFIG_BOOL_ALLOW_TWO_SIDE_INTERACTION_CHAT, CONFIG_BOOL_ALLOW_TWO_SIDE_INTERACTION_CHANNEL, CONFIG_BOOL_ALLOW_TWO_SIDE_INTERACTION_GROUP, CONFIG_BOOL_ALLOW_TWO_SIDE_INTERACTION_GUILD, CONFIG_BOOL_ALLOW_TWO_SIDE_INTERACTION_AUCTION, CONFIG_BOOL_ALLOW_TWO_SIDE_INTERACTION_MAIL, CONFIG_BOOL_ALLOW_TWO_SIDE_INTERACTION_CALENDAR, CONFIG_BOOL_ALLOW_TWO_SIDE_WHO_LIST, CONFIG_BOOL_ALLOW_TWO_SIDE_ADD_FRIEND, CONFIG_BOOL_INSTANCE_IGNORE_LEVEL, CONFIG_BOOL_INSTANCE_IGNORE_RAID, CONFIG_BOOL_INSTANCE_STRICT_COMBAT_LOCKDOWN, CONFIG_BOOL_CAST_UNSTUCK, CONFIG_BOOL_GM_LOG_TRADE, CONFIG_BOOL_GM_LOWER_SECURITY, CONFIG_BOOL_GM_TICKETS_QUEUE_STATUS, CONFIG_BOOL_GM_ALLOW_ACHIEVEMENT_GAINS, CONFIG_BOOL_SKILL_PROSPECTING, CONFIG_BOOL_ALWAYS_MAX_SKILL_FOR_LEVEL, CONFIG_BOOL_WEATHER, CONFIG_BOOL_EVENT_ANNOUNCE, CONFIG_BOOL_QUEST_IGNORE_RAID, CONFIG_BOOL_DETECT_POS_COLLISION, CONFIG_BOOL_CHAT_RESTRICTED_RAID_WARNINGS, CONFIG_BOOL_CHANNEL_RESTRICTED_LFG, CONFIG_BOOL_TALENTS_INSPECTING, CONFIG_BOOL_CHAT_FAKE_MESSAGE_PREVENTING, CONFIG_BOOL_CHAT_STRICT_LINK_CHECKING_SEVERITY, CONFIG_BOOL_CHAT_STRICT_LINK_CHECKING_KICK, CONFIG_BOOL_ADDON_CHANNEL, CONFIG_BOOL_CORPSE_EMPTY_LOOT_SHOW, CONFIG_BOOL_CORPSE_ALLOW_ALL_ITEMS_SHOW_IN_MASTER_LOOT, CONFIG_BOOL_DEATH_CORPSE_RECLAIM_DELAY_PVP, CONFIG_BOOL_DEATH_CORPSE_RECLAIM_DELAY_PVE, CONFIG_BOOL_DEATH_BONES_WORLD, CONFIG_BOOL_DEATH_BONES_BG_OR_ARENA, CONFIG_BOOL_TAXI_FLIGHT_CHAT_FIX, CONFIG_BOOL_LONG_TAXI_PATHS_PERSISTENCE, CONFIG_BOOL_ALL_TAXI_PATHS, CONFIG_BOOL_DECLINED_NAMES_USED, CONFIG_BOOL_SKILL_MILLING, CONFIG_BOOL_SKILL_FAIL_LOOT_FISHING, CONFIG_BOOL_SKILL_FAIL_GAIN_FISHING, CONFIG_BOOL_SKILL_FAIL_POSSIBLE_FISHINGPOOL, CONFIG_BOOL_BATTLEGROUND_CAST_DESERTER, CONFIG_BOOL_BATTLEGROUND_QUEUE_ANNOUNCER_START, CONFIG_BOOL_BATTLEGROUND_SCORE_STATISTICS, CONFIG_BOOL_ARENA_AUTO_DISTRIBUTE_POINTS, CONFIG_BOOL_ARENA_QUEUE_ANNOUNCER_JOIN, CONFIG_BOOL_ARENA_QUEUE_ANNOUNCER_EXIT, CONFIG_BOOL_OUTDOORPVP_SI_ENABLED, CONFIG_BOOL_OUTDOORPVP_EP_ENABLED, CONFIG_BOOL_OUTDOORPVP_HP_ENABLED, CONFIG_BOOL_OUTDOORPVP_ZM_ENABLED, CONFIG_BOOL_OUTDOORPVP_TF_ENABLED, CONFIG_BOOL_OUTDOORPVP_NA_ENABLED, CONFIG_BOOL_OUTDOORPVP_GH_ENABLED, CONFIG_BOOL_BATTLEFIELD_WG_ENABLED, CONFIG_BOOL_KICK_PLAYER_ON_BAD_PACKET, CONFIG_BOOL_STATS_SAVE_ONLY_ON_LOGOUT, CONFIG_BOOL_CLEAN_CHARACTER_DB, CONFIG_BOOL_VMAP_INDOOR_CHECK, CONFIG_BOOL_PET_UNSUMMON_AT_MOUNT, CONFIG_BOOL_KEEP_PET_ON_FLYING_MOUNT, CONFIG_BOOL_PET_ATTACK_FROM_BEHIND, CONFIG_BOOL_AUTO_DOWNRANK, CONFIG_BOOL_MMAP_ENABLED, CONFIG_BOOL_PLAYER_COMMANDS, CONFIG_BOOL_AUTOLOAD_ACTIVE, CONFIG_BOOL_PATH_FIND_OPTIMIZE, CONFIG_BOOL_PATH_FIND_NORMALIZE_Z, CONFIG_BOOL_ALWAYS_SHOW_QUEST_GREETING, CONFIG_BOOL_DISABLE_INSTANCE_RELOCATE, CONFIG_BOOL_PRELOAD_MMAP_TILES, CONFIG_BOOL_SPECIALS_ACTIVE, CONFIG_BOOL_REGEN_ZONE_AREA_ON_STARTUP, CONFIG_BOOL_VALUE_COUNT }; /// Can be used in SMSG_AUTH_RESPONSE packet enum BillingPlanFlags { SESSION_NONE = 0x00, SESSION_UNUSED = 0x01, SESSION_RECURRING_BILL = 0x02, SESSION_FREE_TRIAL = 0x04, SESSION_IGR = 0x08, SESSION_USAGE = 0x10, SESSION_TIME_MIXTURE = 0x20, SESSION_RESTRICTED = 0x40, SESSION_ENABLE_CAIS = 0x80, }; /// Type of server, this is values from second column of Cfg_Configs.dbc (1.12.1 have another numeration) enum RealmType { REALM_TYPE_NORMAL = 0, REALM_TYPE_PVP = 1, REALM_TYPE_NORMAL2 = 4, REALM_TYPE_RP = 6, REALM_TYPE_RPPVP = 8, REALM_TYPE_FFA_PVP = 16 // custom, free for all pvp mode like arena PvP in all zones except rest activated places and sanctuaries // replaced by REALM_PVP in realm list }; /// Storage class for commands issued for delayed execution struct CliCommandHolder { typedef std::function<void(const char*)> Print; typedef std::function<void(bool)> CommandFinished; uint32 m_cliAccountId; // 0 for console and real account id for RA/soap AccountTypes m_cliAccessLevel; std::vector<char> m_command; Print m_print; CommandFinished m_commandFinished; CliCommandHolder(uint32 accountId, AccountTypes cliAccessLevel, const char* command, Print print, CommandFinished commandFinished) : m_cliAccountId(accountId), m_cliAccessLevel(cliAccessLevel), m_command(strlen(command) + 1), m_print(std::move(print)), m_commandFinished(std::move(commandFinished)) { memcpy(&m_command[0], command, m_command.size() - 1); } }; /// The World class World { public: static volatile uint32 m_worldLoopCounter; World(); ~World(); void CleanupsBeforeStop(); WorldSession* FindSession(uint32 id) const; void AddSession(WorldSession* s); bool RemoveSession(uint32 id); /// Get the number of current active sessions void UpdateMaxSessionCounters(); uint32 GetActiveAndQueuedSessionCount() const { return m_sessions.size(); } uint32 GetActiveSessionCount() const { return m_sessions.size() - m_QueuedSessions.size(); } uint32 GetQueuedSessionCount() const { return m_QueuedSessions.size(); } /// Get the maximum number of parallel sessions on the server since last reboot uint32 GetMaxQueuedSessionCount() const { return m_maxQueuedSessionCount; } uint32 GetMaxActiveSessionCount() const { return m_maxActiveSessionCount; } uint32 GetUniqueSessionCount() const { return m_uniqueSessionCount.size(); } // player counts void SetOnlinePlayer(Team team, uint8 race, uint8 plClass, bool apply); // threadsafe uint32 GetOnlineTeamPlayers(bool alliance) const { return m_onlineTeams[alliance]; } uint32 GetOnlineRacePlayers(uint8 race) const { return m_onlineRaces[race]; } uint32 GetOnlineClassPlayers(uint8 plClass) const { return m_onlineClasses[plClass]; } /// Get the active session server limit (or security level limitations) uint32 GetPlayerAmountLimit() const { return m_playerLimit >= 0 ? m_playerLimit : 0; } AccountTypes GetPlayerSecurityLimit() const { return m_playerLimit <= 0 ? AccountTypes(-m_playerLimit) : SEC_PLAYER; } /// Set the active session server limit (or security level limitation) void SetPlayerLimit(int32 limit, bool needUpdate = false); // player Queue typedef std::list<WorldSession*> Queue; void AddQueuedSession(WorldSession*); bool RemoveQueuedSession(WorldSession* sess); int32 GetQueuedSessionPos(WorldSession const* sess) const; /// \todo Actions on m_allowMovement still to be implemented /// Is movement allowed? bool getAllowMovement() const { return m_allowMovement; } /// Allow/Disallow object movements void SetAllowMovement(bool allow) { m_allowMovement = allow; } /// Set a new Message of the Day void SetMotd(const std::string& motd) { m_motd = motd; } /// Get the current Message of the Day const char* GetMotd() const { return m_motd.c_str(); } LocaleConstant GetDefaultDbcLocale() const { return m_defaultDbcLocale; } /// Get the path where data (dbc, maps) are stored on disk std::string GetDataPath() const { return m_dataPath; } /// When server started? time_t const& GetStartTime() const { return m_startTime; } /// What time is it? time_t const& GetGameTime() const { return m_gameTime; } /// Uptime (in secs) uint32 GetUptime() const { return uint32(m_gameTime - m_startTime); } /// Next daily quests and random bg reset time time_t GetNextDailyQuestsResetTime() const { return m_NextDailyQuestReset; } time_t GetNextWeeklyQuestsResetTime() const { return m_NextWeeklyQuestReset; } time_t GetNextRandomBattlegroundResetTime() const { return m_NextRandomBattlegroundReset; } /// Get the maximum skill level a player can reach uint16 GetConfigMaxSkillValue() const { uint32 lvl = getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL); return lvl > 60 ? 300 + ((lvl - 60) * 75) / 10 : lvl * 5; } void SetInitialWorldSettings(); void LoadConfigSettings(bool reload = false); void LoadSpamRecords(bool reload = false); void SendWorldText(int32 string_id, ...); void SendWorldTextToAboveSecurity(uint32 securityLevel, int32 string_id, ...); void SendWorldTextToAcceptingTickets(int32 string_id, ...); void SendGlobalMessage(WorldPacket const& packet, uint32 team = 0) const; void SendServerMessage(ServerMessageType type, const char* text = "", Player* player = nullptr) const; void SendZoneUnderAttackMessage(uint32 zoneId, Team team); void SendDefenseMessage(uint32 zoneId, int32 textId); void SendDefenseMessageBroadcastText(uint32 zoneId, uint32 textId); /// Are we in the middle of a shutdown? bool IsShutdowning() const { return m_ShutdownTimer > 0; } void ShutdownServ(uint32 time, uint32 options, uint8 exitcode); void ShutdownCancel(); void ShutdownMsg(bool show = false, Player* player = nullptr); static uint8 GetExitCode() { return m_ExitCode; } static void StopNow(uint8 exitcode) { m_stopEvent = true; m_ExitCode = exitcode; } static bool IsStopped() { return m_stopEvent; } void Update(uint32 diff); void UpdateSessions(uint32 diff); /// Get a server configuration element (see #eConfigFloatValues) void setConfig(eConfigFloatValues index, float value) { m_configFloatValues[index] = value; } /// Get a server configuration element (see #eConfigFloatValues) float getConfig(eConfigFloatValues rate) const { return m_configFloatValues[rate]; } /// Set a server configuration element (see #eConfigUInt32Values) void setConfig(eConfigUInt32Values index, uint32 value) { m_configUint32Values[index] = value; } /// Get a server configuration element (see #eConfigUInt32Values) uint32 getConfig(eConfigUInt32Values index) const { return m_configUint32Values[index]; } /// Set a server configuration element (see #eConfigInt32Values) void setConfig(eConfigInt32Values index, int32 value) { m_configInt32Values[index] = value; } /// Get a server configuration element (see #eConfigInt32Values) int32 getConfig(eConfigInt32Values index) const { return m_configInt32Values[index]; } /// Set a server configuration element (see #eConfigBoolValues) void setConfig(eConfigBoolValues index, bool value) { m_configBoolValues[index] = value; } /// Get a server configuration element (see #eConfigBoolValues) bool getConfig(eConfigBoolValues index) const { return m_configBoolValues[index]; } /// Get configuration about force-loaded maps bool isForceLoadMap(uint32 id) const { return m_configForceLoadMapIds.find(id) != m_configForceLoadMapIds.end(); } /// Are we on a "Player versus Player" server? bool IsPvPRealm() const { return (getConfig(CONFIG_UINT32_GAME_TYPE) == REALM_TYPE_PVP || getConfig(CONFIG_UINT32_GAME_TYPE) == REALM_TYPE_RPPVP || getConfig(CONFIG_UINT32_GAME_TYPE) == REALM_TYPE_FFA_PVP); } bool IsFFAPvPRealm() const { return getConfig(CONFIG_UINT32_GAME_TYPE) == REALM_TYPE_FFA_PVP; } void KickAll(bool save); void KickAllLess(AccountTypes sec); void WarnAccount(uint32 accountId, std::string from, std::string reason, const char* type = "WARNING"); BanReturn BanAccount(BanMode mode, std::string nameOrIP, uint32 duration_secs, std::string reason, const std::string& author); BanReturn BanAccount(WorldSession *session, uint32 duration_secs, const std::string& reason, const std::string& author); bool RemoveBanAccount(BanMode mode, const std::string& source, const std::string& message, std::string nameOrIP); // for max speed access static float GetMaxVisibleDistanceOnContinents() { return m_MaxVisibleDistanceOnContinents; } static float GetMaxVisibleDistanceInInstances() { return m_MaxVisibleDistanceInInstances; } static float GetMaxVisibleDistanceInBGArenas() { return m_MaxVisibleDistanceInBGArenas; } static float GetRelocationLowerLimitSq() { return m_relocation_lower_limit_sq; } static uint32 GetRelocationAINotifyDelay() { return m_relocation_ai_notify_delay; } void ProcessCliCommands(); void QueueCliCommand(const CliCommandHolder* commandHolder) { std::lock_guard<std::mutex> guard(m_cliCommandQueueLock); m_cliCommandQueue.push_back(commandHolder); } void UpdateResultQueue(); void InitResultQueue(); void UpdateRealmCharCount(uint32 accountId); LocaleConstant GetAvailableDbcLocale(LocaleConstant locale) const { if (m_availableDbcLocaleMask & (1 << locale)) return locale; return m_defaultDbcLocale; } // used World DB version void LoadDBVersion(); char const* GetDBVersion() const { return m_DBVersion.c_str(); } char const* GetCreatureEventAIVersion() const { return m_CreatureEventAIVersion.c_str(); } std::vector<std::string> GetSpamRecords() const { return m_spamRecords; } /** * \brief: force all client to request player data * \param: ObjectGuid guid : guid of the specified player * \returns: void * * Description: InvalidatePlayerDataToAllClient force all connected clients to clear specified player cache * FullName: World::InvalidatePlayerDataToAllClient * Access: public **/ void InvalidatePlayerDataToAllClient(ObjectGuid guid) const; static uint32 GetCurrentMSTime() { return m_currentMSTime; } static TimePoint GetCurrentClockTime() { return m_currentTime; } static uint32 GetCurrentDiff() { return m_currentDiff; } #ifdef ENABLE_PLAYERBOTS static uint32 GetAverageDiff() { return m_averageDiff; } static uint32 GetMaxDiff() { return m_maxDiff; } #endif template<typename T> void ExecuteForAllSessions(T executor) const { for (auto& data : m_sessions) executor(*data.second); } Messager<World>& GetMessager() { return m_messager; } void IncrementOpcodeCounter(uint32 opcodeId); // thread safe due to atomics void LoadWorldSafeLocs() const; void LoadGraveyardZones(); GraveyardManager& GetGraveyardManager() { return m_graveyardManager; } void SendGMTextFlags(uint32 accountFlag, int32 stringId, std::string type, const char* message); LfgRaidBrowser& GetRaidBrowser() { return m_raidBrowser; } LFGQueue& GetLFGQueue() { return m_lfgQueue; } void BroadcastToGroup(ObjectGuid groupGuid, std::vector<WorldPacket> const& packets); void BroadcastPersonalized(std::map<ObjectGuid, std::vector<WorldPacket>> const& personalizedPackets); BattleGroundQueue& GetBGQueue() { return m_bgQueue; } void StartLFGQueueThread(); void StartBGQueueThread(); protected: void _UpdateGameTime(); // callback for UpdateRealmCharacters void _UpdateRealmCharCount(QueryResult* resultCharCount, uint32 accountId); void InitDailyQuestResetTime(); void InitWeeklyQuestResetTime(); void InitRandomBattlegroundResetTime(); void SetMonthlyQuestResetTime(bool initialize = true); void GenerateEventGroupEvents(bool daily, bool weekly, bool deleteColumns); void LoadEventGroupChosen(); void ResetDailyQuests(); void ResetWeeklyQuests(); void ResetMonthlyQuests(); void ResetRandomBattleground(); #ifdef BUILD_METRICS void GeneratePacketMetrics(); // thread safe due to atomics uint32 GetAverageLatency() const; #endif private: void setConfig(eConfigUInt32Values index, char const* fieldname, uint32 defvalue); void setConfig(eConfigInt32Values index, char const* fieldname, int32 defvalue); void setConfig(eConfigFloatValues index, char const* fieldname, float defvalue); void setConfig(eConfigBoolValues index, char const* fieldname, bool defvalue); void setConfigPos(eConfigFloatValues index, char const* fieldname, float defvalue); void setConfigMin(eConfigUInt32Values index, char const* fieldname, uint32 defvalue, uint32 minvalue); void setConfigMin(eConfigInt32Values index, char const* fieldname, int32 defvalue, int32 minvalue); void setConfigMin(eConfigFloatValues index, char const* fieldname, float defvalue, float minvalue); void setConfigMinMax(eConfigUInt32Values index, char const* fieldname, uint32 defvalue, uint32 minvalue, uint32 maxvalue); void setConfigMinMax(eConfigInt32Values index, char const* fieldname, int32 defvalue, int32 minvalue, int32 maxvalue); void setConfigMinMax(eConfigFloatValues index, char const* fieldname, float defvalue, float minvalue, float maxvalue); bool configNoReload(bool reload, eConfigUInt32Values index, char const* fieldname, uint32 defvalue) const; bool configNoReload(bool reload, eConfigInt32Values index, char const* fieldname, int32 defvalue) const; bool configNoReload(bool reload, eConfigFloatValues index, char const* fieldname, float defvalue) const; bool configNoReload(bool reload, eConfigBoolValues index, char const* fieldname, bool defvalue) const; static volatile bool m_stopEvent; static uint8 m_ExitCode; uint32 m_ShutdownTimer; uint32 m_ShutdownMask; time_t m_startTime; time_t m_gameTime; IntervalTimer m_timers[WUPDATE_COUNT]; uint32 mail_timer; uint32 mail_timer_expires; typedef std::unordered_map<uint32, WorldSession*> SessionMap; typedef std::unordered_set<uint32> UniqueSessions; SessionMap m_sessions; UniqueSessions m_uniqueSessionCount; uint32 m_maxActiveSessionCount; uint32 m_maxQueuedSessionCount; uint32 m_configUint32Values[CONFIG_UINT32_VALUE_COUNT]; int32 m_configInt32Values[CONFIG_INT32_VALUE_COUNT]; float m_configFloatValues[CONFIG_FLOAT_VALUE_COUNT]; bool m_configBoolValues[CONFIG_BOOL_VALUE_COUNT]; int32 m_playerLimit; LocaleConstant m_defaultDbcLocale; // from config for one from loaded DBC locales uint32 m_availableDbcLocaleMask; // by loaded DBC void DetectDBCLang(); bool m_allowMovement; std::string m_motd; std::string m_dataPath; // for max speed access static float m_MaxVisibleDistanceOnContinents; static float m_MaxVisibleDistanceInInstances; static float m_MaxVisibleDistanceInBGArenas; static float m_relocation_lower_limit_sq; static uint32 m_relocation_ai_notify_delay; // CLI command holder to be thread safe std::mutex m_cliCommandQueueLock; std::deque<const CliCommandHolder*> m_cliCommandQueue; // next daily quests and random BG reset time time_t m_NextDailyQuestReset; time_t m_NextWeeklyQuestReset; time_t m_NextMonthlyQuestReset; time_t m_NextRandomBattlegroundReset; // Player Queue Queue m_QueuedSessions; // sessions that are added async void AddSession_(WorldSession* s); std::mutex m_sessionAddQueueLock; std::deque<WorldSession*> m_sessionAddQueue; // used versions std::string m_DBVersion; std::string m_CreatureEventAIVersion; // List of Maps that should be force-loaded on startup std::set<uint32> m_configForceLoadMapIds; // Vector of quests that were chosen for given group std::vector<uint32> m_eventGroupChosen; std::vector<std::string> m_spamRecords; static uint32 m_currentMSTime; static TimePoint m_currentTime; static uint32 m_currentDiff; #ifdef ENABLE_PLAYERBOTS static uint32 m_currentDiffSum; static uint32 m_currentDiffSumIndex; static uint32 m_averageDiff; static uint32 m_maxDiff; static std::list<uint32> m_histDiff; #endif Messager<World> m_messager; // Opcode logging std::vector<std::atomic<uint32>> m_opcodeCounters; // online count logging std::array<std::atomic<uint32>, 2> m_onlineTeams; std::array<std::atomic<uint32>, MAX_RACES> m_onlineRaces; std::array<std::atomic<uint32>, MAX_CLASSES> m_onlineClasses; GraveyardManager m_graveyardManager; // World is owner to differentiate from Dungeon finder where queue is completely disjoint LfgRaidBrowser m_raidBrowser; // Housing this here but logically it is completely asynchronous LFGQueue m_lfgQueue; std::thread m_lfgQueueThread; BattleGroundQueue m_bgQueue; std::thread m_bgQueueThread; }; extern uint32 realmID; #define sWorld MaNGOS::Singleton<World>::Instance() #endif /// @}
412
0.937295
1
0.937295
game-dev
MEDIA
0.37197
game-dev
0.504802
1
0.504802