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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
revolucas/CoC-Xray | 11,938 | src/xrGame/ai_stalker_alife.cpp | ////////////////////////////////////////////////////////////////////////////
// Module : ai_stalker_alife.cpp
// Created : 15.10.2004
// Modified : 15.10.2004
// Author : Dmitriy Iassenev
// Description : Stalker ALife functions
////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "ai/stalker/ai_stalker.h"
#include "ai_space.h"
#include "alife_simulator.h"
#include "alife_space.h"
#include "inventory.h"
#include "pda.h"
#include "eatable_item.h"
#include "medkit.h"
#include "weapon.h"
#include "Grenade.h"
#include "customdetector.h"
#include "ef_storage.h"
#include "ef_primary.h"
#include "ef_pattern.h"
#include "trade_parameters.h"
#include "clsid_game.h"
static const int MAX_AMMO_ATTACH_COUNT = 1;
static const int enough_ammo_box_count = 1;
IC bool CAI_Stalker::CTradeItem::operator< (const CTradeItem &trade_item) const
{
return (m_item->object().ID() < trade_item.m_item->object().ID());
}
IC bool CAI_Stalker::CTradeItem::operator== (u16 id) const
{
return (m_item->object().ID() == id);
}
bool CAI_Stalker::tradable_item (CInventoryItem *inventory_item, const u16 ¤t_owner_id)
{
if (!inventory_item->useful_for_NPC())
return (false);
if (CLSID_DEVICE_PDA == inventory_item->object().CLS_ID) {
CPda *pda = smart_cast<CPda*>(inventory_item);
VERIFY (pda);
if (pda->GetOriginalOwnerID() == current_owner_id)
return (false);
}
return (
trade_parameters().enabled(
CTradeParameters::action_sell(0),
inventory_item->object().cNameSect()
)
);
}
u32 CAI_Stalker::fill_items (CInventory &inventory, CGameObject *old_owner, ALife::_OBJECT_ID new_owner_id)
{
u32 result = 0;
TIItemContainer::iterator I = inventory.m_all.begin();
TIItemContainer::iterator E = inventory.m_all.end();
for ( ; I != E; ++I) {
if (!tradable_item(*I,old_owner->ID()))
continue;
m_temp_items.push_back (CTradeItem(*I,old_owner->ID(),new_owner_id));
result += (*I)->Cost();
}
return (result);
}
void CAI_Stalker::transfer_item (CInventoryItem *item, CGameObject *old_owner, CGameObject *new_owner)
{
NET_Packet P;
CGameObject *O = old_owner;
O->u_EventGen (P,GE_TRADE_SELL,O->ID());
P.w_u16 (u16(item->object().ID()));
O->u_EventSend (P);
O = new_owner;
O->u_EventGen (P,GE_TRADE_BUY,O->ID());
P.w_u16 (u16(item->object().ID()));
O->u_EventSend (P);
}
IC void CAI_Stalker::buy_item_virtual (CTradeItem &item)
{
item.m_new_owner_id = ID();
m_total_money -= item.m_item->Cost();
if (m_current_trader)
m_current_trader->set_money(m_current_trader->get_money() + item.m_item->Cost(), true);
}
void CAI_Stalker::choose_food ()
{
// stalker cannot change food due to the game design :-(((
return;
}
void CAI_Stalker::attach_available_ammo (CWeapon *weapon)
{
if (!weapon || weapon->m_ammoTypes.empty())
return;
u32 count = 0;
xr_vector<CTradeItem>::iterator I = m_temp_items.begin();
xr_vector<CTradeItem>::iterator E = m_temp_items.end();
for ( ; I != E; ++I) {
if (m_total_money < (*I).m_item->Cost())
continue;
if (
std::find(
weapon->m_ammoTypes.begin(),
weapon->m_ammoTypes.end(),
(*I).m_item->object().cNameSect()
) ==
weapon->m_ammoTypes.end()
)
continue;
buy_item_virtual (*I);
++count;
if (count >= MAX_AMMO_ATTACH_COUNT)
break;
}
}
void CAI_Stalker::choose_weapon (ALife::EWeaponPriorityType weapon_priority_type)
{
CTradeItem *best_weapon = 0;
float best_value = -1.f;
ai().ef_storage().non_alife().member() = this;
xr_vector<CTradeItem>::iterator I = m_temp_items.begin();
xr_vector<CTradeItem>::iterator E = m_temp_items.end();
for ( ; I != E; ++I) {
if (m_total_money < (*I).m_item->Cost())
continue;
ai().ef_storage().non_alife().member_item() = &(*I).m_item->object();
int j = ai().ef_storage().m_pfPersonalWeaponType->dwfGetWeaponType();
float current_value = -1.f;
switch (weapon_priority_type) {
case ALife::eWeaponPriorityTypeKnife : {
if (1 != j)
continue;
current_value = ai().ef_storage().m_pfItemValue->ffGetValue();
if(I->m_item->m_ItemCurrPlace.type==eItemPlaceSlot)
current_value += 10.0f;
break;
}
case ALife::eWeaponPriorityTypeSecondary : {
if (5 != j)
continue;
current_value = ai().ef_storage().m_pfSmallWeaponValue->ffGetValue();
if(I->m_item->m_ItemCurrPlace.type==eItemPlaceSlot)
current_value += 10.0f;
break;
}
case ALife::eWeaponPriorityTypePrimary : {
if ((6 != j) && (7 != j) && (8 != j) && (9 != j) && (11 != j) && (12 != j))
continue;
current_value = ai().ef_storage().m_pfMainWeaponValue->ffGetValue();
if(I->m_item->m_ItemCurrPlace.type==eItemPlaceSlot)
current_value += 10.0f;
break;
}
case ALife::eWeaponPriorityTypeGrenade : {
if (4 != j)
continue;
current_value = ai().ef_storage().m_pfItemValue->ffGetValue();
if(I->m_item->m_ItemCurrPlace.type==eItemPlaceSlot)
current_value += 10.0f;
break;
}
default : NODEFAULT;
}
if ((current_value > best_value)) {
best_value = current_value;
best_weapon = &*I;
}
}
if (best_weapon) {
buy_item_virtual (*best_weapon);
attach_available_ammo (smart_cast<CWeapon*>(best_weapon->m_item));
}
}
void CAI_Stalker::choose_medikit ()
{
// stalker cannot change medikit due to the game design :-(((
return;
}
void CAI_Stalker::choose_detector ()
{
CTradeItem *best_detector = 0;
float best_value = -1.f;
ai().ef_storage().non_alife().member() = this;
xr_vector<CTradeItem>::iterator I = m_temp_items.begin();
xr_vector<CTradeItem>::iterator E = m_temp_items.end();
for ( ; I != E; ++I) {
if (m_total_money < (*I).m_item->Cost())
continue;
CCustomDetector *detector = smart_cast<CCustomDetector*>((*I).m_item);
if (!detector)
continue;
// evaluating item
ai().ef_storage().non_alife().member_item() = detector;
float current_value = ai().ef_storage().m_pfDetectorType->ffGetValue();
// choosing the best item
if ((current_value > best_value)) {
best_detector = &*I;
best_value = current_value;
}
}
if (best_detector)
buy_item_virtual (*best_detector);
}
void CAI_Stalker::choose_equipment ()
{
// stalker cannot change their equipment due to the game design :-(((
return;
}
void CAI_Stalker::select_items ()
{
if (!m_can_select_items)
return;
choose_food ();
choose_weapon (ALife::eWeaponPriorityTypeKnife);
choose_weapon (ALife::eWeaponPriorityTypeSecondary);
choose_weapon (ALife::eWeaponPriorityTypePrimary);
choose_weapon (ALife::eWeaponPriorityTypeGrenade);
choose_medikit ();
choose_detector ();
choose_equipment ();
}
void CAI_Stalker::update_sell_info ()
{
// if (m_sell_info_actuality)
// return;
m_sell_info_actuality = true;
m_temp_items.clear ();
m_current_trader = 0;
m_total_money = get_money();
u32 money_delta = fill_items(inventory(),this,ALife::_OBJECT_ID(-1));
m_total_money += money_delta;
std::sort (m_temp_items.begin(),m_temp_items.end());
select_items ();
TIItemContainer::iterator I = inventory().m_all.begin();
TIItemContainer::iterator E = inventory().m_all.end();
for ( ; I != E; ++I) {
if (!tradable_item(*I,ID()))
m_temp_items.push_back (CTradeItem(*I,ID(),ID()));
}
}
bool CAI_Stalker::can_sell (CInventoryItem* item)
{
if (READ_IF_EXISTS(pSettings, r_bool, cNameSect(), "is_trader", false))
return (tradable_item(item, ID()));
update_sell_info ();
xr_vector<CTradeItem>::const_iterator I = std::find(m_temp_items.begin(),m_temp_items.end(),item->object().ID());
VERIFY (I != m_temp_items.end());
return ((*I).m_new_owner_id != ID());
}
bool CAI_Stalker::AllowItemToTrade (CInventoryItem const * item, const SInvItemPlace& place) const
{
if (!g_Alive())
return (trade_parameters().enabled(CTradeParameters::action_show(0),item->object().cNameSect()));
return (const_cast<CAI_Stalker*>(this)->can_sell(const_cast<CInventoryItem*>(item)));
}
bool CAI_Stalker::non_conflicted (const CInventoryItem *item, const CWeapon *new_weapon) const
{
if (item == new_weapon)
return (true);
const CWeapon *weapon = smart_cast<const CWeapon*>(item);
if (!weapon)
return (true);
return (weapon->ef_weapon_type() != new_weapon->ef_weapon_type());
}
bool CAI_Stalker::enough_ammo (const CWeapon *new_weapon) const
{
int ammo_box_count = 0;
TIItemContainer::const_iterator I = inventory().m_all.begin();
TIItemContainer::const_iterator E = inventory().m_all.end();
for ( ; I != E; ++I) {
if (std::find(new_weapon->m_ammoTypes.begin(),new_weapon->m_ammoTypes.end(),(*I)->object().cNameSect()) == new_weapon->m_ammoTypes.end())
continue;
++ammo_box_count;
if (ammo_box_count >= enough_ammo_box_count)
return (true);
}
return (false);
}
bool CAI_Stalker::conflicted (const CInventoryItem *item, const CWeapon *new_weapon, bool new_wepon_enough_ammo, int new_weapon_rank) const
{
if (non_conflicted(item,new_weapon))
return (false);
const CWeapon *weapon = smart_cast<const CWeapon*>(item);
VERIFY (weapon);
bool current_weapon_enough_ammo = enough_ammo(weapon);
if (current_weapon_enough_ammo && !new_wepon_enough_ammo)
return (true);
if (!current_weapon_enough_ammo && new_wepon_enough_ammo)
return (false);
if (!fsimilar(weapon->GetCondition(),new_weapon->GetCondition(),.05f))
return (weapon->GetCondition() >= new_weapon->GetCondition());
if (weapon->ef_weapon_type() != new_weapon->ef_weapon_type())
return (weapon->Cost() >= new_weapon->Cost());
return (true);
}
bool CAI_Stalker::can_take (CInventoryItem const * item)
{
const CWeapon *new_weapon = smart_cast<const CWeapon*>(item);
if (!new_weapon)
return (false);
bool new_weapon_enough_ammo = enough_ammo(new_weapon);
TIItemContainer::iterator I = inventory().m_all.begin();
TIItemContainer::iterator E = inventory().m_all.end();
for ( ; I != E; ++I)
if (conflicted(*I,new_weapon,new_weapon_enough_ammo,0))
return (false);
return (true);
}
void CAI_Stalker::remove_personal_only_ammo (const CInventoryItem *item)
{
const CWeapon *weapon = smart_cast<const CWeapon*>(item);
VERIFY (weapon);
xr_vector<shared_str>::const_iterator I = weapon->m_ammoTypes.begin();
xr_vector<shared_str>::const_iterator E = weapon->m_ammoTypes.end();
for ( ; I != E; ++I) {
bool found = false;
TIItemContainer::const_iterator i = inventory().m_all.begin();
TIItemContainer::const_iterator e = inventory().m_all.end();
for ( ; i != e; ++i) {
if ((*i)->object().ID() == weapon->ID())
continue;
const CWeapon *temp = smart_cast<const CWeapon*>(*i);
if (!temp)
continue;
if (std::find(temp->m_ammoTypes.begin(),temp->m_ammoTypes.end(),*I) == temp->m_ammoTypes.end())
continue;
found = true;
break;
}
if (found)
continue;
for (i = inventory().m_all.begin(); i != e; ++i) {
if (xr_strcmp(*I,(*i)->object().cNameSect()))
continue;
NET_Packet packet;
u_EventGen (packet,GE_DESTROY,(*i)->object().ID());
u_EventSend (packet);
}
}
}
void CAI_Stalker::update_conflicted (CInventoryItem *item, const CWeapon *new_weapon)
{
if (non_conflicted(item,new_weapon))
return;
remove_personal_only_ammo (item);
item->SetDropManual (TRUE);
}
void CAI_Stalker::on_after_take (const CGameObject *object)
{
if (!g_Alive())
return;
if (!READ_IF_EXISTS(pSettings,r_bool,cNameSect(),"use_single_item_rule",true))
return;
const CWeapon *new_weapon = smart_cast<const CWeapon*>(object);
if (!new_weapon)
return;
TIItemContainer::iterator I = inventory().m_all.begin();
TIItemContainer::iterator E = inventory().m_all.end();
for ( ; I != E; ++I)
update_conflicted (*I,new_weapon);
}
| 412 | 0.93844 | 1 | 0.93844 | game-dev | MEDIA | 0.94162 | game-dev | 0.9254 | 1 | 0.9254 |
ggnkua/Atari_ST_Sources | 2,003 | ASM/Various/Rockyone/mi-3 v428/MI-3/BINARY_1/DEGAS/SOURCE/PACK_PC1.S | * OUTPUT e:\code\synthy.art\curent\fichiers.inl\pack_pc1.inl
* OPT O+,A+,P+
*********** Compactage Degas basse rsolution ST
* 4(sp) L Adresse de l'image
* 8(sp) L Adresse du buffer destination
* En retour dans D0, taille des donnes compactes en octets
; save pc1
;------------------------------------------------------------------------
movem.l d1-d7/a0-a6,-(a7)
movem.l 60(sp),a0-a1
* move.l 4(sp),a0
* move.l 8(sp),a1
lea LineBuffer(pc),a2
even
moveq #2,d5
move.w #200,d7 Nb ligne
bra.s ConvertLine
* dc.b "DegasPacker by Nucleus/HMD"
* EVEN
*
NextLine:
subq.b #1,d6
bmi.s ConvertLine
lea.l 40(a4),a4
NewCode:
move.l a3,a5 Start adr
move.b (a3)+,d0
cmp.l a3,a4
beq.s CodeCOPY
SameLoop:
cmp.b (a3)+,d0
bne.s NotSame
cmp.l a3,a4
bne.s SameLoop
bra.s CodeREPEAT
NotSame:
move.l a3,d1
sub.l a5,d1
cmp.w d5,d1
bne.s CodeREPEAT1
cmp.l a3,a4
beq.s CodeCOPY
move.b -1(a3),d0
NotSameLoop:
move.b (a3)+,d1
cmp.b d0,d1
beq.s Same2
move.b d1,d0
cmp.l a3,a4
bne.s NotSameLoop
CodeCOPY_1:
bra.s CodeCOPY
Same2:
cmp.l a3,a4
beq.s CodeCOPY
cmp.b (a3),d0
bne.s NotSameLoop
sub.l d5,a3
bra.s CodeCOPY
;................
ConvertLine:
subq.w #1,d7
bmi.s EndOfPict
moveq #3,d6
move.l a2,a3
lea 40(a3),a4
lea 40(a4),a5
lea 40(a5),a6
moveq #19,d0
ConvLoop:
move.w (a0)+,(a3)+
move.w (a0)+,(a4)+
move.w (a0)+,(a5)+
move.w (a0)+,(a6)+
dbf d0,ConvLoop
move.l a2,a3
lea 40(a3),a4
bra.s NewCode
CodeCOPY:
move.l a3,d1
sub.l a5,d1
subq.w #1,d1
move.b d1,(a1)+
copy:
move.b (a5)+,(a1)+
dbf d1,copy
cmp.l a3,a4
bne.s NewCode
bra NextLine
CodeREPEAT1:
subq.l #1,a3
CodeREPEAT:
move.l a3,d1
sub.l a5,d1
subq.w #1,d1 Nb pattern-1
neg.b d1
move.b d1,(a1)+
move.b d0,(a1)+
cmp.l a3,a4
bne NewCode
bra NextLine
;..............................................
EndOfPict:
move.l a1,d0
sub.l 64(sp),d0
movem.l (a7)+,d1-d7/a0-a6
rts
even
LineBuffer: ds.b 160
dc.l 25,"HMD!"
| 412 | 0.699755 | 1 | 0.699755 | game-dev | MEDIA | 0.523759 | game-dev | 0.974483 | 1 | 0.974483 |
senchalabs/AppInspector | 1,484 | app/test/siesta-2.0.5-lite/tests/cmd_app_touch/touch/resources/themes/stylesheets/sencha-touch/mountainview/src/field/_Checkbox.scss | /**
* @class Ext.field.Checkbox
*/
@mixin checkmark($color: #000){
@extend .x-checkmark-base;
color: $color;
}
.x-checkmark-base {
position: absolute;
top: -2px;
right: -3px;
bottom: 0;
content: '3';
font-family: 'Pictos';
font-size: 23px;
text-align: right;
line-height: 1.9em;
@include text-shadow(
0 -1px $background-color,
0 1px $background-color,
-1px 0 $background-color,
1px 0 $background-color,
0 2px 4px rgba($base-color, .3),
0 -2px 4px rgba($base-color, .3),
2px 0 4px rgba($base-color, .3),
-2px 0 4px rgba($base-color, .3)
);
}
.x-field-checkbox .x-field-mask::before,
.x-field-radio .x-field-mask::before,
.x-field-radio .x-field-mask::after {
content: '';
position: absolute;
top: 50%;
right: 0;
margin-top: -10px;
height: 20px;
width: 20px;
border: 1px solid $foreground-color;
}
.x-field-checkbox .x-field-mask::after {
@include checkmark($base-color);
visibility: hidden;
}
.x-input-checkbox,
.x-input-radio {
visibility: hidden;
}
.x-input-el:checked + .x-field-mask::after {
visibility: visible;
}
.x-item-disabled {
&.x-field-checkbox .x-field-mask::before,
&.x-field-radio .x-field-mask::before {
border-color: $secondary-color;
}
&.x-field-checkbox .x-input-el:checked + .x-field-mask::after {
text-shadow: none;
color: $foreground-color;
}
}
| 412 | 0.847978 | 1 | 0.847978 | game-dev | MEDIA | 0.602662 | game-dev | 0.54949 | 1 | 0.54949 |
PaperMC/Paper-archive | 2,697 | patches/server/0197-Make-shield-blocking-delay-configurable.patch | From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: BillyGalbreath <Blake.Galbreath@GMail.com>
Date: Sat, 16 Jun 2018 01:18:16 -0500
Subject: [PATCH] Make shield blocking delay configurable
diff --git a/src/main/java/net/minecraft/world/entity/LivingEntity.java b/src/main/java/net/minecraft/world/entity/LivingEntity.java
index bddd731cbdf88b349598d92f45a5af30b46e34ef..9d0b7fc2e6beee1acb28a0dd473023beaafd86e5 100644
--- a/src/main/java/net/minecraft/world/entity/LivingEntity.java
+++ b/src/main/java/net/minecraft/world/entity/LivingEntity.java
@@ -4109,12 +4109,24 @@ public abstract class LivingEntity extends Entity implements Attackable {
if (this.isUsingItem() && !this.useItem.isEmpty()) {
Item item = this.useItem.getItem();
- return item.getUseAnimation(this.useItem) != ItemUseAnimation.BLOCK ? null : (item.getUseDuration(this.useItem, this) - this.useItemRemaining < 5 ? null : this.useItem);
+ return item.getUseAnimation(this.useItem) != ItemUseAnimation.BLOCK ? null : (item.getUseDuration(this.useItem, this) - this.useItemRemaining < getShieldBlockingDelay() ? null : this.useItem); // Paper - Make shield blocking delay configurable
} else {
return null;
}
}
+ // Paper start - Make shield blocking delay configurable
+ public int shieldBlockingDelay = this.level().paperConfig().misc.shieldBlockingDelay;
+
+ public int getShieldBlockingDelay() {
+ return shieldBlockingDelay;
+ }
+
+ public void setShieldBlockingDelay(int shieldBlockingDelay) {
+ this.shieldBlockingDelay = shieldBlockingDelay;
+ }
+ // Paper end - Make shield blocking delay configurable
+
public boolean isSuppressingSlidingDownLadder() {
return this.isShiftKeyDown();
}
diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftLivingEntity.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftLivingEntity.java
index 445126b24a8c5c9104b14838661c53382bd65e53..4d09ba705220d397adedab27c31d604447c51319 100644
--- a/src/main/java/org/bukkit/craftbukkit/entity/CraftLivingEntity.java
+++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftLivingEntity.java
@@ -873,5 +873,15 @@ public class CraftLivingEntity extends CraftEntity implements LivingEntity {
public void setArrowsStuck(final int arrows) {
this.getHandle().setArrowCount(arrows);
}
+
+ @Override
+ public int getShieldBlockingDelay() {
+ return getHandle().getShieldBlockingDelay();
+ }
+
+ @Override
+ public void setShieldBlockingDelay(int delay) {
+ getHandle().setShieldBlockingDelay(delay);
+ }
// Paper end
}
| 412 | 0.824459 | 1 | 0.824459 | game-dev | MEDIA | 0.954198 | game-dev | 0.857851 | 1 | 0.857851 |
Ferra13671/BThack | 10,026 | src/main/java/com/ferra13671/BThack/impl/Modules/Player/ActionBot/Config/ActionBotTasks/MoveTask.java | package com.ferra13671.BThack.impl.Modules.Player.ActionBot.Config.ActionBotTasks;
import com.ferra13671.BThack.api.Motion.Align.AlignToBlockCenter;
import com.ferra13671.BThack.BThack;
import com.ferra13671.BThack.api.Utils.InputUtils;
import com.ferra13671.BThack.core.Client.ModuleList;
import com.ferra13671.BThack.core.Client.Systems.FileSystem.JsonUtils;
import com.ferra13671.BThack.events.Entity.UpdateInputEvent;
import com.ferra13671.BThack.managers.managers.Place.PlaceManager;
import com.ferra13671.BThack.managers.managers.Break.BreakManager;
import com.ferra13671.BThack.managers.managers.Break.SimpleBreakThread;
import com.ferra13671.BThack.managers.Managers;
import com.ferra13671.BThack.managers.managers.Thread.ThreadClosedException;
import com.ferra13671.BThack.managers.managers.TravelChange.TravelChanger;
import com.ferra13671.BThack.api.Utils.ChatUtils;
import com.ferra13671.BThack.api.Utils.Rotate.RotateUtils;
import com.ferra13671.BThack.impl.Modules.Player.ActionBot.Config.ActionBotConfig;
import com.ferra13671.BThack.impl.Modules.Player.ActionBot.Config.ActionBotTask;
import com.ferra13671.MegaEvents.Base.EventSubscriber;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import net.minecraft.block.FlowerBlock;
import net.minecraft.util.Formatting;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
import java.util.Arrays;
public class MoveTask extends ActionBotTask {
private final Type type;
private final double needX;
private final double needZ;
private final boolean scaffold;
public MoveTask(double needX, double needZ, boolean scaffold, Type type) {
super("Move");
this.mode = "Move";
this.needX = needX;
this.needZ = needZ;
this.scaffold = scaffold;
this.type = type;
this.taskDescription = Arrays.asList(
"When the task is activated, the player starts walking to the specified coordinates.",
"Coordinates should be entered by the ratio of the player's coordinates.",
"I.e., if you need to write 5 at x coordinates, if you want the",
"the player has moved 5 blocks along the x-coordinate."
);
}
public double maxX;
public double minX;
public double maxZ;
public double minZ;
protected boolean cancel;
private float yaw = -99999999;
private boolean moving = false;
private boolean jumping = false;
@SuppressWarnings("DataFlowIssue")
private final TravelChanger travelChanger = new TravelChanger(1000,
() -> new Float[]{yaw, mc.player.getPitch()},
() -> false,
() -> false
);
@EventSubscriber
@SuppressWarnings({"unused", "DataFlowIssue"})
public void onInput(UpdateInputEvent e) {
InputUtils.setInput(moving, false, false, false, jumping, mc.player.input.playerInput.sneak(), mc.player.input.playerInput.sprint());
mc.player.input.movementForward = moving ? 1 : 0;
mc.player.input.movementSideways = 0;
}
@Override
@SuppressWarnings("DataFlowIssue")
public void play() throws ThreadClosedException {
alignAction();
Managers.TRAVEL_CHANGE_MANAGER.addChanger(travelChanger);
BThack.EVENT_BUS.register(this);
boolean scaffoldActivated = true;
try {
double tempX = mc.player.getX() + needX;
double tempZ = mc.player.getZ() + needZ;
if (scaffold) {
scaffoldActivated = ModuleList.scaffold.isEnabled();
ModuleList.scaffold.setEnabled(true);
}
maxX = tempX + 0.15;
minX = tempX - 0.15;
maxZ = tempZ + 0.15;
minZ = tempZ - 0.15;
while (toFarX() || toFarZ()) {
thread.checkThreadStopped();
yaw = RotateUtils.rotations(new Vec3d(tempX, mc.player.getY(), tempZ))[0];
moving = !BreakManager.isDestroying || type != Type.Through_Obstacles;
if (scaffold) {
if (!ModuleList.scaffold.isEnabled()) {
ModuleList.scaffold.setEnabled(true);
}
}
if (mc.player.horizontalCollision) {
switch (type) {
case Default -> {
ChatUtils.sendMessage("[ActionBot: MoveTask] " + Formatting.YELLOW + "The player ran into an obstacle. Skipping a task.");
disableAction(scaffoldActivated);
}
case AutoJump -> tryJump();
case Through_Obstacles -> {
moving = false;
if (!BreakManager.isDestroying) {
double x = mc.player.getX() + RotateUtils.getCordFactorFromDirection((int) yaw)[0];
double z = mc.player.getZ() + RotateUtils.getCordFactorFromDirection((int) yaw)[1];
double y = mc.player.getY() + 0.5;
BlockPos blockPos = BlockPos.ofFloored(x, y, z);
if (PlaceManager.ignoreBlocks.contains(mc.world.getBlockState(blockPos).getBlock()) || mc.world.isAir(blockPos) || mc.world.getBlockState(blockPos).getBlock() instanceof FlowerBlock) {
blockPos = new BlockPos(blockPos.getX(), blockPos.getY() + 1, blockPos.getZ());
}
SimpleBreakThread destroyThread = new SimpleBreakThread(blockPos);
destroyThread.start();
}
}
}
}
if (!toFarX() && !toFarZ()) {
disableAction(scaffoldActivated);
return;
}
if (cancel) {
disableAction(scaffoldActivated);
return;
}
Thread.yield();
}
} finally {
BThack.EVENT_BUS.unregister(this);
Managers.TRAVEL_CHANGE_MANAGER.removeChanger(travelChanger);
alignAction();
disableAction(scaffoldActivated);
thread.checkThreadStopped();
}
}
private void disableScaffold(boolean scaffoldEnabled) {
if (scaffold) {
if (!scaffoldEnabled) {
ModuleList.scaffold.setEnabled(false);
}
}
}
@SuppressWarnings("DataFlowIssue")
private boolean toFarX() {
return mc.player.getX() > maxX || mc.player.getX() < minX;
}
@SuppressWarnings("DataFlowIssue")
private boolean toFarZ() {
return mc.player.getZ() > maxZ || mc.player.getZ() < minZ;
}
@SuppressWarnings("DataFlowIssue")
private void tryJump() throws ThreadClosedException {
double oldPosY = mc.player.getY();
jumping = true;
moving = true;
sleepThread(600);
thread.checkThreadStopped();
moving = false;
jumping = false;
if (mc.player.getY() < oldPosY + 0.4) {
jumping = true;
moving = true;
sleepThread(600);
thread.checkThreadStopped();
jumping = false;
moving = false;
}
if (mc.player.getY() < oldPosY + 0.4) {
jumping = true;
moving = true;
sleepThread(600);
thread.checkThreadStopped();
jumping = false;
moving = false;
}
if (mc.player.getY() < oldPosY + 0.4) {
cancel = true;
}
}
public void alignAction() throws ThreadClosedException {
thread.checkThreadStopped();
AlignToBlockCenter alignToBlockCenter = new AlignToBlockCenter();
alignToBlockCenter.align();
do {
if (thread.isThreadClosed()) {
alignToBlockCenter.getThread().closeThread();
thread.stopOnException();
}
sleepThread(50);
} while (alignToBlockCenter.isMoving());
}
public void disableAction(boolean scaffoldActivated) {
moving = false;
cancel = false;
disableScaffold(scaffoldActivated);
}
public double getNeedX() {
return this.needX;
}
public double getNeedZ() {
return this.needZ;
}
public boolean isScaffold() {
return this.scaffold;
}
public Type getType() {
return this.type;
}
@Override
public String getButtonName() {
return getName() + ": X: " + getNeedX() + " Z: " + getNeedZ() + " Scaffold: " + isScaffold() + " Type: " + getType().name();
}
@Override
public void save(JsonObject jsonObject) {
String type = getType().name();
jsonObject.add("NeedX", new JsonPrimitive(getNeedX()));
jsonObject.add("NeedZ", new JsonPrimitive(getNeedZ()));
jsonObject.add("Scaffold", new JsonPrimitive(isScaffold()));
jsonObject.add("Type", new JsonPrimitive(type));
}
@Override
public void load(JsonObject jsonObject) {
if (JsonUtils.equalsNull(jsonObject, "NeedX", "NeedZ", "Scaffold", "Type")) return;
double needX = jsonObject.get("NeedX").getAsDouble();
double needZ = jsonObject.get("NeedZ").getAsDouble();
boolean scaffold = jsonObject.get("Scaffold").getAsBoolean();
String type = jsonObject.get("Type").getAsString();
Type moveType = Type.Default;
for (Type e : Type.values()) {
if (e.name().equals(type)) {
moveType = e;
break;
}
}
ActionBotConfig.tasks.add(new MoveTask(needX, needZ, scaffold, moveType));
}
public enum Type {
Default,
AutoJump,
Through_Obstacles
}
}
| 412 | 0.933303 | 1 | 0.933303 | game-dev | MEDIA | 0.850092 | game-dev | 0.965403 | 1 | 0.965403 |
mit-pdos/biscuit | 2,859 | src/syscall/asm_darwin_arm.s | // Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
#include "textflag.h"
//
// System call support for ARM, Darwin
//
// func Syscall(syscall uintptr, a1, a2, a3 uintptr) (r1, r2, err uintptr)
TEXT ·Syscall(SB),NOSPLIT,$0-28
BL runtime·entersyscall(SB)
MOVW trap+0(FP), R12
MOVW a1+4(FP), R0
MOVW a2+8(FP), R1
MOVW a3+12(FP), R2
SWI $0x80
BCC ok
MOVW $-1, R1
MOVW R1, r1+16(FP) // r1
MOVW $0, R2
MOVW R2, r2+20(FP) // r2
MOVW R0, err+24(FP) // err
BL runtime·exitsyscall(SB)
RET
ok:
MOVW R0, r1+16(FP) // r1
MOVW R1, r2+20(FP) // r2
MOVW $0, R0
MOVW R0, err+24(FP) // err
BL runtime·exitsyscall(SB)
RET
// func RawSyscall(trap uintptr, a1, a2, a3 uintptr) (r1, r2, err uintptr)
TEXT ·RawSyscall(SB),NOSPLIT,$0-28
MOVW trap+0(FP), R12 // syscall entry
MOVW a1+4(FP), R0
MOVW a2+8(FP), R1
MOVW a3+12(FP), R2
SWI $0x80
BCC ok1
MOVW $-1, R1
MOVW R1, r1+16(FP) // r1
MOVW $0, R2
MOVW R2, r2+20(FP) // r2
MOVW R0, err+24(FP) // err
RET
ok1:
MOVW R0, r1+16(FP) // r1
MOVW R1, r2+20(FP) // r2
MOVW $0, R0
MOVW R0, err+24(FP) // err
RET
// func Syscall6(trap uintptr, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2, err uintptr)
TEXT ·Syscall6(SB),NOSPLIT,$0-40
BL runtime·entersyscall(SB)
MOVW trap+0(FP), R12 // syscall entry
MOVW a1+4(FP), R0
MOVW a2+8(FP), R1
MOVW a3+12(FP), R2
MOVW a4+16(FP), R3
MOVW a5+20(FP), R4
MOVW a6+24(FP), R5
SWI $0x80
BCC ok6
MOVW $-1, R1
MOVW R1, r1+28(FP) // r1
MOVW $0, R2
MOVW R2, r2+32(FP) // r2
MOVW R0, err+36(FP) // err
BL runtime·exitsyscall(SB)
RET
ok6:
MOVW R0, r1+28(FP) // r1
MOVW R1, r2+32(FP) // r2
MOVW $0, R0
MOVW R0, err+36(FP) // err
BL runtime·exitsyscall(SB)
RET
// func RawSyscall6(trap uintptr, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2, err uintptr)
TEXT ·RawSyscall6(SB),NOSPLIT,$0-40
MOVW trap+0(FP), R12 // syscall entry
MOVW a1+4(FP), R0
MOVW a2+8(FP), R1
MOVW a3+12(FP), R2
MOVW a4+16(FP), R3
MOVW a5+20(FP), R4
MOVW a6+24(FP), R5
SWI $0x80
BCC ok2
MOVW $-1, R1
MOVW R1, r1+28(FP) // r1
MOVW $0, R2
MOVW R2, r2+32(FP) // r2
MOVW R0, err+36(FP) // err
RET
ok2:
MOVW R0, r1+28(FP) // r1
MOVW R1, r2+32(FP) // r2
MOVW $0, R0
MOVW R0, err+36(FP) // err
RET
// Actually Syscall7.
TEXT ·Syscall9(SB),NOSPLIT,$0-52
BL runtime·entersyscall(SB)
MOVW num+0(FP), R12 // syscall entry
MOVW a1+4(FP), R0
MOVW a2+8(FP), R1
MOVW a3+12(FP), R2
MOVW a4+16(FP), R3
MOVW a5+20(FP), R4
MOVW a6+24(FP), R5
MOVW a7+28(FP), R6
SWI $0x80
BCC ok9
MOVW $-1, R1
MOVW R1, r1+40(FP) // r1
MOVW $0, R2
MOVW R2, r2+44(FP) // r2
MOVW R0, err+48(FP) // err
BL runtime·exitsyscall(SB)
RET
ok9:
MOVW R0, r1+40(FP) // r1
MOVW R1, r2+44(FP) // r2
MOVW $0, R0
MOVW R0, err+48(FP) // err
BL runtime·exitsyscall(SB)
RET
| 412 | 0.717615 | 1 | 0.717615 | game-dev | MEDIA | 0.411874 | game-dev,os-kernel | 0.927543 | 1 | 0.927543 |
BatteryAcid/godot-3d-multiplayer-template | 3,455 | addons/netfox.extras/weapon/network-weapon-hitscan-3d.gd | extends Node3D
class_name NetworkWeaponHitscan3D
## A 3D-specific implementation of a networked hitscan (raycast) weapon.
## Maximum distance to cast the ray
@export var max_distance: float = 1000.0
## Mask used to detect raycast hits
@export_flags_3d_physics var collision_mask: int = 0xFFFFFFFF
## Colliders excluded from raycast hits
@export var exclude: Array[RID] = []
var _weapon: _NetworkWeaponProxy
## Try to fire the weapon and return the projectile.
## [br][br]
## Returns true if the weapon was fired.
func fire() -> bool:
if not can_fire():
return false
_apply_data(_get_data())
_after_fire()
return true
## Check whether this weapon can be fired.
func can_fire() -> bool:
return _weapon.can_fire()
func _init():
_weapon = _NetworkWeaponProxy.new()
add_child(_weapon, true, INTERNAL_MODE_BACK)
_weapon.owner = self
_weapon.c_can_fire = _can_fire
_weapon.c_can_peer_use = _can_peer_use
_weapon.c_after_fire = _after_fire
_weapon.c_spawn = _spawn
_weapon.c_get_data = _get_data
_weapon.c_apply_data = _apply_data
_weapon.c_is_reconcilable = _is_reconcilable
_weapon.c_reconcile = _reconcile
## Override this method with your own can fire logic.
## [br][br]
## See [NetworkWeapon].
func _can_fire() -> bool:
return true
## Override this method to check if a given peer can use this weapon.
## [br][br]
## See [NetworkWeapon].
func _can_peer_use(peer_id: int) -> bool:
return true
## Override this method to run any logic needed after successfully firing the
## weapon.
## [br][br]
## See [NetworkWeapon].
func _after_fire():
pass
func _spawn():
# No projectile is spawned for a hitscan weapon.
pass
func _get_data() -> Dictionary:
# Collect data needed to synchronize the firing event.
return {
"origin": global_transform.origin,
"direction": -global_transform.basis.z # Assuming forward direction.
}
func _apply_data(data: Dictionary):
# Reproduces the firing event on all peers.
var origin = data["origin"] as Vector3
var direction = data["direction"] as Vector3
# Perform the raycast from origin in the given direction.
var space_state = get_world_3d().direct_space_state
# Create a PhysicsRayQueryParameters3D object.
var ray_params = PhysicsRayQueryParameters3D.new()
ray_params.from = origin
ray_params.to = origin + direction * max_distance
# Set collision masks or exclude objects:
ray_params.collision_mask = collision_mask
ray_params.exclude = exclude
var result = space_state.intersect_ray(ray_params)
if result:
# Handle the hit result, such as spawning hit effects.
_on_hit(result)
# Play firing effects on all peers.
_on_fire()
func _is_reconcilable(request_data: Dictionary, local_data: Dictionary) -> bool:
# Always reconcilable
return true
func _reconcile(local_data: Dictionary, remote_data: Dictionary):
# Nothing to do on reconcile
pass
## Override to implement raycast hit logic.
## [br][br]
## The parameter is the result of a
## [method PhysicsDirectSpaceState3D.intersect_ray] call.
func _on_hit(result: Dictionary):
# Implement hit effect logic here.
# var hit_position = result.position
# var hit_normal = result.normal
# var collider = result.collider
# For example, you might emit a signal or instantiate a hit effect scene:
# emit_signal("hit_detected", hit_position, hit_normal, collider)
pass
## Override to implement firing effects, like muzzle flash or sound.
func _on_fire():
# Implement firing effect logic here.
pass
| 412 | 0.788795 | 1 | 0.788795 | game-dev | MEDIA | 0.967878 | game-dev | 0.697677 | 1 | 0.697677 |
diplomacy/research | 4,903 | diplomacy_research/players/dummy_player.py | # ==============================================================================
# Copyright 2019 - Philip Paquette
#
# NOTICE: 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.
# ==============================================================================
""" Dummy Player
- Contains a class representing a player that chooses to never do anything
"""
import logging
from tornado import gen
from diplomacy_research.players.player import Player
# Constants
LOGGER = logging.getLogger(__name__)
class DummyPlayer(Player):
""" Dummy Player Class """
@property
def is_trainable(self):
""" Returns a boolean that indicates if the player wants to be trained or not """
return False
@gen.coroutine
def get_orders_details_with_proto(self, state_proto, power_name, phase_history_proto, possible_orders_proto,
**kwargs):
""" Gets the orders (and the corresponding policy details) for the locs the power should play.
:param state_proto: A `.proto.game.State` representation of the state of the game.
:param power_name: The name of the power we are playing
:param phase_history_proto: A list of `.proto.game.PhaseHistory`. This represents prev phases.
:param possible_orders_proto: A `proto.game.PossibleOrders` object representing possible order for each loc.
:param kwargs: Additional optional kwargs:
- player_seed: If set. Override the player_seed to use for the model based player.
- noise: If set. Override the noise to use for the model based player.
- temperature: If set. Override the temperature to use for the model based player.
- dropout_rate: If set. Override the dropout_rate to use for the model based player.
- with_state_value: Boolean that indicates to also query the value function.
- retry_on_failure: Boolean that indicates to retry querying from the model if an error is encountered.
:return: If with_state_value=False (default), a tuple consisting of:
1) The list of orders the power should play (e.g. ['A PAR H', 'A MAR - BUR', ...])
2) The policy details ==> {'locs', 'tokens', 'log_probs', 'draw_action', 'draw_prob'}
If with_state_value=True, a tuple consisting of:
1) The list of orders the power should play (e.g. ['A PAR H', 'A MAR - BUR', ...])
2) The policy details ==> {'locs', 'tokens', 'log_probs', 'draw_action', 'draw_prob'}
3) The state value for the given state
"""
# pylint: disable=unused-argument
if kwargs.get('with_state_value', False):
return [], None, 0.
return [], None
@gen.coroutine
def get_state_value_with_proto(self, state_proto, power_name, phase_history_proto, possible_orders_proto=None,
**kwargs):
""" Calculates the player's value of the state of the game for a given power
:param state_proto: A `.proto.game.State` representation of the state of the game.
:param power_name: The power name for which we want to retrieve the value
:param phase_history_proto: A list of `.proto.game.PhaseHistory`. This represents prev phases.
:param possible_orders_proto: A `proto.game.PossibleOrders` object representing possible order for each loc.
:param kwargs: Additional optional kwargs:
- player_seed: If set. Override the player_seed to use for the model based player.
- noise: If set. Override the noise to use for the model based player.
- temperature: If set. Override the temperature to use for the model based player.
- dropout_rate: If set. Override the dropout_rate to use for the model based player.
- retry_on_failure: Boolean that indicates to retry querying from the model if an error is encountered.
:return: A float representing the value of the state of the game to the specified power
"""
# pylint: disable=unused-argument
LOGGER.warning('There are no models available to query state value. Returning a value of 0.')
return 0.
| 412 | 0.868964 | 1 | 0.868964 | game-dev | MEDIA | 0.928756 | game-dev | 0.922567 | 1 | 0.922567 |
traggett/UnityFramework | 6,368 | Framework/Animation/AnimatorLOD/AnimatorLODOverrideController.cs | using System.Collections.Generic;
using UnityEngine;
namespace Framework
{
namespace Animations
{
public class AnimatorLODOverrideController : AnimatorOverrideController
{
#region Private Data
private struct AnimationsLOD
{
public readonly int _minLODLevel;
public readonly List<KeyValuePair<AnimationClip, AnimationClip>> _overrideClipsList;
public readonly Avatar _avatar;
public AnimationsLOD(int lodLevel, List<KeyValuePair<AnimationClip, AnimationClip>> overrideClipsList, Avatar avatar)
{
_minLODLevel = lodLevel;
_overrideClipsList = overrideClipsList;
_avatar = avatar;
}
}
private AnimationsLOD[] _animationsLODs;
private int _currentLOD;
private int _currentAnimationLODSet;
#endregion
#region Public Interface
public AnimatorLODOverrideController(RuntimeAnimatorController controller, AnimatorLODControllerOverrides.AnimatorLOD[] animatorLODs) : base(controller)
{
_animationsLODs = new AnimationsLOD[animatorLODs.Length + 1];
//Create default (zero) LOD with no overrides
{
List<KeyValuePair<AnimationClip, AnimationClip>> overrideClips = new List<KeyValuePair<AnimationClip, AnimationClip>>();
foreach (AnimationClip origClip in controller.animationClips)
{
overrideClips.Add(new KeyValuePair<AnimationClip, AnimationClip>(origClip, null));
}
_animationsLODs[0] = new AnimationsLOD(0, overrideClips, null);
}
//Create LODs
for (int i = 0; i < animatorLODs.Length; i++)
{
List<KeyValuePair<AnimationClip, AnimationClip>> overrideClips = new List<KeyValuePair<AnimationClip, AnimationClip>>();
foreach (AnimationClip origClip in controller.animationClips)
{
AnimationClip overrideClip = null;
for (int j = 0; j < animatorLODs[i]._overrideClips.Length; j++)
{
if (animatorLODs[i]._overrideClips[j]._originalClip == origClip)
{
overrideClip = animatorLODs[i]._overrideClips[j]._overrideClip;
break;
}
}
overrideClips.Add(new KeyValuePair<AnimationClip, AnimationClip>(origClip, overrideClip));
}
_animationsLODs[i + 1] = new AnimationsLOD(animatorLODs[i]._minLODLevel, overrideClips, CreateAvatar(controller, animatorLODs[i]._avatarMask));
}
_currentLOD = 0;
_currentAnimationLODSet = 0;
}
private static Avatar CreateAvatar(RuntimeAnimatorController controller, AvatarMask avatarMask)
{
GameObject avatarGameObject = new GameObject(controller.name + " LOD Avatar");
if (avatarMask != null)
{
for (int i = 0; i < avatarMask.transformCount; i++)
{
if (avatarMask.GetTransformActive(i))
{
string[] pathObjects = avatarMask.GetTransformPath(i).Split('/');
AddPath(avatarGameObject.transform, pathObjects, 0);
}
}
}
Avatar avatar = AvatarBuilder.BuildGenericAvatar(avatarGameObject, "");
Destroy(avatarGameObject);
return avatar;
}
private static void AddPath(Transform root, string[] pathObjects, int pathIndex)
{
if (pathIndex < pathObjects.Length)
{
Transform pathObject = null;
foreach (Transform child in root)
{
if (child.name == pathObjects[pathIndex])
{
pathObject = child;
break;
}
}
if (pathObject == null)
{
GameObject childObject = new GameObject(pathObjects[pathIndex]);
childObject.transform.SetParent(root, false);
pathObject = childObject.transform;
}
AddPath(pathObject, pathObjects, pathIndex + 1);
}
}
public bool OnLODLevelChanged(int level)
{
//Work out animation set for this LOD level
int animationSet = GetAnimationSetForLODLevel(level);
//If different to current set, set it
if (animationSet != -1 && level != _currentLOD)
{
ApplyOverrides(_animationsLODs[animationSet]._overrideClipsList);
_currentLOD = level;
_currentAnimationLODSet = animationSet;
return true;
}
return false;
}
public int GetCurrentLOD()
{
return _currentLOD;
}
public Avatar GetAvatar()
{
return _animationsLODs[_currentAnimationLODSet]._avatar;
}
#endregion
#region Private Functions
private int GetAnimationSetForLODLevel(int level)
{
if (level < 0)
{
return _animationsLODs.Length - 1;
}
for (int i = _animationsLODs.Length - 1; i >= 0; i--)
{
if (level >= _animationsLODs[i]._minLODLevel || i == 0)
{
return i;
}
}
return -1;
}
#endregion
}
}
} | 412 | 0.740481 | 1 | 0.740481 | game-dev | MEDIA | 0.84909 | game-dev | 0.966476 | 1 | 0.966476 |
529324416/MissionSystem | 1,818 | Assets/ParadoxNotion/NodeCanvas/Tasks/Actions/Animator/MecanimSetFloat.cs | using NodeCanvas.Framework;
using ParadoxNotion.Design;
using UnityEngine;
namespace NodeCanvas.Tasks.Actions
{
[Name("Set Parameter Float")]
[Category("Animator")]
[Description("You can either use a parameter name OR hashID. Leave the parameter name empty or none to use hashID instead.")]
public class MecanimSetFloat : ActionTask<Animator>
{
public BBParameter<string> parameter;
public BBParameter<int> parameterHashID;
public BBParameter<float> setTo;
[SliderField(0, 1)]
public float transitTime = 0.25f;
private float currentValue;
protected override string info {
get { return string.Format("Mec.SetFloat {0} to {1}", string.IsNullOrEmpty(parameter.value) && !parameter.useBlackboard ? parameterHashID.ToString() : parameter.ToString(), setTo); }
}
protected override void OnExecute() {
if ( transitTime <= 0 ) {
Set(setTo.value);
EndAction();
return;
}
currentValue = Get();
}
protected override void OnUpdate() {
Set(Mathf.Lerp(currentValue, setTo.value, elapsedTime / transitTime));
if ( elapsedTime >= transitTime ) {
EndAction(true);
}
}
float Get() {
if ( !string.IsNullOrEmpty(parameter.value) ) {
return agent.GetFloat(parameter.value);
}
return agent.GetFloat(parameterHashID.value);
}
void Set(float newValue) {
if ( !string.IsNullOrEmpty(parameter.value) ) {
agent.SetFloat(parameter.value, newValue);
return;
}
agent.SetFloat(parameterHashID.value, newValue);
}
}
} | 412 | 0.917042 | 1 | 0.917042 | game-dev | MEDIA | 0.509531 | game-dev | 0.925759 | 1 | 0.925759 |
AXiX-official/CrossCoreLuascripts | 4,040 | ios/Others/SignInGold.lua | local key = nil
local targetTime = 0
local cfg =nil
function Awake()
eventMgr = ViewEvent.New()
eventMgr:AddListener(EventType.Activity_SignIn, ESignCB)
layout = ComUtil.GetCom(hsv, "UIInfinite")
layout:Init("UIs/SignInContinue5/SignInGoldItem", LayoutCallBack, true)
fade = ComUtil.GetCom(gameObject, "ActionFade")
end
function Update()
if targetTime > 0 then
local tab = TimeUtil:GetTimeTab(targetTime - TimeUtil:GetTime())
local hour = tab[2] % 24
LanguageMgr:SetText(txtTime2, 13020, tab[1]," ".. hour .. ":" .. tab[3] .. ":" .. tab[4])
end
end
function LayoutCallBack(index)
local lua = layout:GetItemLua(index)
if (lua) then
local _data = curDatas[index]
local info = SignInMgr:GetDataByKey(key)
local isCuyDayDone = info:CheckIsDone()
lua.Refresh(_data, isCuyDayDone)
end
end
function OnDestroy()
eventMgr:ClearListener()
ReleaseCSComRefs()
end
function Refresh(data,elseData)
local isSingIn = data.isSingIn ~= nil and data.isSingIn or false
key = data.key
cfg = elseData and elseData.cfg or nil
-- CSAPI.SetGOActive(mask, isSingIn)
if (isSingIn) then
EventMgr.Dispatch(EventType.Activity_Click)
end
SetDatas()
SetTime()
end
-- 如果是12或者倒数12位,则额外加多2个空数据填位
function SetDatas()
curDatas = {}
local info = SignInMgr:GetDataByKey(key)
local curDay = info:GetRealDay()
datas = SignInMgr:GetDayInfos(key)
for i, v in ipairs(datas) do
table.insert(curDatas, v)
end
layout:IEShowList(#curDatas, nil, curDay)
end
-- 签到回调
function ESignCB(proto)
-- if(isClick) then return end
local _key = SignInMgr:GetDataKey(proto.id, proto.index)
if (key ~= _key) then
return
end
if proto.isOk == false then
EventMgr.Dispatch(EventType.Acitivty_List_Pop)
return
end
SignInMgr:AddCacheRecord(key)
-- CSAPI.SetGOActive(mask, false)
-- layout:UpdateList()
SetDatas()
isClick = false
ActivityMgr:SetListData(cfg.id, {
key = _key
})
end
function SetTime()
local info = SignInMgr:GetDataByKey(key)
local cfg = Cfgs.CfgSignReward:GetByID(info.proto.id)
if cfg then
local startTimeStr = StringUtil:split(cfg.begTime, " ")[1]
local targetTimeStr = StringUtil:split(cfg.endTime, " ")[1]
CSAPI.SetText(txtTime, startTimeStr .. "~" .. targetTimeStr)
targetTime = TimeUtil:GetTimeStampBySplit(cfg.endTime)
end
end
function PlayFade(isFade, cb)
local star = isFade and 1 or 0
local target = isFade and 0 or 1
if not IsNil(fade) then
fade:Play(star, target, 200, 0, function()
if cb then
cb()
end
end)
end
end
-- 自动签到
function OnClickMask()
if (not isClick) then
isClick = true
local data = SignInMgr:GetDataByKey(key)
ClientProto:AddSign(data:GetID())
if (data) then
local rewards = {}
for i, info in pairs(data:GetRewardCfg().infos) do
if (i == data:GetIndex()) then
for k, m in pairs(info.rewards) do
table.insert(rewards, {
id = m[1],
num = m[2]
})
end
end
end
local taData = {
reson = "领取活动奖励",
activity_name = "通用签到",
task_id = data.proto.index,
task_name = data.proto.index,
item_gain = rewards
}
if CSAPI.IsADV()==false then
BuryingPointMgr:TrackEvents("activity_attend", taData)
end
end
end
end
-- 点击背景
function OnClickClose()
view:Close()
end
----#Start#----
----释放CS组件引用(生成时会覆盖,请勿改动,尽量把该内容放置在文件结尾。)
function ReleaseCSComRefs()
gameObject = nil;
transform = nil;
this = nil;
hsv = nil;
mask = nil;
view = nil;
end
----#End#----
| 412 | 0.876395 | 1 | 0.876395 | game-dev | MEDIA | 0.707279 | game-dev,desktop-app | 0.961863 | 1 | 0.961863 |
aers/FFXIVClientStructs | 2,582 | FFXIVClientStructs/FFXIV/Client/Game/InventoryType.cs | namespace FFXIVClientStructs.FFXIV.Client.Game;
public enum InventoryType : uint {
Inventory1 = 0,
Inventory2 = 1,
Inventory3 = 2,
Inventory4 = 3,
EquippedItems = 1000,
Currency = 2000,
Crystals = 2001,
MailEdit = 2002, // used by LetterEditor
Mail = 2003,
KeyItems = 2004,
HandIn = 2005,
Unknown2006 = 2006,
BlockedItems = 2007,
Unknown2008 = 2008,
Examine = 2009,
Reclaim = 2010, // LegacyItemStorage, HousingWithdrawStorage
HousingExteriorAppearanceEdit = 2011,
HousingInteriorAppearanceEdit = 2012,
ReconstructionBuyback = 2013, // Doman Enclave Reconstruction Reclamation Box
ArmoryOffHand = 3200,
ArmoryHead = 3201,
ArmoryBody = 3202,
ArmoryHands = 3203,
ArmoryWaist = 3204,
ArmoryLegs = 3205,
ArmoryFeets = 3206,
ArmoryEar = 3207,
ArmoryNeck = 3208,
ArmoryWrist = 3209,
ArmoryRings = 3300,
ArmorySoulCrystal = 3400,
ArmoryMainHand = 3500,
SaddleBag1 = 4000,
SaddleBag2 = 4001,
PremiumSaddleBag1 = 4100,
PremiumSaddleBag2 = 4101,
Cosmopouch1 = 5000, // Cosmic Exploration: Mission Inventory (including Fishing Bait)
Cosmopouch2 = 5001, // Cosmic Exploration: Mech Ops Inventory
Invalid = 9999,
RetainerPage1 = 10000,
RetainerPage2 = 10001,
RetainerPage3 = 10002,
RetainerPage4 = 10003,
RetainerPage5 = 10004,
RetainerPage6 = 10005,
RetainerPage7 = 10006,
RetainerEquippedItems = 11000,
RetainerGil = 12000,
RetainerCrystals = 12001,
RetainerMarket = 12002,
FreeCompanyPage1 = 20000,
FreeCompanyPage2 = 20001,
FreeCompanyPage3 = 20002,
FreeCompanyPage4 = 20003,
FreeCompanyPage5 = 20004,
FreeCompanyGil = 22000,
FreeCompanyCrystals = 22001,
HousingExteriorAppearance = 25000,
HousingExteriorPlacedItems = 25001,
HousingInteriorAppearance = 25002,
HousingInteriorPlacedItems1 = 25003,
HousingInteriorPlacedItems2 = 25004,
HousingInteriorPlacedItems3 = 25005,
HousingInteriorPlacedItems4 = 25006,
HousingInteriorPlacedItems5 = 25007,
HousingInteriorPlacedItems6 = 25008,
HousingInteriorPlacedItems7 = 25009,
HousingInteriorPlacedItems8 = 25010,
HousingExteriorStoreroom = 27000,
HousingInteriorStoreroom1 = 27001,
HousingInteriorStoreroom2 = 27002,
HousingInteriorStoreroom3 = 27003,
HousingInteriorStoreroom4 = 27004,
HousingInteriorStoreroom5 = 27005,
HousingInteriorStoreroom6 = 27006,
HousingInteriorStoreroom7 = 27007,
HousingInteriorStoreroom8 = 27008
}
| 412 | 0.632232 | 1 | 0.632232 | game-dev | MEDIA | 0.903272 | game-dev | 0.621478 | 1 | 0.621478 |
Thelnfamous1/Better-Mob-Combat | 8,562 | common/src/main/java/me/Thelnfamous1/bettermobcombat/config/BMCServerConfig.java | package me.Thelnfamous1.bettermobcombat.config;
import com.google.gson.Gson;
import com.mojang.serialization.JsonOps;
import me.shedaniel.autoconfig.ConfigData;
import me.shedaniel.autoconfig.annotation.Config;
import me.shedaniel.autoconfig.annotation.ConfigEntry;
import me.shedaniel.cloth.clothconfig.shadowed.blue.endless.jankson.Comment;
import net.bettercombat.logic.TargetHelper;
import net.minecraft.Util;
import java.util.LinkedHashMap;
@Config(
name = "server"
)
public class BMCServerConfig implements ConfigData {
private static final Gson GSON = new Gson();
@Comment("The additional attack cooldown applied to a mob, in ticks, after it launches a Better Combat attack. \nIn vanilla, there is usually a delay of 20 ticks between a mob's attacks. \n7 was chosen because a default Better Combat sword attack takes 13 ticks.")
@ConfigEntry.BoundedDiscrete(
max = 100L
)
public int mob_additional_attack_cooldown = 7;
@Comment("The amount of ticks before a mob will launch a Better Combat attack when they are ready to do so.")
@ConfigEntry.BoundedDiscrete(
max = 100L
)
public int mob_begin_attack_delay = 10;
@Comment("The amount to add to the \"upswing_multiplier\" config value when calculating a mob's Better Combat attack upswing. \nA value of 0.0 means the upswing will be at normal speed. \nA value of 0.5 means the upswing will be 50% longer. \nNOTE: The total upswing multiplier will be clamped between 0.2 and 1.0.")
public float mob_additional_upswing_multiplier = 0.0F;
@Comment("The amount to scale a mob's attack range by when determining when they should launch a Better Combat attack. \nA value of 0.5 means attack swings are triggered when the target is up to 50% of the attack range away from the mob. \nA value of 1 means attack swings are triggered when the target is up to the full attack range away from the mob. \nNOTE: This does not affect the range of the mob's attack during the point of damage application.")
public float mob_begin_attack_range_multiplier = 1.0F;
@Comment("Controls which mobs are blacklisted from using the Better Combat system. \nHelpful if certain mobs aren't able to properly animate Better Combat attacks.")
public String[] mob_blacklist = new String[]{"minecraft:fox"};
@Comment("Allows the mob blacklist to instead be used as a whitelist. \nThis makes it so that only mobs in the whitelist can use the Better Combat system.")
public boolean mob_blacklist_as_whitelist = false;
@Comment("Automatically blacklists mobs detected to be using a GeckoLib model from using the Better Combat system. \nGeckoLib models are not supported by Mob Player Animator, and therefore won't animate Better Combat attacks.")
public boolean geckolib_mobs_blacklisted = true;
@Comment("Determines if mobs that are assigned to scoreboard teams will only respect scoreboard team ally checks and ignore any other checks.")
public boolean team_mobs_only_respect_teams = false;
@Comment("Allows mobs to perform the vanilla check for allies. This allows for certain mobs, such as Illagers, to recognize each other as natural allies. \nIf this check fails or is disabled, the system will move on to entity type checks.")
public boolean mobs_check_for_vanilla_allies = true;
@Comment("Allows mobs to check if they are the same entity type as the target. This allows for mobs with identical entity types (such as two Zombified Piglins) to recognize each other as natural allies. \nIf this check fails or is disabled, the system will move on to mob type checks.")
public boolean mobs_check_for_same_entity_type = true;
@Comment("Allows mobs to check if they are the same mob type as the target. This allows for mobs with identical mob types (such as two Undead) to recognize each other as natural allies. \nIf this check fails or is disabled, the system will move on to Better Mob Combat target relation checks.")
public boolean mobs_check_for_same_mob_type = true;
@Comment("""
Relations determine when mobs' undirected weapon swings (cleaves) will hurt another entity (target).\
- `FRIENDLY` - The target can never be damaged by the mob.\
- `NEUTRAL` - The target can be damaged only if the mob is directly targeting it.\
- `HOSTILE` - The target can be damaged if located within the weapon swing area.\
(NOTE: Vanilla sweeping can still hit targets, if not disabled via `allow_sweeping`)\
The various relation related configs are being checked in the following order:\
- `mob_relations`
- `mob_relations_to_passives`\
- `mob_relations_to_hostiles`\
- `mob_relations_to_other`\
(The first relation to be found for the target will be applied. If no relation is found, it will default to HOSTILE.)\
Refer to the wiki for formatting instructions: https://github.com/Thelnfamous1/Better-Mob-Combat/wiki/Mob-Relations. \n
Use a JSON validator such as https://jsonlint.com/ to ensure your JSON strings are correct.
""")
public LinkedHashMap<String, String> mob_relations = new LinkedHashMap<String, String>() {
{
this.put("guardvillagers:guard", encodeMobRelationMap(Util.make(new LinkedHashMap<>(), BMCServerConfig::addDefaultVillagerAllyRelations)));
this.put("recruits:recruit", encodeMobRelationMap(Util.make(new LinkedHashMap<>(), BMCServerConfig::addDefaultVillagerAllyRelations)));
this.put("recruits:bowman", encodeMobRelationMap(Util.make(new LinkedHashMap<>(), BMCServerConfig::addDefaultVillagerAllyRelations)));
this.put("recruits:recruit_shieldman", encodeMobRelationMap(Util.make(new LinkedHashMap<>(), BMCServerConfig::addDefaultVillagerAllyRelations)));
this.put("recruits:nomad", encodeMobRelationMap(Util.make(new LinkedHashMap<>(), BMCServerConfig::addDefaultVillagerAllyRelations)));
this.put("recruits:horseman", encodeMobRelationMap(Util.make(new LinkedHashMap<>(), BMCServerConfig::addDefaultVillagerAllyRelations)));
this.put("minecraft:piglin", encodeMobRelationMap(Util.make(new LinkedHashMap<>(), BMCServerConfig::addDefaultPiglinRelations)));
this.put("minecraft:piglin_brute", encodeMobRelationMap(Util.make(new LinkedHashMap<>(), BMCServerConfig::addDefaultPiglinRelations)));
}
};
private static String encodeMobRelationMap(LinkedHashMap<String, TargetHelper.Relation> input) {
return BMCServerConfigHelper.MOB_RELATIONS_STRING_CODEC.encodeStart(JsonOps.INSTANCE, input).result().get().toString();
}
@Comment("Relation to unspecified entities that are instances of PassiveEntity(Yarn)/AgeableEntity(Mojmap)")
public LinkedHashMap<String, TargetHelper.Relation> mob_relations_to_passives = new LinkedHashMap<String, TargetHelper.Relation>();
@Comment("Relation to unspecified entities that are instances of HostileEntity(Yarn)/MonsterEntity(Mojmap)")
public LinkedHashMap<String, TargetHelper.Relation> mob_relations_to_hostiles = new LinkedHashMap<String, TargetHelper.Relation>();
@Comment("Fallback relation")
public LinkedHashMap<String, TargetHelper.Relation> mob_relations_to_other = new LinkedHashMap<String, TargetHelper.Relation>();
public BMCServerConfig() {
}
private static void addDefaultVillagerAllyRelations(LinkedHashMap<String, TargetHelper.Relation> map) {
map.put("guardvillagers:guard", TargetHelper.Relation.NEUTRAL);
map.put("minecraft:villager", TargetHelper.Relation.NEUTRAL);
map.put("minecraft:iron_golem", TargetHelper.Relation.NEUTRAL);
map.put("recruits:recruit", TargetHelper.Relation.NEUTRAL);
map.put("recruits:bowman", TargetHelper.Relation.NEUTRAL);
map.put("recruits:recruit_shieldman", TargetHelper.Relation.NEUTRAL);
map.put("recruits:nomad", TargetHelper.Relation.NEUTRAL);
map.put("recruits:horseman", TargetHelper.Relation.NEUTRAL);
}
private static void addDefaultPiglinRelations(LinkedHashMap<String, TargetHelper.Relation> map) {
map.put("minecraft:piglin", TargetHelper.Relation.NEUTRAL);
map.put("minecraft:piglin_brute", TargetHelper.Relation.NEUTRAL);
}
public static BMCServerConfig deserialize(String json) {
return GSON.fromJson(json, BMCServerConfig.class);
}
public String serialize() {
return GSON.toJson(this);
}
} | 412 | 0.642079 | 1 | 0.642079 | game-dev | MEDIA | 0.972375 | game-dev | 0.807652 | 1 | 0.807652 |
Wenzil/UnityConsole | 3,285 | Console/Scripts/Console.cs | using System;
using System.Collections;
using UnityEngine;
public delegate void OnConsoleLog(string line);
namespace Wenzil.Console
{
/// <summary>
/// Use Console.Log() anywhere in your code. The Console prefab will display the output.
/// </summary>
public static class Console
{
public static OnConsoleLog OnConsoleLog;
public static void Log(string line)
{
Debug.Log(line);
if (OnConsoleLog != null)
OnConsoleLog(line);
}
public static string ExecuteCommand(string command, params string[] args)
{
return ConsoleCommandsDatabase.ExecuteCommand(command, args);
}
}
public static class MBExtensions {
#region Typesafe Invoke
public static void Invoke(this MonoBehaviour mb, Action action, float delay) {
if(delay == 0f)
action();
else
mb.StartCoroutine(DelayedInvoke(action, delay));
}
public static void Invoke<T>(this MonoBehaviour mb, Action<T> action, T arg, float delay) {
if(delay == 0f)
action(arg);
else
mb.StartCoroutine(DelayedInvoke(action, arg, delay));
}
public static void Invoke<T1, T2>(this MonoBehaviour mb, Action<T1, T2> action, T1 arg1, T2 arg2, float delay) {
if(delay == 0f)
action(arg1, arg2);
else
mb.StartCoroutine(DelayedInvoke(action, arg1, arg2, delay));
}
public static void Invoke<T1, T2, T3>(this MonoBehaviour mb, Action<T1, T2, T3> action, T1 arg1, T2 arg2, T3 arg3, float delay) {
if(delay == 0f)
action(arg1, arg2, arg3);
else
mb.StartCoroutine(DelayedInvoke(action, arg1, arg2, arg3, delay));
}
public static void Invoke<T1, T2, T3, T4>(this MonoBehaviour mb, Action<T1, T2, T3, T4> action, T1 arg1, T2 arg2, T3 arg3, T4 arg4, float delay) {
if(delay == 0f)
action(arg1, arg2, arg3, arg4);
else
mb.StartCoroutine(DelayedInvoke(action, arg1, arg2, arg3, arg4, delay));
}
private static IEnumerator DelayedInvoke(Action action, float delay) {
yield return new WaitForSeconds(delay);
action();
}
private static IEnumerator DelayedInvoke<T>(Action<T> action, T arg, float delay) {
yield return new WaitForSeconds(delay);
action(arg);
}
private static IEnumerator DelayedInvoke<T1, T2>(Action<T1, T2> action, T1 arg1, T2 arg2, float delay) {
yield return new WaitForSeconds(delay);
action(arg1, arg2);
}
private static IEnumerator DelayedInvoke<T1, T2, T3>(Action<T1, T2, T3> action, T1 arg1, T2 arg2, T3 arg3, float delay) {
yield return new WaitForSeconds(delay);
action(arg1, arg2, arg3);
}
private static IEnumerator DelayedInvoke<T1, T2, T3, T4>(Action<T1, T2, T3, T4> action, T1 arg1, T2 arg2, T3 arg3, T4 arg4, float delay) {
yield return new WaitForSeconds(delay);
action(arg1, arg2, arg3, arg4);
}
#endregion
}
} | 412 | 0.579093 | 1 | 0.579093 | game-dev | MEDIA | 0.601597 | game-dev | 0.917669 | 1 | 0.917669 |
Reezonate/EasyOffset | 2,619 | Source/2_Core/Installers/OnMenuInstaller.cs | using JetBrains.Annotations;
using Zenject;
namespace EasyOffset.Installers {
[UsedImplicitly]
public class OnMenuInstaller : Installer<OnMenuInstaller> {
[Inject] [UsedImplicitly] private MenuPlayerController _menuPlayerController;
public override void InstallBindings() {
BindInputManager();
BindGizmosManager();
BindBenchmarkManager();
BindAdjustmentModeManagers();
BindAbomination();
BindUI();
}
private void BindAbomination() {
var vrControllers = new VRControllers(
_menuPlayerController.rightController,
_menuPlayerController.leftController
);
Container.BindInstance(vrControllers).AsSingle();
Container.BindInterfacesAndSelfTo<AbominationTransformManager>().AsSingle();
}
private void BindUI() {
Container.BindInterfacesAndSelfTo<UIManager>().AsSingle();
Container.Bind<UserGuideViewController>().FromNewComponentAsViewController().AsSingle();
Container.BindInterfacesAndSelfTo<UserGuideFloatingManager>().AsSingle();
}
private void BindInputManager() {
Container.BindInterfacesAndSelfTo<ReeInputManager>().AsSingle();
}
private void BindGizmosManager() {
Container.BindInterfacesAndSelfTo<GizmosManager>().AsSingle();
Container.BindExecutionOrder<GizmosManager>(1);
}
private void BindBenchmarkManager() {
Container.BindInterfacesAndSelfTo<SwingBenchmarkManager>().AsSingle();
Container.BindExecutionOrder<SwingBenchmarkManager>(1);
}
private void BindAdjustmentModeManagers() {
Container.BindInterfacesAndSelfTo<AdjustmentBlockManager>().AsSingle();
Container.BindInterfacesAndSelfTo<BasicAdjustmentModeManager>().AsSingle();
Container.BindInterfacesAndSelfTo<PositionAdjustmentModeManager>().AsSingle();
Container.BindInterfacesAndSelfTo<RotationAdjustmentModeManager>().AsSingle();
Container.BindInterfacesAndSelfTo<SwingBenchmarkAdjustmentModeManager>().AsSingle();
Container.BindInterfacesAndSelfTo<PositionAutoAdjustmentModeManager>().AsSingle();
Container.BindInterfacesAndSelfTo<RotationAutoAdjustmentModeManager>().AsSingle();
Container.BindInterfacesAndSelfTo<RoomOffsetAdjustmentModeManager>().AsSingle();
Container.BindInterfacesAndSelfTo<DirectAdjustmentModeManager>().AsSingle();
}
}
} | 412 | 0.734032 | 1 | 0.734032 | game-dev | MEDIA | 0.595417 | game-dev | 0.614864 | 1 | 0.614864 |
AscEmu/AscEmu | 115,825 | src/world/Management/AchievementMgr.cpp | /*
Copyright (c) 2014-2025 AscEmu Team <http://www.ascemu.org>
This file is released under the MIT license. See README-MIT for more information.
*/
#include "AchievementMgr.h"
#include "Group.h"
#include "MailMgr.h"
#include "ObjectMgr.hpp"
#include "QuestProperties.hpp"
#include "Macros/AIInterfaceMacros.hpp"
#include "Storage/WDB/WDBStores.hpp"
#include "Objects/Item.hpp"
#include "Objects/Units/Stats.h"
#include "Server/WorldSocket.h"
#include "Storage/MySQLDataStore.hpp"
#include "Map/Maps/InstanceDefines.hpp"
#include "Map/Management/MapMgr.hpp"
#include "Map/Maps/WorldMap.hpp"
#include "Objects/Units/Creatures/Creature.h"
#include "Objects/Units/Players/Player.hpp"
#include "Server/DatabaseDefinition.hpp"
#include "Server/World.h"
#include "Spell/Definitions/SpellMechanics.hpp"
#include "Spell/SpellMgr.hpp"
#include "Spell/Definitions/SpellEffects.hpp"
#include "Server/Packets/SmsgServerFirstAchievement.h"
#include "Server/Packets/SmsgAchievementDeleted.h"
#include "Server/Packets/SmsgCriteriaDeleted.h"
#include "Server/Packets/SmsgCriteriaUpdate.h"
#include "Server/Packets/SmsgMessageChat.h"
#include "Server/Script/ScriptMgr.hpp"
#include "Objects/Units/Players/Player.hpp"
#include "Server/WorldSession.h"
#include "Spell/SpellInfo.hpp"
#include "Storage/WDB/WDBStructures.hpp"
using namespace AscEmu::Packets;
#if VERSION_STRING > TBC
AchievementMgr::AchievementMgr(Player* _player) : m_player(_player), isCharacterLoading(true) {}
AchievementMgr::~AchievementMgr()
{
m_criteriaProgress.clear();
m_completedAchievements.clear();
}
void AchievementMgr::loadFromDb(QueryResult* _achievementResult, QueryResult* _criteriaResult)
{
if (_achievementResult)
{
do
{
Field* field = _achievementResult->Fetch();
uint32_t id = field[0].asUint32();
if (m_completedAchievements[id] == 0)
m_completedAchievements[id] = field[1].asUint32();
else
sLogger.failure("Duplicate completed achievement {} for player {}, skipping", id, m_player->getGuidLow());
} while (_achievementResult->NextRow());
}
if (_criteriaResult)
{
do
{
Field* field = _criteriaResult->Fetch();
uint32_t progress_id = field[0].asUint32();
if (m_criteriaProgress[progress_id] == nullptr)
{
m_criteriaProgress[progress_id] = std::make_unique<CriteriaProgress>(progress_id, field[1].asUint32(), static_cast<time_t>(field[2].asUint64()));
}
else
sLogger.failure("Duplicate criteria progress {} for player {}, skipping", progress_id, m_player->getGuidLow());
} while (_criteriaResult->NextRow());
}
}
void AchievementMgr::saveToDb(QueryBuffer* _buffer)
{
if (!m_completedAchievements.empty())
{
std::ostringstream ss;
ss << "DELETE FROM character_achievement WHERE guid = ";
ss << m_player->getGuidLow();
ss << ";";
if (_buffer == nullptr)
CharacterDatabase.ExecuteNA(ss.str().c_str());
else
_buffer->AddQueryNA(ss.str().c_str());
ss.rdbuf()->str("");
ss << "INSERT INTO character_achievement VALUES ";
bool first = true;
for (auto iterCompletedAchievements : m_completedAchievements)
{
if (ss.str().length() >= 16000)
{
// SQL query length is limited to 16384 characters
if (_buffer == nullptr)
CharacterDatabase.ExecuteNA(ss.str().c_str());
else
_buffer->AddQueryNA(ss.str().c_str());
ss.str("");
ss << "INSERT INTO character_achievement VALUES ";
first = true;
}
if (!first)
ss << ", ";
else
first = false;
ss << "(" << m_player->getGuidLow() << ", " << iterCompletedAchievements.first << ", " << iterCompletedAchievements.second << ")";
}
if (_buffer == nullptr)
CharacterDatabase.ExecuteNA(ss.str().c_str());
else
_buffer->AddQueryNA(ss.str().c_str());
}
if (!m_criteriaProgress.empty())
{
std::ostringstream ss;
ss << "DELETE FROM character_achievement_progress WHERE guid = ";
ss << m_player->getGuidLow();
ss << ";";
if (_buffer == nullptr)
CharacterDatabase.ExecuteNA(ss.str().c_str());
else
_buffer->AddQueryNA(ss.str().c_str());
ss.rdbuf()->str("");
ss << "INSERT INTO character_achievement_progress VALUES ";
bool first = true;
for (const auto& iterCriteriaProgress : m_criteriaProgress)
{
if (canSaveAchievementProgressToDB(iterCriteriaProgress.second.get()))
{
// only save some progresses, others will be updated when character logs in
if (ss.str().length() >= 16000)
{
// SQL query length is limited to 16384 characters
if (_buffer == nullptr)
CharacterDatabase.ExecuteNA(ss.str().c_str());
else
_buffer->AddQueryNA(ss.str().c_str());
ss.str("");
ss << "INSERT INTO character_achievement_progress VALUES ";
first = true;
}
if (!first)
ss << ", ";
else
first = false;
ss << "(" << m_player->getGuidLow() << ", " << iterCriteriaProgress.first << ", " << iterCriteriaProgress.second->counter << ", " << iterCriteriaProgress.second->date << ")";
}
}
if (!first)
{
// don't execute query if there's no entries to save
if (_buffer == nullptr)
CharacterDatabase.ExecuteNA(ss.str().c_str());
else
_buffer->AddQueryNA(ss.str().c_str());
}
}
}
bool AchievementMgr::canCompleteCriteria(WDB::Structures::AchievementCriteriaEntry const* _achievementCriteria, AchievementCriteriaTypes _type, Player* _player) const
{
switch (_type)
{
case ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL:
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT:
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_IN_ZONE:
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST:
case ACHIEVEMENT_CRITERIA_TYPE_GAIN_REPUTATION:
case ACHIEVEMENT_CRITERIA_TYPE_GAIN_EXALTED_REPUTATION:
case ACHIEVEMENT_CRITERIA_TYPE_NUMBER_OF_MOUNTS:
case ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL:
case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL:
case ACHIEVEMENT_CRITERIA_TYPE_BUY_BANK_SLOT:
case ACHIEVEMENT_CRITERIA_TYPE_WIN_RATED_ARENA:
case ACHIEVEMENT_CRITERIA_TYPE_ROLL_NEED_ON_LOOT:
case ACHIEVEMENT_CRITERIA_TYPE_ROLL_GREED_ON_LOOT:
return true;
case ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA:
return _player->hasOverlayUncovered(_achievementCriteria->explore_area.areaReference);
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_ACHIEVEMENT:
return m_completedAchievements.find(_achievementCriteria->complete_achievement.linkedAchievement) != m_completedAchievements.end();
case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL:
return _player->hasSpell(_achievementCriteria->learn_spell.spellID);
default:
break;
}
return false;
}
bool AchievementMgr::canCompleteCriteria(WDB::Structures::AchievementCriteriaEntry const* _achievementCriteria, AchievementCriteriaTypes _type, int32_t _miscValue1, int32_t /*miscValue2*/, Player* _player) const
{
switch (_type)
{
case ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL:
case ACHIEVEMENT_CRITERIA_TYPE_KILLING_BLOW:
case ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE_TYPE:
case ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING:
case ACHIEVEMENT_CRITERIA_TYPE_QUEST_REWARD_GOLD:
case ACHIEVEMENT_CRITERIA_TYPE_LOOT_MONEY:
case ACHIEVEMENT_CRITERIA_TYPE_GAIN_EXALTED_REPUTATION:
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT:
case ACHIEVEMENT_CRITERIA_TYPE_BUY_BANK_SLOT:
case ACHIEVEMENT_CRITERIA_TYPE_VISIT_BARBER_SHOP:
case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_AT_BARBER:
case ACHIEVEMENT_CRITERIA_TYPE_EARN_HONORABLE_KILL:
case ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_PLAYER:
case ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_CREATURE:
case ACHIEVEMENT_CRITERIA_TYPE_DEATH:
case ACHIEVEMENT_CRITERIA_TYPE_WIN_RATED_ARENA:
case ACHIEVEMENT_CRITERIA_TYPE_ROLL_NEED_ON_LOOT:
case ACHIEVEMENT_CRITERIA_TYPE_ROLL_GREED_ON_LOOT:
return true;
case ACHIEVEMENT_CRITERIA_TYPE_LOOT_ITEM:
case ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM:
return _achievementCriteria->loot_item.itemID == static_cast<uint32_t>(_miscValue1);
case ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA:
return _player->hasOverlayUncovered(_achievementCriteria->explore_area.areaReference);
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_IN_ZONE:
return _achievementCriteria->complete_quests_in_zone.zoneID == static_cast<uint32_t>(_miscValue1);
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST:
return _achievementCriteria->complete_quest.questID == static_cast<uint32_t>(_miscValue1);
case ACHIEVEMENT_CRITERIA_TYPE_GAIN_REPUTATION:
return _achievementCriteria->gain_reputation.factionID == static_cast<uint32_t>(_miscValue1);
case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL:
return _achievementCriteria->learn_spell.spellID == static_cast<uint32_t>(_miscValue1);
case ACHIEVEMENT_CRITERIA_TYPE_NUMBER_OF_MOUNTS:
return _achievementCriteria->number_of_mounts.unknown == static_cast<uint32_t>(_miscValue1);
case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET:
case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET2:
return _achievementCriteria->be_spell_target.spellID == static_cast<uint32_t>(_miscValue1);
case ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE:
return _achievementCriteria->kill_creature.creatureID == static_cast<uint32_t>(_miscValue1);
case ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL:
return _achievementCriteria->reach_skill_level.skillID == static_cast<uint32_t>(_miscValue1);
case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL:
return _achievementCriteria->learn_skill_level.skillID == static_cast<uint32_t>(_miscValue1);
case ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM:
return _achievementCriteria->equip_item.itemID == static_cast<uint32_t>(_miscValue1);
case ACHIEVEMENT_CRITERIA_TYPE_EQUIP_EPIC_ITEM:
return _achievementCriteria->equip_epic_item.itemSlot == static_cast<uint32_t>(_miscValue1);
case ACHIEVEMENT_CRITERIA_TYPE_DO_EMOTE:
return _achievementCriteria->do_emote.emoteID == static_cast<uint32_t>(_miscValue1);
case ACHIEVEMENT_CRITERIA_TYPE_USE_ITEM:
return _achievementCriteria->use_item.itemID == static_cast<uint32_t>(_miscValue1);
case ACHIEVEMENT_CRITERIA_TYPE_USE_GAMEOBJECT:
return _achievementCriteria->use_gameobject.goEntry == static_cast<uint32_t>(_miscValue1);
case ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILL_AT_AREA:
return _achievementCriteria->honorable_kill_at_area.areaID == static_cast<uint32_t>(_miscValue1);
case ACHIEVEMENT_CRITERIA_TYPE_HK_CLASS:
return _achievementCriteria->hk_class.classID == static_cast<uint32_t>(_miscValue1);
case ACHIEVEMENT_CRITERIA_TYPE_HK_RACE:
return _achievementCriteria->hk_race.raceID == static_cast<uint32_t>(_miscValue1);
case ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP:
return _achievementCriteria->death_at_map.mapID == static_cast<uint32_t>(_miscValue1);
default:
break;
}
return false;
}
//////////////////////////////////////////////////////////////////////////////////////////
/// \brief This is called during player login to update some criteria which aren't
/// saved in achievement progress DB, since they are saved in the character DB or
/// can easily be computed.
void AchievementMgr::updateAllAchievementCriteria()
{
for (uint8_t i = 0; i < ACHIEVEMENT_CRITERIA_TYPE_TOTAL; i++)
updateAchievementCriteria(static_cast<AchievementCriteriaTypes>(i));
}
//////////////////////////////////////////////////////////////////////////////////////////
/// Updates achievement criteria of the specified type
/// \brief This is what should be called from other places in the code (upon killing a
/// monster, or looting an object, or completing a quest, etc.). miscvalue1, miscvalue2
/// depend on the achievement type. Generally, miscvalue1 is an ID of some type (quest ID,
/// item ID, faction ID, etc.), and miscvalue2 is the amount to increase the progress.
void AchievementMgr::updateAchievementCriteria(AchievementCriteriaTypes _type, int32_t _miscvalue1, int32_t _miscvalue2, uint32_t /*time*/, Object* _reference /*nullptr*/)
{
if (m_player->getSession()->HasGMPermissions() && worldConfig.gm.disableAchievements)
return;
uint64_t selectedGUID = 0;
if (_type == ACHIEVEMENT_CRITERIA_TYPE_DO_EMOTE)
{
selectedGUID = getPlayer()->getTargetGuid();
}
AchievementCriteriaEntryList const & achievementCriteriaList = sObjectMgr.getAchievementCriteriaByType(_type);
for (const auto achievementCriteria : achievementCriteriaList)
{
if (isCompletedCriteria(achievementCriteria))
continue;
if (achievementCriteria->groupFlag & ACHIEVEMENT_CRITERIA_GROUP_NOT_IN_GROUP && getPlayer()->getGroup())
continue;
const auto achievement = sAchievementStore.lookupEntry(achievementCriteria->referredAchievement);
if (!achievement)
continue;
// achievement requires a faction of which the player is not a member
if ((achievement->factionFlag == ACHIEVEMENT_FACTION_FLAG_HORDE && getPlayer()->isTeamHorde() == false) ||
(achievement->factionFlag == ACHIEVEMENT_FACTION_FLAG_ALLIANCE && getPlayer()->isTeamAlliance() == false))
continue;
if (!canCompleteCriteria(achievementCriteria, _type, _miscvalue1, _miscvalue2, getPlayer()))
continue;
// Check scripted criteria checks
const auto scriptResult = sScriptMgr.callScriptedAchievementCriteriaCanComplete(achievementCriteria->ID, getPlayer(), _reference);
if (!scriptResult)
continue;
switch (_type)
{
//Start of Achievement List
case ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL:
setCriteriaProgress(achievementCriteria, getPlayer()->getLevel());
break;
case ACHIEVEMENT_CRITERIA_TYPE_LOOT_ITEM:
case ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM:
updateCriteriaProgress(achievementCriteria, _miscvalue2);
break;
case ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA:
case ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM:
setCriteriaProgress(achievementCriteria, 1);
break;
case ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILL_AT_AREA:
case ACHIEVEMENT_CRITERIA_TYPE_HK_CLASS:
case ACHIEVEMENT_CRITERIA_TYPE_HK_RACE:
case ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP:
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_IN_ZONE:
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST:
case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET:
case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET2:
case ACHIEVEMENT_CRITERIA_TYPE_USE_GAMEOBJECT:
updateCriteriaProgress(achievementCriteria, 1);
break;
case ACHIEVEMENT_CRITERIA_TYPE_NUMBER_OF_MOUNTS:
// Vanity pets owned - miscvalue1==778
// Number of mounts - miscvalue1==777
updateCriteriaProgress(achievementCriteria, 1);
break;
case ACHIEVEMENT_CRITERIA_TYPE_GAIN_REPUTATION:
case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL:
case ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL:
case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL:
setCriteriaProgress(achievementCriteria, _miscvalue2);
break;
case ACHIEVEMENT_CRITERIA_TYPE_QUEST_REWARD_GOLD:
case ACHIEVEMENT_CRITERIA_TYPE_LOOT_MONEY:
case ACHIEVEMENT_CRITERIA_TYPE_GAIN_EXALTED_REPUTATION:
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT:
case ACHIEVEMENT_CRITERIA_TYPE_BUY_BANK_SLOT:
case ACHIEVEMENT_CRITERIA_TYPE_VISIT_BARBER_SHOP:
case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_AT_BARBER:
case ACHIEVEMENT_CRITERIA_TYPE_EARN_HONORABLE_KILL:
case ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_PLAYER:
case ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_CREATURE:
case ACHIEVEMENT_CRITERIA_TYPE_DEATH:
updateCriteriaProgress(achievementCriteria, _miscvalue1);
break;
// TODO: add achievement scripts for following cases
case ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE:
switch (achievement->ID)
{
case 2556: // Pest Control
if ((_miscvalue1 == 3300 && achievementCriteria->index == 1) // Adder
|| (_miscvalue1 == 32261 && achievementCriteria->index == 2) // Crystal Spider
|| (_miscvalue1 == 24270 && achievementCriteria->index == 3) // Devouring Maggot
|| (_miscvalue1 == 9699 && achievementCriteria->index == 4) // Fire Beetle
|| (_miscvalue1 == 24174 && achievementCriteria->index == 5) // Fjord Rat
|| (_miscvalue1 == 32258 && achievementCriteria->index == 6) // Gold Beetle
|| (_miscvalue1 == 16068 && achievementCriteria->index == 7) // Larva
|| (_miscvalue1 == 16030 && achievementCriteria->index == 8) // Maggot
|| (_miscvalue1 == 4953 && achievementCriteria->index == 9) // Moccasin
|| (_miscvalue1 == 6271 && achievementCriteria->index == 10) // Mouse
|| (_miscvalue1 == 4075 && achievementCriteria->index == 11) // Rat
|| (_miscvalue1 == 4076 && achievementCriteria->index == 12) // Roach
|| (_miscvalue1 == 15476 && achievementCriteria->index == 13) // Scorpion
|| (_miscvalue1 == 2914 && achievementCriteria->index == 14) // Snake
|| (_miscvalue1 == 14881 && achievementCriteria->index == 15) // Spider
|| (_miscvalue1 == 32428 && achievementCriteria->index == 16) // Underbelly Rat
|| (_miscvalue1 == 28202 && achievementCriteria->index == 17)) // Zul'Drak Rat
{
setCriteriaProgress(achievementCriteria, 1);
}
break;
// Kill creature X in Heroic dungeon
case 489: // Heroic: Utgarde Keep
case 490: // Heroic: The Nexus
case 491: // Heroic: Azjol-Nerub
case 492: // Heroic: Ahn'kahet: The Old Kingdom
case 493: // Heroic: Drak'Tharon Keep
case 494: // Heroic: The Violet Hold
case 495: // Heroic: Gundrak
case 496: // Heroic: Halls of Stone
case 497: // Heroic: Halls of Lightning
case 498: // Heroic: The Oculus
case 499: // Heroic: Utgarde Pinnacle
case 500: // Heroic: The Culling of Stratholme
case 563: // Heroic: The Arachnid Quarter
case 565: // Heroic: The Construct Quarter
case 567: // Heroic: The Plague Quarter
case 569: // Heroic: The Military Quarter
case 573: // Heroic: Sapphiron's Demise
case 575: // Heroic: Kel'Thuzad's Defeat
case 577: // Heroic: The Fall of Naxxramas
case 623: // Heroic: The Spellweaver's Downfall
case 625: // Heroic: Besting the Black Dragonflight
case 667: // Heroic: Hellfire Ramparts
case 668: // Heroic: The Blood Furnace
case 669: // Heroic: The Slave Pens
case 670: // Heroic: Underbog
case 671: // Heroic: Mana-Tombs
case 672: // Heroic: Auchenai Crypts
case 673: // Heroic: The Escape From Durnholde
case 674: // Heroic: Sethekk Halls
case 675: // Heroic: Shadow Labyrinth
case 676: // Heroic: Opening of the Dark Portal
case 677: // Heroic: The Steamvault
case 678: // Heroic: The Shattered Halls
case 679: // Heroic: The Mechanar
case 680: // Heroic: The Botanica
case 681: // Heroic: The Arcatraz
case 682: // Heroic: Magister's Terrace
case 1312: // Utgarde Keep bosses on Heroic Difficulty.
case 1504: // Ingvar the Plunderer kills (Heroic Utgarde Keep)
case 1505: // Keristrasza kills (Heroic Nexus)
case 1506: // Anub'arak kills (Heroic Azjol-Nerub)
case 1507: // Herald Volazj kills (Heroic Ahn'kahet)
case 1508: // The Prophet Tharon'ja kills (Heroic Drak'Tharon Keep)
case 1509: // Cyanigosa kills (Heroic Violet Hold)
case 1510: // Gal'darah kills (Heroic Gundrak)
case 1511: // Sjonnir the Ironshaper kills (Heroic Halls of Stone)
case 1512: // Loken kills (Heroic Halls of Lightning)
case 1513: // Ley-Guardian Eregos kills (Heroic Oculus)
case 1514: // King Ymiron kills (Heroic Utgarde Pinnacle)
case 1515: // Mal'Ganis defeated (Heroic CoT: Stratholme)
case 1721: // Heroic: Archavon the Stone Watcher
case 1817: // The Culling of Time
case 1865: // Lockdown!
if (getPlayer()->getDungeonDifficulty() >= InstanceDifficulty::DUNGEON_HEROIC)
updateCriteriaProgress(achievementCriteria, 1);
break;
///\todo More complicated achievements: time limits, group size limits, other criteria...
case 1870: // Heroic: A Poke In The Eye
// Defeat Malygos on Heroic Difficulty with fewer than 21.
case 2056: // Volunteer Work
// Defeat Jedoga Shadowseeker in Ahn'kahet on Heroic Difficulty without killing any Twilight Volunteers.
case 1875: // Heroic: You Don't Have An Eternity
// Defeat Malygos in 6 minutes or less on Heroic Difficulty.
case 2185: // Heroic: Just Can't Get Enough
// Defeat Kel'Thuzad on Heroic Difficulty in Naxxramas while killing at least 18 abominations in his chamber.
case 1862: // Volazj's Quick Demise
// Defeat Herald Volazj in Ahn'kahet on Heroic Difficulty in 2 minutes or less.
case 2186: // The Immortal
// Within one raid lockout period, defeat every boss in Naxxramas on Heroic Difficulty without allowing any raid member to die during any of the boss encounters.
case 2038: // Respect Your Elders
// Defeat Elder Nadox in Ahn'kahet on Heroic Difficulty without killing any Ahn'kahar Guardians.
case 2183: // Heroic: Spore Loser
// Defeat Loatheb in Naxxramas on Heroic Difficulty without killing any spores.
case 1297: // Hadronox Denied
// Defeat Hadronox in Azjol-Nerub on Heroic Difficulty before he webs the top doors and prevents more creatures from spawning.
case 2177: // Heroic: And They Would All Go Down Together
// Defeat the 4 Horsemen in Naxxramas on Heroic Difficulty, ensuring that they all die within 15 seconds of each other.
case 1860: // Gotta Go!
// Defeat Anub'arak in Azjol-Nerub on Heroic Difficulty in 2 minutes or less.
case 2147: // Heroic: The Hundred Club
// Defeat Sapphiron on Heroic Difficulty in Naxxramas without any member of the raid having a frost resist value over 100.
case 1861: // The Party's Over
// Defeat Prince Taldaram in Ahn'kahet on Heroic Difficulty with less than 5 people.
case 2181: // Heroic: Subtraction
// Defeat Thaddius in Naxxramas on Heroic Difficulty with less than 21 people.
case 579: // Heroic: The Dedicated Few
// Defeat the bosses of Naxxramas with less than 21 people in the zone on Heroic Difficulty.
case 1296: // Watch Him Die
// Defeat Krik'thir the Gatewatcher in Azjol-Nerub on Heroic Difficulty while Watcher Gashra, Watcher Narjil and Watcher Silthik are still alive.
case 1589: // Heroic: Arachnophobia
// Kill Maexxna in Naxxramas within 20 minutes of Anub'Rekhan's death on Heroic Difficulty.
case 1857: // Heroic: Make Quick Werk Of Him
// Kill Patchwerk in Naxxramas in 3 minutes or less on Heroic Difficulty.
case 1877: // Heroic: Less Is More
// Defeat Sartharion the Onyx Guardian and the Twilight Drakes on Heroic Difficulty with fewer than 21.
case 1919: // On The Rocks
// Defeat Prince Keleseth in Utgarde Keep on Heroic Difficulty without shattering any Frost Tombs.
case 2036: // Intense Cold
// Defeat Keristrasza in The Nexus on Heroic Difficulty without allowing Intense Cold to reach more than two stacks.
case 2139: // Heroic: The Safety Dance
// Defeat Heigan the Unclean in Naxxramas on Heroic Difficulty without anyone in the raid dying.
case 2140: // Heroic: Momma Said Knock You Out
// Defeat Grand Widow Faerlina in Naxxramas on Heroic Difficulty without dispelling frenzy.
case 2150: // Split Personality
// Defeat Grand Magus Telestra in The Nexus on Heroic Difficulty after having killed her images within 5 seconds of each other during both splits.
case 2151: // Consumption Junction
// Defeat Trollgore in Drak'Tharon Keep on Heroic Difficulty before Consume reaches ten stacks.
case 2179: // Heroic: Shocking!
// Defeat Thaddius in Naxxramas on Heroic Difficulty without anyone in the raid crossing the negative and positive charges.
case 2037: // Chaos Theory
// Defeat Anomalus in The Nexus on Heroic Difficulty without destroying any Chaotic Rifts.
case 2039: // Better Off Dred
// Engage King Dred in Drak'Tharon Keep on Heroic Difficulty and slay 6 Drakkari Gutrippers or Drakkari Scytheclaw during his defeat.
case 2048: // Heroic: Gonna Go When the Volcano Blows
// Defeat Sartharion the Onyx Guardian on Heroic Difficulty without getting hit by Lava Strike.
case 2057: // Oh Novos!
// Defeat Novos the Summoner in Drak'Tharon Keep on Heroic Difficulty without allowing any undead minions to reach the floor.
case 1816: // Defenseless
// Defeat Cyanigosa in The Violet Hold without using Defense Control Crystals and with Prison Seal Integrity at 100% while in Heroic Difficulty.
case 2052: // Heroic: Twilight Assist
// With at least one Twilight Drake still alive, engage and defeat Sartharion the Onyx Guardian on Heroic Difficulty.
case 2053: // Heroic: Twilight Duo
// With at least two Twilight Drakes still alive, engage and defeat Sartharion the Onyx Guardian on Heroic Difficulty.
case 2041: // Dehydration
// Defeat Ichoron in the Violet Hold on Heroic Difficulty without allowing any Ichor Globules to merge.
case 2054: // Heroic: The Twilight Zone
// With all three Twilight Drakes still alive, engage and defeat Sartharion the Onyx Guardian on Heroic Difficulty.
case 1864: // What the Eck?
// Defeat Gal'darah in Gundrak on Heroic Difficulty while under the effects of Eck Residue.
case 2152: // Share The Love
// Defeat Gal'darah in Gundrak on Heroic Difficulty and have 5 unique party members get impaled throughout the fight.
case 2040: // Less-rabi
// Defeat Moorabi in Gundrak on Heroic Difficulty while preventing him from transforming into a mammoth at any point during the encounter.
case 2058: // Snakes. Why'd It Have To Be Snakes?
// Defeat Slad'ran in Gundrak on Heroic Difficulty without getting snake wrapped.
case 1866: // Good Grief
// Defeat the Maiden of Grief in the Halls of Stone on Heroic Difficulty in 1 minute or less.
case 2155: // Abuse the Ooze
// Defeat Sjonnir the Ironshaper in the Halls of Stone on Heroic Difficulty and kill 5 Iron Sludges during the encounter.
case 2154: // Brann Spankin' New
// Defeat the Tribunal of Ages encounter in the Halls of Stone on Heroic Difficulty without allowing Brann Bronzebeard to take any damage.
case 1867: // Timely Death
// Defeat Loken in the Halls of Lightning on Heroic Difficulty in 2 minutes or less.
case 1834: //Lightning Struck
// Defeat General Bjarngrim in the Halls of Lightning on Heroic Difficulty while he has a Temporary Electrical Charge.
case 2042: // Shatter Resistant
// Defeat Volkhan in the Halls of Lightning on Heroic Difficulty without allowing him to shatter more than 4 Brittle Golems.
case 1872: // Zombiefest!
// Kill 100 Risen Zombies in 1 minute in The Culling of Stratholme on Heroic Difficulty.
case 2043: // The Incredible Hulk
// Force Svala Sorrowgrave to kill a Scourge Hulk on Heroic Difficulty in Utgarde Pinnacle.
case 1873: // Lodi Dodi We Loves the Skadi
// Defeat Skadi the Ruthless in Utgarde Pinnacle on Heroic Difficulty within 3 minutes of starting the gauntlet event.
case 2156: // My Girl Loves to Skadi All the Time
// Defeat Skadi the Ruthless in Utgarde Pinnacle on Heroic Difficulty after having killed Grauf from 100% to dead in a single pass.
case 2157: // King's Bane
// Defeat King Ymiron in Utgarde Pinnacle on Heroic Difficulty without anyone in the party triggering Bane.
case 1871: // Experienced Drake Rider
// On three different visits to The Oculus, get credit for defeating Ley-Guardian Eregos while riding an Amber, Emerald, and Ruby drake on Heroic Difficulty.
case 1868: // Make It Count
// Defeat Ley-Guardian Eregos in The Oculus on Heroic Difficulty within 20 minutes of Drakos the Interrogator's death.
case 2044: // Ruby Void
// Defeat Ley-Guardian Eregos in The Oculus on Heroic Difficulty without anyone in your party using a Ruby Drake.
case 2045: // Emerald Void
// Defeat Ley-Guardian Eregos in The Oculus on Heroic Difficulty without anyone in your party using an Emerald Drake.
case 2046: // Amber Void
// Defeat Ley-Guardian Eregos in The Oculus on Heroic Difficulty without anyone in your party using an Amber Drake.
break;
default:
// already tested heroic achievements above, the rest should be normal or non-dungeon
if (!IS_INSTANCE(getPlayer()->GetMapId()) || (getPlayer()->getDungeonDifficulty() == InstanceDifficulty::DUNGEON_NORMAL))
updateCriteriaProgress(achievementCriteria, 1);
break;
}
break;
case ACHIEVEMENT_CRITERIA_TYPE_EQUIP_EPIC_ITEM:
// Achievement ID:556 description Equip an epic item in every slot with a minimum item level of 213.
// "213" value not found in achievement or criteria entries (dbc), have to hard-code it here? :(
// Achievement ID:557 description Equip a superior item in every slot with a minimum item level of 187.
// "187" value not found in achievement or criteria entries (dbc), have to hard-code it here? :(
// AchievementType for both Achievement ID:556 (Equip epic items) and ID:557 (Equip superior items)
// is the same (47) ACHIEVEMENT_CRITERIA_TYPE_EQUIP_EPIC_ITEM
// Going to send item slot in miscvalue1 and item quality in miscvalue2 when calling UpdateAchievementCriteria.
if (achievementCriteria->referredAchievement == 556 && _miscvalue2 == ITEM_QUALITY_EPIC_PURPLE)
setCriteriaProgress(achievementCriteria, 1);
else if (achievementCriteria->referredAchievement == 557 && (_miscvalue2 == ITEM_QUALITY_RARE_BLUE))
setCriteriaProgress(achievementCriteria, 1);
break;
case ACHIEVEMENT_CRITERIA_TYPE_DO_EMOTE:
// emote matches, check the achievement target ... (if required)
switch (achievement->ID)
{
case 1206: // To All The Squirrels I've Loved Before
{
// requires a target
if (const auto unit = getPlayer()->getWorldMap()->getUnit(selectedGUID))
{
const uint32_t unitEntry = unit->getEntry();
if ((unitEntry == 1412 && achievementCriteria->index == 1) // Squirrel
|| (unitEntry == 25679 && achievementCriteria->index == 2) // Steam Frog
|| (unitEntry == 25677 && achievementCriteria->index == 3) // Borean Frog
|| (unitEntry == 6368 && achievementCriteria->index == 4) // Cat
|| (unitEntry == 620 && achievementCriteria->index == 5) // Chicken
|| (unitEntry == 2442 && achievementCriteria->index == 6) // Cow
|| (unitEntry == 6827 && achievementCriteria->index == 7) // Crab
|| (unitEntry == 883 && achievementCriteria->index == 8) // Deer
|| (unitEntry == 19665 && achievementCriteria->index == 9) // Ewe
|| (unitEntry == 890 && achievementCriteria->index == 10) // Fawn
|| (unitEntry == 13321 && achievementCriteria->index == 11) // Frog
|| (unitEntry == 4166 && achievementCriteria->index == 12) // Gazelle
|| (unitEntry == 5951 && achievementCriteria->index == 13) // Hare
|| (unitEntry == 9600 && achievementCriteria->index == 14) // Parrot
|| (unitEntry == 721 && achievementCriteria->index == 15) // Rabbit
|| (unitEntry == 2098 && achievementCriteria->index == 16) // Ram
|| (unitEntry == 1933 && achievementCriteria->index == 17) // Sheep
|| (unitEntry == 17467 && achievementCriteria->index == 18) // Skunk
|| (unitEntry == 10685 && achievementCriteria->index == 19) // Swine
|| (unitEntry == 1420 && achievementCriteria->index == 20) // Toad
|| (unitEntry == 2620 && achievementCriteria->index == 21)) // Prairie Dog
{
setCriteriaProgress(achievementCriteria, 1);
}
}
} break;
case 2557: // To All The Squirrels Who Shared My Life
{
// requires a target
if (const auto unit = getPlayer()->getWorldMap()->getUnit(selectedGUID))
{
const uint32_t unitEntry = unit->getEntry();
if ((unitEntry == 29328 && achievementCriteria->index == 1) // Arctic Hare
|| (unitEntry == 31685 && achievementCriteria->index == 2) // Borean Marmot
|| (unitEntry == 28407 && achievementCriteria->index == 3) // Fjord Penguin
|| (unitEntry == 24746 && achievementCriteria->index == 4) // Fjord Turkey
|| (unitEntry == 32498 && achievementCriteria->index == 5) // Glacier Penguin (not in db?)
|| (unitEntry == 31889 && achievementCriteria->index == 6) // Grizzly Squirrel
|| (unitEntry == 6653 && achievementCriteria->index == 7) // Huge Toad
|| (unitEntry == 9700 && achievementCriteria->index == 8) // Lava Crab
|| (unitEntry == 31890 && achievementCriteria->index == 9) // Mountain Skunk
|| (unitEntry == 26503 && achievementCriteria->index == 10) // Scalawag Frog
|| (unitEntry == 28093 && achievementCriteria->index == 11) // Sholazar Tickbird
|| (unitEntry == 28440 && achievementCriteria->index == 12)) // Tundra Penguin
{
setCriteriaProgress(achievementCriteria, 1);
}
}
} break;
case 247: // Make Love, Not Warcraft
{
Player* pTarget = sObjectMgr.getPlayer(static_cast<uint32_t>(selectedGUID));
if (pTarget && pTarget->isDead() && pTarget->isHostileTo(getPlayer()))
updateCriteriaProgress(achievementCriteria, 1);
}
break;
case 293: ///\todo Disturbing the Peace
// While wearing 3 pieces of Brewfest clothing, get completely smashed and dance in Dalaran.
break;
case 1280: ///\todo Flirt With Disaster
// Get completely smashed, put on your best perfume, throw a handful of rose petals on Jeremiah Payson and then kiss him. You'll regret it in the morning.
break;
case 1279: ///\todo Flirt With Disaster
// Get completely smashed, put on your best perfume, throw a handful of rose petals on Sraaz and then kiss him. You'll regret it in the morning.
break;
case 1690: ///\todo A Frosty Shake
// During the Feast of Winter Veil, use your Winter Veil Disguise kit to become a snowman and then dance with another snowman in Dalaran.
break;
case 1704: ///\todo I Pitied The Fool
// Pity the Love Fool in the locations specified below.
// Wintergrasp (achievementCriteria->index==1)
// Battle Ring of Gurubashi Arena (achievementCriteria->index==2)
// Arathi Basin Blacksmith (achievementCriteria->index==3)
// The Culling of Stratholme (achievementCriteria->index==4)
// Naxxramas (achievementCriteria->index==5)
break;
// Statistics for emotes
case 1042: // Number of Hugs
case 1045: // Total cheers
case 1047: // Total facepalms
case 1065: // Total waves
case 1066: // Total times LOL'd (laugh, guffaw, rofl, giggle, chuckle)
case 1067: // Total times playing world's smallest violin
updateCriteriaProgress(achievementCriteria, 1);
break;
default:
break;
}
break;
case ACHIEVEMENT_CRITERIA_TYPE_KILLING_BLOW:
// miscvalue1 contain Map ID
switch (achievementCriteria->referredAchievement)
{
case 231:
if (((_miscvalue1 == 30) && (achievementCriteria->index == 1)) // Alterac Valley
|| ((_miscvalue1 == 529) && (achievementCriteria->index == 2)) // Arathi Basin
|| ((_miscvalue1 == 566) && (achievementCriteria->index == 3)) // Eye of the Storm
|| ((_miscvalue1 == 489) && (achievementCriteria->index == 4)) // Warsong Gulch
|| ((_miscvalue1 == 607) && (achievementCriteria->index == 5))) // Strand of the Ancients
{
updateCriteriaProgress(achievementCriteria, 1);
}
break;
case 233: ///\todo Berserking killing blow
break;
case 1487: // Total Killing Blows
updateCriteriaProgress(achievementCriteria, 1);
break;
case 1488:
if (((_miscvalue1 == 0) && (achievementCriteria->index == 1)) // Eastern Kingdoms
|| ((_miscvalue1 == 1) && (achievementCriteria->index == 2)) // Kalimdor
|| ((_miscvalue1 == 530) && (achievementCriteria->index == 3)) // Burning Crusade Areas
|| ((_miscvalue1 == 571) && (achievementCriteria->index == 4))) // Northrend
{
updateCriteriaProgress(achievementCriteria, 1);
}
break;
case 1490:
if (((_miscvalue1 == 559) && (achievementCriteria->index == 1)) // Nagrand Arena
|| ((_miscvalue1 == 562) && (achievementCriteria->index == 2)) // Blade's Edge Arena
|| ((_miscvalue1 == 572) && (achievementCriteria->index == 3)) // Ruins of Lordaeron
|| ((_miscvalue1 == 617) && (achievementCriteria->index == 4)) // Dalaran Sewers
|| ((_miscvalue1 == 618) && (achievementCriteria->index == 5))) // Ring of Valor
{
updateCriteriaProgress(achievementCriteria, 1);
}
break;
case 1491:
if (((_miscvalue1 == 30) && (achievementCriteria->index == 1)) // Alterac Valley
|| ((_miscvalue1 == 529) && (achievementCriteria->index == 2)) // Arathi Basin
|| ((_miscvalue1 == 489) && (achievementCriteria->index == 3)) // Warsong Gulch
|| ((_miscvalue1 == 566) && (achievementCriteria->index == 4)) // Eye of the Storm
|| ((_miscvalue1 == 607) && (achievementCriteria->index == 5))) // Strand of the Ancients
{
updateCriteriaProgress(achievementCriteria, 1);
}
break;
case 1492: ///\todo 2v2 Arena Killing Blows
break;
case 1493: ///\todo 3v3 Arena Killing Blows
break;
case 1494: ///\todo 5v5 Arena Killing Blows
break;
case 1495: // Alterac Valley Killing Blows
if (_miscvalue1 == 30)
updateCriteriaProgress(achievementCriteria, 1);
break;
case 1496: // Arathi Basin Killing Blows
if (_miscvalue1 == 529)
updateCriteriaProgress(achievementCriteria, 1);
break;
case 1497: // Warsong Gulch Killing Blows
if (_miscvalue1 == 489)
updateCriteriaProgress(achievementCriteria, 1);
break;
case 1498: // Eye of the Storm Killing Blows
if (_miscvalue1 == 566)
updateCriteriaProgress(achievementCriteria, 1);
break;
case 1499: // Strand of the Ancients Killing Blows
if (_miscvalue1 == 607)
updateCriteriaProgress(achievementCriteria, 1);
break;
case 2148: ///\todo Deliver a killing blow to a Scion of Eternity while riding on a hover disk
break;
case 2149: ///\todo Deliver a killing blow to a Scion of Eternity while riding on a hover disk
break;
default:
break;
}
break;
case ACHIEVEMENT_CRITERIA_TYPE_USE_ITEM: // itemID in miscvalue1
switch (achievementCriteria->referredAchievement)
{
case 1281: // Shoot off 10 Red Rocket Clusters in 25 seconds or less
case 1552: // Shoot off 10 Festival Firecrackers in 30 seconds or less
case 1696: // Shoot off 10 Love Rockets in 20 seconds or less
case 1781: // Get 10 critters in 3 minutes
case 1791: // Hearthstone with kid out
break;
default:
updateCriteriaProgress(achievementCriteria, 1);
break;
}
break;
case ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE_TYPE:
// Total NPC kills, Kill an NPC that yields XP, Beasts, Critters killed, Demons, Dragonkin ...
// miscvalue1 = killed creature high GUID
// miscvalue2 = killed creature low GUID
{
uint64_t creatureGuid = _miscvalue1;
creatureGuid <<= 32; // shift to high 32-bits
creatureGuid += _miscvalue2;
if (const auto unit = getPlayer()->getWorldMap()->getUnit(creatureGuid))
{
bool yieldXP = CalculateXpToGive(unit, getPlayer()) > 0;
if (unit->isCreature())
{
bool isTotem = unit->isTotem();
const uint32_t creatureType = dynamic_cast<Creature*>(unit)->GetCreatureProperties()->Type;
if ((achievementCriteria->ID == 4944) // Total NPC kills refAch==1197
|| ((achievementCriteria->ID == 4946) && (yieldXP)) // Kill an NPC that yields XP refAch==1198
|| ((achievementCriteria->ID == 4948) && (creatureType == UNIT_TYPE_BEAST)) // Beasts refAch== 107
|| ((achievementCriteria->ID == 4958) && (creatureType == UNIT_TYPE_CRITTER)) // Critters killed refAch== 107
|| ((achievementCriteria->ID == 4949) && (creatureType == UNIT_TYPE_DEMON)) // Demons refAch== 107
|| ((achievementCriteria->ID == 4950) && (creatureType == UNIT_TYPE_DRAGONKIN)) // Dragonkin refAch== 107
|| ((achievementCriteria->ID == 4951) && (creatureType == UNIT_TYPE_ELEMENTAL)) // Elemental refAch== 107
|| ((achievementCriteria->ID == 4952) && (creatureType == UNIT_TYPE_GIANT)) // Giant refAch== 107
|| ((achievementCriteria->ID == 4953) && (creatureType == UNIT_TYPE_HUMANOID)) // Humanoid refAch== 107
|| ((achievementCriteria->ID == 4954) && (creatureType == UNIT_TYPE_MECHANICAL)) // Mechanical refAch== 107
|| ((achievementCriteria->ID == 4955) && (creatureType == UNIT_TYPE_UNDEAD)) // Undead refAch== 107
|| ((achievementCriteria->ID == 4956) && (creatureType == UNIT_TYPE_NONE)) // Unspecified refAch== 107
|| ((achievementCriteria->ID == 4957) && (isTotem))) // Totems refAch== 107
{
updateCriteriaProgress(achievementCriteria, 1);
}
}
}
}
break;
case ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING:
// fall distance (>=65) has been checked before UpdateAchievementCriteria() call, but it is sent in miscvalue1 just in case "they" add more...
if (achievement->ID == 1260)
{
// Fall 65 yards without dying while completely smashed during the Brewfest Holiday.
if (_miscvalue2 == DRUNKEN_SMASHED)
{
// drunken state, "completely smashed"
///\todo Check if it is during the Brewfest Holiday ...
updateCriteriaProgress(achievementCriteria, 1);
}
}
else
{
// achievement->ID==964 // Fall 65 yards without dying.
updateCriteriaProgress(achievementCriteria, 1);
}
break;
//End of Achievement List
default:
return;
}
completedCriteria(achievementCriteria);
}
}
//////////////////////////////////////////////////////////////////////////////////////////
/// Updates all achievement criteria of the specified type.
/// \brief This is only called from updateAllAchievementCriteria(), during player login
void AchievementMgr::updateAchievementCriteria(AchievementCriteriaTypes _type)
{
if (m_player->getSession()->HasGMPermissions() && worldConfig.gm.disableAchievements)
return;
AchievementCriteriaEntryList const & achievementCriteriaList = sObjectMgr.getAchievementCriteriaByType(_type);
for (auto achievementCriteria : achievementCriteriaList)
{
const auto achievement = sAchievementStore.lookupEntry(achievementCriteria->referredAchievement);
if (!achievement //|| IsCompletedCriteria(achievementCriteria)
|| (achievement->flags & ACHIEVEMENT_FLAG_COUNTER)
|| (achievement->factionFlag == ACHIEVEMENT_FACTION_FLAG_HORDE && !m_player->isTeamHorde())
|| (achievement->factionFlag == ACHIEVEMENT_FACTION_FLAG_ALLIANCE && !m_player->isTeamAlliance()))
{
continue;
}
if (!canCompleteCriteria(achievementCriteria, _type, getPlayer()))
continue;
// Check scripted criteria checks
const auto scriptResult = sScriptMgr.callScriptedAchievementCriteriaCanComplete(achievementCriteria->ID, getPlayer(), nullptr);
if (!scriptResult)
continue;
switch (_type)
{
//Start of Achievement List
case ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL:
setCriteriaProgress(achievementCriteria, getPlayer()->getLevel());
break;
case ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA:
case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL:
setCriteriaProgress(achievementCriteria, 1);
break;
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_ACHIEVEMENT:
setCriteriaProgress(achievementCriteria, 1, true);
break;
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT:
setCriteriaProgress(achievementCriteria, (int32_t)getPlayer()->getFinishedQuests().size());
break;
case ACHIEVEMENT_CRITERIA_TYPE_GAIN_REPUTATION:
setCriteriaProgress(achievementCriteria, getPlayer()->getFactionStanding(achievementCriteria->gain_reputation.factionID));
break;
case ACHIEVEMENT_CRITERIA_TYPE_GAIN_EXALTED_REPUTATION:
setCriteriaProgress(achievementCriteria, getPlayer()->getExaltedCount());
break;
case ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL:
setCriteriaProgress(achievementCriteria, getPlayer()->getSkillLineCurrent(static_cast<uint16_t>(achievementCriteria->reach_skill_level.skillID), true));
break;
case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL:
setCriteriaProgress(achievementCriteria, getPlayer()->getSkillLineMax(static_cast<uint16_t>(achievementCriteria->learn_skill_level.skillID) / 75U));
break;
case ACHIEVEMENT_CRITERIA_TYPE_BUY_BANK_SLOT:
setCriteriaProgress(achievementCriteria, getPlayer()->getBankSlots());
break;
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_IN_ZONE:
{
uint32_t qcinzone = 0;
for (const uint32_t finishedQuestId : getPlayer()->getFinishedQuests())
{
QuestProperties const* qst = sMySQLStore.getQuestProperties(finishedQuestId);
if (qst && qst->zone_id == achievementCriteria->complete_quests_in_zone.zoneID)
++qcinzone;
}
setCriteriaProgress(achievementCriteria, qcinzone);
} break;
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST:
{
uint32_t completed = 0;
for (const uint32_t finishedQuestId : getPlayer()->getFinishedQuests())
{
if (QuestProperties const* qst = sMySQLStore.getQuestProperties(finishedQuestId))
if (finishedQuestId == achievementCriteria->complete_quest.questID)
++completed;
}
setCriteriaProgress(achievementCriteria, completed);
} break;
case ACHIEVEMENT_CRITERIA_TYPE_NUMBER_OF_MOUNTS:
{
// achievementCriteria field4 = 777 for mounts, 778 for companion pets
auto sl = getPlayer()->getSpellSet().begin();
uint32_t nm = 0;
while (sl != getPlayer()->getSpellSet().end())
{
SpellInfo const* sp = sSpellMgr.getSpellInfo(*sl);
if (achievementCriteria->number_of_mounts.unknown == 777 && sp && sp->getMechanicsType() == MECHANIC_MOUNTED)
{
// mount spell
++nm;
}
else if (achievementCriteria->number_of_mounts.unknown == 778 && sp && (sp->getEffect(0) == SPELL_EFFECT_SUMMON))
{
// Companion pet? Make sure it's a companion pet, not some other summon-type spell
// temporary solution since spell description is no longer loaded -Appled
const auto creatureEntry = sp->getEffectMiscValue(0);
auto creatureProperties = sMySQLStore.getCreatureProperties(creatureEntry);
if (creatureProperties != nullptr && creatureProperties->Type == UNIT_TYPE_NONCOMBAT_PET)
++nm;
}
++sl;
}
setCriteriaProgress(achievementCriteria, nm);
} break;
//End of Achievement List
default:
break;
}
completedCriteria(achievementCriteria);
}
}
bool AchievementMgr::updateAchievementCriteria(Player* _player, int32_t _criteriaId, uint32_t _count)
{
const auto criteria = sAchievementCriteriaStore.lookupEntry(_criteriaId);
if (!criteria)
{
sLogger.debug("Achievement ID {} is Invalid", _criteriaId);
return false;
}
if (isCompletedCriteria(criteria))
{
sLogger.debug("Achievement criteria {} already completed.", _criteriaId);
return false;
}
auto* achievement = sAchievementStore.lookupEntry(criteria->referredAchievement);
if (!achievement)
{
// achievement not found
sLogger.debug("Referred achievement ({}) entry not found.", criteria->referredAchievement);
return false;
}
if (achievement->flags & ACHIEVEMENT_FLAG_COUNTER)
{
// can't complete this type of achivement (counter)
sLogger.debug("AchievementMgr Referred achievement ({}) |Hachievement:{}:{}:0:0:0:-1:0:0:0:0|h[{}]|h is a counter and cannot be completed.",
achievement->ID, achievement->ID, std::to_string(_player->getGuid()), achievement->name[0]);
return false;
}
const auto [itr, _] = m_criteriaProgress.try_emplace(_criteriaId, Util::LazyInstanceCreator([_criteriaId] {
return std::make_unique<CriteriaProgress>(_criteriaId, 0);
}));
auto* progress = itr->second.get();
progress->counter = progress->counter + _count;
sendCriteriaUpdate(progress);
completedCriteria(criteria);
return true;
}
//////////////////////////////////////////////////////////////////////////////////////////
/// Returns the number of achievement progresses that get sent to the player.
uint32_t AchievementMgr::getCriteriaProgressCount()
{
uint32_t criteriapc = 0;
for (const auto& iterCriteriaProgress : m_criteriaProgress)
{
//AchievementEntry const *achievement = dbcAchievementStore.lookupEntry(iterCriteriaProgress.second->id);
if (canSendAchievementProgress(iterCriteriaProgress.second.get()))
++criteriapc;
}
return criteriapc;
}
bool AchievementMgr::isGroupCriteriaType(AchievementCriteriaTypes _type) const
{
switch (_type)
{
case ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE:
case ACHIEVEMENT_CRITERIA_TYPE_WIN_BG:
case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET: // NYI
case ACHIEVEMENT_CRITERIA_TYPE_WIN_RATED_ARENA:
case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET2: // NYI
#if VERSION_STRING > WotLK
case ACHIEVEMENT_CRITERIA_TYPE_WIN_RATED_BATTLEGROUND: // NYI
#endif
return true;
default:
break;
}
return false;
}
//////////////////////////////////////////////////////////////////////////////////////////
/// \brief GM has used a command to make the specified achievement criteria to be completed.
/// If finishAll is true, all achievement criteria get marked as completed
/// \return true if able to complete the achievement criteria, otherwise false
bool AchievementMgr::gmCompleteCriteria(WorldSession* _gmSession, uint32_t _criteriaId, bool _finishAll/* = false*/)
{
if (_finishAll)
{
uint32_t nr = sAchievementCriteriaStore.getNumRows();
for (uint32_t i = 0, j = 0; j < nr; ++i)
{
WDB::Structures::AchievementCriteriaEntry const* crt = sAchievementCriteriaStore.lookupEntry(i);
if (crt == nullptr)
{
sLogger.failure("Achievement Criteria {} entry not found.", i);
continue;
}
++j;
if (crt->raw.field4)
{
setCriteriaProgress(crt, crt->raw.field4);
completedCriteria(crt);
}
}
m_player->getSession()->SystemMessage("All achievement criteria completed.");
return true;
}
const auto criteria = sAchievementCriteriaStore.lookupEntry(_criteriaId);
if (!criteria)
{
_gmSession->SystemMessage("Achievement criteria %d not found.", _criteriaId);
return false;
}
if (isCompletedCriteria(criteria))
{
_gmSession->SystemMessage("Achievement criteria %d already completed.", _criteriaId);
return false;
}
const auto achievement = sAchievementStore.lookupEntry(criteria->referredAchievement);
if (!achievement)
{
// achievement not found
_gmSession->SystemMessage("Referred achievement (%u) entry not found.", criteria->referredAchievement);
return false;
}
if (achievement->flags & ACHIEVEMENT_FLAG_COUNTER)
{
// can't complete this type of achivement (counter)
_gmSession->SystemMessage("Referred achievement (%u) |Hachievement:%u:%s:0:0:0:-1:0:0:0:0|h[%s]|h is a counter and cannot be completed.",
achievement->ID, achievement->ID, std::to_string(_gmSession->GetPlayer()->getGuid()).c_str(), achievement->name);
return false;
}
const auto [itr, _] = m_criteriaProgress.try_emplace(_criteriaId, Util::LazyInstanceCreator([_criteriaId] {
return std::make_unique<CriteriaProgress>(_criteriaId, 0);
}));
auto* progress = itr->second.get();
progress->counter = criteria->raw.field4;
sendCriteriaUpdate(progress);
completedCriteria(criteria);
return true;
}
//////////////////////////////////////////////////////////////////////////////////////////
/// GM has used a command to reset achievement criteria for this player. If criteriaID
/// is finishAll true, all achievement criteria get reset, otherwise only the one specified gets reset
void AchievementMgr::gmResetCriteria(uint32_t _criteriaId, bool _finishAll/* = false*/)
{
if (_finishAll)
{
for (const auto& criteriaProgress : m_criteriaProgress)
{
getPlayer()->sendPacket(SmsgCriteriaDeleted(criteriaProgress.first).serialise().get());
}
m_criteriaProgress.clear();
CharacterDatabase.Execute("DELETE FROM character_achievement_progress WHERE guid = %u", m_player->getGuidLow());
}
else
{
getPlayer()->sendPacket(SmsgCriteriaDeleted(_criteriaId).serialise().get());
m_criteriaProgress.erase(_criteriaId);
CharacterDatabase.Execute("DELETE FROM character_achievement_progress WHERE guid = %u AND criteria = %u", m_player->getGuidLow(), static_cast<uint32_t>(_criteriaId));
}
updateAllAchievementCriteria();
}
//////////////////////////////////////////////////////////////////////////////////////////
/// Sends message to player(s) that the achievement has been completed.
/// Realm first! achievements get sent to all players currently online.
/// All other achievements get sent to all of the achieving player's guild members,
/// group members, and other in-range players
#if VERSION_STRING <= WotLK
void AchievementMgr::sendAllAchievementData(Player* _player)
{
// maximum size for the SMSG_ALL_ACHIEVEMENT_DATA packet without causing client problems seems to be 0x7fff
uint32_t packetSize = 18 + (static_cast<uint32_t>(m_completedAchievements.size()) * 8) + (getCriteriaProgressCount() * 36);
bool doneCompleted = false;
bool doneProgress = false;
WDB::Structures::AchievementCriteriaEntry const* acEntry;
WDB::Structures::AchievementEntry const* achievement;
WorldPacket data;
if (packetSize < 0x8000)
data.resize(packetSize);
else
data.resize(0x7fff);
CompletedAchievementMap::iterator completeIter = m_completedAchievements.begin();
CriteriaProgressMap::iterator progressIter = m_criteriaProgress.begin();
bool packetFull;
while (!doneCompleted || !doneProgress)
{
data.clear();
if (_player == m_player)
{
data.SetOpcode(SMSG_ALL_ACHIEVEMENT_DATA);
}
else
{
data.SetOpcode(SMSG_RESPOND_INSPECT_ACHIEVEMENTS);
FastGUIDPack(data, m_player->getGuid());
}
packetFull = false;
// add the completed achievements
if (!doneCompleted)
{
for (; completeIter != m_completedAchievements.end() && !packetFull; ++completeIter)
{
if (showCompletedAchievement(completeIter->first, m_player))
{
data << uint32_t(completeIter->first);
data << uint32_t(secsToTimeBitFields(completeIter->second));
}
packetFull = data.size() > 0x7f00;
}
if (completeIter == m_completedAchievements.end())
{
doneCompleted = true;
}
}
// 0xffffffff separates between completed achievements and ones in progress
data << int32_t(-1);
for (; progressIter != m_criteriaProgress.end() && !packetFull; ++progressIter)
{
acEntry = sAchievementCriteriaStore.lookupEntry(progressIter->first);
if (!acEntry)
{
continue;
}
achievement = sAchievementStore.lookupEntry(acEntry->referredAchievement);
if (!achievement)
{
continue;
}
// achievement progress to send to self
if (_player == m_player)
{
if (canSendAchievementProgress(progressIter->second.get()))
{
data << uint32_t(progressIter->first);
data.appendPackGUID(progressIter->second->counter);
data << getPlayer()->GetNewGUID();
data << uint32_t(0);
data << uint32_t(secsToTimeBitFields(progressIter->second->date));
data << uint32_t(0);
data << uint32_t(0);
}
}
// achievement progress to send to other players (inspect)
else
{
// only send statistics, no other unfinished achievement progress, since client only displays them as completed or not completed
if ((progressIter->second->counter > 0) && (achievement->flags & ACHIEVEMENT_FLAG_COUNTER))
{
data << uint32_t(progressIter->first);
data.appendPackGUID(progressIter->second->counter);
data << getPlayer()->GetNewGUID();
data << uint32_t(0);
data << uint32_t(secsToTimeBitFields(progressIter->second->date));
data << uint32_t(0);
data << uint32_t(0);
}
}
packetFull = data.size() > 0x7f00;
}
if (progressIter == m_criteriaProgress.end())
{
doneProgress = true;
}
// another 0xffffffff denotes end of the packet
data << int32_t(-1);
_player->getSession()->SendPacket(&data);
}
if (isCharacterLoading && _player == m_player)
{
// a SMSG_ALL_ACHIEVEMENT_DATA packet has been sent to the player, so the achievement manager can send SMSG_CRITERIA_UPDATE and SMSG_ACHIEVEMENT_EARNED when it gets them
isCharacterLoading = false;
}
}
#elif VERSION_STRING == Cata
struct VisibleAchievementPred
{
bool operator()(CompletedAchievementMap::value_type const& completedAchievementPair)
{
auto achievement = sAchievementStore.lookupEntry(completedAchievementPair.first);
return achievement && !(achievement->flags & ACHIEVEMENT_FLAG_HIDDEN);
}
};
void AchievementMgr::sendAllAchievementData(Player* _player)
{
VisibleAchievementPred isVisible;
size_t numCriteria = m_criteriaProgress.size();
size_t numAchievements = std::count_if(m_completedAchievements.begin(), m_completedAchievements.end(), isVisible);
ByteBuffer criteriaData(m_criteriaProgress.size() * (4 + 4 + 4 + 4 + 8 + 8));
ObjectGuid guid = m_player->getGuid();
ObjectGuid counter;
WorldPacket data(SMSG_ALL_ACHIEVEMENT_DATA, 4 + numAchievements * (4 + 4) + 4 + numCriteria * (4 + 4 + 4 + 4 + 8 + 8));
data.writeBits(numCriteria, 21);
for (const auto& progressIter : m_criteriaProgress)
{
WDB::Structures::AchievementCriteriaEntry const* acEntry = sAchievementCriteriaStore.lookupEntry(progressIter.first);
if (!acEntry)
continue;
if (!sAchievementStore.lookupEntry(acEntry->referredAchievement))
continue;
counter = uint64_t(progressIter.second->counter);
data.writeBit(guid[4]);
data.writeBit(counter[3]);
data.writeBit(guid[5]);
data.writeBit(counter[0]);
data.writeBit(counter[6]);
data.writeBit(guid[3]);
data.writeBit(guid[0]);
data.writeBit(counter[4]);
data.writeBit(guid[2]);
data.writeBit(counter[7]);
data.writeBit(guid[7]);
data.writeBits(0u, 2);
data.writeBit(guid[6]);
data.writeBit(counter[2]);
data.writeBit(counter[1]);
data.writeBit(counter[5]);
data.writeBit(guid[1]);
criteriaData.WriteByteSeq(guid[3]);
criteriaData.WriteByteSeq(counter[5]);
criteriaData.WriteByteSeq(counter[6]);
criteriaData.WriteByteSeq(guid[4]);
criteriaData.WriteByteSeq(guid[6]);
criteriaData.WriteByteSeq(counter[2]);
criteriaData << uint32_t(0); // timer 2
criteriaData.WriteByteSeq(guid[2]);
criteriaData << uint32_t(progressIter.first); // criteria id
criteriaData.WriteByteSeq(guid[5]);
criteriaData.WriteByteSeq(counter[0]);
criteriaData.WriteByteSeq(counter[3]);
criteriaData.WriteByteSeq(counter[1]);
criteriaData.WriteByteSeq(counter[4]);
criteriaData.WriteByteSeq(guid[0]);
criteriaData.WriteByteSeq(guid[7]);
criteriaData.WriteByteSeq(counter[7]);
criteriaData << uint32_t(0); // timer 1
criteriaData.appendPackedTime(progressIter.second->date); // criteria date
criteriaData.WriteByteSeq(guid[1]);
}
data.writeBits(m_completedAchievements.size(), 23);
data.flushBits();
data.append(criteriaData);
for (auto completeIter : m_completedAchievements)
{
if (!isVisible(completeIter))
continue;
data << uint32_t(completeIter.first);
data.appendPackedTime(completeIter.second);
}
_player->getSession()->SendPacket(&data);
if (isCharacterLoading && _player == m_player)
{
// a SMSG_ALL_ACHIEVEMENT_DATA packet has been sent to the player, so the achievement manager can send SMSG_CRITERIA_UPDATE and SMSG_ACHIEVEMENT_EARNED when it gets them
isCharacterLoading = false;
}
}
void AchievementMgr::sendRespondInspectAchievements(Player* _player)
{
VisibleAchievementPred isVisible;
ObjectGuid guid = m_player->getGuid();
ObjectGuid counter;
size_t numCriteria = m_criteriaProgress.size();
size_t numAchievements = std::count_if(m_completedAchievements.begin(), m_completedAchievements.end(), isVisible);
ByteBuffer criteriaData(numCriteria * (0));
WorldPacket data(SMSG_RESPOND_INSPECT_ACHIEVEMENTS, 1 + 8 + 3 + 3 + numAchievements * (4 + 4) + numCriteria * (0));
data.writeBit(guid[7]);
data.writeBit(guid[4]);
data.writeBit(guid[1]);
data.writeBits(numAchievements, 23);
data.writeBit(guid[0]);
data.writeBit(guid[3]);
data.writeBits(numCriteria, 21);
data.writeBit(guid[2]);
for (const auto& progressIter : m_criteriaProgress)
{
WDB::Structures::AchievementCriteriaEntry const* acEntry = sAchievementCriteriaStore.lookupEntry(progressIter.first);
if (!acEntry)
continue;
if (!sAchievementStore.lookupEntry(acEntry->referredAchievement))
continue;
counter = uint64_t(progressIter.second->counter);
data.writeBit(counter[5]);
data.writeBit(counter[3]);
data.writeBit(guid[1]);
data.writeBit(guid[4]);
data.writeBit(guid[2]);
data.writeBit(counter[6]);
data.writeBit(guid[0]);
data.writeBit(counter[4]);
data.writeBit(counter[1]);
data.writeBit(counter[2]);
data.writeBit(guid[3]);
data.writeBit(guid[7]);
data.writeBits(0, 2); // criteria progress flags
data.writeBit(counter[0]);
data.writeBit(guid[5]);
data.writeBit(guid[6]);
data.writeBit(counter[7]);
criteriaData.WriteByteSeq(guid[3]);
criteriaData.WriteByteSeq(counter[4]);
criteriaData << uint32_t(0); // timer 1
criteriaData.WriteByteSeq(guid[1]);
criteriaData.appendPackedTime(progressIter.second->date);
criteriaData.WriteByteSeq(counter[3]);
criteriaData.WriteByteSeq(counter[7]);
criteriaData.WriteByteSeq(guid[5]);
criteriaData.WriteByteSeq(counter[0]);
criteriaData.WriteByteSeq(guid[4]);
criteriaData.WriteByteSeq(guid[2]);
criteriaData.WriteByteSeq(guid[6]);
criteriaData.WriteByteSeq(guid[7]);
criteriaData.WriteByteSeq(counter[6]);
criteriaData << uint32_t(progressIter.first);
criteriaData << uint32_t(0); // timer 2
criteriaData.WriteByteSeq(counter[1]);
criteriaData.WriteByteSeq(counter[5]);
criteriaData.WriteByteSeq(guid[0]);
criteriaData.WriteByteSeq(counter[2]);
}
data.writeBit(guid[6]);
data.writeBit(guid[5]);
data.flushBits();
data.append(criteriaData);
data.WriteByteSeq(guid[1]);
data.WriteByteSeq(guid[6]);
data.WriteByteSeq(guid[3]);
data.WriteByteSeq(guid[0]);
data.WriteByteSeq(guid[2]);
for (auto completeIter : m_completedAchievements)
{
if (!isVisible(completeIter))
continue;
data << uint32_t(completeIter.first);
data.appendPackedTime(completeIter.second);
}
data.WriteByteSeq(guid[7]);
data.WriteByteSeq(guid[4]);
data.WriteByteSeq(guid[5]);
_player->getSession()->SendPacket(&data);
}
#else
struct VisibleAchievementPred
{
bool operator()(CompletedAchievementMap::value_type const& completedAchievementPair)
{
auto achievement = sAchievementStore.lookupEntry(completedAchievementPair.first);
return achievement && !(achievement->flags & ACHIEVEMENT_FLAG_HIDDEN);
}
};
void AchievementMgr::sendAllAchievementData(Player* _player)
{
VisibleAchievementPred isVisible;
size_t numCriteria = m_criteriaProgress.size();
size_t numAchievements = std::count_if(m_completedAchievements.begin(), m_completedAchievements.end(), isVisible);
ByteBuffer criteriaData(m_criteriaProgress.size() * (4 + 4 + 4 + 4 + 8 + 8));
ByteBuffer completedData(numAchievements * (4 + 4 + 4 + 4 + 8));
ObjectGuid guid = m_player->getGuid();
ObjectGuid counter;
WorldPacket data(SMSG_ALL_ACHIEVEMENT_DATA, 4 + numAchievements * (4 + 4) + 4 + numCriteria * (4 + 4 + 4 + 4 + 8 + 8));
data.writeBits(numCriteria, 21);
for (const auto& progressIter : m_criteriaProgress)
{
WDB::Structures::AchievementCriteriaEntry const* acEntry = sAchievementCriteriaStore.lookupEntry(progressIter.first);
if (!acEntry)
continue;
if (!sAchievementStore.lookupEntry(acEntry->referredAchievement))
continue;
counter = uint64_t(progressIter.second->counter);
data.writeBit(counter[3]);
data.writeBit(guid[3]);
data.writeBit(guid[6]);
data.writeBit(counter[0]);
data.writeBit(guid[7]);
data.writeBit(counter[1]);
data.writeBit(counter[5]);
data.writeBit(guid[2]);
data.writeBit(guid[1]);
data.writeBit(counter[7]);
data.writeBit(guid[4]);
data.writeBit(guid[0]);
data.writeBit(counter[2]);
data.writeBit(guid[5]);
data.writeBit(counter[4]);
data.writeBits(0, 4);
data.writeBit(counter[6]);
criteriaData.WriteByteSeq(counter[7]);
criteriaData << uint32_t(0); // timer 1
criteriaData.WriteByteSeq(counter[6]);
criteriaData.WriteByteSeq(guid[1]);
criteriaData << uint32_t(progressIter.first); // criteria id
criteriaData.WriteByteSeq(counter[4]);
criteriaData.WriteByteSeq(guid[0]);
criteriaData.WriteByteSeq(guid[4]);
criteriaData.WriteByteSeq(guid[6]);
criteriaData.WriteByteSeq(counter[1]);
criteriaData.WriteByteSeq(counter[5]);
criteriaData.WriteByteSeq(guid[7]);
criteriaData.WriteByteSeq(guid[2]);
criteriaData.WriteByteSeq(counter[2]);
criteriaData.WriteByteSeq(counter[0]);
criteriaData.WriteByteSeq(guid[3]);
criteriaData.WriteByteSeq(counter[3]);
criteriaData << uint32_t(0); // timer 2
criteriaData.WriteByteSeq(guid[5]);
criteriaData.appendPackedTime(progressIter.second->date); // criteria date
}
data.writeBits(m_completedAchievements.size(), 20);
for (auto completeIter : m_completedAchievements)
{
if (!isVisible(completeIter))
continue;
data.writeBit(guid[0]);
data.writeBit(guid[7]);
data.writeBit(guid[1]);
data.writeBit(guid[5]);
data.writeBit(guid[2]);
data.writeBit(guid[4]);
data.writeBit(guid[6]);
data.writeBit(guid[3]);
completedData << uint32_t(completeIter.first); // achievement Id
completedData << uint32_t(1);
completedData.WriteByteSeq(guid[5]);
completedData.WriteByteSeq(guid[7]);
completedData << uint32_t(1);
completedData.appendPackedTime(completeIter.second); // achievement date
completedData.WriteByteSeq(guid[0]);
completedData.WriteByteSeq(guid[4]);
completedData.WriteByteSeq(guid[1]);
completedData.WriteByteSeq(guid[6]);
completedData.WriteByteSeq(guid[2]);
completedData.WriteByteSeq(guid[3]);
data << uint32_t(completeIter.first);
data.appendPackedTime(completeIter.second);
}
data.flushBits();
data.append(completedData);
data.append(criteriaData);
_player->getSession()->SendPacket(&data);
if (isCharacterLoading && _player == m_player)
{
// a SMSG_ALL_ACHIEVEMENT_DATA packet has been sent to the player, so the achievement manager can send SMSG_CRITERIA_UPDATE and SMSG_ACHIEVEMENT_EARNED when it gets them
isCharacterLoading = false;
}
}
void AchievementMgr::sendRespondInspectAchievements(Player* _player)
{
VisibleAchievementPred isVisible;
ObjectGuid guid = m_player->getGuid();
ObjectGuid counter;
size_t numCriteria = m_criteriaProgress.size();
size_t numAchievements = std::count_if(m_completedAchievements.begin(), m_completedAchievements.end(), isVisible);
ByteBuffer criteriaData(numCriteria * (0));
WorldPacket data(SMSG_RESPOND_INSPECT_ACHIEVEMENTS, 1 + 8 + 3 + 3 + numAchievements * (4 + 4) + numCriteria * (0));
data.writeBit(guid[7]);
data.writeBit(guid[4]);
data.writeBit(guid[1]);
data.writeBits(numAchievements, 23);
data.writeBit(guid[0]);
data.writeBit(guid[3]);
data.writeBits(numCriteria, 21);
data.writeBit(guid[2]);
for (const auto& progressIter : m_criteriaProgress)
{
WDB::Structures::AchievementCriteriaEntry const* acEntry = sAchievementCriteriaStore.lookupEntry(progressIter.first);
if (!acEntry)
continue;
if (!sAchievementStore.lookupEntry(acEntry->referredAchievement))
continue;
counter = uint64_t(progressIter.second->counter);
data.writeBit(counter[5]);
data.writeBit(counter[3]);
data.writeBit(guid[1]);
data.writeBit(guid[4]);
data.writeBit(guid[2]);
data.writeBit(counter[6]);
data.writeBit(guid[0]);
data.writeBit(counter[4]);
data.writeBit(counter[1]);
data.writeBit(counter[2]);
data.writeBit(guid[3]);
data.writeBit(guid[7]);
data.writeBits(0, 2); // criteria progress flags
data.writeBit(counter[0]);
data.writeBit(guid[5]);
data.writeBit(guid[6]);
data.writeBit(counter[7]);
criteriaData.WriteByteSeq(guid[3]);
criteriaData.WriteByteSeq(counter[4]);
criteriaData << uint32_t(0); // timer 1
criteriaData.WriteByteSeq(guid[1]);
criteriaData.appendPackedTime(progressIter.second->date);
criteriaData.WriteByteSeq(counter[3]);
criteriaData.WriteByteSeq(counter[7]);
criteriaData.WriteByteSeq(guid[5]);
criteriaData.WriteByteSeq(counter[0]);
criteriaData.WriteByteSeq(guid[4]);
criteriaData.WriteByteSeq(guid[2]);
criteriaData.WriteByteSeq(guid[6]);
criteriaData.WriteByteSeq(guid[7]);
criteriaData.WriteByteSeq(counter[6]);
criteriaData << uint32_t(progressIter.first);
criteriaData << uint32_t(0); // timer 2
criteriaData.WriteByteSeq(counter[1]);
criteriaData.WriteByteSeq(counter[5]);
criteriaData.WriteByteSeq(guid[0]);
criteriaData.WriteByteSeq(counter[2]);
}
data.writeBit(guid[6]);
data.writeBit(guid[5]);
data.flushBits();
data.append(criteriaData);
data.WriteByteSeq(guid[1]);
data.WriteByteSeq(guid[6]);
data.WriteByteSeq(guid[3]);
data.WriteByteSeq(guid[0]);
data.WriteByteSeq(guid[2]);
for (auto completeIter : m_completedAchievements)
{
if (!isVisible(completeIter))
continue;
data << uint32_t(completeIter.first);
data.appendPackedTime(completeIter.second);
}
data.WriteByteSeq(guid[7]);
data.WriteByteSeq(guid[4]);
data.WriteByteSeq(guid[5]);
_player->getSession()->SendPacket(&data);
}
#endif
//////////////////////////////////////////////////////////////////////////////////////////
/// \brief GM has used a command to make the specified achievement to be completed.
/// If finishAll is true, all achievements available for the player's faction get
/// marked as completed
/// \return true if able to complete specified achievement successfully, otherwise false
bool AchievementMgr::gmCompleteAchievement(WorldSession* _gmSession, uint32_t _achievementId, bool _finishAll/* = false*/)
{
if (_finishAll)
{
uint32_t nr = sAchievementStore.getNumRows();
for (uint32_t i = 0; i < nr; ++i)
{
auto achievementEntry = sAchievementStore.lookupEntry(i);
if (achievementEntry == nullptr)
{
m_player->getSession()->SystemMessage("Achievement %u entry not found.", i);
}
else
{
if (!(achievementEntry->flags & ACHIEVEMENT_FLAG_COUNTER))
{
if ((achievementEntry->factionFlag == ACHIEVEMENT_FACTION_FLAG_HORDE && !m_player->isTeamHorde()) ||
(achievementEntry->factionFlag == ACHIEVEMENT_FACTION_FLAG_ALLIANCE && !m_player->isTeamAlliance()))
{
continue;
}
completedAchievement(achievementEntry);
}
}
}
m_player->getSession()->SystemMessage("All achievements completed.");
return true;
}
if (m_completedAchievements.contains(_achievementId))
{
_gmSession->SystemMessage("Player has already completed that achievement.");
return false;
}
const auto achievement = sAchievementStore.lookupEntry(_achievementId);
if (!achievement)
{
_gmSession->SystemMessage("Achievement %d entry not found.", _achievementId);
return false;
}
if (achievement->flags & ACHIEVEMENT_FLAG_COUNTER)
{
_gmSession->SystemMessage("Achievement (%u) |Hachievement:%u:%s:0:0:0:-1:0:0:0:0|h[%s]|h is a counter and cannot be completed.",
achievement->ID, achievement->ID, std::to_string(_gmSession->GetPlayer()->getGuid()).c_str(), achievement->name);
return false;
}
completedAchievement(achievement);
return true;
}
//////////////////////////////////////////////////////////////////////////////////////////
/// \brief GM has used a command to reset achievement(s) for this player. If
/// finishAll is true, all achievements get reset, otherwise the one specified gets reset
void AchievementMgr::gmResetAchievement(uint32_t _achievementId, bool _finishAll/* = false*/)
{
if (_finishAll)
{
for (const auto& completedAchievement : m_completedAchievements)
getPlayer()->sendPacket(SmsgAchievementDeleted(completedAchievement.first).serialise().get());
m_completedAchievements.clear();
CharacterDatabase.Execute("DELETE FROM character_achievement WHERE guid = %u", m_player->getGuidLow());
}
else
{
getPlayer()->sendPacket(SmsgAchievementDeleted(_achievementId).serialise().get());
m_completedAchievements.erase(_achievementId);
CharacterDatabase.Execute("DELETE FROM character_achievement WHERE guid = %u AND achievement = %u", m_player->getGuidLow(), static_cast<uint32_t>(_achievementId));
}
}
time_t AchievementMgr::getCompletedTime(WDB::Structures::AchievementEntry const* _achievement)
{
auto iter = m_completedAchievements.find(_achievement->ID);
if (iter != m_completedAchievements.end())
return iter->second;
return 0;
}
uint32_t AchievementMgr::getCompletedAchievementsCount() const
{
return static_cast<uint32_t>(m_completedAchievements.size());
}
bool AchievementMgr::hasCompleted(uint32_t _achievementId) const
{
return m_completedAchievements.contains(_achievementId);
}
Player* AchievementMgr::getPlayer() const { return m_player; }
//////////////////////////////////////////////////////////////////////////////////////////
/// Completes the achievement for the player.
void AchievementMgr::completedAchievement(WDB::Structures::AchievementEntry const* achievement)
{
if (achievement->flags & ACHIEVEMENT_FLAG_COUNTER || m_completedAchievements.find(achievement->ID) != m_completedAchievements.end())
return;
if (showCompletedAchievement(achievement->ID, getPlayer()))
sendAchievementEarned(achievement);
m_completedAchievements[achievement->ID] = time(nullptr);
sObjectMgr.addCompletedAchievement(achievement->ID);
updateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_ACHIEVEMENT);
// check for reward
giveAchievementReward(achievement);
}
/// true if the achievement should be shown; false otherwise
bool AchievementMgr::showCompletedAchievement(uint32_t _achievementId, const Player* _player)
{
switch (_achievementId)
{
case 457: // Realm First! Level 80
case 467: // Realm First! Level 80 Shaman
case 466: // Realm First! Level 80 Druid
case 465: // Realm First! Level 80 Paladin
case 464: // Realm First! Level 80 Priest
case 463: // Realm First! Level 80 Warlock
case 462: // Realm First! Level 80 Hunter
case 461: // Realm First! Level 80 Death Knight
case 460: // Realm First! Level 80 Mage
case 459: // Realm First! Level 80 Warrior
case 458: // Realm First! Level 80 Rogue
case 1404: // Realm First! Level 80 Gnome
case 1405: // Realm First! Level 80 Blood Elf
case 1406: // Realm First! Level 80 Draenei
case 1407: // Realm First! Level 80 Dwarf
case 1408: // Realm First! Level 80 Human
case 1409: // Realm First! Level 80 Night Elf
case 1410: // Realm First! Level 80 Orc
case 1411: // Realm First! Level 80 Tauren
case 1412: // Realm First! Level 80 Troll
case 1413: // Realm First! Level 80 Forsaken
case 1415: // Realm First! Grand Master Alchemist
case 1414: // Realm First! Grand Master Blacksmith
case 1416: // Realm First! Cooking Grand Master
case 1417: // Realm First! Grand Master Enchanter
case 1418: // Realm First! Grand Master Engineer
case 1419: // Realm First! First Aid Grand Master
case 1420: // Realm First! Grand Master Angler
case 1421: // Realm First! Grand Master Herbalist
case 1422: // Realm First! Grand Master Scribe
case 1423: // Realm First! Grand Master Jewelcrafter
case 1424: // Realm First! Grand Master Leatherworker
case 1425: // Realm First! Grand Master Miner
case 1426: // Realm First! Grand Master Skinner
case 1427: // Realm First! Grand Master Tailor
case 1463: // Realm First! Northrend Vanguard: First player on the realm to gain exalted reputation with the Argent Crusade, Wyrmrest Accord, Kirin Tor and Knights of the Ebon Blade.
{
auto achievementResult = CharacterDatabase.Query("SELECT guid FROM character_achievement WHERE achievement=%u ORDER BY date LIMIT 1", _achievementId);
if (achievementResult != nullptr)
{
Field* field = achievementResult->Fetch();
if (field != nullptr)
{
// somebody has this Realm First achievement... is it this player?
uint64_t firstguid = field->asUint32();
if (firstguid != (uint32_t)_player->getGuid())
{
// nope, somebody else was first.
return false;
}
}
}
}
break;
/* All raid members should receive these last 3 Realm First achievements when they first occur.
(not implemented yet)
case 1400: // Realm First! Magic Seeker: Participated in the realm first defeat of Malygos on Heroic Difficulty.
case 456: // Realm First! Obsidian Slayer: Participated in the realm first defeat of Sartharion the Onyx Guardian on Heroic Difficulty.
case 1402: // Realm First! Conqueror of Naxxramas: Participated in the realm first defeat of Kel'Thuzad on Heroic Difficulty in Naxxramas. */
default:
break;
}
return true;
}
//////////////////////////////////////////////////////////////////////////////////////////
/// Gives reward to player for completing the achievement.
void AchievementMgr::giveAchievementReward(WDB::Structures::AchievementEntry const* _entry)
{
if (_entry == nullptr || isCharacterLoading)
return;
AchievementReward const* Reward = sObjectMgr.getAchievementReward(_entry->ID, getPlayer()->getGender());
if (!Reward)
return;
//Reward Titel
if (getPlayer()->getTeam() == TEAM_ALLIANCE)
{
if (Reward->titel_A)
{
auto char_title = sCharTitlesStore.lookupEntry(Reward->titel_A);
if (char_title)
getPlayer()->setKnownPvPTitle(static_cast<RankTitles>(char_title->bit_index), true);
}
}
if (getPlayer()->getTeam() == TEAM_HORDE)
{
if (Reward->titel_H)
{
auto char_title = sCharTitlesStore.lookupEntry(Reward->titel_H);
if (char_title)
getPlayer()->setKnownPvPTitle(static_cast<RankTitles>(char_title->bit_index), true);
}
}
//Reward Mail
if (Reward->sender)
{
Creature* creature = getPlayer()->getWorldMap()->createCreature(Reward->sender);
if (creature == nullptr)
{
sLogger.failure("can not create sender for achievement {}", _entry->ID);
return;
}
uint32_t sender = Reward->sender;
uint64_t receiver = getPlayer()->getGuid();
const auto loc = (getPlayer()->getSession()->language > 0) ? sMySQLStore.getLocalizedAchievementReward(_entry->ID, getPlayer()->getGender(), getPlayer()->getSession()->language) : nullptr;
const auto subject = loc ? loc->subject : Reward->subject;
const auto rewardText = loc ? loc->text : Reward->text;
std::string messageSubject = subject;
std::string messageBody = rewardText;
//Create Item
auto item = sObjectMgr.createItem(Reward->itemId, getPlayer());
if (Reward->itemId == 0)
{
sMailSystem.SendCreatureGameobjectMail(MAIL_TYPE_CREATURE, sender, receiver, messageSubject, messageBody, 0, 0, 0, 0, MAIL_CHECK_MASK_HAS_BODY, MAIL_DEFAULT_EXPIRATION_TIME);
}
else if (item != nullptr)
{
item->saveToDB(-1, -1, true, nullptr);
sMailSystem.SendCreatureGameobjectMail(MAIL_TYPE_CREATURE, sender, receiver, messageSubject, messageBody, 0, 0, item->getGuid(), 0, MAIL_CHECK_MASK_HAS_BODY, MAIL_DEFAULT_EXPIRATION_TIME);
//removing pItem
item = nullptr;
//removing sender
creature->Delete();
}
else
{
sLogger.failure("Can not create item for message! (nullptr)");
return;
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////
/// Sends message to player(s) that the achievement has been completed.
/// Realm first! achievements get sent to all players currently online.
/// All other achievements get sent to all of the achieving player's guild members,
/// group members, and other in-range players
void AchievementMgr::sendAchievementEarned(WDB::Structures::AchievementEntry const* _entry)
{
if (_entry == nullptr || isCharacterLoading)
return;
// Send Achievement message to everyone currently on the server
if (_entry->flags & (ACHIEVEMENT_FLAG_REALM_FIRST_KILL | ACHIEVEMENT_FLAG_REALM_FIRST_REACH))
{
std::string playerName = getPlayer()->getName();
uint64_t guid = getPlayer()->getGuid();
// own team = clickable name
sWorld.sendGlobalMessage(SmsgServerFirstAchievement(playerName, guid, _entry->ID, 1).serialise().get(), nullptr, getPlayer()->GetTeam());
sWorld.sendGlobalMessage(SmsgServerFirstAchievement(playerName, guid, _entry->ID, 0).serialise().get(), nullptr, getPlayer()->GetTeam() == TEAM_ALLIANCE ? TEAM_HORDE : TEAM_ALLIANCE);
}
else
{
const char* msg = "|Hplayer:$N|h[$N]|h has earned the achievement $a!";
uint32_t guidCount = 0;
uint32_t guidIndex;
// allocate enough space
auto guidList = std::make_unique<uint32_t[]>(sWorld.getSessionCount() + 256);
bool alreadySent;
// Send Achievement message to group members
if (const auto group = getPlayer()->getGroup())
{
// grp->SendPacketToAll(&cdata);
group->Lock();
for (uint8_t i = 0; i < group->GetSubGroupCount(); ++i)
{
SubGroup* sg = group->GetSubGroup(i);
if (sg == nullptr)
continue;
for (const auto groupItr : sg->getGroupMembers())
{
if (Player* loggedInPlayer = sObjectMgr.getPlayer(groupItr->guid))
{
if (loggedInPlayer->getSession())
{
// check if achievement message has already been sent to this player (if they received a guild achievement message already)
alreadySent = false;
for (guidIndex = 0; guidIndex < guidCount; ++guidIndex)
{
if (guidList[guidIndex] == groupItr->guid)
{
alreadySent = true;
guidIndex = guidCount;
}
}
if (!alreadySent)
{
loggedInPlayer->getSession()->SendPacket(SmsgMessageChat(CHAT_MSG_ACHIEVEMENT, LANG_UNIVERSAL, 0, msg, getPlayer()->getGuid(), "", getPlayer()->getGuid(), "", _entry->ID).serialise().get());
guidList[guidCount++] = groupItr->guid;
}
}
}
}
}
group->Unlock();
}
// Send Achievement message to nearby players
for (const auto& inRangeItr : getPlayer()->getInRangePlayersSet())
{
const Player* player = dynamic_cast<Player*>(inRangeItr);
if (player && player->getSession() && !player->isIgnored(getPlayer()->getGuidLow()))
{
// check if achievement message has already been sent to this player (in guild or group)
alreadySent = false;
for (guidIndex = 0; guidIndex < guidCount; ++guidIndex)
{
if (guidList[guidIndex] == player->getGuidLow())
{
alreadySent = true;
guidIndex = guidCount;
}
}
if (!alreadySent)
{
player->getSession()->SendPacket(SmsgMessageChat(CHAT_MSG_ACHIEVEMENT, LANG_UNIVERSAL, 0, msg, getPlayer()->getGuid(), "", getPlayer()->getGuid(), "", _entry->ID).serialise().get());
guidList[guidCount++] = player->getGuidLow();
}
}
}
// Have we sent the message to the achieving player yet?
alreadySent = false;
for (guidIndex = 0; guidIndex < guidCount; ++guidIndex)
{
if (guidList[guidIndex] == getPlayer()->getGuidLow())
{
alreadySent = true;
guidIndex = guidCount;
}
if (!alreadySent)
getPlayer()->getSession()->SendPacket(SmsgMessageChat(CHAT_MSG_ACHIEVEMENT, LANG_UNIVERSAL, 0, msg, getPlayer()->getGuid(), "", getPlayer()->getGuid(), "", _entry->ID).serialise().get());
}
}
// GetPlayer()->sendMessageToSet(&cdata, true);
WorldPacket data(SMSG_ACHIEVEMENT_EARNED, 30);
data << getPlayer()->GetNewGUID();
data << uint32_t(_entry->ID);
data << uint32_t(secsToTimeBitFields(UNIXTIME));
data << uint32_t(0);
getPlayer()->getSession()->SendPacket(&data);
}
//////////////////////////////////////////////////////////////////////////////////////////
/// Returns the completion state of the achievement.
/// \brief ACHIEVEMENT_COMPLETED_COMPLETED_STORED: has been completed and stored already.
/// ACHIVEMENT_COMPLETED_COMPLETED_NOT_STORED: has been completed but not stored yet.
/// ACHIEVEMENT_COMPLETED_NONE: has not been completed yet
AchievementCompletionState AchievementMgr::getAchievementCompletionState(WDB::Structures::AchievementEntry const* _entry)
{
if (m_completedAchievements.contains(_entry->ID))
return ACHIEVEMENT_COMPLETED_COMPLETED_STORED;
uint32_t completedCount = 0;
bool foundOutstanding = false;
for (uint32_t rowId = 0; rowId < sAchievementCriteriaStore.getNumRows(); ++rowId)
{
const auto criteria = sAchievementCriteriaStore.lookupEntry(rowId);
if (criteria == nullptr || criteria->referredAchievement != _entry->ID)
continue;
if (isCompletedCriteria(criteria) && criteria->completionFlag & ACHIEVEMENT_CRITERIA_COMPLETE_FLAG_ALL)
return ACHIEVEMENT_COMPLETED_COMPLETED_NOT_STORED;
if (!isCompletedCriteria(criteria))
foundOutstanding = true;
else
++completedCount;
}
if (!foundOutstanding)
return ACHIEVEMENT_COMPLETED_COMPLETED_NOT_STORED;
if (_entry->count > 1 && completedCount >= _entry->count)
return ACHIEVEMENT_COMPLETED_COMPLETED_NOT_STORED;
return ACHIEVEMENT_COMPLETED_NONE;
}
//////////////////////////////////////////////////////////////////////////////////////////
/// True if CriteriaProgress should be sent to Player; False if CriteriaProgress should not be sent.
/// If the CriteriaProgress specified should not be sent to the Player, it returns false, otherwise it returns true.
/// Examples of CriteriaProgress that should not be sent to the Player are:
/// 1. When counter is zero or negative, which would indicate the achievement hasn't been started yet.
/// 2. Reputation type achievements, where the progress is not shown in the client.
/// 3. Reach-Level type achievements, where the progress is not shown in the client.
bool AchievementMgr::canSendAchievementProgress(const CriteriaProgress* _criteriaProgress)
{
// achievement not started yet, don't send progress
if (_criteriaProgress == nullptr || _criteriaProgress->counter <= 0)
return false;
const auto acEntry = sAchievementCriteriaStore.lookupEntry(_criteriaProgress->id);
if (!acEntry)
return false;
// Exalted with X faction (don't send 12323/42000 progress, it's not shown anyway)
if (acEntry->requiredType == ACHIEVEMENT_CRITERIA_TYPE_GAIN_REPUTATION)
return false;
// Reach level (don't send 7/80 progress, it's not shown anyway)
if (acEntry->requiredType == ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL)
return false;
return true;
}
//////////////////////////////////////////////////////////////////////////////////////////
/// True if CriteriaProgress should be saved to database. False if CriteriaProgress should not be saved to database.
/// Not all achievement progresses get saved to progress database, since some are saved in the character database,
/// or are easily computable when the player logs in.
bool AchievementMgr::canSaveAchievementProgressToDB(const CriteriaProgress* _criteriaProgress)
{
// don't save it if it's not started yet
if (_criteriaProgress->counter <= 0)
return false;
auto achievement = sAchievementCriteriaStore.lookupEntry(_criteriaProgress->id);
if (achievement == nullptr)
return false;
switch (achievement->requiredType)
{
// these get updated when character logs on, don't save to character progress db
case ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL:
case ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA:
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_ACHIEVEMENT:
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT:
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_IN_ZONE:
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST:
case ACHIEVEMENT_CRITERIA_TYPE_GAIN_REPUTATION:
case ACHIEVEMENT_CRITERIA_TYPE_GAIN_EXALTED_REPUTATION:
case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL:
case ACHIEVEMENT_CRITERIA_TYPE_NUMBER_OF_MOUNTS:
case ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL:
case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL:
case ACHIEVEMENT_CRITERIA_TYPE_BUY_BANK_SLOT:
return false;
default:
break;
}
return true;
}
//////////////////////////////////////////////////////////////////////////////////////////
/// \brief Sends update to achievement criteria to the player.
void AchievementMgr::sendCriteriaUpdate(const CriteriaProgress* _criteriaProgress)
{
if (_criteriaProgress == nullptr || isCharacterLoading)
return;
getPlayer()->sendPacket(SmsgCriteriaUpdate(_criteriaProgress->id, _criteriaProgress->counter, getPlayer()->GetNewGUID(), secsToTimeBitFields(_criteriaProgress->date)).serialise().get());
}
//////////////////////////////////////////////////////////////////////////////////////////
/// Sets progress of the achievement criteria.
/// \brief If relative argument is true, this behaves the same as UpdateCriteriaProgress
void AchievementMgr::setCriteriaProgress(WDB::Structures::AchievementCriteriaEntry const* _entry, int32_t _newValue, bool /*relative*/)
{
CriteriaProgress* progress;
if (!m_criteriaProgress.contains(_entry->ID))
{
if (_newValue < 1)
return;
const auto [progressItr, _] = m_criteriaProgress.try_emplace(_entry->ID, std::make_unique<CriteriaProgress>(_entry->ID, _newValue));
progress = progressItr->second.get();
}
else
{
progress = m_criteriaProgress[_entry->ID].get();
if (progress->counter == static_cast<uint32_t>(_newValue))
return;
progress->counter = _newValue;
}
// Send update only if criteria is started (counter > 0)
if (progress->counter > 0)
sendCriteriaUpdate(progress);
}
//////////////////////////////////////////////////////////////////////////////////////////
/// Updates progress of the achievement criteria.
/// \brief updateByValue is added to the current progress counter
void AchievementMgr::updateCriteriaProgress(WDB::Structures::AchievementCriteriaEntry const* _entry, int32_t _updateByValue)
{
CriteriaProgress* progress;
if (!m_criteriaProgress.contains(_entry->ID))
{
if (_updateByValue < 1)
return;
const auto [progressItr, _] = m_criteriaProgress.try_emplace(_entry->ID, std::make_unique<CriteriaProgress>(_entry->ID, _updateByValue));
progress = progressItr->second.get();
}
else
{
progress = m_criteriaProgress[_entry->ID].get();
progress->counter += _updateByValue;
}
// Send update only if criteria is started (counter > 0)
if (progress->counter > 0)
sendCriteriaUpdate(progress);
}
//////////////////////////////////////////////////////////////////////////////////////////
/// If achievement criteria has been completed, checks whether to complete the achievement too.
void AchievementMgr::completedCriteria(WDB::Structures::AchievementCriteriaEntry const* criteria)
{
if (!isCompletedCriteria(criteria))
return;
const auto achievement = sAchievementStore.lookupEntry(criteria->referredAchievement);
if (achievement == nullptr)
return;
if (criteria->completionFlag & ACHIEVEMENT_CRITERIA_COMPLETE_FLAG_ALL || getAchievementCompletionState(achievement) == ACHIEVEMENT_COMPLETED_COMPLETED_NOT_STORED)
completedAchievement(achievement);
}
//////////////////////////////////////////////////////////////////////////////////////////
/// \return True if the criteria has been completed otherwise false (error...)
bool AchievementMgr::isCompletedCriteria(WDB::Structures::AchievementCriteriaEntry const* achievementCriteria)
{
if (!achievementCriteria)
return false;
const auto achievement = sAchievementStore.lookupEntry(achievementCriteria->referredAchievement);
if (achievement == nullptr)
return false;
if (achievement->flags & ACHIEVEMENT_FLAG_COUNTER)
return false;
if (achievement->flags & (ACHIEVEMENT_FLAG_REALM_FIRST_REACH | ACHIEVEMENT_FLAG_REALM_FIRST_KILL))
if (sObjectMgr.isInCompletedAchievements(achievement->ID))
return false;
const auto criteriaProgressIter = m_criteriaProgress.find(achievementCriteria->ID);
if (criteriaProgressIter == m_criteriaProgress.end())
return false;
const CriteriaProgress* progress = criteriaProgressIter->second.get();
if (progress->counter < 1)
return false;
uint32_t progresscounter = progress->counter;
switch (achievementCriteria->requiredType)
{
case ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL:
if ((achievement->ID == 467 && getPlayer()->getClass() != SHAMAN) ||
(achievement->ID == 466 && getPlayer()->getClass() != DRUID) ||
(achievement->ID == 465 && getPlayer()->getClass() != PALADIN) ||
(achievement->ID == 464 && getPlayer()->getClass() != PRIEST) ||
(achievement->ID == 463 && getPlayer()->getClass() != WARLOCK) ||
(achievement->ID == 462 && getPlayer()->getClass() != HUNTER) ||
(achievement->ID == 461 && getPlayer()->getClass() != DEATHKNIGHT) ||
(achievement->ID == 460 && getPlayer()->getClass() != MAGE) ||
(achievement->ID == 459 && getPlayer()->getClass() != WARRIOR) ||
(achievement->ID == 458 && getPlayer()->getClass() != ROGUE) ||
(achievement->ID == 1404 && getPlayer()->getRace() != RACE_GNOME) ||
(achievement->ID == 1405 && getPlayer()->getRace() != RACE_BLOODELF) ||
(achievement->ID == 1406 && getPlayer()->getRace() != RACE_DRAENEI) ||
(achievement->ID == 1407 && getPlayer()->getRace() != RACE_DWARF) ||
(achievement->ID == 1408 && getPlayer()->getRace() != RACE_HUMAN) ||
(achievement->ID == 1409 && getPlayer()->getRace() != RACE_NIGHTELF) ||
(achievement->ID == 1410 && getPlayer()->getRace() != RACE_ORC) ||
(achievement->ID == 1411 && getPlayer()->getRace() != RACE_TAUREN) ||
(achievement->ID == 1412 && getPlayer()->getRace() != RACE_TROLL) ||
(achievement->ID == 1413 && getPlayer()->getRace() != RACE_UNDEAD))
{
return false;
}
return progresscounter >= achievementCriteria->reach_level.level;
case ACHIEVEMENT_CRITERIA_TYPE_LOOT_ITEM:
case ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM:
return progresscounter >= achievementCriteria->loot_item.itemCount;
case ACHIEVEMENT_CRITERIA_TYPE_LOOT_MONEY:
return progresscounter >= achievementCriteria->loot_money.goldInCopper;
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT:
return progresscounter >= achievementCriteria->complete_quest_count.totalQuestCount;
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_IN_ZONE:
return progresscounter >= achievementCriteria->complete_quests_in_zone.questCount;
case ACHIEVEMENT_CRITERIA_TYPE_QUEST_REWARD_GOLD:
return progresscounter >= achievementCriteria->quest_reward_money.goldInCopper;
case ACHIEVEMENT_CRITERIA_TYPE_GAIN_REPUTATION:
return progresscounter >= achievementCriteria->gain_reputation.reputationAmount;
case ACHIEVEMENT_CRITERIA_TYPE_GAIN_EXALTED_REPUTATION:
return progresscounter >= achievementCriteria->gain_exalted_reputation.numberOfExaltedFactions;
case ACHIEVEMENT_CRITERIA_TYPE_NUMBER_OF_MOUNTS:
return progresscounter >= achievementCriteria->number_of_mounts.mountCount;
case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET:
case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET2:
return progresscounter >= achievementCriteria->be_spell_target.spellCount;
case ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE:
return progresscounter >= achievementCriteria->kill_creature.creatureCount;
case ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL:
return progresscounter >= achievementCriteria->reach_skill_level.skillLevel;
case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL:
return progresscounter >= achievementCriteria->learn_skill_level.skillLevel;
case ACHIEVEMENT_CRITERIA_TYPE_USE_ITEM:
return progresscounter >= achievementCriteria->use_item.itemCount;
case ACHIEVEMENT_CRITERIA_TYPE_USE_GAMEOBJECT:
return progresscounter >= achievementCriteria->use_gameobject.useCount;
case ACHIEVEMENT_CRITERIA_TYPE_BUY_BANK_SLOT:
return progresscounter >= achievementCriteria->buy_bank_slot.numberOfSlots;
case ACHIEVEMENT_CRITERIA_TYPE_EARN_HONORABLE_KILL:
return progresscounter >= achievementCriteria->honorable_kill.killCount;
case ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILL_AT_AREA:
return progresscounter >= achievementCriteria->honorable_kill_at_area.killCount;
case ACHIEVEMENT_CRITERIA_TYPE_HK_CLASS:
return progresscounter >= achievementCriteria->hk_class.count;
case ACHIEVEMENT_CRITERIA_TYPE_HK_RACE:
return progresscounter >= achievementCriteria->hk_race.count;
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_ACHIEVEMENT:
return m_completedAchievements.contains(achievementCriteria->complete_achievement.linkedAchievement);
// These achievements only require counter to be 1 (or higher)
case ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA:
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST:
case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL:
case ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM:
case ACHIEVEMENT_CRITERIA_TYPE_EQUIP_EPIC_ITEM:
case ACHIEVEMENT_CRITERIA_TYPE_DO_EMOTE:
case ACHIEVEMENT_CRITERIA_TYPE_VISIT_BARBER_SHOP:
case ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING:
return progresscounter >= 1;
// unknown or need to be finished:
default:
if (achievementCriteria->raw.field4 > 0)
return progresscounter >= achievementCriteria->raw.field4;
break;
}
return false;
}
#endif
| 412 | 0.984038 | 1 | 0.984038 | game-dev | MEDIA | 0.806726 | game-dev | 0.994658 | 1 | 0.994658 |
magicleap/UnityGLTF-Interactivity | 1,984 | Assets/Interactivity/Playback/Pointers/ActiveCameraPointers.cs | using System;
using Unity.Mathematics;
using UnityEngine;
using UnityGLTF.Interactivity.Playback.Extensions;
namespace UnityGLTF.Interactivity.Playback
{
public struct ActiveCameraPointers
{
// These are readonly in the spec but I'm a rebel
public Pointer<float3> translation;
public Pointer<quaternion> rotation;
public static ActiveCameraPointers CreatePointers()
{
// Unity coordinate system differs from the GLTF one.
// Unity is left-handed with y-up and z-forward.
// GLTF is right-handed with y-up and z-forward.
// Handedness is easiest to swap here though we could do it during deserialization for performance.
var pointers = new ActiveCameraPointers();
pointers.translation = new Pointer<float3>()
{
setter = (v) => Camera.main.transform.localPosition = v.SwapHandedness(),
getter = () => Camera.main.transform.localPosition.SwapHandedness(),
evaluator = (a, b, t) => math.lerp(a, b, t)
};
pointers.rotation = new Pointer<quaternion>()
{
setter = (v) => Camera.main.transform.localRotation = ((Quaternion)v).SwapHandedness(),
getter = () => Camera.main.transform.localRotation.SwapHandedness(),
evaluator = (a, b, t) => math.slerp(a, b, t)
};
return pointers;
}
public IPointer ProcessActiveCameraPointer(StringSpanReader reader)
{
reader.AdvanceToNextToken('/');
// Path so far: /activeCamera/
return reader.AsReadOnlySpan() switch
{
var a when a.Is("translation") => translation,
var a when a.Is("rotation") => rotation,
_ => throw new InvalidOperationException($"Property {reader.ToString()} is unsupported at this time!"),
};
}
}
} | 412 | 0.906755 | 1 | 0.906755 | game-dev | MEDIA | 0.57203 | game-dev | 0.870098 | 1 | 0.870098 |
dboglobal/DBOGLOBAL | 3,957 | DboServer/Server/GameServer/BotAiAction_NavMove.cpp | #include "stdafx.h"
#include "BotAiAction_NavMove.h"
#include "SPSNodeAction_PointMove.h"
#include "SvrScrVariableMap.h"
#include "BotAiAction_DestMove.h"
#include "BotPathFinder.h"
#include "GameServer.h"
#include "GameMain.h"
CBotAiAction_NavMove::CBotAiAction_NavMove(CNpc* pBot, CNtlVector& rDestLoc, bool bRunMode, bool bHaveSecondDestLoc, CNtlVector& rSecondDestLoc, CNtlVector& rDestDir, float fMoveSpeed)
:CBotAiAction(pBot, BOTCONTROL_ACTION_NAVMOVE, "BOTCONTROL_ACTION_NAVMOVE")
{
m_vDestLoc.operator=(rDestLoc);
m_vSecondDestLoc.operator=(rSecondDestLoc);
m_vDestDir.operator=(rDestDir);
m_bRunMode = bRunMode;
m_bHaveSecondDestLoc = bHaveSecondDestLoc;
m_fMoveSpeed = fMoveSpeed;
}
CBotAiAction_NavMove::CBotAiAction_NavMove(CNpc* pBot)
:CBotAiAction(pBot, BOTCONTROL_ACTION_NAVMOVE, "BOTCONTROL_ACTION_NAVMOVE")
{
m_bRunMode = false;
m_bHaveSecondDestLoc = false;
m_fMoveSpeed = INVALID_FLOAT;
}
CBotAiAction_NavMove::~CBotAiAction_NavMove()
{
}
bool CBotAiAction_NavMove::AttachControlScriptNode(CControlScriptNode* pControlScriptNode)
{
CSPSNodeAction_PointMove* pPointMove = dynamic_cast<CSPSNodeAction_PointMove*>(pControlScriptNode);
if (pPointMove)
{
m_vDestLoc = pPointMove->m_vDestLoc;
m_vDestDir = pPointMove->m_vDestDir;
m_bRunMode = pPointMove->m_bRunMode;
m_fMoveSpeed = pPointMove->m_fMoveSpeed;
//get Y loc
if (m_vDestLoc.y == 0.0f)
{
if (GetBot()->GetCurWorld())
{
CGameServer* app = (CGameServer*)g_pApp;
m_vDestLoc.y = app->GetGameMain()->GetWorldManager()->GetAdjustedHeight(GetBot()->GetCurWorld()->GetID(), m_vDestLoc.x, m_vDestLoc.y, m_vDestLoc.z, 5000);
return true;
}
else
{
ERR_LOG(LOG_SCRIPT, "The OBJ %u doesn't belong to any world. GetBot()->GetID() = %u, GetBot()->GetTblidx() = %u", GetBot()->GetObjType(), GetBot()->GetID(), GetBot()->GetTblidx());
}
}
}
else
{
ERR_LOG(LOG_BOTAI, "fail : Cant dynamic_cast from CControlScriptNode[%X] to CSPSNodeAction_PointMove", pControlScriptNode);
}
return false;
}
void CBotAiAction_NavMove::OnEnter()
{
DoNavMove();
}
void CBotAiAction_NavMove::OnContinue()
{
RemoveAllSubControl();
DoNavMove();
}
void CBotAiAction_NavMove::OnPause()
{
}
void CBotAiAction_NavMove::OnExit()
{
// printf("CBotAiAction_NavMove::OnExit() \n");
}
int CBotAiAction_NavMove::OnUpdate(DWORD dwTickDiff, float fMultiple)
{
//printf("CBotAiAction_NavMove::OnUpdate() \n");
if (UpdateSubControlQueue(dwTickDiff, fMultiple) == COMPLETED)
{
if (!m_vDestDir.IsZero() && !m_vDestDir.IsInvalid(false))
{
//here send change heading packet
GetBot()->SetCurDir(m_vDestDir);
}
m_status = COMPLETED;
}
return m_status;
}
void CBotAiAction_NavMove::DoNavMove()
{
//printf("CBotAiAction_NavMove::DoNavMove() \n");
if (GetBot()->HasFunction(NPC_FUNC_FLAG_BUS))
{
sVECTOR3 pavLoc;
m_vDestLoc.CopyTo(pavLoc);
CBotAiAction_DestMove* pDestMove = new CBotAiAction_DestMove(GetBot(), BOTAP_MOVE, 1, &pavLoc, m_bRunMode, m_bHaveSecondDestLoc, m_vSecondDestLoc);
AddSubControlQueue(pDestMove, true);
}
else
{
CNpc* pBot = GetBot();
if (pBot->GetPathFinder())
{
pBot->GetPathFinder()->SetDestLoc(m_vDestLoc);
if (m_fMoveSpeed != INVALID_FLOAT)
{
printf("update move speed \n");
/*CBot::SetWalkingSpeed((CBot *)&v19->vfptr, v68->m_fMoveSpeed);
CBot::SetRunningSpeed((CBot *)&v20->vfptr, v68->m_fMoveSpeed);*/
//pBot->UpdateMoveSpeed(m_fMoveSpeed);
}
if (pBot->GetPathFinder()->PathFind())
{
sVECTOR3 destLoc[DBO_MAX_NEXT_DEST_LOC_COUNT];
BYTE byDestLocCount = pBot->GetPathFinder()->GetAllNextNavLoc(destLoc);
CBotAiAction_DestMove* destmove = new CBotAiAction_DestMove(pBot, BOTAP_MOVE, byDestLocCount, destLoc, m_bRunMode, m_bHaveSecondDestLoc, m_vSecondDestLoc);
AddSubControlQueue(destmove, true);
}
}
else
{
ERR_LOG(LOG_BOTAI, "fail : CBotPathFinder object couldn't be found.(NULL == GetBot()->GetPathFinder())");
}
}
}
| 412 | 0.945475 | 1 | 0.945475 | game-dev | MEDIA | 0.585521 | game-dev,embedded-firmware | 0.988721 | 1 | 0.988721 |
hpfxd/PandaSpigot | 2,071 | patches/api/0025-Add-EntityPickupItemEvent.patch | From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Mechoriet <kevinworm92@gmail.com>
Date: Fri, 6 Oct 2023 20:59:21 +0200
Subject: [PATCH] Add EntityPickupItemEvent
diff --git a/src/main/java/org/bukkit/event/entity/EntityPickupItemEvent.java b/src/main/java/org/bukkit/event/entity/EntityPickupItemEvent.java
new file mode 100644
index 0000000000000000000000000000000000000000..b5ab2f4e8a3c157e763425a80ee1fb676d75b119
--- /dev/null
+++ b/src/main/java/org/bukkit/event/entity/EntityPickupItemEvent.java
@@ -0,0 +1,64 @@
+package org.bukkit.event.entity;
+
+import org.bukkit.entity.Item;
+import org.bukkit.entity.LivingEntity;
+import org.bukkit.event.Cancellable;
+import org.bukkit.event.HandlerList;
+
+/**
+ * Thrown when a entity picks an item up from the ground
+ */
+public class EntityPickupItemEvent extends EntityEvent implements Cancellable {
+ private static final HandlerList handlers = new HandlerList();
+ private final Item item;
+ private boolean cancel = false;
+ private final int remaining;
+
+ public EntityPickupItemEvent(final LivingEntity entity, final Item item, final int remaining) {
+ super(entity);
+ this.item = item;
+ this.remaining = remaining;
+ }
+
+ @Override
+ public LivingEntity getEntity() {
+ return (LivingEntity) entity;
+ }
+
+ /**
+ * Gets the Item picked up by the entity.
+ *
+ * @return Item
+ */
+ public Item getItem() {
+ return item;
+ }
+
+ /**
+ * Gets the amount remaining on the ground, if any
+ *
+ * @return amount remaining on the ground
+ */
+ public int getRemaining() {
+ return remaining;
+ }
+
+ @Override
+ public boolean isCancelled() {
+ return cancel;
+ }
+
+ @Override
+ public void setCancelled(boolean cancel) {
+ this.cancel = cancel;
+ }
+
+ @Override
+ public HandlerList getHandlers() {
+ return handlers;
+ }
+
+ public static HandlerList getHandlerList() {
+ return handlers;
+ }
+}
| 412 | 0.739205 | 1 | 0.739205 | game-dev | MEDIA | 0.516103 | game-dev | 0.869971 | 1 | 0.869971 |
playcanvas/editor | 6,606 | src/editor/scene-settings/scene-settings.ts | import { ObserverSync } from '../../common/observer-sync.ts';
import { formatter as f } from '../../common/utils.ts';
import { GAMMA_NONE, GAMMA_SRGB } from '../../core/constants.ts';
editor.once('load', () => {
const schema = editor.api.globals.schema;
const sceneSettings = {
physics: schema.scene.getDefaultPhysicsSettings(),
render: schema.scene.getDefaultRenderSettings()
};
const settings = editor.api.globals.settings.scene.observer;
// get scene settings
editor.method('sceneSettings', () => {
return settings;
});
// when settings are loaded...
editor.api.globals.settings.scene.on('load', () => {
const sync = settings.sync && settings.sync.enabled;
if (sync) {
settings.sync.enabled = false;
}
// remove priority_scripts
if (editor.api.globals.realtime.scenes.current.data.settings.priority_scripts === undefined &&
settings.has('priority_scripts')) {
settings.unset('priority_scripts');
}
if (sync) {
settings.sync.enabled = true;
}
editor.emit('sceneSettings:load', settings);
});
// migrate camera settings
let entitiesLoaded = false;
let projectUserSettingsLoaded = false;
let migrateEntityHandle = null;
const migrateCameraSettings = () => {
if (!entitiesLoaded || !projectUserSettingsLoaded) {
return;
}
// migrate entities
// NOTE: Defaults are set so we need to force the update
const migrateEntity = (entity) => {
// Defeer the migration to the next frame to ensure entity document has been created
setTimeout(() => {
entity.history.enabled = false;
if (entity.get('components.camera')) {
// gamma correction
const gammaCorrection = settings.get('render.gamma_correction');
const oldGammaCorrection = entity.get('components.camera.gammaCorrection');
entity.set('components.camera.gammaCorrection', gammaCorrection, false, false, true);
if (gammaCorrection !== oldGammaCorrection) {
const msg = [
`Setting ${f.path('components.camera.gammaCorrection')} on ${f.entity(entity)} from`,
`${f.value(oldGammaCorrection)}`,
`to ${f.value(gammaCorrection)}`
].join(' ');
editor.call('console:log:entity', entity, msg, true);
}
// tonemapping
const tonemapping = settings.get('render.tonemapping');
const oldTonemapping = entity.get('components.camera.toneMapping');
entity.set('components.camera.toneMapping', tonemapping, false, false, true);
if (tonemapping !== oldTonemapping) {
const msg = [
`Setting ${f.path('components.camera.toneMapping')} on ${f.entity(entity)} from`,
`${f.value(oldTonemapping)}`,
`to ${f.value(tonemapping)}`
].join(' ');
editor.call('console:log:entity', entity, msg, true);
}
}
entity.history.enabled = true;
});
};
editor.call('entities:list').forEach(migrateEntity);
// remove existing handle if found
if (migrateEntityHandle) {
migrateEntityHandle.unbind();
}
migrateEntityHandle = editor.on('entities:add', migrateEntity);
editor.call('status:clear');
};
if (!editor.projectEngineV2) {
editor.on('entities:load', () => {
entitiesLoaded = true;
migrateCameraSettings();
});
editor.on('settings:projectUser:load', () => {
projectUserSettingsLoaded = true;
migrateCameraSettings();
});
settings.on('render.gamma_correction:set', migrateCameraSettings);
settings.on('render.tonemapping:set', migrateCameraSettings);
}
editor.on('sceneSettings:load', (settings) => {
// sync scene settings
if (!settings.sync) {
settings.sync = new ObserverSync({
item: settings,
prefix: ['settings']
});
// client > server
settings.sync.on('op', (op) => {
editor.call('realtime:scene:op', op);
});
// server > client
editor.on('realtime:scene:op:settings', (op) => {
settings.sync.write(op);
});
}
// set default scene settings
for (const type in sceneSettings) {
for (const key in sceneSettings[type]) {
const path = `${type}.${key}`;
if (!settings.has(path)) {
settings.set(path, sceneSettings[type][key]);
}
}
}
// migrations
const history = settings.history.enabled;
const sync = settings.sync.enabled;
settings.history.enabled = false;
settings.sync.enabled = editor.call('permissions:write');
// gamma correction migration
const oldGammaCorrection = settings.get('render.gamma_correction');
if (oldGammaCorrection !== GAMMA_NONE && oldGammaCorrection !== GAMMA_SRGB) {
const gammaCorrection = GAMMA_SRGB;
settings.set('render.gamma_correction', gammaCorrection);
const msg = [
`Setting scene setting ${f.path('render.gamma_correction')} from`,
`${f.value(oldGammaCorrection)}`,
`to ${f.value(gammaCorrection)}`
].join(' ');
editor.call('console:log:settings', settings, msg);
}
settings.history.enabled = history;
settings.sync.enabled = sync;
});
const onUnload = () => {
if (settings.history) {
settings.history.enabled = false;
}
if (settings.sync) {
settings.sync.enabled = false;
}
settings.set('render.skybox', null);
if (settings.history) {
settings.history.enabled = true;
}
if (settings.sync) {
settings.sync.enabled = true;
}
};
editor.on('realtime:disconnected', onUnload);
editor.on('scene:unload', onUnload);
});
| 412 | 0.815605 | 1 | 0.815605 | game-dev | MEDIA | 0.482367 | game-dev | 0.775313 | 1 | 0.775313 |
mono/VulkanSharp | 1,077 | src/Vulkan/Interop/Helpers.cs | using System;
using System.Runtime.InteropServices;
namespace Vulkan.Interop
{
internal class Structure
{
internal static Vulkan.NativePointer Allocate (Type type)
{
return new NativePointer (new NativeReference (Marshal.SizeOf (type), true));
}
unsafe internal static void MarshalFixedSizeString (byte* dst, string src, int size)
{
var bytes = System.Text.UTF8Encoding.UTF8.GetBytes (src);
size = Math.Min (size - 1, bytes.Length);
int i;
for (i = 0; i < size; i++)
dst [i] = bytes[i];
dst [i] = 0;
}
internal static object MarshalPointerToObject (IntPtr ptr, Type type)
{
if (ptr == IntPtr.Zero)
return null;
return Marshal.PtrToStructure (ptr, type);
}
internal static IntPtr MarshalObjectToPointer (IntPtr ptr, object value)
{
if (value == null) {
if (ptr != IntPtr.Zero)
Marshal.FreeHGlobal (ptr);
return IntPtr.Zero;
} else {
if (ptr == IntPtr.Zero)
ptr = Marshal.AllocHGlobal (Marshal.SizeOf (value));
Marshal.StructureToPtr (value, ptr, false);
}
return ptr;
}
}
}
| 412 | 0.851879 | 1 | 0.851879 | game-dev | MEDIA | 0.674159 | game-dev | 0.576993 | 1 | 0.576993 |
LandSandBoat/server | 6,272 | scripts/quests/bastok/Ayame_and_Kaede.lua | -----------------------------------
-- Ayame and Kaede
-----------------------------------
-- Log ID: 1, Quest ID: 60
-- Kaede : !pos 48 -6 67 236
-- Kagetora : !pos -96 -2 29 236
-- Ensetsu : !pos 33 -6 67 236
-- qm2 : !pos -208 -9 176 173
-- Ryoma : !pos -23 0 -9 252
-----------------------------------
local korrolokaID = zones[xi.zone.KORROLOKA_TUNNEL]
local portBastokID = zones[xi.zone.PORT_BASTOK]
-----------------------------------
local quest = Quest:new(xi.questLog.BASTOK, xi.quest.id.bastok.AYAME_AND_KAEDE)
quest.reward =
{
fame = 30,
fameArea = xi.fameArea.BASTOK,
title = xi.title.SHADOW_WALKER,
}
local function isNMSpawned()
for nmId = korrolokaID.mob.KORROLOKA_LEECH, korrolokaID.mob.KORROLOKA_LEECH + 2 do
if GetMobByID(nmId):isSpawned() then
return true
end
end
return false
end
local function isNMDefeated()
for nmId = korrolokaID.mob.KORROLOKA_LEECH, korrolokaID.mob.KORROLOKA_LEECH + 2 do
if GetMobByID(nmId):isDead() then
return true
end
end
return false
end
quest.sections =
{
{
check = function(player, status, vars)
return status == xi.questStatus.QUEST_AVAILABLE and
player:getMainLvl() >= xi.settings.main.ADVANCED_JOB_LEVEL
end,
[xi.zone.PORT_BASTOK] =
{
['Kaede'] = quest:progressEvent(240),
onEventFinish =
{
[240] = function(player, csid, option, npc)
quest:begin(player)
end,
},
},
},
{
check = function(player, status, vars)
return status == xi.questStatus.QUEST_ACCEPTED
end,
[xi.zone.KORROLOKA_TUNNEL] =
{
['qm2'] =
{
onTrigger = function(player, npc)
if
not isNMSpawned() and
quest:getVar(player, 'Prog') == 2
then
if quest:getLocalVar(player, 'nmDefeated') == 1 then
quest:setVar(player, 'Prog', 3)
if quest:getLocalVar(player, 'isActor') == 1 then
quest:setLocalVar(player, 'isActor', 0)
npc:hideNPC(xi.settings.main.FORCE_SPAWN_QM_RESET_TIME)
end
return quest:keyItem(xi.ki.STRANGELY_SHAPED_CORAL)
else
quest:setLocalVar(player, 'isActor', 1)
for nmId = korrolokaID.mob.KORROLOKA_LEECH, korrolokaID.mob.KORROLOKA_LEECH + 2 do
SpawnMob(nmId)
end
return quest:messageSpecial(korrolokaID.text.SENSE_OF_FOREBODING)
end
end
end,
},
['Korroloka_Leech'] =
{
onMobDeath = function(mob, player, optParams)
if
isNMDefeated() and
quest:getVar(player, 'Prog') == 2
then
quest:setLocalVar(player, 'nmDefeated', 1)
end
end,
},
},
[xi.zone.NORG] =
{
['Ryoma'] =
{
onTrigger = function(player, npc)
if quest:getVar(player, 'Prog') == 4 then
return quest:progressEvent(95)
end
end,
},
onEventFinish =
{
[95] = function(player, csid, option, npc)
npcUtil.giveKeyItem(player, xi.ki.SEALED_DAGGER)
player:delKeyItem(xi.ki.STRANGELY_SHAPED_CORAL)
quest:setVar(player, 'Prog', 5)
end,
},
},
[xi.zone.PORT_BASTOK] =
{
['Ensetsu'] =
{
onTrigger = function(player, npc)
local questProgress = quest:getVar(player, 'Prog')
if
questProgress >= 1 and
questProgress <= 2
then
return quest:progressEvent(242)
elseif questProgress == 3 then
return quest:progressEvent(245)
elseif questProgress == 4 then
return quest:event(243)
elseif questProgress == 5 then
return quest:progressEvent(246, xi.ki.SEALED_DAGGER)
end
end,
},
['Kagetora'] =
{
onTrigger = function(player, npc)
local questProgress = quest:getVar(player, 'Prog')
if questProgress == 0 then
return quest:progressEvent(241)
elseif questProgress > 2 then
return quest:event(244)
end
end,
},
onEventFinish =
{
[241] = function(player, csid, option, npc)
quest:setVar(player, 'Prog', 1)
end,
[242] = function(player, csid, option, npc)
quest:setVar(player, 'Prog', 2)
end,
[245] = function(player, csid, option, npc)
quest:setVar(player, 'Prog', 4)
end,
[246] = function(player, csid, option, npc)
if quest:complete(player) then
player:unlockJob(xi.job.NIN)
player:messageSpecial(portBastokID.text.UNLOCK_NINJA)
end
end,
},
},
},
{
check = function(player, status, vars)
return status == xi.questStatus.QUEST_COMPLETED
end,
[xi.zone.PORT_BASTOK] =
{
['Kaede'] = quest:event(248):replaceDefault(),
},
},
}
return quest
| 412 | 0.943611 | 1 | 0.943611 | game-dev | MEDIA | 0.990348 | game-dev | 0.955311 | 1 | 0.955311 |
SFML/SFML-Game-Development-Book | 1,106 | 08_Graphics/Source/GameState.cpp | #include <Book/GameState.hpp>
#include <SFML/Graphics/RenderWindow.hpp>
GameState::GameState(StateStack& stack, Context context)
: State(stack, context)
, mWorld(*context.window, *context.fonts)
, mPlayer(*context.player)
{
mPlayer.setMissionStatus(Player::MissionRunning);
}
void GameState::draw()
{
mWorld.draw();
}
bool GameState::update(sf::Time dt)
{
mWorld.update(dt);
if (!mWorld.hasAlivePlayer())
{
mPlayer.setMissionStatus(Player::MissionFailure);
requestStackPush(States::GameOver);
}
else if (mWorld.hasPlayerReachedEnd())
{
mPlayer.setMissionStatus(Player::MissionSuccess);
requestStackPush(States::GameOver);
}
CommandQueue& commands = mWorld.getCommandQueue();
mPlayer.handleRealtimeInput(commands);
return true;
}
bool GameState::handleEvent(const sf::Event& event)
{
// Game input handling
CommandQueue& commands = mWorld.getCommandQueue();
mPlayer.handleEvent(event, commands);
// Escape pressed, trigger the pause screen
if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Escape)
requestStackPush(States::Pause);
return true;
} | 412 | 0.96761 | 1 | 0.96761 | game-dev | MEDIA | 0.957677 | game-dev | 0.770957 | 1 | 0.770957 |
reedrosenbluth/oscen | 12,068 | oscen-lib/src/envelope/adsr.rs | use crate::graph::types::EventPayload;
use crate::graph::{
EventInstance, InputEndpoint, NodeKey, ProcessingContext, ProcessingNode,
SignalProcessor, ValueKey,
};
use crate::Node;
const MIN_TIME_SECONDS: f32 = 1.0e-5;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Stage {
Idle,
Attack,
Decay,
Sustain,
Release,
}
#[derive(Debug, Node)]
pub struct AdsrEnvelope {
#[input(event)]
gate: (),
#[input(value)]
attack: f32,
#[input(value)]
decay: f32,
#[input(value)]
sustain: f32,
#[input(value)]
release: f32,
#[output(stream)]
output: f32,
stage: Stage,
attack_samples: u32,
decay_samples: u32,
release_samples: u32,
samples_remaining: u32,
increment: f32,
level: f32,
target_level: f32,
sustain_level: f32,
velocity: f32,
sample_rate: f32,
}
impl AdsrEnvelope {
pub fn new(attack: f32, decay: f32, sustain: f32, release: f32) -> Self {
let mut envelope = Self {
gate: (),
attack,
decay,
sustain,
release,
output: 0.0,
stage: Stage::Idle,
attack_samples: 0,
decay_samples: 0,
release_samples: 0,
samples_remaining: 0,
increment: 0.0,
level: 0.0,
target_level: 0.0,
sustain_level: sustain.clamp(0.0, 1.0),
velocity: 1.0,
sample_rate: 44_100.0,
};
envelope.update_sustain_level();
envelope
}
fn apply_parameters(&mut self, attack: f32, decay: f32, sustain: f32, release: f32) {
self.attack = attack.max(0.0);
self.decay = decay.max(0.0);
self.sustain = sustain.clamp(0.0, 1.0);
self.release = release.max(0.0);
self.update_sustain_level();
}
fn update_sustain_level(&mut self) {
self.sustain_level = (self.sustain * self.velocity).clamp(0.0, 1.0);
self.recalculate_cached_steps();
match self.stage {
Stage::Attack if self.samples_remaining > 0 => {
self.samples_remaining = self.samples_remaining.min(self.attack_samples).max(1);
}
Stage::Decay if self.samples_remaining > 0 => {
self.samples_remaining = self.samples_remaining.min(self.decay_samples).max(1);
}
Stage::Release if self.samples_remaining > 0 => {
self.samples_remaining = self.samples_remaining.min(self.release_samples).max(1);
}
_ => {}
}
match self.stage {
Stage::Decay | Stage::Sustain => self.target_level = self.sustain_level,
Stage::Release => self.target_level = 0.0,
_ => {}
}
if matches!(self.stage, Stage::Attack | Stage::Decay | Stage::Release) {
self.update_increment_for_stage();
}
}
fn recalculate_cached_steps(&mut self) {
let sample_rate = self.sample_rate.max(1.0);
self.attack_samples = (self.attack.max(MIN_TIME_SECONDS) * sample_rate) as u32;
self.attack_samples = self.attack_samples.max(1);
self.decay_samples = (self.decay.max(MIN_TIME_SECONDS) * sample_rate) as u32;
self.decay_samples = self.decay_samples.max(1);
self.release_samples = (self.release.max(MIN_TIME_SECONDS) * sample_rate) as u32;
self.release_samples = self.release_samples.max(1);
}
fn set_stage(&mut self, stage: Stage, _duration_secs: f32, target_level: f32) {
self.stage = stage;
self.target_level = target_level.clamp(0.0, 1.0);
let samples = match stage {
Stage::Attack => self.attack_samples,
Stage::Decay => self.decay_samples,
Stage::Release => self.release_samples,
Stage::Sustain | Stage::Idle => 0,
};
if samples == 0 {
self.samples_remaining = 0;
self.increment = 0.0;
self.level = self.target_level;
if !matches!(stage, Stage::Sustain | Stage::Idle) {
self.complete_stage();
}
} else {
self.samples_remaining = samples;
self.update_increment_for_stage();
}
}
fn update_increment_for_stage(&mut self) {
if self.samples_remaining == 0 {
self.increment = 0.0;
return;
}
let current = self.level.clamp(0.0, 1.0);
self.increment = match self.stage {
Stage::Attack => {
let delta = (1.0 - current).max(0.0);
delta / self.samples_remaining as f32
}
Stage::Decay => {
let delta = self.sustain_level - current;
delta / self.samples_remaining as f32
}
Stage::Release => {
if current <= 0.0 {
0.0
} else {
-current / self.samples_remaining as f32
}
}
Stage::Sustain | Stage::Idle => 0.0,
};
}
fn complete_stage(&mut self) {
match self.stage {
Stage::Attack => {
self.level = 1.0;
self.set_stage(Stage::Decay, self.decay, self.sustain_level);
}
Stage::Decay => {
self.level = self.sustain_level;
self.stage = Stage::Sustain;
self.samples_remaining = 0;
self.increment = 0.0;
}
Stage::Release => {
self.level = 0.0;
self.stage = Stage::Idle;
self.samples_remaining = 0;
self.increment = 0.0;
}
Stage::Sustain => {
self.level = self.sustain_level;
self.samples_remaining = 0;
self.increment = 0.0;
}
Stage::Idle => {
self.level = 0.0;
self.samples_remaining = 0;
self.increment = 0.0;
}
}
}
fn process_stage(&mut self) {
match self.stage {
Stage::Attack | Stage::Decay | Stage::Release => {
if self.samples_remaining > 0 {
self.level += self.increment;
self.samples_remaining -= 1;
self.level = self.level.clamp(0.0, 1.0);
}
if self.samples_remaining == 0 {
self.level = self.target_level;
self.complete_stage();
}
}
Stage::Sustain => {
self.level = self.sustain_level;
}
Stage::Idle => {
self.level = 0.0;
}
}
}
fn handle_gate_event(&mut self, event: &EventInstance) {
let velocity = match &event.payload {
EventPayload::Scalar(v) => *v,
EventPayload::Object(_) => 1.0,
};
if velocity > 0.0 {
self.velocity = velocity.clamp(0.0, 1.0);
self.update_sustain_level();
if self.attack <= MIN_TIME_SECONDS {
self.level = 1.0;
self.set_stage(Stage::Decay, self.decay, self.sustain_level);
} else {
self.set_stage(Stage::Attack, self.attack.max(MIN_TIME_SECONDS), 1.0);
}
} else if self.release <= MIN_TIME_SECONDS {
self.stage = Stage::Idle;
self.level = 0.0;
self.samples_remaining = 0;
self.increment = 0.0;
} else {
self.set_stage(Stage::Release, self.release.max(MIN_TIME_SECONDS), 0.0);
}
}
}
impl SignalProcessor for AdsrEnvelope {
fn init(&mut self, sample_rate: f32) {
self.sample_rate = sample_rate;
self.update_sustain_level();
}
fn process<'a>(&mut self, _sample_rate: f32, context: &mut ProcessingContext<'a>) -> f32 {
let attack = self.get_attack(context);
let decay = self.get_decay(context);
let sustain = self.get_sustain(context);
let release = self.get_release(context);
self.apply_parameters(attack, decay, sustain, release);
for event in self.events_gate(&*context).iter() {
self.handle_gate_event(event);
}
self.process_stage();
self.output = self.level;
self.output
}
fn is_active(&self) -> bool {
// Envelope is inactive only when idle and level is zero
// We still process during Sustain stage even though it's static,
// since we need to handle gate-off events
!matches!(self.stage, Stage::Idle) || self.level > 0.0
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::graph::types::EventPayload;
use crate::graph::Graph;
#[test]
fn reaches_sustain_level() {
let mut graph = Graph::new(48_000.0);
let env = graph.add_node(AdsrEnvelope::new(0.01, 0.02, 0.6, 0.05));
let _ = graph
.insert_value_input(env.attack(), 0.01)
.expect("attack input available");
let _ = graph
.insert_value_input(env.decay(), 0.02)
.expect("decay input available");
let _ = graph
.insert_value_input(env.sustain(), 0.6)
.expect("sustain input available");
let _ = graph
.insert_value_input(env.release(), 0.05)
.expect("release input available");
graph.queue_event(env.gate(), 0, EventPayload::scalar(1.0));
for _ in 0..4_800 {
graph.process().expect("graph processes");
} // 100 ms
let value = graph.get_value(&env.output()).unwrap();
assert!(
value >= 0.5 && value <= 0.65,
"value {} not near sustain",
value
);
}
#[test]
fn release_returns_to_zero() {
let mut graph = Graph::new(48_000.0);
let env = graph.add_node(AdsrEnvelope::new(0.0, 0.0, 0.8, 0.01));
let _ = graph
.insert_value_input(env.attack(), 0.0)
.expect("attack input available");
let _ = graph
.insert_value_input(env.decay(), 0.0)
.expect("decay input available");
let _ = graph
.insert_value_input(env.sustain(), 0.8)
.expect("sustain input available");
let _ = graph
.insert_value_input(env.release(), 0.01)
.expect("release input available");
graph.queue_event(env.gate(), 0, EventPayload::scalar(1.0));
for _ in 0..100 {
graph.process().expect("graph processes on note on");
}
graph.queue_event(env.gate(), 0, EventPayload::scalar(0.0));
for _ in 0..4_800 {
graph.process().expect("graph processes on release");
}
let value = graph.get_value(&env.output()).unwrap();
assert!(value <= 0.01, "value {} not near zero", value);
}
#[test]
fn velocity_scales_output() {
let mut graph = Graph::new(48_000.0);
let env = graph.add_node(AdsrEnvelope::new(0.0, 0.0, 1.0, 0.01));
let _ = graph
.insert_value_input(env.attack(), 0.0)
.expect("attack input available");
let _ = graph
.insert_value_input(env.decay(), 0.0)
.expect("decay input available");
let _ = graph
.insert_value_input(env.sustain(), 1.0)
.expect("sustain input available");
let _ = graph
.insert_value_input(env.release(), 0.01)
.expect("release input available");
graph.queue_event(env.gate(), 0, EventPayload::scalar(0.5));
for _ in 0..100 {
graph.process().expect("graph processes");
}
let value = graph.get_value(&env.output()).unwrap();
assert!(
value >= 0.45 && value <= 0.55,
"value {} not scaled by velocity",
value
);
}
}
| 412 | 0.954804 | 1 | 0.954804 | game-dev | MEDIA | 0.484566 | game-dev | 0.954486 | 1 | 0.954486 |
ondras/rri | 7,223 | src/score.ts | import CellRepo, { Cell } from "./cell-repo.js";
import { Direction, clamp, all as allDirections, Vector } from "./direction.js";
import { NONE, ROAD, RAIL, LAKE, FOREST, EdgeType } from "./edge.js";
export interface Score {
exits: number[];
center: number;
deadends: Deadend[];
road: Cell[];
rail: Cell[];
lakes: number[];
forests: Cell[];
}
interface Deadend {
cell: Cell;
direction: Direction;
}
interface LongestPathContext {
cells: CellRepo;
edgeType: EdgeType;
lockedCells: Set<Cell>;
}
function getNeighbor(cell: Cell, direction: Direction, cells: CellRepo) {
let x = cell.x + Vector[direction][0];
let y = cell.y + Vector[direction][1];
return cells.at(x, y);
}
function getCenterCount(cells: CellRepo) {
return cells.filter(cell => cell.center && cell.tile).length;
}
function getEdgeKey(a: Cell, b: Cell) {
if (a.x > b.x || a.y > b.y) { [a, b] = [b, a]; }
return [a.x, a.y, b.x, b.y].join("/");
}
function getSubgraph(start: Cell, cells: CellRepo) {
interface QueueItem {
cell: Cell;
from: Direction | null;
}
let subgraph: Cell[] = [];
let queue: QueueItem[] = [{cell:start, from: null}];
let lockedEdges = new Set<string>();
while (queue.length) {
let current = queue.shift() as QueueItem;
let cell = current.cell;
if (!cell.tile) { continue; }
subgraph.push(cell);
let tile = cell.tile;
let outDirections = (current.from === null ? allDirections : tile.getEdge(current.from).connects);
outDirections.forEach(d => {
let edgeType = tile.getEdge(d).type;
if (edgeType == NONE) { return; }
let neighbor = getNeighbor(cell, d, cells);
if (!neighbor.tile) { return; }
let neighborEdge = clamp(d+2);
let neighborEdgeType = neighbor.tile.getEdge(neighborEdge).type;
if (neighborEdgeType != edgeType) { return; }
let edgeKey = getEdgeKey(cell, neighbor);
if (lockedEdges.has(edgeKey)) { return; }
lockedEdges.add(edgeKey);
queue.push({cell: neighbor, from: neighborEdge});
});
}
return subgraph;
}
function getConnectedExits(start: Cell, cells: CellRepo) {
return getSubgraph(start, cells).filter(cell => cell.border);
}
function getExits(cells: CellRepo) {
let results: number[] = [];
let exitsArr = cells.filter(cell => cell.border && cell.tile);
let exits = new Set(exitsArr);
while (exits.size > 0) {
let cell = exits.values().next().value;
let connected = getConnectedExits(cell, cells);
if (connected.length > 1) { results.push(connected.length); }
connected.forEach(cell => exits.delete(cell));
}
return results;
}
function getLongestFrom(cell: Cell, from: Direction | null, ctx: LongestPathContext) {
if (!cell.tile) { return []; }
let path: Cell[] = [];
let tile = cell.tile;
let outDirections = (from === null ? allDirections : tile.getEdge(from).connects);
ctx.lockedCells.add(cell);
outDirections
.filter(d => tile.getEdge(d).type == ctx.edgeType)
.forEach(d => {
let neighbor = getNeighbor(cell, d, ctx.cells);
if (neighbor.border || !neighbor.tile) { return; }
if (ctx.lockedCells.has(neighbor)) { return; }
let neighborEdge = clamp(d+2);
let neighborEdgeType = neighbor.tile.getEdge(neighborEdge).type;
if (neighborEdgeType != ctx.edgeType) { return; }
let subpath = getLongestFrom(neighbor, neighborEdge, ctx);
if (subpath.length > path.length) { path = subpath; }
});
ctx.lockedCells.delete(cell);
path.unshift(cell);
return path;
}
function getLongest(edgeType: EdgeType, cells: CellRepo) {
function contains(cell: Cell) {
if (cell.border || !cell.tile) { return; }
let tile = cell.tile;
return allDirections.some(d => tile.getEdge(d).type == edgeType);
}
let starts = cells.filter(contains);
let bestPath: Cell[] = [];
starts.forEach(cell => {
let lockedCells = new Set<Cell>();
let ctx: LongestPathContext = { cells, edgeType, lockedCells };
let path = getLongestFrom(cell, null, ctx);
if (path.length > bestPath.length) { bestPath = path; }
});
return bestPath;
}
function isDeadend(deadend: Deadend, cells: CellRepo) {
const cell = deadend.cell;
const tile = cell.tile;
if (!tile) { return false; }
let edge = tile.getEdge(deadend.direction).type;
if (edge != RAIL && edge != ROAD) { return false; }
let neighbor = getNeighbor(cell, deadend.direction, cells);
if (neighbor.border) { return false; }
if (!neighbor.tile) { return true; }
let neighborEdge = clamp(deadend.direction+2);
return (neighbor.tile.getEdge(neighborEdge).type != edge);
}
function getDeadends(cells: CellRepo) {
let deadends: Deadend[] = [];
cells.filter(cell => !cell.border).forEach(cell => {
allDirections.forEach(direction => {
let deadend: Deadend = { cell, direction };
isDeadend(deadend, cells) && deadends.push(deadend);
});
});
return deadends;
}
function extractLake(lakeCells: Cell[], allCells: CellRepo) {
let pending = [lakeCells.shift()];
let processed: Cell[] = [];
while (pending.length) {
const current = pending.shift() as Cell;
processed.push(current);
const tile = current.tile;
if (!tile) { continue; }
allDirections.filter(d => tile.getEdge(d).type == LAKE).forEach(d => {
let neighbor = getNeighbor(current, d, allCells);
if (!neighbor.tile) { return; }
let neighborEdge = clamp(d+2);
let neighborEdgeType = neighbor.tile.getEdge(neighborEdge).type;
if (neighborEdgeType != LAKE) { return; }
let index = lakeCells.indexOf(neighbor);
if (index == -1) { return; }
lakeCells.splice(index, 1);
pending.push(neighbor);
});
}
return processed;
}
function getLakes(cells: CellRepo) {
function isLake(cell: Cell) {
if (!cell.tile) { return; }
let tile = cell.tile;
return allDirections.some(d => tile.getEdge(d).type == LAKE);
}
let lakeCells = cells.filter(isLake);
let sizes = [];
while (lakeCells.length) {
sizes.push(extractLake(lakeCells, cells).length);
}
return sizes;
}
function getForests(cells: CellRepo) {
function isRailRoad(cell: Cell) {
if (cell.border || !cell.tile) { return; }
let tile = cell.tile;
return allDirections.every(d => tile.getEdge(d).type != FOREST);
}
function hasForestNeighbor(cell: Cell) {
return allDirections.some(d => {
let neighbor = getNeighbor(cell, d, cells);
if (!neighbor.tile) { return; }
let neighborEdge = clamp(d+2);
return (neighbor.tile.getEdge(neighborEdge).type == FOREST);
});
}
return cells.filter(isRailRoad).filter(hasForestNeighbor);
}
export function get(cells: CellRepo): Score {
return {
exits: getExits(cells),
center: getCenterCount(cells),
rail: getLongest(RAIL, cells),
road: getLongest(ROAD, cells),
deadends: getDeadends(cells),
lakes: getLakes(cells),
forests: getForests(cells)
}
}
export function mapExits(score: Score) {
return score.exits.map(count => count == 12 ? 45 : (count-1)*4);
}
export function sumLakes(score: Score) {
return (score.lakes.length > 0 ? score.lakes.sort((a, b) => a-b)[0] : 0);
}
export function sum(score: Score) {
let exits = mapExits(score);
let exitScore = exits.reduce((a, b) => a+b, 0);
let lakeScore = sumLakes(score);
return exitScore
+ score.road.length
+ score.rail.length
+ score.center
- score.deadends.length
+ lakeScore
+ score.forests.length;
}
| 412 | 0.923554 | 1 | 0.923554 | game-dev | MEDIA | 0.832965 | game-dev | 0.948049 | 1 | 0.948049 |
EsotericSoftware/spine-runtimes | 7,566 | spine-haxe/example/src/flixelExamples/FlixelState.hx | /******************************************************************************
* Spine Runtimes License Agreement
* Last updated April 5, 2025. Replaces all prior versions.
*
* Copyright (c) 2013-2025, Esoteric Software LLC
*
* Integration of the Spine Runtimes into software or otherwise creating
* derivative works of the Spine Runtimes is permitted under the terms and
* conditions of Section 2 of the Spine Editor License Agreement:
* http://esotericsoftware.com/spine-editor-license
*
* Otherwise, it is permitted to integrate the Spine Runtimes into software
* or otherwise create derivative works of the Spine Runtimes (collectively,
* "Products"), provided that each user of the Products must obtain their own
* Spine Editor license and redistribution of the Products in any form must
* include this license and copyright notice.
*
* THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES,
* BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*****************************************************************************/
package flixelExamples;
import flixel.ui.FlxButton;
import flixel.group.FlxSpriteGroup;
import flixel.FlxSprite;
import flixel.graphics.FlxGraphic;
import spine.animation.AnimationStateData;
import openfl.Assets;
import spine.atlas.TextureAtlas;
import spine.SkeletonData;
import spine.flixel.SkeletonSprite;
import spine.flixel.FlixelTextureLoader;
import flixel.FlxG;
import flixel.FlxState;
import flixel.text.FlxText;
class FlixelState extends FlxState
{
var spineSprite:SkeletonSprite;
var sprite:FlxSprite;
var sprite2:FlxSprite;
var myText:FlxText;
var group:FlxSpriteGroup;
var justSetWalking = false;
var jumping = false;
var scale = 4;
var speed:Float;
override public function create():Void
{
FlxG.cameras.bgColor = 0xffa1b2b0;
// setting speed of spineboy (450 is the speed to not let him slide)
speed = 450 / scale;
// creating a group
group = new FlxSpriteGroup();
group.setPosition(50, 50);
add(group);
// creating the sprite to check overlapping
sprite = new FlxSprite();
sprite.loadGraphic(FlxGraphic.fromRectangle(150, 100, 0xff8d008d));
group.add(sprite);
// creating the text to display overlapping state
myText = new FlxText(0, 25, 150, "", 16);
myText.alignment = CENTER;
group.add(myText);
var button = new FlxButton(0, 0, "Next scene", () -> FlxG.switchState(() -> new BasicExample()));
button.setPosition(FlxG.width * .75, FlxG.height / 10);
add(button);
// creating a sprite for the floor
var floor = new FlxSprite();
floor.loadGraphic(FlxGraphic.fromRectangle(FlxG.width, FlxG.height - 100, 0xff822f02));
floor.y = FlxG.height - 100;
add(floor);
// instructions
var groupInstructions = new FlxSpriteGroup();
groupInstructions.setPosition(50, 405);
groupInstructions.add(new FlxText(0, 0, 200, "Left/Right - Move", 16));
groupInstructions.add(new FlxText(0, 25, 150, "Space - Jump", 16));
groupInstructions.add(new FlxText(200, 25, 400, "Click the button for the next example", 16));
add(groupInstructions);
// loading spineboy
var atlas = new TextureAtlas(Assets.getText("assets/spineboy.atlas"), new FlixelTextureLoader("assets/spineboy.atlas"));
var skeletondata = SkeletonData.from(Assets.getText("assets/spineboy-pro.json"), atlas, 1/scale);
var animationStateData = new AnimationStateData(skeletondata);
spineSprite = new SkeletonSprite(skeletondata, animationStateData);
// positioning spineboy
spineSprite.setPosition(.5 * FlxG.width, .5 * FlxG.height);
// setting mix times
animationStateData.defaultMix = 0.5;
animationStateData.setMixByName("idle", "walk", 0.1);
animationStateData.setMixByName("walk", "idle", 0.1);
animationStateData.setMixByName("idle", "idle-turn", 0.05);
animationStateData.setMixByName("idle-turn", "idle", 0.05);
animationStateData.setMixByName("idle-turn", "walk", 0.3);
animationStateData.setMixByName("idle", "jump", 0);
animationStateData.setMixByName("jump", "idle", 0.05);
animationStateData.setMixByName("jump", "walk", 0.05);
animationStateData.setMixByName("walk", "jump", 0.05);
// setting idle animation
spineSprite.state.setAnimationByName(0, "idle", true);
// setting y offset function to move object body while jumping
var hip = spineSprite.skeleton.findBone("hip");
var initialY = 0.;
var initialOffsetY = 0.;
spineSprite.state.onStart.add(entry -> {
if (entry.animation.name == "jump") {
initialY = spineSprite.y;
initialOffsetY = spineSprite.offsetY;
}
});
spineSprite.state.onComplete.add(entry -> {
if (entry.animation.name == "jump") {
jumping = false;
spineSprite.y = initialY;
spineSprite.offsetY = initialOffsetY;
}
});
var diff = .0;
spineSprite.afterUpdateWorldTransforms = spineSprite -> {
if (jumping) {
diff -= hip.y;
spineSprite.offsetY -= diff;
spineSprite.y += diff;
}
diff = hip.y;
}
// adding spineboy to the stage
add(spineSprite);
// FlxG.debugger.visible = !FlxG.debugger.visible;
// debug ui
// FlxG.debugger.visible = true;
// FlxG.debugger.drawDebug = true;
// FlxG.log.redirectTraces = true;
// FlxG.debugger.track(spineSprite);
// FlxG.watch.add(spineSprite, "width");
// FlxG.watch.add(spineSprite, "offsetY");
// FlxG.watch.add(spineSprite, "y");
// FlxG.watch.add(this, "jumping");
super.create();
}
var justSetIdle = true;
override public function update(elapsed:Float):Void
{
if (FlxG.overlap(spineSprite, group)) {
myText.text = "Overlapping";
} else {
myText.text = "Non overlapping";
}
if (!jumping && FlxG.keys.anyJustPressed([SPACE])) {
spineSprite.state.setAnimationByName(0, "jump", false);
jumping = true;
justSetIdle = false;
justSetWalking = false;
}
if (FlxG.keys.anyJustPressed([J])) {
// spineSprite.antialiasing = !spineSprite.antialiasing;
FlxG.debugger.visible = !FlxG.debugger.visible;
}
if (FlxG.keys.anyPressed([RIGHT, LEFT])) {
justSetIdle = false;
var flipped = false;
var deltaX;
if (FlxG.keys.anyPressed([RIGHT])) {
if (spineSprite.flipX == true) flipped = true;
spineSprite.flipX = false;
}
if (FlxG.keys.anyPressed([LEFT])) {
if (spineSprite.flipX == false) flipped = true;
spineSprite.flipX = true;
}
deltaX = (spineSprite.flipX == false ? 1 : -1) * speed * elapsed;
spineSprite.x += deltaX;
if (!jumping && !justSetWalking) {
justSetWalking = true;
if (flipped) {
spineSprite.state.setAnimationByName(0, "idle-turn", false);
spineSprite.state.addAnimationByName(0, "walk", true, 0);
} else {
spineSprite.state.setAnimationByName(0, "walk", true);
}
}
} else if (!jumping && !justSetIdle) {
justSetWalking = false;
justSetIdle = true;
spineSprite.state.setAnimationByName(0, "idle", true);
}
super.update(elapsed);
}
}
| 412 | 0.527848 | 1 | 0.527848 | game-dev | MEDIA | 0.938452 | game-dev | 0.718623 | 1 | 0.718623 |
Ploaj/HSDLib | 9,114 | HSDRaw/Common/HSD_JOBJ.cs | using HSDRaw.Common.Animation;
using System;
using System.ComponentModel;
using System.Text;
namespace HSDRaw.Common
{
[Flags]
public enum JOBJ_FLAG
{
SKELETON = (1 << 0),
SKELETON_ROOT = (1 << 1),
ENVELOPE_MODEL = (1 << 2),
CLASSICAL_SCALING = (1 << 3),
HIDDEN = (1 << 4),
PTCL = (1 << 5),
MTX_DIRTY = (1 << 6),
LIGHTING = (1 << 7),
TEXGEN = (1 << 8),
BILLBOARD = (1 << 9),
VBILLBOARD = (2 << 9),
HBILLBOARD = (3 << 9),
RBILLBOARD = (4 << 9),
INSTANCE = (1 << 12),
PBILLBOARD = (1 << 13),
SPLINE = (1 << 14),
FLIP_IK = (1 << 15),
SPECULAR = (1 << 16),
USE_QUATERNION = (1 << 17),
OPA = (1 << 18),
XLU = (1 << 19),
TEXEDGE = (1 << 20),
NULL = (0 << 21),
JOINT1 = (1 << 21),
JOINT2 = (2 << 21),
EFFECTOR = (3 << 21),
USER_DEFINED_MTX = (1 << 23),
MTX_INDEPEND_PARENT = (1 << 24),
MTX_INDEPEND_SRT = (1 << 25),
ROOT_OPA = (1 << 28),
ROOT_XLU = (1 << 29),
ROOT_TEXEDGE = (1 << 30),
// custom
MTX_SCALE_COMPENSATE = (1 << 26),
}
public class HSD_JOBJ : HSDTreeAccessor<HSD_JOBJ>
{
public override int TrimmedSize { get; } = 0x40;
/// <summary>
/// Used for class lookup, but you can put whatever you want here
/// </summary>
public string ClassName
{
get => _s.GetString(0x00);
set => _s.SetString(0x00, value);
}
public JOBJ_FLAG Flags
{
get => (JOBJ_FLAG)_s.GetInt32(0x04);
set => _s.SetInt32(0x04, (int)value);
}
public override HSD_JOBJ Child { get => _s.GetReference<HSD_JOBJ>(0x08); set => _s.SetReference(0x08, value); }
public override HSD_JOBJ Next { get => _s.GetReference<HSD_JOBJ>(0x0C); set => _s.SetReference(0x0C, value); }
public HSD_DOBJ Dobj { get => !Flags.HasFlag(JOBJ_FLAG.SPLINE) && !Flags.HasFlag(JOBJ_FLAG.PTCL) ? _s.GetReference<HSD_DOBJ>(0x10) : null; set { _s.SetReference(0x10, value); Flags &= ~JOBJ_FLAG.SPLINE; Flags &= ~JOBJ_FLAG.PTCL; } }
[TypeConverter(typeof(ExpandableObjectConverter))]
public HSD_Spline Spline { get => Flags.HasFlag(JOBJ_FLAG.SPLINE) ? _s.GetReference<HSD_Spline>(0x10) : null; set { _s.SetReference(0x10, value); Flags |= JOBJ_FLAG.SPLINE; } }
[TypeConverter(typeof(ExpandableObjectConverter))]
public HSD_ParticleJoint ParticleJoint { get => Flags.HasFlag(JOBJ_FLAG.PTCL) ? _s.GetReference<HSD_ParticleJoint>(0x10) : null; set { _s.SetReference(0x10, value); Flags |= JOBJ_FLAG.PTCL; } }
public float RX { get => _s.GetFloat(0x14); set => _s.SetFloat(0x14, value); }
public float RY { get => _s.GetFloat(0x18); set => _s.SetFloat(0x18, value); }
public float RZ { get => _s.GetFloat(0x1C); set => _s.SetFloat(0x1C, value); }
public float SX { get => _s.GetFloat(0x20); set => _s.SetFloat(0x20, value); }
public float SY { get => _s.GetFloat(0x24); set => _s.SetFloat(0x24, value); }
public float SZ { get => _s.GetFloat(0x28); set => _s.SetFloat(0x28, value); }
public float TX { get => _s.GetFloat(0x2C); set => _s.SetFloat(0x2C, value); }
public float TY { get => _s.GetFloat(0x30); set => _s.SetFloat(0x30, value); }
public float TZ { get => _s.GetFloat(0x34); set => _s.SetFloat(0x34, value); }
[TypeConverter(typeof(ExpandableObjectConverter))]
public HSD_Matrix4x3 InverseWorldTransform { get => _s.GetReference<HSD_Matrix4x3>(0x38); set => _s.SetReference(0x38, value); }
public HSD_ROBJ ROBJ { get => _s.GetReference<HSD_ROBJ>(0x3C); set => _s.SetReference(0x3C, value); }
protected override int Trim()
{
// quit optimizing these away
_s.CanBeBuffer = false;
return base.Trim();
}
/// <summary>
///
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public float GetDefaultValue(JointTrackType type)
{
switch (type)
{
case JointTrackType.HSD_A_J_TRAX: return TX;
case JointTrackType.HSD_A_J_TRAY: return TY;
case JointTrackType.HSD_A_J_TRAZ: return TZ;
case JointTrackType.HSD_A_J_ROTX: return RX;
case JointTrackType.HSD_A_J_ROTY: return RY;
case JointTrackType.HSD_A_J_ROTZ: return RZ;
case JointTrackType.HSD_A_J_SCAX: return SX;
case JointTrackType.HSD_A_J_SCAY: return SY;
case JointTrackType.HSD_A_J_SCAZ: return SZ;
}
return 0;
}
/// <summary>
/// Autometically sets needed flags for self and all children
/// </summary>
public void UpdateFlags()
{
UpdateFlags(true);
}
/// <summary>
/// Autometically sets needed flags for self and all children
/// </summary>
private void UpdateFlags(bool isRoot)
{
// process child
if (Child != null)
Child.UpdateFlags(false);
// process sibling
if (Next != null)
Next.UpdateFlags(false);
// check dobj flags
if (Dobj != null)
{
bool xlu = false;
bool opa = false;
bool lighting = false;
bool specular = false;
bool envelope = false;
foreach (var dobj in Dobj.List)
{
var mobj = dobj.Mobj;
if (mobj != null)
{
// get xlu or opa
if (mobj.RenderFlags.HasFlag(RENDER_MODE.XLU))
xlu = true;
else
opa = true;
// check if lighting is enabled
if (mobj.RenderFlags.HasFlag(RENDER_MODE.DIFFUSE))
lighting = true;
// check if specular is enabled
if (mobj.RenderFlags.HasFlag(RENDER_MODE.SPECULAR))
specular = true;
}
// check if model is enveloped
if (dobj.Pobj != null)
{
foreach (var pobj in dobj.Pobj.List)
{
if (pobj.Flags.HasFlag(POBJ_FLAG.ENVELOPE))
envelope = true;
}
}
}
SetFlag(JOBJ_FLAG.OPA, opa);
SetFlag(JOBJ_FLAG.XLU | JOBJ_FLAG.TEXEDGE, xlu);
SetFlag(JOBJ_FLAG.SPECULAR, specular);
SetFlag(JOBJ_FLAG.LIGHTING, lighting);
SetFlag(JOBJ_FLAG.ENVELOPE_MODEL, envelope);
//if (xlu)
// Flags |= JOBJ_FLAG.XLU | JOBJ_FLAG.TEXEDGE;
//else
// Flags &= ~JOBJ_FLAG.XLU;
}
// check if this joint is part of the skeleton
SetFlag(JOBJ_FLAG.SKELETON, InverseWorldTransform != null);
// set root flags
SetFlag(JOBJ_FLAG.ROOT_XLU, ChildHasFlag(Child, JOBJ_FLAG.XLU));
SetFlag(JOBJ_FLAG.ROOT_OPA, ChildHasFlag(Child, JOBJ_FLAG.OPA));
SetFlag(JOBJ_FLAG.ROOT_TEXEDGE, ChildHasFlag(Child, JOBJ_FLAG.TEXEDGE));
// TODO: if this joint has any mesh that are not single bound
if (isRoot && ChildHasFlag(Child, JOBJ_FLAG.SKELETON))
SetFlag(JOBJ_FLAG.SKELETON_ROOT, true);
// SetFlag(JOBJ_FLAG.SKELETON_ROOT, isRoot && ChildHasFlag(Child, JOBJ_FLAG.SKELETON));
}
/// <summary>
///
/// </summary>
/// <param name="jobj"></param>
/// <param name="flag"></param>
/// <returns></returns>
private static bool ChildHasFlag(HSD_JOBJ jobj, JOBJ_FLAG flag)
{
// joint is null
if (jobj == null)
return false;
// joint has flag
if (jobj.Flags.HasFlag(flag))
return true;
// check if child has flag
if (jobj.Child != null && ChildHasFlag(jobj.Child, flag))
return true;
// check if sibling has flag
if (jobj.Next != null && ChildHasFlag(jobj.Next, flag))
return true;
return false;
}
/// <summary>
///
/// </summary>
/// <param name="flag"></param>
/// <param name="value"></param>
private void SetFlag(JOBJ_FLAG flag, bool value)
{
if (value)
Flags |= flag;
else
Flags &= ~flag;
}
}
}
| 412 | 0.937868 | 1 | 0.937868 | game-dev | MEDIA | 0.604706 | game-dev,graphics-rendering | 0.837321 | 1 | 0.837321 |
boo-lang/boo | 2,929 | lib/antlr-2.7.5/antlr/CSharpCharFormatter.java | package antlr;
/* ANTLR Translator Generator
* Project led by Terence Parr at http://www.jGuru.com
* Software rights: http://www.antlr.org/license.html
*
* $Id:$
*/
//
// ANTLR C# Code Generator by Kunle Odutola : kunle UNDERSCORE odutola AT hotmail DOT com
//
class CSharpCharFormatter implements CharFormatter {
/** Given a character value, return a string representing the character
* that can be embedded inside a string literal or character literal
* This works for Java/C/C++ code-generation and languages with compatible
* special-character-escapment.
* Code-generators for languages should override this method.
* @param c The character of interest.
* @param forCharLiteral true to escape for char literal, false for string literal
*/
public String escapeChar(int c, boolean forCharLiteral) {
switch (c)
{
// case GrammarAnalyzer.EPSILON_TYPE : return "<end-of-token>";
case '\n' : return "\\n";
case '\t' : return "\\t";
case '\r' : return "\\r";
case '\\' : return "\\\\";
case '\'' : return forCharLiteral ? "\\'" : "'";
case '"' : return forCharLiteral ? "\"" : "\\\"";
default :
if ( c<' '||c>126 )
{
if ( ( 0x0000 <= c ) && ( c <= 0x000F ) )
{
return "\\u000" + Integer.toString(c,16);
}
else if ( ( 0x0010 <= c ) && ( c <= 0x00FF ) )
{
return "\\u00" + Integer.toString(c,16);
}
else if ( ( 0x0100 <= c ) && ( c <= 0x0FFF ))
{
return "\\u0" + Integer.toString(c,16);
}
else
{
return "\\u" + Integer.toString(c,16);
}
}
else
{
return String.valueOf((char)c);
}
}
}
/** Converts a String into a representation that can be use as a literal
* when surrounded by double-quotes.
* @param s The String to be changed into a literal
*/
public String escapeString(String s)
{
String retval = new String();
for (int i = 0; i < s.length(); i++)
{
retval += escapeChar(s.charAt(i), false);
}
return retval;
}
/** Given a character value, return a string representing the character
* literal that can be recognized by the target language compiler.
* This works for languages that use single-quotes for character literals.
* Code-generators for languages should override this method.
* @param c The character of interest.
*/
public String literalChar(int c)
{
return "'" + escapeChar(c, true) + "'";
}
/** Converts a String into a string literal
* This works for languages that use double-quotes for string literals.
* Code-generators for languages should override this method.
* @param s The String to be changed into a literal
*/
public String literalString(String s)
{
//return "\"" + escapeString(s) + "\"";
return "@\"\"\"" + escapeString(s) + "\"\"\"";
}
}
| 412 | 0.898565 | 1 | 0.898565 | game-dev | MEDIA | 0.415646 | game-dev | 0.941946 | 1 | 0.941946 |
Dysoch/DyTech | 2,389 | Secret stuff/CORE-DyTech-Core_2.0.0/prototypes/tile/tiles.lua | data.raw["tile"]["sand"].needs_correction = false
data.raw["tile"]["sand"].minable = {hardness = 0.1, mining_time = 0.25, result = "sand"}
data.raw["tile"]["sand"].mined_sound = {filename = "__base__/sound/deconstruct-bricks.ogg"}
data.raw["tile"]["sand"].walking_speed_modifier = 0.9
local sandbag_vehicle_speed_modifier = 1.1
data:extend(
{
{
type = "tile",
name = "sandbag",
needs_correction = false,
minable = {hardness = 0.2, mining_time = 0.5, result = "sandbag"},
mined_sound = { filename = "__base__/sound/deconstruct-bricks.ogg" },
collision_mask = {"ground-tile"},
walking_speed_modifier = 1.1,
layer = 101,
variants =
{
main =
{
{
picture = "__CORE-DyTech-Core__/graphics/terrain/sandbag/1.png",
count = 16,
size = 1
},
{
picture = "__CORE-DyTech-Core__/graphics/terrain/sandbag/2.png",
count = 4,
size = 2,
probability = 0.39,
},
{
picture = "__CORE-DyTech-Core__/graphics/terrain/sandbag/4.png",
count = 4,
size = 4,
probability = 1,
},
},
inner_corner =
{
picture = "__CORE-DyTech-Core__/graphics/terrain/sandbag/inner-corner.png",
count = 8
},
outer_corner =
{
picture = "__CORE-DyTech-Core__/graphics/terrain/sandbag/outer-corner.png",
count = 8
},
side =
{
picture = "__CORE-DyTech-Core__/graphics/terrain/sandbag/side.png",
count = 8
},
u_transition =
{
picture = "__CORE-DyTech-Core__/graphics/terrain/sandbag/u.png",
count = 8
},
o_transition =
{
picture = "__CORE-DyTech-Core__/graphics/terrain/sandbag/o.png",
count = 1
}
},
walking_sound =
{
{
filename = "__base__/sound/walking/concrete-01.ogg",
volume = 1.2
},
{
filename = "__base__/sound/walking/concrete-02.ogg",
volume = 1.2
},
{
filename = "__base__/sound/walking/concrete-03.ogg",
volume = 1.2
},
{
filename = "__base__/sound/walking/concrete-04.ogg",
volume = 1.2
}
},
map_color={r=139, g=104, b=39},
ageing=0,
vehicle_friction_modifier = sandbag_vehicle_speed_modifier
},
}) | 412 | 0.690574 | 1 | 0.690574 | game-dev | MEDIA | 0.80727 | game-dev | 0.887096 | 1 | 0.887096 |
swegener/sdcc | 3,224 | sim/ucsim/src/core/utils.src/errorcl.h | /*
* Simulator of microcontrollers (errorcl.h)
*
* Copyright (C) 1997 Drotos Daniel
*
* To contact author send email to dr.dkdb@gmail.com
*
*/
/* This file is part of microcontroller simulator: ucsim.
UCSIM 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.
UCSIM 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 UCSIM; see the file COPYING. If not, write to the Free
Software Foundation, 59 Temple Place - Suite 330, Boston, MA
02111-1307, USA. */
/*@1@*/
#ifndef ERRORCL_HEADER
#define ERRORCL_HEADER
#include <string.h>
// prj
#include "pobjcl.h"
#include "stypes.h"
extern struct id_element error_on_off_names[];
enum error_on_off {
ERROR_PARENT,
ERROR_ON,
ERROR_OFF
};
const int err_stop= (err_unknown|err_error);
class cl_error_class: public cl_base
{
protected:
enum error_type type;
//char *name;
enum error_on_off on;
public:
cl_error_class(enum error_type typ, const char *aname,
enum error_on_off be_on= ERROR_PARENT);
cl_error_class(enum error_type typ, const char *aname,
class cl_error_class *parent,
enum error_on_off be_on= ERROR_PARENT);
enum error_on_off get_on(void) { return(on); }
void set_on(enum error_on_off val);
bool is_on(void);
enum error_type get_type(void);
const char *get_type_name(void);
//char *get_name(void);
};
class cl_error_registry
{
public:
cl_error_registry(void);
class cl_error_class *find(const char *type_name)
{
if (0 == registered_errors)
return 0;
return static_cast<class cl_error_class *>(registered_errors->first_that(compare, static_cast<const void *>(type_name)));
}
static class cl_list *get_list(void)
{
return registered_errors;
}
protected:
class cl_error_class *register_error(class cl_error_class *error_class)
{
if (!registered_errors)
registered_errors= new cl_list(2, 2, "registered errors");
registered_errors->add(error_class);
return error_class;
}
private:
static class cl_list *registered_errors;
static int compare(const void *obj1, const void *obj2)
{
return (static_cast<const class cl_base *>(obj1))->is_named(static_cast<const char *>(obj2));
}
};
class cl_commander_base; //forward
class cl_error: public cl_base
{
protected:
class cl_error_class *classification;
public:
bool inst; // Occurred during instruction execution
t_addr PC; // Address of the instruction
public:
cl_error(void);
virtual ~cl_error(void);
virtual int init(void);
public:
virtual enum error_type get_type(void);
virtual enum error_on_off get_on(void);
virtual bool is_on(void);
virtual class cl_error_class *get_class(void) { return(classification); }
virtual void print(class cl_commander_base *c);
virtual const char *get_type_name(void);
};
#endif
/* End of utils.src/errorcl.h */
| 412 | 0.906641 | 1 | 0.906641 | game-dev | MEDIA | 0.293376 | game-dev | 0.746671 | 1 | 0.746671 |
222464/PGE | 2,038 | pge/source/pge/rendering/octree/OctreeNode.h | #pragma once
#include <pge/system/Uncopyable.h>
#include <pge/constructs/AABB3D.h>
#include <pge/constructs/Point3i.h>
#include <pge/scene/SceneObjectRef.h>
#include <memory>
#include <array>
#include <unordered_set>
#include <mutex>
#include <thread>
namespace pge {
class OctreeNode : public Uncopyable {
private:
OctreeNode* _pParent;
class Octree* _pOctree;
bool _hasChildren;
std::array<std::unique_ptr<OctreeNode>, 8> _children;
std::unordered_set<SceneObjectRef, SceneObjectRef> _occupants;
AABB3D _region;
int _level;
int _numOccupantsBelow;
void getPossibleOccupantPosition(const SceneObjectRef &oc, Point3i &point);
void addToThisLevel(const SceneObjectRef &oc);
// Returns true if occupant was added to children
bool addToChildren(const SceneObjectRef &oc);
void destroyChildren() {
for (int i = 0; i < 8; i++)
_children[i].reset();
_hasChildren = false;
}
void getOccupants(std::unordered_set<SceneObjectRef, SceneObjectRef> &occupants);
void partition();
void merge();
void update(const SceneObjectRef &oc);
void remove(const SceneObjectRef &oc);
void removeForDeletion(std::unordered_set<SceneObjectRef, SceneObjectRef> &occupants);
public:
OctreeNode()
: _hasChildren(false), _numOccupantsBelow(0)
{}
OctreeNode(const AABB3D ®ion, int level, OctreeNode* pParent, class Octree* pOctree);
// For use after using default constructor
void create(const AABB3D ®ion, int level, OctreeNode* pParent, class Octree* pOctree);
class Octree* getTree() const {
return _pOctree;
}
void add(const SceneObjectRef &oc);
const AABB3D &getRegion() const {
return _region;
}
void getAllOccupantsBelow(std::vector<SceneObjectRef> &occupants);
void getAllOccupantsBelow(std::unordered_set<SceneObjectRef, SceneObjectRef> &occupants);
int getNumOccupantsBelow() const {
return _numOccupantsBelow;
}
void pruneDeadReferences();
friend class SceneObject;
friend class Octree;
friend class DynamicOctree;
};
} | 412 | 0.859986 | 1 | 0.859986 | game-dev | MEDIA | 0.576603 | game-dev | 0.622969 | 1 | 0.622969 |
Source-SDK-Archives/source-sdk-2004 | 4,249 | src_mod/cl_dll/hl2_hud/c_weapon_gravitygun.cpp | //========= Copyright 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#include "cbase.h"
#include "keydefs.h"
#include "hud.h"
#include "in_buttons.h"
#include "beamdraw.h"
#include "c_weapon__stubs.h"
#include "ClientEffectPrecacheSystem.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
CLIENTEFFECT_REGISTER_BEGIN( PrecacheEffectGravityGun )
CLIENTEFFECT_MATERIAL( "sprites/physbeam" )
CLIENTEFFECT_REGISTER_END()
class C_BeamQuadratic : public CDefaultClientRenderable
{
public:
C_BeamQuadratic();
void Update( C_BaseEntity *pOwner );
// IClientRenderable
virtual const Vector& GetRenderOrigin( void ) { return m_worldPosition; }
virtual const QAngle& GetRenderAngles( void ) { return vec3_angle; }
virtual bool ShouldDraw( void ) { return true; }
virtual bool IsTransparent( void ) { return true; }
virtual bool ShouldReceiveProjectedTextures( int flags ) { return false; }
virtual int DrawModel( int flags );
// Returns the bounds relative to the origin (render bounds)
virtual void GetRenderBounds( Vector& mins, Vector& maxs )
{
// bogus. But it should draw if you can see the end point
mins.Init(-32,-32,-32);
maxs.Init(32,32,32);
}
C_BaseEntity *m_pOwner;
Vector m_targetPosition;
Vector m_worldPosition;
int m_active;
int m_glueTouching;
int m_viewModelIndex;
};
class C_WeaponGravityGun : public C_BaseCombatWeapon
{
DECLARE_CLASS( C_WeaponGravityGun, C_BaseCombatWeapon );
public:
C_WeaponGravityGun() {}
DECLARE_CLIENTCLASS();
DECLARE_PREDICTABLE();
int KeyInput( int down, int keynum, const char *pszCurrentBinding )
{
if ( gHUD.m_iKeyBits & IN_ATTACK )
{
switch ( keynum )
{
case K_MWHEELUP:
gHUD.m_iKeyBits |= IN_WEAPON1;
return 0;
case K_MWHEELDOWN:
gHUD.m_iKeyBits |= IN_WEAPON2;
return 0;
}
}
// Allow engine to process
return BaseClass::KeyInput( down, keynum, pszCurrentBinding );
}
void OnDataChanged( DataUpdateType_t updateType )
{
BaseClass::OnDataChanged( updateType );
m_beam.Update( this );
}
private:
C_WeaponGravityGun( const C_WeaponGravityGun & );
C_BeamQuadratic m_beam;
};
STUB_WEAPON_CLASS_IMPLEMENT( weapon_physgun, C_WeaponGravityGun );
IMPLEMENT_CLIENTCLASS_DT( C_WeaponGravityGun, DT_WeaponGravityGun, CWeaponGravityGun )
RecvPropVector( RECVINFO_NAME(m_beam.m_targetPosition,m_targetPosition) ),
RecvPropVector( RECVINFO_NAME(m_beam.m_worldPosition, m_worldPosition) ),
RecvPropInt( RECVINFO_NAME(m_beam.m_active, m_active) ),
RecvPropInt( RECVINFO_NAME(m_beam.m_glueTouching, m_glueTouching) ),
RecvPropInt( RECVINFO_NAME(m_beam.m_viewModelIndex, m_viewModelIndex) ),
END_RECV_TABLE()
C_BeamQuadratic::C_BeamQuadratic()
{
m_pOwner = NULL;
}
void C_BeamQuadratic::Update( C_BaseEntity *pOwner )
{
m_pOwner = pOwner;
if ( m_active )
{
if ( m_hRenderHandle == INVALID_CLIENT_RENDER_HANDLE )
{
ClientLeafSystem()->AddRenderable( this, RENDER_GROUP_TRANSLUCENT_ENTITY );
}
else
{
ClientLeafSystem()->RenderableChanged( m_hRenderHandle );
}
}
else if ( !m_active && m_hRenderHandle != INVALID_CLIENT_RENDER_HANDLE )
{
ClientLeafSystem()->RemoveRenderable( m_hRenderHandle );
}
}
int C_BeamQuadratic::DrawModel( int )
{
Vector points[3];
QAngle tmpAngle;
if ( !m_active )
return 0;
C_BaseEntity *pEnt = cl_entitylist->GetEnt( m_viewModelIndex );
if ( !pEnt )
return 0;
pEnt->GetAttachment( 1, points[0], tmpAngle );
points[1] = 0.5 * (m_targetPosition + points[0]);
// a little noise 11t & 13t should be somewhat non-periodic looking
//points[1].z += 4*sin( gpGlobals->curtime*11 ) + 5*cos( gpGlobals->curtime*13 );
points[2] = m_worldPosition;
IMaterial *pMat = materials->FindMaterial( "sprites/physbeam", TEXTURE_GROUP_CLIENT_EFFECTS );
Vector color;
if ( m_glueTouching )
{
color.Init(1,0,0);
}
else
{
color.Init(1,1,1);
}
float scrollOffset = gpGlobals->curtime - (int)gpGlobals->curtime;
materials->Bind( pMat );
DrawBeamQuadratic( points[0], points[1], points[2], 13, color, scrollOffset );
return 1;
}
| 412 | 0.957538 | 1 | 0.957538 | game-dev | MEDIA | 0.70342 | game-dev | 0.579675 | 1 | 0.579675 |
Potion-Studios/BYG | 2,295 | Common/src/main/java/potionstudios/byg/mixin/common/world/surface/MixinSurfaceSystem.java | package potionstudios.byg.mixin.common.world.surface;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Holder;
import net.minecraft.core.Registry;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.LevelHeightAccessor;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.biome.BiomeManager;
import net.minecraft.world.level.chunk.BlockColumn;
import net.minecraft.world.level.chunk.ChunkAccess;
import net.minecraft.world.level.levelgen.*;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.LocalCapture;
import potionstudios.byg.common.world.biome.BYGBiomes;
import potionstudios.byg.util.SeedGetter;
@Mixin(SurfaceSystem.class)
public abstract class MixinSurfaceSystem implements SeedGetter {
@Shadow
protected abstract void erodedBadlandsExtension(BlockColumn blockColumn, int i, int j, int k, LevelHeightAccessor levelHeightAccessor);
@Shadow
@Final
private PositionalRandomFactory noiseRandom;
@Inject(method = "buildSurface", at = @At(value = "INVOKE", target = "Lnet/minecraft/core/Holder;is(Lnet/minecraft/resources/ResourceKey;)Z", shift = At.Shift.BEFORE, ordinal = 0), locals = LocalCapture.CAPTURE_FAILHARD)
private void addBYGErodedBadlandsExtension(RandomState $$0, BiomeManager $$1, Registry<Biome> $$2, boolean $$3, WorldGenerationContext $$4, ChunkAccess chunkAccess, NoiseChunk $$6, SurfaceRules.RuleSource $$7, CallbackInfo ci, BlockPos.MutableBlockPos $$8, ChunkPos $$9, int $$10, int $$11, BlockColumn blockColumn, SurfaceRules.Context $$13, SurfaceRules.SurfaceRule $$14, BlockPos.MutableBlockPos $$15, int $$16, int $$17, int $$18, int $$19, int $$20, Holder<Biome> biome) {
if (biome.is(BYGBiomes.SHATTERED_GLACIER) || biome.is(BYGBiomes.SIERRA_BADLANDS)) {
this.erodedBadlandsExtension(blockColumn, $$18, $$19, $$20, chunkAccess);
}
}
@Override
public PositionalRandomFactory getRandom() {
return this.noiseRandom;
}
}
| 412 | 0.794611 | 1 | 0.794611 | game-dev | MEDIA | 0.998299 | game-dev | 0.615842 | 1 | 0.615842 |
Team-Beef-Studios/Quake2Quest | 21,270 | Projects/Android/jni/quake2/src/game/monster/tank/tank.c | /*
* Copyright (C) 1997-2001 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.
*
* =======================================================================
*
* Tank and Tank Commander.
*
* =======================================================================
*/
#include "../../header/local.h"
#include "tank.h"
void tank_refire_rocket(edict_t *self);
void tank_doattack_rocket(edict_t *self);
void tank_reattack_blaster(edict_t *self);
static int sound_thud;
static int sound_pain;
static int sound_idle;
static int sound_die;
static int sound_step;
static int sound_sight;
static int sound_windup;
static int sound_strike;
void
tank_sight(edict_t *self, edict_t *other)
{
if (!self)
{
return;
}
gi.sound(self, CHAN_VOICE, sound_sight, 1, ATTN_NORM, 0);
}
void
tank_footstep(edict_t *self)
{
if (!self)
{
return;
}
gi.sound(self, CHAN_BODY, sound_step, 1, ATTN_NORM, 0);
}
void
tank_thud(edict_t *self)
{
if (!self)
{
return;
}
gi.sound(self, CHAN_BODY, sound_thud, 1, ATTN_NORM, 0);
}
void
tank_windup(edict_t *self)
{
if (!self)
{
return;
}
gi.sound(self, CHAN_WEAPON, sound_windup, 1, ATTN_NORM, 0);
}
void
tank_idle(edict_t *self)
{
if (!self)
{
return;
}
gi.sound(self, CHAN_VOICE, sound_idle, 1, ATTN_IDLE, 0);
}
mframe_t tank_frames_stand[] = {
{ai_stand, 0, NULL},
{ai_stand, 0, NULL},
{ai_stand, 0, NULL},
{ai_stand, 0, NULL},
{ai_stand, 0, NULL},
{ai_stand, 0, NULL},
{ai_stand, 0, NULL},
{ai_stand, 0, NULL},
{ai_stand, 0, NULL},
{ai_stand, 0, NULL},
{ai_stand, 0, NULL},
{ai_stand, 0, NULL},
{ai_stand, 0, NULL},
{ai_stand, 0, NULL},
{ai_stand, 0, NULL},
{ai_stand, 0, NULL},
{ai_stand, 0, NULL},
{ai_stand, 0, NULL},
{ai_stand, 0, NULL},
{ai_stand, 0, NULL},
{ai_stand, 0, NULL},
{ai_stand, 0, NULL},
{ai_stand, 0, NULL},
{ai_stand, 0, NULL},
{ai_stand, 0, NULL},
{ai_stand, 0, NULL},
{ai_stand, 0, NULL},
{ai_stand, 0, NULL},
{ai_stand, 0, NULL},
{ai_stand, 0, NULL}
};
mmove_t tank_move_stand =
{
FRAME_stand01,
FRAME_stand30,
tank_frames_stand,
NULL
};
void
tank_stand(edict_t *self)
{
if (!self)
{
return;
}
self->monsterinfo.currentmove = &tank_move_stand;
}
void tank_walk(edict_t *self);
mframe_t tank_frames_start_walk[] = {
{ai_walk, 0, NULL},
{ai_walk, 6, NULL},
{ai_walk, 6, NULL},
{ai_walk, 11, tank_footstep}
};
mmove_t tank_move_start_walk =
{
FRAME_walk01,
FRAME_walk04,
tank_frames_start_walk,
tank_walk
};
mframe_t tank_frames_walk[] = {
{ai_walk, 4, NULL},
{ai_walk, 5, NULL},
{ai_walk, 3, NULL},
{ai_walk, 2, NULL},
{ai_walk, 5, NULL},
{ai_walk, 5, NULL},
{ai_walk, 4, NULL},
{ai_walk, 4, tank_footstep},
{ai_walk, 3, NULL},
{ai_walk, 5, NULL},
{ai_walk, 4, NULL},
{ai_walk, 5, NULL},
{ai_walk, 7, NULL},
{ai_walk, 7, NULL},
{ai_walk, 6, NULL},
{ai_walk, 6, tank_footstep}
};
mmove_t tank_move_walk =
{
FRAME_walk05,
FRAME_walk20,
tank_frames_walk,
NULL
};
mframe_t tank_frames_stop_walk[] = {
{ai_walk, 3, NULL},
{ai_walk, 3, NULL},
{ai_walk, 2, NULL},
{ai_walk, 2, NULL},
{ai_walk, 4, tank_footstep}
};
mmove_t tank_move_stop_walk =
{
FRAME_walk21,
FRAME_walk25,
tank_frames_stop_walk,
tank_stand
};
void
tank_walk(edict_t *self)
{
if (!self)
{
return;
}
self->monsterinfo.currentmove = &tank_move_walk;
}
void tank_run(edict_t *self);
mframe_t tank_frames_start_run[] = {
{ai_run, 0, NULL},
{ai_run, 6, NULL},
{ai_run, 6, NULL},
{ai_run, 11, tank_footstep}
};
mmove_t tank_move_start_run =
{
FRAME_walk01,
FRAME_walk04,
tank_frames_start_run,
tank_run
};
mframe_t tank_frames_run[] = {
{ai_run, 4, NULL},
{ai_run, 5, NULL},
{ai_run, 3, NULL},
{ai_run, 2, NULL},
{ai_run, 5, NULL},
{ai_run, 5, NULL},
{ai_run, 4, NULL},
{ai_run, 4, tank_footstep},
{ai_run, 3, NULL},
{ai_run, 5, NULL},
{ai_run, 4, NULL},
{ai_run, 5, NULL},
{ai_run, 7, NULL},
{ai_run, 7, NULL},
{ai_run, 6, NULL},
{ai_run, 6, tank_footstep}
};
mmove_t tank_move_run =
{
FRAME_walk05,
FRAME_walk20,
tank_frames_run,
NULL
};
mframe_t tank_frames_stop_run[] = {
{ai_run, 3, NULL},
{ai_run, 3, NULL},
{ai_run, 2, NULL},
{ai_run, 2, NULL},
{ai_run, 4, tank_footstep}
};
mmove_t tank_move_stop_run =
{
FRAME_walk21,
FRAME_walk25,
tank_frames_stop_run,
tank_walk
};
void
tank_run(edict_t *self)
{
if (!self)
{
return;
}
if (self->enemy && self->enemy->client)
{
self->monsterinfo.aiflags |= AI_BRUTAL;
}
else
{
self->monsterinfo.aiflags &= ~AI_BRUTAL;
}
if (self->monsterinfo.aiflags & AI_STAND_GROUND)
{
self->monsterinfo.currentmove = &tank_move_stand;
return;
}
if ((self->monsterinfo.currentmove == &tank_move_walk) ||
(self->monsterinfo.currentmove == &tank_move_start_run))
{
self->monsterinfo.currentmove = &tank_move_run;
}
else
{
self->monsterinfo.currentmove = &tank_move_start_run;
}
}
mframe_t tank_frames_pain1[] = {
{ai_move, 0, NULL},
{ai_move, 0, NULL},
{ai_move, 0, NULL},
{ai_move, 0, NULL}
};
mmove_t tank_move_pain1 =
{
FRAME_pain101,
FRAME_pain104,
tank_frames_pain1,
tank_run
};
mframe_t tank_frames_pain2[] = {
{ai_move, 0, NULL},
{ai_move, 0, NULL},
{ai_move, 0, NULL},
{ai_move, 0, NULL},
{ai_move, 0, NULL}
};
mmove_t tank_move_pain2 =
{
FRAME_pain201,
FRAME_pain205,
tank_frames_pain2,
tank_run
};
mframe_t tank_frames_pain3[] = {
{ai_move, -7, NULL},
{ai_move, 0, NULL},
{ai_move, 0, NULL},
{ai_move, 0, NULL},
{ai_move, 2, NULL},
{ai_move, 0, NULL},
{ai_move, 0, NULL},
{ai_move, 3, NULL},
{ai_move, 0, NULL},
{ai_move, 2, NULL},
{ai_move, 0, NULL},
{ai_move, 0, NULL},
{ai_move, 0, NULL},
{ai_move, 0, NULL},
{ai_move, 0, NULL},
{ai_move, 0, tank_footstep}
};
mmove_t tank_move_pain3 =
{
FRAME_pain301,
FRAME_pain316,
tank_frames_pain3,
tank_run
};
void
tank_pain(edict_t *self, edict_t *other /* other */,
float kick /* other */, int damage)
{
if (!self)
{
return;
}
if (self->health < (self->max_health / 2))
{
self->s.skinnum |= 1;
}
if (damage <= 10)
{
return;
}
if (level.time < self->pain_debounce_time)
{
return;
}
if (damage <= 30)
{
if (random() > 0.2)
{
return;
}
}
/* If hard or nightmare, don't go into pain while attacking */
if (skill->value >= 2)
{
if ((self->s.frame >= FRAME_attak301) &&
(self->s.frame <= FRAME_attak330))
{
return;
}
if ((self->s.frame >= FRAME_attak101) &&
(self->s.frame <= FRAME_attak116))
{
return;
}
}
self->pain_debounce_time = level.time + 3;
gi.sound(self, CHAN_VOICE, sound_pain, 1, ATTN_NORM, 0);
if (skill->value == 3)
{
return; /* no pain anims in nightmare */
}
if (damage <= 30)
{
self->monsterinfo.currentmove = &tank_move_pain1;
}
else if (damage <= 60)
{
self->monsterinfo.currentmove = &tank_move_pain2;
}
else
{
self->monsterinfo.currentmove = &tank_move_pain3;
}
}
void
TankBlaster(edict_t *self)
{
vec3_t forward, right;
vec3_t start;
vec3_t end;
vec3_t dir;
int flash_number;
if (!self)
{
return;
}
if (self->s.frame == FRAME_attak110)
{
flash_number = MZ2_TANK_BLASTER_1;
}
else if (self->s.frame == FRAME_attak113)
{
flash_number = MZ2_TANK_BLASTER_2;
}
else
{
flash_number = MZ2_TANK_BLASTER_3;
}
AngleVectors(self->s.angles, forward, right, NULL);
G_ProjectSource(self->s.origin, monster_flash_offset[flash_number],
forward, right, start);
VectorCopy(self->enemy->s.origin, end);
end[2] += self->enemy->viewheight;
VectorSubtract(end, start, dir);
monster_fire_blaster(self, start, dir, 30, 800, flash_number, EF_BLASTER);
}
void
TankStrike(edict_t *self)
{
gi.sound(self, CHAN_WEAPON, sound_strike, 1, ATTN_NORM, 0);
}
void
TankRocket(edict_t *self)
{
vec3_t forward, right;
vec3_t start;
vec3_t dir;
vec3_t vec;
int flash_number;
if (!self)
{
return;
}
if (self->s.frame == FRAME_attak324)
{
flash_number = MZ2_TANK_ROCKET_1;
}
else if (self->s.frame == FRAME_attak327)
{
flash_number = MZ2_TANK_ROCKET_2;
}
else
{
flash_number = MZ2_TANK_ROCKET_3;
}
AngleVectors(self->s.angles, forward, right, NULL);
G_ProjectSource(self->s.origin, monster_flash_offset[flash_number],
forward, right, start);
VectorCopy(self->enemy->s.origin, vec);
vec[2] += self->enemy->viewheight;
VectorSubtract(vec, start, dir);
VectorNormalize(dir);
monster_fire_rocket(self, start, dir, 50, 550, flash_number);
}
void
TankMachineGun(edict_t *self)
{
vec3_t dir;
vec3_t vec;
vec3_t start;
vec3_t forward, right;
int flash_number;
if (!self)
{
return;
}
flash_number = MZ2_TANK_MACHINEGUN_1 + (self->s.frame - FRAME_attak406);
AngleVectors(self->s.angles, forward, right, NULL);
G_ProjectSource(self->s.origin, monster_flash_offset[flash_number],
forward, right, start);
if (self->enemy)
{
VectorCopy(self->enemy->s.origin, vec);
vec[2] += self->enemy->viewheight;
VectorSubtract(vec, start, vec);
vectoangles(vec, vec);
dir[0] = vec[0];
}
else
{
dir[0] = 0;
}
if (self->s.frame <= FRAME_attak415)
{
dir[1] = self->s.angles[1] - 8 * (self->s.frame - FRAME_attak411);
}
else
{
dir[1] = self->s.angles[1] + 8 * (self->s.frame - FRAME_attak419);
}
dir[2] = 0;
AngleVectors(dir, forward, NULL, NULL);
monster_fire_bullet(self, start, forward, 20, 4,
DEFAULT_BULLET_HSPREAD, DEFAULT_BULLET_VSPREAD,
flash_number);
}
mframe_t tank_frames_attack_blast[] = {
{ai_charge, 0, NULL},
{ai_charge, 0, NULL},
{ai_charge, 0, NULL},
{ai_charge, 0, NULL},
{ai_charge, -1, NULL},
{ai_charge, -2, NULL},
{ai_charge, -1, NULL},
{ai_charge, -1, NULL},
{ai_charge, 0, NULL},
{ai_charge, 0, TankBlaster}, /* 10 */
{ai_charge, 0, NULL},
{ai_charge, 0, NULL},
{ai_charge, 0, TankBlaster},
{ai_charge, 0, NULL},
{ai_charge, 0, NULL},
{ai_charge, 0, TankBlaster} /* 16 */
};
mmove_t tank_move_attack_blast =
{
FRAME_attak101,
FRAME_attak116,
tank_frames_attack_blast,
tank_reattack_blaster
};
mframe_t tank_frames_reattack_blast[] = {
{ai_charge, 0, NULL},
{ai_charge, 0, NULL},
{ai_charge, 0, TankBlaster},
{ai_charge, 0, NULL},
{ai_charge, 0, NULL},
{ai_charge, 0, TankBlaster} /* 16 */
};
mmove_t tank_move_reattack_blast =
{
FRAME_attak111,
FRAME_attak116,
tank_frames_reattack_blast,
tank_reattack_blaster
};
mframe_t tank_frames_attack_post_blast[] = {
{ai_move, 0, NULL}, /* 17 */
{ai_move, 0, NULL},
{ai_move, 2, NULL},
{ai_move, 3, NULL},
{ai_move, 2, NULL},
{ai_move, -2, tank_footstep} /* 22 */
};
mmove_t tank_move_attack_post_blast =
{
FRAME_attak117,
FRAME_attak122,
tank_frames_attack_post_blast,
tank_run
};
void
tank_reattack_blaster(edict_t *self)
{
if (!self)
{
return;
}
if (skill->value >= 2)
{
if (visible(self, self->enemy))
{
if (self->enemy->health > 0)
{
if (random() <= 0.6)
{
self->monsterinfo.currentmove = &tank_move_reattack_blast;
return;
}
}
}
}
self->monsterinfo.currentmove = &tank_move_attack_post_blast;
}
void
tank_poststrike(edict_t *self)
{
if (!self)
{
return;
}
self->enemy = NULL;
tank_run(self);
}
mframe_t tank_frames_attack_strike[] = {
{ai_move, 3, NULL},
{ai_move, 2, NULL},
{ai_move, 2, NULL},
{ai_move, 1, NULL},
{ai_move, 6, NULL},
{ai_move, 7, NULL},
{ai_move, 9, tank_footstep},
{ai_move, 2, NULL},
{ai_move, 1, NULL},
{ai_move, 2, NULL},
{ai_move, 2, tank_footstep},
{ai_move, 2, NULL},
{ai_move, 0, NULL},
{ai_move, 0, NULL},
{ai_move, 0, NULL},
{ai_move, 0, NULL},
{ai_move, -2, NULL},
{ai_move, -2, NULL},
{ai_move, 0, tank_windup},
{ai_move, 0, NULL},
{ai_move, 0, NULL},
{ai_move, 0, NULL},
{ai_move, 0, NULL},
{ai_move, 0, NULL},
{ai_move, 0, NULL},
{ai_move, 0, TankStrike},
{ai_move, 0, NULL},
{ai_move, -1, NULL},
{ai_move, -1, NULL},
{ai_move, -1, NULL},
{ai_move, -1, NULL},
{ai_move, -1, NULL},
{ai_move, -3, NULL},
{ai_move, -10, NULL},
{ai_move, -10, NULL},
{ai_move, -2, NULL},
{ai_move, -3, NULL},
{ai_move, -2, tank_footstep}
};
mmove_t tank_move_attack_strike =
{
FRAME_attak201,
FRAME_attak238,
tank_frames_attack_strike,
tank_poststrike
};
mframe_t tank_frames_attack_pre_rocket[] = {
{ai_charge, 0, NULL},
{ai_charge, 0, NULL},
{ai_charge, 0, NULL},
{ai_charge, 0, NULL},
{ai_charge, 0, NULL},
{ai_charge, 0, NULL},
{ai_charge, 0, NULL},
{ai_charge, 0, NULL},
{ai_charge, 0, NULL},
{ai_charge, 0, NULL}, /* 10 */
{ai_charge, 0, NULL},
{ai_charge, 1, NULL},
{ai_charge, 2, NULL},
{ai_charge, 7, NULL},
{ai_charge, 7, NULL},
{ai_charge, 7, tank_footstep},
{ai_charge, 0, NULL},
{ai_charge, 0, NULL},
{ai_charge, 0, NULL},
{ai_charge, 0, NULL}, /* 20 */
{ai_charge, -3, NULL}
};
mmove_t tank_move_attack_pre_rocket =
{
FRAME_attak301,
FRAME_attak321,
tank_frames_attack_pre_rocket,
tank_doattack_rocket
};
mframe_t tank_frames_attack_fire_rocket[] = {
{ai_charge, -3, NULL}, /* Loop Start 22 */
{ai_charge, 0, NULL},
{ai_charge, 0, TankRocket}, /* 24 */
{ai_charge, 0, NULL},
{ai_charge, 0, NULL},
{ai_charge, 0, TankRocket},
{ai_charge, 0, NULL},
{ai_charge, 0, NULL},
{ai_charge, -1, TankRocket} /* 30 Loop End */
};
mmove_t tank_move_attack_fire_rocket =
{
FRAME_attak322,
FRAME_attak330,
tank_frames_attack_fire_rocket,
tank_refire_rocket
};
mframe_t tank_frames_attack_post_rocket[] = {
{ai_charge, 0, NULL}, /* 31 */
{ai_charge, -1, NULL},
{ai_charge, -1, NULL},
{ai_charge, 0, NULL},
{ai_charge, 2, NULL},
{ai_charge, 3, NULL},
{ai_charge, 4, NULL},
{ai_charge, 2, NULL},
{ai_charge, 0, NULL},
{ai_charge, 0, NULL}, /* 40 */
{ai_charge, 0, NULL},
{ai_charge, -9, NULL},
{ai_charge, -8, NULL},
{ai_charge, -7, NULL},
{ai_charge, -1, NULL},
{ai_charge, -1, tank_footstep},
{ai_charge, 0, NULL},
{ai_charge, 0, NULL},
{ai_charge, 0, NULL},
{ai_charge, 0, NULL}, /* 50 */
{ai_charge, 0, NULL},
{ai_charge, 0, NULL},
{ai_charge, 0, NULL}
};
mmove_t tank_move_attack_post_rocket =
{
FRAME_attak331,
FRAME_attak353,
tank_frames_attack_post_rocket,
tank_run
};
mframe_t tank_frames_attack_chain[] = {
{ai_charge, 0, NULL},
{ai_charge, 0, NULL},
{ai_charge, 0, NULL},
{ai_charge, 0, NULL},
{ai_charge, 0, NULL},
{NULL, 0, TankMachineGun},
{NULL, 0, TankMachineGun},
{NULL, 0, TankMachineGun},
{NULL, 0, TankMachineGun},
{NULL, 0, TankMachineGun},
{NULL, 0, TankMachineGun},
{NULL, 0, TankMachineGun},
{NULL, 0, TankMachineGun},
{NULL, 0, TankMachineGun},
{NULL, 0, TankMachineGun},
{NULL, 0, TankMachineGun},
{NULL, 0, TankMachineGun},
{NULL, 0, TankMachineGun},
{NULL, 0, TankMachineGun},
{NULL, 0, TankMachineGun},
{NULL, 0, TankMachineGun},
{NULL, 0, TankMachineGun},
{NULL, 0, TankMachineGun},
{NULL, 0, TankMachineGun},
{ai_charge, 0, NULL},
{ai_charge, 0, NULL},
{ai_charge, 0, NULL},
{ai_charge, 0, NULL},
{ai_charge, 0, NULL}
};
mmove_t tank_move_attack_chain =
{
FRAME_attak401,
FRAME_attak429,
tank_frames_attack_chain,
tank_run
};
void
tank_refire_rocket(edict_t *self)
{
if (!self)
{
return;
}
/* Only on hard or nightmare */
if (skill->value >= 2)
{
if (self->enemy->health > 0)
{
if (visible(self, self->enemy))
{
if (random() <= 0.4)
{
self->monsterinfo.currentmove =
&tank_move_attack_fire_rocket;
return;
}
}
}
}
self->monsterinfo.currentmove = &tank_move_attack_post_rocket;
}
void
tank_doattack_rocket(edict_t *self)
{
if (!self)
{
return;
}
self->monsterinfo.currentmove = &tank_move_attack_fire_rocket;
}
void
tank_attack(edict_t *self)
{
vec3_t vec;
float range;
float r;
if (!self)
{
return;
}
if (self->enemy->health < 0)
{
self->monsterinfo.currentmove = &tank_move_attack_strike;
self->monsterinfo.aiflags &= ~AI_BRUTAL;
return;
}
VectorSubtract(self->enemy->s.origin, self->s.origin, vec);
range = VectorLength(vec);
r = random();
if (range <= 125)
{
if (r < 0.4)
{
self->monsterinfo.currentmove = &tank_move_attack_chain;
}
else
{
self->monsterinfo.currentmove = &tank_move_attack_blast;
}
}
else if (range <= 250)
{
if (r < 0.5)
{
self->monsterinfo.currentmove = &tank_move_attack_chain;
}
else
{
self->monsterinfo.currentmove = &tank_move_attack_blast;
}
}
else
{
if (r < 0.33)
{
self->monsterinfo.currentmove = &tank_move_attack_chain;
}
else if (r < 0.66)
{
self->monsterinfo.currentmove = &tank_move_attack_pre_rocket;
self->pain_debounce_time = level.time + 5.0; /* no pain for a while */
}
else
{
self->monsterinfo.currentmove = &tank_move_attack_blast;
}
}
}
void
tank_dead(edict_t *self)
{
if (!self)
{
return;
}
VectorSet(self->mins, -16, -16, -16);
VectorSet(self->maxs, 16, 16, -0);
self->movetype = MOVETYPE_TOSS;
self->svflags |= SVF_DEADMONSTER;
self->nextthink = 0;
gi.linkentity(self);
}
mframe_t tank_frames_death1[] = {
{ai_move, -7, NULL},
{ai_move, -2, NULL},
{ai_move, -2, NULL},
{ai_move, 1, NULL},
{ai_move, 3, NULL},
{ai_move, 6, NULL},
{ai_move, 1, NULL},
{ai_move, 1, NULL},
{ai_move, 2, NULL},
{ai_move, 0, NULL},
{ai_move, 0, NULL},
{ai_move, 0, NULL},
{ai_move, -2, NULL},
{ai_move, 0, NULL},
{ai_move, 0, NULL},
{ai_move, -3, NULL},
{ai_move, 0, NULL},
{ai_move, 0, NULL},
{ai_move, 0, NULL},
{ai_move, 0, NULL},
{ai_move, 0, NULL},
{ai_move, 0, NULL},
{ai_move, -4, NULL},
{ai_move, -6, NULL},
{ai_move, -4, NULL},
{ai_move, -5, NULL},
{ai_move, -7, NULL},
{ai_move, -15, tank_thud},
{ai_move, -5, NULL},
{ai_move, 0, NULL},
{ai_move, 0, NULL},
{ai_move, 0, NULL}
};
mmove_t tank_move_death =
{
FRAME_death101,
FRAME_death132,
tank_frames_death1,
tank_dead
};
void
tank_die(edict_t *self, edict_t *inflictor /* unused */,
edict_t *attacker /* unused */, int damage,
vec3_t point /* unused */)
{
int n;
if (!self)
{
return;
}
/* check for gib */
if (self->health <= self->gib_health)
{
gi.sound(self, CHAN_VOICE, gi.soundindex("misc/udeath.wav"), 1, ATTN_NORM, 0);
for (n = 0; n < 1; n++)
{
ThrowGib(self, "models/objects/gibs/sm_meat/tris.md2",
damage, GIB_ORGANIC);
}
for (n = 0; n < 4; n++)
{
ThrowGib(self, "models/objects/gibs/sm_metal/tris.md2",
damage, GIB_METALLIC);
}
ThrowGib(self, "models/objects/gibs/chest/tris.md2",
damage, GIB_ORGANIC);
ThrowHead(self, "models/objects/gibs/gear/tris.md2",
damage, GIB_METALLIC);
self->deadflag = DEAD_DEAD;
return;
}
if (self->deadflag == DEAD_DEAD)
{
return;
}
/* regular death */
gi.sound(self, CHAN_VOICE, sound_die, 1, ATTN_NORM, 0);
self->deadflag = DEAD_DEAD;
self->takedamage = DAMAGE_YES;
self->monsterinfo.currentmove = &tank_move_death;
}
/*
* QUAKED monster_tank (1 .5 0) (-32 -32 -16) (32 32 72) Ambush Trigger_Spawn Sight
* QUAKED monster_tank_commander (1 .5 0) (-32 -32 -16) (32 32 72) Ambush Trigger_Spawn Sight
*/
void
SP_monster_tank(edict_t *self)
{
if (!self)
{
return;
}
if (deathmatch->value)
{
G_FreeEdict(self);
return;
}
self->s.modelindex = gi.modelindex("models/monsters/tank/tris.md2");
VectorSet(self->mins, -32, -32, -16);
VectorSet(self->maxs, 32, 32, 72);
self->movetype = MOVETYPE_STEP;
self->solid = SOLID_BBOX;
sound_pain = gi.soundindex("tank/tnkpain2.wav");
sound_thud = gi.soundindex("tank/tnkdeth2.wav");
sound_idle = gi.soundindex("tank/tnkidle1.wav");
sound_die = gi.soundindex("tank/death.wav");
sound_step = gi.soundindex("tank/step.wav");
sound_windup = gi.soundindex("tank/tnkatck4.wav");
sound_strike = gi.soundindex("tank/tnkatck5.wav");
sound_sight = gi.soundindex("tank/sight1.wav");
gi.soundindex("tank/tnkatck1.wav");
gi.soundindex("tank/tnkatk2a.wav");
gi.soundindex("tank/tnkatk2b.wav");
gi.soundindex("tank/tnkatk2c.wav");
gi.soundindex("tank/tnkatk2d.wav");
gi.soundindex("tank/tnkatk2e.wav");
gi.soundindex("tank/tnkatck3.wav");
if (strcmp(self->classname, "monster_tank_commander") == 0)
{
self->health = 1000;
self->gib_health = -225;
}
else
{
self->health = 750;
self->gib_health = -200;
}
self->mass = 500;
self->pain = tank_pain;
self->die = tank_die;
self->monsterinfo.stand = tank_stand;
self->monsterinfo.walk = tank_walk;
self->monsterinfo.run = tank_run;
self->monsterinfo.dodge = NULL;
self->monsterinfo.attack = tank_attack;
self->monsterinfo.melee = NULL;
self->monsterinfo.sight = tank_sight;
self->monsterinfo.idle = tank_idle;
gi.linkentity(self);
self->monsterinfo.currentmove = &tank_move_stand;
self->monsterinfo.scale = MODEL_SCALE;
walkmonster_start(self);
if (strcmp(self->classname, "monster_tank_commander") == 0)
{
self->s.skinnum = 2;
}
}
| 412 | 0.786303 | 1 | 0.786303 | game-dev | MEDIA | 0.946757 | game-dev | 0.919575 | 1 | 0.919575 |
dwilliamson/GDMagArchive | 6,957 | feb04blow/lerp/pool/world.lerp | struct Entity {
Vector3 position;
Vector3 velocity;
Float radius;
Float mass;
Float r, g, b;
}
struct Database {
Float timestep;
Entity cue_ball; // @The_Point @Refactor: Should be able to search this guy!
}
proc make_entity(Float x, Float y, Float radius, Float r, Float g, Float b) {
Entity e;
e.position = make_vector3(x, y, 0.0);
e.velocity = make_vector3(0.0, 0.0, 0.0);
e.radius = radius;
e.r = r * 1.0;
e.g = g * 1.0;
e.b = b * 1.0;
e.mass = 1.0;
the_world .+ ['Entity e];
return e;
}
proc init_world_base {
Database world;
the_world = world;
the_world.timestep = 0.0;
play_field_width = 3.0; // meters
play_field_height = 3.5; // meters
ball_radius = 1.5 / 20.0;
aim_theta = PI * 0.5;
shot_power = 0.5;
balls_in_motion = 0;
}
proc position_ball1(Entity top, Entity b) {
Float r = top.radius;
Float s = r * 1.01;
Float t = s * 1.727;
Float x = (top.position)[1];
Float y = (top.position)[2];
b.position = make_vector3(x + s, y + t, 0);
}
proc position_ball2(Entity top, Entity a, Entity b) {
Float r = top.radius;
Float s = r * 1.01;
Float t = s * 1.727;
Float x = (top.position)[1];
Float y = (top.position)[2];
a.position = make_vector3(x - s, y + t, 0);
b.position = make_vector3(x + s, y + t, 0);
}
proc init_world {
init_world_base();
Float r = ball_radius;
Float x0 = play_field_width * 0.5;
Float y0 = play_field_height * 0.5;
Entity r1 = make_entity(0, 0, r, 1, 0, 0);
Entity r2 = make_entity(0, 0, r, 1, 0, 0);
Entity r3 = make_entity(0, 0, r, 1, 0, 0);
Entity r4 = make_entity(0, 0, r, 1, 0, 0);
Entity r5 = make_entity(0, 0, r, 1, 0, 0);
Entity r6 = make_entity(0, 0, r, 1, 0, 0);
Entity r7 = make_entity(0, 0, r, 1, 0, 0);
Entity b1 = make_entity(0, 0, r, 0, 0, 1);
Entity b2 = make_entity(0, 0, r, 0, 0, 1);
Entity b3 = make_entity(0, 0, r, 0, 0, 1);
Entity b4 = make_entity(0, 0, r, 0, 0, 1);
Entity b5 = make_entity(0, 0, r, 0, 0, 1);
Entity b6 = make_entity(0, 0, r, 0, 0, 1);
Entity b7 = make_entity(0, 0, r, 0, 0, 1);
Entity eightball = make_entity(0, 0, r, 0, 0, 0);
the_world.cue_ball = make_entity(x0, r * 6, r, 1, 1, 1);
(the_world.cue_ball).mass = 1.2;
r1.position = make_vector3(x0, y0, 0);
position_ball2(r1, b1, r2);
position_ball2(b1, r3, eightball);
position_ball1(r2, b2);
position_ball2(r3, r4, b3);
position_ball2(b2, r5, b4);
position_ball2(r4, r6, b5);
position_ball2(r5, b6, b7);
position_ball1(b4, r7);
}
proc init_world_3 {
init_world_base();
Float r = ball_radius;
Float x0 = play_field_width * 0.5;
Float y0 = play_field_height * 0.5;
Entity r1 = make_entity(0, 0, r, 1, 0, 0);
Entity r2 = make_entity(0, 0, r, 1, 0, 0);
Entity r3 = make_entity(0, 0, r, 1, 0, 0);
Entity r4 = make_entity(0, 0, r, 1, 0, 0);
Entity r5 = make_entity(0, 0, r, 1, 0, 0);
Entity b1 = make_entity(0, 0, r, 0, 0, 1);
Entity b2 = make_entity(0, 0, r, 0, 0, 1);
Entity b3 = make_entity(0, 0, r, 0, 0, 1);
Entity b4 = make_entity(0, 0, r, 0, 0, 1);
Entity b5 = make_entity(0, 0, r, 0, 0, 1);
Entity eightball = make_entity(0, 0, r, 0, 0, 0);
the_world.cue_ball = make_entity(x0, r * 6, r, 1, 1, 1);
(the_world.cue_ball).mass = 1.2;
r1.position = make_vector3(x0, y0, 0);
position_ball2(r1, b1, r2);
position_ball2(b1, r3, eightball);
position_ball1(r2, b2);
position_ball2(r3, r4, b3);
position_ball2(b2, r5, b4);
position_ball1(b3, b5);
}
proc init_world_2 {
init_world_base();
Float r = ball_radius;
Float x0 = play_field_width * 0.5;
Float y0 = play_field_height * 0.5;
Float s = r * 1.01;
Float t = s * 1.727;
make_entity(x0, y0, r, 1, 0, 0);
make_entity(x0 - s, y0 + t, r, 0, 1, 0);
make_entity(x0 + s, y0 + t, r, 0, 0, 1);
the_world.cue_ball = make_entity(x0, r * 6, r, 1, 1, 1);
(the_world.cue_ball).mass = 1.2;
}
proc get_shot_vector() {
Float ct = cos(PI - aim_theta);
Float st = sin(PI - aim_theta);
Float speed = 40 * (the_world.cue_ball).radius * shot_power;
return make_vector3(ct * speed, st * speed, 0.0);
}
proc handle_input {
Float time = seconds_since_startup();
Float dt = time - last_frame_time;
last_frame_time = time;
current_dt = dt;
if (dt == 0.0) dt = 0.05;
Windows.do_window_events();
handle_mouse(dt);
if Keyboard.['key_pressed " "] then {
Vector3 speed = get_shot_vector();
((the_world.cue_ball).velocity) = speed;
}
if Keyboard.['key_pressed '1] then {
init_world();
return;
}
if Keyboard.['key_pressed '2] then {
init_world_2();
return;
}
if Keyboard.['key_pressed '3] then {
init_world_3();
return;
}
Float THETA_RATE = 1.0;
Float INTENSITY_RATE = 0.7;
if Keyboard.['key_held_down 'W] then shot_power += INTENSITY_RATE * dt;
if Keyboard.['key_held_down 'S] then shot_power -= INTENSITY_RATE * dt;
if shot_power < 0 then shot_power = 0.0;
if shot_power > 1 then shot_power = 1.0;
if Keyboard.['key_held_down 'A] then aim_theta += THETA_RATE * dt;
if Keyboard.['key_held_down 'D] then aim_theta -= THETA_RATE * dt;
Float fine_rate = (1.0 - shot_power * 0.9); // XXX
fine_rate *= 0.01;
if Keyboard.['key_held_down 'Z] then aim_theta += THETA_RATE * dt * fine_rate;
if Keyboard.['key_held_down 'C] then aim_theta -= THETA_RATE * dt * fine_rate;
the_world.timestep = dt;
had_focus_last_frame = has_focus_this_frame;
}
proc simulate {
// Database result = pool_simulate(the_world, current_dt);
Database result = Billiards_Sim.simulate(the_world, 0.03);
the_world = result;
Integer old_balls_in_motion = balls_in_motion;
balls_in_motion = 0;
Float SPEED_LIMIT = 0.005;
each the_world.['Entity ?x] if length(x.velocity) > SPEED_LIMIT then balls_in_motion = 1;
if old_balls_in_motion then { // XXXXX Need logical AND?
if !balls_in_motion then each the_world.['Entity ?x] x.velocity = make_vector3(0.0, 0.0, 0.0);
// Or with implicit each, it could be: if !balls_in_motion then the_world.['Entity ??].velocity = make_vector3(0.0, 0.0, 0.0); ... but do we evaluate RHS once or many? And copy-on-write?
}
}
proc draw_predictions {
Entity e = the_world.cue_ball;
// Temporary hack to modify e's velocity if we are setting up a shot...
// we change it back later.
Vector3 velocity_tmp = e.velocity;
if !balls_in_motion then e.velocity = get_shot_vector();
Database predict = Billiards_Sim.simulate_until_everything_is_at_rest(the_world, 0.03);
draw_entities(predict, 0.15);
if !balls_in_motion then e.velocity = velocity_tmp;
}
| 412 | 0.675742 | 1 | 0.675742 | game-dev | MEDIA | 0.850419 | game-dev,graphics-rendering | 0.736814 | 1 | 0.736814 |
kamyu104/LeetCode-Solutions | 1,104 | C++/count-unguarded-cells-in-the-grid.cpp | // Time: O(m * n)
// Space: O(m * n)
// array, simulation
class Solution {
public:
int countUnguarded(int m, int n, vector<vector<int>>& guards, vector<vector<int>>& walls) {
static const vector<pair<int, int>> directions{{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
enum State {GREEN, RED, BLOCK};
vector<vector<int>> grid(m, vector<int>(n, GREEN));
for (const auto& x : guards) {
grid[x[0]][x[1]] = BLOCK;
}
for (const auto& x : walls) {
grid[x[0]][x[1]] = BLOCK;
}
for (const auto& x : guards) {
for (const auto& [dr, dc] : directions) {
for (int nr = x[0] + dr, nc = x[1] + dc;
0 <= nr && nr < m && 0 <= nc && nc < n && grid[nr][nc] != BLOCK;
nr += dr, nc += dc) {
grid[nr][nc] = RED;
}
}
}
int result = 0;
for (const auto& row : grid) {
for (const auto& x : row) {
result += (x == GREEN);
}
}
return result;
}
};
| 412 | 0.979592 | 1 | 0.979592 | game-dev | MEDIA | 0.569267 | game-dev | 0.88678 | 1 | 0.88678 |
rbdl/rbdl | 19,885 | src/Model.cc | /*
* RBDL - Rigid Body Dynamics Library
* Copyright (c) 2011-2018 Martin Felis <martin@fysx.org>
*
* Licensed under the zlib license. See LICENSE for more details.
*/
#include <iostream>
#include <limits>
#include <assert.h>
#include "rbdl/rbdl_mathutils.h"
#include "rbdl/Logging.h"
#include "rbdl/Model.h"
#include "rbdl/Body.h"
#include "rbdl/Joint.h"
using namespace RigidBodyDynamics;
using namespace RigidBodyDynamics::Math;
Model::Model()
{
Body root_body;
Joint root_joint;
Vector3d zero_position (0., 0., 0.);
SpatialVector zero_spatial (0., 0., 0., 0., 0., 0.);
// structural information
lambda.push_back(0);
lambda_q.push_back(0);
mu.push_back(std::vector<unsigned int>());
dof_count = 0;
q_size = 0;
qdot_size = 0;
previously_added_body_id = 0;
gravity = Vector3d (0., -9.81, 0.);
// state information
v.push_back(zero_spatial);
a.push_back(zero_spatial);
// Joints
mJoints.push_back(root_joint);
S.push_back (zero_spatial);
X_T.push_back(SpatialTransform());
v_J.push_back (zero_spatial);
c_J.push_back (zero_spatial);
// Spherical joints
multdof3_S.push_back (Matrix63::Zero());
multdof3_U.push_back (Matrix63::Zero());
multdof3_Dinv.push_back (Matrix3d::Zero());
multdof3_u.push_back (Vector3d::Zero());
multdof3_w_index.push_back (0);
// Dynamic variables
c.push_back(zero_spatial);
IA.push_back(SpatialMatrix::Identity());
pA.push_back(zero_spatial);
U.push_back(zero_spatial);
u = VectorNd::Zero(1);
d = VectorNd::Zero(1);
f.push_back (zero_spatial);
SpatialRigidBodyInertia rbi(0.,
Vector3d (0., 0., 0.),
Matrix3d::Zero());
Ic.push_back (rbi);
I.push_back(rbi);
hc.push_back (zero_spatial);
hdotc.push_back (zero_spatial);
// Bodies
X_lambda.push_back(SpatialTransform());
X_base.push_back(SpatialTransform());
mBodies.push_back(root_body);
mBodyNameMap["ROOT"] = 0;
fixed_body_discriminator = std::numeric_limits<unsigned int>::max() / 2;
}
unsigned int AddBodyFixedJoint (
Model &model,
const unsigned int parent_id,
const SpatialTransform &joint_frame,
const Joint &joint,
const Body &body,
std::string body_name)
{
FixedBody fbody = FixedBody::CreateFromBody (body);
fbody.mMovableParent = parent_id;
fbody.mParentTransform = joint_frame;
if (model.IsFixedBodyId(parent_id)) {
FixedBody fixed_parent =
model.mFixedBodies[parent_id - model.fixed_body_discriminator];
fbody.mMovableParent = fixed_parent.mMovableParent;
fbody.mParentTransform = joint_frame * fixed_parent.mParentTransform;
}
// merge the two bodies
Body parent_body = model.mBodies[fbody.mMovableParent];
parent_body.Join (fbody.mParentTransform, body);
model.mBodies[fbody.mMovableParent] = parent_body;
model.I[fbody.mMovableParent] =
SpatialRigidBodyInertia::createFromMassComInertiaC (
parent_body.mMass,
parent_body.mCenterOfMass,
parent_body.mInertia);
model.mFixedBodies.push_back (fbody);
if (model.mFixedBodies.size() > std::numeric_limits<unsigned int>::max() -
model.fixed_body_discriminator) {
std::ostringstream errormsg;
errormsg << "Error: cannot add more than "
<< std::numeric_limits<unsigned int>::max() - model.mFixedBodies.size()
<< " fixed bodies. You need to modify "
<< "Model::fixed_body_discriminator for this."
<< std::endl;
throw Errors::RBDLError(errormsg.str());
}
if (body_name.size() != 0) {
if (model.mBodyNameMap.find(body_name) != model.mBodyNameMap.end()) {
std::ostringstream errormsg;
errormsg << "Error: Body with name '"
<< body_name
<< "' already exists!"
<< std::endl;
throw Errors::RBDLError(errormsg.str());
}
model.mBodyNameMap[body_name] = model.mFixedBodies.size()
+ model.fixed_body_discriminator - 1;
}
return model.mFixedBodies.size() + model.fixed_body_discriminator - 1;
}
unsigned int AddBodyMultiDofJoint (
Model &model,
const unsigned int parent_id,
const SpatialTransform &joint_frame,
const Joint &joint,
const Body &body,
std::string body_name)
{
// Here we emulate multi DoF joints by simply adding nullbodies. This
// allows us to use fixed size elements for S,v,a, etc. which is very
// fast in Eigen.
unsigned int joint_count = 0;
if (joint.mJointType == JointType1DoF) {
joint_count = 1;
} else if (joint.mJointType == JointType2DoF) {
joint_count = 2;
} else if (joint.mJointType == JointType3DoF) {
joint_count = 3;
} else if (joint.mJointType == JointType4DoF) {
joint_count = 4;
} else if (joint.mJointType == JointType5DoF) {
joint_count = 5;
} else if (joint.mJointType == JointType6DoF) {
joint_count = 6;
} else if (joint.mJointType == JointTypeFloatingBase)
// no action required
{}
else {
std::ostringstream errormsg;
errormsg << "Error: Invalid joint type: "
<< joint.mJointType
<< std::endl;
throw Errors::RBDLError(errormsg.str());
}
Body null_body (0., Vector3d (0., 0., 0.), Vector3d (0., 0., 0.));
null_body.mIsVirtual = true;
unsigned int null_parent = parent_id;
SpatialTransform joint_frame_transform;
if (joint.mJointType == JointTypeFloatingBase) {
null_parent = model.AddBody (parent_id,
joint_frame,
JointTypeTranslationXYZ,
null_body);
return model.AddBody (null_parent,
SpatialTransform(),
JointTypeSpherical,
body,
body_name);
}
Joint single_dof_joint;
unsigned int j;
// Here we add multiple virtual bodies that have no mass or inertia for
// which each is attached to the model with a single degree of freedom
// joint.
for (j = 0; j < joint_count; j++) {
single_dof_joint = Joint (joint.mJointAxes[j]);
if (single_dof_joint.mJointType == JointType1DoF) {
Vector3d rotation (
joint.mJointAxes[j][0],
joint.mJointAxes[j][1],
joint.mJointAxes[j][2]);
Vector3d translation (
joint.mJointAxes[j][3],
joint.mJointAxes[j][4],
joint.mJointAxes[j][5]);
#ifdef RBDL_USE_CASADI_MATH
if (rotation.is_zero()) {
#else
if (rotation == Vector3d (0., 0., 0.)) {
#endif
single_dof_joint = Joint (JointTypePrismatic, translation);
}
#ifdef RBDL_USE_CASADI_MATH
if (translation.is_zero()) {
#else
else if (translation == Vector3d (0., 0., 0.)) {
#endif
single_dof_joint = Joint (JointTypeRevolute, rotation);
}
}
// the first joint has to be transformed by joint_frame, all the
// others must have a null transformation
if (j == 0) {
joint_frame_transform = joint_frame;
} else {
joint_frame_transform = SpatialTransform();
}
if (j == joint_count - 1)
// if we are at the last we must add the real body
{
break;
} else {
// otherwise we just add an intermediate body
null_parent = model.AddBody (null_parent,
joint_frame_transform,
single_dof_joint,
null_body);
}
}
return model.AddBody (null_parent,
joint_frame_transform,
single_dof_joint,
body,
body_name);
}
unsigned int Model::AddBody(
const unsigned int parent_id,
const SpatialTransform &joint_frame,
const Joint &joint,
const Body &body,
std::string body_name)
{
assert (lambda.size() > 0);
assert (joint.mJointType != JointTypeUndefined);
if (joint.mJointType == JointTypeFixed) {
previously_added_body_id = AddBodyFixedJoint (*this,
parent_id,
joint_frame,
joint,
body,
body_name);
return previously_added_body_id;
} else if ( (joint.mJointType == JointTypeSpherical)
|| (joint.mJointType == JointTypeEulerZYX)
|| (joint.mJointType == JointTypeEulerXYZ)
|| (joint.mJointType == JointTypeEulerYXZ)
|| (joint.mJointType == JointTypeEulerZXY)
|| (joint.mJointType == JointTypeTranslationXYZ)
|| (joint.mJointType == JointTypeCustom)
) {
// no action required
} else if (joint.mJointType != JointTypePrismatic
&& joint.mJointType != JointTypeRevolute
&& joint.mJointType != JointTypeRevoluteX
&& joint.mJointType != JointTypeRevoluteY
&& joint.mJointType != JointTypeRevoluteZ
&& joint.mJointType != JointTypeHelical
) {
previously_added_body_id = AddBodyMultiDofJoint (*this,
parent_id,
joint_frame,
joint,
body,
body_name);
return previously_added_body_id;
}
// If we add the body to a fixed body we have to make sure that we
// actually add it to its movable parent.
unsigned int movable_parent_id = parent_id;
SpatialTransform movable_parent_transform;
if (IsFixedBodyId(parent_id)) {
unsigned int fbody_id = parent_id - fixed_body_discriminator;
movable_parent_id = mFixedBodies[fbody_id].mMovableParent;
movable_parent_transform = mFixedBodies[fbody_id].mParentTransform;
}
// structural information
lambda.push_back(movable_parent_id);
unsigned int lambda_q_last = mJoints[mJoints.size() - 1].q_index;
if (mJoints[mJoints.size() - 1].mDoFCount > 0
&& mJoints[mJoints.size() - 1].mJointType != JointTypeCustom) {
lambda_q_last = lambda_q_last + mJoints[mJoints.size() - 1].mDoFCount;
} else if (mJoints[mJoints.size() - 1].mJointType == JointTypeCustom) {
unsigned int custom_index = mJoints[mJoints.size() - 1].custom_joint_index;
lambda_q_last = lambda_q_last
+ mCustomJoints[mCustomJoints.size() - 1]->mDoFCount;
}
for (unsigned int i = 0; i < joint.mDoFCount; i++) {
lambda_q.push_back(lambda_q_last + i);
}
mu.push_back(std::vector<unsigned int>());
mu.at(movable_parent_id).push_back(mBodies.size());
// Bodies
X_lambda.push_back(SpatialTransform());
X_base.push_back(SpatialTransform());
mBodies.push_back(body);
if (body_name.size() != 0) {
if (mBodyNameMap.find(body_name) != mBodyNameMap.end()) {
std::ostringstream errormsg;
errormsg << "Error: Body with name '"
<< body_name
<< "' already exists!"
<< std::endl;
throw Errors::RBDLError(errormsg.str());
}
mBodyNameMap[body_name] = mBodies.size() - 1;
}
// state information
v.push_back(SpatialVector(0., 0., 0., 0., 0., 0.));
a.push_back(SpatialVector(0., 0., 0., 0., 0., 0.));
// Joints
unsigned int prev_joint_index = mJoints.size() - 1;
mJoints.push_back(joint);
if (mJoints[prev_joint_index].mJointType != JointTypeCustom) {
mJoints[mJoints.size() - 1].q_index =
mJoints[prev_joint_index].q_index + mJoints[prev_joint_index].mDoFCount;
} else {
mJoints[mJoints.size() - 1].q_index =
mJoints[prev_joint_index].q_index + mJoints[prev_joint_index].mDoFCount;
}
S.push_back (joint.mJointAxes[0]);
// Joint state variables
v_J.push_back (joint.mJointAxes[0]);
c_J.push_back (SpatialVector(0., 0., 0., 0., 0., 0.));
// workspace for joints with 3 dof
multdof3_S.push_back (Matrix63::Zero());
multdof3_U.push_back (Matrix63::Zero());
multdof3_Dinv.push_back (Matrix3d::Zero());
multdof3_u.push_back (Vector3d::Zero());
multdof3_w_index.push_back (0);
dof_count = dof_count + joint.mDoFCount;
// update the w components of the Quaternions. They are stored at the end
// of the q vector
int multdof3_joint_counter = 0;
int mCustomJoint_joint_counter = 0;
for (unsigned int i = 1; i < mJoints.size(); i++) {
if (mJoints[i].mJointType == JointTypeSpherical) {
multdof3_w_index[i] = dof_count + multdof3_joint_counter;
multdof3_joint_counter++;
}
}
q_size = dof_count
+ multdof3_joint_counter;
qdot_size = qdot_size + joint.mDoFCount;
// we have to invert the transformation as it is later always used from the
// child bodies perspective.
X_T.push_back(joint_frame * movable_parent_transform);
// Dynamic variables
c.push_back(SpatialVector(0., 0., 0., 0., 0., 0.));
IA.push_back(SpatialMatrix::Zero());
pA.push_back(SpatialVector(0., 0., 0., 0., 0., 0.));
U.push_back(SpatialVector(0., 0., 0., 0., 0., 0.));
d = VectorNd::Zero (mBodies.size());
u = VectorNd::Zero (mBodies.size());
f.push_back (SpatialVector (0., 0., 0., 0., 0., 0.));
SpatialRigidBodyInertia rbi =
SpatialRigidBodyInertia::createFromMassComInertiaC (body.mMass,
body.mCenterOfMass,
body.mInertia);
Ic.push_back (rbi);
I.push_back (rbi);
hc.push_back (SpatialVector(0., 0., 0., 0., 0., 0.));
hdotc.push_back (SpatialVector(0., 0., 0., 0., 0., 0.));
if (mBodies.size() == fixed_body_discriminator) {
std::ostringstream errormsg;
errormsg << "Error: cannot add more than "
<< fixed_body_discriminator
<< " movable bodies. You need to modify Model::fixed_body_discriminator for this."
<< std::endl;
throw Errors::RBDLError(errormsg.str());
}
previously_added_body_id = mBodies.size() - 1;
mJointUpdateOrder.clear();
// update the joint order computation
std::vector<std::pair<JointType, unsigned int> > joint_types;
for (unsigned int i = 0; i < mJoints.size(); i++) {
joint_types.push_back(
std::pair<JointType, unsigned int> (mJoints[i].mJointType,i));
mJointUpdateOrder.push_back (mJoints[i].mJointType);
}
mJointUpdateOrder.clear();
JointType current_joint_type = JointTypeUndefined;
while (joint_types.size() != 0) {
current_joint_type = joint_types[0].first;
std::vector<std::pair<JointType, unsigned int> >::iterator type_iter =
joint_types.begin();
while (type_iter != joint_types.end()) {
if (type_iter->first == current_joint_type) {
mJointUpdateOrder.push_back (type_iter->second);
type_iter = joint_types.erase (type_iter);
} else {
++type_iter;
}
}
}
// for (unsigned int i = 0; i < mJointUpdateOrder.size(); i++) {
// std::cout << "i = " << i << ": joint_id = " << mJointUpdateOrder[i]
// << " joint_type = " << mJoints[mJointUpdateOrder[i]].mJointType << std::endl;
// }
return previously_added_body_id;
}
unsigned int Model::AppendBody (
const Math::SpatialTransform &joint_frame,
const Joint &joint,
const Body &body,
std::string body_name)
{
return Model::AddBody (previously_added_body_id,
joint_frame,
joint,
body,
body_name);
}
unsigned int Model::AddBodyCustomJoint (
const unsigned int parent_id,
const Math::SpatialTransform &joint_frame,
CustomJoint *custom_joint,
const Body &body,
std::string body_name)
{
Joint proxy_joint (JointTypeCustom, custom_joint->mDoFCount);
proxy_joint.custom_joint_index = mCustomJoints.size();
//proxy_joint.mDoFCount = custom_joint->mDoFCount; //MM added. Otherwise
//model.q_size = 0, which is not good.
mCustomJoints.push_back (custom_joint);
unsigned int body_id = AddBody (parent_id,
joint_frame,
proxy_joint,
body,
body_name);
return body_id;
}
void Model::UpdateInertiaMatrixForBody(const unsigned int id)
{
unsigned int body_id(id);
if(IsFixedBodyId(id))
{
body_id = mFixedBodies[id - fixed_body_discriminator].mMovableParent;
}
const Body &body(mBodies[body_id]);
Math::SpatialRigidBodyInertia rbi =
Math::SpatialRigidBodyInertia::createFromMassComInertiaC(
body.mMass, body.mCenterOfMass, body.mInertia);
Ic[body_id] = rbi;
I[body_id] = rbi;
}
void Model::SetBodyMass(const unsigned int id, const double mass)
{
if(IsFixedBodyId(id))
{
// The inertial parameters of the fixed body have already been merged in the parent body,
// in order to update correctly the parent body we need to first
// remove the inertial effects of the fixed body from his parent body
// Then update the fixed body inertia
// Finally, merge it again in the parent body
FixedBody& fixedbody(mFixedBodies[id - fixed_body_discriminator]);
mBodies[fixedbody.mMovableParent].Separate(fixedbody.mParentTransform, fixedbody.ToBody());
fixedbody.mMass = mass;
mBodies[fixedbody.mMovableParent].Join(fixedbody.mParentTransform, fixedbody.ToBody());
}
else
{
mBodies[id].mMass = mass;
}
UpdateInertiaMatrixForBody(id);
}
void Model::SetBodyInertia(const unsigned int id, const Math::Matrix3d &inertia)
{
if(IsFixedBodyId(id))
{
// The inertial parameters of the fixed body have already been merged in the parent body,
// in order to update correctly the parent body we need to first
// remove the inertial effects of the fixed body from his parent body
// Then update the fixed body inertia
// Finally, merge it again in the parent body
FixedBody& fixedbody(mFixedBodies[id - fixed_body_discriminator]);
mBodies[fixedbody.mMovableParent].Separate(fixedbody.mParentTransform, fixedbody.ToBody());
fixedbody.mInertia = inertia;
mBodies[fixedbody.mMovableParent].Join(fixedbody.mParentTransform, fixedbody.ToBody());
}
else
{
mBodies[id].mInertia = inertia;
}
UpdateInertiaMatrixForBody(id);
}
void Model::SetBodyCenterOfMass(const unsigned int id, const Math::Vector3d &com)
{
if(IsFixedBodyId(id))
{
// The inertial parameters of the fixed body have already been merged in the parent body,
// in order to update correctly the parent body we need to first
// remove the inertial effects of the fixed body from his parent body
// Then update the fixed body inertia
// Finally, merge it again in the parent body
FixedBody& fixedbody(mFixedBodies[id - fixed_body_discriminator]);
mBodies[fixedbody.mMovableParent].Separate(fixedbody.mParentTransform, fixedbody.ToBody());
fixedbody.mCenterOfMass = com;
mBodies[fixedbody.mMovableParent].Join(fixedbody.mParentTransform, fixedbody.ToBody());
}
else
{
mBodies[id].mCenterOfMass = com;
}
UpdateInertiaMatrixForBody(id);
}
void Model::SetBodyInertialParameters(const unsigned int id, const double mass,
const Math::Matrix3d &inertia, const Math::Vector3d &com)
{
if(IsFixedBodyId(id))
{
// The inertial parameters of the fixed body have already been merged in the parent body,
// in order to update correctly the parent body we need to first
// remove the inertial effects of the fixed body from his parent body
// Then update the fixed body inertia
// Finally, merge it again in the parent body
FixedBody& fixedbody(mFixedBodies[id - fixed_body_discriminator]);
mBodies[fixedbody.mMovableParent].Separate(fixedbody.mParentTransform, fixedbody.ToBody());
fixedbody.mMass = mass;
fixedbody.mInertia = inertia;
fixedbody.mCenterOfMass = com;
mBodies[fixedbody.mMovableParent].Join(fixedbody.mParentTransform, fixedbody.ToBody());
}
else
{
mBodies[id].mMass = mass;
mBodies[id].mInertia = inertia;
mBodies[id].mCenterOfMass = com;
}
UpdateInertiaMatrixForBody(id);
}
| 412 | 0.93698 | 1 | 0.93698 | game-dev | MEDIA | 0.629857 | game-dev | 0.976719 | 1 | 0.976719 |
bilal-fazlani/commanddotnet | 5,235 | CommandDotNet/Execution/CancellationHandlers.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading;
using CommandDotNet.Extensions;
using JetBrains.Annotations;
namespace CommandDotNet.Execution;
[PublicAPI]
public static class CancellationHandlers
{
// using a stack to handle interactive sessions
// so ctrl+c for a long running interactive command
// stops only that command and not the interactive session
private static readonly Stack<CommandContext> SourceStack = new();
private class Handler(CancellationTokenSource source)
{
public CancellationTokenSource Source { get; } = source ?? throw new ArgumentNullException(nameof(source));
public bool ShouldIgnoreCtrlC { get; set; }
}
private static Handler? GetHandler(this CommandContext ctx) => ctx.Services.GetOrDefault<Handler>();
private static void SetHandler(this CommandContext ctx, CancellationTokenSource src) => ctx.Services.Add(new Handler(src));
internal static void BeginRun(CommandContext ctx)
{
if (SourceStack.Count == 0)
{
// initialize for first command
// we don't want to add additional events for commands in a REPL session
ctx.Console.CancelKeyPress += Console_CancelKeyPress;
AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit;
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
}
var tokenSource = new CancellationTokenSource();
ctx.CancellationToken = tokenSource.Token;
ctx.SetHandler(tokenSource);
SourceStack.Push(ctx);
}
internal static void EndRun(CommandContext ctx)
{
SourceStack.Pop();
if (SourceStack.Count == 0)
{
// the app will exit now
// clean up for tests
ctx.Console.CancelKeyPress -= Console_CancelKeyPress;
AppDomain.CurrentDomain.ProcessExit -= CurrentDomain_ProcessExit;
AppDomain.CurrentDomain.UnhandledException -= CurrentDomain_UnhandledException;
}
}
/// <summary>
/// Prefer <see cref="IConsole.TreatControlCAsInput"/> when possible.
/// Use this in cases where another component depends on the <see cref="IConsole.CancelKeyPress"/>
/// event and CommandDotNet should ignore the event during this time.
/// </summary>
public static IDisposable IgnoreCtrlC()
{
// in case the feature isn't enabled but this is called.
if (SourceStack.Count == 0)
{
return DisposableAction.Null;
}
var handler = SourceStack.Peek().GetHandler()!;
handler.ShouldIgnoreCtrlC = true;
return new DisposableAction(() => handler.ShouldIgnoreCtrlC = false);
}
private static void Console_CancelKeyPress(object? sender, ConsoleCancelEventArgs e)
{
var handler = SourceStack.Peek().GetHandler();
if (handler == null)
{
return;
}
if (!handler.ShouldIgnoreCtrlC)
{
StopRun(handler);
e.Cancel = true;
}
}
private static void CurrentDomain_ProcessExit(object? sender, EventArgs e) => Shutdown();
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
if (e.IsTerminating)
{
Shutdown();
}
}
private static void StopRun(Handler? handler)
{
if (handler == null)
{
// this is an edge case race condition.
return;
}
var src = handler.Source;
if (!src.IsCancellationRequested)
{
src.Cancel();
}
}
private static void Shutdown() => SourceStack.ForEach(ctx => StopRun(ctx.GetHandler()));
internal static class TestAccess
{
internal static void Console_CancelKeyPress()
{
var args = Activate<ConsoleCancelEventArgs>(ConsoleSpecialKey.ControlC);
CancellationHandlers.Console_CancelKeyPress(new object(), args);
}
internal static void CurrentDomain_ProcessExit() =>
CancellationHandlers.CurrentDomain_ProcessExit(new object(), EventArgs.Empty);
internal static void CurrentDomain_UnhandledException(bool isTerminating)
{
var ex = new Exception("some random exception");
var args = Activate<UnhandledExceptionEventArgs>(ex, isTerminating);
CancellationHandlers.CurrentDomain_UnhandledException(new object(), args);
}
private static T Activate<T>(params object[] parameters)
{
var bindingFlags = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.CreateInstance;
var parameterTypes = parameters.Select(p => p.GetType()).ToArray();
var constructorInfo = typeof(T).GetConstructor(bindingFlags, null, parameterTypes, null);
if (constructorInfo is null)
{
throw new Exception(".net core contracts have changed. update code to handle new contracts");
}
return (T)constructorInfo.Invoke(parameters);
}
}
} | 412 | 0.939104 | 1 | 0.939104 | game-dev | MEDIA | 0.45862 | game-dev | 0.908355 | 1 | 0.908355 |
goldeneye-source/ges-code | 3,216 | game/shared/hl2/hl2_gamerules.h | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose: Game rules for Half-Life 2.
//
//=============================================================================//
#ifndef HL2_GAMERULES_H
#define HL2_GAMERULES_H
#ifdef _WIN32
#pragma once
#endif
#include "gamerules.h"
#include "singleplay_gamerules.h"
#include "hl2_shareddefs.h"
#ifdef CLIENT_DLL
#define CHalfLife2 C_HalfLife2
#define CHalfLife2Proxy C_HalfLife2Proxy
#endif
class CHalfLife2Proxy : public CGameRulesProxy
{
public:
DECLARE_CLASS( CHalfLife2Proxy, CGameRulesProxy );
DECLARE_NETWORKCLASS();
};
class CHalfLife2 : public CSingleplayRules
{
public:
DECLARE_CLASS( CHalfLife2, CSingleplayRules );
// Damage Query Overrides.
virtual bool Damage_IsTimeBased( int iDmgType );
// TEMP:
virtual int Damage_GetTimeBased( void );
virtual bool ShouldCollide( int collisionGroup0, int collisionGroup1 );
virtual bool ShouldUseRobustRadiusDamage(CBaseEntity *pEntity);
#ifndef CLIENT_DLL
virtual bool ShouldAutoAim( CBasePlayer *pPlayer, edict_t *target );
virtual float GetAutoAimScale( CBasePlayer *pPlayer );
virtual float GetAmmoQuantityScale( int iAmmoIndex );
virtual void LevelInitPreEntity();
#endif
private:
// Rules change for the mega physgun
CNetworkVar( bool, m_bMegaPhysgun );
#ifdef CLIENT_DLL
DECLARE_CLIENTCLASS_NOBASE(); // This makes datatables able to access our private vars.
#else
DECLARE_SERVERCLASS_NOBASE(); // This makes datatables able to access our private vars.
CHalfLife2();
virtual ~CHalfLife2() {}
virtual void Think( void );
virtual bool ClientCommand( CBaseEntity *pEdict, const CCommand &args );
virtual void PlayerSpawn( CBasePlayer *pPlayer );
virtual void InitDefaultAIRelationships( void );
virtual const char* AIClassText(int classType);
virtual const char *GetGameDescription( void ) { return "Half-Life 2"; }
// Ammo
virtual void PlayerThink( CBasePlayer *pPlayer );
virtual float GetAmmoDamage( CBaseEntity *pAttacker, CBaseEntity *pVictim, int nAmmoType );
virtual bool ShouldBurningPropsEmitLight();
public:
bool AllowDamage( CBaseEntity *pVictim, const CTakeDamageInfo &info );
bool NPC_ShouldDropGrenade( CBasePlayer *pRecipient );
bool NPC_ShouldDropHealth( CBasePlayer *pRecipient );
void NPC_DroppedHealth( void );
void NPC_DroppedGrenade( void );
bool MegaPhyscannonActive( void ) { return m_bMegaPhysgun; }
virtual bool IsAlyxInDarknessMode();
private:
float m_flLastHealthDropTime;
float m_flLastGrenadeDropTime;
void AdjustPlayerDamageTaken( CTakeDamageInfo *pInfo );
float AdjustPlayerDamageInflicted( float damage );
int DefaultFOV( void ) { return 75; }
#endif
};
//-----------------------------------------------------------------------------
// Gets us at the Half-Life 2 game rules
//-----------------------------------------------------------------------------
inline CHalfLife2* HL2GameRules()
{
#if ( !defined( HL2_DLL ) && !defined( HL2_CLIENT_DLL ) ) || defined( HL2MP )
Assert( 0 ); // g_pGameRules is NOT an instance of CHalfLife2 and bad things happen
#endif
return static_cast<CHalfLife2*>(g_pGameRules);
}
#endif // HL2_GAMERULES_H
| 412 | 0.946653 | 1 | 0.946653 | game-dev | MEDIA | 0.976596 | game-dev | 0.679062 | 1 | 0.679062 |
EOS-Contrib/eos_plugin_for_unity | 1,315 | com.playeveryware.eos/Runtime/EOS_SDK/Generated/UserInfo/CopyBestDisplayNameOptions.cs | // Copyright Epic Games, Inc. All Rights Reserved.
// This file is automatically generated. Changes to this file may be overwritten.
using System;
using System.Runtime.InteropServices;
namespace Epic.OnlineServices.UserInfo
{
/// <summary>
/// Input parameters for the <see cref="UserInfoInterface.CopyBestDisplayName" /> function.
/// </summary>
public struct CopyBestDisplayNameOptions
{
/// <summary>
/// The Epic Account ID of the local player requesting the information
/// </summary>
public EpicAccountId LocalUserId { get; set; }
/// <summary>
/// The Epic Account ID of the player whose information is being retrieved
/// </summary>
public EpicAccountId TargetUserId { get; set; }
}
[StructLayout(LayoutKind.Sequential)]
internal struct CopyBestDisplayNameOptionsInternal : ISettable<CopyBestDisplayNameOptions>
{
private int m_ApiVersion;
private IntPtr m_LocalUserId;
private IntPtr m_TargetUserId;
public void Set(ref CopyBestDisplayNameOptions other)
{
Dispose();
m_ApiVersion = UserInfoInterface.COPYBESTDISPLAYNAME_API_LATEST;
Helper.Set(other.LocalUserId, ref m_LocalUserId);
Helper.Set(other.TargetUserId, ref m_TargetUserId);
}
public void Dispose()
{
Helper.Dispose(ref m_LocalUserId);
Helper.Dispose(ref m_TargetUserId);
}
}
}
| 412 | 0.573164 | 1 | 0.573164 | game-dev | MEDIA | 0.517082 | game-dev | 0.557963 | 1 | 0.557963 |
thedarkcolour/ForestryCE | 5,726 | src/main/java/forestry/core/models/ModelBlockDefault.java | /*******************************************************************************
* Copyright (c) 2011-2014 SirSengir.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v3
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl-3.0.txt
*
* Various Contributors including, but not limited to:
* SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges
******************************************************************************/
package forestry.core.models;
import com.google.common.base.Preconditions;
import forestry.core.models.baker.ModelBaker;
import forestry.core.models.baker.ModelBakerModel;
import forestry.core.utils.ResourceUtil;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.client.renderer.block.model.BakedQuad;
import net.minecraft.client.renderer.block.model.ItemOverrides;
import net.minecraft.client.renderer.block.model.ItemTransforms;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.resources.model.BakedModel;
import net.minecraft.core.Direction;
import net.minecraft.util.RandomSource;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraftforge.client.model.data.ModelData;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.List;
public abstract class ModelBlockDefault<B extends Block, K> implements BakedModel {
@Nullable
private ItemOverrides overrideList;
protected final Class<B> blockClass;
@Nullable
protected ModelBakerModel blockModel;
@Nullable
protected ModelBakerModel itemModel;
protected ModelBlockDefault(Class<B> blockClass) {
this.blockClass = blockClass;
}
protected BakedModel bakeModel(BlockState state, K key, B block, ModelData extraData) {
ModelBaker baker = new ModelBaker();
bakeBlock(block, extraData, key, baker, false);
this.blockModel = baker.bake(false);
onCreateModel(this.blockModel);
return this.blockModel;
}
protected BakedModel getModel(BlockState state, ModelData extraData) {
Preconditions.checkArgument(this.blockClass.isInstance(state.getBlock()));
K worldKey = getWorldKey(state, extraData);
B block = this.blockClass.cast(state.getBlock());
return bakeModel(state, worldKey, block, extraData);
}
protected BakedModel bakeModel(ItemStack stack, Level world, K key) {
ModelBaker baker = new ModelBaker();
Block block = Block.byItem(stack.getItem());
Preconditions.checkArgument(this.blockClass.isInstance(block));
B bBlock = this.blockClass.cast(block);
bakeBlock(bBlock, ModelData.EMPTY, key, baker, true);
return this.itemModel = baker.bake(true);
}
protected BakedModel getModel(ItemStack stack, Level world) {
return bakeModel(stack, world, getInventoryKey(stack));
}
@Nonnull
@Override
public List<BakedQuad> getQuads(@Nullable BlockState state, @Nullable Direction side, @Nonnull RandomSource rand, @Nonnull ModelData extraData, @Nullable RenderType renderType) {
Preconditions.checkNotNull(state);
BakedModel model = getModel(state, extraData);
return model.getQuads(state, side, rand, extraData, renderType);
}
@Override
public List<BakedQuad> getQuads(@Nullable BlockState state, @Nullable Direction side, RandomSource rand) {
return getQuads(state, side, rand, ModelData.EMPTY, null);
}
protected void onCreateModel(ModelBakerModel model) {
model.setAmbientOcclusion(true);
}
@Override
public boolean useAmbientOcclusion() {
return (this.itemModel != null || this.blockModel != null) &&
(this.blockModel != null ? this.blockModel.useAmbientOcclusion() : this.itemModel.useAmbientOcclusion());
}
@Override
public boolean isGui3d() {
return this.itemModel != null && this.itemModel.isGui3d();
}
@Override
public boolean isCustomRenderer() {
return (this.itemModel != null || this.blockModel != null) &&
(this.blockModel != null ? this.blockModel.isCustomRenderer() : this.itemModel.isCustomRenderer());
}
@Override
public boolean usesBlockLight() {
return this.itemModel != null && this.itemModel.usesBlockLight();
}
@Override
public TextureAtlasSprite getParticleIcon() {
if (this.blockModel != null) {
return this.blockModel.getParticleIcon();
}
return ResourceUtil.getMissingTexture();
}
@Override
public ItemTransforms getTransforms() {
if (this.itemModel == null) {
return ItemTransforms.NO_TRANSFORMS;
}
return this.itemModel.getTransforms();
}
protected ItemOverrides createOverrides() {
return new DefaultItemOverrideList();
}
@Override
public ItemOverrides getOverrides() {
if (this.overrideList == null) {
this.overrideList = createOverrides();
}
return this.overrideList;
}
protected abstract K getInventoryKey(ItemStack stack);
protected abstract K getWorldKey(BlockState state, ModelData extraData);
protected abstract void bakeBlock(B block, ModelData extraData, K key, ModelBaker baker, boolean inventory);
private class DefaultItemOverrideList extends ItemOverrides {
public DefaultItemOverrideList() {
super();
}
@Nullable
@Override
public BakedModel resolve(BakedModel originalModel, ItemStack stack, @Nullable ClientLevel world, @Nullable LivingEntity entity, int p_173469_) {
if (world == null) {
world = Minecraft.getInstance().level;
}
return getModel(stack, world);
}
}
}
| 412 | 0.655308 | 1 | 0.655308 | game-dev | MEDIA | 0.913092 | game-dev | 0.678584 | 1 | 0.678584 |
KoboldAI/KoboldAI-Client | 2,695 | userscripts/examples/haxe_transcend/Main.hx | /*
* This file is part of KoboldAI.
*
* KoboldAI is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import haxe.exceptions.PosException;
import lua.Lua;
@:expose class Main {
public static final kobold:KoboldLib = untyped __lua__("_G.kobold");
public static final exampleConfig = "return true";
public static var shouldRun:Bool;
public static var f:BigInt = -2;
public static var e:BigInt = 4;
public static var s:BigInt = 8;
public static var t:BigInt = 1;
public static var i:BigInt = 0;
public static var v:BigInt = 1;
public static var a:BigInt = 6;
public static var l:BigInt = 1;
public static function inmod() {
if (!shouldRun) return;
kobold.halt_generation();
}
public static function outmod() {
if (!shouldRun) return;
// Gibbons, Jeremy. (2004). Unbounded Spigot Algorithms for the Digits
// of Pi. American Mathematical Monthly. 113. 10.2307/27641917.
while (true) {
var x = i/v;
if (x == (i + t)/v) {
trace(x);
kobold.outputs[1] = Std.string(x);
t *= 10;
i -= x*v;
i *= 10;
break;
}
else {
v *= s*a;
i *= s;
s += 8;
i += e * t;
e += 4;
i *= a;
a += 4;
t *= f*l;
l += 2;
f -= 4;
}
}
kobold.restart_generation(1);
}
public static function main() {
var f = kobold.get_config_file();
f.seek("set");
if (f.read(1) == null) f.write(exampleConfig);
f.seek("set");
var a = f.read("a");
f.close();
var result = Lua.load(a);
trace(result);
if (result.message != null) throw new PosException(result.message);
shouldRun = switch result.func() {
case false: false;
case null: false;
default: true;
}
}
}
| 412 | 0.753666 | 1 | 0.753666 | game-dev | MEDIA | 0.212324 | game-dev | 0.805211 | 1 | 0.805211 |
guicaulada/FiveM-Scripts | 8,766 | vrpex/vrp_adv_homes/cfg/home_components.lua | --[[
FiveM Scripts
Copyright C 2018 Sighmir
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
]]
-- define some basic home components
local sanitizes = module("cfg/sanitizes")
-- CHEST
local function chest_create(owner_id, stype, sid, cid, config, x, y, z, player)
local chest_enter = function(player,area)
local user_id = vRP.getUserId(player)
if user_id and user_id == owner_id then
vRP.openChest(player, "u"..owner_id.."home", config.weight or 200,nil,nil,nil)
end
end
local chest_leave = function(player,area)
vRP.closeMenu(player)
end
local nid = "vRP:home:slot"..stype..sid..":chest"
vRPclient.setNamedMarker(player,nid,x,y,z-1,0.7,0.7,0.5,0,255,125,125,150)
vRP.setArea(player,nid,x,y,z,1,1.5,chest_enter,chest_leave)
end
local function chest_destroy(owner_id, stype, sid, cid, config, x, y, z, player)
local nid = "vRP:home:slot"..stype..sid..":chest"
vRPclient.removeNamedMarker(player,nid)
vRP.removeArea(player,nid)
end
vRPh.defHomeComponent("chest", chest_create, chest_destroy)
-- WARDROBE
local function wardrobe_create(owner_id, stype, sid, cid, config, x, y, z, player)
local wardrobe_enter = nil
wardrobe_enter = function(player,area)
local user_id = vRP.getUserId(player)
if user_id and user_id == owner_id then
-- notify player if wearing a uniform
local data = vRP.getUserDataTable(user_id)
if data.cloakroom_idle then
vRPclient.notify(player,lang.common.wearing_uniform())
end
-- build menu
local menu = {name=lang.home.wardrobe.title(),css={top = "75px", header_color="rgba(0,255,125,0.75)"}}
-- load sets
local data = vRP.getUData(user_id, "vRP:home:wardrobe")
local sets = json.decode(data)
if sets == nil then
sets = {}
end
-- save
menu[lang.home.wardrobe.save.title()] = {function(player, choice)
local setname = vRP.prompt(player, lang.home.wardrobe.save.prompt(), "")
setname = sanitizeString(setname, sanitizes.text[1], sanitizes.text[2])
if string.len(setname) > 0 then
-- save custom
local custom =vRPclient.getCustomization(player)
sets[setname] = custom
-- save to db
vRP.setUData(user_id,"vRP:home:wardrobe",json.encode(sets))
-- actualize menu
wardrobe_enter(player, area)
else
vRPclient.notify(player,lang.common.invalid_value())
end
end}
local choose_set = function(player,choice)
local custom = sets[choice]
if custom then
vRPclient.setCustomization(player,custom)
end
end
-- sets
for k,v in pairs(sets) do
menu[k] = {choose_set}
end
-- open the menu
vRP.openMenu(player,menu)
end
end
local wardrobe_leave = function(player,area)
vRP.closeMenu(player)
end
local nid = "vRP:home:slot"..stype..sid..":wardrobe"
vRPclient.setNamedMarker(player,nid,x,y,z-1,0.7,0.7,0.5,0,255,125,125,150)
vRP.setArea(player,nid,x,y,z,1,1.5,wardrobe_enter,wardrobe_leave)
end
local function wardrobe_destroy(owner_id, stype, sid, cid, config, x, y, z, player)
local nid = "vRP:home:slot"..stype..sid..":wardrobe"
vRPclient.removeNamedMarker(player,nid)
vRP.removeArea(player,nid)
end
vRPh.defHomeComponent("wardrobe", wardrobe_create, wardrobe_destroy)
-- GAMETABLE
local function gametable_create(owner_id, stype, sid, cid, config, x, y, z, player)
local gametable_enter = function(player,area)
local user_id = vRP.getUserId(player)
if user_id and user_id == owner_id then
-- build menu
local menu = {name=lang.home.gametable.title(),css={top = "75px", header_color="rgba(0,255,125,0.75)"}}
-- launch bet
menu[lang.home.gametable.bet.title()] = {function(player, choice)
local amount = vRP.prompt(player, lang.home.gametable.bet.prompt(), "")
amount = parseInt(amount)
if amount > 0 then
if vRP.tryPayment(user_id,amount) then
vRPclient.notify(player,lang.home.gametable.bet.started())
-- init bet total and players (add by default the bet launcher)
local bet_total = amount
local bet_players = {}
local bet_opened = true
table.insert(bet_players, player)
local close_bet = function()
if bet_opened then
bet_opened = false
-- select winner
local wplayer = bet_players[math.random(1,#bet_players)]
local wuser_id = vRP.getUserId(wplayer)
if wuser_id then
vRP.giveMoney(wuser_id, bet_total)
vRPclient.notify(wplayer,lang.money.received({bet_total}))
vRPclient.playAnim(wplayer,true,{{"mp_player_introck","mp_player_int_rock",1}},false)
end
end
end
-- send bet request to all nearest players
local players = vRPclient.getNearestPlayers(player,7)
local pcount = 0
for k,v in pairs(players) do
pcount = pcount+1
local nplayer = parseInt(k)
local nuser_id = vRP.getUserId(nplayer)
if nuser_id then -- request
Citizen.CreateThread(function() -- non blocking
if vRP.request(nplayer,lang.home.gametable.bet.request({amount}), 30) and bet_opened then
if vRP.tryPayment(nuser_id,amount) then -- register player bet
bet_total = bet_total+amount
table.insert(bet_players, nplayer)
vRPclient.notify(nplayer,lang.money.paid({amount}))
else
vRPclient.notify(nplayer,lang.money.not_enough())
end
end
pcount = pcount-1
if pcount == 0 then -- autoclose bet, everyone is ok
close_bet()
end
end)
end
end
-- bet timeout
SetTimeout(32000, close_bet)
else
vRPclient.notify(player,lang.money.not_enough())
end
else
vRPclient.notify(player,lang.common.invalid_value())
end
end,lang.home.gametable.bet.description()}
-- open the menu
vRP.openMenu(player,menu)
end
end
local gametable_leave = function(player,area)
vRP.closeMenu(player)
end
local nid = "vRP:home:slot"..stype..sid..":gametable"
vRPclient.setNamedMarker(player,nid,x,y,z-1,0.7,0.7,0.5,0,255,125,125,150)
vRP.setArea(player,nid,x,y,z,1,1.5,gametable_enter,gametable_leave)
end
local function gametable_destroy(owner_id, stype, sid, cid, config, x, y, z, player)
local nid = "vRP:home:slot"..stype..sid..":gametable"
vRPclient.removeNamedMarker(player,nid)
vRP.removeArea(player,nid)
end
vRPh.defHomeComponent("gametable", gametable_create, gametable_destroy)
-- ITEM TRANSFORMERS
-- item transformers are global to all players, so we need a counter to know when to create/destroy them
local itemtrs = {}
local function itemtr_create(owner_id, stype, sid, cid, config, x, y, z, player)
local nid = "home:slot"..stype..sid..":itemtr"..cid
if itemtrs[nid] == nil then
itemtrs[nid] = 1
-- simple copy
local itemtr = {}
for k,v in pairs(config) do
itemtr[k] = v
end
itemtr.x = x
itemtr.y = y
itemtr.z = z
vRP.setItemTransformer(nid, itemtr)
else
itemtrs[nid] = itemtrs[nid]+1
end
end
local function itemtr_destroy(owner_id, stype, sid, cid, config, x, y, z, player)
local nid = "home:slot"..stype..sid..":itemtr"..cid
if itemtrs[nid] ~= nil then
itemtrs[nid] = itemtrs[nid]-1
if itemtrs[nid] == 0 then
itemtrs[nid] = nil
vRP.removeItemTransformer(nid)
end
end
end
vRPh.defHomeComponent("itemtr", itemtr_create, itemtr_destroy)
| 412 | 0.915411 | 1 | 0.915411 | game-dev | MEDIA | 0.863028 | game-dev | 0.925499 | 1 | 0.925499 |
SammySemicolon/Malum-Mod | 1,230 | src/main/java/com/sammy/malum/common/block/nature/soulwood/SoulwoodBlock.java | package com.sammy.malum.common.block.nature.soulwood;
import com.sammy.malum.registry.common.MalumSoundEvents;
import net.minecraft.sounds.SoundSource;
import net.minecraft.world.item.context.UseOnContext;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.BlockState;
import net.neoforged.neoforge.common.ItemAbilities;
import net.neoforged.neoforge.common.ItemAbility;
import org.jetbrains.annotations.Nullable;
import team.lodestar.lodestone.systems.block.LodestoneLogBlock;
import java.util.function.Supplier;
public class SoulwoodBlock extends LodestoneLogBlock {
public SoulwoodBlock(Properties properties, Supplier<Block> stripped) {
super(properties, stripped);
}
@Nullable
@Override
public BlockState getToolModifiedState(BlockState state, UseOnContext context, ItemAbility itemAbility, boolean simulate) {
if (itemAbility.equals(ItemAbilities.AXE_STRIP)) {
if (!simulate) {
context.getLevel().playSound(null, context.getClickedPos(), MalumSoundEvents.MAJOR_BLIGHT_MOTIF.get(), SoundSource.BLOCKS, 1, 1);
}
return stripped.get().defaultBlockState();
}
return null;
}
}
| 412 | 0.663616 | 1 | 0.663616 | game-dev | MEDIA | 0.997332 | game-dev | 0.723911 | 1 | 0.723911 |
flutter/engine | 2,845 | shell/platform/glfw/client_wrapper/flutter_engine.cc | // Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "include/flutter/flutter_engine.h"
#include <algorithm>
#include <iostream>
namespace flutter {
FlutterEngine::FlutterEngine() {}
FlutterEngine::~FlutterEngine() {}
bool FlutterEngine::Start(const std::string& icu_data_path,
const std::string& assets_path,
const std::vector<std::string>& arguments,
const std::string& aot_library_path) {
if (engine_) {
std::cerr << "Cannot run an already running engine. Create a new instance "
"or call ShutDown first."
<< std::endl;
return false;
}
FlutterDesktopEngineProperties c_engine_properties = {};
c_engine_properties.assets_path = assets_path.c_str();
c_engine_properties.icu_data_path = icu_data_path.c_str();
c_engine_properties.aot_library_path = aot_library_path.c_str();
std::vector<const char*> engine_switches;
std::transform(
arguments.begin(), arguments.end(), std::back_inserter(engine_switches),
[](const std::string& arg) -> const char* { return arg.c_str(); });
if (!engine_switches.empty()) {
c_engine_properties.switches = &engine_switches[0];
c_engine_properties.switches_count = engine_switches.size();
}
engine_ = UniqueEnginePtr(FlutterDesktopRunEngine(c_engine_properties),
FlutterDesktopShutDownEngine);
if (!engine_) {
std::cerr << "Failed to start engine." << std::endl;
return false;
}
return true;
}
void FlutterEngine::ShutDown() {
engine_ = nullptr;
}
FlutterDesktopPluginRegistrarRef FlutterEngine::GetRegistrarForPlugin(
const std::string& plugin_name) {
if (!engine_) {
std::cerr << "Cannot get plugin registrar on an engine that isn't running; "
"call Run first."
<< std::endl;
return nullptr;
}
return FlutterDesktopGetPluginRegistrar(engine_.get(), plugin_name.c_str());
}
void FlutterEngine::RunEventLoopWithTimeout(std::chrono::milliseconds timeout) {
if (!engine_) {
std::cerr << "Cannot run event loop without a running engine; call "
"Run first."
<< std::endl;
return;
}
uint32_t timeout_milliseconds;
if (timeout == std::chrono::milliseconds::max()) {
// The C API uses 0 to represent no timeout, so convert |max| to 0.
timeout_milliseconds = 0;
} else if (timeout.count() > UINT32_MAX) {
timeout_milliseconds = UINT32_MAX;
} else {
timeout_milliseconds = static_cast<uint32_t>(timeout.count());
}
FlutterDesktopRunEngineEventLoopWithTimeout(engine_.get(),
timeout_milliseconds);
}
} // namespace flutter
| 412 | 0.825089 | 1 | 0.825089 | game-dev | MEDIA | 0.481236 | game-dev | 0.81817 | 1 | 0.81817 |
The-Aether-Team/The-Aether | 5,488 | src/main/java/com/aetherteam/aether/client/renderer/player/layer/PlayerHaloLayer.java | package com.aetherteam.aether.client.renderer.player.layer;
import com.aetherteam.aether.Aether;
import com.aetherteam.aether.client.gui.screen.perks.AetherCustomizationsScreen;
import com.aetherteam.aether.client.renderer.AetherModelLayers;
import com.aetherteam.aether.client.renderer.entity.model.HaloModel;
import com.aetherteam.aether.perk.PerkUtil;
import com.aetherteam.aether.perk.data.ClientHaloPerkData;
import com.aetherteam.aether.perk.types.Halo;
import com.aetherteam.nitrogen.api.users.User;
import com.aetherteam.nitrogen.api.users.UserData;
import com.mojang.blaze3d.vertex.PoseStack;
import com.mojang.blaze3d.vertex.VertexConsumer;
import net.minecraft.client.Minecraft;
import net.minecraft.client.model.PlayerModel;
import net.minecraft.client.model.geom.EntityModelSet;
import net.minecraft.client.player.AbstractClientPlayer;
import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.client.renderer.entity.RenderLayerParent;
import net.minecraft.client.renderer.entity.layers.RenderLayer;
import net.minecraft.client.renderer.texture.OverlayTexture;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.entity.player.Player;
import org.apache.commons.lang3.tuple.Triple;
import java.awt.*;
import java.util.Map;
import java.util.UUID;
public class PlayerHaloLayer<T extends Player, M extends PlayerModel<T>> extends RenderLayer<T, M> {
private static final ResourceLocation PLAYER_HALO_LOCATION = ResourceLocation.fromNamespaceAndPath(Aether.MODID, "textures/models/perks/halo.png");
private static final ResourceLocation PLAYER_HALO_GRAYSCALE_LOCATION = ResourceLocation.fromNamespaceAndPath(Aether.MODID, "textures/models/perks/halo_grayscale.png");
private final HaloModel<Player> playerHalo;
public PlayerHaloLayer(RenderLayerParent<T, M> entityRenderer, EntityModelSet modelSet) {
super(entityRenderer);
this.playerHalo = new HaloModel<>(modelSet.bakeLayer(AetherModelLayers.PLAYER_HALO));
}
/**
* If the player has a Halo, this will render it in the {@link AetherCustomizationsScreen} or in the world, and color it based on the settings the player has defined.
*
* @param poseStack The rendering {@link PoseStack}.
* @param buffer The rendering {@link MultiBufferSource}.
* @param packedLight The {@link Integer} for the packed lighting for rendering.
* @param entity The entity.
* @param limbSwing The {@link Float} for the limb swing rotation.
* @param limbSwingAmount The {@link Float} for the limb swing amount.
* @param partialTicks The {@link Float} for the game's partial ticks.
* @param ageInTicks The {@link Float} for the entity's age in ticks.
* @param netHeadYaw The {@link Float} for the head yaw rotation.
* @param headPitch The {@link Float} for the head pitch rotation.
*/
@Override
public void render(PoseStack poseStack, MultiBufferSource buffer, int packedLight, T entity, float limbSwing, float limbSwingAmount, float partialTicks, float ageInTicks, float netHeadYaw, float headPitch) {
if (entity instanceof AbstractClientPlayer abstractClientPlayer && !abstractClientPlayer.isInvisible()) {
User user = UserData.Client.getClientUser();
UUID playerUUID = abstractClientPlayer.getUUID();
Map<UUID, Halo> halos = ClientHaloPerkData.INSTANCE.getClientPerkData();
if ((Minecraft.getInstance().screen instanceof AetherCustomizationsScreen aetherCustomizationsScreen && aetherCustomizationsScreen.haloEnabled && Minecraft.getInstance().player != null && playerUUID.equals(Minecraft.getInstance().player.getUUID()) && user != null && PerkUtil.hasHalo().test(user))
|| (!(Minecraft.getInstance().screen instanceof AetherCustomizationsScreen) && halos.containsKey(playerUUID))) {
this.playerHalo.halo.yRot = this.getParentModel().head.yRot;
this.playerHalo.halo.xRot = this.getParentModel().head.xRot;
if (entity.isCrouching()) {
this.playerHalo.halo.y = 4.2F;
} else {
this.playerHalo.halo.y = 0.0F;
}
this.playerHalo.setupAnim(entity, limbSwing, limbSwingAmount, ageInTicks, netHeadYaw, headPitch);
Triple<Float, Float, Float> color;
if (Minecraft.getInstance().screen instanceof AetherCustomizationsScreen aetherCustomizationsScreen) {
color = PerkUtil.getPerkColor(aetherCustomizationsScreen.haloColor);
} else {
color = PerkUtil.getPerkColor(halos.get(playerUUID).hexColor());
}
if (color != null) {
VertexConsumer vertexConsumer = buffer.getBuffer(RenderType.entityTranslucent(PLAYER_HALO_GRAYSCALE_LOCATION));
this.playerHalo.renderToBuffer(poseStack, vertexConsumer, packedLight, OverlayTexture.NO_OVERLAY, new Color(color.getLeft(), color.getMiddle(), color.getRight(), 1.0F).getRGB());
} else {
VertexConsumer vertexConsumer = buffer.getBuffer(RenderType.entityTranslucent(PLAYER_HALO_LOCATION));
this.playerHalo.renderToBuffer(poseStack, vertexConsumer, packedLight, OverlayTexture.NO_OVERLAY);
}
}
}
}
}
| 412 | 0.578013 | 1 | 0.578013 | game-dev | MEDIA | 0.856757 | game-dev,graphics-rendering | 0.968942 | 1 | 0.968942 |
LorettaDevs/Loretta | 11,199 | src/Compilers/Core/Portable/Syntax/InternalSyntax/SyntaxNodeCache.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.Diagnostics;
#if STATS
using System.Threading;
#endif
namespace Loretta.CodeAnalysis.Syntax.InternalSyntax
{
/// <summary>
/// Provides caching functionality for green nonterminals with up to 3 children.
/// Example:
/// When constructing a node with given kind, flags, child1 and child2, we can look up
/// in the cache whether we already have a node that contains same kind, flags,
/// child1 and child2 and use that.
///
/// For the purpose of children comparison, reference equality is used as a much cheaper
/// alternative to the structural/recursive equality. This implies that in order to de-duplicate
/// a node to a cache node, the children of two nodes must be already de-duplicated.
/// When adding a node to the cache we verify that cache does contain node's children,
/// since otherwise there is no reason for the node to be used.
/// Tokens/nulls are for this purpose considered deduplicated. Indeed most of the tokens
/// are deduplicated via quick-scanner caching, so we just assume they all are.
///
/// As a result of above, "fat" nodes with 4 or more children or their recursive parents
/// will never be in the cache. This naturally limits the typical single cache item to be
/// a relatively simple expression. We do not want the cache to be completely unbounded
/// on the item size.
/// While it still may be possible to store a gigantic nested binary expression,
/// it should be a rare occurrence.
///
/// We only consider "normal" nodes to be cacheable.
/// Nodes with diagnostics/annotations/directives/skipped, etc... have more complicated identity
/// and are not likely to be repetitive.
///
/// </summary>
internal class GreenStats
{
// TODO: remove when done tweaking this cache.
#if STATS
private static GreenStats stats = new GreenStats();
private int greenNodes;
private int greenTokens;
private int nontermsAdded;
private int cacheableNodes;
private int cacheHits;
internal static void NoteGreen(GreenNode node)
{
Interlocked.Increment(ref stats.greenNodes);
if (node.IsToken)
{
Interlocked.Increment(ref stats.greenTokens);
}
}
internal static void ItemAdded()
{
Interlocked.Increment(ref stats.nontermsAdded);
}
internal static void ItemCacheable()
{
Interlocked.Increment(ref stats.cacheableNodes);
}
internal static void CacheHit()
{
Interlocked.Increment(ref stats.cacheHits);
}
~GreenStats()
{
Console.WriteLine("Green: " + greenNodes);
Console.WriteLine("GreenTk: " + greenTokens);
Console.WriteLine("Nonterminals added: " + nontermsAdded);
Console.WriteLine("Nonterminals cacheable: " + cacheableNodes);
Console.WriteLine("CacheHits: " + cacheHits);
Console.WriteLine("RateOfAll: " + (cacheHits * 100 / (cacheHits + greenNodes - greenTokens)) + "%");
Console.WriteLine("RateOfCacheable: " + (cacheHits * 100 / (cacheableNodes)) + "%");
}
#else
#pragma warning disable IDE0079 // Remove unnecessary suppression
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Used in the other overload.")]
#pragma warning restore IDE0079 // Remove unnecessary suppression
internal static void NoteGreen(GreenNode node)
{
}
[Conditional("DEBUG")]
internal static void ItemAdded()
{
}
[Conditional("DEBUG")]
internal static void ItemCacheable()
{
}
[Conditional("DEBUG")]
internal static void CacheHit()
{
}
#endif
}
internal static class SyntaxNodeCache
{
private const int CacheSizeBits = 16;
private const int CacheSize = 1 << CacheSizeBits;
private const int CacheMask = CacheSize - 1;
private readonly struct Entry
{
public readonly int hash;
public readonly GreenNode? node;
internal Entry(int hash, GreenNode node)
{
this.hash = hash;
this.node = node;
}
}
private static readonly Entry[] s_cache = new Entry[CacheSize];
internal static void AddNode(GreenNode node, int hash)
{
if (AllChildrenInCache(node) && !node.IsMissing)
{
GreenStats.ItemAdded();
LorettaDebug.Assert(node.GetCacheHash() == hash);
var idx = hash & CacheMask;
s_cache[idx] = new Entry(hash, node);
}
}
private static bool CanBeCached(GreenNode? child1) =>
child1 == null || child1.IsCacheable;
private static bool CanBeCached(GreenNode? child1, GreenNode? child2) =>
CanBeCached(child1) && CanBeCached(child2);
private static bool CanBeCached(GreenNode? child1, GreenNode? child2, GreenNode? child3) =>
CanBeCached(child1) && CanBeCached(child2) && CanBeCached(child3);
private static bool ChildInCache(GreenNode? child)
{
// for the purpose of this function consider that
// null nodes, tokens and trivias are cached somewhere else.
// TODO: should use slotCount
if (child == null || child.SlotCount == 0) return true;
int hash = child.GetCacheHash();
int idx = hash & CacheMask;
return s_cache[idx].node == child;
}
private static bool AllChildrenInCache(GreenNode node)
{
// TODO: should use slotCount
var cnt = node.SlotCount;
for (int i = 0; i < cnt; i++)
{
if (!ChildInCache(node.GetSlot(i)))
{
return false;
}
}
return true;
}
internal static GreenNode? TryGetNode(int kind, GreenNode? child1, out int hash) =>
TryGetNode(kind, child1, GetDefaultNodeFlags(), out hash);
internal static GreenNode? TryGetNode(int kind, GreenNode? child1, GreenNode.NodeFlags flags, out int hash)
{
if (CanBeCached(child1))
{
GreenStats.ItemCacheable();
int h = hash = GetCacheHash(kind, flags, child1);
int idx = h & CacheMask;
var e = s_cache[idx];
if (e.hash == h && e.node != null && e.node.IsCacheEquivalent(kind, flags, child1))
{
GreenStats.CacheHit();
return e.node;
}
}
else
{
hash = -1;
}
return null;
}
internal static GreenNode? TryGetNode(int kind, GreenNode? child1, GreenNode? child2, out int hash) =>
TryGetNode(kind, child1, child2, GetDefaultNodeFlags(), out hash);
internal static GreenNode? TryGetNode(int kind, GreenNode? child1, GreenNode? child2, GreenNode.NodeFlags flags, out int hash)
{
if (CanBeCached(child1, child2))
{
GreenStats.ItemCacheable();
int h = hash = GetCacheHash(kind, flags, child1, child2);
int idx = h & CacheMask;
var e = s_cache[idx];
if (e.hash == h && e.node != null && e.node.IsCacheEquivalent(kind, flags, child1, child2))
{
GreenStats.CacheHit();
return e.node;
}
}
else
{
hash = -1;
}
return null;
}
internal static GreenNode? TryGetNode(int kind, GreenNode? child1, GreenNode? child2, GreenNode? child3, out int hash) =>
TryGetNode(kind, child1, child2, child3, GetDefaultNodeFlags(), out hash);
internal static GreenNode? TryGetNode(int kind, GreenNode? child1, GreenNode? child2, GreenNode? child3, GreenNode.NodeFlags flags, out int hash)
{
if (CanBeCached(child1, child2, child3))
{
GreenStats.ItemCacheable();
int h = hash = GetCacheHash(kind, flags, child1, child2, child3);
int idx = h & CacheMask;
var e = s_cache[idx];
if (e.hash == h && e.node != null && e.node.IsCacheEquivalent(kind, flags, child1, child2, child3))
{
GreenStats.CacheHit();
return e.node;
}
}
else
{
hash = -1;
}
return null;
}
public static GreenNode.NodeFlags GetDefaultNodeFlags() =>
GreenNode.NodeFlags.IsNotMissing;
private static int GetCacheHash(int kind, GreenNode.NodeFlags flags, GreenNode? child1)
{
int code = (int) flags ^ kind;
// the only child is never null
// https://github.com/dotnet/roslyn/issues/41539
code = Hash.Combine(System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(child1!), code);
// ensure nonnegative hash
return code & int.MaxValue;
}
private static int GetCacheHash(int kind, GreenNode.NodeFlags flags, GreenNode? child1, GreenNode? child2)
{
int code = (int) flags ^ kind;
if (child1 != null)
{
code = Hash.Combine(System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(child1), code);
}
if (child2 != null)
{
code = Hash.Combine(System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(child2), code);
}
// ensure nonnegative hash
return code & int.MaxValue;
}
private static int GetCacheHash(int kind, GreenNode.NodeFlags flags, GreenNode? child1, GreenNode? child2, GreenNode? child3)
{
int code = (int) flags ^ kind;
if (child1 != null)
{
code = Hash.Combine(System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(child1), code);
}
if (child2 != null)
{
code = Hash.Combine(System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(child2), code);
}
if (child3 != null)
{
code = Hash.Combine(System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(child3), code);
}
// ensure nonnegative hash
return code & int.MaxValue;
}
}
}
| 412 | 0.896332 | 1 | 0.896332 | game-dev | MEDIA | 0.715863 | game-dev | 0.927042 | 1 | 0.927042 |
389ds/389-ds-base | 5,293 | ldap/servers/plugins/syntaxes/sicis.c | /** BEGIN COPYRIGHT BLOCK
* Copyright (C) 2005 Red Hat, Inc.
* All rights reserved.
*
* License: GPL (version 3 or any later version).
* See LICENSE for details.
* END COPYRIGHT BLOCK **/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
/*
* sicis.c - space insensitive string syntax routines.
* these strings are also case insensitive.
*
* This is a non-standard syntax. It is only used by the presence plug-in.
* It will be disabled by default unless the presence plug-in is compiled.
*/
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include "syntax.h"
static int sicis_filter_ava(Slapi_PBlock *pb, struct berval *bvfilter, Slapi_Value **bvals, int ftype, Slapi_Value **retVal);
static int sicis_filter_sub(Slapi_PBlock *pb, char *initial, char **any, char * final, Slapi_Value **bvals);
static int sicis_values2keys(Slapi_PBlock *pb, Slapi_Value **val, Slapi_Value ***ivals, int ftype);
static int sicis_assertion2keys_ava(Slapi_PBlock *pb, Slapi_Value *val, Slapi_Value ***ivals, int ftype);
static int sicis_assertion2keys_sub(Slapi_PBlock *pb, char *initial, char **any, char * final, Slapi_Value ***ivals);
static int sicis_compare(struct berval *v1, struct berval *v2);
static void sicis_normalize(
Slapi_PBlock *pb,
char *s,
int trim_spaces,
char **alt);
/* the first name is the official one from RFC 2252 */
static char *names[] = {"SpaceInsensitiveString",
SPACE_INSENSITIVE_STRING_SYNTAX_OID, 0};
static Slapi_PluginDesc pdesc = {"spaceinsensitivestring-syntax",
VENDOR, DS_PACKAGE_VERSION,
"space insensitive string attribute syntax plugin"};
int
sicis_init(Slapi_PBlock *pb)
{
int rc, flags;
slapi_log_err(SLAPI_LOG_PLUGIN, SYNTAX_PLUGIN_SUBSYSTEM, "=> sicis_init\n");
rc = slapi_pblock_set(pb, SLAPI_PLUGIN_VERSION,
(void *)SLAPI_PLUGIN_VERSION_01);
rc |= slapi_pblock_set(pb, SLAPI_PLUGIN_DESCRIPTION,
(void *)&pdesc);
rc |= slapi_pblock_set(pb, SLAPI_PLUGIN_SYNTAX_FILTER_AVA,
(void *)sicis_filter_ava);
rc |= slapi_pblock_set(pb, SLAPI_PLUGIN_SYNTAX_FILTER_SUB,
(void *)sicis_filter_sub);
rc |= slapi_pblock_set(pb, SLAPI_PLUGIN_SYNTAX_VALUES2KEYS,
(void *)sicis_values2keys);
rc |= slapi_pblock_set(pb, SLAPI_PLUGIN_SYNTAX_ASSERTION2KEYS_AVA,
(void *)sicis_assertion2keys_ava);
rc |= slapi_pblock_set(pb, SLAPI_PLUGIN_SYNTAX_ASSERTION2KEYS_SUB,
(void *)sicis_assertion2keys_sub);
flags = SLAPI_PLUGIN_SYNTAX_FLAG_ORDERING;
rc |= slapi_pblock_set(pb, SLAPI_PLUGIN_SYNTAX_FLAGS,
(void *)&flags);
rc |= slapi_pblock_set(pb, SLAPI_PLUGIN_SYNTAX_NAMES,
(void *)names);
rc |= slapi_pblock_set(pb, SLAPI_PLUGIN_SYNTAX_OID,
(void *)SPACE_INSENSITIVE_STRING_SYNTAX_OID);
rc |= slapi_pblock_set(pb, SLAPI_PLUGIN_SYNTAX_COMPARE,
(void *)sicis_compare);
rc |= slapi_pblock_set(pb, SLAPI_PLUGIN_SYNTAX_NORMALIZE,
(void *)sicis_normalize);
slapi_log_err(SLAPI_LOG_PLUGIN, SYNTAX_PLUGIN_SUBSYSTEM, "<= sicis_init %d\n", rc);
return (rc);
}
static int
sicis_filter_ava(
Slapi_PBlock *pb,
struct berval *bvfilter,
Slapi_Value **bvals,
int ftype,
Slapi_Value **retVal)
{
int filter_normalized = 0;
int syntax = SYNTAX_SI | SYNTAX_CIS;
if (pb) {
slapi_pblock_get(pb, SLAPI_PLUGIN_SYNTAX_FILTER_NORMALIZED,
&filter_normalized);
if (filter_normalized) {
syntax |= SYNTAX_NORM_FILT;
}
}
return (string_filter_ava(bvfilter, bvals, syntax,
ftype, retVal));
}
static int
sicis_filter_sub(
Slapi_PBlock *pb,
char *initial,
char **any,
char * final,
Slapi_Value **bvals)
{
return (string_filter_sub(pb, initial, any, final, bvals, SYNTAX_SI | SYNTAX_CIS));
}
static int
sicis_values2keys(
Slapi_PBlock *pb,
Slapi_Value **vals,
Slapi_Value ***ivals,
int ftype)
{
return (string_values2keys(pb, vals, ivals, SYNTAX_SI | SYNTAX_CIS,
ftype));
}
static int
sicis_assertion2keys_ava(
Slapi_PBlock *pb,
Slapi_Value *val,
Slapi_Value ***ivals,
int ftype)
{
return (string_assertion2keys_ava(pb, val, ivals,
SYNTAX_SI | SYNTAX_CIS, ftype));
}
static int
sicis_assertion2keys_sub(
Slapi_PBlock *pb,
char *initial,
char **any,
char * final,
Slapi_Value ***ivals)
{
return (string_assertion2keys_sub(pb, initial, any, final, ivals,
SYNTAX_SI | SYNTAX_CIS));
}
static int
sicis_compare(
struct berval *v1,
struct berval *v2)
{
return value_cmp(v1, v2, SYNTAX_SI | SYNTAX_CIS, 3 /* Normalise both values */);
}
static void
sicis_normalize(
Slapi_PBlock *pb __attribute__((unused)),
char *s,
int trim_spaces,
char **alt)
{
value_normalize_ext(s, SYNTAX_SI | SYNTAX_CIS, trim_spaces, alt);
return;
}
| 412 | 0.733057 | 1 | 0.733057 | game-dev | MEDIA | 0.187736 | game-dev | 0.51532 | 1 | 0.51532 |
hebiiro/anti.aviutl.ultimate.plugin | 1,153 | source/item_align.aua/action/fix_bpm.hpp | #pragma once
namespace apn::item_align
{
//
// このクラスはBPMずれを修正します。
//
struct FixBpm : Action
{
//
// 指定されたフレーム番号を修正して返します。
//
int32_t fix_frame(int32_t frame)
{
auto right_frame = frame_per_time;
auto wrong_frame = ceil(right_frame);
return (int32_t)ceil(frame * right_frame / wrong_frame);
}
//
// 選択オブジェクトを移動します。
//
virtual void move_objects() override
{
MY_TRACE_FUNC("");
auto current_frame = magi.exin.get_exedit_current_frame();
auto fixed_current_frame = fix_frame(current_frame);
auto diff_current_frame = current_frame - fixed_current_frame;
// 選択ノードを走査します。
for (auto& mover : selection)
{
// アイテムを取得します。
auto object = magi.exin.get_object(mover->object_index);
auto frame_begin = object->frame_begin;
auto frame_end = object->frame_end;
if (hive.use_current_frame)
{
frame_begin += diff_current_frame;
frame_end += diff_current_frame;
}
// 位置をずらします。
object->frame_begin = fix_frame(frame_begin);
object->frame_end = frame_end = fix_frame(frame_end + 1) - 1;
magi.exin.create_undo(mover->object_index, 0x00);
}
}
};
}
| 412 | 0.745724 | 1 | 0.745724 | game-dev | MEDIA | 0.51001 | game-dev | 0.735713 | 1 | 0.735713 |
Sigma-Skidder-Team/SigmaRemap | 8,567 | src/main/java/com/mentalfrostbyte/jello/account/BanListener.java | package com.mentalfrostbyte.jello.account;
import com.mentalfrostbyte.Client;
import com.mentalfrostbyte.jello.event.EventTarget;
import com.mentalfrostbyte.jello.event.impl.ReceivePacketEvent;
import net.minecraft.client.Minecraft;
import net.minecraft.network.login.server.SDisconnectLoginPacket;
import net.minecraft.network.login.server.SLoginSuccessPacket;
import net.minecraft.network.play.server.SDisconnectPacket;
import net.minecraft.network.play.server.SChatPacket;
import totalcross.json.JSONException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class BanListener {
public Minecraft field38719 = Minecraft.getInstance();
@EventTarget
private void method30840(ReceivePacketEvent var1) throws JSONException {
if (this.field38719.getCurrentServerData() != null) {
if (var1.getPacket() instanceof SChatPacket) {
SChatPacket var4 = (SChatPacket) var1.getPacket();
ArrayList var5 = new ArrayList<String>(
Arrays.asList(
"You are permanently banned from MinemenClub. ",
"Your connection to the server leu-practice has been prevented due to you being associated to a blacklisted player.",
"You are blacklisted from MinemenClub. "));
if (!var4.getChatComponent().getSiblings().isEmpty()
&& var5.contains(var4.getChatComponent().getString())
&& var4.getChatComponent().getSiblings().get(0).getStyle().getColor().toString()
.equalsIgnoreCase("red")) {
Account var6 = Client.getInstance().accountManager.containsAccount();
if (var6 != null) {
Ban var7 = new Ban(this.field38719.getCurrentServerData().serverIP, new Date(Long.MAX_VALUE));
var6.registerBan(var7);
Client.getInstance().accountManager.updateAccount(var6);
Client.getInstance().accountManager.saveAlts();
}
}
}
if (!(var1.getPacket() instanceof SDisconnectLoginPacket)) {
if (!(var1.getPacket() instanceof SDisconnectPacket)) {
if (var1.getPacket() instanceof SLoginSuccessPacket) {
long var11 = System.currentTimeMillis();
if (this.field38719.getCurrentServerData() == null) {
return;
}
Ban var15 = new Ban(this.field38719.getCurrentServerData().serverIP, new Date(var11));
Account var16 = Client.getInstance().accountManager.containsAccount();
if (var16 != null) {
var16.registerBan(var15);
Client.getInstance().accountManager.updateAccount(var16);
Client.getInstance().accountManager.saveAlts();
}
}
} else {
SDisconnectPacket var13 = (SDisconnectPacket) var1.getPacket();
long var8 = this.method30841(var13.method17390().getString());
if (var8 == 0L) {
return;
}
Ban var17 = new Ban(this.field38719.getCurrentServerData().serverIP, new Date(var8));
Account var10 = Client.getInstance().accountManager.containsAccount();
if (var10 != null) {
var10.registerBan(var17);
Client.getInstance().accountManager.updateAccount(var10);
Client.getInstance().accountManager.saveAlts();
}
}
} else {
SDisconnectLoginPacket var14 = (SDisconnectLoginPacket) var1.getPacket();
long var19 = this.method30841(var14.getReason().getString());
if (var19 == 0L) {
return;
}
Ban var18 = new Ban(this.field38719.getCurrentServerData().serverIP, new Date(var19));
Account var20 = Client.getInstance().accountManager.containsAccount();
if (var20 != null) {
var20.registerBan(var18);
Client.getInstance().accountManager.updateAccount(var20);
Client.getInstance().accountManager.saveAlts();
}
}
}
}
private long method30841(String var1) {
var1 = var1.toLowerCase();
if (var1.contains("security") && var1.contains("alert")) {
return 9223372036854775806L;
} else if (!var1.contains("permanent")) {
if (!var1.contains("your account has been suspended from")) {
if (!var1.contains("tu cuenta ha sido suspendida. al reconectarte, tendr")) {
if (!var1.contains("compromised")) {
if (!var1.contains("gebannt")) {
long var4 = TimeUnit.DAYS.toMillis(this.method30842(var1));
long var6 = TimeUnit.HOURS.toMillis(this.method30843(var1));
long var8 = TimeUnit.MINUTES.toMillis(this.method30844(var1));
long var10 = TimeUnit.SECONDS.toMillis(this.method30845(var1));
if (var1.contains("§6 sentinel caught you cheating! (anticheat)") && var4 == 0L
&& var6 == 0L && var8 == 0L && var10 != 0L) {
}
return var1.contains("vous avez été banni") && var4 == 0L && var6 == 0L && var8 == 0L
&& var10 == 0L
? Long.MAX_VALUE
: System.currentTimeMillis() + var4 + var6 + var8 + var10;
} else {
return Long.MAX_VALUE;
}
} else {
return 9223372036854775806L;
}
} else {
return Long.MAX_VALUE;
}
} else {
return Long.MAX_VALUE;
}
} else {
return Long.MAX_VALUE;
}
}
private int method30842(String var1) {
String[] var4 = new String[] { "day", "jour", "tage", "día", "dia" };
for (String var8 : var4) {
Pattern var9 = Pattern
.compile("([0-9]+)(?:d| " + var8 + "s|" + var8 + "s| " + var8 + "|" + var8 + ")[ |\\n]");
Matcher var10 = var9.matcher(var1);
if (var10.find()) {
return Integer.parseInt(var10.group(1));
}
}
return 0;
}
private int method30843(String var1) {
String[] var4 = new String[] { "hour", "heure", "uhr", "hora" };
for (String var8 : var4) {
Pattern var9 = Pattern
.compile("([0-9]+)(?:h| " + var8 + "s|" + var8 + "s| " + var8 + "|" + var8 + ")[ |\\n]");
Matcher var10 = var9.matcher(var1);
if (var10.find()) {
return Integer.parseInt(var10.group(1));
}
}
return 0;
}
private int method30844(String var1) {
String[] var4 = new String[] { "minute", "min", "minuto", "mínuto" };
for (String var8 : var4) {
Pattern var9 = Pattern
.compile("([0-9]+)(?:m| " + var8 + "s|" + var8 + "s| " + var8 + "|" + var8 + ")[ |\\n]");
Matcher var10 = var9.matcher(var1);
if (var10.find()) {
return Integer.parseInt(var10.group(1));
}
}
return 0;
}
private int method30845(String var1) {
String[] var4 = new String[] { "second", "sec", "seconde", "sekunde", "segundo" };
for (String var8 : var4) {
Pattern var9 = Pattern
.compile("([0-9]+)(?:s| " + var8 + "s|" + var8 + "s| " + var8 + "|" + var8 + ")[ |\\n]");
Matcher var10 = var9.matcher(var1);
if (var10.find()) {
return Integer.parseInt(var10.group(1));
}
}
return 0;
}
}
| 412 | 0.671196 | 1 | 0.671196 | game-dev | MEDIA | 0.408858 | game-dev | 0.889221 | 1 | 0.889221 |
dreamsxin/example | 4,222 | algorithm/算法的乐趣代码/code23/tic-tac-toe/AlphaBetaSearcher.cpp | #include "StdAfx.h"
#include "AlphaBetaSearcher.h"
AlphaBetaSearcher::AlphaBetaSearcher(void)
{
srand((unsigned)time(NULL));
#ifdef _DEBUG
_searcherCounter = 0;
#endif
}
AlphaBetaSearcher::~AlphaBetaSearcher(void)
{
}
int AlphaBetaSearcher::SearchBestPlay(const GameState& state, int depth)
{
std::vector<int> bestCell;
int bestValue = -INFINITY;
int bestPos = 0;
#ifdef _DEBUG
_searcherCounter = 0;
#endif
for(int i = 0; i < BOARD_CELLS; i++)
{
GameState tryState = state;
if(tryState.IsEmptyCell(i))
{
tryState.SetGameCell(i, tryState.GetCurrentPlayer());
tryState.SwitchPlayer();
int value = AlphaBeta(tryState, depth - 1, -INFINITY, INFINITY, state.GetCurrentPlayer());
if(value > bestValue)
{
bestValue = value;
bestCell.clear();
bestCell.push_back(i);
}
else if(value == bestValue)
{
bestCell.push_back(i);
}
}
}
if(bestCell.size() > 0)
bestPos = rand() % bestCell.size();
#ifdef _DEBUG
std::cout << "MinimaxSearcher " << _searcherCounter << " (with Alpha-Beta)" << std::endl;
#endif
return bestCell[bestPos];
}
int AlphaBetaSearcher::AlphaBeta(GameState& state, int depth, int alpha, int beta, int max_player_id)
{
if(state.IsGameOver() || (depth == 0))
{
#ifdef _DEBUG
_searcherCounter++;
#endif
return state.Evaluate(max_player_id);
}
if(state.GetCurrentPlayer() == max_player_id) /*ֵڵ*/
{
for(int i = 0; i < BOARD_CELLS; i++)
{
GameState tryState = state;
if(tryState.IsEmptyCell(i))
{
tryState.SetGameCell(i, tryState.GetCurrentPlayer());
tryState.SwitchPlayer();
int value = AlphaBeta(tryState, depth - 1, alpha, beta, max_player_id);
alpha = std::max(alpha, value);
if(beta <= alpha)/*beta ֦*/
break;
}
}
return alpha;
}
else
{
for(int i = 0; i < BOARD_CELLS; i++)
{
GameState tryState = state;
if(tryState.IsEmptyCell(i))
{
tryState.SetGameCell(i, tryState.GetCurrentPlayer());
tryState.SwitchPlayer();
int value = AlphaBeta(tryState, depth - 1, alpha, beta, max_player_id);
beta = std::min(beta, value);
if(beta <= alpha)/*alpha ֦*/
break;
}
}
return beta;
}
}
#if 0
int CAlphaBetaSearcher::AlphaBeta(CGameState& state, int depth, int alpha, int beta)
{
if(state.IsGameOver() || (depth == 0))
{
#ifdef _DEBUG
_searcherCounter++;
#endif
return state.Evaluate();
}
if(state.IsComputerPlayer()) /*ֵڵ*/
{
for(int i = 0; i < BOARD_CELLS; i++)
{
CGameState tryState = state;
if(tryState.IsEmptyCell(i))
{
tryState.SetGameCell(i, tryState.GetPlayerRole());
tryState.SwitchPlayer();
int value = AlphaBeta(tryState, depth - 1, alpha, beta);
if(value > alpha)
{
alpha = value;
if(alpha >= beta) /*beta ֦*/
{
return beta;
}
}
}
}
return alpha;
}
else
{
for(int i = 0; i < BOARD_CELLS; i++)
{
CGameState tryState = state;
if(tryState.IsEmptyCell(i))
{
tryState.SetGameCell(i, tryState.GetPlayerRole());
tryState.SwitchPlayer();
int value = AlphaBeta(tryState, depth - 1, alpha, beta);
if(value < beta)
{
beta = value;
if(alpha >= beta) /*alpha ֦*/
{
return alpha;
}
}
}
}
return beta;
}
}
#endif | 412 | 0.825175 | 1 | 0.825175 | game-dev | MEDIA | 0.876063 | game-dev,testing-qa | 0.895756 | 1 | 0.895756 |
LuxCoreRender/LuxCore | 6,530 | src/slg/engines/caches/photongi/pgickdtree.cpp | /***************************************************************************
* Copyright 1998-2020 by authors (see AUTHORS.txt) *
* *
* This file is part of LuxCoreRender. *
* *
* 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. *
***************************************************************************/
#include "slg/engines/caches/photongi/photongicache.h"
using namespace std;
using namespace luxrays;
using namespace slg;
//------------------------------------------------------------------------------
// PGCIKdTree
//------------------------------------------------------------------------------
PGICKdTree::PGICKdTree(const vector<PGICVisibilityParticle> *entries) :
IndexKdTree(entries) {
}
PGICKdTree::~PGICKdTree() {
}
u_int PGICKdTree::GetNearestEntry(
const Point &p, const Normal &n, const bool isVolume,
const float radius2, const float normalCosAngle) const {
const int stackSize = 128;
u_int nodeIndexStack[stackSize];
int stackCurrentIndex = 0;
nodeIndexStack[stackCurrentIndex] = 0;
u_int nearestEntryIndex = NULL_INDEX;
float nearestMaxDistance2 = radius2;
while (stackCurrentIndex >= 0) {
// Pop the current node form the stack
const u_int currentNodeIndex = nodeIndexStack[stackCurrentIndex--];
const IndexKdTreeArrayNode &node = arrayNodes[currentNodeIndex];
const u_int axis = KdTreeNodeData_GetAxis(node.nodeData);
// Add check of the children if it is not a leaf
if (axis != 3) {
const float distance2 = Sqr(p[axis] - node.splitPos);
if (p[axis] <= node.splitPos) {
if (KdTreeNodeData_HasLeftChild(node.nodeData)) {
nodeIndexStack[++stackCurrentIndex] = currentNodeIndex + 1;
assert (stackCurrentIndex < stackSize);
assert (nodeIndexStack[stackCurrentIndex] < allEntries->size());
}
const u_int rightChildIndex = KdTreeNodeData_GetRightChild(node.nodeData);
if ((distance2 < nearestMaxDistance2) && (rightChildIndex != KdTreeNodeData_NULL_INDEX)) {
nodeIndexStack[++stackCurrentIndex] = rightChildIndex;
assert (stackCurrentIndex < stackSize);
assert (nodeIndexStack[stackCurrentIndex] < allEntries->size());
}
} else {
const u_int rightChildIndex = KdTreeNodeData_GetRightChild(node.nodeData);
if (rightChildIndex != KdTreeNodeData_NULL_INDEX) {
nodeIndexStack[++stackCurrentIndex] = rightChildIndex;
assert (stackCurrentIndex < stackSize);
assert (nodeIndexStack[stackCurrentIndex] < allEntries->size());
}
if ((distance2 < nearestMaxDistance2) && KdTreeNodeData_HasLeftChild(node.nodeData)) {
nodeIndexStack[++stackCurrentIndex] = currentNodeIndex + 1;
assert (stackCurrentIndex < stackSize);
assert (nodeIndexStack[stackCurrentIndex] < allEntries->size());
}
}
}
// Check the current node
const PGICVisibilityParticle &entry = (*allEntries)[node.index];
const float distance2 = DistanceSquared(entry.p, p);
if ((distance2 < nearestMaxDistance2) && (entry.isVolume == isVolume) &&
(isVolume || (Dot(n, entry.n) > normalCosAngle))) {
// I have found a valid entry
nearestEntryIndex = node.index;
nearestMaxDistance2 = distance2;
}
}
return nearestEntryIndex;
}
void PGICKdTree::GetAllNearEntries(vector<u_int> &allNearEntryIndices,
const Point &p, const Normal &n, const bool isVolume,
const float radius2, const float normalCosAngle) const {
const int stackSize = 128;
u_int nodeIndexStack[stackSize];
int stackCurrentIndex = 0;
nodeIndexStack[stackCurrentIndex] = 0;
while (stackCurrentIndex >= 0) {
// Pop the current node form the stack
const u_int currentNodeIndex = nodeIndexStack[stackCurrentIndex--];
const IndexKdTreeArrayNode &node = arrayNodes[currentNodeIndex];
const u_int axis = KdTreeNodeData_GetAxis(node.nodeData);
// Add check of the children if it is not a leaf
if (axis != 3) {
const float distance2 = Sqr(p[axis] - node.splitPos);
if (p[axis] <= node.splitPos) {
if (KdTreeNodeData_HasLeftChild(node.nodeData)) {
nodeIndexStack[++stackCurrentIndex] = currentNodeIndex + 1;
assert (stackCurrentIndex < stackSize);
assert (nodeIndexStack[stackCurrentIndex] < allEntries->size());
}
const u_int rightChildIndex = KdTreeNodeData_GetRightChild(node.nodeData);
if ((distance2 < radius2) && (rightChildIndex != KdTreeNodeData_NULL_INDEX)) {
nodeIndexStack[++stackCurrentIndex] = rightChildIndex;
assert (stackCurrentIndex < stackSize);
assert (nodeIndexStack[stackCurrentIndex] < allEntries->size());
}
} else {
const u_int rightChildIndex = KdTreeNodeData_GetRightChild(node.nodeData);
if (rightChildIndex != KdTreeNodeData_NULL_INDEX) {
nodeIndexStack[++stackCurrentIndex] = rightChildIndex;
assert (stackCurrentIndex < stackSize);
assert (nodeIndexStack[stackCurrentIndex] < allEntries->size());
}
if ((distance2 < radius2) && KdTreeNodeData_HasLeftChild(node.nodeData)) {
nodeIndexStack[++stackCurrentIndex] = currentNodeIndex + 1;
assert (stackCurrentIndex < stackSize);
assert (nodeIndexStack[stackCurrentIndex] < allEntries->size());
}
}
}
// Check the current node
const PGICVisibilityParticle &entry = (*allEntries)[node.index];
const float distance2 = DistanceSquared(entry.p, p);
if ((distance2 < radius2) && (entry.isVolume == isVolume) &&
(isVolume || (Dot(n, entry.n) > normalCosAngle))) {
// I have found a valid entry
allNearEntryIndices.push_back(node.index);
}
}
}
| 412 | 0.914253 | 1 | 0.914253 | game-dev | MEDIA | 0.300865 | game-dev | 0.951321 | 1 | 0.951321 |
jaquadro/StorageDrawers | 4,335 | common/src/main/java/com/jaquadro/minecraft/storagedrawers/core/recipe/UpgradeDetachedDrawerRecipe.java | package com.jaquadro.minecraft.storagedrawers.core.recipe;
import com.jaquadro.minecraft.storagedrawers.block.tile.tiledata.DetachedDrawerData;
import com.jaquadro.minecraft.storagedrawers.components.item.DetachedDrawerContents;
import com.jaquadro.minecraft.storagedrawers.config.ModCommonConfig;
import com.jaquadro.minecraft.storagedrawers.core.ModDataComponents;
import com.jaquadro.minecraft.storagedrawers.core.ModItems;
import com.jaquadro.minecraft.storagedrawers.core.ModRecipes;
import com.jaquadro.minecraft.storagedrawers.item.ItemDetachedDrawer;
import com.jaquadro.minecraft.storagedrawers.item.ItemUpgradeStorage;
import net.minecraft.core.HolderLookup;
import net.minecraft.core.component.DataComponents;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.component.CustomData;
import net.minecraft.world.item.crafting.CraftingBookCategory;
import net.minecraft.world.item.crafting.CraftingInput;
import net.minecraft.world.item.crafting.CustomRecipe;
import net.minecraft.world.item.crafting.RecipeSerializer;
import net.minecraft.world.level.Level;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
public class UpgradeDetachedDrawerRecipe extends CustomRecipe
{
public UpgradeDetachedDrawerRecipe (CraftingBookCategory cat) {
super(cat);
}
@Override
public boolean matches(@NotNull CraftingInput inv, @NotNull Level world) {
return findContext(inv) != null;
}
@Override
@NotNull
public ItemStack assemble(@NotNull CraftingInput inv, HolderLookup.Provider access) {
Context ctx = findContext(inv);
if (ctx == null)
return ItemStack.EMPTY;
ItemStack ret = ctx.drawer.copy();
CustomData cdata = ret.getOrDefault(DataComponents.CUSTOM_DATA, CustomData.EMPTY);
DetachedDrawerData data = new DetachedDrawerData(access, cdata.copyTag());
int cap = data.getStorageMultiplier();
if (ctx.upgrades.isEmpty()) {
ret = ModItems.DETACHED_DRAWER.get().getDefaultInstance();
data = new DetachedDrawerData();
data.setStorageMultiplier(cap);
} else {
int addedCap = ctx.storageMult * ModCommonConfig.INSTANCE.DRAWERS.baseStackStorage.get()
* ModCommonConfig.INSTANCE.DRAWERS.fullDrawers1x1.unitsPerSlot.get();
data.setStorageMultiplier(data.getStorageMultiplier() + addedCap);
}
// TODO: Move away from CUSTOM_DATA
ret.set(DataComponents.CUSTOM_DATA, CustomData.of(data.serializeNBT(access)));
ItemStack savedItem = data.getStoredItemPrototype().copyWithCount(data.getStoredItemCount());
DetachedDrawerContents contents = new DetachedDrawerContents(savedItem, cap, data.isHeavy());
ret.set(ModDataComponents.DETACHED_DRAWER_CONTENTS.get(), contents);
return ret;
}
private static class Context {
ItemStack drawer = ItemStack.EMPTY;
List<ItemStack> upgrades = new ArrayList<>();
int storageMult = 0;
}
@Nullable
private Context findContext(CraftingInput inv) {
Context ret = new Context();
for (int x = 0; x < inv.size(); x++) {
ItemStack stack = inv.getItem(x);
if (stack.isEmpty())
continue;
if (stack.getItem() instanceof ItemDetachedDrawer) {
if (!ret.drawer.isEmpty())
return null;
ret.drawer = stack;
} else if (stack.getItem() instanceof ItemUpgradeStorage)
ret.upgrades.add(stack);
else
return null;
}
if (ret.drawer.isEmpty())
return null;
for (ItemStack upgrade : ret.upgrades) {
if (upgrade.getItem() instanceof ItemUpgradeStorage storageUpgrade)
ret.storageMult += ModCommonConfig.INSTANCE.UPGRADES.getLevelMult(storageUpgrade.level.getLevel());
}
return ret;
}
@Override
public boolean canCraftInDimensions(int width, int height) {
return width * height >= 2;
}
@Override
@NotNull
public RecipeSerializer<?> getSerializer() {
return ModRecipes.DETACHED_UPGRADE_RECIPE_SERIALIZER.get();
}
}
| 412 | 0.906137 | 1 | 0.906137 | game-dev | MEDIA | 0.999402 | game-dev | 0.957325 | 1 | 0.957325 |
blendogames/SkinDeep | 4,999 | tools/af/DialogAFConstraintBallAndSocket.h | /*
===========================================================================
Doom 3 GPL Source Code
Copyright (C) 1999-2011 id Software LLC, a ZeniMax Media company.
This file is part of the Doom 3 GPL Source Code ("Doom 3 Source Code").
Doom 3 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 3 of the License, or
(at your option) any later version.
Doom 3 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 Doom 3 Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the Doom 3 Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 Source Code. If not, please request a copy in writing from id Software at the address below.
If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
===========================================================================
*/
#pragma once
// DialogAFConstraintBallAndSocket dialog
class DialogAFConstraintBallAndSocket : public CDialog {
DECLARE_DYNAMIC(DialogAFConstraintBallAndSocket)
public:
DialogAFConstraintBallAndSocket(CWnd* pParent = NULL); // standard constructor
virtual ~DialogAFConstraintBallAndSocket();
void LoadFile( idDeclAF *af );
void SaveFile( void );
void LoadConstraint( idDeclAF_Constraint *c );
void SaveConstraint( void );
void UpdateFile( void );
enum { IDD = IDD_DIALOG_AF_CONSTRAINT_BALLANDSOCKET };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
virtual int OnToolHitTest( CPoint point, TOOLINFO* pTI ) const;
afx_msg BOOL OnToolTipNotify( UINT id, NMHDR *pNMHDR, LRESULT *pResult );
afx_msg void OnBnClickedRadioAnchorJoint();
afx_msg void OnBnClickedRadioAnchorCoordinates();
afx_msg void OnCbnSelchangeComboAnchorJoint();
afx_msg void OnEnChangeEditAnchorX();
afx_msg void OnEnChangeEditAnchorY();
afx_msg void OnEnChangeEditAnchorZ();
afx_msg void OnDeltaposSpinAnchorX(NMHDR *pNMHDR, LRESULT *pResult);
afx_msg void OnDeltaposSpinAnchorY(NMHDR *pNMHDR, LRESULT *pResult);
afx_msg void OnDeltaposSpinAnchorZ(NMHDR *pNMHDR, LRESULT *pResult);
afx_msg void OnBnClickedRadioBasLimitNone();
afx_msg void OnBnClickedRadioBasLimitCone();
afx_msg void OnBnClickedRadioBasLimitPyramid();
afx_msg void OnEnChangeEditBasLimitConeAngle();
afx_msg void OnDeltaposSpinBasLimitConeAngle(NMHDR *pNMHDR, LRESULT *pResult);
afx_msg void OnEnChangeEditBasLimitPyramidAngle1();
afx_msg void OnDeltaposSpinBasLimitPyramidAngle1(NMHDR *pNMHDR, LRESULT *pResult);
afx_msg void OnEnChangeEditBasLimitPyramidAngle2();
afx_msg void OnDeltaposSpinBasLimitPyramidAngle2(NMHDR *pNMHDR, LRESULT *pResult);
afx_msg void OnEnChangeEditBasLimitRoll();
afx_msg void OnDeltaposSpinBasLimitRoll(NMHDR *pNMHDR, LRESULT *pResult);
afx_msg void OnBnClickedRadioBasLimitBone();
afx_msg void OnBnClickedRadioBasLimitAngles();
afx_msg void OnCbnSelchangeComboBasLimitJoint1();
afx_msg void OnCbnSelchangeComboBasLimitJoint2();
afx_msg void OnEnChangeEditBasLimitPitch();
afx_msg void OnDeltaposSpinBasLimitPitch(NMHDR *pNMHDR, LRESULT *pResult);
afx_msg void OnEnChangeEditBasLimitYaw();
afx_msg void OnDeltaposSpinBasLimitYaw(NMHDR *pNMHDR, LRESULT *pResult);
afx_msg void OnBnClickedRadioBasLimitAxisBone();
afx_msg void OnBnClickedRadioBasLimitAxisAngles();
afx_msg void OnCbnSelchangeComboBasLimitAxisJoint1();
afx_msg void OnCbnSelchangeComboBasLimitAxisJoint2();
afx_msg void OnEnChangeEditBasLimitAxisPitch();
afx_msg void OnDeltaposSpinBasLimitAxisPitch(NMHDR *pNMHDR, LRESULT *pResult);
afx_msg void OnEnChangeEditBasLimitAxisYaw();
afx_msg void OnDeltaposSpinBasLimitAxisYaw(NMHDR *pNMHDR, LRESULT *pResult);
DECLARE_MESSAGE_MAP()
private:
idDeclAF * file;
idDeclAF_Constraint*constraint;
//{{AFX_DATA(DialogAFConstraintBallAndSocket)
CComboBox m_comboAnchorJoint;
float m_anchor_x;
float m_anchor_y;
float m_anchor_z;
float m_coneAngle;
float m_pyramidAngle1;
float m_pyramidAngle2;
CComboBox m_comboLimitJoint1;
CComboBox m_comboLimitJoint2;
float m_limitPitch;
float m_limitYaw;
float m_limitRoll;
CComboBox m_comboLimitAxisJoint1;
CComboBox m_comboLimitAxisJoint2;
float m_limitAxisPitch;
float m_limitAxisYaw;
//}}AFX_DATA
static toolTip_t toolTips[];
private:
void InitJointLists( void );
};
| 412 | 0.713019 | 1 | 0.713019 | game-dev | MEDIA | 0.574038 | game-dev | 0.670754 | 1 | 0.670754 |
gawric/Unity-Client-for-L2J | 10,193 | l2-unity/Assets/Scripts/Networking/ClientLibrary/PacketInterlude/GameServer/ServerServer/World/Character/UserInfo.cs | using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.TextCore.Text;
using UnityEngine.UIElements;
using static StorageVariable;
using static UnityEditor.Experimental.GraphView.GraphView;
using static UnityEditor.Progress;
public class UserInfo : ServerPacket
{
private PlayerInfoInterlude _info;
public PlayerInfoInterlude PlayerInfoInterlude { get { return _info; } }
public UserInfo(byte[] d , PlayerInfoInterlude info) : base(d)
{
this._info = info;
Parse();
}
public override void Parse()
{
int x = ReadI();
int y = ReadI();
int z = ReadI();
//Vector3 unityPos = VectorUtils.ConvertPosToUnity(new Vector3(x,y,z));
_info.Identity.SetL2jPos(x, y, z);
_info.Identity.Heading = VectorUtils.ConvertHeadingL2jToUnity(ReadI());
_info.Identity.Id = ReadI();
_info.Identity.Name = ReadOtherS();
int reace = ReadI();
int female = ReadI();
_info.Appearance.Sex = female;
_info.Appearance.Race = (int)MapClassId.GetRace(reace);
//int baseClass = ReadI();
_info.Appearance.BaseClass = ReadI();
_info.Stats.Level = ReadI();
long exp = ReadOtherL();
int ost = (int)exp - (int)_info.Stats.Exp;
if (ost > 0) StorageVariable.getInstance().AddS1Items(new VariableItem(ost.ToString(), _info.Identity.Id));
_info.Stats.Exp = exp;
_info.Stats.MaxExp = LevelServer.GetExp(_info.Stats.Level + 1);
_info.Stats.Str = ReadI();
_info.Stats.Dex = ReadI();
_info.Stats.Con = ReadI();
_info.Stats.Int = ReadI();
_info.Stats.Wit = ReadI();
_info.Stats.Men = ReadI();
_info.Stats.MaxHp = ReadI();
_info.Status.SetHp(ReadI());
_info.Stats.MaxMp = ReadI();
_info.Status.SetMp(ReadI());
int sp = ReadI();
int oldSp = (int)_info.Stats.OldSp;
int ostSp = (int)sp - oldSp;
StorageVariable.getInstance().AddS2Items(new VariableItem(ostSp.ToString(), _info.Identity.Id));
_info.Stats.OldSp = sp;
_info.Stats.Sp = sp;
_info.Stats.CurrWeight = ReadI();
_info.Stats.MaxWeight = ReadI(); //the max weight that the Creature can load.
int activeWeaponItem = ReadI(); // 20 no weapon, 40 weapon equipped
/**
* Returns the objectID associated to the item in the paperdoll slot
* @param slot : int pointing out the slot
* @return int designating the objectID
*/
var paperTest = _info.Appearance.PaperDoll;
_info.Appearance.PaperDoll.Obj_Under = ReadI();
_info.Appearance.PaperDoll.Obj_Pear = ReadI();
_info.Appearance.PaperDoll.Obj_Lear = ReadI();
_info.Appearance.PaperDoll.Obj_Neck = ReadI();
_info.Appearance.PaperDoll.Obj_RFinger = ReadI();
_info.Appearance.PaperDoll.Obj_LFinger = ReadI();
_info.Appearance.PaperDoll.Obj_Head = ReadI();
_info.Appearance.PaperDoll.Obj_RHand = ReadI();
_info.Appearance.PaperDoll.Obj_LHand = ReadI();
_info.Appearance.PaperDoll.Obj_Gloves = ReadI();
_info.Appearance.PaperDoll.Obj_Chest = ReadI();
_info.Appearance.PaperDoll.Obj_Legs = ReadI();
_info.Appearance.PaperDoll.Obj_Feet = ReadI();
_info.Appearance.PaperDoll.Obj_Cloak = ReadI();
_info.Appearance.PaperDoll.Obj_RHand = ReadI();
_info.Appearance.PaperDoll.Obj_Hair = ReadI();
_info.Appearance.PaperDoll.Obj_Face = ReadI();
/**
* Returns the ID of the item in the paperdoll slot
* @param slot : int designating the slot
* @return int designating the ID of the item
*/
_info.Appearance.PaperDoll.Item_Under = ReadI();
_info.Appearance.PaperDoll.Item_Rear = ReadI();
_info.Appearance.PaperDoll.Item_Lear = ReadI();
_info.Appearance.PaperDoll.Item_Neck = ReadI();
_info.Appearance.PaperDoll.Item_RFinger = ReadI();
_info.Appearance.PaperDoll.Item_LFinger = ReadI();
_info.Appearance.PaperDoll.Item_Head = ReadI();
_info.Appearance.PaperDoll.Item_RHand = ReadI();
_info.Appearance.PaperDoll.Item_LHand = ReadI();
_info.Appearance.PaperDoll.Item_Gloves = ReadI();
_info.Appearance.Gloves = _info.Appearance.PaperDoll.Item_Gloves;
_info.Appearance.PaperDoll.Item_Chest = ReadI();
_info.Appearance.Chest = _info.Appearance.PaperDoll.Item_Chest;
_info.Appearance.PaperDoll.Item_Legs = ReadI();
_info.Appearance.Legs = _info.Appearance.PaperDoll.Item_Legs;
_info.Appearance.PaperDoll.Item_Feet = ReadI();
_info.Appearance.Feet = _info.Appearance.PaperDoll.Item_Feet;
_info.Appearance.PaperDoll.Item_Cloak = ReadI();
_info.Appearance.PaperDoll.Item_RHand = ReadI();
_info.Appearance.PaperDoll.Item_Hair = ReadI();
_info.Appearance.PaperDoll.Item_Face = ReadI();
_info.Appearance.RHand = _info.Appearance.PaperDoll.Item_RHand;
ReadSh();
ReadSh();
ReadSh();
ReadSh();
ReadSh();
ReadSh();
ReadSh();
ReadSh();
ReadSh();
ReadSh();
ReadSh();
ReadSh();
ReadSh();
ReadSh();
//buffer.writeInt(_player.getInventory().getPaperdollAugmentationId(Inventory.PAPERDOLL_RHAND));
int rhandAugmentationId = ReadI();
ReadSh();
ReadSh();
ReadSh();
ReadSh();
ReadSh();
ReadSh();
ReadSh();
ReadSh();
ReadSh();
ReadSh();
ReadSh();
ReadSh();
// buffer.writeInt(_player.getInventory().getPaperdollAugmentationId(Inventory.PAPERDOLL_RHAND));
int rhandAugmentationId2 = ReadI();
ReadSh();
ReadSh();
ReadSh();
ReadSh();
_info.Stats.PAtk = ReadI();
int atackspped = ReadI();
_info.Stats.BasePAtkSpeed = atackspped;
//_info.Stats.PAtkSpd = atackspped;
// Debug.Log("PAAAAAAAAAAAATACK SPEED " + atackspped);
_info.Stats.PAtkSpd = atackspped;
_info.Stats.PDef = ReadI();
_info.Stats.PEvasion = ReadI();
// int accuracy = ReadI();
_info.Stats.MAccuracy = ReadI();
int criticalHit = ReadI();
_info.Stats.MAtk = ReadI();
_info.Stats.MAtkSpd = ReadI();
int pAttackSpd2 = ReadI();
_info.Stats.MDef = ReadI();
int pvpFlag = ReadI();
_info.Stats.Karma = ReadI();
int runSpeed = ReadI();
_info.Stats.Speed = runSpeed;
//_info.Stats.WalkingSpeed = ReadI();
_info.Stats.BaseWalkingSpeed = ReadI();
_info.Stats.BaseRunSpeed = runSpeed;
int swimRunSpd = ReadI();
int swimWalkSpd = ReadI();
int flyRunSpd = ReadI();
int flyWalkSpd = ReadI();
int flyRunSpd2 = ReadI();
int flyWalkSpd2 = ReadI();
double moveMultiplier = ReadD();
double attackSpeedMultiplier = ReadD();
_info.Stats.WalkRealSpeed = GetRealSpeed(_info.Stats.BaseWalkingSpeed, (float) moveMultiplier);
_info.Stats.RunRealSpeed = GetRealSpeed(_info.Stats.BaseRunSpeed, (float)moveMultiplier);
_info.Stats.PAtkRealSpeed = GetRealSpeed(_info.Stats.PAtkSpd, (float)attackSpeedMultiplier);
Debug.Log("BasePatakSpeed R " + _info.Stats.PAtkRealSpeed);
Debug.Log("BasePatakSpeed B" + _info.Stats.BasePAtkSpeed);
Debug.Log("BasePatakSpeed Spd" + attackSpeedMultiplier);
_info.Appearance.CollisionRadius = (float)ReadD();
// _info.Appearance.CollisionHeight = (float)ReadD();
float collision = (float)ReadD();
_info.Appearance.CollisionHeight = collision;
int hairStyle = ReadI();
int hairColor = ReadI();
int face = ReadI();
int isGm = ReadI();
_info.Identity.Title = ReadOtherS();
//_info.Identity.Title = "My title";
_info.Identity.ClanId = ReadI();
int clanCrestId = ReadI();
int allyId = ReadI();
int allyCrestId = ReadI();
// 0x40 leader rights
// siege flags: attacker - 0x180 sword over name, defender - 0x80 shield, 0xC0 crown (|leader), 0x1C0 flag (|leader)
int relation = ReadI();
byte mountType = ReadB();
byte privateStoreType = ReadB();
byte hasDwarvenCraft = ReadB();
_info.Stats.PkKills = ReadI();
_info.Stats.PvpKills = ReadI();
int cubics_size = ReadSh();
for(int i=0; i < cubics_size; i++)
{
ReadSh();
}
byte isInPartyMatchRoom = ReadB();
int isInvisible = ReadI();
byte isInsideZone = ReadB();
int clanPrivileges = ReadI();
int recomLeft = ReadSh();
int recomHave = ReadSh();
int mountNpcId = ReadI();
int inventoryLimit = ReadSh();
int class_id = ReadI();
int unknow = ReadI();//// special effects? circles around player...
_info.Stats.MaxCp = ReadI();
int cp = ReadI();
_info.Status.Cp = cp;
byte enchantEffect = ReadB();
byte teamId = ReadB();
int clanCrestLargeId = ReadI();
byte isNoble = ReadB();
byte isHero = ReadB();
byte isFishing = ReadB();
int fishingX = ReadI();
int fishingY = ReadI();
int fishingZ = ReadI();
int colorName = ReadI();
byte isRunning = ReadB();// changes the Speed display on Status Window
_info.Appearance.Running = isRunning == 1;
int pledgeClass = ReadI();
int PledgeType = ReadI();
int titleColor = ReadI();
int isCursedWeaponEquipped = ReadI();
StorageVariable.getInstance().ResumeShowDelayMessage((int)MessageID.ADD_EXP_SP);
Debug.Log("USERRRR INFO !!!! ");
}
private float GetRealSpeed(int baseSpeed , float speedMultiplier)
{
return baseSpeed * speedMultiplier;
}
private float GetRealSpeed(double baseSpeed, float speedMultiplier)
{
return (float)baseSpeed * speedMultiplier;
}
}
| 412 | 0.722706 | 1 | 0.722706 | game-dev | MEDIA | 0.51575 | game-dev | 0.776059 | 1 | 0.776059 |
Unity-Technologies/giles | 4,623 | Assets/GILES/Code/Classes/GUI/pb_GUIUtility.cs | using UnityEngine;
using UnityEngine.UI;
namespace GILES.Interface
{
/**
* Static helper functions for common GUI operations.
*/
public static class pb_GUIUtility
{
/// The default color to use as the background for panels.
public static readonly Color PANEL_COLOR = new Color(.27f, .27f, .27f, .5f);
/// The default color to use as the background for items in panels.
public static readonly Color ITEM_BACKGROUND_COLOR = new Color(.15f, .15f, .15f, 1f);
/// The default padding for UI elements.
public const int PADDING = 4;
/// Default padding for panel UI elements.
/// \sa PADDING
public static readonly RectOffset PADDING_RECT_OFFSET = new RectOffset(PADDING, PADDING, PADDING, PADDING);
/// Cache of default font.
/// \sa DefaultFont()
private static Font _defaultFont;
/**
* Replacement for UnityEngine.GUIUtility.ScreenToGUIPoint() which seems not to work.
*/
public static Vector2 ScreenToGUIPoint(Vector2 v)
{
v.y = Screen.height - v.y;
return v;
}
/**
* Get default font.
*/
public static Font DefaultFont()
{
if(_defaultFont == null)
_defaultFont = (Font) Resources.GetBuiltinResource(typeof(Font), "Arial.ttf");
return _defaultFont;
}
/**
* Get a named font from the `Resources/Required/Font` folder.
*/
public static Font GetFont(string fontName)
{
return Resources.Load<Font>("Required/Font/" + fontName);
}
/**
* Returns a new gameObject a vertical layoutgroup and text component child.
*/
public static GameObject CreateLabeledVerticalPanel(string label)
{
GameObject go = new GameObject();
go.name = label;
go.AddComponent<Image>().color = PANEL_COLOR;
AddVerticalLayoutGroup(go);
CreateLabel( label ).transform.SetParent(go.transform);
return go;
}
/**
* Create a new gameObject with a `HorizontalLayoutGroup` and default settings.
*/
public static GameObject CreateHorizontalGroup()
{
GameObject go = new GameObject();
HorizontalLayoutGroup group = go.AddComponent<HorizontalLayoutGroup>();
group.padding = new RectOffset(2,2,2,2);
group.childForceExpandWidth = true;
group.childForceExpandHeight = false;
return go;
}
/**
* Create a new GameObject with `text` and a default font.
*/
public static GameObject CreateLabel(string text)
{
GameObject go = new GameObject();
go.name = "Label Field";
Text field = go.AddComponent<Text>();
string temp = text.Replace("UnityEngine.","");
field.text = temp; //This removes the UnityEngine. Prefix from the Inspector.
//field.text = text;
field.font = pb_GUIUtility.DefaultFont();
go.AddComponent<LayoutElement>().minHeight = 24;
field.alignment = TextAnchor.MiddleLeft;
return go;
}
/**
* Add a `VerticalLayoutGroup` component to `go`, using the default parameters.
*/
public static void AddVerticalLayoutGroup(GameObject go)
{
AddVerticalLayoutGroup(
go,
pb_GUIUtility.PADDING_RECT_OFFSET,
pb_GUIUtility.PADDING,
true,
false);
}
/**
* Add a `VerticalLayoutGroup` component to `go`, using the specified parameters.
*/
public static void AddVerticalLayoutGroup(GameObject go, RectOffset padding, int spacing, bool childForceExpandWidth, bool childForceExpandHeight)
{
VerticalLayoutGroup group = go.AddComponent<VerticalLayoutGroup>();
group.padding = padding;
group.spacing = spacing;
group.childForceExpandWidth = childForceExpandWidth;
group.childForceExpandHeight = childForceExpandHeight;
}
/**
* Get the next selectable to the right, or if null, the next selectable down and left-most.
*/
public static Selectable GetNextSelectable(Selectable current)
{
if(current == null)
return null;
Selectable next = current.FindSelectableOnRight();
if(next != null)
{
return next;
}
else
{
next = current.FindSelectableOnDown();
if(next == null)
return null;
Selectable left = next;
while(next != null)
{
left = left.FindSelectableOnLeft();
if(left == null)
return next;
next = left;
}
}
return null;
}
/**
* Return a rect in screen coordinates.
*/
public static Rect GetScreenRect(this RectTransform rectTransform)
{
Vector3[] world = new Vector3[4];
rectTransform.GetWorldCorners(world);
Vector2 min = Vector3.Min(Vector3.Min(Vector3.Min(world[0], world[1]), world[2]), world[3]);
Vector2 max = Vector3.Max(Vector3.Max(Vector3.Max(world[0], world[1]), world[2]), world[3]);
return new Rect(min.x, max.y, max.x - min.x, max.y - min.y);
}
}
}
| 412 | 0.890892 | 1 | 0.890892 | game-dev | MEDIA | 0.938232 | game-dev | 0.992634 | 1 | 0.992634 |
ImLegiitXD/Dream-Advanced | 8,946 | dll/back/1.20/net/minecraft/commands/arguments/MessageArgument.java | package net.minecraft.commands.arguments;
import com.google.common.collect.Lists;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
import javax.annotation.Nullable;
import net.minecraft.commands.CommandSigningContext;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.arguments.selector.EntitySelector;
import net.minecraft.commands.arguments.selector.EntitySelectorParser;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.MutableComponent;
import net.minecraft.network.chat.PlayerChatMessage;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.network.FilteredText;
public class MessageArgument implements SignedArgument<MessageArgument.Message> {
private static final Collection<String> EXAMPLES = Arrays.asList("Hello world!", "foo", "@e", "Hello @p :)");
public static MessageArgument message() {
return new MessageArgument();
}
public static Component getMessage(CommandContext<CommandSourceStack> p_96836_, String p_96837_) throws CommandSyntaxException {
MessageArgument.Message messageargument$message = p_96836_.getArgument(p_96837_, MessageArgument.Message.class);
return messageargument$message.resolveComponent(p_96836_.getSource());
}
public static void resolveChatMessage(CommandContext<CommandSourceStack> p_249433_, String p_248718_, Consumer<PlayerChatMessage> p_249460_) throws CommandSyntaxException {
MessageArgument.Message messageargument$message = p_249433_.getArgument(p_248718_, MessageArgument.Message.class);
CommandSourceStack commandsourcestack = p_249433_.getSource();
Component component = messageargument$message.resolveComponent(commandsourcestack);
CommandSigningContext commandsigningcontext = commandsourcestack.getSigningContext();
PlayerChatMessage playerchatmessage = commandsigningcontext.getArgument(p_248718_);
if (playerchatmessage != null) {
resolveSignedMessage(p_249460_, commandsourcestack, playerchatmessage.withUnsignedContent(component));
} else {
resolveDisguisedMessage(p_249460_, commandsourcestack, PlayerChatMessage.system(messageargument$message.text).withUnsignedContent(component));
}
}
private static void resolveSignedMessage(Consumer<PlayerChatMessage> p_250000_, CommandSourceStack p_252335_, PlayerChatMessage p_249420_) {
MinecraftServer minecraftserver = p_252335_.getServer();
CompletableFuture<FilteredText> completablefuture = filterPlainText(p_252335_, p_249420_);
CompletableFuture<Component> completablefuture1 = minecraftserver.getChatDecorator().decorate(p_252335_.getPlayer(), p_249420_.decoratedContent());
p_252335_.getChatMessageChainer().append((p_247979_) -> {
return CompletableFuture.allOf(completablefuture, completablefuture1).thenAcceptAsync((p_247970_) -> {
PlayerChatMessage playerchatmessage = p_249420_.withUnsignedContent(completablefuture1.join()).filter(completablefuture.join().mask());
p_250000_.accept(playerchatmessage);
}, p_247979_);
});
}
private static void resolveDisguisedMessage(Consumer<PlayerChatMessage> p_249162_, CommandSourceStack p_248759_, PlayerChatMessage p_252332_) {
MinecraftServer minecraftserver = p_248759_.getServer();
CompletableFuture<Component> completablefuture = minecraftserver.getChatDecorator().decorate(p_248759_.getPlayer(), p_252332_.decoratedContent());
p_248759_.getChatMessageChainer().append((p_247974_) -> {
return completablefuture.thenAcceptAsync((p_247965_) -> {
p_249162_.accept(p_252332_.withUnsignedContent(p_247965_));
}, p_247974_);
});
}
private static CompletableFuture<FilteredText> filterPlainText(CommandSourceStack p_252063_, PlayerChatMessage p_251184_) {
ServerPlayer serverplayer = p_252063_.getPlayer();
return serverplayer != null && p_251184_.hasSignatureFrom(serverplayer.getUUID()) ? serverplayer.getTextFilter().processStreamMessage(p_251184_.signedContent()) : CompletableFuture.completedFuture(FilteredText.passThrough(p_251184_.signedContent()));
}
public MessageArgument.Message parse(StringReader p_96834_) throws CommandSyntaxException {
return MessageArgument.Message.parseText(p_96834_, true);
}
public Collection<String> getExamples() {
return EXAMPLES;
}
public static class Message {
final String text;
private final MessageArgument.Part[] parts;
public Message(String p_96844_, MessageArgument.Part[] p_96845_) {
this.text = p_96844_;
this.parts = p_96845_;
}
public String getText() {
return this.text;
}
public MessageArgument.Part[] getParts() {
return this.parts;
}
Component resolveComponent(CommandSourceStack p_232197_) throws CommandSyntaxException {
return this.toComponent(p_232197_, p_232197_.hasPermission(2));
}
public Component toComponent(CommandSourceStack p_96850_, boolean p_96851_) throws CommandSyntaxException {
if (this.parts.length != 0 && p_96851_) {
MutableComponent mutablecomponent = Component.literal(this.text.substring(0, this.parts[0].getStart()));
int i = this.parts[0].getStart();
for(MessageArgument.Part messageargument$part : this.parts) {
Component component = messageargument$part.toComponent(p_96850_);
if (i < messageargument$part.getStart()) {
mutablecomponent.append(this.text.substring(i, messageargument$part.getStart()));
}
if (component != null) {
mutablecomponent.append(component);
}
i = messageargument$part.getEnd();
}
if (i < this.text.length()) {
mutablecomponent.append(this.text.substring(i));
}
return mutablecomponent;
} else {
return Component.literal(this.text);
}
}
public static MessageArgument.Message parseText(StringReader p_96847_, boolean p_96848_) throws CommandSyntaxException {
String s = p_96847_.getString().substring(p_96847_.getCursor(), p_96847_.getTotalLength());
if (!p_96848_) {
p_96847_.setCursor(p_96847_.getTotalLength());
return new MessageArgument.Message(s, new MessageArgument.Part[0]);
} else {
List<MessageArgument.Part> list = Lists.newArrayList();
int i = p_96847_.getCursor();
while(true) {
int j;
EntitySelector entityselector;
while(true) {
if (!p_96847_.canRead()) {
return new MessageArgument.Message(s, list.toArray(new MessageArgument.Part[0]));
}
if (p_96847_.peek() == '@') {
j = p_96847_.getCursor();
try {
EntitySelectorParser entityselectorparser = new EntitySelectorParser(p_96847_);
entityselector = entityselectorparser.parse();
break;
} catch (CommandSyntaxException commandsyntaxexception) {
if (commandsyntaxexception.getType() != EntitySelectorParser.ERROR_MISSING_SELECTOR_TYPE && commandsyntaxexception.getType() != EntitySelectorParser.ERROR_UNKNOWN_SELECTOR_TYPE) {
throw commandsyntaxexception;
}
p_96847_.setCursor(j + 1);
}
} else {
p_96847_.skip();
}
}
list.add(new MessageArgument.Part(j - i, p_96847_.getCursor() - i, entityselector));
}
}
}
}
public static class Part {
private final int start;
private final int end;
private final EntitySelector selector;
public Part(int p_96856_, int p_96857_, EntitySelector p_96858_) {
this.start = p_96856_;
this.end = p_96857_;
this.selector = p_96858_;
}
public int getStart() {
return this.start;
}
public int getEnd() {
return this.end;
}
public EntitySelector getSelector() {
return this.selector;
}
@Nullable
public Component toComponent(CommandSourceStack p_96861_) throws CommandSyntaxException {
return EntitySelector.joinNames(this.selector.findEntities(p_96861_));
}
}
} | 412 | 0.78549 | 1 | 0.78549 | game-dev | MEDIA | 0.791593 | game-dev,networking | 0.906232 | 1 | 0.906232 |
mfoltz/Bloodcraft | 15,922 | Patches/FamiliarServantPatches.cs | using Bloodcraft.Services;
using Bloodcraft.Utilities;
using HarmonyLib;
using ProjectM;
using ProjectM.Network;
using ProjectM.Scripting;
using Unity.Collections;
using Unity.Entities;
namespace Bloodcraft.Patches;
[HarmonyPatch]
internal static class FamiliarServantPatches
{
static EntityManager EntityManager => Core.EntityManager;
static ServerGameManager ServerGameManager => Core.ServerGameManager;
static SystemService SystemService => Core.SystemService;
static NetworkIdSystem.Singleton NetworkIdSystem => SystemService.NetworkIdSystem;
static readonly bool _familiars = ConfigService.FamiliarSystem;
[HarmonyPatch(typeof(EquipServantItemFromInventorySystem), nameof(EquipServantItemFromInventorySystem.OnUpdate))]
[HarmonyPrefix]
public static void OnUpdatePrefix(EquipServantItemFromInventorySystem __instance)
{
if (!Core.IsReady) return;
else if (!_familiars) return;
NativeArray<Entity> entities = __instance.EntityQueries[0].ToEntityArray(Allocator.Temp);
NativeArray<EquipServantItemFromInventoryEvent> equipServantItemFromInventoryEvents = __instance.EntityQueries[0].ToComponentDataArray<EquipServantItemFromInventoryEvent>(Allocator.Temp);
ComponentLookup<BlockFeedBuff> blockFeedBuffLookup = __instance.GetComponentLookup<BlockFeedBuff>();
try
{
var networkIdLookupMap = NetworkIdSystem._NetworkIdLookupMap;
for (int i = 0; i < entities.Length; i++)
{
Entity entity = entities[i];
EquipServantItemFromInventoryEvent equipServantItemFromInventoryEvent = equipServantItemFromInventoryEvents[i];
NetworkId toEntity = equipServantItemFromInventoryEvent.ToEntity;
NetworkId fromInventory = equipServantItemFromInventoryEvent.FromInventory;
int slotIndex = equipServantItemFromInventoryEvent.SlotIndex;
if (networkIdLookupMap.TryGetValue(toEntity, out Entity servant)
&& blockFeedBuffLookup.HasComponent(servant)
&& networkIdLookupMap.TryGetValue(fromInventory, out Entity inventory))
{
if (InvalidFamiliarEquipment(inventory, slotIndex))
{
Core.Log.LogWarning($"[EquipServantItemFromInventorySystem] isLegendary!");
entity.Destroy(true);
}
else
{
Entity familiar = Familiars.GetServantFamiliar(servant);
if (familiar.Exists())
{
// Core.Log.LogWarning($"[EquipServantItemFromInventorySystem] Familiar servant equipped from inventory, refreshing stats...");
Buffs.RefreshStats(familiar);
}
}
}
}
}
finally
{
entities.Dispose();
equipServantItemFromInventoryEvents.Dispose();
}
}
static bool InvalidFamiliarEquipment(Entity inventory, int slotIndex)
{
if (InventoryUtilities.TryGetItemAtSlot(EntityManager, inventory, slotIndex, out InventoryBuffer item))
{
// bool result = item.ItemType.GetPrefabName().Contains(LEGENDARY);
// return item.ItemType.GetPrefabName().Contains(LEGENDARY) || item.ItemEntity.GetEntityOnServer().IsAncestralWeapon();
return item.ItemEntity.GetEntityOnServer().IsAncestralWeapon();
}
return false;
}
[HarmonyPatch(typeof(EquipServantItemSystem), nameof(EquipServantItemSystem.OnUpdate))]
[HarmonyPrefix]
public static void OnUpdatePrefix(EquipServantItemSystem __instance)
{
if (!Core.IsReady) return;
else if (!_familiars) return;
NativeArray<Entity> entities = __instance.EntityQueries[0].ToEntityArray(Allocator.Temp);
NativeArray<EquipServantItemEvent> equipServantItemEvents = __instance.EntityQueries[0].ToComponentDataArray<EquipServantItemEvent>(Allocator.Temp);
NativeArray<FromCharacter> fromCharacters = __instance.EntityQueries[0].ToComponentDataArray<FromCharacter>(Allocator.Temp);
ComponentLookup<BlockFeedBuff> blockFeedBuffLookup = __instance.GetComponentLookup<BlockFeedBuff>();
try
{
var networkIdLookupMap = NetworkIdSystem._NetworkIdLookupMap;
for (int i = 0; i < entities.Length; i++)
{
Entity entity = entities[i];
EquipServantItemEvent equipServantItemEvent = equipServantItemEvents[i];
FromCharacter fromCharacter = fromCharacters[i];
NetworkId networkId = equipServantItemEvent.ToEntity;
int slotIndex = equipServantItemEvent.SlotIndex;
if (NetworkIdSystem._NetworkIdLookupMap.TryGetValue(networkId, out Entity servant)
&& blockFeedBuffLookup.HasComponent(servant)
&& InventoryUtilities.TryGetInventoryEntity(EntityManager, fromCharacter.Character, out Entity inventory))
{
if (InvalidFamiliarEquipment(inventory, slotIndex))
{
Core.Log.LogWarning($"[EquipServantItemSystem] isLegendary!");
entity.Destroy(true);
}
else
{
Entity familiar = Familiars.GetServantFamiliar(servant);
if (familiar.Exists())
{
// Core.Log.LogWarning($"[EquipServantItemFromInventorySystem] Familiar servant equipped from inventory, refreshing stats...");
Buffs.RefreshStats(familiar);
}
}
}
}
}
finally
{
entities.Dispose();
equipServantItemEvents.Dispose();
fromCharacters.Dispose();
}
}
[HarmonyPatch(typeof(UnEquipServantItemSystem), nameof(UnEquipServantItemSystem.OnUpdate))]
[HarmonyPrefix]
public static void OnUpdatePrefix(UnEquipServantItemSystem __instance)
{
if (!Core.IsReady) return;
else if (!_familiars) return;
NativeArray<UnequipServantItemEvent> unequipServantItemEvents = __instance.EntityQueries[0].ToComponentDataArray<UnequipServantItemEvent>(Allocator.Temp);
ComponentLookup<BlockFeedBuff> blockFeedBuffLookup = __instance.GetComponentLookup<BlockFeedBuff>();
try
{
for (int i = 0; i < unequipServantItemEvents.Length; i++)
{
UnequipServantItemEvent unequipServantItemEvent = unequipServantItemEvents[i];
NetworkId networkId = unequipServantItemEvent.FromEntity;
if (NetworkIdSystem._NetworkIdLookupMap.TryGetValue(networkId, out Entity servant)
&& blockFeedBuffLookup.HasComponent(servant))
{
Entity familiar = Familiars.GetServantFamiliar(servant);
if (familiar.Exists())
{
// Core.Log.LogWarning($"[UnEquipServantItemSystem] Familiar servant unequipped, refreshing stats...");
Buffs.RefreshStats(familiar);
}
}
}
}
finally
{
unequipServantItemEvents.Dispose();
}
}
[HarmonyPatch(typeof(EquipmentTransferSystem), nameof(EquipmentTransferSystem.OnUpdate))]
[HarmonyPrefix]
public static void OnUpdatePrefix(EquipmentTransferSystem __instance)
{
if (!Core.IsReady) return;
else if (!_familiars) return;
NativeArray<Entity> entities = __instance.EntityQueries[0].ToEntityArray(Allocator.Temp);
NativeArray<EquipmentToEquipmentTransferEvent> equipmentToEquipmentTransferEvents = __instance.EntityQueries[0].ToComponentDataArray<EquipmentToEquipmentTransferEvent>(Allocator.Temp);
NativeArray<FromCharacter> fromCharacters = __instance.EntityQueries[0].ToComponentDataArray<FromCharacter>(Allocator.Temp);
ComponentLookup<BlockFeedBuff> blockFeedBuffLookup = __instance.GetComponentLookup<BlockFeedBuff>();
try
{
var networkIdLookupMap = NetworkIdSystem._NetworkIdLookupMap;
for (int i = 0; i < entities.Length; i++)
{
Entity entity = entities[i];
EquipmentToEquipmentTransferEvent equipmentToEquipmentTransferEvent = equipmentToEquipmentTransferEvents[i];
FromCharacter fromCharacter = fromCharacters[i];
NetworkId networkId = equipmentToEquipmentTransferEvent.ToEntity;
EquipmentType equipmentType = equipmentToEquipmentTransferEvent.EquipmentType;
bool servantToCharacter = equipmentToEquipmentTransferEvent.ServantToCharacter;
if (!servantToCharacter && NetworkIdSystem._NetworkIdLookupMap.TryGetValue(networkId, out Entity servant)
&& blockFeedBuffLookup.HasComponent(servant)
&& fromCharacter.Character.TryGetComponent(out Equipment equipment))
{
if (equipment.GetEquipmentEntity(equipmentType).GetEntityOnServer().IsAncestralWeapon())
{
// Core.Log.LogWarning($"[EquipmentTransferSystem] isLegendary!");
entity.Destroy(true);
}
else
{
Entity familiar = Familiars.GetServantFamiliar(servant);
if (familiar.Exists())
{
// Core.Log.LogWarning($"[EquipmentTransferSystem] Familiar servant equipped, refreshing stats...");
Buffs.RefreshStats(familiar);
}
}
}
else if (servantToCharacter)
{
Entity playerCharacter = fromCharacter.Character;
ulong steamId = playerCharacter.GetSteamId();
if (steamId.HasActiveFamiliar())
{
Entity familiar = Familiars.GetActiveFamiliar(playerCharacter);
// Core.Log.LogWarning($"[EquipmentTransferSystem] Familiar servant unequipped (?), refreshing stats...");
Buffs.RefreshStats(familiar);
}
}
}
}
finally
{
entities.Dispose();
equipmentToEquipmentTransferEvents.Dispose();
fromCharacters.Dispose();
}
}
[HarmonyPatch(typeof(ServantPowerSystem), nameof(ServantPowerSystem.OnUpdate))]
[HarmonyPrefix]
public static void OnUpdatePrefix(ServantPowerSystem __instance)
{
if (!Core.IsReady) return;
else if (!_familiars) return;
NativeArray<Entity> entities = __instance.EntityQueries[0].ToEntityArray(Allocator.Temp);
ComponentLookup<BlockFeedBuff> blockFeedBuffLookup = __instance.GetComponentLookup<BlockFeedBuff>();
try
{
foreach (Entity entity in entities)
{
if (blockFeedBuffLookup.HasComponent(entity))
{
// Core.Log.LogWarning($"[ServantPowerSystem] BlockFeedBuff servant...");
Entity familiar = Familiars.GetServantFamiliar(entity);
if (familiar.Exists())
{
// Core.Log.LogWarning($"[ServantPowerSystem] Servant familiar found!");
Familiars.SyncFamiliarServant(familiar, entity);
}
}
}
}
finally
{
entities.Dispose();
}
}
[HarmonyPatch(typeof(MoveItemBetweenInventoriesSystem), nameof(MoveItemBetweenInventoriesSystem.OnUpdate))]
[HarmonyPrefix]
public static void OnUpdatePrefix(MoveItemBetweenInventoriesSystem __instance)
{
if (!Core.IsReady) return;
else if (!_familiars) return;
using NativeAccessor<Entity> entities = __instance._MoveItemBetweenInventoriesEventQuery.ToEntityArrayAccessor();
using NativeAccessor<MoveItemBetweenInventoriesEvent> moveItemBetweenInventoriesEvents = __instance._MoveItemBetweenInventoriesEventQuery.ToComponentDataArrayAccessor<MoveItemBetweenInventoriesEvent>();
using NativeAccessor<FromCharacter> fromCharacters = __instance._MoveItemBetweenInventoriesEventQuery.ToComponentDataArrayAccessor<FromCharacter>();
ComponentLookup<BlockFeedBuff> blockFeedBuffLookup = __instance.GetComponentLookup<BlockFeedBuff>();
try
{
for (int i = 0; i < entities.Length; i++)
{
Entity entity = entities[i];
MoveItemBetweenInventoriesEvent moveItemBetweenInventoriesEvent = moveItemBetweenInventoriesEvents[i];
FromCharacter fromCharacter = fromCharacters[i];
NetworkId toInventory = moveItemBetweenInventoriesEvent.ToInventory;
int slotIndex = moveItemBetweenInventoriesEvent.FromSlot;
// Core.Log.LogWarning($"[MoveItemBetweenInventoriesSystem]"); // yep, this system
if (NetworkIdSystem._NetworkIdLookupMap.TryGetValue(toInventory, out Entity toInventoryEntity))
{
Entity playerCharacter = fromCharacter.Character;
// Entity servant = Familiars.GetFamiliarServant(playerCharacter);
// Entity servantInventory = InventoryUtilities.TryGetInventoryEntity(EntityManager, servant, out Entity inventory) ? inventory : Entity.Null;
// if (servant.Exists()) Core.DumpEntity(Core.Server, servant); // playerCharacter, yeah that makes sense
/*
if (toInventoryEntity.Exists())
{
Core.Log.LogWarning($"[MoveItemBetweenInventoriesSystem] {toInventoryEntity} | {servantInventory}");
Core.DumpEntity(Core.Server, toInventoryEntity); // appears to be the servant entity
}
*/
if (!blockFeedBuffLookup.HasComponent(toInventoryEntity))
{
// Core.Log.LogWarning($"[MoveItemBetweenInventoriesSystem] No BlockFeedBuff component on servant or inventory entities don't match!");
continue;
}
else if (InvalidFamiliarEquipment(playerCharacter, slotIndex))
{
// Core.Log.LogWarning($"[MoveItemBetweenInventoriesSystem] Invalid equipment!");
entity.Destroy(true);
}
else
{
Entity familiar = Familiars.GetActiveFamiliar(playerCharacter);
if (familiar.Exists())
{
// Core.Log.LogWarning($"[MoveItemBetweenInventoriesSystem] Familiar servant equipped, refreshing stats...");
Buffs.RefreshStats(familiar);
}
}
}
else
{
// Core.Log.LogWarning($"[MoveItemBetweenInventoriesSystem] No NetworkId found for toInventory!");
}
}
}
catch (Exception ex)
{
Core.Log.LogError($"[MoveItemBetweenInventoriesSystem] Error in OnUpdatePrefix: {ex}");
}
}
}
| 412 | 0.942504 | 1 | 0.942504 | game-dev | MEDIA | 0.914551 | game-dev | 0.932424 | 1 | 0.932424 |
forest0xia/dota2bot-OpenHyperAI | 27,247 | bots/BotLib/hero_rubick.lua | local X = {}
local bot = GetBot()
local J = require( GetScriptDirectory()..'/FunLib/jmz_func' )
local R = dofile( GetScriptDirectory()..'/FunLib/rubick_utility' )
local SPL = dofile( GetScriptDirectory()..'/FunLib/spell_prob_list' )
local Minion = dofile( GetScriptDirectory()..'/FunLib/aba_minion' )
local sTalentList = J.Skill.GetTalentList( bot )
local sAbilityList = J.Skill.GetAbilityList( bot )
local sRole = J.Item.GetRoleItemsBuyList( bot )
local tTalentTreeList = {--pos4,5
['t25'] = {10, 0},
['t20'] = {0, 10},
['t15'] = {0, 10},
['t10'] = {10, 0},
}
local tAllAbilityBuildList = {
{2,1,2,3,2,6,2,3,3,3,1,6,1,1,6},--pos4,5
}
local nAbilityBuildList = J.Skill.GetRandomBuild(tAllAbilityBuildList)
local nTalentBuildList = J.Skill.GetTalentBuild(tTalentTreeList)
local sRoleItemsBuyList = {}
sRoleItemsBuyList['pos_2'] = {
"item_tango",
"item_double_branches",
"item_faerie_fire",
"item_bottle",
"item_boots",
"item_magic_wand",
"item_dagon_2",
"item_travel_boots",
"item_cyclone",
"item_ultimate_scepter",
"item_octarine_core",--
"item_dagon_5",--
"item_aghanims_shard",
"item_ultimate_scepter_2",
"item_shivas_guard",
"item_travel_boots_2",--
"item_ethereal_blade",--
"item_wind_waker",--
"item_moon_shard",
}
sRoleItemsBuyList['pos_5'] = {
"item_double_tango",
"item_double_branches",
"item_blood_grenade",
"item_magic_stick",
"item_boots",
"item_magic_wand",
"item_arcane_boots",
"item_glimmer_cape",--
'item_pipe',--
"item_aether_lens",
"item_blink",
"item_ancient_janggo",
"item_aghanims_shard",
"item_force_staff",--
"item_ultimate_scepter",
"item_octarine_core",--
-- "item_cyclone",
"item_ethereal_blade",--
-- "item_wind_waker",--
"item_arcane_blink",--
"item_ultimate_scepter_2",
"item_moon_shard",
"item_travel_boots_2",--
}
sRoleItemsBuyList['pos_4'] = {
"item_double_tango",
"item_double_branches",
"item_blood_grenade",
"item_magic_stick",
"item_boots",
"item_magic_wand",
"item_arcane_boots",
"item_glimmer_cape",--
"item_aether_lens",
"item_blink",
"item_mekansm",
"item_guardian_greaves",--
"item_force_staff",--
"item_aghanims_shard",
"item_ultimate_scepter",
"item_octarine_core",--
"item_cyclone",
"item_ethereal_blade",--
-- "item_wind_waker",--
"item_arcane_blink",--
"item_ultimate_scepter_2",
"item_moon_shard",
}
sRoleItemsBuyList['pos_1'] = {
"item_tango",
"item_double_branches",
"item_faerie_fire",
"item_boots",
"item_magic_wand",
"item_dagon_2",
"item_travel_boots",
"item_cyclone",
"item_ultimate_scepter",
"item_octarine_core",--
"item_dagon_5",--
"item_aghanims_shard",
"item_ultimate_scepter_2",
"item_shivas_guard",
"item_travel_boots_2",--
"item_ethereal_blade",--
"item_wind_waker",--
"item_moon_shard",
}
sRoleItemsBuyList['pos_3'] = {
"item_tango",
"item_double_branches",
"item_magic_stick",
"item_ring_of_protection",
"item_helm_of_iron_will",
"item_boots",
"item_magic_wand",
"item_phase_boots",
"item_veil_of_discord",
"item_eternal_shroud",--
"item_ultimate_scepter",
"item_blink",
"item_shivas_guard",--
"item_black_king_bar",--
"item_travel_boots",
"item_overwhelming_blink",--
"item_ultimate_scepter_2",
"item_travel_boots_2",--
"item_aghanims_shard",
"item_moon_shard",
}
X['sBuyList'] = sRoleItemsBuyList[sRole]
X['sSellList'] = {
"item_black_king_bar",
"item_quelling_blade",
}
if J.Role.IsPvNMode() or J.Role.IsAllShadow() then X['sBuyList'], X['sSellList'] = { 'PvN_antimage' }, {} end
nAbilityBuildList, nTalentBuildList, X['sBuyList'], X['sSellList'] = J.SetUserHeroInit( nAbilityBuildList, nTalentBuildList, X['sBuyList'], X['sSellList'] )
X['sSkillList'] = J.Skill.GetSkillList( sAbilityList, nAbilityBuildList, sTalentList, nTalentBuildList )
X['bDeafaultAbility'] = false
X['bDeafaultItem'] = false
function X.MinionThink(hMinionUnit)
Minion.MinionThink(hMinionUnit)
end
local Telekinesis = bot:GetAbilityByName('rubick_telekinesis')
local TelekinesisLand = bot:GetAbilityByName('rubick_telekinesis_land')
local FadeBolt = bot:GetAbilityByName('rubick_fade_bolt')
-- local ArcaneSupremacy = bot:GetAbilityByName('rubick_null_field')
local StolenSpell1 = bot:GetAbilityByName('rubick_empty1')
local StolenSpell2 = bot:GetAbilityByName('rubick_empty2')
local SpellSteal = bot:GetAbilityByName('rubick_spell_steal')
local TelekinesisDesire, TelekinesisTarget
local TelekinesisLandDesire, TelekinesisLandLocation
local FadeBoltDesire, FadeBoltTarget
local SpellStealDesire, SpellStealTarget
local botTarget
local lastTimeStealSpell = 0
if bot.shouldBlink == nil then bot.shouldBlink = false end
function X.SkillsComplement()
if J.CanNotUseAbility(bot) then return end
-- if Rubick is in good health condition and is casting an ability with some enmey still nearby, don't consider any other spells.
if J.GetHP(bot) > 0.3
and not J.IsRetreating(bot)
and (bot:IsChanneling()
or bot:IsUsingAbility()
or bot:IsCastingAbility())
then
local nEnemyHeroes = J.GetNearbyHeroes(bot,nRadius + 300, true, BOT_MODE_NONE)
if nEnemyHeroes ~= nil and #nEnemyHeroes > 0 then
return
end
end
botTarget = J.GetProperTarget(bot)
StolenSpell1 = bot:GetAbilityInSlot(3)
StolenSpell2 = bot:GetAbilityInSlot(4)
-- consider using whatever it has first
X.ConsiderStolenSpell1()
X.ConsiderStolenSpell2()
-- consdier stealing
SpellStealDesire, SpellStealTarget = X.ConsiderSpellSteal()
if SpellStealDesire > 0
then
bot:Action_UseAbilityOnEntity(SpellSteal, SpellStealTarget)
lastTimeStealSpell = DotaTime()
return
end
TelekinesisDesire, TelekinesisTarget = X.ConsiderTelekinesis()
if TelekinesisDesire > 0
then
bot.teleTarget = TelekinesisTarget
bot:Action_UseAbilityOnEntity(Telekinesis, TelekinesisTarget)
return
end
TelekinesisLandDesire, TelekinesisLandLocation = X.ConsiderTelekinesisLand()
if TelekinesisLandDesire > 0
then
bot:Action_UseAbilityOnLocation(TelekinesisLand, TelekinesisLandLocation)
bot.isChannelLand = false
bot.isSaveUltLand= false
bot.isEngagingLand = false
bot.isRetreatLand = false
bot.isSaveAllyLand = false
return
end
FadeBoltDesire, FadeBoltTarget = X.ConsiderFadeBolt()
if FadeBoltDesire > 0
then
bot:Action_UseAbilityOnEntity(FadeBolt, FadeBoltTarget)
return
end
end
function X.ConsiderTelekinesis()
if Telekinesis:IsHidden()
or not Telekinesis:IsFullyCastable()
then
return BOT_ACTION_DESIRE_NONE, nil
end
local nCastRange = J.GetProperCastRange(false, bot, Telekinesis:GetCastRange())
local nEnemyHeroes = J.GetNearbyHeroes(bot,nCastRange + 300, true, BOT_MODE_NONE)
for _, enemyHero in pairs(nEnemyHeroes)
do
if J.IsValidHero(enemyHero)
and J.CanCastOnNonMagicImmune(enemyHero)
and J.CanCastOnTargetAdvanced(enemyHero)
and not J.IsSuspiciousIllusion(enemyHero)
then
if enemyHero:IsChanneling() or J.IsCastingUltimateAbility(enemyHero)
then
bot.isChannelLand = true
return BOT_ACTION_DESIRE_HIGH, enemyHero
end
end
end
if J.IsGoingOnSomeone(bot)
then
local nInRangeAlly = J.GetAlliesNearLoc(bot:GetLocation(), 1200)
local nInRangeEnemy = J.GetEnemiesNearLoc(bot:GetLocation(), 1200)
for _, allyHero in pairs(nInRangeAlly)
do
if J.IsValidHero(allyHero)
and J.IsCore(allyHero)
and not J.IsSuspiciousIllusion(allyHero)
and not allyHero:IsInvulnerable()
and not allyHero:IsAttackImmune()
and not allyHero:HasModifier('modifier_furion_sprout_damage')
and not allyHero:HasModifier('modifier_legion_commander_duel')
and not allyHero:HasModifier('modifier_necrolyte_reapers_scythe')
then
if allyHero:HasModifier('modifier_enigma_black_hole_pull')
or allyHero:HasModifier('modifier_faceless_void_chronosphere_freeze')
then
bot.isSaveUltLand = true
return BOT_ACTION_DESIRE_HIGH, allyHero
end
end
end
if J.IsValidTarget(botTarget)
and J.CanCastOnNonMagicImmune(botTarget)
and J.CanCastOnTargetAdvanced(botTarget)
and J.IsInRange(bot, botTarget, nCastRange + 150)
and not J.IsSuspiciousIllusion(botTarget)
and not J.IsDisabled(botTarget)
and not botTarget:HasModifier('modifier_furion_sprout_damage')
and not botTarget:HasModifier('modifier_legion_commander_duel')
and not botTarget:HasModifier('modifier_necrolyte_reapers_scythe')
then
nInRangeAlly = J.GetAlliesNearLoc(botTarget:GetLocation(), 1200)
nInRangeEnemy = J.GetEnemiesNearLoc(botTarget:GetLocation(), 1200)
if nInRangeAlly ~= nil and nInRangeEnemy ~= nil
and #nInRangeAlly >= #nInRangeEnemy
and not (#nInRangeEnemy == 0 and #nInRangeAlly >= #nInRangeEnemy + 2)
then
bot.isEngagingLand = true
return BOT_ACTION_DESIRE_HIGH, botTarget
end
end
end
if J.IsRetreating(bot)
then
local nInRangeEnemy = J.GetNearbyHeroes(bot,nCastRange, true, BOT_MODE_NONE)
for _, enemyHero in pairs(nInRangeEnemy)
do
if J.IsValidHero(enemyHero)
and J.CanCastOnNonMagicImmune(enemyHero)
and J.CanCastOnTargetAdvanced(enemyHero)
and not J.IsSuspiciousIllusion(enemyHero)
and not J.IsDisabled(enemyHero)
and not enemyHero:HasModifier('modifier_furion_sprout_damage')
then
local nInRangeAlly = J.GetNearbyHeroes(enemyHero, 1200, true, BOT_MODE_NONE)
local nTargetInRangeAlly = J.GetNearbyHeroes(enemyHero, 1200, false, BOT_MODE_NONE)
if nInRangeAlly ~= nil and nTargetInRangeAlly ~= nil
and (#nTargetInRangeAlly > #nInRangeAlly
or bot:WasRecentlyDamagedByAnyHero(2))
then
bot.isRetreatLand = true
return BOT_ACTION_DESIRE_HIGH, enemyHero
end
end
end
end
local nAllyHeroes = J.GetNearbyHeroes(bot,nCastRange, false, BOT_MODE_NONE)
for _, allyHero in pairs(nAllyHeroes)
do
local nAllyInRangeEnemy = J.GetNearbyHeroes(allyHero, 1200, true, BOT_MODE_NONE)
if J.IsValidHero(allyHero)
and J.IsRetreating(allyHero)
and allyHero:WasRecentlyDamagedByAnyHero(2)
and not allyHero:IsIllusion()
then
if nAllyInRangeEnemy ~= nil and #nAllyInRangeEnemy >= 1
and J.IsValidHero(nAllyInRangeEnemy[1])
and J.CanCastOnNonMagicImmune(nAllyInRangeEnemy[1])
and J.CanCastOnTargetAdvanced(nAllyInRangeEnemy[1])
and J.IsInRange(bot, nAllyInRangeEnemy[1], nCastRange)
and J.IsChasingTarget(nAllyInRangeEnemy[1], allyHero)
and nAllyInRangeEnemy[1]:IsFacingLocation(allyHero:GetLocation(), 30)
and not J.IsDisabled(nAllyInRangeEnemy[1])
and not J.IsTaunted(nAllyInRangeEnemy[1])
and not J.IsSuspiciousIllusion(nAllyInRangeEnemy[1])
and not nAllyInRangeEnemy[1]:HasModifier('modifier_legion_commander_duel')
and not nAllyInRangeEnemy[1]:HasModifier('modifier_enigma_black_hole_pull')
and not nAllyInRangeEnemy[1]:HasModifier('modifier_faceless_void_chronosphere_freeze')
and not nAllyInRangeEnemy[1]:HasModifier('modifier_furion_sprout_damage')
and not nAllyInRangeEnemy[1]:HasModifier('modifier_necrolyte_reapers_scythe')
then
bot.isSaveAllyLand = true
return BOT_ACTION_DESIRE_HIGH, nAllyInRangeEnemy[1]
end
end
end
if J.IsDoingRoshan(bot)
then
-- Remove Spell Block
if J.IsRoshan(botTarget)
and J.CanCastOnMagicImmune(botTarget)
and J.IsInRange(bot, botTarget, nCastRange)
and J.IsAttacking(bot)
and botTarget:HasModifier('modifier_roshan_spell_block')
then
return BOT_ACTION_DESIRE_LOW, botTarget
end
end
return BOT_ACTION_DESIRE_NONE, nil
end
function X.ConsiderTelekinesisLand()
if TelekinesisLand:IsHidden()
or not TelekinesisLand:IsFullyCastable()
then
return BOT_ACTION_DESIRE_NONE, 0
end
local nDistance = TelekinesisLand:GetSpecialValueInt('radius')
local nTalent8 = bot:GetAbilityByName('special_bonus_unique_rubick_8')
if nTalent8:IsTrained()
then
nDistance = nDistance + nTalent8:GetSpecialValueInt('value')
end
local nInRangeAlly = J.GetAlliesNearLoc(bot:GetLocation(), 1200)
local nInRangeEnemy = J.GetEnemiesNearLoc(bot:GetLocation(), 1200)
if J.IsValidHero(botTarget)
and not J.IsSuspiciousIllusion(botTarget)
then
nInRangeAlly = J.GetAlliesNearLoc(botTarget:GetLocation(), 1200)
nInRangeEnemy = J.GetEnemiesNearLoc(botTarget:GetLocation(), 1200)
end
if nInRangeAlly ~= nil and nInRangeEnemy ~= nil
and J.IsValid(bot.teleTarget)
then
if bot.isChannelLand ~= nil
and bot.isChannelLand == true
then
if #nInRangeAlly >= #nInRangeEnemy
then
if J.IsInRange(bot, bot.teleTarget, nDistance)
then
return BOT_ACTION_DESIRE_HIGH, bot:GetLocation()
end
if not J.IsInRange(bot, bot.teleTarget, nDistance)
then
return BOT_ACTION_DESIRE_HIGH, J.Site.GetXUnitsTowardsLocation(bot, bot:GetLocation(), nDistance)
end
end
if #nInRangeEnemy > #nInRangeAlly
then
return BOT_ACTION_DESIRE_HIGH, J.Site.GetXUnitsTowardsLocation(bot, J.GetEnemyFountain(), nDistance)
end
end
if bot.isSaveUltLand ~= nil
and bot.isSaveUltLand == true
then
return BOT_ACTION_DESIRE_HIGH, J.Site.GetXUnitsTowardsLocation(bot, J.GetTeamFountain(), nDistance)
end
if bot.isEngagingLand ~= nil
and bot.isEngagingLand == true
then
return BOT_ACTION_DESIRE_HIGH, bot:GetLocation()
end
if bot.isRetreatLand ~= nil
and bot.isRetreatLand == true
then
return BOT_ACTION_DESIRE_HIGH, J.Site.GetXUnitsTowardsLocation(bot, J.GetEnemyFountain(), nDistance)
end
if bot.isSaveAllyLand ~= nil
and bot.isSaveAllyLand == true
then
return BOT_ACTION_DESIRE_HIGH, J.Site.GetXUnitsTowardsLocation(bot, J.GetTeamFountain(), nDistance)
end
end
return BOT_ACTION_DESIRE_NONE, 0
end
function X.ConsiderFadeBolt()
if not FadeBolt:IsFullyCastable()
then
return BOT_ACTION_DESIRE_NONE, nil
end
local nCastRange = J.GetProperCastRange(false, bot, FadeBolt:GetCastRange())
local nDamage = FadeBolt:GetSpecialValueInt('damage')
local nRadius = FadeBolt:GetSpecialValueInt('radius')
local nEnemyHeroes = J.GetNearbyHeroes(bot,nCastRange, true, BOT_MODE_NONE)
for _, enemyHero in pairs(nEnemyHeroes)
do
if J.IsValidHero(enemyHero)
and J.CanCastOnNonMagicImmune(enemyHero)
and J.CanCastOnTargetAdvanced(enemyHero)
and not J.IsSuspiciousIllusion(enemyHero)
and not enemyHero:HasModifier('modifier_rubick_telekinesis')
then
if J.IsInEtherealForm(enemyHero)
then
return BOT_ACTION_DESIRE_HIGH, enemyHero
end
if J.CanKillTarget(enemyHero, nDamage, DAMAGE_TYPE_MAGICAL)
and not enemyHero:HasModifier('modifier_abaddon_borrowed_time')
and not enemyHero:HasModifier('modifier_dazzle_shallow_grave')
and not enemyHero:HasModifier('modifier_necrolyte_reapers_scythe')
and not enemyHero:HasModifier('modifier_oracle_false_promise_timer')
and not enemyHero:HasModifier('modifier_templar_assassin_refraction_absorb')
then
return BOT_ACTION_DESIRE_HIGH, enemyHero
end
end
end
local nAllyHeroes = J.GetNearbyHeroes(bot,nCastRange, false, BOT_MODE_NONE)
for _, allyHero in pairs(nAllyHeroes)
do
local nAllyInRangeEnemy = J.GetNearbyHeroes(allyHero, 1200, true, BOT_MODE_NONE)
if J.IsValidHero(allyHero)
and J.IsRetreating(allyHero)
and allyHero:WasRecentlyDamagedByAnyHero(1.5)
and not allyHero:IsIllusion()
then
if nAllyInRangeEnemy ~= nil and #nAllyInRangeEnemy >= 1
and J.IsValidHero(nAllyInRangeEnemy[1])
and J.CanCastOnNonMagicImmune(nAllyInRangeEnemy[1])
and J.CanCastOnTargetAdvanced(nAllyInRangeEnemy[1])
and J.IsInRange(bot, nAllyInRangeEnemy[1], nCastRange)
and J.IsChasingTarget(nAllyInRangeEnemy[1], allyHero)
and J.IsAttacking(nAllyInRangeEnemy[1])
and nAllyInRangeEnemy[1]:IsFacingLocation(allyHero:GetLocation(), 30)
and not J.IsChasingTarget(nAllyInRangeEnemy[1], bot)
and not J.IsDisabled(nAllyInRangeEnemy[1])
and not J.IsTaunted(nAllyInRangeEnemy[1])
and not J.IsSuspiciousIllusion(nAllyInRangeEnemy[1])
and not nAllyInRangeEnemy[1]:HasModifier('modifier_necrolyte_reapers_scythe')
and not nAllyInRangeEnemy[1]:HasModifier('modifier_rubick_telekinesis')
then
return BOT_ACTION_DESIRE_HIGH, nAllyInRangeEnemy[1]
end
end
end
if J.IsInTeamFight(bot, 1200)
then
local nInRangeEnemy = J.GetEnemiesNearLoc(bot:GetLocation(), nCastRange)
local target = nil
local hp = 100000
for _, enemyHero in pairs(nInRangeEnemy)
do
if J.IsValidHero(enemyHero)
and J.CanCastOnNonMagicImmune(enemyHero)
and J.CanCastOnTargetAdvanced(enemyHero)
and not J.IsSuspiciousIllusion(enemyHero)
and not enemyHero:HasModifier('modifier_abaddon_borrowed_time')
and not enemyHero:HasModifier('modifier_necrolyte_reapers_scythe')
and not enemyHero:HasModifier('modifier_dazzle_shallow_grave')
and not enemyHero:HasModifier('modifier_rubick_telekinesis')
and not enemyHero:HasModifier('modifier_templar_assassin_refraction_absorb')
then
local nTargetInRangeAlly = J.GetEnemiesNearLoc(enemyHero:GetLocation(), nRadius)
local currHP = enemyHero:GetHealth()
if nTargetInRangeAlly ~= nil and #nTargetInRangeAlly >= 1
and currHP < hp
then
hp = currHP
target = enemyHero
end
end
end
if target ~= nil
then
return BOT_ACTION_DESIRE_HIGH, target
end
end
if J.IsGoingOnSomeone(bot)
then
if J.IsValidTarget(botTarget)
and J.CanCastOnNonMagicImmune(botTarget)
and J.CanCastOnTargetAdvanced(botTarget)
and J.IsInRange(bot, botTarget, nCastRange)
and not J.IsSuspiciousIllusion(botTarget)
and not J.IsDisabled(botTarget)
and not botTarget:HasModifier('modifier_abaddon_borrowed_time')
and not botTarget:HasModifier('modifier_dazzle_shallow_grave')
and not botTarget:HasModifier('modifier_necrolyte_reapers_scythe')
and not botTarget:HasModifier('modifier_rubick_telekinesis')
and not botTarget:HasModifier('modifier_templar_assassin_refraction_absorb')
then
local nInRangeAlly = J.GetNearbyHeroes(bot,1200, false, BOT_MODE_NONE)
local nInRangeEnemy = J.GetNearbyHeroes(bot,1200, true, BOT_MODE_NONE)
if nInRangeAlly ~= nil and nInRangeEnemy ~= nil
and #nInRangeAlly >= #nInRangeEnemy
then
return BOT_ACTION_DESIRE_HIGH, botTarget
end
end
end
if J.IsRetreating(bot)
then
local nInRangeEnemy = J.GetNearbyHeroes(bot,nCastRange, true, BOT_MODE_NONE)
for _, enemyHero in pairs(nInRangeEnemy)
do
if J.IsValidHero(enemyHero)
and J.CanCastOnNonMagicImmune(enemyHero)
and J.CanCastOnTargetAdvanced(enemyHero)
and J.IsChasingTarget(enemyHero, bot)
and J.IsAttacking(enemyHero)
and not J.IsInRange(bot, enemyHero, 300)
and not J.IsSuspiciousIllusion(enemyHero)
and not J.IsDisabled(enemyHero)
then
local nInRangeAlly = J.GetNearbyHeroes(enemyHero, 1200, true, BOT_MODE_NONE)
local nTargetInRangeAlly = J.GetNearbyHeroes(enemyHero, 1200, false, BOT_MODE_NONE)
if nInRangeAlly ~= nil and nTargetInRangeAlly ~= nil
and ((#nTargetInRangeAlly > #nInRangeAlly)
or bot:WasRecentlyDamagedByAnyHero(2))
then
return BOT_ACTION_DESIRE_HIGH, enemyHero
end
end
end
end
if J.IsPushing(bot) or J.IsDefending(bot)
then
local nEnemyLaneCreeps = bot:GetNearbyLaneCreeps(1200, true)
if nEnemyLaneCreeps ~= nil and #nEnemyLaneCreeps >= 3
and J.CanBeAttacked(nEnemyLaneCreeps[1])
then
return BOT_ACTION_DESIRE_HIGH, nEnemyLaneCreeps[1]
end
end
if J.IsLaning(bot)
and not J.IsThereNonSelfCoreNearby(800)
then
local creepList = {}
local nInRangeEnemy = J.GetEnemiesNearLoc(bot:GetLocation(), 1200)
local nEnemyLaneCreeps = bot:GetNearbyLaneCreeps(nCastRange, true)
for _, creep in pairs(nEnemyLaneCreeps)
do
if J.IsValid(creep)
and J.CanBeAttacked(creep)
and (J.IsKeyWordUnit('ranged', creep) or J.IsKeyWordUnit('siege', creep) or J.IsKeyWordUnit('flagbearer', creep))
and creep:GetHealth() <= nDamage
and J.GetMP(bot) > 0.3
then
if nInRangeEnemy ~= nil and #nInRangeEnemy >= 1
and GetUnitToUnitDistance(creep, nInRangeEnemy[1]) < 500
then
return BOT_ACTION_DESIRE_HIGH, creep
end
end
if J.IsValid(creep)
and creep:GetHealth() <= nDamage
then
table.insert(creepList, creep)
end
end
if J.GetMP(bot) > 0.3
and nInRangeEnemy ~= nil and #nInRangeEnemy >= 1
and #creepList >= 2
and J.CanBeAttacked(creepList[1])
then
return BOT_ACTION_DESIRE_HIGH, creepList[1]
end
end
if J.IsDoingRoshan(bot)
then
if J.IsRoshan(botTarget)
and J.CanCastOnNonMagicImmune(botTarget)
and J.IsInRange(bot, botTarget, nCastRange)
and not botTarget:HasModifier('modifier_roshan_spell_block')
then
return BOT_ACTION_DESIRE_HIGH, botTarget
end
end
if J.IsDoingTormentor(bot)
then
if J.IsTormentor(botTarget)
and J.IsInRange(bot, botTarget, nCastRange)
and J.IsAttacking(bot)
then
return BOT_ACTION_DESIRE_HIGH, botTarget
end
end
return BOT_ACTION_DESIRE_NONE, nil
end
function X.ConsiderStolenSpell1()
if StolenSpell1:GetName() == 'rubick_empty1'
or not StolenSpell1:IsFullyCastable()
then
return BOT_ACTION_DESIRE_HIGH, 0, ''
end
R.ConsiderStolenSpell(StolenSpell1)
return BOT_ACTION_DESIRE_HIGH, 0, ''
end
function X.ConsiderStolenSpell2()
if StolenSpell2:GetName() == 'rubick_empty2'
or not StolenSpell2:IsFullyCastable()
then
return BOT_ACTION_DESIRE_HIGH, 0, ''
end
R.ConsiderStolenSpell(StolenSpell2)
return BOT_ACTION_DESIRE_HIGH, 0, ''
end
function X.ConsiderSpellSteal()
if not SpellSteal:IsFullyCastable()
then
return BOT_ACTION_DESIRE_NONE, nil
end
if DotaTime() - lastTimeStealSpell < 60 then
-- or low cd high dmg spells
if StolenSpell1:IsFullyCastable() and StolenSpell1:IsUltimate() and not bot:HasScepter() then
return BOT_ACTION_DESIRE_NONE, nil
end
if StolenSpell2:IsFullyCastable() and StolenSpell2:IsUltimate() then
return BOT_ACTION_DESIRE_NONE, nil
end
end
if StolenSpell1:GetCooldownTimeRemaining() < 5 and StolenSpell1:GetAbilityDamage() >= 280 then
return BOT_ACTION_DESIRE_NONE, nil
end
if StolenSpell2:GetCooldownTimeRemaining() < 5 and StolenSpell2:GetAbilityDamage() >= 280 then
return BOT_ACTION_DESIRE_NONE, nil
end
local nCastRange = J.GetProperCastRange(false, bot, SpellSteal:GetCastRange())
local nInRangeEnemy = J.GetEnemiesNearLoc(bot:GetLocation(), nCastRange + 300)
for _, enemyHero in pairs(nInRangeEnemy)
do
-- print("Rubick considering spell steal on an enemy...")
if J.IsValidHero(enemyHero)
and J.CanCastOnTargetAdvanced(enemyHero)
and not J.IsSuspiciousIllusion(enemyHero)
and not J.IsMeepoClone(enemyHero)
then
-- print("Rubick considering spell steal on a valid target enemy...")
if enemyHero:IsUsingAbility()
or enemyHero:IsCastingAbility()
or J.IsCastingUltimateAbility(enemyHero)
or enemyHero:GetLevel() > 10
then
-- print("Rubick considering spell steal on a valid target enemy that casted an ability...")
local ss1Weight = SPL.GetSpellReplaceWeight(StolenSpell1) * 100
local ranInt = RandomInt(1, 70)
-- print("Rubick considering spell steal on a valid target enemy that casted an ability: weight="..ss1Weight..", random int="..ranInt)
if bot:HasScepter()
then
local ss2Weight = SPL.GetSpellReplaceWeight(StolenSpell2) * 100
if ss1Weight * 100 >= ranInt
and ss2Weight * 100 >= RandomInt(1, 70)
then
return BOT_ACTION_DESIRE_HIGH, enemyHero
end
if ss2Weight * 100 >= ranInt
then
return BOT_ACTION_DESIRE_HIGH, enemyHero
end
else
if ss1Weight * 100 >= ranInt
then
return BOT_ACTION_DESIRE_HIGH, enemyHero
end
end
end
end
end
return BOT_ACTION_DESIRE_NONE, nil
end
return X | 412 | 0.913797 | 1 | 0.913797 | game-dev | MEDIA | 0.977887 | game-dev | 0.969134 | 1 | 0.969134 |
rudransh61/Physix-go | 1,904 | examples/oblique_collision.go | package main
import (
"image/color"
"github.com/hajimehoshi/ebiten/v2"
"github.com/hajimehoshi/ebiten/v2/ebitenutil"
"github.com/rudransh61/Physix-go/dynamics/collision"
physix "github.com/rudransh61/Physix-go/dynamics/physics"
"github.com/rudransh61/Physix-go/pkg/rigidbody"
"github.com/rudransh61/Physix-go/pkg/vector"
)
const (
Gravity = 0
BallRadius = 30
Mass = 50
)
var (
ball1 *rigidbody.RigidBody
ball2 *rigidbody.RigidBody
)
func initBalls() {
ball1 = &rigidbody.RigidBody{
Position: vector.Vector{X: 330, Y: 200},
Velocity: vector.Vector{X: 5, Y: 5},
Mass: Mass,
Radius: BallRadius,
Shape: "Circle",
IsMovable: true,
}
ball2 = &rigidbody.RigidBody{
Position: vector.Vector{X: 500, Y: 300},
Velocity: vector.Vector{X: -5, Y: -5},
Mass: Mass,
Radius: BallRadius,
Shape: "Circle",
IsMovable: true,
}
}
func update() error {
physix.ApplyForce(ball1, vector.Vector{X: 0, Y: Gravity}, 0.1)
physix.ApplyForce(ball2, vector.Vector{X: 0, Y: Gravity}, 0.1)
if collision.CircleCollided(ball1, ball2) {
collision.PreventCircleOverlap(ball1, ball2)
collision.BounceOnCollision(ball1, ball2, 1.0)
}
return nil
}
func draw(screen *ebiten.Image) {
ebitenutil.DrawCircle(screen, ball1.Position.X, ball1.Position.Y, ball1.Radius, color.RGBA{0, 255, 0, 255})
ebitenutil.DrawCircle(screen, ball2.Position.X, ball2.Position.Y, ball2.Radius, color.RGBA{0, 0, 255, 255})
}
type Game struct{}
func (g *Game) Update() error { return update() }
func (g *Game) Draw(screen *ebiten.Image) { draw(screen) }
func (g *Game) Layout(outsideWidth, outsideHeight int) (int, int) { return 800, 600 }
func main() {
ebiten.SetWindowSize(800, 600)
ebiten.SetWindowTitle("Oblique Collision")
initBalls()
if err := ebiten.RunGame(&Game{}); err != nil {
panic(err)
}
}
| 412 | 0.681107 | 1 | 0.681107 | game-dev | MEDIA | 0.824112 | game-dev,testing-qa | 0.736597 | 1 | 0.736597 |
google/kmsan | 4,246 | tools/perf/scripts/perl/Perf-Trace-Util/lib/Perf/Trace/Core.pm | package Perf::Trace::Core;
use 5.010000;
use strict;
use warnings;
require Exporter;
our @ISA = qw(Exporter);
our %EXPORT_TAGS = ( 'all' => [ qw(
) ] );
our @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } );
our @EXPORT = qw(
define_flag_field define_flag_value flag_str dump_flag_fields
define_symbolic_field define_symbolic_value symbol_str dump_symbolic_fields
trace_flag_str
);
our $VERSION = '0.01';
my %trace_flags = (0x00 => "NONE",
0x01 => "IRQS_OFF",
0x02 => "IRQS_NOSUPPORT",
0x04 => "NEED_RESCHED",
0x08 => "HARDIRQ",
0x10 => "SOFTIRQ");
sub trace_flag_str
{
my ($value) = @_;
my $string;
my $print_delim = 0;
foreach my $idx (sort {$a <=> $b} keys %trace_flags) {
if (!$value && !$idx) {
$string .= "NONE";
last;
}
if ($idx && ($value & $idx) == $idx) {
if ($print_delim) {
$string .= " | ";
}
$string .= "$trace_flags{$idx}";
$print_delim = 1;
$value &= ~$idx;
}
}
return $string;
}
my %flag_fields;
my %symbolic_fields;
sub flag_str
{
my ($event_name, $field_name, $value) = @_;
my $string;
if ($flag_fields{$event_name}{$field_name}) {
my $print_delim = 0;
foreach my $idx (sort {$a <=> $b} keys %{$flag_fields{$event_name}{$field_name}{"values"}}) {
if (!$value && !$idx) {
$string .= "$flag_fields{$event_name}{$field_name}{'values'}{$idx}";
last;
}
if ($idx && ($value & $idx) == $idx) {
if ($print_delim && $flag_fields{$event_name}{$field_name}{'delim'}) {
$string .= " $flag_fields{$event_name}{$field_name}{'delim'} ";
}
$string .= "$flag_fields{$event_name}{$field_name}{'values'}{$idx}";
$print_delim = 1;
$value &= ~$idx;
}
}
}
return $string;
}
sub define_flag_field
{
my ($event_name, $field_name, $delim) = @_;
$flag_fields{$event_name}{$field_name}{"delim"} = $delim;
}
sub define_flag_value
{
my ($event_name, $field_name, $value, $field_str) = @_;
$flag_fields{$event_name}{$field_name}{"values"}{$value} = $field_str;
}
sub dump_flag_fields
{
for my $event (keys %flag_fields) {
print "event $event:\n";
for my $field (keys %{$flag_fields{$event}}) {
print " field: $field:\n";
print " delim: $flag_fields{$event}{$field}{'delim'}\n";
foreach my $idx (sort {$a <=> $b} keys %{$flag_fields{$event}{$field}{"values"}}) {
print " value $idx: $flag_fields{$event}{$field}{'values'}{$idx}\n";
}
}
}
}
sub symbol_str
{
my ($event_name, $field_name, $value) = @_;
if ($symbolic_fields{$event_name}{$field_name}) {
foreach my $idx (sort {$a <=> $b} keys %{$symbolic_fields{$event_name}{$field_name}{"values"}}) {
if (!$value && !$idx) {
return "$symbolic_fields{$event_name}{$field_name}{'values'}{$idx}";
last;
}
if ($value == $idx) {
return "$symbolic_fields{$event_name}{$field_name}{'values'}{$idx}";
}
}
}
return undef;
}
sub define_symbolic_field
{
my ($event_name, $field_name) = @_;
# nothing to do, really
}
sub define_symbolic_value
{
my ($event_name, $field_name, $value, $field_str) = @_;
$symbolic_fields{$event_name}{$field_name}{"values"}{$value} = $field_str;
}
sub dump_symbolic_fields
{
for my $event (keys %symbolic_fields) {
print "event $event:\n";
for my $field (keys %{$symbolic_fields{$event}}) {
print " field: $field:\n";
foreach my $idx (sort {$a <=> $b} keys %{$symbolic_fields{$event}{$field}{"values"}}) {
print " value $idx: $symbolic_fields{$event}{$field}{'values'}{$idx}\n";
}
}
}
}
1;
__END__
=head1 NAME
Perf::Trace::Core - Perl extension for perf script
=head1 SYNOPSIS
use Perf::Trace::Core
=head1 SEE ALSO
Perf (script) documentation
=head1 AUTHOR
Tom Zanussi, E<lt>tzanussi@gmail.com<gt>
=head1 COPYRIGHT AND LICENSE
Copyright (C) 2009 by Tom Zanussi
This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself, either Perl version 5.10.0 or,
at your option, any later version of Perl 5 you may have available.
Alternatively, this software may be distributed under the terms of the
GNU General Public License ("GPL") version 2 as published by the Free
Software Foundation.
=cut
| 412 | 0.955767 | 1 | 0.955767 | game-dev | MEDIA | 0.814189 | game-dev | 0.632577 | 1 | 0.632577 |
fr1tz/terminal-overload | 2,705 | Engine/lib/bullet/src/BulletDynamics/ConstraintSolver/btUniversalConstraint.h | /*
Bullet Continuous Collision Detection and Physics Library, http://bulletphysics.org
Copyright (C) 2006, 2007 Sony Computer Entertainment Inc.
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef BT_UNIVERSAL_CONSTRAINT_H
#define BT_UNIVERSAL_CONSTRAINT_H
#include "LinearMath/btVector3.h"
#include "btTypedConstraint.h"
#include "btGeneric6DofConstraint.h"
/// Constraint similar to ODE Universal Joint
/// has 2 rotatioonal degrees of freedom, similar to Euler rotations around Z (axis 1)
/// and Y (axis 2)
/// Description from ODE manual :
/// "Given axis 1 on body 1, and axis 2 on body 2 that is perpendicular to axis 1, it keeps them perpendicular.
/// In other words, rotation of the two bodies about the direction perpendicular to the two axes will be equal."
ATTRIBUTE_ALIGNED16(class) btUniversalConstraint : public btGeneric6DofConstraint
{
protected:
btVector3 m_anchor;
btVector3 m_axis1;
btVector3 m_axis2;
public:
BT_DECLARE_ALIGNED_ALLOCATOR();
// constructor
// anchor, axis1 and axis2 are in world coordinate system
// axis1 must be orthogonal to axis2
btUniversalConstraint(btRigidBody& rbA, btRigidBody& rbB, const btVector3& anchor, const btVector3& axis1, const btVector3& axis2);
// access
const btVector3& getAnchor() { return m_calculatedTransformA.getOrigin(); }
const btVector3& getAnchor2() { return m_calculatedTransformB.getOrigin(); }
const btVector3& getAxis1() { return m_axis1; }
const btVector3& getAxis2() { return m_axis2; }
btScalar getAngle1() { return getAngle(2); }
btScalar getAngle2() { return getAngle(1); }
// limits
void setUpperLimit(btScalar ang1max, btScalar ang2max) { setAngularUpperLimit(btVector3(0.f, ang1max, ang2max)); }
void setLowerLimit(btScalar ang1min, btScalar ang2min) { setAngularLowerLimit(btVector3(0.f, ang1min, ang2min)); }
void setAxis( const btVector3& axis1, const btVector3& axis2);
};
#endif // BT_UNIVERSAL_CONSTRAINT_H
| 412 | 0.828058 | 1 | 0.828058 | game-dev | MEDIA | 0.991474 | game-dev | 0.950318 | 1 | 0.950318 |
Let-s-Do-Collection/Vinery | 7,123 | common/src/main/java/net/satisfy/vinery/core/block/WineBottleBlock.java | package net.satisfy.vinery.core.block;
import com.mojang.datafixers.util.Pair;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.core.NonNullList;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.sounds.SoundEvents;
import net.minecraft.sounds.SoundSource;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.ItemInteractionResult;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.LevelAccessor;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.StateDefinition;
import net.minecraft.world.level.block.state.properties.BooleanProperty;
import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.shapes.CollisionContext;
import net.minecraft.world.phys.shapes.Shapes;
import net.minecraft.world.phys.shapes.VoxelShape;
import net.satisfy.vinery.core.block.entity.StorageBlockEntity;
import net.satisfy.vinery.core.item.DrinkBlockItem;
import net.satisfy.vinery.core.registry.StorageTypeRegistry;
import net.satisfy.vinery.core.registry.TagRegistry;
import org.jetbrains.annotations.NotNull;
@SuppressWarnings("deprecation")
public class WineBottleBlock extends StorageBlock {
private static final VoxelShape SHAPE = Shapes.box(0.125, 0, 0.125, 0.875, 0.875, 0.875);
public static final BooleanProperty FAKE_MODEL = BooleanProperty.create("fake_model");
private final int maxCount;
public WineBottleBlock(Properties settings, int maxCount) {
super(settings);
this.maxCount = maxCount;
this.registerDefaultState(this.defaultBlockState().setValue(FAKE_MODEL, true));
}
@Override
public @NotNull ItemInteractionResult useItemOn(ItemStack stack, BlockState state, Level world, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hit) {
BlockEntity blockEntity = world.getBlockEntity(pos);
if(blockEntity instanceof StorageBlockEntity wineEntity){
NonNullList<ItemStack> inventory = wineEntity.getInventory();
if (canInsertStack(stack) && willFitStack(stack, inventory)) {
int posInE = getFirstEmptySlot(inventory);
if(posInE == Integer.MIN_VALUE) return ItemInteractionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION;
if(!world.isClientSide()){
wineEntity.setStack(posInE, stack.split(1));
if (player.isCreative()) {
stack.grow(1);
}
world.playSound(null, pos, SoundEvents.BOTTLE_FILL, SoundSource.BLOCKS, 1.0F, 1.0F);
}
return ItemInteractionResult.sidedSuccess(world.isClientSide());
} else if (stack.isEmpty() && !isEmpty(inventory)) {
int posInE = getLastFullSlot(inventory);
if(posInE == Integer.MIN_VALUE) return ItemInteractionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION;
if(!world.isClientSide()){
ItemStack wine = wineEntity.removeStack(posInE);
if (!player.getInventory().add(wine)) {
player.drop(wine, false);
}
if (isEmpty(inventory)) {
world.destroyBlock(pos, false);
}
world.playSound(null, pos, SoundEvents.BOTTLE_EMPTY, SoundSource.BLOCKS, 1.0F, 1.0F);
}
return ItemInteractionResult.sidedSuccess(world.isClientSide());
}
}
return ItemInteractionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION;
}
public boolean isEmpty(NonNullList<ItemStack> inventory){
for(ItemStack stack : inventory){
if(!stack.isEmpty()) return false;
}
return true;
}
public int getFirstEmptySlot(NonNullList<ItemStack> inventory){
for(ItemStack stack : inventory){
if(stack.isEmpty()) return inventory.indexOf(stack);
}
return Integer.MIN_VALUE;
}
public int getLastFullSlot(NonNullList<ItemStack> inventory){
for(int i = inventory.size() - 1; i >=0; i--){
if(!inventory.get(i).isEmpty()) return i;
}
return Integer.MIN_VALUE;
}
@Override
public @NotNull VoxelShape getShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext context) {
return SHAPE;
}
@Override
protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) {
super.createBlockStateDefinition(builder);
builder.add(FAKE_MODEL);
}
@Override
public @NotNull BlockState updateShape(BlockState blockState, Direction direction, BlockState blockState2, LevelAccessor levelAccessor, BlockPos blockPos, BlockPos blockPos2) {
if (direction == Direction.DOWN && !blockState.canSurvive(levelAccessor, blockPos)) {
levelAccessor.destroyBlock(blockPos, true);
}
return super.updateShape(blockState, direction, blockState2, levelAccessor, blockPos, blockPos2);
}
@Override
public int size() {
return maxCount;
}
@Override
public ResourceLocation type() {
return StorageTypeRegistry.WINE_BOTTLE;
}
@Override
public boolean canInsertStack(ItemStack stack) {
return stack.is(TagRegistry.SMALL_BOTTLE);
}
public boolean willFitStack(ItemStack itemStack, NonNullList<ItemStack> inventory) {
Pair<Integer, Integer> p = getFilledAmountAndBiggest(inventory);
int biggest = p.getSecond();
int count = p.getFirst();
int stackCount = getCount(itemStack);
if(biggest == Integer.MAX_VALUE) return true;
return stackCount > count && count < biggest;
}
public static Pair<Integer, Integer> getFilledAmountAndBiggest(NonNullList<ItemStack> inventory){
int count = 0;
int biggest = Integer.MAX_VALUE;
for(ItemStack stack : inventory){
if(!stack.isEmpty()){
count++;
if(stack.getItem() instanceof DrinkBlockItem item && item.getBlock() instanceof WineBottleBlock wine && wine.maxCount < biggest){
biggest = wine.maxCount;
}
}
}
return new Pair<>(count, biggest);
}
public static int getCount(ItemStack itemStack){
if(itemStack.getItem() instanceof DrinkBlockItem item && item.getBlock() instanceof WineBottleBlock wine){
return wine.maxCount;
}
return Integer.MIN_VALUE;
}
@Override
public int getSection(Float aFloat, Float aFloat1) {
return 0;
}
@Override
public Direction[] unAllowedDirections() {
return new Direction[0];
}
}
| 412 | 0.88033 | 1 | 0.88033 | game-dev | MEDIA | 0.997487 | game-dev | 0.946922 | 1 | 0.946922 |
beyond-aion/aion-server | 6,682 | game-server/data/handlers/ai/instance/rentusBase/CaptainXastaAI.java | package ai.instance.rentusBase;
import java.util.List;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicBoolean;
import com.aionemu.gameserver.ai.AIActions;
import com.aionemu.gameserver.ai.AIName;
import com.aionemu.gameserver.ai.AIState;
import com.aionemu.gameserver.ai.NpcAI;
import com.aionemu.gameserver.ai.event.AIEventType;
import com.aionemu.gameserver.ai.manager.EmoteManager;
import com.aionemu.gameserver.ai.manager.WalkManager;
import com.aionemu.gameserver.model.EmotionType;
import com.aionemu.gameserver.model.gameobjects.Creature;
import com.aionemu.gameserver.model.gameobjects.Npc;
import com.aionemu.gameserver.model.gameobjects.state.CreatureState;
import com.aionemu.gameserver.network.aion.serverpackets.SM_EMOTION;
import com.aionemu.gameserver.skillengine.SkillEngine;
import com.aionemu.gameserver.utils.PacketSendUtility;
import com.aionemu.gameserver.utils.ThreadPoolManager;
import com.aionemu.gameserver.world.WorldMapInstance;
import ai.AggressiveNpcAI;
/**
* @author xTz
*/
@AIName("captain_xasta")
public class CaptainXastaAI extends AggressiveNpcAI {
private boolean canThink = true;
private Future<?> phaseTask;
private AtomicBoolean isHome = new AtomicBoolean(true);
public CaptainXastaAI(Npc owner) {
super(owner);
}
@Override
public boolean canThink() {
return canThink;
}
@Override
public void handleAttack(Creature creature) {
super.handleAttack(creature);
if (isHome.compareAndSet(true, false)) {
if (getNpcId() == 217309) {
PacketSendUtility.broadcastMessage(getOwner(), 1500388);
startPhaseTask(this);
} else {
startPhase2Task();
}
}
}
private void cancelPhaseTask() {
if (phaseTask != null && !phaseTask.isDone()) {
phaseTask.cancel(true);
}
}
private void startPhaseTask(final NpcAI ai) {
phaseTask = ThreadPoolManager.getInstance().scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
if (isDead()) {
cancelPhaseTask();
} else {
canThink = false;
EmoteManager.emoteStopAttacking(getOwner());
getSpawnTemplate().setWalkerId("B186C8F43FF13FDD50FA9483B7D8C2BEABAE7F5C");
WalkManager.startWalking(ai);
startRun(getOwner());
spawnHelpers(ai);
startSanctuaryEvent();
}
}
}, 28000, 28000);
}
@Override
protected void handleMoveArrived() {
super.handleMoveArrived();
if (getSpawnTemplate().getWalkerId() != null) {
getSpawnTemplate().setWalkerId(null);
WalkManager.stopWalking(this);
}
}
private void startPhase2Task() {
phaseTask = ThreadPoolManager.getInstance().scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
if (isDead()) {
cancelPhaseTask();
} else {
SkillEngine.getInstance().getSkill(getOwner(), 19729, 60, getOwner()).useNoAnimationSkill();
PacketSendUtility.broadcastMessage(getOwner(), 1500392);
}
}
}, 30000, 30000);
}
private void startSanctuaryEvent() {
ThreadPoolManager.getInstance().schedule(new Runnable() {
@Override
public void run() {
if (!isDead()) {
canThink = true;
Creature creature = getAggroList().getMostHated();
if (creature == null || creature.isDead() || !getOwner().canSee(creature)) {
setStateIfNot(AIState.FIGHT);
getMoveController().abortMove();
onGeneralEvent(AIEventType.ATTACK_FINISH);
onGeneralEvent(AIEventType.BACK_HOME);
} else {
getMoveController().abortMove();
getOwner().setTarget(creature);
getOwner().getGameStats().renewLastAttackTime();
getOwner().getGameStats().renewLastAttackedTime();
getOwner().getGameStats().renewLastChangeTargetTime();
getOwner().getGameStats().renewLastSkillTime();
setStateIfNot(AIState.FIGHT);
handleMoveValidate();
SkillEngine.getInstance().getSkill(getOwner(), 19657, 60, getOwner()).useNoAnimationSkill();
}
}
}
}, 23000);
}
private void startRun(Npc npc) {
npc.setState(CreatureState.ACTIVE, true);
PacketSendUtility.broadcastPacket(npc, new SM_EMOTION(npc, EmotionType.CHANGE_SPEED, 0, npc.getObjectId()));
}
private void spawnHelpers(final NpcAI ai) {
ThreadPoolManager.getInstance().schedule(new Runnable() {
@Override
public void run() {
if (!isDead()) {
PacketSendUtility.broadcastMessage(getOwner(), 1500389);
SkillEngine.getInstance().getSkill(getOwner(), 19968, 60, getOwner()).useNoAnimationSkill();
Npc npc1 = (Npc) spawn(282604, 263f, 537f, 203f, (byte) 0);
Npc npc2 = (Npc) spawn(282604, 186f, 555f, 203f, (byte) 0);
npc1.getSpawn().setWalkerId("30028000014");
WalkManager.startWalking((NpcAI) npc1.getAi());
npc2.getSpawn().setWalkerId("30028000015");
WalkManager.startWalking((NpcAI) npc2.getAi());
startRun(npc1);
startRun(npc2);
}
}
}, 3000);
}
private void deleteHelpers() {
WorldMapInstance instance = getPosition().getWorldMapInstance();
if (instance != null) {
deleteNpcs(instance.getNpcs(282604));
}
}
private void deleteNpcs(List<Npc> npcs) {
for (Npc npc : npcs) {
if (npc != null) {
npc.getController().delete();
}
}
}
@Override
protected void handleDied() {
cancelPhaseTask();
if (getNpcId() == 217309) {
PacketSendUtility.broadcastMessage(getOwner(), 1500390);
spawn(217310, 238.160f, 598.624f, 178.480f, (byte) 0);
deleteHelpers();
AIActions.deleteOwner(this);
} else {
PacketSendUtility.broadcastMessage(getOwner(), 1500391);
final WorldMapInstance instance = getPosition().getWorldMapInstance();
if (instance != null) {
final Npc ariana = instance.getNpc(799668);
if (ariana != null) {
ariana.getEffectController().removeEffect(19921);
ThreadPoolManager.getInstance().schedule(() -> {
ariana.getSpawn().setWalkerId("30028000016");
WalkManager.startWalking((NpcAI) ariana.getAi());
}, 1000);
PacketSendUtility.broadcastMessage(ariana, 1500415, 4000);
PacketSendUtility.broadcastMessage(ariana, 1500416, 13000);
ThreadPoolManager.getInstance().schedule(() -> {
SkillEngine.getInstance().getSkill(ariana, 19358, 60, ariana).useNoAnimationSkill();
instance.setDoorState(145, true);
deleteNpcs(instance.getNpcs(701156));
ThreadPoolManager.getInstance().schedule(() -> ariana.getController().deleteIfAliveOrCancelRespawn(), 13000);
}, 13000);
}
}
}
super.handleDied();
}
@Override
protected void handleDespawned() {
cancelPhaseTask();
super.handleDespawned();
}
@Override
protected void handleBackHome() {
canThink = true;
cancelPhaseTask();
deleteHelpers();
isHome.set(true);
super.handleBackHome();
}
}
| 412 | 0.96573 | 1 | 0.96573 | game-dev | MEDIA | 0.983257 | game-dev | 0.991459 | 1 | 0.991459 |
ShadzXD/incompetent-Psych-engine | 6,698 | source/backend/ui/PsychUIDropDownMenu.hx | package backend.ui;
import backend.ui.PsychUIBox.UIStyleData;
class PsychUIDropDownMenu extends PsychUIInputText
{
public static final CLICK_EVENT = "dropdown_click";
public var list(default, set):Array<String> = [];
public var button:FlxSprite;
public var onSelect:Int->String->Void;
public var selectedIndex(default, set):Int = -1;
public var selectedLabel(default, set):String = null;
var _curFilter:Array<String>;
var _itemWidth:Float = 0;
public function new(x:Float, y:Float, list:Array<String>, callback:Int->String->Void, ?width:Float = 100)
{
super(x, y);
if(list == null) list = [];
_itemWidth = width - 2;
setGraphicSize(width, 20);
updateHitbox();
textObj.y += 2;
button = new FlxSprite(behindText.width + 1, 0).loadGraphic('assets/embed/images/psych-ui/dropdown_button.png', true, 20, 20);
button.animation.add('normal', [0], false);
button.animation.add('pressed', [1], false);
button.animation.play('normal', true);
add(button);
onSelect = callback;
onChange = function(old:String, cur:String)
{
if(old != cur)
{
_curFilter = this.list.filter(function(str:String) return str.startsWith(cur));
showDropDown(true, 0, _curFilter);
}
}
unfocus = function()
{
showDropDownClickFix();
showDropDown(false);
}
for (option in list)
addOption(option);
selectedIndex = 0;
showDropDown(false);
}
function set_selectedIndex(v:Int)
{
selectedIndex = v;
if(selectedIndex < 0 || selectedIndex >= list.length) selectedIndex = -1;
@:bypassAccessor selectedLabel = list[selectedIndex];
text = (selectedLabel != null) ? selectedLabel : '';
return selectedIndex;
}
function set_selectedLabel(v:String)
{
var id:Int = list.indexOf(v);
if(id >= 0)
{
@:bypassAccessor selectedIndex = id;
selectedLabel = v;
text = selectedLabel;
}
else
{
@:bypassAccessor selectedIndex = -1;
selectedLabel = null;
text = '';
}
return selectedLabel;
}
var _items:Array<PsychUIDropDownItem> = [];
public var curScroll:Int = 0;
override function update(elapsed:Float)
{
var lastFocus = PsychUIInputText.focusOn;
super.update(elapsed);
if(FlxG.mouse.justPressed)
{
if(FlxG.mouse.overlaps(button, camera))
{
button.animation.play('pressed', true);
if(lastFocus != this)
PsychUIInputText.focusOn = this;
else if(PsychUIInputText.focusOn == this)
PsychUIInputText.focusOn = null;
}
}
else if(FlxG.mouse.released && button.animation.curAnim != null && button.animation.curAnim.name != 'normal') button.animation.play('normal', true);
if(lastFocus != PsychUIInputText.focusOn)
{
showDropDown(PsychUIInputText.focusOn == this);
}
else if(PsychUIInputText.focusOn == this)
{
var wheel:Int = FlxG.mouse.wheel;
if(FlxG.keys.justPressed.UP) wheel++;
if(FlxG.keys.justPressed.DOWN) wheel--;
if(wheel != 0) showDropDown(true, curScroll - wheel, _curFilter);
}
}
private function showDropDownClickFix()
{
if(FlxG.mouse.justPressed)
{
for (item in _items) //extra update to fix a little bug where it wouldnt click on any option if another input text was behind the drop down
if(item != null && item.active && item.visible)
item.update(0);
}
}
public function showDropDown(vis:Bool = true, scroll:Int = 0, onlyAllowed:Array<String> = null)
{
if(!vis)
{
text = selectedLabel;
_curFilter = null;
}
curScroll = Std.int(Math.max(0, Math.min(onlyAllowed != null ? (onlyAllowed.length - 1) : (list.length - 1), scroll)));
if(vis)
{
var n:Int = 0;
for (item in _items)
{
if(onlyAllowed != null)
{
if(onlyAllowed.contains(item.label))
{
item.active = item.visible = (n >= curScroll);
n++;
}
else item.active = item.visible = false;
}
else
{
item.active = item.visible = (n >= curScroll);
n++;
}
}
var txtY:Float = behindText.y + behindText.height + 1;
for (num => item in _items)
{
if(!item.visible) continue;
item.x = behindText.x;
item.y = txtY;
txtY += item.height;
item.forceNextUpdate = true;
}
bg.scale.y = txtY - behindText.y + 2;
bg.updateHitbox();
}
else
{
for (item in _items)
item.active = item.visible = false;
bg.scale.y = 20;
bg.updateHitbox();
}
}
public var broadcastDropDownEvent:Bool = true;
function clickedOn(num:Int, label:String)
{
selectedIndex = num;
showDropDown(false);
if(onSelect != null) onSelect(num, label);
if(broadcastDropDownEvent) PsychUIEventHandler.event(CLICK_EVENT, this);
}
function addOption(option:String)
{
@:bypassAccessor list.push(option);
var curID:Int = list.length - 1;
var item:PsychUIDropDownItem = cast recycle(PsychUIDropDownItem, () -> new PsychUIDropDownItem(1, 1, this._itemWidth), true);
item.cameras = cameras;
item.label = option;
item.visible = item.active = false;
item.onClick = function() clickedOn(curID, option);
item.forceNextUpdate = true;
_items.push(item);
insert(1, item);
}
function set_list(v:Array<String>)
{
var selected:String = selectedLabel;
showDropDown(false);
for (item in _items)
item.kill();
_items = [];
list = [];
for (option in v)
addOption(option);
if(selectedLabel != null) selectedLabel = selected;
return v;
}
}
class PsychUIDropDownItem extends FlxSpriteGroup
{
public var hoverStyle:UIStyleData = {
bgColor: 0xFF0066FF,
textColor: FlxColor.WHITE,
bgAlpha: 1
};
public var normalStyle:UIStyleData = {
bgColor: FlxColor.WHITE,
textColor: FlxColor.BLACK,
bgAlpha: 1
};
public var bg:FlxSprite;
public var text:FlxText;
public function new(x:Float = 0, y:Float = 0, width:Float = 100)
{
super(x, y);
bg = new FlxSprite().makeGraphic(1, 1, FlxColor.WHITE);
bg.setGraphicSize(width, 20);
bg.updateHitbox();
add(bg);
text = new FlxText(0, 0, width, 8);
text.color = FlxColor.BLACK;
add(text);
}
public var onClick:Void->Void;
public var forceNextUpdate:Bool = false;
override function update(elapsed:Float)
{
super.update(elapsed);
if(FlxG.mouse.justMoved || FlxG.mouse.justPressed || forceNextUpdate)
{
var overlapped:Bool = (FlxG.mouse.overlaps(bg, camera));
var style = overlapped ? hoverStyle : normalStyle;
bg.color = style.bgColor;
text.color = style.textColor;
bg.alpha = style.bgAlpha;
forceNextUpdate = false;
if(overlapped && FlxG.mouse.justPressed)
onClick();
}
text.x = bg.x;
text.y = bg.y + bg.height/2 - text.height/2;
}
public var label(default, set):String;
function set_label(v:String)
{
label = v;
text.text = v;
bg.scale.y = text.height + 6;
bg.updateHitbox();
return v;
}
} | 412 | 0.94884 | 1 | 0.94884 | game-dev | MEDIA | 0.60987 | game-dev | 0.98369 | 1 | 0.98369 |
rism-digital/verovio | 2,414 | src/mnum.cpp | /////////////////////////////////////////////////////////////////////////////
// Name: mnum.cpp
// Author: Klaus Rettinghaus
// Created: 2018
// Copyright (c) Authors and others. All rights reserved.
/////////////////////////////////////////////////////////////////////////////
#include "mnum.h"
//----------------------------------------------------------------------------
#include <cassert>
//----------------------------------------------------------------------------
#include "editorial.h"
#include "functor.h"
#include "text.h"
#include "verticalaligner.h"
#include "vrv.h"
namespace vrv {
//----------------------------------------------------------------------------
// MNum
//----------------------------------------------------------------------------
MNum::MNum()
: ControlElement(MNUM), TextListInterface(), TextDirInterface(), TimePointInterface(), AttLang(), AttTypography()
{
this->RegisterInterface(TextDirInterface::GetAttClasses(), TextDirInterface::IsInterface());
this->RegisterInterface(TimePointInterface::GetAttClasses(), TimePointInterface::IsInterface());
this->RegisterAttClass(ATT_LANG);
this->RegisterAttClass(ATT_TYPOGRAPHY);
this->Reset();
}
MNum::~MNum() {}
void MNum::Reset()
{
ControlElement::Reset();
TextDirInterface::Reset();
TimePointInterface::Reset();
this->ResetLang();
this->ResetTypography();
m_isGenerated = false;
}
bool MNum::IsSupportedChild(ClassId classId)
{
static const std::vector<ClassId> supported{ REND, TEXT };
if (std::find(supported.begin(), supported.end(), classId) != supported.end()) {
return true;
}
else if (Object::IsEditorialElement(classId)) {
return true;
}
else {
return false;
}
}
//----------------------------------------------------------------------------
// MNum functor methods
//----------------------------------------------------------------------------
static const ClassRegistrar<MNum> s_factory("mNum", MNUM);
FunctorCode MNum::Accept(Functor &functor)
{
return functor.VisitMNum(this);
}
FunctorCode MNum::Accept(ConstFunctor &functor) const
{
return functor.VisitMNum(this);
}
FunctorCode MNum::AcceptEnd(Functor &functor)
{
return functor.VisitMNumEnd(this);
}
FunctorCode MNum::AcceptEnd(ConstFunctor &functor) const
{
return functor.VisitMNumEnd(this);
}
} // namespace vrv
| 412 | 0.844892 | 1 | 0.844892 | game-dev | MEDIA | 0.572496 | game-dev | 0.819851 | 1 | 0.819851 |
alexkulya/pandaria_5.4.8 | 4,451 | src/server/scripts/Pandaria/Scenarios/IsleOfThunder/pursuing_the_black_harvest.h | /*
* This file is part of the Pandaria 5.4.8 Project. See THANKS 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, see <http://www.gnu.org/licenses/>.
*/
#ifndef PURSUING_THE_BLACK_HARVEST_SCENARIO_H_
#define PURSUING_THE_BLACK_HARVEST_SCENARIO_H_
#include "ScriptPCH.h"
#include "ScenarioMgr.h"
#define CHAPTERS 9
const Position DemonicGatewayPos = { 645.96f, 305.97f, 353.67f, 6.15f };
const Position felStalkerPos = { 677.73f, 305.48f, 353.19f, 3.15f };
const Position entrancePos = { 711.20f, 998.29f, 53.55f, 4.66f };
const Position akamaScrollPath[6] =
{
{ 747.29f, 514.64f, 112.84f, 4.99f },
{ 745.15f, 498.72f, 112.76f, 4.52f },
{ 703.29f, 462.86f, 112.74f, 3.84f },
{ 704.51f, 394.93f, 113.16f, 4.70f },
{ 704.00f, 375.43f, 125.05f, 4.68f },
{ 703.24f, 357.72f, 125.15f, 4.63f },
};
const Position akamaSanctumPath[5] =
{
{ 724.33f, 354.70f, 125.16f, 6.20f },
{ 762.46f, 309.34f, 125.09f, 5.46f },
{ 781.58f, 297.84f, 112.80f, 5.77f },
{ 808.19f, 235.39f, 112.75f, 5.11f },
{ 808.52f, 220.40f, 112.76f, 4.73f },
};
const Position akamaPostSanctumPath[3] =
{
{ 808.01f, 119.75f, 112.41f, 4.63f },
{ 756.76f, 69.93f, 112.73f, 3.94f },
{ 663.71f, 65.22f, 112.72f, 3.18f },
};
const Position akamaLastPath[3] =
{
{ 732.50f, 67.13f, 113.25f, 0.00f },
{ 751.60f, 163.19f, 112.77f, 1.36f },
{ 751.75f, 225.62f, 63.63f, 1.53f },
};
const Position kanrethadPath[2] =
{
{ 662.39f, 308.06f, 354.01f, 6.01f },
{ 659.02f, 324.64f, 353.94f, 2.05f },
};
enum Creatures
{
NPC_HUNGERING_SOUL_FRAGMENT = 68140,
NPC_SUFFERING_SOUL_FRAGMENT = 68139,
NPC_ASHTONGUE_SHAMAN = 68129,
NPC_ASHTONGUE_PRIMALIST = 68096,
NPC_ASHTONGUE_WORKER = 68098,
NPC_UNBOUND_CENTURION = 68176,
NPC_UNBOUND_NIGHTLORD = 68174,
NPC_FREED_IMP = 68173,
NPC_UNBOUND_BONEMENDER = 68175,
NPC_UNBOUND_SUCCUBUS = 68205,
NPC_UNBOUND_SHIVARRA = 68206,
NPC_JUBEKA_SHADOWBREAKER = 70166,
NPC_DEMONIC_SOULWELL = 70052,
NPC_AKAMA = 68137,
NPC_ESSENCE_OF_ORDER = 68151,
NPC_KANRETHAD_EBONLOCKE = 69964,
NPC_PIT_LORD = 70075,
NPC_DOOM_LORD = 70073,
NPC_DEMONIC_GATEWAY = 70028,
NPC_KANRETHAD_WILD_IMP = 70071,
NPC_KANRETHAD_FEELHUNTER = 70072,
NPC_HARVEST_CREDIT = 68054, // also used like vehicle for cosmetic transformation (no data)
// Credits
NPC_NETHERSTORM_MEMORY = 68782,
NPC_BLADES_EDGE_MEMORY = 68783,
NPC_SHADOWMOON_MEMORY = 68780,
NPC_BLACK_TEMPLE_ENTRANCE = 68053,
};
enum iSpells
{
SPELL_TRUSTED_BY_ASHTONGUE = 134206,
SPELL_MEMORY_OF_THE_RELICVARY = 134210,
};
enum Data
{
STEP_ENTER_THE_BLACK_TEMPLE,
STEP_SEARCH_FOR_SIGNS,
STEP_FOLLOW_AKAMA,
STEP_UNCOVER_COUNCILS_PLAN,
STEP_DEFEAT_ESSENCE_OF_ORDER,
STEP_ESCAPE_SHRINE_OF_LOST_SOULS,
STEP_PLUNDER_THE_DEN_OF_MORTAL_DELIGHTS,
STEP_HEAD_OF_THE_TEMPLE_SUMMIT,
STEP_DEFEAT_KANRETHAD,
// Misc
PLAYER_DATA,
};
enum eActions
{
ACTION_START_INTRO,
ACTION_MOVE_TO_SANCTUM,
ACTION_KANRETHAD_DEFEATED,
ACTION_INIT_FLAME,
};
enum GameObjects
{
GO_ILLIDARI_SCROLL = 216364,
};
enum eTalks
{
TALK_INTRO,
TALK_SPECIAL_1,
TALK_SPECIAL_2,
TALK_SPECIAL_3,
TALK_SPECIAL_4,
TALK_SPECIAL_5,
TALK_SPECIAL_6,
TALK_SPECIAL_7,
TALK_SPECIAL_8,
};
enum Quests
{
QUEST_INFILTRATING_TO_BLACK_TEMPLE = 32325,
QUEST_SEEK_THE_SIGNAL = 32324,
};
const std::map<uint32, uint32> invOutlandSceneType =
{
{ 127, NPC_NETHERSTORM_MEMORY },
{ 128, NPC_BLADES_EDGE_MEMORY },
{ 129, NPC_SHADOWMOON_MEMORY },
};
#endif // PURSUING_THE_BLACK_HARVEST_SCENARIO_H_ | 412 | 0.650015 | 1 | 0.650015 | game-dev | MEDIA | 0.991729 | game-dev | 0.590299 | 1 | 0.590299 |
SlimeKnights/TinkersConstruct | 1,494 | src/main/java/slimeknights/tconstruct/tools/modifiers/ability/tool/DuelWieldingModifier.java | package slimeknights.tconstruct.tools.modifiers.ability.tool;
import slimeknights.tconstruct.common.TinkerTags;
import slimeknights.tconstruct.library.modifiers.ModifierEntry;
import slimeknights.tconstruct.library.modifiers.ModifierHooks;
import slimeknights.tconstruct.library.modifiers.hook.build.ToolStatsModifierHook;
import slimeknights.tconstruct.library.module.ModuleHookMap.Builder;
import slimeknights.tconstruct.library.tools.nbt.IToolContext;
import slimeknights.tconstruct.library.tools.stat.ModifierStatsBuilder;
import slimeknights.tconstruct.library.tools.stat.ToolStats;
public class DuelWieldingModifier extends OffhandAttackModifier implements ToolStatsModifierHook {
@Override
protected void registerHooks(Builder hookBuilder) {
super.registerHooks(hookBuilder);
hookBuilder.addHook(this, ModifierHooks.TOOL_STATS);
}
@Override
public void addToolStats(IToolContext context, ModifierEntry modifier, ModifierStatsBuilder builder) {
// on two handed tools, take a larger hit to attack damage, smaller to attack speed
if (context.hasTag(TinkerTags.Items.BROAD_TOOLS)) {
ToolStats.ATTACK_DAMAGE.multiplyAll(builder, 0.7);
ToolStats.ATTACK_SPEED.multiplyAll(builder, 0.9);
} else {
// on one handed tools, 80% on both
ToolStats.ATTACK_DAMAGE.multiplyAll(builder, 0.8);
ToolStats.ATTACK_SPEED.multiplyAll(builder, 0.8);
}
}
@Override
public boolean shouldDisplay(boolean advanced) {
return true;
}
}
| 412 | 0.652404 | 1 | 0.652404 | game-dev | MEDIA | 0.239003 | game-dev | 0.563591 | 1 | 0.563591 |
derkork/openscad-graph-editor | 2,512 | Refactorings/AddInvokableParametersRefactoring.cs | using System.Linq;
using OpenScadGraphEditor.Library;
using OpenScadGraphEditor.Nodes;
using OpenScadGraphEditor.Utils;
namespace OpenScadGraphEditor.Refactorings
{
public class AddInvokableParametersRefactoring : Refactoring
{
private readonly InvokableDescription _invokableDescription;
private readonly ParameterDescription[] _newParameters;
public AddInvokableParametersRefactoring(InvokableDescription invokableDescription,
ParameterDescription[] newParameters)
{
_invokableDescription = invokableDescription;
_newParameters = newParameters;
}
public override void PerformRefactoring(RefactoringContext context)
{
// find all nodes which are affected by this and make them refactorable
var affectedNodes = context.Project.FindAllReferencingNodes(_invokableDescription)
.ToList(); // avoid concurrent modification
// add the new parameters to the invokable description. Only do this AFTER
// we have made everything refactorable, otherwise the internal state of the graphs is outdated.
_newParameters.ForAll(it => _invokableDescription.Parameters.Add(it));
// walk over all references to the description
foreach (var referencingNode in affectedNodes)
{
// make the owning graph refactorable
var node = referencingNode.Node;
var nodeAsReference = referencingNode.NodeAsReference;
// setup ports for the new parameters
nodeAsReference.SetupPorts(_invokableDescription);
// prepare literal structures for the new parameters
var parameterIndex = _invokableDescription.Parameters.Count - _newParameters.Length;
for (var i = 0; i < _newParameters.Length; i++)
{
var inputPortIndex = nodeAsReference.GetParameterInputPort(parameterIndex + i);
if (inputPortIndex != -1)
{
node.BuildPortLiteral(PortId.Input(inputPortIndex));
}
var outputPortIndex = nodeAsReference.GetParameterOutputPort(parameterIndex + i);
if (outputPortIndex != -1)
{
node.BuildPortLiteral(PortId.Output(outputPortIndex));
}
}
}
}
}
} | 412 | 0.72928 | 1 | 0.72928 | game-dev | MEDIA | 0.487138 | game-dev | 0.917785 | 1 | 0.917785 |
InvadingOctopus/comedot | 10,522 | AutoLoad/GlobalInput.gd | ## AutoLoad
## Input event labels and global keyboard shortcuts
# class_name GlobalInput
extends Node
#region Input Actions & Events Constants
## Input event labels.
## See the Input Map in the Godot Project Settings for the default axes, buttons and keys assigned to each action.
## NOTE: This is NOT the same as the [Action] Resource which represent special actions performed by explicit in-game choices.
class Actions:
# TBD: Rename to "InputAction" or "InputEventName" etc. to disambiguate from Comedot-specific "special/explicit" [Action]s?
# The primary movement axes in most games. Gamepad Left Joystick, Gamepad D-Pad.
const moveLeft := &"moveLeft"
const moveRight := &"moveRight"
const moveUp := &"moveUp"
const moveDown := &"moveDown"
# Relative-movement controls in games where a character rotates left/right and "thrusts" forward or "reverses" backward.
# Also known as "tank controls", and used in games like Asteroids.
const turnLeft := &"turnLeft" ## Gamepad Right Joystick
const turnRight := &"turnRight" ## Gamepad Right Joystick
const moveForward := &"moveForward"
const moveBackward := &"moveBackward"
# A secondary axis for controlling a camera or aiming gun, cursor etc. Gamepad Right Joystick.
const aimLeft := &"aimLeft"
const aimRight := &"aimRight"
const aimUp := &"aimUp"
const aimDown := &"aimDown"
const jump := &"jump"
const fire := &"fire"
const interact := &"interact"
## Used for generating and detecting input events for an [Action], a Resource which represents an explicitly-chosen game-specific special ability, such as casting a spell.
## See [ActionControlComponent] & [ActionButton] etc.
## NOTE: This string should end in an underscore `_` to separate the prefix from the [member Action.name] which normally begins with a lowercase letter as well.
## Edit the Godot Project Settings' Input Map to add shortcuts for special [Actions] e.g `specialAction_dash`.
const specialActionPrefix := &"specialAction_" # TBD: Less ambiguous name? :')
const back := &"back"
const pause := &"pause"
const screenshot := &"screenshot"
const skipMusic := &"skipMusic"
const quickSave := &"quickSave"
const quickLoad := &"quickLoad"
const windowToggleAlwaysOnTop := &"windowToggleAlwaysOnTop"
const windowResizeTo1080 := &"windowResizeTo1080" ## 1920 x 1080
const windowResizeTo720 := &"windowResizeTo720" ## 1280 x 720
const debugWindow := &"debugWindow" ## Toggles the Debug Info Window.
const debugTest := &"debugTest" ## Activates [TestMode]
const debugBreak := &"debugBreak" ## Causes a debugging breakpoint.
const uiPrefix := &"ui_" ## The prefix that all Godot built-in UI input action names start with.
const accept := &"ui_accept"
const cancel := &"ui_cancel"
const select := &"ui_select" ## ALERT: This is Godot's built-in "UI Select" Input Action, which may NOT necessarily be a gamepad's Select button!
## List of input actions to be excluded from player customization in [InputActionsList] and other control remapping UI.
const excludedFromCustomization: Array[StringName] = [
back, pause,
windowToggleAlwaysOnTop, windowResizeTo1080, windowResizeTo720,
debugWindow, debugTest, debugBreak
]
static var allActions: Dictionary: ## Returns a list of all the input action `const` property names & values. NOTE: NOT updated during runtime!
get:
if not allActions: allActions = Actions.new().get_script().get_script_constant_map()
return allActions
## Replacements for certain strings in the text representations of InputEvent control names, such as "Keyboard" instead of "Physical".
const eventTextReplacements: Dictionary[String, String] = {
"Physical": "Keyboard",
}
#endregion
#region State
## May be set to `false` to disable the pause/unpause shortcut specific situations, such as during a Game Over screen or network UI.
var isPauseShortcutAllowed: bool = true
#endregion
#region Signals
@warning_ignore("unused_signal")
signal didAddInputEvent(inputAction: StringName, inputEvent: InputEvent) ## Emitted by [InputActionUI]
@warning_ignore("unused_signal")
signal didDeleteInputEvent(inputAction: StringName, inputEvent: InputEvent) ## Emitted by [InputActionEventUI]
#endregion
#region Global Events
func _enter_tree() -> void:
Debug.printAutoLoadLog("_enter_tree()")
## Global shortcuts including gamepad etc.
func _unhandled_input(event: InputEvent) -> void:
# TBD: Should we check `event` or [Input]?
if not event.is_action_type(): return
var isHandled: bool = false # Keep other scripts from eating our leftovers, e.g. prevent the Escape key for "Pause" also triggering a "Back" event or vice-versa.
# Game
if isPauseShortcutAllowed and not SceneManager.ongoingTransitionScene and Input.is_action_just_pressed(Actions.pause): # Prevent pausing during scene transitions
self.process_mode = Node.PROCESS_MODE_ALWAYS # TBD: HACK: Is this necessary?
SceneManager.togglePause()
isHandled = true
if isHandled: self.get_viewport().set_input_as_handled()
## Global keyboard shortcuts
func _unhandled_key_input(event: InputEvent) -> void:
# TBD: Should we check `event` or [Input]?
if not event.is_action_type(): return
var isHandled: bool = false # Keep other scripts from eating our leftovers, e.g. prevent the Escape key for "Pause" also triggering a "Back" event or vice-versa.
# NOTE: Mutually-exclusive events should be handled in if/elif/else pairs/sets
# Debugging, before any other actions are handled.
if Input.is_action_just_released(Actions.debugBreak):
Debug.printDebug("Debug Breakpoint Input Received")
breakpoint # TBD: Use `breakpoint` or `assert(false)`? `assert` also adds a message but only runs in debug builds.
# assert(false, "Debug Breakpoint Input Received")
isHandled = true
elif Input.is_action_just_released(Actions.debugWindow):
Debug.toggleDebugWindow()
isHandled = true
# Window
if Input.is_action_just_released(Actions.windowToggleAlwaysOnTop):
var isAlwaysOnTop: bool = DisplayServer.window_get_flag(DisplayServer.WINDOW_FLAG_ALWAYS_ON_TOP)
DisplayServer.window_set_flag(DisplayServer.WINDOW_FLAG_ALWAYS_ON_TOP, not isAlwaysOnTop) # `not` because it's a toggle.
GlobalUI.createTemporaryLabel(str("Window Always on Top: ", not isAlwaysOnTop))
get_viewport().set_input_as_handled() # TBD: Should we let these shortcuts affect other things?
isHandled = true
if Input.is_action_just_released(Actions.windowResizeTo720):
GlobalUI.setWindowSize(1280, 720)
get_viewport().set_input_as_handled() # TBD: Should we let these shortcuts affect other things?
isHandled = true
elif Input.is_action_just_released(Actions.windowResizeTo1080):
GlobalUI.setWindowSize(1920, 1080)
get_viewport().set_input_as_handled() # TBD: Should we let these shortcuts affect other things?
isHandled = true
# Save & Load
if event.is_action_released(GlobalInput.Actions.screenshot):
Global.screenshot()
isHandled = true
if event.is_action_released(GlobalInput.Actions.quickLoad): # TBD: Should Loading take precedence over Saving?
GameState.loadGame()
isHandled = true
elif event.is_action_released(GlobalInput.Actions.quickSave):
GameState.saveGame()
isHandled = true
if isHandled: self.get_viewport().set_input_as_handled()
## Generates a "fake" [InputEventAction] with the specified input action name.
## This [InputEventAction] may then be processed by any Component or other class as any other [method _input] event.
func generateInputEvent(inputActionName: StringName, pressed: bool = true, strength: float = 1 if pressed else 0) -> InputEvent:
if inputActionName.is_empty(): return null
var event: InputEventAction = InputEventAction.new()
event.action = inputActionName
event.pressed = pressed
event.strength = strength
Input.parse_input_event(event)
return event
#endregion
#region Helper Functions
## Returns a list of the textual representation of keys, buttons or other controls specified for an Input Action, such as "Space" for "jump".
## Trims redundant text such as " (Physical)"
func getInputEventText(action: StringName) -> PackedStringArray:
var strings: PackedStringArray
for event: InputEvent in InputMap.action_get_events(action):
strings.append(event.as_text().trim_suffix(" (Physical)"))
return strings
## Returns a list of the textual representation of keys, buttons or other controls specified for an Input Action, such as "Space" for "jump".
## Replaces redundant text such as "(Physical)" with "(Keyboard)" using the [constant eventTextReplacements] [Dictionary].
func getInputEventReplacedText(action: StringName) -> PackedStringArray:
var strings: PackedStringArray
for event: InputEvent in InputMap.action_get_events(action):
strings.append(Tools.replaceStrings(event.as_text(), GlobalInput.eventTextReplacements))
return strings
## Returns: `true` if [method Input.is_action_just_pressed] or [method Input.is_action_just_released].
func hasActionTransitioned(action: StringName) -> bool:
return Input.is_action_just_pressed(action) \
or Input.is_action_just_released(action)
## Returns `true` if an [InputEvent] was one of the "UI actions" built into Godot.
## ALERT: Only checks against a limited set of UI actions such as cancel/accept, next/previous, & directions.
## A jank workaround for Godot's lack of built-in API for a common task.
## @experimental
func isInputEventUIAction(event: InputEvent) -> bool:
# Checking strings like this is very jank but dummy Godot is dummy.
for eventName: StringName in [
&"ui_cancel", &"ui_accept", &"ui_select",
&"ui_focus_next", &"ui_focus_prev",
&"ui_page_up", &"ui_page_down",
&"ui_home", &"ui_end",
&"ui_left", &"ui_right",
&"ui_up", &"ui_down",
]:
if event.is_action(eventName): return true
# else
return false
## Returns all the player control input actions from [GlobalInput] that match a given [InputEvent].
## A jank workaround for Godot's lack of built-in API for a common task.
## WARNING: PERFORMANCE: May be too slow; avoid calling frequently!
## @experimental
func findActionsFromInputEvent(event: InputEvent) -> Array[StringName]:
if not event.is_action_type(): return []
# PERFORMANCE: GRRR: Since dummy Godot does not provide any direct way to get the input actions from an [InputEvent],
# we have to manually check every possibility... >:(
var inputActions: Array[StringName]
for propertyName: String in Actions.allActions:
if event.is_action(propertyName): inputActions.append(propertyName)
return inputActions
#endregion
| 412 | 0.865695 | 1 | 0.865695 | game-dev | MEDIA | 0.852348 | game-dev,desktop-app | 0.937455 | 1 | 0.937455 |
kamrann/BTUtilityPlugin | 2,380 | Source/BTUtilityPlugin/Public/Composites/BTComposite_Utility.h | // Copyright 2015 Cameron Angus. All Rights Reserved.
#pragma once
#include "BehaviorTree/BTCompositeNode.h"
#include "BTUtilityTypes.h"
#include "BTComposite_Utility.generated.h"
UENUM()
enum class EUtilitySelectionMethod: uint8
{
// The child with the highest utility value is always chosen
Priority,
// Selection probability is proportional to utility value
Proportional,
};
struct FBTUtilityMemory : public FBTCompositeMemory
{
/** ordering of child nodes for the current search activation (array is a list of child indexes arranged in execution order) */
FUtilityExecutionOrdering ExecutionOrdering;
};
class UBTDecorator_UtilityFunction;
/**
* Utility selector node.
* Utility Nodes choose at most one of their children to execute. The choice made is a function of the utility values of the children.
* A Utility Node will succeed if its chosen child succeeds, and will fail if its chosen child fails or if no child could be executed.
*/
UCLASS()
class BTUTILITYPLUGIN_API UBTComposite_Utility: public UBTCompositeNode
{
GENERATED_UCLASS_BODY()
public:
// Method used to determine child selection based on utility values
UPROPERTY(EditAnywhere, Category = "Utility")
EUtilitySelectionMethod SelectionMethod;
public:
virtual void InitializeMemory(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory, EBTMemoryInit::Type InitType) const override;
virtual uint16 GetInstanceMemorySize() const override;
virtual FString GetStaticDescription() const override;
protected:
/**
Attempt to find a utility function attached to the specified child.
@return The utility function decorator, or nullptr if none was found.
*/
const UBTDecorator_UtilityFunction* FindChildUtilityFunction(int32 ChildIndex) const;
/**
Invoke utility function for each child and store all the utility values.
@return true if at least one utility value is non-zero.
*/
bool EvaluateUtilityScores(FBehaviorTreeSearchData& SearchData, TArray< float >& OutScores) const;
protected:
virtual void NotifyNodeActivation(FBehaviorTreeSearchData& SearchData) const override;
public:
int32 GetNextChildHandler(struct FBehaviorTreeSearchData& SearchData, int32 PrevChild, EBTNodeResult::Type LastResult) const;
#if WITH_EDITOR
virtual FName GetNodeIconName() const override;
#endif
};
//////////////////////////////////////////////////////////////////////////
// Inlines
| 412 | 0.983853 | 1 | 0.983853 | game-dev | MEDIA | 0.865633 | game-dev | 0.965881 | 1 | 0.965881 |
KassuK1/BlackOut | 6,556 | src/main/java/kassuk/addon/blackout/utils/SettingUtils.java | package kassuk.addon.blackout.utils;
import kassuk.addon.blackout.enums.RotationType;
import kassuk.addon.blackout.enums.SwingState;
import kassuk.addon.blackout.enums.SwingType;
import kassuk.addon.blackout.globalsettings.*;
import meteordevelopment.meteorclient.systems.modules.Modules;
import meteordevelopment.meteorclient.utils.Utils;
import net.minecraft.util.Hand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Box;
import net.minecraft.util.math.Direction;
import net.minecraft.util.math.Vec3d;
import java.util.function.Predicate;
/**
* @author OLEPOSSU
*/
public class SettingUtils {
private static final FacingSettings facing = Modules.get().get(FacingSettings.class);
private static final RangeSettings range = Modules.get().get(RangeSettings.class);
private static final RaytraceSettings raytrace = Modules.get().get(RaytraceSettings.class);
private static final RotationSettings rotation = Modules.get().get(RotationSettings.class);
private static final ServerSettings server = Modules.get().get(ServerSettings.class);
private static final SwingSettings swing = Modules.get().get(SwingSettings.class);
// Range
public static void registerAttack(Box bb) {range.registerAttack(bb);}
public static double getPlaceRange() {
return range.placeRange.get();
}
public static double getPlaceWallsRange() {
return range.placeRangeWalls.get();
}
public static double getAttackRange() {
return range.attackRange.get();
}
public static double getAttackWallsRange() {
return range.attackRangeWalls.get();
}
public static double getMineRange() {
return range.miningRange.get();
}
public static double getMineWallsRange() {
return range.miningRangeWalls.get();
}
public static double placeRangeTo(BlockPos pos) {return range.placeRangeTo(pos, null);}
public static boolean inPlaceRange(BlockPos pos) {return range.inPlaceRange(pos, null);}
public static boolean inPlaceRange(BlockPos pos, Vec3d from) {
return range.inPlaceRange(pos, from);
}
public static boolean inPlaceRangeNoTrace(BlockPos pos) {
return range.inPlaceRangeNoTrace(pos, null);
}
public static boolean inPlaceRangeNoTrace(BlockPos pos, Vec3d from) {
return range.inPlaceRangeNoTrace(pos, from);
}
public static boolean inAttackRange(Box bb) {
return range.inAttackRange(bb, null);
}
public static boolean inAttackRange(Box bb, Vec3d from) {
return range.inAttackRange(bb, from);
}
public static double mineRangeTo(BlockPos pos) {return range.miningRangeTo(pos, null);}
public static boolean inMineRange(BlockPos pos) {
return range.inMineRange(pos);
}
public static boolean inMineRangeNoTrace(BlockPos pos) {
return range.inMineRangeNoTrace(pos);
}
public static boolean inAttackRangeNoTrace(Box bb, double eyeHeight, Vec3d feet) {return range.inAttackRangeNoTrace(bb, feet, null);}
public static boolean inAttackRangeNoTrace(Box bb, double eyeHeight, Vec3d feet, Vec3d from) {return range.inAttackRangeNoTrace(bb, feet, from);}
public static double attackRangeTo(Box bb, Vec3d feet) {return range.attackRangeTo(bb, feet, null, true);}
// Rotate
public static boolean startMineRot() {
return rotation.startMineRot();
}
public static boolean endMineRot() {
return rotation.endMineRot();
}
public static boolean shouldVanillaRotate() {return rotation.vanillaRotation.get();}
public static boolean shouldRotate(RotationType type) {
return rotation.shouldRotate(type);
}
public static boolean rotationCheck(Box box, RotationType type) {return rotation.rotationCheck(box, type);}
// Swing
public static void swing(SwingState state, SwingType type, Hand hand) {
swing.swing(state, type, hand);
}
public static void mineSwing(SwingSettings.MiningSwingState state) {
swing.mineSwing(state);
}
// Facing
public static PlaceData getPlaceData(BlockPos pos) {return facing.getPlaceData(pos, true);}
public static PlaceData getPlaceDataANDDir(BlockPos pos, Predicate<Direction> predicate) {return facing.getPlaceDataAND(pos, predicate, null, true);}
public static PlaceData getPlaceDataANDPos(BlockPos pos, Predicate<BlockPos> predicate) {return facing.getPlaceDataAND(pos, null, predicate,true);}
public static PlaceData getPlaceDataAND(BlockPos pos, Predicate<Direction> predicateDir, Predicate<BlockPos> predicate) {return facing.getPlaceDataAND(pos, predicateDir, predicate,true);}
public static PlaceData getPlaceDataOR(BlockPos pos, Predicate<BlockPos> predicate) {return facing.getPlaceDataOR(pos, predicate, true);}
public static PlaceData getPlaceData(BlockPos pos, boolean ignoreContainers) {return facing.getPlaceData(pos, ignoreContainers);}
public static PlaceData getPlaceDataANDDir(BlockPos pos, Predicate<Direction> predicate, boolean ignoreContainers) {return facing.getPlaceDataAND(pos, predicate, null, ignoreContainers);}
public static PlaceData getPlaceDataANDPos(BlockPos pos, Predicate<BlockPos> predicate, boolean ignoreContainers) {return facing.getPlaceDataAND(pos, null, predicate, ignoreContainers);}
public static PlaceData getPlaceDataAND(BlockPos pos, Predicate<Direction> predicateDir, Predicate<BlockPos> predicate, boolean ignoreContainers) {return facing.getPlaceDataAND(pos, predicateDir, predicate, ignoreContainers);}
public static PlaceData getPlaceDataOR(BlockPos pos, Predicate<BlockPos> predicate, boolean ignoreContainers) {return facing.getPlaceDataOR(pos, predicate, ignoreContainers);}
public static Direction getPlaceOnDirection(BlockPos pos) {
return facing.getPlaceOnDirection(pos);
}
// Raytracing
public static boolean shouldPlaceTrace() {
return raytrace.placeTrace.get();
}
public static boolean shouldAttackTrace() {return raytrace.attackTrace.get();}
public static boolean placeTrace(BlockPos pos) {
return !shouldPlaceTrace() || raytrace.placeTrace(pos);
}
public static boolean attackTrace(Box bb) {
return !shouldAttackTrace() || raytrace.attackTrace(bb);
}
// Server
public static boolean oldDamage() {
return server.oldVerDamage.get();
}
public static boolean oldCrystals() {
return server.oldVerCrystals.get();
}
public static boolean cc() {
return server.cc.get();
}
}
| 412 | 0.553038 | 1 | 0.553038 | game-dev | MEDIA | 0.710539 | game-dev | 0.831501 | 1 | 0.831501 |
BenediktAlkin/SongTaggerForSpotify | 1,643 | Backend/Entities/GraphNodes/FilterRangeNode.cs | using System.Linq;
namespace Backend.Entities.GraphNodes
{
public abstract class FilterRangeNode : GraphNode
{
private int? valueFrom;
public int? ValueFrom
{
get => valueFrom;
set
{
if (value == valueFrom) return;
SetProperty(ref valueFrom, value, nameof(ValueFrom));
OutputResult = null;
PropagateForward(gn => gn.ClearResult(), applyToSelf: false);
}
}
private int? valueTo;
public int? ValueTo
{
get => valueTo;
set
{
if (value == valueTo) return;
SetProperty(ref valueTo, value, nameof(ValueTo));
OutputResult = null;
PropagateForward(gn => gn.ClearResult(), applyToSelf: false);
}
}
protected override bool CanAddInput(GraphNode input) => !Inputs.Any();
protected override void MapInputToOutput()
{
if (ValueFrom != null && ValueTo != null)
OutputResult = InputResult[0].Where(t => ValueFrom <= GetValue(t) && GetValue(t) <= ValueTo).ToList();
else if (ValueFrom != null)
OutputResult = InputResult[0].Where(t => ValueFrom <= GetValue(t)).ToList();
else if (ValueTo != null)
OutputResult = InputResult[0].Where(t => GetValue(t) <= ValueTo).ToList();
else
OutputResult = InputResult[0];
}
protected abstract int? GetValue(Track t);
public override bool IsValid => true;
}
}
| 412 | 0.893217 | 1 | 0.893217 | game-dev | MEDIA | 0.298756 | game-dev | 0.959824 | 1 | 0.959824 |
sandstranger/Underworld-Exporter-Android | 1,610 | Assets/com.unity.uiextensions/Runtime/Scripts/ToolTips/BoundTooltip/BoundTooltipItem.cs | ///Credit Martin Nerurkar // www.martin.nerurkar.de // www.sharkbombs.com
///Sourced from - http://www.sharkbombs.com/2015/02/10/tooltips-with-the-new-unity-ui-ugui/
namespace UnityEngine.UI.Extensions
{
[AddComponentMenu("UI/Extensions/Bound Tooltip/Bound Tooltip Item")]
public class BoundTooltipItem : MonoBehaviour
{
public bool IsActive
{
get
{
return gameObject.activeSelf;
}
}
public UnityEngine.UI.Text TooltipText;
public Vector3 ToolTipOffset;
void Awake()
{
instance = this;
if(!TooltipText) TooltipText = GetComponentInChildren<Text>();
HideTooltip();
}
public void ShowTooltip(string text, Vector3 pos)
{
if (TooltipText.text != text)
TooltipText.text = text;
transform.position = pos + ToolTipOffset;
gameObject.SetActive(true);
}
public void HideTooltip()
{
gameObject.SetActive(false);
}
// Standard Singleton Access
private static BoundTooltipItem instance;
public static BoundTooltipItem Instance
{
get
{
if (instance == null)
{
#if UNITY_2023_1_OR_NEWER
instance = GameObject.FindFirstObjectByType<BoundTooltipItem>();
#else
instance = GameObject.FindObjectOfType<BoundTooltipItem>();
#endif
}
return instance;
}
}
}
}
| 412 | 0.849122 | 1 | 0.849122 | game-dev | MEDIA | 0.983768 | game-dev | 0.963973 | 1 | 0.963973 |
DestinyItemManager/DIM | 10,805 | src/app/destiny1/loadout-builder/utils.ts | import { D1_StatHashes, D1BucketHashes } from 'app/search/d1-known-values';
import { isEmpty, mapValues, uniqBy } from 'app/utils/collections';
import { itemCanBeEquippedBy } from 'app/utils/item-utils';
import { BucketHashes } from 'data/d2/generated-enums';
import { maxBy } from 'es-toolkit';
import { D1Item } from '../../inventory/item-types';
import { D1Store, DimStore } from '../../inventory/store-types';
import { D1StatHashes } from '../d1-manifest-types';
import { Vendor } from '../vendors/vendor.service';
import {
ArmorSet,
ArmorTypes,
D1ItemWithNormalStats,
ItemBucket,
LockedPerkHash,
SetType,
} from './types';
export interface ItemWithBonus {
item: D1ItemWithNormalStats;
bonusType: string;
}
function getBonusType(armorpiece: D1ItemWithNormalStats): string {
if (!armorpiece.normalStats) {
return '';
}
return (
(armorpiece.normalStats[D1StatHashes.Intellect].bonus > 0 ? 'int ' : '') +
(armorpiece.normalStats[D1StatHashes.Discipline].bonus > 0 ? 'dis ' : '') +
(armorpiece.normalStats[D1StatHashes.Strength].bonus > 0 ? 'str' : '')
);
}
function getBestItem(
armor: D1ItemWithNormalStats[],
stats: number[],
type: string,
scaleTypeArg: 'base' | 'scaled',
nonExotic = false,
): ItemWithBonus {
// for specific armor (Helmet), look at stats (int/dis), return best one.
return {
item: maxBy(armor, (o) => {
if (nonExotic && o.isExotic) {
return 0;
}
let bonus = 0;
let total = 0;
for (const stat of stats) {
const scaleType = o.rarity === 'Rare' ? 'base' : scaleTypeArg;
if (o.normalStats) {
const normalStats = o.normalStats[stat];
total += normalStats[scaleType];
bonus = normalStats.bonus;
}
}
return total + bonus;
})!,
bonusType: type,
};
}
export function calcArmorStats(
pieces: ItemWithBonus[],
stats: ArmorSet['stats'],
scaleTypeArg: 'base' | 'scaled',
) {
for (const armor of pieces) {
const int = armor.item.normalStats![D1StatHashes.Intellect];
const dis = armor.item.normalStats![D1StatHashes.Discipline];
const str = armor.item.normalStats![D1StatHashes.Strength];
const scaleType = armor.item.rarity === 'Rare' ? 'base' : scaleTypeArg;
// Mark of the Sunforged, Stormcaller Bond and Nightstalker cloak have special fixed stats
// that do not scale correctly as the scaling is currently implemented.
// See https://github.com/DestinyItemManager/DIM/issues/5191 for details
if ([2820418554, 2122538507, 2300914892].includes(armor.item.hash)) {
stats[D1StatHashes.Intellect].value += int.base;
} else {
stats[D1StatHashes.Intellect].value += int[scaleType];
stats[D1StatHashes.Discipline].value += dis[scaleType];
stats[D1StatHashes.Strength].value += str[scaleType];
}
switch (armor.bonusType) {
case 'int':
stats[D1StatHashes.Intellect].value += int.bonus;
break;
case 'dis':
stats[D1StatHashes.Discipline].value += dis.bonus;
break;
case 'str':
stats[D1StatHashes.Strength].value += str.bonus;
break;
}
}
}
export function getBonusConfig(armor: ArmorSet['armor']): { [armorType in ArmorTypes]: string } {
return mapValues(armor, (armorPiece) => armorPiece.bonusType);
}
export function genSetHash(armorPieces: ItemWithBonus[]) {
let hash = '';
for (const armorPiece of armorPieces) {
hash += armorPiece.item.id;
}
return hash;
}
export function getBestArmor(
bucket: ItemBucket,
vendorBucket: ItemBucket,
locked: { [armorType in ArmorTypes]: D1ItemWithNormalStats | null },
excluded: D1Item[],
lockedPerks: { [armorType in ArmorTypes]: LockedPerkHash },
scaleTypeArg: 'base' | 'scaled',
includeVendors = false,
fullMode = false,
) {
const statHashes = [
{ stats: [D1StatHashes.Intellect, D1StatHashes.Discipline], type: 'intdis' },
{ stats: [D1StatHashes.Intellect, D1StatHashes.Strength], type: 'intstr' },
{ stats: [D1StatHashes.Discipline, D1StatHashes.Strength], type: 'disstr' },
{ stats: [D1StatHashes.Intellect], type: 'int' },
{ stats: [D1StatHashes.Discipline], type: 'dis' },
{ stats: [D1StatHashes.Strength], type: 'str' },
];
const armor: Partial<Record<ArmorTypes, ItemWithBonus[]>> = {};
let best: { item: D1ItemWithNormalStats; bonusType: string }[] = [];
let curbest;
let bestCombs: { item: D1ItemWithNormalStats; bonusType: string }[];
const excludedIndices = new Set(excluded.map((i) => i.index));
for (const armortypestr in bucket) {
const armortype = parseInt(armortypestr, 10) as ArmorTypes;
const combined = includeVendors
? bucket[armortype].concat(vendorBucket[armortype])
: bucket[armortype];
const lockedItem = locked[armortype];
if (lockedItem) {
best = [{ item: lockedItem, bonusType: getBonusType(lockedItem) }];
} else {
best = [];
let hasPerks: (item: D1Item) => boolean = (_i) => true;
if (!isEmpty(lockedPerks[armortype])) {
const lockedPerkKeys = Object.keys(lockedPerks[armortype]).map((k) => parseInt(k, 10));
const andPerkHashes = lockedPerkKeys
.filter((perkHash) => lockedPerks[armortype][perkHash].lockType === 'and')
.map(Number);
const orPerkHashes = lockedPerkKeys
.filter((perkHash) => lockedPerks[armortype][perkHash].lockType === 'or')
.map(Number);
hasPerks = (item) => {
if (!orPerkHashes.length && !andPerkHashes.length) {
return true;
}
function matchNode(perkHash: number) {
return item.talentGrid?.nodes.some((n) => n.hash === perkHash);
}
return Boolean(
(orPerkHashes.length && orPerkHashes.some(matchNode)) ||
(andPerkHashes.length && andPerkHashes.every(matchNode)),
);
};
}
// Filter out excluded and non-wanted perks
const filtered = combined.filter(
(item) => !excludedIndices.has(item.index) && hasPerks(item), // Not excluded and has the correct locked perks
);
if (filtered.length === 0) {
continue; // No items in this bucket
}
for (const [index, hash] of statHashes.entries()) {
if (!fullMode && index > 2) {
continue;
}
curbest = getBestItem(filtered, hash.stats, hash.type, scaleTypeArg);
best.push(curbest);
// add the best -> if best is exotic -> get best legendary
if (curbest.item.isExotic && armortype !== BucketHashes.ClassArmor) {
best.push(getBestItem(filtered, hash.stats, hash.type, scaleTypeArg, true));
}
}
}
bestCombs = [];
for (const obj of uniqBy(best, (o) => o.item.index)) {
obj.bonusType = getBonusType(obj.item);
if (obj.bonusType === '') {
bestCombs.push({ item: obj.item, bonusType: '' });
}
if (obj.bonusType.includes('int')) {
bestCombs.push({ item: obj.item, bonusType: 'int' });
}
if (obj.bonusType.includes('dis')) {
bestCombs.push({ item: obj.item, bonusType: 'dis' });
}
if (obj.bonusType.includes('str')) {
bestCombs.push({ item: obj.item, bonusType: 'str' });
}
}
armor[armortype] = bestCombs;
}
return armor;
}
export function getActiveHighestSets(
setMap: { [setHash: number]: SetType },
activeSets: string,
): SetType[] {
let count = 0;
const topSets: SetType[] = [];
for (const setType of Object.values(setMap)) {
if (count >= 10) {
continue;
}
if (setType.tiers[activeSets]) {
topSets.push(setType);
count += 1;
}
}
return topSets;
}
export function mergeBuckets<T extends any[]>(
bucket1: { [armorType in ArmorTypes]: T },
bucket2: { [armorType in ArmorTypes]: T },
) {
const merged: Partial<{ [armorType in ArmorTypes]: T }> = {};
for (const [type, bucket] of Object.entries(bucket1)) {
merged[parseInt(type, 10) as ArmorTypes] = bucket.concat(
bucket2[parseInt(type, 10) as ArmorTypes],
) as T;
}
return merged as { [armorType in ArmorTypes]: T };
}
export function loadVendorsBucket(
currentStore: DimStore,
vendors?: {
[vendorHash: number]: Vendor;
},
): ItemBucket {
if (!vendors) {
return {
[BucketHashes.Helmet]: [],
[BucketHashes.Gauntlets]: [],
[BucketHashes.ChestArmor]: [],
[BucketHashes.LegArmor]: [],
[BucketHashes.ClassArmor]: [],
[D1BucketHashes.Artifact]: [],
[BucketHashes.Ghost]: [],
};
}
return Object.values(vendors)
.map((vendor) =>
getBuckets(
vendor.allItems
.filter(
(i) =>
i.item.stats &&
i.item.primaryStat?.statHash === D1_StatHashes.Defense &&
itemCanBeEquippedBy(i.item, currentStore),
)
.map((i) => i.item),
),
)
.reduce(mergeBuckets);
}
export function loadBucket(currentStore: DimStore, stores: D1Store[]): ItemBucket {
return stores
.map((store) =>
getBuckets(
store.items.filter(
(i) =>
i.stats &&
i.primaryStat?.statHash === D1_StatHashes.Defense &&
itemCanBeEquippedBy(i, currentStore),
),
),
)
.reduce(mergeBuckets);
}
function getBuckets(items: D1Item[]): ItemBucket {
return {
[BucketHashes.Helmet]: items
.filter((item) => item.bucket.hash === BucketHashes.Helmet)
.map(normalizeStats),
[BucketHashes.Gauntlets]: items
.filter((item) => item.bucket.hash === BucketHashes.Gauntlets)
.map(normalizeStats),
[BucketHashes.ChestArmor]: items
.filter((item) => item.bucket.hash === BucketHashes.ChestArmor)
.map(normalizeStats),
[BucketHashes.LegArmor]: items
.filter((item) => item.bucket.hash === BucketHashes.LegArmor)
.map(normalizeStats),
[BucketHashes.ClassArmor]: items
.filter((item) => item.bucket.hash === BucketHashes.ClassArmor)
.map(normalizeStats),
[D1BucketHashes.Artifact]: items
.filter((item) => item.bucket.hash === D1BucketHashes.Artifact)
.map(normalizeStats),
[BucketHashes.Ghost]: items
.filter((item) => item.bucket.hash === BucketHashes.Ghost)
.map(normalizeStats),
};
}
function normalizeStats(item: D1ItemWithNormalStats) {
item.normalStats = {};
if (item.stats) {
for (const stat of item.stats) {
item.normalStats[stat.statHash] = {
statHash: stat.statHash,
base: stat.base,
scaled: stat.scaled ? stat.scaled.min : 0,
bonus: stat.bonus,
split: stat.split || 0,
qualityPercentage: stat.qualityPercentage ? stat.qualityPercentage.min : 0,
};
}
}
return item;
}
| 412 | 0.814142 | 1 | 0.814142 | game-dev | MEDIA | 0.940564 | game-dev | 0.971411 | 1 | 0.971411 |
anael-seghezzi/Maratis-4 | 1,542 | 3rdparty/SDL2/src/main/psp/SDL_psp_main.c | /*
SDL_psp_main.c, placed in the public domain by Sam Lantinga 3/13/14
*/
#include "SDL_main.h"
#include <pspkernel.h>
#include <pspdebug.h>
#include <pspsdk.h>
#include <pspthreadman.h>
#include <stdlib.h>
#include <stdio.h>
/* If application's main() is redefined as SDL_main, and libSDLmain is
linked, then this file will create the standard exit callback,
define the PSP_MODULE_INFO macro, and exit back to the browser when
the program is finished.
You can still override other parameters in your own code if you
desire, such as PSP_HEAP_SIZE_KB, PSP_MAIN_THREAD_ATTR,
PSP_MAIN_THREAD_STACK_SIZE, etc.
*/
PSP_MODULE_INFO("SDL App", 0, 1, 1);
int sdl_psp_exit_callback(int arg1, int arg2, void *common)
{
exit(0);
return 0;
}
int sdl_psp_callback_thread(SceSize args, void *argp)
{
int cbid;
cbid = sceKernelCreateCallback("Exit Callback",
sdl_psp_exit_callback, NULL);
sceKernelRegisterExitCallback(cbid);
sceKernelSleepThreadCB();
return 0;
}
int sdl_psp_setup_callbacks(void)
{
int thid = 0;
thid = sceKernelCreateThread("update_thread",
sdl_psp_callback_thread, 0x11, 0xFA0, 0, 0);
if(thid >= 0)
sceKernelStartThread(thid, 0, 0);
return thid;
}
int main(int argc, char *argv[])
{
pspDebugScreenInit();
sdl_psp_setup_callbacks();
/* Register sceKernelExitGame() to be called when we exit */
atexit(sceKernelExitGame);
SDL_SetMainReady();
(void)SDL_main(argc, argv);
return 0;
}
| 412 | 0.798679 | 1 | 0.798679 | game-dev | MEDIA | 0.549311 | game-dev | 0.522945 | 1 | 0.522945 |
WorldWindLabs/SpaceBirds | 23,550 | Modified Web WorldWind source/src/util/Tile.js | /*
* Copyright (C) 2014 United States Government as represented by the Administrator of the
* National Aeronautics and Space Administration. All Rights Reserved.
*/
/**
* @exports Tile
* @version $Id: Tile.js 3125 2015-05-29 14:43:25Z tgaskins $
*/
define([
'../error/ArgumentError',
'../geom/BoundingBox',
'../util/Logger',
'../geom/Sector',
'../geom/Vec3',
'../util/WWUtil'
],
function (ArgumentError,
BoundingBox,
Logger,
Sector,
Vec3,
WWUtil) {
"use strict";
/**
* Constructs a tile for a specified sector, level, row and column.
* @alias Tile
* @constructor
* @classdesc Represents a tile of terrain or imagery.
* Provides a base class for texture tiles used by tiled image layers and elevation tiles used by elevation models.
* Applications typically do not interact with this class.
* @param {Sector} sector The sector represented by this tile.
* @param {Level} level This tile's level in a tile pyramid.
* @param {Number} row This tile's row in the specified level in a tile pyramid.
* @param {Number} column This tile's column in the specified level in a tile pyramid.
* @throws {ArgumentError} If the specified sector or level is null or undefined or the row or column arguments
* are less than zero.
*/
var Tile = function (sector, level, row, column) {
if (!sector) {
throw new ArgumentError(
Logger.logMessage(Logger.LEVEL_SEVERE, "Tile", "constructor", "missingSector"));
}
if (!level) {
throw new ArgumentError(
Logger.logMessage(Logger.LEVEL_SEVERE, "Tile", "constructor",
"The specified level is null or undefined."));
}
if (row < 0 || column < 0) {
throw new ArgumentError(
Logger.logMessage(Logger.LEVEL_SEVERE, "Tile", "constructor",
"The specified row or column is less than zero."));
}
/**
* The sector represented by this tile.
* @type {Sector}
* @readonly
*/
this.sector = sector;
/**
* The level at which this tile lies in a tile pyramid.
* @type {Number}
* @readonly
*/
this.level = level;
/**
* The row in this tile's level in which this tile lies in a tile pyramid.
* @type {Number}
* @readonly
*/
this.row = row;
/**
* The column in this tile's level in which this tile lies in a tile pyramid.
* @type {Number}
* @readonly
*/
this.column = column;
/**
* The width in pixels or cells of this tile's associated resource.
* @type {Number}
*/
this.tileWidth = level.tileWidth;
/**
* The height in pixels or cells of this tile's associated resource.
* @type {Number}
*/
this.tileHeight = level.tileHeight;
/**
* The size in radians of pixels or cells of this tile's associated resource.
* @type {Number}
*/
this.texelSize = level.texelSize;
/**
* A key that uniquely identifies this tile within a level set.
* @type {String}
* @readonly
*/
this.tileKey = level.levelNumber.toString() + "." + row.toString() + "." + column.toString();
/**
* The Cartesian bounding box of this tile.
* @type {BoundingBox}
*/
this.extent = null;
/**
* The tile's local origin in model coordinates. Any model coordinate points associates with the tile
* should be relative to this point.
* @type {Vec3}
*/
this.referencePoint = null;
/**
* This tile's opacity.
* @type {Number}
* @default 1
*/
this.opacity = 1;
// Internal use only. Intentionally not documented.
this.samplePoints = null;
// Internal use only. Intentionally not documented.
this.sampleElevations = null;
// Internal use only. Intentionally not documented.
this.updateTimestamp = null;
// Internal use only. Intentionally not documented.
this.updateVerticalExaggeration = null;
// Internal use only. Intentionally not documented.
this.updateGlobeStateKey = null;
};
/**
* Indicates whether this tile is equivalent to a specified tile.
* @param {Tile} that The tile to check equivalence with.
* @returns {boolean} true if this tile is equivalent to the specified one, false if
* they are not equivalent or the specified tile is null or undefined.
*/
Tile.prototype.isEqual = function (that) {
if (!that)
return false;
if (!that.tileKey)
return false;
return this.tileKey == that.tileKey;
};
/**
* Returns the size of this tile in bytes.
* @returns {Number} The size of this tile in bytes.
*/
Tile.prototype.size = function () {
return 4 // child pointer
+ (4 + 32) // sector
+ 4 //level pointer (the level is common to the layer or tessellator so is not included here)
+ 8 // row and column
+ 8 // texel size
+ (4 + 32) // reference point
+ (4 + 676) // bounding box
+ 8 // min and max height
+ (4 + 32) // nearest point
+ 8; // extent timestamp and vertical exaggeration
};
/**
* Computes an approximate distance from this tile to a specified vector.
* @param {Vec3} vector The vector to compute the distance to.
* @returns {number} The distance between this tile and the vector.
* @throws {ArgumentError} If the specified vector is null or undefined.
*/
Tile.prototype.distanceTo = function (vector) {
if (!vector) {
throw new ArgumentError(
Logger.logMessage(Logger.LEVEL_SEVERE, "Tile", "distanceTo", "missingVector"));
}
var px = vector[0], py = vector[1], pz = vector[2],
dx, dy, dz,
points = this.samplePoints,
distance = Number.POSITIVE_INFINITY;
for (var i = 0, len = points.length; i < len; i += 3) {
dx = px - points[i];
dy = py - points[i + 1];
dz = pz - points[i + 2];
distance = Math.min(distance, dx * dx + dy * dy + dz * dz); // minimum squared distance
}
return Math.sqrt(distance);
};
/**
* Returns the four children formed by subdividing this tile.
* @param {Level} level The level of the children.
* @param {TileFactory} tileFactory The tile factory to use to create the children.
* @returns {Tile[]} An array containing the four child tiles.
* @throws {ArgumentError} If the specified tile factory or level is null or undefined.
*/
Tile.prototype.subdivide = function (level, tileFactory) {
if (!level) {
throw new ArgumentError(
Logger.logMessage(Logger.LEVEL_SEVERE, "Tile", "subdivide",
"The specified level is null or undefined."));
}
if (!tileFactory) {
throw new ArgumentError(
Logger.logMessage(Logger.LEVEL_SEVERE, "Tile", "subdivide",
"The specified tile factory is null or undefined."));
}
var latMin = this.sector.minLatitude,
latMax = this.sector.maxLatitude,
latMid = this.sector.centroidLatitude(),
lonMin = this.sector.minLongitude,
lonMax = this.sector.maxLongitude,
lonMid = this.sector.centroidLongitude(),
subRow,
subCol,
childSector,
children = [];
subRow = 2 * this.row;
subCol = 2 * this.column;
childSector = new Sector(latMin, latMid, lonMin, lonMid);
children.push(tileFactory.createTile(childSector, level, subRow, subCol));
subRow = 2 * this.row;
subCol = 2 * this.column + 1;
childSector = new Sector(latMin, latMid, lonMid, lonMax);
children.push(tileFactory.createTile(childSector, level, subRow, subCol));
subRow = 2 * this.row + 1;
subCol = 2 * this.column;
childSector = new Sector(latMid, latMax, lonMin, lonMid);
children.push(tileFactory.createTile(childSector, level, subRow, subCol));
subRow = 2 * this.row + 1;
subCol = 2 * this.column + 1;
childSector = new Sector(latMid, latMax, lonMid, lonMax);
children.push(tileFactory.createTile(childSector, level, subRow, subCol));
return children;
};
/**
* Returns the four children formed by subdividing this tile, drawing those children from a specified cache
* if they exist there.
* @param {Level} level The level of the children.
* @param {TileFactory} tileFactory The tile factory to use to create the children.
* @param {MemoryCache} cache A memory cache that may contain pre-existing child tiles. If non-null, the
* cache is checked for a child collection prior to creating that tile. If one exists
* in the cache it is returned rather than creating a new collection of children. If a new collection is
* created, it is added to the cache.
* @returns {Tile[]} An array containing the four tiles.
* @throws {ArgumentError} If the specified tile factory or level is null or undefined.
*/
Tile.prototype.subdivideToCache = function (level, tileFactory, cache) {
if (!level) {
throw new ArgumentError(
Logger.logMessage(Logger.LEVEL_SEVERE, "Tile", "subdivideToCache",
"The specified level is null or undefined."));
}
if (!tileFactory) {
throw new ArgumentError(
Logger.logMessage(Logger.LEVEL_SEVERE, "Tile", "subdivideToCache",
"The specified tile factory is null or undefined."));
}
var childList = cache ? cache.entryForKey(this.tileKey) : null;
if (!childList) {
childList = this.subdivide(level, tileFactory);
if (childList && cache) {
cache.putEntry(this.tileKey, childList, 4 * childList[0].size());
}
}
return childList;
};
/**
* Indicates whether this tile should be subdivided based on the current navigation state and a specified
* detail factor.
* @param {DrawContext} dc The current draw context.
* @param {Number} detailFactor The detail factor to consider.
* @returns {boolean} true If the tile should be subdivided, otherwise false.
*/
Tile.prototype.mustSubdivide = function (dc, detailFactor) {
// Split when the cell height (length of a texel) becomes greater than the specified fraction of the eye
// distance. The fraction is specified as a power of 10. For example, a detail factor of 3 means split when
// the cell height becomes more than one thousandth of the eye distance. Another way to say it is, use the
// current tile if the cell height is less than the specified fraction of the eye distance.
//
// Note: It's tempting to instead compare a screen pixel size to the texel size, but that calculation is
// window-size dependent and results in selecting an excessive number of tiles when the window is large.
var cellSize = dc.globe.equatorialRadius * this.texelSize,
distance = this.distanceTo(dc.navigatorState.eyePoint),
pixelSize = dc.navigatorState.pixelSizeAtDistance(distance);
return cellSize > Math.max(detailFactor * pixelSize, 0.5);
};
/**
* Updates this tile's frame-dependent properties as necessary, according to the specified draw context.
* <p>
* The tile's frame-dependent properties, include the extent (bounding volume). These properties are dependent
* on the tile's sector and the elevation values currently in memory, and change when those dependencies change.
* Therefore <code>update</code> must be called once per frame before the extent and any other frame-dependent
* properties are used. <code>update</code> intelligently determines when it is necessary to recompute these
* properties, and does nothing if the state of all dependencies has not changed since the last call.
* @param {DrawContext} dc The current draw context.
*/
Tile.prototype.update = function (dc) {
var elevationTimestamp = dc.globe.elevationTimestamp(),
verticalExaggeration = dc.verticalExaggeration,
globeStateKey = dc.globeStateKey;
if (this.updateTimestamp != elevationTimestamp
|| this.updateVerticalExaggeration != verticalExaggeration
|| this.updateGlobeStateKey != globeStateKey) {
this.doUpdate(dc);
dc.frameStatistics.incrementTileUpdateCount(1);
// Set the geometry extent to the globe's elevation timestamp on which the geometry is based. This
// ensures that the geometry timestamp can be reliably compared to the elevation timestamp in subsequent
// frames.
this.updateTimestamp = elevationTimestamp;
this.updateVerticalExaggeration = verticalExaggeration;
this.updateGlobeStateKey = globeStateKey;
}
};
/**
* Updates this tile's frame-dependent properties according to the specified draw context.
* @param {DrawContext} dc The current draw context.
* @protected
*/
Tile.prototype.doUpdate = function (dc) {
// Compute the minimum and maximum world coordinate height for this tile's sector by multiplying the minimum
// and maximum elevations by the scene's vertical exaggeration. This ensures that the elevations to used
// build the terrain are contained by this tile's extent. Use zero if the globe as no elevations in this
// tile's sector.
var globe = dc.globe,
verticalExaggeration = dc.verticalExaggeration,
extremes = globe.minAndMaxElevationsForSector(this.sector),
minHeight = extremes ? (extremes[0] * verticalExaggeration) : 0,
maxHeight = extremes ? (extremes[1] * verticalExaggeration) : 0;
if (minHeight == maxHeight) {
minHeight = maxHeight + 10; // TODO: Determine if this is necessary.
}
// Compute a bounding box for this tile that contains the terrain surface in the tile's coverage area.
if (!this.extent) {
this.extent = new BoundingBox();
}
this.extent.setToSector(this.sector, globe, minHeight, maxHeight);
// Compute the cartesian points for a 3x3 geographic grid. This grid captures sufficiently close sample
// points in order to estimate the distance from the viewer to this tile.
if (!this.samplePoints) {
this.sampleElevations = new Float64Array(9);
this.samplePoints = new Float64Array(3 * this.sampleElevations.length);
}
WWUtil.fillArray(this.sampleElevations, 0.5 * (minHeight + maxHeight));
globe.computePointsForGrid(this.sector, 3, 3, this.sampleElevations, Vec3.ZERO, this.samplePoints);
// Compute the reference point used as a local coordinate origin for the tile.
if (!this.referencePoint) {
this.referencePoint = new Vec3(0, 0, 0);
}
globe.computePointFromPosition(this.sector.centroidLatitude(), this.sector.centroidLongitude(), 0,
this.referencePoint);
};
/**
* Computes a row number for a tile within a level given the tile's latitude.
* @param {Number} delta The level's latitudinal tile delta in degrees.
* @param {Number} latitude The tile's minimum latitude.
* @returns {Number} The computed row number.
*/
Tile.computeRow = function (delta, latitude) {
var row = Math.floor((latitude + 90) / delta);
// If latitude is at the end of the grid, subtract 1 from the computed row to return the last row.
if (latitude == 90) {
row -= 1;
}
return row;
};
/**
* Computes a column number for a tile within a level given the tile's longitude.
* @param {Number} delta The level's longitudinal tile delta in degrees.
* @param {Number} longitude The tile's minimum longitude.
* @returns {Number} The computed column number.
*/
Tile.computeColumn = function (delta, longitude) {
var col = Math.floor((longitude + 180) / delta);
// If longitude is at the end of the grid, subtract 1 from the computed column to return the last column.
if (longitude == 180) {
col -= 1;
}
return col;
};
/**
* Computes the last row number for a tile within a level given the tile's maximum latitude.
* @param {Number} delta The level's latitudinal tile delta in degrees.
* @param {Number} maxLatitude The tile's maximum latitude in degrees.
* @returns {Number} The computed row number.
*/
Tile.computeLastRow = function (delta, maxLatitude) {
var row = Math.ceil((maxLatitude + 90) / delta - 1);
// If max latitude is in the first row, set the max row to 0.
if (maxLatitude + 90 < delta) {
row = 0;
}
return row;
};
/**
* Computes the last column number for a tile within a level given the tile's maximum longitude.
* @param {Number} delta The level's longitudinal tile delta in degrees.
* @param {Number} maxLongitude The tile's maximum longitude in degrees.
* @returns {Number} The computed column number.
*/
Tile.computeLastColumn = function (delta, maxLongitude) {
var col = Math.ceil((maxLongitude + 180) / delta - 1);
// If max longitude is in the first column, set the max column to 0.
if (maxLongitude + 180 < delta) {
col = 0;
}
return col;
};
/**
* Computes a sector spanned by a tile with the specified level number, row and column.
* @param {Level} level The tile's level number.
* @param {Number} row The tile's row number.
* @param {Number} column The tile's column number.
* @returns {Sector} The sector spanned by the tile.
* @throws {ArgumentError} If the specified level is null or undefined or the row or column are less than zero.
*/
Tile.computeSector = function (level, row, column) {
if (!level) {
throw new ArgumentError(
Logger.logMessage(Logger.LEVEL_SEVERE, "Tile", "computeSector", "missingLevel"));
}
if (row < 0 || column < 0) {
throw new ArgumentError(
Logger.logMessage(Logger.LEVEL_SEVERE, "Tile", "computeSector",
"The specified row or column is less than zero."));
}
var deltaLat = level.tileDelta.latitude,
deltaLon = level.tileDelta.longitude,
minLat = -90 + row * deltaLat,
minLon = -180 + column * deltaLon,
maxLat = minLat + deltaLat,
maxLon = minLon + deltaLon;
return new Sector(minLat, maxLat, minLon, maxLon);
};
/**
* Creates all tiles for a specified level number.
* @param {Level} level The level to create the tiles for.
* @param {TileFactory} tileFactory The tile factory to use for creating tiles.
* @param {Tile[]} result An array in which to return the results.
* @throws {ArgumentError} If any argument is null or undefined.
*/
Tile.createTilesForLevel = function (level, tileFactory, result) {
if (!level) {
throw new ArgumentError(
Logger.logMessage(Logger.LEVEL_SEVERE, "Tile", "createTilesForLevel", "missingLevel"));
}
if (!tileFactory) {
throw new ArgumentError(
Logger.logMessage(Logger.LEVEL_SEVERE, "Tile", "createTilesForLevel",
"The specified tile factory is null or undefined"));
}
if (!result) {
throw new ArgumentError(
Logger.logMessage(Logger.LEVEL_SEVERE, "Tile", "createTilesForLevel", "missingResult"));
}
var deltaLat = level.tileDelta.latitude,
deltaLon = level.tileDelta.longitude,
sector = level.sector,
firstRow = Tile.computeRow(deltaLat, sector.minLatitude),
lastRow = Tile.computeRow(deltaLat, sector.maxLatitude),
firstCol = Tile.computeColumn(deltaLon, sector.minLongitude),
lastCol = Tile.computeColumn(deltaLon, sector.maxLongitude),
firstRowLat = -90 + firstRow * deltaLat,
firstRowLon = -180 + firstCol * deltaLon,
minLat = firstRowLat,
minLon,
maxLat,
maxLon;
for (var row = firstRow; row <= lastRow; row += 1) {
maxLat = minLat + deltaLat;
minLon = firstRowLon;
for (var col = firstCol; col <= lastCol; col += 1) {
maxLon = minLon + deltaLon;
var tileSector = new Sector(minLat, maxLat, minLon, maxLon),
tile = tileFactory.createTile(tileSector, level, row, col);
result.push(tile);
minLon = maxLon;
}
minLat = maxLat;
}
};
return Tile;
}); | 412 | 0.857859 | 1 | 0.857859 | game-dev | MEDIA | 0.671673 | game-dev | 0.73304 | 1 | 0.73304 |
StarKRE22/Atomic | 1,812 | Assets/Examples/Shooter/Scripts/Gameplay/GameEntity/Content/Bullet/BulletInstaller.cs | using Atomic.Elements;
using Atomic.Entities;
using UnityEngine;
namespace ShooterGame.Gameplay
{
public sealed class BulletInstaller : SceneEntityInstaller<IGameEntity>
{
[SerializeField]
private GameObject _gameObject;
[SerializeField]
private Transform _transform;
[SerializeField]
private Const<float> _moveSpeed = 3;
[SerializeField]
private Const<int> _damage = 1;
[SerializeField]
private TriggerEvents _trigger;
[SerializeField]
private Cooldown _lifetime = 5;
public override void Install(IGameEntity entity)
{
GameContext gameContext = GameContext.Instance;
//Transform:
entity.AddPosition(new TransformPositionVariable(_transform));
entity.AddRotation(new TransformRotationVariable(_transform));
//Lifetime
entity.AddLifetime(_lifetime);
entity.AddBehaviour<LifetimeBehaviour>();
//Team
entity.AddTeamType(new ReactiveVariable<TeamType>());
entity.AddBehaviour<TeamPhysicsLayerBehaviour>();
//Move
entity.AddMovementSpeed(_moveSpeed);
entity.AddBehaviour<BulletMoveBehaviour>();
//Physics
entity.AddTrigger(_trigger);
entity.AddPhysicsLayer(new ProxyVariable<int>(
getter: () => _gameObject.layer,
setter: value => _gameObject.layer = value
));
entity.AddBehaviour(new BulletCollisionBehaviour(gameContext));
//Damage dealing:
entity.AddDamage(_damage);
entity.AddDestroyAction(new InlineAction(() => BulletUseCase.Despawn(gameContext, entity)));
}
}
} | 412 | 0.878234 | 1 | 0.878234 | game-dev | MEDIA | 0.987704 | game-dev | 0.75679 | 1 | 0.75679 |
electronicarts/CnC_Generals_Zero_Hour | 3,970 | Generals/Code/Libraries/Source/WWVegas/WWLib/inisup.h | /*
** Command & Conquer Generals(tm)
** Copyright 2025 Electronic Arts 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 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/>.
*/
/***********************************************************************************************
*** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S ***
***********************************************************************************************
* *
* Project Name : WWLib *
* *
* $Archive:: /G/wwlib/inisup.h $*
* *
* $Author:: Eric_c $*
* *
* $Modtime:: 4/02/99 11:59a $*
* *
* $Revision:: 2 $*
* *
*---------------------------------------------------------------------------------------------*
* Functions: *
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
#if _MSC_VER >= 1000
#pragma once
#endif // _MSC_VER >= 1000
/*
** This header defines generally unused member structures used by the INI class.
** Previously these were member structures of the INI class but they were separated
** to help reduce header dependancies. -ehc
*/
#include "listnode.h"
#include "index.h"
#include "crc.h"
/*
** The value entries for the INI file are stored as objects of this type.
** The entry identifier and value string are combined into this object.
*/
struct INIEntry : public Node<INIEntry *> {
INIEntry(char * entry = NULL, char * value = NULL) : Entry(entry), Value(value) {}
~INIEntry(void);
// ~INIEntry(void) {free(Entry);Entry = NULL;free(Value);Value = NULL;}
// int Index_ID(void) const {return(CRCEngine()(Entry, strlen(Entry)));};
int Index_ID(void) const { return CRC::String(Entry);};
char * Entry;
char * Value;
};
/*
** Each section (bracketed) is represented by an object of this type. All entries
** subordinate to this section are attached.
*/
struct INISection : public Node<INISection *> {
INISection(char * section) : Section(section) {}
~INISection(void);
// ~INISection(void) {free(Section);Section = 0;EntryList.Delete();}
INIEntry * Find_Entry(char const * entry) const;
// int Index_ID(void) const {return(CRCEngine()(Section, strlen(Section)));};
int Index_ID(void) const { return CRC::String(Section); };
char * Section;
List<INIEntry *> EntryList;
IndexClass<int, INIEntry *> EntryIndex;
private:
INISection(INISection const & rvalue);
INISection operator = (INISection const & rvalue);
};
| 412 | 0.852884 | 1 | 0.852884 | game-dev | MEDIA | 0.582666 | game-dev | 0.602257 | 1 | 0.602257 |
jotesoft/sudachi_yzm | 3,449 | src/input_common/drivers/mouse.h | // SPDX-FileCopyrightText: Copyright 2021 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#pragma once
#include <thread>
#include "common/polyfill_thread.h"
#include "common/vector_math.h"
#include "input_common/input_engine.h"
namespace InputCommon {
enum class MouseButton {
Left,
Right,
Wheel,
Backward,
Forward,
Task,
Extra,
Undefined,
};
/**
* A button device factory representing a keyboard. It receives keyboard events and forward them
* to all button devices it created.
*/
class Mouse final : public InputEngine {
public:
explicit Mouse(std::string input_engine_);
/**
* Signals that mouse has moved.
* @param x the x-coordinate of the cursor
* @param y the y-coordinate of the cursor
* @param center_x the x-coordinate of the middle of the screen
* @param center_y the y-coordinate of the middle of the screen
*/
void Move(int x, int y, int center_x, int center_y);
/**
* Signals that real mouse has moved.
* @param x the absolute position on the touchscreen of the cursor
* @param y the absolute position on the touchscreen of the cursor
*/
void MouseMove(f32 touch_x, f32 touch_y);
/**
* Signals that touch finger has moved.
* @param x the absolute position on the touchscreen of the cursor
* @param y the absolute position on the touchscreen of the cursor
*/
void TouchMove(f32 touch_x, f32 touch_y);
/**
* Sets the status of a button to pressed
* @param x the x-coordinate of the cursor
* @param y the y-coordinate of the cursor
* @param button the id of the button to press
*/
void PressButton(int x, int y, MouseButton button);
/**
* Sets the status of a mouse button to pressed
* @param button the id of the button to press
*/
void PressMouseButton(MouseButton button);
/**
* Sets the status of touch finger to pressed
* @param x the absolute position on the touchscreen of the cursor
* @param y the absolute position on the touchscreen of the cursor
* @param button the id of the button to press
*/
void PressTouchButton(f32 touch_x, f32 touch_y, MouseButton button);
/**
* Sets the status of all buttons bound with the key to released
* @param key_code the code of the key to release
*/
void ReleaseButton(MouseButton button);
/**
* Sets the status of the mouse wheel
* @param x delta movement in the x direction
* @param y delta movement in the y direction
*/
void MouseWheelChange(int x, int y);
void ReleaseAllButtons();
std::vector<Common::ParamPackage> GetInputDevices() const override;
AnalogMapping GetAnalogMappingForDevice(const Common::ParamPackage& params) override;
Common::Input::ButtonNames GetUIName(const Common::ParamPackage& params) const override;
private:
void UpdateThread(std::stop_token stop_token);
void UpdateStickInput();
void UpdateMotionInput();
bool IsMousePanningEnabled();
Common::Input::ButtonNames GetUIButtonName(const Common::ParamPackage& params) const;
Common::Vec2<int> mouse_origin;
Common::Vec2<int> last_mouse_position;
Common::Vec2<float> last_mouse_change;
Common::Vec3<float> last_motion_change;
Common::Vec2<int> wheel_position;
bool button_pressed;
std::jthread update_thread;
};
} // namespace InputCommon
| 412 | 0.932758 | 1 | 0.932758 | game-dev | MEDIA | 0.476719 | game-dev | 0.843123 | 1 | 0.843123 |
PiratesOnlineRewritten/Pirates-Online-Rewritten | 10,146 | pirates/leveleditor/EditorGlobals.py | from pandac.PandaModules import *
from direct.interval.IntervalGlobal import *
from direct.showbase.DirectObject import *
from pirates.effects import DynamicLight
from pirates.creature import Creature
from pirates.creature.Alligator import Alligator
from pirates.creature.Bat import Bat
from pirates.creature.Chicken import Chicken
from pirates.creature.Crab import Crab
from pirates.creature.Dog import Dog
from pirates.creature.FlyTrap import FlyTrap
from pirates.creature.Monkey import Monkey
from pirates.creature.Pig import Pig
from pirates.creature.Rooster import Rooster
from pirates.creature.Scorpion import Scorpion
from pirates.creature.Seagull import Seagull
from pirates.creature.Raven import Raven
from pirates.creature.Stump import Stump
from pirates.creature.Wasp import Wasp
from pirates.npc import BomberZombie
from pirates.battle import EnemyGlobals
from pirates.piratesbase import PiratesGlobals
from pirates.pirate import AvatarTypes
from pirates.ship import ShipGlobals
from pirates.effects import SoundFX
from pirates.effects import AmbientSoundFX
from pirates.effects import CausticsProjector
from pirates.effects import ExplodingBarrel
from pirates.world import WorldGlobals
from pirates.piratesbase import PLocalizerEnglish
LOD_STATE_NORMAL = 0
LOD_STATE_HIGH = 1
LOD_STATE_LOW = 2
LOD_STATE_LOWEST = 3
LOD_STATE_MED = 4
flickerTracks = []
def LightDynamic(levelObj, parent=render, drawIcon=True, modular=False):
if levelObj is None:
levelObj = WorldGlobals.LevelObject('', {})
color = None
if levelObj.data.has_key('Visual'):
if levelObj.data['Visual'].has_key('Color'):
color = levelObj.data['Visual']['Color']
attenuation = None
if levelObj.data.has_key('Attenuation'):
quadAtten = float(levelObj.data['Attenuation'])
else:
quadAtten = 0
if levelObj.data.has_key('QuadraticAttenuation'):
quadAtten = float(levelObj.data['QuadraticAttenuation'])
quadAtten = quadAtten * quadAtten / 100.0
if levelObj.data.has_key('ConstantAttenuation'):
constantAtten = float(levelObj.data['ConstantAttenuation'])
else:
constantAtten = 1
if levelObj.data.has_key('LinearAttenuation'):
linearAtten = float(levelObj.data['LinearAttenuation'])
else:
linearAtten = 0
attenuation = (constantAtten, linearAtten, quadAtten)
intensity = None
if levelObj.data.has_key('Intensity'):
intensity = float(levelObj.data['Intensity'])
coneAngle = None
dropOff = None
if levelObj.data.has_key('ConeAngle'):
coneAngle = float(levelObj.data['ConeAngle'])
if coneAngle == 0.0:
levelObj.data['ConeAngle'] = '60.0'
coneAngle = 60.0
if levelObj.data.has_key('DropOff'):
dropOff = float(levelObj.data['DropOff'])
exponent = None
flickering = False
if not modular or config.GetBool('allow-cave-flicker', 0):
if levelObj.data.get('Flickering', False):
flickering = True
flickRate = 1.0
if levelObj.data.has_key('FlickRate'):
flickRate = float(levelObj.data['FlickRate'])
lightType = DynamicLight.DYN_LIGHT_POINT
if levelObj.data.has_key('LightType'):
typeString = levelObj.data['LightType']
if typeString == 'AMBIENT':
lightType = DynamicLight.DYN_LIGHT_AMBIENT
elif typeString == 'DIRECTIONAL':
lightType = DynamicLight.DYN_LIGHT_DIRECTIONAL
elif typeString == 'SPOT':
lightType = DynamicLight.DYN_LIGHT_SPOT
light = DynamicLight.DynamicLight(type=lightType, parent=parent, pos=levelObj.transform.getPos(), hpr=levelObj.transform.getHpr(), color=color, atten=attenuation, exp=exponent, flicker=flickering, drawIcon=drawIcon, modular=modular)
if not modular:
light.turnOff()
if intensity:
light.setIntensity(intensity)
if coneAngle:
light.setConeAngle(coneAngle)
if dropOff:
light.setDropOff(dropOff)
if not modular or config.GetBool('allow-cave-flicker', 0):
light.setFlickRate(flickRate)
if not modular:
light.turnOn()
if hasattr(base, 'pe'):
base.pe.dynamicLights.append(light)
return light
def LightModular(levelObj, parent=render, drawIcon=True):
return LightDynamic(levelObj, parent, drawIcon, modular=True)
def CreateBomberZombie():
bZombie = BomberZombie.BomberZombie()
bZombie.barrel = ExplodingBarrel.ExplodingBarrel()
lodNode = bZombie.barrel.find('**/+LODNode').node()
lodNode.setSwitch(0, 50000, 0)
lodNode.setSwitch(1, 50003, 50001)
bZombie.barrel.reparentTo(bZombie.leftHandNode)
bZombie.barrel.setScale(0.88)
bZombie.barrel.lightUp()
return bZombie
def CreateAnimal(species=None):
if not species:
species = 'Pig'
exec 'animal = %s()' % species
animal.setAvatarType(eval('AvatarTypes.%s' % species))
return animal
CREATURE_CLASS_DICT = {'Crab': 'Crab','Stone Crab': 'Crab','Rock Crab': 'Crab','Giant Crab': 'Crab','Devourer Crab': 'Crab','FlyTrap': 'FlyTrap','Rancid FlyTrap': 'FlyTrap','Ancient FlyTrap': 'FlyTrap','Stump': 'Stump','Twisted Stump': 'Stump','Alligator': 'Alligator','Bayou Gator': 'Alligator','Huge Gator': 'Alligator','Big Gator': 'Alligator','Bat': 'Bat','Rabid Bat': 'Bat','Vampire Bat': 'Bat','Fire Bat': 'Bat','Wasp': 'Wasp','Killer Wasp': 'Wasp','Angry Wasp': 'Wasp','Soldier Wasp': 'Wasp','Scorpion': 'Scorpion','Dire Scorpion': 'Scorpion','Dread Scorpion': 'Scorpion'}
def CreateCreature(species=None):
if not species:
species = 'Crab'
exec 'creature = %s()' % CREATURE_CLASS_DICT[species]
creature.show()
avatarTypeFunc = AvatarTypes.NPC_SPAWNABLES[species][AvatarTypes.AVATAR_TYPE_IDX]
avatarType = avatarTypeFunc()
creature.height = EnemyGlobals.getHeight(avatarType)
baseStats = EnemyGlobals.getBaseStats(avatarType)
enemyScale = EnemyGlobals.getEnemyScaleByType(avatarType, baseStats[1])
creature.height *= enemyScale
creature.setAvatarScale(enemyScale)
creature.setAvatarType(avatarType)
return creature
def CreateEffectProjector(type='CausticsProjector', drawIcon=True):
projector = None
if type == 'CausticsProjector':
projector = CausticsProjector.CausticsProjector()
projector.enableEffect()
if drawIcon and projector:
newModel = loader.loadModel('models/misc/smiley')
newModel.setColor(0, 0.65, 0, 1)
newModel.reparentTo(projector)
return projector
def CreateSFX(sfxFile=None, volume=0.5, looping=True, delayMin=0, delayMax=0, pos=None, hpr=None, parent=None, drawIcon=True):
soundFX = SoundFX.SoundFX(sfxFile=sfxFile, volume=volume, looping=looping, delayMin=delayMin, delayMax=delayMax, pos=pos, hpr=hpr, parent=parent, listenerNode=base.cam, drawIcon=drawIcon)
return soundFX
def CreateAmbientSFX(pos=None, parent=None):
soundFX = AmbientSoundFX.AmbientSoundFX()
return soundFX
def CreateEntity(entityType, objData=None, parent=None):
newEntity = entityType()
if parent:
newEntity.reparentTo(parent)
if objData:
properties = objData.get('properties')
if properties:
for key in properties:
newEntity.setProperty(key, properties[key])
return newEntity
GREETING_ANIMATIONS = [
'', 'emote_wave', 'emote_wink', 'emote_clap', 'emote_yawn', 'emote_smile', 'emote_no', 'emote_yes', 'attention', 'emote_flex', 'emote_fear', 'emote_sad', 'crazy_ned_day_interact']
class ShipNP(NodePath):
def __init__(self, shipObj):
NodePath.__init__(self, 'ShipModel')
self.shipObj = shipObj
self.shipObj.setOwner(self)
self.shipObj.manufactureCannons()
def getShipEnumerations():
enums = []
shipClasses = ShipGlobals.__shipConfigs.keys()
shipClasses.sort()
for shipClass in shipClasses:
shipStr = str(shipClass) + ': ' + PLocalizerEnglish.ShipClassNames[shipClass]
enums.append(shipStr)
return enums
def getStyleEnumerations():
styleInfo = PLocalizerEnglish.ShipStyleNames
styles = styleInfo.keys()
styles.sort()
return [
'-1: Default'] + [ str(x) + ': ' + styleInfo[x] for x in styles ]
def getLogoEnumerations():
logoInfo = PLocalizerEnglish.ShipLogoNames
logos = logoInfo.keys()
logos.sort()
return [
'-1: Default'] + [ str(x) + ': ' + logoInfo[x] for x in logos ]
def getShipInfo(objectData):
if ':' in objectData['Category']:
shipClass = int(objectData['Category'].split(':')[0])
else:
typeStr = objectData['Category']
level = objectData.get('Level')
if level:
level = int(level)
teamStr = 'Player'
specifiedTeam = objectData.get('Team')
if specifiedTeam:
teamStr = specifiedTeam
teamId = PiratesGlobals.teamStr2TeamId(teamStr)
shipClass = ShipGlobals.WARSHIPL3
newShipClass = None
if hasattr(ShipGlobals, typeStr):
newShipClass = eval('ShipGlobals.' + typeStr)
if newShipClass:
shipClass = newShipClass
elif typeStr == 'NavyMerchant' or typeStr == 'Merchant' and teamId and teamId == PiratesGlobals.NAVY_TEAM:
shipClass = ShipGlobals.NAVY_VANGUARD
elif typeStr == 'Merchant':
shipClass = ShipGlobals.MERCHANTL2
elif typeStr == 'Interceptor':
if level == 2:
shipClass = ShipGlobals.INTERCEPTORL2
elif level == 3:
shipClass = ShipGlobals.INTERCEPTORL3
else:
shipClass = ShipGlobals.INTERCEPTORL1
elif typeStr == 'InterceptorTutorial':
shipClass = ShipGlobals.STUMPY_SHIP
elif typeStr == 'TutorialEnemyShip':
shipClass = ShipGlobals.SKEL_SHADOW_CROW_FR
style = objectData.get('StyleOverride', '%s:Default' % ShipGlobals.Styles.Undefined)
logo = objectData.get('LogoOverride', '%s:Default' % ShipGlobals.Logos.Undefined)
style = int(style.split(':')[0])
logo = int(logo.split(':')[0])
return (
shipClass, style, logo)
| 412 | 0.846659 | 1 | 0.846659 | game-dev | MEDIA | 0.945963 | game-dev | 0.851476 | 1 | 0.851476 |
Justsvetoslavov/Object-oriented_programming_FMI | 4,118 | Seminars/Sem.13/Solutions/PairOfOptinals/PairOfOptionals.hpp | #pragma once
#include <iostream>
template<typename T, typename U>
class PairOfOptionals {
private:
T* first = nullptr;
U* second = nullptr;
public:
PairOfOptionals() = default;
PairOfOptionals(const T& fData, const U& sData);
PairOfOptionals(const PairOfOptionals<T, U>& other);
PairOfOptionals(PairOfOptionals<T, U>&& other);
PairOfOptionals <T, U>& operator=(const PairOfOptionals<T, U>& other);
PairOfOptionals <T, U>& operator=(PairOfOptionals<T, U>&& other);
~PairOfOptionals();
void SetFirst(const T& data);
void SetSecond(const U& data);
const T& GetFirst() const;
const U& GetSecond() const;
void RemoveFirst();
void RemoveSecond();
bool ContainsFirst() const;
bool ContainsSecond() const;
bool IsEmpty() const;
friend bool operator==(const PairOfOptionals<T, U>& lhs, const PairOfOptionals<T, U>& rhs);
private:
void CopyFrom(const PairOfOptionals<T, U>& other);
void MoveFrom(PairOfOptionals<T, U>&& other);
void Free();
};
template<typename S>
bool CompareValues(const S* ptr1, const S* ptr2) {
return (ptr1 == nullptr && ptr2 == nullptr) || (ptr1 != nullptr && ptr2 != nullptr && *ptr1 == *ptr2);
}
template<typename T, typename U>
bool operator==(const PairOfOptionals<T, U>& lhs , const PairOfOptionals<T, U>& rhs) {
return CompareValues<T>(lhs.first, rhs.first) && CompareValues<U>(lhs.second, rhs.second);
}
template<typename T, typename U>
bool operator!=(const PairOfOptionals<T, U>& lhs, const PairOfOptionals<T, U>& rhs) {
return !(lhs == rhs);
}
template<typename T, typename U>
PairOfOptionals<T, U>::PairOfOptionals(const T& fData, const U& sData) {
first = new T(fData);
second = new U(sData);
}
template<typename T, typename U>
void PairOfOptionals<T, U>::CopyFrom(const PairOfOptionals<T, U>& other) {
first = new T(*other.first);
second = new U(*other.second);
}
template<typename T, typename U>
void PairOfOptionals<T, U>::MoveFrom(PairOfOptionals<T, U>&& other) {
first = other.first;
second = other.second;
other.first = other.second = nullptr;
}
template<typename T, typename U>
void PairOfOptionals<T, U>::Free() {
delete first;
delete second;
first = second = nullptr;
}
template<typename T, typename U>
PairOfOptionals<T, U>::PairOfOptionals(const PairOfOptionals<T, U>& other) {
CopyFrom(other);
}
template<typename T, typename U>
PairOfOptionals<T, U>::PairOfOptionals(PairOfOptionals<T, U>&& other) {
MoveFrom(std::move(other));
}
template<typename T, typename U>
PairOfOptionals < T, U>& PairOfOptionals<T, U>::operator=(const PairOfOptionals<T, U>& other) {
if (this != &other) {
Free();
CopyFrom(other);
}
return *this;
}
template<typename T, typename U>
PairOfOptionals < T, U>& PairOfOptionals<T, U>::operator=(PairOfOptionals<T, U>&& other) {
if (this != &other) {
Free();
MoveFrom(std::move(other));
}
return *this;
}
template<typename T, typename U>
PairOfOptionals<T, U>::~PairOfOptionals() {
Free();
}
template<typename T, typename U>
void PairOfOptionals<T, U>::SetFirst(const T& data) {
delete first;
first = new T(data);
}
template<typename T, typename U>
void PairOfOptionals<T, U>::SetSecond(const U& data) {
delete second;
second = new U(data);
}
template<typename T, typename U>
const T& PairOfOptionals<T, U>::GetFirst() const {
if (!ContainsFirst()) {
throw std::logic_error("No element!");
}
return *first;
}
template<typename T, typename U>
const U& PairOfOptionals<T, U>::GetSecond() const {
if (!ContainsSecond()) {
throw std::logic_error("No element!");
}
return *second;
}
template<typename T, typename U>
void PairOfOptionals<T, U>::RemoveFirst() {
delete first;
first = nullptr;
}
template<typename T, typename U>
void PairOfOptionals<T, U>::RemoveSecond() {
delete second;
second = nullptr;
}
template<typename T, typename U>
bool PairOfOptionals<T, U>::ContainsFirst() const {
return first != nullptr;
}
template<typename T, typename U>
bool PairOfOptionals<T, U>::ContainsSecond() const {
return second != nullptr;
}
template<typename T, typename U>
bool PairOfOptionals<T, U>::IsEmpty() const {
return !(ContainsFirst() || ContainsSecond());
} | 412 | 0.737181 | 1 | 0.737181 | game-dev | MEDIA | 0.36136 | game-dev | 0.883421 | 1 | 0.883421 |
mikejsavage/cocainediesel | 1,210 | source/cgame/cg_players.cpp | #include "cgame/cg_local.h"
#include "client/audio/api.h"
static StringHash GetPlayerSound( int entnum, PlayerSound ps ) {
const PlayerModelMetadata * meta = GetPlayerModelMetadata( entnum );
Assert( meta != NULL );
if( meta == NULL ) {
Com_Printf( "Player model metadata is null\n" );
return EMPTY_HASH;
}
return meta->sounds[ ps ];
}
float CG_PlayerPitch( int entnum ) {
float basis = Length( Vec3( 1 ) );
return 1.0f / ( Length( cg_entities[ entnum ].current.scale ) / basis );
}
void CG_PlayerSound( int entnum, PlayerSound ps, bool stop_current ) {
StringHash sfx = GetPlayerSound( entnum, ps );
float pitch = 1.0f;
if( ps == PlayerSound_Death || ps == PlayerSound_Void || ps == PlayerSound_Pain25 || ps == PlayerSound_Pain50 || ps == PlayerSound_Pain75 || ps == PlayerSound_Pain100 || ps == PlayerSound_WallJump ) {
pitch = CG_PlayerPitch( entnum );
}
PlaySFXConfig config = ISVIEWERENTITY( entnum ) ? PlaySFXConfigGlobal() : PlaySFXConfigEntity( entnum );
config.pitch = pitch;
PlayingSFXHandle handle = PlaySFX( sfx, config );
if( stop_current ) {
centity_t * cent = &cg_entities[ entnum ];
StopSFX( cent->playing_body_sound );
cent->playing_body_sound = handle;
}
}
| 412 | 0.771127 | 1 | 0.771127 | game-dev | MEDIA | 0.957556 | game-dev | 0.781694 | 1 | 0.781694 |
hdescottes/GdxGame | 18,637 | core/src/test/java/com/gdx/game/entities/player/PlayerHUDTest.java | package com.gdx.game.entities.player;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Json;
import com.gdx.game.GdxRunner;
import com.gdx.game.battle.BattleObserver;
import com.gdx.game.component.ComponentObserver;
import com.gdx.game.dialog.ConversationGraph;
import com.gdx.game.dialog.ConversationGraphObserver;
import com.gdx.game.entities.Entity;
import com.gdx.game.entities.EntityBonus;
import com.gdx.game.entities.EntityConfig;
import com.gdx.game.entities.EntityFactory;
import com.gdx.game.entities.player.characterclass.ClassObserver;
import com.gdx.game.inventory.InventoryObserver;
import com.gdx.game.inventory.item.InventoryItem;
import com.gdx.game.inventory.item.InventoryItemFactory;
import com.gdx.game.inventory.store.StoreInventoryObserver;
import com.gdx.game.manager.ResourceManager;
import com.gdx.game.map.MapManager;
import com.gdx.game.profile.ProfileManager;
import com.gdx.game.profile.ProfileObserver;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.mockito.MockedConstruction;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Stream;
import static com.gdx.game.component.Component.MESSAGE_TOKEN;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockConstruction;
@ExtendWith(GdxRunner.class)
public class PlayerHUDTest {
private MockedConstruction<ShapeRenderer> mockShapeRenderer;
private MockedConstruction<SpriteBatch> mockSpriteBatch;
private final ProfileManager profileManager = ProfileManager.getInstance();
private static final int HP_MAX_VALUE = 100;
private static final int HP_VALUE = 80;
private static final int MP_MAX_VALUE = 10;
private static final int MP_VALUE = 0;
private static final int XP_MAX_VALUE = 20;
private static final int XP_VALUE = 10;
private static final int GOLD_VALUE = 100;
private static final int LEVEL_VALUE = 2;
private static final String CHARACTER_CLASS = "WARRIOR";
private static final Array<EntityBonus> bonusClass = new Array<>();
@BeforeEach
void init() {
Gdx.gl = mock(GL20.class);
Gdx.gl20 = mock(GL20.class);
mockShapeRenderer = mockConstruction(ShapeRenderer.class);
mockSpriteBatch = mockConstruction(SpriteBatch.class);
profileManager.setProperty("characterClass", CHARACTER_CLASS);
profileManager.setProperty("currentPlayerBonusClassAP", 15);
profileManager.setProperty("currentPlayerBonusClassDP", 15);
profileManager.setProperty("currentPlayerCharacterAP", 15);
profileManager.setProperty("currentPlayerCharacterDP", 15);
profileManager.setProperty("currentPlayerCharacterSPDP", 10);
profileManager.setProperty("currentPlayerXPMax", XP_MAX_VALUE);
profileManager.setProperty("currentPlayerXP", XP_VALUE);
profileManager.setProperty("currentPlayerHPMax", HP_MAX_VALUE);
profileManager.setProperty("currentPlayerHP", HP_VALUE);
profileManager.setProperty("currentPlayerMPMax", MP_MAX_VALUE);
profileManager.setProperty("currentPlayerMP", MP_VALUE);
profileManager.setProperty("currentPlayerLevel", LEVEL_VALUE);
profileManager.setProperty("currentPlayerGP", GOLD_VALUE);
bonusClass.add(new EntityBonus("atk", "0.1"));
profileManager.setProperty("bonusClass", bonusClass);
new ResourceManager();
}
@AfterEach
void end() {
mockShapeRenderer.close();
mockSpriteBatch.close();
}
@ParameterizedTest
@MethodSource("profileLoad")
void profile_load(ProfileObserver.ProfileEvent event, boolean isNewProfile, Map<String, Integer> stats) {
Entity player = EntityFactory.getInstance().getEntity(EntityFactory.EntityType.WARRIOR);
MapManager mapManager = new MapManager();
mapManager.setPlayer(player);
Camera camera = new OrthographicCamera();
PlayerHUD hud = new PlayerHUD(camera, player, mapManager);
profileManager.setProperty("playerQuests", new Array<>());
profileManager.setProperty("playerInventory", new Array<>());
profileManager.setProperty("playerEquipInventory", new Array<>());
profileManager.setIsNewProfile(isNewProfile);
hud.onNotify(profileManager, event);
assertEquals(stats.get("goldValue"), hud.getStatusUI().getGoldValue());
assertEquals(stats.get("hpValue"), hud.getStatusUI().getHPValue());
assertEquals(stats.get("hpMaxValue"), hud.getStatusUI().getHPValueMax());
assertEquals(stats.get("mpValue"), hud.getStatusUI().getMPValue());
assertEquals(stats.get("mpMaxValue"), hud.getStatusUI().getMPValueMax());
assertEquals(stats.get("xpValue"), hud.getStatusUI().getXPValue());
assertEquals(stats.get("xpMaxValue"), hud.getStatusUI().getXPValueMax());
assertEquals(stats.get("levelValue"), hud.getStatusUI().getLevelValue());
}
private static Stream<Arguments> profileLoad() {
Map<String, Integer> newProfileStats = new HashMap<>();
newProfileStats.put("goldValue", 20);
newProfileStats.put("hpValue", 50);
newProfileStats.put("hpMaxValue", 50);
newProfileStats.put("xpValue", 0);
newProfileStats.put("xpMaxValue", 200);
newProfileStats.put("mpValue", 50);
newProfileStats.put("mpMaxValue", 50);
newProfileStats.put("levelValue", 1);
Map<String, Integer> profileStats = new HashMap<>();
profileStats.put("goldValue", GOLD_VALUE);
profileStats.put("hpValue", HP_VALUE);
profileStats.put("hpMaxValue", HP_MAX_VALUE);
profileStats.put("xpValue", XP_VALUE);
profileStats.put("xpMaxValue", XP_MAX_VALUE);
profileStats.put("mpValue", MP_VALUE);
profileStats.put("mpMaxValue", MP_MAX_VALUE);
profileStats.put("levelValue", LEVEL_VALUE);
return Stream.of(
Arguments.of(ProfileObserver.ProfileEvent.PROFILE_LOADED, true, newProfileStats),
Arguments.of(ProfileObserver.ProfileEvent.PROFILE_LOADED, false, profileStats)
);
}
@ParameterizedTest
@MethodSource("profileStates")
void profile_states(ProfileObserver.ProfileEvent event, Map<String, Object> stats) {
Entity player = EntityFactory.getInstance().getEntity(EntityFactory.EntityType.WARRIOR);
MapManager mapManager = new MapManager();
mapManager.setPlayer(player);
Camera camera = new OrthographicCamera();
PlayerHUD hud = new PlayerHUD(camera, player, mapManager);
profileManager.setProperty("playerQuests", new Array<>());
profileManager.setProperty("playerInventory", new Array<>());
profileManager.setProperty("playerEquipInventory", new Array<>());
profileManager.setIsNewProfile(false);
hud.onNotify(profileManager, ProfileObserver.ProfileEvent.PROFILE_LOADED);
hud.onNotify(profileManager, event);
assertEquals(stats.get("goldValue"), profileManager.getProperty("currentPlayerGP", Integer.class));
assertEquals(stats.get("hpValue"), profileManager.getProperty("currentPlayerHP", Integer.class));
assertEquals(stats.get("hpMaxValue"), profileManager.getProperty("currentPlayerHPMax", Integer.class));
assertEquals(stats.get("mpValue"), profileManager.getProperty("currentPlayerMP", Integer.class));
assertEquals(stats.get("mpMaxValue"), profileManager.getProperty("currentPlayerMPMax", Integer.class));
assertEquals(stats.get("xpValue"), profileManager.getProperty("currentPlayerXP", Integer.class));
assertEquals(stats.get("xpMaxValue"), profileManager.getProperty("currentPlayerXPMax", Integer.class));
assertEquals(stats.get("levelValue"), profileManager.getProperty("currentPlayerLevel", Integer.class));
assertEquals(stats.get("characterClass"), profileManager.getProperty("characterClass", String.class));
assertEquals(stats.get("playerCharacter"), profileManager.getProperty("playerCharacter", String.class));
assertEquals(stats.get("bonusClass"), profileManager.getProperty("bonusClass", Array.class));
assertEquals(stats.get("bonusSet"), profileManager.getProperty("bonusSet", Array.class));
}
private static Stream<Arguments> profileStates() {
Map<String, Object> profileStats = new HashMap<>();
profileStats.put("goldValue", GOLD_VALUE);
profileStats.put("hpValue", HP_VALUE);
profileStats.put("hpMaxValue", HP_MAX_VALUE);
profileStats.put("xpValue", XP_VALUE);
profileStats.put("xpMaxValue", XP_MAX_VALUE);
profileStats.put("mpValue", MP_VALUE);
profileStats.put("mpMaxValue", MP_MAX_VALUE);
profileStats.put("levelValue", LEVEL_VALUE);
profileStats.put("bonusClass", bonusClass);
profileStats.put("bonusSet", null);
profileStats.put("playerCharacter", EntityFactory.EntityType.valueOf(CHARACTER_CLASS));
profileStats.put("characterClass", CHARACTER_CLASS);
Map<String, Integer> clearProfileStats = new HashMap<>();
clearProfileStats.put("goldValue", 0);
clearProfileStats.put("hpValue", 0);
clearProfileStats.put("hpMaxValue", 0);
clearProfileStats.put("xpValue", 0);
clearProfileStats.put("xpMaxValue", 0);
clearProfileStats.put("mpValue", 0);
clearProfileStats.put("mpMaxValue", 0);
clearProfileStats.put("levelValue", 0);
clearProfileStats.put("bonusClass", null);
clearProfileStats.put("bonusSet", null);
clearProfileStats.put("playerCharacter", null);
clearProfileStats.put("characterClass", null);
return Stream.of(
Arguments.of(ProfileObserver.ProfileEvent.SAVING_PROFILE, profileStats),
Arguments.of(ProfileObserver.ProfileEvent.CLEAR_CURRENT_PROFILE, clearProfileStats)
);
}
@Test
void load_dialog() {
Json json = new Json();
Entity player = EntityFactory.getInstance().getEntity(EntityFactory.EntityType.WARRIOR);
Entity blacksmith = EntityFactory.getInstance().getEntityByName(EntityFactory.EntityName.TOWN_BLACKSMITH);
MapManager mapManager = new MapManager();
mapManager.setPlayer(player);
Camera camera = new OrthographicCamera();
PlayerHUD hud = new PlayerHUD(camera, player, mapManager);
hud.onNotify(json.toJson(blacksmith.getEntityConfig()), ComponentObserver.ComponentEvent.LOAD_CONVERSATION);
assertEquals(blacksmith.getEntityConfig().getEntityID(), hud.getConversationUI().getCurrentEntityID());
}
@ParameterizedTest
@MethodSource("dialogVisibility")
void dialog_visibility(ComponentObserver.ComponentEvent event, boolean isVisible) {
Json json = new Json();
Entity player = EntityFactory.getInstance().getEntity(EntityFactory.EntityType.WARRIOR);
Entity blacksmith = EntityFactory.getInstance().getEntityByName(EntityFactory.EntityName.TOWN_BLACKSMITH);
MapManager mapManager = new MapManager();
mapManager.setPlayer(player);
Camera camera = new OrthographicCamera();
PlayerHUD hud = new PlayerHUD(camera, player, mapManager);
hud.onNotify(json.toJson(blacksmith.getEntityConfig()), ComponentObserver.ComponentEvent.LOAD_CONVERSATION);
hud.onNotify(json.toJson(blacksmith.getEntityConfig()), event);
assertEquals(isVisible, hud.getConversationUI().isVisible());
}
private static Stream<Arguments> dialogVisibility() {
return Stream.of(
Arguments.of(ComponentObserver.ComponentEvent.SHOW_CONVERSATION, true),
Arguments.of(ComponentObserver.ComponentEvent.HIDE_CONVERSATION, false)
);
}
@Test
void load_store_inventory() {
Entity player = EntityFactory.getInstance().getEntity(EntityFactory.EntityType.WARRIOR);
Entity blacksmith = EntityFactory.getInstance().getEntityByName(EntityFactory.EntityName.TOWN_BLACKSMITH);
MapManager mapManager = new MapManager();
mapManager.setPlayer(player);
mapManager.setCurrentSelectedMapEntity(blacksmith);
Camera camera = new OrthographicCamera();
PlayerHUD hud = new PlayerHUD(camera, player, mapManager);
hud.onNotify(new ConversationGraph(), ConversationGraphObserver.ConversationCommandEvent.LOAD_STORE_INVENTORY);
assertFalse(hud.getConversationUI().isVisible());
assertTrue(hud.getStoreInventoryUI().isVisible());
}
@Test
void update_total_gold() {
Entity player = EntityFactory.getInstance().getEntity(EntityFactory.EntityType.WARRIOR);
MapManager mapManager = new MapManager();
mapManager.setPlayer(player);
Camera camera = new OrthographicCamera();
PlayerHUD hud = new PlayerHUD(camera, player, mapManager);
int totalGold = 10;
hud.onNotify(String.valueOf(totalGold), StoreInventoryObserver.StoreInventoryEvent.PLAYER_GP_TOTAL_UPDATED);
assertEquals(totalGold, hud.getStatusUI().getGoldValue());
}
@Test
void check_upgrade_class() {
Entity player = EntityFactory.getInstance().getEntity(EntityFactory.EntityType.WARRIOR);
MapManager mapManager = new MapManager();
mapManager.setPlayer(player);
Camera camera = new OrthographicCamera();
PlayerHUD hud = new PlayerHUD(camera, player, mapManager);
Array<EntityBonus> bonusArray = new Array<>();
bonusArray.add(new EntityBonus(EntityConfig.EntityProperties.ENTITY_PHYSICAL_ATTACK_POINTS.name(), "0.1"));
bonusArray.add(new EntityBonus(EntityConfig.EntityProperties.ENTITY_PHYSICAL_DEFENSE_POINTS.name(), "0.1"));
hud.onNotify("", ClassObserver.ClassEvent.CHECK_UPGRADE_TREE_CLASS);
assertEquals("KNIGHT", ProfileManager.getInstance().getProperty("characterClass", String.class));
assertEquals(bonusArray.get(0).getValue(), ((EntityBonus) ProfileManager.getInstance().getProperty("bonusClass", Array.class).get(0)).getValue());
assertEquals(bonusArray.get(1).getValue(), ((EntityBonus) ProfileManager.getInstance().getProperty("bonusClass", Array.class).get(1)).getValue());
assertEquals(16, ProfileManager.getInstance().getProperty("currentPlayerBonusClassAP", Integer.class));
assertEquals(16, ProfileManager.getInstance().getProperty("currentPlayerBonusClassDP", Integer.class));
assertFalse(hud.getStatusUI().isVisible());
}
@Test
void opponent_defeated() {
Entity player = EntityFactory.getInstance().getEntity(EntityFactory.EntityType.WARRIOR);
Entity enemy = EntityFactory.getInstance().getEntityByName(EntityFactory.EntityName.RABITE);
MapManager mapManager = new MapManager();
mapManager.setPlayer(player);
Camera camera = new OrthographicCamera();
PlayerHUD hud = new PlayerHUD(camera, player, mapManager);
profileManager.setProperty("playerQuests", new Array<>());
profileManager.setProperty("playerInventory", new Array<>());
profileManager.setProperty("playerEquipInventory", new Array<>());
hud.onNotify(profileManager, ProfileObserver.ProfileEvent.PROFILE_LOADED);
hud.onNotify(enemy, BattleObserver.BattleEvent.OPPONENT_DEFEATED);
assertEquals(GOLD_VALUE + 5, hud.getStatusUI().getGoldValue());
assertEquals(XP_VALUE + 10, hud.getStatusUI().getXPValue());
}
@Test
void player_hit_damage() {
Entity player = EntityFactory.getInstance().getEntity(EntityFactory.EntityType.WARRIOR);
Entity enemy = EntityFactory.getInstance().getEntityByName(EntityFactory.EntityName.RABITE);
MapManager mapManager = new MapManager();
mapManager.setPlayer(player);
Camera camera = new OrthographicCamera();
PlayerHUD hud = new PlayerHUD(camera, player, mapManager);
profileManager.setProperty("playerQuests", new Array<>());
profileManager.setProperty("playerInventory", new Array<>());
profileManager.setProperty("playerEquipInventory", new Array<>());
hud.onNotify(enemy, BattleObserver.BattleEvent.PLAYER_HIT_DAMAGE);
assertEquals(HP_VALUE, hud.getStatusUI().getHPValue());
}
@ParameterizedTest
@MethodSource("consumeItems")
void consume_items(InventoryItem.ItemTypeID itemTypeId, int value, String property) {
Entity player = EntityFactory.getInstance().getEntity(EntityFactory.EntityType.WARRIOR);
MapManager mapManager = new MapManager();
mapManager.setPlayer(player);
Camera camera = new OrthographicCamera();
PlayerHUD hud = new PlayerHUD(camera, player, mapManager);
profileManager.setProperty("playerQuests", new Array<>());
profileManager.setProperty("playerInventory", new Array<>());
profileManager.setProperty("playerEquipInventory", new Array<>());
InventoryItem item = InventoryItemFactory.getInstance().getInventoryItem(itemTypeId);
String itemInfo = item.getItemUseType() + MESSAGE_TOKEN + item.getItemUseTypeValue();
hud.onNotify(profileManager, ProfileObserver.ProfileEvent.PROFILE_LOADED);
hud.onNotify(itemInfo, InventoryObserver.InventoryEvent.ITEM_CONSUMED);
if (InventoryItem.doesRestoreHP(item.getItemUseType())) {
assertEquals(value, hud.getStatusUI().getHPValue());
} else {
assertEquals(value, hud.getStatusUI().getMPValue());
}
assertEquals(value, ProfileManager.getInstance().getProperty(property, Integer.class));
}
private static Stream<Arguments> consumeItems() {
return Stream.of(
Arguments.of(InventoryItem.ItemTypeID.SCROLL01, 90, "currentPlayerHP"),
Arguments.of(InventoryItem.ItemTypeID.POTIONS01, 10, "currentPlayerMP")
);
}
}
| 412 | 0.905623 | 1 | 0.905623 | game-dev | MEDIA | 0.303886 | game-dev | 0.963283 | 1 | 0.963283 |
MoeMod/CSMoE | 5,533 | cl_dll/hud/z4/z4_scoreboard.cpp | /*
z4_scoreboard.cpp - CSMoE Client HUD : Zombie 4 Scoreboard
Copyright (C) 2019 Moemod Hyakuya
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.
*/
#include "hud.h"
#include "cl_util.h"
#include "draw_util.h"
#include "z4.h"
#include "z4_scoreboard.h"
namespace cl {
CHudZ4Scoreboard::CHudZ4Scoreboard(void)
{
BuildNumberRC(m_rcNumber, 14, 32);
InitHUDData();
}
void CHudZ4Scoreboard::InitHUDData()
{
m_iTeam = 1;
m_iDamage = 0;
m_iLastScore = 0;
}
void CHudZ4Scoreboard::BuildNumberRC(wrect_t* rgrc, int w, int h)
{
int nw = 0;
for (int i = 0; i < 10; i++)
{
rgrc[i].left = nw;
rgrc[i].top = 0;
rgrc[i].right = rgrc[i].left + w;
rgrc[i].bottom = h;
nw += w;
}
}
int CHudZ4Scoreboard::VidInit(void)
{
if (!m_iNumber)
m_iNumber = R_LoadTextureShared("resource/zombi/z4number");
if (!m_iScroreBorad)
m_iScroreBorad = R_LoadTextureUnique("resource/zombi/z4_scoreboard");
if (!m_iDamageBorad)
m_iDamageBorad = R_LoadTextureUnique("resource/zombi/z4_scorebg");
if (!m_iTeamIcon[0])
m_iTeamIcon[0] = R_LoadTextureUnique("resource/zombi/z4_scorehuman");
if (!m_iTeamIcon[1])
m_iTeamIcon[1] = R_LoadTextureUnique("resource/zombi/z4_scorezombie");
g_iSelectionHeight = gHUD.GetSpriteRect(gHUD.m_Ammo.m_HUD_selection).bottom - gHUD.GetSpriteRect(gHUD.m_Ammo.m_HUD_selection).top;
return 1;
}
int CHudZ4Scoreboard::Draw(float time)
{
if (!gHUD.m_pCvarDraw->value)
return 0;
DrawScoreBoard(time);
DrawScore(time);
return 1;
}
void CHudZ4Scoreboard::DrawScoreBoard(float time)
{
int iW, iH, iX, iY;
iW = m_iScroreBorad->w();
iH = m_iScroreBorad->h();
iX = ScreenWidth / 2 - iW / 2;
iY = 0;
m_iScroreBorad->Draw2DQuadScaled(iX, iY, iX + iW, iY + iH);
iX = ScreenWidth / 2 - 14;
iY = 27;
DrawNumbers(13, iX, iY, false);
iX = ScreenWidth / 2 - 136;
iY = 7;
DrawNumbers(gHUD.m_Scoreboard.m_iTeamScore_T, iX, iY, true, 0.9, 245, 245, 245);
iX = ScreenWidth / 2 + 67;
iY = 7;
DrawNumbers(gHUD.m_Scoreboard.m_iTeamScore_CT, iX, iY, false, 0.9, 245, 245, 245);
int aliveT = gHUD.m_Scoreboard.m_iTeamAlive_T;
int aliveCT = gHUD.m_Scoreboard.m_iTeamAlive_CT;
iX = ScreenWidth / 2 - 115;
iY = 34;
DrawNumbers(aliveT, iX, iY, true, 0.65, 200, 200, 200);
iX = ScreenWidth / 2 + 63;
iY = 34;
DrawNumbers(aliveCT, iX, iY, false, 0.65, 200, 200, 200);
}
void CHudZ4Scoreboard::DrawScore(float time)
{
if (g_iUser1)
return;
int idx = gEngfuncs.GetLocalPlayer()->index;
if (g_PlayerExtraInfo[idx].dead == true)
return;
/*if (g_szCurWeapon2 && g_bAlive)
{
g_Font.SetColor(200, 144, 72, 255);
g_Font.SetWidth(18);
g_Font.DrawString(g_szCurWeapon2, ScreenWidth - g_Font.GetLen(g_szCurWeapon2) - 18, ScreenHeight - 50, 1000, 100);
}*/
int iOffsetY = gHUD.m_hudstyle->value == 1 ? g_iSelectionHeight * 7 : g_iSelectionHeight;
int iW, iH, iX, iY;
iW = m_iDamageBorad->w();
iH = m_iDamageBorad->h();
iX = ScreenWidth - iW - 7;
iY = ScreenHeight - iH - 80 - iOffsetY;
m_iDamageBorad->Draw2DQuadScaled(iX, iY, iX + iW, iY + iH);
int team = m_iTeam - 1;
iW = m_iTeamIcon[team]->w();
iH = m_iTeamIcon[team]->h();
iX = ScreenWidth - iW - 122;
iY = ScreenHeight - iH - 88 - iOffsetY;
m_iTeamIcon[team]->Draw2DQuadScaled(iX, iY, iX + iW, iY + iH);
iX = ScreenWidth - iW - 56;
iY = ScreenHeight - iH - 80 - iOffsetY;
int iScore = g_PlayerExtraInfo[gEngfuncs.GetLocalPlayer()->index].frags - m_iLastScore;
if (iScore < 0)
iScore = 0;
DrawNumbers(iScore, iX, iY, true, 0.95, 200, 144, 72);
iX = ScreenWidth - iW - 44;
iY = ScreenHeight - iH - 56 - iOffsetY;
if (m_iDamage > 99999)
m_iDamage = 99999;
DrawNumbers(m_iDamage, iX, iY, true, 0.8, 200, 144, 72);
}
void CHudZ4Scoreboard::DrawNumber(int n, int x, int y, float scale, int r, int g, int b)
{
float w = m_iNumber->w() * scale;
float h = m_iNumber->h() * scale;
int left = m_rcNumber[n].left * scale;
int right = m_rcNumber[n].right * scale;
int bottom = m_rcNumber[n].bottom * scale;
int top = m_rcNumber[n].top * scale;
int x2 = x + (right - left);
int y2 = y + (bottom - top);
m_iNumber->Draw2DQuadScaled(x, y, x2, y2, left / w, top / h, right / w, bottom / h, 225, 225, 225);
}
void CHudZ4Scoreboard::DrawNumbers(int n, int x, int y, int from_right, float scale, int r, int g, int b)
{
int width = 14;
width *= scale;
int k;
if (n >= 100000)
{
k = n / 100000;
DrawNumber(k, x, y, scale, r, g, b);
if (!from_right)
x += width;
}
if (from_right)
x += width;
if (n >= 10000)
{
k = (n % 100000) / 10000;
DrawNumber(k, x, y, scale, r, g, b);
if (!from_right)
x += width;
}
if (from_right)
x += width;
if (n >= 1000)
{
k = (n % 10000) / 1000;
DrawNumber(k, x, y, scale, r, g, b);
if (!from_right)
x += width;
}
if (from_right)
x += width;
if (n >= 100)
{
k = (n % 1000) / 100;
DrawNumber(k, x, y, scale, r, g, b);
if (!from_right)
x += width;
}
if (from_right)
x += width;
if (n >= 10)
{
k = (n % 100) / 10;
DrawNumber(k, x, y, scale, r, g, b);
if (!from_right)
x += width;
}
if (from_right)
x += width;
k = n % 10;
DrawNumber(k, x, y, scale, r, g, b);
}
} | 412 | 0.879321 | 1 | 0.879321 | game-dev | MEDIA | 0.524443 | game-dev | 0.985963 | 1 | 0.985963 |
dalerank/caesaria-game | 1,316 | source/city/areainfo.hpp | // This file is part of CaesarIA.
//
// CaesarIA 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.
//
// CaesarIA 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 CaesarIA. If not, see <http://www.gnu.org/licenses/>.
//
// Copyright 2012-2015 Dalerank, dalerankn8@gmail.com
#ifndef __CAESARIA_CITYAREAINFO_H_INCLUDED__
#define __CAESARIA_CITYAREAINFO_H_INCLUDED__
#include "predefinitions.hpp"
#include "gfx/predefinitions.hpp"
#include "gfx/tilepos.hpp"
namespace city
{
class AreaInfo
{
public:
PlayerCityPtr city;
TilePos pos;
bool onload = false;
const gfx::TilesArray& tiles() const;
const gfx::Tile& tile() const;
AreaInfo(PlayerCityPtr rcity,
const TilePos& rpos,
const gfx::TilesArray* tiles = 0);
private:
const gfx::TilesArray* _tiles;
};
}//end namespace city
#endif //__CAESARIA_CITYAREAINFO_H_INCLUDED__
| 412 | 0.805864 | 1 | 0.805864 | game-dev | MEDIA | 0.835844 | game-dev | 0.730558 | 1 | 0.730558 |
sall/vixen | 1,769 | Vixen.System/Execution/QueuingSequenceEnumerator.cs | using System;
using System.Collections.Generic;
using System.Linq;
using Vixen.Services;
using Vixen.Sys;
namespace Vixen.Execution
{
internal class QueuingSequenceEnumerator : IEnumerator<ISequenceExecutor>
{
private ISequence[] _sequences;
private Queue<ISequence> _sequenceQueue;
public QueuingSequenceEnumerator(IEnumerable<ISequence> sequences)
{
_sequences = sequences.ToArray();
Reset();
}
public ISequenceExecutor Current { get; private set; }
object System.Collections.IEnumerator.Current
{
get { return Current; }
}
public bool MoveNext()
{
if (Current != null) {
// Cleanup after the prior sequence.
_DisposeCurrent();
}
// Anything left to play?
if (_sequenceQueue.Count > 0) {
// Get the sequence.
ISequence sequence = _sequenceQueue.Dequeue();
// Get an executor for the sequence.
Current = SequenceTypeService.Instance.CreateSequenceExecutor(sequence);
if (Current == null)
throw new InvalidOperationException(string.Format("Sequence {0} has no executor.", sequence.Name));
Current.Sequence = sequence;
return true;
}
return false;
}
public void Reset()
{
_DisposeCurrent();
_sequenceQueue = new Queue<ISequence>(_sequences);
}
/// <summary>
///
/// </summary>
/// <param name="sequence"></param>
/// <returns>The resulting length of the queue. 0 if it cannot be added.</returns>
public int Queue(ISequence sequence)
{
if (_sequenceQueue != null) {
_sequenceQueue.Enqueue(sequence);
return _sequenceQueue.Count;
}
return 0;
}
public void Dispose()
{
_DisposeCurrent();
}
private void _DisposeCurrent()
{
if (Current != null) {
Current.Dispose();
Current = null;
}
}
}
} | 412 | 0.87186 | 1 | 0.87186 | game-dev | MEDIA | 0.325052 | game-dev | 0.927113 | 1 | 0.927113 |
vmangos/core | 74,014 | src/scripts/eastern_kingdoms/eastern_plaguelands/naxxramas/instance_naxxramas.cpp | /* Copyright (C) 2006 - 2009 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/>
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/* ScriptData
SDName: Instance_Naxxramas
SD%Complete:
SDComment:
SDCategory: Naxxramas
EndScriptData */
#include "scriptPCH.h"
#include "naxxramas.h"
#include "InstanceStatistics.h"
#include "Geometry.h"
enum NaxxEvents
{
EVENT_BIGGLESWORTH_DIED_YELL = 1,
EVENT_THADDIUS_SCREAM,
EVENT_WINGBOSS_DEAD,
EVENT_KT_LK_DIALOGUE_1,
EVENT_KT_LK_DIALOGUE_2,
EVENT_KT_LK_DIALOGUE_3,
EVENT_KT_LK_DIALOGUE_4,
EVENT_KT_LK_DIALOGUE_5,
EVENT_KT_LK_DIALOGUE_GATE_OPEN,
EVENT_SUMMON_FROGGER_WAVE,
EVENT_4HM_DIALOGUE_1, // Sir Zeliek yells: Invaders! Cease this foolish venture at once! Turn away while you still can!
EVENT_4HM_DIALOGUE_2, // Lady Blaumeux yells: Come, Zeliek, do not drive them out. Not until we've had our fun!
EVENT_4HM_DIALOGUE_3, // Highlord Mograine yells: Enough prattling. Let them come. We shall grind their bones to dust.
EVENT_4HM_DIALOGUE_4, // Lady Blaumeux yells: I do hope they stay long enough for me to... introduce myself.
EVENT_4HM_DIALOGUE_5, // Sir Zeliek yells: Perhaps they will come to their senses... and run away as fast as they can.
EVENT_4HM_DIALOGUE_6, // Thane Korth'azz yells: I've heard about enough a' yer snivelin'!Shut your flytrap before I shut it for ye'!
EVENT_4HM_DIALOGUE_7, // Highlord Mograine yells: Conserve your anger. Harness your rage. You will all have outlets for your frustrations soon enough.
EVENT_DKWING_INTRO_2,
EVENT_DKWING_INTRO_3,
EVENT_DKWING_INTRO_4
};
instance_naxxramas::instance_naxxramas(Map* pMap) : ScriptedInstance(pMap),
m_faerlinaHaveGreeted(false),
m_thaddiusHaveGreeted(false),
m_haveDoneDKWingIntro(false),
m_horsemenDeathCounter(0),
m_uiHorsemenChestGUID(0),
m_fChamberCenterX(0.0f),
m_fChamberCenterY(0.0f),
m_fChamberCenterZ(0.0f)
{
Initialize();
}
void instance_naxxramas::Initialize()
{
memset(&m_auiEncounter, 0, sizeof(m_auiEncounter));
m_events.Reset();
// 2-5min, no idea if it's correct
m_events.ScheduleEvent(EVENT_THADDIUS_SCREAM, urand(1000 * 60 * 2, 1000 * 60 * 5));
m_events.ScheduleEvent(EVENT_SUMMON_FROGGER_WAVE, Seconds(6));
}
void instance_naxxramas::SetTeleporterVisualState(GameObject* pGO, uint32 uiData)
{
if (uiData == DONE)
pGO->SetGoState(GO_STATE_ACTIVE);
else
pGO->SetGoState(GO_STATE_READY);
}
void instance_naxxramas::SetTeleporterState(GameObject* pGO, uint32 uiData)
{
SetTeleporterVisualState(pGO, uiData);
if (uiData == DONE)
pGO->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_NO_INTERACT);
else
pGO->SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_NO_INTERACT);
}
uint8 instance_naxxramas::GetNumEndbossDead()
{
uint8 ret = 0;
if (GetData(TYPE_MAEXXNA) == DONE)
++ret;
if (GetData(TYPE_THADDIUS) == DONE)
++ret;
if (GetData(TYPE_FOUR_HORSEMEN) == DONE)
++ret;
if (GetData(TYPE_LOATHEB) == DONE)
++ret;
return ret;
}
static const G3D::Vector2 DK_DOOR_A(2600.15f, -3008.61f);
static const G3D::Vector2 DK_DOOR_B(2579.34f, -3029.44f);
bool instance_naxxramas::HandleEvadeOutOfHome(Creature* pWho)
{
if (pWho->IsInEvadeMode())
return false;
uint32 entry = pWho->GetEntry();
float dist;
switch (entry)
{
case NPC_GROBBULUS:
dist = 180.0f;
break;
case NPC_FAERLINA:
if (pWho->GetPositionZ() > 266.0f)
{
pWho->AI()->EnterEvadeMode();
return false;
}
return true;
case NPC_ANUB_REKHAN:
dist = 130.0f;
break;
case NPC_NOTH:
dist = 120.0f;
break;
case NPC_HEIGAN:
{
// evade if brought out of room towards bat/grub/beast gauntlet
if (pWho->GetPositionX() > 2825.0f || pWho->GetPositionY() < -3737.0f)
{
pWho->AI()->EnterEvadeMode();
return false;
}
dist = 90.0f;
break;
}
case NPC_LOATHEB:
dist = 100.0f;
break;
case NPC_GOTHIK:
{
dist = 150.0f;
break;
}
case NPC_RAZUVIOUS:
if (pWho->GetPositionZ() > 285.0f)
{
pWho->AI()->EnterEvadeMode();
return false;
}
return true;
case NPC_KELTHUZAD:
dist = 130.0f;
break;
case NPC_BLAUMEUX:
case NPC_MOGRAINE:
case NPC_ZELIEK:
case NPC_THANE:
{
if (Geometry::IsPointLeftOfLine(DK_DOOR_A, DK_DOOR_B, pWho->GetPosition()))
{
if (Creature* pC = GetSingleCreatureFromStorage(NPC_BLAUMEUX))
if (pC->IsAlive()) pC->AI()->EnterEvadeMode();
if (Creature* pC = GetSingleCreatureFromStorage(NPC_MOGRAINE))
if (pC->IsAlive()) pC->AI()->EnterEvadeMode();
if (Creature* pC = GetSingleCreatureFromStorage(NPC_ZELIEK))
if (pC->IsAlive()) pC->AI()->EnterEvadeMode();
if (Creature* pC = GetSingleCreatureFromStorage(NPC_THANE))
if (pC->IsAlive()) pC->AI()->EnterEvadeMode();
return false;
}
return true;
}
default:
sLog.Out(LOG_SCRIPTS, LOG_LVL_ERROR, "instance_naxxramas::HandleEvadeOutOfHome called for unsupported creture %d", pWho->GetEntry());
dist = 9999.0f;
break;
}
if (pWho->GetDistance2d(pWho->GetHomePosition()) > dist)
{
pWho->AI()->EnterEvadeMode();
return false;
}
return true;
}
void instance_naxxramas::OnCreatureEnterCombat(Creature * creature)
{
if (creature->GetEntry() == NPC_SewageSlime)
{
std::list<Creature*> sewageSlimes;
GetCreatureListWithEntryInGrid(sewageSlimes, creature, NPC_SewageSlime, 100.0f);
for (Creature* pC : sewageSlimes)
{
if (!pC->IsInCombat())
{
pC->CastSpell(pC, 28033, true); // aggro all in los
}
}
}
}
bool instance_naxxramas::WingsAreCleared()
{
// All bosses must be dead, not just the end bosses. Some bosses aren't gated
// so we just check them all
for (int i = 0; i < TYPE_SAPPHIRON; ++i)
{
if (GetData(i) != DONE)
return false;
}
return true;
}
void instance_naxxramas::UpdateAutomaticBossEntranceDoor(NaxxGOs which, uint32 uiData, int requiredPreBossData)
{
if (requiredPreBossData > -1 && requiredPreBossData != DONE)
return;
if (GameObject* pGo = GetSingleGameObjectFromStorage(which))
{
UpdateAutomaticBossEntranceDoor(pGo, uiData, requiredPreBossData);
}
}
void instance_naxxramas::UpdateAutomaticBossEntranceDoor(GameObject* pGO, uint32 uiData, int requiredPreBossData)
{
if (requiredPreBossData > -1 && requiredPreBossData != DONE)
return;
if (!pGO)
{
sLog.Out(LOG_SCRIPTS, LOG_LVL_ERROR, "instance_naxxramas::UpdateAutomaticBossEntranceDoor called with nullptr GO");
return;
}
if (uiData == IN_PROGRESS || uiData == SPECIAL)
{
pGO->SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_NO_INTERACT);
pGO->SetGoState(GO_STATE_READY);
}
else
{
//pGO->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_NO_INTERACT);
pGO->SetGoState(GO_STATE_ACTIVE);
}
}
void instance_naxxramas::UpdateManualDoor(NaxxGOs which, uint32 uiData)
{
if (GameObject* pGo = GetSingleGameObjectFromStorage(which))
{
UpdateManualDoor(pGo, uiData);
}
}
void instance_naxxramas::UpdateManualDoor(GameObject * pGO, uint32 uiData)
{
if (uiData == DONE)
pGO->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_LOCKED);
else
pGO->SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_LOCKED);
}
void instance_naxxramas::UpdateBossGate(NaxxGOs which, uint32 uiData)
{
if (GameObject* pGo = GetSingleGameObjectFromStorage(which))
{
UpdateBossGate(pGo, uiData);
}
}
void instance_naxxramas::UpdateBossGate(GameObject* pGO, uint32 uiData)
{
if (!pGO)
{
sLog.Out(LOG_SCRIPTS, LOG_LVL_ERROR, "instance_naxxramas::UpdateBossGate called with nullptr GO");
return;
}
if (uiData == DONE)
pGO->SetGoState(GO_STATE_ACTIVE);
else
pGO->SetGoState(GO_STATE_READY);
}
void instance_naxxramas::UpdateTeleporters(uint32 uiType, uint32 uiData)
{
// todo: what was the reason behind these? Should they despawn after 30 minutes?
// DoRespawnGameObject(GO_<WING>_PORTAL, 30 * MINUTE);
switch (uiType)
{
case TYPE_MAEXXNA:
if (GameObject* pGO = GetSingleGameObjectFromStorage(GO_ARAC_EYE_BOSS))
SetTeleporterVisualState(pGO, uiData);
if (GameObject* pGO = GetSingleGameObjectFromStorage(GO_ARAC_EYE_RAMP))
SetTeleporterVisualState(pGO, uiData);
if (GameObject* pGO = GetSingleGameObjectFromStorage(GO_ARAC_PORTAL))
SetTeleporterState(pGO, uiData);
break;
case TYPE_THADDIUS:
if (GameObject* pGO = GetSingleGameObjectFromStorage(GO_CONS_EYE_BOSS))
SetTeleporterVisualState(pGO, uiData);
if (GameObject* pGO = GetSingleGameObjectFromStorage(GO_CONS_EYE_RAMP))
SetTeleporterVisualState(pGO, uiData);
if (GameObject* pGO = GetSingleGameObjectFromStorage(GO_CONS_PORTAL))
SetTeleporterState(pGO, uiData);
break;
case TYPE_LOATHEB:
if (GameObject* pGO = GetSingleGameObjectFromStorage(GO_PLAG_EYE_BOSS))
SetTeleporterVisualState(pGO, uiData);
if (GameObject* pGO = GetSingleGameObjectFromStorage(GO_PLAG_EYE_RAMP))
SetTeleporterVisualState(pGO, uiData);
if (GameObject* pGO = GetSingleGameObjectFromStorage(GO_PLAG_PORTAL))
SetTeleporterState(pGO, uiData);
break;
case TYPE_FOUR_HORSEMEN:
if (GameObject* pGO = GetSingleGameObjectFromStorage(GO_MILI_EYE_BOSS))
SetTeleporterVisualState(pGO, uiData);
if (GameObject* pGO = GetSingleGameObjectFromStorage(GO_MILI_EYE_RAMP))
SetTeleporterVisualState(pGO, uiData);
if (GameObject* pGO = GetSingleGameObjectFromStorage(GO_MILI_PORTAL))
SetTeleporterState(pGO, uiData);
break;
default:
sLog.Out(LOG_SCRIPTS, LOG_LVL_ERROR, "instance_naxxramas::UpdateTeleporters called with unsupported type %d", uiType);
}
if (WingsAreCleared())
{
if (GameObject* pGO = GetSingleGameObjectFromStorage(GO_HUB_PORTAL))
{
pGO->SetGoState(GO_STATE_ACTIVE);
}
}
else
{
if (GameObject* pGO = GetSingleGameObjectFromStorage(GO_HUB_PORTAL))
{
pGO->SetGoState(GO_STATE_READY);
}
}
}
void instance_naxxramas::OnCreatureCreate(Creature* pCreature)
{
switch (pCreature->GetEntry())
{
case NPC_ANUB_REKHAN:
case NPC_FAERLINA:
case NPC_MAEXXNA:
case NPC_PATCHWERK:
case NPC_GROBBULUS:
case NPC_GLUTH:
case NPC_THADDIUS:
//case NPC_STALAGG:
//case NPC_FEUGEN:
case NPC_NOTH:
case NPC_HEIGAN:
case NPC_LOATHEB:
case NPC_RAZUVIOUS:
case NPC_GOTHIK:
case NPC_ZELIEK:
case NPC_THANE:
case NPC_BLAUMEUX:
case NPC_MOGRAINE:
case NPC_SAPPHIRON:
case NPC_KELTHUZAD:
case NPC_MR_BIGGLESWORTH:
m_mNpcEntryGuidStore[pCreature->GetEntry()] = pCreature->GetObjectGuid();
break;
case NPC_SUB_BOSS_TRIGGER:
if (m_auiEncounter[TYPE_GOTHIK] != IN_PROGRESS)
m_lGothTriggerList.push_back(pCreature->GetGUID());
break;
case NPC_SewageSlime:
pCreature->SetWanderDistance(30.0f);
break;
case NPC_BileSludge:
{
// hack to prevent the endless amounts of adds to spawn in case something bugs out
std::list<Creature*> clist;
GetCreatureListWithEntryInGrid(clist, pCreature, NPC_BileSludge, 50.0f);
if (clist.size() > 20)
{
pCreature->ForcedDespawn();
}
}
}
// 4hm
if (pCreature->GetEntry() >= 16062 && pCreature->GetEntry() <= 16065)
{
if (m_auiEncounter[TYPE_FOUR_HORSEMEN] != DONE && pCreature->IsDead())
{
pCreature->Respawn();
}
}
OnCreatureRespawn(pCreature);
}
void instance_naxxramas::OnObjectCreate(GameObject* pGo)
{
switch (pGo->GetEntry())
{
case GO_ARAC_ANUB_DOOR:
case GO_ARAC_ANUB_GATE:
case GO_ARAC_FAER_WEB:
case GO_ARAC_FAER_DOOR:
case GO_ARAC_MAEX_INNER_DOOR:
case GO_ARAC_MAEX_OUTER_DOOR:
case GO_PLAG_SLIME01_DOOR:
case GO_PLAG_SLIME02_DOOR:
case GO_PLAG_NOTH_ENTRY_DOOR:
case GO_PLAG_NOTH_EXIT_DOOR:
case GO_PLAG_HEIG_ENTRY_DOOR:
case GO_PLAG_HEIG_EXIT_DOOR:
case GO_PLAG_HEIG_OLD_EXIT_DOOR:
case GO_PLAG_LOAT_DOOR:
case GO_MILI_GOTH_ENTRY_GATE:
case GO_MILI_GOTH_EXIT_GATE:
case GO_MILI_GOTH_COMBAT_GATE:
case GO_MILI_HORSEMEN_DOOR:
case GO_CHEST_HORSEMEN_NORM:
case GO_CONS_PATH_EXIT_DOOR:
case GO_CONS_GLUT_EXIT_DOOR:
case GO_CONS_THAD_DOOR:
case GO_KELTHUZAD_WATERFALL_DOOR:
case GO_KELTHUZAD_DOOR:
case GO_ARAC_EYE_RAMP:
case GO_PLAG_EYE_RAMP:
case GO_MILI_EYE_RAMP:
case GO_CONS_EYE_RAMP:
case GO_ARAC_PORTAL:
case GO_PLAG_PORTAL:
case GO_MILI_PORTAL:
case GO_CONS_PORTAL:
case GO_ARAC_EYE_BOSS:
case GO_PLAG_EYE_BOSS:
case GO_MILI_EYE_BOSS:
case GO_CONS_EYE_BOSS:
case GO_KT_WINDOW_1:
case GO_KT_WINDOW_2:
case GO_KT_WINDOW_3:
case GO_KT_WINDOW_4:
case GO_CONS_NOX_TESLA_FEUGEN:
case GO_CONS_NOX_TESLA_STALAGG:
case GO_HUB_PORTAL:
case GO_SAPPHIRON_SPAWN:
m_mGoEntryGuidStore[pGo->GetEntry()] = pGo->GetObjectGuid();
break;
}
if (pGo->GetEntry() == GO_CHEST_HORSEMEN_NORM)
m_uiHorsemenChestGUID = pGo->GetGUID();
if (pGo->GetGoType() == GAMEOBJECT_TYPE_TRAP)
{
uint32 uiGoEntry = pGo->GetEntry();
if ((uiGoEntry >= 181517 && uiGoEntry <= 181524) || uiGoEntry == 181678)
m_alHeiganTrapGuids[0].push_back(pGo->GetObjectGuid());
else if ((uiGoEntry >= 181510 && uiGoEntry <= 181516) || (uiGoEntry >= 181525 && uiGoEntry <= 181531) || uiGoEntry == 181533 || uiGoEntry == 181676)
m_alHeiganTrapGuids[1].push_back(pGo->GetObjectGuid());
else if ((uiGoEntry >= 181534 && uiGoEntry <= 181544) || uiGoEntry == 181532 || uiGoEntry == 181677)
{
m_alHeiganTrapGuids[2].push_back(pGo->GetObjectGuid());
}
else if (uiGoEntry >= 181545 && uiGoEntry <= 181552)
{
if(pGo->GetDBTableGUIDLow() != 533119 && pGo->GetDBTableGUIDLow() != 533123) // duplicates
m_alHeiganTrapGuids[3].push_back(pGo->GetObjectGuid());
}
switch (pGo->GetDBTableGUIDLow())
{
case 533181:
case 533182:
case 533183:
case 533184:
case 533187:
case 533188:
case 533189:
case 533190:
case 533191:
case 533192:
case 533193:
case 533194:
case 533195:
case 533197:
case 533199:
case 533200:
m_alHeiganTrapGuids[3].push_back(pGo->GetObjectGuid());
break;
case 533185:
case 533196:
case 533198:
m_alHeiganTrapGuids[2].push_back(pGo->GetObjectGuid());
// case 533186:
}
}
switch (pGo->GetEntry())
{
// Arac wing
case GO_ARAC_ANUB_DOOR:
// starts closed by default, but must make sure it can be interracted with
pGo->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_NO_INTERACT | GO_FLAG_IN_USE);
break;
case GO_ARAC_ANUB_GATE:
UpdateManualDoor(pGo, m_auiEncounter[TYPE_ANUB_REKHAN]);
if (m_auiEncounter[TYPE_ANUB_REKHAN] == DONE)
pGo->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_NO_INTERACT);
break;
case GO_ARAC_FAER_WEB:
pGo->SetGoState(GO_STATE_ACTIVE);
break;
case GO_ARAC_FAER_DOOR:
UpdateManualDoor(pGo, m_auiEncounter[TYPE_FAERLINA]);
// todo: unable to get the door to be properly locked.
// It has the locked flags, and it displays as locked ingame,
// but with green text, aka it can be clicked and opened.
// hackfix by setting no interract flag unless it should be openable.
if (m_auiEncounter[TYPE_FAERLINA] == DONE)
pGo->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_NO_INTERACT);
else
pGo->SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_NO_INTERACT);
break;
case GO_ARAC_MAEX_OUTER_DOOR:
UpdateBossGate(pGo, m_auiEncounter[TYPE_FAERLINA]);
break;
case GO_ARAC_MAEX_INNER_DOOR:
pGo->SetGoState(GO_STATE_ACTIVE);
break;
// Plague wing
case GO_PLAG_NOTH_ENTRY_DOOR:
UpdateAutomaticBossEntranceDoor(pGo, m_auiEncounter[TYPE_NOTH]);
break;
case GO_PLAG_NOTH_EXIT_DOOR:
UpdateBossGate(pGo, m_auiEncounter[TYPE_NOTH]);
break;
case GO_PLAG_HEIG_ENTRY_DOOR:
UpdateAutomaticBossEntranceDoor(pGo, m_auiEncounter[TYPE_HEIGAN]);
break;
case GO_PLAG_HEIG_OLD_EXIT_DOOR:
case GO_PLAG_LOAT_DOOR:
UpdateBossGate(pGo, m_auiEncounter[TYPE_HEIGAN]);
break;
// Millitary wing
case GO_MILI_GOTH_ENTRY_GATE:
UpdateAutomaticBossEntranceDoor(pGo, m_auiEncounter[TYPE_RAZUVIOUS]);
break;
case GO_MILI_GOTH_EXIT_GATE:
UpdateBossGate(pGo, m_auiEncounter[TYPE_GOTHIK]);
break;
case GO_MILI_HORSEMEN_DOOR:
UpdateManualDoor(pGo, m_auiEncounter[TYPE_GOTHIK]);
break;
case GO_MILI_GOTH_COMBAT_GATE:
pGo->SetGoState(GO_STATE_ACTIVE);
break;
case GO_CHEST_HORSEMEN_NORM:
//todo: anything to be done?
break;
// Cons wing doors
case GO_CONS_PATH_EXIT_DOOR:
UpdateBossGate(pGo, m_auiEncounter[TYPE_PATCHWERK]);
break;
case GO_CONS_GLUT_EXIT_DOOR:
UpdateBossGate(pGo, m_auiEncounter[TYPE_GLUTH]);
case GO_CONS_THAD_DOOR:
UpdateManualDoor(pGo, m_auiEncounter[TYPE_GLUTH]);
break;
// Frostwyrm lair
case GO_KELTHUZAD_WATERFALL_DOOR:
case GO_KELTHUZAD_DOOR:
UpdateBossGate(pGo, m_auiEncounter[TYPE_SAPPHIRON]);
break;
// Teleporters visual thing
case GO_ARAC_EYE_RAMP:
case GO_ARAC_EYE_BOSS:
SetTeleporterVisualState(pGo, m_auiEncounter[TYPE_MAEXXNA]);
break;
case GO_PLAG_EYE_RAMP:
case GO_PLAG_EYE_BOSS:
SetTeleporterVisualState(pGo, m_auiEncounter[TYPE_LOATHEB]);
break;
case GO_MILI_EYE_RAMP:
case GO_MILI_EYE_BOSS:
SetTeleporterVisualState(pGo, m_auiEncounter[TYPE_FOUR_HORSEMEN]);
break;
case GO_CONS_EYE_RAMP:
case GO_CONS_EYE_BOSS:
SetTeleporterVisualState(pGo, m_auiEncounter[TYPE_THADDIUS]);
break;
// Actual teleporters
case GO_ARAC_PORTAL:
SetTeleporterState(pGo, m_auiEncounter[TYPE_MAEXXNA]);
break;
case GO_PLAG_PORTAL:
SetTeleporterState(pGo, m_auiEncounter[TYPE_LOATHEB]);
break;
case GO_MILI_PORTAL:
SetTeleporterState(pGo, m_auiEncounter[TYPE_FOUR_HORSEMEN]);
break;
case GO_CONS_PORTAL:
SetTeleporterState(pGo, m_auiEncounter[TYPE_THADDIUS]);
break;
case GO_KT_WINDOW_1:
case GO_KT_WINDOW_2:
case GO_KT_WINDOW_3:
case GO_KT_WINDOW_4:
if (m_auiEncounter[TYPE_KELTHUZAD] == DONE)
pGo->SetGoState(GO_STATE_ACTIVE);
else
pGo->SetGoState(GO_STATE_READY);
break;
case GO_CONS_NOX_TESLA_FEUGEN:
case GO_CONS_NOX_TESLA_STALAGG:
if (m_auiEncounter[TYPE_THADDIUS] == DONE)
pGo->SetGoState(GO_STATE_READY);
else
pGo->SetGoState(GO_STATE_ACTIVE);
case GO_SAPPHIRON_SPAWN:
if(m_auiEncounter[TYPE_SAPPHIRON] == DONE)
pGo->DeleteLater();
break;
}
}
void instance_naxxramas::OnCreatureRespawn(Creature * pCreature)
{
bool forcedDespawn = false;
switch (pCreature->GetEntry())
{
case NPC_ANUB_REKHAN:
forcedDespawn = (GetData(TYPE_ANUB_REKHAN) == DONE);
break;
case NPC_FAERLINA:
forcedDespawn = (GetData(TYPE_FAERLINA) == DONE);
break;
case NPC_MAEXXNA:
forcedDespawn = (GetData(TYPE_MAEXXNA) == DONE);
break;
case NPC_PATCHWERK:
forcedDespawn = (GetData(TYPE_PATCHWERK) == DONE);
break;
case NPC_GROBBULUS:
forcedDespawn = (GetData(TYPE_GROBBULUS) == DONE);
break;
case NPC_GLUTH:
forcedDespawn = (GetData(TYPE_GLUTH) == DONE);
break;
case NPC_THADDIUS:
forcedDespawn = (GetData(TYPE_THADDIUS) == DONE);
break;
case NPC_NOTH:
forcedDespawn = (GetData(TYPE_NOTH) == DONE);
break;
case NPC_HEIGAN:
forcedDespawn = (GetData(TYPE_HEIGAN) == DONE);
break;
case NPC_LOATHEB:
forcedDespawn = (GetData(TYPE_LOATHEB) == DONE);
break;
case NPC_RAZUVIOUS:
forcedDespawn = (GetData(TYPE_RAZUVIOUS) == DONE);
break;
case NPC_GOTHIK:
forcedDespawn = (GetData(TYPE_GOTHIK) == DONE);
break;
case NPC_ZELIEK:
case NPC_THANE:
case NPC_BLAUMEUX:
case NPC_MOGRAINE:
forcedDespawn = (GetData(TYPE_FOUR_HORSEMEN) == DONE);
break;
case NPC_SAPPHIRON:
forcedDespawn = (GetData(TYPE_SAPPHIRON) == DONE);
break;
case NPC_KELTHUZAD:
forcedDespawn = (GetData(TYPE_KELTHUZAD) == DONE);
break;
}
// Something, probably silly, makes gothik respawn, thus the trash
// linked to him gets a chance to respawn as well. Force-despawning his
// trash like this as well to prevent that. There should be no deathknight captains,
// deathknight cavaliers or necro knights after gothik, so this works.
// The hardcoded dbGUID is a lonely shade of naxxramas
if (GetData(TYPE_GOTHIK) == DONE)
{
uint32 e = pCreature->GetEntry();
if (e == NPC_UnholyAxe ||
e == NPC_UnholyStaff ||
e == NPC_UnholySwords ||
e == NPC_NecroKnight ||
e == NPC_DeathKnightCaptain ||
e == NPC_DeathKnightCavalier ||
pCreature->GetDBTableGUIDLow() == 88470)
{
forcedDespawn = true;
}
}
if (forcedDespawn)
{
pCreature->AddObjectToRemoveList();
}
}
bool instance_naxxramas::IsEncounterInProgress() const
{
for (uint32 i : m_auiEncounter)
if (i == IN_PROGRESS || i == SPECIAL)
return true;
return false;
}
void instance_naxxramas::SetData(uint32 uiType, uint32 uiData)
{
ASSERT(this)
bool sameStateAsLast = false;
if (uiType < MAX_ENCOUNTER)
sameStateAsLast = (m_auiEncounter[uiType] == uiData);
switch (uiType)
{
case TYPE_ANUB_REKHAN:
m_auiEncounter[uiType] = uiData;
if (GameObject* pGo = GetSingleGameObjectFromStorage(GO_ARAC_ANUB_DOOR))
{
if (uiData == IN_PROGRESS)
pGo->SetGoState(GO_STATE_READY);
else
pGo->SetGoState(GO_STATE_ACTIVE);
}
UpdateManualDoor(GO_ARAC_ANUB_GATE, uiData);
break;
case TYPE_FAERLINA:
m_auiEncounter[uiType] = uiData;
UpdateAutomaticBossEntranceDoor(GO_ARAC_FAER_WEB, uiData);
UpdateManualDoor(GO_ARAC_FAER_DOOR, uiData);
UpdateBossGate(GO_ARAC_MAEX_OUTER_DOOR, uiData);
// todo: unable to get the door to be properly locked.
// It has the locked flags, and it displays as locked ingame,
// but with green text, aka it can be clicked and opened.
// hackfix by setting no interract flag unless it should be openable.
if (GameObject* pGo = GetSingleGameObjectFromStorage(GO_ARAC_FAER_DOOR))
{
if(uiData == DONE)
pGo->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_NO_INTERACT);
else
pGo->SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_NO_INTERACT);
}
break;
case TYPE_MAEXXNA:
if (uiData == DONE)
m_events.ScheduleEvent(EVENT_WINGBOSS_DEAD, 10000);
m_auiEncounter[uiType] = uiData;
UpdateAutomaticBossEntranceDoor(GO_ARAC_MAEX_INNER_DOOR, uiData, m_auiEncounter[TYPE_FAERLINA]);
UpdateTeleporters(uiType, uiData);
break;
case TYPE_NOTH:
m_auiEncounter[uiType] = uiData;
UpdateAutomaticBossEntranceDoor(GO_PLAG_NOTH_ENTRY_DOOR, uiData);
UpdateBossGate(GO_PLAG_NOTH_EXIT_DOOR, uiData);
UpdateBossGate(GO_PLAG_HEIG_ENTRY_DOOR, uiData);
break;
case TYPE_HEIGAN:
m_auiEncounter[uiType] = uiData;
// entry door is controlled by boss script
UpdateBossGate(GO_PLAG_LOAT_DOOR, uiData);
UpdateBossGate(GO_PLAG_HEIG_OLD_EXIT_DOOR, uiData);
break;
case TYPE_LOATHEB:
if (uiData == DONE)
m_events.ScheduleEvent(EVENT_WINGBOSS_DEAD, 10000);
m_auiEncounter[uiType] = uiData;
UpdateAutomaticBossEntranceDoor(GO_PLAG_LOAT_DOOR, uiData, m_auiEncounter[TYPE_HEIGAN]);
UpdateTeleporters(uiType, uiData);
break;
case TYPE_RAZUVIOUS:
m_auiEncounter[uiType] = uiData;
UpdateBossGate(GO_MILI_GOTH_ENTRY_GATE, uiData);
break;
case TYPE_GOTHIK:
m_auiEncounter[uiType] = uiData;
UpdateAutomaticBossEntranceDoor(GO_MILI_GOTH_ENTRY_GATE, uiData);
UpdateBossGate(GO_MILI_GOTH_EXIT_GATE, uiData);
if (GameObject* pGO = GetSingleGameObjectFromStorage(GO_MILI_GOTH_COMBAT_GATE))
{
switch (uiData)
{
case IN_PROGRESS:
pGO->SetGoState(GO_STATE_READY);
break;
case SPECIAL:
pGO->SetGoState(GO_STATE_ACTIVE);
break;
case FAIL:
//if (m_auiEncounter[TYPE_GOTHIK] == IN_PROGRESS)
pGO->SetGoState(GO_STATE_ACTIVE);
break;
case DONE:
pGO->SetGoState(GO_STATE_ACTIVE);
m_events.ScheduleEvent(EVENT_4HM_DIALOGUE_1, Seconds(10)); // todo: don't know if it should trigger here or when opening 4hm door
break;
}
}
UpdateManualDoor(GO_MILI_HORSEMEN_DOOR, uiData);
break;
case TYPE_FOUR_HORSEMEN:
if(uiData == DONE)
m_events.ScheduleEvent(EVENT_WINGBOSS_DEAD, 10000);
m_auiEncounter[uiType] = uiData;
UpdateAutomaticBossEntranceDoor(GO_MILI_HORSEMEN_DOOR, uiData, m_auiEncounter[TYPE_GOTHIK]);
UpdateTeleporters(uiType, uiData);
if (uiData == SPECIAL)
{
++m_horsemenDeathCounter;
if (m_horsemenDeathCounter >= 4)
{
SetData(TYPE_FOUR_HORSEMEN, DONE);
}
}
else if(uiData == FAIL)
{
m_horsemenDeathCounter = 0;
for (uint32 i = NPC_MOGRAINE; i <= NPC_BLAUMEUX; i++)
{
if (Creature* p = GetSingleCreatureFromStorage(i))
if (p->IsDead())
p->Respawn();
}
}
else if (uiData == DONE)
{
// spawns it for 30 minutes?
DoRespawnGameObject(m_uiHorsemenChestGUID);
std::list<Creature*> spirits;
GetCreatureListWithEntryInGrid(spirits, GetSingleCreatureFromStorage(NPC_ZELIEK), { 16775, 16776, 16777, 16778}, 300.0f);
for (Creature* pC : spirits)
pC->DeleteLater();
// reputation
FactionEntry const *factionEntry = sObjectMgr.GetFactionEntry(529); // Argent Dawn
if (factionEntry)
{
Map::PlayerList const &liste = GetMap()->GetPlayers();
for (const auto& i : liste)
{
if (Player* pPlayer = i.getSource())
{
pPlayer->GetReputationMgr().ModifyReputation(factionEntry, 100);
}
}
}
else
{
sLog.Out(LOG_SCRIPTS, LOG_LVL_ERROR, "4hm just died. Unable to find Argent Dawn faction for reputation ");
}
}
break;
case TYPE_PATCHWERK:
m_auiEncounter[uiType] = uiData;
UpdateBossGate(GO_CONS_PATH_EXIT_DOOR, uiData);
break;
case TYPE_GROBBULUS:
UpdateAutomaticBossEntranceDoor(GO_CONS_PATH_EXIT_DOOR, uiData, m_auiEncounter[TYPE_PATCHWERK]);
m_auiEncounter[uiType] = uiData;
break;
case TYPE_GLUTH:
m_auiEncounter[uiType] = uiData;
UpdateBossGate(GO_CONS_GLUT_EXIT_DOOR, uiData);
UpdateManualDoor(GO_CONS_THAD_DOOR, uiData);
break;
case TYPE_THADDIUS:
// Only set the same state once
if (uiData == m_auiEncounter[uiType])
break;
if (uiData == DONE)
m_events.ScheduleEvent(EVENT_WINGBOSS_DEAD, 10000);
m_auiEncounter[uiType] = uiData;
UpdateAutomaticBossEntranceDoor(GO_CONS_THAD_DOOR, uiData, m_auiEncounter[TYPE_GLUTH]);
UpdateTeleporters(uiType, uiData);
break;
case TYPE_SAPPHIRON:
if(uiData == DONE)
m_events.ScheduleEvent(EVENT_KT_LK_DIALOGUE_1, 12000);
m_auiEncounter[uiType] = uiData;
UpdateBossGate(GO_KELTHUZAD_WATERFALL_DOOR, uiData);
// GO_KELTHUZAD_DOOR is opened at the end of EVENT_KT_LK_DIALOGUE
break;
case TYPE_KELTHUZAD:
UpdateAutomaticBossEntranceDoor(GO_KELTHUZAD_DOOR, uiData, m_auiEncounter[TYPE_SAPPHIRON]);
switch (uiData)
{
case SPECIAL:
{
Map::PlayerList const& lPlayers = instance->GetPlayers();
if (lPlayers.isEmpty())
return;
bool bCanBegin = true;
for (const auto& itr : lPlayers)
{
if (Player* pPlayer = itr.getSource())
{
if (!pPlayer->IsWithinDist2d(m_fChamberCenterX, m_fChamberCenterY, 15.0f))
bCanBegin = false;
}
}
if (bCanBegin)
m_auiEncounter[uiType] = IN_PROGRESS;
break;
}
case FAIL:
m_auiEncounter[uiType] = NOT_STARTED;
break;
default:
m_auiEncounter[uiType] = uiData;
break;
}
break;
}
if (uiData == FAIL && !sameStateAsLast)
{
uint32 entry = 0;
switch (uiType)
{
case TYPE_ANUB_REKHAN:
entry = NPC_ANUB_REKHAN;
break;
case TYPE_FAERLINA:
entry = NPC_FAERLINA;
break;
case TYPE_MAEXXNA:
entry = NPC_MAEXXNA;
break;
case TYPE_NOTH:
entry = NPC_NOTH;
break;
case TYPE_HEIGAN:
entry = NPC_HEIGAN;
break;
case TYPE_LOATHEB:
entry = NPC_LOATHEB;
break;
case TYPE_RAZUVIOUS:
entry = NPC_RAZUVIOUS;
break;
case TYPE_GOTHIK:
entry = NPC_GOTHIK;
break;
case TYPE_FOUR_HORSEMEN:
{
entry = NPC_ZELIEK;
}
break;
case TYPE_PATCHWERK:
entry = NPC_PATCHWERK;
break;
case TYPE_GROBBULUS:
entry = NPC_GROBBULUS;
break;
case TYPE_GLUTH:
entry = NPC_GLUTH;
break;
case TYPE_THADDIUS:
entry = NPC_THADDIUS;
break;
case TYPE_SAPPHIRON:
entry = NPC_SAPPHIRON;
break;
case TYPE_KELTHUZAD:
entry = NPC_KELTHUZAD;
break;
}
if (entry)
{
if (Creature* pCreature = GetSingleCreatureFromStorage(entry))
{
// Crude check to to avoid silly data clogging up our statistics
// We only update the wipe counter if the boss has been in combat for at least 10 seconds
if (pCreature->GetCombatTime(false) > 10)
{
sInstanceStatistics.IncrementWipeCounter(MAP_NAXXRAMAS, entry);
if (entry == NPC_ZELIEK)
{
// special case handling for these 4hm buggers
sInstanceStatistics.IncrementWipeCounter(MAP_NAXXRAMAS, NPC_MOGRAINE);
sInstanceStatistics.IncrementWipeCounter(MAP_NAXXRAMAS, NPC_BLAUMEUX);
sInstanceStatistics.IncrementWipeCounter(MAP_NAXXRAMAS, NPC_THANE);
}
}
}
}
}
if (uiData == DONE)
{
OUT_SAVE_INST_DATA;
std::ostringstream saveStream;
for (uint32 i : m_auiEncounter)
saveStream << i << " ";
strInstData = saveStream.str();
SaveToDB();
OUT_SAVE_INST_DATA_COMPLETE;
}
}
void instance_naxxramas::Load(char const* chrIn)
{
if (!chrIn)
{
OUT_LOAD_INST_DATA_FAIL;
return;
}
OUT_LOAD_INST_DATA(chrIn);
std::istringstream loadStream(chrIn);
for (uint32 & i : m_auiEncounter)
{
loadStream >> i;
if (i == IN_PROGRESS)
i = NOT_STARTED;
}
if (m_auiEncounter[TYPE_THADDIUS] == SPECIAL)
m_auiEncounter[TYPE_THADDIUS] = FAIL;
//todo: at least 4hm might need to be changed from SPECIAL to FAIL/NOT_STARTED as well
OUT_LOAD_INST_DATA_COMPLETE;
}
uint32 instance_naxxramas::GetData(uint32 uiType)
{
if (uiType < MAX_ENCOUNTER)
return m_auiEncounter[uiType];
sLog.Out(LOG_SCRIPTS, LOG_LVL_ERROR, "instance_naxxramas::GetData() called with %d as param. %d is MAX_ENCOUNTERS", uiType, MAX_ENCOUNTER);
return 0;
}
uint64 instance_naxxramas::GetData64(uint32 uiData)
{
sLog.Out(LOG_SCRIPTS, LOG_LVL_BASIC, "instance_naxxramas::GetData64 called. Not implemented");
return 0;
}
uint64 instance_naxxramas::GetGOUuid(NaxxGOs which)
{
auto it = m_mNpcEntryGuidStore.find(which);
if (it == m_mNpcEntryGuidStore.end())
{
sLog.Out(LOG_SCRIPTS, LOG_LVL_ERROR, "instance_naxxramas::GetGOUuid called with param %d, not found", which);
return 0;
}
return it->second;
}
void instance_naxxramas::SetGothTriggers()
{
Creature* pGoth = GetSingleCreatureFromStorage(NPC_GOTHIK);
if (!pGoth)
return;
for (const auto& guid : m_lGothTriggerList)
{
if (Creature* pTrigger = instance->GetCreature(guid))
{
GothTrigger pGt;
pGt.bIsAnchorHigh = (pTrigger->GetPositionZ() >= (pGoth->GetPositionZ() - 5.0f));
pGt.bIsRightSide = IsInRightSideGothArea(pTrigger);
m_mGothTriggerMap[pTrigger->GetGUID()] = pGt;
}
}
}
Creature* instance_naxxramas::GetClosestAnchorForGoth(Creature* pSource, bool bRightSide)
{
std::list<Creature* > lList;
for (const auto& itr : m_mGothTriggerMap)
{
if (!itr.second.bIsAnchorHigh)
continue;
if (itr.second.bIsRightSide != bRightSide)
continue;
if (Creature* pCreature = instance->GetCreature(itr.first))
lList.push_back(pCreature);
}
if (!lList.empty())
{
lList.sort(ObjectDistanceOrder(pSource));
return lList.front();
}
return nullptr;
}
void instance_naxxramas::GetGothSummonPointCreatures(std::list<Creature*> &lList, bool bRightSide)
{
for (const auto& itr : m_mGothTriggerMap)
{
if (itr.second.bIsAnchorHigh)
continue;
if (itr.second.bIsRightSide != bRightSide)
continue;
if (Creature* pCreature = instance->GetCreature(itr.first))
lList.push_back(pCreature);
}
}
bool instance_naxxramas::IsInRightSideGothArea(Unit const* pUnit)
{
if (GameObject* pCombatGate = GetSingleGameObjectFromStorage(GO_MILI_GOTH_COMBAT_GATE))
return (pCombatGate->GetPositionY() >= pUnit->GetPositionY());
sLog.Out(LOG_SCRIPTS, LOG_LVL_ERROR, "left/right side check, Gothik combat area failed.");
return true;
}
void instance_naxxramas::SetChamberCenterCoords(float fX, float fY, float fZ)
{
m_fChamberCenterX = fX;
m_fChamberCenterY = fY;
m_fChamberCenterZ = fZ;
}
void instance_naxxramas::ToggleKelThuzadWindows(bool setOpen)
{
for (int i = GO_KT_WINDOW_1; i <= GO_KT_WINDOW_4; i++)
{
if (GameObject* pGo = GetSingleGameObjectFromStorage(i))
pGo->SetGoState(setOpen ? GO_STATE_ACTIVE : GO_STATE_READY);
}
}
void instance_naxxramas::OnPlayerDeath(Player* p)
{
if (m_auiEncounter[TYPE_ANUB_REKHAN] == IN_PROGRESS)
{
// On player death we spawn 5 scarabs under the player. Since the player
// can die from falldmg or other sources, anubs script impl of KilledUnit may not
// be called, thus we need to do it here.
if (Creature* pAnub = GetSingleCreatureFromStorage(NPC_ANUB_REKHAN))
{
//pAnub->AI()->DoCast(p, 29105, true);
pAnub->SendSpellGo(p, 28864);
for (int i = 0; i < 5; i++)
{
if (Creature* cs = pAnub->SummonCreature(16698, p->GetPositionX(), p->GetPositionY(), p->GetPositionZ(), 0,
TEMPSUMMON_CORPSE_DESPAWN))
{
cs->SetInCombatWithZone();
if (Unit* csTarget = pAnub->SelectAttackingTarget(ATTACKING_TARGET_RANDOM, 0))
{
cs->AI()->AttackStart(csTarget);
cs->AddThreat(csTarget, 5000);
}
}
}
}
}
}
void instance_naxxramas::OnCreatureDeath(Creature* pCreature)
{
switch (pCreature->GetEntry())
{
case NPC_MR_BIGGLESWORTH:
{
if(GetData(TYPE_KELTHUZAD) != DONE)
{
m_events.ScheduleEvent(EVENT_BIGGLESWORTH_DIED_YELL, 1000);
sInstanceStatistics.IncrementCustomCounter(MR_BIGGLESWORTH_KILLS, true);
}
break;
}
case NPC_FrenziedBat:
case NPC_PlaguedBat:
case NPC_MutatedGrub:
case NPC_PlagueBeast:
pCreature->ForcedDespawn(10000);
break;
case NPC_EmbalmingSlime:
pCreature->ForcedDespawn(30000);
break;
case NPC_LightningTotem:
pCreature->DeleteLater();
break;
}
}
void instance_naxxramas::Update(uint32 diff)
{
m_events.Update(diff);
while (auto l_EventId = m_events.ExecuteEvent())
{
switch (l_EventId)
{
case EVENT_BIGGLESWORTH_DIED_YELL:
DoOrSimulateScriptTextForThisInstance(KELTHUZAD_SAY_CAT_DIED, NPC_KELTHUZAD);
break;
case EVENT_THADDIUS_SCREAM:
if (m_auiEncounter[TYPE_THADDIUS] != DONE)
{
if (m_auiEncounter[TYPE_THADDIUS] != IN_PROGRESS && m_auiEncounter[TYPE_THADDIUS] != SPECIAL)
DoOrSimulateScriptTextForThisInstance(THADDIUS_SAY_SCREAM1 + urand(0, 3), NPC_THADDIUS);
m_events.ScheduleEvent(EVENT_THADDIUS_SCREAM, Minutes(urand(5,10)));
}
break;
case EVENT_WINGBOSS_DEAD:
DoOrSimulateScriptTextForThisInstance(KELTHUZAD_SAY_TAUNT1 + GetNumEndbossDead()-1, NPC_KELTHUZAD);
break;
case EVENT_KT_LK_DIALOGUE_1:
DoOrSimulateScriptTextForThisInstance(SAY_SAPP_DIALOG1, NPC_KELTHUZAD);
m_events.ScheduleEvent(EVENT_KT_LK_DIALOGUE_2, Seconds(5));
break;
case EVENT_KT_LK_DIALOGUE_2:
DoOrSimulateScriptTextForThisInstance(SAY_SAPP_DIALOG2_LICH, NPC_LICH_KING);
m_events.ScheduleEvent(EVENT_KT_LK_DIALOGUE_3, 16500);
break;
case EVENT_KT_LK_DIALOGUE_3:
DoOrSimulateScriptTextForThisInstance(SAY_SAPP_DIALOG3, NPC_KELTHUZAD);
m_events.ScheduleEvent(EVENT_KT_LK_DIALOGUE_4, Seconds(6));
break;
case EVENT_KT_LK_DIALOGUE_4:
DoOrSimulateScriptTextForThisInstance(SAY_SAPP_DIALOG4_LICH, NPC_LICH_KING);
m_events.ScheduleEvent(EVENT_KT_LK_DIALOGUE_5, Seconds(8));
break;
case EVENT_KT_LK_DIALOGUE_5:
DoOrSimulateScriptTextForThisInstance(SAY_SAPP_DIALOG5, NPC_KELTHUZAD);
m_events.ScheduleEvent(EVENT_KT_LK_DIALOGUE_GATE_OPEN, 5500);
break;
case EVENT_KT_LK_DIALOGUE_GATE_OPEN:
UpdateBossGate(GO_KELTHUZAD_DOOR, DONE);
break;
case EVENT_SUMMON_FROGGER_WAVE:
{
static constexpr float pos[6][4] = {
{3128.66f, -3121.27f, 293.341f, 4.73893f},
{3154.58f, -3126.18f, 293.591f, 4.43020f},
{3175.28f, -3134.76f, 293.437f, 4.24492f},
{3129.630f, -3157.652f, 293.32f, 4.73893f},
{3144.894f, -3159.587f, 293.32f, 4.43020f},
{3159.510f, -3166.001f, 293.27f, 4.24492f} };
for (int i = 0; i < 3; i++)
{
if (Creature* frogger = instance->SummonCreature(NPC_LivingPoison, pos[i][0], pos[i][1], pos[i][2], pos[i][3], TEMPSUMMON_TIMED_DESPAWN, 13000))
{
frogger->GetMotionMaster()->MovePoint(0, pos[i+3][0], pos[i + 3][1], pos[i + 3][2], pos[i + 3][3]);
}
}
m_events.Repeat(Seconds(6));
break;
}
case EVENT_4HM_DIALOGUE_1:
DoOrSimulateScriptTextForMap(SAY_4HM_DIALOGUE_1, NPC_ZELIEK, GetMap(), GetSingleCreatureFromStorage(NPC_ZELIEK));
m_events.ScheduleEvent(EVENT_4HM_DIALOGUE_2, Seconds(7));
break;
case EVENT_4HM_DIALOGUE_2:
DoOrSimulateScriptTextForMap(SAY_4HM_DIALOGUE_2, NPC_BLAUMEUX, GetMap(), GetSingleCreatureFromStorage(NPC_BLAUMEUX));
m_events.ScheduleEvent(EVENT_4HM_DIALOGUE_3, Seconds(7));
break;
case EVENT_4HM_DIALOGUE_3:
DoOrSimulateScriptTextForMap(SAY_4HM_DIALOGUE_3, NPC_MOGRAINE, GetMap(), GetSingleCreatureFromStorage(NPC_MOGRAINE));
m_events.ScheduleEvent(EVENT_4HM_DIALOGUE_4, Seconds(7));
break;
case EVENT_4HM_DIALOGUE_4:
DoOrSimulateScriptTextForMap(SAY_4HM_DIALOGUE_4, NPC_BLAUMEUX, GetMap(), GetSingleCreatureFromStorage(NPC_BLAUMEUX));
m_events.ScheduleEvent(EVENT_4HM_DIALOGUE_5, Seconds(7));
break;
case EVENT_4HM_DIALOGUE_5:
DoOrSimulateScriptTextForMap(SAY_4HM_DIALOGUE_5, NPC_ZELIEK, GetMap(), GetSingleCreatureFromStorage(NPC_ZELIEK));
m_events.ScheduleEvent(EVENT_4HM_DIALOGUE_6, Seconds(6));
break;
case EVENT_4HM_DIALOGUE_6:
DoOrSimulateScriptTextForMap(SAY_4HM_DIALOGUE_6, NPC_THANE, GetMap(), GetSingleCreatureFromStorage(NPC_THANE));
m_events.ScheduleEvent(EVENT_4HM_DIALOGUE_7, Seconds(7));
break;
case EVENT_4HM_DIALOGUE_7:
DoOrSimulateScriptTextForMap(SAY_4HM_DIALOGUE_7, NPC_MOGRAINE, GetMap(), GetSingleCreatureFromStorage(NPC_MOGRAINE));
break;
case EVENT_DKWING_INTRO_2:
DoOrSimulateScriptTextForMap(SAY_ZELI_TAUNT3, NPC_ZELIEK, GetMap(), GetSingleCreatureFromStorage(NPC_ZELIEK));
m_events.ScheduleEvent(EVENT_DKWING_INTRO_3, 5000);
break;
case EVENT_DKWING_INTRO_3:
DoOrSimulateScriptTextForMap(SAY_MOG_TAUNT3, NPC_MOGRAINE, GetMap(), GetSingleCreatureFromStorage(NPC_MOGRAINE));
m_events.ScheduleEvent(EVENT_DKWING_INTRO_4, 6200);
break;
case EVENT_DKWING_INTRO_4:
DoOrSimulateScriptTextForMap(SAY_BLAU_TAUNT3, NPC_BLAUMEUX, GetMap(), GetSingleCreatureFromStorage(NPC_BLAUMEUX));
break;
}
}
}
InstanceData* GetInstanceData_instance_naxxramas(Map* pMap)
{
return new instance_naxxramas(pMap);
}
void instance_naxxramas::onNaxxramasAreaTrigger(Player* pPlayer, AreaTriggerEntry const* pAt)
{
switch (pAt->id)
{
case AREATRIGGER_HUB_TO_FROSTWYRM:
if (WingsAreCleared())
{
pPlayer->TeleportTo(toFrostwyrmTPPos);
}
break;
case AREATRIGGER_KELTHUZAD:
OnKTAreaTrigger(pAt);
break;
case AREATRIGGER_FAERLINA:
if (!m_faerlinaHaveGreeted)
{
m_faerlinaHaveGreeted = true;
if (Creature* pFaerlina = GetSingleCreatureFromStorage(NPC_FAERLINA))
{
if(pFaerlina->IsAlive())
DoScriptText(SAY_FAERLINA_GREET, pFaerlina);
}
}
break;
case AREATRIGGER_THADDIUS_ENTRANCE:
if (!m_thaddiusHaveGreeted)
{
m_thaddiusHaveGreeted = true;
if (Creature* pThaddius = GetSingleCreatureFromStorage(NPC_THADDIUS))
{
if (pThaddius->IsAlive())
DoScriptText(SAY_THADDIUS_GREET, pThaddius);
}
}
break;
case AREATRIGGER_START_DK_WING:
if (!m_haveDoneDKWingIntro)
{
m_haveDoneDKWingIntro = true;
if (GetData(TYPE_FOUR_HORSEMEN) != DONE)
{
DoOrSimulateScriptTextForMap(SAY_KORT_TAUNT1, NPC_THANE, GetMap(), GetSingleCreatureFromStorage(NPC_THANE));
m_events.ScheduleEvent(EVENT_DKWING_INTRO_2, 5500);
}
}
break;
}
}
bool AreaTrigger_at_naxxramas(Player* pPlayer, AreaTriggerEntry const* pAt)
{
if (pPlayer->IsGameMaster() || !pPlayer->IsAlive())
return false;
if (instance_naxxramas* pInstance = (instance_naxxramas*)pPlayer->GetInstanceData())
{
pInstance->onNaxxramasAreaTrigger(pPlayer, pAt);
}
return false;
}
struct mob_spiritOfNaxxramasAI : public ScriptedAI
{
mob_spiritOfNaxxramasAI(Creature* pCreature) : ScriptedAI(pCreature)
{
Reset();
m_creature->CastSpell(m_creature, 18950, true); // stealth detection
}
ObjectGuid portal;
uint32 portalTimer;
uint32 shadowboltVolleyTimer;
void DespawnPortal()
{
if (!portal)
return;
if (Creature* pPortal = m_creature->GetMap()->GetCreature(portal))
{
static_cast<TemporarySummon*>(pPortal)->UnSummon();
}
portal = 0;
}
void Reset() override
{
portalTimer = 5000;
shadowboltVolleyTimer = 6000;
DespawnPortal();
}
void JustDied(Unit* pKiller) override
{
DespawnPortal();
}
void UpdateAI(uint32 const diff) override
{
if (!m_creature->SelectHostileTarget() || !m_creature->GetVictim())
return;
if (portalTimer)
{
if (portalTimer < diff)
{
// summon portal of shadows
if (Creature* pCreature = m_creature->SummonCreature(16420, m_creature->GetPositionX(), m_creature->GetPositionY(), m_creature->GetPositionZ(), 0,
TEMPSUMMON_TIMED_DESPAWN, 60000))
{
m_creature->SendSpellGo(m_creature, 28383); // since we're manually summoning, we also send the visual that we're not using
portal = pCreature->GetObjectGuid();
pCreature->CastSpell(pCreature, 28384, true); // pCreature casts portal of shadow spell on self
portalTimer = 0;
}
}
else
portalTimer -= diff;
}
// casting shadowbolt volley every 10 sec
if (shadowboltVolleyTimer < diff)
{
if (DoCastSpellIfCan(m_creature, 28599) == CAST_OK)
{
shadowboltVolleyTimer = 10000;
}
}
else
shadowboltVolleyTimer -= diff;
DoMeleeAttackIfReady();
}
};
enum
{
SPELL_INVISIBILITY_AND_STEALTH_DETECTION = 18950,
SPELL_STONESKIN = 28995, // Periodic Heal and Damage Immunity
SPELL_GARGOYLE_STONEFORM_VISUAL = 29153, // Dummy Aura
SPELL_ACID_VOLLEY = 29325,
BCT_STRANGE_NOISE = 10755, // %s emits a strange noise.
};
struct mob_naxxramasGarboyleAI : public ScriptedAI
{
mob_naxxramasGarboyleAI(Creature* pCreature)
: ScriptedAI(pCreature)
{
Reset();
EnterStoneform();
if (m_creature->GetDefaultMovementType() == IDLE_MOTION_TYPE && m_creature->GetEntry() == 16168)
m_creature->CastSpell(m_creature, SPELL_INVISIBILITY_AND_STEALTH_DETECTION, true);
}
void EnterStoneform()
{
if (m_creature->GetDefaultMovementType() == IDLE_MOTION_TYPE && m_creature->GetEntry() == 16168)
m_creature->CastSpell(m_creature, SPELL_GARGOYLE_STONEFORM_VISUAL, true);
}
uint32 m_uiAcidVolleyTimer;
void Reset() override
{
m_uiAcidVolleyTimer = urand(2800, 6500);
}
void JustReachedHome() override
{
EnterStoneform();
}
void MoveInLineOfSight(Unit* pWho) override
{
if (m_creature->HasAura(SPELL_GARGOYLE_STONEFORM_VISUAL))
{
if (pWho->GetTypeId() == TYPEID_PLAYER
&& !m_creature->IsInCombat()
&& m_creature->IsWithinDistInMap(pWho, 17.0f)
&& m_creature->IsWithinLOSInMap(pWho)
&& !pWho->HasAuraType(SPELL_AURA_FEIGN_DEATH)
&& !pWho->HasAuraType(SPELL_AURA_MOD_UNATTACKABLE))
{
AttackStart(pWho);
}
}
else
{
ScriptedAI::MoveInLineOfSight(pWho);
}
}
void Aggro(Unit*) override
{
if (m_creature->HasAura(SPELL_GARGOYLE_STONEFORM_VISUAL))
m_creature->RemoveAurasDueToSpellByCancel(SPELL_GARGOYLE_STONEFORM_VISUAL);
}
void UpdateAI(uint32 const diff) override
{
if (!m_creature->SelectHostileTarget() || !m_creature->GetVictim())
return;
if (m_creature->GetHealthPercent() < 30.0f && !m_creature->IsNonMeleeSpellCasted() && !m_creature->HasAura(SPELL_STONESKIN))
{
if (DoCastSpellIfCan(m_creature, SPELL_STONESKIN) == CAST_OK)
{
m_creature->CastSpell(m_creature, SPELL_STONESKIN, true);
DoScriptText(BCT_STRANGE_NOISE, m_creature);
}
}
if (m_uiAcidVolleyTimer < diff && !m_creature->IsNonMeleeSpellCasted())
{
// supposedly the first gargoyle in plague wing did not do the acid volley, so
// hackfix here to skip him
if (m_creature->GetDBTableGUIDLow() != 88095)
{
if (DoCastSpellIfCan(m_creature, SPELL_ACID_VOLLEY) == CAST_OK) // acid volley
m_uiAcidVolleyTimer = 8000;
}
}
else
m_uiAcidVolleyTimer -= diff;
DoMeleeAttackIfReady();
}
};
struct mob_naxxramasPlagueSlimeAI : public ScriptedAI
{
mob_naxxramasPlagueSlimeAI(Creature* pCreature) : ScriptedAI(pCreature)
{
Reset();
prev_spell = 0;
}
uint32 colorChangeTimer;
uint32 prev_spell;
void ChangeColor()
{
uint32 spell = urand(28987, 28990);
if(SpellEntry const* entry = sSpellMgr.GetSpellEntry(spell))
m_creature->UpdateEntry(entry->EffectMiscValue[0]);
if (prev_spell)
m_creature->RemoveAurasDueToSpell(prev_spell);
DoCastSpellIfCan(m_creature, spell, CF_TRIGGERED);
m_creature->SetObjectScale(2.0f); // updateentry and the actual spells screws up the scale...
prev_spell = spell;
}
void Reset() override
{
colorChangeTimer = 0;
ChangeColor();
}
void Aggro(Unit*) override
{
m_creature->CallForHelp(10.0f);
}
void UpdateAI(uint32 const diff) override
{
if (!m_creature->SelectHostileTarget() || !m_creature->GetVictim())
return;
if (colorChangeTimer < diff)
{
colorChangeTimer = urand(9000, 12000); // todo: no idea if timer is correct
ChangeColor();
}
else
colorChangeTimer -= diff;
DoMeleeAttackIfReady();
}
};
struct mob_toxic_tunnelAI : public ScriptedAI
{
mob_toxic_tunnelAI(Creature* pCreature) : ScriptedAI(pCreature)
{
Reset();
}
uint32 checktime;
uint32 _evadeTimer;
void Reset() override
{
checktime = 0;
_evadeTimer = 0;
}
void AttackStart(Unit*) override { }
void MoveInLineOfSight(Unit*) override { }
void EnterCombat(Unit*) override
{
// Poison aura is hitting someone. Start a short timer to evade & drop combat
if (!_evadeTimer)
_evadeTimer = 5000;
}
void UpdateAI(uint32 const diff) override
{
if (!!_evadeTimer)
{
if (_evadeTimer <= diff)
{
EnterEvadeMode();
_evadeTimer = 0;
}
else
_evadeTimer -= diff;
}
// creature_template_addons should make this aura permanent, but check anyway due
// to some reports of it not recasting
if (checktime <= diff)
{
checktime = 5000;
if (!m_creature->HasAura(28370))
m_creature->CastSpell(m_creature, 28370, true);
}
else
checktime -= diff;
}
};
struct mob_dark_touched_warriorAI : public ScriptedAI
{
mob_dark_touched_warriorAI(Creature* pCreature) : ScriptedAI(pCreature)
{
Reset();
}
bool hasFled;
void Reset() override
{
hasFled = false;
}
void FleeToHorse()
{
if (!m_creature->GetVictim() || m_creature->HasAuraType(SPELL_AURA_PREVENTS_FLEEING))
return;
Creature* pNearest = nullptr;
MaNGOS::NearestCreatureEntryWithLiveStateInObjectRangeCheck u_check(*m_creature, 16067, true, 100.0f);
MaNGOS::CreatureLastSearcher<MaNGOS::NearestCreatureEntryWithLiveStateInObjectRangeCheck> searcher(pNearest, u_check);
Cell::VisitGridObjects(m_creature, searcher, 100.0f);
if (pNearest)
{
m_creature->GetMotionMaster()->MoveSeekAssistance(pNearest->GetPositionX(), pNearest->GetPositionY(), pNearest->GetPositionZ());
m_creature->SetTargetGuid(ObjectGuid());
m_creature->UpdateSpeed(MOVE_RUN, false);
m_creature->InterruptSpellsWithInterruptFlags(SPELL_INTERRUPT_FLAG_MOVEMENT);
}
}
void UpdateAI(uint32 const diff) override
{
if (!m_creature->SelectHostileTarget() || !m_creature->GetVictim())
return;
if (!hasFled && m_creature->GetHealthPercent() < 50.0f)
{
hasFled = true;
FleeToHorse();
}
DoMeleeAttackIfReady();
}
};
CreatureAI* GetAI_mob_spiritOfNaxxramas(Creature* pCreature)
{
return new mob_spiritOfNaxxramasAI(pCreature);
}
CreatureAI* GetAI_mob_naxxramasGargoyle(Creature* pCreature)
{
return new mob_naxxramasGarboyleAI(pCreature);
}
CreatureAI* GetAI_mob_plagueSlimeAI(Creature* pCreature)
{
return new mob_naxxramasPlagueSlimeAI(pCreature);
}
CreatureAI* GetAI_toxic_tunnel(Creature* pCreature)
{
return new mob_toxic_tunnelAI(pCreature);
}
CreatureAI* GetAI_dark_touched_warrior(Creature* pCreature)
{
return new mob_dark_touched_warriorAI(pCreature);
}
enum OmarionMisc
{
QUEST_OMARIONS_HANDBOOK = 9233,
BC_TAILOR_TEXT = 12251, // I am a master tailor, Omarion.
BC_BLACKSMITH_TEXT = 12269, // I am a master blacksmith, Omarion.
BC_LEATHERWORKER_TEXT = 12257, // I am a master leatherworker, Omarion.
BC_NO_CRAFT_TEXT = 12279, // Omarion, I am not a craftsman. Can you still help me?
BC_CLOSE_NO_CRAFTER = 12281, // Thank you, Omarion. You have taken a fatal blow for the team on this day.
BC_CLOSE_CRAFTER = 12270, // I need to go. Evil stirs. Die well, Omarion.
GOSSIP_MENU_INTRO = 8507,
GOSSIP_MENU_CRAFTER = 8508,
GOSSIP_MENU_NOCRAFT = 8516,
GOSSIP_OPT_NOT_CRAFTSMAN = 1,
GOSSIP_SELECT_TAILOR = GOSSIP_ACTION_INFO_DEF + 1,
GOSSIP_SELECT_BS = GOSSIP_ACTION_INFO_DEF + 2,
GOSSIP_SELECT_LW = GOSSIP_ACTION_INFO_DEF + 3,
GOSSIP_SELECT_NOCRAFT = GOSSIP_ACTION_INFO_DEF + 4,
GOSSIP_SELECT_CRAFT_BEGIN = GOSSIP_ACTION_INFO_DEF + 10,
GOSSIP_SELECT_GLACIAL_GLOVES = GOSSIP_SELECT_CRAFT_BEGIN + 1, // tailor honored
GOSSIP_SELECT_GLACIAL_WRISTS = GOSSIP_SELECT_CRAFT_BEGIN + 2, // tailor honored
GOSSIP_SELECT_GLACIAL_CHEST = GOSSIP_SELECT_CRAFT_BEGIN + 3, // tailor exalted
GOSSIP_SELECT_GLACIAL_CLOAK = GOSSIP_SELECT_CRAFT_BEGIN + 4, // tailor exalted
GOSSIP_SELECT_POLAR_GLOVES = GOSSIP_SELECT_CRAFT_BEGIN + 5, // LW honored
GOSSIP_SELECT_POLAR_WRISTS = GOSSIP_SELECT_CRAFT_BEGIN + 6, // LW honored
GOSSIP_SELECT_POLAR_CHEST = GOSSIP_SELECT_CRAFT_BEGIN + 7, // LW exalted
GOSSIP_SELECT_ICYSCALE_GLOVES = GOSSIP_SELECT_CRAFT_BEGIN + 8, // LW honored
GOSSIP_SELECT_ICYSCALE_WRISTS = GOSSIP_SELECT_CRAFT_BEGIN + 9, // LW honored
GOSSIP_SELECT_ICYSCALE_CHEST = GOSSIP_SELECT_CRAFT_BEGIN + 10, // LW exalted
GOSSIP_SELECT_ICEBANE_GLOVES = GOSSIP_SELECT_CRAFT_BEGIN + 11, // BS exalted
GOSSIP_SELECT_ICEBANE_WRISTS = GOSSIP_SELECT_CRAFT_BEGIN + 12, // BS exalted
GOSSIP_SELECT_ICEBANE_CHEST = GOSSIP_SELECT_CRAFT_BEGIN + 13, // BS exalted
GOSSIP_CLOSE = 100
};
void LearnCraftIfCan(uint32 learnId, uint32 knowId, Player* pPlayer, ReputationRank minRank, uint32 currSkill)
{
uint32 argentDawnRep = pPlayer->GetReputationRank(529);
if (argentDawnRep < minRank)
return;
if (currSkill < 300)
return;
if (!pPlayer->HasSpell(knowId))
pPlayer->CastSpell(pPlayer, learnId, false);
}
bool GossipSelect_npc_MasterCraftsmanOmarion(Player* pPlayer, Creature* pCreature, uint32 uiSender, uint32 uiAction)
{
uint32 tailorSkill = pPlayer->GetSkillValue(SKILL_TAILORING);
uint32 blacksmithSkill = pPlayer->GetSkillValue(SKILL_BLACKSMITHING);
uint32 leatherworkSkill = pPlayer->GetSkillValue(SKILL_LEATHERWORKING);
uint32 argentDawnRep = pPlayer->GetReputationRank(529);
ReputationRank BOOK_REQ_RANK = REP_REVERED;
ReputationRank CRACT1_REQ_RANK = REP_REVERED;
ReputationRank CRAFT2_REQ_RANK = REP_EXALTED;
if (uiAction == GOSSIP_CLOSE)
{
pPlayer->CLOSE_GOSSIP_MENU();
return true;
}
// if rep < honored, spit on player and be done with it.
if (argentDawnRep < BOOK_REQ_RANK)
{
// DoScriptText(-1999913, pCreature, pPlayer); // spit on player -- Not in sniffs. Need confirmation
pPlayer->CLOSE_GOSSIP_MENU();
return true;
}
switch (uiAction)
{
case GOSSIP_SELECT_TAILOR:
if (argentDawnRep >= CRACT1_REQ_RANK)
{
pPlayer->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, "Glacial Gloves", GOSSIP_SELECT_TAILOR, GOSSIP_SELECT_GLACIAL_GLOVES);
pPlayer->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, "Glacial Wrists", GOSSIP_SELECT_TAILOR, GOSSIP_SELECT_GLACIAL_WRISTS);
}
if (argentDawnRep >= CRAFT2_REQ_RANK)
{
pPlayer->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, "Glacial Vest" , GOSSIP_SELECT_TAILOR, GOSSIP_SELECT_GLACIAL_CHEST);
pPlayer->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, "Glacial Cloak", GOSSIP_SELECT_TAILOR, GOSSIP_SELECT_GLACIAL_CLOAK);
}
pPlayer->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, BC_CLOSE_CRAFTER, GOSSIP_SELECT_TAILOR, GOSSIP_CLOSE);
pPlayer->SEND_GOSSIP_MENU(GOSSIP_MENU_CRAFTER, pCreature->GetGUID());
return true;
case GOSSIP_SELECT_BS:
if (argentDawnRep >= CRACT1_REQ_RANK)
{
pPlayer->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, "Icebane Gauntlets", GOSSIP_SELECT_BS, GOSSIP_SELECT_ICEBANE_GLOVES);
pPlayer->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, "Icebane Bracers", GOSSIP_SELECT_BS, GOSSIP_SELECT_ICEBANE_WRISTS);
}
if (argentDawnRep >= CRAFT2_REQ_RANK)
{
pPlayer->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, "Icebane Breastplate", GOSSIP_SELECT_BS, GOSSIP_SELECT_ICEBANE_CHEST);
}
pPlayer->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, BC_CLOSE_CRAFTER, GOSSIP_SELECT_BS, GOSSIP_CLOSE);
pPlayer->SEND_GOSSIP_MENU(GOSSIP_MENU_CRAFTER, pCreature->GetGUID());
return true;
case GOSSIP_SELECT_LW:
if (argentDawnRep >= CRACT1_REQ_RANK)
{
pPlayer->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, "Polar Gloves", GOSSIP_SELECT_LW, GOSSIP_SELECT_POLAR_GLOVES);
pPlayer->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, "Icy Scale Gauntlets", GOSSIP_SELECT_LW, GOSSIP_SELECT_ICYSCALE_GLOVES);
pPlayer->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, "Polar Bracers", GOSSIP_SELECT_LW, GOSSIP_SELECT_POLAR_WRISTS);
pPlayer->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, "Icy Scale Bracers", GOSSIP_SELECT_LW, GOSSIP_SELECT_ICYSCALE_WRISTS);
}
if (argentDawnRep >= CRAFT2_REQ_RANK)
{
pPlayer->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, "Polar Tunic", GOSSIP_SELECT_LW, GOSSIP_SELECT_POLAR_CHEST);
pPlayer->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, "Icy Scale Breastplate", GOSSIP_SELECT_LW, GOSSIP_SELECT_ICYSCALE_CHEST);
}
pPlayer->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, BC_CLOSE_CRAFTER, GOSSIP_SELECT_LW, GOSSIP_CLOSE);
pPlayer->SEND_GOSSIP_MENU(GOSSIP_MENU_CRAFTER, pCreature->GetGUID());
return true;
case GOSSIP_SELECT_NOCRAFT:
{
if (argentDawnRep >= BOOK_REQ_RANK)
{
pPlayer->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, BC_CLOSE_NO_CRAFTER, GOSSIP_SENDER_MAIN, GOSSIP_CLOSE);
pPlayer->SEND_GOSSIP_MENU(GOSSIP_MENU_NOCRAFT, pCreature->GetGUID());
if (!pPlayer->HasItemCount(22719, 1, true))
{
pPlayer->AddItem(22719);
}
}
return true;
}
/***************************
* Craft spells
****************************/
case GOSSIP_SELECT_GLACIAL_GLOVES:
{
LearnCraftIfCan(28212, 28205, pPlayer, CRACT1_REQ_RANK, tailorSkill);
break;
}
case GOSSIP_SELECT_GLACIAL_WRISTS:
{
LearnCraftIfCan(28215, 28209, pPlayer, CRACT1_REQ_RANK, tailorSkill);
break;
}
case GOSSIP_SELECT_GLACIAL_CHEST:
{
// spell castbar bug, displays as "glacial gloves"
LearnCraftIfCan(28213, 28207, pPlayer, CRAFT2_REQ_RANK, tailorSkill);
break;
}
case GOSSIP_SELECT_GLACIAL_CLOAK:
{
LearnCraftIfCan(28214, 28208, pPlayer, CRAFT2_REQ_RANK, tailorSkill);
break;
}
case GOSSIP_SELECT_POLAR_GLOVES:
{
LearnCraftIfCan(28229, 28220, pPlayer, CRACT1_REQ_RANK, leatherworkSkill);
break;
}
case GOSSIP_SELECT_POLAR_WRISTS:
{
LearnCraftIfCan(28230, 28221, pPlayer, CRACT1_REQ_RANK, leatherworkSkill);
break;
}
case GOSSIP_SELECT_POLAR_CHEST:
{
LearnCraftIfCan(28228, 28219, pPlayer, CRAFT2_REQ_RANK, leatherworkSkill);
break;
}
case GOSSIP_SELECT_ICYSCALE_GLOVES:
{
LearnCraftIfCan(28232, 28223, pPlayer, CRACT1_REQ_RANK, leatherworkSkill);
break;
}
case GOSSIP_SELECT_ICYSCALE_WRISTS:
{
LearnCraftIfCan(28233, 28224, pPlayer, CRACT1_REQ_RANK, leatherworkSkill);
break;
}
case GOSSIP_SELECT_ICYSCALE_CHEST:
{
LearnCraftIfCan(28231, 28222, pPlayer, CRAFT2_REQ_RANK, leatherworkSkill);
break;
}
case GOSSIP_SELECT_ICEBANE_GLOVES:
{
LearnCraftIfCan(28248, 28243, pPlayer, CRACT1_REQ_RANK, blacksmithSkill);
break;
}
case GOSSIP_SELECT_ICEBANE_WRISTS:
{
LearnCraftIfCan(28249, 28244, pPlayer, CRACT1_REQ_RANK, blacksmithSkill);
break;
}
case GOSSIP_SELECT_ICEBANE_CHEST:
{
LearnCraftIfCan(28245, 28242, pPlayer, CRAFT2_REQ_RANK, blacksmithSkill);
break;
}
}
pPlayer->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, BC_CLOSE_CRAFTER, uiSender, GOSSIP_CLOSE);
pPlayer->SEND_GOSSIP_MENU(GOSSIP_MENU_CRAFTER, pCreature->GetGUID());
return true;
}
bool GossipHello_npc_MasterCraftsmanOmarion(Player* pPlayer, Creature* pCreature)
{
uint32 tailorSkill = pPlayer->GetSkillValue(SKILL_TAILORING);
uint32 blacksmithSkill = pPlayer->GetSkillValue(SKILL_BLACKSMITHING);
uint32 leatherworkSkill = pPlayer->GetSkillValue(SKILL_LEATHERWORKING);
if(tailorSkill >= 225)
pPlayer->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, BC_TAILOR_TEXT, GOSSIP_SELECT_TAILOR, GOSSIP_SELECT_TAILOR);
if(blacksmithSkill >= 225)
pPlayer->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, BC_BLACKSMITH_TEXT, GOSSIP_SELECT_BS, GOSSIP_SELECT_BS);
if(leatherworkSkill >= 225)
pPlayer->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, BC_LEATHERWORKER_TEXT, GOSSIP_SELECT_LW, GOSSIP_SELECT_LW);
pPlayer->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, BC_NO_CRAFT_TEXT, GOSSIP_SENDER_MAIN, GOSSIP_SELECT_NOCRAFT);
pPlayer->SEND_GOSSIP_MENU(GOSSIP_MENU_INTRO, pCreature->GetGUID());
pCreature->HandleEmote(EMOTE_ONESHOT_LAUGH);
return true;
/*
send GOSSIP_INTRO
if player has 300/300 blacksmithing/leatherworking/taloring
add option "I am master <profession>, Omarion."
when clicked
if <300 in your crafting skill OR less than Honored with AD
/spits on you
else
say "Perhaps I can teach you something..."
if revered with AD, give option for bracers and gloves
if exalted with AD, give option for chest
exit dialogue "I need to go. Evil stirs. Die well, Omarion."
regardless of any profession, present option:
"Omarion, I am not a craftsman. Can you still help me?"
if player reputation < honored
/spit on you
else
send gossip GOSSIP_REPLY_NOT_CRAFTSMAN
add item 22719 (book) to player
add exit text "Thank you, Omarion. You have taken a fatal blow for the team on this day."
*/
}
// 29153 - Gargoyle Stoneform Visual
struct GargoyleStoneformScript : public AuraScript
{
void OnBeforeApply(Aura* aura, bool apply) final
{
if (apply)
{
// using stand state 9 in sniff
aura->GetTarget()->SetStandState(MAX_UNIT_STAND_STATE);
aura->GetTarget()->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
}
else // on remove
{
aura->GetTarget()->SetStandState(UNIT_STAND_STATE_STAND);
aura->GetTarget()->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
}
}
};
AuraScript* GetScript_GargoyleStoneform(SpellEntry const*)
{
return new GargoyleStoneformScript();
}
// 27831 - Shadow Bolt Volley (Naxx, Unrelenting Rider)
struct UnrelentingRiderShadowBoltVolleyScript : SpellScript
{
bool OnCheckTarget(Spell const* /*spell*/, Unit* target, SpellEffectIndex /*eff*/) const final
{
// Shadow Bolt volley which should only target players with the Shadow Mark debuff
if (!target->HasAura(27825)) // Shadow Mark
return false;
return true;
}
};
SpellScript* GetScript_UnrelentingRiderShadowBoltVolley(SpellEntry const*)
{
return new UnrelentingRiderShadowBoltVolleyScript();
}
void AddSC_instance_naxxramas()
{
Script* pNewScript;
pNewScript = new Script;
pNewScript->Name = "instance_naxxramas";
pNewScript->GetInstanceData = &GetInstanceData_instance_naxxramas;
pNewScript->RegisterSelf();
pNewScript = new Script;
pNewScript->Name = "at_naxxramas";
pNewScript->pAreaTrigger = &AreaTrigger_at_naxxramas;
pNewScript->RegisterSelf();
pNewScript = new Script;
pNewScript->Name = "spirit_of_naxxramas_ai";
pNewScript->GetAI = &GetAI_mob_spiritOfNaxxramas;
pNewScript->RegisterSelf();
pNewScript = new Script;
pNewScript->Name = "naxxramas_gargoyle_ai";
pNewScript->GetAI = &GetAI_mob_naxxramasGargoyle;
pNewScript->RegisterSelf();
pNewScript = new Script;
pNewScript->Name = "naxxramas_plague_slime_ai";
pNewScript->GetAI = &GetAI_mob_plagueSlimeAI;
pNewScript->RegisterSelf();
pNewScript = new Script;
pNewScript->Name = "toxic_tunnel_ai";
pNewScript->GetAI = &GetAI_toxic_tunnel;
pNewScript->RegisterSelf();
pNewScript = new Script;
pNewScript->Name = "dark_touched_warriorAI";
pNewScript->GetAI = &GetAI_dark_touched_warrior;
pNewScript->RegisterSelf();
pNewScript = new Script;
pNewScript->Name = "mob_craftsman_omarion";
pNewScript->pGossipHello = &GossipHello_npc_MasterCraftsmanOmarion;
pNewScript->pGossipSelect = &GossipSelect_npc_MasterCraftsmanOmarion;
pNewScript->RegisterSelf();
pNewScript = new Script;
pNewScript->Name = "spell_gargoyle_stoneform";
pNewScript->GetAuraScript = &GetScript_GargoyleStoneform;
pNewScript->RegisterSelf();
pNewScript = new Script;
pNewScript->Name = "spell_unrelenting_rider_shadow_bolt_volley";
pNewScript->GetSpellScript = &GetScript_UnrelentingRiderShadowBoltVolley;
pNewScript->RegisterSelf();
}
| 412 | 0.95938 | 1 | 0.95938 | game-dev | MEDIA | 0.979412 | game-dev | 0.990818 | 1 | 0.990818 |
vossenwout/llm-rpg | 6,680 | src/llm_rpg/scenes/battle/battle_states/battle_turn_state.py | from __future__ import annotations
from llm_rpg.scenes.battle.battle_states.battle_states import BattleStates
from llm_rpg.systems.battle.damage_calculator import DamageCalculationResult
from llm_rpg.systems.hero.hero import ProposedHeroAction
from llm_rpg.systems.battle.battle_log import BattleEvent
from typing import TYPE_CHECKING
from llm_rpg.scenes.state import State
from llm_rpg.utils.rendering import render_state_transition_header
if TYPE_CHECKING:
from llm_rpg.scenes.battle.battle_scene import BattleScene
class BattleTurnState(State):
def __init__(self, battle_scene: BattleScene):
self.battle_scene = battle_scene
self.is_hero_input_valid = True
self.proposed_hero_action: ProposedHeroAction = None
self.display_state_transition_header = True
def handle_input(self):
self.proposed_hero_action = self.battle_scene.hero.get_next_action()
def _update_hero_turn(self):
action_effect = self.battle_scene.battle_ai.determine_action_effect(
proposed_action_attacker=self.proposed_hero_action.action,
hero=self.battle_scene.hero,
enemy=self.battle_scene.enemy,
is_hero_attacker=True,
battle_log_string=self.battle_scene.battle_log.to_string_for_battle_ai(),
)
n_new_words_in_action = (
self.battle_scene.creativity_tracker.count_new_words_in_action(
action=self.proposed_hero_action.action
)
)
n_overused_words_in_action = (
self.battle_scene.creativity_tracker.count_overused_words_in_action(
action=self.proposed_hero_action.action
)
)
damage_calculation_result: DamageCalculationResult = (
self.battle_scene.damage_calculator.calculate_damage(
attack=self.battle_scene.hero.get_current_stats().attack,
defense=self.battle_scene.enemy.get_current_stats().defense,
feasibility=action_effect.feasibility,
potential_damage=action_effect.potential_damage,
n_new_words_in_action=n_new_words_in_action,
n_overused_words_in_action=n_overused_words_in_action,
answer_speed_s=self.proposed_hero_action.time_to_answer_seconds,
equiped_items=self.battle_scene.hero.inventory.items,
)
)
self.battle_scene.enemy.inflict_damage(damage_calculation_result.total_dmg)
self.battle_scene.creativity_tracker.add_action(
self.proposed_hero_action.action
)
self.battle_scene.battle_log.add_event(
BattleEvent(
is_hero_turn=True,
character_name=self.battle_scene.hero.name,
proposed_action=self.proposed_hero_action.action,
effect_description=action_effect.effect_description,
damage_calculation_result=damage_calculation_result,
)
)
def _update_enemy_turn(self):
proposed_enemy_action = self.battle_scene.enemy.get_next_action(
self.battle_scene.battle_log, self.battle_scene.hero
)
action_effect = self.battle_scene.battle_ai.determine_action_effect(
proposed_action_attacker=proposed_enemy_action,
hero=self.battle_scene.hero,
enemy=self.battle_scene.enemy,
is_hero_attacker=False,
battle_log_string=self.battle_scene.battle_log.to_string_for_battle_ai(),
)
damage_calculation_result = (
self.battle_scene.damage_calculator.calculate_damage(
attack=self.battle_scene.enemy.get_current_stats().attack,
defense=self.battle_scene.hero.get_current_stats().defense,
feasibility=action_effect.feasibility,
potential_damage=action_effect.potential_damage,
n_new_words_in_action=0,
n_overused_words_in_action=0,
answer_speed_s=1000,
equiped_items=[],
)
)
self.battle_scene.hero.inflict_damage(damage_calculation_result.total_dmg)
self.battle_scene.battle_log.add_event(
BattleEvent(
is_hero_turn=False,
character_name=self.battle_scene.enemy.name,
proposed_action=proposed_enemy_action,
effect_description=action_effect.effect_description,
damage_calculation_result=damage_calculation_result,
)
)
def update(self):
self.display_state_transition_header = False
if self.proposed_hero_action.is_valid:
self._update_hero_turn()
if self.battle_scene.enemy.is_dead():
self.battle_scene.change_state(BattleStates.END)
return
self._update_enemy_turn()
if self.battle_scene.hero.is_dead():
self.battle_scene.change_state(BattleStates.END)
return
def _render_character_stats(self):
print("- Stats - \n")
print(
f"{self.battle_scene.hero.name} HP: {self.battle_scene.hero.hp}/{self.battle_scene.hero.get_current_stats().max_hp}"
)
print(
f"{self.battle_scene.enemy.name} HP: {self.battle_scene.enemy.hp}/{self.battle_scene.enemy.get_current_stats().max_hp}"
)
def _render_ask_for_hero_action(self):
chars_can_type = self.battle_scene.hero.get_current_stats().focus
print(
f"What do you want to do? Your focus allows you to type {chars_can_type} characters."
)
def _render_invalid_hero_action(self):
print("")
print("Action invalid because:")
print(self.proposed_hero_action.invalid_reason)
def _render_battle_log(self):
if self.battle_scene.battle_log.events:
print("")
print("--- The following events took place... --- \n")
string_of_last_2_events = (
self.battle_scene.battle_log.get_string_of_last_events(
n_events=2, debug_mode=self.battle_scene.game.config.debug_mode
)
)
print(string_of_last_2_events)
def render(self):
if self.display_state_transition_header:
render_state_transition_header("Battle has started")
if self.proposed_hero_action and (not self.proposed_hero_action.is_valid):
self._render_invalid_hero_action()
else:
self._render_battle_log()
self._render_character_stats()
print("")
self._render_ask_for_hero_action()
| 412 | 0.713245 | 1 | 0.713245 | game-dev | MEDIA | 0.934849 | game-dev | 0.986949 | 1 | 0.986949 |
OrionFive/Hospitality | 4,265 | Source/Source/Utilities/DialogUtility.cs | using System;
using RimWorld;
using UnityEngine;
using Verse;
using Verse.Sound;
namespace Hospitality.Utilities
{
internal static class DialogUtility
{
private static readonly string txtForceRecruit = "ForceRecruit".Translate();
private static readonly string txtRecruit = "Recruit".Translate();
private static readonly string txtCantRecruit = "CantRecruit".Translate();
private static readonly string txtCantForce = "CantForceRecruit".Translate();
private static readonly string txtRecruitTooltip = "RecruitTooltip".Translate();
private static readonly string txtForceRecruitTooltip = "ForceRecruitTooltip".Translate();
public static void LabelWithTooltip(string label, string tooltip, Rect rect)
{
Widgets.Label(rect, label);
DoTooltip(rect, tooltip);
}
private static void DoTooltip(Rect rect, string tooltip)
{
if (!tooltip.NullOrEmpty())
{
if (Mouse.IsOver(rect)) Widgets.DrawHighlight(rect);
TooltipHandler.TipRegion(rect, tooltip);
}
}
public static void CheckboxLabeled(Listing_Standard listing, string label, ref bool checkOn, Rect rect, bool disabled = false, string tooltip = null)
{
if (!tooltip.NullOrEmpty())
{
if (Mouse.IsOver(rect))
Widgets.DrawHighlight(rect);
TooltipHandler.TipRegion(rect, tooltip);
}
Widgets.CheckboxLabeled(rect, label, ref checkOn, disabled);
listing.Gap(listing.verticalSpacing);
}
public static void DrawRecruitButton(Rect rect, Pawn pawn, bool hasEnoughFriends, bool isRoyal, bool willOnlyJoinByForce, bool canNeverRecruit)
{
var disabled = !pawn.MayRecruitRightNow() || canNeverRecruit;
if (willOnlyJoinByForce && !isRoyal)
{
// Not royal, has acidifier - can only force recruit
if (disabled) DrawButtonDisabled(txtRecruit, rect, txtCantRecruit);
else DrawButton(() => ITab_Pawn_Guest.RecruitDialog(pawn, true), txtForceRecruit, rect, txtForceRecruitTooltip);
}
else if (hasEnoughFriends && !willOnlyJoinByForce)
{
// Enough friends, royal or not - can recruit
if (disabled) DrawButtonDisabled(txtRecruit, rect, txtCantRecruit);
else DrawButton(() => ITab_Pawn_Guest.RecruitDialog(pawn, false), txtRecruit, rect, txtRecruitTooltip);
}
else if (!isRoyal)
{
// Not enough friends, not royal - can force recruit
if (disabled) DrawButtonDisabled(txtRecruit, rect, txtCantRecruit);
else DrawButton(() => ITab_Pawn_Guest.RecruitDialog(pawn, true), txtForceRecruit, rect, txtForceRecruitTooltip);
}
else
{
// Not enough friends, royal - can not recruit
DrawButtonDisabled(txtRecruit, rect, disabled ? txtCantRecruit : txtCantForce);
}
}
public static void DrawButton(Action action, string text, Rect rect, string tooltip = null)
{
if (!tooltip.NullOrEmpty())
{
TooltipHandler.TipRegion(rect, tooltip);
}
if (Widgets.ButtonText(rect, text, true, true, Widgets.NormalOptionColor))
{
SoundDefOf.Designate_DragStandard_Changed.PlayOneShotOnCamera();
action();
}
}
private static void DrawButtonDisabled(string text, Rect rect, string textDenied = null, string tooltip = null)
{
if (!tooltip.NullOrEmpty())
{
TooltipHandler.TipRegion(rect, tooltip);
}
GUI.color = Color.gray;
if(Widgets.ButtonText(rect, text, true, false, Widgets.NormalOptionColor))
{
if (!textDenied.NullOrEmpty())
{
Messages.Message(textDenied, MessageTypeDefOf.RejectInput);
}
}
GUI.color = Color.white;
}
}
}
| 412 | 0.903468 | 1 | 0.903468 | game-dev | MEDIA | 0.782431 | game-dev | 0.945623 | 1 | 0.945623 |
freezy/VisualPinball.Engine | 2,654 | VisualPinball.Unity/VisualPinball.Unity/VPT/Surface/SlingshotApi.cs | // Visual Pinball Engine
// Copyright (C) 2023 freezy and VPE Team
//
// 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/>.
using System;
using NLog;
using UnityEngine;
using Logger = NLog.Logger;
namespace VisualPinball.Unity
{
public class SlingshotApi : IApi, IApiSwitch, IApiSwitchDevice
{
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
private readonly SlingshotComponent _slingshotComponent;
private readonly Player _player;
private SurfaceApi _surfaceApi;
private readonly SwitchHandler _switchHandler;
public event EventHandler Init;
public event EventHandler<SwitchEventArgs> Switch;
public bool IsSwitchEnabled => _switchHandler.IsEnabled;
IApiSwitchStatus IApiSwitch.AddSwitchDest(SwitchConfig switchConfig, IApiSwitchStatus switchStatus) => _switchHandler.AddSwitchDest(switchConfig.WithPulse(true), switchStatus);
void IApiSwitch.AddWireDest(WireDestConfig wireConfig) => _switchHandler.AddWireDest(wireConfig.WithPulse(true));
void IApiSwitch.RemoveWireDest(string destId) => _switchHandler.RemoveWireDest(destId);
IApiSwitch IApiSwitchDevice.Switch(string deviceItem) => this;
private void OnSwitch(bool closed) => _switchHandler.OnSwitch(closed);
internal SlingshotApi(GameObject go, Player player, PhysicsEngine physicsEngine)
{
_slingshotComponent = go.GetComponentInChildren<SlingshotComponent>();
_player = player;
_switchHandler = new SwitchHandler(go.name, player, physicsEngine);
}
void IApi.OnInit(BallManager ballManager)
{
_surfaceApi = _player.TableApi.Surface(_slingshotComponent.SlingshotSurface.MainComponent);
if (_surfaceApi != null) {
_surfaceApi.Slingshot += OnSlingshot;
}
Init?.Invoke(this, EventArgs.Empty);
}
private void OnSlingshot(object sender, EventArgs e)
{
Switch?.Invoke(this, new SwitchEventArgs(true));
OnSwitch(true);
}
void IApi.OnDestroy()
{
Logger.Info($"Destroying {_slingshotComponent.name}");
if (_surfaceApi != null) {
_surfaceApi.Slingshot -= OnSlingshot;
}
}
}
}
| 412 | 0.760789 | 1 | 0.760789 | game-dev | MEDIA | 0.912862 | game-dev | 0.747977 | 1 | 0.747977 |
sumneko/w3x2lni | 15,377 | test/unit_test.lua | require 'utility'
local uni = require 'ffi.unicode'
local core = require 'backend.sandbox_core'
local root = require 'backend.w2l_path'
local config = require 'share.config'
local fs = require 'bee.filesystem'
local lang = require 'share.lang'
lang:set_lang('zhCN')
local slk_keys = {
['units\\abilitydata.slk'] = {
'alias','code','Area1','Area2','Area3','Area4','BuffID1','BuffID2','BuffID3','BuffID4','Cast1','Cast2','Cast3','Cast4','checkDep','Cool1','Cool2','Cool3','Cool4','Cost1','Cost2','Cost3','Cost4','DataA1','DataA2','DataA3','DataA4','DataB1','DataB2','DataB3','DataB4','DataC1','DataC2','DataC3','DataC4','DataD1','DataD2','DataD3','DataD4','DataE1','DataE2','DataE3','DataE4','DataF1','DataF2','DataF3','DataF4','DataG1','DataG2','DataG3','DataG4','DataH1','DataH2','DataH3','DataH4','DataI1','DataI2','DataI3','DataI4','Dur1','Dur2','Dur3','Dur4','EfctID1','EfctID2','EfctID3','EfctID4','HeroDur1','HeroDur2','HeroDur3','HeroDur4','levels','levelSkip','priority','reqLevel','Rng1','Rng2','Rng3','Rng4','targs1','targs2','targs3','targs4','UnitID1','UnitID2','UnitID3','UnitID4',
},
['units\\abilitybuffdata.slk'] = {
'alias',
},
['units\\destructabledata.slk'] = {
'DestructableID','armor','cliffHeight','colorB','colorG','colorR','deathSnd','fatLOS','file','fixedRot','flyH','fogRadius','fogVis','HP','lightweight','maxPitch','maxRoll','maxScale','minScale','MMBlue','MMGreen','MMRed','Name','numVar','occH','pathTex','pathTexDeath','portraitmodel','radius','selcircsize','selectable','shadow','showInMM','targType','texFile','texID','tilesetSpecific','useMMColor','walkable',
},
['units\\itemdata.slk'] = {
'itemID','abilList','armor','class','colorB','colorG','colorR','cooldownID','drop','droppable','file','goldcost','HP','ignoreCD','Level','lumbercost','morph','oldLevel','pawnable','perishable','pickRandom','powerup','prio','scale','sellable','stockMax','stockRegen','stockStart','usable','uses',
},
['units\\upgradedata.slk'] = {
'upgradeid','base1','base2','base3','base4','class','code1','code2','code3','code4','effect1','effect2','effect3','effect4','global','goldbase','goldmod','inherit','lumberbase','lumbermod','maxlevel','mod1','mod2','mod3','mod4','timebase','timemod', 'used',
},
['units\\unitabilities.slk'] = {
'unitAbilID','abilList','auto','heroAbilList',
},
['units\\unitbalance.slk'] = {
'unitBalanceID','AGI','AGIplus','bldtm','bountydice','bountyplus','bountysides','collision','def','defType','defUp','fmade','fused','goldcost','goldRep','HP','INT','INTplus','isbldg','level','lumberbountydice','lumberbountyplus','lumberbountysides','lumbercost','lumberRep','mana0','manaN','maxSpd','minSpd','nbrandom','nsight','preventPlace','Primary','regenHP','regenMana','regenType','reptm','repulse','repulseGroup','repulseParam','repulsePrio','requirePlace','sight','spd','stockMax','stockRegen','stockStart','STR','STRplus','tilesets','type','upgrades',
},
['units\\unitdata.slk'] = {
'unitID','buffRadius','buffType','canBuildOn','canFlee','canSleep','cargoSize','death','deathType','fatLOS','formation','isBuildOn','moveFloor','moveHeight','movetp','nameCount','orientInterp','pathTex','points','prio','propWin','race','requireWaterRadius','targType','turnRate',
},
['units\\unitui.slk'] = {
'unitUIID','name','armor','blend','blue','buildingShadow','customTeamColor','elevPts','elevRad','file','fileVerFlags','fogRad','green','hideHeroBar','hideHeroDeathMsg','hideHeroMinimap','hideOnMinimap','maxPitch','maxRoll','modelScale','nbmmIcon','occH','red','run','scale','scaleBull','selCircOnWater','selZ','shadowH','shadowOnWater','shadowW','shadowX','shadowY','special','teamColor','tilesetSpecific','uberSplat','unitShadow','unitSound','walk',
},
['units\\unitweapons.slk'] = {
'unitWeapID','acquire','atkType1','atkType2','backSw1','backSw2','castbsw','castpt','cool1','cool2','damageLoss1','damageLoss2','dice1','dice2','dmgplus1','dmgplus2','dmgpt1','dmgpt2','dmgUp1','dmgUp2','Farea1','Farea2','Harea1','Harea2','Hfact1','Hfact2','impactSwimZ','impactZ','launchSwimZ','launchX','launchY','launchZ','minRange','Qarea1','Qarea2','Qfact1','Qfact2','rangeN1','rangeN2','RngBuff1','RngBuff2','showUI1','showUI2','sides1','sides2','spillDist1','spillDist2','spillRadius1','spillRadius2','splashTargs1','splashTargs2','targCount1','targCount2','targs1','targs2','weapsOn','weapTp1','weapTp2','weapType1','weapType2',
},
['doodads\\doodads.slk'] = {
'doodID','file','Name','doodClass','soundLoop','selSize','defScale','minScale','maxScale','maxPitch','maxRoll','visRadius','walkable','numVar','floats','shadow','showInFog','animInFog','fixedRot','pathTex','showInMM','useMMColor','MMRed','MMGreen','MMBlue','vertR01','vertG01','vertB01','vertR02','vertG02','vertB02','vertR03','vertG03','vertB03','vertR04','vertG04','vertB04','vertR05','vertG05','vertB05','vertR06','vertG06','vertB06','vertR07','vertG07','vertB07','vertR08','vertG08','vertB08','vertR09','vertG09','vertB09','vertR10','vertG10','vertB10',
},
}
local mt = {}
mt.__index = mt
local function find_txt(buf, id)
local start = buf:find('%['..id..'%]')
if not start then
return nil
end
local stop = buf:find('%c+%[')
return buf:sub(start, stop)
end
function mt:load_obj(w2l, type, id, path)
local w2l = self:w3x2lni()
local target_name = w2l.info.obj[type]
function w2l.input_ar:get(filename)
if filename == target_name then
return io.load(path / filename)
end
end
w2l:frontend()
return { obj = w2l.slk[type][id], type = 'obj' }
end
function mt:load_lni(w2l, type, id, path)
local target_name = w2l.info.lni[type]
function w2l.input_ar:get(filename)
if filename == 'table\\' .. target_name then
return io.load(path / target_name)
end
end
w2l:frontend()
return { obj = w2l.slk[type][id], type = 'lni' }
end
function mt:load_slk(w2l, type, id, path)
w2l.setting.read_slk = true
local enable_keys = {}
local function pack_keys(filename)
if not slk_keys[filename] then
return
end
for _, key in ipairs(slk_keys[filename]) do
enable_keys[key] = true
end
end
local target_names = {}
for _, name in ipairs(w2l.info.txt) do
target_names[name] = name:sub(7)
end
for _, name in ipairs(w2l.info.slk[type]) do
target_names[name] = name:sub(7)
end
function w2l.input_ar:get(filename)
if target_names[filename] then
pack_keys(filename)
return io.load(path / target_names[filename])
end
end
w2l:frontend()
return { obj = w2l.slk[type][id], type = 'slk', keys = enable_keys }
end
function mt:load_all(w2l, type, id, path, setting)
function w2l.input_ar:get(filename)
return io.load(path / filename)
end
w2l:frontend()
return { obj = w2l.slk[type][id], type = 'all' }
end
local function save_obj(w2l, type, id, path)
local lni_name = w2l.info.obj[type]
local obj = { obj = nil, type = 'obj' }
function w2l.output_ar:set(filename, buf)
if filename == lni_name then
if type == 'misc' then
local txt = find_txt(buf, id)
if txt then
obj.obj = txt
end
else
obj.obj = buf
end
end
end
w2l:backend()
return obj
end
local function save_lni(w2l, type, id, path)
local obj = { lni = nil, type = 'lni' }
function w2l:file_save(tp, name, buf)
if tp == 'table' and name == type then
local txt = find_txt(buf, id)
if txt then
obj.lni = txt
end
end
end
w2l:backend()
return obj
end
local function save_slk(w2l, type, id, path)
local txt_names = {}
for _, name in ipairs(w2l.info.txt) do
txt_names[name] = name:sub(7)
end
local slk_names = {}
for _, name in ipairs(w2l.info.slk[type] or {}) do
slk_names[name] = name:sub(7)
end
local obj_name = w2l.info.obj[type]
local obj = { slk = nil, txt = nil, type = 'slk' }
function w2l.output_ar:set(filename, buf)
if slk_names[filename] then
elseif txt_names[filename] then
local txt = find_txt(buf, id)
if txt then
obj.txt = txt
end
elseif filename == obj_name then
obj.obj = buf
end
end
w2l:backend()
return obj
end
local function eq(v1, v2, enable_keys)
for k in pairs(v1) do
if k:sub(1, 1) == '_' then
goto CONTINUE
end
if enable_keys and not enable_keys[k] then
goto CONTINUE
end
if type(v1[k]) ~= type(v2[k]) then
return false, ('[%s] - [%s](%s):[%s](%s)'):format(k, v1[k], type(v1[k]), v2[k], type(v2[k]))
end
if type(v1[k]) == 'table' then
if #v1[k] ~= #v2[k] then
return false, ('[%s] - #%s:#%s'):format(k, #v1[k], #v2[k])
end
for i = 1, #v1[k] do
if v1[k][i] ~= v2[k][i] then
return false, ('[%s][%s] - [%s](%s):[%s](%s)'):format(k, #v1[k], v1[k][i], type(v1[k][i]), v2[k][i], type(v2[k][i]))
end
end
else
if v1[k] ~= v2[k] then
return false, ('[%s] - [%s](%s):[%s](%s)'):format(k, v1[k], type(v1[k]), v2[k], type(v2[k]))
end
end
::CONTINUE::
end
return true
end
local function eq_test(v1, v2, enable_keys, callback)
local ok, msg = eq(v1, v2, enable_keys)
if ok then
return
end
callback(msg)
end
local function trim(str)
if not str then
return nil
end
str = str:gsub('\r\n', '\n'):gsub('[\n]+', '\n')
if str:sub(-1) == '\n' then
str = str:sub(1, -2)
end
if str:sub(1, 1) == '\n' then
str = str:sub(2)
end
return str
end
function mt:w3x2lni()
local w2l = core()
w2l.input_ar = {
get = function ()
end,
set = function ()
end,
remove = function ()
end,
}
w2l.output_ar = {
get = function ()
end,
set = function ()
end,
remove = function ()
end,
}
local set_setting = w2l.set_setting
function w2l.set_setting(self, data)
data = data or {}
local setting = {}
for k, v in pairs(config.global) do
setting[k] = v
end
if config[data.mode] then
for k, v in pairs(config[data.mode]) do
setting[k] = v
end
end
for k, v in pairs(data) do
setting[k] = v
end
set_setting(self, setting)
end
w2l:set_setting()
return w2l
end
function mt:init(type, id)
self._type = type
self._id = id
end
function mt:load(mode, setting)
local w2l = self:w3x2lni()
local name = self._path:filename():string()
local dump
setting = setting or {}
w2l:set_setting(setting)
if mode == 'obj' then
dump = self:load_obj(w2l, self._type, self._id, self._path)
elseif mode == 'lni' then
dump = self:load_lni(w2l, self._type, self._id, self._path)
elseif mode == 'slk' then
dump = self:load_slk(w2l, self._type, self._id, self._path)
elseif mode == 'all' then
dump = self:load_all(w2l, self._type, self._id, self._path)
end
assert(dump.obj, ('\n\n<%s>[%s.%s] 没有读取到%s'):format(name, self._type, self._id, mode))
return dump
end
function mt:save(mode, dump, setting)
local w2l = self:w3x2lni()
local name = self._path:filename():string()
local slk
setting = setting or {}
setting.mode = mode
w2l:set_setting(setting)
w2l.slk = {}
for _, type in ipairs {'ability', 'buff', 'unit', 'item', 'upgrade', 'destructable', 'doodad', 'misc', 'txt'} do
w2l.slk[type] = {}
end
w2l.slk[self._type] = { [self._id] = dump.obj }
if mode == 'obj' then
slk = save_obj(w2l, self._type, self._id, self._path)
elseif mode == 'lni' then
slk = save_lni(w2l, self._type, self._id, self._path)
elseif mode == 'slk' then
slk = save_slk(w2l, self._type, self._id, self._path)
end
assert(slk.slk or slk.txt or slk.obj or slk.lni, ('\n\n<%s>[%s.%s] 没有保存为%s'):format(name, self._type, self._id, mode))
return slk
end
function mt:read(filename)
return io.load(self._path / filename)
end
function mt:dir(filename)
return fs.pairs(self._path / filename)
end
function mt:packDir(filename)
local base = self._path / filename
local packs = {}
local function scan(dir)
for path in fs.pairs(dir) do
if fs.is_directory(path) then
scan(path)
else
local relative = fs.relative(path, base)
packs[relative:string()] = io.load(path)
end
end
end
scan(base)
return packs
end
function mt:compare_string(str1, str2)
local name = self._path:filename():string()
assert(trim(str1) == trim(str2), ('\n\n<%s>[%s.%s] 文本不同:\n\n%s\n'):format(name, self._type, self._id, trim(str1)))
end
function mt:compare_value(v1, v2)
local name = self._path:filename():string()
assert(v1 == v2, ('\n\n<%s>[%s.%s] 值不同:\n\n%s\n'):format(name, self._type, self._id, v1))
end
function mt:compare_dump(dump1, dump2)
local name = self._path:filename():string()
eq_test(dump1.obj, dump2.obj, dump1.keys or dump2.keys, function (msg)
error(('\n\n<%s>[%s.%s]\n%s 与 %s 不等:%s'):format(name, self._type, self._id, dump1.type, dump2.type, msg))
end)
end
local function test_env(path)
local o = setmetatable({ _path = path }, mt)
return setmetatable({}, {
__index = function (self, k)
local f = o[k]
if not f then
return _G[k]
end
return function (...)
return f(o, ...)
end
end,
})
end
local function do_test(path)
local buf = io.load(path / 'test.lua')
if not buf then
return false
end
print(('正在测试[%s]'):format(path:filename():string()))
local debuggerpath = '@'..(path / 'test.lua'):string()
local env = test_env(path)
local f = assert(load(buf, debuggerpath, 't', env))
f()
return true
end
local ignore = {
}
local test_dir = root / 'test' / 'unit_test'
if arg[1] then
do_test(test_dir / arg[1])
print('指定的单元测试完成:' .. arg[1])
else
local mark = {}
for _, name in ipairs(ignore) do
mark[name] = true
end
local count = 0
for path in fs.pairs(test_dir) do
local name = path:stem():string()
if mark[name] then
print(('已跳过[%s]'):format(name))
else
local suc = do_test(path)
if not suc then
error(('单元测试[%s]执行失败'):format(name))
end
count = count + 1
end
end
if count == 0 then
error('没有执行任何单元测试')
end
print(('单元测试完成,共测试[%d]个'):format(count))
end
| 412 | 0.940201 | 1 | 0.940201 | game-dev | MEDIA | 0.361581 | game-dev | 0.867444 | 1 | 0.867444 |
sndyx/hsl | 1,743 | compiler/src/commonMain/kotlin/com/hsc/compiler/parse/Lexing.kt | package com.hsc.compiler.parse
import com.hsc.compiler.span.Span
fun Lexer.expectNumber(): Long {
val lo = pos + 1
val negative = eat('-')
val number = runCatching {
if (first() == '0' && second() !in '0'..'9') "0".also { bump() }
else expect { it in '1'..'9' } + takeWhile { it.isDigit() || it == '_' }
}.getOrElse { throw sess.dcx().err("invalid integer", Span(lo, pos, fid)) }
val long = number.replace("_", "").toLongOrNull()
if (long == null) {
val err = sess.dcx().err("invalid integer")
val hint = if (negative) {
"below 64-bit integer limit"
} else "above 64-bit integer limit"
err.spanLabel(Span(lo, pos, fid), hint)
throw err
}
return if (negative) long * -1L else long
}
fun Lexer.eat(char: Char): Boolean {
if (first() == char) {
bump()
return true
}
return false
}
fun Lexer.expect(char: Char) {
val found = bump()
if (found != char) {
throw sess.dcx().err("expected $char, found $found", Span.single(pos, fid))
}
}
fun Lexer.expect(predicate: (Char) -> Boolean): Char {
val found = bump()
if (found == null || !predicate(found)) {
throw sess.dcx().err("unexpected", Span.single(pos, fid))
}
return found
}
fun Lexer.takeWhile(predicate: (Char) -> Boolean): String {
val sb = StringBuilder()
while (!isEof() && predicate(first())) {
sb.append(bump().also { if (it == '\n') srcp.addLine(pos) })
}
return sb.toString()
}
fun Lexer.eatWhitespace() = eatWhile {
it.isWhitespace()
}
fun <T : Any> Lexer.floating(block: Lexer.() -> T): T {
eatWhitespace()
val result = block(this)
eatWhitespace()
return result
} | 412 | 0.910375 | 1 | 0.910375 | game-dev | MEDIA | 0.475362 | game-dev | 0.944674 | 1 | 0.944674 |
d4rken-org/sdmaid-se | 2,275 | app/src/main/java/eu/darken/sdmse/corpsefinder/ui/details/corpse/elements/CorpseElementFileVH.kt | package eu.darken.sdmse.corpsefinder.ui.details.corpse.elements
import android.text.format.Formatter
import android.view.ViewGroup
import androidx.core.view.isGone
import eu.darken.sdmse.R
import eu.darken.sdmse.common.coil.loadFilePreview
import eu.darken.sdmse.common.files.APathLookup
import eu.darken.sdmse.common.files.FileType
import eu.darken.sdmse.common.files.joinSegments
import eu.darken.sdmse.common.files.removePrefix
import eu.darken.sdmse.common.lists.binding
import eu.darken.sdmse.common.lists.selection.SelectableItem
import eu.darken.sdmse.common.lists.selection.SelectableVH
import eu.darken.sdmse.corpsefinder.core.Corpse
import eu.darken.sdmse.corpsefinder.ui.details.corpse.CorpseElementsAdapter
import eu.darken.sdmse.databinding.CorpsefinderCorpseElementFileBinding
class CorpseElementFileVH(parent: ViewGroup) :
CorpseElementsAdapter.BaseVH<CorpseElementFileVH.Item, CorpsefinderCorpseElementFileBinding>(
R.layout.corpsefinder_corpse_element_file,
parent
), SelectableVH {
private var lastItem: Item? = null
override val itemSelectionKey: String?
get() = lastItem?.itemSelectionKey
override fun updatedSelectionState(selected: Boolean) {
itemView.isActivated = selected
}
override val viewBinding = lazy { CorpsefinderCorpseElementFileBinding.bind(itemView) }
override val onBindData: CorpsefinderCorpseElementFileBinding.(
item: Item,
payloads: List<Any>
) -> Unit = binding { item ->
lastItem = item
icon.loadFilePreview(item.lookup)
val prefixFree = item.lookup.lookedUp.removePrefix(item.corpse.lookup)
primary.text = prefixFree.joinSegments("/")
size.apply {
text = Formatter.formatShortFileSize(context, item.lookup.size)
isGone = item.lookup.fileType != FileType.FILE
}
root.setOnClickListener { item.onItemClick(item) }
}
data class Item(
val corpse: Corpse,
val lookup: APathLookup<*>,
val onItemClick: (Item) -> Unit,
) : CorpseElementsAdapter.Item, SelectableItem {
override val itemSelectionKey: String
get() = lookup.toString()
override val stableId: Long = lookup.hashCode().toLong()
}
} | 412 | 0.808599 | 1 | 0.808599 | game-dev | MEDIA | 0.502264 | game-dev | 0.952752 | 1 | 0.952752 |
mkw-sp/mkw-sp | 1,167 | payload/game/ui/page/ToRaceMenuPage.cc | #include "ToRaceMenuPage.hh"
#include "game/ui/SectionManager.hh"
#include "game/ui/page/RaceMenuPage.hh"
namespace UI {
static const RaceMenuPage::ButtonId TournamentPauseButtons[] = {
RaceMenuPage::ButtonId::Continue1,
RaceMenuPage::ButtonId::Restart1,
RaceMenuPage::ButtonId::ChangeCharacter,
RaceMenuPage::ButtonId::Quit1,
};
static const RaceMenuPage::ButtonId MissionRunPauseButtons[] = {
RaceMenuPage::ButtonId::Continue1,
RaceMenuPage::ButtonId::Restart1,
RaceMenuPage::ButtonId::ChangeMission,
RaceMenuPage::ButtonId::Quit1,
};
const RaceMenuPage::ButtonId *ToRaceMenuPage::getButtons() {
auto currentSectionid = SectionManager::Instance()->currentSection()->id();
if (currentSectionid == SectionId::MR) {
return MissionRunPauseButtons;
} else {
return TournamentPauseButtons;
}
}
const char *ToRaceMenuPage::getResFileName() {
auto currentSectionid = SectionManager::Instance()->currentSection()->id();
if (currentSectionid == SectionId::MR) {
return "PauseMenuMR";
} else {
return "PauseMenuEvent";
}
}
} // namespace UI
| 412 | 0.93628 | 1 | 0.93628 | game-dev | MEDIA | 0.91755 | game-dev | 0.958223 | 1 | 0.958223 |
fitzgen/generational-arena | 8,703 | tests/tests.rs | extern crate generational_arena;
use generational_arena::Arena;
use std::collections::BTreeSet;
#[test]
fn can_decompose_index() {
let mut arena = Arena::with_capacity(1);
let i = arena.try_insert(42).unwrap();
let (k, g) = i.into_raw_parts();
let generated_i = generational_arena::Index::from_raw_parts(k, g);
assert_eq!(arena[generated_i], 42);
}
#[test]
fn can_get_live_value() {
let mut arena = Arena::with_capacity(1);
let i = arena.try_insert(42).unwrap();
assert_eq!(arena[i], 42);
}
#[test]
fn cannot_get_free_value() {
let mut arena = Arena::with_capacity(1);
let i = arena.try_insert(42).unwrap();
assert_eq!(arena.remove(i).unwrap(), 42);
assert!(!arena.contains(i));
}
#[test]
fn cannot_get_other_generation_value() {
let mut arena = Arena::with_capacity(1);
let i = arena.try_insert(42).unwrap();
assert_eq!(arena.remove(i).unwrap(), 42);
assert!(!arena.contains(i));
let j = arena.try_insert(42).unwrap();
assert!(!arena.contains(i));
assert_eq!(arena[j], 42);
assert!(i != j);
}
#[test]
fn try_insert_when_full() {
let mut arena = Arena::with_capacity(1);
arena.try_insert(42).unwrap();
assert_eq!(arena.try_insert(42).unwrap_err(), 42);
}
#[test]
fn try_insert_with_when_full() {
let mut arena = Arena::with_capacity(1);
let first_index = arena.try_insert_with(|_| 42).ok().unwrap();
let returned_fn = arena.try_insert_with(|_| 42).unwrap_err();
assert_eq!(returned_fn(first_index), 42);
}
#[test]
fn insert_many_and_cause_doubling() {
let mut arena = Arena::new();
let indices: Vec<_> = (0..1000).map(|i| arena.insert(i * i)).collect();
for (i, idx) in indices.iter().cloned().enumerate() {
assert_eq!(arena.remove(idx).unwrap(), i * i);
assert!(!arena.contains(idx));
}
}
#[test]
fn insert_with_indicies_match() {
let mut arena = Arena::new();
let a = arena.insert_with(|idx| (40, idx));
let b = arena.insert_with(|idx| (41, idx));
let c = arena.insert_with(|idx| (42, idx));
assert_eq!(arena[a].0, 40);
assert_eq!(arena[b].0, 41);
assert_eq!(arena[c].0, 42);
assert_eq!(arena[a].1, a);
assert_eq!(arena[b].1, b);
assert_eq!(arena[c].1, c);
}
#[test]
fn try_insert_with_indicies_match() {
let mut arena = Arena::with_capacity(3);
let a = arena.try_insert_with(|idx| (40, idx)).ok().unwrap();
let b = arena.try_insert_with(|idx| (41, idx)).ok().unwrap();
let c = arena.try_insert_with(|idx| (42, idx)).ok().unwrap();
assert_eq!(arena[a].0, 40);
assert_eq!(arena[b].0, 41);
assert_eq!(arena[c].0, 42);
assert_eq!(arena[a].1, a);
assert_eq!(arena[b].1, b);
assert_eq!(arena[c].1, c);
}
#[test]
fn capacity_and_reserve() {
let mut arena: Arena<usize> = Arena::with_capacity(42);
assert_eq!(arena.capacity(), 42);
arena.reserve(10);
assert_eq!(arena.capacity(), 52);
}
#[test]
fn get_mut() {
let mut arena = Arena::new();
let idx = arena.insert(5);
arena[idx] += 1;
assert_eq!(arena[idx], 6);
}
#[test]
fn get2_mut() {
let mut arena = Arena::with_capacity(2);
let idx1 = arena.insert(0);
let idx2 = arena.insert(1);
{
let (item1, item2) = arena.get2_mut(idx1, idx2);
assert_eq!(item1, Some(&mut 0));
assert_eq!(item2, Some(&mut 1));
*item1.unwrap() = 3;
*item2.unwrap() = 4;
}
assert_eq!(arena[idx1], 3);
assert_eq!(arena[idx2], 4);
}
#[test]
fn get_unknown_gen() {
let mut arena = Arena::new();
let idx = arena.insert(5);
let i = idx.into_raw_parts().0;
if let Some((el, id)) = arena.get_unknown_gen(i) {
assert_eq!(id, idx);
assert_eq!(*el, 5);
} else {
panic!("element at index {} (without generation) should exist at this point", i);
}
arena.remove(idx);
if let Some((_, _)) = arena.get_unknown_gen(i) {
panic!("element at index {} (without generation) should not exist at this point", i);
}
}
#[test]
fn get_unknown_gen_mut() {
let mut arena = Arena::new();
let idx = arena.insert(5);
let i = idx.into_raw_parts().0;
if let Some((el, id)) = arena.get_unknown_gen_mut(i) {
assert_eq!(id, idx);
assert_eq!(*el, 5);
*el += 1;
} else {
panic!("element at index {} (without generation) should exist at this point", i);
}
assert_eq!(arena.get_mut(idx).cloned(), Some(6));
arena.remove(idx);
if let Some((_, _)) = arena.get_unknown_gen_mut(i) {
panic!("element at index {} (without generation) should not exist at this point", i);
}
}
#[test]
fn get2_mut_with_same_index_but_different_generation() {
let mut arena = Arena::with_capacity(2);
let idx1 = arena.insert(0);
arena.remove(idx1);
let idx2 = arena.insert(1);
let (item1, item2) = arena.get2_mut(idx1, idx2);
assert_eq!(item1, None);
assert_eq!(item2, Some(&mut 1));
}
#[test]
fn into_iter() {
let mut arena = Arena::new();
arena.insert(0);
arena.insert(1);
arena.insert(2);
let set: BTreeSet<_> = arena.into_iter().collect();
assert_eq!(set.len(), 3);
assert!(set.contains(&0));
assert!(set.contains(&1));
assert!(set.contains(&2));
}
#[test]
#[should_panic]
fn index_deleted_item() {
let mut arena = Arena::new();
let idx = arena.insert(42);
arena.remove(idx);
arena[idx];
}
#[test]
fn out_of_bounds_get_with_index_from_other_arena() {
let mut arena1 = Arena::with_capacity(1);
let arena2 = Arena::<usize>::with_capacity(1);
arena1.insert(0);
let idx = arena1.insert(42);
assert!(arena2.get(idx).is_none());
}
#[test]
fn out_of_bounds_remove_with_index_from_other_arena() {
let mut arena1 = Arena::with_capacity(1);
let mut arena2 = Arena::<usize>::with_capacity(1);
arena1.insert(0);
let idx = arena1.insert(42);
assert!(arena2.remove(idx).is_none());
}
#[test]
fn out_of_bounds_get2_mut_with_index_from_other_arena() {
let mut arena1 = Arena::with_capacity(1);
let mut arena2 = Arena::with_capacity(2);
let idx1 = arena1.insert(42);
arena2.insert(0);
let idx2 = arena2.insert(0);
assert_eq!(arena1.get2_mut(idx1, idx2), (Some(&mut 42), None));
}
#[test]
fn drain() {
let mut arena = Arena::new();
let idx_1 = arena.insert("hello");
let idx_2 = arena.insert("world");
assert!(arena.get(idx_1).is_some());
assert!(arena.get(idx_2).is_some());
for (idx, value) in arena.drain() {
assert!((idx == idx_1 && value == "hello") || (idx == idx_2 && value == "world"));
}
assert!(arena.get(idx_1).is_none());
assert!(arena.get(idx_2).is_none());
assert_eq!(arena.capacity(), 0);
assert_eq!(arena.len(), 0);
let idx_3 = arena.insert("a");
assert_ne!(idx_1, idx_3);
assert_eq!(arena.capacity(), 1);
assert_eq!(arena.len(), 1);
// If there are no elements, do not increment generation.
let mut arena_2 = Arena::with_capacity(1);
arena_2.drain();
arena_2.drain();
arena_2.drain();
let idx_1 = arena_2.insert(1);
let gen = idx_1.into_raw_parts().1;
assert_eq!(gen, 0);
}
#[test]
fn clear() {
let mut arena = Arena::with_capacity(1);
arena.insert(42);
arena.insert(43);
assert_eq!(arena.capacity(), 2);
assert_eq!(arena.len(), 2);
arena.clear();
assert_eq!(arena.capacity(), 2);
assert_eq!(arena.len(), 0);
arena.insert(44);
arena.insert(45);
arena.insert(46);
assert_eq!(arena.capacity(), 4);
assert_eq!(arena.len(), 3);
arena.clear();
assert_eq!(arena.capacity(), 4);
assert_eq!(arena.len(), 0);
}
#[test]
fn clear_gen() {
let mut arena = Arena::with_capacity(1);
let idx_1 = arena.insert(1);
arena.clear();
let idx_2 = arena.insert(2);
assert_ne!(idx_1, idx_2);
// If there are no elements, do not increment generation.
let mut arena_2 = Arena::with_capacity(1);
arena_2.clear();
arena_2.clear();
arena_2.clear();
let idx_1 = arena_2.insert(1);
let gen = idx_1.into_raw_parts().1;
assert_eq!(gen, 0);
}
#[test]
fn retain() {
let mut arena = Arena::with_capacity(4);
let index = arena.insert(2);
arena.insert(1);
arena.insert(4);
arena.insert(3);
assert_eq!(arena.len(), 4);
arena.retain(|_, n| *n < 4);
assert_eq!(arena.len(), 3);
assert!(arena.iter().all(|(_, n)| *n < 4));
arena.retain(|_, n| *n < 3);
assert_eq!(arena.len(), 2);
assert!(arena.iter().all(|(_, n)| *n < 3));
assert!(arena.contains(index));
arena.retain(|i, _| i != index);
assert_eq!(arena.len(), 1);
assert!(!arena.contains(index));
}
| 412 | 0.751861 | 1 | 0.751861 | game-dev | MEDIA | 0.885712 | game-dev,testing-qa | 0.663851 | 1 | 0.663851 |
matthias-mayr/skiros2_pyrobosim_lib | 7,779 | skiros2_pyrobosim_lib/pyrobosim_primitive_skills.py | from skiros2_skill.core.skill import SkillDescription
from skiros2_common.core.params import ParamTypes
from skiros2_common.core.world_element import Element
from skiros2_common.core.primitive import PrimitiveBase
import skiros2_world_model.ros.world_model_interface as wmi
from skiros2_std_skills.action_client_primitive import PrimitiveActionClient
from skiros2_common.core.abstract_skill import State
from rclpy import action
from delib_ws_problem_interface.perform_action import ACTIONS, ACTION_NAME
from pyrobosim_msgs.action import ExecuteTaskAction
from pyrobosim_msgs.msg import TaskAction, RobotState
from pyrobosim.planning.actions import ExecutionStatus
#################################################################################
# Descriptions
#################################################################################
class NavigateExecution(SkillDescription):
def createDescription(self):
#=======Params=========
self.addParam("TargetLocation", Element("skiros:Location"), ParamTypes.Required)
class PickExecution(SkillDescription):
def createDescription(self):
#=======Params=========
self.addParam("Object", Element("skiros:Part"), ParamTypes.Required)
class PlaceExecution(SkillDescription):
def createDescription(self):
#=======Params=========
self.addParam("Object", Element("skiros:Part"), ParamTypes.Required)
class OpenExecution(SkillDescription):
def createDescription(self):
#=======Params=========
self.addParam("Object", Element("skiros:OpenableLocation"), ParamTypes.Required)
class CloseExecution(SkillDescription):
def createDescription(self):
#=======Params=========
self.addParam("Object", Element("skiros:OpenableLocation"), ParamTypes.Required)
class GetBatteryPercentage(SkillDescription):
def createDescription(self):
#=======Params=========
self.addParam("BatteryLevel", float, ParamTypes.Optional)
class BatteryAboveLevel(SkillDescription):
def createDescription(self):
#=======Params=========
self.addParam("MinBatteryLevel", float, ParamTypes.Required)
class ChargerLocationFromWM(SkillDescription):
def createDescription(self):
#=======Params=========
self.addParam("ChargerLocation", Element("skiros:Location"), ParamTypes.Optional)
#################################################################################
# Implementations
#################################################################################
class pyrobosim_action_client_base(PrimitiveActionClient):
"""
@brief Base class for pyrobosim actions for the boilerplate code
"""
def buildClient(self)->action.ActionClient:
"""
@brief Called when starting the skill
@return an action client
"""
return action.ActionClient(self.node, ExecuteTaskAction, ACTION_NAME)
def onDone(self, msg) -> State:
if msg.execution_result.status == ExecutionStatus.SUCCESS:
return self.success("Successfully finished")
else:
return self.fail("Failure with msg: {}".format(msg.execution_result.message), msg.execution_result.status)
def pyrobosimTaskAction(self, action: ACTIONS, target: str):
"""
@brief Called when starting the skill
@return an action msg initialized
"""
action_goal = TaskAction()
action_goal.robot = self.params["Robot"].value.label.split(":")[-1]
action_goal.type = action.name.lower()
if action == ACTIONS.NAVIGATE:
action_goal.target_location = target
else:
action_goal.object = target
task_action = ExecuteTaskAction.Goal()
task_action.action = action_goal
return task_action
### Primitive skill implementation
class navigate_execution(pyrobosim_action_client_base):
def createDescription(self):
"""Set the primitive type"""
self.setDescription(NavigateExecution(), "Navigate Execution")
def buildGoal(self):
return self.pyrobosimTaskAction(ACTIONS.NAVIGATE, self.params["TargetLocation"].value.label)
class pick_execution(pyrobosim_action_client_base):
def createDescription(self):
"""Set the primitive type"""
self.setDescription(PickExecution(), "Pick Execution")
def buildGoal(self):
return self.pyrobosimTaskAction(ACTIONS.PICK, self.params["Object"].value.label)
class place_execution(pyrobosim_action_client_base):
def createDescription(self):
"""Set the primitive type"""
self.setDescription(PlaceExecution(), "Place Execution")
def buildGoal(self):
return self.pyrobosimTaskAction(ACTIONS.PLACE, self.params["Object"].value.label)
class open_execution(pyrobosim_action_client_base):
def createDescription(self):
"""Set the primitive type"""
self.setDescription(OpenExecution(), "Open Execution")
def buildGoal(self):
return self.pyrobosimTaskAction(ACTIONS.OPEN, self.params["Object"].value.label)
class close_execution(pyrobosim_action_client_base):
def createDescription(self):
"""Set the primitive type"""
self.setDescription(CloseExecution(), "Close Execution")
def buildGoal(self):
return self.pyrobosimTaskAction(ACTIONS.CLOSE, self.params["Object"].value.label)
class get_battery_percentage(PrimitiveBase):
def createDescription(self):
self.setDescription(GetBatteryPercentage(), "Get Battery Percentage")
def onStart(self):
# initial ros 2 topic subscriber
robot_name = self.params["Robot"].value.label.split(":")[-1]
topic = "/{}/robot_state".format(robot_name)
self.subscription = self.node.create_subscription(RobotState, topic, self.callback, 1)
self.battery_level = None
# Obtain world model robot element
# self.robot = self._wmi.get_element(self.params["Robot"].value.id)
return True
def callback(self, msg):
self.battery_level = msg.battery_level
def execute(self):
if self.battery_level is None:
return self.step("Waiting for battery level")
self.params["BatteryLevel"].value = self.battery_level
# self.robot.setProperty("skiros:BatteryPercentage", self.battery_level)
# self._wmi.update_element_properties(self.robot)
return self.success("Battery level is {}".format(self.battery_level))
class battery_above_level(PrimitiveBase):
def createDescription(self):
self.setDescription(BatteryAboveLevel(), "Battery Above Level")
def onStart(self):
self.robot = self._wmi.get_element(self.params["Robot"].value.id)
self.min_level = self.params["MinBatteryLevel"].value
return True
def execute(self):
self.battery_level = self.robot.getProperty("skiros:BatteryPercentage").value
if self.battery_level >= self.min_level:
return self.success(f"Current battery level {self.battery_level} is above the minimum {self.min_level}.")
else:
return self.fail(f"Current battery level {self.battery_level} is below the minimum {self.min_level}.", -1)
class charger_location_from_wm(PrimitiveBase):
def createDescription(self):
self.setDescription(ChargerLocationFromWM(), "Charger Location From World Model")
def onStart(self):
self.chargers = self._wmi.resolve_elements(wmi.Element(":Charger"))
return True
def execute(self):
if not self.chargers:
return self.fail("No charger found in the world model")
self.params["ChargerLocation"].value = self.chargers[0]
return self.success(f"Charger location set to '{self.chargers[0].id}'")
| 412 | 0.823759 | 1 | 0.823759 | game-dev | MEDIA | 0.843121 | game-dev | 0.851985 | 1 | 0.851985 |
Kaedrin/nwn2cc | 13,708 | NWN2 WIP/Override/override_latest/Scripts/cmi_s2_plantshp.NSS |
#include "x2_inc_itemprop"
#include "nwn2_inc_spells"
#include "cmi_ginc_spells"
#include "cmi_ginc_polymorph"
void main()
{
int nSubrace = GetSubRace(OBJECT_SELF);
int nWisBonus = GetAbilityScore(OBJECT_SELF, ABILITY_WISDOM, FALSE) - GetAbilityScore(OBJECT_SELF, ABILITY_WISDOM, TRUE);
int nIntBonus = GetAbilityScore(OBJECT_SELF, ABILITY_INTELLIGENCE, FALSE) - GetAbilityScore(OBJECT_SELF, ABILITY_INTELLIGENCE, TRUE);
int nChaBonus = GetAbilityScore(OBJECT_SELF, ABILITY_CHARISMA, FALSE) - GetAbilityScore(OBJECT_SELF, ABILITY_CHARISMA, TRUE);
int nLevel = GetLevelByClass(CLASS_TYPE_RANGER, OBJECT_SELF);
nLevel += GetLevelByClass(CLASS_VERDANT_GUARDIAN, OBJECT_SELF);
//--------------------------------------------------------------------------
// Declare major variables
//--------------------------------------------------------------------------
int nSpell = SPELLABILITY_VGUARD_PLANT_SHAPE;
object oTarget = GetSpellTargetObject();
effect eVis = EffectVisualEffect(VFX_DUR_POLYMORPH);
effect ePoly;
int nPoly = POLYMORPH_TYPE_TREANT;
//--------------------------------------------------------------------------
// Determine which items get their item properties merged onto the new form.
//--------------------------------------------------------------------------
int bWeapon = StringToInt(Get2DAString("polymorph","MergeW",nPoly)) == 1;
int bArmor = StringToInt(Get2DAString("polymorph","MergeA",nPoly)) == 1;
int bItems = StringToInt(Get2DAString("polymorph","MergeI",nPoly)) == 1;
//--------------------------------------------------------------------------
// Store the old objects so we can access them after the character has
// changed into his new form
//--------------------------------------------------------------------------
object oWeaponOld = GetItemInSlot(INVENTORY_SLOT_RIGHTHAND,OBJECT_SELF);
object oArmorOld = GetItemInSlot(INVENTORY_SLOT_CHEST,OBJECT_SELF);
object oRing1Old = GetItemInSlot(INVENTORY_SLOT_LEFTRING,OBJECT_SELF);
object oRing2Old = GetItemInSlot(INVENTORY_SLOT_RIGHTRING,OBJECT_SELF);
object oAmuletOld = GetItemInSlot(INVENTORY_SLOT_NECK,OBJECT_SELF);
object oCloakOld = GetItemInSlot(INVENTORY_SLOT_CLOAK,OBJECT_SELF);
object oBootsOld = GetItemInSlot(INVENTORY_SLOT_BOOTS,OBJECT_SELF);
object oBeltOld = GetItemInSlot(INVENTORY_SLOT_BELT,OBJECT_SELF);
object oHelmetOld = GetItemInSlot(INVENTORY_SLOT_HEAD,OBJECT_SELF);
object oShield = GetItemInSlot(INVENTORY_SLOT_LEFTHAND,OBJECT_SELF);
if (GetIsObjectValid(oShield))
{
if (GetBaseItemType(oShield) !=BASE_ITEM_LARGESHIELD &&
GetBaseItemType(oShield) !=BASE_ITEM_SMALLSHIELD &&
GetBaseItemType(oShield) !=BASE_ITEM_TOWERSHIELD)
{
oShield = OBJECT_INVALID;
}
}
//--------------------------------------------------------------------------
// Here the actual polymorphing is done
//--------------------------------------------------------------------------
ePoly = EffectPolymorph(nPoly, FALSE, TRUE); // AFW-OEI 06/06/2007: Use 3rd boolean to say this is a wildshape polymorph.
ePoly = ExtraordinaryEffect(ePoly);
ClearAllActions(); // prevents an exploit
if (GetHasFeat(FEAT_GRIM_SURVIVAL))
{
int nSurvival = nLevel / 2;
if (nSurvival > 10)
nSurvival = 10;
effect eSurvival = EffectSkillIncrease(SKILL_SURVIVAL, nSurvival);
ePoly = EffectLinkEffects(ePoly, eSurvival);
}
ApplyEffectToObject(DURATION_TYPE_INSTANT, eVis, OBJECT_SELF);
ApplyEffectToObject(DURATION_TYPE_PERMANENT, ePoly, OBJECT_SELF);
SignalEvent(oTarget, EventSpellCastAt(OBJECT_SELF, GetSpellId(), FALSE));
int nHeal = GetMaxHitPoints() - GetCurrentHitPoints();
if (nHeal > 0)
{
effect eHeal = EffectHeal(nHeal);
DelayCommand(0.2f, ApplyEffectToObject(DURATION_TYPE_INSTANT, eHeal, OBJECT_SELF));
}
//--------------------------------------------------------------------------
// This code handles the merging of item properties
//--------------------------------------------------------------------------
object oWeaponNew = GetItemInSlot(INVENTORY_SLOT_RIGHTHAND,OBJECT_SELF);
object oArmorNew = GetItemInSlot(INVENTORY_SLOT_CARMOUR,OBJECT_SELF);
//identify weapon
SetIdentified(oWeaponNew, TRUE);
//--------------------------------------------------------------------------
// ...Weapons
//--------------------------------------------------------------------------
if (bWeapon)
{
IPWildShapeCopyItemProperties(oWeaponOld,oWeaponNew, TRUE);
}
//--------------------------------------------------------------------------
// ...Armor
//--------------------------------------------------------------------------
if (bArmor)
{
//----------------------------------------------------------------------
// Merge item properties from armor and helmet...
//----------------------------------------------------------------------
IPWildShapeCopyItemProperties(oArmorOld,oArmorNew);
IPWildShapeCopyItemProperties(oHelmetOld,oArmorNew);
IPWildShapeCopyItemProperties(oShield,oArmorNew);
}
//--------------------------------------------------------------------------
// ...Magic Items
//--------------------------------------------------------------------------
if (bItems)
{
//----------------------------------------------------------------------
// Merge item properties from from rings, amulets, cloak, boots, belt
//----------------------------------------------------------------------
IPWildShapeCopyItemProperties(oRing1Old,oArmorNew);
IPWildShapeCopyItemProperties(oRing2Old,oArmorNew);
IPWildShapeCopyItemProperties(oAmuletOld,oArmorNew);
IPWildShapeCopyItemProperties(oCloakOld,oArmorNew);
IPWildShapeCopyItemProperties(oBootsOld,oArmorNew);
IPWildShapeCopyItemProperties(oBeltOld,oArmorNew);
}
float fDuration = HoursToSeconds(nLevel);
object oBracer = GetItemInSlot(INVENTORY_SLOT_ARMS,OBJECT_SELF);
int nUseWildshapeTiers = GetLocalInt(GetModule(), "UseWildshapeTiers");
if (nUseWildshapeTiers)
{
if (nUseWildshapeTiers > 2)
{
IPWildShapeCopyItemProperties(oCloakOld,oArmorNew);
}
if (nUseWildshapeTiers > 1)
{
IPWildShapeCopyItemProperties(oBootsOld,oArmorNew);
IPWildShapeCopyItemProperties(oBeltOld,oArmorNew);
if (GetIsObjectValid(oBracer))
{
if (GetBaseItemType(oBracer) == BASE_ITEM_GLOVES)
IPWildShapeCopyItemProperties(oBracer,oArmorNew);
}
}
if (nUseWildshapeTiers > 0)
{
IPWildShapeCopyItemProperties(oRing1Old,oArmorNew);
IPWildShapeCopyItemProperties(oRing2Old,oArmorNew);
IPWildShapeCopyItemProperties(oAmuletOld,oArmorNew);
if (GetIsObjectValid(oBracer))
{
if (GetBaseItemType(oBracer) == BASE_ITEM_BRACER)
IPWildShapeCopyItemProperties(oBracer,oArmorNew);
}
}
}
WildshapeAbilityBuffs(OBJECT_SELF, fDuration, oWeaponOld, oShield);
itemproperty ipNaturalSpell = ItemPropertyBonusFeat(125);
AddItemProperty(DURATION_TYPE_TEMPORARY, ipNaturalSpell, oArmorNew, fDuration);
int nHD = GetTotalLevels(OBJECT_SELF,FALSE);
//FEAT_EXALTED_WILD_SHAPE
if (GetHasFeat(FEAT_EXALTED_WILD_SHAPE))
{
int nDR = 0;
int nResist = 0;
int nSR = 5 + nHD;
if (nHD > 7)
nResist = 10;
else
nResist = 5;
if (nHD > 11)
nDR = 10;
else
nDR = 5;
effect eDarkVis = EffectDarkVision();
effect eDR = EffectDamageReduction(10, GMATERIAL_METAL_ADAMANTINE, 0, DR_TYPE_GMATERIAL);
effect eSR = EffectSpellResistanceIncrease(nSR);
effect eLink;
if (GetAlignmentGoodEvil(OBJECT_SELF) == ALIGNMENT_EVIL)
{
//Fiendish
effect eDmgRes1 = EffectDamageResistance(DAMAGE_TYPE_FIRE,nResist);
effect eDmgRes2 = EffectDamageResistance(DAMAGE_TYPE_COLD,nResist);
eLink = EffectLinkEffects(eDmgRes1, eDmgRes2);
}
else
{
//Celestial
effect eDmgRes1 = EffectDamageResistance(DAMAGE_TYPE_ACID,nResist);
effect eDmgRes2 = EffectDamageResistance(DAMAGE_TYPE_COLD,nResist);
effect eDmgRes3 = EffectDamageResistance(DAMAGE_TYPE_ELECTRICAL,nResist);
eLink = EffectLinkEffects(eDmgRes1, eDmgRes2);
eLink = EffectLinkEffects(eLink, eDmgRes3);
}
eLink = EffectLinkEffects(eLink, eDarkVis);
eLink = EffectLinkEffects(eLink, eSR);
eLink = EffectLinkEffects(eLink, eDR);
eLink = SetEffectSpellId(eLink,SPELLABILITY_EXALTED_WILD_SHAPE);
eLink = SupernaturalEffect(eLink);
DelayCommand(0.1f, ApplyEffectToObject(DURATION_TYPE_TEMPORARY, eLink, OBJECT_SELF, fDuration));
itemproperty iBonusFeat = ItemPropertyBonusFeat(810); //Darkvision
AddItemProperty(DURATION_TYPE_TEMPORARY,iBonusFeat,oArmorNew,fDuration);
}
//Fix for Spell Slot loss
object oCursedPolyItem = CreateItemOnObject("cmi_cursedpoly",OBJECT_SELF,1,"",FALSE);
if (oCursedPolyItem == OBJECT_INVALID)
SendMessageToPC(OBJECT_SELF, "Your Inventory was full so bonus spell slots from items and racial spellcasting stat modifiers will not survive the transition to your new form.");
AddSpellSlotsToObject(oWeaponOld,oCursedPolyItem, fDuration);
AddSpellSlotsToObject(oArmorOld,oCursedPolyItem, fDuration);
AddSpellSlotsToObject(oRing1Old,oCursedPolyItem, fDuration);
AddSpellSlotsToObject(oRing2Old,oCursedPolyItem, fDuration);
AddSpellSlotsToObject(oAmuletOld,oCursedPolyItem, fDuration);
AddSpellSlotsToObject(oCloakOld,oCursedPolyItem, fDuration);
AddSpellSlotsToObject(oBootsOld,oCursedPolyItem, fDuration);
AddSpellSlotsToObject(oBeltOld,oCursedPolyItem, fDuration);
AddSpellSlotsToObject(oHelmetOld,oCursedPolyItem, fDuration);
AddSpellSlotsToObject(oShield,oCursedPolyItem, fDuration);
if (nWisBonus > 12)
nWisBonus = 12;
if (nIntBonus > 12)
nIntBonus = 12;
if (nChaBonus > 12)
nChaBonus = 12;
itemproperty ipNewEnhance = ItemPropertyAbilityBonus(IP_CONST_ABILITY_WIS, nWisBonus);
IPSafeAddItemProperty(oCursedPolyItem, ipNewEnhance,fDuration, X2_IP_ADDPROP_POLICY_REPLACE_EXISTING, FALSE, FALSE);
ipNewEnhance = ItemPropertyAbilityBonus(IP_CONST_ABILITY_INT, nIntBonus);
IPSafeAddItemProperty(oCursedPolyItem, ipNewEnhance,fDuration, X2_IP_ADDPROP_POLICY_REPLACE_EXISTING, FALSE, FALSE);
ipNewEnhance = ItemPropertyAbilityBonus(IP_CONST_ABILITY_CHA, nChaBonus);
IPSafeAddItemProperty(oCursedPolyItem, ipNewEnhance,fDuration, X2_IP_ADDPROP_POLICY_REPLACE_EXISTING, FALSE, FALSE);
if (GetHasFeat(FEAT_NATWARR_NATARM_CROC))
{
int nAC = 0;
//Amulet based AC
if (GetItemHasItemProperty(oAmuletOld, ITEM_PROPERTY_AC_BONUS))
{
itemproperty ipLoop=GetFirstItemProperty(oAmuletOld);
while (GetIsItemPropertyValid(ipLoop))
{
//SendMessageToPC(OBJECT_SELF, "InLoop");
if (GetItemPropertyType(ipLoop)==ITEM_PROPERTY_AC_BONUS)
{
nAC = GetItemPropertyParam1Value(ipLoop);
}
ipLoop=GetNextItemProperty(oAmuletOld);
}
}
//Spell based AC
int nEffAC;
int nType;
effect eEffect = GetFirstEffect(OBJECT_SELF);
while(GetIsEffectValid(eEffect))
{
nType = GetEffectType(eEffect);
if(nType == EFFECT_TYPE_AC_INCREASE)
{
if (GetEffectInteger(eEffect, 0) == 1)
nEffAC = GetEffectInteger(eEffect, 1);
}
eEffect = GetNextEffect(OBJECT_SELF);
}
//Final AC
if (nEffAC > nAC)
nAC = nEffAC;
nAC = nAC + GetLevelByClass(CLASS_NATURES_WARRIOR);
if (GetHasFeat(490, OBJECT_SELF))
nAC++;
effect eAC = EffectACIncrease(nAC, AC_NATURAL_BONUS);
eAC = ExtraordinaryEffect(eAC);
eAC = SetEffectSpellId(eAC,-FEAT_NATWARR_NATARM_CROC);
DelayCommand(0.1f, ApplyEffectToObject(DURATION_TYPE_TEMPORARY, eAC, OBJECT_SELF, fDuration));
}
if (GetHasFeat(FEAT_NATWARR_NATARM_GRIZZLY))
{
effect eDmg = EffectDamageIncrease(3);
eDmg = ExtraordinaryEffect(eDmg);
eDmg = SetEffectSpellId(eDmg,-FEAT_NATWARR_NATARM_GRIZZLY);
DelayCommand(0.1f, ApplyEffectToObject(DURATION_TYPE_TEMPORARY, eDmg, OBJECT_SELF, fDuration));
}
if (GetHasFeat(FEAT_NATWARR_NATARM_GROWTH))
{
effect eRegen = EffectRegenerate(1, 6.0f);
eRegen = ExtraordinaryEffect(eRegen);
eRegen = SetEffectSpellId(eRegen,-FEAT_NATWARR_NATARM_GROWTH);
DelayCommand(0.1f, ApplyEffectToObject(DURATION_TYPE_TEMPORARY, eRegen, OBJECT_SELF, fDuration));
}
if (GetHasFeat(FEAT_NATWARR_NATARM_EARTH))
{
int nDR = 3;
if (GetHasFeat(494))
{
nDR += 9;
}
else
if (GetHasFeat(493))
{
nDR += 6;
}
else
if (GetHasFeat(492))
{
nDR += 3;
}
if (GetHasFeat(1253))
nDR++;
effect eDR = EffectDamageReduction(nDR, DR_TYPE_NONE, 0, DR_TYPE_NONE);
eDR = SetEffectSpellId(eDR,-FEAT_NATWARR_NATARM_EARTH);
eDR = ExtraordinaryEffect(eDR);
DelayCommand(0.1f, ApplyEffectToObject(DURATION_TYPE_TEMPORARY, eDR, OBJECT_SELF, fDuration));
}
if (GetHasSpellEffect(SPELLABILITY_FOTF_AC_BONUS,OBJECT_SELF))
{
RemoveSpellEffects(SPELLABILITY_FOTF_AC_BONUS, OBJECT_SELF, OBJECT_SELF);
}
WildshapeCheck (OBJECT_SELF,oCursedPolyItem);
if (GetLocalInt(GetModule(), "UnarmedPolymorphFeatFix"))
DelayCommand(2.0f, WildShape_Unarmed(oTarget, fDuration));
//--------------------------------------------------------------------------
// Decrement wildshape uses
//--------------------------------------------------------------------------
DecrementRemainingFeatUses(OBJECT_SELF, FEAT_VGUARD_PLANT_SHAPE1);
} | 412 | 0.904216 | 1 | 0.904216 | game-dev | MEDIA | 0.940028 | game-dev | 0.9757 | 1 | 0.9757 |
glscene/GLXEngine | 33,935 | Sourcex/GXS.Gui.pas | //
// The graphics engine GLXEngine. The unit of GXScene for Delphi
//
unit GXS.Gui;
(* In GL windows management classes and structures *)
interface
{$I Stage.Defines.inc}
uses
Winapi.OpenGL,
Winapi.OpenGLext,
System.Classes,
System.SysUtils,
Stage.VectorTypes,
GXS.Scene,
GXS.BitmapFont,
GXS.Material,
GXS.Context,
GXS.PersistentClasses,
Stage.VectorGeometry,
GXS.Coordinates,
GXS.BaseClasses;
type
TgxBaseGuiObject = class(TgxBaseSceneObject)
private
FRecursiveVisible: Boolean;
FWidth: Single;
FHeight: Single;
protected
// self notification on hide. Also notifies children.
procedure NotifyHide; virtual;
// child notification on show. Also notifies children.
procedure NotifyShow; virtual;
procedure SetLeft(const Value: Single);
function GetLeft: Single;
procedure SetTop(const Value: Single);
function GetTop: Single;
procedure SetWidth(const val: Single);
procedure SetHeight(const val: Single);
procedure SetVisible(aValue: Boolean); override;
public
constructor Create(AOwner: TComponent); override;
procedure AddChild(AChild: TgxBaseSceneObject); override;
procedure Insert(aIndex: Integer; aChild: TgxBaseSceneObject); override;
// GuiComponent Width in 3D world units.
property Width: Single read FWidth write SetWidth;
// GuiComponent Height in 3D world units.
property Height: Single read FHeight write SetHeight;
// GuiComponent Left in 3D world units.
property Left: Single read GetLeft write SetLeft;
// GuiComponent Top in 3D world units.
property Top: Single read GetTop write SetTop;
property RecursiveVisible: Boolean read FRecursiveVisible;
end;
TGUIAlignments = (GLAlTopLeft, GLAlTop, GLAlTopRight, GLAlLeft, GLAlCenter,
GLAlRight, GLAlBottomLeft, GLAlBottom, GLAlBottomRight, GLAlBorder);
TGUIRect = record
X1: Single;
Y1: Single;
X2: Single;
Y2: Single;
XTiles: Single;
YTiles: Single;
end;
TGUIDrawResult = array[TGUIAlignments] of TGUIRect;
TgxGuiElementName = string;
TgxGuiElement = class(TCollectionItem)
private
FTopLeft: TgxCoordinates2;
FBottomRight: TgxCoordinates2;
FScale: TgxCoordinates2;
FAlign: TGUIAlignments;
FName: TgxGuiElementName;
protected
function GetDisplayName: string; override;
procedure SetName(const val: TgxGuiElementName);
public
constructor Create(Collection: TCollection); override;
destructor Destroy; override;
procedure AssignTo(Dest: TPersistent); override;
published
property TopLeft: TgxCoordinates2 read FTopLeft write FTopLeft;
property BottomRight: TgxCoordinates2 read FBottomRight write FBottomRight;
property Scale: TgxCoordinates2 read FScale write FScale;
property Align: TGUIAlignments read FAlign write FAlign;
property Name: TgxGuiElementName read FName write SetName;
end;
TgxGuiComponent = class;
TgxGuiElementList = class(TOwnedCollection)
private
FGuiComponent: TgxGuiComponent;
protected
procedure SetItems(index: Integer; const val: TgxGuiElement);
function GetItems(index: Integer): TgxGuiElement;
public
constructor Create(AOwner: TgxGuiComponent);
procedure AssignTo(Dest: TPersistent); override;
function GetOwner: TPersistent; override;
function IndexOf(const Item: TgxGuiElement): Integer;
property Items[index: Integer]: TgxGuiElement read GetItems write SetItems;
default;
end;
TgxGuiComponentName = string;
TgxGuiComponentList = class;
TgxGuiComponent = class(TCollectionItem)
private
FElements: TgxGuiElementList;
FName: TgxGuiComponentName;
protected
function GetDisplayName: string; override;
procedure SetName(const val: TgxGuiComponentName);
public
constructor Create(Collection: TCollection); override;
destructor Destroy; override;
procedure AssignTo(Dest: TPersistent); override;
procedure RenderToArea(X1, Y1, X2, Y2: Single; var Res: TGUIDrawResult;
Refresh: Boolean = True; Scale: Single = 1);
function GetOwnerList: TgxGuiComponentList;
property Owner: TgxGuiComponentList read GetOwnerList;
published
property Elements: TgxGuiElementList read FElements write FElements;
property Name: TgxGuiComponentName read FName write SetName;
end;
TgxGuiLayout = class;
TgxGuiComponentList = class(TOwnedCollection)
private
FLayout: TgxGuiLayout;
protected
procedure SetItems(index: Integer; const val: TgxGuiComponent);
function GetItems(index: Integer): TgxGuiComponent;
public
constructor Create(AOwner: TgxGuiLayout);
function GetOwner: TPersistent; override;
function FindItem(name: TgxGuiComponentName): TgxGuiComponent;
property Items[index: Integer]: TgxGuiComponent read GetItems write
SetItems; default;
end;
TgxGuiLayout = class(TgxUpdateAbleComponent)
private
FBitmapFont: TgxCustomBitmapFont;
FMaterial: TgxMaterial;
FGuiComponents: TgxGuiComponentList;
FFileName: string;
FGuiComponentList: TList;
protected
procedure Notification(AComponent: TComponent; Operation: TOperation);
override;
procedure SetFileName(newName: string);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
procedure LoadFromStream(Stream: TStream);
procedure LoadFromFile(FN: string);
procedure Clear;
procedure SaveToStream(Stream: TStream);
procedure SaveToFile(FN: string);
procedure AddGuiComponent(Component: TgxUpdateAbleComponent);
procedure RemoveGuiComponent(Component: TgxUpdateAbleComponent);
procedure NotifyChange(Sender: TObject); override;
published
property BitmapFont: TgxCustomBitmapFont read FBitmapFont write FBitmapFont;
property Material: TgxMaterial read FMaterial write FMaterial;
property GuiComponents: TgxGuiComponentList read FGuiComponents write
FGuiComponents;
property FileName: string read FFileName write SetFileName;
end;
const
GuiNullRect: TGUIRect = (X1: 0.0; Y1: 0.0; X2: 0.0; Y2: 0.0; XTiles: 0.0;
YTiles: 0.0);
function IsInRect(const R: TGUIRect; X, Y: Single): Boolean;
//-----------------------------------
implementation
//-----------------------------------
function IsInRect(const R: TGUIRect; X, Y: Single): Boolean;
begin
Result := (R.X1 <= X) and (R.X2 >= X) and (R.Y1 <= Y) and (R.Y2 >= Y);
end;
// ------------------
// ------------------ TgxBaseGuiObject ------------------
// ------------------
constructor TgxBaseGuiObject.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FRecursiveVisible := Visible;
end;
procedure TgxBaseGuiObject.SetLeft(const Value: Single);
var
NewPosX: Single;
i: integer;
Diff: Single;
begin
if Assigned(Parent) and (Parent is TgxBaseGuiObject) then
NewPosX := (Parent as TgxBaseGuiObject).Position.X + Value
else
NewPosX := Value;
if Position.X <> NewPosX then
begin
Diff := NewPosX - Position.X;
Position.X := NewPosX;
for i := 0 to Count - 1 do
if Children[i] is TgxBaseGuiObject then
begin
(Children[i] as TgxBaseGuiObject).Left := (Children[i] as
TgxBaseGuiObject).Left + Diff;
end;
end;
end;
function TgxBaseGuiObject.GetLeft: Single;
begin
if Assigned(Parent) and (Parent is TgxBaseGuiObject) then
Result := Position.X - (Parent as TgxBaseGuiObject).Position.X
else
Result := Position.X;
end;
procedure TgxBaseGuiObject.SetTop(const Value: Single);
var
NewPosY: Single;
i: integer;
Diff: Single;
begin
if Assigned(Parent) and (Parent is TgxBaseGuiObject) then
NewPosY := (Parent as TgxBaseGuiObject).Position.Y + Value
else
NewPosY := Value;
if Position.Y <> NewPosY then
begin
Diff := NewPosY - Position.Y;
Position.Y := NewPosY;
for i := 0 to Count - 1 do
if Children[i] is TgxBaseGuiObject then
begin
(Children[i] as TgxBaseGuiObject).Top := (Children[i] as
TgxBaseGuiObject).Top + Diff;
end;
end;
end;
function TgxBaseGuiObject.GetTop: Single;
begin
if Assigned(Parent) and (Parent is TgxBaseGuiObject) then
Result := Position.Y - (Parent as TgxBaseGuiObject).Position.Y
else
Result := Position.Y;
end;
procedure TgxBaseGuiObject.SetWidth(const val: Single);
begin
if FWidth <> val then
begin
FWidth := val;
NotifyChange(Self);
end;
end;
procedure TgxBaseGuiObject.SetHeight(const val: Single);
begin
if FHeight <> val then
begin
FHeight := val;
NotifyChange(Self);
end;
end;
procedure TgxBaseGuiObject.NotifyHide;
var
child: TgxBaseSceneObject;
xc: Integer;
begin
if RecursiveVisible then
begin
FRecursiveVisible := False;
for xc := 0 to Count - 1 do
begin
child := Children[xc];
if child is TgxBaseGuiObject then
TgxBaseGuiObject(child).NotifyHide;
end;
end;
end;
procedure TgxBaseGuiObject.NotifyShow;
var
child: TgxBaseSceneObject;
xc: Integer;
begin
if not RecursiveVisible then
begin
FRecursiveVisible := True;
for xc := 0 to Count - 1 do
begin
child := Children[xc];
if child is TgxBaseGuiObject then
TgxBaseGuiObject(child).NotifyShow;
end;
end;
end;
procedure TgxBaseGuiObject.AddChild(aChild: TgxBaseSceneObject);
begin
inherited;
if AChild is TgxBaseGuiObject then
begin
if RecursiveVisible then
TgxBaseGuiObject(AChild).NotifyShow
else
TgxBaseGuiObject(AChild).NotifyHide;
end;
end;
procedure TgxBaseGuiObject.Insert(aIndex: Integer; aChild: TgxBaseSceneObject);
begin
inherited;
if AChild is TgxBaseGuiObject then
begin
if RecursiveVisible then
TgxBaseGuiObject(AChild).NotifyShow
else
TgxBaseGuiObject(AChild).NotifyHide;
end;
end;
procedure TgxBaseGuiObject.SetVisible(aValue: Boolean);
begin
if Visible <> aValue then
begin
inherited SetVisible(aValue);
if aValue then
begin
if Parent <> nil then
if Parent is TgxBaseGuiObject then
begin
if TgxBaseGuiObject(Parent).RecursiveVisible then
NotifyShow;
end
else
begin
if Parent.Visible then
NotifyShow;
end;
end
else
begin
if RecursiveVisible then
NotifyHide;
end;
end;
end;
constructor TgxGuiLayout.Create(AOwner: TComponent);
begin
FGuiComponentList := TList.Create;
inherited;
FGuiComponents := TgxGuiComponentList.Create(Self);
FMaterial := TgxMaterial.Create(Self);
end;
destructor TgxGuiLayout.Destroy;
begin
Clear;
FMaterial.Free;
FGuiComponents.Free;
inherited;
FGuiComponentList.Free;
end;
procedure TgxGuiLayout.SetFileName(newName: string);
begin
if newName <> FFileName then
begin
FFileName := newName;
if FileExists(FFileName) then
begin
Clear;
loadFromFile(FFileName);
end;
end;
end;
procedure TgxGuiLayout.LoadFromFile(FN: string);
var
Stream: TMemoryStream;
begin
Stream := TMemoryStream.Create;
try
Stream.LoadFromFile(FN);
LoadFromStream(stream);
FFileName := FN;
finally
stream.Free;
end;
end;
procedure TgxGuiLayout.SaveToFile(FN: string);
var
Stream: TMemoryStream;
begin
Stream := TMemoryStream.Create;
try
SaveToStream(Stream);
Stream.SaveToFile(FN);
FFileName := FN;
finally
Stream.Free;
end;
end;
procedure TgxGuiLayout.AddGuiComponent(Component: TgxUpdateAbleComponent);
begin
if FGuiComponentList.IndexOf(Component) < 0 then
begin
FreeNotification(Component);
FGuiComponentList.Add(Component);
end;
end;
procedure TgxGuiLayout.RemoveGuiComponent(Component: TgxUpdateAbleComponent);
begin
FGuiComponentList.Remove(Component);
RemoveFreeNotification(Component);
end;
procedure TgxGuiLayout.Assign(Source: TPersistent);
var
LLayout: TgxGuiLayout;
LComponent: TgxGuiComponent;
I: Integer;
begin
if Source is TgxGuiLayout then
begin
LLayout := TgxGuiLayout(Source);
FBitmapFont := LLayout.FBitmapFont;
FMaterial.Assign(LLayout.Material);
FFileName := LLayout.FFileName;
Clear;
for I := 0 to LLayout.FGuiComponents.Count - 1 do
begin
LComponent := TgxGuiComponent(FGuiComponents.Add);
LLayout.FGuiComponents[I].AssignTo(LComponent);
LComponent.Name := LLayout.FGuiComponents[I].Name;
end;
for I := 0 to FGuiComponentList.Count - 1 do
TgxUpdateAbleComponent(FGuiComponentList[I]).RemoveFreeNotification(Self);
FGuiComponentList.Assign(LLayout.FGuiComponentList);
for I := 0 to FGuiComponentList.Count - 1 do
TgxUpdateAbleComponent(FGuiComponentList[I]).FreeNotification(Self);
end
else
inherited; // Assign Error
end;
procedure TgxGuiLayout.Clear;
var
XC: Integer;
begin
for XC := FGuiComponents.Count - 1 downto 0 do
begin
FGuiComponents.Delete(XC);
end;
NotifyChange(Self);
end;
procedure TgxGuiLayout.NotifyChange(Sender: TObject);
var
XC: Integer;
begin
inherited;
for XC := FGuiComponentList.Count - 1 downto 0 do
TgxUpdateAbleComponent(FGuiComponentList[XC]).NotifyChange(Self);
end;
procedure TgxGuiLayout.LoadFromStream(Stream: TStream);
var
TmpComponent: TgxGuiComponent;
XC, YC, ZC: Integer;
TmpElement: TgxGuiElement;
TmpAlignment: TGUIAlignments;
Version: Integer;
Data: TgxBinaryReader;
begin
Data := TgxBinaryReader.Create(Stream);
try
Version := Data.ReadInteger;
if Version <> 1 then
Exit;
for XC := 0 to Data.ReadInteger - 1 do
begin
TmpComponent := FGuiComponents.Add as TgxGuiComponent;
TmpComponent.FName := Data.ReadString;
for YC := 0 to Data.ReadInteger - 1 do
begin
TmpElement := TmpComponent.FElements.add as TgxGuiElement;
TmpElement.FName := Data.ReadString;
TmpElement.FTopLeft.X := Data.ReadFloat;
TmpElement.FTopLeft.Y := Data.ReadFloat;
TmpElement.FTopLeft.Z := Data.ReadFloat;
TmpElement.FBottomRight.X := Data.ReadFloat;
TmpElement.FBottomRight.Y := Data.ReadFloat;
TmpElement.FBottomRight.Z := Data.ReadFloat;
TmpElement.FScale.X := Data.ReadFloat;
TmpElement.FScale.Y := Data.ReadFloat;
TmpElement.FScale.Z := Data.ReadFloat;
for ZC := 0 to Data.ReadInteger - 1 do
begin
TmpAlignment := TGUIAlignments(Data.ReadInteger);
TmpElement.FAlign := TmpAlignment;
end;
end;
end;
finally
Data.Free;
end;
NotifyChange(Self);
end;
procedure TgxGuiLayout.SaveToStream(stream: TStream);
var
TmpComponent: TgxGuiComponent;
Alignments, XC, YC: Integer;
TmpElement: TgxGuiElement;
TmpAlignment: TGUIAlignments;
Data: TgxBinaryWriter;
begin
Data := TgxBinaryWriter.Create(Stream);
try
Data.WriteInteger(1);
Data.WriteInteger(FGuiComponents.Count);
for XC := 0 to FGuiComponents.Count - 1 do
begin
TmpComponent := FGuiComponents.Items[XC];
Data.WriteString(TmpComponent.FName);
Data.WriteInteger(TmpComponent.FElements.Count);
for YC := 0 to TmpComponent.FElements.Count - 1 do
begin
TmpElement := TmpComponent.FElements.Items[YC];
Data.WriteString(TmpElement.FName);
Data.WriteFloat(TmpElement.FTopLeft.X);
Data.WriteFloat(TmpElement.FTopLeft.Y);
Data.WriteFloat(TmpElement.FTopLeft.Z);
Data.WriteFloat(TmpElement.FBottomRight.X);
Data.WriteFloat(TmpElement.FBottomRight.Y);
Data.WriteFloat(TmpElement.FBottomRight.Z);
Data.WriteFloat(TmpElement.FScale.X);
Data.WriteFloat(TmpElement.FScale.Y);
Data.WriteFloat(TmpElement.FScale.Z);
Alignments := 0;
for TmpAlignMent := GLAlTopLeft to GLAlBorder do
begin
if TmpAlignMent = TmpElement.FAlign then
inc(Alignments);
end;
Data.WriteInteger(Alignments);
for TmpAlignMent := GLAlTopLeft to GLAlBorder do
begin
if TmpAlignMent = TmpElement.FAlign then
Data.WriteInteger(Integer(TmpAlignMent));
end;
end;
end;
finally
Data.Free;
end;
end;
constructor TgxGuiComponentList.Create(AOwner: TgxGuiLayout);
begin
inherited Create(AOwner, TgxGuiComponent);
FLayout := AOwner;
end;
function TgxGuiComponentList.GetOwner: TPersistent;
begin
Result := FLayout;
end;
procedure TgxGuiComponentList.SetItems(index: Integer; const val:
TgxGuiComponent);
begin
inherited Items[index] := val;
end;
function TgxGuiComponentList.FindItem(name: TgxGuiComponentName):
TgxGuiComponent;
var
XC: Integer;
gc: TgxGuiComponent;
begin
Result := nil;
if Name = '' then
Exit;
for XC := 0 to Count - 1 do
begin
gc := Items[xc];
if gc.FName = Name then
begin
Result := gc;
Break;
end;
end;
end;
function TgxGuiComponentList.GetItems(index: Integer): TgxGuiComponent;
begin
Result := TgxGuiComponent(inherited Items[index]);
end;
procedure TgxGuiComponent.RenderToArea(X1, Y1, X2, Y2: Single; var Res:
TGUIDrawResult; Refresh: Boolean = True; Scale: Single = 1);
var
XC: Integer;
ThisElement: TgxGuiElement;
W, H: Single;
Len1, Len2: Single;
Layout: TgxGuiLayout;
LibMaterial: TgxLibMaterial;
Material: TgxMaterial;
TexWidth,
TexHeight: Single;
AlignCount: TGUIAlignments;
procedure Prepare;
begin
Len1 := (ThisElement.FTopLeft.x - ThisElement.FBottomRight.x) *
ThisElement.Scale.X * Scale;
Len2 := (ThisElement.FTopLeft.y - ThisElement.FBottomRight.y) *
ThisElement.Scale.Y * Scale;
if Len1 < 0 then
begin
if Len2 < 0 then
begin
W := -Len1;
H := -Len2;
end
else
begin
W := -Len1;
H := Len2;
end;
end
else
begin
if Len2 < 0 then
begin
W := Len1;
H := -Len2;
end
else
begin
W := Len1;
H := Len2;
end;
end;
end;
procedure RenderIt(var ARect: TGuiRect; AElement: TgxGuiElement);
var
XC: Single;
YC: Single;
XPos, X2Pos: Single;
YPos, y2Pos: Single;
tx1, ty1, tx2, ty2: Single;
XTileSize, YTileSize: Single;
tx3, ty3: Single;
tx, ty: Single;
begin
if (ARect.XTiles = 1) and (ARect.YTiles = 1) then
begin
glTexCoord2f(AElement.TopLeft.X / TexWidth, -AElement.TopLeft.Y /
TexHeight);
glVertex2f(ARect.X1, -ARect.Y1);
glTexCoord2f(AElement.TopLeft.X / TexWidth, -AElement.BottomRight.Y /
TexHeight);
glVertex2f(ARect.X1, -ARect.Y2);
glTexCoord2f(AElement.BottomRight.X / TexWidth, -AElement.BottomRight.Y /
TexHeight);
glVertex2f(ARect.X2, -ARect.Y2);
glTexCoord2f(AElement.BottomRight.X / TexWidth, -AElement.TopLeft.Y /
TexHeight);
glVertex2f(ARect.X2, -ARect.Y1);
end
else
begin
XTileSize := (ARect.X2 - ARect.X1) / ARect.XTiles;
YTileSize := (ARect.Y2 - ARect.Y1) / ARect.YTiles;
tx1 := AElement.TopLeft.X / TexWidth;
ty1 := -AElement.TopLeft.Y / TexHeight;
tx2 := AElement.BottomRight.X / TexWidth;
ty2 := -AElement.BottomRight.Y / TexHeight;
tx3 := (AElement.TopLeft.X + (AElement.BottomRight.X - AElement.TopLeft.X)
* Frac(ARect.XTiles)) / TexWidth;
ty3 := -(AElement.TopLeft.y + (AElement.BottomRight.y - AElement.TopLeft.y)
* Frac(ARect.yTiles)) / TexHeight;
XC := ARect.XTiles;
XPos := ARect.X1;
tx := tx2;
while XC > 0 do
begin
YC := ARect.YTiles;
YPos := ARect.Y1;
ty := ty2;
if XC >= 1 then
X2Pos := XPos + XTileSize
else
begin
X2Pos := ARect.X2;
tx := tx3;
end;
while YC > 0 do
begin
if YC >= 1 then
Y2Pos := YPos + YTileSize
else
begin
Y2Pos := ARect.Y2;
ty := ty3;
end;
glTexCoord2f(tx1, ty1);
glVertex2f(XPos, -YPos);
glTexCoord2f(tx1, ty);
glVertex2f(XPos, -Y2Pos);
glTexCoord2f(tx, ty);
glVertex2f(X2Pos, -Y2Pos);
glTexCoord2f(tx, ty1);
glVertex2f(X2Pos, -YPos);
yc := yc - 1.0;
ypos := Y2Pos;
end;
xc := xc - 1.0;
xpos := X2Pos;
end;
end;
end;
procedure RenderBorder(AElement: TgxGuiElement);
var
TmpElement: TgxGuiElement;
begin
TmpElement := TgxGuiElement.Create(nil);
TmpElement.FTopLeft.X := ThisElement.FTopLeft.X;
TmpElement.FTopLeft.Y := ThisElement.FTopLeft.Y;
TmpElement.FBottomRight.X := ThisElement.FTopLeft.X + ThisElement.Scale.X;
TmpElement.FBottomRight.Y := ThisElement.FTopLeft.Y + ThisElement.Scale.Y;
TmpElement.Scale.SetPoint2D(1, 1);
RenderIt(Res[GLALTopLeft], TmpElement);
TmpElement.FTopLeft.X := ThisElement.FTopLeft.X + ThisElement.Scale.X;
TmpElement.FBottomRight.X := ThisElement.FBottomRight.X -
ThisElement.Scale.X;
RenderIt(Res[GLALTop], TmpElement);
TmpElement.FTopLeft.X := ThisElement.FBottomRight.X - ThisElement.Scale.X;
TmpElement.FBottomRight.X := ThisElement.FBottomRight.X;
RenderIt(Res[GLALTopRight], TmpElement);
TmpElement.FTopLeft.Y := ThisElement.FTopLeft.Y + ThisElement.Scale.Y;
TmpElement.FBottomRight.Y := ThisElement.FBottomRight.Y -
ThisElement.Scale.Y;
RenderIt(Res[GLALRight], TmpElement);
TmpElement.FTopLeft.X := ThisElement.FBottomRight.X - ThisElement.Scale.X;
TmpElement.FTopLeft.Y := ThisElement.FBottomRight.Y - ThisElement.Scale.Y;
TmpElement.FBottomRight.X := ThisElement.FBottomRight.X;
TmpElement.FBottomRight.Y := ThisElement.FBottomRight.Y;
RenderIt(Res[GLALBottomRight], TmpElement);
TmpElement.FTopLeft.X := ThisElement.FTopLeft.X + ThisElement.Scale.X;
TmpElement.FTopLeft.Y := ThisElement.FBottomRight.Y - ThisElement.Scale.Y;
TmpElement.FBottomRight.X := ThisElement.FBottomRight.X -
ThisElement.Scale.X;
TmpElement.FBottomRight.Y := ThisElement.FBottomRight.Y;
RenderIt(Res[GLALBottom], TmpElement);
TmpElement.FTopLeft.X := ThisElement.FTopLeft.X;
TmpElement.FTopLeft.Y := ThisElement.FBottomRight.Y - ThisElement.Scale.Y;
TmpElement.FBottomRight.X := ThisElement.FTopLeft.X + ThisElement.Scale.X;
TmpElement.FBottomRight.Y := ThisElement.FBottomRight.Y;
RenderIt(Res[GLALBottomLeft], TmpElement);
TmpElement.FTopLeft.X := ThisElement.FTopLeft.X;
TmpElement.FTopLeft.Y := ThisElement.FTopLeft.Y + ThisElement.Scale.Y;
TmpElement.FBottomRight.X := ThisElement.FTopLeft.X + ThisElement.Scale.X;
TmpElement.FBottomRight.Y := ThisElement.FBottomRight.Y -
ThisElement.Scale.Y;
RenderIt(Res[GLALLeft], TmpElement);
TmpElement.FTopLeft.X := ThisElement.FTopLeft.X + ThisElement.Scale.X;
TmpElement.FTopLeft.Y := ThisElement.FTopLeft.Y + ThisElement.Scale.Y;
TmpElement.FBottomRight.X := ThisElement.FBottomRight.X -
ThisElement.Scale.X;
TmpElement.FBottomRight.Y := ThisElement.FBottomRight.Y -
ThisElement.Scale.Y;
RenderIt(Res[GLALCenter], TmpElement);
end;
begin
Layout := ((GetOwner as TgxGuiComponentList).GetOwner as TgxGuiLayout);
Material := nil;
if Assigned(Layout.Material.MaterialLibrary)
and (Layout.Material.MaterialLibrary is TgxMaterialLibrary)
and (Layout.Material.LibMaterialName <> '') then
begin
LibMaterial :=
TgxMaterialLibrary(Layout.Material.MaterialLibrary).Materials.GetLibMaterialByName(Layout.Material.LibMaterialName);
if Assigned(LibMaterial) then
Material := LibMaterial.Material;
end;
if not Assigned(Material) then
begin
Material := Layout.Material;
end;
if Refresh then
begin
Res[GLALtopLeft].X1 := X1;
Res[GLALtopLeft].Y1 := Y1;
Res[GLALtopLeft].X2 := X1;
Res[GLALtopLeft].Y2 := Y1;
Res[GLALtopRight].X1 := X2;
Res[GLALtopRight].Y1 := Y1;
Res[GLALtopRight].X2 := X2;
Res[GLALtopRight].Y2 := Y1;
Res[GLALBottomLeft].X1 := X1;
Res[GLALBottomLeft].Y1 := Y2;
Res[GLALBottomLeft].X2 := X1;
Res[GLALBottomLeft].Y2 := Y2;
Res[GLALBottomRight].X1 := X2;
Res[GLALBottomRight].Y1 := Y2;
Res[GLALBottomRight].X2 := X2;
Res[GLALBottomRight].Y2 := Y2;
for XC := 0 to FElements.Count - 1 do
begin
ThisElement := FElements[XC];
if GLAlBorder = ThisElement.Align then
begin
Res[GLALtopLeft].X1 := X1;
Res[GLALtopLeft].Y1 := Y1;
Res[GLALtopLeft].X2 := X1 + ThisElement.Scale.X * Scale *
ThisElement.Scale.Z;
Res[GLALtopLeft].Y2 := Y1 + ThisElement.Scale.Y * Scale *
ThisElement.Scale.Z;
Res[GLALtop].X1 := X1 + ThisElement.Scale.X * Scale *
ThisElement.Scale.Z;
Res[GLALtop].Y1 := Y1;
Res[GLALtop].X2 := X2 - ThisElement.Scale.X * Scale *
ThisElement.Scale.Z;
Res[GLALtop].Y2 := Y1 + ThisElement.Scale.Y * Scale *
ThisElement.Scale.Z;
Res[GLALtopRight].X1 := X2 - ThisElement.Scale.X * Scale *
ThisElement.Scale.Z;
Res[GLALtopRight].Y1 := Y1;
Res[GLALtopRight].X2 := X2;
Res[GLALtopRight].Y2 := Y1 + ThisElement.Scale.Y * Scale *
ThisElement.Scale.Z;
Res[GLALRight].X1 := X2 - ThisElement.Scale.X * Scale *
ThisElement.Scale.Z;
Res[GLALRight].Y1 := Y1 + ThisElement.Scale.Y * Scale *
ThisElement.Scale.Z;
Res[GLALRight].X2 := X2;
Res[GLALRight].Y2 := Y2 - ThisElement.Scale.Y * Scale *
ThisElement.Scale.Z;
Res[GLALBottomRight].X1 := X2 - ThisElement.Scale.X * Scale *
ThisElement.Scale.Z;
Res[GLALBottomRight].Y1 := Y2 - ThisElement.Scale.Y * Scale *
ThisElement.Scale.Z;
Res[GLALBottomRight].X2 := X2;
Res[GLALBottomRight].Y2 := Y2;
Res[GLALBottom].X1 := X1 + ThisElement.Scale.X * Scale *
ThisElement.Scale.Z;
Res[GLALBottom].Y1 := Y2 - ThisElement.Scale.Y * Scale *
ThisElement.Scale.Z;
Res[GLALBottom].X2 := X2 - ThisElement.Scale.X * Scale *
ThisElement.Scale.Z;
Res[GLALBottom].Y2 := Y2;
Res[GLALBottomLeft].X1 := X1;
Res[GLALBottomLeft].Y1 := Y2 - ThisElement.Scale.Y * Scale *
ThisElement.Scale.Z;
Res[GLALBottomLeft].X2 := X1 + ThisElement.Scale.X * Scale *
ThisElement.Scale.Z;
Res[GLALBottomLeft].Y2 := Y2;
Res[GLALLeft].X1 := X1;
Res[GLALLeft].Y1 := Y1 + ThisElement.Scale.Y * Scale *
ThisElement.Scale.Z;
Res[GLALLeft].X2 := X1 + ThisElement.Scale.X * Scale *
ThisElement.Scale.Z;
Res[GLALLeft].Y2 := Y2 - ThisElement.Scale.Y * Scale *
ThisElement.Scale.Z;
Res[GLALCenter].X1 := X1 + ThisElement.Scale.X * Scale *
ThisElement.Scale.Z;
Res[GLALCenter].Y1 := Y1 + ThisElement.Scale.Y * Scale *
ThisElement.Scale.Z;
Res[GLALCenter].X2 := X2 - ThisElement.Scale.X * Scale *
ThisElement.Scale.Z;
Res[GLALCenter].Y2 := Y2 - ThisElement.Scale.Y * Scale *
ThisElement.Scale.Z;
end;
if GLALtopLeft = ThisElement.Align then
begin
Prepare;
Res[GLALtopLeft].X1 := X1;
Res[GLALtopLeft].Y1 := Y1;
Res[GLALtopLeft].X2 := X1 + W;
Res[GLALtopLeft].Y2 := Y1 + H;
end;
if GLALtopRight = ThisElement.Align then
begin
Prepare;
Res[GLALtopRight].X1 := X2 - W;
Res[GLALtopRight].Y1 := Y1;
Res[GLALtopRight].X2 := X2;
Res[GLALtopRight].Y2 := Y1 + H;
end;
if GLALBottomLeft = ThisElement.Align then
begin
Prepare;
Res[GLALBottomLeft].X1 := X1;
Res[GLALBottomLeft].Y1 := Y2 - H;
Res[GLALBottomLeft].X2 := X1 + W;
Res[GLALBottomLeft].Y2 := Y2;
end;
if GLALBottomRight = ThisElement.Align then
begin
Prepare;
Res[GLALBottomRight].X1 := X2 - W;
Res[GLALBottomRight].Y1 := Y2 - H;
Res[GLALBottomRight].X2 := X2;
Res[GLALBottomRight].Y2 := Y2;
end;
end;
Res[GLALtop].X1 := Res[GLALtopLeft].X2;
Res[GLALtop].Y1 := Res[GLALtopRight].Y1;
Res[GLALtop].X2 := Res[GLALtopRight].X1;
Res[GLALtop].Y2 := Res[GLALtopLeft].Y2;
Res[GLALBottom].X1 := Res[GLALBottomLeft].X2;
Res[GLALBottom].Y1 := Res[GLALBottomLeft].Y1;
Res[GLALBottom].X2 := Res[GLALBottomRight].X1;
Res[GLALBottom].Y2 := Res[GLALBottomRight].Y2;
Res[GLALLeft].X1 := Res[GLALtopLeft].X1;
Res[GLALLeft].Y1 := Res[GLALtopLeft].Y2;
Res[GLALLeft].X2 := Res[GLALBottomLeft].X2;
Res[GLALLeft].Y2 := Res[GLALBottomLeft].Y1;
Res[GLALRight].X1 := Res[GLALtopRight].X1;
Res[GLALRight].Y1 := Res[GLALtopRight].Y2;
Res[GLALRight].X2 := Res[GLALBottomRight].X2;
Res[GLALRight].Y2 := Res[GLALBottomRight].Y1;
for XC := 0 to FElements.Count - 1 do
begin
ThisElement := FElements[XC];
if GLALtop = ThisElement.Align then
begin
Prepare;
Res[GLALtop].Y1 := Y1;
Res[GLALtop].Y2 := Y1 + H;
end;
if GLALBottom = ThisElement.Align then
begin
Prepare;
Res[GLALBottom].Y1 := Y2 - H;
Res[GLALBottom].Y2 := Y2;
end;
if GLALLeft = ThisElement.Align then
begin
Prepare;
Res[GLALLeft].X1 := X1;
Res[GLALLeft].X2 := X1 + W;
end;
if GLALRight = ThisElement.Align then
begin
Prepare;
Res[GLALRight].X1 := X2 - W;
Res[GLALRight].X2 := X2;
end;
end;
Res[GLALCenter].X1 := Res[GLALLeft].X2;
Res[GLALCenter].Y1 := Res[GLALtop].Y2;
Res[GLALCenter].X2 := Res[GLALRight].X1;
Res[GLALCenter].Y2 := Res[GLALBottom].Y1;
end;
TexWidth := Material.Texture.TexWidth;
if TexWidth = 0 then
TexWidth := Material.Texture.Image.Width;
TexHeight := Material.Texture.TexHeight;
if TexHeight = 0 then
TexHeight := Material.Texture.Image.Height;
glBegin(GL_QUADS);
for XC := 0 to FElements.Count - 1 do
begin
ThisElement := FElements[XC];
for AlignCount := GLAlTopLeft to GLAlBottomRight do
if (AlignCount = ThisElement.Align) then
begin
if Refresh then
begin
Res[AlignCount].XTiles := ((Res[AlignCount].X2 - Res[AlignCount].X1) /
(ThisElement.FBottomRight.X - ThisElement.FTopLeft.X)) /
ThisElement.Scale.X;
Res[AlignCount].YTiles := ((Res[AlignCount].Y2 - Res[AlignCount].Y1) /
(ThisElement.FBottomRight.Y - ThisElement.FTopLeft.Y)) /
ThisElement.Scale.Y;
end;
RenderIt(Res[AlignCount], ThisElement);
end;
if (GLALBorder = ThisElement.Align) then
begin
RenderBorder(ThisElement);
end;
end;
glEnd;
end;
function TgxGuiComponent.GetOwnerList: TgxGuiComponentList;
begin
Result := GetOwner as TgxGuiComponentList;
end;
function TgxGuiComponent.GetDisplayName: string;
begin
Result := FName;
end;
procedure TgxGuiComponent.SetName(const val: TgxGuiComponentName);
begin
FName := Val;
end;
constructor TgxGuiComponent.Create(Collection: TCollection);
begin
inherited;
FElements := TgxGuiElementList.Create(Self);
end;
destructor TgxGuiComponent.Destroy;
begin
FElements.Free;
inherited;
end;
constructor TgxGuiElementList.Create(AOwner: TgxGuiComponent);
begin
inherited Create(AOwner, TgxGuiElement);
FGuiComponent := AOwner;
end;
function TgxGuiElementList.GetOwner: TPersistent;
begin
Result := FGuiComponent;
end;
procedure TgxGuiElementList.SetItems(index: Integer; const val: TgxGuiElement);
begin
inherited Items[index] := val;
end;
function TgxGuiElementList.IndexOf(const Item: TgxGuiElement): Integer;
var
I: Integer;
begin
Result := -1;
if Count <> 0 then
for I := 0 to Count - 1 do
if GetItems(I) = Item then
begin
Result := I;
Exit;
end;
end;
function TgxGuiElementList.GetItems(index: Integer): TgxGuiElement;
begin
Result := TgxGuiElement(inherited Items[index]);
end;
function TgxGuiElement.GetDisplayName: string;
begin
Result := FName;
end;
procedure TgxGuiElement.SetName(const val: TgxGuiElementName);
begin
FName := Val;
end;
constructor TgxGuiElement.Create(Collection: TCollection);
begin
inherited;
FTopLeft := TgxCoordinates2.CreateInitialized(Self, NullHmgVector, csPoint2D);
FBottomRight := TgxCoordinates2.CreateInitialized(Self, NullHmgVector,
csPoint2D);
FScale := TgxCoordinates2.CreateInitialized(Self, XYHmgVector, csPoint2D);
end;
destructor TgxGuiElement.Destroy;
begin
FTopLeft.Free;
FBottomRight.Free;
FScale.Free;
inherited;
end;
procedure TgxGuiLayout.Notification(AComponent: TComponent;
Operation: TOperation);
begin
if Operation = opRemove then
begin
if AComponent = FBitmapFont then
BitmapFont := nil
else
FGuiComponentList.Remove(AComponent);
end;
NotifyChange(Self); // EG : looks suspicious...
inherited;
end;
procedure TgxGuiComponent.AssignTo(Dest: TPersistent);
begin
if Dest is TgxGuiComponent then
begin
TgxGuiComponent(Dest).Elements.Assign(Elements);
end
else
inherited;
end;
procedure TgxGuiElementList.AssignTo(Dest: TPersistent);
var
i: Integer;
begin
if Dest is TgxGuiElementList then
begin
for i := 0 to Count - 1 do
begin
TgxGuiElementList(Dest).Add.Assign(Items[i]);
end;
end
else
inherited;
end;
procedure TgxGuiElement.AssignTo(Dest: TPersistent);
var
element: TgxGuiElement;
begin
if Dest is TgxGuiElement then
begin
element := TgxGuiElement(Dest);
element.TopLeft.Assign(TopLeft);
element.BottomRight.Assign(BottomRight);
element.Scale.Assign(Scale);
element.Align := Align;
element.Name := Name;
end
else
inherited;
end;
end.
| 412 | 0.853484 | 1 | 0.853484 | game-dev | MEDIA | 0.772542 | game-dev | 0.951883 | 1 | 0.951883 |
chakaz/reflang | 2,362 | tests/enum/empty-enum.gen.hpp | // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// !!! This file is auto-generated by Reflang. !!!
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
#ifndef REFLANG_METADATA_EMPTY_ENUM_GEN_HPP
#define REFLANG_METADATA_EMPTY_ENUM_GEN_HPP
#include <string>
#include "lib/reflang.hpp"
#include "empty-enum.src.hpp"
namespace reflang
{
template <>
struct Enum<EmptyEnum> : public IEnum
{
using EnumType = EmptyEnum;
struct ConstIterator
{
ConstIterator(bool is_last);
EnumType operator*();
ConstIterator& operator++();
ConstIterator operator++(int);
ConstIterator& operator--();
ConstIterator operator--(int);
bool operator==(const ConstIterator& o) const;
bool operator!=(const ConstIterator& o) const;
private:
EnumType value_;
bool last_ = true;
};
struct IteratorContainer
{
ConstIterator begin() const;
ConstIterator end() const;
};
static IteratorContainer Iterate();
static bool TryTranslate(const std::string& s, EnumType& value);
static std::string Translate(EnumType e);
const std::string& GetName() const override;
std::vector<std::string> GetStringValues() const override;
std::vector<int> GetIntValues() const override;
bool TryTranslate(const std::string& value, int& out) override;
bool TryTranslate(int value, std::string& out) override;
};
template <>
struct Enum<EmptyCEnum> : public IEnum
{
using EnumType = EmptyCEnum;
struct ConstIterator
{
ConstIterator(bool is_last);
EnumType operator*();
ConstIterator& operator++();
ConstIterator operator++(int);
ConstIterator& operator--();
ConstIterator operator--(int);
bool operator==(const ConstIterator& o) const;
bool operator!=(const ConstIterator& o) const;
private:
EnumType value_;
bool last_ = true;
};
struct IteratorContainer
{
ConstIterator begin() const;
ConstIterator end() const;
};
static IteratorContainer Iterate();
static bool TryTranslate(const std::string& s, EnumType& value);
static std::string Translate(EnumType e);
const std::string& GetName() const override;
std::vector<std::string> GetStringValues() const override;
std::vector<int> GetIntValues() const override;
bool TryTranslate(const std::string& value, int& out) override;
bool TryTranslate(int value, std::string& out) override;
};
} // namespace reflang
#endif //REFLANG_METADATA_EMPTY_ENUM_GEN_HPP
| 412 | 0.911048 | 1 | 0.911048 | game-dev | MEDIA | 0.170321 | game-dev | 0.895027 | 1 | 0.895027 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.