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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
docknetwork/crypto | 3,134 | vb_accumulator/src/persistence.rs | //! Interfaces for persistent storage of accumulators
use ark_std::iter::Iterator;
/// Database interface implemented for the universal accumulator and holds the accumulator members created during setup.
/// These members are never added or removed from the accumulator. Only the accumulator manager needs to keep this.
/// A production implementation of this could be persistent key-value store like LevelDb or Rocksdb.
pub trait InitialElementsStore<T> {
/// Add element
fn add(&mut self, element: T);
/// Check if element is present
fn has(&self, element: &T) -> bool;
}
/// Database interface implemented for the accumulators to store elements present in the accumulator. As elements
/// are added or removed from the accumulator, this database is updated.
pub trait State<T> {
/// Add element
fn add(&mut self, element: T);
/// Remove element
fn remove(&mut self, element: &T);
/// Check if element is present
fn has(&self, element: &T) -> bool;
/// Number of elements currently present
fn size(&self) -> u64;
}
/// Database interface implemented for universal accumulator for calculating non-membership witness. This
/// interface expects the database to be able to return all elements present.
pub trait UniversalAccumulatorState<'a, T: 'a>: State<T> {
type ElementIterator: Iterator<Item = &'a T>;
/// Return an iterator over all elements present.
fn elements(&'a self) -> Self::ElementIterator;
}
#[cfg(test)]
pub mod test {
use super::*;
use std::{collections::HashSet, hash::Hash};
// In-memory stores for testing.
#[derive(Clone, Debug)]
pub struct InMemoryInitialElements<T: Clone> {
pub db: HashSet<T>,
}
impl<T: Clone> InMemoryInitialElements<T> {
pub fn new() -> Self {
let db = HashSet::<T>::new();
Self { db }
}
}
impl<T: Clone + Hash + Eq> InitialElementsStore<T> for InMemoryInitialElements<T> {
fn add(&mut self, element: T) {
self.db.insert(element);
}
fn has(&self, element: &T) -> bool {
self.db.get(element).is_some()
}
}
#[derive(Clone, Debug)]
pub struct InMemoryState<T: Clone> {
pub db: HashSet<T>,
}
impl<T: Clone> InMemoryState<T> {
pub fn new() -> Self {
let db = HashSet::<T>::new();
Self { db }
}
}
impl<T: Clone + Hash + Eq + Sized> State<T> for InMemoryState<T> {
fn add(&mut self, element: T) {
self.db.insert(element);
}
fn remove(&mut self, element: &T) {
self.db.remove(element);
}
fn has(&self, element: &T) -> bool {
self.db.get(element).is_some()
}
fn size(&self) -> u64 {
self.db.len() as u64
}
}
impl<'a, T: Clone + Hash + Eq + Sized + 'a> UniversalAccumulatorState<'a, T> for InMemoryState<T> {
type ElementIterator = std::collections::hash_set::Iter<'a, T>;
fn elements(&'a self) -> Self::ElementIterator {
self.db.iter()
}
}
}
| 412 | 0.922631 | 1 | 0.922631 | game-dev | MEDIA | 0.51453 | game-dev | 0.95825 | 1 | 0.95825 |
MATTYOneInc/AionEncomBase_Java8 | 4,812 | AL-Game_SoloPlay_patches/data/scripts/system/handlers/quest/reshanta/_3735Glory_Against_The_9th.java | /*
* =====================================================================================*
* This file is part of Aion-Unique (Aion-Unique Home Software Development) *
* Aion-Unique Development is a closed Aion Project that use Old Aion Project Base *
* Like Aion-Lightning, Aion-Engine, Aion-Core, Aion-Extreme, Aion-NextGen, ArchSoft, *
* Aion-Ger, U3J, Encom And other Aion project, All Credit Content *
* That they make is belong to them/Copyright is belong to them. And All new Content *
* that Aion-Unique make the copyright is belong to Aion-Unique *
* You may have agreement with Aion-Unique Development, before use this Engine/Source *
* You have agree with all of Term of Services agreement with Aion-Unique Development *
* =====================================================================================*
*/
package quest.reshanta;
import com.aionemu.gameserver.model.gameobjects.player.Player;
import com.aionemu.gameserver.questEngine.handlers.QuestHandler;
import com.aionemu.gameserver.questEngine.model.QuestDialog;
import com.aionemu.gameserver.questEngine.model.QuestEnv;
import com.aionemu.gameserver.questEngine.model.QuestState;
import com.aionemu.gameserver.questEngine.model.QuestStatus;
import com.aionemu.gameserver.utils.stats.AbyssRankEnum;
/****/
/** MATTYOne DainAvenger Ptich
/****/
public class _3735Glory_Against_The_9th extends QuestHandler {
private final static int questId = 3735;
private final static int REQUIRED_KILLS = 1; // summ of NPC needed to kill
// NPC ID, that needs to kill
private final static int[] mobs = {205395, 205396, 205397, 205398, 205399, 205400, 205401, 205402, 217476, 217477, 217478, 217479, 217480, 217481, 217482, 217483, 205404, 205405, 205406, 205407, 205408, 205409, 205410, 205411, 217485, 217486, 217487, 217488, 217489, 217490, 217491, 217492};
public _3735Glory_Against_The_9th() {
super(questId);
}
@Override
public void register() {
qe.registerQuestNpc(278535).addOnQuestStart(questId); //Maius.
qe.registerQuestNpc(278535).addOnTalkEvent(questId); //Maius.
// register NPC in case to kill
for (int mobId : mobs) {
qe.registerQuestNpc(mobId).addOnKillEvent(questId);
}
}
@Override
public boolean onKillEvent(QuestEnv env) {
Player player = env.getPlayer();
QuestState qs = player.getQuestStateList().getQuestState(questId);
if (qs == null || qs.getStatus() != QuestStatus.START) {
return false;
}
int targetId = env.getTargetId();
int killCount = qs.getQuestVarById(1); // Killed NPC
boolean killCounted = false;
// If we kill the opposite faction, then:
if (env.getVisibleObject() instanceof Player && player.getWorldId() == 400010000) {
Player target = (Player) env.getVisibleObject();
if ((env.getPlayer().getLevel() >= (target.getLevel() - 5)) && (env.getPlayer().getLevel() <= (target.getLevel() + 9))) {
killCounted = true;
}
}
// Check NPC ID from list in top
for (int mobId : mobs) {
if (targetId == mobId) {
killCounted = true;
break;
}
}
if (killCounted) {
killCount++; // Kill counter ++
if (killCount >= REQUIRED_KILLS) {
killCount = REQUIRED_KILLS; // TODO
qs.setQuestVarById(0, 1);
qs.setStatus(QuestStatus.REWARD); // If we made MOBS_KILLS = 1 of NPC, then make status REWARD
}
qs.setQuestVarById(1, killCount); // Update variable
updateQuestStatus(env);
return true;
}
return false;
}
@Override
public boolean onDialogEvent(QuestEnv env) {
final Player player = env.getPlayer();
final QuestState qs = player.getQuestStateList().getQuestState(questId);
if (qs == null || qs.getStatus() == QuestStatus.NONE) {
if (env.getTargetId() == 278535) { //Maius.
switch (env.getDialog()) {
case START_DIALOG: {
return sendQuestDialog(env, 4762);
}
case ACCEPT_QUEST_SIMPLE: {
return sendQuestStartDialog(env);
}
case REFUSE_QUEST_SIMPLE: {
return closeDialogWindow(env);
}
}
}
if (qs == null || qs.getStatus() == QuestStatus.REWARD) {
if (env.getTargetId() == 278535) { //Maius.
if (env.getDialog() == QuestDialog.START_DIALOG) {
return sendQuestDialog(env, 10002);
} else if (env.getDialog() == QuestDialog.SELECT_REWARD) {
return sendQuestDialog(env, 5);
} else {
return sendQuestEndDialog(env);
}
}
}
}
return false;
}
} | 412 | 0.951281 | 1 | 0.951281 | game-dev | MEDIA | 0.990959 | game-dev | 0.977519 | 1 | 0.977519 |
buinger/BuingerUnityScripts | 10,932 | GameObjectPoolTool.cs | using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.UI;
public class GameObjectPoolTool : MonoBehaviour
{
public static GameObject GetFromPool(bool active, string fullname)
{
string aimFullName = fullname;
aimFullName = GameObjectPool.FormatPath4ResourceLoad(aimFullName);
GameObject aimGameObj;
aimGameObj = GameObjectPool.OutPool(aimFullName);
if (aimGameObj == null)
{
return null;
}
else
{
//aimGameObj.transform.SetParent(null);
aimGameObj.SetActive(active);
return aimGameObj;
}
}
public static GameObject GetFromPool(string fullName, Vector3 postion, Transform father, bool isLocalSet = false)
{
GameObject aimGameObj = GetFromPool(true, fullName);
aimGameObj.transform.SetParent(father);
if (isLocalSet)
{
aimGameObj.transform.localPosition = postion;
}
else
{
aimGameObj.transform.position = postion;
}
return aimGameObj;
}
public static async Task<GameObject> GetFromPoolForceAsync(bool active, string fullname)
{
string aimFullName = fullname;
aimFullName = GameObjectPool.FormatPath4ResourceLoad(aimFullName);
GameObject aimGameObj;
aimGameObj = GameObjectPool.OutPool(aimFullName);
if (aimGameObj == null)
{
Task getResource = GameObjectPool.PreLoadPrefabToPoolAsync(aimFullName);
await getResource;
aimGameObj = GameObjectPool.OutPool(aimFullName);
aimGameObj.SetActive(active);
return aimGameObj;
}
else
{
//aimGameObj.transform.SetParent(null);
aimGameObj.SetActive(active);
return aimGameObj;
}
}
public static GameObject GetFromPoolForce(bool active, string fullname)
{
string aimFullName = fullname;
aimFullName = GameObjectPool.FormatPath4ResourceLoad(aimFullName);
GameObject aimGameObj;
aimGameObj = GameObjectPool.OutPool(aimFullName);
if (aimGameObj == null)
{
GameObjectPool.PreLoadPrefabToPool(aimFullName);
aimGameObj = GameObjectPool.OutPool(aimFullName);
aimGameObj.SetActive(active);
return aimGameObj;
}
else
{
//aimGameObj.transform.SetParent(null);
aimGameObj.SetActive(active);
return aimGameObj;
}
}
public static GameObject GetFromPool(bool active, string fullname, Vector3 postion)
{
GameObject aimGameObj = GetFromPool(active, fullname);
if (aimGameObj == null)
{
return null;
}
aimGameObj.transform.position = postion;
return aimGameObj;
}
public static GameObject GetFromPool(bool active, string fullname, Vector3 postion, Transform father, bool isLocalSet = false)
{
GameObject aimGameObj = GetFromPool(active, fullname);
if (aimGameObj == null)
{
return null;
}
aimGameObj.transform.SetParent(father);
aimGameObj.transform.localScale = Vector3.one;
if (isLocalSet)
{
aimGameObj.transform.localPosition = postion;
}
else
{
aimGameObj.transform.position = postion;
}
return aimGameObj;
}
//public GameObject GetFromPoolLikeFather(string fullname, Transform tempTrans, bool beSon = false)
//{
// GameObject aimGameObj = GetFromPool(fullname);
// if (aimGameObj == null)
// {
// return null;
// }
// if (beSon == true)
// {
// aimGameObj.transform.SetParent(tempTrans);
// aimGameObj.transform.position = Vector3.zero;
// aimGameObj.transform.rotation = Quaternion.identity;
// }
// else
// {
// aimGameObj.transform.position = tempTrans.position;
// aimGameObj.transform.rotation = tempTrans.rotation;
// }
// return aimGameObj;
//}
public static void PutInPool(GameObject gameObj)
{
GameObjectPool.InPool(gameObj);
}
public static void Release(bool releaseAll = false)
{
if (releaseAll)
{
GameObjectPool.ReleaseAll();
}
else
{
GameObjectPool.ReleaseEmptyObj();
}
}
//-------------------------------Plot池
public class GameObjectPool
{
//池字典
public static Dictionary<string, List<GameObject>> itemPool = new Dictionary<string, List<GameObject>>();
//加载过的资源
public static Dictionary<string, GameObject> loadedPrefabs = new Dictionary<string, GameObject>();
public static void ReleaseAll()
{
foreach (var item in itemPool)
{
foreach (GameObject obj in item.Value)
{
if (obj != null)
{
Destroy(obj);
}
}
}
itemPool.Clear();
}
public static void ReleaseEmptyObj()
{
List<GameObject> allEmptyObj = new List<GameObject>();
foreach (var item in itemPool)
{
List<GameObject> tempEmptyObj = new List<GameObject>();
foreach (GameObject obj in item.Value)
{
if (obj == null)
{
tempEmptyObj.Add(obj);
allEmptyObj.Add(obj);
}
}
foreach (GameObject obj in tempEmptyObj)
{
item.Value.Remove(obj);
}
}
}
public static void InPool(GameObject gameObj)
{
//Button but = gameObj.GetComponent<Button>();
//if (but != null)
//{
// but.onClick.RemoveAllListeners();
//}
if (itemPool.ContainsKey(gameObj.name) == false)
{
itemPool.Add(gameObj.name, new List<GameObject>());
}
gameObj.SetActive(false);
if (!itemPool[gameObj.name].Contains(gameObj))
{
itemPool[gameObj.name].Add(gameObj);
}
}
public static GameObject OutPool(string assetPath)
{
if (itemPool.ContainsKey(assetPath) == false)
{
itemPool.Add(assetPath, new List<GameObject>());
}
if (itemPool[assetPath].Count == 0)
{
return null;
}
else
{
GameObject outGo = itemPool[assetPath][0];
itemPool[assetPath].Remove(outGo);
if (outGo != null)
{
//这里有竞争条件,可能要Lock
outGo.SetActive(true);
return outGo;
}
else
{
return OutPool(assetPath);
}
}
}
/// <summary>
/// 通过路径获取预制件名字
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
private static string GetNameFromPrefabPath(string path)
{
string target = "";
string[] strs = path.Split('/');
if (strs.Length != 0)
{
string temp = strs[strs.Length - 1];
target = FormatPath4ResourceLoad(temp);
}
return target;
}
public static string FormatPath4ResourceLoad(string oringnal)
{
string target = oringnal;
if (target.Contains(".prefab"))
{
target = target.Replace(".prefab", "");
}
if (target.Contains("Assets/Resources/"))
{
target = target.Replace("Assets/Resources/", "");
}
return target;
}
/// <summary>
/// 协程
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static IEnumerator PreLoadPrefabToPoolIE(string path)
{
string assetPath = path;
assetPath = FormatPath4ResourceLoad(assetPath);
Task<GameObject> loadTask = LoadGameObjectAsync(path);
while (!loadTask.IsCompleted)
{
yield return null;
}
GameObject loadedObject = Instantiate(loadTask.Result);
loadedObject.name = path;
InPool(loadedObject);
yield return loadedObject;
}
/// <summary>
/// 异步
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public async static Task<GameObject> PreLoadPrefabToPoolAsync(string path)
{
string assetPath = path;
assetPath = FormatPath4ResourceLoad(assetPath);
Task<GameObject> loadTask = LoadGameObjectAsync(path);
await loadTask;
GameObject loadedObject = Instantiate(loadTask.Result);
loadedObject.name = path;
InPool(loadedObject);
return loadedObject;
}
public static GameObject PreLoadPrefabToPool(string path)
{
string assetPath = path;
assetPath = FormatPath4ResourceLoad(assetPath);
GameObject gameObj = LoadGameObject(path);
GameObject loadedObject = Instantiate(gameObj);
loadedObject.name = path;
InPool(loadedObject);
return loadedObject;
}
static async Task<GameObject> LoadGameObjectAsync(string path)
{
if (loadedPrefabs.ContainsKey(path))
{
return loadedPrefabs[path];
}
else
{
ResourceRequest rr = Resources.LoadAsync<GameObject>(path);
while (rr.isDone == false) await Task.Delay(100);
GameObject gameObj = rr.asset as GameObject;
loadedPrefabs.Add(path, gameObj);
return gameObj;
}
}
static GameObject LoadGameObject(string path)
{
if (loadedPrefabs.ContainsKey(path))
{
return loadedPrefabs[path];
}
else
{
GameObject gameObj = Resources.Load<GameObject>(path);
loadedPrefabs.Add(path, gameObj);
return gameObj;
}
}
}
}
| 412 | 0.575978 | 1 | 0.575978 | game-dev | MEDIA | 0.920583 | game-dev | 0.903842 | 1 | 0.903842 |
Grimrukh/soulstruct | 4,612 | src/soulstruct/eldenring/events/vanilla/m61_47_47_10.evs.py | """
Land of Shadow 11-11 (Alternate) NE NE
linked:
0
82
strings:
0: N:\\GR\\data\\Param\\event\\common_func.emevd
82: N:\\GR\\data\\Param\\event\\common_macro.emevd
166:
168:
170:
172:
174:
"""
# [COMMON_FUNC]
from .common_func import *
from soulstruct.eldenring.events import *
from soulstruct.eldenring.events.instructions import *
from soulstruct.eldenring.game_types import *
@ContinueOnRest(0)
def Constructor():
"""Event 0"""
RegisterGrace(grace_flag=76940, asset=2047471950)
CommonFunc_90005102(
0,
flag=76945,
flag_1=76940,
asset=2047471980,
source_flag=77900,
value=2,
flag_2=78900,
flag_3=78901,
flag_4=78902,
flag_5=78903,
flag_6=78904,
flag_7=78905,
flag_8=78906,
flag_9=78907,
flag_10=78908,
flag_11=78909,
flag_12=9146,
)
Event_2047472200(0, attacker__character=2047475200, region=2047472200)
Event_2047472201(0, character=2047475201)
Event_2047472202(0, character=2047475202)
Event_2047472203(0, character=2047475203)
CommonFunc_90005201(
0,
character=2047470200,
animation_id=30006,
animation_id_1=20006,
radius=10.0,
seconds=0.0,
left=0,
left_1=0,
left_2=0,
left_3=0,
)
CommonFunc_90005501(
0,
flag=2047470510,
flag_1=2047470511,
left=1,
asset=2047471510,
asset_1=2047471511,
asset_2=2047471512,
flag_2=2047470512,
)
Event_2047472510()
CommonFunc_900005610(0, asset=2047472500, dummy_id=100, vfx_id=800, right=0)
@ContinueOnRest(50)
def Preconstructor():
"""Event 50"""
Event_2047470050()
@ContinueOnRest(2047470050)
def Event_2047470050():
"""Event 2047470050"""
if ThisEventSlotFlagEnabled():
return
EnableFlag(2047470510)
@RestartOnRest(2047472200)
def Event_2047472200(_, attacker__character: uint, region: Region | int):
"""Event 2047472200"""
RemoveSpecialEffect(attacker__character, 90020)
RemoveSpecialEffect(attacker__character, 4800)
RemoveSpecialEffect(attacker__character, 5650)
AddSpecialEffect(attacker__character, 4802)
if FlagEnabled(2047472200):
return
AddSpecialEffect(attacker__character, 4800)
AddSpecialEffect(attacker__character, 90020)
AddSpecialEffect(attacker__character, 5650)
AND_9.Add(CharacterIsType(PLAYER, character_type=CharacterType.BlackPhantom))
AND_9.Add(CharacterHasSpecialEffect(PLAYER, 3710))
OR_1.Add(AND_9)
OR_1.Add(CharacterIsType(PLAYER, character_type=CharacterType.Alive))
OR_1.Add(CharacterIsType(PLAYER, character_type=CharacterType.GrayPhantom))
OR_1.Add(CharacterIsType(PLAYER, character_type=CharacterType.WhitePhantom))
AND_1.Add(OR_1)
OR_2.Add(AttackedWithDamageType(attacked_entity=attacker__character, attacker=PLAYER))
OR_2.Add(AttackedWithDamageType(attacked_entity=attacker__character, attacker=ALL_SPIRIT_SUMMONS))
OR_2.Add(AttackedWithDamageType(attacked_entity=ALL_SPIRIT_SUMMONS, attacker=attacker__character))
OR_2.Add(EntityWithinDistance(entity=PLAYER, other_entity=attacker__character, radius=10.0))
OR_2.Add(EntityWithinDistance(entity=ALL_SPIRIT_SUMMONS, other_entity=attacker__character, radius=10.0))
OR_2.Add(CharacterInsideRegion(character=PLAYER, region=region))
OR_2.Add(CharacterInsideRegion(character=ALL_SPIRIT_SUMMONS, region=region))
AND_1.Add(OR_2)
MAIN.Await(AND_1)
EnableNetworkFlag(2047472200)
RemoveSpecialEffect(attacker__character, 4800)
RemoveSpecialEffect(attacker__character, 5650)
@RestartOnRest(2047472201)
def Event_2047472201(_, character: Character | int):
"""Event 2047472201"""
AddSpecialEffect(character, 4404)
End()
@RestartOnRest(2047472202)
def Event_2047472202(_, character: Character | int):
"""Event 2047472202"""
AddSpecialEffect(character, 4405)
@RestartOnRest(2047472203)
def Event_2047472203(_, character: Character | int):
"""Event 2047472203"""
AddSpecialEffect(character, 4401)
@ContinueOnRest(2047472510)
def Event_2047472510():
"""Event 2047472510"""
CommonFunc_90005500(
0,
flag=2047470510,
flag_1=2047470511,
left=1,
asset=2047471510,
asset_1=2047471511,
obj_act_id=2047473511,
asset_2=2047471512,
obj_act_id_1=2047473512,
region=2047472511,
region_1=2047472512,
flag_2=2047470512,
flag_3=2047470513,
left_1=0,
)
| 412 | 0.73842 | 1 | 0.73842 | game-dev | MEDIA | 0.967478 | game-dev | 0.737007 | 1 | 0.737007 |
Azure/azure-iot-sdk-csharp | 1,617 | iothub/service/src/ModernDotNet/Common/IOThreadTimerSlim.cs | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Threading;
namespace Microsoft.Azure.Devices
{
internal class IOThreadTimerSlim : IDisposable
{
private Timer _timer;
private readonly Action<object> _callback;
private readonly object _callbackState;
private SemaphoreSlim _timerSemaphore;
public IOThreadTimerSlim(Action<object> callback, object callbackState)
{
_timerSemaphore = new SemaphoreSlim(1);
_callback = callback;
_callbackState = callbackState;
CreateTimer();
}
public void Set(TimeSpan timeFromNow)
{
if (_timer == null)
{
CreateTimer();
}
_timerSemaphore.Wait();
_timer.Change(timeFromNow, Timeout.InfiniteTimeSpan);
_timerSemaphore.Release();
}
public bool Cancel()
{
_timerSemaphore.Wait();
_timer?.Dispose();
_timer = null;
_timerSemaphore.Release();
return true;
}
public void Dispose()
{
_timer?.Dispose();
_timerSemaphore?.Dispose();
}
private void CreateTimer()
{
_timerSemaphore.Wait();
_timer = new Timer((obj) => _callback(obj), _callbackState, Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan);
_timerSemaphore.Release();
}
}
}
| 412 | 0.834729 | 1 | 0.834729 | game-dev | MEDIA | 0.26683 | game-dev | 0.872681 | 1 | 0.872681 |
abeimler/ecs_benchmark | 2,942 | benchmark/benchmarks/flecs-extended/FlecsEventBenchmarkSuite.h | #ifndef ECS_BENCHMARKS_FLECSEVENTBENCHMARK_H_
#define ECS_BENCHMARKS_FLECSEVENTBENCHMARK_H_
#include "base/components/EmptyComponent.h"
#include "ExtendedECSBenchmark.h"
#include "flecs/FlecsApplication.h"
#include "flecs/entities/EntityFactory.h"
#include "flecs/entities/HeroMonsterEntityFactory.h"
#include "flecs/systems/DataSystem.h"
#include "flecs/systems/MoreComplexSystem.h"
#include "flecs/systems/MovementSystem.h"
#include <utility>
namespace ecs::benchmarks::flecs {
class FlecsEventBenchmarkSuite final
: public ecs::benchmarks::base::ExtendedECSBenchmark<"flecs (enqueue)", FlecsApplication, entities::EntityFactory,
entities::HeroMonsterEntityFactory> {
public:
FlecsEventBenchmarkSuite() = default;
explicit FlecsEventBenchmarkSuite(ecs::benchmarks::base::ESCBenchmarkOptions options)
: ExtendedECSBenchmark(std::move(options)) {}
void BM_EnqueueAndUpdateEventsViaObserverWithMixedEntities(benchmark::State& state) {
using ComponentOne = ecs::benchmarks::base::components::PositionComponent;
using ComponentTwo = ecs::benchmarks::base::components::VelocityComponent;
using EventComponent = ecs::benchmarks::base::components::EmptyComponent;
const auto nentities = static_cast<size_t>(state.range(0));
FlecsApplication app(this->m_options.add_more_complex_system);
::flecs::world& ecs = app.getEntities();
// Create observer for custom event
ecs.observer<ComponentOne, ComponentTwo>()
.event<EventComponent>()
.each([](::flecs::iter& /*it*/, size_t /*i*/, ComponentOne& comp1, ComponentTwo& comp2) {
dummy_each(comp1, comp2);
});
// The observer filter can be matched against the entity, so make sure it
// has the Position component before emitting the event. This does not
// trigger the observer yet.
std::vector<Entity> entities;
const base::ComponentsCounter components_counter =
this->template createEntitiesWithMixedComponents<entities::EntityFactory>(ecs, nentities, entities);
auto q = ecs.query<ComponentOne, ComponentTwo>();
for (auto _ : state) {
// We can only call enqueue events while the world is deferred mode.
ecs.defer_begin();
q.each([&](::flecs::entity e, ComponentOne& comp1, ComponentTwo& comp2) {
dummy_each(comp1, comp2);
// Emit the custom event
ecs.event<EventComponent>()
.id<ComponentOne, ComponentTwo>()
.entity(e)
.enqueue();
});
// Flushes the queue, and invokes the observer
ecs.defer_end();
/// @FIXME: flecs_emit: idr = flecs_query_id_record_get(world, id); idr is NULL
}
this->setCounters(state, entities, components_counter);
//state.counters["events_count"] = static_cast<double>(entities.size());
}
};
} // namespace ecs::benchmarks::flecs
#endif // ECS_BENCHMARKS_FLECSBENCHMARK_H_
| 412 | 0.919924 | 1 | 0.919924 | game-dev | MEDIA | 0.760401 | game-dev | 0.848133 | 1 | 0.848133 |
qt/qtwebkit | 2,979 | Source/WebCore/platform/graphics/texmap/coordinated/AreaAllocator.h | /*
* Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#ifndef AreaAllocator_h
#define AreaAllocator_h
#include "IntPoint.h"
#include "IntRect.h"
#include "IntSize.h"
#if USE(COORDINATED_GRAPHICS)
namespace WebCore {
inline int nextPowerOfTwo(int number)
{
// This is a fast trick to get nextPowerOfTwo for an integer.
--number;
number |= number >> 1;
number |= number >> 2;
number |= number >> 4;
number |= number >> 8;
number |= number >> 16;
number++;
return number;
}
inline IntSize nextPowerOfTwo(const IntSize& size)
{
return IntSize(nextPowerOfTwo(size.width()), nextPowerOfTwo(size.height()));
}
class AreaAllocator {
WTF_MAKE_FAST_ALLOCATED;
public:
explicit AreaAllocator(const IntSize&);
virtual ~AreaAllocator();
IntSize size() const { return m_size; }
IntSize minimumAllocation() const { return m_minAlloc; }
void setMinimumAllocation(const IntSize& size) { m_minAlloc = size; }
IntSize margin() const { return m_margin; }
void setMargin(const IntSize &margin) { m_margin = margin; }
virtual void expand(const IntSize&);
void expandBy(const IntSize&);
virtual IntRect allocate(const IntSize&) = 0;
virtual void release(const IntRect&);
virtual int overhead() const;
protected:
IntSize m_size;
IntSize m_minAlloc;
IntSize m_margin;
IntSize roundAllocation(const IntSize&) const;
};
class GeneralAreaAllocator : public AreaAllocator {
WTF_MAKE_FAST_ALLOCATED;
public:
explicit GeneralAreaAllocator(const IntSize&);
virtual ~GeneralAreaAllocator();
void expand(const IntSize&);
IntRect allocate(const IntSize&);
void release(const IntRect&);
int overhead() const;
private:
enum Split { SplitOnX, SplitOnY };
struct Node {
IntRect rect;
IntSize largestFree;
Node* parent;
Node* left;
Node* right;
};
Node* m_root;
int m_nodeCount;
static void freeNode(Node*);
IntPoint allocateFromNode(const IntSize&, Node*);
Node* splitNode(Node*, Split);
static void updateLargestFree(Node*);
};
} // namespace WebCore
#endif // USE(COORDINATED_GRAPHICS)
#endif // AreaAllocator_h
| 412 | 0.883087 | 1 | 0.883087 | game-dev | MEDIA | 0.354546 | game-dev | 0.883216 | 1 | 0.883216 |
ToxicMushroom/Melijn | 3,204 | src/main/kotlin/me/melijn/melijnbot/internals/music/GuildMusicPlayer.kt | package me.melijn.melijnbot.internals.music
import com.sedmelluq.discord.lavaplayer.track.AudioTrack
import me.melijn.melijnbot.commands.music.NextSongPosition
import me.melijn.melijnbot.database.DaoManager
import me.melijn.melijnbot.internals.command.ICommandContext
import me.melijn.melijnbot.internals.utils.isPremiumGuild
import me.melijn.melijnbot.internals.utils.message.sendRsp
import me.melijn.melijnbot.internals.utils.withVariable
class GuildMusicPlayer(daoManager: DaoManager, lavaManager: LavaManager, val guildId: Long, groupId: String) {
val guildTrackManager: GuildTrackManager = GuildTrackManager(
guildId,
daoManager,
lavaManager,
lavaManager.getIPlayer(guildId, groupId),
groupId
)
var groupId: String
get() = guildTrackManager.groupId
set(value) {
guildTrackManager.groupId = value
}
init {
this.groupId = groupId
}
val searchMenus: MutableMap<Long, TracksForQueue> = mutableMapOf()
init {
addTrackManagerListener()
}
private fun addTrackManagerListener() {
guildTrackManager.iPlayer.addListener(guildTrackManager)
}
fun removeTrackManagerListener() {
guildTrackManager.iPlayer.removeListener(guildTrackManager)
}
fun getSendHandler(): AudioPlayerSendHandler = AudioPlayerSendHandler(guildTrackManager.iPlayer)
suspend fun safeQueueSilent(daoManager: DaoManager, track: AudioTrack, nextPos: NextSongPosition): Boolean {
if (
(guildTrackManager.trackSize() <= DONATE_QUEUE_LIMIT && isPremiumGuild(daoManager, guildId)) ||
guildTrackManager.tracks.size + 1 <= QUEUE_LIMIT
) {
guildTrackManager.queue(track, nextPos)
return true
}
return false
}
suspend fun safeQueue(context: ICommandContext, track: AudioTrack, nextPos: NextSongPosition): Boolean {
val success = safeQueueSilent(context.daoManager, track, nextPos)
if (!success) {
val msg = context.getTranslation("message.music.queuelimit")
.withVariable("amount", QUEUE_LIMIT.toString())
.withVariable("donateAmount", DONATE_QUEUE_LIMIT.toString())
.withVariable("prefix", context.usedPrefix)
sendRsp(context, msg)
}
return success
}
suspend fun queueIsFull(context: ICommandContext, add: Int, silent: Boolean = false): Boolean {
if (
guildTrackManager.tracks.size + add > QUEUE_LIMIT ||
(guildTrackManager.tracks.size + add > DONATE_QUEUE_LIMIT && isPremiumGuild(context))
) {
if (!silent) {
val msg = context.getTranslation("message.music.queuelimit")
.withVariable("amount", QUEUE_LIMIT.toString())
.withVariable("donateAmount", DONATE_QUEUE_LIMIT.toString())
.withVariable("prefix", context.usedPrefix)
sendRsp(context, msg)
}
return true
}
return false
}
}
data class TracksForQueue(
val audioTracks: List<AudioTrack>,
val nextPosition: NextSongPosition
) | 412 | 0.892736 | 1 | 0.892736 | game-dev | MEDIA | 0.721382 | game-dev | 0.93608 | 1 | 0.93608 |
shxzu/Simp | 15,552 | src/main/java/net/optifine/DynamicLights.java | package net.optifine;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import net.minecraft.block.Block;
import net.minecraft.client.renderer.RenderGlobal;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.item.EntityTNTPrimed;
import net.minecraft.entity.monster.EntityBlaze;
import net.minecraft.entity.monster.EntityCreeper;
import net.minecraft.entity.monster.EntityMagmaCube;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.projectile.EntityFireball;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import net.minecraft.src.Config;
import net.minecraft.util.BlockPos;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.World;
import net.optifine.config.ConnectedParser;
import net.optifine.config.EntityClassLocator;
import net.optifine.config.IObjectLocator;
import net.optifine.config.ItemLocator;
import net.optifine.util.PropertiesOrdered;
public class DynamicLights
{
private static final DynamicLightsMap mapDynamicLights = new DynamicLightsMap();
private static final Map<Class, Integer> mapEntityLightLevels = new HashMap();
private static final Map<Item, Integer> mapItemLightLevels = new HashMap();
private static long timeUpdateMs = 0L;
private static final double MAX_DIST = 7.5D;
private static final double MAX_DIST_SQ = 56.25D;
private static final int LIGHT_LEVEL_MAX = 15;
private static final int LIGHT_LEVEL_FIRE = 15;
private static final int LIGHT_LEVEL_BLAZE = 10;
private static final int LIGHT_LEVEL_MAGMA_CUBE = 8;
private static final int LIGHT_LEVEL_MAGMA_CUBE_CORE = 13;
private static final int LIGHT_LEVEL_GLOWSTONE_DUST = 8;
private static final int LIGHT_LEVEL_PRISMARINE_CRYSTALS = 8;
private static boolean initialized;
public static void entityAdded(Entity entityIn, RenderGlobal renderGlobal)
{
}
public static void entityRemoved(Entity entityIn, RenderGlobal renderGlobal)
{
synchronized (mapDynamicLights)
{
DynamicLight dynamiclight = mapDynamicLights.remove(entityIn.getEntityId());
if (dynamiclight != null)
{
dynamiclight.updateLitChunks(renderGlobal);
}
}
}
public static void update(RenderGlobal renderGlobal)
{
long i = System.currentTimeMillis();
if (i >= timeUpdateMs + 50L)
{
timeUpdateMs = i;
if (!initialized)
{
initialize();
}
synchronized (mapDynamicLights)
{
updateMapDynamicLights(renderGlobal);
if (mapDynamicLights.size() > 0)
{
List<DynamicLight> list = mapDynamicLights.valueList();
for (int j = 0; j < list.size(); ++j)
{
DynamicLight dynamiclight = list.get(j);
dynamiclight.update(renderGlobal);
}
}
}
}
}
private static void initialize()
{
initialized = true;
mapEntityLightLevels.clear();
mapItemLightLevels.clear();
String[] astring = new String[0];
for (int i = 0; i < astring.length; ++i)
{
String s = astring[i];
try
{
ResourceLocation resourcelocation = new ResourceLocation(s, "optifine/dynamic_lights.properties");
InputStream inputstream = Config.getResourceStream(resourcelocation);
loadModConfiguration(inputstream, resourcelocation.toString(), s);
}
catch (IOException var5)
{
}
}
if (mapEntityLightLevels.size() > 0)
{
Config.dbg("DynamicLights entities: " + mapEntityLightLevels.size());
}
if (mapItemLightLevels.size() > 0)
{
Config.dbg("DynamicLights items: " + mapItemLightLevels.size());
}
}
private static void loadModConfiguration(InputStream in, String path, String modId)
{
if (in != null)
{
try
{
Properties properties = new PropertiesOrdered();
properties.load(in);
in.close();
Config.dbg("DynamicLights: Parsing " + path);
ConnectedParser connectedparser = new ConnectedParser("DynamicLights");
loadModLightLevels(properties.getProperty("entities"), mapEntityLightLevels, new EntityClassLocator(), connectedparser, path, modId);
loadModLightLevels(properties.getProperty("items"), mapItemLightLevels, new ItemLocator(), connectedparser, path, modId);
}
catch (IOException var5)
{
Config.warn("DynamicLights: Error reading " + path);
}
}
}
private static void loadModLightLevels(String prop, Map mapLightLevels, IObjectLocator ol, ConnectedParser cp, String path, String modId)
{
if (prop != null)
{
String[] astring = Config.tokenize(prop, " ");
for (int i = 0; i < astring.length; ++i)
{
String s = astring[i];
String[] astring1 = Config.tokenize(s, ":");
if (astring1.length != 2)
{
cp.warn("Invalid entry: " + s + ", in:" + path);
}
else
{
String s1 = astring1[0];
String s2 = astring1[1];
String s3 = modId + ":" + s1;
ResourceLocation resourcelocation = new ResourceLocation(s3);
Object object = ol.getObject(resourcelocation);
if (object == null)
{
cp.warn("Object not found: " + s3);
}
else
{
int j = cp.parseInt(s2, -1);
if (j >= 0 && j <= 15)
{
mapLightLevels.put(object, Integer.valueOf(j));
}
else
{
cp.warn("Invalid light level: " + s);
}
}
}
}
}
}
private static void updateMapDynamicLights(RenderGlobal renderGlobal)
{
World world = renderGlobal.getWorld();
if (world != null)
{
for (Entity entity : world.getLoadedEntityList())
{
int i = getLightLevel(entity);
if (i > 0)
{
int j = entity.getEntityId();
DynamicLight dynamiclight = mapDynamicLights.get(j);
if (dynamiclight == null)
{
dynamiclight = new DynamicLight(entity);
mapDynamicLights.put(j, dynamiclight);
}
}
else
{
int k = entity.getEntityId();
DynamicLight dynamiclight1 = mapDynamicLights.remove(k);
if (dynamiclight1 != null)
{
dynamiclight1.updateLitChunks(renderGlobal);
}
}
}
}
}
public static int getCombinedLight(BlockPos pos, int combinedLight)
{
double d0 = getLightLevel(pos);
combinedLight = getCombinedLight(d0, combinedLight);
return combinedLight;
}
public static int getCombinedLight(Entity entity, int combinedLight)
{
double d0 = getLightLevel(entity);
combinedLight = getCombinedLight(d0, combinedLight);
return combinedLight;
}
public static int getCombinedLight(double lightPlayer, int combinedLight)
{
if (lightPlayer > 0.0D)
{
int i = (int)(lightPlayer * 16.0D);
int j = combinedLight & 255;
if (i > j)
{
combinedLight = combinedLight & -256;
combinedLight = combinedLight | i;
}
}
return combinedLight;
}
public static double getLightLevel(BlockPos pos)
{
double d0 = 0.0D;
synchronized (mapDynamicLights)
{
List<DynamicLight> list = mapDynamicLights.valueList();
int i = list.size();
for (int j = 0; j < i; ++j)
{
DynamicLight dynamiclight = list.get(j);
int k = dynamiclight.getLastLightLevel();
if (k > 0)
{
double d1 = dynamiclight.getLastPosX();
double d2 = dynamiclight.getLastPosY();
double d3 = dynamiclight.getLastPosZ();
double d4 = (double)pos.getX() - d1;
double d5 = (double)pos.getY() - d2;
double d6 = (double)pos.getZ() - d3;
double d7 = d4 * d4 + d5 * d5 + d6 * d6;
if (dynamiclight.isUnderwater() && !Config.isClearWater())
{
k = Config.limit(k - 2, 0, 15);
d7 *= 2.0D;
}
if (d7 <= 56.25D)
{
double d8 = Math.sqrt(d7);
double d9 = 1.0D - d8 / 7.5D;
double d10 = d9 * (double)k;
if (d10 > d0)
{
d0 = d10;
}
}
}
}
}
double d11 = Config.limit(d0, 0.0D, 15.0D);
return d11;
}
public static int getLightLevel(ItemStack itemStack)
{
if (itemStack == null)
{
return 0;
}
else
{
Item item = itemStack.getItem();
if (item instanceof ItemBlock itemblock)
{
Block block = itemblock.getBlock();
if (block != null)
{
return block.getLightValue();
}
}
if (item == Items.lava_bucket)
{
return Blocks.lava.getLightValue();
}
else if (item != Items.blaze_rod && item != Items.blaze_powder)
{
if (item == Items.glowstone_dust)
{
return 8;
}
else if (item == Items.prismarine_crystals)
{
return 8;
}
else if (item == Items.magma_cream)
{
return 8;
}
else if (item == Items.nether_star)
{
return Blocks.beacon.getLightValue() / 2;
}
else
{
if (!mapItemLightLevels.isEmpty())
{
Integer integer = mapItemLightLevels.get(item);
if (integer != null)
{
return integer.intValue();
}
}
return 0;
}
}
else
{
return 10;
}
}
}
public static int getLightLevel(Entity entity)
{
if (entity == Config.getMinecraft().getRenderViewEntity() && !Config.isDynamicHandLight())
{
return 0;
}
else
{
if (entity instanceof EntityPlayer entityplayer)
{
if (entityplayer.isSpectator())
{
return 0;
}
}
if (entity.isBurning())
{
return 15;
}
else
{
if (!mapEntityLightLevels.isEmpty())
{
Integer integer = mapEntityLightLevels.get(entity.getClass());
if (integer != null)
{
return integer.intValue();
}
}
if (entity instanceof EntityFireball)
{
return 15;
}
else if (entity instanceof EntityTNTPrimed)
{
return 15;
}
else if (entity instanceof EntityBlaze entityblaze)
{
return entityblaze.func_70845_n() ? 15 : 10;
}
else if (entity instanceof EntityMagmaCube entitymagmacube)
{
return (double)entitymagmacube.squishFactor > 0.6D ? 13 : 8;
}
else
{
if (entity instanceof EntityCreeper entitycreeper)
{
if ((double)entitycreeper.getCreeperFlashIntensity(0.0F) > 0.001D)
{
return 15;
}
}
if (entity instanceof EntityLivingBase entitylivingbase)
{
ItemStack itemstack2 = entitylivingbase.getHeldItem();
int i = getLightLevel(itemstack2);
ItemStack itemstack1 = entitylivingbase.getEquipmentInSlot(4);
int j = getLightLevel(itemstack1);
return Math.max(i, j);
}
else if (entity instanceof EntityItem entityitem)
{
ItemStack itemstack = getItemStack(entityitem);
return getLightLevel(itemstack);
}
else
{
return 0;
}
}
}
}
}
public static void removeLights(RenderGlobal renderGlobal)
{
synchronized (mapDynamicLights)
{
List<DynamicLight> list = mapDynamicLights.valueList();
for (int i = 0; i < list.size(); ++i)
{
DynamicLight dynamiclight = list.get(i);
dynamiclight.updateLitChunks(renderGlobal);
}
mapDynamicLights.clear();
}
}
public static void clear()
{
synchronized (mapDynamicLights)
{
mapDynamicLights.clear();
}
}
public static int getCount()
{
synchronized (mapDynamicLights)
{
return mapDynamicLights.size();
}
}
public static ItemStack getItemStack(EntityItem entityItem)
{
ItemStack itemstack = entityItem.getDataWatcher().getWatchableObjectItemStack(10);
return itemstack;
}
}
| 412 | 0.901784 | 1 | 0.901784 | game-dev | MEDIA | 0.795435 | game-dev | 0.982353 | 1 | 0.982353 |
spaceninjaserver/SpaceNinjaServer | 4,878 | src/services/infestedFoundryService.ts | import { ExportRecipes } from "warframe-public-export-plus";
import type { TInventoryDatabaseDocument } from "../models/inventoryModels/inventoryModel.ts";
import type {
IAccountCheats,
IInfestedFoundryClient,
IInfestedFoundryDatabase
} from "../types/inventoryTypes/inventoryTypes.ts";
import { addRecipes } from "./inventoryService.ts";
import type { ITypeCount } from "../types/commonTypes.ts";
export const addInfestedFoundryXP = (infestedFoundry: IInfestedFoundryDatabase, delta: number): ITypeCount[] => {
const recipeChanges: ITypeCount[] = [];
infestedFoundry.XP ??= 0;
const prevXP = infestedFoundry.XP;
infestedFoundry.XP += delta;
if (prevXP < 2250_00 && infestedFoundry.XP >= 2250_00) {
infestedFoundry.Slots ??= 0;
infestedFoundry.Slots += 3;
}
if (prevXP < 5625_00 && infestedFoundry.XP >= 5625_00) {
recipeChanges.push({
ItemType: "/Lotus/Types/Recipes/AbilityOverrides/HelminthShieldsBlueprint",
ItemCount: 1
});
}
if (prevXP < 10125_00 && infestedFoundry.XP >= 10125_00) {
recipeChanges.push({ ItemType: "/Lotus/Types/Recipes/AbilityOverrides/HelminthHackBlueprint", ItemCount: 1 });
}
if (prevXP < 15750_00 && infestedFoundry.XP >= 15750_00) {
infestedFoundry.Slots ??= 0;
infestedFoundry.Slots += 10;
}
if (prevXP < 22500_00 && infestedFoundry.XP >= 22500_00) {
recipeChanges.push({
ItemType: "/Lotus/Types/Recipes/AbilityOverrides/HelminthAmmoEfficiencyBlueprint",
ItemCount: 1
});
}
if (prevXP < 30375_00 && infestedFoundry.XP >= 30375_00) {
recipeChanges.push({ ItemType: "/Lotus/Types/Recipes/AbilityOverrides/HelminthStunBlueprint", ItemCount: 1 });
}
if (prevXP < 39375_00 && infestedFoundry.XP >= 39375_00) {
infestedFoundry.Slots ??= 0;
infestedFoundry.Slots += 20;
}
if (prevXP < 60750_00 && infestedFoundry.XP >= 60750_00) {
recipeChanges.push({ ItemType: "/Lotus/Types/Recipes/AbilityOverrides/HelminthStatusBlueprint", ItemCount: 1 });
}
if (prevXP < 73125_00 && infestedFoundry.XP >= 73125_00) {
infestedFoundry.Slots = 1;
}
if (prevXP < 86625_00 && infestedFoundry.XP >= 86625_00) {
recipeChanges.push({
ItemType: "/Lotus/Types/Recipes/AbilityOverrides/HelminthShieldArmorBlueprint",
ItemCount: 1
});
}
if (prevXP < 101250_00 && infestedFoundry.XP >= 101250_00) {
recipeChanges.push({
ItemType: "/Lotus/Types/Recipes/AbilityOverrides/HelminthProcBlockBlueprint",
ItemCount: 1
});
}
if (prevXP < 117000_00 && infestedFoundry.XP >= 117000_00) {
recipeChanges.push({
ItemType: "/Lotus/Types/Recipes/AbilityOverrides/HelminthEnergyShareBlueprint",
ItemCount: 1
});
}
if (prevXP < 133875_00 && infestedFoundry.XP >= 133875_00) {
recipeChanges.push({
ItemType: "/Lotus/Types/Recipes/AbilityOverrides/HelminthMaxStatusBlueprint",
ItemCount: 1
});
}
if (prevXP < 151875_00 && infestedFoundry.XP >= 151875_00) {
recipeChanges.push({
ItemType: "/Lotus/Types/Recipes/AbilityOverrides/HelminthTreasureBlueprint",
ItemCount: 1
});
}
return recipeChanges;
};
export const handleSubsumeCompletion = (inventory: TInventoryDatabaseDocument): ITypeCount[] => {
const [recipeType] = Object.entries(ExportRecipes).find(
([_recipeType, recipe]) =>
recipe.secretIngredientAction == "SIA_WARFRAME_ABILITY" &&
recipe.secretIngredients![0].ItemType == inventory.InfestedFoundry!.LastConsumedSuit!.ItemType
)!;
inventory.InfestedFoundry!.LastConsumedSuit = undefined;
inventory.InfestedFoundry!.AbilityOverrideUnlockCooldown = undefined;
const recipeChanges: ITypeCount[] = [
{
ItemType: recipeType,
ItemCount: 1
}
];
addRecipes(inventory, recipeChanges);
return recipeChanges;
};
export const applyCheatsToInfestedFoundry = (cheats: IAccountCheats, infestedFoundry: IInfestedFoundryClient): void => {
if (cheats.infiniteHelminthMaterials) {
infestedFoundry.Resources = [
{ ItemType: "/Lotus/Types/Items/InfestedFoundry/HelminthCalx", Count: 1000 },
{ ItemType: "/Lotus/Types/Items/InfestedFoundry/HelminthBiotics", Count: 1000 },
{ ItemType: "/Lotus/Types/Items/InfestedFoundry/HelminthSynthetics", Count: 1000 },
{ ItemType: "/Lotus/Types/Items/InfestedFoundry/HelminthPheromones", Count: 1000 },
{ ItemType: "/Lotus/Types/Items/InfestedFoundry/HelminthBile", Count: 1000 },
{ ItemType: "/Lotus/Types/Items/InfestedFoundry/HelminthOxides", Count: 1000 }
];
}
};
| 412 | 0.919886 | 1 | 0.919886 | game-dev | MEDIA | 0.940468 | game-dev | 0.86611 | 1 | 0.86611 |
TauCetiStation/TauCetiClassic | 6,915 | code/modules/mob/living/simple_animal/species_larvaes.dm | /mob/living/simple_animal/grown_larvae/proc/evolve_to_young_adult()
return
/mob/living/simple_animal/grown_larvae/proc/handle_evolving()
if(stat == DEAD)
return
if(!mind || !client || !key)
addtimer(CALLBACK(src, .proc/handle_evolving), 100, TIMER_UNIQUE)
return
if(evolv_stage < 4)
addtimer(CALLBACK(src, .proc/handle_evolving), 100, TIMER_UNIQUE)
evolv_stage++
switch(evolv_stage)
if(2)
maxHealth = 20
health += 20
if(3)
maxHealth = 40
health += 40
speed -= 0.5
melee_damage = 2
return
evolve_to_young_adult()
/mob/living/simple_animal/grown_larvae
name = "larva"
desc = "It's a little alien skittery critter. Hiss."
icon = 'icons/mob/animal.dmi'
health = 10
maxHealth = 10
response_help = "hugs"
response_disarm = "gently pushes"
response_harm = "punches"
has_head = TRUE
has_arm = TRUE
has_leg = TRUE
turns_per_move = 4
speed = 3
butcher_results = list(/obj/item/weapon/reagent_containers/food/snacks/candy/fudge/alien_meat = 3)
/mob/living/simple_animal/grown_larvae/atom_init()
. = ..()
handle_evolving()
/mob/living/simple_animal/grown_larvae/Stat()
..()
stat(null)
if(statpanel("Status"))
stat("Прогресс роста: [evolv_stage * 25]/100")
/mob/living/simple_animal/grown_larvae/serpentid
name = "Nabber larva"
icon_state = "larvae-serpentid"
icon_living = "larvae-serpentid"
icon_dead = "larvae-serpentid_dead"
holder_type = /obj/item/weapon/holder/nabber
/mob/living/simple_animal/grown_larvae/serpentid/LateLogin()
. = ..()
to_chat(src, "<span class='userdanger'>Вы агрессивная форма жизни, практикующая каннибализм, так как мясо вашего вида очень вкусное.</span>")
/mob/living/simple_animal/grown_larvae/serpentid/evolve_to_young_adult()
var/mob/living/simple_animal/grown_larvae/snake/S = new(get_turf(loc))
mind.transfer_to(S)
qdel(src)
/mob/living/simple_animal/grown_larvae/serpentid/death()
if(butcher_results)
for(var/path in butcher_results)
for(var/i = 1 to butcher_results[path])
new path(loc)
qdel(src)
/mob/living/simple_animal/grown_larvae/serpentid/helpReaction(mob/living/carbon/human/attacker, show_message = TRUE)
get_scooped(attacker)
/mob/living/simple_animal/grown_larvae/snake
name = "Snake"
desc = "Hiss"
icon_state = "snake"
icon_living = "snake"
icon_dead = "snake_dead"
ventcrawler = 2
melee_damage = 5
speed = 1
has_arm = FALSE
has_leg = FALSE
holder_type = /obj/item/weapon/holder/snake
/mob/living/simple_animal/grown_larvae/snake/LateLogin()
. = ..()
to_chat(src, "<span class='userdanger'>Вы агрессивная форма жизни в стадии развития до взрослой особи. Ваша сила укуса растёт.</span>")
/mob/living/simple_animal/grown_larvae/snake/evolve_to_young_adult()
var/datum/effect/effect/system/smoke_spread/bad/smoke = new /datum/effect/effect/system/smoke_spread/bad()
smoke.set_up(10, 0, loc)
smoke.start()
playsound(src, 'sound/effects/bamf.ogg', VOL_EFFECTS_MASTER)
var/mob/living/carbon/human/serpentid/S = new(get_turf(loc))
mind.transfer_to(S)
create_and_setup_role(/datum/role/animal, S)
var/lore = "Вы агрессивная форма жизни с примитивным интеллектом уровня обезьяны. Вторжение в вашу комфортную зону означает агрессию по отношению к вам. Представителей своего вида вы предпочитаете видеть в качестве завтрака. Своей хваткой вы способны разрывать тела на части. Ваша цель - выжить."
to_chat(S, "<span class='userdanger'>[lore]</span>")
S.mind.store_memory(lore)
qdel(src)
/mob/living/simple_animal/grown_larvae/snake/helpReaction(mob/living/carbon/human/attacker, show_message = TRUE)
get_scooped(attacker)
/mob/living/simple_animal/grown_larvae/small_moth
name = "Young moth"
icon_state = "small_moth"
icon_living = "small_moth"
icon_dead = "small_moth_dead"
minbodytemp = 288
maxbodytemp = 301
heat_damage_per_tick = 9
bodytemperature = 293
holder_type = /obj/item/weapon/holder/moth_small
/mob/living/simple_animal/grown_larvae/small_moth/LateLogin()
. = ..()
to_chat(src, "<span class='userdanger'>Вы дружелюбная форма жизни в стадии развития до взрослой особи. Помните, чем больше вы растёте, тем больше в вас мяса.</span>")
/mob/living/simple_animal/grown_larvae/small_moth/evolve_to_young_adult()
var/mob/living/carbon/human/moth/M = new(get_turf(loc))
mind.transfer_to(M)
M.mind.name = M.real_name
create_and_setup_role(/datum/role/animal, M)
var/lore = "Вы всеядная форма жизни с примитивным интеллектом уровня обезьяны, предпочитающая питаться падалью. В число ваших врагов входят только Серпентиды, отношение к остальным зачастую нейтральное. Ваша цель - выжить."
to_chat(M, "<span class='userdanger'>[lore]</span>")
M.mind.store_memory(lore)
qdel(src)
/mob/living/simple_animal/grown_larvae/small_moth/helpReaction(mob/living/carbon/human/attacker, show_message = TRUE)
get_scooped(attacker)
/mob/living/simple_animal/grown_larvae/newborn_moth
name = "Newborn moth"
real_name = "Newborn moth"
desc = "It's a little alien skittery critter. Hiss."
maxHealth = 5
health = 5
melee_damage = 2
ventcrawler = 0
icon_state = "newborn_moth"
icon_living = "newborn_moth"
icon_dead = "small_moth_dead"
icon_move = null
speak_chance = 0
speak = list("Chirp!", "Chirp?")
speak_emote = list()
emote_hear = list()
emote_see = list()
response_help = "hugs"
response_disarm = "gently pushes"
response_harm = "punches"
butcher_results = list(/obj/item/weapon/reagent_containers/food/snacks/candy/fudge/alien_meat = 1)
minbodytemp = 288
maxbodytemp = 301
heat_damage_per_tick = 9
bodytemperature = 293
holder_type = null
faction = "neutral"
has_arm = FALSE
has_leg = FALSE
holder_type = /obj/item/weapon/holder/mothroach
/mob/living/simple_animal/grown_larvae/newborn_moth/atom_init()
. = ..()
AddComponent(/datum/component/gnawing)
/mob/living/simple_animal/grown_larvae/newborn_moth/LateLogin()
. = ..()
to_chat(src, "<span class='userdanger'>Вы дружелюбная форма жизни, готовая съесть что угодно.</span>")
/mob/living/simple_animal/grown_larvae/newborn_moth/atom_init()
. = ..()
addtimer(CALLBACK(src, .proc/handle_evolving), 100, TIMER_UNIQUE)
/mob/living/simple_animal/grown_larvae/newborn_moth/evolve_to_young_adult()
var/mob/living/simple_animal/grown_larvae/small_moth/moth = new(get_turf(loc))
mind.transfer_to(moth)
qdel(src)
/mob/living/simple_animal/grown_larvae/newborn_moth/death()
if(butcher_results)
for(var/path in butcher_results)
for(var/i = 1 to butcher_results[path])
new path(loc)
qdel(src)
/mob/living/simple_animal/grown_larvae/newborn_moth/helpReaction(mob/living/carbon/human/attacker, show_message = TRUE)
get_scooped(attacker)
//sweet to attract hungry assistants
/obj/item/weapon/reagent_containers/food/snacks/candy/fudge/alien_meat
name = "Larva meat"
desc = "Meat. Sometimes liquid, sometimes jelly-like, sometimes crunchy and sweet. Despite the texture, it smells delicious."
icon_state = "xenomeat"
filling_color = "#cadaba"
| 412 | 0.879276 | 1 | 0.879276 | game-dev | MEDIA | 0.993849 | game-dev | 0.653506 | 1 | 0.653506 |
rorywalsh/cabbage_v1_old | 6,847 | JuceLibraryCode/modules/juce_box2d/box2d/Dynamics/Joints/b2FrictionJoint.cpp | /*
* Copyright (c) 2006-2011 Erin Catto http://www.box2d.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 "b2FrictionJoint.h"
#include "../b2Body.h"
#include "../b2TimeStep.h"
// Point-to-point constraint
// Cdot = v2 - v1
// = v2 + cross(w2, r2) - v1 - cross(w1, r1)
// J = [-I -r1_skew I r2_skew ]
// Identity used:
// w k % (rx i + ry j) = w * (-ry i + rx j)
// Angle constraint
// Cdot = w2 - w1
// J = [0 0 -1 0 0 1]
// K = invI1 + invI2
void b2FrictionJointDef::Initialize(b2Body* bA, b2Body* bB, const b2Vec2& anchor)
{
bodyA = bA;
bodyB = bB;
localAnchorA = bodyA->GetLocalPoint(anchor);
localAnchorB = bodyB->GetLocalPoint(anchor);
}
b2FrictionJoint::b2FrictionJoint(const b2FrictionJointDef* def)
: b2Joint(def)
{
m_localAnchorA = def->localAnchorA;
m_localAnchorB = def->localAnchorB;
m_linearImpulse.SetZero();
m_angularImpulse = 0.0f;
m_maxForce = def->maxForce;
m_maxTorque = def->maxTorque;
}
void b2FrictionJoint::InitVelocityConstraints(const b2SolverData& data)
{
m_indexA = m_bodyA->m_islandIndex;
m_indexB = m_bodyB->m_islandIndex;
m_localCenterA = m_bodyA->m_sweep.localCenter;
m_localCenterB = m_bodyB->m_sweep.localCenter;
m_invMassA = m_bodyA->m_invMass;
m_invMassB = m_bodyB->m_invMass;
m_invIA = m_bodyA->m_invI;
m_invIB = m_bodyB->m_invI;
float32 aA = data.positions[m_indexA].a;
b2Vec2 vA = data.velocities[m_indexA].v;
float32 wA = data.velocities[m_indexA].w;
float32 aB = data.positions[m_indexB].a;
b2Vec2 vB = data.velocities[m_indexB].v;
float32 wB = data.velocities[m_indexB].w;
b2Rot qA(aA), qB(aB);
// Compute the effective mass matrix.
m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA);
m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB);
// J = [-I -r1_skew I r2_skew]
// [ 0 -1 0 1]
// r_skew = [-ry; rx]
// Matlab
// K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB]
// [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB]
// [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB]
float32 mA = m_invMassA, mB = m_invMassB;
float32 iA = m_invIA, iB = m_invIB;
b2Mat22 K;
K.ex.x = mA + mB + iA * m_rA.y * m_rA.y + iB * m_rB.y * m_rB.y;
K.ex.y = -iA * m_rA.x * m_rA.y - iB * m_rB.x * m_rB.y;
K.ey.x = K.ex.y;
K.ey.y = mA + mB + iA * m_rA.x * m_rA.x + iB * m_rB.x * m_rB.x;
m_linearMass = K.GetInverse();
m_angularMass = iA + iB;
if (m_angularMass > 0.0f)
{
m_angularMass = 1.0f / m_angularMass;
}
if (data.step.warmStarting)
{
// Scale impulses to support a variable time step.
m_linearImpulse *= data.step.dtRatio;
m_angularImpulse *= data.step.dtRatio;
b2Vec2 P(m_linearImpulse.x, m_linearImpulse.y);
vA -= mA * P;
wA -= iA * (b2Cross(m_rA, P) + m_angularImpulse);
vB += mB * P;
wB += iB * (b2Cross(m_rB, P) + m_angularImpulse);
}
else
{
m_linearImpulse.SetZero();
m_angularImpulse = 0.0f;
}
data.velocities[m_indexA].v = vA;
data.velocities[m_indexA].w = wA;
data.velocities[m_indexB].v = vB;
data.velocities[m_indexB].w = wB;
}
void b2FrictionJoint::SolveVelocityConstraints(const b2SolverData& data)
{
b2Vec2 vA = data.velocities[m_indexA].v;
float32 wA = data.velocities[m_indexA].w;
b2Vec2 vB = data.velocities[m_indexB].v;
float32 wB = data.velocities[m_indexB].w;
float32 mA = m_invMassA, mB = m_invMassB;
float32 iA = m_invIA, iB = m_invIB;
float32 h = data.step.dt;
// Solve angular friction
{
float32 Cdot = wB - wA;
float32 impulse = -m_angularMass * Cdot;
float32 oldImpulse = m_angularImpulse;
float32 maxImpulse = h * m_maxTorque;
m_angularImpulse = b2Clamp(m_angularImpulse + impulse, -maxImpulse, maxImpulse);
impulse = m_angularImpulse - oldImpulse;
wA -= iA * impulse;
wB += iB * impulse;
}
// Solve linear friction
{
b2Vec2 Cdot = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA);
b2Vec2 impulse = -b2Mul(m_linearMass, Cdot);
b2Vec2 oldImpulse = m_linearImpulse;
m_linearImpulse += impulse;
float32 maxImpulse = h * m_maxForce;
if (m_linearImpulse.LengthSquared() > maxImpulse * maxImpulse)
{
m_linearImpulse.Normalize();
m_linearImpulse *= maxImpulse;
}
impulse = m_linearImpulse - oldImpulse;
vA -= mA * impulse;
wA -= iA * b2Cross(m_rA, impulse);
vB += mB * impulse;
wB += iB * b2Cross(m_rB, impulse);
}
data.velocities[m_indexA].v = vA;
data.velocities[m_indexA].w = wA;
data.velocities[m_indexB].v = vB;
data.velocities[m_indexB].w = wB;
}
bool b2FrictionJoint::SolvePositionConstraints(const b2SolverData& data)
{
B2_NOT_USED(data);
return true;
}
b2Vec2 b2FrictionJoint::GetAnchorA() const
{
return m_bodyA->GetWorldPoint(m_localAnchorA);
}
b2Vec2 b2FrictionJoint::GetAnchorB() const
{
return m_bodyB->GetWorldPoint(m_localAnchorB);
}
b2Vec2 b2FrictionJoint::GetReactionForce(float32 inv_dt) const
{
return inv_dt * m_linearImpulse;
}
float32 b2FrictionJoint::GetReactionTorque(float32 inv_dt) const
{
return inv_dt * m_angularImpulse;
}
void b2FrictionJoint::SetMaxForce(float32 force)
{
b2Assert(b2IsValid(force) && force >= 0.0f);
m_maxForce = force;
}
float32 b2FrictionJoint::GetMaxForce() const
{
return m_maxForce;
}
void b2FrictionJoint::SetMaxTorque(float32 torque)
{
b2Assert(b2IsValid(torque) && torque >= 0.0f);
m_maxTorque = torque;
}
float32 b2FrictionJoint::GetMaxTorque() const
{
return m_maxTorque;
}
void b2FrictionJoint::Dump()
{
int32 indexA = m_bodyA->m_islandIndex;
int32 indexB = m_bodyB->m_islandIndex;
b2Log(" b2FrictionJointDef jd;\n");
b2Log(" jd.bodyA = bodies[%d];\n", indexA);
b2Log(" jd.bodyB = bodies[%d];\n", indexB);
b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected);
b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y);
b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y);
b2Log(" jd.maxForce = %.15lef;\n", m_maxForce);
b2Log(" jd.maxTorque = %.15lef;\n", m_maxTorque);
b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index);
}
| 412 | 0.929435 | 1 | 0.929435 | game-dev | MEDIA | 0.982252 | game-dev | 0.975222 | 1 | 0.975222 |
corporateshark/Mastering-Android-NDK | 3,763 | Chapter8/2_ShadowMaps/jni/SDL/src/joystick/dummy/SDL_sysjoystick.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"
#if defined(SDL_JOYSTICK_DUMMY) || defined(SDL_JOYSTICK_DISABLED)
/* This is the dummy implementation of the SDL joystick API */
#include "SDL_joystick.h"
#include "../SDL_sysjoystick.h"
#include "../SDL_joystick_c.h"
/* Function to scan the system for joysticks.
* It should return 0, or -1 on an unrecoverable fatal error.
*/
int
SDL_SYS_JoystickInit(void)
{
return (0);
}
int SDL_SYS_NumJoysticks()
{
return 0;
}
void SDL_SYS_JoystickDetect()
{
}
SDL_bool SDL_SYS_JoystickNeedsPolling()
{
return SDL_FALSE;
}
/* Function to get the device-dependent name of a joystick */
const char *
SDL_SYS_JoystickNameForDeviceIndex(int device_index)
{
SDL_SetError("Logic error: No joysticks available");
return (NULL);
}
/* Function to perform the mapping from device index to the instance id for this index */
SDL_JoystickID SDL_SYS_GetInstanceIdOfDeviceIndex(int device_index)
{
return device_index;
}
/* Function to open a joystick for use.
The joystick to open is specified by the index field of the joystick.
This should fill the nbuttons and naxes fields of the joystick structure.
It returns 0, or -1 if there is an error.
*/
int
SDL_SYS_JoystickOpen(SDL_Joystick * joystick, int device_index)
{
return SDL_SetError("Logic error: No joysticks available");
}
/* Function to determine is this joystick is attached to the system right now */
SDL_bool SDL_SYS_JoystickAttached(SDL_Joystick *joystick)
{
return SDL_TRUE;
}
/* Function to update the state of a joystick - called as a device poll.
* This function shouldn't update the joystick structure directly,
* but instead should call SDL_PrivateJoystick*() to deliver events
* and update joystick device state.
*/
void
SDL_SYS_JoystickUpdate(SDL_Joystick * joystick)
{
return;
}
/* Function to close a joystick after use */
void
SDL_SYS_JoystickClose(SDL_Joystick * joystick)
{
return;
}
/* Function to perform any system-specific joystick related cleanup */
void
SDL_SYS_JoystickQuit(void)
{
return;
}
SDL_JoystickGUID SDL_SYS_JoystickGetDeviceGUID( int device_index )
{
SDL_JoystickGUID guid;
/* the GUID is just the first 16 chars of the name for now */
const char *name = SDL_SYS_JoystickNameForDeviceIndex( device_index );
SDL_zero( guid );
SDL_memcpy( &guid, name, SDL_min( sizeof(guid), SDL_strlen( name ) ) );
return guid;
}
SDL_JoystickGUID SDL_SYS_JoystickGetGUID(SDL_Joystick * joystick)
{
SDL_JoystickGUID guid;
/* the GUID is just the first 16 chars of the name for now */
const char *name = joystick->name;
SDL_zero( guid );
SDL_memcpy( &guid, name, SDL_min( sizeof(guid), SDL_strlen( name ) ) );
return guid;
}
#endif /* SDL_JOYSTICK_DUMMY || SDL_JOYSTICK_DISABLED */
/* vi: set ts=4 sw=4 expandtab: */
| 412 | 0.730005 | 1 | 0.730005 | game-dev | MEDIA | 0.961685 | game-dev | 0.645331 | 1 | 0.645331 |
bvbohnen/x4-projects | 13,040 | extensions/sn_friendlier_fire/md/sn_friendlier_fire.xml | <?xml version="1.0" encoding="utf-8" ?>
<mdscript name="SN_Friendlier_Fire"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" >
<!--
Logic for detecting friendly fire incidents, and adjusting the
reputation impact.
TODO:
Think about if md.Notifactions.PlayerOwnedShipAttacks needs adjustment;
it may be odd to be able to freely attack down a friendly ship and get
it to bail without hostility. (Though local logic can maybe detect
that case well enough.)
TODO:
Maybe switch out how this works somewhat, and instead occasionally
poll the faction relations to player, and set all faction ships to
disable rep due to attacked (set_object_relation_behaviour) if they
are player friendly.
Drawback is this would impact npc-vs-npc behavior, and would need
to poll often or otherwise listen to new allied ships being created.
-->
<cues>
<!--
Text storage cue, for easier lookup in general.
Members are descriptive names of the text strings, prefixed with $.
-->
<cue name="Text"/>
<library name="Load_Text">
<actions>
<!--TODO: t file-->
<set_value exact="'Friendlier Fire'" name="Text.$Friendlier_Fire" />
<set_value exact="'Enable'" name="Text.$ff_enable_name" />
<set_value exact="'Enables custom friendlier fire'" name="Text.$ff_enable_mouseover" />
</actions>
</library>
<!-- Listen from the menu api reloading. -->
<cue name="Reset_OnReload" instantiate="true">
<conditions>
<event_cue_signalled cue="md.Simple_Menu_Options.Reloaded"/>
</conditions>
<actions>
<!--Load any text.-->
<include_actions ref="Load_Text"/>
<!--TODO: enable mod? enable rep penalties globally? etc.?-->
<signal_cue_instantly
cue = "md.Simple_Menu_Options.Register_Option"
param = "table[
$category = Text.$Friendlier_Fire,
$id = 'sn_ff_enable',
$name = Text.$ff_enable_name,
$mouseover = Text.$ff_enable_mouseover,
$type = 'button',
$default = 1,
$callback = OnChange,
$echo = 'enabled',
]"/>
</actions>
</cue>
<cue name="OnChange" instantiate="true">
<conditions>
<event_cue_signalled />
</conditions>
<actions>
<!--
TODO
-->
</actions>
</cue>
<!--
This cue listens for any changes to the faction-to-player reputation.
Of interest are those changing due to 'attackedobject'.
Note: basic FF handling is defined by properties in defaults.xml,
where a temp 'boost' is applied after so many hits that floors
the reputation (to -1 absolute).
Note: in vanilla, all penalties have:
decay="0.02" delay="540"
TODO: mod defaults.xml so that the boost is smaller and relative, eg. -0.1,
in case a flicker to -1 has other negative impacts before this logic
kicks in and repairs the rep.
Also change the thresholds to trigger right away so this logic fires
more regularly, maybe.
event_player_relation_changed doc:
"Event for when a faction or an object's control entity changes the relation
towards the player (object = entity or null, param = faction or null,
param2 = [new relation, old relation], param3 = relationchangereason).
NOTE: On permanent faction changes, object is null. On relation boosts,
object is non-null, and param is either null (silent boost) or
faction.player (non-silent boost)."
-->
<cue name="Detect_Change" instantiate="true">
<conditions>
<event_player_relation_changed reason="relationchangereason.attackedobject"/>
<check_value value="false"/>
</conditions>
<actions>
<!--Unpack the params.-->
<set_value name="$object" exact="event.object"/>
<set_value name="$rep_new" exact="event.param2.{1}"/>
<set_value name="$rep_old" exact="event.param2.{2}"/>
<set_value name="$rep_delta" exact="$rep_new - $rep_old"/>
<!--Only looking for temp changes, not perm, so object should be known.
Note: in this case, event.param is null (not faction).
The change is expected to be negative.
-->
<do_if value="$object and $rep_delta lt 0">
<!--
The rep_old may be made up partly by basic faction reputation,
and partly by other temp boosts. The goal here is to preserve
other temp boosts, and just counter the newest change.
While add_relation_boost of an opposite amount could be used,
it is unclear on how these temp boosts are tracked, eg. if there
is a limit on how many are included, so there may be some
awkwardness of stacking up a bunch of such temp boosts on
the target.
The logic here will instead pick out what the prior natural
and boost reps were, then cancel all boosts, and use the prior
temp boost to set a new one.
-->
<set_value name="$rep_faction_base" exact="$object.trueowner.relationto.{faction.player}"/>
<!--Boost expected to be negative.-->
<set_value name="$rep_old_boost" exact="$rep_old - $rep_faction_base"/>
<!--Calculate the new boost to apply, based on local logic.-->
<!--TODO: logic checks.-->
<set_value name="$rep_override_boost" exact="$rep_old_boost"/>
<reset_relation_boost object="$object" faction= "faction.player" />
<add_relation_boost
object = "$object"
faction = "faction.player"
value = "$rep_override_boost"
decay = "0.02"
delay = "540s"
silent = "true"/>
<debug_text text="'attackedobject relation change amount: %s to %s (delta %s), for object %s, base faction relation %s, original boost %s, new boost %s'.[
$rep_old, $rep_new, $rep_delta, $object.name, $rep_faction_base, $rep_old_boost, $rep_override_boost]" filter="general"/>
</do_if>
</actions>
</cue>
<!--
Cue to handle generic events of player assets hitting something else.
Note: in testing, this does not fire regularly, and there will be
gaps where player-owned shots can turn something hostile without
this cue being triggered (though more shots can then trigger
the cue and have it reset the hostility).
Result: this would only be suitable if defaults.xml is heavily
edited to prevent it making targets hostile, doing the logic
purely here. This would have side-effects on npc-vs-npc hits
that may be undesirable.
Possible workarounds:
a) Start a polling routine that keeps checking the object at some
regular rate, constantly trying to reset its relation to player
or player asset.
b) Disable relation adjustments on target (set_object_relation_behaviour),
though this is heavy handed and permenant without more effort.
event_player_owned_attacked_object:
"Event for when a player owned object, including the player, attacks
another object (param = attacker, param2 = attacked object,
param3 = kill method)"
-->
<cue name="Detect_Player_Owned_Attacked_Object" instantiate="true">
<conditions>
<event_player_owned_attacked_object/>
<set_value name="$target" exact="event.param2"/>
<check_value value="$target and $target.isoperational"/>
<check_value value="not $target.isplayerowned" />
<check_value value="not $target.isunit"/>
<check_value value="false"/>
</conditions>
<actions>
<!--Unpack the params.-->
<set_value name="$attacker" exact="event.param"/>
<set_value name="$target" exact="event.param2"/>
<!--
In this case, the victim may have set a temp boost rep against
the attacker, and hence the player.
Pick out the current rep, race rep, estimated boost rep.
-->
<set_value name="$rep_current" exact="$target.relationto.{faction.player}"/>
<set_value name="$rep_faction_base" exact="$target.trueowner.relationto.{faction.player}"/>
<!--Boost expected to be negative.-->
<set_value name="$rep_boost" exact="$rep_current - $rep_faction_base"/>
<!--Calculate the new boost to apply, based on local logic.-->
<!--TODO: logic checks.-->
<set_value name="$rep_boost_new" exact="0"/>
<!--TODO: are the boosts just against the attack object, or against
the object and the player? Clear both for now.-->
<reset_relation_boost object="$target" faction= "faction.player" />
<reset_relation_boost object="$target" otherobject="$attacker" />
<!--Set the new boost, adding to faction base using an 'add' node.
Apply to player faction as a whole, not just attacker.-->
<add_relation_boost
object = "$target"
faction = "faction.player"
value = "$rep_boost_new"
decay = "0.02"
delay = "540s"
silent = "true"/>
<debug_text text="'Player %s attacked %s; faction rep %s, prior boost %s, new boost %s'.[
$attacker.name, $target.name, $rep_faction_base,
$rep_boost, $rep_boost_new]" filter="general"/>
</actions>
</cue>
<!--
Detect a player asset getting hit.
As above, this is likely not called on every hit, though relations
can update on every hit, so this may not be reliable if it needs to
run every time.
As a workaround, set_object_relation_behaviour can be used to set
the player asset to ignore being attacked/killed, maybe on some
delay (using time api), or maybe just forever.
event_player_owned_attacked:
"Event for when a player owned object is attacked
(object = attacked object, param = attacker, param2 = kill method,
param3 = attacked component)"
-->
<cue name="Detect_Player_Owned_Attacked" instantiate="true">
<conditions>
<event_player_owned_attacked/>
<set_value name="$attacker" exact="event.param"/>
<check_value value="$attacker and $attacker.isoperational"/>
<check_value value="not $attacker.isplayerowned" />
<check_value value="false"/>
</conditions>
<actions>
<!--Unpack the params.-->
<set_value name="$attacker" exact="event.param"/>
<set_value name="$target" exact="event.object"/>
<!--
In this case, the player asset has a temp boost to the attacker.
-->
<set_value name="$rep_current" exact="$target.relationto.{$attacker}"/>
<set_value name="$rep_faction_base" exact="faction.player.relationto.{$attacker.trueowner}"/>
<!--Boost expected to be negative.-->
<set_value name="$rep_boost" exact="$rep_current - $rep_faction_base"/>
<!--Calculate the new boost to apply, based on local logic.-->
<!--TODO: logic checks.
- Check if attacker has an order to attack the target.
- Check natural relations; if poor, maybe allow the adjustment.
- Check if attacker has a locked rep to player, in which case can
be more lenient with temp boosts (no cascade effect).
-->
<set_value name="$rep_boost_new" exact="0"/>
<!--TODO: are the boosts just against the attack object, or against
the object and the player? Clear both for now.-->
<reset_relation_boost object="$target" faction= "$attacker.trueowner" />
<reset_relation_boost object="$target" otherobject="$attacker" />
<!--Set the new boost, adding to faction base using an 'add' node.
Apply to player faction as a whole, not just attacker.-->
<add_relation_boost
object = "$target"
faction = "$attacker.trueowner"
value = "$rep_boost_new"
decay = "0.02"
delay = "540s"
silent = "true"/>
<!--
Set to prevent further rep changes due to attacks.
TODO: is there any way to make this temporary? Hard to fix this
if it ends up with a problem and needs patching.
-->
<!--<set_object_relation_behaviour object="$target" disable="true"/>-->
<debug_text text="'Player %s attacked by %s; faction rep %s, prior boost %s, new boost %s'.[
$attacker.name, $target.name, $rep_faction_base,
$rep_boost, $rep_boost_new]" filter="general"/>
</actions>
</cue>
</cues>
</mdscript> | 412 | 0.971931 | 1 | 0.971931 | game-dev | MEDIA | 0.983125 | game-dev | 0.881334 | 1 | 0.881334 |
jbosstm/narayana | 7,956 | ArjunaCore/arjuna/classes/com/arjuna/ats/internal/arjuna/recovery/TransactionStatusManagerItem.java | /*
Copyright The Narayana Authors
SPDX-License-Identifier: Apache-2.0
*/
package com.arjuna.ats.internal.arjuna.recovery ;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import com.arjuna.ats.arjuna.common.Uid;
import com.arjuna.ats.arjuna.exceptions.ObjectStoreException;
import com.arjuna.ats.arjuna.logging.tsLogger;
import com.arjuna.ats.arjuna.objectstore.ParticipantStore;
import com.arjuna.ats.arjuna.objectstore.StoreManager;
import com.arjuna.ats.arjuna.state.InputObjectState;
import com.arjuna.ats.arjuna.state.OutputObjectState;
import com.arjuna.ats.arjuna.utils.Utility;
// similar to FactoryContactItem
public class TransactionStatusManagerItem
{
/**
* Create the instance of a Transaction Status Manager
* contact item.
* @deprecated Only used in tests
*/
public static boolean createAndSave( int port )
{
boolean ret_status = true ;
if ( _singularItem == null )
{
_singularItem = new TransactionStatusManagerItem( port );
ret_status = _singularItem.saveThis();
}
return ret_status ;
}
public static boolean createAndSave(String hostAddress, int port )
{
boolean ret_status = true ;
if ( _singularItem == null )
{
_singularItem = new TransactionStatusManagerItem(hostAddress, port );
ret_status = _singularItem.saveThis();
}
return ret_status ;
}
/**
* Get a reference to the Object Store.
*/
private static ParticipantStore getStore()
{
return StoreManager.getCommunicationStore();
}
/**
* Accessor method for host in format xxx.xxx.xxx.xxx
*/
public String host()
{
return _host ;
}
/**
* Accessor method for the port used by this object.
*/
public int port()
{
return _port ;
}
/**
* The process has died.
*/
public void markAsDead()
{
// ignore if done previously
if ( ! _markedDead )
{
// the host/port won't work any more, so forget it
_markedDead = true ;
_deadTime = new Date() ;
saveThis() ;
}
}
/**
* Return time when process marked dead.
*/
public Date getDeadTime()
{
return _deadTime ;
}
/**
* Returns reference to this transaction status manager item.
*/
public static TransactionStatusManagerItem get()
{
return _singularItem ;
}
/**
* Crash Recovery uses this method to recreate a
* representation of the Transaction Status Managers
* host/port pair contact.
*/
public static TransactionStatusManagerItem recreate ( Uid uid )
{
TransactionStatusManagerItem
theItem = new TransactionStatusManagerItem( uid ) ;
if ( theItem.restoreThis() )
{
return theItem ;
}
else
{
return null;
}
}
/**
* Destroy the host/port pair for the specified process Uid.
*/
public static boolean removeThis( Uid pidUid )
{
boolean ret_status = false ;
try
{
ret_status = getStore().remove_committed( pidUid, _typeName ) ;
}
catch ( ObjectStoreException ex ) {
tsLogger.i18NLogger.warn_recovery_TransactionStatusManagerItem_1(ex);
}
return ret_status ;
}
/**
* Type used as path into object store for a TransactionStatusManagerItem.
*/
public static String typeName()
{
return _typeName ;
}
/**
* Read host/port pair from the ObjectStore using
* the process Uid as a unique identifier.
*/
private boolean restoreThis()
{
boolean ret_status = false ;
try
{
InputObjectState objstate = getStore().read_committed( _pidUid,
_typeName ) ;
if ( restore_state( objstate) )
{
return ret_status = true ;
}
}
catch ( ObjectStoreException ex ) {
ret_status = false;
tsLogger.i18NLogger.warn_recovery_TransactionStatusManagerItem_2(ex);
}
return ret_status ;
}
/**
* Retrieve host/port pair from the Object Store.
*/
private boolean restore_state ( InputObjectState objstate )
{
boolean ret_status = false ;
try
{
_host = objstate.unpackString() ;
_port = objstate.unpackInt() ;
_markedDead = objstate.unpackBoolean() ;
if ( _markedDead )
{
long deadtime = objstate.unpackLong() ;
_deadTime = new Date( deadtime ) ;
}
ret_status = true ;
}
catch ( IOException ex ) {
tsLogger.i18NLogger.warn_recovery_TransactionStatusManagerItem_3(ex);
}
return ret_status ;
}
/**
* Save host/port pair to the Object Store.
*/
private boolean save_state ( OutputObjectState objstate )
{
boolean ret_status = false ;
try
{
objstate.packString( _host ) ;
objstate.packInt( _port ) ;
objstate.packBoolean( _markedDead ) ;
if ( _markedDead )
{
objstate.packLong( _deadTime.getTime() ) ;
}
ret_status = true ;
}
catch ( IOException ex ) {
tsLogger.i18NLogger.warn_recovery_TransactionStatusManagerItem_2(ex);
}
return ret_status ;
}
/**
* Write host/port pair to the ObjectStore using
* the process Uid as a unique identifier.
*/
private boolean saveThis()
{
boolean ret_status = false ;
try
{
OutputObjectState objstate = new OutputObjectState();
if ( save_state(objstate) )
{
ret_status = getStore().write_committed ( _pidUid,
_typeName,
objstate ) ;
}
}
catch ( ObjectStoreException ex ) {
tsLogger.i18NLogger.warn_recovery_TransactionStatusManagerItem_2(ex);
}
return ret_status ;
}
/**
* Constructor which obtains the process uid and host for
* use with the specified port.
*/
private TransactionStatusManagerItem ( int port )
{
_pidUid = Utility.getProcessUid() ;
_port = port ;
try
{
_host = InetAddress.getLocalHost().getHostAddress() ;
tsLogger.logger.debugf("TransactionStatusManagerItem host: {0} port: {1}", _host, Integer.toString(_port));
}
catch ( UnknownHostException ex ) {
tsLogger.i18NLogger.warn_recovery_TransactionStatusManagerItem_4(ex);
}
}
/**
* Constructor which obtains the process uid for
* use with the specified host and port.
*/
private TransactionStatusManagerItem (String host, int port )
{
_pidUid = Utility.getProcessUid() ;
_port = port ;
try
{
// make sure the passed in host is valid
Utility.hostNameToInetAddress(host);
_host = host;
tsLogger.logger.debugf("TransactionStatusManagerItem host: {0} port: {1}", _host, Integer.toString(_port));
}
catch ( UnknownHostException ex ) {
tsLogger.i18NLogger.warn_recovery_TransactionStatusManagerItem_4(ex);
}
}
/**
* Used by a Recovery Manager to recreate a Transaction
* status manager contact item.
*/
private TransactionStatusManagerItem( Uid uid )
{
_pidUid = new Uid( uid ) ;
}
// Process Uid.
private Uid _pidUid ;
// Relative location in object store for this 'type'.
private static String _typeName = "/Recovery/TransactionStatusManager" ;
// Host/port pair on which to connect to the Transaction status manager.
private String _host ;
private int _port ;
// The singleton instance of this class.
private static TransactionStatusManagerItem _singularItem = null ;
// Time at which the process for this item has died.
private Date _deadTime = null ;
// flag indicates dead TSM
private boolean _markedDead = false ;
} | 412 | 0.967841 | 1 | 0.967841 | game-dev | MEDIA | 0.207591 | game-dev | 0.997883 | 1 | 0.997883 |
ACCBDD/complicated_bees | 9,530 | src/main/java/com/accbdd/complicated_bees/datagen/loot/BlockLootTables.java | package com.accbdd.complicated_bees.datagen.loot;
import com.accbdd.complicated_bees.block.entity.mellarium.MellariumEnergyCellBlockEntity;
import com.accbdd.complicated_bees.loot.InheritHiveCombFunction;
import com.accbdd.complicated_bees.loot.InheritHiveSpeciesFunction;
import com.accbdd.complicated_bees.registry.BlocksRegistration;
import com.accbdd.complicated_bees.registry.ItemsRegistration;
import net.minecraft.data.loot.BlockLootSubProvider;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.IntTag;
import net.minecraft.world.flag.FeatureFlags;
import net.minecraft.world.item.enchantment.Enchantments;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.storage.loot.LootPool;
import net.minecraft.world.level.storage.loot.LootTable;
import net.minecraft.world.level.storage.loot.entries.LootItem;
import net.minecraft.world.level.storage.loot.functions.ApplyBonusCount;
import net.minecraft.world.level.storage.loot.functions.CopyNbtFunction;
import net.minecraft.world.level.storage.loot.functions.SetItemCountFunction;
import net.minecraft.world.level.storage.loot.providers.nbt.ContextNbtProvider;
import net.minecraft.world.level.storage.loot.providers.number.ConstantValue;
import net.minecraft.world.level.storage.loot.providers.number.UniformGenerator;
import net.minecraftforge.registries.RegistryObject;
import java.util.Collections;
public class BlockLootTables extends BlockLootSubProvider {
public static final CompoundTag ENERGY_TAG_EMPTY = new CompoundTag();
public BlockLootTables() {
super(Collections.emptySet(), FeatureFlags.REGISTRY.allFlags());
ENERGY_TAG_EMPTY.put(MellariumEnergyCellBlockEntity.ENERGY_TAG, IntTag.valueOf(0));
}
@Override
protected void generate() {
dropSelf(BlocksRegistration.APIARY.get());
dropSelf(BlocksRegistration.CENTRIFUGE.get());
dropSelf(BlocksRegistration.FURNACE_GENERATOR.get());
dropSelf(BlocksRegistration.HONEY_GENERATOR.get());
dropSelf(BlocksRegistration.APID_LIBRARY.get());
dropSelf(BlocksRegistration.MICROSCOPE.get());
dropSelf(BlocksRegistration.BEE_SORTER.get());
dropSelf(BlocksRegistration.AUTOLYZER.get());
dropSelf(BlocksRegistration.MELLARIUM_BASE.get());
this.add(BlocksRegistration.MELLARIUM_CONTROLLER.get(), createSingleItemTable(ItemsRegistration.MELLARIUM_BASE.get()));
dropSelf(BlocksRegistration.MELLARIUM_TEMP_UNIT.get());
dropSelf(BlocksRegistration.MELLARIUM_FRAME_HOUSING_1.get());
dropSelf(BlocksRegistration.MELLARIUM_FRAME_HOUSING_2.get());
dropSelf(BlocksRegistration.MELLARIUM_FRAME_HOUSING_3.get());
dropSelf(BlocksRegistration.MELLARIUM_RAIN_SHIELD.get());
dropSelf(BlocksRegistration.MELLARIUM_MUTATOR.get());
dropSelf(BlocksRegistration.MELLARIUM_HYDROREGULATOR.get());
this.add(BlocksRegistration.MELLARIUM_ENERGY_CELL.get(), energyCellBlock(BlocksRegistration.MELLARIUM_ENERGY_CELL.get()));
dropSelf(BlocksRegistration.MELLARIUM_SKYBOX.get());
dropSelf(BlocksRegistration.MELLARIUM_TEMPORAL_SIMULATOR.get());
dropSelf(BlocksRegistration.MELLARIUM_OUTPUT_HATCH.get());
this.add(BlocksRegistration.GYROFUGE_ENERGY_CELL.get(), energyCellBlock(BlocksRegistration.GYROFUGE_ENERGY_CELL.get()));
dropSelf(BlocksRegistration.GYROFUGE_BASE.get());
this.add(BlocksRegistration.GYROFUGE_CONTROLLER.get(), createSingleItemTable(ItemsRegistration.GYROFUGE_BASE.get()));
dropSelf(BlocksRegistration.GYROFUGE_BASIC_PROCESSING_UNIT.get());
dropSelf(BlocksRegistration.GYROFUGE_PROCESSING_UNIT.get());
dropSelf(BlocksRegistration.GYROFUGE_ADVANCED_PROCESSING_UNIT.get());
dropSelf(BlocksRegistration.GYROFUGE_SPEED_UNIT.get());
dropSelf(BlocksRegistration.GYROFUGE_EFFICIENCY_UNIT.get());
dropSelf(BlocksRegistration.GYROFUGE_EXTRACTION_UNIT.get());
dropSelf(BlocksRegistration.GYROFUGE_BASIC_SPEED_UNIT.get());
dropSelf(BlocksRegistration.GYROFUGE_ADVANCED_SPEED_UNIT.get());
dropSelf(BlocksRegistration.GYROFUGE_BASIC_EFFICIENCY_UNIT.get());
dropSelf(BlocksRegistration.GYROFUGE_ADVANCED_EFFICIENCY_UNIT.get());
dropSelf(BlocksRegistration.GYROFUGE_BASIC_EXTRACTION_UNIT.get());
dropSelf(BlocksRegistration.GYROFUGE_ADVANCED_EXTRACTION_UNIT.get());
dropSelf(BlocksRegistration.GYROFUGE_OUTPUT_HATCH.get());
dropSelf(BlocksRegistration.GYROFUGE_INPUT_HATCH.get());
this.add(BlocksRegistration.BEE_NEST.get(), nestLootTable(BlocksRegistration.BEE_NEST.get()));
dropSelf(BlocksRegistration.WAX_BLOCK.get());
dropSelf(BlocksRegistration.WAX_BLOCK_STAIRS.get());
this.add(BlocksRegistration.WAX_BLOCK_SLAB.get(), createSlabItemTable(BlocksRegistration.WAX_BLOCK_SLAB.get()));
dropSelf(BlocksRegistration.WAX_BLOCK_WALL.get());
dropSelf(BlocksRegistration.SMOOTH_WAX.get());
dropSelf(BlocksRegistration.SMOOTH_WAX_STAIRS.get());
this.add(BlocksRegistration.SMOOTH_WAX_SLAB.get(), createSlabItemTable(BlocksRegistration.SMOOTH_WAX_SLAB.get()));
dropSelf(BlocksRegistration.SMOOTH_WAX_WALL.get());
dropSelf(BlocksRegistration.WAX_BRICKS.get());
dropSelf(BlocksRegistration.WAX_BRICK_STAIRS.get());
this.add(BlocksRegistration.WAX_BRICK_SLAB.get(), createSlabItemTable(BlocksRegistration.WAX_BRICK_SLAB.get()));
dropSelf(BlocksRegistration.WAX_BRICK_WALL.get());
dropSelf(BlocksRegistration.CHISELED_WAX.get());
dropSelf(BlocksRegistration.HONEYED_PLANKS.get());
dropSelf(BlocksRegistration.HONEYED_STAIRS.get());
this.add(BlocksRegistration.HONEYED_SLAB.get(), createSlabItemTable(BlocksRegistration.HONEYED_SLAB.get()));
dropSelf(BlocksRegistration.HONEYED_FENCE.get());
dropSelf(BlocksRegistration.HONEYED_FENCE_GATE.get());
dropSelf(BlocksRegistration.HONEYED_BUTTON.get());
dropSelf(BlocksRegistration.HONEYED_PRESSURE_PLATE.get());
this.add(BlocksRegistration.HONEYED_DOOR.get(), createDoorTable(BlocksRegistration.HONEYED_DOOR.get()));
dropSelf(BlocksRegistration.HONEYED_TRAPDOOR.get());
dropSelf(BlocksRegistration.HONEYED_SIGN.get());
dropOther(BlocksRegistration.HONEYED_WALL_SIGN.get(), ItemsRegistration.HONEYED_SIGN.get());
dropSelf(BlocksRegistration.HONEYED_HANGING_SIGN.get());
dropOther(BlocksRegistration.HONEYED_WALL_HANGING_SIGN.get(), ItemsRegistration.HONEYED_HANGING_SIGN.get());
}
@Override
protected Iterable<Block> getKnownBlocks() {
return BlocksRegistration.BLOCKS.getEntries()
.stream()
.map(RegistryObject::get)
.toList();
}
public LootTable.Builder nestLootTable(Block beenest) {
return LootTable.lootTable()
.withPool(LootPool.lootPool()
.when(HAS_SILK_TOUCH)
.setRolls(ConstantValue.exactly(1.0f))
.add(
LootItem.lootTableItem(beenest).apply(CopyNbtFunction
.copyData(ContextNbtProvider.BLOCK_ENTITY)
.copy("species", "BlockEntityTag.species", CopyNbtFunction.MergeStrategy.REPLACE)
)
))
.withPool(LootPool.lootPool()
.when(HAS_NO_SILK_TOUCH)
.setRolls(ConstantValue.exactly(1.0f))
.add(
LootItem.lootTableItem(ItemsRegistration.PRINCESS.get()).apply(InheritHiveSpeciesFunction.set())
))
.withPool(LootPool.lootPool()
.when(HAS_NO_SILK_TOUCH)
.setRolls(ConstantValue.exactly(1.0f))
.add(
LootItem.lootTableItem(ItemsRegistration.DRONE.get())
.apply(InheritHiveSpeciesFunction.set())
.apply(SetItemCountFunction.setCount(UniformGenerator.between(1, 2)))
.apply(ApplyBonusCount.addUniformBonusCount(Enchantments.BLOCK_FORTUNE, 1))
))
.withPool(LootPool.lootPool()
.when(HAS_NO_SILK_TOUCH)
.setRolls(ConstantValue.exactly(1.0f))
.add(
LootItem.lootTableItem(ItemsRegistration.COMB.get())
.apply(InheritHiveCombFunction.set())
.apply(SetItemCountFunction.setCount(UniformGenerator.between(1, 3)))
.apply(ApplyBonusCount.addUniformBonusCount(Enchantments.BLOCK_FORTUNE, 1))
)
);
}
protected LootTable.Builder energyCellBlock(Block pBlock) {
return LootTable.lootTable()
.withPool(LootPool.lootPool()
.setRolls(ConstantValue.exactly(1.0f))
.add(
LootItem.lootTableItem(pBlock)
.apply(CopyNbtFunction.copyData(ContextNbtProvider.BLOCK_ENTITY).copy("energy", "BlockEntityTag.energy"))
)
);
}
}
| 412 | 0.739995 | 1 | 0.739995 | game-dev | MEDIA | 0.885133 | game-dev,testing-qa | 0.700818 | 1 | 0.700818 |
Thales1330/PSP | 1,182 | docs/doxygen/html/dir_f9bb4b9ba954539847076e91ec887623.js | var dir_f9bb4b9ba954539847076e91ec887623 =
[
[ "ConnectionLine.h", "_connection_line_8h.html", "_connection_line_8h" ],
[ "Constant.h", "_constant_8h.html", "_constant_8h" ],
[ "ControlElement.h", "_control_element_8h.html", "_control_element_8h" ],
[ "ControlElementContainer.h", "_control_element_container_8h.html", "_control_element_container_8h" ],
[ "ControlElementSolver.h", "_control_element_solver_8h.html", "_control_element_solver_8h" ],
[ "Divider.h", "_divider_8h.html", "_divider_8h" ],
[ "Exponential.h", "_exponential_8h.html", "_exponential_8h" ],
[ "Gain.h", "_gain_8h.html", "_gain_8h" ],
[ "IOControl.h", "_i_o_control_8h.html", "_i_o_control_8h" ],
[ "Limiter.h", "_limiter_8h.html", "_limiter_8h" ],
[ "MathExpression.h", "_math_expression_8h.html", "_math_expression_8h" ],
[ "MathOperation.h", "_math_operation_8h.html", "_math_operation_8h" ],
[ "Multiplier.h", "_multiplier_8h.html", "_multiplier_8h" ],
[ "RateLimiter.h", "_rate_limiter_8h.html", "_rate_limiter_8h" ],
[ "Sum.h", "_sum_8h.html", "_sum_8h" ],
[ "TransferFunction.h", "_transfer_function_8h.html", "_transfer_function_8h" ]
]; | 412 | 0.687047 | 1 | 0.687047 | game-dev | MEDIA | 0.390941 | game-dev | 0.759528 | 1 | 0.759528 |
Fluorohydride/ygopro-scripts | 3,929 | c97476032.lua | --アイス・ドール
local s,id,o=GetID()
function s.initial_effect(c)
aux.AddCodeList(c,65569724)
--special summon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(id,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetRange(LOCATION_HAND)
e1:SetCountLimit(1,id)
e1:SetCost(s.spcost)
e1:SetTarget(s.sptg)
e1:SetOperation(s.spop)
c:RegisterEffect(e1)
--to hand
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(id,1))
e2:SetCategory(CATEGORY_SEARCH|CATEGORY_TOHAND)
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e2:SetCode(EVENT_SUMMON_SUCCESS)
e2:SetCountLimit(1,id+o)
e2:SetProperty(EFFECT_FLAG_DELAY)
e2:SetCost(s.thcost)
e2:SetTarget(s.thtg)
e2:SetOperation(s.thop)
c:RegisterEffect(e2)
local e3=e2:Clone()
e3:SetCode(EVENT_SPSUMMON_SUCCESS)
c:RegisterEffect(e3)
--to hand
local e4=Effect.CreateEffect(c)
e4:SetDescription(aux.Stringid(id,2))
e4:SetCategory(CATEGORY_SEARCH|CATEGORY_TOHAND)
e4:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e4:SetCode(EVENT_TO_GRAVE)
e4:SetProperty(EFFECT_FLAG_DELAY)
e4:SetCountLimit(1,id+o*2)
e4:SetCondition(s.thcon2)
e4:SetCost(s.thcost)
e4:SetTarget(s.thtg2)
e4:SetOperation(s.thop2)
c:RegisterEffect(e4)
Duel.AddCustomActivityCounter(id,ACTIVITY_SPSUMMON,s.counterfilter)
end
function s.counterfilter(c)
return c:IsAttribute(ATTRIBUTE_WATER)
end
function s.thcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetCustomActivityCount(id,tp,ACTIVITY_SPSUMMON)==0 end
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_CANNOT_SPECIAL_SUMMON)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET+EFFECT_FLAG_OATH)
e1:SetTargetRange(1,0)
e1:SetTarget(s.splimit)
e1:SetReset(RESET_PHASE+PHASE_END)
Duel.RegisterEffect(e1,tp)
end
function s.splimit(e,c,sump,sumtype,sumpos,targetp,se)
return not c:IsAttribute(ATTRIBUTE_WATER)
end
function s.cfilter(c)
return c:IsAttribute(ATTRIBUTE_WATER) and c:IsDiscardable()
end
function s.spcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return s.thcost(e,tp,eg,ep,ev,re,r,rp,chk) and Duel.IsExistingMatchingCard(s.cfilter,tp,LOCATION_HAND,0,1,e:GetHandler()) end
Duel.DiscardHand(tp,s.cfilter,1,1,REASON_COST+REASON_DISCARD,e:GetHandler())
s.thcost(e,tp,eg,ep,ev,re,r,rp,chk)
end
function s.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and e:GetHandler():IsCanBeSpecialSummoned(e,0,tp,false,false) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0)
end
function s.spop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsRelateToEffect(e) then
Duel.SpecialSummon(c,0,tp,tp,false,false,POS_FACEUP)
end
end
function s.thfilter(c)
return c:IsRace(RACE_SPELLCASTER) and c:IsAttribute(ATTRIBUTE_WATER) and c:IsAbleToHand()
end
function s.thtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(s.thfilter,tp,LOCATION_DECK,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK)
end
function s.thop(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectMatchingCard(tp,s.thfilter,tp,LOCATION_DECK,0,1,1,nil)
if #g>0 then
Duel.SendtoHand(g,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,g)
end
end
function s.thcon2(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():IsPreviousLocation(LOCATION_ONFIELD)
end
function s.thfilter2(c)
return c:IsCode(65569724) and c:IsAbleToHand()
end
function s.thtg2(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(s.thfilter2,tp,LOCATION_DECK,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK)
end
function s.thop2(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectMatchingCard(tp,s.thfilter2,tp,LOCATION_DECK,0,1,1,nil)
if #g>0 then
Duel.SendtoHand(g,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,g)
end
end
| 412 | 0.900246 | 1 | 0.900246 | game-dev | MEDIA | 0.981351 | game-dev | 0.953153 | 1 | 0.953153 |
kartik-venugopal/aural-player | 2,884 | Source/Core/Persistence/Model/AudioGraph/MasterUnitPersistentState.swift | //
// MasterUnitPersistentState.swift
// Aural
//
// Copyright © 2025 Kartik Venugopal. All rights reserved.
//
// This software is licensed under the MIT software license.
// See the file "LICENSE" in the project root directory for license terms.
//
import Foundation
///
/// Persistent state for the Master effects unit.
///
/// - SeeAlso: `MasterUnit`
///
struct MasterUnitPersistentState: Codable {
let state: EffectsUnitState?
let userPresets: [MasterPresetPersistentState]?
init(state: EffectsUnitState?, userPresets: [MasterPresetPersistentState]?) {
self.state = state
self.userPresets = userPresets
}
init(legacyPersistentState: LegacyMasterUnitPersistentState?) {
self.state = EffectsUnitState.fromLegacyState(legacyPersistentState?.state)
self.userPresets = legacyPersistentState?.userPresets?.map {MasterPresetPersistentState(legacyPersistentState: $0)}
}
}
///
/// Persistent state for a single Master effects unit preset.
///
/// - SeeAlso: `MasterPreset`
///
struct MasterPresetPersistentState: Codable {
let name: String?
let state: EffectsUnitState?
let eq: EQPresetPersistentState?
let pitchShift: PitchShiftPresetPersistentState?
let timeStretch: TimeStretchPresetPersistentState?
let reverb: ReverbPresetPersistentState?
let delay: DelayPresetPersistentState?
let filter: FilterPresetPersistentState?
init(preset: MasterPreset) {
self.name = preset.name
self.state = preset.state
self.eq = EQPresetPersistentState(preset: preset.eq)
self.pitchShift = PitchShiftPresetPersistentState(preset: preset.pitch)
self.timeStretch = TimeStretchPresetPersistentState(preset: preset.time)
self.reverb = ReverbPresetPersistentState(preset: preset.reverb)
self.delay = DelayPresetPersistentState(preset: preset.delay)
self.filter = FilterPresetPersistentState(preset: preset.filter)
}
init(legacyPersistentState: LegacyMasterPresetPersistentState?) {
self.name = legacyPersistentState?.name
self.state = EffectsUnitState.fromLegacyState(legacyPersistentState?.state)
self.eq = EQPresetPersistentState(legacyPersistentState: legacyPersistentState?.eq)
self.pitchShift = PitchShiftPresetPersistentState(legacyPersistentState: legacyPersistentState?.pitch)
self.timeStretch = TimeStretchPresetPersistentState(legacyPersistentState: legacyPersistentState?.time)
self.reverb = ReverbPresetPersistentState(legacyPersistentState: legacyPersistentState?.reverb)
self.delay = DelayPresetPersistentState(legacyPersistentState: legacyPersistentState?.delay)
self.filter = FilterPresetPersistentState(legacyPersistentState: legacyPersistentState?.filter)
}
}
| 412 | 0.6864 | 1 | 0.6864 | game-dev | MEDIA | 0.865992 | game-dev | 0.698409 | 1 | 0.698409 |
ChristopherRabotin/GMAT | 1,413 | src/csaltTester/src/HelperClasses/BrachistichronePointObject.hpp | //------------------------------------------------------------------------------
// BrachistichronePointObject
//------------------------------------------------------------------------------
// GMAT: General Mission Analysis Tool.
//
// Copyright (c) 2002 - 2022 United States Government as represented by the
// Administrator of the National Aeronautics and Space Administration.
// All Other Rights Reserved.
//
// Author: Jeremy Knittel
// Created: 2016.11.03
//
/**
* Developed based on BrachistichronePointObject.m
*/
//------------------------------------------------------------------------------
#ifndef BrachistichronePointObject_hpp
#define BrachistichronePointObject_hpp
#include "UserPointFunction.hpp"
/**
* BrachistichronePointObject class
*/
class BrachistichronePointObject : public UserPointFunction
{
public:
/// default constructor
BrachistichronePointObject();
/// copy constructor
BrachistichronePointObject(const BrachistichronePointObject ©);
/// operator=
BrachistichronePointObject& operator=(const BrachistichronePointObject ©);
/// default destructor
virtual ~BrachistichronePointObject();
/// EvaluateFunctions
void EvaluateFunctions();
/// EvaluateJacobians
void EvaluateJacobians();
protected:
};
#endif // BrachistichronePointObject_hpp | 412 | 0.765923 | 1 | 0.765923 | game-dev | MEDIA | 0.820035 | game-dev | 0.772579 | 1 | 0.772579 |
SonySemiconductorSolutions/tof-ar-samples-ar | 4,990 | Assets/TofArSamplesAr/SamplesAr/Juggling/Scripts/JugglingDistanceManager.cs | /*
* SPDX-License-Identifier: (Apache-2.0 OR GPL-2.0-only)
*
* Copyright 2022 Sony Semiconductor Solutions Corporation.
*
*/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TofAr.V0.Face;
using TofAr.V0.Hand;
using TofArSettings.Color;
namespace TofArARSamples.Juggling
{
/// <summary>
/// This class manages the distance between hand or face and the camera in juggling scene.
/// </summary>
public class JugglingDistanceManager : MonoBehaviour
{
[SerializeField]
private JugglingFaceController faceController;
private JugglingHandController handController;
private ColorManagerController colorController;
//shortest possible distance to start juggling
[Range(0.0f, 0.7f)]
[SerializeField]
private float minRange = 0.6f;
//longest possible distance to start juggling
[Range(0.7f, 1.2f)]
[SerializeField]
private float maxRange = 0.9f;
private void Start()
{
#if UNITY_IOS
if (faceController == null)
{
faceController = FindObjectOfType<JugglingFaceController>();
}
if (colorController == null)
{
colorController = FindObjectOfType<ColorManagerController>();
}
#endif
if (handController == null)
{
handController = FindObjectOfType<JugglingHandController>();
}
}
/// <summary>
/// checks the distance if the juggling is available.
/// </summary>
/// <returns></returns>
public bool IsOk()
{
#if UNITY_IOS
bool faceInDistance = true;
if (colorController.CurrentResolution.lensFacing == 0)
{
if (faceController.GetTrackingState() != TrackingState.Tracking)
{
return false;
}
faceController.GetDistance(out float distanceFace);
faceInDistance = IsInRange(distanceFace);
}
#endif
if (handController.GetHandStatus() != HandStatus.BothHands)
{
return false;
}
bool isOk = false;
handController.GetDistance(out float distanceHandLeft, out float distanceHandRight);
#if UNITY_IOS
if (faceInDistance && IsInRange(distanceHandLeft) && IsInRange(distanceHandRight))
{
isOk = true;
}
#else
if (IsInRange(distanceHandLeft) && IsInRange(distanceHandRight))
{
isOk = true;
}
#endif
return isOk;
}
/// <summary>
/// checks that the value is within the range.
/// </summary>
/// <param name="param"></param>
/// <returns></returns>
private bool IsInRange(float param)
{
bool isInRange = false;
if (minRange <= param && param <= maxRange)
{
isInRange = true;
}
return isInRange;
}
/// <summary>
/// returns how much more or less distance is needed to start.
/// </summary>
/// <returns></returns>
public void GetRequiredDistance(out float requiredFace, out float requiredHandLeft, out float requiredHandRight)
{
requiredFace = 0f;
requiredHandLeft = 0f;
requiredHandRight = 0f;
#if UNITY_IOS
faceController.GetDistance(out float distanceFace);
if (distanceFace > 0)
{
requiredFace = CalcRequiredDistance(distanceFace);
}
#endif
handController.GetDistance(out float distanceHandLeft, out float distanceHandRight);
if (distanceHandLeft > 0)
{
requiredHandLeft = CalcRequiredDistance(distanceHandLeft);
}
if (distanceHandRight > 0)
{
requiredHandRight = CalcRequiredDistance(distanceHandRight);
}
}
/// <summary>
/// calculates how far or close the value is from the threshold.
/// </summary>
/// <param name="val">current value</param>
/// <returns>distance needed</returns>
private float CalcRequiredDistance(float val)
{
float requied = 0f;
//farther than the longest distance
if (val > maxRange)
{
requied = maxRange - val;
}
//closer than the shortest distance
if (val < minRange)
{
requied = minRange - val;
}
//returns 100 when the value is within range
if (val != 0f && IsInRange(val))
{
requied = 100f;
}
return requied;
}
}
}
| 412 | 0.913004 | 1 | 0.913004 | game-dev | MEDIA | 0.929286 | game-dev | 0.938597 | 1 | 0.938597 |
KhMustafa/Risk-aware-contingency-planning-with-multi-modal-predictions | 41,402 | planner/Frenet/utils/visualization.py | #!/user/bin/env python
"""Visualization functions for the frenét planner."""
import warnings
from commonroad.scenario.scenario import Scenario
from commonroad.visualization.draw_dispatch_cr import draw_object
from commonroad_helper_functions.visualization import (
get_max_frames_from_scenario,
get_plot_limits_from_scenario,
)
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import matplotlib.cm as cm
import matplotlib.animation as animation
from matplotlib.patches import Polygon
import sys
import os
import pickle
# Ignore Matplotlib DeprecationWarning
warnings.filterwarnings("ignore", category=matplotlib.cbook.mplDeprecation)
plt.rcParams["figure.figsize"] = (8, 8)
module_path = os.path.dirname(
os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
)
sys.path.append(module_path)
from planner.Frenet.utils.helper_functions import (
get_max_curvature,
green_to_red_colormap,
)
from planner.utils.timers import ExecTimer
from prediction.utils.visualization import draw_uncertain_predictions
i = 0
def animate_scenario(
scenario: Scenario,
fps: int = 30,
plot_limits: [float] = None,
marked_vehicles: [int] = None,
planning_problem=None,
save_animation: bool = False,
animation_directory: str = "./out/",
animation_area: float = None,
success: bool = None,
failure_msg: str = None,
exec_timer=None,
):
"""
Animate a commonroad scenario.
Args:
scenario (Scenario): Scenario to be animated.
fps (int): Frames per second. Defaults to 30.
plot_limits ([float]): Plot limits for the scenario. Defaults to None.
marked_vehicles ([int]): IDs of the vehicles that should be marked. Defaults to None.
planning_problem (PlanningProblem): Considered planning problem. Defaults to None.
save_animation (bool): True if the animation should be saved. Defaults to False.
animation_directory (str): Directory to save the animation in. Defaults to './out/'.
animation_area (float): Size of the animated area). Defaults to None.
success (bool): True if it is a successfully solved scenario. Defaults to None.
failure_msg (str): Failure-message of the scenario. Defaults to None.
exec_times_dict (dict): Dictionary with the execution times. Defaults to None.
Returns:
animation: Animated scenario.
dict: Dictionary with the execution times.
"""
# Create a dummy logger that does nothing if no timer is given
if exec_timer is None:
exec_timer = ExecTimer(False)
# get the plot limits
if plot_limits is None:
plot_limits = get_plot_limits_from_scenario(scenario=scenario)
# get the frames per second
if 1 / fps < scenario.dt:
fps_available = 1 / scenario.dt
else:
fps_available = fps
# get the number of frames (number of time steps until the planning problem is solved
if marked_vehicles is not None:
frames = (
len(scenario.obstacle_by_id(marked_vehicles[0]).prediction.occupancy_set)
+ 1
)
elif planning_problem is not None and hasattr(
planning_problem.goal.state_list[0], "time_step"
):
frames = planning_problem.goal.state_list[0].time_step.end + 1
else:
trajectory_points = get_max_frames_from_scenario(scenario=scenario)
frames = int(trajectory_points * scenario.dt * fps_available)
if frames == 0:
frames = 1
# get the states of the marked vehicle
t = []
v = []
a = []
yaw = []
with exec_timer.time_with_cm("animate create states"):
if marked_vehicles is not None:
# add the initial states if they are given in the planning problme
trajectory = scenario.obstacle_by_id(
marked_vehicles[0]
).prediction.trajectory
if hasattr(
scenario.obstacle_by_id(marked_vehicles[0]).initial_state, "time_step"
):
t.append(
scenario.obstacle_by_id(marked_vehicles[0]).initial_state.time_step
)
else:
t.append(0)
if hasattr(
scenario.obstacle_by_id(marked_vehicles[0]).initial_state, "velocity"
):
v.append(
scenario.obstacle_by_id(marked_vehicles[0]).initial_state.velocity
)
else:
v.append(0.0)
if hasattr(
scenario.obstacle_by_id(marked_vehicles[0]).initial_state,
"acceleration",
):
a.append(
scenario.obstacle_by_id(
marked_vehicles[0]
).initial_state.acceleration
)
else:
a.append(0.0)
if hasattr(
scenario.obstacle_by_id(marked_vehicles[0]).initial_state, "orientation"
):
yaw.append(
scenario.obstacle_by_id(
marked_vehicles[0]
).initial_state.orientation
)
else:
yaw.append(0.0)
# add every state from the trajectory
for state in trajectory.state_list:
if hasattr(state, "velocity"):
v.append(state.velocity)
else:
v.append(0.0)
if hasattr(state, "time_step"):
t.append(state.time_step)
else:
t.append(0)
if hasattr(state, "acceleration"):
a.append(state.acceleration)
else:
a.append(0.0)
if hasattr(state, "orientation"):
yaw.append(state.orientation)
else:
yaw.append(0.0)
# get information about the success of the solved scenario
# there are 2 directories, one for successful scenarios and one for failed ones
# create these directories if they do not exist yet
success_or_not = ""
if success is not None:
if success is True:
success_or_not = "Succeeded!"
if failure_msg is not None:
success_or_not += "\n" + failure_msg
animation_directory = animation_directory + "/succeeded/"
if not os.path.exists(animation_directory):
os.makedirs(animation_directory)
else:
success_or_not = "Failed!"
if failure_msg is not None:
success_or_not += "\n" + failure_msg
animation_directory = animation_directory + "/failed/"
if not os.path.exists(animation_directory):
os.makedirs(animation_directory)
def animate(j):
# axis 1 sows the marked vehicle in the lanelet network
ax1.cla()
if hasattr(planning_problem.goal.state_list[0], "time_step"):
target_time_string = "Target-time: %.1f s - %.1f s" % (
planning_problem.goal.state_list[0].time_step.start * scenario.dt,
planning_problem.goal.state_list[0].time_step.end * scenario.dt,
)
else:
target_time_string = "No target-time"
ax1.set(
title=(
str(scenario.benchmark_id)
+ ": "
+ success_or_not
+ "\n\nTime: "
+ str(round(j * scenario.dt, 1))
+ " s\n"
+ target_time_string
)
)
ax1.set_aspect("equal")
ax1.set_xlabel(r"$x$ in m")
ax1.set_ylabel(r"$y$ in m")
# draw all obstacles
draw_object(
obj=scenario,
ax=ax1,
plot_limits=plot_limits,
draw_params={"time_begin": int(j / (scenario.dt * fps_available))},
)
# draw the planning problme
if planning_problem is not None:
draw_object(
obj=planning_problem,
ax=ax1,
plot_limits=plot_limits,
draw_params={"time_begin": int(j / (scenario.dt * fps_available))},
)
# draw the ego vehicle in green
# and put the ego vehicle in the center of the plot
if marked_vehicles is not None:
for marked_vehicle in marked_vehicles:
if marked_vehicle is not None:
draw_object(
obj=scenario.obstacle_by_id(marked_vehicle),
ax=ax1,
plot_limits=plot_limits,
draw_params={
"time_begin": int(j / (scenario.dt * fps_available)),
"facecolor": "g",
},
)
if animation_area is not None:
# align ego position to the center
ego_vehicle = scenario.obstacle_by_id(marked_vehicle)
if j == 0:
ego_vehicle_pos = ego_vehicle.initial_state.position
else:
ego_vehicle_pos = ego_vehicle.prediction.occupancy_set[
j - 1
].shape.center
ax1.set(
xlim=(
ego_vehicle_pos[0] - animation_area,
ego_vehicle_pos[0] + animation_area,
)
)
ax1.set(
ylim=(
ego_vehicle_pos[1] - animation_area,
ego_vehicle_pos[1] + animation_area,
)
)
# velocity subplot
ax2.cla()
ax2.set(title="Velocity")
ax2.set(ylabel=r"$v$ in m/s")
ax2.set(xlabel=r"$t$ in s")
# visualize the given goal velocity in the planning problem
if hasattr(planning_problem.goal.state_list[0], "velocity"):
v_min = planning_problem.goal.state_list[0].velocity.start
v_max = planning_problem.goal.state_list[0].velocity.end
if hasattr(planning_problem.goal.state_list[0], "time_step"):
ts_min = planning_problem.goal.state_list[0].time_step.start
ts_max = planning_problem.goal.state_list[0].time_step.end
ax2.plot(
[ts_min, ts_max, ts_max, ts_min, ts_min],
[v_min, v_min, v_max, v_max, v_min],
color="g",
label="goal area",
)
else:
ax2.plot([t[0], t[-1]], [v_min, v_min], color="g")
ax2.plot(
[t[0], t[-1]], [v_max, v_max], color="g", label="goal area"
)
ax2.legend()
ax2.plot(t, v)
ax2.scatter(j, v[j])
# acceleration subplot
ax3.cla()
ax3.set(title="Acceleration")
ax3.set(ylabel=r"$a$ in m/s²")
ax3.set(xlabel=r"$t$ in s")
# visualize the given goal acceleration in the planning problem
if hasattr(planning_problem.goal.state_list[0], "acceleration"):
a_min = planning_problem.goal.state_list[0].acceleration.start
a_max = planning_problem.goal.state_list[0].acceleration.end
if hasattr(planning_problem.goal.state_list[0], "time_step"):
ts_min = planning_problem.goal.state_list[0].time_step.start
ts_max = planning_problem.goal.state_list[0].time_step.end
ax3.plot(
[ts_min, ts_max, ts_max, ts_min, ts_min],
[a_min, a_min, a_max, a_max, a_min],
color="g",
label="goal area",
)
else:
ax3.plot([t[0], t[-1]], [a_min, a_min], color="g")
ax3.plot(
[t[0], t[-1]], [a_max, a_max], color="g", label="goal area"
)
ax3.legend()
ax3.plot(t, a)
ax3.scatter(j, a[j])
# orientation subplot
ax4.cla()
ax4.set(title="Orientation")
ax4.set(ylabel=r"$\psi$ in rad")
ax4.set(xlabel=r"$t$ in s")
# visualize the given goal orientation in the planning problem
if hasattr(planning_problem.goal.state_list[0], "orientation"):
yaw_min = planning_problem.goal.state_list[0].orientation.start
yaw_max = planning_problem.goal.state_list[0].orientation.end
if hasattr(planning_problem.goal.state_list[0], "time_step"):
ts_min = planning_problem.goal.state_list[0].time_step.start
ts_max = planning_problem.goal.state_list[0].time_step.end
ax4.plot(
[ts_min, ts_max, ts_max, ts_min, ts_min],
[yaw_min, yaw_min, yaw_max, yaw_max, yaw_min],
color="g",
label="goal area",
)
else:
ax4.plot([t[0], t[-1]], [yaw_min, yaw_min], color="g")
ax4.plot(
[t[0], t[-1]],
[yaw_max, yaw_max],
color="g",
label="goal area",
)
ax4.legend()
ax4.plot(t, yaw)
ax4.scatter(j, yaw[j])
plt.close()
# create the figure
fig = plt.figure(constrained_layout=False, figsize=(22, 15))
# set the font size
plt.rcParams.update({"font.size": 25})
# add a gridspec for the subplots
gs = fig.add_gridspec(3, 11, left=0.05, top=0.9, right=0.95, wspace=0.3, hspace=0.5)
ax1 = fig.add_subplot(gs[0:2, :])
ax2 = fig.add_subplot(gs[2, 0:3])
ax3 = fig.add_subplot(gs[2, 4:7])
ax4 = fig.add_subplot(gs[2, 8:11])
with exec_timer.time_with_cm("animate create animation"):
anim = animation.FuncAnimation(
fig=fig,
func=animate,
frames=frames,
interval=1 / fps_available * 1000,
repeat=False,
repeat_delay=1000,
blit=False,
)
# save the animation
with exec_timer.time_with_cm("animate save"):
if save_animation:
writergif = animation.PillowWriter(fps=fps_available)
anim.save(
animation_directory + scenario.benchmark_id + ".gif", writer=writergif
)
return anim
def draw_contingent_trajectories(
scenario,
time_step: int,
marked_vehicle: [int] = None,
planning_problem=None,
traj=None,
predictions: dict = None,
visible_area=None,
animation_area: float = 40.0,
global_path: np.ndarray = None,
global_path_after_goal: np.ndarray = None,
driven_traj=None,
ax=None,
picker=False,
show_label=False,
live=True,
valid_traj=None,
best_traj=None,
open_loop=False,
):
if live:
ax = draw_scenario(
scenario,
time_step,
marked_vehicle,
planning_problem,
traj,
visible_area,
animation_area,
global_path,
global_path_after_goal,
driven_traj,
ax,
picker,
show_label,
)
# Draw all possible trajectories with their costs as colors
if valid_traj is not None and len(valid_traj) != 0:
# x and y axis description
ax.set_xlabel("x[m]")
ax.set_ylabel("y[m]")
# align ego position to the center
ax.set_xlim(
valid_traj[0]['shared_plan'].x[0] - animation_area / 6,
valid_traj[0]['shared_plan'].x[0] + animation_area - 15
)
'''
ax.set_ylim(
valid_traj[0]['shared_plan'].y[0] - animation_area / 2,
valid_traj[0]['shared_plan'].y[0]
)
'''
ax.set_ylim(
-10.8, 3.6
)
# best trajectory
if len(valid_traj) > 0:
best_shared_trajectory = valid_traj[0]['shared_plan']
else:
best_shared_trajectory = best_traj[1]['shared_plan']
# if time_step == 0 or open_loop is False:
# if open_loop is True:
# x and y axis description
colorset = ['tab:blue', 'tab:orange', 'tab:green', 'tab:red', 'tab:purple', 'tab:brown', 'tab:pink', 'tab:gray',
'tab:olive', 'tab:cyan', 'y', 'm', 'c', 'g']
ax.plot(
best_shared_trajectory.x,
-best_shared_trajectory.y,
alpha=1.0,
color="blue",
zorder=25,
label="Best trajectory",
picker=picker,
)
keys_list = list(valid_traj[0])
j = 1
for key in keys_list[1:-1]:
ax.plot(
valid_traj[0][key].x,
-valid_traj[0][key].y,
alpha=1.0,
color=colorset[j],
zorder=25,
label="Best trajectory",
picker=picker,
)
j += 1
'''
ax.plot(
best_traj_mode_2.x,
best_traj_mode_2.y,
alpha=1.0,
color="yellow",
zorder=25,
lw=3.0,
label="Best trajectory",
picker=picker,
)
ax.plot(
best_traj_mode_1.x,
best_traj_mode_1.y,
alpha=1.0,
color="blue",
zorder=25,
lw=3.0,
label="Best trajectory",
picker=picker,
)
'''
# draw predictions
prediction_plot_list = list(predictions.values())[:10]
fut_pos_list = [
prediction_plot_list[i]["pos_list"][:20][:]
for i in range(len(prediction_plot_list))
]
for i in range(len(fut_pos_list[0])):
ax.plot(fut_pos_list[0][i][:, 0], -fut_pos_list[0][i][:, 1], alpha=0.5,
color='tab:gray',
lw=0.5,
zorder=25,
marker='o',
markersize=2,
picker=picker, )
'''
if predictions is not None:
draw_uncertain_predictions(predictions, ax)
'''
# show the figure until the next one ins ready
# plt.savefig(str(i).zfill(4) + ".png")
# i += 1
plt.pause(0.000001)
def draw_all_plans(
scenario,
time_step: int,
marked_vehicle: [int] = None,
planning_problem=None,
traj=None,
predictions: dict = None,
visible_area=None,
animation_area: float = 40.0,
global_path: np.ndarray = None,
global_path_after_goal: np.ndarray = None,
driven_traj=None,
ax=None,
picker=False,
show_label=False,
live=True,
valid_traj=None,
best_traj=None,
open_loop=False,
):
if live:
ax = draw_scenario(
scenario,
time_step,
marked_vehicle,
planning_problem,
traj,
visible_area,
animation_area,
global_path,
global_path_after_goal,
driven_traj,
ax,
picker,
show_label,
)
# Draw all possible trajectories with their costs as colors
if valid_traj is not None and len(valid_traj) != 0:
# x and y axis description
ax.set_xlabel("x[m]")
ax.set_ylabel("y[m]")
# align ego position to the center
ax.set_xlim(
valid_traj[0]['shared_plan'].x[0] - animation_area / 6,
valid_traj[0]['shared_plan'].x[0] + animation_area - 15
)
ax.set_ylim(
-10.8, 3.6
)
# best trajectory
if len(valid_traj) > 0:
best_shared_trajectory = valid_traj[0]['shared_plan']
else:
best_shared_trajectory = best_traj[1]['shared_plan']
colorset = ['tab:blue', 'tab:orange', 'tab:green', 'tab:red', 'tab:purple', 'tab:brown', 'tab:pink', 'tab:gray',
'tab:olive', 'tab:cyan', 'y', 'm', 'c', 'g']
colorset = ['tab:pink', 'tab:blue', 'tab:purple', 'tab:olive', 'm', 'tab:cyan']
j = 0
for p in reversed(valid_traj):
ax.plot(p['shared_plan'].x, -p['shared_plan'].y, alpha=0.02, color='k', zorder=25, picker=picker)
j = j + 1
if j == len(colorset):
j = 0
for i in range(len(valid_traj)):
keys_list = list(valid_traj[i])
j = 1
for key in keys_list[1:-1]:
if abs(valid_traj[i][key].d[-1] + 3.6) < 0.1:
j = 0
elif abs(valid_traj[i][key].d[-1] + 2.88) < 0.1:
j = 1
elif abs(valid_traj[i][key].d[-1] + 2.16) < 0.1:
j = 2
elif abs(valid_traj[i][key].d[-1] + 1.44) < 0.1:
j = 3
elif abs(valid_traj[i][key].d[-1] + 0.72) < 0.1:
j = 4
elif abs(valid_traj[i][key].d[-1]) < 0.1:
j = 5
ax.plot(
valid_traj[i][key].x,
-valid_traj[i][key].y,
alpha=0.02,
color=colorset[j],
zorder=25,
label="Best trajectory",
picker=picker,
)
j += 1
if j == len(colorset):
j = 0
# plot best trajectory
ax.plot(best_traj[0]['shared_plan'].x, -best_traj[0]['shared_plan'].y, alpha=1.0, linewidth=3.0, color='tab:blue',
zorder=25, picker=picker)
keys_list = list(best_traj[0])
for key in keys_list[1:-1]:
ax.plot(
best_traj[0][key].x,
-best_traj[0][key].y,
alpha=1.0,
color='tab:blue',
linewidth=1.5,
zorder=25,
label="Best trajectory",
picker=picker,
)
j += 1
# draw predictions
prediction_plot_list = list(predictions.values())[:10]
fut_pos_list = [
prediction_plot_list[i]["pos_list"][:20][:]
for i in range(len(prediction_plot_list))
]
for i in range(len(fut_pos_list[0])):
ax.plot(fut_pos_list[0][i][:, 0], -fut_pos_list[0][i][:, 1], alpha=0.5,
color='tab:gray',
lw=0.5,
zorder=25,
marker='o',
markersize=2,
picker=picker, )
'''
if predictions is not None:
draw_uncertain_predictions(predictions, ax)
'''
# show the figure until the next one ins ready
# plt.savefig(str(i).zfill(4) + ".png")
# i += 1
plt.pause(0.000001)
def draw_all_contingent_trajectories(
scenario,
time_step: int,
marked_vehicle: [int] = None,
planning_problem=None,
traj=None,
predictions: dict = None,
visible_area=None,
animation_area: float = 40.0,
global_path: np.ndarray = None,
global_path_after_goal: np.ndarray = None,
driven_traj=None,
ax=None,
picker=False,
show_label=False,
live=True,
valid_traj=None,
best_traj=None,
open_loop=False,
):
if live:
ax = draw_scenario(
scenario,
time_step,
marked_vehicle,
planning_problem,
traj,
visible_area,
animation_area,
global_path,
global_path_after_goal,
driven_traj,
ax,
picker,
show_label,
)
# Draw all possible trajectories with their costs as colors
if valid_traj is not None and len(valid_traj) != 0:
# x and y axis description
ax.set_xlabel("x[m]")
ax.set_ylabel("y[m]")
# align ego position to the center
ax.set_xlim(
valid_traj[0]['shared_plan'].x[0] - animation_area / 6,
valid_traj[0]['shared_plan'].x[0] + animation_area - 15
)
ax.set_ylim(
-10.8, 3.6
)
# mormalize the costs of the trajectories to map colors to them
norm = matplotlib.colors.Normalize(
vmin=min([valid_traj[i]['cost'] for i in range(len(valid_traj))]),
vmax=max([valid_traj[i]['cost'] for i in range(len(valid_traj))]),
clip=True,
)
mapper = cm.ScalarMappable(norm=norm, cmap=green_to_red_colormap())
# best trajectory
if len(valid_traj) > 0:
best_shared_trajectory = valid_traj[0]['shared_plan']
else:
best_shared_trajectory = best_traj[1]['shared_plan']
colorset = ['tab:blue', 'tab:orange', 'tab:green', 'tab:red', 'tab:purple', 'tab:brown', 'tab:pink', 'tab:gray',
'tab:olive', 'tab:cyan', 'y', 'm', 'c', 'g']
j = 0
for p in reversed(valid_traj):
color = mapper.to_rgba(p['cost'])
ax.plot(p['shared_plan'].x, -p['shared_plan'].y, alpha=0.15, color=colorset[j], zorder=25, picker=picker)
j = j + 1
if j == len(colorset):
j = 0
for i in range(len(valid_traj)):
keys_list = list(valid_traj[i])
j = 1
for key in keys_list[1:-1]:
ax.plot(
valid_traj[i][key].x,
-valid_traj[i][key].y,
alpha=0.15,
color=colorset[j],
zorder=25,
label="Best trajectory",
picker=picker,
)
j += 1
# plot best trajectory
ax.plot(valid_traj[0]['shared_plan'].x, -valid_traj[0]['shared_plan'].y, alpha=1.0, linewidth=3.0, color='tab:blue',
zorder=25, picker=picker)
keys_list = list(valid_traj[0])
for key in keys_list[1:-1]:
ax.plot(
valid_traj[0][key].x,
-valid_traj[0][key].y,
alpha=1.0,
color='tab:blue',
linewidth=1.5,
zorder=25,
label="Best trajectory",
picker=picker,
)
j += 1
# draw predictions
prediction_plot_list = list(predictions.values())[:10]
fut_pos_list = [
prediction_plot_list[i]["pos_list"][:20][:]
for i in range(len(prediction_plot_list))
]
for i in range(len(fut_pos_list[0])):
ax.plot(fut_pos_list[0][i][:, 0], -fut_pos_list[0][i][:, 1], alpha=0.5,
color='tab:gray',
lw=0.5,
zorder=25,
marker='o',
markersize=2,
picker=picker, )
'''
if predictions is not None:
draw_uncertain_predictions(predictions, ax)
'''
# show the figure until the next one ins ready
# plt.savefig(str(i).zfill(4) + ".png")
# i += 1
plt.pause(0.000001)
def draw_frenet_trajectories(
scenario,
time_step: int,
marked_vehicle: [int] = None,
planning_problem=None,
traj=None,
all_traj=None,
predictions: dict = None,
visible_area=None,
animation_area: float = 40.0,
global_path: np.ndarray = None,
global_path_after_goal: np.ndarray = None,
driven_traj=None,
ax=None,
picker=False,
show_label=False,
live=True,
valid_traj=None,
invalid_traj=None,
best_traj=None,
open_loop=False,
):
"""
Plot all frenét trajectories.
Args:
scenario (Scenario): Considered Scenario.
time_step (int): Current time step.
marked_vehicle ([int]): IDs of the marked vehicles. Defaults to None.
planning_problem (PlanningProblem): Considered planning problem. Defaults to None.
traj (FrenetTrajectory): The best trajectory of all frenét trajectories. Defaults to None.
all_traj ([FrenetTrajectory]): All frenét trajectories. Defaults to None.
fut_pos_list (np.ndarray): Future positions of the vehicles. Defaults to None.
visible_area (shapely.Polygon): Polygon of the visible area. Defaults to None.
animation_area (float): Area that should be shown. Defaults to 40.0.
global_path (np.ndarray): Global path for the planning problem. Defaults to None.
global_path_after_goal (np.ndarray): Global path for the planning problem after reaching the goal. Defaults to None.
driven_traj ([States]): Already driven trajectory of the ego vehicle. Defaults to None.
save_fig (bool): True if the figure should be saved. Defaults to False.
:param ax:
"""
if live:
ax = draw_scenario(
scenario,
time_step,
marked_vehicle,
planning_problem,
traj,
visible_area,
animation_area,
global_path,
global_path_after_goal,
driven_traj,
ax,
picker,
show_label,
)
# Draw all possible trajectories with their costs as colors
if all_traj is not None and len(all_traj) != 0:
# x and y axis description
ax.set_xlabel("x in m")
ax.set_ylabel("y in m")
# align ego position to the center
ax.set_xlim(
all_traj[0].x[0] - animation_area, all_traj[0].x[0] + animation_area
)
ax.set_ylim(
all_traj[0].y[0] - animation_area / 2, all_traj[0].y[0] + animation_area / 2
)
# normalize the costs of the trajectories to map colors to them
norm = matplotlib.colors.Normalize(
vmin=min([all_traj[i].cost for i in range(len(all_traj))]),
vmax=max([all_traj[i].cost for i in range(len(all_traj))]),
clip=True,
)
mapper = cm.ScalarMappable(norm=norm, cmap=green_to_red_colormap())
# first plot all invalid trajectories
'''
for p in all_traj:
if p.valid_level < 1:
ax.plot(
p.x,
p.y,
alpha=0.4,
color=(0.7, 0.7, 0.7),
zorder=19,
picker=picker,
)
elif p.valid_level < 10:
ax.plot(
p.x,
p.y,
alpha=0.6,
color=(0.3, 0.3, 0.7),
zorder=20,
picker=picker,
)
# then plot all valid trajectories
for p in reversed(all_traj):
if p.valid_level >= 10:
color = mapper.to_rgba(p.cost)
ax.plot(p.x, p.y, alpha=1.0, color=color, zorder=20, picker=picker)
'''
# best trajectory
if len(valid_traj) > 0:
best_trajectory = valid_traj[0]
elif len(invalid_traj) > 0:
best_trajectory = invalid_traj[0]
if time_step == 0 or open_loop == False:
ax.plot(
best_trajectory.x,
best_trajectory.y,
alpha=1.0,
color="green",
zorder=25,
lw=3.0,
label="Best trajectory",
picker=picker,
)
else:
# x and y axis description
ax.set_xlabel("x in m")
ax.set_ylabel("y in m")
# align ego position to the center
ax.set_xlim(
best_traj['x_m'][time_step] - animation_area, best_traj['x_m'][time_step] + animation_area
)
ax.set_ylim(
best_traj['y_m'][time_step] - animation_area / 2, best_traj['y_m'][time_step] + animation_area / 2
)
ax.plot(
best_traj['x_m'],
best_traj['y_m'],
alpha=1.0,
color="green",
zorder=25,
lw=3.0,
label="Best trajectory",
picker=picker,
)
'''
# draw planned trajectory
if traj is not None:
ax.plot(
traj.x,
traj.y,
alpha=1.0,
color="green",
zorder=25,
lw=3.0,
label="Best trajectory",
picker=picker,
)
'''
# draw predictions
if predictions is not None:
draw_uncertain_predictions(predictions, ax)
# show the figure until the next one ins ready
# plt.savefig(str(i).zfill(4) + ".png")
# i += 1
plt.pause(0.000001)
def show_frenet_details(vehicle_params, fp_list, global_path: np.ndarray = None):
"""
Plot details about the frenét trajectories.
Args:
vehicle_params (VehicleParameters): Parameters of the ego vehicle.
fp_list ([FrenetTrajectory]): Considered frenét trajectories.
global_path (np.ndarray): Global path of the planning problem. Defaults to None
"""
# create the figure
fig = plt.figure(constrained_layout=False, figsize=(17, 10))
# set the font size
plt.rcParams.update({"font.size": 15})
# add a gridspec for the subplots
gs = fig.add_gridspec(3, 2, left=0.05, top=0.9, right=0.95, wspace=0.3, hspace=0.5)
ax1 = fig.add_subplot(gs[:, 0])
ax2 = fig.add_subplot(gs[0, 1])
ax3 = fig.add_subplot(gs[1, 1])
ax4 = fig.add_subplot(gs[2, 1])
# plot the frenét paths
for fp in fp_list:
if fp.valid >= 10:
col = "g"
else:
col = "r"
ax1.plot(fp.x, fp.y, color=col)
ax1.set_aspect("equal")
ax1.set_title("Global trajectory")
ax1.set_xlabel(r"$x$ in m")
ax1.set_ylabel(r"$y$ in m")
if global_path is not None:
ax1.plot(global_path[:, 0], global_path[:, 1], color="b")
# curvature
ax2.set_title("Curvature")
ax2.set_ylim([-0.5, 0.5])
ax2.set_ylabel(r"$\kappa$ in rad/m")
ax2.set_xlabel(r"$t$ in s")
for fp in fp_list:
ax2.plot(fp.t, fp.curv)
max_curv = []
for i in range(len(fp.t)):
max_curv_i, _ = get_max_curvature(vehicle_params=vehicle_params, v=fp.v[i])
max_curv.append(abs(max_curv_i))
ax2.plot(fp.t, max_curv, color="r")
ax2.plot(fp.t, np.multiply((-1), max_curv), color="r")
# lateral offset
ax3.set_title("Lateral offset")
ax3.set_ylabel(r"$d$ in m")
ax3.set_xlabel(r"$t$ in s")
for fp in fp_list:
ax3.plot(fp.t, fp.d)
# covered arc length
ax4.set_title("Covered arc length")
ax4.set_ylabel(r"$s$ in m")
ax4.set_xlabel(r"$t$ in s")
for fp in fp_list:
ax4.plot(fp.t, fp.s)
plt.show()
def draw_reach_sets(
traj=None,
animation_area: float = 55.0,
reach_set=None,
ax=None,
):
"""
Plot reachable sets.
Plot reachable sets of all objects except ego.
Args:
traj (FrenetTrajectory): The best trajectory of all frenét trajectories. Defaults to None.
animation_area (float): Area that should be shown. Defaults to 55.0.
ax (Axes): Plot.
"""
# draw reach sets
if reach_set is not None:
for idx in reach_set:
no_sets = len(reach_set[idx])
set_nr = 0
for reach_set_of_id in reach_set[idx]:
set_nr += 1
for reach_set_step in reach_set_of_id.keys():
polygon = Polygon(
reach_set_of_id[reach_set_step],
closed=True,
alpha=0.075,
color="blue",
fill=True,
label="reach_set "
+ str(set_nr)
+ "/"
+ str(no_sets)
+ " of ID "
+ str(idx)
+ " , step = "
+ str(reach_set_step),
zorder=25,
lw=0, # line width zero to hide seam from exterior to interior
)
ax.add_patch(polygon)
# align ego position to the center
ax.set_xlim(traj.x[0] - animation_area, traj.x[0] + animation_area)
ax.set_ylim(traj.y[0] - animation_area, traj.y[0] + animation_area)
def draw_scenario(
scenario: Scenario = None,
time_step: int = 0,
marked_vehicle=None,
planning_problem=None,
traj=None,
visible_area=None,
animation_area: float = 55.0,
global_path: np.ndarray = None,
global_path_after_goal: np.ndarray = None,
driven_traj=None,
ax=None,
picker=False,
show_label=False,
):
"""
Draw scenario.
General drawing function for scenario.
Args:
scenario (Scenario): Considered Scenario.
time_step (int): Current time step.
marked_vehicle ([int]): IDs of the marked vehicles. Defaults to None.
planning_problem (PlanningProblem): Considered planning problem. Defaults to None.
traj (FrenetTrajectory): The best trajectory of all frenét trajectories. Defaults to None.
visible_area (shapely.Polygon): Polygon of the visible area. Defaults to None.
animation_area (float): Area that should be shown. Defaults to 40.0.
global_path (np.ndarray): Global path for the planning problem. Defaults to None.
global_path_after_goal (np.ndarray): Global path for the planning problem after reaching the goal. Defaults to None.
driven_traj ([States]): Already driven trajectory of the ego vehicle. Defaults to None.
ax (Axes): Plot.
Returns:
Axes: Plot with scenario.
"""
# clear everything
global i
if ax is None:
ax = plt.subplot()
ax.cla()
# plot the scenario at the current time step
draw_object(
scenario,
draw_params={
"time_begin": time_step,
"dynamic_obstacle": {
"draw_shape": True,
"draw_bounding_box": False,
"draw_icon": False,
"show_label": show_label,
},
},
ax=ax,
)
ax.set_aspect("equal")
# draw the planning problem
if planning_problem is not None:
draw_object(planning_problem, ax=ax)
if marked_vehicle is not None:
# mark the ego vehicle
draw_object(
obj=scenario.obstacle_by_id(marked_vehicle),
draw_params={
"time_begin": time_step,
"facecolor": "g",
"dynamic_obstacle": {
"draw_shape": False,
"draw_bounding_box": False,
"draw_icon": True,
},
},
)
# Draw global path
if global_path is not None:
ax.plot(
global_path[:, 0],
global_path[:, 1],
color="blue",
zorder=20,
label="Global path",
)
if global_path_after_goal is not None:
ax.plot(
global_path_after_goal[:, 0],
global_path_after_goal[:, 1],
color="blue",
zorder=20,
linestyle="--",
)
# draw driven trajectory
if driven_traj is not None:
x = [state.position[0] for state in driven_traj]
y = [state.position[1] for state in driven_traj]
ax.plot(x, y, color="green", zorder=25, label="Driven trajectory")
# draw visible sensor area
if visible_area is not None:
if visible_area.geom_type == "MultiPolygon":
for geom in visible_area.geoms:
ax.fill(*geom.exterior.xy, "g", alpha=0.2, zorder=10)
elif visible_area.geom_type == "Polygon":
ax.fill(*visible_area.exterior.xy, "g", alpha=0.2, zorder=10)
else:
for obj in visible_area:
if obj.geom_type == "Polygon":
ax.fill(*obj.exterior.xy, "g", alpha=0.2, zorder=10)
# get the target time to show it in the title
if hasattr(planning_problem.goal.state_list[0], "time_step"):
target_time_string = "Target-time: %.1f s - %.1f s" % (
planning_problem.goal.state_list[0].time_step.start * scenario.dt,
planning_problem.goal.state_list[0].time_step.end * scenario.dt,
)
else:
target_time_string = "No target-time"
# ax.legend()
ax.set_title(
"Time: {0:.1f} s".format(time_step * scenario.dt) + " " + target_time_string
)
if (time_step == planning_problem.goal.state_list[0].time_step.start - 1):
with open("test", "wb") as fp: # Pickling
pickle.dump(driven_traj, fp)
return ax
# EOF
| 412 | 0.805141 | 1 | 0.805141 | game-dev | MEDIA | 0.535612 | game-dev | 0.966605 | 1 | 0.966605 |
Silverlan/pragma | 13,630 | core/server/include/pragma/entities/components/s_ai_component.hpp | // SPDX-FileCopyrightText: (c) 2019 Silverlan <opensource@pragma-engine.com>
// SPDX-License-Identifier: MIT
#ifndef __S_AI_COMPONENT_HPP__
#define __S_AI_COMPONENT_HPP__
#include "pragma/serverdefinitions.h"
#include "pragma/ai/ai_memory.h"
#include "pragma/ai/s_factions.h"
#include "pragma/ai/s_disposition.h"
#include "pragma/ai/ai_behavior.h"
#include "pragma/entities/components/s_entity_component.hpp"
#include <pragma/model/animation/play_animation_flags.hpp>
#include <pragma/entities/components/base_ai_component.hpp>
#include <sharedutils/util_weak_handle.hpp>
#define AI_NEXT_ENEMY_CHECK_IDLE 0.25f
#define AI_NEXT_ENEMY_CHECK_ALERT 0.1f
#define AI_LISTEN_VISIBILITY_THRESHOLD 4.f
#define AI_LISTEN_DISTANCE_THRESHOLD 100.f
class DLLSERVER NPCRelationship {
public:
NPCRelationship(const std::shared_ptr<void> &userData, int pPriority = 0) : data(userData), priority(pPriority) {}
std::shared_ptr<void> data;
int priority;
};
enum class DISPOSITION : uint32_t;
enum class NPCSTATE : int;
class AISquad;
struct DebugBehaviorTreeNode;
namespace pragma {
class SCharacterComponent;
class BaseActorComponent;
class SPlayerComponent;
enum class FPlayAnim : uint32_t;
};
class SBaseEntity;
namespace pragma {
namespace ai {
class Schedule;
class BehaviorNode;
};
struct DLLSERVER CEMemoryData : public ComponentEvent {
CEMemoryData(const ai::Memory::Fragment *memoryFragment);
virtual void PushArguments(lua_State *l) override;
const ai::Memory::Fragment *memoryFragment;
};
struct DLLSERVER CEOnNPCStateChanged : public ComponentEvent {
CEOnNPCStateChanged(NPCSTATE oldState, NPCSTATE newState);
virtual void PushArguments(lua_State *l) override;
NPCSTATE oldState;
NPCSTATE newState;
};
struct DLLSERVER CEOnTargetAcquired : public ComponentEvent {
CEOnTargetAcquired(BaseEntity *entity, float distance, bool isFirstNewTarget);
virtual void PushArguments(lua_State *l) override;
BaseEntity *entity;
float distance;
bool isFirstNewTarget;
};
struct DLLSERVER CEOnControllerActionInput : public ComponentEvent {
CEOnControllerActionInput(Action action, bool pressed);
virtual void PushArguments(lua_State *l) override;
Action action;
bool pressed;
};
struct DLLSERVER CEOnSuspiciousSoundHeared : public ComponentEvent {
CEOnSuspiciousSoundHeared(const std::shared_ptr<ALSound> &sound);
virtual void PushArguments(lua_State *l) override;
std::shared_ptr<ALSound> sound;
};
struct DLLSERVER CEOnStartControl : public ComponentEvent {
CEOnStartControl(pragma::SPlayerComponent &player);
virtual void PushArguments(lua_State *l) override;
pragma::SPlayerComponent &player;
};
struct DLLSERVER CEOnPathNodeChanged : public ComponentEvent {
CEOnPathNodeChanged(uint32_t nodeIndex);
virtual void PushArguments(lua_State *l) override;
uint32_t nodeIndex;
};
struct DLLSERVER CEOnScheduleStateChanged : public ComponentEvent {
CEOnScheduleStateChanged(const std::shared_ptr<ai::Schedule> &schedule, ai::BehaviorNode::Result result);
virtual void PushArguments(lua_State *l) override;
std::shared_ptr<ai::Schedule> schedule;
ai::BehaviorNode::Result result;
};
class DLLSERVER SAIComponent final : public BaseAIComponent, public SBaseSnapshotComponent {
public:
void _debugSendNavInfo(pragma::SPlayerComponent &pl);
void _debugSendScheduleInfo(pragma::SPlayerComponent &pl, std::shared_ptr<DebugBehaviorTreeNode> &dbgTree, std::shared_ptr<ai::Schedule> &aiSchedule, float &tLastSchedUpdate);
static std::vector<ComponentHandle<pragma::SPlayerComponent>> s_plDebugAiNav;
private:
static std::vector<SAIComponent *> s_npcs;
static FactionManager s_factionManager;
public:
static FactionManager &GetFactionManager();
public:
static unsigned int GetNPCCount();
static const std::vector<SAIComponent *> &GetAll();
static ComponentEventId EVENT_SELECT_SCHEDULE;
static ComponentEventId EVENT_SELECT_CONTROLLER_SCHEDULE;
static ComponentEventId EVENT_ON_SCHEDULE_COMPLETE;
static ComponentEventId EVENT_ON_PRIMARY_TARGET_CHANGED;
static ComponentEventId EVENT_ON_PATH_CHANGED;
static ComponentEventId EVENT_ON_NPC_STATE_CHANGED;
static ComponentEventId EVENT_ON_TARGET_VISIBILITY_LOST;
static ComponentEventId EVENT_ON_TARGET_VISIBILITY_REACQUIRED;
static ComponentEventId EVENT_ON_MEMORY_GAINED;
static ComponentEventId EVENT_ON_MEMORY_LOST;
static ComponentEventId EVENT_ON_TARGET_ACQUIRED;
static ComponentEventId EVENT_ON_SUSPICIOUS_SOUND_HEARED;
static ComponentEventId EVENT_ON_CONTROLLER_ACTION_INPUT;
static ComponentEventId EVENT_ON_START_CONTROL;
static ComponentEventId EVENT_ON_END_CONTROL;
static ComponentEventId EVENT_ON_PATH_NODE_CHANGED;
static ComponentEventId EVENT_ON_LOOK_TARGET_CHANGED;
static ComponentEventId EVENT_ON_SCHEDULE_STARTED;
static void RegisterEvents(pragma::EntityComponentManager &componentManager, TRegisterComponentEvent registerEvent);
SAIComponent(BaseEntity &ent);
virtual ~SAIComponent() override;
virtual util::EventReply HandleEvent(ComponentEventId eventId, ComponentEvent &evData) override;
const ai::Memory::Fragment *GetPrimaryTarget() const;
float GetMaxViewDistance() const;
void SetMaxViewDistance(float dist);
float GetMaxViewDotProduct() const;
float GetMaxViewAngle() const;
void SetMaxViewAngle(float ang);
virtual void Initialize() override;
virtual void OnEntitySpawn() override;
void LockAnimation(bool b);
bool IsAnimationLocked() const;
void SetSquad(std::string squadName);
std::string GetSquadName();
NPCSTATE GetNPCState() const;
void SetNPCState(NPCSTATE state);
const std::shared_ptr<AISquad> &GetSquad() const;
void SetRelationship(BaseEntity *ent, DISPOSITION disp, bool revert = true, int priority = 0);
void SetRelationship(EntityHandle &hEnt, DISPOSITION disp, bool revert = true, int priority = 0);
void SetRelationship(std::string className, DISPOSITION disp, int priority = 0);
void SetRelationship(Faction &faction, DISPOSITION disp, int priority = 0);
void ClearRelationship(BaseEntity *ent);
void ClearRelationship(EntityHandle &hEnt);
void ClearRelationship(std::string className);
void ClearRelationship(Faction &faction);
DISPOSITION GetDisposition(BaseEntity *ent, int *priority = nullptr);
DISPOSITION GetDisposition(EntityHandle &hEnt, int *priority = nullptr);
DISPOSITION GetDisposition(std::string className, int *priority = nullptr);
DISPOSITION GetDisposition(Faction &faction, int *priority = nullptr);
std::shared_ptr<ai::Schedule> GetCurrentSchedule();
void StartSchedule(std::shared_ptr<ai::Schedule> &sched);
virtual void OnTick(double tDelta) override;
ai::Memory &GetMemory();
ai::Memory::Fragment *GetMemory(BaseEntity *ent);
ai::Memory::Fragment *Memorize(BaseEntity *ent, ai::Memory::MemoryType memType);
ai::Memory::Fragment *Memorize(BaseEntity *ent, ai::Memory::MemoryType memType, const Vector3 &pos, const Vector3 &vel);
void Forget(BaseEntity *ent);
void ClearMemory();
bool IsInMemory(BaseEntity *ent);
// Returns the number of occupied memory fragments
uint32_t GetMemoryFragmentCount() const;
bool IsInViewCone(BaseEntity *ent, float *dist = nullptr);
float GetMemoryDuration();
void SetMemoryDuration(float dur);
bool CanSee() const;
void SetHearingStrength(float strength);
bool CanHear() const;
float GetHearingStrength() const;
void CancelSchedule();
virtual void OnScheduleComplete(const std::shared_ptr<ai::Schedule> &schedule, ai::BehaviorNode::Result result);
virtual void OnScheduleStarted(const std::shared_ptr<ai::Schedule> &schedule, ai::BehaviorNode::Result result);
virtual bool TurnStep(const Vector3 &target, float &turnAngle, const float *turnSpeed = nullptr) override;
using BaseAIComponent::TurnStep;
bool IsMoving() const;
bool IsAIEnabled() const;
void SetAIEnabled(bool b);
void EnableAI();
void DisableAI();
Action GetControllerActionInput() const;
bool IsControllable() const;
void SetControllable(bool b);
void StartControl(pragma::SPlayerComponent &pl);
void EndControl();
bool IsControlled() const;
pragma::SPlayerComponent *GetController() const;
bool IsEnemy(BaseEntity *ent) const;
bool TriggerScheduleInterrupt(uint32_t interruptFlags);
virtual void SendSnapshotData(NetPacket &packet, pragma::BasePlayerComponent &pl) override;
virtual void SendData(NetPacket &packet, networking::ClientRecipientFilter &rp) override;
virtual bool ShouldTransmitSnapshotData() const override { return true; }
virtual bool ShouldTransmitNetData() const override { return true; }
// Animation
struct AIAnimationInfo {
enum class AIAnimFlags : uint32_t {
None = 0u,
PlayAnimation = 1u,
PlayActivity = PlayAnimation << 1u,
FacePrimaryTarget = 1u,
FacePosition = FacePrimaryTarget << 1u,
FaceEntity = FacePosition << 1u,
PlayAsSchedule = FaceEntity << 1u,
Default = PlayAsSchedule
};
AIAnimationInfo() = default;
void SetPlayFlags(pragma::FPlayAnim flags);
pragma::FPlayAnim GetPlayFlags() const;
AIAnimFlags GetAIAnimFlags() const;
void SetPlayAsSchedule(bool playAsSchedule);
bool ShouldPlayAsSchedule() const;
void SetActivity(Activity activity) const;
void SetAnimation(int32_t animation) const;
void SetFaceTarget(bool primaryTarget);
void SetFaceTarget(const Vector3 &position);
void SetFaceTarget(BaseEntity &target);
// For internal use only
int32_t GetAnimation() const;
Activity GetActivity() const;
const Vector3 *GetFacePosition() const;
BaseEntity *GetEntityFaceTarget() const;
private:
union {
int32_t animation;
Activity activity = Activity::Invalid;
} mutable m_animation;
pragma::FPlayAnim m_flags = pragma::FPlayAnim::Default;
mutable AIAnimFlags m_aiAnimFlags = AIAnimFlags::Default;
mutable std::shared_ptr<void> m_faceTarget = nullptr;
};
bool PlayActivity(Activity act, const AIAnimationInfo &info);
bool PlayAnimation(int32_t anim, const AIAnimationInfo &info);
protected:
friend ai::BehaviorNode;
struct ControlInfo {
ControlInfo();
void Clear();
util::WeakHandle<pragma::SPlayerComponent> hController = {};
CallbackHandle hCbOnRemove = {};
CallbackHandle hCbOnKilled = {};
CallbackHandle hCbOnActionInput = {};
Action actions = Action::None;
};
struct TargetInfo {
TargetInfo(BaseEntity *_ent, float _dist) : ent(_ent), dist(_dist) {}
BaseEntity *ent = nullptr;
float dist = 0.f;
};
bool m_bAnimLocked = false;
ai::Memory m_memory;
const ai::Memory::Fragment *m_primaryTarget = nullptr;
std::shared_ptr<AISquad> m_squad = nullptr;
NPCSTATE m_npcState = {};
float m_maxViewDist = 8192.f;
float m_maxViewAngle = 0.f;
float m_maxViewDot = 0.f;
float m_memoryDuration = 60.f;
float m_tNextEnemyCheck = 0.f;
float m_tNextListenCheck = 0.f;
float m_hearingStrength = 0.f;
bool m_bAiEnabled = true;
bool m_bControllable = true;
ControlInfo m_controlInfo = {};
DISPOSITION GetDefaultDisposition();
std::shared_ptr<ai::Schedule> m_schedule = nullptr;
Vector3 m_posMove = {0, 0, 0};
std::array<std::vector<std::shared_ptr<NPCRelationship>>, umath::to_integral(DISPOSITION::COUNT)> m_classRelationships;
std::array<std::vector<std::shared_ptr<NPCRelationship>>, umath::to_integral(DISPOSITION::COUNT)> m_entityRelationships;
std::array<std::vector<std::shared_ptr<NPCRelationship>>, umath::to_integral(DISPOSITION::COUNT)> m_factionRelationships;
void ClearRelationships();
virtual void OnRemove() override;
virtual void RunSchedule();
void UpdateMemory();
void SelectEnemies();
void Listen(std::vector<TargetInfo> &targets);
void SelectPrimaryTarget();
void OnPrePhysicsSimulate();
virtual void InitializeLuaObject(lua_State *l) override;
virtual void OnEntityComponentAdded(BaseEntityComponent &component) override;
virtual void OnPrimaryTargetChanged(const ai::Memory::Fragment *memFragment);
virtual void OnPathChanged() override;
virtual void SelectSchedule();
virtual void SelectControllerSchedule();
virtual void OnNPCStateChanged(NPCSTATE oldState, NPCSTATE newState);
virtual void OnTargetVisibilityLost(const ai::Memory::Fragment &memFragment);
virtual void OnTargetVisibilityReacquired(const ai::Memory::Fragment &memFragment);
virtual void OnMemoryGained(const ai::Memory::Fragment &memFragment);
virtual void OnMemoryLost(const ai::Memory::Fragment &memFragment);
virtual void OnTargetAcquired(BaseEntity *ent, float dist, bool bFirst);
virtual bool OnSuspiciousSoundHeared(std::shared_ptr<ALSound> &snd);
virtual void OnControllerActionInput(Action action, bool b);
virtual void OnStartControl(pragma::SPlayerComponent &pl);
virtual void OnEndControl();
virtual void OnPathNodeChanged(uint32_t nodeIdx) override;
virtual void OnLookTargetChanged() override;
virtual bool IsObstruction(const BaseEntity &ent) const override;
virtual void UpdateMovementProperties(MovementComponent &movementC) override;
void OnTakenDamage(DamageInfo &info, unsigned short oldHealth, unsigned short newHealth);
void OnTakeDamage(DamageInfo &info);
void MaintainAnimationMovement(const Vector3 &disp);
bool OnInput(std::string input, BaseEntity *activator, BaseEntity *caller, const std::string &data);
void OnKilled(DamageInfo *damageInfo = nullptr);
bool HasCharacterNoTargetEnabled(const BaseEntity &ent) const;
// Animation
bool PlayAnimation(const AIAnimationInfo &info);
bool m_bSkipHandling = false;
};
};
REGISTER_BASIC_BITWISE_OPERATORS(pragma::SAIComponent::AIAnimationInfo::AIAnimFlags)
#endif
| 412 | 0.896824 | 1 | 0.896824 | game-dev | MEDIA | 0.945773 | game-dev | 0.538799 | 1 | 0.538799 |
MaartenKok8/PneumaticCraft | 3,382 | src/pneumaticCraft/common/inventory/ContainerThermopneumaticProcessingPlant.java | package pneumaticCraft.common.inventory;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
import pneumaticCraft.common.item.Itemss;
import pneumaticCraft.common.tileentity.TileEntityThermopneumaticProcessingPlant;
public class ContainerThermopneumaticProcessingPlant extends
ContainerPneumaticBase<TileEntityThermopneumaticProcessingPlant>{
public ContainerThermopneumaticProcessingPlant(InventoryPlayer inventoryPlayer,
TileEntityThermopneumaticProcessingPlant te){
super(te);
for(int i = 0; i < 4; i++)
addSlotToContainer(new SlotUpgrade(te, i, 80 + 18 * i, 93));
addSlotToContainer(new Slot(te, 4, 46, 14));
// Add the player's inventory slots to the container
for(int inventoryRowIndex = 0; inventoryRowIndex < 3; ++inventoryRowIndex) {
for(int inventoryColumnIndex = 0; inventoryColumnIndex < 9; ++inventoryColumnIndex) {
addSlotToContainer(new Slot(inventoryPlayer, inventoryColumnIndex + inventoryRowIndex * 9 + 9, 8 + inventoryColumnIndex * 18, 115 + inventoryRowIndex * 18));
}
}
// Add the player's action bar slots to the container
for(int actionBarSlotIndex = 0; actionBarSlotIndex < 9; ++actionBarSlotIndex) {
addSlotToContainer(new Slot(inventoryPlayer, actionBarSlotIndex, 8 + actionBarSlotIndex * 18, 173));
}
}
@Override
public boolean canInteractWith(EntityPlayer player){
return te.isUseableByPlayer(player);
//return te.isGuiUseableByPlayer(player);
}
/**
* @param itemStack
* ItemStack to merge into inventory
* @param start
* minimum slot to attempt fill
* @param end
* maximum slot to attempt fill
* @param backwards
* go backwards
* @return true if stacks merged successfully public boolean
* mergeItemStack(itemStack, start, end, backwards)
*/
@Override
public ItemStack transferStackInSlot(EntityPlayer par1EntityPlayer, int par2){
ItemStack var3 = null;
Slot var4 = (Slot)inventorySlots.get(par2);
if(var4 != null && var4.getHasStack()) {
ItemStack var5 = var4.getStack();
var3 = var5.copy();
if(par2 < 5) {
if(!mergeItemStack(var5, 5, 41, false)) return null;
var4.onSlotChange(var5, var3);
} else {
if(var5.getItem() == Itemss.machineUpgrade) {
if(!mergeItemStack(var5, 0, 4, false)) return null;
} else {
if(!mergeItemStack(var5, 4, 5, false)) return null;
}
var4.onSlotChange(var5, var3);
}
if(var5.stackSize == 0) {
var4.putStack((ItemStack)null);
} else {
var4.onSlotChanged();
}
if(var5.stackSize == var3.stackSize) return null;
var4.onPickupFromSlot(par1EntityPlayer, var5);
}
return var3;
}
@Override
public void onContainerClosed(EntityPlayer par1EntityPlayer){
super.onContainerClosed(par1EntityPlayer);
// te.closeGUI();
}
}
| 412 | 0.837268 | 1 | 0.837268 | game-dev | MEDIA | 0.997007 | game-dev | 0.971196 | 1 | 0.971196 |
gscept/nebula-trifid | 6,234 | code/extlibs/bullet/bullet/src/BulletCollision/BroadphaseCollision/btDbvtBroadphase.h | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
///btDbvtBroadphase implementation by Nathanael Presson
#ifndef BT_DBVT_BROADPHASE_H
#define BT_DBVT_BROADPHASE_H
#include "BulletCollision/BroadphaseCollision/btDbvt.h"
#include "BulletCollision/BroadphaseCollision/btOverlappingPairCache.h"
//
// Compile time config
//
#define DBVT_BP_PROFILE 0
//#define DBVT_BP_SORTPAIRS 1
#define DBVT_BP_PREVENTFALSEUPDATE 0
#define DBVT_BP_ACCURATESLEEPING 0
#define DBVT_BP_ENABLE_BENCHMARK 0
#define DBVT_BP_MARGIN (btScalar)0.05
#if DBVT_BP_PROFILE
#define DBVT_BP_PROFILING_RATE 256
#include "LinearMath/btQuickprof.h"
#endif
//
// btDbvtProxy
//
struct btDbvtProxy : btBroadphaseProxy
{
/* Fields */
//btDbvtAabbMm aabb;
btDbvtNode* leaf;
btDbvtProxy* links[2];
int stage;
/* ctor */
btDbvtProxy(const btVector3& aabbMin,const btVector3& aabbMax,void* userPtr,short int collisionFilterGroup, short int collisionFilterMask) :
btBroadphaseProxy(aabbMin,aabbMax,userPtr,collisionFilterGroup,collisionFilterMask)
{
links[0]=links[1]=0;
}
};
typedef btAlignedObjectArray<btDbvtProxy*> btDbvtProxyArray;
///The btDbvtBroadphase implements a broadphase using two dynamic AABB bounding volume hierarchies/trees (see btDbvt).
///One tree is used for static/non-moving objects, and another tree is used for dynamic objects. Objects can move from one tree to the other.
///This is a very fast broadphase, especially for very dynamic worlds where many objects are moving. Its insert/add and remove of objects is generally faster than the sweep and prune broadphases btAxisSweep3 and bt32BitAxisSweep3.
struct btDbvtBroadphase : btBroadphaseInterface
{
/* Config */
enum {
DYNAMIC_SET = 0, /* Dynamic set index */
FIXED_SET = 1, /* Fixed set index */
STAGECOUNT = 2 /* Number of stages */
};
/* Fields */
btDbvt m_sets[2]; // Dbvt sets
btDbvtProxy* m_stageRoots[STAGECOUNT+1]; // Stages list
btOverlappingPairCache* m_paircache; // Pair cache
btScalar m_prediction; // Velocity prediction
int m_stageCurrent; // Current stage
int m_fupdates; // % of fixed updates per frame
int m_dupdates; // % of dynamic updates per frame
int m_cupdates; // % of cleanup updates per frame
int m_newpairs; // Number of pairs created
int m_fixedleft; // Fixed optimization left
unsigned m_updates_call; // Number of updates call
unsigned m_updates_done; // Number of updates done
btScalar m_updates_ratio; // m_updates_done/m_updates_call
int m_pid; // Parse id
int m_cid; // Cleanup index
int m_gid; // Gen id
bool m_releasepaircache; // Release pair cache on delete
bool m_deferedcollide; // Defere dynamic/static collision to collide call
bool m_needcleanup; // Need to run cleanup?
#if DBVT_BP_PROFILE
btClock m_clock;
struct {
unsigned long m_total;
unsigned long m_ddcollide;
unsigned long m_fdcollide;
unsigned long m_cleanup;
unsigned long m_jobcount;
} m_profiling;
#endif
/* Methods */
btDbvtBroadphase(btOverlappingPairCache* paircache=0);
~btDbvtBroadphase();
void collide(btDispatcher* dispatcher);
void optimize();
/* btBroadphaseInterface Implementation */
btBroadphaseProxy* createProxy(const btVector3& aabbMin,const btVector3& aabbMax,int shapeType,void* userPtr,short int collisionFilterGroup,short int collisionFilterMask,btDispatcher* dispatcher,void* multiSapProxy);
virtual void destroyProxy(btBroadphaseProxy* proxy,btDispatcher* dispatcher);
virtual void setAabb(btBroadphaseProxy* proxy,const btVector3& aabbMin,const btVector3& aabbMax,btDispatcher* dispatcher);
virtual void rayTest(const btVector3& rayFrom,const btVector3& rayTo, btBroadphaseRayCallback& rayCallback, const btVector3& aabbMin=btVector3(0,0,0), const btVector3& aabbMax = btVector3(0,0,0));
virtual void aabbTest(const btVector3& aabbMin, const btVector3& aabbMax, btBroadphaseAabbCallback& callback);
virtual void getAabb(btBroadphaseProxy* proxy,btVector3& aabbMin, btVector3& aabbMax ) const;
virtual void calculateOverlappingPairs(btDispatcher* dispatcher);
virtual btOverlappingPairCache* getOverlappingPairCache();
virtual const btOverlappingPairCache* getOverlappingPairCache() const;
virtual void getBroadphaseAabb(btVector3& aabbMin,btVector3& aabbMax) const;
virtual void printStats();
///reset broadphase internal structures, to ensure determinism/reproducability
virtual void resetPool(btDispatcher* dispatcher);
void performDeferredRemoval(btDispatcher* dispatcher);
void setVelocityPrediction(btScalar prediction)
{
m_prediction = prediction;
}
btScalar getVelocityPrediction() const
{
return m_prediction;
}
///this setAabbForceUpdate is similar to setAabb but always forces the aabb update.
///it is not part of the btBroadphaseInterface but specific to btDbvtBroadphase.
///it bypasses certain optimizations that prevent aabb updates (when the aabb shrinks), see
///http://code.google.com/p/bullet/issues/detail?id=223
void setAabbForceUpdate( btBroadphaseProxy* absproxy,const btVector3& aabbMin,const btVector3& aabbMax,btDispatcher* /*dispatcher*/);
static void benchmark(btBroadphaseInterface*);
};
#endif
| 412 | 0.973787 | 1 | 0.973787 | game-dev | MEDIA | 0.972359 | game-dev | 0.992029 | 1 | 0.992029 |
BloodAxe/opencv-ios-template-project | 17,788 | externalLibs/boost/include/boost/spirit/home/support/char_encoding/unicode/create_tables.cpp | /*=============================================================================
Copyright (c) 2001-2011 Joel de Guzman
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
#include <boost/config/warning_disable.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix.hpp>
#include <boost/unordered_map.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <boost/cstdint.hpp>
#include <boost/foreach.hpp>
#include <boost/array.hpp>
#include <boost/scoped_array.hpp>
#include <boost/range/iterator_range.hpp>
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <string>
#include <map>
// We place the data here. Each line comprises various fields
typedef std::vector<std::string> ucd_line;
typedef std::vector<ucd_line> ucd_vector;
typedef std::vector<ucd_line>::iterator ucd_iterator;
// spirit and phoenix using declarations
using boost::spirit::qi::parse;
using boost::spirit::qi::hex;
using boost::spirit::qi::char_;
using boost::spirit::qi::eol;
using boost::spirit::qi::rule;
using boost::spirit::qi::omit;
using boost::spirit::qi::_1;
using boost::spirit::qi::_val;
using boost::phoenix::push_back;
using boost::phoenix::ref;
// basic unsigned types
using boost::uint8_t;
using boost::uint16_t;
using boost::uint32_t;
// a char range
struct ucd_range
{
ucd_range(uint32_t start, uint32_t finish)
: start(start), finish(finish) {}
// we need this so we can use ucd_range as a multimap key
friend bool operator<(ucd_range const& a, ucd_range const& b)
{
return a.start < b.start;
}
uint32_t start;
uint32_t finish;
};
class ucd_info
{
public:
ucd_info(char const* filename)
{
std::ifstream in(filename, std::ios_base::in);
if (!in)
{
std::cerr << "Error: Could not open input file: "
<< filename << std::endl;
}
else
{
std::string data; // We will read the contents here.
in.unsetf(std::ios::skipws); // No white space skipping!
std::copy(
std::istream_iterator<char>(in),
std::istream_iterator<char>(),
std::back_inserter(data));
typedef std::string::const_iterator iterator_type;
iterator_type f = data.begin();
iterator_type l = data.end();
rule<iterator_type> endl = -('#' >> *(char_-eol)) >> eol;
rule<iterator_type, std::string()> field = *(char_-(';'|endl)) >> (';'|&endl);
rule<iterator_type, ucd_line()> line = +(field-endl) >> endl;
rule<iterator_type, std::vector<ucd_line>()> file = +(endl | line[push_back(_val, _1)]);
parse(f, l, file, info);
}
}
template <typename Array>
void collect(Array& data, int field, bool collect_properties = true) const
{
BOOST_ASSERT(!info.empty());
ucd_vector::const_iterator current = info.begin();
ucd_vector::const_iterator end = info.end();
while (current != end)
{
std::string range = (*current)[0];
boost::trim(range);
std::string::const_iterator f = range.begin();
std::string::const_iterator l = range.end();
// get the code-point range
uint32_t start;
uint32_t finish;
parse(f, l, hex[ref(start) = ref(finish) = _1] >> -(".." >> hex[ref(finish) = _1]));
// special case for UnicodeData.txt ranges:
if ((*current)[1].find("First>") != std::string::npos)
{
++current;
BOOST_ASSERT(current != end);
BOOST_ASSERT((*current)[1].find("Last>") != std::string::npos);
std::string range = (*current)[0];
boost::trim(range);
f = range.begin();
l = range.end();
parse(f, l, hex[ref(finish) = _1]);
}
std::string code;
if (field < int(current->size()))
code = (*current)[field];
boost::trim(code);
// Only collect properties we are interested in
if (collect_properties) // code for properties
{
if (!ignore_property(code))
{
for (uint32_t i = start; i <= finish; ++i)
data[i] |= map_property(code);
}
}
else // code for actual numeric values
{
for (uint32_t i = start; i <= finish; ++i)
{
if (code.empty())
{
data[i] = 0; // signal that this code maps to itself
}
else
{
f = code.begin();
l = code.end();
parse(f, l, hex, data[i]);
}
}
}
++current;
}
}
private:
static bool ignore_property(std::string const& p)
{
// We don't handle all properties
std::map<std::string, int>& pm = get_property_map();
std::map<std::string, int>::iterator i = pm.find(p);
return i == pm.end();
}
static int
map_property(std::string const& p)
{
std::map<std::string, int>& pm = get_property_map();
std::map<std::string, int>::iterator i = pm.find(p);
BOOST_ASSERT(i != pm.end());
return i->second;
}
static std::map<std::string, int>&
get_property_map()
{
// The properties we are interested in:
static std::map<std::string, int> map;
if (map.empty())
{
// General_Category
map["Lu"] = 0;
map["Ll"] = 1;
map["Lt"] = 2;
map["Lm"] = 3;
map["Lo"] = 4;
map["Mn"] = 8;
map["Me"] = 9;
map["Mc"] = 10;
map["Nd"] = 16;
map["Nl"] = 17;
map["No"] = 18;
map["Zs"] = 24;
map["Zl"] = 25;
map["Zp"] = 26;
map["Cc"] = 32;
map["Cf"] = 33;
map["Co"] = 34;
map["Cs"] = 35;
map["Cn"] = 36;
map["Pd"] = 40;
map["Ps"] = 41;
map["Pe"] = 42;
map["Pc"] = 43;
map["Po"] = 44;
map["Pi"] = 45;
map["Pf"] = 46;
map["Sm"] = 48;
map["Sc"] = 49;
map["Sk"] = 50;
map["So"] = 51;
// Derived Properties.
map["Alphabetic"] = 64;
map["Uppercase"] = 128;
map["Lowercase"] = 256;
map["White_Space"] = 512;
map["Hex_Digit"] = 1024;
map["Noncharacter_Code_Point"] = 2048;
map["Default_Ignorable_Code_Point"] = 4096;
// Script
map["Arabic"] = 0;
map["Imperial_Aramaic"] = 1;
map["Armenian"] = 2;
map["Avestan"] = 3;
map["Balinese"] = 4;
map["Bamum"] = 5;
map["Bengali"] = 6;
map["Bopomofo"] = 7;
map["Braille"] = 8;
map["Buginese"] = 9;
map["Buhid"] = 10;
map["Canadian_Aboriginal"] = 11;
map["Carian"] = 12;
map["Cham"] = 13;
map["Cherokee"] = 14;
map["Coptic"] = 15;
map["Cypriot"] = 16;
map["Cyrillic"] = 17;
map["Devanagari"] = 18;
map["Deseret"] = 19;
map["Egyptian_Hieroglyphs"] = 20;
map["Ethiopic"] = 21;
map["Georgian"] = 22;
map["Glagolitic"] = 23;
map["Gothic"] = 24;
map["Greek"] = 25;
map["Gujarati"] = 26;
map["Gurmukhi"] = 27;
map["Hangul"] = 28;
map["Han"] = 29;
map["Hanunoo"] = 30;
map["Hebrew"] = 31;
map["Hiragana"] = 32;
map["Katakana_Or_Hiragana"] = 33;
map["Old_Italic"] = 34;
map["Javanese"] = 35;
map["Kayah_Li"] = 36;
map["Katakana"] = 37;
map["Kharoshthi"] = 38;
map["Khmer"] = 39;
map["Kannada"] = 40;
map["Kaithi"] = 41;
map["Tai_Tham"] = 42;
map["Lao"] = 43;
map["Latin"] = 44;
map["Lepcha"] = 45;
map["Limbu"] = 46;
map["Linear_B"] = 47;
map["Lisu"] = 48;
map["Lycian"] = 49;
map["Lydian"] = 50;
map["Malayalam"] = 51;
map["Mongolian"] = 52;
map["Meetei_Mayek"] = 53;
map["Myanmar"] = 54;
map["Nko"] = 55;
map["Ogham"] = 56;
map["Ol_Chiki"] = 57;
map["Old_Turkic"] = 58;
map["Oriya"] = 59;
map["Osmanya"] = 60;
map["Phags_Pa"] = 61;
map["Inscriptional_Pahlavi"] = 62;
map["Phoenician"] = 63;
map["Inscriptional_Parthian"] = 64;
map["Rejang"] = 65;
map["Runic"] = 66;
map["Samaritan"] = 67;
map["Old_South_Arabian"] = 68;
map["Saurashtra"] = 69;
map["Shavian"] = 70;
map["Sinhala"] = 71;
map["Sundanese"] = 72;
map["Syloti_Nagri"] = 73;
map["Syriac"] = 74;
map["Tagbanwa"] = 75;
map["Tai_Le"] = 76;
map["New_Tai_Lue"] = 77;
map["Tamil"] = 78;
map["Tai_Viet"] = 79;
map["Telugu"] = 80;
map["Tifinagh"] = 81;
map["Tagalog"] = 82;
map["Thaana"] = 83;
map["Thai"] = 84;
map["Tibetan"] = 85;
map["Ugaritic"] = 86;
map["Vai"] = 87;
map["Old_Persian"] = 88;
map["Cuneiform"] = 89;
map["Yi"] = 90;
map["Inherited"] = 91;
map["Common"] = 92;
map["Unknown"] = 93;
}
return map;
}
ucd_vector info;
};
template <typename T, uint32_t block_size_ = 256>
class ucd_table_builder
{
public:
static uint32_t const block_size = block_size_;
static uint32_t const full_span = 0x110000;
typedef T value_type;
ucd_table_builder() : p(new T[full_span])
{
for (uint32_t i = 0; i < full_span; ++i)
p[i] = 0;
}
void collect(char const* filename, int field, bool collect_properties = true)
{
std::cout << "collecting " << filename << std::endl;
ucd_info info(filename);
info.collect(p, field, collect_properties);
}
void build(std::vector<uint8_t>& stage1, std::vector<T const*>& stage2)
{
std::cout << "building tables" << std::endl;
std::map<block_ptr, std::vector<T const*> > blocks;
for (T const* i = p.get(); i < (p.get() + full_span); i += block_size)
blocks[block_ptr(i)].push_back(i);
// Not enough bits to store the block indices.
BOOST_ASSERT(blocks.size() < (1 << (sizeof(uint8_t) * 8)));
typedef std::pair<block_ptr, std::vector<T const*> > blocks_value_type;
std::map<T const*, std::vector<T const*> > sorted_blocks;
BOOST_FOREACH(blocks_value_type const& val, blocks)
{
sorted_blocks[val.first.p] = val.second;
}
stage1.clear();
stage1.reserve(full_span / block_size);
stage1.resize(full_span / block_size);
stage2.clear();
stage2.reserve(blocks.size());
typedef std::pair<T const*, std::vector<T const*> > sorted_blocks_value_type;
BOOST_FOREACH(sorted_blocks_value_type const& val, sorted_blocks)
{
stage2.push_back(val.first);
BOOST_FOREACH(T const* val2, val.second)
{
stage1[(val2 - p.get()) / block_size] = stage2.size() - 1;
}
}
}
private:
struct block_ptr
{
block_ptr(T const* p) : p(p) {}
friend bool operator<(block_ptr a, block_ptr b)
{
return std::lexicographical_compare(
a.p, a.p + block_size, b.p, b.p + block_size);
}
T const* p;
};
boost::scoped_array<T> p;
};
template <typename Out>
void print_tab(Out& out, int tab)
{
for (int i = 0; i < tab; ++i)
out << ' ';
}
template <typename Out, typename C>
void print_table(Out& out, C const& c, bool trailing_comma, int width = 4, int group = 16)
{
int const tab = 4;
C::size_type size = c.size();
BOOST_ASSERT(size > 1);
print_tab(out, tab);
out << std::setw(width) << int(c[0]);
for (C::size_type i = 1; i < size; ++i)
{
out << ", ";
if ((i % group) == 0)
{
out << std::endl;
print_tab(out, tab);
}
out << std::setw(width) << int(c[i]);
}
if (trailing_comma)
out << ", " << std::endl;
}
template <typename Out>
void print_head(Out& out)
{
out
<< "/*=============================================================================\n"
<< " Copyright (c) 2001-2011 Joel de Guzman\n"
<< "\n"
<< " Distributed under the Boost Software License, Version 1.0. (See accompanying\n"
<< " file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n"
<< "\n"
<< " AUTOGENERATED. DO NOT EDIT!!!\n"
<< "==============================================================================*/\n"
<< "#include <boost/cstdint.hpp>\n"
<< "\n"
<< "namespace boost { namespace spirit { namespace ucd { namespace detail\n"
<< "{"
;
}
template <typename Out>
void print_tail(Out& out)
{
out
<< "\n"
<< "}}}} // namespace boost::spirit::unicode::detail\n"
;
}
char const* get_int_type_name(int size)
{
switch (size)
{
case 1: return "::boost::uint8_t";
case 2: return "::boost::uint16_t";
case 4: return "::boost::uint32_t";
case 5: return "::boost::uint64_t";
default: BOOST_ASSERT(false); return 0; // invalid size
};
}
template <typename Out, typename Builder>
void print_file(Out& out, Builder& builder, int field_width, char const* name)
{
std::cout << "Generating " << name << " tables" << std::endl;
uint32_t const block_size = Builder::block_size;
typedef typename Builder::value_type value_type;
print_head(out);
std::vector<uint8_t> stage1;
std::vector<value_type const*> stage2;
builder.build(stage1, stage2);
std::cout << "Block Size: " << block_size << std::endl;
std::cout << "Total Bytes: "
<< stage1.size()+(stage2.size()*block_size*sizeof(value_type))
<< std::endl;
out
<< "\n"
<< " static const ::boost::uint8_t " << name << "_stage1[] = {\n"
<< "\n"
;
print_table(out, stage1, false, 3);
char const* int_name = get_int_type_name(sizeof(value_type));
out
<< "\n"
<< " };"
<< "\n"
<< "\n"
<< " static const " << int_name << ' ' << name << "_stage2[] = {"
;
int block_n = 0;
for (int i = 0; i < int(stage2.size()); ++i)
{
value_type const* p = stage2[i];
bool last = (i+1 == stage2.size());
out << "\n\n // block " << block_n++ << std::endl;
print_table(out,
boost::iterator_range<value_type const*>(p, p+block_size), !last, field_width);
}
out
<< "\n"
<< " };"
<< "\n"
;
out
<< "\n"
<< " inline " << int_name << ' ' << name << "_lookup(::boost::uint32_t ch)\n"
<< " {\n"
<< " ::boost::uint32_t block_offset = " << name << "_stage1[ch / " << block_size << "] * " << block_size << ";\n"
<< " return " << name << "_stage2[block_offset + ch % " << block_size << "];\n"
<< " }\n"
;
print_tail(out);
}
int main()
{
// The category tables
{
std::ofstream out("category_table.hpp");
ucd_table_builder<uint16_t, 256> builder;
builder.collect("UnicodeData.txt", 2);
builder.collect("DerivedCoreProperties.txt", 1);
builder.collect("PropList.txt", 1);
print_file(out, builder, 4, "category");
}
// The script tables
{
std::ofstream out("script_table.hpp");
ucd_table_builder<uint8_t, 256> builder;
builder.collect("Scripts.txt", 1);
print_file(out, builder, 3, "script");
}
// The lowercase tables
{
std::ofstream out("lowercase_table.hpp");
ucd_table_builder<uint32_t, 256> builder;
builder.collect("UnicodeData.txt", 13, false);
print_file(out, builder, 6, "lowercase");
}
// The uppercase tables
{
std::ofstream out("uppercase_table.hpp");
ucd_table_builder<uint32_t, 256> builder;
builder.collect("UnicodeData.txt", 12, false);
print_file(out, builder, 6, "uppercase");
}
return 0;
}
| 412 | 0.90086 | 1 | 0.90086 | game-dev | MEDIA | 0.291803 | game-dev | 0.714927 | 1 | 0.714927 |
hojat72elect/libgdx_games | 6,585 | DriftGame/uracer-desktop/src/com/bitfire/uracer/game/logic/gametasks/trackeffects/effects/PlayerSkidMarks.java | package com.bitfire.uracer.game.logic.gametasks.trackeffects.effects;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
import com.bitfire.uracer.configuration.PhysicsUtils;
import com.bitfire.uracer.game.logic.gametasks.trackeffects.TrackEffect;
import com.bitfire.uracer.game.logic.gametasks.trackeffects.TrackEffectType;
import com.bitfire.uracer.game.player.PlayerCar;
import com.bitfire.uracer.game.rendering.GameRenderer;
import com.bitfire.uracer.resources.Art;
import com.bitfire.uracer.utils.AlgebraMath;
import com.bitfire.uracer.utils.ConvertUtils;
import org.jetbrains.annotations.NotNull;
public class PlayerSkidMarks extends TrackEffect {
private final int MaxSkidMarks;
private final float MaxParticleLifeSeconds;
private final float InvMaxParticleLifeSeconds;
private final SkidMark[] skidMarks;
private final Vector2 pos;
private final Vector2 last;
private final Vector2 ppos = new Vector2();
private int markIndex;
private int visibleSkidMarksCount;
public PlayerSkidMarks(int maxSkidMarks, float maxParticleLifeSecs) {
super(TrackEffectType.CarSkidMarks);
MaxSkidMarks = maxSkidMarks;
MaxParticleLifeSeconds = maxParticleLifeSecs;
InvMaxParticleLifeSeconds = 1f / MaxParticleLifeSeconds;
markIndex = 0;
visibleSkidMarksCount = 0;
pos = new Vector2();
last = new Vector2();
skidMarks = new SkidMark[MaxSkidMarks];
for (int i = 0; i < MaxSkidMarks; i++) {
skidMarks[i] = new SkidMark();
}
}
@Override
public void player(PlayerCar player) {
super.player(player);
if (hasPlayer) {
for (int i = 0; i < MaxSkidMarks; i++) {
skidMarks[i].setup(ConvertUtils.INSTANCE.mt2px(player.getCarModel().width), ConvertUtils.INSTANCE.mt2px(player.getCarModel().length));
}
}
}
@Override
public int getParticleCount() {
return visibleSkidMarksCount;
}
@Override
public int getMaxParticleCount() {
return MaxSkidMarks;
}
@Override
public void dispose() {
}
@Override
public void reset() {
markIndex = 0;
visibleSkidMarksCount = 0;
}
@Override
public void tick() {
if (hasPlayer) {
if (player.carState.currVelocityLenSquared >= 1 && player.driftState.driftStrength > 0.3f
&& player.carState.currSpeedFactor > 0.1f) {
ppos.x = ConvertUtils.INSTANCE.mt2px(player.getBody().getPosition().x);
ppos.y = ConvertUtils.INSTANCE.mt2px(player.getBody().getPosition().y);
tryAddDriftMark(ppos, player.state().orientation);
}
}
for (int i = 0; i < MaxSkidMarks; i++) {
SkidMark sm = skidMarks[i];
if (sm.life > 0) {
sm.life -= PhysicsUtils.Dt;
} else {
sm.life = 0;
}
}
}
@Override
public void render(@NotNull SpriteBatch batch) {
float lifeRatio;
SkidMark d;
visibleSkidMarksCount = 0;
// front drift marks
for (int i = 0; i < MaxSkidMarks; i++) {
d = skidMarks[i];
if (d.life > 0 && GameRenderer.ScreenUtils.isVisible(d.getBoundingRectangle())) {
visibleSkidMarksCount++;
lifeRatio = d.life * InvMaxParticleLifeSeconds;
d.front.setColor(1, 1, 1, d.alphaFront * lifeRatio);
d.rear.setColor(1, 1, 1, d.alphaRear * lifeRatio);
d.front.draw(batch);
d.rear.draw(batch);
}
}
// Gdx.app.log( "PlayerSkidMarks", "visibles=" + visibleSkidMarksCount );
}
private void tryAddDriftMark(Vector2 position, float orientation) {
// avoid blatant overdrawing
if ((int) position.x == (int) last.x && (int) position.y == (int) last.y) {
return;
}
int driftMarkAddIterations;
float target = PhysicsUtils.Dt;
float curr = Gdx.graphics.getDeltaTime();// deltaMean.getMean();
driftMarkAddIterations = AlgebraMath.clamp(Math.round(curr / target), 1, 3);
float theta = 1f / (float) driftMarkAddIterations;
for (int i = 0; i < driftMarkAddIterations; i++) {
pos.set(position);
pos.x = AlgebraMath.lerp(last.x, position.x, theta * i);
pos.y = AlgebraMath.lerp(last.y, position.y, theta * i);
// add front drift marks?
SkidMark drift = skidMarks[markIndex++];
if (markIndex == MaxSkidMarks) {
markIndex = 0;
}
drift.alphaFront = player.driftState.lateralForcesFront * player.driftState.driftStrength * theta;
drift.alphaRear = player.driftState.lateralForcesRear * player.driftState.driftStrength * theta;
drift.setPosition(pos);
drift.setOrientation(orientation);
drift.life = MaxParticleLifeSeconds;
}
last.set(position);
}
private class SkidMark {
public Sprite front, rear;
public float life;
public float alphaFront, alphaRear;
public SkidMark() {
front = new Sprite();
rear = new Sprite();
life = MaxParticleLifeSeconds;
}
public void setup(float carWidthPx, float carLengthPx) {
front.setRegion(Art.skidMarksFront);
front.setSize(carWidthPx, carLengthPx);
front.setOrigin(front.getWidth() / 2, front.getHeight() / 2);
front.setColor(1, 1, 1, 1);
rear.setRegion(Art.skidMarksRear);
rear.setSize(carWidthPx, carLengthPx);
rear.setOrigin(rear.getWidth() / 2, rear.getHeight() / 2 + 7); // adjust for rear axis in 3d model (pretty distant)
rear.setColor(1, 1, 1, 1);
}
public void setPosition(Vector2 pos) {
front.setPosition(pos.x - front.getOriginX(), pos.y - front.getOriginY());
rear.setPosition(pos.x - rear.getOriginX(), pos.y - rear.getOriginY());
}
public void setOrientation(float degrees) {
front.setRotation(degrees);
rear.setRotation(degrees);
}
public Rectangle getBoundingRectangle() {
return front.getBoundingRectangle();
}
}
}
| 412 | 0.9479 | 1 | 0.9479 | game-dev | MEDIA | 0.89833 | game-dev | 0.998793 | 1 | 0.998793 |
google/mechahamster | 2,582 | Assets/Hamster/Scripts/States/MeltdownMenu.cs | // Copyright 2017 Google Inc. All rights reserved.
//
// 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.
using System;
using Firebase.Crashlytics;
using UnityEngine;
using UnityEngine.UI;
namespace Hamster.States {
/// <summary>
/// The state controller for the MeltdownMenu. This menu appears
/// after the SelfDestruct button in the Settings menu has been
/// clicked a certain number of times. Once the MenuPanel
/// has faded to nothing, it will return the state to the MainMenu.
/// </summary>
public class MeltdownMenu : BaseState {
// The GameObject that will control text on the screen
private Menus.MeltdownMenuGUI meltdownGUI;
public override void Initialize() {
InitializeUI();
}
public override void Resume(StateExitValue results) {
InitializeUI();
}
private void InitializeUI() {
LogCrashlyticsException();
if (meltdownGUI == null) {
meltdownGUI = SpawnUI<Menus.MeltdownMenuGUI>(StringConstants.PrefabMeltdownMenu);
}
meltdownGUI.MenuPanel.gameObject.SetActive(true);
ShowUI();
}
public override void Suspend() {
HideUI();
}
public override StateExitValue Cleanup() {
DestroyUI();
return null;
}
public override void Update() {
if (meltdownGUI.MenuPanel.HasFadedToNothing()) {
ReturnToMainMenu();
}
}
private void ReturnToMainMenu() {
// This is currently two menu levels in,
// this is a bit hard-coded at the moment
// but being used to show a prototype
manager.PopState();
manager.PopState();
}
/// <summary>
/// Log an exception to Crashlytics.
/// </summary>
/// <exception cref="CrashlyticsCaughtException"></exception>
private void LogCrashlyticsException() {
// This is a bit odd, throwing the exception and then catching it immediately,
// but this allows crashlytics to be able to capture the stack trace.
PseudoRandomExceptionChooser.Throw("User hit the \"Self Destruct!\" button too many times.");
}
}
} | 412 | 0.864925 | 1 | 0.864925 | game-dev | MEDIA | 0.928663 | game-dev | 0.918529 | 1 | 0.918529 |
TeamLumi/opendpr | 1,569 | Assets/Scripts/Dpr/Battle/Logic/RaidBattleStatus.cs | namespace Dpr.Battle.Logic
{
public sealed class RaidBattleStatus
{
private byte m_allDeadCount;
private ushort[] m_turnCountAfterAllDead = new ushort[(int)BTL_CLIENT_ID.BTL_CLIENT_NUM];
private bool m_isPlayBtlEffectKill;
public RaidBattleStatus()
{
Initialize();
}
public void Initialize()
{
m_allDeadCount = 0;
for (int i=0; i<m_turnCountAfterAllDead.Length; i++)
m_turnCountAfterAllDead[i] = 0;
m_isPlayBtlEffectKill = false;
}
public void CopyFrom(in RaidBattleStatus src)
{
m_allDeadCount = src.m_allDeadCount;
for (int i=0; i<m_turnCountAfterAllDead.Length; i++)
m_turnCountAfterAllDead[i] = src.m_turnCountAfterAllDead[i];
m_isPlayBtlEffectKill = src.m_isPlayBtlEffectKill;
}
public byte GetAllDeadCount()
{
return m_allDeadCount;
}
// TODO
public void IncAllDeadCount() { }
// TODO
public bool IsAllDeadCountMax() { return false; }
// TODO
public ushort GetTurnCountAfterAllDead(BTL_CLIENT_ID clientID) { return 0; }
// TODO
public void IncTurnCountAfterAllDead(BTL_CLIENT_ID clientID) { }
// TODO
public void ResetTurnCountAfterAllDead(BTL_CLIENT_ID clientID) { }
// TODO
public void PlayBtlEffectKill() { }
// TODO
public bool IsPlayBtlEffectKill() { return false; }
}
} | 412 | 0.629915 | 1 | 0.629915 | game-dev | MEDIA | 0.357773 | game-dev | 0.641431 | 1 | 0.641431 |
msawczyn/EFDesigner | 4,202 | src/Testing/EF6/EF6NetCore3/Generated/Entities/ConcreteDerivedClass.generated.cs | //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Data.Entity.Spatial;
namespace Testing
{
public partial class ConcreteDerivedClass: global::Testing.AbstractBaseClass
{
partial void Init();
/// <summary>
/// Default constructor. Protected due to required properties, but present because EF needs it.
/// </summary>
protected ConcreteDerivedClass(): base()
{
Init();
}
/// <summary>
/// Replaces default constructor, since it's protected. Caller assumes responsibility for setting all required values before saving.
/// </summary>
public static ConcreteDerivedClass CreateConcreteDerivedClassUnsafe()
{
return new ConcreteDerivedClass();
}
/// <summary>
/// Public constructor with required data
/// </summary>
/// <param name="property0"></param>
public ConcreteDerivedClass(string property0)
{
if (string.IsNullOrEmpty(property0)) throw new ArgumentNullException(nameof(property0));
this.Property0 = property0;
Init();
}
/// <summary>
/// Static create function (for use in LINQ queries, etc.)
/// </summary>
/// <param name="property0"></param>
public static new ConcreteDerivedClass Create(string property0)
{
return new ConcreteDerivedClass(property0);
}
/*************************************************************************
* Properties
*************************************************************************/
/// <summary>
/// Backing field for Property1
/// </summary>
protected string _property1;
/// <summary>
/// When provided in a partial class, allows value of Property1 to be changed before setting.
/// </summary>
partial void SetProperty1(string oldValue, ref string newValue);
/// <summary>
/// When provided in a partial class, allows value of Property1 to be changed before returning.
/// </summary>
partial void GetProperty1(ref string result);
public string Property1
{
get
{
string value = _property1;
GetProperty1(ref value);
return (_property1 = value);
}
set
{
string oldValue = _property1;
SetProperty1(oldValue, ref value);
if (oldValue != value)
{
_property1 = value;
}
}
}
/// <summary>
/// Backing field for PropertyInChild
/// </summary>
protected string _propertyInChild;
/// <summary>
/// When provided in a partial class, allows value of PropertyInChild to be changed before setting.
/// </summary>
partial void SetPropertyInChild(string oldValue, ref string newValue);
/// <summary>
/// When provided in a partial class, allows value of PropertyInChild to be changed before returning.
/// </summary>
partial void GetPropertyInChild(ref string result);
public string PropertyInChild
{
get
{
string value = _propertyInChild;
GetPropertyInChild(ref value);
return (_propertyInChild = value);
}
set
{
string oldValue = _propertyInChild;
SetPropertyInChild(oldValue, ref value);
if (oldValue != value)
{
_propertyInChild = value;
}
}
}
}
}
| 412 | 0.769153 | 1 | 0.769153 | game-dev | MEDIA | 0.335223 | game-dev | 0.82494 | 1 | 0.82494 |
Astrabit-ST/Luminol | 15,400 | crates/core/src/data_cache.rs | // Copyright (C) 2024 Melody Madeline Lyons
//
// This file is part of Luminol.
//
// Luminol 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.
//
// Luminol 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 Luminol. If not, see <http://www.gnu.org/licenses/>.
//
// Additional permission under GNU GPL version 3 section 7
//
// If you modify this Program, or any covered work, by linking or combining
// it with Steamworks API by Valve Corporation, containing parts covered by
// terms of the Steamworks API by Valve Corporation, the licensors of this
// Program grant you additional permission to convey the resulting work.
use color_eyre::eyre::WrapErr;
use luminol_data::rpg;
use std::{
cell::{RefCell, RefMut},
collections::HashMap,
};
use crate::error;
pub mod data_formats;
// TODO convert this to an option like project config?
#[allow(clippy::large_enum_variant)]
#[derive(Default, Debug)]
pub enum Data {
#[default]
Unloaded,
Loaded {
actors: RefCell<rpg::Actors>,
animations: RefCell<rpg::Animations>,
armors: RefCell<rpg::Armors>,
classes: RefCell<rpg::Classes>,
common_events: RefCell<rpg::CommonEvents>,
enemies: RefCell<rpg::Enemies>,
items: RefCell<rpg::Items>,
map_infos: RefCell<rpg::MapInfos>,
scripts: RefCell<rpg::Scripts>,
skills: RefCell<rpg::Skills>,
states: RefCell<rpg::States>,
system: RefCell<rpg::System>,
tilesets: RefCell<rpg::Tilesets>,
troops: RefCell<rpg::Troops>,
weapons: RefCell<rpg::Weapons>,
maps: RefCell<HashMap<usize, rpg::Map>>,
},
}
macro_rules! load {
($fs:ident, $type:ident, $format_handler:ident) => {
RefCell::new(rpg::$type {
data: $format_handler
.read_nil_padded($fs, format!("{}", stringify!($type)))
.wrap_err_with(|| format!("While reading {}", stringify!($type)))?,
..Default::default()
})
};
}
macro_rules! from_defaults {
($parent:ident, $child:ident) => {
RefCell::new(rpg::$parent {
data: vec![rpg::$child::default()],
modified: true,
})
};
}
macro_rules! save {
($fs:ident, $type:ident, $field:ident, $format_handler:ident) => {{
let borrowed = $field.get_mut();
if borrowed.modified {
$format_handler
.write_nil_padded(&borrowed.data, $fs, format!("{}", stringify!($type)))
.wrap_err_with(|| format!("While saving {}", stringify!($type)))?;
}
borrowed.modified
}};
}
impl Data {
/// Load all data required when opening a project.
/// Does not load config. That is expected to have been loaded beforehand.
pub fn load(
&mut self,
filesystem: &impl luminol_filesystem::FileSystem,
toasts: &mut crate::Toasts,
config: &mut luminol_config::project::Config,
) -> color_eyre::Result<()> {
let handler = data_formats::Handler::new(config.project.data_format);
let map_infos = RefCell::new(rpg::MapInfos {
data: handler
.read_data(filesystem, "MapInfos")
.wrap_err("While reading MapInfos")?,
..Default::default()
});
let mut system = handler
.read_data::<rpg::System>(filesystem, "System")
.wrap_err("While reading System")?;
system.magic_number = rand::random();
let system = RefCell::new(system);
let mut scripts = None;
let scripts_paths = [
config.project.scripts_path.clone(),
"xScripts".to_string(),
"Scripts".to_string(),
];
for script_path in scripts_paths {
match handler.read_data(filesystem, &script_path) {
Ok(s) => {
config.project.scripts_path = script_path;
scripts = Some(rpg::Scripts {
data: s,
..Default::default()
});
break;
}
Err(e) => {
error!(
*toasts,
e.wrap_err(format!(
"While attempting to read scripts from {script_path}"
))
)
}
}
}
let Some(scripts) = scripts else {
color_eyre::eyre::bail!(
"Unable to load scripts (tried {}, xScripts, and Scripts first)",
config.project.scripts_path
);
};
let scripts = RefCell::new(scripts);
let maps = RefCell::new(std::collections::HashMap::with_capacity(32));
*self = Self::Loaded {
actors: load!(filesystem, Actors, handler),
animations: load!(filesystem, Animations, handler),
armors: load!(filesystem, Armors, handler),
classes: load!(filesystem, Classes, handler),
common_events: load!(filesystem, CommonEvents, handler),
enemies: load!(filesystem, Enemies, handler),
items: load!(filesystem, Items, handler),
skills: load!(filesystem, Skills, handler),
states: load!(filesystem, States, handler),
tilesets: load!(filesystem, Tilesets, handler),
troops: load!(filesystem, Troops, handler),
weapons: load!(filesystem, Weapons, handler),
map_infos,
system,
scripts,
maps,
};
Ok(())
}
pub fn unload(&mut self) {
*self = Self::Unloaded;
}
pub fn from_defaults() -> Self {
let mut map_infos = std::collections::HashMap::with_capacity(16);
map_infos.insert(
1,
rpg::MapInfo {
order: 1,
..Default::default()
},
);
let map_infos = RefCell::new(rpg::MapInfos {
data: map_infos,
modified: true,
});
let system = rpg::System {
magic_number: rand::random(),
modified: true,
..Default::default()
};
let system = RefCell::new(system);
let scripts = vec![]; // FIXME legality of providing defualt scripts is unclear
let scripts = RefCell::new(rpg::Scripts {
data: scripts,
modified: true,
});
let mut maps = std::collections::HashMap::with_capacity(32);
maps.insert(
1,
rpg::Map {
modified: true,
..Default::default()
},
);
let maps = RefCell::new(maps);
Self::Loaded {
actors: from_defaults!(Actors, Actor),
animations: from_defaults!(Animations, Animation),
armors: from_defaults!(Armors, Armor),
classes: from_defaults!(Classes, Class),
common_events: from_defaults!(CommonEvents, CommonEvent),
enemies: from_defaults!(Enemies, Enemy),
items: from_defaults!(Items, Item),
skills: from_defaults!(Skills, Skill),
states: from_defaults!(States, State),
tilesets: from_defaults!(Tilesets, Tileset),
troops: from_defaults!(Troops, Troop),
weapons: from_defaults!(Weapons, Weapon),
map_infos,
system,
scripts,
maps,
}
}
pub fn rxdata_ext(&self) -> &'static str {
todo!()
}
/// Save all cached data to disk.
// we take an &mut self to ensure no outsanding borrows of the cache exist.
pub fn save(
&mut self,
filesystem: &impl luminol_filesystem::FileSystem,
config: &luminol_config::project::Config,
) -> color_eyre::Result<()> {
let handler = data_formats::Handler::new(config.project.data_format);
let Self::Loaded {
actors,
animations,
armors,
classes,
common_events,
enemies,
items,
map_infos,
scripts,
skills,
states,
tilesets,
troops,
weapons,
system,
maps,
} = self
else {
panic!("project not loaded")
};
let mut modified = false;
modified |= save!(filesystem, Actors, actors, handler);
modified |= save!(filesystem, Animations, animations, handler);
modified |= save!(filesystem, Armors, armors, handler);
modified |= save!(filesystem, Classes, classes, handler);
modified |= save!(filesystem, CommonEvents, common_events, handler);
modified |= save!(filesystem, Enemies, enemies, handler);
modified |= save!(filesystem, Items, items, handler);
modified |= save!(filesystem, Skills, skills, handler);
modified |= save!(filesystem, States, states, handler);
modified |= save!(filesystem, Tilesets, tilesets, handler);
modified |= save!(filesystem, Troops, troops, handler);
modified |= save!(filesystem, Weapons, weapons, handler);
{
let map_infos = map_infos.get_mut();
if map_infos.modified {
modified = true;
handler
.write_data(&map_infos.data, filesystem, "MapInfos")
.wrap_err("While saving MapInfos")?;
}
}
{
let scripts = scripts.get_mut();
if scripts.modified {
modified = true;
handler.write_data(&scripts.data, filesystem, &config.project.scripts_path)?;
}
}
{
let maps = maps.get_mut();
maps.iter().try_for_each(|(id, map)| {
if map.modified {
modified = true;
handler
.write_data(map, filesystem, format!("Map{id:0>3}"))
.wrap_err_with(|| format!("While saving map {id:0>3}"))
} else {
Ok(())
}
})?
}
{
let system = system.get_mut();
if system.modified || modified {
system.magic_number = rand::random();
handler
.write_data(system, filesystem, "System")
.wrap_err("While saving System")?;
system.modified = false;
}
}
let pretty_config = ron::ser::PrettyConfig::new()
.struct_names(true)
.enumerate_arrays(true);
// this is autocreated on load. however:
// since we're creating project config now, we need this directory
filesystem
.create_dir(".luminol")
.wrap_err("While creating .luminol")?;
let project_config = ron::ser::to_string_pretty(&config.project, pretty_config.clone())
.wrap_err("While serializing .luminol/config")?;
filesystem
.write(".luminol/config", project_config)
.wrap_err("While writing .luminol/config")?;
let command_db = ron::ser::to_string_pretty(&config.command_db, pretty_config.clone())
.wrap_err("While serializing .luminol/commands")?;
filesystem
.write(".luminol/commands", command_db)
.wrap_err("While writing .luminol/commands")?;
// even though Ini uses fmt::write internally, it provides no easy way to write to a string.
// so we need to open a file instead
let mut ini_file = filesystem
.open_file(
"Game.ini",
luminol_filesystem::OpenFlags::Create
| luminol_filesystem::OpenFlags::Write
| luminol_filesystem::OpenFlags::Truncate,
)
.wrap_err("While opening Game.ini")?;
config
.game_ini
.write_to(&mut ini_file)
.wrap_err("While serializing Game.ini")?;
actors.borrow_mut().modified = false;
animations.borrow_mut().modified = false;
armors.borrow_mut().modified = false;
classes.borrow_mut().modified = false;
common_events.borrow_mut().modified = false;
enemies.borrow_mut().modified = false;
items.borrow_mut().modified = false;
skills.borrow_mut().modified = false;
states.borrow_mut().modified = false;
tilesets.borrow_mut().modified = false;
troops.borrow_mut().modified = false;
weapons.borrow_mut().modified = false;
map_infos.borrow_mut().modified = false;
scripts.borrow_mut().modified = false;
for (_, map) in maps.borrow_mut().iter_mut() {
map.modified = false;
}
Ok(())
}
}
macro_rules! nested_ref_getter {
($($typ:ty, $name:ident),* $(,)?) => {
$(
#[allow(unsafe_code, dead_code)]
pub fn $name(&self) -> RefMut<'_, $typ> {
match self {
Self::Unloaded => panic!("data cache unloaded"),
Self::Loaded { $name, ..} => $name.borrow_mut(),
}
}
)+
};
}
impl Data {
nested_ref_getter! {
rpg::Actors, actors,
rpg::Animations, animations,
rpg::Armors, armors,
rpg::Classes, classes,
rpg::CommonEvents, common_events,
rpg::Enemies, enemies,
rpg::Items, items,
rpg::MapInfos, map_infos,
rpg::Scripts, scripts,
rpg::Skills, skills,
rpg::States, states,
rpg::System, system,
rpg::Tilesets, tilesets,
rpg::Troops, troops,
rpg::Weapons, weapons,
}
/// Load a map.
#[allow(clippy::panic)]
pub fn get_or_load_map(
&self,
id: usize,
filesystem: &impl luminol_filesystem::FileSystem,
config: &luminol_config::project::Config,
) -> RefMut<'_, rpg::Map> {
let maps_ref = match self {
Self::Loaded { maps, .. } => maps.borrow_mut(),
Self::Unloaded => panic!("project not loaded"),
};
RefMut::map(maps_ref, |maps| {
// FIXME
maps.entry(id).or_insert_with(|| {
let handler = data_formats::Handler::new(config.project.data_format);
handler
.read_data(filesystem, format!("Map{id:0>3}"))
.expect("failed to load map")
})
})
}
pub fn get_map(&self, id: usize) -> RefMut<'_, rpg::Map> {
let maps_ref = match self {
Self::Loaded { maps, .. } => maps.borrow_mut(),
Self::Unloaded => panic!("project not loaded"),
};
RefMut::map(maps_ref, |maps| maps.get_mut(&id).expect("map not loaded"))
}
}
| 412 | 0.848887 | 1 | 0.848887 | game-dev | MEDIA | 0.958119 | game-dev | 0.789766 | 1 | 0.789766 |
MarkGG8181/stripped-1.8.9 | 2,997 | src/main/java/net/minecraft/block/BlockFalling.java | package net.minecraft.block;
import java.util.Random;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.item.EntityFallingBlock;
import net.minecraft.init.Blocks;
import net.minecraft.util.BlockPos;
import net.minecraft.world.World;
public class BlockFalling extends Block
{
public static boolean fallInstantly;
public BlockFalling()
{
super(Material.sand);
this.setCreativeTab(CreativeTabs.tabBlock);
}
public BlockFalling(Material materialIn)
{
super(materialIn);
}
public void onBlockAdded(World worldIn, BlockPos pos, IBlockState state)
{
worldIn.scheduleUpdate(pos, this, this.tickRate(worldIn));
}
/**
* Called when a neighboring block changes.
*/
public void onNeighborBlockChange(World worldIn, BlockPos pos, IBlockState state, Block neighborBlock)
{
worldIn.scheduleUpdate(pos, this, this.tickRate(worldIn));
}
public void updateTick(World worldIn, BlockPos pos, IBlockState state, Random rand)
{
if (!worldIn.isRemote)
{
this.checkFallable(worldIn, pos);
}
}
private void checkFallable(World worldIn, BlockPos pos)
{
if (canFallInto(worldIn, pos.down()) && pos.getY() >= 0)
{
int i = 32;
if (!fallInstantly && worldIn.isAreaLoaded(pos.add(-i, -i, -i), pos.add(i, i, i)))
{
if (!worldIn.isRemote)
{
EntityFallingBlock entityfallingblock = new EntityFallingBlock(worldIn, (double)pos.getX() + 0.5D, (double)pos.getY(), (double)pos.getZ() + 0.5D, worldIn.getBlockState(pos));
this.onStartFalling(entityfallingblock);
worldIn.spawnEntityInWorld(entityfallingblock);
}
}
else
{
worldIn.setBlockToAir(pos);
BlockPos blockpos;
for (blockpos = pos.down(); canFallInto(worldIn, blockpos) && blockpos.getY() > 0; blockpos = blockpos.down())
{
}
if (blockpos.getY() > 0)
{
worldIn.setBlockState(blockpos.up(), this.getDefaultState());
}
}
}
}
protected void onStartFalling(EntityFallingBlock fallingEntity)
{
}
/**
* How many world ticks before ticking
*/
public int tickRate(World worldIn)
{
return 2;
}
public static boolean canFallInto(World worldIn, BlockPos pos)
{
Block block = worldIn.getBlockState(pos).getBlock();
Material material = block.blockMaterial;
return block == Blocks.fire || material == Material.air || material == Material.water || material == Material.lava;
}
public void onEndFalling(World worldIn, BlockPos pos)
{
}
}
| 412 | 0.701288 | 1 | 0.701288 | game-dev | MEDIA | 0.998807 | game-dev | 0.843966 | 1 | 0.843966 |
ProjectIgnis/CardScripts | 2,807 | official/c32224143.lua | --ゴーストリック・サキュバス
--Ghostrick Socuteboss
local s,id=GetID()
function s.initial_effect(c)
--xyz summon
Xyz.AddProcedure(c,nil,2,2)
c:EnableReviveLimit()
--destroy
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(id,0))
e1:SetCategory(CATEGORY_DESTROY)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetRange(LOCATION_MZONE)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCountLimit(1)
e1:SetCost(Cost.DetachFromSelf(1))
e1:SetTarget(s.target)
e1:SetOperation(s.operation)
c:RegisterEffect(e1)
--cannot be battle target
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e2:SetRange(LOCATION_MZONE)
e2:SetCode(EFFECT_CANNOT_BE_BATTLE_TARGET)
e2:SetCondition(s.atkcon)
e2:SetValue(aux.imval2)
c:RegisterEffect(e2)
end
s.listed_series={SET_GHOSTRICK}
function s.cfilter(c)
return c:IsFaceup() and c:IsSetCard(SET_GHOSTRICK)
end
function s.filter(c,atk)
return c:IsFaceup() and c:IsAttackBelow(atk)
end
function s.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
local cg=Duel.GetMatchingGroup(s.cfilter,tp,LOCATION_MZONE,LOCATION_MZONE,nil)
local atk=cg:GetSum(Card.GetAttack)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and s.filter(chkc,atk) end
if chk==0 then return Duel.IsExistingTarget(s.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,nil,atk) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY)
local g=Duel.SelectTarget(tp,s.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,1,nil,atk)
Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,1,0,0)
end
function s.operation(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
local seq=tc:GetSequence()
if tc:IsControler(1-tp) then seq=seq+16 end
if tc:IsRelateToEffect(e) and tc:IsFaceup() and Duel.Destroy(tc,REASON_EFFECT)~=0 then
local g=Duel.GetMatchingGroup(s.cfilter,e:GetHandlerPlayer(),LOCATION_MZONE,0,nil)
local tc=g:GetFirst()
for tc in aux.Next(g) do
tc:RegisterFlagEffect(id,RESET_EVENT|RESETS_STANDARD|RESET_OVERLAY,0,1)
end
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_DISABLE_FIELD)
e1:SetLabel(seq)
e1:SetCondition(s.discon)
e1:SetOperation(s.disop)
e1:SetReset(0)
Duel.RegisterEffect(e1,tp)
end
end
function s.cfilter2(c)
return s.cfilter(c) and c:GetFlagEffect(id)~=0
end
function s.discon(e)
local g=Duel.GetMatchingGroup(s.cfilter,e:GetHandlerPlayer(),LOCATION_MZONE,0,nil)
if g:IsExists(s.cfilter2,1,nil) then
local tc=g:GetFirst()
for tc in aux.Next(g) do
tc:RegisterFlagEffect(id,RESET_EVENT|RESETS_STANDARD|RESET_OVERLAY,0,1)
tc=g:GetNext()
end
return true
end
e:Reset()
return false
end
function s.disop(e,tp)
return (0x1<<e:GetLabel())
end
function s.atkcon(e)
return Duel.IsExistingMatchingCard(s.cfilter,e:GetHandlerPlayer(),LOCATION_MZONE,0,1,e:GetHandler())
end
| 412 | 0.964941 | 1 | 0.964941 | game-dev | MEDIA | 0.98334 | game-dev | 0.967732 | 1 | 0.967732 |
magicblock-labs/Solana.Unity-SDK | 5,519 | Runtime/Plugins/UniTask/Runtime/Linq/Publish.cs | using Cysharp.Threading.Tasks.Internal;
using System;
using System.Threading;
namespace Cysharp.Threading.Tasks.Linq
{
public static partial class UniTaskAsyncEnumerable
{
public static IConnectableUniTaskAsyncEnumerable<TSource> Publish<TSource>(this IUniTaskAsyncEnumerable<TSource> source)
{
Error.ThrowArgumentNullException(source, nameof(source));
return new Publish<TSource>(source);
}
}
internal sealed class Publish<TSource> : IConnectableUniTaskAsyncEnumerable<TSource>
{
readonly IUniTaskAsyncEnumerable<TSource> source;
readonly CancellationTokenSource cancellationTokenSource;
TriggerEvent<TSource> trigger;
IUniTaskAsyncEnumerator<TSource> enumerator;
IDisposable connectedDisposable;
bool isCompleted;
public Publish(IUniTaskAsyncEnumerable<TSource> source)
{
this.source = source;
this.cancellationTokenSource = new CancellationTokenSource();
}
public IDisposable Connect()
{
if (connectedDisposable != null) return connectedDisposable;
if (enumerator == null)
{
enumerator = source.GetAsyncEnumerator(cancellationTokenSource.Token);
}
ConsumeEnumerator().Forget();
connectedDisposable = new ConnectDisposable(cancellationTokenSource);
return connectedDisposable;
}
async UniTaskVoid ConsumeEnumerator()
{
try
{
try
{
while (await enumerator.MoveNextAsync())
{
trigger.SetResult(enumerator.Current);
}
trigger.SetCompleted();
}
catch (Exception ex)
{
trigger.SetError(ex);
}
}
finally
{
isCompleted = true;
await enumerator.DisposeAsync();
}
}
public IUniTaskAsyncEnumerator<TSource> GetAsyncEnumerator(CancellationToken cancellationToken = default)
{
return new _Publish(this, cancellationToken);
}
sealed class ConnectDisposable : IDisposable
{
readonly CancellationTokenSource cancellationTokenSource;
public ConnectDisposable(CancellationTokenSource cancellationTokenSource)
{
this.cancellationTokenSource = cancellationTokenSource;
}
public void Dispose()
{
this.cancellationTokenSource.Cancel();
}
}
sealed class _Publish : MoveNextSource, IUniTaskAsyncEnumerator<TSource>, ITriggerHandler<TSource>
{
static readonly Action<object> CancelDelegate = OnCanceled;
readonly Publish<TSource> parent;
CancellationToken cancellationToken;
CancellationTokenRegistration cancellationTokenRegistration;
bool isDisposed;
public _Publish(Publish<TSource> parent, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested) return;
this.parent = parent;
this.cancellationToken = cancellationToken;
if (cancellationToken.CanBeCanceled)
{
this.cancellationTokenRegistration = cancellationToken.RegisterWithoutCaptureExecutionContext(CancelDelegate, this);
}
parent.trigger.Add(this);
TaskTracker.TrackActiveTask(this, 3);
}
public TSource Current { get; private set; }
ITriggerHandler<TSource> ITriggerHandler<TSource>.Prev { get; set; }
ITriggerHandler<TSource> ITriggerHandler<TSource>.Next { get; set; }
public UniTask<bool> MoveNextAsync()
{
cancellationToken.ThrowIfCancellationRequested();
if (parent.isCompleted) return CompletedTasks.False;
completionSource.Reset();
return new UniTask<bool>(this, completionSource.Version);
}
static void OnCanceled(object state)
{
var self = (_Publish)state;
self.completionSource.TrySetCanceled(self.cancellationToken);
self.DisposeAsync().Forget();
}
public UniTask DisposeAsync()
{
if (!isDisposed)
{
isDisposed = true;
TaskTracker.RemoveTracking(this);
cancellationTokenRegistration.Dispose();
parent.trigger.Remove(this);
}
return default;
}
public void OnNext(TSource value)
{
Current = value;
completionSource.TrySetResult(true);
}
public void OnCanceled(CancellationToken cancellationToken)
{
completionSource.TrySetCanceled(cancellationToken);
}
public void OnCompleted()
{
completionSource.TrySetResult(false);
}
public void OnError(Exception ex)
{
completionSource.TrySetException(ex);
}
}
}
} | 412 | 0.878433 | 1 | 0.878433 | game-dev | MEDIA | 0.38927 | game-dev | 0.834174 | 1 | 0.834174 |
jeffheaton/aifh | 3,494 | vol2/vol2-java-examples/src/main/java/com/heatonresearch/aifh/examples/capstone/model/milestone1/CalcSurvival.java | /*
* Artificial Intelligence for Humans
* Volume 2: Nature Inspired Algorithms
* Java Version
* http://www.aifh.org
* http://www.jeffheaton.com
*
* Code repository:
* https://github.com/jeffheaton/aifh
*
* Copyright 2014 by Jeff Heaton
*
* 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.
*
* For more information on Heaton Research copyrights, licenses
* and trademarks visit:
* http://www.heatonresearch.com/copyright
*/
package com.heatonresearch.aifh.examples.capstone.model.milestone1;
/**
* Used to calculate survival by male and female.
*/
public class CalcSurvival {
/**
* The count of males.
*/
private int countMale;
/**
* The count of females.
*/
private int countFemale;
/**
* The count of male survivors.
*/
private int maleSurvive;
/**
* The count of female survivors.
*/
private int femaleSurvive;
/**
* Update for a passenger.
*
* @param male True, if passenger was male.
* @param survived True, if passenger survived.
*/
public void update(boolean male, boolean survived) {
if (male) {
countMale++;
} else {
countFemale++;
}
if (survived) {
if (male) {
this.maleSurvive++;
} else {
this.femaleSurvive++;
}
}
}
/**
* @return The number of male survivors.
*/
public int getMaleSurvive() {
return maleSurvive;
}
/**
* @return The number of female survivors.
*/
public int getFemaleSurvive() {
return femaleSurvive;
}
/**
* @return The total count of passengers.
*/
public int getCount() {
return this.countFemale + this.countMale;
}
/**
* @return The number of male passengers.
*/
public int getCountMale() {
return this.countMale;
}
/**
* @return The number of female passengers.
*/
public int getCountFemale() {
return this.countFemale;
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
StringBuilder result = new StringBuilder();
result.append("(");
result.append("Count: ");
result.append(getCount());
if (getCount() > 0) {
double pct = (double) (this.femaleSurvive + this.maleSurvive) / getCount();
result.append(", survived: ");
result.append(pct);
}
if (getCountMale() > 0) {
double pct = (double) (this.maleSurvive) / (this.countMale);
result.append(", male.survived: ");
result.append(pct);
}
if (getCountFemale() > 0) {
double pct = (double) (this.femaleSurvive) / (this.countFemale);
result.append(", female.survived: ");
result.append(pct);
}
result.append(")");
return result.toString();
}
}
| 412 | 0.516186 | 1 | 0.516186 | game-dev | MEDIA | 0.439331 | game-dev,uncategorized | 0.782312 | 1 | 0.782312 |
ariannedee/oop-python | 1,033 | Refactoring/refactoring_5_inheritance/player.py | from random import randint
class Player:
def __init__(self, num, score=0):
self.num = num
self._score = score
@property
def score(self):
return self._score
@staticmethod
def _roll():
return randint(1, 6)
def take_turn(self):
roll = self._roll()
self._score += roll
print(f"{self}: {self.score} (rolled a {roll})")
def __str__(self):
return f"Player {self.num}"
def __repr__(self):
return f"{type(self).__name__}({self.num}, score={self.score})"
class LuckyPlayer(Player):
def __init__(self, minimum_roll=3, *args, **kwargs):
print(args)
print(kwargs)
super().__init__(*args, **kwargs)
self.min_roll = minimum_roll
def _roll(self):
return randint(self.min_roll, 6)
def __str__(self):
base_str = super().__str__()
return f"{base_str}*"
def get_player(num):
if num == 2:
return LuckyPlayer(2, num, 20)
else:
return Player(num)
| 412 | 0.760493 | 1 | 0.760493 | game-dev | MEDIA | 0.302542 | game-dev | 0.801834 | 1 | 0.801834 |
rpgboss/rpgboss | 1,868 | desktop/src/main/scala/rpgboss/editor/cache/MapTileCache.scala | package rpgboss.editor.cache
import rpgboss.model._
import rpgboss.model.resource._
import java.awt.image._
import com.google.common.cache._
/**
* A tile cache applicable to only one map.
*/
class MapTileCache(
assetCache: AssetCache,
map: RpgMap,
cacheMaxSize: Int = 5000) {
val tilesets = map.metadata.tilesets.map(assetCache.getTileset(_))
val autotiles = map.metadata.autotiles.map(assetCache.getAutotile(_))
val cache = CacheBuilder.newBuilder()
.concurrencyLevel(1)
.softValues()
.maximumSize(cacheMaxSize)
.expireAfterWrite(10, java.util.concurrent.TimeUnit.MINUTES)
.build(new CacheLoader[(Byte, Byte, Byte, Byte), BufferedImage] {
def load(tileTuple: (Byte, Byte, Byte, Byte)) = loadTile(tileTuple)
})
def loadTile(tileTuple: (Byte, Byte, Byte, Byte)) = {
val (tilesetIdx, secondByte, thirdByte, frame) = tileTuple
val secondBytePos = secondByte & 0xff
val thirdBytePos = thirdByte & 0xff
if (tilesetIdx == RpgMap.autotileByte) {
// Autotile
val autotileNum = secondBytePos
val autotileConfig = thirdBytePos
if (autotiles.length > autotileNum) {
autotiles(autotileNum).getTileImage(autotileConfig, frame)
} else ImageResource.errorTile
} else if (tilesetIdx >= 0) {
// Regular tile
val x = secondBytePos
val y = thirdBytePos
if (tilesets.length > tilesetIdx) {
tilesets(tilesetIdx).getTileImage(x, y)
} else ImageResource.errorTile
} else ImageResource.errorTile
}
// frame here means the animation frame
def getTileImage(
mapData: Array[Array[Byte]], xTile: Int, yTile: Int, frame: Byte = 0) = {
val row = mapData(yTile)
val idx = xTile * RpgMap.bytesPerTile
val tileTuple = (row(idx), row(idx + 1), row(idx + 2), frame)
cache.get(tileTuple)
//loadTile(tileTuple)
}
}
| 412 | 0.814089 | 1 | 0.814089 | game-dev | MEDIA | 0.706923 | game-dev,graphics-rendering | 0.985675 | 1 | 0.985675 |
RevereInc/alley-practice | 3,568 | src/main/java/dev/revere/alley/visual/scoreboard/internal/match/BaseMatchScoreboard.java | package dev.revere.alley.visual.scoreboard.internal.match;
import dev.revere.alley.AlleyPlugin;
import dev.revere.alley.core.config.ConfigService;
import dev.revere.alley.feature.match.Match;
import dev.revere.alley.feature.match.model.internal.MatchGamePlayer;
import dev.revere.alley.feature.match.model.GameParticipant;
import dev.revere.alley.core.profile.ProfileService;
import dev.revere.alley.core.profile.Profile;
import dev.revere.alley.common.text.CC;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.List;
/**
* @author Remi
* @project Alley
* @since 26/06/2025
*/
public abstract class BaseMatchScoreboard implements MatchScoreboard {
/**
* Gets the path to the solo version of the scoreboard in the config.
*
* @return The configuration path.
*/
protected abstract String getSoloConfigPath();
/**
* Gets the path to the team version of the scoreboard in the config.
*
* @return The configuration path.
*/
protected abstract String getTeamConfigPath();
@Override
public List<String> getLines(Profile profile, Player player, GameParticipant<MatchGamePlayer> you, GameParticipant<MatchGamePlayer> opponent) {
List<String> scoreboardLines = new ArrayList<>();
Match match = profile.getMatch();
String configPath = match.isTeamMatch() ? getTeamConfigPath() : getSoloConfigPath();
for (String line : AlleyPlugin.getInstance().getService(ConfigService.class).getScoreboardConfig().getStringList(configPath)) {
scoreboardLines.add(replacePlaceholders(line, profile, player, you, opponent));
}
return scoreboardLines;
}
/**
* Replaces all placeholders in a given line of the scoreboard.
* Child classes should override this to add their own specific placeholders.
*
* @param line The line with placeholders.
* @param profile The player's profile.
* @param player The player.
* @param you The player's game participant.
* @param opponent The opponent's game participant.
* @return The line with all placeholders replaced.
*/
protected String replacePlaceholders(String line, Profile profile, Player player, GameParticipant<MatchGamePlayer> you, GameParticipant<MatchGamePlayer> opponent) {
Match match = profile.getMatch();
ProfileService profileService = AlleyPlugin.getInstance().getService(ProfileService.class);
String opponentName = match.isTeamMatch() ? getColoredName(profileService.getProfile(opponent.getLeader().getUuid())) + "' Team" : getColoredName(profileService.getProfile(opponent.getLeader().getUuid()));
return CC.translate(line)
.replace("{opponent}", opponentName)
.replace("{player-ping}", String.valueOf(getPing(player)))
.replace("{opponent-ping}", String.valueOf(getPing(opponent.getLeader().getTeamPlayer())))
.replace("{duration}", match.getDuration())
.replace("{arena}", match.getArena().getDisplayName() == null ? "&c&lNULL" : match.getArena().getDisplayName())
.replace("{kit}", match.getKit().getDisplayName())
.replace("{your-players}", String.valueOf(you.getPlayerSize()))
.replace("{opponent-players}", String.valueOf(opponent.getPlayerSize()))
.replace("{your-alive}", String.valueOf(you.getAlivePlayerSize()))
.replace("{opponent-alive}", String.valueOf(opponent.getAlivePlayerSize()));
}
} | 412 | 0.855657 | 1 | 0.855657 | game-dev | MEDIA | 0.344335 | game-dev | 0.926824 | 1 | 0.926824 |
magefree/mage | 1,753 | Mage.Sets/src/mage/cards/n/NullChampion.java |
package mage.cards.n;
import java.util.UUID;
import mage.MageInt;
import mage.abilities.Abilities;
import mage.abilities.AbilitiesImpl;
import mage.abilities.Ability;
import mage.abilities.common.SimpleActivatedAbility;
import mage.abilities.costs.mana.ManaCostsImpl;
import mage.abilities.effects.common.RegenerateSourceEffect;
import mage.abilities.keyword.LevelUpAbility;
import mage.abilities.keyword.LevelerCardBuilder;
import mage.cards.CardSetInfo;
import mage.cards.LevelerCard;
import mage.constants.CardType;
import mage.constants.SubType;
import mage.constants.Zone;
/**
*
* @author Loki, noxx
*/
public final class NullChampion extends LevelerCard {
public NullChampion (UUID ownerId, CardSetInfo setInfo) {
super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{1}{B}");
this.subtype.add(SubType.ZOMBIE);
this.subtype.add(SubType.WARRIOR);
this.color.setBlack(true);
this.power = new MageInt(1);
this.toughness = new MageInt(1);
this.addAbility(new LevelUpAbility(new ManaCostsImpl<>("{3}")));
Abilities<Ability> abilities1 = new AbilitiesImpl<>();
Abilities<Ability> abilities2 = new AbilitiesImpl<>();
abilities2.add(new SimpleActivatedAbility(new RegenerateSourceEffect(), new ManaCostsImpl<>("{B}")));
this.addAbilities(LevelerCardBuilder.construct(
new LevelerCardBuilder.LevelAbility(1, 3, abilities1, 4, 2),
new LevelerCardBuilder.LevelAbility(4, -1, abilities2, 7, 3)
));
setMaxLevelCounters(4);
}
private NullChampion(final NullChampion card) {
super(card);
}
@Override
public NullChampion copy() {
return new NullChampion(this);
}
}
| 412 | 0.870054 | 1 | 0.870054 | game-dev | MEDIA | 0.968634 | game-dev | 0.9885 | 1 | 0.9885 |
Jermesa-Studio/JRS_Vehicle_Physics_Controller | 2,077 | Library/PackageCache/com.unity.visualscripting@1.9.4/Runtime/VisualScripting.Flow/Framework/Events/CustomEvent.cs | using System;
using System.Collections.Generic;
using UnityEngine;
namespace Unity.VisualScripting
{
/// <summary>
/// A special named event with any amount of parameters called manually with the 'Trigger Custom Event' unit.
/// </summary>
[UnitCategory("Events")]
[UnitOrder(0)]
public sealed class CustomEvent : GameObjectEventUnit<CustomEventArgs>
{
public override Type MessageListenerType => null;
protected override string hookName => EventHooks.Custom;
[SerializeAs(nameof(argumentCount))]
private int _argumentCount;
[DoNotSerialize]
[Inspectable, UnitHeaderInspectable("Arguments")]
public int argumentCount
{
get => _argumentCount;
set => _argumentCount = Mathf.Clamp(value, 0, 10);
}
/// <summary>
/// The name of the event.
/// </summary>
[DoNotSerialize]
[PortLabelHidden]
public ValueInput name { get; private set; }
[DoNotSerialize]
public List<ValueOutput> argumentPorts { get; } = new List<ValueOutput>();
protected override void Definition()
{
base.Definition();
name = ValueInput(nameof(name), string.Empty);
argumentPorts.Clear();
for (var i = 0; i < argumentCount; i++)
{
argumentPorts.Add(ValueOutput<object>("argument_" + i));
}
}
protected override bool ShouldTrigger(Flow flow, CustomEventArgs args)
{
return CompareNames(flow, name, args.name);
}
protected override void AssignArguments(Flow flow, CustomEventArgs args)
{
for (var i = 0; i < argumentCount; i++)
{
flow.SetValue(argumentPorts[i], args.arguments[i]);
}
}
public static void Trigger(GameObject target, string name, params object[] args)
{
EventBus.Trigger(EventHooks.Custom, target, new CustomEventArgs(name, args));
}
}
}
| 412 | 0.906962 | 1 | 0.906962 | game-dev | MEDIA | 0.77096 | game-dev | 0.840853 | 1 | 0.840853 |
m5stack/M5Dial-UserDemo | 2,554 | components/lvgl/src/core/lv_obj_class.h | /**
* @file lv_obj_class.h
*
*/
#ifndef LV_OBJ_CLASS_H
#define LV_OBJ_CLASS_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include <stdint.h>
#include <stdbool.h>
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
struct _lv_obj_t;
struct _lv_obj_class_t;
struct _lv_event_t;
typedef enum {
LV_OBJ_CLASS_EDITABLE_INHERIT, /**< Check the base class. Must have 0 value to let zero initialized class inherit*/
LV_OBJ_CLASS_EDITABLE_TRUE,
LV_OBJ_CLASS_EDITABLE_FALSE,
} lv_obj_class_editable_t;
typedef enum {
LV_OBJ_CLASS_GROUP_DEF_INHERIT, /**< Check the base class. Must have 0 value to let zero initialized class inherit*/
LV_OBJ_CLASS_GROUP_DEF_TRUE,
LV_OBJ_CLASS_GROUP_DEF_FALSE,
} lv_obj_class_group_def_t;
typedef void (*lv_obj_class_event_cb_t)(struct _lv_obj_class_t * class_p, struct _lv_event_t * e);
/**
* Describe the common methods of every object.
* Similar to a C++ class.
*/
typedef struct _lv_obj_class_t {
const struct _lv_obj_class_t * base_class;
void (*constructor_cb)(const struct _lv_obj_class_t * class_p, struct _lv_obj_t * obj);
void (*destructor_cb)(const struct _lv_obj_class_t * class_p, struct _lv_obj_t * obj);
#if LV_USE_USER_DATA
void * user_data;
#endif
void (*event_cb)(const struct _lv_obj_class_t * class_p,
struct _lv_event_t * e); /**< Widget type specific event function*/
lv_coord_t width_def;
lv_coord_t height_def;
uint32_t editable : 2; /**< Value from ::lv_obj_class_editable_t*/
uint32_t group_def : 2; /**< Value from ::lv_obj_class_group_def_t*/
uint32_t instance_size : 16;
} lv_obj_class_t;
/**********************
* GLOBAL PROTOTYPES
**********************/
/**
* Create an object form a class descriptor
* @param class_p pointer to a class
* @param parent pointer to an object where the new object should be created
* @return pointer to the created object
*/
struct _lv_obj_t * lv_obj_class_create_obj(const struct _lv_obj_class_t * class_p, struct _lv_obj_t * parent);
void lv_obj_class_init_obj(struct _lv_obj_t * obj);
void _lv_obj_destruct(struct _lv_obj_t * obj);
bool lv_obj_is_editable(struct _lv_obj_t * obj);
bool lv_obj_is_group_def(struct _lv_obj_t * obj);
/**********************
* MACROS
**********************/
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_OBJ_CLASS_H*/
| 412 | 0.915295 | 1 | 0.915295 | game-dev | MEDIA | 0.471432 | game-dev | 0.553096 | 1 | 0.553096 |
MegaMek/megamek | 3,916 | megamek/src/megamek/common/weapons/ppc/innerSphere/ISSnubNosePPC.java | /*
* Copyright (C) 2004, 2005 Ben Mazur (bmazur@sev.org)
* Copyright (C) 2007-2025 The MegaMek Team. All Rights Reserved.
*
* This file is part of MegaMek.
*
* MegaMek is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License (GPL),
* version 3 or (at your option) any later version,
* as published by the Free Software Foundation.
*
* MegaMek 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.
*
* A copy of the GPL should have been included with this project;
* if not, see <https://www.gnu.org/licenses/>.
*
* NOTICE: The MegaMek organization is a non-profit group of volunteers
* creating free software for the BattleTech community.
*
* MechWarrior, BattleMech, `Mech and AeroTech are registered trademarks
* of The Topps Company, Inc. All Rights Reserved.
*
* Catalyst Game Labs and the Catalyst Game Labs logo are trademarks of
* InMediaRes Productions, LLC.
*
* MechWarrior Copyright Microsoft Corporation. MegaMek was created under
* Microsoft's "Game Content Usage Rules"
* <https://www.xbox.com/en-US/developers/rules> and it is not endorsed by or
* affiliated with Microsoft.
*/
package megamek.common.weapons.ppc.innerSphere;
import java.io.Serial;
import megamek.common.alphaStrike.AlphaStrikeElement;
import megamek.common.enums.AvailabilityValue;
import megamek.common.enums.Faction;
import megamek.common.enums.TechBase;
import megamek.common.enums.TechRating;
import megamek.common.equipment.Mounted;
import megamek.common.weapons.ppc.PPCWeapon;
/**
* @author Andrew Hunter
* @since Sep 13, 2004
*/
public class ISSnubNosePPC extends PPCWeapon {
@Serial
private static final long serialVersionUID = -5650794792475465261L;
public ISSnubNosePPC() {
super();
name = "Snub-Nose PPC";
setInternalName("ISSNPPC");
addLookupName("ISSnubNosedPPC");
sortingName = "PPC Snub";
heat = 10;
damage = DAMAGE_VARIABLE;
minimumRange = 0;
shortRange = 9;
mediumRange = 13;
longRange = 15;
extremeRange = 22;
waterShortRange = 6;
waterMediumRange = 8;
waterLongRange = 9;
waterExtremeRange = 13;
damageShort = 10;
damageMedium = 8;
damageLong = 5;
tonnage = 6.0;
criticalSlots = 2;
bv = 165;
cost = 300000;
maxRange = RANGE_MED;
shortAV = 10;
medAV = 8;
// with a capacitor
explosive = true;
rulesRefs = "234, TM";
techAdvancement.setTechBase(TechBase.IS)
.setIntroLevel(false)
.setUnofficial(false)
.setTechRating(TechRating.E)
.setAvailability(AvailabilityValue.F, AvailabilityValue.X, AvailabilityValue.F, AvailabilityValue.D)
.setISAdvancement(2695, 2784, 3068, 2790, 3067)
.setISApproximate(false, true, false, false, false)
.setPrototypeFactions(Faction.TH)
.setProductionFactions(Faction.TH)
.setReintroductionFactions(Faction.DC, Faction.FW);
}
@Override
public int getDamage(int range) {
if (range <= shortRange) {
return damageShort;
}
if (range <= mediumRange) {
return damageMedium;
}
return damageLong;
}
@Override
public double getBattleForceDamage(int range, Mounted<?> capacitor) {
if (range == AlphaStrikeElement.SHORT_RANGE) {
return (capacitor != null) ? 0.75 : 1;
} else if (range == AlphaStrikeElement.MEDIUM_RANGE) {
return (capacitor != null) ? 0.5 : 0.65;
} else {
return 0;
}
}
}
| 412 | 0.805466 | 1 | 0.805466 | game-dev | MEDIA | 0.978148 | game-dev | 0.855164 | 1 | 0.855164 |
liyunfan1223/mod-playerbots | 17,526 | src/strategy/Engine.cpp | /*
* Copyright (C) 2016+ AzerothCore <www.azerothcore.org>, released under GNU AGPL v3 license, you may redistribute it
* and/or modify it under version 3 of the License, or (at your option), any later version.
*/
#include "Engine.h"
#include "Action.h"
#include "Event.h"
#include "PerformanceMonitor.h"
#include "Playerbots.h"
#include "Queue.h"
#include "Strategy.h"
#include "Timer.h"
Engine::Engine(PlayerbotAI* botAI, AiObjectContext* factory) : PlayerbotAIAware(botAI), aiObjectContext(factory)
{
lastRelevance = 0.0f;
testMode = false;
}
bool ActionExecutionListeners::Before(Action* action, Event event)
{
bool result = true;
for (std::list<ActionExecutionListener*>::iterator i = listeners.begin(); i != listeners.end(); i++)
{
result &= (*i)->Before(action, event);
}
return result;
}
void ActionExecutionListeners::After(Action* action, bool executed, Event event)
{
for (std::list<ActionExecutionListener*>::iterator i = listeners.begin(); i != listeners.end(); i++)
{
(*i)->After(action, executed, event);
}
}
bool ActionExecutionListeners::OverrideResult(Action* action, bool executed, Event event)
{
bool result = executed;
for (std::list<ActionExecutionListener*>::iterator i = listeners.begin(); i != listeners.end(); i++)
{
result = (*i)->OverrideResult(action, result, event);
}
return result;
}
bool ActionExecutionListeners::AllowExecution(Action* action, Event event)
{
bool result = true;
for (std::list<ActionExecutionListener*>::iterator i = listeners.begin(); i != listeners.end(); i++)
{
result &= (*i)->AllowExecution(action, event);
}
return result;
}
ActionExecutionListeners::~ActionExecutionListeners()
{
for (std::list<ActionExecutionListener*>::iterator i = listeners.begin(); i != listeners.end(); i++)
{
delete *i;
}
listeners.clear();
}
Engine::~Engine(void)
{
Reset();
// for (std::map<std::string, Strategy*>::iterator i = strategies.begin(); i != strategies.end(); i++)
// {
// Strategy* strategy = i->second;
// if (strategy) {
// delete strategy;
// }
// }
strategies.clear();
}
void Engine::Reset()
{
strategyTypeMask = 0;
ActionNode* action = nullptr;
while ((action = queue.Pop()) != nullptr)
{
delete action;
}
for (TriggerNode* trigger : triggers)
{
delete trigger;
}
triggers.clear();
for (Multiplier* multiplier : multipliers)
{
delete multiplier;
}
multipliers.clear();
actionNodeFactories.creators.clear();
}
void Engine::Init()
{
Reset();
for (std::map<std::string, Strategy*>::iterator i = strategies.begin(); i != strategies.end(); i++)
{
Strategy* strategy = i->second;
strategyTypeMask |= strategy->GetType();
strategy->InitMultipliers(multipliers);
strategy->InitTriggers(triggers);
for (auto &iter : strategy->actionNodeFactories.creators)
{
actionNodeFactories.creators[iter.first] = iter.second;
}
}
if (testMode)
{
FILE* file = fopen("test.log", "w");
fprintf(file, "\n");
fclose(file);
}
}
bool Engine::DoNextAction(Unit* unit, uint32 depth, bool minimal)
{
LogAction("--- AI Tick ---");
if (sPlayerbotAIConfig->logValuesPerTick)
LogValues();
bool actionExecuted = false;
ActionBasket* basket = nullptr;
time_t currentTime = time(nullptr);
// Update triggers and push default actions
ProcessTriggers(minimal);
PushDefaultActions();
uint32 iterations = 0;
uint32 iterationsPerTick = queue.Size() * (minimal ? 2 : sPlayerbotAIConfig->iterationsPerTick);
while (++iterations <= iterationsPerTick)
{
basket = queue.Peek();
if (!basket)
break;
float relevance = basket->getRelevance(); // for reference
bool skipPrerequisites = basket->isSkipPrerequisites();
if (minimal && (relevance < 100))
continue;
Event event = basket->getEvent();
ActionNode* actionNode = queue.Pop(); // NOTE: Pop() deletes basket
Action* action = InitializeAction(actionNode);
if (!action)
{
LogAction("A:%s - UNKNOWN", actionNode->getName().c_str());
}
else if (action->isUseful())
{
// Apply multipliers early to avoid unnecessary iterations
for (Multiplier* multiplier : multipliers)
{
relevance *= multiplier->GetValue(action);
action->setRelevance(relevance);
if (relevance <= 0)
{
LogAction("Multiplier %s made action %s useless", multiplier->getName().c_str(), action->getName().c_str());
break;
}
}
if (action->isPossible() && relevance > 0)
{
if (!skipPrerequisites)
{
LogAction("A:%s - PREREQ", action->getName().c_str());
if (MultiplyAndPush(actionNode->getPrerequisites(), relevance + 0.002f, false, event, "prereq"))
{
PushAgain(actionNode, relevance + 0.001f, event);
continue;
}
}
PerformanceMonitorOperation* pmo = sPerformanceMonitor->start(PERF_MON_ACTION, action->getName(), &aiObjectContext->performanceStack);
actionExecuted = ListenAndExecute(action, event);
if (pmo)
pmo->finish();
if (actionExecuted)
{
LogAction("A:%s - OK", action->getName().c_str());
MultiplyAndPush(actionNode->getContinuers(), relevance, false, event, "cont");
lastRelevance = relevance;
delete actionNode; // Safe memory management
break;
}
else
{
LogAction("A:%s - FAILED", action->getName().c_str());
MultiplyAndPush(actionNode->getAlternatives(), relevance + 0.003f, false, event, "alt");
}
}
else
{
LogAction("A:%s - IMPOSSIBLE", action->getName().c_str());
MultiplyAndPush(actionNode->getAlternatives(), relevance + 0.003f, false, event, "alt");
}
}
else
{
LogAction("A:%s - USELESS", action->getName().c_str());
lastRelevance = relevance;
}
delete actionNode; // Always delete after processing the action node
}
if (time(nullptr) - currentTime > 1)
{
LogAction("Execution time exceeded 1 second");
}
if (!actionExecuted)
LogAction("no actions executed");
queue.RemoveExpired();
return actionExecuted;
}
ActionNode* Engine::CreateActionNode(std::string const name)
{
ActionNode* node = actionNodeFactories.GetContextObject(name, botAI);
if (node)
return node;
return new ActionNode(name,
/*P*/ nullptr,
/*A*/ nullptr,
/*C*/ nullptr);
}
bool Engine::MultiplyAndPush(NextAction** actions, float forceRelevance, bool skipPrerequisites, Event event,
char const* pushType)
{
bool pushed = false;
if (actions)
{
for (uint32 j = 0; actions[j]; j++)
{
if (NextAction* nextAction = actions[j])
{
ActionNode* action = CreateActionNode(nextAction->getName());
InitializeAction(action);
float k = nextAction->getRelevance();
if (forceRelevance > 0.0f)
{
k = forceRelevance;
}
if (k > 0)
{
LogAction("PUSH:%s - %f (%s)", action->getName().c_str(), k, pushType);
queue.Push(new ActionBasket(action, k, skipPrerequisites, event));
pushed = true;
}
else
{
delete action;
}
delete nextAction;
}
else
break;
}
delete[] actions;
}
return pushed;
}
ActionResult Engine::ExecuteAction(std::string const name, Event event, std::string const qualifier)
{
bool result = false;
ActionNode* actionNode = CreateActionNode(name);
if (!actionNode)
return ACTION_RESULT_UNKNOWN;
Action* action = InitializeAction(actionNode);
if (!action)
{
delete actionNode;
return ACTION_RESULT_UNKNOWN;
}
if (!qualifier.empty())
{
if (Qualified* q = dynamic_cast<Qualified*>(action))
q->Qualify(qualifier);
}
if (!action->isPossible())
{
delete actionNode;
return ACTION_RESULT_IMPOSSIBLE;
}
if (!action->isUseful())
{
delete actionNode;
return ACTION_RESULT_USELESS;
}
action->MakeVerbose();
result = ListenAndExecute(action, event);
MultiplyAndPush(action->getContinuers(), 0.0f, false, event, "default");
delete actionNode;
return result ? ACTION_RESULT_OK : ACTION_RESULT_FAILED;
}
void Engine::addStrategy(std::string const name, bool init)
{
removeStrategy(name, init);
if (Strategy* strategy = aiObjectContext->GetStrategy(name))
{
std::set<std::string> siblings = aiObjectContext->GetSiblingStrategy(name);
for (std::set<std::string>::iterator i = siblings.begin(); i != siblings.end(); i++)
removeStrategy(*i, init);
LogAction("S:+%s", strategy->getName().c_str());
strategies[strategy->getName()] = strategy;
}
if (init)
Init();
}
void Engine::addStrategies(std::string first, ...)
{
addStrategy(first, false);
va_list vl;
va_start(vl, first);
const char* cur;
do
{
cur = va_arg(vl, const char*);
if (cur)
addStrategy(cur, false);
} while (cur);
Init();
va_end(vl);
}
void Engine::addStrategiesNoInit(std::string first, ...)
{
addStrategy(first, false);
va_list vl;
va_start(vl, first);
const char* cur;
do
{
cur = va_arg(vl, const char*);
if (cur)
addStrategy(cur, false);
} while (cur);
va_end(vl);
}
bool Engine::removeStrategy(std::string const name, bool init)
{
std::map<std::string, Strategy*>::iterator i = strategies.find(name);
if (i == strategies.end())
return false;
LogAction("S:-%s", name.c_str());
strategies.erase(i);
if (init)
Init();
return true;
}
void Engine::removeAllStrategies()
{
strategies.clear();
Init();
}
void Engine::toggleStrategy(std::string const name)
{
if (!removeStrategy(name))
addStrategy(name);
}
bool Engine::HasStrategy(std::string const name) { return strategies.find(name) != strategies.end(); }
void Engine::ProcessTriggers(bool minimal)
{
std::unordered_map<Trigger*, Event> fires;
uint32 now = getMSTime();
for (std::vector<TriggerNode*>::iterator i = triggers.begin(); i != triggers.end(); i++)
{
TriggerNode* node = *i;
if (!node)
continue;
Trigger* trigger = node->getTrigger();
if (!trigger)
{
trigger = aiObjectContext->GetTrigger(node->getName());
node->setTrigger(trigger);
}
if (!trigger)
continue;
if (fires.find(trigger) != fires.end())
continue;
if (testMode || trigger->needCheck(now))
{
if (minimal && node->getFirstRelevance() < 100)
continue;
PerformanceMonitorOperation* pmo =
sPerformanceMonitor->start(PERF_MON_TRIGGER, trigger->getName(), &aiObjectContext->performanceStack);
Event event = trigger->Check();
if (pmo)
pmo->finish();
if (!event)
continue;
fires[trigger] = event;
LogAction("T:%s", trigger->getName().c_str());
}
}
for (std::vector<TriggerNode*>::iterator i = triggers.begin(); i != triggers.end(); i++)
{
TriggerNode* node = *i;
Trigger* trigger = node->getTrigger();
if (fires.find(trigger) == fires.end())
continue;
Event event = fires[trigger];
MultiplyAndPush(node->getHandlers(), 0.0f, false, event, "trigger");
}
for (std::vector<TriggerNode*>::iterator i = triggers.begin(); i != triggers.end(); i++)
{
if (Trigger* trigger = (*i)->getTrigger())
trigger->Reset();
}
}
void Engine::PushDefaultActions()
{
for (std::map<std::string, Strategy*>::iterator i = strategies.begin(); i != strategies.end(); i++)
{
Strategy* strategy = i->second;
Event emptyEvent;
MultiplyAndPush(strategy->getDefaultActions(), 0.0f, false, emptyEvent, "default");
}
}
std::string const Engine::ListStrategies()
{
std::string s = "Strategies: ";
if (strategies.empty())
return s;
for (std::map<std::string, Strategy*>::iterator i = strategies.begin(); i != strategies.end(); i++)
{
s.append(i->first);
s.append(", ");
}
return s.substr(0, s.length() - 2);
}
std::vector<std::string> Engine::GetStrategies()
{
std::vector<std::string> result;
for (std::map<std::string, Strategy*>::iterator i = strategies.begin(); i != strategies.end(); i++)
{
result.push_back(i->first);
}
return result;
}
void Engine::PushAgain(ActionNode* actionNode, float relevance, Event event)
{
NextAction** nextAction = new NextAction*[2];
nextAction[0] = new NextAction(actionNode->getName(), relevance);
nextAction[1] = nullptr;
MultiplyAndPush(nextAction, relevance, true, event, "again");
delete actionNode;
}
bool Engine::ContainsStrategy(StrategyType type)
{
for (std::map<std::string, Strategy*>::iterator i = strategies.begin(); i != strategies.end(); i++)
{
if (i->second->GetType() & type)
return true;
}
return false;
}
Action* Engine::InitializeAction(ActionNode* actionNode)
{
Action* action = actionNode->getAction();
if (!action)
{
action = aiObjectContext->GetAction(actionNode->getName());
actionNode->setAction(action);
}
return action;
}
bool Engine::ListenAndExecute(Action* action, Event event)
{
bool actionExecuted = false;
if (actionExecutionListeners.Before(action, event))
{
actionExecuted = actionExecutionListeners.AllowExecution(action, event) ? action->Execute(event) : true;
}
if (botAI->HasStrategy("debug", BOT_STATE_NON_COMBAT))
{
std::ostringstream out;
out << "do: ";
out << action->getName();
if (actionExecuted)
out << " 1 (";
else
out << " 0 (";
out << action->getRelevance() << ")";
if (!event.GetSource().empty())
out << " [" << event.GetSource() << "]";
botAI->TellMasterNoFacing(out);
}
actionExecuted = actionExecutionListeners.OverrideResult(action, actionExecuted, event);
actionExecutionListeners.After(action, actionExecuted, event);
return actionExecuted;
}
void Engine::LogAction(char const* format, ...)
{
Player* bot = botAI->GetBot();
if (sPlayerbotAIConfig->logInGroupOnly && (!bot->GetGroup() || !botAI->HasRealPlayerMaster()) && !testMode)
return;
char buf[1024];
va_list ap;
va_start(ap, format);
vsprintf(buf, format, ap);
va_end(ap);
lastAction += "|";
lastAction += buf;
if (lastAction.size() > 512)
{
lastAction = lastAction.substr(512);
size_t pos = lastAction.find("|");
lastAction = (pos == std::string::npos ? "" : lastAction.substr(pos));
}
if (testMode)
{
FILE* file = fopen("test.log", "a");
fprintf(file, "'%s'", buf);
fprintf(file, "\n");
fclose(file);
}
else
{
LOG_DEBUG("playerbots", "{} {}", bot->GetName().c_str(), buf);
}
}
void Engine::ChangeStrategy(std::string const names)
{
std::vector<std::string> splitted = split(names, ',');
for (std::vector<std::string>::iterator i = splitted.begin(); i != splitted.end(); i++)
{
char const* name = i->c_str();
switch (name[0])
{
case '+':
addStrategy(name + 1);
break;
case '-':
removeStrategy(name + 1);
break;
case '~':
toggleStrategy(name + 1);
break;
case '?':
botAI->TellMaster(ListStrategies());
break;
}
}
}
void Engine::LogValues()
{
if (testMode)
return;
Player* bot = botAI->GetBot();
if (sPlayerbotAIConfig->logInGroupOnly && (!bot->GetGroup() || !botAI->HasRealPlayerMaster()))
return;
std::string const text = botAI->GetAiObjectContext()->FormatValues();
LOG_DEBUG("playerbots", "Values for {}: {}", bot->GetName().c_str(), text.c_str());
}
| 412 | 0.897407 | 1 | 0.897407 | game-dev | MEDIA | 0.891059 | game-dev | 0.965412 | 1 | 0.965412 |
enestoy/PHP-Algorithms-Basics-to-Business | 2,229 | 07-Backtracking/5-Hamiltonian Path/index_en.php | <?php
// Function to check if the Hamiltonian Path is valid for the current step
function isValidHamiltonianPath($graph, $path, $node, $step) {
// If the node has already been visited, it's not valid
for ($i = 0; $i < $step; $i++) {
if ($path[$i] == $node) {
return false;
}
}
// If the node is not a neighbor of the previous node, it's not valid
if ($graph[$path[$step - 1]][$node] == 0) {
return false;
}
return true; // If valid, return true
}
// Backtracking function to find the Hamiltonian Path
function findHamiltonianPath($graph, &$path, $step) {
// If all nodes are visited, a valid path has been found
if ($step == count($graph)) {
return true;
}
// Try each node
for ($node = 0; $node < count($graph); $node++) {
if (isValidHamiltonianPath($graph, $path, $node, $step)) {
// If it's a valid node, add it to the path
$path[$step] = $node;
// Try to find the next step
if (findHamiltonianPath($graph, $path, $step + 1)) {
return true;
}
// If no solution is found, backtrack
$path[$step] = -1;
}
}
// If no solution is found, return false
return false;
}
// Main function: Starts the Hamiltonian Path search
function hamiltonianPathSolver($graph) {
$path = array_fill(0, count($graph), -1); // Initialize the path with no nodes
$path[0] = 0; // Set the first node as the starting point
if (findHamiltonianPath($graph, $path, 1)) {
echo "Hamiltonian Path found:\n";
foreach ($path as $node) {
echo $node . " ";
}
echo "\n";
} else {
echo "No valid Hamiltonian Path found.\n";
}
}
// Example usage (graph is represented as an adjacency matrix)
// Here, each node's neighbors are listed in the matrix.
$graph = [
[0, 1, 0, 1, 0], // Node 0: Neighbors are 1 and 3
[1, 0, 1, 1, 0], // Node 1: Neighbors are 0, 2, and 3
[0, 1, 0, 0, 1], // Node 2: Neighbors are 1 and 4
[1, 1, 0, 0, 0], // Node 3: Neighbors are 0 and 1
[0, 0, 1, 0, 0] // Node 4: Neighbors are 2
];
hamiltonianPathSolver($graph);
?>
| 412 | 0.904057 | 1 | 0.904057 | game-dev | MEDIA | 0.453934 | game-dev | 0.822827 | 1 | 0.822827 |
jmSNU/Isaacsim-Franka | 4,016 | IsaacLab/source/extensions/omni.isaac.lab/omni/isaac/lab/scene/interactive_scene_cfg.py | # Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from dataclasses import MISSING
from omni.isaac.lab.utils.configclass import configclass
@configclass
class InteractiveSceneCfg:
"""Configuration for the interactive scene.
The users can inherit from this class to add entities to their scene. This is then parsed by the
:class:`InteractiveScene` class to create the scene.
.. note::
The adding of entities to the scene is sensitive to the order of the attributes in the configuration.
Please make sure to add the entities in the order you want them to be added to the scene.
The recommended order of specification is terrain, physics-related assets (articulations and rigid bodies),
sensors and non-physics-related assets (lights).
For example, to add a robot to the scene, the user can create a configuration class as follows:
.. code-block:: python
import omni.isaac.lab.sim as sim_utils
from omni.isaac.lab.assets import AssetBaseCfg
from omni.isaac.lab.scene import InteractiveSceneCfg
from omni.isaac.lab.sensors.ray_caster import GridPatternCfg, RayCasterCfg
from omni.isaac.lab.utils import configclass
from omni.isaac.lab_assets.anymal import ANYMAL_C_CFG
@configclass
class MySceneCfg(InteractiveSceneCfg):
# terrain - flat terrain plane
terrain = TerrainImporterCfg(
prim_path="/World/ground",
terrain_type="plane",
)
# articulation - robot 1
robot_1 = ANYMAL_C_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot_1")
# articulation - robot 2
robot_2 = ANYMAL_C_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot_2")
robot_2.init_state.pos = (0.0, 1.0, 0.6)
# sensor - ray caster attached to the base of robot 1 that scans the ground
height_scanner = RayCasterCfg(
prim_path="{ENV_REGEX_NS}/Robot_1/base",
offset=RayCasterCfg.OffsetCfg(pos=(0.0, 0.0, 20.0)),
attach_yaw_only=True,
pattern_cfg=GridPatternCfg(resolution=0.1, size=[1.6, 1.0]),
debug_vis=True,
mesh_prim_paths=["/World/ground"],
)
# extras - light
light = AssetBaseCfg(
prim_path="/World/light",
spawn=sim_utils.DistantLightCfg(intensity=3000.0, color=(0.75, 0.75, 0.75)),
init_state=AssetBaseCfg.InitialStateCfg(pos=(0.0, 0.0, 500.0)),
)
"""
num_envs: int = MISSING
"""Number of environment instances handled by the scene."""
env_spacing: float = MISSING
"""Spacing between environments.
This is the default distance between environment origins in the scene. Used only when the
number of environments is greater than one.
"""
lazy_sensor_update: bool = True
"""Whether to update sensors only when they are accessed. Default is True.
If true, the sensor data is only updated when their attribute ``data`` is accessed. Otherwise, the sensor
data is updated every time sensors are updated.
"""
replicate_physics: bool = True
"""Enable/disable replication of physics schemas when using the Cloner APIs. Default is True.
If True, the simulation will have the same asset instances (USD prims) in all the cloned environments.
Internally, this ensures optimization in setting up the scene and parsing it via the physics stage parser.
If False, the simulation allows having separate asset instances (USD prims) in each environment.
This flexibility comes at a cost of slowdowns in setting up and parsing the scene.
.. note::
Optimized parsing of certain prim types (such as deformable objects) is not currently supported
by the physics engine. In these cases, this flag needs to be set to False.
"""
| 412 | 0.608546 | 1 | 0.608546 | game-dev | MEDIA | 0.532849 | game-dev | 0.532825 | 1 | 0.532825 |
protoman/rockbot | 2,420 | editor/mainwindow_tab/weapon_edit.cpp | #include "weapon_edit.h"
#include "ui_weapon_edit.h"
#include "common.h"
#include "mediator.h"
weapon_edit::weapon_edit(QWidget *parent) :
QWidget(parent),
ui(new Ui::weapon_edit), _selected_weapon(0), _loaded(false)
{
ui->setupUi(this);
reload_weapon_list();
common::fill_weapons_combo(ui->weapon_select_combo);
common::fill_projectiles_combo(ui->weapon_projectile_type);
_loaded = true;
}
weapon_edit::~weapon_edit()
{
delete ui;
}
void weapon_edit::reload()
{
_loaded = false;
_selected_weapon = 0;
reload_weapon_list();
common::fill_weapons_combo(ui->weapon_select_combo);
common::fill_projectiles_combo(ui->weapon_projectile_type);
_loaded = true;
}
void weapon_edit::reload_weapon_list()
{
common::fill_weapons_combo(ui->weapon_select_combo);
}
void weapon_edit::on_weapon_select_combo_currentIndexChanged(int index)
{
_loaded = false;
_selected_weapon = index;
ui->weapon_name->setText(QString(Mediator::get_instance()->game_data.weapons[_selected_weapon].name));
ui->weapon_damage->setValue(Mediator::get_instance()->game_data.weapons[_selected_weapon].damage);
ui->weapon_projectile_type->setCurrentIndex(Mediator::get_instance()->game_data.weapons[_selected_weapon].id_projectile); // +1 because of the -1 default projectile
ui->weapon_charged_projectile_type->setCurrentIndex(Mediator::get_instance()->game_data.weapons[_selected_weapon].id_projectile_charged); // +1 because of the -1 default projectile
_loaded = true;
}
void weapon_edit::on_weapon_name_textChanged(const QString &arg1)
{
if (_loaded == false) {
return;
}
sprintf(Mediator::get_instance()->game_data.weapons[_selected_weapon].name, "%s", arg1.toStdString().c_str());
}
void weapon_edit::on_weapon_projectile_type_currentIndexChanged(int index)
{
if (_loaded == false) {
return;
}
Mediator::get_instance()->game_data.weapons[_selected_weapon].id_projectile = index;
}
void weapon_edit::on_weapon_damage_valueChanged(int arg1)
{
if (_loaded == false) {
return;
}
Mediator::get_instance()->game_data.weapons[_selected_weapon].damage = arg1;
}
void weapon_edit::on_weapon_charged_projectile_type_currentIndexChanged(int index)
{
if (_loaded == false) { return; }
Mediator::get_instance()->game_data.weapons[_selected_weapon].id_projectile_charged = index; //-1 is because default weapon (-1)
}
| 412 | 0.895305 | 1 | 0.895305 | game-dev | MEDIA | 0.975231 | game-dev | 0.530944 | 1 | 0.530944 |
klikli-dev/occultism | 2,434 | src/main/java/com/klikli_dev/occultism/api/common/data/SortType.java | /*
* MIT License
*
* Copyright 2020 klikli-dev
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
* OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
package com.klikli_dev.occultism.api.common.data;
import com.mojang.serialization.Codec;
import io.netty.buffer.ByteBuf;
import it.unimi.dsi.fastutil.objects.Object2ObjectArrayMap;
import net.minecraft.network.codec.ByteBufCodecs;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.util.ByIdMap;
import net.minecraft.util.StringRepresentable;
import java.util.Map;
import java.util.function.IntFunction;
public enum SortType implements StringRepresentable {
AMOUNT,
NAME,
MOD;
private static final Map<String, SortType> TYPES = new Object2ObjectArrayMap<>();
public static final Codec<SortType> CODEC = Codec.stringResolver(SortType::getSerializedName, TYPES::get);
public static final IntFunction<SortType> BY_ID = ByIdMap.continuous(Enum::ordinal, SortType.values(), ByIdMap.OutOfBoundsStrategy.WRAP);
public static final StreamCodec<ByteBuf, SortType> STREAM_CODEC = ByteBufCodecs.idMapper(BY_ID, Enum::ordinal);
static {
for (SortType type : values()) {
TYPES.put(type.getSerializedName(), type);
}
}
@Override
public String getSerializedName() {
return this.name().toLowerCase();
}
public SortType next() {
return values()[(this.ordinal() + 1) % SortType.values().length];
}
}
| 412 | 0.758463 | 1 | 0.758463 | game-dev | MEDIA | 0.532527 | game-dev | 0.817795 | 1 | 0.817795 |
Team-Beef-Studios/JKXR | 23,236 | Projects/Android/jni/OpenJK/code/game/NPC_move.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/>.
===========================================================================
*/
//
// NPC_move.cpp
//
#include "b_local.h"
#include "g_nav.h"
#include "anims.h"
#include "g_navigator.h"
extern qboolean NPC_ClearPathToGoal( vec3_t dir, gentity_t *goal );
extern qboolean NAV_MoveDirSafe( gentity_t *self, usercmd_t *cmd, float distScale = 1.0f );
qboolean G_BoundsOverlap(const vec3_t mins1, const vec3_t maxs1, const vec3_t mins2, const vec3_t maxs2);
extern int GetTime ( int lastTime );
navInfo_t frameNavInfo;
extern qboolean FlyingCreature( gentity_t *ent );
extern qboolean PM_InKnockDown( playerState_t *ps );
extern cvar_t *g_navSafetyChecks;
extern qboolean Boba_Flying( gentity_t *self );
extern qboolean PM_InRoll( playerState_t *ps );
#define APEX_HEIGHT 200.0f
#define PARA_WIDTH (sqrt(APEX_HEIGHT)+sqrt(APEX_HEIGHT))
#define JUMP_SPEED 200.0f
static qboolean NPC_TryJump();
static qboolean NPC_Jump( vec3_t dest, int goalEntNum )
{//FIXME: if land on enemy, knock him down & jump off again
float targetDist, travelTime, impactDist, bestImpactDist = Q3_INFINITE;//fireSpeed,
float originalShotSpeed, shotSpeed, speedStep = 50.0f, minShotSpeed = 30.0f, maxShotSpeed = 500.0f;
qboolean belowBlocked = qfalse, aboveBlocked = qfalse;
vec3_t targetDir, shotVel, failCase;
trace_t trace;
trajectory_t tr;
qboolean blocked;
int elapsedTime, timeStep = 250, hitCount = 0, aboveTries = 0, belowTries = 0, maxHits = 10;
vec3_t lastPos, testPos, bottom;
VectorSubtract( dest, NPC->currentOrigin, targetDir );
targetDist = VectorNormalize( targetDir );
//make our shotSpeed reliant on the distance
originalShotSpeed = targetDist;//DistanceHorizontal( dest, NPC->currentOrigin )/2.0f;
if ( originalShotSpeed > maxShotSpeed )
{
originalShotSpeed = maxShotSpeed;
}
else if ( originalShotSpeed < minShotSpeed )
{
originalShotSpeed = minShotSpeed;
}
shotSpeed = originalShotSpeed;
while ( hitCount < maxHits )
{
VectorScale( targetDir, shotSpeed, shotVel );
travelTime = targetDist/shotSpeed;
shotVel[2] += travelTime * 0.5 * NPC->client->ps.gravity;
if ( !hitCount )
{//save the first one as the worst case scenario
VectorCopy( shotVel, failCase );
}
if ( 1 )//tracePath )
{//do a rough trace of the path
blocked = qfalse;
VectorCopy( NPC->currentOrigin, tr.trBase );
VectorCopy( shotVel, tr.trDelta );
tr.trType = TR_GRAVITY;
tr.trTime = level.time;
travelTime *= 1000.0f;
VectorCopy( NPC->currentOrigin, lastPos );
//This may be kind of wasteful, especially on long throws... use larger steps? Divide the travelTime into a certain hard number of slices? Trace just to apex and down?
for ( elapsedTime = timeStep; elapsedTime < floor(travelTime)+timeStep; elapsedTime += timeStep )
{
if ( (float)elapsedTime > travelTime )
{//cap it
elapsedTime = floor( travelTime );
}
EvaluateTrajectory( &tr, level.time + elapsedTime, testPos );
//FUCK IT, always check for do not enter...
gi.trace( &trace, lastPos, NPC->mins, NPC->maxs, testPos, NPC->s.number, NPC->clipmask|CONTENTS_BOTCLIP, (EG2_Collision)0, 0 );
/*
if ( testPos[2] < lastPos[2]
&& elapsedTime < floor( travelTime ) )
{//going down, haven't reached end, ignore botclip
gi.trace( &trace, lastPos, NPC->mins, NPC->maxs, testPos, NPC->s.number, NPC->clipmask );
}
else
{//going up, check for botclip
gi.trace( &trace, lastPos, NPC->mins, NPC->maxs, testPos, NPC->s.number, NPC->clipmask|CONTENTS_BOTCLIP );
}
*/
if ( trace.allsolid || trace.startsolid )
{//started in solid
if ( NAVDEBUG_showCollision )
{
CG_DrawEdge( lastPos, trace.endpos, EDGE_RED_TWOSECOND );
}
return qfalse;//you're hosed, dude
}
if ( trace.fraction < 1.0f )
{//hit something
if ( NAVDEBUG_showCollision )
{
CG_DrawEdge( lastPos, trace.endpos, EDGE_RED_TWOSECOND ); // TryJump
}
if ( trace.entityNum == goalEntNum )
{//hit the enemy, that's bad!
blocked = qtrue;
/*
if ( g_entities[goalEntNum].client && g_entities[goalEntNum].client->ps.groundEntityNum == ENTITYNUM_NONE )
{//bah, would collide in mid-air, no good
blocked = qtrue;
}
else
{//he's on the ground, good enough, I guess
//Hmm, don't want to land on him, though...?
}
*/
break;
}
else
{
if ( trace.contents & CONTENTS_BOTCLIP )
{//hit a do-not-enter brush
blocked = qtrue;
break;
}
if ( trace.plane.normal[2] > 0.7 && DistanceSquared( trace.endpos, dest ) < 4096 )//hit within 64 of desired location, should be okay
{//close enough!
break;
}
else
{//FIXME: maybe find the extents of this brush and go above or below it on next try somehow?
impactDist = DistanceSquared( trace.endpos, dest );
if ( impactDist < bestImpactDist )
{
bestImpactDist = impactDist;
VectorCopy( shotVel, failCase );
}
blocked = qtrue;
break;
}
}
}
else
{
if ( NAVDEBUG_showCollision )
{
CG_DrawEdge( lastPos, testPos, EDGE_WHITE_TWOSECOND ); // TryJump
}
}
if ( elapsedTime == floor( travelTime ) )
{//reached end, all clear
if ( trace.fraction >= 1.0f )
{//hmm, make sure we'll land on the ground...
//FIXME: do we care how far below ourselves or our dest we'll land?
VectorCopy( trace.endpos, bottom );
bottom[2] -= 128;
gi.trace( &trace, trace.endpos, NPC->mins, NPC->maxs, bottom, NPC->s.number, NPC->clipmask, (EG2_Collision)0, 0 );
if ( trace.fraction >= 1.0f )
{//would fall too far
blocked = qtrue;
}
}
break;
}
else
{
//all clear, try next slice
VectorCopy( testPos, lastPos );
}
}
if ( blocked )
{//hit something, adjust speed (which will change arc)
hitCount++;
//alternate back and forth between trying an arc slightly above or below the ideal
if ( (hitCount%2) && !belowBlocked )
{//odd
belowTries++;
shotSpeed = originalShotSpeed - (belowTries*speedStep);
}
else if ( !aboveBlocked )
{//even
aboveTries++;
shotSpeed = originalShotSpeed + (aboveTries*speedStep);
}
else
{//can't go any higher or lower
hitCount = maxHits;
break;
}
if ( shotSpeed > maxShotSpeed )
{
shotSpeed = maxShotSpeed;
aboveBlocked = qtrue;
}
else if ( shotSpeed < minShotSpeed )
{
shotSpeed = minShotSpeed;
belowBlocked = qtrue;
}
}
else
{//made it!
break;
}
}
else
{//no need to check the path, go with first calc
break;
}
}
if ( hitCount >= maxHits )
{//NOTE: worst case scenario, use the one that impacted closest to the target (or just use the first try...?)
return qfalse;
//NOTE: or try failcase?
//VectorCopy( failCase, NPC->client->ps.velocity );
//return qtrue;
}
VectorCopy( shotVel, NPC->client->ps.velocity );
return qtrue;
}
#define NPC_JUMP_PREP_BACKUP_DIST 34.0f
trace_t mJumpTrace;
qboolean NPC_CanTryJump()
{
if (!(NPCInfo->scriptFlags&SCF_NAV_CAN_JUMP) || // Can't Jump
(NPCInfo->scriptFlags&SCF_NO_ACROBATICS) || // If Can't Jump At All
(level.time<NPCInfo->jumpBackupTime) || // If Backing Up, Don't Try The Jump Again
(level.time<NPCInfo->jumpNextCheckTime) || // Don't Even Try To Jump Again For This Amount Of Time
(NPCInfo->jumpTime) || // Don't Jump If Already Going
(PM_InKnockDown(&NPC->client->ps)) || // Don't Jump If In Knockdown
(PM_InRoll(&NPC->client->ps)) || // ... Or Roll
(NPC->client->ps.groundEntityNum==ENTITYNUM_NONE) // ... Or In The Air
)
{
return qfalse;
}
return qtrue;
}
qboolean NPC_TryJump(const vec3_t& pos, float max_xy_dist, float max_z_diff)
{
if (NPC_CanTryJump())
{
NPCInfo->jumpNextCheckTime = level.time + Q_irand(1000, 2000);
VectorCopy(pos, NPCInfo->jumpDest);
// Can't Try To Jump At A Point In The Air
//-----------------------------------------
{
vec3_t groundTest;
VectorCopy(pos, groundTest);
groundTest[2] += (NPC->mins[2]*3);
gi.trace(&mJumpTrace, NPCInfo->jumpDest, vec3_origin, vec3_origin, groundTest, NPC->s.number, NPC->clipmask, (EG2_Collision)0, 0 );
if (mJumpTrace.fraction >= 1.0f)
{
return qfalse; //no ground = no jump
}
}
NPCInfo->jumpTarget = 0;
NPCInfo->jumpMaxXYDist = (max_xy_dist)?(max_xy_dist):((NPC->client->NPC_class==CLASS_ROCKETTROOPER)?1200:750);
NPCInfo->jumpMazZDist = (max_z_diff)?(max_z_diff):((NPC->client->NPC_class==CLASS_ROCKETTROOPER)?-1000:-450);
NPCInfo->jumpTime = 0;
NPCInfo->jumpBackupTime = 0;
return NPC_TryJump();
}
return qfalse;
}
qboolean NPC_TryJump(gentity_t *goal, float max_xy_dist, float max_z_diff)
{
if (NPC_CanTryJump())
{
NPCInfo->jumpNextCheckTime = level.time + Q_irand(1000, 3000);
// Can't Jump At Targets In The Air
//---------------------------------
if (goal->client && goal->client->ps.groundEntityNum==ENTITYNUM_NONE)
{
return qfalse;
}
VectorCopy(goal->currentOrigin, NPCInfo->jumpDest);
NPCInfo->jumpTarget = goal;
NPCInfo->jumpMaxXYDist = (max_xy_dist)?(max_xy_dist):((NPC->client->NPC_class==CLASS_ROCKETTROOPER)?1200:750);
NPCInfo->jumpMazZDist = (max_z_diff)?(max_z_diff):((NPC->client->NPC_class==CLASS_ROCKETTROOPER)?-1000:-400);
NPCInfo->jumpTime = 0;
NPCInfo->jumpBackupTime = 0;
return NPC_TryJump();
}
return qfalse;
}
void NPC_JumpAnimation()
{
int jumpAnim = BOTH_JUMP1;
if ( NPC->client->NPC_class == CLASS_BOBAFETT
|| (NPC->client->NPC_class == CLASS_REBORN && NPC->s.weapon != WP_SABER)
|| NPC->client->NPC_class == CLASS_ROCKETTROOPER
||( NPCInfo->rank != RANK_CREWMAN && NPCInfo->rank <= RANK_LT_JG ) )
{//can't do acrobatics
jumpAnim = BOTH_FORCEJUMP1;
}
else if (NPC->client->NPC_class != CLASS_HOWLER)
{
if ( NPC->client->NPC_class == CLASS_ALORA && Q_irand( 0, 3 ) )
{
jumpAnim = Q_irand( BOTH_ALORA_FLIP_1, BOTH_ALORA_FLIP_3 );
}
else
{
jumpAnim = BOTH_FLIP_F;
}
}
NPC_SetAnim( NPC, SETANIM_BOTH, jumpAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD );
}
extern void JET_FlyStart(gentity_t* actor);
void NPC_JumpSound()
{
if ( NPC->client->NPC_class == CLASS_HOWLER )
{
//FIXME: can I delay the actual jump so that it matches the anim...?
}
else if ( NPC->client->NPC_class == CLASS_BOBAFETT
|| NPC->client->NPC_class == CLASS_ROCKETTROOPER )
{
// does this really need to be here?
JET_FlyStart(NPC);
}
else
{
G_SoundOnEnt( NPC, CHAN_BODY, "sound/weapons/force/jump.wav" );
}
}
qboolean NPC_TryJump()
{
vec3_t targetDirection;
float targetDistanceXY;
float targetDistanceZ;
// Get The Direction And Distances To The Target
//-----------------------------------------------
VectorSubtract(NPCInfo->jumpDest, NPC->currentOrigin, targetDirection);
targetDirection[2] = 0.0f;
targetDistanceXY = VectorNormalize(targetDirection);
targetDistanceZ = NPCInfo->jumpDest[2] - NPC->currentOrigin[2];
if ((targetDistanceXY>NPCInfo->jumpMaxXYDist) ||
(targetDistanceZ<NPCInfo->jumpMazZDist))
{
return qfalse;
}
// Test To See If There Is A Wall Directly In Front Of Actor, If So, Backup Some
//-------------------------------------------------------------------------------
if (TIMER_Done(NPC, "jumpBackupDebounce"))
{
vec3_t actorProjectedTowardTarget;
VectorMA(NPC->currentOrigin, NPC_JUMP_PREP_BACKUP_DIST, targetDirection, actorProjectedTowardTarget);
gi.trace(&mJumpTrace, NPC->currentOrigin, vec3_origin, vec3_origin, actorProjectedTowardTarget, NPC->s.number, NPC->clipmask, (EG2_Collision)0, 0);
if ((mJumpTrace.fraction < 1.0f) ||
(mJumpTrace.allsolid) ||
(mJumpTrace.startsolid))
{
if (NAVDEBUG_showCollision)
{
CG_DrawEdge(NPC->currentOrigin, actorProjectedTowardTarget, EDGE_RED_TWOSECOND); // TryJump
}
// TODO: We may want to test to see if it is safe to back up here?
NPCInfo->jumpBackupTime = level.time + 1000;
TIMER_Set(NPC, "jumpBackupDebounce", 5000);
return qtrue;
}
}
// bool Wounded = (NPC->health < 150);
// bool OnLowerLedge = ((targetDistanceZ<-80.0f) && (targetDistanceZ>-200.0f));
// bool WithinNormalJumpRange = ((targetDistanceZ<32.0f) && (targetDistanceXY<200.0f));
bool WithinForceJumpRange = ((fabsf(targetDistanceZ)>0) || (targetDistanceXY>128));
/* if (Wounded && OnLowerLedge)
{
ucmd.forwardmove = 127;
VectorClear(NPC->client->ps.moveDir);
TIMER_Set(NPC, "duck", -level.time);
return qtrue;
}
if (WithinNormalJumpRange)
{
ucmd.upmove = 127;
ucmd.forwardmove = 127;
VectorClear(NPC->client->ps.moveDir);
TIMER_Set(NPC, "duck", -level.time);
return qtrue;
}
*/
if (!WithinForceJumpRange)
{
return qfalse;
}
// If There Is Any Chance That This Jump Will Land On An Enemy, Try 8 Different Traces Around The Target
//-------------------------------------------------------------------------------------------------------
if (NPCInfo->jumpTarget)
{
float minSafeRadius = (NPC->maxs[0]*1.5f) + (NPCInfo->jumpTarget->maxs[0]*1.5f);
float minSafeRadiusSq = (minSafeRadius * minSafeRadius);
if (DistanceSquared(NPCInfo->jumpDest, NPCInfo->jumpTarget->currentOrigin)<minSafeRadiusSq)
{
vec3_t startPos;
vec3_t floorPos;
VectorCopy(NPCInfo->jumpDest, startPos);
floorPos[2] = NPCInfo->jumpDest[2] + (NPC->mins[2]-32);
for (int sideTryCount=0; sideTryCount<8; sideTryCount++)
{
NPCInfo->jumpSide++;
if ( NPCInfo->jumpSide > 7 )
{
NPCInfo->jumpSide = 0;
}
switch ( NPCInfo->jumpSide )
{
case 0:
NPCInfo->jumpDest[0] = startPos[0] + minSafeRadius;
NPCInfo->jumpDest[1] = startPos[1];
break;
case 1:
NPCInfo->jumpDest[0] = startPos[0] + minSafeRadius;
NPCInfo->jumpDest[1] = startPos[1] + minSafeRadius;
break;
case 2:
NPCInfo->jumpDest[0] = startPos[0];
NPCInfo->jumpDest[1] = startPos[1] + minSafeRadius;
break;
case 3:
NPCInfo->jumpDest[0] = startPos[0] - minSafeRadius;
NPCInfo->jumpDest[1] = startPos[1] + minSafeRadius;
break;
case 4:
NPCInfo->jumpDest[0] = startPos[0] - minSafeRadius;
NPCInfo->jumpDest[1] = startPos[1];
break;
case 5:
NPCInfo->jumpDest[0] = startPos[0] - minSafeRadius;
NPCInfo->jumpDest[1] = startPos[1] - minSafeRadius;
break;
case 6:
NPCInfo->jumpDest[0] = startPos[0];
NPCInfo->jumpDest[1] = startPos[1] - minSafeRadius;
break;
case 7:
NPCInfo->jumpDest[0] = startPos[0] + minSafeRadius;
NPCInfo->jumpDest[1] = startPos[1] -=minSafeRadius;
break;
}
floorPos[0] = NPCInfo->jumpDest[0];
floorPos[1] = NPCInfo->jumpDest[1];
gi.trace(&mJumpTrace, NPCInfo->jumpDest, NPC->mins, NPC->maxs, floorPos, (NPCInfo->jumpTarget)?(NPCInfo->jumpTarget->s.number):(NPC->s.number), (NPC->clipmask|CONTENTS_BOTCLIP), (EG2_Collision)0, 0);
if ((mJumpTrace.fraction<1.0f) &&
(!mJumpTrace.allsolid) &&
(!mJumpTrace.startsolid))
{
break;
}
if ( NAVDEBUG_showCollision )
{
CG_DrawEdge( NPCInfo->jumpDest, floorPos, EDGE_RED_TWOSECOND );
}
}
// If All Traces Failed, Just Try Going Right Back At The Target Location
//------------------------------------------------------------------------
if ((mJumpTrace.fraction>=1.0f) ||
(mJumpTrace.allsolid) ||
(mJumpTrace.startsolid))
{
VectorCopy(startPos, NPCInfo->jumpDest);
}
}
}
// Now, Actually Try The Jump To The Dest Target
//-----------------------------------------------
if (NPC_Jump(NPCInfo->jumpDest, (NPCInfo->jumpTarget)?(NPCInfo->jumpTarget->s.number):(NPC->s.number)))
{
// We Made IT!
//-------------
NPC_JumpAnimation();
NPC_JumpSound();
NPC->client->ps.forceJumpZStart = NPC->currentOrigin[2];
NPC->client->ps.pm_flags |= PMF_JUMPING;
NPC->client->ps.weaponTime = NPC->client->ps.torsoAnimTimer;
NPC->client->ps.forcePowersActive |= ( 1 << FP_LEVITATION );
ucmd.forwardmove = 0;
NPCInfo->jumpTime = 1;
VectorClear(NPC->client->ps.moveDir);
TIMER_Set(NPC, "duck", -level.time);
return qtrue;
}
return qfalse;
}
qboolean NPC_Jumping()
{
if ( NPCInfo->jumpTime )
{
if ( !(NPC->client->ps.pm_flags & PMF_JUMPING )//forceJumpZStart )
&& !(NPC->client->ps.pm_flags&PMF_TRIGGER_PUSHED))
{//landed
NPCInfo->jumpTime = 0;
}
else
{
// if (NPCInfo->jumpTarget)
// {
// NPC_FaceEntity(NPCInfo->jumpTarget, qtrue);
// }
// else
{
NPC_FacePosition(NPCInfo->jumpDest, qtrue);
}
return qtrue;
}
}
return qfalse;
}
qboolean NPC_JumpBackingUp()
{
if (NPCInfo->jumpBackupTime)
{
if (level.time<NPCInfo->jumpBackupTime)
{
STEER::Activate(NPC);
STEER::Flee(NPC, NPCInfo->jumpDest);
STEER::DeActivate(NPC, &ucmd);
NPC_FacePosition(NPCInfo->jumpDest, qtrue);
NPC_UpdateAngles( qfalse, qtrue );
return qtrue;
}
NPCInfo->jumpBackupTime = 0;
return NPC_TryJump();
}
return qfalse;
}
/*
-------------------------
NPC_CheckCombatMove
-------------------------
*/
inline qboolean NPC_CheckCombatMove( void )
{
//return NPCInfo->combatMove;
if ( ( NPCInfo->goalEntity && NPC->enemy && NPCInfo->goalEntity == NPC->enemy ) || ( NPCInfo->combatMove ) )
{
return qtrue;
}
if ( NPCInfo->goalEntity && NPCInfo->watchTarget )
{
if ( NPCInfo->goalEntity != NPCInfo->watchTarget )
{
return qtrue;
}
}
return qfalse;
}
/*
-------------------------
NPC_LadderMove
-------------------------
*/
static void NPC_LadderMove( vec3_t dir )
{
//FIXME: this doesn't guarantee we're facing ladder
//ALSO: Need to be able to get off at top
//ALSO: Need to play an anim
//ALSO: Need transitionary anims?
if ( ( dir[2] > 0 ) || ( dir[2] < 0 && NPC->client->ps.groundEntityNum == ENTITYNUM_NONE ) )
{
//Set our movement direction
ucmd.upmove = (dir[2] > 0) ? 127 : -127;
//Don't move around on XY
ucmd.forwardmove = ucmd.rightmove = 0;
}
}
/*
-------------------------
NPC_GetMoveInformation
-------------------------
*/
inline qboolean NPC_GetMoveInformation( vec3_t dir, float *distance )
{
//NOTENOTE: Use path stacks!
//Make sure we have somewhere to go
if ( NPCInfo->goalEntity == NULL )
return qfalse;
//Get our move info
VectorSubtract( NPCInfo->goalEntity->currentOrigin, NPC->currentOrigin, dir );
*distance = VectorNormalize( dir );
VectorCopy( NPCInfo->goalEntity->currentOrigin, NPCInfo->blockedTargetPosition );
return qtrue;
}
/*
-------------------------
NAV_GetLastMove
-------------------------
*/
void NAV_GetLastMove( navInfo_t &info )
{
info = frameNavInfo;
}
void G_UcmdMoveForDir( gentity_t *self, usercmd_t *cmd, vec3_t dir )
{
vec3_t forward, right;
AngleVectors( self->currentAngles, forward, right, NULL );
dir[2] = 0;
VectorNormalize( dir );
//NPCs cheat and store this directly because converting movement into a ucmd loses precision
VectorCopy( dir, self->client->ps.moveDir );
float fDot = DotProduct( forward, dir ) * 127.0f;
float rDot = DotProduct( right, dir ) * 127.0f;
//Must clamp this because DotProduct is not guaranteed to return a number within -1 to 1, and that would be bad when we're shoving this into a signed byte
if ( fDot > 127.0f )
{
fDot = 127.0f;
}
if ( fDot < -127.0f )
{
fDot = -127.0f;
}
if ( rDot > 127.0f )
{
rDot = 127.0f;
}
if ( rDot < -127.0f )
{
rDot = -127.0f;
}
cmd->forwardmove = floor(fDot);
cmd->rightmove = floor(rDot);
/*
vec3_t wishvel;
for ( int i = 0 ; i < 3 ; i++ )
{
wishvel[i] = forward[i]*cmd->forwardmove + right[i]*cmd->rightmove;
}
VectorNormalize( wishvel );
if ( !VectorCompare( wishvel, dir ) )
{
Com_Printf( "PRECISION LOSS: %s != %s\n", vtos(wishvel), vtos(dir) );
}
*/
}
/*
-------------------------
NPC_MoveToGoal
Now assumes goal is goalEntity, was no reason for it to be otherwise
-------------------------
*/
#if AI_TIMERS
extern int navTime;
#endif// AI_TIMERS
qboolean NPC_MoveToGoal( qboolean tryStraight ) //FIXME: tryStraight not even used! Stop passing it
{
#if AI_TIMERS
int startTime = GetTime(0);
#endif// AI_TIMERS
if ( PM_InKnockDown( &NPC->client->ps ) || ( ( NPC->client->ps.legsAnim >= BOTH_PAIN1 ) && ( NPC->client->ps.legsAnim <= BOTH_PAIN18 ) && NPC->client->ps.legsAnimTimer > 0 ) )
{//If taking full body pain, don't move
return qtrue;
}
if( NPC->s.eFlags & EF_LOCKED_TO_WEAPON )
{//If in an emplaced gun, never try to navigate!
return qtrue;
}
if( NPC->s.eFlags & EF_HELD_BY_RANCOR )
{//If in a rancor's hand, never try to navigate!
return qtrue;
}
if( NPC->s.eFlags & EF_HELD_BY_WAMPA )
{//If in a wampa's hand, never try to navigate!
return qtrue;
}
if( NPC->s.eFlags & EF_HELD_BY_SAND_CREATURE )
{//If in a worm's mouth, never try to navigate!
return qtrue;
}
if ( NPC->watertype & CONTENTS_LADDER )
{//Do we still want to do this?
vec3_t dir;
VectorSubtract( NPCInfo->goalEntity->currentOrigin, NPC->currentOrigin, dir );
VectorNormalize( dir );
NPC_LadderMove( dir );
}
bool moveSuccess = true;
STEER::Activate(NPC);
{
// Attempt To Steer Directly To Our Goal
//---------------------------------------
moveSuccess = STEER::GoTo(NPC, NPCInfo->goalEntity, NPCInfo->goalRadius);
// Perhaps Not Close Enough? Try To Use The Navigation Grid
//-----------------------------------------------------------
if (!moveSuccess)
{
moveSuccess = NAV::GoTo(NPC, NPCInfo->goalEntity);
if (!moveSuccess)
{
STEER::Stop(NPC);
}
}
}
STEER::DeActivate(NPC, &ucmd);
#if AI_TIMERS
navTime += GetTime( startTime );
#endif// AI_TIMERS
return (qboolean)moveSuccess;
}
/*
-------------------------
void NPC_SlideMoveToGoal( void )
Now assumes goal is goalEntity, if want to use tempGoal, you set that before calling the func
-------------------------
*/
qboolean NPC_SlideMoveToGoal( void )
{
float saveYaw = NPC->client->ps.viewangles[YAW];
NPCInfo->combatMove = qtrue;
qboolean ret = NPC_MoveToGoal( qtrue );
NPCInfo->desiredYaw = saveYaw;
return ret;
}
/*
-------------------------
NPC_ApplyRoff
-------------------------
*/
void NPC_ApplyRoff(void)
{
PlayerStateToEntityState( &NPC->client->ps, &NPC->s );
VectorCopy ( NPC->currentOrigin, NPC->lastOrigin );
// use the precise origin for linking
gi.linkentity(NPC);
}
| 412 | 0.956902 | 1 | 0.956902 | game-dev | MEDIA | 0.990369 | game-dev | 0.992764 | 1 | 0.992764 |
cloudstateio/cloudstate | 10,498 | node-support/test/crdts/ormap-test.js | /*
* Copyright 2019 Lightbend Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const should = require("chai").should();
const protobuf = require("protobufjs");
const path = require("path");
const crdts = require("../../src/crdts");
const ORMap = crdts.ORMap;
const protobufHelper = require("../../src/protobuf-helper");
const AnySupport = require("../../src/protobuf-any");
const CrdtDelta = protobufHelper.moduleRoot.cloudstate.crdt.CrdtDelta;
const root = new protobuf.Root();
root.loadSync(path.join(__dirname, "..", "example.proto"));
root.resolveAll();
const Example = root.lookupType("com.example.Example");
const anySupport = new AnySupport(root);
function roundTripDelta(delta) {
return CrdtDelta.decode(CrdtDelta.encode(delta).finish());
}
function toAny(value) {
return AnySupport.serialize(value, true, true)
}
function fromAnys(values) {
return values.map(any => anySupport.deserialize(any));
}
function fromEntries(entries) {
return entries.map(entry => {
return {
key: anySupport.deserialize(entry.key),
delta: entry.delta
}
});
}
function toMapCounterEntry(key, value) {
return { key: toAny(key), delta: { gcounter: { increment : value } } };
}
describe("ORMap", () => {
it("should have no elements when instantiated", () => {
const map = new ORMap();
map.size.should.equal(0);
should.equal(map.getAndResetDelta(), null);
});
it("should reflect an initial delta", () => {
const map = new ORMap();
map.applyDelta(roundTripDelta({
ormap: {
added: [toMapCounterEntry("one", 5), toMapCounterEntry("two", 7)]
}
}), anySupport, crdts.createCrdtForDelta);
map.size.should.equal(2);
new Set(map.keys()).should.include("one", "two");
map.asObject.one.value.should.equal(5);
map.asObject.two.value.should.equal(7);
should.equal(map.getAndResetDelta(), null);
});
it("should generate an add delta", () => {
const map = new ORMap().set("one", new crdts.GCounter());
map.has("one").should.be.true;
map.size.should.equal(1);
const delta1 = roundTripDelta(map.getAndResetDelta());
delta1.ormap.added.should.have.lengthOf(1);
const entry = fromEntries(delta1.ormap.added)[0];
entry.key.should.equal("one");
entry.delta.gcounter.increment.toNumber().should.equal(0);
should.equal(map.getAndResetDelta(), null);
map.asObject.two = new crdts.GCounter();
map.asObject.two.increment(10);
map.size.should.equal(2);
const delta2 = roundTripDelta(map.getAndResetDelta());
delta2.ormap.added.should.have.lengthOf(1);
const entry2 = fromEntries(delta2.ormap.added)[0];
entry2.key.should.equal("two");
entry2.delta.gcounter.increment.toNumber().should.equal(10);
should.equal(map.getAndResetDelta(), null);
delta2.ormap.updated.should.have.lengthOf(0);
});
it("should generate a remove delta", () => {
const map = new ORMap()
.set("one", new crdts.GCounter())
.set("two", new crdts.GCounter())
.set("three", new crdts.GCounter());
map.getAndResetDelta();
map.has("one").should.be.true;
map.has("two").should.be.true;
map.has("three").should.be.true;
map.size.should.equal(3);
map.delete("one").delete("two");
map.size.should.equal(1);
map.has("three").should.be.true;
map.has("one").should.be.false;
map.has("two").should.be.false;
const delta = roundTripDelta(map.getAndResetDelta());
delta.ormap.removed.should.have.lengthOf(2);
fromAnys(delta.ormap.removed).should.include.members(["one", "two"]);
should.equal(map.getAndResetDelta(), null);
});
it("should generate an update delta", () => {
const map = new ORMap().set("one", new crdts.GCounter());
map.getAndResetDelta();
map.get("one").increment(5);
const delta = roundTripDelta(map.getAndResetDelta());
delta.ormap.updated.should.have.lengthOf(1);
const entry = fromEntries(delta.ormap.updated)[0];
entry.key.should.equal("one");
entry.delta.gcounter.increment.toNumber().should.equal(5);
should.equal(map.getAndResetDelta(), null);
});
it("should generate a clear delta", () => {
const map = new ORMap()
.set("one", new crdts.GCounter())
.set("two", new crdts.GCounter());
map.getAndResetDelta();
map.clear().size.should.equal(0);
const delta = roundTripDelta(map.getAndResetDelta());
delta.ormap.cleared.should.be.true;
should.equal(map.getAndResetDelta(), null);
});
it("should generate a clear delta when everything is removed", () => {
const map = new ORMap()
.set("one", new crdts.GCounter())
.set("two", new crdts.GCounter());
map.getAndResetDelta();
map.delete("one").delete("two").size.should.equal(0);
const delta = roundTripDelta(map.getAndResetDelta());
delta.ormap.cleared.should.be.true;
should.equal(map.getAndResetDelta(), null);
});
it("should not generate a delta when an added element is removed", () => {
const map = new ORMap()
.set("one", new crdts.GCounter());
map.getAndResetDelta();
map.set("two", new crdts.GCounter()).delete("two").size.should.equal(1);
should.equal(map.getAndResetDelta(), null);
});
it("should generate a delta when a removed element is added", () => {
const map = new ORMap()
.set("one", new crdts.GCounter())
.set("two", new crdts.GCounter());
map.getAndResetDelta();
map.delete("two").set("two", new crdts.GCounter()).size.should.equal(2);
const delta = roundTripDelta(map.getAndResetDelta());
delta.ormap.removed.should.have.lengthOf(1);
delta.ormap.added.should.have.lengthOf(1);
delta.ormap.updated.should.have.lengthOf(0);
});
it("should generate a delta when an already existing element is set", () => {
const map = new ORMap()
.set("one", new crdts.GCounter());
map.getAndResetDelta();
map.set("one", new crdts.GCounter()).size.should.equal(1);
const delta = roundTripDelta(map.getAndResetDelta());
delta.ormap.removed.should.have.lengthOf(1);
delta.ormap.added.should.have.lengthOf(1);
delta.ormap.updated.should.have.lengthOf(0);
});
it("should not generate a delta when a non existing element is removed", () => {
const map = new ORMap()
.set("one", new crdts.GCounter());
map.getAndResetDelta();
map.delete("two").size.should.equal(1);
should.equal(map.getAndResetDelta(), null);
});
it("should generate a delta when an already existing element is set", () => {
const map = new ORMap()
.set("one", new crdts.GCounter());
map.getAndResetDelta();
map.set("one", new crdts.GCounter()).size.should.equal(1);
const delta = roundTripDelta(map.getAndResetDelta());
delta.ormap.removed.should.have.lengthOf(1);
delta.ormap.added.should.have.lengthOf(1);
delta.ormap.updated.should.have.lengthOf(0);
});
it("clear all other deltas when the set is cleared", () => {
const map = new ORMap().set("one", new crdts.GCounter())
.set("two", new crdts.GCounter());
map.getAndResetDelta();
map.asObject.two.increment(10);
map.set("one", new crdts.GCounter()).clear().size.should.equal(0);
const delta = roundTripDelta(map.getAndResetDelta());
delta.ormap.cleared.should.be.true;
delta.ormap.added.should.have.lengthOf(0);
delta.ormap.removed.should.have.lengthOf(0);
delta.ormap.updated.should.have.lengthOf(0);
});
it("should reflect a delta add", () => {
const map = new ORMap()
.set("one", new crdts.GCounter());
map.getAndResetDelta();
map.applyDelta(roundTripDelta({
ormap: {
added: [ { key: toAny("two"), delta : {
gcounter: { increment: 4 }
} } ]
}
}), anySupport, crdts.createCrdtForDelta);
map.size.should.equal(2);
new Set(map.keys()).should.include("one", "two");
map.asObject.two.value.should.equal(4);
should.equal(map.getAndResetDelta(), null);
});
it("should reflect a delta remove", () => {
const map = new ORMap()
.set("one", new crdts.GCounter())
.set("two", new crdts.GCounter());
map.getAndResetDelta();
map.applyDelta(roundTripDelta({
ormap: {
removed: [toAny("two")]
}
}), anySupport);
map.size.should.equal(1);
new Set(map.keys()).should.include("one");
should.equal(map.getAndResetDelta(), null);
});
it("should reflect a delta clear", () => {
const map = new ORMap()
.set("one", new crdts.GCounter())
.set("two", new crdts.GCounter());
map.getAndResetDelta();
map.applyDelta(roundTripDelta({
ormap: {
cleared: true
}
}), anySupport);
map.size.should.equal(0);
should.equal(map.getAndResetDelta(), null);
});
it("should work with protobuf keys", () => {
const map = new ORMap()
.set(Example.create({ field1: "one" }), new crdts.GCounter())
.set(Example.create({ field1: "two" }), new crdts.GCounter());
map.getAndResetDelta();
map.delete(Example.create({ field1: "one" }));
map.size.should.equal(1);
const delta = roundTripDelta(map.getAndResetDelta());
delta.ormap.removed.should.have.lengthOf(1);
fromAnys(delta.ormap.removed)[0].field1.should.equal("one");
});
it("should work with json types", () => {
const map = new ORMap()
.set({ foo: "bar" }, new crdts.GCounter())
.set({ foo: "baz" }, new crdts.GCounter());
map.getAndResetDelta();
map.delete({ foo: "bar" });
map.size.should.equal(1);
const delta = roundTripDelta(map.getAndResetDelta());
delta.ormap.removed.should.have.lengthOf(1);
fromAnys(delta.ormap.removed)[0].foo.should.equal("bar");
});
it("should support empty initial deltas (for ORMap added)", () => {
const map = new ORMap();
map.size.should.equal(0);
should.equal(map.getAndResetDelta(), null);
roundTripDelta(map.getAndResetDelta(/* initial = */ true)).ormap.added.should.have.lengthOf(0);
});
});
| 412 | 0.852753 | 1 | 0.852753 | game-dev | MEDIA | 0.338087 | game-dev | 0.906138 | 1 | 0.906138 |
GDACollab/Malisense | 9,116 | Assets/Scripts/Item Scripts/MagicHandScript.cs | using Pathfinding.Util;
using System.Collections;
using System.Data;
using UnityEngine;
using UnityEngine.InputSystem;
public class MagicHandScript : MonoBehaviour
{
private static MagicHandScript Instance;
public Artifact MagicHand;
[SerializeField] float maxDistance = 14f;
[SerializeField] float minCooldown = 5;
[SerializeField] float maxCooldown = 60;
PlayerInput playerInput;
InputAction moveAction, interactAction;
Rigidbody2D rb;
SpriteRenderer sprite;
public GameObject handAsset;
public Color hoverTint;
public Color lineColor;
Collider2D currentHover;
GameObject player;
LineRenderer line;
private void Start()
{
player = GameObject.FindGameObjectWithTag("Player");
sprite = handAsset.GetComponent<SpriteRenderer>();
playerInput = player.GetComponent<PlayerInput>();
line = GetComponent<LineRenderer>();
rb = GetComponent<Rigidbody2D>();
moveAction = playerInput.actions.FindAction("8 Directions Movement");
interactAction = playerInput.actions.FindAction("Interact");
if (MagicHand.cooldown > 0.0f) {
player.GetComponent<Player>().canMove = true;
if(Instance){
Instance.end(minCooldown);
}
Destroy(gameObject);
return;
}
else
{
player.GetComponent<Player>().canMove = false;
}
if(MagicHand.duration == 1)
{
if(Instance){
Instance.end(minCooldown);
}
Destroy(gameObject);
return;
}
GameObject.FindGameObjectWithTag("MainCamera").GetComponent<SmartCamera>().SetTarget(gameObject);
MagicHand.duration = 1;
currentHover = null;
// Disable player movement
if (player == null) Debug.LogError("No player found in scene, Magic hand script");
Instance = this;
// Sync movement
}
private void Update()
{
// Check for movement
float moveX = moveAction.ReadValue<Vector2>().x;
float moveY = moveAction.ReadValue<Vector2>().y;
Vector2 direction = new Vector2(moveX, moveY).normalized;
if (direction != Vector2.zero)
{
Quaternion rot = Quaternion.LookRotation(Vector3.forward, direction);
handAsset.transform.rotation = Quaternion.RotateTowards(handAsset.transform.rotation, rot, 700f * Time.deltaTime);
Vector2 newPos = rb.position + direction * Time.deltaTime * 10f;
Vector3[] pos = { rb.position, player.transform.position };
line.SetPositions(pos);
lineColor.r = (Vector2.Distance(newPos, player.transform.position) / maxDistance);
lineColor.b = 1-(Vector2.Distance(newPos, player.transform.position) / maxDistance);
lineColor.a = Vector2.Distance(newPos, player.transform.position) / maxDistance;
line.startColor = lineColor;
line.endColor = lineColor;
if (Vector2.Distance(newPos, player.transform.position) < maxDistance)
{
rb.MovePosition(newPos);
}
}
if (interactAction.triggered && currentHover != null)
{
if (currentHover.GetComponent<StateMachine>() && currentHover.GetComponent<StateMachine>().currentState != StateMachine.State.Distracted) // If Enemy
{
currentHover.GetComponent<StateMachine>().currentState = StateMachine.State.Distracted;
end(maxCooldown);
}
else if (currentHover.GetComponent<SwitchController>() && !currentHover.GetComponent<CarnelianEarthquake>()) // If Switch
{
currentHover.GetComponent<SwitchController>().ActivateSwitch();
}
else if (currentHover.GetComponent<ItemPickup>()) // If Item
{
ItemPickup x = currentHover.GetComponent<ItemPickup>();
bool success = player.GetComponent<Player>().newInventory.AddItem(x.item, 1);
if (success)
{
Destroy(x.gameObject);
}
}
}
if (interactAction.triggered && currentHover == null)
{
end(minCooldown);
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
StopAllCoroutines();
if (collision.GetComponent<StateMachine>() && collision.GetComponent<StateMachine>().currentState != StateMachine.State.Distracted) // If Enemy
{
currentHover = collision;
sprite.color = hoverTint;
} else if (collision.GetComponent<SwitchController>() && !collision.GetComponent<CarnelianEarthquake>()) // If Switch
{
currentHover = collision;
sprite.color = hoverTint;
} else if (collision.GetComponent<ItemPickup>()) // If Item
{
currentHover = collision;
sprite.color = hoverTint;
}
}
private void OnTriggerExit2D(Collider2D collision)
{
StopAllCoroutines();
if (gameObject.activeInHierarchy)
{
StartCoroutine("Grace");
}
}
IEnumerator Grace()
{
yield return new WaitForSeconds(0.1f);
sprite.color = Color.white;
currentHover = null;
}
private void end(float cooldown)
{
MagicHand.duration = 0;
player.GetComponent<Player>().canMove = true;
MagicHand.cooldown = cooldown;
GameObject.FindGameObjectWithTag("MainCamera").GetComponent<SmartCamera>().SetTarget(player);
Destroy(gameObject);
}
/*//Magic hand can be controlled to move around ala the player, so it needs to spawn a new object that you control instead of the player for a short period
//This script is the one run when the artifact is used, and spawns (and despawns) the hand that the player controls
public float MagicHandCooldown;
public float MagicHandDuration;
public GameObject controllableHand;
public Artifact MagicHand;
GameObject spawnedObject;
GameObject player;
//float timer = 0;
// Start is called before the first frame update
void Start()
{
Debug.Log("in the hand");
//below line (just the one) literally copied and pasted from WhisperingBellArtifact.cs
player = GameObject.FindGameObjectWithTag("Player").GetComponent<Player>().canMove = true;
if (MagicHand.duration > 0.0f || MagicHand.cooldown > 0.0f)
{
if (MagicHand.duration > 0.0f)
{
//Get rid of the prev hand
GameObject prevHand = GameObject.FindGameObjectWithTag("Magic Hand");
Destroy(prevHand);
MagicHand.cooldown = MagicHandCooldown * (1 - (MagicHand.duration / MagicHandDuration)); //cooldown inversely proportional to how long hand has been out
MagicHand.duration = 0.0f;
}
player.GetComponent<Player>().canMove = true;
Destroy(gameObject);
}
}
//(modified from whispering bell artifact code for consistency)
// When using editor, clears all previous runtime values of the object
private void OnValidate()
{
MagicHand.duration = 0.0f;
MagicHand.cooldown = 0.0f;
}
// Update is called once per frame
void Update()
{
if (MagicHand.duration == 0 && MagicHand.cooldown == 0) //first frame of existing
{
//Debug.Log("starting");
stealPlayerInput();
MagicHand.duration = MagicHandDuration;
}
else if (MagicHand.duration > 0)
{
//Debug.Log("decr duration");
*//*
timer += Time.deltaTime;
if(timer > MagicHandDuration)
{
timer = 0;
returnPlayerInput();
}
*//*
MagicHand.duration -= Time.deltaTime;
if (MagicHand.duration <= 0)
{
MagicHand.duration = 0;
returnPlayerInput();
}
}
else if (MagicHand.cooldown >= 0)
{
//Debug.Log("decr cooldown");
MagicHand.cooldown -= Time.deltaTime;
if (MagicHand.cooldown <= 0)
{
MagicHand.cooldown = 0;
Destroy(gameObject);
}
}
//Debug.Log("why is cooldown not saying it's >= 0");
}
void stealPlayerInput()
{
Debug.Log("Stealing Player input");
player.GetComponent<Player>().canMove = false;
spawnedObject = Instantiate(controllableHand, player.transform.position, Quaternion.identity);
}
void returnPlayerInput()
{
Debug.Log("Returning Player input");
player.GetComponent<Player>().canMove = true;
MagicHand.cooldown = MagicHandCooldown;
Destroy(spawnedObject);
//Destroy(gameObject);
}*/
} | 412 | 0.94778 | 1 | 0.94778 | game-dev | MEDIA | 0.989752 | game-dev | 0.993598 | 1 | 0.993598 |
EverestAPI/Everest | 6,177 | Celeste.Mod.mm/Mod/Everest/Everest.LuaLoader.Caches.cs | using KeraLua;
using NLua;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace Celeste.Mod {
public static partial class Everest {
public static partial class LuaLoader {
public class CachedNamespace {
public readonly string Name;
public readonly CachedNamespace Parent;
public readonly string FullName;
public readonly Dictionary<string, CachedNamespace> NamespaceMap = new Dictionary<string, CachedNamespace>();
public CachedNamespace[] Namespaces => NamespaceMap.Values.ToArray();
public readonly Dictionary<string, CachedType> TypeMap = new Dictionary<string, CachedType>();
public CachedType[] Types => TypeMap.Values.ToArray();
public int Count => NamespaceMap.Count + TypeMap.Count;
public CachedNamespace(CachedNamespace ns, string name) {
Name = name;
Parent = ns;
FullName = ns?.Name == null ? name : (ns.FullName + "." + name);
}
public CachedNamespace GetNamespace(string key) {
if (NamespaceMap.TryGetValue(key, out CachedNamespace value))
return value;
return null;
}
public CachedType GetType(string key) {
if (TypeMap.TryGetValue(key, out CachedType value))
return value;
return null;
}
}
public class CachedType {
public readonly string Name;
public readonly CachedNamespace Namespace;
public readonly CachedType Parent;
public readonly string FullName;
public readonly Type Type;
public readonly Dictionary<string, CachedType> NestedTypeMap = new Dictionary<string, CachedType>();
public CachedType[] NestedTypes => NestedTypeMap.Values.ToArray();
private LuaTable nilMemberTable;
private Dictionary<string, LuaTable> membersCache;
private CachedType(Type type) {
Name = type.Name;
Type = type;
FullName = type.FullName;
_Crawl();
}
public CachedType(CachedNamespace ns, Type type)
: this(type) {
Namespace = ns;
}
public CachedType(CachedType parent, Type type)
: this(type) {
Parent = parent;
}
private void _Crawl() {
foreach (Type type in Type.GetNestedTypes()) {
if (!type.IsNestedPublic)
continue;
string part = type.Name;
CachedType ctype = new CachedType(this, type);
NestedTypeMap[part] = ctype;
AllTypes[ctype.FullName] = ctype;
}
}
public LuaTable GetMembers(string key) {
if (membersCache == null) {
// Populate cache with PUBLIC members (the old code used all members but only public ones are actually accesible through NLua)
membersCache = new Dictionary<string, LuaTable>();
foreach (MemberInfo info in Type.GetMembers(BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance)) {
Type mtype = (info as PropertyInfo)?.PropertyType ?? (info as FieldInfo)?.FieldType;
// Cache regular name
string name = info.Name;
if (!membersCache.TryGetValue(name, out LuaTable entry)) {
entry = NewTable();
entry[1] = NewTable();
entry[2] = mtype;
membersCache.Add(name, entry);
}
InsertIntoTable((LuaTable) entry[1], info);
// Cache Lua-ified name
string luaName = string.Empty;
for (int i = 0; i < name.Length; i++) {
if (char.IsLower(name[i]))
break;
luaName += char.ToLower(name[i]);
}
luaName += name.Substring(luaName.Length);
if (name != luaName) {
if (!membersCache.TryGetValue(luaName, out LuaTable luaEntry)) {
luaEntry = NewTable();
luaEntry[1] = NewTable();
luaEntry[2] = mtype;
membersCache.Add(luaName, luaEntry);
}
InsertIntoTable((LuaTable) luaEntry[1], info);
}
}
}
// Lookup in cache
if (membersCache.TryGetValue(key, out LuaTable memberTable))
return memberTable;
if (nilMemberTable == null) {
nilMemberTable = NewTable();
nilMemberTable[1] = nilMemberTable[2] = null;
}
return nilMemberTable;
}
private static LuaTable NewTable() {
Context.State.NewTable();
return new LuaTable(Context.State.Ref(LuaRegistry.Index), Context);
}
// This could be otpimized but eh
private static void InsertIntoTable(LuaTable table, object val) => table[table.Keys.Count + 1] = val;
}
}
}
}
| 412 | 0.918168 | 1 | 0.918168 | game-dev | MEDIA | 0.230536 | game-dev | 0.941245 | 1 | 0.941245 |
ncsoft/Unreal.js-core | 2,770 | Source/JavascriptEditor/JavascriptAssetTypeActions.cpp | #include "JavascriptAssetTypeActions.h"
#if WITH_EDITOR
#include "AssetTypeActions_Base.h"
#include "JavascriptAssetEditorToolkit.h"
#include "JavascriptUIExtender.h"
#include "Misc/MessageDialog.h"
#endif
UJavascriptAssetTypeActions::UJavascriptAssetTypeActions(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
#if WITH_EDITOR
, bRegistered(false)
#endif
{
}
#if WITH_EDITOR
void UJavascriptAssetTypeActions::BeginDestroy()
{
Super::BeginDestroy();
Discard();
}
void UJavascriptAssetTypeActions::Commit()
{
Discard();
IJavascriptEditorModule::Get().AddExtension(this);
bRegistered = true;
}
void UJavascriptAssetTypeActions::Discard()
{
if (bRegistered)
{
IJavascriptEditorModule::Get().RemoveExtension(this);
}
bRegistered = false;
}
void UJavascriptAssetTypeActions::Refresh()
{
if (bRegistered)
{
Unregister();
Register();
}
}
class FAssetTypeActions_Javascript : public FAssetTypeActions_Base
{
public:
UJavascriptAssetTypeActions* Owner;
FAssetTypeActions_Javascript(UJavascriptAssetTypeActions* InOwner)
: Owner(InOwner)
{
}
~FAssetTypeActions_Javascript()
{
}
// IAssetTypeActions interface
virtual FText GetName() const override
{
return Owner->ActionsName;
}
virtual FColor GetTypeColor() const override
{
return Owner->Color;
}
virtual UClass* GetSupportedClass() const override
{
return Owner->SupportedClass;
}
virtual bool HasActions(const TArray<UObject*>& InObjects) const override
{
return Owner->Actions != nullptr;
}
virtual void GetActions(const TArray<UObject*>& InObjects, FMenuBuilder& MenuBuilder) override
{
if (Owner->Actions)
{
Owner->Actions->BuildMenu(MenuBuilder);
}
}
virtual void OpenAssetEditor(const TArray<UObject*>& InObjects, TSharedPtr<IToolkitHost> EditWithinLevelEditor)
{
if (Owner->Editor)
{
Owner->Editor->Open(InObjects, EditWithinLevelEditor);
}
else
{
FMessageDialog::Open(EAppMsgType::Ok, FText::FromString(TEXT("Not implemented")));
}
}
virtual uint32 GetCategories() override
{
return EAssetTypeCategories::Gameplay;
}
};
void UJavascriptAssetTypeActions::Register()
{
if (SupportedClass != nullptr)
{
Instance = MakeShareable(new FAssetTypeActions_Javascript(this));
IAssetTools& AssetTools = FModuleManager::LoadModuleChecked<FAssetToolsModule>("AssetTools").Get();
AssetTools.RegisterAssetTypeActions(Instance.ToSharedRef());
}
}
void UJavascriptAssetTypeActions::Unregister()
{
if (FModuleManager::Get().IsModuleLoaded("AssetTools"))
{
IAssetTools& AssetTools = FModuleManager::LoadModuleChecked<FAssetToolsModule>("AssetTools").Get();
if (Instance.IsValid())
{
AssetTools.UnregisterAssetTypeActions(Instance.ToSharedRef());
}
Instance.Reset();
}
}
#endif | 412 | 0.859787 | 1 | 0.859787 | game-dev | MEDIA | 0.677424 | game-dev | 0.869772 | 1 | 0.869772 |
ShuangYu1145/Faiths-Fix | 1,569 | src/main/java/net/minecraft/item/ItemEmptyMap.java | package net.minecraft.item;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Items;
import net.minecraft.stats.StatList;
import net.minecraft.world.World;
import net.minecraft.world.storage.MapData;
public class ItemEmptyMap extends ItemMapBase
{
protected ItemEmptyMap()
{
this.setCreativeTab(CreativeTabs.tabMisc);
}
/**
* Called whenever this item is equipped and the right mouse button is pressed. Args: itemStack, world, entityPlayer
*/
public ItemStack onItemRightClick(ItemStack itemStackIn, World worldIn, EntityPlayer playerIn)
{
ItemStack itemstack = new ItemStack(Items.filled_map, 1, worldIn.getUniqueDataId("map"));
String s = "map_" + itemstack.getMetadata();
MapData mapdata = new MapData(s);
worldIn.setItemData(s, mapdata);
mapdata.scale = 0;
mapdata.calculateMapCenter(playerIn.posX, playerIn.posZ, mapdata.scale);
mapdata.dimension = (byte)worldIn.provider.getDimensionId();
mapdata.markDirty();
--itemStackIn.stackSize;
if (itemStackIn.stackSize <= 0)
{
return itemstack;
}
else
{
if (!playerIn.inventory.addItemStackToInventory(itemstack.copy()))
{
playerIn.dropPlayerItemWithRandomChoice(itemstack, false);
}
playerIn.triggerAchievement(StatList.objectUseStats[Item.getIdFromItem(this)]);
return itemStackIn;
}
}
}
| 412 | 0.674549 | 1 | 0.674549 | game-dev | MEDIA | 0.988291 | game-dev | 0.957495 | 1 | 0.957495 |
ProjectIgnis/CardScripts | 1,543 | official/c34566435.lua | --エッジインプ・DTモドキ
--Edge Imp Frightfuloid
local s,id=GetID()
function s.initial_effect(c)
--Increase ATK
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(id,0))
e1:SetCategory(CATEGORY_ATKCHANGE)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetRange(LOCATION_MZONE)
e1:SetCountLimit(1,id)
e1:SetTarget(s.target)
e1:SetOperation(s.operation)
c:RegisterEffect(e1)
end
s.listed_series={SET_FRIGHTFUR}
function s.filter(c)
return (c:IsLocation(LOCATION_GRAVE) or c:IsFaceup()) and c:IsType(TYPE_FUSION) and c:IsSetCard(SET_FRIGHTFUR)
end
function s.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsControler(tp) and chkc:IsLocation(LOCATION_MZONE|LOCATION_GRAVE) and s.filter(chkc) end
if chk==0 then return Duel.IsExistingTarget(s.filter,tp,LOCATION_MZONE|LOCATION_GRAVE,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP)
Duel.SelectTarget(tp,s.filter,tp,LOCATION_MZONE|LOCATION_GRAVE,0,1,1,nil)
end
function s.operation(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local tc=Duel.GetFirstTarget()
if c:IsRelateToEffect(e) and c:IsFaceup() and tc and tc:IsRelateToEffect(e) and (tc:IsLocation(LOCATION_GRAVE) or tc:IsFaceup()) then
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_SET_ATTACK_FINAL)
e1:SetValue(tc:GetBaseAttack())
e1:SetReset(RESETS_STANDARD_PHASE_END)
c:RegisterEffect(e1)
local e2=e1:Clone()
e2:SetCode(EFFECT_SET_DEFENSE_FINAL)
e2:SetValue(tc:GetBaseDefense())
c:RegisterEffect(e2)
end
end | 412 | 0.924806 | 1 | 0.924806 | game-dev | MEDIA | 0.986437 | game-dev | 0.781625 | 1 | 0.781625 |
bamboo/unityscript | 2,482 | src/UnityScript.Tests/MonoBehaviour.boo | namespace UnityScript.Tests
import System.Collections
struct Vector3:
x as single
y as single
z as single
def constructor(x_ as single, y_ as single, z_ as single):
x = x_
y = y_
z = z_
class Component:
def GetComponentsInChildren[of T]() as T:
return typeof(T)()
def GetComponentsInChildren[of T](instantiate as bool) as T:
if instantiate: return typeof(T)()
struct Bounds:
def IntersectRay(ray as Ray, ref result as single):
result = 42.0
return true
def IntersectRay(ray as Ray):
return true
struct Ray:
[property(position)]
m_Position as Vector3
class Transform(Component):
[property(position)]
m_Position = Vector3()
[getter(collider)]
m_Collider = Collider()
class Collider(Component):
[getter(bounds)]
m_Bounds = Bounds()
class ComponentFoo(Component):
def Foo():
print "foo"
[property(fooFloat)]
_fooFloat as single = 0.0;
[property(fooVector3)]
_fooVector3 = Vector3();
class ComponentBar(Component):
def Bar():
print "bar"
enum AttributeMaskEnum:
None = 0
Foo = 1
Bar = 2
class AttributeWithMask (System.Attribute):
[getter(mask)]
_mask = AttributeMaskEnum.None
def constructor(a as AttributeMaskEnum):
_mask = a
class ImplicitBoolTest:
bool_casted = false
def constructor(a as bool):
bool_casted = a
public static def op_Implicit (test as ImplicitBoolTest) as bool:
return test.bool_casted
class MonoBehaviour(Component):
_foo = ComponentFoo()
_bar = ComponentBar()
def constructor():
// make sure UnityRuntimeServices is initialized
// just by accessing the Initialized field
// we're triggering initialization
assert UnityScript.Lang.UnityRuntimeServices.Initialized
[getter(transform)]
m_Transform = Transform()
def StartCoroutine_Auto(routine as IEnumerator):
print("Received coroutine")
routine.MoveNext()
return routine.Current
[TypeInferenceRule(TypeInferenceRules.TypeReferencedByFirstArgument)]
def InferredGetComponent(type as System.Type) as Component:
return GetComponent(type)
def GetComponent(type as System.Type) as Component:
return _foo if ComponentFoo is type
return _bar
def GetComponents(type as System.Type) as (Component):
return (GetComponent(type),)
[DuckTyped]
def implicit_bool_test_false() as ImplicitBoolTest:
return ImplicitBoolTest (false)
[DuckTyped]
def implicit_bool_test_true() as ImplicitBoolTest:
return ImplicitBoolTest (true)
class Time:
static time as single:
get:
return 2.0
| 412 | 0.806459 | 1 | 0.806459 | game-dev | MEDIA | 0.465898 | game-dev | 0.757405 | 1 | 0.757405 |
AxioDL/metaforce | 1,090 | Runtime/MP1/CAudioStateWin.cpp | #include "CAudioStateWin.hpp"
#include "Runtime/CArchitectureMessage.hpp"
#include "Runtime/CArchitectureQueue.hpp"
#include "Runtime/CGameState.hpp"
#include "Runtime/GameGlobalObjects.hpp"
#include "Runtime/Audio/CSfxManager.hpp"
#include "Runtime/MP1/MP1.hpp"
namespace metaforce::MP1 {
CIOWin::EMessageReturn CAudioStateWin::OnMessage(const CArchitectureMessage& msg, CArchitectureQueue& queue) {
CMain* m = static_cast<CMain*>(g_Main);
const EArchMsgType msgType = msg.GetType();
if (msgType == EArchMsgType::SetGameState) {
CSfxManager::KillAll(CSfxManager::ESfxChannels::Game);
CSfxManager::TurnOnChannel(CSfxManager::ESfxChannels::Game);
} else if (msgType == EArchMsgType::QuitGameplay) {
if (g_GameState->GetWorldTransitionManager()->GetTransType() == CWorldTransManager::ETransType::Disabled ||
m->GetFlowState() != EClientFlowStates::None) {
CSfxManager::SetChannel(CSfxManager::ESfxChannels::Default);
CSfxManager::KillAll(CSfxManager::ESfxChannels::Game);
}
}
return EMessageReturn::Normal;
}
} // namespace metaforce::MP1
| 412 | 0.796667 | 1 | 0.796667 | game-dev | MEDIA | 0.893849 | game-dev | 0.771585 | 1 | 0.771585 |
MrWalkmanDev/AdaptiSound | 7,400 | addons/AdaptiSound/DEMO/Scenes/DemoScene.gd | extends Node2D
@onready var current_playback_label = %CurrentPlayback
#region TRACK_1
## -------------------------------------------------------------------------------------------------
#############
## TRACK 1 ##
#############
var track_1_name : String = "example_1"
## AudioInteractivePlayList Methods
## This button plays the track from the beginning
func _on_play_track_1_pressed():
## I execute the play function from the AudioManager, passing the track_name,
## volume_db, fade_in and fade_out. The track name is the one assigned in the Audio Panel,
## The fade_out parameter is applied to the track before the new one,
## this way you can create a cross fade effect using fade_in and fade_out parameters.
## I create a variable to save the AudioPlayer, since I will use it later.
var track : AdaptiNode
## Now i check if AudioManager is already playing a previous track,
## because if there is no track playing previously I want the new track to start without fading in
if !AudioManager.current_playback:
track = AudioManager.play_music(track_1_name, 0.0)
## And if there is a previous track then I want to apply a crossfade,
## assigning the fade_in and fade_out time after the volume parameter.
else:
track = AudioManager.play_music(track_1_name, 0.0, 0.7, 1.0)
## NOTE: The play_music method defaults to 0.0db volume, fade_in 0.0, and fade_out 0.0.
## Therefore, there is no crossfade if no fade time is assigned.
## Get resource of currently playing clip.
## In this case, I use the clip change signal to change the color of the
## buttons when changing clips.
if !track.ClipChanged.is_connected(clip_changed):
track.ClipChanged.connect(clip_changed)
clip_changed(track.current_playback_resource)
current_playback_label.text = "Current Playback: " + track_1_name
## Buttons to change the clip to play
func _on_play_clip_0_pressed():
## To change a clip you need to name the track it belongs to, and the clip index.
## (It can also be the name given in the clip resource)
AudioManager.change_clip(track_1_name, 0)
func _on_play_clip_1_pressed():
AudioManager.change_clip(track_1_name, 1)
func _on_play_clip_2_pressed():
## In this line I used the track name instead of the index
AudioManager.change_clip(track_1_name, "Loop2")
func _on_play_clip_3_pressed():
## I set the can_be_interrupted variable manually to prevent a switch
## to another clip on the same track.
## This variable can be changed in the AudioEditroPreview,
## but in this case I change it manually as an example
AudioManager.set_can_be_interrupted(track_1_name, "Outro", false)
AudioManager.change_clip(track_1_name, 3)
#endregion
#region TRACK_2
## -------------------------------------------------------------------------------------------------
#############
## TRACK 2 ##
#############
var track_2_name : String = "example_3"
## AudioSynchronized Methods
## This button plays the track from the beginning
func _on_play_track_2_pressed():
## The same methods are always used
var track : AdaptiNode
track = AudioManager.play_music(track_2_name, 0.0, 0.7, 1.0)
## Every time this track plays I want it to start with only layer 1 active,
## so I'll mute all the other layers and leave only layer 1.
AudioManager.mute_all_layers(true, 0.0)
AudioManager.mute_layer("Layer 0", false, 0.7)
## In this case, with this function I update the state of the track layer buttons.
## It's just a visual aid to know which layer is playing and which isn't.
layer_buttons_update(track)
current_playback_label.text = "Current Playback: " + track_2_name
## Buttons to activate the different layers
## You can use the layer index, or the name.
func _on_layer_1_track_2_toggled(toggled_on):
AudioManager.mute_layer(0, !toggled_on)
func _on_layer_2_track_2_toggled(toggled_on):
AudioManager.mute_layer(1, !toggled_on)
func _on_layer_3_track_2_toggled(toggled_on):
AudioManager.mute_layer(2, !toggled_on)
## In this case I used the layer name as an example.
func _on_layer_4_track_toggled(toggled_on):
AudioManager.mute_layer("Layer 3", !toggled_on)
#endregion
#region TRACK_3
## -------------------------------------------------------------------------------------------------
#############
## TRACK 3 ##
#############
var track_3_name : String = "ChillMusic"
## This is the simplest track, I just call the play_music method to play the track.
func _on_play_pressed():
## In this case it will always start with a crossfade, and set the volume to 2.0db
AudioManager.play_music(track_3_name, 2.0, 0.7, 1.0)
## Visuals
current_playback_label.text = "Current Playback: " + track_3_name
#endregion
#region TRACK_4
## -------------------------------------------------------------------------------------------------
#############
## TRACK 4 ##
#############
## This track is an AudioInteractivePlaylist, but with the shuffle option enabled.
var track_4_name : String = "Sequence"
func _on_track_4_play_pressed() -> void:
var track = AudioManager.play_music(track_4_name, 0.0, 0.7, 1.0)
## I connect the signal to the clip changed to better visualize which track is playing
if !track.ClipChanged.is_connected(track_4_clip_changed):
track.ClipChanged.connect(track_4_clip_changed)
track_4_clip_changed(track.current_playback_resource)
#endregion
func _on_bgm_stop_pressed() -> void:
AudioManager.stop_music(0.5)
## -----------------------------------------------------------------------------------------------
## Stop all tracks. In this case with a fade out of 0.5 sec.
func _on_stop_track_1_pressed():
AudioManager.stop_all(0.5)
set_visual_button(null)
## -----------------------------------------------------------------------------------------------
## BUTTONS VISUALS ##
func clip_changed(clip_res:AdaptiClipResource):
if clip_res:
if clip_res.clip_name == "Intro":
set_visual_button(%Play_clip0)
elif clip_res.clip_name == "Loop1":
set_visual_button(%Play_clip1)
elif clip_res.clip_name == "Loop2":
set_visual_button(%Play_clip2)
elif clip_res.clip_name == "Outro":
set_visual_button(%Play_clip3)
func set_visual_button(node, container:=%Track1):
for i in container.get_children():
i.modulate = "#ffffff"
if node:
node.modulate = Color.GREEN
func layer_buttons_update(track:AdaptiNode):
var audio_players = track.get_children()
%Layer1_track2.button_pressed = !audio_players[0].on_mute
%Layer2_track2.button_pressed = !audio_players[1].on_mute
%Layer3_track2.button_pressed = !audio_players[2].on_mute
%Layer4_track2.button_pressed = !audio_players[3].on_mute
func track_4_clip_changed(clip_res:AdaptiClipResource):
if clip_res:
if clip_res.clip_name == "Clip1":
set_visual_button(%Label1, %Track4Clips)
elif clip_res.clip_name == "Clip2":
set_visual_button(%Label2, %Track4Clips)
elif clip_res.clip_name == "Clip3":
set_visual_button(%Label3, %Track4Clips)
elif clip_res.clip_name == "Clip4":
set_visual_button(%Label4, %Track4Clips)
## ------------------------------------------------------------------------------------------------
## BGS Channel ##
func _on_forest_pressed() -> void:
AudioManager.play_sound("Forest", -3.0)
func _on_rain_pressed() -> void:
AudioManager.play_sound("Rain", -3.0)
func _on_wind_pressed() -> void:
AudioManager.play_sound("Wind", 3.0)
func _on_bgs_stop_pressed() -> void:
AudioManager.stop_sound(2.0)
| 412 | 0.916853 | 1 | 0.916853 | game-dev | MEDIA | 0.507225 | game-dev | 0.9377 | 1 | 0.9377 |
b1inkie/dst-api | 6,227 | scripts_619045/components/fishingrod.lua | local function ontarget(self, target)
self.inst.replica.fishingrod:SetTarget(target)
end
local function onhookedfish(self, hookedfish)
self.inst.replica.fishingrod:SetHookedFish(hookedfish)
end
local function oncaughtfish(self, caughtfish)
self.inst.replica.fishingrod:SetCaughtFish(caughtfish)
end
local FishingRod = Class(function(self, inst)
self.inst = inst
--V2C: Recommended to explicitly add tag to prefab pristine state
inst:AddTag("fishingrod")
self.target = nil
self.fisherman = nil
self.hookedfish = nil
self.caughtfish = nil
self.minwaittime = 0
self.maxwaittime = 10
self.minstraintime = 0
self.maxstraintime = 6
self.fishtask = nil
end,
nil,
{
target = ontarget,
hookedfish = onhookedfish,
caughtfish = oncaughtfish,
})
local function DoNibble(inst)
local fishingrod = inst.components.fishingrod
if fishingrod and fishingrod.fisherman then
inst:PushEvent("fishingnibble")
fishingrod.fisherman:PushEvent("fishingnibble")
fishingrod.fishtask = nil
end
end
local function DoLoseRod(inst)
local fishingrod = inst.components.fishingrod
if fishingrod and fishingrod.fisherman then
inst:PushEvent("fishingloserod")
fishingrod.fisherman:PushEvent("fishingloserod")
fishingrod.fishtask = nil
end
end
function FishingRod:GetDebugString()
local str = string.format("target: %s", tostring(self.target) )
if self.hookedfish then
str = str.." hooked: "..tostring(self.hookedfish)
end
if self.caughtfish then
str = str.." caught: "..tostring(self.caughtfish)
end
return str
end
function FishingRod:SetWaitTimes(min, max)
self.minwaittime = min
self.maxwaittime = max
end
function FishingRod:SetStrainTimes(min, max)
self.minstraintime = min
self.maxstraintime = max
end
function FishingRod:OnUpdate(dt)
if self:IsFishing() then
if not self.fisherman:IsValid()
or (not self.fisherman.sg:HasStateTag("fishing") and not self.fisherman.sg:HasStateTag("catchfish") )
or not self.inst.components.equippable
or not self.inst.components.equippable.isequipped then
self:StopFishing()
end
end
end
function FishingRod:IsFishing()
return self.target ~= nil and self.fisherman ~= nil
end
function FishingRod:HasHookedFish()
return self.target ~= nil and self.hookedfish ~= nil
end
function FishingRod:HasCaughtFish()
return self.caughtfish ~= nil
end
function FishingRod:FishIsBiting()
return self.fisherman and self.fisherman.sg:HasStateTag("nibble")
end
function FishingRod:StartFishing(target, fisherman)
self:StopFishing()
if target and target.components.fishable then
self.target = target
self.fisherman = fisherman
self.inst:StartUpdatingComponent(self)
end
end
function FishingRod:WaitForFish()
if self.target and self.target.components.fishable then
local fishleft = self.target.components.fishable:GetFishPercent()
local nibbletime = nil
if fishleft > 0 then
nibbletime = self.minwaittime + (1.0 - fishleft)*(self.maxwaittime - self.minwaittime)
end
self:CancelFishTask()
if nibbletime then
self.fishtask = self.inst:DoTaskInTime(nibbletime, DoNibble)
end
end
end
function FishingRod:CancelFishTask()
if self.fishtask then
self.fishtask:Cancel()
end
self.fishtask = nil
end
function FishingRod:StopFishing()
if self.target and self.fisherman then
--self.inst:PushEvent("fishingcancel")
self.fisherman:PushEvent("fishingcancel")
self.target = nil
self.fisherman = nil
end
self:CancelFishTask()
self.inst:StopUpdatingComponent(self)
self.hookedfish = nil
self.caughtfish = nil
end
function FishingRod:Hook()
if self.target and self.target.components.fishable then
self.hookedfish = self.target.components.fishable:HookFish(self.fisherman)
if self.inst.components.finiteuses then
local roddurability = self.inst.components.finiteuses:GetPercent()
local loserodtime = self.minstraintime + roddurability*(self.maxstraintime - self.minstraintime)
self.fishtask = self.inst:DoTaskInTime(loserodtime, DoLoseRod)
end
self.inst:PushEvent("fishingstrain")
self.fisherman:PushEvent("fishingstrain")
end
end
function FishingRod:Release()
if self.target and self.target.components.fishable and self.hookedfish then
self.target.components.fishable:ReleaseFish(self.hookedfish)
self:StopFishing()
end
end
function FishingRod:Reel()
if self.target and self.target.components.fishable and self.hookedfish then
self.caughtfish = self.target.components.fishable:RemoveFish(self.hookedfish)
self.hookedfish = nil
self:CancelFishTask()
if self.caughtfish then
local spawnPos = self.fisherman:GetPosition()
local offset = spawnPos - self.target:GetPosition()
spawnPos = spawnPos + offset:GetNormalized()
if self.caughtfish.Physics ~= nil then
self.caughtfish.Physics:SetActive(true)
self.caughtfish.Physics:Teleport(spawnPos:Get())
else
self.caughtfish.Transform:SetPosition(spawnPos:Get())
end
self.inst:PushEvent("fishingcatch", {build = self.caughtfish.build} )
self.fisherman:PushEvent("fishingcatch", {build = self.caughtfish.build} )
end
end
end
function FishingRod:Collect()
if self.caughtfish and self.fisherman then
if self.caughtfish.Physics ~= nil then
self.caughtfish.Physics:SetActive(true)
end
self.caughtfish.entity:Show()
if self.caughtfish.DynamicShadow ~= nil then
self.caughtfish.DynamicShadow:Enable(true)
end
self.caughtfish.persists = true
self.inst:PushEvent("fishingcollect", {fish = self.caughtfish} )
self.fisherman:PushEvent("fishingcollect", {fish = self.caughtfish} )
self:StopFishing()
end
end
return FishingRod | 412 | 0.793889 | 1 | 0.793889 | game-dev | MEDIA | 0.96483 | game-dev | 0.783336 | 1 | 0.783336 |
gamekit-developers/gamekit | 16,698 | bullet/src/BulletCollision/Gimpact/gim_box_set.h | #ifndef GIM_BOX_SET_H_INCLUDED
#define GIM_BOX_SET_H_INCLUDED
/*! \file gim_box_set.h
\author Francisco Leon Najera
*/
/*
-----------------------------------------------------------------------------
This source file is part of GIMPACT Library.
For the latest info, see http://gimpact.sourceforge.net/
Copyright (c) 2006 Francisco Leon Najera. C.C. 80087371.
email: projectileman@yahoo.com
This library is free software; you can redistribute it and/or
modify it under the terms of EITHER:
(1) The GNU Lesser General Public License as published by the Free
Software Foundation; either version 2.1 of the License, or (at
your option) any later version. The text of the GNU Lesser
General Public License is included with this library in the
file GIMPACT-LICENSE-LGPL.TXT.
(2) The BSD-style license that is included with this library in
the file GIMPACT-LICENSE-BSD.TXT.
(3) The zlib/libpng license that is included with this library in
the file GIMPACT-LICENSE-ZLIB.TXT.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files
GIMPACT-LICENSE-LGPL.TXT, GIMPACT-LICENSE-ZLIB.TXT and GIMPACT-LICENSE-BSD.TXT for more details.
-----------------------------------------------------------------------------
*/
#include "gim_array.h"
#include "gim_radixsort.h"
#include "gim_box_collision.h"
#include "gim_tri_collision.h"
//! Overlapping pair
struct GIM_PAIR
{
GUINT m_index1;
GUINT m_index2;
GIM_PAIR()
{}
GIM_PAIR(const GIM_PAIR & p)
{
m_index1 = p.m_index1;
m_index2 = p.m_index2;
}
GIM_PAIR(GUINT index1, GUINT index2)
{
m_index1 = index1;
m_index2 = index2;
}
};
//! A pairset array
class gim_pair_set: public gim_array<GIM_PAIR>
{
public:
gim_pair_set():gim_array<GIM_PAIR>(32)
{
}
inline void push_pair(GUINT index1,GUINT index2)
{
push_back(GIM_PAIR(index1,index2));
}
inline void push_pair_inv(GUINT index1,GUINT index2)
{
push_back(GIM_PAIR(index2,index1));
}
};
//! Prototype Base class for primitive classification
/*!
This class is a wrapper for primitive collections.
This tells relevant info for the Bounding Box set classes, which take care of space classification.
This class can manage Compound shapes and trimeshes, and if it is managing trimesh then the Hierarchy Bounding Box classes will take advantage of primitive Vs Box overlapping tests for getting optimal results and less Per Box compairisons.
*/
class GIM_PRIMITIVE_MANAGER_PROTOTYPE
{
public:
virtual ~GIM_PRIMITIVE_MANAGER_PROTOTYPE() {}
//! determines if this manager consist on only triangles, which special case will be optimized
virtual bool is_trimesh() = 0;
virtual GUINT get_primitive_count() = 0;
virtual void get_primitive_box(GUINT prim_index ,GIM_AABB & primbox) = 0;
virtual void get_primitive_triangle(GUINT prim_index,GIM_TRIANGLE & triangle) = 0;
};
struct GIM_AABB_DATA
{
GIM_AABB m_bound;
GUINT m_data;
};
//! Node Structure for trees
struct GIM_BOX_TREE_NODE
{
GIM_AABB m_bound;
GUINT m_left;//!< Left subtree
GUINT m_right;//!< Right subtree
GUINT m_escapeIndex;//!< Scape index for traversing
GUINT m_data;//!< primitive index if apply
GIM_BOX_TREE_NODE()
{
m_left = 0;
m_right = 0;
m_escapeIndex = 0;
m_data = 0;
}
SIMD_FORCE_INLINE bool is_leaf_node() const
{
return (!m_left && !m_right);
}
};
//! Basic Box tree structure
class GIM_BOX_TREE
{
protected:
GUINT m_num_nodes;
gim_array<GIM_BOX_TREE_NODE> m_node_array;
protected:
GUINT _sort_and_calc_splitting_index(
gim_array<GIM_AABB_DATA> & primitive_boxes,
GUINT startIndex, GUINT endIndex, GUINT splitAxis);
GUINT _calc_splitting_axis(gim_array<GIM_AABB_DATA> & primitive_boxes, GUINT startIndex, GUINT endIndex);
void _build_sub_tree(gim_array<GIM_AABB_DATA> & primitive_boxes, GUINT startIndex, GUINT endIndex);
public:
GIM_BOX_TREE()
{
m_num_nodes = 0;
}
//! prototype functions for box tree management
//!@{
void build_tree(gim_array<GIM_AABB_DATA> & primitive_boxes);
SIMD_FORCE_INLINE void clearNodes()
{
m_node_array.clear();
m_num_nodes = 0;
}
//! node count
SIMD_FORCE_INLINE GUINT getNodeCount() const
{
return m_num_nodes;
}
//! tells if the node is a leaf
SIMD_FORCE_INLINE bool isLeafNode(GUINT nodeindex) const
{
return m_node_array[nodeindex].is_leaf_node();
}
SIMD_FORCE_INLINE GUINT getNodeData(GUINT nodeindex) const
{
return m_node_array[nodeindex].m_data;
}
SIMD_FORCE_INLINE void getNodeBound(GUINT nodeindex, GIM_AABB & bound) const
{
bound = m_node_array[nodeindex].m_bound;
}
SIMD_FORCE_INLINE void setNodeBound(GUINT nodeindex, const GIM_AABB & bound)
{
m_node_array[nodeindex].m_bound = bound;
}
SIMD_FORCE_INLINE GUINT getLeftNodeIndex(GUINT nodeindex) const
{
return m_node_array[nodeindex].m_left;
}
SIMD_FORCE_INLINE GUINT getRightNodeIndex(GUINT nodeindex) const
{
return m_node_array[nodeindex].m_right;
}
SIMD_FORCE_INLINE GUINT getScapeNodeIndex(GUINT nodeindex) const
{
return m_node_array[nodeindex].m_escapeIndex;
}
//!@}
};
//! Generic Box Tree Template
/*!
This class offers an structure for managing a box tree of primitives.
Requires a Primitive prototype (like GIM_PRIMITIVE_MANAGER_PROTOTYPE ) and
a Box tree structure ( like GIM_BOX_TREE).
*/
template<typename _GIM_PRIMITIVE_MANAGER_PROTOTYPE, typename _GIM_BOX_TREE_PROTOTYPE>
class GIM_BOX_TREE_TEMPLATE_SET
{
protected:
_GIM_PRIMITIVE_MANAGER_PROTOTYPE m_primitive_manager;
_GIM_BOX_TREE_PROTOTYPE m_box_tree;
protected:
//stackless refit
SIMD_FORCE_INLINE void refit()
{
GUINT nodecount = getNodeCount();
while(nodecount--)
{
if(isLeafNode(nodecount))
{
GIM_AABB leafbox;
m_primitive_manager.get_primitive_box(getNodeData(nodecount),leafbox);
setNodeBound(nodecount,leafbox);
}
else
{
//get left bound
GUINT childindex = getLeftNodeIndex(nodecount);
GIM_AABB bound;
getNodeBound(childindex,bound);
//get right bound
childindex = getRightNodeIndex(nodecount);
GIM_AABB bound2;
getNodeBound(childindex,bound2);
bound.merge(bound2);
setNodeBound(nodecount,bound);
}
}
}
public:
GIM_BOX_TREE_TEMPLATE_SET()
{
}
SIMD_FORCE_INLINE GIM_AABB getGlobalBox() const
{
GIM_AABB totalbox;
getNodeBound(0, totalbox);
return totalbox;
}
SIMD_FORCE_INLINE void setPrimitiveManager(const _GIM_PRIMITIVE_MANAGER_PROTOTYPE & primitive_manager)
{
m_primitive_manager = primitive_manager;
}
const _GIM_PRIMITIVE_MANAGER_PROTOTYPE & getPrimitiveManager() const
{
return m_primitive_manager;
}
_GIM_PRIMITIVE_MANAGER_PROTOTYPE & getPrimitiveManager()
{
return m_primitive_manager;
}
//! node manager prototype functions
///@{
//! this attemps to refit the box set.
SIMD_FORCE_INLINE void update()
{
refit();
}
//! this rebuild the entire set
SIMD_FORCE_INLINE void buildSet()
{
//obtain primitive boxes
gim_array<GIM_AABB_DATA> primitive_boxes;
primitive_boxes.resize(m_primitive_manager.get_primitive_count(),false);
for (GUINT i = 0;i<primitive_boxes.size() ;i++ )
{
m_primitive_manager.get_primitive_box(i,primitive_boxes[i].m_bound);
primitive_boxes[i].m_data = i;
}
m_box_tree.build_tree(primitive_boxes);
}
//! returns the indices of the primitives in the m_primitive_manager
SIMD_FORCE_INLINE bool boxQuery(const GIM_AABB & box, gim_array<GUINT> & collided_results) const
{
GUINT curIndex = 0;
GUINT numNodes = getNodeCount();
while (curIndex < numNodes)
{
GIM_AABB bound;
getNodeBound(curIndex,bound);
//catch bugs in tree data
bool aabbOverlap = bound.has_collision(box);
bool isleafnode = isLeafNode(curIndex);
if (isleafnode && aabbOverlap)
{
collided_results.push_back(getNodeData(curIndex));
}
if (aabbOverlap || isleafnode)
{
//next subnode
curIndex++;
}
else
{
//skip node
curIndex+= getScapeNodeIndex(curIndex);
}
}
if(collided_results.size()>0) return true;
return false;
}
//! returns the indices of the primitives in the m_primitive_manager
SIMD_FORCE_INLINE bool boxQueryTrans(const GIM_AABB & box,
const btTransform & transform, gim_array<GUINT> & collided_results) const
{
GIM_AABB transbox=box;
transbox.appy_transform(transform);
return boxQuery(transbox,collided_results);
}
//! returns the indices of the primitives in the m_primitive_manager
SIMD_FORCE_INLINE bool rayQuery(
const btVector3 & ray_dir,const btVector3 & ray_origin ,
gim_array<GUINT> & collided_results) const
{
GUINT curIndex = 0;
GUINT numNodes = getNodeCount();
while (curIndex < numNodes)
{
GIM_AABB bound;
getNodeBound(curIndex,bound);
//catch bugs in tree data
bool aabbOverlap = bound.collide_ray(ray_origin,ray_dir);
bool isleafnode = isLeafNode(curIndex);
if (isleafnode && aabbOverlap)
{
collided_results.push_back(getNodeData( curIndex));
}
if (aabbOverlap || isleafnode)
{
//next subnode
curIndex++;
}
else
{
//skip node
curIndex+= getScapeNodeIndex(curIndex);
}
}
if(collided_results.size()>0) return true;
return false;
}
//! tells if this set has hierarcht
SIMD_FORCE_INLINE bool hasHierarchy() const
{
return true;
}
//! tells if this set is a trimesh
SIMD_FORCE_INLINE bool isTrimesh() const
{
return m_primitive_manager.is_trimesh();
}
//! node count
SIMD_FORCE_INLINE GUINT getNodeCount() const
{
return m_box_tree.getNodeCount();
}
//! tells if the node is a leaf
SIMD_FORCE_INLINE bool isLeafNode(GUINT nodeindex) const
{
return m_box_tree.isLeafNode(nodeindex);
}
SIMD_FORCE_INLINE GUINT getNodeData(GUINT nodeindex) const
{
return m_box_tree.getNodeData(nodeindex);
}
SIMD_FORCE_INLINE void getNodeBound(GUINT nodeindex, GIM_AABB & bound) const
{
m_box_tree.getNodeBound(nodeindex, bound);
}
SIMD_FORCE_INLINE void setNodeBound(GUINT nodeindex, const GIM_AABB & bound)
{
m_box_tree.setNodeBound(nodeindex, bound);
}
SIMD_FORCE_INLINE GUINT getLeftNodeIndex(GUINT nodeindex) const
{
return m_box_tree.getLeftNodeIndex(nodeindex);
}
SIMD_FORCE_INLINE GUINT getRightNodeIndex(GUINT nodeindex) const
{
return m_box_tree.getRightNodeIndex(nodeindex);
}
SIMD_FORCE_INLINE GUINT getScapeNodeIndex(GUINT nodeindex) const
{
return m_box_tree.getScapeNodeIndex(nodeindex);
}
SIMD_FORCE_INLINE void getNodeTriangle(GUINT nodeindex,GIM_TRIANGLE & triangle) const
{
m_primitive_manager.get_primitive_triangle(getNodeData(nodeindex),triangle);
}
};
//! Class for Box Tree Sets
/*!
this has the GIM_BOX_TREE implementation for bounding boxes.
*/
template<typename _GIM_PRIMITIVE_MANAGER_PROTOTYPE>
class GIM_BOX_TREE_SET: public GIM_BOX_TREE_TEMPLATE_SET< _GIM_PRIMITIVE_MANAGER_PROTOTYPE, GIM_BOX_TREE>
{
public:
};
/// GIM_BOX_SET collision methods
template<typename BOX_SET_CLASS0,typename BOX_SET_CLASS1>
class GIM_TREE_TREE_COLLIDER
{
public:
gim_pair_set * m_collision_pairs;
BOX_SET_CLASS0 * m_boxset0;
BOX_SET_CLASS1 * m_boxset1;
GUINT current_node0;
GUINT current_node1;
bool node0_is_leaf;
bool node1_is_leaf;
bool t0_is_trimesh;
bool t1_is_trimesh;
bool node0_has_triangle;
bool node1_has_triangle;
GIM_AABB m_box0;
GIM_AABB m_box1;
GIM_BOX_BOX_TRANSFORM_CACHE trans_cache_1to0;
btTransform trans_cache_0to1;
GIM_TRIANGLE m_tri0;
btVector4 m_tri0_plane;
GIM_TRIANGLE m_tri1;
btVector4 m_tri1_plane;
public:
GIM_TREE_TREE_COLLIDER()
{
current_node0 = G_UINT_INFINITY;
current_node1 = G_UINT_INFINITY;
}
protected:
SIMD_FORCE_INLINE void retrieve_node0_triangle(GUINT node0)
{
if(node0_has_triangle) return;
m_boxset0->getNodeTriangle(node0,m_tri0);
//transform triangle
m_tri0.m_vertices[0] = trans_cache_0to1(m_tri0.m_vertices[0]);
m_tri0.m_vertices[1] = trans_cache_0to1(m_tri0.m_vertices[1]);
m_tri0.m_vertices[2] = trans_cache_0to1(m_tri0.m_vertices[2]);
m_tri0.get_plane(m_tri0_plane);
node0_has_triangle = true;
}
SIMD_FORCE_INLINE void retrieve_node1_triangle(GUINT node1)
{
if(node1_has_triangle) return;
m_boxset1->getNodeTriangle(node1,m_tri1);
//transform triangle
m_tri1.m_vertices[0] = trans_cache_1to0.transform(m_tri1.m_vertices[0]);
m_tri1.m_vertices[1] = trans_cache_1to0.transform(m_tri1.m_vertices[1]);
m_tri1.m_vertices[2] = trans_cache_1to0.transform(m_tri1.m_vertices[2]);
m_tri1.get_plane(m_tri1_plane);
node1_has_triangle = true;
}
SIMD_FORCE_INLINE void retrieve_node0_info(GUINT node0)
{
if(node0 == current_node0) return;
m_boxset0->getNodeBound(node0,m_box0);
node0_is_leaf = m_boxset0->isLeafNode(node0);
node0_has_triangle = false;
current_node0 = node0;
}
SIMD_FORCE_INLINE void retrieve_node1_info(GUINT node1)
{
if(node1 == current_node1) return;
m_boxset1->getNodeBound(node1,m_box1);
node1_is_leaf = m_boxset1->isLeafNode(node1);
node1_has_triangle = false;
current_node1 = node1;
}
SIMD_FORCE_INLINE bool node_collision(GUINT node0 ,GUINT node1)
{
retrieve_node0_info(node0);
retrieve_node1_info(node1);
bool result = m_box0.overlapping_trans_cache(m_box1,trans_cache_1to0,true);
if(!result) return false;
if(t0_is_trimesh && node0_is_leaf)
{
//perform primitive vs box collision
retrieve_node0_triangle(node0);
//do triangle vs box collision
m_box1.increment_margin(m_tri0.m_margin);
result = m_box1.collide_triangle_exact(
m_tri0.m_vertices[0],m_tri0.m_vertices[1],m_tri0.m_vertices[2],m_tri0_plane);
m_box1.increment_margin(-m_tri0.m_margin);
if(!result) return false;
return true;
}
else if(t1_is_trimesh && node1_is_leaf)
{
//perform primitive vs box collision
retrieve_node1_triangle(node1);
//do triangle vs box collision
m_box0.increment_margin(m_tri1.m_margin);
result = m_box0.collide_triangle_exact(
m_tri1.m_vertices[0],m_tri1.m_vertices[1],m_tri1.m_vertices[2],m_tri1_plane);
m_box0.increment_margin(-m_tri1.m_margin);
if(!result) return false;
return true;
}
return true;
}
//stackless collision routine
void find_collision_pairs()
{
gim_pair_set stack_collisions;
stack_collisions.reserve(32);
//add the first pair
stack_collisions.push_pair(0,0);
while(stack_collisions.size())
{
//retrieve the last pair and pop
GUINT node0 = stack_collisions.back().m_index1;
GUINT node1 = stack_collisions.back().m_index2;
stack_collisions.pop_back();
if(node_collision(node0,node1)) // a collision is found
{
if(node0_is_leaf)
{
if(node1_is_leaf)
{
m_collision_pairs->push_pair(m_boxset0->getNodeData(node0),m_boxset1->getNodeData(node1));
}
else
{
//collide left
stack_collisions.push_pair(node0,m_boxset1->getLeftNodeIndex(node1));
//collide right
stack_collisions.push_pair(node0,m_boxset1->getRightNodeIndex(node1));
}
}
else
{
if(node1_is_leaf)
{
//collide left
stack_collisions.push_pair(m_boxset0->getLeftNodeIndex(node0),node1);
//collide right
stack_collisions.push_pair(m_boxset0->getRightNodeIndex(node0),node1);
}
else
{
GUINT left0 = m_boxset0->getLeftNodeIndex(node0);
GUINT right0 = m_boxset0->getRightNodeIndex(node0);
GUINT left1 = m_boxset1->getLeftNodeIndex(node1);
GUINT right1 = m_boxset1->getRightNodeIndex(node1);
//collide left
stack_collisions.push_pair(left0,left1);
//collide right
stack_collisions.push_pair(left0,right1);
//collide left
stack_collisions.push_pair(right0,left1);
//collide right
stack_collisions.push_pair(right0,right1);
}// else if node1 is not a leaf
}// else if node0 is not a leaf
}// if(node_collision(node0,node1))
}//while(stack_collisions.size())
}
public:
void find_collision(BOX_SET_CLASS0 * boxset1, const btTransform & trans1,
BOX_SET_CLASS1 * boxset2, const btTransform & trans2,
gim_pair_set & collision_pairs, bool complete_primitive_tests = true)
{
m_collision_pairs = &collision_pairs;
m_boxset0 = boxset1;
m_boxset1 = boxset2;
trans_cache_1to0.calc_from_homogenic(trans1,trans2);
trans_cache_0to1 = trans2.inverse();
trans_cache_0to1 *= trans1;
if(complete_primitive_tests)
{
t0_is_trimesh = boxset1->getPrimitiveManager().is_trimesh();
t1_is_trimesh = boxset2->getPrimitiveManager().is_trimesh();
}
else
{
t0_is_trimesh = false;
t1_is_trimesh = false;
}
find_collision_pairs();
}
};
#endif // GIM_BOXPRUNING_H_INCLUDED
| 412 | 0.961887 | 1 | 0.961887 | game-dev | MEDIA | 0.621162 | game-dev | 0.714308 | 1 | 0.714308 |
Inface0443/pyqt | 19,048 | qtmodel/core/result_db.py | import math
class NodeDisplacement:
"""
节点位移
"""
def __init__(self, node_id, displacements: list[float], time: float = 0):
self.time = time
self.node_id = node_id
if len(displacements) == 6:
self.dx = displacements[0]
self.dy = displacements[1]
self.dz = displacements[2]
self.rx = displacements[3]
self.ry = displacements[4]
self.rz = displacements[5]
else:
raise ValueError("操作错误: 'displacements' 列表有误")
def __str__(self):
obj_dict = {
'node_id': self.node_id,
'time': self.time,
'dx': self.dx,
'dy': self.dy,
'dz': self.dz,
'rx': self.rx,
'ry': self.ry,
'rz': self.rz
}
return obj_dict
def __repr__(self):
return self.__str__()
class SupportReaction:
"""
支座反力
"""
def __init__(self, node_id: int, force: list[float], time: float = 0):
self.node_id = node_id
self.time = time
if len(force) == 6:
self.fx = force[0]
self.fy = force[1]
self.fz = force[2]
self.mx = force[3]
self.my = force[4]
self.mz = force[5]
else:
raise ValueError("操作错误: 'force' 列表有误")
def __str__(self):
obj_dict = {
'node_id': self.node_id,
'time': self.time,
'fx': self.fx,
'fy': self.fy,
'fz': self.fz,
'mx': self.mx,
'my': self.my,
'mz': self.mz
}
return obj_dict
def __repr__(self):
return self.__str__()
class BeamElementForce:
"""
梁单元内力
"""
def __init__(self, element_id: int, force_i: list[float], force_j: list[float], time: float = 0):
"""
单元内力构造器
Args:
element_id: 单元id
force_i: I端单元内力 [Fx,Fy,Fz,Mx,My,Mz]
force_j: J端单元内力 [Fx,Fy,Fz,Mx,My,Mz]
time: 时程分析时间
"""
self.element_id = element_id
self.time = time
if len(force_i) == 6 and len(force_j) == 6:
self.force_i = Force(*force_i)
self.force_j = Force(*force_j)
else:
raise ValueError("操作错误: 'force_i' and 'force_j' 列表有误")
def __str__(self):
obj_dict = {
'element_id': self.element_id,
'time': self.time,
'force_i': self.force_i.__str__(),
'force_j': self.force_j.__str__()
}
return obj_dict
def __repr__(self):
return self.__str__()
class TrussElementForce:
"""
桁架单元内力
"""
def __init__(self, element_id: int, force_i: list[float], force_j: list[float], time: float = 0):
"""
单元内力构造器
Args:
element_id: 单元id
force_i: I端单元内力 [Fx,Fy,Fz,Mx,My,Mz]
force_j: J端单元内力 [Fx,Fy,Fz,Mx,My,Mz]
time: 时程分析结果时间
"""
self.element_id = element_id
self.time = time
if len(force_i) == 6 and len(force_j) == 6:
self.Ni = force_i[3]
self.Fxi = force_i[0]
self.Fyi = force_i[1]
self.Fzi = force_i[2]
self.Nj = force_j[3]
self.Fxj = force_j[0]
self.Fyj = force_j[1]
self.Fzj = force_j[2]
else:
raise ValueError("操作错误: 'stress_i' and 'stress_j' 列表有误")
def __str__(self):
obj_dict = {
'element_id': self.element_id,
'time': self.time,
'Ni': self.Ni,
'Fxi': self.Fxi,
'Fyi': self.Fyi,
'Fzi': self.Fzi,
'Nj': self.Nj,
'Fxj': self.Fxj,
'Fyj': self.Fyj,
'Fzj': self.Fzj
}
return obj_dict
def __repr__(self):
return self.__str__()
class ShellElementForce:
"""
板单元内力
"""
def __init__(self, element_id: int, force_i: list[float], force_j: list[float],
force_k: list[float], force_l: list[float], time: float = 0):
"""
单元内力构造器
Args:
element_id: 单元id
force_i: I端单元内力 [Fx,Fy,Fz,Mx,My,Mz]
force_j: J端单元内力 [Fx,Fy,Fz,Mx,My,Mz]
force_k: K端单元内力 [Fx,Fy,Fz,Mx,My,Mz]
force_l: L端单元内力 [Fx,Fy,Fz,Mx,My,Mz]
time: 时程分析时间
"""
self.element_id = element_id
self.time = time
if len(force_i) == 6 and len(force_i) == 6 and len(force_k) == 6 and len(force_l) == 6:
self.force_i = Force(*force_i)
self.force_j = Force(*force_j)
self.force_k = Force(*force_k)
self.force_l = Force(*force_l)
else:
raise ValueError("操作错误: 内力列表有误")
def __str__(self):
obj_dict = {
'element_id': self.element_id,
'time': self.time,
'force_i': self.force_i.__str__(),
'force_j': self.force_j.__str__(),
'force_k': self.force_k.__str__(),
'force_l': self.force_l.__str__()
}
return obj_dict
def __repr__(self):
return self.__str__()
class CompositeElementForce:
"""
组合梁单元内力
"""
def __init__(self, element_id: int, force_i: list[float], force_j: list[float], shear_force: float,
main_force_i: list[float], main_force_j: list[float],
sub_force_i: list[float], sub_force_j: list[float],
is_composite: bool):
"""
单元内力构造器
Args:
element_id: 单元id
force_i: I端单元内力 [Fx,Fy,Fz,Mx,My,Mz]
force_j: J端单元内力 [Fx,Fy,Fz,Mx,My,Mz]
main_force_i: 主材I端单元内力 [Fx,Fy,Fz,Mx,My,Mz]
main_force_j: 主材J端单元内力 [Fx,Fy,Fz,Mx,My,Mz]
sub_force_i: 辅材I端单元内力 [Fx,Fy,Fz,Mx,My,Mz]
sub_force_j: 辅材J端单元内力 [Fx,Fy,Fz,Mx,My,Mz]
is_composite: 是否结合
shear_force: 接合面剪力
"""
if len(force_i) == 6 and len(force_j) == 6:
self.element_id = element_id
self.force_i = Force(*force_i)
self.force_j = Force(*force_j)
self.shear_force = shear_force
# 运营阶段下述信息全部为0
self.main_force_i = Force(*main_force_i)
self.main_force_j = Force(*main_force_j)
self.sub_force_i = Force(*sub_force_i)
self.sub_force_j = Force(*sub_force_j)
self.is_composite = is_composite
else:
raise ValueError("操作错误: 'force_i' and 'force_j' 列表有误")
def __str__(self):
obj_dict = {
'element_id': self.element_id,
'force_i': self.force_i.__str__(),
'force_j': self.force_j.__str__()
}
return obj_dict
def __repr__(self):
return self.__str__()
class BeamElementStress:
"""
梁单元应力
"""
def __init__(self, element_id: int, stress_i: list[float], stress_j: list[float]):
"""
单元内力构造器
Args:
element_id: 单元id
stress_i: I端单元应力 [top_left, top_right, bot_left, bot_right, sfx, smz_left, smz_right, smy_top, smy_bot]
stress_j: J端单元应力 [top_left, top_right, bot_left, bot_right, sfx, smz_left, smz_right, smy_top, smy_bot]
"""
if len(stress_i) == 9 and len(stress_i) == 9:
self.element_id = element_id
self.stress_i = BeamStress(*stress_i)
self.stress_j = BeamStress(*stress_j)
else:
raise ValueError("操作错误: 单元应力列表有误")
def __str__(self):
obj_dict = {
'element_id': self.element_id,
'stress_i': self.stress_i.__str__(),
'stress_j': self.stress_j.__str__()
}
return obj_dict
def __repr__(self):
return self.__str__()
class ShellElementStress:
"""
板架单元应力
"""
def __init__(self, element_id: int, stress_i_top: list[float], stress_j_top: list[float],
stress_k_top: list[float], stress_l_top: list[float], stress_i_bot: list[float],
stress_j_bot: list[float], stress_k_bot: list[float], stress_l_bot: list[float]):
"""
单元内力构造器
Args:
element_id: 单元id
stress_i_top: I端单元上部应力 [sx,sy,sxy,s1,s2]
stress_j_top: J端单元上部应力 [sx,sy,sxy,s1,s2]
stress_k_top: K端单元上部应力 [sx,sy,sxy,s1,s2]
stress_l_top: L端单元上部应力 [sx,sy,sxy,s1,s2]
stress_i_bot: I端单元下部应力 [sx,sy,sxy,s1,s2]
stress_j_bot: J端单元下部应力 [sx,sy,sxy,s1,s2]
stress_k_bot: K端单元下部应力 [sx,sy,sxy,s1,s2]
stress_l_bot: L端单元下部应力 [sx,sy,sxy,s1,s2]
"""
if len(stress_i_top) == 5 and len(stress_j_top) == 5 \
and len(stress_k_top) == 5 and len(stress_l_top) == 5 \
and len(stress_i_bot) == 5 and len(stress_j_bot) == 5 \
and len(stress_k_bot) == 5 and len(stress_l_bot) == 5:
self.element_id = element_id
self.stress_i_top = ShellStress(*stress_i_top)
self.stress_j_top = ShellStress(*stress_j_top)
self.stress_k_top = ShellStress(*stress_k_top)
self.stress_l_top = ShellStress(*stress_l_top)
self.stress_i_bot = ShellStress(*stress_i_bot)
self.stress_j_bot = ShellStress(*stress_j_bot)
self.stress_k_bot = ShellStress(*stress_k_bot)
self.stress_l_bot = ShellStress(*stress_l_bot)
else:
raise ValueError("操作错误: 单元应力列表有误")
def __str__(self):
obj_dict = {
'element_id': self.element_id,
'stress_i_top': self.stress_i_top.__str__(),
'stress_j_top': self.stress_j_top.__str__(),
'stress_k_top': self.stress_k_top.__str__(),
'stress_l_top': self.stress_l_top.__str__(),
'stress_i_bot': self.stress_i_bot.__str__(),
'stress_j_bot': self.stress_j_bot.__str__(),
'stress_k_bot': self.stress_k_bot.__str__(),
'stress_l_bot': self.stress_l_bot.__str__()
}
return obj_dict
def __repr__(self):
return self.__str__()
class TrussElementStress:
"""
桁架单元应力
"""
def __init__(self, element_id: int, si: float, sj: float):
"""
单元内力构造器
Args:
element_id: 单元id
si: I端单元应力
sj: J端单元应力
"""
self.element_id = element_id
self.Si = si
self.Sj = sj
def __str__(self):
obj_dict = {
'element_id': self.element_id,
'Si': self.Si,
'Sj': self.Sj
}
return obj_dict
def __repr__(self):
return self.__str__()
class CompositeBeamStress:
"""
梁单元应力
"""
def __init__(self, element_id: int, main_stress_i: list[float], main_stress_j: list[float],
sub_stress_i: list[float], sub_stress_j: list[float]):
"""
单元内力构造器
Args:
element_id: 单元id
main_stress_i: 主材I端单元应力 [top_left, top_right, bot_left, bot_right, sfx, smz_left, smz_right, smy_top, smy_bot]
main_stress_j: 主材J端单元应力 [top_left, top_right, bot_left, bot_right, sfx, smz_left, smz_right, smy_top, smy_bot]
sub_stress_i: 辅材I端单元应力 [top_left, top_right, bot_left, bot_right, sfx, smz_left, smz_right, smy_top, smy_bot]
sub_stress_j: 辅材J端单元应力 [top_left, top_right, bot_left, bot_right, sfx, smz_left, smz_right, smy_top, smy_bot]
"""
if len(main_stress_i) == 9 and len(main_stress_j) == 9 and len(sub_stress_i) == 9 and len(sub_stress_j) == 9:
self.element_id = element_id
self.main_stress_i = BeamStress(*main_stress_i)
self.main_stress_j = BeamStress(*main_stress_j)
self.sub_stress_i = BeamStress(*sub_stress_i)
self.sub_stress_j = BeamStress(*sub_stress_j)
else:
raise ValueError("操作错误: 单元应力列表有误")
def __str__(self):
obj_dict = {
'element_id': self.element_id,
'main_stress_i': self.main_stress_i.__str__(),
'main_stress_j': self.main_stress_j.__str__(),
'sub_stress_i': self.sub_stress_i.__str__(),
'sub_stress_j': self.sub_stress_j.__str__(),
}
return obj_dict
def __repr__(self):
return self.__str__()
class Force:
"""
用于梁单元内力和板单元内力
"""
def __init__(self, fx, fy, fz, mx, my, mz):
self.fx = fx
self.fy = fy
self.fz = fz
self.mx = mx
self.my = my
self.mz = mz
self.f_xyz = math.sqrt((self.fx * self.fx + self.fy * self.fy + self.fz * self.fz))
self.m_xyz = math.sqrt((self.mx * self.mx + self.my * self.my + self.mz * self.mz))
def __str__(self):
obj_dict = {
'fx': self.fx,
'fy': self.fy,
'fz': self.fz,
'mx': self.mx,
'my': self.my,
'mz': self.mz,
'f_xyz': self.f_xyz,
'm_xyz': self.m_xyz
}
return obj_dict
def __repr__(self):
return self.__str__()
class ShellStress:
"""
用于板单元应力分量
"""
def __init__(self, sx, sy, sxy, s1, s2):
self.sx = sx
self.sy = sy
self.sxy = sxy
self.s1 = s1
self.s2 = s2
def __str__(self):
obj_dict = {
'sx': self.sx,
'sy': self.sy,
'sxy': self.sxy,
's1': self.s1,
's2': self.s2
}
return obj_dict
def __repr__(self):
return self.__str__()
class BeamStress:
"""
用于梁单元应力分量
"""
def __init__(self, top_left, top_right, bot_left, bot_right, sfx, smz_left, smz_right, smy_top, smy_bot):
self.top_left = top_left # 左上角应力
self.top_right = top_right # 右上角应力
self.bot_left = bot_left # 左下角应力
self.bot_right = bot_right # 右下角应力
self.sfx = sfx # 轴向应力
self.smz_left = smz_left # Mz引起的+y轴应力
self.smz_right = smz_right # Mz引起的-y轴应力
self.smy_top = smy_top # My引起的+z轴应力
self.smy_bot = smy_bot # My引起的-z轴应力
def __str__(self):
obj_dict = {
'top_left': self.top_left,
'top_right': self.top_right,
'bot_left': self.bot_left,
'bot_right': self.bot_right,
'sfx': self.sfx,
'smz_left': self.smz_left,
'smz_right': self.smz_right,
'smy_top': self.smy_top,
'smy_bot': self.smy_bot
}
return obj_dict
def __repr__(self):
return self.__str__()
class ElasticLinkForce:
"""
弹性连接内力
"""
def __init__(self, link_id: int, force: list[float]):
"""
弹性连接内力构造器
Args:
link_id: 弹性连接id
force: 弹性连接内力 [Fx,Fy,Fz,Mx,My,Mz]
"""
self.link_id = link_id
if len(force) == 6:
self.force = Force(*force)
else:
raise ValueError("操作错误: 'force' 列表有误")
def __str__(self):
obj_dict = {
'link_id': self.link_id,
'force': self.force.__str__(),
}
return obj_dict
def __repr__(self):
return self.__str__()
class ConstrainEquationForce:
"""
约束方程内力
"""
def __init__(self, equation_id: int, force: list[float]):
"""
约束方程内力构造器
Args:
equation_id: 约束方程id
force: 约束方程内力 [Fx,Fy,Fz,Mx,My,Mz]
"""
self.equation_id = equation_id
if len(force) == 6:
self.force = Force(*force)
else:
raise ValueError("操作错误: 'force' 列表有误")
def __str__(self):
obj_dict = {
'equation_id': self.equation_id,
'force': self.force.__str__(),
}
return obj_dict
def __repr__(self):
return self.__str__()
class CableLengthResult:
"""
用于存储无应力索长及相关几何信息
"""
def __init__(self, element_id: int, unstressed_length: float,
cos_a_xi: float = 0, cos_a_yi: float = 0, cos_a_zi: float = 0,
cos_a_xj: float = 0, cos_a_yj: float = 0, cos_a_zj: float = 0,
dx: float = 0, dy: float = 0, dz: float = 0):
"""
构造函数
Args:
element_id: 单元号
unstressed_length: 无应力索长
cos_a_xi: 索I端沿着x坐标的余弦
cos_a_yi: 索I端沿着y坐标的余弦
cos_a_zi: 索I端沿着z坐标的余弦
cos_a_xj: 索J端沿着x坐标的余弦
cos_a_yj: 索J端沿着y坐标的余弦
cos_a_zj: 索J端沿着z坐标的余弦
dx: 索JI端沿x坐标距离
dy: 索JI端沿y坐标距离
dz: 索JI端沿z坐标距离
"""
self.element_id = element_id
self.unstressed_length = unstressed_length
self.cos_a_xi = cos_a_xi
self.cos_a_yi = cos_a_yi
self.cos_a_zi = cos_a_zi
self.cos_a_xj = cos_a_xj
self.cos_a_yj = cos_a_yj
self.cos_a_zj = cos_a_zj
self.dx = dx
self.dy = dy
self.dz = dz
def __str__(self):
obj_dict = {
'element_id': self.element_id,
'unstressed_length': self.unstressed_length,
'cos_a_xi': self.cos_a_xi,
'cos_a_yi': self.cos_a_yi,
'cos_a_zi': self.cos_a_zi,
'cos_a_xj': self.cos_a_xj,
'cos_a_yj': self.cos_a_yj,
'cos_a_zj': self.cos_a_zj,
'dx': self.dx,
'dy': self.dy,
'dz': self.dz
}
return str(obj_dict)
def __repr__(self):
return self.__str__()
class FreeVibrationResult:
"""
用于自振周期和频率结果输出
"""
def __init__(self, mode: int, angel_frequency: float, participate_mass: list[float],
sum_participate_mass: list[float],
participate_factor: list[float]):
self.mode = mode
self.angel_frequency = angel_frequency
self.engineering_frequency = angel_frequency * 0.159
self.participate_factor = participate_factor
self.participate_mass = participate_mass
self.sum_participate_mass = sum_participate_mass
def __str__(self):
obj_dict = {
'mode': self.mode,
'angel_frequency': self.angel_frequency,
'engineering_frequency': self.engineering_frequency,
'participate_mass': self.participate_mass,
'sum_participate_mass': self.sum_participate_mass,
'participate_factor': self.participate_factor,
}
return obj_dict
def __repr__(self):
return self.__str__()
class ElasticBucklingResult:
"""
用于弹性屈曲分析特征值结果
"""
def __init__(self, mode: int, eigenvalue: float):
self.mode = mode
self.eigenvalue = eigenvalue
def __str__(self):
obj_dict = {
'mode': self.mode,
'eigenvalue': self.eigenvalue,
}
return obj_dict
def __repr__(self):
return self.__str__()
| 412 | 0.857619 | 1 | 0.857619 | game-dev | MEDIA | 0.692187 | game-dev | 0.919295 | 1 | 0.919295 |
ProjectIgnis/CardScripts | 1,495 | official/c78910579.lua | --儀水鏡の反魂術
--Aquamirror Cycle
local s,id=GetID()
function s.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_TOHAND)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetTarget(s.target)
e1:SetOperation(s.activate)
c:RegisterEffect(e1)
end
function s.filter1(c)
return c:IsFaceup() and c:IsAttribute(ATTRIBUTE_WATER) and c:IsAbleToDeck()
end
function s.filter2(c)
return c:IsAttribute(ATTRIBUTE_WATER) and c:IsAbleToHand()
end
function s.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return false end
if chk==0 then return Duel.IsExistingTarget(s.filter1,tp,LOCATION_MZONE,0,1,nil)
and Duel.IsExistingTarget(s.filter2,tp,LOCATION_GRAVE,0,2,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TODECK)
local g1=Duel.SelectTarget(tp,s.filter1,tp,LOCATION_MZONE,0,1,1,nil)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_RTOHAND)
local g2=Duel.SelectTarget(tp,s.filter2,tp,LOCATION_GRAVE,0,2,2,nil)
Duel.SetOperationInfo(0,CATEGORY_TODECK,g1,1,0,0)
Duel.SetOperationInfo(0,CATEGORY_TOHAND,g2,2,0,0)
end
function s.activate(e,tp,eg,ep,ev,re,r,rp)
local ex,g1=Duel.GetOperationInfo(0,CATEGORY_TODECK)
local ex,g2=Duel.GetOperationInfo(0,CATEGORY_TOHAND)
local tc1=g1:GetFirst()
if tc1:IsRelateToEffect(e) and Duel.SendtoDeck(tc1,nil,SEQ_DECKSHUFFLE,REASON_EFFECT)~=0 then
local hg=g2:Filter(Card.IsRelateToEffect,nil,e)
Duel.SendtoHand(hg,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,hg)
end
end | 412 | 0.895456 | 1 | 0.895456 | game-dev | MEDIA | 0.960836 | game-dev | 0.96396 | 1 | 0.96396 |
jswigart/omni-bot | 10,176 | Installer/Files/et/nav/al_kad_b2.gm | //==========================================================================================
//
// al_kad_b2.gm
//
// Who When What
//------------------------------------------------------------------------------------------
// d00d 05/17/08 Original script
// jaskot 02/03/09 Converted old script to new format
// d00d 11/13/09 Updated for 0.8
//
//==========================================================================================
//
global Map =
{
Ammo_Cabinet_first_ammocabinet = "AMMOCAB_first_ammocabinet",
Ammo_Cabinet_north_ammocabinet = "AMMOCAB_north_ammocabinet",
Health_Cabinet_first_healthcabinet = "HEALTHCAB_first_healthcabinet",
Health_Cabinet_north_healthcabinet = "HEALTHCAB_north_healthcabinet",
Flag_relic = "FLAG_relic",
Cappoint_relic = "CAPPOINT_relic",
Build_Command_Post = "BUILD_Command_Post",
Build_Prison_gate = "BUILD_Prision_gate",
Build_Relic_Box = "BUILD_Relic_Box",
Plant_Back_door = "PLANT_Back_door",
Plant_Command_Post = "PLANT_Command_Post",
Plant_Front_door = "PLANT_Front_door",
Plant_Prison_gate = "PLANT_Prision_gate",
Plant_Relic_Box = "PLANT_Relic_Box",
Plant_Rocket = "PLANT_Rocket",
Talk = true,
Command_Post_Built = function( trigger )
{
if ( TestMap )
{ return; }
Util.MapDebugPrint( "Command_Post_Built" );
},
Prison_gate_Built = function( trigger )
{
if ( TestMap )
{ return; }
Util.MapDebugPrint( "Prison_gate_Built" );
},
Back_door_Destroyed = function( trigger )
{
if ( TestMap )
{ return; }
Util.MapDebugPrint( "Back_door_Destroyed" );
},
Command_Post_Destroyed = function( trigger )
{
if ( TestMap )
{ return; }
Util.MapDebugPrint( "Command_Post_Destroyed" );
},
Front_door_Destroyed = function( trigger )
{
if ( TestMap )
{ return; }
Util.MapDebugPrint( "Front_door_Destroyed" );
},
Prison_gate_Destroyed = function( trigger )
{
if ( TestMap )
{ return; }
Util.MapDebugPrint( "Prison_gate_Destroyed" );
},
Relic_Box_Planted = function( trigger )
{
if ( TestMap )
{ return; }
if ( Map.Talk && MAP_TALK )
{
wppos = Util.GetWpNamePosition( "the_box" );
foreach ( id and bot in BotTable )
{
if ( bot.GetTeam() == TEAM.AXIS &&
bot.GetClass() != CLASS.ENGINEER &&
bot.DistanceTo( wppos ) < 1000 )
{
ran = RandRange( 0, 10 );
if ( ran < 4 &&
!bot.GetNearestAlly( CAT.PLAYER,
CLASS.ENGINEER ) )
{
sleep(ran);
bot.SayVoice( VOICE.NEED_ENGINEER );
}
else if ( ran > 6 )
{
sleep( 0.5 );
bot.SayVoice( VOICE.DISARM_DYNAMITE );
}
}
}
}
Util.MapDebugPrint( "Relic_Box_Planted" );
},
Relic_Box_Destroyed = function( trigger )
{
if ( TestMap )
{ return; }
SetAvailableMapGoals( TEAM.ALLIES, true, Map.Flag_relic );
Util.MapDebugPrint( "Relic_Box_Destroyed" );
},
Rocket_Planted = function( trigger )
{
if ( TestMap )
{ return; }
if ( Map.Talk && MAP_TALK )
{
wppos = Util.GetWpNamePosition( "axis_rocket9" );
foreach ( id and bot in BotTable )
{
if ( bot.GetTeam() == TEAM.AXIS &&
bot.GetClass() != CLASS.ENGINEER &&
bot.DistanceTo( wppos ) < 1000 )
{
ran = RandRange(0,10);
if ( ran < 4 &&
!bot.GetNearestAlly(CAT.PLAYER,
CLASS.ENGINEER) )
{
sleep( ran );
bot.SayVoice( VOICE.NEED_ENGINEER );
}
else if ( ran > 6 )
{
sleep( 0.7 );
bot.SayVoice( VOICE.DISARM_DYNAMITE );
}
}
}
}
Util.MapDebugPrint( "Rocket_Planted" );
},
Rocket_Destroyed = function( trigger )
{
if ( TestMap )
{ return; }
Util.MapDebugPrint( "Rocket_Destroyed" );
},
relic_Taken = function( trigger )
{
if ( TestMap )
{ return; }
SetAvailableMapGoals( TEAM.ALLIES, true, "ATTACK_cappoint.*" );
SetAvailableMapGoals( TEAM.AXIS, true, "ATTACK_cappoint.*" );
Util.MapDebugPrint( "relic_Taken" );
},
relic_Captured = function( trigger )
{
if ( TestMap )
{ return; }
SetGoalPriority( Map.Plant_Rocket, 0.9 );
SetAvailableMapGoals( TEAM.ALLIES, false, "ATTACK_cappoint.*" );
SetAvailableMapGoals( TEAM.AXIS, false, "ATTACK_cappoint.*" );
SetAvailableMapGoals( TEAM.AXIS, true, "DEFEND_axis_rocket.*" );
SetAvailableMapGoals( TEAM.AXIS, true, "SNIPE_axis_rocket.*" );
SetAvailableMapGoals( TEAM.ALLIES, true, "ATTACK_allies_rocket.*" );
SetAvailableMapGoals( TEAM.ALLIES, true, "SNIPE_allies_rocket.*" );
SetAvailableMapGoals( TEAM.ALLIES, true, Map.Plant_Prison_gate );
SetAvailableMapGoals( TEAM.ALLIES, true, Map.Plant_Rocket );
Util.ChangeSpawn( TEAM.ALLIES, 3 );
Util.MapDebugPrint( "relic_Captured" );
if ( Map.Talk && MAP_TALK )
{
timeLeft = GetGameTimeLeft();
if ( timeLeft < 120 ) {
return;
}
rand = ETUtil.CountTeam( TEAM.AXIS ) * 2;
rand2 = ETUtil.CountTeam( TEAM.ALLIES ) * 2;
foreach ( gameId and bot in BotTable )
{
team = bot.GetTeam();
if ( team == TEAM.AXIS )
{
if ( RandInt(0, rand) < 2 ) {
sleep( RandRange( 0.7, 2.1 ) );
bot.SayVoice( VOICE.DEFEND_OBJECTIVE );
}
else if ( RandInt(0, rand) < 2 ) {
sleep( RandRange( 1, 2.0 ) );
bot.ExecCommand( "vsay_team FTFallBack" );
}
else if ( RandInt( 0, rand ) < 2 ) {
sleep( RandRange( 0.5, 1.5 ) );
bot.SayVoice( VOICE.REINFORCE_DEF );
}
}
else if ( team == TEAM.ALLIES )
{
if ( RandInt(0, rand2) < 2 ) {
sleep( RandRange( 1, 2.8 ) );
bot.SayVoice( VOICE.REINFORCE_OFF );
}
else if ( RandInt(0,rand2) < 2 ) {
sleep( 1.5 );
bot.ExecCommand( "vsay_team FTAttack" );
}
else if ( RandInt(1, rand2) < 2
&& bot.GetClass() != CLASS.ENGINEER
&& timeLeft > 180)
{
sleep(0.6);
bot.SayVoice( VOICE.DESTROY_PRIMARY );
}
}
}
}
},
relic_Returned = function( trigger )
{
if ( TestMap )
{ return; }
SetAvailableMapGoals( TEAM.ALLIES, false, "ATTACK_cappoint.*" );
SetAvailableMapGoals( TEAM.AXIS, false, "ATTACK_cappoint.*" );
Util.MapDebugPrint( "relic_Returned" );
},
};
global OnMapLoad = function()
{
if ( TestMapOn )
{ Util.AutoTestMap(); }
OnTrigger( "Allied Command Post constructed. Charge speed increased!", Map.Command_Post_Built );
OnTrigger( "Axis Command Post constructed. Charge speed increased!", Map.Command_Post_Built );
OnTrigger( "Axis has built the Prison gate!", Map.Prison_gate_Built );
OnTrigger( "Back door Destroyed.", Map.Back_door_Destroyed );
OnTrigger( "Axis team has destroyed the Allied Command Post!", Map.Command_Post_Destroyed );
OnTrigger( "Front door Destroyed.", Map.Front_door_Destroyed );
OnTrigger( "Allies have destroyed the Prison gate!", Map.Prison_gate_Destroyed );
OnTrigger( "Planted at the Relic Box.", Map.Relic_Box_Planted );
OnTrigger( "Allies have destroyed the Box!!", Map.Relic_Box_Destroyed );
OnTrigger( "Planted at The Rocket.", Map.Rocket_Planted );
OnTrigger( "Allies have destroyed the rocket!", Map.Rocket_Destroyed );
OnTrigger( "Allies have stolen the relic!", Map.relic_Taken );
OnTrigger( "Allied team has secured the relic!", Map.relic_Captured );
OnTrigger( "Flag returned the relic!", Map.relic_Returned );
Util.SetGoalOffset( 10, 0, 0, Map.Plant_Relic_Box );
Util.SetGoalOffset( 0, 0, -50, Map.Build_Prison_gate );
Util.SetGoalOffset( -10, 0, 0, "PLANT_Front_door" );
Util.AddUseWp( "PLANT_Back_door", "door_inside" );
Util.AddUseWp( "PLANT_Back_door", "door_outside" );
SetGoalPriority( Map.Plant_Relic_Box, 0.8 );
SetGoalPriority( Map.Plant_Front_door, 0.82 );
SetGoalPriority( Map.Plant_Back_door, 0.81 );
SetGoalPriority( Map.Plant_Command_Post, 0.75 );
SetGoalPriority( Map.Build_Command_Post, 0.75 );
SetGoalPriority( "DEFUSE_Rocket.*", 1.2, TEAM.AXIS, CLASS.ENGINEER, true );
SetGoalPriority( Map.Plant_Prison_gate, 0.65, TEAM.ALLIES, CLASS.ENGINEER );
SetAvailableMapGoals( TEAM.ALLIES, true, Map.Plant_Back_door );
SetAvailableMapGoals( TEAM.AXIS, false, Map.Plant_Back_door );
SetAvailableMapGoals( TEAM.AXIS, false, Map.Build_Relic_Box );
SetAvailableMapGoals( TEAM.ALLIES, false, Map.Flag_relic );
SetAvailableMapGoals( TEAM.ALLIES, false, Map.Plant_Prison_gate );
SetAvailableMapGoals( TEAM.ALLIES, false, Map.Plant_Rocket );
SetAvailableMapGoals( TEAM.AXIS, false, "ATTACK_.*" );
SetAvailableMapGoals( TEAM.AXIS, false, "DEFEND_.*" );
SetAvailableMapGoals( TEAM.AXIS, false, "SNIPE_.*" );
SetAvailableMapGoals( TEAM.ALLIES, false, "ATTACK_.*" );
SetAvailableMapGoals( TEAM.ALLIES, false, "DEFEND_.*" );
SetAvailableMapGoals( TEAM.ALLIES, false, "SNIPE_.*" );
SetAvailableMapGoals( TEAM.ALLIES, true, "SNIPE_allies_relic.*" );
SetAvailableMapGoals( TEAM.AXIS, true, "SNIPE_axis_relic.*" );
// set max users for goals
Util.SetMaxUsersInProgress( 1, "GRENADE_.*" );
Util.SetMaxUsersInProgress( 1, "MOBILEM.*" );
Util.SetMaxUsersInProgress( 1, "BUILD.*" );
Util.SetMaxUsersInProgress( 1, "PLANT.*" );
Util.SetMaxUsersInProgress( 1, "SNIPE.*" );
Util.SetMaxUsersInProgress( 1, "DEFEND.*" );
Util.SetMaxUsersInProgress( 1, "ATTACK.*" );
Util.SetMaxUsersInProgress( 3, "FLAG_.*" );
// Routes
MapRoutes =
{
PLANT_Relic_Box =
{
ROUTE_allied_spawn =
{
ROUTE_as_right = {},
ROUTE_as_left =
{
ROUTE_door_left = {},
ROUTE_door_right = {}
},
}
},
PLANT_Front_door =
{
ROUTE_allied_spawn =
{
ROUTE_as_right = {},
ROUTE_as_left =
{
ROUTE_door_left = {},
ROUTE_door_right = {}
},
}
},
FLAG_relic =
{
ROUTE_allied_spawn =
{
ROUTE_ladder = {},
ROUTE_as_right = {},
ROUTE_as_left =
{
ROUTE_door_left = {},
ROUTE_door_right = {}
},
}
},
CAPPOINT_relic =
{
ROUTE_box =
{
ROUTE_stairs1 = {},
ROUTE_stairs2 = {},
ROUTE_jump = {},
ROUTE_jump2 = {},
ROUTE_balcony = {},
},
},
};
MapRoutes.ATTACK_cappoint1 = MapRoutes.CAPPOINT_relic;
MapRoutes.ATTACK_cappoint2 = MapRoutes.CAPPOINT_relic;
MapRoutes.ATTACK_cappoint3 = MapRoutes.CAPPOINT_relic;
Util.Routes(MapRoutes);
Util.MapDebugPrint( "OnMapLoad" );
};
global OnBotJoin = function( bot )
{
}; | 412 | 0.978347 | 1 | 0.978347 | game-dev | MEDIA | 0.917798 | game-dev,testing-qa | 0.95154 | 1 | 0.95154 |
s0bvi/goldsvet-opensource | 41,758 | casino/app/Games/DragonSpiritEGT/SlotSettings.php | <?php
namespace VanguardLTE\Games\DragonSpiritEGT
{
class SlotSettings
{
public $playerId = null;
public $splitScreen = null;
public $reelStrip1 = null;
public $reelStrip2 = null;
public $reelStrip3 = null;
public $reelStrip4 = null;
public $reelStrip5 = null;
public $reelStrip6 = null;
public $reelStripBonus1 = null;
public $reelStripBonus2 = null;
public $reelStripBonus3 = null;
public $reelStripBonus4 = null;
public $reelStripBonus5 = null;
public $reelStripBonus6 = null;
public $slotId = '';
public $slotDBId = '';
public $Line = null;
public $scaleMode = null;
public $numFloat = null;
public $gameLine = null;
public $Bet = null;
public $isBonusStart = null;
public $Balance = null;
public $SymbolGame = null;
public $GambleType = null;
public $lastEvent = null;
public $Jackpots = [];
public $keyController = null;
public $slotViewState = null;
public $hideButtons = null;
public $slotReelsConfig = null;
public $slotFreeCount = null;
public $slotFreeMpl = null;
public $slotWildMpl = null;
public $slotExitUrl = null;
public $slotBonus = null;
public $slotBonusType = null;
public $slotScatterType = null;
public $slotGamble = null;
public $Paytable = [];
public $slotSounds = [];
public $jpgs = null;
private $Bank = null;
private $Percent = null;
private $WinLine = null;
private $WinGamble = null;
private $Bonus = null;
private $shop_id = null;
public $licenseDK = null;
public $currency = null;
public $user = null;
public $game = null;
public $shop = null;
public $jpgPercentZero = false;
public $count_balance = null;
public function __construct($sid, $playerId)
{
$this->slotId = $sid;
$this->playerId = $playerId;
$user = \VanguardLTE\User::lockForUpdate()->find($this->playerId);
$this->user = $user;
$this->shop_id = $user->shop_id;
$gamebank = \VanguardLTE\GameBank::where(['shop_id' => $this->shop_id])->lockForUpdate()->get();
$this->username = $user->username;
$game = \VanguardLTE\Game::where([
'name' => $this->slotId,
'shop_id' => $this->shop_id
])->lockForUpdate()->first();
$this->shop = \VanguardLTE\Shop::find($this->shop_id);
$this->game = $game;
$this->MaxWin = $this->shop->max_win;
$this->increaseRTP = 1;
$this->CurrentDenomGame = $this->game->denomination;
$this->Denominations = \VanguardLTE\Game::$values['denomination'];
$this->CurrentDenom = 1;
$this->scaleMode = 0;
$this->numFloat = 0;
$this->Paytable['SYM_0'] = [
0,
0,
0,
5,
10,
30
];
$this->Paytable['SYM_1'] = [
0,
0,
0,
5,
20,
50
];
$this->Paytable['SYM_2'] = [
0,
0,
0,
5,
20,
80
];
$this->Paytable['SYM_3'] = [
0,
0,
0,
5,
25,
100
];
$this->Paytable['SYM_4'] = [
0,
0,
0,
10,
25,
150
];
$this->Paytable['SYM_5'] = [
0,
0,
0,
10,
50,
200
];
$this->Paytable['SYM_6'] = [
0,
0,
0,
10,
50,
250
];
$this->Paytable['SYM_7'] = [
0,
0,
2,
25,
50,
400
];
$this->Paytable['SYM_8'] = [
0,
0,
2,
30,
75,
500
];
$this->Paytable['SYM_9'] = [
0,
0,
5,
50,
200,
1000
];
$this->Paytable['SYM_10'] = [
0,
0,
0,
5,
0,
0
];
$reel = new GameReel();
foreach( [
'reelStrip1',
'reelStrip2',
'reelStrip3',
'reelStrip4',
'reelStrip5',
'reelStrip6'
] as $reelStrip )
{
if( count($reel->reelsStrip[$reelStrip]) )
{
$this->$reelStrip = $reel->reelsStrip[$reelStrip];
}
}
$this->keyController = [
'13' => 'uiButtonSpin,uiButtonSkip',
'49' => 'uiButtonInfo',
'50' => 'uiButtonCollect',
'51' => 'uiButtonExit2',
'52' => 'uiButtonLinesMinus',
'53' => 'uiButtonLinesPlus',
'54' => 'uiButtonBetMinus',
'55' => 'uiButtonBetPlus',
'56' => 'uiButtonGamble',
'57' => 'uiButtonRed',
'48' => 'uiButtonBlack',
'189' => 'uiButtonAuto',
'187' => 'uiButtonSpin'
];
$this->slotReelsConfig = [
[
425,
142,
3
],
[
669,
142,
3
],
[
913,
142,
3
],
[
1157,
142,
3
],
[
1401,
142,
3
]
];
$this->slotBonusType = 1;
$this->slotScatterType = 0;
$this->splitScreen = false;
$this->slotBonus = true;
$this->slotGamble = true;
$this->slotFastStop = 1;
$this->slotExitUrl = '/';
$this->slotWildMpl = 1;
$this->GambleType = 1;
$this->slotFreeCount = 15;
$this->slotFreeMpl = 1;
$this->slotViewState = ($game->slotViewState == '' ? 'Normal' : $game->slotViewState);
$this->hideButtons = [];
$this->jpgs = \VanguardLTE\JPG::where('shop_id', $this->shop_id)->lockForUpdate()->get();
$this->slotJackPercent = [];
$this->slotJackpot = [];
for( $jp = 0; $jp < 4; $jp++ )
{
if( $this->jpgs[$jp]->balance != '' )
{
$this->slotJackpot[$jp] = sprintf('%01.4f', $this->jpgs[$jp]->balance);
$this->slotJackpot[$jp] = substr($this->slotJackpot[$jp], 0, strlen($this->slotJackpot[$jp]) - 2);
$this->slotJackPercent[] = $this->jpgs[$jp]->percent;
}
}
$this->Line = [
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15
];
$this->gameLine = [
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15
];
$this->Bet = explode(',', $game->bet);
$this->Bet = array_slice($this->Bet, 0, 5);
$this->Balance = $user->balance;
$this->SymbolGame = [
'0',
'1',
2,
3,
4,
5,
6,
7,
8,
9
];
$this->Bank = $game->get_gamebank();
$this->Percent = $this->shop->percent;
$this->WinGamble = $game->rezerv;
$this->slotDBId = $game->id;
$this->slotCurrency = $user->shop->currency;
$this->count_balance = $user->count_balance;
if( $user->address > 0 && $user->count_balance == 0 )
{
$this->Percent = 0;
$this->jpgPercentZero = true;
}
else if( $user->count_balance == 0 )
{
$this->Percent = 100;
}
if( !isset($this->user->session) || strlen($this->user->session) <= 0 )
{
$this->user->session = serialize([]);
}
$this->gameData = unserialize($this->user->session);
if( count($this->gameData) > 0 )
{
foreach( $this->gameData as $key => $vl )
{
if( $vl['timelife'] <= time() )
{
unset($this->gameData[$key]);
}
}
}
if( !isset($this->game->advanced) || strlen($this->game->advanced) <= 0 )
{
$this->game->advanced = serialize([]);
}
$this->gameDataStatic = unserialize($this->game->advanced);
if( count($this->gameDataStatic) > 0 )
{
foreach( $this->gameDataStatic as $key => $vl )
{
if( $vl['timelife'] <= time() )
{
unset($this->gameDataStatic[$key]);
}
}
}
}
public function is_active()
{
if( $this->game && $this->shop && $this->user && (!$this->game->view || $this->shop->is_blocked || $this->user->is_blocked || $this->user->status == \VanguardLTE\Support\Enum\UserStatus::BANNED) )
{
\VanguardLTE\Session::where('user_id', $this->user->id)->delete();
$this->user->update(['remember_token' => null]);
return false;
}
if( !$this->game->view )
{
return false;
}
if( $this->shop->is_blocked )
{
return false;
}
if( $this->user->is_blocked )
{
return false;
}
if( $this->user->status == \VanguardLTE\Support\Enum\UserStatus::BANNED )
{
return false;
}
return true;
}
public function SetGameData($key, $value)
{
$timeLife = 86400;
$this->gameData[$key] = [
'timelife' => time() + $timeLife,
'payload' => $value
];
}
public function GetGameData($key)
{
if( isset($this->gameData[$key]) )
{
return $this->gameData[$key]['payload'];
}
else
{
return 0;
}
}
public function FormatFloat($num)
{
$str0 = explode('.', $num);
if( isset($str0[1]) )
{
if( strlen($str0[1]) > 4 )
{
return round($num * 100) / 100;
}
else if( strlen($str0[1]) > 2 )
{
return floor($num * 100) / 100;
}
else
{
return $num;
}
}
else
{
return $num;
}
}
public function SaveGameData()
{
$this->user->session = serialize($this->gameData);
$this->user->save();
}
public function CheckBonusWin()
{
$allRateCnt = 0;
$allRate = 0;
foreach( $this->Paytable as $vl )
{
foreach( $vl as $vl2 )
{
if( $vl2 > 0 )
{
$allRateCnt++;
$allRate += $vl2;
break;
}
}
}
return $allRate / $allRateCnt;
}
public function GetRandomPay()
{
$allRate = [];
foreach( $this->Paytable as $vl )
{
foreach( $vl as $vl2 )
{
if( $vl2 > 0 )
{
$allRate[] = $vl2;
}
}
}
shuffle($allRate);
if( $this->game->stat_in < ($this->game->stat_out + ($allRate[0] * $this->AllBet)) )
{
$allRate[0] = 0;
}
return $allRate[0];
}
public function HasGameDataStatic($key)
{
if( isset($this->gameDataStatic[$key]) )
{
return true;
}
else
{
return false;
}
}
public function SaveGameDataStatic()
{
$this->game->advanced = serialize($this->gameDataStatic);
$this->game->save();
$this->game->refresh();
}
public function SetGameDataStatic($key, $value)
{
$timeLife = 86400;
$this->gameDataStatic[$key] = [
'timelife' => time() + $timeLife,
'payload' => $value
];
}
public function GetGameDataStatic($key)
{
if( isset($this->gameDataStatic[$key]) )
{
return $this->gameDataStatic[$key]['payload'];
}
else
{
return 0;
}
}
public function HasGameData($key)
{
if( isset($this->gameData[$key]) )
{
return true;
}
else
{
return false;
}
}
public function GetHistory()
{
$history = \VanguardLTE\GameLog::whereRaw('game_id=? and user_id=? ORDER BY id DESC LIMIT 10', [
$this->slotDBId,
$this->playerId
])->get();
$this->lastEvent = 'NULL';
foreach( $history as $log )
{
if( $log->str == 'NONE' )
{
return 'NULL';
}
$tmpLog = json_decode($log->str);
if( $tmpLog->responseEvent != 'gambleResult' && $tmpLog->responseEvent != 'jackpot' )
{
$this->lastEvent = $log->str;
break;
}
}
if( isset($tmpLog) )
{
return $tmpLog;
}
else
{
return 'NULL';
}
}
public function ClearJackpot($jid)
{
$this->jpgs[$jid]->balance = sprintf('%01.4f', 0);
$this->jpgs[$jid]->save();
}
public function UpdateJackpots($bet)
{
$bet = $bet * $this->CurrentDenom;
$count_balance = $this->count_balance;
$slotJackSum = [];
$game = $this->game;
$isJackPay = 0;
$isJackId = 0;
for( $jp = 1; $jp <= 4; $jp++ )
{
if( $this->jpgs[$jp - 1]->balance != '' )
{
$this->slotJackpot[$jp - 1] = number_format($this->jpgs[$jp - 1]->balance, 4, '.', '');
if( $count_balance == 0 || $this->jpgPercentZero )
{
$slotJackSum[$jp - 1] = $this->slotJackpot[$jp - 1];
}
else if( $count_balance < $bet )
{
$slotJackSum[$jp - 1] = number_format($count_balance / 100 * $this->slotJackPercent[$jp - 1] + $this->slotJackpot[$jp - 1], 4, '.', '');
}
else
{
$slotJackSum[$jp - 1] = number_format($bet / 100 * $this->slotJackPercent[$jp - 1] + $this->slotJackpot[$jp - 1], 4, '.', '');
}
$leftOver = $slotJackSum[$jp - 1];
if( $this->jpgs[$jp - 1]->get_pay_sum() <= $this->slotJackpot[$jp - 1] && !$isJackPay && $this->jpgs[$jp - 1]->get_pay_sum() > 0 )
{
if( $this->jpgs[$jp - 1]->user_id && $this->jpgs[$jp - 1]->user_id != $this->user->id )
{
}
else
{
$isJackPay = 1;
$isJackId = $jp - 1;
}
}
$this->slotJackpot[$jp - 1] = sprintf('%01.2f', $slotJackSum[$jp - 1]);
$this->jpgs[$jp - 1]->balance = sprintf('%01.4f', $leftOver);
$this->jpgs[$jp - 1]->save();
}
}
$game->save();
for( $jp = 0; $jp < 4; $jp++ )
{
if( $this->jpgs[$jp]->balance != '' && $this->jpgs[$jp]->balance < $this->jpgs[$jp]->get_min('start_balance') )
{
$summ = $this->jpgs[$jp]->get_start_balance() - $this->jpgs[$jp]->balance;
if( $summ > 0 )
{
$this->jpgs[$jp]->add_jpg('add', $summ);
}
}
}
return [
'isJackPay' => $isJackPay,
'isJackId' => $isJackId
];
}
public function GetBank($slotState = '')
{
if( $this->isBonusStart || $slotState == 'bonus' || $slotState == 'freespin' || $slotState == 'respin' )
{
$slotState = 'bonus';
}
else
{
$slotState = '';
}
$game = $this->game;
$this->Bank = $game->get_gamebank($slotState);
return $this->Bank / $this->CurrentDenom;
}
public function GetPercent()
{
return $this->Percent;
}
public function GetCountBalanceUser()
{
return $this->user->count_balance;
}
public function InternalErrorSilent($errcode)
{
$strLog = '';
$strLog .= "\n";
$strLog .= ('{"responseEvent":"error","responseType":"' . $errcode . '","serverResponse":"InternalError","request":' . json_encode($_REQUEST) . ',"requestRaw":' . file_get_contents('php://input') . '}');
$strLog .= "\n";
$strLog .= ' ############################################### ';
$strLog .= "\n";
$slg = '';
if( file_exists(storage_path('logs/') . $this->slotId . 'Internal.log') )
{
$slg = file_get_contents(storage_path('logs/') . $this->slotId . 'Internal.log');
}
file_put_contents(storage_path('logs/') . $this->slotId . 'Internal.log', $slg . $strLog);
}
public function InternalError($errcode)
{
$strLog = '';
$strLog .= "\n";
$strLog .= ('{"responseEvent":"error","responseType":"' . $errcode . '","serverResponse":"InternalError","request":' . json_encode($_REQUEST) . ',"requestRaw":' . file_get_contents('php://input') . '}');
$strLog .= "\n";
$strLog .= ' ############################################### ';
$strLog .= "\n";
$slg = '';
if( file_exists(storage_path('logs/') . $this->slotId . 'Internal.log') )
{
$slg = file_get_contents(storage_path('logs/') . $this->slotId . 'Internal.log');
}
file_put_contents(storage_path('logs/') . $this->slotId . 'Internal.log', $slg . $strLog);
exit( '' );
}
public function SetBank($slotState = '', $sum, $slotEvent = '')
{
if( $this->isBonusStart || $slotState == 'bonus' || $slotState == 'freespin' || $slotState == 'respin' )
{
$slotState = 'bonus';
}
else
{
$slotState = '';
}
if( $this->GetBank($slotState) + $sum < 0 )
{
$this->InternalError('Bank_ ' . $sum . ' CurrentBank_ ' . $this->GetBank($slotState) . ' CurrentState_ ' . $slotState . ' Trigger_ ' . ($this->GetBank($slotState) + $sum));
}
$sum = $sum * $this->CurrentDenom;
$game = $this->game;
$bankBonusSum = 0;
if( $sum > 0 && $slotEvent == 'bet' )
{
$this->toGameBanks = 0;
$this->toSlotJackBanks = 0;
$this->toSysJackBanks = 0;
$this->betProfit = 0;
$prc = $this->GetPercent();
$prc_b = 10;
if( $prc <= $prc_b )
{
$prc_b = 0;
}
$count_balance = $this->count_balance;
$gameBet = $sum / $this->GetPercent() * 100;
if( $count_balance < $gameBet && $count_balance > 0 )
{
$firstBid = $count_balance;
$secondBid = $gameBet - $firstBid;
if( isset($this->betRemains0) )
{
$secondBid = $this->betRemains0;
}
$bankSum = $firstBid / 100 * $this->GetPercent();
$sum = $bankSum + $secondBid;
$bankBonusSum = $firstBid / 100 * $prc_b;
}
else if( $count_balance > 0 )
{
$bankBonusSum = $gameBet / 100 * $prc_b;
}
for( $i = 0; $i < count($this->jpgs); $i++ )
{
if( !$this->jpgPercentZero )
{
if( $count_balance < $gameBet && $count_balance > 0 )
{
$this->toSlotJackBanks += ($count_balance / 100 * $this->jpgs[$i]->percent);
}
else if( $count_balance > 0 )
{
$this->toSlotJackBanks += ($gameBet / 100 * $this->jpgs[$i]->percent);
}
}
}
$this->toGameBanks = $sum;
$this->betProfit = $gameBet - $this->toGameBanks - $this->toSlotJackBanks - $this->toSysJackBanks;
}
if( $sum > 0 )
{
$this->toGameBanks = $sum;
}
if( $bankBonusSum > 0 )
{
$sum -= $bankBonusSum;
$game->set_gamebank($bankBonusSum, 'inc', 'bonus');
}
if( $sum == 0 && $slotEvent == 'bet' && isset($this->betRemains) )
{
$sum = $this->betRemains;
}
$game->set_gamebank($sum, 'inc', $slotState);
$game->save();
return $game;
}
public function SetBalance($sum, $slotEvent = '')
{
if( $this->GetBalance() + $sum < 0 )
{
$this->InternalError('Balance_ ' . $sum);
}
$sum = $sum * $this->CurrentDenom;
if( $sum < 0 && $slotEvent == 'bet' )
{
$user = $this->user;
if( $user->count_balance == 0 )
{
$remains = [];
$this->betRemains = 0;
$sm = abs($sum);
if( $user->address < $sm && $user->address > 0 )
{
$remains[] = $sm - $user->address;
}
for( $i = 0; $i < count($remains); $i++ )
{
if( $this->betRemains < $remains[$i] )
{
$this->betRemains = $remains[$i];
}
}
}
if( $user->count_balance > 0 && $user->count_balance < abs($sum) )
{
$remains0 = [];
$sm = abs($sum);
$tmpSum = $sm - $user->count_balance;
$this->betRemains0 = $tmpSum;
if( $user->address > 0 )
{
$this->betRemains0 = 0;
if( $user->address < $tmpSum && $user->address > 0 )
{
$remains0[] = $tmpSum - $user->address;
}
for( $i = 0; $i < count($remains0); $i++ )
{
if( $this->betRemains0 < $remains0[$i] )
{
$this->betRemains0 = $remains0[$i];
}
}
}
}
$sum0 = abs($sum);
if( $user->count_balance == 0 )
{
$sm = abs($sum);
if( $user->address < $sm && $user->address > 0 )
{
$user->address = 0;
}
else if( $user->address > 0 )
{
$user->address -= $sm;
}
}
else if( $user->count_balance > 0 && $user->count_balance < $sum0 )
{
$sm = $sum0 - $user->count_balance;
if( $user->address < $sm && $user->address > 0 )
{
$user->address = 0;
}
else if( $user->address > 0 )
{
$user->address -= $sm;
}
}
$this->user->count_balance = $this->user->updateCountBalance($sum, $this->count_balance);
$this->user->count_balance = $this->FormatFloat($this->user->count_balance);
}
$this->user->increment('balance', $sum);
$this->user->balance = $this->FormatFloat($this->user->balance);
$this->user->save();
return $this->user;
}
public function GetBalance()
{
$user = $this->user;
$this->Balance = $user->balance / $this->CurrentDenom;
return $this->Balance;
}
public function SaveLogReport($spinSymbols, $bet, $lines, $win, $slotState)
{
$reportName = $this->slotId . ' ' . $slotState;
if( $slotState == 'freespin' )
{
$reportName = $this->slotId . ' FG';
}
else if( $slotState == 'bet' )
{
$reportName = $this->slotId . '';
}
else if( $slotState == 'slotGamble' )
{
$reportName = $this->slotId . ' DG';
}
$game = $this->game;
if( $slotState == 'bet' )
{
$this->user->update_level('bet', $bet * $this->CurrentDenom);
}
if( $slotState != 'freespin' )
{
$game->increment('stat_in', $bet * $this->CurrentDenom);
}
$game->increment('stat_out', $win * $this->CurrentDenom);
$game->tournament_stat($slotState, $this->user->id, $bet * $this->CurrentDenom, $win * $this->CurrentDenom);
$this->user->update(['last_bid' => \Carbon\Carbon::now()]);
if( !isset($this->betProfit) )
{
$this->betProfit = 0;
$this->toGameBanks = 0;
$this->toSlotJackBanks = 0;
$this->toSysJackBanks = 0;
}
if( !isset($this->toGameBanks) )
{
$this->toGameBanks = 0;
}
$this->game->increment('bids');
$this->game->refresh();
$gamebank = \VanguardLTE\GameBank::where(['shop_id' => $game->shop_id])->first();
if( $gamebank )
{
list($slotsBank, $bonusBank, $fishBank, $tableBank, $littleBank) = \VanguardLTE\Lib\Banker::get_all_banks($game->shop_id);
}
else
{
$slotsBank = $game->get_gamebank('', 'slots');
$bonusBank = $game->get_gamebank('bonus', 'bonus');
$fishBank = $game->get_gamebank('', 'fish');
$tableBank = $game->get_gamebank('', 'table_bank');
$littleBank = $game->get_gamebank('', 'little');
}
$totalBank = $slotsBank + $bonusBank + $fishBank + $tableBank + $littleBank;
\VanguardLTE\GameLog::create([
'game_id' => $this->slotDBId,
'user_id' => $this->playerId,
'ip' => $_SERVER['REMOTE_ADDR'],
'str' => $spinSymbols,
'shop_id' => $this->shop_id
]);
\VanguardLTE\StatGame::create([
'user_id' => $this->playerId,
'balance' => $this->Balance * $this->CurrentDenom,
'bet' => $bet * $this->CurrentDenom,
'win' => $win * $this->CurrentDenom,
'game' => $reportName,
'in_game' => $this->toGameBanks,
'in_jpg' => $this->toSlotJackBanks,
'in_profit' => $this->betProfit,
'denomination' => $this->CurrentDenom,
'shop_id' => $this->shop_id,
'slots_bank' => (double)$slotsBank,
'bonus_bank' => (double)$bonusBank,
'fish_bank' => (double)$fishBank,
'table_bank' => (double)$tableBank,
'little_bank' => (double)$littleBank,
'total_bank' => (double)$totalBank,
'date_time' => \Carbon\Carbon::now()
]);
}
public function GetSpinSettings($garantType = 'bet', $bet, $lines)
{
$curField = 10;
switch( $lines )
{
case 10:
$curField = 10;
break;
case 9:
case 8:
$curField = 9;
break;
case 7:
case 6:
$curField = 7;
break;
case 5:
case 4:
$curField = 5;
break;
case 3:
case 2:
$curField = 3;
break;
case 1:
$curField = 1;
break;
default:
$curField = 10;
break;
}
if( $garantType != 'bet' )
{
$pref = '_bonus';
}
else
{
$pref = '';
}
$this->AllBet = $bet * $lines;
$linesPercentConfigSpin = $this->game->get_lines_percent_config('spin');
$linesPercentConfigBonus = $this->game->get_lines_percent_config('bonus');
$currentPercent = $this->shop->percent;
$currentSpinWinChance = 0;
$currentBonusWinChance = 0;
$percentLevel = '';
foreach( $linesPercentConfigSpin['line' . $curField . $pref] as $k => $v )
{
$l = explode('_', $k);
$l0 = $l[0];
$l1 = $l[1];
if( $l0 <= $currentPercent && $currentPercent <= $l1 )
{
$percentLevel = $k;
break;
}
}
$currentSpinWinChance = $linesPercentConfigSpin['line' . $curField . $pref][$percentLevel];
$currentBonusWinChance = $linesPercentConfigBonus['line' . $curField . $pref][$percentLevel];
$RtpControlCount = 200;
if( !$this->HasGameDataStatic('SpinWinLimit') )
{
$this->SetGameDataStatic('SpinWinLimit', 0);
}
if( !$this->HasGameDataStatic('RtpControlCount') )
{
$this->SetGameDataStatic('RtpControlCount', $RtpControlCount);
}
if( $this->game->stat_in > 0 )
{
$rtpRange = $this->game->stat_out / $this->game->stat_in * 100;
}
else
{
$rtpRange = 0;
}
if( $this->GetGameDataStatic('RtpControlCount') == 0 )
{
if( $currentPercent + rand(1, 2) < $rtpRange && $this->GetGameDataStatic('SpinWinLimit') <= 0 )
{
$this->SetGameDataStatic('SpinWinLimit', rand(25, 50));
}
if( $pref == '' && $this->GetGameDataStatic('SpinWinLimit') > 0 )
{
$currentBonusWinChance = 5000;
$currentSpinWinChance = 20;
$this->MaxWin = rand(1, 5);
if( $rtpRange < ($currentPercent - 1) )
{
$this->SetGameDataStatic('SpinWinLimit', 0);
$this->SetGameDataStatic('RtpControlCount', $this->GetGameDataStatic('RtpControlCount') - 1);
}
}
}
else if( $this->GetGameDataStatic('RtpControlCount') < 0 )
{
if( $currentPercent + rand(1, 2) < $rtpRange && $this->GetGameDataStatic('SpinWinLimit') <= 0 )
{
$this->SetGameDataStatic('SpinWinLimit', rand(25, 50));
}
$this->SetGameDataStatic('RtpControlCount', $this->GetGameDataStatic('RtpControlCount') - 1);
if( $pref == '' && $this->GetGameDataStatic('SpinWinLimit') > 0 )
{
$currentBonusWinChance = 5000;
$currentSpinWinChance = 20;
$this->MaxWin = rand(1, 5);
if( $rtpRange < ($currentPercent - 1) )
{
$this->SetGameDataStatic('SpinWinLimit', 0);
}
}
if( $this->GetGameDataStatic('RtpControlCount') < (-1 * $RtpControlCount) && $currentPercent - 1 <= $rtpRange && $rtpRange <= ($currentPercent + 2) )
{
$this->SetGameDataStatic('RtpControlCount', $RtpControlCount);
}
}
else
{
$this->SetGameDataStatic('RtpControlCount', $this->GetGameDataStatic('RtpControlCount') - 1);
}
$bonusWin = rand(1, $currentBonusWinChance);
$spinWin = rand(1, $currentSpinWinChance);
$return = [
'none',
0
];
if( $bonusWin == 1 && $this->slotBonus )
{
$this->isBonusStart = true;
$garantType = 'bonus';
$winLimit = $this->GetBank($garantType);
$return = [
'bonus',
$winLimit
];
if( $this->game->stat_in < ($this->CheckBonusWin() * $bet + $this->game->stat_out) || $winLimit < ($this->CheckBonusWin() * $bet) )
{
$return = [
'none',
0
];
}
}
else if( $spinWin == 1 )
{
$winLimit = $this->GetBank($garantType);
$return = [
'win',
$winLimit
];
}
if( $garantType == 'bet' && $this->GetBalance() <= (2 / $this->CurrentDenom) )
{
$randomPush = rand(1, 10);
if( $randomPush == 1 )
{
$winLimit = $this->GetBank('');
$return = [
'win',
$winLimit
];
}
}
return $return;
}
public function GetRandomScatterPos($rp)
{
$rpResult = [];
for( $i = 0; $i < count($rp); $i++ )
{
if( $rp[$i] == '10' )
{
if( isset($rp[$i + 1]) && isset($rp[$i - 1]) )
{
array_push($rpResult, $i);
}
if( isset($rp[$i + 1]) && isset($rp[$i + 2]) )
{
array_push($rpResult, $i + 1);
}
if( isset($rp[$i - 1]) && isset($rp[$i - 2]) )
{
array_push($rpResult, $i - 1);
}
}
}
shuffle($rpResult);
if( !isset($rpResult[0]) )
{
$rpResult[0] = rand(2, count($rp) - 3);
}
return $rpResult[0];
}
public function GetGambleSettings()
{
$spinWin = rand(1, $this->WinGamble);
return $spinWin;
}
public function GetReelStrips($winType, $slotEvent)
{
$game = $this->game;
if( $slotEvent == 'freespin' )
{
$reel = new GameReel();
$fArr = $reel->reelsStripBonus;
foreach( [
'reelStrip1',
'reelStrip2',
'reelStrip3',
'reelStrip4',
'reelStrip5',
'reelStrip6'
] as $reelStrip )
{
$curReel = array_shift($fArr);
if( count($curReel) )
{
$this->$reelStrip = $curReel;
}
}
}
if( $winType != 'bonus' )
{
$prs = [];
foreach( [
'reelStrip1',
'reelStrip2',
'reelStrip3',
'reelStrip4',
'reelStrip5',
'reelStrip6'
] as $index => $reelStrip )
{
if( is_array($this->$reelStrip) && count($this->$reelStrip) > 0 )
{
$prs[$index + 1] = mt_rand(0, count($this->$reelStrip) - 3);
}
}
}
else
{
$reelsId = [
1,
2,
3,
4,
5
];
for( $i = 0; $i < count($reelsId); $i++ )
{
if( $i == 0 || $i == 2 || $i == 4 )
{
$prs[$reelsId[$i]] = $this->GetRandomScatterPos($this->{'reelStrip' . $reelsId[$i]});
}
else
{
$prs[$reelsId[$i]] = rand(0, count($this->{'reelStrip' . $reelsId[$i]}) - 3);
}
}
}
$reel = [
'rp' => []
];
foreach( $prs as $index => $value )
{
$key = $this->{'reelStrip' . $index};
$cnt = count($key);
$key[-1] = $key[$cnt - 1];
$key[$cnt] = $key[0];
$reel['reel' . $index][0] = $key[$value - 1];
$reel['reel' . $index][1] = $key[$value];
$reel['reel' . $index][2] = $key[$value + 1];
$reel['reel' . $index][3] = '';
$reel['rp'][] = $value;
}
return $reel;
}
}
}
| 412 | 0.645435 | 1 | 0.645435 | game-dev | MEDIA | 0.580977 | game-dev,web-backend | 0.79016 | 1 | 0.79016 |
Horizon-Private-Server/horizon-forge | 19,324 | codegen/rc4/survival/stackbox.c | /***************************************************
* FILENAME : stackbox.c
*
* DESCRIPTION :
* Handles logic for the stack box.
*
* AUTHOR : Daniel "Dnawrkshp" Gerendasy
*/
#include <tamtypes.h>
#include <libdl/dl.h>
#include <libdl/player.h>
#include <libdl/pad.h>
#include <libdl/time.h>
#include <libdl/net.h>
#include <libdl/game.h>
#include <libdl/string.h>
#include <libdl/math.h>
#include <libdl/random.h>
#include <libdl/math3d.h>
#include <libdl/radar.h>
#include <libdl/stdio.h>
#include <libdl/gamesettings.h>
#include <libdl/dialog.h>
#include <libdl/sound.h>
#include <libdl/patch.h>
#include <libdl/ui.h>
#include <libdl/graphics.h>
#include <libdl/color.h>
#include <libdl/utils.h>
#include "stackbox.h"
#include "game.h"
#include "gate.h"
#include "messageid.h"
#include "maputils.h"
#include "common.h"
char* STACKABLE_ITEM_NAMES[] = {
[STACKABLE_ITEM_EXTRA_JUMP] "Extra Jump Perk",
[STACKABLE_ITEM_EXTRA_SHOT] "Double Shot Perk",
[STACKABLE_ITEM_HOVERBOOTS] "Hoverboots Perk",
[STACKABLE_ITEM_LOW_HEALTH_DMG_BUF] "Berserker Perk",
[STACKABLE_ITEM_ALPHA_MOD_AMMO] "Ammo Mod Perk",
[STACKABLE_ITEM_ALPHA_MOD_SPEED] "Speed Mod Perk",
[STACKABLE_ITEM_ALPHA_MOD_AREA] "Area Mod Perk",
[STACKABLE_ITEM_ALPHA_MOD_IMPACT] "Impact Mod Perk",
[STACKABLE_ITEM_VAMPIRE] "Vampire Perk",
};
char* STACKABLE_ITEM_DESC[] = {
[STACKABLE_ITEM_EXTRA_JUMP] "Gives +1 extra jump",
[STACKABLE_ITEM_EXTRA_SHOT] "Shoots +1 shot each time you fire",
[STACKABLE_ITEM_HOVERBOOTS] "Gives hoverboots, +10%% movement speed, removes chargeboots",
[STACKABLE_ITEM_LOW_HEALTH_DMG_BUF] "Grants +75%% bonus damage for amount of health missing",
[STACKABLE_ITEM_ALPHA_MOD_AMMO] "Gives +2 extra ammo mod for all weapons",
[STACKABLE_ITEM_ALPHA_MOD_SPEED] "Gives +2 extra speed mod for all weapons",
[STACKABLE_ITEM_ALPHA_MOD_AREA] "Gives +2 extra area mod for all weapons",
[STACKABLE_ITEM_ALPHA_MOD_IMPACT] "Gives +2 extra impact mod for all weapons",
[STACKABLE_ITEM_VAMPIRE] "Gives +3 health after each kill, disables health pickups",
};
int STACKABLE_ITEM_TEX_IDS[] = {
[STACKABLE_ITEM_EXTRA_JUMP] 138,
[STACKABLE_ITEM_EXTRA_SHOT] 108,
[STACKABLE_ITEM_HOVERBOOTS] 60,
[STACKABLE_ITEM_LOW_HEALTH_DMG_BUF] 109,
[STACKABLE_ITEM_ALPHA_MOD_AMMO] 41 - 3,
[STACKABLE_ITEM_ALPHA_MOD_SPEED] 55 - 3,
[STACKABLE_ITEM_ALPHA_MOD_AREA] 42 - 3,
[STACKABLE_ITEM_ALPHA_MOD_IMPACT] 47 - 3,
[STACKABLE_ITEM_VAMPIRE] 110,
};
u32 STACKABLE_ITEM_COLORS[] = {
[STACKABLE_ITEM_EXTRA_JUMP] 0x80808080,
[STACKABLE_ITEM_EXTRA_SHOT] 0x80808080,
[STACKABLE_ITEM_HOVERBOOTS] 0x80808080,
[STACKABLE_ITEM_LOW_HEALTH_DMG_BUF] 0x80808080,
[STACKABLE_ITEM_ALPHA_MOD_AMMO] 0x80808080,
[STACKABLE_ITEM_ALPHA_MOD_SPEED] 0x80808080,
[STACKABLE_ITEM_ALPHA_MOD_AREA] 0x80808080,
[STACKABLE_ITEM_ALPHA_MOD_IMPACT] 0x80808080,
[STACKABLE_ITEM_VAMPIRE] 0x80808080,
};
//--------------------------------------------------------------------------
int sboxGetStackableCost(int playerId, enum StackableItemId item)
{
if (!MapConfig.State) return 0;
return STACK_BOX_BASE_COST + playerGetStackableCount(playerId, (int)item) * STACK_BOX_ADD_COST;
}
//--------------------------------------------------------------------------
int sboxGetRandomItem(Moby* moby)
{
if (!moby) return rand(STACKABLE_ITEM_COUNT);
struct StackBoxPVar* pvars = (struct StackBoxPVar*)moby->PVar;
// randomly pick an item
// avoid picking the current item
int item = pvars->Item;
while (item == pvars->Item)
item = rand(STACKABLE_ITEM_COUNT);
return item;
}
//--------------------------------------------------------------------------
void sboxActivate(Moby* moby, int state, enum StackableItemId item, int activatedTime)
{
int i;
// create event
GuberEvent * guberEvent = guberCreateEvent(moby, STACK_BOX_EVENT_ACTIVATE);
if (guberEvent) {
guberEventWrite(guberEvent, &state, 4);
guberEventWrite(guberEvent, &item, 4);
guberEventWrite(guberEvent, &activatedTime, 4);
}
}
//--------------------------------------------------------------------------
void sboxGivePlayer(Moby* moby, int playerId, enum StackableItemId item, int cost)
{
// create event
GuberEvent * guberEvent = guberCreateEvent(moby, STACK_BOX_EVENT_GIVE_PLAYER);
if (guberEvent) {
guberEventWrite(guberEvent, &playerId, 4);
guberEventWrite(guberEvent, &item, 4);
guberEventWrite(guberEvent, &cost, 4);
}
}
//--------------------------------------------------------------------------
void sboxPlayerBuy(Moby* moby, int playerId, enum StackableItemId item)
{
int cost = sboxGetStackableCost(playerId, item);
// check if valid
struct StackBoxPVar* pvars = (struct StackBoxPVar*)moby->PVar;
if (moby->State != STACK_BOX_STATE_ACTIVE) return;
if (pvars->Item != item) return;
if (!MapConfig.State) return;
if (MapConfig.State->PlayerStates[playerId].State.Bolts < cost) return;
if ((gameGetTime() - pvars->ActivatedTime) < (TIME_SECOND * 0.2)) return;
// send to host
if (!gameAmIHost()) {
GuberEvent * guberEvent = guberCreateEvent(moby, STACK_BOX_EVENT_PLAYER_BUY);
if (guberEvent) {
guberEventWrite(guberEvent, &playerId, 4);
guberEventWrite(guberEvent, &item, 4);
}
return;
}
// give player
sboxGivePlayer(moby, playerId, item, cost);
// set new item
sboxActivate(moby, moby->State, sboxGetRandomItem(moby), gameGetTime());
}
//--------------------------------------------------------------------------
void sboxPlayerReroll(Moby* moby, int playerId, enum StackableItemId item)
{
int cost = STACK_BOX_REROLL_COST;
// check if valid
struct StackBoxPVar* pvars = (struct StackBoxPVar*)moby->PVar;
if (moby->State != STACK_BOX_STATE_ACTIVE) return;
if (pvars->Item != item) return;
if (!MapConfig.State) return;
if (MapConfig.State->PlayerStates[playerId].State.Bolts < cost) return;
if ((gameGetTime() - pvars->ActivatedTime) < TIME_SECOND) return;
// send to host
if (!gameAmIHost()) {
GuberEvent * guberEvent = guberCreateEvent(moby, STACK_BOX_EVENT_PLAYER_REROLL);
if (guberEvent) {
guberEventWrite(guberEvent, &playerId, 4);
guberEventWrite(guberEvent, &item, 4);
}
return;
}
// deduct cost from player bolts
sboxGivePlayer(moby, playerId, -1, cost);
// set new item
sboxActivate(moby, moby->State, sboxGetRandomItem(moby), gameGetTime());
}
//--------------------------------------------------------------------------
void sboxDraw(Moby* moby)
{
MATRIX m2, mRot;
VECTOR t;
VECTOR offset = {0,0,3,0};
VECTOR pTL = {0.5,0,0.5,1};
VECTOR pTR = {-0.5,0,0.5,1};
VECTOR pBL = {0.5,0,-0.5,1};
VECTOR pBR = {-0.5,0,-0.5,1};
struct QuadDef quad;
if (!moby || !moby->PVar || moby->State == STACK_BOX_STATE_DISABLED)
return;
struct StackBoxPVar* pvars = (struct StackBoxPVar*)moby->PVar;
int item = pvars->Item;
u32 color = STACKABLE_ITEM_COLORS[item];
int texId = STACKABLE_ITEM_TEX_IDS[item];
// set draw args
matrix_unit(m2);
// init
gfxResetQuad(&quad);
// color of each corner?
vector_copy(quad.VertexPositions[0], pTL);
vector_copy(quad.VertexPositions[1], pTR);
vector_copy(quad.VertexPositions[2], pBL);
vector_copy(quad.VertexPositions[3], pBR);
quad.VertexColors[0] = quad.VertexColors[1] = quad.VertexColors[2] = quad.VertexColors[3] = color;
quad.VertexUVs[0] = (struct UV){0,0};
quad.VertexUVs[1] = (struct UV){1,0};
quad.VertexUVs[2] = (struct UV){0,1};
quad.VertexUVs[3] = (struct UV){1,1};
quad.Clamp = 0x0000000100000001;
quad.Tex0 = gfxGetFrameTex(texId);
quad.Tex1 = 0xFF9000000260;
quad.Alpha = 0x8000000044;
GameCamera* camera = cameraGetGameCamera(0);
if (!camera)
return;
// get forward vector
vector_subtract(t, camera->pos, moby->Position);
t[2] = 0;
vector_normalize(&m2[4], t);
// up vector
m2[8 + 2] = 1;
// right vector
vector_outerproduct(&m2[0], &m2[4], &m2[8]);
// position
matrix_unit(mRot);
memcpy(mRot, moby->M0_03, sizeof(VECTOR)*3);
vector_apply(offset, offset, mRot);
vector_scale(offset, offset, 1);
vector_add(&m2[12], moby->Position, offset);
// draw
gfxDrawQuad((void*)0x00222590, &quad, m2, 0);
}
//--------------------------------------------------------------------------
void sboxUpdate(Moby* moby)
{
Player** players = playerGetAll();
int i;
char buf[64];
if (!moby || !moby->PVar)
return;
struct StackBoxPVar* pvars = (struct StackBoxPVar*)moby->PVar;
int timeSinceActivated = gameGetTime() - pvars->ActivatedTime;
// set state
#if !DEBUGSBOX
if (MapConfig.State && MapConfig.State->RoundCompleteTime) {
if (moby->State != STACK_BOX_STATE_ACTIVE) {
if (pvars->BaseMoby) pvars->BaseMoby->ModeBits = MOBY_MODE_BIT_HIDE_BACKFACES | MOBY_MODE_BIT_HAS_GLOW;
mobySetState(moby, STACK_BOX_STATE_ACTIVE, -1);
if (gameAmIHost()) sboxActivate(moby, STACK_BOX_STATE_ACTIVE, rand(STACKABLE_ITEM_COUNT), gameGetTime());
}
} else {
if (moby->State != STACK_BOX_STATE_DISABLED) {
mobySetState(moby, STACK_BOX_STATE_DISABLED, -1);
if (gameAmIHost()) sboxActivate(moby, STACK_BOX_STATE_DISABLED, rand(STACKABLE_ITEM_COUNT), gameGetTime());
}
}
#endif
// show/hide
if (moby->State == STACK_BOX_STATE_DISABLED) {
moby->DrawDist = 0;
moby->CollActive = -1;
if (pvars->BaseMoby) {
pvars->BaseMoby->CollActive = -1;
pvars->BaseMoby->DrawDist = 0;
}
return;
} else {
moby->DrawDist = 255;
moby->CollActive = 0;
if (pvars->BaseMoby) {
pvars->BaseMoby->CollActive = 0;
pvars->BaseMoby->DrawDist = 255;
}
}
// post draw
gfxRegisterDrawFunction((void**)0x0022251C, (gfxDrawFuncDef*)&sboxDraw, moby);
// map icon
int blipIdx = radarGetBlipIndex(moby);
if (blipIdx >= 0) {
RadarBlip * blip = radarGetBlips() + blipIdx;
blip->X = moby->Position[0];
blip->Y = moby->Position[1];
blip->Life = 0x1F;
blip->Type = 5;
blip->Team = TEAM_ORANGE;
}
for (i = 0; i < GAME_MAX_LOCALS; ++i) {
Player* player = playerGetFromSlot(i);
if (!player || !player->pNetPlayer || !playerIsConnected(player)) continue;
// prompt for
int cost = sboxGetStackableCost(player->PlayerId, pvars->Item);
snprintf(buf, sizeof(buf), "\x11 %s \x0E%'d\x08", STACKABLE_ITEM_NAMES[pvars->Item], cost);
if (tryPlayerInteract(moby, player, buf, STACKABLE_ITEM_DESC[pvars->Item], 0, 0, PLAYER_STACK_BOX_COOLDOWN_TICKS, STACK_BOX_MAX_DIST*STACK_BOX_MAX_DIST, PAD_CIRCLE)) {
sboxPlayerBuy(moby, player->PlayerId, pvars->Item);
}
}
}
//--------------------------------------------------------------------------
int sboxHandleEvent_Spawned(Moby* moby, GuberEvent* event)
{
DPRINTF("sbox spawned: %08X\n", (u32)moby);
struct StackBoxPVar* pvars = (struct StackBoxPVar*)moby->PVar;
if (!pvars)
return 0;
// read event
int item;
guberEventRead(event, moby->Position, 12);
guberEventRead(event, moby->Rotation, 12);
guberEventRead(event, &item, 4);
// set update
moby->PUpdate = &sboxUpdate;
// set item
pvars->Item = item;
// add base
Moby* baseMoby = pvars->BaseMoby = mobySpawn(8348, 0);
if (baseMoby) {
vector_copy(baseMoby->Position, moby->Position);
baseMoby->Scale = 0.14;
baseMoby->PUpdate = NULL;
baseMoby->ModeBits = MOBY_MODE_BIT_HIDE_BACKFACES | MOBY_MODE_BIT_HAS_GLOW;
baseMoby->Opacity = 0x80;
baseMoby->UpdateDist = 0xFF;
baseMoby->DrawDist = 0x00FF;
}
// lower glass a bit
moby->Position[2] -= 1;
// update mode reference
if (MapConfig.State) MapConfig.State->Stackbox = moby;
// set default state
mobySetState(moby, STACK_BOX_STATE_ACTIVE, -1);
return 0;
}
//--------------------------------------------------------------------------
int sboxHandleEvent_Activate(Moby* moby, GuberEvent* event)
{
int state, item, activatedTime;
struct StackBoxPVar* pvars = (struct StackBoxPVar*)moby->PVar;
if (!pvars)
return 0;
guberEventRead(event, &state, 4);
guberEventRead(event, &item, 4);
guberEventRead(event, &activatedTime, 4);
// update
mobySetState(moby, state, -1);
pvars->Item = item;
pvars->ItemTexId = STACKABLE_ITEM_TEX_IDS[item];
pvars->ActivatedTime = activatedTime;
return 0;
}
//--------------------------------------------------------------------------
int sboxHandleEvent_GivePlayer(Moby* moby, GuberEvent* event)
{
int playerId, item, cost, i;
Player** players = playerGetAll();
struct StackBoxPVar* pvars = (struct StackBoxPVar*)moby->PVar;
if (!pvars)
return 0;
// read
guberEventRead(event, &playerId, 4);
guberEventRead(event, &item, 4);
guberEventRead(event, &cost, 4);
if (!MapConfig.State) return 0;
// add
MapConfig.State->PlayerStates[playerId].State.Bolts -= cost;
// item can be negative if box wants to only charge player bolts
if (item >= 0) {
MapConfig.State->PlayerStates[playerId].State.ItemStackable[item] += 1;
Player* player = playerGetAll()[playerId];
playPaidSound(player);
if (player && playerIsLocal(player)) {
char buf[64];
snprintf(buf, sizeof(buf), "Got %s", STACKABLE_ITEM_NAMES[item]);
pushSnack(player->LocalPlayerIndex, buf, 120);
}
}
return 0;
}
//--------------------------------------------------------------------------
int sboxHandleEvent_PlayerBuy(Moby* moby, GuberEvent* event)
{
int playerId, item, i;
Player** players = playerGetAll();
struct StackBoxPVar* pvars = (struct StackBoxPVar*)moby->PVar;
if (!pvars)
return 0;
// read
guberEventRead(event, &playerId, 4);
guberEventRead(event, &item, 4);
// only handle if host
if (gameAmIHost()) {
sboxPlayerBuy(moby, playerId, item);
}
return 0;
}
//--------------------------------------------------------------------------
int sboxHandleEvent_PlayerReroll(Moby* moby, GuberEvent* event)
{
int playerId, item, i;
Player** players = playerGetAll();
struct StackBoxPVar* pvars = (struct StackBoxPVar*)moby->PVar;
if (!pvars)
return 0;
// read
guberEventRead(event, &playerId, 4);
guberEventRead(event, &item, 4);
// only handle if host
if (gameAmIHost()) {
sboxPlayerReroll(moby, playerId, item);
}
return 0;
}
//--------------------------------------------------------------------------
struct GuberMoby* sboxGetGuber(Moby* moby)
{
if (moby->OClass == STACK_BOX_OCLASS && moby->PVar)
return moby->GuberMoby;
return 0;
}
//--------------------------------------------------------------------------
int sboxHandleEvent(Moby* moby, GuberEvent* event)
{
if (!moby || !event)
return 0;
if (isInGame() && !mobyIsDestroyed(moby) && moby->OClass == STACK_BOX_OCLASS && moby->PVar) {
u32 sboxEvent = event->NetEvent.EventID;
switch (sboxEvent)
{
case STACK_BOX_EVENT_SPAWN: return sboxHandleEvent_Spawned(moby, event);
case STACK_BOX_EVENT_ACTIVATE: return sboxHandleEvent_Activate(moby, event);
case STACK_BOX_EVENT_GIVE_PLAYER: return sboxHandleEvent_GivePlayer(moby, event);
case STACK_BOX_EVENT_PLAYER_BUY: return sboxHandleEvent_PlayerBuy(moby, event);
case STACK_BOX_EVENT_PLAYER_REROLL: return sboxHandleEvent_PlayerReroll(moby, event);
default:
{
DPRINTF("unhandle sbox event %d\n", sboxEvent);
break;
}
}
}
return 0;
}
//--------------------------------------------------------------------------
int sboxCreate(VECTOR position, VECTOR rotation)
{
// create guber object
GuberEvent * guberEvent = 0;
guberMobyCreateSpawned(STACK_BOX_OCLASS, sizeof(struct StackBoxPVar), &guberEvent, NULL);
if (guberEvent)
{
int item = sboxGetRandomItem(NULL);
guberEventWrite(guberEvent, position, 12);
guberEventWrite(guberEvent, rotation, 12);
guberEventWrite(guberEvent, &item, 4);
}
else
{
DPRINTF("failed to guberevent sbox\n");
}
return guberEvent != NULL;
}
//--------------------------------------------------------------------------
void sboxSpawn(void)
{
static int spawned = 0;
VECTOR p,r;
int i;
if (spawned)
return;
// spawn at all baked spawn points
if (gameAmIHost()) {
for (i = 0; i < BAKED_SPAWNPOINT_COUNT; ++i) {
if (MapConfig.BakedConfig->BakedSpawnPoints[i].Type == BAKED_SPAWNPOINT_STACK_BOX) {
memcpy(p, MapConfig.BakedConfig->BakedSpawnPoints[i].Position, 12);
memcpy(r, MapConfig.BakedConfig->BakedSpawnPoints[i].Rotation, 12);
sboxCreate(p, r);
}
}
}
spawned = 1;
}
//--------------------------------------------------------------------------
void sboxFrameTick(void)
{
char buffer[64];
int i;
if (!MapConfig.State) return;
// draw upgrade counts
for (i = 0; i < GAME_MAX_LOCALS; ++i) {
Player* p = playerGetFromSlot(i);
if (!p || !p->PlayerMoby) continue;
struct SurvivalPlayer* playerData = &MapConfig.State->PlayerStates[p->PlayerId];
if (gameIsStartMenuOpen(i) && !playerData->IsInWeaponsMenu) {
int j;
for (j = 0; j < STACKABLE_ITEM_COUNT; ++j) {
float x = 400;
float y = 54 + (j * 32);
transformToSplitscreenPixelCoordinates(i, &x, &y);
// draw count
int count = playerGetStackableCount(p->PlayerId, j);
snprintf(buffer, 32, "%d", count);
gfxScreenSpaceText(x+2, y+8+2, 1, 1, 0x40000000, buffer, -1, 0);
x = gfxScreenSpaceText(x, y+8, 1, 1, 0x80C0C0C0, buffer, -1, 0);
// draw icon
gfxSetupGifPaging(0);
u64 texId = gfxGetFrameTex(STACKABLE_ITEM_TEX_IDS[j]);
gfxDrawSprite(x+2, y+8, 16, 16, 0, 0, 32, 32, 0x80C0C0C0, texId);
x += 16 + 4;
gfxDoGifPaging();
// draw factor
switch (j)
{
case STACKABLE_ITEM_ALPHA_MOD_AMMO:
case STACKABLE_ITEM_ALPHA_MOD_SPEED:
case STACKABLE_ITEM_ALPHA_MOD_IMPACT:
case STACKABLE_ITEM_ALPHA_MOD_AREA:
snprintf(buffer, 32, "+%d", count * ITEM_STACKABLE_ALPHA_MOD_AMT); break;
case STACKABLE_ITEM_EXTRA_JUMP: snprintf(buffer, 32, "+%d", count); break;
case STACKABLE_ITEM_EXTRA_SHOT: snprintf(buffer, 32, "+%d", count); break;
case STACKABLE_ITEM_LOW_HEALTH_DMG_BUF: snprintf(buffer, 32, "+%.f%%", count * ITEM_STACKABLE_LOW_HEALTH_DMG_BUF_FAC * 100); break;
case STACKABLE_ITEM_HOVERBOOTS: snprintf(buffer, 32, "+%.0f%%", ITEM_STACKABLE_HOVERBOOTS_SPEED_BUF * count * 100); break;
case STACKABLE_ITEM_VAMPIRE: snprintf(buffer, 32, "+%d", ITEM_STACKABLE_VAMPIRE_HEALTH_AMT * count); break;
}
gfxScreenSpaceText(x+6, y+8+2, 1, 1, 0x40000000, buffer, -1, 0);
gfxScreenSpaceText(x+4, y+8, 1, 1, 0x8000C0C0, buffer, -1, 0);
}
}
}
}
//--------------------------------------------------------------------------
void sboxInit(void)
{
Moby* temp = mobySpawn(STACK_BOX_OCLASS, 0);
if (!temp)
return;
// set vtable callbacks
u32 mobyFunctionsPtr = (u32)mobyGetFunctions(temp);
if (mobyFunctionsPtr) {
*(u32*)(mobyFunctionsPtr + 0x04) = (u32)&sboxGetGuber;
*(u32*)(mobyFunctionsPtr + 0x14) = (u32)&sboxHandleEvent;
DPRINTF("SBOX oClass:%04X mClass:%02X func:%08X getGuber:%08X handleEvent:%08X\n", temp->OClass, temp->MClass, mobyFunctionsPtr, *(u32*)(mobyFunctionsPtr + 0x04), *(u32*)(mobyFunctionsPtr + 0x14));
}
mobyDestroy(temp);
}
| 412 | 0.931776 | 1 | 0.931776 | game-dev | MEDIA | 0.648903 | game-dev | 0.744472 | 1 | 0.744472 |
Los-Vic/GameAbilityNodeSystem | 5,175 | Assets/NodeSystem/Core/Runtime/GraphAssetRuntimeData.cs | using System.Collections.Generic;
using System.Reflection;
using System;
using GCL;
namespace NS
{
public class GraphAssetRuntimeData
{
public NodeGraphAsset Asset { get; private set; }
//Query
private readonly Dictionary<string, Node> _nodeIdMap = new();
private readonly Dictionary<string, NodePort> _portIdMap = new();
private readonly Dictionary<string, List<string>> _nodePortsMap = new();
//To execute action node, we need output value of dependent value && reroute nodes
private readonly Dictionary<string, List<string>> _nodeValDependencyMap = new();
private readonly Dictionary<(Type, int), string> _entryNodeMap = new();
private readonly Dictionary<Type, List<(int, string)>> _entryTypePairListMap = new();
//Transient
private readonly List<string> _toRunNodeList = new();
public void Init(NodeGraphAsset asset)
{
Asset = asset;
//Construct NodeIdMap & NodePortsMap
foreach (var node in Asset.nodes)
{
_nodeIdMap.Add(node.Id, node);
_nodePortsMap.Add(node.Id, new List<string>());
if (!node.IsEntryNode())
continue;
var hasPortalEnum = false;
var nodeType = node.GetType();
foreach (var fieldInfo in nodeType.GetFields())
{
if (fieldInfo.GetCustomAttribute<EntryAttribute>() == null)
continue;
hasPortalEnum = true;
var enumVal = (int)fieldInfo.GetValue(node);
if (!_entryNodeMap.TryAdd((nodeType, enumVal), node.Id))
{
GameLogger.LogError($"Fail to add portal node to ports map. Node type: {nodeType}, portal val: {enumVal}");
}
else
{
_entryTypePairListMap.TryAdd(nodeType, new List<(int, string)>());
_entryTypePairListMap[nodeType].Add((enumVal, node.Id));
}
}
if (hasPortalEnum)
continue;
if (!_entryNodeMap.TryAdd((nodeType, 0), node.Id))
{
GameLogger.LogError($"Fail to add portal node to ports map. Node type: {nodeType}");
}
else
{
_entryTypePairListMap.TryAdd(nodeType, new List<(int, string)>());
_entryTypePairListMap[nodeType].Add((0, node.Id));
}
}
//Construct PortIdMap & NodePortsMap
foreach (var port in Asset.ports)
{
_portIdMap.Add(port.Id, port);
if (_nodePortsMap.TryGetValue(port.belongNodeId, out var portList))
{
portList.Add(port.Id);
}
}
//Construct NodeValDependencyMap
foreach (var node in Asset.nodes)
{
if (!node.IsActionNode())
continue;
var valueNodeList = new List<string>();
_nodeValDependencyMap.Add(node.Id, valueNodeList);
_toRunNodeList.Clear();
_toRunNodeList.Add(node.Id);
while (_toRunNodeList.Count > 0)
{
foreach (var portId in _nodePortsMap[_toRunNodeList[0]])
{
var port = _portIdMap[portId];
if(port.IsFlowPort() || port.direction == EPortDirection.Output)
continue;
if(!NodePort.IsValidPortId(port.connectPortId))
continue;
var connectPort = _portIdMap[port.connectPortId];
var connectNode = _nodeIdMap[connectPort.belongNodeId];
if (!connectNode.IsValueNode())
continue;
valueNodeList.Add(connectNode.Id);
_toRunNodeList.Add(connectNode.Id);
}
_toRunNodeList.RemoveAt(0);
}
}
}
public Node GetNodeById(string id) => _nodeIdMap.GetValueOrDefault(id);
public NodePort GetPortById(string id) => _portIdMap.GetValueOrDefault(id);
public List<string> GetPortIdsOfNode(string nodeId) => _nodePortsMap.GetValueOrDefault(nodeId, new List<string>());
public List<string> GetDependentNodeIds(string nodeId) => _nodeValDependencyMap.GetValueOrDefault(nodeId, new List<string>());
public string GetEntryNodeId(Type nodeType, int portalVal = 0) => _entryNodeMap.GetValueOrDefault((nodeType, portalVal));
public List<(int, string)> GetEntryNodePairList(Type nodeType) => _entryTypePairListMap.GetValueOrDefault(nodeType);
}
} | 412 | 0.820109 | 1 | 0.820109 | game-dev | MEDIA | 0.744949 | game-dev | 0.961847 | 1 | 0.961847 |
GregTechCEu/GregTech | 16,558 | src/main/java/gregtech/api/unification/OreDictUnifier.java | package gregtech.api.unification;
import gregtech.api.GTValues;
import gregtech.api.GregTechAPI;
import gregtech.api.unification.material.Material;
import gregtech.api.unification.material.properties.PropertyKey;
import gregtech.api.unification.material.registry.MaterialRegistry;
import gregtech.api.unification.ore.OrePrefix;
import gregtech.api.unification.stack.*;
import gregtech.api.util.CustomModPriorityComparator;
import gregtech.api.util.GTUtility;
import gregtech.common.ConfigHolder;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.oredict.OreDictionary;
import net.minecraftforge.oredict.OreDictionary.OreRegisterEvent;
import com.google.common.base.Joiner;
import com.google.common.collect.Sets;
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import static gregtech.api.GTValues.M;
public class OreDictUnifier {
private OreDictUnifier() {}
private static final Map<ItemAndMetadata, UnificationEntry> stackUnificationInfo = new Object2ObjectOpenHashMap<>();
private static final Map<UnificationEntry, ArrayList<ItemAndMetadata>> stackUnificationItems = new Object2ObjectOpenHashMap<>();
private static final Map<Item, ItemVariantMap.Mutable<Set<String>>> stackOreDictName = new Object2ObjectOpenHashMap<>();
private static final Map<String, List<ItemStack>> oreDictNameStacks = new Object2ObjectOpenHashMap<>();
@Nullable
private static Comparator<ItemAndMetadata> stackComparator;
public static Comparator<ItemAndMetadata> getSimpleItemStackComparator() {
if (stackComparator == null) {
List<String> modPriorities = Arrays.asList(ConfigHolder.compat.modPriorities);
if (modPriorities.isEmpty()) {
// noinspection ConstantConditions
Function<ItemAndMetadata, String> modIdExtractor = stack -> stack.item.getRegistryName().getNamespace();
stackComparator = Comparator.comparing(modIdExtractor);
} else {
stackComparator = Collections.reverseOrder(new CustomModPriorityComparator(modPriorities));
}
}
return stackComparator;
}
public static Comparator<ItemStack> getItemStackComparator() {
Comparator<ItemAndMetadata> comparator = getSimpleItemStackComparator();
return (first, second) -> comparator.compare(new ItemAndMetadata(first), new ItemAndMetadata(second));
}
public static void registerOre(ItemStack itemStack, OrePrefix orePrefix, @Nullable Material material) {
registerOre(itemStack, orePrefix.name(), material);
}
public static void registerOre(ItemStack itemStack, String customOrePrefix, @Nullable Material material) {
if (itemStack.isEmpty()) return;
OreDictionary.registerOre(customOrePrefix + (material == null ? "" : material.toCamelCaseString()), itemStack);
}
public static void registerOre(ItemStack itemStack, String oreDict) {
if (itemStack.isEmpty()) return;
OreDictionary.registerOre(oreDict, itemStack);
}
public static void init() {
for (String registeredOreName : OreDictionary.getOreNames()) {
for (ItemStack itemStack : OreDictionary.getOres(registeredOreName)) {
onItemRegistration(new OreRegisterEvent(registeredOreName, itemStack));
}
}
MinecraftForge.EVENT_BUS.register(OreDictUnifier.class);
}
@SubscribeEvent
public static void onItemRegistration(OreRegisterEvent event) {
String oreName = event.getName();
// cache this registration by name
ItemVariantMap.Mutable<Set<String>> entry = stackOreDictName.computeIfAbsent(event.getOre().getItem(),
item -> item.getHasSubtypes() ? new MultiItemVariantMap<>() : new SingleItemVariantMap<>());
Set<String> set = entry.get(event.getOre());
if (set == null) {
set = new ObjectOpenHashSet<>();
entry.put(event.getOre(), set);
}
set.add(oreName);
List<ItemStack> itemStackListForOreDictName = oreDictNameStacks.computeIfAbsent(oreName,
k -> new ArrayList<>());
addAndSort(itemStackListForOreDictName, event.getOre().copy(), getItemStackComparator());
// and try to transform registration name into OrePrefix + Material pair
OrePrefix orePrefix = OrePrefix.getPrefix(oreName);
Material material = null;
if (orePrefix == null) {
// split ore dict name to parts
// oreBasalticMineralSand -> ore, Basaltic, Mineral, Sand
ArrayList<String> splits = new ArrayList<>();
StringBuilder builder = new StringBuilder();
for (char character : oreName.toCharArray()) {
if (Character.isUpperCase(character)) {
if (builder.length() > 0) {
splits.add(builder.toString());
builder = new StringBuilder().append(character);
} else splits.add(Character.toString(character));
} else builder.append(character);
}
if (builder.length() > 0) {
splits.add(builder.toString());
}
for (MaterialRegistry registry : GregTechAPI.materialManager.getRegistries()) {
// try to combine in different manners
// oreBasaltic MineralSand , ore BasalticMineralSand
StringBuilder buffer = new StringBuilder();
for (int i = 0; i < splits.size(); i++) {
buffer.append(splits.get(i));
OrePrefix maybePrefix = OrePrefix.getPrefix(buffer.toString()); // ore -> OrePrefix.ore
String possibleMaterialName = Joiner.on("").join(splits.subList(i + 1, splits.size())); // BasalticMineralSand
String underscoreName = GTUtility.toLowerCaseUnderscore(possibleMaterialName); // basaltic_mineral_sand
Material possibleMaterial = registry.getObject(underscoreName); // Materials.BasalticSand
if (possibleMaterial == null) {
// if we didn't find real material, try using marker material registry
possibleMaterial = GregTechAPI.markerMaterialRegistry.getMarkerMaterial(underscoreName);
}
if (maybePrefix != null && possibleMaterial != null) {
orePrefix = maybePrefix;
material = possibleMaterial;
break;
}
}
if (material != null) break;
}
}
// finally register item
if (orePrefix != null && (material != null || orePrefix.isSelfReferencing)) {
ItemAndMetadata key = new ItemAndMetadata(event.getOre());
UnificationEntry unificationEntry = new UnificationEntry(orePrefix, material);
ArrayList<ItemAndMetadata> itemListForUnifiedEntry = stackUnificationItems.computeIfAbsent(unificationEntry,
p -> new ArrayList<>());
addAndSort(itemListForUnifiedEntry, key, getSimpleItemStackComparator());
if (!unificationEntry.orePrefix.isMarkerPrefix()) {
stackUnificationInfo.put(key, unificationEntry);
}
orePrefix.processOreRegistration(material);
}
}
@NotNull
public static Set<String> getOreDictionaryNames(@NotNull ItemStack itemStack) {
if (itemStack.isEmpty()) return Collections.emptySet();
ItemVariantMap<Set<String>> nameEntry = stackOreDictName.get(itemStack.getItem());
if (nameEntry == null) return Collections.emptySet();
short itemDamage = (short) itemStack.getItemDamage();
Set<String> names = nameEntry.get(itemDamage);
Set<String> wildcardNames = itemDamage == GTValues.W ? null : nameEntry.get(GTValues.W);
if (names == null) {
return wildcardNames == null ? Collections.emptySet() : Collections.unmodifiableSet(wildcardNames);
} else if (wildcardNames == null || names == wildcardNames) { // single variant items have identical entries
return Collections.unmodifiableSet(names);
} else {
return Sets.union(names, wildcardNames);
}
}
@Nullable
public static ItemVariantMap<Set<String>> getOreDictionaryEntry(@NotNull Item item) {
ItemVariantMap.Mutable<Set<String>> entry = stackOreDictName.get(item);
return entry == null ? null : ItemVariantMap.unmodifiableSetView(entry);
}
@NotNull
public static ItemVariantMap<Set<String>> getOreDictionaryEntryOrEmpty(@NotNull Item item) {
ItemVariantMap.Mutable<Set<String>> entry = stackOreDictName.get(item);
return entry == null ? ItemVariantMap.empty() : ItemVariantMap.unmodifiableSetView(entry);
}
public static boolean hasOreDictionaryEntry(@NotNull Item item) {
return stackOreDictName.containsKey(item);
}
public static boolean hasOreDictionary(@NotNull ItemStack itemStack, @NotNull String oreDictName) {
if (itemStack.isEmpty()) return false;
ItemVariantMap<Set<String>> nameEntry = stackOreDictName.get(itemStack.getItem());
if (nameEntry == null) return false;
short itemDamage = (short) itemStack.getItemDamage();
Set<String> names = nameEntry.get(itemDamage);
if (names != null && names.contains(oreDictName)) return true;
if (itemDamage == GTValues.W) return false;
Set<String> wildcardNames = nameEntry.get(GTValues.W);
return wildcardNames != null && wildcardNames != names && wildcardNames.contains(oreDictName);
}
public static @NotNull List<@NotNull ItemStack> getAllWithOreDictionaryName(@NotNull String oreDictionaryName) {
var stacks = oreDictNameStacks.get(oreDictionaryName);
if (stacks == null) {
return Collections.emptyList();
}
return stacks.stream()
.map(ItemStack::copy)
.collect(Collectors.toList());
}
public static @Nullable MaterialStack getMaterial(ItemStack itemStack) {
if (itemStack.isEmpty()) {
return null;
}
ItemAndMetadata key = new ItemAndMetadata(itemStack);
UnificationEntry entry = GTUtility.getOrWildcardMeta(stackUnificationInfo, key);
if (entry != null) {
Material entryMaterial = entry.material;
if (entryMaterial == null) {
entryMaterial = entry.orePrefix.materialType;
}
if (entryMaterial != null) {
return new MaterialStack(entryMaterial, entry.orePrefix.getMaterialAmount(entryMaterial));
}
}
return null;
}
public static @Nullable OrePrefix getPrefix(ItemStack itemStack) {
if (itemStack.isEmpty()) {
return null;
}
UnificationEntry entry = GTUtility.getOrWildcardMeta(stackUnificationInfo, new ItemAndMetadata(itemStack));
return entry != null ? entry.orePrefix : null;
}
public static @Nullable UnificationEntry getUnificationEntry(ItemStack itemStack) {
if (itemStack.isEmpty()) {
return null;
}
return GTUtility.getOrWildcardMeta(stackUnificationInfo, new ItemAndMetadata(itemStack));
}
public static ItemStack getUnificated(ItemStack itemStack) {
if (itemStack.isEmpty()) return ItemStack.EMPTY;
UnificationEntry unificationEntry = getUnificationEntry(itemStack);
if (unificationEntry == null || !stackUnificationItems.containsKey(unificationEntry) ||
!unificationEntry.orePrefix.isUnificationEnabled)
return itemStack;
ArrayList<ItemAndMetadata> keys = stackUnificationItems.get(unificationEntry);
return keys.size() > 0 ? keys.get(0).toItemStack(itemStack.getCount()) : itemStack;
}
public static ItemStack get(UnificationEntry unificationEntry) {
return get(unificationEntry.orePrefix, unificationEntry.material);
}
public static ItemStack get(OrePrefix orePrefix, Material material) {
return get(orePrefix, material, 1);
}
public static ItemStack get(OrePrefix orePrefix, Material material, int stackSize) {
UnificationEntry unificationEntry = new UnificationEntry(orePrefix, material);
if (!stackUnificationItems.containsKey(unificationEntry))
return ItemStack.EMPTY;
ArrayList<ItemAndMetadata> keys = stackUnificationItems.get(unificationEntry);
return keys.size() > 0 ? keys.get(0).toItemStack(stackSize) : ItemStack.EMPTY;
}
public static ItemStack get(String oreDictName) {
List<ItemStack> itemStacks = oreDictNameStacks.get(oreDictName);
if (itemStacks == null || itemStacks.size() == 0) return ItemStack.EMPTY;
return itemStacks.get(0).copy();
}
public static List<ItemStack> getAll(UnificationEntry unificationEntry) {
if (!stackUnificationItems.containsKey(unificationEntry))
return Collections.emptyList();
ArrayList<ItemAndMetadata> keys = stackUnificationItems.get(unificationEntry);
return keys.stream().map(ItemAndMetadata::toItemStack).collect(Collectors.toList());
}
public static ItemStack getDust(Material material, long materialAmount) {
if (!material.hasProperty(PropertyKey.DUST) || materialAmount <= 0)
return ItemStack.EMPTY;
if (materialAmount % M == 0 || materialAmount >= M * 16)
return get(OrePrefix.dust, material, (int) (materialAmount / M));
else if ((materialAmount * 4) % M == 0 || materialAmount >= M * 8)
return get(OrePrefix.dustSmall, material, (int) ((materialAmount * 4) / M));
else if ((materialAmount * 9) >= M)
return get(OrePrefix.dustTiny, material, (int) ((materialAmount * 9) / M));
return ItemStack.EMPTY;
}
public static ItemStack getDust(MaterialStack materialStack) {
return getDust(materialStack.material, materialStack.amount);
}
public static ItemStack getIngot(Material material, long materialAmount) {
if (!material.hasProperty(PropertyKey.INGOT) || materialAmount <= 0)
return ItemStack.EMPTY;
if (materialAmount % (M * 9) == 0)
return get(OrePrefix.block, material, (int) (materialAmount / (M * 9)));
if (materialAmount % M == 0 || materialAmount >= M * 16)
return get(OrePrefix.ingot, material, (int) (materialAmount / M));
else if ((materialAmount * 9) >= M)
return get(OrePrefix.nugget, material, (int) ((materialAmount * 9) / M));
return ItemStack.EMPTY;
}
public static ItemStack getIngot(MaterialStack materialStack) {
return getIngot(materialStack.material, materialStack.amount);
}
/**
* Returns an Ingot of the material if it exists. Otherwise it returns a Dust.
* Returns ItemStack.EMPTY if neither exist.
*/
public static ItemStack getIngotOrDust(Material material, long materialAmount) {
ItemStack ingotStack = getIngot(material, materialAmount);
if (ingotStack != ItemStack.EMPTY) return ingotStack;
return getDust(material, materialAmount);
}
public static ItemStack getIngotOrDust(MaterialStack materialStack) {
return getIngotOrDust(materialStack.material, materialStack.amount);
}
public static ItemStack getGem(MaterialStack materialStack) {
if (materialStack.material.hasProperty(PropertyKey.GEM) && !OrePrefix.gem.isIgnored(materialStack.material) &&
materialStack.amount == OrePrefix.gem.getMaterialAmount(materialStack.material)) {
return get(OrePrefix.gem, materialStack.material, (int) (materialStack.amount / M));
}
return getDust(materialStack);
}
synchronized private static <T> void addAndSort(List<T> list, T itemToAdd, Comparator<T> comparator) {
list.add(itemToAdd);
if (list.size() > 1)
list.sort(comparator);
}
}
| 412 | 0.830891 | 1 | 0.830891 | game-dev | MEDIA | 0.96992 | game-dev | 0.928497 | 1 | 0.928497 |
danielah05/UndertaleDecomp | 1,404 | objects/obj_scrollaway_event/Step_0.gml | if (con == 0)
{
con = 1
snd_play(snd_spearappear)
alarm[4] = 20
}
if (con == 1)
{
tile_layer_shift(l2, 0, -1)
tile_layer_shift(l2x, 0, -1)
with (obj_mettboss_event)
{
obj_mainchara.y -= 1
mett.y -= 1
sixty.y -= 1
}
}
if (con == 2)
{
remay = obj_mainchara.y
remby = obj_mettaton_actor.y
snd_play(snd_impact)
con = 3
alarm[4] = 30
blastup = -6
bltotal = 0
bl = 0
ttotal = 0
ttotal2 = 0
cl = 0
}
if (con == 4)
{
if (cl == 0)
{
snd_play(snd_spearrise)
cl = 1
}
tspeed += 0.4
if (tspeed > 22)
tspeed = 22
if (bl == 0)
{
blastup += 0.2
bltotal += blastup
tile_layer_shift(l2, 0, blastup)
tile_layer_shift(l2x, 0, blastup)
sixty.y += blastup
obj_mainchara.y += blastup
obj_mettaton_actor.y += blastup
if (blastup > 0 && bltotal >= 20)
blastup = -2
}
if (ttotal < 300)
{
ttotal += tspeed
ttotal2 += tspeed
tile_layer_shift(l1, 0, tspeed)
tile_layer_shift(l3, 0, tspeed)
}
obj_mettboss_event.bly += tspeed
if (ttotal > 400)
{
ttotal -= 400
tile_layer_shift(l1, 0, -400)
}
instance_create(0, 0, obj_speedline)
}
if (con == 6)
{
with (obj_speedline)
instance_destroy()
con = 7
tile_layer_shift(l2, 0, ((-bltotal) + 20))
tile_layer_shift(l2x, 0, ((-bltotal) + 20))
if instance_exists(sixty)
sixty.y += ((-bltotal) + 20)
tile_layer_shift(l3, 0, (-ttotal2))
tile_layer_shift(l1, 0, (-ttotal))
}
if (con == 7)
instance_destroy()
| 412 | 0.706177 | 1 | 0.706177 | game-dev | MEDIA | 0.979005 | game-dev | 0.959224 | 1 | 0.959224 |
SebLague/Tiny-Chess-Bot-Challenge-Results | 6,399 | Bots/Bot_463.cs | namespace auto_Bot_463;
using ChessChallenge.API;
using System;
using System.Linq;
public struct ValueAndMove
{
public int value;
public Move move = Move.NullMove;
public ValueAndMove(int value, Move move)
{
this.value = value;
this.move = move;
}
}
public class Bot_463 : IChessBot
{
public int searchSteps = 0;
public int searchStepsThisThink = 0;
int depth = 4;
int millisecondsElapsedLastTurn = -1;
public static void Shuffle<T>(T[] array)
{
int n = array.Length;
while (n > 1)
{
n--;
int k = Random.Shared.Next(n + 1);
(array[n], array[k]) = (array[k], array[n]);
}
}
public static int Heuristic(Board board, int depth = 0)
{
if (board.IsDraw())
return 0;
if (board.IsInCheckmate())
return (board.IsWhiteToMove ? -1 : 1) * (depth + 1000000); // add depth to incentivize checkmating faster
var pieceLists = board.GetAllPieceLists();
int whitePiecesValue = pieceLists[0].Count * 1000 + (pieceLists[1].Count + pieceLists[2].Count) * 3000 + pieceLists[3].Count * 5000 + pieceLists[4].Count * 10000;
int blackPiecesValue = pieceLists[6].Count * 1000 + (pieceLists[7].Count + pieceLists[8].Count) * 3000 + pieceLists[9].Count * 5000 + pieceLists[10].Count * 10000;
int whitePieceAdvanceBonus = 0;
// encourage white to advance pieces (except king)
for (int i = 0; i <= 4; i++)
{
foreach (var piece in pieceLists[i])
{
whitePieceAdvanceBonus += piece.Square.Rank;
}
}
// encourage black to advance pieces (except king)
int blackPieceAdvanceBonus = 0;
for (int i = 6; i <= 10; i++)
{
foreach (var piece in pieceLists[i])
{
blackPieceAdvanceBonus += 7 - piece.Square.Rank;
}
}
int whiteLegalMoves = 0;
int blackLegalMoves = 0;
// encourage having more legal moves
if (board.IsWhiteToMove)
whiteLegalMoves += board.GetLegalMoves().Length;
else
blackLegalMoves += board.GetLegalMoves().Length;
if (board.TrySkipTurn())
{
if (board.IsWhiteToMove)
whiteLegalMoves += board.GetLegalMoves().Length;
else
blackLegalMoves += board.GetLegalMoves().Length;
board.UndoSkipTurn();
}
int whiteNotInCheckBonus = 0;
int blackNotInCheckBonus = 0;
// encourage not being in check
if (board.IsWhiteToMove)
whiteNotInCheckBonus = board.IsInCheck() ? 0 : 100;
else
blackNotInCheckBonus = board.IsInCheck() ? 0 : 100;
if (board.TrySkipTurn())
{
if (board.IsWhiteToMove)
whiteNotInCheckBonus = board.IsInCheck() ? 0 : 100;
else
blackNotInCheckBonus = board.IsInCheck() ? 0 : 100;
board.UndoSkipTurn();
}
// even exchanges are beneficial if you're in the lead
return (int)Math.Round(200000.0 * whitePiecesValue / (whitePiecesValue + blackPiecesValue) - 100000.0)
+ whitePieceAdvanceBonus - blackPieceAdvanceBonus
+ whiteLegalMoves - blackLegalMoves
+ whiteNotInCheckBonus - blackNotInCheckBonus;
}
/// <param name="color">1 or -1</param>
public ValueAndMove PrincipalVariationSearch(Board board, int depth, int α, int β, int color)
{
searchSteps++;
searchStepsThisThink++;
Move[] moves;
if (depth == 0 || (moves = board.GetLegalMoves()).Length == 0)
return new ValueAndMove(color * Heuristic(board, depth), Move.NullMove);
Shuffle(moves); // to stop draws by repetition
var moveEnumerator = moves.OrderByDescending(move =>
{
int ret = 0;
board.MakeMove(move);
ret = color * Heuristic(board, depth - 1);
board.UndoMove(move);
return ret;
}).ThenByDescending(move => move.IsCastles);
ValueAndMove αAndMove = new(α, Move.NullMove);
ValueAndMove score;
int i = 0;
foreach (Move move in moveEnumerator)
{
board.MakeMove(move);
if (i == 0)
{
score = new(-PrincipalVariationSearch(board, depth - 1, -β, -αAndMove.value, -color).value, move);
}
else
{
score = new(-PrincipalVariationSearch(board, depth - 1, -αAndMove.value - 1, -αAndMove.value, -color).value, move);
if (αAndMove.value < score.value && score.value < β)
score = new(-PrincipalVariationSearch(board, depth - 1, -β, -score.value, -color).value, move);
}
board.UndoMove(move);
if (score.value > αAndMove.value)
αAndMove = score;
if (αAndMove.value >= β)
break;
i++;
}
return αAndMove;
}
public Move Think(Board board, Timer timer)
{
searchStepsThisThink = 0;
// https://chess.stackexchange.com/questions/2506/what-is-the-average-length-of-a-game-of-chess
int k = board.GameMoveHistory.Length;
int estimatedPlyRemaining = (int)(59.3 + (72830 - 2330 * k) / (2644 + k * (10 + k)));
int allottedTime = timer.MillisecondsRemaining / estimatedPlyRemaining;
ValueAndMove valueAndMove;
if (millisecondsElapsedLastTurn != -1)
{
if (millisecondsElapsedLastTurn > allottedTime)
{
depth--;
}
else if (millisecondsElapsedLastTurn < allottedTime / 2)
{
depth++;
}
}
valueAndMove = PrincipalVariationSearch(board, depth, -10000000, 10000000, board.IsWhiteToMove ? 1 : -1);
DivertedConsole.Write($"[MyBot] value: {valueAndMove.value,10:N0}; depth: {depth,2:N0}; estimated ply remaining: {estimatedPlyRemaining,2:N0}; allotted time: {allottedTime,6:N0}ms; actual time used: {timer.MillisecondsElapsedThisTurn,6:N0}ms; {valueAndMove.move}");
millisecondsElapsedLastTurn = timer.MillisecondsElapsedThisTurn;
return valueAndMove.move;
}
} | 412 | 0.839108 | 1 | 0.839108 | game-dev | MEDIA | 0.795174 | game-dev | 0.935794 | 1 | 0.935794 |
dantman/elite-vr-cockpit | 34,180 | Assets/SteamVR/InteractionSystem/Teleport/Scripts/Teleport.cs | //======= Copyright (c) Valve Corporation, All rights reserved. ===============
//
// Purpose: Handles all the teleport logic
//
//=============================================================================
using UnityEngine;
using UnityEngine.Events;
using System.Collections;
namespace Valve.VR.InteractionSystem
{
//-------------------------------------------------------------------------
public class Teleport : MonoBehaviour
{
public SteamVR_Action_Boolean teleportAction = SteamVR_Input.GetAction<SteamVR_Action_Boolean>("Teleport");
public LayerMask traceLayerMask;
public LayerMask floorFixupTraceLayerMask;
public float floorFixupMaximumTraceDistance = 1.0f;
public Material areaVisibleMaterial;
public Material areaLockedMaterial;
public Material areaHighlightedMaterial;
public Material pointVisibleMaterial;
public Material pointLockedMaterial;
public Material pointHighlightedMaterial;
public Transform destinationReticleTransform;
public Transform invalidReticleTransform;
public GameObject playAreaPreviewCorner;
public GameObject playAreaPreviewSide;
public Color pointerValidColor;
public Color pointerInvalidColor;
public Color pointerLockedColor;
public bool showPlayAreaMarker = true;
public float teleportFadeTime = 0.1f;
public float meshFadeTime = 0.2f;
public float arcDistance = 10.0f;
[Header( "Effects" )]
public Transform onActivateObjectTransform;
public Transform onDeactivateObjectTransform;
public float activateObjectTime = 1.0f;
public float deactivateObjectTime = 1.0f;
[Header( "Audio Sources" )]
public AudioSource pointerAudioSource;
public AudioSource loopingAudioSource;
public AudioSource headAudioSource;
public AudioSource reticleAudioSource;
[Header( "Sounds" )]
public AudioClip teleportSound;
public AudioClip pointerStartSound;
public AudioClip pointerLoopSound;
public AudioClip pointerStopSound;
public AudioClip goodHighlightSound;
public AudioClip badHighlightSound;
[Header( "Debug" )]
public bool debugFloor = false;
public bool showOffsetReticle = false;
public Transform offsetReticleTransform;
public MeshRenderer floorDebugSphere;
public LineRenderer floorDebugLine;
private LineRenderer pointerLineRenderer;
private GameObject teleportPointerObject;
private Transform pointerStartTransform;
private Hand pointerHand = null;
private Player player = null;
private TeleportArc teleportArc = null;
private bool visible = false;
private TeleportMarkerBase[] teleportMarkers;
private TeleportMarkerBase pointedAtTeleportMarker;
private TeleportMarkerBase teleportingToMarker;
private Vector3 pointedAtPosition;
private Vector3 prevPointedAtPosition;
private bool teleporting = false;
private float currentFadeTime = 0.0f;
private float meshAlphaPercent = 1.0f;
private float pointerShowStartTime = 0.0f;
private float pointerHideStartTime = 0.0f;
private bool meshFading = false;
private float fullTintAlpha;
private float invalidReticleMinScale = 0.2f;
private float invalidReticleMaxScale = 1.0f;
private float invalidReticleMinScaleDistance = 0.4f;
private float invalidReticleMaxScaleDistance = 2.0f;
private Vector3 invalidReticleScale = Vector3.one;
private Quaternion invalidReticleTargetRotation = Quaternion.identity;
private Transform playAreaPreviewTransform;
private Transform[] playAreaPreviewCorners;
private Transform[] playAreaPreviewSides;
private float loopingAudioMaxVolume = 0.0f;
private Coroutine hintCoroutine = null;
private bool originalHoverLockState = false;
private Interactable originalHoveringInteractable = null;
private AllowTeleportWhileAttachedToHand allowTeleportWhileAttached = null;
private Vector3 startingFeetOffset = Vector3.zero;
private bool movedFeetFarEnough = false;
SteamVR_Events.Action chaperoneInfoInitializedAction;
// Events
public static SteamVR_Events.Event< float > ChangeScene = new SteamVR_Events.Event< float >();
public static SteamVR_Events.Action< float > ChangeSceneAction( UnityAction< float > action ) { return new SteamVR_Events.Action< float >( ChangeScene, action ); }
public static SteamVR_Events.Event< TeleportMarkerBase > Player = new SteamVR_Events.Event< TeleportMarkerBase >();
public static SteamVR_Events.Action< TeleportMarkerBase > PlayerAction( UnityAction< TeleportMarkerBase > action ) { return new SteamVR_Events.Action< TeleportMarkerBase >( Player, action ); }
public static SteamVR_Events.Event< TeleportMarkerBase > PlayerPre = new SteamVR_Events.Event< TeleportMarkerBase >();
public static SteamVR_Events.Action< TeleportMarkerBase > PlayerPreAction( UnityAction< TeleportMarkerBase > action ) { return new SteamVR_Events.Action< TeleportMarkerBase >( PlayerPre, action ); }
//-------------------------------------------------
private static Teleport _instance;
public static Teleport instance
{
get
{
if ( _instance == null )
{
_instance = GameObject.FindObjectOfType<Teleport>();
}
return _instance;
}
}
//-------------------------------------------------
void Awake()
{
_instance = this;
chaperoneInfoInitializedAction = ChaperoneInfo.InitializedAction( OnChaperoneInfoInitialized );
pointerLineRenderer = GetComponentInChildren<LineRenderer>();
teleportPointerObject = pointerLineRenderer.gameObject;
int tintColorID = Shader.PropertyToID( "_TintColor" );
fullTintAlpha = pointVisibleMaterial.GetColor( tintColorID ).a;
teleportArc = GetComponent<TeleportArc>();
teleportArc.traceLayerMask = traceLayerMask;
loopingAudioMaxVolume = loopingAudioSource.volume;
playAreaPreviewCorner.SetActive( false );
playAreaPreviewSide.SetActive( false );
float invalidReticleStartingScale = invalidReticleTransform.localScale.x;
invalidReticleMinScale *= invalidReticleStartingScale;
invalidReticleMaxScale *= invalidReticleStartingScale;
}
//-------------------------------------------------
void Start()
{
teleportMarkers = GameObject.FindObjectsOfType<TeleportMarkerBase>();
HidePointer();
player = InteractionSystem.Player.instance;
if ( player == null )
{
Debug.LogError("<b>[SteamVR Interaction]</b> Teleport: No Player instance found in map.", this);
Destroy( this.gameObject );
return;
}
CheckForSpawnPoint();
Invoke( "ShowTeleportHint", 5.0f );
}
//-------------------------------------------------
void OnEnable()
{
chaperoneInfoInitializedAction.enabled = true;
OnChaperoneInfoInitialized(); // In case it's already initialized
}
//-------------------------------------------------
void OnDisable()
{
chaperoneInfoInitializedAction.enabled = false;
HidePointer();
}
//-------------------------------------------------
private void CheckForSpawnPoint()
{
foreach ( TeleportMarkerBase teleportMarker in teleportMarkers )
{
TeleportPoint teleportPoint = teleportMarker as TeleportPoint;
if ( teleportPoint && teleportPoint.playerSpawnPoint )
{
teleportingToMarker = teleportMarker;
TeleportPlayer();
break;
}
}
}
//-------------------------------------------------
public void HideTeleportPointer()
{
if ( pointerHand != null )
{
HidePointer();
}
}
//-------------------------------------------------
void Update()
{
Hand oldPointerHand = pointerHand;
Hand newPointerHand = null;
foreach ( Hand hand in player.hands )
{
if ( visible )
{
if ( WasTeleportButtonReleased( hand ) )
{
if ( pointerHand == hand ) //This is the pointer hand
{
TryTeleportPlayer();
}
}
}
if ( WasTeleportButtonPressed( hand ) )
{
newPointerHand = hand;
}
}
//If something is attached to the hand that is preventing teleport
if ( allowTeleportWhileAttached && !allowTeleportWhileAttached.teleportAllowed )
{
HidePointer();
}
else
{
if ( !visible && newPointerHand != null )
{
//Begin showing the pointer
ShowPointer( newPointerHand, oldPointerHand );
}
else if ( visible )
{
if ( newPointerHand == null && !IsTeleportButtonDown( pointerHand ) )
{
//Hide the pointer
HidePointer();
}
else if ( newPointerHand != null )
{
//Move the pointer to a new hand
ShowPointer( newPointerHand, oldPointerHand );
}
}
}
if ( visible )
{
UpdatePointer();
if ( meshFading )
{
UpdateTeleportColors();
}
if ( onActivateObjectTransform.gameObject.activeSelf && Time.time - pointerShowStartTime > activateObjectTime )
{
onActivateObjectTransform.gameObject.SetActive( false );
}
}
else
{
if ( onDeactivateObjectTransform.gameObject.activeSelf && Time.time - pointerHideStartTime > deactivateObjectTime )
{
onDeactivateObjectTransform.gameObject.SetActive( false );
}
}
}
//-------------------------------------------------
private void UpdatePointer()
{
Vector3 pointerStart = pointerStartTransform.position;
Vector3 pointerEnd;
Vector3 pointerDir = pointerStartTransform.forward;
bool hitSomething = false;
bool showPlayAreaPreview = false;
Vector3 playerFeetOffset = player.trackingOriginTransform.position - player.feetPositionGuess;
Vector3 arcVelocity = pointerDir * arcDistance;
TeleportMarkerBase hitTeleportMarker = null;
//Check pointer angle
float dotUp = Vector3.Dot( pointerDir, Vector3.up );
float dotForward = Vector3.Dot( pointerDir, player.hmdTransform.forward );
bool pointerAtBadAngle = false;
if ( ( dotForward > 0 && dotUp > 0.75f ) || ( dotForward < 0.0f && dotUp > 0.5f ) )
{
pointerAtBadAngle = true;
}
//Trace to see if the pointer hit anything
RaycastHit hitInfo;
teleportArc.SetArcData( pointerStart, arcVelocity, true, pointerAtBadAngle );
if ( teleportArc.DrawArc( out hitInfo ) )
{
hitSomething = true;
hitTeleportMarker = hitInfo.collider.GetComponentInParent<TeleportMarkerBase>();
}
if ( pointerAtBadAngle )
{
hitTeleportMarker = null;
}
HighlightSelected( hitTeleportMarker );
if ( hitTeleportMarker != null ) //Hit a teleport marker
{
if ( hitTeleportMarker.locked )
{
teleportArc.SetColor( pointerLockedColor );
#if (UNITY_5_4)
pointerLineRenderer.SetColors( pointerLockedColor, pointerLockedColor );
#else
pointerLineRenderer.startColor = pointerLockedColor;
pointerLineRenderer.endColor = pointerLockedColor;
#endif
destinationReticleTransform.gameObject.SetActive( false );
}
else
{
teleportArc.SetColor( pointerValidColor );
#if (UNITY_5_4)
pointerLineRenderer.SetColors( pointerValidColor, pointerValidColor );
#else
pointerLineRenderer.startColor = pointerValidColor;
pointerLineRenderer.endColor = pointerValidColor;
#endif
destinationReticleTransform.gameObject.SetActive( hitTeleportMarker.showReticle );
}
offsetReticleTransform.gameObject.SetActive( true );
invalidReticleTransform.gameObject.SetActive( false );
pointedAtTeleportMarker = hitTeleportMarker;
pointedAtPosition = hitInfo.point;
if ( showPlayAreaMarker )
{
//Show the play area marker if this is a teleport area
TeleportArea teleportArea = pointedAtTeleportMarker as TeleportArea;
if ( teleportArea != null && !teleportArea.locked && playAreaPreviewTransform != null )
{
Vector3 offsetToUse = playerFeetOffset;
//Adjust the actual offset to prevent the play area marker from moving too much
if ( !movedFeetFarEnough )
{
float distanceFromStartingOffset = Vector3.Distance( playerFeetOffset, startingFeetOffset );
if ( distanceFromStartingOffset < 0.1f )
{
offsetToUse = startingFeetOffset;
}
else if ( distanceFromStartingOffset < 0.4f )
{
offsetToUse = Vector3.Lerp( startingFeetOffset, playerFeetOffset, ( distanceFromStartingOffset - 0.1f ) / 0.3f );
}
else
{
movedFeetFarEnough = true;
}
}
playAreaPreviewTransform.position = pointedAtPosition + offsetToUse;
showPlayAreaPreview = true;
}
}
pointerEnd = hitInfo.point;
}
else //Hit neither
{
destinationReticleTransform.gameObject.SetActive( false );
offsetReticleTransform.gameObject.SetActive( false );
teleportArc.SetColor( pointerInvalidColor );
#if (UNITY_5_4)
pointerLineRenderer.SetColors( pointerInvalidColor, pointerInvalidColor );
#else
pointerLineRenderer.startColor = pointerInvalidColor;
pointerLineRenderer.endColor = pointerInvalidColor;
#endif
invalidReticleTransform.gameObject.SetActive( !pointerAtBadAngle );
//Orient the invalid reticle to the normal of the trace hit point
Vector3 normalToUse = hitInfo.normal;
float angle = Vector3.Angle( hitInfo.normal, Vector3.up );
if ( angle < 15.0f )
{
normalToUse = Vector3.up;
}
invalidReticleTargetRotation = Quaternion.FromToRotation( Vector3.up, normalToUse );
invalidReticleTransform.rotation = Quaternion.Slerp( invalidReticleTransform.rotation, invalidReticleTargetRotation, 0.1f );
//Scale the invalid reticle based on the distance from the player
float distanceFromPlayer = Vector3.Distance( hitInfo.point, player.hmdTransform.position );
float invalidReticleCurrentScale = Util.RemapNumberClamped( distanceFromPlayer, invalidReticleMinScaleDistance, invalidReticleMaxScaleDistance, invalidReticleMinScale, invalidReticleMaxScale );
invalidReticleScale.x = invalidReticleCurrentScale;
invalidReticleScale.y = invalidReticleCurrentScale;
invalidReticleScale.z = invalidReticleCurrentScale;
invalidReticleTransform.transform.localScale = invalidReticleScale;
pointedAtTeleportMarker = null;
if ( hitSomething )
{
pointerEnd = hitInfo.point;
}
else
{
pointerEnd = teleportArc.GetArcPositionAtTime( teleportArc.arcDuration );
}
//Debug floor
if ( debugFloor )
{
floorDebugSphere.gameObject.SetActive( false );
floorDebugLine.gameObject.SetActive( false );
}
}
if ( playAreaPreviewTransform != null )
{
playAreaPreviewTransform.gameObject.SetActive( showPlayAreaPreview );
}
if ( !showOffsetReticle )
{
offsetReticleTransform.gameObject.SetActive( false );
}
destinationReticleTransform.position = pointedAtPosition;
invalidReticleTransform.position = pointerEnd;
onActivateObjectTransform.position = pointerEnd;
onDeactivateObjectTransform.position = pointerEnd;
offsetReticleTransform.position = pointerEnd - playerFeetOffset;
reticleAudioSource.transform.position = pointedAtPosition;
pointerLineRenderer.SetPosition( 0, pointerStart );
pointerLineRenderer.SetPosition( 1, pointerEnd );
}
//-------------------------------------------------
void FixedUpdate()
{
if ( !visible )
{
return;
}
if ( debugFloor )
{
//Debug floor
TeleportArea teleportArea = pointedAtTeleportMarker as TeleportArea;
if ( teleportArea != null )
{
if ( floorFixupMaximumTraceDistance > 0.0f )
{
floorDebugSphere.gameObject.SetActive( true );
floorDebugLine.gameObject.SetActive( true );
RaycastHit raycastHit;
Vector3 traceDir = Vector3.down;
traceDir.x = 0.01f;
if ( Physics.Raycast( pointedAtPosition + 0.05f * traceDir, traceDir, out raycastHit, floorFixupMaximumTraceDistance, floorFixupTraceLayerMask ) )
{
floorDebugSphere.transform.position = raycastHit.point;
floorDebugSphere.material.color = Color.green;
#if (UNITY_5_4)
floorDebugLine.SetColors( Color.green, Color.green );
#else
floorDebugLine.startColor = Color.green;
floorDebugLine.endColor = Color.green;
#endif
floorDebugLine.SetPosition( 0, pointedAtPosition );
floorDebugLine.SetPosition( 1, raycastHit.point );
}
else
{
Vector3 rayEnd = pointedAtPosition + ( traceDir * floorFixupMaximumTraceDistance );
floorDebugSphere.transform.position = rayEnd;
floorDebugSphere.material.color = Color.red;
#if (UNITY_5_4)
floorDebugLine.SetColors( Color.red, Color.red );
#else
floorDebugLine.startColor = Color.red;
floorDebugLine.endColor = Color.red;
#endif
floorDebugLine.SetPosition( 0, pointedAtPosition );
floorDebugLine.SetPosition( 1, rayEnd );
}
}
}
}
}
//-------------------------------------------------
private void OnChaperoneInfoInitialized()
{
ChaperoneInfo chaperone = ChaperoneInfo.instance;
if ( chaperone.initialized && chaperone.roomscale )
{
//Set up the render model for the play area bounds
if ( playAreaPreviewTransform == null )
{
playAreaPreviewTransform = new GameObject( "PlayAreaPreviewTransform" ).transform;
playAreaPreviewTransform.parent = transform;
Util.ResetTransform( playAreaPreviewTransform );
playAreaPreviewCorner.SetActive( true );
playAreaPreviewCorners = new Transform[4];
playAreaPreviewCorners[0] = playAreaPreviewCorner.transform;
playAreaPreviewCorners[1] = Instantiate( playAreaPreviewCorners[0] );
playAreaPreviewCorners[2] = Instantiate( playAreaPreviewCorners[0] );
playAreaPreviewCorners[3] = Instantiate( playAreaPreviewCorners[0] );
playAreaPreviewCorners[0].transform.parent = playAreaPreviewTransform;
playAreaPreviewCorners[1].transform.parent = playAreaPreviewTransform;
playAreaPreviewCorners[2].transform.parent = playAreaPreviewTransform;
playAreaPreviewCorners[3].transform.parent = playAreaPreviewTransform;
playAreaPreviewSide.SetActive( true );
playAreaPreviewSides = new Transform[4];
playAreaPreviewSides[0] = playAreaPreviewSide.transform;
playAreaPreviewSides[1] = Instantiate( playAreaPreviewSides[0] );
playAreaPreviewSides[2] = Instantiate( playAreaPreviewSides[0] );
playAreaPreviewSides[3] = Instantiate( playAreaPreviewSides[0] );
playAreaPreviewSides[0].transform.parent = playAreaPreviewTransform;
playAreaPreviewSides[1].transform.parent = playAreaPreviewTransform;
playAreaPreviewSides[2].transform.parent = playAreaPreviewTransform;
playAreaPreviewSides[3].transform.parent = playAreaPreviewTransform;
}
float x = chaperone.playAreaSizeX;
float z = chaperone.playAreaSizeZ;
playAreaPreviewSides[0].localPosition = new Vector3( 0.0f, 0.0f, 0.5f * z - 0.25f );
playAreaPreviewSides[1].localPosition = new Vector3( 0.0f, 0.0f, -0.5f * z + 0.25f );
playAreaPreviewSides[2].localPosition = new Vector3( 0.5f * x - 0.25f, 0.0f, 0.0f );
playAreaPreviewSides[3].localPosition = new Vector3( -0.5f * x + 0.25f, 0.0f, 0.0f );
playAreaPreviewSides[0].localScale = new Vector3( x - 0.5f, 1.0f, 1.0f );
playAreaPreviewSides[1].localScale = new Vector3( x - 0.5f, 1.0f, 1.0f );
playAreaPreviewSides[2].localScale = new Vector3( z - 0.5f, 1.0f, 1.0f );
playAreaPreviewSides[3].localScale = new Vector3( z - 0.5f, 1.0f, 1.0f );
playAreaPreviewSides[0].localRotation = Quaternion.Euler( 0.0f, 0.0f, 0.0f );
playAreaPreviewSides[1].localRotation = Quaternion.Euler( 0.0f, 180.0f, 0.0f );
playAreaPreviewSides[2].localRotation = Quaternion.Euler( 0.0f, 90.0f, 0.0f );
playAreaPreviewSides[3].localRotation = Quaternion.Euler( 0.0f, 270.0f, 0.0f );
playAreaPreviewCorners[0].localPosition = new Vector3( 0.5f * x - 0.25f, 0.0f, 0.5f * z - 0.25f );
playAreaPreviewCorners[1].localPosition = new Vector3( 0.5f * x - 0.25f, 0.0f, -0.5f * z + 0.25f );
playAreaPreviewCorners[2].localPosition = new Vector3( -0.5f * x + 0.25f, 0.0f, -0.5f * z + 0.25f );
playAreaPreviewCorners[3].localPosition = new Vector3( -0.5f * x + 0.25f, 0.0f, 0.5f * z - 0.25f );
playAreaPreviewCorners[0].localRotation = Quaternion.Euler( 0.0f, 0.0f, 0.0f );
playAreaPreviewCorners[1].localRotation = Quaternion.Euler( 0.0f, 90.0f, 0.0f );
playAreaPreviewCorners[2].localRotation = Quaternion.Euler( 0.0f, 180.0f, 0.0f );
playAreaPreviewCorners[3].localRotation = Quaternion.Euler( 0.0f, 270.0f, 0.0f );
playAreaPreviewTransform.gameObject.SetActive( false );
}
}
//-------------------------------------------------
private void HidePointer()
{
if ( visible )
{
pointerHideStartTime = Time.time;
}
visible = false;
if ( pointerHand )
{
if ( ShouldOverrideHoverLock() )
{
//Restore the original hovering interactable on the hand
if ( originalHoverLockState == true )
{
pointerHand.HoverLock( originalHoveringInteractable );
}
else
{
pointerHand.HoverUnlock( null );
}
}
//Stop looping sound
loopingAudioSource.Stop();
PlayAudioClip( pointerAudioSource, pointerStopSound );
}
teleportPointerObject.SetActive( false );
teleportArc.Hide();
foreach ( TeleportMarkerBase teleportMarker in teleportMarkers )
{
if ( teleportMarker != null && teleportMarker.markerActive && teleportMarker.gameObject != null )
{
teleportMarker.gameObject.SetActive( false );
}
}
destinationReticleTransform.gameObject.SetActive( false );
invalidReticleTransform.gameObject.SetActive( false );
offsetReticleTransform.gameObject.SetActive( false );
if ( playAreaPreviewTransform != null )
{
playAreaPreviewTransform.gameObject.SetActive( false );
}
if ( onActivateObjectTransform.gameObject.activeSelf )
{
onActivateObjectTransform.gameObject.SetActive( false );
}
onDeactivateObjectTransform.gameObject.SetActive( true );
pointerHand = null;
}
//-------------------------------------------------
private void ShowPointer( Hand newPointerHand, Hand oldPointerHand )
{
if ( !visible )
{
pointedAtTeleportMarker = null;
pointerShowStartTime = Time.time;
visible = true;
meshFading = true;
teleportPointerObject.SetActive( false );
teleportArc.Show();
foreach ( TeleportMarkerBase teleportMarker in teleportMarkers )
{
if ( teleportMarker.markerActive && teleportMarker.ShouldActivate( player.feetPositionGuess ) )
{
teleportMarker.gameObject.SetActive( true );
teleportMarker.Highlight( false );
}
}
startingFeetOffset = player.trackingOriginTransform.position - player.feetPositionGuess;
movedFeetFarEnough = false;
if ( onDeactivateObjectTransform.gameObject.activeSelf )
{
onDeactivateObjectTransform.gameObject.SetActive( false );
}
onActivateObjectTransform.gameObject.SetActive( true );
loopingAudioSource.clip = pointerLoopSound;
loopingAudioSource.loop = true;
loopingAudioSource.Play();
loopingAudioSource.volume = 0.0f;
}
if ( oldPointerHand )
{
if ( ShouldOverrideHoverLock() )
{
//Restore the original hovering interactable on the hand
if ( originalHoverLockState == true )
{
oldPointerHand.HoverLock( originalHoveringInteractable );
}
else
{
oldPointerHand.HoverUnlock( null );
}
}
}
pointerHand = newPointerHand;
if ( visible && oldPointerHand != pointerHand )
{
PlayAudioClip( pointerAudioSource, pointerStartSound );
}
if ( pointerHand )
{
pointerStartTransform = GetPointerStartTransform( pointerHand );
if ( pointerHand.currentAttachedObject != null )
{
allowTeleportWhileAttached = pointerHand.currentAttachedObject.GetComponent<AllowTeleportWhileAttachedToHand>();
}
//Keep track of any existing hovering interactable on the hand
originalHoverLockState = pointerHand.hoverLocked;
originalHoveringInteractable = pointerHand.hoveringInteractable;
if ( ShouldOverrideHoverLock() )
{
pointerHand.HoverLock( null );
}
pointerAudioSource.transform.SetParent( pointerStartTransform );
pointerAudioSource.transform.localPosition = Vector3.zero;
loopingAudioSource.transform.SetParent( pointerStartTransform );
loopingAudioSource.transform.localPosition = Vector3.zero;
}
}
//-------------------------------------------------
private void UpdateTeleportColors()
{
float deltaTime = Time.time - pointerShowStartTime;
if ( deltaTime > meshFadeTime )
{
meshAlphaPercent = 1.0f;
meshFading = false;
}
else
{
meshAlphaPercent = Mathf.Lerp( 0.0f, 1.0f, deltaTime / meshFadeTime );
}
//Tint color for the teleport points
foreach ( TeleportMarkerBase teleportMarker in teleportMarkers )
{
teleportMarker.SetAlpha( fullTintAlpha * meshAlphaPercent, meshAlphaPercent );
}
}
//-------------------------------------------------
private void PlayAudioClip( AudioSource source, AudioClip clip )
{
source.clip = clip;
source.Play();
}
//-------------------------------------------------
private void PlayPointerHaptic( bool validLocation )
{
if ( pointerHand != null )
{
if ( validLocation )
{
pointerHand.TriggerHapticPulse( 800 );
}
else
{
pointerHand.TriggerHapticPulse( 100 );
}
}
}
//-------------------------------------------------
private void TryTeleportPlayer()
{
if ( visible && !teleporting )
{
if ( pointedAtTeleportMarker != null && pointedAtTeleportMarker.locked == false )
{
//Pointing at an unlocked teleport marker
teleportingToMarker = pointedAtTeleportMarker;
InitiateTeleportFade();
CancelTeleportHint();
}
}
}
//-------------------------------------------------
private void InitiateTeleportFade()
{
teleporting = true;
currentFadeTime = teleportFadeTime;
TeleportPoint teleportPoint = teleportingToMarker as TeleportPoint;
if ( teleportPoint != null && teleportPoint.teleportType == TeleportPoint.TeleportPointType.SwitchToNewScene )
{
currentFadeTime *= 3.0f;
Teleport.ChangeScene.Send( currentFadeTime );
}
SteamVR_Fade.Start( Color.clear, 0 );
SteamVR_Fade.Start( Color.black, currentFadeTime );
headAudioSource.transform.SetParent( player.hmdTransform );
headAudioSource.transform.localPosition = Vector3.zero;
PlayAudioClip( headAudioSource, teleportSound );
Invoke( "TeleportPlayer", currentFadeTime );
}
//-------------------------------------------------
private void TeleportPlayer()
{
teleporting = false;
Teleport.PlayerPre.Send( pointedAtTeleportMarker );
SteamVR_Fade.Start( Color.clear, currentFadeTime );
TeleportPoint teleportPoint = teleportingToMarker as TeleportPoint;
Vector3 teleportPosition = pointedAtPosition;
if ( teleportPoint != null )
{
teleportPosition = teleportPoint.transform.position;
//Teleport to a new scene
if ( teleportPoint.teleportType == TeleportPoint.TeleportPointType.SwitchToNewScene )
{
teleportPoint.TeleportToScene();
return;
}
}
// Find the actual floor position below the navigation mesh
TeleportArea teleportArea = teleportingToMarker as TeleportArea;
if ( teleportArea != null )
{
if ( floorFixupMaximumTraceDistance > 0.0f )
{
RaycastHit raycastHit;
if ( Physics.Raycast( teleportPosition + 0.05f * Vector3.down, Vector3.down, out raycastHit, floorFixupMaximumTraceDistance, floorFixupTraceLayerMask ) )
{
teleportPosition = raycastHit.point;
}
}
}
if ( teleportingToMarker.ShouldMovePlayer() )
{
Vector3 playerFeetOffset = player.trackingOriginTransform.position - player.feetPositionGuess;
player.trackingOriginTransform.position = teleportPosition + playerFeetOffset;
if (player.leftHand.currentAttachedObjectInfo.HasValue)
player.leftHand.ResetAttachedTransform(player.leftHand.currentAttachedObjectInfo.Value);
if (player.rightHand.currentAttachedObjectInfo.HasValue)
player.rightHand.ResetAttachedTransform(player.rightHand.currentAttachedObjectInfo.Value);
}
else
{
teleportingToMarker.TeleportPlayer( pointedAtPosition );
}
Teleport.Player.Send( pointedAtTeleportMarker );
}
//-------------------------------------------------
private void HighlightSelected( TeleportMarkerBase hitTeleportMarker )
{
if ( pointedAtTeleportMarker != hitTeleportMarker ) //Pointing at a new teleport marker
{
if ( pointedAtTeleportMarker != null )
{
pointedAtTeleportMarker.Highlight( false );
}
if ( hitTeleportMarker != null )
{
hitTeleportMarker.Highlight( true );
prevPointedAtPosition = pointedAtPosition;
PlayPointerHaptic( !hitTeleportMarker.locked );
PlayAudioClip( reticleAudioSource, goodHighlightSound );
loopingAudioSource.volume = loopingAudioMaxVolume;
}
else if ( pointedAtTeleportMarker != null )
{
PlayAudioClip( reticleAudioSource, badHighlightSound );
loopingAudioSource.volume = 0.0f;
}
}
else if ( hitTeleportMarker != null ) //Pointing at the same teleport marker
{
if ( Vector3.Distance( prevPointedAtPosition, pointedAtPosition ) > 1.0f )
{
prevPointedAtPosition = pointedAtPosition;
PlayPointerHaptic( !hitTeleportMarker.locked );
}
}
}
//-------------------------------------------------
public void ShowTeleportHint()
{
CancelTeleportHint();
hintCoroutine = StartCoroutine( TeleportHintCoroutine() );
}
//-------------------------------------------------
public void CancelTeleportHint()
{
if ( hintCoroutine != null )
{
ControllerButtonHints.HideTextHint(player.leftHand, teleportAction);
ControllerButtonHints.HideTextHint(player.rightHand, teleportAction);
StopCoroutine( hintCoroutine );
hintCoroutine = null;
}
CancelInvoke( "ShowTeleportHint" );
}
//-------------------------------------------------
private IEnumerator TeleportHintCoroutine()
{
float prevBreakTime = Time.time;
float prevHapticPulseTime = Time.time;
while ( true )
{
bool pulsed = false;
//Show the hint on each eligible hand
foreach ( Hand hand in player.hands )
{
bool showHint = IsEligibleForTeleport( hand );
bool isShowingHint = !string.IsNullOrEmpty( ControllerButtonHints.GetActiveHintText( hand, teleportAction) );
if ( showHint )
{
if ( !isShowingHint )
{
ControllerButtonHints.ShowTextHint( hand, teleportAction, "Teleport" );
prevBreakTime = Time.time;
prevHapticPulseTime = Time.time;
}
if ( Time.time > prevHapticPulseTime + 0.05f )
{
//Haptic pulse for a few seconds
pulsed = true;
hand.TriggerHapticPulse( 500 );
}
}
else if ( !showHint && isShowingHint )
{
ControllerButtonHints.HideTextHint( hand, teleportAction);
}
}
if ( Time.time > prevBreakTime + 3.0f )
{
//Take a break for a few seconds
yield return new WaitForSeconds( 3.0f );
prevBreakTime = Time.time;
}
if ( pulsed )
{
prevHapticPulseTime = Time.time;
}
yield return null;
}
}
//-------------------------------------------------
public bool IsEligibleForTeleport( Hand hand )
{
if ( hand == null )
{
return false;
}
if ( !hand.gameObject.activeInHierarchy )
{
return false;
}
if ( hand.hoveringInteractable != null )
{
return false;
}
if ( hand.noSteamVRFallbackCamera == null )
{
if ( hand.isActive == false)
{
return false;
}
//Something is attached to the hand
if ( hand.currentAttachedObject != null )
{
AllowTeleportWhileAttachedToHand allowTeleportWhileAttachedToHand = hand.currentAttachedObject.GetComponent<AllowTeleportWhileAttachedToHand>();
if ( allowTeleportWhileAttachedToHand != null && allowTeleportWhileAttachedToHand.teleportAllowed == true )
{
return true;
}
else
{
return false;
}
}
}
return true;
}
//-------------------------------------------------
private bool ShouldOverrideHoverLock()
{
if ( !allowTeleportWhileAttached || allowTeleportWhileAttached.overrideHoverLock )
{
return true;
}
return false;
}
//-------------------------------------------------
private bool WasTeleportButtonReleased( Hand hand )
{
if ( IsEligibleForTeleport( hand ) )
{
if ( hand.noSteamVRFallbackCamera != null )
{
return Input.GetKeyUp( KeyCode.T );
}
else
{
return teleportAction.GetStateUp(hand.handType);
//return hand.controller.GetPressUp( SteamVR_Controller.ButtonMask.Touchpad );
}
}
return false;
}
//-------------------------------------------------
private bool IsTeleportButtonDown( Hand hand )
{
if ( IsEligibleForTeleport( hand ) )
{
if ( hand.noSteamVRFallbackCamera != null )
{
return Input.GetKey( KeyCode.T );
}
else
{
return teleportAction.GetState(hand.handType);
}
}
return false;
}
//-------------------------------------------------
private bool WasTeleportButtonPressed( Hand hand )
{
if ( IsEligibleForTeleport( hand ) )
{
if ( hand.noSteamVRFallbackCamera != null )
{
return Input.GetKeyDown( KeyCode.T );
}
else
{
return teleportAction.GetStateDown(hand.handType);
//return hand.controller.GetPressDown( SteamVR_Controller.ButtonMask.Touchpad );
}
}
return false;
}
//-------------------------------------------------
private Transform GetPointerStartTransform( Hand hand )
{
if ( hand.noSteamVRFallbackCamera != null )
{
return hand.noSteamVRFallbackCamera.transform;
}
else
{
return hand.transform;
}
}
}
}
| 412 | 0.97843 | 1 | 0.97843 | game-dev | MEDIA | 0.987441 | game-dev | 0.971635 | 1 | 0.971635 |
DonnYep/CosmosFramework | 4,024 | Assets/CosmosFramework/Runtime/Modules/Scene/ISceneManager.cs | using System;
using UnityEngine;
namespace Cosmos.Scene
{
public interface ISceneManager : IModuleManager
{
/// <summary>
/// 异步加载场景;
/// </summary>
/// <param name="sceneInfo">场景信息</param>
/// <param name="callback">加载完毕后的回调</param>
/// <returns>协程对象</returns>
Coroutine LoadSceneAsync(SceneAssetInfo sceneInfo, Action callback = null);
/// <summary>
/// 异步加载场景;
/// </summary>
/// <param name="sceneInfo">场景信息</param>
/// <param name="progress">加载场景进度回调</param>
/// <param name="callback">场景加载完毕回调</param>
/// <returns>协程对象</returns>
Coroutine LoadSceneAsync(SceneAssetInfo sceneInfo, Action<float> progress, Action callback = null);
/// <summary>
/// 异步加载场景;
/// </summary>
/// <param name="sceneInfo">场景信息</param>
/// <param name="condition">场景加载完成的条件</param>
/// <param name="callback">场景加载完毕回调</param>
/// <returns>协程对象</returns>
Coroutine LoadSceneAsync(SceneAssetInfo sceneInfo, Func<bool> condition, Action callback = null);
/// <summary>
/// 异步加载场景;
/// </summary>
/// <param name="sceneInfo">场景信息</param>
/// <param name="progress">加载场景进度回调</param>
/// <param name="condition">场景加载完成的条件</param>
/// <param name="callback">场景加载完毕回调</param>
/// <returns>协程对象</returns>
Coroutine LoadSceneAsync(SceneAssetInfo sceneInfo, Action<float> progress, Func<bool> condition, Action callback = null);
/// <summary>
/// 异步加载场景;
/// </summary>
/// <param name="sceneInfo">场景信息</param>
/// <param name="progressProvider">自定义的加载进度0-1</param>
/// <param name="progress">加载场景进度回调</param>
/// <param name="callback">场景加载完毕回调</param>
/// <returns>协程对象</returns>
Coroutine LoadSceneAsync(SceneAssetInfo sceneInfo, Func<float> progressProvider, Action<float> progress, Action callback = null);
/// <summary>
/// 异步加载场景;
/// </summary>
/// <param name="sceneInfo">场景信息</param>
/// <param name="progressProvider">自定义的加载进度0-1</param>
/// <param name="progress">加载场景进度回调</param>
/// <param name="condition">场景加载完成的条件</param>
/// <param name="callback">场景加载完毕回调</param>
/// <returns>协程对象</returns>
Coroutine LoadSceneAsync(SceneAssetInfo sceneInfo, Func<float> progressProvider, Action<float> progress, Func<bool> condition, Action callback = null);
/// <summary>
/// 异步卸载场景;
/// </summary>
/// <param name="sceneInfo">场景信息</param>
/// <param name="callback">场景卸载完毕后的回调</param>
/// <returns>协程对象</returns>
Coroutine UnloadSceneAsync(SceneAssetInfo sceneInfo, Action callback = null);
/// <summary>
/// 异步卸载场景;
/// </summary>
/// <param name="sceneInfo">场景信息</param>
/// <param name="progress">卸载场景的进度</param>
/// <param name="callback">场景卸载完毕后的回调</param>
/// <returns>协程对象</returns>
Coroutine UnloadSceneAsync(SceneAssetInfo sceneInfo, Action<float> progress, Action callback = null);
/// <summary>
/// 异步卸载场景;
/// </summary>
/// <param name="sceneInfo">场景信息</param>
/// <param name="condition">卸载场景完成的条件</param>
/// <param name="callback">场景卸载完毕后的回调</param>
/// <returns>协程对象</returns>
Coroutine UnloadSceneAsync(SceneAssetInfo sceneInfo, Func<bool> condition, Action callback = null);
/// <summary>
/// 异步卸载场景;
/// </summary>
/// <param name="sceneInfo">场景信息</param>
/// <param name="progress">卸载场景的进度</param>
/// <param name="condition">卸载场景完成的条件</param>
/// <param name="callback">场景卸载完毕后的回调</param>
/// <returns>协程对象</returns>
Coroutine UnloadSceneAsync(SceneAssetInfo sceneInfo, Action<float> progress, Func<bool> condition, Action callback = null);
}
}
| 412 | 0.721265 | 1 | 0.721265 | game-dev | MEDIA | 0.377166 | game-dev | 0.506527 | 1 | 0.506527 |
3arthh4ckDevelopment/3arthh4ck-Fabric | 1,470 | src/main/java/me/earth/earthhack/impl/modules/player/spectate/ListenerAnimation.java | package me.earth.earthhack.impl.modules.player.spectate;
import me.earth.earthhack.impl.event.events.network.PacketEvent;
import me.earth.earthhack.impl.event.listeners.ModuleListener;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.network.packet.s2c.play.EntityAnimationS2CPacket;
import net.minecraft.util.Hand;
final class ListenerAnimation extends
ModuleListener<Spectate, PacketEvent.Receive<EntityAnimationS2CPacket>>
{
public ListenerAnimation(Spectate module)
{
super(module, PacketEvent.Receive.class, EntityAnimationS2CPacket.class);
}
@Override
public void invoke(PacketEvent.Receive<EntityAnimationS2CPacket> event)
{
event.addPostEvent(() ->
{
PlayerEntity playerSp = mc.player;
if (playerSp != null && module.spectating)
{
PlayerEntity player = module.player;
EntityAnimationS2CPacket packet = event.getPacket();
if (player != null
&& packet.getEntityId() == player.getId())
{
if (packet.getAnimationId() == 0)
{
playerSp.swingHand(Hand.MAIN_HAND);
}
else if (packet.getAnimationId() == 3)
{
playerSp.swingHand(Hand.OFF_HAND);
}
}
}
});
}
}
| 412 | 0.814398 | 1 | 0.814398 | game-dev | MEDIA | 0.955455 | game-dev | 0.561051 | 1 | 0.561051 |
chipsenkbeil/vimwiki-rs | 2,500 | vimwiki_macros/src/tokens/elements/blocks/tables.rs | use crate::tokens::{
utils::{root_crate, tokenize_hashmap},
Tokenize, TokenizeContext,
};
use proc_macro2::TokenStream;
use quote::quote;
use vimwiki_core::{Cell, CellPos, CellSpan, ColumnAlign, Table};
impl_tokenize!(tokenize_table, Table<'a>, 'a);
fn tokenize_table(ctx: &TokenizeContext, table: &Table) -> TokenStream {
let root = root_crate();
let centered = table.centered;
let cells = tokenize_hashmap(
table.as_data(),
quote!(#root::CellPos),
quote!(#root::Located<#root::Cell>),
|x| do_tokenize!(ctx, x),
|x| do_tokenize!(ctx, x),
);
quote! {
#root::Table::new(
#cells,
#centered,
)
}
}
impl_tokenize!(tokenize_cell, Cell<'a>, 'a);
fn tokenize_cell(ctx: &TokenizeContext, cell: &Cell) -> TokenStream {
let root = root_crate();
match &cell {
Cell::Content(x) => {
let t = do_tokenize!(ctx, x);
quote! { #root::Cell::Content(#t) }
}
Cell::Span(x) => {
let t = do_tokenize!(ctx, x);
quote! { #root::Cell::Span(#t) }
}
Cell::Align(x) => {
let t = do_tokenize!(ctx, x);
quote! { #root::Cell::Align(#t) }
}
}
}
impl_tokenize!(tokenize_column_align, ColumnAlign);
fn tokenize_column_align(
_ctx: &TokenizeContext,
column_align: &ColumnAlign,
) -> TokenStream {
let root = root_crate();
match column_align {
ColumnAlign::None => {
quote! { #root::ColumnAlign::None }
}
ColumnAlign::Left => {
quote! { #root::ColumnAlign::Left }
}
ColumnAlign::Center => {
quote! { #root::ColumnAlign::Center }
}
ColumnAlign::Right => {
quote! { #root::ColumnAlign::Right }
}
}
}
impl_tokenize!(tokenize_cell_span, CellSpan);
fn tokenize_cell_span(
_ctx: &TokenizeContext,
cell_span: &CellSpan,
) -> TokenStream {
let root = root_crate();
match cell_span {
CellSpan::FromAbove => {
quote! { #root::CellSpan::FromAbove }
}
CellSpan::FromLeft => {
quote! { #root::CellSpan::FromLeft }
}
}
}
impl_tokenize!(tokenize_cell_pos, CellPos);
fn tokenize_cell_pos(
_ctx: &TokenizeContext,
cell_pos: &CellPos,
) -> TokenStream {
let root = root_crate();
let row = cell_pos.row;
let col = cell_pos.col;
quote! { #root::CellPos::new(#row, #col) }
}
| 412 | 0.93898 | 1 | 0.93898 | game-dev | MEDIA | 0.178914 | game-dev | 0.688808 | 1 | 0.688808 |
cmangos/playerbots | 58,701 | playerbot/PlayerbotAIConfig.cpp |
#include "playerbot/PlayerbotAIConfig.h"
#include "playerbot/playerbot.h"
#include "RandomPlayerbotFactory.h"
#include "Accounts/AccountMgr.h"
#include "SystemConfig.h"
#include "playerbot/PlayerbotFactory.h"
#include "RandomItemMgr.h"
#include "World/WorldState.h"
#include "playerbot/PlayerbotHelpMgr.h"
#include "playerbot/TravelMgr.h"
#include <iostream>
#include <numeric>
#include <iomanip>
#include <boost/algorithm/string.hpp>
#include <regex>
#include "PlayerbotLoginMgr.h"
std::vector<std::string> ConfigAccess::GetValues(const std::string& name) const
{
std::vector<std::string> values;
auto const nameLower = boost::algorithm::to_lower_copy(name);
for (auto entry : m_entries)
if (entry.first.find(nameLower) != std::string::npos)
values.push_back(entry.first);
return values;
};
INSTANTIATE_SINGLETON_1(PlayerbotAIConfig);
PlayerbotAIConfig::PlayerbotAIConfig()
: enabled(false)
{
}
template <class T>
void LoadList(std::string value, T &list)
{
list.clear();
std::vector<std::string> ids = split(value, ',');
for (std::vector<std::string>::iterator i = ids.begin(); i != ids.end(); i++)
{
std::string string = *i;
if (string.empty())
continue;
uint32 id = atoi(string.c_str());
list.push_back(id);
}
}
template <class T>
void LoadListString(std::string value, T& list)
{
list.clear();
std::vector<std::string> strings = split(value, ',');
for (std::vector<std::string>::iterator i = strings.begin(); i != strings.end(); i++)
{
std::string string = *i;
if (string.empty())
continue;
list.push_back(string);
}
}
inline ParsedUrl parseUrl(const std::string& url) {
std::regex urlRegex(R"((http|https)://([^:/]+)(:([0-9]+))?(/.*)?)");
std::smatch match;
if (!std::regex_match(url, match, urlRegex)) {
throw std::invalid_argument("Invalid URL format");
}
ParsedUrl parsed;
parsed.hostname = match[2];
parsed.https = match[1] == "https";
parsed.port = parsed.https ? 443 : (match[4].length() ? std::stoi(match[4]) : 80);
parsed.path = match[5].length() ? match[5] : std::string("/");
return parsed;
}
bool PlayerbotAIConfig::Initialize()
{
sLog.outString("Initializing AI Playerbot by ike3, based on the original Playerbot by blueboy");
if (!config.SetSource(SYSCONFDIR"aiplayerbot.conf", "PlayerBots_"))
{
sLog.outString("AI Playerbot is Disabled. Unable to open configuration file aiplayerbot.conf");
return false;
}
enabled = config.GetBoolDefault("AiPlayerbot.Enabled", false);
if (!enabled)
{
sLog.outString("AI Playerbot is Disabled in aiplayerbot.conf");
return false;
}
ConfigAccess* configA = reinterpret_cast<ConfigAccess*>(&config);
BarGoLink::SetOutputState(config.GetBoolDefault("AiPlayerbot.ShowProgressBars", false));
globalCoolDown = (uint32) config.GetIntDefault("AiPlayerbot.GlobalCooldown", 500);
maxWaitForMove = config.GetIntDefault("AiPlayerbot.MaxWaitForMove", 3000);
expireActionTime = config.GetIntDefault("AiPlayerbot.ExpireActionTime", 5000);
dispelAuraDuration = config.GetIntDefault("AiPlayerbot.DispelAuraDuration", 2000);
reactDelay = (uint32) config.GetIntDefault("AiPlayerbot.ReactDelay", 100);
passiveDelay = (uint32) config.GetIntDefault("AiPlayerbot.PassiveDelay", 4000);
repeatDelay = (uint32) config.GetIntDefault("AiPlayerbot.RepeatDelay", 5000);
errorDelay = (uint32) config.GetIntDefault("AiPlayerbot.ErrorDelay", 5000);
rpgDelay = (uint32) config.GetIntDefault("AiPlayerbot.RpgDelay", 3000);
sitDelay = (uint32) config.GetIntDefault("AiPlayerbot.SitDelay", 30000);
returnDelay = (uint32) config.GetIntDefault("AiPlayerbot.ReturnDelay", 7000);
lootDelay = (uint32)config.GetIntDefault("AiPlayerbot.LootDelayDelay", 750);
farDistance = config.GetFloatDefault("AiPlayerbot.FarDistance", 20.0f);
sightDistance = config.GetFloatDefault("AiPlayerbot.SightDistance", 75.0f);
spellDistance = config.GetFloatDefault("AiPlayerbot.SpellDistance", 25.0f);
shootDistance = config.GetFloatDefault("AiPlayerbot.ShootDistance", 25.0f);
healDistance = config.GetFloatDefault("AiPlayerbot.HealDistance", 125.0f);
reactDistance = config.GetFloatDefault("AiPlayerbot.ReactDistance", 150.0f);
maxFreeMoveDistance = config.GetFloatDefault("AiPlayerbot.MaxFreeMoveDistance", 150.0f);
freeMoveDelay = config.GetFloatDefault("AiPlayerbot.FreeMoveDelay", 30.0f);
grindDistance = config.GetFloatDefault("AiPlayerbot.GrindDistance", 75.0f);
aggroDistance = config.GetFloatDefault("AiPlayerbot.AggroDistance", 22.0f);
lootDistance = config.GetFloatDefault("AiPlayerbot.LootDistance", 25.0f);
groupMemberLootDistance = config.GetFloatDefault("AiPlayerbot.GroupMemberLootDistance", 15.0f);
groupMemberLootDistanceWithActiveMaster = config.GetFloatDefault("AiPlayerbot.GroupMemberLootDistanceWithActiveMaster", 10.0f);
gatheringDistance = config.GetFloatDefault("AiPlayerbot.GatheringDistance", 15.0f);
groupMemberGatheringDistance = config.GetFloatDefault("AiPlayerbot.GroupMemberGatheringDistance", 10.0f);
groupMemberGatheringDistanceWithActiveMaster = config.GetFloatDefault("AiPlayerbot.GroupMemberGatheringDistanceWithActiveMaster", 5.0f);
fleeDistance = config.GetFloatDefault("AiPlayerbot.FleeDistance", 8.0f);
tooCloseDistance = config.GetFloatDefault("AiPlayerbot.TooCloseDistance", 5.0f);
meleeDistance = config.GetFloatDefault("AiPlayerbot.MeleeDistance", 1.5f);
followDistance = config.GetFloatDefault("AiPlayerbot.FollowDistance", 1.5f);
raidFollowDistance = config.GetFloatDefault("AiPlayerbot.RaidFollowDistance", 5.0f);
whisperDistance = config.GetFloatDefault("AiPlayerbot.WhisperDistance", 6000.0f);
contactDistance = config.GetFloatDefault("AiPlayerbot.ContactDistance", 0.5f);
aoeRadius = config.GetFloatDefault("AiPlayerbot.AoeRadius", 5.0f);
rpgDistance = config.GetFloatDefault("AiPlayerbot.RpgDistance", 80.0f);
proximityDistance = config.GetFloatDefault("AiPlayerbot.ProximityDistance", 20.0f);
criticalHealth = config.GetIntDefault("AiPlayerbot.CriticalHealth", 20);
lowHealth = config.GetIntDefault("AiPlayerbot.LowHealth", 50);
mediumHealth = config.GetIntDefault("AiPlayerbot.MediumHealth", 70);
almostFullHealth = config.GetIntDefault("AiPlayerbot.AlmostFullHealth", 90);
lowMana = config.GetIntDefault("AiPlayerbot.LowMana", 15);
mediumMana = config.GetIntDefault("AiPlayerbot.MediumMana", 40);
randomGearMaxLevel = config.GetIntDefault("AiPlayerbot.RandomGearMaxLevel", 500);
randomGearMaxDiff = config.GetIntDefault("AiPlayerbot.RandomGearMaxDiff", 9);
randomGearUpgradeEnabled = config.GetBoolDefault("AiPlayerbot.RandomGearUpgradeEnabled", false);
randomGearTabards = config.GetBoolDefault("AiPlayerbot.RandomGearTabards", false);
randomGearTabardsChance = config.GetFloatDefault("AiPlayerbot.RandomGearTabardsChance", 0.1f);
randomGearTabardsReplaceGuild = config.GetBoolDefault("AiPlayerbot.RandomGearTabardsReplaceGuild", false);
randomGearTabardsUnobtainable = config.GetBoolDefault("AiPlayerbot.RandomGearTabardsUnobtainable", false);
LoadList<std::list<uint32> >(config.GetStringDefault("AiPlayerbot.RandomGearBlacklist", ""), randomGearBlacklist);
LoadList<std::list<uint32> >(config.GetStringDefault("AiPlayerbot.RandomGearWhitelist", ""), randomGearWhitelist);
randomGearProgression = config.GetBoolDefault("AiPlayerbot.RandomGearProgression", true);
randomGearLoweringChance = config.GetFloatDefault("AiPlayerbot.RandomGearLoweringChance", 0.15f);
randomBotMaxLevelChance = config.GetFloatDefault("AiPlayerbot.RandomBotMaxLevelChance", 0.15f);
randomBotRpgChance = config.GetFloatDefault("AiPlayerbot.RandomBotRpgChance", 0.35f);
usePotionChance = config.GetFloatDefault("AiPlayerbot.UsePotionChance", 1.0f);
attackEmoteChance = config.GetFloatDefault("AiPlayerbot.AttackEmoteChance", 0.0f);
jumpNoCombatChance = config.GetFloatDefault("AiPlayerbot.JumpNoCombatChance", 0.5f);
jumpMeleeInCombatChance = config.GetFloatDefault("AiPlayerbot.JumpMeleeInCombatChance", 0.5f);
jumpRandomChance = config.GetFloatDefault("AiPlayerbot.JumpRandomChance", 0.20f);
jumpInPlaceChance = config.GetFloatDefault("AiPlayerbot.JumpInPlaceChance", 0.50f);
jumpBackwardChance = config.GetFloatDefault("AiPlayerbot.JumpBackwardChance", 0.10f);
jumpHeightLimit = config.GetFloatDefault("AiPlayerbot.JumpHeightLimit", 60.f);
jumpVSpeed = config.GetFloatDefault("AiPlayerbot.JumpVSpeed", 7.96f);
jumpHSpeed = config.GetFloatDefault("AiPlayerbot.JumpHSpeed", 7.0f);
jumpInBg = config.GetBoolDefault("AiPlayerbot.JumpInBg", false);
jumpWithPlayer = config.GetBoolDefault("AiPlayerbot.JumpWithPlayer", false);
jumpFollow = config.GetBoolDefault("AiPlayerbot.JumpFollow", true);
jumpChase = config.GetBoolDefault("AiPlayerbot.JumpChase", true);
useKnockback = config.GetBoolDefault("AiPlayerbot.UseKnockback", true);
iterationsPerTick = config.GetIntDefault("AiPlayerbot.IterationsPerTick", 100);
allowGuildBots = config.GetBoolDefault("AiPlayerbot.AllowGuildBots", true);
allowMultiAccountAltBots = config.GetBoolDefault("AiPlayerbot.AllowMultiAccountAltBots", true);
randomBotMapsAsString = config.GetStringDefault("AiPlayerbot.RandomBotMaps", "0,1,530,571");
LoadList<std::vector<uint32> >(randomBotMapsAsString, randomBotMaps);
LoadList<std::list<uint32> >(config.GetStringDefault("AiPlayerbot.RandomBotQuestItems", "6948,5175,5176,5177,5178,16309,12382,13704,11000,22754"), randomBotQuestItems);
LoadList<std::list<uint32> >(config.GetStringDefault("AiPlayerbot.RandomBotSpellIds", "54197"), randomBotSpellIds);
LoadList<std::list<uint32> >(config.GetStringDefault("AiPlayerbot.PvpProhibitedZoneIds", "2255,656,2361,2362,2363,976,35,2268,3425,392,541,1446,3828,3712,3738,3565,3539,3623,4152,3988,4658,4284,4418,4436,4275,4323"), pvpProhibitedZoneIds);
#ifndef MANGOSBOT_ZERO
// disable pvp near dark portal if event is active
if (sWorldState.GetExpansion() == EXPANSION_NONE)
pvpProhibitedZoneIds.insert(pvpProhibitedZoneIds.begin(), 72);
#endif
LoadList<std::list<uint32> >(config.GetStringDefault("AiPlayerbot.RandomBotQuestIds", "7848,3802,5505,6502,7761,9378"), randomBotQuestIds);
LoadList<std::list<uint32> >(config.GetStringDefault("AiPlayerbot.ImmuneSpellIds", ""), immuneSpellIds);
botAutologin = BotAutoLogin(config.GetIntDefault("AiPlayerbot.BotAutologin", 0));
randomBotAutologin = config.GetBoolDefault("AiPlayerbot.RandomBotAutologin", true);
randomBotAutoCreate = config.GetBoolDefault("AiPlayerbot.RandomBotAutoCreate", true);
minRandomBots = config.GetIntDefault("AiPlayerbot.MinRandomBots", 50);
maxRandomBots = config.GetIntDefault("AiPlayerbot.MaxRandomBots", 200);
randomBotUpdateInterval = config.GetIntDefault("AiPlayerbot.RandomBotUpdateInterval", 1);
randomBotCountChangeMinInterval = config.GetIntDefault("AiPlayerbot.RandomBotCountChangeMinInterval", 1 * 1800);
randomBotCountChangeMaxInterval = config.GetIntDefault("AiPlayerbot.RandomBotCountChangeMaxInterval", 2 * 3600);
loginBoostPercentage = config.GetFloatDefault("AiPlayerbot.LoginBoostPercentage", 90);
randomBotTimedLogout = config.GetBoolDefault("AiPlayerbot.RandomBotTimedLogout", true);
randomBotTimedOffline = config.GetBoolDefault("AiPlayerbot.RandomBotTimedOffline", false);
minRandomBotInWorldTime = config.GetIntDefault("AiPlayerbot.MinRandomBotInWorldTime", 1 * 1800);
maxRandomBotInWorldTime = config.GetIntDefault("AiPlayerbot.MaxRandomBotInWorldTime", 6 * 3600);
minRandomBotRandomizeTime = config.GetIntDefault("AiPlayerbot.MinRandomBotRandomizeTime", 6 * 3600);
maxRandomBotRandomizeTime = config.GetIntDefault("AiPlayerbot.MaxRandomRandomizeTime", 24 * 3600);
minRandomBotChangeStrategyTime = config.GetIntDefault("AiPlayerbot.MinRandomBotChangeStrategyTime", 1800);
maxRandomBotChangeStrategyTime = config.GetIntDefault("AiPlayerbot.MaxRandomBotChangeStrategyTime", 2 * 3600);
minRandomBotReviveTime = config.GetIntDefault("AiPlayerbot.MinRandomBotReviveTime", 60);
maxRandomBotReviveTime = config.GetIntDefault("AiPlayerbot.MaxRandomReviveTime", 300);
enableRandomTeleports = config.GetBoolDefault("AiPlayerbot.EnableRandomTeleports", true);
randomBotTeleportDistance = config.GetIntDefault("AiPlayerbot.RandomBotTeleportDistance", 1000);
randomBotTeleportNearPlayer = config.GetBoolDefault("AiPlayerbot.RandomBotTeleportNearPlayer", false);
randomBotTeleportNearPlayerMaxAmount = config.GetIntDefault("AiPlayerbot.RandomBotTeleportNearPlayerMaxAmount", 0);
randomBotTeleportNearPlayerMaxAmountRadius = config.GetFloatDefault("AiPlayerbot.RandomBotTeleportNearPlayerMaxAmountRadius", 0.0f);
randomBotTeleportMinInterval = config.GetIntDefault("AiPlayerbot.RandomBotTeleportTeleportMinInterval", 2 * 3600);
randomBotTeleportMaxInterval = config.GetIntDefault("AiPlayerbot.RandomBotTeleportTeleportMaxInterval", 48 * 3600);
randomBotsPerInterval = config.GetIntDefault("AiPlayerbot.RandomBotsPerInterval", 3);
randomBotsMaxLoginsPerInterval = config.GetIntDefault("AiPlayerbot.RandomBotsMaxLoginsPerInterval", randomBotsPerInterval);
minRandomBotsPriceChangeInterval = config.GetIntDefault("AiPlayerbot.MinRandomBotsPriceChangeInterval", 2 * 3600);
maxRandomBotsPriceChangeInterval = config.GetIntDefault("AiPlayerbot.MaxRandomBotsPriceChangeInterval", 48 * 3600);
//Auction house settings
shouldQueryAHListingsOutsideOfAH = config.GetBoolDefault("AiPlayerbot.ShouldQueryAHListingsOutsideOfAH", true);
LoadList<std::list<uint32> >(config.GetStringDefault("AiPlayerbot.AhOverVendorItemIds", ""), ahOverVendorItemIds);
LoadList<std::list<uint32> >(config.GetStringDefault("AiPlayerbot.VendorOverAHItemIds", ""), vendorOverAHItemIds);
botCheckAllAuctionListings = config.GetBoolDefault("AiPlayerbot.BotCheckAllAuctionListings", false);
//
randomBotJoinLfg = config.GetBoolDefault("AiPlayerbot.RandomBotJoinLfg", true);
logRandomBotJoinLfg = config.GetBoolDefault("AiPlayerbot.LogRandomBotJoinLfg", false);
randomBotJoinBG = config.GetBoolDefault("AiPlayerbot.RandomBotJoinBG", true);
randomBotAutoJoinBG = config.GetBoolDefault("AiPlayerbot.RandomBotAutoJoinBG", false);
randomBotBracketCount = config.GetIntDefault("AiPlayerbot.RandomBotBracketCount", 3);
logInGroupOnly = config.GetBoolDefault("AiPlayerbot.LogInGroupOnly", true);
logValuesPerTick = config.GetBoolDefault("AiPlayerbot.LogValuesPerTick", false);
fleeingEnabled = config.GetBoolDefault("AiPlayerbot.FleeingEnabled", true);
summonAtInnkeepersEnabled = config.GetBoolDefault("AiPlayerbot.SummonAtInnkeepersEnabled", true);
randomBotMinLevel = config.GetIntDefault("AiPlayerbot.RandomBotMinLevel", 1);
randomBotMaxLevel = config.GetIntDefault("AiPlayerbot.RandomBotMaxLevel", 255);
randomBotLoginAtStartup = config.GetBoolDefault("AiPlayerbot.RandomBotLoginAtStartup", true);
randomBotTeleLevel = config.GetIntDefault("AiPlayerbot.RandomBotTeleLevel", 5);
openGoSpell = config.GetIntDefault("AiPlayerbot.OpenGoSpell", 6477);
randomChangeMultiplier = config.GetFloatDefault("AiPlayerbot.RandomChangeMultiplier", 1.0);
randomBotCombatStrategies = config.GetStringDefault("AiPlayerbot.RandomBotCombatStrategies", "-threat,+custom::say");
randomBotNonCombatStrategies = config.GetStringDefault("AiPlayerbot.RandomBotNonCombatStrategies", "+custom::say");
randomBotReactStrategies = config.GetStringDefault("AiPlayerbot.RandomBotReactStrategies", "");
randomBotDeadStrategies = config.GetStringDefault("AiPlayerbot.RandomBotDeadStrategies", "");
combatStrategies = config.GetStringDefault("AiPlayerbot.CombatStrategies", "");
nonCombatStrategies = config.GetStringDefault("AiPlayerbot.NonCombatStrategies", "+return,+delayed roll");
reactStrategies = config.GetStringDefault("AiPlayerbot.ReactStrategies", "");
deadStrategies = config.GetStringDefault("AiPlayerbot.DeadStrategies", "");
commandPrefix = config.GetStringDefault("AiPlayerbot.CommandPrefix", "");
commandSeparator = config.GetStringDefault("AiPlayerbot.CommandSeparator", "\\\\");
commandServerPort = config.GetIntDefault("AiPlayerbot.CommandServerPort", 0);
perfMonEnabled = config.GetBoolDefault("AiPlayerbot.PerfMonEnabled", false);
bExplicitDbStoreSave = config.GetBoolDefault("AiPlayerbot.ExplicitDbStoreSave", false);
randomBotLoginWithPlayer = config.GetBoolDefault("AiPlayerbot.RandomBotLoginWithPlayer", false);
asyncBotLogin = config.GetBoolDefault("AiPlayerbot.AsyncBotLogin", false);
preloadHolders = config.GetBoolDefault("AiPlayerbot.PreloadHolders", false);
freeRoomForNonSpareBots = config.GetIntDefault("AiPlayerbot.FreeRoomForNonSpareBots", 1);
loginBotsNearPlayerRange = config.GetIntDefault("AiPlayerbot.LoginBotsNearPlayerRange", 1000);
LoadListString<std::vector<std::string> >(config.GetStringDefault("AiPlayerbot.DefaultLoginCriteria", "maxbots,spareroom,offline"), defaultLoginCriteria);
std::vector<std::string> criteriaValues = configA->GetValues("AiPlayerbot.LoginCriteria");
std::sort(criteriaValues.begin(), criteriaValues.end());
loginCriteria.clear();
for (auto& value : criteriaValues)
{
loginCriteria.push_back({});
LoadListString<std::vector<std::string> >(config.GetStringDefault(value, ""), loginCriteria.back());
}
if (criteriaValues.empty())
{
loginCriteria.push_back({ "group" });
loginCriteria.push_back({ "arena" });
loginCriteria.push_back({ "bg" });
loginCriteria.push_back({ "guild" });
loginCriteria.push_back({ "logoff,classrace,level,online" });
loginCriteria.push_back({ "logoff,classrace,level" });
loginCriteria.push_back({ "logoff,classrace" });
}
for (uint32 level = 1; level <= DEFAULT_MAX_LEVEL; ++level)
{
levelProbability[level] = config.GetIntDefault("AiPlayerbot.LevelProbability." + std::to_string(level), 100);
}
sLog.outString("Loading Race/Class probabilities");
classRaceProbabilityTotal = 0;
useFixedClassRaceCounts = config.GetBoolDefault("AiPlayerbot.ClassRace.UseFixedClassRaceCounts", false);
RandomPlayerbotFactory factory(0);
for (uint32 race = 1; race < MAX_RACES; ++race)
{
//Set race defaults
if (race > 0)
{
int rProb = config.GetIntDefault("AiPlayerbot.ClassRaceProb.0." + std::to_string(race), 100);
for (uint32 cls = 1; cls < MAX_CLASSES; ++cls)
{
classRaceProbability[cls][race] = rProb;
}
}
}
//Class overrides
for (uint32 cls = 1; cls < MAX_CLASSES; ++cls)
{
int cProb = config.GetIntDefault("AiPlayerbot.ClassRaceProb." + std::to_string(cls), -1);
if (cProb >= 0)
{
for (uint32 race = 1; race < MAX_RACES; ++race)
{
classRaceProbability[cls][race] = cProb;
}
}
}
//Race Class overrides
for (uint32 race = 1; race < MAX_RACES; ++race)
{
for (uint32 cls = 1; cls < MAX_CLASSES; ++cls)
{
int rcProb = config.GetIntDefault("AiPlayerbot.ClassRaceProb." + std::to_string(cls) + "." + std::to_string(race), -1);
if (rcProb >= 0)
classRaceProbability[cls][race] = rcProb;
if (!factory.isAvailableRace(cls, race))
classRaceProbability[cls][race] = 0;
else
classRaceProbabilityTotal += classRaceProbability[cls][race];
}
}
if (useFixedClassRaceCounts)
{
// Warn about unsupported config keys
for (uint32 race = 1; race < MAX_RACES; ++race)
{
std::string raceKey = "AiPlayerbot.ClassRaceProb.0." + std::to_string(race);
int val = config.GetIntDefault(raceKey.c_str(), -1);
if (val >= 0)
sLog.outError("Fixed class/race counts does not yet support '%s' (race-only). This config entry will be ignored.", raceKey.c_str());
}
for (uint32 cls = 1; cls < MAX_CLASSES; ++cls)
{
std::string classKey = "AiPlayerbot.ClassRaceProb." + std::to_string(cls);
int val = config.GetIntDefault(classKey.c_str(), -1);
if (val >= 0)
sLog.outError("Fixed class/race counts does not yet support '%s' (class-only). This config entry will be ignored.", classKey.c_str());
}
//Parse and build fixedClassRacesCounts
{
for (uint32 cls = 1; cls < MAX_CLASSES; ++cls)
{
for (uint32 race = 1; race < MAX_RACES; ++race)
{
std::string key = "AiPlayerbot.ClassRaceProb." + std::to_string(cls) + "." + std::to_string(race);
int count = config.GetIntDefault(key, -1);
if (count >= 0 && factory.isAvailableRace(cls, race))
{
fixedClassRaceCounts[{cls, race}] = count;
}
}
}
}
}
botCheats.clear();
LoadListString<std::list<std::string>>(config.GetStringDefault("AiPlayerbot.BotCheats", "taxi,item,breath"), botCheats);
botCheatMask = 0;
if (std::find(botCheats.begin(), botCheats.end(), "taxi") != botCheats.end())
botCheatMask |= (uint32)BotCheatMask::taxi;
if (std::find(botCheats.begin(), botCheats.end(), "gold") != botCheats.end())
botCheatMask |= (uint32)BotCheatMask::gold;
if (std::find(botCheats.begin(), botCheats.end(), "health") != botCheats.end())
botCheatMask |= (uint32)BotCheatMask::health;
if (std::find(botCheats.begin(), botCheats.end(), "mana") != botCheats.end())
botCheatMask |= (uint32)BotCheatMask::mana;
if (std::find(botCheats.begin(), botCheats.end(), "power") != botCheats.end())
botCheatMask |= (uint32)BotCheatMask::power;
if (std::find(botCheats.begin(), botCheats.end(), "item") != botCheats.end())
botCheatMask |= (uint32)BotCheatMask::item;
if (std::find(botCheats.begin(), botCheats.end(), "cooldown") != botCheats.end())
botCheatMask |= (uint32)BotCheatMask::cooldown;
if (std::find(botCheats.begin(), botCheats.end(), "repair") != botCheats.end())
botCheatMask |= (uint32)BotCheatMask::repair;
if (std::find(botCheats.begin(), botCheats.end(), "movespeed") != botCheats.end())
botCheatMask |= (uint32)BotCheatMask::movespeed;
if (std::find(botCheats.begin(), botCheats.end(), "attackspeed") != botCheats.end())
botCheatMask |= (uint32)BotCheatMask::attackspeed;
if (std::find(botCheats.begin(), botCheats.end(), "breath") != botCheats.end())
botCheatMask |= (uint32)BotCheatMask::breath;
LoadListString<std::list<std::string>>(config.GetStringDefault("AiPlayerbot.AllowedLogFiles", ""), allowedLogFiles);
LoadListString<std::list<std::string>>(config.GetStringDefault("AiPlayerbot.DebugFilter", "add gathering loot,check values,emote,check mount state,jump"), debugFilter);
worldBuffs.clear();
//Get all config values starting with AiPlayerbot.WorldBuff
std::vector<std::string> values = configA->GetValues("AiPlayerbot.WorldBuff");
if (values.size())
{
sLog.outString("Loading WorldBuffs");
BarGoLink wbuffBar(values.size());
for (auto value : values)
{
std::vector<std::string> ids = split(value, '.');
std::vector<uint32> params = { 0,0,0,0,0,0 };
//Extract faction, class, spec, minlevel, maxlevel
for (uint8 i = 0; i < 6; i++)
if (ids.size() > i + 2)
params[i] = stoi(ids[i + 2]);
//Get list of buffs for this combination.
std::list<uint32> buffs;
LoadList<std::list<uint32>>(config.GetStringDefault(value, ""), buffs);
//Store buffs for later application.
for (auto buff : buffs)
{
worldBuff wb = { buff, params[0], params[1], params[2], params[3], params[4], params[5] };
worldBuffs.push_back(wb);
}
wbuffBar.step();
}
}
randomBotAccountPrefix = config.GetStringDefault("AiPlayerbot.RandomBotAccountPrefix", "rndbot");
randomBotAccountCount = config.GetIntDefault("AiPlayerbot.RandomBotAccountCount", 50);
deleteRandomBotAccounts = config.GetBoolDefault("AiPlayerbot.DeleteRandomBotAccounts", false);
randomBotGuildCount = config.GetIntDefault("AiPlayerbot.RandomBotGuildCount", 20);
deleteRandomBotGuilds = config.GetBoolDefault("AiPlayerbot.DeleteRandomBotGuilds", false);
//arena
randomBotArenaTeamCount = config.GetIntDefault("AiPlayerbot.RandomBotArenaTeamCount", 20);
deleteRandomBotArenaTeams = config.GetBoolDefault("AiPlayerbot.DeleteRandomBotArenaTeams", false);
//cosmetics (by lidocain)
randomBotShowCloak = config.GetBoolDefault("AiPlayerbot.RandomBotShowCloak", false);
randomBotShowHelmet = config.GetBoolDefault("AiPlayerbot.RandomBotShowHelmet", false);
//SPP switches
enableGreet = config.GetBoolDefault("AiPlayerbot.EnableGreet", false);
disableRandomLevels = config.GetBoolDefault("AiPlayerbot.DisableRandomLevels", false);
instantRandomize = config.GetBoolDefault("AiPlayerbot.InstantRandomize", true);
randomBotRandomPassword = config.GetBoolDefault("AiPlayerbot.RandomBotRandomPassword", true);
playerbotsXPrate = config.GetFloatDefault("AiPlayerbot.XPRate", 1.0f);
disableBotOptimizations = config.GetBoolDefault("AiPlayerbot.DisableBotOptimizations", false);
disableActivityPriorities = config.GetBoolDefault("AiPlayerbot.DisableActivityPriorities", false);
botActiveAlone = config.GetIntDefault("AiPlayerbot.botActiveAlone", 10);
diffWithPlayer = config.GetIntDefault("AiPlayerbot.DiffWithPlayer", 100);
diffEmpty = config.GetIntDefault("AiPlayerbot.DiffEmpty", 200);
RandombotsWalkingRPG = config.GetBoolDefault("AiPlayerbot.RandombotsWalkingRPG", false);
RandombotsWalkingRPGInDoors = config.GetBoolDefault("AiPlayerbot.RandombotsWalkingRPG.InDoors", false);
minEnchantingBotLevel = config.GetIntDefault("AiPlayerbot.minEnchantingBotLevel", 60);
randombotStartingLevel = config.GetIntDefault("AiPlayerbot.randombotStartingLevel", 5);
gearscorecheck = config.GetBoolDefault("AiPlayerbot.GearScoreCheck", false);
levelCheck = config.GetIntDefault("AiPlayerbot.LevelCheck", 30);
randomBotPreQuests = config.GetBoolDefault("AiPlayerbot.PreQuests", true);
randomBotSayWithoutMaster = config.GetBoolDefault("AiPlayerbot.RandomBotSayWithoutMaster", false);
randomBotInvitePlayer = config.GetBoolDefault("AiPlayerbot.RandomBotInvitePlayer", true);
randomBotGroupNearby = config.GetBoolDefault("AiPlayerbot.RandomBotGroupNearby", true);
randomBotRaidNearby = config.GetBoolDefault("AiPlayerbot.RandomBotRaidNearby", true);
randomBotGuildNearby = config.GetBoolDefault("AiPlayerbot.RandomBotGuildNearby", true);
inviteChat = config.GetBoolDefault("AiPlayerbot.InviteChat", true);
guildMaxBotLimit = config.GetIntDefault("AiPlayerbot.GuildMaxBotLimit", 1000);
////////////////////////////
enableBroadcasts = config.GetBoolDefault("AiPlayerbot.EnableBroadcasts", true);
//broadcastChanceMaxValue is used in urand(1, broadcastChanceMaxValue) for broadcasts,
//lowering it will increase the chance, setting it to 0 will disable broadcasts
//for internal use, not intended to be change by the user
broadcastChanceMaxValue = enableBroadcasts ? 30000 : 0;
//all broadcast chances should be in range 1-broadcastChanceMaxValue, value of 0 will disable this particular broadcast
//setting value to max does not guarantee the broadcast, as there are some internal randoms as well
broadcastToGuildGlobalChance = config.GetIntDefault("AiPlayerbot.BroadcastToGuildGlobalChance", 30000);
broadcastToWorldGlobalChance = config.GetIntDefault("AiPlayerbot.BroadcastToWorldGlobalChance", 30000);
broadcastToGeneralGlobalChance = config.GetIntDefault("AiPlayerbot.BroadcastToGeneralGlobalChance", 30000);
broadcastToTradeGlobalChance = config.GetIntDefault("AiPlayerbot.BroadcastToTradeGlobalChance", 30000);
broadcastToLFGGlobalChance = config.GetIntDefault("AiPlayerbot.BroadcastToLFGGlobalChance", 30000);
broadcastToLocalDefenseGlobalChance = config.GetIntDefault("AiPlayerbot.BroadcastToLocalDefenseGlobalChance", 30000);
broadcastToWorldDefenseGlobalChance = config.GetIntDefault("AiPlayerbot.BroadcastToWorldDefenseGlobalChance", 30000);
broadcastToGuildRecruitmentGlobalChance = config.GetIntDefault("AiPlayerbot.BroadcastToGuildRecruitmentGlobalChance", 30000);
broadcastToSayGlobalChance = config.GetIntDefault("AiPlayerbot.BroadcastToSayGlobalChance", 30000);
broadcastToYellGlobalChance = config.GetIntDefault("AiPlayerbot.BroadcastToYellGlobalChance", 30000);
broadcastChanceLootingItemPoor = config.GetIntDefault("AiPlayerbot.BroadcastChanceLootingItemPoor", 30);
broadcastChanceLootingItemNormal = config.GetIntDefault("AiPlayerbot.BroadcastChanceLootingItemNormal", 300);
broadcastChanceLootingItemUncommon = config.GetIntDefault("AiPlayerbot.BroadcastChanceLootingItemUncommon", 10000);
broadcastChanceLootingItemRare = config.GetIntDefault("AiPlayerbot.BroadcastChanceLootingItemRare", 20000);
broadcastChanceLootingItemEpic = config.GetIntDefault("AiPlayerbot.BroadcastChanceLootingItemEpic", 30000);
broadcastChanceLootingItemLegendary = config.GetIntDefault("AiPlayerbot.BroadcastChanceLootingItemLegendary", 30000);
broadcastChanceLootingItemArtifact = config.GetIntDefault("AiPlayerbot.BroadcastChanceLootingItemArtifact", 30000);
broadcastChanceQuestAccepted = config.GetIntDefault("AiPlayerbot.BroadcastChanceQuestAccepted", 6000);
broadcastChanceQuestUpdateObjectiveCompleted = config.GetIntDefault("AiPlayerbot.BroadcastChanceQuestUpdateObjectiveCompleted", 300);
broadcastChanceQuestUpdateObjectiveProgress = config.GetIntDefault("AiPlayerbot.BroadcastChanceQuestUpdateObjectiveProgress", 300);
broadcastChanceQuestUpdateFailedTimer = config.GetIntDefault("AiPlayerbot.BroadcastChanceQuestUpdateFailedTimer", 300);
broadcastChanceQuestUpdateComplete = config.GetIntDefault("AiPlayerbot.BroadcastChanceQuestUpdateComplete", 1000);
broadcastChanceQuestTurnedIn = config.GetIntDefault("AiPlayerbot.BroadcastChanceQuestTurnedIn", 10000);
broadcastChanceKillNormal = config.GetIntDefault("AiPlayerbot.BroadcastChanceKillNormal", 30);
broadcastChanceKillElite = config.GetIntDefault("AiPlayerbot.BroadcastChanceKillElite", 300);
broadcastChanceKillRareelite = config.GetIntDefault("AiPlayerbot.BroadcastChanceKillRareelite", 3000);
broadcastChanceKillWorldboss = config.GetIntDefault("AiPlayerbot.BroadcastChanceKillWorldboss", 20000);
broadcastChanceKillRare = config.GetIntDefault("AiPlayerbot.BroadcastChanceKillRare", 10000);
broadcastChanceKillUnknown = config.GetIntDefault("AiPlayerbot.BroadcastChanceKillUnknown", 100);
broadcastChanceKillPet = config.GetIntDefault("AiPlayerbot.BroadcastChanceKillPet", 10);
broadcastChanceKillPlayer = config.GetIntDefault("AiPlayerbot.BroadcastChanceKillPlayer", 30);
broadcastChanceLevelupGeneric = config.GetIntDefault("AiPlayerbot.BroadcastChanceLevelupGeneric", 20000);
broadcastChanceLevelupTenX = config.GetIntDefault("AiPlayerbot.BroadcastChanceLevelupTenX", 30000);
broadcastChanceLevelupMaxLevel = config.GetIntDefault("AiPlayerbot.BroadcastChanceLevelupMaxLevel", 30000);
broadcastChanceSuggestInstance = config.GetIntDefault("AiPlayerbot.BroadcastChanceSuggestInstance", 5000);
broadcastChanceSuggestQuest = config.GetIntDefault("AiPlayerbot.BroadcastChanceSuggestQuest", 10000);
broadcastChanceSuggestGrindMaterials = config.GetIntDefault("AiPlayerbot.BroadcastChanceSuggestGrindMaterials", 5000);
broadcastChanceSuggestGrindReputation = config.GetIntDefault("AiPlayerbot.BroadcastChanceSuggestGrindReputation", 5000);
broadcastChanceSuggestSell = config.GetIntDefault("AiPlayerbot.BroadcastChanceSuggestSell", 300);
broadcastChanceSuggestSomething = config.GetIntDefault("AiPlayerbot.BroadcastChanceSuggestSomething", 30000);
broadcastChanceSuggestSomethingToxic = config.GetIntDefault("AiPlayerbot.BroadcastChanceSuggestSomethingToxic", 0);
broadcastChanceSuggestToxicLinks = config.GetIntDefault("AiPlayerbot.BroadcastChanceSuggestToxicLinks", 0);
toxicLinksPrefix = config.GetStringDefault("AiPlayerbot.ToxicLinksPrefix", "gnomes");
broadcastChanceSuggestThunderfury = config.GetIntDefault("AiPlayerbot.BroadcastChanceSuggestThunderfury", 1);
//does not depend on global chance
broadcastChanceGuildManagement = config.GetIntDefault("AiPlayerbot.BroadcastChanceGuildManagement", 30000);
////////////////////////////
toxicLinksRepliesChance = config.GetIntDefault("AiPlayerbot.ToxicLinksRepliesChance", 30); //0-100
thunderfuryRepliesChance = config.GetIntDefault("AiPlayerbot.ThunderfuryRepliesChance", 40); //0-100
guildRepliesRate = config.GetIntDefault("AiPlayerbot.GuildRepliesRate", 100); //0-100
botAcceptDuelMinimumLevel = config.GetIntDefault("AiPlayerbot.BotAcceptDuelMinimumLevel", 10);
randomBotFormGuild = config.GetBoolDefault("AiPlayerbot.RandomBotFormGuild", true);
boostFollow = config.GetBoolDefault("AiPlayerbot.BoostFollow", false);
turnInRpg = config.GetBoolDefault("AiPlayerbot.TurnInRpg", false);
globalSoundEffects = config.GetBoolDefault("AiPlayerbot.GlobalSoundEffects", false);
nonGmFreeSummon = config.GetBoolDefault("AiPlayerbot.NonGmFreeSummon", false);
//SPP automation
autoPickReward = config.GetStringDefault("AiPlayerbot.AutoPickReward", "no");
autoEquipUpgradeLoot = config.GetBoolDefault("AiPlayerbot.AutoEquipUpgradeLoot", false);
syncQuestWithPlayer = config.GetBoolDefault("AiPlayerbot.SyncQuestWithPlayer", false);
syncQuestForPlayer = config.GetBoolDefault("AiPlayerbot.SyncQuestForPlayer", false);
autoTrainSpells = config.GetStringDefault("AiPlayerbot.AutoTrainSpells", "no");
autoPickTalents = config.GetStringDefault("AiPlayerbot.AutoPickTalents", "no");
autoLearnTrainerSpells = config.GetBoolDefault("AiPlayerbot.AutoLearnTrainerSpells", false);
autoLearnQuestSpells = config.GetBoolDefault("AiPlayerbot.AutoLearnQuestSpells", false);
autoLearnDroppedSpells = config.GetBoolDefault("AiPlayerbot.AutoLearnDroppedSpells", false);
autoDoQuests = config.GetBoolDefault("AiPlayerbot.AutoDoQuests", true);
syncLevelWithPlayers = config.GetBoolDefault("AiPlayerbot.SyncLevelWithPlayers", false);
syncLevelMaxAbove = config.GetIntDefault("AiPlayerbot.SyncLevelMaxAbove", 5);
syncLevelNoPlayer = config.GetIntDefault("AiPlayerbot.SyncLevelNoPlayer", randombotStartingLevel);
tweakValue = config.GetIntDefault("AiPlayerbot.TweakValue", 0);
talentsInPublicNote = config.GetBoolDefault("AiPlayerbot.TalentsInPublicNote", false);
respawnModNeutral = config.GetFloatDefault("AiPlayerbot.RespawnModNeutral", 10.0f);
respawnModHostile = config.GetFloatDefault("AiPlayerbot.RespawnModHostile", 5.0f);
respawnModThreshold = config.GetIntDefault("AiPlayerbot.RespawnModThreshold", 10);
respawnModMax = config.GetIntDefault("AiPlayerbot.RespawnModMax", 18);
respawnModForPlayerBots = config.GetBoolDefault("AiPlayerbot.RespawnModForPlayerBots", false);
respawnModForInstances = config.GetBoolDefault("AiPlayerbot.RespawnModForInstances", false);
//LLM START
llmEnabled = config.GetIntDefault("AiPlayerbot.LLMEnabled", 1);
llmApiEndpoint = config.GetStringDefault("AiPlayerbot.LLMApiEndpoint", "http://127.0.0.1:5001/api/v1/generate");
try {
llmEndPointUrl = parseUrl(llmApiEndpoint);
}
catch (const std::invalid_argument& e) {
sLog.outError("Unable to parse LLMApiEndpoint url: %s", e.what());
}
llmApiKey = config.GetStringDefault("AiPlayerbot.LLMApiKey", "");
llmApiJson = config.GetStringDefault("AiPlayerbot.LLMApiJson", "{ \"max_length\": 100, \"prompt\": \"[<pre prompt>]<context> <prompt> <post prompt>\"}");
llmContextLength = config.GetIntDefault("AiPlayerbot.LLMContextLength", 4096);
llmGenerationTimeout = config.GetIntDefault("AiPlayerbot.LLMGenerationTimeout", 600);
llmMaxSimultaniousGenerations = config.GetIntDefault("AiPlayerbot.LLMMaxSimultaniousGenerations", 100);
llmPrePrompt = config.GetStringDefault("AiPlayerbot.LLMPrePrompt", "You are a roleplaying character in World of Warcraft: <expansion name>. Your name is <bot name>. The <other type> <other name> is speaking to you <channel name> and is an <other gender> <other race> <other class> of level <other level>. You are level <bot level> and play as a <bot gender> <bot race> <bot class> that is currently in <bot subzone> <bot zone>. Answer as a roleplaying character. Limit responses to 100 characters.");
llmPreRpgPrompt = config.GetStringDefault("AiPlayerbot.LLMRpgPrompt", "In World of Warcraft: <expansion name> in <bot zone> <bot subzone> stands <bot type> <bot name> a level <bot level> <bot gender> <bot race> <bot class>."
" Standing nearby is <unit type> <unit name> <unit subname> a level <unit level> <unit gender> <unit race> <unit faction> <unit class>. Answer as a roleplaying character. Limit responses to 100 characters.");
llmPrompt = config.GetStringDefault("AiPlayerbot.LLMPrompt", "<receiver name>:<initial message>");
llmPostPrompt = config.GetStringDefault("AiPlayerbot.LLMPostPrompt", "<sender name>:");
llmResponseStartPattern = config.GetStringDefault("AiPlayerbot.LLMResponseStartPattern", R"(("text":\s*"))");
llmResponseEndPattern = config.GetStringDefault("AiPlayerbot.LLMResponseEndPattern", R"(("|\b(?!<sender name>\b)(\w+):))");
llmResponseDeletePattern = config.GetStringDefault("AiPlayerbot.LLMResponseDeletePattern", R"((\\n|<sender name>:|\\[^ ]+))");
llmResponseSplitPattern = config.GetStringDefault("AiPlayerbot.LLMResponseSplitPattern", R"((\*.*?\*)|(\[.*?\])|(\'.*\')|([^\*\[\] ][^\*\[\]]+?[.?!]))");
if (false) //Disable for release
{
sLog.outError("# AiPlayerbot.LLMResponseStartPattern = %s", llmResponseStartPattern.c_str());
sLog.outError("# AiPlayerbot.LLMResponseEndPattern = %s", llmResponseEndPattern.c_str());
sLog.outError("# AiPlayerbot.LLMResponseDeletePattern = %s", llmResponseDeletePattern.c_str());
sLog.outError("# AiPlayerbot.LLMResponseSplitPattern = %s", llmResponseSplitPattern.c_str());
}
try {
std::regex pattern(llmResponseStartPattern);
}
catch (const std::regex_error& e) {
sLog.outError("Regex error in %s: %s", llmResponseStartPattern.c_str(), e.what());
}
try {
std::regex pattern(llmResponseEndPattern);
}
catch (const std::regex_error& e) {
sLog.outError("Regex error in %s: %s", llmResponseEndPattern.c_str(), e.what());
}
try {
std::regex pattern(llmResponseDeletePattern);
}
catch (const std::regex_error& e) {
sLog.outError("Regex error in %s: %s", llmResponseDeletePattern.c_str(), e.what());
}
try {
std::regex pattern(llmResponseSplitPattern);
}
catch (const std::regex_error& e) {
sLog.outError("Regex error in %s: %s", llmResponseSplitPattern.c_str(), e.what());
}
llmGlobalContext = config.GetBoolDefault("AiPlayerbot.LLMGlobalContext", false);
llmBotToBotChatChance = config.GetIntDefault("AiPlayerbot.LLMBotToBotChatChance", 0);
llmRpgAIChatChance = config.GetIntDefault("AiPlayerbot.LLMRpgAIChatChance", 100);
std::list<std::string> blockedChannels;
LoadListString<std::list<std::string>>(config.GetStringDefault("AiPlayerbot.LLMBlockedReplyChannels", ""), blockedChannels);
std::map<std::string, ChatChannelSource> sourceName;
sourceName["guild"] = ChatChannelSource::SRC_GUILD;
sourceName["world"] = ChatChannelSource::SRC_WORLD;
sourceName["general"] = ChatChannelSource::SRC_GENERAL;
sourceName["trade"] = ChatChannelSource::SRC_TRADE;
sourceName["lfg"] = ChatChannelSource::SRC_LOOKING_FOR_GROUP;
sourceName["ldefence"] = ChatChannelSource::SRC_LOCAL_DEFENSE;
sourceName["wdefence"] = ChatChannelSource::SRC_WORLD_DEFENSE;
sourceName["grecruitement"] = ChatChannelSource::SRC_GUILD_RECRUITMENT;
sourceName["say"] = ChatChannelSource::SRC_SAY;
sourceName["whisper"] = ChatChannelSource::SRC_WHISPER;
sourceName["emote"] = ChatChannelSource::SRC_EMOTE;
sourceName["temote"] = ChatChannelSource::SRC_TEXT_EMOTE;
sourceName["yell"] = ChatChannelSource::SRC_YELL;
sourceName["party"] = ChatChannelSource::SRC_PARTY;
sourceName["raid"] = ChatChannelSource::SRC_RAID;
for (auto& channelName : blockedChannels)
llmBlockedReplyChannels.insert(sourceName[channelName]);
//LLM END
// Gear progression system
gearProgressionSystemEnabled = config.GetBoolDefault("AiPlayerbot.GearProgressionSystem.Enable", false);
// Gear progression phase
for (uint8 phase = 0; phase < MAX_GEAR_PROGRESSION_LEVEL; phase++)
{
std::ostringstream os; os << "AiPlayerbot.GearProgressionSystem." << std::to_string(phase) << ".MinItemLevel";
gearProgressionSystemItemLevels[phase][0] = config.GetIntDefault(os.str().c_str(), 9999999);
os.str(""); os << "AiPlayerbot.GearProgressionSystem." << std::to_string(phase) << ".MaxItemLevel";
gearProgressionSystemItemLevels[phase][1] = config.GetIntDefault(os.str().c_str(), 9999999);
// Gear progression class
for (uint8 cls = 1; cls < MAX_CLASSES; cls++)
{
// Gear progression spec
for (uint8 spec = 0; spec < 4; spec++)
{
// Gear progression slot
for (uint8 slot = 0; slot < SLOT_EMPTY; slot++)
{
std::ostringstream os; os << "AiPlayerbot.GearProgressionSystem." << std::to_string(phase) << "." << std::to_string(cls) << "." << std::to_string(spec) << "." << std::to_string(slot);
gearProgressionSystemItems[phase][cls][spec][slot] = config.GetIntDefault(os.str().c_str(), -1);
}
}
}
}
sLog.outString("Loading free bots.");
selfBotLevel = BotSelfBotLevel(config.GetIntDefault("AiPlayerbot.SelfBotLevel", uint32(BotSelfBotLevel::GM_ONLY)));
LoadListString<std::list<std::string>>(config.GetStringDefault("AiPlayerbot.ToggleAlwaysOnlineAccounts", ""), toggleAlwaysOnlineAccounts);
LoadListString<std::list<std::string>>(config.GetStringDefault("AiPlayerbot.ToggleAlwaysOnlineChars", ""), toggleAlwaysOnlineChars);
for (std::string& nm : toggleAlwaysOnlineAccounts)
std::transform(nm.begin(), nm.end(), nm.begin(), toupper);
for (std::string& nm : toggleAlwaysOnlineChars)
{
std::transform(nm.begin(), nm.end(), nm.begin(), tolower);
nm[0] = toupper(nm[0]);
}
loadFreeAltBotAccounts();
targetPosRecalcDistance = config.GetFloatDefault("AiPlayerbot.TargetPosRecalcDistance", 0.1f),
sLog.outString("Loading area levels.");
sTravelMgr.LoadAreaLevels();
sLog.outString("Loading spellIds.");
ChatHelper::PopulateSpellNameList();
ItemUsageValue::PopulateProfessionReagentIds();
ItemUsageValue::PopulateSoldByVendorItemIds();
ItemUsageValue::PopulateReagentItemIdsForCraftableItemIds();
RandomPlayerbotFactory::CreateRandomBots();
PlayerbotFactory::Init();
sRandomItemMgr.Init();
sPlayerbotTextMgr.LoadBotTexts();
sPlayerbotTextMgr.LoadBotTextChance();
sPlayerbotHelpMgr.LoadBotHelpTexts();
LoadTalentSpecs();
if (sPlayerbotAIConfig.autoDoQuests)
{
sLog.outString("Loading Quest Detail Data...");
sTravelMgr.LoadQuestTravelTable();
}
sLog.outString("Loading named locations...");
sRandomPlayerbotMgr.LoadNamedLocations();
if (sPlayerbotAIConfig.randomBotJoinBG)
sRandomPlayerbotMgr.LoadBattleMastersCache();
sLog.outString("---------------------------------------");
sLog.outString(" AI Playerbot initialized ");
sLog.outString("---------------------------------------");
sLog.outString();
return true;
}
bool PlayerbotAIConfig::IsInRandomAccountList(uint32 id)
{
return find(randomBotAccounts.begin(), randomBotAccounts.end(), id) != randomBotAccounts.end();
}
bool PlayerbotAIConfig::IsFreeAltBot(uint32 guid)
{
for (auto bot : freeAltBots)
if (bot.second == guid)
return true;
return false;
}
bool PlayerbotAIConfig::IsInRandomQuestItemList(uint32 id)
{
return find(randomBotQuestItems.begin(), randomBotQuestItems.end(), id) != randomBotQuestItems.end();
}
bool PlayerbotAIConfig::IsInPvpProhibitedZone(uint32 id)
{
return find(pvpProhibitedZoneIds.begin(), pvpProhibitedZoneIds.end(), id) != pvpProhibitedZoneIds.end();
}
std::string PlayerbotAIConfig::GetValue(std::string name)
{
std::ostringstream out;
if (name == "GlobalCooldown")
out << globalCoolDown;
else if (name == "ReactDelay")
out << reactDelay;
else if (name == "SightDistance")
out << sightDistance;
else if (name == "SpellDistance")
out << spellDistance;
else if (name == "ReactDistance")
out << reactDistance;
else if (name == "GrindDistance")
out << grindDistance;
else if (name == "LootDistance")
out << lootDistance;
else if (name == "FleeDistance")
out << fleeDistance;
else if (name == "CriticalHealth")
out << criticalHealth;
else if (name == "LowHealth")
out << lowHealth;
else if (name == "MediumHealth")
out << mediumHealth;
else if (name == "AlmostFullHealth")
out << almostFullHealth;
else if (name == "LowMana")
out << lowMana;
else if (name == "IterationsPerTick")
out << iterationsPerTick;
return out.str();
}
void PlayerbotAIConfig::SetValue(std::string name, std::string value)
{
std::istringstream out(value, std::istringstream::in);
if (name == "GlobalCooldown")
out >> globalCoolDown;
else if (name == "ReactDelay")
out >> reactDelay;
else if (name == "SightDistance")
out >> sightDistance;
else if (name == "SpellDistance")
out >> spellDistance;
else if (name == "ReactDistance")
out >> reactDistance;
else if (name == "GrindDistance")
out >> grindDistance;
else if (name == "LootDistance")
out >> lootDistance;
else if (name == "FleeDistance")
out >> fleeDistance;
else if (name == "CriticalHealth")
out >> criticalHealth;
else if (name == "LowHealth")
out >> lowHealth;
else if (name == "MediumHealth")
out >> mediumHealth;
else if (name == "AlmostFullHealth")
out >> almostFullHealth;
else if (name == "LowMana")
out >> lowMana;
else if (name == "IterationsPerTick")
out >> iterationsPerTick;
}
void PlayerbotAIConfig::loadFreeAltBotAccounts()
{
bool allCharsOnline = (selfBotLevel == BotSelfBotLevel::ALWAYS_ACTIVE);
freeAltBots.clear();
auto results = LoginDatabase.PQuery("SELECT username, id FROM account where username not like '%s%%'", randomBotAccountPrefix.c_str());
if (results)
{
do
{
bool accountToggle = false;
Field* fields = results->Fetch();
std::string accountName = fields[0].GetString();
uint32 accountId = fields[1].GetUInt32();
if (std::find(toggleAlwaysOnlineAccounts.begin(), toggleAlwaysOnlineAccounts.end(), accountName) != toggleAlwaysOnlineAccounts.end())
accountToggle = true;
auto result = CharacterDatabase.PQuery("SELECT name, guid FROM characters WHERE account = '%u'", accountId);
if (!result)
continue;
do
{
bool charToggle = false;
Field* fields = result->Fetch();
std::string charName = fields[0].GetString();
uint32 guid = fields[1].GetUInt32();
BotAlwaysOnline always = BotAlwaysOnline(sRandomPlayerbotMgr.GetValue(guid, "always"));
if (always == BotAlwaysOnline::DISABLED_BY_COMMAND)
continue;
if (std::find(toggleAlwaysOnlineChars.begin(), toggleAlwaysOnlineChars.end(), charName) != toggleAlwaysOnlineChars.end())
charToggle = true;
bool thisCharAlwaysOnline = allCharsOnline;
if (accountToggle || charToggle)
thisCharAlwaysOnline = !thisCharAlwaysOnline;
if ((thisCharAlwaysOnline && always != BotAlwaysOnline::DISABLED_BY_COMMAND) || always == BotAlwaysOnline::ACTIVE)
{
sLog.outString("Enabling always online for %s", charName.c_str());
freeAltBots.push_back(std::make_pair(accountId, guid));
}
} while (result->NextRow());
} while (results->NextRow());
}
}
std::string PlayerbotAIConfig::GetTimestampStr()
{
time_t t = time(nullptr);
tm* aTm = localtime(&t);
// YYYY year
// MM month (2 digits 01-12)
// DD day (2 digits 01-31)
// HH hour (2 digits 00-23)
// MM minutes (2 digits 00-59)
// SS seconds (2 digits 00-59)
char buf[20];
snprintf(buf, 20, "%04d-%02d-%02d %02d:%02d:%02d", aTm->tm_year + 1900, aTm->tm_mon + 1, aTm->tm_mday, aTm->tm_hour, aTm->tm_min, aTm->tm_sec);
return std::string(buf);
}
bool PlayerbotAIConfig::openLog(std::string fileName, char const* mode, bool haslog)
{
if (!haslog && !hasLog(fileName))
return false;
auto logFileIt = logFiles.find(fileName);
if (logFileIt == logFiles.end())
{
logFiles.insert(make_pair(fileName, std::make_pair(nullptr, false)));
logFileIt = logFiles.find(fileName);
}
FILE* file = logFileIt->second.first;
bool fileOpen = logFileIt->second.second;
if (fileOpen) //close log file
fclose(file);
std::string m_logsDir = sConfig.GetStringDefault("LogsDir");
if (!m_logsDir.empty())
{
if ((m_logsDir.at(m_logsDir.length() - 1) != '/') && (m_logsDir.at(m_logsDir.length() - 1) != '\\'))
m_logsDir.append("/");
}
file = fopen((m_logsDir + fileName).c_str(), mode);
fileOpen = true;
logFileIt->second.first = file;
logFileIt->second.second = fileOpen;
return true;
}
void PlayerbotAIConfig::log(std::string fileName, const char* str, ...)
{
if (!str)
return;
std::lock_guard<std::mutex> guard(m_logMtx);
if (!isLogOpen(fileName))
if (!openLog(fileName, "a"))
return;
FILE* file = logFiles.find(fileName)->second.first;
va_list ap;
va_start(ap, str);
vfprintf(file, str, ap);
fprintf(file, "\n");
va_end(ap);
fflush(file);
fflush(stdout);
}
void PlayerbotAIConfig::logEvent(PlayerbotAI* ai, std::string eventName, std::string info1, std::string info2)
{
if (hasLog("bot_events.csv"))
{
Player* bot = ai->GetBot();
std::ostringstream out;
out << sPlayerbotAIConfig.GetTimestampStr() << "+00,";
out << bot->GetName() << ",";
out << eventName << ",";
out << std::fixed << std::setprecision(2);
WorldPosition(bot).printWKT(out);
out << std::to_string(bot->getRace()) << ",";
out << std::to_string(bot->getClass()) << ",";
float subLevel = ai->GetLevelFloat();
out << subLevel << ",";
out << "\"" << info1 << "\",";
out << "\"" << info2 << "\"";
log("bot_events.csv", out.str().c_str());
}
};
void PlayerbotAIConfig::logEvent(PlayerbotAI* ai, std::string eventName, ObjectGuid guid, std::string info2)
{
std::string info1 = "";
Unit* victim;
if (guid)
{
victim = ai->GetUnit(guid);
if (victim)
info1 = victim->GetName();
}
logEvent(ai, eventName, info1, info2);
};
bool PlayerbotAIConfig::CanLogAction(PlayerbotAI* ai, std::string actionName, bool isExecute, std::string lastActionName)
{
bool forRpg = (actionName.find("rpg") == 0) && ai->HasStrategy("debug rpg", BotState::BOT_STATE_NON_COMBAT);
if (!forRpg)
{
if (isExecute && !ai->HasStrategy("debug", BotState::BOT_STATE_NON_COMBAT))
return false;
if (!isExecute && !ai->HasStrategy("debug action", BotState::BOT_STATE_NON_COMBAT))
return false;
if ((lastActionName == actionName) && (actionName == "melee"))
{
return false;
}
}
return std::find(debugFilter.begin(), debugFilter.end(), actionName) == debugFilter.end();
}
void PlayerbotAIConfig::LoadTalentSpecs()
{
sLog.outString("Loading TalentSpecs");
uint32 maxSpecLevel = 0;
for (uint32 cls = 1; cls < MAX_CLASSES; ++cls)
{
classSpecs[cls] = ClassSpecs(1 << (cls - 1));
for (uint32 spec = 0; spec < MAX_LEVEL; ++spec)
{
std::ostringstream os; os << "AiPlayerbot.PremadeSpecName." << cls << "." << spec;
std::string specName = config.GetStringDefault(os.str().c_str(), "");
if (!specName.empty())
{
std::ostringstream os; os << "AiPlayerbot.PremadeSpecProb." << cls << "." << spec;
int probability = config.GetIntDefault(os.str().c_str(), 100);
TalentPath talentPath(spec, specName, probability);
for (uint32 level = 10; level <= 100; level++)
{
std::ostringstream os; os << "AiPlayerbot.PremadeSpecLink." << cls << "." << spec << "." << level;
std::string specLink = config.GetStringDefault(os.str().c_str(), "");
specLink = specLink.substr(0, specLink.find("#", 0));
specLink = specLink.substr(0, specLink.find(" ", 0));
if (!specLink.empty())
{
if (maxSpecLevel < level)
maxSpecLevel = level;
std::ostringstream out;
//Ignore bad specs.
if (!classSpecs[cls].baseSpec.CheckTalentLink(specLink, &out))
{
sLog.outErrorDb("Error with premade spec link: %s", specLink.c_str());
sLog.outErrorDb("%s", out.str().c_str());
continue;
}
TalentSpec linkSpec(&classSpecs[cls].baseSpec, specLink);
if (!linkSpec.CheckTalents(level, &out))
{
sLog.outErrorDb("Error with premade spec: %s", specLink.c_str());
sLog.outErrorDb("%s", out.str().c_str());
continue;
}
talentPath.talentSpec.push_back(linkSpec);
}
{
//Glyphs
using GlyphPriority = std::pair<std::string, uint32>;
using GlyphPriorityList = std::vector<GlyphPriority>;
using GlyphPriorityLevelMap = std::unordered_map<uint32, GlyphPriorityList>;
using GlyphPrioritySpecMap = std::unordered_map<uint32, GlyphPriorityLevelMap>;
std::ostringstream os; os << "AiPlayerbot.PremadeSpecGlyp." << cls << "." << spec << "." << level;
std::string glyphList = config.GetStringDefault(os.str().c_str(), "");
glyphList = glyphList.substr(0, glyphList.find("#", 0));
boost::trim_right(glyphList);
if (!glyphList.empty())
{
Tokens premadeSpecGlyphs = Qualified::getMultiQualifiers(glyphList, ",");
for (auto& glyph : premadeSpecGlyphs)
{
Tokens tokens = Qualified::getMultiQualifiers(glyph, "|");
std::string glyphName = "Glyph of " + tokens[0];
uint32 talentId = tokens.size() > 1 ? stoi(tokens[1]) : 0;
bool glyphFound = false;
for (auto& itemId : sRandomItemMgr.GetGlyphs(1 << (cls - 1)))
{
ItemPrototype const* proto = sObjectMgr.GetItemPrototype(itemId);
if (!proto)
continue;
if (proto->Name1 == glyphName)
{
glyphPriorityMap[cls][spec][level].push_back(std::make_pair(itemId, talentId));
glyphFound = true;
break;
}
}
if (!glyphFound)
{
sLog.outError("%s is not found for class %d (spec %d level %d)", glyphName.c_str(), cls, spec, level);
}
}
}
}
}
//Only add paths that have atleast 1 spec.
if (talentPath.talentSpec.size() > 0)
classSpecs[cls].talentPath.push_back(talentPath);
}
}
}
if (classSpecs[1].talentPath.empty())
sLog.outErrorDb("No premade specs found!!");
else
{
if (maxSpecLevel < DEFAULT_MAX_LEVEL && randomBotMaxLevel < DEFAULT_MAX_LEVEL)
sLog.outErrorDb("!!!!!!!!!!! randomBotMaxLevel and the talentspec levels are below this expansions max level. Please check if you have the correct config file!!!!!!");
}
}
| 412 | 0.92346 | 1 | 0.92346 | game-dev | MEDIA | 0.424524 | game-dev | 0.877941 | 1 | 0.877941 |
codand/Unity3DPortals | 1,519 | Assets/Portals/Example/Scripts/PortalColliderRaycaster.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Portals;
using System.Linq;
[RequireComponent(typeof(Portal))]
public class PortalColliderRaycaster : MonoBehaviour {
public enum UpdateMode {
Start,
FixedUpdate,
}
[SerializeField] private UpdateMode _updateMode = UpdateMode.Start;
[SerializeField] private LayerMask _layerMask;
[SerializeField] private float _boxcastDistance = 5.0f;
[SerializeField] private float _boxcastScaleMultiplier = 0.99f;
Portal _portal;
Collider _collider;
private void Awake() {
_portal = GetComponent<Portal>();
_collider = GetComponent<Collider>();
}
private void Start() {
if (_updateMode == UpdateMode.Start) {
UpdateColliders();
}
}
private void FixedUpdate() {
if (_updateMode == UpdateMode.FixedUpdate) {
UpdateColliders();
}
}
private void UpdateColliders() {
Vector3 position = transform.position;
Vector3 extents = transform.lossyScale * _boxcastScaleMultiplier * 0.5f;
extents.z = 0.1f;
Quaternion rotation = transform.rotation;
Vector3 direction = transform.forward;
float distance = _boxcastDistance;
RaycastHit[] hits = Physics.BoxCastAll(position, extents, direction, rotation, distance, _layerMask, QueryTriggerInteraction.Ignore);
_portal.IgnoredColliders = hits.Select(hit => hit.collider).ToArray();
}
}
| 412 | 0.789784 | 1 | 0.789784 | game-dev | MEDIA | 0.862556 | game-dev | 0.967914 | 1 | 0.967914 |
Roblox/focus-navigation | 2,712 | modules/input-handlers/src/__tests__/onRelease.spec.lua | --!strict
local Packages = script.Parent.Parent.Parent
local JestGlobals = require(Packages.Dev.JestGlobals)
local jest = JestGlobals.jest
local it = JestGlobals.it
local beforeEach = JestGlobals.beforeEach
local expect = JestGlobals.expect
local EventPropagationService = require(Packages.Dev.EventPropagation)
local makeMockEvent = require(script.Parent.makeMockEvent)
local onRelease = require(script.Parent.Parent.onRelease)
local targetInstance, eventPropagationService
beforeEach(function()
targetInstance = Instance.new("TextButton")
eventPropagationService = EventPropagationService.new()
end)
it("should fire after press and release", function()
local callback = jest.fn()
eventPropagationService:registerEventHandler(targetInstance, "event", onRelease(callback))
eventPropagationService:propagateEvent(targetInstance, "event", makeMockEvent(Enum.UserInputState.Begin), false)
expect(callback).toHaveBeenCalledTimes(0)
eventPropagationService:propagateEvent(targetInstance, "event", makeMockEvent(Enum.UserInputState.End), false)
expect(callback).toHaveBeenCalledTimes(1)
expect(callback).toHaveBeenCalledWith(expect.objectContaining({
eventData = expect.objectContaining({
UserInputState = Enum.UserInputState.End,
}),
}))
end)
it("should fire after multiple presses and releases", function()
local callback = jest.fn()
eventPropagationService:registerEventHandler(targetInstance, "event", onRelease(callback))
eventPropagationService:propagateEvent(targetInstance, "event", makeMockEvent(Enum.UserInputState.Begin), false)
eventPropagationService:propagateEvent(targetInstance, "event", makeMockEvent(Enum.UserInputState.End), false)
eventPropagationService:propagateEvent(targetInstance, "event", makeMockEvent(Enum.UserInputState.Begin), false)
eventPropagationService:propagateEvent(targetInstance, "event", makeMockEvent(Enum.UserInputState.End), false)
expect(callback).toHaveBeenCalledTimes(2)
end)
it("should not fire with only a release", function()
local callback = jest.fn()
eventPropagationService:registerEventHandler(targetInstance, "event", onRelease(callback))
eventPropagationService:propagateEvent(targetInstance, "event", makeMockEvent(Enum.UserInputState.End), false)
expect(callback).toHaveBeenCalledTimes(0)
eventPropagationService:propagateEvent(targetInstance, "event", makeMockEvent(Enum.UserInputState.Begin), false)
eventPropagationService:propagateEvent(targetInstance, "event", makeMockEvent(Enum.UserInputState.End), false)
expect(callback).toHaveBeenCalledTimes(1)
eventPropagationService:propagateEvent(targetInstance, "event", makeMockEvent(Enum.UserInputState.End), false)
expect(callback).toHaveBeenCalledTimes(1)
end)
| 412 | 0.82349 | 1 | 0.82349 | game-dev | MEDIA | 0.732485 | game-dev | 0.800627 | 1 | 0.800627 |
Reinisch/Darkest-Dungeon-Unity | 3,477 | Assets/Scripts/UI/Slots/BattleCampingSlot.cs | using System;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class BattleCampingSlot : MonoBehaviour, IPointerClickHandler, IPointerEnterHandler, IPointerExitHandler
{
[SerializeField]
private Image skillIcon;
[SerializeField]
private Image selectorIcon;
public CampingSkill Skill { get; private set; }
public bool Selected { get; private set; }
public bool IsEmpty { get; private set; }
private RectTransform RectTransform { get; set; }
private bool Available { get; set; }
private bool Selectable { get; set; }
private bool Deselectable { get; set; }
public event Action<BattleCampingSlot> EventSkillSelected;
public event Action<BattleCampingSlot> EventSkillDeselected;
private void Awake()
{
RectTransform = GetComponent<RectTransform>();
}
public void Select()
{
Selected = true;
selectorIcon.enabled = true;
if (EventSkillSelected != null)
EventSkillSelected(this);
}
public void Deselect(bool clearDeselect = false)
{
Selected = false;
selectorIcon.enabled = false;
if(!clearDeselect)
if (EventSkillDeselected != null)
EventSkillDeselected(this);
}
public void SetCombatState()
{
skillIcon.enabled = true;
skillIcon.material = skillIcon.defaultMaterial;
Available = true;
Selectable = true;
Deselectable = true;
IsEmpty = false;
}
public void SetDisabledState()
{
selectorIcon.enabled = false;
skillIcon.enabled = true;
skillIcon.material = DarkestDungeonManager.FullGrayDarkMaterial;
Available = false;
Selected = false;
Selectable = false;
Deselectable = false;
IsEmpty = false;
}
public void SetEmptyState()
{
Skill = null;
selectorIcon.enabled = false;
skillIcon.enabled = false;
Selectable = false;
Deselectable = false;
Selected = false;
Available = false;
IsEmpty = true;
}
public void UpdateSkill(Hero hero, CampingSkill campingSkill)
{
Skill = campingSkill;
if (hero.SelectedCampingSkills.Contains(campingSkill))
{
skillIcon.sprite = DarkestDungeonManager.Data.Sprites["camp_skill_" + Skill.Id];
SetDisabledState();
}
else
ResetSkill();
}
public void ResetSkill()
{
SetEmptyState();
}
public void OnPointerClick(PointerEventData eventData)
{
if (RaidSceneManager.RaidEvents.CampEvent.ActionType != CampUsageResultType.Wait)
return;
if (!Available)
return;
if (Selected && Deselectable)
Deselect();
else if (!Selected && Selectable)
Select();
}
public void OnPointerEnter(PointerEventData eventData)
{
skillIcon.material = !Available ? DarkestDungeonManager.GrayMaterial : DarkestDungeonManager.HighlightMaterial;
if (Skill != null)
ToolTipManager.Instanse.Show(Skill.Tooltip(), RectTransform, ToolTipStyle.FromTop, ToolTipSize.Normal);
}
public void OnPointerExit(PointerEventData eventData)
{
skillIcon.material = !Available ? DarkestDungeonManager.FullGrayDarkMaterial : skillIcon.defaultMaterial;
ToolTipManager.Instanse.Hide();
}
} | 412 | 0.855487 | 1 | 0.855487 | game-dev | MEDIA | 0.963735 | game-dev | 0.712547 | 1 | 0.712547 |
L-Sun/HitagiEngine | 17,595 | hitagi/ecs/test/ecs_test.cpp | #include <hitagi/math/transform.hpp>
#include <hitagi/ecs/world.hpp>
#include <hitagi/ecs/entity.hpp>
#include <hitagi/ecs/schedule.hpp>
#include <hitagi/utils/test.hpp>
#include <range/v3/view/zip.hpp>
#include <spdlog/spdlog.h>
using namespace hitagi::ecs;
using namespace hitagi::math;
template <Component T, typename V>
auto component_value_eq(const char* expr_entity, const char*, Entity entity, const V& value) -> ::testing::AssertionResult {
static_assert(std::is_same_v<decltype(T::value), V>);
if (auto component_value = entity.Get<T>().value; component_value == value) {
return ::testing::AssertionSuccess();
} else {
return ::testing::AssertionFailure() << fmt::format("Expect component value of {} is {}, but actual is {}", expr_entity, value, component_value);
}
}
#define EXPECT_COMPONENT_EQ(_entity, _component, _value) \
EXPECT_PRED_FORMAT2(component_value_eq<_component>, _entity, _value)
auto dynamic_component_value_eq(const char* expr_entity,
const char* expr_dynamic_component,
const char*,
Entity entity,
std::string_view dynamic_component,
int value) -> ::testing::AssertionResult {
auto component = entity.Get(dynamic_component);
if (component) {
if (auto component_value = *reinterpret_cast<int*>(component); component_value == value) {
return ::testing::AssertionSuccess();
} else {
return ::testing::AssertionFailure() << fmt::format("Expect component value of entity({}) is {}, but actual is {}", expr_entity, value, component_value);
}
} else {
return testing::AssertionFailure() << fmt::format("The Entity({}) does not have component({})\n", expr_entity, expr_dynamic_component);
}
}
#define EXPECT_DYNAMIC_COMPONENT_EQ(_entity, _dynamic_component, _value) \
EXPECT_PRED_FORMAT3(dynamic_component_value_eq, _entity, _dynamic_component, _value)
struct Component_1 {
int value = 1;
};
struct Component_2 {
int value = 2;
};
struct Component_3 {
int value = 3;
};
struct ContainerComponent {
std::string value;
};
class EcsTest : public ::testing::Test {
public:
EcsTest()
: world(::testing::UnitTest::GetInstance()->current_test_info()->name()),
em(world.GetEntityManager()),
sm(world.GetSystemManager()) {}
World world;
EntityManager& em;
SystemManager& sm;
};
TEST_F(EcsTest, CreateEntity) {
const auto entity = em.Create();
EXPECT_TRUE(entity.Valid());
EXPECT_TRUE(em.Has(entity));
}
TEST_F(EcsTest, CreateManyEntities) {
const auto entities = em.CreateMany(100);
for (const auto entity : entities) {
EXPECT_TRUE(entity.Valid());
EXPECT_TRUE(em.Has(entity));
}
}
TEST_F(EcsTest, CreateManyEntitiesWithComponent) {
em.RegisterDynamicComponent({
.name = "DynamicComponent",
.size = sizeof(int),
.default_constructor = [&](std::byte* data) { *reinterpret_cast<int*>(data) = 1; },
.destructor = [&](std::byte* data) { *reinterpret_cast<int*>(data) = 0; },
});
const auto entities = em.CreateMany<Component_1, Component_2>(100, {"DynamicComponent"});
for (const auto entity : entities) {
EXPECT_TRUE(entity.Valid());
EXPECT_TRUE(em.Has(entity));
EXPECT_COMPONENT_EQ(entity, Component_1, 1);
EXPECT_COMPONENT_EQ(entity, Component_2, 2);
EXPECT_DYNAMIC_COMPONENT_EQ(entity, "DynamicComponent", 1);
}
}
TEST_F(EcsTest, DestroyEntity) {
auto entity = em.Create();
em.Destroy(entity);
EXPECT_FALSE(entity.Valid());
EXPECT_FALSE(em.Has(entity));
}
TEST_F(EcsTest, DestroyRepeatedly) {
auto entity = em.Create();
EXPECT_TRUE(entity);
EXPECT_EQ(em.NumEntities(), 1);
em.Destroy(entity);
EXPECT_EQ(em.NumEntities(), 0);
EXPECT_FALSE(entity.Valid());
EXPECT_THROW(em.Destroy(entity), std::out_of_range);
}
TEST_F(EcsTest, DestroyNonExistentEntity) {
Entity invalid_entity{};
EXPECT_THROW(em.Destroy(invalid_entity), std::out_of_range);
}
TEST_F(EcsTest, AddComponent) {
em.RegisterDynamicComponent({
.name = "DynamicComponent",
.size = sizeof(int),
.default_constructor = [&](std::byte* data) { *reinterpret_cast<int*>(data) = 1; },
.destructor = [&](std::byte* data) { *reinterpret_cast<int*>(data) = 0; },
});
auto entity = em.Create();
entity.Emplace<Component_1>();
entity.Emplace<Component_2>();
entity.Emplace<Component_3>();
entity.Add("DynamicComponent");
EXPECT_COMPONENT_EQ(entity, Component_1, 1);
EXPECT_COMPONENT_EQ(entity, Component_2, 2);
EXPECT_COMPONENT_EQ(entity, Component_3, 3);
EXPECT_DYNAMIC_COMPONENT_EQ(entity, "DynamicComponent", 1);
}
TEST_F(EcsTest, AddExistedComponent) {
auto entity = em.Create();
entity.Emplace<Component_1>().value = 2;
entity.Emplace<Component_1>();
EXPECT_COMPONENT_EQ(entity, Component_1, 2) << "The old component should not be replaced";
}
TEST_F(EcsTest, AddComponentKeepOldComponent) {
struct PointToSelfComponent {
PointToSelfComponent() : self(this) {}
PointToSelfComponent(const PointToSelfComponent&) : self(this) {}
PointToSelfComponent(PointToSelfComponent&&) noexcept : self(this) {}
PointToSelfComponent& operator=(const PointToSelfComponent&) { return *this; }
PointToSelfComponent& operator=(const PointToSelfComponent&&) noexcept { return *this; }
~PointToSelfComponent() { self = nullptr; }
bool IsValid() const noexcept { return self == this; }
PointToSelfComponent* self = nullptr;
};
auto entity = em.Create();
entity.Emplace<PointToSelfComponent>();
entity.Emplace<Component_1>();
EXPECT_TRUE(entity.Has<PointToSelfComponent>());
EXPECT_TRUE(entity.Has<Component_1>());
EXPECT_TRUE(entity.Get<PointToSelfComponent>().IsValid());
auto entity_2 = em.Create();
entity_2.Emplace<ContainerComponent>().value = "test";
entity_2.Emplace<Component_1>();
EXPECT_STREQ(entity_2.Get<ContainerComponent>().value.c_str(), "test");
}
TEST_F(EcsTest, GetComponent) {
auto entity = em.Create();
entity.Emplace<Component_1>();
ASSERT_TRUE(entity.Has<Entity>()) << "any entity should always have Entity component";
EXPECT_EQ(entity.Get<Entity>(), entity) << "Entity component should always be the entity itself";
}
TEST_F(EcsTest, GetNotExistedComponent) {
auto entity = em.Create();
EXPECT_FALSE(entity.Has<Component_1>());
}
TEST_F(EcsTest, ModifyComponent) {
auto entity = em.Create();
entity.Emplace<Component_1>().value = 1;
EXPECT_COMPONENT_EQ(entity, Component_1, 1);
entity.Get<Component_1>().value = 2;
EXPECT_COMPONENT_EQ(entity, Component_1, 2);
em.RegisterDynamicComponent({
.name = "DynamicComponent",
.size = sizeof(int),
.default_constructor = [&](std::byte* data) { *reinterpret_cast<int*>(data) = 2; },
.destructor = [&](std::byte* data) { *reinterpret_cast<int*>(data) = 0; },
});
entity.Add("DynamicComponent");
EXPECT_DYNAMIC_COMPONENT_EQ(entity, "DynamicComponent", 2);
}
TEST_F(EcsTest, RemoveComponent) {
bool is_destructed = false;
em.RegisterDynamicComponent({
.name = "DynamicComponent",
.size = sizeof(int),
.destructor = [&](std::byte*) { is_destructed = true; },
});
auto entity = em.Create();
entity.Emplace<Component_1>();
entity.Add("DynamicComponent");
entity.Remove<Component_1>();
entity.Remove("DynamicComponent");
EXPECT_FALSE(entity.Has<Component_1>());
EXPECT_FALSE(entity.Has("DynamicComponent"));
EXPECT_TRUE(is_destructed);
}
TEST_F(EcsTest, DestructComponentAfterWorldDestroyed) {
bool is_destructed = false;
{
World _world("DestructComponentAfterWorldDestroyed");
_world.GetEntityManager().RegisterDynamicComponent({
.name = "DynamicComponent",
.size = sizeof(int),
.destructor = [&](std::byte*) { is_destructed = true; },
});
auto entity = _world.GetEntityManager().Create();
entity.Add("DynamicComponent");
}
EXPECT_TRUE(is_destructed);
}
TEST_F(EcsTest, RemoveNotExistedComponent) {
auto entity = em.Create();
EXPECT_NO_THROW(entity.Remove<Component_1>());
}
TEST_F(EcsTest, Register) {
struct System {};
sm.Register<System>();
}
TEST_F(EcsTest, RegisterSystemTwice) {
static unsigned register_counter = 0;
struct System {
static void OnCreate(World&) { register_counter++; }
};
sm.Register<System>();
sm.Register<System>();
EXPECT_EQ(register_counter, 1);
}
TEST_F(EcsTest, Unregister) {
static bool is_unregistered = false;
struct System {
static void OnDestroy(World&) { is_unregistered = true; }
};
sm.Register<System>();
sm.Unregister<System>();
EXPECT_TRUE(is_unregistered);
}
TEST_F(EcsTest, UnregisterSystemTwice) {
static unsigned unregister_counter = 0;
struct System {
static void OnDestroy(World&) { unregister_counter++; }
};
sm.Register<System>();
sm.Unregister<System>();
sm.Unregister<System>();
EXPECT_EQ(unregister_counter, 1);
}
TEST_F(EcsTest, AutoUnregisterSystemAfterWorldDestroyed) {
static bool is_unregistered = false;
struct System {
static void OnDestroy(World&) { is_unregistered = true; }
};
{
World _world("AutoUnregisterSystemAfterWorldDestroyed");
_world.GetSystemManager().Register<System>();
}
EXPECT_TRUE(is_unregistered);
}
TEST_F(EcsTest, SystemUpdate) {
em.RegisterDynamicComponent({
.name = "DynamicComponent",
.size = sizeof(int),
.default_constructor = [&](std::byte* data) { *reinterpret_cast<int*>(data) = 1; },
.destructor = [&](std::byte* data) { *reinterpret_cast<int*>(data) = 0; },
});
static std::vector<Entity> invoked_entities;
struct System {
static void OnUpdate(Schedule& schedule) {
schedule.Request(
"ImplicitFilterAll", [&](Entity e, LastFrame<Component_1> c1, Component_2& c2, std::byte* c3) {
invoked_entities.emplace_back(e);
c2.value = 200;
*reinterpret_cast<int*>(c3) = 300;
},
{"DynamicComponent"});
}
};
auto entity_1 = em.Create();
entity_1.Emplace<Component_1>();
auto entity_2 = em.Create();
entity_2.Emplace<Component_1>();
entity_2.Emplace<Component_2>();
auto entities_with_both = em.CreateMany<Component_1, Component_2>(100, {"DynamicComponent"});
sm.Register<System>();
world.Update();
ASSERT_EQ(invoked_entities.size(), entities_with_both.size());
for (auto [invoked_entity, entity] : ranges::views::zip(invoked_entities, entities_with_both)) {
EXPECT_EQ(invoked_entity, entity);
EXPECT_COMPONENT_EQ(entity, Component_1, 1);
EXPECT_COMPONENT_EQ(entity, Component_2, 200);
EXPECT_DYNAMIC_COMPONENT_EQ(entity, "DynamicComponent", 300);
}
}
TEST_F(EcsTest, SystemUpdateWithNoEntities) {
em.RegisterDynamicComponent({
.name = "DynamicComponent",
.size = sizeof(int),
.default_constructor = [&](std::byte* data) { *reinterpret_cast<int*>(data) = 1; },
.destructor = [&](std::byte* data) { *reinterpret_cast<int*>(data) = 0; },
});
static bool invoked = false;
struct System {
static void OnUpdate(Schedule& schedule) {
schedule.Request(
"ImplicitFilterAll", [&](Entity, LastFrame<Component_1>, Component_2&, std::byte*) {
invoked = true;
},
{"DynamicComponent"});
}
};
sm.Register<System>();
world.Update();
EXPECT_FALSE(invoked);
}
TEST_F(EcsTest, SystemUpdateOrder) {
static std::pmr::vector<std::size_t> order;
std::pmr::vector<std::size_t> expected_order{1, 2, 3, 4};
struct System {
static void OnUpdate(Schedule& schedule) {
schedule
.Request(
"Fn2",
[&](Component_1&) {
order.emplace_back(2);
})
.Request(
"Fn4",
[&](const Component_1&) {
order.emplace_back(4);
})
.Request(
"Fn3",
[&](Component_1&) {
order.emplace_back(3);
})
.Request(
"Fn1",
[&](LastFrame<Component_1>) {
order.emplace_back(1);
});
}
};
em.Create().Emplace<Component_1>();
sm.Register<System>();
world.Update();
EXPECT_EQ(order.size(), 4);
EXPECT_EQ(order, expected_order)
<< "The execution order of a request component is following"
<< "1(ReadBeforWrite). Execute parallel all function request with LastFrame<Component>"
<< "2(Write). Execute all function request with Component sequentially in the order of requesting"
<< "3(ReadAfterWrite). Execute parallel all function request with const Component&";
}
TEST_F(EcsTest, SystemUpdateInCustomOrder) {
static std::pmr::vector<std::size_t> order;
std::pmr::vector<std::size_t> expected_order{2, 1};
struct System {
static void OnUpdate(Schedule& schedule) {
schedule.SetOrder("Fn2", "Fn1");
schedule
.Request("Fn1", [&](Component_1) {
order.emplace_back(1);
})
.Request("Fn2", [&](Component_1) {
order.emplace_back(2);
});
}
};
em.Create().Emplace<Component_1>();
sm.Register<System>();
world.Update();
EXPECT_EQ(order, expected_order);
}
TEST_F(EcsTest, SystemFilterAll) {
struct System {
static void OnUpdate(Schedule& schedule) {
schedule.Request(
"FilterAll",
[&](Entity entity) {
entity.Get<Component_1>().value = 10;
entity.Get<Component_2>().value = 20;
},
{},
filter::All<Component_1, Component_2>());
}
};
auto entity_with_one = em.Create();
entity_with_one.Emplace<Component_1>();
auto entity_with_both = em.Create();
entity_with_both.Emplace<Component_1>();
entity_with_both.Emplace<Component_2>();
sm.Register<System>();
world.Update();
EXPECT_COMPONENT_EQ(entity_with_one, Component_1, 1) << "Component_1 should not be updated";
EXPECT_COMPONENT_EQ(entity_with_both, Component_1, 10) << "Component_1 should be updated";
EXPECT_COMPONENT_EQ(entity_with_both, Component_2, 20) << "Component_2 should be updated";
}
TEST_F(EcsTest, SystemFilterAny) {
struct System {
static void OnUpdate(Schedule& schedule) {
schedule.Request(
"FilterAny",
[&](Entity entity) {
if (entity.Has<Component_1>())
entity.Get<Component_1>().value = 100;
if (entity.Has<Component_2>())
entity.Get<Component_2>().value = 200;
},
{},
filter::Any<Component_1, Component_2>());
}
};
auto entity_with_first = em.Create();
entity_with_first.Emplace<Component_1>();
auto entity_with_second = em.Create();
entity_with_second.Emplace<Component_2>();
auto entity_with_third = em.Create();
entity_with_third.Emplace<Component_3>();
sm.Register<System>();
world.Update();
EXPECT_COMPONENT_EQ(entity_with_first, Component_1, 100) << "Component_1 should be updated";
EXPECT_COMPONENT_EQ(entity_with_second, Component_2, 200) << "Component_2 should be updated";
EXPECT_COMPONENT_EQ(entity_with_third, Component_3, 3) << "Component_3 should not be updated";
}
TEST_F(EcsTest, SystemFilterNone) {
struct System {
static void OnUpdate(Schedule& schedule) {
schedule.Request(
"FilterNone",
[](Component_1& c1) {
c1.value = 100;
},
{},
filter::None<Component_2>());
}
};
auto entity_with_one = em.Create();
entity_with_one.Emplace<Component_1>();
auto entity_with_both = em.Create();
entity_with_both.Emplace<Component_1>();
entity_with_both.Emplace<Component_2>();
sm.Register<System>();
world.Update();
EXPECT_COMPONENT_EQ(entity_with_one, Component_1, 100) << "Component_1 should be updated";
EXPECT_COMPONENT_EQ(entity_with_both, Component_1, 1) << "Component_1 should not be updated";
}
int main(int argc, char** argv) {
spdlog::set_level(spdlog::level::debug);
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} | 412 | 0.912458 | 1 | 0.912458 | game-dev | MEDIA | 0.896536 | game-dev | 0.535083 | 1 | 0.535083 |
geange/lucene-go | 2,211 | core/util/packed/deltapackedlongvalues.go | package packed
import "slices"
type DeltaPackedLongValues struct {
*PackedLongValues
mins []int64
}
func NewDeltaPackedLongValues(pageShift int, pageMask uint64, values []Reader, mins []int64, size int) *DeltaPackedLongValues {
return &DeltaPackedLongValues{
PackedLongValues: NewPackedLongValues(values, pageShift, pageMask, size),
mins: mins,
}
}
func (d *DeltaPackedLongValues) Get(index int) (uint64, error) {
return d.getWithFnGet(index, d.get)
}
func (d *DeltaPackedLongValues) get(block int, element int) (uint64, error) {
value, err := d.values[block].Get(element)
if err != nil {
return 0, err
}
return uint64(d.mins[block] + int64(value)), nil
}
func (d *DeltaPackedLongValues) Iterator() PackedLongValuesIterator {
return d.iteratorWithSPI(d)
}
type DeltaPackedLongValuesBuilder struct {
*PackedLongValuesBuilder
mins []int64
}
func NewDeltaPackedLongValuesBuilder(pageSize int, acceptableOverheadRatio float64) *DeltaPackedLongValuesBuilder {
return &DeltaPackedLongValuesBuilder{
PackedLongValuesBuilder: NewPackedLongValuesBuilder(pageSize, acceptableOverheadRatio),
mins: make([]int64, 0),
}
}
func (d *DeltaPackedLongValuesBuilder) Add(value int64) error {
return d.addWithFnPack(value, d.pack)
}
func (d *DeltaPackedLongValuesBuilder) finish() error {
return d.finishWithFnPack(d.pack)
}
func (d *DeltaPackedLongValuesBuilder) pack() error {
return d.packWithFnPackValues(d.packValues)
}
func (d *DeltaPackedLongValuesBuilder) packValues(values []int64, numValues int, acceptableOverheadRatio float64) error {
var minValue int64
for _, v := range values {
minValue = min(minValue, v)
}
for i := range values {
values[i] -= minValue
}
if err := d.PackedLongValuesBuilder.packValues(values, numValues, acceptableOverheadRatio); err != nil {
return err
}
d.mins = append(d.mins, minValue)
return nil
}
func (d *DeltaPackedLongValuesBuilder) Build() (*DeltaPackedLongValues, error) {
if err := d.finish(); err != nil {
return nil, err
}
d.pending = nil
values := slices.Clone(d.values)
mins := slices.Clone(d.mins)
return NewDeltaPackedLongValues(d.pageShift, d.pageMask, values, mins, d.size), nil
}
| 412 | 0.751094 | 1 | 0.751094 | game-dev | MEDIA | 0.45872 | game-dev | 0.724578 | 1 | 0.724578 |
AirFoundation/Naven-NoAuth | 6,257 | src/main/java/net/minecraft/world/gen/feature/WorldGenLakes.java | package net.minecraft.world.gen.feature;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.init.Blocks;
import net.minecraft.util.BlockPos;
import net.minecraft.world.EnumSkyBlock;
import net.minecraft.world.World;
import net.minecraft.world.biome.BiomeGenBase;
import java.util.Random;
public class WorldGenLakes extends WorldGenerator {
private final Block block;
public WorldGenLakes(Block blockIn) {
this.block = blockIn;
}
public boolean generate(World worldIn, Random rand, BlockPos position) {
for (position = position.add(-8, 0, -8); position.getY() > 5 && worldIn.isAirBlock(position); position = position.down()) {
}
if (position.getY() <= 4) {
return false;
} else {
position = position.down(4);
boolean[] aboolean = new boolean[2048];
int i = rand.nextInt(4) + 4;
for (int j = 0; j < i; ++j) {
double d0 = rand.nextDouble() * 6.0D + 3.0D;
double d1 = rand.nextDouble() * 4.0D + 2.0D;
double d2 = rand.nextDouble() * 6.0D + 3.0D;
double d3 = rand.nextDouble() * (16.0D - d0 - 2.0D) + 1.0D + d0 / 2.0D;
double d4 = rand.nextDouble() * (8.0D - d1 - 4.0D) + 2.0D + d1 / 2.0D;
double d5 = rand.nextDouble() * (16.0D - d2 - 2.0D) + 1.0D + d2 / 2.0D;
for (int l = 1; l < 15; ++l) {
for (int i1 = 1; i1 < 15; ++i1) {
for (int j1 = 1; j1 < 7; ++j1) {
double d6 = ((double) l - d3) / (d0 / 2.0D);
double d7 = ((double) j1 - d4) / (d1 / 2.0D);
double d8 = ((double) i1 - d5) / (d2 / 2.0D);
double d9 = d6 * d6 + d7 * d7 + d8 * d8;
if (d9 < 1.0D) {
aboolean[(l * 16 + i1) * 8 + j1] = true;
}
}
}
}
}
for (int k1 = 0; k1 < 16; ++k1) {
for (int l2 = 0; l2 < 16; ++l2) {
for (int k = 0; k < 8; ++k) {
boolean flag = !aboolean[(k1 * 16 + l2) * 8 + k] && (k1 < 15 && aboolean[((k1 + 1) * 16 + l2) * 8 + k] || k1 > 0 && aboolean[((k1 - 1) * 16 + l2) * 8 + k] || l2 < 15 && aboolean[(k1 * 16 + l2 + 1) * 8 + k] || l2 > 0 && aboolean[(k1 * 16 + (l2 - 1)) * 8 + k] || k < 7 && aboolean[(k1 * 16 + l2) * 8 + k + 1] || k > 0 && aboolean[(k1 * 16 + l2) * 8 + (k - 1)]);
if (flag) {
Material material = worldIn.getBlockState(position.add(k1, k, l2)).getBlock().getMaterial();
if (k >= 4 && material.isLiquid()) {
return false;
}
if (k < 4 && !material.isSolid() && worldIn.getBlockState(position.add(k1, k, l2)).getBlock() != this.block) {
return false;
}
}
}
}
}
for (int l1 = 0; l1 < 16; ++l1) {
for (int i3 = 0; i3 < 16; ++i3) {
for (int i4 = 0; i4 < 8; ++i4) {
if (aboolean[(l1 * 16 + i3) * 8 + i4]) {
worldIn.setBlockState(position.add(l1, i4, i3), i4 >= 4 ? Blocks.air.getDefaultState() : this.block.getDefaultState(), 2);
}
}
}
}
for (int i2 = 0; i2 < 16; ++i2) {
for (int j3 = 0; j3 < 16; ++j3) {
for (int j4 = 4; j4 < 8; ++j4) {
if (aboolean[(i2 * 16 + j3) * 8 + j4]) {
BlockPos blockpos = position.add(i2, j4 - 1, j3);
if (worldIn.getBlockState(blockpos).getBlock() == Blocks.dirt && worldIn.getLightFor(EnumSkyBlock.SKY, position.add(i2, j4, j3)) > 0) {
BiomeGenBase biomegenbase = worldIn.getBiomeGenForCoords(blockpos);
if (biomegenbase.topBlock.getBlock() == Blocks.mycelium) {
worldIn.setBlockState(blockpos, Blocks.mycelium.getDefaultState(), 2);
} else {
worldIn.setBlockState(blockpos, Blocks.grass.getDefaultState(), 2);
}
}
}
}
}
}
if (this.block.getMaterial() == Material.lava) {
for (int j2 = 0; j2 < 16; ++j2) {
for (int k3 = 0; k3 < 16; ++k3) {
for (int k4 = 0; k4 < 8; ++k4) {
boolean flag1 = !aboolean[(j2 * 16 + k3) * 8 + k4] && (j2 < 15 && aboolean[((j2 + 1) * 16 + k3) * 8 + k4] || j2 > 0 && aboolean[((j2 - 1) * 16 + k3) * 8 + k4] || k3 < 15 && aboolean[(j2 * 16 + k3 + 1) * 8 + k4] || k3 > 0 && aboolean[(j2 * 16 + (k3 - 1)) * 8 + k4] || k4 < 7 && aboolean[(j2 * 16 + k3) * 8 + k4 + 1] || k4 > 0 && aboolean[(j2 * 16 + k3) * 8 + (k4 - 1)]);
if (flag1 && (k4 < 4 || rand.nextInt(2) != 0) && worldIn.getBlockState(position.add(j2, k4, k3)).getBlock().getMaterial().isSolid()) {
worldIn.setBlockState(position.add(j2, k4, k3), Blocks.stone.getDefaultState(), 2);
}
}
}
}
}
if (this.block.getMaterial() == Material.water) {
for (int k2 = 0; k2 < 16; ++k2) {
for (int l3 = 0; l3 < 16; ++l3) {
int l4 = 4;
if (worldIn.canBlockFreezeWater(position.add(k2, l4, l3))) {
worldIn.setBlockState(position.add(k2, l4, l3), Blocks.ice.getDefaultState(), 2);
}
}
}
}
return true;
}
}
}
| 412 | 0.793713 | 1 | 0.793713 | game-dev | MEDIA | 0.653148 | game-dev | 0.987657 | 1 | 0.987657 |
OvercastNetwork/ProjectAres | 8,923 | PGM/src/main/java/tc/oc/pgm/match/MatchManager.java | package tc.oc.pgm.match;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
import javax.annotation.Nullable;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Provider;
import javax.inject.Singleton;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.World;
import org.bukkit.configuration.Configuration;
import org.bukkit.event.EventBus;
import tc.oc.api.util.Permissions;
import tc.oc.commons.core.logging.Loggers;
import tc.oc.pgm.development.MapErrorTracker;
import tc.oc.pgm.events.SetNextMapEvent;
import tc.oc.pgm.map.MapLibrary;
import tc.oc.pgm.map.MapLoader;
import tc.oc.pgm.map.MapNotFoundException;
import tc.oc.pgm.map.PGMMap;
import tc.oc.pgm.rotation.FileRotationProviderFactory;
import tc.oc.pgm.rotation.RotationManager;
import tc.oc.pgm.rotation.RotationState;
@Singleton
public class MatchManager implements MatchFinder {
// Maximum randomly selected maps to attempt to load from the library before giving up
private static final int MAX_CYCLE_TRIES = 10;
private final Logger log;
private final Path pluginDataFolder;
private final Provider<Configuration> config;
private final MapLibrary mapLibrary;
private final MapLoader mapLoader;
private final MapErrorTracker mapErrorTracker;
private final FileRotationProviderFactory fileRotationProviderFactory;
private final EventBus eventBus;
private final MatchLoader matchLoader;
private @Nullable RotationManager rotationManager;
/** Custom set next map. */
private PGMMap nextMap = null;
/**
* Creates a new map manager with a specified map rotation.
*/
@Inject MatchManager(Loggers loggers,
@Named("pluginData") Path pluginDataFolder,
Provider<Configuration> config,
MapLibrary mapLibrary,
MapLoader mapLoader,
MapErrorTracker mapErrorTracker,
FileRotationProviderFactory fileRotationProviderFactory,
EventBus eventBus,
MatchLoader matchLoader) throws MapNotFoundException {
this.pluginDataFolder = pluginDataFolder;
this.mapErrorTracker = mapErrorTracker;
this.fileRotationProviderFactory = fileRotationProviderFactory;
this.log = loggers.get(getClass());
this.config = config;
this.mapLibrary = mapLibrary;
this.mapLoader = mapLoader;
this.eventBus = eventBus;
this.matchLoader = matchLoader;
}
@Override
public Map<World, Match> matchesByWorld() {
return matchLoader.matchesByWorld();
}
/** Gets the currently loaded maps. */
public Collection<PGMMap> getMaps() {
return this.mapLibrary.getMaps();
}
public Set<PGMMap> loadNewMaps() throws MapNotFoundException {
log.info("Loading maps...");
Set<Path> added = new HashSet<>(),
updated = new HashSet<>(),
removed = new HashSet<>();
List<PGMMap> maps = mapLoader.loadNewMaps(mapLibrary.getMapsByPath(), added, updated, removed);
mapLibrary.removeMaps(removed);
Set<PGMMap> newMaps = mapLibrary.addMaps(maps);
mapLibrary.pushDirtyMaps();
log.info("Loaded " + newMaps.size() + " maps");
if(mapLibrary.getMaps().isEmpty()) {
throw new MapNotFoundException();
}
return newMaps;
}
public boolean loadRotations() {
return getRotationManager().load(mapLibrary.getMaps().iterator().next());
}
public Set<PGMMap> loadMapsAndRotations() throws MapNotFoundException {
Set<PGMMap> maps = loadNewMaps();
loadRotations();
return maps;
}
public RotationManager getRotationManager() {
if(rotationManager == null) {
rotationManager = new RotationManager(
log,
config.get(),
mapLibrary.getMaps().iterator().next(),
fileRotationProviderFactory.parse(
mapLibrary,
pluginDataFolder,
config.get()
)
);
}
return this.rotationManager;
}
/**
* Gets the next map that will be loaded at this point in time. If a map
* had been specified explicitly (setNextMap) that will be returned,
* otherwise the next map in the rotation will be returned.
*
* @return Next map that would be loaded at this point in time.
*/
public PGMMap getNextMap() {
if(this.nextMap == null) {
return this.getRotationManager().getRotation().getNext();
} else {
return this.nextMap;
}
}
/**
* @return the number of cycles before the rotation starts repeating
*/
public int cyclesBeforeRepeat() {
int size = getRotationManager().getRotation().getMaps().size();
if(nextMap != null) size++; // Extra map is available due to /setnext
return size;
}
private PGMMap advanceRotation() {
PGMMap currentMap;
if(nextMap == null) {
RotationState rotation = getRotationManager().getRotation();
currentMap = rotation.getNext();
rotation = rotation.skip(1);
getRotationManager().setRotation(rotation);
} else {
currentMap = nextMap;
this.nextMap = null;
}
eventBus.callEvent(new SetNextMapEvent(getNextMap()));
return currentMap;
}
/**
* Specified an explicit map for the next cycle.
*
* @param map to be loaded next.
*/
public void setNextMap(PGMMap map) {
if(map != nextMap) {
this.nextMap = map;
eventBus.callEvent(new SetNextMapEvent(map));
}
}
/**
* Cycle to the next map in the rotation
* @param oldMatch The current match, if any
* @param retryRotation Try every map in the rotation until one loads successfully
* @param retryLibrary Try every map in the library, after trying the entire rotation
* @return The new match, or null if no map could be loaded
*/
public @Nullable Match cycleToNext(@Nullable Match oldMatch, boolean retryRotation, boolean retryLibrary) {
// Match unload also does this, but doing it earlier avoids some problems.
// Specifically, RestartCountdown cannot cancel itself during a cycle.
if(oldMatch != null) {
oldMatch.countdowns().cancelAll();
}
Set<PGMMap> failed = new HashSet<>(); // Don't try any map more than once
// Try to load a rotation map
int maxCycles = cyclesBeforeRepeat();
for(int cycles = 0; cycles < maxCycles; cycles++) {
PGMMap map = advanceRotation();
if(!failed.contains(map)) {
Match match = cycleTo(oldMatch, map);
if(match != null) return match;
}
// If retryRotation is false, give up after the first failure
if(!retryRotation) return null;
failed.add(map);
}
// If all rotation maps failed, and we're not allowed to try non-rotation maps, give up
if(!retryLibrary) return null;
// Try every map in the library, in random order, to avoid getting stuck in a folder full of broken maps
final List<PGMMap> maps = new ArrayList<>(mapLibrary.getMaps());
maps.removeAll(failed);
Collections.shuffle(maps);
int tries = 0;
for(PGMMap map : maps) {
if(++tries >= MAX_CYCLE_TRIES) return null;
Match match = cycleTo(oldMatch, map);
if(match != null) return match;
failed.add(map);
}
return null;
}
private @Nullable Match cycleTo(@Nullable Match oldMatch, PGMMap map) {
try {
mapErrorTracker.clearErrors(map);
if(map.shouldReload()) {
Bukkit.broadcast(ChatColor.GREEN + "XML changes detected, reloading", Permissions.MAPERRORS);
mapLoader.loadMap(map);
mapLibrary.pushDirtyMaps();
}
return matchLoader.cycleTo(oldMatch, map);
} catch(MapNotFoundException e) {
// Maps are sometimes removed, must handle it gracefully
log.warning("Skipping deleted map " + map.getName());
try {
loadMapsAndRotations();
} catch(MapNotFoundException e2) {
log.severe("No maps could be loaded, server cannot cycle");
}
return null;
}
}
}
| 412 | 0.820477 | 1 | 0.820477 | game-dev | MEDIA | 0.203313 | game-dev | 0.794942 | 1 | 0.794942 |
BLACKujira/SekaiTools | 5,775 | SekaiTools/Assets/XCharts/Editor/Series/SerieBaseEditor.cs | using System;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using UnityEngine.Assertions;
using XCharts.Runtime;
namespace XCharts.Editor
{
public class SerieBaseEditor
{
internal BaseChart chart { get; private set; }
internal Serie serie { get; private set; }
//Editor m_Inspector;
internal SerializedProperty baseProperty;
internal SerializedProperty showProperty;
internal List<HeaderMenuInfo> menus = new List<HeaderMenuInfo>();
internal List<HeaderMenuInfo> serieDataMenus = new List<HeaderMenuInfo>();
protected Dictionary<string, Type> m_CoordOptionsDic;
protected List<string> m_CoordOptionsNames;
private string m_DisplayName;
internal void Init(BaseChart chart, Serie target, SerializedProperty property, UnityEditor.Editor inspector)
{
this.chart = chart;
this.serie = target;
this.baseProperty = property;
m_DisplayName = string.Format("Serie {0}: {1}", serie.index, serie.GetType().Name);
//m_Inspector = inspector;
showProperty = baseProperty.FindPropertyRelative("m_Show");
if (showProperty == null)
showProperty = baseProperty.FindPropertyRelative("m_Enable");
OnEnable();
if (serie.GetType().IsDefined(typeof(CoordOptionsAttribute), false))
{
var attribute = serie.GetType().GetAttribute<CoordOptionsAttribute>();
m_CoordOptionsDic = new Dictionary<string, Type>();
m_CoordOptionsNames = new List<string>();
if (attribute.type0 != null)
{
m_CoordOptionsDic[attribute.type0.Name] = attribute.type0;
m_CoordOptionsNames.Add(attribute.type0.Name);
}
if (attribute.type1 != null)
{
m_CoordOptionsDic[attribute.type1.Name] = attribute.type1;
m_CoordOptionsNames.Add(attribute.type1.Name);
}
if (attribute.type2 != null)
{
m_CoordOptionsDic[attribute.type2.Name] = attribute.type2;
m_CoordOptionsNames.Add(attribute.type2.Name);
}
if (attribute.type3 != null)
{
m_CoordOptionsDic[attribute.type3.Name] = attribute.type3;
m_CoordOptionsNames.Add(attribute.type3.Name);
}
}
}
public virtual void OnEnable()
{ }
public virtual void OnDisable()
{ }
internal void OnInternalInspectorGUI()
{
OnInspectorGUI();
EditorGUILayout.Space();
}
public virtual void OnInspectorGUI()
{ }
protected virtual void DrawExtendeds()
{ }
public virtual string GetDisplayTitle()
{
// var title = string.Format("serie {0}: {1}", serie.index, serie.GetType().Name);
// return ObjectNames.NicifyVariableName(title);
return m_DisplayName;
}
internal SerializedProperty FindProperty(string path)
{
return baseProperty.FindPropertyRelative(path);
}
protected SerializedProperty PropertyField(string path)
{
Assert.IsNotNull(path);
var property = FindProperty(path);
Assert.IsNotNull(property, "Can't find:" + path);
var title = ChartEditorHelper.GetContent(property.displayName);
PropertyField(property, title);
return property;
}
protected void PropertyField(SerializedProperty property)
{
Assert.IsNotNull(property);
var title = ChartEditorHelper.GetContent(property.displayName);
PropertyField(property, title);
}
protected void PropertyField(SerializedProperty property, GUIContent title)
{
EditorGUILayout.PropertyField(property, title);
}
protected void PropertyListField(string relativePropName, bool showOrder = true)
{
//TODO:
PropertyField(relativePropName);
}
protected void PropertyTwoFiled(string relativePropName)
{
var m_DrawRect = GUILayoutUtility.GetRect(1f, 17f);
var prop = FindProperty(relativePropName);
ChartEditorHelper.MakeTwoField(ref m_DrawRect, m_DrawRect.width, prop, prop.displayName);
}
protected void PropertyFieldLimitMin(string relativePropName, double min)
{
var prop = PropertyField(relativePropName);
switch (prop.propertyType)
{
case SerializedPropertyType.Float:
if (prop.floatValue < min)
prop.floatValue = (float) min;
break;
case SerializedPropertyType.Integer:
if (prop.intValue < min)
prop.intValue = (int) min;
break;
}
}
protected void PropertyFieldLimitMax(string relativePropName, int max)
{
var prop = PropertyField(relativePropName);
switch (prop.propertyType)
{
case SerializedPropertyType.Float:
if (prop.floatValue > max)
prop.floatValue = (float) max;
break;
case SerializedPropertyType.Integer:
if (prop.intValue > max)
prop.intValue = (int) max;
break;
}
}
}
} | 412 | 0.948689 | 1 | 0.948689 | game-dev | MEDIA | 0.713663 | game-dev | 0.995162 | 1 | 0.995162 |
MegaMek/megamek | 4,256 | megamek/src/megamek/common/autoResolve/acar/order/Orders.java | /*
* Copyright (C) 2025 The MegaMek Team. All Rights Reserved.
*
* This file is part of MegaMek.
*
* MegaMek is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License (GPL),
* version 3 or (at your option) any later version,
* as published by the Free Software Foundation.
*
* MegaMek 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.
*
* A copy of the GPL should have been included with this project;
* if not, see <https://www.gnu.org/licenses/>.
*
* NOTICE: The MegaMek organization is a non-profit group of volunteers
* creating free software for the BattleTech community.
*
* MechWarrior, BattleMech, `Mech and AeroTech are registered trademarks
* of The Topps Company, Inc. All Rights Reserved.
*
* Catalyst Game Labs and the Catalyst Game Labs logo are trademarks of
* InMediaRes Productions, LLC.
*
* MechWarrior Copyright Microsoft Corporation. MegaMek was created under
* Microsoft's "Game Content Usage Rules"
* <https://www.xbox.com/en-US/developers/rules> and it is not endorsed by or
* affiliated with Microsoft.
*/
package megamek.common.autoResolve.acar.order;
import java.util.Collection;
import java.util.Iterator;
import org.apache.commons.collections4.MultiValuedMap;
import org.apache.commons.collections4.multimap.HashSetValuedHashMap;
/**
* Orders is a collection of orders that are loaded into a game. This is used to give AI players access to strategic
* objectives for the game being played and be able to change its behavior based on the orders given.
*
* @author Luana Coppio
*/
public class Orders implements Collection<Order> {
private final MultiValuedMap<Integer, Order> ordersPerPlayer = new HashSetValuedHashMap<>();
public Collection<Order> getOrders(int playerId) {
return ordersPerPlayer.get(playerId);
}
public void resetOrders() {
ordersPerPlayer.values().forEach(Order::reset);
}
@Override
public int size() {
return ordersPerPlayer.size();
}
public boolean isEmpty() {
return ordersPerPlayer.isEmpty();
}
@Override
public boolean contains(Object o) {
if (o instanceof Order order) {
var orders = ordersPerPlayer.get(order.getOwnerId());
return orders != null && orders.contains(order);
}
return false;
}
@Override
public Iterator<Order> iterator() {
return ordersPerPlayer.values().iterator();
}
@Override
public Object[] toArray() {
return ordersPerPlayer.values().toArray();
}
@Override
public <T> T[] toArray(T[] a) {
return ordersPerPlayer.values().toArray(a);
}
@Override
public boolean add(Order order) {
return ordersPerPlayer.put(order.getOwnerId(), order);
}
@Override
public boolean remove(Object o) {
if (o instanceof Order order) {
return ordersPerPlayer.removeMapping(order.getOwnerId(), order);
}
return false;
}
@Override
public boolean containsAll(Collection<?> c) {
return ordersPerPlayer.values().containsAll(c);
}
@Override
public boolean addAll(Collection<? extends Order> c) {
var changed = false;
for (Order order : c) {
if (add(order)) {
changed = true;
}
}
return changed;
}
@Override
public boolean removeAll(Collection<?> c) {
var changed = false;
for (Object o : c) {
if (remove(o)) {
changed = true;
}
}
return changed;
}
@Override
public boolean retainAll(Collection<?> collection) {
var changed = false;
for (Order order : ordersPerPlayer.values()) {
if (!collection.contains(order)) {
if (remove(order)) {
changed = true;
}
}
}
return changed;
}
@Override
public void clear() {
ordersPerPlayer.clear();
}
}
| 412 | 0.786559 | 1 | 0.786559 | game-dev | MEDIA | 0.961873 | game-dev | 0.924892 | 1 | 0.924892 |
bastianleicht/badlion-src | 14,615 | com/ibm/icu/impl/LocaleIDParser.java | package com.ibm.icu.impl;
import com.ibm.icu.impl.LocaleIDs;
import com.ibm.icu.impl.locale.AsciiUtil;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
import java.util.Map.Entry;
public final class LocaleIDParser {
private char[] id;
private int index;
private StringBuilder buffer;
private boolean canonicalize;
private boolean hadCountry;
Map keywords;
String baseName;
private static final char KEYWORD_SEPARATOR = '@';
private static final char HYPHEN = '-';
private static final char KEYWORD_ASSIGN = '=';
private static final char COMMA = ',';
private static final char ITEM_SEPARATOR = ';';
private static final char DOT = '.';
private static final char UNDERSCORE = '_';
private static final char DONE = '\uffff';
public LocaleIDParser(String localeID) {
this(localeID, false);
}
public LocaleIDParser(String localeID, boolean canonicalize) {
this.id = localeID.toCharArray();
this.index = 0;
this.buffer = new StringBuilder(this.id.length + 5);
this.canonicalize = canonicalize;
}
private void reset() {
this.index = 0;
this.buffer = new StringBuilder(this.id.length + 5);
}
private void append(char c) {
this.buffer.append(c);
}
private void addSeparator() {
this.append('_');
}
private String getString(int start) {
return this.buffer.substring(start);
}
private void set(int pos, String s) {
this.buffer.delete(pos, this.buffer.length());
this.buffer.insert(pos, s);
}
private void append(String s) {
this.buffer.append(s);
}
private char next() {
if(this.index == this.id.length) {
++this.index;
return '\uffff';
} else {
return this.id[this.index++];
}
}
private void skipUntilTerminatorOrIDSeparator() {
while(!this.isTerminatorOrIDSeparator(this.next())) {
;
}
--this.index;
}
private boolean atTerminator() {
return this.index >= this.id.length || this.isTerminator(this.id[this.index]);
}
private boolean isTerminator(char c) {
return c == 64 || c == '\uffff' || c == 46;
}
private boolean isTerminatorOrIDSeparator(char c) {
return c == 95 || c == 45 || this.isTerminator(c);
}
private boolean haveExperimentalLanguagePrefix() {
if(this.id.length > 2) {
char c = this.id[1];
if(c == 45 || c == 95) {
c = this.id[0];
return c == 120 || c == 88 || c == 105 || c == 73;
}
}
return false;
}
private boolean haveKeywordAssign() {
for(int i = this.index; i < this.id.length; ++i) {
if(this.id[i] == 61) {
return true;
}
}
return false;
}
private int parseLanguage() {
int startLength = this.buffer.length();
if(this.haveExperimentalLanguagePrefix()) {
this.append(AsciiUtil.toLower(this.id[0]));
this.append('-');
this.index = 2;
}
char c;
while(!this.isTerminatorOrIDSeparator(c = this.next())) {
this.append(AsciiUtil.toLower(c));
}
--this.index;
if(this.buffer.length() - startLength == 3) {
String lang = LocaleIDs.threeToTwoLetterLanguage(this.getString(0));
if(lang != null) {
this.set(0, lang);
}
}
return 0;
}
private void skipLanguage() {
if(this.haveExperimentalLanguagePrefix()) {
this.index = 2;
}
this.skipUntilTerminatorOrIDSeparator();
}
private int parseScript() {
if(this.atTerminator()) {
return this.buffer.length();
} else {
int oldIndex = this.index++;
int oldBlen = this.buffer.length();
boolean firstPass = true;
char c;
while(!this.isTerminatorOrIDSeparator(c = this.next()) && AsciiUtil.isAlpha(c)) {
if(firstPass) {
this.addSeparator();
this.append(AsciiUtil.toUpper(c));
firstPass = false;
} else {
this.append(AsciiUtil.toLower(c));
}
}
--this.index;
if(this.index - oldIndex != 5) {
this.index = oldIndex;
this.buffer.delete(oldBlen, this.buffer.length());
} else {
++oldBlen;
}
return oldBlen;
}
}
private void skipScript() {
if(!this.atTerminator()) {
int oldIndex = this.index++;
char c;
while(!this.isTerminatorOrIDSeparator(c = this.next()) && AsciiUtil.isAlpha(c)) {
;
}
--this.index;
if(this.index - oldIndex != 5) {
this.index = oldIndex;
}
}
}
private int parseCountry() {
if(this.atTerminator()) {
return this.buffer.length();
} else {
int oldIndex = this.index++;
int oldBlen = this.buffer.length();
char c;
for(boolean firstPass = true; !this.isTerminatorOrIDSeparator(c = this.next()); this.append(AsciiUtil.toUpper(c))) {
if(firstPass) {
this.hadCountry = true;
this.addSeparator();
++oldBlen;
firstPass = false;
}
}
--this.index;
int charsAppended = this.buffer.length() - oldBlen;
if(charsAppended != 0) {
if(charsAppended >= 2 && charsAppended <= 3) {
if(charsAppended == 3) {
String region = LocaleIDs.threeToTwoLetterRegion(this.getString(oldBlen));
if(region != null) {
this.set(oldBlen, region);
}
}
} else {
this.index = oldIndex;
--oldBlen;
this.buffer.delete(oldBlen, this.buffer.length());
this.hadCountry = false;
}
}
return oldBlen;
}
}
private void skipCountry() {
if(!this.atTerminator()) {
if(this.id[this.index] == 95 || this.id[this.index] == 45) {
++this.index;
}
int oldIndex = this.index;
this.skipUntilTerminatorOrIDSeparator();
int charsSkipped = this.index - oldIndex;
if(charsSkipped < 2 || charsSkipped > 3) {
this.index = oldIndex;
}
}
}
private int parseVariant() {
int oldBlen = this.buffer.length();
boolean start = true;
boolean needSeparator = true;
boolean skipping = false;
boolean firstPass = true;
char c;
while((c = this.next()) != '\uffff') {
if(c == 46) {
start = false;
skipping = true;
} else if(c == 64) {
if(this.haveKeywordAssign()) {
break;
}
skipping = false;
start = false;
needSeparator = true;
} else if(start) {
start = false;
if(c != 95 && c != 45) {
--this.index;
}
} else if(!skipping) {
if(needSeparator) {
needSeparator = false;
if(firstPass && !this.hadCountry) {
this.addSeparator();
++oldBlen;
}
this.addSeparator();
if(firstPass) {
++oldBlen;
firstPass = false;
}
}
c = AsciiUtil.toUpper(c);
if(c == 45 || c == 44) {
c = '_';
}
this.append(c);
}
}
--this.index;
return oldBlen;
}
public String getLanguage() {
this.reset();
return this.getString(this.parseLanguage());
}
public String getScript() {
this.reset();
this.skipLanguage();
return this.getString(this.parseScript());
}
public String getCountry() {
this.reset();
this.skipLanguage();
this.skipScript();
return this.getString(this.parseCountry());
}
public String getVariant() {
this.reset();
this.skipLanguage();
this.skipScript();
this.skipCountry();
return this.getString(this.parseVariant());
}
public String[] getLanguageScriptCountryVariant() {
this.reset();
return new String[]{this.getString(this.parseLanguage()), this.getString(this.parseScript()), this.getString(this.parseCountry()), this.getString(this.parseVariant())};
}
public void setBaseName(String baseName) {
this.baseName = baseName;
}
public void parseBaseName() {
if(this.baseName != null) {
this.set(0, this.baseName);
} else {
this.reset();
this.parseLanguage();
this.parseScript();
this.parseCountry();
this.parseVariant();
int len = this.buffer.length();
if(len > 0 && this.buffer.charAt(len - 1) == 95) {
this.buffer.deleteCharAt(len - 1);
}
}
}
public String getBaseName() {
if(this.baseName != null) {
return this.baseName;
} else {
this.parseBaseName();
return this.getString(0);
}
}
public String getName() {
this.parseBaseName();
this.parseKeywords();
return this.getString(0);
}
private boolean setToKeywordStart() {
for(int i = this.index; i < this.id.length; ++i) {
if(this.id[i] == 64) {
if(this.canonicalize) {
++i;
for(int j = i; j < this.id.length; ++j) {
if(this.id[j] == 61) {
this.index = i;
return true;
}
}
return false;
} else {
++i;
if(i < this.id.length) {
this.index = i;
return true;
}
break;
}
}
}
return false;
}
private static boolean isDoneOrKeywordAssign(char c) {
return c == '\uffff' || c == 61;
}
private static boolean isDoneOrItemSeparator(char c) {
return c == '\uffff' || c == 59;
}
private String getKeyword() {
int start = this.index;
while(!isDoneOrKeywordAssign(this.next())) {
;
}
--this.index;
return AsciiUtil.toLowerString((new String(this.id, start, this.index - start)).trim());
}
private String getValue() {
int start = this.index;
while(!isDoneOrItemSeparator(this.next())) {
;
}
--this.index;
return (new String(this.id, start, this.index - start)).trim();
}
private Comparator getKeyComparator() {
Comparator<String> comp = new Comparator() {
public int compare(String lhs, String rhs) {
return lhs.compareTo(rhs);
}
};
return comp;
}
public Map getKeywordMap() {
if(this.keywords == null) {
TreeMap<String, String> m = null;
if(this.setToKeywordStart()) {
while(true) {
String key = this.getKeyword();
if(key.length() == 0) {
break;
}
char c = this.next();
if(c != 61) {
if(c == '\uffff') {
break;
}
} else {
String value = this.getValue();
if(value.length() != 0) {
label68: {
if(m == null) {
m = new TreeMap(this.getKeyComparator());
} else if(m.containsKey(key)) {
break label68;
}
m.put(key, value);
}
}
}
if(this.next() != 59) {
break;
}
}
}
this.keywords = (Map)(m != null?m:Collections.emptyMap());
}
return this.keywords;
}
private int parseKeywords() {
int oldBlen = this.buffer.length();
Map<String, String> m = this.getKeywordMap();
if(!m.isEmpty()) {
boolean first = true;
for(Entry<String, String> e : m.entrySet()) {
this.append((char)(first?'@':';'));
first = false;
this.append((String)e.getKey());
this.append('=');
this.append((String)e.getValue());
}
if(!first) {
++oldBlen;
}
}
return oldBlen;
}
public Iterator getKeywords() {
Map<String, String> m = this.getKeywordMap();
return m.isEmpty()?null:m.keySet().iterator();
}
public String getKeywordValue(String keywordName) {
Map<String, String> m = this.getKeywordMap();
return m.isEmpty()?null:(String)m.get(AsciiUtil.toLowerString(keywordName.trim()));
}
public void defaultKeywordValue(String keywordName, String value) {
this.setKeywordValue(keywordName, value, false);
}
public void setKeywordValue(String keywordName, String value) {
this.setKeywordValue(keywordName, value, true);
}
private void setKeywordValue(String keywordName, String value, boolean reset) {
if(keywordName == null) {
if(reset) {
this.keywords = Collections.emptyMap();
}
} else {
keywordName = AsciiUtil.toLowerString(keywordName.trim());
if(keywordName.length() == 0) {
throw new IllegalArgumentException("keyword must not be empty");
}
if(value != null) {
value = value.trim();
if(value.length() == 0) {
throw new IllegalArgumentException("value must not be empty");
}
}
Map<String, String> m = this.getKeywordMap();
if(m.isEmpty()) {
if(value != null) {
this.keywords = new TreeMap(this.getKeyComparator());
this.keywords.put(keywordName, value.trim());
}
} else if(reset || !m.containsKey(keywordName)) {
if(value != null) {
m.put(keywordName, value);
} else {
m.remove(keywordName);
if(m.isEmpty()) {
this.keywords = Collections.emptyMap();
}
}
}
}
}
}
| 412 | 0.946514 | 1 | 0.946514 | game-dev | MEDIA | 0.186273 | game-dev | 0.961979 | 1 | 0.961979 |
googlevr/blocks | 3,866 | Assets/ThirdParty/SteamVR/Scripts/SteamVR_TestController.cs | //======= Copyright (c) Valve Corporation, All rights reserved. ===============
//
// Purpose: Test SteamVR_Controller support.
//
//=============================================================================
using UnityEngine;
using System.Collections.Generic;
using Valve.VR;
public class SteamVR_TestController : MonoBehaviour
{
List<int> controllerIndices = new List<int>();
private void OnDeviceConnected(int index, bool connected)
{
var system = OpenVR.System;
if (system == null || system.GetTrackedDeviceClass((uint)index) != ETrackedDeviceClass.Controller)
return;
if (connected)
{
Debug.Log(string.Format("Controller {0} connected.", index));
PrintControllerStatus(index);
controllerIndices.Add(index);
}
else
{
Debug.Log(string.Format("Controller {0} disconnected.", index));
PrintControllerStatus(index);
controllerIndices.Remove(index);
}
}
void OnEnable()
{
SteamVR_Events.DeviceConnected.Listen(OnDeviceConnected);
}
void OnDisable()
{
SteamVR_Events.DeviceConnected.Remove(OnDeviceConnected);
}
void PrintControllerStatus(int index)
{
var device = SteamVR_Controller.Input(index);
Debug.Log("index: " + device.index);
Debug.Log("connected: " + device.connected);
Debug.Log("hasTracking: " + device.hasTracking);
Debug.Log("outOfRange: " + device.outOfRange);
Debug.Log("calibrating: " + device.calibrating);
Debug.Log("uninitialized: " + device.uninitialized);
Debug.Log("pos: " + device.transform.pos);
Debug.Log("rot: " + device.transform.rot.eulerAngles);
Debug.Log("velocity: " + device.velocity);
Debug.Log("angularVelocity: " + device.angularVelocity);
var l = SteamVR_Controller.GetDeviceIndex(SteamVR_Controller.DeviceRelation.Leftmost);
var r = SteamVR_Controller.GetDeviceIndex(SteamVR_Controller.DeviceRelation.Rightmost);
Debug.Log((l == r) ? "first" : (l == index) ? "left" : "right");
}
EVRButtonId[] buttonIds = new EVRButtonId[] {
EVRButtonId.k_EButton_ApplicationMenu,
EVRButtonId.k_EButton_Grip,
EVRButtonId.k_EButton_SteamVR_Touchpad,
EVRButtonId.k_EButton_SteamVR_Trigger
};
EVRButtonId[] axisIds = new EVRButtonId[] {
EVRButtonId.k_EButton_SteamVR_Touchpad,
EVRButtonId.k_EButton_SteamVR_Trigger
};
public Transform point, pointer;
void Update()
{
foreach (var index in controllerIndices)
{
var overlay = SteamVR_Overlay.instance;
if (overlay && point && pointer)
{
var t = SteamVR_Controller.Input(index).transform;
pointer.transform.localPosition = t.pos;
pointer.transform.localRotation = t.rot;
var results = new SteamVR_Overlay.IntersectionResults();
var hit = overlay.ComputeIntersection(t.pos, t.rot * Vector3.forward, ref results);
if (hit)
{
point.transform.localPosition = results.point;
point.transform.localRotation = Quaternion.LookRotation(results.normal);
}
continue;
}
foreach (var buttonId in buttonIds)
{
if (SteamVR_Controller.Input(index).GetPressDown(buttonId))
Debug.Log(buttonId + " press down");
if (SteamVR_Controller.Input(index).GetPressUp(buttonId))
{
Debug.Log(buttonId + " press up");
if (buttonId == EVRButtonId.k_EButton_SteamVR_Trigger)
{
SteamVR_Controller.Input(index).TriggerHapticPulse();
PrintControllerStatus(index);
}
}
if (SteamVR_Controller.Input(index).GetPress(buttonId))
Debug.Log(buttonId);
}
foreach (var buttonId in axisIds)
{
if (SteamVR_Controller.Input(index).GetTouchDown(buttonId))
Debug.Log(buttonId + " touch down");
if (SteamVR_Controller.Input(index).GetTouchUp(buttonId))
Debug.Log(buttonId + " touch up");
if (SteamVR_Controller.Input(index).GetTouch(buttonId))
{
var axis = SteamVR_Controller.Input(index).GetAxis(buttonId);
Debug.Log("axis: " + axis);
}
}
}
}
}
| 412 | 0.92122 | 1 | 0.92122 | game-dev | MEDIA | 0.692883 | game-dev | 0.813497 | 1 | 0.813497 |
OpenDiablo2/OpenDiablo2 | 7,297 | d2game/d2player/inventory_grid.go | package d2player
import (
"errors"
"fmt"
"github.com/OpenDiablo2/OpenDiablo2/d2core/d2records"
"github.com/OpenDiablo2/OpenDiablo2/d2common/d2enum"
"github.com/OpenDiablo2/OpenDiablo2/d2common/d2interface"
"github.com/OpenDiablo2/OpenDiablo2/d2core/d2asset"
"github.com/OpenDiablo2/OpenDiablo2/d2core/d2ui"
"github.com/OpenDiablo2/OpenDiablo2/d2common/d2resource"
"github.com/OpenDiablo2/OpenDiablo2/d2common/d2util"
)
// images for 1x1 grid tile items (rings and stuff) are 28x28 pixel
// however, the grid cells are 29x29 pixels, this is for padding
// for each row in inventory, we need to account for this padding
const cellPadding = 1
const (
fmtFlippyFile = "/data/global/items/inv%s.dc6"
)
// InventoryItem is an interface for an items that can be placed in the inventory grid
type InventoryItem interface {
InventoryGridSize() (width int, height int)
GetItemCode() string
InventoryGridSlot() (x, y int)
SetInventoryGridSlot(x, y int)
GetItemDescription() []string
}
var errorInventoryFull = errors.New("inventory full")
// NewItemGrid creates a new ItemGrid instance
func NewItemGrid(asset *d2asset.AssetManager,
ui *d2ui.UIManager,
l d2util.LogLevel,
record *d2records.InventoryRecord) *ItemGrid {
grid := record.Grid
itemGrid := &ItemGrid{
asset: asset,
uiManager: ui,
width: grid.Box.Width,
height: grid.Box.Height,
originX: grid.Box.Left,
originY: grid.Box.Top + (grid.Rows * cellPadding),
slotSize: grid.CellWidth,
sprites: make(map[string]*d2ui.Sprite),
equipmentSlots: genEquipmentSlotsMap(record),
}
itemGrid.Logger = d2util.NewLogger()
itemGrid.Logger.SetLevel(l)
itemGrid.Logger.SetPrefix(logPrefix)
return itemGrid
}
// ItemGrid is a reusable grid for use with player and merchant inventory.
// Handles layout and rendering item icons based on code.
type ItemGrid struct {
asset *d2asset.AssetManager
uiManager *d2ui.UIManager
items []InventoryItem
equipmentSlots map[d2enum.EquippedSlot]EquipmentSlot
width int
height int
originX int
originY int
sprites map[string]*d2ui.Sprite
slotSize int
*d2util.Logger
}
// SlotToScreen translates slot coordinates to screen coordinates
func (g *ItemGrid) SlotToScreen(slotX, slotY int) (screenX, screenY int) {
screenX = g.originX + slotX*g.slotSize
screenY = g.originY + slotY*g.slotSize
return screenX, screenY
}
// ScreenToSlot translates screen coordinates to slot coordinates
func (g *ItemGrid) ScreenToSlot(screenX, screenY int) (slotX, slotY int) {
slotX = (screenX - g.originX) / g.slotSize
slotY = (screenY - g.originY) / g.slotSize
return slotX, slotY
}
// GetSlot returns the inventory item at a given slot (can return nil)
func (g *ItemGrid) GetSlot(x, y int) InventoryItem {
for _, item := range g.items {
slotX, slotY := item.InventoryGridSlot()
width, height := item.InventoryGridSize()
if x >= slotX && x < slotX+width && y >= slotY && y < slotY+height {
return item
}
}
return nil
}
// ChangeEquippedSlot sets the item for an equipment slot
func (g *ItemGrid) ChangeEquippedSlot(slot d2enum.EquippedSlot, item InventoryItem) {
var curItem = g.equipmentSlots[slot]
curItem.item = item
g.equipmentSlots[slot] = curItem
}
// Add places a given set of items into the first available slots.
// Returns a count of the number of items which could be inserted.
func (g *ItemGrid) Add(items ...InventoryItem) (int, error) {
added := 0
var err error
for _, item := range items {
if g.add(item) {
added++
} else {
err = errorInventoryFull
break
}
}
g.Load(items...)
return added, err
}
func (g *ItemGrid) loadItem(item InventoryItem) {
if _, exists := g.sprites[item.GetItemCode()]; !exists {
var itemSprite *d2ui.Sprite
imgPath := fmt.Sprintf(fmtFlippyFile, item.GetItemCode())
itemSprite, err := g.uiManager.NewSprite(imgPath, d2resource.PaletteSky)
if err != nil {
g.Error("Failed to load sprite, error: " + err.Error())
}
g.sprites[item.GetItemCode()] = itemSprite
}
}
// Load reads the inventory sprites for items into local cache for rendering.
func (g *ItemGrid) Load(items ...InventoryItem) {
for _, item := range items {
g.loadItem(item)
}
for _, eq := range g.equipmentSlots {
if eq.item != nil {
g.loadItem(eq.item)
}
}
}
// Walk from top left to bottom right until a position large enough to hold the item is found.
// This is inefficient but simplifies the storage. At most a hundred or so cells will be looped, so impact is minimal.
func (g *ItemGrid) add(item InventoryItem) bool {
for y := 0; y < g.height; y++ {
for x := 0; x < g.width; x++ {
if !g.canFit(x, y, item) {
continue
}
g.set(x, y, item)
return true
}
}
return false
}
// canFit loops over all items to determine if any other items would overlap the given position.
func (g *ItemGrid) canFit(x, y int, item InventoryItem) bool {
insertWidth, insertHeight := item.InventoryGridSize()
if x+insertWidth > g.width || y+insertHeight > g.height {
return false
}
for _, compItem := range g.items {
slotX, slotY := compItem.InventoryGridSlot()
compWidth, compHeight := compItem.InventoryGridSize()
if x+insertWidth >= slotX &&
x < slotX+compWidth &&
y+insertHeight >= slotY &&
y < slotY+compHeight {
return false
}
}
return true
}
// Set an inventory item at the given grid coordinate
func (g *ItemGrid) Set(x, y int, item InventoryItem) error {
if !g.canFit(x, y, item) {
return fmt.Errorf("can not set item (%s) to position (%v, %v)", item.GetItemCode(), x, y)
}
g.set(x, y, item)
return nil
}
func (g *ItemGrid) set(x, y int, item InventoryItem) {
item.SetInventoryGridSlot(x, y)
g.items = append(g.items, item)
g.Load(item)
}
// Remove does an in place filter to remove the element from the slice of items.
func (g *ItemGrid) Remove(item InventoryItem) {
n := 0
for _, compItem := range g.items {
if compItem == item {
continue
}
g.items[n] = compItem
n++
}
g.items = g.items[:n]
}
func (g *ItemGrid) renderItem(item InventoryItem, target d2interface.Surface, x, y int) {
itemSprite := g.sprites[item.GetItemCode()]
if itemSprite != nil {
itemSprite.SetPosition(x, y)
itemSprite.GetCurrentFrameSize()
itemSprite.Render(target)
}
}
// Render the item grid to the given surface
func (g *ItemGrid) Render(target d2interface.Surface) {
g.renderInventoryItems(target)
g.renderEquippedItems(target)
}
func (g *ItemGrid) renderInventoryItems(target d2interface.Surface) {
for _, item := range g.items {
itemSprite := g.sprites[item.GetItemCode()]
slotX, slotY := g.SlotToScreen(item.InventoryGridSlot())
_, h := itemSprite.GetCurrentFrameSize()
slotY += h
g.renderItem(item, target, slotX, slotY)
}
}
func (g *ItemGrid) renderEquippedItems(target d2interface.Surface) {
for _, eq := range g.equipmentSlots {
if eq.item == nil {
continue
}
itemSprite := g.sprites[eq.item.GetItemCode()]
itemWidth, itemHeight := itemSprite.GetCurrentFrameSize()
// nolint:gomnd // 1/2 ov width
x := eq.x + ((eq.width - itemWidth) / 2)
// nolint:gomnd // 1/2 ov height
y := eq.y - ((eq.height - itemHeight) / 2)
g.renderItem(eq.item, target, x, y)
}
}
| 412 | 0.844483 | 1 | 0.844483 | game-dev | MEDIA | 0.952183 | game-dev | 0.911495 | 1 | 0.911495 |
google/pienoon | 3,769 | src/components/drip_and_vanish.cpp | // Copyright 2015 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "drip_and_vanish.h"
#include "scene_object.h"
CORGI_DEFINE_COMPONENT(fpl::pie_noon::DripAndVanishComponent,
fpl::pie_noon::DripAndVanishData)
namespace fpl {
namespace pie_noon {
using mathfu::vec3;
// DripAndVanish component does exactly one, highly specific thing:
// Gives a child scene object behavior such that it waits for a while,
// and then slowly sinks, while shrinking. It's used to govern behavior
// for splatters on the background.
void DripAndVanishComponent::UpdateAllEntities(corgi::WorldTime delta_time) {
for (auto iter = component_data_.begin(); iter != component_data_.end();
++iter) {
SceneObjectData* so_data = Data<SceneObjectData>(iter->entity);
DripAndVanishData* dv_data = GetComponentData(iter->entity);
dv_data->lifetime_remaining -= delta_time;
if (dv_data->lifetime_remaining > 0) {
if (dv_data->lifetime_remaining < dv_data->slide_time) {
float slide_amount =
1.0f - dv_data->lifetime_remaining / dv_data->slide_time;
vec3 relative_offset = so_data->Translation();
vec3 relative_scale = so_data->Scale();
// The amount it moves is a cubic function, mostly because
// that looked the prettiest.
relative_offset.y() = vec3(dv_data->start_position).y() -
(slide_amount * slide_amount * slide_amount) *
dv_data->drip_distance;
relative_scale = vec3(dv_data->start_scale) * (1.0f - slide_amount);
so_data->SetTranslation(relative_offset);
so_data->SetScale(relative_scale);
}
} else {
entity_manager_->DeleteEntity(iter->entity);
}
}
}
void DripAndVanishComponent::AddFromRawData(corgi::EntityRef& entity,
const void* raw_data) {
auto component_data = static_cast<const ComponentDefInstance*>(raw_data);
assert(component_data->data_type() == ComponentDataUnion_DripAndVanishDef);
DripAndVanishData* entity_data = AddEntity(entity);
const DripAndVanishDef* dripandvanish_data =
static_cast<const DripAndVanishDef*>(component_data->data());
entity_data->drip_distance = dripandvanish_data->distance_dripped();
entity_data->lifetime_remaining =
dripandvanish_data->total_lifetime() * kMillisecondsPerSecond;
entity_data->slide_time =
dripandvanish_data->time_spent_dripping() * kMillisecondsPerSecond;
}
// Make sure we have an accessory.
void DripAndVanishComponent::InitEntity(corgi::EntityRef& entity) {
ComponentInterface* scene_object_component =
GetComponent<SceneObjectComponent>();
assert(scene_object_component);
scene_object_component->AddEntityGenerically(entity);
}
// Set the starting values of the drip thing, since we populate them
// just after creation.
void DripAndVanishComponent::SetStartingValues(corgi::EntityRef& entity) {
DripAndVanishData* entity_data = GetComponentData(entity);
SceneObjectData* so_data = Data<SceneObjectData>(entity);
entity_data->start_position = so_data->Translation();
entity_data->start_scale = so_data->Scale();
}
} // pie noon
} // fpl
| 412 | 0.942852 | 1 | 0.942852 | game-dev | MEDIA | 0.428823 | game-dev,graphics-rendering | 0.880477 | 1 | 0.880477 |
Sigma-Skidder-Team/SigmaRebase | 1,223 | src/main/java/com/mentalfrostbyte/jello/module/impl/player/NoViewReset.java | package com.mentalfrostbyte.jello.module.impl.player;
import com.mentalfrostbyte.jello.event.impl.game.network.EventReceivePacket;
import com.mentalfrostbyte.jello.module.Module;
import com.mentalfrostbyte.jello.module.data.ModuleCategory;
import net.minecraft.network.play.server.SPlayerPositionLookPacket;
import team.sdhq.eventBus.annotations.EventTarget;
public class NoViewReset extends Module {
public NoViewReset() {
super(ModuleCategory.PLAYER, "NoViewReset", "Prevents the server from resetting your client yaw/pitch");
}
@EventTarget
public void onReceivePacket(EventReceivePacket event) {
if (this.isEnabled()) {
if (mc.player != null) {
if (mc.player.ticksExisted >= 10) {
if (mc.player != null && event.packet instanceof SPlayerPositionLookPacket positionLookPacket) {
mc.player.prevRotationYaw = positionLookPacket.yaw;
mc.player.prevRotationPitch = positionLookPacket.pitch;
positionLookPacket.yaw = mc.player.rotationYaw;
positionLookPacket.pitch = mc.player.rotationPitch;
}
}
}
}
}
}
| 412 | 0.809363 | 1 | 0.809363 | game-dev | MEDIA | 0.837353 | game-dev | 0.875435 | 1 | 0.875435 |
networkedsystemsIITB/NFV_LTE_EPC | 1,526 | NFV_LTE_EPC-3.0/EPC 3.0 Control Plane/hss/utils.cpp | #include "utils.h"
Utils g_utils;
/* Action - Exit the program */
void Utils::handle_type1_error(int arg, string msg) {
if (arg < 0) {
msg = to_string(errno) + ": " + msg;
perror(msg.c_str());
exit(EXIT_FAILURE);
}
}
/* Action - Check for error conditions. Do not exit. */
void Utils::handle_type2_error(int arg, string msg) {
if (arg < 0) {
msg = to_string(errno) + ": " + msg;
perror(msg.c_str());
}
}
char* Utils::allocate_str_mem(int len) {
char *tem;
if (len <= 0) {
handle_type1_error(-1, "Memory length error: utils_allocatestrmem");
}
tem = (char*)malloc(len * sizeof (char));
if (tem != NULL) {
memset(tem, 0, len * sizeof (char));
return tem;
}
else {
handle_type1_error(-1, "Memory allocation error: utils_allocatestrmem");
}
}
uint8_t* Utils::allocate_uint8_mem(int len) {
uint8_t *tem;
if (len <= 0) {
handle_type1_error(-1, "Memory length error: utils_allocateuint8mem");
}
tem = (uint8_t*)malloc(len * sizeof (uint8_t));
if (tem != NULL) {
memset(tem, 0, len * sizeof (uint8_t));
return tem;
}
else {
handle_type1_error(-1, "Memory allocation error: utils_allocateuint8mem");
}
}
void Utils::time_check(time_t start_time, double dur_time, bool &time_exceeded) {
double elapsed_time;
if ((elapsed_time = difftime(time(0), start_time)) > dur_time) {
time_exceeded = true;
}
}
int Utils::max_ele(vector<int> inp) {
int ans;
int size;
int i;
ans = 0;
size = inp.size();
for (i = 0; i < size; i++) {
ans = max(ans, inp[i]);
}
return ans;
}
| 412 | 0.860041 | 1 | 0.860041 | game-dev | MEDIA | 0.423281 | game-dev | 0.962165 | 1 | 0.962165 |
google/google-ctf | 4,018 | 2025/hackceler8/game/src/enemy/boss.rs | // Copyright 2025 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the License);
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an AS IS BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use megahx8::*;
use super::Enemy;
use super::Hitbox;
use super::Stats;
use crate::big_sprite::BigSprite;
use crate::data;
use crate::enemy;
use crate::enemy::EnemyImpl;
use crate::enemy::Status;
use crate::entity::*;
use crate::game::Ctx;
use crate::res::enemies::EnemyType;
use crate::res::sprites::explosion as ExplosionSprite;
use crate::resource_state::State;
pub(crate) fn new() -> EnemyImpl {
EnemyImpl {
stats,
update_animation,
}
}
fn stats(_enemy_type: EnemyType) -> Stats {
Stats {
speed: 16,
health: 25,
strength: 1,
melee: true,
shoots: false,
sings: false,
tracks: false,
flies: false,
hitbox: Hitbox {
x: 12,
y: 16,
w: 104,
h: 80,
},
}
}
fn update_animation(_enemy: &mut Enemy, _walking: bool) {}
pub fn should_render_sprite(enemy: &mut Enemy) -> bool {
match enemy.status {
Status::Dying {
falling: _,
cooldown,
// Flash on and off in the first half, then keep the flash o
// for the second half of the death sequence.
} => cooldown > enemy::BOSS_DEATH_COOLDOWN / 2 || (cooldown / 10) % 2 == 0,
Status::KnockedBack {
direction: _,
cooldown,
} => cooldown >= enemy::KNOCKBACK_COOLDOWN - 6,
_ => false,
}
}
/// Boss related enemy state data.
pub struct BossState {
/// Explosions for the boss death sequence.
explosion_sprites: [BigSprite; 2],
}
impl BossState {
pub fn new(res_state: &mut State, vdp: &mut TargetVdp) -> BossState {
let mut explosion_sprites = [
ExplosionSprite::new(res_state, vdp, /* keep_loaded= */ false),
ExplosionSprite::new(res_state, vdp, /* keep_loaded= */ false),
];
for sprite in &mut explosion_sprites {
sprite.set_anim(ExplosionSprite::Anim::Explode as usize);
}
BossState { explosion_sprites }
}
pub fn update(ctx: &mut Ctx) {
if ctx.world.boss_state.is_none() {
return;
}
let state = ctx.world.boss_state.as_mut().unwrap();
let boss = ctx.world.enemies.iter_mut().find(|e| e.is_boss());
if boss.is_none() {
return;
}
let boss = boss.unwrap();
for sprite in &mut state.explosion_sprites {
sprite.update();
}
// Update explosion positions for the boss defeat sequence.
if let Status::Dying {
falling: _,
cooldown,
} = boss.status
{
let center = boss.hitbox().center();
for (i, sprite) in state.explosion_sprites.iter_mut().enumerate() {
// Start new explosions at random positions with a phase shift between the two sprites.
let explosion_frame = cooldown as usize + 15 * i;
if explosion_frame % 30 == 1 {
let (dx, dy) = data::EXPLOSION_OFFSETS[i][explosion_frame / 30];
sprite.set_position(center.0 - 8 + dx, center.1 - 8 + dy);
sprite.set_anim(ExplosionSprite::Anim::Explode as usize);
}
}
}
}
pub fn render(&mut self, renderer: &mut TargetRenderer) {
for sprite in &mut self.explosion_sprites {
sprite.render(renderer);
}
}
}
| 412 | 0.88089 | 1 | 0.88089 | game-dev | MEDIA | 0.992073 | game-dev | 0.786637 | 1 | 0.786637 |
Hoizame/AtlasLootClassic | 72,094 | AtlasLootClassic_Crafting/data.lua | -----------------------------------------------------------------------
-- Upvalued Lua API.
-----------------------------------------------------------------------
local _G = getfenv(0)
local select = _G.select
local string = _G.string
local format = string.format
-- WoW
local RAID_CLASS_COLORS = _G["RAID_CLASS_COLORS"]
-- ----------------------------------------------------------------------------
-- AddOn namespace.
-- ----------------------------------------------------------------------------
local addonname, private = ...
local AtlasLoot = _G.AtlasLoot
local data = AtlasLoot.ItemDB:Add(addonname, 1, AtlasLoot.CLASSIC_VERSION_NUM)
local GetColorSkill = AtlasLoot.Data.Profession.GetColorSkillRankNoSpell
local AL = AtlasLoot.Locales
local ALIL = AtlasLoot.IngameLocales
local NORMAL_DIFF = data:AddDifficulty(AL["Normal"], "n", 1, nil, true)
local LEATHER_DIFF = data:AddDifficulty(ALIL["Leather"], "leather", 0)
local MAIL_DIFF = data:AddDifficulty(ALIL["Mail"], "mail", 0)
local PLATE_DIFF = data:AddDifficulty(ALIL["Plate"], "plate", 0)
local NORMAL_ITTYPE = data:AddItemTableType("Item", "Item")
local PROF_ITTYPE = data:AddItemTableType("Profession", "Item")
local QUEST_EXTRA_ITTYPE = data:AddExtraItemTableType("Quest")
local PRICE_EXTRA_ITTYPE = data:AddExtraItemTableType("Price")
local PROF_CONTENT = data:AddContentType(ALIL["Professions"], ATLASLOOT_PRIMPROFESSION_COLOR)
local PROF_GATH_CONTENT = data:AddContentType(ALIL["Gathering Professions"], ATLASLOOT_PRIMPROFESSION_COLOR)
local PROF_SEC_CONTENT = data:AddContentType(AL["Secondary Professions"], ATLASLOOT_SECPROFESSION_COLOR)
local PROF_CLASS_CONTENT = data:AddContentType(AL["Class Professions"], ATLASLOOT_CLASSPROFESSION_COLOR)
--local RAID20_CONTENT = data:AddContentType(AL["20 Raids"], ATLASLOOT_RAID20_COLOR)
--local RAID40_CONTENT = data:AddContentType(AL["40 Raids"], ATLASLOOT_RAID40_COLOR)
data["Alchemy"] = {
name = ALIL["Alchemy"],
ContentType = PROF_CONTENT,
LoadDifficulty = NORMAL_DIFF,
TableType = PROF_ITTYPE,
CorrespondingFields = private.ALCHEMY_LINK,
items = {
{
name = AL["Flasks"],
[NORMAL_DIFF] = {
{ 1, 17635 }, --Flask of the Titans
{ 2, 17636 }, --Flask of Distilled Wisdom
{ 3, 17637 }, --Flask of Supreme Power
{ 4, 17638 }, --Flask of Chromatic Resistance
{ 16, 17634 }, --Flask of Petrification
},
},
{
name = AL["Transmutes"],
[NORMAL_DIFF] = {
{ 1, 17560 }, --Transmute: Fire to Earth
{ 2, 17565 }, --Transmute: Life to Earth
{ 4, 17561 }, --Transmute: Earth to Water
{ 5, 17563 }, --Transmute: Undeath to Water
{ 7, 17562 }, --Transmute: Water to Air
{ 9, 17564 }, --Transmute: Water to Undeath
{ 11, 17566 }, --Transmute: Earth to Life
{ 13, 17559 }, --Transmute: Air to Fire
{ 16, 17187 }, --Transmute: Arcanite
{ 17, 11479 }, --Transmute: Iron to Gold
{ 18, 11480 }, --Transmute: Mithril to Truesilver
{ 20, 25146 }, --Transmute: Elemental Fire
},
},
{
name = AL["Healing/Mana Potions"],
[NORMAL_DIFF] = {
{ 1, 17556 }, --Major Healing Potion
{ 2, 11457 }, --Superior Healing Potion
{ 3, 7181 }, --Greater Healing Potion
{ 4, 3447 }, --Healing Potion
{ 5, 2337 }, --Lesser Healing Potion
{ 6, 2330 }, --Minor Healing Potion
{ 8, 2332 }, --Minor Rejuvenation Potion
{ 10, 24366 }, --Greater Dreamless Sleep Potion
{ 12, 11458 }, --Wildvine Potion
{ 13, 4508 }, --Discolored Healing Potion
{ 16, 17580 }, --Major Mana Potion
{ 17, 17553 }, --Superior Mana Potion
{ 18, 11448 }, --Greater Mana Potion
{ 19, 3452 }, --Mana Potion
{ 20, 3173 }, --Lesser Mana Potion
{ 21, 2331 }, --Minor Mana Potion
{ 23, 22732 }, --Major Rejuvenation Potion
{ 25, 15833 }, --Dreamless Sleep Potion
{ 27, 24365 }, --Mageblood Potion
},
},
{
name = AL["Protection Potions"],
[NORMAL_DIFF] = {
{ 1, 17574 }, --Greater Fire Protection Potion
{ 2, 17576 }, --Greater Nature Protection Potion
{ 3, 17575 }, --Greater Frost Protection Potion
{ 4, 17578 }, --Greater Shadow Protection Potion
{ 5, 17577 }, --Greater Arcane Protection Potion
{ 7, 11453 }, --Magic Resistance Potion
{ 8, 3174 }, --Elixir of Poison Resistance
{ 16, 7257 }, --Fire Protection Potion
{ 17, 7259 }, --Nature Protection Potion
{ 18, 7258 }, --Frost Protection Potion
{ 19, 7256 }, --Shadow Protection Potion
{ 20, 7255 }, --Holy Protection Potion
{ 22, 3172 }, --Minor Magic Resistance Potion
},
},
{
name = AL["Util Potions"],
[NORMAL_DIFF] = {
{ 1, 11464 }, --Invisibility Potion
{ 2, 2335 }, --Swiftness Potion
{ 3, 6624 }, --Free Action Potion
{ 4, 3175 }, --Limited Invulnerability Potion
{ 5, 24367 }, --Living Action Potion
{ 6, 7841 }, --Swim Speed Potion
{ 8, 17572 }, --Purification Potion
{ 10, 17552 }, --Mighty Rage Potion
{ 11, 6618 }, --Great Rage Potion
{ 12, 6617 }, --Rage Potion
{ 16, 3448 }, --Lesser Invisibility Potion
{ 23, 11452 }, --Restorative Potion
{ 25, 17570 }, --Greater Stoneshield Potion
{ 26, 4942 }, --Lesser Stoneshield Potion
},
},
{
name = AL["Stat Elixirs"],
[NORMAL_DIFF] = {
{ 1, 24368 }, --Mighty Troll
{ 2, 3451 }, --Major Troll
{ 3, 3176 }, --Strong Troll
{ 4, 3170 }, --Weak Troll
{ 6, 17554 }, --Elixir of Superior Defense
{ 7, 11450 }, --Elixir of Greater Defense
{ 8, 3177 }, --Elixir of Defense
{ 9, 7183 }, --Elixir of Minor Defense
{ 11, 11472 }, --Elixir of Giants
{ 12, 3188 }, --Elixir of Ogre
{ 13, 2329 }, --Elixir of Lion
{ 16, 11467 }, --Elixir of Greater Agility
{ 17, 11449 }, --Elixir of Agility
{ 18, 2333 }, --Elixir of Lesser Agility
{ 19, 3230 }, --Elixir of Minor Agility
{ 21, 11465 }, --Elixir of Greater Intellect
{ 22, 3171 }, --Elixir of Wisdom
{ 24, 17573 }, --Greater Arcane Elixir
{ 25, 11461 }, --Arcane Elixir
},
},
{
name = AL["Special Elixirs"],
[NORMAL_DIFF] = {
{ 1, 26277 }, --Elixir of Greater Firepower
{ 2, 17555 }, --Elixir of the Sages
{ 5, 3450 }, --Elixir of Fortitude
{ 7, 17557 }, --Elixir of Brute Force
{ 8, 17571 }, --Elixir of the Mongoose
{ 10, 11477 }, --Elixir of Demonslaying
{ 16, 7845 }, --Elixir of Firepower
{ 17, 21923 }, --Elixir of Frost Power
{ 18, 11476 }, --Elixir of Shadow Power
{ 20, 2334 }, --Elixir of Minor Fortitude
{ 22, 8240 }, --Elixir of Giant Growth
},
},
{
name = AL["Misc Elixirs"],
[NORMAL_DIFF] = {
{ 1, 11478 }, --Elixir of Detect Demon
{ 2, 12609 }, --Catseye Elixir
{ 4, 22808 }, --Elixir of Greater Water Breathing
{ 6, 11468 }, --Elixir of Dream Vision
{ 16, 11460 }, --Elixir of Detect Undead
{ 17, 3453 }, --Elixir of Detect Lesser Invisibility
{ 19, 7179 }, --Elixir of Water Breathing
},
},
{
name = AL["Misc"],
[NORMAL_DIFF] = {
{ 1, 17632 }, --Alchemist's Stone
{ 3, 11473 }, --Ghost Dye
{ 5, 24266 }, --Gurubashi Mojo Madness
{ 7, 11466 }, --Gift of Arthas
{ 8, 3449 }, --Shadow Oil
{ 9, 3454 }, --Frost Oil
{ 10, 11451 }, --Oil of Immolation
{ 16, 11459 }, --Philosophers' Stone
{ 18, 11456 }, --Goblin Rocket Fuel
{ 23, 7836 }, --Blackmouth Oil
{ 24, 7837 }, --Fire Oil
{ 25, 17551 }, --Stonescale Oil
},
},
},
}
data["Blacksmithing"] = {
name = ALIL["Blacksmithing"],
ContentType = PROF_CONTENT,
LoadDifficulty = NORMAL_DIFF,
TableType = PROF_ITTYPE,
CorrespondingFields = private.BLACKSMITHING_LINK,
items = {
{
name = AL["Weapons"].." - "..ALIL["Daggers"],
[NORMAL_DIFF] = {
{ 1, 23638 }, --Black Amnesty / 66
{ 2, 16995 }, --Heartseeker / 63
{ 3, 10013 }, --Ebon Shiv / 51
{ 4, 15973 }, --Searing Golden Blade / 39
{ 5, 15972 }, --Glinting Steel Dagger / 36
{ 6, 3295 }, --Deadly Bronze Poniard / 25
{ 7, 6517 }, --Pearl-handled Dagger / 23
{ 8, 3491 }, --Big Bronze Knife / 20
{ 9, 8880 }, --Copper Dagger / 11
}
},
{
name = AL["Weapons"].." - "..AL["Axes"],
[NORMAL_DIFF] = {
{ 1, "INV_sword_04", nil, ALIL["One-Handed Axes"] },
{ 2, 20897 }, --Dark Iron Destroyer / 65
{ 3, 16991 }, --Annihilator / 63
{ 4, 16970 }, --Dawn / 55
{ 5, 16969 }, --Ornate Thorium Handaxe / 55
{ 6, 9995 }, --Blue Glittering Axe / 44
{ 7, 9993 }, --Heavy Mithril Axe / 42
{ 8, 21913 }, --Edge of Winter / 38
{ 9, 2741 }, --Bronze Axe / 23
{ 10, 3294 }, --Thick War Axe / 17
{ 11, 2738 }, --Copper Axe / 9
{ 16, "INV_sword_04", nil, ALIL["Two-Handed Axes"] },
{ 17, 23653 }, --Nightfall / 70
{ 18, 16994 }, --Arcanite Reaper / 63
{ 19, 15294 }, --Dark Iron Sunderer / 57
{ 20, 16971 }, --Huge Thorium Battleaxe / 56
{ 21, 3500 }, --Shadow Crescent Axe / 40
{ 22, 3498 }, --Massive Iron Axe / 37
{ 23, 9987 }, --Bronze Battle Axe / 27
{ 24, 3293 }, --Copper Battle Axe / 13
}
},
{
name = AL["Weapons"].." - "..AL["Maces"],
[NORMAL_DIFF] = {
{ 1, "INV_sword_04", nil, ALIL["One-Handed Maces"] },
{ 2, 23650 }, --Ebon Hand / 70
{ 3, 16993 }, --Masterwork Stormhammer / 63
{ 4, 27830 }, --Persuader / 63
{ 5, 16984 }, --Volcanic Hammer / 58
{ 6, 16983 }, --Serenity / 57
{ 7, 10009 }, --Runed Mithril Hammer / 49
{ 8, 10003 }, --The Shatterer / 47
{ 9, 10001 }, --Big Black Mace / 46
{ 10, 3297 }, --Mighty Iron Hammer / 30
{ 11, 6518 }, --Iridescent Hammer / 28
{ 12, 3296 }, --Heavy Bronze Mace / 25
{ 13, 2740 }, --Bronze Mace / 22
{ 14, 2737 }, --Copper Mace / 9
{ 16, "INV_sword_04", nil, ALIL["Two-Handed Maces"] },
{ 17, 21161 }, --Sulfuron Hammer / 67
{ 18, 16988 }, --Hammer of the Titans / 63
{ 19, 16973 }, --Enchanted Battlehammer / 56
{ 20, 15292 }, --Dark Iron Pulverizer / 55
{ 21, 3495 }, --Golden Iron Destroyer / 34
{ 22, 3494 }, --Solid Iron Maul / 31
{ 23, 9985 }, --Bronze Warhammer / 25
{ 24, 7408 }, --Heavy Copper Maul / 16
}
},
{
name = AL["Weapons"].." - "..AL["Swords"],
[NORMAL_DIFF] = {
{ 1, "INV_sword_04", nil, ALIL["One-Handed Swords"] },
{ 2, 23652 }, --Blackguard / 70
{ 3, 20890 }, --Dark Iron Reaver / 65
{ 4, 27832 }, --Sageblade / 64
{ 5, 16992 }, --Frostguard / 63
{ 6, 16978 }, --Blazing Rapier / 56
{ 7, 10007 }, --Phantom Blade / 49
{ 8, 10005 }, --Dazzling Mithril Rapier / 48
{ 9, 9997 }, --Wicked Mithril Blade / 45
{ 10, 3493 }, --Jade Serpentblade / 35
{ 11, 3492 }, --Hardened Iron Shortsword / 32
{ 12, 2742 }, --Bronze Shortsword / 24
{ 13, 2739 }, --Copper Shortsword / 9
{ 16, "INV_sword_06", nil, ALIL["Two-Handed Swords"] },
{ 17, 16990 }, --Arcanite Champion / 63
{ 18, 16985 }, --Corruption / 58
{ 19, 10015 }, --Truesilver Champion / 52
{ 20, 3497 }, --Frost Tiger Blade / 40
{ 21, 3496 }, --Moonsteel Broadsword / 36
{ 22, 9986 }, --Bronze Greatsword / 26
{ 23, 3292 }, --Heavy Copper Broadsword / 19
{ 24, 9983 }, --Copper Claymore / 11
}
},
{
name = AL["Weapons"].." - "..ALIL["Polearms"],
[NORMAL_DIFF] = {
{ 1, 23639 }, --Blackfury / 66
{ 2, 10011 }, --Blight / 50
}
},
{
name = AL["Armor"].." - "..ALIL["Head"],
[MAIL_DIFF] = {
{ 1, 16728 }, --Helm of the Great Chief / 61
{ 2, 16659 }, --Radiant Circlet / 59
{ 3, 9961 }, --Mithril Coif / 46
{ 4, 3503 }, --Golden Scale Coif / 38
{ 5, 9814 }, --Barbaric Iron Helm / 35
{ 6, 3502 }, --Green Iron Helm / 34
},
[PLATE_DIFF] = {
{ 1, 23636 }, --Dark Iron Helm / 66
{ 2, 24913 }, --Darkrune Helm / 63
{ 3, 16742 }, --Enchanted Thorium Helm / 62
{ 4, 16729 }, --Lionheart Helm / 61
{ 5, 16726 }, --Runic Plate Helm / 61
{ 6, 16724 }, --Whitesoul Helm / 60
{ 7, 16658 }, --Imperial Plate Helm / 59
{ 8, 16653 }, --Thorium Helm / 56
{ 9, 9980 }, --Ornate Mithril Helm / 49
{ 10, 9970 }, --Heavy Mithril Helm / 47
{ 11, 9935 }, --Steel Plate Helm / 43
},
},
{
name = AL["Armor"].." - "..ALIL["Shoulder"],
[MAIL_DIFF] = {
{ 1, 24137 }, --Bloodsoul Shoulders / 65
{ 2, 20873 }, --Fiery Chain Shoulders / 62
{ 3, 9966 }, --Mithril Scale Shoulders / 47
{ 4, 3505 }, --Golden Scale Shoulders / 35
{ 5, 9811 }, --Barbaric Iron Shoulders / 32
{ 6, 3504 }, --Green Iron Shoulders / 32
{ 7, 3330 }, --Silvered Bronze Shoulders / 25
{ 8, 3328 }, --Rough Bronze Shoulders / 22
},
[PLATE_DIFF] = {
{ 1, 24141 }, --Darksoul Shoulders / 65
{ 2, 16664 }, --Runic Plate Shoulders / 60
{ 3, 15295 }, --Dark Iron Shoulders / 58
{ 4, 16660 }, --Dawnbringer Shoulders / 58
{ 5, 16646 }, --Imperial Plate Shoulders / 53
{ 6, 9952 }, --Ornate Mithril Shoulder / 45
{ 7, 9926 }, --Heavy Mithril Shoulder / 41
},
},
{
name = AL["Armor"].." - "..ALIL["Chest"],
[MAIL_DIFF] = {
{ 1, 27590 }, --Obsidian Mail Tunic / 72
{ 2, 24136 }, --Bloodsoul Breastplate / 65
{ 3, 16746 }, --Invulnerable Mail / 63
{ 4, 15293 }, --Dark Iron Mail / 56
{ 5, 16650 }, --Wildthorn Mail / 54
{ 6, 16648 }, --Radiant Breastplate / 54
{ 7, 3511 }, --Golden Scale Cuirass / 40
{ 8, 9916 }, --Steel Breastplate / 40
{ 9, 3508 }, --Green Iron Hauberk / 36
{ 10, 9813 }, --Barbaric Iron Breastplate / 32
{ 11, 2675 }, --Shining Silver Breastplate / 29
{ 12, 2673 }, --Silvered Bronze Breastplate / 26
{ 13, 2670 }, --Rough Bronze Cuirass / 23
{ 14, 8367 }, --Ironforge Breastplate / 20
{ 15, 2667 }, --Runed Copper Breastplate / 18
{ 16, 3321 }, --Copper Chain Vest / 10
{ 17, 12260 }, --Rough Copper Vest / 7
},
[PLATE_DIFF] = {
{ 1, 28242 }, --Icebane Breastplate / 80
{ 2, 27587 }, --Thick Obsidian Breastplate / 72
{ 3, 28461 }, --Ironvine Breastplate / 70
{ 4, 24139 }, --Darksoul Breastplate / 65
{ 5, 24914 }, --Darkrune Breastplate / 63
{ 6, 16745 }, --Enchanted Thorium Breastplate / 63
{ 7, 16731 }, --Runic Breastplate / 62
{ 8, 16663 }, --Imperial Plate Chest / 60
{ 9, 15296 }, --Dark Iron Plate / 59
{ 10, 16667 }, --Demon Forged Breastplate / 57
{ 11, 16642 }, --Thorium Armor / 50
{ 12, 9974 }, --Truesilver Breastplate / 49
{ 13, 9972 }, --Ornate Mithril Breastplate / 48
{ 14, 9959 }, --Heavy Mithril Breastplate / 46
},
},
{
name = AL["Armor"].." - "..ALIL["Feet"],
[MAIL_DIFF] = {
{ 1, 23629 }, --Heavy Timbermaw Boots / 64
{ 2, 16656 }, --Radiant Boots / 58
{ 3, 3515 }, --Golden Scale Boots / 40
{ 4, 3513 }, --Polished Steel Boots / 37
{ 5, 9818 }, --Barbaric Iron Boots / 36
{ 6, 3334 }, --Green Iron Boots / 29
{ 7, 3331 }, --Silvered Bronze Boots / 26
{ 8, 7817 }, --Rough Bronze Boots / 18
{ 9, 3319 }, --Copper Chain Boots / 9
},
[PLATE_DIFF] = {
{ 1, 24399 }, --Dark Iron Boots / 70
{ 2, 16657 }, --Imperial Plate Boots / 59
{ 3, 16652 }, --Thorium Boots / 56
{ 4, 9979 }, --Ornate Mithril Boots / 49
{ 5, 9968 }, --Heavy Mithril Boots / 47
},
},
{
name = AL["Armor"].." - "..ALIL["Hand"],
[MAIL_DIFF] = {
{ 1, 27589 }, --Black Grasp of the Destroyer / 70
{ 2, 24138 }, --Bloodsoul Gauntlets / 65
{ 3, 16661 }, --Storm Gauntlets / 59
{ 4, 16654 }, --Radiant Gloves / 57
{ 5, 11643 }, --Golden Scale Gauntlets / 41
{ 6, 9820 }, --Barbaric Iron Gloves / 37
{ 7, 3336 }, --Green Iron Gauntlets / 30
{ 8, 3333 }, --Silvered Bronze Gauntlets / 27
{ 9, 3325 }, --Gemmed Copper Gauntlets / 15
{ 10, 3323 }, --Runed Copper Gauntlets / 12
},
[PLATE_DIFF] = {
{ 1, 28243 }, --Icebane Gauntlets / 80
{ 2, 23637 }, --Dark Iron Gauntlets / 70
{ 3, 28462 }, --Ironvine Gloves / 70
{ 4, 23633 }, --Gloves of the Dawn / 64
{ 5, 24912 }, --Darkrune Gauntlets / 63
{ 6, 16741 }, --Stronghold Gauntlets / 62
{ 7, 16655 }, --Fiery Plate Gauntlets / 58
{ 8, 9954 }, --Truesilver Gauntlets / 45
{ 9, 9950 }, --Ornate Mithril Gloves / 44
{ 10, 9928 }, --Heavy Mithril Gauntlet / 41
},
},
{
name = AL["Armor"].." - "..ALIL["Legs"],
[MAIL_DIFF] = {
{ 1, 16725 }, --Radiant Leggings / 61
{ 2, 9931 }, --Mithril Scale Pants / 42
{ 3, 9957 }, --Orcish War Leggings / 42
{ 4, 3507 }, --Golden Scale Leggings / 34
{ 5, 3506 }, --Green Iron Leggings / 31
{ 6, 12259 }, --Silvered Bronze Leggings / 31
{ 7, 2668 }, --Rough Bronze Leggings / 21
{ 8, 3324 }, --Runed Copper Pants / 13
{ 9, 2662 }, --Copper Chain Pants / 9
},
[PLATE_DIFF] = {
{ 1, 24140 }, --Darksoul Leggings / 65
{ 2, 16744 }, --Enchanted Thorium Leggings / 63
{ 3, 16732 }, --Runic Plate Leggings / 62
{ 4, 16730 }, --Imperial Plate Leggings / 61
{ 5, 16662 }, --Thorium Leggings / 60
{ 6, 20876 }, --Dark Iron Leggings / 60
{ 7, 27829 }, --Titanic Leggings / 60
{ 8, 9945 }, --Ornate Mithril Pants / 44
{ 9, 9933 }, --Heavy Mithril Pants / 42
},
},
{
name = AL["Armor"].." - "..ALIL["Waist"],
[MAIL_DIFF] = {
{ 1, 27588 }, --Light Obsidian Belt / 68
{ 2, 20872 }, --Fiery Chain Girdle / 59
{ 3, 23628 }, --Heavy Timbermaw Belt / 58
{ 4, 16645 }, --Radiant Belt / 52
{ 5, 2666 }, --Runed Copper Belt / 18
{ 6, 2661 }, --Copper Chain Belt / 11
},
[PLATE_DIFF] = {
{ 1, 28463 }, --Ironvine Belt / 70
{ 2, 27585 }, --Heavy Obsidian Belt / 68
{ 3, 23632 }, --Girdle of the Dawn / 58
{ 4, 16647 }, --Imperial Plate Belt / 53
{ 5, 16643 }, --Thorium Belt / 50
},
},
{
name = AL["Armor"].." - "..ALIL["Wrist"],
[MAIL_DIFF] = {
{ 1, 9937 }, --Mithril Scale Bracers / 43
{ 2, 7223 }, --Golden Scale Bracers / 37
{ 3, 3501 }, --Green Iron Bracers / 33
{ 4, 2672 }, --Patterned Bronze Bracers / 25
{ 5, 2664 }, --Runed Copper Bracers / 19
{ 6, 2663 }, --Copper Bracers / 7
},
[PLATE_DIFF] = {
{ 1, 28244 }, --Icebane Bracers / 80
{ 2, 20874 }, --Dark Iron Bracers / 59
{ 3, 16649 }, --Imperial Plate Bracers / 54
{ 4, 16644 }, --Thorium Bracers / 51
},
},
{
name = ALIL["Shields"],
[NORMAL_DIFF] = {
{ 1, 27586 }, --Jagged Obsidian Shield / 70
},
},
{
name = AL["Enhancements"],
[NORMAL_DIFF] = {
{ 1, 9964 }, --Mithril Spurs / 43
{ 3, 7224 }, --Steel Weapon Chain / 38
{ 18, 7222 }, --Iron Counterweight / 33
{ 5, 16651 }, --Thorium Shield Spike / 55
{ 6, 9939 }, --Mithril Shield Spike / 43
{ 20, 7221 }, --Iron Shield Spike / 30
{ 8, 22757 }, --Elemental Sharpening Stone / 60
{ 9, 16641 }, --Dense Sharpening Stone / 45
{ 10, 9918 }, --Solid Sharpening Stone / 35
{ 11, 2674 }, --Heavy Sharpening Stone / 25
{ 12, 2665 }, --Coarse Sharpening Stone / 15
{ 13, 2660 }, --Rough Sharpening Stone / 5
{ 24, 16640 }, --Dense Weightstone / 45
{ 25, 9921 }, --Solid Weightstone / 35
{ 26, 3117 }, --Heavy Weightstone / 25
{ 27, 3116 }, --Coarse Weightstone / 15
{ 28, 3115 }, --Rough Weightstone / 5
},
},
{
name = AL["Misc"],
[NORMAL_DIFF] = {
{ 1, 20201 }, --Arcanite Rod / 55
{ 2, 14380 }, --Truesilver Rod / 40
{ 16, 14379 }, --Golden Rod / 30
{ 17, 7818 }, --Silver Rod / 20
{ 4, 19669 }, --Arcanite Skeleton Key / 55
{ 5, 19668 }, --Truesilver Skeleton Key / 40
{ 19, 19667 }, --Golden Skeleton Key / 30
{ 20, 19666 }, --Silver Skeleton Key / 20
{ 7, 11454 }, --Inlaid Mithril Cylinder / 42
{ 22, 8768 }, --Iron Buckle / 30
{ 9, 16639 }, --Dense Grinding Stone / 45
{ 10, 9920 }, --Solid Grinding Stone / 35
{ 11, 3337 }, --Heavy Grinding Stone / 25
{ 24, 3326 }, --Coarse Grinding Stone / 20
{ 25, 3320 }, --Rough Grinding Stone / 10
},
},
}
}
data["Enchanting"] = {
name = ALIL["Enchanting"],
ContentType = PROF_CONTENT,
LoadDifficulty = NORMAL_DIFF,
TableType = PROF_ITTYPE,
CorrespondingFields = private.ENCHANTING_LINK,
items = {
{
name = AL["Oil"],
[NORMAL_DIFF] = {
{ 1, 25130 }, --Brilliant Mana Oil / 310
{ 2, 25129 }, --Brilliant Wizard Oil / 310
{ 3, 25128 }, --Wizard Oil / 285
{ 4, 25127 }, --Lesser Mana Oil / 260
{ 5, 25126 }, --Lesser Wizard Oil / 210
{ 6, 25125 }, --Minor Mana Oil / 160
{ 7, 25124 }, --Minor Wizard Oil / 55
}
},
{
name = ALIL["Wands"],
[NORMAL_DIFF] = {
{ 1, 14810 }, --Greater Mystic Wand / 195
{ 2, 14809 }, --Lesser Mystic Wand / 175
{ 3, 14807 }, --Greater Magic Wand / 110
{ 4, 14293 }, --Lesser Magic Wand / 75
}
},
{
name = AL["Misc"],
[NORMAL_DIFF] = {
{ 1, 20051 }, --Runed Arcanite Rod / 310
{ 2, 13702 }, --Runed Truesilver Rod / 220
{ 3, 13628 }, --Runed Golden Rod / 175
{ 4, 7795 }, --Runed Silver Rod / 130
{ 5, 7421 }, --Runed Copper Rod / 5
{ 16, 15596 }, --Smoking Heart of the Mountain / 285
{ 18, 17181 }, --Enchanted Leather / 250
{ 20, 17180 }, --Enchanted Thorium / 250
}
},
{
name = ALIL["Weapon"].." - "..AL["Enhancements"],
[NORMAL_DIFF] = {
{ 1, 23804 }, --Enchant Weapon - Mighty Intellect / 320
{ 2, 20034 }, --Enchant Weapon - Crusader / 320
{ 3, 20032 }, --Enchant Weapon - Lifestealing / 320
{ 4, 22749 }, --Enchant Weapon - Spell Power / 320
{ 5, 22750 }, --Enchant Weapon - Healing Power / 320
{ 6, 23803 }, --Enchant Weapon - Mighty Spirit / 320
{ 7, 20031 }, --Enchant Weapon - Superior Striking / 320
{ 8, 20033 }, --Enchant Weapon - Unholy Weapon / 315
{ 9, 23799 }, --Enchant Weapon - Strength / 310
{ 10, 23800 }, --Enchant Weapon - Agility / 310
{ 11, 20029 }, --Enchant Weapon - Icy Chill / 305
{ 12, 13898 }, --Enchant Weapon - Fiery Weapon / 285
{ 13, 13943 }, --Enchant Weapon - Greater Striking / 265
{ 14, 13915 }, --Enchant Weapon - Demonslaying / 250
{ 15, 13693 }, --Enchant Weapon - Striking / 215
{ 16, 21931 }, --Enchant Weapon - Winter / 210
{ 17, 13653 }, --Enchant Weapon - Lesser Beastslayer / 195
{ 18, 13655 }, --Enchant Weapon - Lesser Elemental Slayer / 195
{ 19, 13503 }, --Enchant Weapon - Lesser Striking / 165
{ 20, 7788 }, --Enchant Weapon - Minor Striking / 120
{ 21, 7786 }, --Enchant Weapon - Minor Beastslayer / 120
}
},
{
name = ALIL["2H Weapon"].." - "..AL["Enhancements"],
[NORMAL_DIFF] = {
{ 1, 20035 }, --Enchant 2H Weapon - Major Spirit / 320
{ 2, 20036 }, --Enchant 2H Weapon - Major Intellect / 320
{ 3, 20030 }, --Enchant 2H Weapon - Superior Impact / 315
{ 4, 27837 }, --Enchant 2H Weapon - Agility / 310
{ 5, 13937 }, --Enchant 2H Weapon - Greater Impact / 260
{ 6, 13695 }, --Enchant 2H Weapon - Impact / 220
{ 7, 13529 }, --Enchant 2H Weapon - Lesser Impact / 170
{ 8, 13380 }, --Enchant 2H Weapon - Lesser Spirit / 135
{ 9, 7745 }, --Enchant 2H Weapon - Minor Impact / 130
{ 10, 7793 }, --Enchant 2H Weapon - Lesser Intellect / 130
}
},
{
name = ALIL["Cloak"].." - "..AL["Enhancements"],
[NORMAL_DIFF] = {
{ 1, 25086 }, --Enchant Cloak - Dodge / 320
{ 2, 25081 }, --Enchant Cloak - Greater Fire Resistance / 320
{ 3, 25082 }, --Enchant Cloak - Greater Nature Resistance / 320
{ 4, 25084 }, --Enchant Cloak - Subtlety / 320
{ 5, 25083 }, --Enchant Cloak - Stealth / 320
{ 6, 20015 }, --Enchant Cloak - Superior Defense / 305
{ 7, 20014 }, --Enchant Cloak - Greater Resistance / 285
{ 8, 13882 }, --Enchant Cloak - Lesser Agility / 245
{ 9, 13794 }, --Enchant Cloak - Resistance / 225
{ 10, 13746 }, --Enchant Cloak - Greater Defense / 225
{ 11, 13657 }, --Enchant Cloak - Fire Resistance / 195
{ 12, 13635 }, --Enchant Cloak - Defense / 175
{ 13, 13522 }, --Enchant Cloak - Lesser Shadow Resistance / 160
{ 14, 7861 }, --Enchant Cloak - Lesser Fire Resistance / 150
{ 15, 13421 }, --Enchant Cloak - Lesser Protection / 140
{ 16, 13419 }, --Enchant Cloak - Minor Agility / 135
{ 17, 7771 }, --Enchant Cloak - Minor Protection / 110
{ 18, 7454 }, --Enchant Cloak - Minor Resistance / 95
}
},
{
name = ALIL["Chest"].." - "..AL["Enhancements"],
[NORMAL_DIFF] = {
{ 1, 20025 }, --Enchant Chest - Greater Stats / 320
{ 2, 20028 }, --Enchant Chest - Major Mana / 310
{ 3, 20026 }, --Enchant Chest - Major Health / 295
{ 4, 13941 }, --Enchant Chest - Stats / 265
{ 5, 13917 }, --Enchant Chest - Superior Mana / 250
{ 6, 13858 }, --Enchant Chest - Superior Health / 240
{ 7, 13700 }, --Enchant Chest - Lesser Stats / 220
{ 8, 13663 }, --Enchant Chest - Greater Mana / 205
{ 9, 13640 }, --Enchant Chest - Greater Health / 180
{ 10, 13626 }, --Enchant Chest - Minor Stats / 175
{ 11, 13607 }, --Enchant Chest - Mana / 170
{ 12, 13538 }, --Enchant Chest - Lesser Absorption / 165
{ 13, 7857 }, --Enchant Chest - Health / 145
{ 14, 7776 }, --Enchant Chest - Lesser Mana / 115
{ 15, 7748 }, --Enchant Chest - Lesser Health / 105
{ 16, 7426 }, --Enchant Chest - Minor Absorption / 90
{ 17, 7443 }, --Enchant Chest - Minor Mana / 80
{ 18, 7420 }, --Enchant Chest - Minor Health / 70
}
},
{
name = ALIL["Feet"].." - "..AL["Enhancements"],
[NORMAL_DIFF] = {
{ 1, 20023 }, --Enchant Boots - Greater Agility / 315
{ 2, 20024 }, --Enchant Boots - Spirit / 295
{ 3, 20020 }, --Enchant Boots - Greater Stamina / 280
{ 4, 13935 }, --Enchant Boots - Agility / 255
{ 5, 13890 }, --Enchant Boots - Minor Speed / 245
{ 6, 13836 }, --Enchant Boots - Stamina / 235
{ 7, 13687 }, --Enchant Boots - Lesser Spirit / 210
{ 8, 13644 }, --Enchant Boots - Lesser Stamina / 190
{ 9, 13637 }, --Enchant Boots - Lesser Agility / 180
{ 10, 7867 }, --Enchant Boots - Minor Agility / 150
{ 11, 7863 }, --Enchant Boots - Minor Stamina / 150
}
},
{
name = ALIL["Hand"].." - "..AL["Enhancements"],
[NORMAL_DIFF] = {
{ 1, 25080 }, --Enchant Gloves - Superior Agility / 320
{ 2, 25073 }, --Enchant Gloves - Shadow Power / 320
{ 3, 25074 }, --Enchant Gloves - Frost Power / 320
{ 4, 25072 }, --Enchant Gloves - Threat / 320
{ 5, 25079 }, --Enchant Gloves - Healing Power / 320
{ 6, 25078 }, --Enchant Gloves - Fire Power / 320
{ 7, 20013 }, --Enchant Gloves - Greater Strength / 315
{ 8, 20012 }, --Enchant Gloves - Greater Agility / 290
{ 9, 13948 }, --Enchant Gloves - Minor Haste / 270
{ 10, 13947 }, --Enchant Gloves - Riding Skill / 270
{ 11, 13868 }, --Enchant Gloves - Advanced Herbalism / 245
{ 12, 13887 }, --Enchant Gloves - Strength / 245
{ 13, 13841 }, --Enchant Gloves - Advanced Mining / 235
{ 14, 13815 }, --Enchant Gloves - Agility / 230
{ 15, 13698 }, --Enchant Gloves - Skinning / 220
{ 16, 13617 }, --Enchant Gloves - Herbalism / 170
{ 17, 13620 }, --Enchant Gloves - Fishing / 170
{ 18, 13612 }, --Enchant Gloves - Mining / 170
}
},
{
name = ALIL["Shield"].." - "..AL["Enhancements"],
[NORMAL_DIFF] = {
{ 1, 20016 }, --Enchant Shield - Superior Spirit / 300
{ 2, 20017 }, --Enchant Shield - Greater Stamina / 285
{ 3, 13933 }, --Enchant Shield - Frost Resistance / 255
{ 4, 13905 }, --Enchant Shield - Greater Spirit / 250
{ 5, 13817 }, --Enchant Shield - Stamina / 230
{ 6, 13689 }, --Enchant Shield - Lesser Block / 215
{ 7, 13659 }, --Enchant Shield - Spirit / 200
{ 8, 13631 }, --Enchant Shield - Lesser Stamina / 175
{ 9, 13485 }, --Enchant Shield - Lesser Spirit / 155
{ 10, 13464 }, --Enchant Shield - Lesser Protection / 140
{ 11, 13378 }, --Enchant Shield - Minor Stamina / 130
}
},
{
name = ALIL["Wrist"].." - "..AL["Enhancements"],
[NORMAL_DIFF] = {
{ 1, 23802 }, --Enchant Bracer - Healing Power / 320
{ 2, 20011 }, --Enchant Bracer - Superior Stamina / 320
{ 3, 20010 }, --Enchant Bracer - Superior Strength / 315
{ 4, 23801 }, --Enchant Bracer - Mana Regeneration / 310
{ 5, 20009 }, --Enchant Bracer - Superior Spirit / 290
{ 6, 20008 }, --Enchant Bracer - Greater Intellect / 275
{ 7, 13945 }, --Enchant Bracer - Greater Stamina / 265
{ 8, 13939 }, --Enchant Bracer - Greater Strength / 260
{ 9, 13931 }, --Enchant Bracer - Deflection / 255
{ 10, 13846 }, --Enchant Bracer - Greater Spirit / 240
{ 11, 13822 }, --Enchant Bracer - Intellect / 230
{ 12, 13661 }, --Enchant Bracer - Strength / 200
{ 13, 13648 }, --Enchant Bracer - Stamina / 190
{ 14, 13646 }, --Enchant Bracer - Lesser Deflection / 190
{ 15, 13642 }, --Enchant Bracer - Spirit / 185
{ 16, 13622 }, --Enchant Bracer - Lesser Intellect / 175
{ 17, 13536 }, --Enchant Bracer - Lesser Strength / 165
{ 18, 13501 }, --Enchant Bracer - Lesser Stamina / 155
{ 19, 7859 }, --Enchant Bracer - Lesser Spirit / 145
{ 20, 7779 }, --Enchant Bracer - Minor Agility / 115
{ 21, 7782 }, --Enchant Bracer - Minor Strength / 115
{ 22, 7766 }, --Enchant Bracer - Minor Spirit / 105
{ 23, 7457 }, --Enchant Bracer - Minor Stamina / 100
{ 24, 7428 }, --Enchant Bracer - Minor Deflect / 80
{ 25, 7418 }, --Enchant Bracer - Minor Health / 70
}
},
}
}
data["Engineering"] = {
name = ALIL["Engineering"],
ContentType = PROF_CONTENT,
LoadDifficulty = NORMAL_DIFF,
TableType = PROF_ITTYPE,
CorrespondingFields = private.ENGINEERING_LINK,
items = {
{
name = AL["Armor"],
[NORMAL_DIFF] = {
{ 1, 22797 }, --Force Reactive Disk / 65
{ 3, 12903 }, --Gnomish Harm Prevention Belt / 43
{ 5, 8895 }, --Goblin Rocket Boots / 45
{ 16, 19819 }, --Voice Amplification Modulator / 58
{ 18, 12616 }, --Parachute Cloak / 45
{ 20, 12905 }, --Gnomish Rocket Boots / 45
}
},
{
name = AL["Armor"].." - "..ALIL["Head"],
[NORMAL_DIFF] = {
{ 1, 24357 }, --Bloodvine Lens / 65
{ 2, 24356 }, --Bloodvine Goggles / 65
{ 3, 19825 }, --Master Engineer / 58
{ 4, 19794 }, --Spellpower Goggles Xtreme Plus / 54
{ 5, 12622 }, --Green Lens / 49
{ 6, 12758 }, --Goblin Rocket Helmet / 47
{ 7, 12907 }, --Gnomish Mind Control Cap / 47
{ 8, 12618 }, --Rose Colored Goggles / 46
{ 9, 12617 }, --Deepdive Helmet / 46
{ 10, 12607 }, --Catseye Ultra Goggles / 44
{ 11, 12615 }, --Spellpower Goggles Xtreme / 43
{ 12, 12897 }, --Gnomish Goggles / 42
{ 13, 12594 }, --Fire Goggles / 41
{ 14, 12717 }, --Goblin Mining Helmet / 41
{ 15, 12718 }, --Goblin Construction Helmet / 41
{ 16, 3966 }, --Craftsman / 37
{ 17, 12587 }, --Bright-Eye Goggles / 35
{ 18, 3956 }, --Green Tinted Goggles / 30
{ 19, 3940 }, --Shadow Goggles / 24
{ 20, 3934 }, --Flying Tiger Goggles / 20
}
},
{
name = AL["Armor"].." - "..ALIL["Trinket"],
[NORMAL_DIFF] = {
{ 1, 19830 }, --Arcanite Dragonling / 60
{ 2, 23082 }, --Ultra-Flash Shadow Reflector / 60
{ 3, 23081 }, --Hyper-Radiant Flame Reflector / 58
{ 4, 23486 }, --Dimensional Ripper - Everlook / 55
{ 5, 23079 }, --Major Recombobulator / 55
{ 6, 23078 }, --Goblin Jumper Cables XL / 53
{ 7, 23077 }, --Gyrofreeze Ice Reflector / 52
{ 8, 23489 }, --Ultrasafe Transporter: Gadgetzan / 52
{ 9, 12624 }, --Mithril Mechanical Dragonling / 50
{ 10, 12908 }, --Goblin Dragon Gun / 48
{ 11, 12759 }, --Gnomish Death Ray / 48
{ 12, 12906 }, --Gnomish Battle Chicken / 46
{ 13, 12755 }, --Goblin Bomb Dispenser / 46
{ 14, 12902 }, --Gnomish Net-o-Matic Projector / 42
{ 15, 12899 }, --Gnomish Shrink Ray / 41
{ 16, 3969 }, --Mechanical Dragonling / 40
{ 17, 3971 }, --Gnomish Cloaking Device / 40
{ 18, 9273 }, --Goblin Jumper Cables / 33
{ 19, 3952 }, --Minor Recombobulator / 28
{ 20, 9269 }, --Gnomish Universal Remote / 25
}
},
{
name = ALIL["Weapon"].." - "..AL["Enhancements"],
[NORMAL_DIFF] = {
{ 1, 22793 }, --Biznicks 247x128 Accurascope / 60
{ 2, 12620 }, --Sniper Scope / 48
{ 3, 12597 }, --Deadly Scope / 42
{ 4, 3979 }, --Accurate Scope / 36
{ 5, 3978 }, --Standard Scope / 22
{ 6, 3977 }, --Crude Scope / 12
}
},
{
name = AL["Weapons"].." - "..ALIL["Guns"],
[NORMAL_DIFF] = {
{ 1, 22795 }, --Core Marksman Rifle / 65
{ 2, 19833 }, --Flawless Arcanite Rifle / 61
{ 3, 19796 }, --Dark Iron Rifle / 55
{ 4, 19792 }, --Thorium Rifle / 52
{ 5, 12614 }, --Mithril Heavy-bore Rifle / 44
{ 6, 12595 }, --Mithril Blunderbuss / 41
{ 7, 3954 }, --Moonsight Rifle / 29
{ 8, 3949 }, --Silver-plated Shotgun / 26
{ 9, 3939 }, --Lovingly Crafted Boomstick / 24
{ 10, 3936 }, --Deadly Blunderbuss / 21
{ 11, 3925 }, --Rough Boomstick / 10
}
},
{
name = ALIL["Projectile"].." - "..ALIL["Bullet"],
[NORMAL_DIFF] = {
{ 1, 19800 }, --Thorium Shells / 57
{ 2, 12621 }, --Mithril Gyro-Shot / 49
{ 3, 12596 }, --Hi-Impact Mithril Slugs / 42
{ 4, 3947 }, --Crafted Solid Shot / 35
{ 5, 3930 }, --Crafted Heavy Shot / 20
{ 6, 3920 }, --Crafted Light Shot / 10
}
},
{
name = ALIL["Parts"],
[NORMAL_DIFF] = {
{ 1, 19815 }, --Delicate Arcanite Converter / 58
{ 2, 19791 }, --Thorium Widget / 52
{ 3, 19788 }, --Dense Blasting Powder / 50
{ 4, 23071 }, --Truesilver Transformer / 50
{ 5, 12599 }, --Mithril Casing / 43
{ 6, 12591 }, --Unstable Trigger / 40
{ 7, 19795 }, --Thorium Tube / 39
{ 8, 12589 }, --Mithril Tube / 39
{ 9, 12585 }, --Solid Blasting Powder / 35
{ 10, 3961 }, --Gyrochronatom / 34
{ 11, 3958 }, --Iron Strut / 32
{ 12, 12584 }, --Gold Power Core / 30
{ 13, 3953 }, --Bronze Framework / 29
{ 14, 3945 }, --Heavy Blasting Powder / 25
{ 15, 3942 }, --Whirring Bronze Gizmo / 25
{ 16, 3938 }, --Bronze Tube / 21
{ 17, 3973 }, --Silver Contact / 18
{ 18, 3926 }, --Copper Modulator / 13
{ 19, 3929 }, --Coarse Blasting Powder / 15
{ 20, 3924 }, --Copper Tube / 10
{ 21, 3922 }, --Handful of Copper Bolts / 8
{ 22, 3918 }, --Rough Blasting Powder / 5
}
},
{
name = AL["Fireworks"],
[NORMAL_DIFF] = {
{ 16, 26443 }, --Cluster Launcher / 1
{ 1, 26442 }, --Firework Launcher / 1
{ 3, 26418 }, --Small Red Rocket / 1
{ 4, 26417 }, --Small Green Rocket / 1
{ 5, 26416 }, --Small Blue Rocket / 1
{ 7, 26425 }, --Red Rocket Cluster / 1
{ 8, 26424 }, --Green Rocket Cluster / 1
{ 9, 26423 }, --Blue Rocket Cluster / 1
{ 12, 23066 }, --Red Firework / 20
{ 13, 23068 }, --Green Firework / 20
{ 14, 23067 }, --Blue Firework / 20
{ 18, 26422 }, --Large Red Rocket / 1
{ 19, 26421 }, --Large Green Rocket / 1
{ 20, 26420 }, --Large Blue Rocket / 1
{ 22, 26428 }, --Large Red Rocket Cluster / 1
{ 23, 26427 }, --Large Green Rocket Cluster / 1
{ 24, 26426 }, --Large Blue Rocket Cluster / 1
{ 27, 23507 }, --Snake Burst Firework / 50
}
},
{
name = ALIL["Explosives"],
[NORMAL_DIFF] = {
{ 1, 19831 }, --Arcane Bomb / 60
{ 2, 19799 }, --Dark Iron Bomb / 57
{ 3, 19790 }, --Thorium Grenade / 55
{ 4, 23070 }, --Dense Dynamite / 45
{ 5, 12619 }, --Hi-Explosive Bomb / 47
{ 6, 12754 }, --The Big One / 45
{ 7, 3968 }, --Goblin Land Mine / 39
{ 8, 12603 }, --Mithril Frag Bomb / 43
{ 9, 12760 }, --Goblin Sapper Charge / 41
{ 10, 23069 }, --Ez-Thro Dynamite II / 40
{ 11, 3967 }, --Big Iron Bomb / 43
{ 12, 8243 }, --Flash Bomb / 37
{ 13, 3962 }, --Iron Grenade / 35
{ 14, 12586 }, --Solid Dynamite / 35
{ 15, 3955 }, --Explosive Sheep / 30
{ 16, 3950 }, --Big Bronze Bomb / 33
{ 17, 3946 }, --Heavy Dynamite / 30
{ 18, 3941 }, --Small Bronze Bomb / 29
{ 19, 8339 }, --Ez-Thro Dynamite / 25
{ 20, 3937 }, --Large Copper Bomb / 26
{ 21, 3931 }, --Coarse Dynamite / 20
{ 22, 3923 }, --Rough Copper Bomb / 14
{ 23, 3919 }, --Rough Dynamite / 10
}
},
{
name = AL["Pets"],
[NORMAL_DIFF] = {
{ 1, 19793 }, --Lifelike Mechanical Toad / 53
{ 2, 15633 }, --Lil / 41
{ 3, 15628 }, --Pet Bombling / 41
{ 4, 3928 }, --Mechanical Squirrel Box / 15
}
},
{
name = AL["Misc"],
[NORMAL_DIFF] = {
{ 1, 23080 }, --Powerful Seaforium Charge / 52
{ 2, 3972 }, --Large Seaforium Charge / 40
{ 3, 3933 }, --Small Seaforium Charge / 20
{ 5, 22704 }, --Field Repair Bot 74A / 60
{ 6, 15255 }, --Mechanical Repair Kit / 40
{ 8, 19814 }, --Masterwork Target Dummy / 55
{ 9, 3965 }, --Advanced Target Dummy / 37
{ 10, 3932 }, --Target Dummy / 17
{ 12, 28327 }, --Steam Tonk Controller / 55
{ 13, 9271 }, --Aquadynamic Fish Attractor / 30
{ 15, 12715 }, --Recipe: Goblin Rocket Fuel / 42
{ 16, 3957 }, --Ice Deflector / 31
{ 17, 3944 }, --Flame Deflector / 25
{ 19, 23129 }, --World Enlarger / 50
{ 20, 12590 }, --Gyromatic Micro-Adjustor / 35
{ 21, 3959 }, --Discombobulator Ray / 32
{ 22, 26011 }, --Tranquil Mechanical Yeti / 60
{ 23, 23096 }, --Gnomish Alarm-O-Bot / 53
{ 24, 19567 }, --Salt Shaker / 50
{ 25, 21940 }, --SnowMaster 9000 / 38
{ 26, 3963 }, --Compact Harvest Reaper Kit / 35
{ 27, 3960 }, --Portable Bronze Mortar / 33
{ 28, 6458 }, --Ornate Spyglass / 27
{ 29, 8334 }, --Practice Lock / 20
{ 30, 12895 }, --Plans: Inlaid Mithril Cylinder / 40
}
},
}
}
data["Tailoring"] = {
name = ALIL["Tailoring"],
ContentType = PROF_CONTENT,
LoadDifficulty = NORMAL_DIFF,
TableType = PROF_ITTYPE,
CorrespondingFields = private.TAILORING_LINK,
items = {
{
name = AL["Armor"].." - "..ALIL["Cloak"],
[NORMAL_DIFF] = {
{ 1, 28208 }, --Glacial Cloak / 80
{ 2, 28210 }, --Gaea's Embrace / 70
{ 3, 22870 }, --Cloak of Warding / 62
{ 4, 18418 }, --Cindercloth Cloak / 55
{ 5, 18420 }, --Brightcloth Cloak / 55
{ 6, 18422 }, --Cloak of Fire / 55
{ 7, 18409 }, --Runecloth Cloak / 53
{ 8, 3862 }, --Icy Cloak / 40
{ 9, 3861 }, --Long Silken Cloak / 37
{ 10, 8789 }, --Crimson Silk Cloak / 36
{ 11, 8786 }, --Azure Silk Cloak / 35
{ 12, 3844 }, --Heavy Woolen Cloak / 21
{ 13, 6521 }, --Pearl-clasped Cloak / 19
{ 14, 2402 }, --Woolen Cape / 16
{ 15, 2397 }, --Reinforced Linen Cape / 12
{ 16, 2387 }, --Linen Cloak / 6
}
},
{
name = AL["Armor"].." - "..ALIL["Head"],
[NORMAL_DIFF] = {
{ 1, 28481 }, --Sylvan Crown / 70
{ 2, 18452 }, --Mooncloth Circlet / 62
{ 3, 18450 }, --Wizardweave Turban / 61
{ 4, 18444 }, --Runecloth Headband / 59
{ 5, 18442 }, --Felcloth Hood / 58
{ 6, 12092 }, --Dreamweave Circlet / 50
{ 7, 12086 }, --Shadoweave Mask / 49
{ 8, 12084 }, --Red Mageweave Headband / 48
{ 9, 12081 }, --Admiral's Hat / 48
{ 10, 12072 }, --Black Mageweave Headband / 46
{ 11, 12059 }, --White Bandit Mask / 43
{ 12, 3858 }, --Shadow Hood / 34
{ 13, 3857 }, --Enchanter's Cowl / 33
{ 14, 8762 }, --Silk Headband / 32
{ 15, 8760 }, --Azure Silk Hood / 29
}
},
{
name = AL["Armor"].." - "..ALIL["Shoulder"],
[NORMAL_DIFF] = {
{ 1, 28482 }, --Sylvan Shoulders / 70 / 315
{ 2, 23663 }, --Mantle of the Timbermaw / 64 / 315
{ 3, 23665 }, --Argent Shoulders / 64 / 315
{ 4, 18453 }, --Felcloth Shoulders / 62 / 315
{ 5, 20848 }, --Flarecore Mantle / 61 / 315
{ 6, 18449 }, --Runecloth Shoulders / 61 / 315
{ 7, 18448 }, --Mooncloth Shoulders / 61 / 315
{ 8, 12078 }, --Red Mageweave Shoulders / 47 / 250
{ 9, 12076 }, --Shadoweave Shoulders / 47 / 250
{ 10, 12074 }, --Black Mageweave Shoulders / 46 / 245
{ 11, 8793 }, --Crimson Silk Shoulders / 38 / 210
{ 12, 8795 }, --Azure Shoulders / 38 / 210
{ 13, 8774 }, --Green Silken Shoulders / 36 / 200
{ 14, 3849 }, --Reinforced Woolen Shoulders / 24 / 145
{ 15, 3848 }, --Double-stitched Woolen Shoulders / 22 / 135
}
},
{
name = AL["Armor"].." - "..ALIL["Chest"],
[NORMAL_DIFF] = {
{ 1, 28207 }, --Glacial Vest / 80
{ 2, 28480 }, --Sylvan Vest / 70
{ 3, 23666 }, --Flarecore Robe / 66
{ 4, 24091 }, --Bloodvine Vest / 65
{ 5, 18457 }, --Robe of the Archmage / 62
{ 6, 18456 }, --Truefaith Vestments / 62
{ 7, 18458 }, --Robe of the Void / 62
{ 8, 22902 }, --Mooncloth Robe / 61
{ 9, 18451 }, --Felcloth Robe / 61
{ 10, 18446 }, --Wizardweave Robe / 60
{ 11, 18447 }, --Mooncloth Vest / 60
{ 12, 18436 }, --Robe of Winter Night / 57
{ 13, 18416 }, --Ghostweave Vest / 55
{ 14, 18414 }, --Brightcloth Robe / 54
{ 15, 18408 }, --Cindercloth Vest / 52
{ 16, 18407 }, --Runecloth Tunic / 52
{ 17, 18406 }, --Runecloth Robe / 52
{ 18, 18404 }, --Frostweave Robe / 51
{ 19, 18403 }, --Frostweave Tunic / 51
{ 20, 12077 }, --Simple Black Dress / 47
{ 21, 12070 }, --Dreamweave Vest / 45
{ 22, 12069 }, --Cindercloth Robe / 45
{ 23, 12056 }, --Red Mageweave Vest / 43
{ 24, 12055 }, --Shadoweave Robe / 43
{ 25, 12050 }, --Black Mageweave Robe / 42
{ 26, 12048 }, --Black Mageweave Vest / 41
{ 27, 8802 }, --Crimson Silk Robe / 41
{ 28, 8770 }, --Robe of Power / 38
{ 29, 8791 }, --Crimson Silk Vest / 37
{ 30, 12091 }, --White Wedding Dress / 35
{ 101, 12093 }, --Tuxedo Jacket / 35
{ 102, 8764 }, --Earthen Vest / 34
{ 103, 8784 }, --Green Silk Armor / 33
{ 104, 6692 }, --Robes of Arcana / 30
{ 105, 3859 }, --Azure Silk Vest / 30
{ 106, 6690 }, --Lesser Wizard's Robe / 27
{ 107, 7643 }, --Greater Adept's Robe / 23
{ 108, 8467 }, --White Woolen Dress / 22
{ 109, 2403 }, --Gray Woolen Robe / 21
{ 110, 7639 }, --Blue Overalls / 20
{ 111, 2399 }, --Green Woolen Vest / 17
{ 112, 2395 }, --Barbaric Linen Vest / 14
{ 113, 7633 }, --Blue Linen Robe / 14
{ 114, 7629 }, --Red Linen Vest / 12
{ 115, 7630 }, --Blue Linen Vest / 12
{ 116, 8465 }, --Simple Dress / 10
{ 117, 7624 }, --White Linen Robe / 10
{ 118, 2389 }, --Red Linen Robe / 10
{ 119, 7623 }, --Brown Linen Robe / 10
{ 120, 2385 }, --Brown Linen Vest / 8
{ 121, 26407 }, --Festival Suit / 1
{ 122, 26403 }, --Festival Dress / 1
},
},
{
name = AL["Armor"].." - "..ALIL["Feet"],
[NORMAL_DIFF] = {
{ 1, 24093 }, --Bloodvine Boots / 65
{ 2, 24903 }, --Runed Stygian Boots / 63
{ 3, 23664 }, --Argent Boots / 58
{ 4, 18437 }, --Felcloth Boots / 57
{ 5, 19435 }, --Mooncloth Boots / 56
{ 6, 18423 }, --Runecloth Boots / 56
{ 7, 12088 }, --Cindercloth Boots / 49
{ 8, 12082 }, --Shadoweave Boots / 48
{ 9, 12073 }, --Black Mageweave Boots / 46
{ 10, 3860 }, --Boots of the Enchanter / 35
{ 11, 3856 }, --Spider Silk Slippers / 28
{ 12, 3855 }, --Spidersilk Boots / 25
{ 13, 3847 }, --Red Woolen Boots / 20
{ 14, 2401 }, --Woolen Boots / 19
{ 15, 3845 }, --Soft-soled Linen Boots / 16
{ 16, 2386 }, --Linen Boots / 13
{ 17, 12045 }, --Simple Linen Boots / 9
}
},
{
name = AL["Armor"].." - "..ALIL["Hand"],
[NORMAL_DIFF] = {
{ 1, 28205 }, --Glacial Gloves / 80
{ 2, 22869 }, --Mooncloth Gloves / 62
{ 3, 22867 }, --Felcloth Gloves / 62
{ 4, 20849 }, --Flarecore Gloves / 62
{ 5, 22868 }, --Inferno Gloves / 62
{ 6, 18454 }, --Gloves of Spell Mastery / 62
{ 7, 18417 }, --Runecloth Gloves / 55
{ 8, 18415 }, --Brightcloth Gloves / 54
{ 9, 18413 }, --Ghostweave Gloves / 54
{ 10, 18412 }, --Cindercloth Gloves / 54
{ 11, 18411 }, --Frostweave Gloves / 53
{ 12, 12071 }, --Shadoweave Gloves / 45
{ 13, 12066 }, --Red Mageweave Gloves / 45
{ 14, 12067 }, --Dreamweave Gloves / 45
{ 15, 12053 }, --Black Mageweave Gloves / 43
{ 16, 8804 }, --Crimson Silk Gloves / 42
{ 17, 8782 }, --Truefaith Gloves / 30
{ 18, 8780 }, --Hands of Darkness / 29
{ 19, 3854 }, --Azure Silk Gloves / 29
{ 20, 3852 }, --Gloves of Meditation / 26
{ 21, 3868 }, --Phoenix Gloves / 25
{ 22, 3843 }, --Heavy Woolen Gloves / 17
{ 23, 3840 }, --Heavy Linen Gloves / 10
}
},
{
name = AL["Armor"].." - "..ALIL["Legs"],
[NORMAL_DIFF] = {
{ 1, 23667 }, --Flarecore Leggings / 70
{ 2, 24092 }, --Bloodvine Leggings / 65
{ 3, 24901 }, --Runed Stygian Leggings / 63
{ 4, 18440 }, --Mooncloth Leggings / 58
{ 5, 18439 }, --Brightcloth Pants / 58
{ 6, 18441 }, --Ghostweave Pants / 58
{ 7, 18438 }, --Runecloth Pants / 57
{ 8, 18424 }, --Frostweave Pants / 56
{ 9, 18434 }, --Cindercloth Pants / 56
{ 10, 18419 }, --Felcloth Pants / 55
{ 11, 18421 }, --Wizardweave Leggings / 55
{ 12, 12060 }, --Red Mageweave Pants / 43
{ 13, 12052 }, --Shadoweave Pants / 42
{ 14, 12049 }, --Black Mageweave Leggings / 41
{ 15, 8799 }, --Crimson Silk Pantaloons / 39
{ 16, 12089 }, --Tuxedo Pants / 35
{ 17, 8758 }, --Azure Silk Pants / 28
{ 18, 3851 }, --Phoenix Pants / 25
{ 19, 12047 }, --Colorful Kilt / 24
{ 20, 3850 }, --Heavy Woolen Pants / 22
{ 21, 12046 }, --Simple Kilt / 15
{ 22, 3842 }, --Handstitched Linen Britches / 14
{ 23, 3914 }, --Brown Linen Pants / 10
{ 24, 12044 }, --Simple Linen Pants / 7
}
},
{
name = AL["Armor"].." - "..ALIL["Body"],
[NORMAL_DIFF] = {
{ 1, 12085 }, --Tuxedo Shirt / 1 / 245
{ 2, 12080 }, --Pink Mageweave Shirt / 47 / 240
{ 3, 12075 }, --Lavender Mageweave Shirt / 46 / 235
{ 4, 12064 }, --Orange Martial Shirt / 40 / 225
{ 5, 12061 }, --Orange Mageweave Shirt / 43 / 220
{ 6, 3873 }, --Black Swashbuckler's Shirt / 40 / 210
{ 7, 21945 }, --Green Holiday Shirt / 40 / 200
{ 8, 3872 }, --Rich Purple Silk Shirt / 37 / 195
{ 9, 8489 }, --Red Swashbuckler's Shirt / 35 / 185
{ 10, 3871 }, --Formal White Shirt / 34 / 180
{ 11, 8483 }, --White Swashbuckler's Shirt / 32 / 170
{ 12, 3870 }, --Dark Silk Shirt / 31 / 165
{ 13, 7893 }, --Stylish Green Shirt / 25 / 145
{ 14, 3869 }, --Bright Yellow Shirt / 27 / 145
{ 15, 7892 }, --Stylish Blue Shirt / 25 / 145
{ 16, 3866 }, --Stylish Red Shirt / 22 / 135
{ 17, 2406 }, --Gray Woolen Shirt / 20 / 110
{ 18, 2396 }, --Green Linen Shirt / 14 / 95
{ 19, 2394 }, --Blue Linen Shirt / 10 / 65
{ 20, 2392 }, --Red Linen Shirt / 10 / 65
{ 21, 2393 }, --White Linen Shirt / 7 / 35
{ 22, 3915 }, --Brown Linen Shirt / 7 / 35
}
},
{
name = AL["Armor"].." - "..ALIL["Waist"],
[NORMAL_DIFF] = {
{ 1, 24902 }, --Runed Stygian Belt / 63 / 315
{ 2, 22866 }, --Belt of the Archmage / 62 / 315
{ 3, 23662 }, --Wisdom of the Timbermaw / 58 / 305
{ 4, 18410 }, --Ghostweave Belt / 53 / 280
{ 5, 18402 }, --Runecloth Belt / 51 / 270
{ 6, 3864 }, --Star Belt / 40 / 220
{ 7, 8797 }, --Earthen Silk Belt / 39 / 215
{ 8, 3863 }, --Spider Belt / 36 / 200
{ 9, 8772 }, --Crimson Silk Belt / 35 / 195
{ 10, 8766 }, --Azure Silk Belt / 35 / 195
{ 11, 8776 }, --Linen Belt / 9 / 50
}
},
{
name = AL["Armor"].." - "..ALIL["Wrist"],
[NORMAL_DIFF] = {
{ 1, 28209 }, --Glacial Wrists / 80 / 315
{ 2, 22759 }, --Flarecore Wraps / 64 / 320
{ 3, 3841 }, --Green Linen Bracers / 12 / 85
}
},
{
name = ALIL["Bag"],
[NORMAL_DIFF] = {
{ 1, 18455 }, --Bottomless Bag / 62 / 315
{ 2, 18445 }, --Mooncloth Bag / 60 / 315
{ 3, 18405 }, --Runecloth Bag / 52 / 275
{ 4, 12079 }, --Red Mageweave Bag / 35 / 250
{ 5, 12065 }, --Mageweave Bag / 35 / 240
{ 6, 6695 }, --Black Silk Pack / 25 / 205
{ 7, 6693 }, --Green Silk Pack / 25 / 195
{ 8, 3813 }, --Small Silk Pack / 25 / 170
{ 9, 6688 }, --Red Woolen Bag / 15 / 140
{ 10, 3758 }, --Green Woolen Bag / 15 / 120
{ 11, 3757 }, --Woolen Bag / 15 / 105
{ 12, 6686 }, --Red Linen Bag / 5 / 95
{ 13, 3755 }, --Linen Bag / 5 / 70
{ 16, 27725 }, --Satchel of Cenarius / 65 / 315
{ 17, 27724 }, --Cenarion Herb Bag / 55 / 290
{ 19, 27660 }, --Big Bag of Enchantment / 65 / 315
{ 20, 27659 }, --Enchanted Runecloth Bag / 55 / 290
{ 21, 27658 }, --Enchanted Mageweave Pouch / 45 / 240
{ 23, 26087 }, --Core Felcloth Bag / 60 / 315
{ 24, 26086 }, --Felcloth Bag / 57 / 300
{ 25, 26085 }, --Soul Pouch / 52 / 275
}
},
{
name = AL["Misc"],
[NORMAL_DIFF] = {
{ 1, 18560 }, --Mooncloth / 55 / 290
{ 3, 18401 }, --Bolt of Runecloth / 55 / 255
{ 4, 3865 }, --Bolt of Mageweave / 45 / 180
{ 5, 3839 }, --Bolt of Silk Cloth / 35 / 135
{ 6, 2964 }, --Bolt of Woolen Cloth / 25 / 90
{ 7, 2963 }, --Bolt of Linen Cloth / 10 / 25
}
},
}
}
data["Leatherworking"] = {
name = ALIL["Leatherworking"],
ContentType = PROF_CONTENT,
LoadDifficulty = NORMAL_DIFF,
TableType = PROF_ITTYPE,
CorrespondingFields = private.LEATHERWORKING_LINK,
items = {
{
name = AL["Armor"].." - "..ALIL["Cloak"],
[NORMAL_DIFF] = {
{ 1, 22927 }, --Hide of the Wild / 62 / 320
{ 2, 22928 }, --Shifting Cloak / 62 / 320
{ 3, 22926 }, --Chromatic Cloak / 62 / 320
{ 4, 19093 }, --Onyxia Scale Cloak / 60 / 320
{ 5, 10574 }, --Wild Leather Cloak / 50 / 270
{ 6, 10562 }, --Big Voodoo Cloak / 48 / 260
{ 7, 7153 }, --Guardian Cloak / 37 / 205
{ 8, 9198 }, --Frost Leather Cloak / 36 / 200
{ 9, 3760 }, --Hillman's Cloak / 30 / 170
{ 10, 2168 }, --Dark Leather Cloak / 22 / 135
{ 11, 9070 }, --Black Whelp Cloak / 20 / 125
{ 12, 7953 }, --Deviate Scale Cloak / 18 / 120
{ 13, 2159 }, --Fine Leather Cloak / 15 / 105
{ 14, 2162 }, --Embossed Leather Cloak / 13 / 90
{ 15, 9058 }, --Handstitched Leather Cloak / 9 / 40
}
},
{
name = AL["Armor"].." - "..ALIL["Chest"],
[LEATHER_DIFF] = {
{ 1, 28219 }, --Polar Tunic / 80 / 320
{ 2, 24121 }, --Primal Batskin Jerkin / 65 / 320
{ 3, 24124 }, --Blood Tiger Breastplate / 65 / 320
{ 4, 19102 }, --Runic Leather Armor / 62 / 320
{ 5, 19104 }, --Frostsaber Tunic / 62 / 320
{ 6, 19098 }, --Wicked Leather Armor / 61 / 320
{ 7, 19095 }, --Living Breastplate / 60 / 320
{ 8, 19086 }, --Ironfeather Breastplate / 58 / 310
{ 9, 19081 }, --Chimeric Vest / 58 / 310
{ 10, 19076 }, --Volcanic Breastplate / 57 / 305
{ 11, 19079 }, --Stormshroud Armor / 57 / 305
{ 12, 19068 }, --Warbear Harness / 55 / 295
{ 13, 10647 }, --Feathered Breastplate / 50 / 270
{ 14, 10544 }, --Wild Leather Vest / 45 / 245
{ 15, 10520 }, --Big Voodoo Robe / 43 / 235
{ 16, 10499 }, --Nightscape Tunic / 41 / 225
{ 17, 6661 }, --Barbaric Harness / 38 / 210
{ 18, 3773 }, --Guardian Armor / 35 / 195
{ 19, 9197 }, --Green Whelp Armor / 35 / 195
{ 20, 9196 }, --Dusky Leather Armor / 35 / 195
{ 21, 6704 }, --Thick Murloc Armor / 34 / 190
{ 22, 4096 }, --Raptor Hide Harness / 33 / 185
{ 23, 3772 }, --Green Leather Armor / 31 / 175
{ 24, 2166 }, --Toughened Leather Armor / 24 / 145
{ 25, 24940 }, --Black Whelp Tunic / 20 / 125
{ 26, 3762 }, --Hillman's Leather Vest / 20 / 125
{ 27, 2169 }, --Dark Leather Tunic / 20 / 125
{ 28, 6703 }, --Murloc Scale Breastplate / 19 / 125
{ 29, 8322 }, --Moonglow Vest / 18 / 115
{ 30, 3761 }, --Fine Leather Tunic / 17 / 115
{ 101, 2163 }, --White Leather Jerkin / 13 / 90
{ 102, 2160 }, --Embossed Leather Vest / 12 / 70
{ 103, 7126 }, --Handstitched Leather Vest / 8 / 40
},
[MAIL_DIFF] = {
{ 1, 28222 }, --Icy Scale Breastplate / 80 / 320
{ 2, 24703 }, --Dreamscale Breastplate / 68 / 320
{ 3, 24851 }, --Sandstalker Breastplate / 62 / 320
{ 4, 24848 }, --Spitfire Breastplate / 62 / 320
{ 5, 19054 }, --Red Dragonscale Breastplate / 61 / 320
{ 6, 19085 }, --Black Dragonscale Breastplate / 58 / 310
{ 7, 19077 }, --Blue Dragonscale Breastplate / 57 / 305
{ 8, 19051 }, --Heavy Scorpid Vest / 53 / 285
{ 9, 19050 }, --Green Dragonscale Breastplate / 52 / 280
{ 10, 10650 }, --Dragonscale Breastplate / 51 / 275
{ 11, 10525 }, --Tough Scorpid Breastplate / 44 / 240
{ 12, 10511 }, --Turtle Scale Breastplate / 42 / 230
},
},
{
name = AL["Armor"].." - "..ALIL["Feet"],
[LEATHER_DIFF] = {
{ 1, 28473 }, --Bramblewood Boots / 70 / 320
{ 2, 22922 }, --Mongoose Boots / 62 / 320
{ 3, 20853 }, --Corehound Boots / 59 / 315
{ 4, 23705 }, --Dawn Treaders / 58 / 310
{ 5, 19063 }, --Chimeric Boots / 55 / 295
{ 6, 19066 }, --Frostsaber Boots / 55 / 295
{ 7, 10566 }, --Wild Leather Boots / 49 / 265
{ 8, 10558 }, --Nightscape Boots / 47 / 255
{ 9, 9207 }, --Dusky Boots / 40 / 220
{ 10, 9208 }, --Swift Boots / 40 / 220
{ 11, 2167 }, --Dark Leather Boots / 20 / 125
{ 12, 2158 }, --Fine Leather Boots / 18 / 120
{ 13, 2161 }, --Embossed Leather Boots / 15 / 85
{ 14, 2149 }, --Handstitched Leather Boots / 8 / 40
},
[MAIL_DIFF] = {
{ 1, 20855 }, --Black Dragonscale Boots / 61 / 320
{ 2, 10554 }, --Tough Scorpid Boots / 47 / 255
},
},
{
name = AL["Armor"].." - "..ALIL["Hand"],
[LEATHER_DIFF] = {
{ 1, 28220 }, --Polar Gloves / 80 / 320
{ 2, 24122 }, --Primal Batskin Gloves / 65 / 320
{ 3, 23704 }, --Timbermaw Brawlers / 64 / 320
{ 4, 26279 }, --Stormshroud Gloves / 62 / 320
{ 5, 19087 }, --Frostsaber Gloves / 59 / 315
{ 6, 19084 }, --Devilsaur Gauntlets / 58 / 310
{ 7, 19055 }, --Runic Leather Gauntlets / 54 / 290
{ 8, 19053 }, --Chimeric Gloves / 53 / 285
{ 9, 19049 }, --Wicked Leather Gauntlets / 52 / 280
{ 10, 10630 }, --Gauntlets of the Sea / 46 / 250
{ 11, 22711 }, --Shadowskin Gloves / 40 / 210
{ 12, 7156 }, --Guardian Gloves / 38 / 210
{ 13, 21943 }, --Gloves of the Greatfather / 38 / 210
{ 14, 3771 }, --Barbaric Gloves / 30 / 170
{ 15, 9149 }, --Heavy Earthen Gloves / 29 / 170
{ 16, 3764 }, --Hillman's Leather Gloves / 29 / 170
{ 17, 9148 }, --Pilferer's Gloves / 28 / 165
{ 18, 3770 }, --Toughened Leather Gloves / 27 / 160
{ 19, 9146 }, --Herbalist's Gloves / 27 / 160
{ 20, 3765 }, --Dark Leather Gloves / 26 / 155
{ 21, 9145 }, --Fletcher's Gloves / 25 / 150
{ 22, 9074 }, --Nimble Leather Gloves / 24 / 145
{ 23, 9072 }, --Red Whelp Gloves / 24 / 145
{ 24, 7954 }, --Deviate Scale Gloves / 21 / 130
{ 25, 2164 }, --Fine Leather Gloves / 15 / 105
{ 26, 3756 }, --Embossed Leather Gloves / 13 / 85
},
[MAIL_DIFF] = {
{ 1, 28223 }, --Icy Scale Gauntlets / 80 / 320
{ 2, 23708 }, --Chromatic Gauntlets / 70 / 320
{ 3, 24847 }, --Spitfire Gauntlets / 62 / 320
{ 4, 24850 }, --Sandstalker Gauntlets / 62 / 320
{ 5, 24655 }, --Green Dragonscale Gauntlets / 56 / 300
{ 6, 19064 }, --Heavy Scorpid Gauntlet / 55 / 295
{ 7, 10542 }, --Tough Scorpid Gloves / 45 / 245
{ 8, 10619 }, --Dragonscale Gauntlets / 45 / 245
{ 9, 10509 }, --Turtle Scale Gloves / 41 / 225
},
},
{
name = AL["Armor"].." - "..ALIL["Head"],
[LEATHER_DIFF] = {
{ 1, 28472 }, --Bramblewood Helm / 70 / 320
{ 2, 20854 }, --Molten Helm / 60 / 320
{ 3, 19082 }, --Runic Leather Headband / 58 / 310
{ 4, 19071 }, --Wicked Leather Headband / 56 / 300
{ 5, 10632 }, --Helm of Fire / 50 / 270
{ 6, 10621 }, --Wolfshead Helm / 45 / 245
{ 7, 10546 }, --Wild Leather Helmet / 45 / 245
{ 8, 10531 }, --Big Voodoo Mask / 44 / 240
{ 9, 10507 }, --Nightscape Headband / 41 / 225
{ 10, 10490 }, --Comfortable Leather Hat / 40 / 220
},
[MAIL_DIFF] = {
{ 1, 19088 }, --Heavy Scorpid Helm / 59 / 315
{ 2, 10570 }, --Tough Scorpid Helm / 50 / 270
{ 3, 10552 }, --Turtle Scale Helm / 46 / 250
},
},
{
name = AL["Armor"].." - "..ALIL["Legs"],
[LEATHER_DIFF] = {
{ 1, 19097 }, --Devilsaur Leggings / 60 / 320
{ 2, 19091 }, --Runic Leather Pants / 60 / 320
{ 3, 19083 }, --Wicked Leather Pants / 58 / 310
{ 4, 19074 }, --Frostsaber Leggings / 57 / 305
{ 5, 19080 }, --Warbear Woolies / 57 / 305
{ 6, 19078 }, --Living Leggings / 57 / 305
{ 7, 19073 }, --Chimeric Leggings / 56 / 300
{ 8, 19067 }, --Stormshroud Pants / 55 / 295
{ 9, 19059 }, --Volcanic Leggings / 54 / 290
{ 10, 10572 }, --Wild Leather Leggings / 50 / 270
{ 11, 10560 }, --Big Voodoo Pants / 47 / 260
{ 12, 10548 }, --Nightscape Pants / 46 / 250
{ 13, 7149 }, --Barbaric Leggings / 34 / 190
{ 14, 9195 }, --Dusky Leather Leggings / 33 / 185
{ 15, 7147 }, --Guardian Pants / 32 / 180
{ 16, 7135 }, --Dark Leather Pants / 23 / 140
{ 17, 7133 }, --Fine Leather Pants / 21 / 130
{ 18, 9068 }, --Light Leather Pants / 19 / 125
{ 19, 3759 }, --Embossed Leather Pants / 15 / 105
{ 20, 9064 }, --Rugged Leather Pants / 11 / 65
{ 21, 2153 }, --Handstitched Leather Pants / 10 / 45
},
[MAIL_DIFF] = {
{ 1, 19107 }, --Black Dragonscale Leggings / 62 / 320
{ 2, 24654 }, --Blue Dragonscale Leggings / 60 / 320
{ 3, 19075 }, --Heavy Scorpid Leggings / 57 / 305
{ 4, 19060 }, --Green Dragonscale Leggings / 54 / 290
{ 5, 10568 }, --Tough Scorpid Leggings / 49 / 265
{ 6, 10556 }, --Turtle Scale Leggings / 47 / 255
},
},
{
name = AL["Armor"].." - "..ALIL["Shoulder"],
[LEATHER_DIFF] = {
{ 1, 24125 }, --Blood Tiger Shoulders / 65 / 320
{ 2, 23706 }, --Golden Mantle of the Dawn / 64 / 320
{ 3, 19103 }, --Runic Leather Shoulders / 62 / 320
{ 4, 19101 }, --Volcanic Shoulders / 61 / 320
{ 5, 19090 }, --Stormshroud Shoulders / 59 / 315
{ 6, 19061 }, --Living Shoulders / 54 / 290
{ 7, 19062 }, --Ironfeather Shoulders / 54 / 290
{ 8, 10529 }, --Wild Leather Shoulders / 44 / 240
{ 9, 10516 }, --Nightscape Shoulders / 42 / 230
{ 10, 7151 }, --Barbaric Shoulders / 35 / 195
{ 11, 3769 }, --Dark Leather Shoulders / 28 / 165
{ 12, 9147 }, --Earthen Leather Shoulders / 27 / 160
{ 13, 3768 }, --Hillman's Shoulders / 26 / 155
},
[MAIL_DIFF] = {
{ 1, 19100 }, --Heavy Scorpid Shoulders / 61 / 320
{ 2, 19094 }, --Black Dragonscale Shoulders / 60 / 320
{ 3, 19089 }, --Blue Dragonscale Shoulders / 59 / 315
{ 4, 10564 }, --Tough Scorpid Shoulders / 48 / 260
},
},
{
name = AL["Armor"].." - "..ALIL["Waist"],
[LEATHER_DIFF] = {
{ 1, 23709 }, --Corehound Belt / 70 / 320
{ 2, 23710 }, --Molten Belt / 70 / 320
{ 3, 28474 }, --Bramblewood Belt / 70 / 320
{ 4, 23707 }, --Lava Belt / 66 / 320
{ 5, 22921 }, --Girdle of Insight / 62 / 320
{ 6, 19092 }, --Wicked Leather Belt / 60 / 320
{ 7, 23703 }, --Might of the Timbermaw / 58 / 310
{ 8, 19072 }, --Runic Leather Belt / 56 / 300
{ 9, 3779 }, --Barbaric Belt / 40 / 220
{ 10, 9206 }, --Dusky Belt / 39 / 215
{ 11, 3778 }, --Gem-studded Leather Belt / 37 / 205
{ 12, 3775 }, --Guardian Belt / 34 / 190
{ 13, 4097 }, --Raptor Hide Belt / 33 / 185
{ 14, 3774 }, --Green Leather Belt / 32 / 180
{ 15, 3767 }, --Hillman's Belt / 25 / 145
{ 16, 3766 }, --Dark Leather Belt / 25 / 150
{ 17, 7955 }, --Deviate Scale Belt / 23 / 140
{ 18, 6702 }, --Murloc Scale Belt / 18 / 120
{ 19, 3763 }, --Fine Leather Belt / 16 / 110
{ 20, 3753 }, --Handstitched Leather Belt / 10 / 55
},
[MAIL_DIFF] = {
{ 1, 19070 }, --Heavy Scorpid Belt / 56 / 300
},
},
{
name = AL["Armor"].." - "..ALIL["Wrist"],
[LEATHER_DIFF] = {
{ 1, 28221 }, --Polar Bracers / 80 / 320
{ 2, 24123 }, --Primal Batskin Bracers / 65 / 320
{ 3, 19065 }, --Runic Leather Bracers / 55 / 295
{ 4, 19052 }, --Wicked Leather Bracers / 53 / 285
{ 5, 3777 }, --Guardian Leather Bracers / 39 / 215
{ 6, 9202 }, --Green Whelp Bracers / 38 / 210
{ 7, 6705 }, --Murloc Scale Bracers / 38 / 210
{ 8, 9201 }, --Dusky Bracers / 37 / 205
{ 9, 3776 }, --Green Leather Bracers / 36 / 200
{ 10, 23399 }, --Barbaric Bracers / 32 / 175
{ 11, 9065 }, --Light Leather Bracers / 14 / 100
{ 12, 9059 }, --Handstitched Leather Bracers / 9 / 40
},
[MAIL_DIFF] = {
{ 1, 28224 }, --Icy Scale Bracers / 80 / 320
{ 2, 24849 }, --Sandstalker Bracers / 62 / 320
{ 3, 22923 }, --Swift Flight Bracers / 62 / 320
{ 4, 24846 }, --Spitfire Bracers / 62 / 320
{ 5, 19048 }, --Heavy Scorpid Bracers / 51 / 275
{ 6, 10533 }, --Tough Scorpid Bracers / 44 / 240
{ 7, 10518 }, --Turtle Scale Bracers / 42 / 230
},
},
{
name = ALIL["Bag"],
[NORMAL_DIFF] = {
{ 1, 14932 }, --Thick Leather Ammo Pouch / 45 / 245
{ 2, 9194 }, --Heavy Leather Ammo Pouch / 35 / 170
{ 3, 9062 }, --Small Leather Ammo Pouch / 5 / 60
{ 5, 14930 }, --Quickdraw Quiver / 45 / 245
{ 6, 9193 }, --Heavy Quiver / 35 / 170
{ 7, 9060 }, --Light Leather Quiver / 5 / 60
{ 16, 5244 }, --Kodo Hide Bag / 5 / 70
},
},
{
name = AL["Misc"],
[NORMAL_DIFF] = {
{ 1, 22331 }, --Rugged Leather / 50 / 250
{ 2, 20650 }, --Thick Leather / 40 / 200
{ 3, 20649 }, --Heavy Leather / 30 / 150
{ 4, 20648 }, --Medium Leather / 20 / 100
{ 5, 2881 }, --Light Leather / 10 / 20
{ 7, 22727 }, --Core Armor Kit / 60 / 320
{ 8, 19058 }, --Rugged Armor Kit / 50 / 250
{ 9, 10487 }, --Thick Armor Kit / 40 / 220
{ 10, 3780 }, --Heavy Armor Kit / 30 / 170
{ 11, 2165 }, --Medium Armor Kit / 15 / 115
{ 12, 2152 }, --Light Armor Kit / 5 / 30
{ 16, 19047 }, --Cured Rugged Hide / 50 / 250
{ 17, 10482 }, --Cured Thick Hide / 40 / 200
{ 18, 3818 }, --Cured Heavy Hide / 30 / 160
{ 19, 3817 }, --Cured Medium Hide / 20 / 115
{ 20, 3816 }, --Cured Light Hide / 10 / 55
{ 22, 23190 }, --Heavy Leather Ball / 1 / 150
},
},
}
}
data["Mining"] = {
name = ALIL["Mining"],
ContentType = PROF_GATH_CONTENT,
LoadDifficulty = NORMAL_DIFF,
TableType = PROF_ITTYPE,
CorrespondingFields = private.MINING_LINK,
items = {
{
name = AL["Smelting"],
[NORMAL_DIFF] = {
{ 1, 22967 }, --Smelt Elementium / 310
{ 2, 16153 }, --Smelt Thorium / 250
{ 3, 10098 }, --Smelt Truesilver / 230
{ 4, 14891 }, --Smelt Dark Iron / 230
{ 5, 10097 }, --Smelt Mithril / 175
{ 6, 3308 }, --Smelt Gold / 170
{ 7, 3569 }, --Smelt Steel / 165
{ 8, 3307 }, --Smelt Iron / 130
{ 9, 2658 }, --Smelt Silver / 100
{ 10, 2659 }, --Smelt Bronze / 65
{ 11, 3304 }, --Smelt Tin / 50
{ 12, 2657 }, --Smelt Copper / 25
}
},
}
}
data["Herbalism"] = {
name = ALIL["Herbalism"],
ContentType = PROF_GATH_CONTENT,
LoadDifficulty = NORMAL_DIFF,
TableType = NORMAL_ITTYPE,
CorrespondingFields = private.HERBALISM_LINK,
items = {
{
name = AL["Artisan"],
[NORMAL_DIFF] = {
{ 1, 13467 }, -- Icecap
{ 2, 13466 }, -- Plaguebloom
{ 3, 13465 }, -- Mountain Silversage
{ 4, 13463 }, -- Dreamfoil
{ 5, 13464 }, -- Golden Sansam
{ 6, 8846 }, -- Gromsblood
{ 7, 8845 }, -- Ghost Mushroom
{ 8, 8839 }, -- Blindweed
{ 9, 8838 }, -- Sungrass
{ 16, 13468 }, -- Black Lotus
{ 18, 19727 }, -- Blood Scythe
{ 19, 19726 }, -- Bloodvine
}
},
{
name = AL["Expert"],
[NORMAL_DIFF] = {
{ 1, 8836 }, -- Arthas' Tears
{ 2, 8831, 8153 }, -- Purple Lotus
{ 3, 4625 }, -- Firebloom
{ 4, 3819 }, -- Wintersbite
{ 5, 3358 }, -- Khadgar's Whisker
{ 6, 3821 }, -- Goldthorn
{ 7, 3818 }, -- Fadeleaf
--{ 17, 8153 }, -- Wildvine
}
},
{
name = AL["Journeyman"],
[NORMAL_DIFF] = {
{ 1, 3357 }, -- Liferoot
{ 2, 3356 }, -- Kingsblood
{ 3, 3369 }, -- Grave Moss
{ 4, 3355 }, -- Wild Steelbloom
{ 5, 2453 }, -- Bruiseweed
{ 6, 3820 }, -- Stranglekelp
}
},
{
name = AL["Apprentice"],
[NORMAL_DIFF] = {
{ 1, 2450, 2452 }, -- Briarthorn
{ 2, 785, 2452 }, -- Mageroyal
{ 3, 2449 }, -- Earthroot
{ 4, 765 }, -- Silverleaf
{ 5, 2447 }, -- Peacebloom
--{ 16, 2452 }, -- Swiftthistle
}
},
}
}
data["Cooking"] = {
name = ALIL["Cooking"],
ContentType = PROF_SEC_CONTENT,
LoadDifficulty = NORMAL_DIFF,
TableType = PROF_ITTYPE,
CorrespondingFields = private.COOKING_LINK,
items = {
{
name = ALIL["Stamina"],
[NORMAL_DIFF] = {
{ 1, 25659 }, --Dirge / 325
{ 2, 18246 }, --Mightfish Steak / 315
{ 3, 18239 }, --Cooked Glossy Mightfish / 265
},
},
{
name = ALIL["Intellect"],
[NORMAL_DIFF] = {
{ 1, 22761 }, --Runn Tum Tuber Surprise / 315
},
},
{
name = ALIL["Agility"],
[NORMAL_DIFF] = {
{ 1, 18240 }, --Grilled Squid / 280
},
},
{
name = ALIL["Strength"],
[NORMAL_DIFF] = {
{ 1, 24801 }, --Smoked Desert Dumplings / 325
},
},
{
name = ALIL["Spirit"],
[NORMAL_DIFF] = {
{ 1, 18242 }, --Hot Smoked Bass / 280
},
},
{
name = ALIL["Stamina"].." + "..ALIL["Spirit"],
[NORMAL_DIFF] = {
{ 1, 15933 }, --Monster Omelet / 265
{ 2, 22480 }, --Tender Wolf Steak / 265
{ 3, 15915 }, --Spiced Chili Crab / 265
{ 4, 15910 }, --Heavy Kodo Stew / 240
{ 5, 21175 }, --Spider Sausage / 240
{ 6, 15855 }, --Roast Raptor / 215
{ 7, 15863 }, --Carrion Surprise / 215
{ 8, 4094 }, --Barbecued Buzzard Wing / 215
{ 9, 7213 }, --Giant Clam Scorcho / 215
{ 10, 15861 }, --Jungle Stew / 215
{ 11, 15856 }, --Hot Wolf Ribs / 215
{ 12, 3400 }, --Soothing Turtle Bisque / 215
{ 13, 15865 }, --Mystery Stew / 215
{ 14, 3399 }, --Tasty Lion Steak / 190
{ 15, 3398 }, --Hot Lion Chops / 175
{ 16, 3376 }, --Curiously Tasty Omelet / 170
{ 17, 15853 }, --Lean Wolf Steak / 165
{ 18, 6500 }, --Goblin Deviled Clams / 165
{ 19, 24418 }, --Heavy Crocolisk Stew / 160
{ 20, 3373 }, --Crocolisk Gumbo / 160
{ 21, 3397 }, --Big Bear Steak / 150
{ 22, 3377 }, --Gooey Spider Cake / 150
{ 23, 6419 }, --Lean Venison / 150
{ 24, 6418 }, --Crispy Lizard Tail / 140
{ 25, 2549 }, --Seasoned Wolf Kabob / 140
{ 26, 2547 }, --Redridge Goulash / 135
{ 27, 3372 }, --Murloc Fin Soup / 130
{ 28, 3370 }, --Crocolisk Steak / 120
{ 29, 2546 }, --Dry Pork Ribs / 120
{ 30, 2544 }, --Crab Cake / 115
{ 101, 3371 }, --Blood Sausage / 100
{ 102, 6416 }, --Strider Stew / 90
{ 103, 2542 }, --Goretusk Liver Pie / 90
{ 104, 2541 }, --Coyote Steak / 90
{ 105, 6499 }, --Boiled Clams / 90
{ 106, 6415 }, --Fillet of Frenzy / 90
{ 107, 21144 }, --Egg Nog / 75
{ 108, 6414 }, --Roasted Kodo Meat / 75
{ 109, 2795 }, --Beer Basted Boar Ribs / 60
{ 110, 2539 }, --Spiced Wolf Meat / 50
{ 111, 6412 }, --Kaldorei Spider Kabob / 50
{ 112, 15935 }, --Crispy Bat Wing / 45
{ 113, 8604 }, --Herb Baked Egg / 45
{ 114, 21143 }, --Gingerbread Cookie / 45
},
},
{
name = ALIL["Mana Per 5 Sec."],
[NORMAL_DIFF] = {
{ 1, 18243 }, --Nightfin Soup / 290
{ 2, 25954 }, --Sagefish Delight / 215
{ 3, 25704 }, --Smoked Sagefish / 120
},
},
{
name = ALIL["Health Per 5 Sec."],
[NORMAL_DIFF] = {
{ 1, 18244 }, --Poached Sunscale Salmon / 290
},
},
{
name = ALIL["Food"],
[NORMAL_DIFF] = {
{ 1, 18245 }, --Lobster Stew / 315
{ 2, 18238 }, --Spotted Yellowtail / 315
{ 3, 18247 }, --Baked Salmon / 265
{ 4, 6501 }, --Clam Chowder / 265
{ 5, 18241 }, --Filet of Redgill / 265
{ 6, 20916 }, --Mithril Headed Trout / 215
{ 7, 7828 }, --Rockscale Cod / 190
{ 8, 7755 }, --Bristle Whisker Catfish / 140
{ 9, 20626 }, --Undermine Clam Chowder / 130
{ 10, 2548 }, --Succulent Pork Ribs / 130
{ 11, 6417 }, --Dig Rat Stew / 130
{ 12, 2545 }, --Cooked Crab Claw / 125
{ 13, 2543 }, --Westfall Stew / 115
{ 14, 7827 }, --Rainbow Fin Albacore / 90
{ 15, 7754 }, --Loch Frenzy Delight / 90
{ 16, 7753 }, --Longjaw Mud Snapper / 90
{ 17, 8607 }, --Smoked Bear Meat / 80
{ 18, 6413 }, --Scorpid Surprise / 60
{ 19, 7752 }, --Slitherskin Mackerel / 45
{ 20, 2538 }, --Charred Wolf Meat / 45
{ 21, 7751 }, --Brilliant Smallfish / 45
{ 22, 2540 }, --Roasted Boar Meat / 45
},
},
{
name = AL["Special"],
[NORMAL_DIFF] = {
{ 1, 15906 }, --Dragonbreath Chili / 240
{ 2, 8238 }, --Savory Deviate Delight / 125
{ 3, 9513 }, --Thistle Tea / 100
{ 16, 13028 }, --Goldthorn Tea / 215
},
},
}
}
data["FirstAid"] = {
name = ALIL["First Aid"],
ContentType = PROF_SEC_CONTENT,
LoadDifficulty = NORMAL_DIFF,
TableType = PROF_ITTYPE,
CorrespondingFields = private.FIRSTAID_LINK,
items = {
{
name = ALIL["First Aid"],
[NORMAL_DIFF] = {
{ 1, 18630 }, --Heavy Runecloth Bandage / 290
{ 2, 18629 }, --Runecloth Bandage / 260
{ 3, 10841 }, --Heavy Mageweave Bandage / 240
{ 4, 10840 }, --Mageweave Bandage / 210
{ 5, 7929 }, --Heavy Silk Bandage / 180
{ 6, 7928 }, --Silk Bandage / 150
{ 7, 3278 }, --Heavy Wool Bandage / 115
{ 8, 3277 }, --Wool Bandage / 80
{ 9, 3276 }, --Heavy Linen Bandage / 50
{ 10, 3275 }, --Linen Bandage / 30
{ 16, 23787 }, --Powerful Anti-Venom / 300
{ 17, 7935 }, --Strong Anti-Venom / 130
{ 18, 7934 }, --Anti-Venom / 80
}
},
}
}
data["Fishing"] = {
name = ALIL["Fishing"],
ContentType = PROF_SEC_CONTENT,
LoadDifficulty = NORMAL_DIFF,
TableType = NORMAL_ITTYPE,
CorrespondingFields = private.FISHING_LINK,
items = {
{
name = ALIL["Fishing"],
[NORMAL_DIFF] = {
{ 1, 6533 }, -- Aquadynamic Fish Attractor
{ 2, 6532 }, -- Bright Baubles
{ 3, 7307 }, -- Flesh Eating Worm
{ 4, 6811 }, -- Aquadynamic Fish Lens
{ 5, 6530 }, -- Nightcrawlers
{ 16, 19971 }, -- High Test Eternium Fishing Line
{ 29, 16082 }, -- Artisan Fishing - The Way of the Lure
{ 30, 16083 }, -- Expert Fishing - The Bass and You
}
},
{
name = ALIL["Fishing Pole"],
[NORMAL_DIFF] = {
{ 1, 19970 }, -- Arcanite Fishing Pole
{ 2, 19022 }, -- Nat Pagle's Extreme Angler FC-5000
{ 3, 6367 }, -- Big Iron Fishing Pole
{ 4, 6366 }, -- Darkwood Fishing Pole
{ 5, 6365 }, -- Strong Fishing Pole
{ 6, 12225 }, -- Blump Family Fishing Pole
{ 7, 6256 }, -- Fishing Pole
}
},
{
name = AL["Fishes"],
[NORMAL_DIFF] = {
{ 1, 13888 }, -- Darkclaw Lobster
{ 2, 13890 }, -- Plated Armorfish
{ 3, 13889 }, -- Raw Whitescale Salmon
{ 4, 13754 }, -- Raw Glossy Mightfish
{ 5, 13759 }, -- Raw Nightfin Snapper
{ 6, 13758 }, -- Raw Redgill
{ 7, 4603 }, -- Raw Spotted Yellowtail
{ 8, 13756 }, -- Raw Summer Bass
{ 9, 13760 }, -- Raw Sunscale Salmon
{ 10, 7974 }, -- Zesty Clam Meat
{ 11, 21153 }, -- Raw Greater Sagefish
{ 12, 8365 }, -- Raw Mithril Head Trout
{ 13, 6362 }, -- Raw Rockscale Cod
{ 14, 6308 }, -- Raw Bristle Whisker Catfish
{ 15, 21071 }, -- Raw Sagefish
{ 16, 6317 }, -- Raw Loch Frenzy
{ 17, 6289 }, -- Raw Longjaw Mud Snapper
{ 18, 6361 }, -- Raw Rainbow Fin Albacore
{ 19, 6291 }, -- Raw Brilliant Smallfish
{ 20, 6303 }, -- Raw Slitherskin Mackerel
}
},
}
}
data["RoguePoisons"] = {
name = format("|c%s%s|r", RAID_CLASS_COLORS["ROGUE"].colorStr, ALIL["ROGUE"]),
ContentType = PROF_CLASS_CONTENT,
LoadDifficulty = NORMAL_DIFF,
TableType = PROF_ITTYPE,
CorrespondingFields = private.ROGUE_POISONS_LINK,
items = {
{
name = ALIL["Poisons"],
[NORMAL_DIFF] = {
{ 1, 11343 }, -- Instant Poison VI
{ 2, 11342 }, -- Instant Poison V
{ 3, 11341 }, -- Instant Poison IV
{ 4, 8691 }, -- Instant Poison III
{ 5, 8687 }, -- Instant Poison II
{ 6, 8681 }, -- Instant Poison
{ 8, 13230 }, -- Wound Poison IV
{ 9, 13229 }, -- Wound Poison III
{ 10, 13228 }, -- Wound Poison II
{ 11, 13220 }, -- Wound Poison
{ 13, 3420 }, -- Crippling Poison
{ 17, 25347 }, -- Deadly Poison V
{ 18, 11358 }, -- Deadly Poison IV
{ 19, 11357 }, -- Deadly Poison III
{ 20, 2837 }, -- Deadly Poison II
{ 21, 2835 }, -- Deadly Poison
{ 24, 11400 }, -- Mind-numbing Poison III
{ 25, 8694 }, -- Mind-numbing Poison II
{ 26, 5763 }, -- Mind-numbing Poison
{ 28, 6510 }, -- Blinding Powder
}
},
}
} | 412 | 0.527853 | 1 | 0.527853 | game-dev | MEDIA | 0.81122 | game-dev | 0.615905 | 1 | 0.615905 |
followingthefasciaplane/source-engine-diff-check | 18,424 | misc/game/server/hl2/weapon_brickbat.cpp | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose: This is the brickbat weapon
//
// $Workfile: $
// $Date: $
// $NoKeywords: $
//=============================================================================//
#include "cbase.h"
#include "npcevent.h"
#include "basehlcombatweapon.h"
#include "basecombatcharacter.h"
#include "ai_basenpc.h"
#include "AI_Memory.h"
#include "player.h"
#include "gamerules.h" // For g_pGameRules
#include "weapon_brickbat.h"
#include "grenade_brickbat.h"
#include "ammodef.h"
#include "in_buttons.h"
#include "game.h"
#include "IEffects.h"
#include "vstdlib/random.h"
#include "baseviewmodel.h"
#include "movevars_shared.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
extern ConVar sk_npc_dmg_brickbat;
extern ConVar sk_plr_dmg_brickbat;
struct BrickbatAmmo_s
{
const char *m_sClassName;
int m_nAmmoType;
int m_nMaxCarry;
const char *m_sViewModel;
const char *m_sWorldModel;
};
BrickbatAmmo_s BrickBatAmmoArray[NUM_BRICKBAT_AMMO_TYPES] =
{
{ "grenade_rockbb", BRICKBAT_ROCK, 5, "models/weapons/v_bb_bottle.mdl", "models/props_junk/Rock001a.mdl" },
{ "grenade_beerbottle", BRICKBAT_BOTTLE, 3, "models/weapons/v_bb_bottle.mdl", "models/weapons/w_bb_bottle.mdl" },
};
IMPLEMENT_SERVERCLASS_ST(CWeaponBrickbat, DT_WeaponBrickbat)
END_SEND_TABLE()
//LINK_ENTITY_TO_CLASS( weapon_brickbat, CWeaponBrickbat );
//PRECACHE_WEAPON_REGISTER(weapon_brickbat);
acttable_t CWeaponBrickbat::m_acttable[] =
{
{ ACT_RANGE_ATTACK1, ACT_RANGE_ATTACK_THROW, true },
};
IMPLEMENT_ACTTABLE(CWeaponBrickbat);
BEGIN_DATADESC( CWeaponBrickbat )
DEFINE_FIELD( m_bNeedDraw, FIELD_BOOLEAN ),
DEFINE_FIELD( m_bNeedThrow, FIELD_BOOLEAN ),
DEFINE_FIELD( m_iThrowBits, FIELD_INTEGER ),
DEFINE_FIELD( m_fNextThrowCheck, FIELD_TIME ),
DEFINE_FIELD( m_vecTossVelocity, FIELD_VECTOR ),
DEFINE_ARRAY( m_nAmmoCount, FIELD_INTEGER, NUM_BRICKBAT_AMMO_TYPES ),
DEFINE_KEYFIELD( m_iCurrentAmmoType, FIELD_INTEGER, "BrickbatType" ),
// Function Pointers
DEFINE_FUNCTION( BrickbatTouch ),
END_DATADESC()
//------------------------------------------------------------------------------
// Purpose :
// Input :
// Output :
//------------------------------------------------------------------------------
void CWeaponBrickbat::Precache( void )
{
for (int i=0;i<ARRAYSIZE(BrickBatAmmoArray);i++)
{
PrecacheModel(BrickBatAmmoArray[i].m_sWorldModel);
PrecacheModel(BrickBatAmmoArray[i].m_sViewModel);
}
UTIL_PrecacheOther("grenade_molotov");
BaseClass::Precache();
}
void CWeaponBrickbat::Spawn( void )
{
m_bNeedDraw = true;
m_bNeedThrow = false;
for (int i=0;i<NUM_BRICKBAT_AMMO_TYPES;i++)
{
m_nAmmoCount[i] = 0;
}
// Call base class first
BaseClass::Spawn();
// Deactivate the trigger bounds so we can pick it up with the physgun
CollisionProp()->UseTriggerBounds( false );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
const char *CWeaponBrickbat::GetViewModel( int viewmodelindex /*=0*/ )
{
return BrickBatAmmoArray[m_iCurrentAmmoType].m_sViewModel;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
const char *CWeaponBrickbat::GetWorldModel( void )
{
return BrickBatAmmoArray[m_iCurrentAmmoType].m_sWorldModel;
}
//------------------------------------------------------------------------------
// Purpose :
// Input :
// Output :
//------------------------------------------------------------------------------
bool CWeaponBrickbat::Deploy( void )
{
SetModel( GetViewModel() );
m_bNeedDraw = false;
m_bNeedThrow = false;
return DefaultDeploy( (char*)GetViewModel(), (char*)GetWorldModel(), ACT_VM_DRAW, (char*)GetAnimPrefix() );
}
//------------------------------------------------------------------------------
// Purpose : Override to use brickbats pickup touch function
// Input :
// Output :
//------------------------------------------------------------------------------
void CWeaponBrickbat::SetPickupTouch( void )
{
SetTouch( BrickbatTouch );
}
//-----------------------------------------------------------------------------
// Purpose: Override so give correct ammo
// Input : pOther - the entity that touched me
// Output :
//-----------------------------------------------------------------------------
void CWeaponBrickbat::BrickbatTouch( CBaseEntity *pOther )
{
// ---------------------------------------------------
// First give weapon to touching entity if allowed
// Skip ammo given portion by setting clips to zero
// and handle ammo giving here
// ---------------------------------------------------
BaseClass::DefaultTouch(pOther);
//FIXME: This ammo handling code is a bit bogus, need a real solution if brickbats are going to live
/*
// ----------------------------------------------------
// Give brickbat ammo if touching client
// ----------------------------------------------------
if (pOther->GetFlags() & FL_CLIENT)
{
CBaseCombatCharacter* pBCC = ToBaseCombatCharacter( pOther );
// Exit if game rules say I can't have any more of this ammo type.
if ( g_pGameRules->CanHaveAmmo( pBCC, m_iPrimaryAmmoType ) == false )
return;
// ------------------------------------------------
// If already owned weapon of this type remove me
// ------------------------------------------------
CWeaponBrickbat* oldWeapon = (CWeaponBrickbat*)pBCC->Weapon_OwnsThisType( GetClassname() );
// Remove physics object if is one
VPhysicsDestroyObject();
if ( ( oldWeapon != NULL ) && ( oldWeapon != this ) )
{
// Only pick up if not at max ammo amount
if (oldWeapon->m_nAmmoCount[m_iCurrentAmmoType] < BrickBatAmmoArray[m_iCurrentAmmoType].m_nMaxCarry)
{
oldWeapon->m_nAmmoCount[m_iCurrentAmmoType]++;
pBCC->GiveAmmo( 1, oldWeapon->m_iPrimaryAmmoType );
UTIL_Remove( this );
}
}
else
{
// Only pick up if not at max ammo amount
if (m_nAmmoCount[m_iCurrentAmmoType] < BrickBatAmmoArray[m_iCurrentAmmoType].m_nMaxCarry)
{
m_nAmmoCount[m_iCurrentAmmoType]++;
pBCC->GiveAmmo( 1, m_iPrimaryAmmoType );
SetThink (NULL);
}
}
// -----------------------------------------------------
// Switch to this weapon if the only weapon I own
// -----------------------------------------------------
if (!pBCC->GetActiveWeapon() && pBCC->GetActiveWeapon() != this)
{
pBCC->Weapon_Switch(oldWeapon);
}
}
*/
}
//-----------------------------------------------------------------------------
// Purpose: Gets event from anim stream and throws the object
// Input :
// Output :
//-----------------------------------------------------------------------------
void CWeaponBrickbat::Operator_HandleAnimEvent( animevent_t *pEvent, CBaseCombatCharacter *pOperator )
{
switch( pEvent->event )
{
case EVENT_WEAPON_THROW:
{
CAI_BaseNPC *pNPC = GetOwner()->MyNPCPointer();
if (!pNPC)
{
return;
}
Vector vec_target = pNPC->GetEnemyLKP();
// -----------------------------------------------------
// Get position of throw
// -----------------------------------------------------
// If owner has a hand, set position to the hand bone position
Vector launchPos;
int iBIndex = pNPC->LookupBone("Bip01 R Hand");
if (iBIndex != -1) {
Vector origin;
QAngle angles;
pNPC->GetBonePosition( iBIndex, launchPos, angles);
}
// Otherwise just set to in front of the owner
else {
Vector vFacingDir = pNPC->BodyDirection2D( );
vFacingDir = vFacingDir * 60.0;
launchPos = pNPC->GetLocalOrigin()+vFacingDir;
}
ThrowBrickbat( launchPos, m_vecTossVelocity, sk_npc_dmg_brickbat.GetFloat());
// Drop the weapon and remove as no more ammo
pNPC->Weapon_Drop( this );
UTIL_Remove( this );
}
break;
default:
BaseClass::Operator_HandleAnimEvent( pEvent, pOperator );
break;
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input :
// Output :
//-----------------------------------------------------------------------------
bool CWeaponBrickbat::ObjectInWay( void )
{
CBaseCombatCharacter *pOwner = GetOwner();
if (!pOwner)
{
return false;
}
Vector vecSrc = pOwner->Weapon_ShootPosition( );
Vector vecAiming = pOwner->BodyDirection2D( );
trace_t tr;
Vector vecEnd = vecSrc + (vecAiming * 32);
UTIL_TraceLine( vecSrc, vecEnd, MASK_SOLID, pOwner, COLLISION_GROUP_NONE, &tr );
if (tr.fraction < 1.0)
{
// Don't block on a living creature
if (tr.m_pEnt)
{
CBaseEntity *pEntity = tr.m_pEnt;
CBaseCombatCharacter *pBCC = ToBaseCombatCharacter( pEntity );
if (pBCC)
{
return false;
}
}
return true;
}
else
{
return false;
}
}
//-----------------------------------------------------------------------------
// Purpose: Override to allow throw w/o LOS
// Input :
// Output :
//-----------------------------------------------------------------------------
bool CWeaponBrickbat::WeaponLOSCondition(const Vector &ownerPos, const Vector &targetPos,bool bSetConditions)
{
// <<TODO>> should test if can throw from present location here...
return true;
}
//-----------------------------------------------------------------------------
// Purpose: Override to check throw
// Input :
// Output :
//-----------------------------------------------------------------------------
int CWeaponBrickbat::WeaponRangeAttack1Condition( float flDot, float flDist )
{
// If things haven't changed too much since last time
// just return that previously calculated value
if (gpGlobals->curtime < m_fNextThrowCheck )
{
return m_iThrowBits;
}
if ( flDist < m_fMinRange1)
{
m_iThrowBits = COND_TOO_CLOSE_TO_ATTACK;
}
else if (flDist > m_fMaxRange1)
{
m_iThrowBits = COND_TOO_FAR_TO_ATTACK;
}
else if (flDot < 0.5)
{
m_iThrowBits = COND_NOT_FACING_ATTACK;
}
// If moving, can't throw.
else if ( m_flGroundSpeed != 0 )
{
m_iThrowBits = COND_NONE;
}
else
{
// Ok we should check again as some time has passed
// This function is only used by NPC's so we can cast to a Base Monster
CAI_BaseNPC *pNPC = GetOwner()->MyNPCPointer();
CBaseEntity *pEnemy = pNPC->GetEnemy();
if (!pEnemy)
{
return COND_NONE;
}
// Get Enemy Position
Vector vecTarget;
pEnemy->CollisionProp()->NormalizedToWorldSpace( Vector( 0.5f, 0.5f, 0.0f ), &vecTarget );
// Get Toss Vector
Vector throwStart = pNPC->Weapon_ShootPosition();
Vector vecToss;
CBaseEntity* pBlocker = NULL;
float throwDist = (throwStart - vecTarget).Length();
float fGravity = GetCurrentGravity();
float throwLimit = pNPC->ThrowLimit(throwStart, vecTarget, fGravity, 35, WorldAlignMins(), WorldAlignMaxs(), pEnemy, &vecToss, &pBlocker);
// If I can make the throw (or most of the throw)
if (!throwLimit || (throwLimit != throwDist && throwLimit > 0.8*throwDist))
{
m_vecTossVelocity = vecToss;
m_iThrowBits = COND_CAN_RANGE_ATTACK1;
}
else
{
m_iThrowBits = COND_NONE;
}
}
// don't check again for a while.
m_fNextThrowCheck = gpGlobals->curtime + 0.33; // 1/3 second.
return m_iThrowBits;
}
//-----------------------------------------------------------------------------
// Purpose:
//
//
//-----------------------------------------------------------------------------
void CWeaponBrickbat::ThrowBrickbat( Vector vecSrc, Vector vecVelocity, float damage)
{
CGrenade_Brickbat *pBrickbat = (CGrenade_Brickbat*)Create( BrickBatAmmoArray[m_iCurrentAmmoType].m_sClassName, vecSrc, vec3_angle, GetOwner() );
if (!pBrickbat)
{
Msg("Brickbat type (%s) not defined!\n",BrickBatAmmoArray[m_iCurrentAmmoType].m_sClassName);
return;
}
AngularImpulse vecAngVel;
// Tumble through the air
vecAngVel.x = random->RandomFloat ( -100, -500 );
vecAngVel.z = random->RandomFloat ( -100, -500 );
vecAngVel.y = random->RandomFloat ( -100, -500 );
// If physically simulated
IPhysicsObject *pPhysicsObject = pBrickbat->VPhysicsGetObject();
if ( pPhysicsObject )
{
pPhysicsObject->AddVelocity( &vecVelocity, &vecAngVel );
}
// Otherwise
else
{
pBrickbat->SetAbsVelocity( vecVelocity );
QAngle angVel;
AngularImpulseToQAngle( vecAngVel, angVel );
pBrickbat->SetLocalAngularVelocity( angVel );
}
pBrickbat->SetThrower( GetOwner() );
pBrickbat->SetOwnerEntity( ((CBaseEntity*)GetOwner()) );
pBrickbat->SetDamage(damage);
m_nAmmoCount[m_iCurrentAmmoType]--;
m_bNeedThrow = false;
}
//-----------------------------------------------------------------------------
// Purpose:
//
//
//-----------------------------------------------------------------------------
void CWeaponBrickbat::PrimaryAttack( void )
{
CBasePlayer *pPlayer = ToBasePlayer( GetOwner() );
if (!pPlayer)
{
return;
}
SendWeaponAnim(ACT_VM_PULLBACK);
// Don't fire again until fire animation has completed
float flSequenceEndTime = gpGlobals->curtime + SequenceDuration();
pPlayer->m_flNextAttack = m_flNextPrimaryAttack = m_flNextSecondaryAttack = flSequenceEndTime;
m_bNeedThrow = true;
}
//-----------------------------------------------------------------------------
// Purpose:
//
//
//-----------------------------------------------------------------------------
void CWeaponBrickbat::Throw( void )
{
CBasePlayer *pPlayer = ToBasePlayer( GetOwner() );
if (!pPlayer)
{
return;
}
Vector vecSrc = pPlayer->WorldSpaceCenter();
Vector vecFacing = pPlayer->BodyDirection3D( );
vecSrc = vecSrc + vecFacing * 18.0;
vecSrc.z += 24.0f;
// Player may have turned to face a wall during the throw anim in which case
// we don't want to throw the SLAM into the wall
if (ObjectInWay())
{
vecSrc = pPlayer->WorldSpaceCenter() + vecFacing * 5.0;
}
Vector vecAiming = pPlayer->GetAutoaimVector( AUTOAIM_5DEGREES );
vecAiming.z += 0.20; // Raise up so passes through reticle
ThrowBrickbat(vecSrc, vecAiming*800, sk_plr_dmg_brickbat.GetFloat());
pPlayer->RemoveAmmo( 1, m_iPrimaryAmmoType );
SendWeaponAnim(ACT_VM_THROW);
// Don't fire again until fire animation has completed
float flSequenceEndTime = gpGlobals->curtime + SequenceDuration();
pPlayer->m_flNextAttack = m_flNextPrimaryAttack = m_flNextSecondaryAttack = flSequenceEndTime;
m_bNeedThrow = false;
m_bNeedDraw = true;
}
//-----------------------------------------------------------------------------
// Purpose:
//
//
//-----------------------------------------------------------------------------
void CWeaponBrickbat::SecondaryAttack( void )
{
int counter = 0;
while (counter < NUM_BRICKBAT_AMMO_TYPES)
{
m_iCurrentAmmoType = ((++m_iCurrentAmmoType)%NUM_BRICKBAT_AMMO_TYPES);
// If I've found a category with ammo stop looking
if (m_nAmmoCount[m_iCurrentAmmoType] > 0)
{
DrawAmmo();
return;
}
counter++;
}
// I'm out of all ammo types
}
//-----------------------------------------------------------------------------
// Purpose:
//
//
//-----------------------------------------------------------------------------
void CWeaponBrickbat::DrawAmmo( void )
{
CBasePlayer *pOwner = ToBasePlayer( GetOwner() );
// -------------------------------------------
// Make sure I have ammo of the current type
// -------------------------------------------
int counter = 0;
while (m_nAmmoCount[m_iCurrentAmmoType] <=0)
{
m_iCurrentAmmoType = ((++m_iCurrentAmmoType)%NUM_BRICKBAT_AMMO_TYPES);
counter++;
// ----------------------------------------------------
// No ammo of any types so drop the weapon and destroy
// ----------------------------------------------------
if (counter >= NUM_BRICKBAT_AMMO_TYPES)
{
pOwner->Weapon_Drop( this, NULL, NULL );
UTIL_Remove(this);
return;
}
}
SetModel( BrickBatAmmoArray[m_iCurrentAmmoType].m_sViewModel);
CBaseViewModel *vm = pOwner->GetViewModel();
if ( vm )
{
vm->SetModel( BrickBatAmmoArray[m_iCurrentAmmoType].m_sViewModel );
}
//Msg("Drawing %s...\n",BrickBatAmmoArray[m_iCurrentAmmoType].m_sClassName);
m_bNeedDraw = false;
SendWeaponAnim(ACT_VM_DRAW);
// Don't fire again until fire animation has completed
float flSequenceEndTime = gpGlobals->curtime + SequenceDuration();
pOwner->m_flNextAttack = m_flNextPrimaryAttack = m_flNextSecondaryAttack = flSequenceEndTime;
}
//-----------------------------------------------------------------------------
// Purpose: Override so shotgun can do mulitple reloads in a row
// Input :
// Output :
//-----------------------------------------------------------------------------
void CWeaponBrickbat::ItemPostFrame( void )
{
/* HANDY FOR DEBUG
for (int i=0;i<NUM_BRICKBAT_AMMO_TYPES;i++)
{
Msg("%i %s",m_nAmmoCount[i],BrickBatAmmoArray[i].m_sClassName);
if (i==m_iCurrentAmmoType)
{
Msg("**");
}
Msg("\n");
}
*/
CBasePlayer *pOwner = ToBasePlayer( GetOwner() );
if (!pOwner)
{
return;
}
if (m_bNeedThrow)
{
Throw();
}
else if ((pOwner->m_nButtons & IN_ATTACK2) && (m_flNextSecondaryAttack <= gpGlobals->curtime))
{
SecondaryAttack();
}
else if ((pOwner->m_nButtons & IN_ATTACK) && (m_flNextPrimaryAttack <= gpGlobals->curtime))
{
// Uses secondary ammo only
if (pOwner->GetAmmoCount(m_iPrimaryAmmoType))
{
PrimaryAttack();
}
}
else if (m_bNeedDraw)
{
DrawAmmo();
}
else
{
SendWeaponAnim( ACT_VM_IDLE );
//pOwner->m_flNextAttack = gpGlobals->curtime + SequenceDuration();
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input :
// Output :
//-----------------------------------------------------------------------------
void CWeaponBrickbat::TraceAttack( const CTakeDamageInfo &info, const Vector &vecDir, trace_t *ptr )
{
if ( info.GetDamageType() & DMG_BULLET)
{
if ( BrickBatAmmoArray[m_iCurrentAmmoType].m_nAmmoType == BRICKBAT_ROCK )
{
g_pEffects->Ricochet(ptr->endpos,ptr->plane.normal);
}
}
BaseClass::TraceAttack( info, vecDir, ptr );
}
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
CWeaponBrickbat::CWeaponBrickbat( void )
{
#ifdef _DEBUG
m_vecTossVelocity.Init();
#endif
m_fMinRange1 = 200;
m_fMaxRange1 = 1000;
}
| 412 | 0.979069 | 1 | 0.979069 | game-dev | MEDIA | 0.986506 | game-dev | 0.965655 | 1 | 0.965655 |
StefanJo3107/ASCII-Rendering-Shader-in-Unity | 16,468 | ShaderLearning/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_GlyphPairAdjustmentRecordPropertyDrawer.cs | using UnityEngine;
using UnityEngine.TextCore;
using UnityEngine.TextCore.LowLevel;
using UnityEditor;
using System.Collections;
using System.Text.RegularExpressions;
namespace TMPro.EditorUtilities
{
[CustomPropertyDrawer(typeof(TMP_GlyphPairAdjustmentRecord))]
public class TMP_GlyphPairAdjustmentRecordPropertyDrawer : PropertyDrawer
{
private bool isEditingEnabled = false;
private bool isSelectable = false;
private string m_FirstCharacter = string.Empty;
private string m_SecondCharacter = string.Empty;
private string m_PreviousInput;
static GUIContent s_CharacterTextFieldLabel = new GUIContent("Char:", "Enter the character or its UTF16 or UTF32 Unicode character escape sequence. For UTF16 use \"\\uFF00\" and for UTF32 use \"\\UFF00FF00\" representation.");
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
SerializedProperty prop_FirstAdjustmentRecord = property.FindPropertyRelative("m_FirstAdjustmentRecord");
SerializedProperty prop_SecondAdjustmentRecord = property.FindPropertyRelative("m_SecondAdjustmentRecord");
SerializedProperty prop_FirstGlyphIndex = prop_FirstAdjustmentRecord.FindPropertyRelative("m_GlyphIndex");
SerializedProperty prop_FirstGlyphValueRecord = prop_FirstAdjustmentRecord.FindPropertyRelative("m_GlyphValueRecord");
SerializedProperty prop_SecondGlyphIndex = prop_SecondAdjustmentRecord.FindPropertyRelative("m_GlyphIndex");
SerializedProperty prop_SecondGlyphValueRecord = prop_SecondAdjustmentRecord.FindPropertyRelative("m_GlyphValueRecord");
SerializedProperty prop_FontFeatureLookupFlags = property.FindPropertyRelative("m_FeatureLookupFlags");
position.yMin += 2;
float width = position.width / 2;
float padding = 5.0f;
Rect rect;
isEditingEnabled = GUI.enabled;
isSelectable = label.text == "Selectable" ? true : false;
if (isSelectable)
GUILayoutUtility.GetRect(position.width, 75);
else
GUILayoutUtility.GetRect(position.width, 55);
GUIStyle style = new GUIStyle(EditorStyles.label);
style.richText = true;
// First Glyph
GUI.enabled = isEditingEnabled;
if (isSelectable)
{
rect = new Rect(position.x + 70, position.y, position.width, 49);
float labelWidth = GUI.skin.label.CalcSize(new GUIContent("ID: " + prop_FirstGlyphIndex.intValue)).x;
EditorGUI.LabelField(new Rect(position.x + (64 - labelWidth) / 2, position.y + 60, 64f, 18f), new GUIContent("ID: <color=#FFFF80>" + prop_FirstGlyphIndex.intValue + "</color>"), style);
GUI.enabled = isEditingEnabled;
EditorGUIUtility.labelWidth = 30f;
rect = new Rect(position.x + 70, position.y + 10, (width - 70) - padding, 18);
EditorGUI.PropertyField(rect, prop_FirstGlyphValueRecord.FindPropertyRelative("m_XPlacement"), new GUIContent("OX:"));
rect.y += 20;
EditorGUI.PropertyField(rect, prop_FirstGlyphValueRecord.FindPropertyRelative("m_YPlacement"), new GUIContent("OY:"));
rect.y += 20;
EditorGUI.PropertyField(rect, prop_FirstGlyphValueRecord.FindPropertyRelative("m_XAdvance"), new GUIContent("AX:"));
//rect.y += 20;
//EditorGUI.PropertyField(rect, prop_FirstGlyphValueRecord.FindPropertyRelative("m_YAdvance"), new GUIContent("AY:"));
DrawGlyph((uint)prop_FirstGlyphIndex.intValue, new Rect(position.x, position.y, position.width, position.height), property);
}
else
{
rect = new Rect(position.x, position.y, width / 2 * 0.8f - padding, 18);
EditorGUIUtility.labelWidth = 40f;
// First Character Lookup
GUI.SetNextControlName("FirstCharacterField");
EditorGUI.BeginChangeCheck();
string firstCharacter = EditorGUI.TextField(rect, s_CharacterTextFieldLabel, m_FirstCharacter);
if (GUI.GetNameOfFocusedControl() == "FirstCharacterField")
{
if (ValidateInput(firstCharacter))
{
//Debug.Log("1st Unicode value: [" + firstCharacter + "]");
uint unicode = GetUnicodeCharacter(firstCharacter);
// Lookup glyph index
TMP_SerializedPropertyHolder propertyHolder = property.serializedObject.targetObject as TMP_SerializedPropertyHolder;
TMP_FontAsset fontAsset = propertyHolder.fontAsset;
if (fontAsset != null)
{
prop_FirstGlyphIndex.intValue = (int)fontAsset.GetGlyphIndex(unicode);
propertyHolder.firstCharacter = unicode;
}
}
}
if (EditorGUI.EndChangeCheck())
m_FirstCharacter = firstCharacter;
// First Glyph Index
rect.x += width / 2 * 0.8f;
EditorGUIUtility.labelWidth = 25f;
EditorGUI.BeginChangeCheck();
EditorGUI.PropertyField(rect, prop_FirstGlyphIndex, new GUIContent("ID:"));
if (EditorGUI.EndChangeCheck())
{
}
GUI.enabled = isEditingEnabled;
EditorGUIUtility.labelWidth = 25f;
rect = new Rect(position.x, position.y + 20, width * 0.5f - padding, 18);
EditorGUI.PropertyField(rect, prop_FirstGlyphValueRecord.FindPropertyRelative("m_XPlacement"), new GUIContent("OX"));
rect.x += width * 0.5f;
EditorGUI.PropertyField(rect, prop_FirstGlyphValueRecord.FindPropertyRelative("m_YPlacement"), new GUIContent("OY"));
rect.x = position.x;
rect.y += 20;
EditorGUI.PropertyField(rect, prop_FirstGlyphValueRecord.FindPropertyRelative("m_XAdvance"), new GUIContent("AX"));
//rect.x += width * 0.5f;
//EditorGUI.PropertyField(rect, prop_FirstGlyphAdjustment.FindPropertyRelative("m_YAdvance"), new GUIContent("AY"));
}
// Second Glyph
GUI.enabled = isEditingEnabled;
if (isSelectable)
{
float labelWidth = GUI.skin.label.CalcSize(new GUIContent("ID: " + prop_SecondGlyphIndex.intValue)).x;
EditorGUI.LabelField(new Rect(position.width / 2 + 20 + (64 - labelWidth) / 2, position.y + 60, 64f, 18f), new GUIContent("ID: <color=#FFFF80>" + prop_SecondGlyphIndex.intValue + "</color>"), style);
GUI.enabled = isEditingEnabled;
EditorGUIUtility.labelWidth = 30f;
rect = new Rect(position.width / 2 + 20 + 70, position.y + 10, (width - 70) - padding, 18);
EditorGUI.PropertyField(rect, prop_SecondGlyphValueRecord.FindPropertyRelative("m_XPlacement"), new GUIContent("OX:"));
rect.y += 20;
EditorGUI.PropertyField(rect, prop_SecondGlyphValueRecord.FindPropertyRelative("m_YPlacement"), new GUIContent("OY:"));
rect.y += 20;
EditorGUI.PropertyField(rect, prop_SecondGlyphValueRecord.FindPropertyRelative("m_XAdvance"), new GUIContent("AX:"));
//rect.y += 20;
//EditorGUI.PropertyField(rect, prop_SecondGlyphAdjustment.FindPropertyRelative("m_YAdvance"), new GUIContent("AY"));
DrawGlyph((uint)prop_SecondGlyphIndex.intValue, new Rect(position.width / 2 + 20, position.y, position.width, position.height), property);
}
else
{
rect = new Rect(position.width / 2 + 20, position.y, width / 2 * 0.8f - padding, 18);
EditorGUIUtility.labelWidth = 40f;
// Second Character Lookup
GUI.SetNextControlName("SecondCharacterField");
EditorGUI.BeginChangeCheck();
string secondCharacter = EditorGUI.TextField(rect, s_CharacterTextFieldLabel, m_SecondCharacter);
if (GUI.GetNameOfFocusedControl() == "SecondCharacterField")
{
if (ValidateInput(secondCharacter))
{
//Debug.Log("2nd Unicode value: [" + secondCharacter + "]");
uint unicode = GetUnicodeCharacter(secondCharacter);
// Lookup glyph index
TMP_SerializedPropertyHolder propertyHolder = property.serializedObject.targetObject as TMP_SerializedPropertyHolder;
TMP_FontAsset fontAsset = propertyHolder.fontAsset;
if (fontAsset != null)
{
prop_SecondGlyphIndex.intValue = (int)fontAsset.GetGlyphIndex(unicode);
propertyHolder.secondCharacter = unicode;
}
}
}
if (EditorGUI.EndChangeCheck())
m_SecondCharacter = secondCharacter;
// Second Glyph Index
rect.x += width / 2 * 0.8f;
EditorGUIUtility.labelWidth = 25f;
EditorGUI.BeginChangeCheck();
EditorGUI.PropertyField(rect, prop_SecondGlyphIndex, new GUIContent("ID:"));
if (EditorGUI.EndChangeCheck())
{
}
GUI.enabled = isEditingEnabled;
EditorGUIUtility.labelWidth = 25f;
rect = new Rect(position.width / 2 + 20, position.y + 20, width * 0.5f - padding, 18);
EditorGUI.PropertyField(rect, prop_SecondGlyphValueRecord.FindPropertyRelative("m_XPlacement"), new GUIContent("OX"));
rect.x += width * 0.5f;
EditorGUI.PropertyField(rect, prop_SecondGlyphValueRecord.FindPropertyRelative("m_YPlacement"), new GUIContent("OY"));
rect.x = position.width / 2 + 20;
rect.y += 20;
EditorGUI.PropertyField(rect, prop_SecondGlyphValueRecord.FindPropertyRelative("m_XAdvance"), new GUIContent("AX"));
//rect.x += width * 0.5f;
//EditorGUI.PropertyField(rect, prop_SecondGlyphAdjustment.FindPropertyRelative("m_YAdvance"), new GUIContent("AY"));
}
// Font Feature Lookup Flags
if (isSelectable)
{
EditorGUIUtility.labelWidth = 55f;
rect.x = position.width - 255;
rect.y += 23;
rect.width = 270; // width - 70 - padding;
FontFeatureLookupFlags flags = (FontFeatureLookupFlags)prop_FontFeatureLookupFlags.intValue;
EditorGUI.BeginChangeCheck();
flags = (FontFeatureLookupFlags)EditorGUI.EnumFlagsField(rect, new GUIContent("Options:"), flags);
if (EditorGUI.EndChangeCheck())
{
prop_FontFeatureLookupFlags.intValue = (int)flags;
}
}
}
bool ValidateInput(string source)
{
int length = string.IsNullOrEmpty(source) ? 0 : source.Length;
////Filter out unwanted characters.
Event evt = Event.current;
char c = evt.character;
if (c != '\0')
{
switch (length)
{
case 0:
break;
case 1:
if (source != m_PreviousInput)
return true;
if ((source[0] == '\\' && (c == 'u' || c == 'U')) == false)
evt.character = '\0';
break;
case 2:
case 3:
case 4:
case 5:
if ((c < '0' || c > '9') && (c < 'a' || c > 'f') && (c < 'A' || c > 'F'))
evt.character = '\0';
break;
case 6:
case 7:
case 8:
case 9:
if (source[1] == 'u' || (c < '0' || c > '9') && (c < 'a' || c > 'f') && (c < 'A' || c > 'F'))
evt.character = '\0';
// Validate input
if (length == 6 && source[1] == 'u' && source != m_PreviousInput)
return true;
break;
case 10:
if (source != m_PreviousInput)
return true;
evt.character = '\0';
break;
}
}
m_PreviousInput = source;
return false;
}
uint GetUnicodeCharacter (string source)
{
uint unicode;
if (source.Length == 1)
unicode = source[0];
else if (source.Length == 6)
unicode = (uint)TMP_TextUtilities.StringHexToInt(source.Replace("\\u", ""));
else
unicode = (uint)TMP_TextUtilities.StringHexToInt(source.Replace("\\U", ""));
return unicode;
}
void DrawGlyph(uint glyphIndex, Rect position, SerializedProperty property)
{
// Get a reference to the sprite texture
TMP_FontAsset fontAsset = property.serializedObject.targetObject as TMP_FontAsset;
if (fontAsset == null)
return;
// Check if glyph currently exists in the atlas texture.
if (!fontAsset.glyphLookupTable.TryGetValue(glyphIndex, out Glyph glyph))
return;
// Get reference to atlas texture.
int atlasIndex = fontAsset.m_AtlasTextureIndex;
Texture2D atlasTexture = fontAsset.atlasTextures.Length > atlasIndex ? fontAsset.atlasTextures[atlasIndex] : null;
if (atlasTexture == null)
return;
Material mat;
if (((GlyphRasterModes)fontAsset.atlasRenderMode & GlyphRasterModes.RASTER_MODE_BITMAP) == GlyphRasterModes.RASTER_MODE_BITMAP)
{
mat = TMP_FontAssetEditor.internalBitmapMaterial;
if (mat == null)
return;
mat.mainTexture = atlasTexture;
}
else
{
mat = TMP_FontAssetEditor.internalSDFMaterial;
if (mat == null)
return;
mat.mainTexture = atlasTexture;
mat.SetFloat(ShaderUtilities.ID_GradientScale, fontAsset.atlasPadding + 1);
}
// Draw glyph from atlas texture.
Rect glyphDrawPosition = new Rect(position.x, position.y + 2, 64, 60);
GlyphRect glyphRect = glyph.glyphRect;
float normalizedHeight = fontAsset.faceInfo.ascentLine - fontAsset.faceInfo.descentLine;
float scale = glyphDrawPosition.width / normalizedHeight;
// Compute the normalized texture coordinates
Rect texCoords = new Rect((float)glyphRect.x / atlasTexture.width, (float)glyphRect.y / atlasTexture.height, (float)glyphRect.width / atlasTexture.width, (float)glyphRect.height / atlasTexture.height);
if (Event.current.type == EventType.Repaint)
{
glyphDrawPosition.x += (glyphDrawPosition.width - glyphRect.width * scale) / 2;
glyphDrawPosition.y += (glyphDrawPosition.height - glyphRect.height * scale) / 2;
glyphDrawPosition.width = glyphRect.width * scale;
glyphDrawPosition.height = glyphRect.height * scale;
// Could switch to using the default material of the font asset which would require passing scale to the shader.
Graphics.DrawTexture(glyphDrawPosition, atlasTexture, texCoords, 0, 0, 0, 0, new Color(1f, 1f, 1f), mat);
}
}
}
} | 412 | 0.895428 | 1 | 0.895428 | game-dev | MEDIA | 0.924744 | game-dev | 0.961113 | 1 | 0.961113 |
s0bvi/goldsvet-opensource | 2,384 | casino/app/Games/LuckyNewYear/PragmaticLib/Multiple.php | <?php
namespace VanguardLTE\Games\LuckyNewYear\PragmaticLib;
class Multiple
{
public static function getBonanzaMultiple($slotArea, $gameSettings, $currentLog){
$tmp = explode(';', $gameSettings['prm']);
$tmp = explode('~', $tmp[0]);
$prm = $tmp[0]; // multiplier symbol
$prmMultipliers = explode(',',$tmp[1]); // array of possible multiplier values
// rebuild the playing field on reels
$reels = 6;
$tmpSlotArea = array_chunk($slotArea, $reels);
$currentSlotArea = [];
$k = 0;
while ($k < $reels) { // rearrange from rows to rows
$i = 0;
while ($i < $gameSettings['sh']) {
$currentSlotArea[$k][] = $tmpSlotArea[$i][$k];
$i++;
}
$k++;
}
$prmReady = [];
// go through all the coils from the end, and assign multipliers, write in the log which multiplier from which coil
foreach ($currentSlotArea as $reelKey => $reel) {
foreach (array_reverse($reel) as $symbolKey => $symbol) {
if ($symbol == $prm){
$symbolsCount = $gameSettings['sh'] - 1; // arrays start at 0. To find out how many symbols should be in the reel
$prmSymbol = $reelKey + ($reels * ($symbolsCount - $symbolKey)); // calculate position. Coil number, add to the coil position from the beginning
$prmReady[] = [
'Symbol' => $prm,
'Position' => $prmSymbol,
'Multiplier' => self::getMultiplier($currentLog,$prmMultipliers,$reelKey),
'Reel' => $reelKey
];
}
}
}
if ($prmReady) return $prmReady;
else return false;
}
private static function getMultiplier($currentLog, $prmMultipliers, $reelKey){
if ($currentLog && array_key_exists('Multipliers', $currentLog)){
foreach ($currentLog['Multipliers'] as $logMultiplier) {
if ($logMultiplier['Reel'] == $reelKey){
$multiplier = $logMultiplier['Multiplier'];
}
}
}
if (isset($multiplier)) return $multiplier;
else $multiplier = $prmMultipliers[array_rand($prmMultipliers)];
return $multiplier;
}
}
| 412 | 0.749828 | 1 | 0.749828 | game-dev | MEDIA | 0.731114 | game-dev | 0.771448 | 1 | 0.771448 |
AdaCompNUS/hyp-despot | 4,666 | src/HypDespot/src/core/builtin_policy.cpp | #include <despot/core/builtin_policy.h>
#include <despot/interface/pomdp.h>
#include <unistd.h>
using namespace std;
namespace despot {
/* =============================================================================
* BlindPolicy class
* =============================================================================*/
BlindPolicy::BlindPolicy(const DSPOMDP* model, ACT_TYPE action, ParticleLowerBound*
bound) :
DefaultPolicy(model, bound),
action_(action) {
}
ACT_TYPE BlindPolicy::Action(const vector<State*>& particles, RandomStreams& streams,
History& history) const {
return action_;
}
ValuedAction BlindPolicy::Search() {
double dummy_value = Globals::NEG_INFTY;
return ValuedAction(action_, dummy_value);
}
void BlindPolicy::Update(ACT_TYPE action, OBS_TYPE obs) {
}
/* =============================================================================
* RandomPolicy class
* =============================================================================*/
RandomPolicy::RandomPolicy(const DSPOMDP* model, ParticleLowerBound* bound) :
DefaultPolicy(model, bound) {
}
RandomPolicy::RandomPolicy(const DSPOMDP* model,
const vector<double>& action_probs,
ParticleLowerBound* bound) :
DefaultPolicy(model, bound),
action_probs_(action_probs) {
double sum = 0;
for (int i = 0; i < action_probs.size(); i++)
sum += action_probs[i];
assert(fabs(sum - 1.0) < 1.0e-8);
}
ACT_TYPE RandomPolicy::Action(const vector<State*>& particles,
RandomStreams& streams, History& history) const {
if (action_probs_.size() > 0) {
return Random::GetCategory(action_probs_, Random::RANDOM.NextDouble());
} else {
return Random::RANDOM.NextInt(model_->NumActions());
}
}
ValuedAction RandomPolicy::Search() {
double dummy_value = Globals::NEG_INFTY;
if (action_probs_.size() > 0) {
return ValuedAction(
Random::GetCategory(action_probs_, Random::RANDOM.NextDouble()),
dummy_value);
} else {
return ValuedAction(Random::RANDOM.NextInt(model_->NumActions()),
dummy_value);
}
}
void RandomPolicy::Update(ACT_TYPE action, OBS_TYPE obs) {
}
/* =============================================================================
* MajorityActionPolicy class
* =============================================================================*/
MajorityActionPolicy::MajorityActionPolicy(const DSPOMDP* model,
const StatePolicy& policy, ParticleLowerBound* bound) :
DefaultPolicy(model, bound),
policy_(policy) {
}
ACT_TYPE MajorityActionPolicy::Action(const vector<State*>& particles,
RandomStreams& streams, History& history) const {
vector<double> frequencies(model_->NumActions());
for (int i = 0; i < particles.size(); i++) {
State* particle = particles[i];
ACT_TYPE action = policy_.GetAction(*particle);
frequencies[action] += particle->weight;
}
int bestAction = 0;
double bestWeight = frequencies[0];
for (int a = 1; a < frequencies.size(); a++) {
if (bestWeight < frequencies[a]) {
bestWeight = frequencies[a];
bestAction = a;
}
}
return bestAction;
}
/* =============================================================================
* ModeStatePolicy class
* =============================================================================*/
ModeStatePolicy::ModeStatePolicy(const DSPOMDP* model,
const StateIndexer& indexer, const StatePolicy& policy,
ParticleLowerBound* bound) :
DefaultPolicy(model, bound),
indexer_(indexer),
policy_(policy) {
state_probs_.resize(indexer_.NumStates());
}
ACT_TYPE ModeStatePolicy::Action(const vector<State*>& particles,
RandomStreams& streams, History& history) const {
double maxWeight = 0;
State* mode = NULL;
for (int i = 0; i < particles.size(); i++) {
State* particle = particles[i];
int id = indexer_.GetIndex(particle);
state_probs_[id] += particle->weight;
if (state_probs_[id] > maxWeight) {
maxWeight = state_probs_[id];
mode = particle;
}
}
for (int i = 0; i < particles.size(); i++) {
state_probs_[indexer_.GetIndex(particles[i])] = 0;
}
assert(mode != NULL);
return policy_.GetAction(*mode);
}
/* =============================================================================
* MMAPStatePolicy class
* =============================================================================*/
MMAPStatePolicy::MMAPStatePolicy(const DSPOMDP* model,
const MMAPInferencer& inferencer, const StatePolicy& policy,
ParticleLowerBound* bound) :
DefaultPolicy(model, bound),
inferencer_(inferencer),
policy_(policy) {
}
ACT_TYPE MMAPStatePolicy::Action(const vector<State*>& particles,
RandomStreams& streams, History& history) const {
return policy_.GetAction(*inferencer_.GetMMAP(particles));
}
} // namespace despot
| 412 | 0.948747 | 1 | 0.948747 | game-dev | MEDIA | 0.397496 | game-dev | 0.988284 | 1 | 0.988284 |
SinlessDevil/ColliderMeshTool | 3,067 | Assets/Plugins/Zenject/Source/Providers/Decorator/DecoratorProvider.cs | using System;
using System.Collections.Generic;
using ModestTree;
namespace Zenject.Internal
{
public interface IDecoratorProvider
{
void GetAllInstances(
IProvider provider, InjectContext context, List<object> buffer);
}
[NoReflectionBaking]
public class DecoratorProvider<TContract> : IDecoratorProvider
{
readonly Dictionary<IProvider, List<object>> _cachedInstances =
new Dictionary<IProvider, List<object>>();
readonly DiContainer _container;
readonly List<Guid> _factoryBindIds = new List<Guid>();
List<IFactory<TContract, TContract>> _decoratorFactories;
#if ZEN_MULTITHREADING
readonly object _locker = new object();
#endif
public DecoratorProvider(DiContainer container)
{
_container = container;
}
public void AddFactoryId(Guid factoryBindId)
{
_factoryBindIds.Add(factoryBindId);
}
void LazyInitializeDecoratorFactories()
{
if (_decoratorFactories == null)
{
_decoratorFactories = new List<IFactory<TContract, TContract>>();
for (int i = 0; i < _factoryBindIds.Count; i++)
{
var bindId = _factoryBindIds[i];
var factory = _container.ResolveId<IFactory<TContract, TContract>>(bindId);
_decoratorFactories.Add(factory);
}
}
}
public void GetAllInstances(
IProvider provider, InjectContext context, List<object> buffer)
{
if (provider.IsCached)
{
List<object> instances;
#if ZEN_MULTITHREADING
lock (_locker)
#endif
{
if (!_cachedInstances.TryGetValue(provider, out instances))
{
instances = new List<object>();
WrapProviderInstances(provider, context, instances);
_cachedInstances.Add(provider, instances);
}
}
buffer.AllocFreeAddRange(instances);
}
else
{
WrapProviderInstances(provider, context, buffer);
}
}
void WrapProviderInstances(IProvider provider, InjectContext context, List<object> buffer)
{
LazyInitializeDecoratorFactories();
provider.GetAllInstances(context, buffer);
for (int i = 0; i < buffer.Count; i++)
{
buffer[i] = DecorateInstance(buffer[i], context);
}
}
object DecorateInstance(object instance, InjectContext context)
{
for (int i = 0; i < _decoratorFactories.Count; i++)
{
instance = _decoratorFactories[i].Create(
context.Container.IsValidating ? default(TContract) : (TContract)instance);
}
return instance;
}
}
}
| 412 | 0.931374 | 1 | 0.931374 | game-dev | MEDIA | 0.719473 | game-dev | 0.815342 | 1 | 0.815342 |
DarkstarProject/darkstar | 2,082 | scripts/zones/Dangruf_Wadi/npcs/qm4.lua | -----------------------------------
-- NPC: ??? (QM4)
-- Type: Grasswix (dice roll game part 2)
-- !pos -375.379 -2.221 445.034 191
-- Involved in quest "As Thick As Thieves"
-----------------------------------
local ID = require("scripts/zones/Dangruf_Wadi/IDs")
require("scripts/globals/npc_util")
require("scripts/globals/settings")
require("scripts/globals/quests")
-----------------------------------
function onTrade(player,npc,trade)
local thickAsThievesGamblingCS = player:getCharVar("thickAsThievesGamblingCS")
if npcUtil.tradeHas(trade, 534) then -- Trade 1x gaussbit wildgrass
if thickAsThievesGamblingCS == 3 then
local rand1 = math.random(1,999)
local rand2 = math.random(1,999)
if (rand1 > rand2) then
player:messageSpecial(ID.text.YOU_PLACE_ITEM,0,534)
player:startEvent(137,1092,0,rand1,rand2) -- complete 2/3 gamble mini quest
else
player:messageSpecial(ID.text.YOU_PLACE_ITEM,0,534)
player:startEvent(140,0,0,rand1,rand2) -- player looses
end
elseif thickAsThievesGamblingCS < 3 then -- trading out of order
player:messageSpecial(ID.text.DONT_WASTE_TIME)
elseif thickAsThievesGamblingCS > 3 then
player:messageSpecial(ID.text.BEAT_GRASSWIX)
end
end
end
function onTrigger(player,npc)
player:messageSpecial(ID.text.PLANT_EXTRACT)
end
function onEventUpdate(player,csid,option)
end
function onEventFinish(player,csid,option)
if (csid == 137 or csid == 140) and option == 2 then -- player gives up
player:confirmTrade()
player:messageSpecial(ID.text.YOU_GAVE_UP)
elseif csid == 140 and option == 1 then -- player looses dice game
player:confirmTrade()
player:messageSpecial(ID.text.GOBLIN_BEAT_YOU)
elseif csid == 137 and option == 0 then -- player wins dice game
player:confirmTrade()
player:messageSpecial(ID.text.YOU_BEAT_GOBLIN)
player:setCharVar("thickAsThievesGamblingCS",4)
end
end | 412 | 0.938459 | 1 | 0.938459 | game-dev | MEDIA | 0.957969 | game-dev | 0.934871 | 1 | 0.934871 |
dariowouters/ts-map | 2,244 | TsMap/TsItem/TsCityItem.cs | using System.IO;
using TsMap.Common;
using TsMap.Helpers;
using TsMap.Helpers.Logger;
namespace TsMap.TsItem
{
public class TsCityItem : TsItem // TODO: Add zoom levels/range to show city names and icons correctly
{
public TsCity City { get; private set; }
public ulong NodeUid { get; private set; }
public float Width { get; private set; }
public float Height { get; private set; }
public TsCityItem(TsSector sector, int startOffset) : base(sector, startOffset)
{
Valid = true;
TsCityItem825(startOffset);
}
public void TsCityItem825(int startOffset)
{
var fileOffset = startOffset + 0x34; // Set position at start of flags
Hidden = (MemoryHelper.ReadUint8(Sector.Stream, fileOffset) & 0x01) != 0;
var cityId = MemoryHelper.ReadUInt64(Sector.Stream, fileOffset + 0x05);
City = Sector.Mapper.LookupCity(cityId);
if (City == null)
{
Valid = false;
Logger.Instance.Error($"Could not find City: '{ScsToken.TokenToString(cityId)}'({cityId:X}) item uid: 0x{Uid:X}, " +
$"in {Path.GetFileName(Sector.FilePath)} @ {fileOffset} from '{Sector.GetUberFile().Entry.GetArchiveFile().GetPath()}'");
}
Width = MemoryHelper.ReadSingle(Sector.Stream, fileOffset += 0x05 + 0x08); // 0x05(flags) + 0x08(cityId)
Height = MemoryHelper.ReadSingle(Sector.Stream, fileOffset += 0x04); // 0x08(Width)
NodeUid = MemoryHelper.ReadUInt64(Sector.Stream, fileOffset += 0x04); // 0x08(height)
fileOffset += 0x08; // nodeUid
BlockSize = fileOffset - startOffset;
}
public override string ToString()
{
if (City == null) return "Error";
var country = Sector.Mapper.GetCountryByTokenName(City.Country);
var countryName = (country == null)
? City.Country
: Sector.Mapper.Localization.GetLocaleValue(country.LocalizationToken) ?? country.Name;
return $"{countryName} - {Sector.Mapper.Localization.GetLocaleValue(City.LocalizationToken) ?? City.Name}";
}
}
}
| 412 | 0.840917 | 1 | 0.840917 | game-dev | MEDIA | 0.808853 | game-dev,networking | 0.949 | 1 | 0.949 |
TBye101/MagicalLife | 1,207 | MLGUIWindows/GUI/MainMenu/Buttons/NewGameButton.cs | using MagicalLifeAPI.Asset;
using MagicalLifeAPI.Sound;
using MagicalLifeGUIWindows.GUI.New;
using MagicalLifeGUIWindows.GUI.Reusable;
using MagicalLifeGUIWindows.Properties;
using Microsoft.Xna.Framework;
namespace MagicalLifeGUIWindows.GUI.MainMenu.Buttons
{
public class NewGameButton : MonoButton
{
public NewGameButton() : base(TextureLoader.GUIMenuButton, GetLocation(), true, Resources.NewGame)
{
this.ClickEvent += this.NewGameButton_ClickEvent;
}
private void NewGameButton_ClickEvent(object sender, Reusable.Event.ClickEventArgs e)
{
FMODUtil.RaiseEvent(SoundsTable.UIClick);
NewWorldMenu.Initialize();
MainMenu.MainMenuID.PopupChild(NewWorldMenu.NewWorldMenuM);
}
private static Rectangle GetLocation()
{
int width = MainMenuLayout.ButtonWidth;
int height = MainMenuLayout.ButtonHeight;
int x = MainMenuLayout.ButtonX;
int y = MainMenuLayout.NewGameButtonY;
return new Rectangle(x, y, width, height);
}
public string GetTextureName()
{
return "MenuButton";
}
}
} | 412 | 0.74685 | 1 | 0.74685 | game-dev | MEDIA | 0.955801 | game-dev | 0.698949 | 1 | 0.698949 |
sinbad/SUQS | 29,103 | Source/SUQS/Public/SuqsProgression.h | #pragma once
#include "CoreMinimal.h"
#include "SuqsQuest.h"
#include "SuqsQuestState.h"
#include "Engine/DataTable.h"
#include "UObject/Object.h"
#include "SuqsSaveData.h"
#include "SuqsTaskState.h"
#include "SuqsParameterProvider.h"
#include "SuqsProgression.generated.h"
/// Identifies the type of quest event that has occurred, for those who want to listen in to a single event source
UENUM(BlueprintType)
enum class ESuqsProgressionEventType : uint8
{
/// Raised when the list of active quests changes (quests may not be removed from the list immediately on completion/failure)
ActiveQuestsChanged,
/// Raised when a quest is archived because it was previously completed or failed, details include quest link
QuestArchived,
/// Raised when a quest is accepted, details include quest link
QuestAccepted,
/// Raised when a quest is completed, details include quest link
QuestCompleted,
/// Raised when a quest is failed, details include quest link
QuestFailed,
/// Raised when the current objective on a quest changes, details include quest link
QuestCurrentObjectiveChanged,
/// Raised when an objective is completed, details include objective link and quest
ObjectiveCompleted,
/// Raised when an objective is failed, details include objective link and quest
ObjectiveFailed,
/// Raised when a new task has been added to the list of relevant ones to be displayed within the current objective
/// Details include task and quest
TaskAdded,
/// Raised when some detail on the task changes - progress made, time changed etc. NOT raised for status changes e.g. completion (but changes may cause them)
TaskUpdated,
/// Raised when a task has been completed, details include task and quest
TaskCompleted,
/// Raised when a task has failed, details include task and quest
TaskFailed,
/// Raised when a task has been removed from the list of relevant ones to be displayed within the current objective
/// This could be because the task has been completed/failed, or that it's optional and the objective has changed without completing
/// Details include task and quest
TaskRemoved,
/// Raised when a waypoint associated with a currently active task is moved
/// You may be interested in this if you retrieved the waypoints from a task that was added
/// Details include Waypoint
WaypointMoved,
/// Raised when a waypoint associated with a currently active task has its enabled state changed
/// You may be interested in this if you retrieved the waypoints from a task that was added
/// Details include Waypoint
WaypointEnabledOrDisabled,
};
/// Details to go with the general progression event, not all members will be valid, see ESuqsProgressionEventType
USTRUCT(BlueprintType)
struct FSuqsProgressionEventDetails
{
GENERATED_BODY()
public:
/// The event type, always present
UPROPERTY(BlueprintReadOnly)
ESuqsProgressionEventType EventType;
/// The relevant quest; only present for applicable event types
UPROPERTY(BlueprintReadOnly)
class USuqsQuestState* Quest;
/// The relevant objective; only present for applicable event types
UPROPERTY(BlueprintReadOnly)
class USuqsObjectiveState* Objective;
/// The relevant task; only present for applicable event types
UPROPERTY(BlueprintReadOnly)
class USuqsTaskState* Task;
/// The relevant waypoint; only present for applicable event types
UPROPERTY(BlueprintReadOnly)
class USuqsWaypointComponent* Waypoint;
explicit FSuqsProgressionEventDetails(ESuqsProgressionEventType EType)
: EventType(EType), Quest(nullptr), Objective(nullptr), Task(nullptr), Waypoint(nullptr)
{
}
FSuqsProgressionEventDetails(ESuqsProgressionEventType EventType, USuqsQuestState* Quest)
: EventType(EventType),
Quest(Quest),
Objective(nullptr),
Task(nullptr),
Waypoint(nullptr)
{
}
FSuqsProgressionEventDetails(ESuqsProgressionEventType EventType, USuqsObjectiveState* Objective)
: EventType(EventType),
Quest(Objective ? Objective->GetParentQuest() : nullptr),
Objective(Objective),
Task(nullptr),
Waypoint(nullptr)
{
}
FSuqsProgressionEventDetails(ESuqsProgressionEventType EventType, USuqsTaskState* Task)
: EventType(EventType),
Quest(Task ? Task->GetParentObjective()->GetParentQuest() : nullptr),
Objective(nullptr),
Task(Task),
Waypoint(nullptr)
{
}
FSuqsProgressionEventDetails(ESuqsProgressionEventType EventType, USuqsWaypointComponent* Waypoint, USuqsTaskState* Task)
: EventType(EventType),
Quest(Task ? Task->GetParentObjective()->GetParentQuest() : nullptr),
Objective(nullptr),
Task(Task),
Waypoint(Waypoint)
{
}
FSuqsProgressionEventDetails(): EventType(), Quest(nullptr), Objective(nullptr), Task(nullptr), Waypoint(nullptr)
{
}
};
DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FOnProgressionEvent, const FSuqsProgressionEventDetails&, Details);
DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FOnTaskUpdated, USuqsTaskState*, Task);
DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FOnTaskCompleted, USuqsTaskState*, Task);
DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FOnTaskFailed, USuqsTaskState*, Task);
DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FOnObjectiveCompleted, USuqsObjectiveState*, Objective);
DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FOnObjectiveFailed, USuqsObjectiveState*, Objective);
DECLARE_DYNAMIC_MULTICAST_DELEGATE(FOnActiveQuestsListChanged);
DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FOnQuestCompleted, USuqsQuestState*, Quest);
DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FOnQuestFailed, USuqsQuestState*, Quest);
DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FOnQuestAccepted, USuqsQuestState*, Quest);
DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FOnProgressionLoaded, USuqsProgression*, Progression);
DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FOnProgressParameterProvidersChanged, USuqsProgression*, Progression);
// C++ only because of non-const struct
DECLARE_DELEGATE_TwoParams(FOnPreLoad, USuqsProgression*, FSuqsSaveData&);
class USuqsWaypointComponent;
/**
* Progression holds all the state relating to all quests and their objectives/tasks for a single player.
* Add this somewhere that's useful to you, e.g. your PlayerState or GameInstance.
* And of course, you'll want to include it in your save games.
* You MUST only ever have one instance of this in your game.
* NOTE: in multiplayer games it is not advisable to build your UI around this class directly. Only
* use it directly on the server to change state, and use it via USuqsGameStateComponent. On
* clients and server, use the FSuqsProgressView to drive your UI instead, which will work everywhere.
*/
UCLASS(BlueprintType, Blueprintable)
class SUQS_API USuqsProgression : public UObject, public FTickableGameObject
{
GENERATED_BODY()
protected:
UPROPERTY()
TArray<UDataTable*> QuestDataTables;
/// Unified quest defs, combined from all entries in QuestDataTables
UPROPERTY()
TMap<FName, FSuqsQuest> QuestDefinitions;
/// Map of active quests
UPROPERTY()
TMap<FName, USuqsQuestState*> ActiveQuests;
/// Archive of completed / failed quests
UPROPERTY()
TMap<FName, USuqsQuestState*> QuestArchive;
TArray<FName> GlobalActiveBranches;
TSet<FName> OpenGates;
// Name of quest completed -> names of other quests that depend on its completion
TMultiMap<FName, FName> QuestCompletionDeps;
// Name of quest completed -> names of other quests that depend on its failure
TMultiMap<FName, FName> QuestFailureDeps;
TArray<TWeakObjectPtr<UObject>> ParameterProviders;
UPROPERTY()
USuqsNamedFormatParams* FormatParams;
bool bSuppressEvents = false;
float DefaultQuestResolveTimeDelay = 0;
float DefaultTaskResolveTimeDelay = 0;
bool bSubcribedToWaypointEvents = false;
USuqsQuestState* FindQuestState(const FName& QuestID);
const USuqsQuestState* FindQuestState(const FName& QuestID) const;
USuqsTaskState* FindTaskStatus(const FName& QuestID, const FName& TaskID);
void RebuildAllQuestData();
void AddQuestDefinitionInternal(const FSuqsQuest& Quest);
bool AutoAcceptQuests(const FName& FinishedQuestID, bool bFailed);
static void SaveToData(TMap<FName, USuqsQuestState*> Quests, FSuqsSaveData& Data);
FText FormatQuestOrTaskText(const FName& QuestID, const FName& TaskID, const FText& FormatText);
UFUNCTION()
void OnWaypointMoved(USuqsWaypointComponent* Waypoint);
UFUNCTION()
void OnWaypointEnabledChanged(USuqsWaypointComponent* Waypoint);
public:
/// Initialise this progress instance with quest definitions contained in the passed in tables
/// You should only call this once at startup. Calling it again will reset all progress data.
/// You must also call this BEFORE calling any other function
UFUNCTION(BlueprintCallable)
void InitWithQuestDataTables(TArray<UDataTable*> Tables);
/// Initialise this progress instance with quest definitions contained in all datatables found in a given content location.
/// Path must be of the form "/Game/Sub/Folder/Within/Content". Will recurse into subdirectories.
/// You must also call this BEFORE calling any other function
UFUNCTION(BlueprintCallable)
void InitWithQuestDataTablesInPath(const FString& Path);
/// Initialise this progress instance with quest definitions contained in all datatables found in a given content locations.
/// Paths must be of the form "/Game/Sub/Folder/Within/Content". Will recurse into subdirectories.
/// You must also call this BEFORE calling any other function
UFUNCTION(BlueprintCallable)
void InitWithQuestDataTablesInPaths(const TArray<FString>& Paths);
/**
* Get a copy of a Quest Definition. This is mostly so that you can modify it and register it
* as a new runtime quest
* @param QuestID The identifier of the quest
* @param OutQuest Output quest copy
* @return Whether the quest was found
*/
UFUNCTION(BlueprintCallable)
bool GetQuestDefinitionCopy(FName QuestID, FSuqsQuest& OutQuest);
/**
* Create a new runtime created quest to the system.
* @param NewQuest The new quest to add. This will be copied into the quest database.
* @param bOverwriteIfExists If a quest with this ID already exists, overwrite it if this is true.
* Otherwise, report an error and do nothing.
* @return Whether the quest was added
* @note If you overwrite an existing quest, stored progression against it will be reset.
* @note Quest definitions added at runtime will be lost by calling any of the Init..() functions, or by
* forcing a quest system rebuild with the optional parameter to GetQuestDefinitions
*/
UFUNCTION(BlueprintCallable)
bool CreateQuestDefinition(const FSuqsQuest& NewQuest, bool bOverwriteIfExists = false);
/**
* Delete an existing quest definition from the system
* @param QuestID The identifier of the quest
* @return Whether the quest was removed
* @note Removing a quest definition will erase any progress against it
*/
UFUNCTION(BlueprintCallable)
bool DeleteQuestDefinition(FName QuestID);
/**
* Change the default time delays between completing / failing a quest item, and the knock-on effects of that
* (the next task/objective/quest being activated).
* Where one completion rolls into another, the time delays are in serial. Therefore when completing the last
* task in a quest, the task delay will tick by before the objective is completed, which will complete the quest
* and then there can be another delay before any dependent quests are activated.
*
* Objectives don't have a delay of their own since they're just groupings of tasks.
*
* @param QuestDelay The time between a quest being completed/failed, and the effects on dependent quests (default 2)
* @param TaskDelay The time between a task being completed/failed, and dependent effects (next task, objective complete etc) (default 2)
*/
UFUNCTION(BlueprintCallable)
void SetDefaultProgressionTimeDelays(float QuestDelay, float TaskDelay);
/// This single event is best for quest UIs since it can give details about any relevant change in quest state
UPROPERTY(BlueprintAssignable)
FOnProgressionEvent OnProgressionEvent;
/// Fired when a task is completed
UPROPERTY(BlueprintAssignable)
FOnTaskCompleted OnTaskCompleted;
/// Fired when a task has failed
UPROPERTY(BlueprintAssignable)
FOnTaskFailed OnTaskFailed;
/// Fired when a objective is completed
UPROPERTY(BlueprintAssignable)
FOnObjectiveCompleted OnObjectiveCompleted;
/// Fired when a objective has failed
UPROPERTY(BlueprintAssignable)
FOnObjectiveFailed OnObjectiveFailed;
/// Fired when a quest is completed
UPROPERTY(BlueprintAssignable)
FOnQuestCompleted OnQuestCompleted;
/// Fired when a quest has failed
UPROPERTY(BlueprintAssignable)
FOnQuestFailed OnQuestFailed;
/// Fired when something on the detail of a task has changed (progress, time etc). NOT raised for status changes e.g. completion (but changes may cause them)
UPROPERTY(BlueprintAssignable)
FOnTaskUpdated OnTaskUpdated;
/// Fired when a quest has been accepted for the first time
UPROPERTY(BlueprintAssignable)
FOnQuestAccepted OnQuestAccepted;
/// Fired whenever the active quest list changes
UPROPERTY(BlueprintAssignable)
FOnActiveQuestsListChanged OnActiveQuestsListChanged;
/// Raised when this progression object has been completely re-initialised via loading
/// Note: because of timing issues around parameter providers, you probably also want to subscribe to
/// the OnParameterProvidersChanged event as well, since that can change text depending on when you query
UPROPERTY(BlueprintAssignable)
FOnProgressionLoaded OnProgressionLoaded;
/// Raised when the set of parameter providers is changed, which can affect text substitution
UPROPERTY(BlueprintAssignable)
FOnProgressParameterProvidersChanged OnParameterProvidersChanged;
/// Use this from C++ to receive access to the loaded quest data before it's applied to this progression
/// You can therefore change the quest data if you need to adapt it due to quest changes
FOnPreLoad OnPreLoad;
/**
* Return the quest definitions available. These are separate to the list of accepted quests or quest archive and
* represents all of the quests available.
* @param bForceRebuild If true, force the internal rebuild of quest definitions. Only needed if you have changed the
* QuestDataTables property at runtime after using other methods on this instance, which is highly discouraged.
* @return The quest definitions
*/
UFUNCTION(BlueprintCallable)
const TMap<FName, FSuqsQuest>& GetQuestDefinitions(bool bForceRebuild = false);
/// Get the overall status of a named quest
UFUNCTION(BlueprintCallable)
ESuqsQuestStatus GetQuestStatus(FName QuestID) const;
/// Return whether the quest is or has been accepted for the player (may also be completed / failed)
UFUNCTION(BlueprintCallable)
bool IsQuestAccepted(FName QuestID) const;
/// Return whether a quest is active, i.e. accepted and still in the active list. It may be completed / failed
/// but not resolved yet (resolve moves it to the archive potentially later)
UFUNCTION(BlueprintCallable)
bool IsQuestActive(FName QuestID) const;
/// Return whether the quest is incomplete, i.e. accepted but not completed or failed.
UFUNCTION(BlueprintCallable)
bool IsQuestIncomplete(FName QuestID) const;
/// Return whether the quest is completed
UFUNCTION(BlueprintCallable)
bool IsQuestCompleted(FName QuestID) const;
/// Return whether the quest has failed
UFUNCTION(BlueprintCallable)
bool IsQuestFailed(FName QuestID) const;
/// Get a list of the IDs of accepted quests
UFUNCTION(BlueprintCallable)
void GetAcceptedQuestIdentifiers(TArray<FName>& AcceptedQuestIDsOut) const;
/// Get a list of the IDs of archived quests (those that were completed or failed)
UFUNCTION(BlueprintCallable)
void GetArchivedQuestIdentifiers(TArray<FName>& ArchivedQuestIDsOut) const;
/// Get the state of a quest
UFUNCTION(BlueprintCallable)
USuqsQuestState* GetQuest(FName QuestID);
/// Get a list of the currently accepted quests
UFUNCTION(BlueprintCallable)
void GetAcceptedQuests(TArray<USuqsQuestState*>& AcceptedQuestsOut) const;
/// Get a list of the archived quests (those that were completed or failed)
UFUNCTION(BlueprintCallable)
void GetArchivedQuests(TArray<USuqsQuestState*>& ArchivedQuestsOut) const;
/**
* Accept a quest and track its state (if possible)
* Note: you don't need to do this for quests which are set to auto-accept based on the completion of other quests.
* However you will want to do it for events that you activate other ways, e.g. entering areas, talking to characters
* @param QuestID The identifier of the quest
* @param bResetIfFailed If this quest has failed, whether to reset it (default true)
* @param bResetIfComplete If this quest has been previously completed, whether to reset it. Default false (do nothing)
* @param bResetIfInProgress If this quest is already in progress, whether to reset it. If not, do nothing
* @returns Whether the quest was successfully accepted
*/
UFUNCTION(BlueprintCallable)
bool AcceptQuest(FName QuestID, bool bResetIfFailed = true, bool bResetIfComplete = false, bool bResetIfInProgress = false);
/// Reset all progress on a quest. Works whether a quest is in progress, complete or failed. Quest will remain accepted & incomplete
/// Note: this does NOT undo prior auto-acceptance of other quests which were dependent on this quest's completion/failure
/// If you need those other quests to reset or be removed if undoing completion/failure, you must do it manually.
UFUNCTION(BlueprintCallable)
void ResetQuest(FName QuestID);
/**
* Remove a quest from this play state entirely. This is akin to "unaccepting" a quest.
* @param QuestID The identifier of the quest
* @param bRemoveActive Whether active quests should be removed by this call (default true)
* @param bRemoveArchived Whether archived (failed/completed) quests should be removed (default true)
*/
UFUNCTION(BlueprintCallable)
void RemoveQuest(FName QuestID, bool bRemoveActive = true, bool bRemoveArchived = true);
/// Manually fail a quest. You should prefer using FailTask() instead if you need to explain which specific part
/// of a quest failed. Otherwise, this will mark all current tasks /objectives as failed.
UFUNCTION(BlueprintCallable)
void FailQuest(FName QuestID);
/// Manually complete a quest. You should prefer using CompleteTask() instead of using this, since that will
/// automatically bubble up. This will mark all mandatory tasks as complete
UFUNCTION(BlueprintCallable)
void CompleteQuest(FName QuestID);
/// Resolve the outcome of a completed/failed quest; move it to the quest archive and process the knock-on
/// effects such as activating dependent quests.
/// You do not normally need to call this, quests resolve automatically on completion/failure by default. However if
/// the quest definition sets "ResolveAutomatically" to false then you have to call this to resolve it.
/// Has no effect on quests which are incomplete.
UFUNCTION(BlueprintCallable)
void ResolveQuest(FName QuestID);
/**
* Mark a task as failed. If this is a mandatory task, it will fail the objective the task is attached to.
If the objective is mandatory, it will fail the quest.
* @param QuestID The ID of the quest. If None, will scan all active quests and fail any task with TaskIdentifier
* @param TaskIdentifier The identifier of the task within the quest
*/
UFUNCTION(BlueprintCallable)
void FailTask(FName QuestID, FName TaskIdentifier);
/**
* Fully complete a task. If this is the last mandatory task in an objective, also completes the objective, and
* cascades upwards to the quest if that's the last mandatory objective.
* @param QuestID The ID of the quest. If None, will scan all active quests and complete any task with TaskIdentifier
* @param TaskIdentifier The identifier of the task within the quest (required)
* @returns Whether the task was successfully completed
*/
UFUNCTION(BlueprintCallable)
bool CompleteTask(FName QuestID, FName TaskIdentifier);
/**
* Increment task progress. Increases the number value on a task, clamping it to the min/max numbers in the quest
* definition. If this increment takes the task number to the target, it completes the task as per CompleteTask.
* @param QuestID The ID of the quest. If None, will scan all active quests and progress any task with TaskIdentifier
* @param TaskIdentifier The identifier of the task within the quest
* @param Delta The change to make to the number on the task
* @returns The number of "things" outstanding on the task after progress was applied
*/
UFUNCTION(BlueprintCallable)
int ProgressTask(FName QuestID, FName TaskIdentifier, int Delta);
/**
* Directly set the current completed number on a specific task. An alternative to the delta version ProgressTask.
* @param QuestID The ID of the quest. If None, will scan all active quests and set any task with TaskIdentifier
* @param TaskIdentifier The identifier of the task within the quest
* @param Number The number of completed items to set the task to
*/
UFUNCTION(BlueprintCallable)
void SetTaskNumberCompleted(FName QuestID, FName TaskIdentifier, int Number);
/**
* Resolve the outcome of a completed/failed task; activate the next task, or complete/fail the quest if it's the last.
* You do not normally need to call this, tasks resolve automatically on completion/failure by default. However if
* the task definition sets "ResolveAutomatically" to false then you have to call this to resolve it.
* Has no effect on tasks which are incomplete.
* @param QuestID The ID of the quest. If None, will scan all active quests and resolve any task with TaskIdentifier
* @param TaskIdentifier The identifier of the task within the quest (required)
*/
UFUNCTION(BlueprintCallable)
void ResolveTask(FName QuestID, FName TaskIdentifier);
/// Get the current objective for a given quest
UFUNCTION(BlueprintCallable)
USuqsObjectiveState* GetCurrentObjective(FName QuestID) const;
/// Return whether a given objective is incomplete ie not failed or completed. For more information, retrieve the objective itself
UFUNCTION(BlueprintCallable)
bool IsObjectiveIncomplete(FName QuestID, FName ObjectiveID) const;
/// Return whether a given objective is completed. For more information, retrieve the objective itself
UFUNCTION(BlueprintCallable)
bool IsObjectiveCompleted(FName QuestID, FName ObjectiveID) const;
/// Return whether the objective has failed. For more information, retrieve the objective itself
UFUNCTION(BlueprintCallable)
bool IsObjectiveFailed(FName QuestID, FName ObjectiveID) const;
/// Reset a single objective in the quest, rather than the entire quest
UFUNCTION(BlueprintCallable)
void ResetObjective(FName QuestID, FName ObjectiveID);
/// Get the next mandatory task for a given quest.
/// If the objective for this quest only requires ONE of a number of tasks to be completed, this will be the first one.
/// Check the current objective for more details.
UFUNCTION(BlueprintCallable)
USuqsTaskState* GetNextMandatoryTask(FName QuestID) const;
/// Return whether a given task is incomplete ie not failed or completed. For more information, retrieve the task itself
UFUNCTION(BlueprintCallable)
bool IsTaskIncomplete(FName QuestID, FName TaskID) const;
/// Return whether a given task is completed. For more information, retrieve the task
UFUNCTION(BlueprintCallable)
bool IsTaskCompleted(FName QuestID, FName TaskID) const;
/// Return whether the task has failed. For more information, retrieve the task
UFUNCTION(BlueprintCallable)
bool IsTaskFailed(FName QuestID, FName TaskID) const;
/// Return whether a task is "Relevant" i.e. current and incomplete
UFUNCTION(BlueprintCallable)
bool IsTaskRelevant(FName QuestID, FName TaskID) const;
/// Shortcut to getting the whole task state for a specific quest
UFUNCTION(BlueprintCallable)
USuqsTaskState* GetTaskState(FName QuestID, FName TaskID) const;
/// Reset a single task in the quest
UFUNCTION(BlueprintCallable)
void ResetTask(FName QuestID, FName TaskID);
/// Set a branch to be active in a specific quest. Objectives in this quest that are associated with this
/// branch will then be allowed to activate.
UFUNCTION(BlueprintCallable)
void SetQuestBranchActive(FName QuestID, FName Branch, bool bActive);
/// Return whether an objective branch is active or not for a given quest
UFUNCTION(BlueprintCallable)
bool IsQuestBranchActive(FName QuestID, FName Branch);
/// Set a branch to be active globally for ALL quests. For all quests, objectives associated with that branch will be active.
/// This setting affects ALL quests, including any which are accepted after calling this
UFUNCTION(BlueprintCallable)
void SetGlobalQuestBranchActive(FName Branch, bool bActive);
/// Reset the globally active quest branches so that none are active
/// This setting affects ALL quests
UFUNCTION(BlueprintCallable)
void ResetGlobalQuestBranches();
/// Return whether a branch is active globally for all quests or not
UFUNCTION(BlueprintCallable)
bool IsGlobalQuestBranchActive(FName Branch);
/// Return a NON-MODIFIABLE list of globally active branches
UFUNCTION(BlueprintCallable)
const TArray<FName>& GetGlobalActiveQuestBranches() const;
/// Set a whether a given progression gate is open. Gates are unique names which prevent automatic progression on
/// completion / failure of an item until that gate is set open (all gates are closed by default). This can
/// help you manually control when a task / objective / quest rolls over to the next on completion / failure, so
/// you can tick off items but not have things move forward until you're ready.
UFUNCTION(BlueprintCallable)
void SetGateOpen(FName GateName, bool bOpen = true);
/// Return whether a gate to progression is open.
UFUNCTION(BlueprintCallable)
bool IsGateOpen(FName GateName);
/// Return whether the dependencies for a given quest have been met
/// You don't usually need to call this yourself, if auto-accept is enabled on your quests. But if you
/// want to determine it manually you can.
UFUNCTION(BlueprintCallable)
bool QuestDependenciesMet(const FName& QuestID);
/**
* Add an object which can provide parameter values
* @param Provider An object which implements ISuqsParameterProvider. Will be held by WEAK pointer!
*/
UFUNCTION(BlueprintCallable)
void AddParameterProvider(UObject* Provider);
UFUNCTION(BlueprintCallable)
void RemoveParameterProvider(UObject* Provider);
UFUNCTION(BlueprintCallable)
void RemoveAllParameterProviders();
void RaiseTaskUpdated(USuqsTaskState* Task);
void RaiseTaskFailed(USuqsTaskState* Task);
void RaiseTaskCompleted(USuqsTaskState* Task);
void RaiseTaskAdded(USuqsTaskState* Task);
void RaiseTaskRemoved(USuqsTaskState* Task);
void RaiseObjectiveCompleted(USuqsObjectiveState* Objective);
void RaiseObjectiveFailed(USuqsObjectiveState* Objective);
void RaiseQuestCompleted(USuqsQuestState* Quest);
void RaiseQuestFailed(USuqsQuestState* Quest);
void RaiseQuestReset(USuqsQuestState* Quest);
void RaiseCurrentObjectiveChanged(USuqsQuestState* Quest);
FText FormatQuestText(const FName& QuestID, const FText& FormatText);
FText FormatTaskText(const FName& QuestID, const FName& TaskID, const FText& FormatText);
void ProcessQuestStatusChange(USuqsQuestState* Quest);
const FSuqsQuest* GetQuestDefinition(const FName& QuestID);
/// Given a task definition and status, return progression barrier information
FSuqsResolveBarrier GetResolveBarrierForTask(const FSuqsTask* Task, ESuqsTaskStatus Status) const;
/// Given a task definition and status, return progression barrier information
FSuqsResolveBarrier GetResolveBarrierForQuest(const FSuqsQuest* Q, ESuqsQuestStatus Status) const;
/// Standard serialisation support
virtual void Serialize(FArchive& Ar) override;
/// Specific load from our data holder structs, if you prefer over Serialize()
void LoadFromData(const FSuqsSaveData& Data);
/// Specific save to our data holder structs, if you prefer over Serialize()
void SaveToData(FSuqsSaveData& Data) const;
// FTickableGameObject begin
virtual void Tick(float DeltaTime) override;
virtual TStatId GetStatId() const override;
// FTickableGameObject end
/**
* @brief
* @param JsonString Quest definition in a JSON string
* @return A quest data table suitable for adding to USuqsProgression's QuestDataTables property
*/
UFUNCTION(BlueprintCallable, Category="SUQS")
static UDataTable* MakeQuestDataTableFromJSON(const FString& JsonString);
/**
* @brief Helper function to get the description of a progress event
* @param Evt The event
* @return A string description
*/
UFUNCTION(BlueprintCallable, Category="SUQS")
static FString GetProgressEventDescription(const FSuqsProgressionEventDetails& Evt);
/// Determine if some text needs formatting (has parameters)
static bool GetTextNeedsFormatting(const FText& Text);
};
| 412 | 0.608154 | 1 | 0.608154 | game-dev | MEDIA | 0.891468 | game-dev | 0.73137 | 1 | 0.73137 |
VertaAI/modeldb | 2,035 | backend/server/src/main/java/ai/verta/modeldb/entities/ArtifactPartEntity.java | package ai.verta.modeldb.entities;
import ai.verta.common.ArtifactPart;
import com.amazonaws.services.s3.model.PartETag;
import java.io.Serializable;
import java.util.Objects;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "artifact_part")
public class ArtifactPartEntity implements Serializable {
public static final int EXP_RUN_ARTIFACT = 0;
public static final int VERSION_BLOB_ARTIFACT = 1;
public static final int PROJECT_ARTIFACT = 2;
public static final int EXPERIMENT_ARTIFACT = 3;
public ArtifactPartEntity() {}
public ArtifactPartEntity(String artifactId, int artifactType, long partNumber, String etag) {
this.artifact_id = artifactId;
this.artifact_type = artifactType;
this.partNumber = partNumber;
this.etag = etag;
}
@Id
@Column(name = "artifact_id", nullable = false)
private String artifact_id;
@Id
@Column(name = "artifact_type", nullable = false)
private Integer artifact_type;
@Id
@Column(name = "part_number", nullable = false)
private long partNumber;
@Column private String etag;
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ArtifactPartEntity that = (ArtifactPartEntity) o;
return partNumber == that.partNumber
&& Objects.equals(artifact_id, that.artifact_id)
&& Objects.equals(artifact_type, that.artifact_type)
&& Objects.equals(etag, that.etag);
}
@Override
public int hashCode() {
return Objects.hash(artifact_id, artifact_type, partNumber, etag);
}
public ArtifactPart toProto() {
return ArtifactPart.newBuilder().setPartNumber(partNumber).setEtag(etag).build();
}
public PartETag toPartETag() {
return new PartETag((int) partNumber, etag);
}
public long getPartNumber() {
return partNumber;
}
public String getEtag() {
return etag;
}
}
| 412 | 0.725409 | 1 | 0.725409 | game-dev | MEDIA | 0.42008 | game-dev | 0.71302 | 1 | 0.71302 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.