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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Tencent/behaviac | 4,515 | tutorials/tutorial_1/unity/Assets/Scripts/behaviac/runtime/BehaviorTree/Nodes/Composites/Selectorstochastic.cs | /////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Tencent is pleased to support the open source community by making behaviac available.
//
// Copyright (C) 2015-2017 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at http://opensource.org/licenses/BSD-3-Clause
//
// 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.
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using System.Collections.Generic;
namespace behaviac
{
/**
the Selector runs the children from the first sequentially until the child which returns success.
for SelectorStochastic, the children are not sequentially selected, instead it is selected stochasticly.
for example: the children might be [0, 1, 2, 3, 4]
Selector always select the child by the order of 0, 1, 2, 3, 4
while SelectorStochastic, sometime, it is [4, 2, 0, 1, 3], sometime, it is [2, 3, 0, 4, 1], etc.
*/
public class SelectorStochastic : CompositeStochastic
{
protected override void load(int version, string agentType, List<property_t> properties)
{
base.load(version, agentType, properties);
}
public override bool IsValid(Agent pAgent, BehaviorTask pTask)
{
if (!(pTask.GetNode() is SelectorStochastic))
{
return false;
}
return base.IsValid(pAgent, pTask);
}
protected override BehaviorTask createTask()
{
SelectorStochasticTask pTask = new SelectorStochasticTask();
return pTask;
}
private class SelectorStochasticTask : CompositeStochasticTask
{
protected override void addChild(BehaviorTask pBehavior)
{
base.addChild(pBehavior);
}
public override void copyto(BehaviorTask target)
{
base.copyto(target);
}
public override void save(ISerializableNode node)
{
base.save(node);
}
public override void load(ISerializableNode node)
{
base.load(node);
}
protected override bool onenter(Agent pAgent)
{
base.onenter(pAgent);
return true;
}
protected override void onexit(Agent pAgent, EBTStatus s)
{
base.onexit(pAgent, s);
base.onexit(pAgent, s);
}
protected override EBTStatus update(Agent pAgent, EBTStatus childStatus)
{
EBTStatus s = childStatus;
Debug.Check(this.m_activeChildIndex < this.m_children.Count);
SelectorStochastic node = this.m_node as SelectorStochastic;
// Keep going until a child behavior says its running.
for (; ;)
{
if (s == EBTStatus.BT_RUNNING)
{
int childIndex = this.m_set[this.m_activeChildIndex];
BehaviorTask pBehavior = this.m_children[childIndex];
if (node.CheckIfInterrupted(pAgent))
{
return EBTStatus.BT_FAILURE;
}
s = pBehavior.exec(pAgent);
}
// If the child succeeds, or keeps running, do the same.
if (s != EBTStatus.BT_FAILURE)
{
return s;
}
// Hit the end of the array, job done!
++this.m_activeChildIndex;
if (this.m_activeChildIndex >= this.m_children.Count)
{
return EBTStatus.BT_FAILURE;
}
s = EBTStatus.BT_RUNNING;
}
}
}
}
}
| 1 | 0.941795 | 1 | 0.941795 | game-dev | MEDIA | 0.479033 | game-dev | 0.989191 | 1 | 0.989191 |
CliMA/ClimateMachine.jl | 1,092 | src/Atmos/Model/bc_initstate.jl | using ..Mesh.Grids: _x1, _x2, _x3
"""
InitStateBC
Set the value at the boundary to match the `init_state_prognostic!` function. This is
mainly useful for cases where the problem has an explicit solution.
# TODO: This should be fixed later once BCs are figured out (likely want
# different things here?)
"""
struct InitStateBC end
function boundary_state!(
::Union{NumericalFluxFirstOrder, NumericalFluxGradient},
bc::InitStateBC,
m::AtmosModel,
state⁺::Vars,
aux⁺::Vars,
n⁻,
state⁻::Vars,
aux⁻::Vars,
t,
_...,
)
# Put cood in a NamedTuple to mimmic LocalGeometry
init_state_prognostic!(m, state⁺, aux⁺, (coord = aux⁺.coord,), t)
end
function boundary_state!(
::NumericalFluxSecondOrder,
bc::InitStateBC,
m::AtmosModel,
state⁺::Vars,
diff⁺::Vars,
hyperdiff⁺::Vars,
aux⁺::Vars,
n⁻,
state⁻::Vars,
diff⁻::Vars,
hyperdiff⁻::Vars,
aux⁻::Vars,
t,
args...,
)
# Put coord in a NamedTuple to mimmic LocalGeometry
init_state_prognostic!(m, state⁺, aux⁺, (coord = aux⁺.coord,), t)
end
| 1 | 0.90978 | 1 | 0.90978 | game-dev | MEDIA | 0.425101 | game-dev | 0.788519 | 1 | 0.788519 |
PavelZinchenko/event_horizon | 31,042 | Starship/Assets/Scripts/GameDatabase/GeneratedGameCode/Database.cs | //-------------------------------------------------------------------------------
//
// This code was automatically generated.
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
//
//-------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using GameDatabase.DataModel;
using GameDatabase.Storage;
using GameDatabase.Model;
namespace GameDatabase
{
public partial interface IDatabase
{
DatabaseSettings DatabaseSettings { get; }
ExplorationSettings ExplorationSettings { get; }
GalaxySettings GalaxySettings { get; }
ShipSettings ShipSettings { get; }
IEnumerable<AmmunitionObsolete> AmmunitionObsoleteList { get; }
IEnumerable<Component> ComponentList { get; }
IEnumerable<ComponentMod> ComponentModList { get; }
IEnumerable<ComponentStats> ComponentStatsList { get; }
IEnumerable<Device> DeviceList { get; }
IEnumerable<DroneBay> DroneBayList { get; }
IEnumerable<Faction> FactionList { get; }
IEnumerable<Satellite> SatelliteList { get; }
IEnumerable<SatelliteBuild> SatelliteBuildList { get; }
IEnumerable<Ship> ShipList { get; }
IEnumerable<ShipBuild> ShipBuildList { get; }
IEnumerable<Skill> SkillList { get; }
IEnumerable<Technology> TechnologyList { get; }
IEnumerable<Character> CharacterList { get; }
IEnumerable<Fleet> FleetList { get; }
IEnumerable<LootModel> LootList { get; }
IEnumerable<QuestModel> QuestList { get; }
IEnumerable<QuestItem> QuestItemList { get; }
IEnumerable<Ammunition> AmmunitionList { get; }
IEnumerable<BulletPrefab> BulletPrefabList { get; }
IEnumerable<VisualEffect> VisualEffectList { get; }
IEnumerable<Weapon> WeaponList { get; }
AmmunitionObsolete GetAmmunitionObsolete(ItemId<AmmunitionObsolete> id);
Component GetComponent(ItemId<Component> id);
ComponentMod GetComponentMod(ItemId<ComponentMod> id);
ComponentStats GetComponentStats(ItemId<ComponentStats> id);
Device GetDevice(ItemId<Device> id);
DroneBay GetDroneBay(ItemId<DroneBay> id);
Faction GetFaction(ItemId<Faction> id);
Satellite GetSatellite(ItemId<Satellite> id);
SatelliteBuild GetSatelliteBuild(ItemId<SatelliteBuild> id);
Ship GetShip(ItemId<Ship> id);
ShipBuild GetShipBuild(ItemId<ShipBuild> id);
Skill GetSkill(ItemId<Skill> id);
Technology GetTechnology(ItemId<Technology> id);
Character GetCharacter(ItemId<Character> id);
Fleet GetFleet(ItemId<Fleet> id);
LootModel GetLoot(ItemId<LootModel> id);
QuestModel GetQuest(ItemId<QuestModel> id);
QuestItem GetQuestItem(ItemId<QuestItem> id);
Ammunition GetAmmunition(ItemId<Ammunition> id);
BulletPrefab GetBulletPrefab(ItemId<BulletPrefab> id);
VisualEffect GetVisualEffect(ItemId<VisualEffect> id);
Weapon GetWeapon(ItemId<Weapon> id);
ImageData GetImage(string name);
AudioClipData GetAudioClip(string name);
string GetLocalization(string language);
}
public partial class Database : IDatabase
{
public DatabaseSettings DatabaseSettings { get; private set; }
public ExplorationSettings ExplorationSettings { get; private set; }
public GalaxySettings GalaxySettings { get; private set; }
public ShipSettings ShipSettings { get; private set; }
public IEnumerable<AmmunitionObsolete> AmmunitionObsoleteList => _ammunitionObsoleteMap.Values;
public IEnumerable<Component> ComponentList => _componentMap.Values;
public IEnumerable<ComponentMod> ComponentModList => _componentModMap.Values;
public IEnumerable<ComponentStats> ComponentStatsList => _componentStatsMap.Values;
public IEnumerable<Device> DeviceList => _deviceMap.Values;
public IEnumerable<DroneBay> DroneBayList => _droneBayMap.Values;
public IEnumerable<Faction> FactionList => _factionMap.Values;
public IEnumerable<Satellite> SatelliteList => _satelliteMap.Values;
public IEnumerable<SatelliteBuild> SatelliteBuildList => _satelliteBuildMap.Values;
public IEnumerable<Ship> ShipList => _shipMap.Values;
public IEnumerable<ShipBuild> ShipBuildList => _shipBuildMap.Values;
public IEnumerable<Skill> SkillList => _skillMap.Values;
public IEnumerable<Technology> TechnologyList => _technologyMap.Values;
public IEnumerable<Character> CharacterList => _characterMap.Values;
public IEnumerable<Fleet> FleetList => _fleetMap.Values;
public IEnumerable<LootModel> LootList => _lootMap.Values;
public IEnumerable<QuestModel> QuestList => _questMap.Values;
public IEnumerable<QuestItem> QuestItemList => _questItemMap.Values;
public IEnumerable<Ammunition> AmmunitionList => _ammunitionMap.Values;
public IEnumerable<BulletPrefab> BulletPrefabList => _bulletPrefabMap.Values;
public IEnumerable<VisualEffect> VisualEffectList => _visualEffectMap.Values;
public IEnumerable<Weapon> WeaponList => _weaponMap.Values;
public AmmunitionObsolete GetAmmunitionObsolete(ItemId<AmmunitionObsolete> id) { return (_ammunitionObsoleteMap.TryGetValue(id.Value, out var item)) ? item : AmmunitionObsolete.DefaultValue; }
public Component GetComponent(ItemId<Component> id) { return (_componentMap.TryGetValue(id.Value, out var item)) ? item : Component.DefaultValue; }
public ComponentMod GetComponentMod(ItemId<ComponentMod> id) { return (_componentModMap.TryGetValue(id.Value, out var item)) ? item : ComponentMod.DefaultValue; }
public ComponentStats GetComponentStats(ItemId<ComponentStats> id) { return (_componentStatsMap.TryGetValue(id.Value, out var item)) ? item : ComponentStats.DefaultValue; }
public Device GetDevice(ItemId<Device> id) { return (_deviceMap.TryGetValue(id.Value, out var item)) ? item : Device.DefaultValue; }
public DroneBay GetDroneBay(ItemId<DroneBay> id) { return (_droneBayMap.TryGetValue(id.Value, out var item)) ? item : DroneBay.DefaultValue; }
public Faction GetFaction(ItemId<Faction> id) { return (_factionMap.TryGetValue(id.Value, out var item)) ? item : Faction.DefaultValue; }
public Satellite GetSatellite(ItemId<Satellite> id) { return (_satelliteMap.TryGetValue(id.Value, out var item)) ? item : Satellite.DefaultValue; }
public SatelliteBuild GetSatelliteBuild(ItemId<SatelliteBuild> id) { return (_satelliteBuildMap.TryGetValue(id.Value, out var item)) ? item : SatelliteBuild.DefaultValue; }
public Ship GetShip(ItemId<Ship> id) { return (_shipMap.TryGetValue(id.Value, out var item)) ? item : Ship.DefaultValue; }
public ShipBuild GetShipBuild(ItemId<ShipBuild> id) { return (_shipBuildMap.TryGetValue(id.Value, out var item)) ? item : ShipBuild.DefaultValue; }
public Skill GetSkill(ItemId<Skill> id) { return (_skillMap.TryGetValue(id.Value, out var item)) ? item : Skill.DefaultValue; }
public Technology GetTechnology(ItemId<Technology> id) { return (_technologyMap.TryGetValue(id.Value, out var item)) ? item : Technology.DefaultValue; }
public Character GetCharacter(ItemId<Character> id) { return (_characterMap.TryGetValue(id.Value, out var item)) ? item : Character.DefaultValue; }
public Fleet GetFleet(ItemId<Fleet> id) { return (_fleetMap.TryGetValue(id.Value, out var item)) ? item : Fleet.DefaultValue; }
public LootModel GetLoot(ItemId<LootModel> id) { return (_lootMap.TryGetValue(id.Value, out var item)) ? item : LootModel.DefaultValue; }
public QuestModel GetQuest(ItemId<QuestModel> id) { return (_questMap.TryGetValue(id.Value, out var item)) ? item : QuestModel.DefaultValue; }
public QuestItem GetQuestItem(ItemId<QuestItem> id) { return (_questItemMap.TryGetValue(id.Value, out var item)) ? item : QuestItem.DefaultValue; }
public Ammunition GetAmmunition(ItemId<Ammunition> id) { return (_ammunitionMap.TryGetValue(id.Value, out var item)) ? item : Ammunition.DefaultValue; }
public BulletPrefab GetBulletPrefab(ItemId<BulletPrefab> id) { return (_bulletPrefabMap.TryGetValue(id.Value, out var item)) ? item : BulletPrefab.DefaultValue; }
public VisualEffect GetVisualEffect(ItemId<VisualEffect> id) { return (_visualEffectMap.TryGetValue(id.Value, out var item)) ? item : VisualEffect.DefaultValue; }
public Weapon GetWeapon(ItemId<Weapon> id) { return (_weaponMap.TryGetValue(id.Value, out var item)) ? item : Weapon.DefaultValue; }
public ImageData GetImage(string name) { return _images.TryGetValue(name, out var image) ? image : ImageData.Empty; }
public AudioClipData GetAudioClip(string name) { return _audioClips.TryGetValue(name, out var audioClip) ? audioClip : AudioClipData.Empty; }
public string GetLocalization(string language) { return _localizations.TryGetValue(language, out var data) ? data : null; }
private void Clear()
{
_ammunitionObsoleteMap.Clear();
_componentMap.Clear();
_componentModMap.Clear();
_componentStatsMap.Clear();
_deviceMap.Clear();
_droneBayMap.Clear();
_factionMap.Clear();
_satelliteMap.Clear();
_satelliteBuildMap.Clear();
_shipMap.Clear();
_shipBuildMap.Clear();
_skillMap.Clear();
_technologyMap.Clear();
_characterMap.Clear();
_fleetMap.Clear();
_lootMap.Clear();
_questMap.Clear();
_questItemMap.Clear();
_ammunitionMap.Clear();
_bulletPrefabMap.Clear();
_visualEffectMap.Clear();
_weaponMap.Clear();
DatabaseSettings = null;
ExplorationSettings = null;
GalaxySettings = null;
ShipSettings = null;
_images.Clear();
_audioClips.Clear();
_localizations.Clear();
}
private readonly Dictionary<int, AmmunitionObsolete> _ammunitionObsoleteMap = new Dictionary<int, AmmunitionObsolete>();
private readonly Dictionary<int, Component> _componentMap = new Dictionary<int, Component>();
private readonly Dictionary<int, ComponentMod> _componentModMap = new Dictionary<int, ComponentMod>();
private readonly Dictionary<int, ComponentStats> _componentStatsMap = new Dictionary<int, ComponentStats>();
private readonly Dictionary<int, Device> _deviceMap = new Dictionary<int, Device>();
private readonly Dictionary<int, DroneBay> _droneBayMap = new Dictionary<int, DroneBay>();
private readonly Dictionary<int, Faction> _factionMap = new Dictionary<int, Faction>();
private readonly Dictionary<int, Satellite> _satelliteMap = new Dictionary<int, Satellite>();
private readonly Dictionary<int, SatelliteBuild> _satelliteBuildMap = new Dictionary<int, SatelliteBuild>();
private readonly Dictionary<int, Ship> _shipMap = new Dictionary<int, Ship>();
private readonly Dictionary<int, ShipBuild> _shipBuildMap = new Dictionary<int, ShipBuild>();
private readonly Dictionary<int, Skill> _skillMap = new Dictionary<int, Skill>();
private readonly Dictionary<int, Technology> _technologyMap = new Dictionary<int, Technology>();
private readonly Dictionary<int, Character> _characterMap = new Dictionary<int, Character>();
private readonly Dictionary<int, Fleet> _fleetMap = new Dictionary<int, Fleet>();
private readonly Dictionary<int, LootModel> _lootMap = new Dictionary<int, LootModel>();
private readonly Dictionary<int, QuestModel> _questMap = new Dictionary<int, QuestModel>();
private readonly Dictionary<int, QuestItem> _questItemMap = new Dictionary<int, QuestItem>();
private readonly Dictionary<int, Ammunition> _ammunitionMap = new Dictionary<int, Ammunition>();
private readonly Dictionary<int, BulletPrefab> _bulletPrefabMap = new Dictionary<int, BulletPrefab>();
private readonly Dictionary<int, VisualEffect> _visualEffectMap = new Dictionary<int, VisualEffect>();
private readonly Dictionary<int, Weapon> _weaponMap = new Dictionary<int, Weapon>();
private readonly Dictionary<string, ImageData> _images = new Dictionary<string, ImageData>(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, AudioClipData> _audioClips = new Dictionary<string, AudioClipData>(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, string> _localizations = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
public class Loader
{
public static void Load(Database database, DatabaseContent content)
{
var loader = new Loader(database, content);
loader.Load();
}
private Loader(Database database, DatabaseContent content)
{
_database = database;
_content = content;
}
public void Load()
{
foreach (var item in _content.AmmunitionObsoleteList)
if (!item.Disabled && !_database._ammunitionObsoleteMap.ContainsKey(item.Id))
AmmunitionObsolete.Create(item, this);
foreach (var item in _content.ComponentList)
if (!item.Disabled && !_database._componentMap.ContainsKey(item.Id))
Component.Create(item, this);
foreach (var item in _content.ComponentModList)
if (!item.Disabled && !_database._componentModMap.ContainsKey(item.Id))
ComponentMod.Create(item, this);
foreach (var item in _content.ComponentStatsList)
if (!item.Disabled && !_database._componentStatsMap.ContainsKey(item.Id))
ComponentStats.Create(item, this);
foreach (var item in _content.DeviceList)
if (!item.Disabled && !_database._deviceMap.ContainsKey(item.Id))
Device.Create(item, this);
foreach (var item in _content.DroneBayList)
if (!item.Disabled && !_database._droneBayMap.ContainsKey(item.Id))
DroneBay.Create(item, this);
foreach (var item in _content.FactionList)
if (!item.Disabled && !_database._factionMap.ContainsKey(item.Id))
Faction.Create(item, this);
foreach (var item in _content.SatelliteList)
if (!item.Disabled && !_database._satelliteMap.ContainsKey(item.Id))
Satellite.Create(item, this);
foreach (var item in _content.SatelliteBuildList)
if (!item.Disabled && !_database._satelliteBuildMap.ContainsKey(item.Id))
SatelliteBuild.Create(item, this);
foreach (var item in _content.ShipList)
if (!item.Disabled && !_database._shipMap.ContainsKey(item.Id))
Ship.Create(item, this);
foreach (var item in _content.ShipBuildList)
if (!item.Disabled && !_database._shipBuildMap.ContainsKey(item.Id))
ShipBuild.Create(item, this);
foreach (var item in _content.SkillList)
if (!item.Disabled && !_database._skillMap.ContainsKey(item.Id))
Skill.Create(item, this);
foreach (var item in _content.TechnologyList)
if (!item.Disabled && !_database._technologyMap.ContainsKey(item.Id))
Technology.Create(item, this);
foreach (var item in _content.CharacterList)
if (!item.Disabled && !_database._characterMap.ContainsKey(item.Id))
Character.Create(item, this);
foreach (var item in _content.FleetList)
if (!item.Disabled && !_database._fleetMap.ContainsKey(item.Id))
Fleet.Create(item, this);
foreach (var item in _content.LootList)
if (!item.Disabled && !_database._lootMap.ContainsKey(item.Id))
LootModel.Create(item, this);
foreach (var item in _content.QuestList)
if (!item.Disabled && !_database._questMap.ContainsKey(item.Id))
QuestModel.Create(item, this);
foreach (var item in _content.QuestItemList)
if (!item.Disabled && !_database._questItemMap.ContainsKey(item.Id))
QuestItem.Create(item, this);
foreach (var item in _content.AmmunitionList)
if (!item.Disabled && !_database._ammunitionMap.ContainsKey(item.Id))
Ammunition.Create(item, this);
foreach (var item in _content.BulletPrefabList)
if (!item.Disabled && !_database._bulletPrefabMap.ContainsKey(item.Id))
BulletPrefab.Create(item, this);
foreach (var item in _content.VisualEffectList)
if (!item.Disabled && !_database._visualEffectMap.ContainsKey(item.Id))
VisualEffect.Create(item, this);
foreach (var item in _content.WeaponList)
if (!item.Disabled && !_database._weaponMap.ContainsKey(item.Id))
Weapon.Create(item, this);
foreach (var item in _content.Images)
if (!_database._images.ContainsKey(item.Key))
_database._images.Add(item.Key, item.Value);
foreach (var item in _content.AudioClips)
if (!_database._audioClips.ContainsKey(item.Key))
_database._audioClips.Add(item.Key, item.Value);
foreach (var item in _content.Localizations)
if (!_database._localizations.ContainsKey(item.Key))
_database._localizations.Add(item.Key, item.Value);
if (_database.DatabaseSettings == null)
_database.DatabaseSettings = DatabaseSettings.Create(_content.DatabaseSettings ?? new Serializable.DatabaseSettingsSerializable { ItemType = Enums.ItemType.DatabaseSettings }, this);
if (_database.ExplorationSettings == null)
_database.ExplorationSettings = ExplorationSettings.Create(_content.ExplorationSettings ?? new Serializable.ExplorationSettingsSerializable { ItemType = Enums.ItemType.ExplorationSettings }, this);
if (_database.GalaxySettings == null)
_database.GalaxySettings = GalaxySettings.Create(_content.GalaxySettings ?? new Serializable.GalaxySettingsSerializable { ItemType = Enums.ItemType.GalaxySettings }, this);
if (_database.ShipSettings == null)
_database.ShipSettings = ShipSettings.Create(_content.ShipSettings ?? new Serializable.ShipSettingsSerializable { ItemType = Enums.ItemType.ShipSettings }, this);
}
public AmmunitionObsolete GetAmmunitionObsolete(ItemId<AmmunitionObsolete> id, bool notNull = false)
{
if (_database._ammunitionObsoleteMap.TryGetValue(id.Value, out var item)) return item;
var serializable = _content.GetAmmunitionObsolete(id.Value);
if (serializable != null && !serializable.Disabled) return AmmunitionObsolete.Create(serializable, this);
var value = AmmunitionObsolete.DefaultValue;
if (notNull && value == null) throw new DatabaseException("Data not found " + id);
return value;
}
public Component GetComponent(ItemId<Component> id, bool notNull = false)
{
if (_database._componentMap.TryGetValue(id.Value, out var item)) return item;
var serializable = _content.GetComponent(id.Value);
if (serializable != null && !serializable.Disabled) return Component.Create(serializable, this);
var value = Component.DefaultValue;
if (notNull && value == null) throw new DatabaseException("Data not found " + id);
return value;
}
public ComponentMod GetComponentMod(ItemId<ComponentMod> id, bool notNull = false)
{
if (_database._componentModMap.TryGetValue(id.Value, out var item)) return item;
var serializable = _content.GetComponentMod(id.Value);
if (serializable != null && !serializable.Disabled) return ComponentMod.Create(serializable, this);
var value = ComponentMod.DefaultValue;
if (notNull && value == null) throw new DatabaseException("Data not found " + id);
return value;
}
public ComponentStats GetComponentStats(ItemId<ComponentStats> id, bool notNull = false)
{
if (_database._componentStatsMap.TryGetValue(id.Value, out var item)) return item;
var serializable = _content.GetComponentStats(id.Value);
if (serializable != null && !serializable.Disabled) return ComponentStats.Create(serializable, this);
var value = ComponentStats.DefaultValue;
if (notNull && value == null) throw new DatabaseException("Data not found " + id);
return value;
}
public Device GetDevice(ItemId<Device> id, bool notNull = false)
{
if (_database._deviceMap.TryGetValue(id.Value, out var item)) return item;
var serializable = _content.GetDevice(id.Value);
if (serializable != null && !serializable.Disabled) return Device.Create(serializable, this);
var value = Device.DefaultValue;
if (notNull && value == null) throw new DatabaseException("Data not found " + id);
return value;
}
public DroneBay GetDroneBay(ItemId<DroneBay> id, bool notNull = false)
{
if (_database._droneBayMap.TryGetValue(id.Value, out var item)) return item;
var serializable = _content.GetDroneBay(id.Value);
if (serializable != null && !serializable.Disabled) return DroneBay.Create(serializable, this);
var value = DroneBay.DefaultValue;
if (notNull && value == null) throw new DatabaseException("Data not found " + id);
return value;
}
public Faction GetFaction(ItemId<Faction> id, bool notNull = false)
{
if (_database._factionMap.TryGetValue(id.Value, out var item)) return item;
var serializable = _content.GetFaction(id.Value);
if (serializable != null && !serializable.Disabled) return Faction.Create(serializable, this);
var value = Faction.DefaultValue;
if (notNull && value == null) throw new DatabaseException("Data not found " + id);
return value;
}
public Satellite GetSatellite(ItemId<Satellite> id, bool notNull = false)
{
if (_database._satelliteMap.TryGetValue(id.Value, out var item)) return item;
var serializable = _content.GetSatellite(id.Value);
if (serializable != null && !serializable.Disabled) return Satellite.Create(serializable, this);
var value = Satellite.DefaultValue;
if (notNull && value == null) throw new DatabaseException("Data not found " + id);
return value;
}
public SatelliteBuild GetSatelliteBuild(ItemId<SatelliteBuild> id, bool notNull = false)
{
if (_database._satelliteBuildMap.TryGetValue(id.Value, out var item)) return item;
var serializable = _content.GetSatelliteBuild(id.Value);
if (serializable != null && !serializable.Disabled) return SatelliteBuild.Create(serializable, this);
var value = SatelliteBuild.DefaultValue;
if (notNull && value == null) throw new DatabaseException("Data not found " + id);
return value;
}
public Ship GetShip(ItemId<Ship> id, bool notNull = false)
{
if (_database._shipMap.TryGetValue(id.Value, out var item)) return item;
var serializable = _content.GetShip(id.Value);
if (serializable != null && !serializable.Disabled) return Ship.Create(serializable, this);
var value = Ship.DefaultValue;
if (notNull && value == null) throw new DatabaseException("Data not found " + id);
return value;
}
public ShipBuild GetShipBuild(ItemId<ShipBuild> id, bool notNull = false)
{
if (_database._shipBuildMap.TryGetValue(id.Value, out var item)) return item;
var serializable = _content.GetShipBuild(id.Value);
if (serializable != null && !serializable.Disabled) return ShipBuild.Create(serializable, this);
var value = ShipBuild.DefaultValue;
if (notNull && value == null) throw new DatabaseException("Data not found " + id);
return value;
}
public Skill GetSkill(ItemId<Skill> id, bool notNull = false)
{
if (_database._skillMap.TryGetValue(id.Value, out var item)) return item;
var serializable = _content.GetSkill(id.Value);
if (serializable != null && !serializable.Disabled) return Skill.Create(serializable, this);
var value = Skill.DefaultValue;
if (notNull && value == null) throw new DatabaseException("Data not found " + id);
return value;
}
public Technology GetTechnology(ItemId<Technology> id, bool notNull = false)
{
if (_database._technologyMap.TryGetValue(id.Value, out var item)) return item;
var serializable = _content.GetTechnology(id.Value);
if (serializable != null && !serializable.Disabled) return Technology.Create(serializable, this);
var value = Technology.DefaultValue;
if (notNull && value == null) throw new DatabaseException("Data not found " + id);
return value;
}
public Character GetCharacter(ItemId<Character> id, bool notNull = false)
{
if (_database._characterMap.TryGetValue(id.Value, out var item)) return item;
var serializable = _content.GetCharacter(id.Value);
if (serializable != null && !serializable.Disabled) return Character.Create(serializable, this);
var value = Character.DefaultValue;
if (notNull && value == null) throw new DatabaseException("Data not found " + id);
return value;
}
public Fleet GetFleet(ItemId<Fleet> id, bool notNull = false)
{
if (_database._fleetMap.TryGetValue(id.Value, out var item)) return item;
var serializable = _content.GetFleet(id.Value);
if (serializable != null && !serializable.Disabled) return Fleet.Create(serializable, this);
var value = Fleet.DefaultValue;
if (notNull && value == null) throw new DatabaseException("Data not found " + id);
return value;
}
public LootModel GetLoot(ItemId<LootModel> id, bool notNull = false)
{
if (_database._lootMap.TryGetValue(id.Value, out var item)) return item;
var serializable = _content.GetLoot(id.Value);
if (serializable != null && !serializable.Disabled) return LootModel.Create(serializable, this);
var value = LootModel.DefaultValue;
if (notNull && value == null) throw new DatabaseException("Data not found " + id);
return value;
}
public QuestModel GetQuest(ItemId<QuestModel> id, bool notNull = false)
{
if (_database._questMap.TryGetValue(id.Value, out var item)) return item;
var serializable = _content.GetQuest(id.Value);
if (serializable != null && !serializable.Disabled) return QuestModel.Create(serializable, this);
var value = QuestModel.DefaultValue;
if (notNull && value == null) throw new DatabaseException("Data not found " + id);
return value;
}
public QuestItem GetQuestItem(ItemId<QuestItem> id, bool notNull = false)
{
if (_database._questItemMap.TryGetValue(id.Value, out var item)) return item;
var serializable = _content.GetQuestItem(id.Value);
if (serializable != null && !serializable.Disabled) return QuestItem.Create(serializable, this);
var value = QuestItem.DefaultValue;
if (notNull && value == null) throw new DatabaseException("Data not found " + id);
return value;
}
public Ammunition GetAmmunition(ItemId<Ammunition> id, bool notNull = false)
{
if (_database._ammunitionMap.TryGetValue(id.Value, out var item)) return item;
var serializable = _content.GetAmmunition(id.Value);
if (serializable != null && !serializable.Disabled) return Ammunition.Create(serializable, this);
var value = Ammunition.DefaultValue;
if (notNull && value == null) throw new DatabaseException("Data not found " + id);
return value;
}
public BulletPrefab GetBulletPrefab(ItemId<BulletPrefab> id, bool notNull = false)
{
if (_database._bulletPrefabMap.TryGetValue(id.Value, out var item)) return item;
var serializable = _content.GetBulletPrefab(id.Value);
if (serializable != null && !serializable.Disabled) return BulletPrefab.Create(serializable, this);
var value = BulletPrefab.DefaultValue;
if (notNull && value == null) throw new DatabaseException("Data not found " + id);
return value;
}
public VisualEffect GetVisualEffect(ItemId<VisualEffect> id, bool notNull = false)
{
if (_database._visualEffectMap.TryGetValue(id.Value, out var item)) return item;
var serializable = _content.GetVisualEffect(id.Value);
if (serializable != null && !serializable.Disabled) return VisualEffect.Create(serializable, this);
var value = VisualEffect.DefaultValue;
if (notNull && value == null) throw new DatabaseException("Data not found " + id);
return value;
}
public Weapon GetWeapon(ItemId<Weapon> id, bool notNull = false)
{
if (_database._weaponMap.TryGetValue(id.Value, out var item)) return item;
var serializable = _content.GetWeapon(id.Value);
if (serializable != null && !serializable.Disabled) return Weapon.Create(serializable, this);
var value = Weapon.DefaultValue;
if (notNull && value == null) throw new DatabaseException("Data not found " + id);
return value;
}
public void AddAmmunitionObsolete(int id, AmmunitionObsolete item) { _database._ammunitionObsoleteMap.Add(id, item); }
public void AddComponent(int id, Component item) { _database._componentMap.Add(id, item); }
public void AddComponentMod(int id, ComponentMod item) { _database._componentModMap.Add(id, item); }
public void AddComponentStats(int id, ComponentStats item) { _database._componentStatsMap.Add(id, item); }
public void AddDevice(int id, Device item) { _database._deviceMap.Add(id, item); }
public void AddDroneBay(int id, DroneBay item) { _database._droneBayMap.Add(id, item); }
public void AddFaction(int id, Faction item) { _database._factionMap.Add(id, item); }
public void AddSatellite(int id, Satellite item) { _database._satelliteMap.Add(id, item); }
public void AddSatelliteBuild(int id, SatelliteBuild item) { _database._satelliteBuildMap.Add(id, item); }
public void AddShip(int id, Ship item) { _database._shipMap.Add(id, item); }
public void AddShipBuild(int id, ShipBuild item) { _database._shipBuildMap.Add(id, item); }
public void AddSkill(int id, Skill item) { _database._skillMap.Add(id, item); }
public void AddTechnology(int id, Technology item) { _database._technologyMap.Add(id, item); }
public void AddCharacter(int id, Character item) { _database._characterMap.Add(id, item); }
public void AddFleet(int id, Fleet item) { _database._fleetMap.Add(id, item); }
public void AddLoot(int id, LootModel item) { _database._lootMap.Add(id, item); }
public void AddQuest(int id, QuestModel item) { _database._questMap.Add(id, item); }
public void AddQuestItem(int id, QuestItem item) { _database._questItemMap.Add(id, item); }
public void AddAmmunition(int id, Ammunition item) { _database._ammunitionMap.Add(id, item); }
public void AddBulletPrefab(int id, BulletPrefab item) { _database._bulletPrefabMap.Add(id, item); }
public void AddVisualEffect(int id, VisualEffect item) { _database._visualEffectMap.Add(id, item); }
public void AddWeapon(int id, Weapon item) { _database._weaponMap.Add(id, item); }
private readonly DatabaseContent _content;
private readonly Database _database;
}
}
}
| 1 | 0.920175 | 1 | 0.920175 | game-dev | MEDIA | 0.825998 | game-dev | 0.894345 | 1 | 0.894345 |
iniside/Velesarc | 1,599 | ArcX/ArcAI/Source/ArcAI/Tasks/ArcMassActorRotateToFaceTargetTask.cpp | #include "ArcMassActorRotateToFaceTargetTask.h"
#include "AIController.h"
#include "StateTreeExecutionContext.h"
FArcMassActorRotateToFaceTargetTask::FArcMassActorRotateToFaceTargetTask()
{
}
bool FArcMassActorRotateToFaceTargetTask::Link(FStateTreeLinker& Linker)
{
return FMassStateTreeTaskBase::Link(Linker);
}
void FArcMassActorRotateToFaceTargetTask::GetDependencies(UE::MassBehavior::FStateTreeDependencyBuilder& Builder) const
{
FMassStateTreeTaskBase::GetDependencies(Builder);
}
EStateTreeRunStatus FArcMassActorRotateToFaceTargetTask::EnterState(FStateTreeExecutionContext& Context
, const FStateTreeTransitionResult& Transition) const
{
FInstanceDataType& InstanceData = Context.GetInstanceData(*this);
APawn* P = Cast<APawn>(InstanceData.InputActor);
if (!P)
{
return EStateTreeRunStatus::Failed;
}
AAIController* AIController = P->GetController<AAIController>();
if (!AIController)
{
return EStateTreeRunStatus::Failed;
}
if (!InstanceData.Target)
{
return EStateTreeRunStatus::Failed;
}
AIController->SetFocus(InstanceData.Target, EAIFocusPriority::Gameplay);
return EStateTreeRunStatus::Running;
}
void FArcMassActorRotateToFaceTargetTask::ExitState(FStateTreeExecutionContext& Context, const FStateTreeTransitionResult& Transition) const
{
FInstanceDataType& InstanceData = Context.GetInstanceData(*this);
APawn* P = Cast<APawn>(InstanceData.InputActor);
if (!P)
{
return;
}
AAIController* AIController = P->GetController<AAIController>();
if (!AIController)
{
return;
}
AIController->ClearFocus(EAIFocusPriority::Gameplay);
}
| 1 | 0.790841 | 1 | 0.790841 | game-dev | MEDIA | 0.924994 | game-dev | 0.740418 | 1 | 0.740418 |
LoganSMiller/AI-Refactored-Client | 14,605 | AI/Combat/BotThreatEscalationMonitor.cs | // <auto-generated>
// AI-Refactored: BotThreatEscalationMonitor.cs (Supreme Arbitration Overlay/Event, June 2025, Beyond Diamond, Mastermoveplan, SPT/FIKA/Headless/Client Parity)
// Monitors, escalates, and coordinates threat levels, panic, squad morale, and escalation overlays.
// Triple-guard: Arbitration, NavMesh/Y, dedup. Pooled, squad- and voice-aware, fully bulletproof. Never disables, never teleports, never tick-moves.
// MIT License.
// </auto-generated>
namespace AIRefactored.AI.Combat
{
using System;
using AIRefactored.AI.Core;
using AIRefactored.AI.Helpers;
using AIRefactored.AI.Navigation;
using AIRefactored.AI.Optimization;
using AIRefactored.Pools;
using AIRefactored.Runtime;
using BepInEx.Logging;
using EFT;
using UnityEngine;
/// <summary>
/// Supreme arbitration: Escalates bot and squad threat state with event-only overlays, bulletproof comms, max realism, pooled and error-shielded.
/// All overlays go through arbitration, NavMesh/y, and deduplication. Squad escalation/voice is propagated via async processors.
/// </summary>
public sealed class BotThreatEscalationMonitor
{
#region Constants
private const float CheckInterval = 0.73f; // More responsive, less spam.
private const float PanicDurationThreshold = 3.6f;
private const float SquadCasualtyThreshold = 0.36f;
private const float SquadMoraleCollapseThreshold = 0.61f;
private const float VoiceIntervalMin = 1.9f;
private const float VoiceIntervalMax = 4.4f;
private const float EscalationOverlayMoveDedupSqr = 0.07f;
private const float EscalationOverlayMoveCooldown = 0.38f;
private const BotOverlayType OverlayType = BotOverlayType.Attack;
private static readonly EPhraseTrigger[] EscalationPhrases = new[]
{
EPhraseTrigger.OnFight, EPhraseTrigger.NeedHelp, EPhraseTrigger.UnderFire,
EPhraseTrigger.Regroup, EPhraseTrigger.Cooperation, EPhraseTrigger.CoverMe,
EPhraseTrigger.GoForward, EPhraseTrigger.HoldPosition, EPhraseTrigger.FollowMe
};
private static readonly EPhraseTrigger[] SquadCollapsePhrases = new[]
{
EPhraseTrigger.Regroup, EPhraseTrigger.OnBeingHurt, EPhraseTrigger.NeedHelp,
EPhraseTrigger.CoverMe, EPhraseTrigger.HoldPosition, EPhraseTrigger.FollowMe,
EPhraseTrigger.OnFight
};
private static readonly ManualLogSource Logger = Plugin.LoggerInstance;
#endregion
#region Fields
private BotOwner _bot;
private BotComponentCache _cache;
private float _panicStartTime = -1f;
private float _nextCheckTime = -1f;
private float _lastVoiceTime = -1f;
private float _nextSquadVoiceTime = -1f;
private bool _hasEscalated;
private bool _squadCollapseTriggered;
private Vector3 _lastEscalationMoveIssued = Vector3.zero;
private float _lastEscalationMoveTime = -10f;
#endregion
#region Initialization
/// <summary>
/// Initialize the escalation monitor for a bot and its cache.
/// </summary>
public void Initialize(BotOwner botOwner)
{
if (botOwner == null)
{
Logger.LogError("[BotThreatEscalationMonitor] BotOwner is null in Initialize.");
return;
}
_bot = botOwner;
_cache = BotCacheUtility.GetCache(botOwner);
_panicStartTime = -1f;
_nextCheckTime = -1f;
_lastVoiceTime = -1f;
_nextSquadVoiceTime = -1f;
_hasEscalated = false;
_squadCollapseTriggered = false;
_lastEscalationMoveIssued = Vector3.zero;
_lastEscalationMoveTime = -10f;
}
#endregion
#region Main Tick
/// <summary>
/// Main update entry (must be ticked via BotBrain).
/// </summary>
public void Tick(float time)
{
if (!IsValid() || time < _nextCheckTime)
return;
_nextCheckTime = time + CheckInterval;
try
{
if (!_hasEscalated && ShouldEscalate(time))
EscalateBot(time);
if (!_squadCollapseTriggered && SquadMoraleCollapsed())
{
_squadCollapseTriggered = true;
PropagateSquadCollapse(time);
}
}
catch (Exception ex)
{
Logger.LogError("[BotThreatEscalationMonitor] Tick exception: " + ex);
}
}
#endregion
#region Public API
/// <summary>
/// Notify that panic was triggered (from external panic/suppression logic).
/// </summary>
public void NotifyPanicTriggered()
{
if (_panicStartTime < 0f)
_panicStartTime = Time.time;
}
#endregion
#region Escalation Logic
private bool ShouldEscalate(float time)
{
return PanicDurationExceeded(time) || MultipleEnemiesVisible() || SquadHasLostTeammates();
}
private bool PanicDurationExceeded(float time) =>
_panicStartTime >= 0f && (time - _panicStartTime) > PanicDurationThreshold;
private bool MultipleEnemiesVisible()
{
var controller = _bot?.EnemiesController;
if (controller?.EnemyInfos == null)
return false;
int visible = 0;
foreach (var kv in controller.EnemyInfos)
{
if (kv.Value?.IsVisible == true && ++visible >= 2)
return true;
}
return false;
}
private bool SquadHasLostTeammates()
{
var group = _bot?.BotsGroup;
if (group == null || group.MembersCount <= 1)
return false;
int dead = 0;
for (int i = 0; i < group.MembersCount; i++)
if (group.Member(i)?.IsDead == true)
dead++;
return dead >= Mathf.CeilToInt(group.MembersCount * SquadCasualtyThreshold);
}
private bool SquadMoraleCollapsed()
{
var group = _bot?.BotsGroup;
if (group == null || group.MembersCount <= 1)
return false;
int dead = 0;
for (int i = 0; i < group.MembersCount; i++)
if (group.Member(i)?.IsDead == true)
dead++;
return dead >= Mathf.CeilToInt(group.MembersCount * SquadMoraleCollapseThreshold);
}
/// <summary>
/// Escalate bot aggression and squad overlay—arbitration/event only, triple-guarded, pooled, bulletproof.
/// </summary>
private void EscalateBot(float time)
{
_hasEscalated = true;
AIOptimizationManager.Reset(_bot);
AIOptimizationManager.Apply(_bot);
ApplyEscalationTuning(_bot);
ApplyPersonalityTuning(_bot);
// Overlay arbitration (Attack): triple-guarded.
if (BotNavHelper.TryGetSafeTarget(_bot, out var navTarget) && IsVectorValid(navTarget))
{
float now = Time.time;
if (BotOverlayManager.CanIssueMove(_bot, OverlayType)
&& _bot.Mover != null
&& !BotMovementHelper.IsMovementPaused(_bot)
&& !BotMovementHelper.IsInInteractionState(_bot)
&& (_lastEscalationMoveIssued - navTarget).sqrMagnitude > EscalationOverlayMoveDedupSqr
&& (now - _lastEscalationMoveTime) > EscalationOverlayMoveCooldown)
{
float cohesion = BotRegistry.Get(_bot.ProfileId)?.Cohesion ?? 1f;
BotOverlayManager.RegisterMove(_bot, OverlayType);
BotMovementHelper.SmoothMoveToSafe(_bot, navTarget, false, cohesion, OverlayType);
_lastEscalationMoveIssued = navTarget;
_lastEscalationMoveTime = now;
}
}
if (_bot.BotTalk != null && time - _lastVoiceTime > VoiceIntervalMin)
{
TrySayEscalationPhrase(time);
}
// Propagate escalation voice/comms overlays to all squadmates (with micro-delay via async processor).
PropagateSquadEscalation(time);
}
/// <summary>
/// Propagate escalation to all alive squadmates with random async delay (never static/global).
/// </summary>
private void PropagateSquadEscalation(float now)
{
var group = _bot?.BotsGroup;
if (group == null || group.MembersCount <= 1)
return;
for (int i = 0; i < group.MembersCount; i++)
{
BotOwner mate = group.Member(i);
if (mate == null || mate == _bot || mate.IsDead)
continue;
BotComponentCache mateCache = BotCacheUtility.GetCache(mate);
var asyncProcessor = mate.GetComponent<BotAsyncProcessor>();
if (mateCache?.ThreatEscalation != null && asyncProcessor != null)
{
float delay = UnityEngine.Random.Range(0.17f, 0.89f); // Humanized reaction delay
asyncProcessor.QueueDelayedEvent(
(owner, cache) => cache?.ThreatEscalation?.SquadEscalationOverlay(now + delay), delay
);
}
}
}
/// <summary>
/// Called via async event on squadmates to escalate overlays, comms, and personality.
/// </summary>
public void SquadEscalationOverlay(float time)
{
if (_hasEscalated) return; // Only escalate once per bot
_hasEscalated = true;
ApplyEscalationTuning(_bot);
ApplyPersonalityTuning(_bot);
if (_bot.BotTalk != null && time - _lastVoiceTime > VoiceIntervalMin)
{
TrySayEscalationPhrase(time);
}
}
/// <summary>
/// Propagate squad collapse voice overlays.
/// </summary>
private void PropagateSquadCollapse(float now)
{
var group = _bot?.BotsGroup;
if (group == null || group.MembersCount <= 1)
return;
for (int i = 0; i < group.MembersCount; i++)
{
BotOwner mate = group.Member(i);
if (mate == null || mate == _bot || mate.IsDead)
continue;
BotComponentCache mateCache = BotCacheUtility.GetCache(mate);
var asyncProcessor = mate.GetComponent<BotAsyncProcessor>();
if (mateCache?.ThreatEscalation != null && asyncProcessor != null)
{
float delay = UnityEngine.Random.Range(0.14f, 0.66f);
asyncProcessor.QueueDelayedEvent(
(owner, cache) => cache?.ThreatEscalation?.TrySquadCollapseComms(now + delay), delay
);
}
}
TrySquadCollapseComms(now);
}
private void TrySquadCollapseComms(float time)
{
if (_bot.BotTalk != null && time - _nextSquadVoiceTime > VoiceIntervalMax)
{
try
{
var phrase = SquadCollapsePhrases[UnityEngine.Random.Range(0, SquadCollapsePhrases.Length)];
_bot.BotTalk.TrySay(phrase);
_nextSquadVoiceTime = time;
}
catch (Exception ex)
{
Logger.LogError("[BotThreatEscalationMonitor] Squad collapse comms failed: " + ex);
}
}
}
private void TrySayEscalationPhrase(float time)
{
try
{
var phrase = EscalationPhrases[UnityEngine.Random.Range(0, EscalationPhrases.Length)];
_bot.BotTalk.TrySay(phrase);
_lastVoiceTime = time;
}
catch (Exception ex)
{
Logger.LogError("[BotThreatEscalationMonitor] Escalation voice failed: " + ex);
}
}
private void ApplyEscalationTuning(BotOwner bot)
{
var file = bot?.Settings?.FileSettings;
if (file == null) return;
try
{
file.Shoot.RECOIL_PER_METER *= 0.81f;
file.Mind.DIST_TO_FOUND_SQRT *= 1.27f;
file.Mind.ENEMY_LOOK_AT_ME_ANG *= 0.66f;
file.Mind.CHANCE_TO_RUN_CAUSE_DAMAGE_0_100 = Mathf.Clamp(file.Mind.CHANCE_TO_RUN_CAUSE_DAMAGE_0_100 + 31f, 0f, 100f);
file.Look.MAX_VISION_GRASS_METERS += 9f;
}
catch (Exception ex)
{
Logger.LogError("[BotThreatEscalationMonitor] Tuning failed: " + ex);
}
}
private void ApplyPersonalityTuning(BotOwner bot)
{
try
{
var profile = BotRegistry.Get(bot.ProfileId);
if (profile == null) return;
profile.AggressionLevel = Mathf.Clamp01(profile.AggressionLevel + 0.32f);
profile.Caution = Mathf.Clamp01(profile.Caution - 0.21f);
profile.SuppressionSensitivity = Mathf.Clamp01(profile.SuppressionSensitivity * 0.63f);
profile.AccuracyUnderFire = Mathf.Clamp01(profile.AccuracyUnderFire + 0.27f);
profile.CommunicationLevel = Mathf.Clamp01(profile.CommunicationLevel + 0.25f);
}
catch (Exception ex)
{
Logger.LogError("[BotThreatEscalationMonitor] Personality tuning failed: " + ex);
}
}
#endregion
#region Validation
private bool IsValid()
{
try
{
return _bot != null &&
!_bot.IsDead &&
_bot.GetPlayer is Player player &&
player.IsAI;
}
catch { return false; }
}
private static bool IsVectorValid(Vector3 v)
{
return !float.IsNaN(v.x) && !float.IsNaN(v.y) && !float.IsNaN(v.z);
}
#endregion
}
}
| 1 | 0.963265 | 1 | 0.963265 | game-dev | MEDIA | 0.980644 | game-dev | 0.985034 | 1 | 0.985034 |
apollo-rsps/apollo | 1,027 | game/src/main/java/org/apollo/game/release/r377/FifthItemActionMessageDecoder.java | package org.apollo.game.release.r377;
import org.apollo.game.message.impl.ItemActionMessage;
import org.apollo.net.codec.game.DataOrder;
import org.apollo.net.codec.game.DataTransformation;
import org.apollo.net.codec.game.DataType;
import org.apollo.net.codec.game.GamePacket;
import org.apollo.net.codec.game.GamePacketReader;
import org.apollo.net.release.MessageDecoder;
/**
* A {@link MessageDecoder} for the fifth {@link ItemActionMessage}.
*
* @author Graham
*/
public final class FifthItemActionMessageDecoder extends MessageDecoder<ItemActionMessage> {
@Override
public ItemActionMessage decode(GamePacket packet) {
GamePacketReader reader = new GamePacketReader(packet);
int slot = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD);
int id = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD);
int interfaceId = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE);
return new ItemActionMessage(5, interfaceId, id, slot);
}
} | 1 | 0.835384 | 1 | 0.835384 | game-dev | MEDIA | 0.233816 | game-dev | 0.891495 | 1 | 0.891495 |
itsfolf/Discord-Screenshare-Linux | 1,437 | include/modules/video_coding/utility/framerate_controller_deprecated.h | /*
* Copyright (c) 2018 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef MODULES_VIDEO_CODING_UTILITY_FRAMERATE_CONTROLLER_DEPRECATED_H_
#define MODULES_VIDEO_CODING_UTILITY_FRAMERATE_CONTROLLER_DEPRECATED_H_
#include <stdint.h>
#include "absl/types/optional.h"
#include "rtc_base/rate_statistics.h"
namespace webrtc {
// Please use webrtc::FramerateController instead.
class FramerateControllerDeprecated {
public:
explicit FramerateControllerDeprecated(float target_framerate_fps);
void SetTargetRate(float target_framerate_fps);
float GetTargetRate();
// Advices user to drop next frame in order to reach target framerate.
bool DropFrame(uint32_t timestamp_ms) const;
void AddFrame(uint32_t timestamp_ms);
void Reset();
private:
absl::optional<float> Rate(uint32_t timestamp_ms) const;
absl::optional<float> target_framerate_fps_;
absl::optional<uint32_t> last_timestamp_ms_;
uint32_t min_frame_interval_ms_;
RateStatistics framerate_estimator_;
};
} // namespace webrtc
#endif // MODULES_VIDEO_CODING_UTILITY_FRAMERATE_CONTROLLER_DEPRECATED_H_
| 1 | 0.731853 | 1 | 0.731853 | game-dev | MEDIA | 0.499205 | game-dev,audio-video-media | 0.617055 | 1 | 0.617055 |
KeenSoftwareHouse/Miner-Wars-2081 | 13,192 | Sources/MinerWars.GameLib/AppCode/Game/TransparentGeometry/Particles/MyParticleEmitter.cs | using System;
using System.Collections.Generic;
using System.Xml;
using System.Linq;
using System.Globalization;
using MinerWarsMath;
using MinerWars.AppCode.Game.Utils;
using MinerWars.CommonLIB.AppCode.Utils;
namespace MinerWars.AppCode.Game.TransparentGeometry.Particles
{
public enum MyParticleEmitterType
{
Point,
Line,
Box,
Sphere,
Hemisphere,
Circle,
}
public class MyParticleEmitter
{
static string[] MyParticleEmitterTypeStrings =
{
"Point",
"Line",
"Box",
"Sphere",
"Hemisphere",
"Circle",
};
static List<string> s_emitterTypeStrings = MyParticleEmitterTypeStrings.ToList<string>();
//Version of the emitter for serialization
static readonly int Version = 0;
private enum MyEmitterPropertiesEnum
{
Type,
Offset,
Size,
RadiusMin,
RadiusMax,
DirToCamera
}
IMyConstProperty[] m_properties = new IMyConstProperty[Enum.GetValues(typeof(MyEmitterPropertiesEnum)).Length];
/// <summary>
/// Public members to easy access
/// </summary>
public MyParticleEmitterType Type
{
get { return (MyParticleEmitterType)(int)(m_properties[(int)MyEmitterPropertiesEnum.Type] as MyConstPropertyEnum); }
private set { m_properties[(int)MyEmitterPropertiesEnum.Type].SetValue((int)value); }
}
public MyAnimatedPropertyVector3 Offset
{
get { return m_properties[(int)MyEmitterPropertiesEnum.Offset] as MyAnimatedPropertyVector3; }
private set { m_properties[(int)MyEmitterPropertiesEnum.Offset] = value; }
}
public MyAnimatedPropertyFloat Size
{
get { return m_properties[(int)MyEmitterPropertiesEnum.Size] as MyAnimatedPropertyFloat; }
private set { m_properties[(int)MyEmitterPropertiesEnum.Size] = value; }
}
public MyConstPropertyFloat RadiusMin
{
get { return m_properties[(int)MyEmitterPropertiesEnum.RadiusMin] as MyConstPropertyFloat; }
private set { m_properties[(int)MyEmitterPropertiesEnum.RadiusMin] = value; }
}
public MyConstPropertyFloat RadiusMax
{
get { return m_properties[(int)MyEmitterPropertiesEnum.RadiusMax] as MyConstPropertyFloat; }
private set { m_properties[(int)MyEmitterPropertiesEnum.RadiusMax] = value; }
}
public MyConstPropertyBool DirToCamera
{
get { return m_properties[(int)MyEmitterPropertiesEnum.DirToCamera] as MyConstPropertyBool; }
private set { m_properties[(int)MyEmitterPropertiesEnum.DirToCamera] = value; }
}
public MyParticleEmitter(MyParticleEmitterType type)
{
}
public void Init()
{
AddProperty(MyEmitterPropertiesEnum.Type, new MyConstPropertyEnum("Type", typeof(MyParticleEmitterType), s_emitterTypeStrings));
AddProperty(MyEmitterPropertiesEnum.Offset, new MyAnimatedPropertyVector3("Offset"));
AddProperty(MyEmitterPropertiesEnum.Size, new MyAnimatedPropertyFloat("Size"));
AddProperty(MyEmitterPropertiesEnum.RadiusMin, new MyConstPropertyFloat("RadiusMin"));
AddProperty(MyEmitterPropertiesEnum.RadiusMax, new MyConstPropertyFloat("RadiusMax"));
AddProperty(MyEmitterPropertiesEnum.DirToCamera, new MyConstPropertyBool("DirToCamera"));
Offset.AddKey(0, new Vector3(0, 0, 0));
Size.AddKey(0, 1.0f);
RadiusMin.SetValue(1.0f);
RadiusMax.SetValue(1.0f);
DirToCamera.SetValue(false);
}
public void Done()
{
for (int i = 0; i < GetProperties().Length; i++)
{
if (m_properties[i] is IMyAnimatedProperty)
(m_properties[i] as IMyAnimatedProperty).ClearKeys();
}
Close();
}
public void Start()
{
System.Diagnostics.Debug.Assert(Offset == null);
}
public void Close()
{
for (int i = 0; i < m_properties.Length; i++)
{
m_properties[i] = null;
}
}
T AddProperty<T>(MyEmitterPropertiesEnum e, T property) where T : IMyConstProperty
{
m_properties[(int)e] = property;
return property;
}
public void CalculateStartPosition(float elapsedTime, Matrix worldMatrix, float userScale, out Vector3 startOffset, out Vector3 startPosition)
{
Vector3 currentOffsetUntransformed;
Offset.GetInterpolatedValue<Vector3>(elapsedTime, out currentOffsetUntransformed);
float currentSize;
Size.GetInterpolatedValue<float>(elapsedTime, out currentSize);
currentSize *= MyMwcUtils.GetRandomFloat(RadiusMin, RadiusMax) * userScale;
Vector3 localPos = Vector3.Zero;
Vector3 worldOffset;
Vector3.Transform(ref currentOffsetUntransformed, ref worldMatrix, out worldOffset);
switch (Type)
{
case MyParticleEmitterType.Point:
localPos = Vector3.Zero;
break;
case MyParticleEmitterType.Line:
localPos = Vector3.Forward * MyMwcUtils.GetRandomFloat(0.0f, currentSize);
break;
case MyParticleEmitterType.Sphere:
localPos = MyMwcUtils.GetRandomVector3Normalized() * currentSize;
break;
case MyParticleEmitterType.Box:
float currentSizeHalf = currentSize * 0.5f;
localPos =
new Vector3(
MinerWars.CommonLIB.AppCode.Utils.MyMwcUtils.GetRandomFloat(-currentSizeHalf, currentSizeHalf),
MinerWars.CommonLIB.AppCode.Utils.MyMwcUtils.GetRandomFloat(-currentSizeHalf, currentSizeHalf),
MinerWars.CommonLIB.AppCode.Utils.MyMwcUtils.GetRandomFloat(-currentSizeHalf, currentSizeHalf)
);
break;
case MyParticleEmitterType.Hemisphere:
localPos = MyMwcUtils.GetRandomVector3HemisphereNormalized(Vector3.Forward) * currentSize;
break;
case MyParticleEmitterType.Circle:
localPos = MyMwcUtils.GetRandomVector3CircleNormalized() * currentSize;
break;
default:
System.Diagnostics.Debug.Assert(false);
break;
}
Vector3 worldPos;
if (DirToCamera)
{
Matrix WorldView = worldMatrix * MyCamera.ViewMatrix;
WorldView.Translation += currentOffsetUntransformed;
Matrix newWorld = WorldView * Matrix.Invert(MyCamera.ViewMatrix);
Vector3 dir = MyCamera.Position - newWorld.Translation;
dir.Normalize();
Matrix matrix = MyMath.MatrixFromDir(dir);
matrix.Translation = newWorld.Translation;
Vector3.Transform(ref localPos, ref matrix, out worldPos);
startOffset = newWorld.Translation;
startPosition = worldPos;
}
else
{
Vector3.TransformNormal(ref localPos, ref worldMatrix, out worldPos);
startOffset = worldOffset;
startPosition = worldOffset + worldPos;
}
}
public void CreateInstance(MyParticleEmitter emitter)
{
for (int i = 0; i < m_properties.Length; i++)
{
m_properties[i] = emitter.m_properties[i];
}
}
public IMyConstProperty[] GetProperties()
{
return m_properties;
}
public void Duplicate(MyParticleEmitter targetEmitter)
{
for (int i = 0; i < m_properties.Length; i++)
{
targetEmitter.m_properties[i] = m_properties[i].Duplicate();
}
}
#region Serialization
public void Serialize(XmlWriter writer)
{
writer.WriteStartElement("ParticleEmitter");
writer.WriteAttributeString("version", Version.ToString(CultureInfo.InvariantCulture));
foreach (IMyConstProperty property in m_properties)
{
property.Serialize(writer);
}
writer.WriteEndElement(); //ParticleEmitter
}
public void Deserialize(XmlReader reader)
{
int version = Convert.ToInt32(reader.GetAttribute("version"));
reader.ReadStartElement(); //ParticleEmitter
foreach (IMyConstProperty property in m_properties)
{
property.Deserialize(reader);
}
reader.ReadEndElement(); //ParticleEmitter
}
#endregion
#region DebugDraw
public void DebugDraw(float elapsedTime, Matrix worldMatrix)
{
Vector3 currentOffsetUntransformed, currentOffset;
Offset.GetInterpolatedValue<Vector3>(elapsedTime, out currentOffsetUntransformed);
Vector3.Transform(ref currentOffsetUntransformed, ref worldMatrix, out currentOffset);
float currentSize;
Size.GetInterpolatedValue<float>(elapsedTime, out currentSize);
switch (Type)
{
case MyParticleEmitterType.Point:
{
MyDebugDraw.DrawSphereWireframe(currentOffset, 0.1f, new Vector3(1, 1, 0), 1.0f);
}
break;
case MyParticleEmitterType.Line:
{
if (DirToCamera)
{
Vector3 dir = MyCamera.Position - currentOffset;
dir.Normalize();
Matrix matrix = Matrix.CreateScale(currentSize) * MyMath.MatrixFromDir(dir);
Vector3 currentOffsetScaled = Vector3.TransformNormal(Vector3.Forward, matrix);
MyDebugDraw.DrawLine3D(worldMatrix.Translation, worldMatrix.Translation + currentOffsetScaled, Color.Yellow, Color.Yellow);
}
else
{
Vector3 currentOffsetScaled = Vector3.Transform(Vector3.Up * currentSize, worldMatrix);
MyDebugDraw.DrawLine3D(worldMatrix.Translation, currentOffsetScaled, Color.Yellow, Color.Yellow);
}
}
break;
case MyParticleEmitterType.Sphere:
{
MyDebugDraw.DrawSphereWireframe(currentOffset, currentSize, new Vector3(1, 1, 0), 1.0f);
}
break;
case MyParticleEmitterType.Box:
{
Matrix matrix = Matrix.CreateScale(currentSize) * Matrix.CreateTranslation(currentOffsetUntransformed) * worldMatrix;
MyDebugDraw.DrawLowresBoxWireframe(matrix, new Vector3(1, 1, 0), 1.0f);
}
break;
case MyParticleEmitterType.Hemisphere:
{
Vector3 worldPos = currentOffset;
Matrix matrix;
if (DirToCamera)
{
Matrix WorldView = worldMatrix * MyCamera.ViewMatrix;
WorldView.Translation += currentOffsetUntransformed;
Matrix newWorld = WorldView * Matrix.Invert(MyCamera.ViewMatrix);
Vector3 dir = MyCamera.Position - newWorld.Translation;
dir.Normalize();
matrix = Matrix.CreateScale(currentSize) * Matrix.CreateRotationX(MathHelper.PiOver2) * MyMath.MatrixFromDir(dir);
matrix.Translation = newWorld.Translation;
}
else
{
matrix = Matrix.CreateScale(currentSize) * Matrix.CreateTranslation(currentOffsetUntransformed) * worldMatrix;
}
MyDebugDraw.DrawHemisphereWireframe(matrix, new Vector3(1, 1, 0), 1.0f);
}
break;
case MyParticleEmitterType.Circle:
{
//No debug draw
}
break;
default:
System.Diagnostics.Debug.Assert(false);
break;
}
}
#endregion
}
}
| 1 | 0.877428 | 1 | 0.877428 | game-dev | MEDIA | 0.540124 | game-dev,graphics-rendering | 0.979786 | 1 | 0.979786 |
ihmcrobotics/ihmc-open-robotics-software | 3,573 | ihmc-perception/src/main/generated-java/us/ihmc/perception/gpuMapping/HeightMapParameters.java | package us.ihmc.perception.gpuMapping;
import us.ihmc.tools.property.*;
/**
* The JSON file for this property set is located here:
* ihmc-perception/src/main/resources/us/ihmc/perception/heightMap/HeightMapParameters.json
*
* This class was auto generated. Property attributes must be edited in the JSON file,
* after which this class should be regenerated by running the main. This class uses
* the generator to assist in the addition, removal, and modification of property keys.
* It is permissible to forgo these benefits and abandon the generator, in which case
* you should also move it from the generated-java folder to the java folder.
*
* If the constant paths have changed, change them in this file and run the main to regenerate.
*/
public class HeightMapParameters extends StoredPropertySet implements HeightMapParametersBasics
{
public static final StoredPropertyKeyList keys = new StoredPropertyKeyList();
public static final BooleanStoredPropertyKey driftOffsetFilter = keys.addBooleanKey("Drift offset filter");
public static final BooleanStoredPropertyKey flyingPointsFilter = keys.addBooleanKey("Flying points filter");
public static final BooleanStoredPropertyKey enableChunkedMap = keys.addBooleanKey("Enable chunked map");
public static final BooleanStoredPropertyKey logHeightMap = keys.addBooleanKey("Log height map");
public static final DoubleStoredPropertyKey minHeightRegistration = keys.addDoubleKey("Min height registration");
public static final DoubleStoredPropertyKey maxHeightRegistration = keys.addDoubleKey("Max height registration");
public static final DoubleStoredPropertyKey kalmanFilterPredictionNoise = keys.addDoubleKey("Kalman filter prediction noise");
public static final DoubleStoredPropertyKey additionalTranslationalVarianceAdded = keys.addDoubleKey("Additional translational variance added");
public static final DoubleStoredPropertyKey variancePerMeter = keys.addDoubleKey("Variance per meter");
public static final DoubleStoredPropertyKey variancePerTranslationSpeed = keys.addDoubleKey("Variance per translation speed");
public static final DoubleStoredPropertyKey variancePerRotationSpeed = keys.addDoubleKey("Variance per rotation speed");
public static final DoubleStoredPropertyKey minClampHeight = keys.addDoubleKey("Min Clamp Height");
public static final DoubleStoredPropertyKey maxClampHeight = keys.addDoubleKey("Max Clamp Height");
public static final DoubleStoredPropertyKey cellSize = keys.addDoubleKey("Cell size");
public static final DoubleStoredPropertyKey widthInMeters = keys.addDoubleKey("Width in meters");
/**
* Loads this property set.
*/
public HeightMapParameters()
{
this("");
}
/**
* Loads an alternate version of this property set in the same folder.
*/
public HeightMapParameters(String versionSuffix)
{
this(HeightMapParameters.class, versionSuffix);
}
/**
* Loads an alternate version of this property set in other folders.
*/
public HeightMapParameters(Class<?> classForLoading, String versionSuffix)
{
super(keys, classForLoading, HeightMapParameters.class, versionSuffix);
load();
}
public HeightMapParameters(StoredPropertySetReadOnly other)
{
super(keys, HeightMapParameters.class, other.getCurrentVersionSuffix());
set(other);
}
public static void main(String[] args)
{
StoredPropertySet parameters = new StoredPropertySet(keys, HeightMapParameters.class);
parameters.generateJavaFiles();
}
}
| 1 | 0.890907 | 1 | 0.890907 | game-dev | MEDIA | 0.281235 | game-dev | 0.904711 | 1 | 0.904711 |
corporateshark/Mastering-Android-NDK | 2,247 | Chapter10/1_Asteroids/jni/SDL/src/loadso/dlopen/SDL_sysloadso.c | /*
Simple DirectMedia Layer
Copyright (C) 1997-2014 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.
*/
#include "../../SDL_internal.h"
#ifdef SDL_LOADSO_DLOPEN
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* System dependent library loading routines */
#include <stdio.h>
#include <dlfcn.h>
#include "SDL_loadso.h"
void *
SDL_LoadObject(const char *sofile)
{
void *handle = dlopen(sofile, RTLD_NOW|RTLD_LOCAL);
const char *loaderror = (char *) dlerror();
if (handle == NULL) {
SDL_SetError("Failed loading %s: %s", sofile, loaderror);
}
return (handle);
}
void *
SDL_LoadFunction(void *handle, const char *name)
{
void *symbol = dlsym(handle, name);
if (symbol == NULL) {
/* append an underscore for platforms that need that. */
size_t len = 1 + SDL_strlen(name) + 1;
char *_name = SDL_stack_alloc(char, len);
_name[0] = '_';
SDL_strlcpy(&_name[1], name, len);
symbol = dlsym(handle, _name);
SDL_stack_free(_name);
if (symbol == NULL) {
SDL_SetError("Failed loading %s: %s", name,
(const char *) dlerror());
}
}
return (symbol);
}
void
SDL_UnloadObject(void *handle)
{
if (handle != NULL) {
dlclose(handle);
}
}
#endif /* SDL_LOADSO_DLOPEN */
/* vi: set ts=4 sw=4 expandtab: */
| 1 | 0.744164 | 1 | 0.744164 | game-dev | MEDIA | 0.306487 | game-dev | 0.500977 | 1 | 0.500977 |
peterWon/D-LIOM | 3,757 | src/cartographer/cartographer/mapping/map_builder_interface.h | /*
* Copyright 2017 The Cartographer Authors
*
* 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 CARTOGRAPHER_MAPPING_MAP_BUILDER_INTERFACE_H_
#define CARTOGRAPHER_MAPPING_MAP_BUILDER_INTERFACE_H_
#include <set>
#include <string>
#include <vector>
#include "Eigen/Geometry"
#include "cartographer/common/lua_parameter_dictionary.h"
#include "cartographer/common/port.h"
#include "cartographer/io/proto_stream_interface.h"
#include "cartographer/mapping/id.h"
#include "cartographer/mapping/pose_graph_interface.h"
#include "cartographer/mapping/proto/submap_visualization.pb.h"
#include "cartographer/mapping/proto/trajectory_builder_options.pb.h"
#include "cartographer/mapping/submaps.h"
#include "cartographer/mapping/trajectory_builder_interface.h"
namespace cartographer {
namespace mapping {
// This interface is used for both library and RPC implementations.
// Implementations wire up the complete SLAM stack.
class MapBuilderInterface {
public:
using LocalSlamResultCallback =
TrajectoryBuilderInterface::LocalSlamResultCallback;
using SensorId = TrajectoryBuilderInterface::SensorId;
MapBuilderInterface() {}
virtual ~MapBuilderInterface() {}
MapBuilderInterface(const MapBuilderInterface&) = delete;
MapBuilderInterface& operator=(const MapBuilderInterface&) = delete;
// Creates a new trajectory builder and returns its index.
virtual int AddTrajectoryBuilder(
const std::set<SensorId>& expected_sensor_ids,
const proto::TrajectoryBuilderOptions& trajectory_options,
LocalSlamResultCallback local_slam_result_callback) = 0;
// Creates a new trajectory and returns its index. Querying the trajectory
// builder for it will return 'nullptr'.
virtual int AddTrajectoryForDeserialization(
const proto::TrajectoryBuilderOptionsWithSensorIds&
options_with_sensor_ids_proto) = 0;
// Returns the 'TrajectoryBuilderInterface' corresponding to the specified
// 'trajectory_id' or 'nullptr' if the trajectory has no corresponding
// builder.
virtual mapping::TrajectoryBuilderInterface* GetTrajectoryBuilder(
int trajectory_id) const = 0;
// Marks the TrajectoryBuilder corresponding to 'trajectory_id' as finished,
// i.e. no further sensor data is expected.
virtual void FinishTrajectory(int trajectory_id) = 0;
// Fills the SubmapQuery::Response corresponding to 'submap_id'. Returns an
// error string on failure, or an empty string on success.
virtual std::string SubmapToProto(const SubmapId& submap_id,
proto::SubmapQuery::Response* response) = 0;
// Serializes the current state to a proto stream.
virtual void SerializeState(io::ProtoStreamWriterInterface* writer) = 0;
// Loads the SLAM state from a proto stream.
virtual void LoadState(io::ProtoStreamReaderInterface* reader,
bool load_frozen_state) = 0;
virtual int num_trajectory_builders() const = 0;
virtual mapping::PoseGraphInterface* pose_graph() = 0;
virtual const std::vector<proto::TrajectoryBuilderOptionsWithSensorIds>&
GetAllTrajectoryBuilderOptions() const = 0;
};
} // namespace mapping
} // namespace cartographer
#endif // CARTOGRAPHER_MAPPING_MAP_BUILDER_INTERFACE_H_
| 1 | 0.943395 | 1 | 0.943395 | game-dev | MEDIA | 0.273488 | game-dev | 0.659633 | 1 | 0.659633 |
Placidina/MikScrollingBattleText | 109,472 | MikScrollingBattleText/MSBTProfiles.lua | -------------------------------------------------------------------------------
-- Title: Mik's Scrolling Battle Text Profiles
-- Author: Mikord
-------------------------------------------------------------------------------
-- Create module and set its name.
local module = {}
local moduleName = "Profiles"
MikSBT[moduleName] = module
-------------------------------------------------------------------------------
-- Imports.
-------------------------------------------------------------------------------
-- Local references to various modules for faster access.
local L = MikSBT.translations
-- Local references to various functions for faster access.
local string_find = string.find
local string_gsub = string.gsub
local string_format = string.format
local CopyTable = MikSBT.CopyTable
local EraseTable = MikSBT.EraseTable
local SplitString = MikSBT.SplitString
local Print = MikSBT.Print
local GetSkillName = MikSBT.GetSkillName
local IsClassic = WOW_PROJECT_ID >= WOW_PROJECT_CLASSIC
local LoadAddOn = C_AddOns and C_AddOns.LoadAddOn or LoadAddOn
local IsAddOnLoaded = C_AddOns and C_AddOns.IsAddOnLoaded or IsAddOnLoaded
-------------------------------------------------------------------------------
-- Private constants.
-------------------------------------------------------------------------------
local DEFAULT_PROFILE_NAME = "Default"
-- The .toc entries for saved variables.
local SAVED_VARS_NAME = "MSBTProfiles_SavedVars"
local SAVED_VARS_PER_CHAR_NAME = "MSBTProfiles_SavedVarsPerChar"
local SAVED_MEDIA_NAME = "MSBT_SavedMedia"
-- Localized pet name followed by a space.
local PET_SPACE = PET .. " "
-- Flags used by the combat log.
local FLAG_YOU = 0xF0000000
local TARGET_TARGET = 0x00010000
local REACTION_HOSTILE = 0x00000040
-- Spell IDs.
--local SPELLID_BERSERK = 93622
local SPELLID_ELUSIVE_BREW = 126453 -- Activated ability
local SPELLID_EXECUTE = 5308
local SPELLID_FIRST_AID = 3273
local SPELLID_HAMMER_OF_WRATH = 24275
--local SPELLID_KILL_SHOT = 53351
local SPELLID_LAVA_SURGE = not IsClassic and 77762
local SPELLID_REVENGE = 6572
local SPELLID_VICTORY_RUSH = not IsClassic and 34428
--local SPELLID_SHADOW_ORB = 77487
-- Trigger spell names.
--local SPELL_BERSERK = GetSkillName(SPELLID_BERSERK)
--local SPELL_BLINDSIDE = GetSkillName(121153)
--local SPELL_BLOODSURGE = GetSkillName(46916)
--local SPELL_BRAIN_FREEZE = GetSkillName(44549)
--local SPELL_BF_FIREBALL = GetSkillName(57761)
local SPELL_CLEARCASTING = GetSkillName(16870)
--local SPELL_DECIMATION = GetSkillName(108869)
local SPELL_ELUSIVE_BREW = not IsClassic and GetSkillName(128939)
local SPELL_EXECUTE = GetSkillName(SPELLID_EXECUTE)
local SPELL_FINGERS_OF_FROST = not IsClassic and GetSkillName(112965)
local SPELL_FREEZING_FOG = not IsClassic and GetSkillName(59052)
local SPELL_HAMMER_OF_WRATH = GetSkillName(SPELLID_HAMMER_OF_WRATH)
--local SPELL_KILL_SHOT = GetSkillName(SPELLID_KILL_SHOT)
local SPELL_KILLING_MACHINE = not IsClassic and GetSkillName(51124)
local SPELL_LAVA_SURGE = not IsClassic and GetSkillName(SPELLID_LAVA_SURGE)
--local SPELL_LOCK_AND_LOAD = GetSkillName(168980)
--local SPELL_MAELSTROM_WEAPON = GetSkillName(53817)
--local SPELL_MANA_TEA = GetSkillName(115867)
local SPELL_MISSILE_BARRAGE = not IsClassic and GetSkillName(62401)
--local SPELL_MOLTEN_CORE = GetSkillName(122351)
--local SPELL_NIGHTFALL = GetSkillName(108558)
local SPELL_PREDATORS_SWIFTNESS = not IsClassic and GetSkillName(69369)
local SPELL_PVP_TRINKET = not IsClassic and GetSkillName(42292)
local SPELL_REVENGE = GetSkillName(SPELLID_REVENGE)
local SPELL_RIME = not IsClassic and GetSkillName(59057)
local SPELL_SHADOW_TRANCE = GetSkillName(17941)
local SPELL_SHIELD_SLAM = GetSkillName(23922)
--local SPELL_SHADOW_INFUSION = GetSkillName(91342)
--local SPELL_SHADOW_ORB = GetSkillName(SPELLID_SHADOW_ORB)
--local SPELL_SHOOTING_STARS = GetSkillName(93400)
local SPELL_SUDDEN_DEATH = not IsClassic and GetSkillName(52437)
local SPELL_SUDDEN_DOOM = not IsClassic and GetSkillName(81340) -- XXX: No trigger atm - DK
--local SPELL_SWORD_AND_BOARD = GetSkillName(50227)
--local SPELL_TASTE_FOR_BLOOD = GetSkillName(56636)
--local SPELL_THE_ART_OF_WAR = GetSkillName(59578)
local SPELL_TIDAL_WAVES = not IsClassic and GetSkillName(53390)
--local SPELL_ULTIMATUM = GetSkillName(122510)
local SPELL_VICTORY_RUSH = not IsClassic and GetSkillName(SPELLID_VICTORY_RUSH) -- XXX: Update for buff
--local SPELL_VITAL_MISTS = GetSkillName(122107)
-- Throttle, suppression, and other spell names.
--local SPELL_BLOOD_PRESENCE = GetSkillName(48266)
local SPELL_DRAIN_LIFE = not IsClassic and GetSkillName(234153)
local SPELL_SHADOWMEND = not IsClassic and GetSkillName(39373)
--local SPELL_REFLECTIVE_SHIELD = GetSkillName(58252)
local SPELL_UNDYING_RESOLVE = not IsClassic and GetSkillName(51915)
local SPELL_VAMPIRIC_EMBRACE = GetSkillName(15286)
local SPELL_VAMPIRIC_TOUCH = not IsClassic and GetSkillName(34914)
-------------------------------------------------------------------------------
-- Private variables.
-------------------------------------------------------------------------------
--- Prevent tainting global _.
local _
-- Dynamically created frame for receiving events.
local eventFrame
-- Meta table for the differential profile tables.
local differentialMap = {}
local differential_mt = { __index = function(t,k) return differentialMap[t][k] end }
local differentialCache = {}
-- Holds variables to be saved between sessions.
local savedVariables
local savedVariablesPerChar
local savedMedia
-- Currently selected profile.
local currentProfile
-- Path information for setting differential options.
local pathTable = {}
-- Flag to hold whether or not this is the first load.
local isFirstLoad
-------------------------------------------------------------------------------
-- Master profile utility functions.
-------------------------------------------------------------------------------
-- ****************************************************************************
-- Returns a table to be used for the settings of the passed class using color
-- information from the default class colors table.
-- ****************************************************************************
local function CreateClassSettingsTable(class)
-- Return disabled settings if the class doesn't exist in the default class colors table for some reason.
if (not RAID_CLASS_COLORS[class]) then return { disabled = true, colorR = 1, colorG = 1, colorB = 1 } end
-- Return a table using the default class color.
return { colorR = RAID_CLASS_COLORS[class].r, colorG = RAID_CLASS_COLORS[class].g, colorB = RAID_CLASS_COLORS[class].b }
end
-------------------------------------------------------------------------------
-- Master profile.
-------------------------------------------------------------------------------
local masterProfile
if IsClassic then
masterProfile = {
-- Scroll area settings.
scrollAreas = {
Incoming = {
name = L.MSG_INCOMING,
offsetX = -140,
offsetY = -160,
animationStyle = "Parabola",
direction = "Down",
behavior = "CurvedLeft",
stickyBehavior = "Jiggle",
textAlignIndex = 3,
stickyTextAlignIndex = 3,
},
Outgoing = {
name = L.MSG_OUTGOING,
offsetX = 100,
offsetY = -160,
animationStyle = "Parabola",
direction = "Down",
behavior = "CurvedRight",
stickyBehavior = "Jiggle",
textAlignIndex = 1,
stickyTextAlignIndex = 1,
iconAlign = "Right",
},
Notification = {
name = L.MSG_NOTIFICATION,
offsetX = -175,
offsetY = 120,
scrollHeight = 200,
scrollWidth = 350,
},
Static = {
name = L.MSG_STATIC,
offsetX = -20,
offsetY = -300,
scrollHeight = 125,
animationStyle = "Static",
direction = "Down",
},
},
-- Built-in event settings.
events = {
INCOMING_DAMAGE = {
colorG = 0,
colorB = 0,
message = "(%n) -%a",
scrollArea = "Incoming",
},
INCOMING_DAMAGE_CRIT = {
colorG = 0,
colorB = 0,
message = "(%n) -%a",
scrollArea = "Incoming",
isCrit = true,
},
INCOMING_MISS = {
colorR = 0,
colorG = 0,
message = MISS .. "!",
scrollArea = "Incoming",
},
INCOMING_DODGE = {
colorR = 0,
colorG = 0,
message = DODGE .. "!",
scrollArea = "Incoming",
},
INCOMING_PARRY = {
colorR = 0,
colorG = 0,
message = PARRY .. "!",
scrollArea = "Incoming",
},
INCOMING_BLOCK = {
colorR = 0,
colorG = 0,
message = BLOCK .. "!",
scrollArea = "Incoming",
},
INCOMING_DEFLECT = {
colorR = 0,
colorG = 0,
message = DEFLECT .. "!",
scrollArea = "Incoming",
},
INCOMING_ABSORB = {
colorB = 0,
message = ABSORB .. "! <%a>",
scrollArea = "Incoming",
},
INCOMING_IMMUNE = {
colorB = 0,
message = IMMUNE .. "!",
scrollArea = "Incoming",
},
INCOMING_SPELL_DAMAGE = {
colorG = 0,
colorB = 0,
message = "(%s) -%a",
scrollArea = "Incoming",
},
INCOMING_SPELL_DAMAGE_CRIT = {
colorG = 0,
colorB = 0,
message = "(%s) -%a",
scrollArea = "Incoming",
isCrit = true,
},
INCOMING_SPELL_DAMAGE_SHIELD = {
colorG = 0,
colorB = 0,
message = "(%s) -%a",
scrollArea = "Incoming",
},
INCOMING_SPELL_DAMAGE_SHIELD_CRIT = {
colorG = 0,
colorB = 0,
message = "(%s) -%a",
scrollArea = "Incoming",
isCrit = true,
},
INCOMING_SPELL_DOT = {
colorG = 0,
colorB = 0,
message = "(%s) -%a",
scrollArea = "Incoming",
},
INCOMING_SPELL_DOT_CRIT = {
colorG = 0,
colorB = 0,
message = "(%s) -%a",
scrollArea = "Incoming",
isCrit = true,
},
INCOMING_SPELL_MISS = {
colorR = 0,
colorG = 0,
message = "(%s) " .. MISS .. "!",
scrollArea = "Incoming",
},
INCOMING_SPELL_DODGE = {
colorR = 0,
colorG = 0,
message = "(%s) " .. DODGE .. "!",
scrollArea = "Incoming",
},
INCOMING_SPELL_PARRY = {
colorR = 0,
colorG = 0,
message = "(%s) " .. PARRY .. "!",
scrollArea = "Incoming",
},
INCOMING_SPELL_BLOCK = {
colorR = 0,
colorG = 0,
message = "(%s) " .. BLOCK .. "!",
scrollArea = "Incoming",
},
INCOMING_SPELL_DEFLECT = {
colorR = 0,
colorG = 0,
message = "(%s) " .. DEFLECT .. "!",
scrollArea = "Incoming",
},
INCOMING_SPELL_RESIST = {
colorR = 0.5,
colorG = 0,
colorB = 0.5,
message = "(%s) " .. RESIST .. "!",
scrollArea = "Incoming",
},
INCOMING_SPELL_ABSORB = {
colorB = 0,
message = "(%s) " .. ABSORB .. "! <%a>",
scrollArea = "Incoming",
},
INCOMING_SPELL_IMMUNE = {
colorB = 0,
message = "(%s) " .. IMMUNE .. "!",
scrollArea = "Incoming",
},
INCOMING_SPELL_REFLECT = {
colorR = 0.5,
colorG = 0,
colorB = 0.5,
message = "(%s) " .. REFLECT .. "!",
scrollArea = "Incoming",
},
INCOMING_SPELL_INTERRUPT = {
colorB = 0,
message = "(%s) " .. INTERRUPT .. "!",
scrollArea = "Incoming",
},
INCOMING_HEAL = {
colorR = 0,
colorB = 0,
message = "(%s - %n) +%a",
scrollArea = "Incoming",
},
INCOMING_HEAL_CRIT = {
colorR = 0,
colorB = 0,
message = "(%s - %n) +%a",
fontSize = 22,
scrollArea = "Incoming",
isCrit = true,
},
INCOMING_HOT = {
colorR = 0,
colorB = 0,
message = "(%s - %n) +%a",
scrollArea = "Incoming",
},
INCOMING_HOT_CRIT = {
colorR = 0,
colorB = 0,
message = "(%s - %n) +%a",
scrollArea = "Incoming",
isCrit = true,
},
SELF_HEAL = {
colorR = 0,
colorB = 0,
message = "(%s - %n) +%a",
scrollArea = "Incoming",
},
SELF_HEAL_CRIT = {
colorR = 0,
colorB = 0,
message = "(%s - %n) +%a",
fontSize = 22,
scrollArea = "Incoming",
isCrit = true,
},
SELF_HOT = {
colorR = 0,
colorB = 0,
message = "(%s - %n) +%a",
scrollArea = "Incoming",
},
SELF_HOT_CRIT = {
colorR = 0,
colorB = 0,
message = "(%s - %n) +%a",
scrollArea = "Incoming",
isCrit = true,
},
INCOMING_ENVIRONMENTAL = {
colorG = 0,
colorB = 0,
message = "-%a %e",
scrollArea = "Incoming",
},
OUTGOING_DAMAGE = {
message = "%a",
scrollArea = "Outgoing",
},
OUTGOING_DAMAGE_CRIT = {
message = "%a",
scrollArea = "Outgoing",
isCrit = true,
},
OUTGOING_MISS = {
message = MISS .. "!",
scrollArea = "Outgoing",
},
OUTGOING_DODGE = {
message = DODGE .. "!",
scrollArea = "Outgoing",
},
OUTGOING_PARRY = {
message = PARRY .. "!",
scrollArea = "Outgoing",
},
OUTGOING_BLOCK = {
message = BLOCK .. "!",
scrollArea = "Outgoing",
},
OUTGOING_DEFLECT = {
message = DEFLECT.. "!",
scrollArea = "Outgoing",
},
OUTGOING_ABSORB = {
colorB = 0,
message = "<%a> " .. ABSORB .. "!",
scrollArea = "Outgoing",
},
OUTGOING_IMMUNE = {
colorB = 0,
message = IMMUNE .. "!",
scrollArea = "Outgoing",
},
OUTGOING_EVADE = {
colorG = 0.5,
colorB = 0,
message = EVADE .. "!",
fontSize = 22,
scrollArea = "Outgoing",
},
OUTGOING_SPELL_DAMAGE = {
colorB = 0,
message = "%a (%s)",
scrollArea = "Outgoing",
},
OUTGOING_SPELL_DAMAGE_CRIT = {
colorB = 0,
message = "%a (%s)",
scrollArea = "Outgoing",
isCrit = true,
},
OUTGOING_SPELL_DAMAGE_SHIELD = {
colorB = 0,
message = "%a (%s)",
scrollArea = "Outgoing",
},
OUTGOING_SPELL_DAMAGE_SHIELD_CRIT = {
colorB = 0,
message = "%a (%s)",
scrollArea = "Outgoing",
isCrit = true,
},
OUTGOING_SPELL_DOT = {
colorB = 0,
message = "%a (%s)",
scrollArea = "Outgoing",
},
OUTGOING_SPELL_DOT_CRIT = {
colorB = 0,
message = "%a (%s)",
scrollArea = "Outgoing",
isCrit = true,
},
OUTGOING_SPELL_MISS = {
message = MISS .. "! (%s)",
scrollArea = "Outgoing",
},
OUTGOING_SPELL_DODGE = {
message = DODGE .. "! (%s)",
scrollArea = "Outgoing",
},
OUTGOING_SPELL_PARRY = {
message = PARRY .. "! (%s)",
scrollArea = "Outgoing",
},
OUTGOING_SPELL_BLOCK = {
message = BLOCK .. "! (%s)",
scrollArea = "Outgoing",
},
OUTGOING_SPELL_DEFLECT = {
message = DEFLECT .. "! (%s)",
scrollArea = "Outgoing",
},
OUTGOING_SPELL_RESIST = {
colorR = 0.5,
colorG = 0.5,
colorB = 0.698,
message = RESIST .. "! (%s)",
scrollArea = "Outgoing",
},
OUTGOING_SPELL_ABSORB = {
colorB = 0,
message = "<%a> " .. ABSORB .. "! (%s)",
scrollArea = "Outgoing",
},
OUTGOING_SPELL_IMMUNE = {
colorB = 0,
message = IMMUNE .. "! (%s)",
scrollArea = "Outgoing",
},
OUTGOING_SPELL_REFLECT = {
colorB = 0,
message = REFLECT .. "! (%s)",
scrollArea = "Outgoing",
},
OUTGOING_SPELL_INTERRUPT = {
colorB = 0,
message = INTERRUPT .. "! (%s)",
scrollArea = "Outgoing",
},
OUTGOING_SPELL_EVADE = {
colorG = 0.5,
colorB = 0,
message = EVADE .. "! (%s)",
fontSize = 22,
scrollArea = "Outgoing",
},
OUTGOING_HEAL = {
colorR = 0,
colorB = 0,
message = "+%a (%s - %n)",
scrollArea = "Outgoing",
},
OUTGOING_HEAL_CRIT = {
colorR = 0,
colorB = 0,
message = "+%a (%s - %n)",
fontSize = 22,
scrollArea = "Outgoing",
isCrit = true,
},
OUTGOING_HOT = {
colorR = 0,
colorB = 0,
message = "+%a (%s - %n)",
scrollArea = "Outgoing",
},
OUTGOING_HOT_CRIT = {
colorR = 0,
colorB = 0,
message = "+%a (%s - %n)",
scrollArea = "Outgoing",
isCrit = true,
},
OUTGOING_DISPEL = {
colorB = 0.5,
message = L.MSG_DISPEL .. "! (%s)",
scrollArea = "Outgoing",
},
PET_INCOMING_DAMAGE = {
colorG = 0.41,
colorB = 0.41,
message = "(%n) " .. PET .. " -%a",
scrollArea = "Incoming",
},
PET_INCOMING_DAMAGE_CRIT = {
colorG = 0.41,
colorB = 0.41,
message = "(%n) " .. PET .. " -%a",
scrollArea = "Incoming",
isCrit = true,
},
PET_INCOMING_MISS = {
colorR = 0.57,
colorG = 0.58,
message = PET .. " " .. MISS .. "!",
scrollArea = "Incoming",
},
PET_INCOMING_DODGE = {
colorR = 0.57,
colorG = 0.58,
message = PET .. " " .. DODGE .. "!",
scrollArea = "Incoming",
},
PET_INCOMING_PARRY = {
colorR = 0.57,
colorG = 0.58,
message = PET .. " " .. PARRY .. "!",
scrollArea = "Incoming",
},
PET_INCOMING_BLOCK = {
colorR = 0.57,
colorG = 0.58,
message = PET .. " " .. BLOCK .. "!",
scrollArea = "Incoming",
},
PET_INCOMING_DEFLECT = {
colorR = 0.57,
colorG = 0.58,
message = PET .. " " .. DEFLECT .. "!",
scrollArea = "Incoming",
},
PET_INCOMING_ABSORB = {
colorB = 0.57,
message = PET .. " " .. ABSORB .. "! <%a>",
scrollArea = "Incoming",
},
PET_INCOMING_IMMUNE = {
colorB = 0.57,
message = PET .. " " .. IMMUNE .. "!",
scrollArea = "Incoming",
},
PET_INCOMING_SPELL_DAMAGE = {
colorG = 0.41,
colorB = 0.41,
message = "(%s) " .. PET .. " -%a",
scrollArea = "Incoming",
},
PET_INCOMING_SPELL_DAMAGE_CRIT = {
colorG = 0.41,
colorB = 0.41,
message = "(%s) " .. PET .. " -%a",
scrollArea = "Incoming",
isCrit = true,
},
PET_INCOMING_SPELL_DAMAGE_SHIELD = {
colorG = 0.41,
colorB = 0.41,
message = "(%s) " .. PET .. " -%a",
scrollArea = "Incoming",
},
PET_INCOMING_SPELL_DAMAGE_SHIELD_CRIT = {
colorG = 0.41,
colorB = 0.41,
message = "(%s) " .. PET .. " -%a",
scrollArea = "Incoming",
isCrit = true,
},
PET_INCOMING_SPELL_DOT = {
colorG = 0.41,
colorB = 0.41,
message = "(%s) " .. PET .. " -%a",
scrollArea = "Incoming",
},
PET_INCOMING_SPELL_DOT_CRIT = {
colorG = 0.41,
colorB = 0.41,
message = "(%s) " .. PET .. " -%a",
scrollArea = "Incoming",
isCrit = true,
},
PET_INCOMING_SPELL_MISS = {
colorR = 0.57,
colorG = 0.58,
message = "(%s) " .. PET .. " " .. MISS .. "!",
scrollArea = "Incoming",
},
PET_INCOMING_SPELL_DODGE = {
colorR = 0.57,
colorG = 0.58,
message = "(%s) " .. PET .. " " .. DODGE .. "!",
scrollArea = "Incoming",
},
PET_INCOMING_SPELL_PARRY = {
colorR = 0.57,
colorG = 0.58,
message = "(%s) " .. PET .. " " .. PARRY .. "!",
scrollArea = "Incoming",
},
PET_INCOMING_SPELL_BLOCK = {
colorR = 0.57,
colorG = 0.58,
message = "(%s) " .. PET .. " " .. BLOCK .. "!",
scrollArea = "Incoming",
},
PET_INCOMING_SPELL_DEFLECT = {
colorR = 0.57,
colorG = 0.58,
message = "(%s) " .. PET .. " " .. DEFLECT .. "!",
scrollArea = "Incoming",
},
PET_INCOMING_SPELL_RESIST = {
colorR = 0.94,
colorG = 0,
colorB = 0.94,
message = "(%s) " .. PET .. " " .. RESIST .. "!",
scrollArea = "Incoming",
},
PET_INCOMING_SPELL_ABSORB = {
colorB = 0.57,
message = "(%s) " .. PET .. " " .. ABSORB .. "! <%a>",
scrollArea = "Incoming",
},
PET_INCOMING_SPELL_IMMUNE = {
colorB = 0.57,
message = "(%s) " .. PET .. " " .. IMMUNE .. "!",
scrollArea = "Incoming",
},
PET_INCOMING_HEAL = {
colorR = 0.57,
colorB = 0.57,
message = "(%s - %n) " .. PET .. " +%a",
scrollArea = "Incoming",
},
PET_INCOMING_HEAL_CRIT = {
colorR = 0.57,
colorB = 0.57,
message = "(%s - %n) " .. PET .. " +%a",
scrollArea = "Incoming",
isCrit = true,
},
PET_INCOMING_HOT = {
colorR = 0.57,
colorB = 0.57,
message = "(%s - %n) " .. PET .. " +%a",
scrollArea = "Incoming",
},
PET_INCOMING_HOT_CRIT = {
colorR = 0.57,
colorB = 0.57,
message = "(%s - %n) " .. PET .. " +%a",
scrollArea = "Incoming",
isCrit = true,
},
PET_OUTGOING_DAMAGE = {
colorG = 0.5,
colorB = 0,
message = PET .. " %a",
scrollArea = "Outgoing",
},
PET_OUTGOING_DAMAGE_CRIT = {
colorG = 0.5,
colorB = 0,
message = PET .. " %a",
scrollArea = "Outgoing",
isCrit = true,
},
PET_OUTGOING_MISS = {
colorG = 0.5,
colorB = 0,
message = PET .. " " .. MISS,
scrollArea = "Outgoing",
},
PET_OUTGOING_DODGE = {
colorG = 0.5,
colorB = 0,
message = PET .. " " .. DODGE,
scrollArea = "Outgoing",
},
PET_OUTGOING_PARRY = {
colorG = 0.5,
colorB = 0,
message = PET .. " " .. PARRY,
scrollArea = "Outgoing",
},
PET_OUTGOING_BLOCK = {
colorG = 0.5,
colorB = 0,
message = PET .. " " .. BLOCK,
scrollArea = "Outgoing",
},
PET_OUTGOING_DEFLECT = {
colorG = 0.5,
colorB = 0,
message = PET .. " " .. DEFLECT,
scrollArea = "Outgoing",
},
PET_OUTGOING_ABSORB = {
colorR = 0.5,
colorG = 0.5,
message = PET .. " <%a> " .. ABSORB,
scrollArea = "Outgoing",
},
PET_OUTGOING_IMMUNE = {
colorR = 0.5,
colorG = 0.5,
message = PET .. " " .. IMMUNE,
scrollArea = "Outgoing",
},
PET_OUTGOING_EVADE = {
colorG = 0.77,
colorB = 0.57,
message = PET .. " " .. EVADE,
fontSize = 22,
scrollArea = "Outgoing",
},
PET_OUTGOING_SPELL_DAMAGE = {
colorR = 0.33,
colorG = 0.33,
message = PET .. " %a (%s)",
scrollArea = "Outgoing",
},
PET_OUTGOING_SPELL_DAMAGE_CRIT = {
colorR = 0.33,
colorG = 0.33,
message = PET .. " %a (%s)",
scrollArea = "Outgoing",
isCrit = true,
},
PET_OUTGOING_SPELL_DAMAGE_SHIELD = {
colorR = 0.33,
colorG = 0.33,
message = PET .. " %a (%s)",
scrollArea = "Outgoing",
},
PET_OUTGOING_SPELL_DAMAGE_SHIELD_CRIT = {
colorR = 0.33,
colorG = 0.33,
message = PET .. " %a (%s)",
scrollArea = "Outgoing",
isCrit = true,
},
PET_OUTGOING_SPELL_DOT = {
colorR = 0.33,
colorG = 0.33,
message = PET .. " %a (%s)",
scrollArea = "Outgoing",
},
PET_OUTGOING_SPELL_DOT_CRIT = {
colorR = 0.33,
colorG = 0.33,
message = PET .. " %a (%s)",
scrollArea = "Outgoing",
isCrit = true,
},
PET_OUTGOING_SPELL_MISS = {
colorR = 0.33,
colorG = 0.33,
message = PET .. " " .. MISS .. "! (%s)",
scrollArea = "Outgoing",
},
PET_OUTGOING_SPELL_DODGE = {
colorR = 0.33,
colorG = 0.33,
message = PET .. " " .. DODGE .. "! (%s)",
scrollArea = "Outgoing",
},
PET_OUTGOING_SPELL_PARRY = {
colorR = 0.33,
colorG = 0.33,
message = PET .. " " .. PARRY .. "! (%s)",
scrollArea = "Outgoing",
},
PET_OUTGOING_SPELL_BLOCK = {
colorR = 0.33,
colorG = 0.33,
message = PET .. " " .. BLOCK .. "! (%s)",
scrollArea = "Outgoing",
},
PET_OUTGOING_SPELL_DEFLECT = {
colorR = 0.33,
colorG = 0.33,
message = PET .. " " .. DEFLECT .. "! (%s)",
scrollArea = "Outgoing",
},
PET_OUTGOING_SPELL_RESIST = {
colorR = 0.73,
colorG = 0.73,
colorB = 0.84,
message = PET .. " " .. RESIST .. "! (%s)",
scrollArea = "Outgoing",
},
PET_OUTGOING_SPELL_ABSORB = {
colorR = 0.5,
colorG = 0.5,
message = PET .. " <%a> " .. ABSORB .. "! (%s)",
scrollArea = "Outgoing",
},
PET_OUTGOING_SPELL_IMMUNE = {
colorR = 0.5,
colorG = 0.5,
message = PET .. " " .. IMMUNE .. "! (%s)",
scrollArea = "Outgoing",
},
PET_OUTGOING_SPELL_EVADE = {
colorG = 0.77,
colorB = 0.57,
message = PET .. " " .. EVADE .. "! (%s)",
scrollArea = "Outgoing",
},
PET_OUTGOING_HEAL = {
colorR = 0.57,
colorB = 0.57,
message = PET .. " " .. "+%a (%s - %n)",
scrollArea = "Outgoing",
},
PET_OUTGOING_HEAL_CRIT = {
colorR = 0.57,
colorB = 0.57,
message = PET .. " " .. "+%a (%s - %n)",
fontSize = 22,
scrollArea = "Outgoing",
isCrit = true,
},
PET_OUTGOING_HOT = {
colorR = 0.57,
colorB = 0.57,
message = PET .. " " .. "+%a (%s - %n)",
scrollArea = "Outgoing",
},
PET_OUTGOING_HOT_CRIT = {
colorR = 0.57,
colorB = 0.57,
message = PET .. " " .. "+%a (%s - %n)",
scrollArea = "Outgoing",
isCrit = true,
},
PET_OUTGOING_DISPEL = {
colorB = 0.73,
message = PET .. " " .. L.MSG_DISPEL .. "! (%s)",
scrollArea = "Outgoing",
},
NOTIFICATION_DEBUFF = {
colorR = 0,
colorG = 0.5,
colorB = 0.5,
message = "[%sl]",
},
NOTIFICATION_DEBUFF_STACK = {
colorR = 0,
colorG = 0.5,
colorB = 0.5,
message = "[%sl %a]",
},
NOTIFICATION_BUFF = {
colorR = 0.698,
colorG = 0.698,
colorB = 0,
message = "[%sl]",
},
NOTIFICATION_BUFF_STACK = {
colorR = 0.698,
colorG = 0.698,
colorB = 0,
message = "[%sl %a]",
},
NOTIFICATION_ITEM_BUFF = {
colorR = 0.698,
colorG = 0.698,
colorB = 0.698,
message = "[%sl]",
},
NOTIFICATION_DEBUFF_FADE = {
colorR = 0,
colorG = 0.835,
colorB = 0.835,
message = "-[%sl]",
},
NOTIFICATION_BUFF_FADE = {
colorR = 0.918,
colorG = 0.918,
colorB = 0,
message = "-[%sl]",
},
NOTIFICATION_ITEM_BUFF_FADE = {
colorR = 0.831,
colorG = 0.831,
colorB = 0.831,
message = "-[%sl]",
},
NOTIFICATION_COMBAT_ENTER = {
message = "+" .. L.MSG_COMBAT,
},
NOTIFICATION_COMBAT_LEAVE = {
message = "-" .. L.MSG_COMBAT,
},
NOTIFICATION_POWER_GAIN = {
colorB = 0,
message = "+%a %p",
},
NOTIFICATION_POWER_LOSS = {
colorB = 0,
message = "-%a %p",
},
NOTIFICATION_ALT_POWER_GAIN = {
colorR = 0,
colorG = 0.5,
colorB = 0.5,
message = "+%a %p",
},
NOTIFICATION_ALT_POWER_LOSS = {
colorR = 0,
colorG = 0.5,
colorB = 0.5,
message = "-%a %p",
},
NOTIFICATION_CHI_CHANGE = {
colorR = 0.5,
colorG = 0.8,
colorB = 0.7,
message = "%a " .. CHI,
},
NOTIFICATION_CHI_FULL = {
colorR = 0.5,
colorG = 0.8,
colorB = 0.7,
message = L.MSG_CHI_FULL .. "!",
alwaysSticky = true,
fontSize = 26,
},
NOTIFICATION_AC_CHANGE = {
colorR = 0.3,
colorG = 0.7,
colorB = 0.9,
message = "%a " .. L.MSG_AC,
},
NOTIFICATION_AC_FULL = {
colorR = 0.3,
colorG = 0.7,
colorB = 0.9,
message = L.MSG_AC_FULL .. "!",
alwaysSticky = true,
fontSize = 26,
},
NOTIFICATION_CP_GAIN = {
colorG = 0.5,
colorB = 0,
message = "%a " .. L.MSG_CP,
},
NOTIFICATION_CP_FULL = {
colorR = 0.8,
colorG = 0,
colorB = 0,
message = L.MSG_CP_FULL .. "!",
alwaysSticky = true,
fontSize = 26,
},
NOTIFICATION_HOLY_POWER_CHANGE = {
colorG = 0.5,
colorB = 0,
message = "%a " .. HOLY_POWER,
},
NOTIFICATION_HOLY_POWER_FULL = {
colorG = 0.5,
colorB = 0,
message = L.MSG_HOLY_POWER_FULL .. "!",
alwaysSticky = true,
fontSize = 26,
},
NOTIFICATION_HONOR_GAIN = {
colorR = 0.5,
colorG = 0.5,
colorB = 0.698,
message = "+%a " .. HONOR,
},
NOTIFICATION_REP_GAIN = {
colorR = 0.5,
colorG = 0.5,
colorB = 0.698,
message = "+%a " .. REPUTATION .. " (%e)",
},
NOTIFICATION_REP_LOSS = {
colorR = 0.5,
colorG = 0.5,
colorB = 0.698,
message = "-%a " .. REPUTATION .. " (%e)",
},
NOTIFICATION_SKILL_GAIN = {
colorR = 0.333,
colorG = 0.333,
message = "%sl: %a",
},
NOTIFICATION_EXPERIENCE_GAIN = {
disabled = true,
colorR = 0.756,
colorG = 0.270,
colorB = 0.823,
message = "%a " .. XP,
alwaysSticky = true,
fontSize = 26,
},
NOTIFICATION_PC_KILLING_BLOW = {
colorR = 0.333,
colorG = 0.333,
message = L.MSG_KILLING_BLOW .. "! (%n)",
alwaysSticky = true,
fontSize = 26,
},
NOTIFICATION_NPC_KILLING_BLOW = {
disabled = true,
colorR = 0.333,
colorG = 0.333,
message = L.MSG_KILLING_BLOW .. "! (%n)",
alwaysSticky = true,
fontSize = 26,
},
NOTIFICATION_EXTRA_ATTACK = {
colorB = 0,
message = "%sl!",
alwaysSticky = true,
fontSize = 26,
},
NOTIFICATION_ENEMY_BUFF = {
colorB = 0.5,
message = "%n: [%sl]",
scrollArea = "Static",
},
NOTIFICATION_MONSTER_EMOTE = {
colorG = 0.5,
colorB = 0,
message = "%e",
scrollArea = "Static",
},
NOTIFICATION_MONEY = {
message = "+%e",
scrollArea = "Static",
},
NOTIFICATION_COOLDOWN = {
message = "%e " .. L.MSG_READY_NOW .. "!",
scrollArea = "Static",
fontSize = 22,
soundFile = "MSBT Cooldown",
skillColorR = 1,
skillColorG = 0,
skillColorB = 0,
},
NOTIFICATION_PET_COOLDOWN = {
colorR = 0.57,
colorG = 0.58,
message = PET .. " %e " .. L.MSG_READY_NOW .. "!",
scrollArea = "Static",
fontSize = 22,
soundFile = "MSBT Cooldown",
skillColorR = 1,
skillColorG = 0.41,
skillColorB = 0.41,
},
NOTIFICATION_ITEM_COOLDOWN = {
colorR = 0.784,
colorG = 0.784,
colorB = 0,
message = " %e " .. L.MSG_READY_NOW .. "!",
scrollArea = "Static",
fontSize = 22,
soundFile = "MSBT Cooldown",
skillColorR = 1,
skillColorG = 0.588,
skillColorB = 0.588,
},
NOTIFICATION_LOOT = {
colorB = 0,
message = "+%a %e (%t)",
scrollArea = "Static",
},
NOTIFICATION_CURRENCY = {
colorB = 0,
message = "+%a %e (%t)",
scrollArea = "Static",
},
}, -- End events
-- Default trigger settings.
triggers = {
--[[MSBT_TRIGGER_BERSERK = {
colorG = 0.25,
colorB = 0.25,
message = SPELL_BERSERK,
alwaysSticky = true,
fontSize = 26,
classes = "DRUID",
mainEvents = "SPELL_AURA_APPLIED{skillID;;eq;;" .. SPELLID_BERSERK .. ";;recipientAffiliation;;eq;;" .. FLAG_YOU .. "}",
},]]
--[[MSBT_TRIGGER_BLINDSIDE = {
colorR = 0.709,
colorG = 0,
colorB = 0.709,
message = SPELL_BLINDSIDE .. "!",
alwaysSticky = true,
fontSize = 26,
classes = "ROGUE",
mainEvents = "SPELL_AURA_APPLIED{skillName;;eq;;" .. SPELL_BLINDSIDE .. ";;recipientAffiliation;;eq;;" .. FLAG_YOU .. "}"
},]]
--[[MSBT_TRIGGER_BLOODSURGE = {
colorR = 0.8,
colorG = 0.5,
colorB = 0.5,
message = SPELL_BLOODSURGE .. "!",
alwaysSticky = true,
fontSize = 26,
classes = "WARRIOR",
mainEvents = "SPELL_AURA_APPLIED{skillName;;eq;;" .. SPELL_BLOODSURGE .. ";;recipientAffiliation;;eq;;" .. FLAG_YOU .. "}"
},]]
--[[MSBT_TRIGGER_BRAIN_FREEZE = {
colorG = 0.627,
colorB = 0.627,
message = SPELL_BRAIN_FREEZE .. "!",
alwaysSticky = true,
fontSize = 26,
classes = "MAGE",
mainEvents = "SPELL_AURA_APPLIED{skillName;;eq;;" .. SPELL_BF_FIREBALL .. ";;recipientAffiliation;;eq;;" .. FLAG_YOU .. "}",
},]]
MSBT_TRIGGER_CLEARCASTING = {
colorB = 0,
message = SPELL_CLEARCASTING .. "!",
alwaysSticky = true,
fontSize = 26,
classes = "DRUID,MAGE,PRIEST,SHAMAN",
mainEvents = "SPELL_AURA_APPLIED{skillName;;eq;;" .. SPELL_CLEARCASTING .. ";;recipientAffiliation;;eq;;" .. FLAG_YOU .. "}",
},
--[[MSBT_TRIGGER_DECIMATION = {
colorG = 0.627,
colorB = 0.627,
message = SPELL_DECIMATION .. "!",
alwaysSticky = true,
fontSize = 26,
classes = "WARLOCK",
mainEvents = "SPELL_AURA_APPLIED{skillName;;eq;;" .. SPELL_DECIMATION .. ";;recipientAffiliation;;eq;;" .. FLAG_YOU .. "}",
},]]
--[[MSBT_TRIGGER_ELUSIVE_BREW = {
colorB = 0,
message = SPELL_ELUSIVE_BREW .. " x%a!",
alwaysSticky = true,
fontSize = 26,
classes = "MONK",
mainEvents = "SPELL_AURA_APPLIED{skillName;;eq;;" .. SPELL_ELUSIVE_BREW .. ";;amount;;eq;;5;;recipientAffiliation;;eq;;" .. FLAG_YOU .. "}&&" ..
"SPELL_AURA_APPLIED{skillName;;eq;;" .. SPELL_ELUSIVE_BREW .. ";;amount;;eq;;10;;recipientAffiliation;;eq;;" .. FLAG_YOU .. "}&&" ..
"SPELL_AURA_APPLIED{skillName;;eq;;" .. SPELL_ELUSIVE_BREW .. ";;amount;;eq;;15;;recipientAffiliation;;eq;;" .. FLAG_YOU .. "}",
},]]
MSBT_TRIGGER_EXECUTE = {
colorB = 0,
message = SPELL_EXECUTE .. "!",
alwaysSticky = true,
fontSize = 26,
classes = "WARRIOR",
mainEvents = "UNIT_HEALTH{unitID;;eq;;target;;threshold;;lt;;20;;unitReaction;;eq;;" .. REACTION_HOSTILE .. "}",
exceptions = "unavailableSkill;;eq;;" .. SPELL_EXECUTE,
iconSkill = SPELLID_EXECUTE,
},
--[[MSBT_TRIGGER_FINGERS_OF_FROST = {
colorR = 0.118,
colorG = 0.882,
message = SPELL_FINGERS_OF_FROST .. "!",
alwaysSticky = true,
fontSize = 26,
classes = "MAGE",
mainEvents = "SPELL_AURA_APPLIED{skillName;;eq;;" .. SPELL_FINGERS_OF_FROST .. ";;recipientAffiliation;;eq;;" .. FLAG_YOU .. "}",
exceptions = "recentlyFired;;lt;;2",
},]]
MSBT_TRIGGER_HAMMER_OF_WRATH = {
colorB = 0,
message = SPELL_HAMMER_OF_WRATH .. "!",
alwaysSticky = true,
fontSize = 26,
classes = "PALADIN",
mainEvents = "UNIT_HEALTH{unitID;;eq;;target;;threshold;;lt;;20;;unitReaction;;eq;;" .. REACTION_HOSTILE .. "}",
exceptions = "unavailableSkill;;eq;;" .. SPELL_HAMMER_OF_WRATH,
iconSkill = SPELLID_HAMMER_OF_WRATH,
},
--[[MSBT_TRIGGER_KILL_SHOT = {
colorG = 0.25,
colorB = 0.25,
message = SPELL_KILL_SHOT .. "!",
alwaysSticky = true,
fontSize = 26,
classes = "HUNTER",
mainEvents = "UNIT_HEALTH{unitID;;eq;;target;;threshold;;lt;;20;;unitReaction;;eq;;" .. REACTION_HOSTILE .. "}",
exceptions = "unavailableSkill;;eq;;" .. SPELL_KILL_SHOT,
iconSkill = SPELLID_KILL_SHOT,
},]]
--[[MSBT_TRIGGER_KILLING_MACHINE = {
colorR = 0.118,
colorG = 0.882,
message = SPELL_KILLING_MACHINE .. "!",
alwaysSticky = true,
fontSize = 26,
classes = "DEATHKNIGHT",
mainEvents = "SPELL_AURA_APPLIED{skillName;;eq;;" .. SPELL_KILLING_MACHINE .. ";;recipientAffiliation;;eq;;" .. FLAG_YOU .. "}",
},]]
--[[MSBT_TRIGGER_LAVA_SURGE = {
colorG = 0.341,
colorB = 0.129,
message = SPELL_LAVA_SURGE,
alwaysSticky = true,
fontSize = 26,
classes = "SHAMAN",
mainEvents = "SPELL_CAST_SUCCESS{sourceAffiliation;;eq;;" .. FLAG_YOU .. ";;skillID;;eq;;" .. SPELLID_LAVA_SURGE .. "}",
},]]
--[[MSBT_TRIGGER_LOCK_AND_LOAD = {
colorR = 0.627,
colorG = 0.5,
colorB = 0,
message = SPELL_LOCK_AND_LOAD .. "!",
alwaysSticky = true,
fontSize = 26,
classes = "HUNTER",
mainEvents = "SPELL_AURA_APPLIED{skillName;;eq;;" .. SPELL_LOCK_AND_LOAD .. ";;recipientAffiliation;;eq;;" .. FLAG_YOU .. "}",
},]]
MSBT_TRIGGER_LOW_HEALTH = {
colorG = 0.5,
colorB = 0.5,
message = L.MSG_TRIGGER_LOW_HEALTH .. "! (%a)",
alwaysSticky = true,
fontSize = 26,
soundFile = "MSBT Low Health",
mainEvents = "UNIT_HEALTH{unitID;;eq;;player;;threshold;;lt;;35}",
exceptions = "recentlyFired;;lt;;5",
iconSkill = SPELLID_FIRST_AID,
},
MSBT_TRIGGER_LOW_MANA = {
colorR = 0.5,
colorG = 0.5,
message = L.MSG_TRIGGER_LOW_MANA .. "! (%a)",
alwaysSticky = true,
fontSize = 26,
soundFile = "MSBT Low Mana",
classes = "DRUID,MAGE,PALADIN,PRIEST,SHAMAN,WARLOCK",
mainEvents = "UNIT_POWER_UPDATE{powerType;;eq;;0;;unitID;;eq;;player;;threshold;;lt;;35}",
exceptions = "recentlyFired;;lt;;5",
},
MSBT_TRIGGER_LOW_PET_HEALTH = {
colorG = 0.5,
colorB = 0.5,
message = L.MSG_TRIGGER_LOW_PET_HEALTH .. "! (%a)",
fontSize = 26,
classes = "HUNTER,MAGE,WARLOCK",
mainEvents = "UNIT_HEALTH{unitID;;eq;;pet;;threshold;;lt;;40}",
exceptions = "recentlyFired;;lt;;5",
},
--[[MSBT_TRIGGER_MAELSTROM_WEAPON = {
colorR = 0.5,
colorB = 0.5,
message = SPELL_MAELSTROM_WEAPON .. " x5!",
alwaysSticky = true,
fontSize = 26,
classes = "SHAMAN",
mainEvents = "SPELL_AURA_APPLIED{skillName;;eq;;" .. SPELL_MAELSTROM_WEAPON .. ";;amount;;eq;;5;;recipientAffiliation;;eq;;" .. FLAG_YOU .. "}",
},]]
--[[MSBT_TRIGGER_MANA_TEA = {
colorR = 0,
colorG = 0.5,
message = SPELL_MANA_TEA .. " x%a!",
alwaysSticky = true,
fontSize = 26,
classes = "MONK",
mainEvents = "SPELL_AURA_APPLIED{skillName;;eq;;" .. SPELL_MANA_TEA .. ";;amount;;eq;;20;;recipientAffiliation;;eq;;" .. FLAG_YOU .. "}"
},]]
--[[MSBT_TRIGGER_MISSILE_BARRAGE = {
colorG = 0.725,
message = SPELL_MISSILE_BARRAGE .. "!",
alwaysSticky = true,
fontSize = 26,
classes = "MAGE",
mainEvents = "SPELL_AURA_APPLIED{skillName;;eq;;" .. SPELL_MISSILE_BARRAGE .. ";;recipientAffiliation;;eq;;" .. FLAG_YOU .. "}",
},]]
--[[MSBT_TRIGGER_MOLTEN_CORE = {
colorG = 0.25,
colorB = 0.25,
message = SPELL_MOLTEN_CORE .. "!",
alwaysSticky = true,
fontSize = 26,
classes = "WARLOCK",
mainEvents = "SPELL_AURA_APPLIED{skillName;;eq;;" .. SPELL_MOLTEN_CORE .. ";;recipientAffiliation;;eq;;" .. FLAG_YOU .. "}",
},]]
--[[MSBT_TRIGGER_NIGHTFALL = {
colorR = 0.709,
colorG = 0,
colorB = 0.709,
message = SPELL_NIGHTFALL .. "!",
alwaysSticky = true,
fontSize = 26,
classes = "WARLOCK",
mainEvents = "SPELL_AURA_APPLIED{skillName;;eq;;" .. SPELL_SHADOW_TRANCE .. ";;recipientAffiliation;;eq;;" .. FLAG_YOU .. "}",
},]]
--[[MSBT_TRIGGER_PVP_TRINKET = {
colorB = 0,
message = SPELL_PVP_TRINKET .. "! (%r)",
alwaysSticky = true,
fontSize = 26,
mainEvents = "SPELL_AURA_APPLIED{skillName;;eq;;" .. SPELL_PVP_TRINKET .. ";;recipientReaction;;eq;;" .. REACTION_HOSTILE .. "}",
exceptions = "zoneType;;ne;;arena",
},]]
--[[MSBT_TRIGGER_PREDATORS_SWIFTNESS = {
colorR = 0.5,
colorB = 0.5,
message = SPELL_PREDATORS_SWIFTNESS .. "!",
alwaysSticky = true,
fontSize = 26,
classes = "DRUID",
mainEvents = "SPELL_AURA_APPLIED{skillName;;eq;;" .. SPELL_PREDATORS_SWIFTNESS .. ";;recipientAffiliation;;eq;;" .. FLAG_YOU .. "}",
},]]
MSBT_TRIGGER_REVENGE = {
colorB = 0,
message = SPELL_REVENGE .. "!",
alwaysSticky = true,
fontSize = 26,
classes = "WARRIOR",
mainEvents = "GENERIC_MISSED{recipientAffiliation;;eq;;" .. FLAG_YOU .. ";;missType;;eq;;BLOCK}&&GENERIC_MISSED{recipientAffiliation;;eq;;" .. FLAG_YOU .. ";;missType;;eq;;DODGE}&&GENERIC_MISSED{recipientAffiliation;;eq;;" .. FLAG_YOU .. ";;missType;;eq;;PARRY}",
exceptions = "warriorStance;;ne;;2;;unavailableSkill;;eq;;" .. SPELL_REVENGE .. ";;recentlyFired;;lt;;2",
iconSkill = SPELLID_REVENGE,
},
--[[MSBT_TRIGGER_RIME = {
colorR = 0,
colorG = 0.5,
message = SPELL_RIME .. "!",
alwaysSticky = true,
fontSize = 26,
classes = "DEATHKNIGHT",
mainEvents = "SPELL_AURA_APPLIED{skillName;;eq;;" .. SPELL_FREEZING_FOG .. ";;recipientAffiliation;;eq;;" .. FLAG_YOU .. "}",
},]]
--[[MSBT_TRIGGER_SHADOW_INFUSION = {
colorR = 0.709,
colorG = 0,
colorB = 0.709,
message = SPELL_SHADOW_INFUSION .. " x5!",
alwaysSticky = true,
fontSize = 26,
classes = "DEATHKNIGHT",
mainEvents = "SPELL_AURA_APPLIED{skillName;;eq;;" .. SPELL_SHADOW_INFUSION .. ";;amount;;eq;;5;;recipientAffiliation;;eq;;" .. FLAG_YOU .. "}",
},]]
--[[MSBT_TRIGGER_SHOOTING_STARS = {
colorG = 0.725,
message = SPELL_SHOOTING_STARS .. "!",
alwaysSticky = true,
fontSize = 26,
classes = "DRUID",
mainEvents = "SPELL_AURA_APPLIED{skillName;;eq;;" .. SPELL_SHOOTING_STARS .. ";;recipientAffiliation;;eq;;" .. FLAG_YOU .. "}",
},]]
--[[MSBT_TRIGGER_SUDDEN_DEATH = {
colorG = 0,
colorB = 0,
message = SPELL_SUDDEN_DEATH .. "!",
alwaysSticky = true,
fontSize = 26,
classes = "WARRIOR",
mainEvents = "SPELL_AURA_APPLIED{skillName;;eq;;" .. SPELL_SUDDEN_DEATH .. ";;recipientAffiliation;;eq;;" .. FLAG_YOU .. "}",
},]]
--[[MSBT_TRIGGER_SWORD_AND_BOARD = {
colorR = 0,
colorG = 0.5,
message = SPELL_SWORD_AND_BOARD .. "!",
alwaysSticky = true,
fontSize = 26,
classes = "WARRIOR",
mainEvents = "SPELL_AURA_APPLIED{skillName;;eq;;" .. SPELL_SWORD_AND_BOARD .. ";;recipientAffiliation;;eq;;" .. FLAG_YOU .. "}",
exceptions = "unavailableSkill;;eq;;" .. SPELL_SHIELD_SLAM,
},]]
--[[MSBT_TRIGGER_TASTE_FOR_BLOOD = {
colorR = 0.627,
colorG = 0.5,
colorB = 0,
message = SPELL_TASTE_FOR_BLOOD .. "!",
alwaysSticky = true,
fontSize = 26,
classes = "WARRIOR",
mainEvents = "SPELL_AURA_APPLIED{skillName;;eq;;" .. SPELL_TASTE_FOR_BLOOD .. ";;recipientAffiliation;;eq;;" .. FLAG_YOU .. "}",
},]]
--[[MSBT_TRIGGER_THE_ART_OF_WAR = {
colorR = 0.5,
colorB = 0.5,
message = SPELL_THE_ART_OF_WAR .. "!",
alwaysSticky = true,
fontSize = 26,
classes = "PALADIN",
mainEvents = "SPELL_AURA_APPLIED{skillName;;eq;;" .. SPELL_THE_ART_OF_WAR .. ";;recipientAffiliation;;eq;;" .. FLAG_YOU .. "}",
},]]
--[[MSBT_TRIGGER_TIDAL_WAVES = {
colorR = 0,
colorG = 0.5,
message = SPELL_TIDAL_WAVES .. "!",
alwaysSticky = true,
fontSize = 26,
classes = "SHAMAN",
mainEvents = "SPELL_AURA_APPLIED{skillName;;eq;;" .. SPELL_TIDAL_WAVES .. ";;recipientAffiliation;;eq;;" .. FLAG_YOU .. "}",
},]]
--[[MSBT_TRIGGER_ULTIMATUM = {
colorR = 0,
colorG = 0.5,
message = SPELL_ULTIMATUM .. "!",
alwaysSticky = true,
fontSize = 26,
classes = "WARRIOR",
mainEvents = "SPELL_AURA_APPLIED{skillName;;eq;;" .. SPELL_ULTIMATUM .. ";;recipientAffiliation;;eq;;" .. FLAG_YOU .. "}",
},]]
--[[MSBT_TRIGGER_VICTORY_RUSH = {
colorG = 0.25,
colorB = 0.25,
message = SPELL_VICTORY_RUSH .. "!",
alwaysSticky = true,
fontSize = 26,
classes = "WARRIOR",
mainEvents = "PARTY_KILL{sourceAffiliation;;eq;;" .. FLAG_YOU .. "}",
exceptions = "unavailableSkill;;eq;;" .. SPELL_VICTORY_RUSH .. ";;trivialTarget;;eq;;true;;recentlyFired;;lt;;2",
iconSkill = SPELLID_VICTORY_RUSH,
},--]]
--[[MSBT_TRIGGER_VITAL_MISTS = {
colorR = 0.5,
colorB = 0.5,
message = SPELL_VITAL_MISTS .. " x%a!",
alwaysSticky = true,
fontSize = 26,
classes = "MONK",
mainEvents = "SPELL_AURA_APPLIED{skillName;;eq;;" .. SPELL_VITAL_MISTS .. ";;amount;;eq;;5;;recipientAffiliation;;eq;;" .. FLAG_YOU .. "}"
},]]
}, -- End triggers
-- Master font settings.
normalFontName = L.DEFAULT_FONT_NAME,
normalOutlineIndex = 1,
normalFontSize = 18,
normalFontAlpha = 100,
critFontName = L.DEFAULT_FONT_NAME,
critOutlineIndex = 1,
critFontSize = 26,
critFontAlpha = 100,
-- Animation speed.
animationSpeed = 100,
-- Partial effect settings.
crushing = { colorR = 0.5, colorG = 0, colorB = 0, trailer = string_gsub(CRUSHING_TRAILER, "%((.+)%)", "<%1>") },
glancing = { colorR = 1, colorG = 0, colorB = 0, trailer = string_gsub(GLANCING_TRAILER, "%((.+)%)", "<%1>") },
absorb = { colorR = 1, colorG = 1, colorB = 0, trailer = string_gsub(string_gsub(ABSORB_TRAILER, "%((.+)%)", "<%1>"), "%%d", "%%a") },
block = { colorR = 0.5, colorG = 0, colorB = 1, trailer = string_gsub(string_gsub(BLOCK_TRAILER, "%((.+)%)", "<%1>"), "%%d", "%%a") },
resist = { colorR = 0.5, colorG = 0, colorB = 0.5, trailer = string_gsub(string_gsub(RESIST_TRAILER, "%((.+)%)", "<%1>"), "%%d", "%%a") },
overheal = { colorR = 0, colorG = 0.705, colorB = 0.5, trailer = " <%a>" },
overkill = { disabled = true, colorR = 0.83, colorG = 0, colorB = 0.13, trailer = " <%a>" },
-- Damage color settings.
physical = { colorR = 1, colorG = 1, colorB = 1 },
holy = { colorR = 1, colorG = 1, colorB = 0.627 },
fire = { colorR = 1, colorG = 0.5, colorB = 0.5 },
nature = { colorR = 0.5, colorG = 1, colorB = 0.5 },
frost = { colorR = 0.5, colorG = 0.5, colorB = 1 },
shadow = { colorR = 0.628, colorG = 0, colorB = 0.628 },
arcane = { colorR = 1, colorG = 0.725, colorB = 1 },
frostfire = { colorR = 0.824, colorG = 0.314, colorB = 0.471 },
shadowflame = { colorR = 0.824, colorG = 0.5, colorB = 0.628 },
-- Class color settings.
DEATHKNIGHT = CreateClassSettingsTable("DEATHKNIGHT"),
DRUID = CreateClassSettingsTable("DRUID"),
HUNTER = CreateClassSettingsTable("HUNTER"),
MAGE = CreateClassSettingsTable("MAGE"),
MONK = CreateClassSettingsTable("MONK"),
PALADIN = CreateClassSettingsTable("PALADIN"),
PRIEST = CreateClassSettingsTable("PRIEST"),
ROGUE = CreateClassSettingsTable("ROGUE"),
SHAMAN = CreateClassSettingsTable("SHAMAN"),
WARLOCK = CreateClassSettingsTable("WARLOCK"),
WARRIOR = CreateClassSettingsTable("WARRIOR"),
DEMONHUNTER = CreateClassSettingsTable("DEMONHUNTER"),
EVOKER = CreateClassSettingsTable("EVOKER"),
-- Throttle settings.
dotThrottleDuration = 3,
hotThrottleDuration = 3,
powerThrottleDuration = 3,
throttleList = {
--[SPELL_BLOOD_PRESENCE] = 5,
--[SPELL_DRAIN_LIFE] = 3,
--[SPELL_SHADOWMEND] = 5,
--[SPELL_REFLECTIVE_SHIELD] = 5,
[SPELL_VAMPIRIC_EMBRACE] = 5,
--[SPELL_VAMPIRIC_TOUCH] = 5,
},
-- Spam control settings.
mergeExclusions = {},
abilitySubstitutions = {},
abilitySuppressions = {
--[SPELL_UNDYING_RESOLVE] = true,
},
damageThreshold = 0,
healThreshold = 0,
powerThreshold = 0,
hideFullHoTOverheals = true,
shortenNumbers = false,
shortenNumberPrecision = 0,
groupNumbers = false,
-- Cooldown settings.
cooldownExclusions = {},
ignoreCooldownThreshold = {},
cooldownThreshold = 5,
-- Loot settings.
qualityExclusions = {
[LE_ITEM_QUALITY_POOR or Enum.ItemQuality.Poor] = true,
},
alwaysShowQuestItems = true,
itemsAllowed = {},
itemExclusions = {},
}
else
masterProfile = {
-- Scroll area settings.
scrollAreas = {
Incoming = {
name = L.MSG_INCOMING,
offsetX = -140,
offsetY = -160,
animationStyle = "Parabola",
direction = "Down",
behavior = "CurvedLeft",
stickyBehavior = "Jiggle",
textAlignIndex = 3,
stickyTextAlignIndex = 3,
},
Outgoing = {
name = L.MSG_OUTGOING,
offsetX = 100,
offsetY = -160,
animationStyle = "Parabola",
direction = "Down",
behavior = "CurvedRight",
stickyBehavior = "Jiggle",
textAlignIndex = 1,
stickyTextAlignIndex = 1,
iconAlign = "Right",
},
Notification = {
name = L.MSG_NOTIFICATION,
offsetX = -175,
offsetY = 120,
scrollHeight = 200,
scrollWidth = 350,
},
Static = {
name = L.MSG_STATIC,
offsetX = -20,
offsetY = -300,
scrollHeight = 125,
animationStyle = "Static",
direction = "Down",
},
},
-- Built-in event settings.
events = {
INCOMING_DAMAGE = {
colorG = 0,
colorB = 0,
message = "(%n) -%a",
scrollArea = "Incoming",
},
INCOMING_DAMAGE_CRIT = {
colorG = 0,
colorB = 0,
message = "(%n) -%a",
scrollArea = "Incoming",
isCrit = true,
},
INCOMING_MISS = {
colorR = 0,
colorG = 0,
message = MISS .. "!",
scrollArea = "Incoming",
},
INCOMING_DODGE = {
colorR = 0,
colorG = 0,
message = DODGE .. "!",
scrollArea = "Incoming",
},
INCOMING_PARRY = {
colorR = 0,
colorG = 0,
message = PARRY .. "!",
scrollArea = "Incoming",
},
INCOMING_BLOCK = {
colorR = 0,
colorG = 0,
message = BLOCK .. "!",
scrollArea = "Incoming",
},
INCOMING_DEFLECT = {
colorR = 0,
colorG = 0,
message = DEFLECT .. "!",
scrollArea = "Incoming",
},
INCOMING_ABSORB = {
colorB = 0,
message = ABSORB .. "! <%a>",
scrollArea = "Incoming",
},
INCOMING_IMMUNE = {
colorB = 0,
message = IMMUNE .. "!",
scrollArea = "Incoming",
},
INCOMING_SPELL_DAMAGE = {
colorG = 0,
colorB = 0,
message = "(%s) -%a",
scrollArea = "Incoming",
},
INCOMING_SPELL_DAMAGE_CRIT = {
colorG = 0,
colorB = 0,
message = "(%s) -%a",
scrollArea = "Incoming",
isCrit = true,
},
INCOMING_SPELL_DAMAGE_SHIELD = {
colorG = 0,
colorB = 0,
message = "(%s) -%a",
scrollArea = "Incoming",
},
INCOMING_SPELL_DAMAGE_SHIELD_CRIT = {
colorG = 0,
colorB = 0,
message = "(%s) -%a",
scrollArea = "Incoming",
isCrit = true,
},
INCOMING_SPELL_DOT = {
colorG = 0,
colorB = 0,
message = "(%s) -%a",
scrollArea = "Incoming",
},
INCOMING_SPELL_DOT_CRIT = {
colorG = 0,
colorB = 0,
message = "(%s) -%a",
scrollArea = "Incoming",
isCrit = true,
},
INCOMING_SPELL_MISS = {
colorR = 0,
colorG = 0,
message = "(%s) " .. MISS .. "!",
scrollArea = "Incoming",
},
INCOMING_SPELL_DODGE = {
colorR = 0,
colorG = 0,
message = "(%s) " .. DODGE .. "!",
scrollArea = "Incoming",
},
INCOMING_SPELL_PARRY = {
colorR = 0,
colorG = 0,
message = "(%s) " .. PARRY .. "!",
scrollArea = "Incoming",
},
INCOMING_SPELL_BLOCK = {
colorR = 0,
colorG = 0,
message = "(%s) " .. BLOCK .. "!",
scrollArea = "Incoming",
},
INCOMING_SPELL_DEFLECT = {
colorR = 0,
colorG = 0,
message = "(%s) " .. DEFLECT .. "!",
scrollArea = "Incoming",
},
INCOMING_SPELL_RESIST = {
colorR = 0.5,
colorG = 0,
colorB = 0.5,
message = "(%s) " .. RESIST .. "!",
scrollArea = "Incoming",
},
INCOMING_SPELL_ABSORB = {
colorB = 0,
message = "(%s) " .. ABSORB .. "! <%a>",
scrollArea = "Incoming",
},
INCOMING_SPELL_IMMUNE = {
colorB = 0,
message = "(%s) " .. IMMUNE .. "!",
scrollArea = "Incoming",
},
INCOMING_SPELL_REFLECT = {
colorR = 0.5,
colorG = 0,
colorB = 0.5,
message = "(%s) " .. REFLECT .. "!",
scrollArea = "Incoming",
},
INCOMING_SPELL_INTERRUPT = {
colorB = 0,
message = "(%s) " .. INTERRUPT .. "!",
scrollArea = "Incoming",
},
INCOMING_HEAL = {
colorR = 0,
colorB = 0,
message = "(%s - %n) +%a",
scrollArea = "Incoming",
},
INCOMING_HEAL_CRIT = {
colorR = 0,
colorB = 0,
message = "(%s - %n) +%a",
fontSize = 22,
scrollArea = "Incoming",
isCrit = true,
},
INCOMING_HOT = {
colorR = 0,
colorB = 0,
message = "(%s - %n) +%a",
scrollArea = "Incoming",
},
INCOMING_HOT_CRIT = {
colorR = 0,
colorB = 0,
message = "(%s - %n) +%a",
scrollArea = "Incoming",
isCrit = true,
},
SELF_HEAL = {
colorR = 0,
colorB = 0,
message = "(%s - %n) +%a",
scrollArea = "Incoming",
},
SELF_HEAL_CRIT = {
colorR = 0,
colorB = 0,
message = "(%s - %n) +%a",
fontSize = 22,
scrollArea = "Incoming",
isCrit = true,
},
SELF_HOT = {
colorR = 0,
colorB = 0,
message = "(%s - %n) +%a",
scrollArea = "Incoming",
},
SELF_HOT_CRIT = {
colorR = 0,
colorB = 0,
message = "(%s - %n) +%a",
scrollArea = "Incoming",
isCrit = true,
},
INCOMING_ENVIRONMENTAL = {
colorG = 0,
colorB = 0,
message = "-%a %e",
scrollArea = "Incoming",
},
OUTGOING_DAMAGE = {
message = "%a",
scrollArea = "Outgoing",
},
OUTGOING_DAMAGE_CRIT = {
message = "%a",
scrollArea = "Outgoing",
isCrit = true,
},
OUTGOING_MISS = {
message = MISS .. "!",
scrollArea = "Outgoing",
},
OUTGOING_DODGE = {
message = DODGE .. "!",
scrollArea = "Outgoing",
},
OUTGOING_PARRY = {
message = PARRY .. "!",
scrollArea = "Outgoing",
},
OUTGOING_BLOCK = {
message = BLOCK .. "!",
scrollArea = "Outgoing",
},
OUTGOING_DEFLECT = {
message = DEFLECT.. "!",
scrollArea = "Outgoing",
},
OUTGOING_ABSORB = {
colorB = 0,
message = "<%a> " .. ABSORB .. "!",
scrollArea = "Outgoing",
},
OUTGOING_IMMUNE = {
colorB = 0,
message = IMMUNE .. "!",
scrollArea = "Outgoing",
},
OUTGOING_EVADE = {
colorG = 0.5,
colorB = 0,
message = EVADE .. "!",
fontSize = 22,
scrollArea = "Outgoing",
},
OUTGOING_SPELL_DAMAGE = {
colorB = 0,
message = "%a (%s)",
scrollArea = "Outgoing",
},
OUTGOING_SPELL_DAMAGE_CRIT = {
colorB = 0,
message = "%a (%s)",
scrollArea = "Outgoing",
isCrit = true,
},
OUTGOING_SPELL_DAMAGE_SHIELD = {
colorB = 0,
message = "%a (%s)",
scrollArea = "Outgoing",
},
OUTGOING_SPELL_DAMAGE_SHIELD_CRIT = {
colorB = 0,
message = "%a (%s)",
scrollArea = "Outgoing",
isCrit = true,
},
OUTGOING_SPELL_DOT = {
colorB = 0,
message = "%a (%s)",
scrollArea = "Outgoing",
},
OUTGOING_SPELL_DOT_CRIT = {
colorB = 0,
message = "%a (%s)",
scrollArea = "Outgoing",
isCrit = true,
},
OUTGOING_SPELL_MISS = {
message = MISS .. "! (%s)",
scrollArea = "Outgoing",
},
OUTGOING_SPELL_DODGE = {
message = DODGE .. "! (%s)",
scrollArea = "Outgoing",
},
OUTGOING_SPELL_PARRY = {
message = PARRY .. "! (%s)",
scrollArea = "Outgoing",
},
OUTGOING_SPELL_BLOCK = {
message = BLOCK .. "! (%s)",
scrollArea = "Outgoing",
},
OUTGOING_SPELL_DEFLECT = {
message = DEFLECT .. "! (%s)",
scrollArea = "Outgoing",
},
OUTGOING_SPELL_RESIST = {
colorR = 0.5,
colorG = 0.5,
colorB = 0.698,
message = RESIST .. "! (%s)",
scrollArea = "Outgoing",
},
OUTGOING_SPELL_ABSORB = {
colorB = 0,
message = "<%a> " .. ABSORB .. "! (%s)",
scrollArea = "Outgoing",
},
OUTGOING_SPELL_IMMUNE = {
colorB = 0,
message = IMMUNE .. "! (%s)",
scrollArea = "Outgoing",
},
OUTGOING_SPELL_REFLECT = {
colorB = 0,
message = REFLECT .. "! (%s)",
scrollArea = "Outgoing",
},
OUTGOING_SPELL_INTERRUPT = {
colorB = 0,
message = INTERRUPT .. "! (%s)",
scrollArea = "Outgoing",
},
OUTGOING_SPELL_EVADE = {
colorG = 0.5,
colorB = 0,
message = EVADE .. "! (%s)",
fontSize = 22,
scrollArea = "Outgoing",
},
OUTGOING_HEAL = {
colorR = 0,
colorB = 0,
message = "+%a (%s - %n)",
scrollArea = "Outgoing",
},
OUTGOING_HEAL_CRIT = {
colorR = 0,
colorB = 0,
message = "+%a (%s - %n)",
fontSize = 22,
scrollArea = "Outgoing",
isCrit = true,
},
OUTGOING_HOT = {
colorR = 0,
colorB = 0,
message = "+%a (%s - %n)",
scrollArea = "Outgoing",
},
OUTGOING_HOT_CRIT = {
colorR = 0,
colorB = 0,
message = "+%a (%s - %n)",
scrollArea = "Outgoing",
isCrit = true,
},
OUTGOING_DISPEL = {
colorB = 0.5,
message = L.MSG_DISPEL .. "! (%s)",
scrollArea = "Outgoing",
},
PET_INCOMING_DAMAGE = {
colorG = 0.41,
colorB = 0.41,
message = "(%n) " .. PET .. " -%a",
scrollArea = "Incoming",
},
PET_INCOMING_DAMAGE_CRIT = {
colorG = 0.41,
colorB = 0.41,
message = "(%n) " .. PET .. " -%a",
scrollArea = "Incoming",
isCrit = true,
},
PET_INCOMING_MISS = {
colorR = 0.57,
colorG = 0.58,
message = PET .. " " .. MISS .. "!",
scrollArea = "Incoming",
},
PET_INCOMING_DODGE = {
colorR = 0.57,
colorG = 0.58,
message = PET .. " " .. DODGE .. "!",
scrollArea = "Incoming",
},
PET_INCOMING_PARRY = {
colorR = 0.57,
colorG = 0.58,
message = PET .. " " .. PARRY .. "!",
scrollArea = "Incoming",
},
PET_INCOMING_BLOCK = {
colorR = 0.57,
colorG = 0.58,
message = PET .. " " .. BLOCK .. "!",
scrollArea = "Incoming",
},
PET_INCOMING_DEFLECT = {
colorR = 0.57,
colorG = 0.58,
message = PET .. " " .. DEFLECT .. "!",
scrollArea = "Incoming",
},
PET_INCOMING_ABSORB = {
colorB = 0.57,
message = PET .. " " .. ABSORB .. "! <%a>",
scrollArea = "Incoming",
},
PET_INCOMING_IMMUNE = {
colorB = 0.57,
message = PET .. " " .. IMMUNE .. "!",
scrollArea = "Incoming",
},
PET_INCOMING_SPELL_DAMAGE = {
colorG = 0.41,
colorB = 0.41,
message = "(%s) " .. PET .. " -%a",
scrollArea = "Incoming",
},
PET_INCOMING_SPELL_DAMAGE_CRIT = {
colorG = 0.41,
colorB = 0.41,
message = "(%s) " .. PET .. " -%a",
scrollArea = "Incoming",
isCrit = true,
},
PET_INCOMING_SPELL_DAMAGE_SHIELD = {
colorG = 0.41,
colorB = 0.41,
message = "(%s) " .. PET .. " -%a",
scrollArea = "Incoming",
},
PET_INCOMING_SPELL_DAMAGE_SHIELD_CRIT = {
colorG = 0.41,
colorB = 0.41,
message = "(%s) " .. PET .. " -%a",
scrollArea = "Incoming",
isCrit = true,
},
PET_INCOMING_SPELL_DOT = {
colorG = 0.41,
colorB = 0.41,
message = "(%s) " .. PET .. " -%a",
scrollArea = "Incoming",
},
PET_INCOMING_SPELL_DOT_CRIT = {
colorG = 0.41,
colorB = 0.41,
message = "(%s) " .. PET .. " -%a",
scrollArea = "Incoming",
isCrit = true,
},
PET_INCOMING_SPELL_MISS = {
colorR = 0.57,
colorG = 0.58,
message = "(%s) " .. PET .. " " .. MISS .. "!",
scrollArea = "Incoming",
},
PET_INCOMING_SPELL_DODGE = {
colorR = 0.57,
colorG = 0.58,
message = "(%s) " .. PET .. " " .. DODGE .. "!",
scrollArea = "Incoming",
},
PET_INCOMING_SPELL_PARRY = {
colorR = 0.57,
colorG = 0.58,
message = "(%s) " .. PET .. " " .. PARRY .. "!",
scrollArea = "Incoming",
},
PET_INCOMING_SPELL_BLOCK = {
colorR = 0.57,
colorG = 0.58,
message = "(%s) " .. PET .. " " .. BLOCK .. "!",
scrollArea = "Incoming",
},
PET_INCOMING_SPELL_DEFLECT = {
colorR = 0.57,
colorG = 0.58,
message = "(%s) " .. PET .. " " .. DEFLECT .. "!",
scrollArea = "Incoming",
},
PET_INCOMING_SPELL_RESIST = {
colorR = 0.94,
colorG = 0,
colorB = 0.94,
message = "(%s) " .. PET .. " " .. RESIST .. "!",
scrollArea = "Incoming",
},
PET_INCOMING_SPELL_ABSORB = {
colorB = 0.57,
message = "(%s) " .. PET .. " " .. ABSORB .. "! <%a>",
scrollArea = "Incoming",
},
PET_INCOMING_SPELL_IMMUNE = {
colorB = 0.57,
message = "(%s) " .. PET .. " " .. IMMUNE .. "!",
scrollArea = "Incoming",
},
PET_INCOMING_HEAL = {
colorR = 0.57,
colorB = 0.57,
message = "(%s - %n) " .. PET .. " +%a",
scrollArea = "Incoming",
},
PET_INCOMING_HEAL_CRIT = {
colorR = 0.57,
colorB = 0.57,
message = "(%s - %n) " .. PET .. " +%a",
scrollArea = "Incoming",
isCrit = true,
},
PET_INCOMING_HOT = {
colorR = 0.57,
colorB = 0.57,
message = "(%s - %n) " .. PET .. " +%a",
scrollArea = "Incoming",
},
PET_INCOMING_HOT_CRIT = {
colorR = 0.57,
colorB = 0.57,
message = "(%s - %n) " .. PET .. " +%a",
scrollArea = "Incoming",
isCrit = true,
},
PET_OUTGOING_DAMAGE = {
colorG = 0.5,
colorB = 0,
message = PET .. " %a",
scrollArea = "Outgoing",
},
PET_OUTGOING_DAMAGE_CRIT = {
colorG = 0.5,
colorB = 0,
message = PET .. " %a",
scrollArea = "Outgoing",
isCrit = true,
},
PET_OUTGOING_MISS = {
colorG = 0.5,
colorB = 0,
message = PET .. " " .. MISS,
scrollArea = "Outgoing",
},
PET_OUTGOING_DODGE = {
colorG = 0.5,
colorB = 0,
message = PET .. " " .. DODGE,
scrollArea = "Outgoing",
},
PET_OUTGOING_PARRY = {
colorG = 0.5,
colorB = 0,
message = PET .. " " .. PARRY,
scrollArea = "Outgoing",
},
PET_OUTGOING_BLOCK = {
colorG = 0.5,
colorB = 0,
message = PET .. " " .. BLOCK,
scrollArea = "Outgoing",
},
PET_OUTGOING_DEFLECT = {
colorG = 0.5,
colorB = 0,
message = PET .. " " .. DEFLECT,
scrollArea = "Outgoing",
},
PET_OUTGOING_ABSORB = {
colorR = 0.5,
colorG = 0.5,
message = PET .. " <%a> " .. ABSORB,
scrollArea = "Outgoing",
},
PET_OUTGOING_IMMUNE = {
colorR = 0.5,
colorG = 0.5,
message = PET .. " " .. IMMUNE,
scrollArea = "Outgoing",
},
PET_OUTGOING_EVADE = {
colorG = 0.77,
colorB = 0.57,
message = PET .. " " .. EVADE,
fontSize = 22,
scrollArea = "Outgoing",
},
PET_OUTGOING_SPELL_DAMAGE = {
colorR = 0.33,
colorG = 0.33,
message = PET .. " %a (%s)",
scrollArea = "Outgoing",
},
PET_OUTGOING_SPELL_DAMAGE_CRIT = {
colorR = 0.33,
colorG = 0.33,
message = PET .. " %a (%s)",
scrollArea = "Outgoing",
isCrit = true,
},
PET_OUTGOING_SPELL_DAMAGE_SHIELD = {
colorR = 0.33,
colorG = 0.33,
message = PET .. " %a (%s)",
scrollArea = "Outgoing",
},
PET_OUTGOING_SPELL_DAMAGE_SHIELD_CRIT = {
colorR = 0.33,
colorG = 0.33,
message = PET .. " %a (%s)",
scrollArea = "Outgoing",
isCrit = true,
},
PET_OUTGOING_SPELL_DOT = {
colorR = 0.33,
colorG = 0.33,
message = PET .. " %a (%s)",
scrollArea = "Outgoing",
},
PET_OUTGOING_SPELL_DOT_CRIT = {
colorR = 0.33,
colorG = 0.33,
message = PET .. " %a (%s)",
scrollArea = "Outgoing",
isCrit = true,
},
PET_OUTGOING_SPELL_MISS = {
colorR = 0.33,
colorG = 0.33,
message = PET .. " " .. MISS .. "! (%s)",
scrollArea = "Outgoing",
},
PET_OUTGOING_SPELL_DODGE = {
colorR = 0.33,
colorG = 0.33,
message = PET .. " " .. DODGE .. "! (%s)",
scrollArea = "Outgoing",
},
PET_OUTGOING_SPELL_PARRY = {
colorR = 0.33,
colorG = 0.33,
message = PET .. " " .. PARRY .. "! (%s)",
scrollArea = "Outgoing",
},
PET_OUTGOING_SPELL_BLOCK = {
colorR = 0.33,
colorG = 0.33,
message = PET .. " " .. BLOCK .. "! (%s)",
scrollArea = "Outgoing",
},
PET_OUTGOING_SPELL_DEFLECT = {
colorR = 0.33,
colorG = 0.33,
message = PET .. " " .. DEFLECT .. "! (%s)",
scrollArea = "Outgoing",
},
PET_OUTGOING_SPELL_RESIST = {
colorR = 0.73,
colorG = 0.73,
colorB = 0.84,
message = PET .. " " .. RESIST .. "! (%s)",
scrollArea = "Outgoing",
},
PET_OUTGOING_SPELL_ABSORB = {
colorR = 0.5,
colorG = 0.5,
message = PET .. " <%a> " .. ABSORB .. "! (%s)",
scrollArea = "Outgoing",
},
PET_OUTGOING_SPELL_IMMUNE = {
colorR = 0.5,
colorG = 0.5,
message = PET .. " " .. IMMUNE .. "! (%s)",
scrollArea = "Outgoing",
},
PET_OUTGOING_SPELL_EVADE = {
colorG = 0.77,
colorB = 0.57,
message = PET .. " " .. EVADE .. "! (%s)",
scrollArea = "Outgoing",
},
PET_OUTGOING_HEAL = {
colorR = 0.57,
colorB = 0.57,
message = PET .. " " .. "+%a (%s - %n)",
scrollArea = "Outgoing",
},
PET_OUTGOING_HEAL_CRIT = {
colorR = 0.57,
colorB = 0.57,
message = PET .. " " .. "+%a (%s - %n)",
fontSize = 22,
scrollArea = "Outgoing",
isCrit = true,
},
PET_OUTGOING_HOT = {
colorR = 0.57,
colorB = 0.57,
message = PET .. " " .. "+%a (%s - %n)",
scrollArea = "Outgoing",
},
PET_OUTGOING_HOT_CRIT = {
colorR = 0.57,
colorB = 0.57,
message = PET .. " " .. "+%a (%s - %n)",
scrollArea = "Outgoing",
isCrit = true,
},
PET_OUTGOING_DISPEL = {
colorB = 0.73,
message = PET .. " " .. L.MSG_DISPEL .. "! (%s)",
scrollArea = "Outgoing",
},
NOTIFICATION_DEBUFF = {
colorR = 0,
colorG = 0.5,
colorB = 0.5,
message = "[%sl]",
},
NOTIFICATION_DEBUFF_STACK = {
colorR = 0,
colorG = 0.5,
colorB = 0.5,
message = "[%sl %a]",
},
NOTIFICATION_BUFF = {
colorR = 0.698,
colorG = 0.698,
colorB = 0,
message = "[%sl]",
},
NOTIFICATION_BUFF_STACK = {
colorR = 0.698,
colorG = 0.698,
colorB = 0,
message = "[%sl %a]",
},
NOTIFICATION_ITEM_BUFF = {
colorR = 0.698,
colorG = 0.698,
colorB = 0.698,
message = "[%sl]",
},
NOTIFICATION_DEBUFF_FADE = {
colorR = 0,
colorG = 0.835,
colorB = 0.835,
message = "-[%sl]",
},
NOTIFICATION_BUFF_FADE = {
colorR = 0.918,
colorG = 0.918,
colorB = 0,
message = "-[%sl]",
},
NOTIFICATION_ITEM_BUFF_FADE = {
colorR = 0.831,
colorG = 0.831,
colorB = 0.831,
message = "-[%sl]",
},
NOTIFICATION_COMBAT_ENTER = {
message = "+" .. L.MSG_COMBAT,
},
NOTIFICATION_COMBAT_LEAVE = {
message = "-" .. L.MSG_COMBAT,
},
NOTIFICATION_POWER_GAIN = {
colorB = 0,
message = "+%a %p",
},
NOTIFICATION_POWER_LOSS = {
colorB = 0,
message = "-%a %p",
},
NOTIFICATION_ALT_POWER_GAIN = {
colorR = 0,
colorG = 0.5,
colorB = 0.5,
message = "+%a %p",
},
NOTIFICATION_ALT_POWER_LOSS = {
colorR = 0,
colorG = 0.5,
colorB = 0.5,
message = "-%a %p",
},
NOTIFICATION_CHI_CHANGE = {
colorR = 0.5,
colorG = 0.8,
colorB = 0.7,
message = "%a " .. CHI,
},
NOTIFICATION_CHI_FULL = {
colorR = 0.5,
colorG = 0.8,
colorB = 0.7,
message = L.MSG_CHI_FULL .. "!",
alwaysSticky = true,
fontSize = 26,
},
NOTIFICATION_AC_CHANGE = {
colorR = 0.3,
colorG = 0.7,
colorB = 0.9,
message = "%a " .. L.MSG_AC,
},
NOTIFICATION_AC_FULL = {
colorR = 0.3,
colorG = 0.7,
colorB = 0.9,
message = L.MSG_AC_FULL .. "!",
alwaysSticky = true,
fontSize = 26,
},
NOTIFICATION_CP_GAIN = {
colorG = 0.5,
colorB = 0,
message = "%a " .. L.MSG_CP,
},
NOTIFICATION_CP_FULL = {
colorR = 0.8,
colorG = 0,
colorB = 0,
message = L.MSG_CP_FULL .. "!",
alwaysSticky = true,
fontSize = 26,
},
NOTIFICATION_HOLY_POWER_CHANGE = {
colorG = 0.5,
colorB = 0,
message = "%a " .. HOLY_POWER,
},
NOTIFICATION_HOLY_POWER_FULL = {
colorG = 0.5,
colorB = 0,
message = L.MSG_HOLY_POWER_FULL .. "!",
alwaysSticky = true,
fontSize = 26,
},
NOTIFICATION_ESSENCE_CHANGE = {
colorG = 0.5,
colorB = 0,
message = "%a " .. L.MSG_ESSENCE,
},
NOTIFICATION_ESSENCE_FULL = {
colorG = 0.5,
colorB = 0,
message = L.MSG_ESSENCE_FULL .. "!",
alwaysSticky = true,
fontSize = 26,
},
NOTIFICATION_HONOR_GAIN = {
colorR = 0.5,
colorG = 0.5,
colorB = 0.698,
message = "+%a " .. HONOR,
},
NOTIFICATION_REP_GAIN = {
colorR = 0.5,
colorG = 0.5,
colorB = 0.698,
message = "+%a " .. REPUTATION .. " (%e)",
},
NOTIFICATION_REP_LOSS = {
colorR = 0.5,
colorG = 0.5,
colorB = 0.698,
message = "-%a " .. REPUTATION .. " (%e)",
},
NOTIFICATION_SKILL_GAIN = {
colorR = 0.333,
colorG = 0.333,
message = "%sl: %a",
},
NOTIFICATION_EXPERIENCE_GAIN = {
disabled = true,
colorR = 0.756,
colorG = 0.270,
colorB = 0.823,
message = "%a " .. XP,
alwaysSticky = true,
fontSize = 26,
},
NOTIFICATION_PC_KILLING_BLOW = {
colorR = 0.333,
colorG = 0.333,
message = L.MSG_KILLING_BLOW .. "! (%n)",
alwaysSticky = true,
fontSize = 26,
},
NOTIFICATION_NPC_KILLING_BLOW = {
disabled = true,
colorR = 0.333,
colorG = 0.333,
message = L.MSG_KILLING_BLOW .. "! (%n)",
alwaysSticky = true,
fontSize = 26,
},
NOTIFICATION_EXTRA_ATTACK = {
colorB = 0,
message = "%sl!",
alwaysSticky = true,
fontSize = 26,
},
NOTIFICATION_ENEMY_BUFF = {
colorB = 0.5,
message = "%n: [%sl]",
scrollArea = "Static",
},
NOTIFICATION_MONSTER_EMOTE = {
colorG = 0.5,
colorB = 0,
message = "%e",
scrollArea = "Static",
},
NOTIFICATION_MONEY = {
message = "+%e",
scrollArea = "Static",
},
NOTIFICATION_COOLDOWN = {
message = "%e " .. L.MSG_READY_NOW .. "!",
scrollArea = "Static",
fontSize = 22,
soundFile = "MSBT Cooldown",
skillColorR = 1,
skillColorG = 0,
skillColorB = 0,
},
NOTIFICATION_PET_COOLDOWN = {
colorR = 0.57,
colorG = 0.58,
message = PET .. " %e " .. L.MSG_READY_NOW .. "!",
scrollArea = "Static",
fontSize = 22,
soundFile = "MSBT Cooldown",
skillColorR = 1,
skillColorG = 0.41,
skillColorB = 0.41,
},
NOTIFICATION_ITEM_COOLDOWN = {
colorR = 0.784,
colorG = 0.784,
colorB = 0,
message = " %e " .. L.MSG_READY_NOW .. "!",
scrollArea = "Static",
fontSize = 22,
soundFile = "MSBT Cooldown",
skillColorR = 1,
skillColorG = 0.588,
skillColorB = 0.588,
},
NOTIFICATION_LOOT = {
colorB = 0,
message = "+%a %e (%t)",
scrollArea = "Static",
},
NOTIFICATION_CURRENCY = {
colorB = 0,
message = "+%a %e (%t)",
scrollArea = "Static",
},
}, -- End events
-- Default trigger settings.
triggers = {
--[[MSBT_TRIGGER_BERSERK = {
colorG = 0.25,
colorB = 0.25,
message = SPELL_BERSERK,
alwaysSticky = true,
fontSize = 26,
classes = "DRUID",
mainEvents = "SPELL_AURA_APPLIED{skillID;;eq;;" .. SPELLID_BERSERK .. ";;recipientAffiliation;;eq;;" .. FLAG_YOU .. "}",
},]]
--[[MSBT_TRIGGER_BLINDSIDE = {
colorR = 0.709,
colorG = 0,
colorB = 0.709,
message = SPELL_BLINDSIDE .. "!",
alwaysSticky = true,
fontSize = 26,
classes = "ROGUE",
mainEvents = "SPELL_AURA_APPLIED{skillName;;eq;;" .. SPELL_BLINDSIDE .. ";;recipientAffiliation;;eq;;" .. FLAG_YOU .. "}"
},]]
--[[MSBT_TRIGGER_BLOODSURGE = {
colorR = 0.8,
colorG = 0.5,
colorB = 0.5,
message = SPELL_BLOODSURGE .. "!",
alwaysSticky = true,
fontSize = 26,
classes = "WARRIOR",
mainEvents = "SPELL_AURA_APPLIED{skillName;;eq;;" .. SPELL_BLOODSURGE .. ";;recipientAffiliation;;eq;;" .. FLAG_YOU .. "}"
},]]
--[[MSBT_TRIGGER_BRAIN_FREEZE = {
colorG = 0.627,
colorB = 0.627,
message = SPELL_BRAIN_FREEZE .. "!",
alwaysSticky = true,
fontSize = 26,
classes = "MAGE",
mainEvents = "SPELL_AURA_APPLIED{skillName;;eq;;" .. SPELL_BF_FIREBALL .. ";;recipientAffiliation;;eq;;" .. FLAG_YOU .. "}",
},]]
MSBT_TRIGGER_CLEARCASTING = {
colorB = 0,
message = SPELL_CLEARCASTING .. "!",
alwaysSticky = true,
fontSize = 26,
classes = "DRUID,MAGE,PRIEST,SHAMAN",
mainEvents = "SPELL_AURA_APPLIED{skillName;;eq;;" .. SPELL_CLEARCASTING .. ";;recipientAffiliation;;eq;;" .. FLAG_YOU .. "}",
},
--[[MSBT_TRIGGER_DECIMATION = {
colorG = 0.627,
colorB = 0.627,
message = SPELL_DECIMATION .. "!",
alwaysSticky = true,
fontSize = 26,
classes = "WARLOCK",
mainEvents = "SPELL_AURA_APPLIED{skillName;;eq;;" .. SPELL_DECIMATION .. ";;recipientAffiliation;;eq;;" .. FLAG_YOU .. "}",
},]]
MSBT_TRIGGER_ELUSIVE_BREW = {
colorB = 0,
message = SPELL_ELUSIVE_BREW .. " x%a!",
alwaysSticky = true,
fontSize = 26,
classes = "MONK",
mainEvents = "SPELL_AURA_APPLIED{skillName;;eq;;" .. SPELL_ELUSIVE_BREW .. ";;amount;;eq;;5;;recipientAffiliation;;eq;;" .. FLAG_YOU .. "}&&" ..
"SPELL_AURA_APPLIED{skillName;;eq;;" .. SPELL_ELUSIVE_BREW .. ";;amount;;eq;;10;;recipientAffiliation;;eq;;" .. FLAG_YOU .. "}&&" ..
"SPELL_AURA_APPLIED{skillName;;eq;;" .. SPELL_ELUSIVE_BREW .. ";;amount;;eq;;15;;recipientAffiliation;;eq;;" .. FLAG_YOU .. "}",
},
MSBT_TRIGGER_EXECUTE = {
colorB = 0,
message = SPELL_EXECUTE .. "!",
alwaysSticky = true,
fontSize = 26,
classes = "WARRIOR",
mainEvents = "UNIT_HEALTH{unitID;;eq;;target;;threshold;;lt;;20;;unitReaction;;eq;;" .. REACTION_HOSTILE .. "}",
exceptions = "unavailableSkill;;eq;;" .. SPELL_EXECUTE,
iconSkill = SPELLID_EXECUTE,
},
MSBT_TRIGGER_FINGERS_OF_FROST = {
colorR = 0.118,
colorG = 0.882,
message = SPELL_FINGERS_OF_FROST .. "!",
alwaysSticky = true,
fontSize = 26,
classes = "MAGE",
mainEvents = "SPELL_AURA_APPLIED{skillName;;eq;;" .. SPELL_FINGERS_OF_FROST .. ";;recipientAffiliation;;eq;;" .. FLAG_YOU .. "}",
exceptions = "recentlyFired;;lt;;2",
},
MSBT_TRIGGER_HAMMER_OF_WRATH = {
colorB = 0,
message = SPELL_HAMMER_OF_WRATH .. "!",
alwaysSticky = true,
fontSize = 26,
classes = "PALADIN",
mainEvents = "UNIT_HEALTH{unitID;;eq;;target;;threshold;;lt;;20;;unitReaction;;eq;;" .. REACTION_HOSTILE .. "}",
exceptions = "unavailableSkill;;eq;;" .. SPELL_HAMMER_OF_WRATH,
iconSkill = SPELLID_HAMMER_OF_WRATH,
},
--[[MSBT_TRIGGER_KILL_SHOT = {
colorG = 0.25,
colorB = 0.25,
message = SPELL_KILL_SHOT .. "!",
alwaysSticky = true,
fontSize = 26,
classes = "HUNTER",
mainEvents = "UNIT_HEALTH{unitID;;eq;;target;;threshold;;lt;;20;;unitReaction;;eq;;" .. REACTION_HOSTILE .. "}",
exceptions = "unavailableSkill;;eq;;" .. SPELL_KILL_SHOT,
iconSkill = SPELLID_KILL_SHOT,
},]]
MSBT_TRIGGER_KILLING_MACHINE = {
colorR = 0.118,
colorG = 0.882,
message = SPELL_KILLING_MACHINE .. "!",
alwaysSticky = true,
fontSize = 26,
classes = "DEATHKNIGHT",
mainEvents = "SPELL_AURA_APPLIED{skillName;;eq;;" .. SPELL_KILLING_MACHINE .. ";;recipientAffiliation;;eq;;" .. FLAG_YOU .. "}",
},
MSBT_TRIGGER_LAVA_SURGE = {
colorG = 0.341,
colorB = 0.129,
message = SPELL_LAVA_SURGE,
alwaysSticky = true,
fontSize = 26,
classes = "SHAMAN",
mainEvents = "SPELL_CAST_SUCCESS{sourceAffiliation;;eq;;" .. FLAG_YOU .. ";;skillID;;eq;;" .. SPELLID_LAVA_SURGE .. "}",
},
--[[MSBT_TRIGGER_LOCK_AND_LOAD = {
colorR = 0.627,
colorG = 0.5,
colorB = 0,
message = SPELL_LOCK_AND_LOAD .. "!",
alwaysSticky = true,
fontSize = 26,
classes = "HUNTER",
mainEvents = "SPELL_AURA_APPLIED{skillName;;eq;;" .. SPELL_LOCK_AND_LOAD .. ";;recipientAffiliation;;eq;;" .. FLAG_YOU .. "}",
},]]
MSBT_TRIGGER_LOW_HEALTH = {
colorG = 0.5,
colorB = 0.5,
message = L.MSG_TRIGGER_LOW_HEALTH .. "! (%a)",
alwaysSticky = true,
fontSize = 26,
soundFile = "MSBT Low Health",
mainEvents = "UNIT_HEALTH{unitID;;eq;;player;;threshold;;lt;;35}",
exceptions = "recentlyFired;;lt;;5",
iconSkill = SPELLID_FIRST_AID,
},
MSBT_TRIGGER_LOW_MANA = {
colorR = 0.5,
colorG = 0.5,
message = L.MSG_TRIGGER_LOW_MANA .. "! (%a)",
alwaysSticky = true,
fontSize = 26,
soundFile = "MSBT Low Mana",
classes = "DRUID,MAGE,PALADIN,PRIEST,SHAMAN,WARLOCK",
mainEvents = "UNIT_POWER_UPDATE{powerType;;eq;;0;;unitID;;eq;;player;;threshold;;lt;;35}",
exceptions = "recentlyFired;;lt;;5",
},
MSBT_TRIGGER_LOW_PET_HEALTH = {
colorG = 0.5,
colorB = 0.5,
message = L.MSG_TRIGGER_LOW_PET_HEALTH .. "! (%a)",
fontSize = 26,
classes = "HUNTER,MAGE,WARLOCK",
mainEvents = "UNIT_HEALTH{unitID;;eq;;pet;;threshold;;lt;;40}",
exceptions = "recentlyFired;;lt;;5",
},
--[[MSBT_TRIGGER_MAELSTROM_WEAPON = {
colorR = 0.5,
colorB = 0.5,
message = SPELL_MAELSTROM_WEAPON .. " x5!",
alwaysSticky = true,
fontSize = 26,
classes = "SHAMAN",
mainEvents = "SPELL_AURA_APPLIED{skillName;;eq;;" .. SPELL_MAELSTROM_WEAPON .. ";;amount;;eq;;5;;recipientAffiliation;;eq;;" .. FLAG_YOU .. "}",
},]]
--[[MSBT_TRIGGER_MANA_TEA = {
colorR = 0,
colorG = 0.5,
message = SPELL_MANA_TEA .. " x%a!",
alwaysSticky = true,
fontSize = 26,
classes = "MONK",
mainEvents = "SPELL_AURA_APPLIED{skillName;;eq;;" .. SPELL_MANA_TEA .. ";;amount;;eq;;20;;recipientAffiliation;;eq;;" .. FLAG_YOU .. "}"
},]]
MSBT_TRIGGER_MISSILE_BARRAGE = {
colorG = 0.725,
message = SPELL_MISSILE_BARRAGE .. "!",
alwaysSticky = true,
fontSize = 26,
classes = "MAGE",
mainEvents = "SPELL_AURA_APPLIED{skillName;;eq;;" .. SPELL_MISSILE_BARRAGE .. ";;recipientAffiliation;;eq;;" .. FLAG_YOU .. "}",
},
--[[MSBT_TRIGGER_MOLTEN_CORE = {
colorG = 0.25,
colorB = 0.25,
message = SPELL_MOLTEN_CORE .. "!",
alwaysSticky = true,
fontSize = 26,
classes = "WARLOCK",
mainEvents = "SPELL_AURA_APPLIED{skillName;;eq;;" .. SPELL_MOLTEN_CORE .. ";;recipientAffiliation;;eq;;" .. FLAG_YOU .. "}",
},]]
--[[MSBT_TRIGGER_NIGHTFALL = {
colorR = 0.709,
colorG = 0,
colorB = 0.709,
message = SPELL_NIGHTFALL .. "!",
alwaysSticky = true,
fontSize = 26,
classes = "WARLOCK",
mainEvents = "SPELL_AURA_APPLIED{skillName;;eq;;" .. SPELL_SHADOW_TRANCE .. ";;recipientAffiliation;;eq;;" .. FLAG_YOU .. "}",
},]]
MSBT_TRIGGER_PVP_TRINKET = {
colorB = 0,
message = SPELL_PVP_TRINKET .. "! (%r)",
alwaysSticky = true,
fontSize = 26,
mainEvents = "SPELL_AURA_APPLIED{skillName;;eq;;" .. SPELL_PVP_TRINKET .. ";;recipientReaction;;eq;;" .. REACTION_HOSTILE .. "}",
exceptions = "zoneType;;ne;;arena",
},
MSBT_TRIGGER_PREDATORS_SWIFTNESS = {
colorR = 0.5,
colorB = 0.5,
message = SPELL_PREDATORS_SWIFTNESS .. "!",
alwaysSticky = true,
fontSize = 26,
classes = "DRUID",
mainEvents = "SPELL_AURA_APPLIED{skillName;;eq;;" .. SPELL_PREDATORS_SWIFTNESS .. ";;recipientAffiliation;;eq;;" .. FLAG_YOU .. "}",
},
MSBT_TRIGGER_REVENGE = {
colorB = 0,
message = SPELL_REVENGE .. "!",
alwaysSticky = true,
fontSize = 26,
classes = "WARRIOR",
mainEvents = "GENERIC_MISSED{recipientAffiliation;;eq;;" .. FLAG_YOU .. ";;missType;;eq;;BLOCK}&&GENERIC_MISSED{recipientAffiliation;;eq;;" .. FLAG_YOU .. ";;missType;;eq;;DODGE}&&GENERIC_MISSED{recipientAffiliation;;eq;;" .. FLAG_YOU .. ";;missType;;eq;;PARRY}",
exceptions = "warriorStance;;ne;;2;;unavailableSkill;;eq;;" .. SPELL_REVENGE .. ";;recentlyFired;;lt;;2",
iconSkill = SPELLID_REVENGE,
},
MSBT_TRIGGER_RIME = {
colorR = 0,
colorG = 0.5,
message = SPELL_RIME .. "!",
alwaysSticky = true,
fontSize = 26,
classes = "DEATHKNIGHT",
mainEvents = "SPELL_AURA_APPLIED{skillName;;eq;;" .. SPELL_FREEZING_FOG .. ";;recipientAffiliation;;eq;;" .. FLAG_YOU .. "}",
},
--[[MSBT_TRIGGER_SHADOW_INFUSION = {
colorR = 0.709,
colorG = 0,
colorB = 0.709,
message = SPELL_SHADOW_INFUSION .. " x5!",
alwaysSticky = true,
fontSize = 26,
classes = "DEATHKNIGHT",
mainEvents = "SPELL_AURA_APPLIED{skillName;;eq;;" .. SPELL_SHADOW_INFUSION .. ";;amount;;eq;;5;;recipientAffiliation;;eq;;" .. FLAG_YOU .. "}",
},]]
--[[MSBT_TRIGGER_SHOOTING_STARS = {
colorG = 0.725,
message = SPELL_SHOOTING_STARS .. "!",
alwaysSticky = true,
fontSize = 26,
classes = "DRUID",
mainEvents = "SPELL_AURA_APPLIED{skillName;;eq;;" .. SPELL_SHOOTING_STARS .. ";;recipientAffiliation;;eq;;" .. FLAG_YOU .. "}",
},]]
MSBT_TRIGGER_SUDDEN_DEATH = {
colorG = 0,
colorB = 0,
message = SPELL_SUDDEN_DEATH .. "!",
alwaysSticky = true,
fontSize = 26,
classes = "WARRIOR",
mainEvents = "SPELL_AURA_APPLIED{skillName;;eq;;" .. SPELL_SUDDEN_DEATH .. ";;recipientAffiliation;;eq;;" .. FLAG_YOU .. "}",
},
--[[MSBT_TRIGGER_SWORD_AND_BOARD = {
colorR = 0,
colorG = 0.5,
message = SPELL_SWORD_AND_BOARD .. "!",
alwaysSticky = true,
fontSize = 26,
classes = "WARRIOR",
mainEvents = "SPELL_AURA_APPLIED{skillName;;eq;;" .. SPELL_SWORD_AND_BOARD .. ";;recipientAffiliation;;eq;;" .. FLAG_YOU .. "}",
exceptions = "unavailableSkill;;eq;;" .. SPELL_SHIELD_SLAM,
},]]
--[[MSBT_TRIGGER_TASTE_FOR_BLOOD = {
colorR = 0.627,
colorG = 0.5,
colorB = 0,
message = SPELL_TASTE_FOR_BLOOD .. "!",
alwaysSticky = true,
fontSize = 26,
classes = "WARRIOR",
mainEvents = "SPELL_AURA_APPLIED{skillName;;eq;;" .. SPELL_TASTE_FOR_BLOOD .. ";;recipientAffiliation;;eq;;" .. FLAG_YOU .. "}",
},]]
--[[MSBT_TRIGGER_THE_ART_OF_WAR = {
colorR = 0.5,
colorB = 0.5,
message = SPELL_THE_ART_OF_WAR .. "!",
alwaysSticky = true,
fontSize = 26,
classes = "PALADIN",
mainEvents = "SPELL_AURA_APPLIED{skillName;;eq;;" .. SPELL_THE_ART_OF_WAR .. ";;recipientAffiliation;;eq;;" .. FLAG_YOU .. "}",
},]]
MSBT_TRIGGER_TIDAL_WAVES = {
colorR = 0,
colorG = 0.5,
message = SPELL_TIDAL_WAVES .. "!",
alwaysSticky = true,
fontSize = 26,
classes = "SHAMAN",
mainEvents = "SPELL_AURA_APPLIED{skillName;;eq;;" .. SPELL_TIDAL_WAVES .. ";;recipientAffiliation;;eq;;" .. FLAG_YOU .. "}",
},
--[[MSBT_TRIGGER_ULTIMATUM = {
colorR = 0,
colorG = 0.5,
message = SPELL_ULTIMATUM .. "!",
alwaysSticky = true,
fontSize = 26,
classes = "WARRIOR",
mainEvents = "SPELL_AURA_APPLIED{skillName;;eq;;" .. SPELL_ULTIMATUM .. ";;recipientAffiliation;;eq;;" .. FLAG_YOU .. "}",
},]]
MSBT_TRIGGER_VICTORY_RUSH = {
colorG = 0.25,
colorB = 0.25,
message = SPELL_VICTORY_RUSH .. "!",
alwaysSticky = true,
fontSize = 26,
classes = "WARRIOR",
mainEvents = "PARTY_KILL{sourceAffiliation;;eq;;" .. FLAG_YOU .. "}",
exceptions = "unavailableSkill;;eq;;" .. SPELL_VICTORY_RUSH .. ";;trivialTarget;;eq;;true;;recentlyFired;;lt;;2",
iconSkill = SPELLID_VICTORY_RUSH,
},
--[[MSBT_TRIGGER_VITAL_MISTS = {
colorR = 0.5,
colorB = 0.5,
message = SPELL_VITAL_MISTS .. " x%a!",
alwaysSticky = true,
fontSize = 26,
classes = "MONK",
mainEvents = "SPELL_AURA_APPLIED{skillName;;eq;;" .. SPELL_VITAL_MISTS .. ";;amount;;eq;;5;;recipientAffiliation;;eq;;" .. FLAG_YOU .. "}"
},]]
}, -- End triggers
-- Master font settings.
normalFontName = L.DEFAULT_FONT_NAME,
normalOutlineIndex = 1,
normalFontSize = 18,
normalFontAlpha = 100,
critFontName = L.DEFAULT_FONT_NAME,
critOutlineIndex = 1,
critFontSize = 26,
critFontAlpha = 100,
-- Animation speed.
animationSpeed = 100,
-- Partial effect settings.
crushing = { colorR = 0.5, colorG = 0, colorB = 0, trailer = string_gsub(CRUSHING_TRAILER, "%((.+)%)", "<%1>") },
glancing = { colorR = 1, colorG = 0, colorB = 0, trailer = string_gsub(GLANCING_TRAILER, "%((.+)%)", "<%1>") },
absorb = { colorR = 1, colorG = 1, colorB = 0, trailer = string_gsub(string_gsub(ABSORB_TRAILER, "%((.+)%)", "<%1>"), "%%d", "%%a") },
block = { colorR = 0.5, colorG = 0, colorB = 1, trailer = string_gsub(string_gsub(BLOCK_TRAILER, "%((.+)%)", "<%1>"), "%%d", "%%a") },
resist = { colorR = 0.5, colorG = 0, colorB = 0.5, trailer = string_gsub(string_gsub(RESIST_TRAILER, "%((.+)%)", "<%1>"), "%%d", "%%a") },
overheal = { colorR = 0, colorG = 0.705, colorB = 0.5, trailer = " <%a>" },
overkill = { disabled = true, colorR = 0.83, colorG = 0, colorB = 0.13, trailer = " <%a>" },
-- Damage color settings.
physical = { colorR = 1, colorG = 1, colorB = 1 },
holy = { colorR = 1, colorG = 1, colorB = 0.627 },
fire = { colorR = 1, colorG = 0.5, colorB = 0.5 },
nature = { colorR = 0.5, colorG = 1, colorB = 0.5 },
frost = { colorR = 0.5, colorG = 0.5, colorB = 1 },
shadow = { colorR = 0.628, colorG = 0, colorB = 0.628 },
arcane = { colorR = 1, colorG = 0.725, colorB = 1 },
frostfire = { colorR = 0.824, colorG = 0.314, colorB = 0.471 },
shadowflame = { colorR = 0.824, colorG = 0.5, colorB = 0.628 },
-- Class color settings.
DEATHKNIGHT = CreateClassSettingsTable("DEATHKNIGHT"),
DRUID = CreateClassSettingsTable("DRUID"),
HUNTER = CreateClassSettingsTable("HUNTER"),
MAGE = CreateClassSettingsTable("MAGE"),
MONK = CreateClassSettingsTable("MONK"),
PALADIN = CreateClassSettingsTable("PALADIN"),
PRIEST = CreateClassSettingsTable("PRIEST"),
ROGUE = CreateClassSettingsTable("ROGUE"),
SHAMAN = CreateClassSettingsTable("SHAMAN"),
WARLOCK = CreateClassSettingsTable("WARLOCK"),
WARRIOR = CreateClassSettingsTable("WARRIOR"),
DEMONHUNTER = CreateClassSettingsTable("DEMONHUNTER"),
EVOKER = CreateClassSettingsTable("EVOKER"),
-- Throttle settings.
dotThrottleDuration = 3,
hotThrottleDuration = 3,
powerThrottleDuration = 3,
throttleList = {
--[SPELL_BLOOD_PRESENCE] = 5,
[SPELL_DRAIN_LIFE] = 3,
[SPELL_SHADOWMEND] = 5,
--[SPELL_REFLECTIVE_SHIELD] = 5,
[SPELL_VAMPIRIC_EMBRACE] = 5,
[SPELL_VAMPIRIC_TOUCH] = 5,
},
-- Spam control settings.
mergeExclusions = {},
abilitySubstitutions = {},
abilitySuppressions = {
[SPELL_UNDYING_RESOLVE] = true,
},
damageThreshold = 0,
healThreshold = 0,
powerThreshold = 0,
hideFullHoTOverheals = true,
shortenNumbers = false,
shortenNumberPrecision = 0,
groupNumbers = false,
-- Cooldown settings.
cooldownExclusions = {},
ignoreCooldownThreshold = {},
cooldownThreshold = 5,
-- Loot settings.
qualityExclusions = {
[LE_ITEM_QUALITY_POOR or Enum.ItemQuality.Poor] = true,
},
alwaysShowQuestItems = true,
itemsAllowed = {},
itemExclusions = {},
}
end
-------------------------------------------------------------------------------
-- Utility functions.
-------------------------------------------------------------------------------
-- ****************************************************************************
-- Dynamically loads the and displays the options.
-- ****************************************************************************
local function ShowOptions()
-- Load the options module if it's not already loaded.
local optionsName = "MSBTOptions"
if (not IsAddOnLoaded(optionsName)) then
local loaded, failureReason = LoadAddOn(optionsName)
-- Display an error message indicating why the module wasn't loaded if it
-- didn't load properly.
if (not loaded) then
local failureMessage = _G["ADDON_" .. failureReason] or failureReason or ""
Print(string_format(ADDON_LOAD_FAILED, optionsName, failureMessage))
end
end
-- Display the main frame if the options module is loaded.
if (IsAddOnLoaded(optionsName)) then MSBTOptions.Main.ShowMainFrame() end
end
-- ****************************************************************************
-- Recursively removes empty tables and their differential map entries.
-- ****************************************************************************
local function RemoveEmptyDifferentials(currentTable)
-- Find nested tables in the current table.
for fieldName, fieldValue in pairs(currentTable) do
if (type(fieldValue) == "table") then
-- Recursively clear empty tables in the nested table.
RemoveEmptyDifferentials(fieldValue)
-- Remove the table from the differential map and current table if it's
-- empty.
if (not next(fieldValue)) then
differentialMap[fieldValue] = nil
differentialCache[#differentialCache+1] = fieldValue
currentTable[fieldName] = nil
end
end
end
end
-- ****************************************************************************
-- Recursively associates the tables in the passed saved table to corresponding
-- entries in the passed master table.
-- ****************************************************************************
local function AssociateDifferentialTables(savedTable, masterTable)
-- Associate the saved table with the corresponding master entry.
differentialMap[savedTable] = masterTable
setmetatable(savedTable, differential_mt)
-- Look for nested tables that have a corresponding master entry.
for fieldName, fieldValue in pairs(savedTable) do
if (type(fieldValue) == "table" and type(masterTable[fieldName]) == "table") then
-- Recursively call the function to associate nested tables.
AssociateDifferentialTables(fieldValue, masterTable[fieldName])
end
end
end
-- ****************************************************************************
-- Set the passed option to the current profile while handling differential
-- profile mechanics.
-- ****************************************************************************
local function SetOption(optionPath, optionName, optionValue, optionDefault)
-- Clear the path table.
EraseTable(pathTable)
-- Split the passed option path into the path table.
if (optionPath) then SplitString(optionPath, "%.", pathTable) end
-- Attempt to go to the option path in the master profile.
local masterOption = masterProfile
for _, fieldName in ipairs(pathTable) do
masterOption = masterOption[fieldName]
if (not masterOption) then break end
end
-- Get the option name from the master profile.
masterOption = masterOption and masterOption[optionName]
-- Check if the option being set needs to be overridden.
local needsOverride = false
if (optionValue ~= masterOption) then needsOverride = true end
-- Treat a nil master option the same as false.
if ((optionValue == false or optionValue == optionDefault) and not masterOption) then
needsOverride = false
end
-- Make the option value false if the option being set is nil and the master option set.
if (optionValue == nil and masterOption) then optionValue = false end
-- Start at the root of the current profile and master profile.
local currentTable = currentProfile
local masterTable = masterProfile
-- Override needed.
if (needsOverride and optionValue ~= nil) then
-- Loop through all of the fields in path table.
for _, fieldName in ipairs(pathTable) do
-- Check if the field doesn't exist in the current profile.
if (not rawget(currentTable, fieldName)) then
-- Create a table for the field and setup the associated inheritance table.
currentTable[fieldName] = table.remove(differentialCache) or {}
if (masterTable and masterTable[fieldName]) then
differentialMap[currentTable[fieldName]] = masterTable[fieldName]
setmetatable(currentTable[fieldName], differential_mt)
end
end
-- Move to the next field in the option path.
currentTable = currentTable[fieldName]
masterTable = masterTable and masterTable[fieldName]
end
-- Set the option's value.
currentTable[optionName] = optionValue
-- Override NOT needed.
else
-- Attempt to go to the option path in the current profile.
for _, fieldName in ipairs(pathTable) do
currentTable = rawget(currentTable, fieldName)
if (not currentTable) then return end
end
-- Clear the option from the path and remove any empty differential tables.
if (currentTable) then
currentTable[optionName] = nil
RemoveEmptyDifferentials(currentProfile)
end
end
end
-- ****************************************************************************
-- Sets up a button to access MSBT's options from the Blizzard interface
-- options AddOns tab.
-- ****************************************************************************
local function SetupBlizzardOptions()
-- Create a container frame for the Blizzard options area.
local frame = CreateFrame("Frame")
frame.name = "MikScrollingBattleText"
-- Create an option button in the center of the frame to launch MSBT's options.
local button = CreateFrame("Button", nil, frame, IsClassic and "OptionsButtonTemplate" or "UIPanelButtonTemplate")
button:SetSize(100, 24)
button:SetPoint("CENTER")
button:SetText(MikSBT.COMMAND)
button:SetScript("OnClick",
function (this)
ShowOptions()
end
)
-- Add the frame as a new category to Blizzard's interface options.
if InterfaceOptions_AddCategory then
InterfaceOptions_AddCategory(frame)
else
local category, layout = Settings.RegisterCanvasLayoutCategory(frame, frame.name);
Settings.RegisterAddOnCategory(category);
end
end
-- ****************************************************************************
-- Disable Blizzard's combat text.
-- ****************************************************************************
local function DisableBlizzardCombatText()
-- Turn off Blizzard's default combat text.
SetCVar("enableFloatingCombatText", 0)
if not IsClassic then
SetCVar("floatingCombatTextCombatHealing", 0)
end
SetCVar("floatingCombatTextCombatDamage", 0)
SHOW_COMBAT_TEXT = "0"
if (CombatText_UpdateDisplayedMessages) then CombatText_UpdateDisplayedMessages() end
end
-- ****************************************************************************
-- Set the user disabled option
-- ****************************************************************************
local function SetOptionUserDisabled(isDisabled)
savedVariables.userDisabled = isDisabled or nil
-- Check if the mod is being set to disabled.
if (isDisabled) then
-- Disable the cooldowns, triggers, event parser, and main modules.
MikSBT.Cooldowns.Disable()
MikSBT.Triggers.Disable()
MikSBT.Parser.Disable()
MikSBT.Main.Disable()
else
-- Enable the main, event parser, triggers, and cooldowns modules.
MikSBT.Main.Enable()
MikSBT.Parser.Enable()
MikSBT.Triggers.Enable()
MikSBT.Cooldowns.Enable()
end
end
-- ****************************************************************************
-- Returns whether or not the mod is disabled.
-- ****************************************************************************
local function IsModDisabled()
return savedVariables and savedVariables.userDisabled
end
-- ****************************************************************************
-- Updates the class colors in the master profile with the colors defined in
-- the CUSTOM_CLASS_COLORS table.
-- ****************************************************************************
local function UpdateCustomClassColors()
for class, colors in pairs(CUSTOM_CLASS_COLORS) do
if (masterProfile[class]) then
masterProfile[class].colorR = colors.r or masterProfile[class].colorR
masterProfile[class].colorG = colors.g or masterProfile[class].colorG
masterProfile[class].colorB = colors.b or masterProfile[class].colorB
end
end
end
-- ****************************************************************************
-- Searches through current profile for all used fonts and uses the animation
-- module to preload each font so they're available for use.
-- ****************************************************************************
local function LoadUsedFonts()
-- Add the normal and crit master font.
local usedFonts = {}
if currentProfile.normalFontName then usedFonts[currentProfile.normalFontName] = true end
if currentProfile.critFontName then usedFonts[currentProfile.critFontName] = true end
-- Add any unique fonts used in the scroll areas.
if currentProfile.scrollAreas then
for saKey, saSettings in pairs(currentProfile.scrollAreas) do
if saSettings.normalFontName then usedFonts[saSettings.normalFontName] = true end
if saSettings.critFontName then usedFonts[saSettings.critFontName] = true end
end
end
-- Add any unique fonts used in the events.
if currentProfile.events then
for eventName, eventSettings in pairs(currentProfile.events) do
if eventSettings.fontName then usedFonts[eventSettings.fontName] = true end
end
end
-- Add any unique fonts used in the triggers.
if currentProfile.triggers then
for triggerName, triggerSettings in pairs(currentProfile.triggers) do
if type(triggerSettings) == "table" then
if triggerSettings.fontName then usedFonts[triggerSettings.fontName] = true end
end
end
end
-- Let the animation system preload the fonts.
for fontName in pairs(usedFonts) do MikSBT.Animations.LoadFont(fontName) end
end
-------------------------------------------------------------------------------
-- Profile functions.
-------------------------------------------------------------------------------
-- ****************************************************************************
-- Updates profiles created with older versions.
-- ****************************************************************************
local function UpdateProfiles()
-- Loop through all the profiles.
for profileName, profile in pairs(savedVariables.profiles) do
-- Get numeric creation version.
local creationVersion = tonumber(select(3, string_find(tostring(profile.creationVersion), "(%d+%.%d+)")))
-- Delete triggers if upgrading from a version prior to 5.2.
if (creationVersion < 5.2) then
profile.triggers = nil
profile.creationVersion = MikSBT.VERSION .. "." .. MikSBT.SVN_REVISION
end
end
end
-- ****************************************************************************
-- Selects the passed profile.
-- ****************************************************************************
local function SelectProfile(profileName)
-- Make sure the profile exists.
if (savedVariables.profiles[profileName]) then
-- Set the current profile name for the character to the one being selected.
savedVariablesPerChar.currentProfileName = profileName
-- Set the current profile pointer.
currentProfile = savedVariables.profiles[profileName]
module.currentProfile = currentProfile
-- Clear the differential table map.
EraseTable(differentialMap)
-- Associate the current profile tables with the corresponding master profile entries.
AssociateDifferentialTables(currentProfile, masterProfile)
-- Load the fonts used by the profile now so they are available by the time
-- the first text is shown.
LoadUsedFonts()
-- Update the scroll areas and triggers with the current profile settings.
MikSBT.Animations.UpdateScrollAreas()
MikSBT.Triggers.UpdateTriggers()
end
end
-- ****************************************************************************
-- Copies the passed profile to a new profile with the passed name.
-- ****************************************************************************
local function CopyProfile(srcProfileName, destProfileName)
-- Leave the function if the the destination profile name is invalid.
if (not destProfileName or destProfileName == "") then return end
-- Make sure the source profile exists and the destination profile doesn't.
if (savedVariables.profiles[srcProfileName] and not savedVariables.profiles[destProfileName]) then
-- Copy the profile.
savedVariables.profiles[destProfileName] = CopyTable(savedVariables.profiles[srcProfileName])
end
end
-- ****************************************************************************
-- Deletes the passed profile.
-- ****************************************************************************
local function DeleteProfile(profileName)
-- Ignore the delete if the passed profile is the default one.
if (profileName == DEFAULT_PROFILE_NAME) then return end
-- Make sure the profile exists.
if (savedVariables.profiles[profileName]) then
-- Check if the profile being deleted is the current one.
if (profileName == savedVariablesPerChar.currentProfileName) then
-- Select the default profile.
SelectProfile(DEFAULT_PROFILE_NAME)
end
-- Delete the profile.
savedVariables.profiles[profileName] = nil
end
end
-- ****************************************************************************
-- Resets the passed profile to its defaults.
-- ****************************************************************************
local function ResetProfile(profileName, showOutput)
-- Set the profile name to the current profile is one wasn't passed.
if (not profileName) then profileName = savedVariablesPerChar.currentProfileName end
-- Make sure the profile exists.
if (savedVariables.profiles[profileName]) then
-- Reset the profile.
EraseTable(savedVariables.profiles[profileName])
-- Reset the profile's creation version.
savedVariables.profiles[profileName].creationVersion = MikSBT.VERSION .. "." .. MikSBT.SVN_REVISION
-- Check if it's the current profile being reset.
if (profileName == savedVariablesPerChar.currentProfileName) then
-- Reselect the profile to update everything.
SelectProfile(profileName)
end
-- Check if the output text is to be shown.
if (showOutput) then
-- Print the profile reset string.
Print(profileName .. " " .. L.MSG_PROFILE_RESET, 0, 1, 0)
end
end
end
-- ****************************************************************************
-- This function initializes the saved variables.
-- ****************************************************************************
local function InitSavedVariables()
-- Set the saved variables per character to the value specified in the .toc file.
savedVariablesPerChar = _G[SAVED_VARS_PER_CHAR_NAME]
-- Check if there are no saved variables per character.
if (not savedVariablesPerChar) then
-- Create a new table to hold the saved variables per character, and set the .toc entry to it.
savedVariablesPerChar = {}
_G[SAVED_VARS_PER_CHAR_NAME] = savedVariablesPerChar
-- Set the current profile for the character to the default profile.
savedVariablesPerChar.currentProfileName = DEFAULT_PROFILE_NAME
end
-- Set the saved variables to the value specified in the .toc file.
savedVariables = _G[SAVED_VARS_NAME]
-- Check if there are no saved variables.
if (not savedVariables) then
-- Create a new table to hold the saved variables, and set the .toc entry to it.
savedVariables = {}
_G[SAVED_VARS_NAME] = savedVariables
-- Create the profiles table and default profile.
savedVariablesPerChar.currentProfileName = DEFAULT_PROFILE_NAME
savedVariables.profiles = {}
savedVariables.profiles[DEFAULT_PROFILE_NAME] = {}
savedVariables.profiles[DEFAULT_PROFILE_NAME].creationVersion = MikSBT.VERSION .. "." .. MikSBT.SVN_REVISION
-- Set the first time loaded flag.
isFirstLoad = true
-- There are saved variables.
else
-- Updates profiles created by older versions.
UpdateProfiles()
end
-- Select the current profile for the character if it exists, otherwise select the default profile.
if (savedVariables.profiles[savedVariablesPerChar.currentProfileName]) then
SelectProfile(savedVariablesPerChar.currentProfileName)
else
SelectProfile(DEFAULT_PROFILE_NAME)
end
-- Set the saved media to the value specified in the .toc file.
savedMedia = _G[SAVED_MEDIA_NAME]
-- Check if there is no saved media.
if (not savedMedia) then
-- Create a new table to hold the saved media, and set the .toc entry to it.
savedMedia = {}
_G[SAVED_MEDIA_NAME] = savedMedia
-- Create custom font and sounds tables.
savedMedia.fonts = {}
savedMedia.sounds = {}
end
-- Allow public access to saved variables.
module.savedVariables = savedVariables
module.savedMedia = savedMedia
end
-------------------------------------------------------------------------------
-- Command handler functions.
-------------------------------------------------------------------------------
-- ****************************************************************************
-- Returns the current and remaining parameters from the passed string.
-- ****************************************************************************
local function GetNextParameter(paramString)
local remainingParams
local currentParam = paramString
-- Look for a space.
local index = string_find(paramString, " ", 1, true)
if (index) then
-- Get the current and remaing parameters.
currentParam = string.sub(paramString, 1, index-1)
remainingParams = string.sub(paramString, index+1)
end
-- Return the current parameter and the remaining ones.
return currentParam, remainingParams
end
-- ****************************************************************************
-- Called to handle commands.
-- ****************************************************************************
local function CommandHandler(params)
-- Get the parameter.
local currentParam, remainingParams
currentParam, remainingParams = GetNextParameter(params)
-- Flag for whether or not to show usage info.
local showUsage = true
-- Make sure there is a current parameter and lower case it.
if (currentParam) then currentParam = string.lower(currentParam) end
-- Look for the recognized parameters.
if (currentParam == "") then
-- Load the on demand options.
ShowOptions()
-- Don't show the usage info.
showUsage = false
-- Reset.
elseif (currentParam == L.COMMAND_RESET) then
-- Reset the current profile.
ResetProfile(nil, true)
-- Don't show the usage info.
showUsage = false
-- Disable.
elseif (currentParam == L.COMMAND_DISABLE) then
-- Set the user disabled option.
SetOptionUserDisabled(true)
-- Output an informative message.
Print(L.MSG_DISABLE, 1, 1, 1)
-- Don't show the usage info.
showUsage = false
-- Enable.
elseif (currentParam == L.COMMAND_ENABLE) then
-- Unset the user disabled option.
SetOptionUserDisabled(false)
-- Output an informative message.
Print(L.MSG_ENABLE, 1, 1, 1)
-- Don't show the usage info.
showUsage = false
-- Version.
elseif (currentParam == L.COMMAND_SHOWVER) then
-- Output the current version number.
Print(MikSBT.VERSION_STRING, 1, 1, 1)
-- Don't show the usage info.
showUsage = false
end
-- Check if the usage information should be shown.
if (showUsage) then
-- Loop through all of the entries in the command usage list.
for _, msg in ipairs(L.COMMAND_USAGE) do
Print(msg, 1, 1, 1)
end
end -- Show usage.
end
-------------------------------------------------------------------------------
-- Event handlers.
-------------------------------------------------------------------------------
-- ****************************************************************************
-- Called when the registered events occur.
-- ****************************************************************************
local function OnEvent(this, event, arg1)
-- When an addon is loaded.
if (event == "ADDON_LOADED") then
-- Ignore the event if it isn't this addon.
if (arg1 ~= "MikScrollingBattleText") then return end
-- Don't get notification for other addons being loaded.
this:UnregisterEvent("ADDON_LOADED")
-- Register slash commands
SLASH_MSBT1 = MikSBT.COMMAND
SlashCmdList["MSBT"] = CommandHandler
-- Initialize the saved variables to make sure there is a profile to work with.
InitSavedVariables()
-- Add a button to launch MSBT's options from the Blizzard interface options.
SetupBlizzardOptions()
-- Let the media module know the variables are initialized.
MikSBT.Media.OnVariablesInitialized()
-- Variables for all addons loaded.
elseif (event == "VARIABLES_LOADED") then
-- Disable or enable the mod depending on the saved setting.
SetOptionUserDisabled(IsModDisabled())
-- Disable Blizzard's combat text if it's the first load.
if (isFirstLoad) then DisableBlizzardCombatText() end
-- Support CUSTOM_CLASS_COLORS.
if (CUSTOM_CLASS_COLORS) then
UpdateCustomClassColors()
if (CUSTOM_CLASS_COLORS.RegisterCallback) then CUSTOM_CLASS_COLORS:RegisterCallback(UpdateCustomClassColors) end
end
collectgarbage("collect")
end
end
-------------------------------------------------------------------------------
-- Initialization.
-------------------------------------------------------------------------------
-- Create a frame to receive events.
eventFrame = CreateFrame("Frame", "MSBTProfileFrame", UIParent)
eventFrame:SetPoint("BOTTOM")
eventFrame:SetWidth(0.0001)
eventFrame:SetHeight(0.0001)
eventFrame:Hide()
eventFrame:SetScript("OnEvent", OnEvent)
-- Register events for when the mod is loaded and variables are loaded.
eventFrame:RegisterEvent("ADDON_LOADED")
eventFrame:RegisterEvent("VARIABLES_LOADED")
-------------------------------------------------------------------------------
-- Module interface.
-------------------------------------------------------------------------------
-- Protected Variables.
module.masterProfile = masterProfile
-- Protected Functions.
module.CopyProfile = CopyProfile
module.DeleteProfile = DeleteProfile
module.ResetProfile = ResetProfile
module.SelectProfile = SelectProfile
module.SetOption = SetOption
module.SetOptionUserDisabled = SetOptionUserDisabled
module.IsModDisabled = IsModDisabled
| 1 | 0.658221 | 1 | 0.658221 | game-dev | MEDIA | 0.864325 | game-dev | 0.970686 | 1 | 0.970686 |
Qfusion/qfusion | 2,496 | source/gameshared/gs_gameteams.c | /*
Copyright (C) 1997-2001 Id Software, Inc.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include "q_arch.h"
#include "q_math.h"
#include "q_shared.h"
#include "q_comref.h"
#include "q_collision.h"
#include "gs_public.h"
//==================================================
//
// TEAMS
//
//==================================================
static const char *gs_teamNames[] =
{
"SPECTATOR",
"MONSTERS",
"PLAYERS",
"ALPHA",
"BETA",
NULL
};
static char *gs_teamSkinsNames[] =
{
NULL, //null means user defined skin
NULL,
NULL,
"default",
"default",
NULL
};
/*
* GS_TeamName
*/
const char *GS_TeamName( int team ) {
if( team < 0 || team >= GS_MAX_TEAMS ) {
return NULL;
}
return gs.api.GetConfigString( CS_TEAM_SPECTATOR_NAME + team );
}
const char *GS_DefaultTeamName( int team ) {
if( team < 0 || team >= GS_MAX_TEAMS ) {
return NULL;
}
return gs_teamNames[team];
}
/*
* GS_TeamSkinName
*/
const char *GS_TeamSkinName( int team ) {
if( team < 0 || team >= GS_MAX_TEAMS ) {
return NULL;
}
return gs_teamSkinsNames[team];
}
/*
* GS_Teams_TeamFromName
*/
int GS_Teams_TeamFromName( const char *teamname ) {
const char *s;
int i;
if( !teamname || !teamname[0] ) {
return -1; // invalid
}
for( i = 0; i < GS_MAX_TEAMS; i++ ) {
s = gs_teamNames[i];
if( !Q_stricmp( s, teamname ) ) {
return i;
}
s = gs.api.GetConfigString( CS_TEAM_SPECTATOR_NAME + i );
if( s && !Q_stricmp( s, teamname ) ) {
return i;
}
}
return -1; // invalid
}
/*
* GS_IsTeamDamage
*/
bool GS_IsTeamDamage( entity_state_t *targ, entity_state_t *attacker ) {
if( !GS_TeamBasedGametype() ) {
return false;
}
assert( targ && attacker );
if( targ->team && attacker->team &&
targ->team == attacker->team &&
targ->team != TEAM_MONSTERS &&
targ->number != attacker->number ) {
return true;
}
return false;
}
| 1 | 0.866559 | 1 | 0.866559 | game-dev | MEDIA | 0.475637 | game-dev | 0.773442 | 1 | 0.773442 |
tsoding/something | 33,655 | src/something_game.cpp | #include "something_game.hpp"
template <typename ... Types>
void displayf(SDL_Renderer *renderer,
Bitmap_Font *font,
RGBA color,
RGBA shadow_color,
Vec2f p,
Types... args)
{
char text[256];
String_Buffer sbuffer = {256, text, 0};
sprintln(&sbuffer, args...);
auto font_size = vec2(FONT_DEBUG_SIZE, FONT_DEBUG_SIZE);
font->render(renderer, p - vec2(2.0f, 2.0f), font_size, shadow_color, text);
font->render(renderer, p, font_size, color, text);
}
void Game::handle_event(SDL_Event *event)
{
// GLOBAL KEYBINDINGS //////
switch (event->type) {
case SDL_QUIT: {
quit = true;
} break;
case SDL_KEYDOWN: {
switch (event->key.keysym.sym) {
case SDLK_BACKSLASH:
case SDLK_BACKQUOTE: {
console.toggle();
} break;
#ifndef SOMETHING_RELEASE
case SDLK_F2: {
fps_debug = !fps_debug;
} break;
case SDLK_F3: {
bfs_debug = !bfs_debug;
} break;
case SDLK_F5: {
command_reload(this, ""_sv);
} break;
#endif // SOMETHING_RELEASE
}
} break;
case SDL_MOUSEMOTION: {
if (debug) {
debug_toolbar.handle_mouse_hover(
vec_cast<float>(vec2(event->motion.x, event->motion.y)));
debug_toolbar.buttons[debug_toolbar.active_button].tool.handle_event(this, event);
}
grid.resolve_point_collision(&collision_probe);
auto weapon = entities[PLAYER_ENTITY_INDEX].get_current_weapon();
if (weapon != NULL &&
weapon->type == Weapon_Type::Placer &&
holding_down_mouse)
{
entity_shoot({PLAYER_ENTITY_INDEX});
}
} break;
case SDL_MOUSEBUTTONDOWN: {
switch (event->button.button) {
case SDL_BUTTON_RIGHT: {
if (debug) {
tracking_projectile =
projectile_at_position(mouse_position);
if (!tracking_projectile.has_value) {
debug_toolbar.buttons[debug_toolbar.active_button].tool.handle_event(this, event);
}
}
} break;
case SDL_BUTTON_LEFT: {
if (!debug_toolbar.handle_click_at({(float) event->button.x, (float) event->button.y})) {
entity_shoot({PLAYER_ENTITY_INDEX});
}
holding_down_mouse = true;
} break;
}
} break;
case SDL_MOUSEBUTTONUP: {
switch (event->button.button) {
case SDL_BUTTON_LEFT: {
holding_down_mouse = false;
} break;
}
if (debug) {
debug_toolbar.buttons[debug_toolbar.active_button].tool.handle_event(this, event);
}
} break;
}
if (console.enabled) {
console.handle_event(event, this);
} else {
switch (event->type) {
case SDL_KEYDOWN: {
switch (event->key.keysym.sym) {
case SDLK_SPACE: {
if (!event->key.repeat) {
if(entities[PLAYER_ENTITY_INDEX].noclip) {
entities[PLAYER_ENTITY_INDEX].vel.y =
-entities[PLAYER_ENTITY_INDEX].speed;
} else {
entity_jump({PLAYER_ENTITY_INDEX});
}
}
} break;
case SDLK_w: {
if (debug) {
entities[PLAYER_ENTITY_INDEX].vel.y = -entities[PLAYER_ENTITY_INDEX].speed;
}
} break;
case SDLK_s: {
if (debug) {
entities[PLAYER_ENTITY_INDEX].vel.y = entities[PLAYER_ENTITY_INDEX].speed;
}
} break;
case SDLK_n: {
noclip(!entities[PLAYER_ENTITY_INDEX].noclip);
} break;
case SDLK_q: {
debug = !debug;
if (debug) {
for (size_t i = ENEMY_ENTITY_INDEX_OFFSET; i < ENTITIES_COUNT; ++i) {
if (entities[i].state == Entity_State::Alive) {
entities[i].stop();
}
}
} else {
entities[PLAYER_ENTITY_INDEX].noclip = false;
}
} break;
case SDLK_z: {
step_debug = !step_debug;
} break;
case SDLK_r: {
reset_entities();
} break;
}
} break;
case SDL_KEYUP: {
if (entities[PLAYER_ENTITY_INDEX].noclip) {
switch (event->key.keysym.sym) {
case SDLK_SPACE:
case SDLK_w:
case SDLK_s: {
if (debug) {
entities[PLAYER_ENTITY_INDEX].vel.y = 0.0f;
}
} break;
}
}
} break;
case SDL_MOUSEWHEEL: {
if (event->wheel.y < 0) {
entities[PLAYER_ENTITY_INDEX].weapon_current =
mod((int) entities[PLAYER_ENTITY_INDEX].weapon_current + 1,
(int) entities[PLAYER_ENTITY_INDEX].weapon_slots_count);
} else if (event->wheel.y > 0) {
entities[PLAYER_ENTITY_INDEX].weapon_current =
mod((int) entities[PLAYER_ENTITY_INDEX].weapon_current - 1,
(int) entities[PLAYER_ENTITY_INDEX].weapon_slots_count);
}
} break;
}
}
}
void Game::update(float dt)
{
entities[PLAYER_ENTITY_INDEX].point_gun_at(mouse_position);
for (size_t i = 0; i < SPIKES_COUNT; ++i) {
spikes[i].update(dt);
}
for (size_t i = 0; i < SPIKE_WAVES_CAPACITY; ++i) {
spike_waves[i].update(dt, this);
}
// Enemy AI //////////////////////////////
auto &player = entities[PLAYER_ENTITY_INDEX];
Recti *lock = NULL;
for (size_t i = 0; i < camera_locks_count; ++i) {
Rectf lock_abs = rect_cast<float>(camera_locks[i]) * TILE_SIZE;
if (rect_contains_vec2(lock_abs, player.pos)) {
lock = &camera_locks[i];
}
}
player.get_current_weapon()->update(dt);
auto player_tile = grid.abs_to_tile_coord(player.pos);
if (lock) {
grid.bfs_to_tile(player_tile, lock);
}
if (!debug && lock) {
Rectf lock_abs = rect_cast<float>(*lock) * TILE_SIZE;
for (size_t i = ENEMY_ENTITY_INDEX_OFFSET; i < ENTITIES_COUNT; ++i) {
auto &enemy = entities[i];
if (enemy.state == Entity_State::Alive) {
if (rect_contains_vec2(lock_abs, enemy.pos)) {
if (enemy.brain.think) {
enemy.brain.think(this, {i}, lock);
}
}
}
}
}
// Update All Entities //////////////////////////////
for (size_t i = 0; i < ENTITIES_COUNT; ++i) {
entities[i].update(dt, this, {i});
if (!entities[i].noclip) entity_resolve_collision({i});
entities[i].has_jumped = false;
if (entities[i].pos.y > WORLD_DEATH_LIMIT) {
kill_entity(&entities[i]);
}
}
// Update All Projectiles //////////////////////////////
update_projectiles(dt);
// Update Items //////////////////////////////
for (size_t i = 0; i < ITEMS_COUNT; ++i) {
items[i].update(dt);
}
// Entities/Projectiles interaction //////////////////////////////
for (size_t index = 0; index < PROJECTILES_COUNT; ++index) {
auto projectile = projectiles + index;
if (projectile->state != Projectile_State::Active) continue;
for (size_t entity_index = 0;
entity_index < ENTITIES_COUNT;
++entity_index)
{
auto entity = entities + entity_index;
if (entity->state == Entity_State::Alive) {
if (entity_index != projectile->shooter.unwrap) {
if (rect_contains_vec2(entity->hitbox_world(), projectile->pos)) {
projectile->kill();
damage_entity(
entity,
ENTITY_PROJECTILE_DAMAGE,
normalize(projectile->vel) * ENTITY_PROJECTILE_KNOCKBACK);
}
}
}
}
}
// Entities/Items interaction
for (size_t index = 0; index < ITEMS_COUNT; ++index) {
auto item = items + index;
if (item->type != ITEM_NONE) {
for (size_t entity_index = 0;
entity_index < ENTITIES_COUNT;
++entity_index)
{
auto entity = entities + entity_index;
if (entity->state == Entity_State::Alive) {
if (rects_overlap(entity->hitbox_world(), item->hitbox_world())) {
switch (item->type) {
case ITEM_NONE: {
assert(0 && "unreachable");
} break;
case ITEM_HEALTH: {
entity->lives = min(entity->lives + ITEM_HEALTH_POINTS, ENTITY_MAX_LIVES);
entity->flash(ENTITY_HEAL_FLASH_COLOR);
mixer.play_sample(POP_SOUND_INDEX);
item->type = ITEM_NONE;
} break;
case ITEM_DIRT_BLOCK: {
for (size_t i = 0; i < entity->weapon_slots_count; ++i) {
if (entity->weapon_slots[i].type == Weapon_Type::Placer &&
entity->weapon_slots[i].placer.tile == TILE_DIRT_0)
{
entity->weapon_slots[i].placer.amount += 1;
break;
}
}
mixer.play_sample(POP_SOUND_INDEX);
item->type = ITEM_NONE;
} break;
case ITEM_ICE_BLOCK: {
for (size_t i = 0; i < entity->weapon_slots_count; ++i) {
if (entity->weapon_slots[i].type == Weapon_Type::Placer &&
entity->weapon_slots[i].placer.tile == TILE_ICE_0)
{
entity->weapon_slots[i].placer.amount += 1;
break;
}
}
mixer.play_sample(POP_SOUND_INDEX);
item->type = ITEM_NONE;
} break;
}
break;
}
}
}
}
}
// Projectiles/Projectiles Interaction /////////
for (size_t i = 0; i < PROJECTILES_COUNT - 1; ++i) {
for (size_t j = i + 1; j < PROJECTILES_COUNT; ++j) {
projectile_collision(&projectiles[i], &projectiles[j]);
}
}
// Player Movement //////////////////////////////
if (!console.enabled) {
if (keyboard[SDL_SCANCODE_D]) {
entities[PLAYER_ENTITY_INDEX].move(Entity::Right);
} else if (keyboard[SDL_SCANCODE_A]) {
entities[PLAYER_ENTITY_INDEX].move(Entity::Left);
} else {
entities[PLAYER_ENTITY_INDEX].stop();
}
}
// Camera "Physics" //////////////////////////////
const auto player_pos = entities[PLAYER_ENTITY_INDEX].pos;
if(entities[PLAYER_ENTITY_INDEX].noclip) {
camera.vel = (player_pos - camera.pos) * NOCLIP_CAMERA_FORCE;
} else {
camera.vel = (player_pos - camera.pos) * PLAYER_CAMERA_FORCE;
for (size_t i = 0; i < camera_locks_count; ++i) {
Rectf lock_abs = rect_cast<float>(camera_locks[i]) * TILE_SIZE;
if (rect_contains_vec2(lock_abs, player_pos)) {
camera.vel += (rect_center(lock_abs) - camera.pos) * CENTER_CAMERA_FORCE;
}
}
if (camera_shaking_timeout > 0.0f) {
auto random_shaking_vector = polar(CAMERA_SHAKING_INTENSITY, rand_float_range(0.0f, 2.0f * PI));
camera.vel += random_shaking_vector;
camera_shaking_timeout -= dt;
}
}
camera.update(dt);
// Popup //////////////////////////////
popup.update(dt);
// Console //////////////////////////////
console.update(dt);
}
void Game::render(SDL_Renderer *renderer)
{
Recti *lock = NULL;
for (size_t i = 0; i < camera_locks_count; ++i) {
Rectf lock_abs = rect_cast<float>(camera_locks[i]) * TILE_SIZE;
if (rect_contains_vec2(lock_abs, entities[PLAYER_ENTITY_INDEX].pos)) {
lock = &camera_locks[i];
}
}
background.render(renderer, camera);
for (size_t i = 0; i < SPIKES_COUNT; ++i) {
spikes[i].render(renderer, camera);
}
if (bfs_debug && lock) {
grid.render_debug_bfs_overlay(
renderer,
&camera,
lock);
}
grid.render(renderer, camera, lock);
entities[PLAYER_ENTITY_INDEX].render(renderer, camera);
if (lock) {
Rectf lock_abs = rect_cast<float>(*lock) * TILE_SIZE;
for (size_t i = ENEMY_ENTITY_INDEX_OFFSET; i < ENTITIES_COUNT; ++i) {
if (rect_contains_vec2(lock_abs, entities[i].pos)) {
entities[i].render(renderer, camera);
} else {
entities[i].render(renderer, camera, ROOM_NEIGHBOR_DIM_COLOR);
}
}
} else {
for (size_t i = ENEMY_ENTITY_INDEX_OFFSET; i < ENTITIES_COUNT; ++i) {
entities[i].render(renderer, camera, ROOM_NEIGHBOR_DIM_COLOR);
}
}
// TODO(#353): enemies don't have their weapons renderered
{
auto weapon = entities[PLAYER_ENTITY_INDEX].get_current_weapon();
if (weapon != NULL) {
weapon->render(renderer, this, {PLAYER_ENTITY_INDEX});
}
}
render_projectiles(renderer, camera);
for (size_t i = 0; i < ITEMS_COUNT; ++i) {
if (items[i].type != ITEM_NONE) {
items[i].render(renderer, camera);
}
}
if (fps_debug) {
render_fps_overlay(renderer);
}
render_player_hud(renderer);
popup.render(renderer);
console.render(renderer, &debug_font);
}
void Game::entity_shoot(Index<Entity> entity_index)
{
assert(entity_index.unwrap < ENTITIES_COUNT);
Entity *entity = &entities[entity_index.unwrap];
if (entity->state == Entity_State::Alive) {
auto weapon = entity->get_current_weapon();
if (weapon != NULL) {
switch (weapon->type) {
case Weapon_Type::Gun: {
if (entity->cooldown_weapon <= 0) {
weapon->shoot(this, entity_index);
if (weapon->shoot_sample.has_value) {
mixer.play_sample(weapon->shoot_sample.unwrap);
}
// TODO(#305): can we move cooldown_weapon to the Weapon struct
entity->cooldown_weapon = ENTITY_COOLDOWN_WEAPON;
}
} break;
case Weapon_Type::Stomp:
case Weapon_Type::Placer: {
weapon->shoot(this, entity_index);
} break;
}
}
}
}
bool Game::does_tile_contain_entity(Vec2i tile_coord)
{
Rectf tile_rect = grid.rect_of_tile(tile_coord);
for (size_t i = 0; i < ENTITIES_COUNT; ++i) {
if (entities[i].state == Entity_State::Alive && rects_overlap(tile_rect, entities[i].hitbox_world())) {
return true;
}
}
return false;
}
Vec2i Game::where_entity_can_place_block(Index<Entity> index, bool *can_place)
{
Entity *entity = &entities[index.unwrap];
const auto allowed_length = min(length(entity->gun_dir), DIRT_BLOCK_PLACEMENT_PROXIMITY);
const auto allowed_target = entity->pos + allowed_length *normalize(entity->gun_dir);
const auto target_tile = grid.abs_to_tile_coord(allowed_target);
if (can_place) {
*can_place = grid.get_tile(target_tile) == TILE_EMPTY &&
grid.a_sees_b(entity->pos, grid.abs_center_of_tile(target_tile)) &&
!does_tile_contain_entity(target_tile);
}
return target_tile;
}
void Game::entity_jump(Index<Entity> entity_index)
{
assert(entity_index.unwrap < ENTITIES_COUNT);
entities[entity_index.unwrap].jump();
}
void Game::reset_entities()
{
static_assert(ROOM_ROW_COUNT > 0);
entities[PLAYER_ENTITY_INDEX] = player_entity(vec2(200.0f, 200.0f));
}
void Game::entity_resolve_collision(Index<Entity> entity_index)
{
assert(entity_index.unwrap < ENTITIES_COUNT);
Entity *entity = &entities[entity_index.unwrap];
if (entity->state == Entity_State::Alive) {
const float step_x =
entity->hitbox_local.w / ceilf(entity->hitbox_local.w / ENTITY_MESH_STEP);
const float step_y =
entity->hitbox_local.h / ceilf(entity->hitbox_local.h / ENTITY_MESH_STEP);
const Vec2f origin = entity->pos;
for (int rows = 0; rows * step_x <= entity->hitbox_local.w; ++rows) {
for (int cols = 0; cols * step_y <= entity->hitbox_local.h; ++cols) {
Vec2f t0 = entity->pos +
vec2(entity->hitbox_local.x, entity->hitbox_local.y) +
vec2(cols * step_x, rows * step_y);
Vec2f t1 = t0;
grid.resolve_point_collision(&t1);
entity->pos += t1 - t0;
}
}
const Vec2f d = entity->pos - origin;
// NOTE: Don't consider y-impact if x-impact has happened
// This is needed to not get stuck in the wall in the middle of the air
if (abs(d.x) >= ENTITY_IMPACT_THRESHOLD) {
entity->vel.x = 0;
} else if (abs(d.y) >= ENTITY_IMPACT_THRESHOLD && !entity->has_jumped) {
if (fabsf(entity->vel.y) > LANDING_PARTICLE_BURST_THRESHOLD) {
for (int i = 0; i < ENTITY_JUMP_PARTICLE_BURST; ++i) {
entity->particles.push(rand_float_range(PARTICLE_JUMP_VEL_LOW, fabsf(entity->vel.y) * 0.25f));
}
}
entity->vel.y = 0;
}
}
}
void Game::spawn_projectile(Projectile projectile)
{
for (size_t i = 0; i < PROJECTILES_COUNT; ++i) {
if (projectiles[i].state == Projectile_State::Ded) {
projectiles[i] = projectile;
return;
}
}
}
void Game::render_debug_overlay(SDL_Renderer *renderer, size_t fps)
{
sec(SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255));
const float COLLISION_PROBE_SIZE = 10.0f;
const auto collision_probe_rect = rect(
camera.to_screen(collision_probe - COLLISION_PROBE_SIZE),
COLLISION_PROBE_SIZE * 2, COLLISION_PROBE_SIZE * 2);
{
auto rect = rectf_for_sdl(collision_probe_rect);
sec(SDL_RenderFillRect(renderer, &rect));
}
const float PADDING = 10.0f;
displayf(renderer, &debug_font,
FONT_DEBUG_COLOR,
FONT_SHADOW_COLOR,
vec2(PADDING, PADDING),
"FPS: ", fps);
displayf(renderer, &debug_font,
FONT_DEBUG_COLOR,
FONT_SHADOW_COLOR,
vec2(PADDING, 50 + PADDING),
"Mouse Position: ",
mouse_position.x, " ",
mouse_position.y);
displayf(renderer, &debug_font,
FONT_DEBUG_COLOR,
FONT_SHADOW_COLOR,
vec2(PADDING, 2 * 50 + PADDING),
"Collision Probe: ",
collision_probe.x, " ",
collision_probe.y);
displayf(renderer, &debug_font,
FONT_DEBUG_COLOR,
FONT_SHADOW_COLOR,
vec2(PADDING, 3 * 50 + PADDING),
"Projectiles: ",
count_alive_projectiles());
displayf(renderer, &debug_font,
FONT_DEBUG_COLOR,
FONT_SHADOW_COLOR,
vec2(PADDING, 4 * 50 + PADDING),
"Player position: ",
entities[PLAYER_ENTITY_INDEX].pos.x, " ",
entities[PLAYER_ENTITY_INDEX].pos.y);
displayf(renderer, &debug_font,
FONT_DEBUG_COLOR,
FONT_SHADOW_COLOR,
vec2(PADDING, 5 * 50 + PADDING),
"Player velocity: ",
entities[PLAYER_ENTITY_INDEX].vel.x, " ",
entities[PLAYER_ENTITY_INDEX].vel.y);
if (tracking_projectile.has_value) {
auto projectile = projectiles[tracking_projectile.unwrap.unwrap];
const float SECOND_COLUMN_OFFSET = 700.0f;
const RGBA TRACKING_DEBUG_COLOR = sdl_to_rgba({255, 255, 150, 255});
displayf(renderer, &debug_font,
TRACKING_DEBUG_COLOR,
FONT_SHADOW_COLOR,
vec2(PADDING + SECOND_COLUMN_OFFSET, PADDING),
"State: ", projectile_state_as_cstr(projectile.state));
displayf(renderer, &debug_font,
TRACKING_DEBUG_COLOR,
FONT_SHADOW_COLOR,
vec2(PADDING + SECOND_COLUMN_OFFSET, 50 + PADDING),
"Position: ",
projectile.pos.x, " ", projectile.pos.y);
displayf(renderer, &debug_font,
TRACKING_DEBUG_COLOR,
FONT_SHADOW_COLOR,
vec2(PADDING + SECOND_COLUMN_OFFSET, 2 * 50 + PADDING),
"Velocity: ",
projectile.vel.x, " ", projectile.vel.y);
displayf(renderer, &debug_font,
TRACKING_DEBUG_COLOR,
FONT_SHADOW_COLOR,
vec2(PADDING + SECOND_COLUMN_OFFSET, 3 * 50 + PADDING),
"Shooter Index: ",
projectile.shooter.unwrap);
}
for (size_t i = 0; i < ENTITIES_COUNT; ++i) {
if (entities[i].state == Entity_State::Ded) continue;
sec(SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255));
auto dstrect = rectf_for_sdl(camera.to_screen(entities[i].texbox_world()));
sec(SDL_RenderDrawRect(renderer, &dstrect));
sec(SDL_SetRenderDrawColor(renderer, 255, 255, 0, 255));
auto hitbox = rectf_for_sdl(camera.to_screen(entities[i].hitbox_world()));
sec(SDL_RenderDrawRect(renderer, &hitbox));
entities[i].render_debug(renderer, camera, &debug_font);
}
for (size_t i = 0; i < PROJECTILES_COUNT; ++i) {
if (projectiles[i].state == Projectile_State::Active) {
draw_rect(renderer, camera.to_screen(projectiles[i].hitbox()), RGBA_RED);
}
}
if (tracking_projectile.has_value) {
sec(SDL_SetRenderDrawColor(renderer, 255, 255, 0, 255));
auto hitbox = rectf_for_sdl(
camera.to_screen(hitbox_of_projectile(tracking_projectile.unwrap)));
sec(SDL_RenderDrawRect(renderer, &hitbox));
}
auto projectile_index = projectile_at_position(mouse_position);
if (projectile_index.has_value) {
sec(SDL_SetRenderDrawColor(renderer, 255, 255, 0, 255));
auto hitbox = rectf_for_sdl(
camera.to_screen(hitbox_of_projectile(projectile_index.unwrap)));
sec(SDL_RenderDrawRect(renderer, &hitbox));
} else {
sec(SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255));
const Rectf tile_rect = {
floorf(mouse_position.x / TILE_SIZE) * TILE_SIZE,
floorf(mouse_position.y / TILE_SIZE) * TILE_SIZE,
TILE_SIZE,
TILE_SIZE
};
auto rect = rectf_for_sdl(camera.to_screen(tile_rect));
sec(SDL_RenderDrawRect(renderer, &rect));
}
for (size_t i = 0; i < ITEMS_COUNT; ++i) {
items[i].render_debug(renderer, camera);
}
debug_toolbar.render(renderer, debug_font);
}
void Game::render_fps_overlay(SDL_Renderer *renderer) {
const float PADDING = 20.0f;
const float SCALE = 5000.0f;
const float BAR_WIDTH = 2.0f;
for (size_t i = 0; i < FPS_BARS_COUNT; ++i) {
size_t j = (frame_delays_begin + i) % FPS_BARS_COUNT;
fill_rect(
renderer,
rect(
vec2(SCREEN_WIDTH - PADDING - (float) (FPS_BARS_COUNT - j) * BAR_WIDTH,
SCREEN_HEIGHT - PADDING - frame_delays[j] * SCALE),
BAR_WIDTH,
frame_delays[j] * SCALE),
{ clamp( frame_delays[j] * 60.0f - 1.0f, 0.0f, 1.0f),
clamp(2.0f - frame_delays[j] * 60.0f , 0.0f, 1.0f),
0, (float) i / (float) FPS_BARS_COUNT});
}
}
int Game::count_alive_projectiles(void)
{
int res = 0;
for (size_t i = 0; i < PROJECTILES_COUNT; ++i) {
if (projectiles[i].state != Projectile_State::Ded) ++res;
}
return res;
}
void Game::render_projectiles(SDL_Renderer *renderer, Camera camera)
{
for (size_t i = 0; i < PROJECTILES_COUNT; ++i) {
projectiles[i].render(renderer, &camera);
}
}
void Game::update_projectiles(float dt)
{
for (size_t i = 0; i < PROJECTILES_COUNT; ++i) {
projectiles[i].update(dt, &grid);
}
}
const float PROJECTILE_TRACKING_PADDING = 50.0f;
Rectf Game::hitbox_of_projectile(Index<Projectile> index)
{
assert(index.unwrap < PROJECTILES_COUNT);
return Rectf {
projectiles[index.unwrap].pos.x - PROJECTILE_TRACKING_PADDING * 0.5f,
projectiles[index.unwrap].pos.y - PROJECTILE_TRACKING_PADDING * 0.5f,
PROJECTILE_TRACKING_PADDING,
PROJECTILE_TRACKING_PADDING
};
}
Maybe<Index<Projectile>> Game::projectile_at_position(Vec2f position)
{
for (size_t i = 0; i < PROJECTILES_COUNT; ++i) {
if (projectiles[i].state == Projectile_State::Ded) continue;
Rectf hitbox = hitbox_of_projectile({i});
if (rect_contains_vec2(hitbox, position)) {
return {true, {i}};
}
}
return {};
}
void Game::spawn_dirt_block_item_at(Vec2f pos)
{
for (size_t i = 0; i < ITEMS_COUNT; ++i) {
if (items[i].type == ITEM_NONE) {
items[i] = make_dirt_block_item(pos);
break;
}
}
}
void Game::spawn_dirt_block_item_at_mouse()
{
spawn_dirt_block_item_at(mouse_position);
}
void Game::spawn_item_at(Item item, Vec2f pos)
{
item.pos = pos;
for (size_t i = 0; i < ITEMS_COUNT; ++i) {
if (items[i].type == ITEM_NONE) {
items[i] = item;
break;
}
}
}
void Game::spawn_health_at_mouse()
{
for (size_t i = 0; i < ITEMS_COUNT; ++i) {
if (items[i].type == ITEM_NONE) {
items[i] = make_health_item(mouse_position);
break;
}
}
}
void Game::add_camera_lock(Recti rect)
{
assert(camera_locks_count < CAMERA_LOCKS_CAPACITY);
camera_locks[camera_locks_count++] = rect;
}
void Game::spawn_entity_at(Entity entity, Vec2f pos)
{
entity.pos = pos;
for (size_t i = PLAYER_ENTITY_INDEX + ENEMY_ENTITY_INDEX_OFFSET; i < ENTITIES_COUNT; ++i) {
if (entities[i].state == Entity_State::Ded) {
entities[i] = entity;
break;
}
}
}
void Game::spawn_enemy_at(Vec2f pos)
{
for (size_t i = PLAYER_ENTITY_INDEX + ENEMY_ENTITY_INDEX_OFFSET; i < ENTITIES_COUNT; ++i) {
if (entities[i].state == Entity_State::Ded) {
entities[i] = enemy_entity(pos);
break;
}
}
}
void Game::spawn_golem_at(Vec2f pos)
{
for (size_t i = PLAYER_ENTITY_INDEX + ENEMY_ENTITY_INDEX_OFFSET; i < ENTITIES_COUNT; ++i) {
if (entities[i].state == Entity_State::Ded) {
entities[i] = golem_entity(pos);
break;
}
}
}
int Game::get_rooms_count(void)
{
int result = 0;
DIR *rooms_dir = opendir("./assets/rooms/");
if (rooms_dir == NULL) {
println(stderr, "Can't open asset folder: ./assets/rooms/");
abort();
}
for (struct dirent *d = readdir(rooms_dir);
d != NULL;
d = readdir(rooms_dir)) {
if (*d->d_name == '.') continue;
result++;
}
closedir(rooms_dir);
return result;
}
void Game::render_player_hud(SDL_Renderer *renderer)
{
Entity *player = &entities[PLAYER_ENTITY_INDEX];
const size_t MAXIMUM_LENGTH = 3;
char label[MAXIMUM_LENGTH + 1];
auto text_width = MAXIMUM_LENGTH * BITMAP_FONT_CHAR_WIDTH * PLAYER_HUD_FONT_SIZE;
auto text_height = BITMAP_FONT_CHAR_HEIGHT * PLAYER_HUD_FONT_SIZE;
Vec2f border_size = vec2(
PLAYER_HUD_ICON_WIDTH + PADDING_BETWEEN_TEXT_AND_ICON + text_width + PLAYER_HUD_PADDING * 2,
max(PLAYER_HUD_ICON_HEIGHT, text_height) + PLAYER_HUD_PADDING * 2);
for (size_t i = 0; i < player->weapon_slots_count; ++i) {
const auto position = vec2(PLAYER_HUD_MARGIN, PLAYER_HUD_MARGIN + (border_size.y + PLAYER_HUD_MARGIN) * i);
fill_rect(renderer, rect(position, border_size), i == player->weapon_current ? PLAYER_HUD_SELECTED_COLOR : PLAYER_HUD_BACKGROUND_COLOR);
Rectf destrect = rect(position + vec2(PLAYER_HUD_PADDING, PLAYER_HUD_PADDING),
vec2(PLAYER_HUD_ICON_WIDTH, PLAYER_HUD_ICON_HEIGHT));
player->weapon_slots[i].icon().render(renderer, destrect);
switch (player->weapon_slots[i].type) {
case Weapon_Type::Stomp:
case Weapon_Type::Gun:
snprintf(label, sizeof(label), "inf");
break;
case Weapon_Type::Placer:
snprintf(label, sizeof(label), "%d", (unsigned) player->weapon_slots[i].placer.amount);
break;
}
debug_font.render(
renderer,
position + vec2(PLAYER_HUD_PADDING + PLAYER_HUD_ICON_WIDTH + PADDING_BETWEEN_TEXT_AND_ICON, PLAYER_HUD_PADDING),
vec2(PLAYER_HUD_FONT_SIZE, PLAYER_HUD_FONT_SIZE),
PLAYER_HUD_FONT_COLOR,
label);
}
}
void Game::noclip(bool on)
{
if (debug) {
entities[PLAYER_ENTITY_INDEX].noclip = on;
if (entities[PLAYER_ENTITY_INDEX].noclip) {
popup.notify(FONT_SUCCESS_COLOR, "Noclip enabled");
entities[PLAYER_ENTITY_INDEX].vel.y = 0;
} else {
popup.notify(FONT_FAILURE_COLOR, "Noclip disabled");
}
}
}
void Game::projectile_collision(Projectile *a, Projectile *b)
{
if (a != b &&
a->state == Projectile_State::Active &&
b->state == Projectile_State::Active)
{
if (rects_overlap(a->hitbox(), b->hitbox())) {
if ((a->kind == Projectile_Kind::Ice && b->kind == Projectile_Kind::Fire) ||
(a->kind == Projectile_Kind::Rock && b->kind == Projectile_Kind::Water) ||
(a->kind == Projectile_Kind::Fire && b->kind == Projectile_Kind::Water))
{
swap(&a, &b);
}
if (a->kind == Projectile_Kind::Fire && b->kind == Projectile_Kind::Ice) {
spawn_projectile(
water_projectile(
b->pos,
normalize(a->vel + b->vel) * PROJECTILE_SPEED,
b->shooter));
a->kill();
b->kill();
}
if (a->kind == Projectile_Kind::Water && b->kind == Projectile_Kind::Rock) {
a->kill();
b->kill();
}
if (a->kind == Projectile_Kind::Water && b->kind == Projectile_Kind::Fire) {
b->kill();
}
}
}
}
void Game::drop_all_items_of_entity(Entity *entity)
{
for (size_t i = 0; i < entity->items_count; ++i) {
for (size_t j = 0; j < entity->items[i].count; ++j) {
spawn_item_at(entity->items[i].item, entity->pos);
}
}
entity->items_count = 0;
}
void Game::kill_entity(Entity *entity)
{
if (entity->state == Entity_State::Alive) {
entity->state = Entity_State::Poof;
drop_all_items_of_entity(entity);
}
}
void Game::damage_entity(Entity *entity, int amount, Vec2f knockback)
{
entity->lives -= amount;
mixer.play_sample(OOF_SOUND_INDEX);
if (entity->lives <= 0) {
kill_entity(entity);
mixer.play_sample(CRUNCH_SOUND_INDEX);
} else {
entity->vel += knockback;
entity->flash(ENTITY_DAMAGE_FLASH_COLOR);
}
}
void Game::damage_radius(Vec2f center, float radius, Index<Entity> stomper)
{
for (size_t i = 0; i < ENTITIES_COUNT; ++i) {
if (i != stomper.unwrap && entities[i].state == Entity_State::Alive) {
Vec2f dir = entities[i].pos - center;
if (sqr_len(dir) <= radius * radius) {
damage_entity(
&entities[i],
ENTITY_STOMP_DAMAGE,
normalize(dir) * ENTITY_STOMP_KNOCKBACK);
}
}
}
}
void Game::shake_camera(float duration)
{
camera_shaking_timeout = duration;
}
void Game::spawn_spike(Spike spike)
{
for (size_t i = 0; i < SPIKES_COUNT; ++i) {
if (spikes[i].state == Spike_State::Ded) {
spikes[i] = spike;
spikes[i].activate();
return;
}
}
}
void Game::spawn_spike_wave(Vec2f pos, Vec2f dir)
{
for (size_t i = 0; i < SPIKE_WAVES_CAPACITY; ++i) {
if (spike_waves[i].count == 0) {
spike_waves[i].activate(pos, dir);
return;
}
}
}
| 1 | 0.942871 | 1 | 0.942871 | game-dev | MEDIA | 0.987572 | game-dev | 0.965429 | 1 | 0.965429 |
eloquentarduino/EloquentArduino | 1,669 | src/eloquent/graphics/colormaps/seismic_r.h | //
// Created by Simone on 18/05/2022.
//
#pragma once
#include "../../macros.h"
namespace Eloquent {
namespace Graphics {
namespace Colormaps {
class Seismic_r {
public:
/**
* Convert single byte to RGB color
* @param x
* @param r
* @param g
* @param b
*/
void convert(uint8_t x, uint8_t *r, uint8_t *g, uint8_t *b) {
*r = red[x << 2];
*g = green[x << 2];
*b = blue[x << 2];
}
protected:
uint8_t red[64] = {127, 135, 143, 151, 159, 167, 176, 184, 192, 200, 208, 216, 224, 232, 240, 248, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 246, 230, 214, 198, 182, 165, 149, 133, 117, 101, 85, 68, 52, 36, 20, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
uint8_t green[64] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 20, 36, 52, 68, 85, 101, 117, 133, 149, 165, 182, 198, 214, 230, 246, 246, 230, 214, 198, 182, 165, 149, 133, 117, 101, 85, 68, 52, 36, 20, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
uint8_t blue[64] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 20, 36, 52, 68, 85, 101, 117, 133, 149, 165, 182, 198, 214, 230, 246, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 246, 235, 223, 212, 201, 189, 178, 167, 155, 144, 133, 121, 110, 99, 87, 76};
};
}
}
}
ELOQUENT_SINGLETON(Eloquent::Graphics::Colormaps::Seismic_r seismic_r); | 1 | 0.635693 | 1 | 0.635693 | game-dev | MEDIA | 0.56828 | game-dev | 0.551556 | 1 | 0.551556 |
uzh-rpg/sb_min_time_quadrotor_planning | 3,756 | include/vel_search_graph.hpp | #pragma once
#include <vector>
#include "base_map.hpp"
#include "dijkstra.hpp"
#include "drone.hpp"
#include "esdf_map.hpp"
#include "point_speed3d.hpp"
struct TrajectoryPoint {
TrajectoryPoint() {}
TrajectoryPoint(Vector<3> position_, double angle_deg_, bool is_gate_,
int target_gate_id_, int topology_path_id_,
double portion_between_gates_) {
position = position_;
angle_deg = angle_deg_;
is_gate = is_gate_;
target_gate_id = target_gate_id_;
topology_path_id = topology_path_id_;
portion_between_gates = portion_between_gates_;
}
Vector<3> position;
Vector<3> velocity;
double angle_deg;
bool is_gate = false;
int target_gate_id;
int topology_path_id;
double portion_between_gates;
};
struct TrajectoryState {
TrajectoryState() {
state.setZero();
is_gate = false;
}
TrajectoryState(DroneState state_, bool gate_ = false) {
state = state_;
is_gate = gate_;
}
DroneState state;
bool is_gate = false;
};
struct VelocitySearchResult {
double time;
std::vector<Vector<3>> found_gates_speeds;
std::vector<TrMaxAcc3D> trajectories;
std::vector<TrajectoryPoint> gates_waypoints;
bool operator()(VelocitySearchResult& a, VelocitySearchResult& b) {
return a.time > b.time;
}
};
struct VelocitySearchCollision {
VelocitySearchCollision() {
collision_free = true;
position = Vector<3>::Constant(NAN);
trajectory_index = -1;
}
bool collision_free;
Vector<3> position;
int trajectory_index;
};
class VelSearchGraph {
public:
VelSearchGraph(const Drone* drone, std::shared_ptr<BaseMap> map,
const bool check_collisions,
const double collision_distance_check,
const double min_clearance, const double max_yaw_pitch_ang,
const double precision_yaw_pitch_ang,
const double yaw_pitch_cone_angle_boundary,
const double min_velocity_size_boundary,
const double min_velocity_size, const double max_velocity_size,
const double precision_velocity_size,
const std::string output_folder);
VelocitySearchResult find_velocities_in_positions(
const std::vector<TrajectoryPoint>& gates_waypoints,
const bool check_collisions_during_search, const bool end_free);
void save_track_trajectory(const std::vector<TrMaxAcc3D>& trajectories,
const double trajectories_time,
std::string filename);
void save_track_trajectory_equidistant(
const std::vector<TrMaxAcc3D>& trajectories, const double trajectories_time,
std::string filename);
static VelocitySearchCollision isCollisionFree(const TrMaxAcc3D& trajectory);
static VelocitySearchCollision isCollisionFree(
const VelocitySearchResult& trajectory);
static std::vector<Vector<3>> sampleTrajectory(const TrMaxAcc3D& trajectory,
const double ds_desired);
private:
static std::shared_ptr<BaseMap> map_;
static double collision_distance_check_;
static double min_clearance_;
static bool check_collisions_;
// std::vector<std::vector<std::pair<int, double>>> shortest_samples_times_;
// const std::vector<DroneState> gates_;
// const std::vector<double> gates_orientations_;
// const DroneState start_;
// const DroneState end_;
const Drone* drone_;
const double max_yaw_pitch_ang_;
const double precision_yaw_pitch_ang_;
const double max_velocity_size_;
const double min_velocity_size_;
const double min_velocity_size_boundary_;
const double yaw_pitch_cone_angle_boundary_;
const double precision_velocity_size_;
const std::string output_folder_;
}; | 1 | 0.905102 | 1 | 0.905102 | game-dev | MEDIA | 0.401598 | game-dev | 0.599228 | 1 | 0.599228 |
adham-elarabawy/open-quadruped | 1,574 | llc-teensy/lib/ros_lib/actionlib/TwoIntsAction.h | #ifndef _ROS_actionlib_TwoIntsAction_h
#define _ROS_actionlib_TwoIntsAction_h
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include "ros/msg.h"
#include "actionlib/TwoIntsActionGoal.h"
#include "actionlib/TwoIntsActionResult.h"
#include "actionlib/TwoIntsActionFeedback.h"
namespace actionlib
{
class TwoIntsAction : public ros::Msg
{
public:
typedef actionlib::TwoIntsActionGoal _action_goal_type;
_action_goal_type action_goal;
typedef actionlib::TwoIntsActionResult _action_result_type;
_action_result_type action_result;
typedef actionlib::TwoIntsActionFeedback _action_feedback_type;
_action_feedback_type action_feedback;
TwoIntsAction():
action_goal(),
action_result(),
action_feedback()
{
}
virtual int serialize(unsigned char *outbuffer) const
{
int offset = 0;
offset += this->action_goal.serialize(outbuffer + offset);
offset += this->action_result.serialize(outbuffer + offset);
offset += this->action_feedback.serialize(outbuffer + offset);
return offset;
}
virtual int deserialize(unsigned char *inbuffer)
{
int offset = 0;
offset += this->action_goal.deserialize(inbuffer + offset);
offset += this->action_result.deserialize(inbuffer + offset);
offset += this->action_feedback.deserialize(inbuffer + offset);
return offset;
}
const char * getType(){ return "actionlib/TwoIntsAction"; };
const char * getMD5(){ return "6d1aa538c4bd6183a2dfb7fcac41ee50"; };
};
}
#endif
| 1 | 0.8509 | 1 | 0.8509 | game-dev | MEDIA | 0.540046 | game-dev | 0.519098 | 1 | 0.519098 |
terrajobst/nquery-vnext | 6,127 | src/NQuery/Syntax/SeparatedSyntaxList.cs | using System.Collections;
using System.Collections.Immutable;
namespace NQuery.Syntax
{
public sealed class SeparatedSyntaxList<TNode> : IList<TNode>, IReadOnlyList<TNode>
where TNode : SyntaxNode
{
private readonly ImmutableArray<Entry> _entries;
public static readonly SeparatedSyntaxList<TNode> Empty = new(Array.Empty<SyntaxNodeOrToken>());
internal SeparatedSyntaxList(IReadOnlyCollection<SyntaxNodeOrToken> nodeOrTokens)
{
ValidateEntries(nodeOrTokens);
_entries = ReadEntries(nodeOrTokens);
}
private static void ValidateEntries(IEnumerable<SyntaxNodeOrToken> nodeOrTokens)
{
SyntaxNodeOrToken? last = null;
foreach (var nodeOrToken in nodeOrTokens)
{
// We expect a node if either of the following is true
//
// * It's the first element
// * The last element was a separator
// * The current element is a node
var requiresValidNode = (last is null ||
!last.Value.IsNode ||
nodeOrToken.IsNode);
if (requiresValidNode)
{
var isValidNode = nodeOrToken.IsNode && nodeOrToken.AsNode() is TNode;
if (!isValidNode)
throw new ArgumentException(Resources.SeparatedSyntaxListInvalidSequence, nameof(nodeOrTokens));
}
last = nodeOrToken;
}
}
private static ImmutableArray<Entry> ReadEntries(IReadOnlyCollection<SyntaxNodeOrToken> nodeOrTokens)
{
var entryCount = (nodeOrTokens.Count + 1) / 2;
var entries = new Entry[entryCount];
var entryIndex = 0;
foreach (var nodeOrToken in nodeOrTokens)
{
if (nodeOrToken.IsToken)
{
var itemIndex = entryIndex - 1;
var lastEntry = entries[itemIndex];
var separator = nodeOrToken.AsToken();
entries[itemIndex] = new Entry(lastEntry.Node, separator);
}
else
{
var node = (TNode)nodeOrToken.AsNode();
entries[entryIndex] = new Entry(node, null);
entryIndex++;
}
}
return entries.ToImmutableArray();
}
public IEnumerator<TNode> GetEnumerator()
{
return _entries.Select(e => e.Node).GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public SyntaxToken GetSeparator(int index)
{
return _entries[index].Separator;
}
public IEnumerable<SyntaxNodeOrToken> GetWithSeparators()
{
foreach (var entry in _entries)
{
yield return entry.Node;
if (entry.Separator is not null)
yield return entry.Separator;
}
}
public IEnumerable<SyntaxToken> GetSeparators()
{
return from e in _entries
where e.Separator is not null
select e.Separator;
}
public TNode this[int index]
{
get { return _entries[index].Node; }
}
public bool Contains(TNode item)
{
return IndexOf(item) >= 0;
}
public bool Contains(SyntaxToken separator)
{
return IndexOf(separator) >= 0;
}
public bool Contains(SyntaxNodeOrToken itemOrSeparator)
{
return IndexOf(itemOrSeparator) >= 0;
}
void ICollection<TNode>.Clear()
{
throw new NotSupportedException();
}
void ICollection<TNode>.Add(TNode item)
{
throw new NotSupportedException();
}
public int IndexOf(TNode item)
{
for (var i = 0; i < _entries.Length; i++)
{
if (_entries[i].Node == item)
return i;
}
return -1;
}
public int IndexOf(SyntaxToken separator)
{
for (var i = 0; i < _entries.Length; i++)
{
if (_entries[i].Separator == separator)
return i;
}
return -1;
}
public int IndexOf(SyntaxNodeOrToken itemOrSeparator)
{
if (itemOrSeparator.IsNode)
{
if (itemOrSeparator.AsNode() is not TNode node)
return -1;
return IndexOf(node);
}
return IndexOf(itemOrSeparator.AsToken());
}
void IList<TNode>.Insert(int index, TNode item)
{
throw new NotSupportedException();
}
void IList<TNode>.RemoveAt(int index)
{
throw new NotSupportedException();
}
bool ICollection<TNode>.Remove(TNode item)
{
throw new NotSupportedException();
}
bool ICollection<TNode>.IsReadOnly { get { return true; } }
void ICollection<TNode>.CopyTo(TNode[] array, int arrayIndex)
{
for (var i = 0; i < _entries.Length; i++)
array[arrayIndex + i] = _entries[i].Node;
}
TNode IList<TNode>.this[int index]
{
get { return this[index]; }
set { throw new NotSupportedException(); }
}
public int Count
{
get { return _entries.Length; }
}
private struct Entry
{
public Entry(TNode node, SyntaxToken separator)
{
Node = node;
Separator = separator;
}
public TNode Node { get; }
public SyntaxToken Separator { get; }
}
}
} | 1 | 0.883555 | 1 | 0.883555 | game-dev | MEDIA | 0.503152 | game-dev | 0.968345 | 1 | 0.968345 |
elonafoobar/elonafoobar | 2,167 | src/elona/shop.cpp | #include "shop.hpp"
#include "calc.hpp"
#include "character.hpp"
#include "config.hpp"
#include "data/types/type_item.hpp"
#include "food.hpp"
#include "game.hpp"
#include "inventory.hpp"
#include "item.hpp"
#include "itemgen.hpp"
#include "lua_env/interface.hpp"
#include "map.hpp"
#include "menu.hpp"
#include "random.hpp"
#include "skill.hpp"
#include "variables.hpp"
namespace elona
{
void shop_refresh_on_talk(Character& shopkeeper)
{
if (shopkeeper.role == Role::trader)
{
map_calc_trade_goods_price();
}
g_mode = 6;
bool is_temporary = false;
auto shop_inv =
lua::get_data("core.shop_inventory", static_cast<int>(shopkeeper.role));
if (shop_inv)
{
is_temporary = shop_inv->optional_or<bool>("is_temporary", false);
}
if (shopkeeper.shop_store_id == 0)
{
if (is_temporary)
{
shopkeeper.shop_store_id = 1;
}
else
{
++game()->next_inventory_serial_id;
shopkeeper.shop_store_id = game()->next_inventory_serial_id;
}
shop_refresh(shopkeeper);
}
else if (game_now() >= shopkeeper.shop_restock_time)
{
shop_refresh(shopkeeper);
}
else
{
inv_open_tmp_inv(fs::u8path("shop"s + invfile + ".s2"));
}
invfile = shopkeeper.shop_store_id;
shop_load_shoptmp();
}
void shop_load_shoptmp()
{
inv_close_tmp_inv(fs::u8path("shop"s + invfile + ".s2"));
g_mode = 0;
}
void shop_refresh(Character& shopkeeper)
{
inv_open_tmp_inv_no_physical_file();
lua::call("core.Impl.shop_inventory.generate", lua::handle(shopkeeper));
shopkeeper.shop_restock_time =
game_now() + time::Duration::from_days(g_config.restock_interval());
}
void shop_sell_item(optional_ref<Character> shopkeeper)
{
g_mode = 6;
inv_open_tmp_inv(fs::u8path("shop"s + invfile + ".s2"));
shoptrade = 0;
if (shopkeeper)
{
if (shopkeeper->role == Role::trader)
{
shoptrade = 1;
}
}
CtrlInventoryOptions opts;
opts.inventory_owner = shopkeeper;
ctrl_inventory(opts);
}
} // namespace elona
| 1 | 0.892925 | 1 | 0.892925 | game-dev | MEDIA | 0.743021 | game-dev | 0.84782 | 1 | 0.84782 |
localcc/PalworldModdingKit | 3,480 | Source/Pal/Private/PalBullet.cpp | #include "PalBullet.h"
#include "Components/SphereComponent.h"
#include "PalProjectileMovementComponent.h"
APalBullet::APalBullet(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) {
this->RootComponent = CreateDefaultSubobject<USphereComponent>(TEXT("SphereComp"));
this->CollisionComp = (USphereComponent*)RootComponent;
this->ProjectileMovement = CreateDefaultSubobject<UPalProjectileMovementComponent>(TEXT("ProjectileComp"));
this->PlayerDamageCameraShake = EPalPlayerDamageCameraShakeCategory::Gun_S;
this->bIsHitFriend = false;
this->WeaponDamage = 0;
this->PvPWeaponDamageRate = 1.00f;
this->isDamageable = true;
this->AISoundEmitable = true;
this->SneakAttackRate = 2.00f;
this->DeleteTime = -1.00f;
this->DamageDecayStartRate = -1.00f;
this->LifeTimer = 0.00f;
this->weaponBulletDamageReactionType = EPalDamageAnimationReactionType::Big;
this->bUsePool = false;
}
void APalBullet::SetWeaponDamage(int32 Damage) {
}
void APalBullet::SetSneakAttackRate(float Rate) {
}
void APalBullet::SetSkillEffectList(const TArray<FPalPassiveSkillEffect>& inList) {
}
void APalBullet::SetPvPWeaponDamageRate(float Rate) {
}
void APalBullet::SetOwnerStaticItemId(const FName& ItemId) {
}
void APalBullet::SetDeleteTime(float DeleteSecound, float DecayStartRate) {
}
void APalBullet::SetDamageable(bool damageable) {
}
bool APalBullet::SetBulletHoleDecal_Implementation(const FHitResult& Hit, float LifeSpan, float FadeTime, float fadeScreenSize) {
return false;
}
void APalBullet::RegisterIgnoreActor(AActor* Actor) {
}
void APalBullet::RegisterCannotHitAreaBox(UBoxComponent* BoxComp) {
}
void APalBullet::OnHitToPalEnemy_Implementation(UPrimitiveComponent* HitComp, APalCharacter* OtherCharacter, UPrimitiveComponent* OtherComp, const FHitResult& Hit) {
}
void APalBullet::OnHitToPalCharacter_Implementation(UPrimitiveComponent* HitComp, APalCharacter* OtherCharacter, UPrimitiveComponent* OtherComp, const FHitResult& Hit) {
}
void APalBullet::OnHitToActor_Implementation(UPrimitiveComponent* HitComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, const FHitResult& Hit) {
}
void APalBullet::OnHit_Implementation(UPrimitiveComponent* HitComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, const FHitResult& Hit) {
}
void APalBullet::OnDestroy_Implementation(UPrimitiveComponent* HitComp, AActor* OtherCharacter, UPrimitiveComponent* OtherComp, const FHitResult& Hit) {
}
void APalBullet::OnBlock_Implementation(UPrimitiveComponent* HitComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, FVector NormalImpulse, const FHitResult& Hit) {
}
void APalBullet::OnBeginOverlap(UPrimitiveComponent* HitComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& Hit) {
}
bool APalBullet::IsDestroy_Implementation(UPrimitiveComponent* HitComp, AActor* OtherCharacter, UPrimitiveComponent* OtherComp, const FHitResult& Hit) {
return false;
}
int32 APalBullet::GetWeaponDamage() const {
return 0;
}
float APalBullet::GetSneakAttackRate() {
return 0.0f;
}
float APalBullet::GetPvPWeaponDamageRate() const {
return 0.0f;
}
float APalBullet::GetParameterWithPassiveSkillEffect(float originalValue, EPalPassiveSkillEffectType EffectType) const {
return 0.0f;
}
FName APalBullet::GetOwnerStaticItemId() const {
return NAME_None;
}
float APalBullet::GetDecayDamageRate() {
return 0.0f;
}
| 1 | 0.877263 | 1 | 0.877263 | game-dev | MEDIA | 0.804478 | game-dev | 0.916211 | 1 | 0.916211 |
quiverteam/Engine | 18,639 | src/game/server/mapentities.cpp | //========= Copyright 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose: Controls the loading, parsing and creation of the entities from the BSP.
//
//=============================================================================//
#include "cbase.h"
#include "entitylist.h"
#include "mapentities_shared.h"
#include "soundent.h"
#include "TemplateEntities.h"
#include "point_template.h"
#include "ai_initutils.h"
#include "lights.h"
#include "mapentities.h"
#include "wcedit.h"
#include "stringregistry.h"
#include "datacache/imdlcache.h"
#include "world.h"
#include "toolframework/iserverenginetools.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
struct HierarchicalSpawnMapData_t
{
const char *m_pMapData;
int m_iMapDataLength;
};
static CStringRegistry *g_pClassnameSpawnPriority = NULL;
extern edict_t *g_pForceAttachEdict;
// creates an entity by string name, but does not spawn it
CBaseEntity *CreateEntityByName( const char *className, int iForceEdictIndex )
{
if ( iForceEdictIndex != -1 )
{
g_pForceAttachEdict = engine->CreateEdict( iForceEdictIndex );
if ( !g_pForceAttachEdict )
Error( "CreateEntityByName( %s, %d ) - CreateEdict failed.", className, iForceEdictIndex );
}
IServerNetworkable *pNetwork = EntityFactoryDictionary()->Create( className );
g_pForceAttachEdict = NULL;
if ( !pNetwork )
return NULL;
CBaseEntity *pEntity = pNetwork->GetBaseEntity();
Assert( pEntity );
return pEntity;
}
CBaseNetworkable *CreateNetworkableByName( const char *className )
{
IServerNetworkable *pNetwork = EntityFactoryDictionary()->Create( className );
if ( !pNetwork )
return NULL;
CBaseNetworkable *pNetworkable = pNetwork->GetBaseNetworkable();
Assert( pNetworkable );
return pNetworkable;
}
void FreeContainingEntity( edict_t *ed )
{
if ( ed )
{
CBaseEntity *ent = GetContainingEntity( ed );
if ( ent )
{
ed->SetEdict( NULL, false );
CBaseEntity::PhysicsRemoveTouchedList( ent );
CBaseEntity::PhysicsRemoveGroundList( ent );
UTIL_RemoveImmediate( ent );
}
}
}
// parent name may have a , in it to include an attachment point
string_t ExtractParentName(string_t parentName)
{
if ( !strchr(STRING(parentName), ',') )
return parentName;
char szToken[256];
nexttoken(szToken, STRING(parentName), ',');
return AllocPooledString(szToken);
}
//-----------------------------------------------------------------------------
// Purpose: Callback function for qsort, used to sort entities by their depth
// in the movement hierarchy.
// Input : pEnt1 -
// pEnt2 -
// Output : Returns -1, 0, or 1 per qsort spec.
//-----------------------------------------------------------------------------
static int __cdecl CompareSpawnOrder(HierarchicalSpawn_t *pEnt1, HierarchicalSpawn_t *pEnt2)
{
if (pEnt1->m_nDepth == pEnt2->m_nDepth)
{
if ( g_pClassnameSpawnPriority )
{
int o1 = pEnt1->m_pEntity ? g_pClassnameSpawnPriority->GetStringID( pEnt1->m_pEntity->GetClassname() ) : -1;
int o2 = pEnt2->m_pEntity ? g_pClassnameSpawnPriority->GetStringID( pEnt2->m_pEntity->GetClassname() ) : -1;
if ( o1 < o2 )
return 1;
if ( o2 < o1 )
return -1;
}
return 0;
}
if (pEnt1->m_nDepth > pEnt2->m_nDepth)
return 1;
return -1;
}
//-----------------------------------------------------------------------------
// Computes the hierarchical depth of the entities to spawn..
//-----------------------------------------------------------------------------
static int ComputeSpawnHierarchyDepth_r( CBaseEntity *pEntity )
{
if ( !pEntity )
return 1;
if (pEntity->m_iParent == NULL_STRING)
return 1;
CBaseEntity *pParent = gEntList.FindEntityByName( NULL, ExtractParentName(pEntity->m_iParent) );
if (!pParent)
return 1;
if (pParent == pEntity)
{
Warning( "LEVEL DESIGN ERROR: Entity %s is parented to itself!\n", pEntity->GetDebugName() );
return 1;
}
return 1 + ComputeSpawnHierarchyDepth_r( pParent );
}
static void ComputeSpawnHierarchyDepth( int nEntities, HierarchicalSpawn_t *pSpawnList )
{
// NOTE: This isn't particularly efficient, but so what? It's at the beginning of time
// I did it this way because it simplified the parent setting in hierarchy (basically
// eliminated questions about whether you should transform origin from global to local or not)
int nEntity;
for (nEntity = 0; nEntity < nEntities; nEntity++)
{
CBaseEntity *pEntity = pSpawnList[nEntity].m_pEntity;
if (pEntity && !pEntity->IsDormant())
{
pSpawnList[nEntity].m_nDepth = ComputeSpawnHierarchyDepth_r( pEntity );
}
else
{
pSpawnList[nEntity].m_nDepth = 1;
}
}
}
static void SortSpawnListByHierarchy( int nEntities, HierarchicalSpawn_t *pSpawnList )
{
MEM_ALLOC_CREDIT();
g_pClassnameSpawnPriority = new CStringRegistry;
// this will cause the entities to be spawned in the indicated order
// Highest string ID spawns first. String ID is spawn priority.
// by default, anything not in this list has priority -1
g_pClassnameSpawnPriority->AddString( "func_wall", 10 );
g_pClassnameSpawnPriority->AddString( "scripted_sequence", 9 );
g_pClassnameSpawnPriority->AddString( "phys_hinge", 8 );
g_pClassnameSpawnPriority->AddString( "phys_ballsocket", 8 );
g_pClassnameSpawnPriority->AddString( "phys_slideconstraint", 8 );
g_pClassnameSpawnPriority->AddString( "phys_constraint", 8 );
g_pClassnameSpawnPriority->AddString( "phys_pulleyconstraint", 8 );
g_pClassnameSpawnPriority->AddString( "phys_lengthconstraint", 8 );
g_pClassnameSpawnPriority->AddString( "phys_ragdollconstraint", 8 );
g_pClassnameSpawnPriority->AddString( "info_mass_center", 8 ); // spawn these before physbox/prop_physics
g_pClassnameSpawnPriority->AddString( "trigger_vphysics_motion", 8 ); // spawn these before physbox/prop_physics
g_pClassnameSpawnPriority->AddString( "prop_physics", 7 );
g_pClassnameSpawnPriority->AddString( "prop_ragdoll", 7 );
// Sort the entities (other than the world) by hierarchy depth, in order to spawn them in
// that order. This insures that each entity's parent spawns before it does so that
// it can properly set up anything that relies on hierarchy.
#ifdef _WIN32
qsort(&pSpawnList[0], nEntities, sizeof(pSpawnList[0]), (int (__cdecl *)(const void *, const void *))CompareSpawnOrder);
#elif _LINUX
qsort(&pSpawnList[0], nEntities, sizeof(pSpawnList[0]), (int (*)(const void *, const void *))CompareSpawnOrder);
#endif
delete g_pClassnameSpawnPriority;
g_pClassnameSpawnPriority = NULL;
}
void SetupParentsForSpawnList( int nEntities, HierarchicalSpawn_t *pSpawnList )
{
int nEntity;
for (nEntity = nEntities - 1; nEntity >= 0; nEntity--)
{
CBaseEntity *pEntity = pSpawnList[nEntity].m_pEntity;
if ( pEntity )
{
if ( strchr(STRING(pEntity->m_iParent), ',') )
{
char szToken[256];
const char *pAttachmentName = nexttoken(szToken, STRING(pEntity->m_iParent), ',');
pEntity->m_iParent = AllocPooledString(szToken);
CBaseEntity *pParent = gEntList.FindEntityByName( NULL, pEntity->m_iParent );
// setparent in the spawn pass instead - so the model will have been set & loaded
pSpawnList[nEntity].m_pDeferredParent = pParent;
pSpawnList[nEntity].m_pDeferredParentAttachment = pAttachmentName;
}
else
{
CBaseEntity *pParent = gEntList.FindEntityByName( NULL, pEntity->m_iParent );
if ((pParent != NULL) && (pParent->edict() != NULL))
{
pEntity->SetParent( pParent );
}
}
}
}
}
// this is a hook for edit mode
void RememberInitialEntityPositions( int nEntities, HierarchicalSpawn_t *pSpawnList )
{
for (int nEntity = 0; nEntity < nEntities; nEntity++)
{
CBaseEntity *pEntity = pSpawnList[nEntity].m_pEntity;
if ( pEntity )
{
NWCEdit::RememberEntityPosition( pEntity );
}
}
}
void SpawnAllEntities( int nEntities, HierarchicalSpawn_t *pSpawnList, bool bActivateEntities )
{
int nEntity;
for (nEntity = 0; nEntity < nEntities; nEntity++)
{
VPROF( "MapEntity_ParseAllEntities_Spawn");
CBaseEntity *pEntity = pSpawnList[nEntity].m_pEntity;
if ( pSpawnList[nEntity].m_pDeferredParent )
{
// UNDONE: Promote this up to the root of this function?
MDLCACHE_CRITICAL_SECTION();
CBaseEntity *pParent = pSpawnList[nEntity].m_pDeferredParent;
int iAttachment = -1;
CBaseAnimating *pAnim = pParent->GetBaseAnimating();
if ( pAnim )
{
iAttachment = pAnim->LookupAttachment(pSpawnList[nEntity].m_pDeferredParentAttachment);
}
pEntity->SetParent( pParent, iAttachment );
}
if ( pEntity )
{
if (DispatchSpawn(pEntity) < 0)
{
for ( int i = nEntity+1; i < nEntities; i++ )
{
// this is a child object that will be deleted now
if ( pSpawnList[i].m_pEntity && pSpawnList[i].m_pEntity->IsMarkedForDeletion() )
{
pSpawnList[i].m_pEntity = NULL;
}
}
// Spawn failed.
gEntList.CleanupDeleteList();
// Remove the entity from the spawn list
pSpawnList[nEntity].m_pEntity = NULL;
}
}
}
if ( bActivateEntities )
{
VPROF( "MapEntity_ParseAllEntities_Activate");
bool bAsyncAnims = mdlcache->SetAsyncLoad( MDLCACHE_ANIMBLOCK, false );
for (nEntity = 0; nEntity < nEntities; nEntity++)
{
CBaseEntity *pEntity = pSpawnList[nEntity].m_pEntity;
if ( pEntity )
{
MDLCACHE_CRITICAL_SECTION();
pEntity->Activate();
}
}
mdlcache->SetAsyncLoad( MDLCACHE_ANIMBLOCK, bAsyncAnims );
}
}
//-----------------------------------------------------------------------------
// Purpose: Only called on BSP load. Parses and spawns all the entities in the BSP.
// Input : pMapData - Pointer to the entity data block to parse.
//-----------------------------------------------------------------------------
void MapEntity_ParseAllEntities(const char *pMapData, IMapEntityFilter *pFilter, bool bActivateEntities)
{
VPROF("MapEntity_ParseAllEntities");
HierarchicalSpawnMapData_t *pSpawnMapData = new HierarchicalSpawnMapData_t[NUM_ENT_ENTRIES];
HierarchicalSpawn_t *pSpawnList = new HierarchicalSpawn_t[NUM_ENT_ENTRIES];
CUtlVector< CPointTemplate* > pPointTemplates;
int nEntities = 0;
char szTokenBuffer[MAPKEY_MAXLENGTH];
// Allow the tools to spawn different things
if ( serverenginetools )
{
pMapData = serverenginetools->GetEntityData( pMapData );
}
// Loop through all entities in the map data, creating each.
for ( ; true; pMapData = MapEntity_SkipToNextEntity(pMapData, szTokenBuffer) )
{
//
// Parse the opening brace.
//
char token[MAPKEY_MAXLENGTH];
pMapData = MapEntity_ParseToken( pMapData, token );
//
// Check to see if we've finished or not.
//
if (!pMapData)
break;
if (token[0] != '{')
{
Error( "MapEntity_ParseAllEntities: found %s when expecting {", token);
continue;
}
//
// Parse the entity and add it to the spawn list.
//
CBaseEntity *pEntity;
const char *pCurMapData = pMapData;
pMapData = MapEntity_ParseEntity(pEntity, pMapData, pFilter);
if (pEntity == NULL)
continue;
if (pEntity->IsTemplate())
{
// It's a template entity. Squirrel away its keyvalue text so that we can
// recreate the entity later via a spawner. pMapData points at the '}'
// so we must add one to include it in the string.
Templates_Add(pEntity, pCurMapData, (pMapData - pCurMapData) + 2);
// Remove the template entity so that it does not show up in FindEntityXXX searches.
UTIL_Remove(pEntity);
gEntList.CleanupDeleteList();
continue;
}
// To
if ( dynamic_cast<CWorld*>( pEntity ) )
{
VPROF( "MapEntity_ParseAllEntities_SpawnWorld");
pEntity->m_iParent = NULL_STRING; // don't allow a parent on the first entity (worldspawn)
DispatchSpawn(pEntity);
continue;
}
CNodeEnt *pNode = dynamic_cast<CNodeEnt*>(pEntity);
if ( pNode )
{
VPROF( "MapEntity_ParseAllEntities_SpawnTransients");
// We overflow the max edicts on large maps that have lots of entities.
// Nodes & Lights remove themselves immediately on Spawn(), so dispatch their
// spawn now, to free up the slot inside this loop.
// NOTE: This solution prevents nodes & lights from being used inside point_templates.
//
// NOTE: Nodes spawn other entities (ai_hint) if they need to have a persistent presence.
// To ensure keys are copied over into the new entity, we pass the mapdata into the
// node spawn function.
if ( pNode->Spawn( pCurMapData ) < 0 )
{
gEntList.CleanupDeleteList();
}
continue;
}
if ( dynamic_cast<CLight*>(pEntity) )
{
VPROF( "MapEntity_ParseAllEntities_SpawnTransients");
// We overflow the max edicts on large maps that have lots of entities.
// Nodes & Lights remove themselves immediately on Spawn(), so dispatch their
// spawn now, to free up the slot inside this loop.
// NOTE: This solution prevents nodes & lights from being used inside point_templates.
if (DispatchSpawn(pEntity) < 0)
{
gEntList.CleanupDeleteList();
}
continue;
}
// Build a list of all point_template's so we can spawn them before everything else
CPointTemplate *pTemplate = dynamic_cast< CPointTemplate* >(pEntity);
if ( pTemplate )
{
pPointTemplates.AddToTail( pTemplate );
}
else
{
// Queue up this entity for spawning
pSpawnList[nEntities].m_pEntity = pEntity;
pSpawnList[nEntities].m_nDepth = 0;
pSpawnList[nEntities].m_pDeferredParentAttachment = NULL;
pSpawnList[nEntities].m_pDeferredParent = NULL;
pSpawnMapData[nEntities].m_pMapData = pCurMapData;
pSpawnMapData[nEntities].m_iMapDataLength = (pMapData - pCurMapData) + 2;
nEntities++;
}
}
// Now loop through all our point_template entities and tell them to make templates of everything they're pointing to
int iTemplates = pPointTemplates.Count();
for ( int i = 0; i < iTemplates; i++ )
{
VPROF( "MapEntity_ParseAllEntities_SpawnTemplates");
CPointTemplate *pPointTemplate = pPointTemplates[i];
// First, tell the Point template to Spawn
if ( DispatchSpawn(pPointTemplate) < 0 )
{
UTIL_Remove(pPointTemplate);
gEntList.CleanupDeleteList();
continue;
}
pPointTemplate->StartBuildingTemplates();
// Now go through all it's templates and turn the entities into templates
int iNumTemplates = pPointTemplate->GetNumTemplateEntities();
for ( int iTemplateNum = 0; iTemplateNum < iNumTemplates; iTemplateNum++ )
{
// Find it in the spawn list
CBaseEntity *pEntity = pPointTemplate->GetTemplateEntity( iTemplateNum );
for ( int iEntNum = 0; iEntNum < nEntities; iEntNum++ )
{
if ( pSpawnList[iEntNum].m_pEntity == pEntity )
{
// Give the point_template the mapdata
pPointTemplate->AddTemplate( pEntity, pSpawnMapData[iEntNum].m_pMapData, pSpawnMapData[iEntNum].m_iMapDataLength );
if ( pPointTemplate->ShouldRemoveTemplateEntities() )
{
// Remove the template entity so that it does not show up in FindEntityXXX searches.
UTIL_Remove(pEntity);
gEntList.CleanupDeleteList();
// Remove the entity from the spawn list
pSpawnList[iEntNum].m_pEntity = NULL;
}
break;
}
}
}
pPointTemplate->FinishBuildingTemplates();
}
SpawnHierarchicalList( nEntities, pSpawnList, bActivateEntities );
delete [] pSpawnMapData;
delete [] pSpawnList;
}
void SpawnHierarchicalList( int nEntities, HierarchicalSpawn_t *pSpawnList, bool bActivateEntities )
{
// Compute the hierarchical depth of all entities hierarchically attached
ComputeSpawnHierarchyDepth( nEntities, pSpawnList );
// Sort the entities (other than the world) by hierarchy depth, in order to spawn them in
// that order. This insures that each entity's parent spawns before it does so that
// it can properly set up anything that relies on hierarchy.
SortSpawnListByHierarchy( nEntities, pSpawnList );
// save off entity positions if in edit mode
if ( engine->IsInEditMode() )
{
RememberInitialEntityPositions( nEntities, pSpawnList );
}
// Set up entity movement hierarchy in reverse hierarchy depth order. This allows each entity
// to use its parent's world spawn origin to calculate its local origin.
SetupParentsForSpawnList( nEntities, pSpawnList );
// Spawn all the entities in hierarchy depth order so that parents spawn before their children.
SpawnAllEntities( nEntities, pSpawnList, bActivateEntities );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *pEntData -
//-----------------------------------------------------------------------------
void MapEntity_PrecacheEntity( const char *pEntData, int &nStringSize )
{
CEntityMapData entData( (char*)pEntData, nStringSize );
char className[MAPKEY_MAXLENGTH];
if (!entData.ExtractValue("classname", className))
{
Error( "classname missing from entity!\n" );
}
// Construct via the LINK_ENTITY_TO_CLASS factory.
CBaseEntity *pEntity = CreateEntityByName(className);
//
// Set up keyvalues, which can set the model name, which is why we don't just do UTIL_PrecacheOther here...
//
if ( pEntity != NULL )
{
pEntity->ParseMapData(&entData);
pEntity->Precache();
UTIL_RemoveImmediate( pEntity );
}
}
//-----------------------------------------------------------------------------
// Purpose: Takes a block of character data as the input
// Input : pEntity - Receives the newly constructed entity, NULL on failure.
// pEntData - Data block to parse to extract entity keys.
// Output : Returns the current position in the entity data block.
//-----------------------------------------------------------------------------
const char *MapEntity_ParseEntity(CBaseEntity *&pEntity, const char *pEntData, IMapEntityFilter *pFilter)
{
CEntityMapData entData( (char*)pEntData );
char className[MAPKEY_MAXLENGTH];
if (!entData.ExtractValue("classname", className))
{
Error( "classname missing from entity!\n" );
}
pEntity = NULL;
if ( !pFilter || pFilter->ShouldCreateEntity( className ) )
{
//
// Construct via the LINK_ENTITY_TO_CLASS factory.
//
if ( pFilter )
pEntity = pFilter->CreateNextEntity( className );
else
pEntity = CreateEntityByName(className);
//
// Set up keyvalues.
//
if (pEntity != NULL)
{
pEntity->ParseMapData(&entData);
}
else
{
Warning("Can't init %s\n", className);
}
}
else
{
// Just skip past all the keys.
char keyName[MAPKEY_MAXLENGTH];
char value[MAPKEY_MAXLENGTH];
if ( entData.GetFirstKey(keyName, value) )
{
do
{
}
while ( entData.GetNextKey(keyName, value) );
}
}
//
// Return the current parser position in the data block
//
return entData.CurrentBufferPosition();
}
| 1 | 0.965622 | 1 | 0.965622 | game-dev | MEDIA | 0.845018 | game-dev | 0.972732 | 1 | 0.972732 |
WCell/WCell | 5,834 | Services/WCell.RealmServer/Groups/GroupMember.cs | /*************************************************************************
*
* file : GroupMember.cs
* copyright : (C) The WCell Team
* email : info@wcell.org
* last changed : $LastChangedDate: 2010-01-23 20:40:40 +0100 (lø, 23 jan 2010) $
* revision : $Rev: 1211 $
*
* 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.
*
*************************************************************************/
using System;
using WCell.Constants;
using WCell.Core;
using WCell.RealmServer.Entities;
using WCell.RealmServer.Global;
using WCell.Util;
using WCell.Util.Graphics;
namespace WCell.RealmServer.Groups
{
/// <summary>
/// Represents the relationship between a Character and its Group/SubGroup.
/// GroupMembers are also a singly linked list where the head is the person who joined first and the tail is the person who joined last.
/// </summary>
public class GroupMember : INamed
{
private uint m_lowId;
private string m_characterName;
protected internal SubGroup m_subGroup;
protected internal GroupMember m_nextMember;
Character m_chr;
/// <summary>
/// Is set when player logs out
/// </summary>
Vector3 m_lastPos;
/// <summary>
/// Is set when player logs out
/// </summary>
Map m_Map;
#region Constructors
public GroupMember(Character character, GroupMemberFlags flags)
{
m_lowId = character.EntityId.Low;
m_characterName = character.Name;
Flags = flags;
Character = character;
}
#endregion
#region Properties
/// <summary>
/// The low part of the Character's EntityId. Use EntityId.GetPlayerId(Id) to get a full EntityId
/// </summary>
public uint Id
{
get { return m_lowId; }
}
/// <summary>
/// The name of this GroupMember
/// </summary>
public string Name
{
get { return m_characterName; }
}
/// <summary>
/// The SubGroup of this Member (not null)
/// </summary>
public SubGroup SubGroup
{
get { return m_subGroup; }
internal set { m_subGroup = value; }
}
/// <summary>
/// The Group of this Member (not null)
/// </summary>
public Group Group
{
get { return m_subGroup.Group; }
}
public GroupMemberFlags Flags
{
get;
internal set;
}
/// <summary>
/// Returns the Character or null, if this member is offline
/// </summary>
public Character Character
{
get { return m_chr; }
internal set { m_chr = value; }
}
public bool IsOnline
{
get { return m_chr != null; }
}
/// <summary>
/// The current or last Map in which this GroupMember was
/// </summary>
public Map Map
{
get
{
if (m_chr != null)
{
return m_chr.Map;
}
return m_Map;
}
internal set
{
m_Map = value;
}
}
/// <summary>
/// The current position of this GroupMember or the last position if member already logged out
/// </summary>
public Vector3 Position
{
get
{
if (m_chr != null)
{
return m_chr.Position;
}
return m_lastPos;
}
internal set
{
m_lastPos = value;
}
}
/// <summary>
/// The GroupMember who joined after this GroupMember
/// </summary>
public GroupMember Next
{
get { return m_nextMember; }
internal set { m_nextMember = value; }
}
/// <summary>
/// Whether this member is the leader of the Group
/// </summary>
public bool IsLeader
{
get { return m_subGroup.Group.Leader == this; }
}
/// <summary>
/// Whether this member is the MasterLooter of the Group
/// </summary>
public bool IsMasterLooter
{
get { return m_subGroup.Group.MasterLooter == this; }
}
/// <summary>
/// Whether this member is an Assistant
/// </summary>
public bool IsAssistant
{
get
{
return Flags.HasFlag(GroupMemberFlags.Assistant);
}
set
{
if (value)
{
Flags |= GroupMemberFlags.Assistant;
}
else
{
Flags &= ~GroupMemberFlags.Assistant;
}
}
}
/// <summary>
/// Whether this member is the Leader, MainAssistant or Assistant
/// </summary>
public bool IsAtLeastAssistant
{
get
{
return IsLeader || Flags.HasAnyFlag(GroupMemberFlags.Assistant | GroupMemberFlags.MainAssistant);
}
}
/// <summary>
/// Whether this member is a MainAssistant
/// </summary>
public bool IsMainAssistant
{
get
{
return Flags.HasAnyFlag(GroupMemberFlags.MainAssistant);
}
}
/// <summary>
/// Whether this member is the MainTank
/// </summary>
public bool IsMainTank
{
get
{
return Flags.HasAnyFlag(GroupMemberFlags.MainTank);
}
}
/// <summary>
/// Whether this member is MainAssistant or leader
/// </summary>
public bool IsAtLeastMainAssistant
{
get
{
return IsLeader || Flags.HasAnyFlag(GroupMemberFlags.MainAssistant);
}
}
#endregion
public void WriteIdPacked(RealmPacketOut packet)
{
new EntityId(Id, HighId.Player).WritePacked(packet);
}
/// <summary>
/// Lets this Member leave the group.
/// </summary>
public void LeaveGroup()
{
if (m_subGroup != null)
{
m_subGroup.Group.RemoveMember(this);
}
}
/// <summary>
/// Calls the given handler over all members of the same Group within the given radius
/// </summary>
public void IterateMembersInRange(float radius, Action<GroupMember> handler)
{
foreach (var member in Group)
{
var sqDistance = Position.DistanceSquared(member.Position);
if (member == this || member.Map == Map && Utility.IsInRange(sqDistance, radius))
{
handler(member);
}
}
}
public override string ToString()
{
return "GroupMember: " + Name;
}
}
} | 1 | 0.885401 | 1 | 0.885401 | game-dev | MEDIA | 0.545373 | game-dev | 0.851499 | 1 | 0.851499 |
Return-To-The-Roots/s25client | 1,852 | libs/s25main/figures/nofWarehouseWorker.h | // Copyright (C) 2005 - 2024 Settlers Freaks (sf-team at siedler25.org)
//
// SPDX-License-Identifier: GPL-2.0-or-later
#pragma once
#include "figures/noFigure.h"
#include <memory>
class Ware;
class SerializedGameData;
/// Der "Warehouse-Worker" ist ein einfacher(er) Träger, der die Waren aus dem Lagerhaus holt
class nofWarehouseWorker : public noFigure
{
// Mein Lagerhaus, in dem ich arbeite, darf auch mal ein bisschen was an mir ändern
friend class nobBaseWarehouse;
private:
/// Ware currently being carried or nullptr
std::unique_ptr<Ware> carried_ware;
// Aufgabe, die der Warenhaustyp hat (Ware raustragen (0) oder reinholen)
const bool shouldBringWareIn;
// Bin ich fett? (werde immer mal dünn oder fett, damits nicht immer gleich aussieht, wenn jemand rauskommt)
bool fat;
void GoalReached() override;
void Walked() override;
/// wenn man beim Arbeitsplatz "kündigen" soll, man das Laufen zum Ziel unterbrechen muss (warum auch immer)
void AbrogateWorkplace() override;
void LooseWare();
void HandleDerivedEvent(unsigned id) override;
public:
nofWarehouseWorker(MapPoint pos, unsigned char player, std::unique_ptr<Ware> ware, bool task);
nofWarehouseWorker(SerializedGameData& sgd, unsigned obj_id);
nofWarehouseWorker(const nofWarehouseWorker&) = delete;
~nofWarehouseWorker() override;
void Destroy() override;
void Serialize(SerializedGameData& sgd) const override;
GO_Type GetGOT() const final { return GO_Type::NofWarehouseworker; }
void Draw(DrawPoint drawPt) override;
// Ware nach draußen bringen (von Lagerhaus aus aufgerufen)
void CarryWare(Ware* ware);
/// Mitglied von nem Lagerhaus(Lagerhausarbeiter, die die Träger-Bestände nicht beeinflussen?)
bool MemberOfWarehouse() const override { return true; }
};
| 1 | 0.85832 | 1 | 0.85832 | game-dev | MEDIA | 0.850347 | game-dev | 0.872504 | 1 | 0.872504 |
AhmedVargos/Valorant-Agents | 18,142 | features/favorites/src/test/java/com/ahmedvargos/favorites/utils/AgentTestHelper.kt | package com.ahmedvargos.favorites.utils
import com.ahmedvargos.base.data.AgentInfo
import com.ahmedvargos.base.data.DataSource
import com.ahmedvargos.base.data.FailureData
import com.ahmedvargos.base.data.Resource
import com.ahmedvargos.local.entities.AgentEntity
import com.squareup.moshi.Moshi
import com.squareup.moshi.Types
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOf
fun createTempEmissionsFlow(isSuccess: Boolean = true): Flow<Resource<List<AgentInfo>>> {
return flowOf(
if (isSuccess)
Resource.Success(createTempAgentList(), DataSource.CACHE)
else
Resource.Failure(createTempFailureData())
)
}
fun createListOfAgentEntities(): List<AgentEntity> {
return createTempAgentList().map { agent ->
AgentEntity(id = agent.uuid, isFav = agent.isFav, data = agent)
}
}
fun createTempAgentList(): List<AgentInfo> {
val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
val typeCustom = Types.newParameterizedType(List::class.java, AgentInfo::class.java)
val agentsList = moshi.adapter<List<AgentInfo>>(typeCustom).fromJson(agentsTempJson)
return agentsList ?: mutableListOf()
}
fun createTempBoolEmissionsFlow(isSuccess: Boolean): Flow<Resource<Boolean>> {
return flow {
emit(
if (isSuccess)
Resource.Success(true, DataSource.CACHE)
else
Resource.Failure(createTempFailureData())
)
}
}
fun createTempFailureData() = FailureData(999, "Generic error")
/* ktlint-disable max-line-length */
val agentsTempJson = " [\n" +
" {\n" +
" \"uuid\": \"5f8d3a7f-467b-97f3-062c-13acf203c006\",\n" +
" \"displayName\": \"Breach\",\n" +
" \"description\": \"The bionic Swede Breach fires powerful, targeted kinetic blasts to aggressively clear a path through enemy ground. The damage and disruption he inflicts ensures no fight is ever fair.\",\n" +
" \"developerName\": \"Breach\",\n" +
" \"characterTags\": null,\n" +
" \"displayIcon\": \"https://media.valorant-api.com/agents/5f8d3a7f-467b-97f3-062c-13acf203c006/displayicon.png\",\n" +
" \"displayIconSmall\": \"https://media.valorant-api.com/agents/5f8d3a7f-467b-97f3-062c-13acf203c006/displayiconsmall.png\",\n" +
" \"bustPortrait\": \"https://media.valorant-api.com/agents/5f8d3a7f-467b-97f3-062c-13acf203c006/bustportrait.png\",\n" +
" \"fullPortrait\": \"https://media.valorant-api.com/agents/5f8d3a7f-467b-97f3-062c-13acf203c006/fullportrait.png\",\n" +
" \"assetPath\": \"ShooterGame/Content/Characters/Breach/Breach_PrimaryAsset\",\n" +
" \"isFullPortraitRightFacing\": false,\n" +
" \"isPlayableCharacter\": true,\n" +
" \"isAvailableForTest\": true,\n" +
" \"role\": {\n" +
" \"uuid\": \"1b47567f-8f7b-444b-aae3-b0c634622d10\",\n" +
" \"displayName\": \"Initiator\",\n" +
" \"description\": \"Initiators challenge angles by setting up their team to enter contested ground and push defenders away.\",\n" +
" \"displayIcon\": \"https://media.valorant-api.com/agents/roles/1b47567f-8f7b-444b-aae3-b0c634622d10/displayicon.png\",\n" +
" \"assetPath\": \"ShooterGame/Content/Characters/_Core/Roles/Breaker_PrimaryDataAsset\"\n" +
" },\n" +
" \"abilities\": [\n" +
" {\n" +
" \"slot\": \"Ability1\",\n" +
" \"displayName\": \"Flashpoint\",\n" +
" \"description\": \"EQUIP a blinding charge. FIRE the charge to set a fast-acting burst through the wall. The charge detonates to blind all players looking at it.\",\n" +
" \"displayIcon\": \"https://media.valorant-api.com/agents/5f8d3a7f-467b-97f3-062c-13acf203c006/abilities/ability1/displayicon.png\"\n" +
" },\n" +
" {\n" +
" \"slot\": \"Ability2\",\n" +
" \"displayName\": \"Fault Line\",\n" +
" \"description\": \"EQUIP a seismic blast. HOLD FIRE to increase the distance. RELEASE to set off the quake, dazing all players in its zone and in a line up to the zone.\",\n" +
" \"displayIcon\": \"https://media.valorant-api.com/agents/5f8d3a7f-467b-97f3-062c-13acf203c006/abilities/ability2/displayicon.png\"\n" +
" },\n" +
" {\n" +
" \"slot\": \"Grenade\",\n" +
" \"displayName\": \"Aftershock\",\n" +
" \"description\": \"EQUIP a fusion charge. FIRE the charge to set a slow-acting burst through the wall. The burst does heavy damage to anyone caught in its area.\",\n" +
" \"displayIcon\": \"https://media.valorant-api.com/agents/5f8d3a7f-467b-97f3-062c-13acf203c006/abilities/grenade/displayicon.png\"\n" +
" },\n" +
" {\n" +
" \"slot\": \"Ultimate\",\n" +
" \"displayName\": \"Rolling Thunder\",\n" +
" \"description\": \"EQUIP a Seismic Charge. FIRE to send a cascading quake through all terrain in a large cone. The quake dazes and knocks up anyone caught in it.\",\n" +
" \"displayIcon\": \"https://media.valorant-api.com/agents/5f8d3a7f-467b-97f3-062c-13acf203c006/abilities/ultimate/displayicon.png\"\n" +
" }\n" +
" ]\n" +
" },\n" +
" {\n" +
" \"uuid\": \"f94c3b30-42be-e959-889c-5aa313dba261\",\n" +
" \"displayName\": \"Raze\",\n" +
" \"description\": \"Raze explodes out of Brazil with her big personality and big guns. With her blunt-force-trauma playstyle, she excels at flushing entrenched enemies and clearing tight spaces with a generous dose of \\\"boom\\\".\",\n" +
" \"developerName\": \"Clay\",\n" +
" \"characterTags\": [\n" +
" \"Area Damage Specialist\"\n" +
" ],\n" +
" \"displayIcon\": \"https://media.valorant-api.com/agents/f94c3b30-42be-e959-889c-5aa313dba261/displayicon.png\",\n" +
" \"displayIconSmall\": \"https://media.valorant-api.com/agents/f94c3b30-42be-e959-889c-5aa313dba261/displayiconsmall.png\",\n" +
" \"bustPortrait\": \"https://media.valorant-api.com/agents/f94c3b30-42be-e959-889c-5aa313dba261/bustportrait.png\",\n" +
" \"fullPortrait\": \"https://media.valorant-api.com/agents/f94c3b30-42be-e959-889c-5aa313dba261/fullportrait.png\",\n" +
" \"assetPath\": \"ShooterGame/Content/Characters/Clay/Clay_PrimaryAsset\",\n" +
" \"isFullPortraitRightFacing\": true,\n" +
" \"isPlayableCharacter\": true,\n" +
" \"isAvailableForTest\": true,\n" +
" \"role\": {\n" +
" \"uuid\": \"dbe8757e-9e92-4ed4-b39f-9dfc589691d4\",\n" +
" \"displayName\": \"Duelist\",\n" +
" \"description\": \"Duelists are self-sufficient fraggers who their team expects, through abilities and skills, to get high frags and seek out engagements first.\",\n" +
" \"displayIcon\": \"https://media.valorant-api.com/agents/roles/dbe8757e-9e92-4ed4-b39f-9dfc589691d4/displayicon.png\",\n" +
" \"assetPath\": \"ShooterGame/Content/Characters/_Core/Roles/Assault_PrimaryDataAsset\"\n" +
" },\n" +
" \"abilities\": [\n" +
" {\n" +
" \"slot\": \"Ability1\",\n" +
" \"displayName\": \"Blast Pack\",\n" +
" \"description\": \"INSTANTLY throw a Blast Pack that will stick to surfaces. RE-USE the ability after deployment to detonate, damaging and moving anything hit.\",\n" +
" \"displayIcon\": \"https://media.valorant-api.com/agents/f94c3b30-42be-e959-889c-5aa313dba261/abilities/ability1/displayicon.png\"\n" +
" },\n" +
" {\n" +
" \"slot\": \"Ability2\",\n" +
" \"displayName\": \"Paint Shells\",\n" +
" \"description\": \"EQUIP a cluster grenade. FIRE to throw the grenade, which does damage and creates sub-munitions, each doing damage to anyone in their range.\",\n" +
" \"displayIcon\": \"https://media.valorant-api.com/agents/f94c3b30-42be-e959-889c-5aa313dba261/abilities/ability2/displayicon.png\"\n" +
" },\n" +
" {\n" +
" \"slot\": \"Grenade\",\n" +
" \"displayName\": \"Boom Bot\",\n" +
" \"description\": \"EQUIP a Boom Bot. FIRE will deploy the bot, causing it to travel in a straight line on the ground, bouncing off walls. The Boom Bot will lock on to any enemies in its frontal cone and chase them, exploding for heavy damage if it reaches them.\",\n" +
" \"displayIcon\": \"https://media.valorant-api.com/agents/f94c3b30-42be-e959-889c-5aa313dba261/abilities/grenade/displayicon.png\"\n" +
" },\n" +
" {\n" +
" \"slot\": \"Ultimate\",\n" +
" \"displayName\": \"Showstopper\",\n" +
" \"description\": \"EQUIP a rocket launcher. FIRE shoots a rocket that does massive area damage on contact with anything.\",\n" +
" \"displayIcon\": \"https://media.valorant-api.com/agents/f94c3b30-42be-e959-889c-5aa313dba261/abilities/ultimate/displayicon.png\"\n" +
" }\n" +
" ]\n" +
" },\n" +
" {\n" +
" \"uuid\": \"6f2a04ca-43e0-be17-7f36-b3908627744d\",\n" +
" \"displayName\": \"Skye\",\n" +
" \"description\": \"Hailing from Australia, Skye and her band of beasts trailblaze the way through hostile territory. With her creations hampering the enemy, and her power to heal others, the team is strongest and safest by Skye's side.\",\n" +
" \"developerName\": \"Guide\",\n" +
" \"characterTags\": null,\n" +
" \"displayIcon\": \"https://media.valorant-api.com/agents/6f2a04ca-43e0-be17-7f36-b3908627744d/displayicon.png\",\n" +
" \"displayIconSmall\": \"https://media.valorant-api.com/agents/6f2a04ca-43e0-be17-7f36-b3908627744d/displayiconsmall.png\",\n" +
" \"bustPortrait\": \"https://media.valorant-api.com/agents/6f2a04ca-43e0-be17-7f36-b3908627744d/bustportrait.png\",\n" +
" \"fullPortrait\": \"https://media.valorant-api.com/agents/6f2a04ca-43e0-be17-7f36-b3908627744d/fullportrait.png\",\n" +
" \"assetPath\": \"ShooterGame/Content/Characters/Guide/Guide_PrimaryAsset\",\n" +
" \"isFullPortraitRightFacing\": false,\n" +
" \"isPlayableCharacter\": true,\n" +
" \"isAvailableForTest\": true,\n" +
" \"role\": {\n" +
" \"uuid\": \"1b47567f-8f7b-444b-aae3-b0c634622d10\",\n" +
" \"displayName\": \"Initiator\",\n" +
" \"description\": \"Initiators challenge angles by setting up their team to enter contested ground and push defenders away.\",\n" +
" \"displayIcon\": \"https://media.valorant-api.com/agents/roles/1b47567f-8f7b-444b-aae3-b0c634622d10/displayicon.png\",\n" +
" \"assetPath\": \"ShooterGame/Content/Characters/_Core/Roles/Breaker_PrimaryDataAsset\"\n" +
" },\n" +
" \"abilities\": [\n" +
" {\n" +
" \"slot\": \"Ability1\",\n" +
" \"displayName\": \"Trailblazer\",\n" +
" \"description\": \"EQUIP a Tasmanian tiger trinket. FIRE to send out and take control of the predator. While in control, FIRE to leap forward, exploding in a concussive blast and damaging directly hit enemies.\",\n" +
" \"displayIcon\": \"https://media.valorant-api.com/agents/6f2a04ca-43e0-be17-7f36-b3908627744d/abilities/ability1/displayicon.png\"\n" +
" },\n" +
" {\n" +
" \"slot\": \"Ability2\",\n" +
" \"displayName\": \"Guiding Light\",\n" +
" \"description\": \"EQUIP a hawk trinket. FIRE to send it forward. HOLD FIRE to guide the hawk in the direction of your crosshair. RE-USE while the hawk is in flight to transform it into a flash.\",\n" +
" \"displayIcon\": \"https://media.valorant-api.com/agents/6f2a04ca-43e0-be17-7f36-b3908627744d/abilities/ability2/displayicon.png\"\n" +
" },\n" +
" {\n" +
" \"slot\": \"Grenade\",\n" +
" \"displayName\": \"Regrowth\",\n" +
" \"description\": \"EQUIP a healing trinket. HOLD FIRE to channel, healing allies in range and line of sight. Can be reused until her healing pool is depleted. Skye cannot heal herself.\",\n" +
" \"displayIcon\": \"https://media.valorant-api.com/agents/6f2a04ca-43e0-be17-7f36-b3908627744d/abilities/grenade/displayicon.png\"\n" +
" },\n" +
" {\n" +
" \"slot\": \"Ultimate\",\n" +
" \"displayName\": \"Seekers\",\n" +
" \"description\": \"EQUIP a Seeker trinket. FIRE to send out three Seekers to track down the three closest enemies. If a Seeker reaches its target, it nearsights them.\",\n" +
" \"displayIcon\": \"https://media.valorant-api.com/agents/6f2a04ca-43e0-be17-7f36-b3908627744d/abilities/ultimate/displayicon.png\"\n" +
" }\n" +
" ]\n" +
" },\n" +
" {\n" +
" \"uuid\": \"117ed9e3-49f3-6512-3ccf-0cada7e3823b\",\n" +
" \"displayName\": \"Cypher\",\n" +
" \"description\": \"The Moroccan information broker, Cypher is a one-man surveillance network who keeps tabs on the enemy's every move. No secret is safe. No maneuver goes unseen. Cypher is always watching.\",\n" +
" \"developerName\": \"Gumshoe\",\n" +
" \"characterTags\": [\n" +
" \"Detection\",\n" +
" \"Defensive Lockdown\"\n" +
" ],\n" +
" \"displayIcon\": \"https://media.valorant-api.com/agents/117ed9e3-49f3-6512-3ccf-0cada7e3823b/displayicon.png\",\n" +
" \"displayIconSmall\": \"https://media.valorant-api.com/agents/117ed9e3-49f3-6512-3ccf-0cada7e3823b/displayiconsmall.png\",\n" +
" \"bustPortrait\": \"https://media.valorant-api.com/agents/117ed9e3-49f3-6512-3ccf-0cada7e3823b/bustportrait.png\",\n" +
" \"fullPortrait\": \"https://media.valorant-api.com/agents/117ed9e3-49f3-6512-3ccf-0cada7e3823b/fullportrait.png\",\n" +
" \"assetPath\": \"ShooterGame/Content/Characters/Gumshoe/Gumshoe_PrimaryAsset\",\n" +
" \"isFullPortraitRightFacing\": true,\n" +
" \"isPlayableCharacter\": true,\n" +
" \"isAvailableForTest\": true,\n" +
" \"role\": {\n" +
" \"uuid\": \"5fc02f99-4091-4486-a531-98459a3e95e9\",\n" +
" \"displayName\": \"Sentinel\",\n" +
" \"description\": \"Sentinels are defensive experts who can lock down areas and watch flanks, both on attacker and defender rounds.\",\n" +
" \"displayIcon\": \"https://media.valorant-api.com/agents/roles/5fc02f99-4091-4486-a531-98459a3e95e9/displayicon.png\",\n" +
" \"assetPath\": \"ShooterGame/Content/Characters/_Core/Roles/Sentinel_PrimaryDataAsset\"\n" +
" },\n" +
" \"abilities\": [\n" +
" {\n" +
" \"slot\": \"Ability1\",\n" +
" \"displayName\": \"Cyber Cage\",\n" +
" \"description\": \"INSTANTLY toss the cyber cage in front of Cypher. ACTIVATE to create a zone that blocks vision and plays an audio cue when enemies pass through it\",\n" +
" \"displayIcon\": \"https://media.valorant-api.com/agents/117ed9e3-49f3-6512-3ccf-0cada7e3823b/abilities/ability1/displayicon.png\"\n" +
" },\n" +
" {\n" +
" \"slot\": \"Ability2\",\n" +
" \"displayName\": \"Spycam\",\n" +
" \"description\": \"EQUIP a spycam. FIRE to place the spycam at the targeted location. RE-USE this ability to take control of the camera's view. While in control of the camera, FIRE to shoot a marking dart. This dart will reveal the location of any player struck by the dart.\",\n" +
" \"displayIcon\": \"https://media.valorant-api.com/agents/117ed9e3-49f3-6512-3ccf-0cada7e3823b/abilities/ability2/displayicon.png\"\n" +
" },\n" +
" {\n" +
" \"slot\": \"Grenade\",\n" +
" \"displayName\": \"Trapwire\",\n" +
" \"description\": \"EQUIP a trapwire. FIRE to place a destructible and covert tripwire at the targeted location, creating a line that spans between the placed location and the wall opposite. Enemy players who cross a tripwire will be tethered, revealed, and dazed after a short period if they do not destroy the device in time. This ability can be picked up to be REDEPLOYED.\",\n" +
" \"displayIcon\": \"https://media.valorant-api.com/agents/117ed9e3-49f3-6512-3ccf-0cada7e3823b/abilities/grenade/displayicon.png\"\n" +
" },\n" +
" {\n" +
" \"slot\": \"Ultimate\",\n" +
" \"displayName\": \"Neural Theft\",\n" +
" \"description\": \"INSTANTLY use on a dead enemy player in your crosshairs to reveal the location of all living enemy players.\",\n" +
" \"displayIcon\": \"https://media.valorant-api.com/agents/117ed9e3-49f3-6512-3ccf-0cada7e3823b/abilities/ultimate/displayicon.png\"\n" +
" }\n" +
" ]\n" +
" }\n" +
" ]"
| 1 | 0.823323 | 1 | 0.823323 | game-dev | MEDIA | 0.591088 | game-dev | 0.894608 | 1 | 0.894608 |
Nextpeer/Nextpeer-UFORUN | 2,213 | cocos2d-x-2.2/external/emscripten/tests/poppler/goo/GooHash.h | //========================================================================
//
// GooHash.h
//
// Copyright 2001-2003 Glyph & Cog, LLC
//
//========================================================================
#ifndef GHASH_H
#define GHASH_H
#ifdef USE_GCC_PRAGMAS
#pragma interface
#endif
#include "gtypes.h"
class GooString;
struct GooHashBucket;
struct GooHashIter;
//------------------------------------------------------------------------
class GooHash {
public:
GooHash(GBool deleteKeysA = gFalse);
~GooHash();
void add(GooString *key, void *val);
void add(GooString *key, int val);
void replace(GooString *key, void *val);
void replace(GooString *key, int val);
void *lookup(GooString *key);
int lookupInt(GooString *key);
void *lookup(char *key);
int lookupInt(char *key);
void *remove(GooString *key);
int removeInt(GooString *key);
void *remove(char *key);
int removeInt(char *key);
int getLength() { return len; }
void startIter(GooHashIter **iter);
GBool getNext(GooHashIter **iter, GooString **key, void **val);
GBool getNext(GooHashIter **iter, GooString **key, int *val);
void killIter(GooHashIter **iter);
private:
void expand();
GooHashBucket *find(GooString *key, int *h);
GooHashBucket *find(char *key, int *h);
int hash(GooString *key);
int hash(char *key);
GBool deleteKeys; // set if key strings should be deleted
int size; // number of buckets
int len; // number of entries
GooHashBucket **tab;
};
#define deleteGooHash(hash, T) \
do { \
GooHash *_hash = (hash); \
{ \
GooHashIter *_iter; \
GooString *_key; \
void *_p; \
_hash->startIter(&_iter); \
while (_hash->getNext(&_iter, &_key, &_p)) { \
delete (T*)_p; \
} \
delete _hash; \
} \
} while(0)
#endif
| 1 | 0.66056 | 1 | 0.66056 | game-dev | MEDIA | 0.704632 | game-dev | 0.548321 | 1 | 0.548321 |
onitama/OpenHSP | 13,679 | src/hsp3dish/gameplay/src/Animation.cpp | #include "Base.h"
#include "Animation.h"
#include "AnimationController.h"
#include "AnimationClip.h"
#include "AnimationTarget.h"
#include "Game.h"
#include "Transform.h"
#include "Properties.h"
#define ANIMATION_INDEFINITE_STR "INDEFINITE"
#define ANIMATION_DEFAULT_CLIP 0
#define ANIMATION_ROTATE_OFFSET 0
#define ANIMATION_SRT_OFFSET 3
namespace gameplay
{
Animation::Animation(const char* id, AnimationTarget* target, int propertyId, unsigned int keyCount, unsigned int* keyTimes, float* keyValues, unsigned int type)
: _controller(Game::getInstance()->getAnimationController()), _id(id), _duration(0L), _defaultClip(NULL), _clips(NULL)
{
createChannel(target, propertyId, keyCount, keyTimes, keyValues, type);
// Release the animation because a newly created animation has a ref count of 1 and the channels hold the ref to animation.
release();
GP_ASSERT(getRefCount() == 1);
}
Animation::Animation(const char* id, AnimationTarget* target, int propertyId, unsigned int keyCount, unsigned int* keyTimes, float* keyValues, float* keyInValue, float* keyOutValue, unsigned int type)
: _controller(Game::getInstance()->getAnimationController()), _id(id), _duration(0L), _defaultClip(NULL), _clips(NULL)
{
createChannel(target, propertyId, keyCount, keyTimes, keyValues, keyInValue, keyOutValue, type);
// Release the animation because a newly created animation has a ref count of 1 and the channels hold the ref to animation.
release();
GP_ASSERT(getRefCount() == 1);
}
Animation::Animation(const char* id)
: _controller(Game::getInstance()->getAnimationController()), _id(id), _duration(0L), _defaultClip(NULL), _clips(NULL)
{
}
Animation::~Animation()
{
_channels.clear();
if (_defaultClip)
{
if (_defaultClip->isClipStateBitSet(AnimationClip::CLIP_IS_PLAYING_BIT))
{
GP_ASSERT(_controller);
_controller->unschedule(_defaultClip);
}
SAFE_RELEASE(_defaultClip);
}
if (_clips)
{
std::vector<AnimationClip*>::iterator clipIter = _clips->begin();
while (clipIter != _clips->end())
{
AnimationClip* clip = *clipIter;
GP_ASSERT(clip);
if (clip->isClipStateBitSet(AnimationClip::CLIP_IS_PLAYING_BIT))
{
GP_ASSERT(_controller);
_controller->unschedule(clip);
}
SAFE_RELEASE(clip);
clipIter++;
}
_clips->clear();
}
SAFE_DELETE(_clips);
}
Animation::Channel::Channel(Animation* animation, AnimationTarget* target, int propertyId, Curve* curve, unsigned long duration)
: _animation(animation), _target(target), _propertyId(propertyId), _curve(curve), _duration(duration)
{
GP_ASSERT(_animation);
GP_ASSERT(_target);
GP_ASSERT(_curve);
// get property component count, and ensure the property exists on the AnimationTarget by getting the property component count.
GP_ASSERT(_target->getAnimationPropertyComponentCount(propertyId));
_curve->addRef();
_target->addChannel(this);
_animation->addRef();
}
Animation::Channel::Channel(const Channel& copy, Animation* animation, AnimationTarget* target)
: _animation(animation), _target(target), _propertyId(copy._propertyId), _curve(copy._curve), _duration(copy._duration)
{
GP_ASSERT(_curve);
GP_ASSERT(_target);
GP_ASSERT(_animation);
_curve->addRef();
_target->addChannel(this);
_animation->addRef();
}
Animation::Channel::~Channel()
{
SAFE_RELEASE(_curve);
SAFE_RELEASE(_animation);
}
Curve* Animation::Channel::getCurve() const
{
return _curve;
}
const char* Animation::getId() const
{
return _id.c_str();
}
unsigned long Animation::getDuration() const
{
return _duration;
}
void Animation::createClips(const char* url)
{
Properties* properties = Properties::create(url);
GP_ASSERT(properties);
Properties* pAnimation = (strlen(properties->getNamespace()) > 0) ? properties : properties->getNextNamespace();
GP_ASSERT(pAnimation);
int frameCount = pAnimation->getInt("frameCount");
if (frameCount <= 0)
GP_ERROR("The animation's frame count must be greater than 0.");
createClips(pAnimation, (unsigned int)frameCount);
SAFE_DELETE(properties);
}
AnimationClip* Animation::createClip(const char* id, unsigned long begin, unsigned long end)
{
AnimationClip* clip = new AnimationClip(id, this, begin, end);
addClip(clip);
return clip;
}
AnimationClip* Animation::getClip(const char* id)
{
// If id is NULL return the default clip.
if (id == NULL)
{
if (_defaultClip == NULL)
createDefaultClip();
return _defaultClip;
}
else
{
return findClip(id);
}
}
AnimationClip* Animation::getClip(unsigned int index) const
{
if (_clips)
return _clips->at(index);
return NULL;
}
unsigned int Animation::getClipCount() const
{
return _clips ? (unsigned int)_clips->size() : 0;
}
void Animation::play(const char* clipId)
{
// If id is NULL, play the default clip.
if (clipId == NULL)
{
if (_defaultClip == NULL)
createDefaultClip();
_defaultClip->play();
}
else
{
// Find animation clip and play.
AnimationClip* clip = findClip(clipId);
if (clip != NULL)
clip->play();
}
}
void Animation::stop(const char* clipId)
{
// If id is NULL, play the default clip.
if (clipId == NULL)
{
if (_defaultClip)
_defaultClip->stop();
}
else
{
// Find animation clip and play.
AnimationClip* clip = findClip(clipId);
if (clip != NULL)
clip->stop();
}
}
void Animation::pause(const char * clipId)
{
if (clipId == NULL)
{
if (_defaultClip)
_defaultClip->pause();
}
else
{
AnimationClip* clip = findClip(clipId);
if (clip != NULL)
clip->pause();
}
}
bool Animation::targets(AnimationTarget* target) const
{
for (std::vector<Animation::Channel*>::const_iterator itr = _channels.begin(); itr != _channels.end(); ++itr)
{
GP_ASSERT(*itr);
if ((*itr)->_target == target)
{
return true;
}
}
return false;
}
void Animation::createDefaultClip()
{
_defaultClip = new AnimationClip("default_clip", this, 0.0f, _duration);
}
void Animation::createClips(Properties* animationProperties, unsigned int frameCount)
{
GP_ASSERT(animationProperties);
Properties* pClip = animationProperties->getNextNamespace();
while (pClip != NULL && std::strcmp(pClip->getNamespace(), "clip") == 0)
{
int begin = pClip->getInt("begin");
int end = pClip->getInt("end");
AnimationClip* clip = createClip(pClip->getId(), ((float)begin / frameCount) * _duration, ((float)end / frameCount) * _duration);
const char* repeat = pClip->getString("repeatCount");
if (repeat)
{
if (strcmp(repeat, ANIMATION_INDEFINITE_STR) == 0)
{
clip->setRepeatCount(AnimationClip::REPEAT_INDEFINITE);
}
else
{
float value;
sscanf(repeat, "%f", &value);
clip->setRepeatCount(value);
}
}
const char* speed = pClip->getString("speed");
if (speed)
{
float value;
sscanf(speed, "%f", &value);
clip->setSpeed(value);
}
clip->setLoopBlendTime(pClip->getFloat("loopBlendTime")); // returns zero if not specified
pClip = animationProperties->getNextNamespace();
}
}
void Animation::addClip(AnimationClip* clip)
{
if (_clips == NULL)
_clips = new std::vector<AnimationClip*>;
GP_ASSERT(clip);
_clips->push_back(clip);
}
AnimationClip* Animation::findClip(const char* id) const
{
if (_clips)
{
size_t clipCount = _clips->size();
for (size_t i = 0; i < clipCount; i++)
{
AnimationClip* clip = _clips->at(i);
GP_ASSERT(clip);
if (clip->_id.compare(id) == 0)
{
return clip;
}
}
}
return NULL;
}
Animation::Channel* Animation::createChannel(AnimationTarget* target, int propertyId, unsigned int keyCount, unsigned int* keyTimes, float* keyValues, unsigned int type)
{
GP_ASSERT(target);
GP_ASSERT(keyTimes);
GP_ASSERT(keyValues);
unsigned int propertyComponentCount = target->getAnimationPropertyComponentCount(propertyId);
GP_ASSERT(propertyComponentCount > 0);
Curve* curve = Curve::create(keyCount, propertyComponentCount);
GP_ASSERT(curve);
if (target->_targetType == AnimationTarget::TRANSFORM)
setTransformRotationOffset(curve, propertyId);
unsigned int lowest = keyTimes[0];
unsigned long duration = keyTimes[keyCount-1] - lowest;
float* normalizedKeyTimes = new float[keyCount];
normalizedKeyTimes[0] = 0.0f;
curve->setPoint(0, normalizedKeyTimes[0], keyValues, (Curve::InterpolationType) type);
unsigned int pointOffset = propertyComponentCount;
unsigned int i = 1;
for (; i < keyCount - 1; i++)
{
normalizedKeyTimes[i] = (float) (keyTimes[i] - lowest) / (float) duration;
curve->setPoint(i, normalizedKeyTimes[i], (keyValues + pointOffset), (Curve::InterpolationType) type);
pointOffset += propertyComponentCount;
}
if (keyCount > 1) {
i = keyCount - 1;
normalizedKeyTimes[i] = 1.0f;
curve->setPoint(i, normalizedKeyTimes[i], keyValues + pointOffset, (Curve::InterpolationType) type);
}
SAFE_DELETE_ARRAY(normalizedKeyTimes);
Channel* channel = new Channel(this, target, propertyId, curve, duration);
curve->release();
addChannel(channel);
return channel;
}
Animation::Channel* Animation::createChannel(AnimationTarget* target, int propertyId, unsigned int keyCount, unsigned int* keyTimes, float* keyValues, float* keyInValue, float* keyOutValue, unsigned int type)
{
GP_ASSERT(target);
GP_ASSERT(keyTimes);
GP_ASSERT(keyValues);
unsigned int propertyComponentCount = target->getAnimationPropertyComponentCount(propertyId);
GP_ASSERT(propertyComponentCount > 0);
Curve* curve = Curve::create(keyCount, propertyComponentCount);
GP_ASSERT(curve);
if (target->_targetType == AnimationTarget::TRANSFORM)
setTransformRotationOffset(curve, propertyId);
unsigned long lowest = keyTimes[0];
unsigned long duration = keyTimes[keyCount-1] - lowest;
float* normalizedKeyTimes = new float[keyCount];
normalizedKeyTimes[0] = 0.0f;
curve->setPoint(0, normalizedKeyTimes[0], keyValues, (Curve::InterpolationType) type, keyInValue, keyOutValue);
unsigned int pointOffset = propertyComponentCount;
unsigned int i = 1;
for (; i < keyCount - 1; i++)
{
normalizedKeyTimes[i] = (float) (keyTimes[i] - lowest) / (float) duration;
curve->setPoint(i, normalizedKeyTimes[i], (keyValues + pointOffset), (Curve::InterpolationType) type, (keyInValue + pointOffset), (keyOutValue + pointOffset));
pointOffset += propertyComponentCount;
}
i = keyCount - 1;
normalizedKeyTimes[i] = 1.0f;
curve->setPoint(i, normalizedKeyTimes[i], keyValues + pointOffset, (Curve::InterpolationType) type, keyInValue + pointOffset, keyOutValue + pointOffset);
SAFE_DELETE_ARRAY(normalizedKeyTimes);
Channel* channel = new Channel(this, target, propertyId, curve, duration);
curve->release();
addChannel(channel);
return channel;
}
void Animation::addChannel(Channel* channel)
{
GP_ASSERT(channel);
_channels.push_back(channel);
if (channel->_duration > _duration)
_duration = channel->_duration;
}
void Animation::removeChannel(Channel* channel)
{
std::vector<Animation::Channel*>::iterator itr = _channels.begin();
while (itr != _channels.end())
{
Animation::Channel* chan = *itr;
if (channel == chan)
{
_channels.erase(itr);
return;
}
else
{
itr++;
}
}
}
void Animation::setTransformRotationOffset(Curve* curve, unsigned int propertyId)
{
GP_ASSERT(curve);
switch (propertyId)
{
case Transform::ANIMATE_ROTATE:
case Transform::ANIMATE_ROTATE_TRANSLATE:
curve->setQuaternionOffset(ANIMATION_ROTATE_OFFSET);
return;
case Transform::ANIMATE_SCALE_ROTATE:
case Transform::ANIMATE_SCALE_ROTATE_TRANSLATE:
curve->setQuaternionOffset(ANIMATION_SRT_OFFSET);
return;
}
return;
}
Animation* Animation::clone(Channel* channel, AnimationTarget* target)
{
GP_ASSERT(channel);
Animation* animation = new Animation(getId());
Animation::Channel* channelCopy = new Animation::Channel(*channel, animation, target);
animation->addChannel(channelCopy);
// Release the animation because a newly created animation has a ref count of 1 and the channels hold the ref to animation.
animation->release();
GP_ASSERT(animation->getRefCount() == 1);
// Clone the clips
if (_defaultClip)
{
animation->_defaultClip = _defaultClip->clone(animation);
}
if (_clips)
{
for (std::vector<AnimationClip*>::iterator it = _clips->begin(); it != _clips->end(); ++it)
{
AnimationClip* newClip = (*it)->clone(animation);
animation->addClip(newClip);
}
}
return animation;
}
}
| 1 | 0.853433 | 1 | 0.853433 | game-dev | MEDIA | 0.788643 | game-dev | 0.880979 | 1 | 0.880979 |
ghostinthecamera/IGCS-GITC | 4,475 | Cameras/Final Fantasy XIII-2/InjectableGenericCameraSystem/Gamepad.h | //////////////////////////////////////////////////////////////////////
// By Adam Dobos: https://github.com/adam10603/XInput-wrapper
//////////////////////////////////////////////////////////////////////
#pragma once
#if defined( _M_X64 )
#define _AMD64_
#elif defined ( _M_IX86 )
#define _X86_
#elif defined( _M_ARM )
#define _ARM_
#endif
#include <functional>
#include <Xinput.h>
using namespace std;
/* The positions of the analog sticks will be returned as 'vec2'.
* If you have your own type similar to 'vec2', feel free
* to modify the code to use that. As long as it has '.x' and '.y'
* floating point components and a simple constructor that
* takes values for them, it should be a drop-in replacement.
* In case you don't have such a type, here's one for ya:
*/
struct vec2 {
vec2(float _x, float _y) : x{ _x }, y{ _y } {}
float x = 0.0f;
float y = 0.0f;
};
class Gamepad {
public:
// These values represent the buttons on the gamepad.
enum button_t {
A = XINPUT_GAMEPAD_A,
B = XINPUT_GAMEPAD_B,
X = XINPUT_GAMEPAD_X,
Y = XINPUT_GAMEPAD_Y,
UP = XINPUT_GAMEPAD_DPAD_UP,
DOWN = XINPUT_GAMEPAD_DPAD_DOWN,
LEFT = XINPUT_GAMEPAD_DPAD_LEFT,
RIGHT = XINPUT_GAMEPAD_DPAD_RIGHT,
LB = XINPUT_GAMEPAD_LEFT_SHOULDER,
RB = XINPUT_GAMEPAD_RIGHT_SHOULDER,
LSTICK = XINPUT_GAMEPAD_LEFT_THUMB,
RSTICK = XINPUT_GAMEPAD_RIGHT_THUMB,
START = XINPUT_GAMEPAD_START,
BACK = XINPUT_GAMEPAD_BACK
};
// If you have multiple gamepads, create multiple instances of the class using different indexes. The connected gamepads are numbered 0-4. The default argument is 0, meaning this instance will take control of the first (or only one) gamepad connected to the system.
Gamepad(int index = 0) : gpIndex{ index }, buttonDownCallback{ nullptr }, buttonUpCallback{ nullptr }, buttonState{ 0x0 } {}
// Set a function (of type 'void', with a 'button_t' argument) to be called each time a button is pressed on the gamepad. The value of the argument should be checked against values of the 'button_t' enum to determine which button was pressed.
void setButtonDownCallback(function<void(button_t)> fn);
// Set a function (of type 'void', with a 'button_t' argument) to be called each time a button is released on the gamepad. The value of the argument should be checked against values of the 'button_t' enum to determine which button was released.
void setButtonUpCallback(function<void(button_t)> fn);
// Ths update function should be called every cycle of your app (before any other member calls) to keep things up to date. NOTE: All data that other member functions return is actually read from the device at the time you call this function, and will not be updated until you call 'update()' again.
void update();
// Indicates if the gamepad is connected or not. This should be checked before fetching any data.
bool isConnected();
// Indicates if a button (specified by the argument) is currently pressed or not (well, at the time of the last 'update()' call anyway).
bool isButtonPressed(button_t b);
// Returns the position of the left analog stick. '.x' and '.y' range from -1.0 to 1.0.
vec2 getLStickPosition();
// Returns the position of the right analog stick. '.x' and '.y' range from -1.0 to 1.0.
vec2 getRStickPosition();
// Returns the position of the left trigger. Range is 0.0 (not pressed) to 1.0 (pressed all the way).
float getLTrigger();
// Returns the position of the right trigger. Range is 0.0 (not pressed) to 1.0 (pressed all the way).
float getRTrigger();
// Vibrates the gamepad. 'L' and 'R' define the vibration intensity of the left and right motors. They should be in the 0.0 to 1.0 range. NOTE: to turn vibrations off, you must call this function again with both arguments being 0.0.
void vibrate(float L, float R);
// If set to true, the Y-axis of the left analog stick will be inverted.
void setInvertLStickY(bool b);
// If set to true, the Y-axis of the right analog stick will be inverted.
void setInvertRStickY(bool b);
// Only use this if you want to use some XInput functionality directly. It returns a pointer to the current state.
XINPUT_STATE* getState();
// Returns the gamepad's index (the argument the constructor was given). Kind of pointless, but whatever.
int getIndex();
private:
function<void(button_t)> buttonDownCallback;
function<void(button_t)> buttonUpCallback;
XINPUT_STATE gpState;
int gpIndex;
WORD buttonState;
bool connected;
bool invertLSY;
bool invertRSY;
};
| 1 | 0.86008 | 1 | 0.86008 | game-dev | MEDIA | 0.855002 | game-dev | 0.657664 | 1 | 0.657664 |
neoml-lib/neoml | 62,553 | NeoMathEngine/src/CPU/CpuMathEngine.h | /* Copyright © 2017-2024 ABBYY
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.
--------------------------------------------------------------------------------------------------------------*/
#pragma once
#include <NeoMathEngine/NeoMathEngine.h>
#include <NeoMathEngine/SimdMathEngine.h>
#include <MemoryEngineMixin.h>
#include <DllLoader.h>
#include <memory>
#include <CpuMathEngineDnnDistributed.h>
namespace NeoML {
struct CCpuConvolutionDesc;
struct CCommon2DPoolingDesc;
struct CCommonMaxPoolingDesc;
struct CCommon3dConvolutionDesc;
struct CCommonChannelwiseConvolutionDesc;
class ISimdMathEngine;
// Math engine that uses a CPU for calculations
class CCpuMathEngine : public CMemoryEngineMixin, public IRawMemoryManager {
public:
CCpuMathEngine( size_t memoryLimit,
std::shared_ptr<CMultiThreadDistributedCommunicator> communicator = nullptr,
const CMathEngineDistributedInfo& distributedInfo = CMathEngineDistributedInfo() );
~CCpuMathEngine() override;
// IMathEngine interface methods
TMathEngineType GetType() const override { return MET_Cpu; }
void GetMathEngineInfo( CMathEngineInfo& info ) const override;
void* GetBuffer( const CMemoryHandle& handle, size_t pos, size_t size, bool exchange ) override; // specialize
void ReleaseBuffer( const CMemoryHandle& handle, void* ptr, bool exchange ) override; // specialize
void DataExchangeRaw( const CMemoryHandle& handle, const void* data, size_t size ) override;
void DataExchangeRaw( void* data, const CMemoryHandle& handle, size_t size ) override;
// IVectorMathEngine interface methods
void VectorFill( const CFloatHandle& result, float value, int vectorSize ) override;
void VectorFill( const CIntHandle& result, int value, int vectorSize ) override;
void VectorFill( const CFloatHandle& result, int vectorSize, const CConstFloatHandle& value ) override;
void VectorFill( const CIntHandle& result, int vectorSize, const CConstIntHandle& value ) override;
void VectorConvert( const CConstFloatHandle& from, const CIntHandle& to, int vectorSize ) override;
void VectorConvert( const CConstIntHandle& from, const CFloatHandle& to, int vectorSize ) override;
void VectorFillBernoulli( const CFloatHandle& result, float p, int vectorSize, float value, int seed ) override;
void FilterSmallValues( const CFloatHandle& data, int dataSize, float threshold ) override;
void VectorCopy( const CFloatHandle& first, const CConstFloatHandle& second, int vectorSize ) override;
void VectorCopy( const CIntHandle& first, const CConstIntHandle& second, int vectorSize ) override;
void BroadcastCopy( const CIntHandle& toHandle, const CConstIntHandle& fromHandle,
const CBlobDesc& toDesc, const CBlobDesc& fromDesc, int additionalWidth ) override;
void BroadcastCopy( const CFloatHandle& toHandle, const CConstFloatHandle& fromHandle,
const CBlobDesc& toDesc, const CBlobDesc& fromDesc, int additionalWidth ) override;
void VectorSum( const CConstFloatHandle& firstHandle, int vectorSize, const CFloatHandle& resultHandle ) override;
void VectorSumAdd( const CConstFloatHandle& firstHandle, int vectorSize, const CFloatHandle& resultHandle ) override;
void VectorSumAlongDimension( const CConstFloatHandle& firstHandle, int precedingDimension, int dimension,
int followingDimension, const CFloatHandle& resultHandle ) override;
void VectorCumSumAlongDimension( const CConstFloatHandle& firstHandle, int precedingDimension, int dimension,
int followingDimension, const CFloatHandle& resultHandle, bool reverse ) override;
void VectorCumSumAlongDimension( const CConstIntHandle& firstHandle, int precedingDimension, int dimension,
int followingDimension, const CIntHandle& resultHandle, bool reverse ) override;
void VectorSumAlongDimensionDiag( const CConstFloatHandle& firstHandle, int precedingDimension, int dimension,
int followingDimension, const CFloatHandle& resultHandle ) override;
void VectorCumSumAlongDimensionDiag( const CConstFloatHandle& firstHandle, int precedingDimension, int dimension,
int followingDimension, const CFloatHandle& resultHandle ) override;
void VectorEqual( const CConstIntHandle& firstHandle, const CConstIntHandle& secondHandle,
const CFloatHandle& resultHandle, int vectorSize ) override;
void VectorEqualValue( const CConstIntHandle& firstHandle,
const CFloatHandle& resultHandle, int vectorSize, const CConstIntHandle& valueHandle ) override;
void VectorMax( const CConstFloatHandle& firstHandle, float secondValue, const CFloatHandle& resultHandle,
int vectorSize ) override;
void VectorMaxDiff( const CConstFloatHandle& firstHandle, float secondValue, const CFloatHandle& gradHandle,
int gradHeight, int gradWidth ) override;
void VectorELU( const CConstFloatHandle& firstHandle, const CFloatHandle& resultHandle,
int vectorSize, const CConstFloatHandle& alpha ) override;
void VectorELUDiff( const CConstFloatHandle& firstHandle, const CConstFloatHandle& secondHandle,
const CFloatHandle& resultHandle, int vectorSize, const CConstFloatHandle& alpha ) override;
void VectorELUDiffOp( const CConstFloatHandle& firstHandle, const CConstFloatHandle& secondHandle,
const CFloatHandle& resultHandle, int vectorSize, const CConstFloatHandle& alpha ) override;
void VectorReLU( const CConstFloatHandle& firstHandle, const CFloatHandle& resultHandle, int vectorSize,
const CConstFloatHandle& upperThresholdHandle ) override;
void VectorReLUDiff( const CConstFloatHandle& firstHandle, const CConstFloatHandle& secondHandle,
const CFloatHandle& resultHandle, int vectorSize, const CConstFloatHandle& upperThresholdHandle ) override;
void VectorReLUDiffOp( const CConstFloatHandle& firstHandle, const CConstFloatHandle& secondHandle,
const CFloatHandle& resultHandle, int vectorSize, const CConstFloatHandle& upperThresholdHandle ) override;
void VectorLeakyReLU( const CConstFloatHandle& firstHandle, const CFloatHandle& resultHandle,
int vectorSize, const CConstFloatHandle& alpha ) override;
void VectorLeakyReLUDiff( const CConstFloatHandle& firstHandle,
const CConstFloatHandle& secondHandle, const CFloatHandle& resultHandle,
int vectorSize, const CConstFloatHandle& alpha ) override;
void VectorLeakyReLUDiffOp( const CConstFloatHandle& firstHandle,
const CConstFloatHandle& secondHandle, const CFloatHandle& resultHandle,
int vectorSize, const CConstFloatHandle& alpha ) override;
void VectorHSwish( const CConstFloatHandle& firstHandle, const CFloatHandle& resultHandle,
int vectorSize ) override;
void VectorHSwishDiff( const CConstFloatHandle& firstHandle, const CConstFloatHandle& secondHandle,
const CFloatHandle& resultHandle, int vectorSize ) override;
void VectorEltwiseMax( const CConstFloatHandle& firstHandle,
const CConstFloatHandle& secondHandle, const CFloatHandle& resultHandle, int vectorSize ) override;
void VectorEltwiseMin( const CConstFloatHandle& firstHandle, const CConstFloatHandle& secondHandle,
const CFloatHandle& resultHandle, int vectorSize ) override;
void VectorAbs( const CConstFloatHandle& firstHandle, const CFloatHandle& resultHandle, int vectorSize ) override;
void VectorAbsDiff( const CConstFloatHandle& firstHandle, const CConstFloatHandle& secondHandle,
const CFloatHandle& resultHandle, int vectorSize ) override;
void VectorAbsDiff( const CConstFloatHandle& sourceGradHandle, int gradHeight, int gradWidth,
const CConstFloatHandle& firstHandle, const CFloatHandle& resultHandle ) override;
void VectorHinge( const CConstFloatHandle& firstHandle, const CFloatHandle& resultHandle, int vectorSize ) override;
void VectorHingeDiff( const CConstFloatHandle& firstHandle, const CConstFloatHandle& secondHandle,
const CFloatHandle& resultHandle, int vectorSize ) override;
void VectorSquaredHinge( const CConstFloatHandle& firstHandle, const CFloatHandle& resultHandle, int vectorSize ) override;
void VectorSquaredHingeDiff( const CConstFloatHandle& firstHandle, const CConstFloatHandle& secondHandle,
const CFloatHandle& resultHandle, int vectorSize ) override;
void VectorHuber( const CConstFloatHandle& firstHandle, const CFloatHandle& resultHandle, int vectorSize ) override;
void VectorHuberDerivative( const CConstFloatHandle& firstHandle, const CFloatHandle& resultHandle, int vectorSize ) override;
void VectorHardTanh( const CConstFloatHandle& firstHandle, const CFloatHandle& resultHandle, int vectorSize ) override;
void VectorHardTanhDiff( const CConstFloatHandle& firstHandle, const CConstFloatHandle& secondHandle,
const CFloatHandle& resultHandle, int vectorSize ) override;
void VectorHardTanhDiffOp( const CConstFloatHandle& firstHandle, const CConstFloatHandle& secondHandle,
const CFloatHandle& resultHandle, int vectorSize ) override;
void VectorHardSigmoid( const CConstFloatHandle& firstHandle, const CFloatHandle& resultHandle, int vectorSize,
const CConstFloatHandle& slopeHandle, const CConstFloatHandle& biasHandle ) override;
void VectorHardSigmoidDiff( const CConstFloatHandle& firstHandle, const CConstFloatHandle& secondHandle,
const CFloatHandle& resultHandle, int vectorSize, const CConstFloatHandle& slopeHandle, const CConstFloatHandle& biasHandle ) override;
void VectorHardSigmoidDiffOp( const CConstFloatHandle& firstHandle, const CConstFloatHandle& secondHandle,
const CFloatHandle& resultHandle, int vectorSize, const CConstFloatHandle& slopeHandle, const CConstFloatHandle& biasHandle ) override;
void VectorNeg( const CConstFloatHandle& firstHandle, const CFloatHandle& resultHandle, int vectorSize ) override;
void VectorExp( const CConstFloatHandle& firstHandle, const CFloatHandle& resultHandle, int vectorSize ) override;
void VectorLog( const CConstFloatHandle& firstHandle, const CFloatHandle& resultHandle,
int vectorSize ) override;
void VectorLogDiff( const CConstFloatHandle& sourceGradHandle, int sourceGradHeight, int sourceGradWidth,
const CConstFloatHandle& valueHandle, const CFloatHandle& resultHandle ) override;
void VectorNegLog( const CConstFloatHandle& firstHandle, const CFloatHandle& resultHandle, int vectorSize ) override;
void VectorErf( const CConstFloatHandle& firstHandle, const CFloatHandle& resultHandle, int vectorSize ) override;
void VectorBernulliKLDerivative( const CConstFloatHandle& estimationHandle,
const CFloatHandle& resultHandle, int vectorSize, const CConstFloatHandle& target ) override;
void VectorAdd( const CConstFloatHandle& firstHandle,
const CConstFloatHandle& secondHandle, const CFloatHandle& resultHandle, int vectorSize ) override;
void VectorAdd( const CConstIntHandle& firstHandle,
const CConstIntHandle& secondHandle, const CIntHandle& resultHandle, int vectorSize ) override;
void VectorAddValue( const CConstFloatHandle& firstHandle,
const CFloatHandle& resultHandle, int vectorSize, const CConstFloatHandle& addition ) override;
void VectorAddValue( const CConstIntHandle& firstHandle,
const CIntHandle& resultHandle, int vectorSize, const CConstIntHandle& addition ) override;
void VectorSub( const CConstIntHandle& firstHandle,
const CConstIntHandle& secondHandle, const CIntHandle& resultHandle, int vectorSize ) override;
void VectorSub( const CConstFloatHandle& firstHandle,
const CConstFloatHandle& secondHandle, const CFloatHandle& resultHandle, int vectorSize ) override;
void VectorSub( const CConstFloatHandle& firstHandle,
float second, const CFloatHandle& resultHandle, int vectorSize ) override;
void VectorSub( float first,
const CConstFloatHandle& secondHandle, const CFloatHandle& resultHandle, int vectorSize ) override;
void VectorMultiplyAndAdd( const CConstFloatHandle& firstHandle, const CConstFloatHandle& secondHandle,
const CFloatHandle& resultHandle, int vectorSize, const CConstFloatHandle& multHandle ) override;
void VectorMultiplyAndSub( const CConstFloatHandle& firstHandle, const CConstFloatHandle& secondHandle,
const CFloatHandle& resultHandle, int vectorSize, const CConstFloatHandle& multHandle ) override;
void VectorMultiply( const CConstFloatHandle& firstHandle,
const CFloatHandle& resultHandle, int vectorSize, const CConstFloatHandle& multiplierHandle ) override;
void VectorMultiply( const CConstIntHandle& firstHandle,
const CIntHandle& resultHandle, int vectorSize, const CConstIntHandle& multiplierHandle ) override;
void VectorNegMultiply( const CConstFloatHandle& firstHandle,
const CFloatHandle& resultHandle, int vectorSize, const CConstFloatHandle& multiplierHandle ) override;
void VectorEltwiseMultiply( const CConstIntHandle& firstHandle,
const CConstIntHandle& secondHandle, const CIntHandle& resultHandle, int vectorSize ) override;
void VectorEltwiseMultiply( const CConstFloatHandle& firstHandle,
const CConstFloatHandle& secondHandle, const CFloatHandle& resultHandle, int vectorSize ) override;
void VectorEltwiseMultiplyAdd( const CConstFloatHandle& firstHandle,
const CConstFloatHandle& secondHandle, const CFloatHandle& resultHandle, int vectorSize ) override;
void VectorEltwiseNegMultiply( const CConstFloatHandle& firstHandle,
const CConstFloatHandle& secondHandle, const CFloatHandle& resultHandle, int vectorSize ) override;
void VectorEltwiseDivide( const CConstIntHandle& firstHandle,
const CConstIntHandle& secondHandle, const CIntHandle& resultHandle, int vectorSize ) override;
void VectorEltwiseDivide( const CConstFloatHandle& firstHandle,
const CConstFloatHandle& secondHandle, const CFloatHandle& resultHandle, int vectorSize ) override;
void VectorEltwisePower( const CConstFloatHandle& firstHandle,
const CConstFloatHandle& secondHandle, const CFloatHandle& resultHandle, int vectorSize ) override;
void VectorSqrt( const CConstFloatHandle& firstHandle, const CFloatHandle& resultHandle, int vectorSize ) override;
void VectorInv( const CConstFloatHandle& firstHandle, const CFloatHandle& resultHandle, int vectorSize ) override;
void VectorMinMax( const CConstFloatHandle& firstHandle, const CFloatHandle& resultHandle, int vectorSize,
const CConstFloatHandle& minHandle, const CConstFloatHandle& maxHandle ) override;
void VectorMinMaxDiff( const CConstFloatHandle& sourceGradHandle, int gradHeight, int gradWidth,
const CConstFloatHandle& firstHandle, const CFloatHandle& resultHandle,
const CConstFloatHandle& minHandle, const CConstFloatHandle& maxHandle ) override;
void VectorSigmoid( const CConstFloatHandle& firstHandle, const CFloatHandle& resultHandle, int vectorSize ) override;
void VectorSigmoidDiff( const CConstFloatHandle& firstHandle, const CConstFloatHandle& secondHandle,
const CFloatHandle& resultHandle, int vectorSize ) override;
void VectorSigmoidDiffOp( const CConstFloatHandle& firstHandle, const CConstFloatHandle& secondHandle,
const CFloatHandle& resultHandle, int vectorSize ) override;
void VectorTanh( const CConstFloatHandle& firstHandle, const CFloatHandle& resultHandle, int vectorSize ) override;
void VectorTanhDiff( const CConstFloatHandle& firstHandle, const CConstFloatHandle& secondHandle,
const CFloatHandle& resultHandle, int vectorSize ) override;
void VectorTanhDiffOp( const CConstFloatHandle& firstHandle, const CConstFloatHandle& secondHandle,
const CFloatHandle& resultHandle, int vectorSize ) override;
void VectorPower( float exponent, const CConstFloatHandle& firstHandle, const CFloatHandle& resultHandle, int vectorSize ) override;
void VectorPowerDiff( float exponent, const CConstFloatHandle& firstHandle, const CConstFloatHandle& secondHandle,
const CFloatHandle& resultHandle, int vectorSize ) override;
void VectorPowerDiffOp( float exponent, const CConstFloatHandle& firstHandle, const CConstFloatHandle& secondHandle,
const CFloatHandle& resultHandle, int vectorSize ) override;
void VectorL1DiffAdd( const CConstFloatHandle& firstHandle, const CConstFloatHandle& secondHandle,
const CFloatHandle& resultHandle, int vectorSize,
const CConstFloatHandle& hubertThresholdHandle, const CConstFloatHandle& multHandle ) override;
void VectorDotProduct( const CConstFloatHandle& firstHandle, const CConstFloatHandle& secondHandle, int vectorSize,
const CFloatHandle& resultHandle ) override;
void VectorEltwiseNot( const CConstIntHandle& firstHandle, const CIntHandle& resultHandle, int vectorSize ) override;
void VectorEltwiseNotNegative( const CConstIntHandle& firstHanle, const CFloatHandle& resultHandle, int vectorSize ) override;
void VectorEltwiseLess( const CConstFloatHandle& firstHandle, const CConstFloatHandle& secondHandle,
const CFloatHandle& resultHandle, int vectorSize ) override;
void VectorEltwiseLess( const CConstFloatHandle& firstHandle, float second,
const CFloatHandle& resultHandle, int vectorSize ) override;
void VectorEltwiseLess( float first, const CConstFloatHandle& secondHandle,
const CFloatHandle& resultHandle, int vectorSize ) override;
void VectorEltwiseLess( const CConstFloatHandle& firstHandle, const CConstFloatHandle& secondHandle,
const CIntHandle& resultHandle, int vectorSize ) override;
void VectorEltwiseLess( const CConstIntHandle& firstHandle, const CConstIntHandle& secondHandle,
const CIntHandle& resultHandle, int vectorSize ) override;
void VectorEltwiseEqual( const CConstFloatHandle& firstHandle, const CConstFloatHandle& secondHandle,
const CIntHandle& resultHandle, int vectorSize ) override;
void VectorEltwiseEqual( const CConstIntHandle& firstHandle, const CConstIntHandle& secondHandle,
const CIntHandle& resultHandle, int vectorSize ) override;
void VectorEltwiseWhere( const CConstIntHandle& firstHandle, const CConstFloatHandle& secondHandle,
const CConstFloatHandle& thirdHandle, const CFloatHandle& resultHandle, int vectorSize ) override;
void VectorEltwiseWhere( const CConstIntHandle& firstHandle, const CConstIntHandle& secondHandle,
const CConstIntHandle& thirdHandle, const CIntHandle& resultHandle, int vectorSize ) override;
void VectorFindMaxValueInSet( const CConstFloatHandle* vectors, int vectorCount, const CFloatHandle& resultHandle,
int vectorSize ) override;
void VectorFindMaxValueInSet( const CConstFloatHandle* vectors, int vectorCount, const CFloatHandle& resultHandle,
const CIntHandle& indexHandle, int vectorSize ) override;
void VectorSpreadValues( const CConstFloatHandle& sourceHandle, CFloatHandle* vectors, int vectorCount,
const CConstIntHandle& indexHandle, int vectorSize ) override;
void VectorTopK( const CConstFloatHandle& first, int firstSize, int k, const CFloatHandle& result, const CIntHandle& indices ) override;
void VectorTopKDiff( const CConstFloatHandle& sourceGrad, int sourceGradHeight, int sourceGradWidth,
const CConstIntHandle& indices, int k, const CFloatHandle& resultGrad ) override;
// IBlasEngine interface methods
void SetVectorToMatrixRows( const CFloatHandle& resultHandle, int matrixHeight,
int matrixWidth, const CConstFloatHandle& vectorHandle ) override;
void AddVectorToMatrixElements( const CFloatHandle& matrix, int height, int width,
const CConstIntHandle& indices, const CConstFloatHandle& vector ) override;
void AddVectorToMatrixElements( const CFloatHandle& matrix, int height, int width,
const CConstIntHandle& rowIndices, const CConstIntHandle& columnIndices,
const CConstFloatHandle& vector, int vectorSize ) override;
void AddMatrixElementsToVector( const CConstFloatHandle& matrix, int height, int width,
const CConstIntHandle& indices, const CFloatHandle& result, int vectorSize ) override;
void AddMatrixElementsToVector( const CConstFloatHandle& matrix, int height, int width,
const CConstIntHandle& rowIndices, const CConstIntHandle& columnIndices,
const CFloatHandle& result, int vectorSize ) override;
void AddDiagMatrixToMatrix( const CConstFloatHandle& diagMatrix, const CConstFloatHandle& matrix,
int height, int width, const CFloatHandle& result ) override;
void AddMatrixElementsToMatrix( const CConstFloatHandle& matrix, int height, int width,
const CFloatHandle& result, const CConstIntHandle& indices ) override;
void AddVectorToMatrixRows( int batchSize, const CConstFloatHandle& matrixHandle, const CFloatHandle& resultHandle,
int matrixHeight, int matrixWidth, const CConstFloatHandle& vectorHandle ) override;
void AddVectorToMatrixColumns( const CConstFloatHandle& matrixHandle, const CFloatHandle& resultHandle,
int matrixHeight, int matrixWidth, const CConstFloatHandle& vectorHandle ) override;
void AddVectorToMatrixColumns( const CConstIntHandle& matrixHandle, const CIntHandle& resultHandle,
int matrixHeight, int matrixWidth, const CConstIntHandle& vectorHandle ) override;
void SubVectorFromMatrixColumns( const CConstFloatHandle& matrixHandle, const CFloatHandle& resultHandle,
int matrixHeight, int matrixWidth, const CConstFloatHandle& vectorHandle ) override;
void SumMatrixRowsAdd( int batchSize, const CFloatHandle& resultHandle, const CConstFloatHandle& matrixHandle,
int matrixHeight, int matrixWidth ) override;
void SumMatrixRows( int batchSize, const CFloatHandle& resultHandle, const CConstFloatHandle& matrixHandle,
int matrixHeight, int matrixWidth ) override;
void SumMatrixRows( int batchSize, const CIntHandle& resultHandle, const CConstIntHandle& matrixHandle,
int matrixHeight, int matrixWidth ) override;
void SumMatrixColumns( const CFloatHandle& resultHandle, const CConstFloatHandle& matrixHandle,
int matrixHeight, int matrixWidth ) override;
void MatrixColumnsEltwiseDivide( const CConstFloatHandle& matrix, int matrixHeight, int matrixWidth,
const CConstFloatHandle& vector, const CFloatHandle& resultHandle ) override;
void MatrixLogSumExpByRows( const CConstFloatHandle& matrix, int height, int width, const CFloatHandle& result, int resultSize ) override;
void MatrixSoftmaxByRows( const CConstFloatHandle& matrix, int height, int width, const CFloatHandle& result ) override;
void MatrixSoftmaxDiffOpByRows( const CConstFloatHandle& first, const CConstFloatHandle& second,
int height, int width, const CFloatHandle& result ) override;
void MatrixSoftmaxByColumns( const CConstFloatHandle& matrix, int height, int width,
const CFloatHandle& result ) override;
void MatrixSoftmaxDiffOpByColumns( const CConstFloatHandle& first, const CConstFloatHandle& second,
int height, int width, const CFloatHandle& result ) override;
void FindMaxValueInRows( const CConstFloatHandle& matrixHandle, int matrixHeight, int matrixWidth,
const CFloatHandle& resultHandle, const CIntHandle& columnIndices, int vectorSize ) override;
void FindMaxValueInRows( const CConstFloatHandle& matrixHandle,
int matrixHeight, int matrixWidth, const CFloatHandle& resultHandle, int vectorSize ) override;
void FindMaxValueInColumns( int batchSize, const CConstFloatHandle& matrixHandle, int matrixHeight,
int matrixWidth, const CFloatHandle& resultHandle, const CIntHandle& rowIndices, int vectorSize ) override;
void FindMinValueInColumns( const CConstFloatHandle& matrixHandle, int matrixHeight, int matrixWidth,
const CFloatHandle& resultHandle, const CIntHandle& columnIndices ) override;
void VectorMultichannelLookupAndCopy( int batchSize, int channelCount, const CConstFloatHandle& inputHandle,
const CConstFloatHandle* lookupHandles, const CLookupDimension* lookupDimensions, int lookupCount,
const CFloatHandle& outputHandle, int outputChannels ) override;
void VectorMultichannelLookupAndCopy( int batchSize, int channelCount, const CConstIntHandle& inputHandle,
const CConstFloatHandle* lookupHandles, const CLookupDimension* lookupDimensions, int lookupCount,
const CFloatHandle& outputHandle, int outputChannels ) override;
void VectorMultichannelLookupAndCopy( int batchSize, int channelCount, const CConstIntHandle& inputHandle,
const CConstIntHandle* lookupHandles, const CLookupDimension* lookupDimensions, int lookupCount,
const CIntHandle& outputHandle, int outputChannels ) override;
void VectorMultichannelLookupAndAddToTable( int batchSize, int channelCount, const CConstFloatHandle& inputHandle,
const CFloatHandle* lookupHandles, const CLookupDimension* lookupDimensions, int lookupCount,
const CConstFloatHandle& multHandle, const CConstFloatHandle& matrixHandle, int outputChannels ) override;
void VectorMultichannelLookupAndAddToTable( int batchSize, int channelCount, const CConstIntHandle& inputHandle,
const CFloatHandle* lookupHandles, const CLookupDimension* lookupDimensions, int lookupCount,
const CConstFloatHandle& multHandle, const CConstFloatHandle& matrixHandle, int outputChannels ) override;
void LookupAndSum( const CConstIntHandle& indicesHandle, int batchSize, int indexCount,
const CConstFloatHandle& tableHandle, int vectorSize, const CFloatHandle& result ) override;
void LookupAndAddToTable( const CConstIntHandle& indicesHandle, int batchSize, int indexCount,
const CConstFloatHandle& additionsHandle, int vectorSize, const CFloatHandle& tableHandle, int vectorCount ) override;
void EnumBinarization( int batchSize, const CConstFloatHandle& inputHandle, int enumSize,
const CFloatHandle& resultHandle ) override;
void EnumBinarization( int batchSize, const CConstIntHandle& inputHandle, int enumSize,
const CFloatHandle& resultHandle ) override;
void BitSetBinarization( int batchSize, int bitSetSize,
const CConstIntHandle& inputHandle, int outputVectorSize, const CFloatHandle& resultHandle ) override;
void MultiplyLookupMatrixByLookupVector( int batchSize, const CLookupMatrix& matrix,
const CLookupVector& vector, const CFloatHandle& result, int resultSize ) override;
void MultiplyTransposedLookupMatrixByVector( int batchSize, const CLookupMatrix& matrix,
const CConstFloatHandle& vectorHandle, const CFloatHandle& resultHandle, int resultSize ) override;
void MultiplyTransposedLookupMatrixByVectorAndAdd( int batchSize, const CLookupMatrix& matrix,
const CConstFloatHandle& vectorHandle, const CFloatHandle& resultHandle, int resultSize ) override;
void MultiplyVectorByTransposedLookupVectorAndAddToTable( int batchSize,
const CFloatHandle& tableHandle, int vectorCount, int vectorSize, const CConstIntHandle& indices,
const CConstFloatHandle& firstHandle, int firstSize, const CLookupVector& secondVector ) override;
void MultiplyMatrixByTransposedMatrix( const CConstFloatHandle& firstHandle, int firstHeight,
int firstWidth, int firstRowSize, const CConstFloatHandle& secondHandle, int secondHeight, int secondRowSize,
const CFloatHandle& resultHandle, int resultRowSize, int resultBufferSize ) override;
void MultiplyMatrixByTransposedMatrix( int batchSize, const CConstFloatHandle& firstHandle, int firstHeight, int firstWidth,
const CConstFloatHandle& secondHandle, int secondHeight, const CFloatHandle& resultHandle, int resultBufferSize ) override;
void MultiplySparseMatrixByTransposedMatrix( int firstHeight, int firstWidth, int secondHeight,
const CSparseMatrixDesc& firstDesc, const CConstFloatHandle& secondHandle, const CFloatHandle& resultHandle ) override;
void MultiplyTransposedMatrixBySparseMatrix( int firstHeight, int firstWidth, int secondWidth,
const CConstFloatHandle& firstHandle, const CSparseMatrixDesc& secondDesc, const CFloatHandle& resultHandle,
bool isTransposedSparse ) override;
void MultiplyTransposedMatrixBySparseMatrixAndAdd( int firstHeight, int firstWidth, int secondWidth,
const CConstFloatHandle& firstHandle, const CSparseMatrixDesc& secondDesc, const CFloatHandle& resultHandle ) override;
void MultiplySparseMatrixByMatrix( int firstHeight, int firstWidth, int secondWidth,
const CSparseMatrixDesc& firstDesc, const CConstFloatHandle& secondHandle, const CFloatHandle& resultHandle ) override;
void MultiplyTransposedSparseMatrixByMatrix( int firstHeight, int firstWidth, int secondWidth,
const CSparseMatrixDesc& firstDesc, const CConstFloatHandle& secondHandle, const CFloatHandle& resultHandle ) override;
void MultiplyTransposedMatrixByMatrixAndAdd( const CConstFloatHandle& firstHandle, int firstHeight, int firstWidth,
int firstRowSize, const CConstFloatHandle& secondHandle, int secondWidth, int secondRowSize,
const CFloatHandle& resultHandle, int resultRowSize, int resultBufferSize ) override;
void MultiplyTransposedMatrixByMatrix( int batchSize, const CConstFloatHandle& firstHandle, int firstHeight, int firstWidth,
const CConstFloatHandle& secondHandle, int secondWidth, const CFloatHandle& resultHandle, int resultBufferSize ) override;
void MultiplyDiagMatrixByMatrix( const CConstFloatHandle& firstHandle, int firstSize,
const CConstFloatHandle& secondHandle, int secondWidth,
const CFloatHandle& resultHandle, int resultBufferSize ) override;
void Multiply1DiagMatrixByMatrix( int batchSize, const CConstFloatHandle& firstHandle, int firstSize,
const CConstFloatHandle& secondHandle, int secondWidth,
const CFloatHandle& resultHandle, int resultBufferSize ) override;
void MultiplyMatrixByMatrix( int batchSize, const CConstFloatHandle& firstHandle, int firstHeight,
int firstWidth, const CConstFloatHandle& secondHandle, int secondWidth,
const CFloatHandle& resultHandle, int resultBufferSize ) override;
void BatchMultiplyMatrixByDiagMatrix( int batchSize, const CConstFloatHandle& firstHandle, int height,
int width, int firstMatrixOffset, const CConstFloatHandle& secondHandle, int secondMatrixOffset,
const CFloatHandle& resultHandle, int resultBufferSize ) override;
void TransposeMatrix( int batchSize, const CConstFloatHandle& firstHandle,
int height, int medium, int width, int channels, const CFloatHandle& resultHandle, int resultBufferSize ) override;
void TransposeMatrix( int batchSize, const CConstIntHandle& firstHandle,
int height, int medium, int width, int channels, const CIntHandle& resultHandle, int resultBufferSize ) override;
void MultiplyDiagMatrixByMatrixAndAdd( int batchSize, const CConstFloatHandle& firstHandle,
int firstSize, const CConstFloatHandle& secondHandle, int secondWidth, const CFloatHandle& resultHandle ) override;
void RowMultiplyMatrixByMatrix( const CConstFloatHandle& firstHandle,
const CConstFloatHandle& secondHandle, int height, int width, const CFloatHandle& result ) override;
void MatrixSpreadRows( const CConstFloatHandle& sourceHandle, int height, int width,
const CFloatHandle& resultHandle, int resultHeight, const CConstIntHandle& indexHandle,
const CConstFloatHandle& fillValue ) override;
void MatrixSpreadRowsAdd( const CConstFloatHandle& sourceHandle, int height, int width,
const CFloatHandle& resultHandle, int resultHeight, const CConstIntHandle& indexHandle ) override;
void MatrixSpreadRows( const CConstIntHandle& sourceHandle, int height, int width,
const CIntHandle& resultHandle, int resultHeight, const CConstIntHandle& indexHandle,
const CConstIntHandle& fillValue ) override;
void SingularValueDecomposition( const CFloatHandle& a, int height, int width, const CFloatHandle& u, const CFloatHandle& s,
const CFloatHandle& vt, const CFloatHandle& superb, bool returnLeftVectors, bool returnRightVectors ) override;
void QRFactorization( int height, int width, const CFloatHandle& matrixHandle, const CFloatHandle* qHandle, const CFloatHandle* rHandle,
bool inplace, bool returnQ, bool returnR ) override;
void LUFactorization( int height, int width, const CFloatHandle& matrixHandle ) override;
// IDnnEngine interface methods
void BlobMergeByDim( TBlobDim dim, const CBlobDesc* from, const CFloatHandle* fromData, int fromCount,
const CBlobDesc& to, const CFloatHandle& toData ) override;
void BlobMergeByDim( TBlobDim dim, const CBlobDesc* from, const CIntHandle* fromData, int fromCount,
const CBlobDesc& to, const CIntHandle& toData ) override;
void BlobSplitByDim( TBlobDim dim, const CBlobDesc& from, const CConstFloatHandle& fromData,
const CBlobDesc* to, const CFloatHandle* toData, int toCount ) override;
void BlobSplitByDim( TBlobDim dim, const CBlobDesc& from, const CConstIntHandle& fromData,
const CBlobDesc* to, const CIntHandle* toData, int toCount ) override;
void BlobResizeImage( const CBlobDesc& from, const CFloatHandle& fromData, int deltaLeft, int deltaRight,
int deltaTop, int deltaBottom, TBlobResizePadding padding, float defaultValue,
const CBlobDesc& to, const CFloatHandle& toData ) override;
void BlobGetSubSequence( const CBlobDesc& from, const CFloatHandle& fromData, const CIntHandle& indexHandle,
const CBlobDesc& to, const CFloatHandle& toData, int startPos, bool isRev ) override;
CTimeConvolutionDesc* InitTimeConvolution( const CBlobDesc& source, int stride, int paddingFront, int paddingBack,
int dilation, const CBlobDesc& filter, const CBlobDesc& result ) override;
void BlobTimeConvolution( const CTimeConvolutionDesc& desc, const CConstFloatHandle& source,
const CConstFloatHandle& filter, const CConstFloatHandle& freeTerm, const CFloatHandle& result ) override;
void BlobTimeConvolutionBackward( const CTimeConvolutionDesc& desc, const CConstFloatHandle& outputDiff,
const CConstFloatHandle& filter, const CConstFloatHandle& freeTerm, const CFloatHandle& inputDiff ) override;
void BlobTimeConvolutionLearnAdd( const CTimeConvolutionDesc& desc, const CConstFloatHandle& input,
const CConstFloatHandle& outputDiff, const CFloatHandle& filterDiff, const CFloatHandle& freeTermDiff ) override;
C3dConvolutionDesc* InitBlob3dConvolution( const CBlobDesc& input,
int paddingHeight, int paddingWidth, int paddingDepth, int strideHeight, int strideWidth, int strideDepth,
const CBlobDesc& filter, const CBlobDesc& output ) override;
void Blob3dConvolution( const C3dConvolutionDesc& desc, const CConstFloatHandle& source,
const CConstFloatHandle& filter, const CConstFloatHandle* freeTerm, const CFloatHandle& result ) override;
void Blob3dConvolutionBackward( const C3dConvolutionDesc& desc, const CConstFloatHandle& source,
const CConstFloatHandle& filter, const CConstFloatHandle* freeTerm, const CFloatHandle& result ) override;
void Blob3dConvolutionLearnAdd( const C3dConvolutionDesc& desc, const CConstFloatHandle& input,
const CConstFloatHandle& outputDiff, const CFloatHandle& filterDiff,
const CFloatHandle* freeTermDiff, bool isFreeTermDiffFromInput ) override;
CConvolutionDesc* InitBlobConvolution( const CBlobDesc& input, int paddingHeight, int paddingWidth,
int strideHeight, int strideWidth, int dilationHeight, int dilationWidth, const CBlobDesc& filter, const CBlobDesc& output ) override;
void BlobConvolution( const CConvolutionDesc& convDesc,
const CConstFloatHandle& source, const CConstFloatHandle& filter, const CConstFloatHandle* freeTerm,
const CFloatHandle& result ) override;
void BlobConvolutionBackward( const CConvolutionDesc& desc, const CConstFloatHandle& outputDiff,
const CConstFloatHandle& filter, const CConstFloatHandle* freeTerm, const CFloatHandle& inputDiff ) override;
void BlobConvolutionLearnAdd( const CConvolutionDesc& desc,
const CConstFloatHandle& input, const CConstFloatHandle& outputDiff, const CFloatHandle& filterDiff,
const CFloatHandle* freeTermDiff, bool isFreeTermDiffFromInput ) override;
CChannelwiseConvolutionDesc* InitBlobChannelwiseConvolution( const CBlobDesc& input,
int paddingHeight, int paddingWidth, int strideHeight, int strideWidth,
const CBlobDesc& filter, const CBlobDesc* freeTerm, const CBlobDesc& output ) override;
void BlobChannelwiseConvolution( const CChannelwiseConvolutionDesc& desc, const CConstFloatHandle& source,
const CConstFloatHandle& filter, const CConstFloatHandle* freeTerm, const CFloatHandle& result ) override;
void BlobChannelwiseConvolutionBackward( const CChannelwiseConvolutionDesc& convDesc,
const CConstFloatHandle& source, const CConstFloatHandle& filter, const CFloatHandle& result ) override;
void BlobChannelwiseConvolutionLearnAdd( const CChannelwiseConvolutionDesc& convDesc,
const CConstFloatHandle& input, const CConstFloatHandle& outputDiff, const CFloatHandle& filterDiff,
const CFloatHandle* freeTermDiff ) override;
CGlobalMaxPoolingDesc* InitGlobalMaxPooling( const CBlobDesc& source, const CBlobDesc& maxIndices, const CBlobDesc& result ) override;
void BlobGlobalMaxPooling( const CGlobalMaxPoolingDesc& desc,
const CConstFloatHandle& source, const CIntHandle& maxIndices, const CFloatHandle& result ) override;
void BlobGlobalMaxPoolingBackward( const CGlobalMaxPoolingDesc& desc,
const CConstFloatHandle& resultDiff, const CConstIntHandle& maxIndices, const CFloatHandle& sourceDiff ) override;
C3dMaxPoolingDesc* Init3dMaxPooling( const CBlobDesc& source,
int filterHeight, int filterWidth, int filterDepth,
int strideHeight, int strideWidth, int strideDepth, const CBlobDesc& result ) override;
void Blob3dMaxPooling( const C3dMaxPoolingDesc& desc, const CConstFloatHandle& source,
const CIntHandle* maxIndices, const CFloatHandle& result ) override;
void Blob3dMaxPoolingBackward( const C3dMaxPoolingDesc& desc, const CConstFloatHandle& resultDiff,
const CConstIntHandle& maxIndices, const CFloatHandle& sourceDiff ) override;
C3dMeanPoolingDesc* Init3dMeanPooling( const CBlobDesc& source,
int filterHeight, int filterWidth, int filterDepth,
int strideHeight, int strideWidth, int strideDepth,
const CBlobDesc& result ) override;
void Blob3dMeanPooling( const C3dMeanPoolingDesc& desc, const CConstFloatHandle& source, const CFloatHandle& result ) override;
void Blob3dMeanPoolingBackward( const C3dMeanPoolingDesc& desc, const CConstFloatHandle& resultDiff, const CFloatHandle& sourceDiff ) override;
CMaxPoolingDesc* InitMaxPooling( const CBlobDesc& source,
int filterHeight, int filterWidth, int strideHeight, int strideWidth,
const CBlobDesc& result ) override;
void BlobMaxPooling( const CMaxPoolingDesc& desc, const CConstFloatHandle& source,
const CIntHandle* maxIndices, const CFloatHandle& result ) override;
void BlobMaxPoolingBackward( const CMaxPoolingDesc& desc, const CConstFloatHandle& resultDiff,
const CConstIntHandle& maxIndices, const CFloatHandle& sourceDiff ) override;
CMaxOverTimePoolingDesc* InitMaxOverTimePooling( const CBlobDesc& source, int filterLen, int strideLen, const CBlobDesc& result ) override;
void BlobMaxOverTimePooling( const CMaxOverTimePoolingDesc& desc, const CConstFloatHandle& source,
const CIntHandle* maxIndices, const CFloatHandle& result ) override;
void BlobMaxOverTimePoolingBackward( const CMaxOverTimePoolingDesc& desc, const CConstFloatHandle& resultDiff,
const CConstIntHandle& maxIndices, const CFloatHandle& sourceDiff ) override;
CMeanPoolingDesc* InitMeanPooling( const CBlobDesc& source,
int filterHeight, int filterWidth, int strideHeight, int strideWidth,
const CBlobDesc& result ) override;
void BlobMeanPooling( const CMeanPoolingDesc& desc, const CConstFloatHandle& source, const CFloatHandle& result ) override;
void BlobMeanPoolingBackward( const CMeanPoolingDesc& desc, const CConstFloatHandle& resultDiff, const CFloatHandle& sourceDiff ) override;
CGlobalMaxOverTimePoolingDesc* InitGlobalMaxOverTimePooling( const CBlobDesc& source, const CBlobDesc& result ) override;
void BlobGlobalMaxOverTimePooling( const CGlobalMaxOverTimePoolingDesc& desc, const CConstFloatHandle& source, const CIntHandle* maxIndices,
const CFloatHandle& result ) override;
void BlobGlobalMaxOverTimePoolingBackward( const CGlobalMaxOverTimePoolingDesc& desc, const CConstFloatHandle& resultDiff,
const CConstIntHandle& maxIndices, const CFloatHandle& sourceDiff ) override;
void Upsampling2DForward( const CBlobDesc& input, const CConstIntHandle& inputData, int heightCopyCount,
int widthCopyCount, const CBlobDesc& result, const CIntHandle& resultData ) override;
void Upsampling2DForward( const CBlobDesc& input, const CConstFloatHandle& inputData, int heightCopyCount,
int widthCopyCount, const CBlobDesc& result, const CFloatHandle& resultData ) override;
void Upsampling2DBackward( const CBlobDesc& input, const CConstFloatHandle& inputData, int heightCopyCount,
int widthCopyCount, const CBlobDesc& result, const CFloatHandle& resultData ) override;
void BuildIntegerHist( const CConstIntHandle& numbersHandle, int numbersCount,
const CIntHandle& resultHandle, int maxNumber ) override;
void MatrixRowsToVectorSquaredL2Distance( const CConstFloatHandle& matrixHandle, const int matrixHeight,
const int matrixWidth, const CConstFloatHandle& vectorHandle, const CFloatHandle& resultHandle ) override;
CRleConvolutionDesc* InitBlobRleConvolution( const CBlobDesc& input, float strokeValue,
float nonStrokeValue, int strideHeight, int strideWidth, const CBlobDesc& filter,
const CBlobDesc& output ) override;
void BlobRleConvolution( const CRleConvolutionDesc& desc, const CConstFloatHandle& source,
const CConstFloatHandle& filter, const CConstFloatHandle* freeTerm, const CFloatHandle& result ) override;
void BlobRleConvolutionLearnAdd( const CRleConvolutionDesc& desc, const CConstFloatHandle& input,
const CConstFloatHandle& outputDiff, const CFloatHandle& filterDiff, const CFloatHandle* freeTermDiff ) override;
void Reorg( const CBlobDesc& source, const CFloatHandle& sourceData, int stride, bool isForward,
const CBlobDesc& result, const CFloatHandle& resultData ) override;
void Reorg( const CBlobDesc& source, const CIntHandle& sourceData, int stride, bool isForward,
const CBlobDesc& result, const CIntHandle& resultData ) override;
void SpaceToDepth( const CBlobDesc& source, const CConstFloatHandle& sourceData, int blockSize,
const CBlobDesc& result, const CFloatHandle& resultData ) override;
void SpaceToDepth( const CBlobDesc& source, const CConstIntHandle& sourceData, int blockSize,
const CBlobDesc& result, const CIntHandle& resultData ) override;
void DepthToSpace( const CBlobDesc& source, const CConstFloatHandle& sourceData, int blockSize,
const CBlobDesc& result, const CFloatHandle& resultData ) override;
void DepthToSpace( const CBlobDesc& source, const CConstIntHandle& sourceData, int blockSize,
const CBlobDesc& result, const CIntHandle& resultData ) override;
void AddWidthIndex( const CBlobDesc& source, const CConstFloatHandle& sourceData, bool isForward, const CFloatHandle& result ) override;
void AddWidthIndex( const CBlobDesc& source, const CConstIntHandle& sourceData, bool isForward, const CIntHandle& result ) override;
void AddHeightIndex( const CBlobDesc& source, const CConstFloatHandle& sourceData, bool isForward, const CFloatHandle& result ) override;
void AddHeightIndex( const CBlobDesc& source, const CConstIntHandle& sourceData, bool isForward, const CIntHandle& result ) override;
CDropoutDesc* InitDropout( float rate, bool isSpatial, bool isBatchwise, const CBlobDesc& input,
const CBlobDesc& output, int seed ) override;
void Dropout( const CDropoutDesc& desc, const CFloatHandle& input, const CFloatHandle& output ) override;
void QrnnFPooling( bool reverse, int sequenceLength, int objectSize,
const CConstFloatHandle& update, const CConstFloatHandle& forget, const CConstFloatHandle& initialState,
const CFloatHandle& result ) override;
void QrnnFPoolingBackward( bool reverse, int sequenceLength, int objectSize,
const CConstFloatHandle& update, const CConstFloatHandle& forget,
const CConstFloatHandle& initialState, const CConstFloatHandle& result, const CFloatHandle& resultDiff,
const CFloatHandle& updateDiff, const CFloatHandle& forgetDiff ) override;
void QrnnIfPooling( bool reverse, int sequenceLength, int objectSize,
const CConstFloatHandle& update, const CConstFloatHandle& forget, const CConstFloatHandle& input,
const CConstFloatHandle& initialState, const CFloatHandle& result ) override;
void QrnnIfPoolingBackward( bool reverse, int sequenceLength, int objectSize,
const CConstFloatHandle& update, const CConstFloatHandle& forget, const CConstFloatHandle& input,
const CConstFloatHandle& initialState, const CConstFloatHandle& result, const CFloatHandle& resultDiff,
const CFloatHandle& updateDiff, const CFloatHandle& forgetDiff, const CFloatHandle& inputDiff ) override;
void IndRnnRecurrent( bool reverse, int sequenceLength, int batchSize, int objectSize, TActivationFunction activation,
const CConstFloatHandle& wx, const CConstFloatHandle& mask, const CConstFloatHandle& u,
const CFloatHandle& h ) override;
void IndRnnRecurrentBackward( bool reverse, int sequenceLength, int batchSize, int objectSize, TActivationFunction activation,
const CConstFloatHandle& mask, const CConstFloatHandle& u, const CConstFloatHandle& h, const CConstFloatHandle& hDiff,
const CFloatHandle& wxDiff ) override;
void IndRnnRecurrentLearn( bool reverse, int sequenceLength, int batchSize, int objectSize, TActivationFunction activation,
const CConstFloatHandle& mask, const CConstFloatHandle& u, const CConstFloatHandle& h, const CConstFloatHandle& hDiff,
const CFloatHandle& uDiff ) override;
CLrnDesc* InitLrn( const CBlobDesc& source, int windowSize, float bias, float alpha, float beta ) override;
void Lrn( const CLrnDesc& desc, const CConstFloatHandle& input, const CFloatHandle& invSum,
const CFloatHandle& invSumBeta, const CFloatHandle& outputHandle ) override;
void LrnBackward( const CLrnDesc& desc, const CConstFloatHandle& input, const CConstFloatHandle& output,
const CConstFloatHandle& outputDiff, const CConstFloatHandle& invSum, const CConstFloatHandle& invSumBeta,
const CFloatHandle& inputDiff ) override;
void CtcLossForward( int resultLen, int batchSize, int classCount, int labelLen, int blankLabel, bool skipBlanks,
const CConstFloatHandle& result, const CConstIntHandle& labels,
const CConstIntHandle& labelLens, const CConstIntHandle& resultLens, const CConstFloatHandle& labelWeights,
const CFloatHandle& loss, const CFloatHandle& lossGradient ) override;
void BertConv( const CConstFloatHandle& dataHandle, const CConstFloatHandle& kernelHandle, int seqLen, int batchSize,
int numHeads, int headSize, int kernelSize, const CFloatHandle& outputHandle ) override;
void BertConvBackward( const CConstFloatHandle& dataHandle, const CConstFloatHandle& kernelHandle,
const CConstFloatHandle& outDiffHandle, int seqLen, int batchSize, int numHeads, int headSize, int kernelSize,
const CFloatHandle& dataDiffHandle, const CFloatHandle& kernelDiffHandle ) override;
CLstmDesc* InitLstm( bool isCompatibleMode, int hiddenSize, int objectSize,
const CConstFloatHandle& inputWeights, const CConstFloatHandle& inputFreeTerm,
const CConstFloatHandle& recurrentWeights, const CConstFloatHandle& recurrentFreeTerm ) override;
void Lstm( CLstmDesc& desc, bool reverse, int sequenceLength, int sequenceCount,
const CConstFloatHandle& inputStateBackLink, const CConstFloatHandle& inputMainBackLink,
const CConstFloatHandle& input, const CFloatHandle& outputStateBackLink,
const CFloatHandle& outputMainBackLink ) override;
void LinearInterpolation( const CConstFloatHandle& dataHandle, const CFloatHandle& resultHandle,
TInterpolationCoords coords, TInterpolationRound round, int objectCount, int scaledAxis,
int objectSize, float scale ) override;
void ScatterND( const CConstIntHandle& indicesHandle, const CConstFloatHandle& updatesHandle,
const CFloatHandle& dataHandle, const CBlobDesc& dataDesc, int updateCount, int indexDims ) override;
void ScatterND( const CConstIntHandle& indicesHandle, const CConstIntHandle& updatesHandle,
const CIntHandle& dataHandle, const CBlobDesc& dataDesc, int updateCount, int indexDims ) override;
void ChannelwiseWith1x1( const CBlobDesc& inputDesc, const CBlobDesc& outputDesc,
const CRowwiseOperationDesc& rowwiseDesc, const CChannelwiseConvolutionDesc& convDesc,
const CConstFloatHandle& inputHandle, const CFloatHandle& outputHandle ) override;
void MobileNetV2Block( const CBlobDesc& inputDesc, const CBlobDesc& outputDesc,
const CRowwiseOperationDesc& rowwiseDesc, const CChannelwiseConvolutionDesc& convDesc,
const CConstFloatHandle& inputHandle, const CFloatHandle& outputHandle ) override;
void MobileNetV3PreSEBlock( const CBlobDesc& inputDesc, const CBlobDesc& outputDesc,
const CChannelwiseConvolutionDesc& convDesc, const CConstFloatHandle& inputHandle,
const CConstFloatHandle& expandFilter, const CConstFloatHandle* expandFreeTerm,
TActivationFunction expandActivation, float expandReluParam, const CConstFloatHandle& channelwiseFilter,
const CConstFloatHandle* channelwiseFreeTerm, TActivationFunction channelwiseActivation,
float channelwiseReluParam, const CFloatHandle& outputHandle ) override;
void MobileNetV3PostSEBlock( const CBlobDesc& channelwiseOutputDesc, int outputChannels,
const CConstFloatHandle& channelwiseOutputHandle, const CConstFloatHandle& squeezeAndExciteHandle,
const CConstFloatHandle* residualHandle, TActivationFunction activation, float reluParam,
const CConstFloatHandle& downFilterHandle, const CConstFloatHandle* downFreeTermHandle,
const CFloatHandle& outputHandle ) override;
CRowwiseOperationDesc* InitRowwiseActivation( const CActivationDesc& desc ) override;
CRowwiseOperationDesc* InitRowwiseChWith1x1( int stride, const CConstFloatHandle& channelwiseFilter,
const CConstFloatHandle* channelwiseFreeTerm, TActivationFunction activation, float reluParam,
const CConstFloatHandle& convFilter, const CConstFloatHandle* convFreeTerm,
int outputChannels, bool residual ) override;
CRowwiseOperationDesc* InitRowwiseConv( int paddingHeight, int paddingWidth, int strideHeight,
int strideWidth, int dilationHeight, int dilationWidth, const CBlobDesc& filterDesc,
const CConstFloatHandle& filter, const CConstFloatHandle* freeTerm ) override;
CRowwiseOperationDesc* InitRowwiseChConv( int paddingHeight, int paddingWidth, int strideHeight,
int strideWidth, const CBlobDesc& filterDesc, const CConstFloatHandle& filter,
const CConstFloatHandle* freeTerm ) override;
CRowwiseOperationDesc* InitRowwiseResizeImage( TBlobResizePadding padding, float defaultValue,
int deltaLeft, int deltaRight, int deltaTop, int deltaBottom ) override;
CRowwiseOperationDesc* InitRowwiseMobileNetV2( int inputChannels,
const CConstFloatHandle& expandFilter, const CConstFloatHandle* expandFreeTerm, int expandedChannels,
TActivationFunction expandActivation, float expandReluParam,
const CConstFloatHandle& channelwiseFilter, const CConstFloatHandle* channelwiseFreeTerm, int stride,
TActivationFunction channelwiseActivation, float channelwiseReluParam,
const CConstFloatHandle& downFilter, const CConstFloatHandle* downFreeTerm,
int outputChannels, bool residual ) override;
CRowwiseOperationDesc* InitRowwise2DPooling( bool isMax, int filterHeight, int filterWidth,
int strideHeight, int strideWidth ) override;
CBlobDesc RowwiseReshape( CRowwiseOperationDesc** operations, int operationCount,
const CBlobDesc& input ) override;
void RowwiseExecute( const CBlobDesc& inputDesc, CRowwiseOperationDesc** operations, int operationCount,
const CFloatHandle& input, const CFloatHandle& output ) override;
IPerformanceCounters* CreatePerformanceCounters( bool isOnlyTime ) const override;
// For Distributed only
void AllReduce( const CFloatHandle& handle, int size ) override;
void Broadcast( const CFloatHandle& handle, int size, int root ) override;
void AbortDistributed() override;
CMathEngineDistributedInfo GetDistributedInfo() override { return distributedInfo; }
bool IsDistributed() const override { return distributedInfo.Threads > 1; }
protected:
// IRawMemoryManager interface methods
CMemoryHandle Alloc( size_t size ) override;
void Free( const CMemoryHandle& handle ) override;
void CleanUpSpecial() override;
private:
const int floatAlignment; // float alignment
std::shared_ptr<CMultiThreadDistributedCommunicator> communicator;
CMathEngineDistributedInfo distributedInfo;
CDllLoader dllLoader; // loading library for simd instructions
std::unique_ptr<ISimdMathEngine> simdMathEngine; // interface for using simd instructions
SgemmFunc customSgemmFunction = nullptr; // Used when it is availabled and is faster then default sgemm
IMathEngine& mathEngine() { IMathEngine* engine = this; return *engine; }
void blob3dConvolution1x1x1( const CBlobDesc& source, const CBlobDesc& result,
int strideHeight, int strideWidth, int strideDepth,
const float* sourceData, const float* filterData, const float* freeTermData, float* resultData );
void blob3dConvolution1x1x1Backward( const CCommon3dConvolutionDesc& desc, const float* outputDiffData,
const float* filterData, const CConstFloatHandle* freeTermData, float* inputDiffData );
void blob3dConvolution1x1x1LearnAdd( const CCommon3dConvolutionDesc& desc, const CConstFloatHandle& inputData,
const CConstFloatHandle& outputDiffData, const CFloatHandle& filterDiffData, const CFloatHandle* freeTermDiffData );
void blob3dConvolution( const CCommon3dConvolutionDesc& desc, const float* sourceData,
const float* filterData, const CConstFloatHandle* freeTermData, float* resultData );
void blob3dConvolutionBackward( const CCommon3dConvolutionDesc& desc, const float* sourceData,
const CConstFloatHandle& filterData, const CConstFloatHandle* freeTermData, float* resultData );
void blob3dConvolutionLearnAdd( const CCommon3dConvolutionDesc& desc,
const float* inputData, const float* outputDiffData, const CFloatHandle& filterDiffData,
const CFloatHandle* freeTermDiffData, bool isFreeTermDiffFromInput );
void blob3dConvolutionPrepareInput( const CCommon3dConvolutionDesc& desc, float* inputPreparedData,
const float* inputBlobData, int inputObject, int outputHeight, int outputWidthExStart, int outputWidthExCount );
void setVectorToMatrixRows( float* result, int matrixHeight, int matrixWidth, const float* vector );
void addVectorToMatrixRows( const float* matrix, float* result,
int matrixHeight, int matrixWidth, int matrixRowSize, int resultRowSize, const float* vector );
void addMatrixToMatrix( float* first, int height,
int width, int firstRowSize, const float* second, int secondRowSize );
void sumMatrixRowsAdd( float* result, const float* matrix,
int matrixHeight, int matrixWidth );
void sumMatrixColumnsAdd( const CFloatHandle& resultHandle, const CConstFloatHandle& matrixHandle,
int matrixHeight, int matrixWidth );
void multiplyMatrixByMatrix( const float* firstHandle, int firstHeight,
int firstWidth, int firstRowSize, const float* secondHandle, int secondWidth, int secondRowSize,
float* resultHandle, int resultRowSize );
void multiplyMatrixByMatrixAndAdd( const float* first, int firstHeight,
int firstWidth, int firstRowSize, const float* second, int secondWidth, int secondRowSize,
float* result, int resultRowSize );
void multiplyTransposedMatrixByMatrix( const float* first, int firstHeight, int firstWidth,
const float* second, int secondWidth, float* result );
void batchMultiplyTransposedMatrixByMatrix( int batchSize, const float* first, int firstHeight, int firstWidth,
const float* second, int secondWidth, float* result );
void multiplyTransposedMatrixByMatrixAndAdd( const float* first, int firstHeight, int firstWidth, int firstRowSize,
const float* second, int secondWidth, int secondRowSize, float* result, int resultRowSize );
void multiplyMatrixByTransposedMatrix( const float* first, int firstHeight,
int firstWidth, int firstRowSize, const float* second, int secondHeight, int secondRowSize,
float* result, int resultRowSize );
void batchMultiplyMatrixByTransposedMatrix( int batchSize, const CConstFloatHandle& firstHandle, int firstHeight,
int firstWidth, const CConstFloatHandle& secondHandle, int secondHeight, const CFloatHandle& resultHandle );
void multiplyMatrixByTransposedMatrixAndAdd( const float* first, int firstHeight, int firstWidth, int firstRowSize,
const float* second, int secondHeight, int secondRowSize, float* result, int resultRowSize );
void multiplyMatrixByDiagMatrix( const float* first, int firstHeight, int firstWidth,
const float* second, float* result );
void multiplyMatrixByTransposedWithFreeTerm( const float* first, int firstHeight,
int firstWidth, const float* second, int secondHeight, const float* freeTerm, float* result );
template<class T>
void blobMergeByDimCommon( int dimNum, const CBlobDesc* from, const CTypedMemoryHandle<T>* fromData,
int fromCount, const CBlobDesc& to, const CTypedMemoryHandle<T>& toData );
template<class T>
void blobMergeByDim0( const CBlobDesc* from, const CTypedMemoryHandle<T>* fromData, int fromCount,
const CBlobDesc& to, const CTypedMemoryHandle<T>& toData );
template<class T>
void blobMergeByDim( int dim, const CBlobDesc* from, const CTypedMemoryHandle<T>* fromData,
int fromCount, const CBlobDesc& to, const CTypedMemoryHandle<T>& toData );
template<class T>
void blobSplitByDimCommon( int dimNum, const CBlobDesc& from, const CTypedMemoryHandle<const T>& fromData,
const CBlobDesc* to, const CTypedMemoryHandle<T>* toData, int toCount );
template<class T>
void blobSplitByDim0( const CBlobDesc& from, const CTypedMemoryHandle<const T>& fromData,
const CBlobDesc* to, const CTypedMemoryHandle<T>* toData, int toCount );
template<class T>
void blobSplitByDim( int dim, const CBlobDesc& from, const CTypedMemoryHandle<const T>& fromData,
const CBlobDesc* to, const CTypedMemoryHandle<T>* toData, int toCount );
template<typename T>
void transposeMatrixImpl( int batchSize, const T* firstHandle,
int height, int medium, int width, int channels, T* resultHandle );
void transposeMatrix( int batchSize, const float* firstHandle,
int height, int medium, int width, int channels, float* resultHandle );
void transposeMatrix( int batchSize, const int* firstHandle,
int height, int medium, int width, int channels, int* resultHandle );
void createDilationTemporaryBlob( const CCpuConvolutionDesc& desc, const float* inputBlob, int inputBatch,
int outputColumnStart, int outputColumnCount, float* temporaryBlob );
template<class TConvolutionDesc>
void createTemporaryBlob( const TConvolutionDesc& desc, const float* inputData,
int inputBatch, int outputRowStart, int outputRowCount, float* tempBlob );
void transposeResult( const CCpuConvolutionDesc& desc, const float* outputTransposedData,
int batch, int resultStart, int resultCount, float* result );
void fillTempData( const float* sourceData, float* filterData, const CCpuConvolutionDesc& desc, int start, int count );
void blobConvolutionForwardAlgo0( const CCpuConvolutionDesc& desc, const float* sourceData,
const float* filterData, const CConstFloatHandle* freeTermData, float* resultData );
void blobConvolutionForwardAlgo1( const CCpuConvolutionDesc& desc, const float* sourceData,
const float* filterData, const CConstFloatHandle* freeTermData, float* resultData );
void blobConvolutionBackwardAlgo1( const CCpuConvolutionDesc& desc,
const CConstFloatHandle& sourceData, const CConstFloatHandle& filterData, const CConstFloatHandle* freeTerm,
const CFloatHandle& resultData );
void fillTempBlobsForLearnAlgo2( const CCpuConvolutionDesc& desc, const CConstFloatHandle& sourceData,
const CBlobDesc& tempDesc, const CFloatHandle& tempHandle );
void blobConvolutionBackwardAlgo2( const CCpuConvolutionDesc& desc, const CConstFloatHandle& sourceData,
const CConstFloatHandle& filterData, const CConstFloatHandle* freeTerm, const CFloatHandle& resultData );
void blobConvolutionLearnAlgo1( const CCpuConvolutionDesc& desc,
const CConstFloatHandle& input, const CConstFloatHandle& outputDiff, const CFloatHandle& filterDiff,
const CFloatHandle* freeTermDiff, bool isFreeTermDiffFromInput );
void blobConvolutionLearnAlgo2( const CCpuConvolutionDesc& desc, const CConstFloatHandle& input,
const CConstFloatHandle& outputDiff, const CFloatHandle& filterDiff, const CFloatHandle* freeTermDiff,
bool isFreeTermDiffFromInput );
void findMaxValueInColumns( float* result, const float* matrixHandle,
int matrixHeight, int matrixWidth );
void findMaxValueInColumns( float* resultHandle, int* rowIndices,
const float* matrixHandle, int matrixHeight, int matrixWidth );
void blobMaxPoolingWithIndices( const CCommonMaxPoolingDesc& desc, const float* sourceData,
int* maxIndicesData, float* resultData );
void blobMaxPoolingWithoutIndices( const CCommon2DPoolingDesc& desc, int resultRowsToProcess,
const float* sourceData, int sourceRowIndex, float* resultData, int resultRowIndex, float* bufferPtr );
void vectorEltwiseLogSumExp( const CConstFloatHandle& firstHandle, const CConstFloatHandle& secondHandle,
const CFloatHandle& resultHandle, int vectorSize );
void ctcCalcForwardVariables( int resultLen, int batchSize, int classCount, int padLabelLen, bool skipBlanks,
const CConstIntHandle& rowIndices, const CConstIntHandle& padLabels, const CConstFloatHandle& blankSkipMask,
const CConstFloatHandle& resultLogProb, const CFloatHandle& logAlpha );
void ctcCalcBackwardVariables( int resultLen, int batchSize, int classCount, int padLabelLen, bool skipBlanks,
const CConstIntHandle& rowIndices, const CConstIntHandle& padLabels, const CConstFloatHandle& blankSkipMask,
const CConstFloatHandle& resultLogProb, const CConstIntHandle& resultLens, const CConstIntHandle& labelLens,
const CFloatHandle& logBeta );
class CCpuRowwiseConv;
class CCpuRowwiseChConvWith1x1;
class CCpuRowwiseMobileNetV2;
class CCpuRowwise2DPooling;
};
inline void CCpuMathEngine::VectorReLUDiffOp( const CConstFloatHandle& firstHandle, const CConstFloatHandle& secondHandle,
const CFloatHandle& resultHandle, int vectorSize, const CConstFloatHandle& upperThresholdHandle )
{
VectorReLUDiff( firstHandle, secondHandle, resultHandle, vectorSize, upperThresholdHandle );
}
inline void CCpuMathEngine::VectorLeakyReLUDiffOp( const CConstFloatHandle& firstHandle,
const CConstFloatHandle& secondHandle, const CFloatHandle& resultHandle,
int vectorSize, const CConstFloatHandle& alpha )
{
VectorLeakyReLUDiff( firstHandle, secondHandle, resultHandle, vectorSize, alpha );
}
inline void CCpuMathEngine::VectorHardTanhDiffOp( const CConstFloatHandle& firstHandle, const CConstFloatHandle& secondHandle,
const CFloatHandle& resultHandle, int vectorSize )
{
VectorHardTanhDiff( firstHandle, secondHandle, resultHandle, vectorSize );
}
} // namespace NeoML
| 1 | 0.806095 | 1 | 0.806095 | game-dev | MEDIA | 0.559778 | game-dev,graphics-rendering | 0.502948 | 1 | 0.502948 |
SethRobinson/aitools_client | 3,107 | Assets/RT/AI/AnthropicStreamingDownloadHandler.cs | using SimpleJSON;
using System;
using System.Text;
using UnityEngine;
using UnityEngine.Networking;
public class AnthropicStreamingDownloadHandler : DownloadHandlerScript
{
private Action<string> m_textChunkUpdateCallback;
private StringBuilder stringBuilder = new StringBuilder();
private StringBuilder incompleteChunk = new StringBuilder();
public AnthropicStreamingDownloadHandler(Action<string> textChunkUpdateCallback) : base(new byte[1024])
{
m_textChunkUpdateCallback = textChunkUpdateCallback;
}
protected override bool ReceiveData(byte[] data, int dataLength)
{
if (data == null || dataLength == 0)
{
Debug.LogWarning("Received a null/empty buffer");
return false;
}
string text = Encoding.UTF8.GetString(data, 0, dataLength);
ProcessChunk(text);
return true;
}
protected void ProcessChunk(string chunk)
{
incompleteChunk.Append(chunk);
string fullChunk = incompleteChunk.ToString();
string[] events = fullChunk.Split(new[] { "\n" }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < events.Length; i++)
{
string event_data = events[i].Trim();
if (event_data.StartsWith("data: "))
{
string jsonData = event_data.Substring(6); // Remove "data: " prefix
if (jsonData == "[DONE]")
{
// Stream finished
continue;
}
ProcessJsonChunk(jsonData);
}
}
// Keep any remaining incomplete data
int lastNewLineIndex = fullChunk.LastIndexOf("\n");
if (lastNewLineIndex >= 0 && lastNewLineIndex < fullChunk.Length - 1)
{
incompleteChunk.Clear();
incompleteChunk.Append(fullChunk.Substring(lastNewLineIndex + 1));
}
else
{
incompleteChunk.Clear();
}
}
protected void ProcessJsonChunk(string jsonChunk)
{
try
{
JSONNode rootNode = JSON.Parse(jsonChunk);
if (rootNode["type"] == "content_block_delta" && rootNode["delta"] != null && rootNode["delta"]["text"] != null)
{
string content = rootNode["delta"]["text"];
stringBuilder.Append(content);
MainThreadDispatcher.Enqueue(() => m_textChunkUpdateCallback(content));
}
}
catch (Exception ex)
{
Debug.LogWarning($"Error processing JSON chunk: {ex.Message}\nChunk: {jsonChunk}");
}
}
protected override void CompleteContent()
{
Debug.Log("Download complete!");
// Process any remaining data in incompleteChunk
if (incompleteChunk.Length > 0)
{
ProcessChunk("\n"); // Force processing of the last chunk
}
}
public string GetContent()
{
return stringBuilder.ToString();
}
protected override string GetText()
{
return GetContent();
}
} | 1 | 0.880186 | 1 | 0.880186 | game-dev | MEDIA | 0.510434 | game-dev | 0.921444 | 1 | 0.921444 |
seehuhn/moon-buggy | 3,843 | meteor.c | /* meteor.c - stones on the moon to shoot at
*
* Copyright 1999, 2000 Jochen Voss. */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "moon-buggy.h"
#include "darray.h"
enum meteor_state { ms_START, ms_BIG, ms_MEDIUM, ms_SMALL };
static char m_image [] = { 'O', 'O', 'o', ',' };
struct meteor {
enum meteor_state state;
int x;
};
static struct {
struct meteor **data;
int slots, used;
} meteor_table;
static void
score_meteor (struct meteor *m)
{
adjust_score (13);
bonus[m->x] -= 20;
}
static int
scroll_one_meteor (struct meteor *m)
/* Move the meteor *M along with the ground.
* Check for collisions with the car or with laser beams.
* Return 1 iff the meteor should be removed from the list. */
{
if (m->state == ms_START) {
m->state = ms_BIG;
} else {
mvwaddch (moon, BASELINE, m->x, ' ');
}
m->x += 1;
if (m->x >= COLS ) return 1;
if (laser_hit (m->x)) {
m->state += 1;
if (m->state > ms_SMALL) {
score_meteor (m);
return 1;
}
}
if (car_meteor_hit (m->x)) return 1;
mvwaddch (moon, BASELINE, m->x, m_image[m->state]);
return 0;
}
void
scroll_meteors (void)
/* Move the meteors along with the ground.
* Handle collisions with the car or with laser beams. */
{
int j;
if (meteor_table.used > 0) wnoutrefresh (moon);
for (j=meteor_table.used-1; j>=0; --j) {
struct meteor *m = meteor_table.data[j];
int res;
res = scroll_one_meteor (m);
if (res) {
DA_REMOVE (meteor_table, struct meteor *, j);
free (m);
}
}
}
void
place_meteor (void)
/* Place a new meteor on the ground. */
{
struct meteor *m;
if (! meteor_table.data) DA_INIT (meteor_table, struct meteor *);
m = xmalloc (sizeof (struct meteor));
m->state = ms_START;
m->x = 0;
bonus[0] += 20;
DA_ADD (meteor_table, struct meteor *, m);
}
void
remove_meteors (void)
/* Remove all meteors from the ground.
* Free any resources used by the internal representation. */
{
int j;
if (meteor_table.used > 0) wnoutrefresh (moon);
for (j=0; j<meteor_table.used; ++j) {
struct meteor *m = meteor_table.data[j];
mvwaddch (moon, BASELINE, m->x, ' ');
free (m);
}
DA_CLEAR (meteor_table);
}
int
meteor_laser_hit (int x0, int x1)
/* Check for meteors at positions >=x0 and <x1.
* All these are hit by the laser.
* Return true, if there are any hits. */
{
int j;
for (j=0; j<meteor_table.used; ++j) {
struct meteor *m = meteor_table.data[j];
if (m->x >= x0 && m->x < x1) {
int x = m->x;
m->state += 1;
wnoutrefresh (moon);
if (m->state > ms_SMALL) {
mvwaddch (moon, BASELINE, m->x, ' ');
score_meteor (m);
remove_client_data (m);
DA_REMOVE_VALUE (meteor_table, struct meteor *, m);
free (m);
} else {
mvwaddch (moon, BASELINE, m->x, m_image[m->state]);
}
return x;
}
}
return 0;
}
int
meteor_car_hit (int x0, int x1)
/* Check for meteors at positions >=x0 and <x1.
* All these are destroyed by the landing car.
* Return true, if there are any hits. */
{
int j;
int res = 0;
for (j=meteor_table.used-1; j>=0; --j) {
struct meteor *m = meteor_table.data[j];
if (m->x >= x0 && m->x < x1) {
mvwaddch (moon, BASELINE, m->x, ' ');
remove_client_data (m);
DA_REMOVE_VALUE (meteor_table, struct meteor *, m);
free (m);
res = 1;
}
}
if (res) wnoutrefresh (moon);
return res;
}
void
resize_meteors (void)
/* Silently remove all meteors, which are no longer visible. */
{
int j;
j = 0;
while (j<meteor_table.used) {
struct meteor *m = meteor_table.data[j];
if (m->x >= COLS) {
remove_client_data (m);
DA_REMOVE_VALUE (meteor_table, struct meteor *, m);
free (m);
} else {
++j;
}
}
}
| 1 | 0.864698 | 1 | 0.864698 | game-dev | MEDIA | 0.813074 | game-dev | 0.874003 | 1 | 0.874003 |
IAFEnvoy/IceAndFire-CE | 2,202 | common/src/main/java/com/iafenvoy/iceandfire/item/block/GhostChestBlock.java | package com.iafenvoy.iceandfire.item.block;
import com.iafenvoy.iceandfire.item.block.entity.GhostChestBlockEntity;
import com.iafenvoy.iceandfire.registry.IafBlockEntities;
import net.minecraft.block.BlockState;
import net.minecraft.block.ChestBlock;
import net.minecraft.block.MapColor;
import net.minecraft.block.entity.BlockEntity;
import net.minecraft.block.entity.ChestBlockEntity;
import net.minecraft.block.enums.NoteBlockInstrument;
import net.minecraft.item.ItemStack;
import net.minecraft.loot.context.LootContextParameterSet;
import net.minecraft.sound.BlockSoundGroup;
import net.minecraft.stat.Stat;
import net.minecraft.stat.Stats;
import net.minecraft.util.Identifier;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Direction;
import net.minecraft.util.math.MathHelper;
import net.minecraft.world.BlockView;
import java.util.List;
public class GhostChestBlock extends ChestBlock {
public GhostChestBlock() {
super(Settings.create().mapColor(MapColor.OAK_TAN).instrument(NoteBlockInstrument.BASS).burnable().strength(2.5F).sounds(BlockSoundGroup.WOOD), IafBlockEntities.GHOST_CHEST::get);
}
@Override
public BlockEntity createBlockEntity(BlockPos pos, BlockState state) {
return new GhostChestBlockEntity(pos, state);
}
@Override
protected Stat<Identifier> getOpenStat() {
return Stats.CUSTOM.getOrCreateStat(Stats.TRIGGER_TRAPPED_CHEST);
}
@Override
public boolean emitsRedstonePower(BlockState state) {
return true;
}
@Override
public int getWeakRedstonePower(BlockState blockState, BlockView blockAccess, BlockPos pos, Direction side) {
return MathHelper.clamp(ChestBlockEntity.getPlayersLookingInChestCount(blockAccess, pos), 0, 15);
}
@Override
public List<ItemStack> getDroppedStacks(BlockState state, LootContextParameterSet.Builder builder) {
return super.getDroppedStacks(state, builder);
}
@Override
public int getStrongRedstonePower(BlockState blockState, BlockView blockAccess, BlockPos pos, Direction side) {
return side == Direction.UP ? blockState.getWeakRedstonePower(blockAccess, pos, side) : 0;
}
}
| 1 | 0.846998 | 1 | 0.846998 | game-dev | MEDIA | 0.999513 | game-dev | 0.855142 | 1 | 0.855142 |
gurrenm3/BTD-Mod-Helper | 1,609 | BloonsTD6 Mod Helper/Api/ModOptions/ModSettingInt.cs | using System;
using Il2CppTMPro;
namespace BTD_Mod_Helper.Api.ModOptions;
/// <summary>
/// ModSetting for int values
/// </summary>
public class ModSettingInt : ModSettingNumber<long> //it's a long because of JSON parsing
{
/// <summary>
/// Old way of doing slider
/// </summary>
[Obsolete("Use slider instead")]
public bool isSlider;
/// <summary>
/// Old way of doing max
/// </summary>
[Obsolete("Use max instead")]
public long? maxValue;
/// <summary>
/// Old way of doing min
/// </summary>
[Obsolete("Use min instead")]
public long? minValue;
/// <inheritdoc />
public ModSettingInt(int value) : base(value)
{
}
/// <inheritdoc />
protected override TMP_InputField.CharacterValidation Validation => TMP_InputField.CharacterValidation.Integer;
/// <summary>
/// Constructs a new ModSetting with the given value as default
/// </summary>
public static implicit operator ModSettingInt(int value) => new(value);
/// <summary>
/// Gets the current value out of a ModSetting
/// </summary>
public static implicit operator int(ModSettingInt modSettingInt) => (int) modSettingInt.value;
/// <inheritdoc />
protected override string ToString(long input) => input.ToString();
/// <inheritdoc />
protected override long FromString(string s) => int.TryParse(s, out var result) ? result : 0;
/// <inheritdoc />
protected override float ToFloat(long input) => input;
/// <inheritdoc />
protected override long FromFloat(float f) => (long) Math.Round(f);
} | 1 | 0.943636 | 1 | 0.943636 | game-dev | MEDIA | 0.418585 | game-dev | 0.845466 | 1 | 0.845466 |
SkelletonX/DDTank4.1 | 6,412 | Source Flash/scripts/ddt/view/caddyII/badLuck/BadLuckView.as | package ddt.view.caddyII.badLuck
{
import com.pickgliss.ui.ComponentFactory;
import com.pickgliss.ui.controls.SelectedButton;
import com.pickgliss.ui.controls.SelectedButtonGroup;
import com.pickgliss.ui.core.Disposeable;
import com.pickgliss.ui.image.Scale9CornerImage;
import com.pickgliss.ui.text.FilterFrameText;
import com.pickgliss.utils.ObjectUtils;
import ddt.events.PlayerPropertyEvent;
import ddt.manager.PlayerManager;
import ddt.manager.RouletteManager;
import ddt.manager.SoundManager;
import ddt.view.caddyII.CaddyEvent;
import ddt.view.caddyII.reader.CaddyReadAwardsView;
import ddt.view.caddyII.reader.CaddyUpdate;
import flash.display.Bitmap;
import flash.display.Sprite;
import flash.events.MouseEvent;
public class BadLuckView extends Sprite implements Disposeable, CaddyUpdate
{
private var _bg1:Scale9CornerImage;
private var _bg2:Bitmap;
private var _awardBtn:SelectedButton;
private var _badLuckBtn:SelectedButton;
private var _group:SelectedButtonGroup;
private var _lastTimeTxt:FilterFrameText;
private var _myNumberTxt:FilterFrameText;
private var _caddyBadLuckView:CaddyBadLuckView;
private var _readView:CaddyReadAwardsView;
public function BadLuckView()
{
super();
this.initView();
this.initEvents();
}
private function initView() : void
{
this._bg1 = ComponentFactory.Instance.creatComponentByStylename("caddy.readAwardsBGI");
this._bg2 = ComponentFactory.Instance.creatBitmap("asset.caddy.badLuck.MyNumberBG");
this._group = new SelectedButtonGroup();
this._awardBtn = ComponentFactory.Instance.creatComponentByStylename("caddy.badLuck.awardBtn");
this._badLuckBtn = ComponentFactory.Instance.creatComponentByStylename("caddy.badLuck.bacLuckBtn");
this._group.addSelectItem(this._badLuckBtn);
this._group.addSelectItem(this._awardBtn);
this._caddyBadLuckView = ComponentFactory.Instance.creatCustomObject("card.CaddyBadLuckView");
this._readView = ComponentFactory.Instance.creatCustomObject("caddy.CaddyReadAwardsView");
this._lastTimeTxt = ComponentFactory.Instance.creatComponentByStylename("caddy.badLuck.lastTimeTxt");
this._myNumberTxt = ComponentFactory.Instance.creatComponentByStylename("caddy.badLuck.MyNumberTxt");
addChild(this._bg1);
addChild(this._bg2);
addChild(this._awardBtn);
addChild(this._badLuckBtn);
addChild(this._caddyBadLuckView);
addChild(this._readView);
addChild(this._lastTimeTxt);
addChild(this._myNumberTxt);
this._myNumberTxt.text = PlayerManager.Instance.Self.badLuckNumber.toString();
this._group.selectIndex = 1;
this._caddyBadLuckView.visible = false;
}
private function initEvents() : void
{
this._awardBtn.addEventListener(MouseEvent.CLICK,this.__awardBtnClick);
this._badLuckBtn.addEventListener(MouseEvent.CLICK,this.__badLuckBtnClick);
RouletteManager.instance.addEventListener(CaddyEvent.UPDATE_BADLUCK,this.__updateLastTime);
PlayerManager.Instance.Self.addEventListener(PlayerPropertyEvent.PROPERTY_CHANGE,this.__changeBadLuckNumber);
}
private function removeEvents() : void
{
this._awardBtn.removeEventListener(MouseEvent.CLICK,this.__awardBtnClick);
this._badLuckBtn.removeEventListener(MouseEvent.CLICK,this.__badLuckBtnClick);
RouletteManager.instance.removeEventListener(CaddyEvent.UPDATE_BADLUCK,this.__updateLastTime);
PlayerManager.Instance.Self.removeEventListener(PlayerPropertyEvent.PROPERTY_CHANGE,this.__changeBadLuckNumber);
}
private function __awardBtnClick(param1:MouseEvent) : void
{
SoundManager.instance.play("008");
this._caddyBadLuckView.visible = false;
this._readView.visible = true;
}
private function __badLuckBtnClick(param1:MouseEvent) : void
{
SoundManager.instance.play("008");
this._caddyBadLuckView.visible = true;
this._readView.visible = false;
}
private function __updateLastTime(param1:CaddyEvent) : void
{
this._lastTimeTxt.text = "最后更新 " + param1.lastTime;
}
private function __changeBadLuckNumber(param1:PlayerPropertyEvent) : void
{
if(param1.changedProperties["BadLuckNumber"])
{
if(PlayerManager.Instance.Self.badLuckNumber == 0)
{
this._myNumberTxt.text = PlayerManager.Instance.Self.badLuckNumber.toString();
}
}
}
public function update() : void
{
this._readView.update();
this._myNumberTxt.text = PlayerManager.Instance.Self.badLuckNumber.toString();
}
public function dispose() : void
{
this.removeEvents();
if(this._bg1)
{
ObjectUtils.disposeObject(this._bg1);
}
this._bg1 = null;
if(this._bg2)
{
ObjectUtils.disposeObject(this._bg2);
}
this._bg2 = null;
if(this._awardBtn)
{
ObjectUtils.disposeObject(this._awardBtn);
}
this._awardBtn = null;
if(this._badLuckBtn)
{
ObjectUtils.disposeObject(this._badLuckBtn);
}
this._badLuckBtn = null;
this._group = null;
if(this._lastTimeTxt)
{
ObjectUtils.disposeObject(this._lastTimeTxt);
}
this._lastTimeTxt = null;
if(this._myNumberTxt)
{
ObjectUtils.disposeObject(this._myNumberTxt);
}
this._myNumberTxt = null;
if(this._caddyBadLuckView)
{
ObjectUtils.disposeObject(this._caddyBadLuckView);
}
this._caddyBadLuckView = null;
if(this._readView)
{
ObjectUtils.disposeObject(this._readView);
}
this._readView = null;
ObjectUtils.disposeAllChildren(this);
if(parent)
{
parent.removeChild(this);
}
}
}
}
| 1 | 0.917338 | 1 | 0.917338 | game-dev | MEDIA | 0.764896 | game-dev | 0.941733 | 1 | 0.941733 |
plutoprint/plutobook | 16,565 | source/htmltokenizer.h | #ifndef PLUTOBOOK_HTMLTOKENIZER_H
#define PLUTOBOOK_HTMLTOKENIZER_H
#include "document.h"
#include <span>
namespace plutobook {
class HTMLToken {
public:
enum class Type : uint8_t {
Unknown,
DOCTYPE,
StartTag,
EndTag,
Comment,
Character,
SpaceCharacter,
EndOfFile
};
explicit HTMLToken(Heap* heap)
: m_heap(heap)
{}
Type type() const { return m_type; }
bool selfClosing() const { return m_selfClosing; }
bool forceQuirks() const { return m_forceQuirks; }
bool hasPublicIdentifier() const { return m_hasPublicIdentifier; }
bool hasSystemIdentifier() const { return m_hasSystemIdentifier; }
const std::string& publicIdentifier() const { return m_publicIdentifier; }
const std::string& systemIdentifier() const { return m_systemIdentifier; }
const std::string& data() const { return m_data; }
const std::vector<Attribute>& attributes() const { return m_attributes; }
std::vector<Attribute>& attributes() { return m_attributes; }
void beginStartTag() {
assert(m_type == Type::Unknown);
m_type = Type::StartTag;
m_selfClosing = false;
m_attributes.clear();
m_data.clear();
}
void beginEndTag() {
assert(m_type == Type::Unknown);
m_type = Type::EndTag;
m_selfClosing = false;
m_attributes.clear();
m_data.clear();
}
void setSelfClosing() {
assert(m_type == Type::StartTag || m_type == Type::EndTag);
m_selfClosing = true;
}
void addToTagName(char cc) {
assert(m_type == Type::StartTag || m_type == Type::EndTag);
m_data += cc;
}
void beginAttribute() {
assert(m_type == Type::StartTag || m_type == Type::EndTag);
m_attributeName.clear();
m_attributeValue.clear();
}
void addToAttributeName(char cc) {
assert(m_type == Type::StartTag || m_type == Type::EndTag);
m_attributeName += cc;
}
void addToAttributeValue(char cc) {
assert(m_type == Type::StartTag || m_type == Type::EndTag);
m_attributeValue += cc;
}
void addToAttributeValue(const std::string& data) {
assert(m_type == Type::StartTag || m_type == Type::EndTag);
m_attributeValue += data;
}
void endAttribute() {
assert(m_type == Type::StartTag || m_type == Type::EndTag);
auto name = GlobalString(m_attributeName);
auto value = m_heap->createString(m_attributeValue);
m_attributes.emplace_back(name, value);
}
void beginComment() {
assert(m_type == Type::Unknown);
m_type = Type::Comment;
m_data.clear();
}
void addToComment(char cc) {
assert(m_type == Type::Comment);
m_data += cc;
}
void beginCharacter() {
assert(m_type == Type::Unknown);
m_type = Type::Character;
m_data.clear();
}
void addToCharacter(char cc) {
assert(m_type == Type::Character);
m_data += cc;
}
void addToCharacter(const std::string& data) {
assert(m_type == Type::Character);
m_data += data;
}
void beginSpaceCharacter() {
assert(m_type == Type::Unknown);
m_type = Type::SpaceCharacter;
m_data.clear();
}
void addToSpaceCharacter(char cc) {
assert(m_type == Type::SpaceCharacter);
m_data += cc;
}
void beginDOCTYPE() {
assert(m_type == Type::Unknown);
m_type = Type::DOCTYPE;
m_forceQuirks = false;
m_hasPublicIdentifier = false;
m_hasSystemIdentifier = false;
m_publicIdentifier.clear();
m_systemIdentifier.clear();
m_data.clear();
}
void setForceQuirks() {
assert(m_type == Type::DOCTYPE);
m_forceQuirks = true;
}
void addToDOCTYPEName(char cc) {
assert(m_type == Type::DOCTYPE);
m_data += cc;
}
void setPublicIdentifier() {
assert(m_type == Type::DOCTYPE);
m_hasPublicIdentifier = true;
m_publicIdentifier.clear();
}
void setSystemIdentifier() {
assert(m_type == Type::DOCTYPE);
m_hasSystemIdentifier = true;
m_systemIdentifier.clear();
}
void addToPublicIdentifier(char cc) {
assert(m_type == Type::DOCTYPE);
m_publicIdentifier += cc;
}
void addToSystemIdentifier(char cc) {
assert(m_type == Type::DOCTYPE);
m_systemIdentifier += cc;
}
void setEndOfFile() {
m_type = Type::EndOfFile;
m_data.clear();
}
void reset() {
m_type = Type::Unknown;
m_data.clear();
}
private:
Heap* m_heap;
Type m_type{Type::Unknown};
bool m_selfClosing{false};
bool m_forceQuirks{false};
bool m_hasPublicIdentifier{false};
bool m_hasSystemIdentifier{false};
std::string m_publicIdentifier;
std::string m_systemIdentifier;
std::string m_attributeName;
std::string m_attributeValue;
std::vector<Attribute> m_attributes;
std::string m_data;
};
class HTMLTokenView {
public:
HTMLTokenView(HTMLToken& token)
: m_type(token.type())
{
switch(m_type) {
case HTMLToken::Type::DOCTYPE:
m_forceQuirks = token.forceQuirks();
m_hasPublicIdentifier = token.hasPublicIdentifier();
m_hasSystemIdentifier = token.hasSystemIdentifier();
m_publicIdentifier = token.publicIdentifier();
m_systemIdentifier = token.systemIdentifier();
m_data = token.data();
case HTMLToken::Type::StartTag:
case HTMLToken::Type::EndTag:
m_selfClosing = token.selfClosing();
m_tagName = GlobalString(token.data());
m_attributes = token.attributes();
break;
case HTMLToken::Type::Comment:
case HTMLToken::Type::Character:
case HTMLToken::Type::SpaceCharacter:
m_data = token.data();
break;
default:
break;
}
}
HTMLTokenView(HTMLToken::Type type, const GlobalString& tagName)
: m_type(type), m_tagName(tagName)
{}
HTMLToken::Type type() const { return m_type; }
bool selfClosing() const { return m_selfClosing; }
bool forceQuirks() const { return m_forceQuirks; }
bool hasPublicIdentifier() const { return m_hasPublicIdentifier; }
bool hasSystemIdentifier() const { return m_hasSystemIdentifier; }
const std::string_view& publicIdentifier() const { return m_publicIdentifier; }
const std::string_view& systemIdentifier() const { return m_systemIdentifier; }
const GlobalString& tagName() const { return m_tagName; }
const std::span<Attribute>& attributes() const { return m_attributes; }
const std::string_view& data() const { return m_data; }
bool hasCamelCase() const { return m_hasCamelCase; }
void setHasCamelCase(bool value) { m_hasCamelCase = value; }
const Attribute* findAttribute(const GlobalString& name) const {
assert(m_type == HTMLToken::Type::StartTag || m_type == HTMLToken::Type::EndTag);
for(const auto& attribute : m_attributes) {
if(name == attribute.name()) {
return &attribute;
}
}
return nullptr;
}
bool hasAttribute(const GlobalString& name) const {
assert(m_type == HTMLToken::Type::StartTag || m_type == HTMLToken::Type::EndTag);
for(const auto& attribute : m_attributes) {
if(name == attribute.name()) {
return true;
}
}
return false;
}
void adjustTagName(const GlobalString& newName) {
assert(m_type == HTMLToken::Type::StartTag || m_type == HTMLToken::Type::EndTag);
m_tagName = newName;
}
void skipLeadingNewLine() {
assert(m_type == HTMLToken::Type::SpaceCharacter);
if(m_data.front() == '\n') {
m_data.remove_prefix(1);
}
}
private:
HTMLToken::Type m_type;
bool m_selfClosing{false};
bool m_forceQuirks{false};
bool m_hasPublicIdentifier{false};
bool m_hasSystemIdentifier{false};
bool m_hasCamelCase{false};
std::string_view m_publicIdentifier;
std::string_view m_systemIdentifier;
GlobalString m_tagName;
std::span<Attribute> m_attributes;
std::string_view m_data;
};
class HTMLTokenizer {
public:
enum class State {
Data,
CharacterReferenceInData,
RCDATA,
CharacterReferenceInRCDATA,
RAWTEXT,
ScriptData,
PLAINTEXT,
TagOpen,
EndTagOpen,
TagName,
RCDATALessThanSign,
RCDATAEndTagOpen,
RCDATAEndTagName,
RAWTEXTLessThanSign,
RAWTEXTEndTagOpen,
RAWTEXTEndTagName,
ScriptDataLessThanSign,
ScriptDataEndTagOpen,
ScriptDataEndTagName,
ScriptDataEscapeStart,
ScriptDataEscapeStartDash,
ScriptDataEscaped,
ScriptDataEscapedDash,
ScriptDataEscapedDashDash,
ScriptDataEscapedLessThanSign,
ScriptDataEscapedEndTagOpen,
ScriptDataEscapedEndTagName,
ScriptDataDoubleEscapeStart,
ScriptDataDoubleEscaped,
ScriptDataDoubleEscapedDash,
ScriptDataDoubleEscapedDashDash,
ScriptDataDoubleEscapedLessThanSign,
ScriptDataDoubleEscapeEnd,
BeforeAttributeName,
AttributeName,
AfterAttributeName,
BeforeAttributeValue,
AttributeValueDoubleQuoted,
AttributeValueSingleQuoted,
AttributeValueUnquoted,
CharacterReferenceInAttributeValue,
AfterAttributeValueQuoted,
SelfClosingStartTag,
BogusComment,
MarkupDeclarationOpen,
CommentStart,
CommentStartDash,
Comment,
CommentEndDash,
CommentEnd,
CommentEndBang,
DOCTYPE,
BeforeDOCTYPEName,
DOCTYPEName,
AfterDOCTYPEName,
AfterDOCTYPEPublicKeyword,
BeforeDOCTYPEPublicIdentifier,
DOCTYPEPublicIdentifierDoubleQuoted,
DOCTYPEPublicIdentifierSingleQuoted,
AfterDOCTYPEPublicIdentifier,
BetweenDOCTYPEPublicAndSystemIdentifiers,
AfterDOCTYPESystemKeyword,
BeforeDOCTYPESystemIdentifier,
DOCTYPESystemIdentifierDoubleQuoted,
DOCTYPESystemIdentifierSingleQuoted,
AfterDOCTYPESystemIdentifier,
BogusDOCTYPE,
CDATASection,
CDATASectionRightSquareBracket, //
CDATASectionDoubleRightSquareBracket //
};
HTMLTokenizer(const std::string_view& content, Heap* heap)
: m_input(content), m_currentToken(heap)
{}
HTMLTokenView nextToken();
State state() const { return m_state; }
void setState(State state) { m_state = state; }
bool atEOF() const { return m_currentToken.type() == HTMLToken::Type::EndOfFile; }
private:
bool handleState(char cc);
bool handleDataState(char cc);
bool handleCharacterReferenceInDataState(char cc);
bool handleRCDATAState(char cc);
bool handleCharacterReferenceInRCDATAState(char cc);
bool handleRAWTEXTState(char cc);
bool handleScriptDataState(char cc);
bool handlePLAINTEXTState(char cc);
bool handleTagOpenState(char cc);
bool handleEndTagOpenState(char cc);
bool handleTagNameState(char cc);
bool handleRCDATALessThanSignState(char cc);
bool handleRCDATAEndTagOpenState(char cc);
bool handleRCDATAEndTagNameState(char cc);
bool handleRAWTEXTLessThanSignState(char cc);
bool handleRAWTEXTEndTagOpenState(char cc);
bool handleRAWTEXTEndTagNameState(char cc);
bool handleScriptDataLessThanSignState(char cc);
bool handleScriptDataEndTagOpenState(char cc);
bool handleScriptDataEndTagNameState(char cc);
bool handleScriptDataEscapeStartState(char cc);
bool handleScriptDataEscapeStartDashState(char cc);
bool handleScriptDataEscapedState(char cc);
bool handleScriptDataEscapedDashState(char cc);
bool handleScriptDataEscapedDashDashState(char cc);
bool handleScriptDataEscapedLessThanSignState(char cc);
bool handleScriptDataEscapedEndTagOpenState(char cc);
bool handleScriptDataEscapedEndTagNameState(char cc);
bool handleScriptDataDoubleEscapeStartState(char cc);
bool handleScriptDataDoubleEscapedState(char cc);
bool handleScriptDataDoubleEscapedDashState(char cc);
bool handleScriptDataDoubleEscapedDashDashState(char cc);
bool handleScriptDataDoubleEscapedLessThanSignState(char cc);
bool handleScriptDataDoubleEscapeEndState(char cc);
bool handleBeforeAttributeNameState(char cc);
bool handleAttributeNameState(char cc);
bool handleAfterAttributeNameState(char cc);
bool handleBeforeAttributeValueState(char cc);
bool handleAttributeValueDoubleQuotedState(char cc);
bool handleAttributeValueSingleQuotedState(char cc);
bool handleAttributeValueUnquotedState(char cc);
bool handleCharacterReferenceInAttributeValueState(char cc);
bool handleAfterAttributeValueQuotedState(char cc);
bool handleSelfClosingStartTagState(char cc);
bool handleBogusCommentState(char cc);
bool handleMarkupDeclarationOpenState(char cc);
bool handleCommentStartState(char cc);
bool handleCommentStartDashState(char cc);
bool handleCommentState(char cc);
bool handleCommentEndDashState(char cc);
bool handleCommentEndState(char cc);
bool handleCommentEndBangState(char cc);
bool handleDOCTYPEState(char cc);
bool handleBeforeDOCTYPENameState(char cc);
bool handleDOCTYPENameState(char cc);
bool handleAfterDOCTYPENameState(char cc);
bool handleAfterDOCTYPEPublicKeywordState(char cc);
bool handleBeforeDOCTYPEPublicIdentifierState(char cc);
bool handleDOCTYPEPublicIdentifierDoubleQuotedState(char cc);
bool handleDOCTYPEPublicIdentifierSingleQuotedState(char cc);
bool handleAfterDOCTYPEPublicIdentifierState(char cc);
bool handleBetweenDOCTYPEPublicAndSystemIdentifiersState(char cc);
bool handleAfterDOCTYPESystemKeywordState(char cc);
bool handleBeforeDOCTYPESystemIdentifierState(char cc);
bool handleDOCTYPESystemIdentifierDoubleQuotedState(char cc);
bool handleDOCTYPESystemIdentifierSingleQuotedState(char cc);
bool handleAfterDOCTYPESystemIdentifierState(char cc);
bool handleBogusDOCTYPEState(char cc);
bool handleCDATASectionState(char cc);
bool handleCDATASectionRightSquareBracketState(char cc);
bool handleCDATASectionDoubleRightSquareBracketState(char cc);
bool advanceTo(State state);
bool switchTo(State state);
bool emitCurrentToken();
bool emitEOFToken();
bool emitEndTagToken();
bool flushCharacterBuffer();
bool flushEndTagNameBuffer();
bool flushTemporaryBuffer();
bool isAppropriateEndTag() const { return m_appropriateEndTagName == m_endTagNameBuffer; }
bool temporaryBufferIs(const std::string_view& value) const { return m_temporaryBuffer == value; }
char nextInputCharacter();
char handleInputCharacter(char inputCharacter);
bool consumeCharacterReference(std::string& output, bool inAttributeValue);
bool consumeString(const std::string_view& value, bool caseSensitive);
std::string_view m_input;
std::string m_entityBuffer;
std::string m_characterBuffer;
std::string m_temporaryBuffer;
std::string m_endTagNameBuffer;
std::string m_appropriateEndTagName;
State m_state{State::Data};
bool m_reconsumeCurrentCharacter{true};
char m_additionalAllowedCharacter{0};
HTMLToken m_currentToken;
};
inline bool HTMLTokenizer::advanceTo(State state)
{
m_state = state;
m_reconsumeCurrentCharacter = false;
return true;
}
inline bool HTMLTokenizer::switchTo(State state)
{
m_state = state;
m_reconsumeCurrentCharacter = true;
return true;
}
inline char HTMLTokenizer::nextInputCharacter()
{
if(!m_input.empty()) {
if(m_reconsumeCurrentCharacter)
return handleInputCharacter(m_input.front());
m_input.remove_prefix(1);
}
if(!m_input.empty())
return handleInputCharacter(m_input.front());
return 0;
}
inline char HTMLTokenizer::handleInputCharacter(char inputCharacter)
{
if(inputCharacter != '\r')
return inputCharacter;
if(m_input.size() > 1 && m_input[1] == '\n')
m_input.remove_prefix(1);
return '\n';
}
} // namespace plutobook
#endif // PLUTOBOOK_HTMLTOKENIZER_H
| 1 | 0.894244 | 1 | 0.894244 | game-dev | MEDIA | 0.273078 | game-dev | 0.697486 | 1 | 0.697486 |
ImLegiitXD/Ambient | 1,504 | src/main/java/net/minecraft/network/rcon/RConConsoleSource.java | package net.minecraft.network.rcon;
import net.minecraft.command.CommandResultStats;
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.Entity;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.BlockPos;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.IChatComponent;
import net.minecraft.util.Vec3;
import net.minecraft.world.World;
public class RConConsoleSource implements ICommandSender {
private static final RConConsoleSource instance = new RConConsoleSource();
private final StringBuffer buffer = new StringBuffer();
public String getName() {
return "Rcon";
}
public IChatComponent getDisplayName() {
return new ChatComponentText(this.getName());
}
public void addChatMessage(IChatComponent component) {
this.buffer.append(component.getUnformattedText());
}
public boolean canCommandSenderUseCommand(int permLevel, String commandName) {
return true;
}
public BlockPos getPosition() {
return new BlockPos(0, 0, 0);
}
public Vec3 getPositionVector() {
return new Vec3(0.0D, 0.0D, 0.0D);
}
public World getEntityWorld() {
return MinecraftServer.getServer().getEntityWorld();
}
public Entity getCommandSenderEntity() {
return null;
}
public boolean sendCommandFeedback() {
return true;
}
public void setCommandStat(CommandResultStats.Type type, int amount) {
}
}
| 1 | 0.644607 | 1 | 0.644607 | game-dev | MEDIA | 0.973639 | game-dev | 0.817616 | 1 | 0.817616 |
Etheirys/Brio | 1,596 | Brio/UI/Controls/Editors/ActorEditor.cs | using Brio.Capabilities.Actor;
using Brio.Entities.Actor;
using Brio.UI.Controls.Core;
using Dalamud.Bindings.ImGui;
using Dalamud.Interface.Utility;
using Dalamud.Interface.Utility.Raii;
namespace Brio.UI.Controls.Editors;
public class ActorEditor
{
public unsafe static void DrawSpawnMenu(ActorContainerEntity actorContainerEntity)
{
var hasCapability = actorContainerEntity.TryGetCapability<ActorContainerCapability>(out var capability);
using(ImRaii.Disabled(hasCapability == false))
{
DrawSpawnMenu(capability!);
}
}
private unsafe static void DrawSpawnMenu(ActorContainerCapability actorContainerCapability)
{
using var popup = ImRaii.Popup("ActorEditorDrawSpawnMenuPopup"u8);
if(popup.Success)
{
using(ImRaii.PushColor(ImGuiCol.Button, UIConstants.Transparent))
{
if(ImGui.Button("Spawn Actor"u8, new(155 * ImGuiHelpers.GlobalScale, 0)))
{
actorContainerCapability.CreateCharacter(false, true, forceSpawnActorWithoutCompanion: true);
}
if(ImGui.Button("Spawn Actor with Slot"u8, new(155 * ImGuiHelpers.GlobalScale, 0)))
{
actorContainerCapability.CreateCharacter(true, true);
}
ImGui.Separator();
if(ImGui.Button("Spawn Prop"u8, new(155 * ImGuiHelpers.GlobalScale, 0)))
{
actorContainerCapability.CreateProp(true);
}
}
}
}
}
| 1 | 0.597209 | 1 | 0.597209 | game-dev | MEDIA | 0.921127 | game-dev | 0.643639 | 1 | 0.643639 |
vlad250906/Create-UfoPort | 9,115 | modules/create/src/main/java/com/simibubi/create/content/schematics/cannon/SchematicannonRenderer.java | package com.simibubi.create.content.schematics.cannon;
import com.jozufozu.flywheel.backend.Backend;
import com.jozufozu.flywheel.core.model.ModelUtil;
import com.jozufozu.flywheel.core.virtual.VirtualEmptyBlockGetter;
import com.jozufozu.flywheel.fabric.model.DefaultLayerFilteringBakedModel;
import com.mojang.blaze3d.vertex.PoseStack;
import com.mojang.blaze3d.vertex.VertexConsumer;
import com.mojang.math.Axis;
import com.simibubi.create.AllBlocks;
import com.simibubi.create.AllPartialModels;
import com.simibubi.create.content.schematics.cannon.LaunchedItem.ForBelt;
import com.simibubi.create.content.schematics.cannon.LaunchedItem.ForBlockState;
import com.simibubi.create.content.schematics.cannon.LaunchedItem.ForEntity;
import com.simibubi.create.foundation.blockEntity.renderer.SafeBlockEntityRenderer;
import com.simibubi.create.foundation.render.CachedBufferer;
import com.simibubi.create.foundation.render.SuperByteBuffer;
import io.github.fabricators_of_create.porting_lib_ufo.mixin.accessors.client.accessor.BlockRenderDispatcherAccessor;
import io.github.fabricators_of_create.porting_lib_ufo.models.virtual.FixedLightBakedModel;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.ItemBlockRenderTypes;
import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.client.renderer.block.BlockRenderDispatcher;
import net.minecraft.client.renderer.block.model.ItemTransforms;
import net.minecraft.client.renderer.blockentity.BlockEntityRendererProvider;
import net.minecraft.client.resources.model.BakedModel;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.core.particles.ParticleTypes;
import net.minecraft.util.Mth;
import net.minecraft.util.RandomSource;
import net.minecraft.world.item.ItemDisplayContext;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.phys.Vec3;
public class SchematicannonRenderer extends SafeBlockEntityRenderer<SchematicannonBlockEntity> {
public SchematicannonRenderer(BlockEntityRendererProvider.Context context) {}
@Override
protected void renderSafe(SchematicannonBlockEntity blockEntity, float partialTicks, PoseStack ms,
MultiBufferSource buffer, int light, int overlay) {
boolean blocksLaunching = !blockEntity.flyingBlocks.isEmpty();
if (blocksLaunching)
renderLaunchedBlocks(blockEntity, partialTicks, ms, buffer, light, overlay);
if (Backend.canUseInstancing(blockEntity.getLevel()))
return;
BlockPos pos = blockEntity.getBlockPos();
BlockState state = blockEntity.getBlockState();
double[] cannonAngles = getCannonAngles(blockEntity, pos, partialTicks);
double yaw = cannonAngles[0];
double pitch = cannonAngles[1];
double recoil = getRecoil(blockEntity, partialTicks);
ms.pushPose();
VertexConsumer vb = buffer.getBuffer(RenderType.solid());
SuperByteBuffer connector = CachedBufferer.partial(AllPartialModels.SCHEMATICANNON_CONNECTOR, state);
connector.translate(.5f, 0, .5f);
connector.rotate(Direction.UP, (float) ((yaw + 90) / 180 * Math.PI));
connector.translate(-.5f, 0, -.5f);
connector.light(light)
.renderInto(ms, vb);
SuperByteBuffer pipe = CachedBufferer.partial(AllPartialModels.SCHEMATICANNON_PIPE, state);
pipe.translate(.5f, 15 / 16f, .5f);
pipe.rotate(Direction.UP, (float) ((yaw + 90) / 180 * Math.PI));
pipe.rotate(Direction.SOUTH, (float) (pitch / 180 * Math.PI));
pipe.translate(-.5f, -15 / 16f, -.5f);
pipe.translate(0, -recoil / 100, 0);
pipe.light(light)
.renderInto(ms, vb);
ms.popPose();
}
public static double[] getCannonAngles(SchematicannonBlockEntity blockEntity, BlockPos pos, float partialTicks) {
double yaw;
double pitch;
BlockPos target = blockEntity.printer.getCurrentTarget();
if (target != null) {
// Calculate Angle of Cannon
Vec3 diff = Vec3.atLowerCornerOf(target.subtract(pos));
if (blockEntity.previousTarget != null) {
diff = (Vec3.atLowerCornerOf(blockEntity.previousTarget)
.add(Vec3.atLowerCornerOf(target.subtract(blockEntity.previousTarget))
.scale(partialTicks))).subtract(Vec3.atLowerCornerOf(pos));
}
double diffX = diff.x();
double diffZ = diff.z();
yaw = Mth.atan2(diffX, diffZ);
yaw = yaw / Math.PI * 180;
float distance = Mth.sqrt((float) (diffX * diffX + diffZ * diffZ));
double yOffset = 0 + distance * 2f;
pitch = Mth.atan2(distance, diff.y() * 3 + yOffset);
pitch = pitch / Math.PI * 180 + 10;
} else {
yaw = blockEntity.defaultYaw;
pitch = 40;
}
return new double[] { yaw, pitch };
}
public static double getRecoil(SchematicannonBlockEntity blockEntity, float partialTicks) {
double recoil = 0;
for (LaunchedItem launched : blockEntity.flyingBlocks) {
if (launched.ticksRemaining == 0)
continue;
// Apply Recoil if block was just launched
if ((launched.ticksRemaining + 1 - partialTicks) > launched.totalTicks - 10)
recoil = Math.max(recoil, (launched.ticksRemaining + 1 - partialTicks) - launched.totalTicks + 10);
}
return recoil;
}
private static void renderLaunchedBlocks(SchematicannonBlockEntity blockEntity, float partialTicks, PoseStack ms,
MultiBufferSource buffer, int light, int overlay) {
for (LaunchedItem launched : blockEntity.flyingBlocks) {
if (launched.ticksRemaining == 0)
continue;
// Calculate position of flying block
Vec3 start = Vec3.atCenterOf(blockEntity.getBlockPos()
.above());
Vec3 target = Vec3.atCenterOf(launched.target);
Vec3 distance = target.subtract(start);
double yDifference = target.y - start.y;
double throwHeight = Math.sqrt(distance.lengthSqr()) * .6f + yDifference;
Vec3 cannonOffset = distance.add(0, throwHeight, 0)
.normalize()
.scale(2);
start = start.add(cannonOffset);
yDifference = target.y - start.y;
float progress =
((float) launched.totalTicks - (launched.ticksRemaining + 1 - partialTicks)) / launched.totalTicks;
Vec3 blockLocationXZ = target.subtract(start)
.scale(progress)
.multiply(1, 0, 1);
// Height is determined through a bezier curve
float t = progress;
double yOffset = 2 * (1 - t) * t * throwHeight + t * t * yDifference;
Vec3 blockLocation = blockLocationXZ.add(0.5, yOffset + 1.5, 0.5)
.add(cannonOffset);
// Offset to position
ms.pushPose();
ms.translate(blockLocation.x, blockLocation.y, blockLocation.z);
ms.translate(.125f, .125f, .125f);
ms.mulPose(Axis.YP.rotationDegrees(360 * t));
ms.mulPose(Axis.XP.rotationDegrees(360 * t));
ms.translate(-.125f, -.125f, -.125f);
if (launched instanceof ForBlockState) {
// Render the Block
BlockState state;
if (launched instanceof ForBelt) {
// Render a shaft instead of the belt
state = AllBlocks.SHAFT.getDefaultState();
} else {
state = ((ForBlockState) launched).state;
}
float scale = .3f;
ms.scale(scale, scale, scale);
// Minecraft.getInstance()
// .getBlockRenderer()
// .renderSingleBlock(state, ms, buffer, light, overlay);
BlockRenderDispatcher dispatcher = Minecraft.getInstance()
.getBlockRenderer();
switch (state.getRenderShape()) {
case MODEL -> {
BakedModel model = dispatcher.getBlockModel(state);
model = DefaultLayerFilteringBakedModel.wrap(model);
model = FixedLightBakedModel.wrap(model, light);
dispatcher.getModelRenderer()
.tesselateBlock(VirtualEmptyBlockGetter.INSTANCE, model, state, BlockPos.ZERO, ms, buffer.getBuffer(ItemBlockRenderTypes.getRenderType(state, false)), false, RandomSource.create(), 42L, overlay);
}
case ENTITYBLOCK_ANIMATED -> ((BlockRenderDispatcherAccessor) dispatcher).getBlockEntityRenderer().renderByItem(new ItemStack(state.getBlock()), ItemDisplayContext.NONE, ms, buffer, light, overlay);
}
} else if (launched instanceof ForEntity) {
// Render the item
float scale = 1.2f;
ms.scale(scale, scale, scale);
Minecraft.getInstance()
.getItemRenderer()
.renderStatic(launched.stack, ItemDisplayContext.GROUND, light, overlay, ms, buffer, blockEntity.getLevel(), 0);
}
ms.popPose();
// Render particles for launch
if (launched.ticksRemaining == launched.totalTicks && blockEntity.firstRenderTick) {
start = start.subtract(.5, .5, .5);
blockEntity.firstRenderTick = false;
for (int i = 0; i < 10; i++) {
RandomSource r = blockEntity.getLevel()
.getRandom();
double sX = cannonOffset.x * .01f;
double sY = (cannonOffset.y + 1) * .01f;
double sZ = cannonOffset.z * .01f;
double rX = r.nextFloat() - sX * 40;
double rY = r.nextFloat() - sY * 40;
double rZ = r.nextFloat() - sZ * 40;
blockEntity.getLevel()
.addParticle(ParticleTypes.CLOUD, start.x + rX, start.y + rY, start.z + rZ, sX, sY, sZ);
}
}
}
}
@Override
public boolean shouldRenderOffScreen(SchematicannonBlockEntity blockEntity) {
return true;
}
@Override
public int getViewDistance() {
return 128;
}
}
| 1 | 0.871037 | 1 | 0.871037 | game-dev | MEDIA | 0.864289 | game-dev,graphics-rendering | 0.937394 | 1 | 0.937394 |
microsoft/TextWorld | 2,149 | textworld/envs/wrappers/filter.py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT license.
from typing import Tuple, Mapping, Any
from textworld.core import GameState, Wrapper
class Filter(Wrapper):
"""
Environment wrapper to filter what information is made available.
Requested information will be included within the `infos` dictionary
returned by `Filter.reset()` and `Filter.step(...)`. To request
specific information, create a
:py:class:`textworld.EnvInfos <textworld.core.EnvInfos>`
and set the appropriate attributes to `True`. Then, instantiate a `Filter`
wrapper with the `EnvInfos` object.
Example:
Here is an example of how to request information and retrieve it.
>>> from textworld import EnvInfos
>>> from textworld.envs.wrappers import Filter
>>> request_infos = EnvInfos(description=True, inventory=True, extras=["more"])
>>> env = textworld.start(gamefile, request_infos)
>>> env = Filter(env)
>>> ob, infos = env.reset()
>>> print(infos["description"])
>>> print(infos["inventory"])
>>> print(infos["extra.more"])
"""
def _get_requested_infos(self, game_state: GameState):
infos = {attr: getattr(game_state, attr) for attr in self.request_infos.basics}
if self.request_infos.extras:
for attr in self.request_infos.extras:
key = "extra.{}".format(attr)
infos[key] = game_state.get(key)
return infos
def step(self, command: str) -> Tuple[str, Mapping[str, Any]]:
game_state, score, done = super().step(command)
ob = game_state.feedback
infos = self._get_requested_infos(game_state)
return ob, score, done, infos
def reset(self) -> Tuple[str, Mapping[str, Any]]:
game_state = super().reset()
ob = game_state.feedback
infos = self._get_requested_infos(game_state)
return ob, infos
def copy(self) -> "Filter":
env = Filter()
env._wrapped_env = self._wrapped_env.copy()
env.request_infos = self.request_infos
return env
| 1 | 0.585932 | 1 | 0.585932 | game-dev | MEDIA | 0.741178 | game-dev | 0.529436 | 1 | 0.529436 |
austinmao/reduxity | 4,260 | Assets/Plugins/UniRx/Scripts/Operators/ToObservable.cs | using System;
using System.Collections.Generic;
namespace UniRx.Operators
{
internal class ToObservableObservable<T> : OperatorObservableBase<T>
{
readonly IEnumerable<T> source;
readonly IScheduler scheduler;
public ToObservableObservable(IEnumerable<T> source, IScheduler scheduler)
: base(scheduler == Scheduler.CurrentThread)
{
this.source = source;
this.scheduler = scheduler;
}
protected override IDisposable SubscribeCore(IObserver<T> observer, IDisposable cancel)
{
return new ToObservable(this, observer, cancel).Run();
}
class ToObservable : OperatorObserverBase<T, T>
{
readonly ToObservableObservable<T> parent;
public ToObservable(ToObservableObservable<T> parent, IObserver<T> observer, IDisposable cancel) : base(observer, cancel)
{
this.parent = parent;
}
public IDisposable Run()
{
var e = default(IEnumerator<T>);
try
{
e = parent.source.GetEnumerator();
}
catch (Exception exception)
{
OnError(exception);
return Disposable.Empty;
}
if (parent.scheduler == Scheduler.Immediate)
{
while (true)
{
bool hasNext;
var current = default(T);
try
{
hasNext = e.MoveNext();
if (hasNext) current = e.Current;
}
catch (Exception ex)
{
e.Dispose();
try { observer.OnError(ex); }
finally { Dispose(); }
break;
}
if (hasNext)
{
observer.OnNext(current);
}
else
{
e.Dispose();
try { observer.OnCompleted(); }
finally { Dispose(); }
break;
}
}
return Disposable.Empty;
}
var flag = new SingleAssignmentDisposable();
flag.Disposable = parent.scheduler.Schedule(self =>
{
if (flag.IsDisposed)
{
e.Dispose();
return;
}
bool hasNext;
var current = default(T);
try
{
hasNext = e.MoveNext();
if (hasNext) current = e.Current;
}
catch (Exception ex)
{
e.Dispose();
try { observer.OnError(ex); }
finally { Dispose(); }
return;
}
if (hasNext)
{
observer.OnNext(current);
self();
}
else
{
e.Dispose();
try { observer.OnCompleted(); }
finally { Dispose(); }
}
});
return flag;
}
public override void OnNext(T value)
{
// do nothing
}
public override void OnError(Exception error)
{
try { observer.OnError(error); }
finally { Dispose(); }
}
public override void OnCompleted()
{
try { observer.OnCompleted(); }
finally { Dispose(); }
}
}
}
} | 1 | 0.93459 | 1 | 0.93459 | game-dev | MEDIA | 0.395848 | game-dev | 0.9848 | 1 | 0.9848 |
tgstation/tgstation | 21,087 | code/__DEFINES/wounds.dm | // ~wound damage/rolling defines
/// the cornerstone of the wound threshold system, your base wound roll for any attack is rand(1, damage^this), after armor reduces said damage. See [/obj/item/bodypart/proc/check_wounding]
#define WOUND_DAMAGE_EXPONENT 1.4
/// any damage dealt over this is ignored for damage rolls unless the target has the frail quirk (25^1.4=91, for reference). Does not apply if the mob has TRAIT_BLOODY_MESS.
/// This is further affected by TRAIT_EASILY_WOUNDED increasing the max considered damage (before applying the exponent) by 50%, and TRAIT_HARDLY_WOUNDED reducing it by 50%.
#define WOUND_MAX_CONSIDERED_DAMAGE 25
/// an attack must do this much damage after armor in order to roll for being a wound (so pressure damage/being on fire doesn't proc it)
#define WOUND_MINIMUM_DAMAGE 5
/// an attack must do this much damage after armor in order to be eliigible to dismember a suitably mushed bodypart
#define DISMEMBER_MINIMUM_DAMAGE 10
/// If an attack rolls this high with their wound (including mods), we try to outright dismember the limb. Note 250 is high enough that with a perfect max roll of 90 (see max cons'd damage), you'd need +60 in mods to do this
#define WOUND_DISMEMBER_OUTRIGHT_THRESH 150
/// set wound_bonus on an item or attack to this to disable checking wounding for the attack
#define CANT_WOUND -100
/// If there are multiple possible and valid wounds for the same type and severity, weight will be used to pick among them. See _wound_pregen_data.dm for more details
/// This is used in pick_weight, so use integers
#define WOUND_DEFAULT_WEIGHT 50
// ~wound severities
/// for jokey/meme wounds like stubbed toe, no standard messages/sounds or second winds
#define WOUND_SEVERITY_TRIVIAL 0
#define WOUND_SEVERITY_MODERATE 1
#define WOUND_SEVERITY_SEVERE 2
#define WOUND_SEVERITY_CRITICAL 3
/// outright dismemberment of limb
#define WOUND_SEVERITY_LOSS 4
// how much blood the limb needs to be losing per tick (not counting laying down/self grasping modifiers) to get the different bleed icons
#define BLEED_OVERLAY_LOW 0.5
#define BLEED_OVERLAY_MED 1.5
#define BLEED_OVERLAY_GUSH 3.25
/// A "chronological" list of wound severities, starting at the least severe.
GLOBAL_LIST_INIT(wound_severities_chronological, list(
"[WOUND_SEVERITY_TRIVIAL]",
"[WOUND_SEVERITY_MODERATE]",
"[WOUND_SEVERITY_SEVERE]",
"[WOUND_SEVERITY_CRITICAL]"
))
// ~wound categories: wounding_types
/// any brute weapon/attack that doesn't have sharpness. rolls for blunt bone wounds
#define WOUND_BLUNT "wound_blunt"
/// any brute weapon/attack with sharpness = SHARP_EDGED. rolls for slash wounds
#define WOUND_SLASH "wound_slash"
/// any brute weapon/attack with sharpness = SHARP_POINTY. rolls for piercing wounds
#define WOUND_PIERCE "wound_pierce"
/// any concentrated burn attack (lasers really). rolls for burning wounds
#define WOUND_BURN "wound_burn"
/// Mainly a define used for wound_pregen_data, if a pregen data instance expects this, it will accept any and all wound types, even none at all
#define WOUND_ALL "wound_all"
// ~determination second wind defines
// How much determination reagent to add each time someone gains a new wound in [/datum/wound/proc/second_wind]
#define WOUND_DETERMINATION_MODERATE 1
#define WOUND_DETERMINATION_SEVERE 2.5
#define WOUND_DETERMINATION_CRITICAL 5
#define WOUND_DETERMINATION_LOSS 7.5
/// the max amount of determination you can have
#define WOUND_DETERMINATION_MAX 10
/// While someone has determination in their system, their bleed rate is slightly reduced
#define WOUND_DETERMINATION_BLEED_MOD 0.85
/// Wounds using this competition mode will remove any wounds of a greater severity than itself in a random wound roll. In most cases, you dont want to use this.
#define WOUND_COMPETITION_OVERPOWER_GREATERS "wound_submit"
/// Wounds using this competition mode will remove any wounds of a lower severity than itself in a random wound roll. Used for ensuring the worse case scenario of a given injury_roll.
#define WOUND_COMPETITION_OVERPOWER_LESSERS "wound_dominate"
// ~biology defines
// What kind of biology a limb has, and what wounds it can suffer
/// Has absolutely fucking nothing, no wounds
#define BIO_INORGANIC NONE
/// Has bone - allows the victim to suffer T2-T3 bone blunt wounds
#define BIO_BONE (1<<0)
/// Has flesh - allows the victim to suffer fleshy slash pierce and burn wounds
#define BIO_FLESH (1<<1)
/// Has metal - allows the victim to suffer robotic blunt and burn wounds
#define BIO_METAL (1<<2)
/// Is wired internally - allows the victim to suffer electrical wounds (robotic T1-T3 slash/pierce)
#define BIO_WIRED (1<<3)
/// Has bloodflow - can suffer bleeding wounds and can bleed
#define BIO_BLOODED (1<<4)
/// Is connected by a joint - can suffer T1 bone blunt wounds (dislocation)
#define BIO_JOINTED (1<<5)
/// Robotic - can suffer all metal/wired wounds, such as: UNIMPLEMENTED PLEASE UPDATE ONCE SYNTH WOUNDS 9/5/2023 ~Niko
#define BIO_ROBOTIC (BIO_METAL|BIO_WIRED)
/// Has flesh and bone - See BIO_BONE and BIO_FLESH
#define BIO_FLESH_BONE (BIO_BONE|BIO_FLESH)
/// Standard humanoid - can bleed and suffer all flesh/bone wounds, such as: T1-3 slash/pierce/burn/blunt, except dislocations. Think human heads/chests
#define BIO_STANDARD_UNJOINTED (BIO_FLESH_BONE|BIO_BLOODED)
/// Standard humanoid limbs - can bleed and suffer all flesh/bone wounds, such as: T1-3 slash/pierce/burn/blunt. Can also bleed, and be dislocated. Think human arms and legs
#define BIO_STANDARD_JOINTED (BIO_STANDARD_UNJOINTED|BIO_JOINTED)
// "Where" a specific biostate is within a given limb
// Interior is hard shit, the last line, shit like bones
// Exterior is soft shit, targeted by slashes and pierces (usually), protects exterior
// A limb needs both mangled interior and exterior to be dismembered, but slash/pierce must mangle exterior to attack the interior
// Not having exterior/interior counts as mangled exterior/interior for the purposes of dismemberment
/// The given biostate is on the "interior" of the limb - hard shit, protected by exterior
#define ANATOMY_INTERIOR (1<<0)
/// The given biostate is on the "exterior" of the limb - soft shit, protects interior
#define ANATOMY_EXTERIOR (1<<1)
#define ANATOMY_EXTERIOR_AND_INTERIOR (ANATOMY_EXTERIOR|ANATOMY_INTERIOR)
/// A assoc list of BIO_ define to EXTERIOR/INTERIOR defines.
/// This is where the interior/exterior state of a given biostate is set.
/// Note that not all biostates are guaranteed to be one of these - and in fact, many are not
/// IMPORTANT NOTE: All keys are stored as text and must be converted via text2num
GLOBAL_LIST_INIT(bio_state_anatomy, list(
"[BIO_WIRED]" = ANATOMY_EXTERIOR,
"[BIO_METAL]" = ANATOMY_INTERIOR,
"[BIO_FLESH]" = ANATOMY_EXTERIOR,
"[BIO_BONE]" = ANATOMY_INTERIOR,
))
// Wound series
// A "wound series" is just a family of wounds that logically follow eachother
// Multiple wounds in a single series cannot be on a limb - the highest severity will always be prioritized, and lower ones will be skipped
/// T1-T3 Bleeding slash wounds. Requires flesh. Can cause bleeding, but doesn't require it. From: slash.dm
#define WOUND_SERIES_FLESH_SLASH_BLEED "wound_series_flesh_slash_bled"
/// T1-T3 Basic blunt wounds. T1 requires jointed, but 2-3 require bone. From: bone.dm
#define WOUND_SERIES_BONE_BLUNT_BASIC "wound_series_bone_blunt_basic"
/// T1-T3 Basic burn wounds. Requires flesh. From: burns.dm
#define WOUND_SERIES_FLESH_BURN_BASIC "wound_series_flesh_burn_basic"
/// T1-T3 Bleeding puncture wounds. Requires flesh. Can cause bleeding, but doesn't require it. From: pierce.dm
#define WOUND_SERIES_FLESH_PUNCTURE_BLEED "wound_series_flesh_puncture_bleed"
/// Generic loss wounds. See loss.dm
#define WOUND_SERIES_LOSS_BASIC "wound_series_loss_basic"
/// Cranial fissure wound.
#define WOUND_SERIES_CRANIAL_FISSURE "wound_series_cranial_fissure"
/// A assoc list of (wound typepath -> wound_pregen_data instance). Every wound should have a pregen data.
GLOBAL_LIST_INIT_TYPED(all_wound_pregen_data, /datum/wound_pregen_data, generate_wound_static_data())
/// Constructs [GLOB.all_wound_pregen_data] by iterating through a typecache of pregen data, ignoring abstract types, and instantiating the rest.
/proc/generate_wound_static_data()
RETURN_TYPE(/list/datum/wound_pregen_data)
var/list/datum/wound_pregen_data/all_pregen_data = list()
for (var/datum/wound_pregen_data/iterated_path as anything in typecacheof(path = /datum/wound_pregen_data, ignore_root_path = TRUE))
if (initial(iterated_path.abstract))
continue
if (!isnull(all_pregen_data[initial(iterated_path.wound_path_to_generate)]))
stack_trace("pre-existing pregen data for [initial(iterated_path.wound_path_to_generate)] when [iterated_path] was being considered: [all_pregen_data[initial(iterated_path.wound_path_to_generate)]]. \
this is definitely a bug, and is probably because one of the two pregen data have the wrong wound typepath defined. [iterated_path] will not be instantiated")
continue
var/datum/wound_pregen_data/pregen_data = new iterated_path
all_pregen_data[pregen_data.wound_path_to_generate] = pregen_data
return all_pregen_data
// A wound series "collection" is merely a way for us to track what is in what series, and what their types are.
// Without this, we have no centralized way to determine what type is in what series outside of iterating over every pregen data.
/// A branching assoc list of (series -> list(severity -> list(typepath -> weight))). Allows you to say "I want a generic slash wound",
/// then "Of severity 2", and get a wound of that description - via get_corresponding_wound_type()
/// Series: A generic wound_series, such as WOUND_SERIES_BONE_BLUNT_BASIC
/// Severity: Any wounds held within this will be of this severity.
/// Typepath, Weight: Merely a pairing of a given typepath to its weight, held for convenience in pickweight.
GLOBAL_LIST_INIT(wound_series_collections, generate_wound_series_collection())
// Series -> severity -> type -> weight
/// Generates [wound_series_collections] by iterating through all pregen_data. Refer to the mentioned list for documentation
/proc/generate_wound_series_collection()
RETURN_TYPE(/list/datum/wound)
var/list/datum/wound/wound_collection = list()
for (var/datum/wound/wound_typepath as anything in typecacheof(/datum/wound, FALSE, TRUE))
var/datum/wound_pregen_data/pregen_data = GLOB.all_wound_pregen_data[wound_typepath]
if (!pregen_data)
continue
if (pregen_data.abstract)
stack_trace("somehow, a abstract wound_pregen_data instance ([pregen_data.type]) was instantiated and made it to generate_wound_series_collection()! \
i literally have no idea how! please fix this!")
continue
var/series = pregen_data.wound_series
var/list/datum/wound/series_list = wound_collection[series]
if (isnull(series_list))
wound_collection[series] = list()
series_list = wound_collection[series]
var/severity = "[(initial(wound_typepath.severity))]"
var/list/datum/wound/severity_list = series_list[severity]
if (isnull(severity_list))
series_list[severity] = list()
severity_list = series_list[severity]
severity_list[wound_typepath] = pregen_data.weight
return wound_collection
/// A branching assoc list of (wounding_type -> list(wound_series)).
/// Allows for determining of which wound series are caused by what.
GLOBAL_LIST_INIT(wounding_types_to_series, list(
WOUND_BLUNT = list(
WOUND_SERIES_BONE_BLUNT_BASIC
),
WOUND_SLASH = list(
WOUND_SERIES_FLESH_SLASH_BLEED,
),
WOUND_BURN = list(
WOUND_SERIES_FLESH_BURN_BASIC,
),
WOUND_PIERCE = list(
WOUND_SERIES_FLESH_PUNCTURE_BLEED
),
))
/// Used in get_corresponding_wound_type(): Will pick the highest severity wound out of severity_min and severity_max
#define WOUND_PICK_HIGHEST_SEVERITY 1
/// Used in get_corresponding_wound_type(): Will pick the lowest severity wound out of severity_min and severity_max
#define WOUND_PICK_LOWEST_SEVERITY 2
/**
* Searches through all wounds for any of proper type, series, and biostate, and then returns a single one via pickweight.
* Is able to discern between, say, a flesh slash wound, and a metallic slash wound, and will return the respective one for the provided limb.
*
* The severity_max and severity_pick_mode args mostly exist in case you want a wound in a series that may not have your ideal severity wound, as it lets you
* essentially set a "fallback", where if your ideal wound doesnt exist, it'll still return something, trying to get closest to your ideal severity.
*
* Generally speaking, if you want a critical/severe/moderate wound, you should set severity_min to WOUND_SEVERITY_MODERATE, severity_max to your ideal wound,
* and severity_pick_mode to WOUND_PICK_HIGHEST_SEVERITY - UNLESS you for some reason want the LOWEST severity, in which case you should set
* severity_max to the highest wound you're willing to tolerate, and severity_pick_mode to WOUND_PICK_LOWEST_SEVERITY.
*
* Args:
* * wounding_type: Wounding type wounds of which we should be searching for
* * obj/item/bodypart/part: The limb we are considering. Extremely important for biostates.
* * severity_min: The minimum wound severity we will search for.
* * severity_max = severity_min: The maximum wound severity we will search for.
* * severity_pick_mode = WOUND_PICK_HIGHEST_SEVERITY: The "pick mode" we will use when considering multiple wounds of acceptable severity. See the above defines.
* * random_roll = TRUE: If this is considered a "random" consideration. If true, only wounds that can be randomly generated will be considered.
* * duplicates_allowed = FALSE: If exact duplicates of a given wound on part are tolerated. Useful for simply getting a path and not instantiating.
* * care_about_existing_wounds = TRUE: If we iterate over wounds to see if any are above or at a given wounds severity, and disregard it if any are. Useful for simply getting a path and not instantiating.
*
* Returns:
* A randomly picked wound typepath meeting all the above criteria and being applicable to the part's biotype - or null if there were none.
*/
/proc/get_corresponding_wound_type(wounding_type, obj/item/bodypart/part, severity_min, severity_max = severity_min, severity_pick_mode = WOUND_PICK_HIGHEST_SEVERITY, random_roll = TRUE, duplicates_allowed = FALSE, care_about_existing_wounds = TRUE)
RETURN_TYPE(/datum/wound) // note that just because its set to return this doesnt mean its non-nullable
var/list/wounding_type_list = GLOB.wounding_types_to_series[wounding_type]
if (!length(wounding_type_list))
return null
var/list/datum/wound/paths_to_pick_from = list()
for (var/series in shuffle(wounding_type_list))
var/list/severity_list = GLOB.wound_series_collections[series]
if (!length(severity_list))
continue
var/picked_severity
for (var/severity_text in shuffle(GLOB.wound_severities_chronological))
var/severity = text2num(severity_text)
if (!ISINRANGE(severity, severity_min, severity_max))
continue
if (isnull(picked_severity) || ((severity_pick_mode == WOUND_PICK_HIGHEST_SEVERITY && severity > picked_severity) || (severity_pick_mode == WOUND_PICK_LOWEST_SEVERITY && severity < picked_severity)))
picked_severity = severity
var/list/wound_typepaths = severity_list["[picked_severity]"]
if (!length(wound_typepaths))
continue
for (var/datum/wound/iterated_path as anything in wound_typepaths)
var/datum/wound_pregen_data/pregen_data = GLOB.all_wound_pregen_data[iterated_path]
if (pregen_data.can_be_applied_to(part, wounding_type, random_roll = random_roll, duplicates_allowed = duplicates_allowed, care_about_existing_wounds = care_about_existing_wounds))
paths_to_pick_from[iterated_path] = wound_typepaths[iterated_path]
return pick_weight(paths_to_pick_from) // we found our winners!
/// Assoc list of biotype -> ideal scar file to be used and grab stuff from.
GLOBAL_LIST_INIT(biotypes_to_scar_file, list(
"[BIO_FLESH]" = FLESH_SCAR_FILE,
"[BIO_BONE]" = BONE_SCAR_FILE
))
// ~burn wound infection defines
// Thresholds for infection for burn wounds, once infestation hits each threshold, things get steadily worse
/// below this has no ill effects from infection
#define WOUND_INFECTION_MODERATE 4
/// then below here, you ooze some pus and suffer minor tox damage, but nothing serious
#define WOUND_INFECTION_SEVERE 8
/// then below here, your limb occasionally locks up from damage and infection and briefly becomes disabled. Things are getting really bad
#define WOUND_INFECTION_CRITICAL 12
/// below here, your skin is almost entirely falling off and your limb locks up more frequently. You are within a stone's throw of septic paralysis and losing the limb
#define WOUND_INFECTION_SEPTIC 20
// above WOUND_INFECTION_SEPTIC, your limb is completely putrid and you start rolling to lose the entire limb by way of paralyzation. After 3 failed rolls (~4-5% each probably), the limb is paralyzed
// ~random wound balance defines
/// how quickly sanitization removes infestation and decays per second
#define WOUND_BURN_SANITIZATION_RATE 0.075
/// how much blood you can lose per tick per wound max.
#define WOUND_MAX_BLOODFLOW 4.5
/// further slash attacks on a bodypart with a slash wound have their blood_flow further increased by damage * this (10 damage slash adds .25 flow)
#define WOUND_SLASH_DAMAGE_FLOW_COEFF 0.025
/// if we suffer a bone wound to the head that creates brain traumas, the timer for the trauma cycle is +/- by this percent (0-100)
#define WOUND_BONE_HEAD_TIME_VARIANCE 20
// ~mangling defines
// With the wounds pt. 2 update, general dismemberment now requires 2 things for a limb to be dismemberable (exterior/bone only creatures just need the second):
// 1. Exterior is mangled: A critical slash or pierce wound on that limb
// 2. Interior is mangled: At least a severe bone wound on that limb
// Lack of exterior or interior count as mangled exterior/interior respectively
// see [/obj/item/bodypart/proc/get_mangled_state] for more information, as well as GLOB.bio_state_anatomy
#define BODYPART_MANGLED_NONE NONE
#define BODYPART_MANGLED_INTERIOR (1<<0)
#define BODYPART_MANGLED_EXTERIOR (1<<1)
#define BODYPART_MANGLED_BOTH (BODYPART_MANGLED_INTERIOR | BODYPART_MANGLED_EXTERIOR)
// ~wound flag defines
/// If having this wound counts as mangled exterior for dismemberment
#define MANGLES_EXTERIOR (1<<0)
/// If having this wound counts as mangled interior for dismemberment
#define MANGLES_INTERIOR (1<<1)
/// If this wound marks the limb as being allowed to have gauze applied
#define ACCEPTS_GAUZE (1<<2)
/// If this wound allows the victim to grasp it
#define CAN_BE_GRASPED (1<<3)
// ~scar persistence defines
// The following are the order placements for persistent scar save formats
/// The version number of the scar we're saving, any scars being loaded below this number will be discarded, see SCAR_CURRENT_VERSION below
#define SCAR_SAVE_VERS 1
/// The body_zone we're applying to on granting
#define SCAR_SAVE_ZONE 2
/// The description we're loading
#define SCAR_SAVE_DESC 3
/// The precise location we're loading
#define SCAR_SAVE_PRECISE_LOCATION 4
/// The severity the scar had
#define SCAR_SAVE_SEVERITY 5
/// Whether this is a BIO_BONE scar, a BIO_FLESH scar, or a BIO_FLESH_BONE scar (so you can't load fleshy human scars on a plasmaman character)
#define SCAR_SAVE_BIOLOGY 6
/// Which character slot this was saved to
#define SCAR_SAVE_CHAR_SLOT 7
/// if the scar will check for any or all biostates on the limb (defaults to FALSE, so all)
#define SCAR_SAVE_CHECK_ANY_BIO 8
///how many fields we save for each scar (so the number of above fields)
#define SCAR_SAVE_LENGTH 8
/// saved scars with a version lower than this will be discarded, increment when you update the persistent scarring format in a way that invalidates previous saved scars (new fields, reordering, etc)
#define SCAR_CURRENT_VERSION 4
/// how many scar slots, per character slot, we have to cycle through for persistent scarring, if enabled in character prefs
#define PERSISTENT_SCAR_SLOTS 3
// ~blood_flow rates of change, these are used by [/datum/wound/proc/get_bleed_rate_of_change] from [/mob/living/carbon/proc/bleed_warn] to let the player know if their bleeding is getting better/worse/the same
/// Our wound is clotting and will eventually stop bleeding if this continues
#define BLOOD_FLOW_DECREASING -1
/// Our wound is bleeding but is holding steady at the same rate.
#define BLOOD_FLOW_STEADY 0
/// Our wound is bleeding and actively getting worse, like if we're a critical slash or if we're afflicted with heparin
#define BLOOD_FLOW_INCREASING 1
/// How often can we annoy the player about their bleeding? This duration is extended if it's not serious bleeding
#define BLEEDING_MESSAGE_BASE_CD (10 SECONDS)
/// Skeletons and other BIO_ONLY_BONE creatures respond much better to bone gel and can have severe and critical bone wounds healed by bone gel alone. The duration it takes to heal is also multiplied by this, lucky them!
#define WOUND_BONE_BIO_BONE_GEL_MULT 0.25
| 1 | 0.605383 | 1 | 0.605383 | game-dev | MEDIA | 0.854994 | game-dev | 0.678835 | 1 | 0.678835 |
atarimacosx/Atari800MacX | 33,076 | atari800-MacOSX/src/Atari800MacX/SDL2.framework/Versions/A/Headers/SDL_events.h | /*
Simple DirectMedia Layer
Copyright (C) 1997-2020 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.
*/
/**
* \file SDL_events.h
*
* Include file for SDL event handling.
*/
#ifndef SDL_events_h_
#define SDL_events_h_
#include "SDL_stdinc.h"
#include "SDL_error.h"
#include "SDL_video.h"
#include "SDL_keyboard.h"
#include "SDL_mouse.h"
#include "SDL_joystick.h"
#include "SDL_gamecontroller.h"
#include "SDL_quit.h"
#include "SDL_gesture.h"
#include "SDL_touch.h"
#include "begin_code.h"
/* Set up for C function definitions, even when using C++ */
#ifdef __cplusplus
extern "C" {
#endif
/* General keyboard/mouse state definitions */
#define SDL_RELEASED 0
#define SDL_PRESSED 1
/**
* \brief The types of events that can be delivered.
*/
typedef enum
{
SDL_FIRSTEVENT = 0, /**< Unused (do not remove) */
/* Application events */
SDL_QUIT = 0x100, /**< User-requested quit */
/* These application events have special meaning on iOS, see README-ios.md for details */
SDL_APP_TERMINATING, /**< The application is being terminated by the OS
Called on iOS in applicationWillTerminate()
Called on Android in onDestroy()
*/
SDL_APP_LOWMEMORY, /**< The application is low on memory, free memory if possible.
Called on iOS in applicationDidReceiveMemoryWarning()
Called on Android in onLowMemory()
*/
SDL_APP_WILLENTERBACKGROUND, /**< The application is about to enter the background
Called on iOS in applicationWillResignActive()
Called on Android in onPause()
*/
SDL_APP_DIDENTERBACKGROUND, /**< The application did enter the background and may not get CPU for some time
Called on iOS in applicationDidEnterBackground()
Called on Android in onPause()
*/
SDL_APP_WILLENTERFOREGROUND, /**< The application is about to enter the foreground
Called on iOS in applicationWillEnterForeground()
Called on Android in onResume()
*/
SDL_APP_DIDENTERFOREGROUND, /**< The application is now interactive
Called on iOS in applicationDidBecomeActive()
Called on Android in onResume()
*/
SDL_LOCALECHANGED, /**< The user's locale preferences have changed. */
/* Display events */
SDL_DISPLAYEVENT = 0x150, /**< Display state change */
/* Window events */
SDL_WINDOWEVENT = 0x200, /**< Window state change */
SDL_SYSWMEVENT, /**< System specific event */
/* Keyboard events */
SDL_KEYDOWN = 0x300, /**< Key pressed */
SDL_KEYUP, /**< Key released */
SDL_TEXTEDITING, /**< Keyboard text editing (composition) */
SDL_TEXTINPUT, /**< Keyboard text input */
SDL_KEYMAPCHANGED, /**< Keymap changed due to a system event such as an
input language or keyboard layout change.
*/
/* Mouse events */
SDL_MOUSEMOTION = 0x400, /**< Mouse moved */
SDL_MOUSEBUTTONDOWN, /**< Mouse button pressed */
SDL_MOUSEBUTTONUP, /**< Mouse button released */
SDL_MOUSEWHEEL, /**< Mouse wheel motion */
/* Joystick events */
SDL_JOYAXISMOTION = 0x600, /**< Joystick axis motion */
SDL_JOYBALLMOTION, /**< Joystick trackball motion */
SDL_JOYHATMOTION, /**< Joystick hat position change */
SDL_JOYBUTTONDOWN, /**< Joystick button pressed */
SDL_JOYBUTTONUP, /**< Joystick button released */
SDL_JOYDEVICEADDED, /**< A new joystick has been inserted into the system */
SDL_JOYDEVICEREMOVED, /**< An opened joystick has been removed */
/* Game controller events */
SDL_CONTROLLERAXISMOTION = 0x650, /**< Game controller axis motion */
SDL_CONTROLLERBUTTONDOWN, /**< Game controller button pressed */
SDL_CONTROLLERBUTTONUP, /**< Game controller button released */
SDL_CONTROLLERDEVICEADDED, /**< A new Game controller has been inserted into the system */
SDL_CONTROLLERDEVICEREMOVED, /**< An opened Game controller has been removed */
SDL_CONTROLLERDEVICEREMAPPED, /**< The controller mapping was updated */
SDL_CONTROLLERTOUCHPADDOWN, /**< Game controller touchpad was touched */
SDL_CONTROLLERTOUCHPADMOTION, /**< Game controller touchpad finger was moved */
SDL_CONTROLLERTOUCHPADUP, /**< Game controller touchpad finger was lifted */
SDL_CONTROLLERSENSORUPDATE, /**< Game controller sensor was updated */
/* Touch events */
SDL_FINGERDOWN = 0x700,
SDL_FINGERUP,
SDL_FINGERMOTION,
/* Gesture events */
SDL_DOLLARGESTURE = 0x800,
SDL_DOLLARRECORD,
SDL_MULTIGESTURE,
/* Clipboard events */
SDL_CLIPBOARDUPDATE = 0x900, /**< The clipboard changed */
/* Drag and drop events */
SDL_DROPFILE = 0x1000, /**< The system requests a file open */
SDL_DROPTEXT, /**< text/plain drag-and-drop event */
SDL_DROPBEGIN, /**< A new set of drops is beginning (NULL filename) */
SDL_DROPCOMPLETE, /**< Current set of drops is now complete (NULL filename) */
/* Audio hotplug events */
SDL_AUDIODEVICEADDED = 0x1100, /**< A new audio device is available */
SDL_AUDIODEVICEREMOVED, /**< An audio device has been removed. */
/* Sensor events */
SDL_SENSORUPDATE = 0x1200, /**< A sensor was updated */
/* Render events */
SDL_RENDER_TARGETS_RESET = 0x2000, /**< The render targets have been reset and their contents need to be updated */
SDL_RENDER_DEVICE_RESET, /**< The device has been reset and all textures need to be recreated */
/** Events ::SDL_USEREVENT through ::SDL_LASTEVENT are for your use,
* and should be allocated with SDL_RegisterEvents()
*/
SDL_USEREVENT = 0x8000,
/**
* This last event is only for bounding internal arrays
*/
SDL_LASTEVENT = 0xFFFF
} SDL_EventType;
/**
* \brief Fields shared by every event
*/
typedef struct SDL_CommonEvent
{
Uint32 type;
Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */
} SDL_CommonEvent;
/**
* \brief Display state change event data (event.display.*)
*/
typedef struct SDL_DisplayEvent
{
Uint32 type; /**< ::SDL_DISPLAYEVENT */
Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */
Uint32 display; /**< The associated display index */
Uint8 event; /**< ::SDL_DisplayEventID */
Uint8 padding1;
Uint8 padding2;
Uint8 padding3;
Sint32 data1; /**< event dependent data */
} SDL_DisplayEvent;
/**
* \brief Window state change event data (event.window.*)
*/
typedef struct SDL_WindowEvent
{
Uint32 type; /**< ::SDL_WINDOWEVENT */
Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */
Uint32 windowID; /**< The associated window */
Uint8 event; /**< ::SDL_WindowEventID */
Uint8 padding1;
Uint8 padding2;
Uint8 padding3;
Sint32 data1; /**< event dependent data */
Sint32 data2; /**< event dependent data */
} SDL_WindowEvent;
/**
* \brief Keyboard button event structure (event.key.*)
*/
typedef struct SDL_KeyboardEvent
{
Uint32 type; /**< ::SDL_KEYDOWN or ::SDL_KEYUP */
Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */
Uint32 windowID; /**< The window with keyboard focus, if any */
Uint8 state; /**< ::SDL_PRESSED or ::SDL_RELEASED */
Uint8 repeat; /**< Non-zero if this is a key repeat */
Uint8 padding2;
Uint8 padding3;
SDL_Keysym keysym; /**< The key that was pressed or released */
} SDL_KeyboardEvent;
#define SDL_TEXTEDITINGEVENT_TEXT_SIZE (32)
/**
* \brief Keyboard text editing event structure (event.edit.*)
*/
typedef struct SDL_TextEditingEvent
{
Uint32 type; /**< ::SDL_TEXTEDITING */
Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */
Uint32 windowID; /**< The window with keyboard focus, if any */
char text[SDL_TEXTEDITINGEVENT_TEXT_SIZE]; /**< The editing text */
Sint32 start; /**< The start cursor of selected editing text */
Sint32 length; /**< The length of selected editing text */
} SDL_TextEditingEvent;
#define SDL_TEXTINPUTEVENT_TEXT_SIZE (32)
/**
* \brief Keyboard text input event structure (event.text.*)
*/
typedef struct SDL_TextInputEvent
{
Uint32 type; /**< ::SDL_TEXTINPUT */
Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */
Uint32 windowID; /**< The window with keyboard focus, if any */
char text[SDL_TEXTINPUTEVENT_TEXT_SIZE]; /**< The input text */
} SDL_TextInputEvent;
/**
* \brief Mouse motion event structure (event.motion.*)
*/
typedef struct SDL_MouseMotionEvent
{
Uint32 type; /**< ::SDL_MOUSEMOTION */
Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */
Uint32 windowID; /**< The window with mouse focus, if any */
Uint32 which; /**< The mouse instance id, or SDL_TOUCH_MOUSEID */
Uint32 state; /**< The current button state */
Sint32 x; /**< X coordinate, relative to window */
Sint32 y; /**< Y coordinate, relative to window */
Sint32 xrel; /**< The relative motion in the X direction */
Sint32 yrel; /**< The relative motion in the Y direction */
} SDL_MouseMotionEvent;
/**
* \brief Mouse button event structure (event.button.*)
*/
typedef struct SDL_MouseButtonEvent
{
Uint32 type; /**< ::SDL_MOUSEBUTTONDOWN or ::SDL_MOUSEBUTTONUP */
Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */
Uint32 windowID; /**< The window with mouse focus, if any */
Uint32 which; /**< The mouse instance id, or SDL_TOUCH_MOUSEID */
Uint8 button; /**< The mouse button index */
Uint8 state; /**< ::SDL_PRESSED or ::SDL_RELEASED */
Uint8 clicks; /**< 1 for single-click, 2 for double-click, etc. */
Uint8 padding1;
Sint32 x; /**< X coordinate, relative to window */
Sint32 y; /**< Y coordinate, relative to window */
} SDL_MouseButtonEvent;
/**
* \brief Mouse wheel event structure (event.wheel.*)
*/
typedef struct SDL_MouseWheelEvent
{
Uint32 type; /**< ::SDL_MOUSEWHEEL */
Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */
Uint32 windowID; /**< The window with mouse focus, if any */
Uint32 which; /**< The mouse instance id, or SDL_TOUCH_MOUSEID */
Sint32 x; /**< The amount scrolled horizontally, positive to the right and negative to the left */
Sint32 y; /**< The amount scrolled vertically, positive away from the user and negative toward the user */
Uint32 direction; /**< Set to one of the SDL_MOUSEWHEEL_* defines. When FLIPPED the values in X and Y will be opposite. Multiply by -1 to change them back */
} SDL_MouseWheelEvent;
/**
* \brief Joystick axis motion event structure (event.jaxis.*)
*/
typedef struct SDL_JoyAxisEvent
{
Uint32 type; /**< ::SDL_JOYAXISMOTION */
Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */
SDL_JoystickID which; /**< The joystick instance id */
Uint8 axis; /**< The joystick axis index */
Uint8 padding1;
Uint8 padding2;
Uint8 padding3;
Sint16 value; /**< The axis value (range: -32768 to 32767) */
Uint16 padding4;
} SDL_JoyAxisEvent;
/**
* \brief Joystick trackball motion event structure (event.jball.*)
*/
typedef struct SDL_JoyBallEvent
{
Uint32 type; /**< ::SDL_JOYBALLMOTION */
Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */
SDL_JoystickID which; /**< The joystick instance id */
Uint8 ball; /**< The joystick trackball index */
Uint8 padding1;
Uint8 padding2;
Uint8 padding3;
Sint16 xrel; /**< The relative motion in the X direction */
Sint16 yrel; /**< The relative motion in the Y direction */
} SDL_JoyBallEvent;
/**
* \brief Joystick hat position change event structure (event.jhat.*)
*/
typedef struct SDL_JoyHatEvent
{
Uint32 type; /**< ::SDL_JOYHATMOTION */
Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */
SDL_JoystickID which; /**< The joystick instance id */
Uint8 hat; /**< The joystick hat index */
Uint8 value; /**< The hat position value.
* \sa ::SDL_HAT_LEFTUP ::SDL_HAT_UP ::SDL_HAT_RIGHTUP
* \sa ::SDL_HAT_LEFT ::SDL_HAT_CENTERED ::SDL_HAT_RIGHT
* \sa ::SDL_HAT_LEFTDOWN ::SDL_HAT_DOWN ::SDL_HAT_RIGHTDOWN
*
* Note that zero means the POV is centered.
*/
Uint8 padding1;
Uint8 padding2;
} SDL_JoyHatEvent;
/**
* \brief Joystick button event structure (event.jbutton.*)
*/
typedef struct SDL_JoyButtonEvent
{
Uint32 type; /**< ::SDL_JOYBUTTONDOWN or ::SDL_JOYBUTTONUP */
Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */
SDL_JoystickID which; /**< The joystick instance id */
Uint8 button; /**< The joystick button index */
Uint8 state; /**< ::SDL_PRESSED or ::SDL_RELEASED */
Uint8 padding1;
Uint8 padding2;
} SDL_JoyButtonEvent;
/**
* \brief Joystick device event structure (event.jdevice.*)
*/
typedef struct SDL_JoyDeviceEvent
{
Uint32 type; /**< ::SDL_JOYDEVICEADDED or ::SDL_JOYDEVICEREMOVED */
Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */
Sint32 which; /**< The joystick device index for the ADDED event, instance id for the REMOVED event */
} SDL_JoyDeviceEvent;
/**
* \brief Game controller axis motion event structure (event.caxis.*)
*/
typedef struct SDL_ControllerAxisEvent
{
Uint32 type; /**< ::SDL_CONTROLLERAXISMOTION */
Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */
SDL_JoystickID which; /**< The joystick instance id */
Uint8 axis; /**< The controller axis (SDL_GameControllerAxis) */
Uint8 padding1;
Uint8 padding2;
Uint8 padding3;
Sint16 value; /**< The axis value (range: -32768 to 32767) */
Uint16 padding4;
} SDL_ControllerAxisEvent;
/**
* \brief Game controller button event structure (event.cbutton.*)
*/
typedef struct SDL_ControllerButtonEvent
{
Uint32 type; /**< ::SDL_CONTROLLERBUTTONDOWN or ::SDL_CONTROLLERBUTTONUP */
Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */
SDL_JoystickID which; /**< The joystick instance id */
Uint8 button; /**< The controller button (SDL_GameControllerButton) */
Uint8 state; /**< ::SDL_PRESSED or ::SDL_RELEASED */
Uint8 padding1;
Uint8 padding2;
} SDL_ControllerButtonEvent;
/**
* \brief Controller device event structure (event.cdevice.*)
*/
typedef struct SDL_ControllerDeviceEvent
{
Uint32 type; /**< ::SDL_CONTROLLERDEVICEADDED, ::SDL_CONTROLLERDEVICEREMOVED, or ::SDL_CONTROLLERDEVICEREMAPPED */
Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */
Sint32 which; /**< The joystick device index for the ADDED event, instance id for the REMOVED or REMAPPED event */
} SDL_ControllerDeviceEvent;
/**
* \brief Game controller touchpad event structure (event.ctouchpad.*)
*/
typedef struct SDL_ControllerTouchpadEvent
{
Uint32 type; /**< ::SDL_CONTROLLERTOUCHPADDOWN or ::SDL_CONTROLLERTOUCHPADMOTION or ::SDL_CONTROLLERTOUCHPADUP */
Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */
SDL_JoystickID which; /**< The joystick instance id */
Sint32 touchpad; /**< The index of the touchpad */
Sint32 finger; /**< The index of the finger on the touchpad */
float x; /**< Normalized in the range 0...1 with 0 being on the left */
float y; /**< Normalized in the range 0...1 with 0 being at the top */
float pressure; /**< Normalized in the range 0...1 */
} SDL_ControllerTouchpadEvent;
/**
* \brief Game controller sensor event structure (event.csensor.*)
*/
typedef struct SDL_ControllerSensorEvent
{
Uint32 type; /**< ::SDL_CONTROLLERSENSORUPDATE */
Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */
SDL_JoystickID which; /**< The joystick instance id */
Sint32 sensor; /**< The type of the sensor, one of the values of ::SDL_SensorType */
float data[3]; /**< Up to 3 values from the sensor, as defined in SDL_sensor.h */
} SDL_ControllerSensorEvent;
/**
* \brief Audio device event structure (event.adevice.*)
*/
typedef struct SDL_AudioDeviceEvent
{
Uint32 type; /**< ::SDL_AUDIODEVICEADDED, or ::SDL_AUDIODEVICEREMOVED */
Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */
Uint32 which; /**< The audio device index for the ADDED event (valid until next SDL_GetNumAudioDevices() call), SDL_AudioDeviceID for the REMOVED event */
Uint8 iscapture; /**< zero if an output device, non-zero if a capture device. */
Uint8 padding1;
Uint8 padding2;
Uint8 padding3;
} SDL_AudioDeviceEvent;
/**
* \brief Touch finger event structure (event.tfinger.*)
*/
typedef struct SDL_TouchFingerEvent
{
Uint32 type; /**< ::SDL_FINGERMOTION or ::SDL_FINGERDOWN or ::SDL_FINGERUP */
Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */
SDL_TouchID touchId; /**< The touch device id */
SDL_FingerID fingerId;
float x; /**< Normalized in the range 0...1 */
float y; /**< Normalized in the range 0...1 */
float dx; /**< Normalized in the range -1...1 */
float dy; /**< Normalized in the range -1...1 */
float pressure; /**< Normalized in the range 0...1 */
Uint32 windowID; /**< The window underneath the finger, if any */
} SDL_TouchFingerEvent;
/**
* \brief Multiple Finger Gesture Event (event.mgesture.*)
*/
typedef struct SDL_MultiGestureEvent
{
Uint32 type; /**< ::SDL_MULTIGESTURE */
Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */
SDL_TouchID touchId; /**< The touch device id */
float dTheta;
float dDist;
float x;
float y;
Uint16 numFingers;
Uint16 padding;
} SDL_MultiGestureEvent;
/**
* \brief Dollar Gesture Event (event.dgesture.*)
*/
typedef struct SDL_DollarGestureEvent
{
Uint32 type; /**< ::SDL_DOLLARGESTURE or ::SDL_DOLLARRECORD */
Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */
SDL_TouchID touchId; /**< The touch device id */
SDL_GestureID gestureId;
Uint32 numFingers;
float error;
float x; /**< Normalized center of gesture */
float y; /**< Normalized center of gesture */
} SDL_DollarGestureEvent;
/**
* \brief An event used to request a file open by the system (event.drop.*)
* This event is enabled by default, you can disable it with SDL_EventState().
* \note If this event is enabled, you must free the filename in the event.
*/
typedef struct SDL_DropEvent
{
Uint32 type; /**< ::SDL_DROPBEGIN or ::SDL_DROPFILE or ::SDL_DROPTEXT or ::SDL_DROPCOMPLETE */
Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */
char *file; /**< The file name, which should be freed with SDL_free(), is NULL on begin/complete */
Uint32 windowID; /**< The window that was dropped on, if any */
} SDL_DropEvent;
/**
* \brief Sensor event structure (event.sensor.*)
*/
typedef struct SDL_SensorEvent
{
Uint32 type; /**< ::SDL_SENSORUPDATE */
Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */
Sint32 which; /**< The instance ID of the sensor */
float data[6]; /**< Up to 6 values from the sensor - additional values can be queried using SDL_SensorGetData() */
} SDL_SensorEvent;
/**
* \brief The "quit requested" event
*/
typedef struct SDL_QuitEvent
{
Uint32 type; /**< ::SDL_QUIT */
Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */
} SDL_QuitEvent;
/**
* \brief OS Specific event
*/
typedef struct SDL_OSEvent
{
Uint32 type; /**< ::SDL_QUIT */
Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */
} SDL_OSEvent;
/**
* \brief A user-defined event type (event.user.*)
*/
typedef struct SDL_UserEvent
{
Uint32 type; /**< ::SDL_USEREVENT through ::SDL_LASTEVENT-1 */
Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */
Uint32 windowID; /**< The associated window if any */
Sint32 code; /**< User defined event code */
void *data1; /**< User defined data pointer */
void *data2; /**< User defined data pointer */
} SDL_UserEvent;
struct SDL_SysWMmsg;
typedef struct SDL_SysWMmsg SDL_SysWMmsg;
/**
* \brief A video driver dependent system event (event.syswm.*)
* This event is disabled by default, you can enable it with SDL_EventState()
*
* \note If you want to use this event, you should include SDL_syswm.h.
*/
typedef struct SDL_SysWMEvent
{
Uint32 type; /**< ::SDL_SYSWMEVENT */
Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */
SDL_SysWMmsg *msg; /**< driver dependent data, defined in SDL_syswm.h */
} SDL_SysWMEvent;
/**
* \brief General event structure
*/
typedef union SDL_Event
{
Uint32 type; /**< Event type, shared with all events */
SDL_CommonEvent common; /**< Common event data */
SDL_DisplayEvent display; /**< Display event data */
SDL_WindowEvent window; /**< Window event data */
SDL_KeyboardEvent key; /**< Keyboard event data */
SDL_TextEditingEvent edit; /**< Text editing event data */
SDL_TextInputEvent text; /**< Text input event data */
SDL_MouseMotionEvent motion; /**< Mouse motion event data */
SDL_MouseButtonEvent button; /**< Mouse button event data */
SDL_MouseWheelEvent wheel; /**< Mouse wheel event data */
SDL_JoyAxisEvent jaxis; /**< Joystick axis event data */
SDL_JoyBallEvent jball; /**< Joystick ball event data */
SDL_JoyHatEvent jhat; /**< Joystick hat event data */
SDL_JoyButtonEvent jbutton; /**< Joystick button event data */
SDL_JoyDeviceEvent jdevice; /**< Joystick device change event data */
SDL_ControllerAxisEvent caxis; /**< Game Controller axis event data */
SDL_ControllerButtonEvent cbutton; /**< Game Controller button event data */
SDL_ControllerDeviceEvent cdevice; /**< Game Controller device event data */
SDL_ControllerTouchpadEvent ctouchpad; /**< Game Controller touchpad event data */
SDL_ControllerSensorEvent csensor; /**< Game Controller sensor event data */
SDL_AudioDeviceEvent adevice; /**< Audio device event data */
SDL_SensorEvent sensor; /**< Sensor event data */
SDL_QuitEvent quit; /**< Quit request event data */
SDL_UserEvent user; /**< Custom event data */
SDL_SysWMEvent syswm; /**< System dependent window event data */
SDL_TouchFingerEvent tfinger; /**< Touch finger event data */
SDL_MultiGestureEvent mgesture; /**< Gesture event data */
SDL_DollarGestureEvent dgesture; /**< Gesture event data */
SDL_DropEvent drop; /**< Drag and drop event data */
/* This is necessary for ABI compatibility between Visual C++ and GCC
Visual C++ will respect the push pack pragma and use 52 bytes for
this structure, and GCC will use the alignment of the largest datatype
within the union, which is 8 bytes.
So... we'll add padding to force the size to be 56 bytes for both.
*/
Uint8 padding[56];
} SDL_Event;
/* Make sure we haven't broken binary compatibility */
SDL_COMPILE_TIME_ASSERT(SDL_Event, sizeof(SDL_Event) == 56);
/* Function prototypes */
/**
* Pumps the event loop, gathering events from the input devices.
*
* This function updates the event queue and internal input device state.
*
* This should only be run in the thread that sets the video mode.
*/
extern DECLSPEC void SDLCALL SDL_PumpEvents(void);
/* @{ */
typedef enum
{
SDL_ADDEVENT,
SDL_PEEKEVENT,
SDL_GETEVENT
} SDL_eventaction;
/**
* Checks the event queue for messages and optionally returns them.
*
* If \c action is ::SDL_ADDEVENT, up to \c numevents events will be added to
* the back of the event queue.
*
* If \c action is ::SDL_PEEKEVENT, up to \c numevents events at the front
* of the event queue, within the specified minimum and maximum type,
* will be returned and will not be removed from the queue.
*
* If \c action is ::SDL_GETEVENT, up to \c numevents events at the front
* of the event queue, within the specified minimum and maximum type,
* will be returned and will be removed from the queue.
*
* \return The number of events actually stored, or -1 if there was an error.
*
* This function is thread-safe.
*/
extern DECLSPEC int SDLCALL SDL_PeepEvents(SDL_Event * events, int numevents,
SDL_eventaction action,
Uint32 minType, Uint32 maxType);
/* @} */
/**
* Checks to see if certain event types are in the event queue.
*/
extern DECLSPEC SDL_bool SDLCALL SDL_HasEvent(Uint32 type);
extern DECLSPEC SDL_bool SDLCALL SDL_HasEvents(Uint32 minType, Uint32 maxType);
/**
* This function clears events from the event queue
* This function only affects currently queued events. If you want to make
* sure that all pending OS events are flushed, you can call SDL_PumpEvents()
* on the main thread immediately before the flush call.
*/
extern DECLSPEC void SDLCALL SDL_FlushEvent(Uint32 type);
extern DECLSPEC void SDLCALL SDL_FlushEvents(Uint32 minType, Uint32 maxType);
/**
* \brief Polls for currently pending events.
*
* \return 1 if there are any pending events, or 0 if there are none available.
*
* \param event If not NULL, the next event is removed from the queue and
* stored in that area.
*/
extern DECLSPEC int SDLCALL SDL_PollEvent(SDL_Event * event);
/**
* \brief Waits indefinitely for the next available event.
*
* \return 1, or 0 if there was an error while waiting for events.
*
* \param event If not NULL, the next event is removed from the queue and
* stored in that area.
*/
extern DECLSPEC int SDLCALL SDL_WaitEvent(SDL_Event * event);
/**
* \brief Waits until the specified timeout (in milliseconds) for the next
* available event.
*
* \return 1, or 0 if there was an error while waiting for events.
*
* \param event If not NULL, the next event is removed from the queue and
* stored in that area.
* \param timeout The timeout (in milliseconds) to wait for next event.
*/
extern DECLSPEC int SDLCALL SDL_WaitEventTimeout(SDL_Event * event,
int timeout);
/**
* \brief Add an event to the event queue.
*
* \return 1 on success, 0 if the event was filtered, or -1 if the event queue
* was full or there was some other error.
*/
extern DECLSPEC int SDLCALL SDL_PushEvent(SDL_Event * event);
typedef int (SDLCALL * SDL_EventFilter) (void *userdata, SDL_Event * event);
/**
* Sets up a filter to process all events before they change internal state and
* are posted to the internal event queue.
*
* The filter is prototyped as:
* \code
* int SDL_EventFilter(void *userdata, SDL_Event * event);
* \endcode
*
* If the filter returns 1, then the event will be added to the internal queue.
* If it returns 0, then the event will be dropped from the queue, but the
* internal state will still be updated. This allows selective filtering of
* dynamically arriving events.
*
* \warning Be very careful of what you do in the event filter function, as
* it may run in a different thread!
*
* There is one caveat when dealing with the ::SDL_QuitEvent event type. The
* event filter is only called when the window manager desires to close the
* application window. If the event filter returns 1, then the window will
* be closed, otherwise the window will remain open if possible.
*
* If the quit event is generated by an interrupt signal, it will bypass the
* internal queue and be delivered to the application at the next event poll.
*/
extern DECLSPEC void SDLCALL SDL_SetEventFilter(SDL_EventFilter filter,
void *userdata);
/**
* Return the current event filter - can be used to "chain" filters.
* If there is no event filter set, this function returns SDL_FALSE.
*/
extern DECLSPEC SDL_bool SDLCALL SDL_GetEventFilter(SDL_EventFilter * filter,
void **userdata);
/**
* Add a function which is called when an event is added to the queue.
*/
extern DECLSPEC void SDLCALL SDL_AddEventWatch(SDL_EventFilter filter,
void *userdata);
/**
* Remove an event watch function added with SDL_AddEventWatch()
*/
extern DECLSPEC void SDLCALL SDL_DelEventWatch(SDL_EventFilter filter,
void *userdata);
/**
* Run the filter function on the current event queue, removing any
* events for which the filter returns 0.
*/
extern DECLSPEC void SDLCALL SDL_FilterEvents(SDL_EventFilter filter,
void *userdata);
/* @{ */
#define SDL_QUERY -1
#define SDL_IGNORE 0
#define SDL_DISABLE 0
#define SDL_ENABLE 1
/**
* This function allows you to set the state of processing certain events.
* - If \c state is set to ::SDL_IGNORE, that event will be automatically
* dropped from the event queue and will not be filtered.
* - If \c state is set to ::SDL_ENABLE, that event will be processed
* normally.
* - If \c state is set to ::SDL_QUERY, SDL_EventState() will return the
* current processing state of the specified event.
*/
extern DECLSPEC Uint8 SDLCALL SDL_EventState(Uint32 type, int state);
/* @} */
#define SDL_GetEventState(type) SDL_EventState(type, SDL_QUERY)
/**
* This function allocates a set of user-defined events, and returns
* the beginning event number for that set of events.
*
* If there aren't enough user-defined events left, this function
* returns (Uint32)-1
*/
extern DECLSPEC Uint32 SDLCALL SDL_RegisterEvents(int numevents);
/* Ends C function definitions when using C++ */
#ifdef __cplusplus
}
#endif
#include "close_code.h"
#endif /* SDL_events_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| 1 | 0.745059 | 1 | 0.745059 | game-dev | MEDIA | 0.69044 | game-dev | 0.586664 | 1 | 0.586664 |
glKarin/com.n0n3m4.diii4a | 5,956 | Q3E/src/main/jni/source/game/server/logic_achievement.cpp | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Defines a logical entity which passes achievement related events to the gamerules system.
#include "cbase.h"
#include "gamerules.h"
#include "entityinput.h"
#include "entityoutput.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
/*
These are the string choices in the FGD:
ACHIEVEMENT_EVENT_HL2_HIT_CANCOP_WITHCAN
ACHIEVEMENT_EVENT_HL2_ESCAPE_APARTMENTRAID
ACHIEVEMENT_EVENT_HL2_FIND_ONEGMAN
ACHIEVEMENT_EVENT_HL2_BREAK_MINITELEPORTER
ACHIEVEMENT_EVENT_HL2_GET_PISTOL
ACHIEVEMENT_EVENT_HL2_GET_AIRBOAT
ACHIEVEMENT_EVENT_HL2_GET_AIRBOATGUN
ACHIEVEMENT_EVENT_HL2_FIND_VORTIGAUNTCAVE
ACHIEVEMENT_EVENT_HL2_KILL_CHOPPER
ACHIEVEMENT_EVENT_HL2_FIND_HEVFACEPLATE
ACHIEVEMENT_EVENT_HL2_GET_GRAVITYGUN
ACHIEVEMENT_EVENT_HL2_MAKEABASKET
ACHIEVEMENT_EVENT_HL2_BEAT_RAVENHOLM_NOWEAPONS_START
ACHIEVEMENT_EVENT_HL2_BEAT_RAVENHOLM_NOWEAPONS_END
ACHIEVEMENT_EVENT_HL2_BEAT_CEMETERY
ACHIEVEMENT_EVENT_HL2_KILL_ENEMIES_WITHCRANE
ACHIEVEMENT_EVENT_HL2_PIN_SOLDIER_TOBILLBOARD
ACHIEVEMENT_EVENT_HL2_KILL_ODESSAGUNSHIP
ACHIEVEMENT_EVENT_HL2_BEAT_DONTTOUCHSAND
ACHIEVEMENT_EVENT_HL2_ENTER_NOVAPROSPEKT,
ACHIEVEMENT_EVENT_HL2_BEAT_TURRETSTANDOFF2
ACHIEVEMENT_EVENT_HL2_BEAT_NOVAPROSPEKT
ACHIEVEMENT_EVENT_HL2_BEAT_TOXICTUNNEL
ACHIEVEMENT_EVENT_HL2_BEAT_PLAZASTANDOFF
ACHIEVEMENT_EVENT_HL2_KILL_ALLC17SNIPERS
ACHIEVEMENT_EVENT_HL2_BEAT_SUPRESSIONDEVICE
ACHIEVEMENT_EVENT_HL2_BEAT_C17STRIDERSTANDOFF
ACHIEVEMENT_EVENT_HL2_REACH_BREENSOFFICE
ACHIEVEMENT_EVENT_HL2_FIND_LAMDACACHE
// EP1
ACHIEVEMENT_EVENT_EP1_BEAT_MAINELEVATOR
ACHIEVEMENT_EVENT_EP1_BEAT_CITADELCORE
ACHIEVEMENT_EVENT_EP1_BEAT_CITADELCORE_NOSTALKERKILLS
ACHIEVEMENT_EVENT_EP1_BEAT_GARAGEELEVATORSTANDOFF
ACHIEVEMENT_EVENT_EP1_KILL_ENEMIES_WITHSNIPERALYX
ACHIEVEMENT_EVENT_EP1_BEAT_HOSPITALATTICGUNSHIP
ACHIEVEMENT_EVENT_EP1_BEAT_CITIZENESCORT_NOCITIZENDEATHS
// EP2
ACHIEVEMENT_EVENT_EP2_BREAK_ALLWEBS
ACHIEVEMENT_EVENT_EP2_BEAT_ANTLIONINVASION
ACHIEVEMENT_EVENT_EP2_BEAT_ANTLIONGUARDS
ACHIEVEMENT_EVENT_EP2_BEAT_HUNTERAMBUSH
ACHIEVEMENT_EVENT_EP2_KILL_COMBINECANNON
ACHIEVEMENT_EVENT_EP2_FIND_RADAR_CACHE
ACHIEVEMENT_EVENT_EP2_BEAT_RACEWITHDOG
ACHIEVEMENT_EVENT_EP2_BEAT_ROCKETCACHEPUZZLE
ACHIEVEMENT_EVENT_EP2_BEAT_WHITEFORESTINN
ACHIEVEMENT_EVENT_EP2_PUT_ITEMINROCKET
ACHIEVEMENT_EVENT_EP2_BEAT_MISSILESILO2
ACHIEVEMENT_EVENT_EP2_BEAT_OUTLAND12_NOBUILDINGSDESTROYED
// PORTAL
ACHIEVEMENT_EVENT_PORTAL_GET_PORTALGUNS
ACHIEVEMENT_EVENT_PORTAL_KILL_COMPANIONCUBE
ACHIEVEMENT_EVENT_PORTAL_ESCAPE_TESTCHAMBERS
ACHIEVEMENT_EVENT_PORTAL_BEAT_GAME
*/
// Allows map logic to send achievement related events to the achievement system.
class CLogicAchievement : public CLogicalEntity
{
public:
DECLARE_CLASS( CLogicAchievement, CLogicalEntity );
CLogicAchievement();
protected:
// Inputs
void InputFireEvent( inputdata_t &inputdata );
void InputEnable( inputdata_t &inputdata );
void InputDisable( inputdata_t &inputdata );
void InputToggle( inputdata_t &inputdata );
bool m_bDisabled;
string_t m_iszAchievementEventID; // Which achievement event this entity marks
COutputEvent m_OnFired;
DECLARE_DATADESC();
};
LINK_ENTITY_TO_CLASS( logic_achievement, CLogicAchievement );
BEGIN_DATADESC( CLogicAchievement )
DEFINE_KEYFIELD( m_bDisabled, FIELD_BOOLEAN, "StartDisabled" ),
DEFINE_KEYFIELD( m_iszAchievementEventID, FIELD_STRING, "AchievementEvent" ),
// Inputs
DEFINE_INPUTFUNC( FIELD_VOID, "FireEvent", InputFireEvent ),
DEFINE_INPUTFUNC( FIELD_VOID, "Enable", InputEnable ),
DEFINE_INPUTFUNC( FIELD_VOID, "Disable", InputDisable ),
DEFINE_INPUTFUNC( FIELD_VOID, "Toggle", InputToggle ),
// Outputs
DEFINE_OUTPUT( m_OnFired, "OnFired" ),
END_DATADESC()
//-----------------------------------------------------------------------------
// Purpose: Constructor.
//-----------------------------------------------------------------------------
CLogicAchievement::CLogicAchievement(void)
{
m_iszAchievementEventID = NULL_STRING;
}
#define ACHIEVEMENT_PREFIX "ACHIEVEMENT_EVENT_"
//-----------------------------------------------------------------------------
// Purpose: Sends the achievement event to the achievement marking system.
//-----------------------------------------------------------------------------
void CLogicAchievement::InputFireEvent( inputdata_t &inputdata )
{
// If we're active, and our string matched a valid achievement ID
if ( !m_bDisabled && m_iszAchievementEventID != NULL_STRING)
{
m_OnFired.FireOutput( inputdata.pActivator, this );
char const *pchName = STRING( m_iszAchievementEventID );
int nPrefixLen = Q_strlen( ACHIEVEMENT_PREFIX );
if ( !Q_strnicmp( pchName, ACHIEVEMENT_PREFIX, nPrefixLen ) )
{
// Skip the prefix
pchName += nPrefixLen;
if ( pchName && *pchName )
{
CBroadcastRecipientFilter filter;
g_pGameRules->MarkAchievement( filter, pchName );
}
}
}
}
//------------------------------------------------------------------------------
// Purpose: Turns on the relay, allowing it to fire outputs.
//------------------------------------------------------------------------------
void CLogicAchievement::InputEnable( inputdata_t &inputdata )
{
m_bDisabled = false;
}
//------------------------------------------------------------------------------
// Purpose: Turns off the relay, preventing it from firing outputs.
//------------------------------------------------------------------------------
void CLogicAchievement::InputDisable( inputdata_t &inputdata )
{
m_bDisabled = true;
}
//------------------------------------------------------------------------------
// Purpose: Toggles the enabled/disabled state of the relay.
//------------------------------------------------------------------------------
void CLogicAchievement::InputToggle( inputdata_t &inputdata )
{
m_bDisabled = !m_bDisabled;
} | 1 | 0.964459 | 1 | 0.964459 | game-dev | MEDIA | 0.977139 | game-dev | 0.950807 | 1 | 0.950807 |
magefree/mage | 2,109 | Mage.Sets/src/mage/cards/x/XavierSalInfestedCaptain.java | package mage.cards.x;
import mage.MageInt;
import mage.abilities.Ability;
import mage.abilities.common.ActivateAsSorceryActivatedAbility;
import mage.abilities.costs.common.RemoveCounterCost;
import mage.abilities.costs.common.SacrificeTargetCost;
import mage.abilities.costs.common.TapSourceCost;
import mage.abilities.effects.common.PopulateEffect;
import mage.abilities.effects.common.counter.ProliferateEffect;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.SubType;
import mage.constants.SuperType;
import mage.filter.StaticFilters;
import mage.target.TargetPermanent;
import java.util.UUID;
/**
* @author xenohedron
*/
public final class XavierSalInfestedCaptain extends CardImpl {
public XavierSalInfestedCaptain(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{B}{G}{U}");
this.supertype.add(SuperType.LEGENDARY);
this.subtype.add(SubType.HUMAN);
this.subtype.add(SubType.FUNGUS);
this.subtype.add(SubType.PIRATE);
this.power = new MageInt(3);
this.toughness = new MageInt(3);
// {T}, Remove a counter from another permanent you control: Populate. Activate only as a sorcery.
Ability ability = new ActivateAsSorceryActivatedAbility(new PopulateEffect(), new TapSourceCost());
ability.addCost(new RemoveCounterCost(new TargetPermanent(StaticFilters.FILTER_CONTROLLED_ANOTHER_PERMANENT)));
this.addAbility(ability);
// {T}, Sacrifice another creature: Proliferate. Activate only as a sorcery.
Ability ability2 = new ActivateAsSorceryActivatedAbility(new ProliferateEffect(), new TapSourceCost());
ability2.addCost(new SacrificeTargetCost(StaticFilters.FILTER_CONTROLLED_ANOTHER_CREATURE));
this.addAbility(ability2);
}
private XavierSalInfestedCaptain(final XavierSalInfestedCaptain card) {
super(card);
}
@Override
public XavierSalInfestedCaptain copy() {
return new XavierSalInfestedCaptain(this);
}
}
| 1 | 0.950049 | 1 | 0.950049 | game-dev | MEDIA | 0.98224 | game-dev | 0.987904 | 1 | 0.987904 |
Bukkit/Bukkit | 2,333 | src/main/java/org/bukkit/command/defaults/DefaultGameModeCommand.java | package org.bukkit.command.defaults;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang.Validate;
import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.util.StringUtil;
import com.google.common.collect.ImmutableList;
public class DefaultGameModeCommand extends VanillaCommand {
private static final List<String> GAMEMODE_NAMES = ImmutableList.of("adventure", "creative", "survival");
public DefaultGameModeCommand() {
super("defaultgamemode");
this.description = "Set the default gamemode";
this.usageMessage = "/defaultgamemode <mode>";
this.setPermission("bukkit.command.defaultgamemode");
}
@Override
public boolean execute(CommandSender sender, String commandLabel, String[] args) {
if (!testPermission(sender)) return true;
if (args.length == 0) {
sender.sendMessage("Usage: " + usageMessage);
return false;
}
String modeArg = args[0];
int value = -1;
try {
value = Integer.parseInt(modeArg);
} catch (NumberFormatException ex) {}
GameMode mode = GameMode.getByValue(value);
if (mode == null) {
if (modeArg.equalsIgnoreCase("creative") || modeArg.equalsIgnoreCase("c")) {
mode = GameMode.CREATIVE;
} else if (modeArg.equalsIgnoreCase("adventure") || modeArg.equalsIgnoreCase("a")) {
mode = GameMode.ADVENTURE;
} else {
mode = GameMode.SURVIVAL;
}
}
Bukkit.getServer().setDefaultGameMode(mode);
Command.broadcastCommandMessage(sender, "Default game mode set to " + mode.toString().toLowerCase());
return true;
}
@Override
public List<String> tabComplete(CommandSender sender, String alias, String[] args) {
Validate.notNull(sender, "Sender cannot be null");
Validate.notNull(args, "Arguments cannot be null");
Validate.notNull(alias, "Alias cannot be null");
if (args.length == 1) {
return StringUtil.copyPartialMatches(args[0], GAMEMODE_NAMES, new ArrayList<String>(GAMEMODE_NAMES.size()));
}
return ImmutableList.of();
}
}
| 1 | 0.882117 | 1 | 0.882117 | game-dev | MEDIA | 0.962713 | game-dev | 0.866517 | 1 | 0.866517 |
Simplifine-gamedev/orca-engine | 4,297 | modules/jolt_physics/shapes/jolt_cylinder_shape_3d.cpp | /**************************************************************************/
/* jolt_cylinder_shape_3d.cpp */
/**************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/**************************************************************************/
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* 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 "jolt_cylinder_shape_3d.h"
#include "../jolt_project_settings.h"
#include "../misc/jolt_type_conversions.h"
#include "Jolt/Physics/Collision/Shape/CylinderShape.h"
JPH::ShapeRefC JoltCylinderShape3D::_build() const {
const float half_height = height / 2.0f;
const float min_half_extent = MIN(half_height, radius);
const float actual_margin = MIN(margin, min_half_extent * JoltProjectSettings::collision_margin_fraction);
const JPH::CylinderShapeSettings shape_settings(half_height, radius, actual_margin);
const JPH::ShapeSettings::ShapeResult shape_result = shape_settings.Create();
ERR_FAIL_COND_V_MSG(shape_result.HasError(), nullptr, vformat("Failed to build Jolt Physics cylinder shape with %s. It returned the following error: '%s'. This shape belongs to %s.", to_string(), to_godot(shape_result.GetError()), _owners_to_string()));
return shape_result.Get();
}
Variant JoltCylinderShape3D::get_data() const {
Dictionary data;
data["height"] = height;
data["radius"] = radius;
return data;
}
void JoltCylinderShape3D::set_data(const Variant &p_data) {
ERR_FAIL_COND(p_data.get_type() != Variant::DICTIONARY);
const Dictionary data = p_data;
const Variant maybe_height = data.get("height", Variant());
ERR_FAIL_COND(maybe_height.get_type() != Variant::FLOAT);
const Variant maybe_radius = data.get("radius", Variant());
ERR_FAIL_COND(maybe_radius.get_type() != Variant::FLOAT);
const float new_height = maybe_height;
const float new_radius = maybe_radius;
if (unlikely(new_height == height && new_radius == radius)) {
return;
}
height = new_height;
radius = new_radius;
destroy();
}
void JoltCylinderShape3D::set_margin(float p_margin) {
if (unlikely(margin == p_margin)) {
return;
}
margin = p_margin;
destroy();
}
AABB JoltCylinderShape3D::get_aabb() const {
const Vector3 half_extents(radius, height / 2.0f, radius);
return AABB(-half_extents, half_extents * 2.0f);
}
String JoltCylinderShape3D::to_string() const {
return vformat("{height=%f radius=%f margin=%f}", height, radius, margin);
}
| 1 | 0.921776 | 1 | 0.921776 | game-dev | MEDIA | 0.899834 | game-dev | 0.932905 | 1 | 0.932905 |
CodingGay/BlackDex | 1,031 | Bcore/src/main/cpp/Dobby/external/xnucxx/xnucxx/LiteIterator.h | #ifndef LITE_ITERATOR_H
#define LITE_ITERATOR_H
#include "xnucxx/LiteObject.h"
class LiteIteratorInterface : public LiteObject {
public:
class Delegate {
public:
virtual bool initIterator(void *iterationContext) const = 0;
virtual bool getNextObjectForIterator(void *iterationContext, LiteObject **nextObject) const = 0;
};
public:
virtual void reset() = 0;
virtual LiteObject *getNextObject() = 0;
};
class LiteCollectionInterface;
class LiteCollectionIterator : public LiteIteratorInterface {
protected:
const LiteCollectionInterface *collection;
void *innerIterator;
public:
explicit LiteCollectionIterator(const LiteCollectionInterface *collection) {
initWithCollection(collection);
}
~LiteCollectionIterator() {
release();
}
// === LiteObject override ===
void release() override;
// === LiteIteratorInterface override ===
void reset() override;
LiteObject *getNextObject() override;
bool initWithCollection(const LiteCollectionInterface *collection);
};
#endif
| 1 | 0.90217 | 1 | 0.90217 | game-dev | MEDIA | 0.826252 | game-dev | 0.702234 | 1 | 0.702234 |
Mino260806/MessengerPro | 1,158 | app/src/main/java/tn/amin/mpro2/text/parser/node/portal/SimpleNodePortal.java | package tn.amin.mpro2.text.parser.node.portal;
import java.util.List;
import tn.amin.mpro2.text.parser.node.Node;
public class SimpleNodePortal extends NodePortal {
private final int mBeginIndex;
private final int mEndIndex;
private final int mContentBeginIndex;
private final int mContentEndIndex;
private final NodeProvider mNodeProvider;
public SimpleNodePortal(int beginIndex, int endIndex, int contentBeginIndex, int contentEndIndex, NodeProvider nodeProvider) {
mBeginIndex = beginIndex;
mEndIndex = endIndex;
mNodeProvider = nodeProvider;
mContentBeginIndex = contentBeginIndex;
mContentEndIndex = contentEndIndex;
}
@Override
public int getBeginIndex() {
return mBeginIndex;
}
@Override
public int getEndIndex() {
return mEndIndex;
}
@Override
public int getContentBeginIndex() {
return mContentBeginIndex;
}
@Override
public int getContentEndIndex() {
return mContentEndIndex;
}
@Override
public Node getNode(List<Node> children) {
return mNodeProvider.get(children);
}
}
| 1 | 0.80417 | 1 | 0.80417 | game-dev | MEDIA | 0.331808 | game-dev | 0.800353 | 1 | 0.800353 |
jayden320/flutter_shuqi | 1,008 | lib/utility/event_bus.dart | //订阅者回调签名
typedef void EventCallback(arg);
class EventBus {
//私有构造函数
EventBus._internal();
//保存单例
static EventBus _singleton = EventBus._internal();
//工厂构造函数
factory EventBus() => _singleton;
//保存事件订阅者队列,key:事件名(id),value: 对应事件的订阅者队列
var _emap = Map<Object, List<EventCallback>?>();
//添加订阅者
void on(eventName, EventCallback f) {
if (eventName == null) return;
_emap[eventName] ??= [];
_emap[eventName]!.add(f);
}
//移除订阅者
void off(eventName, [EventCallback? f]) {
var list = _emap[eventName];
if (eventName == null || list == null) return;
if (f == null) {
_emap[eventName] = null;
} else {
list.remove(f);
}
}
//触发事件,事件触发后该事件所有订阅者会被调用
void emit(eventName, [arg]) {
var list = _emap[eventName];
if (list == null) return;
int len = list.length - 1;
//反向遍历,防止在订阅者在回调中移除自身带来的下标错位
for (var i = len; i > -1; --i) {
list[i](arg);
}
}
}
//定义一个top-level变量,页面引入该文件后可以直接使用bus
var eventBus = EventBus();
| 1 | 0.777588 | 1 | 0.777588 | game-dev | MEDIA | 0.754208 | game-dev | 0.850245 | 1 | 0.850245 |
gerstrong/Commander-Genius | 10,787 | src/engine/keen/vorticon/CPlayerItems.cpp | /*
* CPlayerItems.cpp
*
* Created on: 07.10.2009
* Author: gerstrong
*
* Those are additional functions that
* aid the player when he collects something. It's
* mainly for goodies
*/
#include "ai/CPlayer.h"
#include <base/audio/Audio.h>
#include "graphics/GsGraphics.h"
#include "engine/core/spritedefines.h"
#include "ai/CManglingMachine.h"
#include "ai/CDoor.h"
#include "ai/CRisingPoints.h"
#include "ai/CAnkhShield.h"
#include <base/interface/StringUtils.h>
#include <base/GsEventContainer.h>
#include <fileio/KeenFiles.h>
#define DOOR_YELLOW 2
#define DOOR_RED 3
#define DOOR_GREEN 4
#define DOOR_BLUE 5
// let's have keen be able to pick up goodies
void CPlayer::getgoodies()
{
if( getGoodie((getXLeftPos())>>CSF, (getYUpPos())>>CSF) ) return; // Upper-Left
else if(getGoodie((getXRightPos())>>CSF, (getYUpPos())>>CSF) ) return; // Upper-Right
else if(getGoodie(((getXLeftPos())>>CSF), ((getYDownPos())>>CSF)) ) return; // Lower-Left
else if(getGoodie(((getXRightPos())>>CSF), ((getYDownPos())>>CSF)) ) return; // Lower-Right
}
// have keen pick up the goodie at screen pixel position (px, py)
bool CPlayer::getGoodie(int px, int py)
{
std::vector<CTileProperties> &TileProperty = gBehaviorEngine.getTileProperties();
Uint16 tile = mpMap->at(px, py);
auto behaviour = TileProperty[tile].behaviour;
if (behaviour>0 && behaviour<31)
{
if ((TileProperty[tile].behaviour < 17 && TileProperty[tile].behaviour > 5) ||
(TileProperty[tile].behaviour > 17 && TileProperty[tile].behaviour < 22) ||
(TileProperty[tile].behaviour == 27 || TileProperty[tile].behaviour == 28) ) // All pickupable items
{ // pick up the goodie, i.e. erase it from the map
mpMap->changeTile(px, py, TileProperty[tile].chgtile);
}
else if (TileProperty[tile].behaviour == 1) // Lethal (Deadly) Behavoir
{ // whoah, this "goodie" isn't so good...
kill();
}
// do whatever the goodie is supposed to do...
procGoodie(tile, px, py);
return true;
}
return false;
}
void CPlayer::procGoodie(int tile, int mpx, int mpy)
{
std::vector<CTileProperties> &TileProperty = gBehaviorEngine.getTileProperties();
Uint8 behaviour = TileProperty[tile].behaviour;
if ( (behaviour > 5 && behaviour < 11) || (behaviour > 17 && behaviour < 22) )
{
playSound(GameSound::GET_BONUS);
}
else if (behaviour > 10 && behaviour < 16)
{
playSound(GameSound::GET_ITEM);
}
char shotInc = 5;
gs_byte *exeptr = gKeenFiles.exeFile.getRawData();
switch(behaviour)
{
// keycards
case 18: give_keycard(DOOR_YELLOW);
riseBonus(PTCARDY_SPRITE, mpx, mpy);
break;
case 19: give_keycard(DOOR_RED);
riseBonus(PTCARDR_SPRITE, mpx, mpy);
break;
case 20: give_keycard(DOOR_GREEN);
riseBonus(PTCARDG_SPRITE, mpx, mpy);
break;
case 21: give_keycard(DOOR_BLUE);
riseBonus(PTCARDB_SPRITE, mpx, mpy);
break;
case DOOR_YELLOW:
if (inventory.HasCardYellow)
openDoor(DOOR_YELLOW, DOOR_YELLOW_SPRITE, mpx, mpy);
break;
case DOOR_RED:
if (inventory.HasCardRed)
openDoor(DOOR_RED, DOOR_RED_SPRITE, mpx, mpy);
break;
case DOOR_GREEN:
if (inventory.HasCardGreen)
openDoor(DOOR_GREEN, DOOR_GREEN_SPRITE, mpx, mpy);
break;
case DOOR_BLUE:
if (inventory.HasCardBlue)
openDoor(DOOR_BLUE, DOOR_BLUE_SPRITE, mpx, mpy);
break;
case 7: // What gives you 100 Points
getBonuspoints(100, mpx, mpy);
break;
case 8: // What gives you 200 Points
getBonuspoints(200, mpx, mpy);
break;
case 6: // What gives you 500 Points
getBonuspoints(500, mpx, mpy);
break;
case 9: // What gives you 1000 Points
getBonuspoints(1000, mpx, mpy);
break;
case 10: // What gives you 5000 Points
getBonuspoints(5000, mpx, mpy);
break;
case 15: // raygun
riseBonus(GUNUP_SPRITE, mpx, mpy);
if (gBehaviorEngine.mDifficulty <= EASY)
{
inventory.charges += 8;
}
else
{
if( gBehaviorEngine.getEpisode() == 2) // Keen Null
memcpy(&shotInc, exeptr+0x728C, 1 );
inventory.charges += shotInc;
}
break;
case 16: // the Holy Pogo Stick
inventory.HasPogo = 1;
playSound(GameSound::GET_PART);
break;
case 11:
inventory.canlooseitem[0] = !(inventory.HasJoystick);
inventory.HasJoystick = true;
playSound(GameSound::GET_PART);
getBonuspoints(10000, mpx, mpy);
break;
case 12:
inventory.canlooseitem[1] = !(inventory.HasBattery);
inventory.HasBattery = true;
playSound(GameSound::GET_PART);
getBonuspoints(10000, mpx, mpy);
break;
case 13:
inventory.canlooseitem[2] = !(inventory.HasVacuum);
inventory.HasVacuum = true;
playSound(GameSound::GET_PART);
getBonuspoints(10000, mpx, mpy);
break;
case 14:
inventory.canlooseitem[3] = !(inventory.HasWiskey);
inventory.HasWiskey = true;
playSound(GameSound::GET_PART);
getBonuspoints(10000, mpx, mpy);
break;
case 24:
// in-level teleporter
// (in level13.ck1 that takes you to the bonus level)
level_done = LEVEL_TELEPORTER;
break;
case 22: // Game info block (Youseein your mind or vorticon elder...)
showGameHint(mpx, mpy);
break;
case 27:
giveAnkh();
riseBonus(ANKHUP_SPRITE, mpx, mpy );
break;
case 28:
inventory.charges++;
playSound(GameSound::GET_ITEM);
riseBonus(SHOTUP_SPRITE, mpx, mpy );
break;
case 17:
if(!pfrozentime)
touchedExit(mpx);
break;
case 23:break; // these are switches. They cannot not be picked up!
case 25:break; // Refer to JumpandPogo to check the activation code
case 26:break;
default:
break;
}
}
// make some sprite fly (Points, and items) :-)
void CPlayer::riseBonus(int spr, int x, int y)
{
if (gBehaviorEngine.mOptions[GameOption::RISEBONUS].value)
{
CRisingPoints *GotPointsObj = new CRisingPoints(mpMap, x<<CSF, y<<CSF);
GotPointsObj->mSpriteIdx = spr;
gEventManager.add(new EventSpawnObject(GotPointsObj) );
}
}
// gives keycard for door doortile to player p
void CPlayer::give_keycard(const int doortile)
{
size_t maxkeycards = (gBehaviorEngine.mOptions[GameOption::KEYSTACK].value) ? 9 : 1;
playSound(GameSound::GET_CARD);
if (doortile==DOOR_YELLOW && inventory.HasCardYellow < maxkeycards)
inventory.HasCardYellow++;
else if (doortile==DOOR_RED && inventory.HasCardRed < maxkeycards)
inventory.HasCardRed++;
else if (doortile==DOOR_GREEN && inventory.HasCardGreen < maxkeycards)
inventory.HasCardGreen++;
else if (doortile==DOOR_BLUE && inventory.HasCardBlue < maxkeycards)
inventory.HasCardBlue++;
}
// take away the specified keycard from the player
void CPlayer::take_keycard(const int doortile)
{
if (doortile==DOOR_YELLOW && inventory.HasCardYellow > 0)
inventory.HasCardYellow--;
else if (doortile==DOOR_RED && inventory.HasCardRed > 0)
inventory.HasCardRed--;
else if (doortile==DOOR_GREEN && inventory.HasCardGreen > 0)
inventory.HasCardGreen--;
else if (doortile==DOOR_BLUE && inventory.HasCardBlue > 0)
inventory.HasCardBlue--;
}
bool CPlayer::showGameHint(const int mpx, const int mpy)
{
if(hintused) return false;
const int ep = gBehaviorEngine.getEpisode();
const int level = mpMap->getLevel();
if(ep == 1)
{
if(mpMap->at(mpx, mpy) >= 435 && mpMap->at(mpx, mpy) <= 438)
{
// it's a garg statue
int tile = gBehaviorEngine.getPhysicsSettings().misc.one_eyed_tile;
mpMap->setTile(mpx, mpy, tile, true);
}
else // It's a yorp statue.. or something else
{
mpMap->setTile(mpx, mpy, 315, true);
}
hintstring = "EP1_YSIYM_LVL" + itoa(level);
}
else if(ep == 2)
{
// Keen 2 seems to have a bug with those tiles.
// On other parts on the map they can be triggered
// This small condition should fix that bug
int t = mpMap->at(mpx, mpy+1);
if(t != 429) return false;
// make the switch stop glowing
switch(level)
{
case 8:
hintstring = "EP2_VE_NOJUMPINDARK";
break;
case 10:
hintstring = "EP2_VE_EVILBELTS";
break;
default:
return false;
}
mpMap->setTile(mpx, mpy+1, 13*14, true);
}
hintused = true;
return true;
}
std::string CPlayer::pollHintMessage()
{
if(hintstring != "")
{
std::string text = hintstring;
hintstring = "";
return text;
}
return hintstring;
}
void CPlayer::getBonuspoints(int numpts, int mpx, int mpy)
{
playSound(GameSound::GET_BONUS);
incScore(numpts);
int spr;
switch(numpts)
{
case 100: spr = PT100_SPRITE; break;
case 200: spr = PT200_SPRITE; break;
case 500: spr = PT500_SPRITE; break;
case 1000: spr = PT1000_SPRITE; break;
case 5000: spr = PT5000_SPRITE; break;
default: spr = 0; break;
}
if (spr) riseBonus(spr, mpx, mpy);
}
void CPlayer::incScore(int numpts)
{
inventory.score += numpts;
// check if score is > than "extra life at"
if (inventory.score >= inventory.extralifeat)
{
gAudio.stopSound(int(GameSound::GET_BONUS));
playSound(GameSound::EXTRA_LIFE);
inventory.lives++;
inventory.extralifeat += 20000;
}
}
void CPlayer::openDoor(int doortile, int doorsprite, int mpx, int mpy)
{
int chgtotile;
short tilefix=0;
std::vector<CTileProperties> &TileProperty = gBehaviorEngine.getTileProperties();
playSound(GameSound::DOOR_OPEN);
take_keycard(doortile);
const int ep = gBehaviorEngine.getEpisode();
// erase door from map
if (ep==3) chgtotile = mpMap->at(mpx-1, mpy);
else chgtotile = TileProperty[mpMap->at(mpx ,mpy)].chgtile;
if(TileProperty[mpMap->at(mpx ,mpy-1)].behaviour>1 &&
TileProperty[mpMap->at(mpx ,mpy-1)].behaviour<6 ) // This happens because, sometimes the player opens the door
{ // from a lower part.
mpMap->setTile(mpx, mpy-1, chgtotile);
tilefix=1;
}
if(TileProperty[mpMap->at(mpx ,mpy)].behaviour>1 &&
TileProperty[mpMap->at(mpx ,mpy)].behaviour<6) // This happens because, sometimes the player opens the door
{ // from a lower part.
mpMap->setTile(mpx, mpy, chgtotile); // upper?
}
if(TileProperty[mpMap->at(mpx, mpy+1)].behaviour>1 &&
TileProperty[mpMap->at(mpx, mpy+1)].behaviour<6) // This happens because, sometimes the player opens the door
{ // from a lower part.
mpMap->setTile(mpx, mpy+1, chgtotile); // When he stands in front of the door!
}
// replace the door tiles with a door object, which will do the animation
CDoor *doorobj = new CDoor(mpMap, mpx<<CSF,(mpy-tilefix)<<CSF, doorsprite);
gEventManager.add(new EventSpawnObject(doorobj) );
}
void CPlayer::giveAnkh()
{
playSound(GameSound::ANKH);
if(ankhtime == 0)
{
gEventManager.add(new EventSpawnObject(new CAnkhShield(*this)) );
}
ankhtime = PLAY_ANKH_TIME;
}
| 1 | 0.923136 | 1 | 0.923136 | game-dev | MEDIA | 0.931487 | game-dev | 0.971554 | 1 | 0.971554 |
kumaransg/LLD | 3,010 | Low_level_Design_Problems/SystemDesign/ElevatorDesign/Elevator.java | package SystemDesign.ElevatorDesign;
public class Elevator {
public enum DIRECTION {
NONE, UP, DOWN
}
private DIRECTION direction = DIRECTION.NONE;
private Boolean move = false;
private boolean [] floors;
private int countUp = 0;
private int countDown = 0;
private int cf = 0;
private int min = Constants.MIN_FLOOR;
private int max = Constants.MAX_FLOOR;
private int numFloors;
private ElevatorEventListener elEventListener;
public Elevator(int numFloors) {
if(numFloors<0) throw new IllegalArgumentException();
this.numFloors = numFloors;
floors = new boolean [numFloors];
}
public Integer getCurrentFloor() {
return cf;
}
public int getGoalFloor() {
if(direction == DIRECTION.UP ) return max;
if(direction == DIRECTION.DOWN ) return min;
return -1;
}
public void moveNext(){
if(!move) {
move = (direction != DIRECTION.NONE);
return;
}
if(direction == DIRECTION.UP) {
if(floors[++cf]) {
floors[cf] = false;
if(--countUp == 0) {
direction = (countDown == 0)?(DIRECTION.NONE):(DIRECTION.DOWN);
max = Constants.MAX_FLOOR;
}
move = false;
if(elEventListener != null) elEventListener.onStopped(this);
}
return;
}
if (direction == DIRECTION.DOWN) {
if(floors[--cf]) {
floors[cf] = false;
if(++countDown == 0) {
direction = (countUp == 0)?(DIRECTION.NONE):(DIRECTION.UP);
min = Constants.MIN_FLOOR;
}
move = false;
if(elEventListener != null) elEventListener.onStopped(this);
}
}
}
public void setGoalFloor(int gf) {
if((gf<0) || (gf >= numFloors ) ) throw new IllegalArgumentException();
if(cf == gf) return;
if(floors[gf]) return;
floors[gf] = true;
if(gf>cf) { countUp++; max = (gf>max)?(gf):(max); }
if(gf<cf) { countDown--; min = (gf<min)?(gf):(min); }
if(direction == DIRECTION.NONE)
direction = (gf>cf)?(DIRECTION.UP):(DIRECTION.DOWN);
}
public void reset() {
cf = countUp = countDown = 0;
move = false;
direction = DIRECTION.NONE;
floors = new boolean [numFloors];
max = Constants.MAX_FLOOR; min = Constants.MIN_FLOOR;
}
public void moveToFloor(int floor) {
if((floor<0) || (floor >= numFloors ) ) throw new IllegalArgumentException();
reset();
cf = floor;
}
public boolean getMove() {
return move;
}
public DIRECTION getDirection() {
return direction;
}
public void setElEventListener(ElevatorEventListener elEventListener) {
this.elEventListener = elEventListener;
}
}
| 1 | 0.729876 | 1 | 0.729876 | game-dev | MEDIA | 0.52764 | game-dev | 0.859116 | 1 | 0.859116 |
ashishgopalhattimare/PathMarkAR | 12,163 | Library/PackageCache/com.unity.textmeshpro@1.3.0/Scripts/Editor/TMP_InputFieldEditor.cs | using UnityEngine;
using UnityEngine.UI;
using UnityEditor;
using UnityEditor.UI;
using UnityEditor.AnimatedValues;
namespace TMPro.EditorUtilities
{
[CanEditMultipleObjects]
[CustomEditor(typeof(TMP_InputField), true)]
public class TMP_InputFieldEditor : SelectableEditor
{
private struct m_foldout
{ // Track Inspector foldout panel states, globally.
public static bool textInput = true;
public static bool fontSettings = true;
public static bool extraSettings = true;
//public static bool shadowSetting = false;
//public static bool materialEditor = true;
}
SerializedProperty m_TextViewport;
SerializedProperty m_TextComponent;
SerializedProperty m_Text;
SerializedProperty m_ContentType;
SerializedProperty m_LineType;
SerializedProperty m_InputType;
SerializedProperty m_CharacterValidation;
SerializedProperty m_InputValidator;
SerializedProperty m_RegexValue;
SerializedProperty m_KeyboardType;
SerializedProperty m_CharacterLimit;
SerializedProperty m_CaretBlinkRate;
SerializedProperty m_CaretWidth;
SerializedProperty m_CaretColor;
SerializedProperty m_CustomCaretColor;
SerializedProperty m_SelectionColor;
SerializedProperty m_HideMobileInput;
SerializedProperty m_Placeholder;
SerializedProperty m_VerticalScrollbar;
SerializedProperty m_ScrollbarScrollSensitivity;
SerializedProperty m_OnValueChanged;
SerializedProperty m_OnEndEdit;
SerializedProperty m_OnSelect;
SerializedProperty m_OnDeselect;
SerializedProperty m_ReadOnly;
SerializedProperty m_RichText;
SerializedProperty m_RichTextEditingAllowed;
SerializedProperty m_ResetOnDeActivation;
SerializedProperty m_RestoreOriginalTextOnEscape;
SerializedProperty m_OnFocusSelectAll;
SerializedProperty m_GlobalPointSize;
SerializedProperty m_GlobalFontAsset;
AnimBool m_CustomColor;
//TMP_InputValidator m_ValidationScript;
protected override void OnEnable()
{
base.OnEnable();
m_TextViewport = serializedObject.FindProperty("m_TextViewport");
m_TextComponent = serializedObject.FindProperty("m_TextComponent");
m_Text = serializedObject.FindProperty("m_Text");
m_ContentType = serializedObject.FindProperty("m_ContentType");
m_LineType = serializedObject.FindProperty("m_LineType");
m_InputType = serializedObject.FindProperty("m_InputType");
m_CharacterValidation = serializedObject.FindProperty("m_CharacterValidation");
m_InputValidator = serializedObject.FindProperty("m_InputValidator");
m_RegexValue = serializedObject.FindProperty("m_RegexValue");
m_KeyboardType = serializedObject.FindProperty("m_KeyboardType");
m_CharacterLimit = serializedObject.FindProperty("m_CharacterLimit");
m_CaretBlinkRate = serializedObject.FindProperty("m_CaretBlinkRate");
m_CaretWidth = serializedObject.FindProperty("m_CaretWidth");
m_CaretColor = serializedObject.FindProperty("m_CaretColor");
m_CustomCaretColor = serializedObject.FindProperty("m_CustomCaretColor");
m_SelectionColor = serializedObject.FindProperty("m_SelectionColor");
m_HideMobileInput = serializedObject.FindProperty("m_HideMobileInput");
m_Placeholder = serializedObject.FindProperty("m_Placeholder");
m_VerticalScrollbar = serializedObject.FindProperty("m_VerticalScrollbar");
m_ScrollbarScrollSensitivity = serializedObject.FindProperty("m_ScrollSensitivity");
m_OnValueChanged = serializedObject.FindProperty("m_OnValueChanged");
m_OnEndEdit = serializedObject.FindProperty("m_OnEndEdit");
m_OnSelect = serializedObject.FindProperty("m_OnSelect");
m_OnDeselect = serializedObject.FindProperty("m_OnDeselect");
m_ReadOnly = serializedObject.FindProperty("m_ReadOnly");
m_RichText = serializedObject.FindProperty("m_RichText");
m_RichTextEditingAllowed = serializedObject.FindProperty("m_isRichTextEditingAllowed");
m_ResetOnDeActivation = serializedObject.FindProperty("m_ResetOnDeActivation");
m_RestoreOriginalTextOnEscape = serializedObject.FindProperty("m_RestoreOriginalTextOnEscape");
m_OnFocusSelectAll = serializedObject.FindProperty("m_OnFocusSelectAll");
m_GlobalPointSize = serializedObject.FindProperty("m_GlobalPointSize");
m_GlobalFontAsset = serializedObject.FindProperty("m_GlobalFontAsset");
m_CustomColor = new AnimBool(m_CustomCaretColor.boolValue);
m_CustomColor.valueChanged.AddListener(Repaint);
}
protected override void OnDisable()
{
base.OnDisable();
m_CustomColor.valueChanged.RemoveListener(Repaint);
}
public override void OnInspectorGUI()
{
serializedObject.Update();
base.OnInspectorGUI();
EditorGUILayout.Space();
EditorGUILayout.PropertyField(m_TextViewport);
EditorGUILayout.PropertyField(m_TextComponent);
TextMeshProUGUI text = null;
if (m_TextComponent != null && m_TextComponent.objectReferenceValue != null)
{
text = m_TextComponent.objectReferenceValue as TextMeshProUGUI;
//if (text.supportRichText)
//{
// EditorGUILayout.HelpBox("Using Rich Text with input is unsupported.", MessageType.Warning);
//}
}
EditorGUI.BeginDisabledGroup(m_TextComponent == null || m_TextComponent.objectReferenceValue == null);
// TEXT INPUT BOX
EditorGUILayout.PropertyField(m_Text);
// INPUT FIELD SETTINGS
#region INPUT FIELD SETTINGS
m_foldout.fontSettings = EditorGUILayout.Foldout(m_foldout.fontSettings, "Input Field Settings", true, TMP_UIStyleManager.boldFoldout);
if (m_foldout.fontSettings)
{
EditorGUI.indentLevel++;
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_GlobalFontAsset, new GUIContent("Font Asset", "Set the Font Asset for both Placeholder and Input Field text object."));
if (EditorGUI.EndChangeCheck())
{
TMP_InputField inputField = target as TMP_InputField;
inputField.SetGlobalFontAsset(m_GlobalFontAsset.objectReferenceValue as TMP_FontAsset);
}
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_GlobalPointSize, new GUIContent("Point Size", "Set the point size of both Placeholder and Input Field text object."));
if (EditorGUI.EndChangeCheck())
{
TMP_InputField inputField = target as TMP_InputField;
inputField.SetGlobalPointSize(m_GlobalPointSize.floatValue);
}
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_CharacterLimit);
EditorGUILayout.Space();
EditorGUILayout.PropertyField(m_ContentType);
if (!m_ContentType.hasMultipleDifferentValues)
{
EditorGUI.indentLevel++;
if (m_ContentType.enumValueIndex == (int)TMP_InputField.ContentType.Standard ||
m_ContentType.enumValueIndex == (int)TMP_InputField.ContentType.Autocorrected ||
m_ContentType.enumValueIndex == (int)TMP_InputField.ContentType.Custom)
{
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_LineType);
if (EditorGUI.EndChangeCheck())
{
if (text != null)
{
if (m_LineType.enumValueIndex == (int)TMP_InputField.LineType.SingleLine)
text.enableWordWrapping = false;
else
text.enableWordWrapping = true;
}
}
}
if (m_ContentType.enumValueIndex == (int)TMP_InputField.ContentType.Custom)
{
EditorGUILayout.PropertyField(m_InputType);
EditorGUILayout.PropertyField(m_KeyboardType);
EditorGUILayout.PropertyField(m_CharacterValidation);
if (m_CharacterValidation.enumValueIndex == (int)TMP_InputField.CharacterValidation.Regex)
{
EditorGUILayout.PropertyField(m_RegexValue);
}
else if (m_CharacterValidation.enumValueIndex == (int)TMP_InputField.CharacterValidation.CustomValidator)
{
EditorGUILayout.PropertyField(m_InputValidator);
}
}
EditorGUI.indentLevel--;
}
EditorGUILayout.Space();
EditorGUILayout.PropertyField(m_Placeholder);
EditorGUILayout.PropertyField(m_VerticalScrollbar);
if (m_VerticalScrollbar.objectReferenceValue != null)
EditorGUILayout.PropertyField(m_ScrollbarScrollSensitivity);
EditorGUILayout.PropertyField(m_CaretBlinkRate);
EditorGUILayout.PropertyField(m_CaretWidth);
EditorGUILayout.PropertyField(m_CustomCaretColor);
m_CustomColor.target = m_CustomCaretColor.boolValue;
if (EditorGUILayout.BeginFadeGroup(m_CustomColor.faded))
{
EditorGUILayout.PropertyField(m_CaretColor);
}
EditorGUILayout.EndFadeGroup();
EditorGUILayout.PropertyField(m_SelectionColor);
EditorGUI.indentLevel--;
}
#endregion
// CONTROL SETTINGS
#region CONTROL SETTINGS
m_foldout.extraSettings = EditorGUILayout.Foldout(m_foldout.extraSettings, "Control Settings", true, TMP_UIStyleManager.boldFoldout);
if (m_foldout.extraSettings)
{
EditorGUI.indentLevel++;
EditorGUILayout.PropertyField(m_OnFocusSelectAll, new GUIContent("OnFocus - Select All", "Should all the text be selected when the Input Field is selected."));
EditorGUILayout.PropertyField(m_ResetOnDeActivation, new GUIContent("Reset On DeActivation", "Should the Text and Caret position be reset when Input Field is DeActivated."));
EditorGUILayout.PropertyField(m_RestoreOriginalTextOnEscape, new GUIContent("Restore On ESC Key", "Should the original text be restored when pressing ESC."));
EditorGUILayout.PropertyField(m_HideMobileInput);
EditorGUILayout.PropertyField(m_ReadOnly);
EditorGUILayout.PropertyField(m_RichText);
EditorGUILayout.PropertyField(m_RichTextEditingAllowed, new GUIContent("Allow Rich Text Editing"));
EditorGUI.indentLevel--;
}
#endregion
EditorGUILayout.Space();
EditorGUILayout.PropertyField(m_OnValueChanged);
EditorGUILayout.PropertyField(m_OnEndEdit);
EditorGUILayout.PropertyField(m_OnSelect);
EditorGUILayout.PropertyField(m_OnDeselect);
EditorGUI.EndDisabledGroup();
serializedObject.ApplyModifiedProperties();
}
}
}
| 1 | 0.886576 | 1 | 0.886576 | game-dev | MEDIA | 0.92134 | game-dev | 0.959593 | 1 | 0.959593 |
berkeley-abc/abc | 8,648 | src/proof/acec/acecStruct.c | /**CFile****************************************************************
FileName [acecStruct.c]
SystemName [ABC: Logic synthesis and verification system.]
PackageName [CEC for arithmetic circuits.]
Synopsis [Core procedures.]
Author [Alan Mishchenko]
Affiliation [UC Berkeley]
Date [Ver. 1.0. Started - June 20, 2005.]
Revision [$Id: acecStruct.c,v 1.00 2005/06/20 00:00:00 alanmi Exp $]
***********************************************************************/
#include "acecInt.h"
#include "misc/vec/vecWec.h"
#include "misc/extra/extra.h"
ABC_NAMESPACE_IMPL_START
////////////////////////////////////////////////////////////////////////
/// DECLARATIONS ///
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
/// FUNCTION DEFINITIONS ///
////////////////////////////////////////////////////////////////////////
/**Function*************************************************************
Synopsis []
Description []
SideEffects []
SeeAlso []
***********************************************************************/
Vec_Int_t * Acec_StructDetectXorRoots( Gia_Man_t * p )
{
Vec_Int_t * vXors = Vec_IntAlloc( 100 );
Vec_Bit_t * vXorIns = Vec_BitStart( Gia_ManObjNum(p) );
Gia_Obj_t * pFan0, * pFan1, * pObj;
int i, k = 0, Entry;
Gia_ManForEachAnd( p, pObj, i )
{
if ( !Gia_ObjRecognizeExor(pObj, &pFan0, &pFan1) )
continue;
Vec_IntPush( vXors, i );
Vec_BitWriteEntry( vXorIns, Gia_ObjId(p, Gia_Regular(pFan0)), 1 );
Vec_BitWriteEntry( vXorIns, Gia_ObjId(p, Gia_Regular(pFan1)), 1 );
}
// collect XORs that not inputs of other XORs
Vec_IntForEachEntry( vXors, Entry, i )
if ( !Vec_BitEntry(vXorIns, Entry) )
Vec_IntWriteEntry( vXors, k++, Entry );
Vec_IntShrink( vXors, k );
Vec_BitFree( vXorIns );
return vXors;
}
/**Function*************************************************************
Synopsis []
Description []
SideEffects []
SeeAlso []
***********************************************************************/
Vec_Int_t * Acec_StructAssignRanks( Gia_Man_t * p, Vec_Int_t * vXorRoots )
{
Vec_Int_t * vDoubles = Vec_IntAlloc( 100 );
Gia_Obj_t * pFan0, * pFan1, * pObj;
int i, k, Fanins[2], Entry, Rank;
// map roots into their ranks
Vec_Int_t * vRanks = Vec_IntStartFull( Gia_ManObjNum(p) );
Vec_IntForEachEntry( vXorRoots, Entry, i )
Vec_IntWriteEntry( vRanks, Entry, i );
// map nodes into their ranks
Gia_ManForEachAndReverse( p, pObj, i )
{
if ( !Gia_ObjRecognizeExor(pObj, &pFan0, &pFan1) )
continue;
Rank = Vec_IntEntry( vRanks, i );
// skip XORs that are not part of any tree
if ( Rank == -1 )
continue;
// iterate through XOR inputs
Fanins[0] = Gia_ObjId(p, Gia_Regular(pFan0));
Fanins[1] = Gia_ObjId(p, Gia_Regular(pFan1));
for ( k = 0; k < 2; k++ )
{
Entry = Vec_IntEntry( vRanks, Fanins[k] );
if ( Entry == Rank ) // the same tree -- allow fanout in this tree
continue;
if ( Entry == -1 )
Vec_IntWriteEntry( vRanks, Fanins[k], Rank );
else
Vec_IntPush( vDoubles, Fanins[k] );
if ( Entry != -1 && Gia_ObjIsAnd(Gia_ManObj(p, Fanins[k])))
printf( "Xor node %d belongs to Tree %d and Tree %d.\n", Fanins[k], Entry, Rank );
}
}
// remove duplicated entries
Vec_IntForEachEntry( vDoubles, Entry, i )
Vec_IntWriteEntry( vRanks, Entry, -1 );
Vec_IntFree( vDoubles );
return vRanks;
}
/**Function*************************************************************
Synopsis []
Description []
SideEffects []
SeeAlso []
***********************************************************************/
Vec_Wec_t * Acec_FindTreeLeaves( Gia_Man_t * p, Vec_Int_t * vXorRoots, Vec_Int_t * vRanks )
{
Vec_Bit_t * vMapXors = Vec_BitStart( Gia_ManObjNum(p) );
Vec_Wec_t * vTreeLeaves = Vec_WecStart( Vec_IntSize(vXorRoots) );
Gia_Obj_t * pFan0, * pFan1, * pObj;
int i, k, Fanins[2], Rank;
Gia_ManForEachAnd( p, pObj, i )
{
if ( !Gia_ObjRecognizeExor(pObj, &pFan0, &pFan1) )
continue;
Vec_BitWriteEntry( vMapXors, i, 1 );
Rank = Vec_IntEntry( vRanks, i );
// skip XORs that are not part of any tree
if ( Rank == -1 )
continue;
// iterate through XOR inputs
Fanins[0] = Gia_ObjId(p, Gia_Regular(pFan0));
Fanins[1] = Gia_ObjId(p, Gia_Regular(pFan1));
for ( k = 0; k < 2; k++ )
{
if ( Vec_BitEntry(vMapXors, Fanins[k]) )
{
assert( Rank == Vec_IntEntry(vRanks, Fanins[k]) );
continue;
}
Vec_WecPush( vTreeLeaves, Rank, Fanins[k] );
}
}
Vec_BitFree( vMapXors );
return vTreeLeaves;
}
/**Function*************************************************************
Synopsis []
Description []
SideEffects []
SeeAlso []
***********************************************************************/
Vec_Int_t * Acec_FindShadows( Gia_Man_t * p, Vec_Int_t * vRanks )
{
Vec_Int_t * vShadows = Vec_IntDup( vRanks );
Gia_Obj_t * pObj; int i, Shad0, Shad1;
Gia_ManForEachCi( p, pObj, i )
Vec_IntWriteEntry( vShadows, Gia_ObjId(p, pObj), -1 );
Gia_ManForEachAnd( p, pObj, i )
{
if ( Vec_IntEntry(vShadows, i) >= 0 )
continue;
Shad0 = Vec_IntEntry(vShadows, Gia_ObjFaninId0(pObj, i));
Shad1 = Vec_IntEntry(vShadows, Gia_ObjFaninId1(pObj, i));
if ( Shad0 == Shad1 && Shad0 != -1 )
Vec_IntWriteEntry(vShadows, i, Shad0);
}
return vShadows;
}
/**Function*************************************************************
Synopsis []
Description []
SideEffects []
SeeAlso []
***********************************************************************/
int Acec_CollectSupp_rec( Gia_Man_t * p, int iNode, int Rank, Vec_Int_t * vRanks )
{
Gia_Obj_t * pObj;
int nSize;
if ( Gia_ObjIsTravIdCurrentId(p, iNode) )
return 0;
Gia_ObjSetTravIdCurrentId(p, iNode);
pObj = Gia_ManObj(p, iNode);
assert( Gia_ObjIsAnd(pObj) );
if ( Vec_IntEntry(vRanks, iNode) == Rank )
return 1;
nSize = Acec_CollectSupp_rec( p, Gia_ObjFaninId0(pObj, iNode), Rank, vRanks );
nSize += Acec_CollectSupp_rec( p, Gia_ObjFaninId1(pObj, iNode), Rank, vRanks );
return nSize;
}
Vec_Wec_t * Acec_FindNexts( Gia_Man_t * p, Vec_Int_t * vRanks, Vec_Int_t * vShadows, Vec_Wec_t * vTreeLeaves )
{
Vec_Wec_t * vNexts = Vec_WecStart( Vec_WecSize(vTreeLeaves) );
Vec_Int_t * vTree;
int i, k, Node, Fanins[2], Shad0, Shad1, Rank, nSupp;
Vec_WecForEachLevel( vTreeLeaves, vTree, i )
Vec_IntForEachEntry( vTree, Node, k )
{
Gia_Obj_t * pObj = Gia_ManObj(p, Node);
if ( !Gia_ObjIsAnd(pObj) )
continue;
Fanins[0] = Gia_ObjFaninId0(pObj, Node);
Fanins[1] = Gia_ObjFaninId1(pObj, Node);
Shad0 = Vec_IntEntry(vShadows, Fanins[0]);
Shad1 = Vec_IntEntry(vShadows, Fanins[1]);
if ( Shad0 != Shad1 || Shad0 == -1 )
continue;
// check support size of Node in terms of the shadow of its fanins
Rank = Vec_IntEntry( vRanks, Node );
assert( Rank != Shad0 );
Gia_ManIncrementTravId( p );
nSupp = Acec_CollectSupp_rec( p, Node, Shad0, vRanks );
assert( nSupp > 1 );
if ( nSupp > 3 )
continue;
Vec_IntPushUniqueOrder( Vec_WecEntry(vNexts, Shad0), Rank );
}
return vNexts;
}
/**Function*************************************************************
Synopsis []
Description []
SideEffects []
SeeAlso []
***********************************************************************/
void Acec_StructTest( Gia_Man_t * p )
{
}
////////////////////////////////////////////////////////////////////////
/// END OF FILE ///
////////////////////////////////////////////////////////////////////////
ABC_NAMESPACE_IMPL_END
| 1 | 0.698782 | 1 | 0.698782 | game-dev | MEDIA | 0.478768 | game-dev,graphics-rendering | 0.90607 | 1 | 0.90607 |
RaiderIO/keystone.guru | 13,025 | app/Console/Commands/Localization/Zone/SyncZoneNames.php | <?php
namespace App\Console\Commands\Localization\Zone;
use App\Console\Commands\Localization\Traits\ExportsTranslations;
use App\Models\Dungeon;
use App\Models\Floor\Floor;
use App\Service\Wowhead\WowheadTranslationServiceInterface;
use Exception;
use Illuminate\Console\Command;
class SyncZoneNames extends Command
{
use ExportsTranslations;
const EXCLUDE_DUNGEONS = [
Dungeon::DUNGEON_SCARLET_MONASTERY_ARMORY,
Dungeon::DUNGEON_SCARLET_MONASTERY_CATHEDRAL,
Dungeon::DUNGEON_SCARLET_MONASTERY_GRAVEYARD,
Dungeon::DUNGEON_SCARLET_MONASTERY_LIBRARY,
Dungeon::DUNGEON_DIRE_MAUL_EAST,
Dungeon::DUNGEON_DIRE_MAUL_NORTH,
Dungeon::DUNGEON_DIRE_MAUL_WEST,
Dungeon::DUNGEON_MECHAGON_JUNKYARD,
Dungeon::DUNGEON_MECHAGON_WORKSHOP,
Dungeon::DUNGEON_DAWN_OF_THE_INFINITE_GALAKRONDS_FALL,
Dungeon::DUNGEON_DAWN_OF_THE_INFINITE_MUROZONDS_RISE,
Dungeon::DUNGEON_TAZAVESH_SO_LEAHS_GAMBIT,
Dungeon::DUNGEON_TAZAVESH_STREETS_OF_WONDER,
];
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'localization:synczonenames';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Fetches the names of all zones from Wowhead and updates the localizations.';
/**
* Execute the console command.
*
*
* @throws Exception
*/
public function handle(WowheadTranslationServiceInterface $wowheadTranslationService): void
{
$updatedTranslations = $this->syncDungeonNames($wowheadTranslationService);
$updatedTranslations = $this->syncFloorNames($wowheadTranslationService, $updatedTranslations);
$this->saveTranslationsToDisk($updatedTranslations);
}
private function syncDungeonNames(WowheadTranslationServiceInterface $wowheadTranslationService): array
{
$dungeonNamesByLocale = $wowheadTranslationService->getDungeonNames();
$dungeonsById = Dungeon::all()
->keyBy('id');
// Get the existing spell names from the localization file and merge with the fetched names
$updatedTranslations = [];
foreach ($dungeonNamesByLocale as $locale => $dungeonNamesForLocale) {
$existingTranslations = __('dungeons', [], $locale);
if (!is_array($existingTranslations) || empty($existingTranslations)) {
$existingTranslations = [];
}
foreach ($dungeonNamesForLocale as $dungeonId => $dungeonName) {
/** @var Dungeon $dungeon */
$dungeon = $dungeonsById->get($dungeonId);
// Skip some zones that we split off compared to the Wowhead data
if (in_array($dungeon->key, self::EXCLUDE_DUNGEONS)) {
$this->comment(sprintf('- Skipping excluded dungeon %s', $dungeon->key));
$this->warn(sprintf('-- Got name "%s" for locale %s', $dungeonName, $locale));
continue;
}
// Ensure expansion array is set
if (!isset($updatedTranslations[$locale][$dungeon->expansion->shortname])) {
$updatedTranslations[$locale][$dungeon->expansion->shortname] = [];
}
$dungeonTranslationKey = explode('.', $dungeon->name)[2];
// Only if we didn't have a translation yet for this dungeon, we add it
// This way we can make manual corrections that won't be overwritten
if (empty($existingTranslations[$dungeon->expansion->shortname][$dungeonTranslationKey]['name'])) {
$updatedTranslations[$locale][$dungeon->expansion->shortname][$dungeonTranslationKey]['name'] = $dungeonName;
}
}
$updatedTranslations[$locale] = array_replace_recursive($existingTranslations, $updatedTranslations[$locale]);
}
return $updatedTranslations;
}
private function syncFloorNames(WowheadTranslationServiceInterface $wowheadTranslationService, array $existingTranslationsByLocale): array
{
$floorNamesByLocale = $wowheadTranslationService->getFloorNames();
$dungeonsByZoneId = Dungeon::all()
->keyBy('zone_id');
$englishFloorNames = $floorNamesByLocale->get('en_US', []);
if (empty($englishFloorNames)) {
$this->error('No zone names found for en_US locale. Please check the Wowhead data.');
return [];
}
// 1. Build up a mapping of zone IDs to their names, and where to find them.
// The zone/floor names don't match up exactly with the Wowhead data, so we need to
// construct a mapping of zone IDs/index to their names. To do this, we use the English names
// to find the zone IDs+index and then use those to find the names in the other locales.
$zoneIdIndexReference = collect();
foreach ($englishFloorNames as $zoneId => $floorNames) {
// Find the KSG floor that this translation belongs to
/** @var Dungeon $dungeon */
$dungeon = $dungeonsByZoneId->get($zoneId);
if (!($dungeon instanceof Dungeon)) {
// We don't care - there's many zones that we don't have a dungeon for
// $this->error(sprintf('No dungeon found for zone ID %d', $zoneId));
continue;
}
// Skip some zones that we split off compared to the Wowhead data
if (in_array($dungeon->key, self::EXCLUDE_DUNGEONS)) {
$this->comment(sprintf('- Skipping excluded dungeon %s for zone ID %d', $dungeon->key, $zoneId));
continue;
}
$dungeonZoneIdIndexReference = [];
// The zone name is an array of names for each floor, so we need to extract them
foreach ($floorNames as $floorIndex => $floorName) {
$found = false;
foreach ($dungeon->floors as $floor) {
if ($floorName === __($floor->name, [], 'en_US')) {
// We found the KSG floor for this name, so we can store where to find it in $dungeonZoneIdIndexReference
$dungeonZoneIdIndexReference[$floor->id] = [
'index' => $floorIndex,
// Extract the translation name key from the floor name
// 0. dungeons
// 1. bfa
// 2. atal_dazar
// 3. floors
// 4. sacrificial_pits <-- looking for this one
'translationKey' => explode('.', $floor->name)[4],
];
$found = true;
break;
}
}
if (!$found) {
$this->warn(sprintf('No floor found for zone ID %d and name "%s"', $zoneId, $floorName));
}
}
// If we have a facade floor, save the facade floor's name as the dungeon name
/** @var Floor $facadeFloor */
$facadeFloor = $dungeon->floors->firstWhere('facade', true);
if ($facadeFloor !== null) {
$dungeonZoneIdIndexReference[$facadeFloor->id] = [
// Facade floor is always the last floor (one will be added shortly so this will match up)
'index' => count($floorNames),
// Extract the translation key from the facade floor name
'translationKey' => explode('.', $facadeFloor->name)[4],
];
}
// Save the zoneID and index reference for the dungeon to the global reference
$zoneIdIndexReference->put($zoneId, $dungeonZoneIdIndexReference);
}
// 2. For all dungeons that we have, but are not in the mapping, at least add the dungeon name as the floor name
foreach ($dungeonsByZoneId as $zoneId => $dungeon) {
if (!$zoneIdIndexReference->has($zoneId)) {
// Skip some zones that we split off compared to the Wowhead data
if (in_array($dungeon->key, self::EXCLUDE_DUNGEONS)) {
$this->comment(sprintf('- Skipping excluded dungeon %s for zone ID %d', $dungeon->key, $zoneId));
continue;
}
$dungeonZoneIdIndexReference = [];
/** @var Floor $floor */
$floor = $dungeon->floors->first();
$dungeonZoneIdIndexReference[$floor->id] = [
// 0 based if the dungeon was not found in the Wowhead data
'index' => 0,
// Extract the translation key from the facade floor name
'translationKey' => explode('.', $floor->name)[4],
];
// Save the zoneID and index reference for the dungeon to the global reference
$zoneIdIndexReference->put($zoneId, $dungeonZoneIdIndexReference);
$this->info(sprintf('Added missing dungeon %s for zone ID %d to the zone ID index reference', $dungeon->key, $zoneId));
}
}
// 3. Based on this mapping, we can now construct the translation array for each locale and save it to disk
foreach ($floorNamesByLocale as $locale => $floorNamesForLocale) {
/** @var array $floorNamesForLocale */
// Now match the zone IDs to the dungeon and construct the translation array
$updatedTranslations = [];
foreach ($zoneIdIndexReference as $zoneId => $floorData) {
if ($dungeonsByZoneId->has($zoneId)) {
/** @var Dungeon $dungeon */
$dungeon = $dungeonsByZoneId->get($zoneId);
// Extract the translation name key from the floor name
// 0. dungeons
// 1. bfa
// 2. atal_dazar <-- looking for this one
$dungeonTranslationKey = explode('.', $dungeon->name)[2];
// Add the facade floor name to the list of floor names "retrieved" from Wowhead so we can resolve facade floor names
$floorNamesForLocale[$zoneId][] = $existingTranslationsByLocale[$locale][$dungeon->expansion->shortname][$dungeonTranslationKey]['name'];
$updatedTranslations[$dungeon->expansion->shortname][$dungeonTranslationKey] = [
'floors' => [],
];
foreach ($floorData as $floorId => $data) {
if (!isset($floorNamesForLocale[$zoneId][$data['index']])) {
$this->warn(sprintf('No floor name found for zone ID %d and index %d in locale %s', $zoneId, $data['index'], $locale));
continue;
}
// Only if we didn't have a translation yet for this floor, we add it
// This way we can make manual corrections that won't be overwritten
if (empty($existingTranslationsByLocale[$locale][$dungeon->expansion->shortname][$dungeonTranslationKey]['floors'][$data['translationKey']])) {
$updatedTranslations[$dungeon->expansion->shortname][$dungeonTranslationKey]['floors'][$data['translationKey']] = $floorNamesForLocale[$zoneId][$data['index']];
}
}
// if ($dungeon->key === Dungeon::DUNGEON_OPERATION_FLOODGATE) {
// dd(
// $zoneId,
//// $zoneIdIndexReference,
// $updatedTranslations[$dungeon->expansion->shortname][$dungeonTranslationKey],
// $floorNamesForLocale[$zoneId],
// $floorData
// );
// }
}
}
// Merge the existing translations with the updated translations
// This ensures that we don't overwrite existing translations that are not in the Wowhead data
$existingTranslationsByLocale[$locale] = array_replace_recursive($existingTranslationsByLocale[$locale], $updatedTranslations);
foreach ($existingTranslationsByLocale[$locale] as &$dungeons) {
ksort($dungeons);
}
}
return $existingTranslationsByLocale;
}
private function saveTranslationsToDisk(array $updatedTranslations): void
{
foreach ($updatedTranslations as $locale => $newTranslations) {
$this->exportTranslations($locale, 'dungeons.php', $newTranslations);
}
}
}
| 1 | 0.84419 | 1 | 0.84419 | game-dev | MEDIA | 0.74666 | game-dev,testing-qa | 0.846504 | 1 | 0.846504 |
shippoiincho/mz1500emulator | 3,336 | mz1500emulator/Z/classes/Shared.hpp | /* Zeta API - Z/classes/Shared.hpp
______ ______________ ___
|__ / | ___|___ ___|/ \
/ /__| __| | | / - \
/______|_____| |__| /__/ \__\
Copyright (C) 2006-2024 Manuel Sainz de Baranda y Goñi.
Released under the terms of the GNU Lesser General Public License v3. */
#ifndef Z_classes_Shared_HPP
#define Z_classes_Shared_HPP
#include <Z/constants/pointer.h>
#include <Z/macros/language.hpp>
#include <Z/types/integral.hpp>
#include <Z/types/pointer.hpp>
namespace Zeta {template <class t> struct Shared {
struct Owned {
t* data;
USize owner_count;
Z_INLINE Owned(t *data) Z_NOTHROW
: data(data), owner_count(1) {}
Z_INLINE ~Owned()
{delete data;}
};
Owned *owned;
Z_CT(CPP11) Shared() Z_NOTHROW
: owned(Z_NULL) {}
Z_INLINE Shared(const Shared &other) Z_NOTHROW
{if ((owned = other.owned)) owned->owner_count++;}
Z_INLINE Shared(t *data) Z_NOTHROW
{owned = data ? new Owned(data) : Z_NULL;}
Z_INLINE ~Shared()
{if (owned && !--owned->owner_count) delete owned;}
Z_INLINE operator Boolean() const Z_NOTHROW
{return Boolean(owned);}
Z_INLINE Shared &operator =(const Shared &rhs)
{
if (owned != rhs.owned)
{
if (owned && !--owned->owner_count) delete owned;
if ((owned = rhs.owned)) owned->owner_count++;
}
return *this;
}
Z_INLINE Shared &operator =(t *rhs)
{
if (owned)
{
if (owned->data == rhs) return *this;
if (!--owned->owner_count) delete owned;
}
owned = rhs ? new Owned(rhs) : Z_NULL;
return *this;
}
friend Z_INLINE Boolean operator ==(const Shared &lhs, const Shared &rhs) Z_NOTHROW
{return lhs.owned == rhs.owned;}
friend Z_INLINE Boolean operator !=(const Shared &lhs, const Shared &rhs) Z_NOTHROW
{return lhs.owned != rhs.owned;}
Z_INLINE t &operator *() const Z_NOTHROW
{return *owned->data;}
Z_INLINE t *operator ->() const Z_NOTHROW
{return owned->data;}
Z_INLINE t *get() const Z_NOTHROW
{return owned ? owned->data : Z_NULL;}
Z_INLINE USize owner_count() const Z_NOTHROW
{return owned->owner_count;}
Z_INLINE void reset()
{
if (owned && !--owned->owner_count) delete owned;
owned = Z_NULL;
}
Z_INLINE void swap(Shared &other) Z_NOTHROW
{
Owned *ex = owned;
owned = other.owned;
other.owned = ex;
}
# ifdef Z_NULLPTR
Z_CT(CPP11) Shared(NullPtr) Z_NOTHROW
: owned(nullptr) {}
Z_INLINE Shared &operator =(NullPtr)
{
if (owned && !--owned->owner_count) delete owned;
owned = nullptr;
return *this;
}
friend Z_INLINE Boolean operator ==(const Shared &lhs, NullPtr) Z_NOTHROW
{return !lhs.owned;}
friend Z_INLINE Boolean operator ==(NullPtr, const Shared &rhs) Z_NOTHROW
{return !rhs.owned;}
friend Z_INLINE Boolean operator !=(const Shared &lhs, NullPtr) Z_NOTHROW
{return !!lhs.owned;}
friend Z_INLINE Boolean operator !=(NullPtr, const Shared &rhs) Z_NOTHROW
{return !!rhs.owned;}
# endif
# if Z_DIALECT_HAS(CPP11, RVALUE_REFERENCE)
Z_INLINE Shared(Shared &&other) Z_NOTHROW
: owned(other.owned)
{other.owned = Z_NULL;}
Z_INLINE Shared &operator =(Shared &&rhs)
{
if (owned != rhs.owned)
{
if (owned && !--owned->owner_count) delete owned;
owned = rhs.owned;
rhs.owned = Z_NULL;
}
return *this;
}
# endif
};}
#endif // Z_classes_Shared_HPP
| 1 | 0.71047 | 1 | 0.71047 | game-dev | MEDIA | 0.212209 | game-dev | 0.713919 | 1 | 0.713919 |
sharpfives/the-gems-game | 7,157 | src/scenes/chase/swing-scene.ts | import { SceneBase } from "../scene-base";
import { Rope } from "../../objects/rope";
import { sleep, tweenPromise, rand, OVERSAMPLE_FACTOR, TOP_DEPTH, LINE_COLOR, DEBUG_SCENE, STATE_DID_CHASE_SCENE, InputMode, AUDIO_CHASE_LOOP, AUDIO_CHASE_START, AUDIO_FOREST, AUDIO_SWING_END, setNumOfItem, ITEM_FEATHER, AUDIO_FOREST_BACKGROUND, AUDIO_SWING_CREAK, AUDIO_FOOTSTEPS } from "../../globals";
import { PolygonArea } from "../../objects/areas/polygon-area";
import { ExitArea } from "../../objects/areas/exit-area";
import { BadGuy } from "../../objects/characters/bad-guy";
import { Particle } from "../../objects/items/particle";
import { collisionManager } from "../../utils/collision-manager";
import { LeftRightExitScene } from "../left-right-exit-scene";
import { ItemEngageBubble } from "../../objects/overlays/item-engage-bubble";
import { Cursor } from "../../objects/overlays/cursor";
import { LeftRightTransition } from "../../objects/overlays/left-right-transition";
import { Door } from "../../objects/items/door";
import { DoorBackground } from "../../objects/overlays/door-background";
import { stateManager } from "../../utils/game-state-manager";
import { audioManager } from "../../utils/audio-manager";
export class SwingScene extends LeftRightExitScene {
private rope1;
private rope2;
private base;
numTaps: number = 0;
swingJoint: MatterJS.Constraint;
isSittingOnSwing: boolean = false;
constructor() {
super();
}
preload() {
super.preload();
this.load.image('swing','resources/swing-base.png');
BadGuy.loadResources(this);
Door.loadResources(this);
audioManager.preload(AUDIO_CHASE_LOOP);
audioManager.preload(AUDIO_CHASE_START);
if (DEBUG_SCENE) {
setNumOfItem(ITEM_FEATHER,1);
stateManager.set(STATE_DID_CHASE_SCENE, false);
}
}
create(data) {
super.create(data);
this.isSittingOnSwing = false;
this.minYForWalk = 61 * OVERSAMPLE_FACTOR;
// this.removeRightExit();
const me = this.me;
const exits = this.sceneLoader.exits;
const swingPoint = exits['swing'];
const ropeY = swingPoint.y;
const startX = swingPoint.x;
const swingHeight = 130;
const base = this.matter.add.image(startX, ropeY + swingHeight, 'swing');
base.setSensor(true);
base.setFixedRotation();
base.setMass(1);
this.base = base;
const areas = this.sceneLoader.areas;
const swingArea = areas['swing'] as PolygonArea;
swingArea.on('selected', async (x,y,double) => {
icon.hide();
if (this.isSittingOnSwing) {
await this.doSwing();
return;
}
try {
await me.move(base.x, base.y + 20,double);
// this.setInputMode(InputMode.Disabled);
// await sleep(300);
this.sitOnSwing();
this.setSwingMode();
}
catch(e) {}
});
const icon = new ItemEngageBubble(this,0,0);
icon.alpha(0);
swingArea.on('moved-out', () => {
icon.hide();
});
swingArea.on('moved-over', () => {
let offset = 0;
if (this.isSittingOnSwing) {
offset = -50;
// return;
}
icon.setIcon(Cursor.handKey);
icon.alpha(1);
icon.show(swingArea.x(), swingArea.y() + offset);
});
const rope2 = new Rope(this);
rope2.invincible = true;
rope2.attach(startX,ropeY,base, {x : -base.width/2, y : -6});
this.rope2 = rope2;
const rope = new Rope(this);
rope.invincible = true;
rope.attach(startX + base.width,ropeY,base, {x : base.width/2, y : -6});
this.rope1 = rope;
// audioManager.play(AUDIO_FOREST);
// setTimeout( async () => {
// this.sitOnSwing();
// await sleep(1000);
// this.doBadGuyOutro();
// }, 1000);
}
sitOnSwing() {
this.isSittingOnSwing = true;
audioManager.stop(AUDIO_FOOTSTEPS);
const me = this.me;
const obj = me.getGameObject();
me.faceRight();
obj.setIgnoreGravity(false);
obj.setStatic(false);
obj.setSensor(true);
obj.setAngle(0);
obj.setFixedRotation();
me.playAnimation('swing-rest');
const j = this.matter.add.joint(me.getGameObject(), this.base, 1, 1.2);
j['pointB'].y = -20;
this.swingJoint = j;
}
getOffSwing() {
const me = this.me;
this.matter.world.removeConstraint(this.swingJoint as MatterJS.Constraint, true);
this.me.playAnimation('rest');
me.getGameObject().setIgnoreGravity(true);
me.getGameObject().setStatic(true);
me.getGameObject().setSensor(true);
me.getGameObject().setAngle(0);
me.getGameObject().setFixedRotation();
me.getGameObject().setVelocity(0,0);
this.me.faceRight();
this.isSittingOnSwing = false;
}
async doSwing() {
const dude = this.me;
sleep(700).then( () => {
audioManager.play(AUDIO_SWING_CREAK);
});
await dude.swing();
dude.sing(2,false);
if (!stateManager.get(STATE_DID_CHASE_SCENE)) {
if (this.numTaps++ === 2) {
this.inputHandler.setOnTap(this, async (x: number, y: number) => {});
this.doBadGuyOutro();
}
}
}
setSwingMode() {
const self = this;
this.inputHandler.setOnTap(this, async (x: number, y: number) => {
if (!stateManager.get(STATE_DID_CHASE_SCENE)) {
await this.doSwing();
}
else {
this.getOffSwing();
this.setWalkMode();
}
});
}
async doBadGuyOutro() {
audioManager.stop(AUDIO_FOREST, 1000);
this.setInputMode(InputMode.Disabled);
this.hud.wideScreen.show();
const me = this.me;
const doorSpot = this.sceneLoader.exits['door'];
const door = new Door(this, doorSpot.x, doorSpot.y);
door.removeOverSetIcon();
door.depth(TOP_DEPTH-1);
await door.dissolve(doorSpot.x, doorSpot.y, { dissolveIn: true });
// this.showDoorBackground(door);
const background = new DoorBackground(this);
background.setDoor(door);
const badguy = new BadGuy(this, doorSpot.x + 2*OVERSAMPLE_FACTOR, doorSpot.y - 3 * OVERSAMPLE_FACTOR);
badguy.depth(door.depth()-1);
// badguy.alpha(0);
badguy.rest();
badguy.static(false);
badguy.sensor(true);
// badguy.bringToTop();
me.ignoreGravity(true);
me.static(true);
me.sensor(true);
sleep(2000);
this.getOffSwing();
await sleep(100);
// me.y(badguy.y());
// me.x(badguy.x() - 200);
await me.walkTo(me.x(), door.y() + 10 * OVERSAMPLE_FACTOR, 15 * OVERSAMPLE_FACTOR);
// await tweenPromise(this, badguy.getGameObject(), {alpha : 1}, 1000);
await door.open();
await sleep(2000);
audioManager.stop(AUDIO_FOREST_BACKGROUND);
audioManager.play(AUDIO_CHASE_START).then( () => {
audioManager.play(AUDIO_CHASE_LOOP);
});
await badguy.walkTo(badguy.x(), badguy.y() + 10 * OVERSAMPLE_FACTOR, 15 * OVERSAMPLE_FACTOR);
badguy.depth(TOP_DEPTH);
door.depth(badguy.depth()-1);
await door.close();
background.destroy();
await sleep(1500);
me.stepBackwards();
await badguy.scream();
await sleep(2000);
await badguy.playAnimation('run-start');
badguy.playAnimation('run');
me.playAnimation('run');
me.faceLeft();
const speed = 52 * OVERSAMPLE_FACTOR;
badguy.faceLeft();
me.moveTo(-15 * OVERSAMPLE_FACTOR, me.y(), speed);
await badguy.moveTo(0, badguy.y(), speed);
badguy.destroy();
const transition = new LeftRightTransition(this);
await transition.show();
this.exitScene('exit');
}
update() {
super.update();
try {
this.rope1.update();
this.rope2.update();
}
catch(e) {}
}
} | 1 | 0.885956 | 1 | 0.885956 | game-dev | MEDIA | 0.757743 | game-dev | 0.969842 | 1 | 0.969842 |
scubajorgen/TomTomWatch | 3,273 | src/main/java/net/studioblueplanet/tomtomwatch/HistoryItem.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package net.studioblueplanet.tomtomwatch;
import net.studioblueplanet.usb.UsbFile;
import net.studioblueplanet.generics.ToolBox;
import net.studioblueplanet.logger.DebugLogger;
import net.studioblueplanet.ttbin.Activity;
import java.util.ArrayList;
import java.util.Iterator;
/**
* This class represents one activity summary as stored on the watch
* as a file with file id 0x0072aaii. aa is the activity code, ii the index
* (0x00 - 0x0a).
* File format:
* uint8 unknown
* uint32 entry count, little endian
* array
* \[
* uint8 tag
* uint32/float32 value
* \]
* @author Jorgen
*/
public class HistoryItem
{
private int numberOfValues;
private final ArrayList<HistoryValue> values;
private int fileId;
/**
* Cosntructor. Constructs the item from the file
* @param file UsbFile to construct/read the history item from
*/
public HistoryItem(UsbFile file)
{
byte[] bytes;
int i;
int tag;
HistoryValue value;
int nextOffset;
values=new ArrayList<>();
fileId=file.fileId;
bytes=file.fileData;
numberOfValues=ToolBox.readInt(bytes, 1, 4, true);
DebugLogger.info("Number of history values: "+numberOfValues);
i=0;
nextOffset=5;
while ((i<numberOfValues) && (nextOffset<bytes.length))
{
tag=ToolBox.readUnsignedInt(bytes, nextOffset, 1, true);
nextOffset++;
value=new HistoryValue();
nextOffset=value.convertValue(tag, bytes, nextOffset);
values.add(value);
i++;
}
if (i<numberOfValues)
{
DebugLogger.info("Insufficient number of values in history file");
}
}
/**
* Returns the fileId
* @return The file ID
*/
public int getFileId()
{
return this.fileId;
}
/**
* Returns the activity description
* @return The description
*/
public String getAcitivity()
{
String description;
description = Activity.getActivityDescription((fileId>>8)&0xff);
return description;
}
/**
* Returns the index
* @return The index (0-10)
*/
public String getIndex()
{
return String.format("%s", fileId&0xff);
}
/**
* Returns the description. A list of tag-values
* @return String with the tag-value on each line
*/
public String getDescription()
{
String description;
Iterator<HistoryValue> it;
HistoryValue value;
description ="";
it=values.iterator();
while (it.hasNext())
{
value =it.next();
description+=value.getDescription();
}
return description;
}
}
| 1 | 0.659221 | 1 | 0.659221 | game-dev | MEDIA | 0.618402 | game-dev | 0.688325 | 1 | 0.688325 |
The-Aether-Team/The-Aether-II | 1,227 | src/main/java/com/aetherteam/aetherii/client/renderer/entity/model/MoaEggModel.java | package com.aetherteam.aetherii.client.renderer.entity.model;
import net.minecraft.client.model.Model;
import net.minecraft.client.model.geom.ModelPart;
import net.minecraft.client.model.geom.PartPose;
import net.minecraft.client.model.geom.builders.*;
import net.minecraft.client.renderer.RenderType;
public class MoaEggModel extends Model {
private final ModelPart moa_egg;
public MoaEggModel(ModelPart root) {
super(root, RenderType::entityCutoutNoCull);
this.moa_egg = root.getChild("moa_egg");
}
public static LayerDefinition createBodyLayer() {
MeshDefinition meshdefinition = new MeshDefinition();
PartDefinition partdefinition = meshdefinition.getRoot();
PartDefinition moa_egg = partdefinition.addOrReplaceChild("moa_egg", CubeListBuilder.create().texOffs(0, 0).addBox(-4.0F, -11.0F, -4.0F, 8.0F, 10.0F, 8.0F, new CubeDeformation(0.0F))
.texOffs(0, 25).addBox(-3.0F, -1.0F, -3.0F, 6.0F, 1.0F, 6.0F, new CubeDeformation(0.0F))
.texOffs(0, 18).addBox(-3.0F, -12.0F, -3.0F, 6.0F, 1.0F, 6.0F, new CubeDeformation(0.0F)), PartPose.offset(0.0F, 24.0F, 0.0F));
return LayerDefinition.create(meshdefinition, 32, 32);
}
} | 1 | 0.723709 | 1 | 0.723709 | game-dev | MEDIA | 0.773613 | game-dev,graphics-rendering | 0.898106 | 1 | 0.898106 |
HiveGamesOSS/Chunker | 5,232 | cli/src/main/java/com/hivemc/chunker/conversion/intermediate/column/blockentity/SpawnerBlockEntity.java | package com.hivemc.chunker.conversion.intermediate.column.blockentity;
import com.hivemc.chunker.conversion.intermediate.column.entity.type.ChunkerEntityType;
import org.jetbrains.annotations.Nullable;
import java.util.Objects;
/**
* Represents a Spawner Block Entity.
*/
public class SpawnerBlockEntity extends BlockEntity {
private short delay;
private short spawnRange;
private short maxSpawnDelay;
private short minSpawnDelay;
private short spawnCount;
private short requiredPlayerRange;
private short maxNearbyEntities;
@Nullable
private ChunkerEntityType entityType = null;
/**
* Get the delay until the next spawn.
*
* @return the delay in ticks until next spawn.
*/
public short getDelay() {
return delay;
}
/**
* Set the delay until the next spawn.
*
* @param delay the delay in ticks until next spawn.
*/
public void setDelay(short delay) {
this.delay = delay;
}
/**
* Get the block range from the spawner that entities will spawn.
*
* @return the range in blocks.
*/
public short getSpawnRange() {
return spawnRange;
}
/**
* Set the block range from the spawner that entities will spawn.
*
* @param spawnRange the range in blocks.
*/
public void setSpawnRange(short spawnRange) {
this.spawnRange = spawnRange;
}
/**
* The maximum delay between activations.
*
* @return the maximum delay between activations in ticks.
*/
public short getMaxSpawnDelay() {
return maxSpawnDelay;
}
/**
* Set the maximum delay between activations.
*
* @param maxSpawnDelay the maximum delay between activations in ticks.
*/
public void setMaxSpawnDelay(short maxSpawnDelay) {
this.maxSpawnDelay = maxSpawnDelay;
}
/**
* The minimum delay between activations.
*
* @return the minimum delay between activations in ticks.
*/
public short getMinSpawnDelay() {
return minSpawnDelay;
}
/**
* Set the minimum delay between activations.
*
* @param minSpawnDelay the minimum delay between activations in ticks.
*/
public void setMinSpawnDelay(short minSpawnDelay) {
this.minSpawnDelay = minSpawnDelay;
}
/**
* Get the number of entities to spawn.
*
* @return the number of entities to spawn when the spawner activates.
*/
public short getSpawnCount() {
return spawnCount;
}
/**
* Set the number of entities to spawn.
*
* @param spawnCount the number of entities to spawn when the spawner activates.
*/
public void setSpawnCount(short spawnCount) {
this.spawnCount = spawnCount;
}
/**
* Get the range a player has to be within for the spawner to activate.
*
* @return the distance in blocks from the spawner.
*/
public short getRequiredPlayerRange() {
return requiredPlayerRange;
}
/**
* Set the range a player has to be within for the spawner to activate.
*
* @param requiredPlayerRange the distance in blocks from the spawner.
*/
public void setRequiredPlayerRange(short requiredPlayerRange) {
this.requiredPlayerRange = requiredPlayerRange;
}
/**
* The maximum number of entities that can be nearby.
*
* @return the number of entities which the spawner will deactivate.
*/
public short getMaxNearbyEntities() {
return maxNearbyEntities;
}
/**
* Set the maximum number of entities that can be nearby.
*
* @param maxNearbyEntities the number of entities which the spawner will deactivate.
*/
public void setMaxNearbyEntities(short maxNearbyEntities) {
this.maxNearbyEntities = maxNearbyEntities;
}
/**
* Get the entity type this spawner spawns.
*
* @return the entity type or null if it is not set.
*/
@Nullable
public ChunkerEntityType getEntityType() {
return entityType;
}
/**
* Set the entity type that this spawner spawns.
*
* @param entityType the type this spawner spawns or null if not set.
*/
public void setEntityType(@Nullable ChunkerEntityType entityType) {
this.entityType = entityType;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof SpawnerBlockEntity that)) return false;
if (!super.equals(o)) return false;
return getDelay() == that.getDelay() && getSpawnRange() == that.getSpawnRange() && getMaxSpawnDelay() == that.getMaxSpawnDelay() && getMinSpawnDelay() == that.getMinSpawnDelay() && getSpawnCount() == that.getSpawnCount() && getRequiredPlayerRange() == that.getRequiredPlayerRange() && getMaxNearbyEntities() == that.getMaxNearbyEntities() && getEntityType() == that.getEntityType();
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), getDelay(), getSpawnRange(), getMaxSpawnDelay(), getMinSpawnDelay(), getSpawnCount(), getRequiredPlayerRange(), getMaxNearbyEntities(), getEntityType());
}
}
| 1 | 0.861382 | 1 | 0.861382 | game-dev | MEDIA | 0.98926 | game-dev | 0.827766 | 1 | 0.827766 |
Decencies/CheatBreaker | 3,191 | CheatBreaker/src/main/java/net/minecraft/src/CompactArrayList.java | package net.minecraft.src;
import java.util.ArrayList;
public class CompactArrayList
{
private ArrayList list;
private int initialCapacity;
private float loadFactor;
private int countValid;
public CompactArrayList()
{
this(10, 0.75F);
}
public CompactArrayList(int initialCapacity)
{
this(initialCapacity, 0.75F);
}
public CompactArrayList(int initialCapacity, float loadFactor)
{
this.list = null;
this.initialCapacity = 0;
this.loadFactor = 1.0F;
this.countValid = 0;
this.list = new ArrayList(initialCapacity);
this.initialCapacity = initialCapacity;
this.loadFactor = loadFactor;
}
public void add(int index, Object element)
{
if (element != null)
{
++this.countValid;
}
this.list.add(index, element);
}
public boolean add(Object element)
{
if (element != null)
{
++this.countValid;
}
return this.list.add(element);
}
public Object set(int index, Object element)
{
Object oldElement = this.list.set(index, element);
if (element != oldElement)
{
if (oldElement == null)
{
++this.countValid;
}
if (element == null)
{
--this.countValid;
}
}
return oldElement;
}
public Object remove(int index)
{
Object oldElement = this.list.remove(index);
if (oldElement != null)
{
--this.countValid;
}
return oldElement;
}
public void clear()
{
this.list.clear();
this.countValid = 0;
}
public void compact()
{
if (this.countValid <= 0 && this.list.size() <= 0)
{
this.clear();
}
else if (this.list.size() > this.initialCapacity)
{
float currentLoadFactor = (float)this.countValid * 1.0F / (float)this.list.size();
if (currentLoadFactor <= this.loadFactor)
{
int dstIndex = 0;
int i;
for (i = 0; i < this.list.size(); ++i)
{
Object wr = this.list.get(i);
if (wr != null)
{
if (i != dstIndex)
{
this.list.set(dstIndex, wr);
}
++dstIndex;
}
}
for (i = this.list.size() - 1; i >= dstIndex; --i)
{
this.list.remove(i);
}
}
}
}
public boolean contains(Object elem)
{
return this.list.contains(elem);
}
public Object get(int index)
{
return this.list.get(index);
}
public boolean isEmpty()
{
return this.list.isEmpty();
}
public int size()
{
return this.list.size();
}
public int getCountValid()
{
return this.countValid;
}
}
| 1 | 0.831005 | 1 | 0.831005 | game-dev | MEDIA | 0.548712 | game-dev | 0.976219 | 1 | 0.976219 |
Dawn-of-Light/DOLSharp | 2,414 | GameServer/commands/admincommands/BenchmarkCommand.cs | /*
* DAWN OF LIGHT - The first free open source DAoC server emulator
*
* 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.
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using DOL.GS;
using DOL.GS.PacketHandler;
using DOL.Language;
namespace DOL.GS.Commands
{
[CmdAttribute(
"&benchmark",
ePrivLevel.Admin,
"Benchmark some aspects of DOL Server.",
"/benchmark listskills|listspells|styles|respawns|deaths|tooltips")]
public class BenchmarkCommand : AbstractCommandHandler, ICommandHandler
{
public void OnCommand(GameClient client, string[] args)
{
if (args.Length < 2 || client == null || client.Player == null)
{
DisplaySyntax(client);
return;
}
long start,spent;
switch(args[1])
{
case "listskills":
start = GameTimer.GetTickCount();
Util.ForEach(Enumerable.Range(0, 1000).AsParallel(), i =>
{
var tmp = client.Player.GetAllUsableSkills(true);
}
);
spent = GameTimer.GetTickCount() - start;
client.Player.Out.SendMessage(string.Format("Skills Benchmark took {0}ms for 1000 iterations...", spent), eChatType.CT_System, eChatLoc.CL_SystemWindow);
break;
case "listspells":
start = GameTimer.GetTickCount();
Util.ForEach(Enumerable.Range(0, 1000).AsParallel(), i =>
{
var tmp = client.Player.GetAllUsableListSpells(true);
}
);
spent = GameTimer.GetTickCount() - start;
client.Player.Out.SendMessage(string.Format("Spells Benchmark took {0}ms for 1000 iterations...", spent), eChatType.CT_System, eChatLoc.CL_SystemWindow);
break;
}
}
}
}
| 1 | 0.784547 | 1 | 0.784547 | game-dev | MEDIA | 0.494525 | game-dev | 0.834653 | 1 | 0.834653 |
realms-mud/core-lib | 1,822 | areas/tol-dhurath/state-machine/tol-dhurath-quest.c | //*****************************************************************************
// Copyright (c) 2025 - Allen Cummings, RealmsMUD, All rights reserved. See
// the accompanying LICENSE file for details.
//*****************************************************************************
inherit "/lib/modules/quests/questItem.c";
/////////////////////////////////////////////////////////////////////////////
private void registerEventHandlers()
{
registerEventHandler("setupHelpingHand");
}
/////////////////////////////////////////////////////////////////////////////
public void Setup()
{
setName("Something's Rotten in Tol Dhurath");
setType("primary");
setDescription("Basil, the commander of the Aegis Guard, has tasked "
"you to look into rumors of activity in the ruins of Tol Dhurath.");
addState("start quest", "I've been asked to look into rumors of "
"illicit activities coming from the ruins of Tol Dhurath.");
addState("met maiwyn",
"I met a woman named Maiwyn who was attempting to escape her "
"captors in Tol Dhurath. She has given some interesting information "
"about this place: A Lord Sullath appears to be a major player "
"in events reaching far beyond what is going on here.");
addTransition("start quest", "met maiwyn", "met maiwyn");
addState("a helping hand",
"Maiwyn has decided to help infiltrate Tol Dhurath.");
addTransition("met maiwyn", "a helping hand", "maiwyn helps");
addEntryAction("a helping hand", "setupHelpingHand");
setInitialState("start quest");
registerEventHandlers();
}
/////////////////////////////////////////////////////////////////////////////
void setupHelpingHand(object player)
{
notify("setupHelpingHand", player);
}
| 1 | 0.588803 | 1 | 0.588803 | game-dev | MEDIA | 0.852981 | game-dev | 0.592015 | 1 | 0.592015 |
AionGermany/aion-germany | 2,973 | AL-Game-5.8/data/scripts/system/handlers/quest/sanctum/_1909ASongOfPraise.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.sanctum;
import com.aionemu.gameserver.model.DialogAction;
import com.aionemu.gameserver.model.gameobjects.player.Player;
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;
/**
* @author Mr. Poke
* @modified Nephis
*/
public class _1909ASongOfPraise extends QuestHandler {
private final static int questId = 1909;
public _1909ASongOfPraise() {
super(questId);
}
@Override
public void register() {
qe.registerQuestNpc(203739).addOnQuestStart(questId);
qe.registerQuestNpc(203739).addOnTalkEvent(questId);
qe.registerQuestNpc(203726).addOnTalkEvent(questId);
qe.registerQuestNpc(203099).addOnTalkEvent(questId);
}
@Override
public boolean onDialogEvent(QuestEnv env) {
final Player player = env.getPlayer();
QuestState qs = player.getQuestStateList().getQuestState(questId);
if (env.getTargetId() == 203739) {
if (qs == null || qs.getStatus() == QuestStatus.NONE) {
if (env.getDialog() == DialogAction.QUEST_SELECT) {
return sendQuestDialog(env, 1011);
}
else {
return sendQuestStartDialog(env);
}
}
}
else if (env.getTargetId() == 203726) {
if (qs != null && qs.getStatus() == QuestStatus.START && qs.getQuestVarById(0) == 0) {
if (env.getDialog() == DialogAction.QUEST_SELECT) {
return sendQuestDialog(env, 1352);
}
else if (env.getDialog() == DialogAction.SETPRO1) {
defaultCloseDialog(env, 0, 1, 182206001, 1, 0, 0);
return true;
}
else {
return sendQuestStartDialog(env);
}
}
}
else if (env.getTargetId() == 203099) {
if (qs != null) {
if (env.getDialog() == DialogAction.QUEST_SELECT && qs.getStatus() == QuestStatus.START) {
return sendQuestDialog(env, 2375);
}
else if (env.getDialogId() == DialogAction.SELECT_QUEST_REWARD.id() && qs.getStatus() != QuestStatus.COMPLETE && qs.getStatus() != QuestStatus.NONE) {
return defaultCloseDialog(env, 1, 2, true, true, 0, 0, 0, 182206001, 1);
}
else {
return sendQuestEndDialog(env);
}
}
}
return false;
}
}
| 1 | 0.850061 | 1 | 0.850061 | game-dev | MEDIA | 0.960591 | game-dev | 0.963325 | 1 | 0.963325 |
exverge-0/yuzu-EA4176 | 2,388 | src/core/hle/service/fgm/fgm.cpp | // SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#include <memory>
#include "core/hle/service/fgm/fgm.h"
#include "core/hle/service/ipc_helpers.h"
#include "core/hle/service/server_manager.h"
#include "core/hle/service/service.h"
#include "core/hle/service/sm/sm.h"
namespace Service::FGM {
class IRequest final : public ServiceFramework<IRequest> {
public:
explicit IRequest(Core::System& system_) : ServiceFramework{system_, "IRequest"} {
// clang-format off
static const FunctionInfo functions[] = {
{0, nullptr, "Initialize"},
{1, nullptr, "Set"},
{2, nullptr, "Get"},
{3, nullptr, "Cancel"},
};
// clang-format on
RegisterHandlers(functions);
}
};
class FGM final : public ServiceFramework<FGM> {
public:
explicit FGM(Core::System& system_, const char* name) : ServiceFramework{system_, name} {
// clang-format off
static const FunctionInfo functions[] = {
{0, &FGM::Initialize, "Initialize"},
};
// clang-format on
RegisterHandlers(functions);
}
private:
void Initialize(HLERequestContext& ctx) {
LOG_DEBUG(Service_FGM, "called");
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(ResultSuccess);
rb.PushIpcInterface<IRequest>(system);
}
};
class FGM_DBG final : public ServiceFramework<FGM_DBG> {
public:
explicit FGM_DBG(Core::System& system_) : ServiceFramework{system_, "fgm:dbg"} {
// clang-format off
static const FunctionInfo functions[] = {
{0, nullptr, "Initialize"},
{1, nullptr, "Read"},
{2, nullptr, "Cancel"},
};
// clang-format on
RegisterHandlers(functions);
}
};
void LoopProcess(Core::System& system) {
auto server_manager = std::make_unique<ServerManager>(system);
server_manager->RegisterNamedService("fgm", std::make_shared<FGM>(system, "fgm"));
server_manager->RegisterNamedService("fgm:0", std::make_shared<FGM>(system, "fgm:0"));
server_manager->RegisterNamedService("fgm:9", std::make_shared<FGM>(system, "fgm:9"));
server_manager->RegisterNamedService("fgm:dbg", std::make_shared<FGM_DBG>(system));
ServerManager::RunServer(std::move(server_manager));
}
} // namespace Service::FGM
| 1 | 0.632537 | 1 | 0.632537 | game-dev | MEDIA | 0.262561 | game-dev | 0.623162 | 1 | 0.623162 |
badasintended/wthit | 3,526 | platform/quilt/build.gradle.kts | evaluationDependsOn(":textile")
plugins {
id("org.quiltmc.loom") version "1.3.4"
}
setupPlatform()
dependencies {
minecraft("com.mojang:minecraft:${rootProp["minecraft"]}")
mappings(loom.officialMojangMappings())
modImplementation("org.quiltmc:quilt-loader:${rootProp["quiltLoader"]}")
modCompileRuntime("org.quiltmc:qsl:${rootProp["qsl"]}")
modCompileRuntime("org.quiltmc.quilted-fabric-api:fabric-key-binding-api-v1:${rootProp["qfapi"]}")
modCompileRuntime("org.quiltmc.quilted-fabric-api:fabric-rendering-v1:${rootProp["qfapi"]}")
modCompileRuntime("org.quiltmc.quilted-fabric-api:fabric-lifecycle-events-v1:${rootProp["qfapi"]}")
modCompileRuntime("org.quiltmc.quilted-fabric-api:fabric-mining-level-api-v1:${rootProp["qfapi"]}")
modCompileRuntime("com.terraformersmc:modmenu:${rootProp["modMenu"]}")
modRuntimeOnly("lol.bai:badpackets:fabric-${rootProp["badpackets"]}")
modRuntimeOnly("org.quiltmc.quilted-fabric-api:quilted-fabric-api:${rootProp["qfapi"]}")
// modRuntimeOnly("dev.architectury:architectury-fabric:${rootProp["architectury"]}")
// modRuntimeOnly("me.shedaniel.cloth:cloth-config-fabric:${rootProp["clothConfig"]}")
when (rootProp["recipeViewer"]) {
"emi" -> modRuntimeOnly("dev.emi:emi-fabric:${rootProp["emi"]}")
"rei" -> modRuntimeOnly("me.shedaniel:RoughlyEnoughItems-fabric:${rootProp["rei"]}")
"jei" -> rootProp["jei"].split("-").also { (mc, jei) ->
modRuntimeOnly("mezz.jei:jei-${mc}-fabric:${jei}")
}
}
}
setupStub()
sourceSets {
val textileSourceSets = project(":textile").sourceSets
val main by getting
val plugin by getting
main {
compileClasspath += textileSourceSets["main"].output
runtimeClasspath += textileSourceSets["main"].output
}
plugin.apply {
compileClasspath += textileSourceSets["plugin"].output
}
listOf(main, plugin).applyEach {
runtimeClasspath += textileSourceSets["plugin"].output
}
}
loom {
mixin {
add(sourceSets["main"], "wthit.refmap.json")
}
runs {
getByName("client") {
programArgs("--username", "A")
}
configureEach {
isIdeConfigGenerated = true
runDir = "run/${namer.determineName(this)}"
}
}
}
tasks.jar {
val textileSourceSets = project(":textile").sourceSets
from(textileSourceSets["main"].output)
from(textileSourceSets["api"].output)
from(textileSourceSets["plugin"].output)
}
tasks.sourcesJar {
val textileSourceSets = project(":textile").sourceSets
from(textileSourceSets["main"].allSource)
from(textileSourceSets["api"].allSource)
from(textileSourceSets["plugin"].allSource)
}
tasks.processResources {
inputs.property("version", project.version)
filesMatching("quilt.mod.json") {
expand("version" to project.version)
}
}
afterEvaluate {
val remapJar = tasks.remapJar.get()
val apiJar = task<ApiJarTask>("apiJar") {
fullJar(remapJar)
}
val remapSourcesJar = tasks.remapSourcesJar.get()
val apiSourcesJar = task<ApiJarTask>("apiSourcesJar") {
fullJar(remapSourcesJar)
}
upload {
curseforge(remapJar)
modrinth(remapJar)
maven(apiJar, apiSourcesJar, suffix = "api")
maven(remapJar, remapSourcesJar) {
pom.withDependencies {
runtime("lol.bai:badpackets:fabric-${rootProp["badpackets"]}")
}
}
}
}
| 1 | 0.54345 | 1 | 0.54345 | game-dev | MEDIA | 0.966276 | game-dev | 0.693668 | 1 | 0.693668 |
emileb/OpenGames | 20,005 | opengames/src/main/jni/OpenJK/code/game/g_vehicleLoad.cpp | //g_vehicleLoad.cpp
// leave this line at the top for all NPC_xxxx.cpp files...
#include "g_headers.h"
#include "../qcommon/q_shared.h"
#include "anims.h"
#include "g_vehicles.h"
extern qboolean G_ParseLiteral( const char **data, const char *string );
extern void G_CreateG2AttachedWeaponModel( gentity_t *ent, const char *weaponModel, int boltNum, int weaponNum );
vehicleInfo_t g_vehicleInfo[MAX_VEHICLES];
int numVehicles = 1;//first one is null/default
typedef enum {
VF_INT,
VF_FLOAT,
VF_LSTRING, // string on disk, pointer in memory, TAG_LEVEL
VF_VECTOR,
VF_BOOL,
VF_VEHTYPE,
VF_ANIM
} vehFieldType_t;
typedef struct
{
char *name;
int ofs;
vehFieldType_t type;
} vehField_t;
vehField_t vehFields[VEH_PARM_MAX] =
{
{"name", VFOFS(name), VF_LSTRING}, //unique name of the vehicle
//general data
{"type", VFOFS(type), VF_VEHTYPE}, //what kind of vehicle
{"numHands", VFOFS(numHands), VF_INT}, //if 2 hands, no weapons, if 1 hand, can use 1-handed weapons, if 0 hands, can use 2-handed weapons
{"lookPitch", VFOFS(lookPitch), VF_FLOAT}, //How far you can look up and down off the forward of the vehicle
{"lookYaw", VFOFS(lookYaw), VF_FLOAT}, //How far you can look left and right off the forward of the vehicle
{"length", VFOFS(length), VF_FLOAT}, //how long it is - used for body length traces when turning/moving?
{"width", VFOFS(width), VF_FLOAT}, //how wide it is - used for body length traces when turning/moving?
{"height", VFOFS(height), VF_FLOAT}, //how tall it is - used for body length traces when turning/moving?
{"centerOfGravity", VFOFS(centerOfGravity), VF_VECTOR},//offset from origin: {forward, right, up} as a modifier on that dimension (-1.0f is all the way back, 1.0f is all the way forward)
//speed stats
{"speedMax", VFOFS(speedMax), VF_FLOAT}, //top speed
{"turboSpeed", VFOFS(turboSpeed), VF_FLOAT}, //turbo speed
{"speedMin", VFOFS(speedMin), VF_FLOAT}, //if < 0, can go in reverse
{"speedIdle", VFOFS(speedIdle), VF_FLOAT}, //what speed it drifts to when no accel/decel input is given
{"accelIdle", VFOFS(accelIdle), VF_FLOAT}, //if speedIdle > 0, how quickly it goes up to that speed
{"acceleration", VFOFS(acceleration), VF_FLOAT}, //when pressing on accelerator
{"decelIdle", VFOFS(decelIdle), VF_FLOAT}, //when giving no input, how quickly it drops to speedIdle
{"strafePerc", VFOFS(strafePerc), VF_FLOAT}, //multiplier on current speed for strafing. If 1.0f, you can strafe at the same speed as you're going forward, 0.5 is half, 0 is no strafing
//handling stats
{"bankingSpeed", VFOFS(bankingSpeed), VF_FLOAT}, //how quickly it pitches and rolls (not under player control)
{"pitchLimit", VFOFS(pitchLimit), VF_FLOAT}, //how far it can roll forward or backward
{"rollLimit", VFOFS(rollLimit), VF_FLOAT}, //how far it can roll to either side
{"braking", VFOFS(braking), VF_FLOAT}, //when pressing on decelerator
{"turningSpeed", VFOFS(turningSpeed), VF_FLOAT}, //how quickly you can turn
{"turnWhenStopped", VFOFS(turnWhenStopped), VF_BOOL},//whether or not you can turn when not moving
{"traction", VFOFS(traction), VF_FLOAT}, //how much your command input affects velocity
{"friction", VFOFS(friction), VF_FLOAT}, //how much velocity is cut on its own
{"maxSlope", VFOFS(maxSlope), VF_FLOAT}, //the max slope that it can go up with control
//durability stats
{"mass", VFOFS(mass), VF_INT}, //for momentum and impact force (player mass is 10)
{"armor", VFOFS(armor), VF_INT}, //total points of damage it can take
{"toughness", VFOFS(toughness), VF_FLOAT}, //modifies incoming damage, 1.0 is normal, 0.5 is half, etc. Simulates being made of tougher materials/construction
{"malfunctionArmorLevel", VFOFS(malfunctionArmorLevel), VF_INT},//when armor drops to or below this point, start malfunctioning
//visuals & sounds
{"model", VFOFS(model), VF_LSTRING}, //what model to use - if make it an NPC's primary model, don't need this?
{"skin", VFOFS(skin), VF_LSTRING}, //what skin to use - if make it an NPC's primary model, don't need this?
{"riderAnim", VFOFS(riderAnim), VF_ANIM}, //what animation the rider uses
{"gunswivelBone", VFOFS(gunswivelBone), VF_LSTRING},//gun swivel bones
{"lFinBone", VFOFS(lFinBone), VF_LSTRING}, //left fin bone
{"rFinBone", VFOFS(rFinBone), VF_LSTRING}, //right fin bone
{"lExhaustTag", VFOFS(lExhaustTag), VF_LSTRING}, //left exhaust tag
{"rExhaustTag", VFOFS(rExhaustTag), VF_LSTRING}, //right exhaust tag
{"soundOn", VFOFS(soundOn), VF_LSTRING}, //sound to play when get on it
{"soundLoop", VFOFS(soundLoop), VF_LSTRING}, //sound to loop while riding it
{"soundOff", VFOFS(soundOff), VF_LSTRING}, //sound to play when get off
{"exhaustFX", VFOFS(exhaustFX), VF_LSTRING}, //exhaust effect, played from "*exhaust" bolt(s)
{"trailFX", VFOFS(trailFX), VF_LSTRING}, //trail effect, played from "*trail" bolt(s)
{"impactFX", VFOFS(impactFX), VF_LSTRING}, //impact effect, for when it bumps into something
{"explodeFX", VFOFS(explodeFX), VF_LSTRING}, //explosion effect, for when it blows up (should have the sound built into explosion effect)
{"wakeFX", VFOFS(wakeFX), VF_LSTRING}, //effect it makes when going across water
//other misc stats
{"gravity", VFOFS(gravity), VF_INT}, //normal is 800
{"hoverHeight", VFOFS(hoverHeight), VF_FLOAT}, //if 0, it's a ground vehicle
{"hoverStrength", VFOFS(hoverStrength), VF_FLOAT}, //how hard it pushes off ground when less than hover height... causes "bounce", like shocks
{"waterProof", VFOFS(waterProof), VF_BOOL}, //can drive underwater if it has to
{"bouyancy", VFOFS(bouyancy), VF_FLOAT}, //when in water, how high it floats (1 is neutral bouyancy)
{"fuelMax", VFOFS(fuelMax), VF_INT}, //how much fuel it can hold (capacity)
{"fuelRate", VFOFS(fuelRate), VF_INT}, //how quickly is uses up fuel
{"visibility", VFOFS(visibility), VF_INT}, //for sight alerts
{"loudness", VFOFS(loudness), VF_INT}, //for sound alerts
{"explosionRadius", VFOFS(explosionRadius), VF_FLOAT},//range of explosion
{"explosionDamage", VFOFS(explosionDamage), VF_INT},//damage of explosion
//new stuff
{"maxPassengers", VFOFS(maxPassengers), VF_INT}, // The max number of passengers this vehicle may have (Default = 0).
{"hideRider", VFOFS(hideRider), VF_BOOL }, // rider (and passengers?) should not be drawn
{"killRiderOnDeath", VFOFS(killRiderOnDeath), VF_BOOL },//if rider is on vehicle when it dies, they should die
{"flammable", VFOFS(flammable), VF_BOOL }, //whether or not the vehicle should catch on fire before it explodes
{"explosionDelay", VFOFS(explosionDelay), VF_INT}, //how long the vehicle should be on fire/dying before it explodes
//camera stuff
{"cameraOverride", VFOFS(cameraOverride), VF_BOOL }, //override the third person camera with the below values - normal is 0 (off)
{"cameraRange", VFOFS(cameraRange), VF_FLOAT}, //how far back the camera should be - normal is 80
{"cameraVertOffset", VFOFS(cameraVertOffset), VF_FLOAT},//how high over the vehicle origin the camera should be - normal is 16
{"cameraHorzOffset", VFOFS(cameraHorzOffset), VF_FLOAT},//how far to left/right (negative/positive) of of the vehicle origin the camera should be - normal is 0
{"cameraPitchOffset", VFOFS(cameraPitchOffset), VF_FLOAT},//a modifier on the camera's pitch (up/down angle) to the vehicle - normal is 0
{"cameraFOV", VFOFS(cameraFOV), VF_FLOAT}, //third person camera FOV, default is 80
{"cameraAlpha", VFOFS(cameraAlpha), VF_BOOL }, //fade out the vehicle if it's in the way of the crosshair
};
stringID_table_t VehicleTable[VH_NUM_VEHICLES+1] =
{
ENUM2STRING(VH_WALKER), //something you ride inside of, it walks like you, like an AT-ST
ENUM2STRING(VH_FIGHTER), //something you fly inside of, like an X-Wing or TIE fighter
ENUM2STRING(VH_SPEEDER), //something you ride on that hovers, like a speeder or swoop
ENUM2STRING(VH_ANIMAL), //animal you ride on top of that walks, like a tauntaun
ENUM2STRING(VH_FLIER), //animal you ride on top of that flies, like a giant mynoc?
"", -1
};
void G_VehicleSetDefaults( vehicleInfo_t *vehicle )
{
vehicle->name = "default"; //unique name of the vehicle
/*
//general data
vehicle->type = VH_SPEEDER; //what kind of vehicle
//FIXME: no saber or weapons if numHands = 2, should switch to speeder weapon, no attack anim on player
vehicle->numHands = 2; //if 2 hands, no weapons, if 1 hand, can use 1-handed weapons, if 0 hands, can use 2-handed weapons
vehicle->lookPitch = 35; //How far you can look up and down off the forward of the vehicle
vehicle->lookYaw = 5; //How far you can look left and right off the forward of the vehicle
vehicle->length = 0; //how long it is - used for body length traces when turning/moving?
vehicle->width = 0; //how wide it is - used for body length traces when turning/moving?
vehicle->height = 0; //how tall it is - used for body length traces when turning/moving?
VectorClear( vehicle->centerOfGravity );//offset from origin: {forward, right, up} as a modifier on that dimension (-1.0f is all the way back, 1.0f is all the way forward)
//speed stats - note: these are DESIRED speed, not actual current speed/velocity
vehicle->speedMax = VEH_DEFAULT_SPEED_MAX; //top speed
vehicle->turboSpeed = 0; //turboBoost
vehicle->speedMin = 0; //if < 0, can go in reverse
vehicle->speedIdle = 0; //what speed it drifts to when no accel/decel input is given
vehicle->accelIdle = 0; //if speedIdle > 0, how quickly it goes up to that speed
vehicle->acceleration = VEH_DEFAULT_ACCEL; //when pressing on accelerator (1/2 this when going in reverse)
vehicle->decelIdle = VEH_DEFAULT_DECEL; //when giving no input, how quickly it desired speed drops to speedIdle
vehicle->strafePerc = VEH_DEFAULT_STRAFE_PERC;//multiplier on current speed for strafing. If 1.0f, you can strafe at the same speed as you're going forward, 0.5 is half, 0 is no strafing
//handling stats
vehicle->bankingSpeed = VEH_DEFAULT_BANKING_SPEED; //how quickly it pitches and rolls (not under player control)
vehicle->rollLimit = VEH_DEFAULT_ROLL_LIMIT; //how far it can roll to either side
vehicle->pitchLimit = VEH_DEFAULT_PITCH_LIMIT; //how far it can pitch forward or backward
vehicle->braking = VEH_DEFAULT_BRAKING; //when pressing on decelerator (backwards)
vehicle->turningSpeed = VEH_DEFAULT_TURNING_SPEED; //how quickly you can turn
vehicle->turnWhenStopped = qfalse; //whether or not you can turn when not moving
vehicle->traction = VEH_DEFAULT_TRACTION; //how much your command input affects velocity
vehicle->friction = VEH_DEFAULT_FRICTION; //how much velocity is cut on its own
vehicle->maxSlope = VEH_DEFAULT_MAX_SLOPE; //the max slope that it can go up with control
//durability stats
vehicle->mass = VEH_DEFAULT_MASS; //for momentum and impact force (player mass is 10)
vehicle->armor = VEH_DEFAULT_MAX_ARMOR; //total points of damage it can take
vehicle->toughness = VEH_DEFAULT_TOUGHNESS; //modifies incoming damage, 1.0 is normal, 0.5 is half, etc. Simulates being made of tougher materials/construction
vehicle->malfunctionArmorLevel = 0; //when armor drops to or below this point, start malfunctioning
//visuals & sounds
vehicle->model = "swoop"; //what model to use - if make it an NPC's primary model, don't need this?
vehicle->modelIndex = 0; //set internally, not until this vehicle is spawned into the level
vehicle->skin = NULL; //what skin to use - if make it an NPC's primary model, don't need this?
vehicle->riderAnim = BOTH_GUNSIT1; //what animation the rider uses
vehicle->gunswivelBone = NULL; //gun swivel bones
vehicle->lFinBone = NULL; //left fin bone
vehicle->rFinBone = NULL; //right fin bone
vehicle->lExhaustTag = NULL; //left exhaust tag
vehicle->rExhaustTag = NULL; //right exhaust tag
vehicle->soundOn = NULL; //sound to play when get on it
vehicle->soundLoop = NULL; //sound to loop while riding it
vehicle->soundOff = NULL; //sound to play when get off
vehicle->exhaustFX = NULL; //exhaust effect, played from "*exhaust" bolt(s)
vehicle->trailFX = NULL; //trail effect, played from "*trail" bolt(s)
vehicle->impactFX = NULL; //explosion effect, for when it blows up (should have the sound built into explosion effect)
vehicle->explodeFX = NULL; //explosion effect, for when it blows up (should have the sound built into explosion effect)
vehicle->wakeFX = NULL; //effect itmakes when going across water
//other misc stats
vehicle->gravity = VEH_DEFAULT_GRAVITY; //normal is 800
vehicle->hoverHeight = 0; //if 0, it's a ground vehicle
vehicle->hoverStrength = 0;//how hard it pushes off ground when less than hover height... causes "bounce", like shocks
vehicle->waterProof = qtrue; //can drive underwater if it has to
vehicle->bouyancy = 1.0f; //when in water, how high it floats (1 is neutral bouyancy)
vehicle->fuelMax = 1000; //how much fuel it can hold (capacity)
vehicle->fuelRate = 1; //how quickly is uses up fuel
vehicle->visibility = VEH_DEFAULT_VISIBILITY; //radius for sight alerts
vehicle->loudness = VEH_DEFAULT_LOUDNESS; //radius for sound alerts
vehicle->explosionRadius = VEH_DEFAULT_EXP_RAD;
vehicle->explosionDamage = VEH_DEFAULT_EXP_DMG;
//new stuff
vehicle->maxPassengers = 0;
vehicle->hideRider = qfalse; // rider (and passengers?) should not be drawn
vehicle->killRiderOnDeath = qfalse; //if rider is on vehicle when it dies, they should die
vehicle->flammable = qfalse; //whether or not the vehicle should catch on fire before it explodes
vehicle->explosionDelay = 0; //how long the vehicle should be on fire/dying before it explodes
//camera stuff
vehicle->cameraOverride = qfalse; //whether or not to use all of the following 3rd person camera override values
vehicle->cameraRange = 0.0f; //how far back the camera should be - normal is 80
vehicle->cameraVertOffset = 0.0f; //how high over the vehicle origin the camera should be - normal is 16
vehicle->cameraHorzOffset = 0.0f; //how far to left/right (negative/positive) of of the vehicle origin the camera should be - normal is 0
vehicle->cameraPitchOffset = 0.0f; //a modifier on the camera's pitch (up/down angle) to the vehicle - normal is 0
vehicle->cameraFOV = 0.0f; //third person camera FOV, default is 80
vehicle->cameraAlpha = qfalse; //fade out the vehicle if it's in the way of the crosshair
*/
}
void G_VehicleClampData( vehicleInfo_t *vehicle )
{//sanity check and clamp the vehicle's data
int i;
for ( i = 0; i < 3; i++ )
{
if ( vehicle->centerOfGravity[i] > 1.0f )
{
vehicle->centerOfGravity[i] = 1.0f;
}
else if ( vehicle->centerOfGravity[i] < -1.0f )
{
vehicle->centerOfGravity[i] = -1.0f;
}
}
// Validate passenger max.
if ( vehicle->maxPassengers > VEH_MAX_PASSENGERS )
{
vehicle->maxPassengers = VEH_MAX_PASSENGERS;
}
else if ( vehicle->maxPassengers < 0 )
{
vehicle->maxPassengers = 0;
}
}
static void G_ParseVehicleParms( vehicleInfo_t *vehicle, const char **holdBuf )
{
const char *token;
const char *value;
int i;
vec3_t vec;
byte *b = (byte *)vehicle;
int _iFieldsRead = 0;
vehicleType_t vehType;
while ( holdBuf )
{
token = COM_ParseExt( holdBuf, qtrue );
if ( !token[0] )
{
gi.Printf( S_COLOR_RED"ERROR: unexpected EOF while parsing vehicles!\n" );
return;
}
if ( !Q_stricmp( token, "}" ) ) // End of data for this vehicle
{
break;
}
// Loop through possible parameters
for ( i = 0; i < VEH_PARM_MAX; i++ )
{
if ( vehFields[i].name && !Q_stricmp( vehFields[i].name, token ) )
{
// found it
if ( COM_ParseString( holdBuf, &value ) )
{
continue;
}
switch( vehFields[i].type )
{
case VF_INT:
*(int *)(b+vehFields[i].ofs) = atoi(value);
break;
case VF_FLOAT:
*(float *)(b+vehFields[i].ofs) = atof(value);
break;
case VF_LSTRING: // string on disk, pointer in memory, TAG_LEVEL
*(char **)(b+vehFields[i].ofs) = G_NewString( value );
break;
case VF_VECTOR:
_iFieldsRead = sscanf (value, "%f %f %f", &vec[0], &vec[1], &vec[2]);
assert(_iFieldsRead==3 );
if (_iFieldsRead!=3)
{
gi.Printf (S_COLOR_YELLOW"G_ParseVehicleParms: VEC3 sscanf() failed to read 3 floats ('angle' key bug?)\n");
}
((float *)(b+vehFields[i].ofs))[0] = vec[0];
((float *)(b+vehFields[i].ofs))[1] = vec[1];
((float *)(b+vehFields[i].ofs))[2] = vec[2];
break;
case VF_BOOL:
*(qboolean *)(b+vehFields[i].ofs) = (atof(value)!=0);
break;
case VF_VEHTYPE:
vehType = (vehicleType_t)GetIDForString( VehicleTable, value );
*(vehicleType_t *)(b+vehFields[i].ofs) = vehType;
break;
case VF_ANIM:
int anim = GetIDForString( animTable, value );
*(int *)(b+vehFields[i].ofs) = anim;
break;
}
break;
}
}
}
}
static void G_VehicleStoreParms( const char *p )
{//load up all into a table: g_vehicleInfo
const char *token;
vehicleInfo_t *vehicle;
////////////////// HERE //////////////////////
// The first vehicle just contains all the base level (not 'overridden') function calls.
G_SetSharedVehicleFunctions( &g_vehicleInfo[0] );
numVehicles = 1;
//try to parse data out
COM_BeginParseSession();
//look for an open brace
while ( p )
{
token = COM_ParseExt( &p, qtrue );
if ( token[0] == 0 )
{//barf
return;
}
if ( !Q_stricmp( token, "{" ) )
{//found one, parse out the goodies
if ( numVehicles >= MAX_VEHICLES )
{//sorry, no more vehicle slots!
gi.Printf( S_COLOR_RED"Too many vehicles in *.veh (limit %d)\n", MAX_VEHICLES );
break;
}
//token = token;
vehicle = &g_vehicleInfo[numVehicles++];
G_VehicleSetDefaults( vehicle );
G_ParseVehicleParms( vehicle, &p );
//sanity check and clamp the vehicle's data
G_VehicleClampData( vehicle );
////////////////// HERE //////////////////////
// Setup the shared function pointers.
G_SetSharedVehicleFunctions( vehicle );
switch( vehicle->type )
{
case VH_SPEEDER:
G_SetSpeederVehicleFunctions( vehicle );
break;
case VH_ANIMAL:
G_SetAnimalVehicleFunctions( vehicle );
break;
case VH_FIGHTER:
G_SetFighterVehicleFunctions( vehicle );
break;
case VH_WALKER:
G_SetAnimalVehicleFunctions( vehicle );
break;
}
}
}
}
void G_VehicleLoadParms( void )
{//HMM... only do this if there's a vehicle on the level?
int len, totallen, vehExtFNLen, fileCnt, i;
char *buffer, *holdChar, *marker;
char vehExtensionListBuf[2048]; // The list of file names read in
#define MAX_VEHICLE_DATA_SIZE 0x20000
char VehicleParms[MAX_VEHICLE_DATA_SIZE]={0};
// gi.Printf( "Parsing *.veh vehicle definitions\n" );
//set where to store the first one
totallen = 0;
marker = VehicleParms;
//now load in the .veh vehicle definitions
fileCnt = gi.FS_GetFileList("ext_data/vehicles", ".veh", vehExtensionListBuf, sizeof(vehExtensionListBuf) );
holdChar = vehExtensionListBuf;
for ( i = 0; i < fileCnt; i++, holdChar += vehExtFNLen + 1 )
{
vehExtFNLen = strlen( holdChar );
//gi.Printf( "Parsing %s\n", holdChar );
len = gi.FS_ReadFile( va( "ext_data/vehicles/%s", holdChar), (void **) &buffer );
if ( len == -1 )
{
gi.Printf( "G_VehicleLoadParms: error reading file %s\n", holdChar );
}
else
{
if ( totallen && *(marker-1) == '}' )
{//don't let it end on a } because that should be a stand-alone token
strcat( marker, " " );
totallen++;
marker++;
}
if ( totallen + len >= MAX_VEHICLE_DATA_SIZE ) {
G_Error( "G_VehicleLoadParms: ran out of space before reading %s\n(you must make the .npc files smaller)", holdChar );
}
strcat( marker, buffer );
gi.FS_FreeFile( buffer );
totallen += len;
marker += len;
}
}
G_VehicleStoreParms(VehicleParms);
}
| 1 | 0.85304 | 1 | 0.85304 | game-dev | MEDIA | 0.977064 | game-dev | 0.773454 | 1 | 0.773454 |
CrazyVince/Hacking | 4,029 | Library/PackageCache/com.unity.timeline@1.6.4/Editor/treeview/TimelineClipUnion.cs | using System.Collections.Generic;
using System.Linq;
using UnityEditorInternal;
using UnityEngine;
namespace UnityEditor.Timeline
{
class TimelineClipUnion
{
List<TimelineClipGUI> m_Members = new List<TimelineClipGUI>();
Rect m_BoundingRect;
Rect m_Union;
double m_Start;
double m_Duration;
bool m_InitUnionRect = true;
void Add(TimelineClipGUI clip)
{
m_Members.Add(clip);
if (m_Members.Count == 1)
{
m_BoundingRect = clip.clippedRect;
}
else
{
m_BoundingRect = Encompass(m_BoundingRect, clip.rect);
}
}
public void Draw(Rect parentRect, WindowState state)
{
if (m_InitUnionRect)
{
m_Start = m_Members.OrderBy(c => c.clip.start).First().clip.start;
m_Duration = m_Members.Sum(c => c.clip.duration);
m_InitUnionRect = false;
}
m_Union = new Rect((float)(m_Start) * state.timeAreaScale.x, 0, (float)m_Duration * state.timeAreaScale.x, 0);
// transform clipRect into pixel-space
m_Union.xMin += state.timeAreaTranslation.x + parentRect.x;
m_Union.xMax += state.timeAreaTranslation.x + parentRect.x;
m_Union.y = parentRect.y + 4.0f;
m_Union.height = parentRect.height - 8.0f;
// calculate clipped rect
if (m_Union.x < parentRect.xMin)
{
var overflow = parentRect.xMin - m_Union.x;
m_Union.x = parentRect.xMin;
m_Union.width -= overflow;
}
// bail out if completely clipped
if (m_Union.xMax < parentRect.xMin)
return;
if (m_Union.xMin > parentRect.xMax)
return;
EditorGUI.DrawRect(m_Union, DirectorStyles.Instance.customSkin.colorClipUnion);
}
public static List<TimelineClipUnion> Build(List<TimelineClipGUI> clips)
{
var unions = new List<TimelineClipUnion>();
if (clips == null)
return unions;
TimelineClipUnion currentUnion = null;
foreach (var c in clips)
{
if (currentUnion == null)
{
currentUnion = new TimelineClipUnion();
currentUnion.Add(c);
unions.Add(currentUnion);
}
else
{
Rect result;
if (Intersection(c.rect, currentUnion.m_BoundingRect, out result))
{
currentUnion.Add(c);
}
else
{
currentUnion = new TimelineClipUnion();
currentUnion.Add(c);
unions.Add(currentUnion);
}
}
}
return unions;
}
public static Rect Encompass(Rect a, Rect b)
{
Rect newRect = a;
newRect.xMin = Mathf.Min(a.xMin, b.xMin);
newRect.yMin = Mathf.Min(a.yMin, b.yMin);
newRect.xMax = Mathf.Max(a.xMax, b.xMax);
newRect.yMax = Mathf.Max(a.yMax, b.yMax);
return newRect;
}
public static bool Intersection(Rect r1, Rect r2, out Rect intersection)
{
if (!r1.Overlaps(r2) && !r2.Overlaps(r1))
{
intersection = new Rect(0, 0, 0, 0);
return false;
}
float left = Mathf.Max(r1.xMin, r2.xMin);
float top = Mathf.Max(r1.yMin, r2.yMin);
float right = Mathf.Min(r1.xMax, r2.xMax);
float bottom = Mathf.Min(r1.yMax, r2.yMax);
intersection = new Rect(left, top, right - left, bottom - top);
return true;
}
}
}
| 1 | 0.932197 | 1 | 0.932197 | game-dev | MEDIA | 0.799767 | game-dev | 0.949313 | 1 | 0.949313 |
glKarin/com.n0n3m4.diii4a | 14,274 | Q3E/src/main/jni/jk/code/game/AI_Seeker.cpp | /*
===========================================================================
Copyright (C) 2000 - 2013, Raven Software, Inc.
Copyright (C) 2001 - 2013, Activision, Inc.
Copyright (C) 2013 - 2015, OpenJK contributors
This file is part of the OpenJK source code.
OpenJK is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, see <http://www.gnu.org/licenses/>.
===========================================================================
*/
#include "b_local.h"
#include "g_nav.h"
#include "../cgame/cg_local.h"
#include "g_functions.h"
extern void NPC_BSST_Patrol( void );
extern void Boba_FireDecide( void );
extern gentity_t *CreateMissile( vec3_t org, vec3_t dir, float vel, int life, gentity_t *owner, qboolean altFire = qfalse );
void Seeker_Strafe( void );
#define VELOCITY_DECAY 0.7f
#define MIN_MELEE_RANGE 320
#define MIN_MELEE_RANGE_SQR ( MIN_MELEE_RANGE * MIN_MELEE_RANGE )
#define MIN_DISTANCE 80
#define MIN_DISTANCE_SQR ( MIN_DISTANCE * MIN_DISTANCE )
#define SEEKER_STRAFE_VEL 100
#define SEEKER_STRAFE_DIS 200
#define SEEKER_UPWARD_PUSH 32
#define SEEKER_FORWARD_BASE_SPEED 10
#define SEEKER_FORWARD_MULTIPLIER 2
#define SEEKER_SEEK_RADIUS 1024
//------------------------------------
void NPC_Seeker_Precache(void)
{
G_SoundIndex("sound/chars/seeker/misc/fire.wav");
G_SoundIndex( "sound/chars/seeker/misc/hiss.wav");
G_EffectIndex( "env/small_explode");
}
//------------------------------------
void NPC_Seeker_Pain( gentity_t *self, gentity_t *inflictor, gentity_t *other, const vec3_t point, int damage, int mod,int hitLoc )
{
if ( !(self->svFlags & SVF_CUSTOM_GRAVITY ))
{
G_Damage( self, NULL, NULL, vec3_origin, (float*)vec3_origin, 999, 0, MOD_FALLING );
}
SaveNPCGlobals();
SetNPCGlobals( self );
Seeker_Strafe();
RestoreNPCGlobals();
NPC_Pain( self, inflictor, other, point, damage, mod );
}
//------------------------------------
void Seeker_MaintainHeight( void )
{
float dif;
// Update our angles regardless
NPC_UpdateAngles( qtrue, qtrue );
// If we have an enemy, we should try to hover at or a little below enemy eye level
if ( NPC->enemy )
{
if (TIMER_Done( NPC, "heightChange" ))
{
TIMER_Set( NPC,"heightChange",Q_irand( 1000, 3000 ));
// Find the height difference
dif = (NPC->enemy->currentOrigin[2] + Q_flrand( NPC->enemy->maxs[2]/2, NPC->enemy->maxs[2]+8 )) - NPC->currentOrigin[2];
float difFactor = 1.0f;
if ( NPC->client->NPC_class == CLASS_BOBAFETT )
{
if ( TIMER_Done( NPC, "flameTime" ) )
{
difFactor = 10.0f;
}
}
// cap to prevent dramatic height shifts
if ( fabs( dif ) > 2*difFactor )
{
if ( fabs( dif ) > 24*difFactor )
{
dif = ( dif < 0 ? -24*difFactor : 24*difFactor );
}
NPC->client->ps.velocity[2] = (NPC->client->ps.velocity[2]+dif)/2;
}
if ( NPC->client->NPC_class == CLASS_BOBAFETT )
{
NPC->client->ps.velocity[2] *= Q_flrand( 0.85f, 3.0f );
}
}
}
else
{
gentity_t *goal = NULL;
if ( NPCInfo->goalEntity ) // Is there a goal?
{
goal = NPCInfo->goalEntity;
}
else
{
goal = NPCInfo->lastGoalEntity;
}
if ( goal )
{
dif = goal->currentOrigin[2] - NPC->currentOrigin[2];
if ( fabs( dif ) > 24 )
{
ucmd.upmove = ( ucmd.upmove < 0 ? -4 : 4 );
}
else
{
if ( NPC->client->ps.velocity[2] )
{
NPC->client->ps.velocity[2] *= VELOCITY_DECAY;
if ( fabs( NPC->client->ps.velocity[2] ) < 2 )
{
NPC->client->ps.velocity[2] = 0;
}
}
}
}
}
// Apply friction
if ( NPC->client->ps.velocity[0] )
{
NPC->client->ps.velocity[0] *= VELOCITY_DECAY;
if ( fabs( NPC->client->ps.velocity[0] ) < 1 )
{
NPC->client->ps.velocity[0] = 0;
}
}
if ( NPC->client->ps.velocity[1] )
{
NPC->client->ps.velocity[1] *= VELOCITY_DECAY;
if ( fabs( NPC->client->ps.velocity[1] ) < 1 )
{
NPC->client->ps.velocity[1] = 0;
}
}
}
//------------------------------------
void Seeker_Strafe( void )
{
int side;
vec3_t end, right, dir;
trace_t tr;
if ( Q_flrand(0.0f, 1.0f) > 0.7f || !NPC->enemy || !NPC->enemy->client )
{
// Do a regular style strafe
AngleVectors( NPC->client->renderInfo.eyeAngles, NULL, right, NULL );
// Pick a random strafe direction, then check to see if doing a strafe would be
// reasonably valid
side = ( rand() & 1 ) ? -1 : 1;
VectorMA( NPC->currentOrigin, SEEKER_STRAFE_DIS * side, right, end );
gi.trace( &tr, NPC->currentOrigin, NULL, NULL, end, NPC->s.number, MASK_SOLID, (EG2_Collision)0, 0 );
// Close enough
if ( tr.fraction > 0.9f )
{
float vel = SEEKER_STRAFE_VEL;
float upPush = SEEKER_UPWARD_PUSH;
if ( NPC->client->NPC_class != CLASS_BOBAFETT )
{
G_Sound( NPC, G_SoundIndex( "sound/chars/seeker/misc/hiss" ));
}
else
{
vel *= 3.0f;
upPush *= 4.0f;
}
VectorMA( NPC->client->ps.velocity, vel*side, right, NPC->client->ps.velocity );
// Add a slight upward push
NPC->client->ps.velocity[2] += upPush;
NPCInfo->standTime = level.time + 1000 + Q_flrand(0.0f, 1.0f) * 500;
}
}
else
{
// Do a strafe to try and keep on the side of their enemy
AngleVectors( NPC->enemy->client->renderInfo.eyeAngles, dir, right, NULL );
// Pick a random side
side = ( rand() & 1 ) ? -1 : 1;
float stDis = SEEKER_STRAFE_DIS;
if ( NPC->client->NPC_class == CLASS_BOBAFETT )
{
stDis *= 2.0f;
}
VectorMA( NPC->enemy->currentOrigin, stDis * side, right, end );
// then add a very small bit of random in front of/behind the player action
VectorMA( end, Q_flrand(-1.0f, 1.0f) * 25, dir, end );
gi.trace( &tr, NPC->currentOrigin, NULL, NULL, end, NPC->s.number, MASK_SOLID, (EG2_Collision)0, 0 );
// Close enough
if ( tr.fraction > 0.9f )
{
VectorSubtract( tr.endpos, NPC->currentOrigin, dir );
dir[2] *= 0.25; // do less upward change
float dis = VectorNormalize( dir );
// Try to move the desired enemy side
VectorMA( NPC->client->ps.velocity, dis, dir, NPC->client->ps.velocity );
float upPush = SEEKER_UPWARD_PUSH;
if ( NPC->client->NPC_class != CLASS_BOBAFETT )
{
G_Sound( NPC, G_SoundIndex( "sound/chars/seeker/misc/hiss" ));
}
else
{
upPush *= 4.0f;
}
// Add a slight upward push
NPC->client->ps.velocity[2] += upPush;
NPCInfo->standTime = level.time + 2500 + Q_flrand(0.0f, 1.0f) * 500;
}
}
}
//------------------------------------
void Seeker_Hunt( qboolean visible, qboolean advance )
{
float speed;
vec3_t forward;
NPC_FaceEnemy( qtrue );
// If we're not supposed to stand still, pursue the player
if ( NPCInfo->standTime < level.time )
{
// Only strafe when we can see the player
if ( visible )
{
Seeker_Strafe();
return;
}
}
// If we don't want to advance, stop here
if ( advance == qfalse )
{
return;
}
// Only try and navigate if the player is visible
if ( visible == qfalse )
{
// Move towards our goal
NPCInfo->goalEntity = NPC->enemy;
NPCInfo->goalRadius = 24;
NPC_MoveToGoal(qtrue);
return;
}
else
{
VectorSubtract( NPC->enemy->currentOrigin, NPC->currentOrigin, forward );
/*distance = */VectorNormalize( forward );
}
speed = SEEKER_FORWARD_BASE_SPEED + SEEKER_FORWARD_MULTIPLIER * g_spskill->integer;
VectorMA( NPC->client->ps.velocity, speed, forward, NPC->client->ps.velocity );
}
//------------------------------------
void Seeker_Fire( void )
{
vec3_t dir, enemy_org, muzzle;
gentity_t *missile;
CalcEntitySpot( NPC->enemy, SPOT_HEAD, enemy_org );
VectorSubtract( enemy_org, NPC->currentOrigin, dir );
VectorNormalize( dir );
// move a bit forward in the direction we shall shoot in so that the bolt doesn't poke out the other side of the seeker
VectorMA( NPC->currentOrigin, 15, dir, muzzle );
missile = CreateMissile( muzzle, dir, 1000, 10000, NPC );
G_PlayEffect( "blaster/muzzle_flash", NPC->currentOrigin, dir );
missile->classname = "blaster";
missile->s.weapon = WP_BLASTER;
missile->damage = 5;
missile->dflags = DAMAGE_DEATH_KNOCKBACK;
missile->methodOfDeath = MOD_ENERGY;
missile->clipmask = MASK_SHOT | CONTENTS_LIGHTSABER;
}
//------------------------------------
void Seeker_Ranged( qboolean visible, qboolean advance )
{
if ( NPC->client->NPC_class != CLASS_BOBAFETT )
{
if ( NPC->count > 0 )
{
if ( TIMER_Done( NPC, "attackDelay" )) // Attack?
{
TIMER_Set( NPC, "attackDelay", Q_irand( 250, 2500 ));
Seeker_Fire();
NPC->count--;
}
}
else
{
// out of ammo, so let it die...give it a push up so it can fall more and blow up on impact
// NPC->client->ps.gravity = 900;
// NPC->svFlags &= ~SVF_CUSTOM_GRAVITY;
// NPC->client->ps.velocity[2] += 16;
G_Damage( NPC, NPC, NPC, NULL, NULL, 999, 0, MOD_UNKNOWN );
}
}
if ( NPCInfo->scriptFlags & SCF_CHASE_ENEMIES )
{
Seeker_Hunt( visible, advance );
}
}
//------------------------------------
void Seeker_Attack( void )
{
// Always keep a good height off the ground
Seeker_MaintainHeight();
// Rate our distance to the target, and our visibilty
float distance = DistanceHorizontalSquared( NPC->currentOrigin, NPC->enemy->currentOrigin );
qboolean visible = NPC_ClearLOS( NPC->enemy );
qboolean advance = (qboolean)(distance > MIN_DISTANCE_SQR);
if ( NPC->client->NPC_class == CLASS_BOBAFETT )
{
advance = (qboolean)(distance>(200.0f*200.0f));
}
// If we cannot see our target, move to see it
if ( visible == qfalse )
{
if ( NPCInfo->scriptFlags & SCF_CHASE_ENEMIES )
{
Seeker_Hunt( visible, advance );
return;
}
}
Seeker_Ranged( visible, advance );
}
//------------------------------------
void Seeker_FindEnemy( void )
{
int numFound;
float dis, bestDis = SEEKER_SEEK_RADIUS * SEEKER_SEEK_RADIUS + 1;
vec3_t mins, maxs;
gentity_t *entityList[MAX_GENTITIES], *ent, *best = NULL;
VectorSet( maxs, SEEKER_SEEK_RADIUS, SEEKER_SEEK_RADIUS, SEEKER_SEEK_RADIUS );
VectorScale( maxs, -1, mins );
numFound = gi.EntitiesInBox( mins, maxs, entityList, MAX_GENTITIES );
for ( int i = 0 ; i < numFound ; i++ )
{
ent = entityList[i];
if ( ent->s.number == NPC->s.number || !ent->client || !ent->NPC || ent->health <= 0 || !ent->inuse )
{
continue;
}
if ( ent->client->playerTeam == NPC->client->playerTeam || ent->client->playerTeam == TEAM_NEUTRAL ) // don't attack same team or bots
{
continue;
}
// try to find the closest visible one
if ( !NPC_ClearLOS( ent ))
{
continue;
}
dis = DistanceHorizontalSquared( NPC->currentOrigin, ent->currentOrigin );
if ( dis <= bestDis )
{
bestDis = dis;
best = ent;
}
}
if ( best )
{
// used to offset seekers around a circle so they don't occupy the same spot. This is not a fool-proof method.
NPC->random = Q_flrand(0.0f, 1.0f) * 6.3f; // roughly 2pi
NPC->enemy = best;
}
}
//------------------------------------
void Seeker_FollowPlayer( void )
{
Seeker_MaintainHeight();
float dis = DistanceHorizontalSquared( NPC->currentOrigin, g_entities[0].currentOrigin );
vec3_t pt, dir;
float minDistSqr = MIN_DISTANCE_SQR;
if ( NPC->client->NPC_class == CLASS_BOBAFETT )
{
if ( TIMER_Done( NPC, "flameTime" ) )
{
minDistSqr = 200*200;
}
}
if ( dis < minDistSqr )
{
// generally circle the player closely till we take an enemy..this is our target point
if ( NPC->client->NPC_class == CLASS_BOBAFETT )
{
pt[0] = g_entities[0].currentOrigin[0] + cos( level.time * 0.001f + NPC->random ) * 250;
pt[1] = g_entities[0].currentOrigin[1] + sin( level.time * 0.001f + NPC->random ) * 250;
if ( NPC->client->jetPackTime < level.time )
{
pt[2] = NPC->currentOrigin[2] - 64;
}
else
{
pt[2] = g_entities[0].currentOrigin[2] + 200;
}
}
else
{
pt[0] = g_entities[0].currentOrigin[0] + cos( level.time * 0.001f + NPC->random ) * 56;
pt[1] = g_entities[0].currentOrigin[1] + sin( level.time * 0.001f + NPC->random ) * 56;
pt[2] = g_entities[0].currentOrigin[2] + 40;
}
VectorSubtract( pt, NPC->currentOrigin, dir );
VectorMA( NPC->client->ps.velocity, 0.8f, dir, NPC->client->ps.velocity );
}
else
{
if ( NPC->client->NPC_class != CLASS_BOBAFETT )
{
if ( TIMER_Done( NPC, "seekerhiss" ))
{
TIMER_Set( NPC, "seekerhiss", 1000 + Q_flrand(0.0f, 1.0f) * 1000 );
G_Sound( NPC, G_SoundIndex( "sound/chars/seeker/misc/hiss" ));
}
}
// Hey come back!
NPCInfo->goalEntity = &g_entities[0];
NPCInfo->goalRadius = 32;
NPC_MoveToGoal( qtrue );
NPC->owner = &g_entities[0];
}
if ( NPCInfo->enemyCheckDebounceTime < level.time )
{
// check twice a second to find a new enemy
Seeker_FindEnemy();
NPCInfo->enemyCheckDebounceTime = level.time + 500;
}
NPC_UpdateAngles( qtrue, qtrue );
}
//------------------------------------
void NPC_BSSeeker_Default( void )
{
if ( in_camera )
{
if ( NPC->client->NPC_class != CLASS_BOBAFETT )
{
// cameras make me commit suicide....
G_Damage( NPC, NPC, NPC, NULL, NULL, 999, 0, MOD_UNKNOWN );
}
}
if ( NPC->random == 0.0f )
{
// used to offset seekers around a circle so they don't occupy the same spot. This is not a fool-proof method.
NPC->random = Q_flrand(0.0f, 1.0f) * 6.3f; // roughly 2pi
}
if ( NPC->enemy && NPC->enemy->health && NPC->enemy->inuse )
{
if ( NPC->client->NPC_class != CLASS_BOBAFETT
&& ( NPC->enemy->s.number == 0 || ( NPC->enemy->client && NPC->enemy->client->NPC_class == CLASS_SEEKER )) )
{
//hacked to never take the player as an enemy, even if the player shoots at it
NPC->enemy = NULL;
}
else
{
Seeker_Attack();
if ( NPC->client->NPC_class == CLASS_BOBAFETT )
{
Boba_FireDecide();
}
return;
}
}
else if ( NPC->client->NPC_class == CLASS_BOBAFETT )
{
NPC_BSST_Patrol();
return;
}
// In all other cases, follow the player and look for enemies to take on
Seeker_FollowPlayer();
} | 1 | 0.964188 | 1 | 0.964188 | game-dev | MEDIA | 0.995242 | game-dev | 0.983308 | 1 | 0.983308 |
simonec73/threatsmanager | 3,727 | Sources/Extensions/ThreatsManager.DevOps/Mapper.cs | using System.Collections.Generic;
using System.Linq;
using PostSharp.Patterns.Contracts;
namespace ThreatsManager.DevOps
{
class Mapper<T>
{
private Dictionary<string, T> _map = new Dictionary<string, T>();
private Dictionary<string, T> _standard = new Dictionary<string,T>();
public void SetStandardMapping([Required] string key, T value)
{
_standard[key] = value;
}
public IEnumerable<string> Keys
{
get
{
IEnumerable<string> result = null;
if (_map.Any() || _standard.Any())
{
var list = new List<string>();
if (_map.Any())
list.AddRange(_map.Keys.ToArray());
if (_standard.Any())
{
foreach (var item in _standard.Keys)
{
if (!list.Contains(item))
list.Add(item);
}
}
result = list;
}
return result;
}
}
public T Get([Required] string key)
{
T result = default(T);
if (_map.ContainsKey(key))
result = _map[key];
else if (_standard.ContainsKey(key))
result = _standard[key];
return result;
}
public IEnumerable<string> Get(T key)
{
var mapList = _map
.Where(x => x.Value.Equals(key))
.Select(x => x.Key).ToArray();
var list = new List<string>();
if (mapList.Any())
{
list.AddRange(mapList);
}
var standardList = _standard
.Where(x => x.Value.Equals(key))
.Select(x => x.Key).ToArray();
if (standardList.Any())
{
foreach (var item in standardList)
{
if (!list.Contains(item))
list.Add(item);
}
}
return list;
}
public void Add([Required] string key, T value)
{
_map[key] = value;
}
public void Remove([Required] string key)
{
_map.Remove(key);
}
public T this[string key]
{
get => Get(key);
set => Add(key, value);
}
public IEnumerable<KeyValuePair<string, T>> ToArray()
{
var result = new Dictionary<string, T>();
if (_standard.Any())
{
foreach (var item in _standard)
{
result[item.Key] = item.Value;
}
}
if (_map.Any())
{
foreach (var item in _map)
{
result[item.Key] = item.Value;
}
}
return result.ToArray();
}
public bool ContainsKey([Required] string key)
{
return _map.ContainsKey(key) || _standard.ContainsKey(key);
}
public bool TryGetValue(string key, out T value)
{
bool result = false;
value = default(T);
if (_map.ContainsKey(key))
{
result = true;
value = _map[key];
} else if (_standard.ContainsKey(key))
{
result = true;
value = _standard[key];
}
return result;
}
}
}
| 1 | 0.889171 | 1 | 0.889171 | game-dev | MEDIA | 0.198587 | game-dev | 0.948664 | 1 | 0.948664 |
tryingsomestuff/Minic | 1,102 | Source/timeMan.hpp | #pragma once
#include "definition.hpp"
struct Position;
/*!
* Time managament in Minic
* GUI protocol is setting internal TimeMan variable as possible.
* Then Timeman is responsible to compute msec for next move, using getNextMSecPerMove(), based on GUI available information.
* Then Searcher::currentMoveMs is set to getNextMSecPerMove at the begining of a search.
* Then, during a search Searcher::getCurrentMoveMs() is used to check the available time.
*/
namespace TimeMan {
extern TimeType msecPerMove, msecInTC, msecInc, msecUntilNextTC, overHead;
extern TimeType targetTime, maxTime;
extern int moveToGo, nbMoveInTC;
extern uint64_t maxNodes;
extern bool isDynamic;
const TimeType msecMinimal = 20; // the minimum time "lost" by move (for instance when parsing input)
void init();
[[nodiscard]] TimeType getNextMSecPerMove(const Position& p);
enum TCType { TC_suddendeath, TC_repeating, TC_fixed };
void simulate(const TCType tcType, const TimeType initialTime, const TimeType increment = -1, const int movesInTC = -1, const TimeType guiLag = 0);
} // namespace TimeMan
| 1 | 0.701314 | 1 | 0.701314 | game-dev | MEDIA | 0.508156 | game-dev | 0.862315 | 1 | 0.862315 |
sniffle6/Scriptable-Object-Inventory | 1,422 | Equipment System Part 1.5 Refractor - old/Assets/Scripts/ModifiableInt.cs | using System;
using System.Collections.Generic;
using UnityEngine;
public delegate void ModifiedEvent();
[Serializable]
public class ModifiableInt
{
[SerializeField]
int baseValue;
public int BaseValue { get { return baseValue; } set { baseValue = value; UpdateModifiedValue(); } }
public int ModifiedValue { get; private set; }
public event ModifiedEvent ValueModified;
public ModifiableInt(ModifiedEvent method = null)
{
ModifiedValue = baseValue;
if (method != null)
ValueModified += method;
}
public List<IModifiers> modifiers = new List<IModifiers>();
public void RegisterModEvent(ModifiedEvent method)
{
ValueModified += method;
}
public void UnregisterModEvent(ModifiedEvent method)
{
ValueModified -= method;
}
public void UpdateModifiedValue()
{
var valueToAdd = 0;
for (int i = 0; i < modifiers.Count; i++)
{
modifiers[i].AddValue(ref valueToAdd);
}
ModifiedValue = baseValue + valueToAdd;
if (ValueModified != null)
{
ValueModified.Invoke();
}
}
public void AddModifier(IModifiers modifier)
{
modifiers.Add(modifier);
UpdateModifiedValue();
}
public void RemoveModifier(IModifiers modifier)
{
modifiers.Remove(modifier);
UpdateModifiedValue();
}
} | 1 | 0.562991 | 1 | 0.562991 | game-dev | MEDIA | 0.328192 | game-dev | 0.653349 | 1 | 0.653349 |
Aussiemon/Darktide-Source-Code | 14,881 | scripts/extension_systems/character_state_machine/character_states/player_character_state_netted.lua | -- chunkname: @scripts/extension_systems/character_state_machine/character_states/player_character_state_netted.lua
require("scripts/extension_systems/character_state_machine/character_states/player_character_state_base")
local Assist = require("scripts/extension_systems/character_state_machine/character_states/utilities/assist")
local CharacterStateAssistSettings = require("scripts/settings/character_state/character_state_assist_settings")
local CharacterStateNettedSettings = require("scripts/settings/character_state/character_state_netted_settings")
local DialogueSettings = require("scripts/settings/dialogue/dialogue_settings")
local FirstPersonView = require("scripts/utilities/first_person_view")
local ForceRotation = require("scripts/extension_systems/locomotion/utilities/force_rotation")
local HealthStateTransitions = require("scripts/extension_systems/character_state_machine/character_states/utilities/health_state_transitions")
local LagCompensation = require("scripts/utilities/lag_compensation")
local Luggable = require("scripts/utilities/luggable")
local Netted = require("scripts/extension_systems/character_state_machine/character_states/utilities/netted")
local PlayerVoiceGrunts = require("scripts/utilities/player_voice_grunts")
local PlayerUnitData = require("scripts/extension_systems/unit_data/utilities/player_unit_data")
local PlayerUnitVisualLoadout = require("scripts/extension_systems/visual_loadout/utilities/player_unit_visual_loadout")
local Vo = require("scripts/utilities/vo")
local PlayerCharacterStateNetted = class("PlayerCharacterStateNetted", "PlayerCharacterStateBase")
local netted_anims = CharacterStateNettedSettings.anim_settings
local breed_specific_settings = CharacterStateNettedSettings.breed_specific_settings
local assist_anims = CharacterStateAssistSettings.anim_settings.netted
local TENSION_TYPE = "netted"
local SFX_SOURCE = "head"
local STINGER_ENTER_ALIAS = "disabled_enter"
local STINGER_EXIT_ALIAS = "disabled_exit"
local LOOPING_SOUND_ALIAS = "netted"
local STINGER_PROPERTIES = {
stinger_type = "netted",
}
local VCE_ALIAS = "scream_long_vce"
PlayerCharacterStateNetted.init = function (self, character_state_init_context, ...)
PlayerCharacterStateNetted.super.init(self, character_state_init_context, ...)
local unit_data_extension = character_state_init_context.unit_data
local disabled_character_state_component = unit_data_extension:write_component("disabled_character_state")
disabled_character_state_component.is_disabled = false
disabled_character_state_component.disabling_unit = nil
disabled_character_state_component.disabling_type = "none"
disabled_character_state_component.target_drag_position = Vector3.zero()
disabled_character_state_component.has_reached_drag_position = false
self._disabled_character_state_component = disabled_character_state_component
self._disabled_state_input = unit_data_extension:read_component("disabled_state_input")
self._entered_state_t = nil
self._time_disabled = nil
end
PlayerCharacterStateNetted.extensions_ready = function (self, world, unit)
PlayerCharacterStateNetted.super.extensions_ready(self, world, unit)
local is_server = self._is_server
local game_session_or_nil = self._game_session
local game_object_id_or_nil = self._game_object_id
self._assist = Assist:new(assist_anims, is_server, unit, game_session_or_nil, game_object_id_or_nil, "saved")
end
PlayerCharacterStateNetted.game_object_initialized = function (self, game_session, game_object_id)
PlayerCharacterStateNetted.super.game_object_initialized(self, game_session, game_object_id)
self._assist:game_object_initialized(game_session, game_object_id)
end
PlayerCharacterStateNetted.on_enter = function (self, unit, dt, t, previous_state, params)
PlayerCharacterStateNetted.super.on_enter(self, unit, dt, t, previous_state, params)
local disabling_unit = self._disabled_state_input.disabling_unit
local disabling_unit_data_extension = ScriptUnit.extension(disabling_unit, "unit_data_system")
self._disabling_breed = disabling_unit_data_extension:breed()
local locomotion_component = self._locomotion_component
local locomotion_force_rotation_component = self._locomotion_force_rotation_component
local locomotion_steering_component = self._locomotion_steering_component
local movement_state_component = self._movement_state_component
local fx_extension = self._fx_extension
local animation_extension = self._animation_extension
local disabled_character_state_component = self._disabled_character_state_component
local inventory_component = self._inventory_component
local visual_loadout_extension = self._visual_loadout_extension
Luggable.drop_luggable(t, unit, inventory_component, visual_loadout_extension, true)
local disabling_breed = self._disabling_breed
Netted.enter(unit, animation_extension, fx_extension, self._breed, disabling_breed, locomotion_steering_component, movement_state_component, t)
local is_server = self._is_server
if is_server then
local navigation_extension = ScriptUnit.extension(unit, "navigation_system")
local drag_position = Netted.calculate_drag_position(locomotion_component, navigation_extension, disabling_unit, self._nav_world)
disabled_character_state_component.target_drag_position = drag_position
end
disabled_character_state_component.is_disabled = true
disabled_character_state_component.disabling_type = "netted"
disabled_character_state_component.disabling_unit = disabling_unit
locomotion_steering_component.disable_minion_collision = true
local disabling_unit_rotation = Unit.world_rotation(disabling_unit, 1)
local force_rotation = Quaternion.look(-Quaternion.forward(disabling_unit_rotation))
local start_rotation = force_rotation
local duration = 0
ForceRotation.start(locomotion_force_rotation_component, locomotion_steering_component, force_rotation, start_rotation, t, duration)
if is_server then
self:_add_buffs(t)
self._fx_extension:trigger_gear_wwise_event_with_source(STINGER_ENTER_ALIAS, STINGER_PROPERTIES, SFX_SOURCE, true, true)
self._dialogue_extension:stop_currently_playing_vo()
self:_init_player_vo(t)
Managers.state.pacing:add_tension_type(TENSION_TYPE, unit)
end
self._entered_state_t = t
self._time_disabled = is_server and 0 or nil
self._assist:reset()
end
PlayerCharacterStateNetted.on_exit = function (self, unit, t, next_state)
PlayerCharacterStateNetted.super.on_exit(self, unit, t, next_state)
local is_server = self._is_server
local disabled_character_state_component = self._disabled_character_state_component
local fx_extension = self._fx_extension
local has_reached_drag_position = disabled_character_state_component.has_reached_drag_position
if not has_reached_drag_position then
self:_on_drag_completed(t)
end
disabled_character_state_component.has_reached_drag_position = false
local locomotion_force_rotation_component = self._locomotion_force_rotation_component
if locomotion_force_rotation_component.use_force_rotation then
ForceRotation.stop(locomotion_force_rotation_component)
end
if is_server then
Netted.try_exit(unit, self._inventory_component, self._visual_loadout_extension, self._unit_data_extension, t)
self:_remove_buffs()
local player_unit_spawn_manager = Managers.state.player_unit_spawn
local player = player_unit_spawn_manager:owner(unit)
local is_player_alive = player:unit_is_alive()
if is_player_alive then
local rescued_by_player = true
local state_name = "netted"
local time_in_captivity = t - self._entered_state_t
Managers.telemetry_events:player_exits_captivity(player, rescued_by_player, state_name, time_in_captivity)
Managers.stats:record_private("hook_escaped_captivitiy", player, state_name, self._time_disabled)
end
self._entered_state_t = nil
self._time_disabled = nil
end
local inventory_component = self._inventory_component
if next_state ~= "dead" and inventory_component.wielded_slot == "slot_unarmed" then
PlayerUnitVisualLoadout.wield_previous_slot(inventory_component, unit, t)
end
local locomotion_steering_component = self._locomotion_steering_component
locomotion_steering_component.disable_minion_collision = false
local rewind_ms = LagCompensation.rewind_ms(is_server, self._is_local_unit, self._player)
FirstPersonView.enter(t, self._first_person_mode_component, rewind_ms)
self._assist:stop()
if is_server and next_state == "walking" then
fx_extension:trigger_exclusive_gear_wwise_event(STINGER_EXIT_ALIAS, STINGER_PROPERTIES)
end
end
PlayerCharacterStateNetted.fixed_update = function (self, unit, dt, t, next_state_params, fixed_frame)
self:_update_netted(unit, dt, t)
local assist = self._assist
local assist_done = assist:update(dt, t)
self._fx_extension:run_looping_sound(LOOPING_SOUND_ALIAS, SFX_SOURCE, nil, fixed_frame)
if self._is_server then
if not assist:in_progress() then
self._time_disabled = self._time_disabled + dt
end
if not assist_done then
self:_update_vo(t)
end
end
return self:_check_transition(unit, t, next_state_params, assist_done)
end
PlayerCharacterStateNetted._update_netted = function (self, unit, dt, t)
local constants = self._constants
local character_state_component = self._character_state_component
local fp_anim_t = character_state_component.entered_t + constants.netted_fp_anim_duration
if fp_anim_t < t then
local is_in_fp = self._first_person_mode_component.wants_1p_camera
if is_in_fp then
self._animation_extension:anim_event(netted_anims.dragged_anim_event)
FirstPersonView.exit(t, self._first_person_mode_component)
end
local disabled_character_state_component = self._disabled_character_state_component
local has_reached_drag_position = disabled_character_state_component.has_reached_drag_position
if not has_reached_drag_position then
local target_drag_position = disabled_character_state_component.target_drag_position
self:_update_drag(unit, dt, t, target_drag_position)
end
end
end
PlayerCharacterStateNetted._check_transition = function (self, unit, t, next_state_params, assist_done)
local unit_data_extension = self._unit_data_extension
local health_transition = HealthStateTransitions.poll(unit_data_extension, next_state_params)
if health_transition then
return health_transition
end
if assist_done then
return "walking"
end
return nil
end
PlayerCharacterStateNetted._init_player_vo = function (self, t)
self._next_vo_trigger_time_t = t + DialogueSettings.netted_vo_start_delay_t
self._vo_sequence = 1
end
PlayerCharacterStateNetted._update_drag = function (self, unit, dt, t, target_drag_position)
local locomotion_component = self._locomotion_component
local current_position = locomotion_component.position
local constants = self._constants
local netted_drag_destination_size = constants.netted_drag_destination_size
local distance_remaining = Vector3.distance(Vector3.flat(current_position), Vector3.flat(target_drag_position))
local disabled_character_state_component = self._disabled_character_state_component
local has_reached_drag_position = disabled_character_state_component.has_reached_drag_position
if not has_reached_drag_position and distance_remaining <= netted_drag_destination_size then
self:_on_drag_completed(t)
else
if not self._previous_position then
self._previous_position = Vector3Box(current_position)
end
local is_stuck = self:_is_stuck(current_position)
if is_stuck then
self:_on_drag_completed(t)
return
end
local breed_settings = breed_specific_settings[self._breed.name]
local slowdown_distance = breed_settings.slowdown_distance
local min_slowdown_factor = breed_settings.min_slowdown_factor
local max_slowdown_factor = breed_settings.max_slowdown_factor
local drag_speed = breed_settings.drag_speed
local slowdown_factor = math.clamp(distance_remaining / slowdown_distance, min_slowdown_factor, max_slowdown_factor)
local wanted_speed = drag_speed * slowdown_factor
local direction = Vector3.normalize(target_drag_position - current_position)
local wanted_velocity = direction * wanted_speed
self._locomotion_steering_component.velocity_wanted = wanted_velocity
end
end
local MAX_FRAMES_STUCK = 10
PlayerCharacterStateNetted._is_stuck = function (self, current_position)
local is_stuck = false
local previous_position = self._previous_position:unbox()
local distance = Vector3.distance(previous_position, current_position)
local min_drag_distance = 0.05
local frames_with_no_movement = self._frames_with_no_movement or 0
if distance < min_drag_distance then
frames_with_no_movement = frames_with_no_movement + 1
is_stuck = frames_with_no_movement >= MAX_FRAMES_STUCK
else
frames_with_no_movement = 0
self._previous_position:store(current_position)
end
self._frames_with_no_movement = frames_with_no_movement
return is_stuck
end
PlayerCharacterStateNetted._on_drag_completed = function (self, t)
FirstPersonView.exit(t, self._first_person_mode_component)
local locomotion_steering_component = self._locomotion_steering_component
locomotion_steering_component.velocity_wanted = Vector3.zero()
locomotion_steering_component.calculate_fall_velocity = true
local disabled_character_state_component = self._disabled_character_state_component
disabled_character_state_component.has_reached_drag_position = true
self._frames_with_no_movement = 0
self._previous_position = nil
end
PlayerCharacterStateNetted._add_buffs = function (self, t)
local constants = self._constants
local buff_extension = self._buff_extension
if not self._damage_tick_buff_indexes then
local _, local_index, component_index = buff_extension:add_externally_controlled_buff(constants.netted_damage_tick_buff, t)
self._damage_tick_buff_indexes = {
local_index = local_index,
component_index = component_index,
}
end
end
PlayerCharacterStateNetted._remove_buffs = function (self)
local buff_extension = self._buff_extension
local damage_tick_buff_indexes = self._damage_tick_buff_indexes
if damage_tick_buff_indexes then
local local_index = damage_tick_buff_indexes.local_index
local component_index = damage_tick_buff_indexes.component_index
buff_extension:remove_externally_controlled_buff(local_index, component_index)
self._damage_tick_buff_indexes = nil
end
end
PlayerCharacterStateNetted._update_vo = function (self, t)
if t <= self._next_vo_trigger_time_t then
return
end
local vo_sequence = self._vo_sequence
if vo_sequence == 1 then
PlayerVoiceGrunts.trigger_voice(VCE_ALIAS, self._visual_loadout_extension, self._fx_extension, true)
else
local disabling_breed = self._disabling_breed
Vo.player_pounced_by_special_event(self._unit, disabling_breed.name)
end
self._next_vo_trigger_time_t = t + DialogueSettings.netted_vo_interval_t
self._vo_sequence = vo_sequence + 1
end
return PlayerCharacterStateNetted
| 1 | 0.936023 | 1 | 0.936023 | game-dev | MEDIA | 0.972905 | game-dev | 0.97775 | 1 | 0.97775 |
v3921358/MapleRoot | 2,590 | MapleRoot/scripts/npc/9040003.js | /*
This file is part of the OdinMS Maple Story Server
Copyright (C) 2008 Patrick Huy <patrick.huy@frz.cc>
Matthias Butz <matze@odinms.de>
Jan Christian Meyer <vimes@odinms.de>
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 version 3 as published by
the Free Software Foundation. You may not use, modify or distribute
this program under any other version of the GNU Affero General Public
License.
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/>.
*/
/*
* @Author TheRamon
* @Author Ronan
*
* Sharen III's Soul, Sharenian: Sharen III's Grave (990000700)
*
* Guild Quest - end of stage 4
*/
function clearStage(stage, eim) {
eim.setProperty("stage" + stage + "clear", "true");
eim.showClearEffect(true);
eim.giveEventPlayersStageReward(stage);
}
var status = 0;
function start() {
status = -1;
action(1, 0, 0);
}
function action(mode, type, selection) {
if (mode == -1) {
cm.dispose();
} else {
if (mode == 1) {
status++;
} else {
cm.dispose();
}
var eim = cm.getPlayer().getEventInstance();
if (eim.getProperty("stage4clear") != null && eim.getProperty("stage4clear") === "true") {
cm.sendOk("After what I thought would be an immortal sleep, I have finally found someone that will save Sharenian. I can truly rest in peace now.");
cm.dispose();
return;
}
if (status == 0) {
if (cm.isEventLeader()) {
cm.sendNext("After what I thought would be an immortal sleep, I have finally found someone that will save Sharenian. This old man will now pave the way for you to finish the quest.");
clearStage(4, eim);
cm.getGuild().gainGP(30);
cm.getPlayer().getMap().getReactorByName("ghostgate").forceHitReactor(1);
cm.dispose();
} else {
cm.sendOk("I need the leader of your party to speak with me, nobody else.");
cm.dispose();
}
}
}
} | 1 | 0.723647 | 1 | 0.723647 | game-dev | MEDIA | 0.92553 | game-dev | 0.82851 | 1 | 0.82851 |
hejiehui/xUnit | 1,355 | com.xrosstools.xunit.editor/src/com/xrosstools/xunit/editor/model/DecoratorNode.java | package com.xrosstools.xunit.editor.model;
import com.xrosstools.xunit.BehaviorType;
public class DecoratorNode extends CompositeUnitNode {
// To keep it simple, we don't provide customization for decorator adapter
// To provide your own decorator adapter implementation, use adapter instead
private UnitNode startNode;
private UnitNodePanel unitsPanel = new UnitNodePanel(this, 1);
private UnitNode endNode;
public DecoratorNode(){
super("a decorator", StructureType.decorator, true);
}
public String getDefaultImplName(){
return DEFAULT_DECORATOR_IMPL;
}
protected String getCategory(String id) {
return null;
}
public void setUnit(UnitNode unit) {
unitsPanel.set(INDEX_UNIT, unit);
}
public UnitNode getUnit() {
return unitsPanel.get(INDEX_UNIT);
}
/**
* Get from decoratee, if deocratee is null, use default as processor
*/
public BehaviorType getType() {
return getUnit() != null ? getUnit().getType() : BehaviorType.processor;
}
/**
* Do nothing because decorator node type will always be the decoratee type
*/
public void setType(BehaviorType type) {
firePropertyChange(PROP_NODE);
}
public UnitNode getStartNode(){
return startNode;
}
public UnitNodeContainer getContainerNode(){
return unitsPanel;
}
public UnitNode getEndNode(){
return endNode;
}
}
| 1 | 0.774951 | 1 | 0.774951 | game-dev | MEDIA | 0.387481 | game-dev | 0.60205 | 1 | 0.60205 |
Dimbreath/AzurLaneData | 10,484 | zh-TW/model/vo/shamchapter.lua | slot0 = class("ShamChapter", import(".Chapter"))
slot0.SAVE_TAG = "sham_all_ships_"
function slot0.Ctor(slot0)
slot0.id = nil
slot0.configId = nil
slot0.theme = nil
slot0.active = false
slot0.shamResetCount = 0
slot0.progress = 0
slot0.repairTimes = 0
slot0.dueTime = 999999999
slot0.fleet = ShamFleet.New()
slot0.fleets = {
slot0.fleet
}
slot0.findex = 1
slot0.ships = {}
slot0.cells = {}
slot0.pathFinder = nil
slot0.friendAssistShip = nil
slot0.mirrors = {}
end
function slot0.getDataType(slot0)
return ChapterConst.TypeSham
end
function slot0.getPlayType(slot0)
return ChapterConst.TypeLagacy
end
function slot0.bindConfigTable(slot0)
return pg.sham_battle_template
end
function slot0.update(slot0, slot1)
slot0.active = true
slot0.id = slot1.id
slot0.configId = slot0.id
slot0.theme = ChapterTheme.New(slot0:getConfig("theme"))
slot0.progress = slot1.progress or 0
slot3 = slot0:getConfig("float_items")
slot0.cells = {}
function slot5(slot0)
slot1 = ChapterCell.New(slot0)
slot2 = ChapterCell.Line2Name(slot1.row, slot1.column)
if _.detect(uv0, function (slot0)
return slot0[1] == uv0.row and slot0[2] == uv0.column
end) then
slot1.item = slot3[3]
slot1.itemOffset = Vector2(slot3[4], slot3[5])
end
uv1.cells[slot2] = slot1
return slot1
end
_.each(slot0:getConfig("grids"), function (slot0)
if not slot0[3] then
uv0({
pos = {
row = slot0[1],
column = slot0[2]
},
item_type = ChapterConst.AttachNone
}):SetWalkable(slot0[3])
end
end)
_.each(slot1.cell_list, function (slot0)
uv0(slot0)
end)
slot0.pathFinder = PathFinding.New({}, ChapterConst.MaxRow, ChapterConst.MaxColumn)
slot0:updateFriendShip(nil)
if slot1.assist_ship and pg.ship_data_statistics[slot1.assist_ship.template_id] then
slot0:updateFriendShip(Ship.New(slot1.assist_ship))
end
slot0.ships = {}
slot0.mirrors = {}
_.each(slot1.group_list, function (slot0)
if not uv0.friendAssistShip or uv0.friendAssistShip.id ~= slot0.id then
uv0.ships[slot0.id] = {
id = slot0.id,
hp_rant = slot0.hp_rant,
strategies = _.map(slot0.strategy_list or {}, function (slot0)
return {
id = slot0.id,
count = slot0.count
}
end)
}
uv0.mirrors[slot0.id] = Ship.New(slot0.ship_info)
elseif uv0.friendAssistShip.id == slot0.id then
uv0.friendAssistShip.hpRant = slot0.hp_rant
uv0.friendAssistShip.strategies = slot1
end
end)
slot0.fleet:updateShipMirrors(slot0.mirrors)
slot0.fleet:update(slot1.group)
slot0:updateFleetShips(slot1.group.formation_list)
end
function slot0.retreat(slot0)
slot0:updateFriendShip(nil)
slot0:flushShips()
for slot4, slot5 in pairs(slot0.ships) do
slot5.hp_rant = 10000
slot5.strategies = {}
end
slot0.fleet:retreat()
slot0.cells = {}
slot0.active = false
end
function slot0.inWartime(slot0)
return slot0.active
end
function slot0.shipInWartime(slot0, slot1)
return slot0:inWartime() and slot0:containsShip(slot1)
end
function slot0.fetchShipVO(slot0, slot1)
if slot0.active then
return Clone(slot0.mirrors[slot1])
else
return getProxy(BayProxy):getShipById(slot1)
end
end
function slot0.flushShips(slot0)
_.each(_.keys(slot0.ships), function (slot0)
if not uv0:fetchShipVO(slot0) then
uv0.ships[slot0] = nil
end
end)
slot0.fleet:flushShips()
end
function slot0.getFriendShip(slot0)
return Clone(slot0.friendAssistShip)
end
function slot0.updateFriendShip(slot0, slot1)
slot0.friendAssistShip = slot1
slot0.fleet:updateFriendShip(slot1)
end
function slot0.getShips(slot0, slot1)
slot3 = _(_.values(slot0.ships)):chain():map(function (slot0)
if uv0:fetchShipVO(slot0.id) then
slot1.hpRant = slot0.hp_rant
slot1.strategies = Clone(slot0.strategies)
end
return slot1
end):filter(function (slot0)
return slot0 ~= nil
end):sort(function (slot0, slot1)
if (uv0.fleet.ships[slot0.id] and 1 or 0) ~= (uv0.fleet.ships[slot1.id] and 1 or 0) then
return slot3 < slot2
else
return slot0.id < slot1.id
end
end):value()
if slot0:getFriendShip() and defaultValue(slot1, false) then
table.insert(slot3, slot4)
end
return slot3
end
function slot0.getShipsByTeam(slot0, slot1)
return _.filter(slot0:getShips(true), function (slot0)
return slot0:getTeamType() == uv0
end)
end
function slot0.getShip(slot0, slot1)
slot2 = nil
if slot0:getFriendShip() and slot3.id == slot1 then
slot2 = slot3
elseif slot0.ships[slot1] and slot0:fetchShipVO(slot4.id) then
slot2.hpRant = slot4.hp_rant
slot2.strategies = Clone(slot4.strategies)
end
return slot2
end
function slot0.containsShip(slot0, slot1)
return slot0.friendAssistShip and slot0.friendAssistShip.id == slot1 or slot0.ships[slot1]
end
function slot0.getRawShips(slot0)
return Clone(slot0.ships)
end
function slot0.updateRawShips(slot0, slot1)
slot0.ships = slot1
end
function slot0.updateRawShipsByTeam(slot0, slot1, slot2)
slot3 = slot0:getFriendShip()
for slot7, slot8 in pairs(slot0.ships) do
slot9 = nil
if (slot3 and slot3.id == slot7 and slot3 or slot0:fetchShipVO(slot7)) and slot9:getTeamType() ~= slot2 then
slot1[slot7] = slot8
end
end
slot0:updateRawShips(slot1)
end
function slot0.updateShipHp(slot0, slot1, slot2)
if slot0.friendAssistShip and slot0.friendAssistShip.id == slot1 then
slot0.friendAssistShip.hpRant = slot2
elseif slot0.ships[slot1] then
slot0.ships[slot1].hp_rant = slot2
end
slot0.fleet:updateShipHp(slot1, slot2)
end
function slot0.isValid(slot0)
return _.any(slot0:getShips(true), function (slot0)
return slot0:getTeamType() == TeamType.Main and slot0.hpRant > 0
end) and _.any(slot1, function (slot0)
return slot0:getTeamType() == TeamType.Vanguard and slot0.hpRant > 0
end)
end
function slot0.updateFleetShips(slot0, slot1)
slot2 = {}
for slot6, slot7 in ipairs(slot1) do
if slot0.friendAssistShip and slot0.friendAssistShip.id == slot7 then
table.insert(slot2, {
id = slot7,
hp_rant = slot0.friendAssistShip.hpRant,
strategies = Clone(slot0.friendAssistShip.strategies)
})
elseif slot0.ships[slot7] then
table.insert(slot2, {
id = slot7,
hp_rant = slot0.ships[slot7].hp_rant,
strategies = Clone(slot0.ships[slot7].strategies)
})
end
end
slot0.fleet:updateShips(slot2)
end
function slot0.updateShipStg(slot0, slot1, slot2, slot3)
slot4 = {}
if slot0.friendAssistShip and slot0.friendAssistShip.id == slot1 then
slot4 = slot0.friendAssistShip.strategies
elseif slot0.ships[slot1] then
slot4 = slot5.strategies
end
_.each(slot4, function (slot0)
if slot0.id == uv0 then
slot0.count = uv1
end
end)
slot0.fleet:updateShipStg(slot1, slot2, slot3)
end
function slot0.getFleetStgIds(slot0, slot1)
slot2 = {}
if slot1.stgId > 0 then
table.insert(slot2, slot1.stgId)
end
return slot2
end
function slot0.filterPower3(slot0)
function slot4(slot0)
table.sort(slot0, function (slot0, slot1)
return slot1:getShipCombatPower() < slot0:getShipCombatPower()
end)
_.each(slot0, function (slot0)
if not _.any(uv0, function (slot0)
return slot0:isSameKind(uv0)
end) then
table.insert(uv0, slot0)
end
end)
_({}):chain():slice(1, 3):each(function (slot0)
table.insert(uv0, slot0.id)
end)
end
slot4(slot0:getShipsByTeam(TeamType.Vanguard))
slot4(slot0:getShipsByTeam(TeamType.Main))
return {}
end
function slot0.isOpen(slot0)
slot1 = false
if ChapterConst.ActivateMirror then
slot1 = getProxy(ActivityProxy):getActivityByType(ActivityConst.ACTIVITY_TYPE_MIRROR) and not slot3:isEnd()
elseif pg.sim_battle_template[slot0.simId] and pg.TimeMgr.GetInstance():STimeDescS(pg.TimeMgr.GetInstance():GetServerTime(), "*t").month == slot0.simId then
slot1 = slot2.sim_time[1] <= slot4.day and slot4.day <= slot2.sim_time[2]
end
return slot1
end
function slot0.isFirstDay(slot0)
slot1 = false
slot2 = pg.TimeMgr.GetInstance()
slot4 = pg.TimeMgr.GetInstance():STimeDescS(slot2:GetServerTime(), "*t")
if ChapterConst.ActivateMirror then
if getProxy(ActivityProxy):getActivityByType(ActivityConst.ACTIVITY_TYPE_MIRROR) and not slot6:isEnd() and slot6:getConfig("time")[2] then
slot1 = slot2:DiffDay(slot2:parseTimeFromConfig(slot7[2], true), slot2:GetServerTime()) == 0
end
elseif pg.sim_battle_template[slot0.simId] then
slot1 = slot4.day == slot5.sim_time[1]
end
return slot1
end
function slot0.getRestDays(slot0)
slot1 = 0
slot2 = pg.TimeMgr.GetInstance()
slot4 = pg.TimeMgr.GetInstance():STimeDescS(slot2:GetServerTime(), "*t")
if ChapterConst.ActivateMirror then
if getProxy(ActivityProxy):getActivityByType(ActivityConst.ACTIVITY_TYPE_MIRROR) and not slot6:isEnd() and slot6:getConfig("time")[1] == "timer" and slot7[3] then
slot1 = slot2:DiffDay(slot2:GetServerTime(), slot2:parseTimeFromConfig(slot7[3]))
end
elseif pg.sim_battle_template[slot0.simId] then
slot1 = slot5.sim_time[2] - slot4.day + 1
end
return math.max(slot1, 1)
end
function slot0.localSaveChapter(slot0)
PlayerPrefs.SetString(uv0.SAVE_TAG .. getProxy(PlayerProxy):getRawData().id, table.concat(_.map(slot0:getShips(false), function (slot0)
return slot0.id
end), ":"))
PlayerPrefs.Save()
end
function slot0.localLoadChapter(slot0)
slot4 = 0
slot5 = ChapterConst.ShamShipLimit
slot6 = {
[TeamType.Vanguard] = 0,
[TeamType.Main] = 0
}
slot7 = ChapterConst.ShamTeamShipLimit
slot8 = getProxy(BayProxy)
_.each(string.split(PlayerPrefs.GetString(uv0.SAVE_TAG .. getProxy(PlayerProxy):getRawData().id) or "", ":"), function (slot0)
if uv0:getShipById(tonumber(slot0)) then
slot3 = slot2:getTeamType()
if uv1 < uv2 and uv3[slot3] < uv4 then
uv1 = uv1 + 1
uv3[slot3] = uv3[slot3] + 1
uv5[slot1] = {
hp_rant = 10000,
id = slot1,
strategies = {}
}
end
end
end)
slot0:updateRawShips({})
end
function slot0.writeBack(slot0, slot1, slot2)
for slot8, slot9 in pairs(slot0.fleet.ships) do
function (slot0)
if uv0.statistics[slot0.id] then
uv1:updateShipHp(slot0.id, slot1.bp)
end
end(slot9)
end
if slot1 then
slot0:getChapterCell(slot3.line.row, slot3.line.column).flag = 1
slot0.progress = slot0.progress + 1
else
slot6 = slot5.rival
function slot7(slot0)
if uv0.statistics._rivalInfo[slot0.id] then
slot0.hpRant = slot1.bp
end
end
_.each(slot6.mainShips, function (slot0)
uv0(slot0)
end)
_.each(slot6.vanguardShips, function (slot0)
uv0(slot0)
end)
end
slot0:updateChapterCell(slot5)
end
return slot0
| 1 | 0.503045 | 1 | 0.503045 | game-dev | MEDIA | 0.843661 | game-dev | 0.89183 | 1 | 0.89183 |
nexquery/samp-textdraw-editor | 40,840 | pawno/include/YSI_Players/y_groups/y_groups__funcs.inc | /*
Legal:
Version: MPL 1.1
The contents of this file are subject to the Mozilla Public License Version
1.1 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.mozilla.org/MPL/
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
for the specific language governing rights and limitations under the
License.
The Original Code is the YSI framework.
The Initial Developer of the Original Code is Alex "Y_Less" Cole.
Portions created by the Initial Developer are Copyright C 2011
the Initial Developer. All Rights Reserved.
Contributors:
Y_Less
koolk
JoeBullet/Google63
g_aSlice/Slice
Misiur
samphunter
tianmeta
maddinat0r
spacemud
Crayder
Dayvison
Ahmad45123
Zeex
irinel1996
Yiin-
Chaprnks
Konstantinos
Masterchen09
Southclaws
PatchwerkQWER
m0k1
paulommu
udan111
Cheaterman
Thanks:
JoeBullet/Google63 - Handy arbitrary ASM jump code using SCTRL.
ZeeX - Very productive conversations.
koolk - IsPlayerinAreaEx code.
TheAlpha - Danish translation.
breadfish - German translation.
Fireburn - Dutch translation.
yom - French translation.
50p - Polish translation.
Zamaroht - Spanish translation.
Los - Portuguese translation.
Dracoblue, sintax, mabako, Xtreme, other coders - Producing other modes for
me to strive to better.
Pixels^ - Running XScripters where the idea was born.
Matite - Pestering me to release it and using it.
Very special thanks to:
Thiadmer - PAWN, whose limits continue to amaze me!
Kye/Kalcor - SA:MP.
SA:MP Team past, present and future - SA:MP.
Optional plugins:
Gamer_Z - GPS.
Incognito - Streamer.
Me - sscanf2, fixes2, Whirlpool.
*/
/*
ad88888ba
d8" "8b ,d
Y8, 88
`Y8aaaaa, ,adPPYba, MM88MMM 88 88 8b,dPPYba,
`"""""8b, a8P_____88 88 88 88 88P' "8a
`8b 8PP""""""" 88 88 88 88 d8
Y8a a8P "8b, ,aa 88, "8a, ,a88 88b, ,a8"
"Y88888P" `"Ybbd8"' "Y888 `"YbbdP'Y8 88`YbbdP"'
88
88
*/
#if defined _inc_y_groups__funcs
#undef _inc_y_groups__funcs
#endif
//#if !defined _INC_y_groups__funcs
// #define _INC_y_groups__funcs
// #include "..\..\YSI_Core\y_utils"
// #include "..\..\YSI_Data\y_bit"
// #include "y_groups_setup"
// #include "..\..\YSI_Data\y_iterate"
//#endif
//#if !defined _GROUP_MAKE_TAG
// #define _GROUP_MAKE_TAG _
//#endif
// Start of the multi-use file.
static stock
YSI_g_sMaxEncountered = -1,
BitArray:YSI_g_sElementAllowed[_GROUP_MAKE_LIMIT]<_:_MAX_GROUPS_G>,
BitArray:YSI_g_sElementDenied[_GROUP_MAKE_LIMIT]<_:_MAX_GROUPS_G>,
BitArray:YSI_g_sDefaultAllowed<_:_MAX_GROUPS_G>,
BitArray:YSI_g_sDefaultDenied<_:_MAX_GROUPS_G>,
BitArray:YSI_g_sEmpty<_:_MAX_GROUPS_G>,
_yGI = 0,
_yGU = 0,
_yGA = 0;
//// Define the callback chaining for the current
//#if defined _YSI_HAS_y_groups
// #define GFOREIGN__%1(%2); _GROUP_MAKE_NAME<FOREIGN__%1>(%2);
// #define GGLOBAL__%1(%2) _GROUP_MAKE_NAME<GLOBAL__%1>(%2)
// #define GPUBLIC__ MASTER_FUNC__
#if YSIM_HAS_MASTER
#if _YSIM_IS_CLIENT
#define GCHAIN__%0(%2) static stock _GROUP_MAKE_NAME<%0...>(%2)
#elseif _YSIM_IS_SERVER
#define GCHAIN__%0(%2) _GROUP_MAKE_NAME<%0...>(%2);public _GROUP_MAKE_NAME<%0...>(%2)for(J@=1;J@;GROUP_CHAIN?<%0>(%2))
#elseif _YSIM_IS_STUB
#define GCHAIN__%0(%2) static stock _GROUP_MAKE_NAME<%0...>(%2)
#else
#define GCHAIN__%0(%2) _GROUP_MAKE_NAME<%0...>(%2);public _GROUP_MAKE_NAME<%0...>(%2)<>GROUP_CHAIN?<%0>(%2);public _GROUP_MAKE_NAME<%0...>(%2)<_YCM:y>for(J@=1;J@;GROUP_CHAIN?<%0>(%2))
#endif
#else
#define GCHAIN__%0(%2) _GROUP_MAKE_NAME<%0...>(%2);public _GROUP_MAKE_NAME<%0...>(%2)for(J@=1;J@;GROUP_CHAIN?<%0>(%2))
#endif
//#elseif __COMPILER_1ST_PASS
// #define GFOREIGN__%0...%1(%2) _GROUP_MAKE_FUNC<@@>:_GROUP_MAKE_NAME<%0...>(%2);_GROUP_MAKE_NAME<%0...%1>(%2)
// #define GGLOBAL__%0...%1(%2) static stock _GROUP_MAKE_NAME<%0...%1>(%2)
// #define GPUBLIC__%0(%2) _GROUP_MAKE_FUNC<@@>:_GROUP_MAKE_NAME<%0...>(%2);_GROUP_MAKE_NAME<%0...>(%2);static stock _GROUP_MAKE_NAME<%0...>(%2)
// #define GCHAIN__%0(%2) _GROUP_MAKE_FUNC<@@>:_GROUP_MAKE_NAME<%0...>(%2);_GROUP_MAKE_NAME<%0...>(%2);static stock _GROUP_MAKE_NAME<%0...>(%2)
// #define _GROUP_SET_PLAYER(%0) P:E(#_GROUP_MAKE_NAME<..._SetPlayer> " called without y_groups")
//#else
// #define GGLOBAL__%0...%1(%2) static stock _GROUP_MAKE_NAME<%0...%1>(%2)
// #define GPUBLIC__%0(%2) static stock _GROUP_MAKE_NAME<%0...>(%2)
// #define GCHAIN__%0(%2) static stock _GROUP_MAKE_NAME<%0...>(%2)
// #define _GROUP_SET_PLAYER(%0) P:E(#_GROUP_MAKE_NAME<..._SetPlayer> " called without y_groups")
//#endif
//#if YSI_KEYWORD(gforeign)
// #define gforeign GFOREIGN__
//#endif
//#if YSI_KEYWORD(gglobal)
// #define gglobal GGLOBAL__
//#endif
//#if YSI_KEYWORD(gpublic)
// #define gpublic GPUBLIC__
//#endif
//#if YSI_KEYWORD(_gchain)
// #define _gchain GCHAIN__
//#endif
/*-------------------------------------------------------------------------*//**
* <param name="x">The element that was added (maybe).</param>
* <remarks>
* This is called when a new element is created, and as such it is NOT chained
* to other parts of the groups system because each part handles one type of
* element. Loop through all players and set up the element for them if they
* are in a group that this is also in by default.
*
* If x is "_GROUP_MAKE_LIMIT" then this is the test used in OnPlayerConnect in
* various libraries to see if the groups system exists, and if not locally
* initialise the player instead of leaving it up to this system.
* </remarks>
*//*------------------------------------------------------------------------**/
stock _GROUP_MAKE_NAME<..._InitialiseFromGroups>(_GROUP_MAKE_TAG:x = _GROUP_MAKE_TAG:_GROUP_MAKE_LIMIT)
{
P:4(#_GROUP_MAKE_NAME<..._InitialiseFromGroups> " called: %i", x);
// A new item has been added to the system - update all players according to
// the default settings for a group.
if (x != _GROUP_MAKE_TAG:_GROUP_MAKE_LIMIT)
{
YSI_g_sElementAllowed[_:x] = YSI_g_sDefaultAllowed,
YSI_g_sElementDenied[_:x] = YSI_g_sDefaultDenied,
YSI_g_sMaxEncountered = max(YSI_g_sMaxEncountered, _:x);
FOREACH__ (new playerid : Player)
{
Group_FullPlayerUpdate(playerid, _:x, YSI_g_sEmpty, YSI_g_sDefaultAllowed, YSI_g_sEmpty, YSI_g_sDefaultDenied, YSI_gGroupPlayers[playerid]);
}
}
return 0;
}
/*
ad88888ba 88 88
d8" "8b "" 88
Y8, 88
`Y8aaaaa, 88 8b,dPPYba, ,adPPYb,d8 88 ,adPPYba,
`"""""8b, 88 88P' `"8a a8" `Y88 88 a8P_____88
`8b 88 88 88 8b 88 88 8PP"""""""
Y8a a8P 88 88 88 "8a, ,d88 88 "8b, ,aa
"Y88888P" 88 88 88 `"YbbdP"Y8 88 `"Ybbd8"'
aa, ,88
"Y8bbdP"
*/
/*-------------------------------------------------------------------------*//**
* <summary>Group_Set...</summary>
* <param name="g">Group to set for.</param>
* <param name="el">Element to set.</param>
* <param name="s">Set or unset?</param>
* <remarks>
* If "s" is true, then one element is added to the current group. False it is
* removed.
* </remarks>
*//*------------------------------------------------------------------------**/
GFOREIGN__ Group_Set...(Group:g,_GROUP_MAKE_TAG:el,E_GROUP_SET:s);
GGLOBAL__ Group_Set...(Group:g,_GROUP_MAKE_TAG:el,E_GROUP_SET:s)
{
P:2(#_GROUP_MAKE_NAME<Group_Set...> " called: %i, %i, %i", _:g, _:el, _:s);
// Set wether a group can use this item.
if (0 <= _:el < _GROUP_MAKE_LIMIT && g <= GROUP_GLOBAL)
{
// There is now NO validity check for reasons of distruibution.
GROUP_FIX(g);
new
slot = Bit_Slot(g),
Bit:mask = Bit_Mask(g),
Bit:neg = ~mask;
P:5(#_GROUP_MAKE_NAME<Group_Set...> ": %i, %i", _:slot, _:mask);
YSI_gTempAllowed_ = YSI_g_sElementAllowed[_:el];
YSI_gTempDenied_ = YSI_g_sElementDenied[_:el];
if (s == E_GROUP_SET:ALLOW)
{
// Is this element allowed in the current group?
if ((YSI_gTempAllowed_[slot] & mask) && !(YSI_gTempDenied_[slot] & mask))
{
// No point adding an element to a group that it is already in.
return 1;
}
YSI_gTempAllowed_[slot] |= mask;
YSI_gTempDenied_[slot] &= neg;
}
else if (s == E_GROUP_SET:DENY)
{
// Is this element denied in the current group?
if ((YSI_gTempDenied_[slot] & mask))
{
// No point banning an element from a group that it is already in.
YSI_g_sElementAllowed[_:el][slot] &= neg;
return 1;
}
YSI_gTempAllowed_[slot] &= neg;
YSI_gTempDenied_[slot] |= mask;
}
else
{
// Is this element NOT in the current group?
if (!(YSI_gTempAllowed_[slot] & mask) && !(YSI_gTempDenied_[slot] & mask))
{
return 1;
}
YSI_gTempAllowed_[slot] &= ~mask;
YSI_gTempDenied_[slot] &= ~mask;
}
FOREACH__ (new playerid : Player)
{
if (YSI_gGroupPlayers[playerid][slot] & mask)
{
// The player is in the group in question, so they need a full
// update.
Group_FullPlayerUpdate(playerid, _:el, YSI_g_sElementAllowed[_:el], YSI_gTempAllowed_, YSI_g_sElementDenied[_:el], YSI_gTempDenied_, YSI_gGroupPlayers[playerid]);
}
}
YSI_g_sElementAllowed[_:el] = YSI_gTempAllowed_;
YSI_g_sElementDenied[_:el] = YSI_gTempDenied_;
return 1;
}
return 0;
}
/*-------------------------------------------------------------------------*//**
* <summary>Group_...Allowed</summary>
* <param name="g">Group to get from.</param>
* <param name="el">Element to get.</param>
* <returns>
* bool: Does the group have the element explicitly allowed?
* </returns>
*//*------------------------------------------------------------------------**/
GFOREIGN__ bool:Group_...Allowed(Group:g,_GROUP_MAKE_TAG:el);
GGLOBAL__ bool:Group_...Allowed(Group:g,_GROUP_MAKE_TAG:el)
{
P:2(#_GROUP_MAKE_NAME<Group_Get...> " called: %i, %i", _:g, _:el);
return (0 <= _:el < _GROUP_MAKE_LIMIT && g <= GROUP_GLOBAL && !Bit_Get(YSI_g_sElementDenied[_:el], _:GROUP_TEMP_FIX(g)) && Bit_Get(YSI_g_sElementAllowed[_:el], _:GROUP_TEMP_FIX(g)));
}
/*-------------------------------------------------------------------------*//**
* <summary>Group_...Denied</summary>
* <param name="g">Group to get from.</param>
* <param name="el">Element to get.</param>
* <returns>
* bool: Does the group have the element explicitly denied?
* </returns>
*//*------------------------------------------------------------------------**/
GFOREIGN__ bool:Group_...Denied(Group:g,_GROUP_MAKE_TAG:el);
GGLOBAL__ bool:Group_...Denied(Group:g,_GROUP_MAKE_TAG:el)
{
P:2(#_GROUP_MAKE_NAME<Group_Get...> " called: %i, %i", _:g, _:el);
return (0 <= _:el < _GROUP_MAKE_LIMIT && g <= GROUP_GLOBAL && Bit_Get(YSI_g_sElementDenied[_:el], _:GROUP_TEMP_FIX(g)));
}
#pragma deprecated Use `Group_...Allowed` or `Group_...Denied`.
stock E_GROUP_SET:_GROUP_MAKE_NAME<Group_Get...>(Group:g,_GROUP_MAKE_TAG:el)
{
// This returns truthy for both allowed and denied. The function is
// deprecated, so this is probably OK, because only people with legacy code
// (thus not using denials) will be calling this function.
P:2(#_GROUP_MAKE_NAME<Group_Get...> " called: %i, %i", _:g, _:el);
return
_GROUP_MAKE_NAME<Group_...Denied>(g, el) ? E_GROUP_SET:DENY :
_GROUP_MAKE_NAME<Group_...Allowed>(g, el) ? E_GROUP_SET:ALLOW :
E_GROUP_SET:UNDEF;
}
/*-------------------------------------------------------------------------*//**
* <summary>Group_Set...Default</summary>
* <param name="g">Group to set for.</param>
* <param name="s">Set or unset?</param>
* <remarks>
* If "s" is true, then all elements are added to this group (i.e. the default
* is set to true and all previous settings are wiped out). If it is false
* then all elements are removed and a full update is done.
* </remarks>
*//*------------------------------------------------------------------------**/
GFOREIGN__ Group_Set...Default(Group:g,E_GROUP_SET:s);
GGLOBAL__ Group_Set...Default(Group:g,E_GROUP_SET:s)
{
P:2(#_GROUP_MAKE_NAME<Group_Set...Default> " called: %i, %i", _:g, _:s);
if (g <= GROUP_GLOBAL)
{
// There is now NO validity check for reasons of distruibution.
GROUP_FIX(g);
new
slot = Bit_Slot(g),
Bit:mask = Bit_Mask(g),
Bit:inv = ~mask,
Iterator:GP<MAX_PLAYERS>;
FOREACH__ (new playerid : Player)
{
// Do this check here so it is only done once per player. This is a
// good argument for moving iterators to be duplicated in every
// script; however, the default "Group()" iterator implementation is
// a function, not a standard iterator - actually it now isn't...
if (YSI_gGroupPlayers[playerid][slot] & mask)
{
// Make a fast local iterator of all the players.
Iter_Add(GP, playerid);
}
}
if (s == E_GROUP_SET:ALLOW)
{
P:5(#_GROUP_MAKE_NAME<Group_Set...Default> ": ALLOW");
YSI_g_sDefaultAllowed[slot] |= mask;
YSI_g_sDefaultDenied[slot] &= inv;
for (new el = 0; el <= YSI_g_sMaxEncountered; ++el)
{
// Check if this group already has this element.
YSI_gTempAllowed_ = YSI_g_sElementAllowed[el];
YSI_gTempDenied_ = YSI_g_sElementDenied[el];
P:7(#_GROUP_MAKE_NAME<Group_Set...Default> ": element %d %d %d", _:el, YSI_gTempAllowed_[slot] & mask, YSI_gTempDenied_[slot] & mask);
if ((YSI_gTempAllowed_[slot] & mask) && !(YSI_gTempDenied_[slot] & mask))
{
// Could already be seen, thus no change.
continue;
}
YSI_gTempAllowed_[slot] |= mask;
YSI_gTempDenied_[slot] &= inv;
// Is this element NOT in the current group?
FOREACH__ (new playerid : GP)
{
Group_FullPlayerUpdate(playerid, el, YSI_g_sElementAllowed[el], YSI_gTempAllowed_, YSI_g_sElementDenied[el], YSI_gTempDenied_, YSI_gGroupPlayers[playerid]);
}
YSI_g_sElementAllowed[el][slot] |= mask;
YSI_g_sElementDenied[el][slot] &= inv;
}
}
else if (s == E_GROUP_SET:DENY)
{
P:5(#_GROUP_MAKE_NAME<Group_Set...Default> ": DENY");
YSI_g_sDefaultAllowed[slot] &= inv;
YSI_g_sDefaultDenied[slot] |= mask;
for (new el = 0; el <= YSI_g_sMaxEncountered; ++el)
{
YSI_gTempDenied_ = YSI_g_sElementDenied[el];
P:7(#_GROUP_MAKE_NAME<Group_Set...Default> ": element %d %d %d", _:el, YSI_g_sElementAllowed[el][slot] & mask, YSI_gTempDenied_[slot] & mask);
if (YSI_gTempDenied_[slot] & mask)
{
// Already denied. Doesn't matter what the old `Allowed`
// state was because denials override them
Bit_Vet(YSI_g_sElementAllowed[el], _:g);
continue;
}
// Is this element NOT in the current group?
YSI_gTempDenied_[slot] |= mask;
FOREACH__ (new playerid : GP)
{
// `YSI_gTempAllowed_` IS NEVER SET. We don't need it at
// all in `Group_FullPlayerUpdate` because we know that
// `YSI_gTempDenied_` has at least one bit set, and will
// therefore prevent the current state of allows being
// checked.
Group_FullPlayerUpdate(playerid, el, YSI_g_sElementAllowed[el], YSI_gTempAllowed_, YSI_g_sElementDenied[el], YSI_gTempDenied_, YSI_gGroupPlayers[playerid]);
}
YSI_g_sElementAllowed[el][slot] &= inv;
YSI_g_sElementDenied[el][slot] |= mask;
}
}
else
{
P:5(#_GROUP_MAKE_NAME<Group_Set...Default> ": UNDEF");
YSI_g_sDefaultAllowed[slot] &= inv;
YSI_g_sDefaultDenied[slot] &= inv;
for (new el = 0; el <= YSI_g_sMaxEncountered; ++el)
{
YSI_gTempAllowed_ = YSI_g_sElementAllowed[el];
YSI_gTempDenied_ = YSI_g_sElementDenied[el];
P:7(#_GROUP_MAKE_NAME<Group_Set...Default> ": element %d %d %d", _:el, YSI_gTempAllowed_[slot] & mask, YSI_gTempDenied_[slot] & mask);
if (!(YSI_gTempAllowed_[slot] & mask) && !(YSI_gTempDenied_[slot] & mask))
{
// Nothing has changed.
continue;
}
// Is this element in the current group?
YSI_gTempAllowed_[slot] &= inv;
YSI_gTempDenied_[slot] &= inv;
FOREACH__ (new playerid : GP)
{
Group_FullPlayerUpdate(playerid, el, YSI_g_sElementAllowed[el], YSI_gTempAllowed_, YSI_g_sElementDenied[el], YSI_gTempDenied_, YSI_gGroupPlayers[playerid]);
}
YSI_g_sElementAllowed[el][slot] &= inv;
YSI_g_sElementDenied[el][slot] &= inv;
}
}
return 1;
}
return 0;
}
/*-------------------------------------------------------------------------*//**
* <summary>Group_Set...New</summary>
* <param name="g">Group to set for.</param>
* <param name="s">Set or unset?</param>
* <remarks>
* Similar to "Group_Set...Default", but doesn't reset all existing elements,
* just sets the permissions for any future items.
* </remarks>
*//*------------------------------------------------------------------------**/
GFOREIGN__ Group_Set...New(Group:g,E_GROUP_SET:s);
GGLOBAL__ Group_Set...New(Group:g,E_GROUP_SET:s)
{
P:2(#_GROUP_MAKE_NAME<Group_Set...New> " called: %i, %i", _:g, _:s);
if (g <= GROUP_GLOBAL)
{
GROUP_FIX(g);
// There is now NO validity check for reasons of distruibution.
if (s == E_GROUP_SET:ALLOW)
{
Bit_Let(YSI_g_sDefaultAllowed, _:g);
Bit_Vet(YSI_g_sDefaultDenied, _:g);
}
else if (s == E_GROUP_SET:DENY)
{
Bit_Vet(YSI_g_sDefaultAllowed, _:g);
Bit_Let(YSI_g_sDefaultDenied, _:g);
}
else
{
Bit_Vet(YSI_g_sDefaultAllowed, _:g);
Bit_Vet(YSI_g_sDefaultDenied, _:g);
}
return 1;
}
return 0;
}
/*-------------------------------------------------------------------------*//**
* <summary>Group_Exclusive...</summary>
* <param name="g">Group to add this to.</param>
* <param name="el">Element to add.</param>
* <remarks>
* Add this element to ONLY this group and remove it from any others it might
* already be in. This is basically a simplified version of "GROUP_ADD".
* </remarks>
*//*------------------------------------------------------------------------**/
GFOREIGN__ Group_Exclusive...(Group:g, _GROUP_MAKE_TAG:el);
GGLOBAL__ Group_Exclusive...(Group:g, _GROUP_MAKE_TAG:el)
{
if (g <= GROUP_GLOBAL)
{
GROUP_FIX(g);
YSI_gTempAllowed_ = YSI_g_sDefaultAllowed;
YSI_g_sDefaultAllowed = YSI_g_cEmptyGroups;
Bit_Let(YSI_g_sDefaultAllowed, _:g);
for (new i = 0; i != bits<_MAX_GROUPS_G>; ++i)
{
YSI_g_sEmpty[i] = ~YSI_g_sDefaultAllowed[i];
}
_GROUP_MAKE_NAME<..._InitialiseFromGroups>(el);
YSI_g_sDefaultAllowed = YSI_gTempAllowed_;
YSI_g_sEmpty = YSI_g_cEmptyGroups;
return 1;
}
return 0;
}
/*-------------------------------------------------------------------------*//**
* <summary>Iter_Func@Group_...</summary>
* <param name="g">Group to iterate over.</param>
* <remarks>
* Iterate over all the items in this group.
* </remarks>
*//*------------------------------------------------------------------------**/
GFOREIGN__ Iter_Func@Group_...(start, Group:g);
GGLOBAL__ Iter_Func@Group_...(start, Group:g)
{
P:3("Iter_Func@Group_... called: %i, %i", start, _:g);
if (g <= GROUP_GLOBAL)
{
GROUP_FIX(g);
new
Bit:mask = Bit_Mask(_:g),
slot = Bit_Slot(_:g);
while (++start != _GROUP_MAKE_LIMIT)
{
if (YSI_g_sElementAllowed[start][slot] & mask)
{
return start;
}
}
}
return -1;
}
stock const
F@z:_GROUP_MAKE_NAME<Iterator@Group_...> = F@z:0,
_GROUP_MAKE_NAME<iterstart@Group_...> = -1;
/*
,ad8888ba, 88 88 88
d8"' `"8b 88 88 88
d8' 88 88 88
88 88 ,adPPYba, 88,dPPYba, ,adPPYYba, 88
88 88888 88 a8" "8a 88P' "8a "" `Y8 88
Y8, 88 88 8b d8 88 d8 ,adPPPPP88 88
Y8a. .a88 88 "8a, ,a8" 88b, ,a8" 88, ,88 88
`"Y88888P" 88 `"YbbdP"' 8Y"Ybbd8"' `"8bbdP"Y8 88
*/
/*-------------------------------------------------------------------------*//**
* <summary>Group_SetGlobal...</summary>
* <param name="el">Element to set.</param>
* <param name="s">Set or unset?</param>
* <remarks>
* If "s" is true, then one element is added to the global group. False it is
* removed.
* </remarks>
*//*------------------------------------------------------------------------**/
GFOREIGN__ Group_SetGlobal...(_GROUP_MAKE_TAG:el,E_GROUP_SET:s);
GGLOBAL__ Group_SetGlobal...(_GROUP_MAKE_TAG:el,E_GROUP_SET:s)
{
P:2(#_GROUP_MAKE_NAME<Group_SetGlobal...> " called: %i, %i", _:el, _:s);
return _GROUP_MAKE_NAME<Group_Set...>(GROUP_GLOBAL, el, s);
}
/*-------------------------------------------------------------------------*//**
* <summary>Group_Global...Allowed</summary>
* <param name="g">Group to get from.</param>
* <param name="el">Element to get.</param>
* <returns>
* bool: Does the group have the element explicitly allowed?
* </returns>
*//*------------------------------------------------------------------------**/
stock bool:_GROUP_MAKE_NAME<Group_Global...Allowed>(_GROUP_MAKE_TAG:el)
{
P:2(#_GROUP_MAKE_NAME<Group_Global...Allowed> " called: %i", _:el);
return _GROUP_MAKE_NAME<Group_...Allowed>(GROUP_GLOBAL, el);
}
/*-------------------------------------------------------------------------*//**
* <summary>Group_Global...Denied</summary>
* <param name="g">Group to get from.</param>
* <param name="el">Element to get.</param>
* <returns>
* bool: Does the group have the element explicitly denied?
* </returns>
*//*------------------------------------------------------------------------**/
stock bool:_GROUP_MAKE_NAME<Group_Global...Denied>(_GROUP_MAKE_TAG:el)
{
P:2(#_GROUP_MAKE_NAME<Group_Global...Denied> " called: %i", _:el);
return _GROUP_MAKE_NAME<Group_...Denied>(GROUP_GLOBAL, el);
}
/*-------------------------------------------------------------------------*//**
* <summary>Group_GetGlobal...</summary>
* <param name="el">Element to get.</param>
* <returns>
* bool: Does the global group have the element?
* </returns>
*//*------------------------------------------------------------------------**/
#pragma deprecated Use `Group_Global...Allowed` or `Group_Global...Denied`.
stock E_GROUP_SET:_GROUP_MAKE_NAME<Group_GetGlobal...>(_GROUP_MAKE_TAG:el)
{
// This returns truthy for both allowed and denied. The function is
// deprecated, so this is probably OK, because only people with legacy code
// (thus not using denials) will be calling this function.
P:2(#_GROUP_MAKE_NAME<Group_GetGlobal...> " called: %i", _:el);
return
_GROUP_MAKE_NAME<Group_...Denied>(GROUP_GLOBAL, el) ? E_GROUP_SET:DENY :
_GROUP_MAKE_NAME<Group_...Allowed>(GROUP_GLOBAL, el) ? E_GROUP_SET:ALLOW :
E_GROUP_SET:UNDEF;
}
/*-------------------------------------------------------------------------*//**
* <summary>Group_SetGlobal...Default</summary>
* <param name="s">Set or unset?</param>
* <remarks>
* If "s" is true, then all elements are added to the global group (i.e. the
* default is set to true and all previous settings are wiped out). If it is
* false then all elements are removed and a full update is done.
* </remarks>
*//*------------------------------------------------------------------------**/
GFOREIGN__ Group_SetGlobal...Default(E_GROUP_SET:s);
GGLOBAL__ Group_SetGlobal...Default(E_GROUP_SET:s)
{
P:2(#_GROUP_MAKE_NAME<Group_SetGlobal...Default> " called: %i", _:s);
return _GROUP_MAKE_NAME<Group_Set...Default>(GROUP_GLOBAL, s);
}
/*-------------------------------------------------------------------------*//**
* <summary>Group_SetGlobal...New</summary>
* <param name="s">Set or unset?</param>
* <remarks>
* All elements created FROM THIS POINT ON will have this default setting.
* </remarks>
*//*------------------------------------------------------------------------**/
GFOREIGN__ Group_SetGlobal...New(E_GROUP_SET:s);
GGLOBAL__ Group_SetGlobal...New(E_GROUP_SET:s)
{
P:2(#_GROUP_MAKE_NAME<Group_SetGlobal...New> " called: %i", _:s);
return _GROUP_MAKE_NAME<Group_Set...New>(GROUP_GLOBAL, s);
}
/*-------------------------------------------------------------------------*//**
* <summary>Group_GlobalExclusive...</summary>
* <param name="el">Element to add.</param>
* <remarks>
* Add this element to ONLY the global group and remove it from any others it
* might already be in.
* </remarks>
*//*------------------------------------------------------------------------**/
GFOREIGN__ Group_GlobalExclusive...(_GROUP_MAKE_TAG:el);
GGLOBAL__ Group_GlobalExclusive...(_GROUP_MAKE_TAG:el)
{
P:2(#_GROUP_MAKE_NAME<Group_GlobalExclusive...> " called: %i", el);
return _GROUP_MAKE_NAME<Group_Exclusive...>(GROUP_GLOBAL, el);
}
/*-------------------------------------------------------------------------*//**
* <summary>Iter_Func@Group_...</summary>
* <remarks>
* Iterate over all the items in this group.
* </remarks>
*//*------------------------------------------------------------------------**/
GFOREIGN__ Iter_Func@Group_Global...(start);
GGLOBAL__ Iter_Func@Group_Global...(start)
{
P:3("Iter_Func@Group_Global... called: %i", start);
new
Bit:mask = Bit_Mask(_:_MAX_GROUPS),
slot = Bit_Slot(_:_MAX_GROUPS);
while (++start != _GROUP_MAKE_LIMIT)
{
if (YSI_g_sElementAllowed[start][slot] & mask)
{
return start;
}
}
return -1;
}
stock const
F@z:_GROUP_MAKE_NAME<Iterator@Group_Global...> = F@z:0,
_GROUP_MAKE_NAME<iterstart@Group_Global...> = -1;
#if defined GROUP_LIBRARY_TAGS
stock Group:operator+(Group:g, GROUP_LIBRARY_TAGS:o)
{
_GROUP_MAKE_NAME<Group_Set...>(g, o, true);
return g;
}
stock Group:operator-(Group:g, GROUP_LIBRARY_TAGS:o)
{
_GROUP_MAKE_NAME<Group_Set...>(g, o, false);
return g;
}
stock Group:operator%(Group:g, GROUP_LIBRARY_TAGS:o)
{
_GROUP_MAKE_NAME<Group_Exclusive...>(g, o);
return g;
}
stock bool:operator==(Group:g, GROUP_LIBRARY_TAGS:o)
{
return _GROUP_MAKE_NAME<Group_Get...>(g, o);
}
stock bool:operator!=(Group:g, GROUP_LIBRARY_TAGS:o)
{
return !_GROUP_MAKE_NAME<Group_Get...>(g, o);
}
#endif
/*
88 88
88 ,d 88
88 88 88
88 8b,dPPYba, MM88MMM ,adPPYba, 8b,dPPYba, 8b,dPPYba, ,adPPYYba, 88
88 88P' `"8a 88 a8P_____88 88P' "Y8 88P' `"8a "" `Y8 88
88 88 88 88 8PP""""""" 88 88 88 ,adPPPPP88 88
88 88 88 88, "8b, ,aa 88 88 88 88, ,88 88
88 88 88 "Y888 `"Ybbd8"' 88 88 88 `"8bbdP"Y8 88
*/
static stock void:Group_Handoff(i,const a[],s)
{
s = min(s, bits<_:_MAX_GROUPS_G>);
if (i == cellmin)
{
memcpy(_:YSI_g_sDefaultAllowed, a, 0, s * 4);
}
else if (i == cellmax)
{
memcpy(_:YSI_g_sDefaultDenied, a, 0, s * 4);
}
else if (i < 0)
{
memcpy(_:YSI_g_sElementDenied[~i], a, 0, s * 4);
}
else
{
memcpy(_:YSI_g_sElementAllowed[i], a, 0, s * 4);
}
}
MASTER_FUNC__ MAKE_YCM<HANDOFF_SOURCE...Group>()<_YCM:p>
{
// Pass data to the new group controller.
Group_Handoff(cellmin, _:YSI_g_sDefaultAllowed, sizeof (YSI_g_sDefaultAllowed));
Group_Handoff(cellmax, _:YSI_g_sDefaultDenied, sizeof (YSI_g_sDefaultDenied));
for (new i = 0; i != sizeof (YSI_g_sElementAllowed); ++i)
{
Group_Handoff(i, _:YSI_g_sElementAllowed[i], sizeof (YSI_g_sElementAllowed[]));
Group_Handoff(~i, _:YSI_g_sElementDenied[i], sizeof (YSI_g_sElementDenied[]));
}
}
/*-------------------------------------------------------------------------*//**
* <param name="playerid">Player to check.</param>
* <param name="el">Element to show or hide.</param>
* <param name="previousAllowed">(p) The old allowed groups.</param>
* <param name="currentAllowed">(c) The new allowed groups.</param>
* <param name="previousDenied">(q) The old denied groups.</param>
* <param name="currentDenied">(d) The new denied groups.</param>
* <param name="reference">(r) What to compare changes to.</param>
* <remarks>
* I did have a good reason for calling this "FU", but I forgot it! Anyway,
* the state of some groups has changed - either a player's groups or an
* elements groups have changed. If the player could previously see the
* element but now can't, hide it. If the player previously couldn't see it
* but now can, show it. If there is no change do nothing. The old version of
* this library would just re-show the element even if they could already see
* it, but this was a bad design as it could incur large overheads in other
* libraries when they had to do IO to enable or disable something for a
* player.
*
* The change can be in either the player's groups or the element's groups,
* either way this code will work regardless.
* </remarks>
*//*------------------------------------------------------------------------**/
static stock Group_FullPlayerUpdate(playerid, el, const Bit:p[], const Bit:c[], const Bit:q[], const Bit:d[], const Bit:r[])
{
// "_GROUPS_CHECK" is a macro that expands to a massive unrolled "if"
// statement checking up to 512 groups at once. Any more than that and this
// code resorts to a loop instead. I say "at once"; it does 32 AT ONCE
// (as in truly in parallel), starting with the most likely match (the
// default group that every player and every element is usually in), and
// loops over all the groups in 32 group chunks. When I say "loop", this
// could be in the form of a huge "if" statement with every iteration put in
// explicitly.
// r = Reference (valid groups).
// c = Current (new groups).
// p = Previous (old groups).
#if _DEBUG >= 7
new debugA[] = "false", debugB[] = "false";
_GROUPS_CHECK_ANY(p,r)
debugA = "true";
_GROUPS_CHECK_ANY(c,r)
debugB = "true";
printf("Group_FullPlayerUpdate ("#_GROUP_MAKE_NAME<...>") called:\r\n\t%d, %d,\r\n\t%s,\r\n\t%s,\r\n\t%s,\r\n\t%s, %s",
playerid, el, Bit_Display(p, bits<_MAX_GROUPS_G>), Bit_Display(c, bits<_MAX_GROUPS_G>), Bit_Display(r, bits<_MAX_GROUPS_G>), debugA, debugB);
#endif
_GROUPS_CHECK_ANY(q,r)
{
// Were previously denied.
_GROUPS_CHECK_ANY(d,r)
{
// Still denied.
P:7("Group_FullPlayerUpdate: %d %d denied, still are", playerid, el);
return;
}
// They were previously denied, but now they aren't. Does that mean
// then can now see it?
_GROUPS_CHECK_ANY(c,r)
{
P:7("Group_FullPlayerUpdate: %d %d denied, now can", playerid, el);
_GROUP_MAKE_NAME<..._SetPlayer>(_GROUP_MAKE_TAG:el, playerid, true);
return;
}
P:7("Group_FullPlayerUpdate: %d %d denied, now not", playerid, el);
return;
}
// Were not previously denied. Are they now?
_GROUPS_CHECK_ANY(d,r)
{
_GROUPS_CHECK_ANY(p,r)
{
// Now denied.
P:7("Group_FullPlayerUpdate: %d %d allowed, now cant't", playerid, el);
_GROUP_MAKE_NAME<..._SetPlayer>(_GROUP_MAKE_TAG:el, playerid, false);
return;
}
P:7("Group_FullPlayerUpdate: %d %d allowed, now aren't", playerid, el);
return;
}
// No denies in force. Check normal allows.
_GROUPS_CHECK_ANY(p,r)
{
// Could previously see this thing. The thing about this design is that
// it can (best case) take just 2 comparisons to end - and that should
// be the common case!
_GROUPS_CHECK_ANY(c,r)
{
// Still can.
P:7("Group_FullPlayerUpdate: %d %d could, still can", playerid, el);
return;
}
// Now can't.
P:7("Group_FullPlayerUpdate: %d %d could, now can't", playerid, el);
_GROUP_MAKE_NAME<..._SetPlayer>(_GROUP_MAKE_TAG:el, playerid, false);
return;
}
// Couldn't see it before.
_GROUPS_CHECK_ANY(c,r)
{
P:7("Group_FullPlayerUpdate: %d %d now can", playerid, el);
// They have whatever this thing is. Note that this may be called
// MULTIPLE times for an element, without anything actually changing.
// I.e. this could be set to "true" repeatedly while never being set
// to "false".
_GROUP_MAKE_NAME<..._SetPlayer>(_GROUP_MAKE_TAG:el, playerid, true);
// We use "return" here because "_GROUPS_CHECK_ANY" MAY be a loop.
return;
}
P:7("Group_FullPlayerUpdate: %d %d can't", playerid, el);
}
/*
,ad8888ba, 88 88
d8"' `"8b 88 ""
d8' 88
88 88,dPPYba, ,adPPYYba, 88 8b,dPPYba, ,adPPYba,
88 88P' "8a "" `Y8 88 88P' `"8a I8[ ""
Y8, 88 88 ,adPPPPP88 88 88 88 `"Y8ba,
Y8a. .a8P 88 88 88, ,88 88 88 88 aa ]8I
`"Y8888Y"' 88 88 `"8bbdP"Y8 88 88 88 `"YbbdP"'
*/
/*-------------------------------------------------------------------------*//**
* <param name="ni">Next init function variable as returned by y_amx.</param>
* <param name="na">Next add function variable as returned by y_amx.</param>
* <param name="nu">Next update function variable as returned by y_amx.</param>
* <remarks>
* This function is called when the group system first starts up to initialise
* the global group and all the various function pointers. The way the
* "GCHAIN__" macro works means that the fact that "ni" etc are references is
* irrelevant; however, it does make the code LOOK much nicer and like
* assigning to the variables does have some wider meaning.
*
* If this is called with "ni = -1", it is special code to temporarily set or
* restore the defaults for use with the "GROUP_ADD" macro. So basically, it
* is poor design giving two distinct uses to a single function.
* </remarks>
*//*------------------------------------------------------------------------**/
GCHAIN__ _yGI(&ni, &na, &nu)
{
P:2(#_GROUP_MAKE_NAME<_yGI...> " called: %i, %i, %i", ni, na, nu);
if (ni == -1)
{
P:4(#_GROUP_MAKE_NAME<_yGI...> " INIT");
static
BitArray:sAllowed<_MAX_GROUPS_G>,
BitArray:sDenied<_MAX_GROUPS_G>;
if (na)
{
// Called to "push" the default settings.
sAllowed = YSI_g_sDefaultAllowed;
sDenied = YSI_g_sDefaultDenied;
YSI_g_sDefaultAllowed = YSI_g_cEmptyGroups;
YSI_g_sDefaultDenied = YSI_g_cEmptyGroups;
Bit_Let(YSI_g_sDefaultAllowed, nu);
for (new i = 0; i != bits<_MAX_GROUPS_G>; ++i)
{
YSI_g_sEmpty[i] = ~YSI_g_sDefaultAllowed[i];
}
}
else
{
// Called to "pop" the default settings.
YSI_g_sDefaultAllowed = sAllowed;
YSI_g_sDefaultDenied = sDenied;
YSI_g_sEmpty = YSI_g_cEmptyGroups;
}
}
else
{
P:4(#_GROUP_MAKE_NAME<_yGI...> " SETUP");
// Enable the default group. If I'm right, this way is actually better than
// using variables as in most cases because "_MAX_GROUPS" is a constant so
// all the other maths will be constant.
Bit_Let(YSI_g_sDefaultAllowed, _MAX_GROUPS);
// Set up the function chaining.
new
x = 0;
ni = AMX_GetPublicPointerPrefix(ni, x, _A<_yGI>);
_yGI = x;
na = AMX_GetPublicPointerPrefix(na, x, _A<_yGA>);
_yGA = x;
nu = AMX_GetPublicPointerPrefix(nu, x, _A<_yGU>);
_yGU = x;
}
}
/*-------------------------------------------------------------------------*//**
* <param name="group">The group that was just created.</param>
* <remarks>
* The given group was just created, loop over all elements and make sure they
* are NOT in this group - only the global group has a "default default" of
* true. We don't need to update any players with this as no-one will ever be
* in a brand new group.
* </remarks>
*//*------------------------------------------------------------------------**/
GCHAIN__ _yGA(&group)
{
P:4(#_GROUP_MAKE_NAME<_yGA...> " called: %i", _:group);
// Adding a new group is now a lot harder than it was before, but on the
// other hand, adding and using elements is vastly simpler so that's OK.
new
s = Bit_Slot(group),
Bit:m = ~Bit_Mask(group);
// Set the default "contains" for this group to false.
YSI_g_sDefaultAllowed[s] &= m;
YSI_g_sDefaultDenied[s] &= m;
// Disable every element in this group. DOESN'T use "YSI_g_sMaxEncountered"
// because we need to set up for the future too.
for (new i = 0; i != _GROUP_MAKE_LIMIT; ++i)
{
YSI_g_sElementAllowed[i][s] &= m;
YSI_g_sElementDenied[i][s] &= m;
}
}
/*-------------------------------------------------------------------------*//**
* <param name="pid">The player who joined or left groups.</param>
* <param name="p">Their previous groups.</param>
* <param name="c">Their new groups.</param>
* <remarks>
* The player "pid" just joined or left a group (or groups - can do multiple).
* Update their visibility accordingly. This function is ONLY called if there
* is a CHANGE - earlier functions confirm that they weren't already in (or
* not) this group(s) before the call.
* </remarks>
*//*------------------------------------------------------------------------**/
GCHAIN__ _yGU(&pid, Bit:p[], Bit:c[])
{
P:4(#_GROUP_MAKE_NAME<_yGU...> " called: %i, %s, %s", pid, Bit_Display(p, bits<_MAX_GROUPS_G>), Bit_Display(c, bits<_MAX_GROUPS_G>));
// This code loops over every "thing" controlled by this script. For every
// one it checks to see if the player can or can't see something that they
// previously could or couldn't see. If their ability to see it has
// changed then the `..._SetPlayer` function in the controlling library is
// called to do the actual internal function of updating their state.
for (new el = 0; el <= YSI_g_sMaxEncountered; ++el)
{
Group_PartPlayerUpdate(pid, el, p, c, YSI_g_sElementAllowed[el], YSI_g_sElementDenied[el]);
}
}
static stock Group_PartPlayerUpdate(playerid, el, const Bit:p[], const Bit:c[], const Bit:a[], const Bit:d[])
{
// p = Previous
// c = Current
// a = Allowed
// d = Denied
P:4("Group_PartPlayerUpdate called: %d %d\n %s\n %s\n %s\n %s", playerid, el, Bit_Display(p, bits<_MAX_GROUPS_G>), Bit_Display(c, bits<_MAX_GROUPS_G>), Bit_Display(a, bits<_MAX_GROUPS_G>), Bit_Display(d, bits<_MAX_GROUPS_G>));
_GROUPS_CHECK_ANY(p,d)
{
P:6("Group_PartPlayerUpdate: Previously Denied.");
// Any previous denials.
_GROUPS_CHECK_ANY(c,d)
{
P:6("Group_PartPlayerUpdate: Currently Denied.");
// No change there.
return;
}
_GROUPS_CHECK_ANY(c,a)
{
P:6("Group_PartPlayerUpdate: Currently Allowed.");
// Now allowed.
_GROUP_MAKE_NAME<..._SetPlayer>(_GROUP_MAKE_TAG:el, playerid, true);
return;
}
return;
}
_GROUPS_CHECK_ANY(c,d)
{
P:6("Group_PartPlayerUpdate: Currently Denied.");
_GROUPS_CHECK_ANY(p,a)
{
P:6("Group_PartPlayerUpdate: Previously Allowed.");
// Previously allowed, now denied.
_GROUP_MAKE_NAME<..._SetPlayer>(_GROUP_MAKE_TAG:el, playerid, false);
return;
}
P:6("Group_PartPlayerUpdate: Previously Nothing.");
return;
}
_GROUPS_CHECK_ANY(p,a)
{
P:6("Group_PartPlayerUpdate: Previously Allowed.");
_GROUPS_CHECK_ANY(c,a)
{
P:6("Group_PartPlayerUpdate: Currently Allowed.");
return;
}
P:6("Group_PartPlayerUpdate: Currently Nothing.");
// Were allowed, now aren't.
_GROUP_MAKE_NAME<..._SetPlayer>(_GROUP_MAKE_TAG:el, playerid, false);
return;
}
_GROUPS_CHECK_ANY(c,a)
{
P:6("Group_PartPlayerUpdate: Currently Allowed.");
// Currently allowed.
_GROUP_MAKE_NAME<..._SetPlayer>(_GROUP_MAKE_TAG:el, playerid, true);
return;
}
P:6("Group_PartPlayerUpdate: Currently Nothing.");
}
/*
,ad8888ba, 88
d8"' `"8b 88
d8' 88
88 88 ,adPPYba, ,adPPYYba, 8b,dPPYba, 88 88 8b,dPPYba,
88 88 a8P_____88 "" `Y8 88P' `"8a 88 88 88P' "8a
Y8, 88 8PP""""""" ,adPPPPP88 88 88 88 88 88 d8
Y8a. .a8P 88 "8b, ,aa 88, ,88 88 88 "8a, ,a88 88b, ,a8"
`"Y8888Y"' 88 `"Ybbd8"' `"8bbdP"Y8 88 88 `"YbbdP'Y8 88`YbbdP"'
88
88
*/
/*-------------------------------------------------------------------------*//**
* <remarks>
* Calls all functions to correctly include them in the AMX when required.
* Also all variables as it turns out they were a problem too.
* </remarks>
*//*------------------------------------------------------------------------**/
#undef GCHAIN__
#undef _GROUP_MAKE_NAME
#undef _GROUP_MAKE_LIMIT
#undef _GROUP_MAKE_TAG
| 1 | 0.873001 | 1 | 0.873001 | game-dev | MEDIA | 0.368746 | game-dev | 0.895714 | 1 | 0.895714 |
alibaba/jvm-sandbox-repeater | 26,620 | repeater-console/repeater-console-start/src/main/resources/static/plugins/ace-editor/mode-lsl.js | ace.define("ace/mode/lsl_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"],function(e,t,n){"use strict";function s(){var e=this.createKeywordMapper({"constant.language.float.lsl":"DEG_TO_RAD|PI|PI_BY_TWO|RAD_TO_DEG|SQRT2|TWO_PI","constant.language.integer.lsl":"ACTIVE|AGENT|AGENT_ALWAYS_RUN|AGENT_ATTACHMENTS|AGENT_AUTOPILOT|AGENT_AWAY|AGENT_BUSY|AGENT_BY_LEGACY_NAME|AGENT_BY_USERNAME|AGENT_CROUCHING|AGENT_FLYING|AGENT_IN_AIR|AGENT_LIST_PARCEL|AGENT_LIST_PARCEL_OWNER|AGENT_LIST_REGION|AGENT_MOUSELOOK|AGENT_ON_OBJECT|AGENT_SCRIPTED|AGENT_SITTING|AGENT_TYPING|AGENT_WALKING|ALL_SIDES|ANIM_ON|ATTACH_AVATAR_CENTER|ATTACH_BACK|ATTACH_BELLY|ATTACH_CHEST|ATTACH_CHIN|ATTACH_HEAD|ATTACH_HUD_BOTTOM|ATTACH_HUD_BOTTOM_LEFT|ATTACH_HUD_BOTTOM_RIGHT|ATTACH_HUD_CENTER_1|ATTACH_HUD_CENTER_2|ATTACH_HUD_TOP_CENTER|ATTACH_HUD_TOP_LEFT|ATTACH_HUD_TOP_RIGHT|ATTACH_LEAR|ATTACH_LEFT_PEC|ATTACH_LEYE|ATTACH_LFOOT|ATTACH_LHAND|ATTACH_LHIP|ATTACH_LLARM|ATTACH_LLLEG|ATTACH_LSHOULDER|ATTACH_LUARM|ATTACH_LULEG|ATTACH_MOUTH|ATTACH_NECK|ATTACH_NOSE|ATTACH_PELVIS|ATTACH_REAR|ATTACH_REYE|ATTACH_RFOOT|ATTACH_RHAND|ATTACH_RHIP|ATTACH_RIGHT_PEC|ATTACH_RLARM|ATTACH_RLLEG|ATTACH_RSHOULDER|ATTACH_RUARM|ATTACH_RULEG|AVOID_CHARACTERS|AVOID_DYNAMIC_OBSTACLES|AVOID_NONE|CAMERA_ACTIVE|CAMERA_BEHINDNESS_ANGLE|CAMERA_BEHINDNESS_LAG|CAMERA_DISTANCE|CAMERA_FOCUS|CAMERA_FOCUS_LAG|CAMERA_FOCUS_LOCKED|CAMERA_FOCUS_OFFSET|CAMERA_FOCUS_THRESHOLD|CAMERA_PITCH|CAMERA_POSITION|CAMERA_POSITION_LAG|CAMERA_POSITION_LOCKED|CAMERA_POSITION_THRESHOLD|CHANGED_ALLOWED_DROP|CHANGED_COLOR|CHANGED_INVENTORY|CHANGED_LINK|CHANGED_MEDIA|CHANGED_OWNER|CHANGED_REGION|CHANGED_REGION_START|CHANGED_SCALE|CHANGED_SHAPE|CHANGED_TELEPORT|CHANGED_TEXTURE|CHARACTER_ACCOUNT_FOR_SKIPPED_FRAMES|CHARACTER_AVOIDANCE_MODE|CHARACTER_CMD_JUMP|CHARACTER_CMD_SMOOTH_STOP|CHARACTER_CMD_STOP|CHARACTER_DESIRED_SPEED|CHARACTER_DESIRED_TURN_SPEED|CHARACTER_LENGTH|CHARACTER_MAX_ACCEL|CHARACTER_MAX_DECEL|CHARACTER_MAX_SPEED|CHARACTER_MAX_TURN_RADIUS|CHARACTER_ORIENTATION|CHARACTER_RADIUS|CHARACTER_STAY_WITHIN_PARCEL|CHARACTER_TYPE|CHARACTER_TYPE_A|CHARACTER_TYPE_B|CHARACTER_TYPE_C|CHARACTER_TYPE_D|CHARACTER_TYPE_NONE|CLICK_ACTION_BUY|CLICK_ACTION_NONE|CLICK_ACTION_OPEN|CLICK_ACTION_OPEN_MEDIA|CLICK_ACTION_PAY|CLICK_ACTION_PLAY|CLICK_ACTION_SIT|CLICK_ACTION_TOUCH|CONTENT_TYPE_ATOM|CONTENT_TYPE_FORM|CONTENT_TYPE_HTML|CONTENT_TYPE_JSON|CONTENT_TYPE_LLSD|CONTENT_TYPE_RSS|CONTENT_TYPE_TEXT|CONTENT_TYPE_XHTML|CONTENT_TYPE_XML|CONTROL_BACK|CONTROL_DOWN|CONTROL_FWD|CONTROL_LBUTTON|CONTROL_LEFT|CONTROL_ML_LBUTTON|CONTROL_RIGHT|CONTROL_ROT_LEFT|CONTROL_ROT_RIGHT|CONTROL_UP|DATA_BORN|DATA_NAME|DATA_ONLINE|DATA_PAYINFO|DATA_SIM_POS|DATA_SIM_RATING|DATA_SIM_STATUS|DEBUG_CHANNEL|DENSITY|ERR_GENERIC|ERR_MALFORMED_PARAMS|ERR_PARCEL_PERMISSIONS|ERR_RUNTIME_PERMISSIONS|ERR_THROTTLED|ESTATE_ACCESS_ALLOWED_AGENT_ADD|ESTATE_ACCESS_ALLOWED_AGENT_REMOVE|ESTATE_ACCESS_ALLOWED_GROUP_ADD|ESTATE_ACCESS_ALLOWED_GROUP_REMOVE|ESTATE_ACCESS_BANNED_AGENT_ADD|ESTATE_ACCESS_BANNED_AGENT_REMOVE|FALSE|FORCE_DIRECT_PATH|FRICTION|GCNP_RADIUS|GCNP_STATIC|GRAVITY_MULTIPLIER|HORIZONTAL|HTTP_BODY_MAXLENGTH|HTTP_BODY_TRUNCATED|HTTP_CUSTOM_HEADER|HTTP_METHOD|HTTP_MIMETYPE|HTTP_PRAGMA_NO_CACHE|HTTP_VERBOSE_THROTTLE|HTTP_VERIFY_CERT|INVENTORY_ALL|INVENTORY_ANIMATION|INVENTORY_BODYPART|INVENTORY_CLOTHING|INVENTORY_GESTURE|INVENTORY_LANDMARK|INVENTORY_NONE|INVENTORY_NOTECARD|INVENTORY_OBJECT|INVENTORY_SCRIPT|INVENTORY_SOUND|INVENTORY_TEXTURE|JSON_APPEND|KFM_CMD_PAUSE|KFM_CMD_PLAY|KFM_CMD_SET_MODE|KFM_CMD_STOP|KFM_COMMAND|KFM_DATA|KFM_FORWARD|KFM_LOOP|KFM_MODE|KFM_PING_PONG|KFM_REVERSE|KFM_ROTATION|KFM_TRANSLATION|LAND_LEVEL|LAND_LOWER|LAND_NOISE|LAND_RAISE|LAND_REVERT|LAND_SMOOTH|LINK_ALL_CHILDREN|LINK_ALL_OTHERS|LINK_ROOT|LINK_SET|LINK_THIS|LIST_STAT_GEOMETRIC_MEAN|LIST_STAT_MAX|LIST_STAT_MEAN|LIST_STAT_MEDIAN|LIST_STAT_MIN|LIST_STAT_NUM_COUNT|LIST_STAT_RANGE|LIST_STAT_STD_DEV|LIST_STAT_SUM|LIST_STAT_SUM_SQUARES|LOOP|MASK_BASE|MASK_EVERYONE|MASK_GROUP|MASK_NEXT|MASK_OWNER|OBJECT_ATTACHED_POINT|OBJECT_BODY_SHAPE_TYPE|OBJECT_CHARACTER_TIME|OBJECT_CLICK_ACTION|OBJECT_CREATOR|OBJECT_DESC|OBJECT_GROUP|OBJECT_HOVER_HEIGHT|OBJECT_LAST_OWNER_ID|OBJECT_NAME|OBJECT_OWNER|OBJECT_PATHFINDING_TYPE|OBJECT_PHANTOM|OBJECT_PHYSICS|OBJECT_PHYSICS_COST|OBJECT_POS|OBJECT_PRIM_EQUIVALENCE|OBJECT_RENDER_WEIGHT|OBJECT_RETURN_PARCEL|OBJECT_RETURN_PARCEL_OWNER|OBJECT_RETURN_REGION|OBJECT_ROOT|OBJECT_ROT|OBJECT_RUNNING_SCRIPT_COUNT|OBJECT_SCRIPT_MEMORY|OBJECT_SCRIPT_TIME|OBJECT_SERVER_COST|OBJECT_STREAMING_COST|OBJECT_TEMP_ON_REZ|OBJECT_TOTAL_SCRIPT_COUNT|OBJECT_UNKNOWN_DETAIL|OBJECT_VELOCITY|OPT_AVATAR|OPT_CHARACTER|OPT_EXCLUSION_VOLUME|OPT_LEGACY_LINKSET|OPT_MATERIAL_VOLUME|OPT_OTHER|OPT_STATIC_OBSTACLE|OPT_WALKABLE|PARCEL_COUNT_GROUP|PARCEL_COUNT_OTHER|PARCEL_COUNT_OWNER|PARCEL_COUNT_SELECTED|PARCEL_COUNT_TEMP|PARCEL_COUNT_TOTAL|PARCEL_DETAILS_AREA|PARCEL_DETAILS_DESC|PARCEL_DETAILS_GROUP|PARCEL_DETAILS_ID|PARCEL_DETAILS_NAME|PARCEL_DETAILS_OWNER|PARCEL_DETAILS_SEE_AVATARS|PARCEL_FLAG_ALLOW_ALL_OBJECT_ENTRY|PARCEL_FLAG_ALLOW_CREATE_GROUP_OBJECTS|PARCEL_FLAG_ALLOW_CREATE_OBJECTS|PARCEL_FLAG_ALLOW_DAMAGE|PARCEL_FLAG_ALLOW_FLY|PARCEL_FLAG_ALLOW_GROUP_OBJECT_ENTRY|PARCEL_FLAG_ALLOW_GROUP_SCRIPTS|PARCEL_FLAG_ALLOW_LANDMARK|PARCEL_FLAG_ALLOW_SCRIPTS|PARCEL_FLAG_ALLOW_TERRAFORM|PARCEL_FLAG_LOCAL_SOUND_ONLY|PARCEL_FLAG_RESTRICT_PUSHOBJECT|PARCEL_FLAG_USE_ACCESS_GROUP|PARCEL_FLAG_USE_ACCESS_LIST|PARCEL_FLAG_USE_BAN_LIST|PARCEL_FLAG_USE_LAND_PASS_LIST|PARCEL_MEDIA_COMMAND_AGENT|PARCEL_MEDIA_COMMAND_AUTO_ALIGN|PARCEL_MEDIA_COMMAND_DESC|PARCEL_MEDIA_COMMAND_LOOP|PARCEL_MEDIA_COMMAND_LOOP_SET|PARCEL_MEDIA_COMMAND_PAUSE|PARCEL_MEDIA_COMMAND_PLAY|PARCEL_MEDIA_COMMAND_SIZE|PARCEL_MEDIA_COMMAND_STOP|PARCEL_MEDIA_COMMAND_TEXTURE|PARCEL_MEDIA_COMMAND_TIME|PARCEL_MEDIA_COMMAND_TYPE|PARCEL_MEDIA_COMMAND_UNLOAD|PARCEL_MEDIA_COMMAND_URL|PASS_ALWAYS|PASS_IF_NOT_HANDLED|PASS_NEVER|PASSIVE|PATROL_PAUSE_AT_WAYPOINTS|PAYMENT_INFO_ON_FILE|PAYMENT_INFO_USED|PAY_DEFAULT|PAY_HIDE|PERMISSION_ATTACH|PERMISSION_CHANGE_LINKS|PERMISSION_CONTROL_CAMERA|PERMISSION_DEBIT|PERMISSION_OVERRIDE_ANIMATIONS|PERMISSION_RETURN_OBJECTS|PERMISSION_SILENT_ESTATE_MANAGEMENT|PERMISSION_TAKE_CONTROLS|PERMISSION_TELEPORT|PERMISSION_TRACK_CAMERA|PERMISSION_TRIGGER_ANIMATION|PERM_ALL|PERM_COPY|PERM_MODIFY|PERM_MOVE|PERM_TRANSFER|PING_PONG|PRIM_ALPHA_MODE|PRIM_ALPHA_MODE_BLEND|PRIM_ALPHA_MODE_EMISSIVE|PRIM_ALPHA_MODE_MASK|PRIM_ALPHA_MODE_NONE|PRIM_BUMP_BARK|PRIM_BUMP_BLOBS|PRIM_BUMP_BRICKS|PRIM_BUMP_BRIGHT|PRIM_BUMP_CHECKER|PRIM_BUMP_CONCRETE|PRIM_BUMP_DARK|PRIM_BUMP_DISKS|PRIM_BUMP_GRAVEL|PRIM_BUMP_LARGETILE|PRIM_BUMP_NONE|PRIM_BUMP_SHINY|PRIM_BUMP_SIDING|PRIM_BUMP_STONE|PRIM_BUMP_STUCCO|PRIM_BUMP_SUCTION|PRIM_BUMP_TILE|PRIM_BUMP_WEAVE|PRIM_BUMP_WOOD|PRIM_COLOR|PRIM_DESC|PRIM_FLEXIBLE|PRIM_FULLBRIGHT|PRIM_GLOW|PRIM_HOLE_CIRCLE|PRIM_HOLE_DEFAULT|PRIM_HOLE_SQUARE|PRIM_HOLE_TRIANGLE|PRIM_LINK_TARGET|PRIM_MATERIAL|PRIM_MATERIAL_FLESH|PRIM_MATERIAL_GLASS|PRIM_MATERIAL_METAL|PRIM_MATERIAL_PLASTIC|PRIM_MATERIAL_RUBBER|PRIM_MATERIAL_STONE|PRIM_MATERIAL_WOOD|PRIM_MEDIA_ALT_IMAGE_ENABLE|PRIM_MEDIA_AUTO_LOOP|PRIM_MEDIA_AUTO_PLAY|PRIM_MEDIA_AUTO_SCALE|PRIM_MEDIA_AUTO_ZOOM|PRIM_MEDIA_CONTROLS|PRIM_MEDIA_CONTROLS_MINI|PRIM_MEDIA_CONTROLS_STANDARD|PRIM_MEDIA_CURRENT_URL|PRIM_MEDIA_FIRST_CLICK_INTERACT|PRIM_MEDIA_HEIGHT_PIXELS|PRIM_MEDIA_HOME_URL|PRIM_MEDIA_MAX_HEIGHT_PIXELS|PRIM_MEDIA_MAX_URL_LENGTH|PRIM_MEDIA_MAX_WHITELIST_COUNT|PRIM_MEDIA_MAX_WHITELIST_SIZE|PRIM_MEDIA_MAX_WIDTH_PIXELS|PRIM_MEDIA_PARAM_MAX|PRIM_MEDIA_PERMS_CONTROL|PRIM_MEDIA_PERMS_INTERACT|PRIM_MEDIA_PERM_ANYONE|PRIM_MEDIA_PERM_GROUP|PRIM_MEDIA_PERM_NONE|PRIM_MEDIA_PERM_OWNER|PRIM_MEDIA_WHITELIST|PRIM_MEDIA_WHITELIST_ENABLE|PRIM_MEDIA_WIDTH_PIXELS|PRIM_NAME|PRIM_NORMAL|PRIM_OMEGA|PRIM_PHANTOM|PRIM_PHYSICS|PRIM_PHYSICS_SHAPE_CONVEX|PRIM_PHYSICS_SHAPE_NONE|PRIM_PHYSICS_SHAPE_PRIM|PRIM_PHYSICS_SHAPE_TYPE|PRIM_POINT_LIGHT|PRIM_POSITION|PRIM_POS_LOCAL|PRIM_ROTATION|PRIM_ROT_LOCAL|PRIM_SCULPT_FLAG_INVERT|PRIM_SCULPT_FLAG_MIRROR|PRIM_SCULPT_TYPE_CYLINDER|PRIM_SCULPT_TYPE_MASK|PRIM_SCULPT_TYPE_PLANE|PRIM_SCULPT_TYPE_SPHERE|PRIM_SCULPT_TYPE_TORUS|PRIM_SHINY_HIGH|PRIM_SHINY_LOW|PRIM_SHINY_MEDIUM|PRIM_SHINY_NONE|PRIM_SIZE|PRIM_SLICE|PRIM_SPECULAR|PRIM_TEMP_ON_REZ|PRIM_TEXGEN|PRIM_TEXGEN_DEFAULT|PRIM_TEXGEN_PLANAR|PRIM_TEXT|PRIM_TEXTURE|PRIM_TYPE|PRIM_TYPE_BOX|PRIM_TYPE_CYLINDER|PRIM_TYPE_PRISM|PRIM_TYPE_RING|PRIM_TYPE_SCULPT|PRIM_TYPE_SPHERE|PRIM_TYPE_TORUS|PRIM_TYPE_TUBE|PROFILE_NONE|PROFILE_SCRIPT_MEMORY|PSYS_PART_BF_DEST_COLOR|PSYS_PART_BF_ONE|PSYS_PART_BF_ONE_MINUS_DEST_COLOR|PSYS_PART_BF_ONE_MINUS_SOURCE_ALPHA|PSYS_PART_BF_ONE_MINUS_SOURCE_COLOR|PSYS_PART_BF_SOURCE_ALPHA|PSYS_PART_BF_SOURCE_COLOR|PSYS_PART_BF_ZERO|PSYS_PART_BLEND_FUNC_DEST|PSYS_PART_BLEND_FUNC_SOURCE|PSYS_PART_BOUNCE_MASK|PSYS_PART_EMISSIVE_MASK|PSYS_PART_END_ALPHA|PSYS_PART_END_COLOR|PSYS_PART_END_GLOW|PSYS_PART_END_SCALE|PSYS_PART_FLAGS|PSYS_PART_FOLLOW_SRC_MASK|PSYS_PART_FOLLOW_VELOCITY_MASK|PSYS_PART_INTERP_COLOR_MASK|PSYS_PART_INTERP_SCALE_MASK|PSYS_PART_MAX_AGE|PSYS_PART_RIBBON_MASK|PSYS_PART_START_ALPHA|PSYS_PART_START_COLOR|PSYS_PART_START_GLOW|PSYS_PART_START_SCALE|PSYS_PART_TARGET_LINEAR_MASK|PSYS_PART_TARGET_POS_MASK|PSYS_PART_WIND_MASK|PSYS_SRC_ACCEL|PSYS_SRC_ANGLE_BEGIN|PSYS_SRC_ANGLE_END|PSYS_SRC_BURST_PART_COUNT|PSYS_SRC_BURST_RADIUS|PSYS_SRC_BURST_RATE|PSYS_SRC_BURST_SPEED_MAX|PSYS_SRC_BURST_SPEED_MIN|PSYS_SRC_MAX_AGE|PSYS_SRC_OMEGA|PSYS_SRC_PATTERN|PSYS_SRC_PATTERN_ANGLE|PSYS_SRC_PATTERN_ANGLE_CONE|PSYS_SRC_PATTERN_ANGLE_CONE_EMPTY|PSYS_SRC_PATTERN_DROP|PSYS_SRC_PATTERN_EXPLODE|PSYS_SRC_TARGET_KEY|PSYS_SRC_TEXTURE|PUBLIC_CHANNEL|PURSUIT_FUZZ_FACTOR|PURSUIT_GOAL_TOLERANCE|PURSUIT_INTERCEPT|PURSUIT_OFFSET|PU_EVADE_HIDDEN|PU_EVADE_SPOTTED|PU_FAILURE_DYNAMIC_PATHFINDING_DISABLED|PU_FAILURE_INVALID_GOAL|PU_FAILURE_INVALID_START|PU_FAILURE_NO_NAVMESH|PU_FAILURE_NO_VALID_DESTINATION|PU_FAILURE_OTHER|PU_FAILURE_PARCEL_UNREACHABLE|PU_FAILURE_TARGET_GONE|PU_FAILURE_UNREACHABLE|PU_GOAL_REACHED|PU_SLOWDOWN_DISTANCE_REACHED|RCERR_CAST_TIME_EXCEEDED|RCERR_SIM_PERF_LOW|RCERR_UNKNOWN|RC_DATA_FLAGS|RC_DETECT_PHANTOM|RC_GET_LINK_NUM|RC_GET_NORMAL|RC_GET_ROOT_KEY|RC_MAX_HITS|RC_REJECT_AGENTS|RC_REJECT_LAND|RC_REJECT_NONPHYSICAL|RC_REJECT_PHYSICAL|RC_REJECT_TYPES|REGION_FLAG_ALLOW_DAMAGE|REGION_FLAG_ALLOW_DIRECT_TELEPORT|REGION_FLAG_BLOCK_FLY|REGION_FLAG_BLOCK_TERRAFORM|REGION_FLAG_DISABLE_COLLISIONS|REGION_FLAG_DISABLE_PHYSICS|REGION_FLAG_FIXED_SUN|REGION_FLAG_RESTRICT_PUSHOBJECT|REGION_FLAG_SANDBOX|REMOTE_DATA_CHANNEL|REMOTE_DATA_REPLY|REMOTE_DATA_REQUEST|REQUIRE_LINE_OF_SIGHT|RESTITUTION|REVERSE|ROTATE|SCALE|SCRIPTED|SIM_STAT_PCT_CHARS_STEPPED|SMOOTH|STATUS_BLOCK_GRAB|STATUS_BLOCK_GRAB_OBJECT|STATUS_BOUNDS_ERROR|STATUS_CAST_SHADOWS|STATUS_DIE_AT_EDGE|STATUS_INTERNAL_ERROR|STATUS_MALFORMED_PARAMS|STATUS_NOT_FOUND|STATUS_NOT_SUPPORTED|STATUS_OK|STATUS_PHANTOM|STATUS_PHYSICS|STATUS_RETURN_AT_EDGE|STATUS_ROTATE_X|STATUS_ROTATE_Y|STATUS_ROTATE_Z|STATUS_SANDBOX|STATUS_TYPE_MISMATCH|STATUS_WHITELIST_FAILED|STRING_TRIM|STRING_TRIM_HEAD|STRING_TRIM_TAIL|TOUCH_INVALID_FACE|TRAVERSAL_TYPE|TRAVERSAL_TYPE_FAST|TRAVERSAL_TYPE_NONE|TRAVERSAL_TYPE_SLOW|TRUE|TYPE_FLOAT|TYPE_INTEGER|TYPE_INVALID|TYPE_KEY|TYPE_ROTATION|TYPE_STRING|TYPE_VECTOR|VEHICLE_ANGULAR_DEFLECTION_EFFICIENCY|VEHICLE_ANGULAR_DEFLECTION_TIMESCALE|VEHICLE_ANGULAR_FRICTION_TIMESCALE|VEHICLE_ANGULAR_MOTOR_DECAY_TIMESCALE|VEHICLE_ANGULAR_MOTOR_DIRECTION|VEHICLE_ANGULAR_MOTOR_TIMESCALE|VEHICLE_BANKING_EFFICIENCY|VEHICLE_BANKING_MIX|VEHICLE_BANKING_TIMESCALE|VEHICLE_BUOYANCY|VEHICLE_FLAG_CAMERA_DECOUPLED|VEHICLE_FLAG_HOVER_GLOBAL_HEIGHT|VEHICLE_FLAG_HOVER_TERRAIN_ONLY|VEHICLE_FLAG_HOVER_UP_ONLY|VEHICLE_FLAG_HOVER_WATER_ONLY|VEHICLE_FLAG_LIMIT_MOTOR_UP|VEHICLE_FLAG_LIMIT_ROLL_ONLY|VEHICLE_FLAG_MOUSELOOK_BANK|VEHICLE_FLAG_MOUSELOOK_STEER|VEHICLE_FLAG_NO_DEFLECTION_UP|VEHICLE_HOVER_EFFICIENCY|VEHICLE_HOVER_HEIGHT|VEHICLE_HOVER_TIMESCALE|VEHICLE_LINEAR_DEFLECTION_EFFICIENCY|VEHICLE_LINEAR_DEFLECTION_TIMESCALE|VEHICLE_LINEAR_FRICTION_TIMESCALE|VEHICLE_LINEAR_MOTOR_DECAY_TIMESCALE|VEHICLE_LINEAR_MOTOR_DIRECTION|VEHICLE_LINEAR_MOTOR_OFFSET|VEHICLE_LINEAR_MOTOR_TIMESCALE|VEHICLE_REFERENCE_FRAME|VEHICLE_TYPE_AIRPLANE|VEHICLE_TYPE_BALLOON|VEHICLE_TYPE_BOAT|VEHICLE_TYPE_CAR|VEHICLE_TYPE_NONE|VEHICLE_TYPE_SLED|VEHICLE_VERTICAL_ATTRACTION_EFFICIENCY|VEHICLE_VERTICAL_ATTRACTION_TIMESCALE|VERTICAL|WANDER_PAUSE_AT_WAYPOINTS|XP_ERROR_EXPERIENCES_DISABLED|XP_ERROR_EXPERIENCE_DISABLED|XP_ERROR_EXPERIENCE_SUSPENDED|XP_ERROR_INVALID_EXPERIENCE|XP_ERROR_INVALID_PARAMETERS|XP_ERROR_KEY_NOT_FOUND|XP_ERROR_MATURITY_EXCEEDED|XP_ERROR_NONE|XP_ERROR_NOT_FOUND|XP_ERROR_NOT_PERMITTED|XP_ERROR_NO_EXPERIENCE|XP_ERROR_QUOTA_EXCEEDED|XP_ERROR_RETRY_UPDATE|XP_ERROR_STORAGE_EXCEPTION|XP_ERROR_STORE_DISABLED|XP_ERROR_THROTTLED|XP_ERROR_UNKNOWN_ERROR","constant.language.integer.boolean.lsl":"FALSE|TRUE","constant.language.quaternion.lsl":"ZERO_ROTATION","constant.language.string.lsl":"EOF|JSON_ARRAY|JSON_DELETE|JSON_FALSE|JSON_INVALID|JSON_NULL|JSON_NUMBER|JSON_OBJECT|JSON_STRING|JSON_TRUE|NULL_KEY|TEXTURE_BLANK|TEXTURE_DEFAULT|TEXTURE_MEDIA|TEXTURE_PLYWOOD|TEXTURE_TRANSPARENT|URL_REQUEST_DENIED|URL_REQUEST_GRANTED","constant.language.vector.lsl":"TOUCH_INVALID_TEXCOORD|TOUCH_INVALID_VECTOR|ZERO_VECTOR","invalid.broken.lsl":"LAND_LARGE_BRUSH|LAND_MEDIUM_BRUSH|LAND_SMALL_BRUSH","invalid.deprecated.lsl":"ATTACH_LPEC|ATTACH_RPEC|DATA_RATING|OBJECT_ATTACHMENT_GEOMETRY_BYTES|OBJECT_ATTACHMENT_SURFACE_AREA|PRIM_CAST_SHADOWS|PRIM_MATERIAL_LIGHT|PRIM_TYPE_LEGACY|PSYS_SRC_INNERANGLE|PSYS_SRC_OUTERANGLE|VEHICLE_FLAG_NO_FLY_UP|llClearExperiencePermissions|llCloud|llGetExperienceList|llMakeExplosion|llMakeFire|llMakeFountain|llMakeSmoke|llRemoteDataSetRegion|llSound|llSoundPreload|llXorBase64Strings|llXorBase64StringsCorrect","invalid.illegal.lsl":"event","invalid.unimplemented.lsl":"CHARACTER_MAX_ANGULAR_ACCEL|CHARACTER_MAX_ANGULAR_SPEED|CHARACTER_TURN_SPEED_MULTIPLIER|PERMISSION_CHANGE_JOINTS|PERMISSION_CHANGE_PERMISSIONS|PERMISSION_EXPERIENCE|PERMISSION_RELEASE_OWNERSHIP|PERMISSION_REMAP_CONTROLS|PRIM_PHYSICS_MATERIAL|PSYS_SRC_OBJ_REL_MASK|llCollisionSprite|llPointAt|llRefreshPrimURL|llReleaseCamera|llRemoteLoadScript|llSetPrimURL|llStopPointAt|llTakeCamera","reserved.godmode.lsl":"llGodLikeRezObject|llSetInventoryPermMask|llSetObjectPermMask","reserved.log.lsl":"print","keyword.control.lsl":"do|else|for|if|jump|return|while","storage.type.lsl":"float|integer|key|list|quaternion|rotation|string|vector","support.function.lsl":"llAbs|llAcos|llAddToLandBanList|llAddToLandPassList|llAdjustSoundVolume|llAgentInExperience|llAllowInventoryDrop|llAngleBetween|llApplyImpulse|llApplyRotationalImpulse|llAsin|llAtan2|llAttachToAvatar|llAttachToAvatarTemp|llAvatarOnLinkSitTarget|llAvatarOnSitTarget|llAxes2Rot|llAxisAngle2Rot|llBase64ToInteger|llBase64ToString|llBreakAllLinks|llBreakLink|llCSV2List|llCastRay|llCeil|llClearCameraParams|llClearLinkMedia|llClearPrimMedia|llCloseRemoteDataChannel|llCollisionFilter|llCollisionSound|llCos|llCreateCharacter|llCreateKeyValue|llCreateLink|llDataSizeKeyValue|llDeleteCharacter|llDeleteKeyValue|llDeleteSubList|llDeleteSubString|llDetachFromAvatar|llDetectedGrab|llDetectedGroup|llDetectedKey|llDetectedLinkNumber|llDetectedName|llDetectedOwner|llDetectedPos|llDetectedRot|llDetectedTouchBinormal|llDetectedTouchFace|llDetectedTouchNormal|llDetectedTouchPos|llDetectedTouchST|llDetectedTouchUV|llDetectedType|llDetectedVel|llDialog|llDie|llDumpList2String|llEdgeOfWorld|llEjectFromLand|llEmail|llEscapeURL|llEuler2Rot|llEvade|llExecCharacterCmd|llFabs|llFleeFrom|llFloor|llForceMouselook|llFrand|llGenerateKey|llGetAccel|llGetAgentInfo|llGetAgentLanguage|llGetAgentList|llGetAgentSize|llGetAlpha|llGetAndResetTime|llGetAnimation|llGetAnimationList|llGetAnimationOverride|llGetAttached|llGetAttachedList|llGetBoundingBox|llGetCameraPos|llGetCameraRot|llGetCenterOfMass|llGetClosestNavPoint|llGetColor|llGetCreator|llGetDate|llGetDisplayName|llGetEnergy|llGetEnv|llGetExperienceDetails|llGetExperienceErrorMessage|llGetForce|llGetFreeMemory|llGetFreeURLs|llGetGMTclock|llGetGeometricCenter|llGetHTTPHeader|llGetInventoryCreator|llGetInventoryKey|llGetInventoryName|llGetInventoryNumber|llGetInventoryPermMask|llGetInventoryType|llGetKey|llGetLandOwnerAt|llGetLinkKey|llGetLinkMedia|llGetLinkName|llGetLinkNumber|llGetLinkNumberOfSides|llGetLinkPrimitiveParams|llGetListEntryType|llGetListLength|llGetLocalPos|llGetLocalRot|llGetMass|llGetMassMKS|llGetMaxScaleFactor|llGetMemoryLimit|llGetMinScaleFactor|llGetNextEmail|llGetNotecardLine|llGetNumberOfNotecardLines|llGetNumberOfPrims|llGetNumberOfSides|llGetObjectDesc|llGetObjectDetails|llGetObjectMass|llGetObjectName|llGetObjectPermMask|llGetObjectPrimCount|llGetOmega|llGetOwner|llGetOwnerKey|llGetParcelDetails|llGetParcelFlags|llGetParcelMaxPrims|llGetParcelMusicURL|llGetParcelPrimCount|llGetParcelPrimOwners|llGetPermissions|llGetPermissionsKey|llGetPhysicsMaterial|llGetPos|llGetPrimMediaParams|llGetPrimitiveParams|llGetRegionAgentCount|llGetRegionCorner|llGetRegionFPS|llGetRegionFlags|llGetRegionName|llGetRegionTimeDilation|llGetRootPosition|llGetRootRotation|llGetRot|llGetSPMaxMemory|llGetScale|llGetScriptName|llGetScriptState|llGetSimStats|llGetSimulatorHostname|llGetStartParameter|llGetStaticPath|llGetStatus|llGetSubString|llGetSunDirection|llGetTexture|llGetTextureOffset|llGetTextureRot|llGetTextureScale|llGetTime|llGetTimeOfDay|llGetTimestamp|llGetTorque|llGetUnixTime|llGetUsedMemory|llGetUsername|llGetVel|llGetWallclock|llGiveInventory|llGiveInventoryList|llGiveMoney|llGround|llGroundContour|llGroundNormal|llGroundRepel|llGroundSlope|llHTTPRequest|llHTTPResponse|llInsertString|llInstantMessage|llIntegerToBase64|llJson2List|llJsonGetValue|llJsonSetValue|llJsonValueType|llKey2Name|llKeyCountKeyValue|llKeysKeyValue|llLinkParticleSystem|llLinkSitTarget|llList2CSV|llList2Float|llList2Integer|llList2Json|llList2Key|llList2List|llList2ListStrided|llList2Rot|llList2String|llList2Vector|llListFindList|llListInsertList|llListRandomize|llListReplaceList|llListSort|llListStatistics|llListen|llListenControl|llListenRemove|llLoadURL|llLog|llLog10|llLookAt|llLoopSound|llLoopSoundMaster|llLoopSoundSlave|llMD5String|llManageEstateAccess|llMapDestination|llMessageLinked|llMinEventDelay|llModPow|llModifyLand|llMoveToTarget|llNavigateTo|llOffsetTexture|llOpenRemoteDataChannel|llOverMyLand|llOwnerSay|llParcelMediaCommandList|llParcelMediaQuery|llParseString2List|llParseStringKeepNulls|llParticleSystem|llPassCollisions|llPassTouches|llPatrolPoints|llPlaySound|llPlaySoundSlave|llPow|llPreloadSound|llPursue|llPushObject|llReadKeyValue|llRegionSay|llRegionSayTo|llReleaseControls|llReleaseURL|llRemoteDataReply|llRemoteLoadScriptPin|llRemoveFromLandBanList|llRemoveFromLandPassList|llRemoveInventory|llRemoveVehicleFlags|llRequestAgentData|llRequestDisplayName|llRequestExperiencePermissions|llRequestInventoryData|llRequestPermissions|llRequestSecureURL|llRequestSimulatorData|llRequestURL|llRequestUsername|llResetAnimationOverride|llResetLandBanList|llResetLandPassList|llResetOtherScript|llResetScript|llResetTime|llReturnObjectsByID|llReturnObjectsByOwner|llRezAtRoot|llRezObject|llRot2Angle|llRot2Axis|llRot2Euler|llRot2Fwd|llRot2Left|llRot2Up|llRotBetween|llRotLookAt|llRotTarget|llRotTargetRemove|llRotateTexture|llRound|llSHA1String|llSameGroup|llSay|llScaleByFactor|llScaleTexture|llScriptDanger|llScriptProfiler|llSendRemoteData|llSensor|llSensorRemove|llSensorRepeat|llSetAlpha|llSetAngularVelocity|llSetAnimationOverride|llSetBuoyancy|llSetCameraAtOffset|llSetCameraEyeOffset|llSetCameraParams|llSetClickAction|llSetColor|llSetContentType|llSetDamage|llSetForce|llSetForceAndTorque|llSetHoverHeight|llSetKeyframedMotion|llSetLinkAlpha|llSetLinkCamera|llSetLinkColor|llSetLinkMedia|llSetLinkPrimitiveParams|llSetLinkPrimitiveParamsFast|llSetLinkTexture|llSetLinkTextureAnim|llSetLocalRot|llSetMemoryLimit|llSetObjectDesc|llSetObjectName|llSetParcelMusicURL|llSetPayPrice|llSetPhysicsMaterial|llSetPos|llSetPrimMediaParams|llSetPrimitiveParams|llSetRegionPos|llSetRemoteScriptAccessPin|llSetRot|llSetScale|llSetScriptState|llSetSitText|llSetSoundQueueing|llSetSoundRadius|llSetStatus|llSetText|llSetTexture|llSetTextureAnim|llSetTimerEvent|llSetTorque|llSetTouchText|llSetVehicleFlags|llSetVehicleFloatParam|llSetVehicleRotationParam|llSetVehicleType|llSetVehicleVectorParam|llSetVelocity|llShout|llSin|llSitTarget|llSleep|llSqrt|llStartAnimation|llStopAnimation|llStopHover|llStopLookAt|llStopMoveToTarget|llStopSound|llStringLength|llStringToBase64|llStringTrim|llSubStringIndex|llTakeControls|llTan|llTarget|llTargetOmega|llTargetRemove|llTeleportAgent|llTeleportAgentGlobalCoords|llTeleportAgentHome|llTextBox|llToLower|llToUpper|llTransferLindenDollars|llTriggerSound|llTriggerSoundLimited|llUnSit|llUnescapeURL|llUpdateCharacter|llUpdateKeyValue|llVecDist|llVecMag|llVecNorm|llVolumeDetect|llWanderWithin|llWater|llWhisper|llWind|llXorBase64","support.function.event.lsl":"at_rot_target|at_target|attach|changed|collision|collision_end|collision_start|control|dataserver|email|experience_permissions|experience_permissions_denied|http_request|http_response|land_collision|land_collision_end|land_collision_start|link_message|listen|money|moving_end|moving_start|no_sensor|not_at_rot_target|not_at_target|object_rez|on_rez|path_update|remote_data|run_time_permissions|sensor|state_entry|state_exit|timer|touch|touch_end|touch_start|transaction_result"},"identifier");this.$rules={start:[{token:"comment.line.double-slash.lsl",regex:"\\/\\/.*$"},{token:"comment.block.begin.lsl",regex:"\\/\\*",next:"comment"},{token:"string.quoted.double.lsl",start:'"',end:'"',next:[{token:"constant.character.escape.lsl",regex:/\\[tn"\\]/}]},{token:"constant.numeric.lsl",regex:"(0[xX][0-9a-fA-F]+|[+-]?[0-9]+(?:(?:\\.[0-9]*)?(?:[eE][+-]?[0-9]+)?)?)\\b"},{token:"entity.name.state.lsl",regex:"\\b((state)\\s+[A-Za-z_]\\w*|default)\\b"},{token:e,regex:"\\b[a-zA-Z_][a-zA-Z0-9_]*\\b"},{token:"support.function.user-defined.lsl",regex:/\b([a-zA-Z_]\w*)(?=\(.*?\))/},{token:"keyword.operator.lsl",regex:"\\+\\+|\\-\\-|<<|>>|&&?|\\|\\|?|\\^|~|[!%<>=*+\\-\\/]=?"},{token:"invalid.illegal.keyword.operator.lsl",regex:":=?"},{token:"punctuation.operator.lsl",regex:"\\,|\\;"},{token:"paren.lparen.lsl",regex:"[\\[\\(\\{]"},{token:"paren.rparen.lsl",regex:"[\\]\\)\\}]"},{token:"text.lsl",regex:"\\s+"}],comment:[{token:"comment.block.end.lsl",regex:"\\*\\/",next:"start"},{defaultToken:"comment.block.lsl"}]},this.normalizeRules()}var r=e("../lib/oop"),i=e("./text_highlight_rules").TextHighlightRules;r.inherits(s,i),t.LSLHighlightRules=s}),ace.define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"],function(e,t,n){"use strict";var r=e("../range").Range,i=function(){};(function(){this.checkOutdent=function(e,t){return/^\s+$/.test(e)?/^\s*\}/.test(t):!1},this.autoOutdent=function(e,t){var n=e.getLine(t),i=n.match(/^(\s*\})/);if(!i)return 0;var s=i[1].length,o=e.findMatchingBracket({row:t,column:s});if(!o||o.row==t)return 0;var u=this.$getIndent(e.getLine(o.row));e.replace(new r(t,0,t,s-1),u)},this.$getIndent=function(e){return e.match(/^\s*/)[0]}}).call(i.prototype),t.MatchingBraceOutdent=i}),ace.define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"],function(e,t,n){"use strict";var r=e("../../lib/oop"),i=e("../../range").Range,s=e("./fold_mode").FoldMode,o=t.FoldMode=function(e){e&&(this.foldingStartMarker=new RegExp(this.foldingStartMarker.source.replace(/\|[^|]*?$/,"|"+e.start)),this.foldingStopMarker=new RegExp(this.foldingStopMarker.source.replace(/\|[^|]*?$/,"|"+e.end)))};r.inherits(o,s),function(){this.foldingStartMarker=/(\{|\[)[^\}\]]*$|^\s*(\/\*)/,this.foldingStopMarker=/^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/,this.singleLineBlockCommentRe=/^\s*(\/\*).*\*\/\s*$/,this.tripleStarBlockCommentRe=/^\s*(\/\*\*\*).*\*\/\s*$/,this.startRegionRe=/^\s*(\/\*|\/\/)#?region\b/,this._getFoldWidgetBase=this.getFoldWidget,this.getFoldWidget=function(e,t,n){var r=e.getLine(n);if(this.singleLineBlockCommentRe.test(r)&&!this.startRegionRe.test(r)&&!this.tripleStarBlockCommentRe.test(r))return"";var i=this._getFoldWidgetBase(e,t,n);return!i&&this.startRegionRe.test(r)?"start":i},this.getFoldWidgetRange=function(e,t,n,r){var i=e.getLine(n);if(this.startRegionRe.test(i))return this.getCommentRegionBlock(e,i,n);var s=i.match(this.foldingStartMarker);if(s){var o=s.index;if(s[1])return this.openingBracketBlock(e,s[1],n,o);var u=e.getCommentFoldRange(n,o+s[0].length,1);return u&&!u.isMultiLine()&&(r?u=this.getSectionRange(e,n):t!="all"&&(u=null)),u}if(t==="markbegin")return;var s=i.match(this.foldingStopMarker);if(s){var o=s.index+s[0].length;return s[1]?this.closingBracketBlock(e,s[1],n,o):e.getCommentFoldRange(n,o,-1)}},this.getSectionRange=function(e,t){var n=e.getLine(t),r=n.search(/\S/),s=t,o=n.length;t+=1;var u=t,a=e.getLength();while(++t<a){n=e.getLine(t);var f=n.search(/\S/);if(f===-1)continue;if(r>f)break;var l=this.getFoldWidgetRange(e,"all",t);if(l){if(l.start.row<=s)break;if(l.isMultiLine())t=l.end.row;else if(r==f)break}u=t}return new i(s,o,u,e.getLine(u).length)},this.getCommentRegionBlock=function(e,t,n){var r=t.search(/\s*$/),s=e.getLength(),o=n,u=/^\s*(?:\/\*|\/\/|--)#?(end)?region\b/,a=1;while(++n<s){t=e.getLine(n);var f=u.exec(t);if(!f)continue;f[1]?a--:a++;if(!a)break}var l=n;if(l>o)return new i(o,r,l,t.length)}}.call(o.prototype)}),ace.define("ace/mode/lsl",["require","exports","module","ace/mode/lsl_highlight_rules","ace/mode/matching_brace_outdent","ace/range","ace/mode/text","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle","ace/lib/oop"],function(e,t,n){"use strict";var r=e("./lsl_highlight_rules").LSLHighlightRules,i=e("./matching_brace_outdent").MatchingBraceOutdent,s=e("../range").Range,o=e("./text").Mode,u=e("./behaviour/cstyle").CstyleBehaviour,a=e("./folding/cstyle").FoldMode,f=e("../lib/oop"),l=function(){this.HighlightRules=r,this.$outdent=new i,this.$behaviour=new u,this.foldingRules=new a};f.inherits(l,o),function(){this.lineCommentStart=["//"],this.blockComment={start:"/*",end:"*/"},this.getNextLineIndent=function(e,t,n){var r=this.$getIndent(t),i=this.getTokenizer().getLineTokens(t,e),s=i.tokens,o=i.state;if(s.length&&s[s.length-1].type==="comment.block.lsl")return r;if(e==="start"){var u=t.match(/^.*[\{\(\[]\s*$/);u&&(r+=n)}return r},this.checkOutdent=function(e,t,n){return this.$outdent.checkOutdent(t,n)},this.autoOutdent=function(e,t,n){this.$outdent.autoOutdent(t,n)},this.$id="ace/mode/lsl"}.call(l.prototype),t.Mode=l}) | 1 | 0.899376 | 1 | 0.899376 | game-dev | MEDIA | 0.85226 | game-dev | 0.524107 | 1 | 0.524107 |
SinlessDevil/ZenjectTemplate | 1,140 | Assets/Shaders/Toony Colors Pro/Demo TCP2/Common Demo Assets/Scripts/TCP2_Demo_Interactive_Environment.cs | using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace ToonyColorsPro
{
namespace Demo
{
public class TCP2_Demo_Interactive_Environment : MonoBehaviour
{
public Material skybox;
public void ApplyEnvironment()
{
var root = this.transform.parent;
var envs = root.GetComponentsInChildren<TCP2_Demo_Interactive_Environment>();
foreach (var env in envs)
{
env.gameObject.SetActive(false);
}
this.gameObject.SetActive(true);
RenderSettings.skybox = this.skybox;
RenderSettings.customReflection = (Cubemap)this.skybox.GetTexture("_Tex");
if (Application.isPlaying)
{
DynamicGI.UpdateEnvironment();
}
}
}
}
}
#if UNITY_EDITOR
namespace ToonyColorsPro
{
namespace Demo
{
[CustomEditor(typeof(TCP2_Demo_Interactive_Environment))]
public class TCP2_Demo_Interactive_Environment_Editor : Editor
{
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
GUILayout.Space(8);
if (GUILayout.Button("Apply Environment"))
{
(target as TCP2_Demo_Interactive_Environment).ApplyEnvironment();
}
}
}
}
}
#endif | 1 | 0.735715 | 1 | 0.735715 | game-dev | MEDIA | 0.592131 | game-dev | 0.745964 | 1 | 0.745964 |
Hiro420/GI_CBT1_Data | 3,526 | resources/lua/scene/3/scene3_group133007187.lua | --================================================================
--
-- 配置
--
--================================================================
-- 怪物
monsters = {
}
-- NPC
npcs = {
}
-- 装置
gadgets = {
{ config_id = 591, gadget_id = 70210031, pos = { x = 2680.5, y = 238.2, z = 48.4 }, rot = { x = 350.9, y = 84.1, z = 0.0 }, level = 1, chest_drop_id = 403225, showcutscene = true, isOneoff = true, persistent = true },
{ config_id = 661, gadget_id = 70710002, pos = { x = 2700.5, y = 240.7, z = 20.3 }, rot = { x = 0.0, y = 264.1, z = 0.0 }, level = 1, route_id = 3007098, save_route = true },
{ config_id = 662, gadget_id = 70900042, pos = { x = 2680.4, y = 238.2, z = 46.2 }, rot = { x = 0.0, y = 82.0, z = 0.0 }, level = 1 }
}
-- 区域
regions = {
{ config_id = 212, shape = RegionShape.SPHERE, radius = 2, pos = { x = 2700.4, y = 240.7, z = 20.3 } },
{ config_id = 213, shape = RegionShape.SPHERE, radius = 3, pos = { x = 2680.7, y = 238.2, z = 47.3 } }
}
-- 触发器
triggers = {
{ name = "ENTER_REGION_212", event = EventType.EVENT_ENTER_REGION, source = "", condition = "condition_EVENT_ENTER_REGION_212", action = "action_EVENT_ENTER_REGION_212", tlog_tag = "风龙_187_移动精灵6_开始" },
{ name = "PLATFORM_REACH_POINT_213", event = EventType.EVENT_PLATFORM_REACH_POINT, source = "", condition = "condition_EVENT_PLATFORM_REACH_POINT_213", action = "action_EVENT_PLATFORM_REACH_POINT_213", tlog_tag = "风龙_187_移动精灵6_成功" }
}
-- 变量
variables = {
{ name = "spirit", value = 0, persistent = false }
}
--================================================================
--
-- 初始化配置
--
--================================================================
-- 初始化时创建
init_config = {
suite = 1,
rand_suite = false,
npcs = { }
}
--================================================================
--
-- 小组配置
--
--================================================================
suites = {
{
-- suite_id = 0,
-- description = ,
monsters = { },
gadgets = { 661, 662 },
regions = { 212, 213 },
triggers = { "ENTER_REGION_212", "PLATFORM_REACH_POINT_213" },
rand_weight = 100
}
}
--================================================================
--
-- 触发器
--
--================================================================
-- 触发条件
function condition_EVENT_ENTER_REGION_212(context, evt)
if evt.param1 ~= 212 then return false end
-- 判断角色数量不少于1
if ScriptLib.GetRegionEntityCount(context, { region_eid = evt.source_eid, entity_type = EntityType.AVATAR }) < 1 then
return false
end
-- 判断变量"spirit"为0
if ScriptLib.GetGroupVariableValue(context, "spirit") ~= 0 then
return false
end
return true
end
-- 触发操作
function action_EVENT_ENTER_REGION_212(context, evt)
-- 设置移动平台路径
if 0 ~= ScriptLib.SetPlatformRouteId(context, 661, 3007100) then
return -1
end
-- 将本组内变量名为 "spirit" 的变量设置为 1
if 0 ~= ScriptLib.SetGroupVariableValue(context, "spirit", 1) then
return -1
end
return 0
end
-- 触发条件
function condition_EVENT_PLATFORM_REACH_POINT_213(context, evt)
-- 判断是gadgetid 为 661的移动平台,是否到达了3007100 的路线中的 3 点
if 661 ~= evt.param1 then
return false
end
if 3007100 ~= evt.param2 then
return false
end
if 3 ~= evt.param3 then
return false
end
-- 判断变量"spirit"为1
if ScriptLib.GetGroupVariableValue(context, "spirit") ~= 1 then
return false
end
return true
end
-- 触发操作
function action_EVENT_PLATFORM_REACH_POINT_213(context, evt)
-- 创建id为591的gadget
if 0 ~= ScriptLib.CreateGadget(context, { config_id = 591 }) then
return -1
end
return 0
end
| 1 | 0.703152 | 1 | 0.703152 | game-dev | MEDIA | 0.961994 | game-dev | 0.583348 | 1 | 0.583348 |
Nebukam/com.nebukam.orca | 5,600 | Runtime/Raycast.cs | // Copyright (c) 2021 Timothé Lapetite - nebukam@gmail.com
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
using Unity.Burst;
using Unity.Mathematics;
using static Unity.Mathematics.math;
using Nebukam.Common;
namespace Nebukam.ORCA
{
/// <summary>
/// Defines which type of object the raycast should include in its checks.
/// </summary>
[System.Flags]
public enum RaycastFilter
{
NONE = 0,
AGENTS = 1,
OBSTACLE_STATIC = 2,
OBSTACLE_DYNAMIC = 4,
OBSTACLES = OBSTACLE_STATIC | OBSTACLE_DYNAMIC,
ANY = AGENTS | OBSTACLES
}
/// <summary>
/// Job-friendly representation of a Raycast.
/// Primarily used within RaycastProvider.
/// </summary>
[BurstCompile]
public struct RaycastData
{
public float2 position;
public float3 worldPosition;
public float baseline;
public float2 direction;
public float3 worldDir;
public float distance;
public ORCALayer layerIgnore;
public RaycastFilter filter;
public bool twoSided;
}
/// <summary>
/// Result of a raycast.
/// Primarily used within RaycastPass
/// </summary>
[BurstCompile]
public struct RaycastResult
{
public int hitAgent;
public float3 hitAgentLocation;
public float2 hitAgentLocation2D;
public bool dynamicObstacle;
public int hitObstacle;
public float3 hitObstacleLocation;
public float2 hitObstacleLocation2D;
public int ObstacleVertexA;
public int ObstacleVertexB;
}
/// <summary>
/// A Raycast object. Holds the Raycast settings as well as its results.
/// </summary>
public class Raycast : Vertex, IRequireCleanUp
{
protected internal float3 m_dir = float3(0f);
protected internal ORCALayer m_layerIgnore = ORCALayer.NONE;
protected internal RaycastFilter m_filter = RaycastFilter.ANY;
protected internal float m_distance = 0f;
protected internal bool m_anyHit = false;
protected internal bool m_twoSided = false;
/// <summary>
/// The direction of the raycast
/// </summary>
public float3 dir { get { return m_dir; } set { m_dir = value; } }
/// <summary>
/// Layers to be ignored by the Raycast when resolved
/// </summary>
public ORCALayer layerIgnore { get { return m_layerIgnore; } set { m_layerIgnore = value; } }
/// <summary>
/// Filters the type of ingredients this Raycast will hit
/// </summary>
public RaycastFilter filter { get { return m_filter; } set { m_filter = value; } }
/// <summary>
/// Distance of the Raycast.
/// This is the length/reach of the Raycast, anything beyond that distance will be ignored.
/// </summary>
public float distance { get { return m_distance; } set { m_distance = value; } }
/// <summary>
/// Whether that raycast hit anything
/// </summary>
public bool anyHit { get { return m_anyHit; } }
/// <summary>
/// Whether that raycast is two-sided.
/// If true, will check for backface collisions, otherwise not. This is useful in situation
/// where the Raycast origin may be within an ingredient (agent or collision).
/// </summary>
public bool twoSided { get { return m_twoSided; } }
/// <summary>
/// The Obstacle hit by the Raycast, if any
/// </summary>
public Obstacle obstacleHit { get; set; }
/// <summary>
/// The location on the Obstacle surface where the Raycast hit.
/// </summary>
public float3 obstacleHitLocation { get; set; }
/// <summary>
/// The Agent hit by the Raycast, if any
/// </summary>
public Agent agentHit { get; set; }
/// <summary>
/// The location on the Agent surface (radius-driven circle) where the Raycast hit
/// </summary>
public float3 agentHitLocation { get; set; }
/// <summary>
/// Cleanup/Reset the Raycast object when interacting with pools.
/// </summary>
public virtual void CleanUp()
{
m_dir = float3(0f);
m_distance = 0f;
m_layerIgnore = ORCALayer.NONE;
m_filter = RaycastFilter.ANY;
m_anyHit = false;
m_twoSided = false;
obstacleHit = null;
agentHit = null;
}
}
}
| 1 | 0.925509 | 1 | 0.925509 | game-dev | MEDIA | 0.676658 | game-dev,graphics-rendering | 0.965986 | 1 | 0.965986 |
hneemann/Digital | 5,657 | src/main/java/de/neemann/digital/gui/components/tree/LibraryTreeModel.java | /*
* Copyright (c) 2017 Helmut Neemann
* Use of this source code is governed by the GPL v3 license
* that can be found in the LICENSE file.
*/
package de.neemann.digital.gui.components.tree;
import de.neemann.digital.draw.library.ElementLibrary;
import de.neemann.digital.draw.library.LibraryListener;
import de.neemann.digital.draw.library.LibraryNode;
import javax.swing.event.TreeModelEvent;
import javax.swing.event.TreeModelListener;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
/**
* TreeModel based on a {@link ElementLibrary}
*/
public class LibraryTreeModel implements TreeModel, LibraryListener {
private final LibraryNode root;
private final ElementLibrary library;
private final Filter filter;
private final ArrayList<TreeModelListener> listeners = new ArrayList<>();
private final HashMap<LibraryNode, Container> map;
/**
* Creates a new library tree model
*
* @param library the library
*/
public LibraryTreeModel(ElementLibrary library) {
this(library, null);
}
/**
* Creates a new library tree model
*
* @param library the library
* @param filter used to filter library entries
*/
public LibraryTreeModel(ElementLibrary library, Filter filter) {
root = library.getRoot();
this.library = library;
this.filter = filter;
map = new HashMap<>();
library.addListener(this);
}
/**
* Called to detach the model from the library
*/
public void close() {
library.removeListener(this);
}
@Override
public Object getRoot() {
return root;
}
@Override
public Object getChild(Object o, int i) {
return getContainer((LibraryNode) o).getChild(i);
}
@Override
public int getChildCount(Object o) {
return getContainer((LibraryNode) o).size();
}
@Override
public boolean isLeaf(Object o) {
return ((LibraryNode) o).isLeaf();
}
@Override
public void valueForPathChanged(TreePath treePath, Object o) {
}
@Override
public int getIndexOfChild(Object o, Object o1) {
return getContainer((LibraryNode) o).indexOf((LibraryNode) o1);
}
@Override
public void addTreeModelListener(TreeModelListener treeModelListener) {
listeners.add(treeModelListener);
}
@Override
public void removeTreeModelListener(TreeModelListener treeModelListener) {
listeners.remove(treeModelListener);
}
@Override
public void libraryChanged(LibraryNode node) {
if (node.isLeaf()) {
map.remove(node);
TreeModelEvent treeModelEvent = new TreeModelEvent(this, new TreePath(node.getPath()));
for (TreeModelListener l : listeners)
l.treeNodesChanged(treeModelEvent);
} else {
map.clear();
TreeModelEvent treeModelEvent = new TreeModelEvent(this, new TreePath(root.getPath()));
for (TreeModelListener l : listeners)
l.treeStructureChanged(treeModelEvent);
}
}
/**
* @return the parent of the first leave
*/
public LibraryNode getFirstLeafParent() {
Container c = getContainer(root);
if (c.size() == 0)
return root;
while (true) {
for (LibraryNode n : c)
if (n.isLeaf())
return c.node;
c = getContainer(c.getChild(0));
}
}
/**
* @return true if this model is filtered
*/
public boolean isFiltered() {
return filter != null;
}
private Container getContainer(LibraryNode libraryNode) {
Container c = map.get(libraryNode);
if (c == null) {
c = new Container(libraryNode, filter);
map.put(libraryNode, c);
}
return c;
}
private final class Container implements Iterable<LibraryNode> {
private final ArrayList<LibraryNode> list;
private final LibraryNode node;
private Container(LibraryNode libraryNode, Filter filter) {
list = new ArrayList<>(libraryNode.size());
node = libraryNode;
for (LibraryNode ln : libraryNode) {
if (!ln.isHidden()) {
if (filter == null)
list.add(ln);
else {
if (ln.isLeaf()) {
if (filter.accept(ln))
list.add(ln);
} else {
Container c = new Container(ln, filter);
if (c.size() > 0) {
list.add(ln);
map.put(ln, c);
}
}
}
}
}
}
private LibraryNode getChild(int i) {
return list.get(i);
}
private int size() {
return list.size();
}
private int indexOf(LibraryNode o1) {
return list.indexOf(o1);
}
@Override
public Iterator<LibraryNode> iterator() {
return list.iterator();
}
}
/**
* filter interface
*/
public interface Filter {
/**
* Returns true if the node should be shown in the tree
*
* @param node the node
* @return true if visible
*/
boolean accept(LibraryNode node);
}
}
| 1 | 0.880947 | 1 | 0.880947 | game-dev | MEDIA | 0.335767 | game-dev | 0.791744 | 1 | 0.791744 |
Secrets-of-Sosaria/World | 1,155 | Data/Scripts/Magic/Knight/BookOfChivalry.cs | using System;
using Server.Network;
using Server.Spells;
namespace Server.Items
{
public class BookOfChivalry : Spellbook
{
public override string DefaultDescription{ get{ return "This book is used by knights, in order for them to use various abilities to spread harmony and peace throughout the land. Some books have enhanced properties, that are only effective when the book is held."; } }
public override SpellbookType SpellbookType{ get{ return SpellbookType.Paladin; } }
public override int BookOffset{ get{ return 200; } }
public override int BookCount{ get{ return 10; } }
[Constructable]
public BookOfChivalry() : this( (ulong)0x3FF )
{
}
[Constructable]
public BookOfChivalry( ulong content ) : base( content, 0x2252 )
{
Name = "knightship book";
Layer = Layer.Trinket;
}
public BookOfChivalry( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int)1 ); // version
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
}
}
} | 1 | 0.72529 | 1 | 0.72529 | game-dev | MEDIA | 0.866337 | game-dev | 0.787291 | 1 | 0.787291 |
tunnelvisionlabs/antlrworks2 | 1,837 | org-antlr-works-editor/src/org/antlr/works/editor/grammar/codemodel/impl/FreezableArrayList.java | /*
* Copyright (c) 2012 Sam Harwell, Tunnel Vision Laboratories LLC
* All rights reserved.
*
* The source code of this document is proprietary work, and is not licensed for
* distribution. For information about licensing, contact Sam Harwell at:
* sam@tunnelvisionlabs.com
*/
package org.antlr.works.editor.grammar.codemodel.impl;
import java.util.ArrayList;
import java.util.Collection;
/**
*
* @author Sam Harwell
*/
public class FreezableArrayList<E> extends ArrayList<E> {
private boolean frozen;
public boolean isFrozen() {
return frozen;
}
public void freeze() {
frozen = true;
}
@Override
public E set(int index, E element) {
ensureModifiable();
return super.set(index, element);
}
@Override
public boolean add(E e) {
ensureModifiable();
return super.add(e);
}
@Override
public void add(int index, E element) {
ensureModifiable();
super.add(index, element);
}
@Override
public boolean remove(Object o) {
ensureModifiable();
return super.remove(o);
}
@Override
public void clear() {
ensureModifiable();
super.clear();
}
@Override
public boolean addAll(Collection<? extends E> c) {
ensureModifiable();
return super.addAll(c);
}
@Override
public boolean addAll(int index, Collection<? extends E> c) {
ensureModifiable();
return super.addAll(index, c);
}
@Override
protected void removeRange(int fromIndex, int toIndex) {
ensureModifiable();
super.removeRange(fromIndex, toIndex);
}
protected void ensureModifiable() {
if (isFrozen()) {
throw new IllegalStateException("The collection is frozen.");
}
}
}
| 1 | 0.805522 | 1 | 0.805522 | game-dev | MEDIA | 0.17866 | game-dev | 0.707201 | 1 | 0.707201 |
instructure/canvas-lms | 1,100 | lib/tasks/i18nliner.rake | # frozen_string_literal: true
require "i18nliner/processors/abstract_processor"
require "i18nliner/scope"
require "i18nliner/call_helpers"
require "yaml"
module I18nliner
module Processors
class FeatureFlagYamlProcessor < AbstractProcessor
default_pattern "config/feature_flags/*.yml"
def check_file(file)
@file_count += 1
definitions = YAML.load_file(file)
definitions.each do |name, definition|
definition.deep_symbolize_keys!
[:display_name, :description].each do |field|
@translation_count += 1
@translations.line = name.to_s
value = definition[field]
case value
when String
key = I18nliner::CallHelpers.infer_key(value)
@translations[key] = value
when Hash
value.delete(:wrapper)
key = value.keys[0]
@translations[key.to_s] = value[key]
end
end
end
end
end
end
end
I18nliner::Processors.register(I18nliner::Processors::FeatureFlagYamlProcessor)
| 1 | 0.908959 | 1 | 0.908959 | game-dev | MEDIA | 0.310894 | game-dev | 0.523327 | 1 | 0.523327 |
foxnne/aftersun | 2,930 | src/ecs/systems/render_light_pass.zig | const std = @import("std");
const zmath = @import("zmath");
const ecs = @import("zflecs");
const game = @import("../../aftersun.zig");
const gfx = game.gfx;
const math = game.math;
const components = game.components;
pub fn system() ecs.system_desc_t {
var desc: ecs.system_desc_t = .{};
desc.query.filter.terms[0] = .{ .id = ecs.id(components.Position), .inout = .In };
desc.query.filter.terms[1] = .{ .id = ecs.id(components.LightRenderer) };
desc.query.order_by_component = ecs.id(components.Position);
desc.query.order_by = orderBy;
desc.run = run;
return desc;
}
pub fn run(it: *ecs.iter_t) callconv(.C) void {
const uniforms = gfx.UniformBufferObject{ .mvp = zmath.transpose(game.state.camera.renderTextureMatrix()) };
// Draw diffuse texture sprites using diffuse pipeline
game.state.batcher.begin(.{
.pipeline_handle = game.state.pipeline_default,
.bind_group_handle = game.state.bind_group_light,
.output_handle = game.state.light_output.view_handle,
.clear_color = math.Color.initBytes(0, 0, 0, 255).toGpuColor(),
}) catch unreachable;
while (ecs.iter_next(it)) {
var i: usize = 0;
while (i < it.count()) : (i += 1) {
if (ecs.field(it, components.Position, 1)) |positions| {
var position = positions[i].toF32x4();
position[1] += position[2];
if (ecs.field(it, components.LightRenderer, 2)) |renderers| {
game.state.batcher.sprite(
position,
&game.state.lightmap,
game.state.light_atlas.sprites[renderers[i].index],
.{
.color = renderers[i].color,
},
) catch unreachable;
}
}
}
}
game.state.batcher.end(uniforms, game.state.uniform_buffer_default) catch unreachable;
}
fn orderBy(e1: ecs.entity_t, c1: ?*const anyopaque, e2: ecs.entity_t, c2: ?*const anyopaque) callconv(.C) c_int {
const position_1 = ecs.cast(components.Position, c1);
const position_2 = ecs.cast(components.Position, c2);
const tile_1 = position_1.toTile(0);
const tile_2 = position_1.toTile(0);
if (tile_1.y > tile_2.y) return @as(c_int, 1) else if (tile_1.y < tile_2.y) return @as(c_int, 0);
if (@abs(position_1.y - position_2.y) <= 16) {
const counter1 = if (ecs.get(game.state.world, e1, components.Tile)) |tile| tile.counter else 0;
const counter2 = if (ecs.get(game.state.world, e2, components.Tile)) |tile| tile.counter else 0;
return @as(c_int, @intCast(@intFromBool(counter1 > counter2))) - @as(c_int, @intCast(@intFromBool(counter1 < counter2)));
}
return @as(c_int, @intCast(@intFromBool(position_1.y < position_2.y))) - @as(c_int, @intCast(@intFromBool(position_1.y > position_2.y)));
}
| 1 | 0.808991 | 1 | 0.808991 | game-dev | MEDIA | 0.657654 | game-dev | 0.914948 | 1 | 0.914948 |
Syslifters/offsec-tools | 11,431 | repos/mimikatz/mimikatz/modules/kuhl_m_minesweeper.c | /* Benjamin DELPY `gentilkiwi`
https://blog.gentilkiwi.com
benjamin@gentilkiwi.com
Licence : https://creativecommons.org/licenses/by/4.0/
*/
#include "kuhl_m_minesweeper.h"
const KUHL_M_C kuhl_m_c_minesweeper[] = {
{kuhl_m_minesweeper_infos, L"infos", L"infos"},
//{kuhl_m_minesweeper_bsod, L"bsod", L"bsod"},
};
const KUHL_M kuhl_m_minesweeper = {
L"minesweeper", L"MineSweeper module", NULL,
ARRAYSIZE(kuhl_m_c_minesweeper), kuhl_m_c_minesweeper, NULL, NULL
};
#if defined(_M_X64) || defined(_M_ARM64) // TODO:ARM64
BYTE PTRN_WIN6_Game_SafeGetSingleton[] = {0x48, 0x89, 0x44, 0x24, 0x70, 0x48, 0x85, 0xc0, 0x74, 0x0a, 0x48, 0x8b, 0xc8, 0xe8};
LONG OFFS_WIN6_ToG = -21;
#elif defined(_M_IX86)
BYTE PTRN_WIN6_Game_SafeGetSingleton[] = {0x84, 0xc0, 0x75, 0x07, 0x6a, 0x67, 0xe8};
LONG OFFS_WIN6_ToG = 12;
#endif
const CHAR DISP_MINESWEEPER[] = "012345678.F? !!";
NTSTATUS kuhl_m_minesweeper_infos(int argc, wchar_t * argv[])
{
DWORD dwPid, r, c;
HANDLE hProcess;
PEB Peb;
PIMAGE_NT_HEADERS pNtHeaders;
PVOID G = NULL;
STRUCT_MINESWEEPER_GAME Game;
STRUCT_MINESWEEPER_BOARD Board;
KULL_M_MEMORY_SEARCH sMemory = {{{NULL, NULL}, 0}, NULL};
KULL_M_MEMORY_ADDRESS aRemote = {NULL, NULL}, aBuffer = {PTRN_WIN6_Game_SafeGetSingleton, &KULL_M_MEMORY_GLOBAL_OWN_HANDLE};
BOOL bAlloc = FALSE;
LONG offsetTemp = 0;
CHAR ** field = NULL;
if(kull_m_process_getProcessIdForName(L"minesweeper.exe", &dwPid))
{
if(hProcess = OpenProcess(PROCESS_VM_READ | PROCESS_VM_OPERATION | PROCESS_QUERY_INFORMATION, FALSE, dwPid))
{
if(kull_m_memory_open(KULL_M_MEMORY_TYPE_PROCESS, hProcess, &aRemote.hMemory))
{
if(kull_m_process_peb(aRemote.hMemory, &Peb, FALSE))
{
aRemote.address = Peb.ImageBaseAddress;
if(kull_m_process_ntheaders(&aRemote, &pNtHeaders))
{
sMemory.kull_m_memoryRange.kull_m_memoryAdress.hMemory = aRemote.hMemory;
sMemory.kull_m_memoryRange.kull_m_memoryAdress.address = (LPVOID) pNtHeaders->OptionalHeader.ImageBase;
sMemory.kull_m_memoryRange.size = pNtHeaders->OptionalHeader.SizeOfImage;
if(kull_m_memory_search(&aBuffer, sizeof(PTRN_WIN6_Game_SafeGetSingleton), &sMemory, TRUE))
{
aRemote.address = (PBYTE) sMemory.result + OFFS_WIN6_ToG;
#if defined(_M_X64) || defined(_M_ARM64) // TODO:ARM64
aBuffer.address = &offsetTemp;
if(kull_m_memory_copy(&aBuffer, &aRemote, sizeof(LONG)))
{
aRemote.address = (PBYTE) aRemote.address + 1 + sizeof(LONG) + offsetTemp;
#elif defined(_M_IX86)
aBuffer.address = &aRemote.address;
if(kull_m_memory_copy(&aBuffer, &aRemote, sizeof(PVOID)))
{
#endif
aBuffer.address = &G;
if(kull_m_memory_copy(&aBuffer, &aRemote, sizeof(PVOID)))
{
aRemote.address = G;
aBuffer.address = &Game;
if(kull_m_memory_copy(&aBuffer, &aRemote, sizeof(STRUCT_MINESWEEPER_GAME)))
{
#if defined(_M_IX86)
if(MIMIKATZ_NT_BUILD_NUMBER >= KULL_M_WIN_MIN_BUILD_7)
Game.pBoard = Game.pBoard_WIN7x86;
#endif
aRemote.address = Game.pBoard;
aBuffer.address = &Board;
if(kull_m_memory_copy(&aBuffer, &aRemote, sizeof(STRUCT_MINESWEEPER_BOARD)))
{
kprintf(L"Field : %u r x %u c\nMines : %u\n\n", Board.cbRows, Board.cbColumns, Board.cbMines);
if(field = (CHAR **) LocalAlloc(LPTR, sizeof(CHAR *) * Board.cbRows))
{
for(r = 0, bAlloc = TRUE; (r < Board.cbRows) && bAlloc; r++)
{
if(field[r] = (CHAR *) LocalAlloc(LPTR, sizeof(CHAR) * Board.cbColumns))
bAlloc &= TRUE;
else PRINT_ERROR(L"Memory C (R = %u)\n", r);
}
}
else PRINT_ERROR(L"Memory R\n");
if(bAlloc)
{
kuhl_m_minesweeper_infos_parseField(aRemote.hMemory, Board.ref_visibles, field, TRUE);
kuhl_m_minesweeper_infos_parseField(aRemote.hMemory, Board.ref_mines, field, FALSE);
for(r = 0; r < Board.cbRows; r++)
{
kprintf(L"\t");
for(c = 0; c < Board.cbColumns; c++)
kprintf(L"%C ", field[r][c]);
kprintf(L"\n");
}
}
if(field)
{
for(r = 0; r < Board.cbRows; r++)
{
if(field[r])
LocalFree(field[r]);
}
LocalFree(field);
}
}
else PRINT_ERROR(L"Board copy\n");
}
else PRINT_ERROR(L"Game copy\n");
}
else PRINT_ERROR(L"G copy\n");
}
else PRINT_ERROR(L"Global copy\n");
}
else PRINT_ERROR(L"Search is KO\n");
LocalFree(pNtHeaders);
}
else PRINT_ERROR(L"Minesweeper NT Headers\n");
}
else PRINT_ERROR(L"Minesweeper PEB\n");
kull_m_memory_close(aRemote.hMemory);
}
CloseHandle(hProcess);
}
else PRINT_ERROR_AUTO(L"OpenProcess");
}
else PRINT_ERROR(L"No MineSweeper in memory!\n");
return STATUS_SUCCESS;
}
void kuhl_m_minesweeper_infos_parseField(PKULL_M_MEMORY_HANDLE hMemory, PSTRUCT_MINESWEEPER_REF_ELEMENT base, CHAR ** field, BOOL isVisible)
{
STRUCT_MINESWEEPER_REF_ELEMENT ref_first_element;
PSTRUCT_MINESWEEPER_REF_ELEMENT * ref_columns_elements;
STRUCT_MINESWEEPER_REF_ELEMENT ref_column_element;
DWORD c, r, szFinalElement = isVisible ? sizeof(DWORD) : sizeof(BYTE);
KULL_M_MEMORY_ADDRESS aRemote = {base, hMemory}, aLocal = {&ref_first_element, &KULL_M_MEMORY_GLOBAL_OWN_HANDLE};
if(kull_m_memory_copy(&aLocal, &aRemote, sizeof(STRUCT_MINESWEEPER_REF_ELEMENT)))
{
if(ref_columns_elements = (PSTRUCT_MINESWEEPER_REF_ELEMENT *) LocalAlloc(LPTR, sizeof(PSTRUCT_MINESWEEPER_REF_ELEMENT) * ref_first_element.cbElements))
{
aLocal.address = ref_columns_elements;
aRemote.address = ref_first_element.elements;
if(kull_m_memory_copy(&aLocal, &aRemote, ref_first_element.cbElements * sizeof(PSTRUCT_MINESWEEPER_REF_ELEMENT)))
{
for(c = 0; c < ref_first_element.cbElements; c++)
{
aLocal.address = &ref_column_element;
aRemote.address = ref_columns_elements[c];
if(kull_m_memory_copy(&aLocal, &aRemote, sizeof(STRUCT_MINESWEEPER_REF_ELEMENT)))
{
if(aLocal.address = LocalAlloc(LPTR, szFinalElement * ref_column_element.cbElements))
{
aRemote.address = ref_column_element.elements;
if(kull_m_memory_copy(&aLocal, &aRemote, szFinalElement * ref_column_element.cbElements))
{
for(r = 0; r < ref_column_element.cbElements; r++)
{
if(isVisible)
field[r][c] = DISP_MINESWEEPER[((DWORD *)(aLocal.address))[r]];
else if(((BYTE *)(aLocal.address))[r])
field[r][c] = '*';
}
}
else PRINT_ERROR(L"Unable to read elements from column: %u\n", c);
LocalFree(aLocal.address);
}
}
else PRINT_ERROR(L"Unable to read references from column: %u\n", c);
}
}
else PRINT_ERROR(L"Unable to read references\n");
LocalFree(ref_columns_elements);
}
}
else PRINT_ERROR(L"Unable to read first element\n");
}
//
//#include "../../modules/kull_m_remotelib.h"
//#ifdef _M_X64
//BYTE CALL_JMP_X64[] = { 0x48, 0xb8,
// 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// 0xff, 0xe0};
//BYTE PTRN_WIN6_Explode[] = {0x57, 0x41, 0x54, 0x41, 0x55, 0x48, 0x83, 0xec, 0x20, 0x48, 0x8b, 0x41, 0x18};
//LONG OFFS_WIN6_ToExplode = -15;
//#endif
//
//NTSTATUS kuhl_m_minesweeper_bsod(int argc, wchar_t * argv[])
//{
// DWORD dwPid;
// HANDLE hProcess;
// PEB Peb;
// PIMAGE_NT_HEADERS pNtHeaders;
// KULL_M_MEMORY_SEARCH sMemory = {{{NULL, NULL}, 0}, NULL};
// KULL_M_MEMORY_ADDRESS aRemote = {NULL, NULL}, aBuffer = {PTRN_WIN6_Explode, &KULL_M_MEMORY_GLOBAL_OWN_HANDLE};
//
// REMOTE_EXT extensions[] = {
// {L"kernel32.dll", "CreateFileA", (PVOID) 0x4a4a4a4a4a4a4a4a, NULL},
// {L"kernel32.dll", "CloseHandle", (PVOID) 0x4b4b4b4b4b4b4b4b, NULL},
// {L"kernel32.dll", "DeviceIoControl", (PVOID) 0x4c4c4c4c4c4c4c4c, NULL},
// };
// MULTIPLE_REMOTE_EXT extForCb = {ARRAYSIZE(extensions), extensions};
//
// if(kull_m_process_getProcessIdForName(L"minesweeper.exe", &dwPid))
// {
// if(hProcess = OpenProcess(PROCESS_VM_READ | PROCESS_VM_WRITE | PROCESS_VM_OPERATION | PROCESS_QUERY_INFORMATION, FALSE, dwPid))
// {
// if(kull_m_memory_open(KULL_M_MEMORY_TYPE_PROCESS, hProcess, &aRemote.hMemory))
// {
// if(kull_m_process_peb(aRemote.hMemory, &Peb, FALSE))
// {
// aRemote.address = Peb.ImageBaseAddress;
// if(kull_m_process_ntheaders(&aRemote, &pNtHeaders))
// {
// sMemory.kull_m_memoryRange.kull_m_memoryAdress.hMemory = aRemote.hMemory;
// sMemory.kull_m_memoryRange.kull_m_memoryAdress.address = (LPVOID) pNtHeaders->OptionalHeader.ImageBase;
// sMemory.kull_m_memoryRange.size = pNtHeaders->OptionalHeader.SizeOfImage;
// if(kull_m_memory_search(&aBuffer, sizeof(PTRN_WIN6_Explode), &sMemory, TRUE))
// {
// sMemory.result = (PBYTE) sMemory.result + OFFS_WIN6_ToExplode;
// aRemote.address = NULL;
// if(kull_m_remotelib_CreateRemoteCodeWitthPatternReplace(aRemote.hMemory, kuhl_m_minesweeper_bsod_thread, (DWORD) ((PBYTE) kuhl_m_minesweeper_bsod_thread_end - (PBYTE) kuhl_m_minesweeper_bsod_thread), &extForCb, &aRemote))
// {
// *(PVOID *) (CALL_JMP_X64 + 2) = aRemote.address;
// aBuffer.address = CALL_JMP_X64;
// aRemote.address = sMemory.result;
// if(kull_m_memory_copy(&aRemote, &aBuffer, sizeof(CALL_JMP_X64)))
// kprintf(L"WARNING! Next Minesweeper error will BSOD!\n");
// }
// else PRINT_ERROR(L"Unable to create remote functions\n");
// }
// else PRINT_ERROR(L"Search is KO\n");
// LocalFree(pNtHeaders);
// }
// else PRINT_ERROR(L"Minesweeper NT Headers\n");
// }
// else PRINT_ERROR(L"Minesweeper PEB\n");
// kull_m_memory_close(aRemote.hMemory);
// }
// CloseHandle(hProcess);
// }
// else PRINT_ERROR_AUTO(L"OpenProcess");
// }
// else PRINT_ERROR(L"No MineSweeper in memory!\n");
// return STATUS_SUCCESS;
//}
//
//typedef HANDLE (WINAPI * PCREATEFILEA) (__in LPCSTR lpFileName, __in DWORD dwDesiredAccess, __in DWORD dwShareMode, __in_opt LPSECURITY_ATTRIBUTES lpSecurityAttributes, __in DWORD dwCreationDisposition, __in DWORD dwFlagsAndAttributes, __in_opt HANDLE hTemplateFile);
//typedef BOOL (WINAPI * PDEVICEIOCONTROL) (__in HANDLE hDevice, __in DWORD dwIoControlCode, __in_bcount_opt(nInBufferSize) LPVOID lpInBuffer, __in DWORD nInBufferSize, __out_bcount_part_opt(nOutBufferSize, *lpBytesReturned) LPVOID lpOutBuffer, __in DWORD nOutBufferSize, __out_opt LPDWORD lpBytesReturned, __inout_opt LPOVERLAPPED lpOverlapped );
//typedef BOOL (WINAPI * PCLOSEHANDLE) (__in HANDLE hObject);
//#pragma optimize("", off)
//void __fastcall kuhl_m_minesweeper_bsod_thread(PVOID a, INT b, INT c, BOOL d)
//{
// DWORD fn[] = {0x5c2e5c5c, 'imim', '\0vrd'};
// HANDLE hDriver = ((PCREATEFILEA) 0x4a4a4a4a4a4a4a4a)((PSTR) fn, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
// if(hDriver && hDriver != INVALID_HANDLE_VALUE)
// {
// ((PDEVICEIOCONTROL) 0x4c4c4c4c4c4c4c4c)(hDriver, IOCTL_MIMIDRV_BSOD, NULL, 0, NULL, 0, NULL, NULL);
// ((PCLOSEHANDLE) 0x4b4b4b4b4b4b4b4b)(hDriver); // !
// }
//}
//DWORD kuhl_m_minesweeper_bsod_thread_end(){return 'sbsm';}
//#pragma optimize("", on) | 1 | 0.94696 | 1 | 0.94696 | game-dev | MEDIA | 0.522989 | game-dev | 0.921537 | 1 | 0.921537 |
puyoai/puyoai | 9,340 | src/cpu/mayah/beam_thinker.cc | #include "beam_thinker.h"
#include <map>
#include <set>
#include <unordered_set>
#include <gflags/gflags.h>
#include "base/time.h"
#include "base/wait_group.h"
#include "core/field_pretty_printer.h"
#include "core/kumipuyo_seq_generator.h"
#include "core/plan/plan.h"
#include "core/rensa/rensa_detector.h"
#include <iostream>
DEFINE_int32(beam_width, 400, "beam width");
DEFINE_int32(beam_depth, 50, "beam depth");
DEFINE_int32(beam_num, 12, "beam iteration number");
using namespace std;
namespace {
struct SearchResult {
std::set<Decision> firstDecisions;
int maxChains = 0;
};
struct State {
State(const CoreField& field, const Decision& firstDecision, double stateScore, int maxChains,
int total_frames) :
field(field),
firstDecision(firstDecision),
stateScore(stateScore),
maxChains(maxChains),
total_frames(total_frames)
{
}
#if 0
friend bool operator<(const State& lhs, const State& rhs) { return lhs.stateScore < rhs.stateScore; }
#endif
friend bool operator>(const State& lhs, const State& rhs) { return lhs.stateScore > rhs.stateScore; }
CoreField field;
Decision firstDecision;
double stateScore = 0;
int maxChains = 0;
int total_frames = 0;
int pending_enemy_score = 0;
int pending_enemy_ojama_drop_frame = 0;
};
std::pair<double, int> evalSuperLight(const CoreField& fieldBeforeRensa)
{
int maxChains = 0;
auto callback = [&maxChains](CoreField&& complementedField, const ColumnPuyoList& /*cpl*/) {
maxChains = std::max(maxChains, complementedField.simulateFast());
};
static const bool prohibits[FieldConstant::MAP_WIDTH] {};
RensaDetector::detectByDropStrategy(fieldBeforeRensa, prohibits, PurposeForFindingRensa::FOR_FIRE, 2, 13, callback);
double maxScore = 0;
maxScore += maxChains * 1000;
double averageHeight = 0;
for (int x = 1; x <= 6; ++x)
averageHeight += fieldBeforeRensa.height(x);
averageHeight /= 6;
double ushapeScore = 0;
for (int x = 1; x <= 6; ++x) {
static const int DIFF[] = { 0, 3, 0, -1, -1, 0, 3, 0 };
ushapeScore -= std::abs((fieldBeforeRensa.height(x) - averageHeight) - DIFF[x]);
}
maxScore += 60 * ushapeScore;
#if 1
// VALLEY
for (int x = 1; x <= 6; ++x) {
if (fieldBeforeRensa.valleyDepth(x) >= 4) {
maxScore -= 200;
}
}
// RIDGE
for (int x = 1; x <= 6; ++x) {
if (fieldBeforeRensa.ridgeHeight(x) >= 4) {
maxScore -= 200;
}
}
#endif
return std::make_pair(maxScore, maxChains);
}
SearchResult run(const std::vector<State>& initialStates, KumipuyoSeq seq, int maxSearchTurns,
std::mutex& mu)
{
SearchResult result;
std::vector<State> currentStates(initialStates);
int maxOverallFiredChains = 0;
int maxOverallFiredScore = 0;
std::vector<State> nextStates;
nextStates.reserve(100000);
std::vector<double> time(std::max(maxSearchTurns, 10));
double beginTime = currentTime();
for (int turn = 3; turn < maxSearchTurns; ++turn) {
time[turn] = currentTime();
seq.dropFront();
std::unordered_set<size_t> visited;
int maxFiredScore = 0;
int maxFiredRensa = 0;
for (const State& s : currentStates) {
Plan::iterateAvailablePlans(s.field, seq, 1, [&](const RefPlan& plan) {
const CoreField& fieldBeforeRensa = plan.field();
if (!visited.insert(fieldBeforeRensa.hash()).second)
return;
int total_frames = s.total_frames + plan.totalFrames() + FRAMES_PREPARING_NEXT;
if (plan.isRensaPlan()) {
maxOverallFiredScore = std::max(maxOverallFiredScore, plan.rensaResult().score);
maxOverallFiredChains = std::max(maxOverallFiredChains, plan.rensaResult().chains);
maxFiredScore = std::max(maxFiredScore, plan.rensaResult().score);
maxFiredRensa = std::max(maxFiredRensa, plan.rensaResult().chains);
nextStates.emplace_back(fieldBeforeRensa, s.firstDecision, plan.rensaResult().chains,
plan.rensaResult().chains, total_frames);
return;
}
double maxScore;
int maxChains;
std::tie(maxScore, maxChains) = evalSuperLight(fieldBeforeRensa);
nextStates.emplace_back(plan.field(), s.firstDecision, maxScore, maxChains, total_frames);
});
}
std::sort(nextStates.begin(), nextStates.end(), std::greater<State>());
int beamWidth = FLAGS_beam_width;
if (turn <= 6) {
beamWidth = 22 * 22;
}
if (nextStates.size() > static_cast<size_t>(beamWidth)) {
nextStates.erase(nextStates.begin() + beamWidth, nextStates.end());
}
std::swap(currentStates, nextStates);
nextStates.clear();
if (false) {
cout << "turn=" << turn
<< " score=" << currentStates.front().stateScore
<< " chains=" << currentStates.front().maxChains
<< " first=" << currentStates.front().firstDecision
<< " : fired_score=" << maxFiredScore
<< " fired_rensa=" << maxFiredRensa
<< endl;
std::map<Decision, int> m;
for (const auto& s : currentStates) {
m[s.firstDecision] += 1;
}
cout << "decision kind = " << m.size() << endl;
for (const auto& entry : m) {
cout << entry.first << " " << entry.second << endl;
}
FieldPrettyPrinter::print(currentStates.front().field.toPlainField(), KumipuyoSeq());
}
}
double endTime = currentTime();
if (false) {
lock_guard<mutex> lock(mu);
if (!currentStates.empty()) {
cout << "FIRED_CHAINS=" << maxOverallFiredChains
<< " FIRED_SCORE=" << maxOverallFiredScore
<< " DECISION=" << currentStates.front().firstDecision
<< " TIME=" << (endTime - beginTime)
<< " TURN4_TIME=" << (time[4] - beginTime)
<< " TURN5_TIME=" << (time[5] - beginTime)
<< " TURN6_TIME=" << (time[6] - beginTime) << endl;
} else {
cout << "EMPTY!" << endl;
result.maxChains = -1;
return result;
}
}
result.maxChains = maxOverallFiredChains;
result.firstDecisions.insert(currentStates.front().firstDecision);
return result;
}
} // anonymous namespace
DropDecision BeamThinker::think(int /*frameId*/, const CoreField& field, const KumipuyoSeq& seq,
const PlayerState& /*me*/, const PlayerState& /*enemy*/, bool /*fast*/) const
{
// If large enough, fire.
if (true) {
Decision tmpd;
Plan::iterateAvailablePlans(field, seq, 2, [&](const RefPlan& plan) {
if (plan.isRensaPlan() && plan.rensaResult().chains >= 14)
tmpd = plan.firstDecision();
});
if (tmpd.isValid()) {
return DropDecision(tmpd);
}
}
// Decision -> max chains
std::map<Decision, int> score;
// Make initial states (the first move).
std::vector<State> currentStates;
Plan::iterateAvailablePlans(field, seq, 1, [&](const RefPlan& plan) {
currentStates.emplace_back(plan.field(), plan.firstDecision(), 0, 0, plan.totalFrames());
// Don't put 11th if rensa is not too good.
if (plan.field().height(3) >= 11) {
score[plan.firstDecision()] -= 100;
}
});
// The second move.
std::vector<State> nextStates;
KumipuyoSeq subSeq = seq.subsequence(1);
for (const auto& s : currentStates) {
Plan::iterateAvailablePlans(s.field, subSeq, 1, [&](const RefPlan& plan) {
int total_frames = s.total_frames + plan.totalFrames() + FRAMES_PREPARING_NEXT;
nextStates.emplace_back(plan.field(), s.firstDecision, 0, 0, total_frames);
});
}
WaitGroup wg;
std::mutex mu;
const int maxSearchTurns = std::min(FLAGS_beam_depth, (78 - field.countPuyos()) / 2 + 4);
#if 0
cout << "maxSearchTurns = " << maxSearchTurns << endl;
#endif
for (int k = 0; k < FLAGS_beam_num; ++k) {
wg.add(1);
executor_->submit([&]() {
KumipuyoSeq tmpSeq(seq.subsequence(2));
tmpSeq.append(KumipuyoSeqGenerator::generateRandomSequence(40));
SearchResult searchResult = run(nextStates, tmpSeq, maxSearchTurns, mu_);
{
lock_guard<mutex> lk(mu);
for (const auto& d : searchResult.firstDecisions) {
score[d] += searchResult.maxChains;
}
}
// wg.done() should be called after releasing mu, because of deadlock.
wg.done();
});
}
wg.waitUntilDone();
Decision d;
int s = 0;
for (const auto& entry : score) {
if (s < entry.second) {
s = entry.second;
d = entry.first;
}
}
return DropDecision(d, "BY BEAM");
}
| 1 | 0.965022 | 1 | 0.965022 | game-dev | MEDIA | 0.405246 | game-dev | 0.971877 | 1 | 0.971877 |
randomguy3725/MoonLight | 1,109 | src/main/java/net/minecraft/client/model/ModelHumanoidHead.java | package net.minecraft.client.model;
import net.minecraft.entity.Entity;
public class ModelHumanoidHead extends ModelSkeletonHead
{
private final ModelRenderer head = new ModelRenderer(this, 32, 0);
public ModelHumanoidHead()
{
super(0, 0, 64, 64);
this.head.addBox(-4.0F, -8.0F, -4.0F, 8, 8, 8, 0.25F);
this.head.setRotationPoint(0.0F, 0.0F, 0.0F);
}
public void render(Entity entityIn, float p_78088_2_, float p_78088_3_, float p_78088_4_, float p_78088_5_, float p_78088_6_, float scale)
{
super.render(entityIn, p_78088_2_, p_78088_3_, p_78088_4_, p_78088_5_, p_78088_6_, scale);
this.head.render(scale);
}
public void setRotationAngles(float limbSwing, float limbSwingAmount, float ageInTicks, float netHeadYaw, float headPitch, float scaleFactor, Entity entityIn)
{
super.setRotationAngles(limbSwing, limbSwingAmount, ageInTicks, netHeadYaw, headPitch, scaleFactor, entityIn);
this.head.rotateAngleY = this.skeletonHead.rotateAngleY;
this.head.rotateAngleX = this.skeletonHead.rotateAngleX;
}
}
| 1 | 0.553999 | 1 | 0.553999 | game-dev | MEDIA | 0.988142 | game-dev | 0.801117 | 1 | 0.801117 |
aiekick/Lumo | 23,238 | 3rdparty/taskflow/3rd-party/tbb/examples/graph/fgbzip2/decompress.cpp | /*
Copyright (c) 2005-2020 Intel Corporation
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.
*/
/*-------------------------------------------------------------*/
/*--- Decompression machinery ---*/
/*--- decompress.cpp ---*/
/*-------------------------------------------------------------*/
/* ------------------------------------------------------------------
The original source for this example:
This file is part of bzip2/libbzip2, a program and library for
lossless, block-sorting data compression.
bzip2/libbzip2 version 1.0.6 of 6 September 2010
Copyright (C) 1996-2010 Julian Seward <jseward@bzip.org>
This program, "bzip2", the associated library "libbzip2", and all
documentation, are copyright (C) 1996-2010 Julian R Seward. All
rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. 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.
3. Altered source versions must be plainly marked as such, and must
not be misrepresented as being the original software.
4. The name of the author may not be used to endorse or promote
products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Julian Seward, jseward@bzip.org
bzip2/libbzip2 version 1.0.6 of 6 September 2010
------------------------------------------------------------------ */
#include "bzlib_private.h"
/*---------------------------------------------------*/
static
void makeMaps_d ( DState* s )
{
Int32 i;
s->nInUse = 0;
for (i = 0; i < 256; i++)
if (s->inUse[i]) {
s->seqToUnseq[s->nInUse] = i;
s->nInUse++;
}
}
/*---------------------------------------------------*/
#define RETURN(rrr) \
{ retVal = rrr; goto save_state_and_return; };
#define GET_BITS(lll,vvv,nnn) \
case lll: s->state = lll; \
while (True) { \
if (s->bsLive >= nnn) { \
UInt32 v; \
v = (s->bsBuff >> \
(s->bsLive-nnn)) & ((1 << nnn)-1); \
s->bsLive -= nnn; \
vvv = v; \
break; \
} \
if (s->strm->avail_in == 0) RETURN(BZ_OK); \
s->bsBuff \
= (s->bsBuff << 8) | \
((UInt32) \
(*((UChar*)(s->strm->next_in)))); \
s->bsLive += 8; \
s->strm->next_in++; \
s->strm->avail_in--; \
s->strm->total_in_lo32++; \
if (s->strm->total_in_lo32 == 0) \
s->strm->total_in_hi32++; \
}
#define GET_UCHAR(lll,uuu) \
GET_BITS(lll,uuu,8)
#define GET_BIT(lll,uuu) \
GET_BITS(lll,uuu,1)
/*---------------------------------------------------*/
#define GET_MTF_VAL(label1,label2,lval) \
{ \
if (groupPos == 0) { \
groupNo++; \
if (groupNo >= nSelectors) \
RETURN(BZ_DATA_ERROR); \
groupPos = BZ_G_SIZE; \
gSel = s->selector[groupNo]; \
gMinlen = s->minLens[gSel]; \
gLimit = &(s->limit[gSel][0]); \
gPerm = &(s->perm[gSel][0]); \
gBase = &(s->base[gSel][0]); \
} \
groupPos--; \
zn = gMinlen; \
GET_BITS(label1, zvec, zn); \
while (1) { \
if (zn > 20 /* the longest code */) \
RETURN(BZ_DATA_ERROR); \
if (zvec <= gLimit[zn]) break; \
zn++; \
GET_BIT(label2, zj); \
zvec = (zvec << 1) | zj; \
}; \
if (zvec - gBase[zn] < 0 \
|| zvec - gBase[zn] >= BZ_MAX_ALPHA_SIZE) \
RETURN(BZ_DATA_ERROR); \
lval = gPerm[zvec - gBase[zn]]; \
}
/*---------------------------------------------------*/
Int32 BZ2_decompress ( DState* s )
{
UChar uc;
Int32 retVal;
Int32 minLen, maxLen;
bz_stream* strm = s->strm;
/* stuff that needs to be saved/restored */
Int32 i;
Int32 j;
Int32 t;
Int32 alphaSize;
Int32 nGroups;
Int32 nSelectors;
Int32 EOB;
Int32 groupNo;
Int32 groupPos;
Int32 nextSym;
Int32 nblockMAX;
Int32 nblock;
Int32 es;
Int32 N;
Int32 curr;
Int32 zt;
Int32 zn;
Int32 zvec;
Int32 zj;
Int32 gSel;
Int32 gMinlen;
Int32* gLimit;
Int32* gBase;
Int32* gPerm;
if (s->state == BZ_X_MAGIC_1) {
/*initialise the save area*/
s->save_i = 0;
s->save_j = 0;
s->save_t = 0;
s->save_alphaSize = 0;
s->save_nGroups = 0;
s->save_nSelectors = 0;
s->save_EOB = 0;
s->save_groupNo = 0;
s->save_groupPos = 0;
s->save_nextSym = 0;
s->save_nblockMAX = 0;
s->save_nblock = 0;
s->save_es = 0;
s->save_N = 0;
s->save_curr = 0;
s->save_zt = 0;
s->save_zn = 0;
s->save_zvec = 0;
s->save_zj = 0;
s->save_gSel = 0;
s->save_gMinlen = 0;
s->save_gLimit = NULL;
s->save_gBase = NULL;
s->save_gPerm = NULL;
}
/*restore from the save area*/
i = s->save_i;
j = s->save_j;
t = s->save_t;
alphaSize = s->save_alphaSize;
nGroups = s->save_nGroups;
nSelectors = s->save_nSelectors;
EOB = s->save_EOB;
groupNo = s->save_groupNo;
groupPos = s->save_groupPos;
nextSym = s->save_nextSym;
nblockMAX = s->save_nblockMAX;
nblock = s->save_nblock;
es = s->save_es;
N = s->save_N;
curr = s->save_curr;
zt = s->save_zt;
zn = s->save_zn;
zvec = s->save_zvec;
zj = s->save_zj;
gSel = s->save_gSel;
gMinlen = s->save_gMinlen;
gLimit = s->save_gLimit;
gBase = s->save_gBase;
gPerm = s->save_gPerm;
retVal = BZ_OK;
switch (s->state) {
GET_UCHAR(BZ_X_MAGIC_1, uc);
if (uc != BZ_HDR_B) RETURN(BZ_DATA_ERROR_MAGIC);
GET_UCHAR(BZ_X_MAGIC_2, uc);
if (uc != BZ_HDR_Z) RETURN(BZ_DATA_ERROR_MAGIC);
GET_UCHAR(BZ_X_MAGIC_3, uc)
if (uc != BZ_HDR_h) RETURN(BZ_DATA_ERROR_MAGIC);
GET_BITS(BZ_X_MAGIC_4, s->blockSize100k, 8)
if (s->blockSize100k < (BZ_HDR_0 + 1) ||
s->blockSize100k > (BZ_HDR_0 + 9)) RETURN(BZ_DATA_ERROR_MAGIC);
s->blockSize100k -= BZ_HDR_0;
if (s->smallDecompress) {
s->ll16 = (UInt16*)BZALLOC( s->blockSize100k * 100000 * sizeof(UInt16) );
s->ll4 = (UChar*)BZALLOC(
((1 + s->blockSize100k * 100000) >> 1) * sizeof(UChar)
);
if (s->ll16 == NULL || s->ll4 == NULL) RETURN(BZ_MEM_ERROR);
} else {
s->tt = (UInt32*)BZALLOC( s->blockSize100k * 100000 * sizeof(Int32) );
if (s->tt == NULL) RETURN(BZ_MEM_ERROR);
}
GET_UCHAR(BZ_X_BLKHDR_1, uc);
if (uc == 0x17) goto endhdr_2;
if (uc != 0x31) RETURN(BZ_DATA_ERROR);
GET_UCHAR(BZ_X_BLKHDR_2, uc);
if (uc != 0x41) RETURN(BZ_DATA_ERROR);
GET_UCHAR(BZ_X_BLKHDR_3, uc);
if (uc != 0x59) RETURN(BZ_DATA_ERROR);
GET_UCHAR(BZ_X_BLKHDR_4, uc);
if (uc != 0x26) RETURN(BZ_DATA_ERROR);
GET_UCHAR(BZ_X_BLKHDR_5, uc);
if (uc != 0x53) RETURN(BZ_DATA_ERROR);
GET_UCHAR(BZ_X_BLKHDR_6, uc);
if (uc != 0x59) RETURN(BZ_DATA_ERROR);
s->currBlockNo++;
if (s->verbosity >= 2)
VPrintf1 ( "\n [%d: huff+mtf ", s->currBlockNo );
s->storedBlockCRC = 0;
GET_UCHAR(BZ_X_BCRC_1, uc);
s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc);
GET_UCHAR(BZ_X_BCRC_2, uc);
s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc);
GET_UCHAR(BZ_X_BCRC_3, uc);
s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc);
GET_UCHAR(BZ_X_BCRC_4, uc);
s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc);
GET_BITS(BZ_X_RANDBIT, s->blockRandomised, 1);
s->origPtr = 0;
GET_UCHAR(BZ_X_ORIGPTR_1, uc);
s->origPtr = (s->origPtr << 8) | ((Int32)uc);
GET_UCHAR(BZ_X_ORIGPTR_2, uc);
s->origPtr = (s->origPtr << 8) | ((Int32)uc);
GET_UCHAR(BZ_X_ORIGPTR_3, uc);
s->origPtr = (s->origPtr << 8) | ((Int32)uc);
if (s->origPtr < 0)
RETURN(BZ_DATA_ERROR);
if (s->origPtr > 10 + 100000*s->blockSize100k)
RETURN(BZ_DATA_ERROR);
/*--- Receive the mapping table ---*/
for (i = 0; i < 16; i++) {
GET_BIT(BZ_X_MAPPING_1, uc);
if (uc == 1)
s->inUse16[i] = True; else
s->inUse16[i] = False;
}
for (i = 0; i < 256; i++) s->inUse[i] = False;
for (i = 0; i < 16; i++)
if (s->inUse16[i])
for (j = 0; j < 16; j++) {
GET_BIT(BZ_X_MAPPING_2, uc);
if (uc == 1) s->inUse[i * 16 + j] = True;
}
makeMaps_d ( s );
if (s->nInUse == 0) RETURN(BZ_DATA_ERROR);
alphaSize = s->nInUse+2;
/*--- Now the selectors ---*/
GET_BITS(BZ_X_SELECTOR_1, nGroups, 3);
if (nGroups < 2 || nGroups > 6) RETURN(BZ_DATA_ERROR);
GET_BITS(BZ_X_SELECTOR_2, nSelectors, 15);
if (nSelectors < 1) RETURN(BZ_DATA_ERROR);
for (i = 0; i < nSelectors; i++) {
j = 0;
while (True) {
GET_BIT(BZ_X_SELECTOR_3, uc);
if (uc == 0) break;
j++;
if (j >= nGroups) RETURN(BZ_DATA_ERROR);
}
s->selectorMtf[i] = j;
}
/*--- Undo the MTF values for the selectors. ---*/
{
UChar pos[BZ_N_GROUPS], tmp, v;
for (v = 0; v < nGroups; v++) pos[v] = v;
for (i = 0; i < nSelectors; i++) {
v = s->selectorMtf[i];
tmp = pos[v];
while (v > 0) { pos[v] = pos[v-1]; v--; }
pos[0] = tmp;
s->selector[i] = tmp;
}
}
/*--- Now the coding tables ---*/
for (t = 0; t < nGroups; t++) {
GET_BITS(BZ_X_CODING_1, curr, 5);
for (i = 0; i < alphaSize; i++) {
while (True) {
if (curr < 1 || curr > 20) RETURN(BZ_DATA_ERROR);
GET_BIT(BZ_X_CODING_2, uc);
if (uc == 0) break;
GET_BIT(BZ_X_CODING_3, uc);
if (uc == 0) curr++; else curr--;
}
s->len[t][i] = curr;
}
}
/*--- Create the Huffman decoding tables ---*/
for (t = 0; t < nGroups; t++) {
minLen = 32;
maxLen = 0;
for (i = 0; i < alphaSize; i++) {
if (s->len[t][i] > maxLen) maxLen = s->len[t][i];
if (s->len[t][i] < minLen) minLen = s->len[t][i];
}
BZ2_hbCreateDecodeTables (
&(s->limit[t][0]),
&(s->base[t][0]),
&(s->perm[t][0]),
&(s->len[t][0]),
minLen, maxLen, alphaSize
);
s->minLens[t] = minLen;
}
/*--- Now the MTF values ---*/
EOB = s->nInUse+1;
nblockMAX = 100000 * s->blockSize100k;
groupNo = -1;
groupPos = 0;
for (i = 0; i <= 255; i++) s->unzftab[i] = 0;
/*-- MTF init --*/
{
Int32 ii, jj, kk;
kk = MTFA_SIZE-1;
for (ii = 256 / MTFL_SIZE - 1; ii >= 0; ii--) {
for (jj = MTFL_SIZE-1; jj >= 0; jj--) {
s->mtfa[kk] = (UChar)(ii * MTFL_SIZE + jj);
kk--;
}
s->mtfbase[ii] = kk + 1;
}
}
/*-- end MTF init --*/
nblock = 0;
GET_MTF_VAL(BZ_X_MTF_1, BZ_X_MTF_2, nextSym);
while (True) {
if (nextSym == EOB) break;
if (nextSym == BZ_RUNA || nextSym == BZ_RUNB) {
es = -1;
N = 1;
do {
/* Check that N doesn't get too big, so that es doesn't
go negative. The maximum value that can be
RUNA/RUNB encoded is equal to the block size (post
the initial RLE), viz, 900k, so bounding N at 2
million should guard against overflow without
rejecting any legitimate inputs. */
if (N >= 2*1024*1024) RETURN(BZ_DATA_ERROR);
if (nextSym == BZ_RUNA) es = es + (0+1) * N; else
if (nextSym == BZ_RUNB) es = es + (1+1) * N;
N = N * 2;
GET_MTF_VAL(BZ_X_MTF_3, BZ_X_MTF_4, nextSym);
}
while (nextSym == BZ_RUNA || nextSym == BZ_RUNB);
es++;
uc = s->seqToUnseq[ s->mtfa[s->mtfbase[0]] ];
s->unzftab[uc] += es;
if (s->smallDecompress)
while (es > 0) {
if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR);
s->ll16[nblock] = (UInt16)uc;
nblock++;
es--;
}
else
while (es > 0) {
if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR);
s->tt[nblock] = (UInt32)uc;
nblock++;
es--;
};
continue;
} else {
if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR);
/*-- uc = MTF ( nextSym-1 ) --*/
{
Int32 ii, jj, kk, pp, lno, off;
UInt32 nn;
nn = (UInt32)(nextSym - 1);
if (nn < MTFL_SIZE) {
/* avoid general-case expense */
pp = s->mtfbase[0];
uc = s->mtfa[pp+nn];
while (nn > 3) {
Int32 z = pp+nn;
s->mtfa[(z) ] = s->mtfa[(z)-1];
s->mtfa[(z)-1] = s->mtfa[(z)-2];
s->mtfa[(z)-2] = s->mtfa[(z)-3];
s->mtfa[(z)-3] = s->mtfa[(z)-4];
nn -= 4;
}
while (nn > 0) {
s->mtfa[(pp+nn)] = s->mtfa[(pp+nn)-1]; nn--;
};
s->mtfa[pp] = uc;
} else {
/* general case */
lno = nn / MTFL_SIZE;
off = nn % MTFL_SIZE;
pp = s->mtfbase[lno] + off;
uc = s->mtfa[pp];
while (pp > s->mtfbase[lno]) {
s->mtfa[pp] = s->mtfa[pp-1]; pp--;
};
s->mtfbase[lno]++;
while (lno > 0) {
s->mtfbase[lno]--;
s->mtfa[s->mtfbase[lno]]
= s->mtfa[s->mtfbase[lno-1] + MTFL_SIZE - 1];
lno--;
}
s->mtfbase[0]--;
s->mtfa[s->mtfbase[0]] = uc;
if (s->mtfbase[0] == 0) {
kk = MTFA_SIZE-1;
for (ii = 256 / MTFL_SIZE-1; ii >= 0; ii--) {
for (jj = MTFL_SIZE-1; jj >= 0; jj--) {
s->mtfa[kk] = s->mtfa[s->mtfbase[ii] + jj];
kk--;
}
s->mtfbase[ii] = kk + 1;
}
}
}
}
/*-- end uc = MTF ( nextSym-1 ) --*/
s->unzftab[s->seqToUnseq[uc]]++;
if (s->smallDecompress)
s->ll16[nblock] = (UInt16)(s->seqToUnseq[uc]); else
s->tt[nblock] = (UInt32)(s->seqToUnseq[uc]);
nblock++;
GET_MTF_VAL(BZ_X_MTF_5, BZ_X_MTF_6, nextSym);
continue;
}
}
/* Now we know what nblock is, we can do a better sanity
check on s->origPtr.
*/
if (s->origPtr < 0 || s->origPtr >= nblock)
RETURN(BZ_DATA_ERROR);
/*-- Set up cftab to facilitate generation of T^(-1) --*/
/* Check: unzftab entries in range. */
for (i = 0; i <= 255; i++) {
if (s->unzftab[i] < 0 || s->unzftab[i] > nblock)
RETURN(BZ_DATA_ERROR);
}
/* Actually generate cftab. */
s->cftab[0] = 0;
for (i = 1; i <= 256; i++) s->cftab[i] = s->unzftab[i-1];
for (i = 1; i <= 256; i++) s->cftab[i] += s->cftab[i-1];
/* Check: cftab entries in range. */
for (i = 0; i <= 256; i++) {
if (s->cftab[i] < 0 || s->cftab[i] > nblock) {
/* s->cftab[i] can legitimately be == nblock */
RETURN(BZ_DATA_ERROR);
}
}
/* Check: cftab entries non-descending. */
for (i = 1; i <= 256; i++) {
if (s->cftab[i-1] > s->cftab[i]) {
RETURN(BZ_DATA_ERROR);
}
}
s->state_out_len = 0;
s->state_out_ch = 0;
BZ_INITIALISE_CRC ( s->calculatedBlockCRC );
s->state = BZ_X_OUTPUT;
if (s->verbosity >= 2) VPrintf0 ( "rt+rld" );
if (s->smallDecompress) {
/*-- Make a copy of cftab, used in generation of T --*/
for (i = 0; i <= 256; i++) s->cftabCopy[i] = s->cftab[i];
/*-- compute the T vector --*/
for (i = 0; i < nblock; i++) {
uc = (UChar)(s->ll16[i]);
SET_LL(i, s->cftabCopy[uc]);
s->cftabCopy[uc]++;
}
/*-- Compute T^(-1) by pointer reversal on T --*/
i = s->origPtr;
j = GET_LL(i);
do {
Int32 tmp = GET_LL(j);
SET_LL(j, i);
i = j;
j = tmp;
}
while (i != s->origPtr);
s->tPos = s->origPtr;
s->nblock_used = 0;
if (s->blockRandomised) {
BZ_RAND_INIT_MASK;
BZ_GET_SMALL(s->k0); s->nblock_used++;
BZ_RAND_UPD_MASK; s->k0 ^= BZ_RAND_MASK;
} else {
BZ_GET_SMALL(s->k0); s->nblock_used++;
}
} else {
/*-- compute the T^(-1) vector --*/
for (i = 0; i < nblock; i++) {
uc = (UChar)(s->tt[i] & 0xff);
s->tt[s->cftab[uc]] |= (i << 8);
s->cftab[uc]++;
}
s->tPos = s->tt[s->origPtr] >> 8;
s->nblock_used = 0;
if (s->blockRandomised) {
BZ_RAND_INIT_MASK;
BZ_GET_FAST(s->k0); s->nblock_used++;
BZ_RAND_UPD_MASK; s->k0 ^= BZ_RAND_MASK;
} else {
BZ_GET_FAST(s->k0); s->nblock_used++;
}
}
RETURN(BZ_OK);
endhdr_2:
GET_UCHAR(BZ_X_ENDHDR_2, uc);
if (uc != 0x72) RETURN(BZ_DATA_ERROR);
GET_UCHAR(BZ_X_ENDHDR_3, uc);
if (uc != 0x45) RETURN(BZ_DATA_ERROR);
GET_UCHAR(BZ_X_ENDHDR_4, uc);
if (uc != 0x38) RETURN(BZ_DATA_ERROR);
GET_UCHAR(BZ_X_ENDHDR_5, uc);
if (uc != 0x50) RETURN(BZ_DATA_ERROR);
GET_UCHAR(BZ_X_ENDHDR_6, uc);
if (uc != 0x90) RETURN(BZ_DATA_ERROR);
s->storedCombinedCRC = 0;
GET_UCHAR(BZ_X_CCRC_1, uc);
s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc);
GET_UCHAR(BZ_X_CCRC_2, uc);
s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc);
GET_UCHAR(BZ_X_CCRC_3, uc);
s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc);
GET_UCHAR(BZ_X_CCRC_4, uc);
s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc);
s->state = BZ_X_IDLE;
RETURN(BZ_STREAM_END);
default: AssertH ( False, 4001 );
}
AssertH ( False, 4002 );
save_state_and_return:
s->save_i = i;
s->save_j = j;
s->save_t = t;
s->save_alphaSize = alphaSize;
s->save_nGroups = nGroups;
s->save_nSelectors = nSelectors;
s->save_EOB = EOB;
s->save_groupNo = groupNo;
s->save_groupPos = groupPos;
s->save_nextSym = nextSym;
s->save_nblockMAX = nblockMAX;
s->save_nblock = nblock;
s->save_es = es;
s->save_N = N;
s->save_curr = curr;
s->save_zt = zt;
s->save_zn = zn;
s->save_zvec = zvec;
s->save_zj = zj;
s->save_gSel = gSel;
s->save_gMinlen = gMinlen;
s->save_gLimit = gLimit;
s->save_gBase = gBase;
s->save_gPerm = gPerm;
return retVal;
}
/*-------------------------------------------------------------*/
/*--- end decompress.c ---*/
/*-------------------------------------------------------------*/
| 1 | 0.998057 | 1 | 0.998057 | game-dev | MEDIA | 0.289014 | game-dev | 0.999304 | 1 | 0.999304 |
lexica/lexica | 6,171 | app/src/main/java/com/serwylo/lexica/MainMenuActivity.java | /*
* Copyright (C) 2008-2009 Rev. Johnny Healey <rev.null@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.serwylo.lexica;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import com.serwylo.lexica.activities.HighScoresActivity;
import com.serwylo.lexica.activities.NewMultiplayerActivity;
import com.serwylo.lexica.databinding.SplashBinding;
import com.serwylo.lexica.db.Database;
import com.serwylo.lexica.db.GameMode;
import com.serwylo.lexica.db.GameModeRepository;
import com.serwylo.lexica.db.Result;
import com.serwylo.lexica.db.ResultRepository;
import com.serwylo.lexica.db.migration.MigrateHighScoresFromPreferences;
import com.serwylo.lexica.lang.Language;
import com.serwylo.lexica.lang.LanguageLabel;
import java.util.Locale;
public class MainMenuActivity extends AppCompatActivity {
@SuppressWarnings("unused")
protected static final String TAG = "Lexica";
private String currentTheme = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
currentTheme = ThemeManager.getInstance().applyTheme(this);
load();
}
private void splashScreen(GameMode gameMode, Result highScore) {
Language language = new Util().getSelectedLanguageOrDefault(this);
SplashBinding binding = SplashBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
binding.newGame.setOnClickListener(v -> {
Intent intent = new Intent("com.serwylo.lexica.action.NEW_GAME");
intent.putExtra("gameMode", gameMode);
intent.putExtra("lang", language.getName());
startActivity(intent);
});
binding.gameModeButton.setOnClickListener(v -> startActivity(new Intent(this, ChooseGameModeActivity.class)));
binding.gameModeButton.setText(gameMode.label(this));
binding.languageButton.setText(LanguageLabel.getLabel(this, language));
binding.languageButton.setOnClickListener(v -> startActivity(new Intent(this, ChooseLexiconActivity.class)));
if (savedGame()) {
binding.restoreGame.setOnClickListener(v -> startActivity(new Intent("com.serwylo.lexica.action.RESTORE_GAME")));
binding.restoreGame.setEnabled(true);
}
binding.about.setOnClickListener(v -> {
Intent i = new Intent(Intent.ACTION_VIEW);
Uri u = Uri.parse("https://github.com/lexica/lexica");
i.setData(u);
startActivity(i);
});
binding.newMultiplayerGame.setOnClickListener(v -> {
startActivity(new Intent(this, NewMultiplayerActivity.class));
});
binding.preferences.setOnClickListener(v -> startActivity(new Intent("com.serwylo.lexica.action.CONFIGURE").setClassName(getPackageName(), "com.serwylo.lexica.SettingsActivity")));
long score = highScore == null ? 0 : highScore.getScore();
binding.highScore.setText(String.format(Locale.getDefault(), "%d", score));
// Think we can get away without yet-another button. It will lower the discoverability
// of the feature, but simplify the home screen a bit more.
binding.highScoreLabel.setOnClickListener(v -> startActivity(new Intent(this, HighScoresActivity.class)));
binding.highScore.setOnClickListener(v -> startActivity(new Intent(this, HighScoresActivity.class)));
Changelog.show(this);
}
public void onResume() {
super.onResume();
// Upon returning from settings, the user may hit the "Up" button in the toolbar (in which
// case the main splash screen will be recreated from scratch and themed appropriately in
// the onCreate() method), or via the "back" button, in which case we will get here.
//
// If the user pressed back, then we will check if they changed the theme from what we set
// it to originally during onCreate(), and if so, force the activity to be recreated (and
// hence rethemed).
if (!ThemeManager.getInstance().getCurrentTheme().equals(currentTheme)) {
ThemeManager.getInstance().forceRestartActivityToRetheme(this);
}
load();
}
public boolean savedGame() {
return new GameSaverPersistent(this).hasSavedGame();
}
private void load() {
AsyncTask.execute(() -> {
// Force migrations to run prior to querying the database.
// This is required because we populate default game modes, for which we need at least one to be present.
// https://stackoverflow.com/a/55067991
final Database db = Database.get(this);
db.getOpenHelper().getReadableDatabase();
Language language = new Util().getSelectedLanguageOrDefault(this);
final GameModeRepository gameModeRepository = new GameModeRepository(getApplicationContext());
final ResultRepository resultRepository = new ResultRepository(this);
if (!gameModeRepository.hasGameModes()) {
new MigrateHighScoresFromPreferences(this).initialiseDb(db.gameModeDao(), db.resultDao());
}
final GameMode gameMode = gameModeRepository.loadCurrentGameMode();
final Result highScore = resultRepository.findHighScore(gameMode, language);
runOnUiThread(() -> splashScreen(gameMode, highScore));
});
}
}
| 1 | 0.887865 | 1 | 0.887865 | game-dev | MEDIA | 0.3009 | game-dev | 0.97654 | 1 | 0.97654 |
Hydreon/Steadfast2 | 1,514 | src/pocketmine/block/RedMushroom.php | <?php
/*
*
* ____ _ _ __ __ _ __ __ ____
* | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
* | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
* | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
* |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* @author PocketMine Team
* @link http://www.pocketmine.net/
*
*
*/
namespace pocketmine\block;
use pocketmine\item\Item;
use pocketmine\level\Level;
use pocketmine\Player;
class RedMushroom extends Flowable{
protected $id = self::RED_MUSHROOM;
public function __construct(){
}
public function getName(){
return "Red Mushroom";
}
public function onUpdate($type){
if($type === Level::BLOCK_UPDATE_NORMAL){
if($this->getSide(0)->isTransparent() === true){
$this->getLevel()->useBreakOn($this);
return Level::BLOCK_UPDATE_NORMAL;
}
}
return false;
}
public function place(Item $item, Block $block, Block $target, $face, $fx, $fy, $fz, Player $player = null){
$down = $this->getSide(0);
if($down->isTransparent() === false){
$this->getLevel()->setBlock($block, $this, true, true);
return true;
}
return false;
}
} | 1 | 0.991123 | 1 | 0.991123 | game-dev | MEDIA | 0.895037 | game-dev | 0.986822 | 1 | 0.986822 |
Sin-cy/dotfiles | 1,317 | nvim/.config/nvim/lua/sethy/plugins/wilder.lua | return {
"gelguy/wilder.nvim",
-- "nvim-telescope/telescope.nvim",
dependencies = {
"nvim-tree/nvim-web-devicons",
"romgrk/fzy-lua-native",
},
config = function()
local wilder = require("wilder")
wilder.setup({ modes = { ":", "/", "?" } })
-- Define custom highlight groups
wilder.set_option(
"renderer",
wilder.popupmenu_renderer(wilder.popupmenu_border_theme({
min_width = "20%", -- minimum height of the popupmenu, can also be a number
max_height = "15%", -- to set a fixed height, set max_height to the same value
reverse = 0, -- if 1, shows the candidates from bottom to top
highlighter = {
wilder.lua_pcre2_highlighter(), -- Requires luarocks install pcre2
wilder.lua_fzy_highlighter(), -- Requires fzy-lua-native
},
highlights = {
default = wilder.make_hl(
"WilderPopupMenu",
"Pmenu",
{ { a = 1 }, { a = 1 }, { background = "#1E212B" } } -- Adjust background color
),
accent = wilder.make_hl(
"WilderAccent",
"Pmenu",
{ { a = 1 }, { a = 1 }, { foreground = "#58FFD6", background = "#1e1e2e" } }
),
},
-- 'single', 'double', 'rounded' or 'solid'
-- can also be a list of 8 characters, see :h wilder#popupmenu_border_theme() for more details
border = "single",
}))
)
end,
}
| 1 | 0.857619 | 1 | 0.857619 | game-dev | MEDIA | 0.471045 | game-dev,desktop-app | 0.888589 | 1 | 0.888589 |
cjcliffe/CubicVR | 5,847 | cubicvr/external/bullet-2.78/src/BulletDynamics/Character/btKinematicCharacterController.h | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2008 Erwin Coumans http://bulletphysics.com
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef BT_KINEMATIC_CHARACTER_CONTROLLER_H
#define BT_KINEMATIC_CHARACTER_CONTROLLER_H
#include "LinearMath/btVector3.h"
#include "btCharacterControllerInterface.h"
#include "BulletCollision/BroadphaseCollision/btCollisionAlgorithm.h"
class btCollisionShape;
class btRigidBody;
class btCollisionWorld;
class btCollisionDispatcher;
class btPairCachingGhostObject;
///btKinematicCharacterController is an object that supports a sliding motion in a world.
///It uses a ghost object and convex sweep test to test for upcoming collisions. This is combined with discrete collision detection to recover from penetrations.
///Interaction between btKinematicCharacterController and dynamic rigid bodies needs to be explicity implemented by the user.
class btKinematicCharacterController : public btCharacterControllerInterface
{
protected:
btScalar m_halfHeight;
btPairCachingGhostObject* m_ghostObject;
btConvexShape* m_convexShape;//is also in m_ghostObject, but it needs to be convex, so we store it here to avoid upcast
btScalar m_verticalVelocity;
btScalar m_verticalOffset;
btScalar m_fallSpeed;
btScalar m_jumpSpeed;
btScalar m_maxJumpHeight;
btScalar m_maxSlopeRadians; // Slope angle that is set (used for returning the exact value)
btScalar m_maxSlopeCosine; // Cosine equivalent of m_maxSlopeRadians (calculated once when set, for optimization)
btScalar m_gravity;
btScalar m_turnAngle;
btScalar m_stepHeight;
btScalar m_addedMargin;//@todo: remove this and fix the code
///this is the desired walk direction, set by the user
btVector3 m_walkDirection;
btVector3 m_normalizedDirection;
//some internal variables
btVector3 m_currentPosition;
btScalar m_currentStepOffset;
btVector3 m_targetPosition;
///keep track of the contact manifolds
btManifoldArray m_manifoldArray;
bool m_touchingContact;
btVector3 m_touchingNormal;
bool m_wasOnGround;
bool m_wasJumping;
bool m_useGhostObjectSweepTest;
bool m_useWalkDirection;
btScalar m_velocityTimeInterval;
int m_upAxis;
static btVector3* getUpAxisDirections();
btVector3 computeReflectionDirection (const btVector3& direction, const btVector3& normal);
btVector3 parallelComponent (const btVector3& direction, const btVector3& normal);
btVector3 perpindicularComponent (const btVector3& direction, const btVector3& normal);
bool recoverFromPenetration ( btCollisionWorld* collisionWorld);
void stepUp (btCollisionWorld* collisionWorld);
void updateTargetPositionBasedOnCollision (const btVector3& hit_normal, btScalar tangentMag = btScalar(0.0), btScalar normalMag = btScalar(1.0));
void stepForwardAndStrafe (btCollisionWorld* collisionWorld, const btVector3& walkMove);
void stepDown (btCollisionWorld* collisionWorld, btScalar dt);
public:
btKinematicCharacterController (btPairCachingGhostObject* ghostObject,btConvexShape* convexShape,btScalar stepHeight, int upAxis = 1);
~btKinematicCharacterController ();
///btActionInterface interface
virtual void updateAction( btCollisionWorld* collisionWorld,btScalar deltaTime)
{
preStep ( collisionWorld);
playerStep (collisionWorld, deltaTime);
}
///btActionInterface interface
void debugDraw(btIDebugDraw* debugDrawer);
void setUpAxis (int axis)
{
if (axis < 0)
axis = 0;
if (axis > 2)
axis = 2;
m_upAxis = axis;
}
/// This should probably be called setPositionIncrementPerSimulatorStep.
/// This is neither a direction nor a velocity, but the amount to
/// increment the position each simulation iteration, regardless
/// of dt.
/// This call will reset any velocity set by setVelocityForTimeInterval().
virtual void setWalkDirection(const btVector3& walkDirection);
/// Caller provides a velocity with which the character should move for
/// the given time period. After the time period, velocity is reset
/// to zero.
/// This call will reset any walk direction set by setWalkDirection().
/// Negative time intervals will result in no motion.
virtual void setVelocityForTimeInterval(const btVector3& velocity,
btScalar timeInterval);
void reset ();
void warp (const btVector3& origin);
void preStep ( btCollisionWorld* collisionWorld);
void playerStep ( btCollisionWorld* collisionWorld, btScalar dt);
void setFallSpeed (btScalar fallSpeed);
void setJumpSpeed (btScalar jumpSpeed);
void setMaxJumpHeight (btScalar maxJumpHeight);
bool canJump () const;
void jump ();
void setGravity(btScalar gravity);
btScalar getGravity() const;
/// The max slope determines the maximum angle that the controller can walk up.
/// The slope angle is measured in radians.
void setMaxSlope(btScalar slopeRadians);
btScalar getMaxSlope() const;
btPairCachingGhostObject* getGhostObject();
void setUseGhostSweepTest(bool useGhostObjectSweepTest)
{
m_useGhostObjectSweepTest = useGhostObjectSweepTest;
}
bool onGround () const;
};
#endif // BT_KINEMATIC_CHARACTER_CONTROLLER_H
| 1 | 0.802102 | 1 | 0.802102 | game-dev | MEDIA | 0.999387 | game-dev | 0.964131 | 1 | 0.964131 |
ovilab/atomify | 3,340 | libs/lammps/src/USER-MISC/temper_grem.h | /* -*- c++ -*- ----------------------------------------------------------
LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator
http://lammps.sandia.gov, Sandia National Laboratories
Steve Plimpton, sjplimp@sandia.gov
Copyright (2003) Sandia Corporation. Under the terms of Contract
DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains
certain rights in this software. This software is distributed under
the GNU General Public License.
See the README file in the top-level LAMMPS directory.
------------------------------------------------------------------------- */
#ifdef COMMAND_CLASS
CommandStyle(temper/grem,TemperGrem)
#else
#ifndef LMP_TEMPER_GREM_H
#define LMP_TEMPER_GREM_H
#include "pointers.h"
namespace LAMMPS_NS {
class TemperGrem : protected Pointers {
public:
TemperGrem(class LAMMPS *);
~TemperGrem();
void command(int, char **);
private:
int me,me_universe; // my proc ID in world and universe
int iworld,nworlds; // world info
double boltz; // copy from output->boltz
MPI_Comm roots; // MPI comm with 1 root proc from each world
class RanPark *ranswap,*ranboltz; // RNGs for swapping and Boltz factor
int nevery; // # of timesteps between swaps
int nswaps; // # of tempering swaps to perform
int seed_swap; // 0 = toggle swaps, n = RNG for swap direction
int seed_boltz; // seed for Boltz factor comparison
int whichfix; // index of temperature fix to use
int fixstyle; // what kind of temperature fix is used
int my_set_lambda; // which set lambda I am simulating
double *set_lambda; // static list of replica set lambdas
int *lambda2world; // lambda2world[i] = world simulating set lambda i
int *world2lambda; // world2lambda[i] = lambda simulated by world i
int *world2root; // world2root[i] = root proc of world i
void print_status();
class FixGrem * fix_grem;
protected:
char *id_nh;
int pressflag;
};
}
#endif
#endif
/* ERROR/WARNING messages:
E: Must have more than one processor partition to grem
Cannot use the grem command with only one processor partition. Use
the -partition command-line option.
E: Grem command before simulation box is defined
The grem command cannot be used before a read_data, read_restart, or
create_box command.
E: Illegal ... command
Self-explanatory. Check the input script syntax and compare to the
documentation for the command. You can use -echo screen as a
command-line option when running LAMMPS to see the offending line.
E: Tempering fix ID is not defined
The fix ID specified by the grem command does not exist.
E: Invalid frequency in grem command
Nevery must be > 0.
E: Non integer # of swaps in grem command
Swap frequency in grem command must evenly divide the total # of
timesteps.
E: Grem temperature fix is not valid
The fix specified by the grem command is not one that controls
temperature (nvt or npt).
E: Too many timesteps
The cumulative timesteps must fit in a 64-bit integer.
E: Grem could not find thermo_pe compute
This compute is created by the thermo command. It must have been
explicitly deleted by a uncompute command.
*/
| 1 | 0.949518 | 1 | 0.949518 | game-dev | MEDIA | 0.278181 | game-dev | 0.896516 | 1 | 0.896516 |
genxium/DelayNoMoreUnity | 92,720 | shared/Battle_geometry.cs | using System;
using static shared.CharacterState;
namespace shared {
public partial class Battle {
private const float magicLeanLowerBound = 0.1f;
private const float magicLeanUpperBound = 0.9f;
private static SatResult tmpResultHolder = new SatResult {
OverlapMag = 0,
OverlapX = 0,
OverlapY = 0,
AContainedInB = false,
BContainedInA = false,
AxisX = 0,
AxisY = 0,
SecondaryOverlapMag = 0,
SecondaryOverlapX = 0,
SecondaryOverlapY = 0,
SecondaryAContainedInB = false,
SecondaryBContainedInA = false,
SecondaryAxisX = 0,
SecondaryAxisY = 0
};
public static void roundToRectilinearDir(ref float normX, ref float normY) {
if (0 == normX) {
if (0 > normY) {
normY = -1f;
} else {
normY = 1f;
}
} else if (0 == normY) {
if (0 > normX) {
normX = -1f;
} else {
normX = 1f;
}
}
}
public static (float, float, float, float) calcForwardDiffOfBoundaries(int xfac, int yfac, float aColliderLeft, float aColliderRight, float aColliderTop, float aColliderBottom, float bColliderLeft, float bColliderRight, float bColliderTop, float bColliderBottom) {
float dx = 0f, dy = 0f, dxFar = 0, dyFar = 0;
float aColliderXCenter = (aColliderLeft+aColliderRight)*0.5f;
if (0 < xfac) {
dx = bColliderLeft - aColliderXCenter;
dxFar = bColliderRight - aColliderRight;
} else if (0 > xfac) {
dx = bColliderRight - aColliderXCenter;
dxFar = bColliderLeft - aColliderLeft;
}
float aColliderYCenter = (aColliderTop + aColliderBottom) * 0.5f;
if (0 < yfac) {
dy = bColliderBottom - aColliderYCenter;
dyFar = bColliderTop - aColliderTop;
} else if (0 > yfac) {
dy = bColliderTop - aColliderYCenter;
dyFar = bColliderBottom - aColliderBottom;
}
return (dx, dy, dxFar, dyFar);
}
public static (bool, float, float) calcPushbacks(float oldDx, float oldDy, ConvexPolygon a, ConvexPolygon b, bool prefersAOnBShapeTopEdges, bool isForCharacterPushback, ref SatResult overlapResult, ILoggerBridge logger, bool forceLogging = false) {
float origX = a.X, origY = a.Y;
try {
a.SetPosition(origX + oldDx, origY + oldDy);
overlapResult.resetForPushbackCalc();
bool overlapped = isPolygonPairOverlapped(a, b, prefersAOnBShapeTopEdges, isForCharacterPushback, ref overlapResult, logger, forceLogging);
if (true == overlapped) {
float pushbackX = overlapResult.OverlapMag * overlapResult.OverlapX;
float pushbackY = overlapResult.OverlapMag * overlapResult.OverlapY;
return (true, pushbackX, pushbackY);
} else {
return (false, 0, 0);
}
} finally {
a.SetPosition(origX, origY);
}
}
public static bool isVelAllowedByTrapCollider(TrapColliderAttr trapCollider, int velX, int velY) {
if (0 == trapCollider.OnlyAllowsAlignedVelX && 0 == trapCollider.OnlyAllowsAlignedVelY) return false;
return (0 < (trapCollider.OnlyAllowsAlignedVelX*velX + trapCollider.OnlyAllowsAlignedVelY*velY));
}
public static int calcHardPushbacksNormsForCharacter(RoomDownsyncFrame currRenderFrame, CharacterConfig chConfig, CharacterDownsync currCharacterDownsync, CharacterDownsync thatCharacterInNextFrame, bool isCharacterFlying, Collider aCollider, ConvexPolygon aShape, Vector[] hardPushbacks, Collision collision, ref SatResult overlapResult, ref SatResult primaryOverlapResult, out int primaryOverlapIndex, out Trap? primaryTrap, out TrapColliderAttr? primaryTrapColliderAttr, out Bullet? primaryBlHardPushbackProvider, FrameRingBuffer<Collider> residueCollided, ILoggerBridge logger) {
primaryTrap = null;
primaryTrapColliderAttr = null;
primaryBlHardPushbackProvider = null;
float virtualGripToWall = 0.0f;
bool isProactivelyGrabbingToWall = ((OnWallIdle1 == currCharacterDownsync.CharacterState || OnWallAtk1 == currCharacterDownsync.CharacterState) && currCharacterDownsync.DirX == thatCharacterInNextFrame.DirX); // [WARNING] Merely "true == currCharacterDownsync.OnWall" might NOT be proactive.
if (isProactivelyGrabbingToWall && 0 == thatCharacterInNextFrame.VelX) {
float xfac = 1.0f;
if (0 > thatCharacterInNextFrame.DirX) {
xfac = -xfac;
}
virtualGripToWall = xfac * currCharacterDownsync.Speed * VIRTUAL_GRID_TO_COLLISION_SPACE_RATIO;
}
int retCnt = 0;
primaryOverlapIndex = -1;
float primaryOverlapMag = float.MinValue;
bool primaryIsGround = false;
float primaryNonWallTop = -MAX_FLOAT32, primaryWallTop = -MAX_FLOAT32;
residueCollided.Clear();
bool collided = aCollider.CheckAllWithHolder(virtualGripToWall, 0, collision, COLLIDABLE_PAIRS);
if (!collided) {
//logger.LogInfo(String.Format("No collision object."));
return retCnt;
}
// Get the largest to ensure determinism regardless of traversal order
float largestNormAlignmentWithHorizon1 = -MAX_FLOAT32;
float largestNormAlignmentWithHorizon2 = -MAX_FLOAT32;
while (true) {
var (exists, bCollider) = collision.PopFirstContactedCollider();
if (!exists || null == bCollider) {
break;
}
int trapLocalId = TERMINATING_TRAP_ID;
TrapColliderAttr? trapColliderAttr = null;
bool isBarrier = false;
bool onTrap = false;
bool onBullet = false;
Bullet? bl = null;
BulletConfig? blConfig = null;
bool providesSlipJump = false;
bool forcesCrouching = false;
switch (bCollider.Data) {
case CharacterDownsync v0:
if (SPECIES_BRICK1 != currCharacterDownsync.SpeciesId && SPECIES_BRICK1 == v0.SpeciesId && v0.BulletTeamId != currCharacterDownsync.BulletTeamId) {
isBarrier = true;
}
if (SPECIES_FIRETOTEM != currCharacterDownsync.SpeciesId && SPECIES_FIRETOTEM == v0.SpeciesId && v0.BulletTeamId != currCharacterDownsync.BulletTeamId) {
isBarrier = true;
}
if (SPECIES_DARKBEAMTOWER != currCharacterDownsync.SpeciesId && SPECIES_DARKBEAMTOWER == v0.SpeciesId && v0.BulletTeamId != currCharacterDownsync.BulletTeamId) {
isBarrier = true;
}
break;
case Bullet v1:
if (SPECIES_FIRETOTEM == currCharacterDownsync.SpeciesId || SPECIES_BRICK1 == currCharacterDownsync.SpeciesId || SPECIES_DARKBEAMTOWER == currCharacterDownsync.SpeciesId) {
break;
}
(_, blConfig) = FindBulletConfig(v1.SkillId, v1.ActiveSkillHit);
if (null == blConfig) {
break;
}
if (blConfig.ProvidesXHardPushback || blConfig.ProvidesYHardPushbackTop || blConfig.ProvidesYHardPushbackBottom) {
isBarrier = true;
onBullet = true;
bl = v1;
}
break;
case PatrolCue v2:
break;
case Pickable v3:
//logger.LogInfo(String.Format("Character encountered a pickable v3 = {0}", v3));
break;
case TrapColliderAttr v4:
trapColliderAttr = v4;
trapLocalId = v4.TrapLocalId;
providesSlipJump = (v4.ProvidesSlipJump && !isCharacterFlying);
forcesCrouching = (v4.ForcesCrouching && !isCharacterFlying); // Obviously you cannot crouch when flying...
bool specialFlyingPass = (isCharacterFlying && v4.ProvidesSlipJump);
if (TERMINATING_TRAP_ID != trapLocalId) {
var trap = currRenderFrame.TrapsArr[trapLocalId-1];
/*
[WARNING]
It's a bit tricky here, as currently "v4.ProvidesSlipJump" implies "v4.ProvidesHardPushback", but we want flying characters to be able to freely fly across "v4.ProvidesSlipJump & v4.ProvidesHardPushback" yet not "!v4.ProvidesSlipJump & v4.ProvidesHardPushback".
*/
onTrap = (v4.ProvidesHardPushback && TrapState.Tdeactivated != trap.TrapState && !specialFlyingPass);
isBarrier = onTrap && !isVelAllowedByTrapCollider(v4, currCharacterDownsync.VelX, currCharacterDownsync.VelY);
} else {
onTrap = (v4.ProvidesHardPushback && !specialFlyingPass);
isBarrier = onTrap && !isVelAllowedByTrapCollider(v4, currCharacterDownsync.VelX, currCharacterDownsync.VelY);
}
break;
case TriggerColliderAttr v5:
break;
default:
// By default it's a regular barrier
isBarrier = true;
break;
}
if (!isBarrier && !forcesCrouching) {
if (residueCollided.Cnt >= residueCollided.N) {
throw new ArgumentException(String.Format("residueCollided is already full! residueCollided.Cnt={0}, residueCollided.N={1}: trying to insert collider.Shape={4}, collider.Data={5}", residueCollided.Cnt, residueCollided.N, bCollider.Shape, bCollider.Data));
}
residueCollided.Put(bCollider);
continue;
}
ConvexPolygon bShape = bCollider.Shape;
var (overlapped, pushbackX, pushbackY) = calcPushbacks(0, 0, aShape, bShape, true, true, ref overlapResult, logger);
if (!overlapped) {
/*
if (0 < overlapResult.OverlapMag && isBarrier && !onTrap && 1 == currCharacterDownsync.JoinIndex && !currCharacterDownsync.InAir && currCharacterDownsync.OnSlope && 0 > currCharacterDownsync.VelX && bShape.GetPointByOffset(1).X != bShape.GetPointByOffset(2).X) {
logger.LogInfo(String.Format("NOTOVERLAP: rdfId={0}, collided with non-trap barrier {1}, now reconstructing the trace", currRenderFrame.Id, bShape.ToString(false), overlapResult.ToString(), currCharacterDownsync.VelX, currCharacterDownsync.VelY));
(_, _, _) = calcPushbacks(0, 0, aShape, bShape, true, true, ref overlapResult, logger, true);
}
*/
continue;
}
if (overlapResult.OverlapMag < CLAMPABLE_COLLISION_SPACE_MAG) {
/*
[WARNING]
Kindly note that if I clamped by a larger threshold here, e.g. "overlapResult.OverlapMag < VIRTUAL_GRID_TO_COLLISION_SPACE_RATIO", it would cause unintended bouncing between "DefaultSizeY & ShrinkedSizeY" on slopes!
Moreover if I didn't clamp "pushbackX & pushbackY" here, there could be disagreed shape overlapping between backend and frontend, see comments around "shapeOverlappedOtherChCnt" in "Battle_dynamics".
*/
continue;
}
bool isCeiling = (0 < overlapResult.OverlapY);
bool isGround = (0 > overlapResult.OverlapY);
float barrierTop = bCollider.Y + bCollider.H;
float characterBottom = aCollider.Y;
if (isCeiling && forcesCrouching && chConfig.CrouchingEnabled) {
// [WARNING] If "forcesCrouching" but "false == chConfig.CrouchingEnabled", then the current "bCollider" should be deemed as a regular barrier!
float characterTop = aCollider.Y + aCollider.H;
if (characterTop < barrierTop && 0 < overlapResult.OverlapY) {
thatCharacterInNextFrame.ForcedCrouching = true;
}
continue;
}
if (providesSlipJump) {
/*
Only provides hardPushbacks when
- the character is not uprising, and
- the "bottom of the character" is higher than "top of the barrier rectangle - chConfig.SlipJumpThresHoldBelowTopFace".
*/
if (0 < currCharacterDownsync.VelY) {
continue;
}
if (characterBottom < (barrierTop - chConfig.SlipJumpThresHoldBelowTopFace)) {
continue;
}
}
float normAlignmentWithHorizon1 = (overlapResult.OverlapX * +1f);
float normAlignmentWithHorizon2 = (overlapResult.OverlapX * -1f);
bool isWall = (VERTICAL_PLATFORM_THRESHOLD < normAlignmentWithHorizon1 || VERTICAL_PLATFORM_THRESHOLD < normAlignmentWithHorizon2);
if (onBullet && null != bl && null != blConfig) {
// [WARNING] Special cases to deal damage only!
if (isWall && !blConfig.ProvidesXHardPushback) {
continue;
}
if (!isWall) {
bool bulletProvidesEffPushback = (blConfig.ProvidesYHardPushbackTop && 0 > overlapResult.OverlapY) || (blConfig.ProvidesYHardPushbackBottom && 0 < overlapResult.OverlapY);
if (!bulletProvidesEffPushback) {
continue;
}
}
}
bool isAlongForwardPropagation = (0 <= currCharacterDownsync.VelX * (bCollider.X-aCollider.X));
if (isWall && isAlongForwardPropagation && primaryNonWallTop >= barrierTop /* barrierTop is wall-top now*/) {
// If primary non-wall is traversed before wall
// [WARNING] Deliberately NOT just skipping "(isWall && !isAlongForwardPropagation)" like bullets, because for a character, "(isWall && !isAlongForwardPropagation)" provides immediate "push outward".
continue;
}
if (normAlignmentWithHorizon1 > largestNormAlignmentWithHorizon1) {
largestNormAlignmentWithHorizon1 = normAlignmentWithHorizon1;
}
if (normAlignmentWithHorizon2 > largestNormAlignmentWithHorizon2) {
largestNormAlignmentWithHorizon2 = normAlignmentWithHorizon2;
}
// [WARNING] At a corner with 1 vertical edge and 1 horizontal edge, make sure that the HORIZONTAL edge is chosen as primary!
if (isGround && !primaryIsGround) {
// Initial non-wall transition
primaryOverlapIndex = retCnt;
primaryOverlapMag = overlapResult.OverlapMag;
overlapResult.cloneInto(ref primaryOverlapResult);
primaryIsGround = isGround;
if (0 > overlapResult.OverlapY) {
primaryNonWallTop = barrierTop;
}
if (onBullet) {
primaryBlHardPushbackProvider = bl;
primaryTrapColliderAttr = null;
primaryTrap = null; // Don't forget to reset to null if the primary is not a trap
} else if (onTrap) {
primaryTrapColliderAttr = trapColliderAttr;
if (TERMINATING_TRAP_ID != trapLocalId) {
primaryTrap = currRenderFrame.TrapsArr[trapLocalId-1];
} else {
primaryTrap = null;
}
primaryBlHardPushbackProvider = null;
} else {
primaryBlHardPushbackProvider = null;
primaryTrapColliderAttr = null;
primaryTrap = null; // Don't forget to reset to null if the primary is not a trap
}
} else if (!isGround && primaryIsGround) {
// Just skip, once a character is checked to collide with a ground, any parasitic non-ground collision would be ignored...
} else {
bool samePolarity = 0 < (overlapResult.OverlapX*primaryOverlapResult.OverlapX + overlapResult.OverlapY*primaryOverlapResult.OverlapY);
if (samePolarity || -1 == primaryOverlapIndex) {
if (overlapResult.OverlapMag > primaryOverlapMag || -1 == primaryOverlapIndex) {
primaryOverlapIndex = retCnt;
primaryOverlapMag = overlapResult.OverlapMag;
overlapResult.cloneInto(ref primaryOverlapResult);
primaryIsGround = isGround;
if (onBullet) {
primaryBlHardPushbackProvider = bl;
primaryTrapColliderAttr = null;
primaryTrap = null;
} else if (onTrap) {
primaryTrapColliderAttr = trapColliderAttr;
if (TERMINATING_TRAP_ID != trapLocalId) {
primaryTrap = currRenderFrame.TrapsArr[trapLocalId-1];
} else {
primaryTrap = null;
}
primaryBlHardPushbackProvider = null;
} else {
primaryBlHardPushbackProvider = null;
primaryTrapColliderAttr = null;
primaryTrap = null; // Don't forget to reset to null if the primary is not a trap
}
} else if (overlapResult.OverlapMag == primaryOverlapMag) {
// [WARNING] Here's an important block for guaranteeing determinism regardless of traversal order.
if (onTrap && null == primaryTrapColliderAttr) {
// If currently straddling across a trap and a non-trap, with equal overlapMap, then the trap takes higher priority!
primaryOverlapIndex = retCnt;
primaryOverlapMag = overlapResult.OverlapMag;
overlapResult.cloneInto(ref primaryOverlapResult);
primaryIsGround = isGround;
primaryTrapColliderAttr = trapColliderAttr;
primaryBlHardPushbackProvider = null;
if (TERMINATING_TRAP_ID != trapLocalId) {
primaryTrap = currRenderFrame.TrapsArr[trapLocalId-1];
} else {
primaryTrap = null;
}
primaryBlHardPushbackProvider = null;
} else {
if ((overlapResult.AxisX < primaryOverlapResult.AxisX) || (overlapResult.AxisX == primaryOverlapResult.AxisX && overlapResult.AxisY < primaryOverlapResult.AxisY)) {
primaryOverlapIndex = retCnt;
primaryOverlapMag = overlapResult.OverlapMag;
overlapResult.cloneInto(ref primaryOverlapResult);
primaryIsGround = isGround;
if (onBullet) {
primaryBlHardPushbackProvider = bl;
primaryTrapColliderAttr = null;
primaryTrap = null;
} else if (onTrap) {
primaryTrapColliderAttr = trapColliderAttr;
if (TERMINATING_TRAP_ID != trapLocalId) {
primaryTrap = currRenderFrame.TrapsArr[trapLocalId-1];
} else {
primaryTrap = null;
}
primaryBlHardPushbackProvider = null;
} else {
primaryBlHardPushbackProvider = null;
primaryTrapColliderAttr = null;
primaryTrap = null; // Don't forget to reset to null if the primary is not a trap
}
}
}
}
if (primaryOverlapIndex == retCnt) {
if (isWall) {
primaryWallTop = barrierTop;
} else {
if (0 > overlapResult.OverlapY) {
primaryNonWallTop = barrierTop;
}
}
}
}
}
hardPushbacks[retCnt].X = pushbackX;
hardPushbacks[retCnt].Y = pushbackY;
retCnt++;
if (retCnt >= hardPushbacks.Length) break;
}
if (VERTICAL_PLATFORM_THRESHOLD < largestNormAlignmentWithHorizon1) {
thatCharacterInNextFrame.OnWall = true;
thatCharacterInNextFrame.OnWallNormX = +1;
thatCharacterInNextFrame.OnWallNormY = 0;
} else if (VERTICAL_PLATFORM_THRESHOLD < largestNormAlignmentWithHorizon2) {
thatCharacterInNextFrame.OnWall = true;
thatCharacterInNextFrame.OnWallNormX = -1;
thatCharacterInNextFrame.OnWallNormY = 0;
} else {
thatCharacterInNextFrame.OnWall = false;
thatCharacterInNextFrame.OnWallNormX = 0;
thatCharacterInNextFrame.OnWallNormY = 0;
}
return retCnt;
}
public static int calcHardPushbacksNormsForBullet(RoomDownsyncFrame currRenderFrame, Bullet bullet, Collider aCollider, ConvexPolygon aShape, Vector[] hardPushbacks, FrameRingBuffer<Collider> residueCollided, Collision collision, ref SatResult overlapResult, ref SatResult primaryOverlapResult, out int primaryOverlapIndex, out Trap? primaryTrap, out TrapColliderAttr? primaryTrapColliderAttr, ILoggerBridge logger) {
primaryTrap = null;
primaryTrapColliderAttr = null;
int retCnt = 0;
primaryOverlapIndex = -1;
float primaryOverlapMag = float.MinValue;
bool primaryIsWall = false; // [WARNING] OPPOSITE preference w.r.t. "calcHardPushbacksNormsForCharacter" here!
float primaryNonWallTop = -MAX_FLOAT32, primaryWallTop = -MAX_FLOAT32;
residueCollided.Clear();
bool collided = aCollider.CheckAllWithHolder(0, 0, collision, COLLIDABLE_PAIRS);
if (!collided) {
//logger.LogInfo(String.Format("No collision object."));
return retCnt;
}
var (_, bulletConfig) = FindBulletConfig(bullet.SkillId, bullet.ActiveSkillHit);
if (null == bulletConfig) {
return 0;
}
while (true) {
var (exists, bCollider) = collision.PopFirstContactedCollider();
if (!exists || null == bCollider) {
break;
}
int trapLocalId = TERMINATING_TRAP_ID;
TrapColliderAttr? trapColliderAttr = null;
bool isAnotherHardPushbackTrap = false;
bool isAnActualBarrier = false;
bool providesSlipJump = false;
switch (bCollider.Data) {
case Pickable v0:
case CharacterDownsync v1:
case Bullet v2:
case PatrolCue v3:
case TriggerColliderAttr v4:
break;
case TrapColliderAttr v5:
trapColliderAttr = v5;
trapLocalId = v5.TrapLocalId;
if (TERMINATING_TRAP_ID != v5.TrapLocalId) {
var trap = currRenderFrame.TrapsArr[v5.TrapLocalId-1];
isAnotherHardPushbackTrap = (v5.ProvidesHardPushback && TrapState.Tdeactivated != trap.TrapState && !isVelAllowedByTrapCollider(v5, bullet.VelX, bullet.VelY));
providesSlipJump = v5.ProvidesSlipJump;
} else {
isAnotherHardPushbackTrap = v5.ProvidesHardPushback && !isVelAllowedByTrapCollider(v5, bullet.VelX, bullet.VelY);
providesSlipJump = v5.ProvidesSlipJump;
}
break;
default:
// By default it's a regular barrier
isAnActualBarrier = true;
break;
}
if (!isAnotherHardPushbackTrap && !isAnActualBarrier) {
if (residueCollided.Cnt >= residueCollided.N) {
throw new ArgumentException(String.Format("residueCollided is already full! residueCollided.Cnt={0}, residueCollided.N={1}: trying to insert collider.Shape={4}, collider.Data={5}", residueCollided.Cnt, residueCollided.N, bCollider.Shape, bCollider.Data));
}
residueCollided.Put(bCollider);
continue;
}
ConvexPolygon bShape = bCollider.Shape;
var (overlapped, pushbackX, pushbackY) = calcPushbacks(0, 0, aShape, bShape, true, false, ref overlapResult, logger);
if (!overlapped) {
continue;
}
if (overlapResult.OverlapMag < CLAMPABLE_COLLISION_SPACE_MAG) {
/*
[WARNING]
If I didn't clamp "pushbackX & pushbackY" here, there could be disagreed shape overlapping between backend and frontend, see comments around "shapeOverlappedOtherChCnt" in "Battle_dynamics".
*/
continue;
}
if (providesSlipJump && 0 <= overlapResult.OverlapY) {
// Even for GroundWave this skipping condition holds true.
continue;
}
float normAlignmentWithGravity = (overlapResult.OverlapY * -1f);
bool isAlongForwardPropagation = false;
if (bulletConfig.BeamCollision) {
isAlongForwardPropagation = true;
} else {
isAlongForwardPropagation = (0 <= bullet.VelX * (bCollider.X - aCollider.X));
}
bool isSqueezer = (-SNAP_INTO_PLATFORM_THRESHOLD > normAlignmentWithGravity);
/*
[WARNING] Deliberately excluding "providesSlipJump" traps for easier handling of intermittent flat terrains as well as better player intuition!
The "isWall" criteria here is deliberately made different from character counterpart!
*/
bool isWall = (SNAP_INTO_PLATFORM_THRESHOLD >= normAlignmentWithGravity);
if ((isSqueezer || isWall) && providesSlipJump) {
continue;
}
float barrierTop = bCollider.Y + bCollider.H;
// [WARNING] At a corner with 1 vertical edge and 1 horizontal edge, make sure that the VERTICAL edge is chosen as primary!
if (isWall && !primaryIsWall) {
if (!isAlongForwardPropagation && BulletType.GroundWave == bulletConfig.BType) {
/*
if (BulletType.GroundWave == bulletConfig.BType) {
logger.LogInfo("@rdfId= " + currRenderFrame.Id + ", groundWave bullet " + bullet.BulletLocalId + " skipping wall not along forward propagation#1. overlapResult=" + overlapResult.ToString());
}
*/
continue;
}
if (primaryNonWallTop >= barrierTop /* barrierTop is wall-top now*/) {
// If primary non-wall is traversed before wall
/*
if (BulletType.GroundWave == bulletConfig.BType) {
logger.LogInfo("@rdfId= " + currRenderFrame.Id + ", groundWave bullet " + bullet.BulletLocalId + " skipping wallTop=" + barrierTop + " <= primaryNonWallTop=" + primaryNonWallTop + " #1. overlapResult=" + overlapResult.ToString());
}
*/
continue;
}
// Initial wall transition
primaryOverlapIndex = retCnt;
primaryOverlapMag = overlapResult.OverlapMag;
overlapResult.cloneInto(ref primaryOverlapResult);
primaryIsWall = isWall;
primaryWallTop = barrierTop;
if (isAnotherHardPushbackTrap) {
primaryTrapColliderAttr = trapColliderAttr;
if (TERMINATING_TRAP_ID != trapLocalId) {
primaryTrap = currRenderFrame.TrapsArr[trapLocalId-1];
} else {
primaryTrap = null;
}
} else {
primaryTrapColliderAttr = null;
primaryTrap = null;
}
} else if (!isWall && primaryIsWall && barrierTop /* barrierTop is non-wall-top now */ < primaryWallTop) {
// Just skip, once the bullet is checked to collide with a wall, any parasitic non-wall collision would be ignored...
/*
if (BulletType.GroundWave == bulletConfig.BType) {
logger.LogInfo("@rdfId= " + currRenderFrame.Id + ", groundWave bullet (primaryIsWall) " + bullet.BulletLocalId + " skipping wallTop=" + barrierTop + " < primaryWallTop=" + primaryWallTop + ". overlapResult=" + overlapResult.ToString());
}
*/
continue;
} else {
if (isWall) {
if (!isAlongForwardPropagation && BulletType.GroundWave == bulletConfig.BType) {
/*
if (BulletType.GroundWave == bulletConfig.BType) {
logger.LogInfo("@rdfId= " + currRenderFrame.Id + ", groundWave bullet " + bullet.BulletLocalId + " skipping wall not along forward propagation#2. overlapResult=" + overlapResult.ToString());
}
*/
continue;
}
if (primaryNonWallTop >= barrierTop /* barrierTop is wall-top now*/) {
// If primary non-wall is traversed before wall
/*
if (BulletType.GroundWave == bulletConfig.BType) {
logger.LogInfo("@rdfId= " + currRenderFrame.Id + ", groundWave bullet " + bullet.BulletLocalId + " skipping wallTop=" + barrierTop + " <= primaryNonWallTop=" + primaryNonWallTop + " #2. overlapResult=" + overlapResult.ToString());
}
*/
continue;
}
}
// bool samePolarity = 0 < (overlapResult.OverlapX*primaryOverlapResult.OverlapX + overlapResult.OverlapY*primaryOverlapResult.OverlapY);
if (overlapResult.OverlapMag < primaryOverlapMag) {
// [WARNING] Just add to "hardPushbacks[*]", don't touch primary markers
} else {
if (overlapResult.OverlapMag > primaryOverlapMag) {
primaryOverlapIndex = retCnt;
primaryOverlapMag = overlapResult.OverlapMag;
overlapResult.cloneInto(ref primaryOverlapResult);
} else {
if ((overlapResult.AxisX < primaryOverlapResult.AxisX) || (overlapResult.AxisX == primaryOverlapResult.AxisX && overlapResult.AxisY < primaryOverlapResult.AxisY)) {
primaryOverlapIndex = retCnt;
primaryOverlapMag = overlapResult.OverlapMag;
overlapResult.cloneInto(ref primaryOverlapResult);
}
}
if (primaryOverlapIndex == retCnt) {
primaryIsWall = isWall;
if (isWall) {
primaryWallTop = barrierTop;
} else {
if (0 > overlapResult.OverlapY) {
primaryNonWallTop = barrierTop;
}
}
if (isAnotherHardPushbackTrap) {
primaryTrapColliderAttr = trapColliderAttr;
if (TERMINATING_TRAP_ID != trapLocalId) {
primaryTrap = currRenderFrame.TrapsArr[trapLocalId - 1];
} else {
primaryTrap = null;
}
} else {
primaryTrapColliderAttr = null;
primaryTrap = null;
}
}
}
}
hardPushbacks[retCnt].X = pushbackX;
hardPushbacks[retCnt].Y = pushbackY;
retCnt++;
if (retCnt >= hardPushbacks.Length) break;
}
return retCnt;
}
public static int calcHardPushbacksNormsForPickable(RoomDownsyncFrame currRenderFrame, Pickable pickable, Collider aCollider, ConvexPolygon aShape, Vector[] hardPushbacks, Collision collision, ref SatResult overlapResult, ref SatResult primaryOverlapResult, out int primaryOverlapIndex, ILoggerBridge logger) {
int retCnt = 0;
primaryOverlapIndex = -1;
float primaryOverlapMag = float.MinValue;
bool collided = aCollider.CheckAllWithHolder(0, 0, collision, COLLIDABLE_PAIRS);
if (!collided) {
//logger.LogInfo(String.Format("No collision object."));
return retCnt;
}
while (true) {
var (exists, bCollider) = collision.PopFirstContactedCollider();
if (!exists || null == bCollider) {
break;
}
int trapLocalId = TERMINATING_TRAP_ID;
bool isAnotherHardPushbackTrap = false;
bool isAnActualBarrier = false;
switch (bCollider.Data) {
case Pickable v0:
case CharacterDownsync v1:
case Bullet v2:
case PatrolCue v3:
case TriggerColliderAttr v4:
break;
case TrapColliderAttr v5:
trapLocalId = v5.TrapLocalId;
if (TERMINATING_TRAP_ID != trapLocalId) {
var trap = currRenderFrame.TrapsArr[trapLocalId-1];
isAnotherHardPushbackTrap = (v5.ProvidesHardPushback && TrapState.Tdeactivated != trap.TrapState && !isVelAllowedByTrapCollider(v5, pickable.VelX, pickable.VelY));
} else {
isAnotherHardPushbackTrap = (v5.ProvidesHardPushback && !isVelAllowedByTrapCollider(v5, pickable.VelX, pickable.VelY));
}
break;
default:
// By default it's a regular barrier
isAnActualBarrier = true;
break;
}
if (!isAnotherHardPushbackTrap && !isAnActualBarrier) {
continue;
}
ConvexPolygon bShape = bCollider.Shape;
var (overlapped, pushbackX, pushbackY) = calcPushbacks(0, 0, aShape, bShape, true, false, ref overlapResult, logger);
if (!overlapped) {
continue;
}
if (overlapResult.OverlapMag < CLAMPABLE_COLLISION_SPACE_MAG) {
/*
[WARNING]
If I didn't clamp "pushbackX & pushbackY" here, there could be disagreed shape overlapping between backend and frontend, see comments around "shapeOverlappedOtherChCnt" in "Battle_dynamics".
*/
continue;
}
// Same polarity
if (overlapResult.OverlapMag > primaryOverlapMag) {
primaryOverlapIndex = retCnt;
primaryOverlapMag = overlapResult.OverlapMag;
overlapResult.cloneInto(ref primaryOverlapResult);
} else {
if ((overlapResult.AxisX < primaryOverlapResult.AxisX) || (overlapResult.AxisX == primaryOverlapResult.AxisX && overlapResult.AxisY < primaryOverlapResult.AxisY)) {
primaryOverlapIndex = retCnt;
primaryOverlapMag = overlapResult.OverlapMag;
overlapResult.cloneInto(ref primaryOverlapResult);
}
}
hardPushbacks[retCnt].X = pushbackX;
hardPushbacks[retCnt].Y = pushbackY;
retCnt++;
if (retCnt >= hardPushbacks.Length) break;
}
return retCnt;
}
public static int calcHardPushbacksNormsForTrap(RoomDownsyncFrame currRenderFrame, TrapColliderAttr colliderAttr, Collider aCollider, ConvexPolygon aShape, Vector[] hardPushbacks, Collision collision, ref SatResult overlapResult, ref SatResult primaryOverlapResult, out int primaryOverlapIndex, FrameRingBuffer<Collider> residueCollided, out bool hitsAnActualBarrier, ILoggerBridge logger) {
hitsAnActualBarrier = false;
int retCnt = 0;
primaryOverlapIndex = -1;
float primaryOverlapMag = float.MinValue;
residueCollided.Clear();
bool collided = aCollider.CheckAllWithHolder(0, 0, collision, COLLIDABLE_PAIRS);
if (!collided) {
//logger.LogInfo(String.Format("No collision object."));
return retCnt;
}
while (true) {
var (exists, bCollider) = collision.PopFirstContactedCollider();
if (!exists || null == bCollider) {
break;
}
int trapLocalId = TERMINATING_TRAP_ID;
bool isAnotherHardPushbackTrap = false;
bool isAnActualBarrier = false;
switch (bCollider.Data) {
case CharacterDownsync v0:
case Bullet v1:
case PatrolCue v2:
case TriggerColliderAttr v3:
case Pickable v4:
break;
case TrapColliderAttr v5:
trapLocalId = v5.TrapLocalId;
if (TERMINATING_TRAP_ID != trapLocalId) {
var trap = currRenderFrame.TrapsArr[trapLocalId-1];
isAnotherHardPushbackTrap = (!v5.ProvidesSlipJump && v5.ProvidesHardPushback && TrapState.Tdeactivated != trap.TrapState && !isVelAllowedByTrapCollider(v5, trap.VelX, trap.VelY));
} else {
isAnotherHardPushbackTrap = (!v5.ProvidesSlipJump && v5.ProvidesHardPushback);
}
break;
default:
// By default it's a regular barrier
isAnActualBarrier = true;
break;
}
if (!isAnotherHardPushbackTrap && !isAnActualBarrier) {
if (residueCollided.Cnt >= residueCollided.N) {
throw new ArgumentException(String.Format("residueCollided is already full! residueCollided.Cnt={0}, residueCollided.N={1}: trying to insert collider.Shape={4}, collider.Data={5}", residueCollided.Cnt, residueCollided.N, bCollider.Shape, bCollider.Data));
}
residueCollided.Put(bCollider);
continue;
}
ConvexPolygon bShape = bCollider.Shape;
var (overlapped, pushbackX, pushbackY) = calcPushbacks(0, 0, aShape, bShape, false, true, ref overlapResult, logger);
if (!overlapped) {
continue;
}
if (overlapResult.OverlapMag < CLAMPABLE_COLLISION_SPACE_MAG) {
/*
[WARNING]
If I didn't clamp "pushbackX & pushbackY" here, there could be disagreed shape overlapping between backend and frontend, see comments around "shapeOverlappedOtherChCnt" in "Battle_dynamics".
*/
continue;
}
if (isAnActualBarrier) {
hitsAnActualBarrier = true;
}
// Same polarity
if (overlapResult.OverlapMag > primaryOverlapMag) {
primaryOverlapIndex = retCnt;
primaryOverlapMag = overlapResult.OverlapMag;
overlapResult.cloneInto(ref primaryOverlapResult);
} else {
if ((overlapResult.AxisX < primaryOverlapResult.AxisX) || (overlapResult.AxisX == primaryOverlapResult.AxisX && overlapResult.AxisY < primaryOverlapResult.AxisY)) {
primaryOverlapIndex = retCnt;
primaryOverlapMag = overlapResult.OverlapMag;
overlapResult.cloneInto(ref primaryOverlapResult);
}
}
hardPushbacks[retCnt].X = pushbackX;
hardPushbacks[retCnt].Y = pushbackY;
retCnt++;
if (retCnt >= hardPushbacks.Length) break;
}
return retCnt;
}
public static void processPrimaryAndImpactEffPushback(Vector effPushback, Vector[] pushbacks, int pushbacksCnt, int primaryOverlapIndex, float snapOverlap, bool eraseReverseDirection) {
if (0 == pushbacksCnt) {
return;
}
// Now that we have a "primaryOverlap" which we should get off by top priority, i.e. all the other hardPushbacks should clamp their x and y components to be no bigger than that of the "primaryOverlap".
float primaryPushbackX = pushbacks[primaryOverlapIndex].X;
float primaryPushbackY = pushbacks[primaryOverlapIndex].Y;
if (0 == primaryPushbackX && 0 == primaryPushbackY) return;
for (int i = 0; i < pushbacksCnt; i++) {
var pushback = pushbacks[i];
if (0 == pushback.X && 0 == pushback.Y) continue;
if (i != primaryOverlapIndex) {
if (pushback.X * primaryPushbackX > 0) {
if (Math.Abs(pushback.X) > Math.Abs(primaryPushbackX)) {
pushback.X -= primaryPushbackX;
} else {
pushback.X = 0;
}
} else if (eraseReverseDirection) {
// Otherwise the sum over the reverse direction might pile up to large value.
pushback.X = 0;
}
if (pushback.Y * primaryPushbackY > 0) {
if (Math.Abs(pushback.Y) > Math.Abs(primaryPushbackY)) {
pushback.Y -= primaryPushbackY;
} else {
pushback.Y = 0;
}
} else if (eraseReverseDirection) {
// Otherwise the sum over the reverse direction might pile up to large value.
pushback.Y = 0;
}
}
// Normalize and thus re-purpose "pushbacks[i]" to be later used
var magSqr = pushback.X * pushback.X + pushback.Y * pushback.Y;
var invMag = InvSqrt32(magSqr);
var mag = magSqr * invMag;
float normX = pushback.X*invMag, normY = pushback.Y*invMag;
// [WARNING] The following statement works even when "mag < snapOverlap"!
effPushback.X += (mag-snapOverlap)*normX;
effPushback.Y += (mag-snapOverlap)*normY;
pushback.X = normX;
pushback.Y = normY;
}
}
public static float InvSqrt32(float x) {
float xhalf = 0.5f * x;
int i = BitConverter.SingleToInt32Bits(x);
i = 0x5f3759df - (i >> 1);
x = BitConverter.Int32BitsToSingle(i);
x = x * (1.5f - xhalf * x * x);
return x;
}
public static double InvSqrt64(double x) {
double xhalf = 0.5 * x;
long i = BitConverter.DoubleToInt64Bits(x);
i = 0x5fe6eb50c7b537a9 - (i >> 1);
x = BitConverter.Int64BitsToDouble(i);
x = x * (1.5 - xhalf * x * x);
return x;
}
private static float TOO_FAR_FOR_PUSHBACK_MAGNITUDE = 64.0f; // Roughly the height of a character
public static bool isPolygonPairOverlapped(ConvexPolygon a, ConvexPolygon b, bool prefersAOnBShapeTopEdges, bool isForCharacterPushback, ref SatResult result, ILoggerBridge logger, bool forceLogging = false) {
int aCnt = a.Points.Cnt;
int bCnt = b.Points.Cnt;
// Single point case
if (1 == aCnt && 1 == bCnt) {
result.OverlapMag = 0;
Vector? aPoint = a.GetPointByOffset(0);
Vector? bPoint = b.GetPointByOffset(0);
return null != aPoint && null != bPoint && aPoint.X == bPoint.X && aPoint.Y == bPoint.Y;
}
bool onlyOnBShapeEdges = (!a.IsRotary && !b.IsRotary); // [WARNING] If both are not rotary, i.e. both rectilinear, then only need check edges of either!
bool foundNonOverwhelmingOverlap = false;
if (1 < aCnt && !onlyOnBShapeEdges) {
// Deliberately using "Points" instead of "SATAxes" to avoid unnecessary heap memory alloc
for (int i = 0; i < aCnt; i++) {
Vector? u = a.GetPointByOffset(i);
if (null == u) {
throw new ArgumentNullException("Getting a null point u from polygon a!");
}
Vector? v = a.GetPointByOffset(0);
if (i != aCnt - 1) {
v = a.GetPointByOffset(i + 1);
}
if (null == v) {
throw new ArgumentNullException("Getting a null point v from polygon a!");
}
float dx = (v.Y - u.Y);
float dy = -(v.X - u.X);
float invSqrtForAxis = InvSqrt32(dx * dx + dy * dy);
dx *= invSqrtForAxis;
dy *= invSqrtForAxis;
if (isPolygonPairSeparatedByDir(a, b, dx, dy, ref result, logger, forceLogging)) {
return false;
}
if (result.OverlapMag < TOO_FAR_FOR_PUSHBACK_MAGNITUDE) {
foundNonOverwhelmingOverlap = true;
}
}
}
if (1 < bCnt) {
tmpResultHolder.reset(); // [WARNING] It's important NOT to reset "tmpResultHolder" on each "i in [0, bCnt)", because inside "isPolygonPairSeparatedByDir(a, b, dx, dy, ref tmpResultHolder)" we rely on the historic value of "tmpResultHolder" to check whether or not we're currently on "shortest path to escape overlap"!
for (int i = 0; i < bCnt; i++) {
Vector? u = b.GetPointByOffset(i);
if (null == u) {
throw new ArgumentNullException("Getting a null point u from polygon b!");
}
Vector? v = b.GetPointByOffset(0);
if (i != bCnt - 1) {
v = b.GetPointByOffset(i + 1);
}
if (null == v) {
throw new ArgumentNullException("Getting a null point v from polygon b!");
}
float dx = (v.Y - u.Y);
float dy = -(v.X - u.X);
float dx2 = dx * dx, dy2 = dy * dy;
if (0 >= dx2 && 0 >= dy2) {
// Not a valid polygon
return false;
}
float invSqrtForAxis = InvSqrt32(dx2 + dy2);
dx *= invSqrtForAxis;
dy *= invSqrtForAxis;
if (isForCharacterPushback || (onlyOnBShapeEdges && prefersAOnBShapeTopEdges)) {
if (isPolygonPairSeparatedByDir(a, b, dx, dy, ref tmpResultHolder, logger, forceLogging)) {
return false;
}
// Overlapped if only axis projection separation were required
if (tmpResultHolder.OverlapMag < TOO_FAR_FOR_PUSHBACK_MAGNITUDE) {
foundNonOverwhelmingOverlap = true;
tmpResultHolder.cloneInto(ref result);
}
} else {
// Just regular usage -- always pick the last overlapping result
if (isPolygonPairSeparatedByDir(a, b, dx, dy, ref result, logger, forceLogging)) {
return false;
}
// Overlapped if only axis projection separation were required
if (result.OverlapMag < TOO_FAR_FOR_PUSHBACK_MAGNITUDE) {
foundNonOverwhelmingOverlap = true;
}
}
}
if (prefersAOnBShapeTopEdges && 0 <= result.OverlapY && 0 > result.SecondaryOverlapY) {
if (result.SecondaryOverlapMag < GROUNDWAVE_SNAP_INTO_PLATFORM_OVERLAP) {
// [WARNING] Close enough to just lift the character.
result.shiftFromSecondary();
} else if (result.SecondaryOverlapMag < SIDE_PUSHBACK_REPEL_THRESHOLD) {
// [WARNING] In this case, the "SecondaryOverlap" is still a top edge of bShape while the "PrimaryOverlap" is a side or bottom edge. However, due to "GROUNDWAVE_SNAP_INTO_PLATFORM_OVERLAP <= SecondaryOverlapMag" we think that "aShape" has fallen into "SecondaryOverlap" too much to deem "SecondaryOverlap" a supporting edge. Therefore, if "SecondaryOverlapMag" is not yet too deep, i.e. "GROUNDWAVE_SNAP_INTO_PLATFORM_OVERLAP <= SecondaryOverlapMag < SIDE_PUSHBACK_REPEL_THRESHOLD", then we just enlarge "PrimaryOverlapMag" to push out aShape, as well as setting "SideSuppressingTop" to assign extra "InertiaFramesToRecover" for a character (if aShape is a character).
result.OverlapMag *= 4;
result.SideSuppressingTop = true;
} else {
// [WARNING] Intentionally left as-is for wall grabbing.
}
}
}
return (isForCharacterPushback || (onlyOnBShapeEdges && prefersAOnBShapeTopEdges)) ? foundNonOverwhelmingOverlap : true;
}
public static bool isPolygonPairSeparatedByDir(ConvexPolygon a, ConvexPolygon b, float axisX, float axisY, ref SatResult result, ILoggerBridge logger, bool forceLogging = false) {
/*
[WARNING] This function is deliberately made private, it shouldn't be used alone (i.e. not along the norms of a polygon), otherwise the pushbacks calculated would be meaningless.
Consider the following example
a: {
anchor: [1337.19 1696.74]
points: [[0 0] [24 0] [24 24] [0 24]]
},
b: {
anchor: [1277.72 1570.56]
points: [[642.57 319.16] [0 319.16] [5.73 0] [643.75 0.90]]
}
e = (-2.98, 1.49).Unit()
*/
roundToRectilinearDir(ref axisX, ref axisY);
if (forceLogging) {
logger.LogInfo(String.Format("Checking isPolygonPairSeparatedByDir for axis=({2}, {3}, aShape={0}, bShape={1})", a.ToString(false), b.ToString(false), axisX, axisY));
}
float aStart = MAX_FLOAT32;
float aEnd = -MAX_FLOAT32;
float bStart = MAX_FLOAT32;
float bEnd = -MAX_FLOAT32;
for (int i = 0; i < a.Points.Cnt; i++) {
Vector? p = a.GetPointByOffset(i);
if (null == p) {
throw new ArgumentNullException("Getting a null point from polygon a!");
}
float dot = (p.X + a.X) * axisX + (p.Y + a.Y) * axisY;
if (aStart > dot) {
aStart = dot;
}
if (aEnd < dot) {
aEnd = dot;
}
if (forceLogging) {
logger.LogInfo(String.Format("\tchecking isPolygonPairSeparatedByDir for aShape.p=({0}, {1}), dot={2}, updated aStart={3}, aEnd={4}", (p.X+a.X), (p.Y + a.Y), dot, aStart, aEnd));
}
}
for (int i = 0; i < b.Points.Cnt; i++) {
Vector? p = b.GetPointByOffset(i);
if (null == p) {
throw new ArgumentNullException("Getting a null point from polygon b!");
}
float dot = (p.X + b.X) * axisX + (p.Y + b.Y) * axisY;
if (bStart > dot) {
bStart = dot;
}
if (bEnd < dot) {
bEnd = dot;
}
if (forceLogging) {
logger.LogInfo(String.Format("\tchecking isPolygonPairSeparatedByDir for bShape.p=({0}, {1}), dot={2}, updated bStart={3}, bEnd={4}", (p.X + b.X), (p.Y + b.Y), dot, bStart, bEnd));
}
}
if (aStart > bEnd || aEnd < bStart) {
// Separated by unit vector (axisX, axisY)
result.AContainedInB = false;
result.BContainedInA = false;
if (forceLogging) {
logger.LogInfo(String.Format("Returning isPolygonPairSeparatedByDir aStart={0}, aEnd={1}, bStart={2}, bEnd={3}", aStart, aEnd, bStart, bEnd));
}
return true;
}
float overlapProjected = 0;
bool falsifyAContainedInB = (aStart < bStart || aEnd > bEnd);
bool falsifyBContainedInA = (aEnd < bEnd || aStart > bStart);
if (aStart < bStart) {
result.AContainedInB = false;
if (aEnd < bEnd) {
overlapProjected = (float)((decimal)aEnd - (decimal)bStart);
result.BContainedInA = false;
} else {
float option1 = (float)((decimal)aEnd - (decimal)bStart);
float option2 = (float)((decimal)bEnd - (decimal)aStart);
if (option1 < option2) {
overlapProjected = option1;
} else {
overlapProjected = -option2;
}
}
} else {
result.BContainedInA &= !falsifyBContainedInA;
if (aEnd > bEnd) {
overlapProjected = (float)((decimal)aStart - (decimal)bEnd);
result.AContainedInB &= false;
} else {
float option1 = (float)((decimal)aEnd - (decimal)bStart);
float option2 = (float)((decimal)bEnd - (decimal)aStart);
if (option1 < option2) {
overlapProjected = option1;
} else {
overlapProjected = -option2;
}
}
}
float currentOverlapMag = result.OverlapMag;
float newOverlapMag = overlapProjected;
if (overlapProjected < 0) {
newOverlapMag = -overlapProjected;
}
float sign = 1;
if (overlapProjected < 0) {
sign = -1;
}
float newOverlapX = axisX * sign, newOverlapY = axisY * sign;
bool hasSmallerOverlapMag = (currentOverlapMag > newOverlapMag);
bool effectivelySameAsPrimary = !hasSmallerOverlapMag && (currentOverlapMag == newOverlapMag && newOverlapX == result.OverlapX && newOverlapY == result.OverlapY);
if (0 == result.AxisX && 0 == result.AxisY) {
result.AContainedInB &= !falsifyAContainedInB;
result.BContainedInA &= !falsifyBContainedInA;
result.OverlapMag = newOverlapMag;
result.OverlapX = newOverlapX;
result.OverlapY = newOverlapY;
result.AxisX = axisX;
result.AxisY = axisY;
} else if (hasSmallerOverlapMag) {
if ((0 == result.SecondaryAxisX && 0 == result.SecondaryAxisY) || result.SecondaryOverlapMag > result.OverlapMag) {
result.shiftToSecondary();
}
result.AContainedInB &= !falsifyAContainedInB;
result.BContainedInA &= !falsifyBContainedInA;
result.OverlapMag = newOverlapMag;
result.OverlapX = newOverlapX;
result.OverlapY = newOverlapY;
result.AxisX = axisX;
result.AxisY = axisY;
} else if ((0 == result.SecondaryAxisX && 0 == result.SecondaryAxisY) || (result.SecondaryOverlapMag > newOverlapMag)) {
if (!effectivelySameAsPrimary) {
result.SecondaryAContainedInB &= !falsifyAContainedInB;
result.SecondaryBContainedInA &= !falsifyBContainedInA;
result.SecondaryOverlapMag = newOverlapMag;
result.SecondaryOverlapX = newOverlapX;
result.SecondaryOverlapY = newOverlapY;
result.SecondaryAxisX = axisX;
result.SecondaryAxisY = axisY;
}
}
// the specified unit vector (axisX, axisY) doesn't separate "a" and "b", overlap result is generated
return false;
}
public static (int, int) PolygonColliderCtrToVirtualGridPos(float wx, float wy) {
// [WARNING] Introduces loss of precision!
// In JavaScript floating numbers suffer from seemingly non-deterministic arithmetics, and even if certain libs solved this issue by approaches such as fixed-point-number, they might not be used in other libs -- e.g. the "collision libs" we're interested in -- thus couldn't kill all pains.
int vx = (int)(Math.Round(wx * COLLISION_SPACE_TO_VIRTUAL_GRID_RATIO));
int vy = (int)(Math.Round(wy * COLLISION_SPACE_TO_VIRTUAL_GRID_RATIO));
return (vx, vy);
}
public static (float, float) VirtualGridToPolygonColliderCtr(int vx, int vy) {
// No loss of precision
float wx = (vx) * VIRTUAL_GRID_TO_COLLISION_SPACE_RATIO;
float wy = (vy) * VIRTUAL_GRID_TO_COLLISION_SPACE_RATIO;
return (wx, wy);
}
public static (float, float) PolygonColliderCtrToBL(float wx, float wy, float halfBoundingW, float halfBoundingH, float topPadding, float bottomPadding, float leftPadding, float rightPadding, float collisionSpaceOffsetX, float collisionSpaceOffsetY) {
return (wx - halfBoundingW - leftPadding + collisionSpaceOffsetX, wy - halfBoundingH - bottomPadding + collisionSpaceOffsetY);
}
public static (float, float) PolygonColliderBLToCtr(float cx, float cy, float halfBoundingW, float halfBoundingH, float topPadding, float bottomPadding, float leftPadding, float rightPadding, float collisionSpaceOffsetX, float collisionSpaceOffsetY) {
return (cx + halfBoundingW + leftPadding - collisionSpaceOffsetX, cy + halfBoundingH + bottomPadding - collisionSpaceOffsetY);
}
public static (int, int) PolygonColliderBLToVirtualGridPos(float cx, float cy, float halfBoundingW, float halfBoundingH, float topPadding, float bottomPadding, float leftPadding, float rightPadding, float collisionSpaceOffsetX, float collisionSpaceOffsetY) {
var (wx, wy) = PolygonColliderBLToCtr(cx, cy, halfBoundingW, halfBoundingH, topPadding, bottomPadding, leftPadding, rightPadding, collisionSpaceOffsetX, collisionSpaceOffsetY);
return PolygonColliderCtrToVirtualGridPos(wx, wy);
}
public static (float, float) VirtualGridToPolygonColliderBLPos(int vx, int vy, float halfBoundingW, float halfBoundingH, float topPadding, float bottomPadding, float leftPadding, float rightPadding, float collisionSpaceOffsetX, float collisionSpaceOffsetY) {
var (wx, wy) = VirtualGridToPolygonColliderCtr(vx, vy);
return PolygonColliderCtrToBL(wx, wy, halfBoundingW, halfBoundingH, topPadding, bottomPadding, leftPadding, rightPadding, collisionSpaceOffsetX, collisionSpaceOffsetY);
}
public static void AlignPolygon2DToBoundingBox(ConvexPolygon input) {
// Transform again to put "anchor" at the "bottom-left point (w.r.t. world space)" of the bounding box for "resolv"
float boundingBoxBLX = MAX_FLOAT32, boundingBoxBLY = MAX_FLOAT32;
for (int i = 0; i < input.Points.Cnt; i++) {
var (exists, p) = input.Points.GetByOffset(i);
if (!exists || null == p) throw new ArgumentNullException("Unexpected null point in ConvexPolygon when calling `AlignPolygon2DToBoundingBox`#1!");
boundingBoxBLX = Math.Min(p.X, boundingBoxBLX);
boundingBoxBLY = Math.Min(p.Y, boundingBoxBLY);
}
// Now "input.Anchor" should move to "input.Anchor+boundingBoxBL", thus "boundingBoxBL" is also the value of the negative diff for all "input.Points"
input.X += boundingBoxBLX;
input.Y += boundingBoxBLY;
for (int i = 0; i < input.Points.Cnt; i++) {
var (exists, p) = input.Points.GetByOffset(i);
if (!exists || null == p) throw new ArgumentNullException("Unexpected null point in ConvexPolygon when calling `AlignPolygon2DToBoundingBox`#2!");
p.X -= boundingBoxBLX;
p.Y -= boundingBoxBLY;
boundingBoxBLX = Math.Min(p.X, boundingBoxBLX);
boundingBoxBLY = Math.Min(p.Y, boundingBoxBLY);
}
}
// These directions are chosen such that when speed is changed to "(speedX+delta, speedY+delta)" for any of them, the direction is unchanged.
public static int[,] DIRECTION_DECODER = new int[,] {
{0, 0}, // 0
{0, +2}, // 1
{0, -2}, // 2
{+2, 0}, // 3
{-2, 0}, // 4
{+1, +1}, // 5
{-1, -1}, // 6
{+1, -1}, // 7
{-1, +1}, // 8
};
public static bool DecodeInput(ulong encodedInput, InputFrameDecoded holder) {
int encodedDirection = (int)(encodedInput & 15);
int btnALevel = (int)((encodedInput >> 4) & 1);
int btnBLevel = (int)((encodedInput >> 5) & 1);
int btnCLevel = (int)((encodedInput >> 6) & 1);
int btnDLevel = (int)((encodedInput >> 7) & 1);
int btnELevel = (int)((encodedInput >> 8) & 1);
holder.Dx = DIRECTION_DECODER[encodedDirection, 0];
holder.Dy = DIRECTION_DECODER[encodedDirection, 1];
holder.BtnALevel = btnALevel;
holder.BtnBLevel = btnBLevel;
holder.BtnCLevel = btnCLevel;
holder.BtnDLevel = btnDLevel;
holder.BtnELevel = btnELevel;
return true;
}
public static ulong EncodeInput(InputFrameDecoded ifd) {
return EncodeInput(ifd.Dx, ifd.Dy, ifd.BtnALevel, ifd.BtnBLevel, ifd.BtnCLevel, ifd.BtnDLevel, ifd.BtnELevel);
}
public static ulong EncodeInput(int dx, int dy, int btnALevel, int btnBLevel, int btnCLevel, int btnDLevel, int btnELevel) {
int encodedBtnALevel = (btnALevel << 4);
int encodedBtnBLevel = (btnBLevel << 5);
int encodedBtnCLevel = (btnCLevel << 6);
int encodedBtnDLevel = (btnDLevel << 7);
int encodedBtnELevel = (btnELevel << 8);
int discretizedDir = EncodeDirection(dx, dy);
return (ulong)(discretizedDir + encodedBtnALevel + encodedBtnBLevel + encodedBtnCLevel + encodedBtnDLevel + encodedBtnELevel);
}
public static int EncodeDirection(int dx, int dy) {
if (0 == dx && 0 == dy) return 0;
if (0 == dx) {
if (0 < dy) return 1; // up
else return 2; // down
}
if (0 < dx) {
if (0 == dy) return 3; // right
if (0 < dy) return 5;
else return 7;
}
// 0 > dx
if (0 == dy) return 4; // left
if (0 < dy) return 8;
else return 6;
}
public static (int, int, int) DiscretizeDirection(float continuousDx, float continuousDy, float eps = 0.1f, bool mustHaveNonZeroX = false) {
int dx = 0, dy = 0, encodedIdx = 0;
float absContinuousDx = Math.Abs(continuousDx);
float absContinuousDy = Math.Abs(continuousDy);
if (absContinuousDx < eps && absContinuousDy < eps) {
return (dx, dy, encodedIdx);
}
float criticalRatio = continuousDy / continuousDx;
float absCriticalRatio = Math.Abs(criticalRatio);
float downEps = 5*eps; // dragging down is often more tentative for a player, thus give it a larger threshold!
if (absCriticalRatio < magicLeanLowerBound && eps < absContinuousDx) {
dy = 0;
if (0 < continuousDx) {
dx = +2; // right
encodedIdx = 3;
} else {
dx = -2; // left
encodedIdx = 4;
}
} else if (absCriticalRatio > magicLeanUpperBound && eps < absContinuousDy) {
dx = 0;
if (0 < continuousDy) {
dy = +2; // up
encodedIdx = 1;
} else if (downEps < absContinuousDy) {
dy = -2; // down
encodedIdx = 2;
} else {
// else stays at "encodedIdx == 0"
}
if (mustHaveNonZeroX) {
if (0 == continuousDx) {
if (0 < dy) {
dx = +1;
} else {
dx = -1;
}
} else if (0 < continuousDx) {
dx = +1;
} else {
dx = -1;
}
if (0 < dx) {
if (0 < dy) {
dy = +1;
encodedIdx = 5;
} else {
dy = -1;
encodedIdx = 7;
}
} else {
dx = -1;
if (0 < dy) {
dy = +1;
encodedIdx = 8;
} else {
dy = -1;
encodedIdx = 6;
}
}
}
} else if (eps < absContinuousDx && eps < absContinuousDy) {
if (0 < continuousDx) {
dx = +1;
if (0 < continuousDy) {
dy = +1;
encodedIdx = 5;
} else {
if (downEps < absContinuousDy) {
dy = -1;
encodedIdx = 7;
} else {
dx = +2; // right
encodedIdx = 3;
}
}
} else {
// 0 > continuousDx
dx = -1;
if (0 < continuousDy) {
dy = +1;
encodedIdx = 8;
} else {
if (downEps < absContinuousDy) {
dy = -1;
encodedIdx = 6;
} else {
dx = -2; // left
encodedIdx = 4;
}
}
}
} else {
// just use encodedIdx = 0
}
return (dx, dy, encodedIdx);
}
private static void findHorizontallyClosestCharacterCollider(int rdfId, RoomDownsyncFrame currRenderFrame, CharacterDownsync currCharacterDownsync, CharacterConfig chConfig, bool isCharacterFlying, Collider visionCollider, Collider entityCollider, Collision collision, ref SatResult overlapResult, ref SatResult mvBlockerOverlapResult, out Collider? res1, out CharacterDownsync? res1Ch, out Collider? res2, out Bullet? res2Bl, out Collider? res3, out CharacterDownsync? res3Ch, out Collider? res4, out TrapColliderAttr? res4Tpc, out Collider? standingOnCollider, ILoggerBridge logger) {
res1 = null;
res1Ch = null;
res2 = null;
res2Bl = null;
res3 = null;
res3Ch = null;
res4 = null;
res4Tpc = null;
standingOnCollider = null;
// [WARNING] Finding only the closest non-self character to react to for avoiding any randomness.
bool collided = visionCollider.CheckAllWithHolder(0, 0, collision, COLLIDABLE_PAIRS);
if (!collided) return;
float minAbsColliderDx = MAX_FLOAT32;
float minAbsColliderDy = MAX_FLOAT32;
float minAbsColliderDxForAlly = MAX_FLOAT32;
float minAbsColliderDyForAlly = MAX_FLOAT32;
float minAbsColliderDxForMvBlocker = MAX_FLOAT32;
float minAbsColliderDyForMvBlocker = MAX_FLOAT32;
ConvexPolygon visionShape = visionCollider.Shape;
while (true) {
var (ok3, bCollider) = collision.PopFirstContactedCollider();
if (false == ok3 || null == bCollider) {
break;
}
float entityColliderLeft = entityCollider.X, entityColliderRight = entityCollider.X+entityCollider.W, entityColliderTop = entityCollider.Y+entityCollider.H, entityColliderBottom = entityCollider.Y;
float bColliderLeft = bCollider.X, bColliderRight = bCollider.X+bCollider.W, bColliderTop = bCollider.Y+bCollider.H, bColliderBottom = bCollider.Y;
switch (bCollider.Data) {
case PatrolCue v0:
case TriggerColliderAttr v1:
case Pickable v2:
break;
case CharacterDownsync v3:
{
// Only check shape collision (which is relatively expensive) if it's the targeted entity type
if (v3.JoinIndex == currCharacterDownsync.JoinIndex) {
continue;
}
if (TERMINATING_TRIGGER_ID != currCharacterDownsync.SubscribesToTriggerLocalId || Dimmed == v3.CharacterState || invinsibleSet.Contains(v3.CharacterState) || 0 < v3.FramesInvinsible) continue; // Target is invinsible, nothing can be done
ConvexPolygon bShape = bCollider.Shape;
var (overlapped, _, _) = calcPushbacks(0, 0, visionShape, bShape, false, false, ref overlapResult, logger);
if (!overlapped && !overlapResult.BContainedInA) {
continue;
}
var colliderDx = (bCollider.X - entityCollider.X);
var colliderDy = (bCollider.Y - entityCollider.Y);
var absColliderDx = Math.Abs(colliderDx);
var absColliderDy = Math.Abs(colliderDy);
if (v3.BulletTeamId != currCharacterDownsync.BulletTeamId) {
// different teams
if (absColliderDx > minAbsColliderDx) {
continue;
}
if (absColliderDx == minAbsColliderDx && absColliderDy > minAbsColliderDy) {
continue;
}
minAbsColliderDx = absColliderDx;
minAbsColliderDy = absColliderDy;
res1 = bCollider;
res1Ch = v3;
res2 = null;
res2Bl = null;
} else {
// same team
if (absColliderDx > minAbsColliderDxForAlly) {
continue;
}
if (absColliderDx == minAbsColliderDxForAlly && absColliderDy > minAbsColliderDyForAlly) {
continue;
}
minAbsColliderDxForAlly = absColliderDx;
minAbsColliderDyForAlly = absColliderDy;
res3 = bCollider;
res3Ch = v3;
}
}
break;
case Bullet v4:
{
if (v4.TeamId == currCharacterDownsync.BulletTeamId) {
continue;
}
var (_, bulletConfig) = FindBulletConfig(v4.SkillId, v4.ActiveSkillHit);
if (null == bulletConfig || (0 >= bulletConfig.Damage && null == bulletConfig.BuffConfig)) continue; // v4 is not offensive
var colliderDx = (bCollider.X - entityCollider.X);
var colliderDy = (bCollider.Y - entityCollider.Y);
if (0 <= v4.DirX*colliderDx) {
/*
if (Def1 == currCharacterDownsync.CharacterState) {
logger.LogInfo(String.Format("@rdfId={0}, ch.Id={1}, dirX={2}, ch.VirtualX={3}, ch.VirtualY={4} evaluating bullet localId={5}, v4.VirtualX={6}, v4.VirtualY={7}, colliderDx={8}, colliderDy={9}; bullet is not offensive", rdfId, currCharacterDownsync.Id, currCharacterDownsync.DirX, currCharacterDownsync.VirtualGridX, currCharacterDownsync.VirtualGridY, v4.BulletLocalId, v4.VirtualGridX, v4.VirtualGridY, colliderDx, colliderDy));
}
*/
continue; // v4 is not offensive
}
ConvexPolygon bShape = bCollider.Shape;
var (overlapped, _, _) = calcPushbacks(0, 0, visionShape, bShape, false, false, ref overlapResult, logger);
if (!overlapped && !overlapResult.BContainedInA) {
continue;
}
var absColliderDx = Math.Abs(colliderDx);
if (absColliderDx > minAbsColliderDx) {
continue;
}
var absColliderDy = Math.Abs(colliderDy);
if (absColliderDx == minAbsColliderDx && absColliderDy > minAbsColliderDy) {
continue;
}
minAbsColliderDx = absColliderDx;
minAbsColliderDy = absColliderDy;
res1 = null;
res1Ch = null;
res2 = bCollider;
res2Bl = v4;
}
break;
case TrapColliderAttr v5:
bool isAnotherHardPushbackTrap = false;
if (TERMINATING_TRAP_ID != v5.TrapLocalId) {
var trap = currRenderFrame.TrapsArr[v5.TrapLocalId-1];
isAnotherHardPushbackTrap = ((!v5.ProvidesSlipJump || !isCharacterFlying) && v5.ProvidesHardPushback && TrapState.Tdeactivated != trap.TrapState && !isVelAllowedByTrapCollider(v5, trap.VelX, trap.VelY));
} else {
isAnotherHardPushbackTrap = ((!v5.ProvidesSlipJump || !isCharacterFlying) && v5.ProvidesHardPushback);
}
if (!isAnotherHardPushbackTrap) {
continue;
}
_updateStandingColliderAndMvBlockerCollider(rdfId, currCharacterDownsync, chConfig, isCharacterFlying, entityCollider, visionShape, entityColliderTop, entityColliderBottom, entityColliderLeft, entityColliderRight, bCollider, bColliderTop, bColliderBottom, bColliderLeft, bColliderRight, v5, ref overlapResult, ref mvBlockerOverlapResult, ref minAbsColliderDxForMvBlocker, ref minAbsColliderDyForMvBlocker, ref res4, ref res4Tpc, ref standingOnCollider, logger);
break;
default:
_updateStandingColliderAndMvBlockerCollider(rdfId, currCharacterDownsync, chConfig, isCharacterFlying, entityCollider, visionShape, entityColliderTop, entityColliderBottom, entityColliderLeft, entityColliderRight, bCollider, bColliderTop, bColliderBottom, bColliderLeft, bColliderRight, null, ref overlapResult, ref mvBlockerOverlapResult, ref minAbsColliderDxForMvBlocker, ref minAbsColliderDyForMvBlocker, ref res4, ref res4Tpc, ref standingOnCollider, logger);
break;
}
}
}
private static bool _updateStandingColliderAndMvBlockerCollider(int rdfId, CharacterDownsync currCharacterDownsync, CharacterConfig chConfig, bool isCharacterFlying, Collider entityCollider, ConvexPolygon visionShape, float entityColliderTop, float entityColliderBottom, float entityColliderLeft, float entityColliderRight, Collider bCollider, float bColliderTop, float bColliderBottom, float bColliderLeft, float bColliderRight, TrapColliderAttr? v5, ref SatResult overlapResult, ref SatResult mvBlockerOverlapResult, ref float minAbsColliderDxForMvBlocker, ref float minAbsColliderDyForMvBlocker, ref Collider? res4, ref TrapColliderAttr? res4Tpc, ref Collider? standingOnCollider, ILoggerBridge logger) {
ConvexPolygon entityShape = entityCollider.Shape;
ConvexPolygon bShape = bCollider.Shape;
bool potentiallyStandingOnCollider = (!isCharacterFlying && !currCharacterDownsync.InAir && (bColliderLeft + SNAP_INTO_PLATFORM_OVERLAP < entityColliderRight && bColliderRight > entityColliderLeft + SNAP_INTO_PLATFORM_OVERLAP && bColliderBottom < entityColliderBottom));
// TODO: It's quite a waste to re-calculate "entityOverlapped" as we already have "calcHardPushbacksForCharacter", should find a way to reuse the results.
if (potentiallyStandingOnCollider) {
var (entityOverlapped, _, _) = calcPushbacks(0, 0, entityShape, bShape, false, false, ref overlapResult, logger);
bool isStandingCandidate = (entityOverlapped && 0 > overlapResult.OverlapY);
if (isStandingCandidate) {
if (null == standingOnCollider) {
standingOnCollider = bCollider;
return true;
} else {
// Handle temptation to step onto a "next standing collider".
if (0 < currCharacterDownsync.VelX && bColliderLeft >= standingOnCollider.X + standingOnCollider.W) {
standingOnCollider = bCollider;
return true;
} else if (0 > currCharacterDownsync.VelX && bColliderRight <= standingOnCollider.X) {
standingOnCollider = bCollider;
return true;
}
}
}
}
var (overlapped, _, _) = calcPushbacks(0, 0, visionShape, bShape, false, false, ref overlapResult, logger);
if (!overlapped) {
return false;
}
int effDx = (0 == currCharacterDownsync.VelX ? currCharacterDownsync.DirX : currCharacterDownsync.VelX), effDy = (0 == currCharacterDownsync.VelY ? currCharacterDownsync.DirY : currCharacterDownsync.VelY);
var (colliderDx, colliderDy, dxFar, dyFar) = calcForwardDiffOfBoundaries(effDx, effDy, entityColliderLeft, entityColliderRight, entityColliderTop, entityColliderBottom, bColliderLeft, bColliderRight, bColliderTop, bColliderBottom);
bool isAlongForwardMv = (0 < effDx * dxFar) || (0 < effDy * dyFar);
if (!isAlongForwardMv) {
return false;
}
if (!isCharacterFlying) {
bool strictlyUp = (bColliderBottom >= entityColliderTop);
bool holdableForRight = (bColliderRight > entityColliderRight);
bool holdableForLeft = (bColliderLeft < entityColliderLeft);
bool strictlyUpAndHoldableOnBothSides = (strictlyUp && holdableForLeft && holdableForRight);
if (strictlyUpAndHoldableOnBothSides) {
return false;
}
}
var absColliderDx = Math.Abs(colliderDx);
var absColliderDy = Math.Abs(colliderDy);
if (absColliderDx > minAbsColliderDxForMvBlocker) {
return false;
}
if (absColliderDx == minAbsColliderDyForMvBlocker && absColliderDy > minAbsColliderDyForMvBlocker) {
return false;
}
overlapResult.cloneInto(ref mvBlockerOverlapResult);
minAbsColliderDxForMvBlocker = absColliderDx;
minAbsColliderDyForMvBlocker = absColliderDy;
res4 = bCollider;
res4Tpc = v5;
return true;
}
private static void findHorizontallyClosestCharacterColliderForBlWithVision(Bullet blWithVision, bool isAllyTargetingBl, Collider aCollider, Collision collision, ref SatResult overlapResult, out Collider? res1, out CharacterDownsync? res1Ch, out Collider? res3, out CharacterDownsync? res3Ch, ILoggerBridge logger) {
res1 = null;
res1Ch = null;
res3 = null;
res3Ch = null;
// [WARNING] Finding only the closest non-self character to react to for avoiding any randomness.
bool collided = aCollider.CheckAllWithHolder(0, 0, collision, COLLIDABLE_PAIRS);
if (!collided) return;
float minAbsColliderDx = MAX_FLOAT32;
float minAbsColliderDy = MAX_FLOAT32;
float minAbsColliderDxForAlly = MAX_FLOAT32;
float minAbsColliderDyForAlly = MAX_FLOAT32;
ConvexPolygon aShape = aCollider.Shape;
while (true) {
var (ok3, bCollider) = collision.PopFirstContactedCollider();
if (false == ok3 || null == bCollider) {
break;
}
CharacterDownsync? v3 = bCollider.Data as CharacterDownsync;
if (null == v3) {
// Only check shape collision (which is relatively expensive) if it's CharacterDownsync
continue;
}
if (v3.JoinIndex == blWithVision.OffenderJoinIndex) {
continue;
}
if (!isAllyTargetingBl && (invinsibleSet.Contains(v3.CharacterState) || 0 < v3.FramesInvinsible)) continue; // Enemy is invinsible, nothing can be done
var (_, bulletConfig) = FindBulletConfig(blWithVision.SkillId, blWithVision.ActiveSkillHit);
if (null == bulletConfig) continue;
int immuneRcdI = 0;
bool shouldBeImmune = false;
if (bulletConfig.RemainsUponHit) {
while (immuneRcdI < v3.BulletImmuneRecords.Count) {
var candidate = v3.BulletImmuneRecords[immuneRcdI];
if (TERMINATING_BULLET_LOCAL_ID == candidate.BulletLocalId) break;
if (candidate.BulletLocalId == blWithVision.BulletLocalId) {
shouldBeImmune = true;
break;
}
immuneRcdI++;
}
}
if (shouldBeImmune) {
continue;
}
ConvexPolygon bShape = bCollider.Shape;
var (overlapped, _, _) = calcPushbacks(0, 0, aShape, bShape, false, false, ref overlapResult, logger);
if (!overlapped) {
continue;
}
var colliderDx = (bCollider.X - aCollider.X);
var colliderDy = (bCollider.Y - aCollider.Y);
var absColliderDx = Math.Abs(colliderDx);
var absColliderDy = Math.Abs(colliderDy);
if (v3.BulletTeamId != blWithVision.TeamId) {
// different teams
if (absColliderDx > minAbsColliderDx) {
continue;
}
if (absColliderDx == minAbsColliderDx && absColliderDy > minAbsColliderDy) {
continue;
}
minAbsColliderDx = absColliderDx;
minAbsColliderDy = absColliderDy;
res1 = bCollider;
res1Ch = v3;
} else {
// same team
if (absColliderDx > minAbsColliderDxForAlly) {
continue;
}
if (absColliderDx == minAbsColliderDxForAlly && absColliderDy > minAbsColliderDyForAlly) {
continue;
}
minAbsColliderDxForAlly = absColliderDx;
minAbsColliderDyForAlly = absColliderDy;
res3 = bCollider;
res3Ch = v3;
}
}
}
private static void findHorizontallyClosestPatrolCueCollider(CharacterDownsync currCharacterDownsync, Collider aCollider, Collision collision, ref SatResult overlapResult, out Collider? res1, out PatrolCue? res2, ILoggerBridge logger) {
res1 = null;
res2 = null;
// [WARNING] Finding only the closest patrol cue to react to for avoiding any randomness.
bool collided = aCollider.CheckAllWithHolder(0, 0, collision, COLLIDABLE_PAIRS);
if (!collided) return;
float minAbsColliderDx = MAX_FLOAT32;
float minAbsColliderDy = MAX_FLOAT32;
ConvexPolygon aShape = aCollider.Shape;
while (true) {
var (ok3, bCollider) = collision.PopFirstContactedCollider();
if (false == ok3 || null == bCollider) {
break;
}
PatrolCue? v3 = bCollider.Data as PatrolCue;
if (null == v3) {
// Only check shape collision (which is relatively expensive) if it's PatrolCue
continue;
}
ConvexPolygon bShape = bCollider.Shape;
var (overlapped, _, _) = calcPushbacks(0, 0, aShape, bShape, false, false, ref overlapResult, logger);
if (!overlapped) {
continue;
}
// By now we're sure that it should react to the PatrolCue
var colliderDx = (aCollider.X - bCollider.X);
var absColliderDx = Math.Abs(colliderDx);
if (absColliderDx > minAbsColliderDx) {
continue;
}
var colliderDy = (aCollider.Y - bCollider.Y);
var absColliderDy = Math.Abs(colliderDy);
if (absColliderDx == minAbsColliderDx && absColliderDy > minAbsColliderDy) {
continue;
}
minAbsColliderDx = absColliderDx;
minAbsColliderDy = absColliderDy;
res1 = bCollider;
res2 = v3;
}
}
}
}
| 1 | 0.935647 | 1 | 0.935647 | game-dev | MEDIA | 0.955197 | game-dev | 0.940274 | 1 | 0.940274 |
Admer456/halflife-adm | 3,598 | src/game/server/entities/NPCs/blackmesa/cleansuit_scientist.cpp | /***
*
* Copyright (c) 1996-2001, Valve LLC. All rights reserved.
*
* This product contains software technology licensed from Id
* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc.
* All Rights Reserved.
*
* This source code contains proprietary and confidential information of
* Valve LLC and its suppliers. Access to this code is restricted to
* persons who have executed a written SDK license with Valve. Any access,
* use or distribution of this code by or to any unlicensed person is illegal.
*
****/
#include "cbase.h"
#include "talkmonster.h"
#include "defaultai.h"
#include "scripted.h"
#include "scientist.h"
/**
* @brief human scientist (passive lab worker)
*/
class CCleansuitScientist : public CScientist
{
public:
void OnCreate() override;
void Heal() override;
};
LINK_ENTITY_TO_CLASS(monster_cleansuit_scientist, CCleansuitScientist);
void CCleansuitScientist::OnCreate()
{
CScientist::OnCreate();
pev->health = GetSkillFloat("cleansuit_scientist_health"sv);
pev->model = MAKE_STRING("models/cleansuit_scientist.mdl");
}
void CCleansuitScientist::Heal()
{
if (!CanHeal())
return;
Vector target = m_hTargetEnt->pev->origin - pev->origin;
if (target.Length() > 100)
return;
m_hTargetEnt->GiveHealth(GetSkillFloat("cleansuit_scientist_heal"sv), DMG_GENERIC);
// Don't heal again for 1 minute
m_healTime = gpGlobals->time + 60;
}
class CDeadCleansuitScientist : public CBaseMonster
{
public:
void OnCreate() override;
void Spawn() override;
bool HasHumanGibs() override { return true; }
bool KeyValue(KeyValueData* pkvd) override;
int m_iPose; // which sequence to display
static const char* m_szPoses[9];
};
LINK_ENTITY_TO_CLASS(monster_cleansuit_scientist_dead, CDeadCleansuitScientist);
const char* CDeadCleansuitScientist::m_szPoses[] =
{
"lying_on_back",
"lying_on_stomach",
"dead_sitting",
"dead_hang",
"dead_table1",
"dead_table2",
"dead_table3",
"scientist_deadpose1",
"dead_against_wall"};
void CDeadCleansuitScientist::OnCreate()
{
CBaseMonster::OnCreate();
// Corpses have less health
pev->health = 8; // GetSkillFloat("scientist_health"sv);
pev->model = MAKE_STRING("models/cleansuit_scientist.mdl");
SetClassification("human_passive");
}
bool CDeadCleansuitScientist::KeyValue(KeyValueData* pkvd)
{
if (FStrEq(pkvd->szKeyName, "pose"))
{
m_iPose = atoi(pkvd->szValue);
return true;
}
return CBaseMonster::KeyValue(pkvd);
}
void CDeadCleansuitScientist::Spawn()
{
PrecacheModel(STRING(pev->model));
SetModel(STRING(pev->model));
pev->effects = 0;
pev->sequence = 0;
m_bloodColor = BLOOD_COLOR_RED;
if (pev->body == -1)
{
pev->body = 0;
// -1 chooses a random head
// pick a head, any head
SetBodygroup(ScientistBodygroup::Head, RANDOM_LONG(0, GetBodygroupSubmodelCount(ScientistBodygroup::Head) - 1));
}
// Luther is black, make his hands black
if (pev->body == HEAD_LUTHER)
pev->skin = 1;
else
pev->skin = 0;
pev->sequence = LookupSequence(m_szPoses[m_iPose]);
if (pev->sequence == -1)
{
AILogger->debug("Dead scientist with bad pose");
}
// pev->skin += 2; // use bloody skin -- UNDONE: Turn this back on when we have a bloody skin again!
MonsterInitDead();
}
class CSittingCleansuitScientist : public CSittingScientist // kdb: changed from public CBaseMonster so he can speak
{
public:
void OnCreate()
{
CSittingScientist::OnCreate();
pev->model = MAKE_STRING("models/cleansuit_scientist.mdl");
}
};
LINK_ENTITY_TO_CLASS(monster_sitting_cleansuit_scientist, CSittingCleansuitScientist);
| 1 | 0.955397 | 1 | 0.955397 | game-dev | MEDIA | 0.644063 | game-dev | 0.826552 | 1 | 0.826552 |
OvercastNetwork/SportBukkit | 2,045 | snapshot/Bukkit/src/main/java/org/bukkit/attribute/Attribute.java | package org.bukkit.attribute;
import java.util.HashMap;
import java.util.Map;
/**
* Types of attributes which may be present on an {@link Attributable}.
*/
public enum Attribute {
/**
* Maximum health of an Entity.
*/
GENERIC_MAX_HEALTH("generic.maxHealth"),
/**
* Range at which an Entity will follow others.
*/
GENERIC_FOLLOW_RANGE("generic.followRange"),
/**
* Resistance of an Entity to knockback.
*/
GENERIC_KNOCKBACK_RESISTANCE("generic.knockbackResistance"),
/**
* Movement speed of an Entity.
*/
GENERIC_MOVEMENT_SPEED("generic.movementSpeed"),
/**
* Attack damage of an Entity.
*/
GENERIC_ATTACK_DAMAGE("generic.attackDamage"),
/**
* Attack speed of an Entity.
*/
GENERIC_ATTACK_SPEED("generic.attackSpeed"),
/**
* Armor bonus of an Entity.
*/
GENERIC_ARMOR("generic.armor"),
/**
* Armor bonus of an Entity.
*/
GENERIC_ARMOR_TOUGHNESS("generic.armorToughness"),
/**
* Luck bonus of an Entity.
*/
GENERIC_LUCK("generic.luck"),
/**
* Strength with which a horse will jump.
*/
HORSE_JUMP_STRENGTH("horse.jumpStrength"),
/**
* Chance of a zombie to spawn reinforcements.
*/
ZOMBIE_SPAWN_REINFORCEMENTS("zombie.spawnReinforcements"),
ARROW_ACCURACY("sportbukkit.arrowAccuracy"),
ARROW_VELOCITY_TRANSFER("sportbukkit.arrowVelocityTransfer"),
SHIELD_STRENGTH("sportbukkit.shieldStrength");
private final String name;
Attribute(String name) {
this.name = name;
}
/**
* @return the external name of this attribute
*/
public String getName() {
return name;
}
private static final Map<String, Attribute> byName = new HashMap<String, Attribute>();
static {
for(Attribute attribute : values()) {
byName.put(attribute.getName(), attribute);
}
}
public static Attribute byName(String name) {
return byName.get(name);
}
}
| 1 | 0.777502 | 1 | 0.777502 | game-dev | MEDIA | 0.971019 | game-dev | 0.7574 | 1 | 0.7574 |
ALE-Psych-Crew/ALE-Psych | 3,605 | source/funkin/visuals/cutscenes/DialogueCharacter.hx | package funkin.visuals.cutscenes;
import lime.utils.Assets;
import sys.FileSystem;
typedef DialogueAnimArray = {
var anim:String;
var loop_name:String;
var loop_offsets:Array<Int>;
var idle_name:String;
var idle_offsets:Array<Int>;
}
typedef DialogueCharacterFile = {
var image:String;
var dialogue_pos:String;
var no_antialiasing:Bool;
var animations:Array<DialogueAnimArray>;
var position:Array<Float>;
var scale:Float;
}
class DialogueCharacter extends FlxSprite
{
private static var IDLE_SUFFIX:String = '-IDLE';
public static var DEFAULT_CHARACTER:String = 'bf';
public static var DEFAULT_SCALE:Float = 0.7;
public var jsonFile:DialogueCharacterFile = null;
public var dialogueAnimations:Map<String, DialogueAnimArray> = new Map<String, DialogueAnimArray>();
public var startingPos:Float = 0; //For center characters, it works as the starting Y, for everything else it works as starting X
public var isGhost:Bool = false; //For the editor
public var curCharacter:String = 'bf';
public var skiptimer = 0;
public var skipping = 0;
public function new(x:Float = 0, y:Float = 0, character:String = null)
{
super(x, y);
if(character == null) character = DEFAULT_CHARACTER;
this.curCharacter = character;
reloadCharacterJson(character);
frames = Paths.getSparrowAtlas('dialogue/' + jsonFile.image);
reloadAnimations();
antialiasing = ClientPrefs.data.antialiasing;
if(jsonFile.no_antialiasing == true) antialiasing = false;
}
public function reloadCharacterJson(character:String) {
var characterPath:String = 'images/dialogue/' + character + '.json';
var rawJson = null;
if (Paths.exists(characterPath))
rawJson = Paths.getContent(characterPath);
jsonFile = cast Json.parse(rawJson);
}
public function reloadAnimations() {
dialogueAnimations.clear();
if(jsonFile.animations != null && jsonFile.animations.length > 0) {
for (anim in jsonFile.animations) {
animation.addByPrefix(anim.anim, anim.loop_name, 24, isGhost);
animation.addByPrefix(anim.anim + IDLE_SUFFIX, anim.idle_name, 24, true);
dialogueAnimations.set(anim.anim, anim);
}
}
}
public function playAnim(animName:String = null, playIdle:Bool = false) {
var leAnim:String = animName;
if(animName == null || !dialogueAnimations.exists(animName)) { //Anim is null, get a random animation
var arrayAnims:Array<String> = [];
for (anim in dialogueAnimations) {
arrayAnims.push(anim.anim);
}
if(arrayAnims.length > 0) {
leAnim = arrayAnims[FlxG.random.int(0, arrayAnims.length-1)];
}
}
if(dialogueAnimations.exists(leAnim) &&
(dialogueAnimations.get(leAnim).loop_name == null ||
dialogueAnimations.get(leAnim).loop_name.length < 1 ||
dialogueAnimations.get(leAnim).loop_name == dialogueAnimations.get(leAnim).idle_name)) {
playIdle = true;
}
animation.play(playIdle ? leAnim + IDLE_SUFFIX : leAnim, false);
if(dialogueAnimations.exists(leAnim)) {
var anim:DialogueAnimArray = dialogueAnimations.get(leAnim);
if(playIdle) {
offset.set(anim.idle_offsets[0], anim.idle_offsets[1]);
//trace('Setting idle offsets: ' + anim.idle_offsets);
} else {
offset.set(anim.loop_offsets[0], anim.loop_offsets[1]);
//trace('Setting loop offsets: ' + anim.loop_offsets);
}
} else {
offset.set(0, 0);
trace('Offsets not found! Dialogue character is badly formatted, anim: ' + leAnim + ', ' + (playIdle ? 'idle anim' : 'loop anim'));
}
}
public function animationIsLoop():Bool {
if(animation.curAnim == null) return false;
return !animation.curAnim.name.endsWith(IDLE_SUFFIX);
}
} | 1 | 0.740224 | 1 | 0.740224 | game-dev | MEDIA | 0.658049 | game-dev | 0.894262 | 1 | 0.894262 |
c-ostic/OriBFArchipelago | 12,176 | Core/RandomizerManager.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using CatlikeCoding.TextBox;
using HarmonyLib;
using OriBFArchipelago.MapTracker.Core;
using System.Collections;
namespace OriBFArchipelago.Core
{
/**
* Creates and manages both the archipelago connection and the randomizer instance when starting a save slot
*/
internal class RandomizerManager : MonoBehaviour
{
public static RandomizerReceiver Receiver { get { return instance.receiver; } }
public static ArchipelagoConnection Connection { get { return instance.connection; } }
public static RandomizerOptions Options { get { return instance.options; } }
public static bool ArchipelagoIOFocussed { get { return instance.archipelagoIOFocussed; } }
public static RandomizerManager instance;
// references to both the receiver and the connection
private RandomizerReceiver receiver;
private ArchipelagoConnection connection;
private RandomizerOptions options;
private bool failedToStart, archipelagoIOFocussed;
private Dictionary<int, SlotData> saveSlots;
// strings associated with the gui buttons in OnGUI
private string slotName = "", server = "", port = "", password = "";
/**
* Called at game launch
*/
private void Awake()
{
instance = this;
if (RandomizerIO.ReadSlotData(out saveSlots))
{
Console.WriteLine("Successfully read slot data");
}
else
{
Console.WriteLine("Could not read slot data");
}
RandomizerSettings.InGame = false;
failedToStart = false;
}
/**
* Called every frame
*/
private void Update()
{
// Call the update method on the receiver while in game
if (RandomizerSettings.InGame)
{
receiver.Update();
connection.Update();
}
// If loading into a level failed to start, re-enable the save slots ui
if (failedToStart)
{
FindObjectOfType<SaveSlotsUI>().Active = true;
failedToStart = false;
}
}
/**
* Create a UI to allow the user to input archipelago data
*/
private void OnGUI()
{
// Only display this UI when on the save select screen
if (RandomizerSettings.InSaveSelect)
{
GUILayout.BeginArea(new Rect(5, 5, 300, 200));
GUILayout.BeginVertical();
Dictionary<string, string> fields = new Dictionary<string, string>
{
{"Slot Name", slotName},
{"Server", server},
{"Port", port},
{"Password", password}
};
// Create an area for slot name
GUILayout.BeginHorizontal();
GUILayout.Label("Slot Name");
GUI.SetNextControlName("slotname");
slotName = GUILayout.TextField(slotName, 50, GUILayout.Width(200));
GUILayout.EndHorizontal();
// Create an area for server name
GUILayout.BeginHorizontal();
GUILayout.Label("Server");
GUI.SetNextControlName("server");
server = GUILayout.TextField(server, 50, GUILayout.Width(200));
GUILayout.EndHorizontal();
// Create an area for port number
GUILayout.BeginHorizontal();
GUILayout.Label("Port");
GUI.SetNextControlName("port");
port = GUILayout.TextField(port, 50, GUILayout.Width(200));
GUILayout.EndHorizontal();
// Create an area for password
GUILayout.BeginHorizontal();
GUILayout.Label("Password");
GUI.SetNextControlName("password");
password = GUILayout.TextField(password, 50, GUILayout.Width(200));
GUILayout.EndHorizontal();
GUILayout.EndVertical();
GUILayout.EndArea();
archipelagoIOFocussed = new string[] { "slotname", "server", "port", "password" }.Contains(GUI.GetNameOfFocusedControl());
}
}
/**
* Called when selecting a save slot, but not starting it yet
*/
public void InspectSaveSlot(int index)
{
if (SaveSlotsUI.Instance is not null && index >= 0 && index < saveSlots.Count)
{
SlotData data = saveSlots[index];
slotName = data.slotName;
server = data.serverName;
port = data.port + "";
password = data.password;
}
}
public bool CopySaveSlot(int from, int to)
{
saveSlots[to] = saveSlots[from];
RandomizerIO.WriteSlotData(saveSlots);
InspectSaveSlot(to);
return true;
}
/**
* Called when attempting to start a save slot
* Returns false if there is a problem with the save slot data or archipelago connection
*/
public bool StartSaveSlot(bool isNew)
{
string missingFields = string.Join(", ", new[] { string.IsNullOrEmpty(slotName) ? "slotname" : null, string.IsNullOrEmpty(server) ? "server" : null, string.IsNullOrEmpty(port) ? "port" : null }.Where(f => f != null).ToArray());
if (!string.IsNullOrEmpty(missingFields))
{
RandomizerMessager.instance.AddMessage($"Required fields are empty: {missingFields}");
failedToStart = true;
return false;
}
RandomizerMessager.instance.AddMessage($"Attempting to connect to {server}:{port} {slotName}");
int saveSlot = SaveSlotsUI.Instance.CurrentSlotIndex;
Console.WriteLine($"Starting save slot {saveSlot}");
bool canStart = true;
// Attempt to load the this slots data first
receiver = new RandomizerReceiver();
if (!receiver.Init(isNew, saveSlot, slotName))
{
Console.WriteLine("Slot name provided does not match save file");
failedToStart = true;
return false;
}
// Attempt to connect to archipelago only if the save slot was loaded correctly
connection = new ArchipelagoConnection();
int.TryParse(port, out int parsedPort);
if (!canStart || !connection.Init(server, parsedPort, slotName, password))
{
canStart = false;
Console.WriteLine("Could not connect to archipelago server");
}
receiver.SyncArchipelagoCheckedLocations(connection.GetArchipelagoCheckedLocations());
// Check if the game can start
if (canStart)
{
// If so, set necessary flags and update the slot data
RandomizerSettings.InGame = true;
RandomizerSettings.InSaveSelect = false;
SlotData updatedData = new SlotData();
updatedData.slotName = slotName;
updatedData.serverName = server;
updatedData.port = parsedPort;
updatedData.password = password;
saveSlots[saveSlot] = updatedData;
RandomizerIO.WriteSlotData(saveSlots);
options = new RandomizerOptions(connection.SlotData);
if (options.DeathLinkLogic != DeathLinkOptions.Disabled)
{
connection.EnableDeathLink(true);
}
}
else
{
// Otherwise, trip failedToStart flag so UI can be re-enabled
failedToStart = true;
}
return canStart;
}
/**
* Called when returning to the main menu from a save
*/
public void QuitSaveSlot()
{
Console.WriteLine($"Quitting save slot {SaveSlotsManager.CurrentSlotIndex}");
RandomizerSettings.InGame = false;
receiver.OnSave(true);
connection.Disconnect();
connection = null;
receiver = null;
LocalGameState.Reset();
}
/**
* Called when deleting a save slot
*/
public void DeleteSaveSlot(int index)
{
Console.WriteLine($"Deleting save slot {index}");
// Delete connection data
saveSlots[index] = new SlotData();
RandomizerIO.WriteSlotData(saveSlots);
// Reinspect the save slot to clear out the previous data
InspectSaveSlot(SaveSlotsUI.Instance.CurrentSlotIndex);
// Delete slot data
RandomizerIO.DeleteSaveFile(index);
}
internal static void CollectSein()
{
Connection.StoreSeinInArchipelagoSession();
Receiver.ReceiveItem(InventoryItem.SpiritFlame);
}
internal static bool IsSeinCollected()
{
if (Connection == null)
return false;
return Connection.IsSeinCollected();
}
}
/**
* Patch into the function that loads a pre-existing save file
*/
[HarmonyPatch(typeof(SaveSlotsUI), nameof(SaveSlotsUI.UsedSaveSlotSelected))]
internal class LoadGamePatch
{
private static bool Prefix()
{
var canStart = RandomizerManager.instance.StartSaveSlot(false);
return canStart;
}
}
/**
* Patch into the function that creates a new save file
*/
[HarmonyPatch(typeof(SaveSlotsUI), nameof(SaveSlotsUI.SetDifficulty))]
internal class NewGamePatch
{
private static bool Prefix()
{
var canStart = RandomizerManager.instance.StartSaveSlot(true);
return canStart;
}
}
/**
* Patch into the function that determines which save is currently selected
*/
[HarmonyPatch(typeof(SaveSlotsUI), nameof(SaveSlotsUI.SetCurrentItem), typeof(int))]
internal class InspectSavePatch
{
private static bool Prefix(int index)
{
RandomizerManager.instance.InspectSaveSlot(index);
return true;
}
}
/**
* Patch into the function that is called when returning to main menu
*/
[HarmonyPatch(typeof(ReturnToTitleScreenAction), nameof(ReturnToTitleScreenAction.Perform))]
internal class ReturnToTitleScreenPatch
{
private static bool Prefix()
{
RandomizerManager.instance.QuitSaveSlot();
return true;
}
}
/**
* Patch into the function called when deleting a save slot
*/
[HarmonyPatch(typeof(SaveSlotsManager), nameof(SaveSlotsManager.DeleteSlot))]
internal class DeleteSavePatch
{
private static bool Prefix(int index)
{
RandomizerManager.instance.DeleteSaveSlot(index);
MaptrackerSettings.Delete();
return true;
}
}
/**
* Patch into the function called when copying a save slot
*/
[HarmonyPatch(typeof(SaveSlotsManager), nameof(SaveSlotsManager.CopySlot))]
internal class CopySaveFilePatch
{
private static void Prefix(int from, int to)
{
RandomizerManager.instance.CopySaveSlot(from, to);
RandomizerIO.CopySaveFile(from, to);
}
}
/**
* Prevent the refreshing of controls while editing
*/
[HarmonyPatch(typeof(PlayerInput), nameof(PlayerInput.FixedUpdate))]
internal class PreventPlayerInputPatch
{
private static bool Prefix()
{
return !RandomizerManager.ArchipelagoIOFocussed;
}
}
}
| 1 | 0.987646 | 1 | 0.987646 | game-dev | MEDIA | 0.566213 | game-dev | 0.985411 | 1 | 0.985411 |
liballeg/allegro5 | 2,075 | demos/shooter/bullet.c | #include "bullet.h"
#include "data.h"
#include "aster.h"
#include "game.h"
/* position of the bullets */
#define BULLET_SPEED 6
BULLET *bullet_list;
/* add a bullet to the list */
BULLET *add_bullet(int x, int y)
{
BULLET *iter, *bullet;
bullet = (BULLET *) malloc(sizeof(BULLET));
bullet->x = x;
bullet->y = y;
bullet->next = NULL;
/* special treatment for head */
if (!bullet_list) {
bullet_list = bullet;
}
else {
for (iter = bullet_list; iter->next; iter = iter->next) ;
iter->next = bullet;
}
return bullet;
}
/* delete a bullet and return the next in the list */
BULLET *delete_bullet(BULLET * bullet)
{
BULLET *iter;
/* special treatment for head */
if (bullet == bullet_list) {
bullet_list = bullet->next;
free(bullet);
return bullet_list;
}
else {
for (iter = bullet_list; iter->next != bullet; iter = iter->next) ;
iter->next = bullet->next;
free(bullet);
return iter->next;
}
}
void move_bullets(void)
{
BULLET *bullet = bullet_list;
while (bullet) {
bullet->y -= BULLET_SPEED;
/* if the bullet is at the top of the screen, delete it */
if (bullet->y < 8) {
bullet = delete_bullet(bullet);
goto bullet_updated;
}
else {
/* shot an asteroid? */
if (asteroid_collision(bullet->x, bullet->y, 20)) {
score += 10;
play_sample(data[BOOM_SPL].dat, 255, PAN(bullet->x), 1000, FALSE);
/* delete the bullet that killed the alien */
bullet = delete_bullet(bullet);
goto bullet_updated;
}
}
bullet = bullet->next;
bullet_updated:;
}
}
void draw_bullets()
{
BULLET *bullet;
for (bullet = bullet_list; bullet; bullet = bullet->next) {
int x = bullet->x;
int y = bullet->y;
RLE_SPRITE *spr = data[ROCKET].dat;
int sprw = al_get_bitmap_width(spr);
int sprh = al_get_bitmap_height(spr);
draw_sprite(spr, x - sprw / 2, y - sprh / 2);
}
}
| 1 | 0.569109 | 1 | 0.569109 | game-dev | MEDIA | 0.34472 | game-dev | 0.725856 | 1 | 0.725856 |
cyllab/CalcUS | 2,296 | static/j2s/J/adapter/readers/simple/OrcaReader.js | Clazz.declarePackage ("J.adapter.readers.simple");
Clazz.load (["J.adapter.smarter.AtomSetCollectionReader"], "J.adapter.readers.simple.OrcaReader", ["java.lang.Float"], function () {
c$ = Clazz.decorateAsClass (function () {
this.chargeTag = null;
this.atomCount = 0;
this.xyzBohr = false;
Clazz.instantialize (this, arguments);
}, J.adapter.readers.simple, "OrcaReader", J.adapter.smarter.AtomSetCollectionReader);
Clazz.overrideMethod (c$, "initializeReader",
function () {
this.chargeTag = (this.checkAndRemoveFilterKey ("CHARGE=LOW") ? "LOEW" : "MULL");
});
Clazz.overrideMethod (c$, "checkLine",
function () {
if (this.line.startsWith ("! Bohrs")) {
this.xyzBohr = true;
return true;
}if (this.line.startsWith ("* xyz") || this.line.startsWith ("*xyz")) {
this.processInputFile ();
this.continuing = false;
return false;
}if (this.line.indexOf ("CARTESIAN COORDINATES (ANG") >= 0) {
this.processCoordinates ();
return true;
}if (this.line.indexOf ("ATOMIC CHARGES") >= 0 && this.line.indexOf (this.chargeTag) >= 0) {
this.processAtomicCharges ();
return true;
}if (this.line.startsWith ("Total Energy")) {
this.processEnergyLine ();
return true;
}return true;
});
Clazz.defineMethod (c$, "processEnergyLine",
function () {
var tokens = this.getTokens ();
this.asc.setAtomSetEnergy (tokens[3], Float.parseFloat (tokens[3]));
});
Clazz.defineMethod (c$, "processInputFile",
function () {
while (this.rd () != null) {
while (this.line.trim ().length == 0 || this.line.startsWith ("#")) {
this.rd ();
}
if (this.line.indexOf ("*") >= 0) break;
var tokens = this.getTokens ();
var a = this.addAtomXYZSymName (tokens, 1, tokens[0], null);
if (this.xyzBohr) a.scale (0.5291772);
}
});
Clazz.defineMethod (c$, "processCoordinates",
function () {
this.asc.newAtomSet ();
this.baseAtomIndex = this.asc.ac;
this.rd ();
while (this.rd () != null) {
var tokens = this.getTokens ();
if (tokens.length != 4) break;
this.addAtomXYZSymName (tokens, 1, tokens[0], null);
}
if (this.baseAtomIndex == 0) this.atomCount = this.asc.ac;
});
Clazz.defineMethod (c$, "processAtomicCharges",
function () {
this.rd ();
for (var i = 0; i < this.atomCount; i++) {
this.rd ();
this.asc.atoms[i + this.baseAtomIndex].partialCharge = Float.parseFloat (this.line.substring (this.line.indexOf (":") + 1));
}
});
});
| 1 | 0.830195 | 1 | 0.830195 | game-dev | MEDIA | 0.280434 | game-dev | 0.906115 | 1 | 0.906115 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.