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
bozimmerman/CoffeeMud
7,632
com/planet_ink/coffee_mud/Abilities/Spells/Spell_PolymorphSelf.java
package com.planet_ink.coffee_mud.Abilities.Spells; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.core.collections.*; import com.planet_ink.coffee_mud.Abilities.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.*; import com.planet_ink.coffee_mud.Behaviors.interfaces.*; import com.planet_ink.coffee_mud.CharClasses.interfaces.*; import com.planet_ink.coffee_mud.Commands.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.*; import com.planet_ink.coffee_mud.Libraries.interfaces.*; import com.planet_ink.coffee_mud.Locales.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.*; import com.planet_ink.coffee_mud.Races.interfaces.*; import java.util.*; /* Copyright 2002-2025 Bo Zimmerman 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. */ public class Spell_PolymorphSelf extends Spell { @Override public String ID() { return "Spell_PolymorphSelf"; } private final static String localizedName = CMLib.lang().L("Polymorph Self"); @Override public String name() { return localizedName; } private final static String localizedStaticDisplay = CMLib.lang().L("(Polymorph Self)"); @Override public String displayText() { return localizedStaticDisplay; } @Override protected int canAffectCode() { return CAN_MOBS; } @Override protected int canTargetCode() { return 0; } @Override public int classificationCode() { return Ability.ACODE_SPELL|Ability.DOMAIN_TRANSMUTATION; } @Override public int abstractQuality() { return Ability.QUALITY_OK_SELF; } @Override public long flags() { return super.flags() | Ability.FLAG_POLYMORPHING; } Race newRace=null; @Override public void affectPhyStats(final Physical affected, final PhyStats affectableStats) { super.affectPhyStats(affected,affectableStats); if(newRace!=null) { if(affected.name().indexOf(' ')>0) affectableStats.setName(L("@x1 called @x2",CMLib.english().startWithAorAn(newRace.name()),affected.name())); else affectableStats.setName(L("@x1 the @x2",affected.name(),newRace.name())); final int oldAdd=affectableStats.weight()-affected.basePhyStats().weight(); newRace.setHeightWeight(affectableStats,'M'); if(oldAdd>0) affectableStats.setWeight(affectableStats.weight()+oldAdd); } } @Override public void affectCharStats(final MOB affected, final CharStats affectableStats) { super.affectCharStats(affected,affectableStats); if(newRace!=null) { final int oldCat=affected.baseCharStats().ageCategory(); if(affectableStats.getMyRace()!=newRace) { affectableStats.getMyRace().unaffectCharStats(affected, affectableStats); affectableStats.setMyRace(newRace); newRace.affectCharStats(affected, affectableStats); } affectableStats.setWearableRestrictionsBitmap(affectableStats.getWearableRestrictionsBitmap()|affectableStats.getMyRace().forbiddenWornBits()); if(affected.baseCharStats().getStat(CharStats.STAT_AGE)>0) affectableStats.setStat(CharStats.STAT_AGE,newRace.getAgingChart()[oldCat]); } } @Override public void unInvoke() { // undo the affects of this spell if(!(affected instanceof MOB)) return; final MOB mob=(MOB)affected; super.unInvoke(); if(canBeUninvoked()) if((mob.location()!=null)&&(!mob.amDead())) mob.location().show(mob,null,CMMsg.MSG_OK_VISUAL,L("<S-NAME> morph(s) back into <S-HIM-HERSELF> again.")); } @Override public void setMiscText(final String newMiscText) { super.setMiscText(newMiscText); if((newMiscText!=null)&&(newMiscText.length()>0)) { newRace=CMClass.findRace(newMiscText); if(newRace != null) { final Physical P=this.affected; if(P instanceof MOB) { final MOB target=(MOB)P; if(target.location()!=null) target.location().show(target,null,CMMsg.MSG_OK_VISUAL,L("<S-NAME> become(s) a @x1!",newRace.name())); target.recoverCharStats(); target.recoverPhyStats(); CMLib.utensils().confirmWearability(target); } } } } @Override public boolean invoke(final MOB mob, final List<String> commands, final Physical givenTarget, final boolean auto, final int asLevel) { if((auto||mob.isMonster())&&((commands.size()<1)||((commands.get(0)).equals(mob.name())))) { commands.clear(); final XVector<Race> V=new XVector<Race>(CMClass.races()); for(int v=V.size()-1;v>=0;v--) { if(!CMath.bset(V.elementAt(v).availabilityCode(),Area.THEME_FANTASY)) V.removeElementAt(v); } if(V.size()>0) commands.add(V.elementAt(CMLib.dice().roll(1,V.size(),-1)).name()); } if(commands.size()==0) { mob.tell(L("You need to specify what to turn yourself into!")); return false; } final String race=CMParms.combine(commands,0); MOB target=mob; if((auto)&&(givenTarget!=null)&&(givenTarget instanceof MOB)) target=(MOB)givenTarget; final Race R=CMClass.getRace(race); if((R==null)||(!CMath.bset(R.availabilityCode(),Area.THEME_FANTASY))) { mob.tell(L("You can't turn yourself into @x1!",CMLib.english().startWithAorAn(race))); return false; } if(target.fetchEffect(this.ID())!=null) { failureTell(mob,target,auto,L("<S-NAME> <S-IS-ARE> already polymorphed."), commands); return false; } if(target.baseCharStats().getMyRace() != target.charStats().getMyRace()) { failureTell(mob,target,auto,L("<S-NAME> <S-IS-ARE> already polymorphed."), commands); return false; } if(!super.invoke(mob,commands,givenTarget,auto,asLevel)) return false; int mobStatTotal=0; for(final int s: CharStats.CODES.BASECODES()) mobStatTotal+=mob.baseCharStats().getStat(s); final MOB fakeMOB=CMClass.getFactoryMOB(); for(final int s: CharStats.CODES.BASECODES()) fakeMOB.baseCharStats().setStat(s,mob.baseCharStats().getStat(s)); fakeMOB.baseCharStats().setMyRace(R); fakeMOB.recoverCharStats(); fakeMOB.recoverPhyStats(); fakeMOB.recoverMaxState(); int fakeStatTotal=0; for(final int s: CharStats.CODES.BASECODES()) fakeStatTotal+=fakeMOB.charStats().getStat(s); fakeMOB.destroy(); final int statDiff=mobStatTotal-fakeStatTotal; boolean success=proficiencyCheck(mob,(statDiff*5),auto); if(success) { invoker=mob; final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?"":L("^S<S-NAME> whisper(s) to <T-NAMESELF> about @x1.^?",CMLib.english().makePlural(R.name()))); if(mob.location().okMessage(mob,msg)) { mob.location().send(mob,msg); if(msg.value()<=0) { newRace=R; mob.location().show(target,null,CMMsg.MSG_OK_VISUAL,L("<S-NAME> become(s) a @x1!",CMLib.english().startWithAorAn(newRace.name()))); success=beneficialAffect(mob,target,asLevel,0)!=null; target.recoverCharStats(); CMLib.utensils().confirmWearability(target); } } } else return beneficialWordsFizzle(mob,target,L("<S-NAME> whisper(s) to <T-NAMESELF>, but the spell fizzles.")); // return whether it worked return success; } }
0
0.91834
1
0.91834
game-dev
MEDIA
0.952641
game-dev
0.97259
1
0.97259
spartanoah/acrimony-client
13,162
net/minecraft/inventory/ContainerEnchantment.java
/* * Decompiled with CFR 0.153-SNAPSHOT (d6f6758-dirty). */ package net.minecraft.inventory; import java.util.List; import java.util.Random; import net.minecraft.enchantment.EnchantmentData; import net.minecraft.enchantment.EnchantmentHelper; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.inventory.Container; import net.minecraft.inventory.ICrafting; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.InventoryBasic; import net.minecraft.inventory.Slot; import net.minecraft.item.EnumDyeColor; import net.minecraft.item.ItemStack; import net.minecraft.stats.StatList; import net.minecraft.util.BlockPos; import net.minecraft.world.World; public class ContainerEnchantment extends Container { public IInventory tableInventory = new InventoryBasic("Enchant", true, 2){ @Override public int getInventoryStackLimit() { return 64; } @Override public void markDirty() { super.markDirty(); ContainerEnchantment.this.onCraftMatrixChanged(this); } }; private World worldPointer; private BlockPos position; private Random rand = new Random(); public int xpSeed; public int[] enchantLevels = new int[3]; public int[] field_178151_h = new int[]{-1, -1, -1}; public ContainerEnchantment(InventoryPlayer playerInv, World worldIn) { this(playerInv, worldIn, BlockPos.ORIGIN); } public ContainerEnchantment(InventoryPlayer playerInv, World worldIn, BlockPos pos) { this.worldPointer = worldIn; this.position = pos; this.xpSeed = playerInv.player.getXPSeed(); this.addSlotToContainer(new Slot(this.tableInventory, 0, 15, 47){ @Override public boolean isItemValid(ItemStack stack) { return true; } @Override public int getSlotStackLimit() { return 1; } }); this.addSlotToContainer(new Slot(this.tableInventory, 1, 35, 47){ @Override public boolean isItemValid(ItemStack stack) { return stack.getItem() == Items.dye && EnumDyeColor.byDyeDamage(stack.getMetadata()) == EnumDyeColor.BLUE; } }); for (int i = 0; i < 3; ++i) { for (int j = 0; j < 9; ++j) { this.addSlotToContainer(new Slot(playerInv, j + i * 9 + 9, 8 + j * 18, 84 + i * 18)); } } for (int k = 0; k < 9; ++k) { this.addSlotToContainer(new Slot(playerInv, k, 8 + k * 18, 142)); } } @Override public void onCraftGuiOpened(ICrafting listener) { super.onCraftGuiOpened(listener); listener.sendProgressBarUpdate(this, 0, this.enchantLevels[0]); listener.sendProgressBarUpdate(this, 1, this.enchantLevels[1]); listener.sendProgressBarUpdate(this, 2, this.enchantLevels[2]); listener.sendProgressBarUpdate(this, 3, this.xpSeed & 0xFFFFFFF0); listener.sendProgressBarUpdate(this, 4, this.field_178151_h[0]); listener.sendProgressBarUpdate(this, 5, this.field_178151_h[1]); listener.sendProgressBarUpdate(this, 6, this.field_178151_h[2]); } @Override public void detectAndSendChanges() { super.detectAndSendChanges(); for (int i = 0; i < this.crafters.size(); ++i) { ICrafting icrafting = (ICrafting)this.crafters.get(i); icrafting.sendProgressBarUpdate(this, 0, this.enchantLevels[0]); icrafting.sendProgressBarUpdate(this, 1, this.enchantLevels[1]); icrafting.sendProgressBarUpdate(this, 2, this.enchantLevels[2]); icrafting.sendProgressBarUpdate(this, 3, this.xpSeed & 0xFFFFFFF0); icrafting.sendProgressBarUpdate(this, 4, this.field_178151_h[0]); icrafting.sendProgressBarUpdate(this, 5, this.field_178151_h[1]); icrafting.sendProgressBarUpdate(this, 6, this.field_178151_h[2]); } } @Override public void updateProgressBar(int id, int data) { if (id >= 0 && id <= 2) { this.enchantLevels[id] = data; } else if (id == 3) { this.xpSeed = data; } else if (id >= 4 && id <= 6) { this.field_178151_h[id - 4] = data; } else { super.updateProgressBar(id, data); } } @Override public void onCraftMatrixChanged(IInventory inventoryIn) { if (inventoryIn == this.tableInventory) { ItemStack itemstack = inventoryIn.getStackInSlot(0); if (itemstack != null && itemstack.isItemEnchantable()) { if (!this.worldPointer.isRemote) { int l = 0; for (int j = -1; j <= 1; ++j) { for (int k = -1; k <= 1; ++k) { if (j == 0 && k == 0 || !this.worldPointer.isAirBlock(this.position.add(k, 0, j)) || !this.worldPointer.isAirBlock(this.position.add(k, 1, j))) continue; if (this.worldPointer.getBlockState(this.position.add(k * 2, 0, j * 2)).getBlock() == Blocks.bookshelf) { ++l; } if (this.worldPointer.getBlockState(this.position.add(k * 2, 1, j * 2)).getBlock() == Blocks.bookshelf) { ++l; } if (k == 0 || j == 0) continue; if (this.worldPointer.getBlockState(this.position.add(k * 2, 0, j)).getBlock() == Blocks.bookshelf) { ++l; } if (this.worldPointer.getBlockState(this.position.add(k * 2, 1, j)).getBlock() == Blocks.bookshelf) { ++l; } if (this.worldPointer.getBlockState(this.position.add(k, 0, j * 2)).getBlock() == Blocks.bookshelf) { ++l; } if (this.worldPointer.getBlockState(this.position.add(k, 1, j * 2)).getBlock() != Blocks.bookshelf) continue; ++l; } } this.rand.setSeed(this.xpSeed); for (int i1 = 0; i1 < 3; ++i1) { this.enchantLevels[i1] = EnchantmentHelper.calcItemStackEnchantability(this.rand, i1, l, itemstack); this.field_178151_h[i1] = -1; if (this.enchantLevels[i1] >= i1 + 1) continue; this.enchantLevels[i1] = 0; } for (int j1 = 0; j1 < 3; ++j1) { List<EnchantmentData> list; if (this.enchantLevels[j1] <= 0 || (list = this.func_178148_a(itemstack, j1, this.enchantLevels[j1])) == null || list.isEmpty()) continue; EnchantmentData enchantmentdata = list.get(this.rand.nextInt(list.size())); this.field_178151_h[j1] = enchantmentdata.enchantmentobj.effectId | enchantmentdata.enchantmentLevel << 8; } this.detectAndSendChanges(); } } else { for (int i = 0; i < 3; ++i) { this.enchantLevels[i] = 0; this.field_178151_h[i] = -1; } } } } @Override public boolean enchantItem(EntityPlayer playerIn, int id) { ItemStack itemstack = this.tableInventory.getStackInSlot(0); ItemStack itemstack1 = this.tableInventory.getStackInSlot(1); int i = id + 1; if (!(itemstack1 != null && itemstack1.stackSize >= i || playerIn.capabilities.isCreativeMode)) { return false; } if (this.enchantLevels[id] > 0 && itemstack != null && (playerIn.experienceLevel >= i && playerIn.experienceLevel >= this.enchantLevels[id] || playerIn.capabilities.isCreativeMode)) { if (!this.worldPointer.isRemote) { boolean flag; List<EnchantmentData> list = this.func_178148_a(itemstack, id, this.enchantLevels[id]); boolean bl = flag = itemstack.getItem() == Items.book; if (list != null) { playerIn.removeExperienceLevel(i); if (flag) { itemstack.setItem(Items.enchanted_book); } for (int j = 0; j < list.size(); ++j) { EnchantmentData enchantmentdata = list.get(j); if (flag) { Items.enchanted_book.addEnchantment(itemstack, enchantmentdata); continue; } itemstack.addEnchantment(enchantmentdata.enchantmentobj, enchantmentdata.enchantmentLevel); } if (!playerIn.capabilities.isCreativeMode) { itemstack1.stackSize -= i; if (itemstack1.stackSize <= 0) { this.tableInventory.setInventorySlotContents(1, null); } } playerIn.triggerAchievement(StatList.field_181739_W); this.tableInventory.markDirty(); this.xpSeed = playerIn.getXPSeed(); this.onCraftMatrixChanged(this.tableInventory); } } return true; } return false; } private List<EnchantmentData> func_178148_a(ItemStack stack, int p_178148_2_, int p_178148_3_) { this.rand.setSeed(this.xpSeed + p_178148_2_); List<EnchantmentData> list = EnchantmentHelper.buildEnchantmentList(this.rand, stack, p_178148_3_); if (stack.getItem() == Items.book && list != null && list.size() > 1) { list.remove(this.rand.nextInt(list.size())); } return list; } public int getLapisAmount() { ItemStack itemstack = this.tableInventory.getStackInSlot(1); return itemstack == null ? 0 : itemstack.stackSize; } @Override public void onContainerClosed(EntityPlayer playerIn) { super.onContainerClosed(playerIn); if (!this.worldPointer.isRemote) { for (int i = 0; i < this.tableInventory.getSizeInventory(); ++i) { ItemStack itemstack = this.tableInventory.getStackInSlotOnClosing(i); if (itemstack == null) continue; playerIn.dropPlayerItemWithRandomChoice(itemstack, false); } } } @Override public boolean canInteractWith(EntityPlayer playerIn) { return this.worldPointer.getBlockState(this.position).getBlock() != Blocks.enchanting_table ? false : playerIn.getDistanceSq((double)this.position.getX() + 0.5, (double)this.position.getY() + 0.5, (double)this.position.getZ() + 0.5) <= 64.0; } @Override public ItemStack transferStackInSlot(EntityPlayer playerIn, int index) { ItemStack itemstack = null; Slot slot = (Slot)this.inventorySlots.get(index); if (slot != null && slot.getHasStack()) { ItemStack itemstack1 = slot.getStack(); itemstack = itemstack1.copy(); if (index == 0) { if (!this.mergeItemStack(itemstack1, 2, 38, true)) { return null; } } else if (index == 1) { if (!this.mergeItemStack(itemstack1, 2, 38, true)) { return null; } } else if (itemstack1.getItem() == Items.dye && EnumDyeColor.byDyeDamage(itemstack1.getMetadata()) == EnumDyeColor.BLUE) { if (!this.mergeItemStack(itemstack1, 1, 2, true)) { return null; } } else { if (((Slot)this.inventorySlots.get(0)).getHasStack() || !((Slot)this.inventorySlots.get(0)).isItemValid(itemstack1)) { return null; } if (itemstack1.hasTagCompound() && itemstack1.stackSize == 1) { ((Slot)this.inventorySlots.get(0)).putStack(itemstack1.copy()); itemstack1.stackSize = 0; } else if (itemstack1.stackSize >= 1) { ((Slot)this.inventorySlots.get(0)).putStack(new ItemStack(itemstack1.getItem(), 1, itemstack1.getMetadata())); --itemstack1.stackSize; } } if (itemstack1.stackSize == 0) { slot.putStack(null); } else { slot.onSlotChanged(); } if (itemstack1.stackSize == itemstack.stackSize) { return null; } slot.onPickupFromSlot(playerIn, itemstack1); } return itemstack; } }
0
0.939757
1
0.939757
game-dev
MEDIA
0.997566
game-dev
0.97419
1
0.97419
microsoft/Sora
8,266
DebugTool/source/DbgPlotViewer/GridAlg.cpp
#include "stdafx.h" #include <assert.h> #include <algorithm> #include "GridAlg.h" using namespace std; #define MAX_SOLUTION 128 GridSolutionSolver::GridSolutionSolver() { _minDataStep = 0.00001; _minPixelStep = 20; _topPixelMargin = 18; _bottomPixelMargin = 15; _maxValue = _maxBeforeSolve = 10.0; _minValue = _minBeforeSolve = 0.0; _bSolved = false; _bMaxMinOptimized = false; } double GridSolutionSolver::Calc10BasedNum(double value, int digit) { assert(value > 0); return pow(10.0, floor(log10(value)-digit)); } double GridSolutionSolver::Ceil(double value1, double value2) { assert(value2 > 0.0); return ceil(value1 / value2) * value2; } double GridSolutionSolver::Floor(double value1, double value2) { assert(value2 > 0.0); return floor(value1 / value2) * value2; } bool GridSolutionSolver::InPixelRange(int pixel) { return (pixel <= (_height - _topPixelMargin)) && (pixel >= _bottomPixelMargin); } void GridSolutionSolver::ForEachDataSize(double dataSize, const std::function<void(double dataStep, double dataValue, int pixelValue)> & func) { double current = Floor(_minValue, dataSize); double upBound = Ceil(_maxValue, dataSize); while(current <= upBound) { int line = (int)(_height / _dataRange * (current - _minValue)); if (InPixelRange(line)) func(dataSize, current, line); current += dataSize; } } bool GridSolutionSolver::CalcSolution(double dataStep, Solution & solution) { int gridCount = 0; int pixelHeight = (int)(_height / _dataRange * dataStep); if (pixelHeight < _minPixelStep) return false; ForEachDataSize(dataStep, [&](double dataStep, double dataValue, int pixelValue){ gridCount++; }); if (gridCount > 0 ) { solution.gridCount = gridCount; solution.pixelHeight = pixelHeight; solution.dataStep = dataStep; return true; } return false; } bool GridSolutionSolver::Solve(double maxValue, double minValue, int height, bool bLog) { if ( _bSolved && (_maxValue == maxValue) && (_minValue == minValue) && (_height == height) && (bLog == bLog) ) { return true; } else { _bMaxMinOptimized = false; _maxValue = maxValue; _minValue = minValue; _height = height; _bLog = bLog; _bSolved = Solve(); return _bSolved; } } bool GridSolutionSolver::SolveWithMaxMinOptimization(double maxBeforeSolve, double minBeforeSolve, double & maxValue, double & minValue, int height, bool bLog) { if (_bMaxMinOptimized && (_maxBeforeSolve == maxBeforeSolve) && (_minBeforeSolve == minBeforeSolve) && (_height == height) && (bLog == bLog)) { maxValue = _maxValue; minValue = _minValue; return true; } else { _height = height; _bLog = bLog; maxValue = _maxBeforeSolve = maxBeforeSolve; minValue = _minBeforeSolve = minBeforeSolve; _bSolved = SolveWithMaxMinOptimization(maxValue, minValue); _bMaxMinOptimized = _bSolved; return _bSolved; } } bool GridSolutionSolver::Solve() { _dataRange = _maxValue - _minValue; double baseDataStep = Calc10BasedNum(_dataRange, 1); Solution solution; Solution solutions[MAX_SOLUTION]; int currentSolutionIdx = 0; double candidates[] = {1.0, 2.0, 5.0, 10.0, 20.0, 50.0}; for (int i = 0; i < sizeof(candidates)/sizeof(*candidates); ++i) { double candidate = candidates[i]; double dataStep = baseDataStep * candidate; if (CalcSolution(dataStep, solution)) { solutions[currentSolutionIdx++] = solution; if (currentSolutionIdx == MAX_SOLUTION) break; } } Solution bestSolution; double minMark; bool bSolutionFound = false; if (currentSolutionIdx > 0) { for (int i = 0; i < currentSolutionIdx; ++i) { if (!bSolutionFound) { bSolutionFound = true; bestSolution = solutions[i]; minMark = SolutionValue(bestSolution.gridCount, bestSolution.pixelHeight); } else { Solution curSolution = solutions[i]; double curMark = SolutionValue(solution.gridCount, solution.pixelHeight); if (curMark < minMark) { bestSolution = curSolution; minMark = curMark; } } } _resultDataStep = bestSolution.dataStep; _result.clear(); ForEachDataSize(_resultDataStep, [this](double dataStep, double dataValue, int pixelValue){ LineInfo lineInfo; lineInfo.dataValue = dataValue; lineInfo.pixelValue = pixelValue; _result.push_back(lineInfo); }); return true; } return false; } bool GridSolutionSolver::SolveWithMaxMinOptimization(double & maxValue, double & minValue) { if ( _height < (_topPixelMargin + _bottomPixelMargin) ) // an empty solution { _result.clear(); _resultDataStep = 0.0; return true; // an empty solution } if (_height < (_minPixelStep * 2 + _topPixelMargin + _bottomPixelMargin)) // an one line solution { return SolveOneLineSolution(); } return SolveMultiLineSolution(maxValue, minValue); // multiline solution } bool GridSolutionSolver::SolveOneLineSolution() { LineInfo lineInfo; lineInfo.dataValue = (_maxValue + _minValue) / 2; lineInfo.pixelValue = _height / 2; _result.clear(); _result.push_back(lineInfo); return true; } bool GridSolutionSolver::SolveMultiLineSolution(double & maxValue, double & minValue) { double dataRange = maxValue - minValue; int gridRegionCount = 3; SolutionWithMaxMinOptimization solutions[MAX_SOLUTION]; int curSolutionIdx = 0; int lastGridRegionCount = -1; double lastdataStepBaseAfterRound = -1.0; while(1) { int gridPixelSize = _height / gridRegionCount; if (gridPixelSize < _minPixelStep) break; double baseDataStep = dataRange * gridPixelSize / _height; double dataStepBaseAfterRound = pow(10.0, ceil(log10(baseDataStep))); if (dataStepBaseAfterRound == lastdataStepBaseAfterRound) { gridRegionCount++; continue; } double factors[] = {1.0, 0.5, 0.2}; for (int iCandidate = 0; iCandidate < sizeof(factors)/sizeof(*factors); ++iCandidate) { double dataStepAfterRound = dataStepBaseAfterRound * factors[iCandidate]; double maxValueRounded = Ceil(maxValue, dataStepAfterRound); double minValueRounded = Floor(minValue, dataStepAfterRound); int actualGridRegionCount = (int)(((maxValueRounded - minValueRounded) / dataStepAfterRound) + 0.5); int pixelHeight = _height / actualGridRegionCount; if (pixelHeight < _minPixelStep) { gridRegionCount++; continue; } SolutionWithMaxMinOptimization solution; solution.maxValue = maxValueRounded; solution.minValue = minValueRounded; solution.gridRegionCount = actualGridRegionCount; solution.dataStep = dataStepAfterRound; solution.gridPixelSize = pixelHeight; solutions[curSolutionIdx++] = solution; if (curSolutionIdx == MAX_SOLUTION) break; } if (curSolutionIdx == MAX_SOLUTION) break; gridRegionCount++; } SolutionWithMaxMinOptimization bestSolution; double mark = 100000.0; bool bSolutionFound = false; for_each(solutions, solutions + curSolutionIdx, [&](const SolutionWithMaxMinOptimization & solution){ if (!bSolutionFound) { bSolutionFound = true; bestSolution = solution; mark = SolutionValue(solution.gridRegionCount - 1, solution.gridPixelSize); return; } double thisMark = SolutionValue(solution.gridRegionCount - 1, solution.gridPixelSize); if (thisMark < mark) { bestSolution = solution; mark = thisMark; } }); if (bSolutionFound) { maxValue = _maxValue = bestSolution.maxValue; minValue = _minValue = bestSolution.minValue; _dataRange = _maxValue - _minValue; _resultDataStep = bestSolution.dataStep; _result.clear(); ForEachDataSize(bestSolution.dataStep, [this](double dataSize, double dataValue, int pixelValue){ LineInfo lineInfo; lineInfo.dataValue = dataValue; lineInfo.pixelValue = pixelValue; this->_result.push_back(lineInfo); }); return true; } return false; } void GridSolutionSolver::ForEachGridLine(const std::function<void(double dataStep, double dataValue, int pixelValue)> & func) { if (!_bSolved) return; for_each(_result.begin(), _result.end(), [this, func](const LineInfo & info){ func(_resultDataStep, info.dataValue, info.pixelValue); }); } double GridSolutionSolver::SolutionValue(double gridCount, double gridSize) { double value = abs(gridCount - 7) + abs(gridSize - 35); if (gridCount == 1) value += 10000; // 1 is very bad return value; }
0
0.84616
1
0.84616
game-dev
MEDIA
0.213643
game-dev
0.969089
1
0.969089
saurabhchalke/RizzRiff
4,853
Assets/Scripts/Game/VelocityEstimator.cs
//======= Copyright (c) Valve Corporation, All rights reserved. =============== // // Purpose: Estimates the velocity of an object based on change in position // //============================================================================= using UnityEngine; using System.Collections; //------------------------------------------------------------------------- public class VelocityEstimator : MonoBehaviour { [Tooltip("How many frames to average over for computing velocity")] public int velocityAverageFrames = 5; [Tooltip("How many frames to average over for computing angular velocity")] public int angularVelocityAverageFrames = 11; public bool estimateOnAwake = false; private Coroutine routine; private int sampleCount; private Vector3[] velocitySamples; private Vector3[] angularVelocitySamples; //------------------------------------------------- public void BeginEstimatingVelocity() { FinishEstimatingVelocity(); routine = StartCoroutine(EstimateVelocityCoroutine()); } //------------------------------------------------- public void FinishEstimatingVelocity() { if (routine != null) { StopCoroutine(routine); routine = null; } } //------------------------------------------------- public Vector3 GetVelocityEstimate() { // Compute average velocity Vector3 velocity = Vector3.zero; int velocitySampleCount = Mathf.Min(sampleCount, velocitySamples.Length); if (velocitySampleCount != 0) { for (int i = 0; i < velocitySampleCount; i++) { velocity += velocitySamples[i]; } velocity *= (1.0f / velocitySampleCount); } return velocity; } //------------------------------------------------- public Vector3 GetAngularVelocityEstimate() { // Compute average angular velocity Vector3 angularVelocity = Vector3.zero; int angularVelocitySampleCount = Mathf.Min(sampleCount, angularVelocitySamples.Length); if (angularVelocitySampleCount != 0) { for (int i = 0; i < angularVelocitySampleCount; i++) { angularVelocity += angularVelocitySamples[i]; } angularVelocity *= (1.0f / angularVelocitySampleCount); } return angularVelocity; } //------------------------------------------------- public Vector3 GetAccelerationEstimate() { Vector3 average = Vector3.zero; for (int i = 2 + sampleCount - velocitySamples.Length; i < sampleCount; i++) { if (i < 2) continue; int first = i - 2; int second = i - 1; Vector3 v1 = velocitySamples[first % velocitySamples.Length]; Vector3 v2 = velocitySamples[second % velocitySamples.Length]; average += v2 - v1; } average *= (1.0f / Time.deltaTime); return average; } //------------------------------------------------- void Awake() { velocitySamples = new Vector3[velocityAverageFrames]; angularVelocitySamples = new Vector3[angularVelocityAverageFrames]; if (estimateOnAwake) { BeginEstimatingVelocity(); } } //------------------------------------------------- private IEnumerator EstimateVelocityCoroutine() { sampleCount = 0; Vector3 previousPosition = transform.position; Quaternion previousRotation = transform.rotation; while (true) { yield return new WaitForEndOfFrame(); float velocityFactor = 1.0f / Time.deltaTime; int v = sampleCount % velocitySamples.Length; int w = sampleCount % angularVelocitySamples.Length; sampleCount++; // Estimate linear velocity velocitySamples[v] = velocityFactor * (transform.position - previousPosition); // Estimate angular velocity Quaternion deltaRotation = transform.rotation * Quaternion.Inverse(previousRotation); float theta = 2.0f * Mathf.Acos(Mathf.Clamp(deltaRotation.w, -1.0f, 1.0f)); if (theta > Mathf.PI) { theta -= 2.0f * Mathf.PI; } Vector3 angularVelocity = new Vector3(deltaRotation.x, deltaRotation.y, deltaRotation.z); if (angularVelocity.sqrMagnitude > 0.0f) { angularVelocity = theta * velocityFactor * angularVelocity.normalized; } angularVelocitySamples[w] = angularVelocity; previousPosition = transform.position; previousRotation = transform.rotation; } } }
0
0.64571
1
0.64571
game-dev
MEDIA
0.615017
game-dev
0.746435
1
0.746435
cyanbun96/qrustyquake
17,246
linux/SDL3/include/SDL3/SDL_scancode.h
/* Simple DirectMedia Layer Copyright (C) 1997-2025 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, 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. */ /** * # CategoryScancode * * Defines keyboard scancodes. * * Please refer to the Best Keyboard Practices document for details on what * this information means and how best to use it. * * https://wiki.libsdl.org/SDL3/BestKeyboardPractices */ #ifndef SDL_scancode_h_ #define SDL_scancode_h_ #include <SDL3/SDL_stdinc.h> /** * The SDL keyboard scancode representation. * * An SDL scancode is the physical representation of a key on the keyboard, * independent of language and keyboard mapping. * * Values of this type are used to represent keyboard keys, among other places * in the `scancode` field of the SDL_KeyboardEvent structure. * * The values in this enumeration are based on the USB usage page standard: * https://usb.org/sites/default/files/hut1_5.pdf * * \since This enum is available since SDL 3.2.0. */ typedef enum SDL_Scancode { SDL_SCANCODE_UNKNOWN = 0, /** * \name Usage page 0x07 * * These values are from usage page 0x07 (USB keyboard page). */ /* @{ */ SDL_SCANCODE_A = 4, SDL_SCANCODE_B = 5, SDL_SCANCODE_C = 6, SDL_SCANCODE_D = 7, SDL_SCANCODE_E = 8, SDL_SCANCODE_F = 9, SDL_SCANCODE_G = 10, SDL_SCANCODE_H = 11, SDL_SCANCODE_I = 12, SDL_SCANCODE_J = 13, SDL_SCANCODE_K = 14, SDL_SCANCODE_L = 15, SDL_SCANCODE_M = 16, SDL_SCANCODE_N = 17, SDL_SCANCODE_O = 18, SDL_SCANCODE_P = 19, SDL_SCANCODE_Q = 20, SDL_SCANCODE_R = 21, SDL_SCANCODE_S = 22, SDL_SCANCODE_T = 23, SDL_SCANCODE_U = 24, SDL_SCANCODE_V = 25, SDL_SCANCODE_W = 26, SDL_SCANCODE_X = 27, SDL_SCANCODE_Y = 28, SDL_SCANCODE_Z = 29, SDL_SCANCODE_1 = 30, SDL_SCANCODE_2 = 31, SDL_SCANCODE_3 = 32, SDL_SCANCODE_4 = 33, SDL_SCANCODE_5 = 34, SDL_SCANCODE_6 = 35, SDL_SCANCODE_7 = 36, SDL_SCANCODE_8 = 37, SDL_SCANCODE_9 = 38, SDL_SCANCODE_0 = 39, SDL_SCANCODE_RETURN = 40, SDL_SCANCODE_ESCAPE = 41, SDL_SCANCODE_BACKSPACE = 42, SDL_SCANCODE_TAB = 43, SDL_SCANCODE_SPACE = 44, SDL_SCANCODE_MINUS = 45, SDL_SCANCODE_EQUALS = 46, SDL_SCANCODE_LEFTBRACKET = 47, SDL_SCANCODE_RIGHTBRACKET = 48, SDL_SCANCODE_BACKSLASH = 49, /**< Located at the lower left of the return * key on ISO keyboards and at the right end * of the QWERTY row on ANSI keyboards. * Produces REVERSE SOLIDUS (backslash) and * VERTICAL LINE in a US layout, REVERSE * SOLIDUS and VERTICAL LINE in a UK Mac * layout, NUMBER SIGN and TILDE in a UK * Windows layout, DOLLAR SIGN and POUND SIGN * in a Swiss German layout, NUMBER SIGN and * APOSTROPHE in a German layout, GRAVE * ACCENT and POUND SIGN in a French Mac * layout, and ASTERISK and MICRO SIGN in a * French Windows layout. */ SDL_SCANCODE_NONUSHASH = 50, /**< ISO USB keyboards actually use this code * instead of 49 for the same key, but all * OSes I've seen treat the two codes * identically. So, as an implementor, unless * your keyboard generates both of those * codes and your OS treats them differently, * you should generate SDL_SCANCODE_BACKSLASH * instead of this code. As a user, you * should not rely on this code because SDL * will never generate it with most (all?) * keyboards. */ SDL_SCANCODE_SEMICOLON = 51, SDL_SCANCODE_APOSTROPHE = 52, SDL_SCANCODE_GRAVE = 53, /**< Located in the top left corner (on both ANSI * and ISO keyboards). Produces GRAVE ACCENT and * TILDE in a US Windows layout and in US and UK * Mac layouts on ANSI keyboards, GRAVE ACCENT * and NOT SIGN in a UK Windows layout, SECTION * SIGN and PLUS-MINUS SIGN in US and UK Mac * layouts on ISO keyboards, SECTION SIGN and * DEGREE SIGN in a Swiss German layout (Mac: * only on ISO keyboards), CIRCUMFLEX ACCENT and * DEGREE SIGN in a German layout (Mac: only on * ISO keyboards), SUPERSCRIPT TWO and TILDE in a * French Windows layout, COMMERCIAL AT and * NUMBER SIGN in a French Mac layout on ISO * keyboards, and LESS-THAN SIGN and GREATER-THAN * SIGN in a Swiss German, German, or French Mac * layout on ANSI keyboards. */ SDL_SCANCODE_COMMA = 54, SDL_SCANCODE_PERIOD = 55, SDL_SCANCODE_SLASH = 56, SDL_SCANCODE_CAPSLOCK = 57, SDL_SCANCODE_F1 = 58, SDL_SCANCODE_F2 = 59, SDL_SCANCODE_F3 = 60, SDL_SCANCODE_F4 = 61, SDL_SCANCODE_F5 = 62, SDL_SCANCODE_F6 = 63, SDL_SCANCODE_F7 = 64, SDL_SCANCODE_F8 = 65, SDL_SCANCODE_F9 = 66, SDL_SCANCODE_F10 = 67, SDL_SCANCODE_F11 = 68, SDL_SCANCODE_F12 = 69, SDL_SCANCODE_PRINTSCREEN = 70, SDL_SCANCODE_SCROLLLOCK = 71, SDL_SCANCODE_PAUSE = 72, SDL_SCANCODE_INSERT = 73, /**< insert on PC, help on some Mac keyboards (but does send code 73, not 117) */ SDL_SCANCODE_HOME = 74, SDL_SCANCODE_PAGEUP = 75, SDL_SCANCODE_DELETE = 76, SDL_SCANCODE_END = 77, SDL_SCANCODE_PAGEDOWN = 78, SDL_SCANCODE_RIGHT = 79, SDL_SCANCODE_LEFT = 80, SDL_SCANCODE_DOWN = 81, SDL_SCANCODE_UP = 82, SDL_SCANCODE_NUMLOCKCLEAR = 83, /**< num lock on PC, clear on Mac keyboards */ SDL_SCANCODE_KP_DIVIDE = 84, SDL_SCANCODE_KP_MULTIPLY = 85, SDL_SCANCODE_KP_MINUS = 86, SDL_SCANCODE_KP_PLUS = 87, SDL_SCANCODE_KP_ENTER = 88, SDL_SCANCODE_KP_1 = 89, SDL_SCANCODE_KP_2 = 90, SDL_SCANCODE_KP_3 = 91, SDL_SCANCODE_KP_4 = 92, SDL_SCANCODE_KP_5 = 93, SDL_SCANCODE_KP_6 = 94, SDL_SCANCODE_KP_7 = 95, SDL_SCANCODE_KP_8 = 96, SDL_SCANCODE_KP_9 = 97, SDL_SCANCODE_KP_0 = 98, SDL_SCANCODE_KP_PERIOD = 99, SDL_SCANCODE_NONUSBACKSLASH = 100, /**< This is the additional key that ISO * keyboards have over ANSI ones, * located between left shift and Z. * Produces GRAVE ACCENT and TILDE in a * US or UK Mac layout, REVERSE SOLIDUS * (backslash) and VERTICAL LINE in a * US or UK Windows layout, and * LESS-THAN SIGN and GREATER-THAN SIGN * in a Swiss German, German, or French * layout. */ SDL_SCANCODE_APPLICATION = 101, /**< windows contextual menu, compose */ SDL_SCANCODE_POWER = 102, /**< The USB document says this is a status flag, * not a physical key - but some Mac keyboards * do have a power key. */ SDL_SCANCODE_KP_EQUALS = 103, SDL_SCANCODE_F13 = 104, SDL_SCANCODE_F14 = 105, SDL_SCANCODE_F15 = 106, SDL_SCANCODE_F16 = 107, SDL_SCANCODE_F17 = 108, SDL_SCANCODE_F18 = 109, SDL_SCANCODE_F19 = 110, SDL_SCANCODE_F20 = 111, SDL_SCANCODE_F21 = 112, SDL_SCANCODE_F22 = 113, SDL_SCANCODE_F23 = 114, SDL_SCANCODE_F24 = 115, SDL_SCANCODE_EXECUTE = 116, SDL_SCANCODE_HELP = 117, /**< AL Integrated Help Center */ SDL_SCANCODE_MENU = 118, /**< Menu (show menu) */ SDL_SCANCODE_SELECT = 119, SDL_SCANCODE_STOP = 120, /**< AC Stop */ SDL_SCANCODE_AGAIN = 121, /**< AC Redo/Repeat */ SDL_SCANCODE_UNDO = 122, /**< AC Undo */ SDL_SCANCODE_CUT = 123, /**< AC Cut */ SDL_SCANCODE_COPY = 124, /**< AC Copy */ SDL_SCANCODE_PASTE = 125, /**< AC Paste */ SDL_SCANCODE_FIND = 126, /**< AC Find */ SDL_SCANCODE_MUTE = 127, SDL_SCANCODE_VOLUMEUP = 128, SDL_SCANCODE_VOLUMEDOWN = 129, /* not sure whether there's a reason to enable these */ /* SDL_SCANCODE_LOCKINGCAPSLOCK = 130, */ /* SDL_SCANCODE_LOCKINGNUMLOCK = 131, */ /* SDL_SCANCODE_LOCKINGSCROLLLOCK = 132, */ SDL_SCANCODE_KP_COMMA = 133, SDL_SCANCODE_KP_EQUALSAS400 = 134, SDL_SCANCODE_INTERNATIONAL1 = 135, /**< used on Asian keyboards, see footnotes in USB doc */ SDL_SCANCODE_INTERNATIONAL2 = 136, SDL_SCANCODE_INTERNATIONAL3 = 137, /**< Yen */ SDL_SCANCODE_INTERNATIONAL4 = 138, SDL_SCANCODE_INTERNATIONAL5 = 139, SDL_SCANCODE_INTERNATIONAL6 = 140, SDL_SCANCODE_INTERNATIONAL7 = 141, SDL_SCANCODE_INTERNATIONAL8 = 142, SDL_SCANCODE_INTERNATIONAL9 = 143, SDL_SCANCODE_LANG1 = 144, /**< Hangul/English toggle */ SDL_SCANCODE_LANG2 = 145, /**< Hanja conversion */ SDL_SCANCODE_LANG3 = 146, /**< Katakana */ SDL_SCANCODE_LANG4 = 147, /**< Hiragana */ SDL_SCANCODE_LANG5 = 148, /**< Zenkaku/Hankaku */ SDL_SCANCODE_LANG6 = 149, /**< reserved */ SDL_SCANCODE_LANG7 = 150, /**< reserved */ SDL_SCANCODE_LANG8 = 151, /**< reserved */ SDL_SCANCODE_LANG9 = 152, /**< reserved */ SDL_SCANCODE_ALTERASE = 153, /**< Erase-Eaze */ SDL_SCANCODE_SYSREQ = 154, SDL_SCANCODE_CANCEL = 155, /**< AC Cancel */ SDL_SCANCODE_CLEAR = 156, SDL_SCANCODE_PRIOR = 157, SDL_SCANCODE_RETURN2 = 158, SDL_SCANCODE_SEPARATOR = 159, SDL_SCANCODE_OUT = 160, SDL_SCANCODE_OPER = 161, SDL_SCANCODE_CLEARAGAIN = 162, SDL_SCANCODE_CRSEL = 163, SDL_SCANCODE_EXSEL = 164, SDL_SCANCODE_KP_00 = 176, SDL_SCANCODE_KP_000 = 177, SDL_SCANCODE_THOUSANDSSEPARATOR = 178, SDL_SCANCODE_DECIMALSEPARATOR = 179, SDL_SCANCODE_CURRENCYUNIT = 180, SDL_SCANCODE_CURRENCYSUBUNIT = 181, SDL_SCANCODE_KP_LEFTPAREN = 182, SDL_SCANCODE_KP_RIGHTPAREN = 183, SDL_SCANCODE_KP_LEFTBRACE = 184, SDL_SCANCODE_KP_RIGHTBRACE = 185, SDL_SCANCODE_KP_TAB = 186, SDL_SCANCODE_KP_BACKSPACE = 187, SDL_SCANCODE_KP_A = 188, SDL_SCANCODE_KP_B = 189, SDL_SCANCODE_KP_C = 190, SDL_SCANCODE_KP_D = 191, SDL_SCANCODE_KP_E = 192, SDL_SCANCODE_KP_F = 193, SDL_SCANCODE_KP_XOR = 194, SDL_SCANCODE_KP_POWER = 195, SDL_SCANCODE_KP_PERCENT = 196, SDL_SCANCODE_KP_LESS = 197, SDL_SCANCODE_KP_GREATER = 198, SDL_SCANCODE_KP_AMPERSAND = 199, SDL_SCANCODE_KP_DBLAMPERSAND = 200, SDL_SCANCODE_KP_VERTICALBAR = 201, SDL_SCANCODE_KP_DBLVERTICALBAR = 202, SDL_SCANCODE_KP_COLON = 203, SDL_SCANCODE_KP_HASH = 204, SDL_SCANCODE_KP_SPACE = 205, SDL_SCANCODE_KP_AT = 206, SDL_SCANCODE_KP_EXCLAM = 207, SDL_SCANCODE_KP_MEMSTORE = 208, SDL_SCANCODE_KP_MEMRECALL = 209, SDL_SCANCODE_KP_MEMCLEAR = 210, SDL_SCANCODE_KP_MEMADD = 211, SDL_SCANCODE_KP_MEMSUBTRACT = 212, SDL_SCANCODE_KP_MEMMULTIPLY = 213, SDL_SCANCODE_KP_MEMDIVIDE = 214, SDL_SCANCODE_KP_PLUSMINUS = 215, SDL_SCANCODE_KP_CLEAR = 216, SDL_SCANCODE_KP_CLEARENTRY = 217, SDL_SCANCODE_KP_BINARY = 218, SDL_SCANCODE_KP_OCTAL = 219, SDL_SCANCODE_KP_DECIMAL = 220, SDL_SCANCODE_KP_HEXADECIMAL = 221, SDL_SCANCODE_LCTRL = 224, SDL_SCANCODE_LSHIFT = 225, SDL_SCANCODE_LALT = 226, /**< alt, option */ SDL_SCANCODE_LGUI = 227, /**< windows, command (apple), meta */ SDL_SCANCODE_RCTRL = 228, SDL_SCANCODE_RSHIFT = 229, SDL_SCANCODE_RALT = 230, /**< alt gr, option */ SDL_SCANCODE_RGUI = 231, /**< windows, command (apple), meta */ SDL_SCANCODE_MODE = 257, /**< I'm not sure if this is really not covered * by any of the above, but since there's a * special SDL_KMOD_MODE for it I'm adding it here */ /* @} *//* Usage page 0x07 */ /** * \name Usage page 0x0C * * These values are mapped from usage page 0x0C (USB consumer page). * * There are way more keys in the spec than we can represent in the * current scancode range, so pick the ones that commonly come up in * real world usage. */ /* @{ */ SDL_SCANCODE_SLEEP = 258, /**< Sleep */ SDL_SCANCODE_WAKE = 259, /**< Wake */ SDL_SCANCODE_CHANNEL_INCREMENT = 260, /**< Channel Increment */ SDL_SCANCODE_CHANNEL_DECREMENT = 261, /**< Channel Decrement */ SDL_SCANCODE_MEDIA_PLAY = 262, /**< Play */ SDL_SCANCODE_MEDIA_PAUSE = 263, /**< Pause */ SDL_SCANCODE_MEDIA_RECORD = 264, /**< Record */ SDL_SCANCODE_MEDIA_FAST_FORWARD = 265, /**< Fast Forward */ SDL_SCANCODE_MEDIA_REWIND = 266, /**< Rewind */ SDL_SCANCODE_MEDIA_NEXT_TRACK = 267, /**< Next Track */ SDL_SCANCODE_MEDIA_PREVIOUS_TRACK = 268, /**< Previous Track */ SDL_SCANCODE_MEDIA_STOP = 269, /**< Stop */ SDL_SCANCODE_MEDIA_EJECT = 270, /**< Eject */ SDL_SCANCODE_MEDIA_PLAY_PAUSE = 271, /**< Play / Pause */ SDL_SCANCODE_MEDIA_SELECT = 272, /* Media Select */ SDL_SCANCODE_AC_NEW = 273, /**< AC New */ SDL_SCANCODE_AC_OPEN = 274, /**< AC Open */ SDL_SCANCODE_AC_CLOSE = 275, /**< AC Close */ SDL_SCANCODE_AC_EXIT = 276, /**< AC Exit */ SDL_SCANCODE_AC_SAVE = 277, /**< AC Save */ SDL_SCANCODE_AC_PRINT = 278, /**< AC Print */ SDL_SCANCODE_AC_PROPERTIES = 279, /**< AC Properties */ SDL_SCANCODE_AC_SEARCH = 280, /**< AC Search */ SDL_SCANCODE_AC_HOME = 281, /**< AC Home */ SDL_SCANCODE_AC_BACK = 282, /**< AC Back */ SDL_SCANCODE_AC_FORWARD = 283, /**< AC Forward */ SDL_SCANCODE_AC_STOP = 284, /**< AC Stop */ SDL_SCANCODE_AC_REFRESH = 285, /**< AC Refresh */ SDL_SCANCODE_AC_BOOKMARKS = 286, /**< AC Bookmarks */ /* @} *//* Usage page 0x0C */ /** * \name Mobile keys * * These are values that are often used on mobile phones. */ /* @{ */ SDL_SCANCODE_SOFTLEFT = 287, /**< Usually situated below the display on phones and used as a multi-function feature key for selecting a software defined function shown on the bottom left of the display. */ SDL_SCANCODE_SOFTRIGHT = 288, /**< Usually situated below the display on phones and used as a multi-function feature key for selecting a software defined function shown on the bottom right of the display. */ SDL_SCANCODE_CALL = 289, /**< Used for accepting phone calls. */ SDL_SCANCODE_ENDCALL = 290, /**< Used for rejecting phone calls. */ /* @} *//* Mobile keys */ /* Add any other keys here. */ SDL_SCANCODE_RESERVED = 400, /**< 400-500 reserved for dynamic keycodes */ SDL_SCANCODE_COUNT = 512 /**< not a key, just marks the number of scancodes for array bounds */ } SDL_Scancode; #endif /* SDL_scancode_h_ */
0
0.784797
1
0.784797
game-dev
MEDIA
0.448843
game-dev
0.580622
1
0.580622
goonstation/goonstation-2016
15,859
code/procs/basketball.dm
proc/bball_nova() set category = "Spells" set name = "B-Ball Nova" set desc = "Causes an eruption of explosive basketballs from your location" var/mob/M = src if(M.stat) boutput(M, "Not when you're incapacitated.") return if(!isturf(M.loc)) return if(!M.bball_spellpower()) return M.verbs -= /proc/bball_nova spawn(300) M.verbs += /proc/bball_nova M.visible_message("<span style=\"color:red\">A swarm of basketballs erupts from [M]!</span>") for(var/turf/T in orange(1, M)) if(!T.density) var/target_dir = get_dir(M.loc, T) var/turf/U = get_edge_target_turf(M, target_dir) new /obj/newmeteor/basketball(my_spawn = T, trg = U) /obj/newmeteor/basketball name = "basketball" icon = 'icons/obj/items.dmi' icon_state = "bball_spin" hits = 6 /proc/showboat_slam(mob/target as mob in oview(6)) set category = "Spells" set name = "Showboat Slam" set desc = "Leap up and slam your target for massive damage" var/mob/M = src if(M.stat) boutput(M, "Not when you're incapacitated.") return if(!isturf(M.loc) || !M.bball_spellpower()) return M.verbs -= /proc/showboat_slam spawn(300) M.verbs += /proc/showboat_slam for(var/obj/item/basketball/B in M.contents) B.item_state = "bball2" M.set_clothing_icon_dirty() M.transforming = 1 M.layer = EFFECTS_LAYER_BASE M.visible_message("<span style=\"color:red\">[M] takes a mighty leap towards the ceiling!</span>") playsound(M.loc, "sound/effects/bionic_sound.ogg", 50) for(var/i = 0, i < 10, i++) M.pixel_y += 4 step_to(M, target) sleep(1) sleep(1) M.pixel_y = 0 M.set_loc(target.loc) M.transforming = 0 M.layer = MOB_LAYER for(var/obj/item/basketball/B in M.contents) B.item_state = "bball" playsound(M.loc, "explosion", 50, 1) var/obj/overlay/O = new/obj/overlay(get_turf(target)) O.anchored = 1 O.name = "Explosion" O.layer = NOLIGHT_EFFECTS_LAYER_BASE O.pixel_x = -17 O.icon = 'icons/effects/hugeexplosion.dmi' O.icon_state = "explosion" spawn(35) qdel(O) for(var/mob/N in AIviewers(M, null)) if(get_dist(N, target) <= 2) if(N != M) N.weakened = max(N.weakened, 5) random_brute_damage(N, 10) if(N.client) shake_camera(N, 6, 5) N.show_message("<span style=\"color:red\">[M] showboat slams [target] to the ground!</span>", 1) random_brute_damage(target, 40) /proc/holy_jam() set category = "Spells" set name = "Holy Jam" set desc = "Powerful jam that blinds surrounding enemies" var/mob/M = src if(M.stat) boutput(M, "Not when you're incapacitated.") return if(!isturf(M.loc) || !M.bball_spellpower()) return M.verbs -= /proc/holy_jam spawn(150) M.verbs += /proc/holy_jam for(var/obj/item/basketball/B in M.contents) B.item_state = "bball2" M.set_clothing_icon_dirty() M.transforming = 1 M.layer = EFFECTS_LAYER_BASE M.visible_message("<span style=\"color:red\">[M] takes a divine leap towards the ceiling!</span>") playsound(M.loc, "sound/effects/heavenly.ogg", 50, 1) for(var/i = 0, i < 10, i++) M.pixel_y += 4 sleep(1) sleep(1) M.pixel_y = 0 M.transforming = 0 M.layer = MOB_LAYER for(var/obj/item/basketball/B in M.contents) B.item_state = "bball" for(var/mob/N in AIviewers(M, null)) if(get_dist(N, M) <= 6) if(N != M) N.apply_flash(30, 5) if(ishuman(N) && istype(N:mutantrace, /datum/mutantrace/zombie)) N.gib() if(N.client) shake_camera(N, 6, 4) N.show_message("<span style=\"color:red\">[M]'s basketball unleashes a brilliant flash of light!</span>", 1) playsound(M.loc, "sound/weapons/flashbang.ogg", 50, 1) proc/blitz_slam() set category = "Spells" set name = "Blitz Slam" set desc="Teleport randomly to a nearby tile." var/mob/M = src if(M.stat) boutput(M, "Not when you're incapacitated.") return var/SPrange = 2 if (M.bball_spellpower()) SPrange = 6 var/list/turfs = new/list() for(var/turf/T in orange(SPrange)) if(istype(T,/turf/space)) continue if(T.density) continue if(T.x>world.maxx-4 || T.x<4) continue //putting them at the edge is dumb if(T.y>world.maxy-4 || T.y<4) continue turfs += T if(!turfs.len) turfs += pick(/turf in orange(6)) var/datum/effects/system/harmless_smoke_spread/smoke = new /datum/effects/system/harmless_smoke_spread() smoke.set_up(10, 0, M.loc) smoke.start() var/turf/picked = pick(turfs) if(!isturf(picked)) return M.set_loc(picked) M.verbs -= /proc/blitz_slam spawn(40) M.verbs += /proc/blitz_slam /proc/clown_jam(mob/living/target as mob in oview(6)) set category = "Spells" set name = "Clown Jam" set desc = "Jams the target into a fat cursed clown" var/mob/M = src if(M.stat) boutput(M, "Not when you're incapacitated.") return var/SPtime = 3000 if (M.bball_spellpower()) SPtime = 900 M.verbs -= /proc/clown_jam spawn(SPtime) M.verbs += /proc/clown_jam for(var/obj/item/basketball/B in M.contents) B.item_state = "bball2" M.set_clothing_icon_dirty() M.transforming = 1 M.layer = EFFECTS_LAYER_BASE M.visible_message("<span style=\"color:red\">[M] comically leaps towards the ceiling!</span>") playsound(M.loc, "sound/effects/bionic_sound.ogg", 50) for(var/i = 0, i < 10, i++) M.pixel_y += 4 M.pixel_x = rand(-4, 4) step_to(M, target) sleep(1) sleep(1) M.pixel_x = 0 M.pixel_y = 0 M.set_loc(target.loc) M.transforming = 0 M.layer = MOB_LAYER for(var/mob/N in AIviewers(M, null)) if(get_dist(N, target) <= 2) if(N != M) N.weakened = max(N.weakened, 5) if(N.client) shake_camera(N, 6, 4) N.show_message("<span style=\"color:red\">[M] clown jams [target]!</span>", 1) for(var/obj/item/basketball/B in M.contents) B.item_state = "bball" playsound(target.loc, "explosion", 50, 1) playsound(target.loc, "sound/items/bikehorn.ogg", 50, 1) var/datum/effects/system/harmless_smoke_spread/smoke = new /datum/effects/system/harmless_smoke_spread() smoke.set_up(5, 0, target.loc) smoke.attach(target) smoke.start() if(target.job != "Clown") boutput(target, "<span style=\"color:red\"><B>You HONK painfully!</B></span>") target.take_brain_damage(80) target.stuttering = 120 target.job = "Clown" target.contract_disease(/datum/ailment/disease/cluwneing_around, null, null, 1) // path, name, strain, bypass resist target.contract_disease(/datum/ailment/disability/clumsy, null, null, 1) // path, name, strain, bypass resist target.nutrition = 9000 target.change_misstep_chance(60) target.unequip_all() if(istype(target, /mob/living/carbon/human)) var/mob/living/carbon/human/cursed = target cursed.equip_if_possible(new /obj/item/clothing/under/gimmick/cursedclown(cursed), cursed.slot_w_uniform) cursed.equip_if_possible(new /obj/item/clothing/shoes/cursedclown_shoes(cursed), cursed.slot_shoes) cursed.equip_if_possible(new /obj/item/clothing/mask/cursedclown_hat(cursed), cursed.slot_wear_mask) cursed.equip_if_possible(new /obj/item/clothing/gloves/cursedclown_gloves(cursed), cursed.slot_gloves) target.real_name = "cluwne" else //The inverse clown principle var/mob/living/carbon/human/H = target if(!istype(H)) return boutput(H, "<span style=\"color:red\"><b>You don't feel very funny.</b></span>") H.take_brain_damage(-120) H.stuttering = 0 H.job = "Lawyer" H.change_misstep_chance(-INFINITY) H.nutrition = 0 for(var/datum/ailment_data/A in H.ailments) if(istype(A.master,/datum/ailment/disability/clumsy)) H.cure_disease(A) var/obj/old_uniform = H.w_uniform var/obj/item/card/id/the_id = H.wear_id if(H.w_uniform && findtext("[H.w_uniform.type]","clown")) H.w_uniform = new /obj/item/clothing/under/suit(H) qdel(old_uniform) if(H.shoes && findtext("[H.shoes.type]","clown")) qdel(H.shoes) H.shoes = new /obj/item/clothing/shoes/black(H) if(the_id && the_id.registered == H.real_name) the_id.assignment = "Lawyer" the_id.name = "[H.real_name]'s ID Card (Lawyer)" H.wear_id = the_id for(var/obj/item/W in H) if (findtext("[W.type]","clown")) H.u_equip(W) if (W) W.set_loc(target.loc) W.dropped(H) W.layer = initial(W.layer) return /proc/chaos_dunk() set category = "Spells" set name = "Chaos Dunk" set desc = "Destroy the entire station with the ultimate slam" var/mob/M = src if(M.stat) boutput(M, "Not when you're incapacitated.") return var/equipped_thing = M.equipped() if(istype(equipped_thing, /obj/item/basketball)) var/obj/item/basketball/BB = equipped_thing if(!BB.payload) boutput(M, __red("This b-ball doesn't have the right heft to it!")) return else //Safety thing to ensure the plutonium core is only good for one dunk var/pl = BB.payload BB.payload = null qdel(pl) else boutput(M, __red("You can't dunk without a b-ball, yo!")) return M.verbs -= /proc/chaos_dunk logTheThing("combat", M, null, "<b>triggers a chaos dunk in [M.loc.loc] ([showCoords(M.x, M.y, M.z)])!</b>") for(var/obj/item/basketball/B in M.contents) B.item_state = "bball2" M.set_clothing_icon_dirty() M.transforming = 1 M.layer = EFFECTS_LAYER_BASE M.visible_message("<span style=\"color:red\">[M] flies through the ceiling!</span>") playsound(M.loc, "sound/effects/bionic_sound.ogg", 50) for(var/i = 0, i < 50, i++) M.pixel_y += 6 M.dir = turn(M.dir, 90) sleep(1) M.layer = 0 var/sound/siren = sound('sound/misc/airraid_loop.ogg') siren.repeat = 1 siren.channel = 5 world << siren command_alert("A massive influx of negative b-ball protons has been detected in [get_area(M)]. A Chaos Dunk is imminent. All personnel currently on [station_name()] have 15 seconds to reach minimum safe distance. This is not a test.") for(var/area/A in world) spawn(0) A.eject = 1 A.updateicon() for(var/mob/N in mobs) spawn(0) shake_camera(N, 120, 2) spawn(0) var/thunder = 70 while(thunder > 0) thunder-- if(prob(15)) world << sound('sound/effects/thunder.ogg', volume = 80) for(var/mob/N in mobs) N.flash(30) sleep(5) sleep(300) playsound(M.loc, "sound/effects/bionic_sound.ogg", 50) M.layer = EFFECTS_LAYER_BASE for(var/i = 0, i < 20, i++) M.pixel_y -= 12 M.dir = turn(M.dir, 90) sleep(1) sleep(1) siren.repeat = 0 siren.status = SOUND_UPDATE siren.channel = 5 world << siren M.visible_message("<span style=\"color:red\">[M] successfully executes a Chaos Dunk!</span>") explosion_new(src, get_turf(M), 1500, 22.78) for(var/area/A in world) spawn(0) A.eject = 0 A.updateicon() /proc/spin() set category = "Spells" set name = "360 Spin" set desc = "Get fools off your back." var/mob/M = src if(!M.bball_spellpower()) return if(M.stat) boutput(M, "Not when you're incapacitated.") return M.transforming = 1 for(var/mob/N in AIviewers(M, null)) if(N.client) N.show_message("<span style=\"color:red\">[M] does a quick spin, knocking you off guard!</span>", 1) if(get_dist(N, M) <= 2) if(N != M) N.stunned = max(N.stunned, 2) M.dir = NORTH sleep(1) M.dir = EAST sleep(1) M.dir = SOUTH sleep(1) M.dir = WEST M.transforming = 0 M.verbs -= /proc/spin spawn(40) M.verbs += /proc/spin /obj/item/bball_uplink name = "station bounced radio" icon = 'icons/obj/device.dmi' icon_state = "radio" var/temp = null var/uses = 4.0 var/selfdestruct = 0.0 var/traitor_frequency = 0.0 var/obj/item/device/radio/origradio = null flags = FPRINT | TABLEPASS| CONDUCT | ONBELT item_state = "radio" throwforce = 5 w_class = 2.0 throw_speed = 4 throw_range = 20 m_amt = 100 /obj/item/bball_uplink/proc/explode() var/turf/location = get_turf(src.loc) location.hotspot_expose(700, 125) explosion(src, location, 0, 0, 2, 4) qdel(src.master) qdel(src) return /obj/item/bball_uplink/attack_self(mob/user as mob) user.machine = src var/dat if (src.selfdestruct) dat = "Self Destructing..." else if (src.temp) dat = "[src.temp]<BR><BR><A href='byond://?src=\ref[src];temp=1'>Clear</A>" else dat = "<B>ZauberTech Baller Uplink Console:</B><BR>" dat += "Tele-Crystals left: [src.uses]<BR>" dat += "<HR>" dat += "<B>Request item:</B><BR>" dat += "<I>Each item costs 1 telecrystal. The number afterwards is the cooldown time.</I><BR>" dat += "<A href='byond://?src=\ref[src];spell_nova=1'>B-Ball Nova</A> (30)<BR>" dat += "<A href='byond://?src=\ref[src];spell_showboat=1'>Showboat Slam</A> (30)<BR>" dat += "<A href='byond://?src=\ref[src];spell_holy=1'>Holy Jam</A> (15)<BR>" dat += "<A href='byond://?src=\ref[src];spell_blink=1'>Blitz Slam</A> (2)<BR>" dat += "<A href='byond://?src=\ref[src];spell_revengeclown=1'>Clown Jam</A> (90)<BR>" // dat += "<A href='byond://?src=\ref[src];spell_summongolem=1'>Summon Basketball Golem</A> (60)<BR>" dat += "<A href='byond://?src=\ref[src];spell_spin=1'>Spin (free)</A> (4)<BR>" dat += "<HR>" if (src.origradio) dat += "<A href='byond://?src=\ref[src];lock=1'>Lock</A><BR>" dat += "<HR>" dat += "<A href='byond://?src=\ref[src];selfdestruct=1'>Self-Destruct</A>" user << browse(dat, "window=radio") onclose(user, "radio") return /obj/item/bball_uplink/Topic(href, href_list) ..() if (usr.stat || usr.restrained()) return var/mob/living/carbon/human/H = usr if (!( istype(H, /mob/living/carbon/human))) return 1 if ((usr.contents.Find(src) || (in_range(src,usr) && istype(src.loc, /turf)))) usr.machine = src if (href_list["spell_nova"]) if (src.uses >= 1) src.uses -= 1 src.temp = "This jam will cause an eruption of explosive basketballs from your location." usr.verbs += /proc/bball_nova if (href_list["spell_showboat"]) if (src.uses >= 1) src.uses -= 1 usr.verbs += /proc/showboat_slam src.temp = "Leap up high above your target and slam them for massive damage." if (href_list["spell_holy"]) if (src.uses >= 1) src.uses -= 1 usr.verbs += /proc/holy_jam src.temp = "A powerful and sacred jam that blinds surrounding enemies." if (href_list["spell_blink"]) if (src.uses >= 1) src.uses -= 1 usr.verbs += /proc/blitz_slam src.temp = "This slam will allow you to teleport randomly at a short distance." if (href_list["spell_revengeclown"]) if (src.uses >= 1) src.uses -= 1 usr.verbs += /proc/clown_jam src.temp = "This unspoken jam bamboozles your target to the extent that they will become an obese, idiotic, horrible, and useless clown." if (href_list["spell_spin"]) usr.verbs += /proc/spin src.temp = "This spell lets you do a 360 spin, knocking down any fools tailing you." /* if (href_list["spell_summongolem"]) if (src.uses >= 1) src.uses -= 1 usr.verbs += /proc/summongolem_bball src.temp = "This zauber allows you to summon a golem.. made of basketballs." */ else if (href_list["lock"] && src.origradio) // presto chango, a regular radio again! (reset the freq too...) usr.machine = null usr << browse(null, "window=radio") var/obj/item/device/radio/T = src.origradio var/obj/item/bball_uplink/R = src R.set_loc(T) T.set_loc(usr) // R.layer = initial(R.layer) R.layer = 0 usr.u_equip(R) usr.put_in_hand_or_drop(T) T.set_frequency(initial(T.frequency)) T.attack_self(usr) return else if (href_list["selfdestruct"]) src.temp = "<A href='byond://?src=\ref[src];selfdestruct2=1'>Self-Destruct</A>" else if (href_list["selfdestruct2"]) src.selfdestruct = 1 spawn (100) explode() return else if (href_list["temp"]) src.temp = null if (istype(src.loc, /mob)) attack_self(src.loc) else for(var/mob/M in viewers(1, src)) if (M.client) src.attack_self(M) return /mob/proc/bball_spellpower() if(!ishuman(src)) return 0 var/mob/living/carbon/human/H = src var/magcount = 0 if (istype(H.w_uniform, /obj/item/clothing/under/jersey)) magcount += 1 for (var/obj/item/basketball/B in usr.contents) magcount += 2 if (magcount >= 3) return 1 return 0
0
0.958393
1
0.958393
game-dev
MEDIA
0.976262
game-dev
0.981235
1
0.981235
michaelliao/warpdb
1,353
src/main/java/com/itranswarp/warpdb/Page.java
package com.itranswarp.warpdb; import java.util.ArrayList; import java.util.List; /** * Represent a Page object using by limit(offset, maxResults). * * @author liaoxuefeng */ public class Page { public static final int DEFAULT_ITEMS_PER_PAGE = 20; public int pageIndex; public int itemsPerPage; public int totalPages; public int totalItems; public boolean isEmpty; public Page() { } public Page(int pageIndex, int itemsPerPage, int totalPages, int totalItems) { this.pageIndex = pageIndex; this.itemsPerPage = itemsPerPage; this.totalPages = totalPages; this.totalItems = totalItems; this.isEmpty = totalItems == 0; } public List<Integer> list(int currentIndex) { int edge = 4; int start = currentIndex - edge; int end = currentIndex + edge; if (start < 1) { start = 1; } if (end > totalPages) { end = totalPages; } List<Integer> list = new ArrayList<>(end - start + 3); if (start >= 2) { list.add(1); } if (start >= 3) { list.add(0); } for (int n = start; n <= end; n++) { list.add(n); } if (end < totalPages) { list.add(0); } return list; } }
0
0.841027
1
0.841027
game-dev
MEDIA
0.215096
game-dev
0.821429
1
0.821429
AionGermany/aion-germany
3,385
AL-Game-5.8/data/scripts/system/handlers/quest/theobomos/_3087DivingForTreasure.java
/** * This file is part of Aion-Lightning <aion-lightning.org>. * * Aion-Lightning 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. * * Aion-Lightning 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 Aion-Lightning. * If not, see <http://www.gnu.org/licenses/>. */ package quest.theobomos; import com.aionemu.gameserver.model.DialogAction; import com.aionemu.gameserver.model.gameobjects.Npc; import com.aionemu.gameserver.model.gameobjects.player.Player; import com.aionemu.gameserver.network.aion.serverpackets.SM_DIALOG_WINDOW; import com.aionemu.gameserver.questEngine.handlers.QuestHandler; import com.aionemu.gameserver.questEngine.model.QuestEnv; import com.aionemu.gameserver.questEngine.model.QuestState; import com.aionemu.gameserver.questEngine.model.QuestStatus; import com.aionemu.gameserver.utils.PacketSendUtility; /** * @author Balthazar */ public class _3087DivingForTreasure extends QuestHandler { private final static int questId = 3087; public _3087DivingForTreasure() { super(questId); } @Override public void register() { qe.registerQuestNpc(798201).addOnQuestStart(questId); qe.registerQuestNpc(798201).addOnTalkEvent(questId); qe.registerQuestNpc(700419).addOnTalkEvent(questId); qe.registerQuestNpc(798144).addOnTalkEvent(questId); } @Override public boolean onDialogEvent(QuestEnv env) { final Player player = env.getPlayer(); final QuestState qs = player.getQuestStateList().getQuestState(questId); int targetId = 0; if (env.getVisibleObject() instanceof Npc) { targetId = ((Npc) env.getVisibleObject()).getNpcId(); } if (qs == null || qs.getStatus() == QuestStatus.NONE) { if (targetId == 798201) { switch (env.getDialog()) { case QUEST_SELECT: { return sendQuestDialog(env, 1011); } default: return sendQuestStartDialog(env); } } } if (qs == null) { return false; } if (qs.getStatus() == QuestStatus.START) { switch (targetId) { case 700419: { switch (env.getDialog()) { case USE_OBJECT: { if (qs.getQuestVarById(0) == 0) { return sendQuestDialog(env, 1352); } } case SETPRO1: { if (player.getInventory().getItemCountByItemId(182208063) == 0) { if (!giveQuestItem(env, 182208063, 1)) { return true; } } qs.setQuestVarById(0, qs.getQuestVarById(0) + 1); qs.setStatus(QuestStatus.REWARD); updateQuestStatus(env); PacketSendUtility.sendPacket(player, new SM_DIALOG_WINDOW(env.getVisibleObject().getObjectId(), 0)); return true; } default: break; } } } } else if (qs.getStatus() == QuestStatus.REWARD) { if (targetId == 798144) { if (env.getDialogId() == DialogAction.SELECT_QUEST_REWARD.id()) { return sendQuestDialog(env, 5); } else { return sendQuestEndDialog(env); } } } return false; } }
0
0.96257
1
0.96257
game-dev
MEDIA
0.970031
game-dev
0.980489
1
0.980489
P3pp3rF1y/AncientWarfare2
10,117
src/main/java/net/shadowmage/ancientwarfare/structure/gui/GuiSoundBlock.java
package net.shadowmage.ancientwarfare.structure.gui; import net.minecraft.client.Minecraft; import net.shadowmage.ancientwarfare.core.container.ContainerBase; import net.shadowmage.ancientwarfare.core.gui.GuiContainerBase; import net.shadowmage.ancientwarfare.core.gui.elements.Button; import net.shadowmage.ancientwarfare.core.gui.elements.Checkbox; import net.shadowmage.ancientwarfare.core.gui.elements.CompositeScrolled; import net.shadowmage.ancientwarfare.core.gui.elements.Label; import net.shadowmage.ancientwarfare.core.gui.elements.Line; import net.shadowmage.ancientwarfare.core.gui.elements.NumberInput; import net.shadowmage.ancientwarfare.core.util.SongPlayData.SongEntry; import net.shadowmage.ancientwarfare.structure.container.ContainerSoundBlock; import net.shadowmage.ancientwarfare.structure.util.BlockSongPlayData; public class GuiSoundBlock extends GuiContainerBase<ContainerSoundBlock> { private CompositeScrolled area; private Checkbox playerEntry; private Checkbox loop; private Checkbox anyTime; private Checkbox day; private Checkbox night; public GuiSoundBlock(ContainerBase container) { super(container, 320, 240); } @Override public void initElements() { //noop } @Override public void setupElements() { clearElements(); int totalHeight = 8; BlockSongPlayData data = getContainer().data; playerEntry = new Checkbox(8, totalHeight, 12, 12, "guistrings.play_on_player_entry") { @Override public void onToggled() { data.setPlayOnPlayerEntry(checked()); loop.setChecked(!checked()); refreshGui(); } }; playerEntry.setChecked(data.getPlayOnPlayerEntry()); addGuiElement(playerEntry); totalHeight += 16; if (playerEntry.checked()) { totalHeight = addPlayerEntryElements(totalHeight); } loop = new Checkbox(8, totalHeight, 12, 12, "guistrings.sound_block.loop") { @Override public void onToggled() { data.setPlayOnPlayerEntry(!checked()); playerEntry.setChecked(!checked()); refreshGui(); } }; loop.setChecked(!data.getPlayOnPlayerEntry()); addGuiElement(loop); totalHeight += 16; if (loop.checked()) { totalHeight = addLoopElements(totalHeight); } totalHeight += 4; anyTime = new Checkbox(10, totalHeight, 12, 12, "guistrings.sound_block.any_time") { @Override public void onToggled() { if (checked()) { data.setTimeOfDay(BlockSongPlayData.TimeOfDay.ANY); day.setChecked(false); night.setChecked(false); } } }; anyTime.setChecked(data.getTimeOfDay() == BlockSongPlayData.TimeOfDay.ANY); addGuiElement(anyTime); day = new Checkbox(74, totalHeight, 12, 12, "guistrings.sound_block.day") { @Override public void onToggled() { if (checked()) { data.setTimeOfDay(BlockSongPlayData.TimeOfDay.DAY); anyTime.setChecked(false); night.setChecked(false); } } }; day.setChecked(data.getTimeOfDay() == BlockSongPlayData.TimeOfDay.DAY); addGuiElement(day); night = new Checkbox(122, totalHeight, 12, 12, "guistrings.sound_block.night") { @Override public void onToggled() { if (checked()) { data.setTimeOfDay(BlockSongPlayData.TimeOfDay.NIGHT); anyTime.setChecked(false); day.setChecked(false); } } }; night.setChecked(data.getTimeOfDay() == BlockSongPlayData.TimeOfDay.NIGHT); addGuiElement(night); totalHeight += 14; Checkbox protectionFlagTurnOff = new Checkbox(8, totalHeight, 16, 16, "guistrings.sound_block.turned_off_by_protection_flag") { @Override public void onToggled() { data.setProtectionFlagTurnOff(checked()); } }; protectionFlagTurnOff.setChecked(data.getProtectionFlagTurnOff()); addGuiElement(protectionFlagTurnOff); totalHeight += 18; Checkbox random = new Checkbox(8, totalHeight, 16, 16, "guistrings.sound_block.play_in_random_order") { @Override public void onToggled() { data.setRandom(checked()); } }; random.setChecked(data.getIsRandom()); addGuiElement(random); totalHeight += 20; addGuiElement(new Label(32, totalHeight + 1, "guistrings.sound_block.sound_range").setShadow(true)); NumberInput soundRange = new NumberInput(8, totalHeight, 22, data.getSoundRange(), this) { @Override public void onValueUpdated(float value) { data.setSoundRange((int) value); } }; soundRange.setIntegerValue(); addGuiElement(soundRange); totalHeight += 14; int areaHeight = addTuneEntries(data, totalHeight); Button newTuneButton = new Button(8, areaHeight, 120, 12, "guistrings.new_tune") { @Override protected void onPressed() { data.addNewEntry(); refreshGui(); } }; area.addGuiElement(newTuneButton); areaHeight += 16; area.setAreaSize(areaHeight); } private int addLoopElements(int totalHeight) { totalHeight += 2; BlockSongPlayData data = getContainer().data; NumberInput minDelay = new NumberInput(74, totalHeight, 28, data.getMinDelay(), this) { @Override public void onValueUpdated(float value) { data.setMinDelay((int) value); } }; minDelay.setIntegerValue(); addGuiElement(minDelay); addGuiElement(new Label(24, totalHeight + 1, "guistrings.min_delay").setShadow(true)); NumberInput maxDelay = new NumberInput(170, totalHeight, 28, data.getMaxDelay(), this) { @Override public void onValueUpdated(float value) { data.setMaxDelay((int) value); } }; maxDelay.setIntegerValue(); addGuiElement(maxDelay); addGuiElement(new Label(116, totalHeight + 1, "guistrings.max_delay").setShadow(true)); totalHeight += 14; NumberInput repetitions = new NumberInput(100, totalHeight + 2, 22, data.getRepetitions(), this) { @Override public void onValueUpdated(float value) { data.setRepetitions((int) value); } }; repetitions.setIntegerValue(); repetitions.setEnabled(data.getLimitedRepetitions()); addGuiElement(repetitions); Checkbox limitedRepetitions = new Checkbox(24, totalHeight, 16, 16, "guistrings.sound_block.stop_after") { @Override public void onToggled() { data.setLimitedRepetitions(checked()); repetitions.setEnabled(checked()); } }; limitedRepetitions.setChecked(data.getLimitedRepetitions()); addGuiElement(limitedRepetitions); addGuiElement(new Label(128, totalHeight + 4, "guistrings.sound_block.repetitions").setShadow(true)); totalHeight += 18; NumberInput limitRange = new NumberInput(184, totalHeight + 2, 22, data.getPlayerRange(), this) { @Override public void onValueUpdated(float value) { data.setPlayerRange((int) value); } }; limitRange.setIntegerValue(); limitRange.setEnabled(data.getWhenInRange()); addGuiElement(limitRange); Checkbox whenInRange = new Checkbox(24, totalHeight, 16, 16, "guistrings.sound_block.play_when_player_less_than") { @Override public void onToggled() { data.setWhenInRange(checked()); limitRange.setEnabled(checked()); } }; whenInRange.setChecked(data.getWhenInRange()); addGuiElement(whenInRange); addGuiElement(new Label(210, totalHeight + 4, "guistrings.sound_block.blocks_away").setShadow(true)); totalHeight += 18; return totalHeight; } private int addPlayerEntryElements(int totalHeight) { totalHeight += 2; BlockSongPlayData data = getContainer().data; addGuiElement(new Label(24, totalHeight + 1, "guistrings.sound_block.range").setShadow(true)); NumberInput playerEntryRange = new NumberInput(60, totalHeight, 22, data.getPlayerRange(), this) { @Override public void onValueUpdated(float value) { data.setPlayerRange((int) value); } }; playerEntryRange.setIntegerValue(); addGuiElement(playerEntryRange); Checkbox onlyOnce = new Checkbox(100, totalHeight - 2, 16, 16, "guistrings.sound_block.only_once") { @Override public void onToggled() { data.setPlayOnce(checked()); } }; onlyOnce.setChecked(data.getPlayOnce()); addGuiElement(onlyOnce); totalHeight += 16; totalHeight += 2; return totalHeight; } private int addTuneEntries(final BlockSongPlayData data, int areaStartY) { area = new CompositeScrolled(this, 0, areaStartY, xSize, ySize - areaStartY); addGuiElement(area); int areaHeight = 4; for (int i = 0; i < data.size(); i++) { areaHeight = addTuneEntry(data.get(i), i, areaHeight); } return areaHeight; } private int addTuneEntry(final SongEntry entry, final int index, int startHeight) { Button input = new Button(8, startHeight, 294, 12, getShortenedName(entry.name())) { @Override public void onPressed() { Minecraft.getMinecraft().displayGuiScreen(new GuiSoundSelect(GuiSoundBlock.this, entry)); refreshGui(); } }; area.addGuiElement(input); startHeight += 14; area.addGuiElement(new Label(8, startHeight + 1, "guistrings.volume").setShadow(true)); NumberInput volume = new NumberInput(50, startHeight, 22, entry.volume(), this) { @Override public void onValueUpdated(float value) { entry.setVolume((int) value); } }; volume.setIntegerValue(); area.addGuiElement(volume); area.addGuiElement(new Button(135, startHeight, 20, 12, "/\\") { @Override protected void onPressed() { final BlockSongPlayData data = getContainer().data; data.decrementEntry(index); refreshGui(); } }); area.addGuiElement(new Button(155, startHeight, 20, 12, "\\/") { @Override protected void onPressed() { final BlockSongPlayData data = getContainer().data; data.incrementEntry(index); refreshGui(); } }); area.addGuiElement(new Button(247, startHeight, 55, 12, "guistrings.delete") { @Override protected void onPressed() { final BlockSongPlayData data = getContainer().data; data.deleteEntry(index); refreshGui(); } }); startHeight += 16; area.addGuiElement(new Line(0, startHeight + 2, xSize, startHeight + 2, 1, 0x000000ff)); startHeight += 5; return startHeight; } private String getShortenedName(String name) { return name.replace("ancientwarfarestructure:auto_load/", "auto:"); } @Override protected boolean onGuiCloseRequested() { getContainer().sendTuneDataToServer(player); return true; } }
0
0.953871
1
0.953871
game-dev
MEDIA
0.84104
game-dev
0.990371
1
0.990371
ProjectIgnis/CardScripts
2,951
official/c98462037.lua
--閃刀姫-アザレア --Sky Striker Ace - Azalea --Scripted by The Razgriz local s,id=GetID() function s.initial_effect(c) c:EnableReviveLimit() c:SetSPSummonOnce(id) --Link Summon procedure Link.AddProcedure(c,aux.FilterBoolFunctionEx(Card.IsAttribute,ATTRIBUTE_LIGHT|ATTRIBUTE_DARK),2,2) --Must be Link Summoned local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE) e1:SetCode(EFFECT_SPSUMMON_CONDITION) e1:SetValue(aux.lnklimit) c:RegisterEffect(e1) --Destroy 1 card on the field local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(id,0)) e2:SetCategory(CATEGORY_DESTROY+CATEGORY_TOGRAVE) e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e2:SetProperty(EFFECT_FLAG_DELAY+EFFECT_FLAG_CARD_TARGET) e2:SetCode(EVENT_SPSUMMON_SUCCESS) e2:SetTarget(s.destg) e2:SetOperation(s.desop) c:RegisterEffect(e2) --Destroy an opponent's monster that battles this card local e3=Effect.CreateEffect(c) e3:SetDescription(aux.Stringid(id,1)) e3:SetCategory(CATEGORY_DESTROY) e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e3:SetCode(EVENT_BATTLE_START) e3:SetRange(LOCATION_MZONE) e3:SetCountLimit(1) e3:SetCondition(s.btcon) e3:SetCost(s.btcost) e3:SetTarget(s.bttg) e3:SetOperation(s.btop) c:RegisterEffect(e3) end s.listed_names={id} function s.destg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsOnField() end if chk==0 then return Duel.IsExistingTarget(nil,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY) local g=Duel.SelectTarget(tp,nil,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,1,nil) Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,1,0,0) Duel.SetPossibleOperationInfo(0,CATEGORY_TOGRAVE,e:GetHandler(),1,0,0) end function s.desop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) and Duel.Destroy(tc,REASON_EFFECT)>0 and c:IsRelateToEffect(e) and Duel.GetMatchingGroupCount(Card.IsSpell,tp,LOCATION_GRAVE,0,nil)<=3 then Duel.BreakEffect() Duel.SendtoGrave(c,REASON_EFFECT) end end function s.btcon(e,tp,eg,ep,ev,re,r,rp) local bc=e:GetHandler():GetBattleTarget() return bc and bc:IsControler(1-tp) end function s.cfilter(c) return c:IsSpell() and c:IsAbleToRemoveAsCost() end function s.btcost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(s.cfilter,tp,LOCATION_GRAVE,0,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE) local g=Duel.SelectMatchingCard(tp,s.cfilter,tp,LOCATION_GRAVE,0,1,1,nil) Duel.Remove(g,POS_FACEUP,REASON_COST) end function s.bttg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end Duel.SetOperationInfo(0,CATEGORY_DESTROY,e:GetHandler():GetBattleTarget(),1,0,0) end function s.btop(e,tp,eg,ep,ev,re,r,rp) local bc=e:GetHandler():GetBattleTarget() if bc:IsRelateToBattle() and bc:IsControler(1-tp) then Duel.Destroy(bc,REASON_EFFECT) end end
0
0.877329
1
0.877329
game-dev
MEDIA
0.993596
game-dev
0.960241
1
0.960241
osgcc/ryzom
2,869
ryzom/tools/leveldesign/georges_convert/mold_elt_type_list.cpp
// Ryzom - MMORPG Framework <http://dev.ryzom.com/projects/ryzom/> // Copyright (C) 2010 Winch Gate Property Limited // // 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/>. #include "stdgeorgesconvert.h" #include "mold_elt_type_list.h" #include "georges_loader.h" #include "form_body_elt.h" #include "type_unit_int_unsigned.h" #include "type_unit_int_signed.h" #include "type_unit_double.h" #include "type_unit_string.h" #include "type_unit_file_name.h" namespace NLOLDGEORGES { ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CMoldEltTypeList::CMoldEltTypeList( CLoader* const _pl, CMoldEltType* const _pmet ) : CMoldEltType( _pl ) { pmet = _pmet; blist = true; benum = pmet->IsEnum(); sxname = pmet->GetName(); } CMoldEltTypeList::~CMoldEltTypeList() { } void CMoldEltTypeList::Load( const CStringEx _sxfullname ) // TODO: Load with parents... { pmet->Load( _sxfullname ); benum = pmet->IsEnum(); sxname = pmet->GetName(); } void CMoldEltTypeList::Load( const CStringEx _sxfullname, const CStringEx _sxdate ) { pmet->Load( _sxfullname, _sxdate ); } CStringEx CMoldEltTypeList::GetFormula() { return( pmet->GetFormula() ); } CStringEx CMoldEltTypeList::Format( const CStringEx _sxvalue ) const { return( pmet->Format( _sxvalue ) ); } CStringEx CMoldEltTypeList::CalculateResult( const CStringEx _sxbasevalue, const CStringEx _sxvalue ) const { return( pmet->CalculateResult( _sxbasevalue, _sxvalue ) ); } CStringEx CMoldEltTypeList::GetDefaultValue() const { return( pmet->GetDefaultValue() ); } unsigned int CMoldEltTypeList::GetType() const { return( pmet->GetType() ); } CStringEx CMoldEltTypeList::GetPredefSubstitute( const CStringEx _sxdesignation ) const { return( pmet->GetPredefSubstitute( _sxdesignation ) ); } CStringEx CMoldEltTypeList::GetPredefDesignation( const CStringEx _sxsubstitute ) const { return( pmet->GetPredefDesignation( _sxsubstitute ) ); } CStringEx CMoldEltTypeList::GetPredefDesignation( const unsigned int _index ) const { return( pmet->GetPredefDesignation( _index ) ); } CMoldElt* CMoldEltTypeList::GetMold() { return( pmet ); } }
0
0.930733
1
0.930733
game-dev
MEDIA
0.223319
game-dev
0.936845
1
0.936845
fuyouawa/MMORPG
1,672
MMORPG/Assets/Scripts/Game/Launch/LaunchController.cs
using System; using QFramework; using Serilog; using UnityEngine; namespace MMORPG.Game { public enum LaunchStatus { InitLog, InitPlugins, InitTool, InitNetwork, InLobby, Playing, ApplicationQuit } public class LaunchController : MonoBehaviour { public FSM<LaunchStatus> FSM = new(); public static LaunchController Instance { get; private set; } private void Awake() { DontDestroyOnLoad(this); Instance = this; } private void Start() { FSM.AddState(LaunchStatus.InitLog, new InitLogState(FSM, this)); FSM.AddState(LaunchStatus.InitPlugins, new InitPluginsState(FSM, this)); FSM.AddState(LaunchStatus.InitTool, new InitToolState(FSM, this)); FSM.AddState(LaunchStatus.InitNetwork, new InitNetworkState(FSM, this)); FSM.AddState(LaunchStatus.InLobby, new InLobbyState(FSM, this)); FSM.AddState(LaunchStatus.Playing, new PlayingState(FSM, this)); FSM.AddState(LaunchStatus.ApplicationQuit, new ApplicationQuitState(FSM, this)); FSM.StartState(LaunchStatus.InitLog); } protected void OnApplicationQuit() { try { FSM.ChangeState(LaunchStatus.ApplicationQuit); } catch (Exception e) { Log.Error(e, "退出程序时出现错误!"); } finally { FSM.Clear(); GameApp.Interface.Deinit(); Log.CloseAndFlush(); } } } }
0
0.643008
1
0.643008
game-dev
MEDIA
0.601962
game-dev
0.884273
1
0.884273
jrbudda/Vivecraft_119
3,135
src/VR/org/vivecraft/gameplay/trackers/RunTracker.java
package org.vivecraft.gameplay.trackers; import org.vivecraft.settings.VRSettings; import net.minecraft.client.Minecraft; import net.minecraft.client.player.LocalPlayer; import net.minecraft.world.phys.Vec3; public class RunTracker extends Tracker { private double direction = 0.0D; private double speed = 0.0D; private Vec3 movedir; public RunTracker(Minecraft mc) { super(mc); } public boolean isActive(LocalPlayer p) { if (Minecraft.getInstance().vrPlayer.getFreeMove() && !Minecraft.getInstance().vrSettings.seated) { if (Minecraft.getInstance().vrSettings.vrFreeMoveMode != VRSettings.FreeMove.RUN_IN_PLACE) { return false; } else if (p != null && p.isAlive()) { if (this.mc.gameMode == null) { return false; } else if (p.isOnGround() || !p.isInWater() && !p.isInLava()) { if (p.onClimbable()) { return false; } else { return !Minecraft.getInstance().bowTracker.isNotched(); } } else { return false; } } else { return false; } } else { return false; } } public double getYaw() { return this.direction; } public double getSpeed() { return this.speed; } public void reset(LocalPlayer player) { this.speed = 0.0D; } public void doProcess(LocalPlayer player) { Vec3 vec3 = this.mc.vrPlayer.vrdata_world_pre.getController(0).getPosition(); Vec3 vec31 = this.mc.vrPlayer.vrdata_world_pre.getController(1).getPosition(); double d0 = this.mc.vr.controllerHistory[0].averageSpeed(0.33D); double d1 = this.mc.vr.controllerHistory[1].averageSpeed(0.33D); if (this.speed > 0.0D) { if (d0 < 0.1D && d1 < 0.1D) { this.speed = 0.0D; return; } } else if (d0 < 0.6D && d1 < 0.6D) { this.speed = 0.0D; return; } if (Math.abs(d0 - d1) > 0.5D) { this.speed = 0.0D; } else { Vec3 vec32 = this.mc.vrPlayer.vrdata_world_pre.getController(0).getDirection().add(this.mc.vrPlayer.vrdata_world_pre.getController(1).getDirection()).scale(0.5D); this.direction = (double)((float)Math.toDegrees(Math.atan2(-vec32.x, vec32.z))); double d2 = (d0 + d1) / 2.0D; this.speed = d2 * 1.0D * 1.3D; if (this.speed > 0.1D) { this.speed = 1.0D; } if (this.speed > 1.0D) { this.speed = (double)1.3F; } } } }
0
0.561007
1
0.561007
game-dev
MEDIA
0.912075
game-dev
0.974489
1
0.974489
joschu/trajopt
21,769
ext/bullet/Demos/OpenGL/GL_DialogDynamicsWorld.cpp
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "GL_DialogDynamicsWorld.h" #include "GL_DialogWindow.h" #include "btBulletDynamicsCommon.h" #include "BulletCollision/CollisionDispatch/btBox2dBox2dCollisionAlgorithm.h" #include "BulletCollision/CollisionDispatch/btConvex2dConvex2dAlgorithm.h" #include "BulletCollision/CollisionShapes/btBox2dShape.h" #include "BulletCollision/CollisionShapes/btConvex2dShape.h" #include "BulletCollision/NarrowPhaseCollision/btMinkowskiPenetrationDepthSolver.h" GL_DialogDynamicsWorld::GL_DialogDynamicsWorld() { m_upperBorder = 0; m_lowerBorder =0; m_pickConstraint = 0; m_screenWidth = 0; m_screenHeight = 0; m_collisionConfiguration = new btDefaultCollisionConfiguration(); m_broadphase = new btDbvtBroadphase(); m_constraintSolver = new btSequentialImpulseConstraintSolver(); m_dispatcher = new btCollisionDispatcher(m_collisionConfiguration); m_dynamicsWorld = new btDiscreteDynamicsWorld(m_dispatcher,m_broadphase,m_constraintSolver,m_collisionConfiguration); m_dynamicsWorld ->getSolverInfo().m_splitImpulse = true; //m_dynamicsWorld->setGravity(btVector3(0,10,0)); m_dynamicsWorld->setGravity(btVector3(0,0,0)); m_simplexSolver = new btVoronoiSimplexSolver(); m_pdSolver = new btMinkowskiPenetrationDepthSolver(); btConvex2dConvex2dAlgorithm::CreateFunc* convexAlgo2d = new btConvex2dConvex2dAlgorithm::CreateFunc(m_simplexSolver,m_pdSolver); m_dispatcher->registerCollisionCreateFunc(CONVEX_2D_SHAPE_PROXYTYPE,CONVEX_2D_SHAPE_PROXYTYPE,convexAlgo2d); m_dispatcher->registerCollisionCreateFunc(BOX_2D_SHAPE_PROXYTYPE,CONVEX_2D_SHAPE_PROXYTYPE,convexAlgo2d); m_dispatcher->registerCollisionCreateFunc(CONVEX_2D_SHAPE_PROXYTYPE,BOX_2D_SHAPE_PROXYTYPE,convexAlgo2d); m_dispatcher->registerCollisionCreateFunc(BOX_2D_SHAPE_PROXYTYPE,BOX_2D_SHAPE_PROXYTYPE,new btBox2dBox2dCollisionAlgorithm::CreateFunc()); ///enable boarders, to avoid 'loosing' menus #if 1 btTransform tr; tr.setIdentity(); { btStaticPlaneShape* plane = new btStaticPlaneShape(btVector3(0,1,0),0); m_upperBorder = new btCollisionObject(); tr.setOrigin(btVector3(0,-BT_LARGE_FLOAT,0)); m_upperBorder->setWorldTransform(tr); m_upperBorder->setCollisionShape(plane); m_dynamicsWorld->addCollisionObject(m_upperBorder); } { btStaticPlaneShape* plane = new btStaticPlaneShape(btVector3(0,-1,0),0); m_lowerBorder = new btCollisionObject(); tr.setIdentity(); tr.setOrigin(btVector3(0,BT_LARGE_FLOAT,0)); m_lowerBorder->setWorldTransform(tr); m_lowerBorder->setCollisionShape(plane); m_dynamicsWorld->addCollisionObject(m_lowerBorder); } { btStaticPlaneShape* plane = new btStaticPlaneShape(btVector3(1,0,0),0); m_leftBorder = new btCollisionObject(); tr.setIdentity(); tr.setOrigin(btVector3(-BT_LARGE_FLOAT,0,0)); m_leftBorder->setWorldTransform(tr); m_leftBorder->setCollisionShape(plane); m_dynamicsWorld->addCollisionObject(m_leftBorder); } { btStaticPlaneShape* plane = new btStaticPlaneShape(btVector3(-1,0,0),0); m_rightBorder = new btCollisionObject(); tr.setIdentity(); tr.setOrigin(btVector3(BT_LARGE_FLOAT,0,0)); m_rightBorder->setWorldTransform(tr); m_rightBorder->setCollisionShape(plane); m_dynamicsWorld->addCollisionObject(m_rightBorder); } #endif } GL_DialogDynamicsWorld::~GL_DialogDynamicsWorld() { delete m_dynamicsWorld; delete m_dispatcher; delete m_constraintSolver; delete m_broadphase; delete m_collisionConfiguration; } void GL_DialogDynamicsWorld::setScreenSize(int width, int height) { int i; for ( i=0;i<m_dynamicsWorld->getCollisionObjectArray().size();i++) { btCollisionObject* colObj = m_dynamicsWorld->getCollisionObjectArray()[i]; btRigidBody* body = btRigidBody::upcast(colObj); if (body) { m_dynamicsWorld->removeRigidBody(body); btVector3 newPos = colObj->getWorldTransform().getOrigin() + btVector3(btScalar(m_screenWidth/2.),btScalar(m_screenHeight/2),btScalar(0))-btVector3(btScalar(width/2.),btScalar(height/2.),btScalar(0)); colObj->getWorldTransform().setOrigin(newPos); m_dynamicsWorld->addRigidBody(body); } else { m_dynamicsWorld->removeCollisionObject(colObj); btVector3 newPos = colObj->getWorldTransform().getOrigin() + btVector3(btScalar(m_screenWidth/2.),btScalar(m_screenHeight/2.),btScalar(0))-btVector3(btScalar(width/2.),btScalar(height/2.),btScalar(0)); colObj->getWorldTransform().setOrigin(newPos); m_dynamicsWorld->addCollisionObject(colObj); } } for ( i=0;i<m_dialogs.size();i++) { m_dialogs[i]->setScreenSize(width,height); } if (width && height) { if (m_upperBorder) { m_dynamicsWorld->removeCollisionObject(m_upperBorder); btTransform tr; tr.setIdentity(); tr.setOrigin(btVector3(btScalar(0),btScalar(-height/2.),btScalar(0.))); m_upperBorder->setWorldTransform(tr); m_dynamicsWorld->addCollisionObject(m_upperBorder); } if (m_lowerBorder) { m_dynamicsWorld->removeCollisionObject(m_lowerBorder); btTransform tr; tr.setIdentity(); tr.setOrigin(btVector3(btScalar(0),btScalar(height/2.),btScalar(0))); m_lowerBorder->setWorldTransform(tr); m_dynamicsWorld->addCollisionObject(m_lowerBorder); } if (m_leftBorder) { m_dynamicsWorld->removeCollisionObject(m_leftBorder); btTransform tr; tr.setIdentity(); tr.setOrigin(btVector3(btScalar(-width/2.),btScalar(0),btScalar(0))); m_leftBorder->setWorldTransform(tr); m_dynamicsWorld->addCollisionObject(m_leftBorder); } if (m_rightBorder) { m_dynamicsWorld->removeCollisionObject(m_rightBorder); btTransform tr; tr.setIdentity(); tr.setOrigin(btVector3(btScalar(width/2.),btScalar(0),btScalar(0))); m_rightBorder->setWorldTransform(tr); m_dynamicsWorld->addCollisionObject(m_rightBorder); } } m_screenWidth = width; m_screenHeight = height; } GL_DialogWindow* GL_DialogDynamicsWorld::createDialog(int horPos,int vertPos,int dialogWidth,int dialogHeight, const char* dialogTitle ) { btBox2dShape* boxShape = new btBox2dShape(btVector3(dialogWidth/2.f,dialogHeight/2.f,0.4f)); btScalar mass = 100.f; btVector3 localInertia; boxShape->calculateLocalInertia(mass,localInertia); btRigidBody::btRigidBodyConstructionInfo rbInfo(mass,0,boxShape,localInertia); btRigidBody* body = new btRigidBody(rbInfo); btTransform trans; trans.setIdentity(); // trans.setOrigin(btVector3(btScalar(horPos-m_screenWidth/2+dialogWidth/2), btScalar(vertPos+m_screenHeight/2.+dialogHeight/2),btScalar(0.))); trans.setOrigin(btVector3(btScalar(horPos-m_screenWidth/2+dialogWidth/2), btScalar(vertPos-m_screenHeight/2.+dialogHeight/2),btScalar(0.))); body->setWorldTransform(trans); body->setDamping(0.999f,0.99f); //body->setActivationState(ISLAND_SLEEPING); body->setLinearFactor(btVector3(1,1,0)); //body->setAngularFactor(btVector3(0,0,1)); body->setAngularFactor(btVector3(0,0,0)); GL_DialogWindow* dialogWindow = new GL_DialogWindow(horPos,vertPos,dialogWidth,dialogHeight,body,dialogTitle); m_dialogs.push_back(dialogWindow); m_dynamicsWorld->addRigidBody(body); return dialogWindow; } GL_SliderControl* GL_DialogDynamicsWorld::createSlider(GL_DialogWindow* dialog, const char* sliderText, btScalar initialFraction) { btBox2dShape* boxShape = new btBox2dShape(btVector3(6.f,6.f,0.4f)); btScalar mass = .1f; btVector3 localInertia; boxShape->calculateLocalInertia(mass,localInertia); btRigidBody::btRigidBodyConstructionInfo rbInfo(mass,0,boxShape,localInertia); btRigidBody* body = new btRigidBody(rbInfo); btTransform trans; trans.setIdentity(); int sliderX = dialog->getDialogHorPos() - m_screenWidth/2 + dialog->getDialogWidth()/2; // int sliderY = dialog->getDialogVertPos() + m_screenHeight/2 + dialog->getDialogHeight()/2 + dialog->getNumControls()*20; int sliderY = dialog->getDialogVertPos() - m_screenHeight/2 + dialog->getDialogHeight()/2 + dialog->getNumControls()*20; trans.setOrigin(btVector3((btScalar)sliderX, (btScalar)sliderY,(btScalar)-0.2f)); body->setWorldTransform(trans); //body->setDamping(0.999,0.99); //body->setActivationState(ISLAND_SLEEPING); body->setLinearFactor(btVector3(1,1,0)); //body->setAngularFactor(btVector3(0,0,1)); body->setAngularFactor(btVector3(0,0,0)); m_dynamicsWorld->addRigidBody(body); body->setCollisionFlags(body->getFlags()|btCollisionObject::CF_NO_CONTACT_RESPONSE); btRigidBody* dialogBody = btRigidBody::upcast(dialog->getCollisionObject()); btAssert(dialogBody); btTransform frameInA; frameInA.setIdentity(); int offsX = -dialog->getDialogWidth()/2 + 16; int offsY = -dialog->getDialogHeight()/2 + dialog->getNumControls()*20 + 36; btVector3 offset(btVector3((btScalar)offsX, (btScalar)offsY, (btScalar)0.2f)); frameInA.setOrigin(offset); btTransform frameInB; frameInB.setIdentity(); //frameInB.setOrigin(-offset/2); // btScalar lowerLimit = 80.f; // btScalar upperLimit = 170.f; btScalar lowerLimit = 141.f; btScalar upperLimit = 227.f; btScalar actualLimit = lowerLimit+initialFraction*(upperLimit-lowerLimit); #if 0 bool useFrameA = false; btGeneric6DofConstraint* constraint = new btGeneric6DofConstraint(*dialogBody,*body,frameInA,frameInB,useFrameA); m_dynamicsWorld->addConstraint(constraint,true); constraint->setLimit(0,lowerLimit,upperLimit); #else btSliderConstraint* sliderConstraint = new btSliderConstraint(*dialogBody,*body,frameInA,frameInB,true);//useFrameA); sliderConstraint->setLowerLinLimit(actualLimit); sliderConstraint->setUpperLinLimit(actualLimit); m_dynamicsWorld->addConstraint(sliderConstraint,true); #endif GL_SliderControl* slider = new GL_SliderControl(sliderText, body,dialog,lowerLimit,upperLimit, sliderConstraint); body->setUserPointer(slider); dialog->addControl(slider); slider->m_fraction = initialFraction; return slider; } GL_ToggleControl* GL_DialogDynamicsWorld::createToggle(GL_DialogWindow* dialog, const char* toggleText) { btBox2dShape* boxShape = new btBox2dShape(btVector3(6.f,6.f,0.4f)); btScalar mass = 0.1f; btVector3 localInertia; boxShape->calculateLocalInertia(mass,localInertia); btRigidBody::btRigidBodyConstructionInfo rbInfo(mass,0,boxShape,localInertia); btRigidBody* body = new btRigidBody(rbInfo); btTransform trans; trans.setIdentity(); int toggleX = dialog->getDialogHorPos() - m_screenWidth/2 + dialog->getDialogWidth()/2; // int toggleY = dialog->getDialogVertPos() + m_screenHeight/2 + dialog->getDialogHeight()/2 + dialog->getNumControls()*20; int toggleY = dialog->getDialogVertPos() - m_screenHeight/2 + dialog->getDialogHeight()/2 + dialog->getNumControls()*20; trans.setOrigin(btVector3((btScalar)toggleX, (btScalar)toggleY,(btScalar) -0.2f)); body->setWorldTransform(trans); body->setDamping(0.999f,0.99f); //body->setActivationState(ISLAND_SLEEPING); body->setLinearFactor(btVector3(1,1,0)); //body->setAngularFactor(btVector3(0,0,1)); body->setAngularFactor(btVector3(0,0,0)); m_dynamicsWorld->addRigidBody(body); body->setCollisionFlags(body->getFlags()|btCollisionObject::CF_NO_CONTACT_RESPONSE); btRigidBody* dialogBody = btRigidBody::upcast(dialog->getCollisionObject()); btAssert(dialogBody); btTransform frameInA; frameInA.setIdentity(); btVector3 offset(btVector3(+dialog->getDialogWidth()/2.f-32.f,-dialog->getDialogHeight()/2.f+dialog->getNumControls()*20.f+36.f,0.2f)); frameInA.setOrigin(offset); btTransform frameInB; frameInB.setIdentity(); //frameInB.setOrigin(-offset/2); bool useFrameA = true; btGeneric6DofConstraint* constraint = new btGeneric6DofConstraint(*dialogBody,*body,frameInA,frameInB,useFrameA); m_dynamicsWorld->addConstraint(constraint,true); GL_ToggleControl* toggle = new GL_ToggleControl(toggleText, body,dialog); body->setUserPointer(toggle); dialog->addControl(toggle); return toggle; } void GL_DialogDynamicsWorld::draw(btScalar timeStep) { if (timeStep) { m_dynamicsWorld->stepSimulation(timeStep); } for (int i=0;i<m_dialogs.size();i++) { m_dialogs[i]->draw(timeStep); } } static btRigidBody* pickedBody = 0;//for deactivation state static btScalar mousePickClamping = 111130.f; //static int gPickingConstraintId = 0; static btVector3 gOldPickingPos; static btVector3 gHitPos(-1,-1,-1); static btScalar gOldPickingDist = 0.f; bool GL_DialogDynamicsWorld::mouseFunc(int button, int state, int x, int y) { if (state == 0) { m_mouseButtons |= 1<<button; } else { m_mouseButtons = 0; } m_mouseOldX = x; m_mouseOldY = y; //printf("button %i, state %i, x=%i,y=%i\n",button,state,x,y); //button 0, state 0 means left mouse down btVector3 rayTo = getRayTo(x,y); switch (button) { case 1: { if (state==0) { #if 0 //apply an impulse if (m_dynamicsWorld) { btCollisionWorld::ClosestRayResultCallback rayCallback(m_cameraPosition,rayTo); m_dynamicsWorld->rayTest(m_cameraPosition,rayTo,rayCallback); if (rayCallback.hasHit()) { btRigidBody* body = btRigidBody::upcast(rayCallback.m_collisionObject); if (body) { body->setActivationState(ACTIVE_TAG); btVector3 impulse = rayTo; impulse.normalize(); float impulseStrength = 10.f; impulse *= impulseStrength; btVector3 relPos = rayCallback.m_hitPointWorld - body->getCenterOfMassPosition(); body->applyImpulse(impulse,relPos); } } } #endif } else { } break; } case 0: { if (state==0) { //add a point to point constraint for picking if (m_dynamicsWorld) { btVector3 rayFrom; if (1)//m_ortho) { rayFrom = rayTo; rayFrom.setZ(-100.f); } //else //{ // rayFrom = m_cameraPosition; //} btCollisionWorld::ClosestRayResultCallback rayCallback(rayFrom,rayTo); m_dynamicsWorld->rayTest(rayFrom,rayTo,rayCallback); if (rayCallback.hasHit()) { btScalar maxPickingClamp = mousePickClamping; btRigidBody* body = (btRigidBody*)btRigidBody::upcast(rayCallback.m_collisionObject); if (body) { bool doPick = true; if (body->getUserPointer()) { ///deal with controls in a special way GL_DialogControl* ctrl = (GL_DialogControl*)body->getUserPointer(); switch(ctrl->getType()) { case GL_TOGGLE_CONTROL: { GL_ToggleControl* toggle = (GL_ToggleControl*) ctrl; toggle->m_active = !toggle->m_active; doPick = false; break; } case GL_SLIDER_CONTROL: { GL_SliderControl* slider = (GL_SliderControl*) ctrl; btTypedConstraint* constraint = slider->getConstraint(); if (constraint->getConstraintType() == SLIDER_CONSTRAINT_TYPE) { btSliderConstraint* sliderConstraint = (btSliderConstraint*) constraint; sliderConstraint->setLowerLinLimit(slider->getLowerLimit()); sliderConstraint->setUpperLinLimit(slider->getUpperLimit()); } maxPickingClamp = 100; } default: { } }; }; if (doPick) { //other exclusions? if (!(body->isStaticObject() || body->isKinematicObject())) { pickedBody = body; pickedBody->setActivationState(DISABLE_DEACTIVATION); btVector3 pickPos = rayCallback.m_hitPointWorld; //printf("pickPos=%f,%f,%f\n",pickPos.getX(),pickPos.getY(),pickPos.getZ()); btVector3 localPivot = body->getCenterOfMassTransform().inverse() * pickPos; btPoint2PointConstraint* p2p = new btPoint2PointConstraint(*body,localPivot); p2p->m_setting.m_impulseClamp = maxPickingClamp; m_dynamicsWorld->addConstraint(p2p); m_pickConstraint = p2p; //save mouse position for dragging gOldPickingPos = rayTo; gHitPos = pickPos; gOldPickingDist = (pickPos-rayFrom).length(); //very weak constraint for picking p2p->m_setting.m_tau = 0.1f; } } return true; } } } } else { if (m_pickConstraint && m_dynamicsWorld) { m_dynamicsWorld->removeConstraint(m_pickConstraint); delete m_pickConstraint; //printf("removed constraint %i",gPickingConstraintId); m_pickConstraint = 0; pickedBody->forceActivationState(ACTIVE_TAG); pickedBody->setDeactivationTime( 0.f ); if (pickedBody->getUserPointer()) { ///deal with controls in a special way GL_DialogControl* ctrl = (GL_DialogControl*)pickedBody->getUserPointer(); if (ctrl->getType()==GL_SLIDER_CONTROL) { GL_SliderControl* sliderControl = (GL_SliderControl*) ctrl; btSliderConstraint* slider = 0; btTypedConstraint* constraint = sliderControl->getConstraint(); if (constraint->getConstraintType() == SLIDER_CONSTRAINT_TYPE) { slider = (btSliderConstraint*)constraint; } if (slider) { btScalar linDepth = slider->getLinearPos(); btScalar lowLim = slider->getLowerLinLimit(); btScalar hiLim = slider->getUpperLinLimit(); slider->setPoweredLinMotor(false); if(linDepth <= lowLim) { slider->setLowerLinLimit(lowLim); slider->setUpperLinLimit(lowLim); } else if(linDepth > hiLim) { slider->setLowerLinLimit(hiLim); slider->setUpperLinLimit(hiLim); } else { slider->setLowerLinLimit(linDepth); slider->setUpperLinLimit(linDepth); } } } } pickedBody = 0; } } break; } default: { } } return false; } btVector3 GL_DialogDynamicsWorld::getRayTo(int x,int y) { float cameraDistance = m_screenHeight/2.f;//m_screenWidth/2;//1.f; btVector3 cameraTargetPosition(0,0,0); btVector3 cameraUp(0,-1,0); if (1)//_ortho) { btScalar aspect; btVector3 extents; if (m_screenWidth> m_screenHeight) { aspect = m_screenWidth / (btScalar)m_screenHeight; extents.setValue(aspect * 1.0f, 1.0f,0); } else { cameraDistance = m_screenWidth/2.f; aspect = m_screenHeight / (btScalar)m_screenWidth; extents.setValue(1.0f, aspect*1.f,0); } extents *= cameraDistance; btVector3 lower = cameraTargetPosition - extents; btVector3 upper = cameraTargetPosition + extents; btScalar u = x / btScalar(m_screenWidth); btScalar v = (m_screenHeight - y) / btScalar(m_screenHeight); btVector3 p(0,0,0); p.setValue( (1.0f - u) * lower.getX() + u * upper.getX(), -((1.0f - v) * lower.getY() + v * upper.getY()), cameraTargetPosition.getZ()); return p; } float top = 1.f; float bottom = -1.f; float nearPlane = 1.f; float tanFov = (top-bottom)*0.5f / nearPlane; float fov = 2 * atanf (tanFov); btVector3 cameraPosition(0,0,-100); btVector3 rayFrom = cameraPosition; btVector3 rayForward = (cameraTargetPosition-cameraPosition); rayForward.normalize(); float farPlane = 10000.f; rayForward*= farPlane; btVector3 rightOffset; btVector3 vertical = cameraUp; btVector3 hor; hor = rayForward.cross(vertical); hor.normalize(); vertical = hor.cross(rayForward); vertical.normalize(); float tanfov = tanf(0.5f*fov); hor *= 2.f * farPlane * tanfov; vertical *= 2.f * farPlane * tanfov; btScalar aspect; if (m_screenWidth > m_screenHeight) { aspect = m_screenWidth / (btScalar)m_screenHeight; hor*=aspect; } else { aspect = m_screenHeight / (btScalar)m_screenWidth; vertical*=aspect; } btVector3 rayToCenter = rayFrom + rayForward; btVector3 dHor = hor * 1.f/float(m_screenWidth); btVector3 dVert = vertical * 1.f/float(m_screenHeight); btVector3 rayTo = rayToCenter - 0.5f * hor + 0.5f * vertical; rayTo += btScalar(x) * dHor; rayTo -= btScalar(y) * dVert; //rayTo += y * dVert; return rayTo; } void GL_DialogDynamicsWorld::mouseMotionFunc(int x,int y) { if (m_pickConstraint) { //move the constraint pivot btPoint2PointConstraint* p2p = static_cast<btPoint2PointConstraint*>(m_pickConstraint); if (p2p) { //keep it at the same picking distance btVector3 newRayTo = getRayTo(x,y); btVector3 rayFrom; btVector3 oldPivotInB = p2p->getPivotInB(); btVector3 newPivotB; if (1)//_ortho) { newPivotB = oldPivotInB; newPivotB.setX(newRayTo.getX()); newPivotB.setY(newRayTo.getY()); } else { //rayFrom = m_cameraPosition; // btVector3 dir = newRayTo-rayFrom; // dir.normalize(); // dir *= gOldPickingDist; // newPivotB = rayFrom + dir; } p2p->setPivotB(newPivotB); } } btScalar dx, dy; dx = btScalar(x) - m_mouseOldX; dy = btScalar(y) - m_mouseOldY; m_mouseOldX = x; m_mouseOldY = y; // updateCamera(); }
0
0.865271
1
0.865271
game-dev
MEDIA
0.902375
game-dev
0.823293
1
0.823293
magefree/mage
1,617
Mage.Sets/src/mage/cards/v/VividGrove.java
package mage.cards.v; import java.util.UUID; import mage.abilities.Ability; import mage.abilities.common.EntersBattlefieldAbility; import mage.abilities.costs.common.RemoveCountersSourceCost; import mage.abilities.effects.common.TapSourceEffect; import mage.abilities.effects.common.counter.AddCountersSourceEffect; import mage.abilities.mana.AnyColorManaAbility; import mage.abilities.mana.GreenManaAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.counters.CounterType; /** * * @author Loki */ public final class VividGrove extends CardImpl { public VividGrove(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.LAND},""); // Vivid Grove enters the battlefield tapped with two charge counters on it. Ability ability = new EntersBattlefieldAbility(new TapSourceEffect(true), false, null, "{this} enters tapped with two charge counters on it.", null); ability.addEffect(new AddCountersSourceEffect(CounterType.CHARGE.createInstance(2))); this.addAbility(ability); // {tap}: Add {G}. this.addAbility(new GreenManaAbility()); // {tap}, Remove a charge counter from Vivid Grove: Add one mana of any color. ability = new AnyColorManaAbility(); ability.addCost(new RemoveCountersSourceCost(CounterType.CHARGE.createInstance(1))); this.addAbility(ability); } private VividGrove(final VividGrove card) { super(card); } @Override public VividGrove copy() { return new VividGrove(this); } }
0
0.933938
1
0.933938
game-dev
MEDIA
0.956322
game-dev
0.993554
1
0.993554
showlab/BYOC
3,859
BlendshapeToolkit/Library/PackageCache/com.unity.visualscripting@1.8.0/Runtime/VisualScripting.Core/Collections/NonNullableList.cs
using System; using System.Collections; using System.Collections.Generic; namespace Unity.VisualScripting { public class NonNullableList<T> : IList<T>, IList { public NonNullableList() { list = new List<T>(); } public NonNullableList(int capacity) { list = new List<T>(capacity); } public NonNullableList(IEnumerable<T> collection) { list = new List<T>(collection); } private readonly List<T> list; public T this[int index] { get { return list[index]; } set { if (value == null) { throw new ArgumentNullException(nameof(value)); } list[index] = value; } } object IList.this[int index] { get { return ((IList)list)[index]; } set { ((IList)list)[index] = value; } } public int Count => list.Count; public bool IsSynchronized => ((ICollection)list).IsSynchronized; public object SyncRoot => ((ICollection)list).SyncRoot; public bool IsReadOnly => false; public bool IsFixedSize => ((IList)list).IsFixedSize; public void CopyTo(Array array, int index) { ((ICollection)list).CopyTo(array, index); } public void Add(T item) { if (item == null) { throw new ArgumentNullException(nameof(item)); } list.Add(item); } public int Add(object value) { return ((IList)list).Add(value); } public void Clear() { list.Clear(); } public bool Contains(object value) { return ((IList)list).Contains(value); } public int IndexOf(object value) { return ((IList)list).IndexOf(value); } public void Insert(int index, object value) { ((IList)list).Insert(index, value); } public void Remove(object value) { ((IList)list).Remove(value); } public bool Contains(T item) { if (item == null) { throw new ArgumentNullException(nameof(item)); } return list.Contains(item); } public void CopyTo(T[] array, int arrayIndex) { list.CopyTo(array, arrayIndex); } public IEnumerator<T> GetEnumerator() { return list.GetEnumerator(); } public int IndexOf(T item) { if (item == null) { throw new ArgumentNullException(nameof(item)); } return list.IndexOf(item); } public void Insert(int index, T item) { if (item == null) { throw new ArgumentNullException(nameof(item)); } list.Insert(index, item); } public bool Remove(T item) { if (item == null) { throw new ArgumentNullException(nameof(item)); } return list.Remove(item); } public void RemoveAt(int index) { list.RemoveAt(index); } IEnumerator IEnumerable.GetEnumerator() { return list.GetEnumerator(); } public void AddRange(IEnumerable<T> collection) { foreach (var item in collection) { Add(item); } } } }
0
0.915791
1
0.915791
game-dev
MEDIA
0.616646
game-dev
0.962251
1
0.962251
OpenGLInsights/OpenGLInsightsCode
2,133
Chapter 18 Hierarchical Depth Culling and Bounding-Box Management on the GPU/core/code/rend/tech/Sorted.boo
namespace kri.rend.tech import System.Collections.Generic #--------- Batch ---------# public struct Batch: # why struct? public e as kri.Entity public va as kri.vb.Array public dict as kri.vb.Dict public bu as kri.shade.Bundle public up as callable() as int public off as int public num as int public def constructor(ent as kri.Entity, vao as kri.vb.Array): e = ent va = vao dict = e.CombinedAttribs off = num = 0 public def draw() as void: nob = up() kri.Ant.Inst.params.activate(e) e.mesh.render(va,bu,dict,off,num,nob,null) #public static cMat = CompMat() public class CompMat( IComparer[of Batch] ): public def Compare(a as Batch, b as Batch) as int: r = a.bu.shader.handle - b.bu.shader.handle return r if r r = a.va.handle - b.va.handle return r public static cMat as IComparer[of Batch] = CompMat() #--------- Sorted batch technique ---------# public abstract class Sorted(General): public static comparer as IComparer[of Batch] = null public final extraDict = kri.vb.Dict() public final butch = List[of Batch]() private tempList = List[of Batch]() private bat as Batch protected def constructor(name as string): super(name) protected virtual def getUpdater(mat as kri.Material) as System.Func[of int]: return do() as int: return 1 protected override def onPass(va as kri.vb.Array, tm as kri.TagMat, bu as kri.shade.Bundle) as void: bat.bu = bu bat.va = va bat.up = getUpdater( tm.mat ) bat.num = tm.num bat.off = tm.off tempList.Add(bat) protected virtual def isGood(ent as kri.Entity) as bool: return true public override def addObject(e as kri.Entity, vd as kri.vb.Dict) as bool: tempList.Clear() bat.dict = e.CombinedAttribs bat.e = e for de in extraDict: bat.dict.Add( de.Key, de.Value ) if super(e,vd): butch.AddRange(tempList) return true return false protected virtual def drawScene() as void: scene = kri.Scene.Current if not scene: return butch.Clear() for e in scene.entities: if isGood(e): addObject(e,null) if comparer: butch.Sort(comparer) for b in butch: b.draw()
0
0.615103
1
0.615103
game-dev
MEDIA
0.303087
game-dev
0.786511
1
0.786511
Sumandora/tarasande
1,539
src/main/java/su/mandora/tarasande/injection/mixin/core/rotation/MixinPlayerEntity.java
package su.mandora.tarasande.injection.mixin.core.rotation; import net.minecraft.client.MinecraftClient; import net.minecraft.entity.EntityType; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.world.World; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import su.mandora.tarasande.feature.rotation.Rotations; import su.mandora.tarasande.feature.rotation.api.Rotation; import su.mandora.tarasande.injection.accessor.ILivingEntity; @Mixin(PlayerEntity.class) public abstract class MixinPlayerEntity extends LivingEntity { protected MixinPlayerEntity(EntityType<? extends LivingEntity> entityType, World world) { super(entityType, world); } @Inject(method = "tickNewAi", at = @At(value = "FIELD", target = "Lnet/minecraft/entity/player/PlayerEntity;headYaw:F")) public void updateHeadRotation(CallbackInfo ci) { Rotation rotation = Rotations.INSTANCE.getFakeRotation(); float yaw = getYaw(); float pitch = getPitch(); //noinspection ConstantValue if ((Object) this == MinecraftClient.getInstance().player && rotation != null) { yaw = rotation.getYaw(); pitch = rotation.getPitch(); } ((ILivingEntity) this).tarasande_setHeadYaw(yaw); ((ILivingEntity) this).tarasande_setHeadPitch(pitch); } }
0
0.802929
1
0.802929
game-dev
MEDIA
0.978525
game-dev
0.880414
1
0.880414
switchports/xash3d-switch
43,181
engine/server/sv_world.c
/* sv_world.c - world query functions Copyright (C) 2008 Uncle Mike 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 "common.h" #include "server.h" #include "const.h" #include "pm_local.h" #include "studio.h" typedef struct moveclip_s { vec3_t boxmins, boxmaxs; // enclose the test object along entire move float *mins, *maxs; // size of the moving object vec3_t mins2, maxs2; // size when clipping against mosnters const float *start, *end; edict_t *passedict; trace_t trace; int type; // move type int flags; // trace flags } moveclip_t; /* =============================================================================== HULL BOXES =============================================================================== */ static hull_t box_hull; static dclipnode_t box_clipnodes[6]; static mplane_t box_planes[6]; /* =================== SV_InitBoxHull Set up the planes and clipnodes so that the six floats of a bounding box can just be stored out and get a proper hull_t structure. =================== */ void SV_InitBoxHull( void ) { int i, side; box_hull.clipnodes = box_clipnodes; box_hull.planes = box_planes; box_hull.firstclipnode = 0; box_hull.lastclipnode = 5; for( i = 0; i < 6; i++ ) { box_clipnodes[i].planenum = i; side = i & 1; box_clipnodes[i].children[side] = CONTENTS_EMPTY; if( i != 5 ) box_clipnodes[i].children[side^1] = i + 1; else box_clipnodes[i].children[side^1] = CONTENTS_SOLID; box_planes[i].type = i>>1; box_planes[i].normal[i>>1] = 1; box_planes[i].signbits = 0; } } /* ==================== StudioPlayerBlend ==================== */ void SV_StudioPlayerBlend( mstudioseqdesc_t *pseqdesc, int *pBlend, float *pPitch ) { // calc up/down pointing *pBlend = (*pPitch * 3); if( *pBlend < pseqdesc->blendstart[0] ) { *pPitch -= pseqdesc->blendstart[0] / 3.0f; *pBlend = 0; } else if( *pBlend > pseqdesc->blendend[0] ) { *pPitch -= pseqdesc->blendend[0] / 3.0f; *pBlend = 255; } else { if( pseqdesc->blendend[0] - pseqdesc->blendstart[0] < 0.1f ) // catch qc error *pBlend = 127; else *pBlend = 255.0f * (*pBlend - pseqdesc->blendstart[0]) / (pseqdesc->blendend[0] - pseqdesc->blendstart[0]); *pPitch = 0; } } /* =================== SV_HullForBox To keep everything totally uniform, bounding boxes are turned into small BSP trees instead of being compared directly. =================== */ hull_t *SV_HullForBox( const vec3_t mins, const vec3_t maxs ) { box_planes[0].dist = maxs[0]; box_planes[1].dist = mins[0]; box_planes[2].dist = maxs[1]; box_planes[3].dist = mins[1]; box_planes[4].dist = maxs[2]; box_planes[5].dist = mins[2]; return &box_hull; } /* ================== SV_HullAutoSelect select the apropriate hull automatically ================== */ hull_t *SV_HullAutoSelect( model_t *model, const vec3_t mins, const vec3_t maxs, const vec3_t size, vec3_t offset ) { float curdiff; float lastdiff = 999; int i, hullNumber = 0; // assume we fail hull_t *hull; // select the hull automatically for( i = 0; i < MAX_MAP_HULLS; i++ ) { curdiff = floor( VectorAvg( size )) - floor( VectorAvg( world.hull_sizes[i] )); curdiff = fabs( curdiff ); if( curdiff < lastdiff ) { hullNumber = i; lastdiff = curdiff; } } // TraceHull stuff hull = &model->hulls[hullNumber]; // calculate an offset value to center the origin // NOTE: never get offset of drawing hull if( !hullNumber ) VectorCopy( hull->clip_mins, offset ); else VectorSubtract( hull->clip_mins, mins, offset ); return hull; } /* ================== SV_HullForBsp forcing to select BSP hull ================== */ hull_t *SV_HullForBsp( edict_t *ent, const vec3_t mins, const vec3_t maxs, float *offset ) { hull_t *hull; model_t *model; vec3_t size; // decide which clipping hull to use, based on the size model = Mod_Handle( ent->v.modelindex ); if( !model || model->type != mod_brush ) { Host_MapDesignError( "Entity %i SOLID_BSP with a non bsp model %i\n", NUM_FOR_EDICT( ent ), (model) ? model->type : mod_bad ); return NULL; } VectorSubtract( maxs, mins, size ); #ifdef RANDOM_HULL_NULLIZATION // author: The FiEctro hull = &model->hulls[Com_RandomLong( 0, 0 )]; #endif if( sv_quakehulls->integer == 1 ) { // Using quake-style hull select for my Quake remake if( size[0] < 3.0f || ( model->flags & MODEL_LIQUID && ent->v.solid != SOLID_TRIGGER )) hull = &model->hulls[0]; else if( size[0] <= 32.0f ) hull = &model->hulls[1]; else hull = &model->hulls[2]; VectorSubtract( hull->clip_mins, mins, offset ); } else if( sv_quakehulls->integer == 2 ) { // undocumented feature: auto hull select hull = SV_HullAutoSelect( model, mins, maxs, size, offset ); } else { if( size[0] <= 8.0f || ( model->flags & MODEL_LIQUID && ent->v.solid != SOLID_TRIGGER )) { hull = &model->hulls[0]; VectorCopy( hull->clip_mins, offset ); } else { if( size[0] <= 36.0f ) { if( size[2] <= 36.0f ) hull = &model->hulls[3]; else hull = &model->hulls[1]; } else hull = &model->hulls[2]; VectorSubtract( hull->clip_mins, mins, offset ); } } VectorAdd( offset, ent->v.origin, offset ); return hull; } /* ================ SV_HullForEntity Returns a hull that can be used for testing or clipping an object of mins/maxs size. Offset is filled in to contain the adjustment that must be added to the testing object's origin to get a point to use with the returned hull. ================ */ hull_t *SV_HullForEntity( edict_t *ent, vec3_t mins, vec3_t maxs, vec3_t offset ) { hull_t *hull; vec3_t hullmins, hullmaxs; if( ent->v.solid == SOLID_BSP ) { if( ent->v.movetype != MOVETYPE_PUSH && ent->v.movetype != MOVETYPE_PUSHSTEP ) { Host_MapDesignError( "'%s' has SOLID_BSP without MOVETYPE_PUSH or MOVETYPE_PUSHSTEP\n", SV_ClassName( ent ) ); } hull = SV_HullForBsp( ent, mins, maxs, offset ); } else { // create a temp hull from bounding box sizes VectorSubtract( ent->v.mins, maxs, hullmins ); VectorSubtract( ent->v.maxs, mins, hullmaxs ); hull = SV_HullForBox( hullmins, hullmaxs ); VectorCopy( ent->v.origin, offset ); } return hull; } /* ==================== SV_HullForStudioModel ==================== */ hull_t *SV_HullForStudioModel( edict_t *ent, vec3_t mins, vec3_t maxs, vec3_t offset, int *numhitboxes ) { int isPointTrace; float scale = 0.5f; hull_t *hull = NULL; vec3_t size; model_t *mod; if(( mod = Mod_Handle( ent->v.modelindex )) == NULL ) { *numhitboxes = 1; return SV_HullForEntity( ent, mins, maxs, offset ); } VectorSubtract( maxs, mins, size ); isPointTrace = false; if( VectorIsNull( size ) && !( svgame.globals->trace_flags & FTRACE_SIMPLEBOX )) { isPointTrace = true; if( ent->v.flags & ( FL_CLIENT|FL_FAKECLIENT )) { if( sv_clienttrace->value == 0.0f ) { // so no way to trace studiomodels by hitboxes // use bbox instead isPointTrace = false; } else { scale = sv_clienttrace->value * 0.5f; VectorSet( size, 1.0f, 1.0f, 1.0f ); } } } if( mod->flags & STUDIO_TRACE_HITBOX || isPointTrace ) { VectorScale( size, scale, size ); VectorClear( offset ); if( ent->v.flags & ( FL_CLIENT|FL_FAKECLIENT )) { studiohdr_t *pstudio; mstudioseqdesc_t *pseqdesc; byte controller[4]; byte blending[2]; vec3_t angles; int iBlend; pstudio = Mod_Extradata( mod ); pseqdesc = (mstudioseqdesc_t *)((byte *)pstudio + pstudio->seqindex) + ent->v.sequence; VectorCopy( ent->v.angles, angles ); SV_StudioPlayerBlend( pseqdesc, &iBlend, &angles[PITCH] ); controller[0] = controller[1] = 0x7F; controller[2] = controller[3] = 0x7F; blending[0] = (byte)iBlend; blending[1] = 0; hull = Mod_HullForStudio( mod, ent->v.frame, ent->v.sequence, angles, ent->v.origin, size, controller, blending, numhitboxes, ent ); } else { hull = Mod_HullForStudio( mod, ent->v.frame, ent->v.sequence, ent->v.angles, ent->v.origin, size, ent->v.controller, ent->v.blending, numhitboxes, ent ); } } if( hull ) return hull; *numhitboxes = 1; return SV_HullForEntity( ent, mins, maxs, offset ); } /* =============================================================================== ENTITY AREA CHECKING =============================================================================== */ static int iTouchLinkSemaphore = 0; // prevent recursion when SV_TouchLinks is active areanode_t sv_areanodes[AREA_NODES]; static int sv_numareanodes; /* =============== SV_CreateAreaNode builds a uniformly subdivided tree for the given world size =============== */ areanode_t *SV_CreateAreaNode( int depth, vec3_t mins, vec3_t maxs ) { areanode_t *anode; vec3_t size; vec3_t mins1, maxs1; vec3_t mins2, maxs2; anode = &sv_areanodes[sv_numareanodes++]; ClearLink( &anode->trigger_edicts ); ClearLink( &anode->solid_edicts ); ClearLink( &anode->water_edicts ); if( depth == AREA_DEPTH ) { anode->axis = -1; anode->children[0] = anode->children[1] = NULL; return anode; } VectorSubtract( maxs, mins, size ); if( size[0] > size[1] ) anode->axis = 0; else anode->axis = 1; anode->dist = 0.5f * ( maxs[anode->axis] + mins[anode->axis] ); VectorCopy( mins, mins1 ); VectorCopy( mins, mins2 ); VectorCopy( maxs, maxs1 ); VectorCopy( maxs, maxs2 ); maxs1[anode->axis] = mins2[anode->axis] = anode->dist; anode->children[0] = SV_CreateAreaNode( depth+1, mins2, maxs2 ); anode->children[1] = SV_CreateAreaNode( depth+1, mins1, maxs1 ); return anode; } /* =============== SV_ClearWorld =============== */ void SV_ClearWorld( void ) { int i; SV_InitBoxHull(); // for box testing // clear lightstyles for( i = 0; i < MAX_LIGHTSTYLES; i++ ) { sv.lightstyles[i].value = 256.0f; sv.lightstyles[i].time = 0.0f; } Q_memset( sv_areanodes, 0, sizeof( sv_areanodes )); iTouchLinkSemaphore = 0; sv_numareanodes = 0; SV_CreateAreaNode( 0, sv.worldmodel->mins, sv.worldmodel->maxs ); } /* =============== SV_UnlinkEdict =============== */ void SV_UnlinkEdict( edict_t *ent ) { // not linked in anywhere if( !ent->area.prev ) return; RemoveLink( &ent->area ); ent->area.prev = NULL; ent->area.next = NULL; } /* ==================== SV_TouchLinks ==================== */ void SV_TouchLinks( edict_t *ent, areanode_t *node ) { link_t *l, *next; edict_t *touch; hull_t *hull; vec3_t test, offset; // touch linked edicts for( l = node->trigger_edicts.next; l != &node->trigger_edicts; l = next ) { next = l->next; touch = (edict_t *)((byte *)l - ADDRESS_OF_AREA); if( svgame.physFuncs.SV_TriggerTouch != NULL ) { // user dll can override trigger checking (Xash3D extension) if( !svgame.physFuncs.SV_TriggerTouch( ent, touch )) continue; } else { if( touch == ent || touch->v.solid != SOLID_TRIGGER ) // disabled ? continue; if( touch->v.groupinfo && ent->v.groupinfo ) { if(( !svs.groupop && !(touch->v.groupinfo & ent->v.groupinfo)) || (svs.groupop == 1 && (touch->v.groupinfo & ent->v.groupinfo))) continue; } if( !BoundsIntersect( ent->v.absmin, ent->v.absmax, touch->v.absmin, touch->v.absmax )) continue; // check brush triggers accuracy if( Mod_GetType( touch->v.modelindex ) == mod_brush ) { model_t *mod = Mod_Handle( touch->v.modelindex ); // force to select bsp-hull hull = SV_HullForBsp( touch, ent->v.mins, ent->v.maxs, offset ); // support for rotational triggers if(( mod->flags & MODEL_HAS_ORIGIN ) && !VectorIsNull( touch->v.angles )) { matrix4x4 matrix; Matrix4x4_CreateFromEntity( matrix, touch->v.angles, offset, 1.0f ); Matrix4x4_VectorITransform( matrix, ent->v.origin, test ); } else { // offset the test point appropriately for this hull. VectorSubtract( ent->v.origin, offset, test ); } // test hull for intersection with this model if( PM_HullPointContents( hull, hull->firstclipnode, test ) != CONTENTS_SOLID ) continue; } } // never touch the triggers when "playersonly" is active if( !( sv.hostflags & SVF_PLAYERSONLY )) { svgame.globals->time = sv.time; svgame.dllFuncs.pfnTouch( touch, ent ); } } // recurse down both sides if( node->axis == -1 ) return; if( ent->v.absmax[node->axis] > node->dist ) SV_TouchLinks( ent, node->children[0] ); if( ent->v.absmin[node->axis] < node->dist ) SV_TouchLinks( ent, node->children[1] ); } /* =============== SV_FindTouchedLeafs =============== */ void SV_FindTouchedLeafs( edict_t *ent, mnode_t *node, int *headnode ) { mplane_t *splitplane; int sides, leafnum; mleaf_t *leaf; if( !node ) // if no collision model return; if( node->contents == CONTENTS_SOLID ) return; // add an efrag if the node is a leaf if( node->contents < 0 ) { if( ent->num_leafs > ( MAX_ENT_LEAFS - 1 )) { // continue counting leafs, // so we know how many it's overrun ent->num_leafs = (MAX_ENT_LEAFS + 1); } else { leaf = (mleaf_t *)node; leafnum = leaf - sv.worldmodel->leafs - 1; ent->leafnums[ent->num_leafs] = leafnum; ent->num_leafs++; } return; } // NODE_MIXED splitplane = node->plane; sides = BOX_ON_PLANE_SIDE( ent->v.absmin, ent->v.absmax, splitplane ); if( sides == 3 && *headnode == -1 ) *headnode = node - sv.worldmodel->nodes; // recurse down the contacted sides if( sides & 1 ) SV_FindTouchedLeafs( ent, node->children[0], headnode ); if( sides & 2 ) SV_FindTouchedLeafs( ent, node->children[1], headnode ); } /* ============= SV_HeadnodeVisible ============= */ qboolean SV_HeadnodeVisible( mnode_t *node, byte *visbits, int *lastleaf ) { int leafnum; if( !node || node->contents == CONTENTS_SOLID ) return false; if( node->contents < 0 ) { leafnum = ((mleaf_t *)node - sv.worldmodel->leafs) - 1; if(!( visbits[leafnum >> 3] & (1U << ( leafnum & 7 )))) return false; if( lastleaf ) *lastleaf = leafnum; return true; } if( SV_HeadnodeVisible( node->children[0], visbits, lastleaf )) return true; return SV_HeadnodeVisible( node->children[1], visbits, lastleaf ); } /* =============== SV_LinkEdict =============== */ void SV_LinkEdict( edict_t *ent, qboolean touch_triggers ) { areanode_t *node; int headnode; if( ent->area.prev ) SV_UnlinkEdict( ent ); // unlink from old position if( ent == svgame.edicts ) return; // don't add the world if( !SV_IsValidEdict( ent )) return; // never add freed ents // set the abs box svgame.dllFuncs.pfnSetAbsBox( ent ); if( ent->v.movetype == MOVETYPE_FOLLOW && SV_IsValidEdict( ent->v.aiment )) { ent->headnode = ent->v.aiment->headnode; ent->num_leafs = ent->v.aiment->num_leafs; Q_memcpy( ent->leafnums, ent->v.aiment->leafnums, sizeof( ent->leafnums )); } else { // link to PVS leafs ent->num_leafs = 0; ent->headnode = -1; headnode = -1; if( ent->v.modelindex ) SV_FindTouchedLeafs( ent, sv.worldmodel->nodes, &headnode ); if( ent->num_leafs > MAX_ENT_LEAFS ) { Q_memset( ent->leafnums, -1, sizeof( ent->leafnums )); ent->num_leafs = 0; // so we use headnode instead ent->headnode = headnode; } } // ignore non-solid bodies if( ent->v.solid == SOLID_NOT && ent->v.skin >= CONTENTS_EMPTY ) return; // find the first node that the ent's box crosses node = sv_areanodes; while( 1 ) { if( node->axis == -1 ) break; if( ent->v.absmin[node->axis] > node->dist ) node = node->children[0]; else if( ent->v.absmax[node->axis] < node->dist ) node = node->children[1]; else break; // crosses the node } // link it in if( ent->v.solid == SOLID_TRIGGER ) InsertLinkBefore( &ent->area, &node->trigger_edicts ); else if( ent->v.solid == SOLID_NOT && ent->v.skin < CONTENTS_EMPTY ) InsertLinkBefore( &ent->area, &node->water_edicts ); else InsertLinkBefore( &ent->area, &node->solid_edicts ); if( touch_triggers && !iTouchLinkSemaphore ) { iTouchLinkSemaphore = true; SV_TouchLinks( ent, sv_areanodes ); iTouchLinkSemaphore = false; } } /* =============================================================================== POINT TESTING IN HULLS =============================================================================== */ void SV_WaterLinks( const vec3_t origin, int *pCont, areanode_t *node ) { link_t *l, *next; edict_t *touch; hull_t *hull; vec3_t test, offset; model_t *mod; Q_memset( offset, 0, 3 * sizeof( float ) ); // get water edicts for( l = node->water_edicts.next; l != &node->water_edicts; l = next ) { next = l->next; touch = (edict_t *)((byte *)l - ADDRESS_OF_AREA); if( touch->v.solid != SOLID_NOT ) // disabled ? continue; if( touch->v.groupinfo ) { if(( !svs.groupop && !(touch->v.groupinfo & svs.groupmask)) || (svs.groupop == 1 && (touch->v.groupinfo & svs.groupmask))) continue; } // only brushes can have special contents if( Mod_GetType( touch->v.modelindex ) != mod_brush ) continue; if( !BoundsIntersect( origin, origin, touch->v.absmin, touch->v.absmax )) continue; mod = Mod_Handle( touch->v.modelindex ); // check water brushes accuracy if( Mod_GetType( touch->v.modelindex ) == mod_brush ) hull = SV_HullForBsp( touch, vec3_origin, vec3_origin, offset ); else { Host_MapDesignError( "Water must have BSP model!\n" ); hull = SV_HullForBox( touch->v.mins, touch->v.maxs ); } // support for rotational water if(( mod->flags & MODEL_HAS_ORIGIN ) && !VectorIsNull( touch->v.angles )) { matrix4x4 matrix; Matrix4x4_CreateFromEntity( matrix, touch->v.angles, offset, 1.0f ); Matrix4x4_VectorITransform( matrix, origin, test ); } else { // offset the test point appropriately for this hull. VectorSubtract( origin, offset, test ); } // test hull for intersection with this model if( PM_HullPointContents( hull, hull->firstclipnode, test ) == CONTENTS_EMPTY ) continue; // compare contents ranking if( RankForContents( touch->v.skin ) > RankForContents( *pCont )) *pCont = touch->v.skin; // new content has more priority } // recurse down both sides if( node->axis == -1 ) return; if( origin[node->axis] > node->dist ) SV_WaterLinks( origin, pCont, node->children[0] ); if( origin[node->axis] < node->dist ) SV_WaterLinks( origin, pCont, node->children[1] ); } /* ============= SV_TruePointContents ============= */ int SV_TruePointContents( const vec3_t p ) { int cont; // sanity check if( !p ) return CONTENTS_NONE; // get base contents from world cont = PM_HullPointContents( &sv.worldmodel->hulls[0], 0, p ); // check all water entities SV_WaterLinks( p, &cont, sv_areanodes ); return cont; } /* ============= SV_PointContents ============= */ int SV_PointContents( const vec3_t p ) { int cont = SV_TruePointContents( p ); if( cont <= CONTENTS_CURRENT_0 && cont >= CONTENTS_CURRENT_DOWN ) cont = CONTENTS_WATER; return cont; } //=========================================================================== /* ============ SV_TestEntityPosition returns true if the entity is in solid currently ============ */ qboolean SV_TestEntityPosition( edict_t *ent, edict_t *blocker ) { trace_t trace; if( ent->v.flags & (FL_CLIENT|FL_FAKECLIENT)) { // to avoid falling through tracktrain update client mins\maxs here if( ent->v.flags & FL_DUCKING ) SV_SetMinMaxSize( ent, svgame.pmove->player_mins[1], svgame.pmove->player_maxs[1] ); else SV_SetMinMaxSize( ent, svgame.pmove->player_mins[0], svgame.pmove->player_maxs[0] ); } trace = SV_Move( ent->v.origin, ent->v.mins, ent->v.maxs, ent->v.origin, MOVE_NORMAL|FMOVE_SIMPLEBOX, ent ); if( SV_IsValidEdict( blocker ) && SV_IsValidEdict( trace.ent )) { if( trace.ent->v.movetype == MOVETYPE_PUSH || trace.ent == blocker ) return trace.startsolid; return false; } return trace.startsolid; } /* =============================================================================== LINE TESTING IN HULLS =============================================================================== */ /* "Not a number" possible here. * Enable this macro to debug it */ #ifdef DEBUGNAN static void _assertNAN(const char *f, int l, const char *x) { MsgDev( D_WARN, "NAN detected at %s:%i (%s)\n", f, l, x ); } #define ASSERTNAN(x) if( !finitef(x) ) _assertNAN( __FILE__, __LINE__, #x ); #else #define ASSERTNAN(x) #endif /* ================== SV_RecursiveHullCheck ================== */ qboolean SV_RecursiveHullCheck( hull_t *hull, int num, float p1f, float p2f, vec3_t p1, vec3_t p2, trace_t *trace ) { dclipnode_t *node; mplane_t *plane; float t1, t2; float frac, midf; int side; vec3_t mid; // check for empty if( num < 0 ) { if( num != CONTENTS_SOLID ) { trace->allsolid = false; if( num == CONTENTS_EMPTY ) trace->inopen = true; else trace->inwater = true; } else trace->startsolid = true; return true; // empty } if( num < hull->firstclipnode || num > hull->lastclipnode ) Host_Error( "SV_RecursiveHullCheck: bad node number\n" ); if( !hull->clipnodes ) return false; // find the point distances node = hull->clipnodes + num; plane = hull->planes + node->planenum; if( plane->type < 3 ) { t1 = p1[plane->type] - plane->dist; t2 = p2[plane->type] - plane->dist; } else { t1 = DotProduct( plane->normal, p1 ) - plane->dist; t2 = DotProduct( plane->normal, p2 ) - plane->dist; } ASSERTNAN( t1 ) ASSERTNAN( t2 ) if( t1 >= 0 && t2 >= 0 ) return SV_RecursiveHullCheck( hull, node->children[0], p1f, p2f, p1, p2, trace ); if( t1 < 0 && t2 < 0 ) return SV_RecursiveHullCheck( hull, node->children[1], p1f, p2f, p1, p2, trace ); ASSERTNAN( t1 ) ASSERTNAN( t2 ) // put the crosspoint DIST_EPSILON pixels on the near side if( t1 < 0 ) frac = ( t1 + DIST_EPSILON ) / ( t1 - t2 ); else frac = ( t1 - DIST_EPSILON ) / ( t1 - t2 ); ASSERTNAN( frac ) if( frac < 0.0f ) frac = 0.0f; if( frac > 1.0f ) frac = 1.0f; midf = p1f + ( p2f - p1f ) * frac; VectorLerp( p1, frac, p2, mid ); side = (t1 < 0); ASSERTNAN( frac ) // move up to the node if( !SV_RecursiveHullCheck( hull, node->children[side], p1f, midf, p1, mid, trace )) return false; if( PM_HullPointContents( hull, node->children[side^1], mid ) != CONTENTS_SOLID ) { // go past the node return SV_RecursiveHullCheck (hull, node->children[side^1], midf, p2f, mid, p2, trace); } if( trace->allsolid ) return false; // never got out of the solid area //================== // the other side of the node is solid, this is the impact point //================== if( !side ) { VectorCopy( plane->normal, trace->plane.normal ); trace->plane.dist = plane->dist; } else { VectorNegate( plane->normal, trace->plane.normal ); trace->plane.dist = -plane->dist; } while( PM_HullPointContents( hull, hull->firstclipnode, mid ) == CONTENTS_SOLID ) { ASSERTNAN( frac ) // shouldn't really happen, but does occasionally frac -= 0.1f; if( ( frac < 0.0f ) || IS_NAN( frac ) ) { trace->fraction = midf; VectorCopy( mid, trace->endpos ); MsgDev( D_WARN, "trace backed up past 0.0\n" ); return false; } midf = p1f + (p2f - p1f) * frac; VectorLerp( p1, frac, p2, mid ); } trace->fraction = midf; VectorCopy( mid, trace->endpos ); return false; } /* ================== SV_ClipMoveToEntity Handles selection or creation of a clipping hull, and offseting (and eventually rotation) of the end points ================== */ void SV_ClipMoveToEntity( edict_t *ent, const vec3_t start, vec3_t mins, vec3_t maxs, const vec3_t end, trace_t *trace ) { hull_t *hull = NULL; model_t *model; vec3_t start_l, end_l; vec3_t offset, temp; int last_hitgroup; trace_t trace_hitbox; int i, j, hullcount; qboolean rotated, transform_bbox; matrix4x4 matrix; Q_memset( trace, 0, sizeof( trace_t )); VectorCopy( end, trace->endpos ); trace->fraction = 1.0f; trace->allsolid = 1; model = Mod_Handle( ent->v.modelindex ); if( model && model->type == mod_studio ) { hull = SV_HullForStudioModel( ent, mins, maxs, offset, &hullcount ); } else { hull = SV_HullForEntity( ent, mins, maxs, offset ); hullcount = 1; } // prevent crash on incorrect hull if( !hull ) return; // rotate start and end into the models frame of reference if( ent->v.solid == SOLID_BSP && !VectorIsNull( ent->v.angles )) rotated = true; else rotated = false; if( host.features & ENGINE_TRANSFORM_TRACE_AABB ) { // keep untransformed bbox less than 45 degress or train on subtransit.bsp will stop working if(( check_angles( ent->v.angles[0] ) || check_angles( ent->v.angles[2] )) && !VectorIsNull( mins )) transform_bbox = true; else transform_bbox = false; } else transform_bbox = false; if( rotated ) { vec3_t out_mins, out_maxs; if( transform_bbox ) Matrix4x4_CreateFromEntity( matrix, ent->v.angles, ent->v.origin, 1.0f ); else Matrix4x4_CreateFromEntity( matrix, ent->v.angles, offset, 1.0f ); Matrix4x4_VectorITransform( matrix, start, start_l ); Matrix4x4_VectorITransform( matrix, end, end_l ); if( transform_bbox ) { World_TransformAABB( matrix, mins, maxs, out_mins, out_maxs ); VectorSubtract( hull[0].clip_mins, out_mins, offset ); // calc new local offset for( j = 0; j < 3; j++ ) { if( start_l[j] >= 0.0f ) start_l[j] -= offset[j]; else start_l[j] += offset[j]; if( end_l[j] >= 0.0f ) end_l[j] -= offset[j]; else end_l[j] += offset[j]; } } } else { VectorSubtract( start, offset, start_l ); VectorSubtract( end, offset, end_l ); } if( hullcount == 1 ) { SV_RecursiveHullCheck( hull, hull->firstclipnode, 0.0f, 1.0f, start_l, end_l, trace ); } else { last_hitgroup = 0; for( i = 0; i < hullcount; i++ ) { Q_memset( &trace_hitbox, 0, sizeof( trace_t )); VectorCopy( end, trace_hitbox.endpos ); trace_hitbox.fraction = 1.0; trace_hitbox.allsolid = 1; SV_RecursiveHullCheck( &hull[i], hull[i].firstclipnode, 0.0f, 1.0f, start_l, end_l, &trace_hitbox ); if( i == 0 || trace_hitbox.allsolid || trace_hitbox.startsolid || trace_hitbox.fraction < trace->fraction ) { if( trace->startsolid ) { *trace = trace_hitbox; trace->startsolid = true; } else *trace = trace_hitbox; last_hitgroup = i; } } trace->hitgroup = Mod_HitgroupForStudioHull( last_hitgroup ); } if( trace->fraction != 1.0f ) { // compute endpos (generic case) VectorLerp( start, trace->fraction, end, trace->endpos ); if( rotated ) { // transform plane VectorCopy( trace->plane.normal, temp ); Matrix4x4_TransformPositivePlane( matrix, temp, trace->plane.dist, trace->plane.normal, &trace->plane.dist ); } else { trace->plane.dist = DotProduct( trace->endpos, trace->plane.normal ); } } if( trace->fraction < 1.0f || trace->startsolid ) trace->ent = ent; } /* ================== SV_CustomClipMoveToEntity A part of physics engine implementation or custom physics implementation ================== */ void SV_CustomClipMoveToEntity( edict_t *ent, const vec3_t start, vec3_t mins, vec3_t maxs, const vec3_t end, trace_t *trace ) { Q_memset( trace, 0, sizeof( trace_t )); VectorCopy( end, trace->endpos ); trace->allsolid = true; trace->fraction = 1.0f; if( svgame.physFuncs.ClipMoveToEntity != NULL ) { // do custom sweep test svgame.physFuncs.ClipMoveToEntity( ent, start, mins, maxs, end, trace ); } else { // function is missed, so we didn't hit anything trace->allsolid = false; } } /* ==================== SV_ClipToLinks Mins and maxs enclose the entire area swept by the move ==================== */ static void SV_ClipToLinks( areanode_t *node, moveclip_t *clip ) { link_t *l, *next; edict_t *touch; trace_t trace; // touch linked edicts for( l = node->solid_edicts.next; l != &node->solid_edicts; l = next ) { next = l->next; touch = (edict_t *)((byte *)l - ADDRESS_OF_AREA); if( touch->v.groupinfo != 0 && SV_IsValidEdict( clip->passedict ) && clip->passedict->v.groupinfo != 0 ) { if(( svs.groupop == 0 && ( touch->v.groupinfo & clip->passedict->v.groupinfo ) == 0) || ( svs.groupop == 1 && (touch->v.groupinfo & clip->passedict->v.groupinfo ) != 0 )) continue; } if( touch == clip->passedict || touch->v.solid == SOLID_NOT ) continue; if( touch->v.solid == SOLID_TRIGGER ) { Host_MapDesignError( "trigger in clipping list\n" ); touch->v.solid = SOLID_NOT; } // custom user filter if( svgame.dllFuncs2.pfnShouldCollide ) { if( !svgame.dllFuncs2.pfnShouldCollide( touch, clip->passedict )) continue; // originally this was 'return' but is completely wrong! } // monsterclip filter (solid custom is a static or dynamic bodies) if( touch->v.solid == SOLID_BSP || touch->v.solid == SOLID_CUSTOM ) { if( touch->v.flags & FL_MONSTERCLIP ) { // func_monsterclip works only with monsters that have same flag! if( !SV_IsValidEdict( clip->passedict ) || !( clip->passedict->v.flags & FL_MONSTERCLIP )) continue; } } else { // ignore all monsters but pushables if( clip->type == MOVE_NOMONSTERS && touch->v.movetype != MOVETYPE_PUSHSTEP ) continue; } if( Mod_GetType( touch->v.modelindex ) == mod_brush && clip->flags & FMOVE_IGNORE_GLASS ) { // we ignore brushes with rendermode != kRenderNormal and without FL_WORLDBRUSH set if( touch->v.rendermode != kRenderNormal && !( touch->v.flags & FL_WORLDBRUSH )) continue; } if( !BoundsIntersect( clip->boxmins, clip->boxmaxs, touch->v.absmin, touch->v.absmax )) continue; // Xash3D extension if( SV_IsValidEdict( clip->passedict ) && clip->passedict->v.solid == SOLID_TRIGGER ) { // never collide items and player (because call "give" always stuck item in player // and total trace returns fail (old half-life bug) // items touch should be done in SV_TouchLinks not here if( touch->v.flags & ( FL_CLIENT|FL_FAKECLIENT )) continue; } // g-cont. make sure what size is really zero - check all the components if( SV_IsValidEdict( clip->passedict ) && !VectorIsNull( clip->passedict->v.size ) && VectorIsNull( touch->v.size )) continue; // points never interact // might intersect, so do an exact clip if( clip->trace.allsolid ) return; if( SV_IsValidEdict( clip->passedict )) { if( touch->v.owner == clip->passedict ) continue; // don't clip against own missiles if( clip->passedict->v.owner == touch ) continue; // don't clip against owner } if( touch->v.solid == SOLID_CUSTOM ) SV_CustomClipMoveToEntity( touch, clip->start, clip->mins, clip->maxs, clip->end, &trace ); else if( touch->v.flags & FL_MONSTER ) SV_ClipMoveToEntity( touch, clip->start, clip->mins2, clip->maxs2, clip->end, &trace ); else SV_ClipMoveToEntity( touch, clip->start, clip->mins, clip->maxs, clip->end, &trace ); clip->trace = World_CombineTraces( &clip->trace, &trace, touch ); } // recurse down both sides if( node->axis == -1 ) return; if( clip->boxmaxs[node->axis] > node->dist ) SV_ClipToLinks( node->children[0], clip ); if( clip->boxmins[node->axis] < node->dist ) SV_ClipToLinks( node->children[1], clip ); } /* ==================== SV_ClipToWorldBrush Mins and maxs enclose the entire area swept by the move ==================== */ void SV_ClipToWorldBrush( areanode_t *node, moveclip_t *clip ) { link_t *l, *next; edict_t *touch; trace_t trace; for( l = node->solid_edicts.next; l != &node->solid_edicts; l = next ) { next = l->next; touch = (edict_t *)((byte *)l - ADDRESS_OF_AREA); if( touch->v.solid != SOLID_BSP || touch == clip->passedict || !( touch->v.flags & FL_WORLDBRUSH )) continue; if( !BoundsIntersect( clip->boxmins, clip->boxmaxs, touch->v.absmin, touch->v.absmax )) continue; if( clip->trace.allsolid ) return; SV_ClipMoveToEntity( touch, clip->start, clip->mins, clip->maxs, clip->end, &trace ); clip->trace = World_CombineTraces( &clip->trace, &trace, touch ); } // recurse down both sides if( node->axis == -1 ) return; if( clip->boxmaxs[node->axis] > node->dist ) SV_ClipToWorldBrush( node->children[0], clip ); if( clip->boxmins[node->axis] < node->dist ) SV_ClipToWorldBrush( node->children[1], clip ); } /* ================== SV_Move ================== */ trace_t SV_Move( const vec3_t start, vec3_t mins, vec3_t maxs, const vec3_t end, int type, edict_t *e ) { moveclip_t clip; vec3_t trace_endpos; float trace_fraction; Q_memset( &clip, 0, sizeof( moveclip_t )); SV_ClipMoveToEntity( EDICT_NUM( 0 ), start, mins, maxs, end, &clip.trace ); if( clip.trace.fraction != 0.0f ) { VectorCopy( clip.trace.endpos, trace_endpos ); trace_fraction = clip.trace.fraction; clip.trace.fraction = 1.0f; clip.start = start; clip.end = trace_endpos; clip.type = (type & 0xFF); clip.flags = (type & 0xFF00); clip.passedict = (e) ? e : EDICT_NUM( 0 ); clip.mins = mins; clip.maxs = maxs; if( clip.type == MOVE_MISSILE ) { VectorSet( clip.mins2, -15.0f, -15.0f, -15.0f ); VectorSet( clip.maxs2, 15.0f, 15.0f, 15.0f ); } else { VectorCopy( mins, clip.mins2 ); VectorCopy( maxs, clip.maxs2 ); } World_MoveBounds( start, clip.mins2, clip.maxs2, trace_endpos, clip.boxmins, clip.boxmaxs ); SV_ClipToLinks( sv_areanodes, &clip ); clip.trace.fraction *= trace_fraction; svgame.globals->trace_ent = clip.trace.ent; } SV_CopyTraceToGlobal( &clip.trace ); return clip.trace; } /* ================== SV_MoveNoEnts ================== */ trace_t SV_MoveNoEnts( const vec3_t start, vec3_t mins, vec3_t maxs, const vec3_t end, int type, edict_t *e ) { moveclip_t clip; vec3_t trace_endpos; float trace_fraction; Q_memset( &clip, 0, sizeof( moveclip_t )); SV_ClipMoveToEntity( EDICT_NUM( 0 ), start, mins, maxs, end, &clip.trace ); if( clip.trace.fraction != 0.0f ) { VectorCopy( clip.trace.endpos, trace_endpos ); trace_fraction = clip.trace.fraction; clip.trace.fraction = 1.0f; clip.start = start; clip.end = trace_endpos; clip.type = (type & 0xFF); clip.flags = (type & 0xFF00); clip.passedict = (e) ? e : EDICT_NUM( 0 ); clip.mins = mins; clip.maxs = maxs; VectorCopy( mins, clip.mins2 ); VectorCopy( maxs, clip.maxs2 ); World_MoveBounds( start, clip.mins2, clip.maxs2, trace_endpos, clip.boxmins, clip.boxmaxs ); SV_ClipToWorldBrush( sv_areanodes, &clip ); clip.trace.fraction *= trace_fraction; svgame.globals->trace_ent = clip.trace.ent; } SV_CopyTraceToGlobal( &clip.trace ); return clip.trace; } /* ================== SV_TraceSurface find the face where the traceline hit assume pTextureEntity is valid ================== */ msurface_t *SV_TraceSurface( edict_t *ent, const vec3_t start, const vec3_t end ) { matrix4x4 matrix; model_t *bmodel; hull_t *hull; vec3_t start_l, end_l; vec3_t offset; bmodel = Mod_Handle( ent->v.modelindex ); if( !bmodel || bmodel->type != mod_brush ) return NULL; hull = SV_HullForBsp( ent, vec3_origin, vec3_origin, offset ); VectorSubtract( start, offset, start_l ); VectorSubtract( end, offset, end_l ); // rotate start and end into the models frame of reference if( !VectorIsNull( ent->v.angles )) { Matrix4x4_CreateFromEntity( matrix, ent->v.angles, offset, 1.0f ); Matrix4x4_VectorITransform( matrix, start, start_l ); Matrix4x4_VectorITransform( matrix, end, end_l ); } return PM_RecursiveSurfCheck( bmodel, &bmodel->nodes[hull->firstclipnode], start_l, end_l ); } /* ================== SV_TraceTexture find the face where the traceline hit assume pTextureEntity is valid ================== */ const char *SV_TraceTexture( edict_t *ent, const vec3_t start, const vec3_t end ) { msurface_t *surf; matrix4x4 matrix; model_t *bmodel; hull_t *hull; vec3_t start_l, end_l; vec3_t offset; bmodel = Mod_Handle( ent->v.modelindex ); if( !bmodel || bmodel->type != mod_brush ) return NULL; hull = SV_HullForBsp( ent, vec3_origin, vec3_origin, offset ); VectorSubtract( start, offset, start_l ); VectorSubtract( end, offset, end_l ); // rotate start and end into the models frame of reference if( !VectorIsNull( ent->v.angles )) { Matrix4x4_CreateFromEntity( matrix, ent->v.angles, offset, 1.0f ); Matrix4x4_VectorITransform( matrix, start, start_l ); Matrix4x4_VectorITransform( matrix, end, end_l ); } surf = PM_RecursiveSurfCheck( bmodel, &bmodel->nodes[hull->firstclipnode], start_l, end_l ); if( !surf || !surf->texinfo || !surf->texinfo->texture ) return NULL; return surf->texinfo->texture->name; } /* ================== SV_MoveToss ================== */ trace_t SV_MoveToss( edict_t *tossent, edict_t *ignore ) { float gravity; vec3_t move, end; vec3_t original_origin; vec3_t original_velocity; vec3_t original_angles; vec3_t original_avelocity; trace_t trace; int i; Q_memset( &trace, 0, sizeof( trace_t ) ); VectorCopy( tossent->v.origin, original_origin ); VectorCopy( tossent->v.velocity, original_velocity ); VectorCopy( tossent->v.angles, original_angles ); VectorCopy( tossent->v.avelocity, original_avelocity ); gravity = tossent->v.gravity * svgame.movevars.gravity * 0.05f; for( i = 0; i < 200; i++ ) { SV_CheckVelocity( tossent ); tossent->v.velocity[2] -= gravity; VectorMA( tossent->v.angles, 0.05f, tossent->v.avelocity, tossent->v.angles ); VectorScale( tossent->v.velocity, 0.05f, move ); VectorAdd( tossent->v.origin, move, end ); trace = SV_Move( tossent->v.origin, tossent->v.mins, tossent->v.maxs, end, MOVE_NORMAL, tossent ); VectorCopy( trace.endpos, tossent->v.origin ); if( trace.fraction < 1.0f ) break; } VectorCopy( original_origin, tossent->v.origin ); VectorCopy( original_velocity, tossent->v.velocity ); VectorCopy( original_angles, tossent->v.angles ); VectorCopy( original_avelocity, tossent->v.avelocity ); return trace; } /* =============================================================================== LIGHTING INFO =============================================================================== */ static vec3_t sv_pointColor; /* ================= SV_RecursiveLightPoint ================= */ static qboolean SV_RecursiveLightPoint( model_t *model, mnode_t *node, const vec3_t start, const vec3_t end ) { int side; mplane_t *plane; msurface_t *surf; mtexinfo_t *tex; float front, back, scale, frac; int i, map, size, s, t; color24 *lm; vec3_t mid; // didn't hit anything if( node->contents < 0 ) return false; // calculate mid point plane = node->plane; if( plane->type < 3 ) { front = start[plane->type] - plane->dist; back = end[plane->type] - plane->dist; } else { front = DotProduct( start, plane->normal ) - plane->dist; back = DotProduct( end, plane->normal ) - plane->dist; } side = front < 0.0f; if(( back < 0.0f ) == side ) return SV_RecursiveLightPoint( model, node->children[side], start, end ); frac = front / ( front - back ); VectorLerp( start, frac, end, mid ); // co down front side if( SV_RecursiveLightPoint( model, node->children[side], start, mid )) return true; // hit something if(( back < 0.0f ) == side ) return false;// didn't hit anything // check for impact on this node surf = model->surfaces + node->firstsurface; for( i = 0; i < node->numsurfaces; i++, surf++ ) { tex = surf->texinfo; if( surf->flags & SURF_DRAWTILED ) continue; // no lightmaps s = DotProduct( mid, tex->vecs[0] ) + tex->vecs[0][3] - surf->texturemins[0]; t = DotProduct( mid, tex->vecs[1] ) + tex->vecs[1][3] - surf->texturemins[1]; if(( s < 0.0f || s > surf->extents[0] ) || ( t < 0.0f || t > surf->extents[1] )) continue; s /= LM_SAMPLE_SIZE; t /= LM_SAMPLE_SIZE; if( !surf->samples ) return true; VectorClear( sv_pointColor ); lm = surf->samples + (t * ((surf->extents[0] / LM_SAMPLE_SIZE) + 1) + s); size = ((surf->extents[0] / LM_SAMPLE_SIZE) + 1) * ((surf->extents[1] / LM_SAMPLE_SIZE) + 1); for( map = 0; map < MAXLIGHTMAPS && surf->styles[map] != 255; map++ ) { scale = sv.lightstyles[surf->styles[map]].value; sv_pointColor[0] += lm->r * scale; sv_pointColor[1] += lm->g * scale; sv_pointColor[2] += lm->b * scale; lm += size; // skip to next lightmap } return true; } // go down back side return SV_RecursiveLightPoint( model, node->children[!side], mid, end ); } void SV_RunLightStyles( void ) { int i, ofs; lightstyle_t *ls; float scale; scale = sv_lighting_modulate->value; // run lightstyles animation for( i = 0, ls = sv.lightstyles; i < MAX_LIGHTSTYLES; i++, ls++ ) { ls->time += host.frametime; if( ls->length == 0 ) { ls->value = scale; // disable this light } else if( ls->length == 1 ) { ls->value = ( ls->map[0] / 12.0f ) * scale; } else { ofs = (ls->time * 10); ls->value = ( ls->map[ofs % ls->length] / 12.0f ) * scale; } } } /* ================== SV_SetLightStyle needs to get correct working SV_LightPoint ================== */ void SV_SetLightStyle( int style, const char* s, float f ) { int j, k; Q_strncpy( sv.lightstyles[style].pattern, s, sizeof( sv.lightstyles[0].pattern )); sv.lightstyles[style].time = f; j = Q_strlen( s ); sv.lightstyles[style].length = j; for( k = 0; k < j; k++ ) sv.lightstyles[style].map[k] = (float)(s[k] - 'a'); if( sv.state != ss_active ) return; // tell the clients about changed lightstyle BF_WriteByte( &sv.reliable_datagram, svc_lightstyle ); BF_WriteByte( &sv.reliable_datagram, style ); BF_WriteString( &sv.reliable_datagram, sv.lightstyles[style].pattern ); BF_WriteFloat( &sv.reliable_datagram, sv.lightstyles[style].time ); } /* ================== SV_GetLightStyle needs to get correct working SV_LightPoint ================== */ const char *SV_GetLightStyle( int style ) { if( style < 0 ) style = 0; if( style >= MAX_LIGHTSTYLES ) Host_Error( "SV_GetLightStyle: style: %i >= %d", style, MAX_LIGHTSTYLES ); return sv.lightstyles[style].pattern; } /* ================== SV_LightForEntity grab the ambient lighting color for current point ================== */ int SV_LightForEntity( edict_t *pEdict ) { vec3_t start, end; if( !pEdict ) return 0; if( pEdict->v.effects & EF_FULLBRIGHT || !sv.worldmodel->lightdata ) { return 255; } if( pEdict->v.flags & FL_CLIENT ) { // player has more precision light level // that come from client-side return pEdict->v.light_level; } VectorCopy( pEdict->v.origin, start ); VectorCopy( pEdict->v.origin, end ); if( pEdict->v.effects & EF_INVLIGHT ) end[2] = start[2] + world.size[2]; else end[2] = start[2] - world.size[2]; VectorSet( sv_pointColor, 1.0f, 1.0f, 1.0f ); SV_RecursiveLightPoint( sv.worldmodel, sv.worldmodel->nodes, start, end ); return VectorAvg( sv_pointColor ); }
0
0.836547
1
0.836547
game-dev
MEDIA
0.704817
game-dev
0.972957
1
0.972957
google/swiftshader
44,904
third_party/llvm-10.0/llvm/lib/Target/MSP430/MSP430InstrInfo.td
//===-- MSP430InstrInfo.td - MSP430 Instruction defs -------*- tablegen -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file describes the MSP430 instructions in TableGen format. // //===----------------------------------------------------------------------===// include "MSP430InstrFormats.td" //===----------------------------------------------------------------------===// // Type Constraints. //===----------------------------------------------------------------------===// class SDTCisI8<int OpNum> : SDTCisVT<OpNum, i8>; class SDTCisI16<int OpNum> : SDTCisVT<OpNum, i16>; //===----------------------------------------------------------------------===// // Type Profiles. //===----------------------------------------------------------------------===// def SDT_MSP430Call : SDTypeProfile<0, -1, [SDTCisVT<0, iPTR>]>; def SDT_MSP430CallSeqStart : SDCallSeqStart<[SDTCisVT<0, i16>, SDTCisVT<1, i16>]>; def SDT_MSP430CallSeqEnd : SDCallSeqEnd<[SDTCisVT<0, i16>, SDTCisVT<1, i16>]>; def SDT_MSP430Wrapper : SDTypeProfile<1, 1, [SDTCisSameAs<0, 1>, SDTCisPtrTy<0>]>; def SDT_MSP430Cmp : SDTypeProfile<0, 2, [SDTCisSameAs<0, 1>]>; def SDT_MSP430BrCC : SDTypeProfile<0, 2, [SDTCisVT<0, OtherVT>, SDTCisVT<1, i8>]>; def SDT_MSP430SelectCC : SDTypeProfile<1, 3, [SDTCisSameAs<0, 1>, SDTCisSameAs<1, 2>, SDTCisVT<3, i8>]>; def SDT_MSP430DAdd : SDTypeProfile<1, 2, [SDTCisSameAs<0, 1>, SDTCisSameAs<0, 2>, SDTCisInt<0>]>; //===----------------------------------------------------------------------===// // MSP430 Specific Node Definitions. //===----------------------------------------------------------------------===// def MSP430retflag : SDNode<"MSP430ISD::RET_FLAG", SDTNone, [SDNPHasChain, SDNPOptInGlue, SDNPVariadic]>; def MSP430retiflag : SDNode<"MSP430ISD::RETI_FLAG", SDTNone, [SDNPHasChain, SDNPOptInGlue, SDNPVariadic]>; def MSP430rra : SDNode<"MSP430ISD::RRA", SDTIntUnaryOp, []>; def MSP430rla : SDNode<"MSP430ISD::RLA", SDTIntUnaryOp, []>; def MSP430rrc : SDNode<"MSP430ISD::RRC", SDTIntUnaryOp, []>; def MSP430rrcl : SDNode<"MSP430ISD::RRCL", SDTIntUnaryOp, []>; def MSP430call : SDNode<"MSP430ISD::CALL", SDT_MSP430Call, [SDNPHasChain, SDNPOutGlue, SDNPOptInGlue, SDNPVariadic]>; def MSP430callseq_start : SDNode<"ISD::CALLSEQ_START", SDT_MSP430CallSeqStart, [SDNPHasChain, SDNPOutGlue]>; def MSP430callseq_end : SDNode<"ISD::CALLSEQ_END", SDT_MSP430CallSeqEnd, [SDNPHasChain, SDNPOptInGlue, SDNPOutGlue]>; def MSP430Wrapper : SDNode<"MSP430ISD::Wrapper", SDT_MSP430Wrapper>; def MSP430cmp : SDNode<"MSP430ISD::CMP", SDT_MSP430Cmp, [SDNPOutGlue]>; def MSP430brcc : SDNode<"MSP430ISD::BR_CC", SDT_MSP430BrCC, [SDNPHasChain, SDNPInGlue]>; def MSP430selectcc: SDNode<"MSP430ISD::SELECT_CC", SDT_MSP430SelectCC, [SDNPInGlue]>; def MSP430dadd : SDNode<"MSP430ISD::DADD", SDT_MSP430DAdd, []>; //===----------------------------------------------------------------------===// // MSP430 Operand Definitions. //===----------------------------------------------------------------------===// def MemAsmOperand : AsmOperandClass { let Name = "Mem"; } // Address operands def memsrc : Operand<i16> { let PrintMethod = "printSrcMemOperand"; let MIOperandInfo = (ops GR16, i16imm); let ParserMatchClass = MemAsmOperand; let EncoderMethod = "getMemOpValue"; let DecoderMethod = "DecodeMemOperand"; } def memdst : Operand<i16> { let PrintMethod = "printSrcMemOperand"; let MIOperandInfo = (ops GR16, i16imm); let ParserMatchClass = MemAsmOperand; let EncoderMethod = "getMemOpValue"; let DecoderMethod = "DecodeMemOperand"; } def IndRegAsmOperand : AsmOperandClass { let Name = "IndReg"; let RenderMethod = "addRegOperands"; } def indreg : Operand<i16> { let PrintMethod = "printIndRegOperand"; let MIOperandInfo = (ops GR16); let ParserMatchClass = IndRegAsmOperand; let DecoderMethod = "DecodeGR16RegisterClass"; } def PostIndRegAsmOperand : AsmOperandClass { let Name = "PostIndReg"; let RenderMethod = "addRegOperands"; } def postreg : Operand<i16> { let PrintMethod = "printPostIndRegOperand"; let MIOperandInfo = (ops GR16); let ParserMatchClass = PostIndRegAsmOperand; let DecoderMethod = "DecodeGR16RegisterClass"; } // Short jump targets have OtherVT type and are printed as pcrel imm values. def jmptarget : Operand<OtherVT> { let PrintMethod = "printPCRelImmOperand"; let EncoderMethod = "getPCRelImmOpValue"; } // Operand for printing out a condition code. def cc : Operand<i8> { let PrintMethod = "printCCOperand"; let EncoderMethod = "getCCOpValue"; } def CGImmAsmOperand : AsmOperandClass { let Name = "CGImm"; let RenderMethod = "addImmOperands"; } def cg8imm : Operand<i8>, ImmLeaf<i8, [{return Imm == 0 || Imm == 1 || Imm == 2 || Imm == 4 || Imm == 8 || Imm == -1;}]> { let ParserMatchClass = CGImmAsmOperand; let EncoderMethod = "getCGImmOpValue"; let DecoderMethod = "DecodeCGImm"; } def cg16imm : Operand<i16>, ImmLeaf<i16, [{return Imm == 0 || Imm == 1 || Imm == 2 || Imm == 4 || Imm == 8 || Imm == -1;}]> { let ParserMatchClass = CGImmAsmOperand; let EncoderMethod = "getCGImmOpValue"; let DecoderMethod = "DecodeCGImm"; } //===----------------------------------------------------------------------===// // MSP430 Complex Pattern Definitions. //===----------------------------------------------------------------------===// def addr : ComplexPattern<iPTR, 2, "SelectAddr", [], []>; //===----------------------------------------------------------------------===// // Pattern Fragments def zextloadi16i8 : PatFrag<(ops node:$ptr), (i16 (zextloadi8 node:$ptr))>; def extloadi16i8 : PatFrag<(ops node:$ptr), (i16 ( extloadi8 node:$ptr))>; def bic : PatFrag<(ops node:$lhs, node:$rhs), (and node:$lhs, (not node:$rhs))>; def and_su : PatFrag<(ops node:$lhs, node:$rhs), (and node:$lhs, node:$rhs), [{ return N->hasOneUse(); }]>; //===----------------------------------------------------------------------===// // Instruction list.. // ADJCALLSTACKDOWN/UP implicitly use/def SP because they may be expanded into // a stack adjustment and the codegen must know that they may modify the stack // pointer before prolog-epilog rewriting occurs. // Pessimistically assume ADJCALLSTACKDOWN / ADJCALLSTACKUP will become // sub / add which can clobber SR. let isCodeGenOnly = 1, Defs = [SP, SR], Uses = [SP] in { def ADJCALLSTACKDOWN : Pseudo<(outs), (ins i16imm:$amt1, i16imm:$amt2), "#ADJCALLSTACKDOWN $amt1 $amt2", [(MSP430callseq_start timm:$amt1, timm:$amt2)]>; def ADJCALLSTACKUP : Pseudo<(outs), (ins i16imm:$amt1, i16imm:$amt2), "#ADJCALLSTACKUP $amt1 $amt2", [(MSP430callseq_end timm:$amt1, timm:$amt2)]>; } let isCodeGenOnly = 1, Defs = [SR], Uses = [SP] in { def ADDframe : Pseudo<(outs GR16:$dst), (ins i16imm:$base, i16imm:$offset), "# ADDframe PSEUDO", []>; } let isCodeGenOnly = 1, usesCustomInserter = 1 in { let Uses = [SR] in { def Select8 : Pseudo<(outs GR8:$dst), (ins GR8:$src, GR8:$src2, i8imm:$cc), "# Select8 PSEUDO", [(set GR8:$dst, (MSP430selectcc GR8:$src, GR8:$src2, imm:$cc))]>; def Select16 : Pseudo<(outs GR16:$dst), (ins GR16:$src, GR16:$src2, i8imm:$cc), "# Select16 PSEUDO", [(set GR16:$dst, (MSP430selectcc GR16:$src, GR16:$src2, imm:$cc))]>; } let Defs = [SR] in { def Shl8 : Pseudo<(outs GR8:$dst), (ins GR8:$src, GR8:$cnt), "# Shl8 PSEUDO", [(set GR8:$dst, (shl GR8:$src, GR8:$cnt))]>; def Shl16 : Pseudo<(outs GR16:$dst), (ins GR16:$src, GR8:$cnt), "# Shl16 PSEUDO", [(set GR16:$dst, (shl GR16:$src, GR8:$cnt))]>; def Sra8 : Pseudo<(outs GR8:$dst), (ins GR8:$src, GR8:$cnt), "# Sra8 PSEUDO", [(set GR8:$dst, (sra GR8:$src, GR8:$cnt))]>; def Sra16 : Pseudo<(outs GR16:$dst), (ins GR16:$src, GR8:$cnt), "# Sra16 PSEUDO", [(set GR16:$dst, (sra GR16:$src, GR8:$cnt))]>; def Srl8 : Pseudo<(outs GR8:$dst), (ins GR8:$src, GR8:$cnt), "# Srl8 PSEUDO", [(set GR8:$dst, (srl GR8:$src, GR8:$cnt))]>; def Srl16 : Pseudo<(outs GR16:$dst), (ins GR16:$src, GR8:$cnt), "# Srl16 PSEUDO", [(set GR16:$dst, (srl GR16:$src, GR8:$cnt))]>; def Rrcl8 : Pseudo<(outs GR8:$dst), (ins GR8:$src), "", [(set GR8:$dst, (MSP430rrcl GR8:$src))]>; def Rrcl16 : Pseudo<(outs GR16:$dst), (ins GR16:$src), "", [(set GR16:$dst, (MSP430rrcl GR16:$src))]>; } } //===----------------------------------------------------------------------===// // Control Flow Instructions... // let isReturn = 1, isTerminator = 1, isBarrier = 1 in { def RET : IForm16<0b0100, DstReg, SrcPostInc, 2, (outs), (ins), "ret", [(MSP430retflag)]> { let DecoderNamespace = "Delta"; let rs = 1; let rd = 0; } def RETI : IIForm16<0b110, SrcReg, 2, (outs), (ins), "reti", [(MSP430retiflag)]> { let rs = 0; } } let isBranch = 1, isTerminator = 1 in { // FIXME: expand opcode & cond field for branches! // Direct branch let isBarrier = 1 in { // Short branch def JMP : CJForm<(outs), (ins jmptarget:$dst), "jmp\t$dst", [(br bb:$dst)]> { let cond = 0b111; } let isIndirectBranch = 1, rd = 0 in { // Long branches def Bi : I16ri<0b0100, (outs), (ins i16imm:$imm), "br\t$imm", [(brind tblockaddress:$imm)]>; def Br : I16rr<0b0100, (outs), (ins GR16:$rs), "br\t$rs", [(brind GR16:$rs)]>; def Bm : I16rm<0b0100, (outs), (ins memsrc:$src), "br\t$src", [(brind (load addr:$src))]>; } } // Conditional branches let Uses = [SR] in def JCC : CJForm<(outs), (ins jmptarget:$dst, cc:$cond), "j$cond\t$dst", [(MSP430brcc bb:$dst, imm:$cond)]>; } // isBranch, isTerminator //===----------------------------------------------------------------------===// // Call Instructions... // // All calls clobber the non-callee saved registers. SPW is marked as // a use to prevent stack-pointer assignments that appear immediately // before calls from potentially appearing dead. Uses for argument // registers are added manually. let isCall = 1, Defs = [R11, R12, R13, R14, R15, SR], Uses = [SP] in { def CALLi : II16i<0b101, (outs), (ins i16imm:$imm), "call\t$imm", [(MSP430call imm:$imm)]>; def CALLr : II16r<0b101, (outs), (ins GR16:$rs), "call\t$rs", [(MSP430call GR16:$rs)]>; def CALLm : II16m<0b101, (outs), (ins memsrc:$src), "call\t$src", [(MSP430call (load addr:$src))]>; def CALLn : II16n<0b101, (outs), (ins indreg:$rs), "call\t$rs", []>; def CALLp : II16p<0b101, (outs), (ins postreg:$rs), "call\t$rs", []>; } //===----------------------------------------------------------------------===// // Miscellaneous Instructions... // let Defs = [SP], Uses = [SP], hasSideEffects = 0 in { let mayLoad = 1 in def POP16r : IForm16<0b0100, DstReg, SrcPostInc, 2, (outs GR16:$rd), (ins), "pop\t$rd", []> { let DecoderNamespace = "Delta"; let rs = 1; } let mayStore = 1 in def PUSH8r : II8r<0b100, (outs), (ins GR8:$rs), "push.b\t$rs", []>; def PUSH16r : II16r<0b100, (outs), (ins GR16:$rs), "push\t$rs", []>; def PUSH16c : II16c<0b100, (outs), (ins cg16imm:$imm), "push\t$imm", []>; def PUSH16i : II16i<0b100, (outs), (ins i16imm:$imm), "push\t$imm", []>; } //===----------------------------------------------------------------------===// // Move Instructions let hasSideEffects = 0 in { def MOV8rr : I8rr<0b0100, (outs GR8:$rd), (ins GR8:$rs), "mov.b\t{$rs, $rd}", []>; def MOV16rr : I16rr<0b0100, (outs GR16:$rd), (ins GR16:$rs), "mov\t{$rs, $rd}", []>; } let isReMaterializable = 1, isAsCheapAsAMove = 1 in { def MOV8rc : I8rc<0b0100, (outs GR8:$rd), (ins cg8imm:$imm), "mov.b\t$imm, $rd", [(set GR8:$rd, cg8imm:$imm)]>; def MOV16rc : I16rc<0b0100, (outs GR16:$rd), (ins cg16imm:$imm), "mov\t$imm, $rd", [(set GR16:$rd, cg16imm:$imm)]>; def MOV8ri : I8ri<0b0100, (outs GR8:$rd), (ins i8imm:$imm), "mov.b\t{$imm, $rd}", [(set GR8:$rd, imm:$imm)]>; def MOV16ri : I16ri<0b0100, (outs GR16:$rd), (ins i16imm:$imm), "mov\t{$imm, $rd}", [(set GR16:$rd, imm:$imm)]>; } let canFoldAsLoad = 1, isReMaterializable = 1 in { def MOV8rm : I8rm<0b0100, (outs GR8:$rd), (ins memsrc:$src), "mov.b\t{$src, $rd}", [(set GR8:$rd, (load addr:$src))]>; def MOV16rm : I16rm<0b0100, (outs GR16:$rd), (ins memsrc:$src), "mov\t{$src, $rd}", [(set GR16:$rd, (load addr:$src))]>; def MOV8rn : I8rn<0b0100, (outs GR8:$rd), (ins indreg:$rs), "mov.b\t{$rs, $rd}", [(set GR8:$rd, (load addr:$rs))]>; def MOV16rn : I16rn<0b0100, (outs GR16:$rd), (ins indreg:$rs), "mov\t{$rs, $rd}", [(set GR16:$rd, (load addr:$rs))]>; } let isCodeGenOnly = 1 in { def MOVZX16rr8 : I8rr<0b0100, (outs GR16:$rd), (ins GR8:$rs), "mov.b\t{$rs, $rd}", [(set GR16:$rd, (zext GR8:$rs))]>; def MOVZX16rm8 : I8rm<0b0100, (outs GR16:$rd), (ins memsrc:$src), "mov.b\t{$src, $rd}", [(set GR16:$rd, (zextloadi16i8 addr:$src))]>; } let mayLoad = 1, hasExtraDefRegAllocReq = 1, Constraints = "$rs = $wb" in { def MOV8rp : I8rp<0b0100, (outs GR8:$rd, GR16:$wb), (ins postreg:$rs), "mov.b\t{$rs, $rd}", []>; def MOV16rp : I16rp<0b0100, (outs GR16:$rd, GR16:$wb), (ins postreg:$rs), "mov\t{$rs, $rd}", []>; } // Any instruction that defines a 8-bit result leaves the high half of the // register. Truncate can be lowered to EXTRACT_SUBREG, and CopyFromReg may // be copying from a truncate, but any other 8-bit operation will zero-extend // up to 16 bits. def def8 : PatLeaf<(i8 GR8:$src), [{ return N->getOpcode() != ISD::TRUNCATE && N->getOpcode() != TargetOpcode::EXTRACT_SUBREG && N->getOpcode() != ISD::CopyFromReg; }]>; // In the case of a 8-bit def that is known to implicitly zero-extend, // we can use a SUBREG_TO_REG. def : Pat<(i16 (zext def8:$src)), (SUBREG_TO_REG (i16 0), GR8:$src, subreg_8bit)>; def MOV8mc : I8mc<0b0100, (outs), (ins memdst:$dst, cg8imm:$imm), "mov.b\t{$imm, $dst}", [(store (i8 cg8imm:$imm), addr:$dst)]>; def MOV16mc : I16mc<0b0100, (outs), (ins memdst:$dst, cg16imm:$imm), "mov\t{$imm, $dst}", [(store (i16 cg16imm:$imm), addr:$dst)]>; def MOV8mi : I8mi<0b0100, (outs), (ins memdst:$dst, i8imm:$imm), "mov.b\t{$imm, $dst}", [(store (i8 imm:$imm), addr:$dst)]>; def MOV16mi : I16mi<0b0100, (outs), (ins memdst:$dst, i16imm:$imm), "mov\t{$imm, $dst}", [(store (i16 imm:$imm), addr:$dst)]>; def MOV8mr : I8mr<0b0100, (outs), (ins memdst:$dst, GR8:$rs), "mov.b\t{$rs, $dst}", [(store GR8:$rs, addr:$dst)]>; def MOV16mr : I16mr<0b0100, (outs), (ins memdst:$dst, GR16:$rs), "mov\t{$rs, $dst}", [(store GR16:$rs, addr:$dst)]>; def MOV8mm : I8mm<0b0100, (outs), (ins memdst:$dst, memsrc:$src), "mov.b\t{$src, $dst}", [(store (i8 (load addr:$src)), addr:$dst)]>; def MOV16mm : I16mm<0b0100, (outs), (ins memdst:$dst, memsrc:$src), "mov\t{$src, $dst}", [(store (i16 (load addr:$src)), addr:$dst)]>; def MOV8mn : I8mn<0b0100, (outs), (ins memdst:$dst, indreg:$rs), "mov.b\t{$rs, $dst}", []>; def MOV16mn : I16mn<0b0100, (outs), (ins memdst:$dst, indreg:$rs), "mov\t{$rs, $dst}", []>; //===----------------------------------------------------------------------===// // Arithmetic Instructions multiclass Arith<bits<4> opcode, string asmstring, SDNode node, bit commutes, list<Register> uses> { let Defs = [SR], Uses = uses in { let Constraints = "$src2 = $rd" in { let isCommutable = commutes in { def 8rr : I8rr<opcode, (outs GR8:$rd), (ins GR8:$src2, GR8:$rs), !strconcat(asmstring, ".b\t$rs, $rd"), [(set GR8:$rd, (node GR8:$src2, GR8:$rs)), (implicit SR)]>; def 16rr : I16rr<opcode, (outs GR16:$rd), (ins GR16:$src2, GR16:$rs), !strconcat(asmstring, "\t$rs, $rd"), [(set GR16:$rd, (node GR16:$src2, GR16:$rs)), (implicit SR)]>; } def 8rm : I8rm<opcode, (outs GR8:$rd), (ins GR8:$src2, memsrc:$src), !strconcat(asmstring, ".b\t$src, $rd"), [(set GR8:$rd, (node GR8:$src2, (load addr:$src))), (implicit SR)]>; def 16rm : I16rm<opcode, (outs GR16:$rd), (ins GR16:$src2, memsrc:$src), !strconcat(asmstring, "\t$src, $rd"), [(set GR16:$rd, (node GR16:$src2, (load addr:$src))), (implicit SR)]>; def 8rn : I8rn<opcode, (outs GR8:$rd), (ins GR8:$src2, indreg:$rs), !strconcat(asmstring, ".b\t$rs, $rd"), []>; def 16rn : I16rn<opcode, (outs GR16:$rd), (ins GR16:$src2, indreg:$rs), !strconcat(asmstring, "\t$rs, $rd"), []>; let mayLoad = 1, hasExtraDefRegAllocReq = 1, Constraints = "$rs = $wb, $src2 = $rd" in { def 8rp : I8rp<opcode, (outs GR8:$rd, GR16:$wb), (ins GR8:$src2, postreg:$rs), !strconcat(asmstring, ".b\t$rs, $rd"), []>; def 16rp : I16rp<opcode, (outs GR16:$rd, GR16:$wb), (ins GR16:$src2, postreg:$rs), !strconcat(asmstring, "\t$rs, $rd"), []>; } def 8rc : I8rc<opcode, (outs GR8:$rd), (ins GR8:$src2, cg8imm:$imm), !strconcat(asmstring, ".b\t$imm, $rd"), [(set GR8:$rd, (node GR8:$src2, cg8imm:$imm)), (implicit SR)]>; def 16rc : I16rc<opcode, (outs GR16:$rd), (ins GR16:$src2, cg16imm:$imm), !strconcat(asmstring, "\t$imm, $rd"), [(set GR16:$rd, (node GR16:$src2, cg16imm:$imm)), (implicit SR)]>; def 8ri : I8ri<opcode, (outs GR8:$rd), (ins GR8:$src2, i8imm:$imm), !strconcat(asmstring, ".b\t$imm, $rd"), [(set GR8:$rd, (node GR8:$src2, imm:$imm)), (implicit SR)]>; def 16ri : I16ri<opcode, (outs GR16:$rd), (ins GR16:$src2, i16imm:$imm), !strconcat(asmstring, "\t$imm, $rd"), [(set GR16:$rd, (node GR16:$src2, imm:$imm)), (implicit SR)]>; } def 8mr : I8mr<opcode, (outs), (ins memdst:$dst, GR8:$rs), !strconcat(asmstring, ".b\t$rs, $dst"), [(store (node (load addr:$dst), GR8:$rs), addr:$dst), (implicit SR)]>; def 16mr : I16mr<opcode, (outs), (ins memdst:$dst, GR16:$rs), !strconcat(asmstring, "\t$rs, $dst"), [(store (node (load addr:$dst), GR16:$rs), addr:$dst), (implicit SR)]>; def 8mc : I8mc<opcode, (outs), (ins memdst:$dst, cg8imm:$imm), !strconcat(asmstring, ".b\t$imm, $dst"), [(store (node (load addr:$dst), (i8 cg8imm:$imm)), addr:$dst), (implicit SR)]>; def 16mc : I16mc<opcode, (outs), (ins memdst:$dst, cg16imm:$imm), !strconcat(asmstring, "\t$imm, $dst"), [(store (node (load addr:$dst), (i16 cg16imm:$imm)), addr:$dst), (implicit SR)]>; def 8mi : I8mi<opcode, (outs), (ins memdst:$dst, i8imm:$imm), !strconcat(asmstring, ".b\t$imm, $dst"), [(store (node (load addr:$dst), (i8 imm:$imm)), addr:$dst), (implicit SR)]>; def 16mi : I16mi<opcode, (outs), (ins memdst:$dst, i16imm:$imm), !strconcat(asmstring, "\t$imm, $dst"), [(store (node (load addr:$dst), (i16 imm:$imm)), addr:$dst), (implicit SR)]>; def 8mm : I8mm<opcode, (outs), (ins memdst:$dst, memsrc:$src), !strconcat(asmstring, ".b\t$src, $dst"), [(store (node (load addr:$dst), (i8 (load addr:$src))), addr:$dst), (implicit SR)]>; def 16mm : I16mm<opcode, (outs), (ins memdst:$dst, memsrc:$src), !strconcat(asmstring, "\t$src, $dst"), [(store (node (load addr:$dst), (i16 (load addr:$src))), addr:$dst), (implicit SR)]>; def 8mn : I8mn<opcode, (outs), (ins memdst:$dst, indreg:$rs), !strconcat(asmstring, ".b\t$rs, $dst"), []>; def 16mn : I16mn<opcode, (outs), (ins memdst:$dst, indreg:$rs), !strconcat(asmstring, "\t$rs, $dst"), []>; def 8mp : I8mp<opcode, (outs), (ins memdst:$dst, postreg:$rs), !strconcat(asmstring, ".b\t$rs, $dst"), []>; def 16mp : I16mp<opcode, (outs), (ins memdst:$dst, postreg:$rs), !strconcat(asmstring, "\t$rs, $dst"), []>; } } defm ADD : Arith<0b0101, "add", add, 1, []>; defm ADDC : Arith<0b0110, "addc", adde, 1, [SR]>; defm AND : Arith<0b1111, "and", and, 1, []>; defm BIS : Arith<0b1101, "bis", or, 1, []>; defm BIC : Arith<0b1100, "bic", bic, 0, []>; defm XOR : Arith<0b1110, "xor", xor, 1, []>; defm SUB : Arith<0b1000, "sub", sub, 0, []>; defm SUBC : Arith<0b0111, "subc", sube, 0, [SR]>; defm DADD : Arith<0b1010, "dadd", MSP430dadd, 1, [SR]>; def ADC8r : InstAlias<"adc.b\t$dst", (ADDC8rc GR8:$dst, 0)>; def ADC16r : InstAlias<"adc\t$dst", (ADDC16rc GR16:$dst, 0)>; def ADC8m : InstAlias<"adc.b\t$dst", (ADDC8mc memdst:$dst, 0)>; def ADC16m : InstAlias<"adc\t$dst", (ADDC16mc memdst:$dst, 0)>; def DADC8r : InstAlias<"dadc.b\t$dst", (DADD8rc GR8:$dst, 0)>; def DADC16r : InstAlias<"dadc\t$dst", (DADD16rc GR16:$dst, 0)>; def DADC8m : InstAlias<"dadc.b\t$dst", (DADD8mc memdst:$dst, 0)>; def DADC16m : InstAlias<"dadc\t$dst", (DADD16mc memdst:$dst, 0)>; def DEC8r : InstAlias<"dec.b\t$dst", (SUB8rc GR8:$dst, 1)>; def DEC16r : InstAlias<"dec\t$dst", (SUB16rc GR16:$dst, 1)>; def DEC8m : InstAlias<"dec.b\t$dst", (SUB8mc memdst:$dst, 1)>; def DEC16m : InstAlias<"dec\t$dst", (SUB16mc memdst:$dst, 1)>; def DECD8r : InstAlias<"decd.b\t$dst", (SUB8rc GR8:$dst, 2)>; def DECD16r : InstAlias<"decd\t$dst", (SUB16rc GR16:$dst, 2)>; def DECD8m : InstAlias<"decd.b\t$dst", (SUB8mc memdst:$dst, 2)>; def DECD16m : InstAlias<"decd\t$dst", (SUB16mc memdst:$dst, 2)>; def INC8r : InstAlias<"inc.b\t$dst", (ADD8rc GR8:$dst, 1)>; def INC16r : InstAlias<"inc\t$dst", (ADD16rc GR16:$dst, 1)>; def INC8m : InstAlias<"inc.b\t$dst", (ADD8mc memdst:$dst, 1)>; def INC16m : InstAlias<"inc\t$dst", (ADD16mc memdst:$dst, 1)>; def INCD8r : InstAlias<"incd.b\t$dst", (ADD8rc GR8:$dst, 2)>; def INCD16r : InstAlias<"incd\t$dst", (ADD16rc GR16:$dst, 2)>; def INCD8m : InstAlias<"incd.b\t$dst", (ADD8mc memdst:$dst, 2)>; def INCD16m : InstAlias<"incd\t$dst", (ADD16mc memdst:$dst, 2)>; def SBC8r : InstAlias<"sbc.b\t$dst", (SUBC8rc GR8:$dst, 0)>; def SBC16r : InstAlias<"sbc\t$dst", (SUBC16rc GR16:$dst, 0)>; def SBC8m : InstAlias<"sbc.b\t$dst", (SUBC8mc memdst:$dst, 0)>; def SBC16m : InstAlias<"sbc\t$dst", (SUBC16mc memdst:$dst, 0)>; def INV8r : InstAlias<"inv.b\t$dst", (XOR8rc GR8:$dst, -1)>; def INV16r : InstAlias<"inv\t$dst", (XOR16rc GR16:$dst, -1)>; def INV8m : InstAlias<"inv.b\t$dst", (XOR8mc memdst:$dst, -1)>; def INV16m : InstAlias<"inv\t$dst", (XOR16mc memdst:$dst, -1)>; // printAliasInstr() doesn't check $dst operands are actually equal // for RLA and RLC aliases below, so disable printing aliases. def RLA8r : InstAlias<"rla.b\t$dst", (ADD8rr GR8:$dst, GR8:$dst), 0>; def RLA16r : InstAlias<"rla\t$dst", (ADD16rr GR16:$dst, GR16:$dst), 0>; def RLA8m : InstAlias<"rla.b\t$dst", (ADD8mm memdst:$dst, memdst:$dst), 0>; def RLA16m : InstAlias<"rla\t$dst", (ADD16mm memdst:$dst, memdst:$dst), 0>; def RLC8r : InstAlias<"rlc.b\t$dst", (ADDC8rr GR8:$dst, GR8:$dst), 0>; def RLC16r : InstAlias<"rlc\t$dst", (ADDC16rr GR16:$dst, GR16:$dst), 0>; def RLC8m : InstAlias<"rlc.b\t$dst", (ADDC8mm memdst:$dst, memdst:$dst), 0>; def RLC16m : InstAlias<"rlc\t$dst", (ADDC16mm memdst:$dst, memdst:$dst), 0>; def DINT : InstAlias<"dint", (BIC16rc SR, 8)>; def EINT : InstAlias<"eint", (BIS16rc SR, 8)>; def NOP : InstAlias<"nop", (MOV16rc CG, 0)>; def CLR8r : InstAlias<"clr.b\t$dst", (MOV8rc GR8:$dst, 0)>; def CLR16r : InstAlias<"clr\t$dst", (MOV16rc GR16:$dst, 0)>; def CLR8m : InstAlias<"clr.b\t$dst", (MOV8mc memdst:$dst, 0)>; def CLR16m : InstAlias<"clr\t$dst", (MOV16mc memdst:$dst, 0)>; def CLRC : InstAlias<"clrc", (BIC16rc SR, 1)>; def CLRN : InstAlias<"clrn", (BIC16rc SR, 4)>; def CLRZ : InstAlias<"clrz", (BIC16rc SR, 2)>; def SETC : InstAlias<"setc", (BIS16rc SR, 1)>; def SETN : InstAlias<"setn", (BIS16rc SR, 4)>; def SETZ : InstAlias<"setz", (BIS16rc SR, 2)>; def : Pat<(MSP430rla GR8:$dst), (ADD8rr $dst, $dst)>; def : Pat<(MSP430rla GR16:$dst), (ADD16rr $dst, $dst)>; // Format-II (Single Operand) Instruction // Register mode let Constraints = "$rs = $rd" in { let Defs = [SR] in { def RRA8r : II8r<0b010, (outs GR8:$rd), (ins GR8:$rs), "rra.b\t$rd", [(set GR8:$rd, (MSP430rra GR8:$rs)), (implicit SR)]>; def RRA16r : II16r<0b010, (outs GR16:$rd), (ins GR16:$rs), "rra\t$rd", [(set GR16:$rd, (MSP430rra GR16:$rs)), (implicit SR)]>; let Uses = [SR] in { def RRC8r : II8r<0b000, (outs GR8:$rd), (ins GR8:$rs), "rrc.b\t$rd", [(set GR8:$rd, (MSP430rrc GR8:$rs)), (implicit SR)]>; def RRC16r : II16r<0b000, (outs GR16:$rd), (ins GR16:$rs), "rrc\t$rd", [(set GR16:$rd, (MSP430rrc GR16:$rs)), (implicit SR)]>; } // Uses = [SR] def SEXT16r : II16r<0b011, (outs GR16:$rd), (ins GR16:$rs), "sxt\t$rd", [(set GR16:$rd, (sext_inreg GR16:$rs, i8)), (implicit SR)]>; } // Defs = [SR] let isCodeGenOnly = 1 in def ZEXT16r : I8rr<0b0100, (outs GR16:$rd), (ins GR16:$rs), "mov.b\t{$rs, $rd}", [(set GR16:$rd, (zext (trunc GR16:$rs)))]>; def SWPB16r : II16r<0b001, (outs GR16:$rd), (ins GR16:$rs), "swpb\t$rd", [(set GR16:$rd, (bswap GR16:$rs))]>; } // Constraints = "$src = $dst" // Indexed, indirect register and indirect autoincrement modes let Defs = [SR] in { def RRA8m : II8m<0b010, (outs), (ins memsrc:$src), "rra.b\t$src", [(store (MSP430rra (i8 (load addr:$src))), addr:$src), (implicit SR)]>; def RRA16m : II16m<0b010, (outs), (ins memsrc:$src), "rra\t$src", [(store (MSP430rra (i16 (load addr:$src))), addr:$src), (implicit SR)]>; def RRA8n : II8n<0b010, (outs), (ins indreg:$rs), "rra.b\t$rs", []>; def RRA16n : II16n<0b010, (outs), (ins indreg:$rs), "rra\t$rs", []>; def RRA8p : II8p<0b010, (outs), (ins postreg:$rs), "rra.b\t$rs", []>; def RRA16p : II16p<0b010, (outs), (ins postreg:$rs), "rra\t$rs", []>; let Uses = [SR] in { def RRC8m : II8m<0b000, (outs), (ins memsrc:$src), "rrc.b\t$src", [(store (MSP430rrc (i8 (load addr:$src))), addr:$src), (implicit SR)]>; def RRC16m : II16m<0b000, (outs), (ins memsrc:$src), "rrc\t$src", [(store (MSP430rrc (i16 (load addr:$src))), addr:$src), (implicit SR)]>; def RRC8n : II8n<0b000, (outs), (ins indreg:$rs), "rrc.b\t$rs", []>; def RRC16n : II16n<0b000, (outs), (ins indreg:$rs), "rrc\t$rs", []>; def RRC8p : II8p<0b000, (outs), (ins postreg:$rs), "rrc.b\t$rs", []>; def RRC16p : II16p<0b000, (outs), (ins postreg:$rs), "rrc\t$rs", []>; } // Uses = [SR] def SEXT16m : II16m<0b011, (outs), (ins memsrc:$src), "sxt\t$src", [(store (sext_inreg (extloadi16i8 addr:$src), i8), addr:$src), (implicit SR)]>; def SEXT16n : II16n<0b011, (outs), (ins indreg:$rs), "sxt\t$rs", []>; def SEXT16p : II16p<0b011, (outs), (ins postreg:$rs), "sxt\t$rs", []>; } // Defs = [SR] def SWPB16m : II16m<0b001, (outs), (ins memsrc:$src), "swpb\t$src", [(store (bswap (i16 (load addr:$src))), addr:$src)]>; def SWPB16n : II16n<0b001, (outs), (ins indreg:$rs), "swpb\t$rs", []>; def SWPB16p : II16p<0b001, (outs), (ins postreg:$rs), "swpb\t$rs", []>; // Integer comparisons let Defs = [SR] in { def CMP8rr : I8rr<0b1001, (outs), (ins GR8:$rd, GR8:$rs), "cmp.b\t$rs, $rd", [(MSP430cmp GR8:$rd, GR8:$rs), (implicit SR)]>; def CMP16rr : I16rr<0b1001, (outs), (ins GR16:$rd, GR16:$rs), "cmp\t$rs, $rd", [(MSP430cmp GR16:$rd, GR16:$rs), (implicit SR)]>; def CMP8rc : I8rc<0b1001, (outs), (ins GR8:$rd, cg8imm:$imm), "cmp.b\t$imm, $rd", [(MSP430cmp GR8:$rd, cg8imm:$imm), (implicit SR)]>; def CMP16rc : I16rc<0b1001, (outs), (ins GR16:$rd, cg16imm:$imm), "cmp\t$imm, $rd", [(MSP430cmp GR16:$rd, cg16imm:$imm), (implicit SR)]>; def CMP8ri : I8ri<0b1001, (outs), (ins GR8:$rd, i8imm:$imm), "cmp.b\t$imm, $rd", [(MSP430cmp GR8:$rd, imm:$imm), (implicit SR)]>; def CMP16ri : I16ri<0b1001, (outs), (ins GR16:$rd, i16imm:$imm), "cmp\t$imm, $rd", [(MSP430cmp GR16:$rd, imm:$imm), (implicit SR)]>; def CMP8mc : I8mc<0b1001, (outs), (ins memsrc:$dst, cg8imm:$imm), "cmp.b\t$imm, $dst", [(MSP430cmp (load addr:$dst), (i8 cg8imm:$imm)), (implicit SR)]>; def CMP16mc : I16mc<0b1001, (outs), (ins memsrc:$dst, cg16imm:$imm), "cmp\t$imm, $dst", [(MSP430cmp (load addr:$dst), (i16 cg16imm:$imm)), (implicit SR)]>; def CMP8mi : I8mi<0b1001, (outs), (ins memsrc:$dst, i8imm:$imm), "cmp.b\t$imm, $dst", [(MSP430cmp (load addr:$dst), (i8 imm:$imm)), (implicit SR)]>; def CMP16mi : I16mi<0b1001, (outs), (ins memsrc:$dst, i16imm:$imm), "cmp\t$imm, $dst", [(MSP430cmp (load addr:$dst), (i16 imm:$imm)), (implicit SR)]>; def CMP8rm : I8rm<0b1001, (outs), (ins GR8:$rd, memsrc:$src), "cmp.b\t$src, $rd", [(MSP430cmp GR8:$rd, (load addr:$src)), (implicit SR)]>; def CMP16rm : I16rm<0b1001, (outs), (ins GR16:$rd, memsrc:$src), "cmp\t$src, $rd", [(MSP430cmp GR16:$rd, (load addr:$src)), (implicit SR)]>; def CMP8rn : I8rn<0b1001, (outs), (ins GR8:$rd, indreg:$rs), "cmp.b\t$rs, $rd", []>; def CMP16rn : I16rn<0b1001, (outs), (ins GR16:$rd, indreg:$rs), "cmp\t$rs, $rd", []>; def CMP8rp : I8rp<0b1001, (outs), (ins GR8:$rd, postreg:$rs), "cmp.b\t$rs, $rd", []>; def CMP16rp : I16rp<0b1001, (outs), (ins GR16:$rd, postreg:$rs), "cmp\t$rs, $rd", []>; def CMP8mr : I8mr<0b1001, (outs), (ins memsrc:$dst, GR8:$rs), "cmp.b\t$rs, $dst", [(MSP430cmp (load addr:$dst), GR8:$rs), (implicit SR)]>; def CMP16mr : I16mr<0b1001, (outs), (ins memsrc:$dst, GR16:$rs), "cmp\t$rs, $dst", [(MSP430cmp (load addr:$dst), GR16:$rs), (implicit SR)]>; def CMP8mm : I8mm<0b1001, (outs), (ins memdst:$dst, memsrc:$src), "cmp.b\t$src, $dst", [(MSP430cmp (load addr:$dst), (i8 (load addr:$src))), (implicit SR)]>; def CMP16mm : I16mm<0b1001, (outs), (ins memdst:$dst, memsrc:$src), "cmp\t$src, $dst", [(MSP430cmp (load addr:$dst), (i16 (load addr:$src))), (implicit SR)]>; def CMP8mn : I8mn<0b1001, (outs), (ins memsrc:$dst, indreg:$rs), "cmp.b\t$rs, $dst", []>; def CMP16mn : I16mn<0b1001, (outs), (ins memsrc:$dst, indreg:$rs), "cmp\t$rs, $dst", []>; def CMP8mp : I8mp<0b1001, (outs), (ins memsrc:$dst, postreg:$rs), "cmp.b\t$rs, $dst", []>; def CMP16mp : I16mp<0b1001, (outs), (ins memsrc:$dst, postreg:$rs), "cmp\t$rs, $dst", []>; // BIT TESTS, just sets condition codes // Note that the C condition is set differently than when using CMP. let isCommutable = 1 in { def BIT8rr : I8rr<0b1011, (outs), (ins GR8:$rd, GR8:$rs), "bit.b\t$rs, $rd", [(MSP430cmp (and_su GR8:$rd, GR8:$rs), 0), (implicit SR)]>; def BIT16rr : I16rr<0b1011, (outs), (ins GR16:$rd, GR16:$rs), "bit\t$rs, $rd", [(MSP430cmp (and_su GR16:$rd, GR16:$rs), 0), (implicit SR)]>; } def BIT8rc : I8rc<0b1011, (outs), (ins GR8:$rd, cg8imm:$imm), "bit.b\t$imm, $rd", [(MSP430cmp (and_su GR8:$rd, cg8imm:$imm), 0), (implicit SR)]>; def BIT16rc : I16rc<0b1011, (outs), (ins GR16:$rd, cg16imm:$imm), "bit\t$imm, $rd", [(MSP430cmp (and_su GR16:$rd, cg16imm:$imm), 0), (implicit SR)]>; def BIT8ri : I8ri<0b1011, (outs), (ins GR8:$rd, i8imm:$imm), "bit.b\t$imm, $rd", [(MSP430cmp (and_su GR8:$rd, imm:$imm), 0), (implicit SR)]>; def BIT16ri : I16ri<0b1011, (outs), (ins GR16:$rd, i16imm:$imm), "bit\t$imm, $rd", [(MSP430cmp (and_su GR16:$rd, imm:$imm), 0), (implicit SR)]>; def BIT8rm : I8rm<0b1011, (outs), (ins GR8:$rd, memdst:$src), "bit.b\t$src, $rd", [(MSP430cmp (and_su GR8:$rd, (load addr:$src)), 0), (implicit SR)]>; def BIT16rm : I16rm<0b1011, (outs), (ins GR16:$rd, memdst:$src), "bit\t$src, $rd", [(MSP430cmp (and_su GR16:$rd, (load addr:$src)), 0), (implicit SR)]>; def BIT8rn : I8rn<0b1011, (outs), (ins GR8:$rd, indreg:$rs), "bit.b\t$rs, $rd", []>; def BIT16rn : I16rn<0b1011, (outs), (ins GR16:$rd, indreg:$rs), "bit\t$rs, $rd", []>; def BIT8rp : I8rp<0b1011, (outs), (ins GR8:$rd, postreg:$rs), "bit.b\t$rs, $rd", []>; def BIT16rp : I16rp<0b1011, (outs), (ins GR16:$rd, postreg:$rs), "bit\t$rs, $rd", []>; def BIT8mr : I8mr<0b1011, (outs), (ins memsrc:$dst, GR8:$rs), "bit.b\t$rs, $dst", [(MSP430cmp (and_su (load addr:$dst), GR8:$rs), 0), (implicit SR)]>; def BIT16mr : I16mr<0b1011, (outs), (ins memsrc:$dst, GR16:$rs), "bit\t$rs, $dst", [(MSP430cmp (and_su (load addr:$dst), GR16:$rs), 0), (implicit SR)]>; def BIT8mc : I8mc<0b1011, (outs), (ins memsrc:$dst, cg8imm:$imm), "bit.b\t$imm, $dst", [(MSP430cmp (and_su (load addr:$dst), (i8 cg8imm:$imm)), 0), (implicit SR)]>; def BIT16mc : I16mc<0b1011, (outs), (ins memdst:$dst, cg16imm:$imm), "bit\t$imm, $dst", [(MSP430cmp (and_su (load addr:$dst), (i16 cg16imm:$imm)), 0), (implicit SR)]>; def BIT8mi : I8mi<0b1011, (outs), (ins memsrc:$dst, i8imm:$imm), "bit.b\t$imm, $dst", [(MSP430cmp (and_su (load addr:$dst), (i8 imm:$imm)), 0), (implicit SR)]>; def BIT16mi : I16mi<0b1011, (outs), (ins memsrc:$dst, i16imm:$imm), "bit\t$imm, $dst", [(MSP430cmp (and_su (load addr:$dst), (i16 imm:$imm)), 0), (implicit SR)]>; def BIT8mm : I8mm<0b1011, (outs), (ins memsrc:$dst, memsrc:$src), "bit.b\t$src, $dst", [(MSP430cmp (and_su (i8 (load addr:$dst)), (load addr:$src)), 0), (implicit SR)]>; def BIT16mm : I16mm<0b1011, (outs), (ins memsrc:$dst, memsrc:$src), "bit\t$src, $dst", [(MSP430cmp (and_su (i16 (load addr:$dst)), (load addr:$src)), 0), (implicit SR)]>; def BIT8mn : I8mn<0b1011, (outs), (ins memsrc:$dst, indreg:$rs), "bit.b\t$rs, $dst", []>; def BIT16mn : I16mn<0b1011, (outs), (ins memsrc:$dst, indreg:$rs), "bit\t$rs, $dst", []>; def BIT8mp : I8mp<0b1011, (outs), (ins memsrc:$dst, postreg:$rs), "bit.b\t$rs, $dst", []>; def BIT16mp : I16mp<0b1011, (outs), (ins memsrc:$dst, postreg:$rs), "bit\t$rs, $dst", []>; } // Defs = [SR] def TST8r : InstAlias<"tst.b\t$dst", (CMP8rc GR8:$dst, 0)>; def TST16r : InstAlias<"tst\t$dst", (CMP16rc GR16:$dst, 0)>; def TST8m : InstAlias<"tst.b\t$dst", (CMP8mc memdst:$dst, 0)>; def TST16m : InstAlias<"tst\t$dst", (CMP16mc memdst:$dst, 0)>; //===----------------------------------------------------------------------===// // Non-Instruction Patterns // extload def : Pat<(extloadi16i8 addr:$src), (MOVZX16rm8 addr:$src)>; // anyext def : Pat<(i16 (anyext GR8:$src)), (SUBREG_TO_REG (i16 0), GR8:$src, subreg_8bit)>; // truncs def : Pat<(i8 (trunc GR16:$src)), (EXTRACT_SUBREG GR16:$src, subreg_8bit)>; // GlobalAddress, ExternalSymbol def : Pat<(i16 (MSP430Wrapper tglobaladdr:$dst)), (MOV16ri tglobaladdr:$dst)>; def : Pat<(i16 (MSP430Wrapper texternalsym:$dst)), (MOV16ri texternalsym:$dst)>; def : Pat<(i16 (MSP430Wrapper tblockaddress:$dst)), (MOV16ri tblockaddress:$dst)>; def : Pat<(add GR16:$src, (MSP430Wrapper tglobaladdr :$src2)), (ADD16ri GR16:$src, tglobaladdr:$src2)>; def : Pat<(add GR16:$src, (MSP430Wrapper texternalsym:$src2)), (ADD16ri GR16:$src, texternalsym:$src2)>; def : Pat<(add GR16:$src, (MSP430Wrapper tblockaddress:$src2)), (ADD16ri GR16:$src, tblockaddress:$src2)>; def : Pat<(store (i16 (MSP430Wrapper tglobaladdr:$src)), addr:$dst), (MOV16mi addr:$dst, tglobaladdr:$src)>; def : Pat<(store (i16 (MSP430Wrapper texternalsym:$src)), addr:$dst), (MOV16mi addr:$dst, texternalsym:$src)>; def : Pat<(store (i16 (MSP430Wrapper tblockaddress:$src)), addr:$dst), (MOV16mi addr:$dst, tblockaddress:$src)>; // calls def : Pat<(MSP430call (i16 tglobaladdr:$dst)), (CALLi tglobaladdr:$dst)>; def : Pat<(MSP430call (i16 texternalsym:$dst)), (CALLi texternalsym:$dst)>; // add and sub always produce carry def : Pat<(addc GR16:$src, GR16:$src2), (ADD16rr GR16:$src, GR16:$src2)>; def : Pat<(addc GR16:$src, (load addr:$src2)), (ADD16rm GR16:$src, addr:$src2)>; def : Pat<(addc GR16:$src, imm:$src2), (ADD16ri GR16:$src, imm:$src2)>; def : Pat<(store (addc (load addr:$dst), GR16:$src), addr:$dst), (ADD16mr addr:$dst, GR16:$src)>; def : Pat<(store (addc (load addr:$dst), (i16 (load addr:$src))), addr:$dst), (ADD16mm addr:$dst, addr:$src)>; def : Pat<(addc GR8:$src, GR8:$src2), (ADD8rr GR8:$src, GR8:$src2)>; def : Pat<(addc GR8:$src, (load addr:$src2)), (ADD8rm GR8:$src, addr:$src2)>; def : Pat<(addc GR8:$src, imm:$src2), (ADD8ri GR8:$src, imm:$src2)>; def : Pat<(store (addc (load addr:$dst), GR8:$src), addr:$dst), (ADD8mr addr:$dst, GR8:$src)>; def : Pat<(store (addc (load addr:$dst), (i8 (load addr:$src))), addr:$dst), (ADD8mm addr:$dst, addr:$src)>; def : Pat<(subc GR16:$src, GR16:$src2), (SUB16rr GR16:$src, GR16:$src2)>; def : Pat<(subc GR16:$src, (load addr:$src2)), (SUB16rm GR16:$src, addr:$src2)>; def : Pat<(subc GR16:$src, imm:$src2), (SUB16ri GR16:$src, imm:$src2)>; def : Pat<(store (subc (load addr:$dst), GR16:$src), addr:$dst), (SUB16mr addr:$dst, GR16:$src)>; def : Pat<(store (subc (load addr:$dst), (i16 (load addr:$src))), addr:$dst), (SUB16mm addr:$dst, addr:$src)>; def : Pat<(subc GR8:$src, GR8:$src2), (SUB8rr GR8:$src, GR8:$src2)>; def : Pat<(subc GR8:$src, (load addr:$src2)), (SUB8rm GR8:$src, addr:$src2)>; def : Pat<(subc GR8:$src, imm:$src2), (SUB8ri GR8:$src, imm:$src2)>; def : Pat<(store (subc (load addr:$dst), GR8:$src), addr:$dst), (SUB8mr addr:$dst, GR8:$src)>; def : Pat<(store (subc (load addr:$dst), (i8 (load addr:$src))), addr:$dst), (SUB8mm addr:$dst, addr:$src)>; // peephole patterns def : Pat<(and GR16:$src, 255), (ZEXT16r GR16:$src)>; def : Pat<(MSP430cmp (trunc (and_su GR16:$src, GR16:$src2)), 0), (BIT8rr (EXTRACT_SUBREG GR16:$src, subreg_8bit), (EXTRACT_SUBREG GR16:$src2, subreg_8bit))>;
0
0.914455
1
0.914455
game-dev
MEDIA
0.262852
game-dev
0.92996
1
0.92996
gitclonparis/ninpai
8,621
ThreeBarBreakoutIndicator.cs
#region Using declarations using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Input; using System.Windows.Media; using System.Xml.Serialization; using NinjaTrader.Cbi; using NinjaTrader.Gui; using NinjaTrader.Gui.Chart; using NinjaTrader.Gui.SuperDom; using NinjaTrader.Gui.Tools; using NinjaTrader.Data; using NinjaTrader.NinjaScript; using NinjaTrader.Core.FloatingPoint; using NinjaTrader.NinjaScript.DrawingTools; #endregion //This namespace holds Indicators in this folder and is required. Do not change it. //This namespace holds Indicators in this folder and is required. Do not change it. namespace NinjaTrader.NinjaScript.Indicators.ninpai { public class ThreeBarBreakoutIndicator : Indicator { private int setupFound; private double highestHighOfRange; private double lowestLowOfRange; // Propriétés publiques pour accéder aux signaux public bool IsUpBreakout { get; private set; } public bool IsDownBreakout { get; private set; } public int SetupFound { get; private set; } protected override void OnStateChange() { if (State == State.SetDefaults) { Description = @"Détecte un setup de 3 barres avec breakout"; Name = "ThreeBarBreakoutIndicator"; Calculate = Calculate.OnBarClose; IsOverlay = true; DisplayInDataBox = true; DrawOnPricePanel = true; DrawHorizontalGridLines = true; DrawVerticalGridLines = true; PaintPriceMarkers = true; ScaleJustification = NinjaTrader.Gui.Chart.ScaleJustification.Right; IsSuspendedWhileInactive = true; UpArrowColor = Brushes.LimeGreen; DownArrowColor = Brushes.Red; ShowUpArrows = true; ShowDownArrows = true; } else if (State == State.Configure) { AddPlot(Brushes.Transparent, "Plot"); } } protected override void OnBarUpdate() { // Vérifier qu'on a suffisamment de barres if (CurrentBar < 3) return; bool isUpBreakout = false; bool isDownBreakout = false; // Appeler la méthode pour détecter le pattern CheckThreeBarPattern(0, out isUpBreakout, out isDownBreakout); // Mettre à jour les valeurs de l'indicateur et les propriétés publiques Values[0][0] = setupFound; // Mettre à jour les propriétés publiques pour l'accès externe SetupFound = setupFound; IsUpBreakout = isUpBreakout; IsDownBreakout = isDownBreakout; } // Méthode pour vérifier le pattern sur 3 barres private void CheckThreeBarPattern(int barsAgo, out bool isUpBreakout, out bool isDownBreakout) { isUpBreakout = false; isDownBreakout = false; // Déterminer les extrémités hautes et basses basées sur Open et Close pour barre1 et barre2 double high1 = Math.Max(Open[barsAgo + 1], Close[barsAgo + 1]); double low1 = Math.Min(Open[barsAgo + 1], Close[barsAgo + 1]); double high2 = Math.Max(Open[barsAgo + 2], Close[barsAgo + 2]); double low2 = Math.Min(Open[barsAgo + 2], Close[barsAgo + 2]); // Vérifier si l'une est inside ou outside par rapport à l'autre bool isInsideBarPattern = (high1 <= high2 && low1 >= low2) || (high2 <= high1 && low2 >= low1); if (isInsideBarPattern) { // Définir le range entre Barre1 et Barre2 highestHighOfRange = Math.Max(high1, high2); lowestLowOfRange = Math.Min(low1, low2); // Vérifier si Barre0 casse le close de Barre1 if (Close[barsAgo] > Close[barsAgo + 1] && Close[barsAgo] > highestHighOfRange) { // Cassure par le haut isUpBreakout = true; if (ShowUpArrows) { Draw.ArrowUp(this, "UpArrow" + CurrentBar.ToString(), true, barsAgo, Math.Min(Open[barsAgo] - 10 * TickSize, Close[barsAgo]), UpArrowColor); } setupFound = 1; } else if (Close[barsAgo] < Close[barsAgo + 1] && Close[barsAgo] < lowestLowOfRange) { // Cassure par le bas isDownBreakout = true; if (ShowDownArrows) { Draw.ArrowDown(this, "DownArrow" + CurrentBar.ToString(), true, barsAgo, Math.Max(Open[barsAgo] + 10 * TickSize, Close[barsAgo]), DownArrowColor); } setupFound = -1; } else { setupFound = 0; } } else { setupFound = 0; } } #region Properties [XmlIgnore] [Display(Name = "Couleur de la flèche haussière", Order = 1, GroupName = "Paramètres")] public Brush UpArrowColor { get; set; } [Browsable(false)] public string UpArrowColorSerializable { get { return Serialize.BrushToString(UpArrowColor); } set { UpArrowColor = Serialize.StringToBrush(value); } } [XmlIgnore] [Display(Name = "Couleur de la flèche baissière", Order = 2, GroupName = "Paramètres")] public Brush DownArrowColor { get; set; } [Browsable(false)] public string DownArrowColorSerializable { get { return Serialize.BrushToString(DownArrowColor); } set { DownArrowColor = Serialize.StringToBrush(value); } } [Display(Name = "Afficher les flèches haussières", Order = 3, GroupName = "Paramètres")] public bool ShowUpArrows { get; set; } [Display(Name = "Afficher les flèches baissières", Order = 4, GroupName = "Paramètres")] public bool ShowDownArrows { get; set; } #endregion } } #region NinjaScript generated code. Neither change nor remove. namespace NinjaTrader.NinjaScript.Indicators { public partial class Indicator : NinjaTrader.Gui.NinjaScript.IndicatorRenderBase { private ninpai.ThreeBarBreakoutIndicator[] cacheThreeBarBreakoutIndicator; public ninpai.ThreeBarBreakoutIndicator ThreeBarBreakoutIndicator() { return ThreeBarBreakoutIndicator(Input); } public ninpai.ThreeBarBreakoutIndicator ThreeBarBreakoutIndicator(ISeries<double> input) { if (cacheThreeBarBreakoutIndicator != null) for (int idx = 0; idx < cacheThreeBarBreakoutIndicator.Length; idx++) if (cacheThreeBarBreakoutIndicator[idx] != null && cacheThreeBarBreakoutIndicator[idx].EqualsInput(input)) return cacheThreeBarBreakoutIndicator[idx]; return CacheIndicator<ninpai.ThreeBarBreakoutIndicator>(new ninpai.ThreeBarBreakoutIndicator(), input, ref cacheThreeBarBreakoutIndicator); } } } namespace NinjaTrader.NinjaScript.MarketAnalyzerColumns { public partial class MarketAnalyzerColumn : MarketAnalyzerColumnBase { public Indicators.ninpai.ThreeBarBreakoutIndicator ThreeBarBreakoutIndicator() { return indicator.ThreeBarBreakoutIndicator(Input); } public Indicators.ninpai.ThreeBarBreakoutIndicator ThreeBarBreakoutIndicator(ISeries<double> input ) { return indicator.ThreeBarBreakoutIndicator(input); } } } namespace NinjaTrader.NinjaScript.Strategies { public partial class Strategy : NinjaTrader.Gui.NinjaScript.StrategyRenderBase { public Indicators.ninpai.ThreeBarBreakoutIndicator ThreeBarBreakoutIndicator() { return indicator.ThreeBarBreakoutIndicator(Input); } public Indicators.ninpai.ThreeBarBreakoutIndicator ThreeBarBreakoutIndicator(ISeries<double> input ) { return indicator.ThreeBarBreakoutIndicator(input); } } } #endregion
0
0.904783
1
0.904783
game-dev
MEDIA
0.72326
game-dev
0.975565
1
0.975565
rehlds/ReGameDLL_CS
3,589
regamedll/dlls/addons/trigger_setorigin.h
/* * * 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 * */ #pragma once #define SF_SETORIGIN_CONST_UPDATE BIT(0) // The entity will constantly update position if set #define SF_SETORIGIN_REMOVEFIRE BIT(2) // The entity will be removed after firing. #define SF_SETORIGIN_LOCK_OFFSETS BIT(3) // Save the offset between the Target entity and the Copy pointer, // apply offset when updating the Target entity's position (Requires "Constant" flag) #define SF_SETORIGIN_COPY_ANGLE_X BIT(4) #define SF_SETORIGIN_COPY_ANGLE_Y BIT(5) #define SF_SETORIGIN_COPY_ANGLE_Z BIT(6) #define SF_SETORIGIN_COPY_AXIS_X BIT(7) #define SF_SETORIGIN_COPY_AXIS_Y BIT(8) #define SF_SETORIGIN_COPY_AXIS_Z BIT(9) #define SF_SETORIGIN_SKIP_INITIAL BIT(10) // If you're using the Constant flag, check this box to NOT move the origin of the entity or set the angles initially. // If you're not using the Constant flag, make sure this isn't enabled or trigger_setorigin won't do anything. // // This allows the "Constant" + "offset difference" combination to work as intended from the entity's original location. // // You would leave this off if you needed to move the entity to an initial position before having it follow another entity. // (If this isn't set, trigger_setorigin will move the entity to it's copypointer's origin before doing the offset difference calculation) const int MAX_SETORIGIN_ENTITIES = 64; class CTriggerSetOrigin: public CBaseDelay { public: void KeyValue(KeyValueData *pkvd); int ObjectCaps() { return CBaseEntity::ObjectCaps() & ~FCAP_ACROSS_TRANSITION; } void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value); void OnCreate(); void OnDestroy(); protected: friend class CTriggerSetOriginManager; void UpdateTick(); void SetupEntities(); void UpdateKnownEntities(); private: EntityHandle<CBaseEntity> m_hCopyPointer; EntityHandle<CBaseEntity> m_hEntities[MAX_SETORIGIN_ENTITIES]; Vector m_vecEntities[MAX_SETORIGIN_ENTITIES]; Vector m_vecOffset; Vector m_vecAngleOffset; bool m_bAngleInvertX; bool m_bAngleInvertY; bool m_bAngleInvertZ; int m_entityNum; int m_triggerType; string_t m_copyPointer; bool m_bUpdateEntities; bool m_bSetupEntities; }; class CTriggerSetOriginManager { public: CTriggerSetOriginManager() {} void Add(CTriggerSetOrigin *pInstance); void Remove(CTriggerSetOrigin *pInstance); void Update(); static CTriggerSetOriginManager *getInstance() { static CTriggerSetOriginManager *pInstance = new CTriggerSetOriginManager; return pInstance; } private: CUtlVector<EntityHandle<CTriggerSetOrigin>> m_Entities; };
0
0.899578
1
0.899578
game-dev
MEDIA
0.701655
game-dev
0.506774
1
0.506774
lrre-foss/rnr
1,805
Projects/Engine/Header/App/Script/Bridge.hpp
#pragma once #include <string> #include <vector> #include <lua.h> #include <lualib.h> #include <OGRE/Ogre.h> #include <App/V8/Tree/Instance.hpp> namespace RNR::Lua { // TODO: rewrite this system in a potentional v2.0.0? class IBridge { protected: std::vector<luaL_Reg> m_classLibrary; std::vector<luaL_Reg> m_metatableLibrary; virtual void registerClassLibrary(); public: static std::map<std::string, IBridge*> bridges; void load(); virtual std::string className(); luaL_Reg* classLibrary() { return m_classLibrary.data(); }; void addMetatable(lua_State* l); }; class Vector3Bridge : public IBridge { private: // lua methods static int lua_new(lua_State* l); protected: virtual void registerClassLibrary(); public: void fromVector3(lua_State* l, Ogre::Vector3 vec); Ogre::Vector3 toVector3(lua_State* l, int index); Vector3Bridge() { load(); } virtual std::string className() { return "Vector3"; } static Vector3Bridge* singleton() { return (Vector3Bridge*)IBridge::bridges["Vector3"]; } }; class InstanceBridge : public IBridge { private: static int lua_new(lua_State* l); static int lua_index(lua_State* l); static int lua_new_index(lua_State* l); protected: virtual void registerClassLibrary(); public: void fromInstance(lua_State* l, Instance* instance); Instance* toInstance(lua_State* l, int index); InstanceBridge() { load(); } virtual std::string className() { return "Instance"; } static const int TAG = 0x1a; static InstanceBridge* singleton() { return (InstanceBridge*)IBridge::bridges["Instance"]; } }; }
0
0.834883
1
0.834883
game-dev
MEDIA
0.46469
game-dev
0.592015
1
0.592015
Arkania/ArkCORE-NG
7,851
src/server/scripts/Commands/cs_event.cpp
/* * Copyright (C) 2008-2014 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2011-2016 ArkCORE <http://www.arkania.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, see <http://www.gnu.org/licenses/>. */ /* ScriptData Name: event_commandscript %Complete: 100 Comment: All event related commands Category: commandscripts EndScriptData */ #include "Chat.h" #include "GameEventMgr.h" #include "Language.h" #include "Player.h" #include "ScriptMgr.h" class event_commandscript : public CommandScript { public: event_commandscript() : CommandScript("event_commandscript") { } ChatCommand* GetCommands() const override { static ChatCommand eventCommandTable[] = { { "activelist", rbac::RBAC_PERM_COMMAND_EVENT_ACTIVELIST, true, &HandleEventActiveListCommand, "", NULL }, { "start", rbac::RBAC_PERM_COMMAND_EVENT_START, true, &HandleEventStartCommand, "", NULL }, { "stop", rbac::RBAC_PERM_COMMAND_EVENT_STOP, true, &HandleEventStopCommand, "", NULL }, { "", rbac::RBAC_PERM_COMMAND_EVENT, true, &HandleEventInfoCommand, "", NULL }, { NULL, 0, false, NULL, "", NULL } }; static ChatCommand commandTable[] = { { "event", rbac::RBAC_PERM_COMMAND_EVENT, false, NULL, "", eventCommandTable }, { NULL, 0, false, NULL, "", NULL } }; return commandTable; } static bool HandleEventActiveListCommand(ChatHandler* handler, char const* /*args*/) { uint32 counter = 0; GameEventMgr::GameEventDataMap const& events = sGameEventMgr->GetEventMap(); GameEventMgr::ActiveEvents const& activeEvents = sGameEventMgr->GetActiveEventList(); char const* active = handler->GetTrinityString(LANG_ACTIVE); for (GameEventMgr::ActiveEvents::const_iterator itr = activeEvents.begin(); itr != activeEvents.end(); ++itr) { uint32 eventId = *itr; GameEventData const& eventData = events[eventId]; if (handler->GetSession()) handler->PSendSysMessage(LANG_EVENT_ENTRY_LIST_CHAT, eventId, eventId, eventData.description.c_str(), active); else handler->PSendSysMessage(LANG_EVENT_ENTRY_LIST_CONSOLE, eventId, eventData.description.c_str(), active); ++counter; } if (counter == 0) handler->SendSysMessage(LANG_NOEVENTFOUND); handler->SetSentErrorMessage(true); return true; } static bool HandleEventInfoCommand(ChatHandler* handler, char const* args) { if (!*args) return false; // id or [name] Shift-click form |color|Hgameevent:id|h[name]|h|r char* id = handler->extractKeyFromLink((char*)args, "Hgameevent"); if (!id) return false; uint32 eventId = atoi(id); GameEventMgr::GameEventDataMap const& events = sGameEventMgr->GetEventMap(); if (eventId >= events.size()) { handler->SendSysMessage(LANG_EVENT_NOT_EXIST); handler->SetSentErrorMessage(true); return false; } GameEventData const& eventData = events[eventId]; if (!eventData.isValid()) { handler->SendSysMessage(LANG_EVENT_NOT_EXIST); handler->SetSentErrorMessage(true); return false; } GameEventMgr::ActiveEvents const& activeEvents = sGameEventMgr->GetActiveEventList(); bool active = activeEvents.find(eventId) != activeEvents.end(); char const* activeStr = active ? handler->GetTrinityString(LANG_ACTIVE) : ""; std::string startTimeStr = TimeToTimestampStr(eventData.start); std::string endTimeStr = TimeToTimestampStr(eventData.end); uint32 delay = sGameEventMgr->NextCheck(eventId); time_t nextTime = time(NULL) + delay; std::string nextStr = nextTime >= eventData.start && nextTime < eventData.end ? TimeToTimestampStr(time(NULL) + delay) : "-"; std::string occurenceStr = secsToTimeString(eventData.occurence * MINUTE); std::string lengthStr = secsToTimeString(eventData.length * MINUTE); handler->PSendSysMessage(LANG_EVENT_INFO, eventId, eventData.description.c_str(), activeStr, startTimeStr.c_str(), endTimeStr.c_str(), occurenceStr.c_str(), lengthStr.c_str(), nextStr.c_str()); return true; } static bool HandleEventStartCommand(ChatHandler* handler, char const* args) { if (!*args) return false; // id or [name] Shift-click form |color|Hgameevent:id|h[name]|h|r char* id = handler->extractKeyFromLink((char*)args, "Hgameevent"); if (!id) return false; int32 eventId = atoi(id); GameEventMgr::GameEventDataMap const& events = sGameEventMgr->GetEventMap(); if (eventId < 1 || uint32(eventId) >= events.size()) { handler->SendSysMessage(LANG_EVENT_NOT_EXIST); handler->SetSentErrorMessage(true); return false; } GameEventData const& eventData = events[eventId]; if (!eventData.isValid()) { handler->SendSysMessage(LANG_EVENT_NOT_EXIST); handler->SetSentErrorMessage(true); return false; } GameEventMgr::ActiveEvents const& activeEvents = sGameEventMgr->GetActiveEventList(); if (activeEvents.find(eventId) != activeEvents.end()) { handler->PSendSysMessage(LANG_EVENT_ALREADY_ACTIVE, eventId); handler->SetSentErrorMessage(true); return false; } sGameEventMgr->StartEvent(eventId, true); return true; } static bool HandleEventStopCommand(ChatHandler* handler, char const* args) { if (!*args) return false; // id or [name] Shift-click form |color|Hgameevent:id|h[name]|h|r char* id = handler->extractKeyFromLink((char*)args, "Hgameevent"); if (!id) return false; int32 eventId = atoi(id); GameEventMgr::GameEventDataMap const& events = sGameEventMgr->GetEventMap(); if (eventId < 1 || uint32(eventId) >= events.size()) { handler->SendSysMessage(LANG_EVENT_NOT_EXIST); handler->SetSentErrorMessage(true); return false; } GameEventData const& eventData = events[eventId]; if (!eventData.isValid()) { handler->SendSysMessage(LANG_EVENT_NOT_EXIST); handler->SetSentErrorMessage(true); return false; } GameEventMgr::ActiveEvents const& activeEvents = sGameEventMgr->GetActiveEventList(); if (activeEvents.find(eventId) == activeEvents.end()) { handler->PSendSysMessage(LANG_EVENT_NOT_ACTIVE, eventId); handler->SetSentErrorMessage(true); return false; } sGameEventMgr->StopEvent(eventId, true); return true; } }; void AddSC_event_commandscript() { new event_commandscript(); }
0
0.877981
1
0.877981
game-dev
MEDIA
0.661677
game-dev
0.860062
1
0.860062
FrictionalGames/PenumbraOverture
12,305
GameLiquidArea.cpp
/* * Copyright (C) 2006-2010 - Frictional Games * * This file is part of Penumbra Overture. * * Penumbra Overture 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. * * Penumbra Overture 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 Penumbra Overture. If not, see <http://www.gnu.org/licenses/>. */ #include "StdAfx.h" #include "GameLiquidArea.h" #include "Init.h" #include "MapHandler.h" #include "Player.h" #include "EffectHandler.h" #include "GlobalInit.h" ////////////////////////////////////////////////////////////////////////// // LOADER ////////////////////////////////////////////////////////////////////////// //----------------------------------------------------------------------- cAreaLoader_GameLiquidArea::cAreaLoader_GameLiquidArea(const tString &asName, cInit *apInit) : iArea3DLoader(asName) { mpInit = apInit; } cAreaLoader_GameLiquidArea::~cAreaLoader_GameLiquidArea() { } //----------------------------------------------------------------------- iEntity3D* cAreaLoader_GameLiquidArea::Load(const tString &asName, const cVector3f &avSize, const cMatrixf &a_mtxTransform,cWorld3D *apWorld) { cGameLiquidArea *pArea = hplNew( cGameLiquidArea, (mpInit,asName) ); pArea->m_mtxOnLoadTransform = a_mtxTransform; //Create physics data iPhysicsWorld *pPhysicsWorld = apWorld->GetPhysicsWorld(); iCollideShape* pShape = pPhysicsWorld->CreateBoxShape(avSize,NULL); std::vector<iPhysicsBody*> vBodies; vBodies.push_back(pPhysicsWorld->CreateBody(asName,pShape)); vBodies[0]->SetCollide(false); vBodies[0]->SetCollideCharacter(false); vBodies[0]->SetMatrix(a_mtxTransform); vBodies[0]->SetUserData(pArea); pArea->SetBodies(vBodies); mpInit->mpMapHandler->AddGameEntity(pArea); pArea->Setup(); //Return something else later perhaps. return NULL; } //----------------------------------------------------------------------- ////////////////////////////////////////////////////////////////////////// // CONSTRUCTORS ////////////////////////////////////////////////////////////////////////// cGameLiquidArea::cGameLiquidArea(cInit *apInit,const tString& asName) : iGameEntity(apInit,asName) { mType = eGameEntityType_LiquidArea; mfDensity = 100; mfLinearViscosity = 1; mfAngularViscosity = 1; mbHasInteraction = false; mpPhysicsMaterial = NULL; mbHasWaves = true; mfWaveAmp = 0.04f; mfWaveFreq = 3; mfTimeCount =0; } //----------------------------------------------------------------------- cGameLiquidArea::~cGameLiquidArea(void) { } //----------------------------------------------------------------------- ////////////////////////////////////////////////////////////////////////// // PUBLIC METHODS ////////////////////////////////////////////////////////////////////////// //----------------------------------------------------------------------- void cGameLiquidArea::SetPhysicsMaterial(const tString asName) { if(asName == "") return; iPhysicsWorld *pPhysicsWorld = mpInit->mpGame->GetScene()->GetWorld3D()->GetPhysicsWorld(); mpPhysicsMaterial = pPhysicsWorld->GetMaterialFromName(asName); if(mpPhysicsMaterial==NULL){ Error("Liquid '%s' could not find material '%s'\n",GetName().c_str(), mpPhysicsMaterial->GetName().c_str()); } } //----------------------------------------------------------------------- void cGameLiquidArea::OnPlayerPick() { } //----------------------------------------------------------------------- void cGameLiquidArea::Update(float afTimeStep) { if(IsActive()==false) return; iPhysicsBody *pAreaBody = mvBodies[0]; cWorld3D *pWorld = mpInit->mpGame->GetScene()->GetWorld3D(); iPhysicsWorld *pPhysicsWorld = pWorld->GetPhysicsWorld(); cCamera3D *pCam = mpInit->mpPlayer->GetCamera(); float fSurfaceY = mvBodies[0]->GetWorldPosition().y + mvBodies[0]->GetShape()->GetSize().y /2; cCollideData collideData; collideData.SetMaxSize(1); mfTimeCount += afTimeStep; //////////////////////////////////////////////////////// //Update waves //////////////////////////////////////////////////////// //Check if player camera is in water. if(cMath::PointBVCollision(pCam->GetPosition(),*pAreaBody->GetBV())) { if(mpInit->mpEffectHandler->GetUnderwater()->IsActive()==false) { mpInit->mpEffectHandler->GetUnderwater()->SetActive(true); mpInit->mpEffectHandler->GetUnderwater()->SetColor(mColor); } } else { mpInit->mpEffectHandler->GetUnderwater()->SetActive(false); } //////////////////////////////////////////////////////// //Iterate all bodies in world and check for intersection cPortalContainerEntityIterator bodyIt = pWorld->GetPortalContainer()->GetEntityIterator( pAreaBody->GetBoundingVolume()); while(bodyIt.HasNext()) { iPhysicsBody *pBody = static_cast<iPhysicsBody*>(bodyIt.Next()); iGameEntity *pEntity = (iGameEntity*)pBody->GetUserData(); if(pBody->GetCollide() && pBody->IsActive()) { if(pBody->GetMass()==0 && pBody->IsCharacter()==false) continue; ///////////////////////// //Bounding volume check if(cMath::CheckCollisionBV(*pBody->GetBV(), *pAreaBody->GetBV())==false) { pBody->SetBuoyancyActive(false); continue; } /////////////////////////////// //Check for collision if(pPhysicsWorld->CheckShapeCollision(pBody->GetShape(),pBody->GetLocalMatrix(), pAreaBody->GetShape(), pAreaBody->GetLocalMatrix(),collideData,1)==false) { pBody->SetBuoyancyActive(false); continue; } if(pBody->IsCharacter()) { iCharacterBody *pCharBody = pBody->GetCharacterBody(); float fToSurface = cMath::Abs(fSurfaceY - pCharBody->GetFeetPosition().y); float fCharHeight = pCharBody->GetSize().y; if(fToSurface > fCharHeight) fToSurface = fCharHeight; float fRadius = pCharBody->GetSize().x/2; float fVolume = fToSurface*fRadius*fRadius*kPif; float fWaterWeight = fVolume * mfDensity; cVector3f vForce = pPhysicsWorld->GetGravity() * -fWaterWeight; //Log("Tosurface: %f Vol: %f\n",fToSurface,fVolume); pCharBody->AddForce(vForce); if(pBody->GetBuoyancyActive()==false) { SplashEffect(pBody); pBody->SetBuoyancyActive(true); } } else { if(pBody->GetBuoyancyActive()==false) { pBody->SetBuoyancySurface(mSurfacePlane); pBody->SetBuoyancyDensity(mfDensity); pBody->SetBuoyancyLinearViscosity(mfLinearViscosity); pBody->SetBuoyancyAngularViscosity(mfAngularViscosity); SplashEffect(pBody); //Log("Splash body: %s\n",pBody->GetName().c_str()); pBody->SetBuoyancyActive(true); } if(mbHasWaves){ cVector3f vPos = cMath::MatrixMul(pBody->GetLocalMatrix(),pBody->GetMassCentre()); float fAddX = sin(mfTimeCount * mfWaveFreq + vPos.x * 15)*mfWaveAmp; float fAddZ = sin(mfTimeCount * mfWaveFreq + vPos.z * 15)*mfWaveAmp; //pBody->AddForce(cVector3f(0, 9.8f * (fAddZ+fAddX)*pBody->GetMass()*2, 0)); //pBody->AddForce(cVector3f(0, 9.8f * cMath::RandRectf(-0.1, 0.1f)*pBody->GetMass()*2, 0)); //Log("F:%f Amp %f\n",fAddZ+fAddX,mfWaveAmp); //pBody->AddTorque(cVector3f((fAddZ+fAddX)*pBody->GetMass(), (fAddZ+fAddX)*pBody->GetMass(), // (fAddZ+fAddX)*pBody->GetMass())); cPlanef tempPlane; tempPlane.FromNormalPoint( cVector3f(0,1,0), cVector3f(0,fSurfaceY + fAddX + fAddZ,0)); pBody->SetBuoyancySurface(tempPlane); pBody->SetEnabled(true); } } } } } //----------------------------------------------------------------------- void cGameLiquidArea::Setup() { //Log("SETUP!\n"); float fHeight = mvBodies[0]->GetShape()->GetSize().y; cVector3f vPos = mvBodies[0]->GetWorldPosition(); mSurfacePlane.FromNormalPoint( cVector3f(0,1,0), cVector3f(0,vPos.y,0) + cVector3f(0,fHeight/2,0)); } //----------------------------------------------------------------------- ////////////////////////////////////////////////////////////////////////// // PRIVATE METHODS ////////////////////////////////////////////////////////////////////////// //----------------------------------------------------------------------- void cGameLiquidArea::SplashEffect(iPhysicsBody *apBody) { if(mpPhysicsMaterial==NULL) return; cSurfaceData *pSurface = mpPhysicsMaterial->GetSurfaceData(); float fSpeed; if(apBody->IsCharacter()) fSpeed = apBody->GetCharacterBody()->GetForceVelocity().Length(); else fSpeed = apBody->GetLinearVelocity().Length(); cSurfaceImpactData *pImpact = pSurface->GetImpactDataFromSpeed(fSpeed); if(pImpact == NULL) return; cVector3f vPos = cMath::MatrixMul(apBody->GetLocalMatrix(),apBody->GetMassCentre()); vPos.y = mvBodies[0]->GetWorldPosition().y + mvBodies[0]->GetShape()->GetSize().y/2; cWorld3D *pWorld = mpInit->mpGame->GetScene()->GetWorld3D(); if(pImpact->GetPSName() != "") { pWorld->CreateParticleSystem("Splash", pImpact->GetPSName(),1, cMath::MatrixTranslate(vPos)); } if(pImpact->GetSoundName() != "") { cSoundEntity *pSound = pWorld->CreateSoundEntity("Splash",pImpact->GetSoundName(),true); if(pSound) { pSound->SetPosition(vPos); } } } //----------------------------------------------------------------------- ////////////////////////////////////////////////////////////////////////// // SAVE OBJECT STUFF ////////////////////////////////////////////////////////////////////////// //----------------------------------------------------------------------- kBeginSerialize(cGameLiquidArea_SaveData,iGameEntity_SaveData) kSerializeVar(mvSize,eSerializeType_Vector3f) kSerializeVar(mfDensity,eSerializeType_Float32) kSerializeVar(mfLinearViscosity,eSerializeType_Float32) kSerializeVar(mfAngularViscosity,eSerializeType_Float32) kSerializeVar(msPhysicsMaterial,eSerializeType_String) kSerializeVar(mColor,eSerializeType_Color) kSerializeVar(mbHasWaves, eSerializeType_Bool) kSerializeVar(mSurfacePlane,eSerializeType_Planef) kEndSerialize() //----------------------------------------------------------------------- iGameEntity* cGameLiquidArea_SaveData::CreateEntity() { return NULL; } //----------------------------------------------------------------------- iGameEntity_SaveData* cGameLiquidArea::CreateSaveData() { return hplNew( cGameLiquidArea_SaveData, () ); } //----------------------------------------------------------------------- void cGameLiquidArea::SaveToSaveData(iGameEntity_SaveData *apSaveData) { __super::SaveToSaveData(apSaveData); cGameLiquidArea_SaveData *pData = static_cast<cGameLiquidArea_SaveData*>(apSaveData); kCopyToVar(pData, mfDensity); kCopyToVar(pData, mfLinearViscosity); kCopyToVar(pData, mfAngularViscosity); kCopyToVar(pData, mSurfacePlane); kCopyToVar(pData, mColor); kCopyToVar(pData, mbHasWaves); if(mpPhysicsMaterial) pData->msPhysicsMaterial = mpPhysicsMaterial->GetName(); else pData->msPhysicsMaterial = ""; pData->mvSize = mvBodies[0]->GetShape()->GetSize(); } //----------------------------------------------------------------------- void cGameLiquidArea::LoadFromSaveData(iGameEntity_SaveData *apSaveData) { __super::LoadFromSaveData(apSaveData); cGameLiquidArea_SaveData *pData = static_cast<cGameLiquidArea_SaveData*>(apSaveData); kCopyFromVar(pData, mfDensity); kCopyFromVar(pData, mfLinearViscosity); kCopyFromVar(pData, mfAngularViscosity); kCopyFromVar(pData, mSurfacePlane); kCopyFromVar(pData, mColor); kCopyFromVar(pData, mbHasWaves); SetPhysicsMaterial(pData->msPhysicsMaterial); } //----------------------------------------------------------------------- void cGameLiquidArea::SetupSaveData(iGameEntity_SaveData *apSaveData) { __super::SetupSaveData(apSaveData); cGameLiquidArea_SaveData *pData = static_cast<cGameLiquidArea_SaveData*>(apSaveData); } //-----------------------------------------------------------------------
0
0.924512
1
0.924512
game-dev
MEDIA
0.90717
game-dev
0.91027
1
0.91027
EclipseMenu/EclipseMenu
2,855
src/hacks/Level/AlwaysShowCoins.cpp
#ifndef GEODE_IS_MACOS // TODO: someone look at fixing this for imac #include <modules/config/config.hpp> #include <modules/gui/gui.hpp> #include <modules/gui/components/toggle.hpp> #include <modules/hack/hack.hpp> #include <Geode/binding/GameManager.hpp> #include <Geode/modify/GameObject.hpp> #include <Geode/modify/GJBaseGameLayer.hpp> namespace eclipse::hacks::Level { void onChangeShowCoins(bool state) { static cocos2d::CCObject* uncollectedSecretCoin = nullptr; static cocos2d::CCObject* uncollectedUserCoin = nullptr; auto* GM = utils::get<GameManager>(); if (!uncollectedSecretCoin) uncollectedSecretCoin = GM->m_unkAnimationDict->objectForKey(-142)->copy(); if (!uncollectedUserCoin) uncollectedUserCoin = GM->m_unkAnimationDict->objectForKey(-1329)->copy(); if (state) { uncollectedSecretCoin->retain(); uncollectedUserCoin->retain(); GM->m_unkAnimationDict->removeObjectForKey(-142); GM->m_unkAnimationDict->removeObjectForKey(-1329); GM->m_unkAnimationDict->setObject(GM->m_unkAnimationDict->objectForKey(142)->copy(), -142); GM->m_unkAnimationDict->setObject(GM->m_unkAnimationDict->objectForKey(1329)->copy(), -1329); } else if (uncollectedSecretCoin && uncollectedUserCoin) { GM->m_unkAnimationDict->removeObjectForKey(-142); GM->m_unkAnimationDict->removeObjectForKey(-1329); GM->m_unkAnimationDict->setObject(uncollectedSecretCoin, -142); GM->m_unkAnimationDict->setObject(uncollectedUserCoin, -1329); } } class $hack(AlwaysShowCoins) { void init() override { auto tab = gui::MenuTab::find("tab.level"); tab->addToggle("level.alwaysshowcoins")->handleKeybinds()->setDescription() ->callback(onChangeShowCoins); } void lateInit() override { onChangeShowCoins(config::get<bool>("level.alwaysshowcoins", false)); } [[nodiscard]] const char* getId() const override { return "Always Show Coins"; } }; REGISTER_HACK(AlwaysShowCoins) // if qolmod makes 3 billion playlayers this will not work correctly static bool skipUniqueCoin = false; class $modify(AlwaysShowCoinsGOHook, GameObject) { ADD_HOOKS_DELEGATE("level.alwaysshowcoins") void playDestroyObjectAnim(GJBaseGameLayer* p0) { skipUniqueCoin = true; GameObject::playDestroyObjectAnim(p0); skipUniqueCoin = false; } }; class $modify(AlwaysShowCoinsBGLHook, GJBaseGameLayer) { bool hasUniqueCoin(EffectGameObject* p0) { if (!GJBaseGameLayer::hasUniqueCoin(p0)) return false; return !skipUniqueCoin; } }; } #endif
0
0.954112
1
0.954112
game-dev
MEDIA
0.978759
game-dev
0.937857
1
0.937857
DeltaV-Station/Delta-v
1,796
Content.Shared/Silicons/Laws/Components/IonStormTargetComponent.cs
using Content.Shared.Random; using Robust.Shared.Prototypes; namespace Content.Shared.Silicons.Laws.Components; /// <summary> /// During the ion storm event, this entity will have <see cref="IonStormLawsEvent"/> raised on it if it has laws. /// New laws can be modified in multiple ways depending on the fields below. /// </summary> [RegisterComponent] public sealed partial class IonStormTargetComponent : Component { /// <summary> /// <see cref="WeightedRandomPrototype"/> for a random lawset to possibly replace the old one with. /// </summary> [DataField, ViewVariables(VVAccess.ReadWrite)] public ProtoId<WeightedRandomPrototype> RandomLawsets = "IonStormLawsets"; /// <summary> /// Chance for this borg to be affected at all. /// </summary> [DataField, ViewVariables(VVAccess.ReadWrite)] public float Chance = 0.8f; /// <summary> /// Chance to replace the lawset with a random one /// </summary> [DataField, ViewVariables(VVAccess.ReadWrite)] public float RandomLawsetChance = 0.25f; /// <summary> /// Chance to remove a random law. /// </summary> [DataField, ViewVariables(VVAccess.ReadWrite)] public float RemoveChance = 0.2f; /// <summary> /// Chance to replace a random law with the new one, rather than have it be a glitched-order law. /// </summary> [DataField, ViewVariables(VVAccess.ReadWrite)] public float ReplaceChance = 0.2f; /// <summary> /// Chance to shuffle laws after everything is done. /// </summary> [DataField, ViewVariables(VVAccess.ReadWrite)] public float ShuffleChance = 0.2f; } /// <summary> /// Raised on an ion storm target to modify its laws. /// </summary> [ByRefEvent] public record struct IonStormLawsEvent(SiliconLawset Lawset);
0
0.612959
1
0.612959
game-dev
MEDIA
0.334599
game-dev
0.695273
1
0.695273
Silverlan/pragma
2,876
core/server/src/entities/components/s_animated_component.cpp
// SPDX-FileCopyrightText: (c) 2019 Silverlan <opensource@pragma-engine.com> // SPDX-License-Identifier: MIT #include "stdafx_server.h" #include "pragma/entities/components/s_animated_component.hpp" #include <pragma/lua/converters/game_type_converters_t.hpp> #include <pragma/networking/enums.hpp> #include <pragma/networking/nwm_util.h> #include <pragma/networking/enums.hpp> using namespace pragma; extern DLLSERVER ServerState *server; void SAnimatedComponent::Initialize() { BaseAnimatedComponent::Initialize(); } void SAnimatedComponent::InitializeLuaObject(lua_State *l) { return BaseEntityComponent::InitializeLuaObject<std::remove_reference_t<decltype(*this)>>(l); } void SAnimatedComponent::RegisterEvents(pragma::EntityComponentManager &componentManager, TRegisterComponentEvent registerEvent) { BaseAnimatedComponent::RegisterEvents(componentManager, registerEvent); } void SAnimatedComponent::GetBaseTypeIndex(std::type_index &outTypeIndex) const { outTypeIndex = std::type_index(typeid(BaseAnimatedComponent)); } void SAnimatedComponent::SendData(NetPacket &packet, networking::ClientRecipientFilter &rp) { packet->Write<int>(GetAnimation()); packet->Write<float>(GetCycle()); } void SAnimatedComponent::PlayAnimation(int animation, FPlayAnim flags) { BaseAnimatedComponent::PlayAnimation(animation, flags); auto &ent = static_cast<SBaseEntity &>(GetEntity()); if(ent.IsShared() == false) return; if((flags & pragma::FPlayAnim::Transmit) != pragma::FPlayAnim::None) { NetPacket p; nwm::write_entity(p, &ent); p->Write<int>(GetBaseAnimationInfo().animation); server->SendPacket("ent_anim_play", p, pragma::networking::Protocol::FastUnreliable); } } void SAnimatedComponent::StopLayeredAnimation(int slot) { auto it = m_animSlots.find(slot); if(it == m_animSlots.end()) return; BaseAnimatedComponent::StopLayeredAnimation(slot); auto &ent = static_cast<SBaseEntity &>(GetEntity()); if(ent.IsShared() == false) return; auto &animInfo = it->second; if((animInfo.flags & pragma::FPlayAnim::Transmit) != pragma::FPlayAnim::None) { NetPacket p; nwm::write_entity(p, &ent); p->Write<int>(slot); server->SendPacket("ent_anim_gesture_stop", p, pragma::networking::Protocol::SlowReliable); } } void SAnimatedComponent::PlayLayeredAnimation(int slot, int animation, FPlayAnim flags) { BaseAnimatedComponent::PlayLayeredAnimation(slot, animation, flags); auto &ent = static_cast<SBaseEntity &>(GetEntity()); if(ent.IsShared() == false) return; if((flags & pragma::FPlayAnim::Transmit) != pragma::FPlayAnim::None) { auto it = m_animSlots.find(slot); if(it == m_animSlots.end()) return; auto &animInfo = it->second; NetPacket p; nwm::write_entity(p, &ent); p->Write<int>(slot); p->Write<int>(animInfo.animation); server->SendPacket("ent_anim_gesture_play", p, pragma::networking::Protocol::SlowReliable); } }
0
0.889419
1
0.889419
game-dev
MEDIA
0.856893
game-dev
0.880325
1
0.880325
mrbjarksen/a-puzzle-a-day
2,486
src/board/compact.rs
use crate::board::Board; use crate::board::piece::Piece; use crate::board::square::Square; use crate::board::path::Path; use crate::board::placement::*; use Rotation::*; #[derive(Debug)] pub struct CompactBoard { squares: [Option<Square>; 8], rotations: [Rotation; 8], mirrors: [bool; 8], } impl TryFrom<CompactBoard> for Board { type Error = PlacementError; fn try_from(cb: CompactBoard) -> Result<Self, Self::Error> { let mut board = Board::default(); let pieces = Piece::pieces(); for (i, &piece) in pieces.iter().enumerate() { if let (Some(square), rotation, mirror) = (cb.squares[i], cb.rotations[i], cb.mirrors[i]) { let path = Path::from_orientation(piece, rotation, mirror); board = board.place(piece, square, &path).ok_or(PlacementError)?; } } Ok(board) } } impl TryFrom<Board> for CompactBoard { type Error = PlacementError; fn try_from(board: Board) -> Result<Self, Self::Error> { let mut squares = [None; 8]; let mut rotations = [Zero; 8]; let mut mirrors = [false; 8]; for Placement { piece, square, rotation, mirror } in board.placements()? { squares[piece as usize] = Some(square); rotations[piece as usize] = rotation; mirrors[piece as usize] = mirror; } Ok(CompactBoard { squares, rotations, mirrors }) } } impl CompactBoard { pub fn to_bytes(&self) -> [u8; 9] { let mut bytes = [0; 9]; for mirror in self.mirrors { bytes[0] = (bytes[0] << 1) | mirror as u8; } for (i, &rotation) in self.rotations.iter().enumerate() { bytes[i+1] = (rotation as u8) << 6 } for (i, &square) in self.squares.iter().enumerate() { bytes[i+1] |= match square { None => 0b111111, Some(square) => square as u8, } } bytes } } impl From<[u8; 9]> for CompactBoard { fn from(bytes: [u8; 9]) -> Self { let mut squares = [None; 8]; let mut rotations = [Zero; 8]; let mut mirrors = [false; 8]; for i in 0..8 { squares[i] = Square::try_from(bytes[i+1] & 0b111111).ok(); rotations[i] = Rotation::from((bytes[i+1] >> 6) & 0b11); mirrors[i] = (bytes[0] >> (7 - i)) & 0b1 == 1; } CompactBoard { squares, rotations, mirrors } } }
0
0.891571
1
0.891571
game-dev
MEDIA
0.334733
game-dev
0.890746
1
0.890746
foursquare/twofishes
6,191
util/src/main/scala/GeometryUtils.scala
// Copyright 2013 Foursquare Labs Inc. All Rights Reserved. package com.foursquare.twofishes.util import com.google.common.geometry.{S2CellId, S2LatLng, S2LatLngRect, S2Polygon, S2PolygonBuilder, S2RegionCoverer} import com.vividsolutions.jts.geom.{Geometry, Point, Polygon} import scalaj.collection.Implicits._ trait RevGeoConstants { val minS2LevelForRevGeo = 8 val maxS2LevelForRevGeo = 12 val defaultLevelModForRevGeo = 2 val defaultMaxCellsHintForRevGeo = 1000 } trait S2CoveringConstants { val minS2LevelForS2Covering = 4 val maxS2LevelForS2Covering = 20 val minS2LevelForS2Interior = minS2LevelForS2Covering val maxS2LevelForS2Interior = 18 val defaultLevelModForS2Covering = 1 val defaultMaxCellsHintForS2Covering = 50 val defaultMaxCellsHintForS2Interior = 100 } object RevGeoConstants extends RevGeoConstants object S2CoveringConstants extends S2CoveringConstants object GeometryUtils extends RevGeoConstants { def getBytes(l: S2CellId): Array[Byte] = getBytes(l.id()) def getBytes(l: Long): Array[Byte] = ByteUtils.longToBytes(l) def getBytes(i: Int): Array[Byte] = ByteUtils.intToBytes(i) def getLongFromBytes(bytes: Array[Byte]): Long = ByteUtils.getLongFromBytes(bytes) def getS2CellIdForLevel(lat: Double, long: Double, s2Level: Int): S2CellId = { val ll = S2LatLng.fromDegrees(lat, long) S2CellId.fromLatLng(ll).parent(s2Level) } /** * Returns an `Iterable` of cells that cover a rectangle. */ def rectCover(topRight: (Double,Double), bottomLeft: (Double,Double), minLevel: Int, maxLevel: Int, levelMod: Option[Int]): Seq[com.google.common.geometry.S2CellId] = { val topRightPoint = S2LatLng.fromDegrees(topRight._1, topRight._2) val bottomLeftPoint = S2LatLng.fromDegrees(bottomLeft._1, bottomLeft._2) val rect = S2LatLngRect.fromPointPair(topRightPoint, bottomLeftPoint) rectCover(rect, minLevel, maxLevel, levelMod) } def rectCover(rect: S2LatLngRect, minLevel: Int, maxLevel: Int, levelMod: Option[Int]): Seq[com.google.common.geometry.S2CellId] = { val coverer = new S2RegionCoverer coverer.setMinLevel(minLevel) coverer.setMaxLevel(maxLevel) levelMod.foreach(m => coverer.setLevelMod(m)) val coveringCells = new java.util.ArrayList[com.google.common.geometry.S2CellId] coverer.getCovering(rect, coveringCells) coveringCells.asScala } def s2BoundingBoxCovering(geomCollection: Geometry, minS2Level: Int, maxS2Level: Int) = { val envelope = geomCollection.getEnvelopeInternal() rectCover( topRight = (envelope.getMaxY(), envelope.getMaxX()), bottomLeft = (envelope.getMinY(), envelope.getMinX()), minLevel = minS2Level, maxLevel = maxS2Level, levelMod = None ) } def s2Polygon(geomCollection: Geometry) = { if (geomCollection.getCoordinates().toList.exists(c => c.y > 90 || c.y < -90)) { throw new Exception("Geometry trying to cross a pole, can't handle: %s".format(geomCollection)) } val polygons: List[S2Polygon] = (for { i <- 0.until(geomCollection.getNumGeometries()).toList val geom = geomCollection.getGeometryN(i) if (geom.isInstanceOf[Polygon]) } yield { val poly = geom.asInstanceOf[Polygon] val ring = poly.getExteriorRing() val coords = ring.getCoordinates() val builder = new S2PolygonBuilder() (coords ++ List(coords(0))).sliding(2).foreach(pair => { val p1 = pair(0) val p2 = pair(1) builder.addEdge( S2LatLng.fromDegrees(p1.y, p1.x).toPoint, S2LatLng.fromDegrees(p2.y, p2.x).toPoint ) }) builder.assemblePolygon() }) val builder = new S2PolygonBuilder() polygons.foreach(p => builder.addPolygon(p)) builder.assemblePolygon() } def s2PolygonCovering( geomCollection: Geometry, minS2Level: Int = minS2LevelForRevGeo, maxS2Level: Int = maxS2LevelForRevGeo, maxCellsHintWhichMightBeIgnored: Option[Int] = None, levelMod: Option[Int] = Some(defaultLevelModForRevGeo), interior: Boolean = false ): Seq[S2CellId] = { if (geomCollection.isInstanceOf[Point]) { val point = geomCollection.asInstanceOf[Point] val lat = point.getY val lng = point.getX minS2Level.to(maxS2Level, levelMod.getOrElse(1)).map(level => { GeometryUtils.getS2CellIdForLevel(lat, lng, level) }) } else { val s2poly = s2Polygon(geomCollection) val coverer = new S2RegionCoverer coverer.setMinLevel(minS2Level) coverer.setMaxLevel(maxS2Level) maxCellsHintWhichMightBeIgnored.foreach(coverer.setMaxCells) levelMod.foreach(m => coverer.setLevelMod(m)) val coveringCells = new java.util.ArrayList[com.google.common.geometry.S2CellId] if (interior) { coverer.getInteriorCovering(s2poly, coveringCells) } else { coverer.getCovering(s2poly, coveringCells) } coveringCells.asScala.toSeq } } def coverAtAllLevels(geomCollection: Geometry, minS2Level: Int, maxS2Level: Int, levelMod: Option[Int] = None ): Seq[S2CellId] = { val initialCovering = s2PolygonCovering(geomCollection, minS2Level = maxS2Level, maxS2Level = maxS2Level, levelMod = levelMod ) val allCells = Set.newBuilder[S2CellId] // The final set of cells will be at most all the parents of the cells in // the initial covering. Wolfram alpha says that'll top out at 4/3 the // initial size: // http://www.wolframalpha.com/input/?i=sum+from+0+to+30+of+1%2F%284%5En%29. // In practice, it'll be less than that since we don't ask for all the // levels. But this is a reasonable upper bound. allCells.sizeHint((initialCovering.size*4)/3) initialCovering.foreach(cellid => { val level = cellid.level() allCells += cellid if (level > minS2Level) { level.to(minS2Level, -levelMod.getOrElse(1)).drop(1).foreach(l => { val p = cellid.parent(l) allCells += p }) } }) allCells.result.toSeq } }
0
0.874302
1
0.874302
game-dev
MEDIA
0.483386
game-dev
0.944908
1
0.944908
Sduibek/fixtsrc
15,118
SCRIPTS/CHDSCOUT.SSL
procedure start; variable SrcObj := 0; variable SrcIsParty := 0; procedure critter_p_proc;// script_action == 12 procedure destroy_p_proc;// script_action == 18 procedure look_at_p_proc;// script_action == 21 procedure talk_p_proc;// script_action == 11 procedure timed_event_p_proc;// script_action == 22 procedure ChdScout0; procedure ChdScout1; procedure ChdScout2; procedure ChdScout3; procedure ChdScout4; procedure ChdScout5; procedure ChdScout6; procedure ChdScout7; procedure ChdScout8; procedure ChdScout9; procedure ChdScout10; procedure ChdScout11; procedure ChdScout12; procedure ChdScout13; procedure ChdScout14; procedure ChdScout15; procedure ChdScout16; procedure ChdScout17; procedure ChdScout17a; procedure ChdScout18; procedure ChdScout19; procedure ChdScout20; procedure ChdScout21; procedure ChdScout22; procedure ChdScout23; procedure ChdScout24; procedure ChdScout25; procedure ChdScout26; procedure ChdScout27; procedure ChdScout28; procedure ChdScout29; procedure ChdScout30; procedure ChdScout31; procedure ChdScout32; procedure ChdScout33; procedure ChdScout34; procedure ChdScout35; procedure ChdScoutend; procedure combat; procedure to_orfeo; import variable Orfeo_ptr; variable HOSTILE; variable initialized := 0; variable in_timed_event; variable weaponPtr; procedure start begin if local_var(12) != 1 then begin// Fallout Fixt lvar12 - this code block heals critter to full HP one time (first time player enters the map) to make sure they always start with full HP. if metarule(14, 0) then begin// Fallout Fixt lvar12 - first visit to map? if metarule(22, 0) == 0 then begin// Fallout Fixt lvar12 - Not currently loading a save? if get_critter_stat(self_obj, 7) > 0 then begin critter_heal(self_obj, 999); end// if obj_is_carrying_obj_pid(self_obj, 46) > 0 then begin display_msg("S-bag " + proto_data(obj_pid(self_obj), 1)); end if obj_is_carrying_obj_pid(self_obj, 90) > 0 then begin display_msg("Pack " + proto_data(obj_pid(self_obj), 1)); end if obj_is_carrying_obj_pid(self_obj, 93) > 0 then begin display_msg("M-bag " + proto_data(obj_pid(self_obj), 1)); end if global_var(330) then begin if critter_inven_obj(self_obj, 0) <= 0 then begin// Equip held armor if not currently wearing any. variable A; if obj_carrying_pid_obj(self_obj, 17) then begin debug_msg("Fallout Fixt - Warning: CRITTER " + obj_pid(self_obj) + " HAD ARMOR BUT EMPTY ARMOR SLOT. EQUIPPING COMBAT ARMOR..."); A := obj_carrying_pid_obj(self_obj, 17); rm_obj_from_inven(self_obj, A); add_obj_to_inven(self_obj, A); wield_obj_critter(self_obj, A); end else begin if obj_carrying_pid_obj(self_obj, 2) then begin debug_msg("Fallout Fixt - Warning: CRITTER " + obj_pid(self_obj) + " HAD ARMOR BUT EMPTY ARMOR SLOT. EQUIPPING METAL ARMOR..."); A := obj_carrying_pid_obj(self_obj, 2); rm_obj_from_inven(self_obj, A); add_obj_to_inven(self_obj, A); wield_obj_critter(self_obj, A); end else begin if obj_carrying_pid_obj(self_obj, 1) then begin debug_msg("Fallout Fixt - Warning: CRITTER " + obj_pid(self_obj) + " HAD ARMOR BUT EMPTY ARMOR SLOT. EQUIPPING LEATHER ARMOR..."); A := obj_carrying_pid_obj(self_obj, 1); rm_obj_from_inven(self_obj, A); add_obj_to_inven(self_obj, A); wield_obj_critter(self_obj, A); end else begin if obj_carrying_pid_obj(self_obj, 74) then begin debug_msg("Fallout Fixt - Warning: CRITTER " + obj_pid(self_obj) + " HAD ARMOR BUT EMPTY ARMOR SLOT. EQUIPPING LEATHER JACKET..."); A := obj_carrying_pid_obj(self_obj, 74); rm_obj_from_inven(self_obj, A); add_obj_to_inven(self_obj, A); wield_obj_critter(self_obj, A); end else begin if obj_carrying_pid_obj(self_obj, 113) then begin debug_msg("Fallout Fixt - Warning: CRITTER " + obj_pid(self_obj) + " HAD ARMOR BUT EMPTY ARMOR SLOT. EQUIPPING ROBES..."); A := obj_carrying_pid_obj(self_obj, 113); rm_obj_from_inven(self_obj, A); add_obj_to_inven(self_obj, A); wield_obj_critter(self_obj, A); end end end end end end end set_local_var(12, 1); end end end if (not(initialized)) then begin initialized := 1; /* TEAM_NUM */ critter_add_trait(self_obj, 1, 6, 20); /* AI_PACKET */ critter_add_trait(self_obj, 1, 5, 67); anim(self_obj, 1000, random(0, 5)); if (local_var(1) == 0) then begin set_local_var(1, 1); weaponPtr := create_object_sid(9, 0, 0, -1); add_obj_to_inven(self_obj, weaponPtr); wield_obj_critter(self_obj, weaponPtr); add_obj_to_inven(self_obj, create_object_sid(29, 0, 0, -1)); end end if (script_action == 12) then begin//<-- critter_p_proc - (can also be "Critter_Action") - do they see you, should they wander, should they attack you, etc.. call critter_p_proc; end else begin if (script_action == 18) then begin//destroy_p_proc - Object or Critter has been killed or otherwise eradicated. Fall down go boom. call destroy_p_proc; end else begin if (script_action == 21) then begin//MOUSE-OVER DESCRIPTION -- look_at_p_proc - (usually brief length. hovered mouse over object, haven't clicked on it.) call look_at_p_proc; end else begin if (script_action == 11) then begin//<--- talk_p_proc (Face icon), can also call "do_dialogue" or "do_dialog" call talk_p_proc; end else begin if (script_action == 22) then begin//<-- timed_event_p_proc -- called by ADD_TIMER_EVENT commands. "fixed_param==#" in this procedure is the number of the event in question (i.e. Add_Timer_Event dude,5,1 would be fixed_param 1) -- can also be "timeforwhat" call timed_event_p_proc; end end end end end end procedure critter_p_proc begin if (global_var(272)) then begin HOSTILE := 1; end if (HOSTILE and obj_can_see_obj(self_obj, dude_obj)) then begin HOSTILE := 0; attack_complex(dude_obj, 0, 1, 0, 0, 30000, 0, 0); end else begin if (not(in_timed_event)) then begin in_timed_event := 1; add_timer_event(self_obj, game_ticks(random(6, 10)), random(1, 3)); end if (obj_can_see_obj(self_obj, dude_obj) and (tile_distance_objs(self_obj, dude_obj) < 6)) then begin if (local_var(0) == 0) then begin dialogue_system_enter; end end end end procedure destroy_p_proc begin rm_timer_event(self_obj); // //BEGIN WEAPON DROP MOD CODE //--original code and mod by:-- // Josan12 (http://www.nma-fallout.com/forum/profile.php?mode=viewprofile&u=18843) and // MIB88 (http://www.nma-fallout.com/forum/profile.php?mode=viewprofile&u=4464) // if global_var(460) and not(global_var(0)) and (critter_inven_obj(self_obj, 1) or critter_inven_obj(self_obj, 2)) then begin// only run if Weapon Drop is enabled, AND Fixes Only is disabled, AND actually holding something variable item1 := 0; variable item2 := 0; variable armor := 0; variable item1PID := 0; variable item2PID := 0; variable armorPID := 0; variable drophex := 0; if global_var(325) then begin debug_msg("Weapon Drop BEGINS"); end if (critter_inven_obj(self_obj, 1) > 0) then begin item1 := critter_inven_obj(self_obj, 1); end if (critter_inven_obj(self_obj, 2) > 0) then begin item2 := critter_inven_obj(self_obj, 2); end if (critter_inven_obj(self_obj, 0) > 0) then begin armor := critter_inven_obj(self_obj, 0); end if item1 then begin item1PID := obj_pid(item1); end if item2 then begin item2PID := obj_pid(item2); end if armor then begin armorPID := obj_pid(armor); end drophex := tile_num_in_direction(tile_num(self_obj), random(0, 5), random(global_var(461), global_var(462))); if (item1PID != 19) and (item1PID != 21) and (item1PID != 79) and (item1PID != 205) and (item1PID != 234) and (item1PID != 235) and (item1PID != 244) and (item2PID != 19) and (item2PID != 21) and (item2PID != 79) and (item2PID != 205) and (item2PID != 234) and (item2PID != 235) and (item2PID != 244) then begin//Don't drop if: Rock (19), Brass Knuckles (21), Flare (79), Lit Flare (205), Spiked Knuckles (234), Power Fist (235), or Gold Nugget (244) if (item1 > 0) then begin if (obj_item_subtype(item1) == 3) then begin rm_obj_from_inven(self_obj, item1); move_to(item1, drophex, elevation(self_obj)); end end if (item2 > 0) then begin if (obj_item_subtype(item2) == 3) then begin rm_obj_from_inven(self_obj, item2); move_to(item2, drophex, elevation(self_obj)); end end if global_var(325) then begin debug_msg("Weapon Drop ENDS"); end end end //END WEAPON DROP MOD CODE // if source_obj == dude_obj then begin set_global_var(160, global_var(160) + 1);// THIS MONSTER WAS A BAD GUY. INCREASE BadGuysKilled COUNTER if (((global_var(160) + global_var(159)) >= 25) and ((global_var(159) > (2 * global_var(160))) or (global_var(317) == 1))) then begin set_global_var(317, 1); set_global_var(157, 0); end if (((global_var(160) + global_var(159)) >= 25) and ((global_var(160) > (3 * global_var(159))) or (global_var(157) == 1))) then begin set_global_var(157, 1); set_global_var(317, 0); end if ((global_var(160) % 6) == 0) then begin set_global_var(155, global_var(155) + 1); end end if source_obj > 0 then begin SrcObj := 0; SrcIsParty := 0; SrcObj := obj_pid(source_obj); if party_member_obj(SrcObj) then begin SrcIsParty := 1; end end if (source_obj == dude_obj) or (SrcIsParty == 1) then begin set_global_var(272, 1); end rm_timer_event(self_obj); end procedure look_at_p_proc begin script_overrides; display_msg(message_str(276, 100)); end procedure talk_p_proc begin anim(dude_obj, 1000, rotation_to_tile(tile_num(dude_obj), tile_num(self_obj))); start_gdialog(276, self_obj, 4, -1, -1); gsay_start; if (local_var(0)) then begin call ChdScout35; end else begin set_local_var(0, 1); call ChdScout0; end gsay_end; end_dialogue; end procedure timed_event_p_proc begin if (fixed_param == 1) then begin anim(self_obj, 1000, random(0, 5)); end else begin animate_move_obj_to_tile(self_obj, tile_num_in_direction(tile_num(self_obj), random(0, 5), random(1, 3)), 0); end in_timed_event := 0; end procedure ChdScout0 begin gsay_reply(276, 101); giq_option(-3, 276, 102, ChdScout1, 50); giq_option(4, 276, 103, ChdScout13, 50); giq_option(4, 276, 104, ChdScout25, 50); giq_option(6, 276, 105, ChdScout26, 50); giq_option(6, 276, 106, ChdScout27, 50); end procedure ChdScout1 begin gsay_reply(276, 107); giq_option(-3, 276, 108, ChdScout2, 50); giq_option(-3, 276, 109, combat, 50); giq_option(-3, 276, 110, ChdScout9, 50); end procedure ChdScout2 begin gsay_reply(276, 111); giq_option(-3, 276, 112, combat, 50); giq_option(-3, 276, 113, ChdScout3, 50); giq_option(-3, 276, 114, ChdScout4, 50); end procedure ChdScout3 begin gsay_message(276, 115, 50); end procedure ChdScout4 begin gsay_reply(276, 116); giq_option(-3, 276, 117, ChdScout5, 50); giq_option(-3, 276, 118, combat, 50); giq_option(-3, 276, 119, ChdScout6, 50); end procedure ChdScout5 begin gsay_message(276, 120, 50); end procedure ChdScout6 begin gsay_reply(276, 121); giq_option(-3, 276, 122, ChdScout7, 50); giq_option(-3, 276, 123, ChdScout5, 50); giq_option(-3, 276, 124, ChdScout8, 50); end procedure ChdScout7 begin gsay_message(276, 125, 50); end procedure ChdScout8 begin gsay_message(276, 126, 50); end procedure ChdScout9 begin gsay_reply(276, 127); giq_option(-3, 276, 128, ChdScout10, 50); giq_option(-3, 276, 129, ChdScout12, 50); giq_option(-3, 276, 130, ChdScoutend, 50); end procedure ChdScout10 begin gsay_reply(276, 131); giq_option(-3, 276, 132, ChdScout11, 50); giq_option(-3, 276, 133, ChdScoutend, 50); end procedure ChdScout11 begin gsay_message(276, 134, 50); end procedure ChdScout12 begin gsay_reply(276, 135); giq_option(-3, 276, 136, ChdScoutend, 50); end procedure ChdScout13 begin gsay_reply(276, 137); giq_option(4, 276, 138, ChdScout14, 50); giq_option(4, 276, 139, ChdScout15, 50); giq_option(4, 276, message_str(276, 140) + proto_data(obj_pid(dude_obj), 1) + message_str(276, 141), ChdScout22, 50); giq_option(4, 276, 142, ChdScout24, 50); giq_option(4, 276, 143, combat, 50); end procedure ChdScout14 begin gsay_message(276, 144, 50); call to_orfeo; end procedure ChdScout15 begin gsay_reply(276, 145); giq_option(4, 276, 146, ChdScout16, 50); giq_option(4, 276, 147, ChdScout17, 50); end procedure ChdScout16 begin gsay_message(276, 148, 50); call to_orfeo; end procedure ChdScout17 begin gsay_reply(276, 149); giq_option(4, 276, message_str(276, 150) + proto_data(obj_pid(dude_obj), 1) + message_str(276, 151), ChdScout17a, 50); giq_option(4, 276, 152, ChdScout20, 50); giq_option(4, 276, 153, combat, 50); end procedure ChdScout17a begin if (is_success(roll_vs_skill(dude_obj, 14, 0))) then begin call ChdScout18; end else begin call ChdScout19; end end procedure ChdScout18 begin gsay_message(276, 154, 50); end procedure ChdScout19 begin gsay_message(276, 155, 50); call combat; end procedure ChdScout20 begin gsay_reply(276, 156); giq_option(4, 276, message_str(276, 157) + proto_data(obj_pid(dude_obj), 1) + message_str(276, 158), ChdScout21, 50); giq_option(4, 276, 159, combat, 50); end procedure ChdScout21 begin gsay_message(276, 160, 50); call ChdScout17a; end procedure ChdScout22 begin gsay_reply(276, message_str(276, 161) + proto_data(obj_pid(dude_obj), 1) + message_str(276, 162)); giq_option(4, 276, 163, ChdScout23, 50); giq_option(4, 276, 164, ChdScout23, 50); giq_option(4, 276, 165, combat, 50); end procedure ChdScout23 begin gsay_message(276, 166, 50); call combat; end procedure ChdScout24 begin gsay_message(276, 167, 50); call combat; end procedure ChdScout25 begin gsay_reply(276, 168); giq_option(4, 276, 169, ChdScout14, 50); giq_option(4, 276, 170, ChdScout15, 50); giq_option(4, 276, message_str(276, 171) + proto_data(obj_pid(dude_obj), 1) + message_str(276, 172), ChdScout22, 50); giq_option(4, 276, 173, ChdScout24, 50); giq_option(4, 276, 174, combat, 50); end procedure ChdScout26 begin gsay_message(276, 175, 50); call combat; end procedure ChdScout27 begin gsay_reply(276, 176); giq_option(6, 276, 177, ChdScout28, 50); giq_option(6, 276, 178, ChdScout29, 50); giq_option(6, 276, 179, ChdScout30, 50); giq_option(6, 276, 180, ChdScout34, 50); end procedure ChdScout28 begin gsay_message(276, 181, 50); end procedure ChdScout29 begin gsay_message(276, 182, 50); end procedure ChdScout30 begin gsay_reply(276, 183); giq_option(6, 276, 184, ChdScout31, 50); giq_option(6, 276, 185, ChdScout32, 50); giq_option(6, 276, 186, combat, 50); end procedure ChdScout31 begin gsay_message(276, 187, 50); call to_orfeo; end procedure ChdScout32 begin gsay_reply(276, 188); giq_option(6, 276, 189, ChdScout33, 50); giq_option(6, 276, 190, ChdScout33, 50); giq_option(6, 276, 191, combat, 50); end procedure ChdScout33 begin gsay_reply(276, 192); giq_option(6, 276, 193, ChdScoutend, 50); giq_option(6, 276, 194, combat, 50); end procedure ChdScout34 begin gsay_message(276, 195, 50); call combat; end procedure ChdScout35 begin gsay_message(276, 196, 50); call combat; end procedure ChdScoutend begin end procedure combat begin HOSTILE := 1; end procedure to_orfeo begin load_map("lafollwr.map", 11); end
0
0.839691
1
0.839691
game-dev
MEDIA
0.970777
game-dev
0.917321
1
0.917321
TeamGalacticraft/Galacticraft
3,321
src/main/java/dev/galacticraft/mod/api/data/recipe/GCRecipeBuilder.java
/* * Copyright (c) 2019-2025 Team Galacticraft * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package dev.galacticraft.mod.api.data.recipe; import net.minecraft.advancements.Advancement; import net.minecraft.advancements.AdvancementRequirements; import net.minecraft.advancements.AdvancementRewards; import net.minecraft.advancements.Criterion; import net.minecraft.advancements.critereon.RecipeUnlockedTrigger; import net.minecraft.data.recipes.RecipeBuilder; import net.minecraft.data.recipes.RecipeOutput; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.Item; import net.minecraft.world.item.crafting.Recipe; import net.minecraft.world.level.ItemLike; import org.jetbrains.annotations.Nullable; import java.util.LinkedHashMap; import java.util.Map; public abstract class GCRecipeBuilder implements RecipeBuilder { private final String subPath; protected final Item result; protected final int count; protected final Map<String, Criterion<?>> criteria = new LinkedHashMap<>(); @Nullable protected String group = ""; protected GCRecipeBuilder(String subPath, ItemLike result, int count) { this.subPath = subPath; this.result = result.asItem(); this.count = count; } @Override public RecipeBuilder unlockedBy(String name, Criterion<?> criterion) { this.criteria.put(name, criterion); return this; } @Override public RecipeBuilder group(@Nullable String group) { this.group = group; return this; } @Override public Item getResult() { return this.result; } @Override public void save(RecipeOutput output, ResourceLocation id) { Advancement.Builder builder = output.advancement() .addCriterion("has_the_recipe", RecipeUnlockedTrigger.unlocked(id)) .rewards(AdvancementRewards.Builder.recipe(id)) .requirements(AdvancementRequirements.Strategy.OR); this.criteria.forEach(builder::addCriterion); output.accept(ResourceLocation.fromNamespaceAndPath(id.getNamespace(), this.subPath + '/' + id.getPath()), createRecipe(id), builder.build(id.withPrefix("recipes/"))); } public abstract Recipe<?> createRecipe(ResourceLocation id); }
0
0.550978
1
0.550978
game-dev
MEDIA
0.99309
game-dev
0.788549
1
0.788549
Fluorohydride/ygopro-scripts
1,066
c69162969.lua
--ライトニング・ボルテックス function c69162969.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_DESTROY) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetCost(c69162969.cost) e1:SetTarget(c69162969.target) e1:SetOperation(c69162969.activate) c:RegisterEffect(e1) end function c69162969.cost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(Card.IsDiscardable,tp,LOCATION_HAND,0,1,e:GetHandler()) end Duel.DiscardHand(tp,Card.IsDiscardable,1,1,REASON_COST+REASON_DISCARD) end function c69162969.filter(c) return c:IsFaceup() end function c69162969.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c69162969.filter,tp,0,LOCATION_MZONE,1,nil) end local sg=Duel.GetMatchingGroup(c69162969.filter,tp,0,LOCATION_MZONE,nil) Duel.SetOperationInfo(0,CATEGORY_DESTROY,sg,sg:GetCount(),0,0) end function c69162969.activate(e,tp,eg,ep,ev,re,r,rp) local sg=Duel.GetMatchingGroup(c69162969.filter,tp,0,LOCATION_MZONE,nil) Duel.Destroy(sg,REASON_EFFECT) end
0
0.93277
1
0.93277
game-dev
MEDIA
0.978512
game-dev
0.929986
1
0.929986
Squalr/Squally
2,159
Source/Scenes/Platformer/Quests/FirewallFissure/DefeatAsmodeus/DefeatAsmodeusLine.cpp
#include "DefeatAsmodeusLine.h" #include "Engine/Quests/QuestTask.h" #include "Scenes/Platformer/Quests/FirewallFissure/DefeatAsmodeus/CraftHeliumBomb.h" #include "Scenes/Platformer/Quests/FirewallFissure/DefeatAsmodeus/DefeatAsmodeus.h" #include "Scenes/Platformer/Quests/FirewallFissure/DefeatAsmodeus/DeliverBomb.h" #include "Scenes/Platformer/Quests/FirewallFissure/DefeatAsmodeus/LavaFlood.h" #include "Scenes/Platformer/Quests/FirewallFissure/DefeatAsmodeus/TalkToQueenElise.h" #include "Scenes/Platformer/Quests/FirewallFissure/DefeatAsmodeus/QueenEliseInterim.h" #include "Scenes/Platformer/Quests/FirewallFissure/DefeatAsmodeus/WantedPosterGone.h" using namespace cocos2d; const std::string DefeatAsmodeusLine::MapKeyQuestLine = "defeat-asmodeus"; DefeatAsmodeusLine* DefeatAsmodeusLine::create() { DefeatAsmodeusLine* instance = new DefeatAsmodeusLine(); instance->autorelease(); return instance; } DefeatAsmodeusLine::DefeatAsmodeusLine() : super(DefeatAsmodeusLine::MapKeyQuestLine, { QuestData(TalkToQueenElise::MapKeyQuest, true, [](GameObject* owner, QuestLine* questLine) { return TalkToQueenElise::create(owner, questLine); }), QuestData(CraftHeliumBomb::MapKeyQuest, true, [](GameObject* owner, QuestLine* questLine) { return CraftHeliumBomb::create(owner, questLine); }), QuestData(DeliverBomb::MapKeyQuest, true, [](GameObject* owner, QuestLine* questLine) { return DeliverBomb::create(owner, questLine); }), QuestData(LavaFlood::MapKeyQuest, true, [](GameObject* owner, QuestLine* questLine) { return LavaFlood::create(owner, questLine); }), QuestData(QueenEliseInterim::MapKeyQuest, true, [](GameObject* owner, QuestLine* questLine) { return QueenEliseInterim::create(owner, questLine); }), QuestData(DefeatAsmodeus::MapKeyQuest, false, [](GameObject* owner, QuestLine* questLine) { return DefeatAsmodeus::create(owner, questLine); }), QuestData(WantedPosterGone::MapKeyQuest, true, [](GameObject* owner, QuestLine* questLine) { return WantedPosterGone::create(owner, questLine); }), }) { } DefeatAsmodeusLine::~DefeatAsmodeusLine() { } QuestLine* DefeatAsmodeusLine::clone() { return DefeatAsmodeusLine::create(); }
0
0.947409
1
0.947409
game-dev
MEDIA
0.975258
game-dev
0.837186
1
0.837186
AAEmu/AAEmu
1,242
AAEmu.Game/Scripts/Commands/MoveAll.cs
using AAEmu.Game.Core.Managers; using AAEmu.Game.Core.Managers.World; using AAEmu.Game.Core.Packets.G2C; using AAEmu.Game.Models.Game; using AAEmu.Game.Models.Game.Char; using AAEmu.Game.Models.Game.Teleport; using AAEmu.Game.Utils.Scripts; namespace AAEmu.Game.Scripts.Commands; public class MoveAll : ICommand { public string[] CommandNames { get; set; } = ["moveall", "move_all"]; public void Execute(Character character, string[] args, IMessageOutput messageOutput) { foreach (var otherChar in WorldManager.Instance.GetAllCharacters()) { if (otherChar != character) { otherChar.DisabledSetPosition = true; otherChar.SendPacket(new SCTeleportUnitPacket(TeleportReason.Gm, 0, character.Transform.World.Position.X, character.Transform.World.Position.Y, character.Transform.World.Position.Z + 1.0f, 0f)); } } } public void OnLoad() { CommandManager.Instance.Register(CommandNames, this); } public string GetCommandLineHelp() { return ""; } public string GetCommandHelpText() { return "Moves every player to your location"; } }
0
0.867718
1
0.867718
game-dev
MEDIA
0.952519
game-dev
0.643384
1
0.643384
GiovanniZambiasi/Client-Side-Prediction
2,088
Assets/Mirror/Examples/MultipleAdditiveScenes/Scripts/Reward.cs
using UnityEngine; namespace Mirror.Examples.MultipleAdditiveScenes { [RequireComponent(typeof(RandomColor))] public class Reward : NetworkBehaviour { static readonly ILogger logger = LogFactory.GetLogger(typeof(Reward)); public bool available = true; public Spawner spawner; public RandomColor randomColor; void OnValidate() { if (randomColor == null) randomColor = GetComponent<RandomColor>(); } [ServerCallback] void OnTriggerEnter(Collider other) { if (other.gameObject.CompareTag("Player")) { ClaimPrize(other.gameObject); } } // This is called from PlayerController.CmdClaimPrize which is invoked by PlayerController.OnControllerColliderHit // This only runs on the server public void ClaimPrize(GameObject player) { if (available) { // This is a fast switch to prevent two players claiming the prize in a bang-bang close contest for it. // First hit turns it off, pending the object being destroyed a few frames later. available = false; Color prizeColor = randomColor.color; // calculate the points from the color ... lighter scores higher as the average approaches 255 // UnityEngine.Color RGB values are float fractions of 255 uint points = (uint)(((prizeColor.r * 255) + (prizeColor.g * 255) + (prizeColor.b * 255)) / 3); if (logger.LogEnabled()) logger.LogFormat(LogType.Log, "Scored {0} points R:{1} G:{2} B:{3}", points, prizeColor.r, prizeColor.g, prizeColor.b); // award the points via SyncVar on the PlayerController player.GetComponent<PlayerScore>().score += points; // spawn a replacement spawner.SpawnPrize(); // destroy this one NetworkServer.Destroy(gameObject); } } } }
0
0.58247
1
0.58247
game-dev
MEDIA
0.806249
game-dev
0.73306
1
0.73306
MelonModding/MelonUtilities
8,807
src/main/java/MelonUtilities/config/Data.java
package MelonUtilities.config; import MelonUtilities.MelonUtilities; import MelonUtilities.config.datatypes.data.*; import MelonUtilities.config.datatypes.jsonadapters.*; import com.b100.utils.FileUtils; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.stream.JsonReader; import net.fabricmc.loader.api.FabricLoader; import net.minecraft.core.data.registry.recipe.adapter.ItemStackJsonAdapter; import net.minecraft.core.item.ItemStack; import net.minecraft.server.player.PlayerListBox; import java.io.*; import java.util.HashMap; import java.util.Map; import java.util.UUID; public class Data { public static Gson gson = new GsonBuilder() .registerTypeAdapter(Role.class, new RoleJsonAdapter()) .registerTypeAdapter(Config.class, new ConfigJsonAdapter()) .registerTypeAdapter(Kit.class, new KitJsonAdapter()) .registerTypeAdapter(ItemStack.class, new ItemStackJsonAdapter()) .registerTypeAdapter(User.class, new UserJsonAdapter()) .registerTypeAdapter(Home.class, new HomeJsonAdapter()) .registerTypeAdapter(Warp.class, new WarpJsonAdapter()) .registerTypeAdapter(Spawn.class, new SpawnJsonAdapter()) .setPrettyPrinting().create(); public static class Roles { public static final Map<String, Role> roleDataHashMap = new HashMap<>(); private static final String roleDir = FabricLoader.getInstance().getConfigDir() + "/" + MelonUtilities.MOD_ID + "/roles"; public static Role create(String roleID){ Role role = new Role(roleID); roleDataHashMap.put(roleID, role); save(roleID); return role; } public static void delete(String roleID){ roleDataHashMap.remove(roleID); if(!new File(roleDir, roleID + ".json").delete()){ MelonUtilities.LOGGER.error("(IO ERROR) Could not delete file for role {}", roleID); } } public static void reload(){ roleDataHashMap.clear(); File dir = new File(roleDir); dir.mkdirs(); File[] files = dir.listFiles(); if (files != null) { for (File child : files) { try { RoleJsonAdapter.fileName = child.getName().replace(".json", ""); Role role = gson.fromJson(new JsonReader(new FileReader(child)), Role.class); roleDataHashMap.put(role.roleID, role); } catch (FileNotFoundException e) { MelonUtilities.LOGGER.error("Could not find file {} while trying to reload roles!", child); continue; } } } else { MelonUtilities.LOGGER.error("Role config dir does not exist!"); } } public static void save(String roleID){ File file = FileUtils.createNewFile(new File(roleDir, roleID + ".json")); try (FileWriter writer = new FileWriter(file)) { gson.toJson(get(roleID), Role.class, writer); PlayerListBox.updateList(); } catch (IOException e) { MelonUtilities.LOGGER.error("Role {} failed to save!", roleID); } } public static void saveAll(){ for(Role role : roleDataHashMap.values()){ role.save(); } } private static void load(String roleID){ roleDataHashMap.remove(roleID); File child = new File(roleDir, roleID + ".json"); try { RoleJsonAdapter.fileName = child.getName().replace(".json", ""); Role role = gson.fromJson(new JsonReader(new FileReader(child)), Role.class); roleDataHashMap.put(role.roleID, role); } catch (FileNotFoundException e) { MelonUtilities.LOGGER.error("Could not reload role {}!", child); } } public static Role get(String roleID){ return roleDataHashMap.get(roleID); } public static Role getOrCreate(String roleID) { if(!roleDataHashMap.containsKey(roleID)){ create(roleID); } return get(roleID); } } public static class Kits { public static final Map<String, Kit> kitDataHashMap = new HashMap<>(); private static final String kitDir = FabricLoader.getInstance().getConfigDir() + "/" + MelonUtilities.MOD_ID + "/kits"; public static Kit create(String kitID){ Kit kit = new Kit(kitID); kitDataHashMap.put(kitID, kit); save(kitID); return kit; } public static void delete(String kitID){ kitDataHashMap.remove(kitID); if(!new File(kitDir, kitID + ".json").delete()){ MelonUtilities.LOGGER.error("(IO ERROR) Could not delete file for kit {}", kitID); } } public static void reload(){ kitDataHashMap.clear(); File dir = new File(kitDir); dir.mkdirs(); File[] files = dir.listFiles(); if (files != null) { for (File child : files) { try { Kit kit = gson.fromJson(new JsonReader(new FileReader(child)), Kit.class); kitDataHashMap.put(kit.kitID, kit); } catch (FileNotFoundException e) { MelonUtilities.LOGGER.error("Could not find file {} while trying to reload kits!", child); continue; } } } else { MelonUtilities.LOGGER.error("Kit config dir does not exist!"); } } public static void save(String kitID){ File file = FileUtils.createNewFile(new File(kitDir, kitID + ".json")); try (FileWriter writer = new FileWriter(file)) { gson.toJson(get(kitID), Kit.class, writer); PlayerListBox.updateList(); } catch (IOException e) { MelonUtilities.LOGGER.error("Kit {} failed to save!", kitID); } } private static void load(String kitID){ kitDataHashMap.remove(kitID); File child = new File(kitDir, kitID + ".json"); try { Kit kit = gson.fromJson(new JsonReader(new FileReader(child)), Kit.class); kitDataHashMap.put(kit.kitID, kit); } catch (FileNotFoundException e) { MelonUtilities.LOGGER.error("Could not reload kit {}!", child); } } public static Kit get(String kitID){ return kitDataHashMap.get(kitID); } public static Kit getOrCreate(String kitID) { if(!kitDataHashMap.containsKey(kitID)){ create(kitID); } return get(kitID); } } public static class MainConfig { public static Config config = new Config(); private static final String configDir = FabricLoader.getInstance().getConfigDir() + "/" + MelonUtilities.MOD_ID; public static void save(){ File file = FileUtils.createNewFile(new File(configDir, "config.json")); try (FileWriter writer = new FileWriter(file)) { gson.toJson(config, Config.class, writer); PlayerListBox.updateList(); } catch (IOException e) { MelonUtilities.LOGGER.error("Config failed to save!"); } } public static void reload(){ File configFile = new File(configDir, "config.json"); try { config = gson.fromJson(new JsonReader(new FileReader(configFile)), Config.class); if(config.configVersion < MelonUtilities.mainConfigVersion){ MelonUtilities.reloadAll(); } } catch (FileNotFoundException e) { MelonUtilities.LOGGER.error("Could not reload Config!"); } } } public static class Users { public static final Map<UUID, User> userDataHashMap = new HashMap<>(); private static final String userDir = FabricLoader.getInstance().getConfigDir() + "/" + MelonUtilities.MOD_ID + "/users"; public static User create(UUID uuid){ User user = new User(uuid); userDataHashMap.put(uuid, user); save(uuid); return user; } public static void delete(UUID uuid){ userDataHashMap.remove(uuid); if(!new File(userDir, uuid + ".json").delete()){ MelonUtilities.LOGGER.error("Could not delete file for User {}", uuid); } } public static void reload(){ userDataHashMap.clear(); File dir = new File(userDir); dir.mkdirs(); File[] files = dir.listFiles(); if (files != null) { for (File child : files) { try { User user = gson.fromJson(new JsonReader(new FileReader(child)), User.class); userDataHashMap.put(user.uuid, user); } catch (FileNotFoundException e) { MelonUtilities.LOGGER.error("Could not find file {} while trying to reload Users!", child); continue; } } } else { MelonUtilities.LOGGER.error("User config dir does not exist!"); } } public static void save(UUID uuid){ File file = FileUtils.createNewFile(new File(userDir, uuid + ".json")); try (FileWriter writer = new FileWriter(file)) { gson.toJson(getOrCreate(uuid), User.class, writer); PlayerListBox.updateList(); } catch (IOException e) { MelonUtilities.LOGGER.error("User {} failed to save!", uuid); } } private static void load(UUID uuid){ userDataHashMap.remove(uuid); File child = new File(userDir, uuid + ".json"); try { User user = gson.fromJson(new JsonReader(new FileReader(child)), User.class); userDataHashMap.put(user.uuid, user); } catch (FileNotFoundException e) { MelonUtilities.LOGGER.error("Could not reload User {}!", child); } } public static User getOrCreate(UUID uuid){ if(!userDataHashMap.containsKey(uuid)){ create(uuid); } return get(uuid); } public static User get(UUID uuid) { return userDataHashMap.get(uuid); } } }
0
0.962619
1
0.962619
game-dev
MEDIA
0.439813
game-dev
0.953735
1
0.953735
flatironinstitute/neurosift
10,120
src/pages/NwbPage/plugins/PSTH/PSTHItemView/DirectSpikeTrainsClient.ts
/* eslint-disable @typescript-eslint/no-explicit-any */ import { DatasetDataType } from "@remote-h5-file"; import { getHdf5DatasetData, getHdf5Group } from "@hdf5Interface"; export class DirectSpikeTrainsClient { #timestampFinders: { [key: number]: TimestampFinder } = {}; constructor( private nwbUrl: string, private path: string, public unitIds: string[], private spikeTimesIndices: DatasetDataType, public startTimeSec: number, public endTimeSec: number, private spike_or_event: "spike" | "event" | undefined, ) {} static async create(nwbUrl: string, path: string) { const group = await getHdf5Group(nwbUrl, path); let spike_or_event: "spike" | "event" | undefined; if (group && group.datasets.find((ds) => ds.name === "spike_times")) { spike_or_event = "spike"; } else if ( group && group.datasets.find((ds) => ds.name === "event_times") ) { spike_or_event = "event"; } else { spike_or_event = undefined; } let unitIds = (await getHdf5DatasetData( nwbUrl, `${path}/id`, {}, )) as any as any[] | undefined; if (!unitIds) throw Error(`Unable to find unit ids for ${path}`); // if unitIds is a Typed array, convert it to a regular array const unitIds2: string[] = []; for (let i = 0; i < unitIds.length; i++) { unitIds2.push(unitIds[i].toString()); } unitIds = unitIds2; // ensure strings unitIds = unitIds.map((val) => val.toString()); const spikeTimesIndices = await getHdf5DatasetData( nwbUrl, `${path}/${spike_or_event}_times_index`, {}, ); const v1 = await getHdf5DatasetData( nwbUrl, `${path}/${spike_or_event}_times`, { slice: [[0, 1]], }, ); const n = spikeTimesIndices ? spikeTimesIndices[spikeTimesIndices.length - 1] : 0; const v2 = await getHdf5DatasetData( nwbUrl, `${path}/${spike_or_event}_times`, { slice: [[n - 1, n]], }, ); const startTimeSec = v1 ? v1[0] : 0; const endTimeSec = v2 ? v2[0] : 1; if (!spikeTimesIndices) throw Error(`Unable to find spike times indices for ${path}`); return new DirectSpikeTrainsClient( nwbUrl, path, unitIds, spikeTimesIndices, startTimeSec, endTimeSec, spike_or_event, ); } get totalNumSpikes() { if (!this.spikeTimesIndices) return undefined; if (!this.spikeTimesIndices) return undefined; return this.spikeTimesIndices[this.spikeTimesIndices.length - 1]; } _createTimestampFinder(unitIndex: number) { const i1 = unitIndex === 0 ? 0 : this.spikeTimesIndices[unitIndex - 1]; const i2 = this.spikeTimesIndices[unitIndex]; const model = { length: i2 - i1, getChunk: async (a1: number, a2: number) => { return await getHdf5DatasetData( this.nwbUrl, `${this.path}/${this.spike_or_event}_times`, { slice: [[i1 + a1, i1 + a2]] }, ); }, }; this.#timestampFinders[unitIndex] = new TimestampFinder(model); } numSpikesForUnit(unitId: number | string) { const ii = this.unitIds.indexOf(unitId.toString()); if (ii < 0) return undefined; const i1 = ii === 0 ? 0 : this.spikeTimesIndices[ii - 1]; const i2 = this.spikeTimesIndices[ii]; return i2 - i1; } async getUnitSpikeTrain( unitId: number | string, o: { canceler?: { onCancel: (() => void)[] } } = {}, ) { const ii = this.unitIds.indexOf(unitId.toString()); if (ii < 0) throw Error(`Unexpected: unitId not found: ${unitId}`); const i1 = ii === 0 ? 0 : this.spikeTimesIndices[ii - 1]; const i2 = this.spikeTimesIndices[ii]; const path = this.path; const tt0 = await getHdf5DatasetData( this.nwbUrl, `${path}/${this.spike_or_event}_times`, { slice: [[i1, i2]], canceler: o.canceler }, ); if (tt0) { return Array.from(tt0); } else { return []; } } async getUnitSpikeTrainForTimeRange( unitId: number | string, t1: number, t2: number, // o: { canceler?: { onCancel: (() => void)[] } } = {}, ) { if (t1 > t2) throw Error("t1 must be <= t2"); const ii = this.unitIds.indexOf(unitId.toString()); if (ii < 0) throw Error(`Unexpected: unitId not found: ${unitId}`); if (!this.#timestampFinders[ii]) { this._createTimestampFinder(ii); } const finder = this.#timestampFinders[ii]; const index1 = await finder.getDataIndexForTime(t1); const index2 = await finder.getDataIndexForTime(t2); if (index1 > index2) throw Error("Unexpected: index1 > index2"); const tt = await finder.getDataForIndices(index1, index2); return tt; } } export class ChunkedDirectSpikeTrainsClient { #chunks: { [key: string]: number[] } = {}; constructor( private client: DirectSpikeTrainsClient, private chunkDurationSec: number, ) {} static async create(nwbUrl: string, path: string, chunkDurationSec = 30) { const client = await DirectSpikeTrainsClient.create(nwbUrl, path); return new ChunkedDirectSpikeTrainsClient(client, chunkDurationSec); } get totalNumSpikes() { return this.client.totalNumSpikes; } get unitIds() { return this.client.unitIds; } get startTimeSec() { return this.client.startTimeSec; } get endTimeSec() { return this.client.endTimeSec; } numSpikesForUnit(unitId: number | string) { return this.client.numSpikesForUnit(unitId); } async _loadChunk(unitId: string, chunkIndex: number) { const key = `${unitId}:${chunkIndex}`; if (key in this.#chunks) return; const t1 = chunkIndex * this.chunkDurationSec; const t2 = (chunkIndex + 1) * this.chunkDurationSec; const tt = await this.client.getUnitSpikeTrainForTimeRange(unitId, t1, t2); this.#chunks[key] = tt; } async getUnitSpikeTrainForTimeRange( unitId: number | string, t1: number, t2: number, ) { const chunkIndex1 = Math.floor(t1 / this.chunkDurationSec); const chunkIndex2 = Math.floor(t2 / this.chunkDurationSec); // ensure we have loaded the chunks const promises = []; for ( let chunkIndex = chunkIndex1; chunkIndex <= chunkIndex2; chunkIndex++ ) { promises.push(this._loadChunk(unitId.toString(), chunkIndex)); } await Promise.all(promises); const ret: number[] = []; for ( let chunkIndex = chunkIndex1; chunkIndex <= chunkIndex2; chunkIndex++ ) { const key = `${unitId}:${chunkIndex}`; const tt = this.#chunks[key]; const t1a = Math.max(t1, chunkIndex * this.chunkDurationSec); const t2a = Math.min((chunkIndex + 1) * this.chunkDurationSec, t2); for (const t of tt) { if (t >= t1a && t < t2a) { ret.push(t); } } } return ret; } } interface TimestampsModel { length: number; getChunk(a1: number, a2: number): Promise<DatasetDataType | undefined>; } class TimestampFinder { #chunkSize = 10000; #chunks: { [key: number]: DatasetDataType } = {}; constructor( private timestampsModel: TimestampsModel, // private estimatedSamplingFrequency: number, ) {} async getDataIndexForTime(time: number): Promise<number> { let iLower = 0; let iUpper = this.timestampsModel.length - 1; if (iUpper === iLower) return iLower; let tLower = await this._get(iLower); let tUpper = await this._get(iUpper); if (isNaN(tUpper)) { // sometimes the final timestamp is NaN, in that case use the second-to-last timestamp // this happens in a Frank Lab dataset: http://localhost:3000/neurosift/?p=/nwb&url=https://dandiarchive.s3.amazonaws.com/blobs/645/10d/64510d67-fab1-45ab-abc3-b18c9738412c tUpper = await this._get(iUpper - 1); iUpper = iUpper - 1; } while (iUpper - iLower > 1) { if (time < tLower) { return iLower; } if (time > tUpper) { return iUpper; } let estimatedIndex = iLower + Math.floor(((iUpper - iLower) * (time - tLower)) / (tUpper - tLower)); if (estimatedIndex <= iLower) estimatedIndex = Math.floor((iUpper + iLower) / 2); if (estimatedIndex >= iUpper) estimatedIndex = Math.floor((iUpper + iLower) / 2); const estimatedT = await this._get(estimatedIndex); if (estimatedT === time) { return estimatedIndex; } if (estimatedT < time) { iLower = estimatedIndex; tLower = estimatedT; } else { iUpper = estimatedIndex; tUpper = estimatedT; } } const distToLower = Math.abs(time - tLower); const distToUpper = Math.abs(time - tUpper); if (distToLower < distToUpper) return iLower; else return iUpper; } async getDataForIndices(i1: number, i2: number) { const ichunk1 = Math.floor(i1 / this.#chunkSize); const ichunk2 = Math.floor(i2 / this.#chunkSize); const ret: number[] = []; for (let ichunk = ichunk1; ichunk <= ichunk2; ichunk++) { const a1 = ichunk * this.#chunkSize; let a2 = (ichunk + 1) * this.#chunkSize; if (a2 > this.timestampsModel.length) a2 = this.timestampsModel.length; const chunk = await this.timestampsModel.getChunk(a1, a2); if (!chunk) throw Error(`Unable to get chunk ${ichunk}`); const i1a = Math.max(i1, a1); const i2a = Math.min(i2, a2); for (let i = i1a; i < i2a; i++) { ret.push(chunk[i - a1]); } } return ret; } async _get(i: number) { const chunkIndex = Math.floor(i / this.#chunkSize); if (!(chunkIndex in this.#chunks)) { const a1 = chunkIndex * this.#chunkSize; let a2 = (chunkIndex + 1) * this.#chunkSize; if (a2 > this.timestampsModel.length) a2 = this.timestampsModel.length; const chunk = await this.timestampsModel.getChunk(a1, a2); if (chunk) { this.#chunks[chunkIndex] = chunk; } else { console.warn("Unable to get chunk", chunkIndex); } } return this.#chunks[chunkIndex][i - chunkIndex * this.#chunkSize]; } }
0
0.886161
1
0.886161
game-dev
MEDIA
0.117885
game-dev
0.958198
1
0.958198
Ragebones/StormCore
12,032
src/common/Collision/Management/VMapManager2.cpp
/* * Copyright (C) 2014-2017 StormCore * * 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/>. */ #include <iostream> #include <iomanip> #include <string> #include <sstream> #include "VMapManager2.h" #include "MapTree.h" #include "ModelInstance.h" #include "WorldModel.h" #include <G3D/Vector3.h> #include "Log.h" #include "VMapDefinitions.h" #include "Errors.h" using G3D::Vector3; namespace VMAP { VMapManager2::VMapManager2() { GetLiquidFlagsPtr = &GetLiquidFlagsDummy; IsVMAPDisabledForPtr = &IsVMAPDisabledForDummy; thread_safe_environment = true; } VMapManager2::~VMapManager2(void) { for (InstanceTreeMap::iterator i = iInstanceMapTrees.begin(); i != iInstanceMapTrees.end(); ++i) { delete i->second; } for (ModelFileMap::iterator i = iLoadedModelFiles.begin(); i != iLoadedModelFiles.end(); ++i) { delete i->second.getModel(); } } void VMapManager2::InitializeThreadUnsafe(std::unordered_map<uint32, std::vector<uint32>> const& mapData) { // the caller must pass the list of all mapIds that will be used in the VMapManager2 lifetime for (auto const& p : mapData) iInstanceMapTrees.insert(InstanceTreeMap::value_type(p.first, nullptr)); thread_safe_environment = false; } Vector3 VMapManager2::convertPositionToInternalRep(float x, float y, float z) const { Vector3 pos; const float mid = 0.5f * 64.0f * 533.33333333f; pos.x = mid - x; pos.y = mid - y; pos.z = z; return pos; } // move to MapTree too? std::string VMapManager2::getMapFileName(unsigned int mapId) { std::stringstream fname; fname.width(4); fname << std::setfill('0') << mapId << std::string(MAP_FILENAME_EXTENSION2); return fname.str(); } int VMapManager2::loadMap(const char* basePath, unsigned int mapId, int x, int y) { int result = VMAP_LOAD_RESULT_IGNORED; if (isMapLoadingEnabled()) { if (_loadMap(mapId, basePath, x, y)) result = VMAP_LOAD_RESULT_OK; else result = VMAP_LOAD_RESULT_ERROR; } return result; } InstanceTreeMap::const_iterator VMapManager2::GetMapTree(uint32 mapId) const { // return the iterator if found or end() if not found/NULL InstanceTreeMap::const_iterator itr = iInstanceMapTrees.find(mapId); if (itr != iInstanceMapTrees.cend() && !itr->second) itr = iInstanceMapTrees.cend(); return itr; } // load one tile (internal use only) bool VMapManager2::_loadMap(uint32 mapId, const std::string& basePath, uint32 tileX, uint32 tileY) { InstanceTreeMap::iterator instanceTree = iInstanceMapTrees.find(mapId); if (instanceTree == iInstanceMapTrees.end()) { if (thread_safe_environment) instanceTree = iInstanceMapTrees.insert(InstanceTreeMap::value_type(mapId, nullptr)).first; else ASSERT(false, "Invalid mapId %u tile [%u, %u] passed to VMapManager2 after startup in thread unsafe environment", mapId, tileX, tileY); } if (!instanceTree->second) { std::string mapFileName = getMapFileName(mapId); StaticMapTree* newTree = new StaticMapTree(mapId, basePath); if (!newTree->InitMap(mapFileName, this)) { delete newTree; return false; } instanceTree->second = newTree; } return instanceTree->second->LoadMapTile(tileX, tileY, this); } void VMapManager2::unloadMap(unsigned int mapId) { InstanceTreeMap::iterator instanceTree = iInstanceMapTrees.find(mapId); if (instanceTree != iInstanceMapTrees.end() && instanceTree->second) { instanceTree->second->UnloadMap(this); if (instanceTree->second->numLoadedTiles() == 0) { delete instanceTree->second; instanceTree->second = nullptr; } } } void VMapManager2::unloadMap(unsigned int mapId, int x, int y) { InstanceTreeMap::iterator instanceTree = iInstanceMapTrees.find(mapId); if (instanceTree != iInstanceMapTrees.end() && instanceTree->second) { instanceTree->second->UnloadMapTile(x, y, this); if (instanceTree->second->numLoadedTiles() == 0) { delete instanceTree->second; instanceTree->second = nullptr; } } } bool VMapManager2::isInLineOfSight(unsigned int mapId, float x1, float y1, float z1, float x2, float y2, float z2) { if (!isLineOfSightCalcEnabled() || IsVMAPDisabledForPtr(mapId, VMAP_DISABLE_LOS)) return true; InstanceTreeMap::const_iterator instanceTree = GetMapTree(mapId); if (instanceTree != iInstanceMapTrees.end()) { Vector3 pos1 = convertPositionToInternalRep(x1, y1, z1); Vector3 pos2 = convertPositionToInternalRep(x2, y2, z2); if (pos1 != pos2) { return instanceTree->second->isInLineOfSight(pos1, pos2); } } return true; } /** get the hit position and return true if we hit something otherwise the result pos will be the dest pos */ bool VMapManager2::getObjectHitPos(unsigned int mapId, float x1, float y1, float z1, float x2, float y2, float z2, float& rx, float &ry, float& rz, float modifyDist) { if (isLineOfSightCalcEnabled() && !IsVMAPDisabledForPtr(mapId, VMAP_DISABLE_LOS)) { InstanceTreeMap::const_iterator instanceTree = GetMapTree(mapId); if (instanceTree != iInstanceMapTrees.end()) { Vector3 pos1 = convertPositionToInternalRep(x1, y1, z1); Vector3 pos2 = convertPositionToInternalRep(x2, y2, z2); Vector3 resultPos; bool result = instanceTree->second->getObjectHitPos(pos1, pos2, resultPos, modifyDist); resultPos = convertPositionToInternalRep(resultPos.x, resultPos.y, resultPos.z); rx = resultPos.x; ry = resultPos.y; rz = resultPos.z; return result; } } rx = x2; ry = y2; rz = z2; return false; } /** get height or INVALID_HEIGHT if no height available */ float VMapManager2::getHeight(unsigned int mapId, float x, float y, float z, float maxSearchDist) { if (isHeightCalcEnabled() && !IsVMAPDisabledForPtr(mapId, VMAP_DISABLE_HEIGHT)) { InstanceTreeMap::const_iterator instanceTree = GetMapTree(mapId); if (instanceTree != iInstanceMapTrees.end()) { Vector3 pos = convertPositionToInternalRep(x, y, z); float height = instanceTree->second->getHeight(pos, maxSearchDist); if (!(height < G3D::finf())) return height = VMAP_INVALID_HEIGHT_VALUE; // No height return height; } } return VMAP_INVALID_HEIGHT_VALUE; } bool VMapManager2::getAreaInfo(unsigned int mapId, float x, float y, float& z, uint32& flags, int32& adtId, int32& rootId, int32& groupId) const { if (!IsVMAPDisabledForPtr(mapId, VMAP_DISABLE_AREAFLAG)) { InstanceTreeMap::const_iterator instanceTree = GetMapTree(mapId); if (instanceTree != iInstanceMapTrees.end()) { Vector3 pos = convertPositionToInternalRep(x, y, z); bool result = instanceTree->second->getAreaInfo(pos, flags, adtId, rootId, groupId); // z is not touched by convertPositionToInternalRep(), so just copy z = pos.z; return result; } } return false; } bool VMapManager2::GetLiquidLevel(uint32 mapId, float x, float y, float z, uint8 reqLiquidType, float& level, float& floor, uint32& type) const { if (!IsVMAPDisabledForPtr(mapId, VMAP_DISABLE_LIQUIDSTATUS)) { InstanceTreeMap::const_iterator instanceTree = GetMapTree(mapId); if (instanceTree != iInstanceMapTrees.end()) { LocationInfo info; Vector3 pos = convertPositionToInternalRep(x, y, z); if (instanceTree->second->GetLocationInfo(pos, info)) { floor = info.ground_Z; ASSERT(floor < std::numeric_limits<float>::max()); ASSERT(info.hitModel); type = info.hitModel->GetLiquidType(); // entry from LiquidType.dbc if (reqLiquidType && !(GetLiquidFlagsPtr(type) & reqLiquidType)) return false; ASSERT(info.hitInstance); if (info.hitInstance->GetLiquidLevel(pos, info, level)) return true; } } } return false; } WorldModel* VMapManager2::acquireModelInstance(const std::string& basepath, const std::string& filename) { //! Critical section, thread safe access to iLoadedModelFiles std::lock_guard<std::mutex> lock(LoadedModelFilesLock); ModelFileMap::iterator model = iLoadedModelFiles.find(filename); if (model == iLoadedModelFiles.end()) { WorldModel* worldmodel = new WorldModel(); if (!worldmodel->readFile(basepath + filename + ".vmo")) { VMAP_ERROR_LOG("misc", "VMapManager2: could not load '%s%s.vmo'", basepath.c_str(), filename.c_str()); delete worldmodel; return NULL; } VMAP_DEBUG_LOG("maps", "VMapManager2: loading file '%s%s'", basepath.c_str(), filename.c_str()); model = iLoadedModelFiles.insert(std::pair<std::string, ManagedModel>(filename, ManagedModel())).first; model->second.setModel(worldmodel); } model->second.incRefCount(); return model->second.getModel(); } void VMapManager2::releaseModelInstance(const std::string &filename) { //! Critical section, thread safe access to iLoadedModelFiles std::lock_guard<std::mutex> lock(LoadedModelFilesLock); ModelFileMap::iterator model = iLoadedModelFiles.find(filename); if (model == iLoadedModelFiles.end()) { VMAP_ERROR_LOG("misc", "VMapManager2: trying to unload non-loaded file '%s'", filename.c_str()); return; } if (model->second.decRefCount() == 0) { VMAP_DEBUG_LOG("maps", "VMapManager2: unloading file '%s'", filename.c_str()); delete model->second.getModel(); iLoadedModelFiles.erase(model); } } bool VMapManager2::existsMap(const char* basePath, unsigned int mapId, int x, int y) { return StaticMapTree::CanLoadMap(std::string(basePath), mapId, x, y); } void VMapManager2::getInstanceMapTree(InstanceTreeMap &instanceMapTree) { instanceMapTree = iInstanceMapTrees; } } // namespace VMAP
0
0.966883
1
0.966883
game-dev
MEDIA
0.77625
game-dev
0.953696
1
0.953696
XANkui/UnityMiniGameParadise
6,590
Assets/MGP_004CompoundBigWatermelon/Scripts/Manager/GameManager.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace MGP_004CompoundBigWatermelon { public class GameManager : IManager { private FruitManager m_FruitManager; private LineManager m_LineManager; private EffectManager m_EffectManager; private AudioManager m_AudioManager; private ScoreManager m_ScoreManager; private UIManager m_UIManager; private Transform m_WorldTrans; private Transform m_UITrans; private Transform m_Warningline; private Transform m_SpawnFruitPosTrans; private bool m_IsGameOverWarning; public bool GameOverWarning => m_IsGameOverWarning; private bool m_IsGameOVer ; public bool GameOver=> m_IsGameOVer; private float m_OverTimer = 0; private float m_WarningTimer = 0; private MonoBehaviour m_Mono; private static GameManager m_Instance; public static GameManager Instance { get { if (m_Instance==null) { m_Instance = new GameManager(); } return m_Instance; } } public void Awake(MonoBehaviour mono) { m_Mono = mono; m_FruitManager = new FruitManager(); m_LineManager = new LineManager(); m_EffectManager = new EffectManager(); m_AudioManager = new AudioManager(); m_ScoreManager = new ScoreManager(); m_UIManager = new UIManager(); } public void Start() { FindGameObjectInScene(); Init(m_WorldTrans, m_UITrans,this); } public void Init(Transform worldTrans, Transform uiTrans, params object[] manager) { m_IsGameOverWarning = false; m_IsGameOVer = false; m_ScoreManager.Init(worldTrans, uiTrans); m_EffectManager.Init(worldTrans, uiTrans); m_AudioManager.Init(worldTrans, uiTrans); m_FruitManager.Init(worldTrans, uiTrans, m_Mono, m_EffectManager,m_AudioManager, m_ScoreManager); m_LineManager.Init(worldTrans, uiTrans, m_FruitManager); m_UIManager.Init(worldTrans, uiTrans, m_ScoreManager); } public void Update() { if (m_IsGameOVer==true) { return; } m_FruitManager.Update(); m_LineManager.Update(); m_EffectManager.Update(); m_AudioManager.Update(); m_ScoreManager.Update(); m_UIManager.Update(); UpdateJudgeGaveOverAndWarning(); } public void Destroy() { m_FruitManager.Destroy(); m_LineManager.Destroy(); m_EffectManager.Destroy(); m_AudioManager.Destroy(); m_ScoreManager.Destroy(); m_UIManager.Destroy(); m_WorldTrans = null; m_UITrans = null; m_Warningline = null; m_SpawnFruitPosTrans = null; m_IsGameOverWarning = false; m_IsGameOVer = false; } void FindGameObjectInScene() { m_WorldTrans = GameObject.Find(GameObjectPathInSceneDefine.WORLD_PATH).transform; m_UITrans = GameObject.Find(GameObjectPathInSceneDefine.UI_PATH).transform; m_Warningline = m_WorldTrans.Find(GameObjectPathInSceneDefine.WARNING_LINE_PATH); m_SpawnFruitPosTrans = m_WorldTrans.Find(GameObjectPathInSceneDefine.SPAWN_FRUIT_POS_TRANS_PATH); } void UpdateJudgeGaveOverAndWarning() { if (IsGameOverWarning() == true) { m_WarningTimer += Time.deltaTime; if (m_WarningTimer >= GameConfig.JUDGE_GAME_OVER_WARNING_TIME_LENGHT) { m_Warningline.gameObject.SetActive(true); } if (IsJudgeGameOver() == true) { m_OverTimer += Time.deltaTime; if (m_OverTimer >= GameConfig.JUDGE_GAME_OVER_TIME_LENGHT) { m_IsGameOVer = true; if (m_FruitManager.CurFruit != null) { m_FruitManager.CurFruit.DisableFruit(); } OnGameOver(); } } else { m_OverTimer = 0; } } else { m_Warningline.gameObject.SetActive(false); m_OverTimer = 0; m_WarningTimer = 0; } } bool IsGameOverWarning() { Fruit fruit; foreach (Transform item in m_SpawnFruitPosTrans) { if (item.gameObject.activeSelf == true) { fruit = item.GetComponent<Fruit>(); if (fruit != null) { if (fruit.CircleCollider2D.enabled == true && fruit != m_FruitManager.CurFruit) { if (m_Warningline.transform.position.y - (fruit.transform.position.y + fruit.CircleCollider2D.radius) < GameConfig.GAME_OVER_WARNING_LINE_DISTANCE) { return true; } } } } } return false; } bool IsJudgeGameOver() { Fruit fruit; foreach (Transform item in m_SpawnFruitPosTrans) { if (item.gameObject.activeSelf == true) { fruit = item.GetComponent<Fruit>(); if (fruit != null) { if (fruit.CircleCollider2D.enabled == true) { if (m_Warningline.transform.position.y - (fruit.transform.position.y + fruit.CircleCollider2D.radius) <= 0) { return true; } } } } } return false; } void OnGameOver() { m_FruitManager.OnGameOver(); m_UIManager.OnGameOver(); } } }
0
0.828572
1
0.828572
game-dev
MEDIA
0.954666
game-dev
0.987206
1
0.987206
Retera/WarsmashModEngine
3,949
core/src/com/etheller/warsmash/viewer5/handlers/w3x/simulation/abilities/skills/human/bloodmage/phoenix/CAbilitySummonPhoenix.java
package com.etheller.warsmash.viewer5.handlers.w3x.simulation.abilities.skills.human.bloodmage.phoenix; import java.util.ArrayList; import java.util.List; import com.etheller.warsmash.units.GameObject; import com.etheller.warsmash.util.War3ID; import com.etheller.warsmash.viewer5.handlers.w3x.simulation.CSimulation; import com.etheller.warsmash.viewer5.handlers.w3x.simulation.CUnit; import com.etheller.warsmash.viewer5.handlers.w3x.simulation.CUnitClassification; import com.etheller.warsmash.viewer5.handlers.w3x.simulation.abilities.skills.CAbilityNoTargetSpellBase; import com.etheller.warsmash.viewer5.handlers.w3x.simulation.abilities.skills.util.CBuffTimedLife; import com.etheller.warsmash.viewer5.handlers.w3x.simulation.abilities.targeting.AbilityTarget; import com.etheller.warsmash.viewer5.handlers.w3x.simulation.abilities.types.definitions.impl.AbilityFields; import com.etheller.warsmash.viewer5.handlers.w3x.simulation.abilities.types.definitions.impl.AbstractCAbilityTypeDefinition; import com.etheller.warsmash.viewer5.handlers.w3x.simulation.orders.OrderIds; import com.etheller.warsmash.viewer5.handlers.w3x.simulation.trigger.enumtypes.CEffectType; public class CAbilitySummonPhoenix extends CAbilityNoTargetSpellBase { private War3ID summonUnitId; private int summonUnitCount; private War3ID buffId; private float areaOfEffect; // TODO maybe "lastSummonHandleIds" instead, for ease of use with saving game, // but then we have to track when they die or else risk re-used handle ID // messing us up private final List<CUnit> lastSummonUnits = new ArrayList<>(); public CAbilitySummonPhoenix(final int handleId, final War3ID alias) { super(handleId, alias); } @Override public void populateData(final GameObject worldEditorAbility, final int level) { this.summonUnitId = War3ID.fromString(worldEditorAbility.getFieldAsString(AbilityFields.UNIT_ID + level, 0)); this.summonUnitCount = worldEditorAbility.getFieldAsInteger(AbilityFields.DATA_A + level, 0); this.buffId = AbstractCAbilityTypeDefinition.getBuffId(worldEditorAbility, level); this.areaOfEffect = worldEditorAbility.getFieldAsFloat(AbilityFields.AREA_OF_EFFECT + level, 0); } @Override public int getBaseOrderId() { return OrderIds.summonphoenix; } @Override public boolean doEffect(final CSimulation simulation, final CUnit unit, final AbilityTarget target) { final float facing = unit.getFacing(); final float facingRad = (float) StrictMath.toRadians(facing); final float x = unit.getX() + ((float) StrictMath.cos(facingRad) * areaOfEffect); final float y = unit.getY() + ((float) StrictMath.sin(facingRad) * areaOfEffect); for (final CUnit lastSummon : this.lastSummonUnits) { if (!lastSummon.isDead()) { lastSummon.kill(simulation); } } this.lastSummonUnits.clear(); for (int i = 0; i < summonUnitCount; i++) { final CUnit summonedUnit = simulation.createUnitSimple(summonUnitId, unit.getPlayerIndex(), x, y, facing); summonedUnit.addClassification(CUnitClassification.SUMMONED); summonedUnit.add(simulation, new CBuffTimedLife(simulation.getHandleIdAllocator().createId(), buffId, getDuration(), false)); simulation.createTemporarySpellEffectOnUnit(summonedUnit, getAlias(), CEffectType.TARGET); this.lastSummonUnits.add(summonedUnit); } return false; } public War3ID getSummonUnitId() { return summonUnitId; } public int getSummonUnitCount() { return summonUnitCount; } public War3ID getBuffId() { return buffId; } public float getAreaOfEffect() { return areaOfEffect; } public void setSummonUnitId(final War3ID summonUnitId) { this.summonUnitId = summonUnitId; } public void setSummonUnitCount(final int summonUnitCount) { this.summonUnitCount = summonUnitCount; } public void setBuffId(final War3ID buffId) { this.buffId = buffId; } public void setAreaOfEffect(final float areaOfEffect) { this.areaOfEffect = areaOfEffect; } }
0
0.890901
1
0.890901
game-dev
MEDIA
0.962363
game-dev
0.990687
1
0.990687
MBU-Team/OpenMBU
1,492
engine/source/core/coreRes.h
//----------------------------------------------------------------------------- // Torque Game Engine // Copyright (C) GarageGames.com, Inc. //----------------------------------------------------------------------------- #ifndef _CORERES_H_ #define _CORERES_H_ #ifndef _RESMANAGER_H_ #include "core/resManager.h" #endif class RawData { private: bool ownMemory; public: char* data; S32 size; RawData() { ownMemory = false; } RawData(Stream& s, S32 sz) { ownMemory = true; size = sz; data = new char[size]; if (data) s.read(size, data); } ~RawData() { if (ownMemory) delete[] data; data = NULL; ownMemory = false; size = 0; } }; //-------------------------------------- RawData type class ResourceTypeRawData : public ResourceType { public: ResourceTypeRawData(const char* ext = ".dat") : ResourceType(ResourceType::typeof(ext)) { } void* construct(Stream* stream, S32 size) { return (void*)new RawData(*stream, size); } void destruct(void* p) { delete (RawData*)p; } }; class ResourceTypeStaticRawData : public ResourceType { public: ResourceTypeStaticRawData(const char* ext = ".sdt") : ResourceType(ResourceType::typeof(ext)) { } void* construct(Stream* stream, S32 size) { return (void*)new RawData(*stream, size); } void destruct(void* p) { } }; #endif //_CORERES_H_
0
0.960854
1
0.960854
game-dev
MEDIA
0.915592
game-dev
0.755556
1
0.755556
cmangos/playerbots
1,118
playerbot/strategy/values/CollisionValue.cpp
#include "playerbot/playerbot.h" #include "CollisionValue.h" #include "playerbot/PlayerbotAIConfig.h" #include "playerbot/ServerFacade.h" #include "Grids/GridNotifiers.h" #include "Grids/GridNotifiersImpl.h" #include "Grids/CellImpl.h" using namespace ai; bool CollisionValue::Calculate() { Unit* target = AI_VALUE(Unit*, qualifier); if (!target) return false; std::list<Unit*> targets; float range = sPlayerbotAIConfig.contactDistance; MaNGOS::AnyUnitInObjectRangeCheck u_check(bot, range); MaNGOS::UnitListSearcher<MaNGOS::AnyUnitInObjectRangeCheck> searcher(targets, u_check); Cell::VisitAllObjects(bot, searcher, range); for (std::list<Unit*>::iterator i = targets.begin(); i != targets.end(); ++i) { Unit* target = *i; if (bot == target) continue; if (!target->isVisibleFor(bot, bot)) continue; float dist = sServerFacade.GetDistance2d(bot, target->GetPositionX(), target->GetPositionY()); if (sServerFacade.IsDistanceLessThan(dist, target->GetObjectBoundingRadius())) return true; } return false; }
0
0.817057
1
0.817057
game-dev
MEDIA
0.920192
game-dev
0.923922
1
0.923922
RecompRando/MMRecompRando
5,322
src/cart_hooks.c
#include "modding.h" #include "global.h" // TODO: figure out how to make this less scuffed (currently can move after being warped) #include "overlays/actors/ovl_En_Horse/z_en_horse.h" struct ObjUm; typedef void (*ObjUmActionFunc)(struct ObjUm*, PlayState*); #define MILK_POTS_COUNT 3 typedef enum ObjUmAnimation { /* -1 */ OBJ_UM_ANIM_MINUS_1 = -1, /* 0 */ OBJ_UM_ANIM_TROT, /* 1 */ OBJ_UM_ANIM_GALLOP, /* 2 */ OBJ_UM_ANIM_IDLE, /* 3 */ OBJ_UM_ANIM_3, // NULL pointer /* 4 */ OBJ_UM_ANIM_LOOK_BACK } ObjUmAnimation; #define UM_LIMB_MAX 0x16 typedef struct ObjUm { /* 0x000 */ DynaPolyActor dyna; /* 0x15C */ ObjUmActionFunc actionFunc; /* 0x160 */ SkelAnime skelAnime; /* 0x1A4 */ Vec3s jointTable[UM_LIMB_MAX]; /* 0x228 */ Vec3s morphTable[UM_LIMB_MAX]; /* 0x2AC */ s16 wheelRot; /* 0x2AE */ s16 type; /* 0x2B0 */ s16 initialPathIndex; /* 0x2B4 */ s32 unk_2B4; /* 0x2B8 */ EnHorse* donkey; /* 0x2BC */ s32 pathIndex; /* 0x2BE */ s32 pointIndex; /* 0x2C4 */ Vec3f unk_2C4; /* 0x2D0 */ Vec3f unk_2D0; /* 0x2DC */ Vec3f unk_2DC; /* 0x2E8 */ Vec3f unk_2E8; /* 0x2F4 */ s32 flags; /* 0x2BC */ Vec3s unk_2F8; /* 0x2FE */ Vec3s unk_2FE; /* 0x304 */ ObjUmAnimation animIndex; /* 0x308 */ Vec3f unk_308; /* 0x314 */ s32 potsLife[MILK_POTS_COUNT]; /* 0x320 */ s32 wasPotHit[MILK_POTS_COUNT]; // resets to false in the same frame /* 0x32C */ Vec3f potPos[MILK_POTS_COUNT]; /* 0x350 */ s32 unk_350; // unused counter? /* 0x354 */ s32 unk_354; // unused? /* 0x358 */ EnHorse* bandit1; /* 0x35C */ EnHorse* bandit2; /* 0x360 */ Vec3f unk_360[16]; /* 0x420 */ s32 unk_420; // ? /* 0x424 */ ColliderCylinder banditsCollisions[2]; /* 0x4BC */ Vec3f cartBedPos; /* 0x4C8 */ u16 lastTime; /* 0x4CC */ s32 unk_4CC; /* 0x4D0 */ s32 eyeTexIndex; /* 0x4D4 */ s32 mouthTexIndex; /* 0x4D8 */ s32 unk_4D8; /* 0x4DC */ s32 unk_4DC; /* 0x4E0 */ s32 areAllPotsBroken; // true when all of the pots have been broken } ObjUm; // size = 0x4E4 typedef enum { /* 0 */ OBJ_UM_TYPE_TERMINA_FIELD, /* 1 */ OBJ_UM_TYPE_RANCH, /* 2 */ OBJ_UM_TYPE_PRE_MILK_RUN, // milk road, pre-minigame /* 3 */ OBJ_UM_TYPE_MILK_RUN_MINIGAME, /* 4 */ OBJ_UM_TYPE_POST_MILK_RUN // milk road, post-minigame } ObjUmType; #define OBJ_UM_FLAG_NONE (0) #define OBJ_UM_FLAG_0001 (1 << 0) #define OBJ_UM_FLAG_MOVING (1 << 1) #define OBJ_UM_FLAG_0004 (1 << 2) #define OBJ_UM_FLAG_WAITING (1 << 3) // Waiting in the Ranch #define OBJ_UM_FLAG_0010 (1 << 4) #define OBJ_UM_FLAG_DRAWN_FLOOR (1 << 5) #define OBJ_UM_FLAG_0040 (1 << 6) #define OBJ_UM_FLAG_PLAYING_MINIGAME (1 << 7) #define OBJ_UM_FLAG_0100 (1 << 8) #define OBJ_UM_FLAG_0200 (1 << 9) // Something bandit1 #define OBJ_UM_FLAG_0400 (1 << 10) // Something bandit2 #define OBJ_UM_FLAG_LOOK_BACK (1 << 11) #define OBJ_UM_FLAG_1000 (1 << 12) #define OBJ_UM_FLAG_MINIGAME_FINISHED (1 << 13) extern s32 D_801BDAA0; RECOMP_PATCH s32 func_80B795A0(PlayState* play, ObjUm* this, s32 arg2) { s32 pad[2]; s32 phi_v1 = true; u16 textId = this->dyna.actor.textId; Player* player; switch (textId) { // "I'll go to town" case 0x33B4: // "Want a ride?" case 0x33CF: SET_WEEKEVENTREG(WEEKEVENTREG_31_40); if (play->msgCtx.choiceIndex == 0) { player = GET_PLAYER(play); Audio_PlaySfx_MessageDecide(); SET_WEEKEVENTREG(WEEKEVENTREG_31_80); // play->nextEntrance = ENTRANCE(ROMANI_RANCH, 11); play->nextEntrance = ENTRANCE(GORMAN_TRACK, 4); if (player->stateFlags1 & PLAYER_STATE1_800000) { D_801BDAA0 = true; } play->transitionType = TRANS_TYPE_64; gSaveContext.nextTransitionType = TRANS_TYPE_FADE_WHITE; play->transitionTrigger = TRANS_TRIGGER_START; phi_v1 = true; } else { Actor_ContinueText(play, &this->dyna.actor, 0x33B5); Audio_PlaySfx_MessageCancel(); Message_BombersNotebookQueueEvent(play, BOMBERS_NOTEBOOK_EVENT_MET_CREMIA); phi_v1 = false; } break; // "I'll go as fast as I can!" case 0x33BB: Actor_ContinueText(play, &this->dyna.actor, 0x33BC); phi_v1 = false; break; // "Chase pursuers with your arrows." case 0x33BC: Actor_ContinueText(play, &this->dyna.actor, 0x33BD); phi_v1 = false; break; // "Understand?" case 0x33BD: if (play->msgCtx.choiceIndex == 0) { Actor_ContinueText(play, &this->dyna.actor, 0x33BE); Audio_PlaySfx_MessageCancel(); } else { Actor_ContinueText(play, &this->dyna.actor, 0x33BF); Audio_PlaySfx_MessageDecide(); } phi_v1 = false; break; // "I'll tell you again!" case 0x33BE: Actor_ContinueText(play, &this->dyna.actor, 0x33BC); phi_v1 = false; break; default: break; } return phi_v1; }
0
0.842353
1
0.842353
game-dev
MEDIA
0.945309
game-dev
0.861793
1
0.861793
realms-mud/core-lib
1,391
areas/tol-dhurath/temple-interior/0x3.c
//***************************************************************************** // Copyright (c) 2025 - Allen Cummings, RealmsMUD, All rights reserved. See // the accompanying LICENSE file for details. //***************************************************************************** inherit "/lib/environment/environment.c"; ///////////////////////////////////////////////////////////////////////////// public void Setup() { cloneEnvironment(); setStateMachine("/areas/tol-dhurath/state-machine/tol-dhurath-quest.c"); setInterior("/lib/environment/interiors/ruin-hallway.c"); addFeature("/lib/environment/features/floors/ruined-marble-floor.c"); addItem("/lib/environment/items/lighting/sconce.c", "south"); addDecorator("ruined interior west alcove north entry"); addExit("east", "/areas/tol-dhurath/temple-interior/1x3.c"); addExitWithDoor("north", "/areas/tol-dhurath/temple-interior/0x4.c"); } ///////////////////////////////////////////////////////////////////////////// public string **customIcon(string **baseIcon, string color, string charset) { string baseColor = getService("region")->iconColor( decoratorType(), color); baseIcon[2][0] = sprintf("%s%s%s", baseColor, (charset == "unicode") ? "\u2560" : "+", (baseColor != "") ? "\x1b[0m" : baseColor); return baseIcon; }
0
0.787502
1
0.787502
game-dev
MEDIA
0.899093
game-dev
0.651105
1
0.651105
ServUO/ServUO
16,735
Scripts/Services/Expansions/Time Of Legends/Myrmidex Invasion/MoonstonePowerGenerator.cs
using Server; using System; using Server.Mobiles; using System.Collections.Generic; using System.Linq; using Server.Commands; namespace Server.Items { public class MoonstonePowerGeneratorAddon : BaseAddon { public override bool ShareHue { get { return false; } } public Timer ActiveTimer { get; set; } public InternalComponent Activator1 { get; set; } public InternalComponent Activator2 { get; set; } [CommandProperty(AccessLevel.GameMaster)] public bool Activated { get; set; } [CommandProperty(AccessLevel.GameMaster)] public bool SetActive { get { return Activated; } set { if (value) { if (ActiveTimer != null) { ActiveTimer.Stop(); ActiveTimer = null; } Activated = true; CheckNetwork(); } } } public bool Link { get; set; } public MoonstonePowerGenerator Generator { get; set; } [Constructable] public MoonstonePowerGeneratorAddon(bool link) { AddonComponent c = new AddonComponent(39759); c.Hue = 2955; AddComponent(c, 0, 0, 0); c = new AddonComponent(39759); c.Hue = 2955; AddComponent(c, -1, 0, 0); c = new AddonComponent(39759); c.Hue = 2955; AddComponent(c, 1, 0, 0); c = new AddonComponent(39759); c.Hue = 2955; AddComponent(c, 0, -1, 0); c = new AddonComponent(39759); c.Hue = 2955; AddComponent(c, 0, 1, 0); c = new AddonComponent(39818); c.Hue = 2955; AddComponent(c, -1, -1, 0); c = new AddonComponent(39818); c.Hue = 2955; AddComponent(c, -1, 1, 0); c = new AddonComponent(39818); c.Hue = 2955; AddComponent(c, 1, -1, 0); c = new AddonComponent(39818); c.Hue = 2955; AddComponent(c, 1, 1, 0); Activator1 = new InternalComponent(40158); Activator2 = new InternalComponent(40203); AddComponent(Activator1, 0, -1, 5); AddComponent(Activator2, 0, 1, 5); AddComponent(new LocalizedAddonComponent(40155, 1156623), 1, 0, 5); AddComponent(new LocalizedAddonComponent(40155, 1156623), -1, 0, 5); AddComponent(new LocalizedAddonComponent(40156, 1156628), -1, 0, 10); AddComponent(new LocalizedAddonComponent(40156, 1156628), 1, 0, 10); //AddComponent(new LocalizedAddonComponent(40147, 1124171), 0, 0, 5); AddComponent(new LocalizedAddonComponent(40157, 1124171), 0, 0, 20); Generator = new MoonstonePowerGenerator(this); Link = link; if (link) Generators.Add(this); } public override void OnLocationChange(Point3D oldlocation) { base.OnLocationChange(oldlocation); if (Generator != null && !Generator.Deleted) { Generator.MoveToWorld(new Point3D(this.X, this.Y, this.Z + 5), this.Map); } } public override void OnMapChange() { base.OnMapChange(); if (Generator != null && !Generator.Deleted) { Generator.Map = this.Map; } } public override void OnComponentUsed(AddonComponent component, Mobile from) { if (!Activated && component != null && component is InternalComponent && from.InRange(component.Location, 2)) { InternalComponent comp = component as InternalComponent; if (!comp.Active) { comp.Active = true; comp.WhoActivated = from; if (Activator1.Active && Activator2.Active && Activator1.WhoActivated != Activator2.WhoActivated) { if (ActiveTimer != null) { ActiveTimer.Stop(); ActiveTimer = null; } Activated = true; CheckNetwork(); } else if (ActiveTimer == null) ActiveTimer = Timer.DelayCall(TimeSpan.FromSeconds(1), Reset); } } } private void Reset() { if (Activator1 != null) Activator1.Active = false; if (Activator2 != null) Activator2.Active = false; ActiveTimer = null; } public class InternalComponent : LocalizedAddonComponent { private bool _Active; [CommandProperty(AccessLevel.GameMaster)] public bool Active { get { return _Active; } set { if (!_Active && value) { ItemID = ActiveID; Effects.PlaySound(this.Location, this.Map, 0x051); } else if (_Active && !value) { ItemID = InactiveID; WhoActivated = null; Effects.PlaySound(this.Location, this.Map, 0x051); } _Active = value; } } public Mobile WhoActivated { get; set; } public int ActiveID { get; set; } public int InactiveID { get; set; } public InternalComponent(int itemid) : base(itemid, 1156624) { InactiveID = itemid; if (itemid == 40203) ActiveID = 40158; else ActiveID = 40203; } public InternalComponent(Serial serial) : base(serial) { } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.Write(0); writer.Write(ActiveID); writer.Write(InactiveID); writer.Write(_Active); } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int v = reader.ReadInt(); ActiveID = reader.ReadInt(); InactiveID = reader.ReadInt(); Active = reader.ReadBool(); MoonstonePowerGeneratorAddon chamber = Addon as MoonstonePowerGeneratorAddon; if (chamber != null) { if (chamber.Activator1 == null) chamber.Activator1 = this; else chamber.Activator2 = this; } } } public override void Delete() { base.Delete(); if (Generators.Contains(this)) Generators.Remove(this); } public static void Configure() { Generators = new List<MoonstonePowerGeneratorAddon>(); } public static void Initialize() { bool active = true; foreach (MoonstonePowerGeneratorAddon c in Generators) { if (!c.Activated) { active = false; break; } } if (!active) { ResetGenerators(true); } else if (Boss == null) { ResetGenerators(); } CommandSystem.Register("ActivateChambers", AccessLevel.Administrator, e => { if (Boss == null) { Generators.ForEach(c => c.Activated = true); CheckNetwork(); } }); CommandSystem.Register("MorphChamberItems", AccessLevel.Administrator, e => { MorphItems(); }); } public static List<MoonstonePowerGeneratorAddon> Generators { get; set; } public static Zipactriotl Boss { get; set; } public static readonly Point3D GroundZero = new Point3D(896, 2304, -19); public static void CheckNetwork() { bool allactive = true; foreach (MoonstonePowerGeneratorAddon c in Generators) { if (!c.Activated) { allactive = false; break; } } if (allactive) { Boss = new Zipactriotl(true); Boss.MoveToWorld(new Point3D(899, 2303, -20), Map.TerMur); foreach (var c in Generators.Where(c => c.Generator != null)) { c.Generator.CanSpawn = true; } MorphItems(); } } public static void MorphItems() { IPooledEnumerable eable = Map.TerMur.GetItemsInRange(GroundZero, 15); foreach (Item item in eable) { if (item.ItemID == 40161) item.ItemID = 40159; else if (item.ItemID == 40142) item.ItemID = 40173; else if (item.ItemID == 40169) item.ItemID = 40174; else if (item.ItemID == 40165) item.ItemID = 40160; else if (item.ItemID == 40159) item.ItemID = 40161; else if (item.ItemID == 40173) item.ItemID = 40142; else if (item.ItemID == 40174) item.ItemID = 40169; else if (item.ItemID == 40160) item.ItemID = 40165; } eable.Free(); } public static void ResetGenerators(bool startup = false) { Generators.ForEach(c => { c.Activated = false; c.Reset(); if (c.Generator == null || c.Generator.Deleted) { c.Generator = new MoonstonePowerGenerator(c); c.Generator.MoveToWorld(new Point3D(c.X, c.Y, c.Z + 5), c.Map); } c.Generator.CanSpawn = false; c.Components.ForEach(comp => { if (!comp.Visible) comp.Visible = true; }); }); if(!startup) MorphItems(); if (Boss != null) Boss = null; } public MoonstonePowerGeneratorAddon(Serial serial) : base(serial) { } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.Write(0); writer.Write(Activated); writer.Write(Link); writer.Write(Generator); } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int v = reader.ReadInt(); Activated = reader.ReadBool(); if (reader.ReadBool()) { Generators.Add(this); Link = true; } Generator = reader.ReadItem() as MoonstonePowerGenerator; if (Generator != null) Generator.Addon = this; } } public class MoonstonePowerGenerator : DamageableItem { public override int LabelNumber { get { return 1156854; } } // Moonstone Power Generator public List<BaseCreature> Spawn; public Timer Timer { get; set; } private bool _CanSpawn; [CommandProperty(AccessLevel.GameMaster)] public bool CanSpawn { get { return _CanSpawn; } set { _CanSpawn = value; if (_CanSpawn) { Spawn = new List<BaseCreature>(); if (Timer != null) { Timer.Stop(); Timer = null; } Timer = Timer.DelayCall(TimeSpan.FromSeconds(30), TimeSpan.FromSeconds(30), OnTick); Timer.Start(); } else { if (Timer != null) { Timer.Stop(); Timer = null; } } } } [CommandProperty(AccessLevel.GameMaster)] public MoonstonePowerGeneratorAddon Addon { get; set; } [Constructable] public MoonstonePowerGenerator(MoonstonePowerGeneratorAddon addon = null) : base(40147, 40153) { Addon = addon; Level = ItemLevel.Average; Name = "Moonstone Power Generator"; } public void OnTick() { if (Spawn.Count >= 7 || this.Deleted || this.Map == null) return; IPooledEnumerable eable = this.Map.GetMobilesInRange(this.Location, 8); foreach (Mobile m in eable) { if (m is PlayerMobile || (m is BaseCreature && ((BaseCreature)m).GetMaster() is PlayerMobile)) { DoSpawn(); break; } } eable.Free(); } private void DoSpawn() { if (Spawn.Count >= 7 || this.Deleted || this.Map == null) return; BaseCreature bc = new IgnisFatalis(); int x = Utility.RandomBool() ? 2 : -2; int y = Utility.RandomBool() ? 2 : -2; bc.MoveToWorld(new Point3D(this.X + x, this.Y + y, this.Map.GetAverageZ(x, y)), this.Map); Spawn.Add(bc); } public override void OnDamage(int amount, Mobile from, bool willkill) { base.OnDamage(amount, from, willkill); int oldhits = Hits; if (this.ItemID == IDHalfHits && this.Hits <= (HitsMax * .10)) { ItemID = 40154; } if (0.033 > Utility.RandomDouble()) { from.PrivateOverheadMessage(Server.Network.MessageType.Regular, 0x23, 1156855, from.NetState); // *Arcing energy from the generator zaps you!* AOS.Damage(from, Utility.RandomMinMax(50, 100), 0, 0, 0, 0, 100); from.FixedParticles(0x3818, 1, 11, 0x13A8, 0, 0, EffectLayer.Waist); Effects.PlaySound(this.Location, this.Map, 0x1DC); } } public override void OnAfterDestroyed() { Effects.PlaySound(this.Location, this.Map, 0x665); if (Spawn != null) { Spawn.ForEach(bc => { if(bc != null && bc.Alive) bc.Kill(); }); Spawn.Clear(); Spawn.TrimExcess(); Spawn = null; } if (Timer != null) { Timer.Stop(); Timer = null; } if (Addon != null) { AddonComponent comp = Addon.Components.FirstOrDefault(c => c.ItemID == 40157); if (comp != null) comp.Visible = false; } base.OnAfterDestroyed(); } public MoonstonePowerGenerator(Serial serial) : base(serial) { } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.Write(0); } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int v = reader.ReadInt(); } } }
0
0.955072
1
0.955072
game-dev
MEDIA
0.982946
game-dev
0.87168
1
0.87168
fulpstation/fulpstation
5,336
code/modules/events/wizard/rpgtitles.dm
/datum/round_event_control/wizard/rpgtitles //its time to adventure on boys name = "RPG Titles" weight = 3 typepath = /datum/round_event/wizard/rpgtitles max_occurrences = 1 earliest_start = 0 MINUTES description = "Everyone gains an RPG title hovering below them." min_wizard_trigger_potency = 4 max_wizard_trigger_potency = 7 /datum/round_event/wizard/rpgtitles/start() GLOB.rpgtitle_controller = new /datum/rpgtitle_controller ///Holds the global datum for rpgtitle, so anywhere may check for its existence (it signals into whatever it needs to modify, so it shouldn't require fetching) GLOBAL_DATUM(rpgtitle_controller, /datum/rpgtitle_controller) /datum/rpgtitle_controller /datum/rpgtitle_controller/New() . = ..() RegisterSignal(SSdcs, COMSIG_GLOB_CREWMEMBER_JOINED, PROC_REF(on_crewmember_join)) RegisterSignal(SSdcs, COMSIG_GLOB_MOB_LOGGED_IN, PROC_REF(on_mob_login)) handle_current_jobs() /datum/rpgtitle_controller/Destroy(force) UnregisterSignal(SSdcs, list(COMSIG_GLOB_CREWMEMBER_JOINED, COMSIG_GLOB_MOB_LOGGED_IN)) . = ..() ///signal sent by a player list expanding /datum/rpgtitle_controller/proc/on_mob_login(datum/source, mob/new_login) SIGNAL_HANDLER if(isliving(new_login)) var/mob/living/living_login = new_login if(living_login.stat != DEAD && !living_login.maptext) on_crewmember_join(source, living_login, living_login.mind.assigned_role.title) ///signal sent by a crewmember joining /datum/rpgtitle_controller/proc/on_crewmember_join(datum/source, mob/living/new_crewmember, rank) SIGNAL_HANDLER var/datum/job/job = SSjob.get_job(rank) //we must prepare for the mother of all strings new_crewmember.maptext_height = max(new_crewmember.maptext_height, 32) new_crewmember.maptext_width = max(new_crewmember.maptext_width, 112) new_crewmember.maptext_x = -38 - new_crewmember.base_pixel_x new_crewmember.maptext_y = -32 //list of lists involving strings related to a biotype flag, their position in the list equal to the position they were defined as bitflags. //the first list entry is an adjective, the second is a noun. if null, we don't want to describe this biotype, and so even if the mob //has that biotype, the null is skipped var/list/biotype_titles = list( null, //organic is too common to be a descriptor null, //mineral is only used with carbons list("Mechanical", "Robot"), list("Reanimated", "Undead"), list("Bipedal", "Humanoid"), list("Insectile", "Bug"), list("Beastly", "Beast"), list("Monstrous", "Megafauna"), list("Reptilian", "Lizard"), list("Paranormal", "Spirit"), list("Flowering", "Plant"), ) var/maptext_title = "" if(!isanimal_or_basicmob(new_crewmember)) maptext_title = job.rpg_title || job.title else //this following code can only be described as bitflag black magic. ye be warned. i tried to comment excessively to explain what the fuck is happening var/list/applicable_biotypes = list() for(var/biotype_flag_position in 0 to 10) var/biotype_flag = (1 << biotype_flag_position) if(new_crewmember.mob_biotypes & biotype_flag)//they have this flag if(biotype_titles[biotype_flag_position+1]) //if there is a fitting verbage for this biotype... applicable_biotypes += list(biotype_titles[biotype_flag_position+1])//...add it to the list of applicable biotypes if(!applicable_biotypes.len) //there will never be an adjective anomaly because anomaly is only added when there are no choices applicable_biotypes += list(null, "Anomaly") //shuffle it to allow for some cool combinations of adjectives and nouns applicable_biotypes = shuffle(applicable_biotypes) //okay, out of the black magic area we now have a list of things to describe our mob, yay!!! for(var/iteration in 1 to applicable_biotypes.len) if(iteration == applicable_biotypes.len) //last descriptor to add, make it the noun maptext_title += applicable_biotypes[iteration][2] break //there are more descriptors, make it an adjective maptext_title += "[applicable_biotypes[iteration][1]] " //mother of all strings... new_crewmember.maptext = MAPTEXT_TINY_UNICODE("<span style='text-align: center; vertical-align: top; -dm-text-outline: 1px #0005'><span style='color: [new_crewmember.chat_color || rgb(rand(100,255), rand(100,255), rand(100,255))]'>Level [rand(1, 100)] [maptext_title]</span></span>") if(!(job.job_flags & JOB_CREW_MEMBER)) return var/obj/item/card/id/card = new_crewmember.get_idcard() if(!card)//since this is called on current crew, some may not have IDs. shame on them for missing out! return card.name = "adventuring license" card.desc = "A written license from the adventuring guild. You're good to go!" card.icon_state = "card_rpg" card.assignment = job.rpg_title if(istype(card, /obj/item/card/id/advanced)) var/obj/item/card/id/advanced/advanced_card = card advanced_card.assigned_icon_state = "rpg_assigned" card.update_label() card.update_icon() /** * ### handle_current_jobs * * Calls on_crewmember_join on every crewmember * If the item it is giving fantasy to is a storage item, there's a chance it'll drop in an item fortification scroll. neat! */ /datum/rpgtitle_controller/proc/handle_current_jobs() for(var/mob/living/player as anything in GLOB.alive_player_list) on_crewmember_join(SSdcs, player, player.mind?.assigned_role.title)
0
0.941111
1
0.941111
game-dev
MEDIA
0.894461
game-dev
0.886694
1
0.886694
TeamREPENTOGON/REPENTOGON
1,153
repentogon/LuaInterfaces/Room/LuaRailManager.cpp
#include "IsaacRepentance.h" #include "LuaCore.h" #include "HookSystem.h" LUA_FUNCTION(Lua_RoomGetRailManager) { Room* room = lua::GetLuabridgeUserdata<Room*>(L, 1, lua::Metatables::ROOM, "Room"); RailManager** ud = (RailManager**)lua_newuserdata(L, sizeof(RailManager*)); *ud = &room->_railManager; luaL_setmetatable(L, lua::metatables::RailManagerMT); return 1; } LUA_FUNCTION(Lua_RailManagerGetRailsSprite) { RailManager* railManager = *lua::GetRawUserdata<RailManager**>(L, 1, lua::metatables::RailManagerMT); ANM2* anm2 = &railManager->_sprite; lua::luabridge::UserdataPtr::push(L, anm2, lua::GetMetatableKey(lua::Metatables::SPRITE)); return 1; } static void RegisterRailManager(lua_State* L) { lua::RegisterFunction(L, lua::Metatables::ROOM, "GetRailManager", Lua_RoomGetRailManager); luaL_Reg functions[] = { { "GetRailsSprite", Lua_RailManagerGetRailsSprite }, { NULL, NULL } }; lua::RegisterNewClass(L, lua::metatables::RailManagerMT, lua::metatables::RailManagerMT, functions); } HOOK_METHOD(LuaEngine, RegisterClasses, () -> void) { super(); lua::LuaStackProtector protector(_state); RegisterRailManager(_state); }
0
0.617536
1
0.617536
game-dev
MEDIA
0.755786
game-dev
0.656034
1
0.656034
rwtema/Extra-Utilities-2-Source
1,981
1.10.2/src/main/java/com/rwtema/extrautils2/power/PowerMultipliers.java
package com.rwtema.extrautils2.power; import net.minecraft.util.math.MathHelper; import net.minecraft.world.World; public class PowerMultipliers { public final static IWorldPowerMultiplier SOLAR = new IWorldPowerMultiplier() { @Override public float multiplier(World world) { if (world == null) return 0; return !isDaytime(world) ? 0 : (world.isRaining() ? 0.95F : 1F); } @Override public String toString() { return "SOLAR"; } }; public final static IWorldPowerMultiplier LUNAR = new IWorldPowerMultiplier() { @Override public float multiplier(World world) { if (world == null) return 0; return (!isDaytime(world) ? 1 + world.getCurrentMoonPhaseFactor() * 0.25F : 0); } @Override public String toString() { return "LUNAR"; } }; public final static IWorldPowerMultiplier WIND = new IWorldPowerMultiplier() { private static final int TIME_POWER = 8; private static final int MASK = (1 << TIME_POWER) - 1; private static final float TIME_DIVISOR = 1 << TIME_POWER; private static final int RESULT_POW = 8; private static final int RESULT_MASK = (1 << RESULT_POW) - 1; private static final float RESULT_DIVISOR = 1 << RESULT_POW; @Override public float multiplier(World world) { if (world == null) return 0; long t = world.getTotalWorldTime(); float v = ((int) t & MASK) / TIME_DIVISOR; long k = t >> TIME_POWER; k += world.provider.getDimension() * 31L; long a = k * k * 42317861L + k * 11L; long b = a + (2 * k + 1) * 42317861L + 11L; float ai = ((int) (a & RESULT_MASK)) / RESULT_DIVISOR; float bi = ((int) (b & RESULT_MASK)) / RESULT_DIVISOR; float v1 = ai + (bi - ai) * v; return 0.5F + v1 * 2F + (world.isRaining() ? 1 : 0) + (world.isThundering() ? 2 : 0); } @Override public String toString() { return "WIND"; } }; public static boolean isDaytime(World world) { return MathHelper.cos(world.getCelestialAngle(1) * ((float) Math.PI * 2.0F)) >= 0; } }
0
0.794237
1
0.794237
game-dev
MEDIA
0.971506
game-dev
0.905306
1
0.905306
gwathlobal/CotD
2,667
src/gods.lisp
(in-package :cotd) (defconstant +malseraphs-piety-very-low+ 40) (defconstant +malseraphs-piety-low+ 80) (defconstant +malseraphs-piety-medium+ 120) (defconstant +malseraphs-piety-high+ 160) (defconstant +malseraphs-piety-very-high+ 200) (defclass god () ((id :initarg :id :accessor id) (name :initform "Unnamed god" :initarg :name :accessor name) (piety-level-func :initform #'(lambda (god piety-num) (declare (ignore god piety-num)) "") :initarg :piety-level-func :accessor piety-level-func) (piety-str-func :initform #'(lambda (god piety-num) (declare (ignore god piety-num)) "") :initarg :piety-str-func :accessor piety-str-func) (piety-tick-func :initform #'(lambda (god mob) (declare (ignore god mob)) nil) :initarg :piety-tick-func :accessor piety-tick-func) (piety-change-str-func :initform #'(lambda (god piety-num-new piety-num-old) (declare (ignore god piety-num-new piety-num-old)) "") :initarg :piety-change-str-func :accessor piety-change-str-func) )) (defun get-god-by-id (god-id) (aref *gods* god-id)) (defun set-god-type (god) (when (>= (id god) (length *gods*)) (adjust-array *gods* (list (1+ (id god))))) (setf (aref *gods* (id god)) god)) (defun return-piety-str (god-id piety-num) (funcall (piety-str-func (get-god-by-id god-id)) (get-god-by-id god-id) piety-num)) (defun get-worshiped-god-type (worshiped-god) (first worshiped-god)) (defun get-worshiped-god-piety (worshiped-god) (second worshiped-god)) (defun get-worshiped-god-param1 (worshiped-god) (third worshiped-god)) (defun get-worshiped-god-param2 (worshiped-god) (fourth worshiped-god)) (defun check-piety-level-changed (god-id piety-num-old piety-num-new) (let ((god (get-god-by-id god-id))) (if (/= (funcall (piety-level-func god) god piety-num-old) (funcall (piety-level-func god) god piety-num-new)) t nil))) (defun return-piety-change-str (god-id piety-num-new piety-num-old) (funcall (piety-change-str-func (get-god-by-id god-id)) (get-god-by-id god-id) piety-num-new piety-num-old)) (defun increase-piety-for-god (god-id mob piety-inc) (when (and (worshiped-god mob) (= (get-worshiped-god-type (worshiped-god mob)) god-id)) (set-mob-piety mob (+ (get-worshiped-god-piety (worshiped-god mob)) piety-inc))))
0
0.555838
1
0.555838
game-dev
MEDIA
0.498783
game-dev
0.556445
1
0.556445
evemuproject/evemu_server
6,012
src/eve-server/exploration/Probes.h
/** * @name Probes.h * Probe Item/SE class for EVEmu * * @Author: Allan * @date: 10 March 2018 * */ #ifndef EVEMU_EXPLORE_PROBES_H_ #define EVEMU_EXPLORE_PROBES_H_ #include "EVEServerConfig.h" #include "StaticDataMgr.h" #include "../../eve-common/EVE_Scanning.h" #include "inventory/InventoryItem.h" #include "system/SystemEntity.h" /** * InventoryItem for probe object. */ class ProbeItem : public InventoryItem { friend class InventoryItem; // to let it construct us public: ProbeItem(uint32 itemID, const ItemType &_type, const ItemData &_data); virtual ~ProbeItem() { /* Do nothing here */ } /* virtual functions default to base class and overridden as needed */ virtual void Delete(); //totally removes item from game and deletes from the DB. static ProbeItemRef Load( uint32 itemID); static ProbeItemRef Spawn( ItemData &data); protected: using InventoryItem::_Load; //virtual bool _Load(); // Template loader: template<class _Ty> static RefPtr<_Ty> _LoadItem( uint32 itemID, const ItemType &type, const ItemData &data) { if ((type.groupID() != EVEDB::invGroups::Scanner_Probe) and (type.groupID() != EVEDB::invGroups::Survey_Probe) //and (type.groupID() != EVEDB::invGroups::Warp_Disruption_Probe) this wont work here... and (type.groupID() != EVEDB::invGroups::Obsolete_Probes)) { _log(ITEM__ERROR, "Trying to load %s as Probe.", sDataMgr.GetCategoryName(type.categoryID())); if (sConfig.debug.StackTrace) EvE::traceStack(); return RefPtr<_Ty>(); } return ProbeItemRef( new ProbeItem(itemID, type, data)); } static uint32 CreateItemID( ItemData &data); }; /** * DynamicSystemEntity which represents celestial object in space */ class PyServiceMgr; class Scan; class ProbeSE : public DynamicSystemEntity { public: // abandoned probe c'tor ProbeSE(ProbeItemRef self, PyServiceMgr& services, SystemManager* system); // launched probe c'tor ProbeSE(ProbeItemRef self, PyServiceMgr& services, SystemManager* system, InventoryItemRef moduleRef, ShipItemRef shipRef); virtual ~ProbeSE(); /* Process Calls - Overridden as needed in derived classes */ virtual bool ProcessTic(); /* class type pointer querys. */ virtual ProbeSE* GetProbeSE() { return this; } /* class type tests. */ /* Base */ virtual bool IsProbeSE() { return true; } /* virtual functions default to base class and overridden as needed */ virtual void MakeDamageState(DoDestinyDamageState &into); virtual PyDict* MakeSlimItem(); /* specific functions handled in this class. */ void RecoverProbe(PyList* list); void UpdateProbe(ProbeData& data); // removes probe from system and scan map, and sends RemoveProbe call to client // does not remove probe from entity list void RemoveProbe(); void SendNewProbe(); void SendSlimChange(); void SendStateChange(uint8 state); void SendWarpStart(float travelTime); void SendWarpEnd(); void SetScan(Scan* pScan) { m_scan = pScan; } void RemoveScan() { m_scan = nullptr; } void StartStateTimer(uint16 time) { m_stateTimer.Start(time); } bool IsMoving(); void SetState(uint8 state=Probe::State::Idle) { m_state = state; } uint8 GetState() { return m_state; } uint8 GetRangeStep() { return m_rangeStep; } // remaining move time in ms uint16 GetMoveTime() { return m_stateTimer.GetRemainingTime(); } int64 GetExpiryTime() { return m_expiry; } // return deviation in meters based on current probe settings float GetDeviation(); // return probe scan range setting in km float GetScanRange() { return m_scanRange; } float GetRangeModifier(float dist); // total probe scan strength, based on data modified by char skills, ship, launcher, and range float GetScanStrength(); GPoint GetDestination() { return m_destination; } const char* GetStateName(uint8 state); bool CanScanShips() { return m_scanShips; } bool IsRing() { return m_ring; } bool IsSphere() { return m_sphere; } void SetRing(bool set=false) { m_ring = set; } void SetSphere(bool set=false) { m_sphere = set; } // this will allow players with Sensor Linking L5 and Signal Acquisition L5 // to add another set of probe results to the signal being scanned (max of 4) bool HasMaxSkill(); private: Timer m_lifeTimer; Timer m_returnTimer; Timer m_stateTimer; Scan* m_scan; Client* m_client; GPoint m_destination; ShipItemRef m_shipRef; InventoryItemRef m_moduleRef; bool m_scanShips; bool m_ring; // used to send additional data to client for partial hit bool m_sphere; // used to send additional data to client for partial hit uint8 m_state; uint8 m_rangeStep; // range 'click'. values are 1 to 8. sent from client uint8 m_rangeFactor; // exponent for range checks uint32 m_baseScanRange; // lowest scan radius, in km int64 m_expiry; // probe lifetime as filetime float m_secStatus; float m_scanRange; // in km. sent from client float m_scanStrength; // scan str in decimal. unsure of uom float m_scanDeviation; // max scan deviation for this probe, in % where 1.0 = 100 }; #endif // EVEMU_EXPLORE_PROBES_H_
0
0.951679
1
0.951679
game-dev
MEDIA
0.389509
game-dev
0.900087
1
0.900087
Mrbt0907/The-Titans-Mod
1,512
src/main/java/net/mrbt0907/thetitans/items/AbstractTitanBow.java
package net.mrbt0907.thetitans.items; import java.util.function.Predicate; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.projectile.EntityArrow; import net.minecraft.item.ItemStack; import net.minecraft.world.World; import net.mrbt0907.util.item.ItemBowEX; public class AbstractTitanBow extends ItemBowEX { public AbstractTitanBow(Predicate<ItemStack> arrowType, int enchantability) { super(arrowType, enchantability); } @Override public void onStartUse(ItemStack stack, World world, EntityPlayer shooter) { // TODO Auto-generated method stub } @Override public void onTickUse(ItemStack stack, World world, EntityPlayer shooter, int timeLeft) { // TODO Auto-generated method stub } @Override public void onStopUse(ItemStack stack, World world, EntityPlayer shooter, int timeLeft) { // TODO Auto-generated method stub } @Override public void onShootPre(ItemStack stack, World world, EntityPlayer shooter, int timeLeft) { // TODO Auto-generated method stub } @Override public void onShoot(ItemStack stack, World world, EntityPlayer shooter, EntityArrow arrow, int timeLeft, int arrowIndex) { // TODO Auto-generated method stub } @Override public void onShootPost(ItemStack stack, World world, EntityPlayer shooter, int timeLeft) { // TODO Auto-generated method stub } @Override public void onShootFail(ItemStack stack, World world, EntityPlayer shooter, int timeLeft) { // TODO Auto-generated method stub } }
0
0.693586
1
0.693586
game-dev
MEDIA
0.983143
game-dev
0.723213
1
0.723213
ozanges/Waveshare-RP2040-Touch-LCD-1.28
5,859
src/libraries/lvgl/src/core/lv_obj_class.c
/** * @file lv_obj_class.c * */ /********************* * INCLUDES *********************/ #include "lv_obj.h" #include "lv_theme.h" /********************* * DEFINES *********************/ #define MY_CLASS &lv_obj_class /********************** * TYPEDEFS **********************/ /********************** * GLOBAL PROTOTYPES **********************/ /********************** * STATIC PROTOTYPES **********************/ static void lv_obj_construct(lv_obj_t * obj); static uint32_t get_instance_size(const lv_obj_class_t * class_p); /********************** * STATIC VARIABLES **********************/ /********************** * MACROS **********************/ /********************** * GLOBAL FUNCTIONS **********************/ lv_obj_t * lv_obj_class_create_obj(const lv_obj_class_t * class_p, lv_obj_t * parent) { LV_TRACE_OBJ_CREATE("Creating object with %p class on %p parent", (void *)class_p, (void *)parent); uint32_t s = get_instance_size(class_p); lv_obj_t * obj = lv_mem_alloc(s); if(obj == NULL) return NULL; lv_memset_00(obj, s); obj->class_p = class_p; obj->parent = parent; /*Create a screen*/ if(parent == NULL) { LV_TRACE_OBJ_CREATE("creating a screen"); lv_disp_t * disp = lv_disp_get_default(); if(!disp) { LV_LOG_WARN("No display created yet. No place to assign the new screen"); lv_mem_free(obj); return NULL; } if(disp->screens == NULL) { disp->screens = lv_mem_alloc(sizeof(lv_obj_t *)); disp->screens[0] = obj; disp->screen_cnt = 1; } else { disp->screen_cnt++; disp->screens = lv_mem_realloc(disp->screens, sizeof(lv_obj_t *) * disp->screen_cnt); disp->screens[disp->screen_cnt - 1] = obj; } /*Set coordinates to full screen size*/ obj->coords.x1 = 0; obj->coords.y1 = 0; obj->coords.x2 = lv_disp_get_hor_res(NULL) - 1; obj->coords.y2 = lv_disp_get_ver_res(NULL) - 1; } /*Create a normal object*/ else { LV_TRACE_OBJ_CREATE("creating normal object"); LV_ASSERT_OBJ(parent, MY_CLASS); if(parent->spec_attr == NULL) { lv_obj_allocate_spec_attr(parent); } if(parent->spec_attr->children == NULL) { parent->spec_attr->children = lv_mem_alloc(sizeof(lv_obj_t *)); parent->spec_attr->children[0] = obj; parent->spec_attr->child_cnt = 1; } else { parent->spec_attr->child_cnt++; parent->spec_attr->children = lv_mem_realloc(parent->spec_attr->children, sizeof(lv_obj_t *) * parent->spec_attr->child_cnt); parent->spec_attr->children[parent->spec_attr->child_cnt - 1] = obj; } } return obj; } void lv_obj_class_init_obj(lv_obj_t * obj) { lv_obj_mark_layout_as_dirty(obj); lv_obj_enable_style_refresh(false); lv_theme_apply(obj); lv_obj_construct(obj); lv_obj_enable_style_refresh(true); lv_obj_refresh_style(obj, LV_PART_ANY, LV_STYLE_PROP_ANY); lv_obj_refresh_self_size(obj); lv_group_t * def_group = lv_group_get_default(); if(def_group && lv_obj_is_group_def(obj)) { lv_group_add_obj(def_group, obj); } lv_obj_t * parent = lv_obj_get_parent(obj); if(parent) { /*Call the ancestor's event handler to the parent to notify it about the new child. *Also triggers layout update*/ lv_event_send(parent, LV_EVENT_CHILD_CHANGED, obj); lv_event_send(parent, LV_EVENT_CHILD_CREATED, obj); /*Invalidate the area if not screen created*/ lv_obj_invalidate(obj); } } void _lv_obj_destruct(lv_obj_t * obj) { if(obj->class_p->destructor_cb) obj->class_p->destructor_cb(obj->class_p, obj); if(obj->class_p->base_class) { /*Don't let the descendant methods run during destructing the ancestor type*/ obj->class_p = obj->class_p->base_class; /*Call the base class's destructor too*/ _lv_obj_destruct(obj); } } bool lv_obj_is_editable(lv_obj_t * obj) { const lv_obj_class_t * class_p = obj->class_p; /*Find a base in which editable is set*/ while(class_p && class_p->editable == LV_OBJ_CLASS_EDITABLE_INHERIT) class_p = class_p->base_class; if(class_p == NULL) return false; return class_p->editable == LV_OBJ_CLASS_EDITABLE_TRUE ? true : false; } bool lv_obj_is_group_def(lv_obj_t * obj) { const lv_obj_class_t * class_p = obj->class_p; /*Find a base in which group_def is set*/ while(class_p && class_p->group_def == LV_OBJ_CLASS_GROUP_DEF_INHERIT) class_p = class_p->base_class; if(class_p == NULL) return false; return class_p->group_def == LV_OBJ_CLASS_GROUP_DEF_TRUE ? true : false; } /********************** * STATIC FUNCTIONS **********************/ static void lv_obj_construct(lv_obj_t * obj) { const lv_obj_class_t * original_class_p = obj->class_p; if(obj->class_p->base_class) { /*Don't let the descendant methods run during constructing the ancestor type*/ obj->class_p = obj->class_p->base_class; /*Construct the base first*/ lv_obj_construct(obj); } /*Restore the original class*/ obj->class_p = original_class_p; if(obj->class_p->constructor_cb) obj->class_p->constructor_cb(obj->class_p, obj); } static uint32_t get_instance_size(const lv_obj_class_t * class_p) { /*Find a base in which instance size is set*/ const lv_obj_class_t * base = class_p; while(base && base->instance_size == 0) base = base->base_class; if(base == NULL) return 0; /*Never happens: set at least in `lv_obj` class*/ return base->instance_size; }
0
0.962503
1
0.962503
game-dev
MEDIA
0.482388
game-dev,graphics-rendering
0.968914
1
0.968914
MrCrayfish/MrCrayfishDeviceMod
4,194
src/main/java/com/mrcrayfish/device/recipe/RecipeCutPaper.java
package com.mrcrayfish.device.recipe; import com.mrcrayfish.device.Reference; import com.mrcrayfish.device.init.DeviceBlocks; import net.minecraft.init.Items; import net.minecraft.inventory.InventoryCrafting; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.IRecipe; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.NonNullList; import net.minecraft.util.ResourceLocation; import net.minecraft.world.World; import net.minecraftforge.common.util.Constants; /** * Author: MrCrayfish */ public class RecipeCutPaper extends net.minecraftforge.registries.IForgeRegistryEntry.Impl<IRecipe> implements IRecipe { public RecipeCutPaper() { this.setRegistryName(new ResourceLocation(Reference.MOD_ID, "cut_paper")); } @Override public boolean matches(InventoryCrafting inv, World worldIn) { ItemStack paper = ItemStack.EMPTY; ItemStack shear = ItemStack.EMPTY; for(int i = 0; i < inv.getSizeInventory(); i++) { ItemStack stack = inv.getStackInSlot(i); if(!stack.isEmpty()) { if(stack.getItem() == Item.getItemFromBlock(DeviceBlocks.PAPER)) { if(!paper.isEmpty()) return false; paper = stack; } if(stack.getItem() == Items.SHEARS) { if(!shear.isEmpty()) return false; shear = stack; } } } return !paper.isEmpty() && !shear.isEmpty(); } @Override public ItemStack getCraftingResult(InventoryCrafting inv) { ItemStack paper = ItemStack.EMPTY; for(int i = 0; i < inv.getSizeInventory(); i++) { ItemStack stack = inv.getStackInSlot(i); if(!stack.isEmpty()) { if(stack.getItem() == Item.getItemFromBlock(DeviceBlocks.PAPER)) { if(!paper.isEmpty()) return ItemStack.EMPTY; paper = stack; } } } if(!paper.isEmpty() && paper.hasTagCompound()) { ItemStack result = new ItemStack(DeviceBlocks.PAPER); NBTTagCompound tag = paper.getTagCompound(); if(!tag.hasKey("BlockEntityTag", Constants.NBT.TAG_COMPOUND)) { return ItemStack.EMPTY; } NBTTagCompound blockTag = tag.getCompoundTag("BlockEntityTag"); if(!blockTag.hasKey("print", Constants.NBT.TAG_COMPOUND)) { return ItemStack.EMPTY; } NBTTagCompound printTag = blockTag.getCompoundTag("print"); NBTTagCompound data = printTag.getCompoundTag("data"); if(!data.hasKey("pixels", Constants.NBT.TAG_INT_ARRAY) || !data.hasKey("resolution", Constants.NBT.TAG_INT)) { return ItemStack.EMPTY; } data.setBoolean("cut", true); result.setTagCompound(tag); return result; } return ItemStack.EMPTY; } @Override public boolean canFit(int width, int height) { return width * height >= 2; } @Override public ItemStack getRecipeOutput() { return ItemStack.EMPTY; } @Override public NonNullList<ItemStack> getRemainingItems(InventoryCrafting inv) { NonNullList<ItemStack> list = NonNullList.withSize(inv.getSizeInventory(), ItemStack.EMPTY); for(int i = 0; i < inv.getSizeInventory(); i++) { ItemStack stack = inv.getStackInSlot(i); if(!stack.isEmpty() && stack.getItem() == Items.SHEARS) { ItemStack copy = stack.copy(); copy.setCount(1); copy.setItemDamage(copy.getItemDamage() + 1); if(copy.getItemDamage() >= copy.getMaxDamage()) break; list.set(i, copy); break; } } return list; } @Override public boolean isDynamic() { return true; } }
0
0.924687
1
0.924687
game-dev
MEDIA
0.999728
game-dev
0.963396
1
0.963396
gameplay3d/gameplay-deps
1,321
bullet-2.82-r2704/src/BulletMultiThreaded/GpuSoftBodySolvers/OpenCL/OpenCLC10/SolvePositions.cl
MSTRINGIFY( float mydot3(float4 a, float4 b) { return a.x*b.x + a.y*b.y + a.z*b.z; } __kernel void SolvePositionsFromLinksKernel( const int startLink, const int numLinks, const float kst, const float ti, __global int2 * g_linksVertexIndices, __global float * g_linksMassLSC, __global float * g_linksRestLengthSquared, __global float * g_verticesInverseMass, __global float4 * g_vertexPositions GUID_ARG) { int linkID = get_global_id(0) + startLink; if( get_global_id(0) < numLinks ) { float massLSC = g_linksMassLSC[linkID]; float restLengthSquared = g_linksRestLengthSquared[linkID]; if( massLSC > 0.0f ) { int2 nodeIndices = g_linksVertexIndices[linkID]; int node0 = nodeIndices.x; int node1 = nodeIndices.y; float4 position0 = g_vertexPositions[node0]; float4 position1 = g_vertexPositions[node1]; float inverseMass0 = g_verticesInverseMass[node0]; float inverseMass1 = g_verticesInverseMass[node1]; float4 del = position1 - position0; float len = mydot3(del, del); float k = ((restLengthSquared - len)/(massLSC*(restLengthSquared+len)))*kst; position0 = position0 - del*(k*inverseMass0); position1 = position1 + del*(k*inverseMass1); g_vertexPositions[node0] = position0; g_vertexPositions[node1] = position1; } } } );
0
0.700053
1
0.700053
game-dev
MEDIA
0.800756
game-dev
0.898489
1
0.898489
blurite/rsprot
1,152
protocol/osrs-232/osrs-232-model/src/main/kotlin/net/rsprot/protocol/game/incoming/resumed/ResumePCountDialog.kt
package net.rsprot.protocol.game.incoming.resumed import net.rsprot.protocol.ClientProtCategory import net.rsprot.protocol.game.incoming.GameClientProtCategory import net.rsprot.protocol.message.IncomingGameMessage /** * Resume p count dialogue is sent whenever a player enters an * integer to the input box, e.g. to withdraw an item in x-quantity. * @property count the count entered. While this can only be a positive * integer for manually-entered inputs, it is **not** guaranteed to always * be positive. Clientscripts can invoke this event with negative values to * represent various potential response codes. */ public class ResumePCountDialog( public val count: Int, ) : IncomingGameMessage { override val category: ClientProtCategory get() = GameClientProtCategory.USER_EVENT override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as ResumePCountDialog return count == other.count } override fun hashCode(): Int = count override fun toString(): String = "ResumePCountDialog(count=$count)" }
0
0.657392
1
0.657392
game-dev
MEDIA
0.764218
game-dev,networking
0.689496
1
0.689496
ModalityTeam/Modality-toolkit
2,193
Modality/Tests/2_MKtlElement_tests.scd
//// Make MKtls by hand: x = MKtlElement(\x, (deviceSpec: [-100, 100], type: \joyX, ioType: \in)); x.deviceSpec; x = MKtlElement(\x, (deviceSpec: \freq, type: \joyX, ioType: \in)); x.deviceSpec; x.deviceSpec_([200, 2000, \exp]); x.deviceSpec; x.deviceSpec; // check x.value; x.value = 0.8; x.value; x.deviceValue; x.value = 0.25; x.value; x.value x.deviceValue x.dump x.name x.type x.ioType x.elementDescription; x.elementDescription_((spec: [100, -100], type: \joyY, ioType: \inout)); x.elementDescription; x.updateDescription((spec: [5, 105].asSpec, type: \joyXYZ)); x.deviceSpec; x.type x.ioType; x.deviceSpec x.deviceSpec_([5, 105] * 2); x.value_(0.75).value; x.deviceValue // cannot be nil, so it cannot get stuck in bad state x.deviceValue_(nil); x.deviceValue x.value; // AN EXAMPLE for making a derived MKtlElement, as in issue #72: // (math is not correct yet, bt works in principle) // // issue #72 - Adding custom filter elements to an existing (and instantiated) controller // m = MKtl.make(\meXYController, \meXYControl); // m.addVirtualElement(\xyPolar, {| me | // atan2(me.elements[\x], me.elements[\y]) // }); // ~post = { |el| [el.name, el.value].postln }; x.addAction(~post); x.value_(1.0.rand); x.valueAction_(0.6); y = MKtlElement(\y, (spec: [-100, 100], type: \joyY, ioType: \in)); y.addAction(~post); Slider2D(nil, Rect(0,0,200,200)).action_({ |sl2d| x.valueAction_(sl2d.x); y.valueAction_(sl2d.y); }).front; z = MKtlElement(\polar, (spec: [-pi, pi], type: \xyPolar, ioType: '?')); ~doZAction = { z.doAction }; [x, y].do {|el| el.addAction(~doZAction) }; [x, y].do { |el| el.removeAction(~post) }; // first add a function to calc value ~getXY = { |polar| polar.deviceValue_(atan2(x.deviceValue, y.deviceValue)); }; z.addAction(~getXY); z.addAction(~post); // polar values/math not ok yet, FIXME later. ~postPolar = { |polar| "polar atan2 value: % \n".postf(polar.deviceValue); }; // then one to do something with it z.removeAction(~post); z.addAction(~postPolar); // MKtlElements work in patterns x.value = 0.6; Pbind(\x, x).trace.play; x.value = 1.0.rand; Pbind(\x, Pfunc({ x.deviceValue })).trace.play; x.deviceValueAction = exprand(20, 200);
0
0.937492
1
0.937492
game-dev
MEDIA
0.332247
game-dev
0.710559
1
0.710559
mastercomfig/tf2-patches-old
14,672
src/game/shared/teamplay_gamerules.cpp
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ //=============================================================================// #include "cbase.h" #include "KeyValues.h" #include "gamerules.h" #include "teamplay_gamerules.h" #ifdef CLIENT_DLL #include "c_baseplayer.h" #include "c_team.h" #else #include "player.h" #include "game.h" #include "gamevars_shared.h" #include "team.h" #endif // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" #ifdef GAME_DLL static char team_names[MAX_TEAMS][MAX_TEAMNAME_LENGTH]; static int team_scores[MAX_TEAMS]; static int num_teams = 0; extern bool g_fGameOver; REGISTER_GAMERULES_CLASS( CTeamplayRules ); CTeamplayRules::CTeamplayRules() { m_DisableDeathMessages = false; m_DisableDeathPenalty = false; m_bSwitchTeams = false; m_bScrambleTeams = false; memset( team_names, 0, sizeof(team_names) ); memset( team_scores, 0, sizeof(team_scores) ); num_teams = 0; // Copy over the team from the server config m_szTeamList[0] = 0; RecountTeams(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTeamplayRules::Precache( void ) { // Call the Team Manager's precaches for ( int i = 0; i < GetNumberOfTeams(); i++ ) { CTeam *pTeam = GetGlobalTeam( i ); pTeam->Precache(); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTeamplayRules::Think ( void ) { BaseClass::Think(); ///// Check game rules ///// if ( g_fGameOver ) // someone else quit the game already { BaseClass::Think(); return; } float flTimeLimit = mp_timelimit.GetFloat() * 60; if ( flTimeLimit != 0 && gpGlobals->curtime >= flTimeLimit ) { ChangeLevel(); return; } float flFragLimit = fraglimit.GetFloat(); if ( flFragLimit ) { // check if any team is over the frag limit for ( int i = 0; i < num_teams; i++ ) { if ( team_scores[i] >= flFragLimit ) { ChangeLevel(); return; } } } } //========================================================= // ClientCommand // the user has typed a command which is unrecognized by everything else; // this check to see if the gamerules knows anything about the command //========================================================= bool CTeamplayRules::ClientCommand( CBaseEntity *pEdict, const CCommand &args ) { if( BaseClass::ClientCommand( pEdict, args ) ) return true; if ( FStrEq( args[0], "menuselect" ) ) { if ( args.ArgC() < 2 ) return true; //int slot = atoi( args[1] ); // select the item from the current menu return true; } return false; } const char *CTeamplayRules::SetDefaultPlayerTeam( CBasePlayer *pPlayer ) { // copy out the team name from the model int clientIndex = pPlayer->entindex(); const char *team = (!pPlayer->IsNetClient())?"default":engine->GetClientConVarValue( clientIndex, "cl_team" ); /* TODO pPlayer->SetTeamName( team ); RecountTeams(); // update the current player of the team he is joining if ( (pPlayer->TeamName())[0] == '\0' || !IsValidTeam( pPlayer->TeamName() ) || defaultteam.GetFloat() ) { const char *pTeamName = NULL; if ( defaultteam.GetFloat() ) { pTeamName = team_names[0]; } else { pTeamName = TeamWithFewestPlayers(); } pPlayer->SetTeamName( pTeamName ); } */ return team; //pPlayer->TeamName(); } //========================================================= // InitHUD //========================================================= void CTeamplayRules::InitHUD( CBasePlayer *pPlayer ) { SetDefaultPlayerTeam( pPlayer ); BaseClass::InitHUD( pPlayer ); RecountTeams(); /* TODO this has to be rewritten, maybe add a new USERINFO cvar "team" const char *team = engine->GetClientConVarValue( pPlayer->entindex(), "cl_team" ); // update the current player of the team he is joining char text[1024]; if ( !strcmp( mdls, pPlayer->TeamName() ) ) { Q_snprintf( text,sizeof(text), "You are on team \'%s\'\n", pPlayer->TeamName() ); } else { Q_snprintf( text,sizeof(text), "You were assigned to team %s\n", pPlayer->TeamName() ); } ChangePlayerTeam( pPlayer, pPlayer->TeamName(), false, false ); if ( Q_strlen( pPlayer->TeamName() ) > 0 ) { UTIL_SayText( text, pPlayer ); } RecountTeams(); */ } void CTeamplayRules::ChangePlayerTeam( CBasePlayer *pPlayer, const char *pTeamName, bool bKill, bool bGib ) { int damageFlags = DMG_GENERIC; // int clientIndex = pPlayer->entindex(); if ( !bGib ) { damageFlags |= DMG_NEVERGIB; } else { damageFlags |= DMG_ALWAYSGIB; } // copy out the team name from the model // pPlayer->SetTeamName( pTeamName ); } //----------------------------------------------------------------------------- // Purpose: Player has just left the game //----------------------------------------------------------------------------- void CTeamplayRules::ClientDisconnected( edict_t *pClient ) { // Msg( "CLIENT DISCONNECTED, REMOVING FROM TEAM.\n" ); CBasePlayer *pPlayer = (CBasePlayer *)CBaseEntity::Instance( pClient ); if ( pPlayer ) { pPlayer->SetConnected( PlayerDisconnecting ); // Remove the player from his team if ( pPlayer->GetTeam() ) { pPlayer->ChangeTeam( 0 ); } } BaseClass::ClientDisconnected( pClient ); } //========================================================= // ClientUserInfoChanged //========================================================= void CTeamplayRules::ClientSettingsChanged( CBasePlayer *pPlayer ) { /* TODO: handle skin, model & team changes char text[1024]; // skin/color/model changes int iTeam = Q_atoi( engine->GetClientConVarValue( pPlayer->entindex(), "cl_team" ) ); int iClass = Q_atoi( engine->GetClientConVarValue( pPlayer->entindex(), "cl_class" ) ); if ( defaultteam.GetBool() ) { // int clientIndex = pPlayer->entindex(); // engine->SetClientKeyValue( clientIndex, "model", pPlayer->TeamName() ); // engine->SetClientKeyValue( clientIndex, "team", pPlayer->TeamName() ); UTIL_SayText( "Not allowed to change teams in this game!\n", pPlayer ); return; } if ( defaultteam.GetFloat() || !IsValidTeam( mdls ) ) { // int clientIndex = pPlayer->entindex(); // engine->SetClientKeyValue( clientIndex, "model", pPlayer->TeamName() ); Q_snprintf( text,sizeof(text), "Can't change team to \'%s\'\n", mdls ); UTIL_SayText( text, pPlayer ); Q_snprintf( text,sizeof(text), "Server limits teams to \'%s\'\n", m_szTeamList ); UTIL_SayText( text, pPlayer ); return; } ChangePlayerTeam( pPlayer, mdls, true, true ); // recound stuff RecountTeams(); */ const char *pszName = engine->GetClientConVarValue( pPlayer->entindex(), "name" ); const char *pszOldName = pPlayer->GetPlayerName(); // msg everyone if someone changes their name, and it isn't the first time (changing no name to current name) // Note, not using FStrEq so that this is case sensitive if ( pszOldName[0] != 0 && Q_strcmp( pszOldName, pszName ) ) { IGameEvent * event = gameeventmanager->CreateEvent( "player_changename" ); if ( event ) { event->SetInt( "userid", pPlayer->GetUserID() ); event->SetString( "oldname", pszOldName ); event->SetString( "newname", pszName ); gameeventmanager->FireEvent( event ); } pPlayer->SetPlayerName( pszName ); } // NVNT see if this user is still or has began using a haptic device const char *pszHH = engine->GetClientConVarValue( pPlayer->entindex(), "hap_HasDevice" ); if(pszHH) { int iHH = atoi(pszHH); pPlayer->SetHaptics(iHH!=0); } } //========================================================= // Deathnotice. //========================================================= void CTeamplayRules::DeathNotice( CBasePlayer *pVictim, const CTakeDamageInfo &info ) { if ( m_DisableDeathMessages ) return; CBaseEntity *pKiller = info.GetAttacker(); if ( pVictim && pKiller && pKiller->IsPlayer() ) { CBasePlayer *pk = (CBasePlayer*)pKiller; if ( pk ) { if ( (pk != pVictim) && (PlayerRelationship( pVictim, pk ) == GR_TEAMMATE) ) { IGameEvent * event = gameeventmanager->CreateEvent( "player_death" ); if ( event ) { event->SetInt("killer", pk->GetUserID() ); event->SetInt("victim", pVictim->GetUserID() ); event->SetInt("priority", 7 ); // HLTV event priority, not transmitted gameeventmanager->FireEvent( event ); } return; } } } BaseClass::DeathNotice( pVictim, info ); } //========================================================= //========================================================= void CTeamplayRules::PlayerKilled( CBasePlayer *pVictim, const CTakeDamageInfo &info ) { if ( !m_DisableDeathPenalty ) { BaseClass::PlayerKilled( pVictim, info ); RecountTeams(); } } //========================================================= // IsTeamplay //========================================================= bool CTeamplayRules::IsTeamplay( void ) { return true; } bool CTeamplayRules::FPlayerCanTakeDamage( CBasePlayer *pPlayer, CBaseEntity *pAttacker, const CTakeDamageInfo &info ) { if ( pAttacker && PlayerRelationship( pPlayer, pAttacker ) == GR_TEAMMATE && !info.IsForceFriendlyFire() ) { // my teammate hit me. if ( (friendlyfire.GetInt() == 0) && (pAttacker != pPlayer) ) { // friendly fire is off, and this hit came from someone other than myself, then don't get hurt return false; } } return BaseClass::FPlayerCanTakeDamage( pPlayer, pAttacker, info ); } //========================================================= //========================================================= int CTeamplayRules::PlayerRelationship( CBaseEntity *pPlayer, CBaseEntity *pTarget ) { // half life multiplay has a simple concept of Player Relationships. // you are either on another player's team, or you are not. if ( !pPlayer || !pTarget || !pTarget->IsPlayer() ) return GR_NOTTEAMMATE; if ( (*GetTeamID(pPlayer) != '\0') && (*GetTeamID(pTarget) != '\0') && !stricmp( GetTeamID(pPlayer), GetTeamID(pTarget) ) ) { return GR_TEAMMATE; } return GR_NOTTEAMMATE; } //----------------------------------------------------------------------------- // Purpose: // Input : *pListener - // *pSpeaker - // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CTeamplayRules::PlayerCanHearChat( CBasePlayer *pListener, CBasePlayer *pSpeaker ) { return ( PlayerRelationship( pListener, pSpeaker ) == GR_TEAMMATE ); } //========================================================= //========================================================= bool CTeamplayRules::ShouldAutoAim( CBasePlayer *pPlayer, edict_t *target ) { // always autoaim, unless target is a teammate CBaseEntity *pTgt = CBaseEntity::Instance( target ); if ( pTgt && pTgt->IsPlayer() ) { if ( PlayerRelationship( pPlayer, pTgt ) == GR_TEAMMATE ) return false; // don't autoaim at teammates } return BaseClass::ShouldAutoAim( pPlayer, target ); } //========================================================= //========================================================= int CTeamplayRules::IPointsForKill( CBasePlayer *pAttacker, CBasePlayer *pKilled ) { if ( !pKilled ) return 0; if ( !pAttacker ) return 1; if ( pAttacker != pKilled && PlayerRelationship( pAttacker, pKilled ) == GR_TEAMMATE ) return -1; return 1; } //========================================================= //========================================================= const char *CTeamplayRules::GetTeamID( CBaseEntity *pEntity ) { if ( pEntity == NULL || pEntity->edict() == NULL ) return ""; // return their team name return pEntity->TeamID(); } int CTeamplayRules::GetTeamIndex( const char *pTeamName ) { if ( pTeamName && *pTeamName != 0 ) { // try to find existing team for ( int tm = 0; tm < num_teams; tm++ ) { if ( !stricmp( team_names[tm], pTeamName ) ) return tm; } } return -1; // No match } const char *CTeamplayRules::GetIndexedTeamName( int teamIndex ) { if ( teamIndex < 0 || teamIndex >= num_teams ) return ""; return team_names[ teamIndex ]; } bool CTeamplayRules::IsValidTeam( const char *pTeamName ) { if ( !m_teamLimit ) // Any team is valid if the teamlist isn't set return true; return ( GetTeamIndex( pTeamName ) != -1 ) ? true : false; } const char *CTeamplayRules::TeamWithFewestPlayers( void ) { int i; int minPlayers = MAX_TEAMS; int teamCount[ MAX_TEAMS ]; char *pTeamName = NULL; memset( teamCount, 0, MAX_TEAMS * sizeof(int) ); // loop through all clients, count number of players on each team for ( i = 1; i <= gpGlobals->maxClients; i++ ) { CBaseEntity *plr = UTIL_PlayerByIndex( i ); if ( plr ) { int team = GetTeamIndex( plr->TeamID() ); if ( team >= 0 ) teamCount[team] ++; } } // Find team with least players for ( i = 0; i < num_teams; i++ ) { if ( teamCount[i] < minPlayers ) { minPlayers = teamCount[i]; pTeamName = team_names[i]; } } return pTeamName; } //========================================================= //========================================================= void CTeamplayRules::RecountTeams( void ) { char *pName; char teamlist[TEAMPLAY_TEAMLISTLENGTH]; // loop through all teams, recounting everything num_teams = 0; // Copy all of the teams from the teamlist // make a copy because strtok is destructive Q_strncpy( teamlist, m_szTeamList, sizeof(teamlist) ); pName = teamlist; pName = strtok( pName, ";" ); while ( pName != NULL && *pName ) { if ( GetTeamIndex( pName ) < 0 ) { Q_strncpy( team_names[num_teams], pName, sizeof(team_names[num_teams])); num_teams++; } pName = strtok( NULL, ";" ); } if ( num_teams < 2 ) { num_teams = 0; m_teamLimit = false; } // Sanity check memset( team_scores, 0, sizeof(team_scores) ); // loop through all clients for ( int i = 1; i <= gpGlobals->maxClients; i++ ) { CBasePlayer *plr = UTIL_PlayerByIndex( i ); if ( plr ) { const char *pTeamName = plr->TeamID(); // try add to existing team int tm = GetTeamIndex( pTeamName ); if ( tm < 0 ) // no team match found { if ( !m_teamLimit ) { // add to new team tm = num_teams; num_teams++; team_scores[tm] = 0; Q_strncpy( team_names[tm], pTeamName, MAX_TEAMNAME_LENGTH ); } } if ( tm >= 0 ) { team_scores[tm] += plr->FragCount(); } } } } #endif // GAME_DLL
0
0.920453
1
0.920453
game-dev
MEDIA
0.93195
game-dev,networking
0.988055
1
0.988055
ax-grymyr/l2dn-server
1,684
L2Dn/L2Dn.GameServer.Scripts/Handlers/SkillConditionHandlers/RemainHpPerSkillCondition.cs
using L2Dn.GameServer.Enums; using L2Dn.GameServer.Model; using L2Dn.GameServer.Model.Actor; using L2Dn.GameServer.Model.Skills; namespace L2Dn.GameServer.Scripts.Handlers.SkillConditionHandlers; /** * @author UnAfraid */ public class RemainHpPerSkillCondition: ISkillCondition { private readonly int _amount; private readonly SkillConditionPercentType _percentType; private readonly SkillConditionAffectType _affectType; public RemainHpPerSkillCondition(StatSet @params) { _amount = @params.getInt("amount"); _percentType = @params.getEnum<SkillConditionPercentType>("percentType"); _affectType = @params.getEnum<SkillConditionAffectType>("affectType"); } public bool canUse(Creature caster, Skill skill, WorldObject? target) { switch (_affectType) { case SkillConditionAffectType.CASTER: { return _percentType.test(caster.getCurrentHpPercent(), _amount); } case SkillConditionAffectType.TARGET: { if (target != null && target.isCreature()) { return _percentType.test(((Creature)target).getCurrentHpPercent(), _amount); } break; } case SkillConditionAffectType.SUMMON: { Summon? summon = caster.getActingPlayer()?.getAnyServitor(); if (caster.hasServitors() && summon != null) { return _percentType.test(summon.getCurrentHpPercent(), _amount); } break; } } return false; } }
0
0.855317
1
0.855317
game-dev
MEDIA
0.702934
game-dev,web-backend
0.828555
1
0.828555
glKarin/com.n0n3m4.diii4a
20,539
Q3E/src/main/jni/serioussam/SamTSE/Sources/EntitiesMP/CannonRotating.es
/* Copyright (c) 2002-2012 Croteam Ltd. This program is free software; you can redistribute it and/or modify it under the terms of version 2 of the GNU General Public License as published by the Free Software Foundation This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ 345 %{ #include "EntitiesMP/StdH/StdH.h" #include "ModelsMP/Enemies/CannonRotating/Turret.h" #include "ModelsMP/Enemies/CannonRotating/RotatingMechanism.h" %} uses "EntitiesMP/ModelHolder2"; uses "EntitiesMP/Projectile"; uses "EntitiesMP/SoundHolder"; uses "EntitiesMP/BloodSpray"; uses "EntitiesMP/CannonBall"; %{ #define CANNONR_SIZE 2.0f // info structure static EntityInfo eiCannonRotating = { EIBT_WOOD, 10000.0f, 0.0f, 1.5f*CANNONR_SIZE, 0.0f, // source (eyes) 0.0f, 0.5f*CANNONR_SIZE, 0.0f, // target (body) }; #define FIRING_POSITION_MUZZLE FLOAT3D(0.0f, 0.0f, -1.0f) #define MUZZLE_ROTATION_SPEED 45.0f //deg/sec %} class CCannonRotating: CEnemyBase { name "CannonRotating"; thumbnail "Thumbnails\\CannonRotating.tbn"; properties: 1 FLOAT m_fHealth "Cannon Health" = 100.0f, 2 RANGE m_fFiringRangeClose "Cannon Firing Close Range" = 50.0f, 3 RANGE m_fFiringRangeFar "Cannon Firing Far Range" = 150.0f, 4 FLOAT m_fWaitAfterFire "Cannon Wait After Fire" = 3.0f, 5 FLOAT m_fSize = CANNONR_SIZE, 6 FLOAT m_fMaxPitch "Cannon Max Pitch" = 20.0f, 7 FLOAT m_fViewAngle "Cannon View Angle" = 2.5f, 8 FLOAT m_fScanAngle "Cannon Scanning Angle" = 60.0f, 9 FLOAT m_fRotationSpeed "Cannon Rotation Speed" = 20.0f, 10 BOOL m_bActive "Cannon Active" = TRUE, 20 FLOAT3D m_fRotSpeedMuzzle = ANGLE3D(0.0f, 0.0f, 0.0f), 21 FLOAT3D m_fRotSpeedRotator = ANGLE3D(0.0f, 0.0f, 0.0f), 25 FLOAT m_fDistanceToPlayer = 0.0f, 26 FLOAT m_fDesiredMuzzlePitch = 0.0f, 27 FLOAT m_iMuzzleDir = 1.0f, 28 FLOAT3D m_vFiringPos = FLOAT3D(0.0f, 0.0f, 0.0f), 29 FLOAT3D m_vTarget = FLOAT3D(0.0f, 0.0f, 0.0f), 30 FLOAT m_tmLastFireTime = -1000.0f, 40 FLOAT3D m_aBeginMuzzleRotation = ANGLE3D(0.0f, 0.0f, 0.0f), 41 FLOAT3D m_aEndMuzzleRotation = ANGLE3D(0.0f, 0.0f, 0.0f), 42 FLOAT3D m_aBeginRotatorRotation = ANGLE3D(0.0f, 0.0f, 0.0f), 43 FLOAT3D m_aEndRotatorRotation = ANGLE3D(0.0f, 0.0f, 0.0f), components: 1 class CLASS_BASE "Classes\\EnemyBase.ecl", 2 class CLASS_BASIC_EFFECT "Classes\\BasicEffect.ecl", 3 class CLASS_PROJECTILE "Classes\\Projectile.ecl", 4 class CLASS_CANNONBALL "Classes\\CannonBall.ecl", // ************** CANNON MODEL ************** 10 model MODEL_TURRET "ModelsMP\\Enemies\\CannonRotating\\Turret.mdl", 11 model MODEL_ROTATOR "ModelsMP\\Enemies\\CannonRotating\\RotatingMechanism.mdl", 12 model MODEL_CANNON "ModelsMP\\Enemies\\CannonStatic\\Cannon.mdl", 20 texture TEXTURE_TURRET "ModelsMP\\Enemies\\CannonRotating\\Turret.tex", 21 texture TEXTURE_ROTATOR "ModelsMP\\Enemies\\CannonRotating\\RotatingMechanism.tex", 22 texture TEXTURE_CANNON "Models\\Weapons\\Cannon\\Body.tex", // ************** CANNON PARTS ************** 30 model MODEL_DEBRIS_MUZZLE "ModelsMP\\Enemies\\CannonRotating\\Debris\\Cannon.mdl", 31 model MODEL_DEBRIS_ROTATOR "ModelsMP\\Enemies\\CannonRotating\\Debris\\RotatingMechanism.mdl", 32 model MODEL_DEBRIS_BASE "ModelsMP\\Enemies\\CannonRotating\\Debris\\Turret.mdl", 35 model MODEL_BALL "Models\\Weapons\\Cannon\\Projectile\\CannonBall.mdl", 36 texture TEXTURE_BALL "Models\\Weapons\\Cannon\\Projectile\\IronBall.tex", // ************** SOUNDS ************** 50 sound SOUND_FIRE "ModelsMP\\Enemies\\CannonRotating\\Sounds\\Fire.wav", functions: virtual CTString GetPlayerKillDescription(const CTString &strPlayerName, const EDeath &eDeath) { CTString str; str.PrintF(TRANSV("A Cannon killed %s"), (const char *) strPlayerName); return str; } /* Entity info */ void *GetEntityInfo(void) { return &eiCannonRotating; }; virtual const CTFileName &GetComputerMessageName(void) const { static DECLARE_CTFILENAME(fnmCannon, "DataMP\\Messages\\Enemies\\CannonRotating.txt"); return fnmCannon; }; void Precache(void) { CEnemyBase::Precache(); PrecacheModel(MODEL_DEBRIS_MUZZLE); PrecacheModel(MODEL_DEBRIS_ROTATOR); PrecacheModel(MODEL_DEBRIS_BASE); PrecacheModel(MODEL_BALL); PrecacheTexture(TEXTURE_BALL); PrecacheSound(SOUND_FIRE); PrecacheClass(CLASS_CANNONBALL); }; void ReceiveDamage(CEntity *penInflictor, enum DamageType dmtType, FLOAT fDamageAmmount, const FLOAT3D &vHitPoint, const FLOAT3D &vDirection) { // take less damage from heavy bullets (e.g. sniper) if(dmtType==DMT_BULLET && fDamageAmmount>100.0f) { fDamageAmmount*=0.5f; } CEnemyBase::ReceiveDamage(penInflictor, dmtType, fDamageAmmount, vHitPoint, vDirection); }; // damage anim INDEX AnimForDamage(FLOAT fDamage) { return 0; }; // death INDEX AnimForDeath(void) { return 0; }; // cast a ray to entity checking only for brushes BOOL IsVisible(CEntity *penEntity) { ASSERT(penEntity!=NULL); // get ray source and target FLOAT3D vSource, vTarget; GetPositionCastRay(this, penEntity, vSource, vTarget); // cast the ray CCastRay crRay(this, vSource, vTarget); crRay.cr_ttHitModels = CCastRay::TT_NONE; // check for brushes only crRay.cr_bHitTranslucentPortals = FALSE; en_pwoWorld->CastRay(crRay); // if hit nothing (no brush) the entity can be seen return (crRay.cr_penHit==NULL); }; BOOL IsInTheLineOfFire(CEntity *penEntity, FLOAT fAngle) { ASSERT(penEntity!=NULL); FLOAT fCosAngle; FLOAT3D vHeading; FLOAT3D vToPlayer; FLOAT3D vSide = FLOAT3D(1.0f, 0.0f, 0.0f)*GetRotationMatrix(); FLOAT3D vFront = FLOAT3D(0.0f, 0.0f, -1.0f)*GetRotationMatrix(); FLOATmatrix3D m; MakeRotationMatrixFast(m, m_aBeginRotatorRotation); vSide = vSide*m; vFront = vFront*m; vToPlayer = penEntity->GetPlacement().pl_PositionVector - GetPlacement().pl_PositionVector; vToPlayer.Normalize(); fCosAngle = vToPlayer%vSide; // if on the firing plane if (Abs(fCosAngle)<CosFast(90.0f-fAngle)) { // if in front if ((vToPlayer%vFront)>0.0f) { return TRUE; } } return FALSE; } CPlayer *AcquireTarget() { // find actual number of players INDEX ctMaxPlayers = GetMaxPlayers(); CEntity *penPlayer; for(INDEX i=0; i<ctMaxPlayers; i++) { penPlayer=GetPlayerEntity(i); if (penPlayer!=NULL && DistanceTo(this, penPlayer)<m_fFiringRangeFar) { // if this player is more or less directly in front of the shooter if (IsInTheLineOfFire(penPlayer, m_fViewAngle)) { // see if something blocks the path to the player if (IsVisible(penPlayer)) { return (CPlayer *)penPlayer; } } } } return NULL; }; // spawn body parts void CannonBlowUp(void) { FLOAT3D vNormalizedDamage = m_vDamage-m_vDamage*(m_fBlowUpAmount/m_vDamage.Length()); vNormalizedDamage /= Sqrt(vNormalizedDamage.Length()); vNormalizedDamage *= 0.75f; vNormalizedDamage += FLOAT3D(0.0f, 15.0f+FRnd()*10.0f, 0.0f); FLOAT3D vBodySpeed = en_vCurrentTranslationAbsolute-en_vGravityDir*(en_vGravityDir%en_vCurrentTranslationAbsolute); // spawn debris Debris_Begin(EIBT_WOOD, DPT_NONE, BET_NONE, 1.0f, vNormalizedDamage, vBodySpeed, 5.0f, 2.0f); Debris_Spawn(this, this, MODEL_DEBRIS_MUZZLE, TEXTURE_CANNON, 0, 0, 0, 0, m_fSize, FLOAT3D(FRnd()*0.6f+0.2f, FRnd()*0.6f+0.2f, FRnd()*0.6f+0.2f)); Debris_Spawn(this, this, MODEL_DEBRIS_ROTATOR, TEXTURE_ROTATOR, 0, 0, 0, 0, m_fSize, FLOAT3D(FRnd()*0.6f+0.2f, FRnd()*0.6f+0.2f, FRnd()*0.6f+0.2f)); Debris_Spawn(this, this, MODEL_DEBRIS_ROTATOR, TEXTURE_ROTATOR, 0, 0, 0, 0, m_fSize, FLOAT3D(FRnd()*0.6f+0.2f, FRnd()*0.6f+0.2f, FRnd()*0.6f+0.2f)); Debris_Spawn(this, this, MODEL_DEBRIS_BASE, TEXTURE_TURRET, 0, 0, 0, 0, m_fSize, FLOAT3D(FRnd()*0.6f+0.2f, FRnd()*0.6f+0.2f, FRnd()*0.6f+0.2f)); Debris_Spawn(this, this, MODEL_BALL, TEXTURE_BALL, 0, 0, 0, 0, m_fSize/2.0f, FLOAT3D(FRnd()*0.6f+0.2f, FRnd()*0.6f+0.2f, FRnd()*0.6f+0.2f)); Debris_Spawn(this, this, MODEL_BALL, TEXTURE_BALL, 0, 0, 0, 0, m_fSize/2.0f, FLOAT3D(FRnd()*0.6f+0.2f, FRnd()*0.6f+0.2f, FRnd()*0.6f+0.2f)); // spawn explosion CPlacement3D plExplosion = GetPlacement(); CEntityPointer penExplosion = CreateEntity(plExplosion, CLASS_BASIC_EFFECT); ESpawnEffect eSpawnEffect; eSpawnEffect.colMuliplier = C_WHITE|CT_OPAQUE; eSpawnEffect.betType = BET_CANNON; FLOAT fSize = m_fBlowUpSize*1.0f; eSpawnEffect.vStretch = FLOAT3D(fSize,fSize,fSize); penExplosion->Initialize(eSpawnEffect); // spawn shockwave plExplosion = GetPlacement(); penExplosion = CreateEntity(plExplosion, CLASS_BASIC_EFFECT); eSpawnEffect.colMuliplier = C_WHITE|CT_OPAQUE; eSpawnEffect.betType = BET_CANNONSHOCKWAVE; fSize = m_fBlowUpSize*1.0f; eSpawnEffect.vStretch = FLOAT3D(fSize,fSize,fSize); penExplosion->Initialize(eSpawnEffect); // hide yourself (must do this after spawning debris) SwitchToEditorModel(); SetPhysicsFlags(EPF_MODEL_IMMATERIAL); SetCollisionFlags(ECF_IMMATERIAL); } void PreMoving() { // manually update rotation of the attachments UpdateAttachmentRotations(); CEnemyBase::PreMoving(); } void PostMoving() { CEnemyBase::PostMoving(); // make sure this entity stays in the moving list SetFlags(GetFlags()&~ENF_INRENDERING); } // rotate to between-tick position BOOL AdjustShadingParameters(FLOAT3D &vLightDirection, COLOR &colLight, COLOR &colAmbient) { // rotator CAttachmentModelObject &amo0 = *GetModelObject()->GetAttachmentModel(TURRET_ATTACHMENT_ROTATORHEADING); amo0.amo_plRelative.pl_OrientationAngle = Lerp(m_aBeginRotatorRotation, m_aEndRotatorRotation, _pTimer->GetLerpFactor()); // muzzle CAttachmentModelObject &amo1 = *amo0.amo_moModelObject.GetAttachmentModel(ROTATINGMECHANISM_ATTACHMENT_CANNON); amo1.amo_plRelative.pl_OrientationAngle = Lerp(m_aBeginMuzzleRotation, m_aEndMuzzleRotation, _pTimer->GetLerpFactor()); // finish by calling the default 'AdjustShadingParameters' return CEnemyBase::AdjustShadingParameters(vLightDirection, colLight, colAmbient); }; void UpdateAttachmentRotations( void ) { // rotator m_aBeginRotatorRotation = m_aEndRotatorRotation; m_aEndRotatorRotation += m_fRotSpeedRotator*_pTimer->TickQuantum; // muzzle m_aBeginMuzzleRotation = m_aEndMuzzleRotation; m_aEndMuzzleRotation += m_fRotSpeedMuzzle*_pTimer->TickQuantum; } void UpdateFiringPos() { FLOATmatrix3D m; // initial position m_vFiringPos = FIRING_POSITION_MUZZLE*m_fSize; // heading rotation MakeRotationMatrixFast(m, m_aBeginRotatorRotation); m_vFiringPos = m_vFiringPos*m; // pitch rotation MakeRotationMatrixFast(m, m_aBeginMuzzleRotation); m_vFiringPos = m_vFiringPos*m; // add translations CAttachmentModelObject &amo0 = *GetModelObject()->GetAttachmentModel(TURRET_ATTACHMENT_ROTATORHEADING); CAttachmentModelObject &amo1 = *amo0.amo_moModelObject.GetAttachmentModel(ROTATINGMECHANISM_ATTACHMENT_CANNON); m_vFiringPos += amo0.amo_plRelative.pl_PositionVector + amo1.amo_plRelative.pl_PositionVector; } procedures: MainLoop() { wait() { on (EBegin) : { call Scan(); resume; } on (EDeactivate) : { jump Inactive(); } on (EDeath eDeath) : { // die jump Die(eDeath); } }; return; }; Scan() { // this is a kind of 'sleep' mode - check to see if any player entered // the attack radius every once in a while, and change rotation when needed while(TRUE) { autowait(0.20f); // adjust rotations BOOL bPause = FALSE; if ( m_aBeginRotatorRotation(1)>(m_fScanAngle/2.0f) ) { m_fRotSpeedRotator = FLOAT3D(-m_fRotationSpeed, 0.0f, 0.0f); if (m_iMuzzleDir!=-1.0f) { m_iMuzzleDir= -1.0f; bPause = TRUE; } } else if ( m_aBeginRotatorRotation(1)<(-m_fScanAngle/2.0f) ) { m_fRotSpeedRotator = FLOAT3D(m_fRotationSpeed, 0.0f, 0.0f); if (m_iMuzzleDir!=1.0f) { m_iMuzzleDir= 1.0f; bPause = TRUE; } } else if (TRUE) { m_fRotSpeedRotator = FLOAT3D(m_iMuzzleDir*m_fRotationSpeed, 0.0f, 0.0f); } if (bPause) { m_fRotSpeedRotator = FLOAT3D(0.0f, 0.0f, 0.0f); autowait(0.5f); } // check for players CPlayer *pTarget = AcquireTarget(); if (pTarget) { if ((pTarget->GetFlags()&ENF_ALIVE) && !(pTarget->GetFlags()&ENF_DELETED)) { // stop rotations m_fRotSpeedRotator = FLOAT3D(0.0f, 0.0f, 0.0f); m_penEnemy = pTarget; m_fDistanceToPlayer = DistanceTo(this, pTarget); // if it's time to fire, do so if (m_tmLastFireTime+m_fWaitAfterFire<_pTimer->CurrentTick()) { autocall FireCannon() EReturn; } } } } } Die(EDeath eDeath) { // not alive anymore SetFlags(GetFlags()&~ENF_ALIVE); // find the one who killed, or other best suitable player CEntityPointer penKiller = eDeath.eLastDamage.penInflictor; if (penKiller==NULL || !IsOfClass(penKiller, "Player")) { penKiller = m_penEnemy; } if (penKiller==NULL || !IsOfClass(penKiller, "Player")) { penKiller = FixupCausedToPlayer(this, penKiller, /*bWarning=*/FALSE); } // if killed by someone if (penKiller!=NULL) { // give him score EReceiveScore eScore; eScore.iPoints = (INDEX) m_iScore; penKiller->SendEvent(eScore); if( CountAsKill()) { penKiller->SendEvent(EKilledEnemy()); } // send computer message EComputerMessage eMsg; eMsg.fnmMessage = GetComputerMessageName(); if (eMsg.fnmMessage!="") { penKiller->SendEvent(eMsg); } } // send event to death target SendToTarget(m_penDeathTarget, m_eetDeathType, penKiller); // send event to spawner if any // NOTE: trigger's penCaused has been changed from penKiller to THIS; if (m_penSpawnerTarget) { SendToTarget(m_penSpawnerTarget, EET_TRIGGER, this); } // spawn debris CannonBlowUp(); Destroy(); return; }; RotateMuzzle() { FLOAT fDeltaP = m_fDesiredMuzzlePitch - m_aBeginMuzzleRotation(2); // if close enough to desired rotation, don't rotate if (Abs(fDeltaP)<5.0f) { return EReturn(); } m_fRotSpeedMuzzle = ANGLE3D(0.0f, MUZZLE_ROTATION_SPEED*Sgn(fDeltaP), 0.0f); //CPrintF("wait %f; beg:%f, end:%f at %f\n", Abs(fDeltaP/MUZZLE_ROTATION_SPEED), m_aBeginMuzzleRotation, m_aEndMuzzleRotation, _pTimer->CurrentTick()); autowait(Abs(fDeltaP/MUZZLE_ROTATION_SPEED)); m_fRotSpeedMuzzle = ANGLE3D(0.0f, 0.0f, 0.0f); return EReturn(); }; FireCannon() { UpdateFiringPos(); FLOAT3D vToTarget = m_penEnemy->GetPlacement().pl_PositionVector - GetPlacement().pl_PositionVector + m_vFiringPos; vToTarget.Normalize(); // get vector pointing in heading direction of the muzzle FLOAT3D vCannonFront = FLOAT3D(0.0f, 0.0f, -1.0f)*GetRotationMatrix(); FLOATmatrix3D m; MakeRotationMatrixFast(m, m_aBeginRotatorRotation); vCannonFront = vCannonFront*m; ANGLE aToPlayer = ACos(vToTarget%vCannonFront); FLOAT fPitch = aToPlayer + 5.0f; FLOAT3D vCannonUp = FLOAT3D(0.0, 1.0f, 0.0f)*GetRotationMatrix(); // if too far, do not fire if (m_fDistanceToPlayer>m_fFiringRangeFar) { return EReturn(); // if player under cannon, minimize pitch } else if (vToTarget%vCannonUp<0.0f) { fPitch = 5.0f; // if in far range } else if (m_fDistanceToPlayer>m_fFiringRangeClose) { if (aToPlayer<m_fMaxPitch) { fPitch = aToPlayer + m_fMaxPitch*(m_fDistanceToPlayer-m_fFiringRangeClose)/(m_fFiringRangeFar-m_fFiringRangeClose); } else if (TRUE) { fPitch = aToPlayer + 10.0f + m_fMaxPitch*(m_fDistanceToPlayer-m_fFiringRangeClose)/(m_fFiringRangeFar-m_fFiringRangeClose); } // just to make sure fPitch = Clamp(fPitch, 1.0f, 60.0f); } m_vTarget = m_penEnemy->GetPlacement().pl_PositionVector; m_fDesiredMuzzlePitch = fPitch; autocall RotateMuzzle() EReturn; FLOAT3D vShooting = GetPlacement().pl_PositionVector + m_vFiringPos; FLOAT3D vSpeedDest = FLOAT3D(0.0f, 0.0f, 0.0f); FLOAT fLaunchSpeed; FLOAT fRelativeHdg; // calculate parameters for predicted angular launch curve EntityInfo *peiTarget = (EntityInfo*) (m_penEnemy->GetEntityInfo()); CalculateAngularLaunchParams( vShooting, peiTarget->vTargetCenter[1]-6.0f/3.0f, m_vTarget, vSpeedDest, m_fDesiredMuzzlePitch , fLaunchSpeed, fRelativeHdg); // target enemy body FLOAT3D vShootTarget; GetEntityInfoPosition(m_penEnemy, peiTarget->vTargetCenter, vShootTarget); // launch CPlacement3D pl; PrepareFreeFlyingProjectile(pl, vShootTarget, m_vFiringPos, ANGLE3D( fRelativeHdg, m_fDesiredMuzzlePitch, 0)); CEntityPointer penBall = CreateEntity(pl, CLASS_CANNONBALL); ELaunchCannonBall eLaunch; eLaunch.penLauncher = this; eLaunch.fLaunchPower = fLaunchSpeed; eLaunch.cbtType = CBT_IRON; eLaunch.fSize = 1.0f; penBall->Initialize(eLaunch); m_tmLastFireTime = _pTimer->CurrentTick(); return EReturn(); }; Inactive() { m_fRotSpeedMuzzle = ANGLE3D(0.0f, 0.0f, 0.0f); m_fRotSpeedRotator = ANGLE3D(0.0f, 0.0f, 0.0f); wait() { on (EBegin) : { resume; } on (EActivate) : { jump MainLoop(); } on (EDeath eDeath) : { jump Die(eDeath); } otherwise (): { resume; } } } Main(EVoid) { // declare yourself as a model InitAsModel(); SetPhysicsFlags(EPF_MODEL_WALKING|EPF_HASLUNGS); SetCollisionFlags(ECF_MODEL); SetFlags(GetFlags()|ENF_ALIVE); en_fDensity = 2000.0f; // set your appearance SetModel(MODEL_TURRET); SetModelMainTexture(TEXTURE_TURRET); AddAttachment(TURRET_ATTACHMENT_ROTATORHEADING, MODEL_ROTATOR, TEXTURE_ROTATOR); CModelObject &amo0 = GetModelObject()->GetAttachmentModel(TURRET_ATTACHMENT_ROTATORHEADING)->amo_moModelObject; AddAttachmentToModel(this, amo0, ROTATINGMECHANISM_ATTACHMENT_CANNON, MODEL_CANNON, TEXTURE_CANNON, 0, 0, 0); // setup moving speed m_fWalkSpeed = 0.0f; m_aWalkRotateSpeed = 0.0f; m_fAttackRunSpeed = 0.0f; m_aAttackRotateSpeed = 0.0f; m_fCloseRunSpeed = 0.0f; m_aCloseRotateSpeed = 0.0f; // setup attack distances m_fStopDistance = 100.0f; //m_fBlowUpAmount = 65.0f; m_fBlowUpAmount = 100.0f; m_fBodyParts = 4; m_fDamageWounded = 0.0f; m_iScore = 1000; m_sptType = SPT_WOOD; // properties that modify EnemyBase properties if (m_fHealth<=0.0f) { m_fHealth=1.0f; } m_fCloseFireTime = m_fAttackFireTime = m_fWaitAfterFire; SetHealth(m_fHealth); m_fMaxHealth = m_fHealth; if (m_fFiringRangeFar<m_fFiringRangeClose) { m_fFiringRangeFar=m_fFiringRangeClose+1.0f; } // set stretch factors for height and width GetModelObject()->StretchModel(FLOAT3D(m_fSize, m_fSize, m_fSize)); ModelChangeNotify(); StandingAnim(); // don't continue behavior in base class! - this enemy is derived // from CEnemyBase only because of its properties autowait(0.05f); SetDesiredTranslation(FLOAT3D(0.0f, 0.0f, 0.0f)); UpdateFiringPos(); if (!m_bActive) { jump Inactive(); } jump MainLoop(); }; };
0
0.898259
1
0.898259
game-dev
MEDIA
0.992237
game-dev
0.789124
1
0.789124
tezheng/UH5
2,522
src/UnityEngine/Utils/UIPanel.cs
 using System; namespace Logic { public class Convert { public static int ToInt32(object val) { if (val is sbyte || val is byte || val is short || val is ushort || val is int || val is uint || val is long || val is ulong || val is float || val is double || val is decimal) return (int) val; if (!(val is string)) throw new System.Exception("Wrong Convert.ToInt32"); return (int) long.Parse((string)val); } public static long ToInt64(object val) { if (val is sbyte || val is byte || val is short || val is ushort || val is int || val is uint || val is long || val is ulong || val is float || val is double || val is decimal) return (long) val; if (!(val is string)) throw new System.Exception("Wrong Convert.ToInt32"); return long.Parse((string)val); } public static float ToSingle(object val) { if (val is sbyte || val is byte || val is short || val is ushort || val is int || val is uint || val is long || val is ulong || val is float || val is double || val is decimal) return (float) val; if (!(val is string)) throw new System.Exception("Wrong Convert.ToSingle"); return float.Parse((string)val); } public static float ToDouble(object val) { if (val is sbyte || val is byte || val is short || val is ushort || val is int || val is uint || val is long || val is ulong || val is float || val is double || val is decimal) return (float) val; if (!(val is string)) throw new System.Exception("Wrong Convert.ToDouble"); return float.Parse((string)val); } // public static int ToInt32(string val, int basev) // { // return 0; // } // public static char ToChar(int a) // { // return 'a'; // } // public static string ToString(int codepoint, int size) // { // return ""; // } // public static string ToBase64String() // { // return ""; // } // public static object FromBase64String(string str) // { // return null; // } } }
0
0.610902
1
0.610902
game-dev
MEDIA
0.407501
game-dev
0.556333
1
0.556333
EpicSkookumScript/SkookumScript-Plugin
1,984
Source/SkookumScript/Private/SkookumScript/SkSymbolDefs.cpp
// Copyright 1998-2019 Epic Games, Inc. All Rights Reserved. //======================================================================================= // SkookumScript C++ library. // // A number of handy symbol definitions //======================================================================================= //======================================================================================= // Includes //======================================================================================= #include <SkookumScript/Sk.hpp> // Always include Sk.hpp first (as some builds require a designated precompiled header) #include <SkookumScript/SkSymbolDefs.hpp> //======================================================================================= // Global Variables //======================================================================================= namespace SkSymbolDefs { //--------------------------------------------------------------------------------------- // Assign values to the static symbols void initialize() { #define ASYM(_id) ASYMBOL_ASSIGN(ASymbol, _id) #define ASYMX(_id, _str) ASYMBOL_ASSIGN_STR(ASymbolX, _id, _str) SK_SYMBOLS SK_SYMBOLS_NAMED #undef ASYMX #undef ASYM } //--------------------------------------------------------------------------------------- // Clean up static symbols void deinitialize() { #define ASYM(_id) ASYMBOL_ASSIGN_NULL(ASymbol, _id) #define ASYMX(_id, _str) ASYMBOL_ASSIGN_STR_NULL(ASymbolX, _id, _str) SK_SYMBOLS SK_SYMBOLS_NAMED #undef ASYMX #undef ASYM } } //--------------------------------------------------------------------------------------- // Define ASymbol constants // Symbol Table to use in macros #define ASYM(_id) ASYMBOL_DEFINE_NULL(ASymbol, _id) #define ASYMX(_id, _str) ASYMBOL_DEFINE_STR_NULL(ASymbolX, _id, _str) SK_SYMBOLS SK_SYMBOLS_NAMED #undef ASYMX #undef ASYM
0
0.735369
1
0.735369
game-dev
MEDIA
0.584027
game-dev
0.509026
1
0.509026
ServUO/ServUO
1,632
Scripts/Items/Artifacts/Equipment/Armor/HealersTouch.cs
using System; namespace Server.Items { public class HealersTouch : LeatherGloves { public override bool IsArtifact { get { return true; } } [Constructable] public HealersTouch() { LootType = LootType.Blessed; Attributes.BonusStam = 3; Attributes.ReflectPhysical = 5; } public HealersTouch(Serial serial) : base(serial) { } public override int LabelNumber { get { return 1077684; } }// Healer's Touch public override int BasePhysicalResistance { get { return 6; } } public override int BaseFireResistance { get { return 6; } } public override int BaseColdResistance { get { return 5; } } public override int BasePoisonResistance { get { return 5; } } public override int BaseEnergyResistance { get { return 5; } } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.WriteEncodedInt(0); // version } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadEncodedInt(); } } }
0
0.801071
1
0.801071
game-dev
MEDIA
0.456572
game-dev
0.750409
1
0.750409
sebas77/-Obsolete-TaskRunner
1,141
Assets/Scripts/Svelto/TaskRunner/TaskRoutinePool.cs
using System.Collections; using Svelto.DataStructures; namespace Svelto.Tasks.Internal { internal class TaskRoutinePool { internal TaskRoutinePool(IRunner runner) { _runner = runner; } internal TaskRoutine RetrieveTask() { if (_pool.Count > 0) return _pool.Dequeue(); return CreateEmptyTask(); } internal void Start(IEnumerator enumerator, bool isSimple) { TaskRoutine task = RetrieveTask(); task.Start(EnumeratorDecorator(enumerator, task), isSimple); } IEnumerator EnumeratorDecorator(IEnumerator enumerator, TaskRoutine task) { while (enumerator.MoveNext() == true) yield return enumerator.Current; _pool.Enqueue(task); } TaskRoutine CreateEmptyTask() { PausableTask ptask = new PausableTask(_runner); return new TaskRoutine(ptask); } ThreadSafeQueue<TaskRoutine> _pool = new ThreadSafeQueue<TaskRoutine>(); IRunner _runner; } }
0
0.739475
1
0.739475
game-dev
MEDIA
0.644119
game-dev
0.846262
1
0.846262
rockbite/talos
1,040
editor/src/com/talosvfx/talos/editor/addons/scene/events/GameObjectSelectionChanged.java
package com.talosvfx.talos.editor.addons.scene.events; import com.badlogic.gdx.utils.ObjectSet; import com.talosvfx.talos.runtime.scene.GameObject; import com.talosvfx.talos.editor.notifications.ContextRequiredEvent; import com.talosvfx.talos.editor.notifications.events.AbstractContextRequiredEvent; public class GameObjectSelectionChanged<T> extends AbstractContextRequiredEvent<T> { private ObjectSet<GameObject> objectArray = new ObjectSet<>(); public GameObjectSelectionChanged set(T context, GameObject gameObject) { setContext(context); objectArray.clear(); objectArray.add(gameObject); return this; } public GameObjectSelectionChanged set(T context, ObjectSet<GameObject> arr) { setContext(context); objectArray.clear(); objectArray.addAll(arr); return this; } public ObjectSet<GameObject> get() { return objectArray; } @Override public void reset () { super.reset(); objectArray.clear(); } }
0
0.863049
1
0.863049
game-dev
MEDIA
0.918608
game-dev
0.812607
1
0.812607
PolarisSS13/Polaris
6,611
code/game/objects/effects/decals/posters/posters.dm
/proc/get_poster_decl(var/path = null, var/exact = TRUE) if(ispath(path)) if(exact) return decls_repository.get_decl(path) else var/list/L = decls_repository.get_decls_of_type(path) return L[pick(L)] return null /obj/item/poster name = "rolled-up poster" desc = "The poster comes with its own automatic adhesive mechanism, for easy pinning to any vertical surface." icon = 'icons/obj/contraband.dmi' icon_state = "rolled_poster" drop_sound = 'sound/items/drop/wrapper.ogg' pickup_sound = 'sound/items/pickup/wrapper.ogg' force = 0 var/decl/poster/poster_decl = null var/poster_type = /obj/structure/sign/poster /obj/item/poster/Initialize(var/mapload, var/decl/poster/poster_decl = null) if(ispath(src.poster_decl)) src.poster_decl = get_poster_decl(src.poster_decl, TRUE) else if(istype(poster_decl)) src.poster_decl = poster_decl else if(ispath(poster_decl)) src.poster_decl = get_poster_decl(poster_decl, TRUE) else src.poster_decl = get_poster_decl(/decl/poster, FALSE) name += " - [src.poster_decl.name]" return ..() //Places the poster on a wall /obj/item/poster/afterattack(var/atom/A, var/mob/user, var/adjacent, var/clickparams) if(!adjacent) return FALSE //must place on a wall and user must not be inside a closet/mecha/whatever var/turf/W = A if(!iswall(W) || !isturf(user.loc)) to_chat(user, "<span class='warning'>You can't place this here!</span>") return FALSE var/placement_dir = get_dir(user, W) if(!(placement_dir in cardinal)) to_chat(user, "<span class='warning'>You must stand directly in front of the wall you wish to place that on.</span>") return FALSE //just check if there is a poster on or adjacent to the wall var/stuff_on_wall = 0 if(locate(/obj/structure/sign/poster) in W) stuff_on_wall = 1 //crude, but will cover most cases. We could do stuff like check pixel_x/y but it's not really worth it. for (var/dir in cardinal) var/turf/T = get_step(W, dir) if (locate(/obj/structure/sign/poster) in T) stuff_on_wall = 1 break if(stuff_on_wall) to_chat(user, "<span class='notice'>There is already a poster there!</span>") return FALSE to_chat(user, "<span class='notice'>You start placing the poster on the wall...</span>") //Looks like it's uncluttered enough. Place the poster. var/obj/structure/sign/poster/P = new poster_type(user.loc, get_dir(user, W), src) if(do_after(user, 17)) //Let's check if everything is still there to_chat(user, "<span class='notice'>You place the poster!</span>") qdel(src) return TRUE P.roll_and_drop(P.loc) qdel(src) return FALSE //NT subtype /obj/item/poster/nanotrasen icon_state = "rolled_poster_nt" poster_type = /obj/structure/sign/poster/nanotrasen /obj/item/poster/nanotrasen/Initialize(turf/loc, var/decl/poster/P = null) if(!ispath(src.poster_decl) && !ispath(P) && !istype(P)) src.poster_decl = get_poster_decl(/decl/poster/nanotrasen, FALSE) return ..() //Selectable subtype /obj/item/poster/custom name = "rolled-up poly-poster" desc = "The poster comes with its own automatic adhesive mechanism, for easy pinning to any vertical surface. This one is made from some kind of e-paper, and could display almost anything!" poster_type = /obj/structure/sign/poster/custom /obj/item/poster/custom/verb/select_poster() set name = "Set Poster type" set category = "Object" set desc = "Click to choose a poster to display." var/mob/M = usr var/list/options = list() var/list/decl/poster/posters = decls_repository.get_decls_of_type(/decl/poster) for(var/option in posters) options[posters[option].listing_name] = posters[option] var/choice = input(M,"Choose a poster!","Customize Poster") in options if(src && choice && !M.stat && in_range(M,src)) poster_decl = options[choice] name = "rolled-up poly-poster - [src.poster_decl.name]" to_chat(M, "The poster is now: [choice].") //############################## THE ACTUAL DECALS ########################### /obj/structure/sign/poster name = "poster" desc = "A large piece of space-resistant printed paper. " icon = 'icons/obj/contraband.dmi' anchored = 1 var/decl/poster/poster_decl = null var/target_poster_decl_path = /decl/poster var/roll_type = /obj/item/poster var/ruined = FALSE // This stuff needs to go in new() for the the flick() to look right while it's being placed /obj/structure/sign/poster/Initialize(var/ml, var/placement_dir = null, var/obj/item/poster/P = null) if(placement_dir) dir = placement_dir switch (dir) if (NORTH) pixel_x = 0 pixel_y = 32 if (SOUTH) pixel_x = 0 pixel_y = -32 if (EAST) pixel_x = 32 pixel_y = 0 if (WEST) pixel_x = -32 pixel_y = 0 flick("poster_being_set", src) . = ..() /obj/structure/sign/poster/Initialize(var/newloc, var/placement_dir = null, var/obj/item/poster/P = null) if(ispath(src.poster_decl)) src.poster_decl = get_poster_decl(src.poster_decl, TRUE) else if(istype(P)) src.poster_decl = P.poster_decl roll_type = P.type else if(ispath(P)) src.poster_decl = get_poster_decl(P, TRUE) else src.poster_decl = get_poster_decl(target_poster_decl_path, FALSE) name = "[initial(name)] - [poster_decl.name]" desc = "[initial(desc)] [poster_decl.desc]" icon_state = poster_decl.icon_state return ..() /obj/structure/sign/poster/attackby(obj/item/W as obj, mob/user as mob) if(W.is_wirecutter()) playsound(src, W.usesound, 100, 1) if(ruined) to_chat(user, "<span class='notice'>You remove the remnants of the poster.</span>") qdel(src) else to_chat(user, "<span class='notice'>You carefully remove the poster from the wall.</span>") roll_and_drop(get_turf(user)) return /obj/structure/sign/poster/attack_hand(mob/user as mob) if(ruined) return if(alert("Do I want to rip the poster from the wall?","You think...","Yes","No") == "Yes") if(ruined || !user.Adjacent(src)) return visible_message("<span class='warning'>[user] rips [src] in a single, decisive motion!</span>" ) playsound(src, 'sound/items/poster_ripped.ogg', 100, 1) ruined = TRUE icon_state = "poster_ripped" name = "ripped poster" desc = "You can't make out anything from the poster's original print. It's ruined." add_fingerprint(user) /obj/structure/sign/poster/proc/roll_and_drop(turf/newloc) var/obj/item/poster/P = new roll_type(newloc, poster_decl) P.loc = newloc qdel(src) // NT poster subtype. /obj/structure/sign/poster/nanotrasen roll_type = /obj/item/poster/nanotrasen target_poster_decl_path = /decl/poster/nanotrasen // Non-Random Posters /obj/structure/sign/poster/custom roll_type = /obj/item/poster/custom
0
0.803051
1
0.803051
game-dev
MEDIA
0.894467
game-dev
0.704348
1
0.704348
AndnixSH/Free-Shared-Mod-Codes-Collections
2,645
Mobile Hooking and Patching sources (C++)/[G-Presto] GODDESS KISS O.V.E.hpp
bool hack1 = false, hack2 = false, hack3 = false; int dmgmul = 1, defmul = 1; void Changes(JNIEnv *env, jclass clazz, jobject obj, jint featNum, jstring featName, jint value, jboolean boolean, jstring str) { // You must count your features from 0, not 1 switch (featNum) { case 0: if (value >= 1) { dmgmul = value; } break; case 1: if (value >= 1) { defmul = value; } break; } } std::vector<bool> toggles; jobjectArray GetFeatureList( JNIEnv *env, jobject activityObject) { jobjectArray ret; const char *features[] = { O("InputValue_Damage Multiplier"), O("InputValue_Defense Multiplier")}; int Total_Feature = (sizeof features / sizeof features[0]); //Now you dont have to manually update the number everytime; ret = (jobjectArray) env->NewObjectArray(Total_Feature, env->FindClass(O("java/lang/String")), env->NewStringUTF("")); int i; for (i = 0; i < Total_Feature; i++) env->SetObjectArrayElement(ret, i, env->NewStringUTF(features[i])); return (ret); } // public enum FBGGDJFPEJL // { // [Token(Token = "0x4006971")] // None = -1, // [Token(Token = "0x4006972")] // Defence, // [Token(Token = "0x4006973")] // Attack, // [Token(Token = "0x4006974")] // Max // } //public class ObjectBase : MonoBehaviour //public virtual int GJJHLNIIBJP(GCBBKJJLOEF OEJFFEBIIDI, ObjectBase KFEPCDBOMMK, bool IOALKEKKPLC, bool CPMJGHLMPAK, int ANBKCEFMCHJ = 1, bool MFCMLDNGLKM = false) int (*orig_Attack)(void* _this, int OEJFFEBIIDI, void* KFEPCDBOMMK, bool IOALKEKKPLC, bool CPMJGHLMPAK, int ANBKCEFMCHJ, bool MFCMLDNGLKM ); int Attack(void* _this, int OEJFFEBIIDI, void* KFEPCDBOMMK, bool IOALKEKKPLC, bool CPMJGHLMPAK, int ANBKCEFMCHJ, bool MFCMLDNGLKM ) { int side = *(int*)((uint64_t)_this + 0x28); //public FBGGDJFPEJL _teamType; int orig = orig_Attack(_this, OEJFFEBIIDI, KFEPCDBOMMK, IOALKEKKPLC, CPMJGHLMPAK, ANBKCEFMCHJ, MFCMLDNGLKM); //LOGD("side %d", side); if(side == 1) //Attack { return orig * dmgmul; } if(side == 0) //Defence { return orig / defmul; } return orig; } #define SoFile O("libil2cpp.so") void hack_thread(){ LOGI(O("load lib open")); do { sleepy(1); } while (!isLibraryLoaded(SoFile)); sleepy(6); Hook((void *)( /* "Assembly-CSharp.dll" "ObjectBase" "GJJHLNIIBJP" */ ), (void *)Attack, (void **) &orig_Attack); LOGD(O("il2cpp loaded")); }
0
0.693886
1
0.693886
game-dev
MEDIA
0.333486
game-dev
0.730104
1
0.730104
roflmuffin/CounterStrikeSharp
1,723
managed/CounterStrikeSharp.API/Core/Schema/Classes/CGameRules.g.cs
// <auto-generated /> #nullable enable #pragma warning disable CS1591 using System; using System.Diagnostics; using System.Drawing; using CounterStrikeSharp; using CounterStrikeSharp.API.Modules.Events; using CounterStrikeSharp.API.Modules.Entities; using CounterStrikeSharp.API.Modules.Memory; using CounterStrikeSharp.API.Modules.Utils; using CounterStrikeSharp.API.Core.Attributes; namespace CounterStrikeSharp.API.Core; public partial class CGameRules : NativeObject { public CGameRules (IntPtr pointer) : base(pointer) {} // __m_pChainEntity [SchemaMember("CGameRules", "__m_pChainEntity")] public CNetworkVarChainer __m_pChainEntity => Schema.GetDeclaredClass<CNetworkVarChainer>(this.Handle, "CGameRules", "__m_pChainEntity"); // m_szQuestName [SchemaMember("CGameRules", "m_szQuestName")] public string QuestName { get { return Schema.GetString(this.Handle, "CGameRules", "m_szQuestName"); } set { Schema.SetStringBytes(this.Handle, "CGameRules", "m_szQuestName", value, 128); } } // m_nQuestPhase [SchemaMember("CGameRules", "m_nQuestPhase")] public ref Int32 QuestPhase => ref Schema.GetRef<Int32>(this.Handle, "CGameRules", "m_nQuestPhase"); // m_nTotalPausedTicks [SchemaMember("CGameRules", "m_nTotalPausedTicks")] public ref Int32 TotalPausedTicks => ref Schema.GetRef<Int32>(this.Handle, "CGameRules", "m_nTotalPausedTicks"); // m_nPauseStartTick [SchemaMember("CGameRules", "m_nPauseStartTick")] public ref Int32 PauseStartTick => ref Schema.GetRef<Int32>(this.Handle, "CGameRules", "m_nPauseStartTick"); // m_bGamePaused [SchemaMember("CGameRules", "m_bGamePaused")] public ref bool GamePaused => ref Schema.GetRef<bool>(this.Handle, "CGameRules", "m_bGamePaused"); }
0
0.793208
1
0.793208
game-dev
MEDIA
0.971779
game-dev
0.599448
1
0.599448
InvadingOctopus/octopuskit
8,337
Sources/OctopusKit/Components/Abstract/RelayComponent.swift
// // RelayComponent.swift // OctopusKit // // Created by ShinryakuTako@invadingoctopus.io on 2018/04/10. // Copyright © 2020 Invading Octopus. Licensed under Apache License v2.0 (see LICENSE.txt) // import OctopusCore import GameplayKit import OSLog /// A component that points to another component in a different entity. Used for sharing a single component instance across different entities. /// /// Useful for cases like dynamically linking input event manager components (e.g. `TouchEventComponent`) from a scene to input-controlled components (e.g. `TouchControlledPositioningComponent`) in an entity. /// /// The `GKComponent.coComponent(ofType:)` and `GKEntity.componentOrRelay(ofType:)` methods will check the entity for a `RelayComponent` which points to a component of the specified type, if the entity itself does not have a component of the specified type. /// /// - Important: `GKEntity.component(ofType:)` does *not* automatically substitute a `RelayComponent` for the specified component class, due to GameplayKit/Swift limitations. Use `GKEntity.componentOrRelay(ofType:)` or `GKComponent.coComponent(ofType:)` to automatically look for `RelayComponent`s. public final class RelayComponent <MasterComponentType> : OKComponent where MasterComponentType: GKComponent { // ℹ️ GameplayKit does not allow an entity to have more than one component of the same class, but a generic class with different associated types can be added, e.g. `RelayComponent<Component1>` and `RelayComponent<Component2>`. /// The component that this `RelayComponent` holds a reference to. /// /// At runtime, this property resolves to either the `directlyReferencedComponent`, or if that is `nil`, the `sceneComponentType`, which checks the scene entity of the `NodeComponent` node of this `RelayComponent`'s entity. /// /// The `GKComponent.coComponent(ofType:)` and `GKEntity.componentOrRelay(ofType:)` methods will check the entity for a `RelayComponent` which points to a component matching the specified type, if the entity itself does not have a component of the specified type. /// /// - IMPORTANT: `GKEntity.component(ofType:)` does *not* automatically substitute a `RelayComponent` for the specified component class, due to GameplayKit/Swift limitations. Use `GKEntity.componentOrRelay(ofType:)` or `GKComponent.coComponent(ofType:)` to automatically look for `RelayComponent`s. @inlinable public var target: MasterComponentType? { #if LOGECSDEBUG debugLog("self: \(self)") #endif if let directlyReferencedComponent = self.directlyReferencedComponent { #if LOGECSDEBUG debugLog("directlyReferencedComponent: \(directlyReferencedComponent)") #endif return directlyReferencedComponent } else if let sceneComponentType = self.sceneComponentType { #if LOGECSDEBUG debugLog("Accessing self.entityNode?.scene?.entity?.component(ofType: \(sceneComponentType))") #endif // ❕ NOTE: Accessing `entityNode` used to cause infinite recursion because `GKEntity.node` calls `GKEntity.componentOrRelay(ofType:)` which leads back here. :) // FIXED: `GKEntity.node` now uses `GKEntity.component(ofType:)` instead of `GKEntity.componentOrRelay(ofType:)` and checks for `directlyReferencedComponent` instead of this `target` property. return self.entityNode?.scene?.entity?.component(ofType: sceneComponentType) } else { return nil } } /// A direct reference to a shared component. If this value is `nil`, then this `RelayComponent` will point to the `sceneComponentType`, if specified. public var directlyReferencedComponent: MasterComponentType? // PERFORMANCE: The increased property accesses may decrease performance, especially for components like `TouchEventComponent` that are accessed every frame. /// The type of component to look for in the entity which represents the scene associated with the `NodeComponent` node of this `RelayComponent`'s entity. /// /// `RelayComponent.entityNode?.scene?.entity?.component(ofType: sceneComponentType)` /// /// This property is only used if the `directlyReferencedComponent` is `nil. public var sceneComponentType: MasterComponentType.Type? /// This helps `GKEntity.componentOrRelay(ofType:)` see the correct concrete type at runtime, e.g. when comparing with `OKComponent.requiredComponents`. @inlinable public override var componentType: GKComponent.Type { #if LOGECSDEBUG debugLog("self: \(self), \(type(of: self)), target?.componentType: \(target?.componentType)") #endif return target?.componentType ?? type(of: self) } public override var description: String { "\(super.description), directlyReferencedComponent: \(directlyReferencedComponent), sceneComponentType: \(sceneComponentType)" } // MARK: - Life Cycle public init(for targetComponent: MasterComponentType?) { // ℹ️ DESIGN: `target` is optional so that we can write stuff like `entity1.addComponent(RelayComponent(for: entity2.component(ofType: SomeComponent.self)))` #if LOGECSVERBOSE debugLog("targetComponent: \(targetComponent)") #endif self.directlyReferencedComponent = targetComponent super.init() } /// Creates a `RelayComponent` which points to a component of the specified type in the scene entity associated with the `NodeComponent` node of this `RelayComponent`'s entity. /// /// Whenever the `target` of this relay is requested, it will check for `self.entityNode?.scene?.entity?.component(ofType: sceneComponentType)`. /// /// - IMPORTANT: ⚠️ Newly-created entities will not be able to find components via `RelayComponent(sceneComponentType:)` *before* they are added to a scene. public init(sceneComponentType: MasterComponentType.Type) { #if LOGECSVERBOSE debugLog("sceneComponentType: \(sceneComponentType)") #endif self.sceneComponentType = sceneComponentType super.init() } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @inlinable public override func didAddToEntity() { super.didAddToEntity() guard let entity = self.entity else { return } // Warn if the entity already has the actual component that we're a relay for. if let existingComponent = coComponent(MasterComponentType.self, ignoreRelayComponents: true) { if existingComponent === target { OKLog.warnings.debug("\(📜("\(entity) already has \(existingComponent)"))") } else { OKLog.warnings.debug("\(📜("\(entity) already has a \(type(of: existingComponent)) component: \(existingComponent)"))") } } } // MARK: Debugging public override func update(deltaTime seconds: TimeInterval) { OKLog.warnings.debug("\(📜("RelayComponent.update(deltaTime:) should not be called — Update the target component: \(self.target) — Object: \(self)"))") } /* public override var baseComponent: GKComponent? { // CHECK: Include? Will it improve correctness and performance in GKEntity.componentOrRelay(ofType:) or is it unnecessary? // THANKS: https://forums.swift.org/u/TellowKrinkle // https://forums.swift.org/t/type-information-loss-when-comparing-generic-variables-with-an-array-of-metatypes/30650 target?.baseComponent // ?? self } */ } // MARK: Convenience /// A protocol to add the `relay()` convenience for `GKComponent` and all subclasses. public protocol RelayComponentTarget: GKComponent { // THANKS: https://forums.swift.org/u/ddddxxx } public extension RelayComponentTarget { /// Creates and returns a `RelayComponent` for this component. func relay() -> RelayComponent<Self> { return RelayComponent(for: self) } } extension GKComponent: RelayComponentTarget {}
0
0.721773
1
0.721773
game-dev
MEDIA
0.937186
game-dev
0.578049
1
0.578049
prasannavl/LiquidState
6,266
LiquidState/Extensions/StateConfigurationExtensions.cs
// Author: Prasanna V. Loganathar // Created: 22:55 17-07-2015 // Project: LiquidState // License: http://www.apache.org/licenses/LICENSE-2.0 using System; using LiquidState.Core; using LiquidState.Synchronous.Core; using LiquidState.Common; namespace LiquidState { public static class StateConfigurationExtensions { public static StateConfiguration<TState, TTrigger> OnEntry<TState, TTrigger>( this StateConfiguration<TState, TTrigger> config, Action action) { Contract.NotNull(action != null, nameof(action)); return config.OnEntry(t => action()); } public static StateConfiguration<TState, TTrigger> OnExit<TState, TTrigger>( this StateConfiguration<TState, TTrigger> config, Action action) { Contract.NotNull(action != null, nameof(action)); return config.OnExit(t => action()); } public static StateConfiguration<TState, TTrigger> Permit<TState, TTrigger>( this StateConfiguration<TState, TTrigger> config, TTrigger trigger, TState resultingState, Action onTriggerAction) { Contract.NotNull(onTriggerAction != null, nameof(onTriggerAction)); return config.Permit(trigger, resultingState, t => onTriggerAction()); } public static StateConfiguration<TState, TTrigger> Permit<TState, TTrigger, TArgument>(this StateConfiguration<TState, TTrigger> config, ParameterizedTrigger<TTrigger, TArgument> trigger, TState resultingState, Action<TArgument> onTriggerAction) { Contract.NotNull(onTriggerAction != null, nameof(onTriggerAction)); return config.Permit(trigger, resultingState, (t, a) => onTriggerAction (a)); } public static StateConfiguration<TState, TTrigger> PermitIf<TState, TTrigger>( StateConfiguration<TState, TTrigger> config, Func<bool> predicate, TTrigger trigger, TState resultingState, Action onTriggerAction) { Contract.NotNull(onTriggerAction != null, nameof(onTriggerAction)); return config.PermitIf(predicate, trigger, resultingState, t => onTriggerAction()); } public static StateConfiguration<TState, TTrigger> PermitIf<TArgument, TState, TTrigger>( this StateConfiguration<TState, TTrigger> config, Func<bool> predicate, ParameterizedTrigger<TTrigger, TArgument> trigger, TState resultingState, Action<TArgument> onTriggerAction) { Contract.NotNull(onTriggerAction != null, nameof(onTriggerAction)); return config.PermitIf(predicate, trigger, resultingState, (t, a) => onTriggerAction(a)); } public static StateConfiguration<TState, TTrigger> PermitReentry<TState, TTrigger>( this StateConfiguration<TState, TTrigger> config, TTrigger trigger, Action onTriggerAction) { Contract.NotNull(onTriggerAction != null, nameof(onTriggerAction)); return config.PermitReentry(trigger, t => onTriggerAction()); } public static StateConfiguration<TState, TTrigger> PermitReentry<TArgument, TState, TTrigger>( this StateConfiguration<TState, TTrigger> config, ParameterizedTrigger<TTrigger, TArgument> trigger, Action<TArgument> onTriggerAction) { Contract.NotNull(onTriggerAction != null, nameof(onTriggerAction)); return config.PermitReentry(trigger, (t, a) => onTriggerAction(a)); } public static StateConfiguration<TState, TTrigger> PermitReentryIf<TState, TTrigger>( this StateConfiguration<TState, TTrigger> config, Func<bool> predicate, TTrigger trigger, Action onTriggerAction) { Contract.NotNull(onTriggerAction != null, nameof(onTriggerAction)); return config.PermitReentryIf(predicate, trigger, t => onTriggerAction()); } public static StateConfiguration<TState, TTrigger> PermitReentryIf<TArgument, TState, TTrigger>( this StateConfiguration<TState, TTrigger> config, Func<bool> predicate, ParameterizedTrigger<TTrigger, TArgument> trigger, Action<TArgument> onTriggerAction) { Contract.NotNull(onTriggerAction != null, nameof(onTriggerAction)); return config.PermitReentryIf(predicate, trigger, (t, a) => onTriggerAction(a)); } public static StateConfiguration<TState, TTrigger> PermitDynamic<TState, TTrigger>( this StateConfiguration<TState, TTrigger> config, TTrigger trigger, Func<DynamicState<TState>> targetStatePredicate, Action onTriggerAction) { Contract.NotNull(onTriggerAction != null, nameof(onTriggerAction)); return config.PermitDynamic(trigger, targetStatePredicate, t => onTriggerAction()); } public static StateConfiguration<TState, TTrigger> PermitDynamic<TArgument, TState, TTrigger>( this StateConfiguration<TState, TTrigger> config, ParameterizedTrigger<TTrigger, TArgument> trigger, Func<DynamicState<TState>> targetStatePredicate, Action<TArgument> onTriggerAction) { Contract.NotNull(onTriggerAction != null, nameof(onTriggerAction)); return config.PermitDynamic(trigger, targetStatePredicate, (t, a) => onTriggerAction(a)); } public static StateConfiguration<TState, TTrigger> PermitDynamic<TArgument, TState, TTrigger>( this StateConfiguration<TState, TTrigger> config, ParameterizedTrigger<TTrigger, TArgument> trigger, Func<TArgument, DynamicState<TState>> targetStatePredicate, Action<TArgument> onTriggerAction) { Contract.NotNull(onTriggerAction != null, nameof(onTriggerAction)); return config.PermitDynamic(trigger, targetStatePredicate, (t, a) => onTriggerAction(a)); } } }
0
0.82431
1
0.82431
game-dev
MEDIA
0.775299
game-dev
0.805982
1
0.805982
OvercastNetwork/SportBukkit
2,125
snapshot/CraftBukkit/src/main/java/org/bukkit/craftbukkit/entity/CraftFish.java
package org.bukkit.craftbukkit.entity; import net.minecraft.server.BlockPosition; import net.minecraft.server.EntityFishingHook; import net.minecraft.server.EntityHuman; import net.minecraft.server.MathHelper; import org.apache.commons.lang.Validate; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.EntityType; import org.bukkit.entity.Fish; import org.bukkit.entity.LivingEntity; import org.bukkit.projectiles.ProjectileSource; public class CraftFish extends AbstractProjectile implements Fish { private double biteChance = -1; public CraftFish(CraftServer server, EntityFishingHook entity) { super(server, entity); } public ProjectileSource getShooter() { if (getHandle().owner != null) { return getHandle().owner.getBukkitEntity(); } return null; } public void setShooter(ProjectileSource shooter) { if (shooter instanceof CraftHumanEntity) { getHandle().owner = (EntityHuman) ((CraftHumanEntity) shooter).entity; } } @Override public EntityFishingHook getHandle() { return (EntityFishingHook) entity; } @Override public String toString() { return "CraftFish"; } public EntityType getType() { return EntityType.FISHING_HOOK; } public double getBiteChance() { EntityFishingHook hook = getHandle(); if (this.biteChance == -1) { if (hook.world.isRainingAt(new BlockPosition(MathHelper.floor(hook.locX), MathHelper.floor(hook.locY) + 1, MathHelper.floor(hook.locZ)))) { return 1/300.0; } return 1/500.0; } return this.biteChance; } public void setBiteChance(double chance) { Validate.isTrue(chance >= 0 && chance <= 1, "The bite chance must be between 0 and 1."); this.biteChance = chance; } @Deprecated public LivingEntity _INVALID_getShooter() { return (LivingEntity) getShooter(); } @Deprecated public void _INVALID_setShooter(LivingEntity shooter) { setShooter(shooter); } }
0
0.6895
1
0.6895
game-dev
MEDIA
0.965565
game-dev
0.757628
1
0.757628
Toxocious/Moonlight
1,543
Server/src/main/java/net/swordie/ms/constants/MonsterCollectionGroup.java
package net.swordie.ms.constants; import net.swordie.ms.client.character.Char; import net.swordie.ms.client.character.MonsterCollection; import net.swordie.ms.client.character.items.Item; import net.swordie.ms.loaders.ItemData; import net.swordie.ms.loaders.MonsterCollectionData; import java.util.*; /** * @author Sjonnie * Created on 7/22/2018. */ public class MonsterCollectionGroup { private Map<Integer, Integer> mobs = new HashMap<>(); private boolean rewardClaimed; private int reward; private int rewardQuantity; public MonsterCollectionGroup() { } public Map<Integer, Integer> getMobs() { return mobs; } public void setMobs(Map<Integer, Integer> mobs) { this.mobs = mobs; } public void addMob(int pos, int mob) { getMobs().put(pos, mob); } public int getReward() { return reward; } public void setReward(int reward) { this.reward = reward; } public boolean isRewardClaimed() { return rewardClaimed; } public void setRewardClaimed(boolean rewardClaimed) { this.rewardClaimed = rewardClaimed; } public void setRewardQuantity(int rewardQuantity) { this.rewardQuantity = rewardQuantity; } public int getRewardQuantity() { return rewardQuantity; } public boolean hasMob(int templateID) { return getMobs().values().contains(templateID); } public boolean hasMobAtPosition(int pos) { return getMobs().containsKey(pos); } }
0
0.525631
1
0.525631
game-dev
MEDIA
0.989673
game-dev
0.838001
1
0.838001
HbmMods/Hbm-s-Nuclear-Tech-GIT
6,478
src/main/java/com/hbm/blocks/machine/rbmk/RBMKBase.java
package com.hbm.blocks.machine.rbmk; import com.hbm.blocks.BlockDummyable; import com.hbm.blocks.ILookOverlay; import com.hbm.handler.MultiblockHandlerXR; import com.hbm.handler.neutron.NeutronNodeWorld; import com.hbm.handler.neutron.RBMKNeutronHandler.RBMKNeutronNode; import com.hbm.items.ModItems; import com.hbm.items.machine.ItemRBMKLid; import com.hbm.lib.RefStrings; import com.hbm.main.MainRegistry; import com.hbm.tileentity.machine.rbmk.RBMKDials; import com.hbm.tileentity.machine.rbmk.TileEntityRBMKBase; import api.hbm.block.IToolable; import com.hbm.util.fauxpointtwelve.BlockPos; import cpw.mods.fml.client.registry.RenderingRegistry; import cpw.mods.fml.common.network.internal.FMLNetworkHandler; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.ResourceLocation; import net.minecraft.world.World; import net.minecraftforge.client.event.RenderGameOverlayEvent.Pre; import net.minecraftforge.common.util.ForgeDirection; public abstract class RBMKBase extends BlockDummyable implements IToolable, ILookOverlay { public static boolean dropLids = true; public static boolean digamma = false; public ResourceLocation coverTexture; protected RBMKBase() { super(Material.iron); this.setHardness(3F); this.setResistance(30F); } @Override public Block setBlockTextureName(String texture) { this.textureName = texture; this.coverTexture = new ResourceLocation(RefStrings.MODID + ":textures/blocks/" + (texture.split(":")[1]) + ".png"); return this; } @Override public int[] getDimensions() { return new int[] {3, 0, 0, 0, 0, 0}; } @Override public int getOffset() { return 0; } public boolean openInv(World world, int x, int y, int z, EntityPlayer player) { if(world.isRemote) { return true; } int[] pos = this.findCore(world, x, y, z); if(pos == null) return false; TileEntity te = world.getTileEntity(pos[0], pos[1], pos[2]); if(!(te instanceof TileEntityRBMKBase)) return false; TileEntityRBMKBase rbmk = (TileEntityRBMKBase) te; if(player.getHeldItem() != null && player.getHeldItem().getItem() instanceof ItemRBMKLid) { if(!rbmk.hasLid()) return false; } if(!player.isSneaking()) { FMLNetworkHandler.openGui(player, MainRegistry.instance, 0, world, pos[0], pos[1], pos[2]); return true; } else { return true; } } @Override public AxisAlignedBB getCollisionBoundingBoxFromPool(World world, int x, int y, int z) { float height = 0.0F; int[] pos = this.findCore(world, x, y, z); if(pos != null) { TileEntity te = world.getTileEntity(pos[0], pos[1], pos[2]); if(te instanceof TileEntityRBMKBase) { TileEntityRBMKBase rbmk = (TileEntityRBMKBase) te; if(rbmk.hasLid()) { height += 0.25F; } } } return AxisAlignedBB.getBoundingBox(x + this.minX, y + this.minY, z + this.minZ, x + this.maxX, y + this.maxY + height, z + this.maxZ); } /* * NORTH: no cover * EAST: concrete cover * SOUTH: lead glass cover * WEST: UNUSED */ public static final ForgeDirection DIR_NO_LID = ForgeDirection.NORTH; public static final ForgeDirection DIR_NORMAL_LID = ForgeDirection.EAST; public static final ForgeDirection DIR_GLASS_LID = ForgeDirection.SOUTH; @Override public void fillSpace(World world, int x, int y, int z, ForgeDirection dir, int o) { MultiblockHandlerXR.fillSpace(world, x + dir.offsetX * o, y + dir.offsetY * o, z + dir.offsetZ * o, getDimensions(world), this, dir); this.makeExtra(world, x, y + RBMKDials.getColumnHeight(world), z); } @Override protected ForgeDirection getDirModified(ForgeDirection dir) { return DIR_NO_LID; } public int[] getDimensions(World world) { return new int[] {RBMKDials.getColumnHeight(world), 0, 0, 0, 0, 0}; } @Override public void breakBlock(World world, int x, int y, int z, Block b, int i) { if(!world.isRemote && dropLids) { if(i == DIR_NORMAL_LID.ordinal() + offset) { world.spawnEntityInWorld(new EntityItem(world, x + 0.5, y + 0.5 + RBMKDials.getColumnHeight(world), z + 0.5, new ItemStack(ModItems.rbmk_lid))); } if(i == DIR_GLASS_LID.ordinal() + offset) { world.spawnEntityInWorld(new EntityItem(world, x + 0.5, y + 0.5 + RBMKDials.getColumnHeight(world), z + 0.5, new ItemStack(ModItems.rbmk_lid_glass))); } } super.breakBlock(world, x, y, z, b, i); } @Override public boolean onScrew(World world, EntityPlayer player, int x, int y, int z, int side, float fX, float fY, float fZ, ToolType tool) { if(tool != ToolType.SCREWDRIVER) return false; int[] pos = this.findCore(world, x, y, z); if(pos != null) { TileEntity te = world.getTileEntity(pos[0], pos[1], pos[2]); if(te instanceof TileEntityRBMKBase) { TileEntityRBMKBase rbmk = (TileEntityRBMKBase) te; int i = rbmk.getBlockMetadata(); if(rbmk.hasLid() && rbmk.isLidRemovable()) { RBMKNeutronNode node = (RBMKNeutronNode) NeutronNodeWorld.getNode(world, new BlockPos(te)); if(node != null) node.removeLid(); if(!world.isRemote) { if(i == DIR_NORMAL_LID.ordinal() + offset) { world.spawnEntityInWorld(new EntityItem(world, pos[0] + 0.5, pos[1] + 0.5 + RBMKDials.getColumnHeight(world), pos[2] + 0.5, new ItemStack(ModItems.rbmk_lid))); } if(i == DIR_GLASS_LID.ordinal() + offset) { world.spawnEntityInWorld(new EntityItem(world, pos[0] + 0.5, pos[1] + 0.5 + RBMKDials.getColumnHeight(world), pos[2] + 0.5, new ItemStack(ModItems.rbmk_lid_glass))); } world.setBlockMetadataWithNotify(pos[0], pos[1], pos[2], DIR_NO_LID.ordinal() + offset, 3); } return true; } } } return false; } @Override @SideOnly(Side.CLIENT) public void printHook(Pre event, World world, int x, int y, int z) { TileEntityRBMKBase.diagnosticPrintHook(event, world, x, y, z); } public static int renderIDRods = RenderingRegistry.getNextAvailableRenderId(); public static int renderIDPassive = RenderingRegistry.getNextAvailableRenderId(); public static int renderIDControl = RenderingRegistry.getNextAvailableRenderId(); @Override public int transformMeta(int meta, int coordBaseMode) { return meta; } }
0
0.915628
1
0.915628
game-dev
MEDIA
0.969389
game-dev
0.897255
1
0.897255
krpc/krpc
5,483
service/SpaceCenter/src/Services/Parts/ResourceHarvester.cs
using System; using System.Text.RegularExpressions; using KRPC.Service.Attributes; using KRPC.SpaceCenter.ExtensionMethods; using KRPC.Utils; namespace KRPC.SpaceCenter.Services.Parts { /// <summary> /// A resource harvester (drill). Obtained by calling <see cref="Part.ResourceHarvester"/>. /// </summary> [KRPCClass (Service = "SpaceCenter")] public class ResourceHarvester : Equatable<ResourceHarvester> { readonly ModuleResourceHarvester harvester; readonly ModuleAnimationGroup animator; internal static bool Is (Part part) { var internalPart = part.InternalPart; return internalPart.HasModule<ModuleResourceHarvester> () && internalPart.HasModule<ModuleAnimationGroup> (); } internal ResourceHarvester (Part part) { Part = part; var internalPart = part.InternalPart; harvester = internalPart.Module<ModuleResourceHarvester> (); animator = internalPart.Module<ModuleAnimationGroup> (); if (harvester == null || animator == null) throw new ArgumentException ("Part is not a resource harvester"); } /// <summary> /// Returns true if the objects are equal. /// </summary> public override bool Equals (ResourceHarvester other) { return !ReferenceEquals (other, null) && Part == other.Part && (harvester == other.harvester || harvester.Equals (other.harvester)); } /// <summary> /// Hash code for the object. /// </summary> public override int GetHashCode () { return Part.GetHashCode () ^ harvester.GetHashCode (); } /// <summary> /// The part object for this harvester. /// </summary> [KRPCProperty] public Part Part { get; private set; } /// <summary> /// The state of the harvester. /// </summary> [KRPCProperty] public ResourceHarvesterState State { get { if (harvester.IsActivated) return ResourceHarvesterState.Active; else if (animator.ActiveAnimation.isPlaying) return animator.isDeployed ? ResourceHarvesterState.Deploying : ResourceHarvesterState.Retracting; else if (animator.isDeployed) return ResourceHarvesterState.Deployed; else return ResourceHarvesterState.Retracted; } } /// <summary> /// Whether the harvester is deployed. /// </summary> [KRPCProperty] public bool Deployed { get { var state = State; return state == ResourceHarvesterState.Deployed || state == ResourceHarvesterState.Active; } set { if (value && !animator.isDeployed) animator.DeployModule (); if (!value && animator.isDeployed) animator.RetractModule (); } } /// <summary> /// Whether the harvester is actively drilling. /// </summary> [KRPCProperty] public bool Active { get { return State == ResourceHarvesterState.Active; } set { if (!Deployed) return; if (value && !harvester.IsActivated) harvester.StartResourceConverter (); if (!value && harvester.IsActivated) harvester.StopResourceConverter (); } } /// <summary> /// The rate at which the drill is extracting ore, in units per second. /// </summary> [KRPCProperty] public float ExtractionRate { get { if (!Active) return 0; return GetFloatValue (harvester.ResourceStatus); } } /// <summary> /// The thermal efficiency of the drill, as a percentage of its maximum. /// </summary> [KRPCProperty] public float ThermalEfficiency { get { if (!Active) return 0; var status = harvester.status; if (!status.Contains ("load")) return 0; return GetFloatValue (status); } } /// <summary> /// The core temperature of the drill, in Kelvin. /// </summary> [KRPCProperty] public float CoreTemperature { get { return (float)harvester.GetCoreTemperature (); } } /// <summary> /// The core temperature at which the drill will operate with peak efficiency, in Kelvin. /// </summary> [KRPCProperty] public float OptimumCoreTemperature { get { return (float)harvester.GetGoalTemperature (); } } static readonly Regex numberRegex = new Regex (@"(\d+(\.\d+)?)"); static float GetFloatValue (string value) { Match match = numberRegex.Match (value); if (!match.Success) return 0; float result; if (!float.TryParse (match.Groups [1].Value, out result)) return 0; return result; } } }
0
0.841774
1
0.841774
game-dev
MEDIA
0.971639
game-dev
0.903306
1
0.903306
ennuo/toolkit
1,318
lib/cwlib/src/main/java/cwlib/structs/script/LocalVariableDefinitionRow.java
package cwlib.structs.script; import cwlib.enums.ModifierType; import cwlib.io.Serializable; import cwlib.io.serializer.Serializer; import java.util.EnumSet; public class LocalVariableDefinitionRow implements Serializable { public static final int BASE_ALLOCATION_SIZE = 0x8; public EnumSet<ModifierType> modifiers = EnumSet.noneOf(ModifierType.class); public int typeReferenceIdx; public int nameStringIdx; public int offset; @Override public void serialize(Serializer serializer) { int version = serializer.getRevision().getVersion(); if (serializer.isWriting()) { short flags = ModifierType.getFlags(modifiers); if (version >= 0x3d9) serializer.getOutput().i16(flags); else serializer.getOutput().i32(flags); } else { int flags = (version >= 0x3d9) ? serializer.getInput().i16() : serializer.getInput().i32(); modifiers = ModifierType.fromValue(flags); } typeReferenceIdx = serializer.i32(typeReferenceIdx); nameStringIdx = serializer.i32(nameStringIdx); offset = serializer.i32(offset); } @Override public int getAllocatedSize() { return LocalVariableDefinitionRow.BASE_ALLOCATION_SIZE; } }
0
0.90837
1
0.90837
game-dev
MEDIA
0.463995
game-dev
0.814399
1
0.814399
folgerwang/UnrealEngine
23,152
Engine/Source/Runtime/Experimental/ChaosSolvers/Private/PBDRigidsSolver.cpp
// Copyright 1998-2019 Epic Games, Inc. All Rights Reserved. #if INCLUDE_CHAOS #include "PBDRigidsSolver.h" #include "Chaos/Utilities.h" #include "Chaos/PBDCollisionConstraintUtil.h" #include "Async/AsyncWork.h" #include "Misc/ScopeLock.h" #include "ChaosStats.h" DEFINE_LOG_CATEGORY_STATIC(LogPBDRigidsSolverSolver, Log, All); namespace Chaos { int8 PBDRigidsSolver::Invalid = -1; class AdvanceOneTimeStepTask : public FNonAbandonableTask { friend class FAutoDeleteAsyncTask<AdvanceOneTimeStepTask>; public: AdvanceOneTimeStepTask( PBDRigidsSolver* Scene, const float DeltaTime, TSharedPtr<FCriticalSection> PrevFrameLock, TSharedPtr<FEvent> PrevFrameEvent, TSharedPtr<FCriticalSection> CurrentFrameLock, TSharedPtr<FEvent> CurrentFrameEvent) : MScene(Scene) , MDeltaTime(DeltaTime) , PrevLock(PrevFrameLock) , CurrentLock(CurrentFrameLock) , PrevEvent(PrevFrameEvent) , CurrentEvent(CurrentFrameEvent) { UE_LOG(LogPBDRigidsSolverSolver, Verbose, TEXT("AdvanceOneTimeStepTask::AdvanceOneTimeStepTask()")); CurrentFrameLock->Lock(); } void DoWork() { UE_LOG(LogPBDRigidsSolverSolver, Verbose, TEXT("AdvanceOneTimeStepTask::DoWork()")); while (PrevLock.IsValid() && !PrevLock->TryLock()) { PrevEvent->Wait(1); } MScene->CreateRigidBodyCallback(MScene->MEvolution->Particles()); MScene->ParameterUpdateCallback(MScene->MEvolution->Particles(), MScene->MTime); MScene->DisableCollisionsCallback(MScene->MEvolution->DisabledCollisions()); { SCOPE_CYCLE_COUNTER(STAT_BeginFrame); MScene->StartFrameCallback(MDeltaTime, MScene->MTime); } while (MDeltaTime > MScene->MMaxDeltaTime) { MScene->ForceUpdateCallback(MScene->MEvolution->Particles(), MScene->MTime); MScene->MEvolution->ReconcileIslands(); MScene->KinematicUpdateCallback(MScene->MEvolution->Particles(), MScene->MMaxDeltaTime, MScene->MTime); MScene->MEvolution->AdvanceOneTimeStep(MScene->MMaxDeltaTime); MDeltaTime -= MScene->MMaxDeltaTime; } MScene->ForceUpdateCallback(MScene->MEvolution->Particles(), MScene->MTime); MScene->MEvolution->ReconcileIslands(); MScene->KinematicUpdateCallback(MScene->MEvolution->Particles(), MDeltaTime, MScene->MTime); MScene->MEvolution->AdvanceOneTimeStep(MDeltaTime); MScene->MTime += MDeltaTime; MScene->CurrentFrame++; { SCOPE_CYCLE_COUNTER(STAT_EndFrame); MScene->EndFrameCallback(MDeltaTime); } CurrentLock->Unlock(); CurrentEvent->Trigger(); } protected: TStatId GetStatId() const { RETURN_QUICK_DECLARE_CYCLE_STAT(AdvanceOneTimeStepTask, STATGROUP_ThreadPoolAsyncTasks); } PBDRigidsSolver* MScene; float MDeltaTime; TSharedPtr<FCriticalSection> PrevLock, CurrentLock; TSharedPtr<FEvent> PrevEvent, CurrentEvent; }; PBDRigidsSolver::PBDRigidsSolver() : TimeStepMultiplier(1.f) , bEnabled(false) , bHasFloor(true) , bIsFloorAnalytic(false) , FloorHeight(0.f) , MaxCollisionDataSize(1024) , CollisionDataTimeWindow(0.1f) , DoCollisionDataSpatialHash(true) , CollisionDataSpatialHashRadius(15.f) , MaxCollisionPerCell(1) , MaxBreakingDataSize(1024) , BreakingDataTimeWindow(0.1f) , DoBreakingDataSpatialHash(true) , BreakingDataSpatialHashRadius(15.f) , MaxBreakingPerCell(1) , MaxTrailingDataSize(1024) , TrailingDataTimeWindow(0.1f) , TrailingMinSpeedThreshold(100.f) , TrailingMinVolumeThreshold(1000.f) , MCurrentEvent(nullptr) , MCurrentLock(nullptr) { UE_LOG(LogPBDRigidsSolverSolver, Verbose, TEXT("PBDRigidsSolver::PBDRigidsSolver()")); Reset(); } void PBDRigidsSolver::Reset() { UE_LOG(LogPBDRigidsSolverSolver, Verbose, TEXT("PBDRigidsSolver::Reset()")); MTime = 0; MLastDt = 0.0f; bEnabled = false; CurrentFrame = 0; MMaxDeltaTime = 1; FieldForceNum = 0; FParticlesType TRigidParticles; MEvolution = TUniquePtr<FPBDRigidsEvolution>(new FPBDRigidsEvolution(MoveTemp(TRigidParticles))); GetRigidParticles().AddArray(&FieldForce); MEvolution->AddPBDConstraintFunction([&](FParticlesType& Particle, const float Time, const int32 Island) { this->AddConstraintCallback(Particle, Time, Island); }); MEvolution->AddForceFunction([&](FParticlesType& Particles, const float Time, const int32 Index) { this->AddForceCallback(Particles, Time, Index); }); MEvolution->AddForceFunction([&](FParticlesType& Particles, const float Time, const int32 Index) { if (Index < FieldForceNum) { Particles.F(Index) += FieldForce[Index]; } }); MEvolution->SetCollisionContactsFunction([&](FParticlesType& Particles, FCollisionConstraintsType& CollisionConstraints) { this->CollisionContactsCallback(Particles, CollisionConstraints); }); MEvolution->SetBreakingFunction([&](FParticlesType& Particles) { this->BreakingCallback(Particles); }); MEvolution->SetTrailingFunction([&](FParticlesType& Particles) { this->TrailingCallback(Particles); }); Callbacks.Reset(); FieldCallbacks.Reset(); KinematicProxies.Reset(); } void PBDRigidsSolver::RegisterCallbacks(FSolverCallbacks* CallbacksIn) { UE_LOG(LogPBDRigidsSolverSolver, Verbose, TEXT("PBDRigidsSolver::RegisterCallbacks()")); Callbacks.Add(CallbacksIn); KinematicProxies.Add(FKinematicProxy()); } void PBDRigidsSolver::UnregisterCallbacks(FSolverCallbacks* CallbacksIn) { UE_LOG(LogPBDRigidsSolverSolver, Verbose, TEXT("PBDRigidsSolver::UnregisterCallbacks()")); for (int CallbackIndex = 0; CallbackIndex < Callbacks.Num(); CallbackIndex++) { if (Callbacks[CallbackIndex] == CallbacksIn) { Callbacks[CallbackIndex] = nullptr; } } } void PBDRigidsSolver::RegisterFieldCallbacks(FSolverFieldCallbacks* CallbacksIn) { UE_LOG(LogPBDRigidsSolverSolver, Verbose, TEXT("PBDRigidsSolver::RegisterFieldCallbacks()")); FieldCallbacks.Add(CallbacksIn); } void PBDRigidsSolver::UnregisterFieldCallbacks(FSolverFieldCallbacks* CallbacksIn) { UE_LOG(LogPBDRigidsSolverSolver, Verbose, TEXT("PBDRigidsSolver::UnregisterFieldCallbacks()")); for (int CallbackIndex = 0; CallbackIndex < FieldCallbacks.Num(); CallbackIndex++) { if (FieldCallbacks[CallbackIndex] == CallbacksIn) { FieldCallbacks[CallbackIndex] = nullptr; } } } void PBDRigidsSolver::AdvanceSolverBy(float DeltaTime) { UE_LOG(LogPBDRigidsSolverSolver, Verbose, TEXT("PBDRigidsSolver::Tick(%3.5f)"), DeltaTime); if (bEnabled) { MLastDt = DeltaTime; // @todo : This is kind of strange. can we expose the solver to the // callbacks in a different way? for (int CallbackIndex = 0; CallbackIndex < Callbacks.Num(); CallbackIndex++) { if (Callbacks[CallbackIndex] != nullptr) { Callbacks[CallbackIndex]->SetSolver(this); } } for (int CallbackIndex = 0; CallbackIndex < FieldCallbacks.Num(); CallbackIndex++) { if (FieldCallbacks[CallbackIndex] != nullptr) { FieldCallbacks[CallbackIndex]->SetSolver(this); } } int32 NumTimeSteps = (int32)(1.f*TimeStepMultiplier); float dt = FMath::Min(DeltaTime, float(5 / 30.)) / (float)NumTimeSteps; for (int i = 0; i < NumTimeSteps; i++) { TSharedPtr<FCriticalSection> NewFrameLock(new FCriticalSection()); TSharedPtr<FEvent> NewFrameEvent(FPlatformProcess::CreateSynchEvent()); //(new FAutoDeleteAsyncTask<AdvanceOneTimeStepTask>(this, DeltaTime, MCurrentLock, MCurrentEvent, NewFrameLock, NewFrameEvent))->StartBackgroundTask(); AdvanceOneTimeStepTask(this, DeltaTime, MCurrentLock, MCurrentEvent, NewFrameLock, NewFrameEvent).DoWork(); MCurrentLock = NewFrameLock; MCurrentEvent = NewFrameEvent; } } } void PBDRigidsSolver::CreateRigidBodyCallback(PBDRigidsSolver::FParticlesType& Particles) { UE_LOG(LogPBDRigidsSolverSolver, Verbose, TEXT("PBDRigidsSolver::CreateRigidBodyCallback()")); int32 NumParticles = Particles.Size(); if (!Particles.Size()) { UE_LOG(LogPBDRigidsSolverSolver, Verbose, TEXT("... creating particles")); if (bHasFloor) { UE_LOG(LogPBDRigidsSolverSolver, Verbose, TEXT("... creating floor")); int Index = Particles.Size(); Particles.AddParticles(1); Particles.X(Index) = Chaos::TVector<float, 3>(0.f, 0.f, FloorHeight); Particles.V(Index) = Chaos::TVector<float, 3>(0.f, 0.f, 0.f); Particles.R(Index) = Chaos::TRotation<float, 3>::MakeFromEuler(Chaos::TVector<float, 3>(0.f, 0.f, 0.f)); Particles.W(Index) = Chaos::TVector<float, 3>(0.f, 0.f, 0.f); Particles.P(Index) = Particles.X(0); Particles.Q(Index) = Particles.R(0); Particles.M(Index) = 1.f; Particles.InvM(Index) = 0.f; Particles.I(Index) = Chaos::PMatrix<float, 3, 3>(1.f, 0.f, 0.f, 0.f, 1.f, 0.f, 0.f, 0.f, 1.f); Particles.InvI(Index) = Chaos::PMatrix<float, 3, 3>(0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f); Particles.Geometry(Index) = new Chaos::TPlane<float, 3>(Chaos::TVector<float, 3>(0.f, 0.f, FloorHeight), Chaos::TVector<float, 3>(0.f, 0.f, 1.f)); Particles.Geometry(Index)->IgnoreAnalyticCollisions(!bIsFloorAnalytic); } } for (int CallbackIndex = 0; CallbackIndex < Callbacks.Num(); CallbackIndex++) { UE_LOG(LogPBDRigidsSolverSolver, Verbose, TEXT("... creating bodies from callbacks")); if (Callbacks[CallbackIndex]!=nullptr && Callbacks[CallbackIndex]->IsSimulating()) { Callbacks[CallbackIndex]->CreateRigidBodyCallback(Particles); } } if (NumParticles != Particles.Size()) { int Size = ParticleCallbackMapping.Num(); ParticleCallbackMapping.Resize(Particles.Size()); for (int Index = Size; Index < ParticleCallbackMapping.Num(); Index++) { ParticleCallbackMapping[Index] = Invalid; } for (int CallbackIndex = 0; CallbackIndex < Callbacks.Num(); CallbackIndex++) { if (Callbacks[CallbackIndex] != nullptr) { Callbacks[CallbackIndex]->BindParticleCallbackMapping(CallbackIndex, ParticleCallbackMapping); } } InitializeFromParticleData(); } } bool PBDRigidsSolver::Enabled() const { UE_LOG(LogPBDRigidsSolverSolver, Verbose, TEXT("PBDRigidsSolver::Enabled()")); if (bEnabled) { for (int CallbackIndex = 0; CallbackIndex < Callbacks.Num(); CallbackIndex++) { if (Callbacks[CallbackIndex] != nullptr && Callbacks[CallbackIndex]->IsSimulating()) return true; } } return false; } void PBDRigidsSolver::ParameterUpdateCallback(PBDRigidsSolver::FParticlesType& Particles, const float Time) { UE_LOG(LogPBDRigidsSolverSolver, Verbose, TEXT("PBDRigidsSolver::ParameterUpdateCallback()")); for (int CallbackIndex = 0; CallbackIndex < Callbacks.Num(); CallbackIndex++) { if (Callbacks[CallbackIndex] != nullptr && Callbacks[CallbackIndex]->IsSimulating()) { Callbacks[CallbackIndex]->ParameterUpdateCallback(Particles, Time); } } } void PBDRigidsSolver::ForceUpdateCallback(PBDRigidsSolver::FParticlesType& Particles, const float Time) { UE_LOG(LogPBDRigidsSolverSolver, Verbose, TEXT("PBDRigidsSolver::ParameterUpdateCallback()")); // reset the FieldForces FieldForceNum = FieldForce.Num(); for (int32 i = 0; i < FieldForce.Num(); i++) { FieldForce[i] = FVector(0); } for (int CallbackIndex = 0; CallbackIndex < FieldCallbacks.Num(); CallbackIndex++) { if (FieldCallbacks[CallbackIndex] != nullptr && FieldCallbacks[CallbackIndex]->IsSimulating()) { FieldCallbacks[CallbackIndex]->CommandUpdateCallback(Particles, FieldForce, Time); } } } void PBDRigidsSolver::DisableCollisionsCallback(TSet<TTuple<int32, int32>>& CollisionPairs) { UE_LOG(LogPBDRigidsSolverSolver, Verbose, TEXT("PBDRigidsSolver::DisableCollisionsCallback()")); for (int CallbackIndex = 0; CallbackIndex < Callbacks.Num(); CallbackIndex++) { if (Callbacks[CallbackIndex] != nullptr && Callbacks[CallbackIndex]->IsSimulating()) { Callbacks[CallbackIndex]->DisableCollisionsCallback(CollisionPairs); } } } void PBDRigidsSolver::StartFrameCallback(const float Dt, const float Time) { UE_LOG(LogPBDRigidsSolverSolver, Verbose, TEXT("PBDRigidsSolver::StartFrameCallback()")); for (int CallbackIndex = 0; CallbackIndex < Callbacks.Num(); CallbackIndex++) { if (Callbacks[CallbackIndex] != nullptr) { Callbacks[CallbackIndex]->StartFrameCallback(Dt, Time); } // @todo: This data should be pushed; not pulled if (Callbacks[CallbackIndex] != nullptr && Callbacks[CallbackIndex]->IsSimulating()) { Callbacks[CallbackIndex]->UpdateKinematicBodiesCallback(MEvolution->Particles(), Dt, Time, KinematicProxies[CallbackIndex]); } } } void PBDRigidsSolver::EndFrameCallback(const float EndFrame) { UE_LOG(LogPBDRigidsSolverSolver, Verbose, TEXT("PBDRigidsSolver::EndFrameCallback()")); for (int CallbackIndex = 0; CallbackIndex < Callbacks.Num(); CallbackIndex++) { if (Callbacks[CallbackIndex] != nullptr && Callbacks[CallbackIndex]->IsSimulating()) { Callbacks[CallbackIndex]->EndFrameCallback(EndFrame); } } } void PBDRigidsSolver::KinematicUpdateCallback(PBDRigidsSolver::FParticlesType& Particles, const float Dt, const float Time) { UE_LOG(LogPBDRigidsSolverSolver, Verbose, TEXT("PBDRigidsSolver::KinematicUpdateCallback()")); SCOPE_CYCLE_COUNTER(STAT_KinematicUpdate); PhysicsParallelFor(KinematicProxies.Num(), [&](int32 i) { FKinematicProxy& KinematicProxy = KinematicProxies[i]; for (int32 ProxyIndex = 0; ProxyIndex < KinematicProxy.Ids.Num(); ++ProxyIndex) { const int32 Index = KinematicProxy.Ids[ProxyIndex]; if (Index < 0 || Particles.InvM(Index) != 0 || Particles.Disabled(Index)) { continue; } Particles.X(Index) = KinematicProxy.Position[ProxyIndex]; Particles.R(Index) = KinematicProxy.Rotation[ProxyIndex]; Particles.V(Index) = (KinematicProxy.NextPosition[ProxyIndex] - KinematicProxy.Position[ProxyIndex]) / Dt; TRotation<float, 3> Delta = KinematicProxy.NextRotation[ProxyIndex] * KinematicProxy.Rotation[ProxyIndex].Inverse(); TVector<float, 3> Axis; float Angle; Delta.ToAxisAndAngle(Axis, Angle); Particles.W(Index) = Axis * Angle / Dt; } }); } void PBDRigidsSolver::AddConstraintCallback(PBDRigidsSolver::FParticlesType& Particles, const float Time, const int32 Island) { UE_LOG(LogPBDRigidsSolverSolver, Verbose, TEXT("PBDRigidsSolver::AddConstraintCallback()")); for (int CallbackIndex = 0; CallbackIndex < Callbacks.Num(); CallbackIndex++) { if (Callbacks[CallbackIndex] != nullptr && Callbacks[CallbackIndex]->IsSimulating()) { Callbacks[CallbackIndex]->AddConstraintCallback(Particles, Time, Island); } } } void PBDRigidsSolver::AddForceCallback(PBDRigidsSolver::FParticlesType& Particles, const float Dt, const int32 Index) { // @todo : The index based callbacks need to change. This should be based on the indices // managed by the specific Callback. UE_LOG(LogPBDRigidsSolverSolver, Verbose, TEXT("PBDRigidsSolver::AddForceCallback()")); Chaos::PerParticleGravity<float, 3>(Chaos::TVector<float, 3>(0, 0, -1), 980.0).Apply(Particles, Dt, Index); } void PBDRigidsSolver::CollisionContactsCallback(PBDRigidsSolver::FParticlesType& Particles, PBDRigidsSolver::FCollisionConstraintsType& CollisionConstraints) { float CurrentTime = MTime; if (CurrentTime == 0.f) { CollisionData.TimeCreated = CurrentTime; CollisionData.NumCollisions = 0; CollisionData.CollisionDataArray.SetNum(MaxCollisionDataSize); } else { if (CurrentTime - CollisionData.TimeCreated > CollisionDataTimeWindow) { CollisionData.TimeCreated = CurrentTime; CollisionData.NumCollisions = 0; CollisionData.CollisionDataArray.Empty(MaxCollisionDataSize); CollisionData.CollisionDataArray.SetNum(MaxCollisionDataSize); } } const TArray<Chaos::TPBDCollisionConstraint<float, 3>::FRigidBodyContactConstraint>& AllConstraintsArray = CollisionConstraints.GetAllConstraints(); if (AllConstraintsArray.Num() > 0) { // Only process the constraints with AccumulatedImpulse != 0 TArray<Chaos::TPBDCollisionConstraint<float, 3>::FRigidBodyContactConstraint> ConstraintsArray; FBox BoundingBox(ForceInitToZero); for (int32 Idx = 0; Idx < AllConstraintsArray.Num(); ++Idx) { if (!AllConstraintsArray[Idx].AccumulatedImpulse.IsZero() && AllConstraintsArray[Idx].Phi < 0.f) { if (ensure(FMath::IsFinite(AllConstraintsArray[Idx].Location.X) && FMath::IsFinite(AllConstraintsArray[Idx].Location.Y) && FMath::IsFinite(AllConstraintsArray[Idx].Location.Z))) { ConstraintsArray.Add(AllConstraintsArray[Idx]); BoundingBox += AllConstraintsArray[Idx].Location; } } } if (ConstraintsArray.Num() > 0) { if (DoCollisionDataSpatialHash) { if (CollisionDataSpatialHashRadius > 0.0 && (BoundingBox.GetExtent().X > 0.0 || BoundingBox.GetExtent().Y > 0.0 || BoundingBox.GetExtent().Z > 0.0)) { // Spatial hash the constraints TMultiMap<int32, int32> HashTableMap; ComputeHashTable(ConstraintsArray, BoundingBox, HashTableMap, CollisionDataSpatialHashRadius); TArray<int32> UsedCellsArray; HashTableMap.GetKeys(UsedCellsArray); for (int32 IdxCell = 0; IdxCell < UsedCellsArray.Num(); ++IdxCell) { TArray<int32> ConstraintsInCellArray; HashTableMap.MultiFind(UsedCellsArray[IdxCell], ConstraintsInCellArray); int32 NumConstraintsToGetFromCell = FMath::Min(MaxCollisionPerCell, ConstraintsInCellArray.Num()); for (int32 IdxConstraint = 0; IdxConstraint < NumConstraintsToGetFromCell; ++IdxConstraint) { const Chaos::TPBDCollisionConstraint<float, 3>::FRigidBodyContactConstraint& Constraint = ConstraintsArray[ConstraintsInCellArray[IdxConstraint]]; TCollisionData<float, 3> CollisionDataItem{ CurrentTime, Constraint.Location, Constraint.AccumulatedImpulse, Constraint.Normal, Particles.V(Constraint.ParticleIndex), Particles.V(Constraint.LevelsetIndex), Particles.M(Constraint.ParticleIndex), Particles.M(Constraint.LevelsetIndex), Constraint.ParticleIndex, Constraint.LevelsetIndex }; int32 Idx = CollisionData.NumCollisions % MaxCollisionDataSize; CollisionData.CollisionDataArray[Idx] = CollisionDataItem; CollisionData.NumCollisions++; } } } } else { for (int32 IdxConstraint = 0; IdxConstraint < ConstraintsArray.Num(); ++IdxConstraint) { const Chaos::TPBDCollisionConstraint<float, 3>::FRigidBodyContactConstraint& Constraint = ConstraintsArray[IdxConstraint]; TCollisionData<float, 3> CollisionDataItem{ CurrentTime, Constraint.Location, Constraint.AccumulatedImpulse, Constraint.Normal, Particles.V(Constraint.ParticleIndex), Particles.V(Constraint.LevelsetIndex), Particles.M(Constraint.ParticleIndex), Particles.M(Constraint.LevelsetIndex), Constraint.ParticleIndex, Constraint.LevelsetIndex }; int32 Idx = CollisionData.NumCollisions % MaxCollisionDataSize; CollisionData.CollisionDataArray[Idx] = CollisionDataItem; CollisionData.NumCollisions++; } } } } } void PBDRigidsSolver::BreakingCallback(PBDRigidsSolver::FParticlesType& Particles) { } void PBDRigidsSolver::TrailingCallback(PBDRigidsSolver::FParticlesType& Particles) { float CurrentTime = MTime; if (CurrentTime == 0.f) { TrailingData.TimeLastUpdated = 0.f; TrailingData.TrailingDataSet.Empty(MaxTrailingDataSize); } else { if (CurrentTime - TrailingData.TimeLastUpdated > TrailingDataTimeWindow) { TrailingData.TimeLastUpdated = CurrentTime; } else { return; } } const float TrailingMinSpeedThresholdSquared = TrailingMinSpeedThreshold * TrailingMinSpeedThreshold; if (Particles.Size() > 0) { // Remove Sleeping, Disabled or too slow particles from TrailingData.TrailingDataSet if (TrailingData.TrailingDataSet.Num() > 0) { FTrailingDataSet ParticlesToRemoveFromTrailingSet; for (auto& TrailingDataItem : TrailingData.TrailingDataSet) { int32 ParticleIndex = TrailingDataItem.ParticleIndex; if (Particles.Sleeping(ParticleIndex) || Particles.Disabled(ParticleIndex) || Particles.V(ParticleIndex).SizeSquared() < TrailingMinSpeedThresholdSquared) { ParticlesToRemoveFromTrailingSet.Add(TrailingDataItem); } } TrailingData.TrailingDataSet = TrailingData.TrailingDataSet.Difference(TrailingData.TrailingDataSet.Intersect(ParticlesToRemoveFromTrailingSet)); } for (uint32 IdxParticle = 0; IdxParticle < Particles.Size(); ++IdxParticle) { if (TrailingData.TrailingDataSet.Num() >= MaxTrailingDataSize) { break; } if (!Particles.Disabled(IdxParticle) && !Particles.Sleeping(IdxParticle) && Particles.InvM(IdxParticle) != 0.f) { if (Particles.Geometry(IdxParticle)->HasBoundingBox()) { TVector<float, 3> Location = Particles.X(IdxParticle); TVector<float, 3> Velocity = Particles.V(IdxParticle); TVector<float, 3> AngularVelocity = Particles.W(IdxParticle); float Mass = Particles.M(IdxParticle); if (ensure(FMath::IsFinite(Location.X) && FMath::IsFinite(Location.Y) && FMath::IsFinite(Location.Z) && FMath::IsFinite(Velocity.X) && FMath::IsFinite(Velocity.Y) && FMath::IsFinite(Velocity.Z) && FMath::IsFinite(AngularVelocity.X) && FMath::IsFinite(AngularVelocity.Y) && FMath::IsFinite(AngularVelocity.Z))) { TBox<float, 3> BoundingBox = Particles.Geometry(IdxParticle)->BoundingBox(); TVector<float, 3> Extents = BoundingBox.Extents(); float ExtentMax = Extents[BoundingBox.LargestAxis()]; int32 SmallestAxis; if (Extents[0] < Extents[1] && Extents[0] < Extents[2]) { SmallestAxis = 0; } else if (Extents[1] < Extents[2]) { SmallestAxis = 1; } else { SmallestAxis = 2; } float ExtentMin = Extents[SmallestAxis]; float Volume = Extents[0] * Extents[1] * Extents[2]; float SpeedSquared = Velocity.SizeSquared(); if (SpeedSquared > TrailingMinSpeedThresholdSquared && Volume > TrailingMinVolumeThreshold) { TTrailingData<float, 3> TrailingDataItem{ CurrentTime, Location, ExtentMin, ExtentMax, Velocity, AngularVelocity, Mass, (int32)IdxParticle }; if (!TrailingData.TrailingDataSet.Contains(TrailingDataItem)) { TrailingData.TrailingDataSet.Add(TrailingDataItem); } else { FSetElementId Id = TrailingData.TrailingDataSet.FindId(TrailingDataItem); TrailingData.TrailingDataSet[Id].Location = Location; TrailingData.TrailingDataSet[Id].Velocity = Velocity; TrailingData.TrailingDataSet[Id].AngularVelocity = AngularVelocity; } } } } } } } } } #endif
0
0.901067
1
0.901067
game-dev
MEDIA
0.677552
game-dev
0.901713
1
0.901713
folgerwang/UnrealEngine
2,187
Engine/Source/Editor/SkeletonEditor/Public/ISkeletonEditorModule.h
// Copyright 1998-2019 Epic Games, Inc. All Rights Reserved. #pragma once #include "CoreMinimal.h" #include "Widgets/SWidget.h" #include "Modules/ModuleInterface.h" #include "Framework/Commands/UICommandList.h" #include "Framework/MultiBox/MultiBoxExtender.h" #include "Toolkits/AssetEditorToolkit.h" #include "ISkeletonEditor.h" #include "ISkeletonTree.h" #include "BlendProfilePicker.h" class IEditableSkeleton; class USkeleton; DECLARE_LOG_CATEGORY_EXTERN(LogSkeletonEditor, Log, All); class ISkeletonEditorModule : public IModuleInterface, public IHasMenuExtensibility, public IHasToolBarExtensibility { public: /** Creates a new skeleton editor instance */ virtual TSharedRef<ISkeletonEditor> CreateSkeletonEditor(const EToolkitMode::Type Mode, const TSharedPtr<IToolkitHost>& InitToolkitHost, class USkeleton* InSkeleton) = 0; /** Creates a new skeleton tree instance */ virtual TSharedRef<ISkeletonTree> CreateSkeletonTree(USkeleton* InSkeleton, const FSkeletonTreeArgs& InSkeletonTreeArgs) = 0; /** Creates a new skeleton tree instance */ virtual TSharedRef<ISkeletonTree> CreateSkeletonTree(const TSharedRef<IEditableSkeleton>& InEditableSkeleton, const FSkeletonTreeArgs& InSkeletonTreeArgs) = 0; /** Creates a new skeleton tree instance & registers a tab factory with the supplied tab factories */ virtual TSharedRef<class FWorkflowTabFactory> CreateSkeletonTreeTabFactory(const TSharedRef<class FWorkflowCentricApplication>& InHostingApp, const TSharedRef<ISkeletonTree>& InSkeletonTree) = 0; /** Creates a new editable skeleton instance */ virtual TSharedRef<IEditableSkeleton> CreateEditableSkeleton(USkeleton* InSkeleton) = 0; /** Creates a new blend profile picker instance */ virtual TSharedRef<SWidget> CreateBlendProfilePicker(USkeleton* InSkeleton, const FBlendProfilePickerArgs& InArgs = FBlendProfilePickerArgs()) = 0; /** Get all toolbar extenders */ DECLARE_DELEGATE_RetVal_TwoParams(TSharedRef<FExtender>, FSkeletonEditorToolbarExtender, const TSharedRef<FUICommandList> /*InCommandList*/, TSharedRef<ISkeletonEditor> /*InSkeletonEditor*/); virtual TArray<FSkeletonEditorToolbarExtender>& GetAllSkeletonEditorToolbarExtenders() = 0; };
0
0.883161
1
0.883161
game-dev
MEDIA
0.56509
game-dev
0.551548
1
0.551548
CryptoMorin/XSeries
8,007
core/src/main/java/com/cryptomorin/xseries/XAttribute.java
/* * The MIT License (MIT) * * Copyright (c) 2025 Crypto Morin * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.cryptomorin.xseries; import com.cryptomorin.xseries.base.XModule; import com.cryptomorin.xseries.base.XRegistry; import com.cryptomorin.xseries.base.annotations.XInfo; import org.bukkit.NamespacedKey; import org.bukkit.Registry; import org.bukkit.attribute.Attribute; import org.bukkit.attribute.AttributeModifier; import org.bukkit.inventory.EquipmentSlot; import org.bukkit.inventory.EquipmentSlotGroup; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Unmodifiable; import java.util.Collection; import java.util.Objects; import java.util.Optional; import java.util.UUID; public final class XAttribute extends XModule<XAttribute, Attribute> { public static final XRegistry<XAttribute, Attribute> REGISTRY = new XRegistry<>(Attribute.class, XAttribute.class, () -> Registry.ATTRIBUTE, XAttribute::new, XAttribute[]::new); public static final XAttribute MAX_HEALTH = std(/* v1.20.3+ */ "max_health", "generic.max_health"), FOLLOW_RANGE = std(/* v1.20.3+ */ "follow_range", "generic.follow_range"), KNOCKBACK_RESISTANCE = std(/* v1.20.3+ */ "knockback_resistance", "generic.knockback_resistance"), MOVEMENT_SPEED = std(/* v1.20.3+ */ "movement_speed", "generic.movement_speed"), FLYING_SPEED = std(/* v1.20.3+ */ "flying_speed", "generic.flying_speed"), ATTACK_DAMAGE = std(/* v1.20.3+ */ "attack_damage", "generic.attack_damage"), ATTACK_KNOCKBACK = std(/* v1.20.3+ */ "attack_knockback", "generic.attack_knockback"), ATTACK_SPEED = std(/* v1.20.3+ */ "attack_speed", "generic.attack_speed"), ARMOR = std(/* v1.20.3+ */ "armor", "generic.armor"), ARMOR_TOUGHNESS = std(/* v1.20.3+ */ "armor_toughness", "generic.armor_toughness"), FALL_DAMAGE_MULTIPLIER = std(/* v1.20.3+ */ "fall_damage_multiplier", "generic.fall_damage_multiplier"), LUCK = std(/* v1.20.3+ */ "luck", "generic.luck"), MAX_ABSORPTION = std(/* v1.20.3+ */ "max_absorption", "generic.max_absorption"), SAFE_FALL_DISTANCE = std(/* v1.20.3+ */ "safe_fall_distance", "generic.safe_fall_distance"), SCALE = std(/* v1.20.3+ */ "scale", "generic.scale"), STEP_HEIGHT = std(/* v1.20.3+ */ "step_height", "generic.step_height"), GRAVITY = std(/* v1.20.3+ */ "gravity", "generic.gravity"), JUMP_STRENGTH = std(/* v1.20.3+ */ "jump_strength", "generic.jump_strength", /* 1.13+? */ "horse.jump_strength"), BURNING_TIME = std(/* v1.20.3+ */ "burning_time", "generic.burning_time"), EXPLOSION_KNOCKBACK_RESISTANCE = std(/* v1.20.3+ */ "explosion_knockback_resistance", "generic.explosion_knockback_resistance"), MOVEMENT_EFFICIENCY = std(/* v1.20.3+ */ "movement_efficiency", "generic.movement_efficiency"), OXYGEN_BONUS = std(/* v1.20.3+ */ "oxygen_bonus", "generic.oxygen_bonus"), WATER_MOVEMENT_EFFICIENCY = std(/* v1.20.3+ */ "water_movement_efficiency", "generic.water_movement_efficiency"), TEMPT_RANGE = std(/* v1.20.3+ */ "tempt_range", "generic.tempt_range"), BLOCK_INTERACTION_RANGE = std(/* v1.20.3+ */ "block_interaction_range", "player.block_interaction_range"), ENTITY_INTERACTION_RANGE = std(/* v1.20.3+ */ "entity_interaction_range", "player.entity_interaction_range"), BLOCK_BREAK_SPEED = std(/* v1.20.3+ */ "block_break_speed", "player.block_break_speed"), MINING_EFFICIENCY = std(/* v1.20.3+ */ "mining_efficiency", "player.mining_efficiency"), SNEAKING_SPEED = std(/* v1.20.3+ */ "sneaking_speed", "player.sneaking_speed"), SUBMERGED_MINING_SPEED = std(/* v1.20.3+ */ "submerged_mining_speed", "player.submerged_mining_speed"), SWEEPING_DAMAGE_RATIO = std(/* v1.20.3+ */ "sweeping_damage_ratio", "player.sweeping_damage_ratio"), SPAWN_REINFORCEMENTS = std(/* v1.20.3+ */ "spawn_reinforcements", "zombie.spawn_reinforcements"); @XInfo(since = "1.21.6") public static final XAttribute CAMERA_DISTANCE = std("camera_distance"), WAYPOINT_TRANSMIT_RANGE = std("waypoint_transmit_range"), WAYPOINT_RECEIVE_RANGE = std("waypoint_receive_range"); private static final boolean SUPPORTS_MODERN_MODIFIERS; static { // public AttributeModifier(NamespacedKey key, double amount, AttributeModifier.Operation operation, EquipmentSlotGroup slot) boolean supportsModernModifiers; try { // noinspection UnstableApiUsage AttributeModifier.class.getConstructor( org.bukkit.NamespacedKey.class, double.class, AttributeModifier.Operation.class, org.bukkit.inventory.EquipmentSlotGroup.class ); supportsModernModifiers = true; } catch (NoSuchMethodException | NoClassDefFoundError ignored) { supportsModernModifiers = false; } SUPPORTS_MODERN_MODIFIERS = supportsModernModifiers; } private XAttribute(Attribute attribute, String[] names) { super(attribute, names); } static { REGISTRY.discardMetadata(); } /** * Creates a new {@link AttributeModifier}. * * @param slot when null, defaults to {@link org.bukkit.inventory.EquipmentSlotGroup#ANY} */ @SuppressWarnings({"removal", "UnstableApiUsage"}) public static AttributeModifier createModifier(@NotNull String key, double amount, @NotNull AttributeModifier.Operation operation, @Nullable EquipmentSlot slot) { Objects.requireNonNull(key, "Key is null"); Objects.requireNonNull(operation, "Operation is null"); if (SUPPORTS_MODERN_MODIFIERS) { NamespacedKey ns = Objects.requireNonNull(NamespacedKey.fromString(key), () -> "Invalid namespace: " + key); return new AttributeModifier(ns, amount, operation, (slot == null ? EquipmentSlotGroup.ANY : slot.getGroup())); } else { return new AttributeModifier(UUID.randomUUID(), key, amount, operation, slot); } } public static XAttribute of(Attribute attribute) { return REGISTRY.getByBukkitForm(attribute); } public static Optional<XAttribute> of(String attribute) { return REGISTRY.getByName(attribute); } /** * @deprecated Use {@link #getValues()} instead. */ @Deprecated public static XAttribute[] values() { return REGISTRY.values(); } @NotNull @Unmodifiable public static Collection<XAttribute> getValues() { return REGISTRY.getValues(); } private static XAttribute std(String... names) { return REGISTRY.std(names); } }
0
0.75046
1
0.75046
game-dev
MEDIA
0.924157
game-dev
0.815525
1
0.815525
LeagueSandbox/GameServer
1,404
GameServerLib/Chatbox/Commands/HotReloadCommand.cs
using LeagueSandbox.GameServer.GameObjects; using LeagueSandbox.GameServer.GameObjects.SpellNS; namespace LeagueSandbox.GameServer.Chatbox.Commands { public class HotReloadCommand : ChatCommandBase { public override string Command => "hotreload"; public override string Syntax => $"{Command} 0 (disable) / 1 (enable)"; public HotReloadCommand(ChatCommandManager chatCommandManager, Game game) : base(chatCommandManager, game) { } public override void Execute(int userId, bool hasReceivedArguments, string arguments = "") { var split = arguments.ToLower().Split(' '); if (split.Length < 2 || !byte.TryParse(split[1], out byte input) || input > 1) { ChatCommandManager.SendDebugMsgFormatted(DebugMsgType.SYNTAXERROR); ShowSyntax(); } else { if (input == 1) { Game.EnableHotReload(true); ChatCommandManager.SendDebugMsgFormatted(DebugMsgType.INFO, "Scripts hot reload enabled."); } else { Game.EnableHotReload(false); ChatCommandManager.SendDebugMsgFormatted(DebugMsgType.INFO, "Scripts hot reload disabled."); } } } } }
0
0.768877
1
0.768877
game-dev
MEDIA
0.812781
game-dev
0.776941
1
0.776941
Darkrp-community/OpenKeep
5,322
code/modules/research/xenobiology/crossbreeding/industrial.dm
/* Industrial extracts: Slowly consume plasma, produce items with it. */ /obj/item/slimecross/industrial name = "industrial extract" desc = "" effect = "industrial" icon_state = "industrial_still" var/plasmarequired = 2 //Units of plasma required to be consumed to produce item. var/itempath = /obj/item //The item produced by the extract. var/plasmaabsorbed = 0 //Units of plasma aborbed by the extract already. Absorbs at a rate of 2u/obj tick. var/itemamount = 1 //How many items to spawn /obj/item/slimecross/industrial/examine(mob/user) . = ..() . += "It currently has [plasmaabsorbed] units of plasma floating inside the outer shell, out of [plasmarequired] units." /obj/item/slimecross/industrial/proc/do_after_spawn(obj/item/spawned) return /obj/item/slimecross/industrial/Initialize() . = ..() create_reagents(100, INJECTABLE | DRAWABLE) START_PROCESSING(SSobj,src) /obj/item/slimecross/industrial/Destroy() STOP_PROCESSING(SSobj,src) return ..() /obj/item/slimecross/industrial/process() var/IsWorking = FALSE if(reagents.has_reagent(/datum/reagent/toxin/plasma,amount = 2) && plasmarequired > 1) //Can absorb as much as 2 IsWorking = TRUE reagents.remove_reagent(/datum/reagent/toxin/plasma,2) plasmaabsorbed += 2 else if(reagents.has_reagent(/datum/reagent/toxin/plasma,amount = 1)) //Can absorb as little as 1 IsWorking = TRUE reagents.remove_reagent(/datum/reagent/toxin/plasma,1) plasmaabsorbed += 1 if(plasmaabsorbed >= plasmarequired) playsound(src, 'sound/blank.ogg', 50, TRUE) plasmaabsorbed -= plasmarequired for(var/i = 0, i < itemamount, i++) do_after_spawn(new itempath(get_turf(src))) else if(IsWorking) playsound(src, 'sound/blank.ogg', 5, TRUE) if(IsWorking) icon_state = "industrial" else icon_state = "industrial_still" /obj/item/slimecross/industrial/grey colour = "grey" effect_desc = "" itempath = /obj/item/reagent_containers/food/snacks/monkeycube itemamount = 5 /obj/item/slimecross/industrial/orange colour = "orange" effect_desc = "" plasmarequired = 6 itempath = /obj/item/lighter/slime /obj/item/slimecross/industrial/purple colour = "purple" effect_desc = "" plasmarequired = 5 itempath = /obj/item/slimecrossbeaker/autoinjector/regenpack /obj/item/slimecross/industrial/blue colour = "blue" effect_desc = "" plasmarequired = 10 itempath = /obj/item/extinguisher /obj/item/slimecross/industrial/metal colour = "metal" effect_desc = "" plasmarequired = 3 itempath = /obj/item/stack/sheet/metal/ten /obj/item/slimecross/industrial/darkpurple colour = "dark purple" effect_desc = "" plasmarequired = 10 itempath = /obj/item/stack/sheet/mineral/plasma /obj/item/slimecross/industrial/darkblue colour = "dark blue" effect_desc = "" plasmarequired = 6 itempath = /obj/item/slimepotion/fireproof /obj/item/slimecross/industrial/darkblue/do_after_spawn(obj/item/spawned) var/obj/item/slimepotion/fireproof/potion = spawned if(istype(potion)) potion.uses = 1 /obj/item/slimecross/industrial/silver colour = "silver" effect_desc = "" plasmarequired = 1 //Item picked below. /obj/item/slimecross/industrial/silver/process() itempath = pick(list(get_random_food(), get_random_drink())) ..() /obj/item/slimecross/industrial/bluespace colour = "bluespace" effect_desc = "" plasmarequired = 7 itempath = /obj/item/stack/ore/bluespace_crystal/artificial /obj/item/slimecross/industrial/cerulean colour = "cerulean" effect_desc = "" plasmarequired = 5 itempath = /obj/item/slimepotion/enhancer /obj/item/slimecross/industrial/pyrite colour = "pyrite" effect_desc = "" plasmarequired = 2 itempath = /obj/item/toy/crayon/spraycan /obj/item/slimecross/industrial/red colour = "red" effect_desc = "" plasmarequired = 5 itempath = /obj/item/slimecrossbeaker/bloodpack /obj/item/slimecross/industrial/green colour = "green" effect_desc = "" plasmarequired = 7 itempath = /obj/item/slimecrossbeaker/autoinjector/slimejelly /obj/item/slimecross/industrial/pink colour = "pink" effect_desc = "" plasmarequired = 6 itempath = /obj/item/slimecrossbeaker/autoinjector/peaceandlove /obj/item/slimecross/industrial/gold colour = "gold" effect_desc = "" plasmarequired = 10 /obj/item/slimecross/industrial/gold/process() itempath = pick(/obj/item/coin/silver, /obj/item/coin/iron, /obj/item/coin/gold, /obj/item/coin/diamond, /obj/item/coin/plasma, /obj/item/coin/uranium) ..() /obj/item/slimecross/industrial/oil colour = "oil" effect_desc = "" plasmarequired = 4 itempath = /obj/item/grenade/iedcasing /obj/item/slimecross/industrial/black //What does this have to do with black slimes? No clue! Fun, though colour = "black" effect_desc = "" plasmarequired = 6 itempath = /obj/item/storage/fancy/cigarettes/cigpack_xeno /obj/item/slimecross/industrial/lightpink colour = "light pink" effect_desc = "" plasmarequired = 3 itempath = /obj/item/storage/fancy/heart_box /obj/item/slimecross/industrial/adamantine colour = "adamantine" effect_desc = "" plasmarequired = 10 itempath = /obj/item/stack/sheet/mineral/adamantine /obj/item/slimecross/industrial/rainbow colour = "rainbow" effect_desc = "" plasmarequired = 5 //Item picked below. /obj/item/slimecross/industrial/rainbow/process() itempath = pick(subtypesof(/obj/item/slime_extract)) ..()
0
0.762858
1
0.762858
game-dev
MEDIA
0.997975
game-dev
0.63143
1
0.63143
Interkarma/daggerfall-unity
7,212
Assets/Scripts/Game/LevitateMotor.cs
// Project: Daggerfall Unity // Copyright: Copyright (C) 2009-2023 Daggerfall Workshop // Web Site: http://www.dfworkshop.net // License: MIT License (http://www.opensource.org/licenses/mit-license.php) // Source Code: https://github.com/Interkarma/daggerfall-unity // Original Author: Gavin Clayton (interkarma@dfworkshop.net) // Contributors: // // Notes: // using System; using UnityEngine; namespace DaggerfallWorkshop.Game { /// <summary> /// A temporary replacement motor for player levitation and swimming. /// </summary> public class LevitateMotor : MonoBehaviour { const float standardLevitateMoveSpeed = 4.0f; bool playerLevitating = false; bool playerSwimming = false; PlayerMotor playerMotor; PlayerSpeedChanger speedChanger; PlayerGroundMotor groundMotor; ClimbingMotor climbingMotor; Camera playerCamera; float levitateMoveSpeed = standardLevitateMoveSpeed; float moveSpeed = standardLevitateMoveSpeed; Vector3 moveDirection = Vector3.zero; public bool IsLevitating { get { return playerLevitating; } set { SetLevitating(value); } } public bool IsSwimming { get { return playerSwimming; } set { SetSwimming(value); } } public float LevitateMoveSpeed { get { return levitateMoveSpeed; } set { levitateMoveSpeed = value; } } private void Start() { playerMotor = GetComponent<PlayerMotor>(); groundMotor = GetComponent<PlayerGroundMotor>(); speedChanger = GetComponent<PlayerSpeedChanger>(); climbingMotor = GetComponent<ClimbingMotor>(); playerCamera = GameManager.Instance.MainCamera; } private void Update() { if (!playerMotor || !playerCamera || (!playerLevitating && !playerSwimming)) return; // Cancel levitate movement if player is paralyzed if (GameManager.Instance.PlayerEntity.IsParalyzed) return; float inputX = InputManager.Instance.Horizontal; float inputY = InputManager.Instance.Vertical; if (inputX != 0.0f || inputY != 0.0f) { float inputModifyFactor = (inputX != 0.0f && inputY != 0.0f && playerMotor.limitDiagonalSpeed) ? .7071f : 1.0f; AddMovement(playerCamera.transform.TransformDirection(new Vector3(inputX * inputModifyFactor, 0, inputY * inputModifyFactor))); } // Up/down Vector3 upDownVector = new Vector3 (0, 0, 0); bool overEncumbered = (GameManager.Instance.PlayerEntity.CarriedWeight * 4 > 250) && !playerLevitating && !GameManager.Instance.PlayerEntity.GodMode; if (playerSwimming && overEncumbered && !climbingMotor.IsClimbing && !GameManager.Instance.PlayerEntity.IsWaterWalking) upDownVector += Vector3.down; else if (InputManager.Instance.HasAction(InputManager.Actions.Jump) || InputManager.Instance.HasAction(InputManager.Actions.FloatUp)) upDownVector += Vector3.up; else if (InputManager.Instance.HasAction(InputManager.Actions.Crouch) || InputManager.Instance.HasAction(InputManager.Actions.FloatDown)) upDownVector += Vector3.down; AddMovement(upDownVector, true); // Execute movement if (moveDirection == Vector3.zero) { // Hack to make sure that the player can get pushed by moving objects if he's not moving const float pos = 0.0001f; groundMotor.MoveWithMovingPlatform(Vector3.up * pos); groundMotor.MoveWithMovingPlatform(Vector3.down * pos); groundMotor.MoveWithMovingPlatform(Vector3.left * pos); groundMotor.MoveWithMovingPlatform(Vector3.right * pos); groundMotor.MoveWithMovingPlatform(Vector3.forward * pos); groundMotor.MoveWithMovingPlatform(Vector3.back * pos); } groundMotor.MoveWithMovingPlatform(moveDirection); moveDirection = Vector3.zero; } void AddMovement(Vector3 direction, bool upOrDown = false) { // No up or down movement while swimming without using a float up/float down key, levitating while swimming, or sinking from encumbrance if (!upOrDown && playerSwimming && !playerLevitating) direction.y = 0; if (playerSwimming && GameManager.Instance.PlayerEntity.IsWaterWalking) { // Swimming with water walking on makes player move at normal speed in water moveSpeed = GameManager.Instance.PlayerMotor.Speed; moveDirection += direction * moveSpeed; return; } else if (playerSwimming && !playerLevitating) { // Do not allow player to swim up out of water, as he would immediately be pulled back in, making jerky movement and playing the splash sound repeatedly if ((direction.y > 0) && (playerMotor.controller.transform.position.y + (50 * MeshReader.GlobalScale) - 0.93f) >= (GameManager.Instance.PlayerEnterExit.blockWaterLevel * -1 * MeshReader.GlobalScale) && !playerLevitating) direction.y = 0; // There's a fixed speed for up/down movement in classic (use moveSpeed = 2 here to replicate) float baseSpeed = speedChanger.GetBaseSpeed(); moveSpeed = speedChanger.GetSwimSpeed(baseSpeed); } moveDirection += direction * moveSpeed; // Reset to levitate speed in case it has been changed by swimming moveSpeed = levitateMoveSpeed; } void SetLevitating(bool levitating) { // Must have PlayerMotor reference if (!playerMotor) return; // Start levitating if (!playerLevitating && levitating) { playerMotor.CancelMovement = true; playerLevitating = true; return; } // Stop levitating if (playerLevitating && !levitating) { playerMotor.CancelMovement = true; playerLevitating = false; return; } } void SetSwimming(bool swimming) { // Must have PlayerMotor reference if (!playerMotor) return; // Start swimming if (!playerSwimming && swimming) { playerMotor.CancelMovement = true; playerSwimming = true; return; } // Stop swimming if (playerSwimming && !swimming) { playerMotor.CancelMovement = true; playerSwimming = false; return; } } } }
0
0.791265
1
0.791265
game-dev
MEDIA
0.977145
game-dev
0.896571
1
0.896571
ElasticSea/unity-fracture
10,020
Assets/Tools/PostProcessing/Runtime/Models/ColorGradingModel.cs
using System; namespace UnityEngine.PostProcessing { [Serializable] public class ColorGradingModel : PostProcessingModel { public enum Tonemapper { None, /// <summary> /// ACES Filmic reference tonemapper. /// </summary> ACES, /// <summary> /// Neutral tonemapper (based off John Hable's & Jim Hejl's work). /// </summary> Neutral } [Serializable] public struct TonemappingSettings { [Tooltip("Tonemapping algorithm to use at the end of the color grading process. Use \"Neutral\" if you need a customizable tonemapper or \"Filmic\" to give a standard filmic look to your scenes.")] public Tonemapper tonemapper; // Neutral settings [Range(-0.1f, 0.1f)] public float neutralBlackIn; [Range(1f, 20f)] public float neutralWhiteIn; [Range(-0.09f, 0.1f)] public float neutralBlackOut; [Range(1f, 19f)] public float neutralWhiteOut; [Range(0.1f, 20f)] public float neutralWhiteLevel; [Range(1f, 10f)] public float neutralWhiteClip; public static TonemappingSettings defaultSettings { get { return new TonemappingSettings { tonemapper = Tonemapper.Neutral, neutralBlackIn = 0.02f, neutralWhiteIn = 10f, neutralBlackOut = 0f, neutralWhiteOut = 10f, neutralWhiteLevel = 5.3f, neutralWhiteClip = 10f }; } } } [Serializable] public struct BasicSettings { [Tooltip("Adjusts the overall exposure of the scene in EV units. This is applied after HDR effect and right before tonemapping so it won't affect previous effects in the chain.")] public float postExposure; [Range(-100f, 100f), Tooltip("Sets the white balance to a custom color temperature.")] public float temperature; [Range(-100f, 100f), Tooltip("Sets the white balance to compensate for a green or magenta tint.")] public float tint; [Range(-180f, 180f), Tooltip("Shift the hue of all colors.")] public float hueShift; [Range(0f, 2f), Tooltip("Pushes the intensity of all colors.")] public float saturation; [Range(0f, 2f), Tooltip("Expands or shrinks the overall range of tonal values.")] public float contrast; public static BasicSettings defaultSettings { get { return new BasicSettings { postExposure = 0f, temperature = 0f, tint = 0f, hueShift = 0f, saturation = 1f, contrast = 1f, }; } } } [Serializable] public struct ChannelMixerSettings { public Vector3 red; public Vector3 green; public Vector3 blue; [HideInInspector] public int currentEditingChannel; // Used only in the editor public static ChannelMixerSettings defaultSettings { get { return new ChannelMixerSettings { red = new Vector3(1f, 0f, 0f), green = new Vector3(0f, 1f, 0f), blue = new Vector3(0f, 0f, 1f), currentEditingChannel = 0 }; } } } [Serializable] public struct LogWheelsSettings { [Trackball("GetSlopeValue")] public Color slope; [Trackball("GetPowerValue")] public Color power; [Trackball("GetOffsetValue")] public Color offset; public static LogWheelsSettings defaultSettings { get { return new LogWheelsSettings { slope = Color.clear, power = Color.clear, offset = Color.clear }; } } } [Serializable] public struct LinearWheelsSettings { [Trackball("GetLiftValue")] public Color lift; [Trackball("GetGammaValue")] public Color gamma; [Trackball("GetGainValue")] public Color gain; public static LinearWheelsSettings defaultSettings { get { return new LinearWheelsSettings { lift = Color.clear, gamma = Color.clear, gain = Color.clear }; } } } public enum ColorWheelMode { Linear, Log } [Serializable] public struct ColorWheelsSettings { public ColorWheelMode mode; [TrackballGroup] public LogWheelsSettings log; [TrackballGroup] public LinearWheelsSettings linear; public static ColorWheelsSettings defaultSettings { get { return new ColorWheelsSettings { mode = ColorWheelMode.Log, log = LogWheelsSettings.defaultSettings, linear = LinearWheelsSettings.defaultSettings }; } } } [Serializable] public struct CurvesSettings { public ColorGradingCurve master; public ColorGradingCurve red; public ColorGradingCurve green; public ColorGradingCurve blue; public ColorGradingCurve hueVShue; public ColorGradingCurve hueVSsat; public ColorGradingCurve satVSsat; public ColorGradingCurve lumVSsat; // Used only in the editor [HideInInspector] public int e_CurrentEditingCurve; [HideInInspector] public bool e_CurveY; [HideInInspector] public bool e_CurveR; [HideInInspector] public bool e_CurveG; [HideInInspector] public bool e_CurveB; public static CurvesSettings defaultSettings { get { return new CurvesSettings { master = new ColorGradingCurve(new AnimationCurve(new Keyframe(0f, 0f, 1f, 1f), new Keyframe(1f, 1f, 1f, 1f)), 0f, false, new Vector2(0f, 1f)), red = new ColorGradingCurve(new AnimationCurve(new Keyframe(0f, 0f, 1f, 1f), new Keyframe(1f, 1f, 1f, 1f)), 0f, false, new Vector2(0f, 1f)), green = new ColorGradingCurve(new AnimationCurve(new Keyframe(0f, 0f, 1f, 1f), new Keyframe(1f, 1f, 1f, 1f)), 0f, false, new Vector2(0f, 1f)), blue = new ColorGradingCurve(new AnimationCurve(new Keyframe(0f, 0f, 1f, 1f), new Keyframe(1f, 1f, 1f, 1f)), 0f, false, new Vector2(0f, 1f)), hueVShue = new ColorGradingCurve(new AnimationCurve(), 0.5f, true, new Vector2(0f, 1f)), hueVSsat = new ColorGradingCurve(new AnimationCurve(), 0.5f, true, new Vector2(0f, 1f)), satVSsat = new ColorGradingCurve(new AnimationCurve(), 0.5f, false, new Vector2(0f, 1f)), lumVSsat = new ColorGradingCurve(new AnimationCurve(), 0.5f, false, new Vector2(0f, 1f)), e_CurrentEditingCurve = 0, e_CurveY = true, e_CurveR = false, e_CurveG = false, e_CurveB = false }; } } } [Serializable] public struct Settings { public TonemappingSettings tonemapping; public BasicSettings basic; public ChannelMixerSettings channelMixer; public ColorWheelsSettings colorWheels; public CurvesSettings curves; public static Settings defaultSettings { get { return new Settings { tonemapping = TonemappingSettings.defaultSettings, basic = BasicSettings.defaultSettings, channelMixer = ChannelMixerSettings.defaultSettings, colorWheels = ColorWheelsSettings.defaultSettings, curves = CurvesSettings.defaultSettings }; } } } [SerializeField] Settings m_Settings = Settings.defaultSettings; public Settings settings { get { return m_Settings; } set { m_Settings = value; OnValidate(); } } public bool isDirty { get; internal set; } public RenderTexture bakedLut { get; internal set; } public override void Reset() { m_Settings = Settings.defaultSettings; OnValidate(); } public override void OnValidate() { isDirty = true; } } }
0
0.697239
1
0.697239
game-dev
MEDIA
0.675611
game-dev,graphics-rendering
0.753792
1
0.753792
Minecraft-LightLand/Youkai-Homecoming
2,043
src/main/java/dev/xkmc/youkaishomecoming/content/item/fluid/BottleTexture.java
package dev.xkmc.youkaishomecoming.content.item.fluid; import com.tterrag.registrate.providers.DataGenContext; import com.tterrag.registrate.providers.RegistrateItemModelProvider; import dev.xkmc.youkaishomecoming.init.YoukaisHomecoming; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.Ingredient; import net.minecraftforge.client.model.generators.ModelFile; import java.util.ArrayList; import java.util.List; public abstract class BottleTexture { private static List<BottleTexture> LIST = new ArrayList<>(); public final int index; public BottleTexture() { index = LIST.size(); LIST.add(this); } public static Ingredient replace(Ingredient ing) { for (var e : LIST) { if (ing.test(e.holder().asStack(1))) { return new SlipBottleIngredient(e.holder().source()).validate(); } } return ing; } public abstract IYHFluidHolder holder(); public abstract String bottleModel(); public static void buildBottleModel(DataGenContext<Item, SlipBottleItem> ctx, RegistrateItemModelProvider pvd) { var model = pvd.generated(ctx, pvd.modLoc("item/sake_bottle")); model.override() .predicate(YoukaisHomecoming.loc("slip"), 1 / 32f) .model(pvd.getBuilder(ctx.getName() + "_overlay") .parent(new ModelFile.UncheckedModelFile("item/generated")) .texture("layer0", pvd.modLoc("item/sake_bottle")) .texture("layer1", pvd.modLoc("item/sake_bottle_overlay"))) .end(); int n = LIST.size(); for (var e : LIST) { model.override() .predicate(YoukaisHomecoming.loc("bottle"), (e.index + 0.5f) / n) .model(new ModelFile.UncheckedModelFile(pvd.modLoc("item/" + e.bottleModel()))) .end(); } } public static float texture(ItemStack stack) { var fluid = SlipBottleItem.getFluid(stack); if (fluid.isEmpty()) return 0; if (!(fluid.getFluid() instanceof YHFluid liquid)) return 0; var set = liquid.type.bottleSet(); if (set == null) return 0; return (set.index + 1) * 1f / LIST.size(); } }
0
0.797408
1
0.797408
game-dev
MEDIA
0.70022
game-dev,graphics-rendering
0.924642
1
0.924642
magefree/mage
1,252
Mage.Sets/src/mage/cards/p/PearlDragon.java
package mage.cards.p; import java.util.UUID; import mage.MageInt; import mage.abilities.common.SimpleActivatedAbility; import mage.abilities.costs.mana.ManaCostsImpl; import mage.abilities.effects.common.continuous.BoostSourceEffect; import mage.abilities.keyword.FlyingAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.SubType; import mage.constants.Duration; import mage.constants.Zone; /** * * @author Quercitron */ public final class PearlDragon extends CardImpl { public PearlDragon(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{4}{W}{W}"); this.subtype.add(SubType.DRAGON); this.power = new MageInt(4); this.toughness = new MageInt(4); // Flying this.addAbility(FlyingAbility.getInstance()); // {1}{W}: Pearl Dragon gets +0/+1 until end of turn. this.addAbility(new SimpleActivatedAbility(new BoostSourceEffect(0, 1, Duration.EndOfTurn), new ManaCostsImpl<>("{1}{W}"))); } private PearlDragon(final PearlDragon card) { super(card); } @Override public PearlDragon copy() { return new PearlDragon(this); } }
0
0.870398
1
0.870398
game-dev
MEDIA
0.910331
game-dev
0.953131
1
0.953131
PrimeSense/Sensor
5,038
Include/XnEE/XnVStreamContainer.h
/***************************************************************************** * * * PrimeSense Sensor 5.x Alpha * * Copyright (C) 2012 PrimeSense Ltd. * * * * This file is part of PrimeSense Sensor * * * * 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. * * * *****************************************************************************/ #ifndef _XNV_STREAM_CONTAINER_H_ #define _XNV_STREAM_CONTAINER_H_ //--------------------------------------------------------------------------- // Includes //--------------------------------------------------------------------------- #include <XnOS.h> #include "XnVStatus.h" #include "XnVPropertySet.h" #include <XnGeneralBuffer.h> #include "XnVEventHandlers.h" //--------------------------------------------------------------------------- // Types //--------------------------------------------------------------------------- /** * This is an interface for any class that holds Streams and Modules. * Currently implemented a single subclass - XnVDevice. */ class XN_EE_CORE_API XnVStreamContainer { public: virtual ~XnVStreamContainer() {} virtual XnStatus GetProperty(const XnChar* strModule, const XnChar* strProperty, XnUInt64& nValue) const = 0; virtual XnStatus GetProperty(const XnChar* strModule, const XnChar* strProperty, XnDouble& fValue) const = 0; virtual XnStatus SetProperty(const XnChar* strModule, const XnChar* strProperty, XnUInt64 nValue) = 0; virtual XnStatus SetProperty(const XnChar* strModule, const XnChar* strProperty, XnDouble fValue) = 0; virtual XnStatus DoesModuleExist(const XnChar* strModule, XnBool* pbDoesExist) const = 0; virtual XnStatus DoesPropertyExist(const XnChar* strModule, const XnChar* strProperty, XnBool* pbDoesExist) const = 0; virtual XnStatus GetAllProperties(XnVPropertySet& PropertySet, XnBool bNoStreams = FALSE, const XnChar* strModule = NULL) const = 0; virtual XnStatus GetProperty(const XnChar* strModule, const XnChar* strProperty, XnChar* pcsValue) const = 0; virtual XnStatus GetProperty(const XnChar* strModule, const XnChar* strProperty, const XnGeneralBuffer& gbValue) const = 0; virtual XnStatus SetProperty(const XnChar* strModule, const XnChar* strProperty, const XnChar* csValue) = 0; virtual XnStatus SetProperty(const XnChar* strModule, const XnChar* strProperty, const XnGeneralBuffer& gbValue) = 0; virtual XnStatus RegisterForPropertyChangedEvent(const XnChar* strModule, const XnChar* strProperty, XnVModulePropertyChangedHandler* pHandler, XnCallbackHandle& hCallback) = 0; virtual XnStatus RegisterForStreamCollectionChangedEvent(XnVStreamCollectionChangedHandler* pHandler, XnCallbackHandle& hCallback) = 0; virtual XnStatus UnregisterFromPropertyChangedEvent(const XnChar* strModule, const XnChar* strProperty, XnCallbackHandle hCallback) = 0; virtual XnStatus UnregisterFromStreamCollectionChangedEvent(XnCallbackHandle hCallback) = 0; XN_3_6_API virtual XnBool IsModuleExist(const XnChar* strModule) = 0; XN_3_6_API virtual XnBool IsPropertyExist(const XnChar* strModule, const XnChar* strProperty) = 0; XN_3_6_API virtual XnStatus GetProperty(const XnChar* strModule, const XnChar* strProperty, XnUInt16& nValue) const = 0; XN_3_6_API virtual XnStatus GetProperty(const XnChar* strModule, const XnChar* strProperty, XnUInt32& nValue) const = 0; XN_3_6_API virtual XnStatus GetProperty(const XnChar* strModule, const XnChar* strProperty, void*& pValue) const = 0; XN_3_6_API virtual XnStatus SetProperty(const XnChar* strModule, const XnChar* strProperty, XnUInt16 nValue) = 0; XN_3_6_API virtual XnStatus SetProperty(const XnChar* strModule, const XnChar* strProperty, XnUInt32 nValue) = 0; XN_3_6_API virtual XnStatus SetProperty(const XnChar* strModule, const XnChar* strProperty, void* pValue) = 0; }; #endif // _XNV_STREAM_CONTAINER_H_
0
0.847183
1
0.847183
game-dev
MEDIA
0.593093
game-dev
0.679009
1
0.679009
Hork-Engine/Hork-Source
9,523
ThirdParty/JoltPhysics/Jolt/Physics/Constraints/PathConstraint.h
// Jolt Physics Library (https://github.com/jrouwe/JoltPhysics) // SPDX-FileCopyrightText: 2021 Jorrit Rouwe // SPDX-License-Identifier: MIT #pragma once #include <Jolt/Physics/Constraints/TwoBodyConstraint.h> #include <Jolt/Physics/Constraints/PathConstraintPath.h> #include <Jolt/Physics/Constraints/MotorSettings.h> #include <Jolt/Physics/Constraints/ConstraintPart/AxisConstraintPart.h> #include <Jolt/Physics/Constraints/ConstraintPart/DualAxisConstraintPart.h> #include <Jolt/Physics/Constraints/ConstraintPart/HingeRotationConstraintPart.h> #include <Jolt/Physics/Constraints/ConstraintPart/RotationEulerConstraintPart.h> JPH_NAMESPACE_BEGIN /// How to constrain the rotation of the body to a PathConstraint enum class EPathRotationConstraintType { Free, ///< Do not constrain the rotation of the body at all ConstrainAroundTangent, ///< Only allow rotation around the tangent vector (following the path) ConstrainAroundNormal, ///< Only allow rotation around the normal vector (perpendicular to the path) ConstrainAroundBinormal, ///< Only allow rotation around the binormal vector (perpendicular to the path) ConstrainToPath, ///< Fully constrain the rotation of body 2 to the path (following the tangent and normal of the path) FullyConstrained, ///< Fully constrain the rotation of the body 2 to the rotation of body 1 }; /// Path constraint settings, used to constrain the degrees of freedom between two bodies to a path /// /// The requirements of the path are that: /// * Tangent, normal and bi-normal form an orthonormal basis with: tangent cross bi-normal = normal /// * The path points along the tangent vector /// * The path is continuous so doesn't contain any sharp corners /// /// The reason for all this is that the constraint acts like a slider constraint with the sliding axis being the tangent vector (the assumption here is that delta time will be small enough so that the path is linear for that delta time). class JPH_EXPORT PathConstraintSettings final : public TwoBodyConstraintSettings { public: JPH_DECLARE_SERIALIZABLE_VIRTUAL(JPH_EXPORT, PathConstraintSettings) // See: ConstraintSettings::SaveBinaryState virtual void SaveBinaryState(StreamOut &inStream) const override; /// Create an instance of this constraint virtual TwoBodyConstraint * Create(Body &inBody1, Body &inBody2) const override; /// The path that constrains the two bodies RefConst<PathConstraintPath> mPath; /// The position of the path start relative to world transform of body 1 Vec3 mPathPosition = Vec3::sZero(); /// The rotation of the path start relative to world transform of body 1 Quat mPathRotation = Quat::sIdentity(); /// The fraction along the path that corresponds to the initial position of body 2. Usually this is 0, the beginning of the path. But if you want to start an object halfway the path you can calculate this with mPath->GetClosestPoint(point on path to attach body to). float mPathFraction = 0.0f; /// Maximum amount of friction force to apply (N) when not driven by a motor. float mMaxFrictionForce = 0.0f; /// In case the constraint is powered, this determines the motor settings along the path MotorSettings mPositionMotorSettings; /// How to constrain the rotation of the body to the path EPathRotationConstraintType mRotationConstraintType = EPathRotationConstraintType::Free; protected: // See: ConstraintSettings::RestoreBinaryState virtual void RestoreBinaryState(StreamIn &inStream) override; }; /// Path constraint, used to constrain the degrees of freedom between two bodies to a path class JPH_EXPORT PathConstraint final : public TwoBodyConstraint { public: JPH_OVERRIDE_NEW_DELETE /// Construct point constraint PathConstraint(Body &inBody1, Body &inBody2, const PathConstraintSettings &inSettings); // Generic interface of a constraint virtual EConstraintSubType GetSubType() const override { return EConstraintSubType::Path; } virtual void NotifyShapeChanged(const BodyID &inBodyID, Vec3Arg inDeltaCOM) override; virtual void SetupVelocityConstraint(float inDeltaTime) override; virtual void ResetWarmStart() override; virtual void WarmStartVelocityConstraint(float inWarmStartImpulseRatio) override; virtual bool SolveVelocityConstraint(float inDeltaTime) override; virtual bool SolvePositionConstraint(float inDeltaTime, float inBaumgarte) override; #ifdef JPH_DEBUG_RENDERER virtual void DrawConstraint(DebugRenderer *inRenderer) const override; #endif // JPH_DEBUG_RENDERER virtual void SaveState(StateRecorder &inStream) const override; virtual void RestoreState(StateRecorder &inStream) override; virtual bool IsActive() const override { return TwoBodyConstraint::IsActive() && mPath != nullptr; } virtual Ref<ConstraintSettings> GetConstraintSettings() const override; // See: TwoBodyConstraint virtual Mat44 GetConstraintToBody1Matrix() const override { return mPathToBody1; } virtual Mat44 GetConstraintToBody2Matrix() const override { return mPathToBody2; } /// Update the path for this constraint void SetPath(const PathConstraintPath *inPath, float inPathFraction); /// Access to the current path const PathConstraintPath * GetPath() const { return mPath; } /// Access to the current fraction along the path e [0, GetPath()->GetMaxPathFraction()] float GetPathFraction() const { return mPathFraction; } /// Friction control void SetMaxFrictionForce(float inFrictionForce) { mMaxFrictionForce = inFrictionForce; } float GetMaxFrictionForce() const { return mMaxFrictionForce; } /// Position motor settings MotorSettings & GetPositionMotorSettings() { return mPositionMotorSettings; } const MotorSettings & GetPositionMotorSettings() const { return mPositionMotorSettings; } // Position motor controls (drives body 2 along the path) void SetPositionMotorState(EMotorState inState) { JPH_ASSERT(inState == EMotorState::Off || mPositionMotorSettings.IsValid()); mPositionMotorState = inState; } EMotorState GetPositionMotorState() const { return mPositionMotorState; } void SetTargetVelocity(float inVelocity) { mTargetVelocity = inVelocity; } float GetTargetVelocity() const { return mTargetVelocity; } void SetTargetPathFraction(float inFraction) { JPH_ASSERT(mPath->IsLooping() || (inFraction >= 0.0f && inFraction <= mPath->GetPathMaxFraction())); mTargetPathFraction = inFraction; } float GetTargetPathFraction() const { return mTargetPathFraction; } ///@name Get Lagrange multiplier from last physics update (the linear/angular impulse applied to satisfy the constraint) inline Vector<2> GetTotalLambdaPosition() const { return mPositionConstraintPart.GetTotalLambda(); } inline float GetTotalLambdaPositionLimits() const { return mPositionLimitsConstraintPart.GetTotalLambda(); } inline float GetTotalLambdaMotor() const { return mPositionMotorConstraintPart.GetTotalLambda(); } inline Vector<2> GetTotalLambdaRotationHinge() const { return mHingeConstraintPart.GetTotalLambda(); } inline Vec3 GetTotalLambdaRotation() const { return mRotationConstraintPart.GetTotalLambda(); } private: // Internal helper function to calculate the values below void CalculateConstraintProperties(float inDeltaTime); // CONFIGURATION PROPERTIES FOLLOW RefConst<PathConstraintPath> mPath; ///< The path that attaches the two bodies Mat44 mPathToBody1; ///< Transform that takes a quantity from path space to body 1 center of mass space Mat44 mPathToBody2; ///< Transform that takes a quantity from path space to body 2 center of mass space EPathRotationConstraintType mRotationConstraintType; ///< How to constrain the rotation of the path // Friction float mMaxFrictionForce; // Motor controls MotorSettings mPositionMotorSettings; EMotorState mPositionMotorState = EMotorState::Off; float mTargetVelocity = 0.0f; float mTargetPathFraction = 0.0f; // RUN TIME PROPERTIES FOLLOW // Positions where the point constraint acts on in world space Vec3 mR1; Vec3 mR2; // X2 + R2 - X1 - R1 Vec3 mU; // World space path tangent Vec3 mPathTangent; // Normals to the path tangent Vec3 mPathNormal; Vec3 mPathBinormal; // Inverse of initial rotation from body 1 to body 2 in body 1 space (only used when rotation constraint type is FullyConstrained) Quat mInvInitialOrientation; // Current fraction along the path where body 2 is attached float mPathFraction = 0.0f; // Translation constraint parts DualAxisConstraintPart mPositionConstraintPart; ///< Constraint part that keeps the movement along the tangent of the path AxisConstraintPart mPositionLimitsConstraintPart; ///< Constraint part that prevents movement beyond the beginning and end of the path AxisConstraintPart mPositionMotorConstraintPart; ///< Constraint to drive the object along the path or to apply friction // Rotation constraint parts HingeRotationConstraintPart mHingeConstraintPart; ///< Constraint part that removes 2 degrees of rotation freedom RotationEulerConstraintPart mRotationConstraintPart; ///< Constraint part that removes all rotational freedom }; JPH_NAMESPACE_END
0
0.97504
1
0.97504
game-dev
MEDIA
0.894421
game-dev
0.924299
1
0.924299
magefree/mage
4,217
Mage/src/main/java/mage/abilities/keyword/OffspringAbility.java
package mage.abilities.keyword; import mage.abilities.Ability; import mage.abilities.SpellAbility; import mage.abilities.StaticAbility; import mage.abilities.common.EntersBattlefieldTriggeredAbility; import mage.abilities.condition.Condition; import mage.abilities.costs.*; import mage.abilities.costs.mana.ManaCostsImpl; import mage.abilities.effects.OneShotEffect; import mage.abilities.effects.common.CreateTokenCopyTargetEffect; import mage.constants.Outcome; import mage.constants.Zone; import mage.game.Game; import mage.game.permanent.Permanent; import mage.players.Player; import mage.util.CardUtil; /** * @author TheElk801 */ public class OffspringAbility extends StaticAbility implements OptionalAdditionalSourceCosts { private static final String keywordText = "Offspring"; private static final String reminderText = "You may pay an additional %s as you cast this spell. If you do, when this creature enters, create a 1/1 token copy of it."; private final String rule; public static final String OFFSPRING_ACTIVATION_VALUE_KEY = "offspringActivation"; protected OptionalAdditionalCost additionalCost; public OffspringAbility(String manaString) { this(new ManaCostsImpl<>(manaString)); } public OffspringAbility(Cost cost) { super(Zone.STACK, null); this.additionalCost = new OptionalAdditionalCostImpl( keywordText + ' ' + cost.getText(), String.format(reminderText, cost.getText()), cost ); this.additionalCost.setRepeatable(false); this.rule = additionalCost.getName() + ' ' + additionalCost.getReminderText(); this.setRuleAtTheTop(true); this.addSubAbility(new EntersBattlefieldTriggeredAbility(new OffspringEffect()) .withInterveningIf(OffspringCondition.instance).setRuleVisible(false)); } private OffspringAbility(final OffspringAbility ability) { super(ability); this.rule = ability.rule; this.additionalCost = ability.additionalCost.copy(); } @Override public OffspringAbility copy() { return new OffspringAbility(this); } @Override public void addOptionalAdditionalCosts(Ability ability, Game game) { if (!(ability instanceof SpellAbility)) { return; } Player player = game.getPlayer(ability.getControllerId()); if (player == null) { return; } additionalCost.reset(); if (!additionalCost.canPay(ability, this, ability.getControllerId(), game) || !player.chooseUse(Outcome.PutCreatureInPlay, "Pay " + additionalCost.getText(true) + " for offspring?", ability, game)) { return; } additionalCost.activate(); for (Cost cost : ((Costs<Cost>) additionalCost)) { ability.getCosts().add(cost.copy()); } ability.setCostsTag(OFFSPRING_ACTIVATION_VALUE_KEY, null); } @Override public String getCastMessageSuffix() { return additionalCost.getCastSuffixMessage(0); } @Override public String getRule() { return rule; } } class OffspringEffect extends OneShotEffect { OffspringEffect() { super(Outcome.Benefit); staticText = "create a 1/1 token copy of it"; } private OffspringEffect(final OffspringEffect effect) { super(effect); } @Override public OffspringEffect copy() { return new OffspringEffect(this); } @Override public boolean apply(Game game, Ability source) { Permanent permanent = source.getSourcePermanentOrLKI(game); return permanent != null && new CreateTokenCopyTargetEffect( null, null, false, 1, false, false, null, 1, 1, false ).setSavedPermanent(permanent).apply(game, source); } } enum OffspringCondition implements Condition { instance; @Override public boolean apply(Game game, Ability source) { return CardUtil.checkSourceCostsTagExists(game, source, OffspringAbility.OFFSPRING_ACTIVATION_VALUE_KEY); } @Override public String toString() { return "its offspring cost was paid"; } }
0
0.943885
1
0.943885
game-dev
MEDIA
0.98593
game-dev
0.978616
1
0.978616
Azanor/thaumcraft-api
2,563
casters/FocusNode.java
package thaumcraft.api.casters; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Set; import net.minecraft.util.math.RayTraceResult; import thaumcraft.api.aspects.Aspect; public abstract class FocusNode implements IFocusElement { public FocusNode() { super(); initialize(); } public String getUnlocalizedName() { return getKey()+".name"; } public String getUnlocalizedText() { return getKey()+".text"; } public abstract int getComplexity(); public abstract Aspect getAspect(); public abstract EnumSupplyType[] mustBeSupplied(); public abstract EnumSupplyType[] willSupply(); public boolean canSupply(EnumSupplyType type) { if (willSupply()!=null) for (EnumSupplyType st:willSupply()) { if (st==type) return true; } return false; } public enum EnumSupplyType { TARGET, TRAJECTORY; } public RayTraceResult[] supplyTargets() { return null;} public Trajectory[] supplyTrajectories() { return null;} FocusPackage pack; public final void setPackage(FocusPackage pack) { this.pack = pack; } public final FocusPackage getPackage() { return pack; } public final FocusPackage getRemainingPackage() { FocusPackage p = getPackage(); List<IFocusElement> l = p.nodes.subList(p.index+1, p.nodes.size()); List<IFocusElement> l2 = Collections.synchronizedList(new ArrayList<>()); for (IFocusElement fe:l) l2.add(fe); FocusPackage p2 = new FocusPackage(); p2.setUniqueID(p.getUniqueID()); p2.world = p.world; p2.multiplyPower(p.getPower()); p2.nodes = l2; p2.setCasterUUID(p.getCasterUUID()); return l2.isEmpty() ? null : p2; } private FocusNode parent; public final FocusNode getParent() { return parent; } final HashMap<String, NodeSetting> settings = new HashMap<>(); public final Set<String> getSettingList() { return settings.keySet(); } public final NodeSetting getSetting(String key) { return settings.get(key); } public final int getSettingValue(String key) { return settings.containsKey(key) ? settings.get(key).getValue() : 0; } public NodeSetting[] createSettings() { return null; } public final void initialize() { NodeSetting[] set = createSettings(); if (set!=null) { for (NodeSetting setting : set) { settings.put(setting.key, setting); } } } public void setParent(FocusNode parent) { this.parent = parent; } public float getPowerMultiplier() { return 1; } public boolean isExclusive() { return false; } }
0
0.934281
1
0.934281
game-dev
MEDIA
0.687557
game-dev
0.954075
1
0.954075
iamjosephmj/flinger
2,335
app/src/main/java/io/iamjosephmj/flingersample/ui/state/ScrollState.kt
/* * MIT License * * Copyright (c) 2021 Joseph James * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ package io.iamjosephmj.flingersample.ui.state import io.iamjosephmj.flinger.configs.FlingConfiguration /** * This is how we make a fling behaviour with all values from the settings page. * * @author Joseph James. */ object ScrollState { fun buildScrollBehaviour() = FlingConfiguration.Builder() .scrollViewFriction(scrollFriction) .absVelocityThreshold(absVelocityThreshold) .gravitationalForce(gravitationalForce) .inchesPerMeter(inchesPerMeter) .decelerationFriction(decelerationFriction) .decelerationRate(decelerationRate) .splineInflection(splineInflection) .splineStartTension(splineStartTension) .splineEndTension(splineEndTension) .numberOfSplinePoints(numberOfSplinePoints) .build() var type = 1 var scrollFriction: Float = 0.008f var absVelocityThreshold: Float = 0f var gravitationalForce: Float = 9.80665f var inchesPerMeter: Float = 39.37f var decelerationFriction: Float = .09f var decelerationRate: Float = 2.358201f var splineInflection: Float = 0.1f var splineStartTension: Float = 0.1f var splineEndTension: Float = 1.0f var numberOfSplinePoints: Int = 100 }
0
0.858176
1
0.858176
game-dev
MEDIA
0.288717
game-dev
0.872888
1
0.872888
kbengine/kbengine_cocos2d_js_demo
8,228
cocos2d-js-client/frameworks/js-bindings/cocos2d-x/cocos/editor-support/cocostudio/CCDatas.cpp
/**************************************************************************** Copyright (c) 2013-2014 Chukong Technologies Inc. http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "cocostudio/CCDatas.h" #include "cocostudio/CCUtilMath.h" #include "cocostudio/CCTransformHelp.h" using namespace cocos2d; namespace cocostudio { BaseData::BaseData() : x(0.0f) , y(0.0f) , zOrder(0) , skewX(0.0f) , skewY(0.0f) , scaleX(1.0f) , scaleY(1.0f) , tweenRotate(0.0f) , isUseColorInfo(false) , a(255) , r(255) , g(255) , b(255) { } BaseData::~BaseData() { } void BaseData::copy(const BaseData *node ) { x = node->x; y = node->y; zOrder = node->zOrder; scaleX = node->scaleX; scaleY = node->scaleY; skewX = node->skewX; skewY = node->skewY; tweenRotate = node->tweenRotate; isUseColorInfo = node->isUseColorInfo; r = node->r; g = node->g; b = node->b; a = node->a; } void BaseData::subtract(BaseData *from, BaseData *to, bool limit) { x = to->x - from->x; y = to->y - from->y; scaleX = to->scaleX - from->scaleX; scaleY = to->scaleY - from->scaleY; skewX = to->skewX - from->skewX; skewY = to->skewY - from->skewY; if(isUseColorInfo || from->isUseColorInfo || to->isUseColorInfo) { a = to->a - from->a; r = to->r - from->r; g = to->g - from->g; b = to->b - from->b; isUseColorInfo = true; } else { a = r = g = b = 0; isUseColorInfo = false; } if (limit) { if (skewX > M_PI) { skewX -= (float)CC_DOUBLE_PI; } if (skewX < -M_PI) { skewX += (float)CC_DOUBLE_PI; } if (skewY > M_PI) { skewY -= (float)CC_DOUBLE_PI; } if (skewY < -M_PI) { skewY += (float)CC_DOUBLE_PI; } } if (to->tweenRotate) { skewX += to->tweenRotate * M_PI * 2; skewY -= to->tweenRotate * M_PI * 2; } } void BaseData::setColor(const Color4B &color) { r = color.r; g = color.g; b = color.b; a = color.a; } Color4B BaseData::getColor() { return Color4B(r, g, b, a); } const std::string DisplayData::changeDisplayToTexture(const std::string& displayName) { // remove .xxx std::string textureName = displayName; size_t startPos = textureName.find_last_of("."); if(startPos != std::string::npos) { textureName = textureName.erase(startPos); } return textureName; } DisplayData::DisplayData(void) : displayType(CS_DISPLAY_MAX) , displayName("") { } void DisplayData::copy(DisplayData *displayData) { displayName = displayData->displayName; displayType = displayData->displayType; } SpriteDisplayData::SpriteDisplayData(void) { displayType = CS_DISPLAY_SPRITE; } void SpriteDisplayData::copy(DisplayData *displayData) { DisplayData::copy(displayData); if (SpriteDisplayData *sdd = dynamic_cast<SpriteDisplayData*>(displayData)) { skinData = sdd->skinData; } } ArmatureDisplayData::ArmatureDisplayData(void) { displayType = CS_DISPLAY_ARMATURE; } ParticleDisplayData::ParticleDisplayData(void) { displayType = CS_DISPLAY_PARTICLE; } BoneData::BoneData(void) : name("") , parentName("") { } BoneData::~BoneData(void) { } bool BoneData::init() { return true; } void BoneData::addDisplayData(DisplayData *displayData) { displayDataList.pushBack(displayData); } DisplayData *BoneData::getDisplayData(int index) { return displayDataList.at(index); } ArmatureData::ArmatureData() : dataVersion(0.1f) { } ArmatureData::~ArmatureData() { } bool ArmatureData::init() { return true; } void ArmatureData::addBoneData(BoneData *boneData) { boneDataDic.insert(boneData->name, boneData); } BoneData *ArmatureData::getBoneData(const std::string& boneName) { return static_cast<BoneData*>(boneDataDic.at(boneName)); } FrameData::FrameData(void) : frameID(0) , duration(1) , tweenEasing(cocos2d::tweenfunc::Linear) , easingParamNumber(0) , easingParams(nullptr) , isTween(true) , displayIndex(0) , blendFunc(BlendFunc::ALPHA_PREMULTIPLIED) , strEvent("") , strMovement("") , strSound("") , strSoundEffect("") { } FrameData::~FrameData(void) { CC_SAFE_DELETE(easingParams); } void FrameData::copy(const BaseData *baseData) { BaseData::copy(baseData); if (const FrameData *frameData = dynamic_cast<const FrameData*>(baseData)) { duration = frameData->duration; displayIndex = frameData->displayIndex; tweenEasing = frameData->tweenEasing; easingParamNumber = frameData->easingParamNumber; CC_SAFE_DELETE(easingParams); if (easingParamNumber != 0) { easingParams = new float[easingParamNumber]; for (int i = 0; i<easingParamNumber; i++) { easingParams[i] = frameData->easingParams[i]; } } blendFunc = frameData->blendFunc; isTween = frameData->isTween; } } MovementBoneData::MovementBoneData() : delay(0.0f) , scale(1.0f) , duration(0) , name("") { } MovementBoneData::~MovementBoneData(void) { } bool MovementBoneData::init() { return true; } void MovementBoneData::addFrameData(FrameData *frameData) { frameList.pushBack(frameData); } FrameData *MovementBoneData::getFrameData(int index) { return frameList.at(index); } MovementData::MovementData(void) : name("") , duration(0) , scale(1.0f) , durationTo(0) , durationTween(0) , loop(true) , tweenEasing(cocos2d::tweenfunc::Linear) { } MovementData::~MovementData(void) { } void MovementData::addMovementBoneData(MovementBoneData *movBoneData) { movBoneDataDic.insert(movBoneData->name, movBoneData); } MovementBoneData *MovementData::getMovementBoneData(const std::string& boneName) { return movBoneDataDic.at(boneName); } AnimationData::AnimationData(void) { } AnimationData::~AnimationData(void) { } void AnimationData::addMovement(MovementData *movData) { movementDataDic.insert(movData->name, movData); movementNames.push_back(movData->name); } MovementData *AnimationData::getMovement(const std::string& movementName) { return movementDataDic.at(movementName); } ssize_t AnimationData::getMovementCount() { return movementDataDic.size(); } ContourData::ContourData() { } ContourData::~ContourData() { } bool ContourData::init() { return true; } void ContourData::addVertex(Vec2 &vertex) { vertexList.push_back(vertex); } TextureData::TextureData() : height(0.0f) , width(0.0f) , pivotX(0.5f) , pivotY(0.5f) , name("") { } TextureData::~TextureData() { } bool TextureData::init() { return true; } void TextureData::addContourData(ContourData *contourData) { contourDataList.pushBack(contourData); } ContourData *TextureData::getContourData(int index) { return contourDataList.at(index); } }
0
0.949436
1
0.949436
game-dev
MEDIA
0.627449
game-dev,graphics-rendering
0.888011
1
0.888011
dpjudas/UT99VulkanDrv
2,739
Thirdparty/Unreal_226_Gold/Engine/Inc/UnIn.h
/*============================================================================= UnIn.h: Unreal input system. Copyright 1997-1999 Epic Games, Inc. All Rights Reserved. Description: This subsystem contains all input. The input is generated by the platform-specific code, and processed by the actor code. Revision history: * Created by Tim Sweeney =============================================================================*/ /*----------------------------------------------------------------------------- Enums. -----------------------------------------------------------------------------*/ // // Maximum aliases. // enum {ALIAS_MAX=40}; /*----------------------------------------------------------------------------- UInput. -----------------------------------------------------------------------------*/ // // An input alias. // struct FAlias { FName Alias; FString Command; FAlias() : Alias() , Command( E_NoInit ) {} }; // // The input system base class. // class ENGINE_API UInput : public USubsystem { static const TCHAR* StaticConfigName() {return TEXT("User");} DECLARE_CLASS(UInput,USubsystem,CLASS_Transient|CLASS_Config) // Variables. FAlias Aliases[ALIAS_MAX];//!!tarray FStringNoInit Bindings[IK_MAX];//!!tarray UViewport* Viewport; // Constructors. UInput(); void StaticConstructor(); // UObject interface. void Serialize( FArchive& Ar ); // UInput interface. static void StaticInitInput(); virtual void Init( UViewport* Viewport ); virtual UBOOL Exec( const TCHAR* Cmd, FOutputDevice& Ar ); virtual UBOOL PreProcess( EInputKey iKey, EInputAction State, FLOAT Delta=0.0 ); virtual UBOOL Process( FOutputDevice& Ar, EInputKey iKey, EInputAction State, FLOAT Delta=0.0 ); virtual void ReadInput( FLOAT DeltaSeconds, FOutputDevice& Ar ); virtual void ResetInput(); virtual const TCHAR* GetKeyName( EInputKey Key ) const; virtual int FindKeyName( const TCHAR* KeyName, EInputKey& iKey ) const; // Accessors. void SetInputAction( EInputAction NewAction, FLOAT NewDelta=0.0 ) {Action = NewAction; Delta = NewDelta;} EInputAction GetInputAction() {return Action;} FLOAT GetInputDelta() {return Delta;} BYTE KeyDown( int i ) {return KeyDownTable[Clamp(i,0,IK_MAX-1)];} protected: UEnum* InputKeys; EInputAction Action; FLOAT Delta; BYTE KeyDownTable[IK_MAX]; virtual BYTE* FindButtonName( AActor* Actor, const TCHAR* ButtonName ) const; virtual FLOAT* FindAxisName( AActor* Actor, const TCHAR* ButtonName ) const; virtual void ExecInputCommands( const TCHAR* Cmd, FOutputDevice& Ar ); }; /*----------------------------------------------------------------------------- The End. -----------------------------------------------------------------------------*/
0
0.84844
1
0.84844
game-dev
MEDIA
0.891756
game-dev
0.578248
1
0.578248
spicylobstergames/shotcaller-godot
4,191
prototype/goap/ActionPlanner.gd
extends Node # self = GoapActionPlanner var _actions: Array # set actions available for planning. # this can be changed in runtime for more dynamic options. func set_actions(actions: Array): _actions = actions # Receives a Goal and returns a list of actions to be executed. func get_plan(agent, goal) -> Array: var desired_state = goal.get_desired_state(agent) if desired_state.is_empty(): return [] return _find_best_plan(goal, desired_state, agent) func _find_best_plan(goal, desired_state, agent): # goal is set as root action var root = { "action": goal, "state": desired_state, "children": [] } # build plans will populate root with children. # In case it doesn't find a valid path, it will return false. if _build_plans(root, agent): var plans = _transform_tree_into_array(root, agent) if plans.is_empty(): push_error("goap action planner error: no valid plans") return [] return _get_cheapest_plan(plans) return [] # Compares plan's cost and returns # actions included in the cheapest one. func _get_cheapest_plan(plans): var best_plan for p in plans: if best_plan == null or p.cost < best_plan.cost: best_plan = p return best_plan.actions # Builds graph with actions. # Only includes valid plans that achieve the goal. # # This function uses recursion to build the graph. This is # necessary because any new action included in the graph may # add pre-conditions to the desired state that can be satisfied # by previously considered actions, meaning, on every step we # need to iterate from the beginning to find all solutions. # # TODO: protected from circular dependencies # # Returns true if the path has a solution. func _build_plans(step, agent): var has_followup = false # each node in the graph has it's own desired state. var state = step.state.duplicate() # checks if the current state is satisfied for s in step.state: var a = agent.get_state(s) if a is Object: a = true var w = WorldState.get_state(s) if w is Object: w = true var b = state[s] if b == a or b == w: state.erase(s) # if the state is empty, it means this branch already # found the solution, so it doesn't need to look for # more actions if state.is_empty(): return true for action in _actions: if not action.is_valid(agent): continue var should_use_action = false var effects = action.get_effects() var desired_state = state.duplicate() # check if action should be used, i.e. it # satisfies at least one condition from the # desired state for s in desired_state: if desired_state[s] == effects.get(s): desired_state.erase(s) should_use_action = true if should_use_action: # adds actions pre-conditions to the desired state var preconditions = action.get_preconditions() for p in preconditions: desired_state[p] = preconditions[p] var s = { "action": action, "state": desired_state, "children": [] } # if desired state is empty, it means this action can be included # if it's not empty, _build_plans is called again (recursively) so # it can try to find actions to satisfy this current state. In case # it can't find anything, this action won't be included in the graph. if desired_state.is_empty() or _build_plans(s, agent): step.children.push_back(s) has_followup = true return has_followup # Transforms graph with actions into list of actions and calculates # the cost by summing actions' cost # # Returns list of plans. func _transform_tree_into_array(p, agent): var plans = [] if p.children.size() == 0 and p.action.has_method("get_cost"): plans.push_back({ "actions": [p.action], "cost": p.action.get_cost(agent) }) return plans for c in p.children: for child_plan in _transform_tree_into_array(c, agent): if p.action.has_method("get_cost"): child_plan.actions.push_back(p.action) child_plan.cost += p.action.get_cost(agent) plans.push_back(child_plan) return plans # Prints plan. Used for Debugging only. func _print_plan(plan): var actions = [] for a in plan.actions: actions.push_back(a.get_class_name()) print("action_planner: ", {"cost": plan.cost, "actions": actions})
0
0.896303
1
0.896303
game-dev
MEDIA
0.913492
game-dev
0.945995
1
0.945995
Ji-Rath/MassAIExample
2,284
Plugins/MassPersistence/Source/MassPersistence/Private/PersistentDataSetupProcessor.cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "PersistentDataSetupProcessor.h" #include "MassExecutionContext.h" #include "MassPersistentDataSubsystem.h" #include "PersistentDataFragment.h" UPersistentDataInitializerProcessor::UPersistentDataInitializerProcessor() : EntityQuery(*this) { ObservedType = FPersistentDataTag::StaticStruct(); Operation = EMassObservedOperation::Add; } void UPersistentDataInitializerProcessor::ConfigureQueries(const TSharedRef<FMassEntityManager>& EntityManager) { EntityQuery.AddSubsystemRequirement<UMassPersistentDataSubsystem>(EMassFragmentAccess::ReadWrite); } void UPersistentDataInitializerProcessor::Execute(FMassEntityManager& EntityManager, FMassExecutionContext& Context) { EntityQuery.ForEachEntityChunk(Context, [this](FMassExecutionContext& Context) { auto& PersistentDataSubsystem = Context.GetMutableSubsystemChecked<UMassPersistentDataSubsystem>(); const int32 NumEntities = Context.GetNumEntities(); for (int EntityIdx = 0; EntityIdx < NumEntities; EntityIdx++) { PersistentDataSubsystem.ManagedEntities.Emplace(Context.GetEntity(EntityIdx)); } }); } UPersistentDataDestructorProcessor::UPersistentDataDestructorProcessor() : EntityQuery(*this) { ObservedType = FPersistentDataTag::StaticStruct(); Operation = EMassObservedOperation::Remove; } void UPersistentDataDestructorProcessor::ConfigureQueries(const TSharedRef<FMassEntityManager>& EntityManager) { EntityQuery.AddSubsystemRequirement<UMassPersistentDataSubsystem>(EMassFragmentAccess::ReadWrite); } void UPersistentDataDestructorProcessor::Execute(FMassEntityManager& EntityManager, FMassExecutionContext& Context) { EntityQuery.ForEachEntityChunk(Context, [this](FMassExecutionContext& Context) { auto& PersistentDataSubsystem = Context.GetMutableSubsystemChecked<UMassPersistentDataSubsystem>(); TSet<FMassEntityHandle> EntitiesToRemove; const int32 NumEntities = Context.GetNumEntities(); for (int EntityIdx = 0; EntityIdx < NumEntities; EntityIdx++) { EntitiesToRemove.Add(Context.GetEntity(EntityIdx)); } PersistentDataSubsystem.ManagedEntities.RemoveAllSwap([&EntitiesToRemove](FMassEntityHandle& Entity) { return EntitiesToRemove.Contains(Entity); }); }); }
0
0.84935
1
0.84935
game-dev
MEDIA
0.854817
game-dev
0.848652
1
0.848652
copygirl/BetterStorage
4,672
src/main/java/net/mcft/copy/betterstorage/tile/crate/CrateItems.java
package net.mcft.copy.betterstorage.tile.crate; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NavigableMap; import java.util.TreeMap; import java.util.TreeSet; import net.mcft.copy.betterstorage.misc.ItemIdentifier; import net.mcft.copy.betterstorage.utils.RandomUtils; import net.mcft.copy.betterstorage.utils.StackUtils; import net.minecraft.item.ItemStack; public class CrateItems { private final Map<ItemIdentifier, ItemStack> itemsMap = new HashMap<ItemIdentifier, ItemStack>(); private int totalStacks = 0; private NavigableMap<Integer, ItemStack> weightedMap = new TreeMap<Integer, ItemStack>(); private boolean weightedMapDirty = false; // TODO: Find a better way than recreating the weighted map every time something changes. // For now though, this is much better than how things were done before. /** Gets the number of unique items. */ public int getUniqueItems() { return itemsMap.size(); } /** Gets the number of total stacks all items would occupy. */ public int getTotalStacks() { return totalStacks; } /** Gets the amount of items of this type, 0 if none. */ public int get(ItemIdentifier item) { ItemStack stack = itemsMap.get(item); return ((stack != null) ? stack.stackSize : 0); } /** Sets the amount of items of this type. <br> * If amount > 0 and item was previously not present, adds the item. <br> * If amount <= 0 and item was previously present, removes the item. * Automatically updates the number of total stacks * and marks the weighted map as dirty if necessary. */ public void set(ItemIdentifier item, int amount) { ItemStack stack = itemsMap.get(item); int stacksBefore, stacksAfter; if (stack != null) { if (amount == stack.stackSize) return; stacksBefore = StackUtils.calcNumStacks(stack); if (amount > 0) { stack.stackSize = amount; stacksAfter = StackUtils.calcNumStacks(stack); } else { stacksAfter = 0; itemsMap.remove(item); } } else if (amount > 0) { stack = item.createStack(amount); stacksBefore = 0; stacksAfter = StackUtils.calcNumStacks(stack); itemsMap.put(item, stack); } else return; if (stacksBefore != stacksAfter) { totalStacks += (stacksAfter - stacksBefore); weightedMapDirty = true; } } /** Returns an iterable of all of the items. * Stack sizes might exceed usual stack limits. */ public Iterable<ItemStack> getItems() { return itemsMap.values(); } /** Returns an iterable that allows iterating over all stacks in a * random order. Each stack has the same chance of getting picked. */ public Iterable<ItemStack> getRandomStacks() { return new Iterable<ItemStack>() { @Override public Iterator<ItemStack> iterator() { return new ItemsIterator(getWeightedMap(), getTotalStacks()); } }; } /** Returns a list of random stacks with a maximum size of the specified amount. * May return less elements, or an empty list, if there's not enough stacks. */ public List<ItemStack> getRandomStacks(int amount) { amount = Math.min(amount, getTotalStacks()); List<ItemStack> stacks = new ArrayList<ItemStack>(amount); for (ItemStack stack : getRandomStacks()) { stacks.add(stack); if (stacks.size() >= amount) break; } return stacks; } private NavigableMap<Integer, ItemStack> getWeightedMap() { if (weightedMapDirty) { weightedMap.clear(); int stacks = 0; for (ItemStack stack : getItems()) weightedMap.put((stacks += StackUtils.calcNumStacks(stack)), stack); } return weightedMap; } private static class ItemsIterator implements Iterator<ItemStack> { private final NavigableMap<Integer, ItemStack> map; private final int stacks; private final TreeSet<Integer> picked = new TreeSet<Integer>(); public ItemsIterator(NavigableMap<Integer, ItemStack> map, int stacks) { this.map = map; this.stacks = stacks; } @Override public boolean hasNext() { return (picked.size() < stacks); } @Override public ItemStack next() { int index = 1 + RandomUtils.getInt(stacks - picked.size()); if (!picked.isEmpty()) for (int p : picked) if (p > index) break; else index++; picked.add(index); Map.Entry<Integer, ItemStack> entry = map.ceilingEntry(index); ItemStack stack = entry.getValue(); int maxStackSize = stack.getMaxStackSize(); int amount = ((index != entry.getKey()) ? maxStackSize : ((stack.stackSize - 1) % maxStackSize + 1)); return StackUtils.copyStack(stack, amount); } @Override public void remove() { throw new UnsupportedOperationException(); } } }
0
0.894338
1
0.894338
game-dev
MEDIA
0.754507
game-dev,uncategorized
0.995438
1
0.995438
Pan4ur/ThunderHack-Recode
10,189
src/main/java/thunder/hack/features/modules/movement/PacketFly.java
package thunder.hack.features.modules.movement; import meteordevelopment.orbit.EventHandler; import org.jetbrains.annotations.NotNull; import thunder.hack.ThunderHack; import thunder.hack.events.impl.EventMove; import thunder.hack.events.impl.EventSync; import thunder.hack.events.impl.PacketEvent; import thunder.hack.injection.accesors.IPlayerPositionLookS2CPacket; import thunder.hack.features.modules.Module; import thunder.hack.setting.Setting; import net.minecraft.client.gui.screen.DownloadingTerrainScreen; import net.minecraft.network.packet.c2s.play.PlayerMoveC2SPacket; import net.minecraft.network.packet.c2s.play.TeleportConfirmC2SPacket; import net.minecraft.network.packet.s2c.play.PlayerPositionLookS2CPacket; import net.minecraft.util.math.Vec3d; import thunder.hack.setting.impl.BooleanSettingGroup; import thunder.hack.utility.player.MovementUtility; import java.util.ArrayList; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ThreadLocalRandom; public class PacketFly extends Module { public PacketFly() { super("PacketFly", Category.MOVEMENT); } private final Setting<Mode> mode = new Setting<>("Mode", Mode.Fast); private final Setting<Type> type = new Setting<>("Type", Type.Preserve); private final Setting<Phase> phase = new Setting<>("Phase", Phase.Full); private final Setting<Boolean> limit = new Setting<>("Limit", true); private final Setting<BooleanSettingGroup> antiKick = new Setting<>("AntiKick", new BooleanSettingGroup(true)); private final Setting<Integer> interval = new Setting<>("Interval", 4, 1, 50).addToGroup(antiKick); private final Setting<Integer> upInterval = new Setting<>("UpInterval", 20, 1, 50).addToGroup(antiKick); private final Setting<Float> anticKickOffset = new Setting<>("anticKickOffset", 0.04f, 0.008f, 1f).addToGroup(antiKick); private final Setting<Float> speed = new Setting<>("Speed", 1.0f, 0.0f, 10.0f); private final Setting<Float> upSpeed = new Setting<>("UpSpeed", 0.062f, 0.001f, 0.1f); private final Setting<Float> timer = new Setting<>("Timer", 1f, 0.1f, 5f); private final Setting<Integer> increaseTicks = new Setting<>("IncreaseTicks", 1, 1, 20); private final Setting<Float> factor = new Setting<>("Factor", 1f, 1f, 10f); private final Setting<Float> offset = new Setting<>("Offset", 1337f, 1f, 1337f, v-> type.is(Type.Up) || type.is(Type.Down)); private final ConcurrentHashMap<Integer,Teleport> teleports = new ConcurrentHashMap<>(); private final ArrayList<PlayerMoveC2SPacket> movePackets = new ArrayList<>(); private int ticks, factorTicks, teleportId = -1; private boolean flip = false; @Override public void onEnable() { teleportId = -1; if (fullNullCheck() && mc.player != null) { ticks = 0; teleportId = 0; movePackets.clear(); teleports.clear(); } factorTicks = 0; } @Override public void onDisable() { ThunderHack.TICK_TIMER = 1.0f; } public boolean getTickCounter(int n) { ++ticks; if (ticks >= n) { ticks = 0; return true; } return false; } private int getWorldBorder() { if (mc.isInSingleplayer()) { return 1; } int n = ThreadLocalRandom.current().nextInt(29000000); if (ThreadLocalRandom.current().nextBoolean()) { return n; } return -n; } public Vec3d getVectorByMode(@NotNull Vec3d vec3d, Vec3d vec3d2) { Vec3d vec3d3 = vec3d.add(vec3d2); switch (type.getValue()) { case Preserve -> vec3d3 = vec3d3.add(getWorldBorder(), 0.0, getWorldBorder()); case Up -> vec3d3 = vec3d3.add(0.0, offset.getValue(), 0.0); case Down -> vec3d3 = vec3d3.add(0.0, -offset.getValue(), 0.0); case Bounds -> vec3d3 = new Vec3d(vec3d3.x, mc.player.getY() <= 10.0 ? 255.0 : 1.0, vec3d3.z); } return vec3d3; } public void sendPackets(Vec3d vec3d, boolean confirm) { Vec3d motion = mc.player.getPos().add(vec3d); Vec3d rubberBand = getVectorByMode(vec3d, motion); PlayerMoveC2SPacket motionPacket = new PlayerMoveC2SPacket.PositionAndOnGround(motion.x, motion.y, motion.z, mc.player.isOnGround()); movePackets.add(motionPacket); sendPacket(motionPacket); PlayerMoveC2SPacket rubberBandPacket = new PlayerMoveC2SPacket.PositionAndOnGround(rubberBand.x, rubberBand.y, rubberBand.z, mc.player.isOnGround()); movePackets.add(rubberBandPacket); sendPacket(rubberBandPacket); if (confirm) { sendPacket(new TeleportConfirmC2SPacket(++teleportId)); teleports.put(teleportId, new Teleport(motion.x, motion.y, motion.z, System.currentTimeMillis())); } } @EventHandler public void onPacketReceive(PacketEvent.Receive event) { if (fullNullCheck()) return; if (mc.player != null && event.getPacket() instanceof PlayerPositionLookS2CPacket pac) { Teleport teleport = teleports.remove(pac.getTeleportId()); if ( mc.player.isAlive() && mc.world.isChunkLoaded((int) mc.player.getX() >> 4, (int) mc.player.getZ() >> 4) && !(mc.currentScreen instanceof DownloadingTerrainScreen) && mode.getValue() != Mode.Rubber && teleport != null && teleport.x == pac.getX() && teleport.y == pac.getY() && teleport.z == pac.getZ() ) { event.cancel(); return; } ((IPlayerPositionLookS2CPacket) pac).setYaw(mc.player.getYaw()); ((IPlayerPositionLookS2CPacket) pac).setPitch(mc.player.getPitch()); teleportId = pac.getTeleportId(); } } @EventHandler public void onPacketSend(PacketEvent.@NotNull Send event) { if (event.getPacket() instanceof PlayerMoveC2SPacket) { if (movePackets.contains((PlayerMoveC2SPacket) event.getPacket())) { movePackets.remove((PlayerMoveC2SPacket) event.getPacket()); return; } event.cancel(); } } @Override public void onUpdate() { teleports.entrySet().removeIf(entry -> System.currentTimeMillis() - entry.getValue().time > 30000); } @EventHandler public void onMove(@NotNull EventMove event) { if (!event.isCancelled()) { if (mode.getValue() != Mode.Rubber && teleportId == 0) return; event.cancel(); event.setX(mc.player.getVelocity().x); event.setY(mc.player.getVelocity().y); event.setZ(mc.player.getVelocity().z); if (phase.getValue() != Phase.Off && (phase.getValue() == Phase.Semi || mc.world.getBlockCollisions(mc.player, mc.player.getBoundingBox().expand(-0.0625, -0.0625, -0.0625)).iterator().hasNext())) { mc.player.noClip = true; } } } @EventHandler public void onSync(EventSync eventPlayerUpdateWalking) { if (timer.getValue() != 1.0) ThunderHack.TICK_TIMER = timer.getValue(); mc.player.setVelocity(0.0, 0.0, 0.0); if (mode.getValue() != Mode.Rubber && teleportId == 0) { if (getTickCounter(4)) sendPackets(Vec3d.ZERO, false); return; } boolean insideBlock = mc.world.getBlockCollisions(mc.player, mc.player.getBoundingBox().expand(-0.0625, -0.0625, -0.0625)).iterator().hasNext(); double upMotion = 0; if (mc.options.jumpKey.isPressed() && (insideBlock || !MovementUtility.isMoving())) { if (antiKick.getValue().isEnabled() && !insideBlock) upMotion = getTickCounter(mode.is(Mode.Rubber) ? upInterval.getValue() / 2 : upInterval.getValue()) ? -upSpeed.getValue() / 2f : upSpeed.getValue(); else upMotion = upSpeed.getValue(); } else if (mc.options.sneakKey.isPressed()) upMotion = -upSpeed.getValue(); else if(antiKick.getValue().isEnabled() && !insideBlock) upMotion = getTickCounter(interval.getValue()) ? -anticKickOffset.getValue() : 0.0; if (phase.is(Phase.Full) && insideBlock && MovementUtility.isMoving() && upMotion != 0.0) upMotion = mc.options.jumpKey.isPressed() ? upMotion / 2.5 : upMotion / 1.5; double[] motion = MovementUtility.forward(phase.is(Phase.Full) && insideBlock ? 0.034444444444444444 : (double) (speed.getValue()) * 0.26); int factorInt = 1; if (mode.getValue() == Mode.Factor && mc.player.age % increaseTicks.getValue() == 0) { factorInt = (int) Math.floor(factor.getValue()); factorTicks++; if (factorTicks > (int) (20D / ((factor.getValue() - factorInt) * 20D))) { factorInt += 1; factorTicks = 0; } } for (int i = 1; i <= factorInt; ++i) { if (mode.getValue() == Mode.Limit) { if (mc.player.age % 2 == 0) { if (flip && upMotion >= 0.0) { flip = false; upMotion = -upSpeed.getValue() / 2f; } mc.player.setVelocity(motion[0] * i,upMotion * i,motion[1] * i); sendPackets(mc.player.getVelocity(), !limit.getValue()); continue; } if (!(upMotion < 0.0)) continue; flip = true; continue; } mc.player.setVelocity(motion[0] * i,upMotion * i,motion[1] * i); sendPackets(mc.player.getVelocity(), !mode.is(Mode.Rubber)); } } public enum Mode { Fast, Factor, Rubber, Limit } public enum Phase { Full, Off, Semi } public enum Type { Preserve, Up, Down, Bounds } public record Teleport(double x, double y, double z, long time){} }
0
0.776864
1
0.776864
game-dev
MEDIA
0.949848
game-dev
0.97516
1
0.97516
geode-sdk/geode
9,004
loader/include/Geode/cocos/script_support/CCScriptSupport.h
/**************************************************************************** Copyright (c) 2010-2012 cocos2d-x.org http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #ifndef __SCRIPT_SUPPORT_H__ #define __SCRIPT_SUPPORT_H__ #include "../platform/CCCommon.h" #include "../platform/CCAccelerometer.h" #include "../touch_dispatcher/CCTouch.h" #include "../cocoa/CCSet.h" #include <map> #include <string> #include <list> typedef struct lua_State lua_State; NS_CC_BEGIN class CCTimer; class CCLayer; class CCMenuItem; class CCNotificationCenter; class CCCallFunc; class CCAcceleration; enum ccScriptType { kScriptTypeNone = 0, kScriptTypeLua, kScriptTypeJavascript }; /** * @js NA * @lua NA */ class CCScriptHandlerEntry : public CCObject { public: static CCScriptHandlerEntry* create(int nHandler); ~CCScriptHandlerEntry(void); int getHandler(void) { return m_nHandler; } int getEntryId(void) { return m_nEntryId; } protected: CCScriptHandlerEntry(int nHandler) : m_nHandler(nHandler) { static int newEntryId = 0; newEntryId++; m_nEntryId = newEntryId; } public: int m_nHandler; int m_nEntryId; }; /** * @addtogroup script_support * @{ * @js NA * @lua NA */ class CCSchedulerScriptHandlerEntry : public CCScriptHandlerEntry { public: // nHandler return by tolua_ref_function(), called from LuaCocos2d.cpp static CCSchedulerScriptHandlerEntry* create(int nHandler, float fInterval, bool bPaused); ~CCSchedulerScriptHandlerEntry(void); cocos2d::CCTimer* getTimer(void) { return m_pTimer; } bool isPaused(void) { return m_bPaused; } void markedForDeletion(void) { m_bMarkedForDeletion = true; } bool isMarkedForDeletion(void) { return m_bMarkedForDeletion; } private: CCSchedulerScriptHandlerEntry(int nHandler) : CCScriptHandlerEntry(nHandler) , m_pTimer(NULL) , m_bPaused(false) , m_bMarkedForDeletion(false) { } bool init(float fInterval, bool bPaused); public: cocos2d::CCTimer* m_pTimer; bool m_bPaused; bool m_bMarkedForDeletion; }; /** * @js NA * @lua NA */ class CCTouchScriptHandlerEntry : public CCScriptHandlerEntry { public: static CCTouchScriptHandlerEntry* create(int nHandler, bool bIsMultiTouches, int nPriority, bool bSwallowsTouches); ~CCTouchScriptHandlerEntry(void); bool isMultiTouches(void) { return m_bIsMultiTouches; } int getPriority(void) { return m_nPriority; } bool getSwallowsTouches(void) { return m_bSwallowsTouches; } private: CCTouchScriptHandlerEntry(int nHandler) : CCScriptHandlerEntry(nHandler) , m_bIsMultiTouches(false) , m_nPriority(0) , m_bSwallowsTouches(false) { } bool init(bool bIsMultiTouches, int nPriority, bool bSwallowsTouches); public: bool m_bIsMultiTouches; int m_nPriority; bool m_bSwallowsTouches; }; // Don't make CCScriptEngineProtocol inherits from CCObject since setScriptEngine is invoked only once in AppDelegate.cpp, // It will affect the lifecycle of ScriptCore instance, the autorelease pool will be destroyed before destructing ScriptCore. // So a crash will appear on Win32 if you click the close button. /** * @js NA * @lua NA */ class CC_DLL CCScriptEngineProtocol { GEODE_FRIEND_MODIFY public: virtual ~CCScriptEngineProtocol() {}; /** Get script type */ virtual ccScriptType getScriptType() { return kScriptTypeNone; }; /** Remove script object. */ virtual void removeScriptObjectByCCObject(CCObject* pObj) = 0; /** Remove script function handler, only CCLuaEngine class need to implement this function. */ virtual void removeScriptHandler(int nHandler) {}; /** Reallocate script function handler, only CCLuaEngine class need to implement this function. */ virtual int reallocateScriptHandler(int nHandler) { return -1;} /** @brief Execute script code contained in the given string. @param codes holding the valid script code that should be executed. @return 0 if the string is executed correctly. @return other if the string is executed wrongly. */ virtual int executeString(const char* codes) = 0; /** @brief Execute a script file. @param filename String object holding the filename of the script file that is to be executed */ virtual int executeScriptFile(const char* filename) = 0; /** @brief Execute a scripted global function. @brief The function should not take any parameters and should return an integer. @param functionName String object holding the name of the function, in the global script environment, that is to be executed. @return The integer value returned from the script function. */ virtual int executeGlobalFunction(const char* functionName) = 0; /** @brief Execute a node event function @param pNode which node produce this event @param nAction kCCNodeOnEnter,kCCNodeOnExit,kCCMenuItemActivated,kCCNodeOnEnterTransitionDidFinish,kCCNodeOnExitTransitionDidStart @return The integer value returned from the script function. */ virtual int executeNodeEvent(CCNode* pNode, int nAction) = 0; virtual int executeMenuItemEvent(CCMenuItem* pMenuItem) = 0; /** Execute a notification event function */ virtual int executeNotificationEvent(CCNotificationCenter* pNotificationCenter, const char* pszName) = 0; /** execute a callfun event */ virtual int executeCallFuncActionEvent(CCCallFunc* pAction, CCObject* pTarget = NULL) = 0; /** execute a schedule function */ virtual int executeSchedule(int nHandler, float dt, CCNode* pNode = NULL) = 0; /** functions for executing touch event */ virtual int executeLayerTouchesEvent(CCLayer* pLayer, int eventType, CCSet *pTouches) = 0; virtual int executeLayerTouchEvent(CCLayer* pLayer, int eventType, CCTouch *pTouch) = 0; /** functions for keypad event */ virtual int executeLayerKeypadEvent(CCLayer* pLayer, int eventType) = 0; /** execute a accelerometer event */ virtual int executeAccelerometerEvent(CCLayer* pLayer, CCAcceleration* pAccelerationValue) = 0; /** function for common event */ virtual int executeEvent(int nHandler, const char* pEventName, CCObject* pEventSource = NULL, const char* pEventSourceClassName = NULL) = 0; /** function for c++ call back lua funtion */ virtual int executeEventWithArgs(int nHandler, CCArray* pArgs) { return 0; } /** called by CCAssert to allow scripting engine to handle failed assertions * @return true if the assert was handled by the script engine, false otherwise. */ virtual bool handleAssert(const char *msg) = 0; /** * */ enum ConfigType { NONE, COCOSTUDIO, }; virtual bool parseConfig(ConfigType type, const gd::string& str) = 0; }; /** CCScriptEngineManager is a singleton which holds an object instance of CCScriptEngineProtocl It helps cocos2d-x and the user code to find back LuaEngine object @since v0.99.5-x-0.8.5 @js NA @lua NA */ class CC_DLL CCScriptEngineManager { GEODE_FRIEND_MODIFY public: GEODE_CUSTOM_CONSTRUCTOR_BEGIN(CCScriptEngineManager) ~CCScriptEngineManager(void); CCScriptEngineProtocol* getScriptEngine(void) { return m_pScriptEngine; } void setScriptEngine(CCScriptEngineProtocol *pScriptEngine); void removeScriptEngine(void); static CCScriptEngineManager* sharedManager(void); static void purgeSharedManager(void); private: CCScriptEngineManager(void) : m_pScriptEngine(NULL) { } public: CCScriptEngineProtocol *m_pScriptEngine; }; // end of script_support group /// @} NS_CC_END #endif // __SCRIPT_SUPPORT_H__
0
0.932199
1
0.932199
game-dev
MEDIA
0.842521
game-dev
0.578033
1
0.578033
Maxlego08/zEssentials
5,879
src/main/java/fr/maxlego08/essentials/commands/commands/items/CommandItemLoreSet.java
package fr.maxlego08.essentials.commands.commands.items; import fr.maxlego08.essentials.api.EssentialsPlugin; import fr.maxlego08.essentials.api.commands.CommandResultType; import fr.maxlego08.essentials.api.commands.Permission; import fr.maxlego08.essentials.api.messages.Message; import fr.maxlego08.essentials.module.modules.ItemModule; import fr.maxlego08.essentials.zutils.utils.commands.VCommand; import fr.maxlego08.essentials.zutils.utils.paper.PaperComponent; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.TextDecoration; import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; import org.bukkit.NamespacedKey; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.persistence.PersistentDataContainer; import org.bukkit.persistence.PersistentDataType; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.IntStream; public class CommandItemLoreSet extends VCommand { private final NamespacedKey loreLineRaw; public CommandItemLoreSet(EssentialsPlugin plugin) { super(plugin); this.loreLineRaw = new NamespacedKey(plugin, "lore-line-raw"); this.setModule(ItemModule.class); this.setPermission(Permission.ESSENTIALS_ITEM_LORE_SET); this.setDescription(Message.DESCRIPTION_ITEM_LORE_SET); this.addSubCommand("set"); this.addRequireArg("index", (sender, args) -> { if (sender instanceof Player player) { ItemStack itemStack = player.getInventory().getItemInMainHand(); ItemMeta itemMeta = itemStack.getItemMeta(); if (itemMeta.hasLore()) { var lore = itemMeta.lore(); if (lore == null) return new ArrayList<>(); return IntStream.range(1, lore.size() + 1).mapToObj(String::valueOf).toList(); } } return new ArrayList<>(); }); this.addRequireArg("line", (sender, args) -> { if (sender instanceof Player player) { ItemStack itemStack = player.getInventory().getItemInMainHand(); ItemMeta itemMeta = itemStack.getItemMeta(); if (itemMeta.hasLore()) { var lore = itemMeta.lore(); if (lore == null) return new ArrayList<>(); try { int index = Integer.parseInt(args[1]) - 1; if (itemMeta.getPersistentDataContainer().has(this.loreLineRaw, PersistentDataType.STRING)) { var line = itemMeta.getPersistentDataContainer().getOrDefault(this.loreLineRaw, PersistentDataType.STRING, "").split(";"); return Arrays.asList(line[index]); } var component = lore.get(index); return List.of(component == null ? "" : colorReverse(LegacyComponentSerializer.legacyAmpersand().serialize(component))); } catch (Exception ignored) { } } } return new ArrayList<>(); }); this.setExtendedArgs(true); this.onlyPlayers(); } @Override protected CommandResultType perform(EssentialsPlugin plugin) { int index = this.argAsInteger(0); String loreLine = this.getArgs(2); if (loreLine.isEmpty()) return CommandResultType.SYNTAX_ERROR; ItemStack itemStack = this.player.getInventory().getItemInMainHand(); if (itemStack.getType().isAir()) { message(sender, Message.COMMAND_ITEM_EMPTY); return CommandResultType.DEFAULT; } ItemMeta itemMeta = itemStack.getItemMeta(); List<Component> components = itemMeta.hasLore() ? itemMeta.lore() : new ArrayList<>(); if (components == null) components = new ArrayList<>(); if (components.size() < index) { message(sender, Message.COMMAND_ITEM_LORE_SET_ERROR, "%line%", index); return CommandResultType.DEFAULT; } PaperComponent paperComponent = (PaperComponent) this.componentMessage; if (components.size() < index) { for (int i = components.size(); i < index; i++) { components.add(Component.text("")); } } components.set(index - 1, paperComponent.getComponent(loreLine).decorationIfAbsent(TextDecoration.ITALIC, TextDecoration.State.FALSE)); itemMeta.lore(components); PersistentDataContainer dataContainer = itemMeta.getPersistentDataContainer(); int newSize = itemMeta.lore() == null ? 1 : itemMeta.lore().size(); String[] rawLoreLines = dataContainer.has(loreLineRaw, PersistentDataType.STRING) ? dataContainer.getOrDefault(loreLineRaw, PersistentDataType.STRING, "").split(";") : new String[newSize]; if (rawLoreLines.length < newSize) { String[] newRawLoreLines = new String[newSize]; System.arraycopy(rawLoreLines, 0, newRawLoreLines, 0, rawLoreLines.length); rawLoreLines = newRawLoreLines; } for (int i = 0; i != components.size(); i++) { if (rawLoreLines[i] == null) { rawLoreLines[i] = colorReverse(LegacyComponentSerializer.legacyAmpersand().serialize(components.get(i))); } } rawLoreLines[index - 1] = loreLine; String rawLoreCombined = String.join(";", rawLoreLines); dataContainer.set(loreLineRaw, PersistentDataType.STRING, rawLoreCombined); itemStack.setItemMeta(itemMeta); message(sender, Message.COMMAND_ITEM_LORE_SET, "%text%", loreLine, "%line%", index); return CommandResultType.SUCCESS; } }
0
0.906465
1
0.906465
game-dev
MEDIA
0.986699
game-dev
0.983266
1
0.983266
Deadrik/TFCraft
15,930
src/Common/com/bioxx/tfc/TileEntities/TEForge.java
package com.bioxx.tfc.TileEntities; import java.util.Random; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import com.bioxx.tfc.Core.TFC_Core; import com.bioxx.tfc.Items.ItemBloom; import com.bioxx.tfc.Items.ItemMeltedMetal; import com.bioxx.tfc.api.*; import com.bioxx.tfc.api.Enums.EnumFuelMaterial; import com.bioxx.tfc.api.Interfaces.ISmeltable; import com.bioxx.tfc.api.TileEntities.TEFireEntity; public class TEForge extends TEFireEntity implements IInventory { public boolean isSmokeStackValid; public ItemStack fireItemStacks[]; private int smokeTimer; public TEForge() { super(); fuelTimeLeft = 200; fuelBurnTemp = 200; fireTemp = 20; isSmokeStackValid = false; fireItemStacks = new ItemStack[14]; maxFireTempScale = 2500; } private boolean validateSmokeStack() { if (!TFC_Core.isExposedToRain(worldObj, xCoord, yCoord, zCoord)) return true; else if (checkChimney(xCoord + 1, yCoord + 1, zCoord)) return true; else if (checkChimney(xCoord - 1, yCoord + 1, zCoord)) return true; else if (checkChimney(xCoord, yCoord + 1, zCoord + 1)) return true; else if (checkChimney(xCoord, yCoord + 1, zCoord - 1)) return true; else if (notOpaque(xCoord + 1, yCoord + 1, zCoord) && checkChimney(xCoord + 2, yCoord + 1, zCoord)) return true; else if (notOpaque(xCoord - 1, yCoord + 1, zCoord) && checkChimney(xCoord - 2, yCoord + 1, zCoord)) return true; else if (notOpaque(xCoord, yCoord + 1, zCoord + 1) && checkChimney(xCoord, yCoord + 1, zCoord + 2)) return true; else return notOpaque(xCoord, yCoord + 1, zCoord - 1) && checkChimney(xCoord, yCoord + 1, zCoord - 2); } private boolean checkChimney(int x, int y, int z) { return notOpaque(x, y, z) && worldObj.canBlockSeeTheSky(x, y, z); } private boolean notOpaque(int x, int y, int z) { return worldObj.blockExists(x, y, z) && !worldObj.getBlock(x, y, z).isOpaqueCube(); } private void genSmokeRoot(int x, int y, int z) { if(fuelTimeLeft >= 0) { if(worldObj.getBlock(x,y,z) != TFCBlocks.smoke) worldObj.setBlock(x, y, z, TFCBlocks.smoke); } else { worldObj.setBlockToAir(x, y, z); } } /*private class CoordDirection { int x; int y; int z; ForgeDirection dir; public CoordDirection(int x, int y, int z, ForgeDirection d) { this.x = x;this.y = y;this.z = z;this.dir = d; } }*/ @Override public void closeInventory() { } public void combineMetals(ItemStack inputItem, ItemStack destItem) { int d1 = 100 - inputItem.getItemDamage(); int d2 = 100 - destItem.getItemDamage(); destItem.setItemDamage(100 - (d1 + d2)); } public void cookItem(int i) { HeatRegistry manager = HeatRegistry.getInstance(); Random r = new Random(); if(fireItemStacks[i] != null) { HeatIndex index = manager.findMatchingIndex(fireItemStacks[i]); ItemStack inputCopy = fireItemStacks[i].copy(); if(index != null && TFC_ItemHeat.getTemp(fireItemStacks[i]) > index.meltTemp) { float temperature = TFC_ItemHeat.getTemp(fireItemStacks[i]); //int dam = fireItemStacks[i].getItemDamage(); // If not unshaped metal, morph the input to the output. If not an input with direct morph (sand, sticks, etc) this deletes the input item from the slot. if(!(fireItemStacks[i].getItem() instanceof ItemMeltedMetal)) fireItemStacks[i] = index.getMorph(); // Handle items that had a direct morph. if(fireItemStacks[i] != null) { HeatIndex morphIndex = manager.findMatchingIndex(fireItemStacks[i]); if(morphIndex != null) { // Apply old temperature to direct morphs that can continue to be heated. TFC_ItemHeat.setTemp(fireItemStacks[i], temperature); } } else if(index.hasOutput()) { ItemStack output = index.getOutput(inputCopy, r); if (inputCopy.getItem() instanceof ISmeltable) { ISmeltable smelt = (ISmeltable)inputCopy.getItem(); ItemStack meltedItem = new ItemStack(smelt.getMetalType(inputCopy).meltedItem); TFC_ItemHeat.setTemp(meltedItem, temperature); int units = smelt.getMetalReturnAmount(inputCopy); // Raw/Refined Blooms give at max 100 units to force players to split using the anvil if (inputCopy.getItem() instanceof ItemBloom) units = Math.min(100, units); while(units > 0 && getMold() != null) { ItemStack moldIS = this.getMold(); ItemStack outputCopy = meltedItem.copy(); if (units > 100) { units-= 100; moldIS.stackSize--; if(!addToStorage(outputCopy.copy())) { EntityItem ei = new EntityItem(worldObj, xCoord + 0.5, yCoord + 1.5, zCoord + 0.5, outputCopy); ei.motionX = 0; ei.motionY = 0; ei.motionZ = 0; worldObj.spawnEntityInWorld(ei); } } else if (units > 0) // Put the last item in the forge cooking slot, replacing the input. { outputCopy.setItemDamage(100-units); units = 0; moldIS.stackSize--; fireItemStacks[i] = outputCopy.copy(); } } } else { fireItemStacks[i] = output; } if(TFC_ItemHeat.isCookable(fireItemStacks[i]) > -1) { //if the input is a new item, then apply the old temperature to it TFC_ItemHeat.setTemp(fireItemStacks[i], temperature); } } } } } public boolean addToStorage(ItemStack is) { if(this.getStackInSlot(10) == null) { this.setInventorySlotContents(10, is); return true; } if(this.getStackInSlot(11) == null) { this.setInventorySlotContents(11, is); return true; } if(this.getStackInSlot(12) == null) { this.setInventorySlotContents(12, is); return true; } if(this.getStackInSlot(13) == null) { this.setInventorySlotContents(13, is); return true; } return false; } private ItemStack getMold() { if(fireItemStacks[10] != null && fireItemStacks[10].getItem() == TFCItems.ceramicMold && fireItemStacks[10].stackSize > 0) { return fireItemStacks[10]; } else if(fireItemStacks[11] != null && fireItemStacks[11].getItem() == TFCItems.ceramicMold && fireItemStacks[11].stackSize > 0) { return fireItemStacks[11]; } else if(fireItemStacks[12] != null && fireItemStacks[12].getItem() == TFCItems.ceramicMold && fireItemStacks[12].stackSize > 0) { return fireItemStacks[12]; } else if(fireItemStacks[13] != null && fireItemStacks[13].getItem() == TFCItems.ceramicMold && fireItemStacks[13].stackSize > 0) { return fireItemStacks[13]; } return null; } @Override public ItemStack decrStackSize(int i, int j) { if(fireItemStacks[i] != null) { if(fireItemStacks[i].stackSize <= j) { ItemStack is = fireItemStacks[i]; fireItemStacks[i] = null; return is; } ItemStack isSplit = fireItemStacks[i].splitStack(j); if(fireItemStacks[i].stackSize == 0) fireItemStacks[i] = null; return isSplit; } else return null; } public void ejectContents() { float f3 = 0.05F; EntityItem entityitem; Random rand = new Random(); float f = rand.nextFloat() * 0.8F + 0.1F; float f1 = rand.nextFloat() * 0.8F + 0.4F; float f2 = rand.nextFloat() * 0.8F + 0.1F; for (int i = 0; i < getSizeInventory(); i++) { if(fireItemStacks[i]!= null) { entityitem = new EntityItem(worldObj, xCoord + f, yCoord + f1, zCoord + f2, fireItemStacks[i]); entityitem.motionX = (float)rand.nextGaussian() * f3; entityitem.motionY = (float)rand.nextGaussian() * f3 + 0.2F; entityitem.motionZ = (float)rand.nextGaussian() * f3; worldObj.spawnEntityInWorld(entityitem); fireItemStacks[i] = null; } } } @Override public int getInventoryStackLimit() { return 64; } @Override public String getInventoryName() { return "Forge"; } public int getMoldIndex() { if(fireItemStacks[10] != null && fireItemStacks[10].getItem() == TFCItems.ceramicMold) return 10; if(fireItemStacks[11] != null && fireItemStacks[11].getItem() == TFCItems.ceramicMold) return 11; if(fireItemStacks[12] != null && fireItemStacks[12].getItem() == TFCItems.ceramicMold) return 12; if(fireItemStacks[13] != null && fireItemStacks[13].getItem() == TFCItems.ceramicMold) return 13; return -1; } @Override public int getSizeInventory() { return fireItemStacks.length; } @Override public ItemStack getStackInSlot(int i) { return fireItemStacks[i]; } @Override public ItemStack getStackInSlotOnClosing(int var1) { return null; } public void handleFuelStack() { Random random = new Random(); if(fireItemStacks[7] == null) { if(random.nextBoolean() && fireItemStacks[6] != null) { fireItemStacks[7] = fireItemStacks[6]; fireItemStacks[6] = null; } else { fireItemStacks[7] = fireItemStacks[8]; fireItemStacks[8] = null; } } if(fireItemStacks[6] == null) { if(fireItemStacks[5] != null) { fireItemStacks[6] = fireItemStacks[5]; fireItemStacks[5] = null; } } if(fireItemStacks[8] == null) { if(fireItemStacks[9] != null) { fireItemStacks[8] = fireItemStacks[9]; fireItemStacks[9] = null; } } } @Override public boolean isUseableByPlayer(EntityPlayer entityplayer) { return false; } @Override public void openInventory() { } @Override public void readFromNBT(NBTTagCompound nbt) { super.readFromNBT(nbt); isSmokeStackValid = nbt.getBoolean("isValid"); NBTTagList nbttaglist = nbt.getTagList("Items", 10); fireItemStacks = new ItemStack[getSizeInventory()]; for(int i = 0; i < nbttaglist.tagCount(); i++) { NBTTagCompound nbt1 = nbttaglist.getCompoundTagAt(i); byte byte0 = nbt1.getByte("Slot"); if(byte0 >= 0 && byte0 < fireItemStacks.length) fireItemStacks[byte0] = ItemStack.loadItemStackFromNBT(nbt1); } } @Override public void setInventorySlotContents(int i, ItemStack itemstack) { fireItemStacks[i] = itemstack; if(itemstack != null && itemstack.stackSize > getInventoryStackLimit()) itemstack.stackSize = getInventoryStackLimit(); } @Override public void updateEntity() { //Here we make sure that the forge is valid isSmokeStackValid = validateSmokeStack(); if(!worldObj.isRemote) { //Here we take care of the items that we are cooking in the fire careForInventorySlot(fireItemStacks[0]); careForInventorySlot(fireItemStacks[1]); careForInventorySlot(fireItemStacks[2]); careForInventorySlot(fireItemStacks[3]); careForInventorySlot(fireItemStacks[4]); ItemStack[] fuelStack = new ItemStack[9]; fuelStack[0] = fireItemStacks[5]; fuelStack[1] = fireItemStacks[6]; fuelStack[2] = fireItemStacks[7]; fuelStack[3] = fireItemStacks[8]; fuelStack[4] = fireItemStacks[9]; fuelStack[5] = fireItemStacks[10]; fuelStack[6] = fireItemStacks[11]; fuelStack[7] = fireItemStacks[12]; fuelStack[8] = fireItemStacks[13]; //Now we cook the input item cookItem(0); cookItem(1); cookItem(2); cookItem(3); cookItem(4); //push the input fuel down the stack handleFuelStack(); //Play the fire sound Random r = new Random(); if(r.nextInt(10) == 0 && fireTemp > 20) worldObj.playSoundEffect(xCoord, yCoord, zCoord, "fire.fire", 0.4F + (r.nextFloat() / 2), 0.7F + r.nextFloat()); if(fireTemp >= 20 && worldObj.getBlockMetadata(xCoord, yCoord, zCoord) != 1) worldObj.setBlockMetadataWithNotify(xCoord, yCoord, zCoord, 1, 3); else if(fireTemp < 20 && worldObj.getBlockMetadata(xCoord, yCoord, zCoord) != 0) worldObj.setBlockMetadataWithNotify(xCoord, yCoord, zCoord, 0, 3); //If the fire is still burning and has fuel if (fuelTimeLeft > 0 && fireTemp >= 1 && !TFC_Core.isExposedToRain(worldObj, xCoord, yCoord, zCoord)) { float desiredTemp = handleTemp(); handleTempFlux(desiredTemp); smokeTimer++; if(smokeTimer > 60) { smokeTimer = 0; createSmoke(); } if(TFCOptions.enableDebugMode) { fireTemp = 2000; fuelTimeLeft = 9999; } TFC_Core.handleItemTicking(fuelStack, worldObj, xCoord, yCoord, zCoord); } else if(fuelTimeLeft <= 0 && fireTemp >= 1 && fireItemStacks[7] != null && isSmokeStackValid) { //here we set the temp and burn time based on the fuel in the bottom slot. EnumFuelMaterial m = TFC_Core.getFuelMaterial(fireItemStacks[7]); fuelTimeLeft = m.burnTimeMax; fuelBurnTemp = m.burnTempMax; fuelTasteProfile = m.ordinal(); fireItemStacks[7] = null; } else { removeSmoke(); handleTempFlux(0); TFC_Core.handleItemTicking(this, worldObj, xCoord, yCoord, zCoord); } //Here we handle the bellows handleAirReduction(); //do a last minute check to verify stack size for(int c = 0; c < 5; c++) { if(fireItemStacks[c] != null) { if(fireItemStacks[c].stackSize <= 0) fireItemStacks[c].stackSize = 1; } } } } private void createSmoke() { if(!TFCOptions.generateSmoke) return; if (checkChimney(xCoord + 1, yCoord + 1, zCoord)) genSmokeRoot(xCoord+1, yCoord+1, zCoord); else if (checkChimney(xCoord - 1, yCoord + 1, zCoord)) genSmokeRoot(xCoord-1, yCoord+1, zCoord); else if (checkChimney(xCoord, yCoord + 1, zCoord + 1)) genSmokeRoot(xCoord, yCoord+1, zCoord+1); else if (checkChimney(xCoord, yCoord + 1, zCoord - 1)) genSmokeRoot(xCoord, yCoord+1, zCoord-1); else if (notOpaque(xCoord + 1, yCoord + 1, zCoord) && checkChimney(xCoord + 2, yCoord + 1, zCoord)) genSmokeRoot(xCoord+2, yCoord+1, zCoord); else if (notOpaque(xCoord - 1, yCoord + 1, zCoord) && checkChimney(xCoord - 2, yCoord + 1, zCoord)) genSmokeRoot(xCoord-2, yCoord+1, zCoord); else if (notOpaque(xCoord, yCoord + 1, zCoord + 1) && checkChimney(xCoord, yCoord + 1, zCoord + 2)) genSmokeRoot(xCoord, yCoord+1, zCoord+2); else if (notOpaque(xCoord, yCoord + 1, zCoord - 1) && checkChimney(xCoord, yCoord + 1, zCoord - 2)) genSmokeRoot(xCoord, yCoord+1, zCoord-2); } public void removeSmoke() { if (isSmoke(xCoord, yCoord + 1, zCoord)) worldObj.setBlockToAir(xCoord, yCoord+1, zCoord); else if (isSmoke(xCoord + 1, yCoord + 1, zCoord)) worldObj.setBlockToAir(xCoord+1, yCoord+1, zCoord); else if (isSmoke(xCoord - 1, yCoord + 1, zCoord)) worldObj.setBlockToAir(xCoord-1, yCoord+1, zCoord); else if (isSmoke(xCoord, yCoord + 1, zCoord + 1)) worldObj.setBlockToAir(xCoord, yCoord+1, zCoord+1); else if (isSmoke(xCoord, yCoord + 1, zCoord - 1)) worldObj.setBlockToAir(xCoord, yCoord+1, zCoord-1); else if (isSmoke(xCoord + 2, yCoord + 1, zCoord)) worldObj.setBlockToAir(xCoord+2, yCoord+1, zCoord); else if (isSmoke(xCoord - 2, yCoord + 1, zCoord)) worldObj.setBlockToAir(xCoord-2, yCoord+1, zCoord); else if (isSmoke(xCoord, yCoord + 1, zCoord + 2)) worldObj.setBlockToAir(xCoord, yCoord+1, zCoord+2); else if (isSmoke(xCoord, yCoord + 1, zCoord - 2)) worldObj.setBlockToAir(xCoord, yCoord+1, zCoord-2); } private boolean isSmoke(int x, int y, int z) { return worldObj.blockExists(x, y, z) && worldObj.getBlock(x, y, z) == TFCBlocks.smoke; } @Override public boolean hasCustomInventoryName() { return false; } @Override public boolean isItemValidForSlot(int i, ItemStack itemstack) { return false; } @Override public void writeToNBT(NBTTagCompound nbt) { super.writeToNBT(nbt); nbt.setBoolean("isValid", isSmokeStackValid); NBTTagList nbttaglist = new NBTTagList(); for(int i = 0; i < fireItemStacks.length; i++) { if(fireItemStacks[i] != null) { NBTTagCompound nbt1 = new NBTTagCompound(); nbt1.setByte("Slot", (byte)i); fireItemStacks[i].writeToNBT(nbt1); nbttaglist.appendTag(nbt1); } } nbt.setTag("Items", nbttaglist); } }
0
0.891868
1
0.891868
game-dev
MEDIA
0.981448
game-dev
0.952522
1
0.952522
TechPizzaDev/MinecraftServerSharp
1,160
MCServerSharp.Base/Maths/BlockPosition.cs
using System; namespace MCServerSharp.Maths { public readonly struct BlockPosition : IEquatable<BlockPosition>, ILongHashable { public int X { get; } public int Y { get; } public int Z { get; } public BlockPosition(int x, int y, int z) { X = x; Y = y; Z = z; } public bool Equals(BlockPosition other) { return X == other.X && Y == other.Y && Z == other.Z; } public override bool Equals(object? obj) { return obj is BlockPosition value && Equals(value); } public override int GetHashCode() { return HashCode.Combine(X, Y, Z); } public long GetLongHashCode() { return LongHashCode.Combine(X, Y, Z); } public static bool operator ==(BlockPosition left, BlockPosition right) { return left.Equals(right); } public static bool operator !=(BlockPosition left, BlockPosition right) { return !(left == right); } } }
0
0.908199
1
0.908199
game-dev
MEDIA
0.359742
game-dev
0.857338
1
0.857338
MJRLegends/ExtraPlanets
54,133
src/main/java/com/mjr/extraplanets/planets/Ceres/worldgen/village/StructureComponentVillageHouse.java
package com.mjr.extraplanets.planets.Ceres.worldgen.village; import java.util.List; import java.util.Random; import com.mjr.extraplanets.blocks.ExtraPlanets_Blocks; import com.mjr.extraplanets.blocks.planetAndMoonBlocks.BlockBasicCeres; import net.minecraft.init.Blocks; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.EnumFacing; import net.minecraft.world.World; import net.minecraft.world.gen.structure.StructureBoundingBox; import net.minecraft.world.gen.structure.StructureComponent; import net.minecraft.world.gen.structure.template.TemplateManager; import micdoodle8.mods.galacticraft.core.GCBlocks; import micdoodle8.mods.galacticraft.core.blocks.BlockTorchBase; public class StructureComponentVillageHouse extends StructureComponentVillage { private int averageGroundLevel = -1; public StructureComponentVillageHouse() { } public StructureComponentVillageHouse(StructureComponentVillageStartPiece par1ComponentVillageStartPiece, int par2, Random par3Random, StructureBoundingBox par4StructureBoundingBox, EnumFacing par5) { super(par1ComponentVillageStartPiece, par2); this.setCoordBaseMode(par5); this.boundingBox = par4StructureBoundingBox; } public static StructureComponentVillageHouse func_74921_a(StructureComponentVillageStartPiece par0ComponentVillageStartPiece, List<StructureComponent> par1List, Random rand, int par3, int par4, int par5, EnumFacing par6, int par7) { final StructureBoundingBox var8 = StructureBoundingBox.getComponentToAddBoundingBox(par3, par4, par5, 0, 0, 0, 17, 9, 17, par6); return StructureComponent.findIntersecting(par1List, var8) == null ? new StructureComponentVillageHouse(par0ComponentVillageStartPiece, par7, rand, var8, par6) : null; } @Override protected void writeStructureToNBT(NBTTagCompound nbt) { super.writeStructureToNBT(nbt); nbt.setInteger("AvgGroundLevel", this.averageGroundLevel); } @Override protected void readStructureFromNBT(NBTTagCompound nbt, TemplateManager manager) { super.readStructureFromNBT(nbt, manager); this.averageGroundLevel = nbt.getInteger("AvgGroundLevel"); } /** * second Part of Structure generating, this for example places Spiderwebs, Mob Spawners, it closes Mineshafts at the end, it adds Fences... */ @Override public boolean addComponentParts(World par1World, Random rand, StructureBoundingBox par3StructureBoundingBox) { if (this.averageGroundLevel < 0) { this.averageGroundLevel = this.getAverageGroundLevel(par1World, par3StructureBoundingBox); if (this.averageGroundLevel < 0) { return true; } this.boundingBox.offset(0, this.averageGroundLevel - this.boundingBox.maxY + 9 - 1, 0); } this.fillWithAir(par1World, par3StructureBoundingBox, 3, 0, 3, 13, 9, 13); this.fillWithAir(par1World, par3StructureBoundingBox, 5, 0, 2, 11, 9, 14); this.fillWithAir(par1World, par3StructureBoundingBox, 2, 0, 5, 14, 9, 11); for (int i = 3; i <= 13; i++) { for (int j = 3; j <= 13; j++) { this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState(), i, 0, j, par3StructureBoundingBox); } } for (int i = 5; i <= 11; i++) { for (int j = 2; j <= 14; j++) { this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState(), i, 0, j, par3StructureBoundingBox); } } for (int i = 2; i <= 14; i++) { for (int j = 5; j <= 11; j++) { this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState(), i, 0, j, par3StructureBoundingBox); } } int yLevel = 0; for (yLevel = -8; yLevel < 4; yLevel++) { this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 4, yLevel, 2, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 3, yLevel, 2, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 2, yLevel, 3, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 2, yLevel, 4, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 1, yLevel, 5, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 1, yLevel, 6, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 1, yLevel, 7, par3StructureBoundingBox); this.setBlockState(par1World, yLevel <= 1 ? ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE) : Blocks.AIR.getDefaultState(), 1, yLevel, 8, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 1, yLevel, 9, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 1, yLevel, 10, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 1, yLevel, 11, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 2, yLevel, 12, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 2, yLevel, 13, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 3, yLevel, 14, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 4, yLevel, 14, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 5, yLevel, 15, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 6, yLevel, 15, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 7, yLevel, 15, par3StructureBoundingBox); this.setBlockState(par1World, yLevel <= 1 ? ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE) : Blocks.AIR.getDefaultState(), 8, yLevel, 15, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 9, yLevel, 15, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 10, yLevel, 15, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 11, yLevel, 15, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 12, yLevel, 14, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 13, yLevel, 14, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 14, yLevel, 13, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 14, yLevel, 12, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 15, yLevel, 11, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 15, yLevel, 10, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 15, yLevel, 9, par3StructureBoundingBox); this.setBlockState(par1World, yLevel <= 1 ? ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE) : Blocks.AIR.getDefaultState(), 15, yLevel, 8, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 15, yLevel, 7, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 15, yLevel, 6, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 15, yLevel, 5, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 14, yLevel, 4, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 14, yLevel, 3, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 13, yLevel, 2, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 12, yLevel, 2, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 11, yLevel, 1, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 10, yLevel, 1, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 9, yLevel, 1, par3StructureBoundingBox); this.setBlockState(par1World, yLevel <= 1 ? ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE) : Blocks.AIR.getDefaultState(), 8, yLevel, 1, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 7, yLevel, 1, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 6, yLevel, 1, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 5, yLevel, 1, par3StructureBoundingBox); } yLevel = 4; this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 4, yLevel, 2, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 3, yLevel, 3, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 2, yLevel, 4, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 1, yLevel, 5, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 1, yLevel, 6, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 1, yLevel, 7, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 1, yLevel, 8, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 1, yLevel, 9, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 1, yLevel, 10, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 1, yLevel, 11, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 2, yLevel, 12, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 3, yLevel, 13, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 4, yLevel, 14, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 5, yLevel, 15, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 6, yLevel, 15, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 7, yLevel, 15, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 8, yLevel, 15, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 9, yLevel, 15, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 10, yLevel, 15, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 11, yLevel, 15, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 12, yLevel, 14, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 13, yLevel, 13, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 14, yLevel, 12, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 15, yLevel, 11, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 15, yLevel, 10, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 15, yLevel, 9, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 15, yLevel, 8, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 15, yLevel, 7, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 15, yLevel, 6, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 15, yLevel, 5, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 14, yLevel, 4, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 13, yLevel, 3, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 12, yLevel, 2, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 11, yLevel, 1, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 10, yLevel, 1, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 9, yLevel, 1, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 8, yLevel, 1, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 7, yLevel, 1, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 6, yLevel, 1, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 5, yLevel, 1, par3StructureBoundingBox); this.setBlockState(par1World, GCBlocks.glowstoneTorch.getDefaultState().withProperty(BlockTorchBase.FACING, this.getCoordBaseMode()), 8, yLevel, 2, par3StructureBoundingBox); this.setBlockState(par1World, GCBlocks.glowstoneTorch.getDefaultState().withProperty(BlockTorchBase.FACING, this.getCoordBaseMode().rotateY()), 14, yLevel, 8, par3StructureBoundingBox); this.setBlockState(par1World, GCBlocks.glowstoneTorch.getDefaultState().withProperty(BlockTorchBase.FACING, this.getCoordBaseMode().getOpposite()), 8, yLevel, 14, par3StructureBoundingBox); this.setBlockState(par1World, GCBlocks.glowstoneTorch.getDefaultState().withProperty(BlockTorchBase.FACING, this.getCoordBaseMode().rotateYCCW()), 2, yLevel, 8, par3StructureBoundingBox); yLevel = 5; // corner 1 this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 5, yLevel, 2, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 4, yLevel, 2, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 3, yLevel, 3, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 2, yLevel, 4, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 2, yLevel, 5, par3StructureBoundingBox); // side 1 this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 1, yLevel, 6, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 1, yLevel, 7, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 1, yLevel, 8, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 1, yLevel, 9, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 1, yLevel, 10, par3StructureBoundingBox); // corner 2 this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 2, yLevel, 11, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 2, yLevel, 12, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 3, yLevel, 13, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 4, yLevel, 14, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 5, yLevel, 14, par3StructureBoundingBox); // side 2 this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 6, yLevel, 15, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 7, yLevel, 15, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 8, yLevel, 15, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 9, yLevel, 15, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 10, yLevel, 15, par3StructureBoundingBox); // corner 3 this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 11, yLevel, 14, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 12, yLevel, 14, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 13, yLevel, 13, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 14, yLevel, 12, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 14, yLevel, 11, par3StructureBoundingBox); // side 3 this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 15, yLevel, 10, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 15, yLevel, 9, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 15, yLevel, 8, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 15, yLevel, 7, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 15, yLevel, 6, par3StructureBoundingBox); // corner 4 this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 14, yLevel, 5, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 14, yLevel, 4, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 13, yLevel, 3, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 12, yLevel, 2, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 11, yLevel, 2, par3StructureBoundingBox); // side 4 this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 10, yLevel, 1, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 9, yLevel, 1, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 8, yLevel, 1, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 7, yLevel, 1, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 6, yLevel, 1, par3StructureBoundingBox); yLevel = 6; // corner 1 this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 4, yLevel, 3, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 3, yLevel, 4, par3StructureBoundingBox); // side 1 this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 2, yLevel, 5, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 2, yLevel, 6, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 2, yLevel, 7, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 2, yLevel, 8, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 2, yLevel, 9, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 2, yLevel, 10, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 2, yLevel, 11, par3StructureBoundingBox); // corner 2 this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 3, yLevel, 12, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 4, yLevel, 13, par3StructureBoundingBox); // side 2 this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 5, yLevel, 14, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 6, yLevel, 14, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 7, yLevel, 14, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 8, yLevel, 14, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 9, yLevel, 14, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 10, yLevel, 14, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 11, yLevel, 14, par3StructureBoundingBox); // corner 3 this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 12, yLevel, 13, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 13, yLevel, 12, par3StructureBoundingBox); // side 3 this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 14, yLevel, 11, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 14, yLevel, 10, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 14, yLevel, 9, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 14, yLevel, 8, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 14, yLevel, 7, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 14, yLevel, 6, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 14, yLevel, 5, par3StructureBoundingBox); // corner 4 this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 13, yLevel, 4, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 12, yLevel, 3, par3StructureBoundingBox); // side 4 this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 11, yLevel, 2, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 10, yLevel, 2, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 9, yLevel, 2, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 8, yLevel, 2, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 7, yLevel, 2, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 6, yLevel, 2, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 5, yLevel, 2, par3StructureBoundingBox); yLevel = 7; // corner 1 this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 6, yLevel, 3, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 5, yLevel, 3, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 4, yLevel, 4, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 3, yLevel, 5, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 3, yLevel, 6, par3StructureBoundingBox); // side 1 this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 2, yLevel, 7, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 2, yLevel, 8, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 2, yLevel, 9, par3StructureBoundingBox); // corner 2 this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 3, yLevel, 10, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 3, yLevel, 11, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 4, yLevel, 12, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 5, yLevel, 13, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 6, yLevel, 13, par3StructureBoundingBox); // side 2 this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 7, yLevel, 14, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 8, yLevel, 14, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 9, yLevel, 14, par3StructureBoundingBox); // corner 3 this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 10, yLevel, 13, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 11, yLevel, 13, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 12, yLevel, 12, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 13, yLevel, 11, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 13, yLevel, 10, par3StructureBoundingBox); // side 3 this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 14, yLevel, 9, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 14, yLevel, 8, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 14, yLevel, 7, par3StructureBoundingBox); // corner 4 this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 13, yLevel, 6, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 13, yLevel, 5, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 12, yLevel, 4, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 11, yLevel, 3, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 10, yLevel, 3, par3StructureBoundingBox); // side 4 this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 9, yLevel, 2, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 8, yLevel, 2, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 7, yLevel, 2, par3StructureBoundingBox); yLevel = 8; // corner 1 this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 6, yLevel, 4, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 5, yLevel, 4, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 4, yLevel, 5, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 4, yLevel, 6, par3StructureBoundingBox); // side 1 this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 3, yLevel, 7, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 3, yLevel, 8, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 3, yLevel, 9, par3StructureBoundingBox); // corner 2 this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 4, yLevel, 10, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 4, yLevel, 11, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 5, yLevel, 12, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 6, yLevel, 12, par3StructureBoundingBox); // side 2 this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 7, yLevel, 13, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 8, yLevel, 13, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 9, yLevel, 13, par3StructureBoundingBox); // corner 3 this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 10, yLevel, 12, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 11, yLevel, 12, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 12, yLevel, 11, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 12, yLevel, 10, par3StructureBoundingBox); // side 3 this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 13, yLevel, 9, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 13, yLevel, 8, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 13, yLevel, 7, par3StructureBoundingBox); // corner 4 this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 12, yLevel, 6, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 12, yLevel, 5, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 11, yLevel, 4, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 10, yLevel, 4, par3StructureBoundingBox); // side 4 this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 9, yLevel, 3, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 8, yLevel, 3, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 7, yLevel, 3, par3StructureBoundingBox); // extras this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 5, yLevel, 5, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 5, yLevel, 11, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 11, yLevel, 11, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 11, yLevel, 5, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 4, yLevel, 7, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 4, yLevel, 8, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 4, yLevel, 9, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 7, yLevel, 12, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 8, yLevel, 12, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 9, yLevel, 12, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 9, yLevel, 4, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 8, yLevel, 4, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 7, yLevel, 4, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 12, yLevel, 7, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 12, yLevel, 8, par3StructureBoundingBox); this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), 12, yLevel, 9, par3StructureBoundingBox); yLevel = 9; for (int i = 5; i <= 11; i++) { for (int j = 5; j <= 11; j++) { if (!(j == 5 && i == 5 || j == 5 && i == 11 || j == 11 && i == 5 || j == 11 && i == 11)) { if (i >= 7 && i <= 9 && j >= 7 && j <= 9) { this.setBlockState(par1World, Blocks.GLASS.getDefaultState(), i, yLevel, j, par3StructureBoundingBox); } else { this.setBlockState(par1World, ExtraPlanets_Blocks.CERES_BLOCKS.getDefaultState().withProperty(BlockBasicCeres.BASIC_TYPE, BlockBasicCeres.EnumBlockBasic.STONE), i, yLevel, j, par3StructureBoundingBox); } } } } this.spawnVillagers(par1World, par3StructureBoundingBox, 6, 5, 6, 4); return true; } }
0
0.840676
1
0.840676
game-dev
MEDIA
0.884365
game-dev
0.935054
1
0.935054