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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
exult/exult | 8,503 | content/bgkeyring/src/quests/locklake/cleanup_eggs.uc | /*
*
* Copyright (C) 2006 The Exult Team
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
*
* This source file contains the code for the cleaning of Lock Lake.
*
* Author: Marzo Junior
* Last Modified: 2006-03-19
*/
const int LOCK_LAKE_TIMER = 0xC;
void eggCleanLockLake object#() () {
if (event != EGG) {
return;
}
struct<Position> pos;
//Get the eggs' quality:
var quality = get_item_quality();
//Base number of objects to remove:
var items_to_remove = 10;
//Independent control of time for each of the eggs while
//using but a single timer:
static var last_elapsed_time_1;
static var last_elapsed_time_2;
static var last_elapsed_time_3;
static var last_elapsed_time_4;
static var last_elapsed_time_5;
if (gflags[LOCK_LAKE_BILL_SIGNED]) {
//Miranda's Bill has been signed, so the cleaning can start
//Check the elapsed time:
var elapsed_time = UI_get_timer(LOCK_LAKE_TIMER);
if (!elapsed_time) {
//No elapsed time means the timer does not exist yet;
//create timer and abort:
UI_set_timer(LOCK_LAKE_TIMER);
abort;
}
//Store the current elapsed time, but only
//after storing it in a local variable:
var time;
if (quality == 0) {
time = last_elapsed_time_1;
last_elapsed_time_1 = elapsed_time;
} else if (quality == 1) {
time = last_elapsed_time_2;
last_elapsed_time_2 = elapsed_time;
} else if (quality == 5) {
time = last_elapsed_time_3;
last_elapsed_time_3 = elapsed_time;
} else if (quality == 9) {
time = last_elapsed_time_4;
last_elapsed_time_4 = elapsed_time;
} else if (quality == 11) {
time = last_elapsed_time_5;
last_elapsed_time_5 = elapsed_time;
}
//Get the amount of time that elapsed since the last visit
//to this egg:
elapsed_time -= time;
if (elapsed_time <= 0) {
//No time elapsed or invalid time; abort:
abort;
}
//Get the center of the current cleaning session:
if (!(quality in [5, 7])) {
pos = get_object_position();
} else {
pos = [0x5D3, 0x44A, 0x0];
}
//Get the shapes of all nearby 'garbage' items:
var garbage = pos->find_nearby(SHAPE_BROKEN_DISH, 50, MASK_NONE);
garbage = [garbage, pos->find_nearby(SHAPE_GARBAGE, 50, MASK_NONE)];
garbage = [garbage, pos->find_nearby(SHAPE_STAIN, 50, MASK_TRANSLUCENT)];
garbage = [garbage, pos->find_nearby(SHAPE_DIAPER, 50, MASK_NONE)];
garbage = [garbage, pos->find_nearby(SHAPE_BROKEN_ROOF, 50, MASK_NONE)];
garbage = [garbage, pos->find_nearby(SHAPE_ANCHOR, 50, MASK_NONE)];
garbage = [garbage, pos->find_nearby(SHAPE_CHAIR, 50, MASK_NONE)];
garbage = [garbage, pos->find_nearby(SHAPE_FOOD, 50, MASK_NONE)];
garbage = [garbage, pos->find_nearby(SHAPE_TOP, 50, MASK_NONE)];
garbage = [garbage, pos->find_nearby(SHAPE_HOOD, 50, MASK_NONE)];
garbage = [garbage, pos->find_nearby(SHAPE_PANTS, 50, MASK_NONE)];
garbage = [garbage, pos->find_nearby(SHAPE_CLOTH, 50, MASK_NONE)];
garbage = [garbage, pos->find_nearby(SHAPE_BODIES_3, 50, MASK_NONE)];
garbage = [garbage, pos->find_nearby(SHAPE_BODIES_4, 50, MASK_NONE)];
if (garbage) {
//Only do this if there is at least one garbage item
var obj;
//See how many items are available to be cleaned:
var total_items = UI_get_array_size(garbage);
var rand;
//Split garbage in three categories according to condition checking:
var simple_garbage = [SHAPE_BROKEN_DISH, SHAPE_GARBAGE, SHAPE_STAIN, SHAPE_DIAPER, SHAPE_BROKEN_ROOF, SHAPE_ANCHOR];
var clothing = [SHAPE_TOP, SHAPE_HOOD, SHAPE_PANTS, SHAPE_CLOTH];
var bodies = [SHAPE_BODIES_3, SHAPE_BODIES_4];
var itemshape;
var unremovable_objects;
//How many items will be cleaned this time:
items_to_remove = (elapsed_time + UI_die_roll(5, 12)) * 3;
for (obj in garbage) {
//For each garbage object in the list,
//Get a random number:
rand = UI_get_random(total_items);
//Get the garbage's shape and position:
itemshape = obj->get_item_shape();
pos = obj->get_object_position();
if ((itemshape in simple_garbage)
//There are some clothing and food items which are
//inside houses and should not be removed:
|| (((itemshape in clothing) || (itemshape == SHAPE_FOOD)) && (pos.y < 1230))
//Only chairs of frame 21 (which are outside houses)
//should be removed:
|| ((itemshape == SHAPE_CHAIR) && (obj->get_item_frame() == 21))) {
//If we are here, the item can (at least in principle) be removed;
//use the random number above to see if we should remove the
//item or not:
if (rand <= items_to_remove) {
//Remove it and reduce likelyhood of next item being removed:
obj->remove_item();
items_to_remove -= 1;
}
} else if (itemshape in bodies) {
//We have a body in our hands
//If we are here, the item can (at least in principle) be removed;
//use the random number above to see if we should remove the
//item or not:
if (rand <= items_to_remove) {
//If this is the fish with Mack's key,
if (obj->get_cont_items(SHAPE_KEY, 55, FRAME_ANY)) {
//set flag so that Cove's mayor now has it
gflags[MACKS_KEY_WITH_COVE_MAYOR] = true;
}
//Get all objects contained in the body:
var cont_items = obj->get_cont_items(SHAPE_ANY, QUALITY_ANY, FRAME_ANY);
if (cont_items) {
for (obj2 in cont_items) {
//Remove them all:
obj2->remove_item();
}
}
//Remove body and reduce likelyhood of next item being removed:
obj->remove_item();
items_to_remove -= 1;
}
} else {
//Object cannot be removed (e.g., clothes inside houses)
unremovable_objects += 1;
}
//Increase likelyhood that next objects will be removed:
total_items -= 1;
}
if (unremovable_objects && (unremovable_objects == UI_get_array_size(garbage))) {
//If there are only unremovable objects left,
if (quality == 0) {
//Remove the egg with quality zero:
remove_item();
return;
}
} else if (items_to_remove < 10) {
//If there are less than 10 items left to remove in this
//session, there is nothing else that can be done now:
return;
}
}
//The egg with quality zero has nothing to do from now on;
if (quality == 0) {
//Remove it:
remove_item();
return;
}
var posx = [
0x59F, 0x5AF, 0x5BF, 0x5CF, 0x5DF, 0x5EF, 0x5CF, 0x5DF,
0x60F, 0x5FF, 0x5EF, 0x5DF
];
var posy;
items_to_remove -= 9;
while (items_to_remove > 0) {
//Go in steps of 9
items_to_remove -= 9;
//Determine y coordinate by the quality:
if ((quality >= 1) && (quality <= 6)) {
posy = 0x45F;
} else if ((quality == 7) || (quality == 8)) {
posy = 0x44F;
} else {
posy = 0x4BF;
}
//Create the fake water cover:
UI_create_new_object(SHAPE_FAKE_WATER);
//Put it in the correct place:
UI_update_last_created([posx[quality], posy, 0]);
//Create another fake water cover:
UI_create_new_object(SHAPE_FAKE_WATER);
//Put it in the correct place:
UI_update_last_created([posx[quality + 1], posy, 0]);
if (quality in [3, 7, 9, 11]) {
//These eggs are basically done
if (quality >= 9) {
//Some eggs have fly-generating eggs nearby;
//find fly eggs:
var fly_eggs = [UI_find_nearby([0x5CA, 0x4C6, 0x0], SHAPE_EGG, 5, MASK_EGG),
UI_find_nearby([0x5DB, 0x4D3, 0x0], SHAPE_EGG, 5, MASK_EGG),
UI_find_nearby([0x5E4, 0x4BE, 0x0], SHAPE_EGG, 5, MASK_EGG),
UI_find_nearby([0x600, 0x4C9, 0x0], SHAPE_EGG, 5, MASK_EGG)];
for (egg in fly_eggs) {
//Remove them all:
egg->remove_item();
}
}
//Egg is done, so remove it:
remove_item();
break;
} else {
//Prepare egg for next cleaning session:
quality += 2;
set_item_quality(quality);
}
}
}
}
| 1 | 0.631462 | 1 | 0.631462 | game-dev | MEDIA | 0.771357 | game-dev | 0.946838 | 1 | 0.946838 |
KimigaiiWuyi/GenshinUID | 18,324 | GenshinUID/genshinuid_enka/to_data.py | import json
import time
import asyncio
import threading
from copy import deepcopy
from typing import Dict, List, Union, Literal, Optional
import aiofiles
from httpx import ReadTimeout
from gsuid_core.utils.api.enka.models import EnkaData
from gsuid_core.utils.api.enka.request import get_enka_info
from ..utils.message import UID_HINT
from .mono.Character import Character
from ..utils.api.cv.request import _CvApi
from .draw_normal import get_artifact_score_data
from ..genshinuid_config.gs_config import gsconfig
from ..utils.resource.RESOURCE_PATH import PLAYER_PATH
from ..utils.ambr_to_minigg import convert_ambr_to_weapon
from ..utils.map.GS_MAP_PATH import (
icon2Name,
propId2Name,
skillId2Name,
artifact2attr,
avatarId2Name,
talentId2Name,
weaponHash2Name,
weaponHash2Type,
artifactId2Piece,
avatarName2Element,
)
# from gsuid_core.utils.api.minigg.request import get_weapon_info
PROP_ATTR_MAP = {
'Anemo': '44',
'Cryo': '46',
'Dendro': '43',
'Electro': '41',
'Geo': '45',
'Hydro': '42',
'Pyro': '40',
}
AT_MAP = {
'maxHp': 'maxHP',
'atk': 'maxATK',
'def': 'maxDEF',
'elementalMastery': 'elementalMastery',
'energyRecharge': 'energyRecharge',
'healingBonus': 'healingBonus',
'critRate': 'critRate',
'critDamage': 'critDMG',
}
ENKA_API: List[Literal['enka', 'microgg']] = ['enka', 'microgg']
is_enable_akasha = gsconfig.get_config('EnableAkasha').data
ARTIFACT_DATA = {
'data': {
'flower': [],
'plume': [],
'sands': [],
'goblet': [],
'circlet': [],
},
'tag': {
'flower': [],
'plume': [],
'sands': [],
'goblet': [],
'circlet': [],
},
}
async def switch_api():
global ENKA_API
if ENKA_API[0] == 'enka':
ENKA_API = ['microgg', 'enka']
else:
ENKA_API = ['enka', 'microgg']
return f'切换成功!当前api为{ENKA_API[0]}!'
async def enka_to_dict(
uid: str, enka_data: Optional[EnkaData] = None
) -> Union[List[dict], str]:
'''
:说明:
访问enkaAPI并转换为genshinUID的数据Json。
:参数:
* ``uid: str``: 玩家uid。
* ``enka_data: Optional[dict] = None``: 来自enka的dict, 可留空。
:返回:
* ``刷新完成提示语: str``: 包含刷新成功的角色列表。
'''
if '未找到绑定的UID' in uid:
return UID_HINT
if enka_data:
pass
else:
try:
enka_data = await get_enka_info(uid, ENKA_API[0])
except ReadTimeout:
return '网络不太稳定...'
if isinstance(enka_data, str):
return []
if isinstance(enka_data, dict):
if 'playerInfo' not in enka_data:
im = (
'服务器正在维护或者关闭中...\n'
f'检查{ENKA_API[0]}是否可以访问\n'
'如可以访问,尝试[切换api]或上报Bug!'
)
return im
elif enka_data is None:
return []
now = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
playerInfo = enka_data['playerInfo']
path = PLAYER_PATH / str(uid)
path.mkdir(parents=True, exist_ok=True)
# 保存基本玩家信息
async with aiofiles.open(
path / f'{uid}.json', 'w', encoding='UTF-8'
) as file:
await file.write(json.dumps(playerInfo, indent=4, ensure_ascii=False))
# 保存原始数据
async with aiofiles.open(
path / 'rawData.json', 'w', encoding='UTF-8'
) as file:
await file.write(json.dumps(enka_data, indent=4, ensure_ascii=False))
if (
enka_data is None
or enka_data == {}
or 'avatarInfoList' not in enka_data
or not enka_data['avatarInfoList']
):
return f'UID{uid}刷新失败!未打开角色展柜或角色展柜未展示角色!'
char_dict_list = []
# 确认是否存在圣遗物列表
all_artifacts_path = path / 'artifacts.json'
if not all_artifacts_path.exists():
all_artifacts_data = deepcopy(ARTIFACT_DATA)
else:
async with aiofiles.open(
all_artifacts_path, 'r', encoding='UTF-8'
) as file:
all_artifacts_data = json.loads(await file.read())
for char in enka_data['avatarInfoList']:
# 处理基本信息
char_data = {}
avatarId = char['avatarId']
char_data['playerUid'] = str(uid)
char_data['playerName'] = enka_data['playerInfo']['nickname']
char_data['avatarId'] = avatarId
avatarName = avatarId2Name[str(char['avatarId'])]
char_data['avatarName'] = avatarId2Name[str(char['avatarId'])]
char_data['avatarFetter'] = char['fetterInfo']['expLevel']
char_data['avatarLevel'] = char['propMap']['4001']['val']
try:
char_data['avatarElement'] = avatarName2Element[
char_data['avatarName']
]
except KeyError:
check = skillId2Name['Name'][
str(list(char['skillLevelMap'].keys())[2])
]
if '风' in check:
char_data['avatarElement'] = 'Anemo'
elif '雷' in check:
char_data['avatarElement'] = 'Electro'
elif '岩' in check:
char_data['avatarElement'] = 'Geo'
elif '草' in check:
char_data['avatarElement'] = 'Dendro'
elif '冰' in check:
char_data['avatarElement'] = 'Cryo'
elif '水' in check:
char_data['avatarElement'] = 'Hydro'
else:
char_data['avatarElement'] = 'Pyro'
char_data['dataTime'] = now
char_data['avatarSkill'] = []
# 处理天赋
for skill in char['skillLevelMap']:
skill_temp = {}
skill_temp['skillId'] = skill
skill_temp['skillName'] = skillId2Name['Name'][
skill_temp['skillId']
]
skill_temp['skillLevel'] = char['skillLevelMap'][skill]
skill_temp['skillIcon'] = skillId2Name['Icon'][
skill_temp['skillId']
]
char_data['avatarSkill'].append(skill_temp)
if char_data['avatarName'] in ['神里绫华', '安柏']:
char_data['avatarSkill'][0], char_data['avatarSkill'][-1] = (
char_data['avatarSkill'][-1],
char_data['avatarSkill'][0],
)
char_data['avatarSkill'][2], char_data['avatarSkill'][-1] = (
char_data['avatarSkill'][-1],
char_data['avatarSkill'][2],
)
char_data['avatarEnName'] = char_data['avatarSkill'][1][
'skillIcon'
].split('_')[-2]
elif char_data['avatarName'] in ['旅行者']:
char_data['avatarSkill'][0], char_data['avatarSkill'][-1] = (
char_data['avatarSkill'][-1],
char_data['avatarSkill'][0],
)
char_data['avatarSkill'][1], char_data['avatarSkill'][-1] = (
char_data['avatarSkill'][-1],
char_data['avatarSkill'][1],
)
char_data['avatarEnName'] = str(avatarId)
else:
char_data['avatarEnName'] = char_data['avatarSkill'][-1][
'skillIcon'
].split('_')[-2]
# 处理命座
talent_temp = []
if 'talentIdList' in char:
for index, talent in enumerate(char['talentIdList']):
talentTemp = {}
talentTemp['talentId'] = char['talentIdList'][index]
talentTemp['talentName'] = talentId2Name['Name'][str(talent)]
talentTemp['talentIcon'] = talentId2Name['Icon'][str(talent)]
talent_temp.append(talentTemp)
char_data['talentList'] = talent_temp
# 处理属性
fight_prop = {}
# 血量
fight_prop['hp'] = char['fightPropMap']['2000']
fight_prop['baseHp'] = char['fightPropMap']['1']
fight_prop['addHp'] = (
char['fightPropMap']['2000'] - char['fightPropMap']['1']
)
# 攻击力
fight_prop['atk'] = char['fightPropMap']['2001']
fight_prop['baseAtk'] = char['fightPropMap']['4']
fight_prop['addAtk'] = (
char['fightPropMap']['2001'] - char['fightPropMap']['4']
)
# 防御力
fight_prop['def'] = char['fightPropMap']['2002']
fight_prop['baseDef'] = char['fightPropMap']['7']
fight_prop['addDef'] = (
char['fightPropMap']['2002'] - char['fightPropMap']['7']
)
# 元素精通
fight_prop['elementalMastery'] = char['fightPropMap']['28']
# 暴击率
fight_prop['critRate'] = char['fightPropMap']['20']
# 暴击伤害
fight_prop['critDmg'] = char['fightPropMap']['22']
# 充能效率
fight_prop['energyRecharge'] = char['fightPropMap']['23']
# 治疗&受治疗
fight_prop['healBonus'] = char['fightPropMap']['26']
fight_prop['healedBonus'] = char['fightPropMap']['27']
# 物理伤害加成 & 抗性
fight_prop['physicalDmgSub'] = char['fightPropMap']['29']
fight_prop['physicalDmgBonus'] = char['fightPropMap']['30']
# 伤害加成
fight_prop['dmgBonus'] = char['fightPropMap'][
PROP_ATTR_MAP[char_data['avatarElement']]
]
char_data['avatarFightProp'] = fight_prop
# 处理武器
weapon_info = {}
weapon_data = char['equipList'][-1]
weapon_info['itemId'] = weapon_data['itemId']
weapon_info['nameTextMapHash'] = weapon_data['flat']['nameTextMapHash']
weapon_info['weaponIcon'] = weapon_data['flat']['icon']
weapon_info['weaponType'] = weaponHash2Type[
str(weapon_info['nameTextMapHash'])
]
weapon_info['weaponName'] = weaponHash2Name[
str(weapon_info['nameTextMapHash'])
]
weapon_info['weaponStar'] = weapon_data['flat']['rankLevel']
# 防止未精炼
if 'promoteLevel' in weapon_data['weapon']:
weapon_info['promoteLevel'] = weapon_data['weapon']['promoteLevel']
else:
weapon_info['promoteLevel'] = 0
weapon_info['weaponLevel'] = weapon_data['weapon']['level']
if 'affixMap' in weapon_data['weapon']:
weapon_info['weaponAffix'] = (
list(weapon_data['weapon']['affixMap'].values())[0] + 1
)
else:
weapon_info['weaponAffix'] = 1
weapon_info['weaponStats'] = []
for k in weapon_data['flat']['weaponStats']:
weapon_prop_temp = {}
weapon_prop_temp['appendPropId'] = k['appendPropId']
weapon_prop_temp['statName'] = propId2Name[k['appendPropId']]
weapon_prop_temp['statValue'] = k['statValue']
weapon_info['weaponStats'].append(weapon_prop_temp)
# 武器特效,须请求API
'''
try:
effect_raw = await get_weapon_info(weapon_info['weaponName'])
except: # noqa
'''
effect_raw = await convert_ambr_to_weapon(weapon_info['itemId'])
if (
not isinstance(effect_raw, List)
and not isinstance(effect_raw, int)
and effect_raw is not None
and int(effect_raw['rarity']) > 2
):
effect = effect_raw[f'r{weapon_info["weaponAffix"]}'][
'description'
]
else:
effect = '无特效。'
weapon_info['weaponEffect'] = effect
char_data['weaponInfo'] = weapon_info
# 处理圣遗物
artifacts_info = []
artifacts_data = char['equipList'][:-1]
artifact_set_list = []
for artifact in artifacts_data:
artifact_temp = {}
artifact_temp['itemId'] = artifact['itemId']
artifact_temp['nameTextMapHash'] = artifact['flat'][
'nameTextMapHash'
]
artifact_temp['icon'] = artifact['flat']['icon']
artifact_temp['aritifactName'] = icon2Name[
artifact['flat']['icon']
]
artifact_temp['aritifactSetsName'] = artifact2attr[
artifact_temp['aritifactName']
]
artifact_set_list.append(artifact_temp['aritifactSetsName'])
artifact_temp['aritifactSetPiece'] = artifactId2Piece[
artifact_temp['icon'].split('_')[-1]
][0]
artifact_temp['aritifactPieceName'] = artifactId2Piece[
artifact_temp['icon'].split('_')[-1]
][1]
artifact_temp['aritifactStar'] = artifact['flat']['rankLevel']
artifact_temp['aritifactLevel'] = (
artifact['reliquary']['level'] - 1
)
artifact_temp['reliquaryMainstat'] = artifact['flat'][
'reliquaryMainstat'
]
artifact_temp['reliquaryMainstat']['statName'] = propId2Name[
artifact_temp['reliquaryMainstat']['mainPropId']
]
if 'reliquarySubstats' in artifact['flat']:
artifact_temp['reliquarySubstats'] = artifact['flat'][
'reliquarySubstats'
]
else:
artifact_temp['reliquarySubstats'] = []
for sub in artifact_temp['reliquarySubstats']:
sub['statName'] = propId2Name[sub['appendPropId']]
# 加入单个圣遗物部件
artifacts_info.append(artifact_temp)
# 保存原始数据
async with aiofiles.open(
path / 'artifacts.json', 'w', encoding='UTF-8'
) as file:
await file.write(
json.dumps(all_artifacts_data, indent=4, ensure_ascii=False)
)
equipSetList = set(artifact_set_list)
char_data['equipSets'] = {'type': '', 'set': ''}
char_data['equipList'] = artifacts_info
for equip in equipSetList:
if artifact_set_list.count(equip) >= 4:
char_data['equipSets']['type'] = '4'
char_data['equipSets']['set'] = equip
break
elif artifact_set_list.count(equip) == 1:
pass
elif artifact_set_list.count(equip) >= 2:
char_data['equipSets']['type'] += '2'
char_data['equipSets']['set'] += '|' + equip
if char_data['equipSets']['set'].startswith('|'):
char_data['equipSets']['set'] = char_data['equipSets']['set'][1:]
threading.Thread(
target=lambda: asyncio.run(
_get_data(
artifacts_info,
all_artifacts_data,
avatarId,
char_data,
)
),
daemon=True,
).start()
char_dict_list.append(char_data)
async with aiofiles.open(
path / '{}.json'.format(avatarName), 'w', encoding='UTF-8'
) as file:
await file.write(
json.dumps(char_data, indent=4, ensure_ascii=False)
)
if is_enable_akasha:
asyncio.create_task(_restore_cv_data(uid, now))
return char_dict_list
async def _restore_cv_data(uid: str, now: str):
cv_api = _CvApi()
data = await cv_api.get_rank_data(uid)
path = PLAYER_PATH / str(uid) / 'rank.json'
if path.exists():
async with aiofiles.open(path, 'r', encoding='UTF-8') as file:
rank_data = json.loads(await file.read())
else:
rank_data = {}
if not isinstance(data, int):
data1, data2 = data[0], data[1]
for i in data1['data']:
for j in data2['data']:
if i['_id'] == j['_id']:
_value = 0
stats = {'critValue': j['critValue']}
for k in j['stats']:
if k in AT_MAP:
_k = AT_MAP[k]
elif k.endswith('DamageBonus'):
if j['stats'][k]['value'] > 0:
_value = j['stats'][k]['value']
continue
else:
continue
else:
_k = k
stats[_k] = j['stats'][k]['value']
stats['DMG'] = _value
break
cal = i['calculations']
cal['fit']['stats'] = stats
rank_data[i['characterId']] = {
'calculations': cal,
'time': now,
}
async with aiofiles.open(path, 'w', encoding='UTF-8') as file:
await file.write(
json.dumps(rank_data, indent=4, ensure_ascii=False)
)
async def enka_to_data(
uid: str, enka_data: Optional[EnkaData] = None
) -> Union[dict, str]:
raw_data = await enka_to_dict(uid, enka_data)
if isinstance(raw_data, str):
return raw_data
char_name_list = []
char_name_list_str = ''
for char_data in raw_data:
char_name_list.append(char_data['avatarName'])
char_name_list_str = ','.join(char_name_list)
return f'UID{uid}刷新完成!\n本次缓存:{char_name_list_str}'
async def _get_data(
artifacts_info: List,
all_artifacts_data: Dict,
avatarId: int,
char_data: Dict,
):
for _artifact in artifacts_info:
await input_artifacts_data(
deepcopy(_artifact), all_artifacts_data, avatarId, char_data
)
async def input_artifacts_data(
artifact_temp: Dict,
all_artifacts_data: Dict,
avatarId: int,
char_data: Dict,
):
artifact_temp = await get_artifact_score_data(
artifact_temp, Character(char_data)
)
# 加入圣遗物数据列表
if (
artifact_temp
not in all_artifacts_data['data'][artifact_temp['aritifactSetPiece']]
):
all_artifacts_data['data'][artifact_temp['aritifactSetPiece']].append(
artifact_temp
)
all_artifacts_data['tag'][artifact_temp['aritifactSetPiece']].append(
[avatarId]
)
elif (
avatarId
not in all_artifacts_data['tag'][artifact_temp['aritifactSetPiece']][
all_artifacts_data['data'][
artifact_temp['aritifactSetPiece']
].index(artifact_temp)
]
):
all_artifacts_data['tag'][artifact_temp['aritifactSetPiece']][
all_artifacts_data['data'][
artifact_temp['aritifactSetPiece']
].index(artifact_temp)
].append(avatarId)
return all_artifacts_data
| 1 | 0.860898 | 1 | 0.860898 | game-dev | MEDIA | 0.334301 | game-dev | 0.96087 | 1 | 0.96087 |
AdamEisfeld/PhyKit | 3,283 | PhyKit-shared/bullet/BulletCollision/CollisionShapes/btConvexShape.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.
*/
#ifndef BT_CONVEX_SHAPE_INTERFACE1
#define BT_CONVEX_SHAPE_INTERFACE1
#include "btCollisionShape.h"
#include "LinearMath/btVector3.h"
#include "LinearMath/btTransform.h"
#include "LinearMath/btMatrix3x3.h"
#include "btCollisionMargin.h"
#include "LinearMath/btAlignedAllocator.h"
#define MAX_PREFERRED_PENETRATION_DIRECTIONS 10
/// The btConvexShape is an abstract shape interface, implemented by all convex shapes such as btBoxShape, btConvexHullShape etc.
/// It describes general convex shapes using the localGetSupportingVertex interface, used by collision detectors such as btGjkPairDetector.
ATTRIBUTE_ALIGNED16(class)
btConvexShape : public btCollisionShape
{
public:
BT_DECLARE_ALIGNED_ALLOCATOR();
btConvexShape();
virtual ~btConvexShape();
virtual btVector3 localGetSupportingVertex(const btVector3& vec) const = 0;
////////
#ifndef __SPU__
virtual btVector3 localGetSupportingVertexWithoutMargin(const btVector3& vec) const = 0;
#endif //#ifndef __SPU__
btVector3 localGetSupportVertexWithoutMarginNonVirtual(const btVector3& vec) const;
btVector3 localGetSupportVertexNonVirtual(const btVector3& vec) const;
btScalar getMarginNonVirtual() const;
void getAabbNonVirtual(const btTransform& t, btVector3& aabbMin, btVector3& aabbMax) const;
virtual void project(const btTransform& trans, const btVector3& dir, btScalar& minProj, btScalar& maxProj, btVector3& witnesPtMin, btVector3& witnesPtMax) const;
//notice that the vectors should be unit length
virtual void batchedUnitVectorGetSupportingVertexWithoutMargin(const btVector3* vectors, btVector3* supportVerticesOut, int numVectors) const = 0;
///getAabb's default implementation is brute force, expected derived classes to implement a fast dedicated version
void getAabb(const btTransform& t, btVector3& aabbMin, btVector3& aabbMax) const = 0;
virtual void getAabbSlow(const btTransform& t, btVector3& aabbMin, btVector3& aabbMax) const = 0;
virtual void setLocalScaling(const btVector3& scaling) = 0;
virtual const btVector3& getLocalScaling() const = 0;
virtual void setMargin(btScalar margin) = 0;
virtual btScalar getMargin() const = 0;
virtual int getNumPreferredPenetrationDirections() const = 0;
virtual void getPreferredPenetrationDirection(int index, btVector3& penetrationVector) const = 0;
};
#endif //BT_CONVEX_SHAPE_INTERFACE1
| 1 | 0.927258 | 1 | 0.927258 | game-dev | MEDIA | 0.992289 | game-dev | 0.849278 | 1 | 0.849278 |
Pursue525/Nattalie-1.12.2 | 39,877 | src/net/minecraft/entity/passive/AbstractHorse.java | package net.minecraft.entity.passive;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import java.util.UUID;
import javax.annotation.Nullable;
import net.minecraft.advancements.CriteriaTriggers;
import net.minecraft.block.Block;
import net.minecraft.block.SoundType;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityAgeable;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.EnumCreatureAttribute;
import net.minecraft.entity.IEntityLivingData;
import net.minecraft.entity.IJumpingMount;
import net.minecraft.entity.SharedMonsterAttributes;
import net.minecraft.entity.ai.EntityAIFollowParent;
import net.minecraft.entity.ai.EntityAILookIdle;
import net.minecraft.entity.ai.EntityAIMate;
import net.minecraft.entity.ai.EntityAIPanic;
import net.minecraft.entity.ai.EntityAIRunAroundLikeCrazy;
import net.minecraft.entity.ai.EntityAISwimming;
import net.minecraft.entity.ai.EntityAIWanderAvoidWater;
import net.minecraft.entity.ai.EntityAIWatchClosest;
import net.minecraft.entity.ai.attributes.IAttribute;
import net.minecraft.entity.ai.attributes.IAttributeInstance;
import net.minecraft.entity.ai.attributes.RangedAttribute;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.init.MobEffects;
import net.minecraft.init.SoundEvents;
import net.minecraft.inventory.ContainerHorseChest;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.IInventoryChangedListener;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.datasync.DataParameter;
import net.minecraft.network.datasync.DataSerializers;
import net.minecraft.network.datasync.EntityDataManager;
import net.minecraft.server.management.PreYggdrasilConverter;
import net.minecraft.util.DamageSource;
import net.minecraft.util.EnumParticleTypes;
import net.minecraft.util.SoundEvent;
import net.minecraft.util.datafix.DataFixer;
import net.minecraft.util.datafix.FixTypes;
import net.minecraft.util.datafix.walkers.ItemStackData;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.world.DifficultyInstance;
import net.minecraft.world.World;
public abstract class AbstractHorse extends EntityAnimal implements IInventoryChangedListener, IJumpingMount
{
private static final Predicate<Entity> IS_HORSE_BREEDING = new Predicate<Entity>()
{
public boolean apply(@Nullable Entity p_apply_1_)
{
return p_apply_1_ instanceof AbstractHorse && ((AbstractHorse)p_apply_1_).isBreeding();
}
};
protected static final IAttribute JUMP_STRENGTH = (new RangedAttribute((IAttribute)null, "horse.jumpStrength", 0.7D, 0.0D, 2.0D)).setDescription("Jump Strength").setShouldWatch(true);
private static final DataParameter<Byte> STATUS = EntityDataManager.<Byte>createKey(AbstractHorse.class, DataSerializers.BYTE);
private static final DataParameter<Optional<UUID>> OWNER_UNIQUE_ID = EntityDataManager.<Optional<UUID>>createKey(AbstractHorse.class, DataSerializers.OPTIONAL_UNIQUE_ID);
private int field_190689_bJ;
private int openMouthCounter;
private int jumpRearingCounter;
public int tailCounter;
public int sprintCounter;
protected boolean horseJumping;
protected ContainerHorseChest horseChest;
/**
* "The higher this value, the more likely the horse is to be tamed next time a player rides it."
*/
protected int temper;
protected float jumpPower;
private boolean allowStandSliding;
private float headLean;
private float prevHeadLean;
private float rearingAmount;
private float prevRearingAmount;
private float mouthOpenness;
private float prevMouthOpenness;
protected boolean field_190688_bE = true;
/** Used to determine the sound that the horse should make when it steps */
protected int gallopTime;
public AbstractHorse(World p_i47299_1_)
{
super(p_i47299_1_);
this.setSize(1.3964844F, 1.6F);
this.stepHeight = 1.0F;
this.initHorseChest();
}
protected void initEntityAI()
{
this.tasks.addTask(0, new EntityAISwimming(this));
this.tasks.addTask(1, new EntityAIPanic(this, 1.2D));
this.tasks.addTask(1, new EntityAIRunAroundLikeCrazy(this, 1.2D));
this.tasks.addTask(2, new EntityAIMate(this, 1.0D, AbstractHorse.class));
this.tasks.addTask(4, new EntityAIFollowParent(this, 1.0D));
this.tasks.addTask(6, new EntityAIWanderAvoidWater(this, 0.7D));
this.tasks.addTask(7, new EntityAIWatchClosest(this, EntityPlayer.class, 6.0F));
this.tasks.addTask(8, new EntityAILookIdle(this));
}
protected void entityInit()
{
super.entityInit();
this.dataManager.register(STATUS, Byte.valueOf((byte)0));
this.dataManager.register(OWNER_UNIQUE_ID, Optional.absent());
}
protected boolean getHorseWatchableBoolean(int p_110233_1_)
{
return (((Byte)this.dataManager.get(STATUS)).byteValue() & p_110233_1_) != 0;
}
protected void setHorseWatchableBoolean(int p_110208_1_, boolean p_110208_2_)
{
byte b0 = ((Byte)this.dataManager.get(STATUS)).byteValue();
if (p_110208_2_)
{
this.dataManager.set(STATUS, Byte.valueOf((byte)(b0 | p_110208_1_)));
}
else
{
this.dataManager.set(STATUS, Byte.valueOf((byte)(b0 & ~p_110208_1_)));
}
}
public boolean isTame()
{
return this.getHorseWatchableBoolean(2);
}
@Nullable
public UUID getOwnerUniqueId()
{
return (UUID)((Optional)this.dataManager.get(OWNER_UNIQUE_ID)).orNull();
}
public void setOwnerUniqueId(@Nullable UUID uniqueId)
{
this.dataManager.set(OWNER_UNIQUE_ID, Optional.fromNullable(uniqueId));
}
public float getHorseSize()
{
return 0.5F;
}
/**
* "Sets the scale for an ageable entity according to the boolean parameter, which says if it's a child."
*/
public void setScaleForAge(boolean child)
{
this.setScale(child ? this.getHorseSize() : 1.0F);
}
public boolean isHorseJumping()
{
return this.horseJumping;
}
public void setHorseTamed(boolean tamed)
{
this.setHorseWatchableBoolean(2, tamed);
}
public void setHorseJumping(boolean jumping)
{
this.horseJumping = jumping;
}
public boolean canBeLeashedTo(EntityPlayer player)
{
return super.canBeLeashedTo(player) && this.getCreatureAttribute() != EnumCreatureAttribute.UNDEAD;
}
protected void onLeashDistance(float p_142017_1_)
{
if (p_142017_1_ > 6.0F && this.isEatingHaystack())
{
this.setEatingHaystack(false);
}
}
public boolean isEatingHaystack()
{
return this.getHorseWatchableBoolean(16);
}
public boolean isRearing()
{
return this.getHorseWatchableBoolean(32);
}
public boolean isBreeding()
{
return this.getHorseWatchableBoolean(8);
}
public void setBreeding(boolean breeding)
{
this.setHorseWatchableBoolean(8, breeding);
}
public void setHorseSaddled(boolean saddled)
{
this.setHorseWatchableBoolean(4, saddled);
}
public int getTemper()
{
return this.temper;
}
public void setTemper(int temperIn)
{
this.temper = temperIn;
}
public int increaseTemper(int p_110198_1_)
{
int i = MathHelper.clamp(this.getTemper() + p_110198_1_, 0, this.func_190676_dC());
this.setTemper(i);
return i;
}
/**
* Called when the entity is attacked.
*/
public boolean attackEntityFrom(DamageSource source, float amount)
{
Entity entity = source.getEntity();
return this.isBeingRidden() && entity != null && this.isRidingOrBeingRiddenBy(entity) ? false : super.attackEntityFrom(source, amount);
}
/**
* Returns true if this entity should push and be pushed by other entities when colliding.
*/
public boolean canBePushed()
{
return !this.isBeingRidden();
}
private void eatingHorse()
{
this.openHorseMouth();
if (!this.isSilent())
{
this.world.playSound((EntityPlayer)null, this.posX, this.posY, this.posZ, SoundEvents.ENTITY_HORSE_EAT, this.getSoundCategory(), 1.0F, 1.0F + (this.rand.nextFloat() - this.rand.nextFloat()) * 0.2F);
}
}
public void fall(float distance, float damageMultiplier)
{
if (distance > 1.0F)
{
this.playSound(SoundEvents.ENTITY_HORSE_LAND, 0.4F, 1.0F);
}
int i = MathHelper.ceil((distance * 0.5F - 3.0F) * damageMultiplier);
if (i > 0)
{
this.attackEntityFrom(DamageSource.fall, (float)i);
if (this.isBeingRidden())
{
for (Entity entity : this.getRecursivePassengers())
{
entity.attackEntityFrom(DamageSource.fall, (float)i);
}
}
IBlockState iblockstate = this.world.getBlockState(new BlockPos(this.posX, this.posY - 0.2D - (double)this.prevRotationYaw, this.posZ));
Block block = iblockstate.getBlock();
if (iblockstate.getMaterial() != Material.AIR && !this.isSilent())
{
SoundType soundtype = block.getSoundType();
this.world.playSound((EntityPlayer)null, this.posX, this.posY, this.posZ, soundtype.getStepSound(), this.getSoundCategory(), soundtype.getVolume() * 0.5F, soundtype.getPitch() * 0.75F);
}
}
}
protected int func_190686_di()
{
return 2;
}
protected void initHorseChest()
{
ContainerHorseChest containerhorsechest = this.horseChest;
this.horseChest = new ContainerHorseChest("HorseChest", this.func_190686_di());
this.horseChest.setCustomName(this.getName());
if (containerhorsechest != null)
{
containerhorsechest.removeInventoryChangeListener(this);
int i = Math.min(containerhorsechest.getSizeInventory(), this.horseChest.getSizeInventory());
for (int j = 0; j < i; ++j)
{
ItemStack itemstack = containerhorsechest.getStackInSlot(j);
if (!itemstack.func_190926_b())
{
this.horseChest.setInventorySlotContents(j, itemstack.copy());
}
}
}
this.horseChest.addInventoryChangeListener(this);
this.updateHorseSlots();
}
/**
* Updates the items in the saddle and armor slots of the horse's inventory.
*/
protected void updateHorseSlots()
{
if (!this.world.isRemote)
{
this.setHorseSaddled(!this.horseChest.getStackInSlot(0).func_190926_b() && this.func_190685_dA());
}
}
/**
* Called by InventoryBasic.onInventoryChanged() on a array that is never filled.
*/
public void onInventoryChanged(IInventory invBasic)
{
boolean flag = this.isHorseSaddled();
this.updateHorseSlots();
if (this.ticksExisted > 20 && !flag && this.isHorseSaddled())
{
this.playSound(SoundEvents.ENTITY_HORSE_SADDLE, 0.5F, 1.0F);
}
}
@Nullable
protected AbstractHorse getClosestHorse(Entity entityIn, double distance)
{
double d0 = Double.MAX_VALUE;
Entity entity = null;
for (Entity entity1 : this.world.getEntitiesInAABBexcluding(entityIn, entityIn.getEntityBoundingBox().addCoord(distance, distance, distance), IS_HORSE_BREEDING))
{
double d1 = entity1.getDistanceSq(entityIn.posX, entityIn.posY, entityIn.posZ);
if (d1 < d0)
{
entity = entity1;
d0 = d1;
}
}
return (AbstractHorse)entity;
}
public double getHorseJumpStrength()
{
return this.getEntityAttribute(JUMP_STRENGTH).getAttributeValue();
}
@Nullable
protected SoundEvent getDeathSound()
{
this.openHorseMouth();
return null;
}
@Nullable
protected SoundEvent getHurtSound(DamageSource p_184601_1_)
{
this.openHorseMouth();
if (this.rand.nextInt(3) == 0)
{
this.makeHorseRear();
}
return null;
}
@Nullable
protected SoundEvent getAmbientSound()
{
this.openHorseMouth();
if (this.rand.nextInt(10) == 0 && !this.isMovementBlocked())
{
this.makeHorseRear();
}
return null;
}
public boolean func_190685_dA()
{
return true;
}
public boolean isHorseSaddled()
{
return this.getHorseWatchableBoolean(4);
}
@Nullable
protected SoundEvent getAngrySound()
{
this.openHorseMouth();
this.makeHorseRear();
return null;
}
protected void playStepSound(BlockPos pos, Block blockIn)
{
if (!blockIn.getDefaultState().getMaterial().isLiquid())
{
SoundType soundtype = blockIn.getSoundType();
if (this.world.getBlockState(pos.up()).getBlock() == Blocks.SNOW_LAYER)
{
soundtype = Blocks.SNOW_LAYER.getSoundType();
}
if (this.isBeingRidden() && this.field_190688_bE)
{
++this.gallopTime;
if (this.gallopTime > 5 && this.gallopTime % 3 == 0)
{
this.func_190680_a(soundtype);
}
else if (this.gallopTime <= 5)
{
this.playSound(SoundEvents.ENTITY_HORSE_STEP_WOOD, soundtype.getVolume() * 0.15F, soundtype.getPitch());
}
}
else if (soundtype == SoundType.WOOD)
{
this.playSound(SoundEvents.ENTITY_HORSE_STEP_WOOD, soundtype.getVolume() * 0.15F, soundtype.getPitch());
}
else
{
this.playSound(SoundEvents.ENTITY_HORSE_STEP, soundtype.getVolume() * 0.15F, soundtype.getPitch());
}
}
}
protected void func_190680_a(SoundType p_190680_1_)
{
this.playSound(SoundEvents.ENTITY_HORSE_GALLOP, p_190680_1_.getVolume() * 0.15F, p_190680_1_.getPitch());
}
protected void applyEntityAttributes()
{
super.applyEntityAttributes();
this.getAttributeMap().registerAttribute(JUMP_STRENGTH);
this.getEntityAttribute(SharedMonsterAttributes.MAX_HEALTH).setBaseValue(53.0D);
this.getEntityAttribute(SharedMonsterAttributes.MOVEMENT_SPEED).setBaseValue(0.22499999403953552D);
}
/**
* Will return how many at most can spawn in a chunk at once.
*/
public int getMaxSpawnedInChunk()
{
return 6;
}
public int func_190676_dC()
{
return 100;
}
/**
* Returns the volume for the sounds this mob makes.
*/
protected float getSoundVolume()
{
return 0.8F;
}
/**
* Get number of ticks, at least during which the living entity will be silent.
*/
public int getTalkInterval()
{
return 400;
}
public void openGUI(EntityPlayer playerEntity)
{
if (!this.world.isRemote && (!this.isBeingRidden() || this.isPassenger(playerEntity)) && this.isTame())
{
this.horseChest.setCustomName(this.getName());
playerEntity.openGuiHorseInventory(this, this.horseChest);
}
}
protected boolean func_190678_b(EntityPlayer p_190678_1_, ItemStack p_190678_2_)
{
boolean flag = false;
float f = 0.0F;
int i = 0;
int j = 0;
Item item = p_190678_2_.getItem();
if (item == Items.WHEAT)
{
f = 2.0F;
i = 20;
j = 3;
}
else if (item == Items.SUGAR)
{
f = 1.0F;
i = 30;
j = 3;
}
else if (item == Item.getItemFromBlock(Blocks.HAY_BLOCK))
{
f = 20.0F;
i = 180;
}
else if (item == Items.APPLE)
{
f = 3.0F;
i = 60;
j = 3;
}
else if (item == Items.GOLDEN_CARROT)
{
f = 4.0F;
i = 60;
j = 5;
if (this.isTame() && this.getGrowingAge() == 0 && !this.isInLove())
{
flag = true;
this.setInLove(p_190678_1_);
}
}
else if (item == Items.GOLDEN_APPLE)
{
f = 10.0F;
i = 240;
j = 10;
if (this.isTame() && this.getGrowingAge() == 0 && !this.isInLove())
{
flag = true;
this.setInLove(p_190678_1_);
}
}
if (this.getHealth() < this.getMaxHealth() && f > 0.0F)
{
this.heal(f);
flag = true;
}
if (this.isChild() && i > 0)
{
this.world.spawnParticle(EnumParticleTypes.VILLAGER_HAPPY, this.posX + (double)(this.rand.nextFloat() * this.width * 2.0F) - (double)this.width, this.posY + 0.5D + (double)(this.rand.nextFloat() * this.height), this.posZ + (double)(this.rand.nextFloat() * this.width * 2.0F) - (double)this.width, 0.0D, 0.0D, 0.0D);
if (!this.world.isRemote)
{
this.addGrowth(i);
}
flag = true;
}
if (j > 0 && (flag || !this.isTame()) && this.getTemper() < this.func_190676_dC())
{
flag = true;
if (!this.world.isRemote)
{
this.increaseTemper(j);
}
}
if (flag)
{
this.eatingHorse();
}
return flag;
}
protected void mountTo(EntityPlayer player)
{
player.rotationYaw = this.rotationYaw;
player.rotationPitch = this.rotationPitch;
this.setEatingHaystack(false);
this.setRearing(false);
if (!this.world.isRemote)
{
player.startRiding(this);
}
}
/**
* Dead and sleeping entities cannot move
*/
protected boolean isMovementBlocked()
{
return super.isMovementBlocked() && this.isBeingRidden() && this.isHorseSaddled() || this.isEatingHaystack() || this.isRearing();
}
/**
* Checks if the parameter is an item which this animal can be fed to breed it (wheat, carrots or seeds depending on
* the animal type)
*/
public boolean isBreedingItem(ItemStack stack)
{
return false;
}
private void moveTail()
{
this.tailCounter = 1;
}
/**
* Called when the mob's health reaches 0.
*/
public void onDeath(DamageSource cause)
{
super.onDeath(cause);
if (!this.world.isRemote && this.horseChest != null)
{
for (int i = 0; i < this.horseChest.getSizeInventory(); ++i)
{
ItemStack itemstack = this.horseChest.getStackInSlot(i);
if (!itemstack.func_190926_b())
{
this.entityDropItem(itemstack, 0.0F);
}
}
}
}
/**
* Called frequently so the entity can update its state every tick as required. For example, zombies and skeletons
* use this to react to sunlight and start to burn.
*/
public void onLivingUpdate()
{
if (this.rand.nextInt(200) == 0)
{
this.moveTail();
}
super.onLivingUpdate();
if (!this.world.isRemote)
{
if (this.rand.nextInt(900) == 0 && this.deathTime == 0)
{
this.heal(1.0F);
}
if (this.func_190684_dE())
{
if (!this.isEatingHaystack() && !this.isBeingRidden() && this.rand.nextInt(300) == 0 && this.world.getBlockState(new BlockPos(MathHelper.floor(this.posX), MathHelper.floor(this.posY) - 1, MathHelper.floor(this.posZ))).getBlock() == Blocks.GRASS)
{
this.setEatingHaystack(true);
}
if (this.isEatingHaystack() && ++this.field_190689_bJ > 50)
{
this.field_190689_bJ = 0;
this.setEatingHaystack(false);
}
}
this.func_190679_dD();
}
}
protected void func_190679_dD()
{
if (this.isBreeding() && this.isChild() && !this.isEatingHaystack())
{
AbstractHorse abstracthorse = this.getClosestHorse(this, 16.0D);
if (abstracthorse != null && this.getDistanceSqToEntity(abstracthorse) > 4.0D)
{
this.navigator.getPathToEntityLiving(abstracthorse);
}
}
}
public boolean func_190684_dE()
{
return true;
}
/**
* Called to update the entity's position/logic.
*/
public void onUpdate()
{
super.onUpdate();
if (this.openMouthCounter > 0 && ++this.openMouthCounter > 30)
{
this.openMouthCounter = 0;
this.setHorseWatchableBoolean(64, false);
}
if (this.canPassengerSteer() && this.jumpRearingCounter > 0 && ++this.jumpRearingCounter > 20)
{
this.jumpRearingCounter = 0;
this.setRearing(false);
}
if (this.tailCounter > 0 && ++this.tailCounter > 8)
{
this.tailCounter = 0;
}
if (this.sprintCounter > 0)
{
++this.sprintCounter;
if (this.sprintCounter > 300)
{
this.sprintCounter = 0;
}
}
this.prevHeadLean = this.headLean;
if (this.isEatingHaystack())
{
this.headLean += (1.0F - this.headLean) * 0.4F + 0.05F;
if (this.headLean > 1.0F)
{
this.headLean = 1.0F;
}
}
else
{
this.headLean += (0.0F - this.headLean) * 0.4F - 0.05F;
if (this.headLean < 0.0F)
{
this.headLean = 0.0F;
}
}
this.prevRearingAmount = this.rearingAmount;
if (this.isRearing())
{
this.headLean = 0.0F;
this.prevHeadLean = this.headLean;
this.rearingAmount += (1.0F - this.rearingAmount) * 0.4F + 0.05F;
if (this.rearingAmount > 1.0F)
{
this.rearingAmount = 1.0F;
}
}
else
{
this.allowStandSliding = false;
this.rearingAmount += (0.8F * this.rearingAmount * this.rearingAmount * this.rearingAmount - this.rearingAmount) * 0.6F - 0.05F;
if (this.rearingAmount < 0.0F)
{
this.rearingAmount = 0.0F;
}
}
this.prevMouthOpenness = this.mouthOpenness;
if (this.getHorseWatchableBoolean(64))
{
this.mouthOpenness += (1.0F - this.mouthOpenness) * 0.7F + 0.05F;
if (this.mouthOpenness > 1.0F)
{
this.mouthOpenness = 1.0F;
}
}
else
{
this.mouthOpenness += (0.0F - this.mouthOpenness) * 0.7F - 0.05F;
if (this.mouthOpenness < 0.0F)
{
this.mouthOpenness = 0.0F;
}
}
}
private void openHorseMouth()
{
if (!this.world.isRemote)
{
this.openMouthCounter = 1;
this.setHorseWatchableBoolean(64, true);
}
}
public void setEatingHaystack(boolean p_110227_1_)
{
this.setHorseWatchableBoolean(16, p_110227_1_);
}
public void setRearing(boolean rearing)
{
if (rearing)
{
this.setEatingHaystack(false);
}
this.setHorseWatchableBoolean(32, rearing);
}
private void makeHorseRear()
{
if (this.canPassengerSteer())
{
this.jumpRearingCounter = 1;
this.setRearing(true);
}
}
public void func_190687_dF()
{
this.makeHorseRear();
SoundEvent soundevent = this.getAngrySound();
if (soundevent != null)
{
this.playSound(soundevent, this.getSoundVolume(), this.getSoundPitch());
}
}
public boolean setTamedBy(EntityPlayer player)
{
this.setOwnerUniqueId(player.getUniqueID());
this.setHorseTamed(true);
if (player instanceof EntityPlayerMP)
{
CriteriaTriggers.field_193136_w.func_193178_a((EntityPlayerMP)player, this);
}
this.world.setEntityState(this, (byte)7);
return true;
}
public void func_191986_a(float p_191986_1_, float p_191986_2_, float p_191986_3_)
{
if (this.isBeingRidden() && this.canBeSteered() && this.isHorseSaddled())
{
EntityLivingBase entitylivingbase = (EntityLivingBase)this.getControllingPassenger();
this.rotationYaw = entitylivingbase.rotationYaw;
this.prevRotationYaw = this.rotationYaw;
this.rotationPitch = entitylivingbase.rotationPitch * 0.5F;
this.setRotation(this.rotationYaw, this.rotationPitch);
this.renderYawOffset = this.rotationYaw;
this.rotationYawHead = this.renderYawOffset;
p_191986_1_ = entitylivingbase.moveStrafing * 0.5F;
p_191986_3_ = entitylivingbase.field_191988_bg;
if (p_191986_3_ <= 0.0F)
{
p_191986_3_ *= 0.25F;
this.gallopTime = 0;
}
if (this.onGround && this.jumpPower == 0.0F && this.isRearing() && !this.allowStandSliding)
{
p_191986_1_ = 0.0F;
p_191986_3_ = 0.0F;
}
if (this.jumpPower > 0.0F && !this.isHorseJumping() && this.onGround)
{
this.motionY = this.getHorseJumpStrength() * (double)this.jumpPower;
if (this.isPotionActive(MobEffects.JUMP_BOOST))
{
this.motionY += (double)((float)(this.getActivePotionEffect(MobEffects.JUMP_BOOST).getAmplifier() + 1) * 0.1F);
}
this.setHorseJumping(true);
this.isAirBorne = true;
if (p_191986_3_ > 0.0F)
{
float f = MathHelper.sin(this.rotationYaw * 0.017453292F);
float f1 = MathHelper.cos(this.rotationYaw * 0.017453292F);
this.motionX += (double)(-0.4F * f * this.jumpPower);
this.motionZ += (double)(0.4F * f1 * this.jumpPower);
this.playSound(SoundEvents.ENTITY_HORSE_JUMP, 0.4F, 1.0F);
}
this.jumpPower = 0.0F;
}
this.jumpMovementFactor = this.getAIMoveSpeed() * 0.1F;
if (this.canPassengerSteer())
{
this.setAIMoveSpeed((float)this.getEntityAttribute(SharedMonsterAttributes.MOVEMENT_SPEED).getAttributeValue());
super.func_191986_a(p_191986_1_, p_191986_2_, p_191986_3_);
}
else if (entitylivingbase instanceof EntityPlayer)
{
this.motionX = 0.0D;
this.motionY = 0.0D;
this.motionZ = 0.0D;
}
if (this.onGround)
{
this.jumpPower = 0.0F;
this.setHorseJumping(false);
}
this.prevLimbSwingAmount = this.limbSwingAmount;
double d1 = this.posX - this.prevPosX;
double d0 = this.posZ - this.prevPosZ;
float f2 = MathHelper.sqrt(d1 * d1 + d0 * d0) * 4.0F;
if (f2 > 1.0F)
{
f2 = 1.0F;
}
this.limbSwingAmount += (f2 - this.limbSwingAmount) * 0.4F;
this.limbSwing += this.limbSwingAmount;
}
else
{
this.jumpMovementFactor = 0.02F;
super.func_191986_a(p_191986_1_, p_191986_2_, p_191986_3_);
}
}
public static void func_190683_c(DataFixer p_190683_0_, Class<?> p_190683_1_)
{
EntityLiving.registerFixesMob(p_190683_0_, p_190683_1_);
p_190683_0_.registerWalker(FixTypes.ENTITY, new ItemStackData(p_190683_1_, new String[] {"SaddleItem"}));
}
/**
* (abstract) Protected helper method to write subclass entity data to NBT.
*/
public void writeEntityToNBT(NBTTagCompound compound)
{
super.writeEntityToNBT(compound);
compound.setBoolean("EatingHaystack", this.isEatingHaystack());
compound.setBoolean("Bred", this.isBreeding());
compound.setInteger("Temper", this.getTemper());
compound.setBoolean("Tame", this.isTame());
if (this.getOwnerUniqueId() != null)
{
compound.setString("OwnerUUID", this.getOwnerUniqueId().toString());
}
if (!this.horseChest.getStackInSlot(0).func_190926_b())
{
compound.setTag("SaddleItem", this.horseChest.getStackInSlot(0).writeToNBT(new NBTTagCompound()));
}
}
/**
* (abstract) Protected helper method to read subclass entity data from NBT.
*/
public void readEntityFromNBT(NBTTagCompound compound)
{
super.readEntityFromNBT(compound);
this.setEatingHaystack(compound.getBoolean("EatingHaystack"));
this.setBreeding(compound.getBoolean("Bred"));
this.setTemper(compound.getInteger("Temper"));
this.setHorseTamed(compound.getBoolean("Tame"));
String s;
if (compound.hasKey("OwnerUUID", 8))
{
s = compound.getString("OwnerUUID");
}
else
{
String s1 = compound.getString("Owner");
s = PreYggdrasilConverter.convertMobOwnerIfNeeded(this.getServer(), s1);
}
if (!s.isEmpty())
{
this.setOwnerUniqueId(UUID.fromString(s));
}
IAttributeInstance iattributeinstance = this.getAttributeMap().getAttributeInstanceByName("Speed");
if (iattributeinstance != null)
{
this.getEntityAttribute(SharedMonsterAttributes.MOVEMENT_SPEED).setBaseValue(iattributeinstance.getBaseValue() * 0.25D);
}
if (compound.hasKey("SaddleItem", 10))
{
ItemStack itemstack = new ItemStack(compound.getCompoundTag("SaddleItem"));
if (itemstack.getItem() == Items.SADDLE)
{
this.horseChest.setInventorySlotContents(0, itemstack);
}
}
this.updateHorseSlots();
}
/**
* Returns true if the mob is currently able to mate with the specified mob.
*/
public boolean canMateWith(EntityAnimal otherAnimal)
{
return false;
}
/**
* Return true if the horse entity ready to mate. (no rider, not riding, tame, adult, not steril...)
*/
protected boolean canMate()
{
return !this.isBeingRidden() && !this.isRiding() && this.isTame() && !this.isChild() && this.getHealth() >= this.getMaxHealth() && this.isInLove();
}
@Nullable
public EntityAgeable createChild(EntityAgeable ageable)
{
return null;
}
protected void func_190681_a(EntityAgeable p_190681_1_, AbstractHorse p_190681_2_)
{
double d0 = this.getEntityAttribute(SharedMonsterAttributes.MAX_HEALTH).getBaseValue() + p_190681_1_.getEntityAttribute(SharedMonsterAttributes.MAX_HEALTH).getBaseValue() + (double)this.getModifiedMaxHealth();
p_190681_2_.getEntityAttribute(SharedMonsterAttributes.MAX_HEALTH).setBaseValue(d0 / 3.0D);
double d1 = this.getEntityAttribute(JUMP_STRENGTH).getBaseValue() + p_190681_1_.getEntityAttribute(JUMP_STRENGTH).getBaseValue() + this.getModifiedJumpStrength();
p_190681_2_.getEntityAttribute(JUMP_STRENGTH).setBaseValue(d1 / 3.0D);
double d2 = this.getEntityAttribute(SharedMonsterAttributes.MOVEMENT_SPEED).getBaseValue() + p_190681_1_.getEntityAttribute(SharedMonsterAttributes.MOVEMENT_SPEED).getBaseValue() + this.getModifiedMovementSpeed();
p_190681_2_.getEntityAttribute(SharedMonsterAttributes.MOVEMENT_SPEED).setBaseValue(d2 / 3.0D);
}
/**
* returns true if all the conditions for steering the entity are met. For pigs, this is true if it is being ridden
* by a player and the player is holding a carrot-on-a-stick
*/
public boolean canBeSteered()
{
return this.getControllingPassenger() instanceof EntityLivingBase;
}
public float getGrassEatingAmount(float p_110258_1_)
{
return this.prevHeadLean + (this.headLean - this.prevHeadLean) * p_110258_1_;
}
public float getRearingAmount(float p_110223_1_)
{
return this.prevRearingAmount + (this.rearingAmount - this.prevRearingAmount) * p_110223_1_;
}
public float getMouthOpennessAngle(float p_110201_1_)
{
return this.prevMouthOpenness + (this.mouthOpenness - this.prevMouthOpenness) * p_110201_1_;
}
public void setJumpPower(int jumpPowerIn)
{
if (this.isHorseSaddled())
{
if (jumpPowerIn < 0)
{
jumpPowerIn = 0;
}
else
{
this.allowStandSliding = true;
this.makeHorseRear();
}
if (jumpPowerIn >= 90)
{
this.jumpPower = 1.0F;
}
else
{
this.jumpPower = 0.4F + 0.4F * (float)jumpPowerIn / 90.0F;
}
}
}
public boolean canJump()
{
return this.isHorseSaddled();
}
public void handleStartJump(int p_184775_1_)
{
this.allowStandSliding = true;
this.makeHorseRear();
}
public void handleStopJump()
{
}
/**
* "Spawns particles for the horse entity. par1 tells whether to spawn hearts. If it is false, it spawns smoke."
*/
protected void spawnHorseParticles(boolean p_110216_1_)
{
EnumParticleTypes enumparticletypes = p_110216_1_ ? EnumParticleTypes.HEART : EnumParticleTypes.SMOKE_NORMAL;
for (int i = 0; i < 7; ++i)
{
double d0 = this.rand.nextGaussian() * 0.02D;
double d1 = this.rand.nextGaussian() * 0.02D;
double d2 = this.rand.nextGaussian() * 0.02D;
this.world.spawnParticle(enumparticletypes, this.posX + (double)(this.rand.nextFloat() * this.width * 2.0F) - (double)this.width, this.posY + 0.5D + (double)(this.rand.nextFloat() * this.height), this.posZ + (double)(this.rand.nextFloat() * this.width * 2.0F) - (double)this.width, d0, d1, d2);
}
}
public void handleStatusUpdate(byte id)
{
if (id == 7)
{
this.spawnHorseParticles(true);
}
else if (id == 6)
{
this.spawnHorseParticles(false);
}
else
{
super.handleStatusUpdate(id);
}
}
public void updatePassenger(Entity passenger)
{
super.updatePassenger(passenger);
if (passenger instanceof EntityLiving)
{
EntityLiving entityliving = (EntityLiving)passenger;
this.renderYawOffset = entityliving.renderYawOffset;
}
if (this.prevRearingAmount > 0.0F)
{
float f3 = MathHelper.sin(this.renderYawOffset * 0.017453292F);
float f = MathHelper.cos(this.renderYawOffset * 0.017453292F);
float f1 = 0.7F * this.prevRearingAmount;
float f2 = 0.15F * this.prevRearingAmount;
passenger.setPosition(this.posX + (double)(f1 * f3), this.posY + this.getMountedYOffset() + passenger.getYOffset() + (double)f2, this.posZ - (double)(f1 * f));
if (passenger instanceof EntityLivingBase)
{
((EntityLivingBase)passenger).renderYawOffset = this.renderYawOffset;
}
}
}
/**
* Returns randomized max health
*/
protected float getModifiedMaxHealth()
{
return 15.0F + (float)this.rand.nextInt(8) + (float)this.rand.nextInt(9);
}
/**
* Returns randomized jump strength
*/
protected double getModifiedJumpStrength()
{
return 0.4000000059604645D + this.rand.nextDouble() * 0.2D + this.rand.nextDouble() * 0.2D + this.rand.nextDouble() * 0.2D;
}
/**
* Returns randomized movement speed
*/
protected double getModifiedMovementSpeed()
{
return (0.44999998807907104D + this.rand.nextDouble() * 0.3D + this.rand.nextDouble() * 0.3D + this.rand.nextDouble() * 0.3D) * 0.25D;
}
/**
* returns true if this entity is by a ladder, false otherwise
*/
public boolean isOnLadder()
{
return false;
}
public float getEyeHeight()
{
return this.height;
}
public boolean func_190677_dK()
{
return false;
}
public boolean func_190682_f(ItemStack p_190682_1_)
{
return false;
}
public boolean replaceItemInInventory(int inventorySlot, ItemStack itemStackIn)
{
int i = inventorySlot - 400;
if (i >= 0 && i < 2 && i < this.horseChest.getSizeInventory())
{
if (i == 0 && itemStackIn.getItem() != Items.SADDLE)
{
return false;
}
else if (i != 1 || this.func_190677_dK() && this.func_190682_f(itemStackIn))
{
this.horseChest.setInventorySlotContents(i, itemStackIn);
this.updateHorseSlots();
return true;
}
else
{
return false;
}
}
else
{
int j = inventorySlot - 500 + 2;
if (j >= 2 && j < this.horseChest.getSizeInventory())
{
this.horseChest.setInventorySlotContents(j, itemStackIn);
return true;
}
else
{
return false;
}
}
}
@Nullable
/**
* For vehicles, the first passenger is generally considered the controller and "drives" the vehicle. For example,
* Pigs, Horses, and Boats are generally "steered" by the controlling passenger.
*/
public Entity getControllingPassenger()
{
return this.getPassengers().isEmpty() ? null : (Entity)this.getPassengers().get(0);
}
@Nullable
/**
* Called only once on an entity when first time spawned, via egg, mob spawner, natural spawning etc, but not called
* when entity is reloaded from nbt. Mainly used for initializing attributes and inventory
*/
public IEntityLivingData onInitialSpawn(DifficultyInstance difficulty, @Nullable IEntityLivingData livingdata)
{
livingdata = super.onInitialSpawn(difficulty, livingdata);
if (this.rand.nextInt(5) == 0)
{
this.setGrowingAge(-24000);
}
return livingdata;
}
}
| 1 | 0.923057 | 1 | 0.923057 | game-dev | MEDIA | 0.995405 | game-dev | 0.953824 | 1 | 0.953824 |
emeiri/ogldev | 1,899 | Physics/Source/fake_spring_force.cpp | /*
Copyright 2024 Etay Meiri
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "particle.h"
#include "fake_spring_force_generator.h"
namespace OgldevPhysics {
FakeSpringForceGenerator::FakeSpringForceGenerator(const Vector3f* pAnchor, float SpringConstant, float Damping)
{
m_pAnchor = pAnchor;
m_springConstant = SpringConstant;
m_damping = Damping;
}
void FakeSpringForceGenerator::Init(const Vector3f* pAnchor, float SpringConstant, float Damping)
{
m_pAnchor = pAnchor;
m_springConstant = SpringConstant;
m_damping = Damping;
}
void FakeSpringForceGenerator::UpdateForce(Particle* pParticle, float dt)
{
if (!pParticle->HasFiniteMass()) {
return;
}
Vector3f Position = pParticle->GetPosition() - *m_pAnchor;
float Gamma = 0.5f * sqrtf(4.0f * m_springConstant - m_damping * m_damping);
if (Gamma == 0.0f) {
return;
}
Vector3f c = Position * (m_damping / (2.0f * Gamma)) + pParticle->GetVelocity() * (1.0f / Gamma);
Vector3f Target = Position * cosf(Gamma * dt) + c * sinf(Gamma * dt);
Vector3f Acceleration = (Target - Position) * (1.0f / dt * dt) - pParticle->GetVelocity() * dt;
Vector3f Force = Acceleration * pParticle->GetMass();
pParticle->AddForce(Force);
}
} | 1 | 0.707519 | 1 | 0.707519 | game-dev | MEDIA | 0.732618 | game-dev | 0.837327 | 1 | 0.837327 |
remotion-dev/cloudflare-containers-demo | 1,736 | src/HelloWorld/Logo.tsx | import {
AbsoluteFill,
interpolate,
spring,
useCurrentFrame,
useVideoConfig,
} from "remotion";
import { Arc } from "./Arc";
import { Atom } from "./Atom";
import { z } from "zod";
import { zColor } from "@remotion/zod-types";
export const myCompSchema2 = z.object({
logoColor1: zColor(),
logoColor2: zColor(),
});
export const Logo: React.FC<z.infer<typeof myCompSchema2>> = ({
logoColor1: color1,
logoColor2: color2,
}) => {
const videoConfig = useVideoConfig();
const frame = useCurrentFrame();
const development = spring({
config: {
damping: 100,
mass: 0.5,
},
fps: videoConfig.fps,
frame,
});
const rotationDevelopment = spring({
config: {
damping: 100,
mass: 0.5,
},
fps: videoConfig.fps,
frame,
});
const scale = spring({
frame,
config: {
mass: 0.5,
},
fps: videoConfig.fps,
});
const logoRotation = interpolate(
frame,
[0, videoConfig.durationInFrames],
[0, 360],
);
return (
<AbsoluteFill
style={{
transform: `scale(${scale}) rotate(${logoRotation}deg)`,
}}
>
<Arc
rotateProgress={rotationDevelopment}
progress={development}
rotation={30}
color1={color1}
color2={color2}
/>
<Arc
rotateProgress={rotationDevelopment}
rotation={90}
progress={development}
color1={color1}
color2={color2}
/>
<Arc
rotateProgress={rotationDevelopment}
rotation={-30}
progress={development}
color1={color1}
color2={color2}
/>
<Atom scale={rotationDevelopment} color1={color1} color2={color2} />
</AbsoluteFill>
);
};
| 1 | 0.586809 | 1 | 0.586809 | game-dev | MEDIA | 0.465339 | game-dev,graphics-rendering | 0.787895 | 1 | 0.787895 |
volskaya/windovigation.nvim | 1,219 | lua/windovigation/keymaps.lua | local actions = require("windovigation.actions")
local options = require("windovigation.options")
local M = {}
---@param buf integer?
M.set_default_keymaps = function(buf)
if not options.keymaps then
return
end
local movement_key = options.keymaps.bracket_movement_key or ""
local movement_key_lwr = string.lower(movement_key)
local movement_key_upr = string.upper(movement_key)
local close_key = options.keymaps.buffer_close_key or ""
local keymaps = movement_key:len() > 0
and {
{ "n", "[" .. movement_key_lwr, actions.move_to_previous_file, "Previous File" },
{ "n", "]" .. movement_key_lwr, actions.move_to_next_file, "Next File" },
{ "n", "[" .. movement_key_upr, actions.move_to_first_file, "First File" },
{ "n", "]" .. movement_key_upr, actions.move_to_last_file, "Last File" },
}
or {}
if close_key:len() > 0 then
table.insert(keymaps, { "n", "<leader>b" .. close_key, actions.close_current_file, "Close File" })
end
for _, keymap in ipairs(keymaps) do
local opts = { desc = keymap[4], buffer = buf, noremap = true } ---@type vim.keymap.set.Opts
vim.keymap.set(keymap[1], keymap[2], keymap[3], opts)
end
end
return M
| 1 | 0.772191 | 1 | 0.772191 | game-dev | MEDIA | 0.62947 | game-dev | 0.613374 | 1 | 0.613374 |
patrickheng/vuejs-threejs-webpack-boilerplate | 25,599 | src/utils/webgl/AWDLoader.js | /* eslint-disable */
var UNCOMPRESSED = 0,
DEFLATE = 1,
LZMA = 2,
AWD_FIELD_INT8 = 1,
AWD_FIELD_INT16 = 2,
AWD_FIELD_INT32 = 3,
AWD_FIELD_UINT8 = 4,
AWD_FIELD_UINT16 = 5,
AWD_FIELD_UINT32 = 6,
AWD_FIELD_FLOAT32 = 7,
AWD_FIELD_FLOAT64 = 8,
AWD_FIELD_BOOL = 21,
AWD_FIELD_COLOR = 22,
AWD_FIELD_BADDR = 23,
AWD_FIELD_STRING = 31,
AWD_FIELD_BYTEARRAY = 32,
AWD_FIELD_VECTOR2x1 = 41,
AWD_FIELD_VECTOR3x1 = 42,
AWD_FIELD_VECTOR4x1 = 43,
AWD_FIELD_MTX3x2 = 44,
AWD_FIELD_MTX3x3 = 45,
AWD_FIELD_MTX4x3 = 46,
AWD_FIELD_MTX4x4 = 47,
BOOL = 21,
COLOR = 22,
BADDR = 23,
INT8 = 1,
INT16 = 2,
INT32 = 3,
UINT8 = 4,
UINT16 = 5,
UINT32 = 6,
FLOAT32 = 7,
FLOAT64 = 8;
var littleEndian = true;
function Block() {
this.id = 0;
this.data = null;
}
const AWDProperties = function() {}
AWDProperties.prototype = {
set : function( key, value ) {
this[ key ] = value;
},
get : function( key, fallback ) {
if ( this.hasOwnProperty( key ) )
return this[ key ];
else return fallback;
}
}
const AWDLoader = function ( manager ) {
this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
this.trunk = new THREE.Object3D();
this.materialFactory = undefined;
this._url = '';
this._baseDir = '';
this._data;
this._ptr = 0;
this._version = [];
this._streaming = false;
this._optimized_for_accuracy = false;
this._compression = 0;
this._bodylen = 0xFFFFFFFF;
this._blocks = [ new Block() ];
this._accuracyMatrix = false;
this._accuracyGeo = false;
this._accuracyProps = false;
};
AWDLoader.prototype = {
constructor: AWDLoader,
load: function ( url, onLoad, onProgress, onError ) {
var scope = this;
this._url = url;
this._baseDir = url.substr( 0, url.lastIndexOf( '/' ) + 1 );
var loader = new THREE.XHRLoader( this.manager );
loader.setResponseType( 'arraybuffer' );
loader.load( url, function ( text ) {
onLoad( scope.parse( text ) );
}, onProgress, onError );
},
parse: function ( data ) {
var blen = data.byteLength;
this._ptr = 0;
this._data = new DataView( data );
this._parseHeader( );
if ( this._compression != 0 ) {
console.error( 'compressed AWD not supported' );
}
if ( ! this._streaming && this._bodylen != data.byteLength - this._ptr ) {
console.error( 'AWDLoader: body len does not match file length', this._bodylen, blen - this._ptr );
}
while ( this._ptr < blen ) {
this.parseNextBlock();
}
return this.trunk;
},
parseNextBlock: function() {
var assetData,
ns, type, len, block,
blockId = this.readU32(),
ns = this.readU8(),
type = this.readU8(),
flags = this.readU8(),
len = this.readU32();
switch ( type ) {
case 1:
assetData = this.parseMeshData( len );
break;
case 22:
assetData = this.parseContainer( len );
break;
case 23:
assetData = this.parseMeshInstance( len );
break;
case 81:
assetData = this.parseMaterial( len );
break;
case 82:
assetData = this.parseTexture( len );
break;
case 101:
assetData = this.parseSkeleton( len );
break;
// case 111:
// assetData = this.parseMeshPoseAnimation(len, true);
// break;
case 112:
assetData = this.parseMeshPoseAnimation( len, false );
break;
case 113:
assetData = this.parseVertexAnimationSet( len );
break;
case 102:
assetData = this.parseSkeletonPose( len );
break;
case 103:
assetData = this.parseSkeletonAnimation( len );
break;
case 122:
assetData = this.parseAnimatorSet( len );
break;
// case 121:
// assetData = parseUVAnimation(len);
// break;
default:
//debug('Ignoring block!',type, len);
this._ptr += len;
break;
}
// Store block reference for later use
this._blocks[ blockId ] = block = new Block();
block.data = assetData;
block.id = blockId;
},
_parseHeader: function () {
var version = this._version,
awdmagic =
( this.readU8() << 16 )
| ( this.readU8() << 8 )
| this.readU8();
if ( awdmagic != 4282180 )
throw new Error( "AWDLoader - bad magic" );
version[ 0 ] = this.readU8();
version[ 1 ] = this.readU8();
var flags = this.readU16();
this._streaming = ( flags & 0x1 ) == 0x1;
if ( ( version[ 0 ] === 2 ) && ( version[ 1 ] === 1 ) ) {
this._accuracyMatrix = ( flags & 0x2 ) === 0x2;
this._accuracyGeo = ( flags & 0x4 ) === 0x4;
this._accuracyProps = ( flags & 0x8 ) === 0x8;
}
this._geoNrType = this._accuracyGeo ? FLOAT64 : FLOAT32;
this._matrixNrType = this._accuracyMatrix ? FLOAT64 : FLOAT32;
this._propsNrType = this._accuracyProps ? FLOAT64 : FLOAT32;
this._optimized_for_accuracy = ( flags & 0x2 ) === 0x2;
this._compression = this.readU8();
this._bodylen = this.readU32();
},
parseContainer: function ( len ) {
var parent,
ctr = new THREE.Object3D(),
par_id = this.readU32(),
mtx = this.parseMatrix4();
ctr.name = this.readUTF();
ctr.applyMatrix( mtx );
parent = this._blocks[ par_id ].data || this.trunk;
parent.add( ctr );
this.parseProperties( {
1: this._matrixNrType,
2: this._matrixNrType,
3: this._matrixNrType,
4: UINT8
} );
ctr.extra = this.parseUserAttributes();
return ctr;
},
parseMeshInstance: function ( len ) {
var name,
mesh, geometries, meshLen, meshes,
par_id, data_id,
mtx,
materials, mat, mat_id,
num_materials,
materials_parsed,
parent,
i;
par_id = this.readU32();
mtx = this.parseMatrix4();
name = this.readUTF();
data_id = this.readU32();
num_materials = this.readU16();
geometries = this.getBlock( data_id );
materials = [];
materials_parsed = 0;
for ( i = 0; i < num_materials; i ++ ) {
mat_id = this.readU32();
mat = this.getBlock( mat_id );
materials.push( mat );
}
meshLen = geometries.length;
meshes = [];
// TODO : BufferGeometry don't support "geometryGroups" for now.
// so we create sub meshes for each groups
if ( meshLen > 1 ) {
mesh = new THREE.Object3D();
for ( i = 0; i < meshLen; i ++ ) {
var sm = new THREE.Mesh( geometries[ i ] );
meshes.push( sm );
mesh.add( sm );
}
} else {
mesh = new THREE.Mesh( geometries[ 0 ] );
meshes.push( mesh );
}
mesh.applyMatrix( mtx );
mesh.name = name;
parent = this.getBlock( par_id ) || this.trunk;
parent.add( mesh );
var matLen = materials.length;
var maxLen = Math.max( meshLen, matLen );
for ( i = 0; i < maxLen; i ++ )
meshes[ i % meshLen ].material = materials[ i % matLen ];
// Ignore for now
this.parseProperties( null );
mesh.extra = this.parseUserAttributes();
return mesh;
},
parseMaterial: function ( len ) {
var name,
type,
props,
mat,
attributes,
finalize,
num_methods,
methods_parsed;
name = this.readUTF();
type = this.readU8();
num_methods = this.readU8();
//log( "AWDLoader parseMaterial ",name )
// Read material numerical properties
// (1=color, 2=bitmap url, 11=alpha_blending, 12=alpha_threshold, 13=repeat)
props = this.parseProperties( {
1: AWD_FIELD_INT32,
2: AWD_FIELD_BADDR,
11: AWD_FIELD_BOOL,
12: AWD_FIELD_FLOAT32,
13: AWD_FIELD_BOOL
} );
methods_parsed = 0;
while ( methods_parsed < num_methods ) {
var method_type = this.readU16();
this.parseProperties( null );
this.parseUserAttributes();
}
attributes = this.parseUserAttributes();
if ( this.materialFactory !== undefined ) {
mat = this.materialFactory( name );
if ( mat ) return mat;
}
mat = new THREE.MeshPhongMaterial();
if ( type === 1 ) {
// Color material
mat.color.setHex( props.get( 1, 0xcccccc ) );
} else if ( type === 2 ) {
// Bitmap material
var tex_addr = props.get( 2, 0 );
mat.map = this.getBlock( tex_addr );
}
mat.extra = attributes;
mat.alphaThreshold = props.get( 12, 0.0 );
mat.repeat = props.get( 13, false );
return mat;
},
parseTexture: function( len ) {
var name = this.readUTF(),
type = this.readU8(),
asset,
data_len;
// External
if ( type === 0 ) {
data_len = this.readU32();
var url = this.readUTFBytes( data_len );
console.log( url );
asset = this.loadTexture( url );
} else {
// embed texture not supported
}
// Ignore for now
this.parseProperties( null );
this.parseUserAttributes();
return asset;
},
loadTexture: function( url ) {
var tex = new THREE.Texture();
var loader = new THREE.ImageLoader( this.manager );
loader.load( this._baseDir + url, function( image ) {
tex.image = image;
tex.needsUpdate = true;
} );
return tex;
},
parseSkeleton: function( len ) {
// Array<Bone>
var name = this.readUTF(),
num_joints = this.readU16(),
skeleton = [],
joints_parsed = 0;
this.parseProperties( null );
while ( joints_parsed < num_joints ) {
var joint, ibp;
// Ignore joint id
this.readU16();
joint = new THREE.Bone();
joint.parent = this.readU16() - 1; // 0=null in AWD
joint.name = this.readUTF();
ibp = this.parseMatrix4();
joint.skinMatrix = ibp;
// Ignore joint props/attributes for now
this.parseProperties( null );
this.parseUserAttributes();
skeleton.push( joint );
joints_parsed ++;
}
// Discard attributes for now
this.parseUserAttributes();
return skeleton;
},
parseSkeletonPose: function( blockID ) {
var name = this.readUTF();
var num_joints = this.readU16();
this.parseProperties( null );
// debug( 'parse Skeleton Pose. joints : ' + num_joints);
var pose = [];
var joints_parsed = 0;
while ( joints_parsed < num_joints ) {
var joint_pose;
var has_transform; //:uint;
var mtx_data;
has_transform = this.readU8();
if ( has_transform === 1 ) {
mtx_data = this.parseMatrix4();
} else {
mtx_data = new THREE.Matrix4();
}
pose[ joints_parsed ] = mtx_data;
joints_parsed ++;
}
// Skip attributes for now
this.parseUserAttributes();
return pose;
},
parseSkeletonAnimation: function( blockID ) {
var frame_dur;
var pose_addr;
var pose;
var name = this.readUTF();
var clip = [];
var num_frames = this.readU16();
this.parseProperties( null );
var frames_parsed = 0;
var returnedArray;
// debug( 'parse Skeleton Animation. frames : ' + num_frames);
while ( frames_parsed < num_frames ) {
pose_addr = this.readU32();
frame_dur = this.readU16();
pose = this._blocks[ pose_addr ].data;
// debug( 'pose address ',pose[2].elements[12],pose[2].elements[13],pose[2].elements[14] );
clip.push( {
pose : pose,
duration : frame_dur
} );
frames_parsed ++;
}
if ( clip.length === 0 ) {
// debug("Could not this SkeletonClipNode, because no Frames where set.");
return;
}
// Ignore attributes for now
this.parseUserAttributes();
return clip;
},
parseVertexAnimationSet: function( len ) {
var poseBlockAdress,
name = this.readUTF(),
num_frames = this.readU16(),
props = this.parseProperties( { 1: UINT16 } ),
frames_parsed = 0,
skeletonFrames = [];
while ( frames_parsed < num_frames ) {
poseBlockAdress = this.readU32();
skeletonFrames.push( this._blocks[ poseBlockAdress ].data );
frames_parsed ++;
}
this.parseUserAttributes();
return skeletonFrames;
},
parseAnimatorSet: function( len ) {
var targetMesh;
var animSetBlockAdress; //:int
var targetAnimationSet; //:AnimationSetBase;
var outputString = ""; //:String = "";
var name = this.readUTF();
var type = this.readU16();
var props = this.parseProperties( { 1: BADDR } );
animSetBlockAdress = this.readU32();
var targetMeshLength = this.readU16();
var meshAdresses = []; //:Vector.<uint> = new Vector.<uint>;
for ( var i = 0; i < targetMeshLength; i ++ )
meshAdresses.push( this.readU32() );
var activeState = this.readU16();
var autoplay = Boolean( this.readU8() );
this.parseUserAttributes();
this.parseUserAttributes();
var returnedArray;
var targetMeshes = []; //:Vector.<Mesh> = new Vector.<Mesh>;
for ( i = 0; i < meshAdresses.length; i ++ ) {
// returnedArray = getAssetByID(meshAdresses[i], [AssetType.MESH]);
// if (returnedArray[0])
targetMeshes.push( this._blocks[ meshAdresses[ i ]].data );
}
targetAnimationSet = this._blocks[ animSetBlockAdress ].data;
var thisAnimator;
if ( type == 1 ) {
thisAnimator = {
animationSet : targetAnimationSet,
skeleton : this._blocks[ props.get( 1, 0 ) ].data
};
} else if ( type == 2 ) {
// debug( "vertex Anim???");
}
for ( i = 0; i < targetMeshes.length; i ++ ) {
targetMeshes[ i ].animator = thisAnimator;
}
// debug("Parsed a Animator: Name = " + name);
return thisAnimator;
},
parseMeshData: function ( len ) {
var name = this.readUTF(),
num_subs = this.readU16(),
geom,
subs_parsed = 0,
props,
buffer,
skinW, skinI,
geometries = [];
props = this.parseProperties( {
1: this._geoNrType,
2: this._geoNrType
} );
// Loop through sub meshes
while ( subs_parsed < num_subs ) {
var sm_len, sm_end, attrib;
geom = new THREE.BufferGeometry();
geom.name = name;
geometries.push( geom );
sm_len = this.readU32();
sm_end = this._ptr + sm_len;
// Ignore for now
this.parseProperties( { 1: this._geoNrType, 2: this._geoNrType } );
// Loop through data streams
while ( this._ptr < sm_end ) {
var idx = 0,
str_type = this.readU8(),
str_ftype = this.readU8(),
str_len = this.readU32(),
str_end = str_len + this._ptr;
// VERTICES
// ------------------
if ( str_type === 1 ) {
buffer = new Float32Array( ( str_len / 12 ) * 3 );
attrib = new THREE.BufferAttribute( buffer, 3 );
geom.addAttribute( 'position', attrib );
idx = 0;
while ( this._ptr < str_end ) {
buffer[ idx ] = - this.readF32();
buffer[ idx + 1 ] = this.readF32();
buffer[ idx + 2 ] = this.readF32();
idx += 3;
}
}
// INDICES
// -----------------
else if ( str_type === 2 ) {
buffer = new Uint16Array( str_len / 2 );
attrib = new THREE.BufferAttribute( buffer, 1 );
geom.setIndex( attrib );
idx = 0;
while ( this._ptr < str_end ) {
buffer[ idx + 1 ] = this.readU16();
buffer[ idx ] = this.readU16();
buffer[ idx + 2 ] = this.readU16();
idx += 3;
}
}
// UVS
// -------------------
else if ( str_type === 3 ) {
buffer = new Float32Array( ( str_len / 8 ) * 2 );
attrib = new THREE.BufferAttribute( buffer, 2 );
geom.addAttribute( 'uv', attrib );
idx = 0;
while ( this._ptr < str_end ) {
buffer[ idx ] = this.readF32();
buffer[ idx + 1 ] = 1.0 - this.readF32();
idx += 2;
}
}
// NORMALS
else if ( str_type === 4 ) {
buffer = new Float32Array( ( str_len / 12 ) * 3 );
attrib = new THREE.BufferAttribute( buffer, 3 );
geom.addAttribute( 'normal', attrib );
idx = 0;
while ( this._ptr < str_end ) {
buffer[ idx ] = - this.readF32();
buffer[ idx + 1 ] = this.readF32();
buffer[ idx + 2 ] = this.readF32();
idx += 3;
}
}
// else if (str_type == 6) {
// skinI = new Float32Array( str_len>>1 );
// idx = 0
// while (this._ptr < str_end) {
// skinI[idx] = this.readU16();
// idx++;
// }
// }
// else if (str_type == 7) {
// skinW = new Float32Array( str_len>>2 );
// idx = 0;
// while (this._ptr < str_end) {
// skinW[idx] = this.readF32();
// idx++;
// }
// }
else {
this._ptr = str_end;
}
}
this.parseUserAttributes();
geom.computeBoundingSphere();
subs_parsed ++;
}
//geom.computeFaceNormals();
this.parseUserAttributes();
//finalizeAsset(geom, name);
return geometries;
},
parseMeshPoseAnimation: function( len, poseOnly ) {
var num_frames = 1,
num_submeshes,
frames_parsed,
subMeshParsed,
frame_dur,
x, y, z,
str_len,
str_end,
geom,
subGeom,
idx = 0,
clip = {},
indices,
verts,
num_Streams,
streamsParsed,
streamtypes = [],
props,
thisGeo,
name = this.readUTF(),
geoAdress = this.readU32();
var mesh = this.getBlock( geoAdress );
if ( mesh === null ) {
console.log( "parseMeshPoseAnimation target mesh not found at:", geoAdress );
return;
}
geom = mesh.geometry;
geom.morphTargets = [];
if ( ! poseOnly )
num_frames = this.readU16();
num_submeshes = this.readU16();
num_Streams = this.readU16();
// debug("VA num_frames : ", num_frames );
// debug("VA num_submeshes : ", num_submeshes );
// debug("VA numstreams : ", num_Streams );
streamsParsed = 0;
while ( streamsParsed < num_Streams ) {
streamtypes.push( this.readU16() );
streamsParsed ++;
}
props = this.parseProperties( { 1: BOOL, 2: BOOL } );
clip.looping = props.get( 1, true );
clip.stitchFinalFrame = props.get( 2, false );
frames_parsed = 0;
while ( frames_parsed < num_frames ) {
frame_dur = this.readU16();
subMeshParsed = 0;
while ( subMeshParsed < num_submeshes ) {
streamsParsed = 0;
str_len = this.readU32();
str_end = this._ptr + str_len;
while ( streamsParsed < num_Streams ) {
if ( streamtypes[ streamsParsed ] === 1 ) {
//geom.addAttribute( 'morphTarget'+frames_parsed, Float32Array, str_len/12, 3 );
var buffer = new Float32Array( str_len / 4 );
geom.morphTargets.push( {
array : buffer
} );
//buffer = geom.attributes['morphTarget'+frames_parsed].array
idx = 0;
while ( this._ptr < str_end ) {
buffer[ idx ] = this.readF32();
buffer[ idx + 1 ] = this.readF32();
buffer[ idx + 2 ] = this.readF32();
idx += 3;
}
subMeshParsed ++;
} else
this._ptr = str_end;
streamsParsed ++;
}
}
frames_parsed ++;
}
this.parseUserAttributes();
return null;
},
getBlock: function ( id ) {
return this._blocks[ id ].data;
},
parseMatrix4: function () {
var mtx = new THREE.Matrix4();
var e = mtx.elements;
e[ 0 ] = this.readF32();
e[ 1 ] = this.readF32();
e[ 2 ] = this.readF32();
e[ 3 ] = 0.0;
//e[3] = 0.0;
e[ 4 ] = this.readF32();
e[ 5 ] = this.readF32();
e[ 6 ] = this.readF32();
//e[7] = this.readF32();
e[ 7 ] = 0.0;
e[ 8 ] = this.readF32();
e[ 9 ] = this.readF32();
e[ 10 ] = this.readF32();
//e[11] = this.readF32();
e[ 11 ] = 0.0;
e[ 12 ] = - this.readF32();
e[ 13 ] = this.readF32();
e[ 14 ] = this.readF32();
//e[15] = this.readF32();
e[ 15 ] = 1.0;
return mtx;
},
parseProperties: function ( expected ) {
var list_len = this.readU32();
var list_end = this._ptr + list_len;
var props = new AWDProperties();
if ( expected ) {
while ( this._ptr < list_end ) {
var key = this.readU16();
var len = this.readU32();
var type;
if ( expected.hasOwnProperty( key ) ) {
type = expected[ key ];
props.set( key, this.parseAttrValue( type, len ) );
} else {
this._ptr += len;
}
}
}
return props;
},
parseUserAttributes: function () {
// skip for now
this._ptr = this.readU32() + this._ptr;
return null;
},
parseAttrValue: function ( type, len ) {
var elem_len;
var read_func;
switch ( type ) {
case AWD_FIELD_INT8:
elem_len = 1;
read_func = this.readI8;
break;
case AWD_FIELD_INT16:
elem_len = 2;
read_func = this.readI16;
break;
case AWD_FIELD_INT32:
elem_len = 4;
read_func = this.readI32;
break;
case AWD_FIELD_BOOL:
case AWD_FIELD_UINT8:
elem_len = 1;
read_func = this.readU8;
break;
case AWD_FIELD_UINT16:
elem_len = 2;
read_func = this.readU16;
break;
case AWD_FIELD_UINT32:
case AWD_FIELD_BADDR:
elem_len = 4;
read_func = this.readU32;
break;
case AWD_FIELD_FLOAT32:
elem_len = 4;
read_func = this.readF32;
break;
case AWD_FIELD_FLOAT64:
elem_len = 8;
read_func = this.readF64;
break;
case AWD_FIELD_VECTOR2x1:
case AWD_FIELD_VECTOR3x1:
case AWD_FIELD_VECTOR4x1:
case AWD_FIELD_MTX3x2:
case AWD_FIELD_MTX3x3:
case AWD_FIELD_MTX4x3:
case AWD_FIELD_MTX4x4:
elem_len = 8;
read_func = this.readF64;
break;
}
if ( elem_len < len ) {
var list;
var num_read;
var num_elems;
list = [];
num_read = 0;
num_elems = len / elem_len;
while ( num_read < num_elems ) {
list.push( read_func.call( this ) );
num_read ++;
}
return list;
} else {
return read_func.call( this );
}
},
readU8: function () {
return this._data.getUint8( this._ptr ++ );
},
readI8: function () {
return this._data.getInt8( this._ptr ++ );
},
readU16: function () {
var a = this._data.getUint16( this._ptr, littleEndian );
this._ptr += 2;
return a;
},
readI16: function () {
var a = this._data.getInt16( this._ptr, littleEndian );
this._ptr += 2;
return a;
},
readU32: function () {
var a = this._data.getUint32( this._ptr, littleEndian );
this._ptr += 4;
return a;
},
readI32: function () {
var a = this._data.getInt32( this._ptr, littleEndian );
this._ptr += 4;
return a;
},
readF32: function () {
var a = this._data.getFloat32( this._ptr, littleEndian );
this._ptr += 4;
return a;
},
readF64: function () {
var a = this._data.getFloat64( this._ptr, littleEndian );
this._ptr += 8;
return a;
},
/**
* Converts a UTF-8 byte array to JavaScript's 16-bit Unicode.
* @param {Array.<number>} bytes UTF-8 byte array.
* @return {string} 16-bit Unicode string.
*/
readUTF: function () {
var len = this.readU16();
return this.readUTFBytes( len );
},
/**
* Converts a UTF-8 byte array to JavaScript's 16-bit Unicode.
* @param {Array.<number>} bytes UTF-8 byte array.
* @return {string} 16-bit Unicode string.
*/
readUTFBytes: function ( len ) {
// TODO(user): Use native implementations if/when available
var out = [], c = 0;
while ( out.length < len ) {
var c1 = this._data.getUint8( this._ptr ++, littleEndian );
if ( c1 < 128 ) {
out[ c ++ ] = String.fromCharCode( c1 );
} else if ( c1 > 191 && c1 < 224 ) {
var c2 = this._data.getUint8( this._ptr ++, littleEndian );
out[ c ++ ] = String.fromCharCode( ( c1 & 31 ) << 6 | c2 & 63 );
} else {
var c2 = this._data.getUint8( this._ptr ++, littleEndian );
var c3 = this._data.getUint8( this._ptr ++, littleEndian );
out[ c ++ ] = String.fromCharCode(
( c1 & 15 ) << 12 | ( c2 & 63 ) << 6 | c3 & 63
);
}
}
return out.join( '' );
}
};
/* eslint-enable */
export default AWDLoader;
| 1 | 0.88313 | 1 | 0.88313 | game-dev | MEDIA | 0.659774 | game-dev,graphics-rendering | 0.964256 | 1 | 0.964256 |
DescentDevelopers/D3Edit | 22,193 | NewEditor/GoalDialog.cpp | /*
THE COMPUTER CODE CONTAINED HEREIN IS THE SOLE PROPERTY OF OUTRAGE
ENTERTAINMENT, INC. ("OUTRAGE"). OUTRAGE, IN DISTRIBUTING THE CODE TO
END-USERS, AND SUBJECT TO ALL OF THE TERMS AND CONDITIONS HEREIN, GRANTS A
ROYALTY-FREE, PERPETUAL LICENSE TO SUCH END-USERS FOR USE BY SUCH END-USERS
IN USING, DISPLAYING, AND CREATING DERIVATIVE WORKS THEREOF, SO LONG AS
SUCH USE, DISPLAY OR CREATION IS FOR NON-COMMERCIAL, ROYALTY OR REVENUE
FREE PURPOSES. IN NO EVENT SHALL THE END-USER USE THE COMPUTER CODE
CONTAINED HEREIN FOR REVENUE-BEARING PURPOSES. THE END-USER UNDERSTANDS
AND AGREES TO THE TERMS HEREIN AND ACCEPTS THE SAME BY USE OF THIS FILE.
COPYRIGHT 1996-2000 OUTRAGE ENTERTAINMENT, INC. ALL RIGHTS RESERVED.
*/
// GoalDialog.cpp : implementation file
//
#include "stdafx.h"
#include "neweditor.h"
#include "GoalDialog.h"
#include "EditLineDialog.h"
#include "levelgoal.h"
#include "ned_Util.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CGoalDialog dialog
CGoalDialog::CGoalDialog(CWnd *pParent) : CDialog(CGoalDialog::IDD, pParent) {
//{{AFX_DATA_INIT(CGoalDialog)
//}}AFX_DATA_INIT
}
void CGoalDialog::DoDataExchange(CDataExchange *pDX) {
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CGoalDialog)
DDX_Control(pDX, IDC_GOAL_ITEM_TRIGGER_COMBO, m_trigger_combo);
DDX_Control(pDX, IDC_GOAL_ITEM_ROOM_COMBO, m_room_combo);
DDX_Control(pDX, IDC_GOAL_ITEM_OBJECT_COMBO, m_object_combo);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CGoalDialog, CDialog)
//{{AFX_MSG_MAP(CGoalDialog)
ON_BN_CLICKED(IDC_ADD_GOAL, OnAddGoal)
ON_BN_CLICKED(IDC_DELETE_GOAL, OnDeleteGoal)
ON_BN_CLICKED(IDC_NEXT_GOAL, OnNextGoal)
ON_BN_CLICKED(IDC_PREV_GOAL, OnPrevGoal)
ON_BN_CLICKED(IDC_GOAL_SELECT, OnGoalSelect)
ON_EN_KILLFOCUS(IDC_GOAL_NAME, OnKillfocusGoalName)
ON_EN_KILLFOCUS(IDC_GOAL_LOCOBJ_NAME, OnKillfocusGoalLocobjName)
ON_EN_KILLFOCUS(IDC_GOAL_DESCRIPTION, OnKillfocusGoalDescription)
ON_EN_KILLFOCUS(IDC_GOAL_PRIORITY, OnKillfocusGoalPriority)
ON_EN_KILLFOCUS(IDC_GOAL_LIST, OnKillfocusGoalList)
ON_BN_CLICKED(IDC_GOAL_COMPLETED, OnGoalCompleted)
ON_BN_CLICKED(IDC_GOAL_ENABLED, OnGoalEnabled)
ON_BN_CLICKED(IDC_GOAL_GB_KNOWS, OnGoalGbKnows)
ON_BN_CLICKED(IDC_GOAL_LOC_BASED, OnGoalLocBased)
ON_BN_CLICKED(IDC_GOAL_OBJECTIVE, OnGoalObjective)
ON_BN_CLICKED(IDC_GOAL_SECONDARY, OnGoalSecondary)
ON_WM_PAINT()
ON_BN_CLICKED(IDC_GOAL_ITEM_ACTIVATE, OnGoalItemActivate)
ON_BN_CLICKED(IDC_GOAL_ITEM_ENTER, OnGoalItemEnter)
ON_BN_CLICKED(IDC_GOAL_ITEM_PICKUP_DESTROY, OnGoalItemPickupDestroy)
ON_BN_CLICKED(IDC_GOAL_ITEM_PLAYER_COLLIDE, OnGoalItemPlayerCollide)
ON_BN_CLICKED(IDC_GOAL_ITEM_PLAYER_WEAPON, OnGoalItemPlayerWeapon)
ON_BN_CLICKED(IDC_GOAL_ITEM_ADD, OnGoalItemAdd)
ON_BN_CLICKED(IDC_GOAL_ITEM_DELETE, OnGoalItemDelete)
ON_BN_CLICKED(IDC_GOAL_ITEM_DALLAS, OnGoalItemDallas)
ON_BN_CLICKED(IDC_GOAL_ITEM_ROOM, OnGoalItemRoom)
ON_BN_CLICKED(IDC_GOAL_ITEM_SELECT, OnGoalItemSelect)
ON_BN_CLICKED(IDC_GOAL_ITEM_TRIGGER, OnGoalItemTrigger)
ON_BN_CLICKED(IDC_GOAL_ITEM_OBJECT, OnGoalItemObject)
ON_BN_CLICKED(IDC_NEXT_GOAL_ITEM, OnNextGoalItem)
ON_BN_CLICKED(IDC_PREV_GOAL_ITEM, OnPrevGoalItem)
ON_CBN_SELENDOK(IDC_GOAL_ITEM_TRIGGER_COMBO, OnSelendokGoalItemTriggerCombo)
ON_CBN_SELENDOK(IDC_GOAL_ITEM_ROOM_COMBO, OnSelendokGoalItemRoomCombo)
ON_CBN_SELENDOK(IDC_GOAL_ITEM_OBJECT_COMBO, OnSelendokGoalItemObjectCombo)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CGoalDialog message handlers
void CGoalDialog::OnAddGoal() {
// TODO: Add your control notification handler code here
m_CurrentGoal = Level_goals.AddGoal(true);
m_CurrentItem = 0;
UpdateDialog();
OnGoalItemAdd();
}
void CGoalDialog::OnDeleteGoal() {
// TODO: Add your control notification handler code here
Level_goals.DeleteGoal(m_CurrentGoal);
m_CurrentGoal = 0;
m_CurrentItem = 0;
UpdateDialog();
}
void CGoalDialog::OnNextGoal() {
// TODO: Add your control notification handler code here
int num_goals = Level_goals.GetNumGoals();
if (m_CurrentGoal < num_goals - 1) {
m_CurrentGoal++;
} else {
m_CurrentGoal = 0;
}
m_CurrentItem = 0;
UpdateDialog();
}
void CGoalDialog::OnPrevGoal() {
// TODO: Add your control notification handler code here
int num_goals = Level_goals.GetNumGoals();
if (m_CurrentGoal > 0) {
m_CurrentGoal--;
} else {
m_CurrentGoal = num_goals - 1;
}
m_CurrentItem = 0;
UpdateDialog();
}
void CGoalDialog::OnGoalSelect() {
// TODO: Add your control notification handler code here
int n;
int num_goals = Level_goals.GetNumGoals();
if (InputNumber(&n, "Select Goal", "Enter goal number to select", this)) {
if (n > num_goals || n <= 0) {
OutrageMessageBox("Invalid goal number.");
return;
}
m_CurrentGoal = n - 1;
m_CurrentItem = 0;
UpdateDialog();
}
}
void CGoalDialog::OnKillfocusGoalName() {
// TODO: Add your control notification handler code here
char str[256];
((CEdit *)GetDlgItem(IDC_GOAL_NAME))->GetWindowText(str, 255);
Level_goals.GoalSetName(m_CurrentGoal, str);
UpdateDialog();
}
void CGoalDialog::OnKillfocusGoalLocobjName() {
// TODO: Add your control notification handler code here
char str[256];
((CEdit *)GetDlgItem(IDC_GOAL_LOCOBJ_NAME))->GetWindowText(str, 255);
Level_goals.GoalSetItemName(m_CurrentGoal, str);
UpdateDialog();
}
void CGoalDialog::OnKillfocusGoalDescription() {
// TODO: Add your control notification handler code here
char str[2560];
((CEdit *)GetDlgItem(IDC_GOAL_DESCRIPTION))->GetWindowText(str, 2559);
Level_goals.GoalSetDesc(m_CurrentGoal, str);
UpdateDialog();
}
void CGoalDialog::OnKillfocusGoalPriority() {
// TODO: Add your control notification handler code here
int priority;
char str[256];
((CEdit *)GetDlgItem(IDC_GOAL_PRIORITY))->GetWindowText(str, 255);
sscanf(str, "%d", &priority);
Level_goals.GoalPriority(m_CurrentGoal, LO_SET_SPECIFIED, &priority);
UpdateDialog();
}
bool CGoalDialog::ValidateCurrentGoal() {
int num_goals = Level_goals.GetNumGoals();
if (num_goals > 0) {
if (m_CurrentGoal < 0 || m_CurrentGoal >= num_goals)
m_CurrentGoal = 0;
return true;
} else {
m_CurrentGoal = -1;
return false;
}
}
bool CGoalDialog::ValidateCurrentItem() {
if (ValidateCurrentGoal()) {
int num_items = Level_goals.GoalGetNumItems(m_CurrentGoal);
if (num_items > 0) {
if (m_CurrentItem < 0 || m_CurrentItem >= num_items)
m_CurrentItem = 0;
return true;
}
}
m_CurrentItem = -1;
return false;
}
void make_goal_dialog_text(char *big_text_message) {
int i;
int j;
big_text_message[0] = '\0';
int num_goals[2 * MAX_GOAL_LISTS];
int goals[2 * MAX_GOAL_LISTS][MAX_LEVEL_GOALS];
int p[2 * MAX_GOAL_LISTS][MAX_LEVEL_GOALS];
for (i = 0; i < 2 * MAX_GOAL_LISTS; i++) {
num_goals[i] = 0;
}
int n = Level_goals.GetNumGoals();
for (i = 0; i < n; i++) {
int priority;
char list;
int flags;
Level_goals.GoalPriority(i, LO_GET_SPECIFIED, &priority);
Level_goals.GoalGoalList(i, LO_GET_SPECIFIED, &list);
Level_goals.GoalStatus(i, LO_GET_SPECIFIED, &flags, true);
if (flags & LGF_SECONDARY_GOAL) {
list += MAX_GOAL_LISTS;
}
int insert = num_goals[list];
for (j = 0; j < num_goals[list]; j++) {
if (priority < p[list][j]) {
insert = j;
break;
}
}
for (j = num_goals[list]; j > insert; j--) {
goals[list][j] = goals[list][j - 1];
p[list][j] = p[list][j - 1];
}
goals[list][insert] = i;
p[list][insert] = priority;
num_goals[list]++;
}
for (i = 0; i < 2 * MAX_GOAL_LISTS; i++) {
strcat(big_text_message, "\r\n---------------------\r\n");
if (i < MAX_GOAL_LISTS) {
char cur[50];
sprintf(cur, "Primary List %d\r\n", i);
strcat(big_text_message, cur);
} else {
char cur[50];
sprintf(cur, "Secondary List %d\r\n", i - MAX_GOAL_LISTS);
strcat(big_text_message, cur);
}
strcat(big_text_message, "---------------------\r\n");
for (j = 0; j < num_goals[i]; j++) {
char name[41];
char p_text[5];
strcat(big_text_message, " ");
Level_goals.GoalGetName(goals[i][j], name, 40);
int flags;
Level_goals.GoalStatus(goals[i][j], LO_GET_SPECIFIED, &flags, true);
if (flags & LGF_TELCOM_LISTS) {
strcat(big_text_message, "(Obj) ");
}
strcat(big_text_message, name);
sprintf(p_text, " (%d)", p[i][j]);
strcat(big_text_message, p_text);
strcat(big_text_message, "\r\n");
}
}
}
void CGoalDialog::EnableControls(bool enable) {
((CButton *)GetDlgItem(IDC_ADD_GOAL))->EnableWindow(enable);
((CButton *)GetDlgItem(IDC_DELETE_GOAL))->EnableWindow(enable);
((CButton *)GetDlgItem(IDC_NEXT_GOAL))->EnableWindow(enable);
((CButton *)GetDlgItem(IDC_PREV_GOAL))->EnableWindow(enable);
((CButton *)GetDlgItem(IDC_GOAL_SELECT))->EnableWindow(enable);
((CButton *)GetDlgItem(IDC_GOAL_NAME))->EnableWindow(enable);
((CButton *)GetDlgItem(IDC_GOAL_LOCOBJ_NAME))->EnableWindow(enable);
((CButton *)GetDlgItem(IDC_GOAL_DESCRIPTION))->EnableWindow(enable);
((CButton *)GetDlgItem(IDC_GOAL_PRIORITY))->EnableWindow(enable);
((CButton *)GetDlgItem(IDC_GOAL_LIST))->EnableWindow(enable);
((CButton *)GetDlgItem(IDC_GOAL_COMPLETED))->EnableWindow(enable);
((CButton *)GetDlgItem(IDC_GOAL_ENABLED))->EnableWindow(enable);
((CButton *)GetDlgItem(IDC_GOAL_GB_KNOWS))->EnableWindow(enable);
((CButton *)GetDlgItem(IDC_GOAL_LOC_BASED))->EnableWindow(enable);
((CButton *)GetDlgItem(IDC_GOAL_OBJECTIVE))->EnableWindow(enable);
((CButton *)GetDlgItem(IDC_GOAL_SECONDARY))->EnableWindow(enable);
((CButton *)GetDlgItem(IDC_GOAL_ITEM_ACTIVATE))->EnableWindow(enable);
((CButton *)GetDlgItem(IDC_GOAL_ITEM_ENTER))->EnableWindow(enable);
((CButton *)GetDlgItem(IDC_GOAL_ITEM_PICKUP_DESTROY))->EnableWindow(enable);
((CButton *)GetDlgItem(IDC_GOAL_ITEM_PLAYER_COLLIDE))->EnableWindow(enable);
((CButton *)GetDlgItem(IDC_GOAL_ITEM_PLAYER_WEAPON))->EnableWindow(enable);
((CButton *)GetDlgItem(IDC_GOAL_ITEM_ADD))->EnableWindow(enable);
((CButton *)GetDlgItem(IDC_GOAL_ITEM_DELETE))->EnableWindow(enable);
((CButton *)GetDlgItem(IDC_GOAL_ITEM_DALLAS))->EnableWindow(enable);
((CButton *)GetDlgItem(IDC_GOAL_ITEM_ROOM))->EnableWindow(enable);
((CButton *)GetDlgItem(IDC_GOAL_ITEM_SELECT))->EnableWindow(enable);
((CButton *)GetDlgItem(IDC_GOAL_ITEM_TRIGGER))->EnableWindow(enable);
((CButton *)GetDlgItem(IDC_GOAL_ITEM_OBJECT))->EnableWindow(enable);
((CButton *)GetDlgItem(IDC_NEXT_GOAL_ITEM))->EnableWindow(enable);
((CButton *)GetDlgItem(IDC_PREV_GOAL_ITEM))->EnableWindow(enable);
((CButton *)GetDlgItem(IDC_GOAL_ITEM_TRIGGER_COMBO))->EnableWindow(enable);
((CButton *)GetDlgItem(IDC_GOAL_ITEM_ROOM_COMBO))->EnableWindow(enable);
((CButton *)GetDlgItem(IDC_GOAL_ITEM_OBJECT_COMBO))->EnableWindow(enable);
}
void CGoalDialog::UpdateDialog() {
int flags;
int lgflags;
int priority;
char g_list;
char name[256];
char iname[256];
char desc[2560];
int num_goals;
int num_items = 0;
char big_text_message[MAX_LEVEL_GOALS * 5 * 40];
char item_type;
int item_handle;
if (theApp.m_pLevelWnd == NULL || Curroomp == NULL) {
// EnableTabControls(this->m_hWnd,false,IDC_ADD_GOAL,-1);
EnableControls(false);
return;
} else {
// EnableTabControls(this->m_hWnd,true,IDC_ADD_GOAL,-1);
EnableControls(true);
}
Level_goals.LGStatus(LO_GET_SPECIFIED, &lgflags);
if (ValidateCurrentGoal()) {
num_goals = Level_goals.GetNumGoals();
num_items = Level_goals.GoalGetNumItems(m_CurrentGoal);
Level_goals.GoalStatus(m_CurrentGoal, LO_GET_SPECIFIED, &flags, true);
Level_goals.GoalPriority(m_CurrentGoal, LO_GET_SPECIFIED, &priority);
Level_goals.GoalGoalList(m_CurrentGoal, LO_GET_SPECIFIED, &g_list);
Level_goals.GoalGetName(m_CurrentGoal, name, sizeof(name));
Level_goals.GoalGetItemName(m_CurrentGoal, iname, sizeof(iname));
Level_goals.GoalGetDesc(m_CurrentGoal, desc, sizeof(desc));
make_goal_dialog_text(big_text_message);
} else {
num_goals = 0;
num_items = 0;
flags = 0;
priority = 0;
g_list = 0;
strcpy(name, "No goals");
strcpy(iname, "No goals");
strcpy(desc, "No goals");
strcpy(big_text_message, "No goals");
}
if (ValidateCurrentItem()) {
Level_goals.GoalItemInfo(m_CurrentGoal, m_CurrentItem, LO_GET_SPECIFIED, &item_type, &item_handle, NULL);
} else {
item_type = LIT_OBJECT;
item_handle = OBJECT_HANDLE_NONE;
}
PrintToDlgItem(this, IDC_GOAL_NUMBER, "%d of %d", m_CurrentGoal + 1, num_goals);
PrintToDlgItem(this, IDC_GOAL_ITEM_NUMBER, "%d of %d", m_CurrentItem + 1, num_items);
PrintToDlgItem(this, IDC_GOAL_SUMMARY, big_text_message);
PrintToDlgItem(this, IDC_GOAL_NAME, "%s", name);
PrintToDlgItem(this, IDC_GOAL_LOCOBJ_NAME, "%s", iname);
PrintToDlgItem(this, IDC_GOAL_DESCRIPTION, "%s", desc);
CheckDlgButton(IDC_GOAL_ITEM_ROOM, item_type == LIT_INTERNAL_ROOM);
CheckDlgButton(IDC_GOAL_ITEM_OBJECT, item_type == LIT_OBJECT);
CheckDlgButton(IDC_GOAL_ITEM_TRIGGER, item_type == LIT_TRIGGER);
CheckDlgButton(IDC_GOAL_SECONDARY, flags & LGF_SECONDARY_GOAL);
CheckDlgButton(IDC_GOAL_ENABLED, flags & LGF_ENABLED);
CheckDlgButton(IDC_GOAL_COMPLETED, flags & LGF_COMPLETED);
CheckDlgButton(IDC_GOAL_OBJECTIVE, flags & LGF_TELCOM_LISTS);
CheckDlgButton(IDC_GOAL_GB_KNOWS, flags & LGF_GB_DOESNT_KNOW_LOC);
CheckDlgButton(IDC_GOAL_LOC_BASED, flags & LGF_NOT_LOC_BASED);
CheckDlgButton(IDC_GOAL_ITEM_ACTIVATE, (flags & LGF_COMP_MASK) == LGF_COMP_ACTIVATE);
CheckDlgButton(IDC_GOAL_ITEM_ENTER, (flags & LGF_COMP_MASK) == LGF_COMP_ENTER);
CheckDlgButton(IDC_GOAL_ITEM_PICKUP_DESTROY, (flags & LGF_COMP_MASK) == LGF_COMP_DESTROY);
CheckDlgButton(IDC_GOAL_ITEM_PLAYER_WEAPON, (flags & LGF_COMP_MASK) == LGF_COMP_PLAYER_WEAPON);
CheckDlgButton(IDC_GOAL_ITEM_PLAYER_COLLIDE, (flags & LGF_COMP_MASK) == LGF_COMP_PLAYER);
CheckDlgButton(IDC_GOAL_ITEM_DALLAS, (flags & LGF_COMP_MASK) == LGF_COMP_DALLAS);
if (item_type == LIT_OBJECT)
m_object_combo.SetSelected(item_handle);
else
m_object_combo.SetSelected(-1);
if (item_type == LIT_INTERNAL_ROOM)
m_room_combo.SetSelected(item_handle);
else
m_room_combo.SetSelected(-1);
if (item_type == LIT_TRIGGER)
m_trigger_combo.SetSelected(item_handle);
else
m_trigger_combo.SetSelected(-1);
PrintToDlgItem(this, IDC_GOAL_PRIORITY, "%d", priority);
PrintToDlgItem(this, IDC_GOAL_LIST, "%d", g_list);
}
BOOL CGoalDialog::OnInitDialog() {
CDialog::OnInitDialog();
// TODO: Add extra initialization here
m_room_combo.Init(-1);
m_trigger_combo.Init(-1);
m_object_combo.Init(OBJ_NONE, OBJECT_HANDLE_NONE);
UpdateDialog();
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
void CGoalDialog::OnKillfocusGoalList() {
// TODO: Add your control notification handler code here
int int_g_list;
char g_list;
char str[256];
((CEdit *)GetDlgItem(IDC_GOAL_LIST))->GetWindowText(str, 255);
sscanf(str, "%d", &int_g_list);
g_list = (char)int_g_list;
Level_goals.GoalGoalList(m_CurrentGoal, LO_SET_SPECIFIED, &g_list);
UpdateDialog();
}
void CGoalDialog::DoGoalFlagToggle(int flag) {
char op = LO_CLEAR_SPECIFIED;
int flags;
bool f_set;
Level_goals.GoalStatus(m_CurrentGoal, LO_GET_SPECIFIED, &flags, true);
f_set = ((flags & flag) == 0);
if (f_set) {
op = LO_SET_SPECIFIED;
}
Level_goals.GoalStatus(m_CurrentGoal, op, &flag, true);
UpdateDialog();
}
void CGoalDialog::OnGoalCompleted() {
// TODO: Add your control notification handler code here
DoGoalFlagToggle(LGF_COMPLETED);
}
void CGoalDialog::OnGoalEnabled() {
// TODO: Add your control notification handler code here
DoGoalFlagToggle(LGF_ENABLED);
}
void CGoalDialog::OnGoalGbKnows() {
// TODO: Add your control notification handler code here
DoGoalFlagToggle(LGF_GB_DOESNT_KNOW_LOC);
}
void CGoalDialog::OnGoalLocBased() {
// TODO: Add your control notification handler code here
DoGoalFlagToggle(LGF_NOT_LOC_BASED);
}
void CGoalDialog::OnGoalObjective() {
// TODO: Add your control notification handler code here
DoGoalFlagToggle(LGF_TELCOM_LISTS);
}
void CGoalDialog::OnGoalSecondary() {
// TODO: Add your control notification handler code here
DoGoalFlagToggle(LGF_SECONDARY_GOAL);
}
void CGoalDialog::PostNcDestroy() {
// TODO: Add your specialized code here and/or call the base class
theApp.m_pGoalDlg = NULL;
delete this;
}
void CGoalDialog::OnCancel() {
// TODO: Add extra cleanup here
DestroyWindow();
}
void CGoalDialog::OnPaint() {
CPaintDC dc(this); // device context for painting
// TODO: Add your message handler code here
UpdateDialog();
// Do not call CDialog::OnPaint() for painting messages
}
void CGoalDialog::OnGoalItemActivate() {
// TODO: Add your control notification handler code here
int flags = LGF_COMP_MASK;
Level_goals.GoalStatus(m_CurrentGoal, LO_CLEAR_SPECIFIED, &flags, true);
flags = LGF_COMP_ACTIVATE;
Level_goals.GoalStatus(m_CurrentGoal, LO_SET_SPECIFIED, &flags, true);
}
void CGoalDialog::OnGoalItemEnter() {
// TODO: Add your control notification handler code here
int flags = LGF_COMP_MASK;
Level_goals.GoalStatus(m_CurrentGoal, LO_CLEAR_SPECIFIED, &flags, true);
flags = LGF_COMP_ENTER;
Level_goals.GoalStatus(m_CurrentGoal, LO_SET_SPECIFIED, &flags, true);
}
void CGoalDialog::OnGoalItemPickupDestroy() {
// TODO: Add your control notification handler code here
int flags = LGF_COMP_MASK;
Level_goals.GoalStatus(m_CurrentGoal, LO_CLEAR_SPECIFIED, &flags, true);
flags = LGF_COMP_DESTROY;
Level_goals.GoalStatus(m_CurrentGoal, LO_SET_SPECIFIED, &flags, true);
}
void CGoalDialog::OnGoalItemPlayerCollide() {
// TODO: Add your control notification handler code here
int flags = LGF_COMP_MASK;
Level_goals.GoalStatus(m_CurrentGoal, LO_CLEAR_SPECIFIED, &flags, true);
flags = LGF_COMP_PLAYER;
Level_goals.GoalStatus(m_CurrentGoal, LO_SET_SPECIFIED, &flags, true);
}
void CGoalDialog::OnGoalItemPlayerWeapon() {
// TODO: Add your control notification handler code here
int flags = LGF_COMP_MASK;
Level_goals.GoalStatus(m_CurrentGoal, LO_CLEAR_SPECIFIED, &flags, true);
flags = LGF_COMP_PLAYER_WEAPON;
Level_goals.GoalStatus(m_CurrentGoal, LO_SET_SPECIFIED, &flags, true);
}
void CGoalDialog::OnGoalItemAdd() {
// TODO: Add your control notification handler code here
int item;
item = Level_goals.GoalAddItem(m_CurrentGoal);
if (item != -1) {
m_CurrentItem = item;
} else {
OutrageMessageBox(MBOX_OK, "Sorry: No more items are allowed for this goal.");
}
UpdateDialog();
}
void CGoalDialog::OnGoalItemDelete() {
// TODO: Add your control notification handler code here
if (Level_goals.GoalGetNumItems(m_CurrentGoal)) {
Level_goals.GoalDeleteItem(m_CurrentGoal, m_CurrentItem);
m_CurrentItem = 0;
}
UpdateDialog();
}
void CGoalDialog::OnGoalItemDallas() {
// TODO: Add your control notification handler code here
int flags = LGF_COMP_MASK;
Level_goals.GoalStatus(m_CurrentGoal, LO_CLEAR_SPECIFIED, &flags, true);
flags = LGF_COMP_DALLAS;
Level_goals.GoalStatus(m_CurrentGoal, LO_SET_SPECIFIED, &flags, true);
}
void CGoalDialog::OnGoalItemRoom() {
// TODO: Add your control notification handler code here
char type = LIT_INTERNAL_ROOM;
int handle = -1;
Level_goals.GoalItemInfo(m_CurrentGoal, m_CurrentItem, LO_SET_SPECIFIED, &type, &handle, NULL);
UpdateDialog();
}
void CGoalDialog::OnGoalItemSelect() {
// TODO: Add your control notification handler code here
int n;
int num_items = Level_goals.GoalGetNumItems(m_CurrentGoal);
if (InputNumber(&n, "Select Goal Item", "Enter goal item number to select", this)) {
if (n > num_items || n <= 0) {
OutrageMessageBox("Invalid goal item number.");
return;
}
m_CurrentItem = n - 1;
UpdateDialog();
}
}
void CGoalDialog::OnGoalItemTrigger() {
// TODO: Add your control notification handler code here
char type = LIT_TRIGGER;
int handle = -1;
Level_goals.GoalItemInfo(m_CurrentGoal, m_CurrentItem, LO_SET_SPECIFIED, &type, &handle, NULL);
UpdateDialog();
}
void CGoalDialog::OnGoalItemObject() {
// TODO: Add your control notification handler code here
char type = LIT_OBJECT;
int handle = -1;
Level_goals.GoalItemInfo(m_CurrentGoal, m_CurrentItem, LO_SET_SPECIFIED, &type, &handle, NULL);
UpdateDialog();
}
void CGoalDialog::OnNextGoalItem() {
// TODO: Add your control notification handler code here
if (m_CurrentItem < Level_goals.GoalGetNumItems(m_CurrentGoal) - 1)
m_CurrentItem++;
else
m_CurrentItem = 0;
UpdateDialog();
}
void CGoalDialog::OnPrevGoalItem() {
// TODO: Add your control notification handler code here
if (m_CurrentItem > 0)
m_CurrentItem--;
else
m_CurrentItem = Level_goals.GoalGetNumItems(m_CurrentGoal) - 1;
UpdateDialog();
}
void CGoalDialog::OnSelendokGoalItemTriggerCombo() {
// TODO: Add your control notification handler code here
int handle = m_trigger_combo.GetSelected();
Level_goals.GoalItemInfo(m_CurrentGoal, m_CurrentItem, LO_SET_SPECIFIED, NULL, &handle, NULL);
UpdateDialog();
}
void CGoalDialog::OnSelendokGoalItemRoomCombo() {
// TODO: Add your control notification handler code here
int handle = m_room_combo.GetSelected();
Level_goals.GoalItemInfo(m_CurrentGoal, m_CurrentItem, LO_SET_SPECIFIED, NULL, &handle, NULL);
UpdateDialog();
}
void CGoalDialog::OnSelendokGoalItemObjectCombo() {
// TODO: Add your control notification handler code here
int handle = m_object_combo.GetSelected();
Level_goals.GoalItemInfo(m_CurrentGoal, m_CurrentItem, LO_SET_SPECIFIED, NULL, &handle, NULL);
UpdateDialog();
}
void CGoalDialog::OnOK() {
// TODO: Add extra validation here
// Do nothing!
}
| 1 | 0.847964 | 1 | 0.847964 | game-dev | MEDIA | 0.738256 | game-dev | 0.712458 | 1 | 0.712458 |
chsami/Microbot | 10,352 | runelite-client/src/main/java/net/runelite/client/plugins/microbot/questhelper/questinfo/QuestVarbits.java | package net.runelite.client.plugins.microbot.questhelper.questinfo;
import lombok.AllArgsConstructor;
import lombok.Getter;
import net.runelite.api.gameval.VarbitID;
@AllArgsConstructor
@Getter
public enum QuestVarbits
{
QUEST_TAB(VarbitID.SIDE_JOURNAL_TAB),
/**
* f2p Quest varbits, these don't hold the completion value.
*/
QUEST_BELOW_ICE_MOUNTAIN(VarbitID.BIM),
QUEST_DEMON_SLAYER(VarbitID.DEMONSLAYER_MAIN),
QUEST_GOBLIN_DIPLOMACY(VarbitID.GOBDIP_MAIN),
QUEST_MISTHALIN_MYSTERY(VarbitID.MISTMYST_PROGRESS),
QUEST_THE_CORSAIR_CURSE(VarbitID.CORSCURS_PROGRESS),
QUEST_X_MARKS_THE_SPOT(VarbitID.CLUEQUEST),
/**
* member Quest varbits, these don't hold the completion value.
*/
QUEST_ANIMAL_MAGNETISM(VarbitID.ANMA_MAIN),
QUEST_BENEATH_CURSED_SANDS(VarbitID.BCS),
QUEST_BETWEEN_A_ROCK(VarbitID.DWARFROCK_QUEST),
QUEST_CONTACT(VarbitID.CONTACT),
QUEST_ZOGRE_FLESH_EATERS(VarbitID.ZOGRE),
QUEST_DARKNESS_OF_HALLOWVALE(VarbitID.MYQ3_MAIN_QUEST),
QUEST_DEATH_TO_THE_DORGESHUUN(VarbitID.DTTD_MAIN),
QUEST_DESERT_TREASURE(VarbitID.DESERTTREASURE),
QUEST_DESERT_TREASURE_II(VarbitID.DT2),
QUEST_DEVIOUS_MINDS(VarbitID.DEVIOUS_MAIN),
QUEST_EAGLES_PEAK(VarbitID.EAGLEPEAK_QUEST),
QUEST_ELEMENTAL_WORKSHOP_II(VarbitID.ELEMENTAL_QUEST_2_MAIN),
QUEST_ENAKHRAS_LAMENT(VarbitID.ENAKH_QUEST),
QUEST_ENLIGHTENED_JOURNEY(VarbitID.ZEP_QUEST),
QUEST_THE_EYES_OF_GLOUPHRIE(VarbitID.EYEGLO_QUEST),
QUEST_THE_PATH_OF_GLOUPHRIE(VarbitID.POG),
QUEST_FAIRYTALE_I_GROWING_PAINS(VarbitID.FAIRY_FARMERS_QUEST),
QUEST_FAIRYTALE_II_CURE_A_QUEEN(VarbitID.FAIRY2_QUEENCURE_QUEST),
QUEST_THE_FEUD(VarbitID.FEUD_VAR),
QUEST_FORGETTABLE_TALE(VarbitID.FORGET_QUEST),
QUEST_GARDEN_OF_TRANQUILLITY(VarbitID.GARDEN_QUEST),
QUEST_GHOSTS_AHOY(VarbitID.AHOY_QUESTVAR),
QUEST_THE_GIANT_DWARF(VarbitID.GIANTDWARF_QUEST),
QUEST_THE_GOLEM(VarbitID.GOLEM_A),
QUEST_THE_HAND_IN_THE_SAND(VarbitID.HANDSAND_QUEST),
QUEST_HORROR_FROM_THE_DEEP(VarbitID.HORRORQUEST),
QUEST_ICTHLARINS_LITTLE_HELPER(VarbitID.ICS_LITTLE_VAR),
QUEST_IN_AID_OF_THE_MYREQUE(VarbitID.MYREQUE_2_QUEST),
QUEST_LAND_OF_THE_GOBLINS(VarbitID.LOTG),
QUEST_THE_LOST_TRIBE(VarbitID.LOST_TRIBE_QUEST),
QUEST_LUNAR_DIPLOMACY(VarbitID.LUNAR_QUEST_MAIN),
QUEST_MAKING_HISTORY(VarbitID.MAKINGHISTORY_PROG),
QUEST_MOUNTAIN_DAUGHTER(VarbitID.MDAUGHTER_QUEST_VAR),
QUEST_MOURNINGS_END_PART_II(VarbitID.MOURNING_QUEST_MAIN),
QUEST_MY_ARMS_BIG_ADVENTURE(VarbitID.MYARM),
QUEST_RATCATCHERS(VarbitID.RATCATCH_VAR),
QUEST_RECIPE_FOR_DISASTER(VarbitID.HUNDRED_MAIN_QUEST_VAR),
QUEST_RECIPE_FOR_DISASTER_DWARF(VarbitID.HUNDRED_DWARF_QUEST),
QUEST_RECIPE_FOR_DISASTER_WARTFACE_AND_BENTNOZE(VarbitID._100GOBLIN),
QUEST_RECIPE_FOR_DISASTER_PIRATE_PETE(VarbitID._100_PIRATE_QUEST_VAR),
QUEST_RECIPE_FOR_DISASTER_LUMBRIDGE_GUIDE(VarbitID._100GUIDE_PROG),
QUEST_RECIPE_FOR_DISASTER_EVIL_DAVE(VarbitID.HUNDRED_DAVE_MAIN),
QUEST_RECIPE_FOR_DISASTER_SIR_AMIK_VARZE(VarbitID.CHICKENQUEST),
QUEST_RECIPE_FOR_DISASTER_SKRACH_UGLOGWEE(VarbitID._100_OGRE_PROG),
QUEST_RECIPE_FOR_DISASTER_MONKEY_AMBASSADOR(VarbitID.HUNDRED_ILM_QUEST),
QUEST_RECRUITMENT_DRIVE(VarbitID.RD_MAIN),
QUEST_ROYAL_TROUBLE(VarbitID.ROYAL_QUEST),
QUEST_THE_SLUG_MENACE(VarbitID.SLUG2_MAIN),
QUEST_SHADOW_OF_THE_STORM(VarbitID.AGRITH_QUEST),
QUEST_A_SOULS_BANE(VarbitID.SOULBANE_PROG),
QUEST_SPIRITS_OF_THE_ELID(VarbitID.ELIDQUEST),
QUEST_SWAN_SONG(VarbitID.SWANSONG),
QUEST_A_TAIL_OF_TWO_CATS(VarbitID.TWOCATS_QUEST),
QUEST_TEARS_OF_GUTHIX(VarbitID.TOG_JUNA_BOWL),
QUEST_WANTED(VarbitID.WANTED_MAIN),
QUEST_COLD_WAR(VarbitID.PENG_QUEST),
QUEST_THE_FREMENNIK_ISLES(VarbitID.FRIS_QUEST),
QUEST_TOWER_OF_LIFE(VarbitID.TOL_PROG),
QUEST_WHAT_LIES_BELOW(VarbitID.SUROK_QUEST),
QUEST_OLAFS_QUEST(VarbitID.OLAF_QUEST_VAR),
QUEST_ANOTHER_SLICE_OF_HAM(VarbitID.SLICE_QUEST),
QUEST_DREAM_MENTOR(VarbitID.DREAM_PROG),
QUEST_GRIM_TALES(VarbitID.GRIM_QUEST),
QUEST_KINGS_RANSOM(VarbitID.KR_QUEST),
QUEST_MONKEY_MADNESS_II(VarbitID.MM2_PROGRESS),
QUEST_CLIENT_OF_KOUREND(VarbitID.VEOS_PROGRESS),
QUEST_BONE_VOYAGE(VarbitID.FOSSILQUEST_PROGRESS),
QUEST_THE_QUEEN_OF_THIEVES(VarbitID.PISCQUEST),
QUEST_THE_DEPTHS_OF_DESPAIR(VarbitID.HOSIDIUSQUEST),
QUEST_DRAGON_SLAYER_II(VarbitID.DS2),
QUEST_TALE_OF_THE_RIGHTEOUS(VarbitID.SHAYZIENQUEST),
QUEST_A_TASTE_OF_HOPE(VarbitID.MYQ4),
QUEST_MAKING_FRIENDS_WITH_MY_ARM(VarbitID.MY2ARM_STATUS),
QUEST_THE_ASCENT_OF_ARCEUUS(VarbitID.ARCQUEST),
QUEST_THE_FORSAKEN_TOWER(VarbitID.LOVAQUEST),
QUEST_SONG_OF_THE_ELVES(VarbitID.SOTE),
QUEST_THE_FREMENNIK_EXILES(VarbitID.VIKINGEXILE),
QUEST_SINS_OF_THE_FATHER(VarbitID.MYQ5),
QUEST_A_PORCINE_OF_INTEREST(VarbitID.PORCINE),
QUEST_GETTING_AHEAD(VarbitID.GA),
QUEST_A_KINGDOM_DIVIDED(VarbitID.AKD),
QUEST_A_NIGHT_AT_THE_THEATRE(VarbitID.TOBQUEST),
QUEST_TEMPLE_OF_THE_EYE(VarbitID.TOTE),
QUEST_SLEEPING_GIANTS(VarbitID.SLEEPING_GIANTS),
QUEST_THE_GARDEN_OF_DEATH(VarbitID.TGOD),
QUEST_SECRETS_OF_THE_NORTH(VarbitID.SOTN),
QUEST_CHILDREN_OF_THE_SUN(VarbitID.VMQ1),
QUEST_DEFENDER_OF_VARROCK(VarbitID.DOV),
QUEST_AT_FIRST_LIGHT(VarbitID.AFL),
QUEST_PERILOUS_MOONS(VarbitID.PMOON_QUEST),
QUEST_THE_RIBBITING_TALE_OF_A_LILY_PAD_LABOUR_DISPUTE(VarbitID.FROG_QUEST),
QUEST_TWILIGHTS_PROMISE(VarbitID.VMQ2),
QUEST_WHILE_GUTHIX_SLEEPS(VarbitID.WGS),
QUEST_ETHICALLY_ACQUIRED_ANTIQUITIES(VarbitID.EAA),
QUEST_DEATH_ON_THE_ISLE(VarbitID.DOTI),
QUEST_MEAT_AND_GREET(VarbitID.MAG),
QUEST_THE_HEART_OF_DARKNESS(VarbitID.VMQ3),
QUEST_THE_CURSE_OF_ARRAV(VarbitID.COA),
QUEST_THE_FINAL_DAWN(VarbitID.VMQ4),
QUEST_SHADOWS_OF_CUSTODIA(VarbitID.SOC),
QUEST_SCRAMBLED(VarbitID.SCRAMBLED),
/**
* mini-quest varbits, these don't hold the completion value.
*/
QUEST_ARCHITECTURAL_ALLIANCE(VarbitID.ZEAH_STATUE),
QUEST_BEAR_YOUR_SOUL(VarbitID.ARCEUUS_SOULBEARER_STORY),
QUEST_CURSE_OF_THE_EMPTY_LORD(VarbitID.SECRET_GHOST6_BACKSTORY),
QUEST_ENCHANTED_KEY(VarbitID.MAKINGHISTORY_LOCSTATUS),
QUEST_THE_GENERALS_SHADOW(VarbitID.SHADOW_MAJ_MAIN),
QUEST_SKIPPY_AND_THE_MOGRES(VarbitID.SKIPPY_STATE),
QUEST_LAIR_OF_TARN_RAZORLOR(VarbitID.LOTR_INSTANCE_ENTERED),
QUEST_FAMILY_PEST(VarbitID.FAMILY_QUEST_PROGRESS),
QUEST_THE_MAGE_ARENA_II(VarbitID.MA2_PROGRESS),
QUEST_IN_SEARCH_OF_KNOWLEDGE(VarbitID.HOSDUN_KNOWLEDGE_SEARCH),
QUEST_DADDYS_HOME(VarbitID.DADDYSHOME_STATUS),
QUEST_HOPESPEARS_WILL(VarbitID.HOPESPEAR),
QUEST_VALE_TOTEMS(VarbitID.ENT_TOTEMS_INTRO),
HIS_FAITHFUL_SERVANTS(VarbitID.HFS),
BARBARIAN_TRAINING(VarbitID.BRUT_MINIQUEST),
// Fake miniquests
KNIGHT_WAVES_TRAINING_GROUNDS(VarbitID.KR_KNIGHTWAVES_STATE),
BALLOON_TRANSPORT_CRAFTING_GUILD(VarbitID.ZEP_MULTI_CRAFT),
BALLOON_TRANSPORT_VARROCK(VarbitID.ZEP_MULTI_VARR),
BALLOON_TRANSPORT_CASTLE_WARS(VarbitID.ZEP_MULTI_CAST),
BALLOON_TRANSPORT_GRAND_TREE(VarbitID.ZEP_MULTI_GNO),
STRONGHOLD_OF_SECURITY(VarbitID.SOS_EMOTE_STAMP),
// Achievement Diaries
// Ardougne
ACHIEVEMENT_DIARY_ARDOUGNE_EASY(VarbitID.ARDOUGNE_EASY_REWARD),
ACHIEVEMENT_DIARY_ARDOUGNE_MEDIUM(VarbitID.ARDOUGNE_MEDIUM_REWARD),
ACHIEVEMENT_DIARY_ARDOUGNE_HARD(VarbitID.ARDOUGNE_HARD_REWARD),
ACHIEVEMENT_DIARY_ARDOUGNE_ELITE(VarbitID.ARDOUGNE_ELITE_REWARD),
// Desert
ACHIEVEMENT_DIARY_DESERT_EASY(VarbitID.DESERT_EASY_REWARD),
ACHIEVEMENT_DIARY_DESERT_MEDIUM(VarbitID.DESERT_MEDIUM_REWARD),
ACHIEVEMENT_DIARY_DESERT_HARD(VarbitID.DESERT_HARD_REWARD),
ACHIEVEMENT_DIARY_DESERT_ELITE(VarbitID.DESERT_ELITE_REWARD),
// Falador
ACHIEVEMENT_DIARY_FALADOR_EASY(VarbitID.FALADOR_EASY_REWARD),
ACHIEVEMENT_DIARY_FALADOR_MEDIUM(VarbitID.FALADOR_MEDIUM_REWARD),
ACHIEVEMENT_DIARY_FALADOR_HARD(VarbitID.FALADOR_HARD_REWARD),
ACHIEVEMENT_DIARY_FALADOR_ELITE(VarbitID.FALADOR_ELITE_REWARD),
// Fremennik
ACHIEVEMENT_DIARY_FREMENNIK_EASY(VarbitID.FREMENNIK_EASY_REWARD),
ACHIEVEMENT_DIARY_FREMENNIK_MEDIUM(VarbitID.FREMENNIK_MEDIUM_REWARD),
ACHIEVEMENT_DIARY_FREMENNIK_HARD(VarbitID.FREMENNIK_HARD_REWARD),
ACHIEVEMENT_DIARY_FREMENNIK_ELITE(VarbitID.FREMENNIK_ELITE_REWARD),
// Kandarin
ACHIEVEMENT_DIARY_KANDARIN_EASY(VarbitID.KANDARIN_EASY_REWARD),
ACHIEVEMENT_DIARY_KANDARIN_MEDIUM(VarbitID.KANDARIN_MEDIUM_REWARD),
ACHIEVEMENT_DIARY_KANDARIN_HARD(VarbitID.KANDARIN_HARD_REWARD),
ACHIEVEMENT_DIARY_KANDARIN_ELITE(VarbitID.KANDARIN_ELITE_REWARD),
// Karamja
ACHIEVEMENT_DIARY_KARAMJA_EASY(VarbitID.ATJUN_EASY_REWARD),
ACHIEVEMENT_DIARY_KARAMJA_MEDIUM(VarbitID.ATJUN_MED_REWARD),
ACHIEVEMENT_DIARY_KARAMJA_HARD(VarbitID.ATJUN_HARD_REWARD),
ACHIEVEMENT_DIARY_KARAMJA_ELITE(VarbitID.KARAMJA_ELITE_REWARD),
// Kourend & Kebos
ACHIEVEMENT_DIARY_KOUREND_EASY(VarbitID.KOUREND_EASY_REWARD),
ACHIEVEMENT_DIARY_KOUREND_MEDIUM(VarbitID.KOUREND_MEDIUM_REWARD),
ACHIEVEMENT_DIARY_KOUREND_HARD(VarbitID.KOUREND_HARD_REWARD),
ACHIEVEMENT_DIARY_KOUREND_ELITE(VarbitID.KOUREND_ELITE_REWARD),
// Lumbridge & Draynor
ACHIEVEMENT_DIARY_LUMBRIDGE_EASY(VarbitID.LUMBRIDGE_EASY_REWARD),
ACHIEVEMENT_DIARY_LUMBRIDGE_MEDIUM(VarbitID.LUMBRIDGE_MEDIUM_REWARD),
ACHIEVEMENT_DIARY_LUMBRIDGE_HARD(VarbitID.LUMBRIDGE_HARD_REWARD),
ACHIEVEMENT_DIARY_LUMBRIDGE_ELITE(VarbitID.LUMBRIDGE_ELITE_REWARD),
// Morytania
ACHIEVEMENT_DIARY_MORYTANIA_EASY(VarbitID.MORYTANIA_EASY_REWARD),
ACHIEVEMENT_DIARY_MORYTANIA_MEDIUM(VarbitID.MORYTANIA_MEDIUM_REWARD),
ACHIEVEMENT_DIARY_MORYTANIA_HARD(VarbitID.MORYTANIA_HARD_REWARD),
ACHIEVEMENT_DIARY_MORYTANIA_ELITE(VarbitID.MORYTANIA_ELITE_REWARD),
// Varrock
ACHIEVEMENT_DIARY_VARROCK_EASY(VarbitID.VARROCK_EASY_REWARD),
ACHIEVEMENT_DIARY_VARROCK_MEDIUM(VarbitID.VARROCK_MEDIUM_REWARD),
ACHIEVEMENT_DIARY_VARROCK_HARD(VarbitID.VARROCK_HARD_REWARD),
ACHIEVEMENT_DIARY_VARROCK_ELITE(VarbitID.VARROCK_ELITE_REWARD),
// Western Provinces
ACHIEVEMENT_DIARY_WESTERN_EASY(VarbitID.WESTERN_EASY_REWARD),
ACHIEVEMENT_DIARY_WESTERN_MEDIUM(VarbitID.WESTERN_MEDIUM_REWARD),
ACHIEVEMENT_DIARY_WESTERN_HARD(VarbitID.WESTERN_HARD_REWARD),
ACHIEVEMENT_DIARY_WESTERN_ELITE(VarbitID.WESTERN_ELITE_REWARD),
// Wilderness
ACHIEVEMENT_DIARY_WILDERNESS_EASY(VarbitID.WILDERNESS_EASY_REWARD),
ACHIEVEMENT_DIARY_WILDERNESS_MEDIUM(VarbitID.WILDERNESS_MEDIUM_REWARD),
ACHIEVEMENT_DIARY_WILDERNESS_HARD(VarbitID.WILDERNESS_HARD_REWARD),
ACHIEVEMENT_DIARY_WILDERNESS_ELITE(VarbitID.WILDERNESS_ELITE_REWARD),
CUTSCENE(VarbitID.CUTSCENE_STATUS),
DIALOG_CHOICE(VarbitID.SETTINGS_BARBARIAN_POTION_MAKEX);
private final int id;
}
| 1 | 0.837675 | 1 | 0.837675 | game-dev | MEDIA | 0.925507 | game-dev | 0.643249 | 1 | 0.643249 |
utilForever/BOJ | 3,399 | 23000/23293 - Ajou Survival.rs | use io::Write;
use std::{io, str};
pub struct UnsafeScanner<R> {
reader: R,
buf_str: Vec<u8>,
buf_iter: str::SplitAsciiWhitespace<'static>,
}
impl<R: io::BufRead> UnsafeScanner<R> {
pub fn new(reader: R) -> Self {
Self {
reader,
buf_str: vec![],
buf_iter: "".split_ascii_whitespace(),
}
}
pub fn token<T: str::FromStr>(&mut self) -> T {
loop {
if let Some(token) = self.buf_iter.next() {
return token.parse().ok().expect("Failed parse");
}
self.buf_str.clear();
self.reader
.read_until(b'\n', &mut self.buf_str)
.expect("Failed read");
self.buf_iter = unsafe {
let slice = str::from_utf8_unchecked(&self.buf_str);
std::mem::transmute(slice.split_ascii_whitespace())
}
}
}
}
#[derive(Clone)]
struct Player {
area: usize,
items: Vec<i64>,
}
impl Default for Player {
fn default() -> Self {
Self {
area: 1,
items: vec![0; 54],
}
}
}
fn main() {
let (stdin, stdout) = (io::stdin(), io::stdout());
let mut scan = UnsafeScanner::new(stdin.lock());
let mut out = io::BufWriter::new(stdout.lock());
let (t, n) = (scan.token::<i64>(), scan.token::<usize>());
let mut players = vec![Player::default(); n + 1];
let mut logs_invalid = Vec::new();
let mut players_block = Vec::new();
for _ in 0..t {
let (num, player, code, factor) = (
scan.token::<i64>(),
scan.token::<usize>(),
scan.token::<char>(),
scan.token::<usize>(),
);
match code {
'M' => {
players[player].area = factor;
}
'F' => {
if players[player].area != factor {
logs_invalid.push(num);
}
players[player].items[factor] += 1;
}
'C' => {
let factor2 = scan.token::<usize>();
if players[player].items[factor] == 0 || players[player].items[factor2] == 0 {
logs_invalid.push(num);
}
players[player].items[factor] -= 1;
players[player].items[factor2] -= 1;
if players[player].items[factor] < 0 {
players[player].items[factor] = 0;
}
if players[player].items[factor2] < 0 {
players[player].items[factor2] = 0;
}
}
'A' => {
if players[player].area != players[factor].area {
logs_invalid.push(num);
players_block.push(player);
}
}
_ => unreachable!(),
}
}
players_block.sort();
players_block.dedup();
writeln!(out, "{}", logs_invalid.len()).unwrap();
if !logs_invalid.is_empty() {
for log in logs_invalid {
write!(out, "{log} ").unwrap();
}
writeln!(out).unwrap();
}
writeln!(out, "{}", players_block.len()).unwrap();
if !players_block.is_empty() {
for player in players_block {
write!(out, "{player} ").unwrap();
}
writeln!(out).unwrap();
}
}
| 1 | 0.89156 | 1 | 0.89156 | game-dev | MEDIA | 0.324308 | game-dev | 0.926969 | 1 | 0.926969 |
Penlect/rectangle-packer | 19,356 | src/rpackcore.c | /* Core functions and data structures
This file was formmatted with:
$ indent -kr --no-tabs rpackcore.c
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <limits.h>
#include "rpackcore.h"
/* Cell
====
*/
Cell _cell;
Cell *const COL_FULL = &_cell;
/* start_pos computes the starting position of a Cell by returning the
end position of the previous cell. */
long start_pos(Cell * self)
{
if (self == NULL) {
return 0;
} else if (self->prev == NULL) {
return 0;
} else {
return self->prev->end_pos;
}
}
/* CellLink
========
The CellLink is used to handle the Grid's rows and columns. The
CellLink is a doubly linked list and each cell corresponds to a row
or column in the grid. Each cell has an end position which all
together define the row and column widths. Each cell has a
`jump_index`. These indecies are used when checking if a region,
defined by a row-cell and column-cell, is occupied or not.
*/
/* clear_cell_link restores the CellLink to the "starting state".
I.e. the CellLink will only have one cell which has the full
size. */
static void clear_cell_link(CellLink * self)
{
self->jump_index = 0;
self->head = &self->cells[0];
self->head->prev = NULL;
self->head->next = NULL;
self->head->end_pos = self->end_pos;
self->head->jump_index = self->jump_index;
self->jump_index++;
return;
}
/* free_cell_link frees the memory allocated by CellLink */
static void free_cell_link(CellLink * cell_link)
{
if (cell_link == NULL) {
return;
}
if (cell_link->cells != NULL) {
free(cell_link->cells);
}
free(cell_link);
return;
}
/* alloc_cell_link allocates memory for a new CellLink. `size` refers
to the maximum number of Cells the CellLink will contain. They are
all allocated at this step, but only added to the linked-list when
`cut` is called. */
static CellLink *alloc_cell_link(size_t size, long end_pos)
{
CellLink *cl = NULL;
Cell *cells = NULL;
if ((cl = malloc(sizeof(*cl))) == NULL) {
return NULL;
}
if ((cells = calloc(size, sizeof(*cells))) == NULL) {
free(cl);
return NULL;
}
if (size == 0) {
size = 1;
}
if (end_pos == 0) {
end_pos = 1;
}
cl->size = size;
cl->end_pos = end_pos;
cl->cells = cells;
clear_cell_link(cl);
return cl;
}
/* cut will 'split' an existing Cell and add another cell from the
preallocated list of Cells after it. The end positions will be
adjusted accordingly. */
static void
cut(CellLink * self, Cell * victim, long end_pos, size_t *src_i,
size_t *dest_i)
{
Cell *new_cell = NULL;
new_cell = &self->cells[self->jump_index];
new_cell->end_pos = victim->end_pos;
new_cell->jump_index = *dest_i = self->jump_index;
self->jump_index++; /* May overflow size if called to many times */
new_cell->prev = victim;
new_cell->next = victim->next;
victim->next = new_cell;
victim->end_pos = end_pos;
if (new_cell->next != NULL) {
new_cell->next->prev = new_cell;
}
*src_i = victim->jump_index;
return;
}
// =================================
/* JumpMatrix
==========
The JumpMatrix works like a look-up table to check if a region
defined by a row-cell and column-cell is free or not. If an element
is NULL that region is free, else occupied.
*/
/* alloc_jump_matrix allocates memory for a new JumpMatrix */
static JumpMatrix alloc_jump_matrix(size_t size)
{
size_t i, len = 0;
Cell **ptr, ***arr;
if (size == 0) {
size = 1;
}
len = sizeof(Cell **) * size + sizeof(Cell *) * size * size;
if ((arr = (Cell ***) malloc(len)) == NULL) {
return NULL;
}
/* Ptr is now pointing to the first element in of 2D array */
ptr = (Cell **) (arr + size);
/* For loop to point rows pointer to appropriate location in 2D array */
for (i = 0; i < size; i++) {
arr[i] = (ptr + size * i);
}
arr[0][0] = NULL;
return arr;
}
/* copy_row copies a range of elements decided by `jump_index_col`
from src-row to dest-row. */
static void
copy_row(JumpMatrix self, size_t src_i, size_t dest_i,
size_t jump_index_col)
{
size_t index = 0;
for (index = 0; index < jump_index_col; index++) {
self[dest_i][index] = self[src_i][index];
}
}
/* copy_col copies a range of elements decided by `jump_index_row`
from src-col to dest-col. */
static void
copy_col(JumpMatrix self, size_t src_i, size_t dest_i,
size_t jump_index_row)
{
size_t index = 0;
for (index = 0; index < jump_index_row; index++) {
self[index][dest_i] = self[index][src_i];
}
}
/* Grid
====
The Grid contains two CellLinks - one for rows and one for
columns. It also contains a JumpMatrix to keep track of which
regions are free or not.
*/
/* grid_alloc allocates memory for a new Grid */
Grid *grid_alloc(size_t size, long width, long height)
{
Grid *grid = NULL;
if ((grid = malloc(sizeof(*grid))) == NULL) {
return NULL;
}
if (size == 0) {
size = 1;
}
grid->size = size;
grid->width = width;
grid->height = height;
grid->cols = NULL;
grid->rows = NULL;
grid->jump_matrix = NULL;
if ((grid->cols = alloc_cell_link(size, width)) == NULL) {
grid_free(grid);
return NULL;
}
if ((grid->rows = alloc_cell_link(size, height)) == NULL) {
grid_free(grid);
return NULL;
}
if ((grid->jump_matrix = alloc_jump_matrix(size)) == NULL) {
grid_free(grid);
return NULL;
}
return grid;
}
/* grid_free frees the memory allocated by Grid */
void grid_free(Grid * grid)
{
if (grid == NULL) {
return;
}
if (grid->cols != NULL) {
free_cell_link(grid->cols);
}
if (grid->rows != NULL) {
free_cell_link(grid->rows);
}
if (grid->jump_matrix != NULL) {
free(grid->jump_matrix);
}
free(grid);
}
/* grid_clear clears the CellLinks and JumpMatrix to "start state" */
void grid_clear(Grid * self)
{
if (self == NULL) {
return;
}
self->cols->end_pos = self->width;
clear_cell_link(self->cols);
self->rows->end_pos = self->height;
clear_cell_link(self->rows);
self->jump_matrix[0][0] = NULL;
}
/* grid_split will split the grid by cutting a column and a row in two
in such a way that the region `reg` will fit the grid */
void grid_split(Grid * self, Region * reg)
{
size_t src_i, dest_i;
Cell *r_cell = NULL;
Cell *c_cell = NULL;
Cell *jump_target = NULL;
assert(reg->row_end_pos <= reg->row_cell->end_pos);
assert(reg->col_end_pos <= reg->col_cell->end_pos);
if (reg->row_end_pos < reg->row_cell->end_pos) {
cut(self->rows, reg->row_cell, reg->row_end_pos, &src_i, &dest_i);
copy_row(self->jump_matrix, src_i, dest_i, self->cols->jump_index);
}
if (reg->col_end_pos < reg->col_cell->end_pos) {
cut(self->cols, reg->col_cell, reg->col_end_pos, &src_i, &dest_i);
copy_col(self->jump_matrix, src_i, dest_i, self->rows->jump_index);
}
/* Compute jump_target */
if (reg->row_cell->next == NULL) {
assert(reg->row_cell->end_pos == self->height);
jump_target = COL_FULL;
} else {
jump_target = reg->row_cell->next;
}
for (r_cell = reg->row_cell_start; r_cell != NULL;
r_cell = r_cell->next) {
assert(self->jump_matrix[r_cell->jump_index]
[reg->col_cell_start->jump_index] == NULL);
self->jump_matrix[r_cell->jump_index][reg->
col_cell_start->jump_index] =
jump_target;
if (r_cell == reg->row_cell) {
break;
}
}
if (reg->col_cell_start == reg->col_cell) {
return;
}
for (c_cell = reg->col_cell_start->next; c_cell != NULL;
c_cell = c_cell->next) {
assert(self->jump_matrix[reg->row_cell_start->jump_index]
[c_cell->jump_index] == NULL);
self->jump_matrix[reg->row_cell_start->
jump_index][c_cell->jump_index] = jump_target;
if (c_cell == reg->col_cell) {
break;
}
}
return;
}
/* grid_find_region searches the grid for a free space that can
contain the region `reg`. */
int grid_find_region(Grid * grid, Rectangle * rectangle, Region * reg)
{
long rec_col_end_pos, rec_row_end_pos;
long delta = rectangle->height;
long tmp;
Cell *col_cell_start = NULL;
Cell *col_cell = NULL;
Cell *row_cell_start = NULL;
Cell *row_cell = NULL;
Cell *jump_first = NULL;
Cell *jump_target = NULL;
/* Loop over columns */
rec_col_end_pos = rectangle->width;
col_cell_start = grid->cols->head;
while (col_cell_start != NULL) {
/* Loop over rows */
rec_row_end_pos = rectangle->height;
row_cell_start = row_cell = grid->rows->head;
jump_first = NULL;
while (row_cell_start != NULL) {
/* Check if cell is free. The cell is free if the
jump_matrix element is NULL. If not NULL, it is a
pointer to the next row cell to test. This is an
optimization to prevent checking cells we already know
are not free. */
jump_target =
grid->jump_matrix[row_cell->
jump_index][col_cell_start->jump_index];
if (jump_target != NULL) {
if (jump_first == NULL) {
jump_first = row_cell;
} else {
/* This is an optimization to make bigger jumps */
grid->jump_matrix[jump_first->jump_index]
[col_cell_start->jump_index] = jump_target;
}
}
/* Column full. Abort this column. */
if (jump_target == COL_FULL) {
break;
}
/* Normal jump */
if (jump_target != NULL) {
row_cell = row_cell_start = jump_target;
rec_row_end_pos =
row_cell->prev->end_pos + rectangle->height;
continue;
}
/* Free slot. Reset jump_first. */
jump_first = NULL;
/* Rectangle hight still doesn't fit; continue search */
if (row_cell->end_pos < rec_row_end_pos) {
row_cell = row_cell->next;
if (row_cell == NULL) {
/* No more rows. Abort. */
if ((tmp = rec_row_end_pos - grid->height) < delta) {
delta = tmp;
}
break;
}
continue;
}
/* Free row-range found. Now we need to search column-wise
to check if free space is available in that direction
as well. */
col_cell = col_cell_start;
while (col_cell != NULL) {
jump_target =
grid->
jump_matrix[row_cell_start->jump_index][col_cell->
jump_index];
if (jump_target != NULL) {
break;
}
if (rec_col_end_pos <= col_cell->end_pos) {
/* Free region found */
reg->row_cell_start = row_cell_start;
reg->row_cell = row_cell;
reg->row_end_pos = rec_row_end_pos;
reg->col_cell_start = col_cell_start;
reg->col_cell = col_cell;
reg->col_end_pos = rec_col_end_pos;
return delta;
}
col_cell = col_cell->next;
}
/* Todo: Consider removing this break to continue the
search further down the row. */
break;
}
/* Prepare new iteration */
rec_col_end_pos = col_cell_start->end_pos + rectangle->width;
col_cell_start = col_cell_start->next;
/* Too wide to fit in any remaining columns. Abort. */
if (rec_col_end_pos > grid->width) {
break;
}
}
/* Failure! Couldn't find a free region. */
reg->col_cell = NULL; /* Used as fail signal */
return delta;
}
/* grid_search_bbox will search for a bbox with smallest area that can
contain all the rectangles, `sizes`, in the `grid`. The bounding
box must also satisfy the bounding box restrictions `bbr`. */
long
grid_search_bbox(Grid * grid, Rectangle * sizes, BBoxRestrictions * bbr)
{
size_t i = 0;
long happy_area = 1; /* Todo */
long start_width, start_area, area, best_h, best_w, delta, d, grid_w;
Region reg;
grid->height = bbr->min_height;
grid->width = bbr->max_area / grid->height;
if (bbr->max_width < grid->width) {
grid->width = bbr->max_width;
}
start_width = grid->width;
start_area = area = bbr->max_area - 1;
best_w = grid->width;
best_h = grid->height;
while (grid->height <= bbr->max_height
&& bbr->min_width <= grid->width) {
grid_clear(grid);
delta = bbr->max_height;
grid_w = 0;
/* Find position for all rectangles */
for (i = 0; i < grid->size - 1; i++) {
d = grid_find_region(grid, &sizes[i], ®);
if (d < delta) {
delta = d;
}
/* Break if failure */
if (reg.col_cell == NULL) {
break;
}
/* Keep track of current grid width */
if (grid_w < reg.col_end_pos) {
grid_w = reg.col_end_pos;
}
assert(grid_w <= grid->width);
grid_split(grid, ®);
}
/* All rectangles successfully packed? Update area. */
if (reg.col_cell != NULL) {
best_h = grid->height;
best_w = grid_w;
assert(best_h * best_w < area);
area = best_h * best_w;
assert(area <= bbr->max_area);
if (area <= happy_area) {
/* We have found a solution the caller is happy
with. End search. */
goto done;
}
}
/* Inc height */
grid->height += delta;
/* Dec width limit */
grid->width = area / grid->height;
if (grid->width > bbr->max_width) {
grid->width = bbr->max_width;
}
if (grid->width * grid->height == area) {
grid->width -= 1;
}
assert(grid->width * grid->height < area);
}
/* If the area hasn't changed from the start it means that we
never found a successful packing in the while loop. We set the
grid maximum with/height and return a negative value to
indicate failure. */
if (start_area == area) {
grid->width = start_width;
grid->height = bbr->min_height;
return -1;
}
/* Success */
done:grid->width = best_w;
grid->height = best_h;
return best_h;
}
/* ==========
* TEST CASES
* ==========
*/
#ifndef NDEBUG
static void test_cell_link(void)
{
CellLink *cl = NULL;
cl = alloc_cell_link(100, 1234);
assert(cl != NULL);
assert(cl->size == 100);
assert(cl->end_pos == 1234);
assert(cl->jump_index == 1);
assert(cl->head == &cl->cells[0]);
assert(cl->head->prev == NULL);
assert(cl->head->next == NULL);
assert(cl->head->end_pos == cl->end_pos);
free_cell_link(cl);
}
static void test_cell_link_cut(void)
{
CellLink *cl = NULL;
cl = alloc_cell_link(100, 1000);
assert(cl != NULL);
size_t src_i, dest_i;
cut(cl, cl->head, 111, &src_i, &dest_i);
assert(cl->size == 100);
assert(cl->end_pos == 1000);
assert(cl->jump_index == 2);
assert(cl->head == &cl->cells[0]);
assert(cl->head->prev == NULL);
assert(cl->head->next == &cl->cells[1]);
assert(cl->head->end_pos == 111);
assert(src_i == 0);
assert(dest_i == 1);
assert(cl->cells[1].prev == cl->head);
assert(cl->cells[1].end_pos == 1000);
cut(cl, cl->head, 11, &src_i, &dest_i);
assert(src_i == 0);
assert(dest_i == 2);
assert(cl->head->end_pos == 11);
assert(cl->head->next->jump_index == 2);
assert(start_pos(cl->head->next) == 11);
clear_cell_link(cl);
assert(cl->jump_index == 1);
free_cell_link(cl);
}
static void test_jump_matrix(void)
{
Cell *cell = NULL;
JumpMatrix jm = NULL;
size_t i, j, size;
size = 100;
jm = alloc_jump_matrix(size);
assert(jm != NULL);
assert(jm[0][0] == NULL);
for (i = 0; i < size; i++) {
for (j = 0; j < size; j++) {
jm[i][j] = cell;
}
}
free(jm);
}
static void test_jump_matrix_copy(void)
{
JumpMatrix jm = NULL;
size_t i, j, size;
size = 2;
jm = alloc_jump_matrix(size);
assert(jm != NULL);
assert(jm[0][0] == NULL);
copy_row(jm, 0, 1, 1);
copy_col(jm, 0, 1, 2);
for (i = 0; i < size; i++) {
for (j = 0; j < size; j++) {
assert(jm[i][j] == NULL);
}
}
free(jm);
}
static void test_grid(void)
{
Grid *grid = NULL;
grid = grid_alloc(100, 120, 50);
assert(grid != NULL);
assert(grid->size == 100);
assert(grid->width == 120);
assert(grid->height == 50);
assert(grid->cols != NULL);
assert(grid->rows != NULL);
assert(grid->jump_matrix != NULL);
grid_free(grid);
}
static void test_grid_split(void)
{
Grid *grid = NULL;
Region reg;
grid = grid_alloc(100, 120, 50);
assert(grid != NULL);
reg.row_cell_start = reg.row_cell = grid->rows->head;
reg.row_end_pos = 30;
reg.col_cell_start = reg.col_cell = grid->cols->head;
reg.col_end_pos = 30;
grid_split(grid, ®);
assert(grid->rows->head->end_pos == 30);
assert(grid->cols->head->end_pos == 30);
assert(grid->rows->head->next->end_pos == 50);
assert(grid->cols->head->next->end_pos == 120);
Cell _cell;
Cell *test_cell = &_cell;
grid->jump_matrix[0][0] = test_cell;
reg.row_cell_start = reg.row_cell = grid->rows->head->next;
reg.row_end_pos = 40;
reg.col_cell_start = reg.col_cell = grid->cols->head;
reg.col_end_pos = 10;
grid_split(grid, ®);
assert(grid->jump_matrix[0][0] == test_cell);
assert(grid->jump_matrix[0][1] == NULL);
assert(grid->jump_matrix[0][2] == test_cell);
assert(grid->jump_matrix[1][0] == grid->rows->head->next->next);
assert(grid->jump_matrix[1][1] == NULL);
assert(grid->jump_matrix[1][2] == NULL);
assert(grid->jump_matrix[2][0] == NULL);
assert(grid->jump_matrix[2][1] == NULL);
assert(grid->jump_matrix[2][2] == NULL);
grid_free(grid);
}
int main(void)
{
test_cell_link();
test_cell_link_cut();
printf("CELL LINK: PASSED\n");
test_jump_matrix();
test_jump_matrix_copy();
printf("JUMP MATRIX: PASSED\n");
test_grid();
test_grid_split();
printf("GRID: PASSED\n");
return 0;
}
#endif
| 1 | 0.874328 | 1 | 0.874328 | game-dev | MEDIA | 0.518052 | game-dev | 0.996002 | 1 | 0.996002 |
UnityTechnologies/Test_ShaderGraphBlog | 1,453 | Assets/Unity Recorder/Editor/Sources/Recorders/GIFRecorder/GIFRecorderSettings.cs | using UnityEditor.Recorder.FrameCapturer;
using UnityEngine;
namespace UnityEditor.Recorder
{
[RecorderSettings(typeof(GIFRecorder), "GIF Animation", "imagesequence_16")]
public class GIFRecorderSettings : BaseFCRecorderSettings
{
[SerializeField] internal fcAPI.fcGifConfig gifEncoderSettings = fcAPI.fcGifConfig.default_value;
public int numColors
{
get { return gifEncoderSettings.numColors; }
set { gifEncoderSettings.numColors = Mathf.Clamp(value, 1, 256); }
}
public int keyframeInterval
{
get { return gifEncoderSettings.keyframeInterval; }
set { gifEncoderSettings.keyframeInterval = Mathf.Clamp(value, 1, 120); }
}
public int maxTasks
{
get { return gifEncoderSettings.maxTasks; }
set { gifEncoderSettings.maxTasks = Mathf.Clamp(value, 1, 32); }
}
public GIFRecorderSettings()
{
fileNameGenerator.fileName = "gif_animation_" + DefaultWildcard.Take;
m_ImageInputSelector.cameraInputSettings.flipFinalOutput = true;
m_ImageInputSelector.renderTextureInputSettings.flipFinalOutput = true;
m_ImageInputSelector.renderTextureSamplerSettings.flipFinalOutput = true;
}
public override string extension
{
get { return "gif"; }
}
}
}
| 1 | 0.894987 | 1 | 0.894987 | game-dev | MEDIA | 0.472384 | game-dev | 0.851095 | 1 | 0.851095 |
jakubkulhan/chrome-devtools-protocol | 1,391 | gen-src/ChromeDevtoolsProtocol/Model/Overlay/SetShowGridOverlaysRequest.php | <?php
namespace ChromeDevtoolsProtocol\Model\Overlay;
/**
* Request for Overlay.setShowGridOverlays command.
*
* @generated This file has been auto-generated, do not edit.
*
* @author Jakub Kulhan <jakub.kulhan@gmail.com>
*/
final class SetShowGridOverlaysRequest implements \JsonSerializable
{
/**
* An array of node identifiers and descriptors for the highlight appearance.
*
* @var GridNodeHighlightConfig[]
*/
public $gridNodeHighlightConfigs;
/**
* @param object $data
* @return static
*/
public static function fromJson($data)
{
$instance = new static();
if (isset($data->gridNodeHighlightConfigs)) {
$instance->gridNodeHighlightConfigs = [];
foreach ($data->gridNodeHighlightConfigs as $item) {
$instance->gridNodeHighlightConfigs[] = GridNodeHighlightConfig::fromJson($item);
}
}
return $instance;
}
public function jsonSerialize()
{
$data = new \stdClass();
if ($this->gridNodeHighlightConfigs !== null) {
$data->gridNodeHighlightConfigs = [];
foreach ($this->gridNodeHighlightConfigs as $item) {
$data->gridNodeHighlightConfigs[] = $item->jsonSerialize();
}
}
return $data;
}
/**
* Create new instance using builder.
*
* @return SetShowGridOverlaysRequestBuilder
*/
public static function builder(): SetShowGridOverlaysRequestBuilder
{
return new SetShowGridOverlaysRequestBuilder();
}
}
| 1 | 0.890587 | 1 | 0.890587 | game-dev | MEDIA | 0.463083 | game-dev,graphics-rendering | 0.846607 | 1 | 0.846607 |
lichess-org/lila | 5,315 | modules/simul/src/main/SimulRepo.scala | package lila.simul
import chess.variant.Variant
import chess.{ Clock, Status }
import reactivemongo.api.bson.*
import lila.core.game.GameRepo
import lila.db.BSON
import lila.db.dsl.{ *, given }
final private[simul] class SimulRepo(val coll: Coll, gameRepo: GameRepo)(using Executor):
import gameRepo.given
private given BSONHandler[SimulStatus] = tryHandler(
{ case BSONInteger(v) => SimulStatus(v).toTry(s"No such simul status: $v") },
x => BSONInteger(x.id)
)
private given BSONHandler[Variant] = variantByIdHandler
private given BSONDocumentHandler[Clock.Config] = Macros.handler
private given BSONDocumentHandler[SimulClock] = Macros.handler
private given BSONDocumentHandler[SimulPlayer] = Macros.handler
private given BSONDocumentHandler[SimulApplicant] = Macros.handler
private given BSON[SimulPairing] with
def reads(r: BSON.Reader) =
SimulPairing(
player = r.get[SimulPlayer]("player"),
gameId = r.get[GameId]("gameId"),
status = r.get[Status]("status"),
wins = r.boolO("wins"),
hostColor = r.strO("hostColor").flatMap(Color.fromName) | chess.White
)
def writes(w: BSON.Writer, o: SimulPairing) =
$doc(
"player" -> o.player,
"gameId" -> o.gameId,
"status" -> o.status,
"wins" -> o.wins,
"hostColor" -> o.hostColor.name
)
import SimulCondition.bsonHandler
private given BSONDocumentHandler[Simul] = Macros.handler
private val createdSelect = $doc("status" -> SimulStatus.Created.id)
private val startedSelect = $doc("status" -> SimulStatus.Started.id)
private val finishedSelect = $doc("status" -> SimulStatus.Finished.id)
private val createdSort = $sort.desc("createdAt")
def find(id: SimulId): Fu[Option[Simul]] =
coll.byId[Simul](id)
def byIds(ids: List[SimulId]): Fu[List[Simul]] =
coll.byIds[Simul, SimulId](ids)
def exists(id: SimulId): Fu[Boolean] =
coll.exists($id(id))
def findStarted(id: SimulId): Fu[Option[Simul]] =
find(id).map(_.filter(_.isStarted))
def findCreated(id: SimulId): Fu[Option[Simul]] =
find(id).map(_.filter(_.isCreated))
def findPending(hostId: UserId): Fu[List[Simul]] =
coll.list[Simul](createdSelect ++ $doc("hostId" -> hostId))
def byTeamLeaders[U: UserIdOf](teamId: TeamId, hosts: Seq[U]): Fu[List[Simul]] =
coll
.find(createdSelect ++ $doc("hostId".$in(hosts.map(_.id)), "team" -> teamId))
.hint(coll.hint($doc("hostId" -> 1)))
.cursor[Simul]()
.listAll()
def byHostAdapter(hostId: UserId) =
lila.db.paginator.Adapter[Simul](
collection = coll,
selector = finishedSelect ++ $doc("hostId" -> hostId),
projection = none,
sort = createdSort,
_.sec
)
def hostId(id: SimulId): Fu[Option[UserId]] =
coll.primitiveOne[UserId]($id(id), "hostId")
def countByHost(hostId: UserId) = coll.secondary.countSel($doc("hostId" -> hostId))
private val featurableSelect = $doc("featurable" -> true)
def allCreatedFeaturable: Fu[List[Simul]] =
coll
.find(
// hits partial index hostSeenAt_-1
createdSelect ++ featurableSelect ++ $doc(
"hostSeenAt".$gte(nowInstant.minusSeconds(12)),
"createdAt".$gte(nowInstant.minusHours(1))
)
)
.sort(createdSort)
.hint(coll.hint($doc("hostSeenAt" -> -1)))
.cursor[Simul]()
.list(50)
.map:
_.foldLeft(List.empty[Simul]) {
case (acc, sim) if acc.exists(_.hostId == sim.hostId) => acc
case (acc, sim) => sim :: acc
}.reverse
def allStarted: Fu[List[Simul]] =
coll
.find(startedSelect)
.sort(createdSort)
.cursor[Simul]()
.list(50)
def allFinishedFeaturable(max: Int): Fu[List[Simul]] =
coll
.find(finishedSelect ++ featurableSelect)
.sort($sort.desc("finishedAt"))
.cursor[Simul]()
.list(max)
def allNotFinished =
coll.list[Simul]($doc("status".$ne(SimulStatus.Finished.id)))
def create(simul: Simul): Funit =
coll.insert.one(simul).void
def update(simul: Simul) =
coll.update
.one(
$id(simul.id),
$set(bsonWriteObjTry[Simul](simul).get) ++
simul.estimatedStartAt.isEmpty.so($unset("estimatedStartAt"))
)
.void
def remove(simul: Simul) =
coll.delete.one($id(simul.id)).void
def setHostGameId(simul: Simul, gameId: GameId) =
coll.update
.one(
$id(simul.id),
$set("hostGameId" -> gameId)
)
.void
def setHostSeenNow(simul: Simul) =
coll.update
.one(
$id(simul.id),
$set("hostSeenAt" -> nowInstant)
)
.void
def setText(simul: Simul, text: String) =
coll.update
.one(
$id(simul.id),
$set("text" -> text)
)
.void
def cleanup =
coll.delete.one(
createdSelect ++ $doc(
"createdAt" -> $doc("$lt" -> (nowInstant.minusMinutes(60)))
)
)
private[simul] def anonymizeHost(id: UserId) =
coll.update.one($doc("hostId" -> id), $set("hostId" -> UserId.ghost), multi = true)
private[simul] def anonymizePlayers(id: UserId) =
coll.update.one(
$doc("pairings.player.user" -> id),
$set("pairings.$.player.user" -> UserId.ghost),
multi = true
)
| 1 | 0.81095 | 1 | 0.81095 | game-dev | MEDIA | 0.306469 | game-dev | 0.943604 | 1 | 0.943604 |
kami-blue/client | 5,118 | src/main/kotlin/org/kamiblue/client/module/modules/movement/Strafe.kt | package org.kamiblue.client.module.modules.movement
import net.minecraft.client.settings.KeyBinding
import org.kamiblue.client.event.SafeClientEvent
import org.kamiblue.client.event.events.PlayerTravelEvent
import org.kamiblue.client.manager.managers.TimerManager.modifyTimer
import org.kamiblue.client.manager.managers.TimerManager.resetTimer
import org.kamiblue.client.mixin.extension.isInWeb
import org.kamiblue.client.module.Category
import org.kamiblue.client.module.Module
import org.kamiblue.client.util.BaritoneUtils
import org.kamiblue.client.util.EntityUtils.isInOrAboveLiquid
import org.kamiblue.client.util.MovementUtils
import org.kamiblue.client.util.MovementUtils.applySpeedPotionEffects
import org.kamiblue.client.util.MovementUtils.calcMoveYaw
import org.kamiblue.client.util.MovementUtils.setSpeed
import org.kamiblue.client.util.MovementUtils.speed
import org.kamiblue.client.util.TickTimer
import org.kamiblue.client.util.TimeUnit
import org.kamiblue.client.util.threads.safeListener
import kotlin.math.cos
import kotlin.math.sin
internal object Strafe : Module(
name = "Strafe",
category = Category.MOVEMENT,
description = "Improves control in air",
modulePriority = 100
) {
private val mode by setting("Mode", SpeedBoost.NCP)
private val page by setting("Page", Page.GENERIC_SETTINGS)
/* Generic Settings */
private val airSpeedBoost by setting("Air Speed Boost", true, { page == Page.GENERIC_SETTINGS })
private val groundSpeedBoost by setting("Ground Speed Boost", true, { page == Page.GENERIC_SETTINGS })
private val timerBoost by setting("Timer Boost", true, { page == Page.GENERIC_SETTINGS })
private val autoJump by setting("Auto Jump", true, { page == Page.GENERIC_SETTINGS })
private val onHoldingSprint by setting("On Holding Sprint", false, { page == Page.GENERIC_SETTINGS })
private val cancelInertia by setting("Cancel Inertia", false, { page == Page.GENERIC_SETTINGS })
/* NCP Mode */
private val ncpStrict by setting("NCP Strict", false, { mode == SpeedBoost.NCP && page == Page.MODE_SETTINGS })
/* Custom Mode */
private val settingSpeed by setting("Speed", 0.28, 0.0..1.0, 0.01, { mode == SpeedBoost.CUSTOM && page == Page.MODE_SETTINGS })
private val constantSpeed by setting("Constant Speed", false, { mode == SpeedBoost.CUSTOM && page == Page.MODE_SETTINGS })
private enum class SpeedBoost {
NCP, CUSTOM
}
private enum class Page {
GENERIC_SETTINGS, MODE_SETTINGS
}
private var jumpTicks = 0
private val strafeTimer = TickTimer(TimeUnit.TICKS)
init {
onDisable {
reset()
}
safeListener<PlayerTravelEvent> {
if (!shouldStrafe) {
reset()
if (cancelInertia && !strafeTimer.tick(2L, false)) {
player.motionX = 0.0
player.motionZ = 0.0
}
return@safeListener
}
if (airSpeedBoost) player.jumpMovementFactor = 0.029f
if (timerBoost) modifyTimer(45.87155914306640625f)
if (!player.collidedHorizontally) {
if (autoJump) jump()
setSpeed(getSpeed())
}
strafeTimer.reset()
}
}
private fun reset() {
mc.player?.jumpMovementFactor = 0.02f
resetTimer()
jumpTicks = 0
}
private val SafeClientEvent.shouldStrafe: Boolean
get() = !player.capabilities.isFlying
&& !player.isElytraFlying
&& !mc.gameSettings.keyBindSneak.isKeyDown
&& (!onHoldingSprint || mc.gameSettings.keyBindSprint.isKeyDown)
&& !BaritoneUtils.isPathing
&& MovementUtils.isInputting
&& !(player.isInOrAboveLiquid || player.isInWeb)
private fun SafeClientEvent.jump() {
if (player.onGround && jumpTicks <= 0) {
if (player.isSprinting) {
val yaw = calcMoveYaw()
player.motionX -= sin(yaw) * 0.2
player.motionZ += cos(yaw) * 0.2
}
KeyBinding.setKeyBindState(mc.gameSettings.keyBindJump.keyCode, false)
player.motionY = 0.41
player.isAirBorne = true
jumpTicks = 5
}
jumpTicks--
}
private fun SafeClientEvent.getSpeed() = when (mode) {
SpeedBoost.NCP -> {
if (shouldBoostGroundSpeed) {
val speed = if (ncpStrict) 0.26 else 0.28
applySpeedPotionEffects(speed)
} else {
player.speed
}
}
SpeedBoost.CUSTOM -> {
when {
constantSpeed -> {
settingSpeed
}
shouldBoostGroundSpeed -> {
applySpeedPotionEffects(settingSpeed)
}
else -> {
player.speed
}
}
}
}
private val SafeClientEvent.shouldBoostGroundSpeed
get() = groundSpeedBoost && player.onGround
}
| 1 | 0.84726 | 1 | 0.84726 | game-dev | MEDIA | 0.809907 | game-dev | 0.932019 | 1 | 0.932019 |
ixray-team/ixray-1.6-stcop | 7,696 | gamedata/configs/scripts/zaton/zat_b106_stalker_gonta.ltx | [logic@zat_b106_stalker_gonta]
suitable = {=check_npc_name(zat_b106_stalker_gonta)} true
prior = 200
active = walker@start
[walker@start]
path_walk = gonta_1_walk
path_look = garmata_1_walk
def_state_standing = wait_na
meet = no_meet
on_info = {-zat_b106_start_dialogs} walker@infirmary ;%+zat_b106_start_dialogs%
on_info2 = {+zat_b106_start_dialogs -zat_b106_hunt_finish} animpoint@base
on_info3 = {+zat_b106_start_dialogs +zat_b106_hunt_finish} walker@ya_doma %+zat_b106_gonta_free%
combat_ignore_cond = true
combat_ignore_keep_when_attacked = true
invulnerable = true
out_restr = zat_a2_sr_noweap
gather_items_enabled = false
help_wounded_enabled = false
corpse_detection_enabled = false
def_state_moving = walk
[walker@infirmary]
path_walk = gonta_1_walk
path_look = garmata_1_walk
def_state_standing = wait_na
meet = no_meet
on_info = {=actor_in_zone(zat_b106_sr_infirmary)} remark@story_ask %+zat_b106_start_dialogs%
combat_ignore_cond = true
combat_ignore_keep_when_attacked = true
invulnerable = true
out_restr = zat_a2_sr_noweap
gather_items_enabled = false
help_wounded_enabled = false
corpse_detection_enabled = false
def_state_moving = walk
[remark@story_ask]
anim = wait_na
target = path | zat_stalker_base_smart_garmata_1_walk, 0
on_info = %=play_sound(zat_b106_gonta_story_ask)%
on_signal = sound_end | walker@story_wait %+zat_b106_gonta_story_ask_done%
meet = no_meet
combat_ignore_cond = true
combat_ignore_keep_when_attacked = true
invulnerable = true
out_restr = zat_a2_sr_noweap
gather_items_enabled = false
help_wounded_enabled = false
corpse_detection_enabled = false
def_state_moving = walk
[walker@story_wait]
path_walk = gonta_1_walk
path_look = garmata_1_walk
def_state_standing = wait_na
meet = no_meet
on_info = {+zat_b106_garmata_story_reply_done} remark@story_angry
combat_ignore_cond = true
combat_ignore_keep_when_attacked = true
invulnerable = true
out_restr = zat_a2_sr_noweap
gather_items_enabled = false
help_wounded_enabled = false
corpse_detection_enabled = false
def_state_moving = walk
[remark@story_angry]
anim = wait_na
target = path | zat_stalker_base_smart_garmata_1_walk, 0
on_info = %=play_sound(zat_b106_gonta_story_angry)%
on_signal = sound_end | walker@story_angry
meet = no_meet
combat_ignore_cond = true
combat_ignore_keep_when_attacked = true
invulnerable = true
out_restr = zat_a2_sr_noweap
gather_items_enabled = false
help_wounded_enabled = false
corpse_detection_enabled = false
def_state_moving = walk
[walker@story_angry]
path_walk = gonta_1_walk
path_look = gonta_2_look
def_state_standing = wait_na
meet = no_meet
on_game_timer = 30 | remark@story_calm
;on_signal = crab_look | remark@story_calm
combat_ignore_cond = true
combat_ignore_keep_when_attacked = true
invulnerable = true
out_restr = zat_a2_sr_noweap
gather_items_enabled = false
help_wounded_enabled = false
corpse_detection_enabled = false
def_state_moving = walk
[remark@story_calm]
anim = stoop_no_weap ;wait_na
target = story | zat_b106_stalker_crab
on_info = %=play_sound(zat_b106_gonta_story_calm)%
on_signal = anim_end | {!actor_in_zone(zat_b106_actor_go_on)} walker@story_calm %+zat_b106_gonta_story_calm_done%, {=actor_in_zone(zat_b106_actor_go_on)} walker@to_actor
meet = no_meet
combat_ignore_cond = true
combat_ignore_keep_when_attacked = true
invulnerable = true
out_restr = zat_a2_sr_noweap
gather_items_enabled = false
help_wounded_enabled = false
corpse_detection_enabled = false
def_state_moving = walk
[walker@story_calm]
path_walk = gonta_1_walk
path_look = gonta_1_look
def_state_standing = wait_na
meet = no_meet
on_game_timer = 10 | animpoint@base
combat_ignore_cond = true
combat_ignore_keep_when_attacked = true
invulnerable = true
out_restr = zat_a2_sr_noweap
gather_items_enabled = false
help_wounded_enabled = false
corpse_detection_enabled = false
def_state_moving = walk
[walker@to_actor]
path_walk = gonta_1_walk
path_look = gonta_1_look
def_state_standing = wait_na
meet = no_meet
on_game_timer = 20 | {!is_playing_sound} remark@to_actor
;on_signal = actor_look | {!is_playing_sound} remark@story_calm
combat_ignore_cond = true
combat_ignore_keep_when_attacked = true
invulnerable = true
out_restr = zat_a2_sr_noweap
gather_items_enabled = false
help_wounded_enabled = false
corpse_detection_enabled = false
def_state_moving = walk
[remark@to_actor]
anim = wait_na
target = story | actor
on_info = %=play_sound(zat_b106_gonta_to_actor)%
on_signal = sound_end | {!actor_in_zone(zat_b106_actor_go_on)} walker@story_calm %+zat_b106_gonta_story_calm_done%, {=actor_in_zone(zat_b106_actor_go_on)} remark@wait_actor ;walker@wait_actor
meet = no_meet
snd_anim_sync = true
combat_ignore_cond = true
combat_ignore_keep_when_attacked = true
invulnerable = true
out_restr = zat_a2_sr_noweap
gather_items_enabled = false
help_wounded_enabled = false
corpse_detection_enabled = false
def_state_moving = walk
[walker@wait_actor]
path_walk = gonta_1_walk
path_look = gonta_1_look
def_state_standing = wait_na
on_game_timer = 10 | remark@wait_actor
;on_info = {!actor_in_zone(zat_b106_actor_go_on)} walker@story_calm %+zat_b106_gonta_story_calm_done%
meet = no_meet
combat_ignore_cond = true
combat_ignore_keep_when_attacked = true
invulnerable = true
out_restr = zat_a2_sr_noweap
gather_items_enabled = false
help_wounded_enabled = false
corpse_detection_enabled = false
def_state_moving = walk
[remark@wait_actor]
anim = wait_na
target = story | actor
on_info = {!actor_in_zone(zat_b106_actor_go_on)} walker@story_calm %+zat_b106_gonta_story_calm_done%
meet = meet
combat_ignore_cond = true
combat_ignore_keep_when_attacked = true
invulnerable = true
out_restr = zat_a2_sr_noweap
gather_items_enabled = false
help_wounded_enabled = false
corpse_detection_enabled = false
def_state_moving = walk
[walker@ya_doma]
path_walk = gonta_4_walk
path_look = gonta_4_look
on_signal = gonta_home | animpoint@base
def_state_standing = guard_na
meet = no_meet
combat_ignore_cond = true
combat_ignore_keep_when_attacked = true
invulnerable = true
out_restr = zat_a2_sr_noweap
gather_items_enabled = false
help_wounded_enabled = false
corpse_detection_enabled = false
def_state_moving = assault
wounded = wounded
[animpoint@base]
cover_name = zat_a2_sc_zat_b106_stalker_gonta
meet = meet
use_camp = false
;on_info = {+zat_b106_give_gonta_items -zat_b106_give_gonta_items_done} %=give_items(wpn_ak74:ammo_5.45x39_fmj) +zat_b106_give_gonta_items_done%
;on_info2 = {+zat_b106_give_gonta_items_2 -zat_b106_give_gonta_items_2_done} %=give_items(wpn_ak74:ammo_5.45x39_fmj) +zat_b106_give_gonta_items_2_done%
combat_ignore_cond = true
combat_ignore_keep_when_attacked = true
invulnerable = true
out_restr = zat_a2_sr_noweap
gather_items_enabled = false
help_wounded_enabled = false
corpse_detection_enabled = false
[meet@idle]
close_victim = actor
close_distance = 5
close_snd_hello = nil
close_snd_bye = nil
close_anim = wait_na
use = {!dist_to_actor_le(3)} false, {=actor_enemy} false, true
meet_dialog = {-zat_b106_first_dialog_done} zat_b106_stalker_gonta_info_about_soroka_start
trade_enable = false
allow_break = false
abuse = true
[meet]
close_anim = nil
close_victim = nil
far_anim = nil
far_victim = nil
close_distance = 0
far_distance = 0
close_snd_hello = nil
close_snd_bye = nil
use = {!dist_to_actor_le(3)} false, {=actor_enemy} false, true
meet_dialog = {-zat_b106_first_dialog_done} zat_b106_stalker_gonta_info_about_soroka_start
trade_enable = false
allow_break = false
meet_on_talking = false
[wounded]
hp_state = 0|wounded_heavy@help_heavy
hp_state_see = 0|wounded_heavy@help_heavy
hp_victim = 0|nil
hp_fight = 0|false
hp_cover = 0|false | 1 | 0.931944 | 1 | 0.931944 | game-dev | MEDIA | 0.99547 | game-dev | 0.896658 | 1 | 0.896658 |
hyprwm/hyprutils | 2,781 | include/hyprutils/animation/AnimationConfig.hpp | #pragma once
#include "../memory/WeakPtr.hpp"
#include <string>
#include <unordered_map>
namespace Hyprutils {
namespace Animation {
/*
Structure for animation properties.
Config properties need to have a static lifetime to allow for config reload.
*/
struct SAnimationPropertyConfig {
bool overridden = false;
std::string internalBezier = "";
std::string internalStyle = "";
float internalSpeed = 0.f;
int internalEnabled = -1;
Memory::CWeakPointer<SAnimationPropertyConfig> pValues;
Memory::CWeakPointer<SAnimationPropertyConfig> pParentAnimation;
};
/* A class to manage SAnimationPropertyConfig objects in a tree structure */
class CAnimationConfigTree {
public:
CAnimationConfigTree() = default;
~CAnimationConfigTree() = default;
/* Add a new animation node inheriting from a parent.
If parent is empty, a root node will be created that references it's own values.
Make sure the parent node has already been created through this interface. */
void createNode(const std::string& nodeName, const std::string& parent = "");
/* check if a node name has been created using createNode */
bool nodeExists(const std::string& nodeName) const;
/* Override the values of a node. The root node can also be overriden. */
void setConfigForNode(const std::string& nodeName, int enabled, float speed, const std::string& bezier, const std::string& style = "");
Memory::CSharedPointer<SAnimationPropertyConfig> getConfig(const std::string& name) const;
const std::unordered_map<std::string, Memory::CSharedPointer<SAnimationPropertyConfig>>& getFullConfig() const;
CAnimationConfigTree(const CAnimationConfigTree&) = delete;
CAnimationConfigTree(CAnimationConfigTree&&) = delete;
CAnimationConfigTree& operator=(const CAnimationConfigTree&) = delete;
CAnimationConfigTree& operator=(CAnimationConfigTree&&) = delete;
private:
void setAnimForChildren(Memory::CSharedPointer<SAnimationPropertyConfig> PANIM);
std::unordered_map<std::string, Memory::CSharedPointer<SAnimationPropertyConfig>> m_mAnimationConfig;
};
}
}
| 1 | 0.91421 | 1 | 0.91421 | game-dev | MEDIA | 0.357829 | game-dev | 0.728325 | 1 | 0.728325 |
Space-Stories/space-station-14 | 3,528 | Content.Shared/Devour/SharedDevourSystem.cs | using Content.Shared.Actions;
using Content.Shared.Devour.Components;
using Content.Shared.DoAfter;
using Content.Shared.Mobs;
using Content.Shared.Mobs.Components;
using Content.Shared.Popups;
using Content.Shared.Whitelist;
using Robust.Shared.Audio;
using Robust.Shared.Audio.Systems;
using Robust.Shared.Containers;
using Robust.Shared.Serialization;
namespace Content.Shared.Devour;
public abstract class SharedDevourSystem : EntitySystem
{
[Dependency] protected readonly SharedAudioSystem _audioSystem = default!;
[Dependency] private readonly SharedDoAfterSystem _doAfterSystem = default!;
[Dependency] private readonly SharedPopupSystem _popupSystem = default!;
[Dependency] private readonly SharedActionsSystem _actionsSystem = default!;
[Dependency] protected readonly SharedContainerSystem ContainerSystem = default!;
[Dependency] private readonly EntityWhitelistSystem _whitelistSystem = default!;
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<DevourerComponent, MapInitEvent>(OnInit);
SubscribeLocalEvent<DevourerComponent, DevourActionEvent>(OnDevourAction);
}
protected void OnInit(EntityUid uid, DevourerComponent component, MapInitEvent args)
{
//Devourer doesn't actually chew, since he sends targets right into his stomach.
//I did it mom, I added ERP content into upstream. Legally!
component.Stomach = ContainerSystem.EnsureContainer<Container>(uid, "stomach");
_actionsSystem.AddAction(uid, ref component.DevourActionEntity, component.DevourAction);
}
/// <summary>
/// The devour action
/// </summary>
protected void OnDevourAction(EntityUid uid, DevourerComponent component, DevourActionEvent args)
{
if (args.Handled || _whitelistSystem.IsWhitelistFailOrNull(component.Whitelist, args.Target))
return;
args.Handled = true;
var target = args.Target;
// Structure and mob devours handled differently.
if (TryComp(target, out MobStateComponent? targetState))
{
switch (targetState.CurrentState)
{
case MobState.Critical:
case MobState.Dead:
_doAfterSystem.TryStartDoAfter(new DoAfterArgs(EntityManager, uid, component.DevourTime, new DevourDoAfterEvent(), uid, target: target, used: uid)
{
BreakOnMove = true,
});
break;
default:
_popupSystem.PopupClient(Loc.GetString("devour-action-popup-message-fail-target-alive"), uid,uid);
break;
}
return;
}
_popupSystem.PopupClient(Loc.GetString("devour-action-popup-message-structure"), uid, uid);
if (component.SoundStructureDevour != null)
_audioSystem.PlayPredicted(component.SoundStructureDevour, uid, uid, component.SoundStructureDevour.Params);
_doAfterSystem.TryStartDoAfter(new DoAfterArgs(EntityManager, uid, component.StructureDevourTime, new DevourDoAfterEvent(), uid, target: target, used: uid)
{
BreakOnMove = true,
});
}
}
public sealed partial class DevourActionEvent : EntityTargetActionEvent { }
[Serializable, NetSerializable]
public sealed partial class DevourDoAfterEvent : SimpleDoAfterEvent { }
[Serializable, NetSerializable]
public enum FoodPreference : byte
{
Humanoid = 0,
All = 1
}
| 1 | 0.932414 | 1 | 0.932414 | game-dev | MEDIA | 0.885264 | game-dev | 0.96402 | 1 | 0.96402 |
Lallassu/gizmo | 2,226 | ai.go | package main
import (
"math/rand"
"github.com/faiface/pixel"
)
// ai used for mobs
type ai struct {
entity entity
dirX float64
dirY float64
objList []pixel.Vec
updateTime float64
}
// creates initiates a new ai entity.
func (a *ai) create(e entity) {
a.entity = e
a.dirX = 0.01
a.objList = []pixel.Vec{}
}
//updateObjectList updates the information where weapons/objects exists in the world.
func (a *ai) updateObjectList() {
// Get all weapons within view range.
m, ok := a.entity.(*mob)
if !ok {
return
}
a.objList = []pixel.Vec{}
for _, v := range global.gWorld.qt.RetrieveIntersections(&Bounds{X: m.bounds.X, Y: m.bounds.Y, Width: 300, Height: 300}) {
//if v.entity.getType() == entityObject {
switch item := v.entity.(type) {
case *weapon:
if item.isFree() {
pos := item.getPosition()
a.objList = append(a.objList, pos)
}
}
// }
}
}
// findWeapon let the AI try to find a weapon
func (a *ai) findWeapon(dt float64) {
// If at weapon position. Call m.pickup()
closest := 0.0
find := -1
ePos := a.entity.getPosition()
for i, o := range a.objList {
dist := distance(o, ePos)
if closest > dist || i == 0 {
closest = dist
find = i
}
}
if find == -1 {
return
}
if closest < 20 {
if m, ok := a.entity.(*mob); ok {
m.pickup()
}
return
}
// Go towards closest
if ePos.X > a.objList[find].X {
a.dirX = -dt
} else {
a.dirX = dt
}
if ePos.Y > a.objList[find].Y {
a.dirY = -dt
} else {
a.dirY = dt
}
}
func (a *ai) update(dt, time float64) {
var m *mob
var ok bool
if m, ok = a.entity.(*mob); !ok {
return
}
if m.carry == nil {
a.updateTime += dt
if a.updateTime > 5.0 {
a.updateObjectList()
a.updateTime = 0
} else if a.updateTime < 1.0 {
a.findWeapon(dt)
}
} else {
// Find player
distToPlayer := distance(m.getPosition(), global.gPlayer.getPosition())
if distToPlayer < 100 {
if rand.Float64() < 0.2 {
m.shoot()
}
}
}
if m.hitLeftWall {
a.dirX = -dt
} else if m.hitRightWall {
a.dirX = dt
//} else if m.IsOnLadder() {
//a.dir_y = dt
} else {
a.dirY = -dt
}
// Jump randomly
if rand.Float64() < 0.01 {
a.dirY = dt
}
m.move(a.dirX, a.dirY)
}
| 1 | 0.817054 | 1 | 0.817054 | game-dev | MEDIA | 0.948359 | game-dev | 0.94947 | 1 | 0.94947 |
M-HT/SR | 2,447 | games/Albion/SR-Main/Albion-int2.h | /**
*
* Copyright (C) 2016-2023 Roman Pauer
*
* 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.
*
*/
#if !defined(_ALBION_INT2_H_INCLUDED_)
#define _ALBION_INT2_H_INCLUDED_
#pragma pack(4)
typedef struct _Game_SREGS_ {
uint16_t es;
uint16_t cs;
uint16_t ss;
uint16_t ds;
uint16_t fs;
uint16_t gs;
} Game_SREGS;
typedef struct _Game_DWORDREGS_ {
uint32_t eax;
uint32_t ebx;
uint32_t ecx;
uint32_t edx;
uint32_t esi;
uint32_t edi;
uint32_t cflag;
} Game_DWORDREGS;
typedef struct _Game_WORDREGS_ {
uint16_t ax, _upper_ax;
uint16_t bx, _upper_bx;
uint16_t cx, _upper_cx;
uint16_t dx, _upper_dx;
uint16_t si, _upper_si;
uint16_t di, _upper_di;
uint32_t cflag;
} Game_WORDREGS;
typedef struct _Game_BYTEREGS_ {
uint8_t al;
uint8_t ah;
uint16_t _upper_ax;
uint8_t bl;
uint8_t bh;
uint16_t _upper_bx;
uint8_t cl;
uint8_t ch;
uint16_t _upper_cx;
uint8_t dl;
uint8_t dh;
uint16_t _upper_dx;
uint16_t si, _upper_si;
uint16_t di, _upper_di;
uint32_t cflag;
} Game_BYTEREGS;
typedef union _Game_REGS_ {
Game_DWORDREGS d;
Game_WORDREGS w;
Game_BYTEREGS h;
} Game_REGS;
#pragma pack()
#ifdef __cplusplus
extern "C" {
#endif
extern uint32_t Game_int386x(
const uint32_t IntNum,
const Game_REGS *in_regs,
Game_REGS *out_regs,
Game_SREGS *seg_regs
);
#ifdef __cplusplus
}
#endif
#endif /* _ALBION_INT2_H_INCLUDED_ */
| 1 | 0.595491 | 1 | 0.595491 | game-dev | MEDIA | 0.361495 | game-dev | 0.636755 | 1 | 0.636755 |
RHeavenStudioPlus/HeavenStudioPlus | 4,513 | Assets/Plugins/com.unity.uiextensions/Runtime/Scripts/Controls/ColorPicker/ColorPickerControl.cs | ///Credit judah4
///Sourced from - http://forum.unity3d.com/threads/color-picker.267043/
using System.Collections.Generic;
namespace UnityEngine.UI.Extensions.ColorPicker
{
[ExecuteInEditMode]
public class ColorPickerControl : MonoBehaviour
{
private float _hue = 0;
private float _saturation = 0;
private float _brightness = 0;
private float _red = 0;
private float _green = 0;
private float _blue = 0;
private float _alpha = 1;
public ColorChangedEvent onValueChanged = new ColorChangedEvent();
public HSVChangedEvent onHSVChanged = new HSVChangedEvent();
[SerializeField]
bool hsvSlidersOn = true;
[SerializeField]
List<GameObject> hsvSliders = new List<GameObject>();
[SerializeField]
bool rgbSlidersOn = true;
[SerializeField]
List<GameObject> rgbSliders = new List<GameObject>();
[SerializeField]
GameObject alphaSlider = null;
public void SetHSVSlidersOn(bool value)
{
hsvSlidersOn = value;
foreach (var item in hsvSliders)
item.SetActive(value);
if (alphaSlider)
alphaSlider.SetActive(hsvSlidersOn || rgbSlidersOn);
}
public void SetRGBSlidersOn(bool value)
{
rgbSlidersOn = value;
foreach (var item in rgbSliders)
item.SetActive(value);
if (alphaSlider)
alphaSlider.SetActive(hsvSlidersOn || rgbSlidersOn);
}
void Update()
{
#if UNITY_EDITOR
SetHSVSlidersOn(hsvSlidersOn);
SetRGBSlidersOn(rgbSlidersOn);
#endif
}
public Color CurrentColor
{
get
{
return new Color(_red, _green, _blue, _alpha);
}
set
{
if (CurrentColor == value)
return;
_red = value.r;
_green = value.g;
_blue = value.b;
_alpha = value.a;
RGBChanged();
SendChangedEvent();
}
}
private void Start()
{
SendChangedEvent();
}
public float H
{
get
{
return _hue;
}
set
{
if (_hue == value)
return;
_hue = value;
HSVChanged();
SendChangedEvent();
}
}
public float S
{
get
{
return _saturation;
}
set
{
if (_saturation == value)
return;
_saturation = value;
HSVChanged();
SendChangedEvent();
}
}
public float V
{
get
{
return _brightness;
}
set
{
if (_brightness == value)
return;
_brightness = value;
HSVChanged();
SendChangedEvent();
}
}
public float R
{
get
{
return _red;
}
set
{
if (_red == value)
return;
_red = value;
RGBChanged();
SendChangedEvent();
}
}
public float G
{
get
{
return _green;
}
set
{
if (_green == value)
return;
_green = value;
RGBChanged();
SendChangedEvent();
}
}
public float B
{
get
{
return _blue;
}
set
{
if (_blue == value)
return;
_blue = value;
RGBChanged();
SendChangedEvent();
}
}
private float A
{
get
{
return _alpha;
}
set
{
if (_alpha == value)
return;
_alpha = value;
SendChangedEvent();
}
}
private void RGBChanged()
{
HsvColor color = HSVUtil.ConvertRgbToHsv(CurrentColor);
_hue = color.NormalizedH;
_saturation = color.NormalizedS;
_brightness = color.NormalizedV;
}
private void HSVChanged()
{
Color color = HSVUtil.ConvertHsvToRgb(_hue * 360, _saturation, _brightness, _alpha);
_red = color.r;
_green = color.g;
_blue = color.b;
}
private void SendChangedEvent()
{
onValueChanged.Invoke(CurrentColor);
onHSVChanged.Invoke(_hue, _saturation, _brightness);
}
public void AssignColor(ColorValues type, float value)
{
switch (type)
{
case ColorValues.R:
R = value;
break;
case ColorValues.G:
G = value;
break;
case ColorValues.B:
B = value;
break;
case ColorValues.A:
A = value;
break;
case ColorValues.Hue:
H = value;
break;
case ColorValues.Saturation:
S = value;
break;
case ColorValues.Value:
V = value;
break;
default:
break;
}
}
public float GetValue(ColorValues type)
{
switch (type)
{
case ColorValues.R:
return R;
case ColorValues.G:
return G;
case ColorValues.B:
return B;
case ColorValues.A:
return A;
case ColorValues.Hue:
return H;
case ColorValues.Saturation:
return S;
case ColorValues.Value:
return V;
default:
throw new System.NotImplementedException("");
}
}
}
} | 1 | 0.92582 | 1 | 0.92582 | game-dev | MEDIA | 0.442912 | game-dev,graphics-rendering | 0.962531 | 1 | 0.962531 |
X2CommunityCore/X2WOTCCommunityHighlander | 67,570 | X2WOTCCommunityHighlander/Src/XComGame/Classes/XComGameState_AIGroup.uc |
//---------------------------------------------------------------------------------------
// ********* FIRAXIS SOURCE CODE ******************
// FILE: XComGameState_AIGroup.uc
// AUTHOR: Alex Cheng -- 12/10/2014
//---------------------------------------------------------------------------------------
// Copyright (c) 2016 Firaxis Games, Inc. All rights reserved.
//---------------------------------------------------------------------------------------
class XComGameState_AIGroup extends XComGameState_BaseObject
dependson(XComAISpawnManager, XComGameState_AIUnitData)
native(AI)
config(AI);
// The Name of this encounter, used for determining when a specific group has been engaged/defeated
var Name EncounterID;
// If specified, allows encounters to be searched for and found by tag in kismet, instead of just by EncounterID
var Name PrePlacedEncounterTag;
// How wide should this group's encounter band be?
var float MyEncounterZoneWidth;
// How deep should this group's encounter band be?
var float MyEncounterZoneDepth;
// The offset from the LOP for this group.
var float MyEncounterZoneOffsetFromLOP;
// The index of the encounter zone that this group should attempt to roam around within
var float MyEncounterZoneOffsetAlongLOP;
// If specified, the encounter zone should be defined by finding a tagged volume in the level instead of offsetting one using the previous fields.
var Name MyEncounterZoneVolumeTag;
var privatewrite array<StateObjectReference> m_arrMembers; // Current list of group members
var array<TTile> m_arrGuardLocation;
var array<StateObjectReference> m_arrDisplaced; // Reference to unit that is not currently a member due to mind-control.
// Keeping track of unit to be able to restore the unit if mind-control wears off.
var float InfluenceRange;
// Patrol group data. TODO- keep track of this here.
//var TTile kCurr; // Tile location of current node
//var TTile kLast; // Tile location of last node.
//var array<TTile> kLoc;
var bool bObjective; // Objective Guard?
var bool bPlotPath;
var bool bInterceptObjectiveLocation;
var bool bProcessedScamper; //TRUE if this AI group has scampered
var bool bPendingScamper; //TRUE if this AI group has been told to scamper, but has not started to scamper yet ( can happen during group moves that reveal XCOM )
// the current destination that this group will attempt to be moving towards while in green alert
var Vector CurrentTargetLocation;
var int TurnCountForLastDestination;
struct native ai_group_stats
{
var int m_iInitialMemberCount;
var array<StateObjectReference> m_arrDead; // Keeping track of units that have died.
};
var ai_group_stats m_kStats;
var int InitiativePriority; // in what relative initiative order should this group be processed compared to other groups for the same player. Higher # = process initiative later
////////////////////////////////////////////////////////////////////////////////////////
// Reveal/Scamper data
// The alert data which instigated the reveal/scamper.
var EAlertCause DelayedScamperCause;
// The object Id of the unit who was the source of the alert data causing this reveal/scamper.
var int RevealInstigatorUnitObjectID;
// The Object IDs of all units that were concealed prior to this reveal, but had their concealment broken.
var array<int> PreviouslyConcealedUnitObjectIDs;
// The Object IDs of the revealed units who are surprised by the reveal.
var array<int> SurprisedScamperUnitIDs;
// If this group is mid-move, this is the step along the pre-calculated movement path at which the reveal will take place.
var int FinalVisibilityMovementStep;
// If this group is mid-move, this is the list of units within this group that still need to process some of their move before the group can reveal.
var array<int> WaitingOnUnitList;
// True while this group is in the process of performing a reveal/scamper.
var bool SubmittingScamperReflexGameState;
// if non-none, this specifies a non-standard reveal type
var name SpecialRevealType;
////////////////////////////////////////////////////////////////////////////////////////
// Ever Sighted
// Until true, this group has not been sighted by enemies, so the first sighting should show a camera look at.
var protectedwrite bool EverSightedByEnemy;
var int SightedByUnitID;
////////////////////////////////////////////////////////////////////////////////////////
var config float SURPRISED_SCAMPER_CHANCE;
var config float DESTINATION_REACHED_SIZE_SQ;
var config float MAX_TURNS_BETWEEN_DESTINATIONS;
////////////////////////////////////////////////////////////////////////////////////////
// Fallback behavior variables
var bool bHasCheckedForFallback; // true if the decision to fallback or not has already been made.
var bool bFallingBack; // true if Fallback is active.
var bool bPlayedFallbackCallAnimation; // Flag if the call animation has happened already.
var StateObjectReference FallbackGroup; // Fallback group reference.
var config array<Name> FallbackExclusionList; // List of unit types that are unable to fallback
var config float FallbackChance; // Chance to fallback, currently set to 50%.
// Config variables to determine when to disable fallback.
// Fallback is disabled at the start of the AI turn when either of the following conditions are filled:
// 1) XCom has caused the fallback-to-group to scamper, and no other groups can be set as an alternate fallback, or
// 2) the Unit is in range of the fallback group, as defined by the config value below, at which time the unit joins the group at green alert
var config int UnitInFallbackRangeMeters; // Distance from fallback destination to be considered "In Fallback Area"
var int FallbackMaximumOverwatchCount; // Any more overwatchers than this will prevent fallback from activating.
////////////////////////////////////////////////////////////////////////////////////////
const Z_TILE_RANGE = 3;
////////////////////////////////////////////////////////////////////////////////////////
// Group Initiative
// If true, the initiative of this group has been interrupted; when resuming initiative,
// this group should not reinitialize action points or perform start-of-turn behaviors
var bool bInitiativeInterrupted;
// If true, this group should be removed from the initiative order after it's initiative has been processed.
// Primarily used for groups that interrupt the initiative order (like the Chosen)
var bool bShouldRemoveFromInitiativeOrder;
// The name of the team this group should be associated with (currently ETeam enum; TODO replace with FName)
var ETeam TeamName;
// The display name for this group in any UI
var string FriendlyGroupName;
// until summoning sickness is cleared (at the start of the player turn for the leader of this group),
// this group will not activate as part of the initiative order
var bool bSummoningSicknessCleared;
// debug tracking variables
var name m_mergeGroupMoveVizStage;
////////////////////////////////////////////////////////////////////////////////////////
// Group membership
native function AddUnitToGroup(int UnitID, XComGameState NewGameState);
native function RemoveUnitFromGroup(int UnitID, XComGameState NewGameState);
////////////////////////////////////////////////////////////////////////////////////////
function OnUnitDeath( StateObjectReference DeadUnit, bool bIsAIUnit )
{
if (bIsAIUnit)
{
if (m_arrMembers.Find('ObjectID', DeadUnit.ObjectID) != -1 && m_kStats.m_arrDead.Find('ObjectID', DeadUnit.ObjectID) == -1)
{
m_kStats.m_arrDead.AddItem(DeadUnit);
}
}
}
function bool GetLivingMembers(out array<int> arrMemberIDs, optional out array<XComGameState_Unit> LivingMemberStates)
{
local XComGameStateHistory History;
local XComGameState_Unit Member;
local StateObjectReference Ref;
History = `XCOMHISTORY;
foreach m_arrMembers(Ref)
{
Member = XComGameState_Unit(History.GetGameStateForObjectID(Ref.ObjectID));
if (Member != None && Member.IsAlive())
{
arrMemberIDs.AddItem(Ref.ObjectID);
LivingMemberStates.AddItem(Member);
}
}
return arrMemberIDs.Length > 0;
}
function Vector GetGroupMidpoint(optional int HistoryIndex = -1)
{
local TTile GroupMidpointTile;
local XComWorldData WorldData;
WorldData = `XWORLD;
GetUnitMidpoint(GroupMidpointTile, HistoryIndex);
return WorldData.GetPositionFromTileCoordinates(GroupMidpointTile);
}
// Get midpoint of all living members in this group.
function bool GetUnitMidpoint(out TTile Midpoint, optional int HistoryIndex = -1)
{
local XComGameStateHistory History;
local XComGameState_Unit Member;
local StateObjectReference Ref;
local TTile MinTile, MaxTile;
local bool bInited;
History = `XCOMHISTORY;
foreach m_arrMembers(Ref)
{
Member = XComGameState_Unit(History.GetGameStateForObjectID(Ref.ObjectID, , HistoryIndex));
if (Member != None && Member.IsAlive())
{
if (!bInited)
{
MinTile = Member.TileLocation;
MaxTile = Member.TileLocation;
bInited = true;
}
else
{
MinTile.X = Min(MinTile.X, Member.TileLocation.X);
MinTile.Y = Min(MinTile.Y, Member.TileLocation.Y);
MinTile.Z = Min(MinTile.Z, Member.TileLocation.Z);
MaxTile.X = Max(MaxTile.X, Member.TileLocation.X);
MaxTile.Y = Max(MaxTile.Y, Member.TileLocation.Y);
MaxTile.Z = Max(MaxTile.Z, Member.TileLocation.Z);
}
}
}
if( bInited )
{
Midpoint.X = (MinTile.X + MaxTile.X)*0.5f;
Midpoint.Y = (MinTile.Y + MaxTile.Y)*0.5f;
Midpoint.Z = (MinTile.Z + MaxTile.Z)*0.5f;
return true;
}
else
{
//Failsafe, look for any member, don't care if they are alive
foreach m_arrMembers(Ref)
{
Member = XComGameState_Unit(History.GetGameStateForObjectID(Ref.ObjectID, , HistoryIndex));
if (Member != None)
{
Midpoint = Member.TileLocation;
}
}
}
return false;
}
// Returns true if any living units are red or orange alert.
function bool IsEngaged()
{
local XComGameStateHistory History;
local XComGameState_Unit Unit;
local XComGameState_AIUnitData AIData;
local StateObjectReference Ref, KnowledgeRef;
local int AlertLevel, DataID;
History = `XCOMHISTORY;
foreach m_arrMembers(Ref)
{
Unit = XComGameState_Unit(History.GetGameStateForObjectID(Ref.ObjectID));
if( Unit != None && Unit.IsAlive() )
{
AlertLevel = Unit.GetCurrentStat(eStat_AlertLevel);
if (AlertLevel == `ALERT_LEVEL_RED)
{
return true;
}
if(AlertLevel == `ALERT_LEVEL_GREEN )
{
continue;
}
// Orange alert check.
DataID = Unit.GetAIUnitDataID();
if( DataID > 0 )
{
AIData = XComGameState_AIUnitData(History.GetGameStateForObjectID(DataID));
if( AIData.HasAbsoluteKnowledge(KnowledgeRef) )
{
return true;
}
}
}
}
return false;
}
function MarkGroupSighted(XComGameState_Unit SightingUnit, XComGameState NewGameState)
{
local Object SelfObj;
`assert(SightingUnit != none);
if(!EverSightedByEnemy)
{
EverSightedByEnemy = true;
SightedByUnitID = SightingUnit.ObjectID;
SelfObj = self;
`XEVENTMGR.TriggerEvent('EnemyGroupSighted', SelfObj, SightingUnit, NewGameState);
}
}
function float GetMaxMobility()
{
local XComGameStateHistory History;
local XComGameState_Unit Member;
local StateObjectReference Ref;
local float MaxMobility;
History = `XCOMHISTORY;
foreach m_arrMembers(Ref)
{
Member = XComGameState_Unit(History.GetGameStateForObjectID(Ref.ObjectID));
if( Member != None && Member.IsAlive() )
{
MaxMobility = Max(MaxMobility, Member.GetCurrentStat(eStat_Mobility));
}
}
return MaxMobility;
}
// Determine if this AI Group should currently be moving towards an intercept location
function bool ShouldMoveToIntercept(out Vector TargetInterceptLocation, XComGameState NewGameState, XComGameState_AIPlayerData PlayerData)
{
local XComGameState_BattleData BattleData;
local Vector CurrentGroupLocation;
local EncounterZone MyEncounterZone;
local XComAISpawnManager SpawnManager;
local XComTacticalMissionManager MissionManager;
local MissionSchedule ActiveMissionSchedule;
local array<Vector> EncounterCorners;
local int CornerIndex;
local XComGameState_AIGroup NewGroupState;
local XComGameStateHistory History;
local Vector CurrentXComLocation;
local XComWorldData World;
local TTile Tile;
World = `XWORLD;
History = `XCOMHISTORY;
BattleData = XComGameState_BattleData(History.GetSingleGameStateObjectForClass(class'XComGameState_BattleData'));
if( XComSquadMidpointPassedGroup() && !BattleData.bKismetDisabledInterceptMovement )
{
if( !GetNearestEnemyLocation(GetGroupMidpoint(), TargetInterceptLocation) )
{
// If for some reason the nearest enemy can't be found, send these units to the objective.
TargetInterceptLocation = BattleData.MapData.ObjectiveLocation;
}
return true;
}
// This flag is turned on if XCom is unengaged, and the SeqAct_CompleteMissionObjective has fired, and this is the closest group -or cheatmgr setting bAllPodsConvergeOnMissionComplete is on.
if( bInterceptObjectiveLocation )
{
TargetInterceptLocation = BattleData.MapData.ObjectiveLocation;
return true;
}
// Start Issue #507
//
// Mod override for AI patrol behavior. If the event returns `true`, then
// leave the mod to handle it and just quit out of this method.
if (TriggerOverridePatrolBehavior())
{
return false;
}
// End Issue #507
// TODO: otherwise, try to patrol around within the current encounter zone
CurrentGroupLocation = GetGroupMidpoint();
Tile = World.GetTileCoordinatesFromPosition(CurrentTargetLocation);
if( PlayerData.StatsData.TurnCount - TurnCountForLastDestination > MAX_TURNS_BETWEEN_DESTINATIONS ||
World.IsTileOutOfRange(Tile) ||
VSizeSq(CurrentGroupLocation - CurrentTargetLocation) < DESTINATION_REACHED_SIZE_SQ )
{
// choose new target location
SpawnManager = `SPAWNMGR;
MissionManager = `TACTICALMISSIONMGR;
MissionManager.GetActiveMissionSchedule(ActiveMissionSchedule);
// Start Issue #500
/// HL-Docs: ref:OverrideEncounterZoneAnchorPoint
/// This allows mods to override the LoP anchor point for the encounter zone. By
/// default, the encounter zone adjusts to the current location of the XCOM
/// squad.
///
/// As an example, a mod could use the XCOM's spawn location instead so that
/// the encounter zones remain the same regardless of where the XCOM squad is
/// currently.
CurrentXComLocation = SpawnManager.GetCurrentXComLocation();
TriggerOverrideEncounterZoneAnchorPoint(CurrentXComLocation);
// End Issue #500
MyEncounterZone = SpawnManager.BuildEncounterZone(
BattleData.MapData.ObjectiveLocation,
CurrentXComLocation,
MyEncounterZoneDepth,
MyEncounterZoneWidth,
MyEncounterZoneOffsetFromLOP,
MyEncounterZoneOffsetAlongLOP,
MyEncounterZoneVolumeTag);
EncounterCorners[0] = SpawnManager.CastVector(MyEncounterZone.Origin);
EncounterCorners[0].Z = CurrentGroupLocation.Z;
EncounterCorners[1] = EncounterCorners[0] + SpawnManager.CastVector(MyEncounterZone.SideA);
EncounterCorners[2] = EncounterCorners[1] + SpawnManager.CastVector(MyEncounterZone.SideB);
EncounterCorners[3] = EncounterCorners[0] + SpawnManager.CastVector(MyEncounterZone.SideB);
for( CornerIndex = EncounterCorners.Length - 1; CornerIndex >= 0; --CornerIndex )
{
// Start Issue #508
//
// Ensure the potential patrol locations are on-map, otherwise the alert will fail to set.
/// HL-Docs: ref:Bugfixes; issue:508
/// Patrol logic now ensures units do not attempt to patrol outside of the map which would cause them to stop patrolling
EncounterCorners[CornerIndex] = World.FindClosestValidLocation(EncounterCorners[CornerIndex], false, false);
// End Issue #508
if( VSizeSq(CurrentGroupLocation - EncounterCorners[CornerIndex]) < DESTINATION_REACHED_SIZE_SQ )
{
EncounterCorners.Remove(CornerIndex, 1);
}
}
if( EncounterCorners.Length > 0 )
{
TargetInterceptLocation = EncounterCorners[`SYNC_RAND_STATIC(EncounterCorners.Length)];
Tile = World.GetTileCoordinatesFromPosition(TargetInterceptLocation);
if (World.IsTileOutOfRange(Tile))
{
World.ClampTile(Tile);
TargetInterceptLocation = World.GetPositionFromTileCoordinates(Tile);
}
NewGroupState = XComGameState_AIGroup(NewGameState.ModifyStateObject(class'XComGameState_AIGroup', ObjectID));
NewGroupState.CurrentTargetLocation = TargetInterceptLocation;
NewGroupState.TurnCountForLastDestination = PlayerData.StatsData.TurnCount;
return true;
}
}
return false;
}
// Start Issue #500
/// HL-Docs: feature:OverrideEncounterZoneAnchorPoint; issue:500; tags:tactical
/// The `OverrideEncounterZoneAnchorPoint` event allows mods to override
/// the anchor point for determining encounter zones for patrolling pods.
///
/// X, Y and Z components of the tuple should be treated as components
/// of the Anchor Point's vector coordinates.
///
///```event
///EventID: OverrideEncounterZoneAnchorPoint,
///EventData: [inout float X, inout float Y, inout float Z],
///EventSource: XComGameState_AIGroup (AIGroup),
///NewGameState: none
///```
function TriggerOverrideEncounterZoneAnchorPoint(out Vector Anchor)
{
local XComLWTuple OverrideTuple;
OverrideTuple = new class'XComLWTuple';
OverrideTuple.Id = 'OverrideEncounterZoneAnchorPoint';
OverrideTuple.Data.Add(3);
OverrideTuple.Data[0].kind = XComLWTVFloat;
OverrideTuple.Data[0].f = Anchor.X;
OverrideTuple.Data[1].kind = XComLWTVFloat;
OverrideTuple.Data[1].f = Anchor.Y;
OverrideTuple.Data[2].kind = XComLWTVFloat;
OverrideTuple.Data[2].f = Anchor.Z;
`XEVENTMGR.TriggerEvent('OverrideEncounterZoneAnchorPoint', OverrideTuple, self);
Anchor.X = OverrideTuple.Data[0].f;
Anchor.Y = OverrideTuple.Data[1].f;
Anchor.Z = OverrideTuple.Data[2].f;
}
// End Issue #500
// Start Issue #507
/// HL-Docs: feature:OverridePatrolBehavior; issue:507; tags:tactical
/// The `OverridePatrolBehavior` event allows mods to override pods' patrol behavior.
/// The `bOverridePatrolBehavior` component of the tuple should be set to `true`
/// if the mod *is* overriding the patrol behavior and wants to bypass
/// the default base game patrol logic.
///
///```event
///EventID: OverridePatrolBehavior,
///EventData: [out bool bOverridePatrolBehavior],
///EventSource: XComGameState_AIGroup (AIGroup),
///NewGameState: none
///```
// The method returns `true` if the mod *is* overriding the patrol
// behavior and wants to bypass the default base game patrol logic.
function bool TriggerOverridePatrolBehavior()
{
local XComLWTuple OverrideTuple;
OverrideTuple = new class'XComLWTuple';
OverrideTuple.Id = 'OverridePatrolBehavior';
OverrideTuple.Data.Add(1);
OverrideTuple.Data[0].kind = XComLWTVBool;
OverrideTuple.Data[0].b = false;
`XEVENTMGR.TriggerEvent('OverridePatrolBehavior', OverrideTuple, self);
return OverrideTuple.Data[0].b;
}
// End Issue #507
// Return true if XCom units have passed our group location.
function bool XComSquadMidpointPassedGroup()
{
local vector GroupLocationToEnemy;
local vector GroupLocationToEnemyStart;
local vector GroupLocation;
local vector GroupLocationOnAxis;
local TwoVectors CurrentLineOfPlay;
local XGAIPlayer AIPlayer;
AIPlayer = XGAIPlayer(XGBattle_SP(`BATTLE).GetAIPlayer());
AIPlayer = XGAIPlayer(`BATTLE.GetAIPlayer());
AIPlayer.m_kNav.UpdateCurrentLineOfPlay(CurrentLineOfPlay);
GroupLocation = GetGroupMidpoint();
GroupLocationOnAxis = AIPlayer.m_kNav.GetNearestPointOnAxisOfPlay(GroupLocation);
GroupLocationToEnemy = CurrentLineOfPlay.v1 - GroupLocationOnAxis;
GroupLocationToEnemyStart = AIPlayer.m_kNav.m_kAxisOfPlay.v1 - GroupLocationOnAxis;
if( GroupLocationToEnemyStart dot GroupLocationToEnemy < 0 )
{
return true;
}
return false;
}
function bool GetNearestEnemyLocation(vector TargetLocation, out vector ClosestLocation)
{
local float fDistSq, fClosest;
local XComGameStateHistory History;
local XComGameState_Unit UnitState;
local int ClosestID;
local vector UnitLocation;
local XComWorldData World;
local bool EnemyUnit;
World = `XWORLD;
History = `XCOMHISTORY;
foreach History.IterateByClassType(class'XComGameState_Unit', UnitState)
{
EnemyUnit = class'XGPlayerNativeBase'.static.AreEnemyTeams( TeamName, UnitState.GetTeam() );
if( EnemyUnit && !UnitState.bRemovedFromPlay && UnitState.IsAlive() && !UnitState.IsBleedingOut() )
{
UnitLocation = World.GetPositionFromTileCoordinates(UnitState.TileLocation);
fDistSq = VSizeSq(UnitLocation - TargetLocation);
if( ClosestID <= 0 || fDistSq < fClosest )
{
ClosestID = UnitState.ObjectID;
fClosest = fDistSq;
ClosestLocation = UnitLocation;
}
}
}
if( ClosestID > 0 )
{
return true;
}
return false;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function GatherBrokenConcealmentUnits()
{
local XComGameStateHistory History;
local int EventChainStartHistoryIndex;
local XComGameState_Unit UnitState;
History = `XCOMHISTORY;
PreviouslyConcealedUnitObjectIDs.Length = 0;
EventChainStartHistoryIndex = History.GetEventChainStartIndex();
foreach History.IterateByClassType(class'XComGameState_Unit', UnitState)
{
if( !UnitState.IsConcealed() && UnitState.WasConcealed(EventChainStartHistoryIndex) )
{
PreviouslyConcealedUnitObjectIDs.AddItem(UnitState.ObjectID);
}
}
}
function bool IsWaitingOnUnitForReveal(XComGameState_Unit JustMovedUnitState)
{
return WaitingOnUnitList.Find(JustMovedUnitState.ObjectID) != INDEX_NONE;
}
function StopWaitingOnUnitForReveal(XComGameState_Unit JustMovedUnitState)
{
WaitingOnUnitList.RemoveItem(JustMovedUnitState.ObjectID);
// just removed the last impediment to performing the reveal
if( WaitingOnUnitList.Length == 0 )
{
ProcessReflexMoveActivate();
}
}
function InitiateReflexMoveActivate(XComGameState_Unit TargetUnitState, EAlertCause eCause, optional name InSpecialRevealType)
{
DelayedScamperCause = eCause;
RevealInstigatorUnitObjectID = TargetUnitState.ObjectID;
GatherBrokenConcealmentUnits();
ProcessReflexMoveActivate(InSpecialRevealType);
}
private function bool CanScamper(XComGameState_Unit UnitStateObject)
{
return UnitStateObject.IsAlive() &&
(!UnitStateObject.IsIncapacitated()) &&
UnitStateObject.bTriggerRevealAI &&
!UnitStateObject.IsPanicked() &&
!UnitStateObject.IsUnitAffectedByEffectName(class'X2AbilityTemplateManager'.default.PanickedName) &&
!UnitStateObject.IsUnitAffectedByEffectName(class'X2AbilityTemplateManager'.default.BurrowedName) &&
!UnitStateObject.IsPlayerControlled() && // Player-controlled units do not scamper.
(`CHEATMGR == None || !`CHEATMGR.bAbortScampers);
}
function ApplyAlertAbilityToGroup(EAlertCause eCause)
{
local StateObjectReference Ref;
local XComGameState_Unit UnitStateObject;
local XComGameStateHistory History;
History = `XCOMHISTORY;
foreach m_arrMembers(Ref)
{
UnitStateObject = XComGameState_Unit(History.GetGameStateForObjectID(Ref.ObjectID));
UnitStateObject.ApplyAlertAbilityForNewAlertData(eCause);
}
}
function ProcessReflexMoveActivate(optional name InSpecialRevealType)
{
local XComGameStateHistory History;
local int Index, NumScamperers, NumSurprised, i, NumActionPoints;
local XComGameState_Unit UnitStateObject, TargetStateObject, NewUnitState;
local XComGameState_AIGroup NewGroupState;
local StateObjectReference Ref;
local XGAIPlayer AIPlayer;
local XComGameState NewGameState;
local array<StateObjectReference> Scamperers;
local float SurprisedChance;
local bool bUnitIsSurprised;
local X2TacticalGameRuleset Rules;
History = `XCOMHISTORY;
if( !bProcessedScamper ) // Only allow scamper once.
{
//First, collect a list of scampering units. Due to cheats and other mechanics this list could be empty, in which case we should just skip the following logic
foreach m_arrMembers(Ref)
{
UnitStateObject = XComGameState_Unit(History.GetGameStateForObjectID(Ref.ObjectID));
if(CanScamper(UnitStateObject))
{
Scamperers.AddItem(Ref);
}
}
NumScamperers = Scamperers.Length;
if( NumScamperers > 0 )
{
//////////////////////////////////////////////////////////////
// Kick off the BT scamper actions
//Find the AI player data object
AIPlayer = XGAIPlayer(`BATTLE.GetAIPlayer());
`assert(AIPlayer != none);
TargetStateObject = XComGameState_Unit(History.GetGameStateForObjectID(RevealInstigatorUnitObjectID));
// Give the units their scamper action points
NewGameState = class'XComGameStateContext_ChangeContainer'.static.CreateChangeState("Add Scamper Action Points");
foreach Scamperers(Ref)
{
NewUnitState = XComGameState_Unit(NewGameState.ModifyStateObject(class'XComGameState_Unit', Ref.ObjectID));
if( NewUnitState.IsAbleToAct() )
{
NewUnitState.ActionPoints.Length = 0;
NumActionPoints = NewUnitState.GetNumScamperActionPoints();
for (i = 0; i < NumActionPoints; ++i)
{
NewUnitState.ActionPoints.AddItem(class'X2CharacterTemplateManager'.default.StandardActionPoint); //Give the AI one free action point to use.
}
if (NewUnitState.GetMyTemplate().OnRevealEventFn != none)
{
NewUnitState.GetMyTemplate().OnRevealEventFn(NewUnitState);
}
}
else
{
NewGameState.PurgeGameStateForObjectID(NewUnitState.ObjectID);
}
}
NewGroupState = XComGameState_AIGroup(NewGameState.ModifyStateObject(class'XComGameState_AIGroup', ObjectID));
NewGroupState.bProcessedScamper = true;
NewGroupState.bPendingScamper = true;
NewGroupState.SpecialRevealType = InSpecialRevealType;
NewGroupState.bSummoningSicknessCleared = false;
if(NewGameState.GetNumGameStateObjects() > 0)
{
// Now that we are kicking off a scamper Behavior Tree (latent), we need to handle the scamper clean-up on
// an event listener that waits until after the scampering behavior decisions are made.
for( Index = 0; Index < NumScamperers; ++Index )
{
UnitStateObject = XComGameState_Unit(History.GetGameStateForObjectID(Scamperers[Index].ObjectID));
// choose which scampering units should be surprised
// randomly choose half to be surprised
if(PreviouslyConcealedUnitObjectIDs.Length > 0)
{
if( UnitStateObject.IsGroupLeader() )
{
bUnitIsSurprised = false;
}
else
{
NumSurprised = NewGroupState.SurprisedScamperUnitIDs.Length;
SurprisedChance = (float(NumScamperers) * SURPRISED_SCAMPER_CHANCE - NumSurprised) / float(NumScamperers - Index);
bUnitIsSurprised = `SYNC_FRAND() <= SurprisedChance;
}
if(bUnitIsSurprised)
{
NewGroupState.SurprisedScamperUnitIDs.AddItem(Scamperers[Index].ObjectID);
}
}
AIPlayer.QueueScamperBehavior(UnitStateObject, TargetStateObject, bUnitIsSurprised, Index == 0);
}
// Start Issue #510
//
// Mods can't use the `OnScamperBegin` event to provide extra action points because it
// happens too late, so we fire this custom event here instead.
`XEVENTMGR.TriggerEvent('ProcessReflexMove', UnitStateObject, self, NewGameState);
// End Issue #510
Rules = `TACTICALRULES;
Rules.SubmitGameState(NewGameState);
`BEHAVIORTREEMGR.TryUpdateBTQueue();
}
else
{
History.CleanupPendingGameState(NewGameState);
}
}
}
}
function OnScamperBegin()
{
local XComGameStateHistory History;
local XComGameStateContext_RevealAI ScamperContext;
local StateObjectReference Ref;
local XComGameState_Unit UnitStateObject;
local X2GameRuleset Ruleset;
local array<int> ScamperList;
local XComGameState_Unit GroupLeaderUnitState;
local XComGameState_AIGroup AIGroupState;
History = `XCOMHISTORY;
Ruleset = `XCOMGAME.GameRuleset;
//////////////////////////////////////////////////////////////
// Reveal Begin
foreach m_arrMembers(Ref)
{
UnitStateObject = XComGameState_Unit(History.GetGameStateForObjectID(Ref.ObjectID));
if( CanScamper(UnitStateObject) )
{
ScamperList.AddItem(Ref.ObjectID);
}
}
// Prevent a red screen by only submitting this game state if we have units that are scampering.
if(ScamperList.Length > 0 )
{
ScamperContext = XComGameStateContext_RevealAI(class'XComGameStateContext_RevealAI'.static.CreateXComGameStateContext());
ScamperContext.RevealAIEvent = eRevealAIEvent_Begin;
ScamperContext.CausedRevealUnit_ObjectID = RevealInstigatorUnitObjectID;
ScamperContext.ConcealmentBrokenUnits = PreviouslyConcealedUnitObjectIDs;
ScamperContext.SurprisedScamperUnitIDs = SurprisedScamperUnitIDs;
//Mark this game state as a visualization fence (ie. we need to see whatever triggered the scamper fully before the scamper happens)
ScamperContext.SetVisualizationFence(true);
ScamperContext.RevealedUnitObjectIDs = ScamperList;
ScamperContext.SpecialRevealType = SpecialRevealType;
// determine if this is the first ever sighting of this type of enemy
GroupLeaderUnitState = GetGroupLeader();
AIGroupState = GroupLeaderUnitState.GetGroupMembership();
if (AIGroupState != None && !AIGroupState.EverSightedByEnemy)
{
ScamperContext.bDoSoldierVO = true;
}
Ruleset.SubmitGameStateContext(ScamperContext);
}
}
function XComGameState_Unit GetGroupLeader()
{
if( m_arrMembers.Length > 0 )
{
return XComGameState_Unit(`XCOMHISTORY.GetGameStateForObjectID(m_arrMembers[0].ObjectID));
}
return None;
}
function DelayedOnScamperComplete()
{
if (`XCOMGAME.GameRuleset.IsDoingLatentSubmission())
{
`BATTLE.SetTimer(0.1f, false, nameof(DelayedOnScamperComplete), self);
}
else
{
OnScamperComplete();
}
}
// After Scamper behavior trees have finished running, clean up all the scamper vars.
function OnScamperComplete()
{
local XComGameStateContext_RevealAI ScamperContext;
local XGAIPlayer AIPlayer;
local StateObjectReference Ref;
local XComGameStateContext_RevealAI AIRevealContext;
local XComGameStateContext Context;
local XComGameStateContext_Ability AbilityContext;
local Array<int> SourceObjects;
local bool PreventSimultaneousVisualization;
local XComGameStateHistory History;
History = `XCOMHISTORY;
//Find the AI player data object, and mark the reflex action state done.
AIPlayer = XGAIPlayer(`BATTLE.GetAIPlayer());
ScamperContext = XComGameStateContext_RevealAI(class'XComGameStateContext_RevealAI'.static.CreateXComGameStateContext());
ScamperContext.RevealAIEvent = eRevealAIEvent_End; // prevent from reflexing again.
foreach m_arrMembers(Ref)
{
ScamperContext.RevealedUnitObjectIDs.AddItem(Ref.ObjectID);
}
ScamperContext.CausedRevealUnit_ObjectID = RevealInstigatorUnitObjectID;
`XCOMGAME.GameRuleset.SubmitGameStateContext(ScamperContext);
PreventSimultaneousVisualization = false;
foreach History.IterateContextsByClassType(class'XComGameStateContext', Context)
{
AIRevealContext = XComGameStateContext_RevealAI(Context);
if( AIRevealContext != None && AIRevealContext.RevealAIEvent == eRevealAIEvent_Begin )
{
break;
}
AbilityContext = XComGameStateContext_Ability(Context);
if( AbilityContext != None && AbilityContext.InputContext.AbilityTemplateName != 'StandardMove' )
{
if( SourceObjects.Find(AbilityContext.InputContext.SourceObject.ObjectID) != INDEX_NONE )
{
PreventSimultaneousVisualization = true;
break;
}
SourceObjects.AddItem(AbilityContext.InputContext.SourceObject.ObjectID);
}
}
if( PreventSimultaneousVisualization )
{
foreach History.IterateContextsByClassType(class'XComGameStateContext', Context)
{
AIRevealContext = XComGameStateContext_RevealAI(Context);
if( AIRevealContext != None && AIRevealContext.RevealAIEvent == eRevealAIEvent_Begin )
{
break;
}
Context.SetVisualizationStartIndex(-1);
}
}
ClearScamperData();
AIPlayer.ClearWaitForScamper();
}
function ClearScamperData()
{
local XComGameState_AIGroup NewGroupState;
local XComGameState NewGameState;
// Mark the end of the reveal/scamper process
NewGameState = class'XComGameStateContext_ChangeContainer'.static.CreateChangeState("AIRevealComplete [" $ ObjectID $ "]");
NewGroupState = XComGameState_AIGroup(NewGameState.ModifyStateObject(class'XComGameState_AIGroup', ObjectID));
NewGroupState.DelayedScamperCause = eAC_None;
NewGroupState.RevealInstigatorUnitObjectID = INDEX_NONE;
NewGroupState.FinalVisibilityMovementStep = INDEX_NONE;
NewGroupState.WaitingOnUnitList.Length = 0;
NewGroupState.PreviouslyConcealedUnitObjectIDs.Length = 0;
NewGroupState.SurprisedScamperUnitIDs.Length = 0;
NewGroupState.SubmittingScamperReflexGameState = false;
`XCOMGAME.GameRuleset.SubmitGameState(NewGameState);
}
function bool IsFallingBack(optional out vector Destination)
{
if( bFallingBack )
{
Destination = GetFallBackDestination();
return true;
}
return false;
}
function vector GetFallBackDestination()
{
local XComGameState_AIGroup GroupState;
local vector Destination;
GroupState = XComGameState_AIGroup(`XCOMHISTORY.GetGameStateForObjectID(FallbackGroup.ObjectID));
Destination = GroupState.GetGroupMidpoint();
return Destination;
}
function bool ShouldDoFallbackYell()
{
return !bPlayedFallbackCallAnimation;
}
// Update while fallback is active. Disable fallback once XCom reaches the area.
function UpdateFallBack()
{
local array<int> LivingUnits;
local XComGameState_Unit UnitState;
local bool bDisableFallback;
local StateObjectReference AlternateGroup, TransferUnitRef;
if( bFallingBack )
{
GetLivingMembers(LivingUnits);
if( LivingUnits.Length > 0 )
{
UnitState = XComGameState_Unit(`XCOMHISTORY.GetGameStateForObjectID(LivingUnits[0]));
if( IsXComVisibleToFallbackArea() )
{
// Option A - Pick another group to fallback to, if any.
if( HasRetreatLocation(XGUnit(UnitState.GetVisualizer()), AlternateGroup) )
{
`LogAI("FALLBACK- Changing fallback-to-group since original group has already scampered.");
SetFallbackStatus(true, AlternateGroup);
return;
}
else
{
`LogAI("FALLBACK- Disabling fallback due to XCom soldiers in the fallback zone.");
bDisableFallback = true;
}
}
// Disable fallback if this unit is already in the fallback area, and XCom is already within range.
if( IsUnitInFallbackArea(UnitState) )
{
bDisableFallback = true;
TransferUnitRef = UnitState.GetReference();
}
}
else
{
`LogAI("FALLBACK- Disabling fallback due to no living units in group remaining.");
bDisableFallback = true;
}
if( bDisableFallback )
{
SetFallbackStatus(false, FallbackGroup, TransferUnitRef);
}
}
}
function bool IsUnitInFallbackArea(XComGameState_Unit Unit)
{
local vector UnitLocation;
UnitLocation = `XWORLD.GetPositionFromTileCoordinates(Unit.TileLocation);
return IsInFallbackArea(UnitLocation);
}
function bool IsInFallbackArea( vector UnitLocation )
{
local vector FallbackLocation;
FallbackLocation = GetFallBackDestination();
if( VSizeSq(UnitLocation - FallbackLocation) < Square(`METERSTOUNITS(UnitInFallbackRangeMeters) ))
{
return true;
}
return false;
}
// Once the target group has scampered, fallback should be disabled, or transferred to another group.
function bool IsXComVisibleToFallbackArea()
{
local XComGameState_AIGroup TargetGroup;
TargetGroup = XComGameState_AIGroup(`XCOMHISTORY.GetGameStateForObjectID(FallbackGroup.ObjectID));
return (TargetGroup != None && TargetGroup.bProcessedScamper);
}
// Update game state
function SetFallbackStatus(bool bFallback, optional StateObjectReference FallbackRef, optional StateObjectReference TransferUnitRef, optional XComGameState NewGameState)
{
local XComGameState_AIGroup NewGroupState, TargetGroup;
local XComGameState_AIPlayerData NewAIPlayerData;
local XGAIPlayer AIPlayer;
local XComGameStateHistory History;
local XComGameState_Unit NewUnitState, LeaderState;
local float LeaderAlert;
local bool SubmitState;
if( bFallback == bFallingBack && bHasCheckedForFallback && FallbackGroup == FallbackRef && TransferUnitRef.ObjectID <= 0)
{
// No change, early exit.
return;
}
History = `XCOMHISTORY;
if (NewGameState == none)
{
NewGameState = History.GetStartState(); // Fallback can be disabled when this group is spawned if it is a singleton.
if( NewGameState == none )
{
// Create a new gamestate to update the fallback variables.
NewGameState = class'XComGameStateContext_ChangeContainer'.static.CreateChangeState("Set Fallback Status");
SubmitState = true;
}
}
NewGroupState = XComGameState_AIGroup(NewGameState.ModifyStateObject(class'XComGameState_AIGroup', ObjectID));
NewGroupState.bHasCheckedForFallback = true;
NewGroupState.bFallingBack = bFallback;
NewGroupState.FallbackGroup = FallbackRef;
if( bFallback )
{
// Add to fallback count in AIPlayerData.
AIPlayer = XGAIPlayer(XGBattle_SP(`BATTLE).GetAIPlayer());
NewAIPlayerData = XComGameState_AIPlayerData(NewGameState.ModifyStateObject(class'XComGameState_AIPlayerData', AIPlayer.GetAIDataID()));
NewAIPlayerData.StatsData.FallbackCount++;
}
if( TransferUnitRef.ObjectID > 0 ) // If this ref exists, we want to transfer the unit to the fallback-to group.
{
`Assert(bFallback == false && FallbackRef.ObjectID > 0); // Cannot be set to fallback and have a transfer unit.
// We also want to make some changes to the unit to make him more ready to join the group.
NewUnitState = XComGameState_Unit(NewGameState.ModifyStateObject(class'XComGameState_Unit', TransferUnitRef.ObjectID));
// Unit needs to have the same unrevealed pod status.
NewUnitState.bTriggerRevealAI = true;
TargetGroup = XComGameState_AIGroup(History.GetGameStateForObjectID(FallbackRef.ObjectID));
LeaderState = XComGameState_Unit(History.GetGameStateForObjectID(TargetGroup.m_arrMembers[0].ObjectID));
LeaderAlert = LeaderState.GetCurrentStat(eStat_AlertLevel);
// Unit needs to have the same alert level as the rest of the pod.
if( NewUnitState.GetCurrentStat(eStat_AlertLevel) != LeaderAlert )
{
NewUnitState.SetCurrentStat(eStat_AlertLevel, LeaderAlert);
}
// Now to transfer the unit out of its old group and into its new group.
AIPlayer = XGAIPlayer(XGBattle_SP(`BATTLE).GetAIPlayer());
NewAIPlayerData = XComGameState_AIPlayerData(NewGameState.ModifyStateObject(class'XComGameState_AIPlayerData', AIPlayer.GetAIDataID()));
if( !NewAIPlayerData.TransferUnitToGroup(FallbackRef, TransferUnitRef, NewGameState) )
{
`RedScreen("Error in transferring fallback unit to new group. @acheng");
}
}
if( SubmitState )
{
`XCOMGAME.GameRuleset.SubmitGameState(NewGameState);
}
// If a unit was transferred, update group listings in visualizers after the gamestates are updated.
if( TransferUnitRef.ObjectID > 0 && AIPlayer != None && TargetGroup != None)
{
if( TargetGroup.m_arrMembers.Length > 0 )
{
AIPlayer.m_kNav.TransferUnitToGroup(TargetGroup.m_arrMembers[0].ObjectID, TransferUnitRef.ObjectID);
}
else
{
`RedScreen("TransferUnitGroup On Fallback failure - Target group has no units? @acheng");
}
}
}
// Do a fallback check. Check if the last living unit qualifies and roll the dice.
function CheckForFallback()
{
local array<int> LivingUnitIDs;
local bool bShouldFallback;
local float Roll;
local StateObjectReference FallbackGroupRef;
GetLivingMembers(LivingUnitIDs);
if( LivingUnitIDs.Length != 1 )
{
`RedScreen("Error - XComGameState_AIGroup::CheckForFallback living unit length does not equal 1. @acheng");
}
else
{
if( IsUnitEligibleForFallback(LivingUnitIDs[0], FallbackGroupRef) )
{
Roll = `SYNC_FRAND_STATIC();
bShouldFallback = Roll < FallbackChance;
`LogAI("FALLBACK CHECK for unit"@LivingUnitIDs[0]@"- Rolled"@Roll@"on fallback check..." @(bShouldFallback ? "Passed, falling back." : "Failed.Not falling back."));
}
else
{
`LogAI("FALLBACK CHECK for unit"@LivingUnitIDs[0]@"- Failed in check IsUnitEligibleForFallback.");
}
}
SetFallbackStatus(bShouldFallback, FallbackGroupRef);
}
function bool HasRetreatLocation(XGUnit RetreatUnit, optional out StateObjectReference RetreatGroupRef)
{
local XGAIPlayer AIPlayer;
AIPlayer = XGAIPlayer(XGBattle_SP(`BATTLE).GetAIPlayer());
return AIPlayer.HasRetreatLocation(RetreatUnit, RetreatGroupRef);
}
function bool HasHitRetreatCap()
{
local XGAIPlayer AIPlayer;
local XComGameState_AIPlayerData AIData;
AIPlayer = XGAIPlayer(XGBattle_SP(`BATTLE).GetAIPlayer());
AIData = XComGameState_AIPlayerData(`XCOMHISTORY.GetGameStateForObjectID(AIPlayer.GetAIDataID()));
if( AIData.RetreatCap < 0 ) // Unlimited retreating when retreat cap is negative.
{
return false;
}
return AIData.StatsData.FallbackCount >= AIData.RetreatCap;
}
// This sends the entire group toward a single destination.
function bool GroupMoveToPoint(vector Destination, out string FailText)
{
local array<PathingInputData> GroupPaths;
local XGUnit UnitVisualizer;
if( GetGroupMovePaths(Destination, GroupPaths, UnitVisualizer) )
{
XComTacticalController(`BATTLE.GetALocalPlayerController()).GameStateMoveUnit(UnitVisualizer, GroupPaths);
return true;
}
else
{
FailText = FailText @ GetFuncName() @ " failure.";
}
return false;
}
// this function is called to merge each StandardMove visualization as part of a group move
//
// StandardMove 0 Begin -> BeginGroupMove -> MidpointFramingCamera -> StandardMove 0 -> RemoveMidpointFramingCamera -> EndGroupMove -> StandardMove 0 End
// -> StandardMove 1 ->
// -> StandardMove N ->
//
function MergeGroupMoveVisualization(X2Action BuildTree, out X2Action VisualizationTree)
{
local XComGameStateVisualizationMgr VisMgr;
local array<X2Action> MarkerActions;
local X2Action TestMarkerAction;
local X2Action_MarkerTreeInsertBegin MarkerBeginAction;
local X2Action_MarkerTreeInsertEnd MarkerEndAction;
local X2Action_MarkerNamed GroupBeginMarkerAction, GroupEndMarkerAction, CameraReplaceAction;
local X2Action_RevealAIBegin RevealBeginAction;
local X2Action_CameraFrameAbility FramingAction;
local X2Action_CameraRemove CameraRemoveAction;
local VisualizationActionMetadata Metadata;
local XComGameStateContext Context;
local X2Action_MarkerNamed SyncAction;
local bool bScamperAlreadyFramed;
local bool bMoveIsVisible;
VisMgr = `XCOMVISUALIZATIONMGR;
m_mergeGroupMoveVizStage = 'Setup';
// grab the head and the tail of this StandardMove sequence
MarkerActions.Length = 0;
VisMgr.GetNodesOfType(BuildTree, class'X2Action_MarkerTreeInsertBegin', MarkerActions);
MarkerBeginAction = X2Action_MarkerTreeInsertBegin(MarkerActions[0]);
Metadata = MarkerBeginAction.Metadata;
Context = MarkerBeginAction.StateChangeContext;
MarkerActions.Length = 0;
VisMgr.GetNodesOfType(BuildTree, class'X2Action_MarkerTreeInsertEnd', MarkerActions);
MarkerEndAction = X2Action_MarkerTreeInsertEnd(MarkerActions[0]);
m_mergeGroupMoveVizStage = 'X2Action_CameraFollowUnit';
// as part of a group move, the camera framing actions need to be removed from this BuildTree
VisMgr.GetNodesOfType(BuildTree, class'X2Action_CameraFollowUnit', MarkerActions);
foreach MarkerActions(TestMarkerAction)
{
CameraReplaceAction = X2Action_MarkerNamed(class'X2Action_MarkerNamed'.static.CreateVisualizationAction(Context));
CameraReplaceAction.SetName("GroupMoveCameraFollowUnitReplacement");
VisMgr.ReplaceNode(CameraReplaceAction, TestMarkerAction);
}
m_mergeGroupMoveVizStage = 'X2Action_CameraFrameAbility';
VisMgr.GetNodesOfType(BuildTree, class'X2Action_CameraFrameAbility', MarkerActions);
foreach MarkerActions(TestMarkerAction)
{
CameraReplaceAction = X2Action_MarkerNamed(class'X2Action_MarkerNamed'.static.CreateVisualizationAction(Context));
CameraReplaceAction.SetName("GroupMoveCameraFrameAbilityReplacement");
VisMgr.ReplaceNode(CameraReplaceAction, TestMarkerAction);
}
m_mergeGroupMoveVizStage = 'X2Action_CameraRemove';
VisMgr.GetNodesOfType(BuildTree, class'X2Action_CameraRemove', MarkerActions);
foreach MarkerActions(TestMarkerAction)
{
CameraReplaceAction = X2Action_MarkerNamed(class'X2Action_MarkerNamed'.static.CreateVisualizationAction(Context));
CameraReplaceAction.SetName("GroupMoveCameraRemoveReplacement");
VisMgr.ReplaceNode(CameraReplaceAction, TestMarkerAction);
}
m_mergeGroupMoveVizStage = 'X2Action_StartCinescriptCamera';
VisMgr.GetNodesOfType(BuildTree, class'X2Action_StartCinescriptCamera', MarkerActions);
foreach MarkerActions(TestMarkerAction)
{
CameraReplaceAction = X2Action_MarkerNamed(class'X2Action_MarkerNamed'.static.CreateVisualizationAction(Context));
CameraReplaceAction.SetName("GroupMoveCameraStartCinescriptReplacement");
VisMgr.ReplaceNode(CameraReplaceAction, TestMarkerAction);
}
m_mergeGroupMoveVizStage = 'X2Action_EndCinescriptCamera';
VisMgr.GetNodesOfType(BuildTree, class'X2Action_EndCinescriptCamera', MarkerActions);
foreach MarkerActions(TestMarkerAction)
{
CameraReplaceAction = X2Action_MarkerNamed(class'X2Action_MarkerNamed'.static.CreateVisualizationAction(Context));
CameraReplaceAction.SetName("GroupMoveCameraEndCinescriptReplacement");
VisMgr.ReplaceNode(CameraReplaceAction, TestMarkerAction);
}
m_mergeGroupMoveVizStage = 'GroupMoveBegin-GroupMoveEnd';
// now find the existing GroupMove Begin/End nodes
MarkerActions.Length = 0;
VisMgr.GetNodesOfType(VisualizationTree, class'X2Action_MarkerNamed', MarkerActions);
foreach MarkerActions(TestMarkerAction)
{
if( X2Action_MarkerNamed(TestMarkerAction).MarkerName == 'GroupMoveBegin' )
{
GroupBeginMarkerAction = X2Action_MarkerNamed(TestMarkerAction);
}
if( X2Action_MarkerNamed(TestMarkerAction).MarkerName == 'GroupMoveEnd' )
{
GroupEndMarkerAction = X2Action_MarkerNamed(TestMarkerAction);
}
}
m_mergeGroupMoveVizStage = 'X2Action_RevealAIBegin';
//Check for whether this is part of a reveal sequence ( which has its own camera )
bScamperAlreadyFramed = false;
VisMgr.GetNodesOfType(VisualizationTree, class'X2Action_RevealAIBegin', MarkerActions);
foreach MarkerActions(TestMarkerAction)
{
RevealBeginAction = X2Action_RevealAIBegin(TestMarkerAction);
// only consider reveals that frame the scamper
if( RevealBeginAction.WantsToPlayTheLostCamera() && RevealBeginAction.CanPlayTheLostCamera() )
{
bScamperAlreadyFramed = true;
}
}
m_mergeGroupMoveVizStage = 'not bScamperAlreadyFramed';
// if there is no framed scamper, then we need to determine if any part of the move needs to be framed
bMoveIsVisible = false;
if( !bScamperAlreadyFramed )
{
VisMgr.GetNodesOfType(BuildTree, class'X2Action_Move', MarkerActions);
foreach MarkerActions(TestMarkerAction)
{
// any move action that is not a MoveTeleport is a visible move action
if( X2Action_MoveTeleport(TestMarkerAction) == none )
{
bMoveIsVisible = true;
break;
}
}
}
// the group actions haven't been built yet; build them now
if( GroupBeginMarkerAction == none )
{
m_mergeGroupMoveVizStage = 'GroupBeginMarkerAction eq none';
GroupBeginMarkerAction = X2Action_MarkerNamed(class'X2Action_MarkerNamed'.static.AddToVisualizationTree(Metadata, Context, true, MarkerBeginAction));
GroupBeginMarkerAction.SetName("GroupMoveBegin");
if ( bScamperAlreadyFramed )
{
SyncAction = X2Action_MarkerNamed(class'X2Action_MarkerNamed'.static.AddToVisualizationTree(Metadata, Context, true, GroupBeginMarkerAction));
SyncAction.SetName("SyncAction");
}
else
{
FramingAction = X2Action_CameraFrameAbility(class'X2Action_CameraFrameAbility'.static.AddToVisualizationTree(Metadata, Context, true, GroupBeginMarkerAction));
if( bMoveIsVisible )
{
FramingAction.AbilitiesToFrame.AddItem(XComGameStateContext_Ability(Context));
}
FramingAction.CameraTag = 'GroupMoveFramingCamera';
FramingAction.bFollowMovingActors = true;
}
CameraRemoveAction = X2Action_CameraRemove(class'X2Action_CameraRemove'.static.AddToVisualizationTree(Metadata, Context, true, none, MarkerEndAction.ParentActions));
CameraRemoveAction.CameraTagToRemove = 'GroupMoveFramingCamera';
GroupEndMarkerAction = X2Action_MarkerNamed(class'X2Action_MarkerNamed'.static.AddToVisualizationTree(Metadata, Context, true, CameraRemoveAction));
GroupEndMarkerAction.SetName("GroupMoveEnd");
//Merge us into the tree at large using standard merge logic - additional moves will find the above marker nodes and attach to them
XComGameStateContext_Ability(BuildTree.StateChangeContext).SuperMergeIntoVisualizationTree(BuildTree, VisualizationTree);
}
// the group actions are already present, just need to merge this tree
else
{
m_mergeGroupMoveVizStage = 'GroupBeginMarkerAction ne none';
SyncAction = X2Action_MarkerNamed(GroupBeginMarkerAction.ChildActions[0]);
if( SyncAction == none )
{
FramingAction = X2Action_CameraFrameAbility(GroupBeginMarkerAction.ChildActions[0]);
if( bMoveIsVisible )
{
FramingAction.AbilitiesToFrame.AddItem(XComGameStateContext_Ability(Context));
}
}
VisMgr.DisconnectAction(MarkerBeginAction);
VisMgr.ConnectAction(MarkerBeginAction, VisualizationTree, false, SyncAction == none ? FramingAction : SyncAction);
CameraRemoveAction = X2Action_CameraRemove(GroupEndMarkerAction.ParentActions[0]);
MarkerActions = CameraRemoveAction.ParentActions;
MarkerActions.AddItem(MarkerEndAction);
VisMgr.DisconnectAction(CameraRemoveAction);
VisMgr.ConnectAction(CameraRemoveAction, VisualizationTree, false, none, MarkerActions);
}
}
function GameStateMoveUnitCallback(XComGameState ResultState)
{
}
// This sends the specified units in the group each to specific destinations, respectively.
function bool MoveGroupMembersToPoints(array<XComGameState_Unit> Members, array<TTile> Destinations, bool bSeparateGameStates,
optional delegate<X2GameRuleset.LatentSubmitGameStateContextCallbackFn> ActivationCallback)
{
local int Index;
local array<PathingInputData> GroupPathData;
local XGUnit UnitVisualizer, LeaderVisualizer;
local PathingInputData MemberPathData;
local TTile TileDest;
local array<TTile> MemberPath, StartingTiles, ActualDestList, ExclusionList;
local array<XComGameState_Unit> MoveAbortedUnits;
local XComWorldData WorldData;
local TTile MemberDestination;
local XComGameState_Unit MemberState;
if (Destinations.Length != Members.Length)
{
`RedScreen("Destination list length does not match the number of group members! @acheng");
return false;
}
WorldData = `XWORLD;
ActualDestList.Length = 0;
// Clear all blocking, but track what tiles units started out in.
foreach Members(MemberState)
{
WorldData.ClearTileBlockedByUnitFlag(MemberState);
StartingTiles.AddItem(MemberState.TileLocation);
}
for( Index = 0; Index < Members.Length; ++Index )
{
UnitVisualizer = XGUnit(Members[Index].GetVisualizer());
MemberDestination = Destinations[Index];
MemberPath.Length = 0;
if( UnitVisualizer != None )
{
TileDest = MemberDestination;
TileDest.Z = WorldData.GetFloorTileZ(MemberDestination);
if ( !WorldData.IsFloorTile(TileDest) )
{
TileDest = MemberDestination;
}
if( !UnitVisualizer.m_kReachableTilesCache.BuildPathToTile(TileDest, MemberPath) )
{
// Update exclusion list. This includes both destinations and starting tiles of units that have not yet moved,
// and destinations of units that have moved.
ExclusionList.Length = 0;
ExclusionList = Destinations;
ExclusionList.Remove(0, Index); // Remove all destinations of units that already moved. (these are added in ActualDestList).
class'Helpers'.static.GetTileUnion(ExclusionList, StartingTiles, ActualDestList, true);
`LogAI("Unable to build a path to ("$TileDest.X@TileDest.Y@TileDest.Z$") for unit "$UnitVisualizer.ObjectID$"- Attempting alternate destination."@GetFuncName());
TileDest = UnitVisualizer.m_kReachableTilesCache.GetClosestReachableDestination(TileDest, ExclusionList);
// Abort movement on this unit if no valid closest reachable found.
if ( class'Helpers'.static.FindTileInList(TileDest, ExclusionList) != INDEX_NONE ||
!UnitVisualizer.m_kReachableTilesCache.IsTileReachable(TileDest) ||
!UnitVisualizer.m_kReachableTilesCache.BuildPathToTile(TileDest, MemberPath))
{
`LogAI("Alternate destination for unit "$UnitVisualizer.ObjectID$"- FAILURE."@GetFuncName());
// If this unit failed to move, mark this unit's actual destination as his starting location.
ActualDestList.AddItem(Members[Index].TileLocation);
StartingTiles.Remove(0, 1); // Remove the front tile.
MoveAbortedUnits.AddItem(Members[Index]);
continue;
}
else
{
`LogAI("Alternate destination for unit "$UnitVisualizer.ObjectID$"- Succeeded. Moving to ("$TileDest.X@TileDest.Y@TileDest.Z$")"@GetFuncName());
}
}
else
{
`LogAI("GroupMove Unit "$UnitVisualizer.ObjectID$" moving to ("$TileDest.X@TileDest.Y@TileDest.Z$") as expected."@GetFuncName());
}
if (LeaderVisualizer == None)
{
LeaderVisualizer = UnitVisualizer;
}
MemberPathData.MovingUnitRef = Members[Index].GetReference();
MemberPathData.MovementTiles = MemberPath;
GroupPathData.AddItem(MemberPathData);
if (bSeparateGameStates)
{
// only do passed in callback on last move
if( Index == Members.Length-1)
XComTacticalController(`BATTLE.GetALocalPlayerController()).GameStateMoveUnit(UnitVisualizer, GroupPathData, , ActivationCallback, MergeGroupMoveVisualization);
else
XComTacticalController(`BATTLE.GetALocalPlayerController()).GameStateMoveUnit(UnitVisualizer, GroupPathData, , GameStateMoveUnitCallback, MergeGroupMoveVisualization);
GroupPathData.Length = 0;
}
ActualDestList.AddItem(TileDest); // Update the exclusion list of tiles already claimed.
StartingTiles.Remove(0, 1); // Remove the front tile.
}
}
if (bSeparateGameStates)
{
// Reset blocking on any units that were supposed to move, but didn't.
foreach MoveAbortedUnits(MemberState)
{
WorldData.SetTileBlockedByUnitFlag(MemberState);
}
return true; // Already submitted each individually.
}
if( GroupPathData.Length > 0)
{
XComTacticalController(`BATTLE.GetALocalPlayerController()).GameStateMoveUnit(LeaderVisualizer, GroupPathData);
// Reset blocking on any units that were supposed to move, but didn't.
foreach MoveAbortedUnits(MemberState)
{
WorldData.SetTileBlockedByUnitFlag(MemberState);
}
return true;
}
`RedScreen(GetFuncName()@"failure with no group path data! @ACHENG");
return false;
}
function ComputeGroupPath(vector GroupDestination, array<int> LivingUnits, out array<TTile> GroupPath, out XGUnit LeaderVisualizer)
{
local XComGameStateHistory History;
local XComWorldData WorldData;
local TTile TileDest;
// get the patrol leader visualizer
History = `XCOMHISTORY;
`Assert(LivingUnits.Length > 0);
LeaderVisualizer = XGUnit(History.GetVisualizer(LivingUnits[0]));
if( LeaderVisualizer == none ) return; // couldn't find the group leader
// and attempt to have him build a path to the destination
WorldData = `XWORLD;
if( !WorldData.GetFloorTileForPosition(GroupDestination, TileDest) )
{
TileDest = WorldData.GetTileCoordinatesFromPosition(GroupDestination);
}
if( !LeaderVisualizer.m_kReachableTilesCache.BuildPathToTile(TileDest, GroupPath) )
{
TileDest = LeaderVisualizer.m_kReachableTilesCache.GetClosestReachableDestination(TileDest);
if( !LeaderVisualizer.m_kReachableTilesCache.BuildPathToTile(TileDest, GroupPath) )
{
`RedScreen("Unable to build a path to destination - "@GetFuncName()@" @ACHENG");
}
}
}
// Update me for AIGroup states.
function bool GetGroupMovePaths(vector GroupDestination, out array<PathingInputData> GroupPathData, out XGUnit LeaderVisualizerOut)
{
local XComGameStateHistory History;
local X2TacticalGameRuleset TacticalRules;
local XGUnit UnitVisualizer;
local TTile IdealTileDest, TileDest;
local PathingInputData InputData;
local int GroupProcessIndex;
local XComGameState_Unit GroupMovingUnit, LeaderState;
local GameRulesCache_Unit UnitActionsCache;
local AvailableAction kAction;
local name AbilityName;
local bool bMoveActionAvailable;
local array<TTile> ExclusionTiles, GroupPath;
local array<int> LivingUnits;
History = `XCOMHISTORY;
TacticalRules = `TACTICALRULES;
GetLivingMembers(LivingUnits);
if( LivingUnits.Length > 0 )
{
LeaderState = XComGameState_Unit(History.GetGameStateForObjectID(LivingUnits[0]));
// always start by making sure the group path has been built
ComputeGroupPath(GroupDestination, LivingUnits, GroupPath, LeaderVisualizerOut);
//Only proceed if a valid move was possible
if( GroupPath.Length > 0 )
{
//Setup the leader's input data
InputData.MovingUnitRef = LeaderState.GetReference();
InputData.MovementTiles = GroupPath;
// Add the leader's path
GroupPathData.AddItem(InputData);
// add the leader's destination so the follower's don't end up on it
ExclusionTiles.AddItem(GroupPath[GroupPath.Length - 1]);
//Here, we make the assumption that group moving units follow the leader and will choose "group move" in their behavior tree if the
//ability is available
for( GroupProcessIndex = 1; GroupProcessIndex < LivingUnits.Length; ++GroupProcessIndex )
{
GroupMovingUnit = XComGameState_Unit(History.GetGameStateForObjectID(LivingUnits[GroupProcessIndex]));
if( GroupMovingUnit == none )
{
continue; //Filter out invalid or unexpected errors in the game state or visualizers
}
UnitVisualizer = XGUnit(GroupMovingUnit.GetVisualizer());
if( UnitVisualizer == none || UnitVisualizer.m_kBehavior == none )
{
continue; //Filter out invalid or unexpected errors in the game state or visualizers
}
//Setup the follower's input data
InputData.MovingUnitRef = GroupMovingUnit.GetReference();
//Now see if this unit can move - if so, set up their path
if( TacticalRules.GetGameRulesCache_Unit(InputData.MovingUnitRef, UnitActionsCache) )
{
foreach UnitActionsCache.AvailableActions(kAction)
{
AbilityName = XComGameState_Ability(History.GetGameStateForObjectID(kAction.AbilityObjectRef.ObjectID)).GetMyTemplateName();
if( AbilityName == 'StandardMove' )
{
bMoveActionAvailable = kAction.AvailableCode == 'AA_Success';
break;
}
}
}
if( bMoveActionAvailable )
{
// We have a valid follower:
// for the followers, compute a location in formation behind the leader and have them path there
IdealTileDest = GetIdealFollowerDestinationTile(GroupMovingUnit, GroupProcessIndex, GroupPath);
TileDest = UnitVisualizer.m_kReachableTilesCache.GetClosestReachableDestination(IdealTileDest, ExclusionTiles);
InputData.MovementTiles.Length = 0; //This input structure is being reused, reset the movement tiles length
// Get closest can fail if the unit is in a bad tile.
if( !UnitVisualizer.m_kReachableTilesCache.IsTileReachable(TileDest) )
{
`RedScreen(`Location@"\nUnit cannot reach 'closest reachable tile' - likely unit is stuck in an unpathable location! \nUnit #"$UnitVisualizer.ObjectID@GroupMovingUnit.GetMyTemplateName()$" \n@Tile ("$GroupMovingUnit.TileLocation.X@GroupMovingUnit.TileLocation.Y@GroupMovingUnit.TileLocation.Z$")\n @raasland or @dburchanowski or @acheng\n\n");
}
else
{
if( !UnitVisualizer.m_kReachableTilesCache.BuildPathToTile(TileDest, InputData.MovementTiles) )
{
`RedScreen(GetFuncName()@UnitVisualizer@"(ID#"$UnitVisualizer.ObjectID$") is unable to build a path to a 'reachable tile' ("$TileDest.X@TileDest.Y@TileDest.Z$"). @Burch");
}
}
// Handle pathing failures. Force the path with only the unit start and end points, or skip movement if that end tile is occupied.
if( InputData.MovementTiles.Length < 2 )
{
if( class'Helpers'.static.FindTileInList(IdealTileDest, ExclusionTiles) == INDEX_NONE )
{
`LogAI("Invalid movement path. Forcing a fake path with unit start location and ideal tile destination.");
InputData.MovementTiles[0] = GroupMovingUnit.TileLocation;
InputData.MovementTiles[1] = IdealTileDest;
}
else if( class'Helpers'.static.FindTileInList(GroupMovingUnit.TileLocation, ExclusionTiles) == INDEX_NONE )
{
// Skip movement if the unit's current tile location is available.
`LogAI("Invalid movement path. Target destination is occupied, so skipping movement.. Not adding to group move.");
continue;
}
else
{
`RedScreen("Error - Group Move failure, potential for multiple units in one tile. No path found to ideal destination, and current tile is being moved into. @acheng");
}
}
if( InputData.MovementTiles.Length > 0 )
{
ExclusionTiles.AddItem(InputData.MovementTiles[InputData.MovementTiles.Length - 1]);
}
// Add the follower's path
GroupPathData.AddItem(InputData);
}
}
return GroupPathData.Length > 0;
}
else
{
`redscreenonce("Could not find a valid group move path for unit:"@LeaderState.ObjectID);
}
}
return false;
}
// finds the ideal destination of the given follower unit
private function TTile GetIdealFollowerDestinationTile(XComGameState_Unit Unit, int UnitIndex, array<TTile> GroupPath)
{
local XComWorldData WorldData;
local TTile PathTile0;
local TTile PathTile1;
local vector PathStartVector;
local vector PathStartRightVector;
local vector UnitLocation;
local float UnitDotPathStart;
local TTile PathEndTile;
local TTile PathOneFromEndTile;
local vector PathEndVector;
local vector UnitPlacementVector;
local int TilesBack; // how many tiles behind the leader should we try for?
//Check whether there is a valid path. If not, just return our starting tile
if( GroupPath.Length < 2 )
{
return Unit.TileLocation;
}
WorldData = `XWORLD;
// figure out which side of the pathing line we are currently standing on. We'll try to have this unit
// end up on the same side, since it looks strange and unnatural to have the units just crossing over
// the main path line for no reason. This will also leave them in relatively the same positions relative
// to the leader at the end of the move.
PathTile0 = GroupPath[0];
PathTile1 = GroupPath[1];
PathStartVector = WorldData.GetPositionFromTileCoordinates(PathTile1) - WorldData.GetPositionFromTileCoordinates(PathTile0);
PathStartRightVector = PathStartVector cross vect(0, 0, 1);
UnitLocation = WorldData.GetPositionFromTileCoordinates(Unit.TileLocation);
UnitDotPathStart = PathStartRightVector dot(UnitLocation - WorldData.GetPositionFromTileCoordinates(PathTile0));
// now decide how many tiles behind the leader this unit should go
TilesBack = (UnitIndex - 1) / 2 + 1; // first two followers go one tile behind, next two go two tiles behind, etc.
// now find our ideal destination tile. Fan out behind the leading unit using the parameters we just computed
PathEndTile = GroupPath[GroupPath.Length - 1];
PathOneFromEndTile = GroupPath[GroupPath.Length - 2];
PathEndVector = WorldData.GetPositionFromTileCoordinates(PathEndTile) - WorldData.GetPositionFromTileCoordinates(PathOneFromEndTile);
PathEndVector = Normal(PathEndVector);
// get the offset from the end of the path to the side
UnitPlacementVector = (PathEndVector cross vect(0, 0, 1)) * class'XComWorldData'.const.WORLD_StepSize * (UnitDotPathStart > 0 ? 1.0f : -1.0f);
// slide it back
UnitPlacementVector -= PathEndVector * (TilesBack * class'XComWorldData'.const.WORLD_StepSize);
// scale it up a bit to add a bit of extra potential buffer from the lead unit. Because this get quantized to a tile,
// it may or may not be enough to push us into the next tile. Which adds variety and visual interest.
UnitPlacementVector *= 1.2f;
// and offset it to the end of the path
UnitPlacementVector += WorldData.GetPositionFromTileCoordinates(PathEndTile);
// now figure out which tile that places us in
return WorldData.GetTileCoordinatesFromPosition(UnitPlacementVector);
}
function bool IsUnitEligibleForFallback(int UnitID, optional out StateObjectReference RetreatGroupRef)
{
local XComGameState_Unit UnitState;
local array<StateObjectReference> Overwatchers;
UnitState = XComGameState_Unit(`XCOMHISTORY.GetGameStateForObjectID(UnitID));
if( !HasRetreatLocation(XGUnit(UnitState.GetVisualizer()), RetreatGroupRef) )
{
return false;
}
`LogAI("Found fallback group for unit"@UnitID@"at group ID#"$RetreatGroupRef.ObjectID);
if( UnitState != None )
{
if( FallbackExclusionList.Find(UnitState.GetMyTemplateName()) != INDEX_NONE )
{
`LogAI("Fallback failure: Ineligible for unit type: "$UnitState.GetMyTemplateName());
return false;
}
}
// Check if the number of overwatchers prevents fallback.
class'X2TacticalVisibilityHelpers'.static.GetOverwatchingEnemiesOfTarget(UnitID, Overwatchers);
if( Overwatchers.Length > FallbackMaximumOverwatchCount )
{
`LogAI("Fallback failure: Exceeded maximum overwatch count. Overwatcher count ="@Overwatchers.Length);
return false;
}
// Check if under suppression.
if( UnitState.IsUnitAffectedByEffectName(class'X2Effect_Suppression'.default.EffectName) )
{
`LogAI("Fallback failure: Unit is being suppressed.");
return false;
}
// Retreat cap - total number of retreats in this mission has reached the retreat cap (specified in AIPlayerData).
if( HasHitRetreatCap() )
{
`LogAI("Fallback failure: Reached retreat cap!");
return false;
}
return true;
}
function bool AIBTFindAbility(string AbilityName, bool bRefreshAbilityCache=false, optional out XGAIBehavior MemberBehavior)
{
local AvailableAction kAbility;
local string strError;
local array<int> GroupUnitIDs;
local int UnitID;
local XGUnit MemberUnit;
local XComGameStateHistory History;
History = `XCOMHISTORY;
if (GetLivingMembers(GroupUnitIDs))
{
foreach GroupUnitIDs(UnitID)
{
MemberUnit = XGUnit(History.GetVisualizer(UnitID));
if (MemberUnit != None && MemberUnit.m_kBehavior != None)
{
MemberBehavior = MemberUnit.m_kBehavior;
if ( bRefreshAbilityCache )
{
MemberBehavior.RefreshUnitCache();
}
kAbility = MemberBehavior.GetAvailableAbility(AbilityName, , strError);
if (kAbility.AbilityObjectRef.ObjectID > 0)
{
`LogAIBT("GroupState::FindAbility succeeded with unit# "$UnitID);
return true;
}
`LogAIBT("Unit# "$UnitID@ ":"$strError);
}
}
}
return false;
}
defaultproperties
{
bTacticalTransient=true
RevealInstigatorUnitObjectID = -1
FinalVisibilityMovementStep = -1
TurnCountForLastDestination = -100
FallbackMaximumOverwatchCount = 1;
}
| 1 | 0.936824 | 1 | 0.936824 | game-dev | MEDIA | 0.962193 | game-dev | 0.743387 | 1 | 0.743387 |
Geant4/geant4 | 3,979 | examples/extended/optical/wls/wls.cc | //
// ********************************************************************
// * License and Disclaimer *
// * *
// * The Geant4 software is copyright of the Copyright Holders of *
// * the Geant4 Collaboration. It is provided under the terms and *
// * conditions of the Geant4 Software License, included in the file *
// * LICENSE and available at http://cern.ch/geant4/license . These *
// * include a list of copyright holders. *
// * *
// * Neither the authors of this software system, nor their employing *
// * institutes,nor the agencies providing financial support for this *
// * work make any representation or warranty, express or implied, *
// * regarding this software system or assume any liability for its *
// * use. Please see the license in the file LICENSE and URL above *
// * for the full disclaimer and the limitation of liability. *
// * *
// * This code implementation is the result of the scientific and *
// * technical work of the GEANT4 collaboration. *
// * By using, copying, modifying or distributing the software (or *
// * any work based on the software) you agree to acknowledge its *
// * use in resulting scientific publications, and indicate your *
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
//
/// \file optical/wls/wls.cc
/// \brief Main program of the optical/wls example
//
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
#include "FTFP_BERT.hh"
#include "WLSActionInitialization.hh"
#include "WLSDetectorConstruction.hh"
#include "G4EmStandardPhysics_option4.hh"
#include "G4OpticalPhysics.hh"
#include "G4RunManagerFactory.hh"
#include "G4Types.hh"
#include "G4UIExecutive.hh"
#include "G4UImanager.hh"
#include "G4VisExecutive.hh"
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
int main(int argc, char** argv)
{
// Instantiate G4UIExecutive if interactive mode
G4UIExecutive* ui = nullptr;
if (argc == 1) {
ui = new G4UIExecutive(argc, argv);
}
auto runManager = G4RunManagerFactory::CreateRunManager();
G4int seed = 123;
if (argc > 2) seed = atoi(argv[argc - 1]);
// Choose the Random engine and set the seed
// G4Random::setTheEngine(new CLHEP::RanecuEngine);
G4Random::setTheSeed(seed);
// Detector construction
auto detector = new WLSDetectorConstruction();
runManager->SetUserInitialization(detector);
// Physics list
G4VModularPhysicsList* physicsList = new FTFP_BERT;
physicsList->ReplacePhysics(new G4EmStandardPhysics_option4());
auto opticalPhysics = new G4OpticalPhysics();
auto opticalParams = G4OpticalParameters::Instance();
opticalParams->SetBoundaryInvokeSD(true);
physicsList->RegisterPhysics(opticalPhysics);
runManager->SetUserInitialization(physicsList);
// User action initialization
runManager->SetUserInitialization(new WLSActionInitialization(detector));
// Initialize visualization
G4VisManager* visManager = new G4VisExecutive;
visManager->Initialize();
// Get the pointer to the User Interface manager
G4UImanager* UImanager = G4UImanager::GetUIpointer();
if (ui) {
// Define (G)UI terminal for interactive mode
if (ui->IsGUI()) UImanager->ApplyCommand("/control/execute gui.mac");
ui->SessionStart();
delete ui;
}
else {
G4String command = "/control/execute ";
G4String fileName = argv[1];
UImanager->ApplyCommand(command + fileName);
}
// job termination
delete visManager;
delete runManager;
return 0;
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
| 1 | 0.695035 | 1 | 0.695035 | game-dev | MEDIA | 0.587456 | game-dev | 0.809224 | 1 | 0.809224 |
Therealsxlar/4.2-Gameserver | 9,570 | 4.2-Gameserver/SDK/SDK/Fortnite_M_Avg_Player_MenusScreen_AnimBP_parameters.hpp | #pragma once
// Dumped with Dumper-7!
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
#include "../SDK.hpp"
namespace SDK
{
namespace Params
{
//---------------------------------------------------------------------------------------------------------------------
// PARAMETERS
//---------------------------------------------------------------------------------------------------------------------
// 0x0 (0x0 - 0x0)
// Function Fortnite_M_Avg_Player_MenusScreen_AnimBP.Fortnite_M_Avg_Player_MenusScreen_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Fortnite_M_Avg_Player_MenusScreen_AnimBP_AnimGraphNode_TransitionResult_9B548FD24DD8CA302DBE0493C9C73F98
struct UFortnite_M_Avg_Player_MenusScreen_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Fortnite_M_Avg_Player_MenusScreen_AnimBP_AnimGraphNode_TransitionResult_9B548FD24DD8CA302DBE0493C9C73F98_Params
{
public:
};
// 0x0 (0x0 - 0x0)
// Function Fortnite_M_Avg_Player_MenusScreen_AnimBP.Fortnite_M_Avg_Player_MenusScreen_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Fortnite_M_Avg_Player_MenusScreen_AnimBP_AnimGraphNode_BlendListByInt_646F5CD042D0A5ED4317CA9FB189AF7D
struct UFortnite_M_Avg_Player_MenusScreen_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Fortnite_M_Avg_Player_MenusScreen_AnimBP_AnimGraphNode_BlendListByInt_646F5CD042D0A5ED4317CA9FB189AF7D_Params
{
public:
};
// 0x0 (0x0 - 0x0)
// Function Fortnite_M_Avg_Player_MenusScreen_AnimBP.Fortnite_M_Avg_Player_MenusScreen_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Fortnite_M_Avg_Player_MenusScreen_AnimBP_AnimGraphNode_TransitionResult_D53EBE274630FE146FC57C9C40922FA4
struct UFortnite_M_Avg_Player_MenusScreen_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Fortnite_M_Avg_Player_MenusScreen_AnimBP_AnimGraphNode_TransitionResult_D53EBE274630FE146FC57C9C40922FA4_Params
{
public:
};
// 0x0 (0x0 - 0x0)
// Function Fortnite_M_Avg_Player_MenusScreen_AnimBP.Fortnite_M_Avg_Player_MenusScreen_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Fortnite_M_Avg_Player_MenusScreen_AnimBP_AnimGraphNode_TransitionResult_DD721A434BAE1DC3B4791ABEF2973E96
struct UFortnite_M_Avg_Player_MenusScreen_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Fortnite_M_Avg_Player_MenusScreen_AnimBP_AnimGraphNode_TransitionResult_DD721A434BAE1DC3B4791ABEF2973E96_Params
{
public:
};
// 0x0 (0x0 - 0x0)
// Function Fortnite_M_Avg_Player_MenusScreen_AnimBP.Fortnite_M_Avg_Player_MenusScreen_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Fortnite_M_Avg_Player_MenusScreen_AnimBP_AnimGraphNode_TransitionResult_F1DB3E5A42B9996B6785308036E85FAE
struct UFortnite_M_Avg_Player_MenusScreen_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Fortnite_M_Avg_Player_MenusScreen_AnimBP_AnimGraphNode_TransitionResult_F1DB3E5A42B9996B6785308036E85FAE_Params
{
public:
};
// 0x0 (0x0 - 0x0)
// Function Fortnite_M_Avg_Player_MenusScreen_AnimBP.Fortnite_M_Avg_Player_MenusScreen_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Fortnite_M_Avg_Player_MenusScreen_AnimBP_AnimGraphNode_TransitionResult_863AEA3C426E5A0975CC67A91E44BA76
struct UFortnite_M_Avg_Player_MenusScreen_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Fortnite_M_Avg_Player_MenusScreen_AnimBP_AnimGraphNode_TransitionResult_863AEA3C426E5A0975CC67A91E44BA76_Params
{
public:
};
// 0x0 (0x0 - 0x0)
// Function Fortnite_M_Avg_Player_MenusScreen_AnimBP.Fortnite_M_Avg_Player_MenusScreen_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Fortnite_M_Avg_Player_MenusScreen_AnimBP_AnimGraphNode_TransitionResult_53B8C117420CB0F1D06CF7BB2D0F611F
struct UFortnite_M_Avg_Player_MenusScreen_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Fortnite_M_Avg_Player_MenusScreen_AnimBP_AnimGraphNode_TransitionResult_53B8C117420CB0F1D06CF7BB2D0F611F_Params
{
public:
};
// 0x0 (0x0 - 0x0)
// Function Fortnite_M_Avg_Player_MenusScreen_AnimBP.Fortnite_M_Avg_Player_MenusScreen_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Fortnite_M_Avg_Player_MenusScreen_AnimBP_AnimGraphNode_TransitionResult_63200C884B8BFFB1AB40C7BA4AE4764A
struct UFortnite_M_Avg_Player_MenusScreen_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Fortnite_M_Avg_Player_MenusScreen_AnimBP_AnimGraphNode_TransitionResult_63200C884B8BFFB1AB40C7BA4AE4764A_Params
{
public:
};
// 0x0 (0x0 - 0x0)
// Function Fortnite_M_Avg_Player_MenusScreen_AnimBP.Fortnite_M_Avg_Player_MenusScreen_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Fortnite_M_Avg_Player_MenusScreen_AnimBP_AnimGraphNode_TransitionResult_FCD8E69443C0A585805514BA49F1D848
struct UFortnite_M_Avg_Player_MenusScreen_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Fortnite_M_Avg_Player_MenusScreen_AnimBP_AnimGraphNode_TransitionResult_FCD8E69443C0A585805514BA49F1D848_Params
{
public:
};
// 0x4 (0x4 - 0x0)
// Function Fortnite_M_Avg_Player_MenusScreen_AnimBP.Fortnite_M_Avg_Player_MenusScreen_AnimBP_C.BlueprintUpdateAnimation
struct UFortnite_M_Avg_Player_MenusScreen_AnimBP_C_BlueprintUpdateAnimation_Params
{
public:
float DeltaTimeX; // 0x0(0x4)(BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
};
// 0x40 (0x40 - 0x0)
// Function Fortnite_M_Avg_Player_MenusScreen_AnimBP.Fortnite_M_Avg_Player_MenusScreen_AnimBP_C.ExecuteUbergraph_Fortnite_M_Avg_Player_MenusScreen_AnimBP
struct UFortnite_M_Avg_Player_MenusScreen_AnimBP_C_ExecuteUbergraph_Fortnite_M_Avg_Player_MenusScreen_AnimBP_Params
{
public:
int32 EntryPoint; // 0x0(0x4)(BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
float CallFunc_GetInstanceAssetPlayerTimeFromEnd_ReturnValue; // 0x4(0x4)(ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
float CallFunc_GetInstanceAssetPlayerTimeFromEnd_ReturnValue1; // 0x8(0x4)(ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
bool CallFunc_Less_FloatFloat_ReturnValue; // 0xC(0x1)(ZeroConstructor, IsPlainOldData, NoDestructor)
bool CallFunc_Less_FloatFloat_ReturnValue1; // 0xD(0x1)(ZeroConstructor, IsPlainOldData, NoDestructor)
uint8 Pad_3233[0x2]; // Fixing Size After Last Property [ Dumper-7 ]
float CallFunc_GetInstanceAssetPlayerTimeFromEnd_ReturnValue2; // 0x10(0x4)(ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
float CallFunc_GetInstanceAssetPlayerTimeFromEnd_ReturnValue3; // 0x14(0x4)(ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
bool CallFunc_Less_FloatFloat_ReturnValue2; // 0x18(0x1)(ZeroConstructor, IsPlainOldData, NoDestructor)
bool CallFunc_Less_FloatFloat_ReturnValue3; // 0x19(0x1)(ZeroConstructor, IsPlainOldData, NoDestructor)
uint8 Pad_3234[0x2]; // Fixing Size After Last Property [ Dumper-7 ]
float CallFunc_GetInstanceAssetPlayerTimeFromEnd_ReturnValue4; // 0x1C(0x4)(ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
bool CallFunc_Less_FloatFloat_ReturnValue4; // 0x20(0x1)(ZeroConstructor, IsPlainOldData, NoDestructor)
uint8 Pad_3235[0x3]; // Fixing Size After Last Property [ Dumper-7 ]
float CallFunc_GetInstanceAssetPlayerTimeFromEnd_ReturnValue5; // 0x24(0x4)(ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
bool CallFunc_Less_FloatFloat_ReturnValue5; // 0x28(0x1)(ZeroConstructor, IsPlainOldData, NoDestructor)
uint8 Pad_3236[0x3]; // Fixing Size After Last Property [ Dumper-7 ]
float CallFunc_GetInstanceAssetPlayerTimeFromEnd_ReturnValue6; // 0x2C(0x4)(ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
bool CallFunc_Less_FloatFloat_ReturnValue6; // 0x30(0x1)(ZeroConstructor, IsPlainOldData, NoDestructor)
uint8 Pad_3237[0x3]; // Fixing Size After Last Property [ Dumper-7 ]
float CallFunc_GetInstanceAssetPlayerTimeFromEnd_ReturnValue7; // 0x34(0x4)(ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
bool CallFunc_Less_FloatFloat_ReturnValue7; // 0x38(0x1)(ZeroConstructor, IsPlainOldData, NoDestructor)
uint8 Pad_3238[0x3]; // Fixing Size After Last Property [ Dumper-7 ]
float K2Node_Event_DeltaTimeX; // 0x3C(0x4)(ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
};
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 1 | 0.579216 | 1 | 0.579216 | game-dev | MEDIA | 0.950191 | game-dev | 0.771628 | 1 | 0.771628 |
AionGermany/aion-germany | 2,900 | AL-Game-5.8/data/scripts/system/handlers/quest/oriel/_18807BlessedBeThyHame.java | /**
* This file is part of Aion-Lightning <aion-lightning.org>.
*
* Aion-Lightning is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Aion-Lightning is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License
* along with Aion-Lightning.
* If not, see <http://www.gnu.org/licenses/>.
*/
package quest.oriel;
import com.aionemu.gameserver.model.DialogAction;
import com.aionemu.gameserver.model.gameobjects.player.Player;
import com.aionemu.gameserver.questEngine.handlers.QuestHandler;
import com.aionemu.gameserver.questEngine.model.QuestEnv;
import com.aionemu.gameserver.questEngine.model.QuestState;
import com.aionemu.gameserver.questEngine.model.QuestStatus;
/**
* @author zhkchi
* @reworked FrozenKiller
*/
public class _18807BlessedBeThyHame extends QuestHandler {
private static final int questId = 18807;
public _18807BlessedBeThyHame() {
super(questId);
}
@Override
public void register() {
qe.registerQuestNpc(830194).addOnQuestStart(questId);
qe.registerQuestNpc(830194).addOnTalkEvent(questId);
qe.registerQuestNpc(730524).addOnTalkEvent(questId);
}
@Override
public boolean onDialogEvent(QuestEnv env) {
final Player player = env.getPlayer();
int targetId = env.getTargetId();
DialogAction dialog = env.getDialog();
QuestState qs = player.getQuestStateList().getQuestState(questId);
if (qs == null || qs.getStatus() == QuestStatus.NONE) {
if (targetId == 830194) {
switch (dialog) {
case QUEST_SELECT:
return sendQuestDialog(env, 1011);
case QUEST_ACCEPT_SIMPLE:
return sendQuestStartDialog(env, 182213220, 1);
case QUEST_REFUSE_SIMPLE:
return closeDialogWindow(env);
default:
break;
}
}
}
else if (qs.getStatus() == QuestStatus.START) {
switch (targetId) {
case 730524: {
switch (dialog) {
case QUEST_SELECT:
return sendQuestDialog(env, 1352);
case USE_OBJECT:
changeQuestStep(env, 0, 1, false);
return false;
default:
break;
}
break;
}
case 830194: {
switch (dialog) {
case QUEST_SELECT: {
return sendQuestDialog(env, 2375);
}
case SELECT_QUEST_REWARD:
changeQuestStep(env, 1, 1, true);
return sendQuestDialog(env, 5);
default:
break;
}
}
}
}
else if (qs.getStatus() == QuestStatus.REWARD) {
if (targetId == 830194) {
return sendQuestEndDialog(env);
}
}
return false;
}
}
| 1 | 0.930973 | 1 | 0.930973 | game-dev | MEDIA | 0.968979 | game-dev | 0.977397 | 1 | 0.977397 |
Ordyns/MakeNewWay | 1,940 | Assets/Scripts/Project/ScenesLoader.cs | using UnityEngine;
using UnityEngine.SceneManagement;
public class ScenesLoader : MonoBehaviour
{
public event System.Action<int> GameLevelLoaded;
public event System.Action<int> GameLevelLoading;
public int LastLoadedLevelNumber { get; private set; }
[SerializeField] private string tutorialSceneName = "Tutorial";
[SerializeField] private string menuSceneName = "Menu";
[SerializeField] private string baseSceneName = "Base";
[SerializeField] private string levelSceneName = "Level";
private ScenesTransitions _scenesTransitions;
[Zenject.Inject]
private void Init(ScenesTransitions scenesTransitions){
_scenesTransitions = scenesTransitions;
}
public void LoadLevel(int number){
if(number == 0) number = 1;
GameLevelLoading?.Invoke(number);
AddTransition(() => {
SceneManager.LoadSceneAsync($"{levelSceneName} {number}").completed += (asyncOperation) => LevelLoaded(number);
SceneManager.LoadSceneAsync(baseSceneName, LoadSceneMode.Additive);
});
}
public void LoadMenu(){
LoadScene(menuSceneName);
}
public void LoadTutorial() => LoadScene(tutorialSceneName);
public void LoadNextLevel(){
LoadLevel(LastLoadedLevelNumber + 1);
}
private void LoadScene(string name){
AddTransition(() => {
SceneManager.LoadSceneAsync(name).completed += (asyncOperation) => CloseTransition();
});
}
public void RestartLevel(){
LoadLevel(LastLoadedLevelNumber);
}
private void LevelLoaded(int levelNumber){
LastLoadedLevelNumber = levelNumber;
GameLevelLoaded?.Invoke(levelNumber);
CloseTransition();
}
private void AddTransition(System.Action onBeginLoad) => _scenesTransitions.CreateNewTransition(onBeginLoad);
private void CloseTransition() => _scenesTransitions.CloseCurrentTransition();
} | 1 | 0.83546 | 1 | 0.83546 | game-dev | MEDIA | 0.903905 | game-dev | 0.938434 | 1 | 0.938434 |
Squashwell/bepuik | 22,572 | source/gameengine/Ketsji/KX_ObstacleSimulation.cpp | /*
* ***** BEGIN GPL LICENSE BLOCK *****
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* Contributor(s): none yet.
*
* ***** END GPL LICENSE BLOCK *****
*/
/** \file gameengine/Ketsji/KX_ObstacleSimulation.cpp
* \ingroup ketsji
*
* Simulation for obstacle avoidance behavior
*/
#include "KX_ObstacleSimulation.h"
#include "KX_NavMeshObject.h"
#include "KX_PythonInit.h"
#include "DNA_object_types.h"
#include "BLI_math.h"
namespace
{
inline float perp(const MT_Vector2& a, const MT_Vector2& b) { return a.x()*b.y() - a.y()*b.x(); }
inline float sqr(float x) { return x * x; }
inline float lerp(float a, float b, float t) { return a + (b - a) * t; }
inline float clamp(float a, float mn, float mx) { return a < mn ? mn : (a > mx ? mx : a); }
inline void vset(float v[2], float x, float y) { v[0] = x; v[1] = y; }
}
/* grr, seems moto provides no nice way to do this */
#define MT_3D_AS_2D(v) MT_Vector2((v)[0], (v)[1])
static int sweepCircleCircle(
const MT_Vector2 &pos0, const MT_Scalar r0, const MT_Vector2 &v,
const MT_Vector2 &pos1, const MT_Scalar r1,
float& tmin, float& tmax)
{
static const float EPS = 0.0001f;
MT_Vector2 c0(pos0.x(), pos0.y());
MT_Vector2 c1(pos1.x(), pos1.y());
MT_Vector2 s = c1 - c0;
MT_Scalar r = r0+r1;
float c = s.length2() - r*r;
float a = v.length2();
if (a < EPS) return 0; // not moving
// Overlap, calc time to exit.
float b = MT_dot(v,s);
float d = b*b - a*c;
if (d < 0.0f) return 0; // no intersection.
tmin = (b - sqrtf(d)) / a;
tmax = (b + sqrtf(d)) / a;
return 1;
}
static int sweepCircleSegment(
const MT_Vector2 &pos0, const MT_Scalar r0, const MT_Vector2 &v,
const MT_Vector2& pa, const MT_Vector2 &pb, const MT_Scalar sr,
float& tmin, float &tmax)
{
// equation parameters
MT_Vector2 c0(pos0.x(), pos0.y());
MT_Vector2 sa(pa.x(), pa.y());
MT_Vector2 sb(pb.x(), pb.y());
MT_Vector2 L = sb-sa;
MT_Vector2 H = c0-sa;
MT_Scalar radius = r0+sr;
float l2 = L.length2();
float r2 = radius * radius;
float dl = perp(v, L);
float hl = perp(H, L);
float a = dl * dl;
float b = 2.0f * hl * dl;
float c = hl * hl - (r2 * l2);
float d = (b*b) - (4.0f * a * c);
// infinite line missed by infinite ray.
if (d < 0.0f)
return 0;
d = sqrtf(d);
tmin = (-b - d) / (2.0f * a);
tmax = (-b + d) / (2.0f * a);
// line missed by ray range.
/* if (tmax < 0.0f || tmin > 1.0f)
return 0;*/
// find what part of the ray was collided.
MT_Vector2 Pedge;
Pedge = c0+v*tmin;
H = Pedge - sa;
float e0 = MT_dot(H, L) / l2;
Pedge = c0 + v*tmax;
H = Pedge - sa;
float e1 = MT_dot(H, L) / l2;
if (e0 < 0.0f || e1 < 0.0f)
{
float ctmin, ctmax;
if (sweepCircleCircle(pos0, r0, v, pa, sr, ctmin, ctmax))
{
if (e0 < 0.0f && ctmin > tmin)
tmin = ctmin;
if (e1 < 0.0f && ctmax < tmax)
tmax = ctmax;
}
else
{
return 0;
}
}
if (e0 > 1.0f || e1 > 1.0f)
{
float ctmin, ctmax;
if (sweepCircleCircle(pos0, r0, v, pb, sr, ctmin, ctmax))
{
if (e0 > 1.0f && ctmin > tmin)
tmin = ctmin;
if (e1 > 1.0f && ctmax < tmax)
tmax = ctmax;
}
else
{
return 0;
}
}
return 1;
}
static bool inBetweenAngle(float a, float amin, float amax, float& t)
{
if (amax < amin) amax += (float)M_PI*2;
if (a < amin-(float)M_PI) a += (float)M_PI*2;
if (a > amin+(float)M_PI) a -= (float)M_PI*2;
if (a >= amin && a < amax)
{
t = (a-amin) / (amax-amin);
return true;
}
return false;
}
static float interpolateToi(float a, const float* dir, const float* toi, const int ntoi)
{
for (int i = 0; i < ntoi; ++i)
{
int next = (i+1) % ntoi;
float t;
if (inBetweenAngle(a, dir[i], dir[next], t))
{
return lerp(toi[i], toi[next], t);
}
}
return 0;
}
KX_ObstacleSimulation::KX_ObstacleSimulation(MT_Scalar levelHeight, bool enableVisualization)
: m_levelHeight(levelHeight)
, m_enableVisualization(enableVisualization)
{
}
KX_ObstacleSimulation::~KX_ObstacleSimulation()
{
for (size_t i=0; i<m_obstacles.size(); i++)
{
KX_Obstacle* obs = m_obstacles[i];
delete obs;
}
m_obstacles.clear();
}
KX_Obstacle* KX_ObstacleSimulation::CreateObstacle(KX_GameObject* gameobj)
{
KX_Obstacle* obstacle = new KX_Obstacle();
obstacle->m_gameObj = gameobj;
vset(obstacle->vel, 0,0);
vset(obstacle->pvel, 0,0);
vset(obstacle->dvel, 0,0);
vset(obstacle->nvel, 0,0);
for (int i = 0; i < VEL_HIST_SIZE; ++i)
vset(&obstacle->hvel[i*2], 0,0);
obstacle->hhead = 0;
gameobj->RegisterObstacle(this);
m_obstacles.push_back(obstacle);
return obstacle;
}
void KX_ObstacleSimulation::AddObstacleForObj(KX_GameObject* gameobj)
{
KX_Obstacle* obstacle = CreateObstacle(gameobj);
struct Object* blenderobject = gameobj->GetBlenderObject();
obstacle->m_type = KX_OBSTACLE_OBJ;
obstacle->m_shape = KX_OBSTACLE_CIRCLE;
obstacle->m_rad = blenderobject->obstacleRad;
}
void KX_ObstacleSimulation::AddObstaclesForNavMesh(KX_NavMeshObject* navmeshobj)
{
dtStatNavMesh* navmesh = navmeshobj->GetNavMesh();
if (navmesh)
{
int npoly = navmesh->getPolyCount();
for (int pi=0; pi<npoly; pi++)
{
const dtStatPoly* poly = navmesh->getPoly(pi);
for (int i = 0, j = (int)poly->nv-1; i < (int)poly->nv; j = i++)
{
if (poly->n[j]) continue;
const float* vj = navmesh->getVertex(poly->v[j]);
const float* vi = navmesh->getVertex(poly->v[i]);
KX_Obstacle* obstacle = CreateObstacle(navmeshobj);
obstacle->m_type = KX_OBSTACLE_NAV_MESH;
obstacle->m_shape = KX_OBSTACLE_SEGMENT;
obstacle->m_pos = MT_Point3(vj[0], vj[2], vj[1]);
obstacle->m_pos2 = MT_Point3(vi[0], vi[2], vi[1]);
obstacle->m_rad = 0;
}
}
}
}
void KX_ObstacleSimulation::DestroyObstacleForObj(KX_GameObject* gameobj)
{
for (size_t i=0; i<m_obstacles.size(); )
{
if (m_obstacles[i]->m_gameObj == gameobj)
{
KX_Obstacle* obstacle = m_obstacles[i];
obstacle->m_gameObj->UnregisterObstacle();
m_obstacles[i] = m_obstacles.back();
m_obstacles.pop_back();
delete obstacle;
}
else
i++;
}
}
void KX_ObstacleSimulation::UpdateObstacles()
{
for (size_t i=0; i<m_obstacles.size(); i++)
{
if (m_obstacles[i]->m_type==KX_OBSTACLE_NAV_MESH || m_obstacles[i]->m_shape==KX_OBSTACLE_SEGMENT)
continue;
KX_Obstacle* obs = m_obstacles[i];
obs->m_pos = obs->m_gameObj->NodeGetWorldPosition();
obs->vel[0] = obs->m_gameObj->GetLinearVelocity().x();
obs->vel[1] = obs->m_gameObj->GetLinearVelocity().y();
// Update velocity history and calculate perceived (average) velocity.
copy_v2_v2(&obs->hvel[obs->hhead * 2], obs->vel);
obs->hhead = (obs->hhead+1) % VEL_HIST_SIZE;
vset(obs->pvel,0,0);
for (int j = 0; j < VEL_HIST_SIZE; ++j)
add_v2_v2v2(obs->pvel, obs->pvel, &obs->hvel[j * 2]);
mul_v2_fl(obs->pvel, 1.0f / VEL_HIST_SIZE);
}
}
KX_Obstacle* KX_ObstacleSimulation::GetObstacle(KX_GameObject* gameobj)
{
for (size_t i=0; i<m_obstacles.size(); i++)
{
if (m_obstacles[i]->m_gameObj == gameobj)
return m_obstacles[i];
}
return NULL;
}
void KX_ObstacleSimulation::AdjustObstacleVelocity(KX_Obstacle* activeObst, KX_NavMeshObject* activeNavMeshObj,
MT_Vector3& velocity, MT_Scalar maxDeltaSpeed,MT_Scalar maxDeltaAngle)
{
}
void KX_ObstacleSimulation::DrawObstacles()
{
if (!m_enableVisualization)
return;
static const MT_Vector3 bluecolor(0,0,1);
static const MT_Vector3 normal(0.0, 0.0, 1.0);
static const int SECTORS_NUM = 32;
for (size_t i=0; i<m_obstacles.size(); i++)
{
if (m_obstacles[i]->m_shape==KX_OBSTACLE_SEGMENT)
{
MT_Point3 p1 = m_obstacles[i]->m_pos;
MT_Point3 p2 = m_obstacles[i]->m_pos2;
//apply world transform
if (m_obstacles[i]->m_type == KX_OBSTACLE_NAV_MESH)
{
KX_NavMeshObject* navmeshobj = static_cast<KX_NavMeshObject*>(m_obstacles[i]->m_gameObj);
p1 = navmeshobj->TransformToWorldCoords(p1);
p2 = navmeshobj->TransformToWorldCoords(p2);
}
KX_RasterizerDrawDebugLine(p1, p2, bluecolor);
}
else if (m_obstacles[i]->m_shape==KX_OBSTACLE_CIRCLE)
{
KX_RasterizerDrawDebugCircle(m_obstacles[i]->m_pos, m_obstacles[i]->m_rad, bluecolor,
normal, SECTORS_NUM);
}
}
}
static MT_Point3 nearestPointToObstacle(MT_Point3& pos ,KX_Obstacle* obstacle)
{
switch (obstacle->m_shape)
{
case KX_OBSTACLE_SEGMENT :
{
MT_Vector3 ab = obstacle->m_pos2 - obstacle->m_pos;
if (!ab.fuzzyZero())
{
const MT_Scalar dist = ab.length();
MT_Vector3 abdir = ab.normalized();
MT_Vector3 v = pos - obstacle->m_pos;
MT_Scalar proj = abdir.dot(v);
CLAMP(proj, 0, dist);
MT_Point3 res = obstacle->m_pos + abdir*proj;
return res;
}
}
case KX_OBSTACLE_CIRCLE :
default:
return obstacle->m_pos;
}
}
static bool filterObstacle(KX_Obstacle* activeObst, KX_NavMeshObject* activeNavMeshObj, KX_Obstacle* otherObst,
float levelHeight)
{
//filter obstacles by type
if ( (otherObst == activeObst) ||
(otherObst->m_type==KX_OBSTACLE_NAV_MESH && otherObst->m_gameObj!=activeNavMeshObj) )
return false;
//filter obstacles by position
MT_Point3 p = nearestPointToObstacle(activeObst->m_pos, otherObst);
if ( fabs(activeObst->m_pos.z() - p.z()) > levelHeight)
return false;
return true;
}
///////////*********TOI_rays**********/////////////////
KX_ObstacleSimulationTOI::KX_ObstacleSimulationTOI(MT_Scalar levelHeight, bool enableVisualization)
: KX_ObstacleSimulation(levelHeight, enableVisualization),
m_maxSamples(32),
m_minToi(0.0f),
m_maxToi(0.0f),
m_velWeight(1.0f),
m_curVelWeight(1.0f),
m_toiWeight(1.0f),
m_collisionWeight(1.0f)
{
}
void KX_ObstacleSimulationTOI::AdjustObstacleVelocity(KX_Obstacle* activeObst, KX_NavMeshObject* activeNavMeshObj,
MT_Vector3& velocity, MT_Scalar maxDeltaSpeed, MT_Scalar maxDeltaAngle)
{
int nobs = m_obstacles.size();
int obstidx = std::find(m_obstacles.begin(), m_obstacles.end(), activeObst) - m_obstacles.begin();
if (obstidx == nobs)
return;
vset(activeObst->dvel, velocity.x(), velocity.y());
//apply RVO
sampleRVO(activeObst, activeNavMeshObj, maxDeltaAngle);
// Fake dynamic constraint.
float dv[2];
float vel[2];
sub_v2_v2v2(dv, activeObst->nvel, activeObst->vel);
float ds = len_v2(dv);
if (ds > maxDeltaSpeed || ds<-maxDeltaSpeed)
mul_v2_fl(dv, fabs(maxDeltaSpeed / ds));
add_v2_v2v2(vel, activeObst->vel, dv);
velocity.x() = vel[0];
velocity.y() = vel[1];
}
///////////*********TOI_rays**********/////////////////
static const int AVOID_MAX_STEPS = 128;
struct TOICircle
{
TOICircle() : n(0), minToi(0), maxToi(1) {}
float toi[AVOID_MAX_STEPS]; // Time of impact (seconds)
float toie[AVOID_MAX_STEPS]; // Time of exit (seconds)
float dir[AVOID_MAX_STEPS]; // Direction (radians)
int n; // Number of samples
float minToi, maxToi; // Min/max TOI (seconds)
};
KX_ObstacleSimulationTOI_rays::KX_ObstacleSimulationTOI_rays(MT_Scalar levelHeight, bool enableVisualization):
KX_ObstacleSimulationTOI(levelHeight, enableVisualization)
{
m_maxSamples = 32;
m_minToi = 0.5f;
m_maxToi = 1.2f;
m_velWeight = 4.0f;
m_toiWeight = 1.0f;
m_collisionWeight = 100.0f;
}
void KX_ObstacleSimulationTOI_rays::sampleRVO(KX_Obstacle* activeObst, KX_NavMeshObject* activeNavMeshObj,
const float maxDeltaAngle)
{
MT_Vector2 vel(activeObst->dvel[0], activeObst->dvel[1]);
float vmax = (float) vel.length();
float odir = (float) atan2(vel.y(), vel.x());
MT_Vector2 ddir = vel;
ddir.normalize();
float bestScore = FLT_MAX;
float bestDir = odir;
float bestToi = 0;
TOICircle tc;
tc.n = m_maxSamples;
tc.minToi = m_minToi;
tc.maxToi = m_maxToi;
const int iforw = m_maxSamples/2;
const float aoff = (float)iforw / (float)m_maxSamples;
size_t nobs = m_obstacles.size();
for (int iter = 0; iter < m_maxSamples; ++iter)
{
// Calculate sample velocity
const float ndir = ((float)iter/(float)m_maxSamples) - aoff;
const float dir = odir+ndir*M_PI*2;
MT_Vector2 svel;
svel.x() = cosf(dir) * vmax;
svel.y() = sinf(dir) * vmax;
// Find min time of impact and exit amongst all obstacles.
float tmin = m_maxToi;
float tmine = 0;
for (int i = 0; i < nobs; ++i)
{
KX_Obstacle* ob = m_obstacles[i];
bool res = filterObstacle(activeObst, activeNavMeshObj, ob, m_levelHeight);
if (!res)
continue;
float htmin,htmax;
if (ob->m_shape == KX_OBSTACLE_CIRCLE)
{
MT_Vector2 vab;
if (len_v2(ob->vel) < 0.01f * 0.01f) {
// Stationary, use VO
vab = svel;
}
else
{
// Moving, use RVO
vab = 2*svel - vel - ob->vel;
}
if (!sweepCircleCircle(MT_3D_AS_2D(activeObst->m_pos), activeObst->m_rad,
vab, MT_3D_AS_2D(ob->m_pos), ob->m_rad, htmin, htmax))
{
continue;
}
}
else if (ob->m_shape == KX_OBSTACLE_SEGMENT)
{
MT_Point3 p1 = ob->m_pos;
MT_Point3 p2 = ob->m_pos2;
//apply world transform
if (ob->m_type == KX_OBSTACLE_NAV_MESH)
{
KX_NavMeshObject* navmeshobj = static_cast<KX_NavMeshObject*>(ob->m_gameObj);
p1 = navmeshobj->TransformToWorldCoords(p1);
p2 = navmeshobj->TransformToWorldCoords(p2);
}
if (!sweepCircleSegment(MT_3D_AS_2D(activeObst->m_pos), activeObst->m_rad, svel,
MT_3D_AS_2D(p1), MT_3D_AS_2D(p2), ob->m_rad, htmin, htmax))
{
continue;
}
}
else {
continue;
}
if (htmin > 0.0f)
{
// The closest obstacle is somewhere ahead of us, keep track of nearest obstacle.
if (htmin < tmin)
tmin = htmin;
}
else if (htmax > 0.0f)
{
// The agent overlaps the obstacle, keep track of first safe exit.
if (htmax > tmine)
tmine = htmax;
}
}
// Calculate sample penalties and final score.
const float apen = m_velWeight * fabsf(ndir);
const float tpen = m_toiWeight * (1.0f/(0.0001f+tmin/m_maxToi));
const float cpen = m_collisionWeight * (tmine/m_minToi)*(tmine/m_minToi);
const float score = apen + tpen + cpen;
// Update best score.
if (score < bestScore)
{
bestDir = dir;
bestToi = tmin;
bestScore = score;
}
tc.dir[iter] = dir;
tc.toi[iter] = tmin;
tc.toie[iter] = tmine;
}
if (len_v2(activeObst->vel) > 0.1f) {
// Constrain max turn rate.
float cura = atan2(activeObst->vel[1],activeObst->vel[0]);
float da = bestDir - cura;
if (da < -M_PI) da += (float)M_PI*2;
if (da > M_PI) da -= (float)M_PI*2;
if (da < -maxDeltaAngle)
{
bestDir = cura - maxDeltaAngle;
bestToi = min(bestToi, interpolateToi(bestDir, tc.dir, tc.toi, tc.n));
}
else if (da > maxDeltaAngle)
{
bestDir = cura + maxDeltaAngle;
bestToi = min(bestToi, interpolateToi(bestDir, tc.dir, tc.toi, tc.n));
}
}
// Adjust speed when time of impact is less than min TOI.
if (bestToi < m_minToi)
vmax *= bestToi/m_minToi;
// New steering velocity.
activeObst->nvel[0] = cosf(bestDir) * vmax;
activeObst->nvel[1] = sinf(bestDir) * vmax;
}
///////////********* TOI_cells**********/////////////////
static void processSamples(KX_Obstacle* activeObst, KX_NavMeshObject* activeNavMeshObj,
KX_Obstacles& obstacles, float levelHeight, const float vmax,
const float* spos, const float cs, const int nspos, float* res,
float maxToi, float velWeight, float curVelWeight, float sideWeight,
float toiWeight)
{
vset(res, 0,0);
const float ivmax = 1.0f / vmax;
float adir[2] /*, adist */;
if (normalize_v2_v2(adir, activeObst->pvel) <= 0.01f) {
zero_v2(adir);
}
float activeObstPos[2];
vset(activeObstPos, activeObst->m_pos.x(), activeObst->m_pos.y());
/* adist = vdot(adir, activeObstPos); */
float minPenalty = FLT_MAX;
for (int n = 0; n < nspos; ++n)
{
float vcand[2];
copy_v2_v2(vcand, &spos[n * 2]);
// Find min time of impact and exit amongst all obstacles.
float tmin = maxToi;
float side = 0;
int nside = 0;
for (int i = 0; i < obstacles.size(); ++i)
{
KX_Obstacle* ob = obstacles[i];
bool res = filterObstacle(activeObst, activeNavMeshObj, ob, levelHeight);
if (!res)
continue;
float htmin, htmax;
if (ob->m_shape==KX_OBSTACLE_CIRCLE)
{
float vab[2];
// Moving, use RVO
mul_v2_v2fl(vab, vcand, 2);
sub_v2_v2v2(vab, vab, activeObst->vel);
sub_v2_v2v2(vab, vab, ob->vel);
// Side
// NOTE: dp, and dv are constant over the whole calculation,
// they can be precomputed per object.
const float* pa = activeObstPos;
float pb[2];
vset(pb, ob->m_pos.x(), ob->m_pos.y());
const float orig[2] = {0, 0};
float dp[2], dv[2], np[2];
sub_v2_v2v2(dp, pb, pa);
normalize_v2(dp);
sub_v2_v2v2(dv, ob->dvel, activeObst->dvel);
/* TODO: use line_point_side_v2 */
if (area_tri_signed_v2(orig, dp, dv) < 0.01f) {
np[0] = -dp[1];
np[1] = dp[0];
}
else {
np[0] = dp[1];
np[1] = -dp[0];
}
side += clamp(min(dot_v2v2(dp, vab),
dot_v2v2(np, vab)) * 2.0f, 0.0f, 1.0f);
nside++;
if (!sweepCircleCircle(MT_3D_AS_2D(activeObst->m_pos), activeObst->m_rad,
vab, MT_3D_AS_2D(ob->m_pos), ob->m_rad, htmin, htmax))
{
continue;
}
// Handle overlapping obstacles.
if (htmin < 0.0f && htmax > 0.0f)
{
// Avoid more when overlapped.
htmin = -htmin * 0.5f;
}
}
else if (ob->m_shape == KX_OBSTACLE_SEGMENT)
{
MT_Point3 p1 = ob->m_pos;
MT_Point3 p2 = ob->m_pos2;
//apply world transform
if (ob->m_type == KX_OBSTACLE_NAV_MESH)
{
KX_NavMeshObject* navmeshobj = static_cast<KX_NavMeshObject*>(ob->m_gameObj);
p1 = navmeshobj->TransformToWorldCoords(p1);
p2 = navmeshobj->TransformToWorldCoords(p2);
}
float p[2], q[2];
vset(p, p1.x(), p1.y());
vset(q, p2.x(), p2.y());
// NOTE: the segments are assumed to come from a navmesh which is shrunken by
// the agent radius, hence the use of really small radius.
// This can be handle more efficiently by using seg-seg test instead.
// If the whole segment is to be treated as obstacle, use agent->rad instead of 0.01f!
const float r = 0.01f; // agent->rad
if (dist_squared_to_line_segment_v2(activeObstPos, p, q) < sqr(r + ob->m_rad)) {
float sdir[2], snorm[2];
sub_v2_v2v2(sdir, q, p);
snorm[0] = sdir[1];
snorm[1] = -sdir[0];
// If the velocity is pointing towards the segment, no collision.
if (dot_v2v2(snorm, vcand) < 0.0f)
continue;
// Else immediate collision.
htmin = 0.0f;
htmax = 10.0f;
}
else
{
if (!sweepCircleSegment(activeObstPos, r, vcand, p, q, ob->m_rad, htmin, htmax))
continue;
}
// Avoid less when facing walls.
htmin *= 2.0f;
}
else {
continue;
}
if (htmin >= 0.0f)
{
// The closest obstacle is somewhere ahead of us, keep track of nearest obstacle.
if (htmin < tmin)
tmin = htmin;
}
}
// Normalize side bias, to prevent it dominating too much.
if (nside)
side /= nside;
const float vpen = velWeight * (len_v2v2(vcand, activeObst->dvel) * ivmax);
const float vcpen = curVelWeight * (len_v2v2(vcand, activeObst->vel) * ivmax);
const float spen = sideWeight * side;
const float tpen = toiWeight * (1.0f/(0.1f+tmin/maxToi));
const float penalty = vpen + vcpen + spen + tpen;
if (penalty < minPenalty) {
minPenalty = penalty;
copy_v2_v2(res, vcand);
}
}
}
void KX_ObstacleSimulationTOI_cells::sampleRVO(KX_Obstacle* activeObst, KX_NavMeshObject* activeNavMeshObj,
const float maxDeltaAngle)
{
vset(activeObst->nvel, 0.f, 0.f);
float vmax = len_v2(activeObst->dvel);
float* spos = new float[2*m_maxSamples];
int nspos = 0;
if (!m_adaptive)
{
const float cvx = activeObst->dvel[0]*m_bias;
const float cvy = activeObst->dvel[1]*m_bias;
float vmax = len_v2(activeObst->dvel);
const float vrange = vmax*(1-m_bias);
const float cs = 1.0f / (float)m_sampleRadius*vrange;
for (int y = -m_sampleRadius; y <= m_sampleRadius; ++y)
{
for (int x = -m_sampleRadius; x <= m_sampleRadius; ++x)
{
if (nspos < m_maxSamples)
{
const float vx = cvx + (float)(x+0.5f)*cs;
const float vy = cvy + (float)(y+0.5f)*cs;
if (vx*vx+vy*vy > sqr(vmax+cs/2)) continue;
spos[nspos*2+0] = vx;
spos[nspos*2+1] = vy;
nspos++;
}
}
}
processSamples(activeObst, activeNavMeshObj, m_obstacles, m_levelHeight, vmax, spos, cs/2,
nspos, activeObst->nvel, m_maxToi, m_velWeight, m_curVelWeight, m_collisionWeight, m_toiWeight);
}
else
{
int rad;
float res[2];
float cs;
// First sample location.
rad = 4;
res[0] = activeObst->dvel[0]*m_bias;
res[1] = activeObst->dvel[1]*m_bias;
cs = vmax*(2-m_bias*2) / (float)(rad-1);
for (int k = 0; k < 5; ++k)
{
const float half = (rad-1)*cs*0.5f;
nspos = 0;
for (int y = 0; y < rad; ++y)
{
for (int x = 0; x < rad; ++x)
{
const float v_xy[2] = {
res[0] + x * cs - half,
res[1] + y * cs - half};
if (len_squared_v2(v_xy) > sqr(vmax + cs / 2))
continue;
copy_v2_v2(&spos[nspos * 2 + 0], v_xy);
nspos++;
}
}
processSamples(activeObst, activeNavMeshObj, m_obstacles, m_levelHeight, vmax, spos, cs/2,
nspos, res, m_maxToi, m_velWeight, m_curVelWeight, m_collisionWeight, m_toiWeight);
cs *= 0.5f;
}
copy_v2_v2(activeObst->nvel, res);
}
delete [] spos;
}
KX_ObstacleSimulationTOI_cells::KX_ObstacleSimulationTOI_cells(MT_Scalar levelHeight, bool enableVisualization)
: KX_ObstacleSimulationTOI(levelHeight, enableVisualization)
, m_bias(0.4f)
, m_adaptive(true)
, m_sampleRadius(15)
{
m_maxSamples = (m_sampleRadius*2+1)*(m_sampleRadius*2+1) + 100;
m_maxToi = 1.5f;
m_velWeight = 2.0f;
m_curVelWeight = 0.75f;
m_toiWeight = 2.5f;
m_collisionWeight = 0.75f; //side_weight
}
| 1 | 0.979612 | 1 | 0.979612 | game-dev | MEDIA | 0.935831 | game-dev | 0.999537 | 1 | 0.999537 |
lensesio/stream-reactor | 3,100 | kafka-connect-cloud-common/src/main/scala/io/lenses/streamreactor/connect/cloud/common/config/kcqlprops/PropsKeyEnum.scala | /*
* Copyright 2017-2025 Lenses.io Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.lenses.streamreactor.connect.cloud.common.config.kcqlprops
import enumeratum.Enum
import enumeratum.EnumEntry
import io.lenses.streamreactor.connect.cloud.common.config.DataStorageSettings
sealed abstract class PropsKeyEntry(override val entryName: String) extends EnumEntry
object PropsKeyEnum extends Enum[PropsKeyEntry] {
override val values: IndexedSeq[PropsKeyEntry] = findValues
case object ReadTextMode extends PropsKeyEntry("read.text.mode")
case object ReadRegex extends PropsKeyEntry("read.text.regex")
case object ReadStartTag extends PropsKeyEntry("read.text.start.tag")
case object ReadEndTag extends PropsKeyEntry("read.text.end.tag")
case object BufferSize extends PropsKeyEntry("read.text.buffer.size")
case object ReadStartLine extends PropsKeyEntry("read.text.start.line")
case object ReadEndLine extends PropsKeyEntry("read.text.end.line")
case object ReadLastEndLineMissing extends PropsKeyEntry("read.text.last.end.line.missing")
case object ReadTrimLine extends PropsKeyEntry("read.text.trim")
case object StoreEnvelope extends PropsKeyEntry(DataStorageSettings.StoreEnvelopeKey)
case object StoreEnvelopeKey extends PropsKeyEntry(DataStorageSettings.StoreKeyKey)
case object StoreEnvelopeHeaders extends PropsKeyEntry(DataStorageSettings.StoreHeadersKey)
case object StoreEnvelopeValue extends PropsKeyEntry(DataStorageSettings.StoreValueKey)
case object StoreEnvelopeMetadata extends PropsKeyEntry(DataStorageSettings.StoreMetadataKey)
case object PaddingLength extends PropsKeyEntry("padding.length")
case object PaddingCharacter extends PropsKeyEntry("padding.char")
case object PaddingSelection extends PropsKeyEntry("padding.type")
case object PartitionIncludeKeys extends PropsKeyEntry("partition.include.keys")
case object FlushSize extends PropsKeyEntry("flush.size")
case object FlushCount extends PropsKeyEntry("flush.count")
case object FlushInterval extends PropsKeyEntry("flush.interval")
// enum - copy, move, delete, tag, execute lambda trigger
case object PostProcessAction extends PropsKeyEntry("post.process.action")
case object PostProcessActionBucket extends PropsKeyEntry("post.process.action.bucket")
case object PostProcessActionPrefix extends PropsKeyEntry("post.process.action.prefix")
case object PostProcessActionRetain extends PropsKeyEntry("post.process.action.retain.dirs")
case object KeySuffix extends PropsKeyEntry("key.suffix")
}
| 1 | 0.708855 | 1 | 0.708855 | game-dev | MEDIA | 0.308555 | game-dev | 0.880264 | 1 | 0.880264 |
luoyikun/ThunderFireUXTool-UGUI | 3,030 | Assets/UXTools/Editor/Tools/UXTools/WidgetGenerator/WidgetGenerator.cs | #if UNITY_EDITOR
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEditor.Experimental.SceneManagement;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.UIElements;
namespace ThunderFireUITool
{
public static class WidgetGenerator
{
//创建UX UI前都会创建一个GameObject来挂载Component
private static GameObject CreateUIObjWithParent(string name)
{
RectTransform parent;
bool haveParent = Utils.TryGetSelectionRectTransform(out parent);
if (haveParent)
{
var obj = new GameObject(name);
obj.layer = LayerMask.NameToLayer("UI");
var rectTransform = obj.AddComponent<RectTransform>();
rectTransform.sizeDelta = new Vector2(200, 200);
obj.transform.SetParent(parent.transform);
obj.GetComponent<RectTransform>().localPosition = new Vector3(0, 0, 0);
Undo.RegisterCreatedObjectUndo(obj.gameObject, "Create" + obj.name);
return obj;
}
else
{
EditorUtility.DisplayDialog("messageBox",
EditorLocalization.GetLocalization(EditorLocalizationStorage.Def_请先选择一个父节点),
EditorLocalization.GetLocalization(EditorLocalizationStorage.Def_确定),
EditorLocalization.GetLocalization(EditorLocalizationStorage.Def_取消));
return null;
}
}
public static GameObject CreateUIObj(string name)
{
var obj = new GameObject(name);
obj.layer = LayerMask.NameToLayer("UI");
var rectTransform = obj.AddComponent<RectTransform>();
rectTransform.sizeDelta = new Vector2(100, 100);
obj.GetComponent<RectTransform>().localPosition = new Vector3(0, 0, 0);
return obj;
}
/// <summary>
///
/// </summary>
/// <param name="name"></param>
/// <param name="pos">LocalPosition</param>
/// <param name="size"></param>
/// <param name="selection"></param>
/// <returns></returns>
public static GameObject CreateUIObj(string name, Vector3 pos, Vector3 size, GameObject[] selection)
{
name = "UX" + name;
var obj = new GameObject(name);
Undo.RegisterCreatedObjectUndo(obj, "");
obj.layer = LayerMask.NameToLayer("UI");
Transform parent;
parent = FindContainerLogic.GetObjectParent(selection);
Undo.SetTransformParent(obj.transform, parent, "");
obj.transform.SetParent(parent);
var rectTransform = Undo.AddComponent<RectTransform>(obj);
rectTransform.sizeDelta = size;
obj.transform.localPosition = pos;
obj.transform.localScale = Vector3.one;
Undo.SetCurrentGroupName("Create " + name);
return obj;
}
}
}
#endif | 1 | 0.783279 | 1 | 0.783279 | game-dev | MEDIA | 0.836596 | game-dev | 0.844405 | 1 | 0.844405 |
shit-ware/IW4 | 4,677 | ui_mp/settings_quick_gtnw_@mpui_rules_health_regen.menu | {
menuDef
{
name "settings_quick_gtnw_@mpui_rules_health_regen"
rect 0 100 272 18 2 1
popup
visible 1
style 1
forecolor 1 1 1 1
focuscolor 1 1 1 1
fadeCycle 1
fadeClamp 1
fadeAmount 0.1
exp rect y ( localvarint( "ui_popupYPos" ) )
onOpen
{
focusfirst;
setfocusbydvar "scr_player_healthregentime";
setLocalVarBool "ui_hideSelectButton" ( 1 );
}
onClose
{
setLocalVarBool "ui_hideSelectButton" ( 0 );
}
onEsc
{
play "mouse_click";
close self;
}
itemDef
{
rect -600 -800 2000 2000 0 0
visible 1
forecolor 1 1 1 1
type 1
textfont 1
textscale 0.55
action
{
close self;
}
}
itemDef
{
rect 144 0 110 70 0 0
decoration
visible 1
style 3
forecolor 0.35 0.35 0.35 1
textscale 0.55
exp material ( "white" )
}
itemDef
{
rect 128 -16 16 16 2 1
decoration
visible 1
style 3
forecolor 0 0 0 1
background "drop_shadow_tl"
textscale 0.55
visible when ( 1 )
}
itemDef
{
rect 144 -16 110 16 2 1
decoration
visible 1
style 3
forecolor 0 0 0 1
background "drop_shadow_t"
textscale 0.55
visible when ( 1 )
}
itemDef
{
rect 254 -16 16 16 2 1
decoration
visible 1
style 3
forecolor 0 0 0 1
background "drop_shadow_tr"
textscale 0.55
visible when ( 1 )
}
itemDef
{
rect 254 0 16 70 2 1
decoration
visible 1
style 3
forecolor 0 0 0 1
background "drop_shadow_r"
textscale 0.55
visible when ( 1 )
}
itemDef
{
rect 254 70 16 16 2 1
decoration
visible 1
style 3
forecolor 0 0 0 1
background "drop_shadow_br"
textscale 0.55
visible when ( 1 )
}
itemDef
{
rect 144 70 110 16 2 1
decoration
visible 1
style 3
forecolor 0 0 0 1
background "drop_shadow_b"
textscale 0.55
visible when ( 1 )
}
itemDef
{
rect 128 70 16 16 2 1
decoration
visible 1
style 3
forecolor 0 0 0 1
background "drop_shadow_bl"
textscale 0.55
visible when ( 1 )
}
itemDef
{
rect 128 0 16 70 2 1
decoration
visible 1
style 3
forecolor 0 0 0 1
background "drop_shadow_l"
textscale 0.55
visible when ( 1 )
}
itemDef
{
rect 144 0 128 15 0 0
visible 1
forecolor 0.65 0.65 0.65 1
textalign 8
textalignx 12
textscale 0.375
text "@MPUI_RULES_NONE"
dvarTest "scr_player_healthregentime"
focusDvar { 0 }
visible when ( "@MPUI_RULES_NONE" != "" )
action
{
setdvar "scr_player_healthregentime" 0 play "mouse_click";
close self;
}
leaveFocus
{
play "mouse_submenu_over";
}
}
itemDef
{
rect 144 15 128 15 0 0
visible 1
forecolor 0.65 0.65 0.65 1
textalign 8
textalignx 12
textscale 0.375
text "@MPUI_RULES_FAST"
dvarTest "scr_player_healthregentime"
focusDvar { 2 }
visible when ( "@MPUI_RULES_FAST" != "" )
action
{
setdvar "scr_player_healthregentime" 2 play "mouse_click";
close self;
}
leaveFocus
{
play "mouse_submenu_over";
}
}
itemDef
{
rect 144 30 128 15 0 0
visible 1
forecolor 0.65 0.65 0.65 1
textalign 8
textalignx 12
textscale 0.375
text "@MPUI_RULES_NORMAL"
dvarTest "scr_player_healthregentime"
focusDvar { 5 }
visible when ( "@MPUI_RULES_NORMAL" != "" )
action
{
setdvar "scr_player_healthregentime" 5 play "mouse_click";
close self;
}
leaveFocus
{
play "mouse_submenu_over";
}
}
itemDef
{
rect 144 45 128 15 0 0
visible 1
forecolor 0.65 0.65 0.65 1
textalign 8
textalignx 12
textscale 0.375
text "@MPUI_RULES_SLOW"
dvarTest "scr_player_healthregentime"
focusDvar { "10" }
visible when ( "@MPUI_RULES_SLOW" != "" )
action
{
setdvar "scr_player_healthregentime" "10" play "mouse_click";
close self;
}
leaveFocus
{
play "mouse_submenu_over";
}
}
itemDef
{
rect 144 60 128 15 0 0
visible 1
forecolor 0.65 0.65 0.65 1
textalign 8
textalignx 12
textscale 0.375
dvarTest "scr_player_healthregentime"
focusDvar { 0 }
visible when ( "" != "" )
action
{
setdvar "scr_player_healthregentime" 0 play "mouse_click";
close self;
}
leaveFocus
{
play "mouse_submenu_over";
}
}
itemDef
{
rect 144 75 128 15 0 0
visible 1
forecolor 0.65 0.65 0.65 1
textalign 8
textalignx 12
textscale 0.375
dvarTest "scr_player_healthregentime"
focusDvar { 0 }
visible when ( "" != "" )
action
{
setdvar "scr_player_healthregentime" 0 play "mouse_click";
close self;
}
leaveFocus
{
play "mouse_submenu_over";
}
}
}
}
| 1 | 0.779346 | 1 | 0.779346 | game-dev | MEDIA | 0.916043 | game-dev | 0.864579 | 1 | 0.864579 |
audeering/opensmile | 10,919 | src/rnn/rnnVad2.cpp | /*F***************************************************************************
* This file is part of openSMILE.
*
* Copyright (c) audEERING GmbH. All rights reserved.
* See the file COPYING for details on license terms.
***************************************************************************E*/
/* openSMILE component:
rnnVad
Although this component is called rnnVad, it does not contain nor use an RNN.
It reads the RNN output activation, and applies some thresholds and logic to smooth it to a
stable VAD decision. For the SEMAINE system it supports VAD supression, when
then agent is talking.
*/
#include <rnn/rnnVad2.hpp>
#define MODULE "cRnnVad2"
SMILECOMPONENT_STATICS(cRnnVad2)
SMILECOMPONENT_REGCOMP(cRnnVad2)
{
SMILECOMPONENT_REGCOMP_INIT
scname = COMPONENT_NAME_CRNNVAD2;
sdescription = COMPONENT_DESCRIPTION_CRNNVAD2;
// we inherit cVectorProcessor configType and extend it:
SMILECOMPONENT_INHERIT_CONFIGTYPE("cDataProcessor")
// if the inherited config type was found, we register our configuration variables
SMILECOMPONENT_IFNOTREGAGAIN( {} // <- this is only to avoid compiler warnings...
// name append has a special role: it is defined in cDataProcessor, and can be overwritten here:
//ct->setField("nameAppend",NULL,"processed");
ct->setField("voiceIdx","The index of the field which contains the 'voice' class output activation. (0 is the first field)",0);
ct->setField("agentIdx","The index of the field which contains the 'agent/alien' class output activation. (0 is the first field)",1);
ct->setField("voiceThresh","The threshold to apply to the 'voice' output activation.",0.4);
ct->setField("agentThresh","The threshold to apply to the 'agent' output activation.",0.3);
ct->setField("energyIdx","The index of the field which contains the energy/loudness/intensity/etc. value (set to -1 to disable)",2);
ct->setField("f0Idx","Index of F0 input field (set to -1 to disable)",3);
// ct->setField("nPost","Number of silence frames after speech before silence is detected.",10);
// agent block by energy...
//ct->setField("agentBlockTime","initial user speech time during which to block agent in frames (this must be high enough in order to have robust enough models)",1000);
ct->setField("agentTurnPastBlock","time the VAD will be blocked after receiving an agent speech end message (in frames, usually 100fps) (use 20 for the SEMAINE speech2speech system, and 60 for the speech2face system).",20);
ct->setField("alwaysRejectAgent", "1 = never detect a speaker turn while the agent is speaking",0);
ct->setField("smartRejectAgent", "1 = apply different VAD strategy while agent is speaking",1);
ct->setField("userEavgHold","Hold time for user energy envelope and average computation (10ms frames as unit).",500); // 600
ct->setField("userEavgDecay","Decay (linear) time for user energy envelope and average computation (10ms frames as unit).",500); // 300
ct->setField("agentEavgHold","Hold time for user energy envelope and average computation (10ms frames as unit).",200);
ct->setField("agentEavgDecay","Decay (linear) time for user energy envelope and average computation (10ms frames as unit).",200); // 100
ct->setField("vadDebug","1 = output energy and VAD statistics for debugging (set to 2 to always force vad output value to 0 while debugging).",0);
ct->setField("allowEoverride","1 = allow VAD output even if LSTM does not detect voice when the energy is in the range of the user's current energy envelope (NOTE: this reduces noise robustness, e.g. when moving a headset etc.)",1);
/*
agent reject based on mean energy:
learning:
mean energy of user & agent
productive:
user speech turn only detected when energy >> mean agent energy ??
*/
)
// The configType gets automatically registered with the config manger by the SMILECOMPONENT_IFNOTREGAGAIN macro
// we now create out sComponentInfo, including name, description, success status, etc. and return that
SMILECOMPONENT_MAKEINFO(cRnnVad2);
}
SMILECOMPONENT_CREATE(cRnnVad2)
//-----
cRnnVad2::cRnnVad2(const char *_name) :
cDataProcessor(_name), voiceThresh(0.0), frameO(NULL),
doReset(0), agentTurn(0), userPresence(0), agentTurnCntdn(0),
eUser(NULL), eCurrent(NULL), eAgent(NULL), eBg(NULL), cnt(0)
{
}
void cRnnVad2::myFetchConfig()
{
cDataProcessor::myFetchConfig();
voiceIdx = getInt("voiceIdx");
SMILE_IDBG(2,"voiceIdx = %i",voiceIdx);
agentIdx = getInt("agentIdx");
SMILE_IDBG(2,"agentIdx = %i",agentIdx);
energyIdx = getInt("energyIdx");
SMILE_IDBG(2,"energyIdx = %i",energyIdx);
f0Idx = getInt("f0Idx");
SMILE_IDBG(2,"f0Idx = %i",f0Idx);
// nPost = getInt("nPost");
voiceThresh = (FLOAT_DMEM)getDouble("voiceThresh");
agentThresh = (FLOAT_DMEM)getDouble("agentThresh");
//agentBlockTime = getInt("agentBlockTime");
agentTurnPastBlock = getInt("agentTurnPastBlock");
smartRejectAgent = getInt("smartRejectAgent");
alwaysRejectAgent = getInt("alwaysRejectAgent");
allowEoverride = getInt("allowEoverride");
vadDebug = getInt("vadDebug");
int userEavgHold = getInt("userEavgHold");
int userEavgDecay = getInt("userEavgDecay");
int agentEavgHold = getInt("agentEavgHold");
int agentEavgDecay = getInt("agentEavgDecay");
eCurrent = new cEavgHold(20, 10); /* short-term envelope and average */
eUser = new cEavgHold(userEavgHold, userEavgDecay); /* user energy level, long term */
eAgent = new cEavgHold(agentEavgHold, agentEavgDecay); /* user energy level, long term */
eBg = new cEavgHold(1000, 1000);
}
int cRnnVad2::setupNewNames(long nEl)
{
writer_->addField("voiceAct");
namesAreSet_=1;
return 1;
}
int cRnnVad2::myFinaliseInstance()
{
int ret = cDataProcessor::myFinaliseInstance();
if (ret) {
frameO = new cVector(1);
}
return ret;
}
int cRnnVad2::processComponentMessage( cComponentMessage *_msg )
{
if (isMessageType(_msg,"semaineCallback")) {
// determine origin by message's user-defined name, which can be set in the config file
SMILE_IDBG(3,"received 'semaineCallback' message '%s'",_msg->msgname);
if (!strncmp(_msg->msgname,"start",5)) { agentTurn = 1; agentTurnCntdn = 0; }
else if (!strncmp(_msg->msgname,"end",3)) {
agentTurn = 0; agentTurnCntdn = agentTurnPastBlock;
}
else if (!strncmp(_msg->msgname,"present",7)) { if (userPresence != 1) { userPresence = 1; doReset=1; } }
else if (!strncmp(_msg->msgname,"absent",6)) { if (userPresence != 0) { userPresence = 0; doReset=1; } }
return 1; // message was processed
}
return 0; // if message was not processed
}
// a derived class should override this method, in order to implement the actual processing
eTickResult cRnnVad2::myTick(long long t)
{
if (!writer_->checkWrite(1))
return TICK_DEST_NO_SPACE;
cVector * frame = reader_->getNextFrame();
if (frame == NULL) return TICK_SOURCE_NOT_AVAIL;
cnt++;
int vad = 0;
FLOAT_DMEM E = 0.0;
FLOAT_DMEM vact = frame->data[voiceIdx];
FLOAT_DMEM aact = 0.0;
if (agentIdx >= 0) aact = frame->data[agentIdx];
/* get frame energy */
if (energyIdx >= 0) {
E = frame->data[energyIdx];
eCurrent->nextE(E);
}
/*
get the "agent's talking state" ..
*/
int _agentTurn = 0;
int noV = 0;
lockMessageMemory();
if (doReset == 1) {
doReset=0;
}
_agentTurn = agentTurn;
if ((agentTurn)||(agentTurnCntdn>0)) {
if (smartRejectAgent || alwaysRejectAgent) { noV = 1; }
//if (cnt < agentBlockTime) { noV=1; }
}
if (agentTurnCntdn > 0) agentTurnCntdn--;
unlockMessageMemory();
/* case A: we know it's the agent's turn, and we apply a different strategy for getting the user's voice */
if (noV) {
if (energyIdx >= 0 && !alwaysRejectAgent) {
if (vact > voiceThresh) {
/* energy based user voice detection with a high threshold */
/*if (eCurrent->getEnv() > eUser->getAvg()*1.2 && eCurrent->getEnv() > eAgent->getEnv()*0.9 && aact < agentThresh && eUser->getAvg() > 0.0) {
vad = 8;
} else */
if (eCurrent->getEnv() > eUser->getEnv()*0.9 && eCurrent->getEnv() > eAgent->getEnv()*0.9 && aact < agentThresh-0.1 && eUser->getEnv() > 0.0 && eAgent->getEnv() > 0.0) {
vad = 9;
} else if (eCurrent->getEnv() > eAgent->getEnv()*1.1 && aact < agentThresh+0.1 && eAgent->getEnv() > 0.0) {
vad = 10;
}
}
/* update agent energy stats */
if (vact > voiceThresh && aact > 0.1 && vad == 0 && eCurrent->getEnv() < eUser->getEnv()*0.9) {
eAgent->nextE(E);
}
}
} else {
/* case B: no agent turn, we look for user voice primarily */
if (vact > voiceThresh) {
if (energyIdx >= 0) {
if (aact <= agentThresh+0.05 && eCurrent->getEnv() > eBg->getAvg()*1.1 && eBg->getAvg() > 0.0) { /* if no agent voice is detected, update user energy stats */
eUser->nextE(E);
} /*else {
//eAgent->nextE(E);
}*/
if ((eCurrent->getEnv() > eUser->getEnv()*0.75 || vact > 0.95 || eUser->getEnv() == 0.0 || eCurrent->getEnv() == 0.0) && aact < agentThresh) { /* Energy verification, low threshold */
vad = 1;
} else {
/* energy based user voice detection with a high threshold */
if (eCurrent->getEnv() > eUser->getEnv()*0.9 && eUser->getEnv() > 0.0) {
vad = 3;
} /* else if (eCurrent->getEnv() > eUser->getEnv()*0.6 && eUser->getEnv() > 0.0) {
vad = 4;
}*/
}
} else {
vad = 5;
}
} else {
if (energyIdx >= 0) {
/* energy based user voice detection with a high threshold */
if (eCurrent->getEnv() > eUser->getEnv()*0.8 && vact > 0.3 && eUser->getEnv() > 0.0) {
vad = 6; /* higher thresh */
} else if (eCurrent->getEnv() > eUser->getEnv()*0.9 && eCurrent->getEnv() < eUser->getEnv()*1.1 && eUser->getEnv() > 0.0 && vact > 0.1) {
vad = 7;
} else {
/* update background energy model */
eBg->nextE(E);
}
}
}
}
if (vadDebug) {
printf("noV=%i vact=%.3f aact=%.3f eU=%.3f eCur=%.3f eBg=%.3f eAg=%.3f v=%i\n",noV,vact,aact,eUser->getEnv(),eCurrent->getEnv(),eBg->getEnv(),eAgent->getEnv(),vad);
}
/*
generate output frame with voicing info
*/
if (cnt < 100) vad=0; /* block vad output at the beginning, it may confuse the turnDetector otherwise */
if (vad > 0) vad = 1; /* map the internal VAD states to binary 0/1 */
if (vadDebug==2) { vad=0; } /* Disable VAD output for debugging ONLY vad functionality without other interfering components */
frameO->data[0] = (FLOAT_DMEM)(vad);
writer_->setNextFrame(frameO);
return TICK_SUCCESS;
}
cRnnVad2::~cRnnVad2()
{
if (frameO != NULL) delete frameO;
if (eCurrent != NULL) delete eCurrent;
if (eUser != NULL) delete eUser;
if (eAgent != NULL) delete eAgent;
if (eBg != NULL) delete eBg;
}
| 1 | 0.935665 | 1 | 0.935665 | game-dev | MEDIA | 0.643987 | game-dev | 0.988577 | 1 | 0.988577 |
omnigres/omnigres | 24,772 | deps/h2o/deps/mruby/src/variable.c | /*
** variable.c - mruby variables
**
** See Copyright Notice in mruby.h
*/
#include <mruby.h>
#include <mruby/array.h>
#include <mruby/class.h>
#include <mruby/proc.h>
#include <mruby/string.h>
#include <mruby/variable.h>
#include <mruby/internal.h>
#include <mruby/presym.h>
/* Instance variable table structure */
typedef struct iv_tbl {
int size, alloc;
mrb_value *ptr;
} iv_tbl;
#define IV_EMPTY 0
#define IV_DELETED (1UL<<31)
#define IV_KEY_P(k) (((k)&~((uint32_t)IV_DELETED))!=0)
/* Creates the instance variable table. */
static iv_tbl*
iv_new(mrb_state *mrb)
{
iv_tbl *t;
t = (iv_tbl*)mrb_malloc(mrb, sizeof(iv_tbl));
t->size = 0;
t->alloc = 0;
t->ptr = NULL;
return t;
}
static void iv_put(mrb_state *mrb, iv_tbl *t, mrb_sym sym, mrb_value val);
static void
iv_rehash(mrb_state *mrb, iv_tbl *t)
{
int old_alloc = t->alloc;
int new_alloc = old_alloc+4;
mrb_value *old_ptr = t->ptr;
khash_power2(new_alloc);
if (old_alloc == new_alloc) return;
t->ptr = (mrb_value*)mrb_calloc(mrb, sizeof(mrb_value)+sizeof(mrb_sym), new_alloc);
t->size = 0;
t->alloc = new_alloc;
if (old_alloc == 0) return;
mrb_sym *keys = (mrb_sym*)&old_ptr[old_alloc];
mrb_value *vals = old_ptr;
for (int i = 0; i < old_alloc; i++) {
if (IV_KEY_P(keys[i])) {
iv_put(mrb, t, keys[i], vals[i]);
}
}
mrb_free(mrb, old_ptr);
}
/* Set the value for the symbol in the instance variable table. */
static void
iv_put(mrb_state *mrb, iv_tbl *t, mrb_sym sym, mrb_value val)
{
int hash, pos, start, dpos = -1;
if (t == NULL) return;
if (t->alloc == 0) {
iv_rehash(mrb, t);
}
mrb_sym *keys = (mrb_sym*)&t->ptr[t->alloc];
mrb_value *vals = t->ptr;
hash = kh_int_hash_func(mrb, sym);
start = pos = hash & (t->alloc-1);
for (;;) {
mrb_sym key = keys[pos];
if (key == sym) {
vals[pos] = val;
return;
}
else if (key == IV_EMPTY) {
t->size++;
keys[pos] = sym;
vals[pos] = val;
return;
}
else if (key == IV_DELETED && dpos < 0) {
dpos = pos;
}
pos = (pos+1) & (t->alloc-1);
if (pos == start) { /* not found */
if (dpos >= 0) {
t->size++;
keys[dpos] = sym;
vals[dpos] = val;
return;
}
/* no room */
iv_rehash(mrb, t);
keys = (mrb_sym*)&t->ptr[t->alloc];
vals = t->ptr;
start = pos = hash & (t->alloc-1);
}
}
}
/* Get a value for a symbol from the instance variable table. */
static int
iv_get(mrb_state *mrb, iv_tbl *t, mrb_sym sym, mrb_value *vp)
{
int hash, pos, start;
if (t == NULL) return FALSE;
if (t->alloc == 0) return FALSE;
if (t->size == 0) return FALSE;
mrb_sym *keys = (mrb_sym*)&t->ptr[t->alloc];
mrb_value *vals = t->ptr;
hash = kh_int_hash_func(mrb, sym);
start = pos = hash & (t->alloc-1);
for (;;) {
mrb_sym key = keys[pos];
if (key == sym) {
if (vp) *vp = vals[pos];
return pos+1;
}
else if (key == IV_EMPTY) {
return 0;
}
pos = (pos+1) & (t->alloc-1);
if (pos == start) { /* not found */
return 0;
}
}
}
/* Deletes the value for the symbol from the instance variable table. */
static mrb_bool
iv_del(mrb_state *mrb, iv_tbl *t, mrb_sym sym, mrb_value *vp)
{
int hash, pos, start;
if (t == NULL) return FALSE;
if (t->alloc == 0) return FALSE;
if (t->size == 0) return FALSE;
mrb_sym *keys = (mrb_sym*)&t->ptr[t->alloc];
mrb_value *vals = t->ptr;
hash = kh_int_hash_func(mrb, sym);
start = pos = hash & (t->alloc-1);
for (;;) {
mrb_sym key = keys[pos];
if (key == sym) {
if (vp) *vp = vals[pos];
t->size--;
keys[pos] = IV_DELETED;
return TRUE;
}
else if (key == IV_EMPTY) {
return FALSE;
}
pos = (pos+1) & (t->alloc-1);
if (pos == start) { /* not found */
return FALSE;
}
}
}
/* Iterates over the instance variable table. */
static void
iv_foreach(mrb_state *mrb, iv_tbl *t, mrb_iv_foreach_func *func, void *p)
{
int i;
if (t == NULL) return;
if (t->alloc == 0) return;
if (t->size == 0) return;
mrb_sym *keys = (mrb_sym*)&t->ptr[t->alloc];
mrb_value *vals = t->ptr;
for (i=0; i<t->alloc; i++) {
if (IV_KEY_P(keys[i])) {
if ((*func)(mrb, keys[i], vals[i], p) != 0) {
return;
}
}
}
return;
}
/* Get the size of the instance variable table. */
/* Size is approximated by the allocated table size. */
static size_t
iv_size(mrb_state *mrb, iv_tbl *t)
{
if (t == NULL) return 0;
return (size_t)t->size;
}
/* Copy the instance variable table. */
static iv_tbl*
iv_copy(mrb_state *mrb, iv_tbl *t)
{
iv_tbl *t2;
int i;
if (t == NULL) return NULL;
if (t->alloc == 0) return NULL;
if (t->size == 0) return NULL;
mrb_sym *keys = (mrb_sym*)&t->ptr[t->alloc];
mrb_value *vals = t->ptr;
t2 = iv_new(mrb);
for (i=0; i<t->alloc; i++) {
if (IV_KEY_P(keys[i])) {
iv_put(mrb, t2, keys[i], vals[i]);
}
}
return t2;
}
/* Free memory of the instance variable table. */
static void
iv_free(mrb_state *mrb, iv_tbl *t)
{
mrb_free(mrb, t->ptr);
mrb_free(mrb, t);
}
static int
iv_mark_i(mrb_state *mrb, mrb_sym sym, mrb_value v, void *p)
{
mrb_gc_mark_value(mrb, v);
return 0;
}
static void
mark_tbl(mrb_state *mrb, iv_tbl *t)
{
iv_foreach(mrb, t, iv_mark_i, 0);
}
void
mrb_gc_mark_gv(mrb_state *mrb)
{
mark_tbl(mrb, mrb->globals);
}
void
mrb_gc_free_gv(mrb_state *mrb)
{
if (mrb->globals)
iv_free(mrb, mrb->globals);
}
void
mrb_gc_mark_iv(mrb_state *mrb, struct RObject *obj)
{
mark_tbl(mrb, obj->iv);
}
size_t
mrb_gc_mark_iv_size(mrb_state *mrb, struct RObject *obj)
{
return iv_size(mrb, obj->iv);
}
void
mrb_gc_free_iv(mrb_state *mrb, struct RObject *obj)
{
if (obj->iv) {
iv_free(mrb, obj->iv);
}
}
mrb_value
mrb_vm_special_get(mrb_state *mrb, mrb_sym i)
{
return mrb_fixnum_value(0);
}
void
mrb_vm_special_set(mrb_state *mrb, mrb_sym i, mrb_value v)
{
}
static mrb_bool
obj_iv_p(mrb_value obj)
{
switch (mrb_type(obj)) {
case MRB_TT_OBJECT:
case MRB_TT_CLASS:
case MRB_TT_MODULE:
case MRB_TT_SCLASS:
case MRB_TT_HASH:
case MRB_TT_DATA:
case MRB_TT_EXCEPTION:
return TRUE;
default:
return FALSE;
}
}
MRB_API mrb_value
mrb_obj_iv_get(mrb_state *mrb, struct RObject *obj, mrb_sym sym)
{
mrb_value v;
if (obj->iv && iv_get(mrb, obj->iv, sym, &v))
return v;
return mrb_nil_value();
}
MRB_API mrb_value
mrb_iv_get(mrb_state *mrb, mrb_value obj, mrb_sym sym)
{
if (obj_iv_p(obj)) {
return mrb_obj_iv_get(mrb, mrb_obj_ptr(obj), sym);
}
return mrb_nil_value();
}
static inline void assign_class_name(mrb_state *mrb, struct RObject *obj, mrb_sym sym, mrb_value v);
void
mrb_obj_iv_set_force(mrb_state *mrb, struct RObject *obj, mrb_sym sym, mrb_value v)
{
assign_class_name(mrb, obj, sym, v);
if (!obj->iv) {
obj->iv = iv_new(mrb);
}
iv_put(mrb, obj->iv, sym, v);
mrb_field_write_barrier_value(mrb, (struct RBasic*)obj, v);
}
MRB_API void
mrb_obj_iv_set(mrb_state *mrb, struct RObject *obj, mrb_sym sym, mrb_value v)
{
mrb_check_frozen(mrb, obj);
mrb_obj_iv_set_force(mrb, obj, sym, v);
}
/* Iterates over the instance variable table. */
MRB_API void
mrb_iv_foreach(mrb_state *mrb, mrb_value obj, mrb_iv_foreach_func *func, void *p)
{
if (!obj_iv_p(obj)) return;
iv_foreach(mrb, mrb_obj_ptr(obj)->iv, func, p);
}
static inline mrb_bool
namespace_p(enum mrb_vtype tt)
{
return tt == MRB_TT_CLASS || tt == MRB_TT_MODULE ? TRUE : FALSE;
}
static inline void
assign_class_name(mrb_state *mrb, struct RObject *obj, mrb_sym sym, mrb_value v)
{
if (namespace_p(obj->tt) && namespace_p(mrb_type(v))) {
struct RObject *c = mrb_obj_ptr(v);
if (obj != c && ISUPPER(mrb_sym_name_len(mrb, sym, NULL)[0])) {
mrb_sym id_classname = MRB_SYM(__classname__);
mrb_value o = mrb_obj_iv_get(mrb, c, id_classname);
if (mrb_nil_p(o)) {
mrb_sym id_outer = MRB_SYM(__outer__);
o = mrb_obj_iv_get(mrb, c, id_outer);
if (mrb_nil_p(o)) {
if ((struct RClass *)obj == mrb->object_class) {
mrb_obj_iv_set_force(mrb, c, id_classname, mrb_symbol_value(sym));
}
else {
mrb_obj_iv_set_force(mrb, c, id_outer, mrb_obj_value(obj));
}
}
}
}
}
}
MRB_API void
mrb_iv_set(mrb_state *mrb, mrb_value obj, mrb_sym sym, mrb_value v)
{
if (obj_iv_p(obj)) {
mrb_obj_iv_set(mrb, mrb_obj_ptr(obj), sym, v);
}
else {
mrb_raise(mrb, E_ARGUMENT_ERROR, "cannot set instance variable");
}
}
MRB_API mrb_bool
mrb_obj_iv_defined(mrb_state *mrb, struct RObject *obj, mrb_sym sym)
{
iv_tbl *t;
t = obj->iv;
if (t && iv_get(mrb, t, sym, NULL)) return TRUE;
return FALSE;
}
MRB_API mrb_bool
mrb_iv_defined(mrb_state *mrb, mrb_value obj, mrb_sym sym)
{
if (!obj_iv_p(obj)) return FALSE;
return mrb_obj_iv_defined(mrb, mrb_obj_ptr(obj), sym);
}
MRB_API mrb_bool
mrb_iv_name_sym_p(mrb_state *mrb, mrb_sym iv_name)
{
const char *s;
mrb_int len;
s = mrb_sym_name_len(mrb, iv_name, &len);
if (len < 2) return FALSE;
if (s[0] != '@') return FALSE;
if (ISDIGIT(s[1])) return FALSE;
return mrb_ident_p(s+1, len-1);
}
MRB_API void
mrb_iv_name_sym_check(mrb_state *mrb, mrb_sym iv_name)
{
if (!mrb_iv_name_sym_p(mrb, iv_name)) {
mrb_name_error(mrb, iv_name, "'%n' is not allowed as an instance variable name", iv_name);
}
}
MRB_API void
mrb_iv_copy(mrb_state *mrb, mrb_value dest, mrb_value src)
{
struct RObject *d = mrb_obj_ptr(dest);
struct RObject *s = mrb_obj_ptr(src);
if (d->iv) {
iv_free(mrb, d->iv);
d->iv = 0;
}
if (s->iv) {
mrb_write_barrier(mrb, (struct RBasic*)d);
d->iv = iv_copy(mrb, s->iv);
}
}
static int
inspect_i(mrb_state *mrb, mrb_sym sym, mrb_value v, void *p)
{
mrb_value str = *(mrb_value*)p;
const char *s;
mrb_int len;
mrb_value ins;
char *sp = RSTRING_PTR(str);
/* need not to show internal data */
if (sp[0] == '-') { /* first element */
sp[0] = '#';
mrb_str_cat_lit(mrb, str, " ");
}
else {
mrb_str_cat_lit(mrb, str, ", ");
}
s = mrb_sym_name_len(mrb, sym, &len);
mrb_str_cat(mrb, str, s, len);
mrb_str_cat_lit(mrb, str, "=");
if (mrb_object_p(v)) {
ins = mrb_any_to_s(mrb, v);
}
else {
ins = mrb_inspect(mrb, v);
}
mrb_str_cat_str(mrb, str, ins);
return 0;
}
mrb_value
mrb_obj_iv_inspect(mrb_state *mrb, struct RObject *obj)
{
iv_tbl *t = obj->iv;
size_t len = iv_size(mrb, t);
if (len > 0) {
const char *cn = mrb_obj_classname(mrb, mrb_obj_value(obj));
mrb_value str = mrb_str_new_capa(mrb, 30);
mrb_str_cat_lit(mrb, str, "-<");
mrb_str_cat_cstr(mrb, str, cn);
mrb_str_cat_lit(mrb, str, ":");
mrb_str_cat_str(mrb, str, mrb_ptr_to_str(mrb, obj));
iv_foreach(mrb, t, inspect_i, &str);
mrb_str_cat_lit(mrb, str, ">");
return str;
}
return mrb_any_to_s(mrb, mrb_obj_value(obj));
}
MRB_API mrb_value
mrb_iv_remove(mrb_state *mrb, mrb_value obj, mrb_sym sym)
{
if (obj_iv_p(obj)) {
iv_tbl *t = mrb_obj_ptr(obj)->iv;
mrb_value val;
mrb_check_frozen(mrb, mrb_obj_ptr(obj));
if (iv_del(mrb, t, sym, &val)) {
return val;
}
}
return mrb_undef_value();
}
static int
iv_i(mrb_state *mrb, mrb_sym sym, mrb_value v, void *p)
{
mrb_value ary;
const char* s;
mrb_int len;
ary = *(mrb_value*)p;
s = mrb_sym_name_len(mrb, sym, &len);
if (len > 1 && s[0] == '@' && s[1] != '@') {
mrb_ary_push(mrb, ary, mrb_symbol_value(sym));
}
return 0;
}
/* 15.3.1.3.23 */
/*
* call-seq:
* obj.instance_variables -> array
*
* Returns an array of instance variable names for the receiver. Note
* that simply defining an accessor does not create the corresponding
* instance variable.
*
* class Fred
* attr_accessor :a1
* def initialize
* @iv = 3
* end
* end
* Fred.new.instance_variables #=> [:@iv]
*/
mrb_value
mrb_obj_instance_variables(mrb_state *mrb, mrb_value self)
{
mrb_value ary;
ary = mrb_ary_new(mrb);
if (obj_iv_p(self)) {
iv_foreach(mrb, mrb_obj_ptr(self)->iv, iv_i, &ary);
}
return ary;
}
static int
cv_i(mrb_state *mrb, mrb_sym sym, mrb_value v, void *p)
{
mrb_value ary;
const char* s;
mrb_int len;
ary = *(mrb_value*)p;
s = mrb_sym_name_len(mrb, sym, &len);
if (len > 2 && s[0] == '@' && s[1] == '@') {
mrb_ary_push(mrb, ary, mrb_symbol_value(sym));
}
return 0;
}
/* 15.2.2.4.19 */
/*
* call-seq:
* mod.class_variables(inherit=true) -> array
*
* Returns an array of the names of class variables in <i>mod</i>.
*
* class One
* @@var1 = 1
* end
* class Two < One
* @@var2 = 2
* end
* One.class_variables #=> [:@@var1]
* Two.class_variables #=> [:@@var2]
*/
mrb_value
mrb_mod_class_variables(mrb_state *mrb, mrb_value mod)
{
mrb_value ary;
struct RClass *c;
mrb_bool inherit = TRUE;
mrb_get_args(mrb, "|b", &inherit);
ary = mrb_ary_new(mrb);
c = mrb_class_ptr(mod);
while (c) {
iv_foreach(mrb, c->iv, cv_i, &ary);
if (!inherit) break;
c = c->super;
}
return ary;
}
mrb_value
mrb_mod_cv_get(mrb_state *mrb, struct RClass *c, mrb_sym sym)
{
struct RClass * cls = c;
mrb_value v;
int given = FALSE;
while (c) {
if (c->iv && iv_get(mrb, c->iv, sym, &v)) {
given = TRUE;
}
c = c->super;
}
if (given) return v;
if (cls && cls->tt == MRB_TT_SCLASS) {
mrb_value klass;
klass = mrb_obj_iv_get(mrb, (struct RObject *)cls, MRB_SYM(__attached__));
c = mrb_class_ptr(klass);
if (c->tt == MRB_TT_CLASS || c->tt == MRB_TT_MODULE) {
given = FALSE;
while (c) {
if (c->iv && iv_get(mrb, c->iv, sym, &v)) {
given = TRUE;
}
c = c->super;
}
if (given) return v;
}
}
mrb_name_error(mrb, sym, "uninitialized class variable %n in %C", sym, cls);
/* not reached */
return mrb_nil_value();
}
MRB_API mrb_value
mrb_cv_get(mrb_state *mrb, mrb_value mod, mrb_sym sym)
{
return mrb_mod_cv_get(mrb, mrb_class_ptr(mod), sym);
}
MRB_API void
mrb_mod_cv_set(mrb_state *mrb, struct RClass *c, mrb_sym sym, mrb_value v)
{
struct RClass * cls = c;
while (c) {
iv_tbl *t = c->iv;
int pos = iv_get(mrb, t, sym, NULL);
if (pos) {
mrb_check_frozen(mrb, c);
t->ptr[pos-1] = v; /* iv_get returns pos+1 to put */
mrb_field_write_barrier_value(mrb, (struct RBasic*)c, v);
return;
}
c = c->super;
}
if (cls && cls->tt == MRB_TT_SCLASS) {
mrb_value klass;
klass = mrb_obj_iv_get(mrb, (struct RObject*)cls, MRB_SYM(__attached__));
switch (mrb_type(klass)) {
case MRB_TT_CLASS:
case MRB_TT_MODULE:
case MRB_TT_SCLASS:
c = mrb_class_ptr(klass);
break;
default:
c = cls;
break;
}
}
else{
c = cls;
}
mrb_check_frozen(mrb, c);
if (!c->iv) {
c->iv = iv_new(mrb);
}
iv_put(mrb, c->iv, sym, v);
mrb_field_write_barrier_value(mrb, (struct RBasic*)c, v);
}
MRB_API void
mrb_cv_set(mrb_state *mrb, mrb_value mod, mrb_sym sym, mrb_value v)
{
mrb_mod_cv_set(mrb, mrb_class_ptr(mod), sym, v);
}
mrb_bool
mrb_mod_cv_defined(mrb_state *mrb, struct RClass * c, mrb_sym sym)
{
while (c) {
iv_tbl *t = c->iv;
if (iv_get(mrb, t, sym, NULL)) return TRUE;
c = c->super;
}
return FALSE;
}
MRB_API mrb_bool
mrb_cv_defined(mrb_state *mrb, mrb_value mod, mrb_sym sym)
{
return mrb_mod_cv_defined(mrb, mrb_class_ptr(mod), sym);
}
mrb_value
mrb_vm_cv_get(mrb_state *mrb, mrb_sym sym)
{
struct RClass *c;
const struct RProc *p = mrb->c->ci->proc;
for (;;) {
c = MRB_PROC_TARGET_CLASS(p);
if (c && c->tt != MRB_TT_SCLASS) break;
p = p->upper;
}
return mrb_mod_cv_get(mrb, c, sym);
}
void
mrb_vm_cv_set(mrb_state *mrb, mrb_sym sym, mrb_value v)
{
struct RClass *c;
const struct RProc *p = mrb->c->ci->proc;
for (;;) {
c = MRB_PROC_TARGET_CLASS(p);
if (c && c->tt != MRB_TT_SCLASS) break;
p = p->upper;
}
mrb_mod_cv_set(mrb, c, sym, v);
}
static void
mod_const_check(mrb_state *mrb, mrb_value mod)
{
switch (mrb_type(mod)) {
case MRB_TT_CLASS:
case MRB_TT_MODULE:
case MRB_TT_SCLASS:
break;
default:
mrb_raise(mrb, E_TYPE_ERROR, "constant look-up for non class/module");
break;
}
}
static mrb_value
const_get(mrb_state *mrb, struct RClass *base, mrb_sym sym, mrb_bool skip)
{
struct RClass *c = base;
mrb_value v;
mrb_bool retry = FALSE;
mrb_value name;
/* if skip then skip the current class (already searched) */
if (skip) c = c->super;
L_RETRY:
while (c) {
if (!MRB_FLAG_TEST(c, MRB_FL_CLASS_IS_PREPENDED) && c->iv) {
if (iv_get(mrb, c->iv, sym, &v))
return v;
}
c = c->super;
if (!skip && c == mrb->object_class) break;
}
if (!retry && base->tt == MRB_TT_MODULE) {
c = mrb->object_class;
retry = TRUE;
goto L_RETRY;
}
name = mrb_symbol_value(sym);
return mrb_funcall_argv(mrb, mrb_obj_value(base), MRB_SYM(const_missing), 1, &name);
}
MRB_API mrb_value
mrb_const_get(mrb_state *mrb, mrb_value mod, mrb_sym sym)
{
mod_const_check(mrb, mod);
return const_get(mrb, mrb_class_ptr(mod), sym, FALSE);
}
mrb_value
mrb_vm_const_get(mrb_state *mrb, mrb_sym sym)
{
struct RClass *c;
struct RClass *c2;
mrb_value v;
const struct RProc *proc = mrb->c->ci->proc;
c = MRB_PROC_TARGET_CLASS(proc);
if (!c) c = mrb->object_class;
if (iv_get(mrb, c->iv, sym, &v)) {
return v;
}
c2 = c;
while (c2 && c2->tt == MRB_TT_SCLASS) {
mrb_value klass;
if (!iv_get(mrb, c2->iv, MRB_SYM(__attached__), &klass)) {
c2 = NULL;
break;
}
c2 = mrb_class_ptr(klass);
}
if (c2 && (c2->tt == MRB_TT_CLASS || c2->tt == MRB_TT_MODULE)) c = c2;
proc = proc->upper;
while (proc) {
c2 = MRB_PROC_TARGET_CLASS(proc);
if (!c2) c2 = mrb->object_class;
if (c2 && iv_get(mrb, c2->iv, sym, &v)) {
return v;
}
proc = proc->upper;
}
return const_get(mrb, c, sym, TRUE);
}
MRB_API void
mrb_const_set(mrb_state *mrb, mrb_value mod, mrb_sym sym, mrb_value v)
{
mod_const_check(mrb, mod);
if (mrb_type(v) == MRB_TT_CLASS || mrb_type(v) == MRB_TT_MODULE) {
mrb_class_name_class(mrb, mrb_class_ptr(mod), mrb_class_ptr(v), sym);
}
mrb_iv_set(mrb, mod, sym, v);
}
void
mrb_vm_const_set(mrb_state *mrb, mrb_sym sym, mrb_value v)
{
struct RClass *c;
c = MRB_PROC_TARGET_CLASS(mrb->c->ci->proc);
if (!c) c = mrb->object_class;
mrb_obj_iv_set(mrb, (struct RObject*)c, sym, v);
}
MRB_API void
mrb_const_remove(mrb_state *mrb, mrb_value mod, mrb_sym sym)
{
mod_const_check(mrb, mod);
mrb_iv_remove(mrb, mod, sym);
}
MRB_API void
mrb_define_const_id(mrb_state *mrb, struct RClass *mod, mrb_sym name, mrb_value v)
{
mrb_obj_iv_set(mrb, (struct RObject*)mod, name, v);
}
MRB_API void
mrb_define_const(mrb_state *mrb, struct RClass *mod, const char *name, mrb_value v)
{
mrb_obj_iv_set(mrb, (struct RObject*)mod, mrb_intern_cstr(mrb, name), v);
}
MRB_API void
mrb_define_global_const(mrb_state *mrb, const char *name, mrb_value val)
{
mrb_define_const(mrb, mrb->object_class, name, val);
}
static int
const_i(mrb_state *mrb, mrb_sym sym, mrb_value v, void *p)
{
mrb_value ary;
const char* s;
mrb_int len;
ary = *(mrb_value*)p;
s = mrb_sym_name_len(mrb, sym, &len);
if (len >= 1 && ISUPPER(s[0])) {
mrb_int i, alen = RARRAY_LEN(ary);
for (i=0; i<alen; i++) {
if (mrb_symbol(RARRAY_PTR(ary)[i]) == sym)
break;
}
if (i==alen) {
mrb_ary_push(mrb, ary, mrb_symbol_value(sym));
}
}
return 0;
}
/* 15.2.2.4.24 */
/*
* call-seq:
* mod.constants -> array
*
* Returns an array of all names of constants defined in the receiver.
*/
mrb_value
mrb_mod_constants(mrb_state *mrb, mrb_value mod)
{
mrb_value ary;
mrb_bool inherit = TRUE;
struct RClass *c = mrb_class_ptr(mod);
mrb_get_args(mrb, "|b", &inherit);
ary = mrb_ary_new(mrb);
while (c) {
iv_foreach(mrb, c->iv, const_i, &ary);
if (!inherit) break;
c = c->super;
if (c == mrb->object_class) break;
}
return ary;
}
MRB_API mrb_value
mrb_gv_get(mrb_state *mrb, mrb_sym sym)
{
mrb_value v;
if (iv_get(mrb, mrb->globals, sym, &v))
return v;
return mrb_nil_value();
}
MRB_API void
mrb_gv_set(mrb_state *mrb, mrb_sym sym, mrb_value v)
{
iv_tbl *t;
if (!mrb->globals) {
mrb->globals = iv_new(mrb);
}
t = mrb->globals;
iv_put(mrb, t, sym, v);
}
MRB_API void
mrb_gv_remove(mrb_state *mrb, mrb_sym sym)
{
iv_del(mrb, mrb->globals, sym, NULL);
}
static int
gv_i(mrb_state *mrb, mrb_sym sym, mrb_value v, void *p)
{
mrb_value ary;
ary = *(mrb_value*)p;
mrb_ary_push(mrb, ary, mrb_symbol_value(sym));
return 0;
}
/* 15.3.1.2.4 */
/* 15.3.1.3.14 */
/*
* call-seq:
* global_variables -> array
*
* Returns an array of the names of global variables.
*
* global_variables.grep /std/ #=> [:$stdin, :$stdout, :$stderr]
*/
mrb_value
mrb_f_global_variables(mrb_state *mrb, mrb_value self)
{
iv_tbl *t = mrb->globals;
mrb_value ary = mrb_ary_new(mrb);
iv_foreach(mrb, t, gv_i, &ary);
return ary;
}
static mrb_bool
const_defined_0(mrb_state *mrb, mrb_value mod, mrb_sym id, mrb_bool exclude, mrb_bool recurse)
{
struct RClass *klass = mrb_class_ptr(mod);
struct RClass *tmp;
mrb_bool mod_retry = FALSE;
tmp = klass;
retry:
while (tmp) {
if (iv_get(mrb, tmp->iv, id, NULL)) {
return TRUE;
}
if (!recurse && (klass != mrb->object_class)) break;
tmp = tmp->super;
}
if (!exclude && !mod_retry && (klass->tt == MRB_TT_MODULE)) {
mod_retry = TRUE;
tmp = mrb->object_class;
goto retry;
}
return FALSE;
}
MRB_API mrb_bool
mrb_const_defined(mrb_state *mrb, mrb_value mod, mrb_sym id)
{
return const_defined_0(mrb, mod, id, TRUE, TRUE);
}
MRB_API mrb_bool
mrb_const_defined_at(mrb_state *mrb, mrb_value mod, mrb_sym id)
{
return const_defined_0(mrb, mod, id, TRUE, FALSE);
}
MRB_API mrb_value
mrb_attr_get(mrb_state *mrb, mrb_value obj, mrb_sym id)
{
return mrb_iv_get(mrb, obj, id);
}
struct csym_arg {
struct RClass *c;
mrb_sym sym;
};
static int
csym_i(mrb_state *mrb, mrb_sym sym, mrb_value v, void *p)
{
struct csym_arg *a = (struct csym_arg*)p;
struct RClass *c = a->c;
if (mrb_type(v) == c->tt && mrb_class_ptr(v) == c) {
a->sym = sym;
return 1; /* stop iteration */
}
return 0;
}
static mrb_sym
find_class_sym(mrb_state *mrb, struct RClass *outer, struct RClass *c)
{
struct csym_arg arg;
if (!outer) return 0;
if (outer == c) return 0;
arg.c = c;
arg.sym = 0;
iv_foreach(mrb, outer->iv, csym_i, &arg);
return arg.sym;
}
static struct RClass*
outer_class(mrb_state *mrb, struct RClass *c)
{
mrb_value ov;
ov = mrb_obj_iv_get(mrb, (struct RObject*)c, MRB_SYM(__outer__));
if (mrb_nil_p(ov)) return NULL;
switch (mrb_type(ov)) {
case MRB_TT_CLASS:
case MRB_TT_MODULE:
return mrb_class_ptr(ov);
default:
break;
}
return NULL;
}
static mrb_bool
detect_outer_loop(mrb_state *mrb, struct RClass *c)
{
struct RClass *t = c; /* tortoise */
struct RClass *h = c; /* hare */
for (;;) {
if (h == NULL) return FALSE;
h = outer_class(mrb, h);
if (h == NULL) return FALSE;
h = outer_class(mrb, h);
t = outer_class(mrb, t);
if (t == h) return TRUE;
}
}
mrb_value
mrb_class_find_path(mrb_state *mrb, struct RClass *c)
{
struct RClass *outer;
mrb_value path;
mrb_sym name;
const char *str;
mrb_int len;
if (detect_outer_loop(mrb, c)) return mrb_nil_value();
outer = outer_class(mrb, c);
if (outer == NULL) return mrb_nil_value();
name = find_class_sym(mrb, outer, c);
if (name == 0) return mrb_nil_value();
str = mrb_class_name(mrb, outer);
path = mrb_str_new_capa(mrb, 40);
mrb_str_cat_cstr(mrb, path, str);
mrb_str_cat_cstr(mrb, path, "::");
str = mrb_sym_name_len(mrb, name, &len);
mrb_str_cat(mrb, path, str, len);
if (RSTRING_PTR(path)[0] != '#') {
iv_del(mrb, c->iv, MRB_SYM(__outer__), NULL);
iv_put(mrb, c->iv, MRB_SYM(__classname__), path);
mrb_field_write_barrier_value(mrb, (struct RBasic*)c, path);
path = mrb_str_dup(mrb, path);
}
return path;
}
size_t
mrb_obj_iv_tbl_memsize(mrb_value obj)
{
iv_tbl *t = mrb_obj_ptr(obj)->iv;
if (t == NULL) return 0;
return sizeof(iv_tbl) + t->alloc*(sizeof(mrb_value)+sizeof(mrb_sym));
}
#define identchar(c) (ISALNUM(c) || (c) == '_' || !ISASCII(c))
mrb_bool
mrb_ident_p(const char *s, mrb_int len)
{
mrb_int i;
for (i = 0; i < len; i++) {
if (!identchar(s[i])) return FALSE;
}
return TRUE;
}
| 1 | 0.890444 | 1 | 0.890444 | game-dev | MEDIA | 0.487175 | game-dev | 0.972124 | 1 | 0.972124 |
ForestryMC/Binnie | 1,429 | extrabees/src/main/java/binnie/extrabees/items/ItemMiscProduct.java | package binnie.extrabees.items;
import binnie.extrabees.ExtraBees;
import binnie.extrabees.items.types.IEBItemMiscProvider;
import forestry.api.core.IModelManager;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.client.util.ITooltipFlag;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import javax.annotation.Nullable;
import java.util.List;
public class ItemMiscProduct extends ItemProduct<IEBItemMiscProvider> {
public ItemMiscProduct(CreativeTabs tab, IEBItemMiscProvider[] types) {
super(types);
setCreativeTab(tab);
setRegistryName("misc");
}
@Override
@SideOnly(Side.CLIENT)
public void addInformation(ItemStack stack, @Nullable World worldIn, List<String> tooltip, ITooltipFlag flagIn) {
IEBItemMiscProvider provider = get(stack);
provider.addInformation(tooltip);
}
@Override
@SideOnly(Side.CLIENT)
@SuppressWarnings("all")
public void registerModel(Item item, IModelManager manager) {
for (IEBItemMiscProvider type : types) {
ModelLoader.setCustomModelResourceLocation(item, type.ordinal(), new ModelResourceLocation(ExtraBees.MODID + ":misc/" + type.getModelPath(), "inventory"));
}
}
}
| 1 | 0.680358 | 1 | 0.680358 | game-dev | MEDIA | 0.995194 | game-dev | 0.692205 | 1 | 0.692205 |
DigitalExtinction/Game | 6,175 | crates/menu/src/multiplayer/gamelisting.rs | use std::time::Duration;
use bevy::{prelude::*, time::Stopwatch};
use de_gui::{ButtonCommands, GuiCommands, LabelCommands, OuterStyle, ToastEvent};
use de_lobby_client::{ListGamesRequest, RequestEvent, ResponseEvent};
use de_lobby_model::GamePartial;
use super::{current::GameNameRes, MultiplayerState};
use crate::menu::Menu;
const REFRESH_INTERVAL: Duration = Duration::from_secs(10);
pub(super) struct GameListingPlugin;
impl Plugin for GameListingPlugin {
fn build(&self, app: &mut App) {
app.add_systems(OnEnter(MultiplayerState::GameListing), setup)
.add_systems(OnExit(MultiplayerState::GameListing), cleanup)
.add_systems(
Update,
(refresh_system, list_games_system, button_system)
.run_if(in_state(MultiplayerState::GameListing)),
);
}
}
#[derive(Resource)]
struct GamesTable(Entity);
#[derive(Component)]
enum ButtonAction {
Create,
Join(String),
}
fn setup(
mut commands: GuiCommands,
menu: Res<Menu>,
mut requests: EventWriter<RequestEvent<ListGamesRequest>>,
) {
let column_id = commands
.spawn(NodeBundle {
style: Style {
flex_direction: FlexDirection::Column,
width: Val::Percent(80.),
height: Val::Percent(80.),
margin: UiRect::all(Val::Auto),
align_items: AlignItems::Center,
justify_content: JustifyContent::FlexStart,
..default()
},
..default()
})
.id();
commands.entity(menu.root_node()).add_child(column_id);
create_game_button(&mut commands, column_id);
let table_id = table(&mut commands, column_id);
commands.insert_resource(GamesTable(table_id));
requests.send(RequestEvent::new("list-games", ListGamesRequest));
}
fn cleanup(mut commands: Commands) {
commands.remove_resource::<GamesTable>();
}
fn create_game_button(commands: &mut GuiCommands, parent_node: Entity) {
let button_id = commands
.spawn_button(
OuterStyle {
width: Val::Percent(100.),
height: Val::Percent(8.),
margin: UiRect::bottom(Val::Percent(1.)),
},
"Create Game",
)
.insert(ButtonAction::Create)
.id();
commands.entity(parent_node).add_child(button_id);
}
fn table(commands: &mut GuiCommands, parent_node: Entity) -> Entity {
let table_id = commands
.spawn(NodeBundle {
style: Style {
flex_direction: FlexDirection::Column,
width: Val::Percent(100.),
height: Val::Percent(91.),
margin: UiRect::all(Val::Auto),
align_items: AlignItems::Center,
justify_content: JustifyContent::FlexStart,
..default()
},
..default()
})
.id();
commands.entity(parent_node).add_child(table_id);
table_id
}
fn row(commands: &mut GuiCommands, game: &GamePartial) -> Entity {
let row_id = commands
.spawn(NodeBundle {
style: Style {
flex_direction: FlexDirection::Row,
width: Val::Percent(100.),
height: Val::Percent(8.),
margin: UiRect::vertical(Val::Percent(0.5)),
align_items: AlignItems::Center,
justify_content: JustifyContent::FlexStart,
..default()
},
..default()
})
.id();
let name_id = commands
.spawn_label(
OuterStyle {
width: Val::Percent(80.),
height: Val::Percent(100.),
margin: UiRect::right(Val::Percent(2.)),
},
format!(
"{} ({}/{})",
game.config().name(),
game.num_players(),
game.config().max_players()
),
)
.id();
commands.entity(row_id).add_child(name_id);
if game.num_players() < game.config().max_players() {
let button_id = commands
.spawn_button(
OuterStyle {
width: Val::Percent(18.),
height: Val::Percent(100.),
..default()
},
"Join",
)
.insert(ButtonAction::Join(game.config().name().to_owned()))
.id();
commands.entity(row_id).add_child(button_id);
}
row_id
}
fn refresh_system(
time: Res<Time>,
mut stopwatch: Local<Stopwatch>,
mut requests: EventWriter<RequestEvent<ListGamesRequest>>,
) {
stopwatch.tick(time.delta());
if stopwatch.elapsed() >= REFRESH_INTERVAL {
stopwatch.reset();
requests.send(RequestEvent::new("list-games", ListGamesRequest));
}
}
fn list_games_system(
mut commands: GuiCommands,
table: Res<GamesTable>,
mut events: EventReader<ResponseEvent<ListGamesRequest>>,
mut toasts: EventWriter<ToastEvent>,
) {
let Some(event) = events.read().last() else {
return;
};
commands.entity(table.0).despawn_descendants();
match event.result() {
Ok(games) => {
for game in games.games() {
let row_id = row(&mut commands, game);
commands.entity(table.0).add_child(row_id);
}
}
Err(error) => {
toasts.send(ToastEvent::new(error));
}
}
}
fn button_system(
mut commands: Commands,
mut next_state: ResMut<NextState<MultiplayerState>>,
interactions: Query<(&Interaction, &ButtonAction), Changed<Interaction>>,
) {
for (&interaction, action) in interactions.iter() {
if let Interaction::Pressed = interaction {
match action {
ButtonAction::Create => next_state.set(MultiplayerState::GameCreation),
ButtonAction::Join(name) => {
commands.insert_resource(GameNameRes::new(name));
next_state.set(MultiplayerState::GameJoining);
}
}
}
}
}
| 1 | 0.910759 | 1 | 0.910759 | game-dev | MEDIA | 0.972105 | game-dev | 0.774464 | 1 | 0.774464 |
Opentrons/opentrons | 12,897 | protocol-designer/src/file-data/selectors/fileCreator.ts | import flatMap from 'lodash/flatMap'
import isEmpty from 'lodash/isEmpty'
import mapValues from 'lodash/mapValues'
import reduce from 'lodash/reduce'
import uniq from 'lodash/uniq'
import { createSelector } from 'reselect'
import {
FLEX_ROBOT_TYPE,
FLEX_STANDARD_DECKID,
NONE_LIQUID_CLASS_NAME,
OT2_STANDARD_DECKID,
OT2_STANDARD_MODEL,
} from '@opentrons/shared-data'
import {
PD_APPLICATION_VERSION,
pythonCustomLabwareDict,
pythonDefRun,
pythonImports,
pythonMetadata,
pythonRequirements,
swatchColors,
} from '@opentrons/step-generation'
import { selectors as dismissSelectors } from '../../dismiss'
import { selectors as labwareDefSelectors } from '../../labware-defs'
import { selectors as ingredSelectors } from '../../labware-ingred/selectors'
import { selectors as stepFormSelectors } from '../../step-forms'
import { getStepGroups } from '../../step-forms/selectors'
import { selectors as uiLabwareSelectors } from '../../ui/labware'
import { getInitialRobotState, getRobotStateTimeline } from './commands'
import { getFileMetadata, getRobotType } from './fileFields'
import {
getLabwareLoadInfo,
getLoadCommands,
getModulesLoadInfo,
getPipettesLoadInfo,
} from './utils'
import type {
CommandAnnotationV1Mixin,
CommandV14Mixin,
CreateCommand,
LabwareV2Mixin,
LiquidV1Mixin,
OT2RobotMixin,
OT3RobotMixin,
ProtocolBase,
ProtocolFile,
} from '@opentrons/shared-data'
import type { SecondOrderCommandAnnotation } from '@opentrons/shared-data/commandAnnotation/types'
import type {
Ingredients,
LabwareEntities,
PipetteEntities,
PipetteEntity,
} from '@opentrons/step-generation'
import type {
PDMetadata,
PDPythonFile,
PythonDesignerApplication,
} from '../../file-types'
import type { LabwareDefByDefURI } from '../../labware-defs'
import type { Selector } from '../../types'
// TODO: BC: 2018-02-21 uncomment this assert, causes test failures
// console.assert(!isEmpty(_OT_PD_VERSION_), 'Could not find application version!')
if (isEmpty(_OT_PD_VERSION_))
console.warn('Could not find application version!')
const applicationVersion: string = _OT_PD_VERSION_ || ''
// Internal release date: this should never be read programatically,
// it just helps us humans quickly identify what build a user was using
// when we look at saved protocols (without requiring us to trace thru git logs)
const _internalAppBuildDate = _OT_PD_BUILD_DATE_
// A labware definition is considered "in use" and should be included in
// the protocol file if it either...
// 1. is present on the deck in initial deck setup
// 2. OR is a tiprack def assigned to a pipette, even if it's not on the deck
export const getLabwareDefinitionsInUse = (
labware: LabwareEntities,
pipettes: PipetteEntities,
allLabwareDefsByURI: LabwareDefByDefURI
): LabwareDefByDefURI => {
const labwareDefURIsOnDeck: string[] = Object.keys(labware).map(
(labwareId: string) => labware[labwareId].labwareDefURI
)
const tiprackDefURIsInUse: string[] = Object.keys(pipettes)
.map(id => pipettes[id])
.flatMap((pipetteEntity: PipetteEntity) => pipetteEntity.tiprackDefURI)
const labwareDefURIsInUse = uniq([
...tiprackDefURIsInUse,
...labwareDefURIsOnDeck,
])
return labwareDefURIsInUse.reduce<LabwareDefByDefURI>(
(acc, labwareDefURI: string) => ({
...acc,
[labwareDefURI]: allLabwareDefsByURI[labwareDefURI],
}),
{}
)
}
// eventually will be deprecated
export const createJSONFile: Selector<ProtocolFile> = createSelector(
getFileMetadata,
getInitialRobotState,
getRobotStateTimeline,
getRobotType,
dismissSelectors.getAllDismissedWarnings,
ingredSelectors.getLiquidsByLabwareId,
stepFormSelectors.getSavedStepForms,
stepFormSelectors.getOrderedStepIds,
uiLabwareSelectors.getLabwareNicknamesById,
labwareDefSelectors.getLabwareDefsByURI,
getStepGroups,
stepFormSelectors.getInvariantContext,
(
fileMetadata,
initialRobotState,
robotStateTimeline,
robotType,
dismissedWarnings,
ingredLocations,
savedStepForms,
orderedStepIds,
labwareNicknamesById,
labwareDefsByURI,
stepGroups,
invariantContext
) => {
const { author, description, created, source } = fileMetadata
const {
pipetteEntities,
labwareEntities,
liquidEntities,
moduleEntities,
} = invariantContext
const loadCommands = getLoadCommands(
initialRobotState,
pipetteEntities,
moduleEntities,
labwareEntities,
labwareNicknamesById,
liquidEntities,
ingredLocations,
savedStepForms
)
const name = fileMetadata.protocolName || 'untitled'
const lastModified = fileMetadata.lastModified
// TODO: Ian 2018-07-10 allow user to save steps in JSON file, even if those
// step never have saved forms.
// (We could just export the `steps` reducer, but we've sunset it)
const savedOrderedStepIds = orderedStepIds.filter(
stepId => savedStepForms[stepId]
)
const ingredients: Ingredients = Object.entries(liquidEntities).reduce(
(acc: Ingredients, [liquidId, liquidData]) => {
const {
displayName,
description,
displayColor,
liquidGroupId,
liquidClass,
} = liquidData
acc[liquidId] = {
displayName,
description,
displayColor,
liquidGroupId,
liquidClass,
}
return acc
},
{}
)
const designerApplication = {
name: 'opentrons/protocol-designer',
version: applicationVersion,
data: {
_internalAppBuildDate,
pipetteTiprackAssignments: mapValues(
pipetteEntities,
(p: typeof pipetteEntities[keyof typeof pipetteEntities]): string[] =>
p.tiprackDefURI
),
dismissedWarnings,
ingredients,
ingredLocations,
savedStepForms,
orderedStepIds: savedOrderedStepIds,
pipettes: getPipettesLoadInfo(pipetteEntities),
modules: getModulesLoadInfo(moduleEntities),
labware: getLabwareLoadInfo(labwareEntities, labwareNicknamesById),
},
}
const liquids: LiquidV1Mixin['liquids'] = reduce(
liquidEntities,
(acc, liquidData, liquidId) => {
return {
...acc,
[liquidId]: {
displayName: liquidData.displayName,
description: liquidData.description ?? '',
displayColor: liquidData.displayColor ?? swatchColors(liquidId),
},
}
},
{}
)
const labwareDefinitions = getLabwareDefinitionsInUse(
labwareEntities,
pipetteEntities,
labwareDefsByURI
)
const nonLoadCommands: CreateCommand[] = flatMap(
robotStateTimeline.timeline,
timelineFrame => timelineFrame.commands
)
const commands = [...loadCommands, ...nonLoadCommands]
const flexDeckSpec: OT3RobotMixin = {
robot: {
model: FLEX_ROBOT_TYPE,
deckId: FLEX_STANDARD_DECKID,
},
}
const ot2DeckSpec: OT2RobotMixin = {
robot: {
model: OT2_STANDARD_MODEL,
deckId: OT2_STANDARD_DECKID,
},
}
const deckStructure =
robotType === FLEX_ROBOT_TYPE ? flexDeckSpec : ot2DeckSpec
const labwareV2Mixin: LabwareV2Mixin = {
labwareDefinitionSchemaId: 'opentronsLabwareSchemaV2',
labwareDefinitions,
}
const liquidV2Mixin: LiquidV1Mixin = {
liquidSchemaId: 'opentronsLiquidSchemaV1',
liquids,
}
const commandv14Mixin: CommandV14Mixin = {
commandSchemaId: 'opentronsCommandSchemaV14',
commands,
}
const commandAnnotations: SecondOrderCommandAnnotation[] = Object.entries(
stepGroups
).map(([name, groupStepIds]) => {
// map stepIds from group to orderedStepIds and return indices from orderedStepIds
const stepIndices = groupStepIds
.map(groupStepId => orderedStepIds.indexOf(groupStepId))
.filter(index => index !== -1)
// return commands assosciated with the indices
const commands = stepIndices.flatMap(
index => robotStateTimeline.timeline[index].commands
)
const commandKeys = commands.map(command => command.key ?? '')
const annotation: SecondOrderCommandAnnotation = {
annotationType: 'secondOrderCommand',
machineReadableName: name,
params: {}, // what is this used for?
commandKeys,
}
return annotation
})
const commandAnnotionaV1Mixin: CommandAnnotationV1Mixin = {
commandAnnotationSchemaId: 'opentronsCommandAnnotationSchemaV1',
commandAnnotations,
}
const protocolBase: ProtocolBase<PDMetadata> = {
$otSharedSchema: '#/protocol/schemas/8',
schemaVersion: 8,
metadata: {
protocolName: name,
author,
description,
created,
lastModified,
source,
// TODO LATER
category: null,
subcategory: null,
tags: [],
},
designerApplication,
}
return {
...protocolBase,
...deckStructure,
...labwareV2Mixin,
...liquidV2Mixin,
...commandv14Mixin,
...commandAnnotionaV1Mixin,
}
}
)
export const createFile: Selector<PDPythonFile> = createSelector(
getFileMetadata,
getInitialRobotState,
getRobotStateTimeline,
getRobotType,
dismissSelectors.getAllDismissedWarnings,
ingredSelectors.getLiquidsByLabwareId,
stepFormSelectors.getSavedStepForms,
stepFormSelectors.getOrderedStepIds,
uiLabwareSelectors.getLabwareNicknamesById,
stepFormSelectors.getInvariantContext,
(
fileMetadata,
robotState,
robotStateTimeline,
robotType,
dismissedWarnings,
ingredLocations,
savedStepForms,
orderedStepIds,
labwareNicknamesById,
invariantContext
) => {
const {
pipetteEntities,
moduleEntities,
labwareEntities,
liquidEntities,
} = invariantContext
const savedOrderedStepIds = orderedStepIds.filter(
stepId => savedStepForms[stepId]
)
const ingredients: Ingredients = Object.fromEntries(
Object.entries(
liquidEntities
).map(([liquidId, { pythonName, ...rest }]) => [liquidId, rest])
)
const allUniqueLiquidClassesFromForms = Array.from(
Object.values(savedStepForms).reduce<Set<string>>((acc, stepForm) => {
if (
'liquidClass' in stepForm &&
stepForm.liquidClass != null &&
stepForm.liquidClass !== NONE_LIQUID_CLASS_NAME
) {
acc.add(stepForm.liquidClass as string)
}
return acc
}, new Set())
)
const designerApplication: PythonDesignerApplication = {
robot: {
model: robotType,
},
designerApplication: {
name: 'opentrons/protocol-designer',
// NOTE: hardcoding in the version like this could be tricky since we
// will have to remember to update the version with every release. But this solves
// the issues where you have to manually update when importing back to PD, before the release
// since using `applicationVersion` means that the version is tied to the release tag.
version: PD_APPLICATION_VERSION,
data: {
pipetteTiprackAssignments: mapValues(
pipetteEntities,
(
p: typeof pipetteEntities[keyof typeof pipetteEntities]
): string[] => p.tiprackDefURI
),
dismissedWarnings,
ingredients,
ingredLocations,
savedStepForms,
orderedStepIds: savedOrderedStepIds,
pipettes: getPipettesLoadInfo(pipetteEntities),
modules: getModulesLoadInfo(moduleEntities),
labware: getLabwareLoadInfo(labwareEntities, labwareNicknamesById),
},
},
metadata: fileMetadata,
}
const pythonProtocol =
[
// Here are the sections of the Python file:
pythonImports(),
pythonMetadata({
...fileMetadata,
// It's OK to use the "real" _OT_PD_VERSION_ here instead of the hard-coded
// proxy PD_APPLICATION_VERSION, as done above, because this is just metadata for humans
// and doesn't have the migration baggage described above.
protocolDesigner: _OT_PD_VERSION_,
}),
pythonRequirements(robotType),
pythonDefRun(
invariantContext,
robotState,
robotStateTimeline,
ingredLocations,
labwareNicknamesById,
robotType,
allUniqueLiquidClassesFromForms
),
pythonCustomLabwareDict(invariantContext.labwareEntities),
]
.filter(section => section) // skip any blank sections
.join('\n\n') + '\n'
return { pythonProtocol, designerApplication }
}
)
| 1 | 0.850862 | 1 | 0.850862 | game-dev | MEDIA | 0.229018 | game-dev | 0.831409 | 1 | 0.831409 |
hocha113/CalamityOverhaul | 4,682 | Content/Projectiles/Weapons/Melee/DawnshatterAzureProj/DawnshatterSwing.cs | using CalamityMod.Items.Weapons.Rogue;
using CalamityMod.Projectiles.Melee;
using CalamityOverhaul.Content.Items.Melee;
using CalamityOverhaul.Content.PRTTypes;
using InnoVault.PRT;
using Microsoft.Xna.Framework.Graphics;
using System;
using Terraria;
using Terraria.GameContent;
using Terraria.Localization;
using Terraria.ModLoader;
namespace CalamityOverhaul.Content.Projectiles.Weapons.Melee.DawnshatterAzureProj
{
internal class DawnshatterSwing : ModProjectile
{
public override LocalizedText DisplayName => VaultUtils.GetLocalizedItemName<DawnshatterAzure>();
public override string Texture => CWRConstant.Item_Melee + "DawnshatterAzure";
public override void SetDefaults() {
Projectile.width = Projectile.height = 40;
Projectile.DamageType = DamageClass.Melee;
Projectile.timeLeft = 190;
Projectile.friendly = true;
Projectile.hostile = false;
Projectile.tileCollide = false;
Projectile.ignoreWater = true;
Projectile.MaxUpdates = 3;
Projectile.penetrate = -1;
Projectile.ownerHitCheck = true;
Projectile.usesLocalNPCImmunity = true;
Projectile.localNPCHitCooldown = 7;
}
public override bool PreAI() {
VaultUtils.ClockFrame(ref Projectile.frame, 5, 3);
return true;
}
public override void AI() {
Projectile.velocity *= 0.98f;
Projectile.rotation += 0.1f;
Projectile.scale += 0.01f;
BasePRT particle2 = new PRT_Smoke(Projectile.Center + Projectile.velocity * Main.rand.NextFloat(0.3f, 1.7f), VaultUtils.RandVr(3, (int)(26 * Projectile.scale))
, VaultUtils.MultiStepColorLerp(Main.rand.NextFloat(), Color.Red, Color.DarkRed)
, 23, Main.rand.NextFloat(0.2f, 1.1f), 0.5f, 0.1f);
PRTLoader.AddParticle(particle2);
}
public override void OnKill(int timeLeft) {
float spread = 180f * 0.0174f;
double startAngle = Math.Atan2(Projectile.velocity.X, Projectile.velocity.Y) - (spread / 2);
double deltaAngle = spread / 8f;
double offsetAngle;
if (Projectile.owner == Main.myPlayer) {
for (int i = 0; i < 13; i++) {
offsetAngle = startAngle + (deltaAngle * (i + (i * i)) / 2f) + (32f * i);
_ = Projectile.NewProjectile(Projectile.GetSource_FromThis(), Projectile.Center.X, Projectile.Center.Y
, (float)(Math.Sin(offsetAngle) * 15f), (float)(Math.Cos(offsetAngle) * 15f)
, ModContent.ProjectileType<SandFire>(), Projectile.damage, Projectile.knockBack, Projectile.owner, 0f, 0f);
_ = Projectile.NewProjectile(Projectile.GetSource_FromThis(), Projectile.Center.X, Projectile.Center.Y
, (float)(-Math.Sin(offsetAngle) * 15f), (float)(-Math.Cos(offsetAngle) * 15f)
, ModContent.ProjectileType<SandFire>(), Projectile.damage, Projectile.knockBack, Projectile.owner, 0f, 0f);
}
Projectile.NewProjectile(Projectile.GetSource_FromThis(), Projectile.Center, Vector2.Zero
, ModContent.ProjectileType<DawnshatterEndOrb>(), (int)(Projectile.damage * 0.01), 0f, Projectile.owner);
}
Projectile.Explode(2220, Supernova.ExplosionSound with { Pitch = -0.7f });
for (int i = 0; i < 132; i++) {
BasePRT particle = new PRT_Light(Projectile.Center, VaultUtils.RandVr(3, 116), Main.rand.NextFloat(0.3f, 0.7f), Color.OrangeRed, 12, 0.2f);
PRTLoader.AddParticle(particle);
BasePRT particle2 = new PRT_Smoke(Projectile.Center + Projectile.velocity * Main.rand.NextFloat(0.3f, 1.7f), VaultUtils.RandVr(3, 16)
, VaultUtils.MultiStepColorLerp(Main.rand.NextFloat(), Color.Red, Color.DarkRed)
, 15, Main.rand.NextFloat(0.2f, 1.1f), 0.5f, 0.1f);
PRTLoader.AddParticle(particle2);
}
}
public override bool PreDraw(ref Color lightColor) {
Texture2D texture = TextureAssets.Projectile[Type].Value;
float rot = Projectile.rotation;
Vector2 drawPosition = Projectile.Center - Main.screenPosition;
Vector2 origin = VaultUtils.GetOrig(texture, 4);
Main.EntitySpriteDraw(texture, drawPosition, texture.GetRectangle(Projectile.frame, 4), Color.White
, rot, origin, Projectile.scale * 0.7f, 0, 0);
return false;
}
}
}
| 1 | 0.886649 | 1 | 0.886649 | game-dev | MEDIA | 0.994709 | game-dev | 0.98356 | 1 | 0.98356 |
adepierre/Botcraft | 1,155 | protocolCraft/include/protocolCraft/Types/AdvancementDisplay.hpp | #pragma once
#include "protocolCraft/NetworkType.hpp"
#include "protocolCraft/Types/Chat/Chat.hpp"
#include "protocolCraft/Types/Item/Slot.hpp"
#include "protocolCraft/Types/Identifier.hpp"
namespace ProtocolCraft
{
class AdvancementDisplay : public NetworkType
{
DEFINE_CONDITION(HasBackgroundTexture, GetFlags() & 0x01);
SERIALIZED_FIELD(Title, Chat);
SERIALIZED_FIELD(Description, Chat);
SERIALIZED_FIELD(Icon, Slot);
SERIALIZED_FIELD(FrameType, VarInt);
SERIALIZED_FIELD(Flags, int);
SERIALIZED_FIELD_WITHOUT_GETTER_SETTER(BackgroundTexture, Internal::Conditioned<Identifier, &AdvancementDisplay::HasBackgroundTexture>);
SERIALIZED_FIELD(XCoord, float);
SERIALIZED_FIELD(YCoord, float);
DECLARE_READ_WRITE_SERIALIZE;
GETTER(BackgroundTexture);
public:
auto& SetBackgroundTexture(const std::optional<Identifier>& BackgroundTexture_)
{
SetFlags(BackgroundTexture_.has_value() ? (GetFlags() | 0x01) : (GetFlags() & ~0x01));
BackgroundTexture = BackgroundTexture_;
return *this;
}
};
}
| 1 | 0.814335 | 1 | 0.814335 | game-dev | MEDIA | 0.867596 | game-dev | 0.723872 | 1 | 0.723872 |
snowflame0/AtlasLootClassic_MoP | 11,370 | AtlasLootClassic/Core/ItemInfo.lua | local _G = _G
local AtlasLoot = _G.AtlasLoot
local ItemInfo = {}
AtlasLoot.ItemInfo = ItemInfo
local AL = AtlasLoot.Locales
local IngameLocales = AtlasLoot.IngameLocales
local type, rawset, rawget, setmetatable = type, rawset, rawget, setmetatable
-- local GetAuctionItemClasses, GetAuctionItemSubClasses = GetAuctionItemClasses, GetAuctionItemSubClasses
local GetItemClassInfo, GetItemSubClassInfo = C_Item.GetItemClassInfo, C_Item.GetItemSubClassInfo
local LOC_DATA = {
[0] = {
["__name"] = "Consumable",
[0] = "Consumable",
[1] = "Cheese/Bread(OBSOLETE)",
[2] = "Liquid(OBSOLETE)",
},
[1] = {
["__name"] = "Container",
[0] = "Bag",
[1] = "Soul Bag(OBSOLETE)",
[2] = "Herb Bag",
[3] = "Enchanting Bag",
[4] = "Engineering Bag",
},
[2] = {
["__name"] = "Weapon",
[0] = "One-Handed Axes",
[1] = "Two-Handed Axes",
[2] = "Bows",
[3] = "Guns",
[4] = "One-Handed Maces",
[5] = "Two-Handed Maces",
[6] = "Polearms",
[7] = "One-Handed Swords",
[8] = "Two-Handed Swords",
[9] = "Obsolete",
[10] = "Staves",
[11] = "One-Handed Exotics",
[12] = "Two-Handed Exotics",
[13] = "Fist Weapons",
[14] = "Miscellaneous",
[15] = "Daggers",
[16] = "Thrown",
[17] = "Spears",
[18] = "Crossbows",
[19] = "Wands",
[20] = "Fishing Pole",
},
[3] = {
["__name"] = "Jewelry(OBSOLETE)",
[0] = "Jewelry(OBSOLETE)",
},
[4] = {
["__name"] = "Armor",
[0] = "Miscellaneous",
[1] = "Cloth",
[2] = "Leather",
[3] = "Mail",
[4] = "Plate",
[5] = "Bucklers",
[6] = "Shields",
--[7] = "Librams",
--[8] = "Idols",
--[9] = "Totems",
},
[5] = {
["__name"] = "Reagent",
[0] = "Reagent",
},
[6] = {
["__name"] = "Projectile",
--[0] = "Wand(OBSOLETE)",
--[1] = "Bolt(OBSOLETE)",
--[2] = "Arrow",
--[3] = "Bullet",
--[4] = "Thrown(OBSOLETE)",
},
[7] = {
["__name"] = "Trade Goods",
[0] = "Trade Goods",
[1] = "Parts",
[2] = "Explosives",
[3] = "Devices",
},
[8] = {
["__name"] = "Generic(OBSOLETE)",
[0] = "Generic(OBSOLETE)",
},
[9] = {
["__name"] = "Recipe",
[0] = "Book",
[1] = "Leatherworking",
[2] = "Tailoring",
[3] = "Engineering",
[4] = "Blacksmithing",
[5] = "Cooking",
[6] = "Alchemy",
[7] = "First Aid",
[8] = "Enchanting",
[9] = "Fishing",
},
[10] = {
["__name"] = "Money(OBSOLETE)",
[0] = "Money(OBSOLETE)",
},
[11] = {
["__name"] = "Quiver",
[0] = "Quiver(OBSOLETE)",
[1] = "Quiver(OBSOLETE)",
[2] = "Quiver",
[3] = "Ammo Pouch",
},
[12] = {
["__name"] = "Quest",
[0] = "Quest",
},
[13] = {
["__name"] = "Key",
[0] = "Key",
[1] = "Lockpick",
},
[14] = {
["__name"] = "Permanent(OBSOLETE)",
[0] = "Permanent",
},
[15] = {
["__name"] = "Miscellaneous",
[0] = "Junk",
},
}
local ITEM_DESC_INFO = {
["slot"] = {
[""] = "",
["INVTYPE_RANGEDRIGHT"] = "",
["INVTYPE_SHIELD"] = _G["INVTYPE_SHIELD"],
["INVTYPE_RANGED"] = "",
["INVTYPE_WEAPON"] = "",
["INVTYPE_2HWEAPON"] = "",
["INVTYPE_WRIST"] = _G["INVTYPE_WRIST"],
["INVTYPE_TRINKET"] = _G["INVTYPE_TRINKET"],
["INVTYPE_ROBE"] = _G["INVTYPE_ROBE"],
["INVTYPE_CLOAK"] = _G["INVTYPE_CLOAK"],
["INVTYPE_HEAD"] = _G["INVTYPE_HEAD"],
["INVTYPE_HOLDABLE"] = _G["INVTYPE_HOLDABLE"],
["INVTYPE_CHEST"] = _G["INVTYPE_CHEST"],
["INVTYPE_NECK"] = _G["INVTYPE_NECK"],
["INVTYPE_TABARD"] = _G["INVTYPE_TABARD"],
["INVTYPE_LEGS"] = _G["INVTYPE_LEGS"],
["INVTYPE_HAND"] = _G["INVTYPE_HAND"],
["INVTYPE_WAIST"] = _G["INVTYPE_WAIST"],
["INVTYPE_FEET"] = _G["INVTYPE_FEET"],
["INVTYPE_SHOULDER"] = _G["INVTYPE_SHOULDER"],
["INVTYPE_FINGER"] = _G["INVTYPE_FINGER"],
["INVTYPE_BAG"] = _G["INVTYPE_BAG"],
["INVTYPE_AMMO"] = _G["INVTYPE_AMMO"],
["INVTYPE_BODY"] = _G["INVTYPE_BODY"], -- Shirt
["INVTYPE_QUIVER"] = _G["INVTYPE_QUIVER"],
["INVTYPE_RELIC"] = "", -- _G["INVTYPE_RELIC"],
["INVTYPE_THROWN"] = "", -- _G["INVTYPE_THROWN"],
["INVTYPE_WEAPONMAINHAND"] = _G["INVTYPE_WEAPONMAINHAND"],
["INVTYPE_WEAPONMAINHAND_PET"] = _G["INVTYPE_WEAPONMAINHAND_PET"], -- "Main Attack"
["INVTYPE_WEAPONOFFHAND"] = _G["INVTYPE_WEAPONOFFHAND"],
},
--[[
["Consumable"] = { -- 0
["Consumable"] = true, -- 0
["Cheese/Bread(OBSOLETE)"] = true, -- 1
["Liquid(OBSOLETE)"] = true, -- 2
},
--]]
["Container"] = { -- 1
["Bag"] = "", -- 0
--["Soul Bag"] = true, -- 1
--["Herb Bag"] = true, -- 2
--["Enchanting Bag"] = true, -- 3
--["Engineering Bag"] = true, -- 4
},
["Weapon"] = { -- 2
["One-Handed Axes"] = AL["One-Hand, Axe"], -- 0
["Two-Handed Axes"] = AL["Two-Hand, Axe"], -- 1
["Bows"] = AL["Bow"], -- 2
["Guns"] = AL["Gun"], -- 3
["One-Handed Maces"] = AL["One-Hand, Mace"], -- 4
["Two-Handed Maces"] = AL["Two-Hand, Mace"], -- 5
["Polearms"] = AL["Polearm"], -- 6
["One-Handed Swords"] = AL["One-Hand, Sword"], -- 7
["Two-Handed Swords"] = AL["Two-Hand, Sword"], -- 8
--["Obsolete"] = true, -- 9
["Staves"] = AL["Staff"], -- 10
--["One-Handed Exotics"]= true, -- 11
--["Two-Handed Exotics"]= true, -- 12
["Fist Weapons"] = AL["Fist Weapon"], -- 13
--["Miscellaneous"] = true, -- 14
["Daggers"] = AL["Dagger"], -- 15
--["Thrown"] = true, -- 16
--["Spears"] = true, -- 17
["Crossbows"] = AL["Crossbow"], -- 18
["Wands"] = AL["Wand"], -- 19
["Fishing Pole"] = AL["Fishing Pole"], -- 20
},
--[[
["Jewelry(OBSOLETE)"] = { -- 3
["Jewelry(OBSOLETE)"] = true, -- 0
},
--]]
["Armor"] = { -- 4
["Miscellaneous"] = "", -- 0
--["Cloth"] = true, -- 1
--["Leather"] = true, -- 2
--["Mail"] = true, -- 3
--["Plate"] = true, -- 4
--["Bucklers"] = true, -- 5
["Shields"] = AL["Shield"], -- 6
--["Librams"] = true, -- 7
--["Idols"] = true, -- 8
--["Totems"] = true, -- 9
},
--[[
["Reagent"] = { -- 5
["Reagent"] = true, -- 0
},
--]]
--[[
["Projectile"] = { -- 6
["Wand(OBSOLETE)"] = true, -- 0
["Bolt(OBSOLETE)"] = true, -- 1
["Arrow"] = true, -- 2
["Bullet"] = true, -- 3
["Thrown(OBSOLETE)"] = true, -- 4
},
--]]
--[[
["Trade Goods"] = { -- 7
["Trade Goods"] = true, -- 0
["Parts"] = true, -- 1
["Explosives"] = true, -- 2
["Devices"] = true, -- 3
},
--]]
--[[
["Generic(OBSOLETE)"] = { -- 8
["Generic(OBSOLETE)"] = true, -- 0
},
--]]
--[[
["Recipe"] = { -- 9
["Book"] = true, -- 0
["Leatherworking"] = true, -- 1
["Tailoring"] = true, -- 2
["Engineering"] = true, -- 3
["Blacksmithing"] = true, -- 4
["Cooking"] = true, -- 5
["Alchemy"] = true, -- 6
["First Aid"] = true, -- 7
["Enchanting"] = true, -- 8
["Fishing"] = true, -- 9
},
--]]
["Money(OBSOLETE)"] = { -- 10
["Money(OBSOLETE)"] = IngameLocales["Currency"], -- 0
},
--[[
["Quiver"] = { -- 11
["Quiver(OBSOLETE)"] = true, -- 0
["Quiver(OBSOLETE)"] = true, -- 1
["Quiver"] = true, -- 2
["Ammo Pouch"] = true, -- 3
},
--]]
--[[
["Quest"] = { -- 12
["Quest"] = true, -- 0
},
--]]
--[[
["Key"] = { -- 13
["Key"] = true, -- 0
["Lockpick"] = true, -- 1
},
--]]
--[[
["Permanent(OBSOLETE)"] = { -- 14
["Permanent"] = true, -- 0
},
--]]
["Miscellaneous"] = { -- 15
["Junk"] = _G["MISCELLANEOUS"], -- 0
},
}
-- small info
-- 2 ways you can replace _G["INVTYPE_WEAPONMAINHAND"] with "" in the ITEM_DESC_INFO["slot"] table too hide ALL Mainhand info in description or you use the filter and generate a own name like "Main Hand, Axe"
local FILTER = {
--- examples
--{ slot = "INVTYPE_CLOAK", itemType = "Armor", itemSubType = "Cloth", __new = "HELLO THIS IS A TEST :)" }, -- This replace "Back, Cloth" with "HELLO THIS IS A TEST :)"
--{ slot = "INVTYPE_CLOAK", itemType = "Armor", itemSubType = "Cloth", __new = { slot = "INVTYPE_THROWN", itemType = "Miscellaneous", itemSubType = "Junk" }}, -- This replace "Back, Cloth" with "Thrown, Junk"
-- replace
{ slot = "INVTYPE_CLOAK", itemType = "Armor", itemSubType = "Cloth", __new = { slot = "INVTYPE_CLOAK" } }, -- This replace "Back, Cloth" with "Back"
}
local preMt
local function __indexFunc(self, key)
if not rawget(self, key) then
rawset(self, key, setmetatable({}, preMt))
end
return rawget(self, key)
end
local PreSave = {}
preMt = {
__index = __indexFunc
}
setmetatable(PreSave, preMt)
local function GetAuctionItemClasses()
return 'Weapon', 'Armor', 'Container', 'Consumable', 'Trade Goods', 'Projectile', 'Quiver', 'Recipes', 'Reagent', 'Miscellaneous'
end
local function GetAuctionItemClassesLoc()
return {
AUCTION_CATEGORY_WEAPONS,
AUCTION_CATEGORY_ARMOR,
AUCTION_CATEGORY_CONTAINERS,
AUCTION_CATEGORY_CONSUMABLES,
AUCTION_CATEGORY_TRADE_GOODS,
AUCTION_CATEGORY_PROJECTILE,
AUCTION_CATEGORY_QUIVER,
AUCTION_CATEGORY_RECIPES,
AUCTION_CATEGORY_REAGENT,
AUCTION_CATEGORY_MISCELLANEOUS,
}
end
local function Init()
local NewLocData = {
--en = {},
loc = {},
}
for iC = 0, #LOC_DATA do
local class = LOC_DATA[iC]
local className = GetItemClassInfo(iC)
--NewLocData.en[class.__name] = className
NewLocData.loc[className] = class.__name
for isC = 0, #class do
local subClass = class[isC]
local name = GetItemSubClassInfo(iC,isC)
if not NewLocData[subClass] then
--NewLocData.en[class.__name..subClass] = name
NewLocData.loc[className..name] = subClass
end
end
end
LOC_DATA = NewLocData
for i = 1,#FILTER do
FILTER[ ItemInfo.CreateDescription(FILTER[i].slot, LOC_DATA.loc[FILTER[i].itemType], LOC_DATA.loc[FILTER[i].itemType..FILTER[i].itemSubType], true) ] = type(FILTER[i].__new) == "table" and ItemInfo.CreateDescription(FILTER[i].__new.slot, LOC_DATA.loc[FILTER[i].__new.itemType], (FILTER[i].__new.itemType and FILTER[i].__new.itemSubType) and FILTER[i].__new.itemType..FILTER[i].__new.itemSubType or nil, true) or FILTER[i].__new
end
end
AtlasLoot:AddInitFunc(Init)
-- only use this if you need to ignore the filter
function ItemInfo.CreateDescription(slot, itemType, itemSubType, filterIgnore)
local desc = ""
if slot then
desc = ITEM_DESC_INFO["slot"][slot] and ITEM_DESC_INFO["slot"][slot] or ( _G[slot] or "" )
end
itemType = itemType and ( LOC_DATA.loc[itemType] or itemType ) or itemType
itemSubType = (itemType and itemSubType) and ( LOC_DATA.loc[itemType..itemSubType] or itemSubType ) or itemSubType
if itemType and itemSubType then
if ITEM_DESC_INFO[itemType] and ITEM_DESC_INFO[itemType][itemSubType] then
if ITEM_DESC_INFO[itemType][itemSubType] ~= true then
if ITEM_DESC_INFO[itemType][itemSubType] ~= "" then
desc = (desc=="" and "" or desc..", ")..ITEM_DESC_INFO[itemType][itemSubType]
end
else
desc = (desc=="" and "" or desc..", ")..itemSubType
end
else
desc = (desc=="" and "" or desc..", ")..itemSubType
end
end
if not filterIgnore then PreSave[slot or "nil"][itemType or "nil"][itemSubType or "nil"] = { true, FILTER[desc] or desc } end
return filterIgnore and desc or ( FILTER[desc] or desc )
end
function ItemInfo.GetDescription(slot, itemType, itemSubType)
return PreSave[slot or "nil"][itemType or "nil"][itemSubType or "nil"][1] == true and PreSave[slot or "nil"][itemType or "nil"][itemSubType or "nil"][2] or ItemInfo.CreateDescription(slot, itemType, itemSubType)
end
| 1 | 0.772013 | 1 | 0.772013 | game-dev | MEDIA | 0.958992 | game-dev | 0.719027 | 1 | 0.719027 |
spring/spring | 1,117 | rts/Sim/Weapons/BombDropper.h | /* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */
#ifndef BOMB_DROPPER_H
#define BOMB_DROPPER_H
#include "Weapon.h"
class CBombDropper: public CWeapon
{
CR_DECLARE_DERIVED(CBombDropper)
public:
CBombDropper(CUnit* owner = nullptr, const WeaponDef* def = nullptr, bool useTorps = false);
float GetPredictedImpactTime(float3 p) const override final;
private:
bool CanFire(bool ignoreAngleGood, bool ignoreTargetType, bool ignoreRequestedDir) const override final;
bool TestTarget(const float3 pos, const SWeaponTarget& trg) const override final;
bool TestRange(const float3 pos, const SWeaponTarget& trg) const override final;
// TODO: requires sampling parabola from aimFromPos down to dropPos
bool HaveFreeLineOfFire(const float3 srcPos, const float3 tgtPos, const SWeaponTarget& trg) const override final { return true; }
void FireImpl(const bool scriptCall) override final;
private:
/// if we should drop torpedoes
bool dropTorpedoes;
/// range of bombs (torpedoes) after they hit ground/water
float torpMoveRange;
float tracking;
};
#endif /* BOMB_DROPPER_H */
| 1 | 0.762311 | 1 | 0.762311 | game-dev | MEDIA | 0.555166 | game-dev | 0.620457 | 1 | 0.620457 |
StockSharp/AlgoTrading | 4,971 | API/1249_Reversal_Finder/CS/ReversalFinderStrategy.cs | using System;
using System.Linq;
using System.Collections.Generic;
using Ecng.Common;
using Ecng.Collections;
using Ecng.Serialization;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
namespace StockSharp.Samples.Strategies;
/// <summary>
/// Reversal Finder strategy.
/// Detects potential reversal bars based on range expansion and extreme prices.
/// Enters long when a large range candle closes near its high after making a new low.
/// Enters short when a large range candle closes near its low after making a new high.
/// </summary>
public class ReversalFinderStrategy : Strategy
{
private readonly StrategyParam<int> _lookback;
private readonly StrategyParam<int> _smaLength;
private readonly StrategyParam<decimal> _rangeMultiple;
private readonly StrategyParam<decimal> _rangeThreshold;
private readonly StrategyParam<DataType> _candleType;
private SimpleMovingAverage _rangeSma;
private Highest _highest;
private Lowest _lowest;
private decimal? _prevHigh;
private decimal? _prevLow;
/// <summary>
/// Lookback period for highest high and lowest low.
/// </summary>
public int Lookback
{
get => _lookback.Value;
set => _lookback.Value = value;
}
/// <summary>
/// SMA length for average range calculation.
/// </summary>
public int SmaLength
{
get => _smaLength.Value;
set => _smaLength.Value = value;
}
/// <summary>
/// Range multiple threshold.
/// </summary>
public decimal RangeMultiple
{
get => _rangeMultiple.Value;
set => _rangeMultiple.Value = value;
}
/// <summary>
/// Range threshold as fraction (0-1).
/// </summary>
public decimal RangeThreshold
{
get => _rangeThreshold.Value;
set => _rangeThreshold.Value = value;
}
/// <summary>
/// Candle type to process.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Initializes a new instance of <see cref="ReversalFinderStrategy"/>.
/// </summary>
public ReversalFinderStrategy()
{
_lookback = Param(nameof(Lookback), 20)
.SetGreaterThanZero()
.SetDisplay("Lookback", "Period for highest high/lowest low", "General")
.SetCanOptimize(true);
_smaLength = Param(nameof(SmaLength), 20)
.SetGreaterThanZero()
.SetDisplay("SMA Length", "Length for average range", "General")
.SetCanOptimize(true);
_rangeMultiple = Param(nameof(RangeMultiple), 1.5m)
.SetDisplay("Range Multiple", "Multiplier for average range", "General")
.SetCanOptimize(true);
_rangeThreshold = Param(nameof(RangeThreshold), 0.5m)
.SetDisplay("Range Threshold", "Fraction of range near extreme", "General")
.SetCanOptimize(true);
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(5).TimeFrame())
.SetDisplay("Candle Type", "Type of candles", "General");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_rangeSma = default;
_highest = default;
_lowest = default;
_prevHigh = default;
_prevLow = default;
}
/// <inheritdoc />
protected override void OnStarted(DateTimeOffset time)
{
base.OnStarted(time);
_rangeSma = new SimpleMovingAverage { Length = SmaLength };
_highest = new Highest { Length = Lookback };
_lowest = new Lowest { Length = Lookback };
var subscription = SubscribeCandles(CandleType);
subscription.WhenNew(ProcessCandle).Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, _rangeSma);
DrawIndicator(area, _highest);
DrawIndicator(area, _lowest);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle)
{
if (candle.State != CandleStates.Finished)
return;
var range = candle.HighPrice - candle.LowPrice;
var avgRangeValue = _rangeSma.Process(range);
IIndicatorValue highestValue = default;
IIndicatorValue lowestValue = default;
if (_prevHigh != null && _prevLow != null)
{
highestValue = _highest.Process(_prevHigh.Value);
lowestValue = _lowest.Process(_prevLow.Value);
}
_prevHigh = candle.HighPrice;
_prevLow = candle.LowPrice;
if (!avgRangeValue.IsFinal || highestValue == null || !highestValue.IsFinal || lowestValue == null || !lowestValue.IsFinal)
return;
if (!IsFormedAndOnlineAndAllowTrading())
return;
var avgRange = avgRangeValue.ToDecimal();
var highest = highestValue.ToDecimal();
var lowest = lowestValue.ToDecimal();
var rangeCondition = range >= avgRange * RangeMultiple;
var longSignal = rangeCondition && candle.LowPrice < lowest &&
candle.ClosePrice >= candle.HighPrice - range * RangeThreshold;
var shortSignal = rangeCondition && candle.HighPrice > highest &&
candle.ClosePrice <= candle.LowPrice + range * RangeThreshold;
if (longSignal && Position <= 0)
{
var volume = Volume + (Position < 0 ? -Position : 0m);
BuyMarket(volume);
}
else if (shortSignal && Position >= 0)
{
var volume = Volume + (Position > 0 ? Position : 0m);
SellMarket(volume);
}
}
}
| 1 | 0.877845 | 1 | 0.877845 | game-dev | MEDIA | 0.250015 | game-dev | 0.869613 | 1 | 0.869613 |
Vawlpe/BakuganDotC-decomp | 6,416 | src/TODO/FUN_08979710@08979710.c | #include "ULUS10536_MYTHREAD-MAIN.BIN.h"
void FUN_08979710(int param_1)
{
undefined auVar1 [16];
undefined auVar2 [16];
ushort uVar3;
undefined4 uVar4;
undefined4 uVar5;
uint *puVar6;
uint *puVar7;
int iVar8;
uint *puVar9;
short sVar10;
int iVar11;
int iVar12;
float fVar13;
uint uVar14;
undefined4 in_V74;
uint *local_a0 [4];
undefined4 local_90;
undefined4 local_8c;
undefined4 local_88;
undefined4 local_84;
undefined4 local_80;
undefined4 local_7c;
undefined4 local_78;
undefined4 local_74;
float local_64;
float local_60;
float local_50;
float local_4c;
if (*(int *)(param_1 + 0x18) != 0) {
FUN_0890a520(param_1);
uVar4 = FUN_089f2178(0x42480000);
FUN_089f5474(*(undefined4 *)(param_1 + 0x18),1);
FUN_089f5084(*(undefined4 *)(param_1 + 0x18),uVar4);
uVar4 = FUN_089f2178(0x43480000);
FUN_089f5474(*(undefined4 *)(param_1 + 0x18),2);
FUN_089f5084(*(undefined4 *)(param_1 + 0x18),uVar4);
uVar4 = FUN_089f2178(0x43960000);
FUN_089f5474(*(undefined4 *)(param_1 + 0x18),4);
FUN_089f5084(*(undefined4 *)(param_1 + 0x18),uVar4);
uVar4 = FUN_089f2178(0x43c80000);
FUN_089f5474(*(undefined4 *)(param_1 + 0x18),8);
FUN_089f5084(*(undefined4 *)(param_1 + 0x18),uVar4);
}
iVar12 = 0;
iVar11 = param_1;
do {
if (*(char *)(iVar11 + 0xef0) != '\0') {
local_80 = 0;
local_7c = 0;
local_78 = 0x43f00000;
local_74 = 0x43880000;
if (iVar12 == 0) {
uVar4 = FUN_089f2178(0x437a0000);
}
else {
uVar4 = FUN_089f2178(0x43af0000);
}
uVar5 = FUN_089f1308(uVar4);
uVar5 = FUN_089f1418(uVar5);
uVar5 = FUN_089e3014(DAT_08ac5c8c,uVar5,0xffffffff);
uVar5 = FUN_089f202c(uVar5,&DAT_08b00190,0,1);
local_84 = *(undefined4 *)(iVar11 + 0xef4);
local_90 = 0;
local_8c = 0;
local_88 = 0;
uVar5 = FUN_089f2c88(uVar4,uVar5,&local_80,&local_90);
FUN_089f13c8(uVar4,uVar5);
}
iVar12 = iVar12 + 1;
iVar11 = iVar11 + 0x10;
} while (iVar12 < 2);
uVar4 = FUN_089f2178(0x41a00000);
local_a0[0] = (uint *)FUN_089f1308(uVar4);
iVar12 = 0;
iVar11 = param_1;
do {
if ((*(int *)(iVar11 + 0x12a4) != 0) && (*(char *)(param_1 + iVar12 + 0x12c0) == '\0')) {
local_a0[0] = (uint *)FUN_089f1490(local_a0[0],*(undefined4 *)(iVar11 + 0x1288),1);
fVar13 = DAT_08b0019c;
if (1.0 < DAT_08b0019c) {
fVar13 = 1.0;
}
if (fVar13 <= 0.0001) {
uVar14 = 0xcf000000;
local_60 = 10000.0;
local_64 = 10000.0;
}
else {
fVar13 = (1.0 - fVar13) * 800.0 + 1.0;
if (0.0 < fVar13) {
local_60 = 1.0 / fVar13;
}
else if (fVar13 < 0.0) {
local_60 = 1.0 / fVar13;
}
else {
local_60 = 0.0;
}
auVar1._12_4_ = DAT_08b0019c;
auVar1._8_4_ = DAT_08b00198;
auVar1._4_4_ = DAT_08b00194;
auVar1._0_4_ = DAT_08b00190;
auVar1 = vsat0_q(auVar1);
auVar1 = vscl_q(auVar1,in_V74);
auVar1 = vf2iz_q(auVar1,0x17);
uVar14 = vi2uc_q(auVar1);
uVar14 = uVar14 & 0xffffff | 0xcf000000;
local_64 = fVar13 + 20000.0;
}
*local_a0[0] = uVar14;
local_a0[0][1] = (uint)local_64 >> 8 | 0xcd000000;
local_a0[0][2] = (uint)local_60 >> 8 | 0xce000000;
local_a0[0] = local_a0[0] + 3;
iVar8 = *(int *)(*(int *)(iVar11 + 0x12a4) + 0x14);
(**(code **)(iVar8 + 0x44))
(*(int *)(iVar11 + 0x12a4) + (int)*(short *)(iVar8 + 0x40),local_a0);
}
iVar12 = iVar12 + 1;
iVar11 = iVar11 + 4;
} while (iVar12 < 7);
puVar9 = local_a0[0] + 2;
puVar6 = local_a0[0] + 0x62;
*local_a0[0] = ((uint)puVar6 >> 0x18 & 0xf) << 0x10 | 0x10000000;
local_a0[0][1] = (uint)puVar6 & 0xffffff | 0x8000000;
iVar11 = 0;
puVar7 = puVar9;
do {
uVar3 = (ushort)iVar11 & 1;
if (iVar11 < 0) {
uVar3 = -uVar3;
}
*(ushort *)(puVar7 + 1) = ((short)(iVar11 / 2) + uVar3) * 0x20;
uVar3 = (ushort)iVar11 & 1;
if (iVar11 < 0) {
sVar10 = uVar3 * -0x110;
}
else {
sVar10 = uVar3 * 0x110;
}
*(short *)((int)puVar7 + 6) = sVar10;
*(undefined2 *)(puVar7 + 2) = 0;
iVar11 = iVar11 + 1;
puVar7 = puVar7 + 3;
} while (iVar11 < 0x20);
*puVar6 = 0xd3000401;
local_a0[0][99] = 0x1280011c;
puVar7 = local_a0[0] + 100;
if (puVar9 != (uint *)0x0) {
*puVar7 = ((uint)puVar9 >> 0x18 & 0xf) << 0x10 | 0x10000000;
local_a0[0][0x65] = (uint)puVar9 & 0xffffff | 0x1000000;
puVar7 = local_a0[0] + 0x66;
}
*puVar7 = 0x4060020;
puVar7[1] = 0xd3000000;
local_a0[0] = puVar7 + 2;
FUN_089f13c8(uVar4);
uVar4 = FUN_089f2178(0x43c30000);
local_a0[0] = (uint *)FUN_089f1308(uVar4);
iVar12 = 0;
iVar11 = param_1;
do {
if ((*(int *)(iVar11 + 0x12a4) != 0) && (*(char *)(param_1 + iVar12 + 0x12c0) == '\x01')) {
local_a0[0] = (uint *)FUN_089f1490(local_a0[0],*(undefined4 *)(iVar11 + 0x1288),1);
fVar13 = DAT_08b0019c;
if (1.0 < DAT_08b0019c) {
fVar13 = 1.0;
}
if (fVar13 <= 0.0001) {
local_4c = 10000.0;
uVar14 = 0xcf000000;
local_50 = local_4c;
}
else {
fVar13 = (1.0 - fVar13) * 800.0 + 1.0;
if (0.0 < fVar13) {
local_4c = 1.0 / fVar13;
}
else if (fVar13 < 0.0) {
local_4c = 1.0 / fVar13;
}
else {
local_4c = 0.0;
}
auVar2._12_4_ = DAT_08b0019c;
auVar2._8_4_ = DAT_08b00198;
auVar2._4_4_ = DAT_08b00194;
auVar2._0_4_ = DAT_08b00190;
auVar1 = vsat0_q(auVar2);
auVar1 = vscl_q(auVar1,in_V74);
auVar1 = vf2iz_q(auVar1,0x17);
uVar14 = vi2uc_q(auVar1);
uVar14 = uVar14 & 0xffffff | 0xcf000000;
local_50 = fVar13 + 20000.0;
}
*local_a0[0] = uVar14;
local_a0[0][1] = (uint)local_50 >> 8 | 0xcd000000;
local_a0[0][2] = (uint)local_4c >> 8 | 0xce000000;
local_a0[0] = local_a0[0] + 3;
iVar8 = *(int *)(*(int *)(iVar11 + 0x12a4) + 0x14);
(**(code **)(iVar8 + 0x44))
(*(int *)(iVar11 + 0x12a4) + (int)*(short *)(iVar8 + 0x40),local_a0);
}
iVar12 = iVar12 + 1;
iVar11 = iVar11 + 4;
} while (iVar12 < 7);
FUN_089f13c8(uVar4,local_a0[0]);
FUN_0897963c(param_1);
return;
}
| 1 | 0.527408 | 1 | 0.527408 | game-dev | MEDIA | 0.671054 | game-dev | 0.870913 | 1 | 0.870913 |
Felix4Weber/java-stellar-sdk | 1,871 | src/main/java/org/stellar/sdk/xdr/SCContractInstance.java | // Automatically generated by xdrgen
// DO NOT EDIT or your changes may be overwritten
package org.stellar.sdk.xdr;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.stellar.sdk.Base64Factory;
/**
* SCContractInstance's original definition in the XDR file is:
*
* <pre>
* struct SCContractInstance {
* ContractExecutable executable;
* SCMap* storage;
* };
* </pre>
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder(toBuilder = true)
public class SCContractInstance implements XdrElement {
private ContractExecutable executable;
private SCMap storage;
public void encode(XdrDataOutputStream stream) throws IOException {
executable.encode(stream);
if (storage != null) {
stream.writeInt(1);
storage.encode(stream);
} else {
stream.writeInt(0);
}
}
public static SCContractInstance decode(XdrDataInputStream stream) throws IOException {
SCContractInstance decodedSCContractInstance = new SCContractInstance();
decodedSCContractInstance.executable = ContractExecutable.decode(stream);
int storagePresent = stream.readInt();
if (storagePresent != 0) {
decodedSCContractInstance.storage = SCMap.decode(stream);
}
return decodedSCContractInstance;
}
public static SCContractInstance fromXdrBase64(String xdr) throws IOException {
byte[] bytes = Base64Factory.getInstance().decode(xdr);
return fromXdrByteArray(bytes);
}
public static SCContractInstance fromXdrByteArray(byte[] xdr) throws IOException {
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(xdr);
XdrDataInputStream xdrDataInputStream = new XdrDataInputStream(byteArrayInputStream);
return decode(xdrDataInputStream);
}
}
| 1 | 0.892386 | 1 | 0.892386 | game-dev | MEDIA | 0.610429 | game-dev | 0.918351 | 1 | 0.918351 |
kripken/box2d.js | 8,087 | Box2D_v2.3.1/Box2D/Dynamics/Joints/b2MotorJoint.cpp | /*
* Copyright (c) 2006-2012 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 <Box2D/Dynamics/Joints/b2MotorJoint.h>
#include <Box2D/Dynamics/b2Body.h>
#include <Box2D/Dynamics/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 b2MotorJointDef::Initialize(b2Body* bA, b2Body* bB)
{
bodyA = bA;
bodyB = bB;
b2Vec2 xB = bodyB->GetPosition();
linearOffset = bodyA->GetLocalPoint(xB);
float32 angleA = bodyA->GetAngle();
float32 angleB = bodyB->GetAngle();
angularOffset = angleB - angleA;
}
b2MotorJoint::b2MotorJoint(const b2MotorJointDef* def)
: b2Joint(def)
{
m_linearOffset = def->linearOffset;
m_angularOffset = def->angularOffset;
m_linearImpulse.SetZero();
m_angularImpulse = 0.0f;
m_maxForce = def->maxForce;
m_maxTorque = def->maxTorque;
m_correctionFactor = def->correctionFactor;
}
void b2MotorJoint::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;
b2Vec2 cA = data.positions[m_indexA].c;
float32 aA = data.positions[m_indexA].a;
b2Vec2 vA = data.velocities[m_indexA].v;
float32 wA = data.velocities[m_indexA].w;
b2Vec2 cB = data.positions[m_indexB].c;
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_localCenterA);
m_rB = b2Mul(qB, -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;
}
m_linearError = cB + m_rB - cA - m_rA - b2Mul(qA, m_linearOffset);
m_angularError = aB - aA - m_angularOffset;
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 b2MotorJoint::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;
float32 inv_h = data.step.inv_dt;
// Solve angular friction
{
float32 Cdot = wB - wA + inv_h * m_correctionFactor * m_angularError;
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) + inv_h * m_correctionFactor * m_linearError;
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 b2MotorJoint::SolvePositionConstraints(const b2SolverData& data)
{
B2_NOT_USED(data);
return true;
}
b2Vec2 b2MotorJoint::GetAnchorA() const
{
return m_bodyA->GetPosition();
}
b2Vec2 b2MotorJoint::GetAnchorB() const
{
return m_bodyB->GetPosition();
}
b2Vec2 b2MotorJoint::GetReactionForce(float32 inv_dt) const
{
return inv_dt * m_linearImpulse;
}
float32 b2MotorJoint::GetReactionTorque(float32 inv_dt) const
{
return inv_dt * m_angularImpulse;
}
void b2MotorJoint::SetMaxForce(float32 force)
{
b2Assert(b2IsValid(force) && force >= 0.0f);
m_maxForce = force;
}
float32 b2MotorJoint::GetMaxForce() const
{
return m_maxForce;
}
void b2MotorJoint::SetMaxTorque(float32 torque)
{
b2Assert(b2IsValid(torque) && torque >= 0.0f);
m_maxTorque = torque;
}
float32 b2MotorJoint::GetMaxTorque() const
{
return m_maxTorque;
}
void b2MotorJoint::SetCorrectionFactor(float32 factor)
{
b2Assert(b2IsValid(factor) && 0.0f <= factor && factor <= 1.0f);
m_correctionFactor = factor;
}
float32 b2MotorJoint::GetCorrectionFactor() const
{
return m_correctionFactor;
}
void b2MotorJoint::SetLinearOffset(const b2Vec2& linearOffset)
{
if (linearOffset.x != m_linearOffset.x || linearOffset.y != m_linearOffset.y)
{
m_bodyA->SetAwake(true);
m_bodyB->SetAwake(true);
m_linearOffset = linearOffset;
}
}
const b2Vec2& b2MotorJoint::GetLinearOffset() const
{
return m_linearOffset;
}
void b2MotorJoint::SetAngularOffset(float32 angularOffset)
{
if (angularOffset != m_angularOffset)
{
m_bodyA->SetAwake(true);
m_bodyB->SetAwake(true);
m_angularOffset = angularOffset;
}
}
float32 b2MotorJoint::GetAngularOffset() const
{
return m_angularOffset;
}
void b2MotorJoint::Dump()
{
int32 indexA = m_bodyA->m_islandIndex;
int32 indexB = m_bodyB->m_islandIndex;
b2Log(" b2MotorJointDef 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.linearOffset.Set(%.15lef, %.15lef);\n", m_linearOffset.x, m_linearOffset.y);
b2Log(" jd.angularOffset = %.15lef;\n", m_angularOffset);
b2Log(" jd.maxForce = %.15lef;\n", m_maxForce);
b2Log(" jd.maxTorque = %.15lef;\n", m_maxTorque);
b2Log(" jd.correctionFactor = %.15lef;\n", m_correctionFactor);
b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index);
}
| 1 | 0.929799 | 1 | 0.929799 | game-dev | MEDIA | 0.987672 | game-dev | 0.972026 | 1 | 0.972026 |
clickcrystals-development/ClickCrystals | 2,509 | src/main/java/io/github/itzispyder/clickcrystals/mixins/MixinClientPlayNetworkHandler.java | package io.github.itzispyder.clickcrystals.mixins;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import io.github.itzispyder.clickcrystals.ClickCrystals;
import io.github.itzispyder.clickcrystals.Global;
import io.github.itzispyder.clickcrystals.commands.Command;
import io.github.itzispyder.clickcrystals.events.events.client.ChatCommandEvent;
import io.github.itzispyder.clickcrystals.events.events.client.ChatReceiveEvent;
import io.github.itzispyder.clickcrystals.events.events.client.ChatSendEvent;
import net.minecraft.client.network.ClientPlayNetworkHandler;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(ClientPlayNetworkHandler.class)
public abstract class MixinClientPlayNetworkHandler implements Global {
@Shadow
public abstract void sendChatMessage(String content);
@Unique
private static boolean ignoreChatMessage = false;
@Inject(method = "sendChatMessage", at = @At("HEAD"), cancellable = true)
public void sendChatMessage(String content, CallbackInfo ci) {
String prefix = ClickCrystals.commandPrefix.getKeyName();
prefix = prefix.equals("NONE") ? "'" : prefix;
if (content.startsWith(prefix)) {
if (content.startsWith(prefix + prefix)) {
return;
}
try {
Command.dispatch(content.substring(prefix.length()));
}
catch (CommandSyntaxException ex) {
Command.error(ex.getMessage());
}
ci.cancel();
return;
}
if (!ignoreChatMessage) {
ChatSendEvent event = new ChatSendEvent(content);
system.eventBus.pass(event);
if (!event.isCancelled()) {
ignoreChatMessage = true;
sendChatMessage(event.getMessage());
ignoreChatMessage = false;
}
ChatReceiveEvent.lock();
ci.cancel();
}
}
@Inject(method = "sendChatCommand", at = @At("HEAD"), cancellable = true)
public void sendCommand(String command, CallbackInfo ci) {
ChatCommandEvent event = new ChatCommandEvent(command);
system.eventBus.pass(event);
if (event.isCancelled()) ci.cancel();
}
}
| 1 | 0.861312 | 1 | 0.861312 | game-dev | MEDIA | 0.706867 | game-dev,web-backend | 0.880151 | 1 | 0.880151 |
badoo/hprof-tools | 1,818 | hprof-viewer/src/main/java/com/badoo/hprof/viewer/factory/IntentFactory.java | package com.badoo.hprof.viewer.factory;
import com.badoo.hprof.library.model.Instance;
import com.badoo.hprof.viewer.MemoryDump;
import com.badoo.hprof.viewer.android.Bundle;
import com.badoo.hprof.viewer.android.Intent;
import com.badoo.hprof.viewer.factory.classdefs.IntentClassDef;
import java.io.IOException;
import java.util.Collections;
import javax.annotation.Nonnull;
/**
* Factory class for creating Intent based on instance dumps
* <p/>
* Created by Erik Andre on 08/12/15.
*/
public class IntentFactory extends BaseClassFactory<IntentClassDef, Intent> {
private static IntentFactory instance;
public static IntentFactory getInstance(@Nonnull MemoryDump data, @Nonnull Environment env) {
if (instance == null) {
instance = new IntentFactory(data, env);
}
return instance;
}
private IntentFactory(@Nonnull MemoryDump data, @Nonnull Environment env) {
super(data, env);
}
@Override
protected Intent create(@Nonnull Instance instance, @Nonnull MemoryDump data, @Nonnull Environment env, @Nonnull IntentClassDef classDef) throws IOException {
Instance actionInstance = data.instances.get(instance.getObjectField(classDef.action, data.classes));
String action = StringFactory.getInstance(data, env).create(actionInstance);
Instance bundleInstance = data.instances.get(instance.getObjectField(classDef.extras, data.classes));
Bundle extras = BundleFactory.getInstance(data, env).create(bundleInstance);
if (extras == null) {
extras = new Bundle(Collections.emptyMap());
}
return new Intent(action, extras);
}
@Nonnull
@Override
protected IntentClassDef createClassDef(@Nonnull MemoryDump data) {
return new IntentClassDef(data);
}
}
| 1 | 0.798585 | 1 | 0.798585 | game-dev | MEDIA | 0.177371 | game-dev | 0.804953 | 1 | 0.804953 |
Magic-Nipples/Duake | 5,933 | dlls/enforcer.cpp | //
// enforcer.cpp
//
#include "extdll.h"
#include "util.h"
#include "cbase.h"
#include "monster.h"
#include "items.h"
#include "skill.h"
#include "player.h"
#include "gamerules.h"
#include "decals.h"
#include "weapons.h"
class CEnforcer : public CQuakeMonster
{
public:
void Spawn( void );
void Precache( void );
BOOL MonsterHasMissileAttack( void ) { return TRUE; }
void MonsterMissileAttack( void );
void MonsterAttack( void );
void MonsterKilled( entvars_t *pevAttacker, int iGib );
void MonsterPain( CBaseEntity *pAttacker, float flDamage );
int BloodColor( void ) { return BLOOD_COLOR_RED; }
void MonsterSight( void );
void MonsterIdle( void );
void MonsterWalk( void );
void MonsterRun( void );
void MonsterFire( void );
void PainSound( void );
void IdleSound( void );
void DeathSound( void );
void MonsterEvents(void);
static const char *pSightSounds[];
static const char *pPainSounds[];
virtual int Save( CSave &save );
virtual int Restore( CRestore &restore );
static TYPEDESCRIPTION m_SaveData[];
int m_fAttackFinished;
int m_fInAttack;
};
LINK_ENTITY_TO_CLASS( monster_enforcer, CEnforcer );
TYPEDESCRIPTION CEnforcer :: m_SaveData[] =
{
DEFINE_FIELD( CEnforcer, m_fInAttack, FIELD_CHARACTER ),
DEFINE_FIELD( CEnforcer, m_fAttackFinished, FIELD_BOOLEAN ),
}; IMPLEMENT_SAVERESTORE( CEnforcer, CQuakeMonster );
const char *CEnforcer::pPainSounds[] =
{
"enforcer/pain1.wav",
"enforcer/pain2.wav",
};
const char *CEnforcer::pSightSounds[] =
{
"enforcer/sight1.wav",
"enforcer/sight2.wav",
"enforcer/sight3.wav",
"enforcer/sight4.wav",
};
void CEnforcer :: MonsterSight( void )
{
EMIT_SOUND_ARRAY_DYN( CHAN_VOICE, pSightSounds, ATTN_NORM );
}
void CEnforcer :: MonsterIdle( void )
{
m_iAIState = STATE_IDLE;
SetActivity( ACT_IDLE );
m_flMonsterSpeed = 0;
}
void CEnforcer :: MonsterWalk( void )
{
m_iAIState = STATE_WALK;
SetActivity( ACT_WALK );
m_flMonsterSpeed = 3;
}
void CEnforcer :: MonsterRun( void )
{
m_iAIState = STATE_RUN;
SetActivity( ACT_RUN );
m_flMonsterSpeed = 12;
}
void CEnforcer :: MonsterMissileAttack( void )
{
m_iAIState = STATE_ATTACK;
SetActivity( ACT_RANGE_ATTACK1 );
}
void CEnforcer :: MonsterPain( CBaseEntity *pAttacker, float flDamage )
{
float random;
if( pev->pain_finished > gpGlobals->time )
return;
EMIT_SOUND_ARRAY_DYN( CHAN_VOICE, pPainSounds, ATTN_NORM );
m_iAIState = STATE_PAIN;
m_flMonsterSpeed = 0;
random = RANDOM_FLOAT(0.0f, 1.0f);
if (random < 0.2)
{
SetActivity(ACT_FLINCH1);
pev->pain_finished = gpGlobals->time + 1;
}
else if (random < 0.4)
{
SetActivity(ACT_FLINCH2);
pev->pain_finished = gpGlobals->time + 1;
}
else if (random < 0.7)
{
SetActivity(ACT_FLINCH2);
pev->pain_finished = gpGlobals->time + 1;
}
else
{
SetActivity(ACT_FLINCH3);
pev->pain_finished = gpGlobals->time + 2;
}
}
void CEnforcer :: MonsterKilled( entvars_t *pevAttacker, int iGib )
{
CItemAmmo::DropAmmo(this, IT_NAILS, false);
if( ShouldGibMonster( iGib ))
{
EMIT_SOUND( edict(), CHAN_VOICE, "player/udeath.wav", 1.0, ATTN_NORM );
CGib::ThrowHead ("models/h_mega.mdl", pev);
CGib::ThrowGib ("models/gib1.mdl", pev);
CGib::ThrowGib ("models/gib2.mdl", pev);
CGib::ThrowGib ("models/gib3.mdl", pev);
UTIL_Remove( this );
return;
}
// regular death
EMIT_SOUND( edict(), CHAN_VOICE, "enforcer/death1.wav", 1.0, ATTN_NORM );
}
void CEnforcer :: MonsterAttack( void )
{
if( m_fAttackFinished )
{
m_fAttackFinished = FALSE;
m_fInAttack = FALSE;
if( CheckRefire())
MonsterMissileAttack ();
else
MonsterRun();
}
AI_Face();
}
void CEnforcer :: MonsterFire( void )
{
if (m_fInAttack > 6) return; //if( m_fInAttack > 1 ) return;
AI_Face();
UTIL_MakeVectors(pev->angles);
#if 0
EMIT_SOUND(edict(), CHAN_VOICE, "enforcer/enfire.wav", 1.0, ATTN_NORM);
Vector vecOrg = pev->origin + gpGlobals->v_forward * 30.0f + gpGlobals->v_right * 8.5 + Vector( 0, 0, 16 );
Vector vecDir = (m_hEnemy->pev->origin - pev->origin).Normalize();
CLaser::LaunchLaser(vecOrg, vecDir, this);
#else
EMIT_SOUND(edict(), CHAN_VOICE, "weapons/chaingun_fire.wav", 1, ATTN_NORM);
Vector vecDir = ((m_hEnemy->pev->origin - m_hEnemy->pev->velocity * 0.075f) - pev->origin).Normalize();
CBasePlayer::FireBullets(pev, 1, vecDir, Vector(0.075, 0.075, 0), BULLET_FLAG_NPC);
#endif
pev->effects |= EF_MUZZLEFLASH;
m_fInAttack++;
}
//=========================================================
// Spawn
//=========================================================
void CEnforcer :: Spawn( void )
{
if( !g_pGameRules->FAllowMonsters( ) || !g_registered )
{
REMOVE_ENTITY( ENT(pev) );
return;
}
Precache( );
SET_MODEL(ENT(pev), "progs/enforcer.mdl");
UTIL_SetSize( pev, Vector( -16, -16, -24 ), Vector( 16, 16, 40 ));
pev->solid = SOLID_SLIDEBOX;
pev->movetype = MOVETYPE_STEP;
pev->health = 80;
WalkMonsterInit ();
}
//=========================================================
// Precache - precaches all resources this monster needs
//=========================================================
void CEnforcer :: Precache()
{
PRECACHE_MODEL( "progs/enforcer.mdl" );
PRECACHE_MODEL( "models/h_mega.mdl" );
PRECACHE_MODEL("sprites/items/wchaingun.spr");
PRECACHE_SOUND_ARRAY( pSightSounds );
PRECACHE_SOUND_ARRAY( pPainSounds );
PRECACHE_SOUND( "enforcer/death1.wav" );
PRECACHE_SOUND( "enforcer/enfire.wav" );
PRECACHE_SOUND( "enforcer/enfstop.wav" );
PRECACHE_SOUND( "enforcer/idle1.wav" );
}
void CEnforcer::MonsterEvents(void)
{
switch (m_Activity)
{
case ACT_RANGE_ATTACK1:
//if (pev->frame == 36)
//MonsterFire();
if (pev->frame >= 34 && pev->frame < 40)
MonsterFire();
if (pev->frame == 40)
{
m_fInAttack = 2;
m_fAttackFinished = TRUE;
}
break;
case ACT_IDLE:
if (pev->frame == 4)
{
if (RANDOM_FLOAT(0.0f, 1.0f) < 0.2f)
EMIT_SOUND(edict(), CHAN_VOICE, "enforcer/idle1.wav", 1.0, ATTN_IDLE);
}
break;
}
} | 1 | 0.941009 | 1 | 0.941009 | game-dev | MEDIA | 0.973025 | game-dev | 0.949759 | 1 | 0.949759 |
randomguy3725/MoonLight | 12,508 | src/main/java/net/minecraft/block/BlockLiquid.java | package net.minecraft.block;
import java.util.Random;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.PropertyInteger;
import net.minecraft.block.state.BlockState;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.Entity;
import net.minecraft.init.Blocks;
import net.minecraft.item.Item;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.BlockPos;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumParticleTypes;
import net.minecraft.util.EnumWorldBlockLayer;
import net.minecraft.util.MathHelper;
import net.minecraft.util.Vec3;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraft.world.biome.BiomeColorHelper;
public abstract class BlockLiquid extends Block
{
public static final PropertyInteger LEVEL = PropertyInteger.create("level", 0, 15);
protected BlockLiquid(Material materialIn)
{
super(materialIn);
this.setDefaultState(this.blockState.getBaseState().withProperty(LEVEL, 0));
this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F);
this.setTickRandomly(true);
}
public boolean isPassable(IBlockAccess worldIn, BlockPos pos)
{
return this.blockMaterial != Material.lava;
}
public int colorMultiplier(IBlockAccess worldIn, BlockPos pos, int renderPass)
{
return this.blockMaterial == Material.water ? BiomeColorHelper.getWaterColorAtPos(worldIn, pos) : 16777215;
}
public static float getLiquidHeightPercent(int meta)
{
if (meta >= 8)
{
meta = 0;
}
return (float)(meta + 1) / 9.0F;
}
protected int getLevel(IBlockAccess worldIn, BlockPos pos)
{
return worldIn.getBlockState(pos).getBlock().getMaterial() == this.blockMaterial ? worldIn.getBlockState(pos).getValue(LEVEL) : -1;
}
protected int getEffectiveFlowDecay(IBlockAccess worldIn, BlockPos pos)
{
int i = this.getLevel(worldIn, pos);
return i >= 8 ? 0 : i;
}
public boolean isFullCube()
{
return false;
}
public boolean isOpaqueCube()
{
return false;
}
public boolean canCollideCheck(IBlockState state, boolean hitIfLiquid)
{
return hitIfLiquid && state.getValue(LEVEL) == 0;
}
public boolean isBlockSolid(IBlockAccess worldIn, BlockPos pos, EnumFacing side)
{
Material material = worldIn.getBlockState(pos).getBlock().getMaterial();
return material != this.blockMaterial && (side == EnumFacing.UP || (material != Material.ice && super.isBlockSolid(worldIn, pos, side)));
}
public boolean shouldSideBeRendered(IBlockAccess worldIn, BlockPos pos, EnumFacing side)
{
return worldIn.getBlockState(pos).getBlock().getMaterial() != this.blockMaterial && (side == EnumFacing.UP || super.shouldSideBeRendered(worldIn, pos, side));
}
public boolean shouldRenderSides(IBlockAccess blockAccess, BlockPos pos)
{
for (int i = -1; i <= 1; ++i)
{
for (int j = -1; j <= 1; ++j)
{
IBlockState iblockstate = blockAccess.getBlockState(pos.add(i, 0, j));
Block block = iblockstate.getBlock();
Material material = block.getMaterial();
if (material != this.blockMaterial && !block.isFullBlock())
{
return true;
}
}
}
return false;
}
public AxisAlignedBB getCollisionBoundingBox(World worldIn, BlockPos pos, IBlockState state)
{
return null;
}
public int getRenderType()
{
return 1;
}
public Item getItemDropped(IBlockState state, Random rand, int fortune)
{
return null;
}
public int quantityDropped(Random random)
{
return 0;
}
protected Vec3 getFlowVector(IBlockAccess worldIn, BlockPos pos)
{
Vec3 vec3 = new Vec3(0.0D, 0.0D, 0.0D);
int i = this.getEffectiveFlowDecay(worldIn, pos);
for (EnumFacing enumfacing : EnumFacing.Plane.HORIZONTAL)
{
BlockPos blockpos = pos.offset(enumfacing);
int j = this.getEffectiveFlowDecay(worldIn, blockpos);
if (j < 0)
{
if (!worldIn.getBlockState(blockpos).getBlock().getMaterial().blocksMovement())
{
j = this.getEffectiveFlowDecay(worldIn, blockpos.down());
if (j >= 0)
{
int k = j - (i - 8);
vec3 = vec3.addVector((blockpos.getX() - pos.getX()) * k, (blockpos.getY() - pos.getY()) * k, (blockpos.getZ() - pos.getZ()) * k);
}
}
}
else if (j >= 0)
{
int l = j - i;
vec3 = vec3.addVector((blockpos.getX() - pos.getX()) * l, (blockpos.getY() - pos.getY()) * l, (blockpos.getZ() - pos.getZ()) * l);
}
}
if (worldIn.getBlockState(pos).getValue(LEVEL) >= 8)
{
for (EnumFacing enumfacing1 : EnumFacing.Plane.HORIZONTAL)
{
BlockPos blockpos1 = pos.offset(enumfacing1);
if (this.isBlockSolid(worldIn, blockpos1, enumfacing1) || this.isBlockSolid(worldIn, blockpos1.up(), enumfacing1))
{
vec3 = vec3.normalize().addVector(0.0D, -6.0D, 0.0D);
break;
}
}
}
return vec3.normalize();
}
public Vec3 modifyAcceleration(World worldIn, BlockPos pos, Entity entityIn, Vec3 motion)
{
return motion.add(this.getFlowVector(worldIn, pos));
}
public int tickRate(World worldIn)
{
return this.blockMaterial == Material.water ? 5 : (this.blockMaterial == Material.lava ? (worldIn.provider.getHasNoSky() ? 10 : 30) : 0);
}
public int getMixedBrightnessForBlock(IBlockAccess worldIn, BlockPos pos)
{
int i = worldIn.getCombinedLight(pos, 0);
int j = worldIn.getCombinedLight(pos.up(), 0);
int k = i & 255;
int l = j & 255;
int i1 = i >> 16 & 255;
int j1 = j >> 16 & 255;
return (k > l ? k : l) | (i1 > j1 ? i1 : j1) << 16;
}
public EnumWorldBlockLayer getBlockLayer()
{
return this.blockMaterial == Material.water ? EnumWorldBlockLayer.TRANSLUCENT : EnumWorldBlockLayer.SOLID;
}
public void randomDisplayTick(World worldIn, BlockPos pos, IBlockState state, Random rand)
{
double d0 = pos.getX();
double d1 = pos.getY();
double d2 = pos.getZ();
if (this.blockMaterial == Material.water)
{
int i = state.getValue(LEVEL);
if (i > 0 && i < 8)
{
if (rand.nextInt(64) == 0)
{
worldIn.playSound(d0 + 0.5D, d1 + 0.5D, d2 + 0.5D, "liquid.water", rand.nextFloat() * 0.25F + 0.75F, rand.nextFloat() + 0.5F, false);
}
}
else if (rand.nextInt(10) == 0)
{
worldIn.spawnParticle(EnumParticleTypes.SUSPENDED, d0 + (double)rand.nextFloat(), d1 + (double)rand.nextFloat(), d2 + (double)rand.nextFloat(), 0.0D, 0.0D, 0.0D);
}
}
if (this.blockMaterial == Material.lava && worldIn.getBlockState(pos.up()).getBlock().getMaterial() == Material.air && !worldIn.getBlockState(pos.up()).getBlock().isOpaqueCube())
{
if (rand.nextInt(100) == 0)
{
double d8 = d0 + (double)rand.nextFloat();
double d4 = d1 + this.maxY;
double d6 = d2 + (double)rand.nextFloat();
worldIn.spawnParticle(EnumParticleTypes.LAVA, d8, d4, d6, 0.0D, 0.0D, 0.0D);
worldIn.playSound(d8, d4, d6, "liquid.lavapop", 0.2F + rand.nextFloat() * 0.2F, 0.9F + rand.nextFloat() * 0.15F, false);
}
if (rand.nextInt(200) == 0)
{
worldIn.playSound(d0, d1, d2, "liquid.lava", 0.2F + rand.nextFloat() * 0.2F, 0.9F + rand.nextFloat() * 0.15F, false);
}
}
if (rand.nextInt(10) == 0 && World.doesBlockHaveSolidTopSurface(worldIn, pos.down()))
{
Material material = worldIn.getBlockState(pos.down(2)).getBlock().getMaterial();
if (!material.blocksMovement() && !material.isLiquid())
{
double d3 = d0 + (double)rand.nextFloat();
double d5 = d1 - 1.05D;
double d7 = d2 + (double)rand.nextFloat();
if (this.blockMaterial == Material.water)
{
worldIn.spawnParticle(EnumParticleTypes.DRIP_WATER, d3, d5, d7, 0.0D, 0.0D, 0.0D);
}
else
{
worldIn.spawnParticle(EnumParticleTypes.DRIP_LAVA, d3, d5, d7, 0.0D, 0.0D, 0.0D);
}
}
}
}
public static double getFlowDirection(IBlockAccess worldIn, BlockPos pos, Material materialIn)
{
Vec3 vec3 = getFlowingBlock(materialIn).getFlowVector(worldIn, pos);
return vec3.xCoord == 0.0D && vec3.zCoord == 0.0D ? -1000.0D : MathHelper.atan2(vec3.zCoord, vec3.xCoord) - (Math.PI / 2D);
}
public void onBlockAdded(World worldIn, BlockPos pos, IBlockState state)
{
this.checkForMixing(worldIn, pos, state);
}
public void onNeighborBlockChange(World worldIn, BlockPos pos, IBlockState state, Block neighborBlock)
{
this.checkForMixing(worldIn, pos, state);
}
public boolean checkForMixing(World worldIn, BlockPos pos, IBlockState state)
{
if (this.blockMaterial == Material.lava)
{
boolean flag = false;
for (EnumFacing enumfacing : EnumFacing.values())
{
if (enumfacing != EnumFacing.DOWN && worldIn.getBlockState(pos.offset(enumfacing)).getBlock().getMaterial() == Material.water)
{
flag = true;
break;
}
}
if (flag)
{
Integer integer = state.getValue(LEVEL);
if (integer == 0)
{
worldIn.setBlockState(pos, Blocks.obsidian.getDefaultState());
this.triggerMixEffects(worldIn, pos);
return true;
}
if (integer <= 4)
{
worldIn.setBlockState(pos, Blocks.cobblestone.getDefaultState());
this.triggerMixEffects(worldIn, pos);
return true;
}
}
}
return false;
}
protected void triggerMixEffects(World worldIn, BlockPos pos)
{
double d0 = pos.getX();
double d1 = pos.getY();
double d2 = pos.getZ();
worldIn.playSoundEffect(d0 + 0.5D, d1 + 0.5D, d2 + 0.5D, "random.fizz", 0.5F, 2.6F + (worldIn.rand.nextFloat() - worldIn.rand.nextFloat()) * 0.8F);
for (int i = 0; i < 8; ++i)
{
worldIn.spawnParticle(EnumParticleTypes.SMOKE_LARGE, d0 + Math.random(), d1 + 1.2D, d2 + Math.random(), 0.0D, 0.0D, 0.0D);
}
}
public IBlockState getStateFromMeta(int meta)
{
return this.getDefaultState().withProperty(LEVEL, meta);
}
public int getMetaFromState(IBlockState state)
{
return state.getValue(LEVEL);
}
protected BlockState createBlockState()
{
return new BlockState(this, LEVEL);
}
public static BlockDynamicLiquid getFlowingBlock(Material materialIn)
{
if (materialIn == Material.water)
{
return Blocks.flowing_water;
}
else if (materialIn == Material.lava)
{
return Blocks.flowing_lava;
}
else
{
throw new IllegalArgumentException("Invalid material");
}
}
public static BlockStaticLiquid getStaticBlock(Material materialIn)
{
if (materialIn == Material.water)
{
return Blocks.water;
}
else if (materialIn == Material.lava)
{
return Blocks.lava;
}
else
{
throw new IllegalArgumentException("Invalid material");
}
}
}
| 1 | 0.866385 | 1 | 0.866385 | game-dev | MEDIA | 0.988933 | game-dev | 0.961126 | 1 | 0.961126 |
ParadiseSS13/Paradise | 11,855 | code/game/verbs/ooc.dm | #define DEFAULT_PLAYER_OOC_COLOUR "#075FE5" // Can't initial() a global so we store the default in a macro instead
GLOBAL_VAR_INIT(normal_ooc_colour, DEFAULT_PLAYER_OOC_COLOUR)
GLOBAL_VAR_INIT(member_ooc_colour, "#035417")
GLOBAL_VAR_INIT(mentor_ooc_colour, "#00B0EB")
GLOBAL_VAR_INIT(moderator_ooc_colour, "#184880")
GLOBAL_VAR_INIT(admin_ooc_colour, "#b82e00")
/client/verb/ooc(msg = "" as text)
set name = "OOC"
set category = "OOC"
if(!mob)
return
if(IsGuestKey(key))
to_chat(src, "<span class='danger'>Guests may not use OOC.</span>", MESSAGE_TYPE_WARNING, confidential = TRUE)
return
if(!check_rights(R_ADMIN|R_MOD, 0))
if(!GLOB.ooc_enabled)
to_chat(src, "<span class='danger'>OOC is globally muted.</span>", MESSAGE_TYPE_WARNING, confidential = TRUE)
return
if(!GLOB.dooc_enabled && (mob.stat == DEAD))
to_chat(usr, "<span class='danger'>OOC for dead mobs has been turned off.</span>", MESSAGE_TYPE_WARNING, confidential = TRUE)
return
if(check_mute(ckey, MUTE_OOC))
to_chat(src, "<span class='danger'>You cannot use OOC (muted).</span>", MESSAGE_TYPE_WARNING, confidential = TRUE)
return
if(!msg)
msg = typing_input(src.mob, "", "ooc \"text\"")
msg = trim(sanitize(copytext_char(msg, 1, MAX_MESSAGE_LEN)))
if(!msg)
return
if(!(prefs.toggles & PREFTOGGLE_CHAT_OOC))
to_chat(src, "<span class='danger'>You have OOC muted.</span>")
return
if(!check_rights(R_ADMIN|R_MOD,0))
if(!GLOB.ooc_enabled)
to_chat(src, "<span class='danger'>OOC is globally muted.</span>")
return
if(handle_spam_prevention(msg, MUTE_OOC, OOC_COOLDOWN))
return
if(findtext(msg, "byond://"))
to_chat(src, "<B>Advertising other servers is not allowed.</B>")
log_admin("[key_name(src)] has attempted to advertise in OOC: [msg]")
message_admins("[key_name_admin(src)] has attempted to advertise in OOC: [msg]")
return
log_ooc(msg, src)
mob.create_log(OOC_LOG, msg)
var/display_colour = get_ooc_color()
for(var/client/C in GLOB.clients)
if(C.prefs.toggles & PREFTOGGLE_CHAT_OOC)
var/display_name = key
if(prefs.unlock_content)
if(prefs.toggles & PREFTOGGLE_MEMBER_PUBLIC)
var/icon/byond = icon('icons/member_content.dmi', "blag")
display_name = "[bicon(byond)][display_name]"
if(donator_level > 0)
if(prefs.toggles & PREFTOGGLE_DONATOR_PUBLIC)
var/icon/donator = icon('icons/ooc_tag_16x.png')
display_name = "[bicon(donator)][display_name]"
if(holder)
if(holder.fakekey)
if(C.holder && C.holder.rights & R_ADMIN)
display_name = "[holder.fakekey]/([key])"
else
display_name = holder.fakekey
if(GLOB.configuration.general.enable_ooc_emoji)
msg = emoji_parse(msg)
to_chat(C, "<font color='[display_colour]'><span class='ooc'><span class='prefix'>OOC:</span> <EM>[display_name]:</EM> <span class='message'>[msg]</span></span></font>")
/client/proc/get_ooc_color()
if(!holder || holder.fakekey)
if(prefs.unlock_content && (prefs.toggles & PREFTOGGLE_MEMBER_PUBLIC))
return GLOB.member_ooc_colour
return GLOB.normal_ooc_colour
if(!check_rights(R_ADMIN, FALSE))
if(check_rights(R_MOD, FALSE))
return GLOB.moderator_ooc_colour
return GLOB.mentor_ooc_colour
if(!GLOB.configuration.admin.allow_admin_ooc_colour)
return GLOB.admin_ooc_colour
return prefs.ooccolor
/proc/toggle_ooc()
GLOB.ooc_enabled = (!GLOB.ooc_enabled)
if(GLOB.ooc_enabled)
to_chat(world, "<B>The OOC channel has been globally enabled!</B>")
else
to_chat(world, "<B>The OOC channel has been globally disabled!</B>")
/proc/auto_toggle_ooc(on)
if(GLOB.configuration.general.auto_disable_ooc && GLOB.ooc_enabled != on)
toggle_ooc()
/client/verb/looc(msg = "" as text)
set name = "LOOC"
set desc = "Local OOC, seen only by those in view."
set category = "OOC"
if(!mob)
return
if(IsGuestKey(key))
to_chat(src, "<span class='danger'>Guests may not use LOOC.</span>", MESSAGE_TYPE_WARNING, confidential = TRUE)
return
if(!check_rights(R_ADMIN|R_MOD,0))
if(!GLOB.looc_enabled)
to_chat(src, "<span class='danger'>LOOC is globally muted.</span>", MESSAGE_TYPE_WARNING, confidential = TRUE)
return
if(!GLOB.dooc_enabled && (mob.stat == DEAD))
to_chat(usr, "<span class='danger'>LOOC for dead mobs has been turned off.</span>", MESSAGE_TYPE_WARNING, confidential = TRUE)
return
if(check_mute(ckey, MUTE_OOC))
to_chat(src, "<span class='danger'>You cannot use LOOC (muted).</span>", MESSAGE_TYPE_WARNING, confidential = TRUE)
return
if(!msg)
msg = typing_input(src.mob, "Local OOC, seen only by those in view.", "looc \"text\"")
msg = trim(sanitize(copytext_char(msg, 1, MAX_MESSAGE_LEN)))
if(!msg)
return
if(!(prefs.toggles & PREFTOGGLE_CHAT_LOOC))
to_chat(src, "<span class='danger'>You have LOOC muted.</span>")
return
if(!check_rights(R_ADMIN|R_MOD,0))
if(handle_spam_prevention(msg, MUTE_OOC, OOC_COOLDOWN))
return
if(findtext(msg, "byond://"))
to_chat(src, "<B>Advertising other servers is not allowed.</B>")
log_admin("[key_name(src)] has attempted to advertise in LOOC: [msg]")
message_admins("[key_name_admin(src)] has attempted to advertise in LOOC: [msg]")
return
log_looc(msg, src)
mob.create_log(LOOC_LOG, msg)
if(isliving(mob))
for(var/mob/M in viewers(7, mob))
if(M.client?.prefs.toggles2 & PREFTOGGLE_2_RUNECHAT)
M.create_chat_message(mob, msg, FALSE, symbol = RUNECHAT_SYMBOL_LOOC)
var/mob/source = mob.get_looc_source()
var/list/heard = get_mobs_in_view(7, source)
var/display_name = key
if(holder && holder.fakekey)
display_name = holder.fakekey
if(mob.stat != DEAD)
display_name = mob.name
for(var/client/target in GLOB.clients)
if(target.prefs.toggles & PREFTOGGLE_CHAT_LOOC)
var/prefix = ""
var/admin_stuff = ""
var/send = 0
if(target in GLOB.admins)
if(check_rights(R_ADMIN|R_MOD,0,target.mob))
admin_stuff += "/([key])"
if(target != src)
admin_stuff += " ([admin_jump_link(mob)])"
if(target.mob in heard)
send = 1
if(is_ai(target.mob))
prefix = " (Core)"
else if(is_ai(target.mob)) // Special case
var/mob/living/silicon/ai/A = target.mob
if(A.eyeobj in hearers(7, source))
send = 1
prefix = " (Eye)"
if(!send && (target in GLOB.admins))
if(check_rights(R_ADMIN|R_MOD,0,target.mob))
send = 1
prefix = "(R)"
if(send)
to_chat(target, "<span class='ooc'><span class='looc'>LOOC<span class='prefix'>[prefix]: </span><em>[display_name][admin_stuff]:</em> <span class='message'>[msg]</span></span></span>", MESSAGE_TYPE_OOC)
// Ported from /tg/, full credit to SpaceManiac and Timberpoes.
/client/verb/fit_viewport()
set name = "Fit Viewport"
set desc = "Fit the size of the map window to match the viewport."
set category = "Special Verbs"
// Fetch aspect ratio
var/list/view_size = getviewsize(view)
var/aspect_ratio = view_size[1] / view_size[2]
// Calculate desired pixel width using window size and aspect ratio
var/list/sizes = params2list(winget(src, "mainwindow.mainvsplit;paramapwindow", "size"))
// Client closed the window? Some other error? This is unexpected behaviour, let's CRASH with some info.
if(!sizes["paramapwindow.size"])
CRASH("sizes does not contain paramapwindow.size key. This means a winget() failed to return what we wanted. --- sizes var: [sizes] --- list contents:[list2params(sizes)] --- sizes length: [length(sizes)]")
var/list/map_size = splittext(sizes["paramapwindow.size"], "x")
// Gets the type of zoom we're currently using
// If it's 0 we do our pixel calculations based off the size of the mapwindow
// If it's not, we already know how big we want our window to be, since zoom is the exact pixel ratio of the map
var/icon_size = params2list(winget(src, "mainwindow.mainvsplit;paramapwindow;map", "icon-size")) || 0
var/zoom_value = text2num(icon_size["map.icon-size"]) / 32
var/desired_width = 0
if(zoom_value)
desired_width = round(view_size[1] * zoom_value * world.icon_size)
else
// Looks like we didn't expect paramapwindow.size to be "ixj" where i and j are numbers.
// If we don't get our expected 2 outputs, let's give some useful error info.
if(length(map_size) != 2)
CRASH("map_size of incorrect length --- map_size var: [map_size] --- map_size length: [length(map_size)]")
var/height = text2num(map_size[2])
desired_width = round(height * aspect_ratio)
if(text2num(map_size[1]) == desired_width)
// Nothing to do.
return
var/list/split_size = splittext(sizes["mainwindow.mainvsplit.size"], "x")
var/split_width = text2num(split_size[1])
// Avoid auto-resizing the statpanel and chat into nothing.
desired_width = min(desired_width, split_width - 300)
// Calculate and apply a best estimate
// +4 pixels are for the width of the splitter's handle
var/pct = 100 * (desired_width + 4) / split_width
winset(src, "mainwindow.mainvsplit", "splitter=[pct]")
// Apply an ever-lowering offset until we finish or fail
var/delta
for(var/safety in 1 to 10)
var/after_size = winget(src, "paramapwindow", "size")
map_size = splittext(after_size, "x")
var/produced_width = text2num(map_size[1])
if(produced_width == desired_width)
// Success!
return
else if(isnull(delta))
// Calculate a probably delta based on the difference
delta = 100 * (desired_width - produced_width) / split_width
else if((delta > 0 && produced_width > desired_width) || (delta < 0 && produced_width < desired_width))
// If we overshot, halve the delta and reverse direction
delta = -delta / 2
pct += delta
winset(src, "mainwindow.mainvsplit", "splitter=[pct]")
/mob/proc/get_looc_source()
return src
/mob/living/silicon/ai/get_looc_source()
if(eyeobj)
return eyeobj
return src
/client/verb/fix_stat_panel()
set name = "Fix Stat Panel"
set hidden = TRUE
init_verbs()
/client/verb/show_own_notes()
set name = "Show My Notes"
set desc = "View your public notes."
set category = "OOC"
if(!key)
return
if(!SSdbcore.IsConnected())
to_chat(src, "<span class='danger'>Failed to establish database connection.</span>")
return
var/list/output = list("<!DOCTYPE html>")
var/datum/db_query/query_get_notes = SSdbcore.NewQuery({"
SELECT timestamp, notetext, adminckey, last_editor, server, crew_playtime, round_id
FROM notes WHERE ckey=:targetkey AND deleted=0 AND public=1 ORDER BY timestamp"}, list(
"targetkey" = ckey
))
if(!query_get_notes.warn_execute())
to_chat(src, "<span class='danger'>Unfortunately, we were not able to retrieve your notes.</span>")
qdel(query_get_notes)
return
output += "<h2><center>Notes of [ckey]</center></h2><br><center><font size='1'>Don't discuss warnings or other punishments from the admins in Paradise Discord.</font></center>"
output += "<hr style='background:#000000; border:0; height:3px'>"
var/found_notes = FALSE
while(query_get_notes.NextRow())
found_notes = TRUE
var/timestamp = query_get_notes.item[1]
var/notetext = query_get_notes.item[2]
var/adminckey = query_get_notes.item[3]
var/last_editor = query_get_notes.item[4]
var/server = query_get_notes.item[5]
var/mins = text2num(query_get_notes.item[6])
var/round_id = text2num(query_get_notes.item[7])
output += "<b>[timestamp][round_id ? " (Round [round_id])" : ""] | [server] | [adminckey]"
if(mins)
var/playstring = get_exp_format(mins)
output += " | [playstring] as Crew"
output += "</b>"
if(last_editor)
output += " <font size='1'>Last edit by [last_editor].</font>"
output += "<br>[replacetext(notetext, "\n", "<br>")]<hr style='background:#000000; border:0; height:1px'>"
if(!found_notes)
output += "<b>You have no public notes.</b>"
qdel(query_get_notes)
var/datum/browser/popup = new(mob, "show_public_notes", "Public Notes", 900, 500)
popup.set_content(output.Join(""))
popup.open()
#undef DEFAULT_PLAYER_OOC_COLOUR
| 1 | 0.968839 | 1 | 0.968839 | game-dev | MEDIA | 0.821515 | game-dev,desktop-app | 0.971283 | 1 | 0.971283 |
plooshi/28.30 | 2,655 | 28.30/SDK/HidingProp_CameraModifier_functions.cpp | #pragma once
/*
* SDK generated by Dumper-7
*
* https://github.com/Encryqed/Dumper-7
*/
// Package: HidingProp_CameraModifier
#include "Basic.hpp"
#include "HidingProp_CameraModifier_classes.hpp"
#include "HidingProp_CameraModifier_parameters.hpp"
namespace SDK
{
// Function HidingProp_CameraModifier.HidingProp_CameraModifier_C.BlueprintModifyCamera
// (BlueprintCosmetic, Event, Public, HasOutParams, BlueprintCallable, BlueprintEvent)
// Parameters:
// float DeltaTime (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
// struct FVector ViewLocation (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
// struct FRotator ViewRotation (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
// float FOV (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
// struct FVector NewViewLocation (Parm, OutParm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
// struct FRotator NewViewRotation (Parm, OutParm, ZeroConstructor, IsPlainOldData, NoDestructor)
// float NewFOV (Parm, OutParm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
void UHidingProp_CameraModifier_C::BlueprintModifyCamera(float DeltaTime, const struct FVector& ViewLocation, const struct FRotator& ViewRotation, float FOV, struct FVector* NewViewLocation, struct FRotator* NewViewRotation, float* NewFOV)
{
static class UFunction* Func = nullptr;
if (Func == nullptr)
Func = Class->FindFunction("BlueprintModifyCamera");
Params::HidingProp_CameraModifier_C_BlueprintModifyCamera Parms{};
Parms.DeltaTime = DeltaTime;
Parms.ViewLocation = std::move(ViewLocation);
Parms.ViewRotation = std::move(ViewRotation);
Parms.FOV = FOV;
UObject::ProcessEvent(Func, &Parms);
if (NewViewLocation != nullptr)
*NewViewLocation = std::move(Parms.NewViewLocation);
if (NewViewRotation != nullptr)
*NewViewRotation = std::move(Parms.NewViewRotation);
if (NewFOV != nullptr)
*NewFOV = Parms.NewFOV;
}
}
| 1 | 0.830066 | 1 | 0.830066 | game-dev | MEDIA | 0.612586 | game-dev,graphics-rendering | 0.559993 | 1 | 0.559993 |
DrRed96/Nonsense-Client-Old | 4,404 | src/main/java/net/minecraft/client/renderer/entity/layers/LayerCustomHead.java | package net.minecraft.client.renderer.entity.layers;
import com.mojang.authlib.GameProfile;
import java.util.UUID;
import net.minecraft.client.Minecraft;
import net.minecraft.client.model.ModelRenderer;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.block.model.ItemCameraTransforms;
import net.minecraft.client.renderer.tileentity.TileEntitySkullRenderer;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.monster.EntityZombie;
import net.minecraft.entity.passive.EntityVillager;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTUtil;
import net.minecraft.tileentity.TileEntitySkull;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.StringUtils;
public class LayerCustomHead implements LayerRenderer<EntityLivingBase>
{
private final ModelRenderer field_177209_a;
public LayerCustomHead(ModelRenderer p_i46120_1_)
{
this.field_177209_a = p_i46120_1_;
}
public void doRenderLayer(EntityLivingBase entitylivingbaseIn, float p_177141_2_, float p_177141_3_, float partialTicks, float p_177141_5_, float p_177141_6_, float p_177141_7_, float scale)
{
ItemStack itemstack = entitylivingbaseIn.getCurrentArmor(3);
if (itemstack != null && itemstack.getItem() != null)
{
Item item = itemstack.getItem();
Minecraft minecraft = Minecraft.getMinecraft();
GlStateManager.pushMatrix();
if (entitylivingbaseIn.isSneaking())
{
GlStateManager.translate(0.0F, 0.2F, 0.0F);
}
boolean flag = entitylivingbaseIn instanceof EntityVillager || entitylivingbaseIn instanceof EntityZombie && ((EntityZombie)entitylivingbaseIn).isVillager();
if (!flag && entitylivingbaseIn.isChild())
{
float f = 2.0F;
float f1 = 1.4F;
GlStateManager.scale(f1 / f, f1 / f, f1 / f);
GlStateManager.translate(0.0F, 16.0F * scale, 0.0F);
}
this.field_177209_a.postRender(0.0625F);
GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);
if (item instanceof ItemBlock)
{
float f2 = 0.625F;
GlStateManager.translate(0.0F, -0.25F, 0.0F);
GlStateManager.rotate(180.0F, 0.0F, 1.0F, 0.0F);
GlStateManager.scale(f2, -f2, -f2);
if (flag)
{
GlStateManager.translate(0.0F, 0.1875F, 0.0F);
}
minecraft.getItemRenderer().renderItem(entitylivingbaseIn, itemstack, ItemCameraTransforms.TransformType.HEAD);
}
else if (item == Items.skull)
{
float f3 = 1.1875F;
GlStateManager.scale(f3, -f3, -f3);
if (flag)
{
GlStateManager.translate(0.0F, 0.0625F, 0.0F);
}
GameProfile gameprofile = null;
if (itemstack.hasTagCompound())
{
NBTTagCompound nbttagcompound = itemstack.getTagCompound();
if (nbttagcompound.hasKey("SkullOwner", 10))
{
gameprofile = NBTUtil.readGameProfileFromNBT(nbttagcompound.getCompoundTag("SkullOwner"));
}
else if (nbttagcompound.hasKey("SkullOwner", 8))
{
String s = nbttagcompound.getString("SkullOwner");
if (!StringUtils.isNullOrEmpty(s))
{
gameprofile = TileEntitySkull.updateGameprofile(new GameProfile((UUID)null, s));
nbttagcompound.setTag("SkullOwner", NBTUtil.writeGameProfile(new NBTTagCompound(), gameprofile));
}
}
}
TileEntitySkullRenderer.instance.renderSkull(-0.5F, 0.0F, -0.5F, EnumFacing.UP, 180.0F, itemstack.getMetadata(), gameprofile, -1);
}
GlStateManager.popMatrix();
}
}
public boolean shouldCombineTextures()
{
return true;
}
}
| 1 | 0.748698 | 1 | 0.748698 | game-dev | MEDIA | 0.990633 | game-dev | 0.945983 | 1 | 0.945983 |
MCCTeam/Minecraft-Console-Client | 9,200 | MinecraftClient/ChatBots/FollowPlayer.cs | using System;
using System.Linq;
using Brigadier.NET;
using Brigadier.NET.Builder;
using MinecraftClient.CommandHandler;
using MinecraftClient.CommandHandler.Patch;
using MinecraftClient.Mapping;
using MinecraftClient.Scripting;
using Tomlet.Attributes;
namespace MinecraftClient.ChatBots
{
public class FollowPlayer : ChatBot
{
public const string CommandName = "follow";
public static Configs Config = new();
[TomlDoNotInlineObject]
public class Configs
{
[NonSerialized] private const string BotName = "FollowPlayer";
public bool Enabled = false;
[TomlInlineComment("$ChatBot.FollowPlayer.Update_Limit$")]
public double Update_Limit = 1.5;
[TomlInlineComment("$ChatBot.FollowPlayer.Stop_At_Distance$")]
public double Stop_At_Distance = 3.0;
public void OnSettingUpdate()
{
if (Update_Limit < 0)
Update_Limit = 0;
if (Stop_At_Distance < 0)
Stop_At_Distance = 0;
}
}
private string? _playerToFollow = null;
private int _updateCounter = 0;
private bool _unsafeEnabled = false;
public override void Initialize()
{
if (!GetEntityHandlingEnabled())
{
LogToConsole(Translations.extra_entity_required);
LogToConsole(Translations.general_bot_unload);
UnloadBot();
return;
}
if (!GetTerrainEnabled())
{
LogToConsole(Translations.extra_terrainandmovement_required);
LogToConsole(Translations.general_bot_unload);
UnloadBot();
return;
}
McClient.dispatcher.Register(l => l.Literal("help")
.Then(l => l.Literal(CommandName)
.Executes(r => OnCommandHelp(r.Source, string.Empty))
)
);
McClient.dispatcher.Register(l => l.Literal(CommandName)
.Then(l => l.Literal("start")
.Then(l => l.Argument("PlayerName", MccArguments.PlayerName())
.Executes(r => OnCommandStart(r.Source, Arguments.GetString(r, "PlayerName"), takeRisk: false))
.Then(l => l.Literal("-f")
.Executes(r =>
OnCommandStart(r.Source, Arguments.GetString(r, "PlayerName"), takeRisk: true)))))
.Then(l => l.Literal("stop")
.Executes(r => OnCommandStop(r.Source)))
.Then(l => l.Literal("_help")
.Executes(r => OnCommandHelp(r.Source, string.Empty))
.Redirect(McClient.dispatcher.GetRoot().GetChild("help").GetChild(CommandName)))
);
}
public override void OnUnload()
{
BotMovementLock.Instance?.UnLock("Follow Player");
McClient.dispatcher.Unregister(CommandName);
McClient.dispatcher.GetRoot().GetChild("help").RemoveChild(CommandName);
}
private int OnCommandHelp(CmdResult r, string? cmd)
{
return r.SetAndReturn(cmd switch
{
#pragma warning disable format // @formatter:off
_ => Translations.cmd_follow_desc + ": " + Translations.cmd_follow_usage
+ '\n' + McClient.dispatcher.GetAllUsageString(CommandName, false),
#pragma warning restore format // @formatter:on
});
}
private int OnCommandStart(CmdResult r, string name, bool takeRisk)
{
if (!IsValidName(name))
return r.SetAndReturn(CmdResult.Status.Fail, Translations.cmd_follow_invalid_name);
var player = GetEntities().Values.ToList().Find(entity =>
entity.Type == EntityType.Player
&& !string.IsNullOrEmpty(entity.Name)
&& entity.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
if (player == null)
return r.SetAndReturn(CmdResult.Status.Fail, Translations.cmd_follow_invalid_player);
if (!CanMoveThere(player.Location))
return r.SetAndReturn(CmdResult.Status.Fail, Translations.cmd_follow_cant_reach_player);
if (_playerToFollow != null && _playerToFollow.Equals(name, StringComparison.OrdinalIgnoreCase))
return r.SetAndReturn(CmdResult.Status.Fail,
string.Format(Translations.cmd_follow_already_following, _playerToFollow));
var movementLock = BotMovementLock.Instance;
if (movementLock is { IsLocked: true })
return r.SetAndReturn(CmdResult.Status.Fail,
string.Format(Translations.bot_common_movement_lock_held, "Follow Player", movementLock.LockedBy));
var result =
string.Format(
_playerToFollow != null ? Translations.cmd_follow_switched : Translations.cmd_follow_started,
player.Name!);
_playerToFollow = name.ToLower();
switch (movementLock)
{
case { IsLocked: false }:
if (!movementLock.Lock("Follow Player"))
{
LogToConsole($"§§6§1§0Follow Player bot failed to obtain the movement lock for some reason!");
LogToConsole($"§§6§1§0Disable other bots who have movement mechanics, and try again!");
return r.SetAndReturn(CmdResult.Status.Fail);
}
break;
}
if (!takeRisk) return r.SetAndReturn(CmdResult.Status.Done, Translations.cmd_follow_note);
_unsafeEnabled = true;
return r.SetAndReturn(CmdResult.Status.Done,
Translations.cmd_follow_note + '\n' + Translations.cmd_follow_unsafe_enabled);
}
private int OnCommandStop(CmdResult r)
{
if (_playerToFollow == null)
return r.SetAndReturn(CmdResult.Status.Fail, Translations.cmd_follow_already_stopped);
var movementLock = BotMovementLock.Instance;
movementLock?.UnLock("Follow Player");
_playerToFollow = null;
return r.SetAndReturn(CmdResult.Status.Done, Translations.cmd_follow_stopping);
}
public override void Update()
{
_updateCounter++;
}
public override void OnEntityMove(Entity entity)
{
if (entity.Type != EntityType.Player)
return;
if (_playerToFollow == null || string.IsNullOrEmpty(entity.Name))
return;
if (_playerToFollow != entity.Name.ToLower())
return;
if (_updateCounter < Settings.DoubleToTick(Config.Update_Limit))
return;
_updateCounter = 0;
if (!CanMoveThere(entity.Location))
return;
// Stop at specified distance from player (prevents pushing player around)
var distance = entity.Location.Distance(GetCurrentLocation());
if (distance < Config.Stop_At_Distance)
return;
MoveToLocation(entity.Location, _unsafeEnabled);
}
public override void OnEntitySpawn(Entity entity)
{
if (entity.Type != EntityType.Player)
return;
if (_playerToFollow != null && !string.IsNullOrEmpty(entity.Name) &&
_playerToFollow.Equals(entity.Name, StringComparison.OrdinalIgnoreCase))
{
LogToConsole(string.Format(Translations.cmd_follow_player_came_to_the_range, _playerToFollow));
LogToConsole(Translations.cmd_follow_resuming);
}
}
public override void OnEntityDespawn(Entity entity)
{
if (entity.Type != EntityType.Player)
return;
if (_playerToFollow != null && !string.IsNullOrEmpty(entity.Name) &&
_playerToFollow.Equals(entity.Name, StringComparison.OrdinalIgnoreCase))
{
LogToConsole(string.Format(Translations.cmd_follow_player_left_the_range, _playerToFollow));
LogToConsole(Translations.cmd_follow_pausing);
}
}
public override void OnPlayerLeave(Guid uuid, string? name)
{
if (_playerToFollow != null && !string.IsNullOrEmpty(name) &&
_playerToFollow.Equals(name, StringComparison.OrdinalIgnoreCase))
{
LogToConsole(string.Format(Translations.cmd_follow_player_left, _playerToFollow));
LogToConsole(Translations.cmd_follow_stopping);
_playerToFollow = null;
}
}
private bool CanMoveThere(Location location)
{
var chunkColumn = GetWorld().GetChunkColumn(location);
return chunkColumn != null && chunkColumn.FullyLoaded != false;
}
}
} | 1 | 0.900793 | 1 | 0.900793 | game-dev | MEDIA | 0.557106 | game-dev | 0.977728 | 1 | 0.977728 |
arl/go-detour | 7,536 | detour/structs.go | package detour
import (
"encoding/binary"
"io"
"math"
)
type navMeshSetHeader struct {
Magic uint32
Version uint32
NumTiles uint32
Params NavMeshParams
}
func (s *navMeshSetHeader) Size() int {
return 12 + s.Params.size()
}
func (s *navMeshSetHeader) serialize(dst []byte) {
if len(dst) < s.Size() {
panic("undersized buffer for navMeshSetHeader")
}
var (
little = binary.LittleEndian
off int
)
// write each field as little endian
little.PutUint32(dst[off:], s.Magic)
little.PutUint32(dst[off+4:], s.Version)
little.PutUint32(dst[off+8:], s.NumTiles)
s.Params.serialize(dst[off+12:])
}
func (s *navMeshSetHeader) WriteTo(w io.Writer) (int64, error) {
buf := make([]byte, s.Size())
s.serialize(buf)
n, err := w.Write(buf)
return int64(n), err
}
// NavMeshParams contains the configuration parameters used to define
// multi-tile navigation meshes.
//
// The values are used to allocate space during the initialization of a
// navigation mesh.
// see NavMesh.Init()
type NavMeshParams struct {
Orig [3]float32 // The world space origin of the navigation mesh's tile space. [(x, y, z)]
TileWidth float32 // The width of each tile. (Along the x-axis.)
TileHeight float32 // The height of each tile. (Along the z-axis.)
MaxTiles uint32 // The maximum number of tiles the navigation mesh can contain.
MaxPolys uint32 // The maximum number of polygons each tile can contain.
}
// size returns the size of the serialized structure.
func (s *NavMeshParams) size() int {
return 28
}
// serialize encodes the structure content into dst.
//
// The function panics is the destination slice is too small.
func (s *NavMeshParams) serialize(dst []byte) {
if len(dst) < s.size() {
panic("destination slice is too small")
}
var (
little = binary.LittleEndian
off int
)
// write each field as little endian
little.PutUint32(dst[off:], uint32(math.Float32bits(s.Orig[0])))
little.PutUint32(dst[off+4:], uint32(math.Float32bits(s.Orig[1])))
little.PutUint32(dst[off+8:], uint32(math.Float32bits(s.Orig[2])))
little.PutUint32(dst[off+12:], uint32(math.Float32bits(s.TileWidth)))
little.PutUint32(dst[off+16:], uint32(math.Float32bits(s.TileHeight)))
little.PutUint32(dst[off+20:], uint32(s.MaxTiles))
little.PutUint32(dst[off+24:], uint32(s.MaxPolys))
}
// MeshHeader provides high level information related to a MeshTile object.
type MeshHeader struct {
Magic int32 // Tile magic number. (Used to identify the data format.)
Version int32 // Tile data format version number.
X int32 // The x-position of the tile within the NavMesh tile grid. (x, y, layer)
Y int32 // The y-position of the tile within the NavMesh tile grid. (x, y, layer)
Layer int32 // The layer of the tile within the NavMesh tile grid. (x, y, layer)
UserID uint32 // The user defined id of the tile.
PolyCount int32 // The number of polygons in the tile.
VertCount int32 // The number of vertices in the tile.
MaxLinkCount int32 // The number of allocated links.
DetailMeshCount int32 // The number of sub-meshes in the detail mesh.
DetailVertCount int32 // The number of unique vertices in the detail mesh. (In addition to the polygon vertices.)
DetailTriCount int32 // The number of triangles in the detail mesh.
BvNodeCount int32 // The number of bounding volume nodes. (Zero if bounding volumes are disabled.)
OffMeshConCount int32 // The number of off-mesh connections.
OffMeshBase int32 // The index of the first polygon which is an off-mesh connection.
WalkableHeight float32 // The height of the agents using the tile.
WalkableRadius float32 // The radius of the agents using the tile.
WalkableClimb float32 // The maximum climb height of the agents using the tile.
BMin [3]float32 // The minimum bounds of the tile's AABB. [(x, y, z)]
BMax [3]float32 // The maximum bounds of the tile's AABB. [(x, y, z)]
BvQuantFactor float32 // The bounding volume quantization factor.
}
func (s *MeshHeader) size() int {
return 100
}
func (s *MeshHeader) serialize(dst []byte) {
if len(dst) < s.size() {
panic("undersized buffer for MeshHeader")
}
var (
little = binary.LittleEndian
off int
)
// write each field as little endian
little.PutUint32(dst[off:], uint32(s.Magic))
little.PutUint32(dst[off+4:], uint32(s.Version))
little.PutUint32(dst[off+8:], uint32(s.X))
little.PutUint32(dst[off+12:], uint32(s.Y))
little.PutUint32(dst[off+16:], uint32(s.Layer))
little.PutUint32(dst[off+20:], uint32(s.UserID))
little.PutUint32(dst[off+24:], uint32(s.PolyCount))
little.PutUint32(dst[off+28:], uint32(s.VertCount))
little.PutUint32(dst[off+32:], uint32(s.MaxLinkCount))
little.PutUint32(dst[off+36:], uint32(s.DetailMeshCount))
little.PutUint32(dst[off+40:], uint32(s.DetailVertCount))
little.PutUint32(dst[off+44:], uint32(s.DetailTriCount))
little.PutUint32(dst[off+48:], uint32(s.BvNodeCount))
little.PutUint32(dst[off+52:], uint32(s.OffMeshConCount))
little.PutUint32(dst[off+56:], uint32(s.OffMeshBase))
little.PutUint32(dst[off+60:], uint32(math.Float32bits(s.WalkableHeight)))
little.PutUint32(dst[off+64:], uint32(math.Float32bits(s.WalkableRadius)))
little.PutUint32(dst[off+68:], uint32(math.Float32bits(s.WalkableClimb)))
little.PutUint32(dst[off+72:], uint32(math.Float32bits(s.BMin[0])))
little.PutUint32(dst[off+76:], uint32(math.Float32bits(s.BMin[1])))
little.PutUint32(dst[off+80:], uint32(math.Float32bits(s.BMin[2])))
little.PutUint32(dst[off+84:], uint32(math.Float32bits(s.BMax[0])))
little.PutUint32(dst[off+88:], uint32(math.Float32bits(s.BMax[1])))
little.PutUint32(dst[off+92:], uint32(math.Float32bits(s.BMax[2])))
little.PutUint32(dst[off+96:], uint32(math.Float32bits(s.BvQuantFactor)))
}
func (s *MeshHeader) unserialize(src []byte) {
if len(src) < s.size() {
panic("undersized buffer for MeshHeader")
}
var (
little = binary.LittleEndian
off int
)
// write each field as little endian
s.Magic = int32(little.Uint32(src[off:]))
s.Version = int32(little.Uint32(src[off+4:]))
s.X = int32(little.Uint32(src[off+8:]))
s.Y = int32(little.Uint32(src[off+12:]))
s.Layer = int32(little.Uint32(src[off+16:]))
s.UserID = little.Uint32(src[off+20:])
s.PolyCount = int32(little.Uint32(src[off+24:]))
s.VertCount = int32(little.Uint32(src[off+28:]))
s.MaxLinkCount = int32(little.Uint32(src[off+32:]))
s.DetailMeshCount = int32(little.Uint32(src[off+36:]))
s.DetailVertCount = int32(little.Uint32(src[off+40:]))
s.DetailTriCount = int32(little.Uint32(src[off+44:]))
s.BvNodeCount = int32(little.Uint32(src[off+48:]))
s.OffMeshConCount = int32(little.Uint32(src[off+52:]))
s.OffMeshBase = int32(little.Uint32(src[off+56:]))
s.WalkableHeight = math.Float32frombits(little.Uint32(src[off+60:]))
s.WalkableRadius = math.Float32frombits(little.Uint32(src[off+64:]))
s.WalkableClimb = math.Float32frombits(little.Uint32(src[off+68:]))
s.BMin[0] = math.Float32frombits(little.Uint32(src[off+72:]))
s.BMin[1] = math.Float32frombits(little.Uint32(src[off+76:]))
s.BMin[2] = math.Float32frombits(little.Uint32(src[off+80:]))
s.BMax[0] = math.Float32frombits(little.Uint32(src[off+84:]))
s.BMax[1] = math.Float32frombits(little.Uint32(src[off+88:]))
s.BMax[2] = math.Float32frombits(little.Uint32(src[off+92:]))
s.BvQuantFactor = math.Float32frombits(little.Uint32(src[off+96:]))
}
| 1 | 0.798453 | 1 | 0.798453 | game-dev | MEDIA | 0.132316 | game-dev | 0.975134 | 1 | 0.975134 |
maitrix-org/SimWorld | 8,726 | simworld/traffic/manager/vehicle_manager.py | """Vehicle management module for traffic simulation.
This module handles the creation, spawning, and updating of vehicles in the simulation.
It manages vehicle lifecycle, movement logic, and interaction with traffic signals.
"""
import random
from simworld.agent.vehicle import Vehicle, VehicleState
from simworld.traffic.base.traffic_signal import TrafficSignalState
from simworld.utils.load_json import load_json
from simworld.utils.logger import Logger
from simworld.utils.traffic_utils import cal_waypoints
class VehicleManager:
"""Manages vehicles in the traffic simulation.
This class handles spawning vehicles on roads, updating their positions and states,
and managing their interactions with other elements in the simulation.
"""
def __init__(self, roads, num_vehicles, config):
"""Initialize the vehicle manager with configuration and initial vehicles.
Args:
roads: List of road segments where vehicles can be placed.
num_vehicles: Number of vehicles to create initially.
config: Configuration dictionary with simulation parameters.
"""
self.config = config
self.vehicles = []
self.roads = roads
self.num_vehicles = num_vehicles
self.vehicle_types = load_json(self.config['traffic.vehicle.model_file_path'])
# logger
self.logger = Logger.get_logger('VehicleController')
self.logger.info(f'VehicleController initialized with {num_vehicles} vehicles')
self.last_states = {} # {vehicle_id: (throttle, brake, steering)}
self.init_vehicles()
def init_vehicles(self):
"""Initialize the vehicles and place them on the roads.
Vehicles are randomly placed on lanes, ensuring they maintain safe distances
from other vehicles and intersections.
"""
while len(self.vehicles) < self.num_vehicles:
target_road = random.choice(self.roads)
target_lane = random.choice(list(target_road.lanes.values()))
target_position = random.uniform(target_lane.start, target_lane.end)
# check if the vehicle is too close to intersection
if target_position.distance(target_lane.end) < 3 * self.config['traffic.distance_between_objects']:
continue
possible_vehicles = target_lane.vehicles
for vehicle in possible_vehicles:
# check if the vehicle is too close to another vehicle
if vehicle.position.distance(target_position) < 2 * self.config['traffic.distance_between_objects'] + vehicle.length:
break
else:
target_direction = target_lane.direction
# Randomly select a vehicle type
vehicle_type = random.choice(list(self.vehicle_types.values()))
new_vehicle = Vehicle(position=target_position, direction=target_direction, current_lane=target_lane,
vehicle_reference=vehicle_type['reference'], config=self.config,
length=vehicle_type['length'], width=vehicle_type['width'])
waypoints = cal_waypoints(target_position, target_lane.end, self.config['traffic.gap_between_waypoints'])
new_vehicle.add_waypoint(waypoints)
target_lane.add_vehicle(new_vehicle)
self.vehicles.append(new_vehicle)
self.logger.info(f"Spawned Vehicle: {new_vehicle.id} of type {vehicle_type['name']} on Lane {target_lane.id} at {target_position}")
def spawn_vehicles(self, communicator):
"""Spawn vehicles in the simulation environment.
Args:
communicator: Communication interface to the simulation environment.
"""
communicator.spawn_vehicles(self.vehicles)
def update_vehicles(self, communicator, intersection_controller, pedestrians):
"""Update vehicle states and movements based on environment conditions.
This method handles vehicle movement logic, including waypoint following,
intersection crossing, obstacle avoidance, and traffic signal compliance.
Args:
communicator: Interface for sending updates to the simulation.
intersection_controller: Controller for managing intersection logic.
pedestrians: List of pedestrians to check for collision avoidance.
"""
for vehicle in self.vehicles:
# update vehicle waypoints
if vehicle.waypoints and len(vehicle.waypoints) > 0:
# Calculate vector from current position to waypoint
to_waypoint = vehicle.waypoints[0] - vehicle.position
# Calculate dot product between vehicle direction and to_waypoint vector
dot_product = vehicle.direction.dot(to_waypoint.normalize())
# If angle is greater than 90 degrees (dot product < 0), remove the waypoint
if dot_product < 0:
vehicle.waypoints.pop(0)
if vehicle.state == VehicleState.WAITING:
communicator.vehicle_make_u_turn(vehicle.id)
vehicle.set_attributes(0.05, 0, -1) # throttle = 0, brake = 0, steering = -1
vehicle.state = VehicleState.MAKING_U_TURN
if vehicle.state == VehicleState.MAKING_U_TURN:
if vehicle.completed_u_turn():
vehicle.state = VehicleState.MOVING
vehicle.steering_pid.reset()
else:
continue
if vehicle.is_close_to_object(self.vehicles, pedestrians):
self.logger.debug(f'Vehicle {vehicle.id} is close to another vehicle, stop it')
if not vehicle.state == VehicleState.STOPPED:
vehicle.set_attributes(0, 1, 0) # throttle = 0, brake = 1, steering = 0
vehicle.state = VehicleState.STOPPED
continue
# Check if vehicle has reached current waypoint
if vehicle.is_close_to_end():
self.logger.debug(f'Vehicle {vehicle.id} has reached current waypoint, get next waypoints')
next_lane, waypoints, current_intersection, is_u_turn = intersection_controller.get_waypoints_for_vehicle(vehicle.current_lane)
if is_u_turn:
vehicle.state = VehicleState.WAITING
vehicle.add_waypoint(waypoints)
vehicle.change_to_next_lane(next_lane)
# communicator.set_state(vehicle.vehicle_id, 0, 1, 0)
vehicle.set_attributes(0, 1, 0) # throttle = 0, brake = 1, steering = 0
continue
else:
vehicle_light_state, _ = current_intersection.get_traffic_light_state(vehicle.current_lane)
if vehicle_light_state == TrafficSignalState.VEHICLE_GREEN:
self.logger.debug(f'Vehicle {vehicle.id} has green light on lane {vehicle.current_lane.id}, add waypoints')
vehicle.add_waypoint(waypoints)
vehicle.change_to_next_lane(next_lane)
else:
if not vehicle.state == VehicleState.STOPPED:
self.logger.debug(f'Vehicle {vehicle.id} has red light on lane {vehicle.current_lane.id}, stop it')
# communicator.set_state(vehicle.vehicle_id, 0, 1, 0)
vehicle.set_attributes(0, 1, 0) # throttle = 0, brake = 1, steering = 0
vehicle.state = VehicleState.STOPPED
continue
if vehicle.waypoints and len(vehicle.waypoints) > 0:
throttle, brake, steering, changed = vehicle.compute_control(vehicle.waypoints[0], 0.1)
if not vehicle.state == VehicleState.MOVING:
vehicle.state = VehicleState.MOVING
changed_states = {}
for vehicle in self.vehicles:
vehicle_id = vehicle.id
current_state = vehicle.get_attributes()
if vehicle_id not in self.last_states or current_state != self.last_states[vehicle_id]:
changed_states[vehicle_id] = current_state
self.last_states[vehicle_id] = current_state
if changed_states:
communicator.update_vehicles(changed_states)
def stop_vehicles(self, communicator):
"""Stop all vehicles in the simulation."""
for vehicle in self.vehicles:
vehicle.state = VehicleState.STOPPED
communicator.update_vehicle(vehicle.id, 0, 1, 0)
| 1 | 0.751753 | 1 | 0.751753 | game-dev | MEDIA | 0.64175 | game-dev | 0.836403 | 1 | 0.836403 |
freebsd/freebsd-src | 25,037 | contrib/llvm-project/compiler-rt/lib/asan/asan_poisoning.cpp | //===-- asan_poisoning.cpp ------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file is a part of AddressSanitizer, an address sanity checker.
//
// Shadow memory poisoning by ASan RTL and by user application.
//===----------------------------------------------------------------------===//
#include "asan_poisoning.h"
#include "asan_report.h"
#include "asan_stack.h"
#include "sanitizer_common/sanitizer_atomic.h"
#include "sanitizer_common/sanitizer_flags.h"
#include "sanitizer_common/sanitizer_interface_internal.h"
#include "sanitizer_common/sanitizer_libc.h"
namespace __asan {
static atomic_uint8_t can_poison_memory;
void SetCanPoisonMemory(bool value) {
atomic_store(&can_poison_memory, value, memory_order_release);
}
bool CanPoisonMemory() {
return atomic_load(&can_poison_memory, memory_order_acquire);
}
void PoisonShadow(uptr addr, uptr size, u8 value) {
if (value && !CanPoisonMemory()) return;
CHECK(AddrIsAlignedByGranularity(addr));
CHECK(AddrIsInMem(addr));
CHECK(AddrIsAlignedByGranularity(addr + size));
CHECK(AddrIsInMem(addr + size - ASAN_SHADOW_GRANULARITY));
CHECK(REAL(memset));
FastPoisonShadow(addr, size, value);
}
void PoisonShadowPartialRightRedzone(uptr addr,
uptr size,
uptr redzone_size,
u8 value) {
if (!CanPoisonMemory()) return;
CHECK(AddrIsAlignedByGranularity(addr));
CHECK(AddrIsInMem(addr));
FastPoisonShadowPartialRightRedzone(addr, size, redzone_size, value);
}
struct ShadowSegmentEndpoint {
u8 *chunk;
s8 offset; // in [0, ASAN_SHADOW_GRANULARITY)
s8 value; // = *chunk;
explicit ShadowSegmentEndpoint(uptr address) {
chunk = (u8*)MemToShadow(address);
offset = address & (ASAN_SHADOW_GRANULARITY - 1);
value = *chunk;
}
};
void AsanPoisonOrUnpoisonIntraObjectRedzone(uptr ptr, uptr size, bool poison) {
uptr end = ptr + size;
if (Verbosity()) {
Printf("__asan_%spoison_intra_object_redzone [%p,%p) %zd\n",
poison ? "" : "un", (void *)ptr, (void *)end, size);
if (Verbosity() >= 2)
PRINT_CURRENT_STACK();
}
CHECK(size);
CHECK_LE(size, 4096);
CHECK(IsAligned(end, ASAN_SHADOW_GRANULARITY));
if (!IsAligned(ptr, ASAN_SHADOW_GRANULARITY)) {
*(u8 *)MemToShadow(ptr) =
poison ? static_cast<u8>(ptr % ASAN_SHADOW_GRANULARITY) : 0;
ptr |= ASAN_SHADOW_GRANULARITY - 1;
ptr++;
}
for (; ptr < end; ptr += ASAN_SHADOW_GRANULARITY)
*(u8*)MemToShadow(ptr) = poison ? kAsanIntraObjectRedzone : 0;
}
} // namespace __asan
// ---------------------- Interface ---------------- {{{1
using namespace __asan;
// Current implementation of __asan_(un)poison_memory_region doesn't check
// that user program (un)poisons the memory it owns. It poisons memory
// conservatively, and unpoisons progressively to make sure asan shadow
// mapping invariant is preserved (see detailed mapping description here:
// https://github.com/google/sanitizers/wiki/AddressSanitizerAlgorithm).
//
// * if user asks to poison region [left, right), the program poisons
// at least [left, AlignDown(right)).
// * if user asks to unpoison region [left, right), the program unpoisons
// at most [AlignDown(left), right).
void __asan_poison_memory_region(void const volatile *addr, uptr size) {
if (!flags()->allow_user_poisoning || size == 0) return;
uptr beg_addr = (uptr)addr;
uptr end_addr = beg_addr + size;
VPrintf(3, "Trying to poison memory region [%p, %p)\n", (void *)beg_addr,
(void *)end_addr);
ShadowSegmentEndpoint beg(beg_addr);
ShadowSegmentEndpoint end(end_addr);
if (beg.chunk == end.chunk) {
CHECK_LT(beg.offset, end.offset);
s8 value = beg.value;
CHECK_EQ(value, end.value);
// We can only poison memory if the byte in end.offset is unaddressable.
// No need to re-poison memory if it is poisoned already.
if (value > 0 && value <= end.offset) {
if (beg.offset > 0) {
*beg.chunk = Min(value, beg.offset);
} else {
*beg.chunk = kAsanUserPoisonedMemoryMagic;
}
}
return;
}
CHECK_LT(beg.chunk, end.chunk);
if (beg.offset > 0) {
// Mark bytes from beg.offset as unaddressable.
if (beg.value == 0) {
*beg.chunk = beg.offset;
} else {
*beg.chunk = Min(beg.value, beg.offset);
}
beg.chunk++;
}
REAL(memset)(beg.chunk, kAsanUserPoisonedMemoryMagic, end.chunk - beg.chunk);
// Poison if byte in end.offset is unaddressable.
if (end.value > 0 && end.value <= end.offset) {
*end.chunk = kAsanUserPoisonedMemoryMagic;
}
}
void __asan_unpoison_memory_region(void const volatile *addr, uptr size) {
if (!flags()->allow_user_poisoning || size == 0) return;
uptr beg_addr = (uptr)addr;
uptr end_addr = beg_addr + size;
VPrintf(3, "Trying to unpoison memory region [%p, %p)\n", (void *)beg_addr,
(void *)end_addr);
ShadowSegmentEndpoint beg(beg_addr);
ShadowSegmentEndpoint end(end_addr);
if (beg.chunk == end.chunk) {
CHECK_LT(beg.offset, end.offset);
s8 value = beg.value;
CHECK_EQ(value, end.value);
// We unpoison memory bytes up to enbytes up to end.offset if it is not
// unpoisoned already.
if (value != 0) {
*beg.chunk = Max(value, end.offset);
}
return;
}
CHECK_LT(beg.chunk, end.chunk);
REAL(memset)(beg.chunk, 0, end.chunk - beg.chunk);
if (end.offset > 0 && end.value != 0) {
*end.chunk = Max(end.value, end.offset);
}
}
int __asan_address_is_poisoned(void const volatile *addr) {
return __asan::AddressIsPoisoned((uptr)addr);
}
uptr __asan_region_is_poisoned(uptr beg, uptr size) {
if (!size)
return 0;
uptr end = beg + size;
if (!AddrIsInMem(beg))
return beg;
if (!AddrIsInMem(end))
return end;
CHECK_LT(beg, end);
uptr aligned_b = RoundUpTo(beg, ASAN_SHADOW_GRANULARITY);
uptr aligned_e = RoundDownTo(end, ASAN_SHADOW_GRANULARITY);
uptr shadow_beg = MemToShadow(aligned_b);
uptr shadow_end = MemToShadow(aligned_e);
// First check the first and the last application bytes,
// then check the ASAN_SHADOW_GRANULARITY-aligned region by calling
// mem_is_zero on the corresponding shadow.
if (!__asan::AddressIsPoisoned(beg) && !__asan::AddressIsPoisoned(end - 1) &&
(shadow_end <= shadow_beg ||
__sanitizer::mem_is_zero((const char *)shadow_beg,
shadow_end - shadow_beg)))
return 0;
// The fast check failed, so we have a poisoned byte somewhere.
// Find it slowly.
for (; beg < end; beg++)
if (__asan::AddressIsPoisoned(beg))
return beg;
UNREACHABLE("mem_is_zero returned false, but poisoned byte was not found");
return 0;
}
#define CHECK_SMALL_REGION(p, size, isWrite) \
do { \
uptr __p = reinterpret_cast<uptr>(p); \
uptr __size = size; \
if (UNLIKELY(__asan::AddressIsPoisoned(__p) || \
__asan::AddressIsPoisoned(__p + __size - 1))) { \
GET_CURRENT_PC_BP_SP; \
uptr __bad = __asan_region_is_poisoned(__p, __size); \
__asan_report_error(pc, bp, sp, __bad, isWrite, __size, 0);\
} \
} while (false)
extern "C" SANITIZER_INTERFACE_ATTRIBUTE
u16 __sanitizer_unaligned_load16(const uu16 *p) {
CHECK_SMALL_REGION(p, sizeof(*p), false);
return *p;
}
extern "C" SANITIZER_INTERFACE_ATTRIBUTE
u32 __sanitizer_unaligned_load32(const uu32 *p) {
CHECK_SMALL_REGION(p, sizeof(*p), false);
return *p;
}
extern "C" SANITIZER_INTERFACE_ATTRIBUTE
u64 __sanitizer_unaligned_load64(const uu64 *p) {
CHECK_SMALL_REGION(p, sizeof(*p), false);
return *p;
}
extern "C" SANITIZER_INTERFACE_ATTRIBUTE
void __sanitizer_unaligned_store16(uu16 *p, u16 x) {
CHECK_SMALL_REGION(p, sizeof(*p), true);
*p = x;
}
extern "C" SANITIZER_INTERFACE_ATTRIBUTE
void __sanitizer_unaligned_store32(uu32 *p, u32 x) {
CHECK_SMALL_REGION(p, sizeof(*p), true);
*p = x;
}
extern "C" SANITIZER_INTERFACE_ATTRIBUTE
void __sanitizer_unaligned_store64(uu64 *p, u64 x) {
CHECK_SMALL_REGION(p, sizeof(*p), true);
*p = x;
}
extern "C" SANITIZER_INTERFACE_ATTRIBUTE
void __asan_poison_cxx_array_cookie(uptr p) {
if (SANITIZER_WORDSIZE != 64) return;
if (!flags()->poison_array_cookie) return;
uptr s = MEM_TO_SHADOW(p);
*reinterpret_cast<u8*>(s) = kAsanArrayCookieMagic;
}
extern "C" SANITIZER_INTERFACE_ATTRIBUTE
uptr __asan_load_cxx_array_cookie(uptr *p) {
if (SANITIZER_WORDSIZE != 64) return *p;
if (!flags()->poison_array_cookie) return *p;
uptr s = MEM_TO_SHADOW(reinterpret_cast<uptr>(p));
u8 sval = *reinterpret_cast<u8*>(s);
if (sval == kAsanArrayCookieMagic) return *p;
// If sval is not kAsanArrayCookieMagic it can only be freed memory,
// which means that we are going to get double-free. So, return 0 to avoid
// infinite loop of destructors. We don't want to report a double-free here
// though, so print a warning just in case.
// CHECK_EQ(sval, kAsanHeapFreeMagic);
if (sval == kAsanHeapFreeMagic) {
Report("AddressSanitizer: loaded array cookie from free-d memory; "
"expect a double-free report\n");
return 0;
}
// The cookie may remain unpoisoned if e.g. it comes from a custom
// operator new defined inside a class.
return *p;
}
// This is a simplified version of __asan_(un)poison_memory_region, which
// assumes that left border of region to be poisoned is properly aligned.
static void PoisonAlignedStackMemory(uptr addr, uptr size, bool do_poison) {
if (size == 0) return;
uptr aligned_size = size & ~(ASAN_SHADOW_GRANULARITY - 1);
PoisonShadow(addr, aligned_size,
do_poison ? kAsanStackUseAfterScopeMagic : 0);
if (size == aligned_size)
return;
s8 end_offset = (s8)(size - aligned_size);
s8* shadow_end = (s8*)MemToShadow(addr + aligned_size);
s8 end_value = *shadow_end;
if (do_poison) {
// If possible, mark all the bytes mapping to last shadow byte as
// unaddressable.
if (end_value > 0 && end_value <= end_offset)
*shadow_end = (s8)kAsanStackUseAfterScopeMagic;
} else {
// If necessary, mark few first bytes mapping to last shadow byte
// as addressable
if (end_value != 0)
*shadow_end = Max(end_value, end_offset);
}
}
void __asan_set_shadow_00(uptr addr, uptr size) {
REAL(memset)((void *)addr, 0, size);
}
void __asan_set_shadow_01(uptr addr, uptr size) {
REAL(memset)((void *)addr, 0x01, size);
}
void __asan_set_shadow_02(uptr addr, uptr size) {
REAL(memset)((void *)addr, 0x02, size);
}
void __asan_set_shadow_03(uptr addr, uptr size) {
REAL(memset)((void *)addr, 0x03, size);
}
void __asan_set_shadow_04(uptr addr, uptr size) {
REAL(memset)((void *)addr, 0x04, size);
}
void __asan_set_shadow_05(uptr addr, uptr size) {
REAL(memset)((void *)addr, 0x05, size);
}
void __asan_set_shadow_06(uptr addr, uptr size) {
REAL(memset)((void *)addr, 0x06, size);
}
void __asan_set_shadow_07(uptr addr, uptr size) {
REAL(memset)((void *)addr, 0x07, size);
}
void __asan_set_shadow_f1(uptr addr, uptr size) {
REAL(memset)((void *)addr, 0xf1, size);
}
void __asan_set_shadow_f2(uptr addr, uptr size) {
REAL(memset)((void *)addr, 0xf2, size);
}
void __asan_set_shadow_f3(uptr addr, uptr size) {
REAL(memset)((void *)addr, 0xf3, size);
}
void __asan_set_shadow_f5(uptr addr, uptr size) {
REAL(memset)((void *)addr, 0xf5, size);
}
void __asan_set_shadow_f8(uptr addr, uptr size) {
REAL(memset)((void *)addr, 0xf8, size);
}
void __asan_poison_stack_memory(uptr addr, uptr size) {
VReport(1, "poisoning: %p %zx\n", (void *)addr, size);
PoisonAlignedStackMemory(addr, size, true);
}
void __asan_unpoison_stack_memory(uptr addr, uptr size) {
VReport(1, "unpoisoning: %p %zx\n", (void *)addr, size);
PoisonAlignedStackMemory(addr, size, false);
}
static void FixUnalignedStorage(uptr storage_beg, uptr storage_end,
uptr &old_beg, uptr &old_end, uptr &new_beg,
uptr &new_end) {
constexpr uptr granularity = ASAN_SHADOW_GRANULARITY;
if (UNLIKELY(!AddrIsAlignedByGranularity(storage_end))) {
uptr end_down = RoundDownTo(storage_end, granularity);
// Ignore the last unaligned granule if the storage is followed by
// unpoisoned byte, because we can't poison the prefix anyway. Don't call
// AddressIsPoisoned at all if container changes does not affect the last
// granule at all.
if ((((old_end != new_end) && Max(old_end, new_end) > end_down) ||
((old_beg != new_beg) && Max(old_beg, new_beg) > end_down)) &&
!AddressIsPoisoned(storage_end)) {
old_beg = Min(end_down, old_beg);
old_end = Min(end_down, old_end);
new_beg = Min(end_down, new_beg);
new_end = Min(end_down, new_end);
}
}
// Handle misaligned begin and cut it off.
if (UNLIKELY(!AddrIsAlignedByGranularity(storage_beg))) {
uptr beg_up = RoundUpTo(storage_beg, granularity);
// The first unaligned granule needs special handling only if we had bytes
// there before and will have none after.
if ((new_beg == new_end || new_beg >= beg_up) && old_beg != old_end &&
old_beg < beg_up) {
// Keep granule prefix outside of the storage unpoisoned.
uptr beg_down = RoundDownTo(storage_beg, granularity);
*(u8 *)MemToShadow(beg_down) = storage_beg - beg_down;
old_beg = Max(beg_up, old_beg);
old_end = Max(beg_up, old_end);
new_beg = Max(beg_up, new_beg);
new_end = Max(beg_up, new_end);
}
}
}
void __sanitizer_annotate_contiguous_container(const void *beg_p,
const void *end_p,
const void *old_mid_p,
const void *new_mid_p) {
if (!flags()->detect_container_overflow)
return;
VPrintf(2, "contiguous_container: %p %p %p %p\n", beg_p, end_p, old_mid_p,
new_mid_p);
uptr storage_beg = reinterpret_cast<uptr>(beg_p);
uptr storage_end = reinterpret_cast<uptr>(end_p);
uptr old_end = reinterpret_cast<uptr>(old_mid_p);
uptr new_end = reinterpret_cast<uptr>(new_mid_p);
uptr old_beg = storage_beg;
uptr new_beg = storage_beg;
uptr granularity = ASAN_SHADOW_GRANULARITY;
if (!(storage_beg <= old_end && storage_beg <= new_end &&
old_end <= storage_end && new_end <= storage_end)) {
GET_STACK_TRACE_FATAL_HERE;
ReportBadParamsToAnnotateContiguousContainer(storage_beg, storage_end,
old_end, new_end, &stack);
}
CHECK_LE(storage_end - storage_beg,
FIRST_32_SECOND_64(1UL << 30, 1ULL << 40)); // Sanity check.
if (old_end == new_end)
return; // Nothing to do here.
FixUnalignedStorage(storage_beg, storage_end, old_beg, old_end, new_beg,
new_end);
uptr a = RoundDownTo(Min(old_end, new_end), granularity);
uptr c = RoundUpTo(Max(old_end, new_end), granularity);
uptr d1 = RoundDownTo(old_end, granularity);
// uptr d2 = RoundUpTo(old_mid, granularity);
// Currently we should be in this state:
// [a, d1) is good, [d2, c) is bad, [d1, d2) is partially good.
// Make a quick sanity check that we are indeed in this state.
//
// FIXME: Two of these three checks are disabled until we fix
// https://github.com/google/sanitizers/issues/258.
// if (d1 != d2)
// DCHECK_EQ(*(u8*)MemToShadow(d1), old_mid - d1);
//
// NOTE: curly brackets for the "if" below to silence a MSVC warning.
if (a + granularity <= d1) {
DCHECK_EQ(*(u8 *)MemToShadow(a), 0);
}
// if (d2 + granularity <= c && c <= end)
// DCHECK_EQ(*(u8 *)MemToShadow(c - granularity),
// kAsanContiguousContainerOOBMagic);
uptr b1 = RoundDownTo(new_end, granularity);
uptr b2 = RoundUpTo(new_end, granularity);
// New state:
// [a, b1) is good, [b2, c) is bad, [b1, b2) is partially good.
if (b1 > a)
PoisonShadow(a, b1 - a, 0);
else if (c > b2)
PoisonShadow(b2, c - b2, kAsanContiguousContainerOOBMagic);
if (b1 != b2) {
CHECK_EQ(b2 - b1, granularity);
*(u8 *)MemToShadow(b1) = static_cast<u8>(new_end - b1);
}
}
// Annotates a double ended contiguous memory area like std::deque's chunk.
// It allows detecting buggy accesses to allocated but not used begining
// or end items of such a container.
void __sanitizer_annotate_double_ended_contiguous_container(
const void *storage_beg_p, const void *storage_end_p,
const void *old_container_beg_p, const void *old_container_end_p,
const void *new_container_beg_p, const void *new_container_end_p) {
if (!flags()->detect_container_overflow)
return;
VPrintf(2, "contiguous_container: %p %p %p %p %p %p\n", storage_beg_p,
storage_end_p, old_container_beg_p, old_container_end_p,
new_container_beg_p, new_container_end_p);
uptr storage_beg = reinterpret_cast<uptr>(storage_beg_p);
uptr storage_end = reinterpret_cast<uptr>(storage_end_p);
uptr old_beg = reinterpret_cast<uptr>(old_container_beg_p);
uptr old_end = reinterpret_cast<uptr>(old_container_end_p);
uptr new_beg = reinterpret_cast<uptr>(new_container_beg_p);
uptr new_end = reinterpret_cast<uptr>(new_container_end_p);
constexpr uptr granularity = ASAN_SHADOW_GRANULARITY;
if (!(old_beg <= old_end && new_beg <= new_end) ||
!(storage_beg <= new_beg && new_end <= storage_end) ||
!(storage_beg <= old_beg && old_end <= storage_end)) {
GET_STACK_TRACE_FATAL_HERE;
ReportBadParamsToAnnotateDoubleEndedContiguousContainer(
storage_beg, storage_end, old_beg, old_end, new_beg, new_end, &stack);
}
CHECK_LE(storage_end - storage_beg,
FIRST_32_SECOND_64(1UL << 30, 1ULL << 40)); // Sanity check.
if ((old_beg == old_end && new_beg == new_end) ||
(old_beg == new_beg && old_end == new_end))
return; // Nothing to do here.
FixUnalignedStorage(storage_beg, storage_end, old_beg, old_end, new_beg,
new_end);
// Handle non-intersecting new/old containers separately have simpler
// intersecting case.
if (old_beg == old_end || new_beg == new_end || new_end <= old_beg ||
old_end <= new_beg) {
if (old_beg != old_end) {
// Poisoning the old container.
uptr a = RoundDownTo(old_beg, granularity);
uptr b = RoundUpTo(old_end, granularity);
PoisonShadow(a, b - a, kAsanContiguousContainerOOBMagic);
}
if (new_beg != new_end) {
// Unpoisoning the new container.
uptr a = RoundDownTo(new_beg, granularity);
uptr b = RoundDownTo(new_end, granularity);
PoisonShadow(a, b - a, 0);
if (!AddrIsAlignedByGranularity(new_end))
*(u8 *)MemToShadow(b) = static_cast<u8>(new_end - b);
}
return;
}
// Intersection of old and new containers is not empty.
CHECK_LT(new_beg, old_end);
CHECK_GT(new_end, old_beg);
if (new_beg < old_beg) {
// Round down because we can't poison prefixes.
uptr a = RoundDownTo(new_beg, granularity);
// Round down and ignore the [c, old_beg) as its state defined by unchanged
// [old_beg, old_end).
uptr c = RoundDownTo(old_beg, granularity);
PoisonShadow(a, c - a, 0);
} else if (new_beg > old_beg) {
// Round down and poison [a, old_beg) because it was unpoisoned only as a
// prefix.
uptr a = RoundDownTo(old_beg, granularity);
// Round down and ignore the [c, new_beg) as its state defined by unchanged
// [new_beg, old_end).
uptr c = RoundDownTo(new_beg, granularity);
PoisonShadow(a, c - a, kAsanContiguousContainerOOBMagic);
}
if (new_end > old_end) {
// Round down to poison the prefix.
uptr a = RoundDownTo(old_end, granularity);
// Round down and handle remainder below.
uptr c = RoundDownTo(new_end, granularity);
PoisonShadow(a, c - a, 0);
if (!AddrIsAlignedByGranularity(new_end))
*(u8 *)MemToShadow(c) = static_cast<u8>(new_end - c);
} else if (new_end < old_end) {
// Round up and handle remained below.
uptr a2 = RoundUpTo(new_end, granularity);
// Round up to poison entire granule as we had nothing in [old_end, c2).
uptr c2 = RoundUpTo(old_end, granularity);
PoisonShadow(a2, c2 - a2, kAsanContiguousContainerOOBMagic);
if (!AddrIsAlignedByGranularity(new_end)) {
uptr a = RoundDownTo(new_end, granularity);
*(u8 *)MemToShadow(a) = static_cast<u8>(new_end - a);
}
}
}
static const void *FindBadAddress(uptr begin, uptr end, bool poisoned) {
CHECK_LE(begin, end);
constexpr uptr kMaxRangeToCheck = 32;
if (end - begin > kMaxRangeToCheck * 2) {
if (auto *bad = FindBadAddress(begin, begin + kMaxRangeToCheck, poisoned))
return bad;
if (auto *bad = FindBadAddress(end - kMaxRangeToCheck, end, poisoned))
return bad;
}
for (uptr i = begin; i < end; ++i)
if (AddressIsPoisoned(i) != poisoned)
return reinterpret_cast<const void *>(i);
return nullptr;
}
const void *__sanitizer_contiguous_container_find_bad_address(
const void *beg_p, const void *mid_p, const void *end_p) {
if (!flags()->detect_container_overflow)
return nullptr;
uptr granularity = ASAN_SHADOW_GRANULARITY;
uptr beg = reinterpret_cast<uptr>(beg_p);
uptr end = reinterpret_cast<uptr>(end_p);
uptr mid = reinterpret_cast<uptr>(mid_p);
CHECK_LE(beg, mid);
CHECK_LE(mid, end);
// If the byte after the storage is unpoisoned, everything in the granule
// before must stay unpoisoned.
uptr annotations_end =
(!AddrIsAlignedByGranularity(end) && !AddressIsPoisoned(end))
? RoundDownTo(end, granularity)
: end;
beg = Min(beg, annotations_end);
mid = Min(mid, annotations_end);
if (auto *bad = FindBadAddress(beg, mid, false))
return bad;
if (auto *bad = FindBadAddress(mid, annotations_end, true))
return bad;
return FindBadAddress(annotations_end, end, false);
}
int __sanitizer_verify_contiguous_container(const void *beg_p,
const void *mid_p,
const void *end_p) {
return __sanitizer_contiguous_container_find_bad_address(beg_p, mid_p,
end_p) == nullptr;
}
const void *__sanitizer_double_ended_contiguous_container_find_bad_address(
const void *storage_beg_p, const void *container_beg_p,
const void *container_end_p, const void *storage_end_p) {
if (!flags()->detect_container_overflow)
return nullptr;
uptr granularity = ASAN_SHADOW_GRANULARITY;
uptr storage_beg = reinterpret_cast<uptr>(storage_beg_p);
uptr storage_end = reinterpret_cast<uptr>(storage_end_p);
uptr beg = reinterpret_cast<uptr>(container_beg_p);
uptr end = reinterpret_cast<uptr>(container_end_p);
// The prefix of the firs granule of the container is unpoisoned.
if (beg != end)
beg = Max(storage_beg, RoundDownTo(beg, granularity));
// If the byte after the storage is unpoisoned, the prefix of the last granule
// is unpoisoned.
uptr annotations_end = (!AddrIsAlignedByGranularity(storage_end) &&
!AddressIsPoisoned(storage_end))
? RoundDownTo(storage_end, granularity)
: storage_end;
storage_beg = Min(storage_beg, annotations_end);
beg = Min(beg, annotations_end);
end = Min(end, annotations_end);
if (auto *bad = FindBadAddress(storage_beg, beg, true))
return bad;
if (auto *bad = FindBadAddress(beg, end, false))
return bad;
if (auto *bad = FindBadAddress(end, annotations_end, true))
return bad;
return FindBadAddress(annotations_end, storage_end, false);
}
int __sanitizer_verify_double_ended_contiguous_container(
const void *storage_beg_p, const void *container_beg_p,
const void *container_end_p, const void *storage_end_p) {
return __sanitizer_double_ended_contiguous_container_find_bad_address(
storage_beg_p, container_beg_p, container_end_p, storage_end_p) ==
nullptr;
}
extern "C" SANITIZER_INTERFACE_ATTRIBUTE
void __asan_poison_intra_object_redzone(uptr ptr, uptr size) {
AsanPoisonOrUnpoisonIntraObjectRedzone(ptr, size, true);
}
extern "C" SANITIZER_INTERFACE_ATTRIBUTE
void __asan_unpoison_intra_object_redzone(uptr ptr, uptr size) {
AsanPoisonOrUnpoisonIntraObjectRedzone(ptr, size, false);
}
// --- Implementation of LSan-specific functions --- {{{1
namespace __lsan {
bool WordIsPoisoned(uptr addr) {
return (__asan_region_is_poisoned(addr, sizeof(uptr)) != 0);
}
}
| 1 | 0.972713 | 1 | 0.972713 | game-dev | MEDIA | 0.520129 | game-dev | 0.966147 | 1 | 0.966147 |
retest/recheck | 10,664 | src/main/java/de/retest/recheck/review/GlobalChangeSetApplier.java | package de.retest.recheck.review;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang3.tuple.ImmutablePair;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import de.retest.recheck.report.ActionReplayResult;
import de.retest.recheck.report.TestReport;
import de.retest.recheck.review.counter.Counter;
import de.retest.recheck.review.counter.NopCounter;
import de.retest.recheck.ui.descriptors.Element;
import de.retest.recheck.ui.descriptors.IdentifyingAttributes;
import de.retest.recheck.ui.diff.AttributeDifference;
import de.retest.recheck.ui.diff.ElementDifference;
import de.retest.recheck.ui.diff.ElementIdentificationWarning;
import de.retest.recheck.ui.diff.InsertedDeletedElementDifference;
import de.retest.recheck.ui.review.ActionChangeSet;
import de.retest.recheck.ui.review.AttributeChanges;
import lombok.AccessLevel;
import lombok.Getter;
public class GlobalChangeSetApplier {
private final Counter counter;
private GlobalChangeSetApplier( final TestReport testReport, final Counter counter ) {
this.counter = counter;
attributeDiffsLookupMap = ArrayListMultimap.create();
warningsLookup = new HashMap<>();
insertedDiffsLookupMap = ArrayListMultimap.create();
deletedDiffsLookupMap = ArrayListMultimap.create();
actionChangeSetLookupMap = new HashMap<>();
fillReplayResultLookupMaps( testReport );
}
public static GlobalChangeSetApplier create( final TestReport testReport ) {
return create( testReport, NopCounter.getInstance() );
}
public static GlobalChangeSetApplier create( final TestReport testReport, final Counter counter ) {
return new GlobalChangeSetApplier( testReport, counter );
}
// Replay result lookup maps.
@Getter( AccessLevel.PACKAGE )
private final Multimap<ImmutablePair<String, String>, ActionReplayResult> attributeDiffsLookupMap;
@Getter( AccessLevel.PACKAGE )
private final HashMap<ImmutablePair<String, String>, Set<ElementIdentificationWarning>> warningsLookup;
@Getter( AccessLevel.PACKAGE )
private final Multimap<String, ActionReplayResult> insertedDiffsLookupMap;
@Getter( AccessLevel.PACKAGE )
private final Multimap<String, ActionReplayResult> deletedDiffsLookupMap;
private void fillReplayResultLookupMaps( final TestReport testReport ) {
testReport.getSuiteReplayResults().stream() //
.flatMap( suiteReplayResult -> suiteReplayResult.getTestReplayResults().stream() ) //
.flatMap( testReplayResult -> testReplayResult.getActionReplayResults().stream() ) //
.forEach( this::fillReplayResultLookupMaps );
}
private void fillReplayResultLookupMaps( final ActionReplayResult actionReplayResult ) {
for ( final ElementDifference elementDiff : actionReplayResult.getAllElementDifferences() ) {
if ( elementDiff.isInsertionOrDeletion() ) {
fillInsertedDeletedDifferencesLookupMaps( actionReplayResult, elementDiff );
} else {
fillAttributeDifferencesLookupMap( actionReplayResult, elementDiff );
}
}
}
private void fillInsertedDeletedDifferencesLookupMaps( final ActionReplayResult actionReplayResult,
final ElementDifference elementDiff ) {
final InsertedDeletedElementDifference insertedDeletedElementDiff =
(InsertedDeletedElementDifference) elementDiff.getIdentifyingAttributesDifference();
if ( insertedDeletedElementDiff.isInserted() ) {
insertedDiffsLookupMap.put( identifier( insertedDeletedElementDiff.getActual() ), actionReplayResult );
} else {
deletedDiffsLookupMap.put( identifier( elementDiff.getIdentifyingAttributes() ), actionReplayResult );
}
}
private void fillAttributeDifferencesLookupMap( final ActionReplayResult actionReplayResult,
final ElementDifference elementDiff ) {
final IdentifyingAttributes identifyingAttributes = elementDiff.getIdentifyingAttributes();
for ( final AttributeDifference attributeDifference : elementDiff.getAttributeDifferences() ) {
final ImmutablePair<String, String> key =
ImmutablePair.of( identifier( identifyingAttributes ), identifier( attributeDifference ) );
attributeDiffsLookupMap.put( key, actionReplayResult );
final List<ElementIdentificationWarning> warnings = attributeDifference.getElementIdentificationWarnings();
if ( !warnings.isEmpty() ) {
warningsLookup.computeIfAbsent( key, k -> new HashSet<>() ).addAll( warnings );
}
}
}
private Collection<ActionReplayResult> findAllActionResultsWithEqualDifferences(
final IdentifyingAttributes identifyingAttributes, final AttributeDifference attributeDifference ) {
return attributeDiffsLookupMap
.get( ImmutablePair.of( identifier( identifyingAttributes ), identifier( attributeDifference ) ) );
}
private Set<ElementIdentificationWarning> findAllWarningsForDifference( final IdentifyingAttributes attributes,
final AttributeDifference difference ) {
return warningsLookup.getOrDefault( ImmutablePair.of( identifier( attributes ), identifier( difference ) ),
Collections.emptySet() );
}
private ActionChangeSet findCorrespondingActionChangeSet( final ActionReplayResult actionReplayResult ) {
final ActionChangeSet actionChangeSet = actionChangeSetLookupMap.get( actionReplayResult );
assert actionChangeSet != null : "Error, introduce() wasn't called for this actionReplayResult!";
return actionChangeSet;
}
// Action change set lookup map.
private final Map<ActionReplayResult, ActionChangeSet> actionChangeSetLookupMap;
public void introduce( final ActionReplayResult actionReplayResult, final ActionChangeSet actionChangeSet ) {
actionChangeSetLookupMap.put( actionReplayResult, actionChangeSet );
}
// Add/remove element differences.
public void addChangeSetForAllEqualIdentAttributeChanges( final IdentifyingAttributes identifyingAttributes,
final AttributeDifference attributeDifference ) {
final Collection<ActionReplayResult> actionResultsWithDiffs =
findAllActionResultsWithEqualDifferences( identifyingAttributes, attributeDifference );
assert !actionResultsWithDiffs.isEmpty() : "Should have been added during load and thus not be empty!";
for ( final ActionReplayResult actionReplayResult : actionResultsWithDiffs ) {
final ActionChangeSet correspondingActionChangeSet = findCorrespondingActionChangeSet( actionReplayResult );
assert correspondingActionChangeSet != null : "Should have been added during load and thus not be empty!";
final AttributeChanges changes = correspondingActionChangeSet.getIdentAttributeChanges();
changes.add( identifyingAttributes, injectWarningsFor( identifyingAttributes, attributeDifference ) );
}
counter.add();
}
public void createChangeSetForAllEqualAttributesChanges( final IdentifyingAttributes identifyingAttributes,
final AttributeDifference attributeDifference ) {
for ( final ActionReplayResult actionReplayResult : findAllActionResultsWithEqualDifferences(
identifyingAttributes, attributeDifference ) ) {
final ActionChangeSet correspondingActionChangeSet = findCorrespondingActionChangeSet( actionReplayResult );
final AttributeChanges changes = correspondingActionChangeSet.getAttributesChanges();
changes.add( identifyingAttributes, injectWarningsFor( identifyingAttributes, attributeDifference ) );
}
counter.add();
}
public void removeChangeSetForAllEqualIdentAttributeChanges( final IdentifyingAttributes identifyingAttributes,
final AttributeDifference attributeDifference ) {
for ( final ActionReplayResult actionReplayResult : findAllActionResultsWithEqualDifferences(
identifyingAttributes, attributeDifference ) ) {
final ActionChangeSet correspondingActionChangeSet = findCorrespondingActionChangeSet( actionReplayResult );
final AttributeChanges changes = correspondingActionChangeSet.getIdentAttributeChanges();
changes.remove( identifyingAttributes, injectWarningsFor( identifyingAttributes, attributeDifference ) );
}
counter.remove();
}
public void removeChangeSetForAllEqualAttributesChanges( final IdentifyingAttributes identifyingAttributes,
final AttributeDifference attributeDifference ) {
for ( final ActionReplayResult actionReplayResult : findAllActionResultsWithEqualDifferences(
identifyingAttributes, attributeDifference ) ) {
final ActionChangeSet correspondingActionChangeSet = findCorrespondingActionChangeSet( actionReplayResult );
final AttributeChanges changes = correspondingActionChangeSet.getAttributesChanges();
changes.remove( identifyingAttributes, injectWarningsFor( identifyingAttributes, attributeDifference ) );
}
counter.remove();
}
private AttributeDifference injectWarningsFor( final IdentifyingAttributes attributes,
final AttributeDifference difference ) {
final AttributeDifference copy =
new AttributeDifference( difference.getKey(), difference.getExpected(), difference.getActual() );
copy.addElementIdentificationWarnings( findAllWarningsForDifference( attributes, difference ) );
return copy;
}
// Add/remove inserted/deleted differences.
public void addChangeSetForAllEqualInsertedChanges( final Element inserted ) {
for ( final ActionReplayResult replayResult : insertedDiffsLookupMap.get( identifier( inserted ) ) ) {
findCorrespondingActionChangeSet( replayResult ).addInsertChange( inserted );
}
counter.add();
}
public void addChangeSetForAllEqualDeletedChanges( final IdentifyingAttributes deleted ) {
for ( final ActionReplayResult replayResult : deletedDiffsLookupMap.get( identifier( deleted ) ) ) {
findCorrespondingActionChangeSet( replayResult ).addDeletedChange( deleted );
}
counter.add();
}
public void removeChangeSetForAllEqualInsertedChanges( final Element inserted ) {
for ( final ActionReplayResult replayResult : insertedDiffsLookupMap.get( identifier( inserted ) ) ) {
findCorrespondingActionChangeSet( replayResult ).removeInsertChange( inserted );
}
counter.remove();
}
public void removeChangeSetForAllEqualDeletedChanges( final IdentifyingAttributes deleted ) {
for ( final ActionReplayResult replayResult : deletedDiffsLookupMap.get( identifier( deleted ) ) ) {
findCorrespondingActionChangeSet( replayResult ).removeDeletedChange( deleted );
}
counter.remove();
}
private String identifier( final Element element ) {
return identifier( element.getIdentifyingAttributes() );
}
private String identifier( final IdentifyingAttributes attributes ) {
return attributes.identifier();
}
private String identifier( final AttributeDifference difference ) {
return difference.identifier();
}
}
| 1 | 0.885027 | 1 | 0.885027 | game-dev | MEDIA | 0.437037 | game-dev | 0.948023 | 1 | 0.948023 |
lordofduct/spacepuppy-unity-framework-4.0 | 5,925 | Framework/com.spacepuppy.input/Runtime/src/SPInput/InputSignatureCollection.cs | using UnityEngine;
using System.Collections.Generic;
namespace com.spacepuppy.SPInput
{
public class InputSignatureCollection : IInputSignatureCollection
{
#region Fields
private Dictionary<string, IInputSignature> _table = new Dictionary<string, IInputSignature>();
private List<IInputSignature> _sortedList = new List<IInputSignature>();
#endregion
#region Methods
public Enumerator GetEnumerator()
{
return new Enumerator(this);
}
#endregion
#region IInputSignatureCollection Interface
public virtual IInputSignature GetSignature(string id)
{
IInputSignature result;
if (_table.TryGetValue(id, out result) && result != null && result.Id == id)
{
return result;
}
return null;
}
public virtual bool Contains(string id)
{
IInputSignature result;
if (_table.TryGetValue(id, out result) && result != null && result.Id == id)
{
return true;
}
return false;
}
public virtual bool Remove(string id)
{
IInputSignature sig;
if (_table.TryGetValue(id, out sig) && _table.Remove(id))
{
_sortedList.Remove(sig);
return true;
}
return false;
}
public void Sort()
{
_sortedList.Sort(SortOnPrecedence);
}
public void Update(bool isFixed)
{
var e = _table.GetEnumerator();
if (isFixed)
{
while (e.MoveNext())
{
e.Current.Value.FixedUpdate();
}
}
else
{
while (e.MoveNext())
{
e.Current.Value.Update();
}
}
}
#endregion
#region ICollection Interface
public int Count
{
get { return _table.Count; }
}
public void Add(IInputSignature item)
{
if (item == null) throw new System.ArgumentNullException("item");
if (_table.ContainsKey(item.Id)) throw new System.ArgumentException("A signature already exists with this Id and/or Hash.", "item");
var e = _table.GetEnumerator();
while (e.MoveNext())
{
if (e.Current.Value.Id == item.Id)
{
throw new System.ArgumentException("A signature already exists with this Id and/or Hash.", "item");
}
}
_table[item.Id] = item;
_sortedList.Add(item);
}
public void Clear()
{
_table.Clear();
_sortedList.Clear();
}
public bool Contains(IInputSignature item)
{
return _sortedList.Contains(item);
}
public void CopyTo(IInputSignature[] array, int arrayIndex)
{
_sortedList.CopyTo(array, arrayIndex);
}
bool ICollection<IInputSignature>.IsReadOnly
{
get { return false; }
}
public bool Remove(IInputSignature item)
{
var e = _table.GetEnumerator();
while (e.MoveNext())
{
if (e.Current.Value == item)
{
if (_table.Remove(e.Current.Key))
{
_sortedList.Remove(item);
return true;
}
else
return false;
}
}
return false;
}
IEnumerator<IInputSignature> IEnumerable<IInputSignature>.GetEnumerator()
{
return this.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
#endregion
#region Special Types
public struct Enumerator : IEnumerator<IInputSignature>
{
private List<IInputSignature>.Enumerator _e;
public Enumerator(InputSignatureCollection coll)
{
if (coll == null) throw new System.ArgumentNullException("coll");
_e = coll._sortedList.GetEnumerator();
}
public IInputSignature Current
{
get { return _e.Current; }
}
object System.Collections.IEnumerator.Current
{
get { return _e.Current; }
}
public bool MoveNext()
{
return _e.MoveNext();
}
void System.Collections.IEnumerator.Reset()
{
(_e as System.Collections.IEnumerator).Reset();
}
public void Dispose()
{
_e.Dispose();
}
}
#endregion
#region Sort Methods
private static System.Comparison<IInputSignature> _sortOnPrecedence;
private static System.Comparison<IInputSignature> SortOnPrecedence
{
get
{
if (_sortOnPrecedence == null)
{
_sortOnPrecedence = (a, b) =>
{
if (a.Precedence > b.Precedence)
return 1;
if (a.Precedence < b.Precedence)
return -1;
else
return 0;
};
}
return _sortOnPrecedence;
}
}
#endregion
}
}
| 1 | 0.913762 | 1 | 0.913762 | game-dev | MEDIA | 0.549513 | game-dev | 0.980284 | 1 | 0.980284 |
magefree/mage | 1,837 | Mage.Sets/src/mage/cards/h/HyenaUmbra.java | package mage.cards.h;
import mage.abilities.Ability;
import mage.abilities.common.SimpleStaticAbility;
import mage.abilities.effects.common.AttachEffect;
import mage.abilities.effects.common.continuous.BoostEnchantedEffect;
import mage.abilities.effects.common.continuous.GainAbilityAttachedEffect;
import mage.abilities.keyword.EnchantAbility;
import mage.abilities.keyword.FirstStrikeAbility;
import mage.abilities.keyword.UmbraArmorAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.*;
import mage.target.TargetPermanent;
import mage.target.common.TargetCreaturePermanent;
import java.util.UUID;
/**
* @author Loki
*/
public final class HyenaUmbra extends CardImpl {
public HyenaUmbra(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.ENCHANTMENT}, "{W}");
this.subtype.add(SubType.AURA);
// Enchant creature
TargetPermanent auraTarget = new TargetCreaturePermanent();
this.getSpellAbility().addTarget(auraTarget);
this.getSpellAbility().addEffect(new AttachEffect(Outcome.BoostCreature));
this.addAbility(new EnchantAbility(auraTarget));
// Enchanted creature gets +1/+1 and has first strike.
Ability ability = new SimpleStaticAbility(new BoostEnchantedEffect(
1, 1, Duration.WhileOnBattlefield
));
ability.addEffect(new GainAbilityAttachedEffect(
FirstStrikeAbility.getInstance(), AttachmentType.AURA
).setText("and has first strike"));
this.addAbility(ability);
// Umbra armor
this.addAbility(new UmbraArmorAbility());
}
private HyenaUmbra(final HyenaUmbra card) {
super(card);
}
@Override
public HyenaUmbra copy() {
return new HyenaUmbra(this);
}
}
| 1 | 0.937461 | 1 | 0.937461 | game-dev | MEDIA | 0.967963 | game-dev | 0.949614 | 1 | 0.949614 |
TeamWizardry/Wizardry | 13,985 | src/main/java/com/teamwizardry/wizardry/common/potion/PotionPhase.java | package com.teamwizardry.wizardry.common.potion;
import com.teamwizardry.wizardry.api.ConfigValues;
import com.teamwizardry.wizardry.api.events.EntityMoveEvent;
import com.teamwizardry.wizardry.api.events.PlayerClipEvent;
import com.teamwizardry.wizardry.api.util.BlockUtils;
import com.teamwizardry.wizardry.init.ModPotions;
import net.minecraft.block.Block;
import net.minecraft.block.BlockFence;
import net.minecraft.block.BlockFenceGate;
import net.minecraft.block.BlockWall;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.crash.CrashReport;
import net.minecraft.crash.CrashReportCategory;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.MoverType;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.util.ReportedException;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.world.World;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import java.util.List;
/**
* Created by Demoniaque.
*/
public class PotionPhase extends PotionBase {
public PotionPhase() {
super("phase", false, 0xDAEFE7);
MinecraftForge.EVENT_BUS.register(this);
}
@SubscribeEvent
public void playerClipEvent(PlayerClipEvent event) {
if (event.player.isPotionActive(ModPotions.PHASE)) {
event.noClip = true;
}
}
@SubscribeEvent
public void entityMove(EntityMoveEvent event) {
if (!(event.entity instanceof EntityLivingBase)) return;
EntityLivingBase base = (EntityLivingBase) event.entity;
if (!base.isPotionActive(ModPotions.PHASE)) return;
event.setCanceled(true); // TODO: 10/6/18 fix your shit demoniaque
//event.entity.noClip = true;
event.entity.fallDistance = 0;
event.entity.isAirBorne = true;
Entity entity = event.entity;
double x = event.x;
double y = event.y;
double z = event.z;
MoverType type = event.type;
entity.world.profiler.startSection("move");
double d10 = entity.posX;
double d11 = entity.posY;
double d1 = entity.posZ;
double d2 = x;
double d3 = y;
double d4 = z;
if ((type == MoverType.SELF || type == MoverType.PLAYER) && entity.onGround && entity.isSneaking() && entity instanceof EntityPlayer) {
for (; x != 0.0D && entity.world.getCollisionBoxes(entity, entity.getEntityBoundingBox().offset(x, -entity.stepHeight, 0.0D)).isEmpty(); d2 = x) {
if (x >= 0.05D || x < -0.05D) {
if (x > 0.0D) {
x -= 0.05D;
} else {
x += 0.05D;
}
} else x = 0.0D;
}
for (; z != 0.0D && entity.world.getCollisionBoxes(entity, entity.getEntityBoundingBox().offset(0.0D, -entity.stepHeight, z)).isEmpty(); d4 = z) {
if (z >= 0.05D || z < -0.05D) {
if (z > 0.0D) {
z -= 0.05D;
} else {
z += 0.05D;
}
} else z = 0.0D;
}
for (; x != 0.0D && z != 0.0D && entity.world.getCollisionBoxes(entity, entity.getEntityBoundingBox().offset(x, -entity.stepHeight, z)).isEmpty(); d4 = z) {
if (x >= 0.05D || x < -0.05D) {
if (x > 0.0D) {
x -= 0.05D;
} else {
x += 0.05D;
}
} else x = 0.0D;
d2 = x;
if (z >= 0.05D || z < -0.05D) {
if (z > 0.0D) {
z -= 0.05D;
} else {
z += 0.05D;
}
} else y = 0.0D;
}
}
List<AxisAlignedBB> list1 = entity.world.getCollisionBoxes(entity, entity.getEntityBoundingBox().offset(x, y, z));
AxisAlignedBB axisalignedbb = entity.getEntityBoundingBox();
if (y != 0.0D) {
int k = 0;
for (int l = list1.size(); k < l; ++k) {
AxisAlignedBB collision = list1.get(k);
double offsetY = collision.calculateYOffset(entity.getEntityBoundingBox(), y);
if (BlockUtils.isBlockBlacklistedInPhaseEffect(getBlockFromCollisionBox(collision, entity.world))) {
y = offsetY;
}
if (offsetY <= 0)
y = offsetY;
}
double yModifier = 0;
if (y == 0 && entity.isSneaking()) {
int j6 = MathHelper.floor(entity.posX);
int i1 = MathHelper.floor(entity.posY - 0.20000000298023224D);
int k6 = MathHelper.floor(entity.posZ);
BlockPos blockpos = new BlockPos(j6, i1, k6);
IBlockState blockState = entity.world.getBlockState(blockpos);
if (!isBlacklistedBlock(blockState.getBlock())) {
yModifier = -0.1;
}
}
entity.setEntityBoundingBox(entity.getEntityBoundingBox().offset(0.0D, y + yModifier, 0.0D));
}
if (x != 0.0D) {
int j5 = 0;
for (int l5 = list1.size(); j5 < l5; ++j5)
{
AxisAlignedBB collision = list1.get(j5);
if (BlockUtils.isBlockBlacklistedInPhaseEffect(getBlockFromCollisionBox(collision, entity.world))) {
x = collision.calculateXOffset(entity.getEntityBoundingBox(), x);
}
}
if (x != 0.0D)
entity.setEntityBoundingBox(entity.getEntityBoundingBox().offset(x, 0.0D, 0.0D));
}
if (z != 0.0D) {
int k5 = 0;
for (int i6 = list1.size(); k5 < i6; ++k5)
{
AxisAlignedBB collision = list1.get(k5);
if (BlockUtils.isBlockBlacklistedInPhaseEffect(getBlockFromCollisionBox(collision, entity.world))) {
z = collision.calculateZOffset(entity.getEntityBoundingBox(), z);
}
}
if (z != 0.0D)
entity.setEntityBoundingBox(entity.getEntityBoundingBox().offset(0.0D, 0.0D, z));
}
boolean flag = entity.onGround || d3 != y && d3 < 0.0D;
if (entity.stepHeight > 0.0F && flag && (d2 != x || d4 != z)) {
double d14 = x;
double d6 = y;
double d7 = z;
AxisAlignedBB axisalignedbb1 = entity.getEntityBoundingBox();
entity.setEntityBoundingBox(axisalignedbb);
y = entity.stepHeight;
List<AxisAlignedBB> list = entity.world.getCollisionBoxes(entity, entity.getEntityBoundingBox().offset(d2, y, d4));
AxisAlignedBB axisalignedbb2 = entity.getEntityBoundingBox();
AxisAlignedBB axisalignedbb3 = axisalignedbb2.offset(d2, 0.0D, d4);
double d8 = y;
int j1 = 0;
for (int k1 = list.size(); j1 < k1; ++j1) {
AxisAlignedBB collision = list1.get(j1);
double offsetY = collision.calculateYOffset(axisalignedbb3, y);
if (BlockUtils.isBlockBlacklistedInPhaseEffect(getBlockFromCollisionBox(collision, entity.world))) {
d8 = offsetY;
}
if (offsetY <= 0)
d8 = offsetY;
}
axisalignedbb2 = axisalignedbb2.offset(0.0D, d8, 0.0D);
double d18 = d2;
int l1 = 0;
for (int i2 = list.size(); l1 < i2; ++l1)
{
AxisAlignedBB collision = list.get(l1);
if (BlockUtils.isBlockBlacklistedInPhaseEffect(getBlockFromCollisionBox(collision, entity.world))) {
d18 = collision.calculateXOffset(axisalignedbb2, d18);
}
}
axisalignedbb2 = axisalignedbb2.offset(d2, 0.0D, 0.0D);
double d19 = d4;
int j2 = 0;
for (int k2 = list.size(); j2 < k2; ++j2)
{
AxisAlignedBB collision = list.get(j2);
if (BlockUtils.isBlockBlacklistedInPhaseEffect(getBlockFromCollisionBox(collision, entity.world))) {
d19 = collision.calculateZOffset(axisalignedbb2, d19);
}
}
axisalignedbb2 = axisalignedbb2.offset(0.0D, 0.0D, d4);
AxisAlignedBB axisalignedbb4 = entity.getEntityBoundingBox();
double d20 = y;
int l2 = 0;
for (int i3 = list.size(); l2 < i3; ++l2) {
AxisAlignedBB collision = list1.get(l2);
double offsetY = collision.calculateYOffset(axisalignedbb4, y);
if (BlockUtils.isBlockBlacklistedInPhaseEffect(getBlockFromCollisionBox(collision, entity.world))) {
d20 = offsetY;
}
if (offsetY <= 0)
d20 = offsetY;
}
axisalignedbb4 = axisalignedbb4.offset(0.0D, d20, 0.0D);
double d21 = d2;
int j3 = 0;
for (int k3 = list.size(); j3 < k3; ++j3)
{
AxisAlignedBB collision = list.get(j3);
if (BlockUtils.isBlockBlacklistedInPhaseEffect(getBlockFromCollisionBox(collision, entity.world))) {
d21 = collision.calculateXOffset(axisalignedbb4, d21);
}
}
axisalignedbb4 = axisalignedbb4.offset(d2, 0.0D, 0.0D);
double d22 = d4;
int l3 = 0;
for (int i4 = list.size(); l3 < i4; ++l3)
{
AxisAlignedBB collision = list.get(l3);
if (BlockUtils.isBlockBlacklistedInPhaseEffect(getBlockFromCollisionBox(collision, entity.world))) {
d22 = collision.calculateZOffset(axisalignedbb4, d22);
}
}
axisalignedbb4 = axisalignedbb4.offset(0.0D, 0.0D, d4);
double d23 = d2 * d2 + d4 * d4;
double d9 = d2 * d2 + d4 * d4;
if (d23 > d9) {
x = d18;
z = d19;
y = -d8;
entity.setEntityBoundingBox(axisalignedbb2);
} else {
x = d21;
z = d22;
y = -d20;
entity.setEntityBoundingBox(axisalignedbb4);
}
int j4 = 0;
for (int k4 = list.size(); j4 < k4; ++j4) {
AxisAlignedBB collision = list1.get(j4);
double offsetY = collision.calculateYOffset(entity.getEntityBoundingBox(), y);
if (BlockUtils.isBlockBlacklistedInPhaseEffect(getBlockFromCollisionBox(collision, entity.world))) {
y = offsetY;
}
if (offsetY <= 0)
y = offsetY;
}
entity.setEntityBoundingBox(entity.getEntityBoundingBox().offset(0.0D, y, 0.0D));
if (d14 * d14 + d7 * d7 >= x * x + z * z) {
x = d14;
y = d6;
z = d7;
entity.setEntityBoundingBox(axisalignedbb1);
}
}
entity.world.profiler.endSection();
entity.world.profiler.startSection("rest");
entity.resetPositionToBB();
entity.collidedHorizontally = d2 != x || d4 != z;
entity.collidedVertically = d3 != y;
entity.onGround = entity.collidedVertically && d3 < 0.0D;
entity.collided = entity.collidedHorizontally || entity.collidedVertically;
int j6 = MathHelper.floor(entity.posX);
int i1 = MathHelper.floor(entity.posY - 0.20000000298023224D);
int k6 = MathHelper.floor(entity.posZ);
BlockPos blockpos = new BlockPos(j6, i1, k6);
IBlockState iblockstate = entity.world.getBlockState(blockpos);
if (iblockstate.getMaterial() == Material.AIR) {
BlockPos blockpos1 = blockpos.down();
IBlockState iblockstate1 = entity.world.getBlockState(blockpos1);
Block block1 = iblockstate1.getBlock();
if (block1 instanceof BlockFence || block1 instanceof BlockWall || block1 instanceof BlockFenceGate) {
iblockstate = iblockstate1;
blockpos = blockpos1;
}
}
Block block = iblockstate.getBlock();
if (d3 != y) {
block.onLanded(entity.world, entity);
}
if ((!entity.onGround || !entity.isSneaking() || !(entity instanceof EntityPlayer)) && !entity.isRiding()) {
double d15 = entity.posX - d10;
double d16 = entity.posY - d11;
double d17 = entity.posZ - d1;
if (block != Blocks.LADDER) {
d16 = 0.0D;
}
if (entity.onGround) {
block.onEntityWalk(entity.world, blockpos, entity);
}
entity.distanceWalkedModified = (float) ((double) entity.distanceWalkedModified + (double) MathHelper.sqrt(d15 * d15 + d17 * d17) * 0.6D);
entity.distanceWalkedOnStepModified = (float) ((double) entity.distanceWalkedOnStepModified + (double) MathHelper.sqrt(d15 * d15 + d16 * d16 + d17 * d17) * 0.6D);
}
try {
AxisAlignedBB bb = entity.getEntityBoundingBox();
BlockPos.PooledMutableBlockPos blockpos$pooledmutableblockpos = BlockPos.PooledMutableBlockPos.retain(bb.minX + 0.001D, bb.minY + 0.001D, bb.minZ + 0.001D);
BlockPos.PooledMutableBlockPos blockpos$pooledmutableblockpos1 = BlockPos.PooledMutableBlockPos.retain(bb.maxX - 0.001D, bb.maxY - 0.001D, bb.maxZ - 0.001D);
BlockPos.PooledMutableBlockPos blockpos$pooledmutableblockpos2 = BlockPos.PooledMutableBlockPos.retain();
if (entity.world.isAreaLoaded(blockpos$pooledmutableblockpos, blockpos$pooledmutableblockpos1)) {
for (int i = blockpos$pooledmutableblockpos.getX(); i <= blockpos$pooledmutableblockpos1.getX(); ++i) {
for (int j = blockpos$pooledmutableblockpos.getY(); j <= blockpos$pooledmutableblockpos1.getY(); ++j) {
for (int k = blockpos$pooledmutableblockpos.getZ(); k <= blockpos$pooledmutableblockpos1.getZ(); ++k) {
blockpos$pooledmutableblockpos2.setPos(i, j, k);
IBlockState state = entity.world.getBlockState(blockpos$pooledmutableblockpos2);
try {
state.getBlock().onEntityCollision(entity.world, blockpos$pooledmutableblockpos2, state, entity);
if (isBlacklistedBlock(state.getBlock())) {
entity.onInsideBlock(state);
}
} catch (Throwable throwable) {
CrashReport crashreport = CrashReport.makeCrashReport(throwable, "Colliding entity with block");
CrashReportCategory crashreportcategory = crashreport.makeCategory("Block being collided with");
CrashReportCategory.addBlockInfo(crashreportcategory, blockpos$pooledmutableblockpos2, state);
throw new ReportedException(crashreport);
}
}
}
}
}
blockpos$pooledmutableblockpos.release();
blockpos$pooledmutableblockpos1.release();
blockpos$pooledmutableblockpos2.release();
} catch (Throwable throwable) {
CrashReport crashreport = CrashReport.makeCrashReport(throwable, "Checking entity block collision");
CrashReportCategory crashreportcategory = crashreport.makeCategory("Entity being checked for collision");
entity.addEntityCrashInfo(crashreportcategory);
throw new ReportedException(crashreport);
}
entity.world.profiler.endSection();
//event.entity.noClip = false;
}
public Block getBlockFromCollisionBox(AxisAlignedBB collisionBox, World world) {
try {
BlockPos blockPos = new BlockPos(collisionBox.getCenter());
IBlockState blockState = world.getBlockState(blockPos);
return blockState.getBlock();
} catch(Exception ignored) {}
return Blocks.AIR;
}
public boolean isBlacklistedBlock(Block block) {
ResourceLocation registry = block.getRegistryName();
if (registry == null) {
return false;
}
String name = registry.toString();
for (String regName : ConfigValues.phaseBlocksBlackList) {
if (name.equals(regName)) {
return true;
}
}
return false;
}
} | 1 | 0.928927 | 1 | 0.928927 | game-dev | MEDIA | 0.869684 | game-dev | 0.939439 | 1 | 0.939439 |
defold/examples | 1,494 | animation/cursor/example/cursor.script | function init(self)
msg.post(".", "acquire_input_focus") -- <1>
-- Get the current value on component "sprite"
self.duration = 0 -- <2>
end
function on_input(self, action_id, action)
if action_id == hash("mouse_button_left") and action.pressed then -- <3>
self.duration = self.duration + 1 -- <4>
if self.duration > 3 then -- <5>
self.duration = 0
end
label.set_text("#info", "Cursor animation duration: "..self.duration) -- <6>
go.cancel_animations("#sprite", "cursor") -- <7>
go.set("#sprite", "cursor", 0.0) -- <8>
go.animate("#sprite", "cursor", go.PLAYBACK_LOOP_FORWARD, 1, go.EASING_LINEAR, self.duration) -- <9>
end
end
--[[
1. Tell the engine that this object ("." is shorthand for the current game object) should listen to input. Any input will be received in the `on_input()` function.
2. Store a duration time used in this example (for defining how long the cursor animation should take) in self reference.
3. If we receive input (touch or mouse click) we change the duration of the cursor animation.
4. Increase the duration.
5. If the duration is larger than 3, set it back to 0 to make a circular change of the duration.
6. Set the text of the label with id `info` to show the current duration of the animation to user.
7. Cancel previous animation on cursor value.
8. Reset cursor value to 0.
9. Start new animation of cursor value with playback set to be looped and in foward direction (increasing cursor value), linear easing and new duration.
--]]
| 1 | 0.642247 | 1 | 0.642247 | game-dev | MEDIA | 0.696786 | game-dev,web-frontend | 0.52866 | 1 | 0.52866 |
esoui/esoui | 34,499 | esoui/ingame/inventory/gamepad/guildbank_gamepad.lua | -------------------------------------
-- Gamepad Guild Bank Inventory List
-------------------------------------
ZO_GamepadGuildBankInventoryList = ZO_GamepadBankCommonInventoryList:Subclass()
function ZO_GamepadGuildBankInventoryList:Initialize(...)
ZO_GamepadBankCommonInventoryList.Initialize(self, ...)
self.list:AddDataTemplate("ZO_GamepadMenuEntryTemplate", ZO_SharedGamepadEntry_OnSetup, ZO_GamepadMenuEntryTemplateParametricListFunction)
local goldTransferEntryName = self:IsInWithdrawMode() and GetString(SI_GAMEPAD_BANK_WITHDRAW_GOLD_ENTRY_NAME) or GetString(SI_GAMEPAD_BANK_DEPOSIT_GOLD_ENTRY_NAME)
local goldTransferEntryIcon = self:IsInWithdrawMode() and "EsoUI/Art/Bank/Gamepad/gp_bank_menuIcon_gold_withdraw.dds" or "EsoUI/Art/Bank/Gamepad/gp_bank_menuIcon_gold_deposit.dds"
local entryData = ZO_GamepadEntryData:New(goldTransferEntryName, goldTransferEntryIcon)
entryData:SetIconTintOnSelection(true)
entryData:SetIconDisabledTintOnSelection(true)
entryData.currencyType = CURT_MONEY
self.goldTransferEntryData = entryData
end
do
local NO_DEPOSIT_PERMISSIONS_STRING = zo_strformat(SI_GAMEPAD_GUILD_BANK_NO_DEPOSIT_PERMISSIONS, GetNumGuildMembersRequiredForPrivilege(GUILD_PRIVILEGE_BANK_DEPOSIT))
local NO_WITHDRAW_PERMISSIONS_STRING = GetString(SI_GAMEPAD_GUILD_BANK_NO_WITHDRAW_PERMISSIONS)
local NO_ITEMS_TO_WITHDRAW_STRING = GetString(SI_GAMEPAD_GUILD_BANK_NO_WITHDRAW_ITEMS)
local function IsInFilteredCategories(filterCategories, itemData)
-- No category selected, don't filter out anything.
if ZO_IsTableEmpty(filterCategories) then
return true
end
for _, filterData in ipairs(itemData.filterData) do
if filterCategories[filterData] then
return true
end
end
return false
end
function ZO_GamepadGuildBankInventoryList:OnRefreshList(shouldTriggerRefreshListCallback)
if TEXT_SEARCH_MANAGER:IsSearchDirty(self.searchContext) then
return
end
local guildId = GetSelectedGuildBankId()
local shouldShowList = false
-- Assume we have all these privileges unless otherwise specified.
local guildHasDepositPrivilege = true
local playerCanWithdrawItem = true
local playerCanWithdrawGold = true
if guildId then
guildHasDepositPrivilege = DoesGuildHavePrivilege(guildId, GUILD_PRIVILEGE_BANK_DEPOSIT)
playerCanWithdrawItem = DoesPlayerHaveGuildPermission(guildId, GUILD_PERMISSION_BANK_WITHDRAW)
playerCanWithdrawGold = DoesPlayerHaveGuildPermission(guildId, GUILD_PERMISSION_BANK_WITHDRAW_GOLD)
if GAMEPAD_GUILD_BANK:IsLoadingGuildBank() then
self:SetNoItemText("")
elseif self:IsInDepositMode() then
if not guildHasDepositPrivilege then
self:SetNoItemText(NO_DEPOSIT_PERMISSIONS_STRING)
else
shouldShowList = DoesPlayerHaveGuildPermission(guildId, GUILD_PERMISSION_BANK_DEPOSIT)
end
elseif self:IsInWithdrawMode() then
if not (playerCanWithdrawItem or playerCanWithdrawGold) then
self:SetNoItemText(NO_WITHDRAW_PERMISSIONS_STRING)
else
self:SetNoItemText(NO_ITEMS_TO_WITHDRAW_STRING)
shouldShowList = playerCanWithdrawItem
end
else
self:SetNoItemText("")
end
else
self:SetNoItemText("")
end
self.list:Clear()
local function CanWithdrawOrDeposit(currencyType)
local canUse = true
-- Check if there are funds to withdraw or if the player's wallet isn't full, depending on the mode
if self:IsInWithdrawMode() then
canUse = DoesPlayerHaveGuildPermission(GetSelectedGuildBankId(), GUILD_PERMISSION_BANK_VIEW_GOLD) and GetCurrencyAmount(currencyType, CURRENCY_LOCATION_GUILD_BANK) ~= 0 and
GetCurrencyAmount(currencyType, CURRENCY_LOCATION_CHARACTER) ~= GetMaxPossibleCurrency(currencyType, CURRENCY_LOCATION_CHARACTER)
elseif self:IsInDepositMode() then
canUse = GetCurrencyAmount(currencyType, CURRENCY_LOCATION_GUILD_BANK) ~= GetMaxPossibleCurrency(currencyType, CURRENCY_LOCATION_GUILD_BANK) and
GetCurrencyAmount(currencyType, CURRENCY_LOCATION_CHARACTER) ~= 0
end
return canUse
end
local slots = nil
if shouldShowList then
slots = self:GenerateSlotTable()
end
local shouldAddDepositWithdrawEntry = (self:IsInWithdrawMode() and playerCanWithdrawGold) or (self:IsInDepositMode() and guildHasDepositPrivilege)
if shouldAddDepositWithdrawEntry then
self.goldTransferEntryData:SetEnabled(CanWithdrawOrDeposit(CURT_MONEY))
self.list:AddEntry("ZO_GamepadBankCurrencySelectorTemplate", self.goldTransferEntryData)
end
if shouldShowList then
for _, bagId in ipairs(self.inventoryTypes) do
self.dataByBagAndSlotIndex[bagId] = {}
end
local template = self.template
local currentBestCategoryName = nil
for _, itemData in ipairs(slots) do
local passesTextFilter = TEXT_SEARCH_MANAGER:IsDataInSearchTextResults(self.searchContext, BACKGROUND_LIST_FILTER_TARGET_BAG_SLOT, itemData.bagId, itemData.slotIndex)
local passesCategoryFilter = IsInFilteredCategories(self.filterCategories, itemData)
if passesTextFilter and passesCategoryFilter then
local entry = ZO_GamepadEntryData:New(itemData.name, itemData.iconFile)
self:SetupItemEntry(entry, itemData)
if self.currentSortType == ITEM_LIST_SORT_TYPE_CATEGORY and itemData.bestGamepadItemCategoryName ~= currentBestCategoryName then
currentBestCategoryName = itemData.bestGamepadItemCategoryName
entry:SetHeader(currentBestCategoryName)
self.list:AddEntryWithHeader(template, entry)
else
self.list:AddEntry(template, entry)
end
self.dataByBagAndSlotIndex[itemData.bagId][itemData.slotIndex] = entry
end
end
end
self.list:Commit()
if shouldTriggerRefreshListCallback and self.onRefreshListCallback then
self.onRefreshListCallback(self.list)
end
end
end
do
local BANK_MODE_INFO =
{
[BANKING_GAMEPAD_MODE_DEPOSIT] = { requirement = GUILD_PERMISSION_BANK_DEPOSIT, errorMessage = GetString("SI_GUILDBANKRESULT", GUILD_BANK_NO_DEPOSIT_PERMISSION)},
[BANKING_GAMEPAD_MODE_WITHDRAW] = { requirement = GUILD_PERMISSION_BANK_WITHDRAW, errorMessage = GetString("SI_GUILDBANKRESULT", GUILD_BANK_NO_WITHDRAW_PERMISSION)},
}
function ZO_GamepadGuildBankInventoryList:SetBankMode(mode)
local modeInfo = BANK_MODE_INFO[mode]
if modeInfo then
self.mode = mode
self.guildrequirement = modeInfo.requirement
self.requirementFailMessage = modeInfo.errorMessage
end
end
end
-----------------------
-- Gamepad Guild Bank
-----------------------
local GAMEPAD_GUILD_BANK_SCENE_NAME = "gamepad_guild_bank"
ZO_GuildBank_Gamepad = ZO_BankingCommon_Gamepad:Subclass()
function ZO_GuildBank_Gamepad:Initialize(control)
self.withdrawLoadingControlShown = false
GAMEPAD_GUILD_BANK_SCENE = ZO_InteractScene:New(GAMEPAD_GUILD_BANK_SCENE_NAME, SCENE_MANAGER, GUILD_BANKING_INTERACTION)
ZO_BankingCommon_Gamepad.Initialize(self, "guildBankTextSearch", control, GAMEPAD_GUILD_BANK_SCENE)
self:ClearBankedBags()
self:AddBankedBag(BAG_GUILDBANK)
self:SetCarriedBag(BAG_BACKPACK)
local function OnOpenGuildBank()
if IsInGamepadPreferredMode() then
self:ActivateTextSearch()
SCENE_MANAGER:Show(GAMEPAD_GUILD_BANK_SCENE_NAME)
end
end
local function OnCloseGuildBank()
if IsInGamepadPreferredMode() then
self:DeactivateTextSearch()
SCENE_MANAGER:Hide(GAMEPAD_GUILD_BANK_SCENE_NAME)
end
end
self.control:RegisterForEvent(EVENT_OPEN_GUILD_BANK, OnOpenGuildBank)
self.control:RegisterForEvent(EVENT_CLOSE_GUILD_BANK, OnCloseGuildBank)
end
function ZO_GuildBank_Gamepad:ActivateTextSearch()
if self.searchContext then
-- Reset the search string to force a search again since the guild bank slots get rebuild each show.
TEXT_SEARCH_MANAGER:MarkDirtyByFilterTargetAndPrimaryKey(BACKGROUND_LIST_FILTER_TARGET_BAG_SLOT, BAG_GUILDBANK)
ZO_Gamepad_ParametricList_BagsSearch_Screen.ActivateTextSearch(self)
end
end
function ZO_GuildBank_Gamepad:OnSceneShowing()
ZO_SharedInventory_SelectAccessibleGuildBank(ZO_GUILD_SELECTOR_MANAGER:GetSelectedGuildBankId())
self:RefreshGuildBank()
TriggerTutorial(TUTORIAL_TRIGGER_GUILD_BANK_OPENED)
end
function ZO_GuildBank_Gamepad:SetCurrentKeybindDescriptor(descriptor)
self:RemoveKeybinds()
ZO_BankingCommon_Gamepad.SetCurrentKeybindDescriptor(self, descriptor)
self:RefreshKeybinds()
end
function ZO_GuildBank_Gamepad:AddKeybinds()
if self.currentKeybindStripDescriptor then
KEYBIND_STRIP:AddKeybindButtonGroup(self.currentKeybindStripDescriptor)
end
end
function ZO_GuildBank_Gamepad:RemoveKeybinds()
if self.currentKeybindStripDescriptor then
KEYBIND_STRIP:RemoveKeybindButtonGroup(self.currentKeybindStripDescriptor)
end
end
function ZO_GuildBank_Gamepad:UpdateKeybinds()
if self.currentKeybindStripDescriptor then
KEYBIND_STRIP:UpdateKeybindButtonGroup(self.currentKeybindStripDescriptor)
end
end
function ZO_GuildBank_Gamepad:RefreshKeybinds()
if self:GetCurrentList() and self:GetCurrentList():IsActive() and not self:IsHeaderActive() then
if not KEYBIND_STRIP:HasKeybindButtonGroup(self.currentKeybindStripDescriptor) then
self:AddKeybinds()
else
self:UpdateKeybinds()
end
else
self:RemoveKeybinds()
end
end
function ZO_GuildBank_Gamepad:OnWithdrawDepositStateChanged(oldState, newState)
if newState == SCENE_SHOWING then
local TRIGGER_CALLBACK = true
self:UpdateGuildBankList(TRIGGER_CALLBACK)
self.depositList:RefreshList(TRIGGER_CALLBACK)
elseif newState == SCENE_SHOWN then
GAMEPAD_TOOLTIPS:ClearTooltip(GAMEPAD_LEFT_TOOLTIP)
end
end
function ZO_GuildBank_Gamepad:SetWithdrawLoadingControlShown(shouldShowLoading)
if self.withdrawLoadingControlShown ~= shouldShowLoading then
self.withdrawLoadingControlShown = shouldShowLoading
self.withdrawLoadingControl:SetHidden(not shouldShowLoading)
local shouldShowWithdrawList = not shouldShowLoading
if not (self:GetListFragment("withdraw"):GetState() == SCENE_FRAGMENT_HIDING and shouldShowWithdrawList) then
--Because we change the active lists by adding and removing fragments, everytime we change tabs we are in a state where two list fragments are showing at the same. This causes problems
--when the bank info becomes avaiable as the withdraw fragment is hiding because it will try to activate and adds its list bindings when the deposit list is also active and has added its
--binds. The best way to fix this is to have these lists be scenes on a sub-scene manager so they don't overlap times when they are active. However, that means significant changes to the
--parametric list screen. So we handle the problem by not showing the withdraw list if the fragment is hiding. We wait until it is hidden to do that in the fragment's state change callback.
self.withdrawList:GetControl():SetHidden(not shouldShowWithdrawList)
end
if shouldShowWithdrawList and self:CanLeaveHeader() then
self:RequestLeaveHeader()
end
end
end
function ZO_GuildBank_Gamepad:CreateEventTable()
local function OnGuildBankOpenError()
if self.loadingGuildBank then
self.loadingGuildBank = false
self:SetWithdrawLoadingControlShown(false)
self:ClearAllGuildBankItems()
end
end
local function OnGuildBankUpdated()
self:UpdateGuildBankList()
self:RefreshHeaderData()
end
local function OnInventoryUpdated(eventId, bagId, slotIndex, _, itemSoundCategory)
if self.scene:IsShowing() then
self:MarkDirtyByBagId(bagId)
self:RefreshHeaderData()
KEYBIND_STRIP:UpdateKeybindButtonGroup(self.currentKeybindStripDescriptor)
self:LayoutBankingEntryTooltip(self:GetTargetData())
end
end
local function OnGuildBankSelected()
self.loadingGuildBank = true
GAMEPAD_TOOLTIPS:ClearTooltip(GAMEPAD_LEFT_TOOLTIP)
self:SetWithdrawLoadingControlShown(true)
self:ClearAllGuildBankItems()
end
local function OnGuildBankDeselected()
self:ClearAllGuildBankItems()
end
local function OnGuildBankReady()
self.loadingGuildBank = false
self:SetWithdrawLoadingControlShown(false)
local UPDATE_SELECTION = true
self.depositList:RefreshList(UPDATE_SELECTION)
if GAMEPAD_GUILD_BANK_SCENE:IsShowing() then
KEYBIND_STRIP:UpdateKeybindButtonGroup(self.currentKeybindStripDescriptor)
end
OnGuildBankUpdated()
end
local function RefreshHeaderData()
self:RefreshHeaderData()
end
local function RefreshLists()
local TRIGGER_CALLBACK = true
self.depositList:RefreshList(TRIGGER_CALLBACK)
self.withdrawList:RefreshList(TRIGGER_CALLBACK)
end
local function AlertAndRefreshHeader(currencyType, currentCurrency, oldCurrency, reason)
local alertString
local amount
local IS_GAMEPAD = true
local DONT_USE_SHORT_FORMAT = nil
if reason == CURRENCY_CHANGE_REASON_GUILD_BANK_DEPOSIT then
amount = oldCurrency - currentCurrency
alertString = zo_strformat(SI_GAMEPAD_BANK_GOLD_AMOUNT_DEPOSITED, ZO_CurrencyControl_FormatCurrencyAndAppendIcon(amount, DONT_USE_SHORT_FORMAT, currencyType, IS_GAMEPAD))
elseif CURRENCY_CHANGE_REASON_GUILD_BANK_WITHDRAWAL then
amount = currentCurrency - oldCurrency
alertString = zo_strformat(SI_GAMEPAD_BANK_GOLD_AMOUNT_WITHDRAWN, ZO_CurrencyControl_FormatCurrencyAndAppendIcon(amount, DONT_USE_SHORT_FORMAT, currencyType, IS_GAMEPAD))
end
if alertString then
ZO_AlertNoSuppression(UI_ALERT_CATEGORY_ALERT, nil, alertString)
end
RefreshHeaderData()
end
local function UpdateMoney(event, currentMoney, oldMoney, reason)
RefreshLists()
AlertAndRefreshHeader(CURT_MONEY, currentMoney, oldMoney, reason)
end
local function UpdateGuildBankedCurrency()
RefreshLists()
RefreshHeaderData()
end
local function OnGuildRanksChanged(_, guildId)
if guildId == GetSelectedGuildBankId() then
KEYBIND_STRIP:UpdateKeybindButtonGroup(self.currentKeybindStripDescriptor)
RefreshLists()
end
end
local function OnGuildMemberRankChanged(_, guildId, displayName)
if guildId == GetSelectedGuildBankId() and displayName == GetDisplayName() then
KEYBIND_STRIP:UpdateKeybindButtonGroup(self.currentKeybindStripDescriptor)
RefreshLists()
end
end
local function OnGuildSizeChanged()
KEYBIND_STRIP:UpdateKeybindButtonGroup(self.currentKeybindStripDescriptor)
end
local function OnGuildLeft(event, guildId, guildName)
ZO_Dialogs_ReleaseAllDialogsOfName("GUILD_BANK_GAMEPAD_CHANGE_ACTIVE_GUILD")
end
self.eventTable =
{
[EVENT_GUILD_BANK_OPEN_ERROR] = OnGuildBankOpenError,
[EVENT_GUILD_BANK_SELECTED] = OnGuildBankSelected,
[EVENT_GUILD_BANK_DESELECTED] = OnGuildBankDeselected,
[EVENT_GUILD_BANK_ITEMS_READY] = OnGuildBankReady,
[EVENT_GUILD_BANK_ITEM_ADDED] = OnGuildBankUpdated,
[EVENT_GUILD_BANK_ITEM_REMOVED] = OnGuildBankUpdated,
[EVENT_GUILD_BANK_UPDATED_QUANTITY] = OnGuildBankUpdated,
[EVENT_MONEY_UPDATE] = UpdateMoney,
[EVENT_GUILD_BANKED_MONEY_UPDATE] = UpdateGuildBankedCurrency,
[EVENT_GUILD_RANKS_CHANGED] = OnGuildRanksChanged,
[EVENT_GUILD_RANK_CHANGED] = OnGuildRanksChanged,
[EVENT_GUILD_MEMBER_RANK_CHANGED] = OnGuildMemberRankChanged,
[EVENT_GUILD_MEMBER_ADDED] = OnGuildSizeChanged,
[EVENT_GUILD_MEMBER_REMOVED] = OnGuildSizeChanged,
[EVENT_GUILD_SELF_LEFT_GUILD] = OnGuildLeft,
[EVENT_INVENTORY_FULL_UPDATE] = OnInventoryUpdated,
[EVENT_INVENTORY_SINGLE_SLOT_UPDATE] = OnInventoryUpdated,
}
end
function ZO_GuildBank_Gamepad:RegisterForEvents()
ZO_BankingCommon_Gamepad.RegisterForEvents(self)
self:GetListFragment(self.withdrawList):RegisterCallback("StateChange", self.OnWithdrawDepositStateChanged)
self:GetListFragment(self.depositList):RegisterCallback("StateChange", self.OnWithdrawDepositStateChanged)
end
function ZO_GuildBank_Gamepad:UnregisterForEvents()
ZO_BankingCommon_Gamepad.UnregisterForEvents(self)
self:GetListFragment(self.withdrawList):UnregisterCallback("StateChange", self.OnWithdrawDepositStateChanged)
self:GetListFragment(self.depositList):UnregisterCallback("StateChange", self.OnWithdrawDepositStateChanged)
end
function ZO_GuildBank_Gamepad:OnDeferredInitialization()
ZO_SharedInventory_SelectAccessibleGuildBank()
SHARED_INVENTORY:RegisterCallback("FullInventoryUpdate", function()
if self.scene:IsShowing() then
self:MarkDirtyByBagId(BAG_BACKPACK)
self:MarkDirtyByBagId(BAG_GUILDBANK)
self:RefreshGuildBank()
end
end)
if self.loadingGuildBank then
GAMEPAD_TOOLTIPS:ClearTooltip(GAMEPAD_LEFT_TOOLTIP)
self:SetWithdrawLoadingControlShown(true)
end
end
do
local function DepositItemFilter(itemData)
return not itemData.stolen and
not IsItemBound(itemData.bagId, itemData.slotIndex) and
not IsItemBoPAndTradeable(itemData.bagId, itemData.slotIndex) and
not itemData.isPlayerLocked
end
function ZO_GuildBank_Gamepad:InitializeLists()
local function OnTargetDataChangedCallback(...)
self:OnTargetChanged(...)
end
local function OnRefreshList(list)
if list:GetNumItems() == 0 then
self:RequestEnterHeader()
else
self:RequestLeaveHeader()
if not list:IsActive() then
list:Activate()
end
end
end
local SETUP_LIST_LOCALLY = true
local NO_ON_SELECTED_DATA_CHANGED_CALLBACK = nil
local withdrawList = self:AddList("withdraw", SETUP_LIST_LOCALLY, ZO_GamepadGuildBankInventoryList, BANKING_GAMEPAD_MODE_WITHDRAW, self.bankedBags, SLOT_TYPE_GUILD_BANK_ITEM, NO_ON_SELECTED_DATA_CHANGED_CALLBACK, nil, nil, nil, nil, nil, ZO_SharedGamepadEntry_OnSetup)
withdrawList:SetOnRefreshListCallback(OnRefreshList)
withdrawList:SetSearchContext(self.searchContext)
withdrawList:SetOnTargetDataChangedCallback(OnTargetDataChangedCallback)
self:SetWithdrawList(withdrawList)
local withdrawListFragment = self:GetListFragment("withdraw")
withdrawListFragment:RegisterCallback("StateChange", function(oldState, newState)
if newState == SCENE_FRAGMENT_SHOWING then
--The parametric list screen does not call OnTargetChanged when changing the current list which means anything that updates off of the current
--selection is out of date. So we run OnTargetChanged when a list shows to remedy this.
self:OnTargetChanged(self:GetCurrentList(), self:GetTargetData())
end
--See SetWithdrawLoadingControlShown for more info
if newState ~= SCENE_FRAGMENT_HIDING then
self.withdrawList:GetControl():SetHidden(self.withdrawLoadingControlShown)
end
end)
local withdrawListControl = withdrawList:GetControl()
local withdrawContainerControl = withdrawListControl:GetParent()
self.withdrawLoadingControl = CreateControlFromVirtual("$(parent)Loading", withdrawContainerControl, "ZO_GamepadCenteredLoadingIconAndLabelTemplate")
self.withdrawLoadingControl:GetNamedChild("ContainerText"):SetText(GetString(SI_INVENTORY_RETRIEVING_ITEMS))
local depositList = self:AddList("deposit", SETUP_LIST_LOCALLY, ZO_GamepadGuildBankInventoryList, BANKING_GAMEPAD_MODE_DEPOSIT, self.carriedBag, SLOT_TYPE_ITEM, NO_ON_SELECTED_DATA_CHANGED_CALLBACK, nil, nil, nil, nil, nil, ZO_SharedGamepadEntry_OnSetup)
depositList:SetOnRefreshListCallback(OnRefreshList)
depositList:SetSearchContext(self.searchContext)
depositList:SetOnTargetDataChangedCallback(OnTargetDataChangedCallback)
depositList:SetItemFilterFunction(DepositItemFilter)
self:SetDepositList(depositList)
local depositListFragment = self:GetListFragment("deposit")
depositListFragment:RegisterCallback("StateChange", function(oldState, newState)
if newState == SCENE_FRAGMENT_SHOWING then
--The parametric list screen does not call OnTargetChanged when changing the current list which means anything that updates off of the current
--selection is out of date. So we run OnTargetChanged when a list shows to remedy this.
self:OnTargetChanged(self:GetCurrentList(), self:GetTargetData())
end
end)
end
end
local function CanUseBank(requestPermission)
local guildId = GetSelectedGuildBankId()
if guildId then
return DoesPlayerHaveGuildPermission(guildId, requestPermission)
else
return false
end
end
local function NotEnoughSpace(reason)
local message = zo_strformat(reason)
ZO_AlertNoSuppression(UI_ALERT_CATEGORY_ALERT, nil, message)
PlaySound(SOUNDS.GENERAL_ALERT_ERROR)
end
local function DepositItem(list)
local targetData = list:GetTargetData()
if targetData then
if GetNumBagUsedSlots(BAG_GUILDBANK) < GetBagSize(BAG_GUILDBANK) then
local soundCategory = GetItemSoundCategory(targetData.itemData.bagId, targetData.itemData.slotIndex)
PlayItemSound(soundCategory, ITEM_SOUND_ACTION_PICKUP)
TransferToGuildBank(targetData.itemData.bagId, targetData.itemData.slotIndex)
else
NotEnoughSpace(SI_GUILDBANKRESULT5)
end
end
end
local function WithdrawItem(list)
local targetData = list:GetTargetData()
if targetData then
if GetNumBagFreeSlots(BAG_BACKPACK) > 0 then
local soundCategory = GetItemSoundCategory(targetData.itemData.bagId, targetData.itemData.slotIndex)
PlayItemSound(soundCategory, ITEM_SOUND_ACTION_PICKUP)
TransferFromGuildBank(targetData.itemData.slotIndex)
else
NotEnoughSpace(SI_INVENTORY_ERROR_INVENTORY_FULL)
end
end
end
local CURRENT_DATA_TYPE_NONE = 0
local CURRENT_DATA_TYPE_GOLD_SELECTOR = 1
local CURRENT_DATA_TYPE_ITEM_DATA = 2
local function GetCurrentDataType(list)
local targetData = list:GetTargetData()
if targetData then
if targetData.currencyType == CURT_MONEY then
return CURRENT_DATA_TYPE_GOLD_SELECTOR
else
return CURRENT_DATA_TYPE_ITEM_DATA
end
end
return CURRENT_DATA_TYPE_NONE
end
function ZO_GuildBank_Gamepad:InitializeKeybindStripDescriptors()
ZO_BankingCommon_Gamepad.InitializeKeybindStripDescriptors(self)
self.switchActiveGuildKeybind =
{
alignment = KEYBIND_STRIP_ALIGN_LEFT,
keybind = "UI_SHORTCUT_TERTIARY",
name = GetString(SI_TRADING_HOUSE_GUILD_LABEL),
callback = function()
ZO_Dialogs_ShowGamepadDialog("GUILD_BANK_GAMEPAD_CHANGE_ACTIVE_GUILD")
end,
visible = function()
return GetNumGuilds() > 1
end,
}
self:SetWithdrawKeybindDescriptor(
{
alignment = KEYBIND_STRIP_ALIGN_LEFT,
{
keybind = "UI_SHORTCUT_PRIMARY",
name = function()
return GetString(SI_BANK_WITHDRAW_BIND)
end,
enabled = function()
return self:CanWithdraw()
end,
visible = function()
local currentDataType = GetCurrentDataType(self.withdrawList)
if currentDataType == CURRENT_DATA_TYPE_GOLD_SELECTOR then
return CanUseBank(GUILD_PERMISSION_BANK_WITHDRAW_GOLD)
elseif currentDataType == CURRENT_DATA_TYPE_ITEM_DATA then
return CanUseBank(GUILD_PERMISSION_BANK_WITHDRAW) and GetNumBagUsedSlots(BAG_GUILDBANK) > 0
end
end,
callback = function()
self:ConfirmWithdrawal()
end,
},
{
keybind = "UI_SHORTCUT_LEFT_STICK",
name = function()
local sortIconPath = self.withdrawList.currentSortOrder == ZO_ICON_SORT_ARROW_UP and SORT_ARROW_UP or ZO_ICON_SORT_ARROW_DOWN
local sortIconText = zo_iconFormat(sortIconPath, 16, 16)
if ZO_IsTableEmpty(self.withdrawList.filterCategories) then
return zo_strformat(GetString(SI_GAMEPAD_BANK_FILTER_KEYBIND), GetString("SI_ITEMLISTSORTTYPE", self.withdrawList.currentSortType), sortIconText)
else
return zo_strformat(GetString(SI_GAMEPAD_BANK_FILTER_SORT_DROPDOWN_TEXT), NonContiguousCount(self.withdrawList.filterCategories), GetString("SI_ITEMLISTSORTTYPE", self.withdrawList.currentSortType), sortIconText)
end
end,
callback = function()
ZO_Dialogs_ShowGamepadDialog("GAMEPAD_BANK_SEARCH_FILTERS", { bankObject = self })
end
},
self.switchActiveGuildKeybind,
})
ZO_Gamepad_AddBackNavigationKeybindDescriptors(self.withdrawKeybindStripDescriptor, GAME_NAVIGATION_TYPE_BUTTON, function()
SCENE_MANAGER:HideCurrentScene()
end)
self:SetDepositKeybindDescriptor(
{
alignment = KEYBIND_STRIP_ALIGN_LEFT,
{
keybind = "UI_SHORTCUT_PRIMARY",
name = function()
return GetString(SI_BANK_DEPOSIT_BIND)
end,
enabled = function()
return self:CanDeposit()
end,
visible = function()
local currentDataType = GetCurrentDataType(self.depositList)
if currentDataType == CURRENT_DATA_TYPE_GOLD_SELECTOR then
return DoesGuildHavePrivilege(GetSelectedGuildBankId(), GUILD_PRIVILEGE_BANK_DEPOSIT)
elseif currentDataType == CURRENT_DATA_TYPE_ITEM_DATA then
return not self.loadingGuildBank and CanUseBank(GUILD_PERMISSION_BANK_DEPOSIT) and GetNumBagUsedSlots(BAG_BACKPACK) > 0 and DoesGuildHavePrivilege(GetSelectedGuildBankId(), GUILD_PRIVILEGE_BANK_DEPOSIT)
end
end,
callback = function()
self:ConfirmDeposit()
end
},
self.switchActiveGuildKeybind,
})
ZO_Gamepad_AddBackNavigationKeybindDescriptors(self.depositKeybindStripDescriptor, GAME_NAVIGATION_TYPE_BUTTON)
end
function ZO_GuildBank_Gamepad:CanDeposit()
local inventoryData = self:GetTargetData()
if not inventoryData then
return false
end
local currencyType = inventoryData.currencyType
if currencyType then
if self:GetMaxBankedFunds(currencyType) ~= GetCurrencyAmount(currencyType, CURRENCY_LOCATION_GUILD_BANK) and GetCurrencyAmount(currencyType, CURRENCY_LOCATION_CHARACTER) ~= 0 then
return true
else
if self:GetMaxBankedFunds(currencyType) == GetCurrencyAmount(currencyType, CURRENCY_LOCATION_GUILD_BANK) then
return false, GetString("SI_GUILDBANKRESULT", GUILD_BANK_NO_SPACE_LEFT) -- "Your guild bank is full"
elseif GetCurrencyAmount(currencyType, CURRENCY_LOCATION_CHARACTER) == 0 then
return false, GetString(SI_GAMEPAD_INVENTORY_ERROR_NO_PLAYER_FUNDS) -- "No player funds"
end
end
elseif GetNumBagFreeSlots(BAG_GUILDBANK) > 0 then
return true
else
return false, GetString(SI_INVENTORY_ERROR_BANK_FULL) -- "Your guild bank is full"
end
end
function ZO_GuildBank_Gamepad:CanWithdraw()
local inventoryData = self:GetTargetData()
if not inventoryData then
return false
end
local currencyType = inventoryData.currencyType
if currencyType then
if not DoesPlayerHaveGuildPermission(GetSelectedGuildBankId(), GUILD_PERMISSION_BANK_VIEW_GOLD) then
return false
elseif GetCurrencyAmount(currencyType, CURRENCY_LOCATION_GUILD_BANK) ~= 0 and GetCurrencyAmount(currencyType, CURRENCY_LOCATION_CHARACTER) ~= GetMaxPossibleCurrency(currencyType, CURRENCY_LOCATION_CHARACTER) then
return true
else
if GetCurrencyAmount(currencyType, CURRENCY_LOCATION_CHARACTER) == GetMaxPossibleCurrency(currencyType, CURRENCY_LOCATION_CHARACTER) then
return false, GetString(SI_INVENTORY_ERROR_INVENTORY_FULL) -- "Your inventory is full"
elseif GetCurrencyAmount(currencyType, CURRENCY_LOCATION_GUILD_BANK) == 0 then
return false, GetString(SI_GAMEPAD_INVENTORY_ERROR_NO_BANK_FUNDS) -- "No bank funds"
end
end
elseif GetNumBagFreeSlots(BAG_BACKPACK) > 0 then
return true
else
return false, GetString(SI_INVENTORY_ERROR_INVENTORY_FULL) -- "Your inventory is full"
end
end
function ZO_GuildBank_Gamepad:ConfirmDeposit()
local inventoryData = self:GetTargetData()
if inventoryData.currencyType then
self:SetMaxAndShowSelector(function(currencyType) return GetMaxCurrencyTransfer(currencyType, CURRENCY_LOCATION_CHARACTER, CURRENCY_LOCATION_GUILD_BANK) end)
else
DepositItem(self.depositList)
end
end
function ZO_GuildBank_Gamepad:ConfirmWithdrawal()
local inventoryData = self:GetTargetData()
if inventoryData.currencyType then
self:SetMaxAndShowSelector(function(currencyType) return GetMaxCurrencyTransfer(currencyType, CURRENCY_LOCATION_GUILD_BANK, CURRENCY_LOCATION_CHARACTER) end)
else
WithdrawItem(self.withdrawList)
end
end
function ZO_GuildBank_Gamepad:SetMaxAndShowSelector(maxInputFunction)
self:SetMaxInputFunction(maxInputFunction)
self:ShowSelector()
end
function ZO_GuildBank_Gamepad:GetWithdrawMoneyAmount()
return GetCurrencyAmount(CURT_MONEY, CURRENCY_LOCATION_GUILD_BANK)
end
function ZO_GuildBank_Gamepad:GetWithdrawMoneyOptions()
return ZO_BANKING_CURRENCY_LABEL_OPTIONS
end
function ZO_GuildBank_Gamepad:DoesObfuscateWithdrawAmount()
return not DoesPlayerHaveGuildPermission(GetSelectedGuildBankId(), GUILD_PERMISSION_BANK_VIEW_GOLD)
end
function ZO_GuildBank_Gamepad:GetMaxBankedFunds(currencyType)
return GetMaxPossibleCurrency(currencyType, CURRENCY_LOCATION_GUILD_BANK)
end
function ZO_GuildBank_Gamepad:GetDepositMoneyAmount()
return GetCurrencyAmount(CURT_MONEY, CURRENCY_LOCATION_CHARACTER)
end
function ZO_GuildBank_Gamepad:DepositFunds(currencyType, amount)
TransferCurrency(currencyType, amount, CURRENCY_LOCATION_CHARACTER, CURRENCY_LOCATION_GUILD_BANK)
end
function ZO_GuildBank_Gamepad:WithdrawFunds(currencyType, amount)
TransferCurrency(currencyType, amount, CURRENCY_LOCATION_GUILD_BANK, CURRENCY_LOCATION_CHARACTER)
end
function ZO_GuildBank_Gamepad:OnCategoryChangedCallback(selectedData)
ZO_BankingCommon_Gamepad.OnCategoryChangedCallback(self, selectedData)
if self.loadingGuildBank and selectedData.mode == BANKING_GAMEPAD_MODE_WITHDRAW then
self:SetSelectedInventoryData(nil)
end
end
function ZO_GuildBank_Gamepad:InitializeHeader()
ZO_BankingCommon_Gamepad.InitializeHeader(self)
ZO_GUILD_NAME_FOOTER_FRAGMENT:SetGuildName(GetGuildName(GetSelectedGuildBankId()))
end
function ZO_GuildBank_Gamepad:OnEnterHeader()
ZO_Gamepad_ParametricList_Screen.OnEnterHeader(self)
if self.textSearchHeaderFocus then
KEYBIND_STRIP:AddKeybindButton(self.switchActiveGuildKeybind)
end
end
function ZO_GuildBank_Gamepad:OnLeaveHeader()
ZO_Gamepad_ParametricList_Screen.OnLeaveHeader(self)
if self.textSearchHeaderFocus then
KEYBIND_STRIP:RemoveKeybindButton(self.switchActiveGuildKeybind)
end
end
function ZO_GuildBank_Gamepad:ExitHeader()
ZO_Gamepad_ParametricList_Screen.ExitHeader(self)
if self.textSearchHeaderFocus then
KEYBIND_STRIP:RemoveKeybindButton(self.switchActiveGuildKeybind)
end
end
function ZO_GuildBank_Gamepad:RefreshGuildBank()
self.depositList:RefreshList()
self:UpdateGuildBankList()
self:RefreshHeaderData()
end
function ZO_GuildBank_Gamepad:ChangeGuildBank(guildBankId)
if guildBankId ~= GetSelectedGuildBankId() then
self.loadingGuildBank = true
ZO_GUILD_SELECTOR_MANAGER:SetSelectedGuildBankId(guildBankId)
end
end
function ZO_GuildBank_Gamepad:IsLoadingGuildBank()
return self.loadingGuildBank
end
function ZO_GuildBank_Gamepad:OnRefreshHeaderData()
ZO_GUILD_NAME_FOOTER_FRAGMENT:SetGuildName(GetGuildName(GetSelectedGuildBankId()))
end
function ZO_GuildBank_Gamepad:UpdateGuildBankList(shouldTriggerRefreshCallback)
self.withdrawList:RefreshList(shouldTriggerRefreshCallback)
end
function ZO_GuildBank_Gamepad:SetSelectedInventoryData(_, inventoryData)
self:LayoutBankingEntryTooltip(inventoryData)
end
function ZO_GuildBank_Gamepad:ClearAllGuildBankItems()
self.withdrawList:ClearList()
end
function ZO_GuildBank_Gamepad_Initialize(control)
GAMEPAD_GUILD_BANK = ZO_GuildBank_Gamepad:New(control)
end | 1 | 0.943595 | 1 | 0.943595 | game-dev | MEDIA | 0.69344 | game-dev | 0.913014 | 1 | 0.913014 |
Ayfri/Kore | 1,643 | kore/src/main/kotlin/io/github/ayfri/kore/arguments/components/item/ContainerComponent.kt | package io.github.ayfri.kore.arguments.components.item
import io.github.ayfri.kore.arguments.ItemSlotType
import io.github.ayfri.kore.arguments.components.Component
import io.github.ayfri.kore.arguments.components.ComponentsScope
import io.github.ayfri.kore.data.item.ItemStack
import io.github.ayfri.kore.generated.ItemComponentTypes
import io.github.ayfri.kore.serializers.InlineAutoSerializer
import kotlinx.serialization.Serializable
@Serializable
data class ContainerSlot(var slot: Int, var item: ItemStack)
@Serializable(with = ContainerComponent.Companion.ContainerComponentSerializer::class)
data class ContainerComponent(var slots: List<ContainerSlot>) : Component() {
companion object {
data object ContainerComponentSerializer : InlineAutoSerializer<ContainerComponent>(ContainerComponent::class)
}
}
fun ComponentsScope.container(slots: List<ContainerSlot>) = apply {
this[ItemComponentTypes.CONTAINER] = ContainerComponent(slots)
}
fun ComponentsScope.container(vararg slots: ContainerSlot) = apply {
this[ItemComponentTypes.CONTAINER] = ContainerComponent(slots.toList())
}
fun ComponentsScope.container(block: ContainerComponent.() -> Unit) = apply {
this[ItemComponentTypes.CONTAINER] = ContainerComponent(mutableListOf()).apply(block)
}
fun ContainerComponent.slot(slot: Int, item: ItemStack) = apply {
slots += ContainerSlot(slot, item)
}
operator fun ContainerComponent.set(slot: Int, item: ItemStack) = slot(slot, item)
fun ContainerComponent.slot(slot: ItemSlotType, item: ItemStack) = slot(slot.asIndex(), item)
operator fun ContainerComponent.set(slot: ItemSlotType, item: ItemStack) = slot(slot, item)
| 1 | 0.678191 | 1 | 0.678191 | game-dev | MEDIA | 0.876626 | game-dev | 0.551149 | 1 | 0.551149 |
TrashboxBobylev/Summoning-Pixel-Dungeon | 3,473 | core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/actors/blobs/Fire.java | /*
* Pixel Dungeon
* Copyright (C) 2012-2015 Oleg Dolya
*
* Shattered Pixel Dungeon
* Copyright (C) 2014-2022 Evan Debenham
*
* Summoning Pixel Dungeon
* Copyright (C) 2019-2022 TrashboxBobylev
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.shatteredpixel.shatteredpixeldungeon.actors.blobs;
import com.shatteredpixel.shatteredpixeldungeon.Dungeon;
import com.shatteredpixel.shatteredpixeldungeon.actors.Actor;
import com.shatteredpixel.shatteredpixeldungeon.actors.Char;
import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Buff;
import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Burning;
import com.shatteredpixel.shatteredpixeldungeon.effects.BlobEmitter;
import com.shatteredpixel.shatteredpixeldungeon.effects.particles.FlameParticle;
import com.shatteredpixel.shatteredpixeldungeon.items.Heap;
import com.shatteredpixel.shatteredpixeldungeon.messages.Messages;
import com.shatteredpixel.shatteredpixeldungeon.plants.Plant;
import com.shatteredpixel.shatteredpixeldungeon.scenes.GameScene;
public class Fire extends Blob {
@Override
protected void evolve() {
boolean[] flamable = Dungeon.level.flamable;
int cell;
int fire;
Freezing freeze = (Freezing)Dungeon.level.blobs.get( Freezing.class );
boolean observe = false;
for (int i = area.left-1; i <= area.right; i++) {
for (int j = area.top-1; j <= area.bottom; j++) {
cell = i + j*Dungeon.level.width();
if (cur[cell] > 0) {
if (freeze != null && freeze.volume > 0 && freeze.cur[cell] > 0){
freeze.clear(cell);
off[cell] = cur[cell] = 0;
continue;
}
burn( cell );
fire = cur[cell] - 1;
if (fire <= 0 && flamable[cell]) {
Dungeon.level.destroy( cell );
observe = true;
GameScene.updateMap( cell );
}
} else if (freeze == null || freeze.volume <= 0 || freeze.cur[cell] <= 0) {
if (flamable[cell]
&& (cur[cell-1] > 0
|| cur[cell+1] > 0
|| cur[cell-Dungeon.level.width()] > 0
|| cur[cell+Dungeon.level.width()] > 0)) {
fire = 4;
burn( cell );
area.union(i, j);
} else {
fire = 0;
}
} else {
fire = 0;
}
volume += (off[cell] = fire);
}
}
if (observe) {
Dungeon.observe();
}
}
public static void burn( int pos ) {
Char ch = Actor.findChar( pos );
if (ch != null && !ch.isImmune(Fire.class)) {
Buff.affect( ch, Burning.class ).reignite( ch );
}
Heap heap = Dungeon.level.heaps.get( pos );
if (heap != null) {
heap.burn();
}
Plant plant = Dungeon.level.plants.get( pos );
if (plant != null){
plant.wither();
}
}
@Override
public void use( BlobEmitter emitter ) {
super.use( emitter );
emitter.pour( FlameParticle.FACTORY, 0.03f );
}
@Override
public String tileDesc() {
return Messages.get(this, "desc");
}
}
| 1 | 0.831192 | 1 | 0.831192 | game-dev | MEDIA | 0.983885 | game-dev | 0.880941 | 1 | 0.880941 |
morkt/GARbro | 6,226 | Experimental/RPGMaker/ArcRGSS.cs | //! \file ArcRGSS3.cs
//! \date 2017 Nov 18
//! \brief RPG Maker resource archive implementation.
//
// Copyright (C) 2017 by morkt
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
using System.Text;
namespace GameRes.Formats.RPGMaker
{
[Export(typeof(ArchiveFormat))]
public class RgssOpener : ArchiveFormat
{
public override string Tag { get { return "RGSSAD"; } }
public override string Description { get { return "RPG Maker engine resource archive"; } }
public override uint Signature { get { return 0x53534752; } } // 'RGSS'
public override bool IsHierarchic { get { return true; } }
public override bool CanWrite { get { return false; } }
public RgssOpener ()
{
Extensions = new string[] { "rgss3a", "rgss2a", "rgssad" };
}
public override ArcFile TryOpen (ArcView file)
{
if (!file.View.AsciiEqual (4, "AD\0"))
return null;
int version = file.View.ReadByte (7);
using (var index = file.CreateStream())
{
List<Entry> dir = null;
if (3 == version)
dir = ReadIndexV3 (index);
else if (1 == version)
dir = ReadIndexV1 (index);
if (null == dir || 0 == dir.Count)
return null;
return new ArcFile (file, this, dir);
}
}
List<Entry> ReadIndexV1 (IBinaryStream file)
{
var max_offset = file.Length;
file.Position = 8;
var key_gen = new KeyGenerator (0xDEADCAFE);
var dir = new List<Entry>();
while (file.PeekByte() != -1)
{
uint name_length = file.ReadUInt32() ^ key_gen.GetNext();
var name_bytes = file.ReadBytes ((int)name_length);
var name = DecryptName (name_bytes, key_gen);
var entry = FormatCatalog.Instance.Create<RgssEntry> (name);
entry.Size = file.ReadUInt32() ^ key_gen.GetNext();
entry.Offset = file.Position;
entry.Key = key_gen.Current;
if (!entry.CheckPlacement (max_offset))
return null;
dir.Add (entry);
file.Seek (entry.Size, SeekOrigin.Current);
}
return dir;
}
List<Entry> ReadIndexV3 (IBinaryStream file)
{
var max_offset = file.Length;
file.Position = 8;
uint key = file.ReadUInt32() * 9 + 3;
var dir = new List<Entry>();
while (file.PeekByte() != -1)
{
uint offset = file.ReadUInt32() ^ key;
if (0 == offset)
break;
uint size = file.ReadUInt32() ^ key;
uint entry_key = file.ReadUInt32() ^ key;
uint name_length = file.ReadUInt32() ^ key;
var name_bytes = file.ReadBytes ((int)name_length);
var name = DecryptName (name_bytes, key);
var entry = FormatCatalog.Instance.Create<RgssEntry> (name);
entry.Offset = offset;
entry.Size = size;
entry.Key = entry_key;
if (!entry.CheckPlacement (max_offset))
return null;
dir.Add (entry);
}
return dir;
}
public override Stream OpenEntry (ArcFile arc, Entry entry)
{
var rent = (RgssEntry)entry;
var data = arc.File.View.ReadBytes (rent.Offset, rent.Size);
var key_gen = new KeyGenerator (rent.Key);
uint key = key_gen.GetNext();
for (int i = 0; i < data.Length; )
{
data[i] ^= (byte)(key >> (i << 3));
++i;
if (0 == (i & 3))
{
key = key_gen.GetNext();
}
}
return new BinMemoryStream (data);
}
string DecryptName (byte[] name, KeyGenerator key_gen)
{
for (int i = 0; i < name.Length; ++i)
{
name[i] ^= (byte)key_gen.GetNext();
}
return Encoding.UTF8.GetString (name);
}
string DecryptName (byte[] name, uint key)
{
for (int i = 0; i < name.Length; ++i)
{
name[i] ^= (byte)(key >> (i << 3));
}
return Encoding.UTF8.GetString (name);
}
}
internal class RgssEntry : Entry
{
public uint Key;
}
internal class KeyGenerator
{
uint m_seed;
public KeyGenerator (uint seed)
{
m_seed = seed;
}
public uint Current { get { return m_seed; } }
public uint GetNext ()
{
uint key = m_seed;
m_seed = m_seed * 7 + 3;
return key;
}
}
}
| 1 | 0.876432 | 1 | 0.876432 | game-dev | MEDIA | 0.522293 | game-dev | 0.950492 | 1 | 0.950492 |
kbengine/unity3d_nav_critterai | 4,385 | sources/src/main/Assets/CAI/nmbuild-u3d/Editor/input/TagSceneQuery.cs | /*
* Copyright (c) 2012 Stephen A. Pratt
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using UnityEngine;
using System.Collections.Generic;
using org.critterai.nmbuild.u3d.editor;
/// <summary>
/// Queries the scene for components based on game object tag. (Editor Only)
/// </summary>
/// <remarks>
/// <para>
/// Components are returned based the tags assigned to game objects. The query can be local
/// to the tagged objects, or can include children.
/// </para>
/// </remarks>
[System.Serializable]
public sealed class TagSceneQuery
: ScriptableObject, ISceneQuery
{
/// <summary>
/// One or more tags to base the query on.
/// </summary>
public List<string> tags = new List<string>();
[SerializeField]
private bool mIncludeChildren = true;
private GameObject[] mObjects;
/// <summary>
/// True if components whose parents have one of the tags should be included in the results.
/// </summary>
/// <remarks>
/// <para>
/// If true, the query behavior will be the same as calling GetComponentsInChildren() on the
/// tagged game object. If false, the query behavior will be the same as GetComponent().
/// </para>
/// </remarks>
public bool IncludeChildren
{
get { return mIncludeChildren; }
set { mIncludeChildren = value; }
}
/// <summary>
/// Initializes the object before each use.
/// </summary>
/// <remarks>
/// <para>
/// This method is called by the manager of the object before each use. It allows the
/// object to refresh its internal state.
/// </para>
/// </remarks>
public void Initialize()
{
if (tags == null || tags.Count == 0)
{
mObjects = new GameObject[0];
return;
}
if (tags.Count == 1)
// Shortcut.
mObjects = GameObject.FindGameObjectsWithTag(tags[0]);
else
{
// Need to aggregate.
List<GameObject> list = new List<GameObject>();
foreach (string tag in tags)
{
if (tag != null && tag.Length > 0)
{
GameObject[] g = GameObject.FindGameObjectsWithTag(tag);
list.AddRange(g);
}
}
mObjects = list.ToArray();
}
}
/// <summary>
/// Gets all scene components of the specified type, based the component or parent tags.
/// </summary>
/// <remarks>
/// <para>
/// All queries are against the currently open scene.
/// </para>
/// </remarks>
/// <typeparam name="T">The type of component to retrieve.</typeparam>
/// <returns>All components of the specified type.</returns>
public T[] GetComponents<T>() where T : Component
{
List<T> result = new List<T>();
foreach (GameObject go in mObjects)
{
if (go == null || !go.active)
continue;
if (mIncludeChildren)
{
T[] cs = go.GetComponentsInChildren<T>(false);
result.AddRange(cs);
}
else
{
T cs = go.GetComponent<T>();
if (cs != null)
result.Add(cs);
}
}
return result.ToArray();
}
}
| 1 | 0.754575 | 1 | 0.754575 | game-dev | MEDIA | 0.847803 | game-dev | 0.765377 | 1 | 0.765377 |
CardboardPowered/cardboard | 1,340 | src/main/java/org/cardboardpowered/impl/entity/CardboardEvoker.java | package org.cardboardpowered.impl.entity;
import net.minecraft.entity.mob.EvokerEntity;
import net.minecraft.entity.mob.SpellcastingIllagerEntity;
import org.bukkit.craftbukkit.CraftServer;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Evoker;
import org.bukkit.entity.Sheep;
public class CardboardEvoker extends CardboardSpellcaster implements Evoker {
public CardboardEvoker(CraftServer server, EvokerEntity entity) {
super(server, entity);
}
@Override
public EvokerEntity getHandle() {
return (EvokerEntity) super.getHandle();
}
@Override
public String toString() {
return "Evoker";
}
@Override
public EntityType getType() {
return EntityType.EVOKER;
}
@Override
public Evoker.Spell getCurrentSpell() {
return Evoker.Spell.values()[getHandle().getSpell().ordinal()];
}
@Override
public void setCurrentSpell(Evoker.Spell spell) {
getHandle().setSpell(spell == null ? SpellcastingIllagerEntity.Spell.NONE : SpellcastingIllagerEntity.Spell.byId(spell.ordinal()));
}
@Override
public Sheep getWololoTarget() {
// TODO Auto-generated method stub
return null;
}
@Override
public void setWololoTarget(Sheep arg0) {
// TODO Auto-generated method stub
}
} | 1 | 0.861517 | 1 | 0.861517 | game-dev | MEDIA | 0.940368 | game-dev | 0.839154 | 1 | 0.839154 |
plooshi/CelestiaGS | 34,611 | SDK/StatsListItemWIdget_parameters.hpp | #pragma once
/*
* SDK generated by Dumper-7
*
* https://github.com/Encryqed/Dumper-7
*/
// Package: StatsListItemWIdget
#include "Basic.hpp"
#include "CommonInput_structs.hpp"
#include "UMG_structs.hpp"
#include "FortniteUI_structs.hpp"
#include "CoreUObject_structs.hpp"
#include "SlateCore_structs.hpp"
namespace SDK::Params
{
// Function StatsListItemWIdget.StatsListItemWIdget_C.Initial Reset
// 0x0008 (0x0008 - 0x0000)
struct StatsListItemWIdget_C_Initial_Reset final
{
public:
class UUMGSequencePlayer* CallFunc_PlayAnimation_ReturnValue; // 0x0000(0x0008)(ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
};
static_assert(alignof(StatsListItemWIdget_C_Initial_Reset) == 0x000008, "Wrong alignment on StatsListItemWIdget_C_Initial_Reset");
static_assert(sizeof(StatsListItemWIdget_C_Initial_Reset) == 0x000008, "Wrong size on StatsListItemWIdget_C_Initial_Reset");
static_assert(offsetof(StatsListItemWIdget_C_Initial_Reset, CallFunc_PlayAnimation_ReturnValue) == 0x000000, "Member 'StatsListItemWIdget_C_Initial_Reset::CallFunc_PlayAnimation_ReturnValue' has a wrong offset!");
// Function StatsListItemWIdget.StatsListItemWIdget_C.Populate-Update
// 0x0008 (0x0008 - 0x0000)
struct StatsListItemWIdget_C_PopulateMinusUpdate final
{
public:
class UUMGSequencePlayer* CallFunc_PlayAnimation_ReturnValue; // 0x0000(0x0008)(ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
};
static_assert(alignof(StatsListItemWIdget_C_PopulateMinusUpdate) == 0x000008, "Wrong alignment on StatsListItemWIdget_C_PopulateMinusUpdate");
static_assert(sizeof(StatsListItemWIdget_C_PopulateMinusUpdate) == 0x000008, "Wrong size on StatsListItemWIdget_C_PopulateMinusUpdate");
static_assert(offsetof(StatsListItemWIdget_C_PopulateMinusUpdate, CallFunc_PlayAnimation_ReturnValue) == 0x000000, "Member 'StatsListItemWIdget_C_PopulateMinusUpdate::CallFunc_PlayAnimation_ReturnValue' has a wrong offset!");
// Function StatsListItemWIdget.StatsListItemWIdget_C.SetTextAndBorderHighlight
// 0x0018 (0x0018 - 0x0000)
struct StatsListItemWIdget_C_SetTextAndBorderHighlight final
{
public:
bool bHightlight; // 0x0000(0x0001)(BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
bool Temp_bool_Variable; // 0x0001(0x0001)(ZeroConstructor, IsPlainOldData, NoDestructor)
bool Temp_bool_Variable_1; // 0x0002(0x0001)(ZeroConstructor, IsPlainOldData, NoDestructor)
uint8 Pad_718A[0x5]; // 0x0003(0x0005)(Fixing Size After Last Property [ Dumper-7 ])
class UClass* K2Node_Select_Default; // 0x0008(0x0008)(ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
class UClass* K2Node_Select_Default_1; // 0x0010(0x0008)(ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
};
static_assert(alignof(StatsListItemWIdget_C_SetTextAndBorderHighlight) == 0x000008, "Wrong alignment on StatsListItemWIdget_C_SetTextAndBorderHighlight");
static_assert(sizeof(StatsListItemWIdget_C_SetTextAndBorderHighlight) == 0x000018, "Wrong size on StatsListItemWIdget_C_SetTextAndBorderHighlight");
static_assert(offsetof(StatsListItemWIdget_C_SetTextAndBorderHighlight, bHightlight) == 0x000000, "Member 'StatsListItemWIdget_C_SetTextAndBorderHighlight::bHightlight' has a wrong offset!");
static_assert(offsetof(StatsListItemWIdget_C_SetTextAndBorderHighlight, Temp_bool_Variable) == 0x000001, "Member 'StatsListItemWIdget_C_SetTextAndBorderHighlight::Temp_bool_Variable' has a wrong offset!");
static_assert(offsetof(StatsListItemWIdget_C_SetTextAndBorderHighlight, Temp_bool_Variable_1) == 0x000002, "Member 'StatsListItemWIdget_C_SetTextAndBorderHighlight::Temp_bool_Variable_1' has a wrong offset!");
static_assert(offsetof(StatsListItemWIdget_C_SetTextAndBorderHighlight, K2Node_Select_Default) == 0x000008, "Member 'StatsListItemWIdget_C_SetTextAndBorderHighlight::K2Node_Select_Default' has a wrong offset!");
static_assert(offsetof(StatsListItemWIdget_C_SetTextAndBorderHighlight, K2Node_Select_Default_1) == 0x000010, "Member 'StatsListItemWIdget_C_SetTextAndBorderHighlight::K2Node_Select_Default_1' has a wrong offset!");
// Function StatsListItemWIdget.StatsListItemWIdget_C.GetListItemTooltipWidget
// 0x00B8 (0x00B8 - 0x0000)
struct StatsListItemWIdget_C_GetListItemTooltipWidget final
{
public:
class UWidget* ReturnValue; // 0x0000(0x0008)(Parm, OutParm, ZeroConstructor, ReturnParm, InstancedReference, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
class UCommonInputSubsystem* CallFunc_GetContext_ReturnValue; // 0x0008(0x0008)(ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
class APlayerController* CallFunc_GetOwningPlayer_ReturnValue; // 0x0010(0x0008)(ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
ECommonInputType CallFunc_GetCurrentInputType_ReturnValue; // 0x0018(0x0001)(ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
uint8 Pad_718B[0x7]; // 0x0019(0x0007)(Fixing Size After Last Property [ Dumper-7 ])
struct FFortDisplayAttribute CallFunc_GetCurrentAttributeCopy_OutDisplayAttribute; // 0x0020(0x0088)()
bool CallFunc_EqualEqual_ByteByte_ReturnValue; // 0x00A8(0x0001)(ZeroConstructor, IsPlainOldData, NoDestructor)
uint8 Pad_718C[0x7]; // 0x00A9(0x0007)(Fixing Size After Last Property [ Dumper-7 ])
class UUserWidget* CallFunc_Create_Basic_Tooltip_Output; // 0x00B0(0x0008)(ZeroConstructor, InstancedReference, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
};
static_assert(alignof(StatsListItemWIdget_C_GetListItemTooltipWidget) == 0x000008, "Wrong alignment on StatsListItemWIdget_C_GetListItemTooltipWidget");
static_assert(sizeof(StatsListItemWIdget_C_GetListItemTooltipWidget) == 0x0000B8, "Wrong size on StatsListItemWIdget_C_GetListItemTooltipWidget");
static_assert(offsetof(StatsListItemWIdget_C_GetListItemTooltipWidget, ReturnValue) == 0x000000, "Member 'StatsListItemWIdget_C_GetListItemTooltipWidget::ReturnValue' has a wrong offset!");
static_assert(offsetof(StatsListItemWIdget_C_GetListItemTooltipWidget, CallFunc_GetContext_ReturnValue) == 0x000008, "Member 'StatsListItemWIdget_C_GetListItemTooltipWidget::CallFunc_GetContext_ReturnValue' has a wrong offset!");
static_assert(offsetof(StatsListItemWIdget_C_GetListItemTooltipWidget, CallFunc_GetOwningPlayer_ReturnValue) == 0x000010, "Member 'StatsListItemWIdget_C_GetListItemTooltipWidget::CallFunc_GetOwningPlayer_ReturnValue' has a wrong offset!");
static_assert(offsetof(StatsListItemWIdget_C_GetListItemTooltipWidget, CallFunc_GetCurrentInputType_ReturnValue) == 0x000018, "Member 'StatsListItemWIdget_C_GetListItemTooltipWidget::CallFunc_GetCurrentInputType_ReturnValue' has a wrong offset!");
static_assert(offsetof(StatsListItemWIdget_C_GetListItemTooltipWidget, CallFunc_GetCurrentAttributeCopy_OutDisplayAttribute) == 0x000020, "Member 'StatsListItemWIdget_C_GetListItemTooltipWidget::CallFunc_GetCurrentAttributeCopy_OutDisplayAttribute' has a wrong offset!");
static_assert(offsetof(StatsListItemWIdget_C_GetListItemTooltipWidget, CallFunc_EqualEqual_ByteByte_ReturnValue) == 0x0000A8, "Member 'StatsListItemWIdget_C_GetListItemTooltipWidget::CallFunc_EqualEqual_ByteByte_ReturnValue' has a wrong offset!");
static_assert(offsetof(StatsListItemWIdget_C_GetListItemTooltipWidget, CallFunc_Create_Basic_Tooltip_Output) == 0x0000B0, "Member 'StatsListItemWIdget_C_GetListItemTooltipWidget::CallFunc_Create_Basic_Tooltip_Output' has a wrong offset!");
// Function StatsListItemWIdget.StatsListItemWIdget_C.SetStatIcon
// 0x0088 (0x0088 - 0x0000)
struct StatsListItemWIdget_C_SetStatIcon final
{
public:
struct FSlateBrush NewParam; // 0x0000(0x0088)(BlueprintVisible, BlueprintReadOnly, Parm)
};
static_assert(alignof(StatsListItemWIdget_C_SetStatIcon) == 0x000008, "Wrong alignment on StatsListItemWIdget_C_SetStatIcon");
static_assert(sizeof(StatsListItemWIdget_C_SetStatIcon) == 0x000088, "Wrong size on StatsListItemWIdget_C_SetStatIcon");
static_assert(offsetof(StatsListItemWIdget_C_SetStatIcon, NewParam) == 0x000000, "Member 'StatsListItemWIdget_C_SetStatIcon::NewParam' has a wrong offset!");
// Function StatsListItemWIdget.StatsListItemWIdget_C.UpdateBuffArrows
// 0x0148 (0x0148 - 0x0000)
struct StatsListItemWIdget_C_UpdateBuffArrows final
{
public:
struct FFortDisplayAttribute CurrentAttribute; // 0x0000(0x0088)(BlueprintVisible, BlueprintReadOnly, Parm)
struct FFortDisplayAttribute LocalCurrentAttribute; // 0x0088(0x0088)(Edit, BlueprintVisible)
float Temp_float_Variable; // 0x0110(0x0004)(ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
float Temp_float_Variable_1; // 0x0114(0x0004)(ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
float Temp_float_Variable_2; // 0x0118(0x0004)(ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
EFortClampState Temp_byte_Variable; // 0x011C(0x0001)(ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
ESlateVisibility Temp_byte_Variable_1; // 0x011D(0x0001)(ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
ESlateVisibility Temp_byte_Variable_2; // 0x011E(0x0001)(ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
ESlateVisibility Temp_byte_Variable_3; // 0x011F(0x0001)(ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
EFortComparisonType Temp_byte_Variable_4; // 0x0120(0x0001)(ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
uint8 Pad_718D[0x3]; // 0x0121(0x0003)(Fixing Size After Last Property [ Dumper-7 ])
float Temp_float_Variable_3; // 0x0124(0x0004)(ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
float Temp_float_Variable_4; // 0x0128(0x0004)(ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
float Temp_float_Variable_5; // 0x012C(0x0004)(ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
float Temp_float_Variable_6; // 0x0130(0x0004)(ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
EFortComparisonType Temp_byte_Variable_5; // 0x0134(0x0001)(ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
uint8 Pad_718E[0x3]; // 0x0135(0x0003)(Fixing Size After Last Property [ Dumper-7 ])
float K2Node_Select_Default; // 0x0138(0x0004)(ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
ESlateVisibility Temp_byte_Variable_6; // 0x013C(0x0001)(ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
ESlateVisibility Temp_byte_Variable_7; // 0x013D(0x0001)(ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
ESlateVisibility Temp_byte_Variable_8; // 0x013E(0x0001)(ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
ESlateVisibility Temp_byte_Variable_9; // 0x013F(0x0001)(ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
ESlateVisibility K2Node_Select_Default_1; // 0x0140(0x0001)(ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
ESlateVisibility K2Node_Select_Default_2; // 0x0141(0x0001)(ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
EFortClampState Temp_byte_Variable_10; // 0x0142(0x0001)(ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
uint8 Pad_718F[0x1]; // 0x0143(0x0001)(Fixing Size After Last Property [ Dumper-7 ])
float K2Node_Select_Default_3; // 0x0144(0x0004)(ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
};
static_assert(alignof(StatsListItemWIdget_C_UpdateBuffArrows) == 0x000008, "Wrong alignment on StatsListItemWIdget_C_UpdateBuffArrows");
static_assert(sizeof(StatsListItemWIdget_C_UpdateBuffArrows) == 0x000148, "Wrong size on StatsListItemWIdget_C_UpdateBuffArrows");
static_assert(offsetof(StatsListItemWIdget_C_UpdateBuffArrows, CurrentAttribute) == 0x000000, "Member 'StatsListItemWIdget_C_UpdateBuffArrows::CurrentAttribute' has a wrong offset!");
static_assert(offsetof(StatsListItemWIdget_C_UpdateBuffArrows, LocalCurrentAttribute) == 0x000088, "Member 'StatsListItemWIdget_C_UpdateBuffArrows::LocalCurrentAttribute' has a wrong offset!");
static_assert(offsetof(StatsListItemWIdget_C_UpdateBuffArrows, Temp_float_Variable) == 0x000110, "Member 'StatsListItemWIdget_C_UpdateBuffArrows::Temp_float_Variable' has a wrong offset!");
static_assert(offsetof(StatsListItemWIdget_C_UpdateBuffArrows, Temp_float_Variable_1) == 0x000114, "Member 'StatsListItemWIdget_C_UpdateBuffArrows::Temp_float_Variable_1' has a wrong offset!");
static_assert(offsetof(StatsListItemWIdget_C_UpdateBuffArrows, Temp_float_Variable_2) == 0x000118, "Member 'StatsListItemWIdget_C_UpdateBuffArrows::Temp_float_Variable_2' has a wrong offset!");
static_assert(offsetof(StatsListItemWIdget_C_UpdateBuffArrows, Temp_byte_Variable) == 0x00011C, "Member 'StatsListItemWIdget_C_UpdateBuffArrows::Temp_byte_Variable' has a wrong offset!");
static_assert(offsetof(StatsListItemWIdget_C_UpdateBuffArrows, Temp_byte_Variable_1) == 0x00011D, "Member 'StatsListItemWIdget_C_UpdateBuffArrows::Temp_byte_Variable_1' has a wrong offset!");
static_assert(offsetof(StatsListItemWIdget_C_UpdateBuffArrows, Temp_byte_Variable_2) == 0x00011E, "Member 'StatsListItemWIdget_C_UpdateBuffArrows::Temp_byte_Variable_2' has a wrong offset!");
static_assert(offsetof(StatsListItemWIdget_C_UpdateBuffArrows, Temp_byte_Variable_3) == 0x00011F, "Member 'StatsListItemWIdget_C_UpdateBuffArrows::Temp_byte_Variable_3' has a wrong offset!");
static_assert(offsetof(StatsListItemWIdget_C_UpdateBuffArrows, Temp_byte_Variable_4) == 0x000120, "Member 'StatsListItemWIdget_C_UpdateBuffArrows::Temp_byte_Variable_4' has a wrong offset!");
static_assert(offsetof(StatsListItemWIdget_C_UpdateBuffArrows, Temp_float_Variable_3) == 0x000124, "Member 'StatsListItemWIdget_C_UpdateBuffArrows::Temp_float_Variable_3' has a wrong offset!");
static_assert(offsetof(StatsListItemWIdget_C_UpdateBuffArrows, Temp_float_Variable_4) == 0x000128, "Member 'StatsListItemWIdget_C_UpdateBuffArrows::Temp_float_Variable_4' has a wrong offset!");
static_assert(offsetof(StatsListItemWIdget_C_UpdateBuffArrows, Temp_float_Variable_5) == 0x00012C, "Member 'StatsListItemWIdget_C_UpdateBuffArrows::Temp_float_Variable_5' has a wrong offset!");
static_assert(offsetof(StatsListItemWIdget_C_UpdateBuffArrows, Temp_float_Variable_6) == 0x000130, "Member 'StatsListItemWIdget_C_UpdateBuffArrows::Temp_float_Variable_6' has a wrong offset!");
static_assert(offsetof(StatsListItemWIdget_C_UpdateBuffArrows, Temp_byte_Variable_5) == 0x000134, "Member 'StatsListItemWIdget_C_UpdateBuffArrows::Temp_byte_Variable_5' has a wrong offset!");
static_assert(offsetof(StatsListItemWIdget_C_UpdateBuffArrows, K2Node_Select_Default) == 0x000138, "Member 'StatsListItemWIdget_C_UpdateBuffArrows::K2Node_Select_Default' has a wrong offset!");
static_assert(offsetof(StatsListItemWIdget_C_UpdateBuffArrows, Temp_byte_Variable_6) == 0x00013C, "Member 'StatsListItemWIdget_C_UpdateBuffArrows::Temp_byte_Variable_6' has a wrong offset!");
static_assert(offsetof(StatsListItemWIdget_C_UpdateBuffArrows, Temp_byte_Variable_7) == 0x00013D, "Member 'StatsListItemWIdget_C_UpdateBuffArrows::Temp_byte_Variable_7' has a wrong offset!");
static_assert(offsetof(StatsListItemWIdget_C_UpdateBuffArrows, Temp_byte_Variable_8) == 0x00013E, "Member 'StatsListItemWIdget_C_UpdateBuffArrows::Temp_byte_Variable_8' has a wrong offset!");
static_assert(offsetof(StatsListItemWIdget_C_UpdateBuffArrows, Temp_byte_Variable_9) == 0x00013F, "Member 'StatsListItemWIdget_C_UpdateBuffArrows::Temp_byte_Variable_9' has a wrong offset!");
static_assert(offsetof(StatsListItemWIdget_C_UpdateBuffArrows, K2Node_Select_Default_1) == 0x000140, "Member 'StatsListItemWIdget_C_UpdateBuffArrows::K2Node_Select_Default_1' has a wrong offset!");
static_assert(offsetof(StatsListItemWIdget_C_UpdateBuffArrows, K2Node_Select_Default_2) == 0x000141, "Member 'StatsListItemWIdget_C_UpdateBuffArrows::K2Node_Select_Default_2' has a wrong offset!");
static_assert(offsetof(StatsListItemWIdget_C_UpdateBuffArrows, Temp_byte_Variable_10) == 0x000142, "Member 'StatsListItemWIdget_C_UpdateBuffArrows::Temp_byte_Variable_10' has a wrong offset!");
static_assert(offsetof(StatsListItemWIdget_C_UpdateBuffArrows, K2Node_Select_Default_3) == 0x000144, "Member 'StatsListItemWIdget_C_UpdateBuffArrows::K2Node_Select_Default_3' has a wrong offset!");
// Function StatsListItemWIdget.StatsListItemWIdget_C.UpdateBasicPairLabel
// 0x00A8 (0x00A8 - 0x0000)
struct StatsListItemWIdget_C_UpdateBasicPairLabel final
{
public:
struct FFortDisplayAttribute CurrentAttribute; // 0x0000(0x0088)(BlueprintVisible, BlueprintReadOnly, Parm)
class FText CallFunc_GetEmptyText_ReturnValue; // 0x0088(0x0018)()
bool CallFunc_NotEqual_TextText_ReturnValue; // 0x00A0(0x0001)(ZeroConstructor, IsPlainOldData, NoDestructor)
};
static_assert(alignof(StatsListItemWIdget_C_UpdateBasicPairLabel) == 0x000008, "Wrong alignment on StatsListItemWIdget_C_UpdateBasicPairLabel");
static_assert(sizeof(StatsListItemWIdget_C_UpdateBasicPairLabel) == 0x0000A8, "Wrong size on StatsListItemWIdget_C_UpdateBasicPairLabel");
static_assert(offsetof(StatsListItemWIdget_C_UpdateBasicPairLabel, CurrentAttribute) == 0x000000, "Member 'StatsListItemWIdget_C_UpdateBasicPairLabel::CurrentAttribute' has a wrong offset!");
static_assert(offsetof(StatsListItemWIdget_C_UpdateBasicPairLabel, CallFunc_GetEmptyText_ReturnValue) == 0x000088, "Member 'StatsListItemWIdget_C_UpdateBasicPairLabel::CallFunc_GetEmptyText_ReturnValue' has a wrong offset!");
static_assert(offsetof(StatsListItemWIdget_C_UpdateBasicPairLabel, CallFunc_NotEqual_TextText_ReturnValue) == 0x0000A0, "Member 'StatsListItemWIdget_C_UpdateBasicPairLabel::CallFunc_NotEqual_TextText_ReturnValue' has a wrong offset!");
// Function StatsListItemWIdget.StatsListItemWIdget_C.UpdateValueText
// 0x0088 (0x0088 - 0x0000)
struct StatsListItemWIdget_C_UpdateValueText final
{
public:
struct FFortDisplayAttribute CurrentAttribute; // 0x0000(0x0088)(BlueprintVisible, BlueprintReadOnly, Parm)
};
static_assert(alignof(StatsListItemWIdget_C_UpdateValueText) == 0x000008, "Wrong alignment on StatsListItemWIdget_C_UpdateValueText");
static_assert(sizeof(StatsListItemWIdget_C_UpdateValueText) == 0x000088, "Wrong size on StatsListItemWIdget_C_UpdateValueText");
static_assert(offsetof(StatsListItemWIdget_C_UpdateValueText, CurrentAttribute) == 0x000000, "Member 'StatsListItemWIdget_C_UpdateValueText::CurrentAttribute' has a wrong offset!");
// Function StatsListItemWIdget.StatsListItemWIdget_C.UpdateType
// 0x0098 (0x0098 - 0x0000)
struct StatsListItemWIdget_C_UpdateType final
{
public:
struct FFortDisplayAttribute CurrentAttribute; // 0x0000(0x0088)(BlueprintVisible, BlueprintReadOnly, Parm)
EFortStatValueDisplayType Temp_byte_Variable; // 0x0088(0x0001)(ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
uint8 Pad_7190[0x7]; // 0x0089(0x0007)(Fixing Size After Last Property [ Dumper-7 ])
class UWidget* K2Node_Select_Default; // 0x0090(0x0008)(ZeroConstructor, InstancedReference, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
};
static_assert(alignof(StatsListItemWIdget_C_UpdateType) == 0x000008, "Wrong alignment on StatsListItemWIdget_C_UpdateType");
static_assert(sizeof(StatsListItemWIdget_C_UpdateType) == 0x000098, "Wrong size on StatsListItemWIdget_C_UpdateType");
static_assert(offsetof(StatsListItemWIdget_C_UpdateType, CurrentAttribute) == 0x000000, "Member 'StatsListItemWIdget_C_UpdateType::CurrentAttribute' has a wrong offset!");
static_assert(offsetof(StatsListItemWIdget_C_UpdateType, Temp_byte_Variable) == 0x000088, "Member 'StatsListItemWIdget_C_UpdateType::Temp_byte_Variable' has a wrong offset!");
static_assert(offsetof(StatsListItemWIdget_C_UpdateType, K2Node_Select_Default) == 0x000090, "Member 'StatsListItemWIdget_C_UpdateType::K2Node_Select_Default' has a wrong offset!");
// Function StatsListItemWIdget.StatsListItemWIdget_C.UpdateColors
// 0x01C8 (0x01C8 - 0x0000)
struct StatsListItemWIdget_C_UpdateColors final
{
public:
struct FFortDisplayAttribute CurrentAttribute; // 0x0000(0x0088)(BlueprintVisible, BlueprintReadOnly, Parm)
struct FFortDisplayAttribute LocalCurrentAttribute; // 0x0088(0x0088)(Edit, BlueprintVisible)
struct FLinearColor BuffColor; // 0x0110(0x0010)(Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
struct FLinearColor BaseColor; // 0x0120(0x0010)(Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
class UClass* Temp_class_Variable; // 0x0130(0x0008)(ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
class UClass* Temp_class_Variable_1; // 0x0138(0x0008)(ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
class UClass* Temp_class_Variable_2; // 0x0140(0x0008)(ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
EFortBuffState Temp_byte_Variable; // 0x0148(0x0001)(ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
EFortBuffState Temp_byte_Variable_1; // 0x0149(0x0001)(ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
uint8 Pad_7191[0x6]; // 0x014A(0x0006)(Fixing Size After Last Property [ Dumper-7 ])
class UClass* K2Node_Select_Default; // 0x0150(0x0008)(ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
struct FLinearColor CallFunc_Get_Base___Buff_Colors_Base; // 0x0158(0x0010)(ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
struct FLinearColor CallFunc_Get_Base___Buff_Colors_Buff; // 0x0168(0x0010)(ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
EFortComparisonType Temp_byte_Variable_2; // 0x0178(0x0001)(ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
bool K2Node_SwitchEnum_CmpSuccess; // 0x0179(0x0001)(ZeroConstructor, IsPlainOldData, NoDestructor)
bool CallFunc_NotEqual_TextText_ReturnValue; // 0x017A(0x0001)(ZeroConstructor, IsPlainOldData, NoDestructor)
uint8 Pad_7192[0x1]; // 0x017B(0x0001)(Fixing Size After Last Property [ Dumper-7 ])
struct FLinearColor K2Node_Select_Default_1; // 0x017C(0x0010)(ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
uint8 Pad_7193[0x4]; // 0x018C(0x0004)(Fixing Size After Last Property [ Dumper-7 ])
struct FSlateColor K2Node_MakeStruct_SlateColor; // 0x0190(0x0028)()
struct FLinearColor K2Node_Select_Default_2; // 0x01B8(0x0010)(ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
};
static_assert(alignof(StatsListItemWIdget_C_UpdateColors) == 0x000008, "Wrong alignment on StatsListItemWIdget_C_UpdateColors");
static_assert(sizeof(StatsListItemWIdget_C_UpdateColors) == 0x0001C8, "Wrong size on StatsListItemWIdget_C_UpdateColors");
static_assert(offsetof(StatsListItemWIdget_C_UpdateColors, CurrentAttribute) == 0x000000, "Member 'StatsListItemWIdget_C_UpdateColors::CurrentAttribute' has a wrong offset!");
static_assert(offsetof(StatsListItemWIdget_C_UpdateColors, LocalCurrentAttribute) == 0x000088, "Member 'StatsListItemWIdget_C_UpdateColors::LocalCurrentAttribute' has a wrong offset!");
static_assert(offsetof(StatsListItemWIdget_C_UpdateColors, BuffColor) == 0x000110, "Member 'StatsListItemWIdget_C_UpdateColors::BuffColor' has a wrong offset!");
static_assert(offsetof(StatsListItemWIdget_C_UpdateColors, BaseColor) == 0x000120, "Member 'StatsListItemWIdget_C_UpdateColors::BaseColor' has a wrong offset!");
static_assert(offsetof(StatsListItemWIdget_C_UpdateColors, Temp_class_Variable) == 0x000130, "Member 'StatsListItemWIdget_C_UpdateColors::Temp_class_Variable' has a wrong offset!");
static_assert(offsetof(StatsListItemWIdget_C_UpdateColors, Temp_class_Variable_1) == 0x000138, "Member 'StatsListItemWIdget_C_UpdateColors::Temp_class_Variable_1' has a wrong offset!");
static_assert(offsetof(StatsListItemWIdget_C_UpdateColors, Temp_class_Variable_2) == 0x000140, "Member 'StatsListItemWIdget_C_UpdateColors::Temp_class_Variable_2' has a wrong offset!");
static_assert(offsetof(StatsListItemWIdget_C_UpdateColors, Temp_byte_Variable) == 0x000148, "Member 'StatsListItemWIdget_C_UpdateColors::Temp_byte_Variable' has a wrong offset!");
static_assert(offsetof(StatsListItemWIdget_C_UpdateColors, Temp_byte_Variable_1) == 0x000149, "Member 'StatsListItemWIdget_C_UpdateColors::Temp_byte_Variable_1' has a wrong offset!");
static_assert(offsetof(StatsListItemWIdget_C_UpdateColors, K2Node_Select_Default) == 0x000150, "Member 'StatsListItemWIdget_C_UpdateColors::K2Node_Select_Default' has a wrong offset!");
static_assert(offsetof(StatsListItemWIdget_C_UpdateColors, CallFunc_Get_Base___Buff_Colors_Base) == 0x000158, "Member 'StatsListItemWIdget_C_UpdateColors::CallFunc_Get_Base___Buff_Colors_Base' has a wrong offset!");
static_assert(offsetof(StatsListItemWIdget_C_UpdateColors, CallFunc_Get_Base___Buff_Colors_Buff) == 0x000168, "Member 'StatsListItemWIdget_C_UpdateColors::CallFunc_Get_Base___Buff_Colors_Buff' has a wrong offset!");
static_assert(offsetof(StatsListItemWIdget_C_UpdateColors, Temp_byte_Variable_2) == 0x000178, "Member 'StatsListItemWIdget_C_UpdateColors::Temp_byte_Variable_2' has a wrong offset!");
static_assert(offsetof(StatsListItemWIdget_C_UpdateColors, K2Node_SwitchEnum_CmpSuccess) == 0x000179, "Member 'StatsListItemWIdget_C_UpdateColors::K2Node_SwitchEnum_CmpSuccess' has a wrong offset!");
static_assert(offsetof(StatsListItemWIdget_C_UpdateColors, CallFunc_NotEqual_TextText_ReturnValue) == 0x00017A, "Member 'StatsListItemWIdget_C_UpdateColors::CallFunc_NotEqual_TextText_ReturnValue' has a wrong offset!");
static_assert(offsetof(StatsListItemWIdget_C_UpdateColors, K2Node_Select_Default_1) == 0x00017C, "Member 'StatsListItemWIdget_C_UpdateColors::K2Node_Select_Default_1' has a wrong offset!");
static_assert(offsetof(StatsListItemWIdget_C_UpdateColors, K2Node_MakeStruct_SlateColor) == 0x000190, "Member 'StatsListItemWIdget_C_UpdateColors::K2Node_MakeStruct_SlateColor' has a wrong offset!");
static_assert(offsetof(StatsListItemWIdget_C_UpdateColors, K2Node_Select_Default_2) == 0x0001B8, "Member 'StatsListItemWIdget_C_UpdateColors::K2Node_Select_Default_2' has a wrong offset!");
// Function StatsListItemWIdget.StatsListItemWIdget_C.Update
// 0x0110 (0x0110 - 0x0000)
struct StatsListItemWIdget_C_Update final
{
public:
struct FFortDisplayAttribute CurrentAttribute; // 0x0000(0x0088)(Edit, BlueprintVisible)
struct FFortDisplayAttribute CallFunc_GetCurrentAttributeCopy_OutDisplayAttribute; // 0x0088(0x0088)()
};
static_assert(alignof(StatsListItemWIdget_C_Update) == 0x000008, "Wrong alignment on StatsListItemWIdget_C_Update");
static_assert(sizeof(StatsListItemWIdget_C_Update) == 0x000110, "Wrong size on StatsListItemWIdget_C_Update");
static_assert(offsetof(StatsListItemWIdget_C_Update, CurrentAttribute) == 0x000000, "Member 'StatsListItemWIdget_C_Update::CurrentAttribute' has a wrong offset!");
static_assert(offsetof(StatsListItemWIdget_C_Update, CallFunc_GetCurrentAttributeCopy_OutDisplayAttribute) == 0x000088, "Member 'StatsListItemWIdget_C_Update::CallFunc_GetCurrentAttributeCopy_OutDisplayAttribute' has a wrong offset!");
// Function StatsListItemWIdget.StatsListItemWIdget_C.ValueChanged
// 0x0004 (0x0004 - 0x0000)
struct StatsListItemWIdget_C_ValueChanged final
{
public:
float Delta; // 0x0000(0x0004)(BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
};
static_assert(alignof(StatsListItemWIdget_C_ValueChanged) == 0x000004, "Wrong alignment on StatsListItemWIdget_C_ValueChanged");
static_assert(sizeof(StatsListItemWIdget_C_ValueChanged) == 0x000004, "Wrong size on StatsListItemWIdget_C_ValueChanged");
static_assert(offsetof(StatsListItemWIdget_C_ValueChanged, Delta) == 0x000000, "Member 'StatsListItemWIdget_C_ValueChanged::Delta' has a wrong offset!");
// Function StatsListItemWIdget.StatsListItemWIdget_C.ExecuteUbergraph_StatsListItemWIdget
// 0x0098 (0x0098 - 0x0000)
struct StatsListItemWIdget_C_ExecuteUbergraph_StatsListItemWIdget final
{
public:
int32 EntryPoint; // 0x0000(0x0004)(BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
bool CallFunc_IsValid_ReturnValue; // 0x0004(0x0001)(ZeroConstructor, IsPlainOldData, NoDestructor)
uint8 Pad_7194[0x3]; // 0x0005(0x0003)(Fixing Size After Last Property [ Dumper-7 ])
struct FFortDisplayAttribute CallFunc_GetCurrentAttributeCopy_OutDisplayAttribute; // 0x0008(0x0088)()
float K2Node_Event_Delta; // 0x0090(0x0004)(ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
};
static_assert(alignof(StatsListItemWIdget_C_ExecuteUbergraph_StatsListItemWIdget) == 0x000008, "Wrong alignment on StatsListItemWIdget_C_ExecuteUbergraph_StatsListItemWIdget");
static_assert(sizeof(StatsListItemWIdget_C_ExecuteUbergraph_StatsListItemWIdget) == 0x000098, "Wrong size on StatsListItemWIdget_C_ExecuteUbergraph_StatsListItemWIdget");
static_assert(offsetof(StatsListItemWIdget_C_ExecuteUbergraph_StatsListItemWIdget, EntryPoint) == 0x000000, "Member 'StatsListItemWIdget_C_ExecuteUbergraph_StatsListItemWIdget::EntryPoint' has a wrong offset!");
static_assert(offsetof(StatsListItemWIdget_C_ExecuteUbergraph_StatsListItemWIdget, CallFunc_IsValid_ReturnValue) == 0x000004, "Member 'StatsListItemWIdget_C_ExecuteUbergraph_StatsListItemWIdget::CallFunc_IsValid_ReturnValue' has a wrong offset!");
static_assert(offsetof(StatsListItemWIdget_C_ExecuteUbergraph_StatsListItemWIdget, CallFunc_GetCurrentAttributeCopy_OutDisplayAttribute) == 0x000008, "Member 'StatsListItemWIdget_C_ExecuteUbergraph_StatsListItemWIdget::CallFunc_GetCurrentAttributeCopy_OutDisplayAttribute' has a wrong offset!");
static_assert(offsetof(StatsListItemWIdget_C_ExecuteUbergraph_StatsListItemWIdget, K2Node_Event_Delta) == 0x000090, "Member 'StatsListItemWIdget_C_ExecuteUbergraph_StatsListItemWIdget::K2Node_Event_Delta' has a wrong offset!");
}
| 1 | 0.584633 | 1 | 0.584633 | game-dev | MEDIA | 0.573812 | game-dev | 0.816545 | 1 | 0.816545 |
Nevermore1994/slark | 1,965 | src/platform/Android/sdk/src/main/java/com/slark/sdk/SlarkPlayerManager.kt | package com.slark.sdk
import com.slark.api.SlarkPlayerEvent
import com.slark.api.SlarkPlayerState
import java.util.concurrent.ConcurrentHashMap
class SlarkPlayerManager {
enum class Action {
PREPARE,
PLAY,
PAUSE,
RELEASE
}
companion object {
private val players = ConcurrentHashMap<String, SlarkPlayerImpl>()
@JvmStatic
fun addPlayer(playerId: String, player: SlarkPlayerImpl) {
players[playerId] = player
}
@JvmStatic
fun removePlayer(playerId: String) {
players.remove(playerId)
}
@JvmStatic
fun notifyPlayerState(playerId: String, state: SlarkPlayerState) {
players[playerId]?.observer()?.notifyState(playerId, state)
}
@JvmStatic
fun notifyPlayerEvent(playerId: String, event: SlarkPlayerEvent, value: String) {
players[playerId]?.observer()?.notifyEvent(playerId, event, value)
}
@JvmStatic
fun notifyPlayerTime(playerId: String, time: Double) {
players[playerId]?.observer()?.notifyTime(playerId, time)
}
@JvmStatic
fun requestRender(playerId: String, textureId: Int, width: Int, height: Int) {
players[playerId]?.requestRender(textureId, width, height)
}
external fun createPlayer(path: String, start: Double, duration: Double): String
external fun doAction(playerId: String, action: Int)
external fun setLoop(playerId: String, isLoop: Boolean)
external fun setVolume(playerId: String, volume: Float)
external fun setMute(playerId: String, isMute: Boolean)
external fun seek(playerId: String, time: Double, isAccurate: Boolean)
external fun totalDuration(playerId: String):Double
external fun currentPlayedTime(playerId: String): Double
external fun state(playerId: String): SlarkPlayerState
}
} | 1 | 0.700392 | 1 | 0.700392 | game-dev | MEDIA | 0.52754 | game-dev | 0.568796 | 1 | 0.568796 |
exmex/HC | 7,063 | Client/Code_Client/template/msvc/CCAppWiz.win32/Templates/1033/Resources/hello.lua |
-- for CCLuaEngine traceback
function __G__TRACKBACK__(msg)
print("----------------------------------------")
print("LUA ERROR: " .. tostring(msg) .. "\n")
print(debug.traceback())
print("----------------------------------------")
end
local function main()
-- avoid memory leak
collectgarbage("setpause", 100)
collectgarbage("setstepmul", 5000)
local cclog = function(...)
print(string.format(...))
end
require "hello2"
cclog("result is " .. myadd(3, 5))
---------------
local visibleSize = CCDirector:sharedDirector():getVisibleSize()
local origin = CCDirector:sharedDirector():getVisibleOrigin()
-- add the moving dog
local function creatDog()
local frameWidth = 105
local frameHeight = 95
-- create dog animate
local textureDog = CCTextureCache:sharedTextureCache():addImage("dog.png")
local rect = CCRectMake(0, 0, frameWidth, frameHeight)
local frame0 = CCSpriteFrame:createWithTexture(textureDog, rect)
rect = CCRectMake(frameWidth, 0, frameWidth, frameHeight)
local frame1 = CCSpriteFrame:createWithTexture(textureDog, rect)
local spriteDog = CCSprite:createWithSpriteFrame(frame0)
spriteDog.isPaused = false
spriteDog:setPosition(origin.x, origin.y + visibleSize.height / 4 * 3)
local animFrames = CCArray:create()
animFrames:addObject(frame0)
animFrames:addObject(frame1)
local animation = CCAnimation:createWithSpriteFrames(animFrames, 0.5)
local animate = CCAnimate:create(animation);
spriteDog:runAction(CCRepeatForever:create(animate))
-- moving dog at every frame
local function tick()
if spriteDog.isPaused then return end
local x, y = spriteDog:getPosition()
if x > origin.x + visibleSize.width then
x = origin.x
else
x = x + 1
end
spriteDog:setPositionX(x)
end
CCDirector:sharedDirector():getScheduler():scheduleScriptFunc(tick, 0, false)
return spriteDog
end
-- create farm
local function createLayerFarm()
local layerFarm = CCLayer:create()
-- add in farm background
local bg = CCSprite:create("farm.jpg")
bg:setPosition(origin.x + visibleSize.width / 2 + 80, origin.y + visibleSize.height / 2)
layerFarm:addChild(bg)
-- add land sprite
for i = 0, 3 do
for j = 0, 1 do
local spriteLand = CCSprite:create("land.png")
spriteLand:setPosition(200 + j * 180 - i % 2 * 90, 10 + i * 95 / 2)
layerFarm:addChild(spriteLand)
end
end
-- add crop
local frameCrop = CCSpriteFrame:create("crop.png", CCRectMake(0, 0, 105, 95))
for i = 0, 3 do
for j = 0, 1 do
local spriteCrop = CCSprite:createWithSpriteFrame(frameCrop);
spriteCrop:setPosition(10 + 200 + j * 180 - i % 2 * 90, 30 + 10 + i * 95 / 2)
layerFarm:addChild(spriteCrop)
end
end
-- add moving dog
local spriteDog = creatDog()
layerFarm:addChild(spriteDog)
-- handing touch events
local touchBeginPoint = nil
local function onTouchBegan(x, y)
cclog("onTouchBegan: %0.2f, %0.2f", x, y)
touchBeginPoint = {x = x, y = y}
spriteDog.isPaused = true
-- CCTOUCHBEGAN event must return true
return true
end
local function onTouchMoved(x, y)
cclog("onTouchMoved: %0.2f, %0.2f", x, y)
if touchBeginPoint then
local cx, cy = layerFarm:getPosition()
layerFarm:setPosition(cx + x - touchBeginPoint.x,
cy + y - touchBeginPoint.y)
touchBeginPoint = {x = x, y = y}
end
end
local function onTouchEnded(x, y)
cclog("onTouchEnded: %0.2f, %0.2f", x, y)
touchBeginPoint = nil
spriteDog.isPaused = false
end
local function onTouch(eventType, x, y)
if eventType == "began" then
return onTouchBegan(x, y)
elseif eventType == "moved" then
return onTouchMoved(x, y)
else
return onTouchEnded(x, y)
end
end
layerFarm:registerScriptTouchHandler(onTouch)
layerFarm:setTouchEnabled(true)
return layerFarm
end
-- create menu
local function createLayerMenu()
local layerMenu = CCLayer:create()
local menuPopup, menuTools, effectID
local function menuCallbackClosePopup()
-- stop test sound effect
SimpleAudioEngine:sharedEngine():stopEffect(effectID)
menuPopup:setVisible(false)
end
local function menuCallbackOpenPopup()
-- loop test sound effect
local effectPath = CCFileUtils:sharedFileUtils():fullPathForFilename("effect1.wav")
effectID = SimpleAudioEngine:sharedEngine():playEffect(effectPath)
menuPopup:setVisible(true)
end
-- add a popup menu
local menuPopupItem = CCMenuItemImage:create("menu2.png", "menu2.png")
menuPopupItem:setPosition(0, 0)
menuPopupItem:registerScriptTapHandler(menuCallbackClosePopup)
menuPopup = CCMenu:createWithItem(menuPopupItem)
menuPopup:setPosition(origin.x + visibleSize.width / 2, origin.y + visibleSize.height / 2)
menuPopup:setVisible(false)
layerMenu:addChild(menuPopup)
-- add the left-bottom "tools" menu to invoke menuPopup
local menuToolsItem = CCMenuItemImage:create("menu1.png", "menu1.png")
menuToolsItem:setPosition(0, 0)
menuToolsItem:registerScriptTapHandler(menuCallbackOpenPopup)
menuTools = CCMenu:createWithItem(menuToolsItem)
local itemWidth = menuToolsItem:getContentSize().width
local itemHeight = menuToolsItem:getContentSize().height
menuTools:setPosition(origin.x + itemWidth/2, origin.y + itemHeight/2)
layerMenu:addChild(menuTools)
return layerMenu
end
-- play background music, preload effect
-- uncomment below for the BlackBerry version
-- local bgMusicPath = CCFileUtils:sharedFileUtils():fullPathForFilename("background.ogg")
local bgMusicPath = CCFileUtils:sharedFileUtils():fullPathForFilename("background.mp3")
SimpleAudioEngine:sharedEngine():playBackgroundMusic(bgMusicPath, true)
local effectPath = CCFileUtils:sharedFileUtils():fullPathForFilename("effect1.wav")
SimpleAudioEngine:sharedEngine():preloadEffect(effectPath)
-- run
local sceneGame = CCScene:create()
sceneGame:addChild(createLayerFarm())
sceneGame:addChild(createLayerMenu())
CCDirector:sharedDirector():runWithScene(sceneGame)
end
xpcall(main, __G__TRACKBACK__)
| 1 | 0.733454 | 1 | 0.733454 | game-dev | MEDIA | 0.878 | game-dev | 0.756916 | 1 | 0.756916 |
hibernate/hibernate-validator | 2,406 | engine/src/main/java/org/hibernate/validator/internal/engine/messageinterpolation/parser/ELState.java | /*
* SPDX-License-Identifier: Apache-2.0
* Copyright Red Hat Inc. and Hibernate Authors
*/
package org.hibernate.validator.internal.engine.messageinterpolation.parser;
import static org.hibernate.validator.internal.engine.messageinterpolation.util.InterpolationHelper.EL_DESIGNATOR;
import java.lang.invoke.MethodHandles;
import org.hibernate.validator.internal.util.logging.Log;
import org.hibernate.validator.internal.util.logging.LoggerFactory;
/**
* @author Hardy Ferentschik
*/
public class ELState implements ParserState {
private static final Log LOG = LoggerFactory.make( MethodHandles.lookup() );
@Override
public void terminate(TokenCollector tokenCollector) throws MessageDescriptorFormatException {
tokenCollector.appendToToken( EL_DESIGNATOR );
tokenCollector.terminateToken();
}
@Override
public void handleNonMetaCharacter(char character, TokenCollector tokenCollector)
throws MessageDescriptorFormatException {
tokenCollector.appendToToken( EL_DESIGNATOR );
tokenCollector.appendToToken( character );
tokenCollector.terminateToken();
tokenCollector.transitionState( new MessageState() );
}
@Override
public void handleBeginTerm(char character, TokenCollector tokenCollector) throws MessageDescriptorFormatException {
tokenCollector.terminateToken();
tokenCollector.appendToToken( EL_DESIGNATOR );
tokenCollector.appendToToken( character );
tokenCollector.makeELToken();
tokenCollector.transitionState( new InterpolationTermState() );
}
@Override
public void handleEndTerm(char character, TokenCollector tokenCollector) throws MessageDescriptorFormatException {
throw LOG.getUnbalancedBeginEndParameterException(
tokenCollector.getOriginalMessageDescriptor(),
character
);
}
@Override
public void handleEscapeCharacter(char character, TokenCollector tokenCollector)
throws MessageDescriptorFormatException {
tokenCollector.appendToToken( EL_DESIGNATOR );
tokenCollector.appendToToken( character );
// Do not go back to this state after the escape: $\ is not the start of an EL expression
ParserState stateAfterEscape = new MessageState();
tokenCollector.transitionState( new EscapedState( stateAfterEscape ) );
}
@Override
public void handleELDesignator(char character, TokenCollector tokenCollector)
throws MessageDescriptorFormatException {
handleNonMetaCharacter( character, tokenCollector );
}
}
| 1 | 0.824135 | 1 | 0.824135 | game-dev | MEDIA | 0.358595 | game-dev | 0.797936 | 1 | 0.797936 |
grayj/Jedi-Academy | 16,616 | code/game/genericparser2.cpp | // Filename:- genericparser2.cpp
// leave this at the top for PCH reasons...
#include "common_headers.h"
#ifdef _JK2EXE
#include "../qcommon/qcommon.h"
#else
#include "g_headers.h"
#endif
//#define _EXE
#define MAX_TOKEN_SIZE 1024
static char token[MAX_TOKEN_SIZE];
static char *GetToken(char **text, bool allowLineBreaks, bool readUntilEOL = false)
{
char *pointer = *text;
int length = 0;
int c = 0;
bool foundLineBreak;
token[0] = 0;
if (!pointer)
{
return token;
}
while(1)
{
foundLineBreak = false;
while(1)
{
c = *pointer;
if (c > ' ')
{
break;
}
if (!c)
{
*text = 0;
return token;
}
if (c == '\n')
{
foundLineBreak = true;
}
pointer++;
}
if (foundLineBreak && !allowLineBreaks)
{
*text = pointer;
return token;
}
c = *pointer;
// skip single line comment
if (c == '/' && pointer[1] == '/')
{
pointer += 2;
while (*pointer && *pointer != '\n')
{
pointer++;
}
}
// skip multi line comments
else if (c == '/' && pointer[1] == '*')
{
pointer += 2;
while (*pointer && (*pointer != '*' || pointer[1] != '/'))
{
pointer++;
}
if (*pointer)
{
pointer += 2;
}
}
else
{ // found the start of a token
break;
}
}
if (c == '\"')
{ // handle a string
pointer++;
while (1)
{
c = *pointer++;
if (c == '\"')
{
// token[length++] = c;
break;
}
else if (!c)
{
break;
}
else if (length < MAX_TOKEN_SIZE)
{
token[length++] = c;
}
}
}
else if (readUntilEOL)
{
// absorb all characters until EOL
while(c != '\n' && c != '\r')
{
if (c == '/' && ((*(pointer+1)) == '/' || (*(pointer+1)) == '*'))
{
break;
}
if (length < MAX_TOKEN_SIZE)
{
token[length++] = c;
}
pointer++;
c = *pointer;
}
// remove trailing white space
while(length && token[length-1] < ' ')
{
length--;
}
}
else
{
while(c > ' ')
{
if (length < MAX_TOKEN_SIZE)
{
token[length++] = c;
}
pointer++;
c = *pointer;
}
}
if (token[0] == '\"')
{ // remove start quote
length--;
memmove(token, token+1, length);
if (length && token[length-1] == '\"')
{ // remove end quote
length--;
}
}
if (length >= MAX_TOKEN_SIZE)
{
length = 0;
}
token[length] = 0;
*text = (char *)pointer;
return token;
}
CTextPool::CTextPool(int initSize) :
mNext(0),
mSize(initSize),
mUsed(0)
{
#ifdef _EXE
// mPool = (char *)Z_Malloc(mSize, TAG_GP2);
mPool = (char *)Z_Malloc(mSize, TAG_TEXTPOOL, qtrue);
#else
mPool = (char *)trap_Z_Malloc(mSize, TAG_GP2);
#endif
}
CTextPool::~CTextPool(void)
{
#ifdef _EXE
Z_Free(mPool);
#else
trap_Z_Free(mPool);
#endif
}
char *CTextPool::AllocText(char *text, bool addNULL, CTextPool **poolPtr)
{
int length = strlen(text) + (addNULL ? 1 : 0);
if (mUsed + length + 1> mSize)
{ // extra 1 to put a null on the end
if (poolPtr)
{
(*poolPtr)->SetNext(new CTextPool(mSize));
*poolPtr = (*poolPtr)->GetNext();
return (*poolPtr)->AllocText(text, addNULL);
}
return 0;
}
strcpy(mPool + mUsed, text);
mUsed += length;
mPool[mUsed] = 0;
return mPool + mUsed - length;
}
void CleanTextPool(CTextPool *pool)
{
CTextPool *next;
while(pool)
{
next = pool->GetNext();
delete pool;
pool = next;
}
}
CGPObject::CGPObject(const char *initName) :
mName(initName),
mNext(0),
mInOrderNext(0),
mInOrderPrevious(0)
{
}
bool CGPObject::WriteText(CTextPool **textPool, const char *text)
{
if (strchr(text, ' ') || !text[0])
{
(*textPool)->AllocText("\"", false, textPool);
(*textPool)->AllocText((char *)text, false, textPool);
(*textPool)->AllocText("\"", false, textPool);
}
else
{
(*textPool)->AllocText((char *)text, false, textPool);
}
return true;
}
CGPValue::CGPValue(const char *initName, const char *initValue) :
CGPObject(initName),
mList(0)
{
if (initValue)
{
AddValue(initValue);
}
}
CGPValue::~CGPValue(void)
{
CGPObject *next;
while(mList)
{
next = mList->GetNext();
delete mList;
mList = next;
}
}
CGPValue *CGPValue::Duplicate(CTextPool **textPool)
{
CGPValue *newValue;
CGPObject *iterator;
char *name;
if (textPool)
{
name = (*textPool)->AllocText((char *)mName, true, textPool);
}
else
{
name = (char *)mName;
}
newValue = new CGPValue(name);
iterator = mList;
while(iterator)
{
if (textPool)
{
name = (*textPool)->AllocText((char *)iterator->GetName(), true, textPool);
}
else
{
name = (char *)iterator->GetName();
}
newValue->AddValue(name);
iterator = iterator->GetNext();
}
return newValue;
}
bool CGPValue::IsList(void)
{
if (!mList || !mList->GetNext())
{
return false;
}
return true;
}
const char *CGPValue::GetTopValue(void)
{
if (mList)
{
return mList->GetName();
}
return 0;
}
void CGPValue::AddValue(const char *newValue, CTextPool **textPool)
{
if (textPool)
{
newValue = (*textPool)->AllocText((char *)newValue, true, textPool);
}
if (mList == 0)
{
mList = new CGPObject(newValue);
mList->SetInOrderNext(mList);
}
else
{
mList->GetInOrderNext()->SetNext(new CGPObject(newValue));
mList->SetInOrderNext(mList->GetInOrderNext()->GetNext());
}
}
bool CGPValue::Parse(char **dataPtr, CTextPool **textPool)
{
char *token;
char *value;
while(1)
{
token = GetToken(dataPtr, true, true);
if (!token[0])
{ // end of data - error!
return false;
}
else if (strcmpi(token, "]") == 0)
{ // ending brace for this list
break;
}
value = (*textPool)->AllocText(token, true, textPool);
AddValue(value);
}
return true;
}
bool CGPValue::Write(CTextPool **textPool, int depth)
{
int i;
CGPObject *next;
if (!mList)
{
return true;
}
for(i=0;i<depth;i++)
{
(*textPool)->AllocText("\t", false, textPool);
}
WriteText(textPool, mName);
if (!mList->GetNext())
{
(*textPool)->AllocText("\t\t", false, textPool);
mList->WriteText(textPool, mList->GetName());
(*textPool)->AllocText("\r\n", false, textPool);
}
else
{
(*textPool)->AllocText("\r\n", false, textPool);
for(i=0;i<depth;i++)
{
(*textPool)->AllocText("\t", false, textPool);
}
(*textPool)->AllocText("[\r\n", false, textPool);
next = mList;
while(next)
{
for(i=0;i<depth+1;i++)
{
(*textPool)->AllocText("\t", false, textPool);
}
mList->WriteText(textPool, next->GetName());
(*textPool)->AllocText("\r\n", false, textPool);
next = next->GetNext();
}
for(i=0;i<depth;i++)
{
(*textPool)->AllocText("\t", false, textPool);
}
(*textPool)->AllocText("]\r\n", false, textPool);
}
return true;
}
CGPGroup::CGPGroup(const char *initName, CGPGroup *initParent) :
CGPObject(initName),
mPairs(0),
mInOrderPairs(0),
mCurrentPair(0),
mSubGroups(0),
mInOrderSubGroups(0),
mCurrentSubGroup(0),
mParent(initParent),
mWriteable(false)
{
}
CGPGroup::~CGPGroup(void)
{
Clean();
}
int CGPGroup::GetNumSubGroups(void)
{
int count;
CGPGroup *group;
count = 0;
group = mSubGroups;
while(group)
{
count++;
group = (CGPGroup *)group->GetNext();
}
return(count);
}
int CGPGroup::GetNumPairs(void)
{
int count;
CGPValue *pair;
count = 0;
pair = mPairs;
while(pair)
{
count++;
pair = (CGPValue *)pair->GetNext();
}
return(count);
}
void CGPGroup::Clean(void)
{
while(mPairs)
{
mCurrentPair = (CGPValue *)mPairs->GetNext();
delete mPairs;
mPairs = mCurrentPair;
}
while(mSubGroups)
{
mCurrentSubGroup = (CGPGroup *)mSubGroups->GetNext();
delete mSubGroups;
mSubGroups = mCurrentSubGroup;
}
mPairs = mInOrderPairs = mCurrentPair = 0;
mSubGroups = mInOrderSubGroups = mCurrentSubGroup = 0;
mParent = 0;
mWriteable = false;
}
CGPGroup *CGPGroup::Duplicate(CTextPool **textPool, CGPGroup *initParent)
{
CGPGroup *newGroup, *subSub, *newSub;
CGPValue *newPair, *subPair;
char *name;
if (textPool)
{
name = (*textPool)->AllocText((char *)mName, true, textPool);
}
else
{
name = (char *)mName;
}
newGroup = new CGPGroup(name);
subSub = mSubGroups;
while(subSub)
{
newSub = subSub->Duplicate(textPool, newGroup);
newGroup->AddGroup(newSub);
subSub = (CGPGroup *)subSub->GetNext();
}
subPair = mPairs;
while(subPair)
{
newPair = subPair->Duplicate(textPool);
newGroup->AddPair(newPair);
subPair = (CGPValue *)subPair->GetNext();
}
return newGroup;
}
void CGPGroup::SortObject(CGPObject *object, CGPObject **unsortedList, CGPObject **sortedList,
CGPObject **lastObject)
{
CGPObject *test, *last;
if (!*unsortedList)
{
*unsortedList = *sortedList = object;
}
else
{
(*lastObject)->SetNext(object);
test = *sortedList;
last = 0;
while(test)
{
if (strcmpi(object->GetName(), test->GetName()) < 0)
{
break;
}
last = test;
test = test->GetInOrderNext();
}
if (test)
{
test->SetInOrderPrevious(object);
object->SetInOrderNext(test);
}
if (last)
{
last->SetInOrderNext(object);
object->SetInOrderPrevious(last);
}
else
{
*sortedList = object;
}
}
*lastObject = object;
}
CGPValue *CGPGroup::AddPair(const char *name, const char *value, CTextPool **textPool)
{
CGPValue *newPair;
if (textPool)
{
name = (*textPool)->AllocText((char *)name, true, textPool);
if (value)
{
value = (*textPool)->AllocText((char *)value, true, textPool);
}
}
newPair = new CGPValue(name, value);
AddPair(newPair);
return newPair;
}
void CGPGroup::AddPair(CGPValue *NewPair)
{
SortObject(NewPair, (CGPObject **)&mPairs, (CGPObject **)&mInOrderPairs,
(CGPObject **)&mCurrentPair);
}
CGPGroup *CGPGroup::AddGroup(const char *name, CTextPool **textPool)
{
CGPGroup *newGroup;
if (textPool)
{
name = (*textPool)->AllocText((char *)name, true, textPool);
}
newGroup = new CGPGroup(name);
AddGroup(newGroup);
return newGroup;
}
void CGPGroup::AddGroup(CGPGroup *NewGroup)
{
SortObject(NewGroup, (CGPObject **)&mSubGroups, (CGPObject **)&mInOrderSubGroups,
(CGPObject **)&mCurrentSubGroup);
}
CGPGroup *CGPGroup::FindSubGroup(const char *name)
{
CGPGroup *group;
group = mSubGroups;
while(group)
{
if(!stricmp(name, group->GetName()))
{
return(group);
}
group = (CGPGroup *)group->GetNext();
}
return(NULL);
}
bool CGPGroup::Parse(char **dataPtr, CTextPool **textPool)
{
char *token;
char lastToken[MAX_TOKEN_SIZE];
CGPGroup *newSubGroup;
CGPValue *newPair;
while(1)
{
token = GetToken(dataPtr, true);
if (!token[0])
{ // end of data - error!
if (mParent)
{
return false;
}
else
{
break;
}
}
else if (strcmpi(token, "}") == 0)
{ // ending brace for this group
break;
}
strcpy(lastToken, token);
// read ahead to see what we are doing
token = GetToken(dataPtr, true, true);
if (strcmpi(token, "{") == 0)
{ // new sub group
newSubGroup = AddGroup(lastToken, textPool);
newSubGroup->SetWriteable(mWriteable);
if (!newSubGroup->Parse(dataPtr, textPool))
{
return false;
}
}
else if (strcmpi(token, "[") == 0)
{ // new pair list
newPair = AddPair(lastToken, 0, textPool);
if (!newPair->Parse(dataPtr, textPool))
{
return false;
}
}
else
{ // new pair
AddPair(lastToken, token, textPool);
}
}
return true;
}
bool CGPGroup::Write(CTextPool **textPool, int depth)
{
int i;
CGPValue *mPair = mPairs;
CGPGroup *mSubGroup = mSubGroups;
if (depth >= 0)
{
for(i=0;i<depth;i++)
{
(*textPool)->AllocText("\t", false, textPool);
}
WriteText(textPool, mName);
(*textPool)->AllocText("\r\n", false, textPool);
for(i=0;i<depth;i++)
{
(*textPool)->AllocText("\t", false, textPool);
}
(*textPool)->AllocText("{\r\n", false, textPool);
}
while(mPair)
{
mPair->Write(textPool, depth+1);
mPair = (CGPValue *)mPair->GetNext();
}
while(mSubGroup)
{
mSubGroup->Write(textPool, depth+1);
mSubGroup = (CGPGroup *)mSubGroup->GetNext();
}
if (depth >= 0)
{
for(i=0;i<depth;i++)
{
(*textPool)->AllocText("\t", false, textPool);
}
(*textPool)->AllocText("}\r\n", false, textPool);
}
return true;
}
CGPValue *CGPGroup::FindPair(const char *key)
{
CGPValue *pair = mPairs;
while(pair)
{
if (strcmpi(pair->GetName(), key) == 0)
{
return pair;
}
pair = pair->GetNext();
}
return 0;
}
const char *CGPGroup::FindPairValue(const char *key, const char *defaultVal)
{
CGPValue *pair = FindPair(key);
if (pair)
{
return pair->GetTopValue();
}
return defaultVal;
}
CGenericParser2::CGenericParser2(void) :
mTextPool(0),
mWriteable(false)
{
}
CGenericParser2::~CGenericParser2(void)
{
Clean();
}
bool CGenericParser2::Parse(char **dataPtr, bool cleanFirst, bool writeable)
{
CTextPool *topPool;
#ifdef _XBOX
// Parsers are temporary structures. They exist mainly at load time.
extern void Z_SetNewDeleteTemporary(bool bTemp);
Z_SetNewDeleteTemporary(true);
#endif
if (cleanFirst)
{
Clean();
}
if (!mTextPool)
{
mTextPool = new CTextPool;
}
SetWriteable(writeable);
mTopLevel.SetWriteable(writeable);
topPool = mTextPool;
bool ret = mTopLevel.Parse(dataPtr, &topPool);
#ifdef _XBOX
Z_SetNewDeleteTemporary(false);
#endif
return ret;
}
void CGenericParser2::Clean(void)
{
mTopLevel.Clean();
CleanTextPool(mTextPool);
mTextPool = 0;
}
bool CGenericParser2::Write(CTextPool *textPool)
{
return mTopLevel.Write(&textPool, -1);
}
// The following groups of routines are used for a C interface into GP2.
// C++ users should just use the objects as normally and not call these routines below
//
// CGenericParser2 (void *) routines
TGenericParser2 GP_Parse(char **dataPtr, bool cleanFirst, bool writeable)
{
CGenericParser2 *parse;
parse = new CGenericParser2;
if (parse->Parse(dataPtr, cleanFirst, writeable))
{
return parse;
}
delete parse;
return 0;
}
void GP_Clean(TGenericParser2 GP2)
{
if (!GP2)
{
return;
}
((CGenericParser2 *)GP2)->Clean();
}
void GP_Delete(TGenericParser2 *GP2)
{
if (!GP2 || !(*GP2))
{
return;
}
delete ((CGenericParser2 *)(*GP2));
(*GP2) = 0;
}
TGPGroup GP_GetBaseParseGroup(TGenericParser2 GP2)
{
if (!GP2)
{
return 0;
}
return ((CGenericParser2 *)GP2)->GetBaseParseGroup();
}
// CGPGroup (void *) routines
const char *GPG_GetName(TGPGroup GPG)
{
if (!GPG)
{
return "";
}
return ((CGPGroup *)GPG)->GetName();
}
TGPGroup GPG_GetNext(TGPGroup GPG)
{
if (!GPG)
{
return 0;
}
return ((CGPGroup *)GPG)->GetNext();
}
TGPGroup GPG_GetInOrderNext(TGPGroup GPG)
{
if (!GPG)
{
return 0;
}
return ((CGPGroup *)GPG)->GetInOrderNext();
}
TGPGroup GPG_GetInOrderPrevious(TGPGroup GPG)
{
if (!GPG)
{
return 0;
}
return ((CGPGroup *)GPG)->GetInOrderPrevious();
}
TGPGroup GPG_GetPairs(TGPGroup GPG)
{
if (!GPG)
{
return 0;
}
return ((CGPGroup *)GPG)->GetPairs();
}
TGPGroup GPG_GetInOrderPairs(TGPGroup GPG)
{
if (!GPG)
{
return 0;
}
return ((CGPGroup *)GPG)->GetInOrderPairs();
}
TGPGroup GPG_GetSubGroups(TGPGroup GPG)
{
if (!GPG)
{
return 0;
}
return ((CGPGroup *)GPG)->GetSubGroups();
}
TGPGroup GPG_GetInOrderSubGroups(TGPGroup GPG)
{
if (!GPG)
{
return 0;
}
return ((CGPGroup *)GPG)->GetInOrderSubGroups();
}
TGPGroup GPG_FindSubGroup(TGPGroup GPG, const char *name)
{
if (!GPG)
{
return 0;
}
return ((CGPGroup *)GPG)->FindSubGroup(name);
}
TGPValue GPG_FindPair(TGPGroup GPG, const char *key)
{
if (!GPG)
{
return 0;
}
return ((CGPGroup *)GPG)->FindPair(key);
}
const char *GPG_FindPairValue(TGPGroup GPG, const char *key, const char *defaultVal)
{
if (!GPG)
{
return defaultVal;
}
return ((CGPGroup *)GPG)->FindPairValue(key, defaultVal);
}
// CGPValue (void *) routines
const char *GPV_GetName(TGPValue GPV)
{
if (!GPV)
{
return "";
}
return ((CGPValue *)GPV)->GetName();
}
TGPValue GPV_GetNext(TGPValue GPV)
{
if (!GPV)
{
return 0;
}
return ((CGPValue *)GPV)->GetNext();
}
TGPValue GPV_GetInOrderNext(TGPValue GPV)
{
if (!GPV)
{
return 0;
}
return ((CGPValue *)GPV)->GetInOrderNext();
}
TGPValue GPV_GetInOrderPrevious(TGPValue GPV)
{
if (!GPV)
{
return 0;
}
return ((CGPValue *)GPV)->GetInOrderPrevious();
}
bool GPV_IsList(TGPValue GPV)
{
if (!GPV)
{
return 0;
}
return ((CGPValue *)GPV)->IsList();
}
const char *GPV_GetTopValue(TGPValue GPV)
{
if (!GPV)
{
return "";
}
return ((CGPValue *)GPV)->GetTopValue();
}
TGPValue GPV_GetList(TGPValue GPV)
{
if (!GPV)
{
return 0;
}
return ((CGPValue *)GPV)->GetList();
}
//////////////////// eof /////////////////////
| 1 | 0.942002 | 1 | 0.942002 | game-dev | MEDIA | 0.204288 | game-dev | 0.936717 | 1 | 0.936717 |
kteong1012/LubanEditor | 36,680 | Unity/Assets/GameScript/Editor/ConfigEditor/Models/test/TestRef.cs |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System.Collections.Generic;
using SimpleJSON;
using Luban;
using UnityEngine;
using System.Linq;
using System;
namespace editor.cfg.test
{
public sealed class TestRef : Luban.EditorBeanBase
{
public TestRef()
{
a1 = System.Array.Empty<int>();
a2 = System.Array.Empty<int>();
b1 = new System.Collections.Generic.List<int>();
b2 = new System.Collections.Generic.List<int>();
c1 = new System.Collections.Generic.List<int>();
c2 = new System.Collections.Generic.List<int>();
d1 = new System.Collections.Generic.List<object[]>();
d2 = new System.Collections.Generic.List<object[]>();
e3 = "";
f3 = "";
}
public override void LoadJson(SimpleJSON.JSONObject _json)
{
{
var _fieldJson = _json["id"];
if (_fieldJson != null)
{
if(!_fieldJson.IsNumber) { throw new SerializationException(); } id = _fieldJson;
}
else
{
id = 0;
}
}
{
var _fieldJson = _json["x1"];
if (_fieldJson != null)
{
if(!_fieldJson.IsNumber) { throw new SerializationException(); } x1 = _fieldJson;
}
else
{
x1 = 0;
}
}
{
var _fieldJson = _json["x1_2"];
if (_fieldJson != null)
{
if(!_fieldJson.IsNumber) { throw new SerializationException(); } x12 = _fieldJson;
}
else
{
x12 = 0;
}
}
{
var _fieldJson = _json["x2"];
if (_fieldJson != null)
{
if(!_fieldJson.IsNumber) { throw new SerializationException(); } x2 = _fieldJson;
}
else
{
x2 = 0;
}
}
{
var _fieldJson = _json["x3"];
if (_fieldJson != null)
{
if(!_fieldJson.IsNumber) { throw new SerializationException(); } x3 = _fieldJson;
}
else
{
x3 = 0;
}
}
{
var _fieldJson = _json["x4"];
if (_fieldJson != null)
{
if(!_fieldJson.IsNumber) { throw new SerializationException(); } x4 = _fieldJson;
}
else
{
x4 = 0;
}
}
{
var _fieldJson = _json["a1"];
if (_fieldJson != null)
{
if(!_fieldJson.IsArray) { throw new SerializationException(); } int __n0 = _fieldJson.Count; a1 = new int[__n0]; int __i0=0; foreach(SimpleJSON.JSONNode __e0 in _fieldJson.Children) { int __v0; if(!__e0.IsNumber) { throw new SerializationException(); } __v0 = __e0; a1[__i0++] = __v0; }
}
else
{
a1 = System.Array.Empty<int>();
}
}
{
var _fieldJson = _json["a2"];
if (_fieldJson != null)
{
if(!_fieldJson.IsArray) { throw new SerializationException(); } int __n0 = _fieldJson.Count; a2 = new int[__n0]; int __i0=0; foreach(SimpleJSON.JSONNode __e0 in _fieldJson.Children) { int __v0; if(!__e0.IsNumber) { throw new SerializationException(); } __v0 = __e0; a2[__i0++] = __v0; }
}
else
{
a2 = System.Array.Empty<int>();
}
}
{
var _fieldJson = _json["b1"];
if (_fieldJson != null)
{
if(!_fieldJson.IsArray) { throw new SerializationException(); } b1 = new System.Collections.Generic.List<int>(); foreach(SimpleJSON.JSONNode __e0 in _fieldJson.Children) { int __v0; if(!__e0.IsNumber) { throw new SerializationException(); } __v0 = __e0; b1.Add(__v0); }
}
else
{
b1 = new System.Collections.Generic.List<int>();
}
}
{
var _fieldJson = _json["b2"];
if (_fieldJson != null)
{
if(!_fieldJson.IsArray) { throw new SerializationException(); } b2 = new System.Collections.Generic.List<int>(); foreach(SimpleJSON.JSONNode __e0 in _fieldJson.Children) { int __v0; if(!__e0.IsNumber) { throw new SerializationException(); } __v0 = __e0; b2.Add(__v0); }
}
else
{
b2 = new System.Collections.Generic.List<int>();
}
}
{
var _fieldJson = _json["c1"];
if (_fieldJson != null)
{
if(!_fieldJson.IsArray) { throw new SerializationException(); } c1 = new System.Collections.Generic.List<int>(); foreach(SimpleJSON.JSONNode __e0 in _fieldJson.Children) { int __v0; if(!__e0.IsNumber) { throw new SerializationException(); } __v0 = __e0; c1.Add(__v0); }
}
else
{
c1 = new System.Collections.Generic.List<int>();
}
}
{
var _fieldJson = _json["c2"];
if (_fieldJson != null)
{
if(!_fieldJson.IsArray) { throw new SerializationException(); } c2 = new System.Collections.Generic.List<int>(); foreach(SimpleJSON.JSONNode __e0 in _fieldJson.Children) { int __v0; if(!__e0.IsNumber) { throw new SerializationException(); } __v0 = __e0; c2.Add(__v0); }
}
else
{
c2 = new System.Collections.Generic.List<int>();
}
}
{
var _fieldJson = _json["d1"];
if (_fieldJson != null)
{
if(!_fieldJson.IsArray) { throw new SerializationException(); } d1 = new System.Collections.Generic.List<object[]>(); foreach(SimpleJSON.JSONNode __e0 in _fieldJson.Children) { int __k0; if(!__e0[0].IsNumber) { throw new SerializationException(); } __k0 = __e0[0]; int __v0; if(!__e0[1].IsNumber) { throw new SerializationException(); } __v0 = __e0[1]; d1.Add(new object[] { __k0, __v0 }); }
}
else
{
d1 = new System.Collections.Generic.List<object[]>();
}
}
{
var _fieldJson = _json["d2"];
if (_fieldJson != null)
{
if(!_fieldJson.IsArray) { throw new SerializationException(); } d2 = new System.Collections.Generic.List<object[]>(); foreach(SimpleJSON.JSONNode __e0 in _fieldJson.Children) { int __k0; if(!__e0[0].IsNumber) { throw new SerializationException(); } __k0 = __e0[0]; int __v0; if(!__e0[1].IsNumber) { throw new SerializationException(); } __v0 = __e0[1]; d2.Add(new object[] { __k0, __v0 }); }
}
else
{
d2 = new System.Collections.Generic.List<object[]>();
}
}
{
var _fieldJson = _json["e1"];
if (_fieldJson != null)
{
if(!_fieldJson.IsNumber) { throw new SerializationException(); } e1 = _fieldJson;
}
else
{
e1 = 0;
}
}
{
var _fieldJson = _json["e2"];
if (_fieldJson != null)
{
if(!_fieldJson.IsNumber) { throw new SerializationException(); } e2 = _fieldJson;
}
else
{
e2 = 0;
}
}
{
var _fieldJson = _json["e3"];
if (_fieldJson != null)
{
if(!_fieldJson.IsString) { throw new SerializationException(); } e3 = _fieldJson;
}
else
{
e3 = "";
}
}
{
var _fieldJson = _json["f1"];
if (_fieldJson != null)
{
if(!_fieldJson.IsNumber) { throw new SerializationException(); } f1 = _fieldJson;
}
else
{
f1 = 0;
}
}
{
var _fieldJson = _json["f2"];
if (_fieldJson != null)
{
if(!_fieldJson.IsNumber) { throw new SerializationException(); } f2 = _fieldJson;
}
else
{
f2 = 0;
}
}
{
var _fieldJson = _json["f3"];
if (_fieldJson != null)
{
if(!_fieldJson.IsString) { throw new SerializationException(); } f3 = _fieldJson;
}
else
{
f3 = "";
}
}
{
var _fieldJson = _json["s1"];
if (_fieldJson != null)
{
if (!_fieldJson.IsObject)
{
throw new SerializationException();
}
s1 = editor.cfg.test.RefDynamicBase.LoadJsonRefDynamicBase(_fieldJson);
}
else
{
s1 = test.RefDynamicBase.Create("RefBean");
}
}
}
public override void SaveJson(SimpleJSON.JSONObject _json)
{
{
_json["id"] = new JSONNumber(id);
}
{
_json["x1"] = new JSONNumber(x1);
}
{
_json["x1_2"] = new JSONNumber(x12);
}
{
_json["x2"] = new JSONNumber(x2);
}
{
_json["x3"] = new JSONNumber(x3);
}
{
_json["x4"] = new JSONNumber(x4);
}
if (a1 != null)
{
{ var __cjson0 = new JSONArray(); foreach(var __e0 in a1) { __cjson0["null"] = new JSONNumber(__e0); } __cjson0.Inline = __cjson0.Count == 0; _json["a1"] = __cjson0; }
}
if (a2 != null)
{
{ var __cjson0 = new JSONArray(); foreach(var __e0 in a2) { __cjson0["null"] = new JSONNumber(__e0); } __cjson0.Inline = __cjson0.Count == 0; _json["a2"] = __cjson0; }
}
if (b1 != null)
{
{ var __cjson0 = new JSONArray(); foreach(var __e0 in b1) { __cjson0["null"] = new JSONNumber(__e0); } __cjson0.Inline = __cjson0.Count == 0; _json["b1"] = __cjson0; }
}
if (b2 != null)
{
{ var __cjson0 = new JSONArray(); foreach(var __e0 in b2) { __cjson0["null"] = new JSONNumber(__e0); } __cjson0.Inline = __cjson0.Count == 0; _json["b2"] = __cjson0; }
}
if (c1 != null)
{
{ var __cjson0 = new JSONArray(); foreach(var __e0 in c1) { __cjson0["null"] = new JSONNumber(__e0); } __cjson0.Inline = __cjson0.Count == 0; _json["c1"] = __cjson0; }
}
if (c2 != null)
{
{ var __cjson0 = new JSONArray(); foreach(var __e0 in c2) { __cjson0["null"] = new JSONNumber(__e0); } __cjson0.Inline = __cjson0.Count == 0; _json["c2"] = __cjson0; }
}
if (d1 != null)
{
{
var __cjson0 = new JSONArray();
foreach(var __e0 in d1)
{
var __entry0 = new JSONArray();
__cjson0[null] = __entry0;
__entry0["null"] = new JSONNumber((int)__e0[0]);
__entry0["null"] = new JSONNumber((int)__e0[1]);
}
__cjson0.Inline = __cjson0.Count == 0;
_json["d1"] = __cjson0;
}
}
if (d2 != null)
{
{
var __cjson0 = new JSONArray();
foreach(var __e0 in d2)
{
var __entry0 = new JSONArray();
__cjson0[null] = __entry0;
__entry0["null"] = new JSONNumber((int)__e0[0]);
__entry0["null"] = new JSONNumber((int)__e0[1]);
}
__cjson0.Inline = __cjson0.Count == 0;
_json["d2"] = __cjson0;
}
}
{
_json["e1"] = new JSONNumber(e1);
}
{
_json["e2"] = new JSONNumber(e2);
}
if (e3 != null)
{
_json["e3"] = new JSONString(e3);
}
{
_json["f1"] = new JSONNumber(f1);
}
{
_json["f2"] = new JSONNumber(f2);
}
if (f3 != null)
{
_json["f3"] = new JSONString(f3);
}
if (s1 != null)
{
{ var __bjson = new JSONObject(); editor.cfg.test.RefDynamicBase.SaveJsonRefDynamicBase(s1, __bjson); _json["s1"] = __bjson; }
}
}
private static GUIStyle _areaStyle = new GUIStyle(GUI.skin.button);
public static void RenderTestRef(TestRef obj)
{
obj.Render();
}
public override void Render()
{
{
UnityEditor.EditorGUILayout.BeginVertical(_areaStyle);UnityEditor.EditorGUILayout.BeginHorizontal();
if (ConfigEditorSettings.showComment)
{
UnityEditor.EditorGUILayout.LabelField(new UnityEngine.GUIContent("id", "id"), GUILayout.Width(100));
}
else
{
UnityEditor.EditorGUILayout.LabelField(new UnityEngine.GUIContent("id", ""), GUILayout.Width(100));
}
this.id = UnityEditor.EditorGUILayout.IntField(this.id, GUILayout.Width(150));
UnityEditor.EditorGUILayout.EndHorizontal();UnityEditor.EditorGUILayout.BeginHorizontal();
if (ConfigEditorSettings.showComment)
{
UnityEditor.EditorGUILayout.LabelField(new UnityEngine.GUIContent("x1", "x1"), GUILayout.Width(100));
}
else
{
UnityEditor.EditorGUILayout.LabelField(new UnityEngine.GUIContent("x1", ""), GUILayout.Width(100));
}
this.x1 = UnityEditor.EditorGUILayout.IntField(this.x1, GUILayout.Width(150));
UnityEditor.EditorGUILayout.EndHorizontal();UnityEditor.EditorGUILayout.BeginHorizontal();
if (ConfigEditorSettings.showComment)
{
UnityEditor.EditorGUILayout.LabelField(new UnityEngine.GUIContent("x1_2", "x1_2"), GUILayout.Width(100));
}
else
{
UnityEditor.EditorGUILayout.LabelField(new UnityEngine.GUIContent("x1_2", ""), GUILayout.Width(100));
}
this.x12 = UnityEditor.EditorGUILayout.IntField(this.x12, GUILayout.Width(150));
UnityEditor.EditorGUILayout.EndHorizontal();UnityEditor.EditorGUILayout.BeginHorizontal();
if (ConfigEditorSettings.showComment)
{
UnityEditor.EditorGUILayout.LabelField(new UnityEngine.GUIContent("x2", "x2"), GUILayout.Width(100));
}
else
{
UnityEditor.EditorGUILayout.LabelField(new UnityEngine.GUIContent("x2", ""), GUILayout.Width(100));
}
this.x2 = UnityEditor.EditorGUILayout.IntField(this.x2, GUILayout.Width(150));
UnityEditor.EditorGUILayout.EndHorizontal();UnityEditor.EditorGUILayout.BeginHorizontal();
if (ConfigEditorSettings.showComment)
{
UnityEditor.EditorGUILayout.LabelField(new UnityEngine.GUIContent("x3", "x3"), GUILayout.Width(100));
}
else
{
UnityEditor.EditorGUILayout.LabelField(new UnityEngine.GUIContent("x3", ""), GUILayout.Width(100));
}
this.x3 = UnityEditor.EditorGUILayout.IntField(this.x3, GUILayout.Width(150));
UnityEditor.EditorGUILayout.EndHorizontal();UnityEditor.EditorGUILayout.BeginHorizontal();
if (ConfigEditorSettings.showComment)
{
UnityEditor.EditorGUILayout.LabelField(new UnityEngine.GUIContent("x4", "x4"), GUILayout.Width(100));
}
else
{
UnityEditor.EditorGUILayout.LabelField(new UnityEngine.GUIContent("x4", ""), GUILayout.Width(100));
}
this.x4 = UnityEditor.EditorGUILayout.IntField(this.x4, GUILayout.Width(150));
UnityEditor.EditorGUILayout.EndHorizontal();UnityEditor.EditorGUILayout.BeginHorizontal();
if (ConfigEditorSettings.showComment)
{
UnityEditor.EditorGUILayout.LabelField(new UnityEngine.GUIContent("a1", "a1"), GUILayout.Width(100));
}
else
{
UnityEditor.EditorGUILayout.LabelField(new UnityEngine.GUIContent("a1", ""), GUILayout.Width(100));
}
{
UnityEditor.EditorGUILayout.BeginVertical(_areaStyle);
int __n1 = this.a1.Length;
UnityEditor.EditorGUILayout.LabelField("长度: " + __n1.ToString());
for (int __i1 = 0; __i1 < __n1; __i1++)
{
UnityEditor.EditorGUILayout.BeginHorizontal();
if (GUILayout.Button("-", GUILayout.Width(20)))
{
var __list1 = new System.Collections.Generic.List<int>(this.a1);
__list1.RemoveAt(__i1);
this.a1 = __list1.ToArray();
UnityEditor.EditorGUILayout.EndHorizontal();
break;
}
UnityEditor.EditorGUILayout.LabelField(__i1.ToString(), GUILayout.Width(20));
int __e1 = this.a1[__i1];
__e1 = UnityEditor.EditorGUILayout.IntField(__e1, GUILayout.Width(150));;
this.a1[__i1] = __e1;
UnityEditor.EditorGUILayout.EndHorizontal();
}
UnityEditor.EditorGUILayout.BeginHorizontal();
if (GUILayout.Button("+", GUILayout.Width(20)))
{
var __list1 = new System.Collections.Generic.List<int>(this.a1);
int __e1;
__e1 = 0;;
__list1.Add(__e1);
this.a1 = __list1.ToArray();
}
if (ConfigEditorSettings.showImportButton && GUILayout.Button("import", GUILayout.Width(100)))
{
ConfigEditorImportWindow.Open((__importJsonText1) =>
{
var __importJson1 = SimpleJSON.JSON.Parse(__importJsonText1);
int __importElement1;
if(!__importJson1.IsNumber) { throw new SerializationException(); } __importElement1 = __importJson1;
var __list1 = new System.Collections.Generic.List<int>(this.a1);
__list1.Add(__importElement1);
this.a1 = __list1.ToArray();
});
}
UnityEditor.EditorGUILayout.EndHorizontal();
UnityEditor.EditorGUILayout.EndVertical();
}
UnityEditor.EditorGUILayout.EndHorizontal();UnityEditor.EditorGUILayout.BeginHorizontal();
if (ConfigEditorSettings.showComment)
{
UnityEditor.EditorGUILayout.LabelField(new UnityEngine.GUIContent("a2", "a2"), GUILayout.Width(100));
}
else
{
UnityEditor.EditorGUILayout.LabelField(new UnityEngine.GUIContent("a2", ""), GUILayout.Width(100));
}
{
UnityEditor.EditorGUILayout.BeginVertical(_areaStyle);
int __n1 = this.a2.Length;
UnityEditor.EditorGUILayout.LabelField("长度: " + __n1.ToString());
for (int __i1 = 0; __i1 < __n1; __i1++)
{
UnityEditor.EditorGUILayout.BeginHorizontal();
if (GUILayout.Button("-", GUILayout.Width(20)))
{
var __list1 = new System.Collections.Generic.List<int>(this.a2);
__list1.RemoveAt(__i1);
this.a2 = __list1.ToArray();
UnityEditor.EditorGUILayout.EndHorizontal();
break;
}
UnityEditor.EditorGUILayout.LabelField(__i1.ToString(), GUILayout.Width(20));
int __e1 = this.a2[__i1];
__e1 = UnityEditor.EditorGUILayout.IntField(__e1, GUILayout.Width(150));;
this.a2[__i1] = __e1;
UnityEditor.EditorGUILayout.EndHorizontal();
}
UnityEditor.EditorGUILayout.BeginHorizontal();
if (GUILayout.Button("+", GUILayout.Width(20)))
{
var __list1 = new System.Collections.Generic.List<int>(this.a2);
int __e1;
__e1 = 0;;
__list1.Add(__e1);
this.a2 = __list1.ToArray();
}
if (ConfigEditorSettings.showImportButton && GUILayout.Button("import", GUILayout.Width(100)))
{
ConfigEditorImportWindow.Open((__importJsonText1) =>
{
var __importJson1 = SimpleJSON.JSON.Parse(__importJsonText1);
int __importElement1;
if(!__importJson1.IsNumber) { throw new SerializationException(); } __importElement1 = __importJson1;
var __list1 = new System.Collections.Generic.List<int>(this.a2);
__list1.Add(__importElement1);
this.a2 = __list1.ToArray();
});
}
UnityEditor.EditorGUILayout.EndHorizontal();
UnityEditor.EditorGUILayout.EndVertical();
}
UnityEditor.EditorGUILayout.EndHorizontal();UnityEditor.EditorGUILayout.BeginHorizontal();
if (ConfigEditorSettings.showComment)
{
UnityEditor.EditorGUILayout.LabelField(new UnityEngine.GUIContent("b1", "b1"), GUILayout.Width(100));
}
else
{
UnityEditor.EditorGUILayout.LabelField(new UnityEngine.GUIContent("b1", ""), GUILayout.Width(100));
}
{
UnityEditor.EditorGUILayout.BeginVertical(_areaStyle);
int __n1 = this.b1.Count;
UnityEditor.EditorGUILayout.LabelField("长度: " + __n1.ToString());
for (int __i1 = 0; __i1 < __n1; __i1++)
{
UnityEditor.EditorGUILayout.BeginHorizontal();
if (GUILayout.Button("-", GUILayout.Width(20)))
{
this.b1.RemoveAt(__i1);
UnityEditor.EditorGUILayout.EndHorizontal();
break;
}
UnityEditor.EditorGUILayout.LabelField(__i1.ToString(), GUILayout.Width(20));
int __e1 = this.b1[__i1];
__e1 = UnityEditor.EditorGUILayout.IntField(__e1, GUILayout.Width(150));;
this.b1[__i1] = __e1;
UnityEditor.EditorGUILayout.EndHorizontal();
}
UnityEditor.EditorGUILayout.BeginHorizontal();
if (GUILayout.Button("+", GUILayout.Width(20)))
{
int __e1;
__e1 = 0;;
this.b1.Add(__e1);
}
if (ConfigEditorSettings.showImportButton && GUILayout.Button("import", GUILayout.Width(100)))
{
ConfigEditorImportWindow.Open((__importJsonText1) =>
{
var __importJson1 = SimpleJSON.JSON.Parse(__importJsonText1);
int __importElement1;
if(!__importJson1.IsNumber) { throw new SerializationException(); } __importElement1 = __importJson1;
this.b1.Add(__importElement1);
});
}
UnityEditor.EditorGUILayout.EndHorizontal();
UnityEditor.EditorGUILayout.EndVertical();
}
UnityEditor.EditorGUILayout.EndHorizontal();UnityEditor.EditorGUILayout.BeginHorizontal();
if (ConfigEditorSettings.showComment)
{
UnityEditor.EditorGUILayout.LabelField(new UnityEngine.GUIContent("b2", "b2"), GUILayout.Width(100));
}
else
{
UnityEditor.EditorGUILayout.LabelField(new UnityEngine.GUIContent("b2", ""), GUILayout.Width(100));
}
{
UnityEditor.EditorGUILayout.BeginVertical(_areaStyle);
int __n1 = this.b2.Count;
UnityEditor.EditorGUILayout.LabelField("长度: " + __n1.ToString());
for (int __i1 = 0; __i1 < __n1; __i1++)
{
UnityEditor.EditorGUILayout.BeginHorizontal();
if (GUILayout.Button("-", GUILayout.Width(20)))
{
this.b2.RemoveAt(__i1);
UnityEditor.EditorGUILayout.EndHorizontal();
break;
}
UnityEditor.EditorGUILayout.LabelField(__i1.ToString(), GUILayout.Width(20));
int __e1 = this.b2[__i1];
__e1 = UnityEditor.EditorGUILayout.IntField(__e1, GUILayout.Width(150));;
this.b2[__i1] = __e1;
UnityEditor.EditorGUILayout.EndHorizontal();
}
UnityEditor.EditorGUILayout.BeginHorizontal();
if (GUILayout.Button("+", GUILayout.Width(20)))
{
int __e1;
__e1 = 0;;
this.b2.Add(__e1);
}
if (ConfigEditorSettings.showImportButton && GUILayout.Button("import", GUILayout.Width(100)))
{
ConfigEditorImportWindow.Open((__importJsonText1) =>
{
var __importJson1 = SimpleJSON.JSON.Parse(__importJsonText1);
int __importElement1;
if(!__importJson1.IsNumber) { throw new SerializationException(); } __importElement1 = __importJson1;
this.b2.Add(__importElement1);
});
}
UnityEditor.EditorGUILayout.EndHorizontal();
UnityEditor.EditorGUILayout.EndVertical();
}
UnityEditor.EditorGUILayout.EndHorizontal();UnityEditor.EditorGUILayout.BeginHorizontal();
if (ConfigEditorSettings.showComment)
{
UnityEditor.EditorGUILayout.LabelField(new UnityEngine.GUIContent("c1", "c1"), GUILayout.Width(100));
}
else
{
UnityEditor.EditorGUILayout.LabelField(new UnityEngine.GUIContent("c1", ""), GUILayout.Width(100));
}
{
UnityEditor.EditorGUILayout.BeginVertical(_areaStyle);
int __n1 = this.c1.Count;
UnityEditor.EditorGUILayout.LabelField("长度: " + __n1.ToString());
for (int __i1 = 0; __i1 < __n1; __i1++)
{
UnityEditor.EditorGUILayout.BeginHorizontal();
if (GUILayout.Button("-", GUILayout.Width(20)))
{
this.c1.RemoveAt(__i1);
UnityEditor.EditorGUILayout.EndHorizontal();
break;
}
UnityEditor.EditorGUILayout.LabelField(__i1.ToString(), GUILayout.Width(20));
int __e1 = this.c1[__i1];
__e1 = UnityEditor.EditorGUILayout.IntField(__e1, GUILayout.Width(150));;
this.c1[__i1] = __e1;
UnityEditor.EditorGUILayout.EndHorizontal();
}
UnityEditor.EditorGUILayout.BeginHorizontal();
if (GUILayout.Button("+", GUILayout.Width(20)))
{
int __e1;
__e1 = 0;;
this.c1.Add(__e1);
}
if (ConfigEditorSettings.showImportButton && GUILayout.Button("import", GUILayout.Width(100)))
{
ConfigEditorImportWindow.Open((__importJsonText1) =>
{
var __importJson1 = SimpleJSON.JSON.Parse(__importJsonText1);
int __importElement1;
if(!__importJson1.IsNumber) { throw new SerializationException(); } __importElement1 = __importJson1;
this.c1.Add(__importElement1);
});
}
UnityEditor.EditorGUILayout.EndHorizontal();
UnityEditor.EditorGUILayout.EndVertical();
}
UnityEditor.EditorGUILayout.EndHorizontal();UnityEditor.EditorGUILayout.BeginHorizontal();
if (ConfigEditorSettings.showComment)
{
UnityEditor.EditorGUILayout.LabelField(new UnityEngine.GUIContent("c2", "c2"), GUILayout.Width(100));
}
else
{
UnityEditor.EditorGUILayout.LabelField(new UnityEngine.GUIContent("c2", ""), GUILayout.Width(100));
}
{
UnityEditor.EditorGUILayout.BeginVertical(_areaStyle);
int __n1 = this.c2.Count;
UnityEditor.EditorGUILayout.LabelField("长度: " + __n1.ToString());
for (int __i1 = 0; __i1 < __n1; __i1++)
{
UnityEditor.EditorGUILayout.BeginHorizontal();
if (GUILayout.Button("-", GUILayout.Width(20)))
{
this.c2.RemoveAt(__i1);
UnityEditor.EditorGUILayout.EndHorizontal();
break;
}
UnityEditor.EditorGUILayout.LabelField(__i1.ToString(), GUILayout.Width(20));
int __e1 = this.c2[__i1];
__e1 = UnityEditor.EditorGUILayout.IntField(__e1, GUILayout.Width(150));;
this.c2[__i1] = __e1;
UnityEditor.EditorGUILayout.EndHorizontal();
}
UnityEditor.EditorGUILayout.BeginHorizontal();
if (GUILayout.Button("+", GUILayout.Width(20)))
{
int __e1;
__e1 = 0;;
this.c2.Add(__e1);
}
if (ConfigEditorSettings.showImportButton && GUILayout.Button("import", GUILayout.Width(100)))
{
ConfigEditorImportWindow.Open((__importJsonText1) =>
{
var __importJson1 = SimpleJSON.JSON.Parse(__importJsonText1);
int __importElement1;
if(!__importJson1.IsNumber) { throw new SerializationException(); } __importElement1 = __importJson1;
this.c2.Add(__importElement1);
});
}
UnityEditor.EditorGUILayout.EndHorizontal();
UnityEditor.EditorGUILayout.EndVertical();
}
UnityEditor.EditorGUILayout.EndHorizontal();UnityEditor.EditorGUILayout.BeginHorizontal();
if (ConfigEditorSettings.showComment)
{
UnityEditor.EditorGUILayout.LabelField(new UnityEngine.GUIContent("d1", "d1"), GUILayout.Width(100));
}
else
{
UnityEditor.EditorGUILayout.LabelField(new UnityEngine.GUIContent("d1", ""), GUILayout.Width(100));
}
{
UnityEditor.EditorGUILayout.BeginVertical(_areaStyle);
int __n1 = this.d1.Count;
UnityEditor.EditorGUILayout.LabelField("长度: " + __n1.ToString());
for (int __i1 = 0; __i1 < __n1; __i1++)
{
UnityEditor.EditorGUILayout.BeginHorizontal();
if (GUILayout.Button("-", GUILayout.Width(20)))
{
this.d1.RemoveAt(__i1);
UnityEditor.EditorGUILayout.EndHorizontal();
break;
}
UnityEditor.EditorGUILayout.LabelField(__i1.ToString(), GUILayout.Width(20));
var __e1 = this.d1[__i1];
int __key1 = 0;
int __value1 = 0;
if (__e1 == null)
{
__e1 = new object[2] { __key1, __value1 };
this.d1[__i1] = __e1;
}
else
{
__key1 = __e1[0] != null ? (int)__e1[0] : default;
__value1 = __e1[1] != null ? (int)__e1[1] : default;
}
__key1 = UnityEditor.EditorGUILayout.IntField(__key1, GUILayout.Width(150));;
__value1 = UnityEditor.EditorGUILayout.IntField(__value1, GUILayout.Width(150));;
__e1[0] = __key1;
__e1[1] = __value1;
UnityEditor.EditorGUILayout.EndHorizontal();
}
if (GUILayout.Button("+", GUILayout.Width(20)))
{
this.d1.Add(new object[2]);
}
UnityEditor.EditorGUILayout.EndVertical();
}
UnityEditor.EditorGUILayout.EndHorizontal();UnityEditor.EditorGUILayout.BeginHorizontal();
if (ConfigEditorSettings.showComment)
{
UnityEditor.EditorGUILayout.LabelField(new UnityEngine.GUIContent("d2", "d2"), GUILayout.Width(100));
}
else
{
UnityEditor.EditorGUILayout.LabelField(new UnityEngine.GUIContent("d2", ""), GUILayout.Width(100));
}
{
UnityEditor.EditorGUILayout.BeginVertical(_areaStyle);
int __n1 = this.d2.Count;
UnityEditor.EditorGUILayout.LabelField("长度: " + __n1.ToString());
for (int __i1 = 0; __i1 < __n1; __i1++)
{
UnityEditor.EditorGUILayout.BeginHorizontal();
if (GUILayout.Button("-", GUILayout.Width(20)))
{
this.d2.RemoveAt(__i1);
UnityEditor.EditorGUILayout.EndHorizontal();
break;
}
UnityEditor.EditorGUILayout.LabelField(__i1.ToString(), GUILayout.Width(20));
var __e1 = this.d2[__i1];
int __key1 = 0;
int __value1 = 0;
if (__e1 == null)
{
__e1 = new object[2] { __key1, __value1 };
this.d2[__i1] = __e1;
}
else
{
__key1 = __e1[0] != null ? (int)__e1[0] : default;
__value1 = __e1[1] != null ? (int)__e1[1] : default;
}
__key1 = UnityEditor.EditorGUILayout.IntField(__key1, GUILayout.Width(150));;
__value1 = UnityEditor.EditorGUILayout.IntField(__value1, GUILayout.Width(150));;
__e1[0] = __key1;
__e1[1] = __value1;
UnityEditor.EditorGUILayout.EndHorizontal();
}
if (GUILayout.Button("+", GUILayout.Width(20)))
{
this.d2.Add(new object[2]);
}
UnityEditor.EditorGUILayout.EndVertical();
}
UnityEditor.EditorGUILayout.EndHorizontal();UnityEditor.EditorGUILayout.BeginHorizontal();
if (ConfigEditorSettings.showComment)
{
UnityEditor.EditorGUILayout.LabelField(new UnityEngine.GUIContent("e1", "e1"), GUILayout.Width(100));
}
else
{
UnityEditor.EditorGUILayout.LabelField(new UnityEngine.GUIContent("e1", ""), GUILayout.Width(100));
}
this.e1 = UnityEditor.EditorGUILayout.IntField(this.e1, GUILayout.Width(150));
UnityEditor.EditorGUILayout.EndHorizontal();UnityEditor.EditorGUILayout.BeginHorizontal();
if (ConfigEditorSettings.showComment)
{
UnityEditor.EditorGUILayout.LabelField(new UnityEngine.GUIContent("e2", "e2"), GUILayout.Width(100));
}
else
{
UnityEditor.EditorGUILayout.LabelField(new UnityEngine.GUIContent("e2", ""), GUILayout.Width(100));
}
this.e2 = UnityEditor.EditorGUILayout.LongField(this.e2, GUILayout.Width(150));
UnityEditor.EditorGUILayout.EndHorizontal();UnityEditor.EditorGUILayout.BeginHorizontal();
if (ConfigEditorSettings.showComment)
{
UnityEditor.EditorGUILayout.LabelField(new UnityEngine.GUIContent("e3", "e3"), GUILayout.Width(100));
}
else
{
UnityEditor.EditorGUILayout.LabelField(new UnityEngine.GUIContent("e3", ""), GUILayout.Width(100));
}
this.e3 = UnityEditor.EditorGUILayout.TextField(this.e3, GUILayout.Width(150));
if (GUILayout.Button("…", GUILayout.Width(20)))
{
TextInputWindow.GetTextAsync(this.e3,__x =>this.e3 = __x);
}
UnityEditor.EditorGUILayout.EndHorizontal();UnityEditor.EditorGUILayout.BeginHorizontal();
if (ConfigEditorSettings.showComment)
{
UnityEditor.EditorGUILayout.LabelField(new UnityEngine.GUIContent("f1", "f1"), GUILayout.Width(100));
}
else
{
UnityEditor.EditorGUILayout.LabelField(new UnityEngine.GUIContent("f1", ""), GUILayout.Width(100));
}
this.f1 = UnityEditor.EditorGUILayout.IntField(this.f1, GUILayout.Width(150));
UnityEditor.EditorGUILayout.EndHorizontal();UnityEditor.EditorGUILayout.BeginHorizontal();
if (ConfigEditorSettings.showComment)
{
UnityEditor.EditorGUILayout.LabelField(new UnityEngine.GUIContent("f2", "f2"), GUILayout.Width(100));
}
else
{
UnityEditor.EditorGUILayout.LabelField(new UnityEngine.GUIContent("f2", ""), GUILayout.Width(100));
}
this.f2 = UnityEditor.EditorGUILayout.LongField(this.f2, GUILayout.Width(150));
UnityEditor.EditorGUILayout.EndHorizontal();UnityEditor.EditorGUILayout.BeginHorizontal();
if (ConfigEditorSettings.showComment)
{
UnityEditor.EditorGUILayout.LabelField(new UnityEngine.GUIContent("f3", "f3"), GUILayout.Width(100));
}
else
{
UnityEditor.EditorGUILayout.LabelField(new UnityEngine.GUIContent("f3", ""), GUILayout.Width(100));
}
this.f3 = UnityEditor.EditorGUILayout.TextField(this.f3, GUILayout.Width(150));
if (GUILayout.Button("…", GUILayout.Width(20)))
{
TextInputWindow.GetTextAsync(this.f3,__x =>this.f3 = __x);
}
UnityEditor.EditorGUILayout.EndHorizontal();UnityEditor.EditorGUILayout.BeginHorizontal();
if (ConfigEditorSettings.showComment)
{
UnityEditor.EditorGUILayout.LabelField(new UnityEngine.GUIContent("s1", "s1"), GUILayout.Width(100));
}
else
{
UnityEditor.EditorGUILayout.LabelField(new UnityEngine.GUIContent("s1", ""), GUILayout.Width(100));
}
{
if (this.s1 == null)
{
this.s1 = test.RefDynamicBase.Create("RefBean");
}
test.RefDynamicBase.RenderRefDynamicBase(ref this.s1);
}
UnityEditor.EditorGUILayout.EndHorizontal(); UnityEditor.EditorGUILayout.EndVertical();
} }
public static TestRef LoadJsonTestRef(SimpleJSON.JSONNode _json)
{
TestRef obj = new test.TestRef();
obj.LoadJson((SimpleJSON.JSONObject)_json);
return obj;
}
public static void SaveJsonTestRef(TestRef _obj, SimpleJSON.JSONNode _json)
{
_obj.SaveJson((SimpleJSON.JSONObject)_json);
}
public int id;
public int x1;
public int x12;
public int x2;
public int x3;
public int x4;
public int[] a1;
public int[] a2;
public System.Collections.Generic.List<int> b1;
public System.Collections.Generic.List<int> b2;
public System.Collections.Generic.List<int> c1;
public System.Collections.Generic.List<int> c2;
public System.Collections.Generic.List<object[]> d1;
public System.Collections.Generic.List<object[]> d2;
public int e1;
public long e2;
public string e3;
public int f1;
public long f2;
public string f3;
public editor.cfg.test.RefDynamicBase s1;
public override string ToString()
{
return "{ "
+ "id:" + id + ","
+ "x1:" + x1 + ","
+ "x12:" + x12 + ","
+ "x2:" + x2 + ","
+ "x3:" + x3 + ","
+ "x4:" + x4 + ","
+ "a1:" + Luban.StringUtil.CollectionToString(a1) + ","
+ "a2:" + Luban.StringUtil.CollectionToString(a2) + ","
+ "b1:" + Luban.StringUtil.CollectionToString(b1) + ","
+ "b2:" + Luban.StringUtil.CollectionToString(b2) + ","
+ "c1:" + Luban.StringUtil.CollectionToString(c1) + ","
+ "c2:" + Luban.StringUtil.CollectionToString(c2) + ","
+ "d1:" + Luban.StringUtil.CollectionToString(d1) + ","
+ "d2:" + Luban.StringUtil.CollectionToString(d2) + ","
+ "e1:" + e1 + ","
+ "e2:" + e2 + ","
+ "e3:" + e3 + ","
+ "f1:" + f1 + ","
+ "f2:" + f2 + ","
+ "f3:" + f3 + ","
+ "s1:" + s1 + ","
+ "}";
}
}
}
| 1 | 0.79473 | 1 | 0.79473 | game-dev | MEDIA | 0.435197 | game-dev | 0.751417 | 1 | 0.751417 |
Sarjuuk/aowow | 6,044 | setup/tools/filegen/itemscaling.ss.php | <?php
namespace Aowow;
if (!defined('AOWOW_REVISION'))
die('illegal access');
if (!CLI)
die('not in cli mode');
CLISetup::registerSetup("build", new class extends SetupScript
{
use TrTemplateFile;
protected $info = array(
'itemscaling' => [[], CLISetup::ARGV_PARAM, 'Compiles item scaling data to file to make heirloom tooltips interactive.']
);
protected $fileTemplateDest = ['datasets/item-scaling'];
protected $fileTemplateSrc = ['item-scaling.in'];
protected $dbcSourceFiles = ['scalingstatdistribution', 'scalingstatvalues', 'gtoctclasscombatratingscalar', 'gtcombatratings'];
private function debugify(array $data) : string
{
$buff = [];
foreach ($data as $id => $row)
{
foreach ($row as &$r)
$r = str_pad($r, 5, " ", STR_PAD_LEFT);
$buff[] = str_pad($id, 7, " ", STR_PAD_LEFT).": [".implode(', ', $row)."]";
}
return "{\r\n".implode(",\r\n", $buff)."\r\n}";
}
private function itemScalingRB() : string
{
// data and format observed via wayback machine. Not entirely sure about the redunacy within the combat ratings though.
$ratings = array(
Stat::DEFENSE_RTG => CR_DEFENSE_SKILL,
Stat::DODGE_RTG => CR_DODGE,
Stat::PARRY_RTG => CR_PARRY,
Stat::BLOCK_RTG => CR_BLOCK,
Stat::MELEE_HIT_RTG => CR_HIT_MELEE,
Stat::RANGED_HIT_RTG => CR_HIT_RANGED,
Stat::SPELL_HIT_RTG => CR_HIT_SPELL,
Stat::MELEE_CRIT_RTG => CR_CRIT_MELEE,
Stat::RANGED_CRIT_RTG => CR_CRIT_RANGED,
Stat::SPELL_CRIT_RTG => CR_CRIT_SPELL,
Stat::MELEE_HIT_TAKEN_RTG => CR_HIT_TAKEN_MELEE,
Stat::RANGED_HIT_TAKEN_RTG => CR_HIT_TAKEN_RANGED,
Stat::SPELL_HIT_TAKEN_RTG => CR_HIT_TAKEN_SPELL,
Stat::MELEE_CRIT_TAKEN_RTG => CR_CRIT_TAKEN_MELEE, // may be forced 0
Stat::RANGED_CRIT_TAKEN_RTG => CR_CRIT_TAKEN_RANGED, // may be forced 0
Stat::SPELL_CRIT_TAKEN_RTG => CR_CRIT_TAKEN_SPELL, // may be forced 0
Stat::MELEE_HASTE_RTG => CR_HASTE_MELEE,
Stat::RANGED_HASTE_RTG => CR_HASTE_RANGED,
Stat::SPELL_HASTE_RTG => CR_HASTE_SPELL,
Stat::HIT_RTG => CR_HIT_MELEE,
Stat::CRIT_RTG => CR_CRIT_MELEE,
Stat::HIT_TAKEN_RTG => CR_HIT_TAKEN_MELEE, // may be forced 0
Stat::CRIT_TAKEN_RTG => CR_CRIT_TAKEN_MELEE, // may be forced 0
Stat::RESILIENCE_RTG => CR_CRIT_TAKEN_MELEE,
Stat::HASTE_RTG => CR_HASTE_MELEE,
Stat::EXPERTISE_RTG => CR_EXPERTISE,
Stat::ARMOR_PENETRATION_RTG => CR_ARMOR_PENETRATION
);
$data = $ratings;
$offsets = array_map(function ($v) { // LookupEntry(cr*GT_MAX_LEVEL+level-1)
return $v * 100 + 60 - 1; // combat rating where introduced during the transition vanilla > burnig crusade. So at level 60 (at the time) the rating on the item was equal to 1% effect and is still the baseline in 3.3.5a.
}, $ratings);
$base = DB::Aowow()->selectCol('SELECT CAST((idx + 1 - 60) / 100 AS UNSIGNED) AS ARRAY_KEY, ratio FROM dbc_gtcombatratings WHERE idx IN (?a)', $offsets);
/* non-1 scaler in 3.3.5.12340
| ratingId | classId | ratio |
| 17 | 2 | 1.3 |
| 17 | 6 | 1.3 |
| 17 | 7 | 1.3 |
| 17 | 11 | 1.3 |
| 24 | < all > | 1.1 |
*/
$offsets = array_map(function ($v) { // LookupEntry((getClass()-1)*GT_MAX_RATING+cr+1)
return (ChrClass::WARRIOR->value - 1) * 32 + $v + 1; // should this be dynamic per pinned character? ITEM_MOD HASTE has a worse scaler for a subset of classes (see table)
}, $ratings);
$mods = DB::Aowow()->selectCol('SELECT idx - 1 AS ARRAY_KEY, ratio FROM dbc_gtoctclasscombatratingscalar WHERE idx IN (?a)', $offsets);
foreach ($data as &$val)
$val = Cfg::get('DEBUG') ? $base[$val].' / '.$mods[$val] : $base[$val] / $mods[$val];
if (!Cfg::get('DEBUG'))
return Util::toJSON($data);
$buff = [];
foreach ($data as $k => $v)
$buff[] = $k.': '.$v;
return "{\r\n ".implode(",\r\n ", $buff)."\r\n}";
}
private function itemScalingSV() : string
{
/* so the javascript expects a slightly different structure, than the dbc provides .. f*** it
e.g.
dbc - 80: 97 97 56 41 210 395 878 570 120 156 86 112 108 220 343 131 73 140 280 527 1171 2093
expected - 80: 97 97 56 131 41 210 395 878 1570 120 156 86 112 108 220 343 0 0 73 140 280 527 1171 2093
*/
$fields = Util::$ssdMaskFields;
array_walk($fields, function(&$v, $k) {
$v = $v ?: '0 AS idx'.$k; // NULL => 0 (plus some index so we can have 2x 0)
});
$data = DB::Aowow()->select('SELECT id AS ARRAY_KEY, '.implode(', ', $fields).' FROM dbc_scalingstatvalues');
foreach ($data as &$d)
$d = array_values($d); // strip indizes
return Cfg::get('DEBUG') ? $this->debugify($data) : Util::toJSON($data);
}
private function itemScalingSD() : string
{
$data = DB::Aowow()->select('SELECT *, id AS ARRAY_KEY FROM dbc_scalingstatdistribution');
foreach ($data as &$row)
{
$row = array_values($row);
array_splice($row, 0, 1);
}
return Cfg::get('DEBUG') ? $this->debugify($data) : Util::toJSON($data);
}
})
?>
| 1 | 0.901084 | 1 | 0.901084 | game-dev | MEDIA | 0.673548 | game-dev | 0.897234 | 1 | 0.897234 |
cbhust8025/ChromiumBase | 4,693 | src/Chromium/Base/lazy_instance_helpers.h | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef BASE_LAZY_INSTANCE_INTERNAL_H_
#define BASE_LAZY_INSTANCE_INTERNAL_H_
#include "base/atomicops.h"
#include "base/base_export.h"
#include "base/logging.h"
// Helper methods used by LazyInstance and a few other base APIs for thread-safe
// lazy construction.
namespace base {
namespace internal {
// Our AtomicWord doubles as a spinlock, where a value of
// kLazyInstanceStateCreating means the spinlock is being held for creation.
constexpr subtle::AtomicWord kLazyInstanceStateCreating = 1;
// Helper for GetOrCreateLazyPointer(). Checks if instance needs to be created.
// If so returns true otherwise if another thread has beat us, waits for
// instance to be created and returns false.
BASE_EXPORT bool NeedsLazyInstance(subtle::AtomicWord* state);
// Helper for GetOrCreateLazyPointer(). After creating an instance, this is
// called to register the dtor to be called at program exit and to update the
// atomic state to hold the |new_instance|
BASE_EXPORT void CompleteLazyInstance(subtle::AtomicWord* state,
subtle::AtomicWord new_instance,
void (*destructor)(void*),
void* destructor_arg);
} // namespace internal
namespace subtle {
// If |state| is uninitialized (zero), constructs a value using
// |creator_func(creator_arg)|, stores it into |state| and registers
// |destructor(destructor_arg)| to be called when the current AtExitManager goes
// out of scope. Then, returns the value stored in |state|. It is safe to have
// concurrent calls to this function with the same |state|. |creator_func| may
// return nullptr if it doesn't want to create an instance anymore (e.g. on
// shutdown), it is from then on required to return nullptr to all callers (ref.
// StaticMemorySingletonTraits). In that case, callers need to synchronize
// before |creator_func| may return a non-null instance again (ref.
// StaticMemorySingletonTraits::ResurectForTesting()).
// Implementation note on |creator_func/creator_arg|. It makes for ugly adapters
// but it avoids redundant template instantiations (e.g. saves 27KB in
// chrome.dll) because linker is able to fold these for multiple Types but
// couldn't with the more advanced CreatorFunc template type which in turn
// improves code locality (and application startup) -- ref.
// https://chromium-review.googlesource.com/c/chromium/src/+/530984/5/base/lazy_instance.h#140,
// worsened by https://chromium-review.googlesource.com/c/chromium/src/+/868013
// and caught then as https://crbug.com/804034.
template <typename Type>
Type* GetOrCreateLazyPointer(subtle::AtomicWord* state,
Type* (*creator_func)(void*),
void* creator_arg,
void (*destructor)(void*),
void* destructor_arg) {
DCHECK(state);
DCHECK(creator_func);
// If any bit in the created mask is true, the instance has already been
// fully constructed.
constexpr subtle::AtomicWord kLazyInstanceCreatedMask =
~internal::kLazyInstanceStateCreating;
// We will hopefully have fast access when the instance is already created.
// Since a thread sees |state| == 0 or kLazyInstanceStateCreating at most
// once, the load is taken out of NeedsLazyInstance() as a fast-path. The load
// has acquire memory ordering as a thread which sees |state| > creating needs
// to acquire visibility over the associated data. Pairing Release_Store is in
// CompleteLazyInstance().
subtle::AtomicWord instance = subtle::Acquire_Load(state);
if (!(instance & kLazyInstanceCreatedMask)) {
if (internal::NeedsLazyInstance(state)) {
// This thread won the race and is now responsible for creating the
// instance and storing it back into |state|.
instance =
reinterpret_cast<subtle::AtomicWord>((*creator_func)(creator_arg));
internal::CompleteLazyInstance(state, instance, destructor,
destructor_arg);
} else {
// This thread lost the race but now has visibility over the constructed
// instance (NeedsLazyInstance() doesn't return until the constructing
// thread releases the instance via CompleteLazyInstance()).
instance = subtle::Acquire_Load(state);
DCHECK(instance & kLazyInstanceCreatedMask);
}
}
return reinterpret_cast<Type*>(instance);
}
} // namespace subtle
} // namespace base
#endif // BASE_LAZY_INSTANCE_INTERNAL_H_
| 1 | 0.872529 | 1 | 0.872529 | game-dev | MEDIA | 0.279144 | game-dev | 0.6031 | 1 | 0.6031 |
sandstranger/Underworld-Exporter-Android | 2,873 | Assets/Editor/ImageEffects/AntialiasingEditor.cs | using System;
using UnityEditor;
using UnityEngine;
namespace UnityStandardAssets.ImageEffects
{
[CustomEditor(typeof (Antialiasing))]
public class AntialiasingEditor : Editor
{
private SerializedObject serObj;
private SerializedProperty mode;
private SerializedProperty showGeneratedNormals;
private SerializedProperty offsetScale;
private SerializedProperty blurRadius;
private SerializedProperty dlaaSharp;
private SerializedProperty edgeThresholdMin;
private SerializedProperty edgeThreshold;
private SerializedProperty edgeSharpness;
private void OnEnable()
{
serObj = new SerializedObject(target);
mode = serObj.FindProperty("mode");
showGeneratedNormals = serObj.FindProperty("showGeneratedNormals");
offsetScale = serObj.FindProperty("offsetScale");
blurRadius = serObj.FindProperty("blurRadius");
dlaaSharp = serObj.FindProperty("dlaaSharp");
edgeThresholdMin = serObj.FindProperty("edgeThresholdMin");
edgeThreshold = serObj.FindProperty("edgeThreshold");
edgeSharpness = serObj.FindProperty("edgeSharpness");
}
public override void OnInspectorGUI()
{
serObj.Update();
GUILayout.Label("Luminance based fullscreen antialiasing", EditorStyles.miniBoldLabel);
EditorGUILayout.PropertyField(mode, new GUIContent("Technique"));
Material mat = (target as Antialiasing).CurrentAAMaterial();
if (null == mat && (target as Antialiasing).enabled)
{
EditorGUILayout.HelpBox("This AA technique is currently not supported. Choose a different technique or disable the effect and use MSAA instead.", MessageType.Warning);
}
if (mode.enumValueIndex == (int) AAMode.NFAA)
{
EditorGUILayout.PropertyField(offsetScale, new GUIContent("Edge Detect Ofs"));
EditorGUILayout.PropertyField(blurRadius, new GUIContent("Blur Radius"));
EditorGUILayout.PropertyField(showGeneratedNormals, new GUIContent("Show Normals"));
}
else if (mode.enumValueIndex == (int) AAMode.DLAA)
{
EditorGUILayout.PropertyField(dlaaSharp, new GUIContent("Sharp"));
}
else if (mode.enumValueIndex == (int) AAMode.FXAA3Console)
{
EditorGUILayout.PropertyField(edgeThresholdMin, new GUIContent("Edge Min Threshhold"));
EditorGUILayout.PropertyField(edgeThreshold, new GUIContent("Edge Threshhold"));
EditorGUILayout.PropertyField(edgeSharpness, new GUIContent("Edge Sharpness"));
}
serObj.ApplyModifiedProperties();
}
}
}
| 1 | 0.888763 | 1 | 0.888763 | game-dev | MEDIA | 0.910634 | game-dev | 0.912806 | 1 | 0.912806 |
shdwcat/YUI | 1,842 | objects/yui_object_attachment/Create_0.gml | /// @description init
// Inherit the parent event
event_inherited();
placement = undefined;
onLayoutInit = function() {
target_value = new YuiBindableValue(yui_element.target, undefined);
placement = yui_element.placement;
}
alignToTarget = function(target) {
switch placement {
case YUI_PLACEMENT_MODE.TopLeft:
yui_align_relative(target, fa_left, fa_top);
break;
case YUI_PLACEMENT_MODE.TopCenter:
yui_align_relative(target, fa_center, fa_top);
break;
case YUI_PLACEMENT_MODE.TopRight:
yui_align_relative(target, fa_right, fa_top);
break;
// todo actually support these -- need to figure out how tho
case YUI_PLACEMENT_MODE.LeftTop:
yui_align_relative(target, fa_right, fa_top);
break;
case YUI_PLACEMENT_MODE.RightTop:
yui_align_relative(target, fa_left, fa_top);
break;
case YUI_PLACEMENT_MODE.BottomLeft:
yui_align_relative(target, fa_left, fa_bottom);
break;
case YUI_PLACEMENT_MODE.BottomCenter:
yui_align_relative(target, fa_center, fa_bottom);
break;
case YUI_PLACEMENT_MODE.BottomRight:
yui_align_relative(target, fa_right, fa_bottom);
break;
}
if content_item && instance_exists(content_item) {
var xdiff = draw_size.x - content_item.draw_size.x;
var ydiff = draw_size.y - content_item.draw_size.y;
content_item.move(xdiff, ydiff);
}
}
border_arrange = arrange;
arrange = function(available_size, viewport_size) {
var size = border_arrange(available_size, viewport_size);
if target_value.is_live
target_value.update(data_source);
var target = target_value.value;
if target != undefined && instance_exists(target)
alignToTarget(target);
}
// override this to avoid notifying parent -- our size doesn't affect the parent
onChildLayoutComplete = function(child) {
if !is_arranging {
arrange(draw_rect, viewport_size);
}
} | 1 | 0.821933 | 1 | 0.821933 | game-dev | MEDIA | 0.746905 | game-dev | 0.799856 | 1 | 0.799856 |
ldtteam/minecolonies | 2,334 | src/main/java/com/minecolonies/core/tileentities/TileEntityScarecrow.java | package com.minecolonies.core.tileentities;
import com.minecolonies.api.colony.IColony;
import com.minecolonies.api.colony.IColonyManager;
import com.minecolonies.api.tileentities.AbstractTileEntityScarecrow;
import com.minecolonies.api.tileentities.ScareCrowType;
import com.minecolonies.core.Network;
import com.minecolonies.core.network.messages.server.colony.building.fields.FarmFieldRegistrationMessage;
import net.minecraft.core.BlockPos;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.protocol.game.ClientboundBlockEntityDataPacket;
import net.minecraft.world.level.block.state.BlockState;
import org.jetbrains.annotations.NotNull;
import java.util.Random;
/**
* The scarecrow tile entity to store extra data.
*/
@SuppressWarnings("PMD.ExcessiveImports")
public class TileEntityScarecrow extends AbstractTileEntityScarecrow
{
/**
* Random generator.
*/
private final Random random = new Random();
/**
* The colony this field is located in.
*/
private IColony currentColony;
/**
* The type of the scarecrow.
*/
private ScareCrowType type;
/**
* Creates an instance of the tileEntity.
*/
public TileEntityScarecrow(final BlockPos pos, final BlockState state)
{
super(pos, state);
}
@Override
public ScareCrowType getScarecrowType()
{
if (this.type == null)
{
final ScareCrowType[] values = ScareCrowType.values();
this.type = values[this.random.nextInt(values.length)];
}
return this.type;
}
@Override
public IColony getCurrentColony()
{
if (currentColony == null && level != null)
{
this.currentColony = IColonyManager.getInstance().getIColony(level, worldPosition);
// TODO: Remove in 1.20.2
if (this.currentColony != null)
{
Network.getNetwork().sendToServer(new FarmFieldRegistrationMessage(currentColony, worldPosition));
}
}
return currentColony;
}
@Override
public ClientboundBlockEntityDataPacket getUpdatePacket()
{
return ClientboundBlockEntityDataPacket.create(this);
}
@NotNull
@Override
public CompoundTag getUpdateTag()
{
return saveWithId();
}
}
| 1 | 0.822276 | 1 | 0.822276 | game-dev | MEDIA | 0.96728 | game-dev | 0.614468 | 1 | 0.614468 |
NEventStore/NEventStore | 4,388 | src/NEventStore/ImmutableDictionary.cs | using System.Collections;
namespace NEventStore
{
/// <summary>
/// Represents an immutable dictionary.
/// </summary>
public sealed class ImmutableDictionary<TKey, TValue> : IDictionary<TKey, TValue>
{
private readonly IDictionary<TKey, TValue> _inner;
/// <summary>
/// Initializes a new instance of the ImmutableDictionary class.
/// </summary>
public ImmutableDictionary(IDictionary<TKey, TValue> inner)
{
_inner = inner;
}
/// <summary>
/// Gets the value associated with the specified key.
/// </summary>
/// <exception cref="NotSupportedException"></exception>
public TValue this[TKey key] { get => _inner[key]; set => throw new NotSupportedException(Resources.ReadOnlyCollection); }
/// <summary>
/// Gets the keys in the dictionary.
/// </summary>
public ICollection<TKey> Keys => _inner.Keys;
/// <summary>
/// Gets the values in the dictionary.
/// </summary>
public ICollection<TValue> Values => _inner.Values;
/// <summary>
/// Gets the number of elements in the dictionary.
/// </summary>
public int Count => _inner.Count;
/// <summary>
/// Gets a value indicating whether the dictionary is read-only.
/// </summary>
public bool IsReadOnly => true;
/// <summary>
/// Adds an element with the provided key and value to the dictionary.
/// </summary>
/// <exception cref="NotSupportedException"></exception>
public void Add(TKey key, TValue value)
{
throw new NotSupportedException(Resources.ReadOnlyCollection);
}
/// <summary>
/// Adds an item to the dictionary.
/// </summary>
/// <exception cref="NotSupportedException"></exception>
public void Add(KeyValuePair<TKey, TValue> item)
{
throw new NotSupportedException(Resources.ReadOnlyCollection);
}
/// <summary>
/// Removes all items from the dictionary.
/// </summary>
/// <exception cref="NotSupportedException"></exception>
public void Clear()
{
throw new NotSupportedException(Resources.ReadOnlyCollection);
}
/// <summary>
/// Determines whether the dictionary contains a specific value.
/// </summary>
public bool Contains(KeyValuePair<TKey, TValue> item)
{
return _inner.Contains(item);
}
/// <summary>
/// Determines whether the dictionary contains a specific key.
/// </summary>
public bool ContainsKey(TKey key)
{
return _inner.ContainsKey(key);
}
/// <summary>
/// Copies the elements of the dictionary to an array, starting at a particular array index.
/// </summary>
public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
_inner.CopyTo(array, arrayIndex);
}
/// <summary>
/// Removes the element with the specified key from the dictionary.
/// </summary>
/// <exception cref="NotSupportedException"></exception>
public bool Remove(TKey key)
{
throw new NotSupportedException(Resources.ReadOnlyCollection);
}
/// <summary>
/// Removes the first occurrence of a specific object from the dictionary.
/// </summary>
/// <exception cref="NotSupportedException"></exception>
public bool Remove(KeyValuePair<TKey, TValue> item)
{
throw new NotSupportedException(Resources.ReadOnlyCollection);
}
/// <summary>
/// Gets the value associated with the specified key.
/// </summary>
public bool TryGetValue(TKey key, out TValue value)
{
return _inner.TryGetValue(key, out value);
}
/// <summary>
/// Returns an enumerator that iterates through the dictionary.
/// </summary>
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
return _inner.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
} | 1 | 0.883404 | 1 | 0.883404 | game-dev | MEDIA | 0.320931 | game-dev | 0.848236 | 1 | 0.848236 |
google/santa-tracker-android | 4,823 | presentquest/src/main/java/com/google/android/apps/santatracker/presentquest/vo/User.java | /*
* Copyright (C) 2016 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.
*/
package com.google.android.apps.santatracker.presentquest.vo;
import androidx.room.Entity;
import androidx.room.Ignore;
import androidx.room.PrimaryKey;
@Entity
public class User {
@Ignore public static final int USER_DATABASE_ID = 88;
@Ignore public static final int WORKSHOP_2_LEVEL = 2;
@Ignore public static final int WORKSHOP_3_LEVEL = 4;
// Presents required on each level to proceed to next level.
// If the user is on level i they will have collected somewhere between
// PRESENTS_REQUIRED[i - 1] and PRESENTS_REQUIRED[i] presents
//
// A good game of present collecting returns around 50 presents, so getting
// 100 points is two games and 1000 points is twenty games.
@Ignore
public static final int[] PRESENTS_REQUIRED = {
0, // Level 0 (does not exist)
1, // Level 1
50, // Level 2
200, // Level 3
500, // Level 4
750, // Level 5
1000, // Level 6
2000, // Level 7
5000, // Level 8
10000, // Level 9
15000, // Level 10
20000, // Level 11
// Level 12 is the last level, can't beat it
Integer.MAX_VALUE
};
// Maximum presents that can be collected (held before returning) on each level.
@Ignore
private static final int[] MAX_PRESENTS_COLLECTED = {
0, // Level 0 (does not exist)
10, // Level 1
50, // Level 2
75, // Level 3
100, // Level 4
250, // Level 5
300, // Level 6
350, // Level 7
400, // Level 8
450, // Level 9
500, // Level 10
500, // Level 11
1000, // Level 12
};
// Chance that a present bunch dropped is "large"
@Ignore
private static final float[] LARGE_PRESENT_CHANCE = {
0.00f, // Level 0
0.05f, // Level 1
0.10f, // Level 2
0.15f, // Level 3
0.20f, // Level 4
0.25f, // Level 5
0.30f, // Level 6
0.35f, // Level 7
0.40f, // Level 8
0.45f, // Level 9
0.55f, // Level 10
0.60f, // Level 11
0.65f, // Level 12
};
@PrimaryKey public long id = USER_DATABASE_ID;
public int presentsCollected = 0;
public int presentsReturned = 0;
public User() {}
// Returns current level.
public int getLevel() {
for (int i = 0; i < PRESENTS_REQUIRED.length; i++) {
if (presentsReturned < PRESENTS_REQUIRED[i]) {
return i;
}
}
return 1;
}
public boolean isWorkshopUnlocked(int i) {
return getMaxWorkshops() >= i;
}
private int getMaxWorkshops() {
int level = getLevel();
if (level >= WORKSHOP_3_LEVEL) {
return 3;
} else if (level >= WORKSHOP_2_LEVEL) {
return 2;
} else {
return 1;
}
}
// Returns avatar for current level.
public int getAvatar() {
return Avatars.AVATARS_UNLOCKED[getLevel() - 1];
}
// Returns progress percentage for current level.
public int getLevelProgress() {
int level = getLevel();
// It's impossible to get past the last level, so always show full progress at level 12.
if (level == (PRESENTS_REQUIRED.length - 1)) {
return 100;
}
int requiredThisLevel = PRESENTS_REQUIRED[level];
int requiredPreviousLevel = PRESENTS_REQUIRED[level - 1];
int requiredForLevel = requiredThisLevel - requiredPreviousLevel;
int returnedForLevel = presentsReturned - requiredPreviousLevel;
int progress = (int) ((returnedForLevel * 100.0f) / requiredForLevel);
return progress;
}
public int getMaxPresentsCollected() {
return MAX_PRESENTS_COLLECTED[getLevel()];
}
public int getPresentsCollectedAllTime() {
return presentsReturned + presentsCollected;
}
public int getBagFillPercentage() {
int percentFull = (100 * presentsCollected) / (getMaxPresentsCollected());
return Math.min(percentFull, 100);
}
public float getLargePresentChance() {
return LARGE_PRESENT_CHANCE[getLevel()];
}
}
| 1 | 0.661343 | 1 | 0.661343 | game-dev | MEDIA | 0.954024 | game-dev | 0.591154 | 1 | 0.591154 |
renpy/rapt | 2,543 | native/jni/sdl2/src/video/haiku/SDL_bclipboard.cc | /*
Simple DirectMedia Layer
Copyright (C) 1997-2015 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 SDL_VIDEO_DRIVER_HAIKU
/* BWindow based framebuffer implementation */
#include <unistd.h>
#include <TypeConstants.h>
#include "SDL_BWin.h"
#include "SDL_timer.h"
#include "../SDL_sysvideo.h"
#ifdef __cplusplus
extern "C" {
#endif
int BE_SetClipboardText(_THIS, const char *text) {
BMessage *clip = NULL;
if(be_clipboard->Lock()) {
be_clipboard->Clear();
if((clip = be_clipboard->Data())) {
/* Presumably the string of characters is ascii-format */
ssize_t asciiLength = 0;
for(; text[asciiLength] != 0; ++asciiLength) {}
clip->AddData("text/plain", B_MIME_TYPE, &text, asciiLength);
be_clipboard->Commit();
}
be_clipboard->Unlock();
}
return 0;
}
char *BE_GetClipboardText(_THIS) {
BMessage *clip = NULL;
const char *text = NULL;
ssize_t length;
char *result;
if(be_clipboard->Lock()) {
if((clip = be_clipboard->Data())) {
/* Presumably the string of characters is ascii-format */
clip->FindData("text/plain", B_MIME_TYPE, (const void**)&text,
&length);
} else {
be_clipboard->Unlock();
}
be_clipboard->Unlock();
}
if (!text) {
result = SDL_strdup("");
} else {
/* Copy the data and pass on to SDL */
result = (char*)SDL_calloc(1, sizeof(char*)*length);
SDL_strlcpy(result, text, length);
}
return result;
}
SDL_bool BE_HasClipboardText(_THIS) {
SDL_bool result = SDL_FALSE;
char *text = BE_GetClipboardText(_this);
if (text) {
result = text[0] != '\0' ? SDL_TRUE : SDL_FALSE;
SDL_free(text);
}
return result;
}
#ifdef __cplusplus
}
#endif
#endif /* SDL_VIDEO_DRIVER_HAIKU */
| 1 | 0.729263 | 1 | 0.729263 | game-dev | MEDIA | 0.459753 | game-dev | 0.618875 | 1 | 0.618875 |
BigheadSMZ/Zelda-LA-DX-HD-Updated | 1,208 | ladxhd_game_source_code/InGame/GameObjects/Things/ObjCactus.cs | using Microsoft.Xna.Framework;
using ProjectZ.InGame.GameObjects.Base;
using ProjectZ.InGame.GameObjects.Base.CObjects;
using ProjectZ.InGame.GameObjects.Base.Components;
using ProjectZ.InGame.Things;
namespace ProjectZ.InGame.GameObjects.Things
{
internal class ObjCactus : GameObject
{
public ObjCactus() : base("cactus") { }
public ObjCactus(Map.Map map, int posX, int posY) : base(map)
{
EntityPosition = new CPosition(posX + 8, posY + 16, 0);
EntitySize = new Rectangle(-8, -16, 16, 16);
var sprite = new CSprite("cactus", EntityPosition);
var collisionBox = new CBox(posX + 3, posY + 3, 0, 10, 12, 8);
var damageBox = new CBox(posX + 2, posY + 2, 0, 12, 14, 8);
AddComponent(CollisionComponent.Index, new BoxCollisionComponent(collisionBox, Values.CollisionTypes.Normal));
AddComponent(DamageFieldComponent.Index, new DamageFieldComponent(damageBox, HitType.Enemy, 2));
AddComponent(DrawComponent.Index, new DrawCSpriteComponent(sprite, Values.LayerPlayer));
AddComponent(DrawShadowComponent.Index, new DrawShadowCSpriteComponent(sprite));
}
}
} | 1 | 0.766159 | 1 | 0.766159 | game-dev | MEDIA | 0.756723 | game-dev | 0.923133 | 1 | 0.923133 |
AXiX-official/CrossCoreLuascripts | 5,591 | ios/Others/AccuChargeMgr.lua | local AccuChargeData = require("AccuChargeData")
local AccuChargeDataS = require("AccuChargeDataS")
local AccuChargeDataT = require("AccuChargeDataT")
local this = MgrRegister("AccuChargeMgr")
function this:Init()
self:Clear()
self:InitData()
PlayerProto:GetColletData()
PlayerProto:GetColletDataByType()
end
function this:Clear()
self.proto = {}
self.datas = {}
self.proto2 = nil
self.datas2 = {}
end
function this:InitData()
self.datas = {}
local cfgs = Cfgs.CfgRechargeCount:GetAll()
for i, v in ipairs(cfgs) do
local data = AccuChargeData.New()
data:InitData(v)
table.insert(self.datas, data)
end
--
self.datas2 = {}
local cfgs = Cfgs.CfgRechargeCount2:GetAll()
for i, v in ipairs(cfgs) do
local data = AccuChargeDataS.New()
data:InitData(v)
table.insert(self.datas2, data)
end
--
self.datas3 = {}
local cfgs = Cfgs.CfgRechargeCount:GetAll()
for i, v in ipairs(cfgs) do
local data = AccuChargeDataT.New()
data:InitData(v)
table.insert(self.datas3, data)
end
end
---------------------------------1--------------------------------------------------------
function this:GetColletDataRet(proto)
self.proto = proto
-- EventMgr.Dispatch(EventType.AccuCharge_Get)
self:CheckRed()
end
function this:GetDatas()
return self.datas
end
function this:CheckRed()
local num = 0
for k, v in pairs(self.datas) do
if (v:IsRed()) then
num = 1
break
end
end
local rData = RedPointMgr:GetData(RedPointType.AccuCharge)
if (rData == nil or rData ~= num) then
RedPointMgr:UpdateData(RedPointType.AccuCharge, num)
ActivityMgr:CheckRedPointData(ActivityListType.AccuCharge)
end
end
function this:GetScore()
local socre = self.proto.score
if (socre) then
return math.floor(socre / 100)
end
return 0
end
function this:CheckIsGet(id)
if (self.proto.data) then
for k, v in pairs(self.proto.data) do
if (v == id) then
return true
end
end
end
return false
end
----------------------------------2---------------------------------------------------------
function this:GetColletDataByTypeRet(proto)
self.proto2 = proto
self:CheckRed2()
end
function this:GetCfg2()
return Cfgs.CfgActiveList:GetByID(ActivityListType.AccuCharge2)
end
function this:GetDatas2()
return self.datas2
end
function this:CheckRed2()
local num = 0
for k, v in pairs(self.datas2) do
if (v:IsRed()) then
num = 1
break
end
end
local rData = RedPointMgr:GetData(RedPointType.AccuCharge2)
if (rData == nil or rData ~= num) then
RedPointMgr:UpdateData(RedPointType.AccuCharge2, num)
ActivityMgr:CheckRedPointData(ActivityListType.AccuCharge2)
end
end
function this:GetScore2()
local socre = self.proto2.score
if (socre) then
return math.floor(socre / 100)
end
return 0
end
function this:CheckIsGet2(id)
if (self.proto2 and self.proto2.data) then
for k, v in pairs(self.proto2.data) do
if (v == id) then
return true
end
end
end
return false
end
-- 关闭活动时间,关闭入口时间
function this:GetEndTime2()
if (not self.proto2 or not self.proto2.closeTime or self.proto2.closeTime == -1) then
return nil
end
local cTime = self:GetCfg2().cTime or 0
local endTime = self.proto2.closeTime + cTime * 3600
return self.proto2.closeTime, endTime
end
-- 是否需要显示(活动有效时间+等待关闭时间)
function this:IsOpen2()
if (not self.proto2 or self.proto2.openTime == 0) then
return false
end
local curTime = TimeUtil:GetTime()
if (curTime >= self.proto2.openTime) then
if (not self.proto2.closeTime or self.proto2.closeTime == -1) then
return true
end
local cTime = self:GetCfg2().cTime or 0
local endTime = self.proto2.closeTime + cTime * 3600
if (endTime > curTime) then
return true
end
end
return false
end
-- 是否可充值或领取
function this:IsActive2()
if (self:IsOpen2()) then
local endTime = self.proto2.closeTime or -1
if (endTime == -1 or endTime > TimeUtil:GetTime()) then
return true
end
end
return false
end
----------------------------------3---------------------------------------------------------
function this:GetColletDataByTypeRet3(proto)
self.proto3 = proto
self:CheckRed3()
end
function this:GetCfg3()
return Cfgs.CfgActiveList:GetByID(ActivityListType.AccuCharge3)
end
function this:GetDatas3()
return self.datas3
end
function this:CheckRed3()
local num = 0
for k, v in pairs(self.datas3) do
if (v:IsRed()) then
num = 1
break
end
end
local rData = RedPointMgr:GetData(RedPointType.AccuCharge3)
if (rData == nil or rData ~= num) then
RedPointMgr:UpdateData(RedPointType.AccuCharge3, num)
ActivityMgr:CheckRedPointData(ActivityListType.AccuCharge3)
end
end
function this:GetScore3()
local socre = self.proto3.score
if (socre) then
return math.floor(socre / 100)
end
return 0
end
function this:CheckIsGet3(id)
if (self.proto3 and self.proto3.data) then
for k, v in pairs(self.proto3.data) do
if (v == id) then
return true
end
end
end
return false
end
return this
| 1 | 0.859539 | 1 | 0.859539 | game-dev | MEDIA | 0.688654 | game-dev | 0.822026 | 1 | 0.822026 |
Tangshitao/Semi-supervised-Adaptive-Distillation | 12,283 | caffe2/third_party/protobuf/src/google/protobuf/arenastring.h | // Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef GOOGLE_PROTOBUF_ARENASTRING_H__
#define GOOGLE_PROTOBUF_ARENASTRING_H__
#include <string>
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/fastmem.h>
#include <google/protobuf/arena.h>
// This is the implementation of arena string fields written for the open-source
// release. The ArenaStringPtr struct below is an internal implementation class
// and *should not be used* by user code. It is used to collect string
// operations together into one place and abstract away the underlying
// string-field pointer representation, so that (for example) an alternate
// implementation that knew more about ::std::string's internals could integrate more
// closely with the arena allocator.
namespace google {
namespace protobuf {
namespace internal {
struct LIBPROTOBUF_EXPORT ArenaStringPtr {
inline void Set(const ::std::string* default_value,
const ::std::string& value, ::google::protobuf::Arena* arena) {
if (ptr_ == default_value) {
CreateInstance(arena, &value);
} else {
*ptr_ = value;
}
}
// Basic accessors.
inline const ::std::string& Get() const { return *ptr_; }
inline ::std::string* Mutable(const ::std::string* default_value,
::google::protobuf::Arena* arena) {
if (ptr_ == default_value) {
CreateInstance(arena, default_value);
}
return ptr_;
}
// Release returns a ::std::string* instance that is heap-allocated and is not
// Own()'d by any arena. If the field was not set, it returns NULL. The caller
// retains ownership. Clears this field back to NULL state. Used to implement
// release_<field>() methods on generated classes.
inline ::std::string* Release(const ::std::string* default_value,
::google::protobuf::Arena* arena) {
if (ptr_ == default_value) {
return NULL;
}
::std::string* released = NULL;
if (arena != NULL) {
// ptr_ is owned by the arena -- we need to return a copy.
released = new ::std::string(*ptr_);
} else {
released = ptr_;
}
ptr_ = const_cast< ::std::string* >(default_value);
return released;
}
// UnsafeArenaRelease returns a ::std::string*, but it may be arena-owned (i.e.
// have its destructor already registered) if arena != NULL. If the field was
// not set, this returns NULL. This method clears this field back to NULL
// state. Used to implement unsafe_arena_release_<field>() methods on
// generated classes.
inline ::std::string* UnsafeArenaRelease(const ::std::string* default_value,
::google::protobuf::Arena* /* arena */) {
if (ptr_ == default_value) {
return NULL;
}
::std::string* released = ptr_;
ptr_ = const_cast< ::std::string* >(default_value);
return released;
}
// Takes a string that is heap-allocated, and takes ownership. The string's
// destructor is registered with the arena. Used to implement
// set_allocated_<field> in generated classes.
inline void SetAllocated(const ::std::string* default_value,
::std::string* value, ::google::protobuf::Arena* arena) {
if (arena == NULL && ptr_ != default_value) {
Destroy(default_value, arena);
}
if (value != NULL) {
ptr_ = value;
if (arena != NULL) {
arena->Own(value);
}
} else {
ptr_ = const_cast< ::std::string* >(default_value);
}
}
// Takes a string that has lifetime equal to the arena's lifetime. The arena
// must be non-null. It is safe only to pass this method a value returned by
// UnsafeArenaRelease() on another field of a message in the same arena. Used
// to implement unsafe_arena_set_allocated_<field> in generated classes.
inline void UnsafeArenaSetAllocated(const ::std::string* default_value,
::std::string* value,
::google::protobuf::Arena* /* arena */) {
if (value != NULL) {
ptr_ = value;
} else {
ptr_ = const_cast< ::std::string* >(default_value);
}
}
// Swaps internal pointers. Arena-safety semantics: this is guarded by the
// logic in Swap()/UnsafeArenaSwap() at the message level, so this method is
// 'unsafe' if called directly.
GOOGLE_ATTRIBUTE_ALWAYS_INLINE void Swap(ArenaStringPtr* other) {
std::swap(ptr_, other->ptr_);
}
// Frees storage (if not on an arena).
inline void Destroy(const ::std::string* default_value,
::google::protobuf::Arena* arena) {
if (arena == NULL && ptr_ != default_value) {
delete ptr_;
}
}
// Clears content, but keeps allocated string if arena != NULL, to avoid the
// overhead of heap operations. After this returns, the content (as seen by
// the user) will always be the empty string. Assumes that |default_value|
// is an empty string.
inline void ClearToEmpty(const ::std::string* default_value,
::google::protobuf::Arena* /* arena */) {
if (ptr_ == default_value) {
// Already set to default (which is empty) -- do nothing.
} else {
ptr_->clear();
}
}
// Clears content, but keeps allocated string if arena != NULL, to avoid the
// overhead of heap operations. After this returns, the content (as seen by
// the user) will always be equal to |default_value|.
inline void ClearToDefault(const ::std::string* default_value,
::google::protobuf::Arena* /* arena */) {
if (ptr_ == default_value) {
// Already set to default -- do nothing.
} else {
// Have another allocated string -- rather than throwing this away and
// resetting ptr_ to the canonical default string instance, we just reuse
// this instance.
*ptr_ = *default_value;
}
}
// Called from generated code / reflection runtime only. Resets value to point
// to a default string pointer, with the semantics that this ArenaStringPtr
// does not own the pointed-to memory. Disregards initial value of ptr_ (so
// this is the *ONLY* safe method to call after construction or when
// reinitializing after becoming the active field in a oneof union).
inline void UnsafeSetDefault(const ::std::string* default_value) {
// Casting away 'const' is safe here: accessors ensure that ptr_ is only
// returned as a const if it is equal to default_value.
ptr_ = const_cast< ::std::string* >(default_value);
}
// The 'NoArena' variants of methods below assume arena == NULL and are
// optimized to provide very little overhead relative to a raw string pointer
// (while still being in-memory compatible with other code that assumes
// ArenaStringPtr). Note the invariant that a class instance that has only
// ever been mutated by NoArena methods must *only* be in the String state
// (i.e., tag bits are not used), *NEVER* ArenaString. This allows all
// tagged-pointer manipulations to be avoided.
inline void SetNoArena(const ::std::string* default_value,
const ::std::string& value) {
if (ptr_ == default_value) {
CreateInstanceNoArena(&value);
} else {
*ptr_ = value;
}
}
#if LANG_CXX11
void SetNoArena(const ::std::string* default_value, ::std::string&& value) {
if (IsDefault(default_value)) {
ptr_ = new ::std::string(std::move(value));
} else {
*ptr_ = std::move(value);
}
}
#endif
void AssignWithDefault(const ::std::string* default_value, ArenaStringPtr value);
inline const ::std::string& GetNoArena() const { return *ptr_; }
inline ::std::string* MutableNoArena(const ::std::string* default_value) {
if (ptr_ == default_value) {
CreateInstanceNoArena(default_value);
}
return ptr_;
}
inline ::std::string* ReleaseNoArena(const ::std::string* default_value) {
if (ptr_ == default_value) {
return NULL;
} else {
::std::string* released = ptr_;
ptr_ = const_cast< ::std::string* >(default_value);
return released;
}
}
inline void SetAllocatedNoArena(const ::std::string* default_value,
::std::string* value) {
if (ptr_ != default_value) {
delete ptr_;
}
if (value != NULL) {
ptr_ = value;
} else {
ptr_ = const_cast< ::std::string* >(default_value);
}
}
inline void DestroyNoArena(const ::std::string* default_value) {
if (ptr_ != default_value) {
delete ptr_;
}
}
inline void ClearToEmptyNoArena(const ::std::string* default_value) {
if (ptr_ == default_value) {
// Nothing: already equal to default (which is the empty string).
} else {
ptr_->clear();
}
}
inline void ClearToDefaultNoArena(const ::std::string* default_value) {
if (ptr_ == default_value) {
// Nothing: already set to default.
} else {
// Reuse existing allocated instance.
*ptr_ = *default_value;
}
}
// Internal accessor used only at parse time to provide direct access to the
// raw pointer from the shared parse routine (in the non-arenas case). The
// parse routine does the string allocation in order to save code size in the
// generated parsing code.
inline ::std::string** UnsafeRawStringPointer() {
return &ptr_;
}
inline bool IsDefault(const ::std::string* default_value) const {
return ptr_ == default_value;
}
private:
::std::string* ptr_;
GOOGLE_ATTRIBUTE_NOINLINE void CreateInstance(::google::protobuf::Arena* arena,
const ::std::string* initial_value) {
GOOGLE_DCHECK(initial_value != NULL);
ptr_ = new ::std::string(*initial_value);
if (arena != NULL) {
arena->Own(ptr_);
}
}
GOOGLE_ATTRIBUTE_NOINLINE void CreateInstanceNoArena(const ::std::string* initial_value) {
GOOGLE_DCHECK(initial_value != NULL);
ptr_ = new ::std::string(*initial_value);
}
};
} // namespace internal
} // namespace protobuf
namespace protobuf {
namespace internal {
inline void ArenaStringPtr::AssignWithDefault(const ::std::string* default_value,
ArenaStringPtr value) {
const ::std::string* me = *UnsafeRawStringPointer();
const ::std::string* other = *value.UnsafeRawStringPointer();
// If the pointers are the same then do nothing.
if (me != other) {
SetNoArena(default_value, value.GetNoArena());
}
}
} // namespace internal
} // namespace protobuf
} // namespace google
#endif // GOOGLE_PROTOBUF_ARENASTRING_H__
| 1 | 0.873638 | 1 | 0.873638 | game-dev | MEDIA | 0.18571 | game-dev | 0.748312 | 1 | 0.748312 |
Mrmaxmeier/BombSquad-Community-Mod-Manager | 3,189 | mods/frozenone.py | import bs
from bsChosenOne import ChosenOneGame
def bsGetAPIVersion():
return 4
def bsGetGames():
return [FrozenOneGame]
class FrozenOneGame(ChosenOneGame):
@classmethod
def getName(cls):
return 'Frozen One'
@classmethod
def getDescription(cls,sessionType):
return ('Be the Frozen one for a length of time to win.\n'
'Kill the Frozen one to become it.')
@classmethod
def getSettings(cls, sessionType):
return [('Frozen One Time', {'default': 30, 'increment': 10, 'minValue': 10}),
('Frozen One Gets Gloves', {'default': True}),
('Time Limit',
{'choices': [('None', 0),
('1 Minute', 60),
('2 Minutes', 120),
('5 Minutes', 300),
('10 Minutes', 600),
('20 Minutes', 1200)],
'default': 0}),
('Respawn Times',
{'choices': [('Shorter', 0.25),
('Short', 0.5),
('Normal', 1.0),
('Long', 2.0),
('Longer', 4.0)],
'default': 1.0}),
('Epic Mode', {'default': False})]
def onTeamJoin(self,team):
team.gameData['timeRemaining'] = self.settings["Frozen One Time"]
self._updateScoreBoard()
def endGame(self):
results = bs.TeamGameResults()
for team in self.teams: results.setTeamScore(team,self.settings['Frozen One Time'] - team.gameData['timeRemaining'])
self.end(results=results,announceDelay=0)
def _setChosenOnePlayer(self, player):
try:
for p in self.players: p.gameData['FrozenLight'] = None
bs.playSound(self._swipSound)
if player is None or not player.exists():
self._flag = bs.Flag(color=(1,0.9,0.2),
position=self._flagSpawnPos,
touchable=False)
self._chosenOnePlayer = None
l = bs.newNode('light',
owner=self._flag.node,
attrs={'position': self._flagSpawnPos,
'intensity':0.6,
'heightAttenuated':False,
'volumeIntensityScale':0.1,
'radius':0.1,
'color': (1.2,1.2,0.4)})
self._flashFlagSpawn()
else:
if player.actor is not None:
self._flag = None
self._chosenOnePlayer = player
if player.actor.node.exists():
if self.settings['Frozen One Gets Gloves']: player.actor.handleMessage(bs.PowerupMessage('punch'))
player.actor.frozen = True
player.actor.node.frozen = 1
# use a color that's partway between their team color and white
color = [0.3+c*0.7 for c in bs.getNormalizedColor(player.getTeam().color)]
l = player.gameData['FrozenLight'] = bs.NodeActor(bs.newNode('light',
attrs={"intensity":0.6,
"heightAttenuated":False,
"volumeIntensityScale":0.1,
"radius":0.13,
"color": color}))
bs.animate(l.node, 'intensity', {0:1.0, 200:0.4, 400:1.0}, loop=True)
player.actor.node.connectAttr('position',l.node,'position')
except Exception, e:
import traceback
print 'EXC in _setChosenOnePlayer'
traceback.print_exc(e)
traceback.print_stack()
def _updateScoreBoard(self):
for team in self.teams:
self._scoreBoard.setTeamValue(team,team.gameData['timeRemaining'],self.settings['Frozen One Time'], countdown=True)
| 1 | 0.817826 | 1 | 0.817826 | game-dev | MEDIA | 0.836164 | game-dev | 0.937094 | 1 | 0.937094 |
egordorichev/BurningKnight | 4,767 | BurningKnight/entity/projectile/ProjectileBuilder.cs | using System;
using BurningKnight.assets.lighting;
using BurningKnight.entity.buff;
using BurningKnight.entity.component;
using BurningKnight.entity.creature.mob;
using BurningKnight.entity.creature.mob.boss;
using BurningKnight.entity.creature.player;
using BurningKnight.entity.events;
using BurningKnight.entity.item;
using BurningKnight.save;
using BurningKnight.state;
using BurningKnight.util;
using Lens.entity;
using Lens.util;
using Lens.util.math;
using Microsoft.Xna.Framework;
using VelcroPhysics.Dynamics;
namespace BurningKnight.entity.projectile {
public class ProjectileBuilder {
public Entity Owner;
private Projectile parent;
public Projectile Parent {
get => parent;
set {
if (value != null) {
Color = value.Color;
}
parent = value;
}
}
public ProjectileFlags Flags = Projectile.DefaultFlags;
public string Slice;
public Vector2 Velocity;
public Vector2 Offset;
public float Scale = 1f;
public float Damage = 1f;
public float Range = -1f;
public bool RectHitbox;
public bool Poof;
public Color Color = ProjectileColor.Red;
public float LightRadius;
public int Bounce;
private bool empty;
public ProjectileBuilder(Entity projectileOwner, string projectileSlice) {
if (projectileSlice == "default") {
projectileSlice = "rect";
}
Slice = projectileSlice;
Owner = projectileOwner;
if (Owner is Mob mob) {
if (Rnd.Chance(LevelSave.MobDestructionChance)) {
empty = true;
return;
}
if (mob.HasPrefix) {
LightRadius = 64;
Color = Color.Black;
AddFlags(ProjectileFlags.Scourged);
}
} else if (Owner is Player || (Owner is Item item && item.Owner is Player)) {
Color = ProjectileColor.Yellow;
}
}
public ProjectileBuilder Shoot(double angle, float speed) {
Velocity = MathUtils.CreateVector(angle, speed);
return this;
}
public ProjectileBuilder Move(double angle, float distance) {
Offset = MathUtils.CreateVector(angle, distance);
return this;
}
public ProjectileBuilder AddFlags(params ProjectileFlags[] projectileFlags) {
foreach (var flag in projectileFlags) {
Flags |= flag;
}
return this;
}
public ProjectileBuilder RemoveFlags(params ProjectileFlags[] projectileFlags) {
foreach (var flag in projectileFlags) {
Flags &= ~flag;
}
return this;
}
public Projectile Build() {
if (empty || ((Owner is Mob && !(Owner is creature.bk.BurningKnight)) && Owner.Area.Tagged[Tags.MobProjectile].Count >= 199)) {
return null;
}
Item item = null;
if (Owner is Item i) {
item = i;
Owner = i.Owner;
}
var projectile = new Projectile {
Owner = Owner,
FirstOwner = Owner,
Damage = Damage,
Flags = Flags,
Slice = Slice,
Bounce = Math.Min(8, Bounce),
Scale = Scale,
Color = Color,
Parent = parent,
Item = item
};
Owner.Area.Add(projectile);
if (Owner is Mob) {
projectile.AddTag(Tags.MobProjectile);
if ((Owner is Boss && Run.Loop > 0) || Run.Loop > 1) {
projectile.AddFlags(ProjectileFlags.Scourged);
}
} else if (Owner is Player) {
projectile.AddTag(Tags.PlayerProjectile);
}
var graphics = new ProjectileGraphicsComponent("projectiles", Slice);
if (graphics.Sprite == null) {
Log.Error($"Not found projectile slice {Slice}");
empty = true;
return null;
}
projectile.AddComponent(graphics);
var w = graphics.Sprite.Source.Width * Scale;
var h = graphics.Sprite.Source.Height * Scale;
projectile.Width = w;
projectile.Height = h;
projectile.Center = Owner.Center + Offset;
BodyComponent bodyComponent;
if (RectHitbox) {
projectile.AddComponent(bodyComponent = new RectBodyComponent(0, 0, w, h, BodyType.Dynamic, false, true));
} else {
projectile.AddComponent(bodyComponent = new CircleBodyComponent(0, 0, w / 2f, BodyType.Dynamic, false, true));
}
var body = bodyComponent.Body;
body.Restitution = 1;
body.Friction = 0;
body.IsBullet = true;
body.Rotation = Velocity.ToAngle();
if (Owner.TryGetComponent<BuffsComponent>(out var buffs) && buffs.Has<SlowBuff>()) {
Velocity *= 0.5f;
}
if (Range > 0) {
// / Velocity.Length()
projectile.T = Range;
}
Velocity *= 10f;
body.LinearVelocity = Velocity;
var count = Owner.Area.Tagged[Tags.Projectile].Count;
if (count < 99) {
if (LightRadius > 0) {
projectile.AddComponent(new LightComponent(projectile, LightRadius * Scale, Color));
}
if (Poof) {
AnimationUtil.Poof(projectile.Center);
}
}
Owner.HandleEvent(new ProjectileCreatedEvent {
Owner = Owner,
Item = item,
Projectile = projectile
});
return projectile;
}
}
} | 1 | 0.788096 | 1 | 0.788096 | game-dev | MEDIA | 0.984955 | game-dev | 0.718136 | 1 | 0.718136 |
mig1023/seeker | 3,222 | Seeker/Seeker/Gamebook/CreatureOfHavoc/Paragraphs.cs | using System.Collections.Generic;
using System.Linq;
using System.Xml;
using Seeker.Game;
namespace Seeker.Gamebook.CreatureOfHavoc
{
class Paragraphs : Prototypes.Paragraphs, Abstract.IParagraphs
{
public override Paragraph Get(int id, XmlNode xmlParagraph)
{
Paragraph paragraph = ParagraphTemplate(xmlParagraph);
foreach (XmlNode xmlOption in xmlParagraph.SelectNodes("Options/*"))
{
Option option = OptionsTemplateWithoutGoto(xmlOption);
if (ThisIsGameover(xmlOption))
{
option.Goto = GetGoto(xmlOption);
}
else if (int.TryParse(xmlOption.Attributes["Goto"].Value, out int _))
{
option.Goto = Xml.IntParse(xmlOption.Attributes["Goto"]);
}
else
{
List<string> link = xmlOption.Attributes["Goto"].Value.Split(',').ToList<string>();
option.Goto = int.Parse(link[random.Next(link.Count())]);
}
XmlNode optionMod = xmlOption.SelectSingleNode("*");
if ((optionMod != null) && (optionMod["Value"] != null))
option.Do.Add(Xml.ModificationParse(optionMod, new Modification()));
paragraph.Options.Add(option);
}
foreach (XmlNode xmlAction in xmlParagraph.SelectNodes("Actions/*"))
paragraph.Actions.Add(ActionParse(xmlAction));
foreach (XmlNode xmlModification in xmlParagraph.SelectNodes("Modifications/*"))
paragraph.Modification.Add(ModificationParse(xmlModification));
return paragraph;
}
public override Abstract.IActions ActionParse(XmlNode xmlAction)
{
Actions action = (Actions)ActionTemplate(xmlAction, new Actions());
foreach (string param in GetProperties(action))
SetProperty(action, param, xmlAction);
if (xmlAction["Enemy"] != null)
{
action.Enemies = new List<Character> { EnemyParse(xmlAction["Enemy"]) };
}
else if (xmlAction["Enemies"] != null)
{
action.Enemies = new List<Character>();
foreach (XmlNode xmlEnemy in xmlAction.SelectNodes("Enemies/Enemy"))
action.Enemies.Add(EnemyParse(xmlEnemy));
}
if (action.Type == "Option")
action.Option = OptionParseWithDo(xmlAction, new Modification());
return action;
}
public override Abstract.IModification ModificationParse(XmlNode xmlModification) =>
(Abstract.IModification)base.ModificationParse(xmlModification, new Modification());
private Character EnemyParse(XmlNode xmlEnemy)
{
Character enemy = new Character();
foreach (string param in GetProperties(enemy))
SetPropertyByAttr(enemy, param, xmlEnemy, maxPrefix: true);
enemy.Mastery = enemy.MaxMastery;
enemy.Endurance = enemy.MaxEndurance;
return enemy;
}
}
}
| 1 | 0.764157 | 1 | 0.764157 | game-dev | MEDIA | 0.463362 | game-dev | 0.82556 | 1 | 0.82556 |
genxium/DelayNoMoreUnity | 52,973 | frontend/Assets/SuperTiled2Unity/Scripts/Editor/ThirdParty/LibTessDotNet/Sweep.cs | /*
** SGI FREE SOFTWARE LICENSE B (Version 2.0, Sept. 18, 2008)
** Copyright (C) 2011 Silicon Graphics, Inc.
** All Rights Reserved.
**
** 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 including the dates of first publication and either this
** permission notice or a reference to http://oss.sgi.com/projects/FreeB/ 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 SILICON GRAPHICS, INC.
** 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.
**
** Except as contained in this notice, the name of Silicon Graphics, Inc. shall not
** be used in advertising or otherwise to promote the sale, use or other dealings in
** this Software without prior written authorization from Silicon Graphics, Inc.
*/
/*
** Original Author: Eric Veach, July 1994.
** libtess2: Mikko Mononen, http://code.google.com/p/libtess2/.
** LibTessDotNet: Remi Gillig, https://github.com/speps/LibTessDotNet
*/
// Seanba edit: Put LibTessDotNet in unique namespace so avoid name collisions
// Seanba edit: Namespace modifications not supported by Unity
using System;
using System.Diagnostics;
//#if DOUBLE
//using Real = System.Double;
//namespace LibTessDotNet.Double
//#else
using Real = System.Single;
namespace SuperTiled2Unity.Editor.LibTessDotNet
//#endif
{
public partial class Tess
{
internal class ActiveRegion : Pooled<ActiveRegion>
{
internal MeshUtils.Edge _eUp;
internal Dict<ActiveRegion>.Node _nodeUp;
internal int _windingNumber;
internal bool _inside, _sentinel, _dirty, _fixUpperEdge;
public void Init(IPool pool)
{
}
public void Reset(IPool pool)
{
_eUp = null;
_nodeUp = null;
_windingNumber = 0;
_inside = false;
_sentinel = false;
_dirty = false;
_fixUpperEdge = false;
}
}
private ActiveRegion RegionBelow(ActiveRegion reg)
{
return reg._nodeUp._prev._key;
}
private ActiveRegion RegionAbove(ActiveRegion reg)
{
return reg._nodeUp._next._key;
}
/// <summary>
/// Both edges must be directed from right to left (this is the canonical
/// direction for the upper edge of each region).
///
/// The strategy is to evaluate a "t" value for each edge at the
/// current sweep line position, given by tess->event. The calculations
/// are designed to be very stable, but of course they are not perfect.
///
/// Special case: if both edge destinations are at the sweep event,
/// we sort the edges by slope (they would otherwise compare equally).
/// </summary>
private bool EdgeLeq(ActiveRegion reg1, ActiveRegion reg2)
{
var e1 = reg1._eUp;
var e2 = reg2._eUp;
if (e1._Dst == _event)
{
if (e2._Dst == _event)
{
// Two edges right of the sweep line which meet at the sweep event.
// Sort them by slope.
if (Geom.VertLeq(e1._Org, e2._Org))
{
return Geom.EdgeSign(e2._Dst, e1._Org, e2._Org) <= 0.0f;
}
return Geom.EdgeSign(e1._Dst, e2._Org, e1._Org) >= 0.0f;
}
return Geom.EdgeSign(e2._Dst, _event, e2._Org) <= 0.0f;
}
if (e2._Dst == _event)
{
return Geom.EdgeSign(e1._Dst, _event, e1._Org) >= 0.0f;
}
// General case - compute signed distance *from* e1, e2 to event
var t1 = Geom.EdgeEval(e1._Dst, _event, e1._Org);
var t2 = Geom.EdgeEval(e2._Dst, _event, e2._Org);
return (t1 >= t2);
}
private void DeleteRegion(ActiveRegion reg)
{
if (reg._fixUpperEdge)
{
// It was created with zero winding number, so it better be
// deleted with zero winding number (ie. it better not get merged
// with a real edge).
Debug.Assert(reg._eUp._winding == 0);
}
reg._eUp._activeRegion = null;
_dict.Remove(reg._nodeUp);
_pool.Return(reg);
}
/// <summary>
/// Replace an upper edge which needs fixing (see ConnectRightVertex).
/// </summary>
private void FixUpperEdge(ActiveRegion reg, MeshUtils.Edge newEdge)
{
Debug.Assert(reg._fixUpperEdge);
_mesh.Delete(_pool, reg._eUp);
reg._fixUpperEdge = false;
reg._eUp = newEdge;
newEdge._activeRegion = reg;
}
private ActiveRegion TopLeftRegion(ActiveRegion reg)
{
var org = reg._eUp._Org;
// Find the region above the uppermost edge with the same origin
do {
reg = RegionAbove(reg);
} while (reg._eUp._Org == org);
// If the edge above was a temporary edge introduced by ConnectRightVertex,
// now is the time to fix it.
if (reg._fixUpperEdge)
{
var e = _mesh.Connect(_pool, RegionBelow(reg)._eUp._Sym, reg._eUp._Lnext);
FixUpperEdge(reg, e);
reg = RegionAbove(reg);
}
return reg;
}
private ActiveRegion TopRightRegion(ActiveRegion reg)
{
var dst = reg._eUp._Dst;
// Find the region above the uppermost edge with the same destination
do {
reg = RegionAbove(reg);
} while (reg._eUp._Dst == dst);
return reg;
}
/// <summary>
/// Add a new active region to the sweep line, *somewhere* below "regAbove"
/// (according to where the new edge belongs in the sweep-line dictionary).
/// The upper edge of the new region will be "eNewUp".
/// Winding number and "inside" flag are not updated.
/// </summary>
private ActiveRegion AddRegionBelow(ActiveRegion regAbove, MeshUtils.Edge eNewUp)
{
var regNew = _pool.Get<ActiveRegion>();
regNew._eUp = eNewUp;
regNew._nodeUp = _dict.InsertBefore(regAbove._nodeUp, regNew);
regNew._fixUpperEdge = false;
regNew._sentinel = false;
regNew._dirty = false;
eNewUp._activeRegion = regNew;
return regNew;
}
private void ComputeWinding(ActiveRegion reg)
{
reg._windingNumber = RegionAbove(reg)._windingNumber + reg._eUp._winding;
reg._inside = Geom.IsWindingInside(_windingRule, reg._windingNumber);
}
/// <summary>
/// Delete a region from the sweep line. This happens when the upper
/// and lower chains of a region meet (at a vertex on the sweep line).
/// The "inside" flag is copied to the appropriate mesh face (we could
/// not do this before -- since the structure of the mesh is always
/// changing, this face may not have even existed until now).
/// </summary>
private void FinishRegion(ActiveRegion reg)
{
var e = reg._eUp;
var f = e._Lface;
f._inside = reg._inside;
f._anEdge = e;
DeleteRegion(reg);
}
/// <summary>
/// We are given a vertex with one or more left-going edges. All affected
/// edges should be in the edge dictionary. Starting at regFirst->eUp,
/// we walk down deleting all regions where both edges have the same
/// origin vOrg. At the same time we copy the "inside" flag from the
/// active region to the face, since at this point each face will belong
/// to at most one region (this was not necessarily true until this point
/// in the sweep). The walk stops at the region above regLast; if regLast
/// is null we walk as far as possible. At the same time we relink the
/// mesh if necessary, so that the ordering of edges around vOrg is the
/// same as in the dictionary.
/// </summary>
private MeshUtils.Edge FinishLeftRegions(ActiveRegion regFirst, ActiveRegion regLast)
{
var regPrev = regFirst;
var ePrev = regFirst._eUp;
while (regPrev != regLast)
{
regPrev._fixUpperEdge = false; // placement was OK
var reg = RegionBelow(regPrev);
var e = reg._eUp;
if (e._Org != ePrev._Org)
{
if (!reg._fixUpperEdge)
{
// Remove the last left-going edge. Even though there are no further
// edges in the dictionary with this origin, there may be further
// such edges in the mesh (if we are adding left edges to a vertex
// that has already been processed). Thus it is important to call
// FinishRegion rather than just DeleteRegion.
FinishRegion(regPrev);
break;
}
// If the edge below was a temporary edge introduced by
// ConnectRightVertex, now is the time to fix it.
e = _mesh.Connect(_pool, ePrev._Lprev, e._Sym);
FixUpperEdge(reg, e);
}
// Relink edges so that ePrev.Onext == e
if (ePrev._Onext != e)
{
_mesh.Splice(_pool, e._Oprev, e);
_mesh.Splice(_pool, ePrev, e);
}
FinishRegion(regPrev); // may change reg.eUp
ePrev = reg._eUp;
regPrev = reg;
}
return ePrev;
}
/// <summary>
/// Purpose: insert right-going edges into the edge dictionary, and update
/// winding numbers and mesh connectivity appropriately. All right-going
/// edges share a common origin vOrg. Edges are inserted CCW starting at
/// eFirst; the last edge inserted is eLast.Oprev. If vOrg has any
/// left-going edges already processed, then eTopLeft must be the edge
/// such that an imaginary upward vertical segment from vOrg would be
/// contained between eTopLeft.Oprev and eTopLeft; otherwise eTopLeft
/// should be null.
/// </summary>
private void AddRightEdges(ActiveRegion regUp, MeshUtils.Edge eFirst, MeshUtils.Edge eLast, MeshUtils.Edge eTopLeft, bool cleanUp)
{
bool firstTime = true;
var e = eFirst; do
{
Debug.Assert(Geom.VertLeq(e._Org, e._Dst));
AddRegionBelow(regUp, e._Sym);
e = e._Onext;
} while (e != eLast);
// Walk *all* right-going edges from e.Org, in the dictionary order,
// updating the winding numbers of each region, and re-linking the mesh
// edges to match the dictionary ordering (if necessary).
if (eTopLeft == null)
{
eTopLeft = RegionBelow(regUp)._eUp._Rprev;
}
ActiveRegion regPrev = regUp, reg;
var ePrev = eTopLeft;
while (true)
{
reg = RegionBelow(regPrev);
e = reg._eUp._Sym;
if (e._Org != ePrev._Org) break;
if (e._Onext != ePrev)
{
// Unlink e from its current position, and relink below ePrev
_mesh.Splice(_pool, e._Oprev, e);
_mesh.Splice(_pool, ePrev._Oprev, e);
}
// Compute the winding number and "inside" flag for the new regions
reg._windingNumber = regPrev._windingNumber - e._winding;
reg._inside = Geom.IsWindingInside(_windingRule, reg._windingNumber);
// Check for two outgoing edges with same slope -- process these
// before any intersection tests (see example in tessComputeInterior).
regPrev._dirty = true;
if (!firstTime && CheckForRightSplice(regPrev))
{
Geom.AddWinding(e, ePrev);
DeleteRegion(regPrev);
_mesh.Delete(_pool, ePrev);
}
firstTime = false;
regPrev = reg;
ePrev = e;
}
regPrev._dirty = true;
Debug.Assert(regPrev._windingNumber - e._winding == reg._windingNumber);
if (cleanUp)
{
// Check for intersections between newly adjacent edges.
WalkDirtyRegions(regPrev);
}
}
/// <summary>
/// Two vertices with idential coordinates are combined into one.
/// e1.Org is kept, while e2.Org is discarded.
/// </summary>
private void SpliceMergeVertices(MeshUtils.Edge e1, MeshUtils.Edge e2)
{
_mesh.Splice(_pool, e1, e2);
}
/// <summary>
/// Find some weights which describe how the intersection vertex is
/// a linear combination of "org" and "dest". Each of the two edges
/// which generated "isect" is allocated 50% of the weight; each edge
/// splits the weight between its org and dst according to the
/// relative distance to "isect".
/// </summary>
private void VertexWeights(MeshUtils.Vertex isect, MeshUtils.Vertex org, MeshUtils.Vertex dst, out Real w0, out Real w1)
{
var t1 = Geom.VertL1dist(org, isect);
var t2 = Geom.VertL1dist(dst, isect);
w0 = (t2 / (t1 + t2)) / 2.0f;
w1 = (t1 / (t1 + t2)) / 2.0f;
isect._coords.X += w0 * org._coords.X + w1 * dst._coords.X;
isect._coords.Y += w0 * org._coords.Y + w1 * dst._coords.Y;
isect._coords.Z += w0 * org._coords.Z + w1 * dst._coords.Z;
}
/// <summary>
/// We've computed a new intersection point, now we need a "data" pointer
/// from the user so that we can refer to this new vertex in the
/// rendering callbacks.
/// </summary>
private void GetIntersectData(MeshUtils.Vertex isect, MeshUtils.Vertex orgUp, MeshUtils.Vertex dstUp, MeshUtils.Vertex orgLo, MeshUtils.Vertex dstLo)
{
isect._coords = Vec3.Zero;
Real w0, w1, w2, w3;
VertexWeights(isect, orgUp, dstUp, out w0, out w1);
VertexWeights(isect, orgLo, dstLo, out w2, out w3);
if (_combineCallback != null)
{
isect._data = _combineCallback(
isect._coords,
new object[] { orgUp._data, dstUp._data, orgLo._data, dstLo._data },
new Real[] { w0, w1, w2, w3 }
);
}
}
/// <summary>
/// Check the upper and lower edge of "regUp", to make sure that the
/// eUp->Org is above eLo, or eLo->Org is below eUp (depending on which
/// origin is leftmost).
///
/// The main purpose is to splice right-going edges with the same
/// dest vertex and nearly identical slopes (ie. we can't distinguish
/// the slopes numerically). However the splicing can also help us
/// to recover from numerical errors. For example, suppose at one
/// point we checked eUp and eLo, and decided that eUp->Org is barely
/// above eLo. Then later, we split eLo into two edges (eg. from
/// a splice operation like this one). This can change the result of
/// our test so that now eUp->Org is incident to eLo, or barely below it.
/// We must correct this condition to maintain the dictionary invariants.
///
/// One possibility is to check these edges for intersection again
/// (ie. CheckForIntersect). This is what we do if possible. However
/// CheckForIntersect requires that tess->event lies between eUp and eLo,
/// so that it has something to fall back on when the intersection
/// calculation gives us an unusable answer. So, for those cases where
/// we can't check for intersection, this routine fixes the problem
/// by just splicing the offending vertex into the other edge.
/// This is a guaranteed solution, no matter how degenerate things get.
/// Basically this is a combinatorial solution to a numerical problem.
/// </summary>
private bool CheckForRightSplice(ActiveRegion regUp)
{
var regLo = RegionBelow(regUp);
var eUp = regUp._eUp;
var eLo = regLo._eUp;
if (Geom.VertLeq(eUp._Org, eLo._Org))
{
if (Geom.EdgeSign(eLo._Dst, eUp._Org, eLo._Org) > 0.0f)
{
return false;
}
// eUp.Org appears to be below eLo
if (!Geom.VertEq(eUp._Org, eLo._Org))
{
// Splice eUp._Org into eLo
_mesh.SplitEdge(_pool, eLo._Sym);
_mesh.Splice(_pool, eUp, eLo._Oprev);
regUp._dirty = regLo._dirty = true;
}
else if (eUp._Org != eLo._Org)
{
// merge the two vertices, discarding eUp.Org
_pq.Remove(eUp._Org._pqHandle);
SpliceMergeVertices(eLo._Oprev, eUp);
}
}
else
{
if (Geom.EdgeSign(eUp._Dst, eLo._Org, eUp._Org) < 0.0f)
{
return false;
}
// eLo.Org appears to be above eUp, so splice eLo.Org into eUp
RegionAbove(regUp)._dirty = regUp._dirty = true;
_mesh.SplitEdge(_pool, eUp._Sym);
_mesh.Splice(_pool, eLo._Oprev, eUp);
}
return true;
}
/// <summary>
/// Check the upper and lower edge of "regUp", to make sure that the
/// eUp->Dst is above eLo, or eLo->Dst is below eUp (depending on which
/// destination is rightmost).
///
/// Theoretically, this should always be true. However, splitting an edge
/// into two pieces can change the results of previous tests. For example,
/// suppose at one point we checked eUp and eLo, and decided that eUp->Dst
/// is barely above eLo. Then later, we split eLo into two edges (eg. from
/// a splice operation like this one). This can change the result of
/// the test so that now eUp->Dst is incident to eLo, or barely below it.
/// We must correct this condition to maintain the dictionary invariants
/// (otherwise new edges might get inserted in the wrong place in the
/// dictionary, and bad stuff will happen).
///
/// We fix the problem by just splicing the offending vertex into the
/// other edge.
/// </summary>
private bool CheckForLeftSplice(ActiveRegion regUp)
{
var regLo = RegionBelow(regUp);
var eUp = regUp._eUp;
var eLo = regLo._eUp;
Debug.Assert(!Geom.VertEq(eUp._Dst, eLo._Dst));
if (Geom.VertLeq(eUp._Dst, eLo._Dst))
{
if (Geom.EdgeSign(eUp._Dst, eLo._Dst, eUp._Org) < 0.0f)
{
return false;
}
// eLo.Dst is above eUp, so splice eLo.Dst into eUp
RegionAbove(regUp)._dirty = regUp._dirty = true;
var e = _mesh.SplitEdge(_pool, eUp);
_mesh.Splice(_pool, eLo._Sym, e);
e._Lface._inside = regUp._inside;
}
else
{
if (Geom.EdgeSign(eLo._Dst, eUp._Dst, eLo._Org) > 0.0f)
{
return false;
}
// eUp.Dst is below eLo, so splice eUp.Dst into eLo
regUp._dirty = regLo._dirty = true;
var e = _mesh.SplitEdge(_pool, eLo);
_mesh.Splice(_pool, eUp._Lnext, eLo._Sym);
e._Rface._inside = regUp._inside;
}
return true;
}
/// <summary>
/// Check the upper and lower edges of the given region to see if
/// they intersect. If so, create the intersection and add it
/// to the data structures.
///
/// Returns TRUE if adding the new intersection resulted in a recursive
/// call to AddRightEdges(); in this case all "dirty" regions have been
/// checked for intersections, and possibly regUp has been deleted.
/// </summary>
private bool CheckForIntersect(ActiveRegion regUp)
{
var regLo = RegionBelow(regUp);
var eUp = regUp._eUp;
var eLo = regLo._eUp;
var orgUp = eUp._Org;
var orgLo = eLo._Org;
var dstUp = eUp._Dst;
var dstLo = eLo._Dst;
Debug.Assert(!Geom.VertEq(dstLo, dstUp));
Debug.Assert(Geom.EdgeSign(dstUp, _event, orgUp) <= 0.0f);
Debug.Assert(Geom.EdgeSign(dstLo, _event, orgLo) >= 0.0f);
Debug.Assert(orgUp != _event && orgLo != _event);
Debug.Assert(!regUp._fixUpperEdge && !regLo._fixUpperEdge);
if( orgUp == orgLo )
{
// right endpoints are the same
return false;
}
var tMinUp = Math.Min(orgUp._t, dstUp._t);
var tMaxLo = Math.Max(orgLo._t, dstLo._t);
if( tMinUp > tMaxLo )
{
// t ranges do not overlap
return false;
}
if (Geom.VertLeq(orgUp, orgLo))
{
if (Geom.EdgeSign( dstLo, orgUp, orgLo ) > 0.0f)
{
return false;
}
}
else
{
if (Geom.EdgeSign( dstUp, orgLo, orgUp ) < 0.0f)
{
return false;
}
}
// At this point the edges intersect, at least marginally
var isect = _pool.Get<MeshUtils.Vertex>();
Geom.EdgeIntersect(dstUp, orgUp, dstLo, orgLo, isect);
// The following properties are guaranteed:
Debug.Assert(Math.Min(orgUp._t, dstUp._t) <= isect._t);
Debug.Assert(isect._t <= Math.Max(orgLo._t, dstLo._t));
Debug.Assert(Math.Min(dstLo._s, dstUp._s) <= isect._s);
Debug.Assert(isect._s <= Math.Max(orgLo._s, orgUp._s));
if (Geom.VertLeq(isect, _event))
{
// The intersection point lies slightly to the left of the sweep line,
// so move it until it''s slightly to the right of the sweep line.
// (If we had perfect numerical precision, this would never happen
// in the first place). The easiest and safest thing to do is
// replace the intersection by tess._event.
isect._s = _event._s;
isect._t = _event._t;
}
// Similarly, if the computed intersection lies to the right of the
// rightmost origin (which should rarely happen), it can cause
// unbelievable inefficiency on sufficiently degenerate inputs.
// (If you have the test program, try running test54.d with the
// "X zoom" option turned on).
var orgMin = Geom.VertLeq(orgUp, orgLo) ? orgUp : orgLo;
if (Geom.VertLeq(orgMin, isect))
{
isect._s = orgMin._s;
isect._t = orgMin._t;
}
if (Geom.VertEq(isect, orgUp) || Geom.VertEq(isect, orgLo))
{
// Easy case -- intersection at one of the right endpoints
CheckForRightSplice(regUp);
_pool.Return(isect);
return false;
}
if ( (! Geom.VertEq(dstUp, _event)
&& Geom.EdgeSign(dstUp, _event, isect) >= 0.0f)
|| (! Geom.VertEq(dstLo, _event)
&& Geom.EdgeSign(dstLo, _event, isect) <= 0.0f))
{
// Very unusual -- the new upper or lower edge would pass on the
// wrong side of the sweep event, or through it. This can happen
// due to very small numerical errors in the intersection calculation.
if (dstLo == _event)
{
// Splice dstLo into eUp, and process the new region(s)
_mesh.SplitEdge(_pool, eUp._Sym);
_mesh.Splice(_pool, eLo._Sym, eUp);
regUp = TopLeftRegion(regUp);
eUp = RegionBelow(regUp)._eUp;
FinishLeftRegions(RegionBelow(regUp), regLo);
AddRightEdges(regUp, eUp._Oprev, eUp, eUp, true);
_pool.Return(isect);
return true;
}
if( dstUp == _event ) {
/* Splice dstUp into eLo, and process the new region(s) */
_mesh.SplitEdge(_pool, eLo._Sym);
_mesh.Splice(_pool, eUp._Lnext, eLo._Oprev);
regLo = regUp;
regUp = TopRightRegion(regUp);
var e = RegionBelow(regUp)._eUp._Rprev;
regLo._eUp = eLo._Oprev;
eLo = FinishLeftRegions(regLo, null);
AddRightEdges(regUp, eLo._Onext, eUp._Rprev, e, true);
_pool.Return(isect);
return true;
}
// Special case: called from ConnectRightVertex. If either
// edge passes on the wrong side of tess._event, split it
// (and wait for ConnectRightVertex to splice it appropriately).
if (Geom.EdgeSign( dstUp, _event, isect ) >= 0.0f)
{
RegionAbove(regUp)._dirty = regUp._dirty = true;
_mesh.SplitEdge(_pool, eUp._Sym);
eUp._Org._s = _event._s;
eUp._Org._t = _event._t;
}
if (Geom.EdgeSign(dstLo, _event, isect) <= 0.0f)
{
regUp._dirty = regLo._dirty = true;
_mesh.SplitEdge(_pool, eLo._Sym);
eLo._Org._s = _event._s;
eLo._Org._t = _event._t;
}
// leave the rest for ConnectRightVertex
_pool.Return(isect);
return false;
}
// General case -- split both edges, splice into new vertex.
// When we do the splice operation, the order of the arguments is
// arbitrary as far as correctness goes. However, when the operation
// creates a new face, the work done is proportional to the size of
// the new face. We expect the faces in the processed part of
// the mesh (ie. eUp._Lface) to be smaller than the faces in the
// unprocessed original contours (which will be eLo._Oprev._Lface).
_mesh.SplitEdge(_pool, eUp._Sym);
_mesh.SplitEdge(_pool, eLo._Sym);
_mesh.Splice(_pool, eLo._Oprev, eUp);
eUp._Org._s = isect._s;
eUp._Org._t = isect._t;
_pool.Return(isect);
isect = null;
eUp._Org._pqHandle = _pq.Insert(eUp._Org);
if (eUp._Org._pqHandle._handle == PQHandle.Invalid)
{
throw new InvalidOperationException("PQHandle should not be invalid");
}
GetIntersectData(eUp._Org, orgUp, dstUp, orgLo, dstLo);
RegionAbove(regUp)._dirty = regUp._dirty = regLo._dirty = true;
return false;
}
/// <summary>
/// When the upper or lower edge of any region changes, the region is
/// marked "dirty". This routine walks through all the dirty regions
/// and makes sure that the dictionary invariants are satisfied
/// (see the comments at the beginning of this file). Of course
/// new dirty regions can be created as we make changes to restore
/// the invariants.
/// </summary>
private void WalkDirtyRegions(ActiveRegion regUp)
{
var regLo = RegionBelow(regUp);
MeshUtils.Edge eUp, eLo;
while (true)
{
// Find the lowest dirty region (we walk from the bottom up).
while (regLo._dirty)
{
regUp = regLo;
regLo = RegionBelow(regLo);
}
if (!regUp._dirty)
{
regLo = regUp;
regUp = RegionAbove( regUp );
if(regUp == null || !regUp._dirty)
{
// We've walked all the dirty regions
return;
}
}
regUp._dirty = false;
eUp = regUp._eUp;
eLo = regLo._eUp;
if (eUp._Dst != eLo._Dst)
{
// Check that the edge ordering is obeyed at the Dst vertices.
if (CheckForLeftSplice(regUp))
{
// If the upper or lower edge was marked fixUpperEdge, then
// we no longer need it (since these edges are needed only for
// vertices which otherwise have no right-going edges).
if (regLo._fixUpperEdge)
{
DeleteRegion(regLo);
_mesh.Delete(_pool, eLo);
regLo = RegionBelow(regUp);
eLo = regLo._eUp;
}
else if( regUp._fixUpperEdge )
{
DeleteRegion(regUp);
_mesh.Delete(_pool, eUp);
regUp = RegionAbove(regLo);
eUp = regUp._eUp;
}
}
}
if (eUp._Org != eLo._Org)
{
if( eUp._Dst != eLo._Dst
&& ! regUp._fixUpperEdge && ! regLo._fixUpperEdge
&& (eUp._Dst == _event || eLo._Dst == _event) )
{
// When all else fails in CheckForIntersect(), it uses tess._event
// as the intersection location. To make this possible, it requires
// that tess._event lie between the upper and lower edges, and also
// that neither of these is marked fixUpperEdge (since in the worst
// case it might splice one of these edges into tess.event, and
// violate the invariant that fixable edges are the only right-going
// edge from their associated vertex).
if (CheckForIntersect(regUp))
{
// WalkDirtyRegions() was called recursively; we're done
return;
}
}
else
{
// Even though we can't use CheckForIntersect(), the Org vertices
// may violate the dictionary edge ordering. Check and correct this.
CheckForRightSplice(regUp);
}
}
if (eUp._Org == eLo._Org && eUp._Dst == eLo._Dst)
{
// A degenerate loop consisting of only two edges -- delete it.
Geom.AddWinding(eLo, eUp);
DeleteRegion(regUp);
_mesh.Delete(_pool, eUp);
regUp = RegionAbove(regLo);
}
}
}
/// <summary>
/// Purpose: connect a "right" vertex vEvent (one where all edges go left)
/// to the unprocessed portion of the mesh. Since there are no right-going
/// edges, two regions (one above vEvent and one below) are being merged
/// into one. "regUp" is the upper of these two regions.
///
/// There are two reasons for doing this (adding a right-going edge):
/// - if the two regions being merged are "inside", we must add an edge
/// to keep them separated (the combined region would not be monotone).
/// - in any case, we must leave some record of vEvent in the dictionary,
/// so that we can merge vEvent with features that we have not seen yet.
/// For example, maybe there is a vertical edge which passes just to
/// the right of vEvent; we would like to splice vEvent into this edge.
///
/// However, we don't want to connect vEvent to just any vertex. We don''t
/// want the new edge to cross any other edges; otherwise we will create
/// intersection vertices even when the input data had no self-intersections.
/// (This is a bad thing; if the user's input data has no intersections,
/// we don't want to generate any false intersections ourselves.)
///
/// Our eventual goal is to connect vEvent to the leftmost unprocessed
/// vertex of the combined region (the union of regUp and regLo).
/// But because of unseen vertices with all right-going edges, and also
/// new vertices which may be created by edge intersections, we don''t
/// know where that leftmost unprocessed vertex is. In the meantime, we
/// connect vEvent to the closest vertex of either chain, and mark the region
/// as "fixUpperEdge". This flag says to delete and reconnect this edge
/// to the next processed vertex on the boundary of the combined region.
/// Quite possibly the vertex we connected to will turn out to be the
/// closest one, in which case we won''t need to make any changes.
/// </summary>
private void ConnectRightVertex(ActiveRegion regUp, MeshUtils.Edge eBottomLeft)
{
var eTopLeft = eBottomLeft._Onext;
var regLo = RegionBelow(regUp);
var eUp = regUp._eUp;
var eLo = regLo._eUp;
bool degenerate = false;
if (eUp._Dst != eLo._Dst)
{
CheckForIntersect(regUp);
}
// Possible new degeneracies: upper or lower edge of regUp may pass
// through vEvent, or may coincide with new intersection vertex
if (Geom.VertEq(eUp._Org, _event))
{
_mesh.Splice(_pool, eTopLeft._Oprev, eUp);
regUp = TopLeftRegion(regUp);
eTopLeft = RegionBelow(regUp)._eUp;
FinishLeftRegions(RegionBelow(regUp), regLo);
degenerate = true;
}
if (Geom.VertEq(eLo._Org, _event))
{
_mesh.Splice(_pool, eBottomLeft, eLo._Oprev);
eBottomLeft = FinishLeftRegions(regLo, null);
degenerate = true;
}
if (degenerate)
{
AddRightEdges(regUp, eBottomLeft._Onext, eTopLeft, eTopLeft, true);
return;
}
// Non-degenerate situation -- need to add a temporary, fixable edge.
// Connect to the closer of eLo.Org, eUp.Org.
MeshUtils.Edge eNew;
if (Geom.VertLeq(eLo._Org, eUp._Org))
{
eNew = eLo._Oprev;
}
else
{
eNew = eUp;
}
eNew = _mesh.Connect(_pool, eBottomLeft._Lprev, eNew);
// Prevent cleanup, otherwise eNew might disappear before we've even
// had a chance to mark it as a temporary edge.
AddRightEdges(regUp, eNew, eNew._Onext, eNew._Onext, false);
eNew._Sym._activeRegion._fixUpperEdge = true;
WalkDirtyRegions(regUp);
}
/// <summary>
/// The event vertex lies exacty on an already-processed edge or vertex.
/// Adding the new vertex involves splicing it into the already-processed
/// part of the mesh.
/// </summary>
private void ConnectLeftDegenerate(ActiveRegion regUp, MeshUtils.Vertex vEvent)
{
var e = regUp._eUp;
if (Geom.VertEq(e._Org, vEvent))
{
// e.Org is an unprocessed vertex - just combine them, and wait
// for e.Org to be pulled from the queue
// C# : in the C version, there is a flag but it was never implemented
// the vertices are before beginning the tesselation
throw new InvalidOperationException("Vertices should have been merged before");
}
if (!Geom.VertEq(e._Dst, vEvent))
{
// General case -- splice vEvent into edge e which passes through it
_mesh.SplitEdge(_pool, e._Sym);
if (regUp._fixUpperEdge)
{
// This edge was fixable -- delete unused portion of original edge
_mesh.Delete(_pool, e._Onext);
regUp._fixUpperEdge = false;
}
_mesh.Splice(_pool, vEvent._anEdge, e);
SweepEvent(vEvent); // recurse
return;
}
// See above
throw new InvalidOperationException("Vertices should have been merged before");
}
/// <summary>
/// Purpose: connect a "left" vertex (one where both edges go right)
/// to the processed portion of the mesh. Let R be the active region
/// containing vEvent, and let U and L be the upper and lower edge
/// chains of R. There are two possibilities:
///
/// - the normal case: split R into two regions, by connecting vEvent to
/// the rightmost vertex of U or L lying to the left of the sweep line
///
/// - the degenerate case: if vEvent is close enough to U or L, we
/// merge vEvent into that edge chain. The subcases are:
/// - merging with the rightmost vertex of U or L
/// - merging with the active edge of U or L
/// - merging with an already-processed portion of U or L
/// </summary>
private void ConnectLeftVertex(MeshUtils.Vertex vEvent)
{
var tmp = _pool.Get<ActiveRegion>();
// Get a pointer to the active region containing vEvent
tmp._eUp = vEvent._anEdge._Sym;
var regUp = _dict.Find(tmp).Key;
_pool.Return(tmp);
var regLo = RegionBelow(regUp);
if (regLo == null)
{
// This may happen if the input polygon is coplanar.
return;
}
var eUp = regUp._eUp;
var eLo = regLo._eUp;
// Try merging with U or L first
if (Geom.EdgeSign(eUp._Dst, vEvent, eUp._Org) == 0.0f)
{
ConnectLeftDegenerate(regUp, vEvent);
return;
}
// Connect vEvent to rightmost processed vertex of either chain.
// e._Dst is the vertex that we will connect to vEvent.
var reg = Geom.VertLeq(eLo._Dst, eUp._Dst) ? regUp : regLo;
if (regUp._inside || reg._fixUpperEdge)
{
MeshUtils.Edge eNew;
if (reg == regUp)
{
eNew = _mesh.Connect(_pool, vEvent._anEdge._Sym, eUp._Lnext);
}
else
{
eNew = _mesh.Connect(_pool, eLo._Dnext, vEvent._anEdge)._Sym;
}
if (reg._fixUpperEdge)
{
FixUpperEdge(reg, eNew);
}
else
{
ComputeWinding(AddRegionBelow(regUp, eNew));
}
SweepEvent(vEvent);
}
else
{
// The new vertex is in a region which does not belong to the polygon.
// We don't need to connect this vertex to the rest of the mesh.
AddRightEdges(regUp, vEvent._anEdge, vEvent._anEdge, null, true);
}
}
/// <summary>
/// Does everything necessary when the sweep line crosses a vertex.
/// Updates the mesh and the edge dictionary.
/// </summary>
private void SweepEvent(MeshUtils.Vertex vEvent)
{
_event = vEvent;
// Check if this vertex is the right endpoint of an edge that is
// already in the dictionary. In this case we don't need to waste
// time searching for the location to insert new edges.
var e = vEvent._anEdge;
while (e._activeRegion == null)
{
e = e._Onext;
if (e == vEvent._anEdge)
{
// All edges go right -- not incident to any processed edges
ConnectLeftVertex(vEvent);
return;
}
}
// Processing consists of two phases: first we "finish" all the
// active regions where both the upper and lower edges terminate
// at vEvent (ie. vEvent is closing off these regions).
// We mark these faces "inside" or "outside" the polygon according
// to their winding number, and delete the edges from the dictionary.
// This takes care of all the left-going edges from vEvent.
var regUp = TopLeftRegion(e._activeRegion);
var reg = RegionBelow(regUp);
var eTopLeft = reg._eUp;
var eBottomLeft = FinishLeftRegions(reg, null);
// Next we process all the right-going edges from vEvent. This
// involves adding the edges to the dictionary, and creating the
// associated "active regions" which record information about the
// regions between adjacent dictionary edges.
if (eBottomLeft._Onext == eTopLeft)
{
// No right-going edges -- add a temporary "fixable" edge
ConnectRightVertex(regUp, eBottomLeft);
}
else
{
AddRightEdges(regUp, eBottomLeft._Onext, eTopLeft, eTopLeft, true);
}
}
/// <summary>
/// Make the sentinel coordinates big enough that they will never be
/// merged with real input features.
///
/// We add two sentinel edges above and below all other edges,
/// to avoid special cases at the top and bottom.
/// </summary>
private void AddSentinel(Real smin, Real smax, Real t)
{
var e = _mesh.MakeEdge(_pool);
e._Org._s = smax;
e._Org._t = t;
e._Dst._s = smin;
e._Dst._t = t;
_event = e._Dst; // initialize it
var reg = _pool.Get<ActiveRegion>();
reg._eUp = e;
reg._windingNumber = 0;
reg._inside = false;
reg._fixUpperEdge = false;
reg._sentinel = true;
reg._dirty = false;
reg._nodeUp = _dict.Insert(reg);
}
/// <summary>
/// We maintain an ordering of edge intersections with the sweep line.
/// This order is maintained in a dynamic dictionary.
/// </summary>
private void InitEdgeDict()
{
_dict = new Dict<ActiveRegion>(EdgeLeq);
AddSentinel(-SentinelCoord, SentinelCoord, -SentinelCoord);
AddSentinel(-SentinelCoord, SentinelCoord, +SentinelCoord);
}
private void DoneEdgeDict()
{
int fixedEdges = 0;
ActiveRegion reg;
while ((reg = _dict.Min().Key) != null)
{
// At the end of all processing, the dictionary should contain
// only the two sentinel edges, plus at most one "fixable" edge
// created by ConnectRightVertex().
if (!reg._sentinel)
{
Debug.Assert(reg._fixUpperEdge);
Debug.Assert(++fixedEdges == 1);
}
Debug.Assert(reg._windingNumber == 0);
DeleteRegion(reg);
}
_dict = null;
}
/// <summary>
/// Remove zero-length edges, and contours with fewer than 3 vertices.
/// </summary>
private void RemoveDegenerateEdges()
{
MeshUtils.Edge eHead = _mesh._eHead, e, eNext, eLnext;
for (e = eHead._next; e != eHead; e = eNext)
{
eNext = e._next;
eLnext = e._Lnext;
if (Geom.VertEq(e._Org, e._Dst) && e._Lnext._Lnext != e)
{
// Zero-length edge, contour has at least 3 edges
SpliceMergeVertices(eLnext, e); // deletes e.Org
_mesh.Delete(_pool, e); // e is a self-loop
e = eLnext;
eLnext = e._Lnext;
}
if (eLnext._Lnext == e)
{
// Degenerate contour (one or two edges)
if (eLnext != e)
{
if (eLnext == eNext || eLnext == eNext._Sym)
{
eNext = eNext._next;
}
_mesh.Delete(_pool, eLnext);
}
if (e == eNext || e == eNext._Sym)
{
eNext = eNext._next;
}
_mesh.Delete(_pool, e);
}
}
}
/// <summary>
/// Insert all vertices into the priority queue which determines the
/// order in which vertices cross the sweep line.
/// </summary>
private void InitPriorityQ()
{
MeshUtils.Vertex vHead = _mesh._vHead, v;
int vertexCount = 0;
for (v = vHead._next; v != vHead; v = v._next)
{
vertexCount++;
}
// Make sure there is enough space for sentinels.
vertexCount += 8;
_pq = new PriorityQueue<MeshUtils.Vertex>(vertexCount, Geom.VertLeq);
vHead = _mesh._vHead;
for( v = vHead._next; v != vHead; v = v._next ) {
v._pqHandle = _pq.Insert(v);
if (v._pqHandle._handle == PQHandle.Invalid)
{
throw new InvalidOperationException("PQHandle should not be invalid");
}
}
_pq.Init();
}
private void DonePriorityQ()
{
_pq = null;
}
/// <summary>
/// Delete any degenerate faces with only two edges. WalkDirtyRegions()
/// will catch almost all of these, but it won't catch degenerate faces
/// produced by splice operations on already-processed edges.
/// The two places this can happen are in FinishLeftRegions(), when
/// we splice in a "temporary" edge produced by ConnectRightVertex(),
/// and in CheckForLeftSplice(), where we splice already-processed
/// edges to ensure that our dictionary invariants are not violated
/// by numerical errors.
///
/// In both these cases it is *very* dangerous to delete the offending
/// edge at the time, since one of the routines further up the stack
/// will sometimes be keeping a pointer to that edge.
/// </summary>
private void RemoveDegenerateFaces()
{
MeshUtils.Face f, fNext;
MeshUtils.Edge e;
for (f = _mesh._fHead._next; f != _mesh._fHead; f = fNext)
{
fNext = f._next;
e = f._anEdge;
Debug.Assert(e._Lnext != e);
if (e._Lnext._Lnext == e)
{
// A face with only two edges
Geom.AddWinding(e._Onext, e);
_mesh.Delete(_pool, e);
}
}
}
/// <summary>
/// ComputeInterior computes the planar arrangement specified
/// by the given contours, and further subdivides this arrangement
/// into regions. Each region is marked "inside" if it belongs
/// to the polygon, according to the rule given by windingRule.
/// Each interior region is guaranteed to be monotone.
/// </summary>
protected void ComputeInterior()
{
// Each vertex defines an event for our sweep line. Start by inserting
// all the vertices in a priority queue. Events are processed in
// lexicographic order, ie.
//
// e1 < e2 iff e1.x < e2.x || (e1.x == e2.x && e1.y < e2.y)
RemoveDegenerateEdges();
InitPriorityQ();
RemoveDegenerateFaces();
InitEdgeDict();
MeshUtils.Vertex v, vNext;
while ((v = _pq.ExtractMin()) != null)
{
while (true)
{
vNext = _pq.Minimum();
if (vNext == null || !Geom.VertEq(vNext, v))
{
break;
}
// Merge together all vertices at exactly the same location.
// This is more efficient than processing them one at a time,
// simplifies the code (see ConnectLeftDegenerate), and is also
// important for correct handling of certain degenerate cases.
// For example, suppose there are two identical edges A and B
// that belong to different contours (so without this code they would
// be processed by separate sweep events). Suppose another edge C
// crosses A and B from above. When A is processed, we split it
// at its intersection point with C. However this also splits C,
// so when we insert B we may compute a slightly different
// intersection point. This might leave two edges with a small
// gap between them. This kind of error is especially obvious
// when using boundary extraction (BoundaryOnly).
vNext = _pq.ExtractMin();
SpliceMergeVertices(v._anEdge, vNext._anEdge);
}
SweepEvent(v);
}
DoneEdgeDict();
DonePriorityQ();
RemoveDegenerateFaces();
_mesh.Check();
}
}
}
| 1 | 0.792428 | 1 | 0.792428 | game-dev | MEDIA | 0.151263 | game-dev | 0.983676 | 1 | 0.983676 |
jannson/wordmaker | 1,059 | src/marisa/agent.cc | #include <new>
#include "agent.h"
#include "grimoire/trie.h"
namespace marisa {
Agent::Agent() : query_(), key_(), state_() {}
Agent::~Agent() {}
void Agent::set_query(const char *str) {
MARISA_THROW_IF(str == NULL, MARISA_NULL_ERROR);
if (state_.get() != NULL) {
state_->reset();
}
query_.set_str(str);
}
void Agent::set_query(const char *ptr, std::size_t length) {
MARISA_THROW_IF((ptr == NULL) && (length != 0), MARISA_NULL_ERROR);
if (state_.get() != NULL) {
state_->reset();
}
query_.set_str(ptr, length);
}
void Agent::set_query(std::size_t key_id) {
if (state_.get() != NULL) {
state_->reset();
}
query_.set_id(key_id);
}
void Agent::init_state() {
MARISA_THROW_IF(state_.get() != NULL, MARISA_STATE_ERROR);
state_.reset(new (std::nothrow) grimoire::State);
MARISA_THROW_IF(state_.get() == NULL, MARISA_MEMORY_ERROR);
}
void Agent::clear() {
Agent().swap(*this);
}
void Agent::swap(Agent &rhs) {
query_.swap(rhs.query_);
key_.swap(rhs.key_);
state_.swap(rhs.state_);
}
} // namespace marisa
| 1 | 0.753675 | 1 | 0.753675 | game-dev | MEDIA | 0.294382 | game-dev | 0.922409 | 1 | 0.922409 |
imesense/minecraft-projects | 4,603 | forge-1.16.5/src/main/java/org/imesense/emptymod/EmptyMod.java | package org.imesense.emptymod;
import java.lang.ref.WeakReference;
import java.util.stream.Collectors;
import net.minecraft.block.Block;
import net.minecraft.block.Blocks;
import net.minecraft.client.Minecraft;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.InterModComms;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;
import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent;
import net.minecraftforge.fml.event.lifecycle.InterModEnqueueEvent;
import net.minecraftforge.fml.event.lifecycle.InterModProcessEvent;
import net.minecraftforge.fml.event.server.FMLServerStartingEvent;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import net.minecraftforge.fml.loading.FMLEnvironment;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.imesense.emptymod.proxy.ClientProxy;
import org.imesense.emptymod.proxy.IProxy;
import org.imesense.emptymod.proxy.ServerProxy;
/**
* Main class of modification
*/
@Mod("emptymod")
public class EmptyMod
{
/**
* Instance of this class
*/
public static EmptyMod Instance;
/**
*
*/
public static IProxy Proxy;
/**
* Directly reference log4j logger
*/
private static final Logger LOGGER = LogManager.getLogger();
/**
* Constructs main class object
*/
public EmptyMod()
{
// Initialize instance
Instance = this;
if (FMLEnvironment.dist.isClient())
{
Proxy = new ClientProxy();
}
else
{
Proxy = new ServerProxy();
}
// Register `setup` method for modloading
FMLJavaModLoadingContext
.get()
.getModEventBus()
.addListener(this::setup);
// Register `enqueueIMC` method for modloading
FMLJavaModLoadingContext
.get()
.getModEventBus()
.addListener(this::enqueueIMC);
// Register `processIMC` method for modloading
FMLJavaModLoadingContext
.get()
.getModEventBus()
.addListener(this::processIMC);
// Register `doClientStuff` method for modloading
FMLJavaModLoadingContext
.get()
.getModEventBus()
.addListener(this::doClientStuff);
// Register ourselves for server and other game events
MinecraftForge.EVENT_BUS.register(this);
}
/**
* Setup action
*
* @param event Common setup event
*/
private void setup(final FMLCommonSetupEvent event)
{
Proxy.init();
LOGGER.info("HELLO FROM PREINIT");
LOGGER.info("DIRT BLOCK >> {}", Blocks.DIRT.getRegistryName());
}
/**
* Performs client actions
*
* @param event Client setup event
*/
private void doClientStuff(final FMLClientSetupEvent event)
{
Minecraft mcInstance = event.getMinecraftSupplier().get();
LOGGER.info("Got game settings {}", mcInstance.options);
}
/**
* Enqueues method
*
* @param event Intermod enqueue event
*/
private void enqueueIMC(final InterModEnqueueEvent event)
{
InterModComms.sendTo("examplemod", "helloworld", () ->
{
LOGGER.info("Hello world from the MDK"); return "Hello world";
});
}
/**
* Processes method
*
* @param event Intermod process event
*/
private void processIMC(final InterModProcessEvent event)
{
LOGGER.info("Got IMC {}", event.getIMCStream().
map(message -> message.getMessageSupplier().get()).
collect(Collectors.toList()));
}
/**
* Server starting action
*
* @param event Server starting event
*/
@SubscribeEvent
public void onServerStarting(FMLServerStartingEvent event)
{
LOGGER.info("HELLO from server starting");
}
/**
* Registry events
*/
@Mod.EventBusSubscriber(bus = Mod.EventBusSubscriber.Bus.MOD)
public static class RegistryEvents
{
/**
* Blocks registry action
*
* @param blockRegistryEvent Block registry event
*/
@SubscribeEvent
public static void onBlocksRegistry(final RegistryEvent.Register<Block> blockRegistryEvent)
{
LOGGER.info("HELLO from Register Block");
}
}
}
| 1 | 0.889309 | 1 | 0.889309 | game-dev | MEDIA | 0.91502 | game-dev | 0.919508 | 1 | 0.919508 |
PentestSS13/Pentest | 4,367 | modular_pentest/master_files/code/modules/mob/living/simple_animal/hostile/human/cat_butcher.dm | /mob/living/simple_animal/hostile/human/cat_butcherer
name = "Cat Surgeon"
desc = "Feline genemod physiological modification surgery is outlawed in Nanotrasen-controlled sectors. This doctor doesn't seem to care, and thus, is wanted for several warcrimes."
icon_state = "cat_butcher"
icon_living = "cat_butcher"
projectiletype = /obj/projectile/bullet/dart/tranq
projectilesound = 'sound/items/syringeproj.ogg'
ranged = TRUE
ranged_message = "fires the syringe gun at"
ranged_cooldown_time = 30
speak_chance = 0
stat_attack = HARD_CRIT
melee_damage_lower = 15
melee_damage_upper = 15
attack_verb_continuous = "slashes at"
attack_verb_simple = "slash at"
attack_sound = 'sound/weapons/circsawhit.ogg'
loot = list(/obj/effect/mob_spawn/human/corpse/cat_butcher, /obj/item/circular_saw, /obj/item/gun/syringe)
atmos_requirements = list("min_oxy" = 5, "max_oxy" = 0, "min_tox" = 0, "max_tox" = 1, "min_co2" = 0, "max_co2" = 5, "min_n2" = 0, "max_n2" = 0)
faction = list("hostile")
check_friendly_fire = TRUE
var/impatience = 0
/mob/living/simple_animal/hostile/human/cat_butcherer/CanAttack(atom/the_target)
if(iscarbon(target))
var/mob/living/carbon/human/C = target
if(C.getorgan(/obj/item/organ/ears/cat) && C.getorgan(/obj/item/organ/tail/cat) && C.has_trauma_type(/datum/brain_trauma/severe/pacifism))//he wont attack his creations
if(C.stat >= UNCONSCIOUS && (!HAS_TRAIT(C, TRAIT_NOMETABOLISM) || !istype(C.dna.species, /datum/species/ipc)))//unless they need healing
return ..()
else
return FALSE
return ..()
/mob/living/simple_animal/hostile/human/cat_butcherer/AttackingTarget()
if(iscarbon(target))
var/mob/living/carbon/human/L = target
if(!L.getorgan(/obj/item/organ/ears/cat) && L.stat >= UNCONSCIOUS) //target doesnt have cat ears
if(L.getorgan(/obj/item/organ/ears)) //slice off the old ears
var/obj/item/organ/ears/ears = L.getorgan(/obj/item/organ/ears)
visible_message("[src] slices off [L]'s ears!", span_notice("You slice [L]'s ears off."))
ears.Remove(L)
ears.forceMove(get_turf(L))
else //implant new ears
visible_message("[src] attaches a pair of cat ears to [L]!", span_notice("You attach a pair of cat ears to [L]."))
var/obj/item/organ/ears/cat/newears = new
newears.Insert(L, drop_if_replaced = FALSE)
return
else if(!L.getorgan(/obj/item/organ/tail/cat) && L.stat >= UNCONSCIOUS)
if(L.getorgan(/obj/item/organ/tail)) //cut off the tail if they have one already
var/obj/item/organ/tail/tail = L.getorgan(/obj/item/organ/tail)
visible_message("[src] severs [L]'s tail in one swift swipe!", span_notice("You sever [L]'s tail in one swift swipe."))
tail.Remove(L)
tail.forceMove(get_turf(L))
else //put a cat tail on
visible_message("[src] attaches a cat tail to [L]!", span_notice("You attach a tail to [L]."))
var/obj/item/organ/tail/cat/newtail = new
newtail.Insert(L, drop_if_replaced = FALSE)
return
else if(!L.has_trauma_type(/datum/brain_trauma/severe/pacifism) && L.stat >= UNCONSCIOUS) //still does damage
visible_message("[src] drills a hole in [L]'s skull!", span_notice("You pacify [L]. Another successful creation."))
L.gain_trauma(/datum/brain_trauma/severe/pacifism, TRAUMA_RESILIENCE_SURGERY)
say("I'm a genius!!")
L.health += 20 //he heals a bit whenever he finishes
else if(L.stat >= UNCONSCIOUS) //quickly heal them up and move on to our next target!
visible_message("[src] injects [L] with an unknown medicine!", span_notice("You inject [L] with medicine."))
L.set_sleeping(0, FALSE)
L.SetUnconscious(0, FALSE)
L.adjustOxyLoss(-50)// do CPR first
if(L.blood_volume <= 500) //bandage them up and give em some blood if they're bleeding
L.blood_volume += 30
L.heal_bleeding(10)
if(L.getBruteLoss() >= 50)// first, did we beat them into crit? if so, heal that
var/healing = min(L.getBruteLoss(), 120)
L.adjustBruteLoss(-healing)
L.heal_bleeding(10)
return
else if(L.getFireLoss() >= 50) // are they still down from other damage? fix it, but not as fast as the burns
var/healing = min(L.getFireLoss(), 50)
L.adjustFireLoss(-healing)
impatience += 50
if(prob(impatience))
FindTarget()//so we don't focus on some unconscious dude when we could get our eyes on the prize
impatience = 0
say("Bah!!")
return
return ..()
| 1 | 0.952202 | 1 | 0.952202 | game-dev | MEDIA | 0.981688 | game-dev | 0.970877 | 1 | 0.970877 |
ronellsicat/DxR | 3,549 | Assets/HoloToolkit/Utilities/Scripts/Extensions/GameObjectExtensions.cs | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
using System.Collections.Generic;
using UnityEngine;
namespace HoloToolkit.Unity
{
/// <summary>
/// Extension methods for Unity's GameObject class
/// </summary>
public static class GameObjectExtensions
{
[Obsolete("Use the more extensive TransformExtensions.GetFullPath instead.")]
public static string GetFullPath(this GameObject go)
{
return go.transform.GetFullPath("/", "");
}
/// <summary>
/// Set the layer to the given object and the full hierarchy below it.
/// </summary>
/// <param name="root">Start point of the traverse</param>
/// <param name="layer">The layer to apply</param>
public static void SetLayerRecursively(this GameObject root, int layer)
{
if (root == null)
{
throw new ArgumentNullException("root", "Root transform can't be null.");
}
foreach (var child in root.transform.EnumerateHierarchy())
{
child.gameObject.layer = layer;
}
}
/// <summary>
/// Set the layer to the given object and the full hierarchy below it and cache the previous layers in the out parameter.
/// </summary>
/// <param name="root">Start point of the traverse</param>
/// <param name="layer">The layer to apply</param>
/// <param name="cache">The previously set layer for each object</param>
public static void SetLayerRecursively(this GameObject root, int layer, out Dictionary<GameObject, int> cache)
{
if (root == null) { throw new ArgumentNullException("root"); }
cache = new Dictionary<GameObject, int>();
foreach (var child in root.transform.EnumerateHierarchy())
{
cache[child.gameObject] = child.gameObject.layer;
child.gameObject.layer = layer;
}
}
/// <summary>
/// Reapplies previously cached hierarchy layers
/// </summary>
/// <param name="root">Start point of the traverse</param>
/// <param name="cache">The previously set layer for each object</param>
public static void ApplyLayerCacheRecursively(this GameObject root, Dictionary<GameObject, int> cache)
{
if (root == null) { throw new ArgumentNullException("root"); }
if (cache == null) { throw new ArgumentNullException("cache"); }
foreach (var child in root.transform.EnumerateHierarchy())
{
int layer;
if (!cache.TryGetValue(child.gameObject, out layer)) { continue; }
child.gameObject.layer = layer;
cache.Remove(child.gameObject);
}
}
/// <summary>
/// Gets the GameObject's root Parent object.
/// </summary>
/// <param name="child">The GameObject we're trying to find the root parent for.</param>
/// <returns>The Root parent GameObject.</returns>
public static GameObject GetParentRoot(this GameObject child)
{
if (child.transform.parent == null)
{
return child;
}
else
{
return GetParentRoot(child.transform.parent.gameObject);
}
}
}
}
| 1 | 0.861193 | 1 | 0.861193 | game-dev | MEDIA | 0.911856 | game-dev | 0.969266 | 1 | 0.969266 |
protocolbuffers/upb | 10,931 | archive/upb/util/required_fields.c | // Protocol Buffers - Google's data interchange format
// Copyright 2023 Google LLC. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google LLC nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "upb/util/required_fields.h"
#include <inttypes.h>
#include <stdarg.h>
#include "upb/collections/map.h"
#include "upb/port/vsnprintf_compat.h"
#include "upb/reflection/message.h"
// Must be last.
#include "upb/port/def.inc"
////////////////////////////////////////////////////////////////////////////////
// upb_FieldPath_ToText()
////////////////////////////////////////////////////////////////////////////////
typedef struct {
char* buf;
char* ptr;
char* end;
size_t overflow;
} upb_PrintfAppender;
UPB_PRINTF(2, 3)
static void upb_FieldPath_Printf(upb_PrintfAppender* a, const char* fmt, ...) {
size_t n;
size_t have = a->end - a->ptr;
va_list args;
va_start(args, fmt);
n = _upb_vsnprintf(a->ptr, have, fmt, args);
va_end(args);
if (UPB_LIKELY(have > n)) {
// We can't end up here if the user passed (NULL, 0), therefore ptr is known
// to be non-NULL, and UPB_PTRADD() is not necessary.
assert(a->ptr);
a->ptr += n;
} else {
a->ptr = UPB_PTRADD(a->ptr, have);
a->overflow += (n - have);
}
}
static size_t upb_FieldPath_NullTerminate(upb_PrintfAppender* d, size_t size) {
size_t ret = d->ptr - d->buf + d->overflow;
if (size > 0) {
if (d->ptr == d->end) d->ptr--;
*d->ptr = '\0';
}
return ret;
}
static void upb_FieldPath_PutMapKey(upb_PrintfAppender* a,
upb_MessageValue map_key,
const upb_FieldDef* key_f) {
switch (upb_FieldDef_CType(key_f)) {
case kUpb_CType_Int32:
upb_FieldPath_Printf(a, "[%" PRId32 "]", map_key.int32_val);
break;
case kUpb_CType_Int64:
upb_FieldPath_Printf(a, "[%" PRId64 "]", map_key.int64_val);
break;
case kUpb_CType_UInt32:
upb_FieldPath_Printf(a, "[%" PRIu32 "]", map_key.uint32_val);
break;
case kUpb_CType_UInt64:
upb_FieldPath_Printf(a, "[%" PRIu64 "]", map_key.uint64_val);
break;
case kUpb_CType_Bool:
upb_FieldPath_Printf(a, "[%s]", map_key.bool_val ? "true" : "false");
break;
case kUpb_CType_String:
upb_FieldPath_Printf(a, "[\"");
for (size_t i = 0; i < map_key.str_val.size; i++) {
char ch = map_key.str_val.data[i];
if (ch == '"') {
upb_FieldPath_Printf(a, "\\\"");
} else {
upb_FieldPath_Printf(a, "%c", ch);
}
}
upb_FieldPath_Printf(a, "\"]");
break;
default:
UPB_UNREACHABLE(); // Other types can't be map keys.
}
}
size_t upb_FieldPath_ToText(upb_FieldPathEntry** path, char* buf, size_t size) {
upb_FieldPathEntry* ptr = *path;
upb_PrintfAppender appender;
appender.buf = buf;
appender.ptr = buf;
appender.end = UPB_PTRADD(buf, size);
appender.overflow = 0;
bool first = true;
while (ptr->field) {
const upb_FieldDef* f = ptr->field;
upb_FieldPath_Printf(&appender, first ? "%s" : ".%s", upb_FieldDef_Name(f));
first = false;
ptr++;
if (upb_FieldDef_IsMap(f)) {
const upb_FieldDef* key_f =
upb_MessageDef_Field(upb_FieldDef_MessageSubDef(f), 0);
upb_FieldPath_PutMapKey(&appender, ptr->map_key, key_f);
ptr++;
} else if (upb_FieldDef_IsRepeated(f)) {
upb_FieldPath_Printf(&appender, "[%zu]", ptr->array_index);
ptr++;
}
}
// Advance beyond terminating NULL.
ptr++;
*path = ptr;
return upb_FieldPath_NullTerminate(&appender, size);
}
////////////////////////////////////////////////////////////////////////////////
// upb_util_HasUnsetRequired()
////////////////////////////////////////////////////////////////////////////////
typedef struct {
upb_FieldPathEntry* path;
size_t size;
size_t cap;
} upb_FieldPathVector;
typedef struct {
upb_FieldPathVector stack;
upb_FieldPathVector out_fields;
const upb_DefPool* ext_pool;
jmp_buf err;
bool has_unset_required;
bool save_paths;
} upb_FindContext;
static void upb_FieldPathVector_Init(upb_FieldPathVector* vec) {
vec->path = NULL;
vec->size = 0;
vec->cap = 0;
}
static void upb_FieldPathVector_Reserve(upb_FindContext* ctx,
upb_FieldPathVector* vec,
size_t elems) {
if (vec->cap - vec->size < elems) {
size_t need = vec->size + elems;
vec->cap = UPB_MAX(4, vec->cap);
while (vec->cap < need) vec->cap *= 2;
vec->path = realloc(vec->path, vec->cap * sizeof(*vec->path));
if (!vec->path) {
UPB_LONGJMP(ctx->err, 1);
}
}
}
static void upb_FindContext_Push(upb_FindContext* ctx, upb_FieldPathEntry ent) {
if (!ctx->save_paths) return;
upb_FieldPathVector_Reserve(ctx, &ctx->stack, 1);
ctx->stack.path[ctx->stack.size++] = ent;
}
static void upb_FindContext_Pop(upb_FindContext* ctx) {
if (!ctx->save_paths) return;
assert(ctx->stack.size != 0);
ctx->stack.size--;
}
static void upb_util_FindUnsetInMessage(upb_FindContext* ctx,
const upb_Message* msg,
const upb_MessageDef* m) {
// Iterate over all fields to see if any required fields are missing.
for (int i = 0, n = upb_MessageDef_FieldCount(m); i < n; i++) {
const upb_FieldDef* f = upb_MessageDef_Field(m, i);
if (upb_FieldDef_Label(f) != kUpb_Label_Required) continue;
if (!msg || !upb_Message_HasFieldByDef(msg, f)) {
// A required field is missing.
ctx->has_unset_required = true;
if (ctx->save_paths) {
// Append the contents of the stack to the out array, then
// NULL-terminate.
upb_FieldPathVector_Reserve(ctx, &ctx->out_fields, ctx->stack.size + 2);
if (ctx->stack.size) {
memcpy(&ctx->out_fields.path[ctx->out_fields.size], ctx->stack.path,
ctx->stack.size * sizeof(*ctx->stack.path));
}
ctx->out_fields.size += ctx->stack.size;
ctx->out_fields.path[ctx->out_fields.size++] =
(upb_FieldPathEntry){.field = f};
ctx->out_fields.path[ctx->out_fields.size++] =
(upb_FieldPathEntry){.field = NULL};
}
}
}
}
static void upb_util_FindUnsetRequiredInternal(upb_FindContext* ctx,
const upb_Message* msg,
const upb_MessageDef* m) {
// OPT: add markers in the schema for where we can avoid iterating:
// 1. messages with no required fields.
// 2. messages that cannot possibly reach any required fields.
upb_util_FindUnsetInMessage(ctx, msg, m);
if (!msg) return;
// Iterate over all present fields to find sub-messages that might be missing
// required fields. This may revisit some of the fields already inspected
// in the previous loop. We do this separately because this loop will also
// find present extensions, which the previous loop will not.
//
// TODO(haberman): consider changing upb_Message_Next() to be capable of
// visiting extensions only, for example with a kUpb_Message_BeginEXT
// constant.
size_t iter = kUpb_Message_Begin;
const upb_FieldDef* f;
upb_MessageValue val;
while (upb_Message_Next(msg, m, ctx->ext_pool, &f, &val, &iter)) {
// Skip non-submessage fields.
if (!upb_FieldDef_IsSubMessage(f)) continue;
upb_FindContext_Push(ctx, (upb_FieldPathEntry){.field = f});
const upb_MessageDef* sub_m = upb_FieldDef_MessageSubDef(f);
if (upb_FieldDef_IsMap(f)) {
// Map field.
const upb_FieldDef* val_f = upb_MessageDef_Field(sub_m, 1);
const upb_MessageDef* val_m = upb_FieldDef_MessageSubDef(val_f);
if (!val_m) continue;
const upb_Map* map = val.map_val;
size_t iter = kUpb_Map_Begin;
upb_MessageValue key, map_val;
while (upb_Map_Next(map, &key, &map_val, &iter)) {
upb_FindContext_Push(ctx, (upb_FieldPathEntry){.map_key = key});
upb_util_FindUnsetRequiredInternal(ctx, map_val.msg_val, val_m);
upb_FindContext_Pop(ctx);
}
} else if (upb_FieldDef_IsRepeated(f)) {
// Repeated field.
const upb_Array* arr = val.array_val;
for (size_t i = 0, n = upb_Array_Size(arr); i < n; i++) {
upb_MessageValue elem = upb_Array_Get(arr, i);
upb_FindContext_Push(ctx, (upb_FieldPathEntry){.array_index = i});
upb_util_FindUnsetRequiredInternal(ctx, elem.msg_val, sub_m);
upb_FindContext_Pop(ctx);
}
} else {
// Scalar sub-message field.
upb_util_FindUnsetRequiredInternal(ctx, val.msg_val, sub_m);
}
upb_FindContext_Pop(ctx);
}
}
bool upb_util_HasUnsetRequired(const upb_Message* msg, const upb_MessageDef* m,
const upb_DefPool* ext_pool,
upb_FieldPathEntry** fields) {
upb_FindContext ctx;
ctx.has_unset_required = false;
ctx.save_paths = fields != NULL;
ctx.ext_pool = ext_pool;
upb_FieldPathVector_Init(&ctx.stack);
upb_FieldPathVector_Init(&ctx.out_fields);
upb_util_FindUnsetRequiredInternal(&ctx, msg, m);
free(ctx.stack.path);
if (fields) {
upb_FieldPathVector_Reserve(&ctx, &ctx.out_fields, 1);
ctx.out_fields.path[ctx.out_fields.size] =
(upb_FieldPathEntry){.field = NULL};
*fields = ctx.out_fields.path;
}
return ctx.has_unset_required;
}
| 1 | 0.980441 | 1 | 0.980441 | game-dev | MEDIA | 0.263494 | game-dev | 0.967326 | 1 | 0.967326 |
crashdezz/BlexPloit | 1,087 | src/de/blexploit/command/cmds/Heal.java | package de.blexploit.command.cmds;
import org.bukkit.entity.Player;
import org.bukkit.potion.PotionEffectType;
import api.Fehler;
import de.blexploit.command.Command;
import de.blexploit.manager.TabManager;
import de.blexploit.players.create.MittrollerEntity;
public final class Heal extends Command {
public Heal() {
super("heal", "Heile dich oder andere Spieler", TabManager.INSERT_PLAYERNAME);
}
@Override
public void run(String[] args, MittrollerEntity mt) {
if (args.length == 1) {
toPlayer(mt.getPlayer());
mt.sendMessage("Du wurdest geheilt!");
} else if (args.length > 1) {
Player victim = api.Get.player(args[1]);
if (victim != null) {
this.SpielerInfo(mt, "hat §c" + victim.getName() + this.CHAT_COLOR + " geheilt!");
toPlayer(victim);
} else {
mt.fehler(Fehler.PLAYER_NOT_FOUND);
}
}
}
private void toPlayer(Player p) {
for (PotionEffectType pt : PotionEffectType.values()) {
if (pt != null) {
if (p.hasPotionEffect(pt)) {
p.removePotionEffect(pt);
}
}
}
p.setHealth(20);
p.setFoodLevel(20);
}
}
| 1 | 0.950178 | 1 | 0.950178 | game-dev | MEDIA | 0.910988 | game-dev | 0.991044 | 1 | 0.991044 |
Melledy/LunarCore | 4,793 | src/main/java/emu/lunarcore/game/player/PlayerUnlockData.java | package emu.lunarcore.game.player;
import dev.morphia.annotations.Entity;
import dev.morphia.annotations.Id;
import emu.lunarcore.GameConstants;
import emu.lunarcore.LunarCore;
import emu.lunarcore.data.GameData;
import emu.lunarcore.game.avatar.GameAvatar;
import emu.lunarcore.game.enums.PersonalizeShowType;
import emu.lunarcore.proto.PlayerSyncScNotifyOuterClass.PlayerSyncScNotify;
import emu.lunarcore.server.game.Syncable;
import emu.lunarcore.server.packet.BasePacket;
import emu.lunarcore.server.packet.send.PacketPlayerSyncScNotify;
import emu.lunarcore.server.packet.send.PacketUnlockChatBubbleScNotify;
import emu.lunarcore.server.packet.send.PacketUnlockPhoneThemeScNotify;
import it.unimi.dsi.fastutil.ints.IntOpenHashSet;
import it.unimi.dsi.fastutil.ints.IntSet;
import lombok.Getter;
@Getter
@Entity(value = "unlocks", useDiscriminator = false)
public class PlayerUnlockData implements Syncable {
private transient Player owner;
@Id private int ownerUid;
private IntSet headIcons;
private IntSet chatBubbles;
private IntSet phoneThemes;
private IntSet pets;
@Deprecated // Morphia only
public PlayerUnlockData() {}
public PlayerUnlockData(Player player) {
this.owner = player;
this.ownerUid = player.getUid();
// Add default head icons
for (int iconId : GameConstants.DEFAULT_HEAD_ICONS) {
this.addHeadIcon(iconId);
}
// Add head icons from avatars we already have
for (GameAvatar avatar : owner.getAvatars()) {
this.addHeadIcon(avatar.getHeadIconId());
}
// Add default chat bubble(s)
for (var excel : GameData.getChatBubbleExcelMap().values()) {
if (excel.getShowType() == PersonalizeShowType.Always) {
this.addChatBubble(excel.getId());
}
}
// Add default phone theme(s)
for (var excel : GameData.getPhoneThemeExcelMap().values()) {
if (excel.getShowType() == PersonalizeShowType.Always) {
this.addPhoneTheme(excel.getId());
}
}
this.save();
}
protected void setOwner(Player player) {
this.owner = player;
}
public IntSet getHeadIcons() {
if (this.headIcons == null) {
this.headIcons = new IntOpenHashSet();
}
return this.headIcons;
}
public IntSet getChatBubbles() {
if (this.chatBubbles == null) {
this.chatBubbles = new IntOpenHashSet();
}
return this.chatBubbles;
}
public IntSet getPhoneThemes() {
if (this.phoneThemes == null) {
this.phoneThemes = new IntOpenHashSet();
}
return this.phoneThemes;
}
public IntSet getPets() {
if (this.pets == null) {
this.pets = new IntOpenHashSet();
}
return this.pets;
}
public void addHeadIcon(int headIconId) {
boolean success = this.getHeadIcons().add(headIconId);
if (success && this.getOwner().isLoggedIn()) {
this.sendPacket(new PacketPlayerSyncScNotify(this));
this.save();
}
}
public void addChatBubble(int chatBubbleId) {
boolean success = this.getChatBubbles().add(chatBubbleId);
if (success && this.getOwner().isLoggedIn()) {
this.sendPacket(new PacketUnlockChatBubbleScNotify(chatBubbleId));
this.save();
}
}
public void addPhoneTheme(int phoneThemeId) {
boolean success = this.getPhoneThemes().add(phoneThemeId);
if (success && this.getOwner().isLoggedIn()) {
this.sendPacket(new PacketUnlockPhoneThemeScNotify(phoneThemeId));
this.save();
}
}
public void addPet(int petItemId) {
// Get pet excel TODO optimize
var excel = GameData.getPetExcelMap().values().stream()
.filter(e -> e.getPetItemID() == petItemId)
.findFirst()
.orElse(null);
if (excel == null) {
return;
}
// Add
boolean success = this.getPets().add(excel.getPetID());
if (success && this.getOwner().isLoggedIn()) {
// Pet sync packet TODO
this.save();
}
}
private void sendPacket(BasePacket packet) {
this.getOwner().sendPacket(packet);
}
// Player sync
public void onSync(PlayerSyncScNotify proto) {
proto.setBoardDataSync(this.getOwner().toBoardData());
}
// Database
public void save() {
LunarCore.getGameDatabase().save(this);
}
}
| 1 | 0.835012 | 1 | 0.835012 | game-dev | MEDIA | 0.378401 | game-dev | 0.984414 | 1 | 0.984414 |
moq/moq.spikes | 4,183 | spikes/v5/Moq/CastleProxyFactory.cs | #region Apache Licensed
/*
Copyright 2013 Clarius Consulting, Daniel Cazzulino
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.
*/
#endregion
using System;
using System.Linq;
using System.Reflection;
using System.Security.Permissions;
using Castle.DynamicProxy;
using Castle.DynamicProxy.Generators;
using System.Diagnostics.CodeAnalysis;
using CastleInterceptor = Castle.DynamicProxy.IInterceptor;
using CastleInvocation = Castle.DynamicProxy.IInvocation;
using Moq.Sdk;
namespace Moq
{
/// <summary>
/// Provides a proxy factory for mocks based on Castle Dynamic Proxy.
/// </summary>
internal class CastleProxyFactory : IProxyFactory
{
private static readonly ProxyGenerator generator = CreateProxyGenerator();
[SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline", Justification = "By Design")]
static CastleProxyFactory()
{
#pragma warning disable 618
AttributesToAvoidReplicating.Add<SecurityPermissionAttribute>();
#pragma warning restore 618
#if !SILVERLIGHT
AttributesToAvoidReplicating.Add<ReflectionPermissionAttribute>();
AttributesToAvoidReplicating.Add<PermissionSetAttribute>();
AttributesToAvoidReplicating.Add<System.Runtime.InteropServices.MarshalAsAttribute>();
#if !NET3x
AttributesToAvoidReplicating.Add<System.Runtime.InteropServices.TypeIdentifierAttribute>();
#endif
#endif
}
public T CreateProxy<T>(IProxied interceptable, Type[] interfaces, object[] arguments)
{
var mockType = typeof(T);
interfaces = interfaces.Concat(new[] { typeof(IMocked) }).ToArray();
if (mockType.IsInterface)
{
return (T)generator.CreateInterfaceProxyWithoutTarget(mockType, interfaces, new ForwardingInterceptor(interceptable));
}
try
{
return (T)generator.CreateClassProxy(mockType, interfaces, new ProxyGenerationOptions(), arguments, new ForwardingInterceptor(interceptable));
}
catch (TypeLoadException e)
{
throw;
//throw new ArgumentException(Resources.InvalidMockClass, e);
}
catch (MissingMethodException e)
{
throw;
//throw new ArgumentException(Resources.ConstructorNotFound, e);
}
}
private static ProxyGenerator CreateProxyGenerator()
{
return new ProxyGenerator();
}
// Forwards intercepted calls to the proxied mock.
private class ForwardingInterceptor : CastleInterceptor
{
private IProxied mock;
internal ForwardingInterceptor(IProxied mock)
{
this.mock = mock;
}
public void Intercept(CastleInvocation invocation)
{
if (invocation.Method.DeclaringType == typeof(IMocked))
{
// "Mixin" of IMocked.Mock
invocation.ReturnValue = this.mock;
return;
}
this.mock.Execute(new InvocationAdapter(invocation, this.mock));
}
}
// Adapts the Castle invocation contract to Moq's.
[Serializable]
private class InvocationAdapter : Moq.Sdk.IInvocation
{
[NonSerialized]
private CastleInvocation invocation;
[NonSerialized]
private IProxied mock;
internal InvocationAdapter(CastleInvocation invocation, IProxied mock)
{
this.invocation = invocation;
this.mock = mock;
}
public IMock Mock
{
get { return this.mock as IMock; }
}
public object[] Arguments
{
get { return this.invocation.Arguments; }
}
public MethodInfo Method
{
get { return this.invocation.Method; }
}
public object ReturnValue
{
get { return this.invocation.ReturnValue; }
set { this.invocation.ReturnValue = value; }
}
public void InvokeBase()
{
this.invocation.Proceed();
}
public object Target
{
get { return this.invocation.InvocationTarget; }
}
}
}
} | 1 | 0.843628 | 1 | 0.843628 | game-dev | MEDIA | 0.199309 | game-dev | 0.765257 | 1 | 0.765257 |
Griiimon/Manymies | 1,356 | spawner/enemy_spawner.gd | extends Node2D
@export var enemy_scene: PackedScene
@export var spawn_interval: float= 0.1
@export var wait_for_empty_space: bool= false
@export var empty_radius: float= 20.0
@onready var timer: Timer = $Timer
var paused:= false
var busy:= false
var empty_space_query: PhysicsShapeQueryParameters2D
func _ready() -> void:
if wait_for_empty_space:
var query:= PhysicsShapeQueryParameters2D.new()
query.collide_with_areas= true
query.collide_with_bodies= true
query.collision_mask= Global.ENEMY_COLLISION_LAYER + Global.RAYCAST_ENEMY_COLLISION_LAYER
query.transform= transform
var shape:= CircleShape2D.new()
shape.radius= empty_radius
query.shape= shape
empty_space_query= query
timer.wait_time= spawn_interval
timer.start()
func _process(delta: float) -> void:
if Input.is_action_just_pressed("pause_spawner"):
paused= not paused
func spawn_enemy():
if busy: return
if paused: return
if wait_for_empty_space:
busy= true
await get_tree().physics_frame
busy= false
var space_state: PhysicsDirectSpaceState2D= get_world_2d().direct_space_state
if not space_state: return
var result= space_state.intersect_shape(empty_space_query)
if result: return
var obj: BaseEnemy= enemy_scene.instantiate()
obj.position= position
Global.enemies.add_child(obj)
func _on_timer_timeout() -> void:
spawn_enemy()
| 1 | 0.594203 | 1 | 0.594203 | game-dev | MEDIA | 0.84393 | game-dev | 0.9216 | 1 | 0.9216 |
Critical-Impact/InventoryTools | 4,824 | InventoryTools/Services/ItemSearchService.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using AllaganLib.GameSheets.Sheets;
using AllaganLib.GameSheets.Sheets.Rows;
using CriticalCommonLib.Extensions;
using CriticalCommonLib.Services;
using CriticalCommonLib.Services.Mediator;
using DalaMock.Host.Mediator;
using Dalamud.Game.Text;
using Dalamud.Game.Text.SeStringHandling;
using Dalamud.Game.Text.SeStringHandling.Payloads;
using Dalamud.Plugin.Services;
using FFXIVClientStructs.FFXIV.Client.Game;
using InventoryTools.Logic.Editors;
using InventoryTools.Mediator;
using Lumina.Excel.Sheets;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace InventoryTools.Services;
public class ItemSearchService(MediatorService mediatorService, IClientState clientState, InventoryToolsConfiguration configuration, IInventoryMonitor inventoryMonitor, ICharacterMonitor characterMonitor, InventoryScopeCalculator calculator, IChatGui chatGui, ItemSheet itemSheet, ILogger<ItemSearchService> logger) : IHostedService, IMediatorSubscriber, IDisposable
{
private readonly ILogger<ItemSearchService> _logger = logger;
public ItemSheet ItemSheet { get; } = itemSheet;
public Task StartAsync(CancellationToken cancellationToken)
{
mediatorService.Subscribe<ItemSearchRequestedMessage>(this, ItemSearchRequested);
return Task.CompletedTask;
}
private void ItemSearchRequested(ItemSearchRequestedMessage searchRequest)
{
if (!clientState.IsLoggedIn)
{
return;
}
var item = itemSheet.GetRowOrDefault(searchRequest.ItemId);
if (item == null)
{
return;
}
var itemList = inventoryMonitor.AllItems.Where(c => c.ItemId == searchRequest.ItemId);
if (configuration.ItemSearchScope != null && configuration.ItemSearchScope.Count != 0)
{
itemList = itemList.Where(c => calculator.Filter(configuration.ItemSearchScope, c));
}
var stringBuilder = new SeStringBuilder();
stringBuilder.Append("Searching for ");
stringBuilder.AddUiForeground(0x0225)
.AddUiGlow(0x0226)
.AddItemLinkRaw(item.RowId)
.AddUiForeground(0x01F4)
.AddUiGlow(0x01F5)
.AddText($"{(char) SeIconChar.LinkMarker}")
.AddUiGlowOff()
.AddUiForegroundOff()
.AddText(item.NameString)
.Add(RawPayload.LinkTerminator)
.AddUiGlowOff()
.AddUiForegroundOff();
stringBuilder.Append(":" + "\n");
var itemsByRetainer = itemList.GroupBy(c => c.RetainerId);
var searchResults = new List<string>();
uint normalTotal = 0;
uint hqTotal = 0;
foreach (var itemByRetainer in itemsByRetainer)
{
var character = characterMonitor.GetCharacterById(itemByRetainer.Key);
if(character == null) continue;
var itemsByCategories = itemByRetainer.GroupBy(c => c.SortedCategory);
searchResults.Add(" " + character.FormattedName + ":");
foreach (var itemByCategory in itemsByCategories)
{
var normalQuantity = itemByCategory.Where(c => c.Flags == InventoryItem.ItemFlags.None).Sum(c => c.Quantity);
var hqQuantity = itemByCategory.Where(c => c.Flags == InventoryItem.ItemFlags.HighQuality).Sum(c => c.Quantity);
if(normalQuantity == 0 && hqQuantity == 0) continue;
normalTotal = (uint)(normalTotal + normalQuantity);
hqTotal = (uint)(hqTotal + hqQuantity);
searchResults.Add($" {(normalQuantity != 0 ? normalQuantity.ToString() : "")}{(hqQuantity != 0 ? (normalQuantity != 0 ? "," : "") + hqQuantity + "\uE03c" : "")} found in {itemByCategory.Key.FormattedName()}");
}
}
if (normalTotal == 0 && hqTotal == 0)
{
searchResults.Add("No results found.");
}
else
{
searchResults.Add($"Total: {(normalTotal != 0 ? normalTotal.ToString() : "")}{(hqTotal != 0 ? "," + hqTotal + "\uE03c" : "")} found.");
}
stringBuilder.Append(String.Join("\n", searchResults));
chatGui.Print(stringBuilder.BuiltString);
}
public Task StopAsync(CancellationToken cancellationToken)
{
_logger.LogTrace("Stopping service {Type} ({This})", GetType().Name, this);
mediatorService.UnsubscribeAll(this);
_logger.LogTrace("Stopped service {Type} ({This})", GetType().Name, this);
return Task.CompletedTask;
}
public void Dispose()
{
mediatorService.UnsubscribeAll(this);
}
public MediatorService MediatorService => mediatorService;
} | 1 | 0.897317 | 1 | 0.897317 | game-dev | MEDIA | 0.41101 | game-dev,desktop-app | 0.973333 | 1 | 0.973333 |
kentjhall/mizu | 2,218 | core/hle/service/fgm/fgm.cpp | // Copyright 2018 yuzu emulator team
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
//
// Adapted by Kent Hall for mizu on Horizon Linux.
#include <memory>
#include "core/hle/ipc_helpers.h"
#include "core/hle/service/fgm/fgm.h"
#include "core/hle/service/service.h"
#include "core/hle/service/sm/sm.h"
namespace Service::FGM {
class IRequest final : public ServiceFramework<IRequest> {
public:
explicit IRequest(Core::System& system_) : ServiceFramework{system_, "IRequest"} {
// clang-format off
static const FunctionInfo functions[] = {
{0, nullptr, "Initialize"},
{1, nullptr, "Set"},
{2, nullptr, "Get"},
{3, nullptr, "Cancel"},
};
// clang-format on
RegisterHandlers(functions);
}
};
class FGM final : public ServiceFramework<FGM> {
public:
explicit FGM(Core::System& system_, const char* name) : ServiceFramework{system_, name} {
// clang-format off
static const FunctionInfo functions[] = {
{0, &FGM::Initialize, "Initialize"},
};
// clang-format on
RegisterHandlers(functions);
}
private:
void Initialize(Kernel::HLERequestContext& ctx) {
LOG_DEBUG(Service_FGM, "called");
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(ResultSuccess);
rb.PushIpcInterface<IRequest>(system);
}
};
class FGM_DBG final : public ServiceFramework<FGM_DBG> {
public:
explicit FGM_DBG(Core::System& system_) : ServiceFramework{system_, "fgm:dbg"} {
// clang-format off
static const FunctionInfo functions[] = {
{0, nullptr, "Initialize"},
{1, nullptr, "Read"},
{2, nullptr, "Cancel"},
};
// clang-format on
RegisterHandlers(functions);
}
};
void InstallInterfaces(SM::ServiceManager& sm, Core::System& system) {
std::make_shared<FGM>(system, "fgm")->InstallAsService(sm);
std::make_shared<FGM>(system, "fgm:0")->InstallAsService(sm);
std::make_shared<FGM>(system, "fgm:9")->InstallAsService(sm);
std::make_shared<FGM_DBG>(system)->InstallAsService(sm);
}
} // namespace Service::FGM
| 1 | 0.553511 | 1 | 0.553511 | game-dev | MEDIA | 0.26987 | game-dev | 0.586056 | 1 | 0.586056 |
sonata-project/SonataPageBundle | 1,201 | src/Model/Block.php | <?php
declare(strict_types=1);
/*
* This file is part of the Sonata Project package.
*
* (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sonata\PageBundle\Model;
use Sonata\BlockBundle\Model\BaseBlock;
use Sonata\BlockBundle\Model\BlockInterface;
/**
* @author Thomas Rabaix <thomas.rabaix@sonata-project.org>
*/
abstract class Block extends BaseBlock implements PageBlockInterface
{
/**
* @var int|string|null
*/
protected $id;
protected ?PageInterface $page = null;
public function getId()
{
return $this->id;
}
public function setId($id): void
{
$this->id = $id;
}
public function getPage(): ?PageInterface
{
return $this->page;
}
public function setPage(?PageInterface $page = null): void
{
$this->page = $page;
}
public function addChild(BlockInterface $child): void
{
parent::addChild($child);
if ($child instanceof PageBlockInterface) {
$child->setPage($this->getPage());
}
}
}
| 1 | 0.783261 | 1 | 0.783261 | game-dev | MEDIA | 0.343543 | game-dev | 0.728252 | 1 | 0.728252 |
AlibabaResearch/DAMO-ConvAI | 5,305 | s2sql/asdl/hypothesis.py | # coding=utf-8
from asdl.asdl import *
from asdl.asdl_ast import AbstractSyntaxTree
from asdl.transition_system import *
class Hypothesis(object):
def __init__(self):
self.tree = None
self.actions = []
self.score = 0.
self.frontier_node = None
self.frontier_field = None
self._value_buffer = []
# record the current time step
self.t = 0
def apply_action(self, action):
if self.tree is None: # the first action
assert isinstance(action, ApplyRuleAction), 'Invalid action [%s], only ApplyRule action is valid ' \
'at the beginning of decoding'
self.tree = AbstractSyntaxTree(action.production)
self.update_frontier_info()
elif self.frontier_node:
if isinstance(self.frontier_field.type, ASDLCompositeType):
if isinstance(action, ApplyRuleAction):
field_value = AbstractSyntaxTree(action.production)
field_value.created_time = self.t
self.frontier_field.add_value(field_value)
self.update_frontier_info()
elif isinstance(action, ReduceAction):
assert self.frontier_field.cardinality in ('optional', 'multiple'), 'Reduce action can only be ' \
'applied on field with multiple ' \
'cardinality'
self.frontier_field.set_finish()
self.update_frontier_info()
else:
raise ValueError('Invalid action [%s] on field [%s]' % (action, self.frontier_field))
else: # fill in a primitive field
if isinstance(action, GenTokenAction):
# only field of type string requires termination signal </primitive>
end_primitive = False
if self.frontier_field.type.name == 'string':
if action.is_stop_signal():
self.frontier_field.add_value(' '.join(self._value_buffer))
self._value_buffer = []
end_primitive = True
else:
self._value_buffer.append(action.token)
else:
self.frontier_field.add_value(action.token)
end_primitive = True
if end_primitive and self.frontier_field.cardinality in ('single', 'optional'):
self.frontier_field.set_finish()
self.update_frontier_info()
elif isinstance(action, ReduceAction):
assert self.frontier_field.cardinality in ('optional', 'multiple'), 'Reduce action can only be ' \
'applied on field with multiple ' \
'cardinality'
self.frontier_field.set_finish()
self.update_frontier_info()
else:
raise ValueError('Can only invoke GenToken or Reduce actions on primitive fields')
self.t += 1
self.actions.append(action)
def update_frontier_info(self):
def _find_frontier_node_and_field(tree_node):
# return None if each field of this ast node is realized else unfinished ast node, unrealized field
if tree_node:
for field in tree_node.fields:
# if it's an intermediate node, check its children
if isinstance(field.type, ASDLCompositeType) and field.value:
if field.cardinality in ('single', 'optional'): iter_values = [field.value]
else: iter_values = field.value
for child_node in iter_values:
result = _find_frontier_node_and_field(child_node)
if result: return result
# now all its possible children are checked
if not field.finished:
return tree_node, field
return None
else: return None
frontier_info = _find_frontier_node_and_field(self.tree)
if frontier_info:
self.frontier_node, self.frontier_field = frontier_info
else:
self.frontier_node, self.frontier_field = None, None
def clone_and_apply_action(self, action):
new_hyp = self.copy()
new_hyp.apply_action(action)
return new_hyp
def copy(self):
new_hyp = Hypothesis()
if self.tree:
new_hyp.tree = self.tree.copy()
new_hyp.actions = list(self.actions)
new_hyp.score = self.score
new_hyp._value_buffer = list(self._value_buffer)
new_hyp.t = self.t
new_hyp.update_frontier_info()
return new_hyp
@property
def completed(self):
return self.tree and self.frontier_field is None
| 1 | 0.902494 | 1 | 0.902494 | game-dev | MEDIA | 0.301273 | game-dev | 0.972499 | 1 | 0.972499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.