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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
VolantisDev/Launchpad | 1,959 | Lib/Launchpad/BulkOperation/DetectedGamesOp/AddDetectedGamesOp.ahk | class AddDetectedGamesOp extends BulkOperationBase {
detectedGames := ""
launcherManager := ""
state := ""
progressTitle := "Adding Selected Games"
progressText := "Please wait while Launchpad adds the selected games..."
shouldNotify := true
successMessage := "Added {n} games."
failedMessage := "Failed to add {n} games."
__New(app, detectedGames, launcherManager, state, owner := "") {
this.detectedGames := detectedGames
this.launcherManager := launcherManager
this.state := state
super.__New(app, owner)
}
RunAction() {
if (this.useProgress) {
this.progress.SetRange(0, this.detectedGames.Count)
}
if (!this.state.State.Has("DetectedGames")) {
this.state.State["DetectedGames"] := Map()
}
modifiedLaunchers := false
for key, detectedGameObj in this.detectedGames {
this.StartItem(detectedGameObj.key, "Adding " . detectedGameObj.key . "...")
if (this.launcherManager.Has(detectedGameObj.key)) {
detectedGameObj.UpdateLauncher(this.launcherManager[detectedGameObj.key])
} else {
detectedGameObj.CreateLauncher(this.launcherManager)
}
if (!this.state.State["DetectedGames"].Has(detectedGameObj.platform.displayName)) {
this.state.State["DetectedGames"][detectedGameObj.platform.displayName] := Map()
}
this.state.State["DetectedGames"][detectedGameObj.platform.displayName][detectedGameObj.detectedKey] := detectedGameObj.key
this.results[detectedGameObj.key] := true
modifiedLaunchers := true
this.FinishItem(detectedGameObj.key, true, "Finished adding " . detectedGameObj.key . ".")
}
this.state.SaveState()
if (modifiedLaunchers) {
this.launcherManager.LoadComponents(true)
}
}
}
| 412 | 0.845905 | 1 | 0.845905 | game-dev | MEDIA | 0.602576 | game-dev,desktop-app | 0.849796 | 1 | 0.849796 |
SAT-R/sa3 | 5,703 | src/game/enemies/gaogao.c | #include "global.h"
#include "malloc_vram.h"
#include "sprite.h"
#include "task.h"
#include "game/camera.h"
#include "game/enemy_unknown.h"
#include "game/entity.h"
#include "game/player.h"
#include "game/stage.h"
#include "constants/animations.h"
#include "constants/anim_sizes.h"
extern TileInfo2 gUnknown_080D1F5C[2];
typedef struct {
/* 0x00 */ MapEntity *me;
/* 0x04 */ u8 id;
/* 0x05 */ u8 spriteX;
/* 0x06 */ s8 unk6;
/* 0x07 */ s8 unk7;
/* 0x08 */ u16 region[2];
/* 0x0C */ s32 unkC;
/* 0x10 */ s32 unk10;
/* 0x14 */ Vec2_32 qPos;
/* 0x1C */ s32 unk1C;
/* 0x20 */ s32 unk20;
/* 0x24 */ Sprite s;
/* 0x4C */ u8 filler4C[0x4];
/* 0x50 */ u16 unk50[2]; // TODO: type
} GaoGao; /* size: 0x54 */
void Task_GaoGao(void);
void TaskDestructor_GaoGao(struct Task *t);
void sub_805DF94(GaoGao *);
void Task_805E0AC(void);
void sub_805E144(GaoGao *);
AnimCmdResult sub_805E17C(GaoGao *);
bool32 sub_805E1F0(GaoGao *);
void CreateEntity_GaoGao(MapEntity *me, u16 regionX, u16 regionY, u8 id)
{
struct Task *t = TaskCreate(Task_GaoGao, sizeof(GaoGao), 0x2100, 0, TaskDestructor_GaoGao);
GaoGao *enemy = TASK_DATA(t);
s32 qX, qY;
enemy->me = me;
enemy->spriteX = me->x;
enemy->id = id;
enemy->region[0] = regionX;
enemy->region[1] = regionY;
qX = Q(me->x * TILE_WIDTH);
enemy->qPos.x = qX;
qY = Q(me->y * TILE_WIDTH);
enemy->qPos.y = qY;
enemy->unkC = qX;
enemy->unk10 = qY;
enemy->unk1C = qX + Q(me->d.sData[0] * TILE_WIDTH);
enemy->unk20 = enemy->unk1C + Q(me->d.uData[2] * TILE_WIDTH);
if (me->d.uData[4] & 0x8) {
enemy->unk7 = -1;
} else {
enemy->unk7 = +1;
}
enemy->unk6 = 0;
CpuFill16(0, &enemy->unk50, sizeof(enemy->unk50));
sub_805DF94(enemy);
SET_MAP_ENTITY_INITIALIZED(me);
}
void sub_805DF94(GaoGao *enemy)
{
void *tiles = ALLOC_TILES(ANIM_GAOGAO);
Sprite *s = &enemy->s;
s->tiles = tiles;
s->anim = gUnknown_080D1F5C[0].anim;
s->variant = gUnknown_080D1F5C[0].variant;
s->prevVariant = -1;
s->x = TO_WORLD_POS_RAW(I(enemy->qPos.x), enemy->region[0]) - gCamera.x;
s->y = TO_WORLD_POS_RAW(I(enemy->qPos.y), enemy->region[1]) - gCamera.y;
s->oamFlags = SPRITE_OAM_ORDER(18);
s->animCursor = 0;
s->qAnimDelay = 0;
s->animSpeed = SPRITE_ANIM_SPEED(1.0);
s->palId = 0;
s->frameFlags = SPRITE_FLAG(PRIORITY, 1);
if (enemy->unk7 < 0) {
s->frameFlags |= SPRITE_FLAG_MASK_X_FLIP;
}
s->hitboxes[0].index = HITBOX_STATE_INACTIVE;
UpdateSpriteAnimation(s);
}
void Task_GaoGao(void)
{
GaoGao *enemy = TASK_DATA(gCurTask);
sub_805CD70(&enemy->qPos, NULL, enemy->region, &enemy->unk6);
if ((gStageData.unk4 != 1) && (gStageData.unk4 != 2) && (gStageData.unk4 != 4)) {
sub_805E144(enemy);
}
if (sub_805E1F0(enemy) == TRUE) {
TaskDestroy(gCurTask);
return;
}
sub_805E17C(enemy);
if ((enemy->qPos.x <= enemy->unk1C) || (enemy->qPos.x >= enemy->unk20)) {
Sprite *s = &enemy->s;
s->anim = gUnknown_080D1F5C[1].anim;
s->variant = gUnknown_080D1F5C[1].variant;
gCurTask->main = Task_805E0AC;
}
}
void Task_805E0AC(void)
{
GaoGao *enemy = TASK_DATA(gCurTask);
AnimCmdResult acmdRes = sub_805E17C(enemy);
if (sub_805E1F0(enemy) == TRUE) {
TaskDestroy(gCurTask);
return;
}
if ((gStageData.unk4 != 1) && (gStageData.unk4 != 2) && (gStageData.unk4 != 4) && (acmdRes == ACMD_RESULT__ENDED)) {
Sprite *s = &enemy->s;
if (s->frameFlags & SPRITE_FLAG_MASK_X_FLIP) {
s->frameFlags &= ~SPRITE_FLAG_MASK_X_FLIP;
enemy->unk7 = +1;
} else {
s->frameFlags |= SPRITE_FLAG_MASK_X_FLIP;
enemy->unk7 = -1;
}
s->anim = gUnknown_080D1F5C[0].anim;
s->variant = gUnknown_080D1F5C[0].variant;
gCurTask->main = Task_GaoGao;
}
}
void sub_805E144(GaoGao *enemy)
{
if (enemy->s.frameFlags & SPRITE_FLAG_MASK_X_FLIP) {
if (enemy->qPos.x <= enemy->unk20) {
enemy->qPos.x += Q(0.25);
if (enemy->qPos.x > enemy->unk20) {
enemy->qPos.x = enemy->unk20;
}
}
} else {
if (enemy->qPos.x >= enemy->unk1C) {
enemy->qPos.x -= Q(0.25);
if (enemy->qPos.x < enemy->unk1C) {
enemy->qPos.x = enemy->unk1C;
}
}
}
}
AnimCmdResult sub_805E17C(GaoGao *enemy)
{
AnimCmdResult acmdRes;
Sprite *s = &enemy->s;
s->x = TO_WORLD_POS_RAW(I(enemy->qPos.x), enemy->region[0]) - gCamera.x;
s->y = TO_WORLD_POS_RAW(I(enemy->qPos.y), enemy->region[1]) - gCamera.y;
acmdRes = UpdateSpriteAnimation(s);
DisplaySprite(s);
return acmdRes;
}
bool32 sub_805E1C0(GaoGao *enemy, EnemyUnknownStruc0 *param1)
{
Sprite *s;
param1->me = NULL;
param1->spriteX = 0;
param1->unk4 = 0;
s = &enemy->s;
param1->spr = s;
param1->posX = enemy->qPos.x;
param1->posY = enemy->qPos.y;
param1->regionX = enemy->region[0];
param1->regionY = enemy->region[1];
return sub_805C890(param1, enemy->unk7);
}
bool32 sub_805E1F0(GaoGao *enemy)
{
EnemyUnknownStruc0 unk;
unk.unk4 = sub_805E1C0(enemy, &unk);
unk.spr = &enemy->s;
unk.posX = enemy->unkC;
unk.posY = enemy->unk10;
unk.regionX = enemy->region[0];
unk.regionY = enemy->region[1];
unk.me = enemy->me;
unk.spriteX = enemy->spriteX;
return sub_805C280(&unk);
}
void TaskDestructor_GaoGao(struct Task *t)
{
GaoGao *enemy = TASK_DATA(t);
VramFree(enemy->s.tiles);
} | 412 | 0.766332 | 1 | 0.766332 | game-dev | MEDIA | 0.990135 | game-dev | 0.985768 | 1 | 0.985768 |
rafaelcastrocouto/foda | 3,263 | client/js/ai/kotl.js | game.heroesAI.kotl = {
move: {
default: 'alert'
},
play: function (card, cardData) {
var illuminate = $('.'+game.ai.side+'decks .hand .skills.kotl-illuminate');
var mana = $('.'+game.ai.side+'decks .hand .skills.kotl-mana');
var blind = $('.'+game.ai.side+'decks .hand .skills.kotl-blind');
var ult = $('.'+game.ai.side+'decks .hand .skills.kotl-ult');
if (!$('.map .'+game.ai.side+'.kotl').length) {
illuminate.data('ai discard', illuminate.data('ai discard') + 1);
blind.data('ai discard', blind.data('ai discard') + 1);
}
if (card.canCast(illuminate)) {
game.aia.castLine(card, illuminate);
}
if (card.canCast(blind)) {
game.aia.castArea(card, blind);
}
if (card.canCast(mana)) {
cardData['can-cast'] = true;
if (game[card.side()].skills.hand.children().length < 8) {
cardData['cast-strats'].push({
priority: 50,
skill: 'mana',
card: mana.attr('id'),
target: card.attr('id')
});
}
}
if (card.canCast(ult)) {
cardData['can-cast'] = true;
card.around(ult.data('cast range'), function (spot) {
var targets = 0, p = 0;
spot.around(ult.data('aoe range'), function (nspot) {
var cardInRange = $('.card.'+game.opponent(game.ai.side)+':not(.invisible, .ghost, .dead)', nspot);
if (cardInRange.length) {
targets++;
p += parseInt((cardInRange.data('hp')-cardInRange.data('current hp'))/4);
if (cardInRange.hasClass('channeling towers')) p += 20;
if (cardInRange.hasClass('units')) p -= 5;
}
});
if (targets > 1) {
cardData['cast-strats'].push({
priority: p,
skill: 'ult',
card: ult.attr('id'),
target: spot.attr('id')
});
}
});
}
card.data('ai', JSON.stringify(cardData));
},
defend: function (card, cardData) {
var illuminate = game.data.skills.kotl.illuminate;
var range = illuminate['aoe range'];
var width = illuminate['aoe width'];
var channeling = card.hasClass('channeling');
card.around(1, function (dirSpot) {
card.inLine(dirSpot, range, width, function (spot) {
var spotData = JSON.parse(spot.data('ai'));
spotData.priority -= 5;
if (channeling) spotData.priority -= 25;
spotData['can-be-casted'] = true;
spot.data('ai', JSON.stringify(spotData));
var cardInRange = $('.card.'+card.opponent(), spot);
if (cardInRange.length && !cardInRange.hasClasses('ghost dead towers')) {
var cardInRangeData = JSON.parse(cardInRange.data('ai'));
cardInRangeData.strats.dodge += 10;
if (channeling) cardInRangeData.strats.dodge += 15;
cardInRange.data('ai', JSON.stringify(cardInRangeData));
}
});
});
$('.map .card.'+card.opponent()).each(function (i, el) {
var opponent = $(el);
var opponentData = JSON.parse(opponent.data('ai'));
if (opponent.hasBuff('kotl-blind')) {
opponentData.strats.siege += 30;
}
opponent.data('ai', JSON.stringify(opponentData));
});
card.data('ai', JSON.stringify(cardData));
}
}; | 412 | 0.690473 | 1 | 0.690473 | game-dev | MEDIA | 0.516723 | game-dev,web-frontend | 0.880312 | 1 | 0.880312 |
Pascal-Jansen/Bayesian-Optimization-for-Unity | 17,808 | Library/PackageCache/com.unity.ugui@f250afc9b68d/Runtime/TMP/TMP_DefaultControls.cs | using UnityEngine;
using System.Collections;
using UnityEngine.UI;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace TMPro
{
public static class TMP_DefaultControls
{
public struct Resources
{
public Sprite standard;
public Sprite background;
public Sprite inputField;
public Sprite knob;
public Sprite checkmark;
public Sprite dropdown;
public Sprite mask;
}
private const float kWidth = 160f;
private const float kThickHeight = 30f;
private const float kThinHeight = 20f;
private static Vector2 s_TextElementSize = new Vector2(100f, 100f);
private static Vector2 s_ThickElementSize = new Vector2(kWidth, kThickHeight);
private static Vector2 s_ThinElementSize = new Vector2(kWidth, kThinHeight);
//private static Vector2 s_ImageElementSize = new Vector2(100f, 100f);
private static Color s_DefaultSelectableColor = new Color(1f, 1f, 1f, 1f);
//private static Color s_PanelColor = new Color(1f, 1f, 1f, 0.392f);
private static Color s_TextColor = new Color(50f / 255f, 50f / 255f, 50f / 255f, 1f);
private static GameObject CreateUIElementRoot(string name, Vector2 size)
{
GameObject root;
#if UNITY_EDITOR
root = ObjectFactory.CreateGameObject(name, typeof(RectTransform));
var rt = root.GetComponent<RectTransform>();
rt.sizeDelta = size;
#else
root = new GameObject(name);
RectTransform rectTransform = root.AddComponent<RectTransform>();
rectTransform.sizeDelta = size;
#endif
return root;
}
static GameObject CreateUIObject(string name, GameObject parent)
{
GameObject go;
#if UNITY_EDITOR
go = ObjectFactory.CreateGameObject(name, typeof(RectTransform));
#else
go = new GameObject(name);
go.AddComponent<RectTransform>();
#endif
SetParentAndAlign(go, parent);
return go;
}
private static void SetDefaultTextValues(TMP_Text lbl)
{
// Set text values we want across UI elements in default controls.
// Don't set values which are the same as the default values for the Text component,
// since there's no point in that, and it's good to keep them as consistent as possible.
lbl.color = s_TextColor;
lbl.fontSize = 14;
}
private static void SetDefaultColorTransitionValues(Selectable slider)
{
ColorBlock colors = slider.colors;
colors.highlightedColor = new Color(0.882f, 0.882f, 0.882f);
colors.pressedColor = new Color(0.698f, 0.698f, 0.698f);
colors.disabledColor = new Color(0.521f, 0.521f, 0.521f);
}
private static void SetParentAndAlign(GameObject child, GameObject parent)
{
if (parent == null)
return;
#if UNITY_EDITOR
Undo.SetTransformParent(child.transform, parent.transform, "");
#else
child.transform.SetParent(parent.transform, false);
#endif
SetLayerRecursively(child, parent.layer);
}
private static void SetLayerRecursively(GameObject go, int layer)
{
go.layer = layer;
Transform t = go.transform;
for (int i = 0; i < t.childCount; i++)
SetLayerRecursively(t.GetChild(i).gameObject, layer);
}
// Actual controls
public static GameObject CreateScrollbar(Resources resources)
{
// Create GOs Hierarchy
GameObject scrollbarRoot = CreateUIElementRoot("Scrollbar", s_ThinElementSize);
GameObject sliderArea = CreateUIObject("Sliding Area", scrollbarRoot);
GameObject handle = CreateUIObject("Handle", sliderArea);
Image bgImage = AddComponent<Image>(scrollbarRoot);
bgImage.sprite = resources.background;
bgImage.type = Image.Type.Sliced;
bgImage.color = s_DefaultSelectableColor;
Image handleImage = AddComponent<Image>(handle);
handleImage.sprite = resources.standard;
handleImage.type = Image.Type.Sliced;
handleImage.color = s_DefaultSelectableColor;
RectTransform sliderAreaRect = sliderArea.GetComponent<RectTransform>();
sliderAreaRect.sizeDelta = new Vector2(-20, -20);
sliderAreaRect.anchorMin = Vector2.zero;
sliderAreaRect.anchorMax = Vector2.one;
RectTransform handleRect = handle.GetComponent<RectTransform>();
handleRect.sizeDelta = new Vector2(20, 20);
Scrollbar scrollbar = AddComponent<Scrollbar>(scrollbarRoot);
scrollbar.handleRect = handleRect;
scrollbar.targetGraphic = handleImage;
SetDefaultColorTransitionValues(scrollbar);
return scrollbarRoot;
}
public static GameObject CreateButton(Resources resources)
{
GameObject buttonRoot = CreateUIElementRoot("Button", s_ThickElementSize);
GameObject childText;
#if UNITY_EDITOR
childText = ObjectFactory.CreateGameObject("Text (TMP)", typeof(RectTransform));
#else
childText = new GameObject("Text (TMP)");
childText.AddComponent<RectTransform>();
#endif
SetParentAndAlign(childText, buttonRoot);
Image image = AddComponent<Image>(buttonRoot);
image.sprite = resources.standard;
image.type = Image.Type.Sliced;
image.color = s_DefaultSelectableColor;
Button bt = AddComponent<Button>(buttonRoot);
SetDefaultColorTransitionValues(bt);
TextMeshProUGUI text = AddComponent<TextMeshProUGUI>(childText);
text.text = "Button";
text.alignment = TextAlignmentOptions.Center;
SetDefaultTextValues(text);
RectTransform textRectTransform = childText.GetComponent<RectTransform>();
textRectTransform.anchorMin = Vector2.zero;
textRectTransform.anchorMax = Vector2.one;
textRectTransform.sizeDelta = Vector2.zero;
return buttonRoot;
}
public static GameObject CreateText(Resources resources)
{
GameObject go = null;
#if UNITY_EDITOR
go = ObjectFactory.CreateGameObject("Text (TMP)", typeof(TextMeshProUGUI));
#else
go = CreateUIElementRoot("Text (TMP)", s_TextElementSize);
go.AddComponent<TextMeshProUGUI>();
#endif
return go;
}
public static GameObject CreateInputField(Resources resources)
{
GameObject root = CreateUIElementRoot("InputField (TMP)", s_ThickElementSize);
GameObject textArea = CreateUIObject("Text Area", root);
GameObject childPlaceholder = CreateUIObject("Placeholder", textArea);
GameObject childText = CreateUIObject("Text", textArea);
Image image = AddComponent<Image>(root);
image.sprite = resources.inputField;
image.type = Image.Type.Sliced;
image.color = s_DefaultSelectableColor;
TMP_InputField inputField = AddComponent<TMP_InputField>(root);
SetDefaultColorTransitionValues(inputField);
RectMask2D rectMask = AddComponent<RectMask2D>(textArea);
rectMask.padding = new Vector4(-8, -5, -8, -5);
RectTransform textAreaRectTransform = textArea.GetComponent<RectTransform>();
textAreaRectTransform.anchorMin = Vector2.zero;
textAreaRectTransform.anchorMax = Vector2.one;
textAreaRectTransform.sizeDelta = Vector2.zero;
textAreaRectTransform.offsetMin = new Vector2(10, 6);
textAreaRectTransform.offsetMax = new Vector2(-10, -7);
TextMeshProUGUI text = AddComponent<TextMeshProUGUI>(childText);
text.text = "";
text.textWrappingMode = TextWrappingModes.NoWrap;
text.extraPadding = true;
text.richText = true;
SetDefaultTextValues(text);
TextMeshProUGUI placeholder = AddComponent<TextMeshProUGUI>(childPlaceholder);
placeholder.text = "Enter text...";
placeholder.fontSize = 14;
placeholder.fontStyle = FontStyles.Italic;
placeholder.textWrappingMode = TextWrappingModes.NoWrap;
placeholder.extraPadding = true;
// Make placeholder color half as opaque as normal text color.
Color placeholderColor = text.color;
placeholderColor.a *= 0.5f;
placeholder.color = placeholderColor;
// Add Layout component to placeholder.
AddComponent<LayoutElement>(placeholder.gameObject).ignoreLayout = true;
RectTransform textRectTransform = childText.GetComponent<RectTransform>();
textRectTransform.anchorMin = Vector2.zero;
textRectTransform.anchorMax = Vector2.one;
textRectTransform.sizeDelta = Vector2.zero;
textRectTransform.offsetMin = new Vector2(0, 0);
textRectTransform.offsetMax = new Vector2(0, 0);
RectTransform placeholderRectTransform = childPlaceholder.GetComponent<RectTransform>();
placeholderRectTransform.anchorMin = Vector2.zero;
placeholderRectTransform.anchorMax = Vector2.one;
placeholderRectTransform.sizeDelta = Vector2.zero;
placeholderRectTransform.offsetMin = new Vector2(0, 0);
placeholderRectTransform.offsetMax = new Vector2(0, 0);
inputField.textViewport = textAreaRectTransform;
inputField.textComponent = text;
inputField.placeholder = placeholder;
inputField.fontAsset = text.font;
return root;
}
public static GameObject CreateDropdown(Resources resources)
{
GameObject root = CreateUIElementRoot("Dropdown", s_ThickElementSize);
GameObject label = CreateUIObject("Label", root);
GameObject arrow = CreateUIObject("Arrow", root);
GameObject template = CreateUIObject("Template", root);
GameObject viewport = CreateUIObject("Viewport", template);
GameObject content = CreateUIObject("Content", viewport);
GameObject item = CreateUIObject("Item", content);
GameObject itemBackground = CreateUIObject("Item Background", item);
GameObject itemCheckmark = CreateUIObject("Item Checkmark", item);
GameObject itemLabel = CreateUIObject("Item Label", item);
// Sub controls.
GameObject scrollbar = CreateScrollbar(resources);
scrollbar.name = "Scrollbar";
SetParentAndAlign(scrollbar, template);
Scrollbar scrollbarScrollbar = scrollbar.GetComponent<Scrollbar>();
scrollbarScrollbar.SetDirection(Scrollbar.Direction.BottomToTop, true);
RectTransform vScrollbarRT = scrollbar.GetComponent<RectTransform>();
vScrollbarRT.anchorMin = Vector2.right;
vScrollbarRT.anchorMax = Vector2.one;
vScrollbarRT.pivot = Vector2.one;
vScrollbarRT.sizeDelta = new Vector2(vScrollbarRT.sizeDelta.x, 0);
// Setup item UI components.
TextMeshProUGUI itemLabelText = AddComponent<TextMeshProUGUI>(itemLabel);
SetDefaultTextValues(itemLabelText);
itemLabelText.alignment = TextAlignmentOptions.Left;
Image itemBackgroundImage = AddComponent<Image>(itemBackground);
itemBackgroundImage.color = new Color32(245, 245, 245, 255);
Image itemCheckmarkImage = AddComponent<Image>(itemCheckmark);
itemCheckmarkImage.sprite = resources.checkmark;
Toggle itemToggle = AddComponent<Toggle>(item);
itemToggle.targetGraphic = itemBackgroundImage;
itemToggle.graphic = itemCheckmarkImage;
itemToggle.isOn = true;
// Setup template UI components.
Image templateImage = AddComponent<Image>(template);
templateImage.sprite = resources.standard;
templateImage.type = Image.Type.Sliced;
ScrollRect templateScrollRect = AddComponent<ScrollRect>(template);
templateScrollRect.content = (RectTransform)content.transform;
templateScrollRect.viewport = (RectTransform)viewport.transform;
templateScrollRect.horizontal = false;
templateScrollRect.movementType = ScrollRect.MovementType.Clamped;
templateScrollRect.verticalScrollbar = scrollbarScrollbar;
templateScrollRect.verticalScrollbarVisibility = ScrollRect.ScrollbarVisibility.AutoHideAndExpandViewport;
templateScrollRect.verticalScrollbarSpacing = -3;
Mask scrollRectMask = AddComponent<Mask>(viewport);
scrollRectMask.showMaskGraphic = false;
Image viewportImage = AddComponent<Image>(viewport);
viewportImage.sprite = resources.mask;
viewportImage.type = Image.Type.Sliced;
// Setup dropdown UI components.
TextMeshProUGUI labelText = AddComponent<TextMeshProUGUI>(label);
SetDefaultTextValues(labelText);
labelText.alignment = TextAlignmentOptions.Left;
Image arrowImage = AddComponent<Image>(arrow);
arrowImage.sprite = resources.dropdown;
Image backgroundImage = AddComponent<Image>(root);
backgroundImage.sprite = resources.standard;
backgroundImage.color = s_DefaultSelectableColor;
backgroundImage.type = Image.Type.Sliced;
TMP_Dropdown dropdown = AddComponent<TMP_Dropdown>(root);
dropdown.targetGraphic = backgroundImage;
SetDefaultColorTransitionValues(dropdown);
dropdown.template = template.GetComponent<RectTransform>();
dropdown.captionText = labelText;
dropdown.itemText = itemLabelText;
// Setting default Item list.
itemLabelText.text = "Option A";
dropdown.options.Add(new TMP_Dropdown.OptionData {text = "Option A" });
dropdown.options.Add(new TMP_Dropdown.OptionData {text = "Option B" });
dropdown.options.Add(new TMP_Dropdown.OptionData {text = "Option C" });
dropdown.RefreshShownValue();
// Set up RectTransforms.
RectTransform labelRT = label.GetComponent<RectTransform>();
labelRT.anchorMin = Vector2.zero;
labelRT.anchorMax = Vector2.one;
labelRT.offsetMin = new Vector2(10, 6);
labelRT.offsetMax = new Vector2(-25, -7);
RectTransform arrowRT = arrow.GetComponent<RectTransform>();
arrowRT.anchorMin = new Vector2(1, 0.5f);
arrowRT.anchorMax = new Vector2(1, 0.5f);
arrowRT.sizeDelta = new Vector2(20, 20);
arrowRT.anchoredPosition = new Vector2(-15, 0);
RectTransform templateRT = template.GetComponent<RectTransform>();
templateRT.anchorMin = new Vector2(0, 0);
templateRT.anchorMax = new Vector2(1, 0);
templateRT.pivot = new Vector2(0.5f, 1);
templateRT.anchoredPosition = new Vector2(0, 2);
templateRT.sizeDelta = new Vector2(0, 150);
RectTransform viewportRT = viewport.GetComponent<RectTransform>();
viewportRT.anchorMin = new Vector2(0, 0);
viewportRT.anchorMax = new Vector2(1, 1);
viewportRT.sizeDelta = new Vector2(-18, 0);
viewportRT.pivot = new Vector2(0, 1);
RectTransform contentRT = content.GetComponent<RectTransform>();
contentRT.anchorMin = new Vector2(0f, 1);
contentRT.anchorMax = new Vector2(1f, 1);
contentRT.pivot = new Vector2(0.5f, 1);
contentRT.anchoredPosition = new Vector2(0, 0);
contentRT.sizeDelta = new Vector2(0, 28);
RectTransform itemRT = item.GetComponent<RectTransform>();
itemRT.anchorMin = new Vector2(0, 0.5f);
itemRT.anchorMax = new Vector2(1, 0.5f);
itemRT.sizeDelta = new Vector2(0, 20);
RectTransform itemBackgroundRT = itemBackground.GetComponent<RectTransform>();
itemBackgroundRT.anchorMin = Vector2.zero;
itemBackgroundRT.anchorMax = Vector2.one;
itemBackgroundRT.sizeDelta = Vector2.zero;
RectTransform itemCheckmarkRT = itemCheckmark.GetComponent<RectTransform>();
itemCheckmarkRT.anchorMin = new Vector2(0, 0.5f);
itemCheckmarkRT.anchorMax = new Vector2(0, 0.5f);
itemCheckmarkRT.sizeDelta = new Vector2(20, 20);
itemCheckmarkRT.anchoredPosition = new Vector2(10, 0);
RectTransform itemLabelRT = itemLabel.GetComponent<RectTransform>();
itemLabelRT.anchorMin = Vector2.zero;
itemLabelRT.anchorMax = Vector2.one;
itemLabelRT.offsetMin = new Vector2(20, 1);
itemLabelRT.offsetMax = new Vector2(-10, -2);
template.SetActive(false);
return root;
}
private static T AddComponent<T>(GameObject go) where T : Component
{
#if UNITY_EDITOR
return ObjectFactory.AddComponent<T>(go);
#else
return go.AddComponent<T>();
#endif
}
}
}
| 412 | 0.92732 | 1 | 0.92732 | game-dev | MEDIA | 0.88757 | game-dev | 0.987793 | 1 | 0.987793 |
moai/moai-dev | 2,350 | samples/pathfinding-diamond/main.lua | ----------------------------------------------------------------
-- Copyright (c) 2010-2017 Zipline Games, Inc.
-- All Rights Reserved.
-- http://getmoai.com
----------------------------------------------------------------
MOAISim.openWindow ( "test", 544, 272 )
viewport = MOAIViewport.new ()
viewport:setSize ( 544, 272 )
viewport:setScale ( 544, 272 )
layer = MOAIPartitionViewLayer.new ()
layer:setViewport ( viewport )
layer:pushRenderPass ()
grid = MOAIGrid.new ()
grid:initDiamondGrid ( 8, 16, 64, 32 )
grid:setRow ( 1, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x00, 0x03 )
grid:setRow ( 2, 0x03, 0x03, 0x03, 0x03, 0x03, 0x00, 0x03, 0x03 )
grid:setRow ( 3, 0x03, 0x03, 0x00, 0x03, 0x03, 0x00, 0x03, 0x03 )
grid:setRow ( 4, 0x03, 0x00, 0x03, 0x03, 0x00, 0x03, 0x03, 0x03 )
grid:setRow ( 5, 0x03, 0x00, 0x03, 0x03, 0x00, 0x03, 0x03, 0x03 )
grid:setRow ( 6, 0x00, 0x03, 0x03, 0x00, 0x03, 0x03, 0x00, 0x03 )
grid:setRow ( 7, 0x00, 0x03, 0x03, 0x00, 0x03, 0x03, 0x00, 0x03 )
grid:setRow ( 8, 0x03, 0x03, 0x00, 0x03, 0x03, 0x00, 0x03, 0x03 )
grid:setRow ( 9, 0x03, 0x03, 0x00, 0x03, 0x03, 0x00, 0x03, 0x03 )
grid:setRow ( 10, 0x03, 0x00, 0x03, 0x03, 0x00, 0x03, 0x03, 0x00 )
grid:setRow ( 11, 0x03, 0x00, 0x03, 0x03, 0x00, 0x03, 0x03, 0x00 )
grid:setRow ( 12, 0x03, 0x03, 0x03, 0x00, 0x03, 0x03, 0x00, 0x03 )
grid:setRow ( 13, 0x03, 0x03, 0x03, 0x00, 0x03, 0x03, 0x00, 0x03 )
grid:setRow ( 14, 0x03, 0x03, 0x00, 0x03, 0x03, 0x00, 0x03, 0x03 )
grid:setRow ( 15, 0x03, 0x03, 0x00, 0x03, 0x03, 0x03, 0x03, 0x03 )
grid:setRow ( 16, 0x03, 0x00, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03 )
tileDeck = MOAITileDeck2D.new ()
tileDeck:setTexture ( "diamond-tiles.png" )
tileDeck:setSize ( 4, 4 )
prop = MOAIProp.new ()
prop:setDeck ( tileDeck )
prop:setGrid ( grid )
prop:setLoc ( -272, -128 )
prop:setPartition ( layer )
startNode = grid:getCellAddr ( 1, 1 )
endNode = grid:getCellAddr ( 8, 16 )
pathFinder = MOAIPathFinder.new ()
pathFinder:setGraph ( grid )
pathFinder:setHeuristic ( MOAIGridPathGraph.EUCLIDEAN_DISTANCE )
pathFinder:init ( startNode, endNode )
while pathFinder:findPath ( 3 ) do
print ( 'finding...' )
end
pathSize = pathFinder:getPathSize ()
for i = 1, pathSize do
entry = pathFinder:getPathEntry ( i )
x, y = grid:cellAddrToCoord ( entry )
grid:setTile ( x, y, 0x02 )
end
grid:setTile ( 1, 1, 0x01 )
grid:setTile ( 8, 16, 0x04 ) | 412 | 0.633061 | 1 | 0.633061 | game-dev | MEDIA | 0.851534 | game-dev | 0.552555 | 1 | 0.552555 |
Creators-of-Create/Create | 2,656 | src/main/java/com/simibubi/create/content/decoration/slidingDoor/DoorControl.java | package com.simibubi.create.content.decoration.slidingDoor;
import java.util.Arrays;
import java.util.function.Consumer;
import com.simibubi.create.foundation.gui.widget.Label;
import com.simibubi.create.foundation.gui.widget.ScrollInput;
import com.simibubi.create.foundation.gui.widget.SelectionScrollInput;
import com.simibubi.create.foundation.utility.CreateLang;
import net.createmod.catnip.data.Pair;
import net.createmod.catnip.lang.Lang;
import net.minecraft.client.Minecraft;
import net.minecraft.core.Direction;
import net.minecraft.network.chat.Component;
import net.minecraft.world.entity.Entity;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
public enum DoorControl {
ALL, NORTH, EAST, SOUTH, WEST, NONE;
private static String[] valuesAsString() {
DoorControl[] values = values();
return Arrays.stream(values)
.map(dc -> Lang.asId(dc.name()))
.toList()
.toArray(new String[values.length]);
}
public boolean matches(Direction doorDirection) {
return switch (this) {
case ALL -> true;
case NORTH -> doorDirection == Direction.NORTH;
case EAST -> doorDirection == Direction.EAST;
case SOUTH -> doorDirection == Direction.SOUTH;
case WEST -> doorDirection == Direction.WEST;
default -> false;
};
}
@OnlyIn(Dist.CLIENT)
public static Pair<ScrollInput, Label> createWidget(int x, int y, Consumer<DoorControl> callback,
DoorControl initial) {
DoorControl playerFacing = NONE;
Entity cameraEntity = Minecraft.getInstance().cameraEntity;
if (cameraEntity != null) {
Direction direction = cameraEntity.getDirection();
if (direction == Direction.EAST)
playerFacing = EAST;
if (direction == Direction.WEST)
playerFacing = WEST;
if (direction == Direction.NORTH)
playerFacing = NORTH;
if (direction == Direction.SOUTH)
playerFacing = SOUTH;
}
Label label = new Label(x + 4, y + 6, Component.empty()).withShadow();
ScrollInput input = new SelectionScrollInput(x, y, 53, 16)
.forOptions(CreateLang.translatedOptions("contraption.door_control", valuesAsString()))
.titled(CreateLang.translateDirect("contraption.door_control"))
.calling(s -> {
DoorControl mode = values()[s];
label.text = CreateLang.translateDirect("contraption.door_control." + Lang.asId(mode.name()) + ".short");
callback.accept(mode);
})
.addHint(CreateLang.translateDirect("contraption.door_control.player_facing",
CreateLang.translateDirect("contraption.door_control." + Lang.asId(playerFacing.name()) + ".short")))
.setState(initial.ordinal());
input.onChanged();
return Pair.of(input, label);
}
}
| 412 | 0.874188 | 1 | 0.874188 | game-dev | MEDIA | 0.726641 | game-dev | 0.892734 | 1 | 0.892734 |
discordia-space/CEV-Eris | 3,269 | code/modules/mob/living/carbon/superior_animal/roach/types/nanites.dm | /mob/living/carbon/superior_animal/roach/nanite
name = "Kraftwerk Roach"
desc = "A deformed mess of a roach that is covered in metallic outcrops and formations. It seems to have a production center on its thorax."
icon_state = "naniteroach"
meat_type = /obj/item/reagent_containers/food/snacks/meat/roachmeat/kraftwerk
meat_amount = 3
turns_per_move = 1
maxHealth = 30
health = 30
melee_damage_lower = 2
melee_damage_upper = 4 //He's a ranged roach
breath_required_type = NONE
breath_poison_type = NONE
min_breath_required_type = 0
min_breath_poison_type = 0
min_air_pressure = 0
min_bodytemperature = 0
spawn_tags = SPAWN_TAG_ROACH_NANITE
rarity_value = 22.5
var/list/nanite_swarms = list()
var/max_swarms = 5
mob_size = MOB_SMALL * 1.5 // 15
// Armor related variables
armor = list(
melee = 5,
bullet = 5,
energy = 10,
bomb = 10,
bio = 25,
rad = 100
)
/mob/living/carbon/superior_animal/roach/nanite/UnarmedAttack(atom/A, var/proximity)
. = ..()
if(isliving(A))
var/mob/living/L = A
if(istype(L) && prob(25) && nanite_swarms.len < max_swarms)
var/sound/screech = pick('sound/machines/robots/robot_talk_light1.ogg','sound/machines/robots/robot_talk_light2.ogg','sound/machines/robots/robot_talk_heavy4.ogg')
playsound(src, screech, 30, 1, -3)
var/mob/living/simple_animal/hostile/naniteswarm/M = new /mob/living/simple_animal/hostile/naniteswarm(get_turf(src), src)
nanite_swarms.Add(M)
M.friends += src.friends
say("10101010011100010101")
/mob/living/carbon/superior_animal/roach/nanite/death()
for(var/mob/living/simple_animal/hostile/naniteswarm/NS in nanite_swarms)
nanite_swarms.Remove(NS)
NS.death()
..()
/mob/living/carbon/superior_animal/roach/nanite/Destroy()
for(var/mob/living/simple_animal/hostile/naniteswarm/NS in nanite_swarms)
nanite_swarms.Remove(NS)
NS.death()
.=..()
/mob/living/carbon/superior_animal/roach/nanite/joinOvermind(datum/overmind/roachmind/jointhis)
jointhis.addRanged(src) // Kraftwerk is Ranged
overseer = jointhis
/mob/living/carbon/superior_animal/roach/nanite/leaveOvermind()
overseer?.removeRanged(src) // Ranged Kraftwerk
overseer?.casualties.Remove(src)
overseer = null
/mob/living/simple_animal/hostile/naniteswarm
name = "nanite infested miniroach cluster"
desc = "A swarm of disgusting locusts infested with nanomachines."
icon = 'icons/mob/critter.dmi'
icon_state = "naniteroach"
icon_living = "naniteroach"
pass_flags = PASSTABLE
density = FALSE
health = 10
maxHealth = 10
melee_damage_lower = 2
melee_damage_upper = 4
armor_divisor = ARMOR_PEN_MASSIVE
attacktext = "cut"
attack_sound = 'sound/weapons/bladeslice.ogg'
faction = "roach"
min_oxy = 0
max_oxy = 0
min_tox = 0
max_tox = 0
min_co2 = 0
max_co2 = 0
min_n2 = 0
max_n2 = 0
minbodytemp = 0
var/mob/living/carbon/superior_animal/roach/nanite/parent
/mob/living/simple_animal/hostile/naniteswarm/New(loc, var/nuparent)
..()
parent = nuparent
/mob/living/simple_animal/hostile/naniteswarm/death()
..()
if(parent)
parent.nanite_swarms.Remove(src)
new /obj/effect/decal/cleanable/blood/oil(get_turf(src))
qdel(src)
/mob/living/simple_animal/hostile/naniteswarm/Destroy()
if(parent)
parent.nanite_swarms.Remove(src)
parent = null
.=..()
| 412 | 0.904793 | 1 | 0.904793 | game-dev | MEDIA | 0.999673 | game-dev | 0.686034 | 1 | 0.686034 |
ImLegiitXD/Dream-Advanced | 10,083 | dll/back/1.12/net/minecraft/block/BlockPane.java | package net.minecraft.block;
import java.util.List;
import java.util.Random;
import javax.annotation.Nullable;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.properties.PropertyBool;
import net.minecraft.block.state.BlockFaceShape;
import net.minecraft.block.state.BlockStateContainer;
import net.minecraft.block.state.IBlockState;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.Entity;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.util.BlockRenderLayer;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.Mirror;
import net.minecraft.util.Rotation;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
public class BlockPane extends Block
{
public static final PropertyBool NORTH = PropertyBool.create("north");
public static final PropertyBool EAST = PropertyBool.create("east");
public static final PropertyBool SOUTH = PropertyBool.create("south");
public static final PropertyBool WEST = PropertyBool.create("west");
protected static final AxisAlignedBB[] AABB_BY_INDEX = new AxisAlignedBB[] {new AxisAlignedBB(0.4375D, 0.0D, 0.4375D, 0.5625D, 1.0D, 0.5625D), new AxisAlignedBB(0.4375D, 0.0D, 0.4375D, 0.5625D, 1.0D, 1.0D), new AxisAlignedBB(0.0D, 0.0D, 0.4375D, 0.5625D, 1.0D, 0.5625D), new AxisAlignedBB(0.0D, 0.0D, 0.4375D, 0.5625D, 1.0D, 1.0D), new AxisAlignedBB(0.4375D, 0.0D, 0.0D, 0.5625D, 1.0D, 0.5625D), new AxisAlignedBB(0.4375D, 0.0D, 0.0D, 0.5625D, 1.0D, 1.0D), new AxisAlignedBB(0.0D, 0.0D, 0.0D, 0.5625D, 1.0D, 0.5625D), new AxisAlignedBB(0.0D, 0.0D, 0.0D, 0.5625D, 1.0D, 1.0D), new AxisAlignedBB(0.4375D, 0.0D, 0.4375D, 1.0D, 1.0D, 0.5625D), new AxisAlignedBB(0.4375D, 0.0D, 0.4375D, 1.0D, 1.0D, 1.0D), new AxisAlignedBB(0.0D, 0.0D, 0.4375D, 1.0D, 1.0D, 0.5625D), new AxisAlignedBB(0.0D, 0.0D, 0.4375D, 1.0D, 1.0D, 1.0D), new AxisAlignedBB(0.4375D, 0.0D, 0.0D, 1.0D, 1.0D, 0.5625D), new AxisAlignedBB(0.4375D, 0.0D, 0.0D, 1.0D, 1.0D, 1.0D), new AxisAlignedBB(0.0D, 0.0D, 0.0D, 1.0D, 1.0D, 0.5625D), new AxisAlignedBB(0.0D, 0.0D, 0.0D, 1.0D, 1.0D, 1.0D)};
private final boolean canDrop;
protected BlockPane(Material materialIn, boolean canDrop)
{
super(materialIn);
this.setDefaultState(this.blockState.getBaseState().withProperty(NORTH, Boolean.valueOf(false)).withProperty(EAST, Boolean.valueOf(false)).withProperty(SOUTH, Boolean.valueOf(false)).withProperty(WEST, Boolean.valueOf(false)));
this.canDrop = canDrop;
this.setCreativeTab(CreativeTabs.DECORATIONS);
}
public void addCollisionBoxToList(IBlockState state, World worldIn, BlockPos pos, AxisAlignedBB entityBox, List<AxisAlignedBB> collidingBoxes, @Nullable Entity entityIn, boolean p_185477_7_)
{
if (!p_185477_7_)
{
state = this.getActualState(state, worldIn, pos);
}
addCollisionBoxToList(pos, entityBox, collidingBoxes, AABB_BY_INDEX[0]);
if (((Boolean)state.getValue(NORTH)).booleanValue())
{
addCollisionBoxToList(pos, entityBox, collidingBoxes, AABB_BY_INDEX[getBoundingBoxIndex(EnumFacing.NORTH)]);
}
if (((Boolean)state.getValue(SOUTH)).booleanValue())
{
addCollisionBoxToList(pos, entityBox, collidingBoxes, AABB_BY_INDEX[getBoundingBoxIndex(EnumFacing.SOUTH)]);
}
if (((Boolean)state.getValue(EAST)).booleanValue())
{
addCollisionBoxToList(pos, entityBox, collidingBoxes, AABB_BY_INDEX[getBoundingBoxIndex(EnumFacing.EAST)]);
}
if (((Boolean)state.getValue(WEST)).booleanValue())
{
addCollisionBoxToList(pos, entityBox, collidingBoxes, AABB_BY_INDEX[getBoundingBoxIndex(EnumFacing.WEST)]);
}
}
private static int getBoundingBoxIndex(EnumFacing p_185729_0_)
{
return 1 << p_185729_0_.getHorizontalIndex();
}
public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess source, BlockPos pos)
{
state = this.getActualState(state, source, pos);
return AABB_BY_INDEX[getBoundingBoxIndex(state)];
}
private static int getBoundingBoxIndex(IBlockState state)
{
int i = 0;
if (((Boolean)state.getValue(NORTH)).booleanValue())
{
i |= getBoundingBoxIndex(EnumFacing.NORTH);
}
if (((Boolean)state.getValue(EAST)).booleanValue())
{
i |= getBoundingBoxIndex(EnumFacing.EAST);
}
if (((Boolean)state.getValue(SOUTH)).booleanValue())
{
i |= getBoundingBoxIndex(EnumFacing.SOUTH);
}
if (((Boolean)state.getValue(WEST)).booleanValue())
{
i |= getBoundingBoxIndex(EnumFacing.WEST);
}
return i;
}
/**
* Get the actual Block state of this Block at the given position. This applies properties not visible in the
* metadata, such as fence connections.
*/
public IBlockState getActualState(IBlockState state, IBlockAccess worldIn, BlockPos pos)
{
return state.withProperty(NORTH, Boolean.valueOf(this.attachesTo(worldIn, worldIn.getBlockState(pos.north()), pos.north(), EnumFacing.SOUTH))).withProperty(SOUTH, Boolean.valueOf(this.attachesTo(worldIn, worldIn.getBlockState(pos.south()), pos.south(), EnumFacing.NORTH))).withProperty(WEST, Boolean.valueOf(this.attachesTo(worldIn, worldIn.getBlockState(pos.west()), pos.west(), EnumFacing.EAST))).withProperty(EAST, Boolean.valueOf(this.attachesTo(worldIn, worldIn.getBlockState(pos.east()), pos.east(), EnumFacing.WEST)));
}
/**
* Get the Item that this Block should drop when harvested.
*/
public Item getItemDropped(IBlockState state, Random rand, int fortune)
{
return !this.canDrop ? Items.AIR : super.getItemDropped(state, rand, fortune);
}
/**
* Used to determine ambient occlusion and culling when rebuilding chunks for render
*/
public boolean isOpaqueCube(IBlockState state)
{
return false;
}
public boolean isFullCube(IBlockState state)
{
return false;
}
public boolean shouldSideBeRendered(IBlockState blockState, IBlockAccess blockAccess, BlockPos pos, EnumFacing side)
{
return blockAccess.getBlockState(pos.offset(side)).getBlock() == this ? false : super.shouldSideBeRendered(blockState, blockAccess, pos, side);
}
public final boolean attachesTo(IBlockAccess p_193393_1_, IBlockState state, BlockPos pos, EnumFacing facing)
{
Block block = state.getBlock();
BlockFaceShape blockfaceshape = state.getBlockFaceShape(p_193393_1_, pos, facing);
return !isExcepBlockForAttachWithPiston(block) && blockfaceshape == BlockFaceShape.SOLID || blockfaceshape == BlockFaceShape.MIDDLE_POLE_THIN;
}
protected static boolean isExcepBlockForAttachWithPiston(Block p_193394_0_)
{
return p_193394_0_ instanceof BlockShulkerBox || p_193394_0_ instanceof BlockLeaves || p_193394_0_ == Blocks.BEACON || p_193394_0_ == Blocks.CAULDRON || p_193394_0_ == Blocks.GLOWSTONE || p_193394_0_ == Blocks.ICE || p_193394_0_ == Blocks.SEA_LANTERN || p_193394_0_ == Blocks.PISTON || p_193394_0_ == Blocks.STICKY_PISTON || p_193394_0_ == Blocks.PISTON_HEAD || p_193394_0_ == Blocks.MELON_BLOCK || p_193394_0_ == Blocks.PUMPKIN || p_193394_0_ == Blocks.LIT_PUMPKIN || p_193394_0_ == Blocks.BARRIER;
}
protected boolean canSilkHarvest()
{
return true;
}
public BlockRenderLayer getBlockLayer()
{
return BlockRenderLayer.CUTOUT_MIPPED;
}
/**
* Convert the BlockState into the correct metadata value
*/
public int getMetaFromState(IBlockState state)
{
return 0;
}
/**
* Returns the blockstate with the given rotation from the passed blockstate. If inapplicable, returns the passed
* blockstate.
*/
public IBlockState withRotation(IBlockState state, Rotation rot)
{
switch (rot)
{
case CLOCKWISE_180:
return state.withProperty(NORTH, state.getValue(SOUTH)).withProperty(EAST, state.getValue(WEST)).withProperty(SOUTH, state.getValue(NORTH)).withProperty(WEST, state.getValue(EAST));
case COUNTERCLOCKWISE_90:
return state.withProperty(NORTH, state.getValue(EAST)).withProperty(EAST, state.getValue(SOUTH)).withProperty(SOUTH, state.getValue(WEST)).withProperty(WEST, state.getValue(NORTH));
case CLOCKWISE_90:
return state.withProperty(NORTH, state.getValue(WEST)).withProperty(EAST, state.getValue(NORTH)).withProperty(SOUTH, state.getValue(EAST)).withProperty(WEST, state.getValue(SOUTH));
default:
return state;
}
}
/**
* Returns the blockstate with the given mirror of the passed blockstate. If inapplicable, returns the passed
* blockstate.
*/
public IBlockState withMirror(IBlockState state, Mirror mirrorIn)
{
switch (mirrorIn)
{
case LEFT_RIGHT:
return state.withProperty(NORTH, state.getValue(SOUTH)).withProperty(SOUTH, state.getValue(NORTH));
case FRONT_BACK:
return state.withProperty(EAST, state.getValue(WEST)).withProperty(WEST, state.getValue(EAST));
default:
return super.withMirror(state, mirrorIn);
}
}
protected BlockStateContainer createBlockState()
{
return new BlockStateContainer(this, new IProperty[] {NORTH, EAST, WEST, SOUTH});
}
public BlockFaceShape getBlockFaceShape(IBlockAccess p_193383_1_, IBlockState p_193383_2_, BlockPos p_193383_3_, EnumFacing p_193383_4_)
{
return p_193383_4_ != EnumFacing.UP && p_193383_4_ != EnumFacing.DOWN ? BlockFaceShape.MIDDLE_POLE_THIN : BlockFaceShape.CENTER_SMALL;
}
}
| 412 | 0.955447 | 1 | 0.955447 | game-dev | MEDIA | 0.918543 | game-dev | 0.945929 | 1 | 0.945929 |
Evolveum/midpoint | 4,818 | icf-connectors/dummy-resource/src/main/java/com/evolveum/icf/dummy/resource/LinkStore.java | /*
* Copyright (C) 2010-2024 Evolveum and contributors
*
* This work is dual-licensed under the Apache License 2.0
* and European Union Public License. See LICENSE file for details.
*/
package com.evolveum.icf.dummy.resource;
import static com.evolveum.midpoint.util.MiscUtil.argCheck;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import com.evolveum.midpoint.util.DebugDumpable;
import com.evolveum.midpoint.util.DebugUtil;
/**
* Stores all links of given link class.
*/
class LinkStore implements DebugDumpable {
@NotNull private final LinkClassDefinition linkClassDefinition;
/** Preliminary implementation. */
@NotNull private final Set<Link> links = ConcurrentHashMap.newKeySet();
LinkStore(@NotNull LinkClassDefinition linkClassDefinition) {
this.linkClassDefinition = linkClassDefinition;
}
public void clear() {
links.clear();
}
@Override
public String debugDump(int indent) {
var sb = DebugUtil.createTitleStringBuilder("Link store for " + linkClassDefinition.getName(), indent);
sb.append("\n");
DebugUtil.debugDumpWithLabel(sb, "Links", links, indent + 1);
return sb.toString();
}
void addLink(DummyObject first, DummyObject second) {
links.add(new Link(first, second));
}
void deleteLink(DummyObject first, DummyObject second) {
links.removeIf(link -> link.first.equals(first) && link.second.equals(second));
}
public @NotNull LinkClassDefinition getLinkClassDefinition() {
return linkClassDefinition;
}
/** Returns objects that should be deleted by cascade. */
@NotNull Set<DummyObject> removeLinksFor(@NotNull DummyObject deletedObject) {
boolean cascadeIfFirst = linkClassDefinition.getSecondParticipant().isCascadeDelete();
boolean cascadeIfSecond = linkClassDefinition.getFirstParticipant().isCascadeDelete();
Set<DummyObject> toBeDeleted = new HashSet<>();
for (Iterator<Link> iterator = links.iterator(); iterator.hasNext(); ) {
Link link = iterator.next();
if (link.first.equals(deletedObject)) {
iterator.remove();
if (cascadeIfFirst) {
toBeDeleted.add(link.second);
}
} else if (link.second.equals(deletedObject)) {
iterator.remove();
if (cascadeIfSecond) {
toBeDeleted.add(link.first);
}
}
}
return toBeDeleted;
}
Collection<DummyObject> getLinkedObjects(DummyObject dummyObject, LinkDefinition linkDef) {
return links.stream()
.map(link -> link.getLinkedObject(dummyObject, linkDef))
.filter(Objects::nonNull)
.toList();
}
static class Link {
@NotNull private final DummyObject first;
@NotNull private final DummyObject second;
Link(@NotNull DummyObject first, @NotNull DummyObject second) {
argCheck(!first.equals(second), "Both objects are the same: %s (currently not supported)", first);
this.first = first;
this.second = second;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Link link = (Link) o;
return Objects.equals(first, link.first) && Objects.equals(second, link.second);
}
@Override
public int hashCode() {
return Objects.hash(first, second);
}
@Override
public String toString() {
return first + " <-> " + second;
}
public boolean matches(@NotNull String id) {
return id.equals(first.getId()) || id.equals(second.getId());
}
public boolean matches(DummyObject dummyObject, LinkDefinition linkDef) {
if (linkDef.isFirst()) {
return first.equals(dummyObject);
} else {
return second.equals(dummyObject);
}
}
public @Nullable DummyObject getLinkedObject(DummyObject dummyObject, LinkDefinition linkDef) {
if (linkDef.isFirst()) {
if (first.equals(dummyObject)) {
return second;
} else {
return null;
}
} else {
if (second.equals(dummyObject)) {
return first;
} else {
return null;
}
}
}
}
}
| 412 | 0.86775 | 1 | 0.86775 | game-dev | MEDIA | 0.233309 | game-dev | 0.893746 | 1 | 0.893746 |
ghuntley/cursed | 16,353 | stdlib/memory/advanced_pools_demo.💀 | // CURSED Advanced Memory Pool Management Demo
// Demonstrates high-performance NUMA-aware pools, thread-local optimization,
// generational GC integration, and fragmentation reduction
yeet "advanced_pools"
yeet "vibez"
yeet "mathz"
slay main_character() {
vibez.spill("🚀 CURSED Advanced Memory Pool Management Demo")
vibez.spill("================================================")
// Initialize the NUMA-aware pool manager
vibez.spill("\n🔧 Initializing NUMA-aware pool manager...")
sus manager *NumaPoolManager = init_numa_pool_manager()
if manager == cringe {
vibez.spill("❌ Failed to initialize pool manager")
damn 1
}
vibez.spill("✅ Pool manager initialized successfully")
vibez.spill(" - NUMA nodes detected: " + tea(manager.node_count))
vibez.spill(" - Thread pool size: " + tea(THREAD_POOL_SIZE))
vibez.spill(" - Generation count: " + tea(GENERATION_COUNT))
// Demo 1: NUMA-Aware Allocation
demo_numa_awareness()
// Demo 2: Thread-Local Cache Optimization
demo_thread_local_optimization()
// Demo 3: Generational GC Integration
demo_generational_gc()
// Demo 4: Fragmentation Reduction
demo_fragmentation_management()
// Demo 5: Performance Comparison
demo_performance_comparison()
// Display final statistics
vibez.spill("\n📊 Final System Statistics:")
get_numa_manager_stats()
// Cleanup
vibez.spill("\n🧹 Cleaning up resources...")
cleanup_numa_pools()
vibez.spill("✨ Demo completed successfully!")
damn 0
}
// Demonstrate NUMA-aware allocation strategies
slay demo_numa_awareness() {
vibez.spill("\n🌐 Demo 1: NUMA-Aware Allocation")
vibez.spill("===================================")
// Create NUMA-aware pool for different object sizes
sus small_pool *AdvancedPool = create_numa_pool("numa_small", 64, POOL_TYPE_NUMA_AWARE)
sus medium_pool *AdvancedPool = create_numa_pool("numa_medium", 1024, POOL_TYPE_NUMA_AWARE)
sus large_pool *AdvancedPool = create_numa_pool("numa_large", 8192, POOL_TYPE_NUMA_AWARE)
if small_pool == cringe || medium_pool == cringe || large_pool == cringe {
vibez.spill("❌ Failed to create NUMA pools")
damn
}
vibez.spill("✅ Created NUMA-aware pools:")
vibez.spill(" - Small objects (64B) on NUMA node " + tea(small_pool.numa_node))
vibez.spill(" - Medium objects (1KB) on NUMA node " + tea(medium_pool.numa_node))
vibez.spill(" - Large objects (8KB) on NUMA node " + tea(large_pool.numa_node))
// Demonstrate allocation patterns
vibez.spill("\n🎯 Allocating objects with NUMA optimization...")
// Allocate small objects
sus small_allocations [20]*byte
frfr i := 0; i < 20; i++ {
small_allocations[i] = numa_pool_allocate(small_pool, 64)
if small_allocations[i] == cringe {
vibez.spill("⚠️ Small allocation " + tea(i) + " failed")
}
}
// Allocate medium objects
sus medium_allocations [10]*byte
frfr i := 0; i < 10; i++ {
medium_allocations[i] = numa_pool_allocate(medium_pool, 1024)
if medium_allocations[i] == cringe {
vibez.spill("⚠️ Medium allocation " + tea(i) + " failed")
}
}
// Allocate large objects
sus large_allocations [5]*byte
frfr i := 0; i < 5; i++ {
large_allocations[i] = numa_pool_allocate(large_pool, 8192)
if large_allocations[i] == cringe {
vibez.spill("⚠️ Large allocation " + tea(i) + " failed")
}
}
vibez.spill("✅ Completed NUMA-aware allocations:")
vibez.spill(" - Small objects: 20 allocated")
vibez.spill(" - Medium objects: 10 allocated")
vibez.spill(" - Large objects: 5 allocated")
// Show NUMA statistics
vibez.spill("\n📈 NUMA Performance Statistics:")
get_numa_pool_stats(small_pool)
}
// Demonstrate thread-local cache optimization
slay demo_thread_local_optimization() {
vibez.spill("\n🧵 Demo 2: Thread-Local Cache Optimization")
vibez.spill("============================================")
// Create thread-local optimized pool
sus pool *AdvancedPool = create_numa_pool("thread_local_demo", 256, POOL_TYPE_THREAD_LOCAL)
if pool == cringe {
vibez.spill("❌ Failed to create thread-local pool")
damn
}
vibez.spill("✅ Created thread-local optimized pool (256-byte objects)")
// Create thread-local cache for current thread
sus thread_id normie = get_current_thread_id()
sus cache *ThreadLocalCache = create_thread_local_cache(pool, thread_id)
if cache == cringe {
vibez.spill("❌ Failed to create thread-local cache")
damn
}
vibez.spill("✅ Created thread-local cache for thread " + tea(thread_id))
// Warm up the cache
vibez.spill("\n🔥 Warming up thread-local cache...")
sus warmup_allocations [50]*byte
frfr i := 0; i < 50; i++ {
warmup_allocations[i] = numa_pool_allocate(pool, 256)
if warmup_allocations[i] == cringe {
vibez.spill("⚠️ Warmup allocation " + tea(i) + " failed")
}
}
// Measure cache performance
vibez.spill("\n⚡ Testing cache-optimized allocations...")
sus cache_test_allocations [100]*byte
frfr i := 0; i < 100; i++ {
cache_test_allocations[i] = numa_pool_allocate(pool, 256)
if cache_test_allocations[i] == cringe {
vibez.spill("⚠️ Cache test allocation " + tea(i) + " failed")
}
}
// Display cache statistics
vibez.spill("✅ Thread-local cache performance:")
vibez.spill(" - Total allocations: " + tea(cache.allocations))
vibez.spill(" - Cache hits: " + tea(cache.cache_hits))
vibez.spill(" - Cache misses: " + tea(cache.cache_misses))
sus hit_rate drip = 0.0
if cache.allocations > 0 {
hit_rate = (*drip)(cache.cache_hits) / (*drip)(cache.allocations) * 100.0
}
vibez.spill(" - Cache hit rate: " + tea(hit_rate) + "%")
if hit_rate > 80.0 {
vibez.spill("🎉 Excellent cache performance!")
} else if hit_rate > 60.0 {
vibez.spill("👍 Good cache performance")
} else {
vibez.spill("⚠️ Cache could be optimized further")
}
}
// Demonstrate generational GC integration
slay demo_generational_gc() {
vibez.spill("\n♻️ Demo 3: Generational GC Integration")
vibez.spill("======================================")
// Create generational pool
sus pool *AdvancedPool = create_numa_pool("generational_demo", 512, POOL_TYPE_GENERATIONAL)
if pool == cringe {
vibez.spill("❌ Failed to create generational pool")
damn
}
vibez.spill("✅ Created generational pool (512-byte objects)")
vibez.spill(" - Generations: " + tea(GENERATION_COUNT))
vibez.spill(" - Current generation: " + tea(pool.current_generation))
// Allocate objects in different generations
vibez.spill("\n🎯 Allocating objects across generations...")
frfr gen := 0; gen < GENERATION_COUNT; gen++ {
sus generation *GenerationalPool = &pool.generations[gen]
vibez.spill("\n📦 Generation " + tea(gen) + " (" + generation.name + "):")
// Allocate objects in current generation
sus gen_allocations [15]*byte
frfr i := 0; i < 15; i++ {
gen_allocations[i] = generational_allocate(generation, 512)
if gen_allocations[i] == cringe {
vibez.spill("⚠️ Generation " + tea(gen) + " allocation " + tea(i) + " failed")
}
}
vibez.spill(" - Allocated objects: " + tea(generation.total_objects))
vibez.spill(" - Live objects: " + tea(generation.live_objects))
vibez.spill(" - Survival rate: " + tea(generation.survival_rate))
vibez.spill(" - Allocation rate: " + tea(generation.allocation_rate))
}
// Simulate object aging and promotion
vibez.spill("\n⏰ Simulating object aging and generation promotion...")
sus gen0 *GenerationalPool = &pool.generations[0]
sus gen1 *GenerationalPool = &pool.generations[1]
sus initial_gen0_objects normie = gen0.total_objects
sus initial_gen1_objects normie = gen1.total_objects
// Simulate long-lived objects by increasing allocation count
sus current_chunk *AdvancedChunk = gen0.chunks
bestie current_chunk != cringe {
current_chunk.allocation_count += 150 // Simulate many allocations (>100 threshold)
current_chunk = current_chunk.next
}
// Force generation promotion
promote_generation(pool)
vibez.spill("✅ Generation promotion completed:")
vibez.spill(" - Gen0 objects before: " + tea(initial_gen0_objects))
vibez.spill(" - Gen0 objects after: " + tea(gen0.total_objects))
vibez.spill(" - Gen1 objects before: " + tea(initial_gen1_objects))
vibez.spill(" - Gen1 objects after: " + tea(gen1.total_objects))
vibez.spill(" - Current generation: " + tea(pool.current_generation))
}
// Demonstrate fragmentation reduction
slay demo_fragmentation_management() {
vibez.spill("\n🧩 Demo 4: Fragmentation Reduction")
vibez.spill("==================================")
// Create compacting pool
sus pool *AdvancedPool = create_numa_pool("fragmentation_demo", 128, POOL_TYPE_COMPACTING)
if pool == cringe {
vibez.spill("❌ Failed to create compacting pool")
damn
}
vibez.spill("✅ Created compacting pool (128-byte objects)")
vibez.spill(" - Compaction threshold: " + tea(COMPACTION_THRESHOLD))
vibez.spill(" - Fragmentation limit: " + tea(FRAGMENTATION_LIMIT))
// Create fragmented allocation pattern
vibez.spill("\n🔀 Creating fragmented allocation pattern...")
sus allocations [60]*byte
sus allocation_count normie = 0
// Allocate various sizes to create fragmentation
frfr i := 0; i < 60; i++ {
sus size_variant normie = 64 + (i % 6) * 32 // Sizes: 64, 96, 128, 160, 192, 224
sus ptr *byte = numa_pool_allocate(pool, size_variant)
if ptr != cringe {
allocations[allocation_count] = ptr
allocation_count++
}
}
vibez.spill(" - Allocated " + tea(allocation_count) + " objects with varying sizes")
// Simulate deallocation to create fragmentation
vibez.spill(" - Simulating deallocations (every 3rd object)...")
sus deallocated_count normie = 0
frfr i := 0; i < allocation_count; i += 3 {
if allocations[i] != cringe {
allocations[i] = cringe // Simulate deallocation
deallocated_count++
}
}
vibez.spill(" - Deallocated " + tea(deallocated_count) + " objects")
// Measure initial fragmentation
sus initial_fragmentation drip = calculate_pool_fragmentation(pool)
vibez.spill("\n📊 Initial fragmentation level: " + tea(initial_fragmentation * 100.0) + "%")
if initial_fragmentation > FRAGMENTATION_LIMIT {
vibez.spill("⚠️ Fragmentation exceeds limit (" + tea(FRAGMENTATION_LIMIT * 100.0) + "%)")
vibez.spill("🔧 Triggering automatic compaction...")
// Perform compaction
compact_pool(pool)
// Measure fragmentation after compaction
sus final_fragmentation drip = calculate_pool_fragmentation(pool)
vibez.spill("📊 Final fragmentation level: " + tea(final_fragmentation * 100.0) + "%")
sus reduction_percent drip = (initial_fragmentation - final_fragmentation) / initial_fragmentation * 100.0
vibez.spill("✅ Fragmentation reduction: " + tea(reduction_percent) + "%")
vibez.spill(" - Compaction cycles: " + tea(pool.compaction_count))
if final_fragmentation < FRAGMENTATION_LIMIT {
vibez.spill("🎉 Fragmentation successfully reduced below limit!")
}
} else {
vibez.spill("✅ Fragmentation within acceptable limits")
}
}
// Demonstrate performance comparison
slay demo_performance_comparison() {
vibez.spill("\n🏁 Demo 5: Performance Comparison")
vibez.spill("=================================")
// Create different types of pools for comparison
sus numa_pool *AdvancedPool = create_numa_pool("perf_numa", 256, POOL_TYPE_NUMA_AWARE)
sus thread_pool *AdvancedPool = create_numa_pool("perf_thread", 256, POOL_TYPE_THREAD_LOCAL)
sus gen_pool *AdvancedPool = create_numa_pool("perf_gen", 256, POOL_TYPE_GENERATIONAL)
sus compact_pool *AdvancedPool = create_numa_pool("perf_compact", 256, POOL_TYPE_COMPACTING)
if numa_pool == cringe || thread_pool == cringe || gen_pool == cringe || compact_pool == cringe {
vibez.spill("❌ Failed to create performance test pools")
damn
}
vibez.spill("✅ Created performance test pools:")
vibez.spill(" - NUMA-aware pool")
vibez.spill(" - Thread-local pool")
vibez.spill(" - Generational pool")
vibez.spill(" - Compacting pool")
// Create thread-local cache for thread pool
sus cache *ThreadLocalCache = create_thread_local_cache(thread_pool, 0)
// Test allocation performance for each pool type
sus test_iterations normie = 500
vibez.spill("\n⏱️ Testing allocation performance (" + tea(test_iterations) + " iterations)...")
// Test NUMA pool
vibez.spill("\n🌐 NUMA-Aware Pool Performance:")
test_pool_performance(numa_pool, test_iterations, "NUMA")
// Test thread-local pool
vibez.spill("\n🧵 Thread-Local Pool Performance:")
test_pool_performance(thread_pool, test_iterations, "Thread-Local")
// Test generational pool
vibez.spill("\n♻️ Generational Pool Performance:")
test_pool_performance(gen_pool, test_iterations, "Generational")
// Test compacting pool
vibez.spill("\n🧩 Compacting Pool Performance:")
test_pool_performance(compact_pool, test_iterations, "Compacting")
// Summary comparison
vibez.spill("\n📊 Performance Summary:")
vibez.spill(" - All pools successfully handled " + tea(test_iterations) + " allocations")
vibez.spill(" - NUMA pool optimizes for locality")
vibez.spill(" - Thread-local pool provides highest cache efficiency")
vibez.spill(" - Generational pool integrates with GC")
vibez.spill(" - Compacting pool manages fragmentation automatically")
}
// Helper function to test pool performance
slay test_pool_performance(pool *AdvancedPool, iterations normie, pool_type tea) {
if pool == cringe {
vibez.spill("❌ Invalid pool for performance test")
damn
}
sus successful_allocations normie = 0
sus failed_allocations normie = 0
// Record initial statistics
sus initial_allocations normie = pool.allocations
sus initial_cache_hits normie = pool.cache_hits
// Perform allocation test
frfr i := 0; i < iterations; i++ {
sus ptr *byte = numa_pool_allocate(pool, 256)
if ptr != cringe {
successful_allocations++
} else {
failed_allocations++
}
}
// Calculate performance metrics
sus final_allocations normie = pool.allocations
sus final_cache_hits normie = pool.cache_hits
sus new_allocations normie = final_allocations - initial_allocations
sus new_cache_hits normie = final_cache_hits - initial_cache_hits
sus success_rate drip = (*drip)(successful_allocations) / (*drip)(iterations) * 100.0
sus cache_hit_rate drip = 0.0
if new_allocations > 0 {
cache_hit_rate = (*drip)(new_cache_hits) / (*drip)(new_allocations) * 100.0
}
vibez.spill(" - Successful allocations: " + tea(successful_allocations) + "/" + tea(iterations))
vibez.spill(" - Success rate: " + tea(success_rate) + "%")
vibez.spill(" - Cache hit rate: " + tea(cache_hit_rate) + "%")
vibez.spill(" - Total pool allocations: " + tea(final_allocations))
if success_rate > 95.0 {
vibez.spill(" ✅ Excellent performance!")
} else if success_rate > 90.0 {
vibez.spill(" 👍 Good performance")
} else {
vibez.spill(" ⚠️ Performance could be improved")
}
}
| 412 | 0.945562 | 1 | 0.945562 | game-dev | MEDIA | 0.791786 | game-dev | 0.910656 | 1 | 0.910656 |
realms-mud/core-lib | 4,140 | lib/services/crafting/enchantments.c | //*****************************************************************************
// Copyright (c) 2025 - Allen Cummings, RealmsMUD, All rights reserved. See
// the accompanying LICENSE file for details.
//*****************************************************************************
#ifndef _enchantment_c
#define _enchantment_c
#include "/lib/services/crafting/core.c"
/////////////////////////////////////////////////////////////////////////////
private nomask int getEnchantmentStrength(string enchantment, object user)
{
int ret = user->researchBonusTo(sprintf("crafting %s", enchantment));
mapping skills = equipmentEnchantments[enchantment]["crafting prerequisites"];
if (sizeof(skills))
{
string *skillList = m_indices(skills);
foreach(string skill in skillList)
{
if (skills[skill]["type"] == "skill")
{
ret += (user->getSkill(skill) - skills[skill]["value"]) / 10;
}
}
}
return ret;
}
/////////////////////////////////////////////////////////////////////////////
private nomask int applyEffects(string enchantment, object user, object item,
int count)
{
int ret = 1;
int bonus = getEnchantmentStrength(enchantment, user);
mapping effects = equipmentEnchantments[enchantment]["effects"] + ([]);
foreach(string effect in m_indices(effects))
{
if (mappingp(effects[effect]))
{
foreach(string element in m_indices(effects[effect]))
{
effects[effect][element] =
(effects[effect][element] + bonus) * count;
}
}
else if(effect != "damage type")
{
effects[effect] = (effects[effect] + bonus) * count;
}
ret &&= item->set(effect, effects[effect]);
}
if (member(equipmentEnchantments[enchantment], "experience modifier"))
{
item->set("crafting experience", item->query("crafting experience") *
equipmentEnchantments[enchantment]["experience modifier"]);
}
return ret;
}
/////////////////////////////////////////////////////////////////////////////
protected nomask int applyEnchantments(object item, object user)
{
int ret = 1;
mapping enchantments = item->query("crafting enchantments");
if (!mappingp(enchantments))
{
enchantments = ([]);
}
string *enchantmentList = m_indices(enchantments);
foreach(string enchantment in enchantmentList)
{
if (member(equipmentEnchantments, enchantment))
{
ret &&= applyEffects(enchantment, user, item,
enchantments[enchantment]);
}
}
return ret;
}
/////////////////////////////////////////////////////////////////////////////
public nomask int canEnchantItem(object item, object user)
{
return user->isResearched("/lib/instances/research/crafting/enchantments/craftEnchantments.c");
}
/////////////////////////////////////////////////////////////////////////////
public nomask varargs int addEnchantment(object item, string enchantment, int decrement)
{
int ret = 1;
mapping craftingEnchantments = item->query("crafting enchantments");
if (!mappingp(craftingEnchantments))
{
craftingEnchantments = ([]);
}
if (member(equipmentEnchantments, enchantment))
{
int newLevel = decrement ? -1 : 1;
if (member(craftingEnchantments, enchantment))
{
newLevel += craftingEnchantments[enchantment];
}
if (newLevel < 0)
{
newLevel = 0;
}
if (!newLevel)
{
m_delete(craftingEnchantments, enchantment);
}
else if (newLevel < 4)
{
craftingEnchantments[enchantment] = newLevel;
}
else
{
ret = 0;
}
if (sizeof(craftingEnchantments))
{
item->set("crafting enchantments", craftingEnchantments);
}
else
{
item->unset("crafting enchantments");
}
}
return ret;
}
#endif
| 412 | 0.726738 | 1 | 0.726738 | game-dev | MEDIA | 0.983043 | game-dev | 0.579505 | 1 | 0.579505 |
opennars/OpenNARS-for-Applications | 2,990 | src/system_tests/Cartpole_Test.h | static double velocity = 0.0;
static double angle = -3.1415/2.0;
static double angle_velocity = 0.0;
static double position = 0.0;
static double max_angle_velocity = 0.3;
static Feedback NAR_CP_Left()
{
double reverse = angle > 0 ? 1 : -1;
//if(position > 0.0 && position < 1.0)
{
angle_velocity -= reverse * 0.2;
}
velocity -= 0.1;
return (Feedback) {0};
}
static Feedback NAR_CP_Right()
{
double reverse = angle > 0 ? 1 : -1;
//if(position > 0.0 && position < 1.0)
{
angle_velocity += reverse * 0.2;
}
velocity += 0.1;
return (Feedback) {0};
}
static double successes = 0;
static double failures = 0;
void NAR_Cartpole(long iterations)
{
char initial[] = " |\n"
" |\n"
" ----------- |\n"
" |\n"
" |\n";
int t=0;
puts(">>NAR CP start");
NAR_AddOperation("^left", NAR_CP_Left);
NAR_AddOperation("^right", NAR_CP_Right);
while(1)
{
position += velocity;
position = MAX(0.0, MIN(1.0, position));
angle += angle_velocity;
CLEAR_SCREEN;
char world[sizeof(initial)];
memcpy(world, initial, sizeof(initial));
DRAW_LINE(10+position*5,2,angle,5,(char*) &world,'o');
puts(world);
//gravity
angle_velocity += 0.2*cos(angle);
//max. velocities given by air density
if(angle_velocity > max_angle_velocity)
{
angle_velocity = max_angle_velocity;
}
if(angle_velocity < -max_angle_velocity)
{
angle_velocity = -max_angle_velocity;
}
//wrap around angle (where angle 1 corresponds to half a circle)
double PI = 3.1415; //hm why M_PI doesn't work?
if(angle > PI)
{
angle = -PI;
}
if(angle < -PI)
{
angle = PI;
}
if(t++ > iterations && iterations != -1)
{
break;
}
printf("position=%f, velocity=%f, angle=%f, angleV=%f\nsuccesses=%f, failures=%f, ratio=%f, time=%d\n", position, velocity, angle, angle_velocity, successes, failures, successes/(successes+failures), t);
velocity = 0.0; //strong friction
if(fabs(angle-(-PI/2.0)) <= 0.5) //in balance
{
NAR_AddInputNarsese("good. :|:");
successes += 1.0;
}
else
if(angle >= 0 && angle <= PI)
{
NAR_AddInputNarsese("good. :|: %0%");
failures += 1.0;
}
char str[20] = {0};
int encodingInt = (int)((angle+PI)/(2*PI)*8);
sprintf(str, "%d. :|:", encodingInt);
NAR_AddInputNarsese(str);
NAR_AddInputNarsese("good! :|:");
//NAR_Cycles(3);
fflush(stdout);
if(iterations == -1)
{
SLEEP;SLEEP;SLEEP;
}
}
}
| 412 | 0.723298 | 1 | 0.723298 | game-dev | MEDIA | 0.39808 | game-dev | 0.662886 | 1 | 0.662886 |
Suprcode/Crystal | 1,130 | Server/MirObjects/Monsters/BlueSoul.cs | using Server.MirDatabase;
using Server.MirEnvir;
using S = ServerPackets;
namespace Server.MirObjects.Monsters
{
public class BlueSoul : AxeSkeleton
{
protected internal BlueSoul(MonsterInfo info)
: base(info)
{
}
protected override void Attack()
{
if (!Target.IsAttackTarget(this))
{
Target = null;
return;
}
ShockTime = 0;
Direction = Functions.DirectionFromPoint(CurrentLocation, Target.CurrentLocation);
Broadcast(new S.ObjectRangeAttack { ObjectID = ObjectID, Direction = Direction, Location = CurrentLocation, TargetID = Target.ObjectID, Type = 0 });
ActionTime = Envir.Time + 300;
AttackTime = Envir.Time + AttackSpeed;
int damage = GetAttackPower(Stats[Stat.MinDC], Stats[Stat.MaxDC]);
if (damage == 0) return;
DelayedAction action = new DelayedAction(DelayedType.RangeDamage, Envir.Time + 500, Target, damage, DefenceType.MACAgility);
ActionList.Add(action);
}
}
} | 412 | 0.96495 | 1 | 0.96495 | game-dev | MEDIA | 0.935753 | game-dev | 0.901455 | 1 | 0.901455 |
JevLOMCN/Crystal-Monk | 3,219 | Server/MirObjects/Monsters/Cat/SeedingsGeneral.cs | using Server.MirDatabase;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using S = ServerPackets;
namespace Server.MirObjects.Monsters
{
public class SeedingsGeneral : MonsterObject
{
public SeedingsGeneral(MonsterInfo info)
: base(info)
{
}
protected override void Attack()
{
if (!Target.IsAttackTarget(this))
{
Target = null;
return;
}
if (!CanAttack)
return;
ShockTime = 0;
Direction = Functions.DirectionFromPoint(CurrentLocation, Target.CurrentLocation);
int damage = GetAttackPower(MinDC, MaxDC);
if (damage == 0) return;
if (Envir.Random.Next(3) == 0)
{
RangeAttack();
}
else if (Envir.Random.Next(3) == 0)
{
RangeAttack2();
}
else if (Envir.Random.Next(3) == 0)
{
RangeAttack3();
}
else
{
Attack1();
}
AttackTime = Envir.Time + AttackSpeed;
ActionTime = Envir.Time + 300;
}
protected override void RangeAttack3()
{
int damage = GetAttackPower(MinDC, MaxDC);
if (damage == 0) return;
Broadcast(new S.ObjectRangeAttack { ObjectID = ObjectID, Direction = Direction, Location = CurrentLocation, TargetID = Target.ObjectID, Type = 2 });
LineAttack(3, damage, DefenceType.MACAgility, 100);
}
protected override void CompleteRangeAttack(IList<object> data)
{
MapObject target = (MapObject)data[0];
int damage = (int)data[1];
DefenceType defence = (DefenceType)data[2];
int type = (int)data[3];
List<MapObject> targets;
switch (type)
{
case 0:
if (target == null || !target.IsAttackTarget(this) || target.CurrentMap != CurrentMap || target.Node == null) return;
target.Attacked(this, damage, DefenceType.MAC);
if (Envir.Random.Next(5) == 0)
{
target.ApplyPoison(new Poison { Owner = this, Duration = 30, PType = PoisonType.Red, Value = damage / 20, TickSpeed = 1000 }, this);
}
break;
case 1:
targets = FindAllTargets(1, CurrentLocation);
for (int i = 0; i < targets.Count; i++)
{
if (!targets[i].IsAttackTarget(this)) continue;
targets[i].Attacked(this, damage, DefenceType.MAC);
if (Envir.Random.Next(6) == 0)
{
targets[i].ApplyPoison(new Poison { Owner = this, Duration = 12, PType = PoisonType.Slow, Value = damage / 20, TickSpeed = 1000 }, this);
}
}
break;
}
}
}
}
| 412 | 0.979946 | 1 | 0.979946 | game-dev | MEDIA | 0.920735 | game-dev | 0.931766 | 1 | 0.931766 |
BentoBoxWorld/BentoBox | 2,666 | src/main/java/world/bentobox/bentobox/api/events/command/CommandEvent.java | package world.bentobox.bentobox.api.events.command;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.event.Cancellable;
import org.bukkit.event.HandlerList;
import org.eclipse.jdt.annotation.NonNull;
import world.bentobox.bentobox.api.events.BentoBoxEvent;
/**
* Fired when a command event happens.
*
* @author tastybento
*/
public class CommandEvent extends BentoBoxEvent implements Cancellable {
private boolean cancelled;
private final CommandSender sender;
private final Command command;
private final String label;
private final String[] args;
private static final HandlerList handlers = new HandlerList();
@Override
public @NonNull HandlerList getHandlers() {
return getHandlerList();
}
public static HandlerList getHandlerList() {
return handlers;
}
private CommandEvent(CommandSender sender, Command command, String label, String[] args) {
super();
this.sender = sender;
this.command = command;
this.label = label;
this.args = args;
}
public static CommandEventBuilder builder() {
return new CommandEventBuilder();
}
public static class CommandEventBuilder {
// Here field are NOT final. They are just used for the building.
private CommandSender sender;
private Command command;
private String label;
private String[] args;
public CommandEventBuilder setSender(CommandSender sender) {
this.sender = sender;
return this;
}
public CommandEventBuilder setCommand(Command command) {
this.command = command;
return this;
}
public CommandEventBuilder setLabel(String label) {
this.label = label;
return this;
}
public CommandEventBuilder setArgs(String[] args) {
this.args = args;
return this;
}
public CommandEvent build() {
CommandEvent event = new CommandEvent(sender, command, label, args);
Bukkit.getPluginManager().callEvent(event);
return event;
}
}
public CommandSender getSender() {
return sender;
}
public Command getCommand() {
return command;
}
public String getLabel() {
return label;
}
public String[] getArgs() {
return args;
}
@Override
public boolean isCancelled() {
return cancelled;
}
@Override
public void setCancelled(boolean arg0) {
cancelled = arg0;
}
}
| 412 | 0.786558 | 1 | 0.786558 | game-dev | MEDIA | 0.781514 | game-dev | 0.746692 | 1 | 0.746692 |
PavelZinchenko/event_horizon | 1,189 | Starship/Assets/Scripts/Domain/Quests/Requirements/CurrentStarRequirements.cs | using GameServices.Player;
using Services.Localization;
namespace Domain.Quests
{
public class CurrentStarRequirements : IRequirements
{
public CurrentStarRequirements(int minDistance, int maxDistance, MotherShip motherShip)
{
_motherShip = motherShip;
_minDistance = minDistance;
_maxDistance = maxDistance;
}
public bool IsMet
{
get
{
var star = _motherShip.CurrentStar;
var level = star.Level;
if (level < _minDistance || level > _maxDistance) return false;
return !star.Occupant.IsAggressive;
}
}
public bool CanStart(int starId, int seed) { return IsMet; }
public string GetDescription(ILocalization localization)
{
#if UNITY_EDITOR
return "POSITION: " + _minDistance + " - " + _maxDistance;
#else
return string.Empty;
#endif
}
public int BeaconPosition { get { return -1; } }
private readonly int _minDistance;
private readonly int _maxDistance;
private readonly MotherShip _motherShip;
}
}
| 412 | 0.750685 | 1 | 0.750685 | game-dev | MEDIA | 0.668508 | game-dev | 0.655795 | 1 | 0.655795 |
borntofrappe/svelte-tutorial | 4,640 | Infinity Maze/res/Maze Algorithm/script.js | // variables describing the structure of the grid
// number of cells
const columns = 8;
const rows = 8;
// size of the cell, horizontal and vertical
const h = 80;
const v = 80;
// size of the stroke
const stroke = 10;
// array describing the grid through columns and rows
// gates describes the borders for the cells
const grid = Array(rows)
.fill()
.map((r, row) =>
Array(columns)
.fill()
.map((c, column) => ({
column,
row,
// the idea is to remove the borders by removing the matching use element
gates: {
north: true,
east: true,
south: true,
west: true,
},
// ! whether or not a cell has been visited can be very well described by the lack of at least a gate
isVisited: false,
}))
);
// flatten the array to have the cells in a 1D array
// the position is not based on the index in the array, but on the column and row properties
const flat = grid.reduce((acc, curr) => [...acc, ...curr], []);
function drawMaze() {
// include an svg element with one group for each cell
// in this group include one <use> element per gate, identifying the border
// ! the viewBox is incremented by the stroke to avoid cropping (this is paired with the translation of the first group element)
const width = columns * h;
const height = rows * v;
const maze = `
<svg
viewBox="0 0 ${width + stroke} ${height + stroke}"
width=${width}
height=${height}>
<defs>
<path id="north" d="M 0 0 h ${h}"></path>
<path id="east" d="M ${h} 0 v ${v}"></path>
<path id="south" d="M 0 ${v} h ${h}"></path>
<path id="west" d="M 0 0 v ${v}"></path>
<rect id="square" x="0" y="0" width="${h - stroke}" height="${v -
stroke}"></rect>
</defs>
<g
stroke="currentColor"
stroke-width=${stroke}
stroke-linejoin="square"
stroke-linecap="square"
fill="none">
<g transform="translate(${stroke / 2} ${stroke / 2})">
${flat
.map(
({ column, row, gates }) => `
<g transform="translate(${column * h} ${row * v})">
${Object.entries(gates)
.filter(([, isGated]) => isGated)
.map(([href]) => `<use href="#${href}"></use>`)
.join('')}
</g>
`
)
.join('')}
</g>
</g>
</sgv>
`;
const body = document.querySelector('body');
body.innerHTML = maze;
}
// aldous-broder algorithm: visit a cell and pick a neighbor at random
// if not visited, link the two, and repeat until every cell has been visited
// ! draw the maze only when every cell has been visited
const oppositeGates = [['north', 'south'], ['east', 'west']];
function randomWalk(vX, vY) {
const cell = flat.find(({ column, row }) => column === vX && row === vY);
// visit the cell
cell.isVisited = true;
// find the neighbors
// ! be sure to filter out the objects outside of the maze
const neighbors = [
{
gate: 'north',
coordinates: [vX, vY - 1],
},
{
gate: 'east',
coordinates: [vX + 1, vY],
},
{
gate: 'south',
coordinates: [vX, vY + 1],
},
{
gate: 'west',
coordinates: [vX - 1, vY],
},
].filter(({ coordinates }) => {
const [x, y] = coordinates;
return x >= 0 && x <= columns - 1 && y >= 0 && y <= rows - 1;
});
// pick a neighbor at random
const neighbor = neighbors[Math.floor(Math.random() * neighbors.length)];
// the gate describes the direction picked up by the cell
const { gate } = neighbor;
const [nX, nY] = neighbor.coordinates;
// find the neighboring cell
const neighboringCell = flat.find(
({ column, row }) => column === nX && row === nY
);
// link the two only if the neighboring cell hasn't already being visited
if (!neighboringCell.isVisited) {
// remove the gates facing each other
cell.gates[gate] = false;
const direction = oppositeGates.find(opposites => opposites.includes(gate));
const oppositeGate = direction.find(opposite => opposite !== gate);
neighboringCell.gates[oppositeGate] = false;
}
// if every cell has been visited draw the maze, else continue toward the neighboring cell
const areVisited = flat.every(({ isVisited }) => isVisited);
if (areVisited) {
drawMaze();
} else {
randomWalk(nX, nY);
}
}
randomWalk(Math.floor(Math.random(rows)), Math.floor(Math.random(columns)));
| 412 | 0.89207 | 1 | 0.89207 | game-dev | MEDIA | 0.705555 | game-dev,web-frontend | 0.777662 | 1 | 0.777662 |
open-watcom/open-watcom-v2 | 7,875 | bld/src/fortran/ads/rel12/fact.for | !-----------------------------------------------------------------------
! MAIN - the main routine
*$include adsapi.fi
program main
include 'adslib.fi'
integer*2 scode/RSRSLT/ ! Normal result code (default)
integer stat
external funcload, dofun, funcinit
integer funcload, dofun, funcinit
stat = funcinit()
call ads_init( 0, 0 ) ! Open communication with AutoLISP
loop ! Request/Result loop
stat = ads_link( scode )
if( stat .lt. 0 )then
print *, 'FACT: bad status from ads_link() =', stat
return
end if
scode = RSRSLT ! Reset result code
select( stat )
case( RQXLOAD ) ! Load & define functions
if( funcload() .eq. RTNORM )then
scode = RSRSLT
else
scode = RSERR
end if
case( RQSUBR ) ! Handle external function requests
if( dofun() .eq. RTNORM )then
scode = RSRSLT
else
scode = RSERR
end if
end select
end loop
end
!-----------------------------------------------------------------------
! FUNCINIT -- Initialize function definition structure
function funcinit()
include 'adslib.fi'
integer funcinit, funcload, dofun
integer fact, squareroot
external fact, squareroot
integer*4 args
record /resbuf/ rb(:)
integer val, i
structure /func_entry/
character*32 func_name
integer func
end structure
! To add another function, change the value of "NUM_FUNS" and
! add the new function(s) to the function table ("func_table").
integer NUM_FUNS
parameter ( NUM_FUNS = 2 )
record /func_entry/ func_table(NUM_FUNS)
func_table(1).func_name = 'fact'//char(0)
func_table(1).func = loc( fact )
func_table(2).func_name = 'sqr'//char(0)
func_table(2).func = loc( squareroot )
funcinit = 0
return
!-----------------------------------------------------------------------
! FUNCLOAD -- Define this application's external functions. Return
! RTERROR on error, else RTNORM.
entry funcload()
do i = 1, NUM_FUNS
if( ads_defun( func_table(i).func_name, i - 1 ) .eq. 0 )then
funcload = RTERROR
return
endif
end do
funcload = RTNORM
return
!-----------------------------------------------------------------------
! DOFUN -- Execute external function (called upon an RQSUBR request).
! Return value from the function executed, RTNORM or RTERROR.
entry dofun()
! Get the function code and check that it's within range.
! (It can't fail to be, but paranoia doesn't hurt.)
val = ads_getfuncode()
if( val .lt. 0 .or. val .gt. NUM_FUNS )then
call ads_fail(
& 'Received nonexistent function code.'//char(0) )
dofun = RTERROR
return
end if
! Code that handles a single argument.
! Fetch the arguments, if any.
args = ads_getargs()
! Point allocatable array to a result buffer.
allocate( rb(1), location=args )
! Call the handler and return its success-failure status.
dofun = call_handler( func_table(val+1).func, rb )
! Disassociate buffer from allocatable array
deallocate( rb )
! Code that handles multiple arguments.
* ! Fetch the arguments, if any.
* args = ads_getargs()
*
* while( args .ne. NULL )do
*
* ! Point allocatable array to a result buffer.
* allocate( rb(1), location=args )
*
* ! Call the handler and return its success-failure status.
* dofun = call_handler( func_table(val+1).func, rb )
* if( dofun .ne. RTNORM ) quit
*
* ! Get next argument in list.
* args = rb(1).rbnext
*
* ! Disassociate buffer from allocatable array so we don't
* ! get an error on next allocate
* deallocate( rb )
*
* end while
end
!-----------------------------------------------------------------------
! FACT -- First set up the argument, then call the factorial function
integer function fact( rb )
record /resbuf/ rb
include 'adslib.fi'
integer x
double precision rfact
external rfact
if( loc( rb ) .eq. NULL )then
fact = RTERROR
return
end if
if( rb.restype .eq. RTSHORT )then
x = rb.resval.rint ! Save in local variable
else
call ads_fail( 'Argument should be an integer.'//char(0) )
fact = RTERROR
return
end if
if( x .lt. 0 )then ! Check argument range
call ads_fail( 'Argument should be positive.'//char(0) )
fact = RTERROR
return
else if( x .gt. 170 )then ! Avoid floating-point overflow
call ads_fail( 'Argument should be 170 or less.'//char(0) )
fact = RTERROR
return
endif
call ads_retreal( rfact( x ) ) ! Call the function itself, and
! return the value to AutoLISP
fact = RTNORM
end
!-----------------------------------------------------------------------
! This is the implementation of the actual external factorial function
double precision function rfact( n ) ! static
integer n
integer i
rfact = 1.0
do i = n, 1, -1
rfact = rfact * i
end do
end
!-----------------------------------------------------------------------
! SQUAREROOT -- First set up the argument, then call the root function
integer function squareroot( rb )
record /resbuf/ rb
include 'adslib.fi'
double precision x
double precision rsqr
external rsqr
if( loc( rb ) .eq. NULL )then
squareroot = RTERROR ! A proper error msg would be better
return
endif
if( rb.restype .eq. RTSHORT )then ! Save in local variable
x = rb.resval.rint
else if( rb.restype .eq. RTREAL )then
x = rb.resval.rreal ! can accept either real
else ! or integer
call ads_fail(
& 'Argument should be a real or integer value.'//char(0) )
squareroot = RTERROR
end if
if( x .lt. 0.0 )then ! Check argument range
call ads_fail( 'Argument should be positive.'//char(0) )
squareroot = RTERROR
end if
call ads_retreal( rsqr( x ) ) ! Call the function itself, and
! return the value to AutoLISP
squareroot = RTNORM
end
!-----------------------------------------------------------------------
! This is the implementation of the actual external function
double precision function rsqr( x ) ! static
double precision x
! Square root by Newton's method
integer n/50/
double precision c, cl
if( x .eq. 0.0 )then
rsqr = 0.0
return
end if
rsqr = (x * 2 + .1) / (x + 1.0)
c = (rsqr - x / rsqr) / 2
cl= 0.0
while( (c .ne. cl) .and. (n .gt. 0) )do
rsqr = rsqr - c
cl = c
c = (rsqr - x / rsqr) / 2
n = n - 1
end while
end
| 412 | 0.736447 | 1 | 0.736447 | game-dev | MEDIA | 0.184956 | game-dev | 0.933968 | 1 | 0.933968 |
Robosturm/Commander_Wars | 10,440 | resources/scripts/cos/co_andy.js | var Constructor = function()
{
this.getCOStyles = function()
{
return ["+alt", "+alt2", "+alt3"];
};
this.getAiUsePower = function(co, powerSurplus, unitCount, repairUnits, indirectUnits, directUnits, enemyUnits, turnMode)
{
if (turnMode === GameEnums.AiTurnMode_StartOfDay)
{
if (co.canUseSuperpower())
{
return GameEnums.PowerMode_Superpower;
}
else if (powerSurplus <= 0.5 &&
co.canUsePower())
{
return CO.getAiUsePowerAtUnitCount(co, powerSurplus, turnMode, repairUnits);
}
}
};
this.init = function(co, map)
{
co.setPowerStars(3);
co.setSuperpowerStars(3);
};
this.activatePower = function(co, map)
{
var dialogAnimation = co.createPowerSentence();
var powerNameAnimation = co.createPowerScreen(GameEnums.PowerMode_Power);
dialogAnimation.queueAnimation(powerNameAnimation);
var units = co.getOwner().getUnits();
var animations = [];
var counter = 0;
units.randomize();
for (var i = 0; i < units.size(); i++)
{
var unit = units.at(i);
var animation = GameAnimationFactory.createAnimation(map, unit.getX(), unit.getY());
animation.writeDataInt32(unit.getX());
animation.writeDataInt32(unit.getY());
animation.writeDataInt32(CO_ANDY.powerHeal);
animation.setEndOfAnimationCall("ANIMATION", "postAnimationHeal");
var delay = globals.randInt(135, 265);
if (animations.length < 5)
{
delay *= i;
}
animation.setSound("power0.wav", 1, delay);
if (animations.length < 5)
{
animation.addSprite("power0", -map.getImageSize() * 1.27, -map.getImageSize() * 1.27, 0, 2, delay);
powerNameAnimation.queueAnimation(animation);
animations.push(animation);
}
else
{
animation.addSprite("power0", -map.getImageSize() * 1.27, -map.getImageSize() * 1.27, 0, 2, delay);
animations[counter].queueAnimation(animation);
animations[counter] = animation;
counter++;
if (counter >= animations.length)
{
counter = 0;
}
}
}
};
this.activateSuperpower = function(co, powerMode, map)
{
var dialogAnimation = co.createPowerSentence();
var powerNameAnimation = co.createPowerScreen(powerMode);
powerNameAnimation.queueAnimationBefore(dialogAnimation);
var units = co.getOwner().getUnits();
var animations = [];
var counter = 0;
units.randomize();
for (var i = 0; i < units.size(); i++)
{
var unit = units.at(i);
var animation = GameAnimationFactory.createAnimation(map, unit.getX(), unit.getY());
animation.writeDataInt32(unit.getX());
animation.writeDataInt32(unit.getY());
animation.writeDataInt32(CO_ANDY.superPowerHeal);
animation.setEndOfAnimationCall("ANIMATION", "postAnimationHeal");
var delay = globals.randInt(135, 265);
if (animations.length < 7)
{
delay *= i;
}
if (i % 2 === 0)
{
animation.setSound("power12_1.wav", 1, delay);
}
else
{
animation.setSound("power12_2.wav", 1, delay);
}
if (animations.length < 7)
{
animation.addSprite("power12", -map.getImageSize() * 2, -map.getImageSize() * 2, 0, 2, delay);
powerNameAnimation.queueAnimation(animation);
animations.push(animation);
}
else
{
animation.addSprite("power12", -map.getImageSize() * 2, -map.getImageSize() * 2, 0, 2, delay);
animations[counter].queueAnimation(animation);
animations[counter] = animation;
counter++;
if (counter >= animations.length)
{
counter = 0;
}
}
}
};
this.loadCOMusic = function(co, map)
{
if (CO.isActive(co))
{
switch (co.getPowerMode())
{
case GameEnums.PowerMode_Power:
audio.addMusic("resources/music/cos/power.ogg", 992, 45321);
break;
case GameEnums.PowerMode_Superpower:
audio.addMusic("resources/music/cos/superpower.ogg", 1505, 49515);
break;
case GameEnums.PowerMode_Tagpower:
audio.addMusic("resources/music/cos/tagpower.ogg", 14611, 65538);
break;
default:
audio.addMusic("resources/music/cos/andy.ogg", 4466, 74972);
break;
}
}
};
this.getCOUnitRange = function(co, map)
{
return 3;
};
this.getCOArmy = function()
{
return "OS";
};
this.superPowerHeal = 5;
this.superPowerOffBonus = 30;
this.superPowerMovementBonus = 1;
this.powerDefBonus = 20;
this.powerOffBonus = 20;
this.powerHeal = 2;
this.d2dCoZoneOffBonus = 20;
this.d2dCoZoneDefBonus = 20;
this.getOffensiveBonus = function(co, attacker, atkPosX, atkPosY,
defender, defPosX, defPosY, isDefender, action, luckmode, map)
{
if (CO.isActive(co))
{
switch (co.getPowerMode())
{
case GameEnums.PowerMode_Tagpower:
case GameEnums.PowerMode_Superpower:
return CO_ANDY.superPowerOffBonus;
case GameEnums.PowerMode_Power:
return CO_ANDY.powerOffBonus;
default:
if (co.inCORange(Qt.point(atkPosX, atkPosY), attacker))
{
return CO_ANDY.d2dCoZoneOffBonus;
}
break;
}
}
return 0;
};
this.getDeffensiveBonus = function(co, attacker, atkPosX, atkPosY,
defender, defPosX, defPosY, isAttacker, action, luckmode, map)
{
if (CO.isActive(co))
{
if (co.getPowerMode() > GameEnums.PowerMode_Off)
{
return CO_ANDY.powerDefBonus;
}
else if (co.inCORange(Qt.point(defPosX, defPosY), defender))
{
return CO_ANDY.d2dCoZoneDefBonus;
}
}
return 0;
};
this.getMovementpointModifier = function(co, unit, posX, posY, map)
{
if (CO.isActive(co))
{
if (co.getPowerMode() === GameEnums.PowerMode_Superpower ||
co.getPowerMode() === GameEnums.PowerMode_Tagpower)
{
return CO_ANDY.superPowerMovementBonus;
}
}
return 0;
};
this.getCOUnits = function(co, building, map)
{
if (CO.isActive(co))
{
var buildingId = building.getBuildingID();
if (buildingId === "FACTORY" ||
buildingId === "TOWN" ||
BUILDING.isHq(building))
{
return ["ZCOUNIT_REPAIR_TANK"];
}
}
return [];
};
this.getAiCoUnitBonus = function(co, unit, map)
{
return 1;
};
// CO - Intel
this.getBio = function(co)
{
return qsTr("A whiz with a wrench, this mechanical boy wonder earned fame as the hero who saved Macro Land in the last great war.");
};
this.getHits = function(co)
{
return qsTr("Mechanics");
};
this.getMiss = function(co)
{
return qsTr("Waking up too early");
};
this.getCODescription = function(co)
{
return qsTr("No real weaknesses or strengths. Ready to fight wherever and whenever.");
};
this.getLongCODescription = function(co, map)
{
var text = qsTr("\nSpecial Unit:\nRepair Tank\n") +
qsTr("\nGlobal Effect: \nNone.") +
qsTr("\n\nCO Zone Effect: \nAndy's units gain +%0% firepower and +%1% defence.");
text = replaceTextArgs(text, [CO_ANDY.d2dCoZoneOffBonus, CO_ANDY.d2dCoZoneDefBonus]);
return text;
};
this.getPowerDescription = function(co)
{
var text = qsTr("Restores +%0 HP to all of Andy's units. His units gain +%1% firepower and +%2% defence.");
text = replaceTextArgs(text, [CO_ANDY.powerHeal, CO_ANDY.powerOffBonus, CO_ANDY.powerDefBonus]);
return text;
};
this.getPowerName = function(co)
{
return qsTr("Hyper Repair");
};
this.getSuperPowerDescription = function(co)
{
var text = qsTr("Restores +%0 HP to all of Andy's units. His units gain +%2 movement, +%1% firepower, and +%3% defence.");
text = replaceTextArgs(text, [CO_ANDY.superPowerHeal, CO_ANDY.superPowerOffBonus, CO_ANDY.superPowerMovementBonus, CO_ANDY.powerDefBonus]);
return text;
};
this.getSuperPowerName = function(co)
{
return qsTr("Hyper Upgrade");
};
this.getPowerSentences = function(co)
{
return [qsTr("I've got parts to spare!"),
qsTr("I'm not giving up!"),
qsTr("Time to roll up my sleeves!"),
qsTr("I haven't even cranked the engine yet!"),
qsTr("Pass me my wrench!"),
qsTr("It's time for a tune-up!"),
qsTr("Never give up, and never lose! I'm on my way!"),
qsTr("I'm not worried! I can fix anything!")];
};
this.getVictorySentences = function(co)
{
return [qsTr("We won! Woohoo!"),
qsTr("I can fix anything!"),
qsTr("I did it! Did you see that!?")];
};
this.getDefeatSentences = function(co)
{
return [qsTr("Oh, come on!"),
qsTr("Next time I see you, you're in trouble!")];
};
this.getName = function()
{
return qsTr("Andy");
};
}
Constructor.prototype = CO;
var CO_ANDY = new Constructor();
| 412 | 0.590997 | 1 | 0.590997 | game-dev | MEDIA | 0.98053 | game-dev | 0.62406 | 1 | 0.62406 |
shiptest-ss13/Shiptest | 12,714 | code/_onclick/hud/human.dm | /atom/movable/screen/human
icon = 'icons/hud/screen_midnight.dmi'
/atom/movable/screen/human/toggle
name = "toggle"
icon_state = "toggle"
/atom/movable/screen/human/toggle/Click()
var/mob/targetmob = usr
if(isobserver(usr))
if(ishuman(usr.client.eye) && (usr.client.eye != usr))
var/mob/M = usr.client.eye
targetmob = M
if(usr.hud_used.inventory_shown && targetmob.hud_used)
usr.hud_used.inventory_shown = FALSE
usr.client.screen -= targetmob.hud_used.toggleable_inventory
else
usr.hud_used.inventory_shown = TRUE
usr.client.screen += targetmob.hud_used.toggleable_inventory
targetmob.hud_used.hidden_inventory_update(usr)
/atom/movable/screen/human/equip
name = "equip"
icon_state = "act_equip"
/atom/movable/screen/human/equip/Click()
if(ismecha(usr.loc)) // stops inventory actions in a mech
return 1
var/mob/living/carbon/human/H = usr
H.quick_equip()
/atom/movable/screen/ling
icon = 'icons/hud/screen_changeling.dmi'
invisibility = INVISIBILITY_ABSTRACT
/atom/movable/screen/ling/sting
name = "current sting"
screen_loc = ui_lingstingdisplay
/atom/movable/screen/ling/sting/Click()
if(isobserver(usr))
return
var/mob/living/carbon/U = usr
U.unset_sting()
/atom/movable/screen/ling/chems
name = "chemical storage"
icon_state = "power_display"
screen_loc = ui_lingchemdisplay
/datum/hud/human/New(mob/living/carbon/human/owner)
..()
var/widescreen_layout = FALSE
if(owner.client?.prefs?.widescreenpref)
widescreen_layout = TRUE
var/atom/movable/screen/using
var/atom/movable/screen/inventory/inv_box
using = new/atom/movable/screen/language_menu
using.icon = ui_style
if(!widescreen_layout)
using.screen_loc = UI_BOXLANG
using.hud = src
static_inventory += using
using = new/atom/movable/screen/skills
using.icon = ui_style
if(!widescreen_layout)
using.screen_loc = UI_BOXLANG
static_inventory += using
using = new /atom/movable/screen/area_creator
using.icon = ui_style
if(!widescreen_layout)
using.screen_loc = UI_BOXAREA
using.hud = src
static_inventory += using
action_intent = new /atom/movable/screen/act_intent/segmented
action_intent.icon_state = mymob.a_intent
action_intent.hud = src
static_inventory += action_intent
using = new /atom/movable/screen/mov_intent
using.icon = ui_style
using.icon_state = (mymob.m_intent == MOVE_INTENT_RUN ? "running" : "walking")
using.screen_loc = ui_movi
using.hud = src
static_inventory += using
using = new /atom/movable/screen/drop()
using.icon = ui_style
using.screen_loc = ui_drop_throw
using.hud = src
static_inventory += using
inv_box = new /atom/movable/screen/inventory()
inv_box.name = "i_clothing"
inv_box.icon = ui_style
inv_box.slot_id = ITEM_SLOT_ICLOTHING
inv_box.icon_state = "uniform"
inv_box.screen_loc = ui_iclothing
inv_box.hud = src
toggleable_inventory += inv_box
inv_box = new /atom/movable/screen/inventory()
inv_box.name = "o_clothing"
inv_box.icon = ui_style
inv_box.slot_id = ITEM_SLOT_OCLOTHING
inv_box.icon_state = "suit"
inv_box.screen_loc = ui_oclothing
inv_box.hud = src
toggleable_inventory += inv_box
build_hand_slots()
using = new /atom/movable/screen/swap_hand()
using.icon = ui_style
using.icon_state = "swap_1"
using.screen_loc = ui_swaphand_position(owner,1)
using.hud = src
static_inventory += using
using = new /atom/movable/screen/swap_hand()
using.icon = ui_style
using.icon_state = "swap_2"
using.screen_loc = ui_swaphand_position(owner,2)
using.hud = src
static_inventory += using
inv_box = new /atom/movable/screen/inventory()
inv_box.name = "id"
inv_box.icon = ui_style
inv_box.icon_state = "id"
inv_box.screen_loc = ui_id
inv_box.slot_id = ITEM_SLOT_ID
inv_box.hud = src
static_inventory += inv_box
inv_box = new /atom/movable/screen/inventory()
inv_box.name = "mask"
inv_box.icon = ui_style
inv_box.icon_state = "mask"
inv_box.screen_loc = ui_mask
inv_box.slot_id = ITEM_SLOT_MASK
inv_box.hud = src
toggleable_inventory += inv_box
inv_box = new /atom/movable/screen/inventory()
inv_box.name = "neck"
inv_box.icon = ui_style
inv_box.icon_state = "neck"
inv_box.screen_loc = ui_neck
inv_box.slot_id = ITEM_SLOT_NECK
inv_box.hud = src
toggleable_inventory += inv_box
inv_box = new /atom/movable/screen/inventory()
inv_box.name = "back"
inv_box.icon = ui_style
inv_box.icon_state = "back"
inv_box.screen_loc = ui_back
inv_box.slot_id = ITEM_SLOT_BACK
inv_box.hud = src
static_inventory += inv_box
inv_box = new /atom/movable/screen/inventory()
inv_box.name = "storage1"
inv_box.icon = ui_style
inv_box.icon_state = "pocket"
inv_box.screen_loc = ui_storage1
inv_box.slot_id = ITEM_SLOT_LPOCKET
inv_box.hud = src
static_inventory += inv_box
inv_box = new /atom/movable/screen/inventory()
inv_box.name = "storage2"
inv_box.icon = ui_style
inv_box.icon_state = "pocket"
inv_box.screen_loc = ui_storage2
inv_box.slot_id = ITEM_SLOT_RPOCKET
inv_box.hud = src
static_inventory += inv_box
inv_box = new /atom/movable/screen/inventory()
inv_box.name = "suit storage"
inv_box.icon = ui_style
inv_box.icon_state = "suit_storage"
inv_box.screen_loc = ui_sstore1
inv_box.slot_id = ITEM_SLOT_SUITSTORE
inv_box.hud = src
static_inventory += inv_box
using = new /atom/movable/screen/resist()
using.icon = ui_style
using.screen_loc = ui_above_intent
using.hud = src
hotkeybuttons += using
using = new /atom/movable/screen/human/toggle()
using.icon = ui_style
using.screen_loc = ui_inventory
using.hud = src
static_inventory += using
using = new /atom/movable/screen/human/equip()
using.icon = ui_style
using.screen_loc = ui_equip_position(mymob)
using.hud = src
static_inventory += using
inv_box = new /atom/movable/screen/inventory()
inv_box.name = "gloves"
inv_box.icon = ui_style
inv_box.icon_state = "gloves"
inv_box.screen_loc = ui_gloves
inv_box.slot_id = ITEM_SLOT_GLOVES
inv_box.hud = src
toggleable_inventory += inv_box
inv_box = new /atom/movable/screen/inventory()
inv_box.name = "eyes"
inv_box.icon = ui_style
inv_box.icon_state = "glasses"
inv_box.screen_loc = ui_glasses
inv_box.slot_id = ITEM_SLOT_EYES
inv_box.hud = src
toggleable_inventory += inv_box
inv_box = new /atom/movable/screen/inventory()
inv_box.name = "ears"
inv_box.icon = ui_style
inv_box.icon_state = "ears"
inv_box.screen_loc = ui_ears
inv_box.slot_id = ITEM_SLOT_EARS
inv_box.hud = src
toggleable_inventory += inv_box
inv_box = new /atom/movable/screen/inventory()
inv_box.name = "head"
inv_box.icon = ui_style
inv_box.icon_state = "head"
inv_box.screen_loc = ui_head
inv_box.slot_id = ITEM_SLOT_HEAD
inv_box.hud = src
toggleable_inventory += inv_box
inv_box = new /atom/movable/screen/inventory()
inv_box.name = "shoes"
inv_box.icon = ui_style
inv_box.icon_state = "shoes"
inv_box.screen_loc = ui_shoes
inv_box.slot_id = ITEM_SLOT_FEET
inv_box.hud = src
toggleable_inventory += inv_box
inv_box = new /atom/movable/screen/inventory()
inv_box.name = "belt"
inv_box.icon = ui_style
inv_box.icon_state = "belt"
// inv_box.icon_full = "template_small"
inv_box.screen_loc = ui_belt
inv_box.slot_id = ITEM_SLOT_BELT
inv_box.hud = src
static_inventory += inv_box
throw_icon = new /atom/movable/screen/throw_catch()
throw_icon.icon = ui_style
throw_icon.screen_loc = ui_drop_throw
throw_icon.hud = src
hotkeybuttons += throw_icon
rest_icon = new /atom/movable/screen/rest()
rest_icon.icon = ui_style
rest_icon.screen_loc = ui_above_movement
rest_icon.hud = src
static_inventory += rest_icon
internals = new /atom/movable/screen/internals()
internals.hud = src
infodisplay += internals
healths = new /atom/movable/screen/healths()
healths.hud = src
infodisplay += healths
healthdoll = new /atom/movable/screen/healthdoll()
healthdoll.hud = src
infodisplay += healthdoll
pull_icon = new /atom/movable/screen/pull()
pull_icon.icon = ui_style
pull_icon.update_appearance()
pull_icon.screen_loc = ui_above_intent
pull_icon.hud = src
static_inventory += pull_icon
lingchemdisplay = new /atom/movable/screen/ling/chems()
lingchemdisplay.hud = src
infodisplay += lingchemdisplay
lingstingdisplay = new /atom/movable/screen/ling/sting()
lingstingdisplay.hud = src
infodisplay += lingstingdisplay
zone_select = new /atom/movable/screen/zone_sel()
zone_select.icon = ui_style
zone_select.hud = src
zone_select.update_appearance()
static_inventory += zone_select
combo_display = new /atom/movable/screen/combo()
infodisplay += combo_display
ammo_counter = new /atom/movable/screen/ammo_counter(null, src)
infodisplay += ammo_counter
use_timer = new(null, src)
use_timer.RegisterSignal(mymob, COMSIG_LIVING_CHANGENEXT_MOVE, TYPE_PROC_REF(/atom/movable/screen/progbar_container, on_changenext))
static_inventory += use_timer
for(var/atom/movable/screen/inventory/inv in (static_inventory + toggleable_inventory))
if(inv.slot_id)
inv.hud = src
inv_slots[TOBITSHIFT(inv.slot_id) + 1] = inv
inv.update_appearance()
update_locked_slots()
/datum/hud/human/update_locked_slots()
if(!mymob)
return
var/mob/living/carbon/human/H = mymob
if(!istype(H) || !H.dna.species)
return
var/datum/species/S = H.dna.species
for(var/atom/movable/screen/inventory/inv in (static_inventory + toggleable_inventory))
if(inv.slot_id)
if(inv.slot_id in S.no_equip)
inv.alpha = 128
else
inv.alpha = initial(inv.alpha)
/datum/hud/human/hidden_inventory_update(mob/viewer)
if(!mymob)
return
var/mob/living/carbon/human/H = mymob
var/mob/screenmob = viewer || H
if(screenmob.hud_used.inventory_shown && screenmob.hud_used.hud_shown)
if(H.shoes)
H.shoes.screen_loc = ui_shoes
screenmob.client.screen += H.shoes
if(H.gloves)
H.gloves.screen_loc = ui_gloves
screenmob.client.screen += H.gloves
if(H.ears)
H.ears.screen_loc = ui_ears
screenmob.client.screen += H.ears
if(H.glasses)
H.glasses.screen_loc = ui_glasses
screenmob.client.screen += H.glasses
if(H.w_uniform)
H.w_uniform.screen_loc = ui_iclothing
screenmob.client.screen += H.w_uniform
if(H.wear_suit)
H.wear_suit.screen_loc = ui_oclothing
screenmob.client.screen += H.wear_suit
if(H.wear_mask)
H.wear_mask.screen_loc = ui_mask
screenmob.client.screen += H.wear_mask
if(H.wear_neck)
H.wear_neck.screen_loc = ui_neck
screenmob.client.screen += H.wear_neck
if(H.head)
H.head.screen_loc = ui_head
screenmob.client.screen += H.head
else
if(H.shoes) screenmob.client.screen -= H.shoes
if(H.gloves) screenmob.client.screen -= H.gloves
if(H.ears) screenmob.client.screen -= H.ears
if(H.glasses) screenmob.client.screen -= H.glasses
if(H.w_uniform) screenmob.client.screen -= H.w_uniform
if(H.wear_suit) screenmob.client.screen -= H.wear_suit
if(H.wear_mask) screenmob.client.screen -= H.wear_mask
if(H.wear_neck) screenmob.client.screen -= H.wear_neck
if(H.head) screenmob.client.screen -= H.head
/datum/hud/human/persistent_inventory_update(mob/viewer)
if(!mymob)
return
..()
var/mob/living/carbon/human/H = mymob
var/mob/screenmob = viewer || H
if(screenmob.hud_used)
if(screenmob.hud_used.hud_shown)
if(H.s_store)
H.s_store.screen_loc = ui_sstore1
screenmob.client.screen += H.s_store
if(H.wear_id)
H.wear_id.screen_loc = ui_id
screenmob.client.screen += H.wear_id
if(H.belt)
H.belt.screen_loc = ui_belt
screenmob.client.screen += H.belt
if(H.back)
H.back.screen_loc = ui_back
screenmob.client.screen += H.back
if(H.l_store)
H.l_store.screen_loc = ui_storage1
screenmob.client.screen += H.l_store
if(H.r_store)
H.r_store.screen_loc = ui_storage2
screenmob.client.screen += H.r_store
else
if(H.s_store)
screenmob.client.screen -= H.s_store
if(H.wear_id)
screenmob.client.screen -= H.wear_id
if(H.belt)
screenmob.client.screen -= H.belt
if(H.back)
screenmob.client.screen -= H.back
if(H.l_store)
screenmob.client.screen -= H.l_store
if(H.r_store)
screenmob.client.screen -= H.r_store
if(hud_version != HUD_STYLE_NOHUD)
for(var/obj/item/I in H.held_items)
I.screen_loc = ui_hand_position(H.get_held_index_of_item(I))
screenmob.client.screen += I
else
for(var/obj/item/I in H.held_items)
I.screen_loc = null
screenmob.client.screen -= I
/mob/living/carbon/human/verb/toggle_hotkey_verbs()
set category = "OOC"
set name = "Toggle hotkey buttons"
set desc = "This disables or enables the user interface buttons which can be used with hotkeys."
if(hud_used.hotkey_ui_hidden)
client.screen += hud_used.hotkeybuttons
hud_used.hotkey_ui_hidden = FALSE
else
client.screen -= hud_used.hotkeybuttons
hud_used.hotkey_ui_hidden = TRUE
| 412 | 0.822097 | 1 | 0.822097 | game-dev | MEDIA | 0.620166 | game-dev | 0.892987 | 1 | 0.892987 |
fredakilla/GPlayEngine | 3,848 | thirdparty/bullet/src/BulletSoftBody/btSoftMultiBodyDynamicsWorld.h | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
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_SOFT_MULTIBODY_DYNAMICS_WORLD_H
#define BT_SOFT_MULTIBODY_DYNAMICS_WORLD_H
#include "BulletDynamics/Dynamics/btDiscreteDynamicsWorld.h"
#include "BulletDynamics/Featherstone/btMultiBodyDynamicsWorld.h"
#include "BulletSoftBody/btSoftBody.h"
typedef btAlignedObjectArray<btSoftBody*> btSoftBodyArray;
class btSoftBodySolver;
class btSoftMultiBodyDynamicsWorld : public btMultiBodyDynamicsWorld
{
btSoftBodyArray m_softBodies;
int m_drawFlags;
bool m_drawNodeTree;
bool m_drawFaceTree;
bool m_drawClusterTree;
btSoftBodyWorldInfo m_sbi;
///Solver classes that encapsulate multiple soft bodies for solving
btSoftBodySolver *m_softBodySolver;
bool m_ownsSolver;
protected:
virtual void predictUnconstraintMotion(btScalar timeStep);
virtual void internalSingleStepSimulation( btScalar timeStep);
void solveSoftBodiesConstraints( btScalar timeStep );
void serializeSoftBodies(btSerializer* serializer);
public:
btSoftMultiBodyDynamicsWorld(btDispatcher* dispatcher,btBroadphaseInterface* pairCache,btMultiBodyConstraintSolver* constraintSolver, btCollisionConfiguration* collisionConfiguration, btSoftBodySolver *softBodySolver = 0 );
virtual ~btSoftMultiBodyDynamicsWorld();
virtual void debugDrawWorld();
void addSoftBody(btSoftBody* body, int collisionFilterGroup=btBroadphaseProxy::DefaultFilter, int collisionFilterMask=btBroadphaseProxy::AllFilter);
void removeSoftBody(btSoftBody* body);
///removeCollisionObject will first check if it is a rigid body, if so call removeRigidBody otherwise call btDiscreteDynamicsWorld::removeCollisionObject
virtual void removeCollisionObject(btCollisionObject* collisionObject);
int getDrawFlags() const { return(m_drawFlags); }
void setDrawFlags(int f) { m_drawFlags=f; }
btSoftBodyWorldInfo& getWorldInfo()
{
return m_sbi;
}
const btSoftBodyWorldInfo& getWorldInfo() const
{
return m_sbi;
}
virtual btDynamicsWorldType getWorldType() const
{
return BT_SOFT_MULTIBODY_DYNAMICS_WORLD;
}
btSoftBodyArray& getSoftBodyArray()
{
return m_softBodies;
}
const btSoftBodyArray& getSoftBodyArray() const
{
return m_softBodies;
}
virtual void rayTest(const btVector3& rayFromWorld, const btVector3& rayToWorld, RayResultCallback& resultCallback) const;
/// rayTestSingle performs a raycast call and calls the resultCallback. It is used internally by rayTest.
/// In a future implementation, we consider moving the ray test as a virtual method in btCollisionShape.
/// This allows more customization.
static void rayTestSingle(const btTransform& rayFromTrans,const btTransform& rayToTrans,
btCollisionObject* collisionObject,
const btCollisionShape* collisionShape,
const btTransform& colObjWorldTransform,
RayResultCallback& resultCallback);
virtual void serialize(btSerializer* serializer);
};
#endif //BT_SOFT_MULTIBODY_DYNAMICS_WORLD_H
| 412 | 0.672027 | 1 | 0.672027 | game-dev | MEDIA | 0.988472 | game-dev | 0.611686 | 1 | 0.611686 |
PsiCodes/ktxpy | 18,635 | libp7zip/src/main/cpp/p7zip/CPP/7zip/Archive/7z/7zHandler.cpp | // 7zHandler.cpp
#include "StdAfx.h"
#include "../../../../C/CpuArch.h"
#include "../../../Common/ComTry.h"
#include "../../../Common/IntToString.h"
#ifndef __7Z_SET_PROPERTIES
#include "../../../Windows/System.h"
#endif
#include "../Common/ItemNameUtils.h"
#include "7zHandler.h"
#include "7zProperties.h"
#ifdef __7Z_SET_PROPERTIES
#ifdef EXTRACT_ONLY
#include "../Common/ParseProperties.h"
#endif
#endif
using namespace NWindows;
using namespace NCOM;
namespace NArchive {
namespace N7z {
CHandler::CHandler()
{
#ifndef _NO_CRYPTO
_isEncrypted = false;
_passwordIsDefined = false;
#endif
#ifdef EXTRACT_ONLY
_crcSize = 4;
#ifdef __7Z_SET_PROPERTIES
_numThreads = NSystem::GetNumberOfProcessors();
_useMultiThreadMixer = true;
#endif
#endif
}
STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems)
{
*numItems = _db.Files.Size();
return S_OK;
}
#ifdef _SFX
IMP_IInArchive_ArcProps_NO_Table
STDMETHODIMP CHandler::GetNumberOfProperties(UInt32 *numProps)
{
*numProps = 0;
return S_OK;
}
STDMETHODIMP CHandler::GetPropertyInfo(UInt32 /* index */,
BSTR * /* name */, PROPID * /* propID */, VARTYPE * /* varType */)
{
return E_NOTIMPL;
}
#else
static const Byte kArcProps[] =
{
kpidHeadersSize,
kpidMethod,
kpidSolid,
kpidNumBlocks
// , kpidIsTree
};
IMP_IInArchive_ArcProps
static inline char GetHex(unsigned value)
{
return (char)((value < 10) ? ('0' + value) : ('A' + (value - 10)));
}
static unsigned ConvertMethodIdToString_Back(char *s, UInt64 id)
{
int len = 0;
do
{
s[--len] = GetHex((unsigned)id & 0xF); id >>= 4;
s[--len] = GetHex((unsigned)id & 0xF); id >>= 4;
}
while (id != 0);
return (unsigned)-len;
}
static void ConvertMethodIdToString(AString &res, UInt64 id)
{
const unsigned kLen = 32;
char s[kLen];
unsigned len = kLen - 1;
s[len] = 0;
res += s + len - ConvertMethodIdToString_Back(s + len, id);
}
static unsigned GetStringForSizeValue(char *s, UInt32 val)
{
unsigned i;
for (i = 0; i <= 31; i++)
if (((UInt32)1 << i) == val)
{
if (i < 10)
{
s[0] = (char)('0' + i);
s[1] = 0;
return 1;
}
if (i < 20) { s[0] = '1'; s[1] = (char)('0' + i - 10); }
else if (i < 30) { s[0] = '2'; s[1] = (char)('0' + i - 20); }
else { s[0] = '3'; s[1] = (char)('0' + i - 30); }
s[2] = 0;
return 2;
}
char c = 'b';
if ((val & ((1 << 20) - 1)) == 0) { val >>= 20; c = 'm'; }
else if ((val & ((1 << 10) - 1)) == 0) { val >>= 10; c = 'k'; }
::ConvertUInt32ToString(val, s);
unsigned pos = MyStringLen(s);
s[pos++] = c;
s[pos] = 0;
return pos;
}
/*
static inline void AddHexToString(UString &res, Byte value)
{
res += GetHex((Byte)(value >> 4));
res += GetHex((Byte)(value & 0xF));
}
*/
static char *AddProp32(char *s, const char *name, UInt32 v)
{
*s++ = ':';
s = MyStpCpy(s, name);
::ConvertUInt32ToString(v, s);
return s + MyStringLen(s);
}
void CHandler::AddMethodName(AString &s, UInt64 id)
{
AString name;
FindMethod(EXTERNAL_CODECS_VARS id, name);
if (name.IsEmpty())
ConvertMethodIdToString(s, id);
else
s += name;
}
#endif
STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
{
#ifndef _SFX
COM_TRY_BEGIN
#endif
NCOM::CPropVariant prop;
switch (propID)
{
#ifndef _SFX
case kpidMethod:
{
AString s;
const CParsedMethods &pm = _db.ParsedMethods;
FOR_VECTOR (i, pm.IDs)
{
UInt64 id = pm.IDs[i];
s.Add_Space_if_NotEmpty();
char temp[16];
if (id == k_LZMA2)
{
s += "LZMA2:";
if ((pm.Lzma2Prop & 1) == 0)
ConvertUInt32ToString((pm.Lzma2Prop >> 1) + 12, temp);
else
GetStringForSizeValue(temp, 3 << ((pm.Lzma2Prop >> 1) + 11));
s += temp;
}
else if (id == k_LZMA)
{
s += "LZMA:";
GetStringForSizeValue(temp, pm.LzmaDic);
s += temp;
}
else
AddMethodName(s, id);
}
prop = s;
break;
}
case kpidSolid: prop = _db.IsSolid(); break;
case kpidNumBlocks: prop = (UInt32)_db.NumFolders; break;
case kpidHeadersSize: prop = _db.HeadersSize; break;
case kpidPhySize: prop = _db.PhySize; break;
case kpidOffset: if (_db.ArcInfo.StartPosition != 0) prop = _db.ArcInfo.StartPosition; break;
/*
case kpidIsTree: if (_db.IsTree) prop = true; break;
case kpidIsAltStream: if (_db.ThereAreAltStreams) prop = true; break;
case kpidIsAux: if (_db.IsTree) prop = true; break;
*/
// case kpidError: if (_db.ThereIsHeaderError) prop = "Header error"; break;
#endif
case kpidWarningFlags:
{
UInt32 v = 0;
if (_db.StartHeaderWasRecovered) v |= kpv_ErrorFlags_HeadersError;
if (_db.UnsupportedFeatureWarning) v |= kpv_ErrorFlags_UnsupportedFeature;
if (v != 0)
prop = v;
break;
}
case kpidErrorFlags:
{
UInt32 v = 0;
if (!_db.IsArc) v |= kpv_ErrorFlags_IsNotArc;
if (_db.ThereIsHeaderError) v |= kpv_ErrorFlags_HeadersError;
if (_db.UnexpectedEnd) v |= kpv_ErrorFlags_UnexpectedEnd;
// if (_db.UnsupportedVersion) v |= kpv_ErrorFlags_Unsupported;
if (_db.UnsupportedFeatureError) v |= kpv_ErrorFlags_UnsupportedFeature;
prop = v;
break;
}
}
prop.Detach(value);
return S_OK;
#ifndef _SFX
COM_TRY_END
#endif
}
static void SetFileTimeProp_From_UInt64Def(PROPVARIANT *prop, const CUInt64DefVector &v, int index)
{
UInt64 value;
if (v.GetItem(index, value))
PropVarEm_Set_FileTime64(prop, value);
}
bool CHandler::IsFolderEncrypted(CNum folderIndex) const
{
if (folderIndex == kNumNoIndex)
return false;
size_t startPos = _db.FoCodersDataOffset[folderIndex];
const Byte *p = _db.CodersData + startPos;
size_t size = _db.FoCodersDataOffset[folderIndex + 1] - startPos;
CInByte2 inByte;
inByte.Init(p, size);
CNum numCoders = inByte.ReadNum();
for (; numCoders != 0; numCoders--)
{
Byte mainByte = inByte.ReadByte();
unsigned idSize = (mainByte & 0xF);
const Byte *longID = inByte.GetPtr();
UInt64 id64 = 0;
for (unsigned j = 0; j < idSize; j++)
id64 = ((id64 << 8) | longID[j]);
inByte.SkipDataNoCheck(idSize);
if (id64 == k_AES)
return true;
if ((mainByte & 0x20) != 0)
inByte.SkipDataNoCheck(inByte.ReadNum());
}
return false;
}
STDMETHODIMP CHandler::GetNumRawProps(UInt32 *numProps)
{
*numProps = 0;
return S_OK;
}
STDMETHODIMP CHandler::GetRawPropInfo(UInt32 /* index */, BSTR *name, PROPID *propID)
{
*name = NULL;
*propID = kpidNtSecure;
return S_OK;
}
STDMETHODIMP CHandler::GetParent(UInt32 /* index */, UInt32 *parent, UInt32 *parentType)
{
/*
const CFileItem &file = _db.Files[index];
*parentType = (file.IsAltStream ? NParentType::kAltStream : NParentType::kDir);
*parent = (UInt32)(Int32)file.Parent;
*/
*parentType = NParentType::kDir;
*parent = (UInt32)(Int32)-1;
return S_OK;
}
STDMETHODIMP CHandler::GetRawProp(UInt32 index, PROPID propID, const void **data, UInt32 *dataSize, UInt32 *propType)
{
*data = NULL;
*dataSize = 0;
*propType = 0;
if (/* _db.IsTree && propID == kpidName ||
!_db.IsTree && */ propID == kpidPath)
{
if (_db.NameOffsets && _db.NamesBuf)
{
size_t offset = _db.NameOffsets[index];
size_t size = (_db.NameOffsets[index + 1] - offset) * 2;
if (size < ((UInt32)1 << 31))
{
*data = (const void *)(_db.NamesBuf + offset * 2);
*dataSize = (UInt32)size;
*propType = NPropDataType::kUtf16z;
}
}
return S_OK;
}
/*
if (propID == kpidNtSecure)
{
if (index < (UInt32)_db.SecureIDs.Size())
{
int id = _db.SecureIDs[index];
size_t offs = _db.SecureOffsets[id];
size_t size = _db.SecureOffsets[id + 1] - offs;
if (size >= 0)
{
*data = _db.SecureBuf + offs;
*dataSize = (UInt32)size;
*propType = NPropDataType::kRaw;
}
}
}
*/
return S_OK;
}
#ifndef _SFX
HRESULT CHandler::SetMethodToProp(CNum folderIndex, PROPVARIANT *prop) const
{
PropVariant_Clear(prop);
if (folderIndex == kNumNoIndex)
return S_OK;
// for (int ttt = 0; ttt < 1; ttt++) {
const unsigned kTempSize = 256;
char temp[kTempSize];
unsigned pos = kTempSize;
temp[--pos] = 0;
size_t startPos = _db.FoCodersDataOffset[folderIndex];
const Byte *p = _db.CodersData + startPos;
size_t size = _db.FoCodersDataOffset[folderIndex + 1] - startPos;
CInByte2 inByte;
inByte.Init(p, size);
// numCoders == 0 ???
CNum numCoders = inByte.ReadNum();
bool needSpace = false;
for (; numCoders != 0; numCoders--, needSpace = true)
{
if (pos < 32) // max size of property
break;
Byte mainByte = inByte.ReadByte();
unsigned idSize = (mainByte & 0xF);
const Byte *longID = inByte.GetPtr();
UInt64 id64 = 0;
for (unsigned j = 0; j < idSize; j++)
id64 = ((id64 << 8) | longID[j]);
inByte.SkipDataNoCheck(idSize);
if ((mainByte & 0x10) != 0)
{
inByte.ReadNum(); // NumInStreams
inByte.ReadNum(); // NumOutStreams
}
CNum propsSize = 0;
const Byte *props = NULL;
if ((mainByte & 0x20) != 0)
{
propsSize = inByte.ReadNum();
props = inByte.GetPtr();
inByte.SkipDataNoCheck(propsSize);
}
const char *name = NULL;
char s[32];
s[0] = 0;
if (id64 <= (UInt32)0xFFFFFFFF)
{
UInt32 id = (UInt32)id64;
if (id == k_LZMA)
{
name = "LZMA";
if (propsSize == 5)
{
UInt32 dicSize = GetUi32((const Byte *)props + 1);
char *dest = s + GetStringForSizeValue(s, dicSize);
UInt32 d = props[0];
if (d != 0x5D)
{
UInt32 lc = d % 9;
d /= 9;
UInt32 pb = d / 5;
UInt32 lp = d % 5;
if (lc != 3) dest = AddProp32(dest, "lc", lc);
if (lp != 0) dest = AddProp32(dest, "lp", lp);
if (pb != 2) dest = AddProp32(dest, "pb", pb);
}
}
}
else if (id == k_LZMA2)
{
name = "LZMA2";
if (propsSize == 1)
{
Byte d = props[0];
if ((d & 1) == 0)
ConvertUInt32ToString((UInt32)((d >> 1) + 12), s);
else
GetStringForSizeValue(s, 3 << ((d >> 1) + 11));
}
}
else if (id == k_PPMD)
{
name = "PPMD";
if (propsSize == 5)
{
Byte order = *props;
char *dest = s;
*dest++ = 'o';
ConvertUInt32ToString(order, dest);
dest += MyStringLen(dest);
dest = MyStpCpy(dest, ":mem");
GetStringForSizeValue(dest, GetUi32(props + 1));
}
}
else if (id == k_Delta)
{
name = "Delta";
if (propsSize == 1)
ConvertUInt32ToString((UInt32)props[0] + 1, s);
}
else if (id == k_BCJ2) name = "BCJ2";
else if (id == k_BCJ) name = "BCJ";
else if (id == k_AES)
{
name = "7zAES";
if (propsSize >= 1)
{
Byte firstByte = props[0];
UInt32 numCyclesPower = firstByte & 0x3F;
ConvertUInt32ToString(numCyclesPower, s);
}
}
}
if (name)
{
unsigned nameLen = MyStringLen(name);
unsigned propsLen = MyStringLen(s);
unsigned totalLen = nameLen + propsLen;
if (propsLen != 0)
totalLen++;
if (needSpace)
totalLen++;
if (totalLen + 5 >= pos)
break;
pos -= totalLen;
MyStringCopy(temp + pos, name);
if (propsLen != 0)
{
char *dest = temp + pos + nameLen;
*dest++ = ':';
MyStringCopy(dest, s);
}
if (needSpace)
temp[pos + totalLen - 1] = ' ';
}
else
{
AString methodName;
FindMethod(EXTERNAL_CODECS_VARS id64, methodName);
if (needSpace)
temp[--pos] = ' ';
if (methodName.IsEmpty())
pos -= ConvertMethodIdToString_Back(temp + pos, id64);
else
{
unsigned len = methodName.Len();
if (len + 5 > pos)
break;
pos -= len;
for (unsigned i = 0; i < len; i++)
temp[pos + i] = methodName[i];
}
}
}
if (numCoders != 0 && pos >= 4)
{
temp[--pos] = ' ';
temp[--pos] = '.';
temp[--pos] = '.';
temp[--pos] = '.';
}
return PropVarEm_Set_Str(prop, temp + pos);
// }
}
#endif
STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)
{
PropVariant_Clear(value);
// COM_TRY_BEGIN
// NCOM::CPropVariant prop;
/*
const CRef2 &ref2 = _refs[index];
if (ref2.Refs.IsEmpty())
return E_FAIL;
const CRef &ref = ref2.Refs.Front();
*/
const CFileItem &item = _db.Files[index];
UInt32 index2 = index;
switch (propID)
{
case kpidIsDir: PropVarEm_Set_Bool(value, item.IsDir); break;
case kpidSize:
{
PropVarEm_Set_UInt64(value, item.Size);
// prop = ref2.Size;
break;
}
case kpidPackSize:
{
// prop = ref2.PackSize;
{
CNum folderIndex = _db.FileIndexToFolderIndexMap[index2];
if (folderIndex != kNumNoIndex)
{
if (_db.FolderStartFileIndex[folderIndex] == (CNum)index2)
PropVarEm_Set_UInt64(value, _db.GetFolderFullPackSize(folderIndex));
/*
else
PropVarEm_Set_UInt64(value, 0);
*/
}
else
PropVarEm_Set_UInt64(value, 0);
}
break;
}
// case kpidIsAux: prop = _db.IsItemAux(index2); break;
case kpidPosition: { UInt64 v; if (_db.StartPos.GetItem(index2, v)) PropVarEm_Set_UInt64(value, v); break; }
case kpidCTime: SetFileTimeProp_From_UInt64Def(value, _db.CTime, index2); break;
case kpidATime: SetFileTimeProp_From_UInt64Def(value, _db.ATime, index2); break;
case kpidMTime: SetFileTimeProp_From_UInt64Def(value, _db.MTime, index2); break;
case kpidAttrib: if (item.AttribDefined) PropVarEm_Set_UInt32(value, item.Attrib); break;
case kpidCRC: if (item.CrcDefined) PropVarEm_Set_UInt32(value, item.Crc); break;
case kpidEncrypted: PropVarEm_Set_Bool(value, IsFolderEncrypted(_db.FileIndexToFolderIndexMap[index2])); break;
case kpidIsAnti: PropVarEm_Set_Bool(value, _db.IsItemAnti(index2)); break;
/*
case kpidIsAltStream: prop = item.IsAltStream; break;
case kpidNtSecure:
{
int id = _db.SecureIDs[index];
size_t offs = _db.SecureOffsets[id];
size_t size = _db.SecureOffsets[id + 1] - offs;
if (size >= 0)
{
prop.SetBlob(_db.SecureBuf + offs, (ULONG)size);
}
break;
}
*/
case kpidPath: return _db.GetPath_Prop(index, value);
#ifndef _SFX
case kpidMethod: return SetMethodToProp(_db.FileIndexToFolderIndexMap[index2], value);
case kpidBlock:
{
CNum folderIndex = _db.FileIndexToFolderIndexMap[index2];
if (folderIndex != kNumNoIndex)
PropVarEm_Set_UInt32(value, (UInt32)folderIndex);
}
break;
/*
case kpidPackedSize0:
case kpidPackedSize1:
case kpidPackedSize2:
case kpidPackedSize3:
case kpidPackedSize4:
{
CNum folderIndex = _db.FileIndexToFolderIndexMap[index2];
if (folderIndex != kNumNoIndex)
{
if (_db.FolderStartFileIndex[folderIndex] == (CNum)index2 &&
_db.FoStartPackStreamIndex[folderIndex + 1] -
_db.FoStartPackStreamIndex[folderIndex] > (propID - kpidPackedSize0))
{
PropVarEm_Set_UInt64(value, _db.GetFolderPackStreamSize(folderIndex, propID - kpidPackedSize0));
}
}
else
PropVarEm_Set_UInt64(value, 0);
}
break;
*/
#endif
}
// prop.Detach(value);
return S_OK;
// COM_TRY_END
}
STDMETHODIMP CHandler::Open(IInStream *stream,
const UInt64 *maxCheckStartPosition,
IArchiveOpenCallback *openArchiveCallback)
{
COM_TRY_BEGIN
Close();
#ifndef _SFX
_fileInfoPopIDs.Clear();
#endif
try
{
CMyComPtr<IArchiveOpenCallback> openArchiveCallbackTemp = openArchiveCallback;
#ifndef _NO_CRYPTO
CMyComPtr<ICryptoGetTextPassword> getTextPassword;
if (openArchiveCallback)
openArchiveCallbackTemp.QueryInterface(IID_ICryptoGetTextPassword, &getTextPassword);
#endif
CInArchive archive(
#ifdef __7Z_SET_PROPERTIES
_useMultiThreadMixer
#else
true
#endif
);
_db.IsArc = false;
RINOK(archive.Open(stream, maxCheckStartPosition));
_db.IsArc = true;
HRESULT result = archive.ReadDatabase(
EXTERNAL_CODECS_VARS
_db
#ifndef _NO_CRYPTO
, getTextPassword, _isEncrypted, _passwordIsDefined, _password
#endif
);
RINOK(result);
_inStream = stream;
}
catch(...)
{
Close();
// return E_INVALIDARG;
// return S_FALSE;
// we must return out_of_memory here
return E_OUTOFMEMORY;
}
// _inStream = stream;
#ifndef _SFX
FillPopIDs();
#endif
return S_OK;
COM_TRY_END
}
STDMETHODIMP CHandler::Close()
{
COM_TRY_BEGIN
_inStream.Release();
_db.Clear();
#ifndef _NO_CRYPTO
_isEncrypted = false;
_passwordIsDefined = false;
_password.Empty();
#endif
return S_OK;
COM_TRY_END
}
#ifdef __7Z_SET_PROPERTIES
#ifdef EXTRACT_ONLY
STDMETHODIMP CHandler::SetProperties(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps)
{
COM_TRY_BEGIN
const UInt32 numProcessors = NSystem::GetNumberOfProcessors();
_numThreads = numProcessors;
_useMultiThreadMixer = true;
for (UInt32 i = 0; i < numProps; i++)
{
UString name = names[i];
name.MakeLower_Ascii();
if (name.IsEmpty())
return E_INVALIDARG;
const PROPVARIANT &value = values[i];
UInt32 number;
unsigned index = ParseStringToUInt32(name, number);
if (index == 0)
{
if (name.IsEqualTo("mtf"))
{
RINOK(PROPVARIANT_to_bool(value, _useMultiThreadMixer));
continue;
}
if (name.IsPrefixedBy_Ascii_NoCase("mt"))
{
RINOK(ParseMtProp(name.Ptr(2), value, numProcessors, _numThreads));
continue;
}
else
return E_INVALIDARG;
}
}
return S_OK;
COM_TRY_END
}
#endif
#endif
IMPL_ISetCompressCodecsInfo
}}
| 412 | 0.983879 | 1 | 0.983879 | game-dev | MEDIA | 0.324694 | game-dev | 0.995825 | 1 | 0.995825 |
ForestryMC/ForestryMC | 1,025 | src/main/java/forestry/api/book/IBookContent.java | package forestry.api.book;
import javax.annotation.Nullable;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import forestry.api.gui.IElementGroup;
import forestry.api.gui.IGuiElement;
import forestry.api.gui.IGuiElementFactory;
@SideOnly(Side.CLIENT)
public interface IBookContent {
/**
* Called after the deserialization.
*/
default void onDeserialization() {
}
/**
* Adds the content to the page by adding a {@link IGuiElement} or at the content to the previous element.
*
* @param page The gui element that represents a book page
* @param previous The content of the previous element.
* @param previousElement The element that was previously added to the page.
* @param pageHeight The max height of the current page.
* @return True if you added an element.
*/
boolean addElements(IElementGroup page, IGuiElementFactory factory, @Nullable BookContent previous, @Nullable IGuiElement previousElement, int pageHeight);
}
| 412 | 0.726403 | 1 | 0.726403 | game-dev | MEDIA | 0.376521 | game-dev,graphics-rendering | 0.647633 | 1 | 0.647633 |
AndroidBBQ/android10 | 1,949 | frameworks/compile/mclinker/include/mcld/Script/RpnExpr.h | //===- RPNExpr.h ----------------------------------------------------------===//
//
// The MCLinker Project
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef MCLD_SCRIPT_RPNEXPR_H_
#define MCLD_SCRIPT_RPNEXPR_H_
#include "mcld/Config/Config.h"
#include "mcld/Object/SectionMap.h"
#include "mcld/Support/Allocators.h"
#include <vector>
namespace mcld {
class ExprToken;
class Fragment;
/** \class RpnExpr
* \brief This class defines the interfaces to a rpn expression.
*/
class RpnExpr {
public:
typedef std::vector<ExprToken*> TokenQueue;
typedef TokenQueue::const_iterator const_iterator;
typedef TokenQueue::iterator iterator;
private:
friend class Chunk<RpnExpr, MCLD_SYMBOLS_PER_INPUT>;
RpnExpr();
public:
~RpnExpr();
const_iterator begin() const { return m_TokenQueue.begin(); }
iterator begin() { return m_TokenQueue.begin(); }
const_iterator end() const { return m_TokenQueue.end(); }
iterator end() { return m_TokenQueue.end(); }
size_t size() const { return m_TokenQueue.size(); }
bool empty() const { return m_TokenQueue.empty(); }
bool hasDot() const;
void dump() const;
void push_back(ExprToken* pToken);
iterator insert(iterator pPosition, ExprToken* pToken);
void erase(iterator pPosition);
/* factory methods */
static RpnExpr* create();
static void destroy(RpnExpr*& pRpnExpr);
static void clear();
// buildHelperExpr - build the helper expr:
// ADDR ( `output_sect' ) + SIZEOF ( `output_sect' )
static RpnExpr* buildHelperExpr(SectionMap::iterator pIter);
// buildHelperExpr - build the helper expr: `fragment'
static RpnExpr* buildHelperExpr(Fragment& pFrag);
private:
TokenQueue m_TokenQueue;
};
} // namespace mcld
#endif // MCLD_SCRIPT_RPNEXPR_H_
| 412 | 0.948818 | 1 | 0.948818 | game-dev | MEDIA | 0.496552 | game-dev | 0.890971 | 1 | 0.890971 |
Pierre-Terdiman/PEEL | 11,679 | PEEL/Physics/Ice/APIs/Ice/IceCore/IceParser.h | ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Contains a parser.
* \file IceParser.h
* \author Pierre Terdiman
* \date April, 4, 2000
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Include Guard
#ifndef ICEPARSER_H
#define ICEPARSER_H
//
FUNCTION ICECORE_API bool ReadScript(const char* name);
// Parse & search
FUNCTION ICECORE_API bool ParseAndSearch(const String& str, const String& keywords);
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* User-callback, called by the parser each time a new string parameter has been found.
* \param param [in] the string parameter
* \param user_data [in] user-defined data
* \return true to end parsing
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
typedef bool (*PARSE_CALLBACK) (const char* param, void* user_data);
class ICECORE_API TextParser : public Allocateable
{
public:
// Constructor/Destructor
TextParser();
~TextParser();
// Initialize separators and end symbol
static bool Init();
static void SetSeparator(ubyte symbol) { mSeparator[symbol] = true; }
static void SetDiscarded(ubyte symbol) { mDiscarded[symbol] = true; }
// Callback control
inline_ TextParser& SetUserData(void* user_data) { mUserData = user_data; return *this; }
inline_ TextParser& SetCallback(PARSE_CALLBACK callback) { mCallback = callback; return *this; }
// Parsing method
bool Parse(const char* text);
private:
static bool mSeparator[256]; //!< Separators
static bool mDiscarded[256]; //!< Discarded symbols
static ubyte mEndSymbol; //!< End marker
// User callback
void* mUserData; //!< User-defined data sent to callbacks
PARSE_CALLBACK mCallback;
};
// Forward declarations
class ParameterBlock;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* User-callback, called by the parser each time a new string parameter has been found, or when an error occurs.
* \param command [in] original unmodified command currently parsed
* \param pb [in] command's parameter block
* \param context [in] callback context (e.g. error codes for error callback)
* \param user_data [in] user-defined data
* \param cmd [in] possible matched command's parameter block
* \return true to go ahead and continue parsing, false to stop it
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
typedef bool (*CMDPARSE_CALLBACK) (const char* command, const ParameterBlock& pb, udword context, void* user_data, const ParameterBlock* cmd);
typedef bool (*RAWPARSE_CALLBACK) (const char* command, void* user_data);
enum BlockFixingCode
{
BFC_PRESERVE = 0, //!< Don't modify strings
BFC_REMOVE_TABS = (1<<0), //!< Replace tabs with spaces
BFC_MAKE_LOWER_CASE = (1<<1), //!< Make lower case
BFC_REMOVE_SEMICOLON = (1<<2), //!< Remove end-of-line semicolons
BFC_REMOVE_PIPE = (1<<3), //!< Remove |
BFC_DISCARD_COMMENTS = (1<<4), //!< Discard comments
BFC_DISCARD_UNKNOWNCMDS = (1<<5), //!< Discard unknown commands
BFC_DISCARD_INVALIDCMDS = (1<<6), //!< Discard invalid commands
BFC_DISCARD_GLOBALCMDS = (1<<7), //!< Discard global commands
BFC_COMMENTS_FLIPSTATUS = (1<<8), //!< Internal comments/code status
BFC_SUPPORT_INCLUDE = (1<<9), //!< Supports "#include" command or not
BFC_READONLY = BFC_COMMENTS_FLIPSTATUS|BFC_SUPPORT_INCLUDE,
BFC_FORCE_DWORD = 0x7fffffff
};
class ICECORE_API ParameterBlock : public Allocateable
{
public:
// Constructor/Destructor
ParameterBlock();
ParameterBlock(const char* str);
// ParameterBlock(const String& str);
ParameterBlock(const ParameterBlock& block);
~ParameterBlock();
// Initialize
udword Create(const char* str);
udword Create(const ParameterBlock& block);
inline_ udword Create(const String& str) { return Create(str.Get()); }
// Reset
void DeleteAll();
// Operations
bool MakeLowerCase();
bool MakeUpperCase();
// Settings
void BindData(CMDPARSE_CALLBACK callback, udword context, bool check_params);
void ForceNbParams(udword i) { mNbParams = i; }
// Data access
inline_ udword GetNbParams() const { return mNbParams; }
inline_ String& GetParam(udword i) { ASSERT(i<mNbParams); return mTable[i]; }
inline_ const String& GetParam(udword i) const { ASSERT(i<mNbParams); return mTable[i]; }
inline_ String& operator[](udword i) const { ASSERT(i<mNbParams); return mTable[i]; }
inline_ const String& GetCommand() const { return mCommand; }
inline_ CMDPARSE_CALLBACK GetCallback() const { return mCallback; }
inline_ udword GetContext() const { return mContext; }
inline_ bool MustCheckParams() const { return mCheckParams; }
private:
String mCommand; //!< Original string
// Parameters
udword mNbParams;
String* mTable;
// Data
CMDPARSE_CALLBACK mCallback;
udword mContext;
bool mCheckParams;
};
class ICECORE_API ReadOnlyParameterBlock : public Allocateable
{
public:
// Constructor/Destructor
ReadOnlyParameterBlock();
ReadOnlyParameterBlock(const char* str);
~ReadOnlyParameterBlock();
// Initialize
udword Create(const char* str);
// Reset
void DeleteAll();
// Operations
bool MakeLowerCase();
bool MakeUpperCase();
// Settings
void BindData(CMDPARSE_CALLBACK callback, udword context, bool check_params);
void ForceNbParams(udword i) { mNbParams = i; }
// Data access
inline_ udword GetNbParams() const { return mNbParams; }
inline_ const char* operator[](udword i) const { ASSERT(i<mNbParams); return mTable[i]; }
inline_ const String& GetCommand() const { return mCommand; }
inline_ CMDPARSE_CALLBACK GetCallback() const { return mCallback; }
inline_ udword GetContext() const { return mContext; }
inline_ bool MustCheckParams() const { return mCheckParams; }
private:
String mCommand; //!< Original string
char* mModified; //!< Modified string
// Parameters
udword mNbParams;
char** mTable;
// Data
CMDPARSE_CALLBACK mCallback;
udword mContext;
bool mCheckParams;
};
class ICECORE_API CommandManager : public Allocateable
{
public:
// Constructor/Destructor
CommandManager();
virtual ~CommandManager();
// Commands
bool FlushCommands();
bool RegisterCommand(const char* command, CMDPARSE_CALLBACK callback=null, udword context=0, bool check_params=true);
bool UnregisterCommand(const char* command);
inline_ udword GetNbCommands() const { return mCommands.GetNbEntries(); }
inline_ ParameterBlock* GetCommand(udword i) const { return (ParameterBlock*)mCommands.GetEntry(i); }
private:
// Registered commands and associated data
Container mCommands;
};
ICECORE_API CommandManager* GetCommandManager();
class ICECORE_API CommandParser : public CommandManager
{
public:
// Constructor/Destructor
CommandParser();
virtual ~CommandParser();
DECLARE_FLAGS(BlockFixingCode, mParsingFlags, BFC_READONLY)
// Callback control
inline_ void SetUserData(void* user_data) { mUserData = user_data; }
inline_ void SetParseCallback(CMDPARSE_CALLBACK callback) { mParseCallback = callback; }
inline_ void SetRawParseCallback(RAWPARSE_CALLBACK callback) { mRawParseCallback = callback; }
inline_ void SetErrorCallback(CMDPARSE_CALLBACK callback) { mErrorCallback = callback; }
// Parsing method
bool CommandParse(const char* buffer);
// To overload
virtual bool Execute(const char* source) { mParsingFlags&=~BFC_COMMENTS_FLIPSTATUS; return true; }
private:
Constants* mDefines; //!< Used for #define command
// User callback
void* mUserData; //!< User-defined data sent to callbacks
RAWPARSE_CALLBACK mRawParseCallback; //!< User-defined callback for each line
CMDPARSE_CALLBACK mParseCallback; //!< User-defined callback for each line
CMDPARSE_CALLBACK mErrorCallback; //!< User-defined callback for errors
// Current line is cut to pieces in this parameter block
ParameterBlock mPB;
// Internal methods
bool FindCommand(const char* buffer, const CommandManager* cm, const ParameterBlock& work, bool& valid_command, ParameterBlock*& cmd);
};
class ICECORE_API BufferParser : public CommandParser
{
public:
// Constructor/Destructor
BufferParser();
virtual ~BufferParser();
// Parsing method
virtual bool Execute(const char* buffer);
};
class VirtualFile;
class ICECORE_API ScriptFile : public CommandParser
{
public:
// Constructor/Destructor
ScriptFile();
virtual ~ScriptFile();
// Parsing method
virtual bool Execute(const char* filename);
bool Execute(const VirtualFileHandle& handle);
bool Execute(VirtualFile& file);
};
class ICECORE_API Parsable
{
public:
// Constructor/Destructor
Parsable();
virtual ~Parsable();
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Parses a text and call the parsing callback for each line.
* \param text [in] the text to parse
* \return true if success
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool Parse(const char* text);
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* User-callback, called by the parser each time a new line has been found.
* \param line [in] the new line
* \param pb [in] a parameter-block made from current line
* \return true to end parsing
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
virtual bool Parameter(const char* line, const ParameterBlock& pb) { return false; }
};
#endif // ICEPARSER_H
| 412 | 0.82908 | 1 | 0.82908 | game-dev | MEDIA | 0.360676 | game-dev | 0.651326 | 1 | 0.651326 |
DukeofCambridge/Road2Technical_Artist | 37,158 | Assets/Plugins/AmplifyShaderEditor/Plugins/Editor/Nodes/Constants/StaticSwitch.cs | // Amplify Shader Editor - Visual Shader vEditing Tool
// Copyright (c) Amplify Creations, Lda <info@amplify.pt>
using UnityEngine;
using UnityEditor;
using System;
namespace AmplifyShaderEditor
{
[Serializable]
[NodeAttributes( "Static Switch", "Logical Operators", "Creates a shader keyword toggle", Available = true )]
public sealed class StaticSwitch : PropertyNode
{
private float InstanceIconWidth = 19;
private float InstanceIconHeight = 19;
private readonly Color ReferenceHeaderColor = new Color( 0f, 0.5f, 0.585f, 1.0f );
[SerializeField]
private int m_defaultValue = 0;
[SerializeField]
private int m_materialValue = 0;
[SerializeField]
private int m_multiCompile = 0;
[SerializeField]
private int m_currentKeywordId = 0;
[SerializeField]
private string m_currentKeyword = string.Empty;
[SerializeField]
private bool m_createToggle = true;
[SerializeField]
private bool m_lockKeyword = true;
private const string IsLocalStr = "Is Local";
#if UNITY_2019_1_OR_NEWER
[SerializeField]
private bool m_isLocal = true;
#else
[SerializeField]
private bool m_isLocal = false;
#endif
private GUIContent m_checkContent;
private GUIContent m_popContent;
private int m_conditionId = -1;
private const int MinComboSize = 50;
private const int MaxComboSize = 105;
private Rect m_varRect;
private Rect m_imgRect;
private bool m_editing;
public enum KeywordModeType
{
Toggle = 0,
ToggleOff,
KeywordEnum,
}
public enum StaticSwitchVariableMode
{
Create = 0,
Fetch,
Reference
}
[SerializeField]
private KeywordModeType m_keywordModeType = KeywordModeType.Toggle;
[SerializeField]
private StaticSwitch m_reference = null;
private const string StaticSwitchStr = "Static Switch";
private const string MaterialToggleStr = "Material Toggle";
private const string ToggleMaterialValueStr = "Material Value";
private const string ToggleDefaultValueStr = "Default Value";
private const string AmountStr = "Amount";
private const string KeywordStr = "Keyword";
private const string CustomStr = "Custom";
private const string ToggleTypeStr = "Toggle Type";
private const string TypeStr = "Type";
private const string ModeStr = "Mode";
private const string KeywordTypeStr = "Keyword Type";
private const string KeywordNameStr = "Keyword Name";
public readonly static string[] KeywordTypeList = { "Shader Feature", "Multi Compile"/*, "Define Symbol"*/ };
public readonly static int[] KeywordTypeInt = { 0, 1/*, 2*/ };
[SerializeField]
private string[] m_defaultKeywordNames = { "Key0", "Key1", "Key2", "Key3", "Key4", "Key5", "Key6", "Key7", "Key8" };
[SerializeField]
private string[] m_keywordEnumList = { "Key0", "Key1" };
[SerializeField]
private StaticSwitchVariableMode m_staticSwitchVarMode = StaticSwitchVariableMode.Create;
[SerializeField]
private int m_referenceArrayId = -1;
[SerializeField]
private int m_referenceNodeId = -1;
private int m_keywordEnumAmount = 2;
private bool m_isStaticSwitchDirty = false;
private Rect m_iconPos;
protected override void CommonInit( int uniqueId )
{
base.CommonInit( uniqueId );
AddOutputPort( WirePortDataType.FLOAT, Constants.EmptyPortValue );
AddInputPort( WirePortDataType.FLOAT, false, "False", -1, MasterNodePortCategory.Fragment, 1 );
AddInputPort( WirePortDataType.FLOAT, false, "True", -1, MasterNodePortCategory.Fragment, 0 );
for( int i = 2; i < 9; i++ )
{
AddInputPort( WirePortDataType.FLOAT, false, m_defaultKeywordNames[ i ] );
m_inputPorts[ i ].Visible = false;
}
m_headerColor = new Color( 0.0f, 0.55f, 0.45f, 1f );
m_customPrefix = KeywordStr + " ";
m_autoWrapProperties = false;
m_freeType = false;
m_useVarSubtitle = true;
m_allowPropertyDuplicates = true;
m_showTitleWhenNotEditing = false;
m_currentParameterType = PropertyType.Property;
m_checkContent = new GUIContent();
m_checkContent.image = UIUtils.CheckmarkIcon;
m_popContent = new GUIContent();
m_popContent.image = UIUtils.PopupIcon;
m_previewShaderGUID = "0b708c11c68e6a9478ac97fe3643eab1";
m_showAutoRegisterUI = true;
}
public override void SetPreviewInputs()
{
base.SetPreviewInputs();
if( m_conditionId == -1 )
m_conditionId = Shader.PropertyToID( "_Condition" );
StaticSwitch node = ( m_staticSwitchVarMode == StaticSwitchVariableMode.Reference && m_reference != null ) ? m_reference : this;
if( m_createToggle )
PreviewMaterial.SetInt( m_conditionId, node.MaterialValue );
else
PreviewMaterial.SetInt( m_conditionId, node.DefaultValue );
}
protected override void OnUniqueIDAssigned()
{
base.OnUniqueIDAssigned();
if( m_createToggle )
UIUtils.RegisterPropertyNode( this );
else
UIUtils.UnregisterPropertyNode( this );
if( CurrentVarMode != StaticSwitchVariableMode.Reference )
{
ContainerGraph.StaticSwitchNodes.AddNode( this );
}
if( UniqueId > -1 )
ContainerGraph.StaticSwitchNodes.OnReorderEventComplete += OnReorderEventComplete;
}
public override void Destroy()
{
base.Destroy();
UIUtils.UnregisterPropertyNode( this );
if( CurrentVarMode != StaticSwitchVariableMode.Reference )
{
ContainerGraph.StaticSwitchNodes.RemoveNode( this );
}
if( UniqueId > -1 )
ContainerGraph.StaticSwitchNodes.OnReorderEventComplete -= OnReorderEventComplete;
}
void OnReorderEventComplete()
{
if( CurrentVarMode == StaticSwitchVariableMode.Reference )
{
if( m_reference != null )
{
m_referenceArrayId = ContainerGraph.StaticSwitchNodes.GetNodeRegisterIdx( m_reference.UniqueId );
}
}
}
public override void OnInputPortConnected( int portId, int otherNodeId, int otherPortId, bool activateNode = true )
{
base.OnInputPortConnected( portId, otherNodeId, otherPortId, activateNode );
UpdateConnections();
}
public override void OnConnectedOutputNodeChanges( int inputPortId, int otherNodeId, int otherPortId, string name, WirePortDataType type )
{
base.OnConnectedOutputNodeChanges( inputPortId, otherNodeId, otherPortId, name, type );
UpdateConnections();
}
public override void OnInputPortDisconnected( int portId )
{
base.OnInputPortDisconnected( portId );
UpdateConnections();
}
private void UpdateConnections()
{
WirePortDataType mainType = WirePortDataType.FLOAT;
int highest = UIUtils.GetPriority( mainType );
for( int i = 0; i < m_inputPorts.Count; i++ )
{
if( m_inputPorts[ i ].IsConnected )
{
WirePortDataType portType = m_inputPorts[ i ].GetOutputConnection().DataType;
if( UIUtils.GetPriority( portType ) > highest )
{
mainType = portType;
highest = UIUtils.GetPriority( portType );
}
}
}
for( int i = 0; i < m_inputPorts.Count; i++ )
{
m_inputPorts[ i ].ChangeType( mainType, false );
}
m_outputPorts[ 0 ].ChangeType( mainType, false );
}
public override string GetPropertyValue()
{
if( m_createToggle )
if( m_keywordModeType == KeywordModeType.KeywordEnum && m_keywordEnumAmount > 0 )
return PropertyAttributes + "[" + m_keywordModeType.ToString() + "(" + GetKeywordEnumPropertyList() + ")] " + m_propertyName + "(\"" + m_propertyInspectorName + "\", Float) = " + m_defaultValue;
else
return PropertyAttributes + "[" + m_keywordModeType.ToString() + "(" + GetPropertyValStr() + ")] " + m_propertyName + "(\"" + m_propertyInspectorName + "\", Float) = " + m_defaultValue;
else
return string.Empty;
}
public string KeywordEnum( int index )
{
if( m_createToggle )
{
return string.IsNullOrEmpty( PropertyName ) ? KeywordEnumList( index ) : ( PropertyName + "_" + KeywordEnumList( index ) );
}
else
{
return string.IsNullOrEmpty( PropertyName ) ? KeywordEnumList( index ) : ( PropertyName + KeywordEnumList( index ) );
}
}
public string KeywordEnumList( int index )
{
if( CurrentVarMode == StaticSwitchVariableMode.Fetch )
return m_keywordEnumList[ index ];
else
{
return m_createToggle ? m_keywordEnumList[ index ].ToUpper() : m_keywordEnumList[ index ];
}
}
public override string PropertyName
{
get
{
if( CurrentVarMode == StaticSwitchVariableMode.Fetch )
return m_currentKeyword;
else
{
return m_createToggle ? base.PropertyName.ToUpper() : base.PropertyName;
}
}
}
public override string GetPropertyValStr()
{
if( m_keywordModeType == KeywordModeType.KeywordEnum )
return PropertyName;
else if( !m_lockKeyword )
return CurrentKeyword;
else if( CurrentVarMode == StaticSwitchVariableMode.Fetch )
return m_currentKeyword;
else
return PropertyName + OnOffStr;
}
private string GetKeywordEnumPropertyList()
{
string result = string.Empty;
for( int i = 0; i < m_keywordEnumList.Length; i++ )
{
if( i == 0 )
result = m_keywordEnumList[ i ];
else
result += "," + m_keywordEnumList[ i ];
}
return result;
}
private string GetKeywordEnumPragmaList()
{
string result = string.Empty;
for( int i = 0; i < m_keywordEnumList.Length; i++ )
{
if( i == 0 )
result = KeywordEnum( i );
else
result += " " + KeywordEnum( i );
}
return result;
}
public override string GetUniformValue()
{
return string.Empty;
}
public override bool GetUniformData( out string dataType, out string dataName, ref bool fullValue )
{
dataType = string.Empty;
dataName = string.Empty;
return false;
}
public override void DrawProperties()
{
//base.DrawProperties();
NodeUtils.DrawPropertyGroup( ref m_propertiesFoldout, Constants.ParameterLabelStr, PropertyGroup );
NodeUtils.DrawPropertyGroup( ref m_visibleCustomAttrFoldout, CustomAttrStr, DrawCustomAttributes, DrawCustomAttrAddRemoveButtons );
CheckPropertyFromInspector();
}
void DrawEnumList()
{
EditorGUI.BeginChangeCheck();
KeywordEnumAmount = EditorGUILayoutIntSlider( AmountStr, KeywordEnumAmount, 2, 9 );
if( EditorGUI.EndChangeCheck() )
{
CurrentSelectedInput = Mathf.Clamp( CurrentSelectedInput, 0, KeywordEnumAmount - 1 );
UpdateLabels();
}
EditorGUI.indentLevel++;
for( int i = 0; i < m_keywordEnumList.Length; i++ )
{
EditorGUI.BeginChangeCheck();
m_keywordEnumList[ i ] = EditorGUILayoutTextField( "Item " + i, m_keywordEnumList[ i ] );
if( EditorGUI.EndChangeCheck() )
{
m_keywordEnumList[ i ] = UIUtils.RemoveInvalidEnumCharacters( m_keywordEnumList[ i ] );
m_keywordEnumList[ i ] = m_keywordEnumList[ i ].Replace( " ", "" ); // sad face :( does not support spaces
m_inputPorts[ i ].Name = m_keywordEnumList[ i ];
m_defaultKeywordNames[ i ] = m_inputPorts[ i ].Name;
}
}
EditorGUI.indentLevel--;
}
public void UpdateLabels()
{
int maxinputs = m_keywordModeType == KeywordModeType.KeywordEnum ? KeywordEnumAmount : 2;
KeywordEnumAmount = Mathf.Clamp( KeywordEnumAmount, 0, maxinputs );
m_keywordEnumList = new string[ maxinputs ];
for( int i = 0; i < maxinputs; i++ )
{
m_keywordEnumList[ i ] = m_defaultKeywordNames[ i ];
m_inputPorts[ i ].Name = m_keywordEnumList[ i ];
}
if( m_keywordModeType != KeywordModeType.KeywordEnum )
{
m_inputPorts[ 0 ].Name = "False";
m_inputPorts[ 1 ].Name = "True";
}
for( int i = 0; i < m_inputPorts.Count; i++ )
{
m_inputPorts[ i ].Visible = ( i < maxinputs );
}
m_sizeIsDirty = true;
m_isStaticSwitchDirty = true;
}
void PropertyGroup()
{
EditorGUI.BeginChangeCheck();
CurrentVarMode = (StaticSwitchVariableMode)EditorGUILayoutEnumPopup( ModeStr, CurrentVarMode );
if( EditorGUI.EndChangeCheck() )
{
if( CurrentVarMode == StaticSwitchVariableMode.Fetch )
{
m_keywordModeType = KeywordModeType.Toggle;
UpdateLabels();
}
if( CurrentVarMode == StaticSwitchVariableMode.Reference )
{
UIUtils.UnregisterPropertyNode( this );
}
else
{
if( m_createToggle )
UIUtils.RegisterPropertyNode( this );
else
UIUtils.UnregisterPropertyNode( this );
}
}
if( CurrentVarMode == StaticSwitchVariableMode.Create )
{
EditorGUI.BeginChangeCheck();
m_multiCompile = EditorGUILayoutIntPopup( KeywordTypeStr, m_multiCompile, KeywordTypeList, KeywordTypeInt );
if( EditorGUI.EndChangeCheck() )
{
BeginPropertyFromInspectorCheck();
}
}
else if( CurrentVarMode == StaticSwitchVariableMode.Reference )
{
string[] arr = ContainerGraph.StaticSwitchNodes.NodesArr;
bool guiEnabledBuffer = GUI.enabled;
if( arr != null && arr.Length > 0 )
{
GUI.enabled = true;
}
else
{
m_referenceArrayId = -1;
GUI.enabled = false;
}
EditorGUI.BeginChangeCheck();
m_referenceArrayId = EditorGUILayoutPopup( Constants.AvailableReferenceStr, m_referenceArrayId, arr );
if( EditorGUI.EndChangeCheck() )
{
m_reference = ContainerGraph.StaticSwitchNodes.GetNode( m_referenceArrayId );
if( m_reference != null )
{
m_referenceNodeId = m_reference.UniqueId;
CheckReferenceValues( true );
}
else
{
m_referenceArrayId = -1;
m_referenceNodeId = -1;
}
}
GUI.enabled = guiEnabledBuffer;
return;
}
if( CurrentVarMode == StaticSwitchVariableMode.Create || m_createToggle )
{
EditorGUI.BeginChangeCheck();
m_keywordModeType = (KeywordModeType)EditorGUILayoutEnumPopup( TypeStr, m_keywordModeType );
if( EditorGUI.EndChangeCheck() )
{
UpdateLabels();
}
}
if( m_keywordModeType != KeywordModeType.KeywordEnum )
{
if( CurrentVarMode == StaticSwitchVariableMode.Create || m_createToggle )
{
ShowPropertyInspectorNameGUI();
ShowPropertyNameGUI( true );
if( CurrentVarMode == StaticSwitchVariableMode.Create )
{
EditorGUILayout.BeginHorizontal();
bool guiEnabledBuffer = GUI.enabled;
GUI.enabled = !m_lockKeyword;
if( m_lockKeyword )
EditorGUILayout.TextField( KeywordNameStr, GetPropertyValStr() );
else
m_currentKeyword = EditorGUILayoutTextField( KeywordNameStr, m_currentKeyword );
GUI.enabled = guiEnabledBuffer;
m_lockKeyword = GUILayout.Toggle( m_lockKeyword, ( m_lockKeyword ? UIUtils.LockIconOpen : UIUtils.LockIconClosed ), "minibutton", GUILayout.Width( 22 ) );
EditorGUILayout.EndHorizontal();
}
}
}
else
{
if( CurrentVarMode == StaticSwitchVariableMode.Create || m_createToggle )
{
ShowPropertyInspectorNameGUI();
ShowPropertyNameGUI( true );
DrawEnumList();
}
}
if( CurrentVarMode == StaticSwitchVariableMode.Fetch )
{
//ShowPropertyInspectorNameGUI();
EditorGUI.BeginChangeCheck();
m_currentKeywordId = EditorGUILayoutPopup( KeywordStr, m_currentKeywordId, UIUtils.AvailableKeywords );
if( EditorGUI.EndChangeCheck() )
{
if( m_currentKeywordId != 0 )
{
m_currentKeyword = UIUtils.AvailableKeywords[ m_currentKeywordId ];
}
}
if( m_currentKeywordId == 0 )
{
EditorGUI.BeginChangeCheck();
m_currentKeyword = EditorGUILayoutTextField( CustomStr, m_currentKeyword );
if( EditorGUI.EndChangeCheck() )
{
m_currentKeyword = UIUtils.RemoveInvalidCharacters( m_currentKeyword );
}
}
}
#if UNITY_2019_1_OR_NEWER
m_isLocal = EditorGUILayoutToggle( IsLocalStr, m_isLocal );
#endif
//if( CurrentVarMode == StaticSwitchVariableMode.Create )
{
ShowAutoRegister();
}
EditorGUI.BeginChangeCheck();
m_createToggle = EditorGUILayoutToggle( MaterialToggleStr, m_createToggle );
if( EditorGUI.EndChangeCheck() )
{
if( m_createToggle )
UIUtils.RegisterPropertyNode( this );
else
UIUtils.UnregisterPropertyNode( this );
}
if( m_createToggle )
{
EditorGUILayout.BeginHorizontal();
GUILayout.Space( 20 );
m_propertyTab = GUILayout.Toolbar( m_propertyTab, LabelToolbarTitle );
EditorGUILayout.EndHorizontal();
switch( m_propertyTab )
{
default:
case 0:
{
EditorGUI.BeginChangeCheck();
if( m_keywordModeType != KeywordModeType.KeywordEnum )
m_materialValue = EditorGUILayoutToggle( ToggleMaterialValueStr, m_materialValue == 1 ) ? 1 : 0;
else
m_materialValue = EditorGUILayoutPopup( ToggleMaterialValueStr, m_materialValue, m_keywordEnumList );
if( EditorGUI.EndChangeCheck() )
m_requireMaterialUpdate = true;
}
break;
case 1:
{
if( m_keywordModeType != KeywordModeType.KeywordEnum )
m_defaultValue = EditorGUILayoutToggle( ToggleDefaultValueStr, m_defaultValue == 1 ) ? 1 : 0;
else
m_defaultValue = EditorGUILayoutPopup( ToggleDefaultValueStr, m_defaultValue, m_keywordEnumList );
}
break;
}
}
//EditorGUILayout.HelpBox( "Keyword Type:\n" +
// "The difference is that unused variants of \"Shader Feature\" shaders will not be included into game build while \"Multi Compile\" variants are included regardless of their usage.\n\n" +
// "So \"Shader Feature\" makes most sense for keywords that will be set on the materials, while \"Multi Compile\" for keywords that will be set from code globally.\n\n" +
// "You can set keywords using the material property using the \"Property Name\" or you can set the keyword directly using the \"Keyword Name\".", MessageType.None );
}
public override void CheckPropertyFromInspector( bool forceUpdate = false )
{
if( m_propertyFromInspector )
{
if( forceUpdate || ( EditorApplication.timeSinceStartup - m_propertyFromInspectorTimestamp ) > MaxTimestamp )
{
m_propertyFromInspector = false;
RegisterPropertyName( true, m_propertyInspectorName, m_autoGlobalName, m_underscoredGlobal );
m_propertyNameIsDirty = true;
if( CurrentVarMode != StaticSwitchVariableMode.Reference )
{
ContainerGraph.StaticSwitchNodes.UpdateDataOnNode( UniqueId, DataToArray );
}
}
}
}
public override void OnNodeLayout( DrawInfo drawInfo )
{
float finalSize = 0;
if( m_keywordModeType == KeywordModeType.KeywordEnum )
{
GUIContent dropdown = new GUIContent( m_inputPorts[ CurrentSelectedInput ].Name );
int cacheSize = UIUtils.GraphDropDown.fontSize;
UIUtils.GraphDropDown.fontSize = 10;
Vector2 calcSize = UIUtils.GraphDropDown.CalcSize( dropdown );
UIUtils.GraphDropDown.fontSize = cacheSize;
finalSize = Mathf.Clamp( calcSize.x, MinComboSize, MaxComboSize );
if( m_insideSize.x != finalSize )
{
m_insideSize.Set( finalSize, 25 );
m_sizeIsDirty = true;
}
}
base.OnNodeLayout( drawInfo );
if( m_keywordModeType != KeywordModeType.KeywordEnum )
{
m_varRect = m_remainingBox;
m_varRect.size = Vector2.one * 22 * drawInfo.InvertedZoom;
m_varRect.center = m_remainingBox.center;
if( m_showPreview )
m_varRect.y = m_remainingBox.y;
}
else
{
m_varRect = m_remainingBox;
m_varRect.width = finalSize * drawInfo.InvertedZoom;
m_varRect.height = 16 * drawInfo.InvertedZoom;
m_varRect.x = m_remainingBox.xMax - m_varRect.width;
m_varRect.y += 1 * drawInfo.InvertedZoom;
m_imgRect = m_varRect;
m_imgRect.x = m_varRect.xMax - 16 * drawInfo.InvertedZoom;
m_imgRect.width = 16 * drawInfo.InvertedZoom;
m_imgRect.height = m_imgRect.width;
}
CheckReferenceValues( false );
if( m_staticSwitchVarMode == StaticSwitchVariableMode.Reference )
{
m_iconPos = m_globalPosition;
m_iconPos.width = InstanceIconWidth * drawInfo.InvertedZoom;
m_iconPos.height = InstanceIconHeight * drawInfo.InvertedZoom;
m_iconPos.y += 10 * drawInfo.InvertedZoom;
m_iconPos.x += /*m_globalPosition.width - m_iconPos.width - */5 * drawInfo.InvertedZoom;
}
}
void CheckReferenceValues( bool forceUpdate )
{
if( m_staticSwitchVarMode == StaticSwitchVariableMode.Reference )
{
if( m_reference == null && m_referenceNodeId > 0 )
{
m_reference = ContainerGraph.GetNode( m_referenceNodeId ) as StaticSwitch;
m_referenceArrayId = ContainerGraph.StaticSwitchNodes.GetNodeRegisterIdx( m_referenceNodeId );
}
if( m_reference != null )
{
if( forceUpdate || m_reference.IsStaticSwitchDirty )
{
int count = m_inputPorts.Count;
for( int i = 0; i < count; i++ )
{
m_inputPorts[ i ].Name = m_reference.InputPorts[ i ].Name;
m_inputPorts[ i ].Visible = m_reference.InputPorts[ i ].Visible;
}
m_sizeIsDirty = true;
}
}
}
else
{
m_isStaticSwitchDirty = false;
}
}
public override void DrawGUIControls( DrawInfo drawInfo )
{
base.DrawGUIControls( drawInfo );
if( drawInfo.CurrentEventType != EventType.MouseDown || !m_createToggle )
return;
if( m_varRect.Contains( drawInfo.MousePosition ) )
{
m_editing = true;
}
else if( m_editing )
{
m_editing = false;
}
}
private int CurrentSelectedInput
{
get
{
return m_materialMode ? m_materialValue : m_defaultValue;
}
set
{
if( m_materialMode )
m_materialValue = value;
else
m_defaultValue = value;
}
}
public override void Draw( DrawInfo drawInfo )
{
base.Draw( drawInfo );
if( m_staticSwitchVarMode == StaticSwitchVariableMode.Reference )
return;
if( m_editing )
{
if( m_keywordModeType != KeywordModeType.KeywordEnum )
{
if( GUI.Button( m_varRect, GUIContent.none, UIUtils.GraphButton ) )
{
CurrentSelectedInput = CurrentSelectedInput == 1 ? 0 : 1;
PreviewIsDirty = true;
m_editing = false;
if( m_materialMode )
m_requireMaterialUpdate = true;
}
if( CurrentSelectedInput == 1 )
{
GUI.Label( m_varRect, m_checkContent, UIUtils.GraphButtonIcon );
}
}
else
{
EditorGUI.BeginChangeCheck();
CurrentSelectedInput = EditorGUIPopup( m_varRect, CurrentSelectedInput, m_keywordEnumList, UIUtils.GraphDropDown );
if( EditorGUI.EndChangeCheck() )
{
PreviewIsDirty = true;
m_editing = false;
if( m_materialMode )
m_requireMaterialUpdate = true;
}
}
}
}
public override void OnNodeRepaint( DrawInfo drawInfo )
{
base.OnNodeRepaint( drawInfo );
if( !m_isVisible )
return;
if( m_staticSwitchVarMode == StaticSwitchVariableMode.Reference )
{
GUI.Label( m_iconPos, string.Empty, UIUtils.GetCustomStyle( CustomStyle.SamplerTextureIcon ) );
return;
}
if( m_createToggle && ContainerGraph.LodLevel <= ParentGraph.NodeLOD.LOD2 )
{
if( !m_editing )
{
if( m_keywordModeType != KeywordModeType.KeywordEnum )
{
GUI.Label( m_varRect, GUIContent.none, UIUtils.GraphButton );
if( CurrentSelectedInput == 1 )
GUI.Label( m_varRect, m_checkContent, UIUtils.GraphButtonIcon );
}
else
{
GUI.Label( m_varRect, m_keywordEnumList[ CurrentSelectedInput ], UIUtils.GraphDropDown );
GUI.Label( m_imgRect, m_popContent, UIUtils.GraphButtonIcon );
}
}
}
}
private string OnOffStr
{
get
{
if( !m_lockKeyword )
return string.Empty;
StaticSwitch node = null;
switch( CurrentVarMode )
{
default:
case StaticSwitchVariableMode.Create:
case StaticSwitchVariableMode.Fetch:
node = this;
break;
case StaticSwitchVariableMode.Reference:
{
node = ( m_reference != null ) ? m_reference : this;
}
break;
}
if( !node.CreateToggle )
return string.Empty;
switch( node.KeywordModeTypeValue )
{
default:
case KeywordModeType.Toggle:
return "_ON";
case KeywordModeType.ToggleOff:
return "_OFF";
}
}
}
string GetStaticSwitchType()
{
string staticSwitchType = ( m_multiCompile == 1 ) ? "multi_compile" : "shader_feature";
#if UNITY_2019_1_OR_NEWER
if( m_isLocal )
staticSwitchType += "_local";
#endif
return staticSwitchType;
}
void RegisterPragmas( ref MasterNodeDataCollector dataCollector )
{
if( CurrentVarMode == StaticSwitchVariableMode.Create )
{
string staticSwitchType = GetStaticSwitchType();
if( m_keywordModeType == KeywordModeType.KeywordEnum )
{
if( m_multiCompile == 1 )
dataCollector.AddToPragmas( UniqueId, staticSwitchType + " " + GetKeywordEnumPragmaList() );
else if( m_multiCompile == 0 )
dataCollector.AddToPragmas( UniqueId, staticSwitchType + " " + GetKeywordEnumPragmaList() );
}
else
{
if( m_multiCompile == 1 )
dataCollector.AddToPragmas( UniqueId, staticSwitchType + " __ " + CurrentKeyword );
else if( m_multiCompile == 0 )
dataCollector.AddToPragmas( UniqueId, staticSwitchType + " " + CurrentKeyword );
}
}
}
protected override void RegisterProperty( ref MasterNodeDataCollector dataCollector )
{
if( m_staticSwitchVarMode == StaticSwitchVariableMode.Reference && m_reference != null )
{
m_reference.RegisterProperty( ref dataCollector );
m_reference.RegisterPragmas( ref dataCollector );
}
else
{
if( m_createToggle )
base.RegisterProperty( ref dataCollector );
RegisterPragmas( ref dataCollector );
}
}
public override string GenerateShaderForOutput( int outputId, ref MasterNodeDataCollector dataCollector, bool ignoreLocalvar )
{
if( m_outputPorts[ 0 ].IsLocalValue( dataCollector.PortCategory ) )
return m_outputPorts[ 0 ].LocalValue( dataCollector.PortCategory );
base.GenerateShaderForOutput( outputId, ref dataCollector, ignoreLocalvar );
StaticSwitch node = ( m_staticSwitchVarMode == StaticSwitchVariableMode.Reference && m_reference != null ) ? m_reference : this;
this.OrderIndex = node.RawOrderIndex;
this.OrderIndexOffset = node.OrderIndexOffset;
//if( m_keywordModeType == KeywordModeType.KeywordEnum )
//node.RegisterPragmas( ref dataCollector );
string outType = UIUtils.PrecisionWirePortToCgType( CurrentPrecisionType, m_outputPorts[ 0 ].DataType );
if( node.KeywordModeTypeValue == KeywordModeType.KeywordEnum )
{
string defaultKey = "\t" + outType + " staticSwitch" + OutputId + " = " + m_inputPorts[ node.DefaultValue ].GeneratePortInstructions( ref dataCollector ) + ";";
string[] allOutputs = new string[ node.KeywordEnumAmount ];
for( int i = 0; i < node.KeywordEnumAmount; i++ )
allOutputs[ i ] = m_inputPorts[ i ].GeneratePortInstructions( ref dataCollector );
for( int i = 0; i < node.KeywordEnumAmount; i++ )
{
string keyword = node.KeywordEnum( i );
if( i == 0 )
dataCollector.AddLocalVariable( UniqueId, "#if defined(" + keyword + ")", true );
else
dataCollector.AddLocalVariable( UniqueId, "#elif defined(" + keyword + ")", true );
if( node.DefaultValue == i )
dataCollector.AddLocalVariable( UniqueId, defaultKey, true );
else
dataCollector.AddLocalVariable( UniqueId, "\t" + outType + " staticSwitch" + OutputId + " = " + allOutputs[ i ] + ";", true );
}
dataCollector.AddLocalVariable( UniqueId, "#else", true );
dataCollector.AddLocalVariable( UniqueId, defaultKey, true );
dataCollector.AddLocalVariable( UniqueId, "#endif", true );
}
else
{
string falseCode = m_inputPorts[ 0 ].GeneratePortInstructions( ref dataCollector );
string trueCode = m_inputPorts[ 1 ].GeneratePortInstructions( ref dataCollector );
//if( node.CurrentVarMode == StaticSwitchVariableMode.Fetch )
dataCollector.AddLocalVariable( UniqueId, "#ifdef " + node.CurrentKeyword, true );
//else
// dataCollector.AddLocalVariable( UniqueId, "#ifdef " + node.PropertyName + OnOffStr, true );
dataCollector.AddLocalVariable( UniqueId, "\t" + outType + " staticSwitch" + OutputId + " = " + trueCode + ";", true );
dataCollector.AddLocalVariable( UniqueId, "#else", true );
dataCollector.AddLocalVariable( UniqueId, "\t" + outType + " staticSwitch" + OutputId + " = " + falseCode + ";", true );
dataCollector.AddLocalVariable( UniqueId, "#endif", true );
}
m_outputPorts[ 0 ].SetLocalValue( "staticSwitch" + OutputId, dataCollector.PortCategory );
return m_outputPorts[ 0 ].LocalValue( dataCollector.PortCategory );
}
public override void DrawTitle( Rect titlePos )
{
bool referenceMode = m_staticSwitchVarMode == StaticSwitchVariableMode.Reference && m_reference != null;
string subTitle = string.Empty;
string subTitleFormat = string.Empty;
if( referenceMode )
{
subTitle = m_reference.GetPropertyValStr();
subTitleFormat = Constants.SubTitleRefNameFormatStr;
}
else
{
subTitle = GetPropertyValStr();
subTitleFormat = Constants.SubTitleVarNameFormatStr;
}
SetAdditonalTitleTextOnCallback( subTitle, ( instance, newSubTitle ) => instance.AdditonalTitleContent.text = string.Format( subTitleFormat, newSubTitle ) );
if( !m_isEditing && ContainerGraph.LodLevel <= ParentGraph.NodeLOD.LOD3 )
{
GUI.Label( titlePos, StaticSwitchStr, UIUtils.GetCustomStyle( CustomStyle.NodeTitle ) );
}
}
public override void UpdateMaterial( Material mat )
{
base.UpdateMaterial( mat );
if( UIUtils.IsProperty( m_currentParameterType ) && !InsideShaderFunction )
{
if( m_keywordModeType == KeywordModeType.KeywordEnum )
{
for( int i = 0; i < m_keywordEnumAmount; i++ )
{
string key = KeywordEnum( i );
mat.DisableKeyword( key );
}
mat.EnableKeyword( KeywordEnum( m_materialValue ));
mat.SetFloat( m_propertyName, m_materialValue );
}
else
{
int final = m_materialValue;
if( m_keywordModeType == KeywordModeType.ToggleOff )
final = final == 1 ? 0 : 1;
mat.SetFloat( m_propertyName, m_materialValue );
if( final == 1 )
mat.EnableKeyword( GetPropertyValStr() );
else
mat.DisableKeyword( GetPropertyValStr() );
}
}
}
public override void SetMaterialMode( Material mat, bool fetchMaterialValues )
{
base.SetMaterialMode( mat, fetchMaterialValues );
if( fetchMaterialValues && m_materialMode && UIUtils.IsProperty( m_currentParameterType ) && mat.HasProperty( m_propertyName ) )
{
m_materialValue = mat.GetInt( m_propertyName );
}
}
public override void ForceUpdateFromMaterial( Material material )
{
if( UIUtils.IsProperty( m_currentParameterType ) && material.HasProperty( m_propertyName ) )
{
m_materialValue = material.GetInt( m_propertyName );
PreviewIsDirty = true;
}
}
public override void ReadFromString( ref string[] nodeParams )
{
base.ReadFromString( ref nodeParams );
m_multiCompile = Convert.ToInt32( GetCurrentParam( ref nodeParams ) );
if( UIUtils.CurrentShaderVersion() > 14403 )
{
m_defaultValue = Convert.ToInt32( GetCurrentParam( ref nodeParams ) );
if( UIUtils.CurrentShaderVersion() > 14101 )
{
m_materialValue = Convert.ToInt32( GetCurrentParam( ref nodeParams ) );
}
}
else
{
m_defaultValue = Convert.ToBoolean( GetCurrentParam( ref nodeParams ) ) ? 1 : 0;
if( UIUtils.CurrentShaderVersion() > 14101 )
{
m_materialValue = Convert.ToBoolean( GetCurrentParam( ref nodeParams ) ) ? 1 : 0;
}
}
if( UIUtils.CurrentShaderVersion() > 13104 )
{
m_createToggle = Convert.ToBoolean( GetCurrentParam( ref nodeParams ) );
m_currentKeyword = GetCurrentParam( ref nodeParams );
m_currentKeywordId = UIUtils.GetKeywordId( m_currentKeyword );
}
if( UIUtils.CurrentShaderVersion() > 14001 )
{
m_keywordModeType = (KeywordModeType)Enum.Parse( typeof( KeywordModeType ), GetCurrentParam( ref nodeParams ) );
}
if( UIUtils.CurrentShaderVersion() > 14403 )
{
KeywordEnumAmount = Convert.ToInt32( GetCurrentParam( ref nodeParams ) );
for( int i = 0; i < KeywordEnumAmount; i++ )
{
m_defaultKeywordNames[ i ] = GetCurrentParam( ref nodeParams );
}
UpdateLabels();
}
if( UIUtils.CurrentShaderVersion() > 16304 )
{
string currentVarMode = GetCurrentParam( ref nodeParams );
CurrentVarMode = (StaticSwitchVariableMode)Enum.Parse( typeof( StaticSwitchVariableMode ), currentVarMode );
if( CurrentVarMode == StaticSwitchVariableMode.Reference )
{
m_referenceNodeId = Convert.ToInt32( GetCurrentParam( ref nodeParams ) );
}
}
else
{
CurrentVarMode = (StaticSwitchVariableMode)m_variableMode;
}
if( CurrentVarMode == StaticSwitchVariableMode.Reference )
{
UIUtils.UnregisterPropertyNode( this );
}
else
{
if( m_createToggle )
UIUtils.RegisterPropertyNode( this );
else
UIUtils.UnregisterPropertyNode( this );
}
if( UIUtils.CurrentShaderVersion() > 16700 )
{
m_isLocal = Convert.ToBoolean( GetCurrentParam( ref nodeParams ) );
}
if( UIUtils.CurrentShaderVersion() > 18401 )
m_lockKeyword = Convert.ToBoolean( GetCurrentParam( ref nodeParams ) );
SetMaterialToggleRetrocompatibility();
if( !m_isNodeBeingCopied && CurrentVarMode != StaticSwitchVariableMode.Reference )
{
ContainerGraph.StaticSwitchNodes.UpdateDataOnNode( UniqueId, DataToArray );
}
}
void SetMaterialToggleRetrocompatibility()
{
if( UIUtils.CurrentShaderVersion() < 17108 )
{
if( !m_createToggle && m_staticSwitchVarMode == StaticSwitchVariableMode.Create )
{
if( m_keywordModeType != KeywordModeType.KeywordEnum )
{
m_propertyName = m_propertyName.ToUpper() + "_ON";
}
else
{
m_propertyName = m_propertyName.ToUpper();
for( int i = 0; i < m_keywordEnumList.Length; i++ )
{
m_keywordEnumList[ i ] = "_" + m_keywordEnumList[ i ].ToUpper();
}
}
m_autoGlobalName = false;
}
}
}
public override void ReadFromDeprecated( ref string[] nodeParams, Type oldType = null )
{
base.ReadFromDeprecated( ref nodeParams, oldType );
{
m_currentKeyword = GetCurrentParam( ref nodeParams );
m_currentKeywordId = UIUtils.GetKeywordId( m_currentKeyword );
m_createToggle = false;
m_keywordModeType = KeywordModeType.Toggle;
m_variableMode = VariableMode.Fetch;
CurrentVarMode = StaticSwitchVariableMode.Fetch;
}
}
public override void WriteToString( ref string nodeInfo, ref string connectionsInfo )
{
base.WriteToString( ref nodeInfo, ref connectionsInfo );
IOUtils.AddFieldValueToString( ref nodeInfo, m_multiCompile );
IOUtils.AddFieldValueToString( ref nodeInfo, m_defaultValue );
IOUtils.AddFieldValueToString( ref nodeInfo, m_materialValue );
IOUtils.AddFieldValueToString( ref nodeInfo, m_createToggle );
IOUtils.AddFieldValueToString( ref nodeInfo, m_currentKeyword );
IOUtils.AddFieldValueToString( ref nodeInfo, m_keywordModeType );
IOUtils.AddFieldValueToString( ref nodeInfo, KeywordEnumAmount );
for( int i = 0; i < KeywordEnumAmount; i++ )
{
IOUtils.AddFieldValueToString( ref nodeInfo, m_keywordEnumList[ i ] );
}
IOUtils.AddFieldValueToString( ref nodeInfo, CurrentVarMode );
if( CurrentVarMode == StaticSwitchVariableMode.Reference )
{
int referenceId = ( m_reference != null ) ? m_reference.UniqueId : -1;
IOUtils.AddFieldValueToString( ref nodeInfo, referenceId );
}
IOUtils.AddFieldValueToString( ref nodeInfo, m_isLocal );
IOUtils.AddFieldValueToString( ref nodeInfo, m_lockKeyword );
}
public override void RefreshExternalReferences()
{
base.RefreshExternalReferences();
CheckReferenceValues( true );
}
StaticSwitchVariableMode CurrentVarMode
{
get { return m_staticSwitchVarMode; }
set
{
if( m_staticSwitchVarMode != value )
{
if( value == StaticSwitchVariableMode.Reference )
{
ContainerGraph.StaticSwitchNodes.RemoveNode( this );
m_referenceArrayId = -1;
m_referenceNodeId = -1;
m_reference = null;
m_headerColorModifier = ReferenceHeaderColor;
}
else
{
m_headerColorModifier = Color.white;
ContainerGraph.StaticSwitchNodes.AddNode( this );
UpdateLabels();
}
}
m_staticSwitchVarMode = value;
}
}
public bool IsStaticSwitchDirty { get { return m_isStaticSwitchDirty; } }
public KeywordModeType KeywordModeTypeValue { get { return m_keywordModeType; } }
public int DefaultValue { get { return m_defaultValue; } }
public int MaterialValue { get { return m_materialValue; } }
//public string CurrentKeyword { get { return m_currentKeyword; } }
public string CurrentKeyword
{
get
{
return ( m_lockKeyword || string.IsNullOrEmpty( m_currentKeyword ) ? PropertyName + OnOffStr : m_currentKeyword );
}
}
public bool CreateToggle { get { return m_createToggle; } }
public int KeywordEnumAmount
{
get
{
return m_keywordEnumAmount;
}
set
{
m_keywordEnumAmount = value;
m_defaultValue = Mathf.Clamp( m_defaultValue, 0, m_keywordEnumAmount - 1 );
m_materialValue = Mathf.Clamp( m_defaultValue, 0, m_keywordEnumAmount - 1 );
}
}
}
}
| 412 | 0.96467 | 1 | 0.96467 | game-dev | MEDIA | 0.828847 | game-dev | 0.949645 | 1 | 0.949645 |
jackylee0424/Attention-Meter | 2,514 | flash-cs5/jp/maaash/ObjectDetection/ObjectDetectorEvent.as | //
// Project Marilena
// Object Detection in Actionscript3
// based on OpenCV (Open Computer Vision Library) Object Detection
//
// Copyright (C) 2008, Masakazu OHTSUKA (mash), all rights reserved.
// contact o.masakazu(at)gmail.com
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// 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 Intel Corporation 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.
//
package jp.maaash.ObjectDetection
{
import flash.events.Event;
import flash.geom.Rectangle;
public class ObjectDetectorEvent extends Event {
public static const DETECTION_COMPLETE :String = "ObjectDetectorEvent_DETECTION_COMPLETE";
public static const FACE_FOUND :String = "ObjectDetectorEvent_FACE_FOUND";
public static const HAARCASCADES_LOADING :String = "ObjectDetectorEvent_HAARCASCADES_LOADING";
public static const HAARCASCADES_LOAD_COMPLETE :String = "ObjectDetectorEvent_HAARCASCADES_LOAD_COMPLETE";
public static const DETECTION_START :String = "ObjectDetectorEvent_DETECTION_START";
public var rect :Rectangle;
public var rects :Array;
public function ObjectDetectorEvent( t :String ) {
super(t);
}
public override function clone():Event {
var ev :ObjectDetectorEvent = new ObjectDetectorEvent( type );
ev.rect = rect;
ev.rects = rects;
return ev;
}
}
}
| 412 | 0.693448 | 1 | 0.693448 | game-dev | MEDIA | 0.740678 | game-dev | 0.840186 | 1 | 0.840186 |
ismail0234/Subnautica-Below-Zero-Multiplayer | 7,149 | Subnautica.Client/Synchronizations/InitialSync/BaseProcessor.cs | namespace Subnautica.Client.Synchronizations.InitialSync
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Subnautica.API.Extensions;
using Subnautica.API.Features;
using Subnautica.Client.MonoBehaviours.Construction;
using Subnautica.Network.Models.Storage.World.Childrens;
using Subnautica.Network.Structures;
using UWE;
public class BaseProcessor
{
/**
*
* Üs verilerini ayarlar.
*
* @author Ismail <ismaiil_0234@hotmail.com>
*
*/
public static IEnumerator InitialBases()
{
yield return CoroutineUtils.waitForNextFrame;
try
{
if (Network.Session.Current.Bases != null)
{
foreach (var item in Network.Session.Current.Bases)
{
if (item.BaseColor != null)
{
SetBaseColor(item.BaseId, item.Name, item.BaseColor, item.StripeColor1, item.StripeColor2, item.NameColor);
}
var baseComponent = Network.Identifier.GetComponentByGameObject<global::Base>(item.BaseId);
if (baseComponent)
{
SetDisablePowers(baseComponent, item.DisablePowers);
SetMinimapPositions(baseComponent, item.MinimapPositions);
SetLeakers(baseComponent, item.Leakers);
SetCellWaterLevel(baseComponent, item.CellWaterLevels);
}
}
}
}
catch (Exception e)
{
Log.Error(string.Format("[InitialBases] Exception: {0}", e));
}
}
/**
*
* Üs rengini değiştirir.
*
* @author Ismail <ismaiil_0234@hotmail.com>
*
*/
private static void SetBaseColor(string baseId, string name, ZeroColor baseColor, ZeroColor stripeColor1, ZeroColor stripeColor2, ZeroColor nameColor)
{
var customizeable = Network.Identifier.GetComponentByGameObject<ICustomizeable>(baseId);
if (customizeable != null)
{
customizeable.SetName(name);
customizeable.SetColor(0, uGUI_ColorPicker.HSBFromColor(baseColor.ToColor()), baseColor.ToColor());
customizeable.SetColor(1, uGUI_ColorPicker.HSBFromColor(stripeColor1.ToColor()), stripeColor1.ToColor());
customizeable.SetColor(2, uGUI_ColorPicker.HSBFromColor(stripeColor2.ToColor()), stripeColor2.ToColor());
customizeable.SetColor(3, uGUI_ColorPicker.HSBFromColor(nameColor.ToColor()), nameColor.ToColor());
}
}
/**
*
* Üs harita konumlarını değiştirir.
*
* @author Ismail <ismaiil_0234@hotmail.com>
*
*/
private static void SetMinimapPositions(global::Base baseComponent, Dictionary<string, ZeroVector3> minimapPositions)
{
foreach (var controlRoom in baseComponent.GetComponentsInChildren<global::BaseControlRoom>())
{
controlRoom.mapDirty = true;
if (minimapPositions.Count > 0)
{
var uniqueId = Network.Identifier.GetIdentityId(controlRoom.gameObject, false);
if (uniqueId.IsNotNull())
{
var minimap = minimapPositions.FirstOrDefault(q => q.Key == uniqueId);
if (minimap.Key == null)
{
continue;
}
controlRoom.minimapBase.transform.localPosition = minimap.Value.ToVector3();
}
}
}
}
/**
*
* Üs kapalı ışıkları ayarlar.
*
* @author Ismail <ismaiil_0234@hotmail.com>
*
*/
private static void SetDisablePowers(global::Base baseComponent, HashSet<ZeroInt3> disablePowers)
{
for (int cellIndex = 0; cellIndex < baseComponent.cellLighting.Length; cellIndex++)
{
if (baseComponent.cellLighting[cellIndex] && !baseComponent.cellLighting[cellIndex].cellPowered)
{
baseComponent.SetPowered(baseComponent.GetCellPointFromIndex(cellIndex), true);
}
}
foreach (var cell in disablePowers)
{
var cellIndex = baseComponent.GetCellIndex(cell.ToInt3());
if (baseComponent.cellLighting[cellIndex])
{
baseComponent.SetPowered(cell.ToInt3(), false);
}
}
}
/**
*
* Üs'deki sızıntıları senkronlar.
*
* @author Ismail <ismaiil_0234@hotmail.com>
*
*/
private static void SetLeakers(global::Base baseComponent, HashSet<Leaker> leakers)
{
if (leakers.Count > 0)
{
foreach (var leaker in leakers)
{
var baseDeconstructable = Network.Identifier.GetComponentByGameObject<global::BaseDeconstructable>(leaker.UniqueId);
if (baseDeconstructable == null)
{
continue;
}
var leakable = baseDeconstructable.GetComponentInParent<global::Leakable>();
if (leakable == null)
{
continue;
}
foreach (var point in leaker.Points)
{
var leakPoint = leakable.unusedLeakPoints.FirstOrDefault(q => q.transform.position.ToZeroVector3() == point);
if (leakPoint)
{
leakPoint.pointActive = true;
leakable.leakingLeakPoints.Add(leakPoint);
leakable.unusedLeakPoints.Remove(leakPoint);
}
}
}
}
}
/**
*
* Üs'deki su seviyelerini senkronlar.
*
* @author Ismail <ismaiil_0234@hotmail.com>
*
*/
private static void SetCellWaterLevel(global::Base baseComponent, Dictionary<ushort, float> cellWaterLevels)
{
if (cellWaterLevels.Count > 0)
{
var baseHullStrength = baseComponent.gameObject.EnsureComponent<BuilderBaseHullStrength>();
if (baseHullStrength)
{
foreach (var waterLevel in cellWaterLevels)
{
baseHullStrength.SetCellWaterLevel(waterLevel.Key, waterLevel.Value);
}
}
}
}
}
}
| 412 | 0.83163 | 1 | 0.83163 | game-dev | MEDIA | 0.878557 | game-dev | 0.967909 | 1 | 0.967909 |
tuProlog/2p-kt | 2,969 | solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/impl/AbstractTimedState.kt | package it.unibo.tuprolog.solve.streams.solver.fsm.impl
import it.unibo.tuprolog.solve.ExecutionContext
import it.unibo.tuprolog.solve.TimeDuration
import it.unibo.tuprolog.solve.TimeInstant
import it.unibo.tuprolog.solve.currentTimeInstant
import it.unibo.tuprolog.solve.exception.TimeOutException
import it.unibo.tuprolog.solve.primitive.Solve
import it.unibo.tuprolog.solve.primitive.Solve.Response
import it.unibo.tuprolog.solve.streams.solver.fsm.AbstractState
import it.unibo.tuprolog.solve.streams.solver.fsm.IntermediateState
import it.unibo.tuprolog.solve.streams.solver.fsm.State
import it.unibo.tuprolog.solve.streams.solver.fsm.TimedState
/**
* Base class for all States that should have a timed behaviour
*
* @author Enrico
*/
internal abstract class AbstractTimedState(
/** The [Solve.Request] that guides the State behaviour towards [Response]s */
override val solve: Solve.Request<ExecutionContext>,
) : AbstractState(solve),
IntermediateState,
TimedState {
/** Internal cached currentTime at first behave() call, enabling identical re-execution of that state */
private val stateCurrentTime by lazy { currentTimeInstant() }
override fun behave(): Sequence<State> =
when {
// optimized without check, when maxDuration is infinite
solve.maxDuration == TimeDuration.MAX_VALUE -> behaveTimed()
timeIsOver(stateCurrentTime - solve.startTime, solve.maxDuration) ->
sequenceOf(statEndHaltTimeout())
else -> behaveTimed()
}
/** Called only if executionTimeout has not been reached yet, and computation should go on */
protected abstract fun behaveTimed(): Sequence<State>
/** A function to check if currently the timeout has expired and return the halt state if yes,
* the provided [toYieldState] otherwise*/
protected fun IntermediateState.ifTimeIsNotOver(toYieldState: State): State =
when {
timeIsOver(currentTimeInstant() - solve.startTime, solve.maxDuration) ->
statEndHaltTimeout()
else -> toYieldState
}
override fun getCurrentTime(): TimeInstant = stateCurrentTime
/** A function to check if time for execution has ended */
private fun timeIsOver(
currentDuration: TimeDuration,
maxDuration: TimeDuration,
) = currentDuration >= maxDuration
override fun toString(): String = "${this::class} with $solve"
companion object {
/** An utility function to create the end Halt state to be returned upon timeout expiry */
private fun IntermediateState.statEndHaltTimeout(): State =
stateEndHalt(
TimeOutException(
"Given time for `${solve.query}` computation (${solve.maxDuration}) wasn't enough for completion",
context = solve.context,
exceededDuration = solve.maxDuration,
),
)
}
}
| 412 | 0.909362 | 1 | 0.909362 | game-dev | MEDIA | 0.255911 | game-dev | 0.983472 | 1 | 0.983472 |
Goob-Station/Goob-Station | 1,739 | Content.Goobstation.Shared/Weapons/Recoil/GunRecoilSystem.cs | // SPDX-FileCopyrightText: 2025 Aviu00 <aviu00@protonmail.com>
// SPDX-FileCopyrightText: 2025 GoobBot <uristmchands@proton.me>
//
// SPDX-License-Identifier: AGPL-3.0-or-later
using Content.Shared.Stunnable;
using Content.Shared.Throwing;
using Content.Shared.Weapons.Ranged.Systems;
using Robust.Shared.Physics.Components;
namespace Content.Goobstation.Shared.Weapons.Recoil;
public sealed class GunRecoilSystem : EntitySystem
{
[Dependency] private readonly ThrowingSystem _throwing = default!;
[Dependency] private readonly SharedStunSystem _stun = default!;
[Dependency] private readonly SharedTransformSystem _transform = default!;
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<GunRecoilComponent, GunShotEvent>(OnShoot);
}
private void OnShoot(Entity<GunRecoilComponent> ent, ref GunShotEvent args)
{
var dir = -_transform.GetWorldRotation(args.User).ToWorldVec();
var range = ent.Comp.BaseThrowRange;
var speed = ent.Comp.BaseThrowSpeed;
var knockdownTime = ent.Comp.BaseKnockdownTime;
if (ent.Comp.AffectedByMass && TryComp(args.User, out PhysicsComponent? physics))
{
var multiplier = physics.InvMass * ent.Comp.MassMultiplier;
range *= multiplier;
speed *= multiplier;
knockdownTime *= multiplier;
}
if (range > 0f && speed > 0f)
_throwing.TryThrow(args.User, dir * range, speed, animated: false);
if (knockdownTime <= 0f)
return;
_stun.TryKnockdown(args.User,
TimeSpan.FromSeconds(knockdownTime),
ent.Comp.RefreshKnockdown,
ent.Comp.Behavior);
}
}
| 412 | 0.880851 | 1 | 0.880851 | game-dev | MEDIA | 0.979081 | game-dev | 0.935669 | 1 | 0.935669 |
ClassiCube/MCGalaxy | 7,768 | MCGalaxy/Modules/Games/LavaSurvival/LSGame.cs | /*
Copyright 2011 MCForge
Dual-licensed under the Educational Community License, Version 2.0 and
the GNU General Public License, Version 3 (the "Licenses"); you may
not use this file except in compliance with the Licenses. You may
obtain a copy of the Licenses at
https://opensource.org/license/ecl-2-0/
https://www.gnu.org/licenses/gpl-3.0.html
Unless required by applicable law or agreed to in writing,
software distributed under the Licenses are distributed on an "AS IS"
BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
or implied. See the Licenses for the specific language governing
permissions and limitations under the Licenses.
*/
using System;
using System.Collections.Generic;
using MCGalaxy.Games;
using MCGalaxy.Maths;
using BlockID = System.UInt16;
namespace MCGalaxy.Modules.Games.LS
{
public sealed class LSData
{
public int TimesDied, SpongesLeft, WaterLeft, DoorsLeft;
}
public enum LSFloodMode
{
Calm, Disturbed, Furious, Wild, Extreme
}
public partial class LSGame : RoundsGame
{
LSMapConfig cfg = new LSMapConfig();
public LSConfig Config = new LSConfig();
public override string GameName { get { return "Lava survival"; } }
public override RoundsGameConfig GetConfig() { return Config; }
protected override string WelcomeMessage {
get { return "&cLava Survival &Sis running! Type &T/LS go &Sto join"; }
}
bool flooded, fastMode, waterMode, layerMode, floodUp;
BlockID floodBlock;
LSFloodMode floodMode;
int curLayer, spreadDelay;
int roundTotalSecs, floodDelaySecs, layerIntervalSecs;
byte destroyDelay, dissipateChance, burnChance;
static bool hooked;
public static LSGame Instance = new LSGame();
public LSGame() { Picker = new SimpleLevelPicker(); }
public static LSData Get(Player p) {
object data;
if (!p.Extras.TryGet("MCG_LS_DATA", out data)) {
data = new LSData();
p.Extras["MCG_LS_DATA"] = data;
}
return (LSData)data;
}
public override void UpdateMapConfig() {
LSMapConfig cfg = new LSMapConfig();
cfg.SetDefaults(Map);
cfg.Load(Map.name);
this.cfg = cfg;
Random rnd = new Random();
waterMode = rnd.Next(1, 101) <= cfg.WaterChance;
layerMode = rnd.Next(1, 101) <= cfg.LayerChance;
fastMode = rnd.Next(1, 101) <= cfg.FastChance && !waterMode;
floodUp = rnd.Next(1, 101) <= cfg.FloodUpChance;
if (waterMode) {
floodBlock = Block.Deadly_ActiveWater;
} else {
floodBlock = Block.Deadly_ActiveLava;
}
spreadDelay = fastMode ? 0 : 4;
roundTotalSecs = (int)Config.GetRoundTime(cfg).TotalSeconds;
floodDelaySecs = (int)Config.GetFloodTime(cfg).TotalSeconds;
layerIntervalSecs = (int)Config.GetLayerInterval(cfg).TotalSeconds;
SetFloodMode(RandomFloodMode(rnd));
}
LSFloodMode RandomFloodMode(Random rnd) {
int likelihood = rnd.Next(1, 101);
int threshold = 0;
int[] chances = { Config.CalmChance, Config.DisturbedChance,
Config.WildChance, Config.FuriousChance, Config.ExtremeChance
};
for (int i = 0; i < chances.Length; i++)
{
threshold += chances[i];
if (likelihood <= threshold) return (LSFloodMode)i;
}
return LSFloodMode.Calm;
}
public void SetFloodMode(LSFloodMode mode) {
floodMode = mode;
destroyDelay = GetDestroyDelay();
dissipateChance = GetDissipateChance();
burnChance = GetBurnChance();
if (RoundInProgress) UpdatePhysicsLevel();
}
void UpdatePhysicsLevel() {
Map.SetPhysics(floodMode > LSFloodMode.Calm ? 2 : 1);
}
protected override List<Player> GetPlayers() {
return Map.getPlayers();
}
protected override void StartGame() {
ResetPlayerDeaths();
if (hooked) return;
hooked = true;
//HookStats();
HookCommands();
HookItems();
}
protected override void EndGame() {
flooded = false;
ResetPlayerDeaths();
UpdateBlockHandlers();
hooked = false;
//UnhookStats();
UnhookCommands();
UnhookItems();
}
public override bool HandlesBlockchange(Player p, ushort x, ushort y, ushort z) {
if (!IsPlayerDead(p)) return false;
p.Message("You are out of the round, and cannot build.");
p.RevertBlock(x, y, z);
return true;
}
void ResetPlayerDeaths() {
Player[] players = PlayerInfo.Online.Items;
foreach (Player p in players)
{
if (p.level != Map) continue;
AddLives(p, Get(p).TimesDied, true);
}
}
public override void PlayerJoinedGame(Player p) {
bool announce = false;
HandleJoinedLevel(p, Map, Map, ref announce);
}
static void ResetRoundState(Player p, LSData data) {
data.SpongesLeft = 10;
data.WaterLeft = 30;
data.DoorsLeft = 0;
}
bool InSafeZone(ushort x, ushort y, ushort z) {
return x >= cfg.SafeZoneMin.X && x <= cfg.SafeZoneMax.X && y >= cfg.SafeZoneMin.Y
&& y <= cfg.SafeZoneMax.Y && z >= cfg.SafeZoneMin.Z && z <= cfg.SafeZoneMax.Z;
}
Vec3U16 CurrentLayerPos() {
Vec3U16 pos = cfg.LayerPos;
pos.Y = (ushort)(pos.Y + ((cfg.LayerHeight * curLayer) - 1));
return pos;
}
string FloodBlockName() {
return waterMode ? "water" : "lava";
}
public bool IsPlayerDead(Player p) {
return Config.MaxLives > 0 && Get(p).TimesDied >= Config.MaxLives;
}
public string DescribeLives(Player p) {
if (Config.MaxLives <= 0) return "have &ainfinite &Slives";
int lives = Config.MaxLives - Get(p).TimesDied;
return lives <= 0 ? "are &4dead" : "have &a" + lives + " &Slives left";
}
public void AddLives(Player p, int amount, bool silent) {
LSData data = Get(p);
if (Config.MaxLives <= 0) { data.TimesDied = 0; return; }
data.TimesDied -= amount;
UpdateStatus1(p);
if (silent) return;
p.Message("You " + DescribeLives(p));
if (!IsPlayerDead(p)) return;
Chat.MessageFromLevel(p, "λNICK &4ran out of lives, and is out of the round!");
p.Message("&4You can still watch, but you cannot build.");
// TODO: Buy life message
}
protected override string FormatStatus1(Player p) {
string money = "&a" + p.money + " &S" + Server.Config.Currency;
return money + ", you " + DescribeLives(p);
}
}
}
| 412 | 0.934614 | 1 | 0.934614 | game-dev | MEDIA | 0.924709 | game-dev | 0.963791 | 1 | 0.963791 |
tukkek/javelin | 5,804 | javelin/controller/action/Target.java | package javelin.controller.action;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.ConcurrentModificationException;
import java.util.List;
import javelin.Javelin;
import javelin.controller.exception.RepeatTurn;
import javelin.controller.old.Game;
import javelin.controller.old.Game.Delay;
import javelin.controller.walker.Walker;
import javelin.model.BattleMap;
import javelin.model.condition.Charging;
import javelin.model.state.BattleState;
import javelin.model.state.BattleState.Vision;
import javelin.model.unit.Combatant;
import javelin.view.screen.BattleScreen;
import javelin.view.screen.InfoScreen;
import javelin.view.screen.StatisticsScreen;
import tyrant.mikera.engine.Thing;
/**
* Base class for all actions involving selecting an unit as target.
*
* @author alex
*/
public abstract class Target extends Action {
/**
* Pressing this key confirms the target selection, usually same as the
* action key.
*
* @see Action#keys
*/
protected char confirmkey;
/** Constructor. */
public Target(String string) {
super(string);
}
/** Constructor. */
public Target(String string, String[] strings) {
super(string, strings);
}
/** Constructor. */
public Target(String name, String key) {
super(name, key);
}
/**
* @return Minimum number the active combatant has to roll on a d20 to hit
* the target.
*/
protected abstract int calculatehitdc(final Combatant target,
Combatant active, BattleState state);
/** Called once a target is confirmed. */
protected abstract void attack(Combatant active, Combatant target,
BattleState s, final BattleMap map);
@Override
public boolean perform(final Combatant c, BattleMap map, Thing thing) {
final Thing hero = Game.hero();
checkhero(hero);
final BattleState state = map.getState();
if (checkengaged(state, state.clone(hero.combatant))) {
Game.message("Disengage first!", null, Delay.WAIT);
throw new RepeatTurn();
}
final Combatant combatant = state.clone(Game.hero().combatant);
final List<Combatant> targets =
state.getAllTargets(combatant, state.getCombatants());
filtertargets(combatant, targets, state);
if (targets.isEmpty()) {
Game.message("No valid targets.", null, Delay.WAIT);
throw new RepeatTurn();
}
Collections.sort(targets, new Comparator<Combatant>() {
@Override
public int compare(final Combatant o1, final Combatant o2) {
int priority1 = prioritize(c, state, o1);
int priority2 = prioritize(c, state, o2);
if (priority1 == priority2) {
return new Long(Math.round(Walker.distance(o1, c) * 10
- Walker.distance(o2, c) * 10)).intValue();
}
return priority1 > priority2 ? -1 : 1;
}
});
selecttarget(map, combatant, targets, state);
return true;
}
/**
* TODO turn into dynamic instead?
*/
public int prioritize(final Combatant c, final BattleState state,
final Combatant target) {
int priority = -target.surprise();
if (state.hasLineOfSight(c, target) == Vision.COVERED) {
priority -= 4;
}
/* TODO take into account relevant feats */
if (state.isengaged(target)) {
priority -= 4;
}
if (target.hascondition(Charging.class) != null) {
priority += 2;
}
return priority;
}
private void selecttarget(BattleMap map, final Combatant combatant,
final List<Combatant> targets, BattleState state) {
int targeti = 0;
lockTarget(targets.get(0), map, combatant, state);
while (true) {
Game.redraw();
final Character key = InfoScreen.feedback();
if (Action.MOVE_W.isPressed(key)) {
targeti -= 1;
} else if (Action.MOVE_E.isPressed(key)) {
targeti += 1;
} else if (key == '\n' || key == confirmkey) {
Game.messagepanel.clear();
attack(combatant, targets.get(targeti), state, map);
break;
} else if (key == 'v') {
new StatisticsScreen(targets.get(targeti));
} else {
Game.messagepanel.clear();
Game.instance().hero = combatant.visual;
throw new RepeatTurn();
}
final int max = targets.size() - 1;
if (targeti > max) {
targeti = 0;
} else if (targeti < 0) {
targeti = max;
}
lockTarget(targets.get(targeti), map, combatant, state);
}
}
/**
* By default uses {@link BattleState#isengaged(Combatant)}
*
* @return <code>true</code> if the active unit is currently engaded and
* should not be allowed to continue targetting.
*/
protected boolean checkengaged(final BattleState state, Combatant c) {
return state.isengaged(c);
}
/**
* Does nothing by default.
*
* @param hero
* Active unit.
* @throws RepeatTurn
*/
protected void checkhero(final Thing hero) {
}
/**
* By default only allows targeting enemies that are in line-of-sight.
*
* @param targets
* Remove invalid targets from this list. Beware of
* {@link ConcurrentModificationException}.
*/
protected void filtertargets(Combatant active, List<Combatant> targets,
BattleState s) {
for (Combatant target : new ArrayList<Combatant>(targets)) {
if (target.isAlly(active, s)
|| s.hasLineOfSight(active, target) == Vision.BLOCKED) {
targets.remove(target);
}
}
}
private void lockTarget(final Combatant target, BattleMap map,
Combatant active, BattleState state) {
Game.instance().hero = target.visual;
Game.messagepanel.clear();
Game.message(
"Use ← and → to select target, ENTER or " + confirmkey
+ " to confirm, v to view target's sheet, q to quit.\n",
null, Delay.NONE);
Game.message(target + " (" + target.getStatus() + ", "
+ Javelin.translatetochance(
calculatehitdc(target, active, state))
+ " to hit)", null, Delay.NONE);
BattleScreen.active.centerscreen(target.location[0],
target.location[1]);
}
} | 412 | 0.959206 | 1 | 0.959206 | game-dev | MEDIA | 0.926232 | game-dev | 0.994898 | 1 | 0.994898 |
twhl-community/halflife-unified-sdk | 3,968 | src/game/server/entities/CBaseButton.h | /***
*
* Copyright (c) 1996-2001, Valve LLC. All rights reserved.
*
* This product contains software technology licensed from Id
* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc.
* All Rights Reserved.
*
* Use, distribution, and modification of this source code and/or resulting
* object code is restricted to non-commercial enhancements to products from
* Valve LLC. All other use, distribution, or modification is prohibited
* without written permission from Valve LLC.
*
****/
#pragma once
#include "CBaseToggle.h"
/**
* @brief sounds that doors and buttons make when locked/unlocked
*/
struct locksound_t
{
string_t sLockedSound; //!< sound a door makes when it's locked
string_t sLockedSentence; //!< sentence group played when door is locked
string_t sUnlockedSound; //!< sound a door makes when it's unlocked
string_t sUnlockedSentence; //!< sentence group played when door is unlocked
int iLockedSentence; //!< which sentence in sentence group to play next
int iUnlockedSentence; //!< which sentence in sentence group to play next
float flwaitSound; //!< time delay between playing consecutive 'locked/unlocked' sounds
float flwaitSentence; //!< time delay between playing consecutive sentences
byte bEOFLocked; //!< true if hit end of list of locked sentences
byte bEOFUnlocked; //!< true if hit end of list of unlocked sentences
};
/**
* @brief play door or button locked or unlocked sounds.
* @details pass in pointer to valid locksound struct.
* if flocked is true, play 'door is locked' sound, otherwise play 'door is unlocked' sound
* NOTE: this routine is shared by doors and buttons
*/
void PlayLockSounds(CBaseEntity* entity, locksound_t* pls, bool flocked, bool fbutton);
/**
* @brief Generic Button
* @details When a button is touched, it moves some distance in the direction of its angle,
* triggers all of its targets, waits some time, then returns to its original position where it can be triggered again.
*/
class CBaseButton : public CBaseToggle
{
DECLARE_CLASS(CBaseButton, CBaseToggle);
DECLARE_DATAMAP();
public:
void Spawn() override;
void Precache() override;
bool KeyValue(KeyValueData* pkvd) override;
/**
* @brief Starts the button moving "in/up".
*/
void ButtonActivate();
/**
* @brief Touching a button simply "activates" it.
*/
void ButtonTouch(CBaseEntity* pOther);
/**
* @brief Makes flagged buttons spark when turned off
*/
void ButtonSpark();
/**
* @brief Button has reached the "in/up" position. Activate its "targets", and pause before "popping out".
*/
void TriggerAndWait();
/**
* @brief Starts the button moving "out/down".
*/
void ButtonReturn();
/**
* @brief Button has returned to start state. Quiesce it.
*/
void ButtonBackHome();
void ButtonUse(CBaseEntity* pActivator, CBaseEntity* pCaller, USE_TYPE useType, float value);
bool TakeDamage(CBaseEntity* inflictor, CBaseEntity* attacker, float flDamage, int bitsDamageType) override;
enum BUTTON_CODE
{
BUTTON_NOTHING,
BUTTON_ACTIVATE,
BUTTON_RETURN
};
BUTTON_CODE ButtonResponseToTouch();
// Buttons that don't take damage can be IMPULSE used
int ObjectCaps() override { return (CBaseToggle::ObjectCaps() & ~FCAP_ACROSS_TRANSITION) | (pev->takedamage ? 0 : FCAP_IMPULSE_USE); }
bool m_fStayPushed; // button stays pushed in until touched again?
bool m_fRotating; // a rotating button? default is a sliding button.
string_t m_strChangeTarget; // if this field is not null, this is an index into the engine string array.
// when this button is touched, it's target entity's TARGET field will be set
// to the button's ChangeTarget. This allows you to make a func_train switch paths, etc.
locksound_t m_ls; // door lock sounds
string_t m_LockedSound; // ordinals from entity selection
string_t m_LockedSentence;
string_t m_UnlockedSound;
string_t m_UnlockedSentence;
string_t m_sounds;
};
| 412 | 0.859743 | 1 | 0.859743 | game-dev | MEDIA | 0.659975 | game-dev | 0.597438 | 1 | 0.597438 |
DarkStorm652/DarkBot | 1,327 | src/main/protocols/org/darkstorm/darkbot/minecraftbot/protocol/v5x/play/server/PacketS2D_OpenWindow.java | package org.darkstorm.darkbot.minecraftbot.protocol.v5x.play.server;
import java.io.*;
import org.darkstorm.darkbot.minecraftbot.protocol.*;
import org.darkstorm.darkbot.minecraftbot.protocol.ProtocolX.State;
import org.darkstorm.darkbot.minecraftbot.world.item.InventoryType;
public class PacketS2D_OpenWindow extends AbstractPacketX implements ReadablePacket {
private int windowId;
private InventoryType inventoryType;
private String windowTitle;
private int slotCount;
private boolean useWindowTitle;
private int entityId;
public PacketS2D_OpenWindow() {
super(0x2D, State.PLAY, Direction.DOWNSTREAM);
}
@Override
public void readData(DataInputStream in) throws IOException {
windowId = in.readByte() & 255;
inventoryType = InventoryType.byId(in.readByte() & 255);
windowTitle = readString(in);
slotCount = in.readByte() & 255;
useWindowTitle = in.readBoolean();
if(inventoryType == InventoryType.ANIMAL_CHEST)
entityId = in.readInt();
}
public int getWindowId() {
return windowId;
}
public InventoryType getInventoryType() {
return inventoryType;
}
public String getWindowTitle() {
return windowTitle;
}
public int getSlotCount() {
return slotCount;
}
public boolean useWindowTitle() {
return useWindowTitle;
}
public int getEntityId() {
return entityId;
}
}
| 412 | 0.864048 | 1 | 0.864048 | game-dev | MEDIA | 0.748454 | game-dev | 0.842461 | 1 | 0.842461 |
counter185/voidsprite | 5,485 | external_liblcf/generated/lcf/rpg/actor.h | /* !!!! GENERATED FILE - DO NOT EDIT !!!!
* --------------------------------------
*
* This file is part of liblcf. Copyright (c) liblcf authors.
* https://github.com/EasyRPG/liblcf - https://easyrpg.org
*
* liblcf is Free/Libre Open Source Software, released under the MIT License.
* For the full copyright and license information, please view the COPYING
* file that was distributed with this source code.
*/
#ifndef LCF_RPG_ACTOR_H
#define LCF_RPG_ACTOR_H
// Headers
#include <stdint.h>
#include <vector>
#include "lcf/dbbitarray.h"
#include "lcf/dbstring.h"
#include "lcf/rpg/equipment.h"
#include "lcf/rpg/learning.h"
#include "lcf/rpg/parameters.h"
#include "lcf/context.h"
#include <ostream>
#include <type_traits>
/**
* rpg::Actor class.
*/
namespace lcf {
namespace rpg {
class Actor {
public:
void Setup(bool is2k3);
int ID = 0;
DBString name;
DBString title;
DBString character_name;
int32_t character_index = 0;
bool transparent = false;
int32_t initial_level = 1;
int32_t final_level = -1;
bool critical_hit = true;
int32_t critical_hit_chance = 30;
DBString face_name;
int32_t face_index = 0;
bool two_weapon = false;
bool lock_equipment = false;
bool auto_battle = false;
bool super_guard = false;
Parameters parameters;
int32_t exp_base = -1;
int32_t exp_inflation = -1;
int32_t exp_correction = 0;
Equipment initial_equipment;
int32_t unarmed_animation = 1;
int32_t class_id = 0;
int32_t battle_x = 220;
int32_t battle_y = 120;
int32_t battler_animation = 1;
std::vector<Learning> skills;
bool rename_skill = false;
DBString skill_name;
std::vector<uint8_t> state_ranks;
std::vector<uint8_t> attribute_ranks;
std::vector<int32_t> battle_commands;
int32_t easyrpg_actorai = -1;
bool easyrpg_prevent_critical = false;
bool easyrpg_raise_evasion = false;
bool easyrpg_immune_to_attribute_downshifts = false;
bool easyrpg_ignore_evasion = false;
int32_t easyrpg_unarmed_hit = -1;
DBBitArray easyrpg_unarmed_state_set;
int32_t easyrpg_unarmed_state_chance = 0;
DBBitArray easyrpg_unarmed_attribute_set;
bool easyrpg_dual_attack = false;
bool easyrpg_attack_all = false;
};
inline bool operator==(const Actor& l, const Actor& r) {
return l.name == r.name
&& l.title == r.title
&& l.character_name == r.character_name
&& l.character_index == r.character_index
&& l.transparent == r.transparent
&& l.initial_level == r.initial_level
&& l.final_level == r.final_level
&& l.critical_hit == r.critical_hit
&& l.critical_hit_chance == r.critical_hit_chance
&& l.face_name == r.face_name
&& l.face_index == r.face_index
&& l.two_weapon == r.two_weapon
&& l.lock_equipment == r.lock_equipment
&& l.auto_battle == r.auto_battle
&& l.super_guard == r.super_guard
&& l.parameters == r.parameters
&& l.exp_base == r.exp_base
&& l.exp_inflation == r.exp_inflation
&& l.exp_correction == r.exp_correction
&& l.initial_equipment == r.initial_equipment
&& l.unarmed_animation == r.unarmed_animation
&& l.class_id == r.class_id
&& l.battle_x == r.battle_x
&& l.battle_y == r.battle_y
&& l.battler_animation == r.battler_animation
&& l.skills == r.skills
&& l.rename_skill == r.rename_skill
&& l.skill_name == r.skill_name
&& l.state_ranks == r.state_ranks
&& l.attribute_ranks == r.attribute_ranks
&& l.battle_commands == r.battle_commands
&& l.easyrpg_actorai == r.easyrpg_actorai
&& l.easyrpg_prevent_critical == r.easyrpg_prevent_critical
&& l.easyrpg_raise_evasion == r.easyrpg_raise_evasion
&& l.easyrpg_immune_to_attribute_downshifts == r.easyrpg_immune_to_attribute_downshifts
&& l.easyrpg_ignore_evasion == r.easyrpg_ignore_evasion
&& l.easyrpg_unarmed_hit == r.easyrpg_unarmed_hit
&& l.easyrpg_unarmed_state_set == r.easyrpg_unarmed_state_set
&& l.easyrpg_unarmed_state_chance == r.easyrpg_unarmed_state_chance
&& l.easyrpg_unarmed_attribute_set == r.easyrpg_unarmed_attribute_set
&& l.easyrpg_dual_attack == r.easyrpg_dual_attack
&& l.easyrpg_attack_all == r.easyrpg_attack_all;
}
inline bool operator!=(const Actor& l, const Actor& r) {
return !(l == r);
}
std::ostream& operator<<(std::ostream& os, const Actor& obj);
template <typename F, typename ParentCtx = Context<void,void>>
void ForEachString(Actor& obj, const F& f, const ParentCtx* parent_ctx = nullptr) {
const auto ctx1 = Context<Actor, ParentCtx>{ "name", -1, &obj, parent_ctx };
f(obj.name, ctx1);
const auto ctx2 = Context<Actor, ParentCtx>{ "title", -1, &obj, parent_ctx };
f(obj.title, ctx2);
const auto ctx3 = Context<Actor, ParentCtx>{ "character_name", -1, &obj, parent_ctx };
f(obj.character_name, ctx3);
const auto ctx10 = Context<Actor, ParentCtx>{ "face_name", -1, &obj, parent_ctx };
f(obj.face_name, ctx10);
const auto ctx16 = Context<Actor, ParentCtx>{ "parameters", -1, &obj, parent_ctx };
ForEachString(obj.parameters, f, &ctx16);
const auto ctx20 = Context<Actor, ParentCtx>{ "initial_equipment", -1, &obj, parent_ctx };
ForEachString(obj.initial_equipment, f, &ctx20);
for (int i = 0; i < static_cast<int>(obj.skills.size()); ++i) {
const auto ctx26 = Context<Actor, ParentCtx>{ "skills", i, &obj, parent_ctx };
ForEachString(obj.skills[i], f, &ctx26);
}
const auto ctx28 = Context<Actor, ParentCtx>{ "skill_name", -1, &obj, parent_ctx };
f(obj.skill_name, ctx28);
(void)obj;
(void)f;
(void)parent_ctx;
}
} // namespace rpg
} // namespace lcf
#endif
| 412 | 0.743885 | 1 | 0.743885 | game-dev | MEDIA | 0.894228 | game-dev | 0.772824 | 1 | 0.772824 |
MafiaHub/Framework | 2,692 | vendors/flecs/examples/cpp/prefabs/slots/src/main.cpp | #include <slots.h>
#include <iostream>
// Slots can be combined with prefab hierarchies to make it easier to access
// the child entities created for an instance.
//
// To create a slot, the SlotOf relationship is added to the child of a prefab,
// with as relationship target the prefab for which to register the slot. When
// the prefab is instantiated, each slot will be added as a relationship pair
// to the instance that looks like this:
// (PrefabChild, InstanceChild)
//
// For a SpaceShip prefab and an Engine child, that pair would look like this:
// (SpaceShip.Engine, Instance.Engine)
//
// To get the entity for a slot, an application can use the regular functions
// to inspect relationships and relationship targets (see code).
//
// Slots can be added to any level of a prefab hierarchy, as long as it is above
// (a parent of) the slot itself. When the prefab tree is instantiated, the
// slots are added to the entities that correspond with the prefab children.
//
// Without slots, an application would have to rely on manually looking up
// entities by name to get access to the instantiated children, like what the
// hierarchy example does.
int main() {
flecs::world ecs;
// Create the same prefab hierarchy as from the hierarchy example, but now
// with the SlotOf relationship.
flecs::entity SpaceShip = ecs.prefab("SpaceShip");
flecs::entity Engine = ecs.prefab("Engine")
.child_of(SpaceShip)
.slot_of(SpaceShip);
flecs::entity Cockpit = ecs.prefab("Cockpit")
.child_of(SpaceShip)
.slot_of(SpaceShip);
// Add an additional child to the Cockpit prefab to demonstrate how
// slots can be different from the parent. This slot could have been
// added to the Cockpit prefab, but instead we register it on the top
// level SpaceShip prefab.
flecs::entity PilotSeat = ecs.prefab("PilotSeat")
.child_of(Cockpit)
.slot_of(SpaceShip);
// Create a prefab instance.
flecs::entity inst = ecs.entity("my_spaceship").is_a(SpaceShip);
// Get the instantiated entities for the prefab slots
flecs::entity inst_engine = inst.target(Engine);
flecs::entity inst_cockpit = inst.target(Cockpit);
flecs::entity inst_seat = inst.target(PilotSeat);
std::cout << "instance engine: " << inst_engine.path() << "\n";
std::cout << "instance cockpit: " << inst_cockpit.path() << "\n";
std::cout << "instance seat: " << inst_seat.path() << "\n";
// Output:
// instance engine: ::my_spaceship::Engine
// instance cockpit: ::my_spaceship::Cockpit
// instance seat: ::my_spaceship::Cockpit::PilotSeat
}
| 412 | 0.72281 | 1 | 0.72281 | game-dev | MEDIA | 0.92142 | game-dev | 0.778054 | 1 | 0.778054 |
OpenSees/OpenSees | 17,524 | SRC/analysis/integrator/NewmarkHSFixedNumIter.cpp | /* ****************************************************************** **
** OpenSees - Open System for Earthquake Engineering Simulation **
** Pacific Earthquake Engineering Research Center **
** **
** **
** (C) Copyright 1999, The Regents of the University of California **
** All Rights Reserved. **
** **
** Commercial use of this program without express permission of the **
** University of California, Berkeley, is strictly prohibited. See **
** file 'COPYRIGHT' in main directory for information on usage and **
** redistribution, and for a DISCLAIMER OF ALL WARRANTIES. **
** **
** Developed by: **
** Frank McKenna (fmckenna@ce.berkeley.edu) **
** Gregory L. Fenves (fenves@ce.berkeley.edu) **
** Filip C. Filippou (filippou@ce.berkeley.edu) **
** **
** ****************************************************************** */
// $Revision$
// $Date$
// $URL$
// Written: Andreas Schellenberg (andreas.schellenberg@gmail.com)
// Created: 09/05
// Revision: A
//
// Description: This file contains the implementation of the NewmarkHSFixedNumIter class.
#include <NewmarkHSFixedNumIter.h>
#include <FE_Element.h>
#include <FE_EleIter.h>
#include <LinearSOE.h>
#include <AnalysisModel.h>
#include <Vector.h>
#include <DOF_Group.h>
#include <DOF_GrpIter.h>
#include <AnalysisModel.h>
#include <Channel.h>
#include <FEM_ObjectBroker.h>
#include <ConvergenceTest.h>
#include <elementAPI.h>
#define OPS_Export
void * OPS_NewmarkHSFixedNumIter(void)
{
// pointer to an integrator that will be returned
TransientIntegrator *theIntegrator = 0;
int argc = OPS_GetNumRemainingInputArgs();
if (argc != 2 && argc != 4) {
opserr << "WARNING - incorrect number of args want NewmarkHSFixedNumIter $gamma $beta <-polyOrder $O>\n";
return 0;
}
double dData[2];
int polyOrder = 2;
bool updDomFlag = true;
int numData = 2;
if (OPS_GetDouble(&numData, dData) != 0) {
opserr << "WARNING - invalid args want NewmarkHSFixedNumIter $gamma $beta <-polyOrder $O>\n";
return 0;
}
if (argc == 4) {
const char *argvLoc = OPS_GetString();
if (strcmp(argvLoc, "-polyOrder") == 0) {
numData = 1;
if (OPS_GetInt(&numData, &polyOrder) != 0) {
opserr << "WARNING - invalid polyOrder want NewmarkHSFixedNumIter $gamma $beta <-polyOrder $O>\n";
}
}
}
theIntegrator = new NewmarkHSFixedNumIter(dData[0], dData[1], polyOrder, updDomFlag);
if (theIntegrator == 0)
opserr << "WARNING - out of memory creating NewmarkHSFixedNumIter integrator\n";
return theIntegrator;
}
NewmarkHSFixedNumIter::NewmarkHSFixedNumIter()
: TransientIntegrator(INTEGRATOR_TAGS_NewmarkHSFixedNumIter),
gamma(0.5), beta(0.25), polyOrder(2), updDomFlag(true),
c1(0.0), c2(0.0), c3(0.0), x(1.0),
Ut(0), Utdot(0), Utdotdot(0), U(0), Udot(0), Udotdot(0),
Utm1(0), Utm2(0), scaledDeltaU(0)
{
}
NewmarkHSFixedNumIter::NewmarkHSFixedNumIter(double _gamma,
double _beta, int polyorder, bool upddomflag)
: TransientIntegrator(INTEGRATOR_TAGS_NewmarkHSFixedNumIter),
gamma(_gamma), beta(_beta), polyOrder(polyorder), updDomFlag(upddomflag),
c1(0.0), c2(0.0), c3(0.0), x(1.0),
Ut(0), Utdot(0), Utdotdot(0), U(0), Udot(0), Udotdot(0),
Utm1(0), Utm2(0), scaledDeltaU(0)
{
}
NewmarkHSFixedNumIter::~NewmarkHSFixedNumIter()
{
// clean up the memory created
if (Ut != 0)
delete Ut;
if (Utdot != 0)
delete Utdot;
if (Utdotdot != 0)
delete Utdotdot;
if (U != 0)
delete U;
if (Udot != 0)
delete Udot;
if (Udotdot != 0)
delete Udotdot;
if (Utm1 != 0)
delete Utm1;
if (Utm2 != 0)
delete Utm2;
if (scaledDeltaU != 0)
delete scaledDeltaU;
}
int NewmarkHSFixedNumIter::newStep(double deltaT)
{
if (beta == 0 || gamma == 0) {
opserr << "NewmarkHSFixedNumIter::newStep() - error in variable\n";
opserr << "gamma = " << gamma << " beta = " << beta << endln;
return -1;
}
if (deltaT <= 0.0) {
opserr << "NewmarkHSFixedNumIter::newStep() - error in variable\n";
opserr << "dT = " << deltaT << endln;
return -2;
}
// get a pointer to the AnalysisModel
AnalysisModel *theModel = this->getAnalysisModel();
// set the constants
c1 = 1.0;
c2 = gamma/(beta*deltaT);
c3 = 1.0/(beta*deltaT*deltaT);
if (U == 0) {
opserr << "NewmarkHSFixedNumIter::newStep() - domainChange() failed or hasn't been called\n";
return -3;
}
// set response at t to be that at t+deltaT of previous step
(*Utm2) = *Utm1;
(*Utm1) = *Ut;
(*Ut) = *U;
(*Utdot) = *Udot;
(*Utdotdot) = *Udotdot;
// determine new velocities and accelerations at t+deltaT
double a1 = (1.0 - gamma/beta);
double a2 = deltaT*(1.0 - 0.5*gamma/beta);
Udot->addVector(a1, *Utdotdot, a2);
double a3 = -1.0/(beta*deltaT);
double a4 = 1.0 - 0.5/beta;
Udotdot->addVector(a4, *Utdot, a3);
// set the trial response quantities
theModel->setVel(*Udot);
theModel->setAccel(*Udotdot);
// increment the time to t+deltaT and apply the load
double time = theModel->getCurrentDomainTime();
time += deltaT;
theModel->applyLoadDomain(time);
//correctForce = true;
return 0;
}
int NewmarkHSFixedNumIter::revertToLastStep()
{
// set response at t+deltaT to be that at t .. for next step
if (U != 0) {
(*U) = *Ut;
(*Udot) = *Utdot;
(*Udotdot) = *Utdotdot;
(*Ut) = *Utm1;
(*Utm1) = *Utm2;
}
return 0;
}
int NewmarkHSFixedNumIter::formEleTangent(FE_Element *theEle)
{
theEle->zeroTangent();
if (statusFlag == CURRENT_TANGENT)
theEle->addKtToTang(c1);
else if (statusFlag == INITIAL_TANGENT)
theEle->addKiToTang(c1);
theEle->addCtoTang(c2);
theEle->addMtoTang(c3);
return 0;
}
int NewmarkHSFixedNumIter::formNodTangent(DOF_Group *theDof)
{
theDof->zeroTangent();
theDof->addCtoTang(c2);
theDof->addMtoTang(c3);
return 0;
}
int NewmarkHSFixedNumIter::domainChanged()
{
AnalysisModel *theModel = this->getAnalysisModel();
LinearSOE *theLinSOE = this->getLinearSOE();
const Vector &x = theLinSOE->getX();
int size = x.Size();
// create the new Vector objects
if (Ut == 0 || Ut->Size() != size) {
// delete the old
if (Ut != 0)
delete Ut;
if (Utdot != 0)
delete Utdot;
if (Utdotdot != 0)
delete Utdotdot;
if (U != 0)
delete U;
if (Udot != 0)
delete Udot;
if (Udotdot != 0)
delete Udotdot;
if (Utm1 != 0)
delete Utm1;
if (Utm2 != 0)
delete Utm2;
if (scaledDeltaU != 0)
delete scaledDeltaU;
// create the new
Ut = new Vector(size);
Utdot = new Vector(size);
Utdotdot = new Vector(size);
U = new Vector(size);
Udot = new Vector(size);
Udotdot = new Vector(size);
Utm1 = new Vector(size);
Utm2 = new Vector(size);
scaledDeltaU = new Vector(size);
// check we obtained the new
if (Ut == 0 || Ut->Size() != size ||
Utdot == 0 || Utdot->Size() != size ||
Utdotdot == 0 || Utdotdot->Size() != size ||
U == 0 || U->Size() != size ||
Udot == 0 || Udot->Size() != size ||
Udotdot == 0 || Udotdot->Size() != size ||
Utm1 == 0 || Utm1->Size() != size ||
Utm2 == 0 || Utm2->Size() != size ||
scaledDeltaU == 0 || scaledDeltaU->Size() != size) {
opserr << "NewmarkHSFixedNumIter::domainChanged() - ran out of memory\n";
// delete the old
if (Ut != 0)
delete Ut;
if (Utdot != 0)
delete Utdot;
if (Utdotdot != 0)
delete Utdotdot;
if (U != 0)
delete U;
if (Udot != 0)
delete Udot;
if (Udotdot != 0)
delete Udotdot;
if (Utm1 != 0)
delete Utm1;
if (Utm2 != 0)
delete Utm2;
if (scaledDeltaU != 0)
delete scaledDeltaU;
Ut = 0; Utdot = 0; Utdotdot = 0;
U = 0; Udot = 0; Udotdot = 0;
Utm1 = 0; Utm2 = 0; scaledDeltaU = 0;
return -1;
}
}
// now go through and populate U, Udot and Udotdot by iterating through
// the DOF_Groups and getting the last committed velocity and accel
DOF_GrpIter &theDOFs = theModel->getDOFs();
DOF_Group *dofPtr;
while ((dofPtr = theDOFs()) != 0) {
const ID &id = dofPtr->getID();
int idSize = id.Size();
int i;
const Vector &disp = dofPtr->getCommittedDisp();
for (i=0; i < idSize; i++) {
int loc = id(i);
if (loc >= 0) {
(*Utm1)(loc) = disp(i);
(*Ut)(loc) = disp(i);
(*U)(loc) = disp(i);
}
}
const Vector &vel = dofPtr->getCommittedVel();
for (i=0; i < idSize; i++) {
int loc = id(i);
if (loc >= 0) {
(*Udot)(loc) = vel(i);
}
}
const Vector &accel = dofPtr->getCommittedAccel();
for (i=0; i < idSize; i++) {
int loc = id(i);
if (loc >= 0) {
(*Udotdot)(loc) = accel(i);
}
}
}
if (polyOrder == 2)
opserr << "\nWARNING: NewmarkHSFixedNumIter::domainChanged() - assuming Ut-1 = Ut\n";
else if (polyOrder == 3)
opserr << "\nWARNING: NewmarkHSFixedNumIter::domainChanged() - assuming Ut-2 = Ut-1 = Ut\n";
return 0;
}
int NewmarkHSFixedNumIter::update(const Vector &deltaU)
{
AnalysisModel *theModel = this->getAnalysisModel();
if (theModel == 0) {
opserr << "WARNING NewmarkHSFixedNumIter::update() - no AnalysisModel set\n";
return -1;
}
ConvergenceTest *theTest = this->getConvergenceTest();
if (theTest == 0) {
opserr << "WARNING NewmarkHSFixedNumIter::update() - no ConvergenceTest set\n";
return -2;
}
// check domainChanged() has been called, i.e. Ut will not be zero
if (Ut == 0) {
opserr << "WARNING NewmarkHSFixedNumIter::update() - domainChange() failed or not called\n";
return -3;
}
// check deltaU is of correct size
if (deltaU.Size() != U->Size()) {
opserr << "WARNING NewmarkHSFixedNumIter::update() - Vectors of incompatible size";
opserr << " expecting " << U->Size() << " obtained " << deltaU.Size() << endln;
return -4;
}
// get interpolation location and scale displacement increment
x = (double) theTest->getNumTests()/theTest->getMaxNumTests();
if (polyOrder == 1) {
(*scaledDeltaU) = x*((*U)+deltaU) - (x-1.0)*(*Ut) - (*U);
}
else if (polyOrder == 2) {
(*scaledDeltaU) = x*(x+1.0)/2.0*((*U)+deltaU) - (x-1.0)*(x+1.0)*(*Ut)
+ (x-1.0)*x/2.0*(*Utm1) - (*U);
}
else if (polyOrder == 3) {
(*scaledDeltaU) = x*(x+1.0)*(x+2.0)/6.0*((*U)+deltaU) - (x-1.0)*(x+1.0)*(x+2.0)/2.0*(*Ut)
+ (x-1.0)*x*(x+2.0)/2.0*(*Utm1) - (x-1.0)*x*(x+1.0)/6.0*(*Utm2) - (*U);
}
else {
opserr << "WARNING NewmarkHSFixedNumIter::update() - polyOrder > 3 not supported\n";
return -5;
}
// determine the response at t+deltaT
U->addVector(1.0, *scaledDeltaU, c1);
Udot->addVector(1.0, *scaledDeltaU, c2);
Udotdot->addVector(1.0, *scaledDeltaU, c3);
// update the response at the DOFs
theModel->setResponse(*U, *Udot, *Udotdot);
if (theModel->updateDomain() < 0) {
opserr << "NewmarkHSFixedNumIter::update() - failed to update the domain\n";
return -6;
}
return 0;
}
int NewmarkHSFixedNumIter::commit(void)
{
AnalysisModel *theModel = this->getAnalysisModel();
if (theModel == 0) {
opserr << "WARNING NewmarkHSFixedNumIter::commit() - no AnalysisModel set\n";
return -1;
}
if (updDomFlag == true) {
LinearSOE *theSOE = this->getLinearSOE();
if (theSOE == 0) {
opserr << "WARNING NewmarkHSFixedNumIter::commit() - no LinearSOE set\n";
return -2;
}
if (this->formTangent(statusFlag) < 0) {
opserr << "WARNING NewmarkHSFixedNumIter::commit() - "
<< "the Integrator failed in formTangent()\n";
return -3;
}
if (theSOE->solve() < 0) {
opserr << "WARNING NewmarkHSFixedNumIter::commit() - "
<< "the LinearSysOfEqn failed in solve()\n";
return -4;
}
const Vector &deltaU = theSOE->getX();
// determine the response at t+deltaT
U->addVector(1.0, deltaU, c1);
Udot->addVector(1.0, deltaU, c2);
Udotdot->addVector(1.0, deltaU, c3);
// update the response at the DOFs
theModel->setResponse(*U, *Udot, *Udotdot);
}
return theModel->commitDomain();
}
const Vector &
NewmarkHSFixedNumIter::getVel()
{
return *Udot;
}
int NewmarkHSFixedNumIter::sendSelf(int cTag, Channel &theChannel)
{
Vector data(4);
data(0) = gamma;
data(1) = beta;
data(2) = polyOrder;
if (updDomFlag == true)
data(3) = 1.0;
else
data(3) = 0.0;
if (theChannel.sendVector(this->getDbTag(), cTag, data) < 0) {
opserr << "WARNING NewmarkHSFixedNumIter::sendSelf() - could not send data\n";
return -1;
}
return 0;
}
int NewmarkHSFixedNumIter::recvSelf(int cTag, Channel &theChannel, FEM_ObjectBroker &theBroker)
{
Vector data(4);
if (theChannel.recvVector(this->getDbTag(), cTag, data) < 0) {
opserr << "WARNING NewmarkHSFixedNumIter::recvSelf() - could not receive data\n";
return -1;
}
gamma = data(0);
beta = data(1);
polyOrder = int(data(2));
if (data(3) == 1.0)
updDomFlag = true;
else
updDomFlag = false;
return 0;
}
void NewmarkHSFixedNumIter::Print(OPS_Stream &s, int flag)
{
AnalysisModel *theModel = this->getAnalysisModel();
if (theModel != 0) {
double currentTime = theModel->getCurrentDomainTime();
s << "NewmarkHSFixedNumIter - currentTime: " << currentTime << endln;
s << " gamma: " << gamma << " beta: " << beta << endln;
s << " c1: " << c1 << " c2: " << c2 << " c3: " << c3 << endln;
s << " polyOrder: " << polyOrder << endln;
if (updDomFlag)
s << " update Domain: yes\n";
else
s << " update Domain: no\n";
} else
s << "NewmarkHSFixedNumIter - no associated AnalysisModel\n";
}
/* force correction does not work if numIter = 1, yields slightly
// improved results if numIter = 2 and has no effect if numIter >= 3
int NewmarkHSFixedNumIter::formElementResidual(void)
{
// calculate Residual Force
AnalysisModel *theModel = this->getAnalysisModel();
LinearSOE *theSOE = this->getLinearSOE();
// loop through the FE_Elements and add the residual
FE_Element *elePtr;
FE_EleIter &theEles = theModel->getFEs();
while ((elePtr = theEles()) != 0) {
if (theSOE->addB(elePtr->getResidual(this),elePtr->getID()) < 0) {
opserr << "WARNING NewmarkHSFixedNumIter::formElementResidual() -";
opserr << " failed in addB for ID " << elePtr->getID();
return -1;
}
if (correctForce) {
const Vector &deltaU = theSOE->getX();
if (statusFlag == CURRENT_TANGENT) {
if (theSOE->addB(elePtr->getK_Force(deltaU), elePtr->getID()) < 0) {
opserr << "WARNING NewmarkHSFixedNumIter::formElementResidual() -";
opserr << " failed in addB for ID " << elePtr->getID();
return -2;
}
} else if (statusFlag == INITIAL_TANGENT) {
if (theSOE->addB(elePtr->getKi_Force(deltaU), elePtr->getID()) < 0) {
opserr << "WARNING NewmarkHSFixedNumIter::formElementResidual() -";
opserr << " failed in addB for ID " << elePtr->getID();
return -2;
}
}
}
}
correctForce = false;
return 0;
}*/
| 412 | 0.952115 | 1 | 0.952115 | game-dev | MEDIA | 0.594568 | game-dev | 0.98852 | 1 | 0.98852 |
goldeneye-source/ges-code | 4,362 | game/server/fish.h | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
// fish.h
// Simple fish behavior
// Author: Michael S. Booth, April 2005
#ifndef _FISH_H_
#define _FISH_H_
#include "baseanimating.h"
#include "GameEventListener.h"
class CFishPool;
//----------------------------------------------------------------------------------------------
/**
* Simple ambient fish
*/
class CFish : public CBaseAnimating
{
public:
DECLARE_CLASS( CFish, CBaseAnimating );
DECLARE_SERVERCLASS();
DECLARE_DATADESC();
CFish( void );
virtual ~CFish();
void Initialize( CFishPool *pool, unsigned int id );
virtual void Spawn( void );
virtual void Event_Killed( const CTakeDamageInfo &info );
virtual void Touch( CBaseEntity *other ); ///< in contact with "other"
void Update( float deltaT ); ///< invoked each server tick
void FlockTo( CFish *other, float amount ); ///< influence my motion to flock with other nearby fish
float Avoid( void );
void Panic( void ); ///< panic for awhile
void ResetVisible( void ); ///< zero the visible vector
void AddVisible( CFish *fish ); ///< add this fish to our visible vector
private:
friend void SendProxy_FishOriginX( const SendProp *pProp, const void *pStruct, const void *pData, DVariant *pOut, int iElement, int objectID );
friend void SendProxy_FishOriginY( const SendProp *pProp, const void *pStruct, const void *pData, DVariant *pOut, int iElement, int objectID );
CHandle<CFishPool> m_pool; ///< the pool we are in
unsigned int m_id; ///< our unique ID
CNetworkVar( float, m_x ); ///< have to send position coordinates separately since Z is unused
CNetworkVar( float, m_y ); ///< have to send position coordinates separately since Z is unused
CNetworkVar( float, m_z ); ///< only sent once since fish always swim at the same depth
CNetworkVar( float, m_angle ); ///< only yaw changes
float m_angleChange;
Vector m_forward;
Vector m_perp;
CNetworkVar( Vector, m_poolOrigin ); ///< used to efficiently network our relative position
CNetworkVar( float, m_waterLevel );
float m_speed;
float m_desiredSpeed;
float m_calmSpeed; ///< speed the fish moves when calm
float m_panicSpeed; ///< speed the fish moves when panicked
float m_avoidRange; ///< range to avoid obstacles
CountdownTimer m_turnTimer; ///< every so often our turn preference changes
bool m_turnClockwise; ///< if true this fish prefers to turn clockwise, else CCW
CountdownTimer m_goTimer; ///< start the fish moving when timer elapses
CountdownTimer m_moveTimer; ///< dont decay speed while we are moving
CountdownTimer m_panicTimer; ///< if active, fish is panicked
CountdownTimer m_disperseTimer; ///< initial non-flocking time
CUtlVector< CFish * > m_visible; ///< vector of fish that we can see
};
//----------------------------------------------------------------------------------------------
/**
* This class defines a volume of water where a number of CFish swim
*/
class CFishPool : public CBaseEntity, public CGameEventListener
{
public:
DECLARE_CLASS( CFishPool, CBaseEntity );
DECLARE_DATADESC();
CFishPool( void );
virtual void Spawn();
virtual bool KeyValue( const char *szKeyName, const char *szValue );
virtual void FireGameEvent( IGameEvent *event );
void Update( void ); ///< invoked each server tick
float GetWaterLevel( void ) const; ///< return Z coordinate of water in world coords
float GetMaxRange( void ) const; ///< return how far a fish is allowed to wander
private:
int m_fishCount; ///< number of fish in the pool
float m_maxRange; ///< how far a fish is allowed to wander
float m_swimDepth; ///< the depth the fish swim below the water surface
float m_waterLevel; ///< Z of water surface
bool m_isDormant;
CUtlVector< CHandle<CFish> > m_fishes; ///< vector of all fish in this pool
CountdownTimer m_visTimer; ///< for throttling line of sight checks between all fish
};
inline float CFishPool::GetMaxRange( void ) const
{
return m_maxRange;
}
inline float CFishPool::GetWaterLevel( void ) const
{
return m_waterLevel;
}
#endif // _FISH_H_
| 412 | 0.826371 | 1 | 0.826371 | game-dev | MEDIA | 0.881907 | game-dev | 0.650517 | 1 | 0.650517 |
IrisShaders/Iris | 1,824 | neoforge/src/main/java/net/irisshaders/iris/platform/IrisForgeHelpers.java | package net.irisshaders.iris.platform;
import net.irisshaders.iris.Iris;
import net.minecraft.client.KeyMapping;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.world.level.BlockAndTintGetter;
import net.minecraft.world.level.block.state.BlockState;
import net.neoforged.fml.loading.FMLLoader;
import net.neoforged.fml.loading.FMLPaths;
import net.neoforged.fml.loading.LoadingModList;
import org.apache.maven.artifact.versioning.ArtifactVersion;
import org.apache.maven.artifact.versioning.DefaultArtifactVersion;
import java.nio.file.Path;
public class IrisForgeHelpers implements IrisPlatformHelpers {
@Override
public boolean isModLoaded(String modId) {
return LoadingModList.get().getModFileById(modId) != null;
}
boolean HAS_CAMO = isModLoaded("cable_facades");
@Override
public String getVersion() {
return LoadingModList.get().getModFileById(Iris.MODID).versionString();
}
@Override
public boolean isDevelopmentEnvironment() {
return !FMLLoader.isProduction();
}
@Override
public Path getGameDir() {
return FMLPaths.GAMEDIR.get();
}
@Override
public Path getConfigDir() {
return FMLPaths.CONFIGDIR.get();
}
@Override
public int compareVersions(String currentVersion, String semanticVersion) throws Exception {
return new DefaultArtifactVersion(currentVersion).compareTo(new DefaultArtifactVersion(semanticVersion));
}
@Override
public KeyMapping registerKeyBinding(KeyMapping keyMapping) {
IrisForgeMod.KEYLIST.add(keyMapping);
return keyMapping;
}
@Override
public boolean useELS() {
return true;
}
// TODO find a way to do this without breaking Cable Facades...
@Override
public BlockState getBlockAppearance(BlockAndTintGetter level, BlockState state, Direction cullFace, BlockPos pos) {
return state;
}
}
| 412 | 0.831459 | 1 | 0.831459 | game-dev | MEDIA | 0.939327 | game-dev | 0.909782 | 1 | 0.909782 |
AionGermany/aion-germany | 1,888 | AL-Game-5.8/src/com/aionemu/gameserver/taskmanager/tasks/PlayerMoveTaskManager.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 com.aionemu.gameserver.taskmanager.tasks;
import com.aionemu.gameserver.model.gameobjects.Creature;
import com.aionemu.gameserver.taskmanager.AbstractPeriodicTaskManager;
import javolution.util.FastMap;
/**
* @author ATracer
*/
public class PlayerMoveTaskManager extends AbstractPeriodicTaskManager {
private final FastMap<Integer, Creature> movingPlayers = new FastMap<Integer, Creature>().shared();
private PlayerMoveTaskManager() {
super(200);
}
public void addPlayer(Creature player) {
movingPlayers.put(player.getObjectId(), player);
}
public void removePlayer(Creature player) {
movingPlayers.remove(player.getObjectId());
}
@Override
public void run() {
for (FastMap.Entry<Integer, Creature> e = movingPlayers.head(), mapEnd = movingPlayers.tail(); (e = e.getNext()) != mapEnd;) {
Creature player = e.getValue();
player.getMoveController().moveToDestination();
}
}
public static final PlayerMoveTaskManager getInstance() {
return SingletonHolder.INSTANCE;
}
private static final class SingletonHolder {
private static final PlayerMoveTaskManager INSTANCE = new PlayerMoveTaskManager();
}
}
| 412 | 0.779484 | 1 | 0.779484 | game-dev | MEDIA | 0.856029 | game-dev | 0.670424 | 1 | 0.670424 |
risingPhil/PokeMe64 | 4,091 | include/animations/IAnimation.h | #ifndef _IANIMATION_H
#define _IANIMATION_H
#include <cstdint>
/**
* A Distance time function indicates at a certain normalized time point in the [0.0, 1.0] range in the animation,
* how much of the total movement the animation should have done (also normalized in the [0.0, 1.0])
*
* This gives you a way to control the acceleration/deceleration of the animation.
*/
enum class AnimationDistanceTimeFunctionType
{
/**
* No distance time function means no animation -> The animation will immediately be move to the end position (1.0f)
*/
NONE,
/**
* Linear distance time function means that the animation always moves at the same speed
*/
LINEAR,
/**
* The Ease-in Ease-out distance time function slowly accelerates the animation at the start and slowly decelerates the animation at the end
*/
EASE_IN_EASE_OUT
};
/**
* @brief This enum defines what loop type the animation has (if any)
*/
enum class AnimationLoopType
{
/**
* No loop
*/
NONE,
/**
* After the end of the animation is reached, it restarts from the beginning
*/
NORMAL_LOOP,
/**
* After the end of the animation is reached, it will start going backwards until the beginning is reached again. And then it will go forward again.
* This cycle repeats until someone/something stops the animation.
*/
BACK_AND_FORTH
};
class IAnimation
{
public:
virtual ~IAnimation();
virtual AnimationDistanceTimeFunctionType getDistanceTimeFunctionType() const = 0;
/**
* Applies the specified step. This should be a stepSize in the [0.f - 1.f] range
*/
virtual void step(float stepSize, bool suppressFinishedCallback = false) = 0;
/**
* @brief returns the duration of the animation in milliseconds
*/
virtual uint32_t getDurationInMs() const = 0;
/**
* Skips to the end of the animation
*/
virtual void skipToEnd() = 0;
/** Indicates whether this animation is finished and should therefore be removed from AnimationManager */
virtual bool isFinished() const = 0;
/**
* Returns the current loop type (if any)
*/
virtual AnimationLoopType getLoopType() const = 0;
/**
* Sets the loop type (if any)
*/
virtual void setLoopType(AnimationLoopType loopType) = 0;
/**
* @brief Sets a callback that should be called when the animation has finished.
* Note: this only applies to scenarios where AnimationLoopType == NONE
*/
virtual void setAnimationFinishedCallback(void* context, void (*animationFinishedCb)(void*)) = 0;
protected:
/**
* @brief This function applies the relative pos [0.f-1.f] to the
* specific animation implementation.
*
* This pos indicates the point in the animation between the start and the end, not in function of time
* but in function of distance (the actual point that needs to be applied)
*/
virtual void apply(float pos) = 0;
private:
};
/**
* @brief Abstract implementation of common functionality defined in IAnimation
*
*/
class AbstractAnimation : public IAnimation
{
public:
AbstractAnimation(float initialTimePos = 0);
virtual ~AbstractAnimation();
void step(float stepSize, bool suppressFinishedCallback = false) override;
void skipToEnd() override;
bool isFinished() const override;
/**
* Returns the current loop type (if any)
*/
AnimationLoopType getLoopType() const override;
/**
* Sets the loop type (if any)
*/
void setLoopType(AnimationLoopType loopType) override;
/**
* @brief Sets a callback that should be called when the animation has finished.
* Note: this only applies to scenarios where AnimationLoopType == NONE
*/
void setAnimationFinishedCallback(void* context, void (*animationFinishedCb)(void*));
protected:
float currentTimePos_;
private:
void (*animationFinishedCb_)(void*);
void *animationFinishedCallbackContext_;
AnimationLoopType loopType_;
bool isStepIncreasing_;
};
#endif | 412 | 0.856667 | 1 | 0.856667 | game-dev | MEDIA | 0.569824 | game-dev,graphics-rendering | 0.897996 | 1 | 0.897996 |
gmitch215/MobChip | 3,684 | nms/1_20_R3/src/main/java/me/gamercoder215/mobchip/abstraction/v1_20_R3/EntityController1_20_R3.java | package me.gamercoder215.mobchip.abstraction.v1_20_R3;
import me.gamercoder215.mobchip.ai.controller.EntityController;
import me.gamercoder215.mobchip.ai.controller.NaturalMoveType;
import net.minecraft.world.entity.MoverType;
import net.minecraft.world.entity.ai.control.JumpControl;
import net.minecraft.world.entity.ai.control.LookControl;
import net.minecraft.world.entity.ai.control.MoveControl;
import net.minecraft.world.phys.Vec3;
import org.bukkit.Location;
import org.bukkit.entity.Mob;
import org.bukkit.util.Vector;
import org.jetbrains.annotations.NotNull;
final class EntityController1_20_R3 implements EntityController {
private final JumpControl jumpC;
private final MoveControl moveC;
private final LookControl lookC;
private final Mob m;
private final net.minecraft.world.entity.Mob nms;
public EntityController1_20_R3(Mob m) {
net.minecraft.world.entity.Mob nms = ChipUtil1_20_R3.toNMS(m);
this.lookC = nms.getLookControl();
this.moveC = nms.getMoveControl();
this.jumpC = nms.getJumpControl();
this.m = m;
this.nms = nms;
}
@Override
public EntityController jump() {
jumpC.jump();
jumpC.tick();
return this;
}
@Override
public boolean isLookingAtTarget() {
Vector dir = m.getLocation().getDirection();
int x = dir.getBlockX();
int y = dir.getBlockY();
int z = dir.getBlockZ();
return lookC.getWantedX() == x && lookC.getWantedY() == y && lookC.getWantedZ() == z;
}
@Override
public EntityController moveTo(double x, double y, double z, double speedMod) {
moveC.setWantedPosition(x, y, z, speedMod);
moveC.tick();
nms.getNavigation().moveTo(moveC.getWantedX(), moveC.getWantedY(), moveC.getWantedZ(), moveC.getSpeedModifier());
nms.getNavigation().tick();
return this;
}
@Override
public EntityController naturalMoveTo(double x, double y, double z, NaturalMoveType type) {
Vec3 vec = new Vec3(x, y, z);
MoverType m = switch (type) {
default -> MoverType.SELF;
case PLAYER -> MoverType.PLAYER;
case PISTON -> MoverType.PISTON;
case SHULKER_BOX -> MoverType.SHULKER_BOX;
case SHULKER -> MoverType.SHULKER;
};
nms.move(m, vec);
return this;
}
@Override
public EntityController strafe(float fwd, float right) {
moveC.strafe(fwd, right);
moveC.tick();
nms.getNavigation().moveTo(moveC.getWantedX(), moveC.getWantedY(), moveC.getWantedZ(), moveC.getSpeedModifier());
nms.getNavigation().tick();
return this;
}
@Override
public double getCurrentSpeedModifier() {
return moveC.getSpeedModifier();
}
@Override
public Location getTargetMoveLocation() {
return new Location(m.getWorld(), moveC.getWantedX(), moveC.getWantedY(), moveC.getWantedZ());
}
@Override
public Location getTargetLookLocation() {
return new Location(m.getWorld(), lookC.getWantedX(), lookC.getWantedY(), lookC.getWantedZ());
}
@Override
public EntityController lookAt(double x, double y, double z) {
lookC.setLookAt(x, y, z);
lookC.tick();
return this;
}
@Override
public @NotNull Vector getDeltaMovement() {
Vec3 delta = nms.getDeltaMovement();
return new Vector(delta.x, delta.y, delta.z);
}
@Override
public void setDeltaMovement(@NotNull Vector delta) {
Vec3 vec = new Vec3(delta.getX(), delta.getY(), delta.getZ());
nms.setDeltaMovement(vec);
}
}
| 412 | 0.887305 | 1 | 0.887305 | game-dev | MEDIA | 0.950088 | game-dev | 0.957863 | 1 | 0.957863 |
Jermesa-Studio/JRS_Vehicle_Physics_Controller | 2,783 | Assets/JS Vehicle Physics Controller/Script AMR/JrsFollowCamera.cs | // MIT License
//
// Copyright (c) 2023 Samborlang Pyrtuh
//
// 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;
public class JrsFollowCamera : MonoBehaviour
{
public Transform target; // The vehicle to follow
public Vector3 offset; // The offset from the vehicle
public float horizontalSpringConstant = 0.5f; // The spring constant for horizontal movement
public float horizontalDampingConstant = 0.3f; // The damping constant for horizontal movement
private Vector3 velocity; // The velocity of the camera
void FixedUpdate()
{
Vector3 desiredPosition = target.TransformPoint(offset);
Vector3 horizontalDisplacement = new Vector3(desiredPosition.x - transform.position.x, 0, desiredPosition.z - transform.position.z);
Vector3 horizontalSpringForce = horizontalSpringConstant * horizontalDisplacement;
Vector3 horizontalDampingForce = -horizontalDampingConstant * new Vector3(velocity.x, 0, velocity.z);
Vector3 force = horizontalSpringForce + horizontalDampingForce;
velocity += force * Time.fixedDeltaTime;
transform.position += new Vector3(velocity.x, 0, velocity.z) * Time.fixedDeltaTime;
// Calculate the desired camera height based on the target's position and offset
float desiredCameraHeight = target.position.y + offset.y;
// Set the camera's position with the desired height
transform.position = new Vector3(transform.position.x, desiredCameraHeight, transform.position.z);
Vector3 lookDirection = target.position - transform.position;
Quaternion rotation = Quaternion.LookRotation(new Vector3(lookDirection.x, lookDirection.y, lookDirection.z));
transform.rotation = rotation;
}
}
| 412 | 0.866021 | 1 | 0.866021 | game-dev | MEDIA | 0.859502 | game-dev | 0.595463 | 1 | 0.595463 |
ciplogic/fheroes2enh | 11,535 | src/fheroes2/maps/maps_tiles.h | /***************************************************************************
* Copyright (C) 2009 by Andrey Afletdinov <fheroes2@gmail.com> *
* *
* Part of the Free Heroes2 Engine: *
* http://sourceforge.net/projects/fheroes2 *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#pragma once
#include "direction.h"
#include "skill.h"
#include "artifact.h"
#include "army_troop.h"
#include "resource.h"
#include "ByteVectorReader.h"
#include "ByteVectorWriter.h"
class Sprite;
class Heroes;
class Spell;
class Monster;
namespace MP2
{
struct mp2tile_t;
struct mp2addon_t;
}
namespace Maps
{
struct TilesAddon
{
enum level_t
{
GROUND = 0,
DOWN = 1,
SHADOW = 2,
UPPER = 3
};
TilesAddon();
TilesAddon(int lv, uint32_t gid, int obj, uint32_t ii);
TilesAddon& operator=(const TilesAddon& ta);
bool isUniq(uint32_t) const;
bool isRoad(int) const;
bool isICN(int) const;
string String(int level) const;
static bool isStream(const TilesAddon&);
static bool isRoad(const TilesAddon&);
static bool isResource(const TilesAddon&);
static bool isWaterResource(const TilesAddon&);
static bool isWhirlPool(const TilesAddon&);
static bool isStandingStone(const TilesAddon&);
static bool isArtifact(const TilesAddon&);
static bool isCampFire(const TilesAddon&);
static bool isMonster(const TilesAddon&);
static bool isArtesianSpring(const TilesAddon&);
static bool isOasis(const TilesAddon&);
static bool isWateringHole(const TilesAddon&);
static bool isJail(const TilesAddon&);
static bool isMine(const TilesAddon&);
static bool isShadow(const TilesAddon&);
static bool isEvent(const TilesAddon&);
static bool isBoat(const TilesAddon&);
static bool isMiniHero(const TilesAddon&);
static bool isRandomResource(const TilesAddon&);
static bool isRandomArtifact(const TilesAddon&);
static bool isRandomArtifact1(const TilesAddon&);
static bool isRandomArtifact2(const TilesAddon&);
static bool isRandomArtifact3(const TilesAddon&);
static bool isUltimateArtifact(const TilesAddon&);
static bool isCastle(const TilesAddon&);
static bool isRandomCastle(const TilesAddon&);
static bool isRandomMonster(const TilesAddon&);
static bool isSkeleton(const TilesAddon&);
static bool isSkeletonFix(const TilesAddon&);
static bool isFlag32(const TilesAddon&);
static bool isX_LOC123(const TilesAddon&);
static bool isAbandoneMineSprite(const TilesAddon&);
static bool isMounts(const TilesAddon&);
static bool isRocs(const TilesAddon&);
static bool isForests(const TilesAddon&);
static bool isTrees(const TilesAddon&);
static bool isDeadTrees(const TilesAddon&);
static bool isCactus(const TilesAddon&);
static bool isStump(const TilesAddon&);
static int GetPassable(const TilesAddon&);
static int GetActionObject(const TilesAddon&);
static int GetLoyaltyObject(const TilesAddon&);
static bool isBarrier(const TilesAddon&);
static int ColorFromBarrierSprite(const TilesAddon&);
static int ColorFromTravellerTentSprite(const TilesAddon&);
static pair<int, int>
ColorRaceFromHeroSprite(const TilesAddon&);
static bool PredicateSortRules1(const TilesAddon&, const TilesAddon&);
static bool PredicateSortRules2(const TilesAddon&, const TilesAddon&);
static void UpdateFountainSprite(TilesAddon&);
static void UpdateTreasureChestSprite(TilesAddon&);
static int UpdateStoneLightsSprite(TilesAddon&);
static void UpdateAbandoneMineLeftSprite(TilesAddon&, int resource);
static void UpdateAbandoneMineRightSprite(TilesAddon&);
static bool ForceLevel1(const TilesAddon&);
static bool ForceLevel2(const TilesAddon&);
uint32_t uniq;
u8 level;
u8 object;
u8 index;
u8 tmp;
};
struct Addons
{
vector<TilesAddon> _items;
void Remove(uint32_t uniq);
};
class Tiles
{
public:
Tiles();
void Init(s32, const MP2::mp2tile_t&);
s32 GetIndex() const;
Point GetCenter() const;
int GetObject(bool skip_hero = true) const;
uint32_t GetObjectUID(int obj) const;
int GetQuantity1() const
{
return quantity1;
}
int GetQuantity2() const
{
return quantity2;
}
int GetPassable() const;
int GetGround() const;
bool isWater() const;
uint32_t TileSpriteIndex() const;
uint32_t TileSpriteShape() const;
Surface GetTileSurface() const;
bool isPassable(const Heroes&) const;
bool isPassable(const Heroes*, int direct, bool skipfog) const;
bool isRoad(int = DIRECTION_ALL) const;
bool isObject(int obj) const
{
return obj == mp2_object;
}
bool isStream() const;
bool GoodForUltimateArtifact() const;
TilesAddon* FindAddonICN1(int icn1);
TilesAddon* FindAddonICN2(int icn2);
TilesAddon* FindAddonLevel1(uint32_t uniq1);
TilesAddon* FindAddonLevel2(uint32_t uniq2);
TilesAddon* FindObject(int) const;
const TilesAddon* FindObjectConst(int) const;
void SetTile(uint32_t sprite_index, uint32_t shape /* 0: none, 1 : vert, 2: horz, 3: both */);
void SetObject(int object);
void SetIndex(int);
void FixObject();
void UpdatePassable();
void CaptureFlags32(int obj, int col);
void RedrawTile(Surface&) const;
void RedrawBottom(Surface&, bool skip_objs = false) const;
void RedrawBottom4Hero(Surface&) const;
void RedrawTop(Surface&, const TilesAddon* skip = nullptr) const;
void RedrawTop4Hero(Surface&, bool skip_ground) const;
void RedrawObjects(Surface&) const;
void RedrawFogs(Surface&, int) const;
static void RedrawPassable(Surface&);
void AddonsPushLevel1(const MP2::mp2tile_t&);
void AddonsPushLevel1(const MP2::mp2addon_t&);
void AddonsPushLevel1(const TilesAddon&);
void AddonsPushLevel2(const MP2::mp2tile_t&);
void AddonsPushLevel2(const MP2::mp2addon_t&);
void AddonsPushLevel2(const TilesAddon&);
void AddonsSort();
void Remove(uint32_t uniq);
void RemoveObjectSprite();
string String() const;
bool isFog(int color) const;
void ClearFog(int color);
/* monster operation */
bool MonsterJoinConditionSkip() const;
bool MonsterJoinConditionMoney() const;
bool MonsterJoinConditionFree() const;
bool MonsterJoinConditionForce() const;
int MonsterJoinCondition() const;
void MonsterSetJoinCondition(int) const;
void MonsterSetFixedCount() const;
bool MonsterFixedCount() const;
void MonsterSetCount(uint32_t count);
uint32_t MonsterCount() const;
bool CaptureObjectIsProtection() const;
/* object quantity operation */
void QuantityUpdate();
void QuantityReset();
bool QuantityIsValid() const;
void QuantitySetColor(int);
int QuantityTeleportType() const;
int QuantityVariant() const;
int QuantityExt() const;
int QuantityColor() const;
uint32_t QuantityGold() const;
Spell QuantitySpell() const;
Skill::Secondary QuantitySkill() const;
Artifact QuantityArtifact() const;
ResourceCount QuantityResourceCount() const;
Funds QuantityFunds() const;
Monster QuantityMonster() const;
Troop QuantityTroop() const;
void SetObjectPassable(bool);
Heroes* GetHeroes() const;
void SetHeroes(Heroes*);
static void PlaceMonsterOnTile(Tiles&, const Monster&, uint32_t);
static void UpdateAbandoneMineSprite(Tiles&);
static void FixedPreload(Tiles&);
private:
TilesAddon* FindFlags();
void CorrectFlags32(uint32_t index, bool);
void RemoveJailSprite();
void RemoveBarrierSprite();
bool isLongObject(int direction);
void RedrawBoat(Surface&) const;
void RedrawMonster(Surface&) const;
void QuantitySetVariant(int);
void QuantitySetExt(int);
void QuantitySetSkill(Skill::SkillT);
void QuantitySetSpell(int);
void QuantitySetArtifact(int);
void QuantitySetResource(int, uint32_t);
void QuantitySetTeleportType(int);
int GetQuantity3() const;
void SetQuantity3(int);
static void UpdateMonsterInfo(Tiles&);
static void UpdateDwellingPopulation(Tiles&);
static void UpdateMonsterPopulation(Tiles&);
static void UpdateRNDArtifactSprite(Tiles&);
static void UpdateRNDResourceSprite(Tiles&);
static void UpdateStoneLightsSprite(Tiles&);
static void UpdateFountainSprite(Tiles&);
static void UpdateTreasureChestSprite(Tiles&);
friend ByteVectorWriter& operator<<(ByteVectorWriter&, const Tiles&);
friend ByteVectorReader& operator>>(ByteVectorReader&, Tiles&);
Addons addons_level1;
Addons addons_level2; // 16
uint32_t maps_index = 0;
u16 pack_sprite_index = 0;
u16 tile_passable = 0;
u8 mp2_object = 0;
u8 fog_colors = 0;
u8 quantity1 = 0;
u8 quantity2 = 0;
u8 quantity3 = 0;
};
ByteVectorWriter& operator<<(ByteVectorWriter&, const TilesAddon&);
ByteVectorWriter& operator<<(ByteVectorWriter&, const Tiles&);
ByteVectorReader& operator>>(ByteVectorReader&, TilesAddon&);
ByteVectorReader& operator>>(ByteVectorReader&, Tiles&);
}
| 412 | 0.791952 | 1 | 0.791952 | game-dev | MEDIA | 0.701184 | game-dev | 0.559443 | 1 | 0.559443 |
spazzylemons/playdoom | 16,728 | src/p_pspr.c | //
// Copyright(C) 1993-1996 Id Software, Inc.
// Copyright(C) 2005-2014 Simon Howard
//
// 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.
//
// DESCRIPTION:
// Weapon sprite animation, weapon objects.
// Action functions for weapons.
//
#include "doomdef.h"
#include "d_event.h"
#include "m_random.h"
#include "p_local.h"
#include "s_sound.h"
// State.
#include "doomstat.h"
// Data.
#include "sounds.h"
#include "p_pspr.h"
#define LOWERSPEED FRACUNIT*6
#define RAISESPEED FRACUNIT*6
#define WEAPONBOTTOM 168*FRACUNIT
#define WEAPONTOP 72*FRACUNIT
//
// P_SetPsprite
//
void
P_SetPsprite
( player_t* player,
int position,
statenum_t stnum )
{
pspdef_t* psp;
state_t* state;
psp = &player->psprites[position];
do
{
if (!stnum)
{
// object removed itself
psp->state = NULL;
break;
}
state = &states[stnum];
psp->state = state;
psp->tics = state->tics; // could be 0
if (state->misc1)
{
// coordinate set
psp->sx = state->misc1 << FRACBITS;
psp->sy = state->misc2 << FRACBITS;
}
// Call action routine.
// Modified handling.
if (state->action.acp2)
{
state->action.acp2(player, psp);
if (!psp->state)
break;
}
stnum = psp->state->nextstate;
} while (!psp->tics);
// an initial state of 0 could cycle through
}
//
// P_CalcSwing
//
fixed_t swingx;
fixed_t swingy;
void P_CalcSwing (player_t* player)
{
fixed_t swing;
int angle;
// OPTIMIZE: tablify this.
// A LUT would allow for different modes,
// and add flexibility.
swing = player->bob;
angle = (FINEANGLES/70*leveltime)&FINEMASK;
swingx = FixedMul ( swing, finesine[angle]);
angle = (FINEANGLES/70*leveltime+FINEANGLES/2)&FINEMASK;
swingy = -FixedMul ( swingx, finesine[angle]);
}
//
// P_BringUpWeapon
// Starts bringing the pending weapon up
// from the bottom of the screen.
// Uses player
//
void P_BringUpWeapon (player_t* player)
{
statenum_t newstate;
if (player->pendingweapon == wp_nochange)
player->pendingweapon = player->readyweapon;
if (player->pendingweapon == wp_chainsaw)
S_StartSound (player->mo, sfx_sawup);
newstate = weaponinfo[player->pendingweapon].upstate;
player->pendingweapon = wp_nochange;
player->psprites[ps_weapon].sy = WEAPONBOTTOM;
P_SetPsprite (player, ps_weapon, newstate);
}
//
// P_CheckAmmo
// Returns true if there is enough ammo to shoot.
// If not, selects the next weapon to use.
//
boolean P_CheckAmmo (player_t* player)
{
ammotype_t ammo;
int count;
ammo = weaponinfo[player->readyweapon].ammo;
// Minimal amount for one shot varies.
if (player->readyweapon == wp_bfg)
count = 40;
else if (player->readyweapon == wp_supershotgun)
count = 2; // Double barrel.
else
count = 1; // Regular.
// Some do not need ammunition anyway.
// Return if current ammunition sufficient.
if (ammo == am_noammo || player->ammo[ammo] >= count)
return true;
// Out of ammo, pick a weapon to change to.
// Preferences are set here.
do
{
if (player->weaponowned[wp_plasma]
&& player->ammo[am_cell]
&& (gamemode != shareware) )
{
player->pendingweapon = wp_plasma;
}
else if (player->weaponowned[wp_supershotgun]
&& player->ammo[am_shell]>2
&& (gamemode == commercial) )
{
player->pendingweapon = wp_supershotgun;
}
else if (player->weaponowned[wp_chaingun]
&& player->ammo[am_clip])
{
player->pendingweapon = wp_chaingun;
}
else if (player->weaponowned[wp_shotgun]
&& player->ammo[am_shell])
{
player->pendingweapon = wp_shotgun;
}
else if (player->ammo[am_clip])
{
player->pendingweapon = wp_pistol;
}
else if (player->weaponowned[wp_chainsaw])
{
player->pendingweapon = wp_chainsaw;
}
else if (player->weaponowned[wp_missile]
&& player->ammo[am_misl])
{
player->pendingweapon = wp_missile;
}
else if (player->weaponowned[wp_bfg]
&& player->ammo[am_cell]>40
&& (gamemode != shareware) )
{
player->pendingweapon = wp_bfg;
}
else
{
// If everything fails.
player->pendingweapon = wp_fist;
}
} while (player->pendingweapon == wp_nochange);
// Now set appropriate weapon overlay.
P_SetPsprite (player,
ps_weapon,
weaponinfo[player->readyweapon].downstate);
return false;
}
//
// P_FireWeapon.
//
void P_FireWeapon (player_t* player)
{
statenum_t newstate;
if (!P_CheckAmmo (player))
return;
P_SetMobjState (player->mo, S_PLAY_ATK1);
newstate = weaponinfo[player->readyweapon].atkstate;
P_SetPsprite (player, ps_weapon, newstate);
P_NoiseAlert (player->mo, player->mo);
}
//
// P_DropWeapon
// Player died, so put the weapon away.
//
void P_DropWeapon (player_t* player)
{
P_SetPsprite (player,
ps_weapon,
weaponinfo[player->readyweapon].downstate);
}
//
// A_WeaponReady
// The player can fire the weapon
// or change to another weapon at this time.
// Follows after getting weapon up,
// or after previous attack/fire sequence.
//
void
A_WeaponReady
( player_t* player,
pspdef_t* psp )
{
statenum_t newstate;
int angle;
// get out of attack state
if (player->mo->state == &states[S_PLAY_ATK1]
|| player->mo->state == &states[S_PLAY_ATK2] )
{
P_SetMobjState (player->mo, S_PLAY);
}
if (player->readyweapon == wp_chainsaw
&& psp->state == &states[S_SAW])
{
S_StartSound (player->mo, sfx_sawidl);
}
// check for change
// if player is dead, put the weapon away
if (player->pendingweapon != wp_nochange || !player->health)
{
// change weapon
// (pending weapon should allready be validated)
newstate = weaponinfo[player->readyweapon].downstate;
P_SetPsprite (player, ps_weapon, newstate);
return;
}
// check for fire
// the missile launcher and bfg do not auto fire
if (player->cmd.buttons & BT_ATTACK)
{
if ( !player->attackdown
|| (player->readyweapon != wp_missile
&& player->readyweapon != wp_bfg) )
{
player->attackdown = true;
P_FireWeapon (player);
return;
}
}
else
player->attackdown = false;
// bob the weapon based on movement speed
angle = (128*leveltime)&FINEMASK;
psp->sx = FRACUNIT + FixedMul (player->bob, finecosine[angle]);
angle &= FINEANGLES/2-1;
psp->sy = WEAPONTOP + FixedMul (player->bob, finesine[angle]);
}
//
// A_ReFire
// The player can re-fire the weapon
// without lowering it entirely.
//
void A_ReFire
( player_t* player,
pspdef_t* psp )
{
// check for fire
// (if a weaponchange is pending, let it go through instead)
if ( (player->cmd.buttons & BT_ATTACK)
&& player->pendingweapon == wp_nochange
&& player->health)
{
player->refire++;
P_FireWeapon (player);
}
else
{
player->refire = 0;
P_CheckAmmo (player);
}
}
void
A_CheckReload
( player_t* player,
pspdef_t* psp )
{
P_CheckAmmo (player);
}
//
// A_Lower
// Lowers current weapon,
// and changes weapon at bottom.
//
void
A_Lower
( player_t* player,
pspdef_t* psp )
{
psp->sy += LOWERSPEED;
// Is already down.
if (psp->sy < WEAPONBOTTOM )
return;
// Player is dead.
if (player->playerstate == PST_DEAD)
{
psp->sy = WEAPONBOTTOM;
// don't bring weapon back up
return;
}
// The old weapon has been lowered off the screen,
// so change the weapon and start raising it
if (!player->health)
{
// Player is dead, so keep the weapon off screen.
P_SetPsprite (player, ps_weapon, S_NULL);
return;
}
player->readyweapon = player->pendingweapon;
P_BringUpWeapon (player);
}
//
// A_Raise
//
void
A_Raise
( player_t* player,
pspdef_t* psp )
{
statenum_t newstate;
psp->sy -= RAISESPEED;
if (psp->sy > WEAPONTOP )
return;
psp->sy = WEAPONTOP;
// The weapon has been raised all the way,
// so change to the ready state.
newstate = weaponinfo[player->readyweapon].readystate;
P_SetPsprite (player, ps_weapon, newstate);
}
//
// A_GunFlash
//
void
A_GunFlash
( player_t* player,
pspdef_t* psp )
{
P_SetMobjState (player->mo, S_PLAY_ATK2);
P_SetPsprite (player,ps_flash,weaponinfo[player->readyweapon].flashstate);
}
//
// WEAPON ATTACKS
//
//
// A_Punch
//
void
A_Punch
( player_t* player,
pspdef_t* psp )
{
angle_t angle;
int damage;
int slope;
damage = (P_Random ()%10+1)<<1;
if (player->powers[pw_strength])
damage *= 10;
angle = player->mo->angle;
angle += P_SubRandom() << 18;
slope = P_AimLineAttack (player->mo, angle, MELEERANGE);
P_LineAttack (player->mo, angle, MELEERANGE, slope, damage);
// turn to face target
if (linetarget)
{
S_StartSound (player->mo, sfx_punch);
player->mo->angle = R_PointToAngle2 (player->mo->x,
player->mo->y,
linetarget->x,
linetarget->y);
}
}
//
// A_Saw
//
void
A_Saw
( player_t* player,
pspdef_t* psp )
{
angle_t angle;
int damage;
int slope;
damage = 2*(P_Random ()%10+1);
angle = player->mo->angle;
angle += P_SubRandom() << 18;
// use meleerange + 1 se the puff doesn't skip the flash
slope = P_AimLineAttack (player->mo, angle, MELEERANGE+1);
P_LineAttack (player->mo, angle, MELEERANGE+1, slope, damage);
if (!linetarget)
{
S_StartSound (player->mo, sfx_sawful);
return;
}
S_StartSound (player->mo, sfx_sawhit);
// turn to face target
angle = R_PointToAngle2 (player->mo->x, player->mo->y,
linetarget->x, linetarget->y);
if (angle - player->mo->angle > ANG180)
{
if ((signed int) (angle - player->mo->angle) < -ANG90/20)
player->mo->angle = angle + ANG90/21;
else
player->mo->angle -= ANG90/20;
}
else
{
if (angle - player->mo->angle > ANG90/20)
player->mo->angle = angle - ANG90/21;
else
player->mo->angle += ANG90/20;
}
player->mo->flags |= MF_JUSTATTACKED;
}
// Doom does not check the bounds of the ammo array. As a result,
// it is possible to use an ammo type > 4 that overflows into the
// maxammo array and affects that instead. Through dehacked, for
// example, it is possible to make a weapon that decreases the max
// number of ammo for another weapon. Emulate this.
static void DecreaseAmmo(player_t *player, int ammonum, int amount)
{
if (ammonum < NUMAMMO)
{
player->ammo[ammonum] -= amount;
}
else
{
player->maxammo[ammonum - NUMAMMO] -= amount;
}
}
//
// A_FireMissile
//
void
A_FireMissile
( player_t* player,
pspdef_t* psp )
{
DecreaseAmmo(player, weaponinfo[player->readyweapon].ammo, 1);
P_SpawnPlayerMissile (player->mo, MT_ROCKET);
}
//
// A_FireBFG
//
void
A_FireBFG
( player_t* player,
pspdef_t* psp )
{
DecreaseAmmo(player, weaponinfo[player->readyweapon].ammo,
40);
P_SpawnPlayerMissile (player->mo, MT_BFG);
}
//
// A_FirePlasma
//
void
A_FirePlasma
( player_t* player,
pspdef_t* psp )
{
DecreaseAmmo(player, weaponinfo[player->readyweapon].ammo, 1);
P_SetPsprite (player,
ps_flash,
weaponinfo[player->readyweapon].flashstate+(P_Random ()&1) );
P_SpawnPlayerMissile (player->mo, MT_PLASMA);
}
//
// P_BulletSlope
// Sets a slope so a near miss is at aproximately
// the height of the intended target
//
fixed_t bulletslope;
void P_BulletSlope (mobj_t* mo)
{
angle_t an;
// see which target is to be aimed at
an = mo->angle;
bulletslope = P_AimLineAttack (mo, an, 16*64*FRACUNIT);
if (!linetarget)
{
an += 1<<26;
bulletslope = P_AimLineAttack (mo, an, 16*64*FRACUNIT);
if (!linetarget)
{
an -= 2<<26;
bulletslope = P_AimLineAttack (mo, an, 16*64*FRACUNIT);
}
}
}
//
// P_GunShot
//
void
P_GunShot
( mobj_t* mo,
boolean accurate )
{
angle_t angle;
int damage;
damage = 5*(P_Random ()%3+1);
angle = mo->angle;
if (!accurate)
angle += P_SubRandom() << 18;
P_LineAttack (mo, angle, MISSILERANGE, bulletslope, damage);
}
//
// A_FirePistol
//
void
A_FirePistol
( player_t* player,
pspdef_t* psp )
{
S_StartSound (player->mo, sfx_pistol);
P_SetMobjState (player->mo, S_PLAY_ATK2);
DecreaseAmmo(player, weaponinfo[player->readyweapon].ammo, 1);
P_SetPsprite (player,
ps_flash,
weaponinfo[player->readyweapon].flashstate);
P_BulletSlope (player->mo);
P_GunShot (player->mo, !player->refire);
}
//
// A_FireShotgun
//
void
A_FireShotgun
( player_t* player,
pspdef_t* psp )
{
int i;
S_StartSound (player->mo, sfx_shotgn);
P_SetMobjState (player->mo, S_PLAY_ATK2);
DecreaseAmmo(player, weaponinfo[player->readyweapon].ammo, 1);
P_SetPsprite (player,
ps_flash,
weaponinfo[player->readyweapon].flashstate);
P_BulletSlope (player->mo);
for (i=0 ; i<7 ; i++)
P_GunShot (player->mo, false);
}
//
// A_FireShotgun2
//
void
A_FireShotgun2
( player_t* player,
pspdef_t* psp )
{
int i;
angle_t angle;
int damage;
S_StartSound (player->mo, sfx_dshtgn);
P_SetMobjState (player->mo, S_PLAY_ATK2);
DecreaseAmmo(player, weaponinfo[player->readyweapon].ammo, 2);
P_SetPsprite (player,
ps_flash,
weaponinfo[player->readyweapon].flashstate);
P_BulletSlope (player->mo);
for (i=0 ; i<20 ; i++)
{
damage = 5*(P_Random ()%3+1);
angle = player->mo->angle;
angle += P_SubRandom() << ANGLETOFINESHIFT;
P_LineAttack (player->mo,
angle,
MISSILERANGE,
bulletslope + (P_SubRandom() << 5), damage);
}
}
//
// A_FireCGun
//
void
A_FireCGun
( player_t* player,
pspdef_t* psp )
{
S_StartSound (player->mo, sfx_pistol);
if (!player->ammo[weaponinfo[player->readyweapon].ammo])
return;
P_SetMobjState (player->mo, S_PLAY_ATK2);
DecreaseAmmo(player, weaponinfo[player->readyweapon].ammo, 1);
P_SetPsprite (player,
ps_flash,
weaponinfo[player->readyweapon].flashstate
+ psp->state
- &states[S_CHAIN1] );
P_BulletSlope (player->mo);
P_GunShot (player->mo, !player->refire);
}
//
// ?
//
void A_Light0 (player_t *player, pspdef_t *psp)
{
player->extralight = 0;
}
void A_Light1 (player_t *player, pspdef_t *psp)
{
player->extralight = 1;
}
void A_Light2 (player_t *player, pspdef_t *psp)
{
player->extralight = 2;
}
//
// A_BFGSpray
// Spawn a BFG explosion on every monster in view
//
void A_BFGSpray (mobj_t* mo)
{
int i;
int j;
int damage;
angle_t an;
// offset angles from its attack angle
for (i=0 ; i<40 ; i++)
{
an = mo->angle - ANG90/2 + ANG90/40*i;
// mo->target is the originator (player)
// of the missile
P_AimLineAttack (mo->target, an, 16*64*FRACUNIT);
if (!linetarget)
continue;
P_SpawnMobj (linetarget->x,
linetarget->y,
linetarget->z + (linetarget->height>>2),
MT_EXTRABFG);
damage = 0;
for (j=0;j<15;j++)
damage += (P_Random()&7) + 1;
P_DamageMobj (linetarget, mo->target,mo->target, damage);
}
}
//
// A_BFGsound
//
void
A_BFGsound
( player_t* player,
pspdef_t* psp )
{
S_StartSound (player->mo, sfx_bfg);
}
//
// P_SetupPsprites
// Called at start of level for each player.
//
void P_SetupPsprites (player_t* player)
{
int i;
// remove all psprites
for (i=0 ; i<NUMPSPRITES ; i++)
player->psprites[i].state = NULL;
// spawn the gun
player->pendingweapon = player->readyweapon;
P_BringUpWeapon (player);
}
//
// P_MovePsprites
// Called every tic by player thinking routine.
//
void P_MovePsprites (player_t* player)
{
int i;
pspdef_t* psp;
state_t* state;
psp = &player->psprites[0];
for (i=0 ; i<NUMPSPRITES ; i++, psp++)
{
// a null state means not active
if ( (state = psp->state) )
{
// drop tic count and possibly change state
// a -1 tic count never changes
if (psp->tics != -1)
{
psp->tics--;
if (!psp->tics)
P_SetPsprite (player, i, psp->state->nextstate);
}
}
}
player->psprites[ps_flash].sx = player->psprites[ps_weapon].sx;
player->psprites[ps_flash].sy = player->psprites[ps_weapon].sy;
}
| 412 | 0.967599 | 1 | 0.967599 | game-dev | MEDIA | 0.994323 | game-dev | 0.909179 | 1 | 0.909179 |
Szumi57/LethalInternship | 172,814 | LethalInternship.Core/Interns/AI/InternAI.cs | using GameNetcodeStuff;
using LethalInternship.Core.Interns.AI.BT;
using LethalInternship.Core.Interns.AI.TimedTasks;
using LethalInternship.Core.Managers;
using LethalInternship.Core.Utils;
using LethalInternship.SharedAbstractions.Adapters;
using LethalInternship.SharedAbstractions.Constants;
using LethalInternship.SharedAbstractions.Enums;
using LethalInternship.SharedAbstractions.Hooks.ModelReplacementAPIHooks;
using LethalInternship.SharedAbstractions.Hooks.PlayerControllerBHooks;
using LethalInternship.SharedAbstractions.Hooks.PluginLoggerHooks;
using LethalInternship.SharedAbstractions.Hooks.ReviveCompanyHooks;
using LethalInternship.SharedAbstractions.Interns;
using LethalInternship.SharedAbstractions.NetworkSerializers;
using LethalInternship.SharedAbstractions.Parameters;
using LethalInternship.SharedAbstractions.PluginRuntimeProvider;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.AI;
using Component = UnityEngine.Component;
using Quaternion = UnityEngine.Quaternion;
using Random = System.Random;
using Vector2 = UnityEngine.Vector2;
using Vector3 = UnityEngine.Vector3;
namespace LethalInternship.Core.Interns.AI
{
/// <summary>
/// AI for the intern.
/// </summary>
/// <remarks>
/// The AI is a component attached to the <c>GameObject</c> parent of the <c>PlayerControllerB</c> for the intern.<br/>
/// For moving the AI has a agent that pathfind to the next node each game loop,
/// the component moves by itself, detached from the body and the body (<c>PlayerControllerB</c>) moves toward it.<br/>
/// For piloting the body, we use <see cref="NpcController"><c>NpcController</c></see> that has a reference to the body (<c>PlayerControllerB</c>).<br/>
/// Then the AI class use its methods to pilot the body using <c>NpcController</c>.
/// The <c>NpcController</c> is set outside in <see cref="InternManager.InitInternSpawning"><c>InternManager.InitInternSpawning</c></see>.
/// </remarks>
public class InternAI : EnemyAI, IInternAI
{
public INpcController NpcController => npcController;
public PlayerControllerB Npc => npcController.Npc;
public IInternIdentity InternIdentity { get => internIdentity; set => internIdentity = value; }
public GameObject GameObject => this.gameObject;
public new ulong OwnerClientId => base.OwnerClientId;
public new NetworkObject NetworkObject => base.NetworkObject;
public Transform Transform => this.transform;
public IRagdollInternBody RagdollInternBody { get => ragdollInternBody; set => ragdollInternBody = value; }
public bool IsEnemyDead => base.isEnemyDead;
public new bool IsSpawned => base.IsSpawned;
public bool AnimationCoroutineRagdollingRunning => animationCoroutineRagdollingRunning;
public List<IBodyReplacementBase> ListModelReplacement { get => listModelReplacement; set => listModelReplacement = value; }
public GrabbableObject? HeldItem { get => heldItem; set => heldItem = value; }
private INpcController npcController = null!;
private IInternIdentity internIdentity = null!;
private IRagdollInternBody ragdollInternBody = null!;
public BTController BTController = null!;
public IPointOfInterest? PointOfInterest = null!;
public EnumCommandTypes CurrentCommand;
public bool CanRun = true; // const for now
public AudioSource InternVoice = null!;
/// <summary>
/// Currently held item by intern
/// </summary>
public Collider InternBodyCollider = null!;
private GrabbableObject? heldItem = null!;
public int InternId = -1;
public int MaxHealth = ConfigConst.DEFAULT_INTERN_MAX_HEALTH;
public float TimeSinceTeleporting = 0f;
private List<IBodyReplacementBase> listModelReplacement = null!;
public EntranceTeleport[] EntrancesTeleportArray = null!;
public TimedTouchingGroundCheck IsTouchingGroundTimedCheck = null!;
public TimedAngleFOVWithLocalPlayerCheck AngleFOVWithLocalPlayerTimedCheck = null!;
private TimedGetClosestPlayerDistance GetClosestPlayerDistanceTimed = null!;
public LineRendererUtil LineRendererUtil = null!;
private EnumStateControllerMovement StateControllerMovement;
private DoorLock[] doorLocksArray = null!;
private Dictionary<string, Component> dictComponentByCollider = null!;
private DeadBodyInfo ragdollBodyDeadBodyInfo = null!;
private Coroutine grabObjectCoroutine = null!;
private Coroutine? spawnAnimationCoroutine = null!;
private bool animationCoroutineRagdollingRunning = false;
private string stateIndicatorServer = string.Empty;
private float updateDestinationIntervalInternAI;
private float healthRegenerateTimerMax;
private float timerCheckDoor;
private void Awake()
{
// Behaviour states
currentBehaviourStateIndex = -1;
}
public void AdaptController(PlayerControllerB playerControllerB)
{
npcController = new NpcController(playerControllerB);
}
/// <summary>
/// Start unity method.
/// </summary>
/// <remarks>
/// The agent is initialized here
/// </remarks>
public override void Start()
{
// AIIntervalTime
AIIntervalTime = 0.3f;
try
{
// Ok so the unity project is so broken with this dll right now
// External mod dependencies chain nightmare
// So we initialize enemyType in the code, it's ugly sorry (but it works ;p)
EnemyType enemyTypeIntern = ScriptableObject.CreateInstance<EnemyType>();
enemyTypeIntern.name = "InternNPC";
enemyTypeIntern.enemyName = enemyTypeIntern.name;
enemyTypeIntern.doorSpeedMultiplier = 0.25f;
enemyTypeIntern.canDie = true;
this.enemyType = enemyTypeIntern;
gameObject.GetComponentInChildren<EnemyAICollisionDetect>().mainScript = this;
agent = gameObject.GetComponentInChildren<NavMeshAgent>();
agent.enabled = false;
skinnedMeshRenderers = gameObject.GetComponentsInChildren<SkinnedMeshRenderer>();
meshRenderers = gameObject.GetComponentsInChildren<MeshRenderer>();
if (creatureAnimator == null)
{
creatureAnimator = gameObject.GetComponentInChildren<Animator>();
}
thisNetworkObject = gameObject.GetComponentInChildren<NetworkObject>();
path1 = new NavMeshPath();
openDoorSpeedMultiplier = enemyType.doorSpeedMultiplier;
}
catch (Exception arg)
{
PluginLoggerHook.LogError?.Invoke(string.Format("Error when initializing intern variables for {0} : {1}", gameObject.name, arg));
}
}
/// <summary>
/// Initialization of the field.
/// </summary>
/// <remarks>
/// This method is used as an initialization and re-initialization too.
/// </remarks>
public void Init(EnumSpawnAnimation enumSpawnAnimation)
{
// Entrances
EntrancesTeleportArray = FindObjectsOfType<EntranceTeleport>(includeInactive: false);
// Doors
doorLocksArray = FindObjectsOfType<DoorLock>(includeInactive: false);
// Important colliders
InitImportantColliders();
// Model replacements
listModelReplacement = new List<IBodyReplacementBase>();
// Grabbableobject
InternManager.Instance.RegisterItems();
// Init controller
NpcController.Awake();
// Refresh billboard position
StartCoroutine(WaitSecondsForChangeSuitToApply());
// Health
MaxHealth = InternIdentity.HpMax;
NpcController.Npc.health = MaxHealth;
healthRegenerateTimerMax = 100f / MaxHealth;
NpcController.Npc.healthRegenerateTimer = healthRegenerateTimerMax;
// AI init
ventAnimationFinished = true;
isEnemyDead = false;
enabled = true;
addPlayerVelocityToDestination = 3f;
// Behavior tree
BTController = new BTController(this);
// Body collider
InternBodyCollider = NpcController.Npc.GetComponentInChildren<Collider>();
// Intern voice
InitInternVoiceComponent();
UpdateInternVoiceEffects();
// Line renderer used for debugging stuff
LineRendererUtil = new LineRendererUtil(20, transform);
TeleportAgentAIAndBody(NpcController.Npc.transform.position);
StateControllerMovement = EnumStateControllerMovement.FollowAgent;
// Start timed calculation
IsTouchingGroundTimedCheck = new TimedTouchingGroundCheck();
AngleFOVWithLocalPlayerTimedCheck = new TimedAngleFOVWithLocalPlayerCheck();
// Spawn animation
spawnAnimationCoroutine = BeginInternSpawnAnimation(enumSpawnAnimation);
}
private void InitInternVoiceComponent()
{
if (creatureVoice == null)
{
foreach (var component in gameObject.GetComponentsInChildren<AudioSource>())
{
if (component.name == "CreatureVoice")
{
creatureVoice = component;
break;
}
}
}
if (creatureVoice == null)
{
PluginLoggerHook.LogWarning?.Invoke($"Could not initialize intern {InternId} {NpcController.Npc.playerUsername} voice !");
return;
}
NpcController.Npc.currentVoiceChatAudioSource = creatureVoice;
InternVoice = NpcController.Npc.currentVoiceChatAudioSource;
InternVoice.enabled = true;
InternIdentity.Voice.InternID = InternId;
InternIdentity.Voice.CurrentAudioSource = InternVoice;
// OccludeAudio
NpcController.OccludeAudioComponent = creatureVoice.GetComponent<OccludeAudio>();
// AudioLowPassFilter
AudioLowPassFilter? audioLowPassFilter = creatureVoice.GetComponent<AudioLowPassFilter>();
if (audioLowPassFilter == null)
{
audioLowPassFilter = creatureVoice.gameObject.AddComponent<AudioLowPassFilter>();
}
NpcController.AudioLowPassFilterComponent = audioLowPassFilter;
// AudioHighPassFilter
AudioHighPassFilter? audioHighPassFilter = creatureVoice.GetComponent<AudioHighPassFilter>();
if (audioHighPassFilter == null)
{
audioHighPassFilter = creatureVoice.gameObject.AddComponent<AudioHighPassFilter>();
}
NpcController.AudioHighPassFilterComponent = audioHighPassFilter;
// AudioMixerGroup
if ((int)NpcController.Npc.playerClientId >= SoundManager.Instance.playerVoiceMixers.Length)
{
// Because of morecompany, playerVoiceMixers gets somehow resized down
InternManager.Instance.ResizePlayerVoiceMixers(InternManager.Instance.AllEntitiesCount);
}
InternVoice.outputAudioMixerGroup = SoundManager.Instance.playerVoiceMixers[(int)NpcController.Npc.playerClientId];
}
private void FixedUpdate()
{
if (NpcController == null)
{
// Intern AI not init
return;
}
UpdateSurfaceRayCast();
}
private void UpdateSurfaceRayCast()
{
NpcController.IsTouchingGround = IsTouchingGroundTimedCheck.IsTouchingGround(NpcController.Npc.thisPlayerBody.position);
// Update current material standing on
if (NpcController.IsTouchingGround)
{
RaycastHit groundRaycastHit = IsTouchingGroundTimedCheck.GetGroundHit(NpcController.Npc.thisPlayerBody.position);
if (InternManager.Instance.DictTagSurfaceIndex.ContainsKey(groundRaycastHit.collider.tag))
{
NpcController.Npc.currentFootstepSurfaceIndex = InternManager.Instance.DictTagSurfaceIndex[groundRaycastHit.collider.tag];
}
}
}
/// <summary>
/// Update unity method.
/// </summary>
/// <remarks>
/// The AI does not calculate each frame but use a timer <c>updateDestinationIntervalInternAI</c>
/// to update every some number of ms.
/// </remarks>
public override void Update()
{
if (NpcController == null)
{
// Intern AI not init
return;
}
// Update identity
InternIdentity.Hp = NpcController.Npc.isPlayerDead ? 0 : NpcController.Npc.health;
// Not owner no AI
if (!IsOwner)
{
if (currentSearch.inProgress)
{
StopSearch(currentSearch);
}
SetAgent(enabled: false);
return;
}
if (!NpcController.Npc.gameObject.activeSelf
|| !NpcController.Npc.isPlayerControlled
|| isEnemyDead
|| NpcController.Npc.isPlayerDead)
{
// Intern dead or
// Not controlled we do nothing
SetAgent(enabled: false);
return;
}
// No AI calculation if in special animation
if (inSpecialAnimation
|| (RagdollInternBody != null && RagdollInternBody.IsRagdollBodyHeld()))
{
SetAgent(enabled: false);
return;
}
// No AI calculation if in special animation if climbing ladder or inSpecialInteractAnimation
if (!NpcController.Npc.isClimbingLadder
&& (NpcController.Npc.inSpecialInteractAnimation || NpcController.Npc.enteringSpecialAnimation))
{
SetAgent(enabled: false);
return;
}
// Update movement
float x;
float z;
if (NpcController.HasToMove)
{
Vector2 vector2 = new Vector2(NpcController.MoveVector.x, NpcController.MoveVector.z);
agent.speed = 1f * vector2.magnitude;
if (!NpcController.Npc.isClimbingLadder
&& !NpcController.Npc.inSpecialInteractAnimation
&& !NpcController.Npc.enteringSpecialAnimation)
{
// Npc is following ai agent position that follows destination path
NpcController.SetTurnBodyTowardsDirectionWithPosition(transform.position);
}
x = Mathf.Lerp(NpcController.Npc.transform.position.x, transform.position.x, 0.075f);
z = Mathf.Lerp(NpcController.Npc.transform.position.z, transform.position.z, 0.075f);
}
else
{
SetAgent(enabled: false);
x = Mathf.Lerp(NpcController.Npc.transform.position.x + NpcController.MoveVector.x * Time.deltaTime, transform.position.x, 0.075f);
z = Mathf.Lerp(NpcController.Npc.transform.position.z + NpcController.MoveVector.z * Time.deltaTime, transform.position.z, 0.075f);
}
// Movement free (falling from bridge, jetpack, tulip snake taking off...)
bool shouldFreeMovement = ShouldFreeMovement();
// Update position
if (shouldFreeMovement
|| StateControllerMovement == EnumStateControllerMovement.Free)
{
StateControllerMovement = EnumStateControllerMovement.Free;
//PluginLoggerHook.LogDebug?.Invoke($"{NpcController.Npc.playerUsername} falling ! NpcController.Npc.transform.position {NpcController.Npc.transform.position} MoveVector {NpcController.MoveVector}");
NpcController.Npc.transform.position = NpcController.Npc.transform.position + NpcController.MoveVector * Time.deltaTime;
}
else if (StateControllerMovement == EnumStateControllerMovement.FollowAgent)
{
Vector3 aiPosition = transform.position;
NpcController.Npc.transform.position = new Vector3(x,
aiPosition.y,
z); ;
transform.position = aiPosition;
NpcController.Npc.ResetFallGravity();
}
// Is still falling ?
if (StateControllerMovement == EnumStateControllerMovement.Free
&& IsTouchingGroundTimedCheck.IsTouchingGround(NpcController.Npc.thisPlayerBody.position)
&& !shouldFreeMovement)
{
//PluginLoggerHook.LogDebug?.Invoke($"{NpcController.Npc.playerUsername} ============= touch ground GroundHit.point {NpcController.GroundHit.point}");
StateControllerMovement = EnumStateControllerMovement.FollowAgent;
TeleportAgentAIAndBody(IsTouchingGroundTimedCheck.GetGroundHit(NpcController.Npc.thisPlayerBody.position).point);
//PluginLoggerHook.LogDebug?.Invoke($"{NpcController.Npc.playerUsername} ============= NpcController.Npc.transform.position {NpcController.Npc.transform.position}");
}
// No AI when falling
if (StateControllerMovement == EnumStateControllerMovement.Free)
{
return;
}
if (ShouldDoAIInterval())
{
DoAIInterval();
}
}
private bool ShouldDoAIInterval()
{
// Update interval timer for AI calculation
if (updateDestinationIntervalInternAI >= 0f)
{
updateDestinationIntervalInternAI -= Time.deltaTime;
return false;
}
if (InternManager.Instance.GetCurrentBatch() == (int)Npc.playerClientId)
{
//PluginLoggerHook.LogDebug?.Invoke($"Current batch for intern ! id {Npc.playerClientId}");
return false;
}
// Reset time
updateDestinationIntervalInternAI = AIIntervalTime;
return true;
}
/// <summary>
/// Where the AI begin its calculations.
/// </summary>
/// <remarks>
/// For the behaviour of the AI, we use a behaviour tree
/// </remarks>
public override void DoAIInterval()
{
SetAgent(enabled: true);
if (isEnemyDead
|| NpcController.Npc.isPlayerDead
|| (RagdollInternBody != null && RagdollInternBody.IsRagdollBodyHeld()))
{
return;
}
BTController.TickTree(AIIntervalTime);
// Doors
OpenDoorIfNeeded();
}
#region Commands
public IPointOfInterest? GetPointOfInterest()
{
if (InternManager.Instance.CheckAndClearInvalidPointOfInterest(this.PointOfInterest))
{
this.PointOfInterest = null;
return null;
}
return this.PointOfInterest;
}
public void SetCommandTo(IPointOfInterest pointOfInterest)
{
this.PointOfInterest = pointOfInterest;
EnumCommandTypes? newCommand = pointOfInterest.GetCommand();
if (newCommand == null)
{
SetCommandToFollowPlayer();
return;
}
CurrentCommand = newCommand.Value;
PluginLoggerHook.LogDebug?.Invoke($"SetCommandTo {CurrentCommand}");
PluginLoggerHook.LogDebug?.Invoke($"VVV PointOfInterest VVV");
foreach (var p in this.PointOfInterest.GetListInterestPoints())
{
PluginLoggerHook.LogDebug?.Invoke($"Interest point {p.GetType()}");
}
// AI batch
InternManager.Instance.CancelBatch((int)Npc.playerClientId);
// Voice
TryPlayCurrentOrderVoiceAudio(EnumVoicesState.OrderedToGoThere);
}
public void SetCommandToFollowPlayer()
{
CurrentCommand = EnumCommandTypes.FollowPlayer;
this.PointOfInterest = null;
PluginLoggerHook.LogDebug?.Invoke($"SetCommandToFollowPlayer");
// AI batch
InternManager.Instance.CancelBatch((int)Npc.playerClientId);
// Voice
TryPlayCurrentOrderVoiceAudio(EnumVoicesState.OrderedToFollow);
}
private void TryPlayCurrentOrderVoiceAudio(EnumVoicesState enumVoicesState)
{
// Default states, wait for cooldown and if no one is talking close
this.InternIdentity.Voice.TryPlayVoiceAudio(new PlayVoiceParameters()
{
VoiceState = enumVoicesState,
CanTalkIfOtherInternTalk = false,
WaitForCooldown = false,
CutCurrentVoiceStateToTalk = true,
CanRepeatVoiceState = false,
ShouldSync = true,
IsInternInside = this.NpcController.Npc.isInsideFactory,
AllowSwearing = PluginRuntimeProvider.Context.Config.AllowSwearing
});
}
#endregion
public void UpdateController()
{
if (RagdollInternBody != null
&& RagdollInternBody.IsRagdollBodyHeld())
{
return;
}
if (NpcController.IsControllerInCruiser)
{
return;
}
NpcController.Update();
}
private void LateUpdate()
{
if (NpcController == null)
{
// Intern AI not init
return;
}
// Update voice position
InternVoice.transform.position = NpcController.Npc.gameplayCamera.transform.position;
}
private bool ShouldFreeMovement()
{
if (IsTouchingGroundTimedCheck.IsTouchingGround(NpcController.Npc.thisPlayerBody.position)
&& dictComponentByCollider.TryGetValue(IsTouchingGroundTimedCheck.GetGroundHit(NpcController.Npc.thisPlayerBody.position).collider.name, out Component component))
{
BridgeTrigger? bridgeTrigger = component as BridgeTrigger;
if (bridgeTrigger != null
&& bridgeTrigger.fallenBridgeColliders.Length > 0
&& bridgeTrigger.fallenBridgeColliders[0].enabled)
{
PluginLoggerHook.LogDebug?.Invoke($"{NpcController.Npc.playerUsername} on fallen bridge ! {IsTouchingGroundTimedCheck.GetGroundHit(NpcController.Npc.thisPlayerBody.position).collider.name}");
return true;
}
}
if (NpcController.Npc.externalForces.y > 7.1f)
{
PluginLoggerHook.LogDebug?.Invoke($"{NpcController.Npc.playerUsername} externalForces.y {NpcController.Npc.externalForces.y}");
return true;
}
return false;
}
public void FollowCrouchIfCanDo(bool panik = false)
{
if (panik
&& NpcController.Npc.isCrouching)
{
NpcController.OrderToToggleCrouch();
return;
}
if (PluginRuntimeProvider.Context.Config.FollowCrouchWithPlayer
&& targetPlayer != null)
{
if (targetPlayer.isCrouching
&& !NpcController.Npc.isCrouching)
{
NpcController.OrderToToggleCrouch();
}
else if (!targetPlayer.isCrouching
&& NpcController.Npc.isCrouching)
{
NpcController.OrderToToggleCrouch();
}
}
}
public override void OnCollideWithPlayer(Collider other)
{
if (other.CompareTag("Player"))
{
PlayerControllerB componentPlayer = other.GetComponent<PlayerControllerB>();
if (componentPlayer != null
&& !InternManager.Instance.IsPlayerIntern(componentPlayer))
{
NpcController.NearEntitiesPushVector += Vector3.Normalize((NpcController.Npc.transform.position - other.transform.position) * 100f) * 1.2f;
}
}
}
public override void OnCollideWithEnemy(Collider other, EnemyAI collidedEnemy)
{
if (!IsOwner)
{
return;
}
if (collidedEnemy == null
|| collidedEnemy.GetType() == typeof(InternAI)
|| collidedEnemy.GetType() == typeof(FlowerSnakeEnemy))
{
return;
}
if ((NpcController.Npc.transform.position - other.transform.position).sqrMagnitude < collidedEnemy.enemyType.pushPlayerDistance * collidedEnemy.enemyType.pushPlayerDistance)
{
NpcController.NearEntitiesPushVector += Vector3.Normalize((NpcController.Npc.transform.position - other.transform.position) * 100f) * collidedEnemy.enemyType.pushPlayerForce;
}
// Enemy collide with the intern collider
collidedEnemy.OnCollideWithPlayer(InternBodyCollider);
}
public override void DetectNoise(Vector3 noisePosition, float noiseLoudness, int timesPlayedInOneSpot = 0, int noiseID = 0)
{
if (NpcController == null
|| !NpcController.Npc.gameObject.activeSelf
|| !NpcController.Npc.isPlayerControlled
|| isEnemyDead
|| NpcController.Npc.isPlayerDead)
{
return;
}
// Player voice = 75 ?
if (noiseID != 75)
{
return;
}
// Make the intern stop talking for some time
InternIdentity.Voice.TryStopAudioFadeOut();
if (IsOwner)
{
InternIdentity.Voice.SetNewRandomCooldownAudio();
}
PluginLoggerHook.LogDebug?.Invoke($"Intern {NpcController.Npc.playerUsername} detected noise noisePosition {noisePosition}, noiseLoudness {noiseLoudness}, timesPlayedInOneSpot {timesPlayedInOneSpot}, noiseID {noiseID}");
// Player heard
// todo : BT
}
public void SetAgent(bool enabled)
{
if (agent != null)
{
agent.enabled = enabled;
}
}
public bool IsAgentInValidState()
{
if (agent.isActiveAndEnabled
&& agent.isOnNavMesh
&& !isEnemyDead
&& !NpcController.Npc.isPlayerDead
&& !StartOfRound.Instance.shipIsLeaving)
{
return true;
}
return false;
}
/// <summary>
/// Set the destination in <c>EnemyAI</c>, not on the agent
/// </summary>
/// <param name="position">the destination</param>
public void SetDestinationToPositionInternAI(Vector3 position)
{
moveTowardsDestination = true;
movingTowardsTargetPlayer = false;
destination = position;
}
/// <summary>
/// Try to set the destination on the agent, if destination not reachable, try the closest possible position of the destination
/// </summary>
public void UpdateDestinationToAgent(bool calculatePartialPath = false, bool checkForPath = false)
{
if (IsAgentInValidState()
&& agent.destination != base.destination)
{
agent.SetDestination(destination);
}
}
public void OrderAgentAndBodyMoveToDestination(bool calculatePartialPath = false, bool checkForPath = false)
{
NpcController.OrderToMove();
UpdateDestinationToAgent(calculatePartialPath, checkForPath);
}
public void StopMoving()
{
if (NpcController.HasToMove)
{
NpcController.OrderToStopMoving();
}
}
/// <summary>
/// Is the current client running the code is the owner of the <c>InternAI</c> ?
/// </summary>
/// <returns></returns>
public bool IsClientOwnerOfIntern()
{
return OwnerClientId == GameNetworkManager.Instance.localPlayerController.actualClientId;
}
private int MaxHealthPercent(int percentage)
{
return InternManager.Instance.MaxHealthPercent(percentage, MaxHealth);
}
public void CheckAndBringCloserTeleportIntern(float percentageOfDestination)
{
bool isAPlayerSeeingIntern = false;
StartOfRound instanceSOR = StartOfRound.Instance;
Transform thisInternCamera = NpcController.Npc.gameplayCamera.transform;
PlayerControllerB player;
Vector3 vectorPlayerToIntern;
Vector3 internDestination = NpcController.Npc.thisPlayerBody.transform.position + (destination - NpcController.Npc.transform.position) * percentageOfDestination;
Vector3 internBodyDestination = internDestination + new Vector3(0, 1f, 0);
for (int i = 0; i < InternManager.Instance.IndexBeginOfInterns; i++)
{
player = instanceSOR.allPlayerScripts[i];
if (player.isPlayerDead
|| !player.isPlayerControlled)
{
continue;
}
// No obsruction
if (!Physics.Linecast(player.gameplayCamera.transform.position, thisInternCamera.position, StartOfRound.Instance.collidersAndRoomMaskAndDefault))
{
vectorPlayerToIntern = thisInternCamera.position - player.gameplayCamera.transform.position;
if (Vector3.Angle(player.gameplayCamera.transform.forward, vectorPlayerToIntern) < player.gameplayCamera.fieldOfView)
{
isAPlayerSeeingIntern = true;
break;
}
}
if (!Physics.Linecast(player.gameplayCamera.transform.position, internBodyDestination, StartOfRound.Instance.collidersAndRoomMaskAndDefault))
{
vectorPlayerToIntern = internBodyDestination - player.gameplayCamera.transform.position;
if (Vector3.Angle(player.gameplayCamera.transform.forward, vectorPlayerToIntern) < player.gameplayCamera.fieldOfView)
{
isAPlayerSeeingIntern = true;
break;
}
}
}
if (!isAPlayerSeeingIntern)
{
TeleportIntern(internDestination);
}
}
/// <summary>
/// Check the line of sight if the intern can see the target player
/// </summary>
/// <param name="width">FOV of the intern</param>
/// <param name="range">Distance max for seeing something</param>
/// <param name="proximityAwareness">Distance where the interns "sense" the player, in line of sight or not. -1 for no proximity awareness</param>
/// <returns>Target player <c>PlayerControllerB</c> or null</returns>
public PlayerControllerB? CheckLOSForTarget(float width = 45f, int range = 60, int proximityAwareness = -1)
{
if (targetPlayer == null)
{
return null;
}
if (!PlayerIsTargetable(targetPlayer))
{
return null;
}
// Fog reduce the visibility
if (isOutside && !enemyType.canSeeThroughFog && TimeOfDay.Instance.currentLevelWeather == LevelWeatherType.Foggy)
{
range = Mathf.Clamp(range, 0, 30);
}
// Check for target player
Transform thisInternCamera = NpcController.Npc.gameplayCamera.transform;
Vector3 posTargetCamera = targetPlayer.gameplayCamera.transform.position;
if (Vector3.Distance(posTargetCamera, thisInternCamera.position) < range
&& !Physics.Linecast(thisInternCamera.position, posTargetCamera, StartOfRound.Instance.collidersAndRoomMaskAndDefault))
{
// Target close enough and nothing in between to break line of sight
Vector3 to = posTargetCamera - thisInternCamera.position;
if (Vector3.Angle(thisInternCamera.forward, to) < width
|| proximityAwareness != -1 && Vector3.Distance(thisInternCamera.position, posTargetCamera) < proximityAwareness)
{
// Target in FOV or proximity awareness range
return targetPlayer;
}
}
return null;
}
/// <summary>
/// Check the line of sight if the intern can see any player and take the closest.
/// </summary>
/// <param name="width">FOV of the intern</param>
/// <param name="range">Distance max for seeing something</param>
/// <param name="proximityAwareness">Distance where the interns "sense" the player, in line of sight or not. -1 for no proximity awareness</param>
/// <param name="bufferDistance"></param>
/// <returns>Target player <c>PlayerControllerB</c> or null</returns>
public PlayerControllerB? CheckLOSForClosestPlayer(float width = 45f, int range = 60, int proximityAwareness = -1, float bufferDistance = 0f)
{
// Fog reduce the visibility
if (isOutside && !enemyType.canSeeThroughFog && TimeOfDay.Instance.currentLevelWeather == LevelWeatherType.Foggy)
{
range = Mathf.Clamp(range, 0, 30);
}
StartOfRound instanceSOR = StartOfRound.Instance;
Transform thisInternCamera = NpcController.Npc.gameplayCamera.transform;
float currentClosestDistance = 1000f;
int indexPlayer = -1;
for (int i = 0; i < InternManager.Instance.IndexBeginOfInterns; i++)
{
PlayerControllerB player = instanceSOR.allPlayerScripts[i];
if (!player.isPlayerControlled || player.isPlayerDead)
{
continue;
}
// Target close enough ?
Vector3 cameraPlayerPosition = player.gameplayCamera.transform.position;
if ((cameraPlayerPosition - transform.position).sqrMagnitude > range * range)
{
continue;
}
if (!PlayerIsTargetable(player))
{
continue;
}
// Nothing in between to break line of sight ?
if (Physics.Linecast(thisInternCamera.position, cameraPlayerPosition, instanceSOR.collidersAndRoomMaskAndDefault))
{
continue;
}
Vector3 vectorInternToPlayer = cameraPlayerPosition - thisInternCamera.position;
float distanceInternToPlayer = Vector3.Distance(thisInternCamera.position, cameraPlayerPosition);
if ((Vector3.Angle(thisInternCamera.forward, vectorInternToPlayer) < width || proximityAwareness != -1 && distanceInternToPlayer < proximityAwareness)
&& distanceInternToPlayer < currentClosestDistance)
{
// Target in FOV or proximity awareness range
currentClosestDistance = distanceInternToPlayer;
indexPlayer = i;
}
}
if (targetPlayer != null
&& indexPlayer != -1
&& targetPlayer != instanceSOR.allPlayerScripts[indexPlayer]
&& bufferDistance > 0f
&& Mathf.Abs(currentClosestDistance - Vector3.Distance(transform.position, targetPlayer.transform.position)) < bufferDistance)
{
return null;
}
if (indexPlayer < 0)
{
return null;
}
mostOptimalDistance = currentClosestDistance;
return instanceSOR.allPlayerScripts[indexPlayer];
}
/// <summary>
/// Check if enemy in line of sight.
/// </summary>
/// <param name="width">FOV of the intern</param>
/// <param name="range">Distance max for seeing something</param>
/// <param name="proximityAwareness">Distance where the interns "sense" the player, in line of sight or not. -1 for no proximity awareness</param>
/// <returns>Enemy <c>EnemyAI</c> or null</returns>
public EnemyAI? CheckLOSForEnemy(float width = 45f, int range = 20, int proximityAwareness = -1)
{
// Fog reduce the visibility
if (isOutside && !enemyType.canSeeThroughFog && TimeOfDay.Instance.currentLevelWeather == LevelWeatherType.Foggy)
{
range = Mathf.Clamp(range, 0, 30);
}
StartOfRound instanceSOR = StartOfRound.Instance;
RoundManager instanceRM = RoundManager.Instance;
Transform thisInternCamera = NpcController.Npc.gameplayCamera.transform;
int index = -1;
foreach (EnemyAI spawnedEnemy in instanceRM.SpawnedEnemies)
{
index++;
if (spawnedEnemy.isEnemyDead)
{
continue;
}
// Enemy close enough ?
Vector3 positionEnemy = spawnedEnemy.transform.position;
Vector3 directionEnemyFromCamera = positionEnemy - thisInternCamera.position;
float sqrDistanceToEnemy = directionEnemyFromCamera.sqrMagnitude;
if (sqrDistanceToEnemy > range * range)
{
continue;
}
// Obstructed
if (Physics.Linecast(thisInternCamera.position, positionEnemy, instanceSOR.collidersAndRoomMaskAndDefault))
{
continue;
}
// Fear range
float? fearRange = GetFearRangeForEnemies(spawnedEnemy);
if (!fearRange.HasValue)
{
continue;
}
if (sqrDistanceToEnemy > fearRange * fearRange)
{
continue;
}
// Enemy in distance of fear range
// Proximity awareness, danger
if (proximityAwareness > -1
&& sqrDistanceToEnemy < proximityAwareness * (float)proximityAwareness)
{
PluginLoggerHook.LogDebug?.Invoke($"{NpcController.Npc.playerUsername} DANGER CLOSE \"{spawnedEnemy.enemyType.enemyName}\" {spawnedEnemy.enemyType.name}");
return instanceRM.SpawnedEnemies[index];
}
// Line of Sight, danger
if (Vector3.Angle(thisInternCamera.forward, directionEnemyFromCamera) < width)
{
PluginLoggerHook.LogDebug?.Invoke($"{NpcController.Npc.playerUsername} DANGER LOS \"{spawnedEnemy.enemyType.enemyName}\" {spawnedEnemy.enemyType.name}");
return instanceRM.SpawnedEnemies[index];
}
}
return null;
}
/// <summary>
/// Check for, an enemy, the minimal distance from enemy to intern before panicking.
/// </summary>
/// <param name="enemy">Enemy to check</param>
/// <returns>The minimal distance from enemy to intern before panicking, null if nothing to worry about</returns>
public float? GetFearRangeForEnemies(EnemyAI enemy)
{
//PluginLoggerHook.LogDebug?.Invoke($"enemy \"{enemy.enemyType.enemyName}\" {enemy.enemyType.name}");
switch (enemy.enemyType.enemyName) // using enemyName
{
case "Crawler":
case "MouthDog":
case "ForestGiant":
case "Butler Bees":
case "Nutcracker":
case "Blob":
case "ImmortalSnail":
return 15f;
case "Red Locust Bees":
case "Earth Leviathan":
case "Clay Surgeon":
case "Flowerman":
case "Bush Wolf":
case "GiantKiwi":
return 5f;
case "Puffer":
return 2f;
case "Centipede":
return 1f;
case "Bunker Spider":
if (enemy.currentBehaviourStateIndex == 2)
{
// Mad
return 15f;
}
else
{
return null;
}
case "Spring":
if (enemy.currentBehaviourStateIndex > 0)
{
// Mad
return 15f;
}
else
{
return null;
}
case "Butler":
if (enemy.currentBehaviourStateIndex == 2)
{
// Mad
return 15f;
}
else
{
return null;
}
case "Hoarding bug":
if (enemy.currentBehaviourStateIndex == 2)
{
// Mad
return 15f;
}
else
{
return null;
}
case "Jester":
if (enemy.currentBehaviourStateIndex == 2)
{
// Mad
return 15f;
}
else
{
return null;
}
case "RadMech":
if (enemy.currentBehaviourStateIndex > 0)
{
// Mad
return 15f;
}
else
{
return null;
}
case "Baboon hawk":
if (enemy.currentBehaviourStateIndex == 2)
{
// Mad
return 15f;
}
else
{
return null;
}
case "Maneater":
if (enemy.currentBehaviourStateIndex > 0)
{
// Mad
return 15f;
}
else
{
return null;
}
default:
// Not dangerous enemies (at first sight)
// "Docile Locust Bees"
// "Manticoil"
// "Masked"
// "Girl"
// "Tulip Snake"
return null;
}
}
public void ReParentIntern(Transform newParent)
{
NpcController.ReParentNotSpawnedTransform(newParent);
}
public string GetSizedBillboardStateIndicator()
{
string indicator;
int sizePercentage = Math.Clamp((int)(100f + 2.5f * NpcController.GetSqrDistanceWithLocalPlayer(NpcController.Npc.transform.position)),
100, 500);
if (IsOwner)
{
//indicator = State == null ? string.Empty : State.GetBillboardStateIndicator();
indicator = string.Empty;
}
else
{
indicator = stateIndicatorServer;
}
return $"<size={sizePercentage}%>{indicator}</size>";
}
/// <summary>
/// Search for all the loaded ladders on the map.
/// </summary>
/// <returns>Array of <c>InteractTrigger</c> (ladders)</returns>
private InteractTrigger[] RefreshLaddersList()
{
List<InteractTrigger> ladders = new List<InteractTrigger>();
InteractTrigger[] interactsTrigger = Resources.FindObjectsOfTypeAll<InteractTrigger>();
for (int i = 0; i < interactsTrigger.Length; i++)
{
if (interactsTrigger[i] == null)
{
continue;
}
if (interactsTrigger[i].isLadder && interactsTrigger[i].ladderHorizontalPosition != null)
{
ladders.Add(interactsTrigger[i]);
}
}
return ladders.ToArray();
}
/// <summary>
/// Check every ladder to see if the body of intern is close to either the bottom of the ladder (wants to go up) or the top of the ladder (wants to go down).
/// Orders the controller to set field <c>hasToGoDown</c>.
/// </summary>
/// <returns>The ladder to use, null if nothing close</returns>
public InteractTrigger? GetLadderIfWantsToUseLadder()
{
//InteractTrigger ladder;
//Vector3 npcBodyPos = NpcController.Npc.thisController.transform.position;
//for (int i = 0; i < laddersInteractTrigger.Length; i++)
//{
// ladder = laddersInteractTrigger[i];
// Vector3 ladderBottomPos = ladder.bottomOfLadderPosition.position;
// Vector3 ladderTopPos = ladder.topOfLadderPosition.position;
// if ((ladderBottomPos - npcBodyPos).sqrMagnitude < Const.DISTANCE_NPCBODY_FROM_LADDER * Const.DISTANCE_NPCBODY_FROM_LADDER)
// {
// PluginLoggerHook.LogDebug?.Invoke($"{NpcController.Npc.playerUsername} Wants to go up on ladder");
// // Wants to go up on ladder
// NpcController.OrderToGoUpDownLadder(hasToGoDown: false);
// return ladder;
// }
// else if ((ladderTopPos - npcBodyPos).sqrMagnitude < Const.DISTANCE_NPCBODY_FROM_LADDER * Const.DISTANCE_NPCBODY_FROM_LADDER)
// {
// PluginLoggerHook.LogDebug?.Invoke($"{NpcController.Npc.playerUsername} Wants to go down on ladder");
// // Wants to go down on ladder
// NpcController.OrderToGoUpDownLadder(hasToGoDown: true);
// return ladder;
// }
//}
return null;
}
/// <summary>
/// Check all doors to know if the intern is close enough to it to open it if necessary.
/// </summary>
/// <returns></returns>
public DoorLock? GetDoorIfWantsToOpen()
{
Vector3 npcBodyPos = NpcController.Npc.thisController.transform.position;
foreach (var door in doorLocksArray.Where(x => !x.isLocked))
{
if ((door.transform.position - npcBodyPos).sqrMagnitude < Const.DISTANCE_NPCBODY_FROM_DOOR * Const.DISTANCE_NPCBODY_FROM_DOOR)
{
return door;
}
}
return null;
}
/// <summary>
/// Check the doors after some interval of ms to see if intern can open one to unstuck himself.
/// </summary>
/// <returns>true: a door has been opened by intern. Else false</returns>
private bool OpenDoorIfNeeded()
{
if (timerCheckDoor > Const.TIMER_CHECK_DOOR)
{
timerCheckDoor = 0f;
DoorLock? door = GetDoorIfWantsToOpen();
if (door != null)
{
// Prevent stuck behind open door
Physics.IgnoreCollision(NpcController.Npc.playerCollider, door.GetComponent<Collider>());
// Open door
door.OpenOrCloseDoor(NpcController.Npc);
door.OpenDoorAsEnemyServerRpc();
return true;
}
}
timerCheckDoor += AIIntervalTime;
return false;
}
/// <summary>
/// Check ladders if intern needs to use one to follow player.
/// </summary>
/// <returns>true: the intern is using or is waiting to use the ladder, else false</returns>
private bool UseLadderIfNeeded()
{
//if (NpcController.Npc.isClimbingLadder)
//{
// return true;
//}
//InteractTrigger? ladder = GetLadderIfWantsToUseLadder();
//if (ladder == null)
//{
// return false;
//}
//// Intern wants to use ladder
//// Removing all that for the moment
////if (PluginRuntimeProvider.Context.Config.TeleportWhenUsingLadders.Value)
////{
//// NpcController.Npc.transform.position = this.transform.position;
//// return true;
////}
//// Try to use ladder
//if (NpcController.CanUseLadder(ladder))
//{
// InteractTriggerPatch.Interact_ReversePatch(ladder, NpcController.Npc.thisPlayerBody);
// // Set rotation of intern to face ladder
// NpcController.Npc.transform.rotation = ladder.ladderPlayerPositionNode.transform.rotation;
// NpcController.SetTurnBodyTowardsDirection(NpcController.Npc.transform.forward);
//}
//else
//{
// // Wait to use ladder
// StopMoving();
//}
return true;
}
/// <summary>
/// Is the intern holding an item ?
/// </summary>
/// <returns>I mean come on</returns>
public bool AreHandsFree()
{
return HeldItem == null;
}
/// <summary>
/// Check all conditions for deciding if an item is grabbable or not.
/// </summary>
/// <param name="grabbableObject">Item to check</param>
/// <returns></returns>
public bool IsGrabbableObjectGrabbable(GrabbableObject grabbableObject)
{
if (grabbableObject == null
|| !grabbableObject.gameObject.activeSelf)
{
return false;
}
if (grabbableObject.isHeld
|| !grabbableObject.grabbable
|| grabbableObject.deactivated)
{
return false;
}
RagdollGrabbableObject? ragdollGrabbableObject = grabbableObject as RagdollGrabbableObject;
if (ragdollGrabbableObject != null)
{
if (!ragdollGrabbableObject.grabbableToEnemies)
{
return false;
}
}
// Item just dropped, should wait a bit before grab it again
if (InternManager.Instance.IsGrabbableObjectJustDropped(grabbableObject))
{
return false;
}
// Is item too close to entrance (with config option enabled)
if (!PluginRuntimeProvider.Context.Config.GrabItemsNearEntrances)
{
for (int j = 0; j < EntrancesTeleportArray.Length; j++)
{
if ((grabbableObject.transform.position - EntrancesTeleportArray[j].entrancePoint.position).sqrMagnitude < Const.DISTANCE_ITEMS_TO_ENTRANCE * Const.DISTANCE_ITEMS_TO_ENTRANCE)
{
return false;
}
}
}
// Trim dictionnary if too large
InternManager.Instance.TrimDictJustDroppedItems();
// Is the item reachable with the agent pathfind ? (only owner knows and calculate) real position of ai intern)
//if (IsOwner
// && PathIsIntersectedByLineOfSight(grabbableObject.transform.position, false, false))
//{
// PluginLoggerHook.LogDebug?.Invoke($"object {grabbableObject.name} pathfind is not reachable");
// return false;
//}
//NavMesh.CalculatePath(this.transform.position, grabbableObject.transform.position, NavMesh.AllAreas, this.path1);
//if (this.path1.status == NavMeshPathStatus.PathPartial)
//{
// PluginLoggerHook.LogDebug?.Invoke($"2 object {grabbableObject.name} pathfind is not reachable");
//}
return true;
}
public void SetInternInElevator()
{
StartOfRound instanceSOR = StartOfRound.Instance;
if (NpcController == null)
{
return;
}
if (RagdollInternBody != null
&& RagdollInternBody.IsRagdollBodyHeld())
{
return;
}
bool wasInHangarShipRoom = NpcController.Npc.isInHangarShipRoom;
if (!NpcController.Npc.isInElevator
&& instanceSOR.shipBounds.bounds.Contains(NpcController.Npc.transform.position))
{
NpcController.Npc.isInElevator = true;
}
if (NpcController.Npc.isInElevator
&& !wasInHangarShipRoom
&& instanceSOR.shipInnerRoomBounds.bounds.Contains(NpcController.Npc.transform.position))
{
NpcController.Npc.isInHangarShipRoom = true;
}
else if (NpcController.Npc.isInElevator
&& !instanceSOR.shipBounds.bounds.Contains(NpcController.Npc.transform.position))
{
NpcController.Npc.isInElevator = false;
NpcController.Npc.isInHangarShipRoom = false;
wasInHangarShipRoom = false;
if (!AreHandsFree())
{
NpcController.Npc.SetItemInElevator(droppedInShipRoom: false, droppedInElevator: false, HeldItem);
}
}
if (wasInHangarShipRoom != NpcController.Npc.isInHangarShipRoom
&& !NpcController.Npc.isInHangarShipRoom
&& !AreHandsFree())
{
NpcController.Npc.SetItemInElevator(droppedInShipRoom: false, droppedInElevator: true, HeldItem);
}
}
private void InitImportantColliders()
{
if (dictComponentByCollider == null)
{
dictComponentByCollider = new Dictionary<string, Component>();
}
else
{
dictComponentByCollider.Clear();
}
BridgeTrigger[] bridgeTriggers = FindObjectsOfType<BridgeTrigger>(includeInactive: false);
for (int i = 0; i < bridgeTriggers.Length; i++)
{
Component[] bridgePhysicsPartsContainerComponents = bridgeTriggers[i].bridgePhysicsPartsContainer.gameObject.GetComponentsInChildren<Transform>();
for (int j = 0; j < bridgePhysicsPartsContainerComponents.Length; j++)
{
if (bridgePhysicsPartsContainerComponents[j].name == "Mesh")
{
continue;
}
if (!dictComponentByCollider.ContainsKey(bridgePhysicsPartsContainerComponents[j].name))
{
dictComponentByCollider.Add(bridgePhysicsPartsContainerComponents[j].name, bridgeTriggers[i]);
}
}
}
//foreach (var a in dictComponentByCollider)
//{
// PluginLoggerHook.LogDebug?.Invoke($"dictComponentByCollider {a.Key} {a.Value}");
// ComponentUtil.ListAllComponents(((BridgeTrigger)a.Value).bridgePhysicsPartsContainer.gameObject);
//}
}
public void HideShowLevelStickerBetaBadge(bool show)
{
MeshRenderer[] componentsInChildren = NpcController.Npc.gameObject.GetComponentsInChildren<MeshRenderer>();
(from x in componentsInChildren
where x.gameObject.name == "LevelSticker"
select x).First().enabled = show;
(from x in componentsInChildren
where x.gameObject.name == "BetaBadge"
select x).First().enabled = show;
}
public void SetInternLookAt(Vector3? position = null)
{
if (PluginRuntimeProvider.Context.InputActionsInstance.MakeInternLookAtPosition.IsPressed())
{
LookAtWhatPlayerPointingAt();
}
else
{
if (position.HasValue)
{
NpcController.OrderToLookAtPlayer(position.Value + new Vector3(0, 2.35f, 0));
}
else
{
// Looking at player or forward
PlayerControllerB? playerToLook = CheckLOSForClosestPlayer(Const.INTERN_FOV, (int)Const.DISTANCE_CLOSE_ENOUGH_HOR, (int)Const.DISTANCE_CLOSE_ENOUGH_HOR);
if (playerToLook != null)
{
NpcController.OrderToLookAtPlayer(playerToLook.playerEye.position);
}
else
{
NpcController.OrderToLookForward();
}
}
}
}
public void LookAtWhatPlayerPointingAt()
{
PlayerControllerB localPlayer = StartOfRound.Instance.localPlayerController;
// Look where the target player is looking
Ray interactRay = new Ray(localPlayer.gameplayCamera.transform.position, localPlayer.gameplayCamera.transform.forward);
RaycastHit[] raycastHits = Physics.RaycastAll(interactRay);
if (raycastHits.Length == 0)
{
NpcController.SetTurnBodyTowardsDirection(localPlayer.gameplayCamera.transform.forward);
NpcController.OrderToLookForward();
}
else
{
// Check if looking at a player/intern
foreach (var hit in raycastHits)
{
PlayerControllerB? player = hit.collider.gameObject.GetComponent<PlayerControllerB>();
if (player != null
&& player.playerClientId != StartOfRound.Instance.localPlayerController.playerClientId)
{
NpcController.OrderToLookAtPosition(hit.point);
NpcController.SetTurnBodyTowardsDirectionWithPosition(hit.point);
return;
}
}
// Check if looking too far in the distance or at a valid position
foreach (var hit in raycastHits)
{
if (hit.distance < 0.1f)
{
NpcController.SetTurnBodyTowardsDirection(localPlayer.gameplayCamera.transform.forward);
NpcController.OrderToLookForward();
return;
}
PlayerControllerB? player = hit.collider.gameObject.GetComponent<PlayerControllerB>();
if (player != null && player.playerClientId == StartOfRound.Instance.localPlayerController.playerClientId)
{
continue;
}
// Look at position
NpcController.OrderToLookAtPosition(hit.point);
NpcController.SetTurnBodyTowardsDirectionWithPosition(hit.point);
break;
}
}
}
#region Voices
public void UpdateInternVoiceEffects()
{
PlayerControllerB internController = NpcController.Npc;
int internPlayerClientID = (int)internController.playerClientId;
PlayerControllerB spectatedPlayerScript;
if (GameNetworkManager.Instance.localPlayerController.isPlayerDead && GameNetworkManager.Instance.localPlayerController.spectatedPlayerScript != null)
{
spectatedPlayerScript = GameNetworkManager.Instance.localPlayerController.spectatedPlayerScript;
}
else
{
spectatedPlayerScript = GameNetworkManager.Instance.localPlayerController;
}
bool walkieTalkie = internController.speakingToWalkieTalkie
&& spectatedPlayerScript.holdingWalkieTalkie
&& internController != spectatedPlayerScript;
AudioLowPassFilter audioLowPassFilter = NpcController.AudioLowPassFilterComponent;
OccludeAudio occludeAudio = NpcController.OccludeAudioComponent;
audioLowPassFilter.enabled = true;
occludeAudio.overridingLowPass = walkieTalkie || internController.voiceMuffledByEnemy;
NpcController.AudioHighPassFilterComponent.enabled = walkieTalkie;
if (!walkieTalkie)
{
creatureVoice.spatialBlend = 1f;
creatureVoice.bypassListenerEffects = false;
creatureVoice.bypassEffects = false;
creatureVoice.outputAudioMixerGroup = SoundManager.Instance.playerVoiceMixers[internPlayerClientID];
audioLowPassFilter.lowpassResonanceQ = 1f;
}
else
{
creatureVoice.spatialBlend = 0f;
if (GameNetworkManager.Instance.localPlayerController.isPlayerDead)
{
creatureVoice.panStereo = 0f;
creatureVoice.outputAudioMixerGroup = SoundManager.Instance.playerVoiceMixers[internPlayerClientID];
creatureVoice.bypassListenerEffects = false;
creatureVoice.bypassEffects = false;
}
else
{
creatureVoice.panStereo = 0.4f;
creatureVoice.bypassListenerEffects = false;
creatureVoice.bypassEffects = false;
creatureVoice.outputAudioMixerGroup = SoundManager.Instance.playerVoiceMixers[internPlayerClientID];
}
occludeAudio.lowPassOverride = 4000f;
audioLowPassFilter.lowpassResonanceQ = 3f;
}
}
[ServerRpc(RequireOwnership = false)]
public void PlayAudioServerRpc(string smallPathAudioClip, int enumTalkativeness)
{
PlayAudioClientRpc(smallPathAudioClip, enumTalkativeness);
}
[ClientRpc]
private void PlayAudioClientRpc(string smallPathAudioClip, int enumTalkativeness)
{
if (enumTalkativeness == PluginRuntimeProvider.Context.Config.Talkativeness
|| InternIdentity.Voice.CanPlayAudioAfterCooldown())
{
AudioManager.Instance.PlayAudio(smallPathAudioClip, InternIdentity.Voice);
}
}
#endregion
#region TeleportIntern RPC
/// <summary>
/// Teleport intern and send to server to call client to sync
/// </summary>
/// <param name="pos">Position destination</param>
/// <param name="setOutside">Is the teleport destination outside of the facility</param>
/// <param name="isUsingEntrance">Is the intern actually using entrance to teleport ?</param>
public void SyncTeleportIntern(Vector3 pos, bool setOutside, bool isUsingEntrance)
{
if (!IsOwner)
{
return;
}
TeleportIntern(pos, setOutside, isUsingEntrance);
TeleportInternServerRpc(pos, setOutside, isUsingEntrance);
}
/// <summary>
/// Server side, call clients to sync teleport intern
/// </summary>
/// <param name="pos">Position destination</param>
/// <param name="setOutside">Is the teleport destination outside of the facility</param>
/// <param name="isUsingEntrance">Is the intern actually using entrance to teleport ?</param>
[ServerRpc]
private void TeleportInternServerRpc(Vector3 pos, bool setOutside, bool isUsingEntrance)
{
TeleportInternClientRpc(pos, setOutside, isUsingEntrance);
}
/// <summary>
/// Client side, teleport intern on client, only for not the owner
/// </summary>
/// <param name="pos">Position destination</param>
/// <param name="setOutside">Is the teleport destination outside of the facility</param>
/// <param name="isUsingEntrance">Is the intern actually using entrance to teleport ?</param>
[ClientRpc]
private void TeleportInternClientRpc(Vector3 pos, bool setOutside, bool isUsingEntrance)
{
if (IsOwner)
{
return;
}
TeleportIntern(pos, setOutside, isUsingEntrance);
}
/// <summary>
/// Teleport the intern.
/// </summary>
/// <param name="pos">Position destination</param>
/// <param name="setOutside">Is the teleport destination outside of the facility</param>
/// <param name="isUsingEntrance">Is the intern actually using entrance to teleport ?</param>
public void TeleportIntern(Vector3 pos, bool? setOutside = null, bool isUsingEntrance = false)
{
// teleport body
TeleportAgentAIAndBody(pos);
// Set AI outside or inside dungeon
if (!setOutside.HasValue)
{
setOutside = pos.y >= -80f;
}
NpcController.Npc.isInsideFactory = !setOutside.Value;
if (isOutside != setOutside.Value)
{
SetEnemyOutside(setOutside.Value);
}
// Using main entrance or fire exits ?
if (isUsingEntrance)
{
NpcController.Npc.thisPlayerBody.RotateAround(NpcController.Npc.thisPlayerBody.transform.position, Vector3.up, 180f);
TimeSinceTeleporting = Time.timeSinceLevelLoad;
EntranceTeleport entranceTeleport = RoundManager.FindMainEntranceScript(setOutside.Value);
if (entranceTeleport.doorAudios != null && entranceTeleport.doorAudios.Length != 0)
{
entranceTeleport.entrancePointAudio.PlayOneShot(entranceTeleport.doorAudios[0]);
}
}
}
/// <summary>
/// Teleport the brain and body of intern
/// </summary>
/// <param name="pos"></param>
private void TeleportAgentAIAndBody(Vector3 pos)
{
Vector3 navMeshPosition = RoundManager.Instance.GetNavMeshPosition(pos, default, 2.7f);
serverPosition = navMeshPosition;
NpcController.Npc.transform.position = navMeshPosition;
if (agent == null
|| !agent.enabled)
{
transform.position = navMeshPosition;
}
else
{
agent.enabled = false;
transform.position = navMeshPosition;
agent.enabled = true;
}
// For CullFactory mod
if (HeldItem != null)
{
HeldItem.EnableItemMeshes(true);
}
}
public void SyncTeleportInternVehicle(Vector3 pos, bool enteringVehicle, NetworkBehaviourReference networkBehaviourReferenceVehicle)
{
if (!IsOwner)
{
return;
}
TeleportInternVehicle(pos, enteringVehicle, networkBehaviourReferenceVehicle);
TeleportInternVehicleServerRpc(pos, enteringVehicle, networkBehaviourReferenceVehicle);
}
[ServerRpc]
private void TeleportInternVehicleServerRpc(Vector3 pos, bool enteringVehicle, NetworkBehaviourReference networkBehaviourReferenceVehicle)
{
TeleportInternVehicleClientRpc(pos, enteringVehicle, networkBehaviourReferenceVehicle);
}
[ClientRpc]
private void TeleportInternVehicleClientRpc(Vector3 pos, bool enteringVehicle, NetworkBehaviourReference networkBehaviourReferenceVehicle)
{
if (IsOwner)
{
return;
}
TeleportInternVehicle(pos, enteringVehicle, networkBehaviourReferenceVehicle);
}
private void TeleportInternVehicle(Vector3 pos, bool enteringVehicle, NetworkBehaviourReference networkBehaviourReferenceVehicle)
{
if (enteringVehicle)
{
if (agent != null)
{
agent.enabled = false;
}
NpcController.Npc.transform.position = pos;
StateControllerMovement = EnumStateControllerMovement.Fixed;
}
else
{
TeleportIntern(pos);
StateControllerMovement = EnumStateControllerMovement.FollowAgent;
}
NpcController.IsControllerInCruiser = enteringVehicle;
if (NpcController.IsControllerInCruiser)
{
if (networkBehaviourReferenceVehicle.TryGet(out VehicleController vehicleController))
{
// Attach intern to vehicle
PluginLoggerHook.LogDebug?.Invoke($"{NpcController.Npc.playerUsername} enters vehicle");
ReParentIntern(vehicleController.transform);
}
StopSinkingState();
}
else
{
PluginLoggerHook.LogDebug?.Invoke($"{NpcController.Npc.playerUsername} exits vehicle");
ReParentIntern(NpcController.Npc.playersManager.playersContainer);
}
}
#endregion
#region AssignTargetAndSetMovingTo RPC
/// <summary>
/// Change the ownership of the intern to the new player target,
/// and set the destination to him.
/// </summary>
/// <param name="newTarget">New <c>PlayerControllerB to set the owner of intern to.</c></param>
public void SyncAssignTargetAndSetMovingTo(PlayerControllerB newTarget)
{
if (OwnerClientId != newTarget.actualClientId)
{
// Changes the ownership of the intern, on server and client directly
ChangeOwnershipOfEnemy(newTarget.actualClientId);
if (IsServer)
{
SyncFromAssignTargetAndSetMovingToClientRpc(newTarget.playerClientId);
}
else
{
SyncAssignTargetAndSetMovingToServerRpc(newTarget.playerClientId);
}
}
else
{
AssignTargetAndSetMovingTo(newTarget.playerClientId);
}
}
/// <summary>
/// Server side, call clients to sync the set destination to new target player.
/// </summary>
/// <param name="playerid">Id of the new target player</param>
[ServerRpc(RequireOwnership = false)]
private void SyncAssignTargetAndSetMovingToServerRpc(ulong playerid)
{
SyncFromAssignTargetAndSetMovingToClientRpc(playerid);
}
/// <summary>
/// Client side, set destination to the new target player
/// </summary>
/// <remarks>
/// Change the state to <c>GetCloseToPlayerState</c>
/// </remarks>
/// <param name="playerid">Id of the new target player</param>
[ClientRpc]
private void SyncFromAssignTargetAndSetMovingToClientRpc(ulong playerid)
{
if (!IsOwner)
{
return;
}
AssignTargetAndSetMovingTo(playerid);
}
private void AssignTargetAndSetMovingTo(ulong playerid)
{
PlayerControllerB targetPlayer = StartOfRound.Instance.allPlayerScripts[playerid];
SetMovingTowardsTargetPlayer(targetPlayer);
SetDestinationToPositionInternAI(this.targetPlayer.transform.position);
SetCommandToFollowPlayer();
}
#endregion
#region UpdatePlayerPosition RPC
/// <summary>
/// Sync the intern position between server and clients.
/// </summary>
/// <param name="newPos">New position of the intern controller</param>
/// <param name="inElevator">Is the intern on the ship ?</param>
/// <param name="inShipRoom">Is the intern in the ship room ?</param>
/// <param name="exhausted">Is the intern exhausted ?</param>
/// <param name="isPlayerGrounded">Is the intern player body touching the ground ?</param>
public void SyncUpdateInternPosition(Vector3 newPos, bool inElevator, bool inShipRoom, bool exhausted, bool isPlayerGrounded)
{
if (IsServer)
{
UpdateInternPositionClientRpc(newPos, inElevator, inShipRoom, exhausted, isPlayerGrounded);
}
else
{
UpdateInternPositionServerRpc(newPos, inElevator, inShipRoom, exhausted, isPlayerGrounded);
}
}
/// <summary>
/// Server side, call clients to sync the new position of the intern
/// </summary>
/// <param name="newPos">New position of the intern controller</param>
/// <param name="inElevator">Is the intern on the ship ?</param>
/// <param name="inShipRoom">Is the intern in the ship room ?</param>
/// <param name="exhausted">Is the intern exhausted ?</param>
/// <param name="isPlayerGrounded">Is the intern player body touching the ground ?</param>
[ServerRpc(RequireOwnership = false)]
private void UpdateInternPositionServerRpc(Vector3 newPos, bool inElevator, bool inShipRoom, bool exhausted, bool isPlayerGrounded)
{
UpdateInternPositionClientRpc(newPos, inElevator, inShipRoom, exhausted, isPlayerGrounded);
}
/// <summary>
/// Update the intern position if not owner of intern, the owner move on his side the intern.
/// </summary>
/// <param name="newPos">New position of the intern controller</param>
/// <param name="inElevator">Is the intern on the ship ?</param>
/// <param name="isInShip">Is the intern in the ship room ?</param>
/// <param name="exhausted">Is the intern exhausted ?</param>
/// <param name="isPlayerGrounded">Is the intern player body touching the ground ?</param>
[ClientRpc]
private void UpdateInternPositionClientRpc(Vector3 newPos, bool inElevator, bool isInShip, bool exhausted, bool isPlayerGrounded)
{
if (NpcController == null)
{
return;
}
bool flag = NpcController.Npc.currentFootstepSurfaceIndex == 8 && (IsOwner && NpcController.IsTouchingGround || isPlayerGrounded);
if (NpcController.Npc.bleedingHeavily || flag)
{
NpcController.Npc.DropBlood(Vector3.down, NpcController.Npc.bleedingHeavily, flag);
}
NpcController.Npc.timeSincePlayerMoving = 0f;
if (IsOwner)
{
// Only update if not owner
return;
}
NpcController.Npc.isExhausted = exhausted;
NpcController.Npc.isInElevator = inElevator;
NpcController.Npc.isInHangarShipRoom = isInShip;
if (!AreHandsFree()
&& HeldItem != null
&& HeldItem.isInShipRoom != isInShip)
{
HeldItem.isInElevator = inElevator;
NpcController.Npc.SetItemInElevator(droppedInShipRoom: isInShip, droppedInElevator: inElevator, HeldItem);
}
NpcController.Npc.oldPlayerPosition = NpcController.Npc.serverPlayerPosition;
if (!NpcController.Npc.inVehicleAnimation)
{
NpcController.Npc.serverPlayerPosition = newPos;
}
}
#endregion
#region UpdatePlayerRotation and look RPC
/// <summary>
/// Sync the intern body rotation and rotation of head (where he looks) between server and clients.
/// </summary>
/// <param name="direction">Direction to turn body towards to</param>
/// <param name="intEnumObjectsLookingAt">State to know where the intern should look</param>
/// <param name="playerEyeToLookAt">Position of the player eyes to look at</param>
/// <param name="positionToLookAt">Position to look at</param>
public void SyncUpdateInternRotationAndLook(string stateIndicator, Vector3 direction, int intEnumObjectsLookingAt, Vector3 playerEyeToLookAt, Vector3 positionToLookAt)
{
if (IsServer)
{
UpdateInternRotationAndLookClientRpc(stateIndicator, direction, intEnumObjectsLookingAt, playerEyeToLookAt, positionToLookAt);
}
else
{
UpdateInternRotationAndLookServerRpc(stateIndicator, direction, intEnumObjectsLookingAt, playerEyeToLookAt, positionToLookAt);
}
}
/// <summary>
/// Server side, call clients to update intern body rotation and rotation of head (where he looks)
/// </summary>
/// <param name="direction">Direction to turn body towards to</param>
/// <param name="intEnumObjectsLookingAt">State to know where the intern should look</param>
/// <param name="playerEyeToLookAt">Position of the player eyes to look at</param>
/// <param name="positionToLookAt">Position to look at</param>
[ServerRpc(RequireOwnership = false)]
private void UpdateInternRotationAndLookServerRpc(string stateIndicator, Vector3 direction, int intEnumObjectsLookingAt, Vector3 playerEyeToLookAt, Vector3 positionToLookAt)
{
UpdateInternRotationAndLookClientRpc(stateIndicator, direction, intEnumObjectsLookingAt, playerEyeToLookAt, positionToLookAt);
}
/// <summary>
/// Client side, update the intern body rotation and rotation of head (where he looks).
/// </summary>
/// <param name="direction">Direction to turn body towards to</param>
/// <param name="intEnumObjectsLookingAt">State to know where the intern should look</param>
/// <param name="playerEyeToLookAt">Position of the player eyes to look at</param>
/// <param name="positionToLookAt">Position to look at</param>
[ClientRpc]
private void UpdateInternRotationAndLookClientRpc(string stateIndicator, Vector3 direction, int intEnumObjectsLookingAt, Vector3 playerEyeToLookAt, Vector3 positionToLookAt)
{
if (NpcController == null)
{
return;
}
if (IsClientOwnerOfIntern())
{
// Only update if not owner
return;
}
// Update state indicator
// Actually, too much cluter, indicator just for owner for now
//this.stateIndicatorServer = stateIndicator;
// Update direction
NpcController.SetTurnBodyTowardsDirection(direction);
switch ((EnumObjectsLookingAt)intEnumObjectsLookingAt)
{
case EnumObjectsLookingAt.Forward:
NpcController.OrderToLookForward();
break;
case EnumObjectsLookingAt.Player:
NpcController.OrderToLookAtPlayer(playerEyeToLookAt);
break;
case EnumObjectsLookingAt.Position:
NpcController.OrderToLookAtPosition(positionToLookAt);
break;
}
}
#endregion
#region UpdatePlayer animations RPC
/// <summary>
/// Server side, call client to sync changes in animation of the intern
/// </summary>
/// <param name="animationState">Current animation state</param>
/// <param name="animationSpeed">Current animation speed</param>
[ServerRpc(RequireOwnership = false)]
public void UpdateInternAnimationServerRpc(int animationState, float animationSpeed)
{
UpdateInternAnimationClientRpc(animationState, animationSpeed);
}
/// <summary>
/// Client, update changes in animation of the intern
/// </summary>
/// <param name="animationState">Current animation state</param>
/// <param name="animationSpeed">Current animation speed</param>
[ClientRpc]
private void UpdateInternAnimationClientRpc(int animationState, float animationSpeed)
{
if (NpcController == null)
{
return;
}
if (IsClientOwnerOfIntern())
{
// Only update if not owner
return;
}
NpcController.ApplyUpdateInternAnimationsNotOwner(animationState, animationSpeed);
}
#endregion
#region UpdateSpecialAnimation RPC
/// <summary>
/// Sync the changes in special animation of the intern body, between server and clients
/// </summary>
/// <param name="specialAnimation">Is in special animation ?</param>
/// <param name="timed">Wait time of the special animation to end</param>
/// <param name="climbingLadder">Is climbing ladder ?</param>
public void UpdateInternSpecialAnimationValue(bool specialAnimation, float timed, bool climbingLadder)
{
if (!IsClientOwnerOfIntern())
{
return;
}
UpdateInternSpecialAnimationServerRpc(specialAnimation, timed, climbingLadder);
}
/// <summary>
/// Server side, call clients to update the intern special animation
/// </summary>
/// <param name="specialAnimation">Is in special animation ?</param>
/// <param name="timed">Wait time of the special animation to end</param>
/// <param name="climbingLadder">Is climbing ladder ?</param>
[ServerRpc(RequireOwnership = false)]
private void UpdateInternSpecialAnimationServerRpc(bool specialAnimation, float timed, bool climbingLadder)
{
UpdateInternSpecialAnimationClientRpc(specialAnimation, timed, climbingLadder);
}
/// <summary>
/// Client side, update the intern special animation
/// </summary>
/// <param name="specialAnimation">Is in special animation ?</param>
/// <param name="timed">Wait time of the special animation to end</param>
/// <param name="climbingLadder">Is climbing ladder ?</param>
[ClientRpc]
private void UpdateInternSpecialAnimationClientRpc(bool specialAnimation, float timed, bool climbingLadder)
{
UpdateInternSpecialAnimation(specialAnimation, timed, climbingLadder);
}
/// <summary>
/// Update the intern special animation
/// </summary>
/// <param name="specialAnimation">Is in special animation ?</param>
/// <param name="timed">Wait time of the special animation to end</param>
/// <param name="climbingLadder">Is climbing ladder ?</param>
private void UpdateInternSpecialAnimation(bool specialAnimation, float timed, bool climbingLadder)
{
if (NpcController == null)
{
return;
}
PlayerControllerBHook.IsInSpecialAnimationClientRpc_ReversePatch?.Invoke(NpcController.Npc, specialAnimation, timed, climbingLadder);
NpcController.Npc.ResetZAndXRotation();
}
#endregion
#region SyncDeadBodyPosition RPC
/// <summary>
/// Server side, call the clients to update the dead body of the intern
/// </summary>
/// <param name="newBodyPosition">New dead body position</param>
[ServerRpc(RequireOwnership = false)]
public void SyncDeadBodyPositionServerRpc(Vector3 newBodyPosition)
{
SyncDeadBodyPositionClientRpc(newBodyPosition);
}
/// <summary>
/// Client side, update the dead body of the intern
/// </summary>
/// <param name="newBodyPosition">New dead body position</param>
[ClientRpc]
private void SyncDeadBodyPositionClientRpc(Vector3 newBodyPosition)
{
PlayerControllerBHook.SyncBodyPositionClientRpc_ReversePatch?.Invoke(NpcController.Npc, newBodyPosition);
}
#endregion
#region SyncFaceUnderwater
[ServerRpc(RequireOwnership = false)]
public void SyncSetFaceUnderwaterServerRpc(bool isUnderwater)
{
SyncSetFaceUnderwaterClientRpc(isUnderwater);
}
[ClientRpc]
private void SyncSetFaceUnderwaterClientRpc(bool isUnderwater)
{
NpcController.Npc.isUnderwater = isUnderwater;
}
#endregion
#region Grab item RPC
/// <summary>
/// Server side, call clients to make the intern grab item on their side to sync everyone
/// </summary>
/// <param name="networkObjectReference">Item reference over the network</param>
[ServerRpc(RequireOwnership = false)]
public void GrabItemServerRpc(NetworkObjectReference networkObjectReference, bool itemGiven)
{
if (!networkObjectReference.TryGet(out NetworkObject networkObject))
{
PluginLoggerHook.LogError?.Invoke($"{NpcController.Npc.playerUsername} GrabItem for InternAI {InternId} {NpcController.Npc.playerUsername}: Failed to get network object from network object reference (Grab item RPC)");
return;
}
GrabbableObject grabbableObject = networkObject.GetComponent<GrabbableObject>();
if (grabbableObject == null)
{
PluginLoggerHook.LogError?.Invoke($"{NpcController.Npc.playerUsername} GrabItem for InternAI {InternId} {NpcController.Npc.playerUsername}: Failed to get GrabbableObject component from network object (Grab item RPC)");
return;
}
if (!itemGiven)
{
if (!IsGrabbableObjectGrabbable(grabbableObject))
{
PluginLoggerHook.LogDebug?.Invoke($"{NpcController.Npc.playerUsername} grabbableObject {grabbableObject} not grabbable");
return;
}
}
GrabItemClientRpc(networkObjectReference);
}
/// <summary>
/// Client side, make the intern grab item
/// </summary>
/// <param name="networkObjectReference">Item reference over the network</param>
[ClientRpc]
private void GrabItemClientRpc(NetworkObjectReference networkObjectReference)
{
if (!networkObjectReference.TryGet(out NetworkObject networkObject))
{
PluginLoggerHook.LogError?.Invoke($"{NpcController.Npc.playerUsername} GrabItem for InternAI {InternId} {NpcController.Npc.playerUsername}: Failed to get network object from network object reference (Grab item RPC)");
return;
}
GrabbableObject grabbableObject = networkObject.GetComponent<GrabbableObject>();
if (grabbableObject == null)
{
PluginLoggerHook.LogError?.Invoke($"{NpcController.Npc.playerUsername} GrabItem for InternAI {InternId} {NpcController.Npc.playerUsername}: Failed to get GrabbableObject component from network object (Grab item RPC)");
return;
}
if (HeldItem == grabbableObject)
{
PluginLoggerHook.LogError?.Invoke($"{NpcController.Npc.playerUsername} cannot grab already held item {grabbableObject} on client #{NetworkManager.LocalClientId}");
return;
}
GrabItem(grabbableObject);
}
/// <summary>
/// Make the intern grab an item like an enemy would, but update the body (<c>PlayerControllerB</c>) too.
/// </summary>
/// <param name="grabbableObject">Item to grab</param>
private void GrabItem(GrabbableObject grabbableObject)
{
PluginLoggerHook.LogDebug?.Invoke($"{NpcController.Npc.playerUsername} try to grab item {grabbableObject} on client #{NetworkManager.LocalClientId}");
HeldItem = grabbableObject;
grabbableObject.GrabItemFromEnemy(this);
grabbableObject.parentObject = NpcController.Npc.serverItemHolder;
grabbableObject.playerHeldBy = NpcController.Npc;
grabbableObject.isHeld = true;
grabbableObject.hasHitGround = false;
grabbableObject.isInFactory = NpcController.Npc.isInsideFactory;
grabbableObject.EquipItem();
NpcController.Npc.isHoldingObject = true;
NpcController.Npc.currentlyHeldObjectServer = grabbableObject;
NpcController.Npc.twoHanded = grabbableObject.itemProperties.twoHanded;
NpcController.Npc.twoHandedAnimation = grabbableObject.itemProperties.twoHandedAnimation;
NpcController.Npc.carryWeight += Mathf.Clamp(grabbableObject.itemProperties.weight - 1f, 0f, 10f);
NpcController.GrabbedObjectValidated = true;
if (grabbableObject.itemProperties.grabSFX != null)
{
NpcController.Npc.itemAudio.PlayOneShot(grabbableObject.itemProperties.grabSFX, 1f);
}
// animations
NpcController.Npc.playerBodyAnimator.SetBool(Const.PLAYER_ANIMATION_BOOL_GRABINVALIDATED, false);
NpcController.Npc.playerBodyAnimator.SetBool(Const.PLAYER_ANIMATION_BOOL_GRABVALIDATED, false);
NpcController.Npc.playerBodyAnimator.SetBool(Const.PLAYER_ANIMATION_BOOL_CANCELHOLDING, false);
NpcController.Npc.playerBodyAnimator.ResetTrigger(Const.PLAYER_ANIMATION_TRIGGER_THROW);
SetSpecialGrabAnimationBool(true, grabbableObject);
if (grabObjectCoroutine != null)
{
StopCoroutine(grabObjectCoroutine);
}
grabObjectCoroutine = StartCoroutine(GrabAnimationCoroutine());
PluginLoggerHook.LogDebug?.Invoke($"{NpcController.Npc.playerUsername} Grabbed item {grabbableObject} on client #{NetworkManager.LocalClientId}");
}
/// <summary>
/// Coroutine for the grab animation
/// </summary>
/// <returns></returns>
private IEnumerator GrabAnimationCoroutine()
{
if (HeldItem != null)
{
float grabAnimationTime = HeldItem.itemProperties.grabAnimationTime > 0f ? HeldItem.itemProperties.grabAnimationTime : 0.4f;
yield return new WaitForSeconds(grabAnimationTime - 0.2f);
NpcController.Npc.playerBodyAnimator.SetBool(Const.PLAYER_ANIMATION_BOOL_GRABVALIDATED, true);
NpcController.Npc.isGrabbingObjectAnimation = false;
}
yield break;
}
/// <summary>
/// Set the animation of body to something special if the item has a special grab animation.
/// </summary>
/// <param name="setBool">Activate or deactivate special animation</param>
/// <param name="item">Item that has the special grab animation</param>
private void SetSpecialGrabAnimationBool(bool setBool, GrabbableObject? item)
{
NpcController.Npc.playerBodyAnimator.SetBool(Const.PLAYER_ANIMATION_BOOL_GRAB, setBool);
if (item != null
&& !string.IsNullOrEmpty(item.itemProperties.grabAnim))
{
try
{
NpcController.SetAnimationBoolForItem(item.itemProperties.grabAnim, setBool);
NpcController.Npc.playerBodyAnimator.SetBool(item.itemProperties.grabAnim, setBool);
}
catch (Exception)
{
PluginLoggerHook.LogError?.Invoke("An item tried to set an animator bool which does not exist: " + item.itemProperties.grabAnim);
}
}
}
#endregion
#region Drop item RPC
/// <summary>
/// Make the intern drop his item like an enemy, but update the body (<c>PlayerControllerB</c>) too.
/// </summary>
public void DropItem()
{
PluginLoggerHook.LogDebug?.Invoke($"{NpcController.Npc.playerUsername} Try to drop item on client #{NetworkManager.LocalClientId}");
if (HeldItem == null)
{
PluginLoggerHook.LogError?.Invoke($"{NpcController.Npc.playerUsername} Try to drop not held item on client #{NetworkManager.LocalClientId}");
return;
}
GrabbableObject grabbableObject = HeldItem;
bool placeObject = false;
Vector3 placePosition = default;
NetworkObject parentObjectTo = null!;
bool matchRotationOfParent = true;
Vector3 vector;
NetworkObject physicsRegionOfDroppedObject = grabbableObject.GetPhysicsRegionOfDroppedObject(NpcController.Npc, out vector);
if (physicsRegionOfDroppedObject != null)
{
placePosition = vector;
parentObjectTo = physicsRegionOfDroppedObject;
placeObject = true;
matchRotationOfParent = false;
}
if (placeObject)
{
if (parentObjectTo == null)
{
if (NpcController.Npc.isInElevator)
{
placePosition = StartOfRound.Instance.elevatorTransform.InverseTransformPoint(placePosition);
}
else
{
placePosition = StartOfRound.Instance.propsContainer.InverseTransformPoint(placePosition);
}
int floorYRot2 = (int)transform.localEulerAngles.y;
// on client
SetObjectAsNoLongerHeld(grabbableObject,
NpcController.Npc.isInElevator,
NpcController.Npc.isInHangarShipRoom,
placePosition,
floorYRot2);
// for other clients
SetObjectAsNoLongerHeldServerRpc(new DropItemNetworkSerializable()
{
DroppedInElevator = NpcController.Npc.isInElevator,
DroppedInShipRoom = NpcController.Npc.isInHangarShipRoom,
FloorYRot = floorYRot2,
GrabbedObject = grabbableObject.NetworkObject,
TargetFloorPosition = placePosition
});
}
else
{
// on client
PlaceGrabbableObject(grabbableObject, parentObjectTo.transform, placePosition, matchRotationOfParent);
// for other clients
PlaceGrabbableObjectServerRpc(new PlaceItemNetworkSerializable()
{
GrabbedObject = grabbableObject.NetworkObject,
MatchRotationOfParent = matchRotationOfParent,
ParentObject = parentObjectTo,
PlacePositionOffset = placePosition
});
}
}
else
{
bool droppedInElevator = NpcController.Npc.isInElevator;
Vector3 targetFloorPosition;
if (!NpcController.Npc.isInElevator)
{
Vector3 vector2;
if (grabbableObject.itemProperties.allowDroppingAheadOfPlayer)
{
vector2 = DropItemAheadOfPlayer(grabbableObject, NpcController.Npc);
}
else
{
vector2 = grabbableObject.GetItemFloorPosition(default);
}
if (!NpcController.Npc.playersManager.shipBounds.bounds.Contains(vector2))
{
targetFloorPosition = NpcController.Npc.playersManager.propsContainer.InverseTransformPoint(vector2);
}
else
{
droppedInElevator = true;
targetFloorPosition = NpcController.Npc.playersManager.elevatorTransform.InverseTransformPoint(vector2);
}
}
else
{
Vector3 vector2 = grabbableObject.GetItemFloorPosition(default);
if (!NpcController.Npc.playersManager.shipBounds.bounds.Contains(vector2))
{
droppedInElevator = false;
targetFloorPosition = NpcController.Npc.playersManager.propsContainer.InverseTransformPoint(vector2);
}
else
{
targetFloorPosition = NpcController.Npc.playersManager.elevatorTransform.InverseTransformPoint(vector2);
}
}
int floorYRot = (int)transform.localEulerAngles.y;
// on client
SetObjectAsNoLongerHeld(grabbableObject,
droppedInElevator,
NpcController.Npc.isInHangarShipRoom,
targetFloorPosition,
floorYRot);
// for other clients
SetObjectAsNoLongerHeldServerRpc(new DropItemNetworkSerializable()
{
DroppedInElevator = droppedInElevator,
DroppedInShipRoom = NpcController.Npc.isInHangarShipRoom,
FloorYRot = floorYRot,
GrabbedObject = grabbableObject.NetworkObject,
TargetFloorPosition = targetFloorPosition
});
}
}
private Vector3 DropItemAheadOfPlayer(GrabbableObject grabbableObject, PlayerControllerB player)
{
Vector3 vector;
Ray ray = new Ray(transform.position + Vector3.up * 0.4f, player.gameplayCamera.transform.forward);
if (Physics.Raycast(ray, out RaycastHit hit, 1.7f, 268438273, QueryTriggerInteraction.Ignore))
{
vector = ray.GetPoint(Mathf.Clamp(hit.distance - 0.3f, 0.01f, 2f));
}
else
{
vector = ray.GetPoint(1.7f);
}
Vector3 itemFloorPosition = grabbableObject.GetItemFloorPosition(vector);
if (itemFloorPosition == vector)
{
itemFloorPosition = grabbableObject.GetItemFloorPosition(default);
}
return itemFloorPosition;
}
[ServerRpc(RequireOwnership = false)]
private void SetObjectAsNoLongerHeldServerRpc(DropItemNetworkSerializable dropItemNetworkSerializable)
{
NetworkObject networkObject;
if (dropItemNetworkSerializable.GrabbedObject.TryGet(out networkObject, null))
{
SetObjectAsNoLongerHeldClientRpc(dropItemNetworkSerializable);
}
else
{
PluginLoggerHook.LogError?.Invoke($"Intern {NpcController.Npc.playerUsername} on client #{NetworkManager.LocalClientId} (server) drop item : Object was not thrown because it does not exist on the server.");
}
}
[ClientRpc]
private void SetObjectAsNoLongerHeldClientRpc(DropItemNetworkSerializable dropItemNetworkSerializable)
{
if (HeldItem == null)
{
PluginLoggerHook.LogDebug?.Invoke($"{NpcController.Npc.playerUsername} held item already dropped, on client #{NetworkManager.LocalClientId}");
return;
}
NetworkObject networkObject;
if (dropItemNetworkSerializable.GrabbedObject.TryGet(out networkObject, null))
{
SetObjectAsNoLongerHeld(networkObject.GetComponent<GrabbableObject>(),
dropItemNetworkSerializable.DroppedInElevator,
dropItemNetworkSerializable.DroppedInShipRoom,
dropItemNetworkSerializable.TargetFloorPosition,
dropItemNetworkSerializable.FloorYRot);
}
else
{
PluginLoggerHook.LogError?.Invoke($"Intern {NpcController.Npc.playerUsername} on client #{NetworkManager.LocalClientId} drop item : The server did not have a reference to the held object");
}
}
private void SetObjectAsNoLongerHeld(GrabbableObject grabbableObject,
bool droppedInElevator,
bool droppedInShipRoom,
Vector3 targetFloorPosition,
int floorYRot = -1)
{
grabbableObject.heldByPlayerOnServer = false;
grabbableObject.parentObject = null;
if (droppedInElevator)
{
grabbableObject.transform.SetParent(NpcController.Npc.playersManager.elevatorTransform, true);
}
else
{
grabbableObject.transform.SetParent(NpcController.Npc.playersManager.propsContainer, true);
}
NpcController.Npc.SetItemInElevator(droppedInShipRoom, droppedInElevator, grabbableObject);
grabbableObject.EnablePhysics(true);
grabbableObject.EnableItemMeshes(true);
grabbableObject.isHeld = false;
grabbableObject.isPocketed = false;
grabbableObject.fallTime = 0f;
grabbableObject.startFallingPosition = grabbableObject.transform.parent.InverseTransformPoint(grabbableObject.transform.position);
grabbableObject.targetFloorPosition = targetFloorPosition;
grabbableObject.floorYRot = floorYRot;
EndDropItem(grabbableObject);
}
[ServerRpc(RequireOwnership = false)]
private void PlaceGrabbableObjectServerRpc(PlaceItemNetworkSerializable placeItemNetworkSerializable)
{
NetworkObject networkObject;
NetworkObject networkObject2;
if (placeItemNetworkSerializable.GrabbedObject.TryGet(out networkObject, null)
&& placeItemNetworkSerializable.ParentObject.TryGet(out networkObject2, null))
{
PlaceGrabbableObjectClientRpc(placeItemNetworkSerializable);
return;
}
NetworkObject networkObject3;
if (!placeItemNetworkSerializable.GrabbedObject.TryGet(out networkObject3, null))
{
PluginLoggerHook.LogError?.Invoke($"Object placement not synced to clients, missing reference to a network object: placing object with id: {placeItemNetworkSerializable.GrabbedObject.NetworkObjectId}; intern {NpcController.Npc.playerUsername}");
return;
}
NetworkObject networkObject4;
if (!placeItemNetworkSerializable.ParentObject.TryGet(out networkObject4, null))
{
PluginLoggerHook.LogError?.Invoke($"Object placement not synced to clients, missing reference to a network object: parent object with id: {placeItemNetworkSerializable.ParentObject.NetworkObjectId}; intern {NpcController.Npc.playerUsername}");
}
}
[ClientRpc]
private void PlaceGrabbableObjectClientRpc(PlaceItemNetworkSerializable placeItemNetworkSerializable)
{
NetworkObject networkObject;
if (placeItemNetworkSerializable.GrabbedObject.TryGet(out networkObject, null))
{
GrabbableObject grabbableObject = networkObject.GetComponent<GrabbableObject>();
NetworkObject networkObject2;
if (placeItemNetworkSerializable.ParentObject.TryGet(out networkObject2, null))
{
PlaceGrabbableObject(grabbableObject,
networkObject2.transform,
placeItemNetworkSerializable.PlacePositionOffset,
placeItemNetworkSerializable.MatchRotationOfParent);
}
else
{
PluginLoggerHook.LogError?.Invoke($"Reference to parent object when placing was missing. object: {grabbableObject} placed by intern #{NpcController.Npc.playerUsername}");
}
}
else
{
PluginLoggerHook.LogError?.Invoke("The server did not have a reference to the held object (when attempting to PLACE object on client.)");
}
}
private void PlaceGrabbableObject(GrabbableObject placeObject, Transform parentObject, Vector3 positionOffset, bool matchRotationOfParent)
{
if (HeldItem == null)
{
PluginLoggerHook.LogDebug?.Invoke($"{NpcController.Npc.playerUsername} held item already placed, on client #{NetworkManager.LocalClientId}");
return;
}
PlayerPhysicsRegion componentInChildren = parentObject.GetComponentInChildren<PlayerPhysicsRegion>();
if (componentInChildren != null && componentInChildren.allowDroppingItems)
{
parentObject = componentInChildren.physicsTransform;
}
placeObject.EnablePhysics(true);
placeObject.EnableItemMeshes(true);
placeObject.isHeld = false;
placeObject.isPocketed = false;
placeObject.heldByPlayerOnServer = false;
NpcController.Npc.SetItemInElevator(NpcController.Npc.isInHangarShipRoom, NpcController.Npc.isInElevator, placeObject);
placeObject.parentObject = null;
placeObject.transform.SetParent(parentObject, true);
placeObject.startFallingPosition = placeObject.transform.localPosition;
placeObject.transform.localScale = placeObject.originalScale;
placeObject.transform.localPosition = positionOffset;
placeObject.targetFloorPosition = positionOffset;
if (!matchRotationOfParent)
{
placeObject.fallTime = 0f;
}
else
{
placeObject.transform.localEulerAngles = new Vector3(0f, 0f, 0f);
placeObject.fallTime = 1.1f;
}
placeObject.OnPlaceObject();
EndDropItem(placeObject);
}
private void EndDropItem(GrabbableObject grabbableObject)
{
grabbableObject.DiscardItem();
SetSpecialGrabAnimationBool(false, grabbableObject);
NpcController.Npc.playerBodyAnimator.SetBool(Const.PLAYER_ANIMATION_BOOL_CANCELHOLDING, true);
NpcController.Npc.playerBodyAnimator.SetTrigger(Const.PLAYER_ANIMATION_TRIGGER_THROW);
InternManager.Instance.AddToDictJustDroppedItems(grabbableObject);
HeldItem = null;
NpcController.Npc.isHoldingObject = false;
NpcController.Npc.currentlyHeldObjectServer = null;
NpcController.Npc.twoHanded = false;
NpcController.Npc.twoHandedAnimation = false;
NpcController.GrabbedObjectValidated = false;
float weightToLose = grabbableObject.itemProperties.weight - 1f < 0f ? 0f : grabbableObject.itemProperties.weight - 1f;
NpcController.Npc.carryWeight = Mathf.Clamp(NpcController.Npc.carryWeight - weightToLose, 1f, 10f);
SyncBatteryIntern(grabbableObject, (int)(grabbableObject.insertedBattery.charge * 100f));
PluginLoggerHook.LogDebug?.Invoke($"{NpcController.Npc.playerUsername} dropped {grabbableObject}, on client #{NetworkManager.LocalClientId}");
}
[ServerRpc(RequireOwnership = false)]
public void SyncBatteryInternServerRpc(NetworkObjectReference networkObjectReferenceGrabbableObject, int charge)
{
SyncBatteryInternClientRpc(networkObjectReferenceGrabbableObject, charge);
}
[ClientRpc]
private void SyncBatteryInternClientRpc(NetworkObjectReference networkObjectReferenceGrabbableObject, int charge)
{
if (!networkObjectReferenceGrabbableObject.TryGet(out NetworkObject networkObject))
{
PluginLoggerHook.LogError?.Invoke($"SyncBatteryInternClientRpc : Failed to get network object from network object reference (Grab item RPC)");
return;
}
GrabbableObject grabbableObject = networkObject.GetComponent<GrabbableObject>();
if (grabbableObject == null)
{
PluginLoggerHook.LogError?.Invoke($"SyncBatteryInternClientRpc : Failed to get GrabbableObject component from network object (Grab item RPC)");
return;
}
SyncBatteryIntern(grabbableObject, charge);
}
private void SyncBatteryIntern(GrabbableObject grabbableObject, int charge)
{
float num = charge / 100f;
grabbableObject.insertedBattery = new Battery(num <= 0f, num);
grabbableObject.ChargeBatteries();
}
#endregion
#region Give item to intern RPC
[ServerRpc(RequireOwnership = false)]
public void GiveItemToInternServerRpc(ulong playerClientIdGiver, NetworkObjectReference networkObjectReference)
{
if (!networkObjectReference.TryGet(out NetworkObject networkObject))
{
PluginLoggerHook.LogError?.Invoke($"{NpcController.Npc.playerUsername} GiveItemToInternServerRpc for InternAI {InternId} {NpcController.Npc.playerUsername}: Failed to get network object from network object reference (Grab item RPC)");
return;
}
GrabbableObject grabbableObject = networkObject.GetComponent<GrabbableObject>();
if (grabbableObject == null)
{
PluginLoggerHook.LogError?.Invoke($"{NpcController.Npc.playerUsername} GiveItemToInternServerRpc for InternAI {InternId} {NpcController.Npc.playerUsername}: Failed to get GrabbableObject component from network object (Grab item RPC)");
return;
}
GiveItemToInternClientRpc(playerClientIdGiver, networkObjectReference);
}
[ClientRpc]
private void GiveItemToInternClientRpc(ulong playerClientIdGiver, NetworkObjectReference networkObjectReference)
{
if (!networkObjectReference.TryGet(out NetworkObject networkObject))
{
PluginLoggerHook.LogError?.Invoke($"{NpcController.Npc.playerUsername} GiveItemToInternClientRpc for InternAI {InternId}: Failed to get network object from network object reference (Grab item RPC)");
return;
}
GrabbableObject grabbableObject = networkObject.GetComponent<GrabbableObject>();
if (grabbableObject == null)
{
PluginLoggerHook.LogError?.Invoke($"{NpcController.Npc.playerUsername} GiveItemToInternClientRpc for InternAI {InternId}: Failed to get GrabbableObject component from network object (Grab item RPC)");
return;
}
GiveItemToIntern(playerClientIdGiver, grabbableObject);
}
private void GiveItemToIntern(ulong playerClientIdGiver, GrabbableObject grabbableObject)
{
PluginLoggerHook.LogDebug?.Invoke($"GiveItemToIntern playerClientIdGiver {playerClientIdGiver}, localPlayerController {StartOfRound.Instance.localPlayerController.playerClientId}");
PlayerControllerB player = StartOfRound.Instance.allPlayerScripts[playerClientIdGiver];
// Discard for player
if (player.playerClientId == StartOfRound.Instance.localPlayerController.playerClientId)
{
PlayerControllerBHook.SetSpecialGrabAnimationBool_ReversePatch?.Invoke(player, false, player.currentlyHeldObjectServer);
player.playerBodyAnimator.SetBool("cancelHolding", true);
player.playerBodyAnimator.SetTrigger("Throw");
HUDManager.Instance.itemSlotIcons[player.currentItemSlot].enabled = false;
HUDManager.Instance.holdingTwoHandedItem.enabled = false;
HUDManager.Instance.ClearControlTips();
}
for (int i = 0; i < player.ItemSlots.Length; i++)
{
if (player.ItemSlots[i] == grabbableObject)
{
player.ItemSlots[i] = null;
}
}
grabbableObject.EnablePhysics(true);
grabbableObject.EnableItemMeshes(true);
grabbableObject.parentObject = null;
grabbableObject.heldByPlayerOnServer = false;
grabbableObject.DiscardItem();
player.isHoldingObject = false;
player.currentlyHeldObjectServer = null;
player.twoHanded = false;
player.twoHandedAnimation = false;
float weightToLose = grabbableObject.itemProperties.weight - 1f < 0f ? 0f : grabbableObject.itemProperties.weight - 1f;
player.carryWeight = Mathf.Clamp(player.carryWeight - weightToLose, 1f, 10f);
SyncBatteryInternServerRpc(grabbableObject.NetworkObject, (int)(grabbableObject.insertedBattery.charge * 100f));
// Intern grab item
GrabItem(grabbableObject);
}
#endregion
#region Damage intern from client players RPC
/// <summary>
/// Server side, call client to sync the damage to the intern coming from a player
/// </summary>
/// <param name="damageAmount"></param>
/// <param name="hitDirection"></param>
/// <param name="playerWhoHit"></param>
[ServerRpc(RequireOwnership = false)]
public void DamageInternFromOtherClientServerRpc(int damageAmount, Vector3 hitDirection, int playerWhoHit)
{
DamageInternFromOtherClientClientRpc(damageAmount, hitDirection, playerWhoHit);
}
/// <summary>
/// Client side, update and apply the damage to the intern coming from a player
/// </summary>
/// <param name="damageAmount"></param>
/// <param name="hitDirection"></param>
/// <param name="playerWhoHit"></param>
[ClientRpc]
private void DamageInternFromOtherClientClientRpc(int damageAmount, Vector3 hitDirection, int playerWhoHit)
{
DamageInternFromOtherClient(damageAmount, hitDirection, playerWhoHit);
}
/// <summary>
/// Update and apply the damage to the intern coming from a player
/// </summary>
/// <param name="damageAmount"></param>
/// <param name="hitDirection"></param>
/// <param name="playerWhoHit"></param>
private void DamageInternFromOtherClient(int damageAmount, Vector3 hitDirection, int playerWhoHit)
{
if (NpcController == null)
{
return;
}
if (!NpcController.Npc.AllowPlayerDeath())
{
return;
}
if (NpcController.Npc.isPlayerControlled)
{
CentipedeAI[] array = FindObjectsByType<CentipedeAI>(FindObjectsSortMode.None);
for (int i = 0; i < array.Length; i++)
{
if (array[i].clingingToPlayer == this)
{
return;
}
}
DamageIntern(damageAmount, CauseOfDeath.Bludgeoning, 0, false, default);
}
NpcController.Npc.movementAudio.PlayOneShot(StartOfRound.Instance.hitPlayerSFX);
if (NpcController.Npc.health < MaxHealthPercent(6))
{
NpcController.Npc.DropBlood(hitDirection, true, false);
NpcController.Npc.bodyBloodDecals[0].SetActive(true);
NpcController.Npc.playersManager.allPlayerScripts[playerWhoHit].AddBloodToBody();
NpcController.Npc.playersManager.allPlayerScripts[playerWhoHit].movementAudio.PlayOneShot(StartOfRound.Instance.bloodGoreSFX);
}
}
#endregion
#region Damage intern RPC
public override void HitEnemy(int force = 1, PlayerControllerB playerWhoHit = null!, bool playHitSFX = false, int hitID = -1)
{
// The HitEnemy function works with player controller instead
return;
}
/// <summary>
/// Sync the damage taken by the intern between server and clients
/// </summary>
/// <remarks>
/// Better to call <see cref="PlayerControllerB.DamagePlayer"><c>PlayerControllerB.DamagePlayer</c></see> so prefixes from other mods can activate. (ex : peepers)
/// The base game function will be ignored because the intern playerController is not owned because not spawned
/// </remarks>
/// <param name="damageNumber"></param>
/// <param name="causeOfDeath"></param>
/// <param name="deathAnimation"></param>
/// <param name="fallDamage">Coming from a long fall ?</param>
/// <param name="force">Force applied to the intern when taking the hit</param>
public void SyncDamageIntern(int damageNumber,
CauseOfDeath causeOfDeath = CauseOfDeath.Unknown,
int deathAnimation = 0,
bool fallDamage = false,
Vector3 force = default)
{
PluginLoggerHook.LogDebug?.Invoke($"SyncDamageIntern for LOCAL client #{NetworkManager.LocalClientId}, intern object: Intern #{InternId} {NpcController.Npc.playerUsername}");
if (NpcController.Npc.isPlayerDead)
{
return;
}
if (!NpcController.Npc.AllowPlayerDeath())
{
return;
}
if (IsServer)
{
DamageInternClientRpc(damageNumber, causeOfDeath, deathAnimation, fallDamage, force);
}
else
{
DamageInternServerRpc(damageNumber, causeOfDeath, deathAnimation, fallDamage, force);
}
}
/// <summary>
/// Server side, call clients to update and apply the damage taken by the intern
/// </summary>
/// <param name="damageNumber"></param>
/// <param name="causeOfDeath"></param>
/// <param name="deathAnimation"></param>
/// <param name="fallDamage">Coming from a long fall ?</param>
/// <param name="force">Force applied to the intern when taking the hit</param>
[ServerRpc]
private void DamageInternServerRpc(int damageNumber,
CauseOfDeath causeOfDeath,
int deathAnimation,
bool fallDamage,
Vector3 force)
{
DamageInternClientRpc(damageNumber, causeOfDeath, deathAnimation, fallDamage, force);
}
/// <summary>
/// Client side, update and apply the damage taken by the intern
/// </summary>
/// <param name="damageNumber"></param>
/// <param name="causeOfDeath"></param>
/// <param name="deathAnimation"></param>
/// <param name="fallDamage">Coming from a long fall ?</param>
/// <param name="force">Force applied to the intern when taking the hit</param>
[ClientRpc]
private void DamageInternClientRpc(int damageNumber,
CauseOfDeath causeOfDeath,
int deathAnimation,
bool fallDamage,
Vector3 force)
{
DamageIntern(damageNumber, causeOfDeath, deathAnimation, fallDamage, force);
}
/// <summary>
/// Apply the damage to the intern, kill him if needed, or make critically injured
/// </summary>
/// <param name="damageNumber"></param>
/// <param name="causeOfDeath"></param>
/// <param name="deathAnimation"></param>
/// <param name="fallDamage">Coming from a long fall ?</param>
/// <param name="force">Force applied to the intern when taking the hit</param>
private void DamageIntern(int damageNumber,
CauseOfDeath causeOfDeath,
int deathAnimation,
bool fallDamage,
Vector3 force)
{
PluginLoggerHook.LogDebug?.Invoke(@$"DamageIntern for LOCAL client #{NetworkManager.LocalClientId}, intern object: Intern #{InternId} {NpcController.Npc.playerUsername},
damageNumber {damageNumber}, causeOfDeath {causeOfDeath}, deathAnimation {deathAnimation}, fallDamage {fallDamage}, force {force}");
if (NpcController.Npc.isPlayerDead)
{
return;
}
if (!NpcController.Npc.AllowPlayerDeath())
{
return;
}
// Apply damage, if not killed, set the minimum health to 5
if (NpcController.Npc.health - damageNumber <= 0
&& !NpcController.Npc.criticallyInjured
&& damageNumber < MaxHealthPercent(50)
&& MaxHealthPercent(10) != MaxHealthPercent(20))
{
NpcController.Npc.health = 1;
}
else
{
NpcController.Npc.health = Mathf.Clamp(NpcController.Npc.health - damageNumber, 0, MaxHealth);
}
NpcController.Npc.PlayQuickSpecialAnimation(0.7f);
// Kill intern if necessary
if (NpcController.Npc.health <= 0)
{
if (IsClientOwnerOfIntern())
{
// Call the server to spawn dead bodies
KillInternSpawnBodyServerRpc(spawnBody: true);
}
// Kill on this client side only, since we are already in a rpc send to all clients
KillIntern(force, spawnBody: true, causeOfDeath, deathAnimation, positionOffset: default);
}
else
{
// Critically injured
if ((NpcController.Npc.health < MaxHealthPercent(10) || NpcController.Npc.health == 1)
&& !NpcController.Npc.criticallyInjured)
{
// Client side only, since we are already in an rpc send to all clients
MakeCriticallyInjured();
}
else
{
// Limit sprinting when close to death
if (damageNumber >= MaxHealthPercent(10))
{
NpcController.Npc.sprintMeter = Mathf.Clamp(NpcController.Npc.sprintMeter + damageNumber / 125f, 0f, 1f);
}
}
if (fallDamage)
{
NpcController.Npc.movementAudio.PlayOneShot(StartOfRound.Instance.fallDamageSFX, 1f);
}
else
{
NpcController.Npc.movementAudio.PlayOneShot(StartOfRound.Instance.damageSFX, 1f);
}
// Audio, already in client rpc method so no sync necessary
InternIdentity.Voice.TryPlayVoiceAudio(new PlayVoiceParameters()
{
VoiceState = EnumVoicesState.Hit,
CanTalkIfOtherInternTalk = true,
WaitForCooldown = false,
CutCurrentVoiceStateToTalk = true,
CanRepeatVoiceState = true,
ShouldSync = false,
IsInternInside = NpcController.Npc.isInsideFactory,
AllowSwearing = PluginRuntimeProvider.Context.Config.AllowSwearing
});
}
NpcController.Npc.takingFallDamage = false;
if (!NpcController.Npc.inSpecialInteractAnimation)
{
NpcController.Npc.playerBodyAnimator.SetTrigger(Const.PLAYER_ANIMATION_TRIGGER_DAMAGE);
}
NpcController.Npc.specialAnimationWeight = 1f;
NpcController.Npc.PlayQuickSpecialAnimation(0.7f);
}
public void HealthRegen()
{
if (NpcController.Npc.health < MaxHealthPercent(20)
|| NpcController.Npc.health == 1)
{
if (NpcController.Npc.healthRegenerateTimer <= 0f)
{
NpcController.Npc.healthRegenerateTimer = healthRegenerateTimerMax;
NpcController.Npc.health = NpcController.Npc.health + 1 > MaxHealth ? MaxHealth : NpcController.Npc.health + 1;
if (NpcController.Npc.criticallyInjured &&
(NpcController.Npc.health >= MaxHealthPercent(20) || MaxHealth == 1))
{
Heal();
}
}
else
{
NpcController.Npc.healthRegenerateTimer -= Time.deltaTime;
}
}
}
/// <summary>
/// Update the state of critically injured
/// </summary>
private void MakeCriticallyInjured()
{
NpcController.Npc.bleedingHeavily = true;
NpcController.Npc.criticallyInjured = true;
NpcController.Npc.hasBeenCriticallyInjured = true;
NpcController.Npc.playerBodyAnimator.SetBool(Const.PLAYER_ANIMATION_BOOL_LIMP, true);
}
/// <summary>
/// Heal the intern
/// </summary>
private void Heal()
{
NpcController.Npc.bleedingHeavily = false;
NpcController.Npc.criticallyInjured = false;
NpcController.Npc.playerBodyAnimator.SetBool(Const.PLAYER_ANIMATION_BOOL_LIMP, false);
}
#endregion
#region Kill intern RPC
public override void KillEnemy(bool destroy = false)
{
// The kill function works with player controller instead
return;
}
/// <summary>
/// Sync the action to kill intern between server and clients
/// </summary>
/// <remarks>
/// Better to call <see cref="PlayerControllerB.KillPlayer"><c>PlayerControllerB.KillPlayer</c></see> so prefixes from other mods can activate. (ex : peepers)
/// The base game function will be ignored because the intern playerController is not owned because not spawned
/// </remarks>
/// <param name="bodyVelocity"></param>
/// <param name="spawnBody">Should a body be spawned ?</param>
/// <param name="causeOfDeath"></param>
/// <param name="deathAnimation"></param>
public void SyncKillIntern(Vector3 bodyVelocity,
bool spawnBody = true,
CauseOfDeath causeOfDeath = CauseOfDeath.Unknown,
int deathAnimation = 0,
Vector3 positionOffset = default)
{
PluginLoggerHook.LogDebug?.Invoke($"SyncKillIntern for LOCAL client #{NetworkManager.LocalClientId}, intern object: Intern #{InternId} {NpcController.Npc.playerUsername}");
if (NpcController.Npc.isPlayerDead)
{
return;
}
if (!NpcController.Npc.AllowPlayerDeath())
{
return;
}
if (IsServer)
{
KillInternSpawnBody(spawnBody);
KillInternClientRpc(bodyVelocity, spawnBody, causeOfDeath, deathAnimation, positionOffset);
}
else
{
KillInternServerRpc(bodyVelocity, spawnBody, causeOfDeath, deathAnimation, positionOffset);
}
}
/// <summary>
/// Server side, call clients to do the action to kill intern
/// </summary>
/// <param name="bodyVelocity"></param>
/// <param name="spawnBody"></param>
/// <param name="causeOfDeath"></param>
/// <param name="deathAnimation"></param>
[ServerRpc]
private void KillInternServerRpc(Vector3 bodyVelocity,
bool spawnBody,
CauseOfDeath causeOfDeath,
int deathAnimation,
Vector3 positionOffset)
{
KillInternSpawnBody(spawnBody);
KillInternClientRpc(bodyVelocity, spawnBody, causeOfDeath, deathAnimation, positionOffset);
}
/// <summary>
/// Server side, spawn the ragdoll of the dead body, despawn held object if no dead body to spawn
/// (intern eaten or disappeared in some way)
/// </summary>
/// <param name="spawnBody">Is there a dead body to spawn following the death of the intern ?</param>
[ServerRpc]
private void KillInternSpawnBodyServerRpc(bool spawnBody)
{
KillInternSpawnBody(spawnBody);
}
/// <summary>
/// Spawn the ragdoll of the dead body, despawn held object if no dead body to spawn
/// (intern eaten or disappeared in some way)
/// </summary>
/// <param name="spawnBody">Is there a dead body to spawn following the death of the intern ?</param>
private void KillInternSpawnBody(bool spawnBody)
{
if (!spawnBody)
{
for (int i = 0; i < NpcController.Npc.ItemSlots.Length; i++)
{
GrabbableObject grabbableObject = NpcController.Npc.ItemSlots[i];
if (grabbableObject != null)
{
grabbableObject.gameObject.GetComponent<NetworkObject>().Despawn(true);
}
}
}
else
{
GameObject gameObject = Instantiate(StartOfRound.Instance.ragdollGrabbableObjectPrefab, NpcController.Npc.playersManager.propsContainer);
gameObject.GetComponent<NetworkObject>().Spawn(false);
gameObject.GetComponent<RagdollGrabbableObject>().bodyID.Value = (int)NpcController.Npc.playerClientId;
}
}
/// <summary>
/// Client side, do the action to kill intern
/// </summary>
/// <param name="bodyVelocity"></param>
/// <param name="spawnBody"></param>
/// <param name="causeOfDeath"></param>
/// <param name="deathAnimation"></param>
[ClientRpc]
private void KillInternClientRpc(Vector3 bodyVelocity,
bool spawnBody,
CauseOfDeath causeOfDeath,
int deathAnimation,
Vector3 positionOffset)
{
KillIntern(bodyVelocity, spawnBody, causeOfDeath, deathAnimation, positionOffset);
}
/// <summary>
/// Do the action of killing the intern
/// </summary>
/// <param name="bodyVelocity"></param>
/// <param name="spawnBody"></param>
/// <param name="causeOfDeath"></param>
/// <param name="deathAnimation"></param>
private void KillIntern(Vector3 bodyVelocity,
bool spawnBody,
CauseOfDeath causeOfDeath,
int deathAnimation,
Vector3 positionOffset)
{
PluginLoggerHook.LogDebug?.Invoke(@$"KillIntern for LOCAL client #{NetworkManager.LocalClientId}, intern object: Intern #{InternId} {NpcController.Npc.playerUsername}
bodyVelocity {bodyVelocity}, spawnBody {spawnBody}, causeOfDeath {causeOfDeath}, deathAnimation {deathAnimation}, positionOffset {positionOffset}");
if (NpcController.Npc.isPlayerDead)
{
return;
}
if (!NpcController.Npc.AllowPlayerDeath())
{
return;
}
// If ragdoll body of intern is held
// Release the intern before killing him
if (RagdollInternBody.IsRagdollBodyHeld())
{
PlayerControllerB playerHolder = RagdollInternBody.GetPlayerHolder();
ReleaseIntern(playerHolder.playerClientId);
TeleportIntern(playerHolder.transform.position, !playerHolder.isInsideFactory, isUsingEntrance: false);
}
// Reset body
NpcController.Npc.isPlayerDead = true;
NpcController.Npc.isPlayerControlled = false;
NpcController.Npc.thisPlayerModelArms.enabled = false;
NpcController.Npc.localVisor.position = NpcController.Npc.playersManager.notSpawnedPosition.position;
InternManager.Instance.DisableInternControllerModel(NpcController.Npc.gameObject, NpcController.Npc, enable: false, disableLocalArms: false);
NpcController.Npc.isInsideFactory = false;
NpcController.Npc.IsInspectingItem = false;
NpcController.Npc.inTerminalMenu = false;
NpcController.Npc.twoHanded = false;
NpcController.Npc.isHoldingObject = false;
NpcController.Npc.currentlyHeldObjectServer = null;
NpcController.Npc.carryWeight = 1f;
NpcController.Npc.fallValue = 0f;
NpcController.Npc.fallValueUncapped = 0f;
NpcController.Npc.takingFallDamage = false;
StopSinkingState();
NpcController.Npc.sinkingValue = 0f;
NpcController.Npc.hinderedMultiplier = 1f;
NpcController.Npc.isMovementHindered = 0;
NpcController.Npc.inAnimationWithEnemy = null;
NpcController.Npc.bleedingHeavily = false;
NpcController.Npc.setPositionOfDeadPlayer = true;
NpcController.Npc.snapToServerPosition = false;
NpcController.Npc.causeOfDeath = causeOfDeath;
if (spawnBody)
{
NpcController.Npc.SpawnDeadBody((int)NpcController.Npc.playerClientId, bodyVelocity, (int)causeOfDeath, NpcController.Npc, deathAnimation, null, positionOffset);
if (NpcController.Npc.deadBody != null)
{
ResizeRagdoll(NpcController.Npc.deadBody.transform);
// Replace body position or else disappear with shotgun or knife (don't know why)
NpcController.Npc.deadBody.transform.position = NpcController.Npc.transform.position + Vector3.up + positionOffset;
// Need to be set to true (don't know why) (so many mysteries unsolved tonight)
NpcController.Npc.deadBody.canBeGrabbedBackByPlayers = true;
InternIdentity.DeadBody = NpcController.Npc.deadBody;
// Register body for animation culling
InternManager.Instance.RegisterInternBodyForAnimationCulling(NpcController.Npc.deadBody, HasInternModelReplacementAPI());
}
}
NpcController.Npc.physicsParent = null;
NpcController.Npc.overridePhysicsParent = null;
NpcController.Npc.lastSyncedPhysicsParent = null;
NpcController.CurrentInternPhysicsRegions.Clear();
ReParentIntern(NpcController.Npc.playersManager.playersContainer);
if (HeldItem != null)
{
DropItem();
}
NpcController.Npc.DisableJetpackControlsLocally();
NpcController.IsControllerInCruiser = false;
isEnemyDead = true;
InternIdentity.Hp = 0;
if (agent != null)
{
agent.enabled = false;
}
InternIdentity.Voice.StopAudioFadeOut();
PluginLoggerHook.LogDebug?.Invoke($"Ran kill intern function for LOCAL client #{NetworkManager.LocalClientId}, intern object: Intern #{InternId} {NpcController.Npc.playerUsername}");
// Compat with revive company mod
if (PluginRuntimeProvider.Context.IsModReviveCompanyLoaded)
{
ReviveCompanyHook.ReviveCompanySetPlayerDiedAt?.Invoke((int)Npc.playerClientId);
}
PointOfInterest = null;
}
#endregion
#region Grab intern
[ServerRpc(RequireOwnership = false)]
public void GrabInternServerRpc(ulong idPlayerGrabberController)
{
GrabInternClientRpc(idPlayerGrabberController);
}
[ClientRpc]
private void GrabInternClientRpc(ulong idPlayerGrabberController)
{
PlayerControllerB playerGrabberController = StartOfRound.Instance.allPlayerScripts[idPlayerGrabberController];
InstantiateDeadBodyInfo(playerGrabberController);
RagdollInternBody.SetGrabbedBy(playerGrabberController,
ragdollBodyDeadBodyInfo,
(int)idPlayerGrabberController);
if (idPlayerGrabberController == StartOfRound.Instance.localPlayerController.playerClientId)
{
// Add weight of body
float weightToGain = RagdollInternBody.GetWeight() - 1f < 0f ? 0f : RagdollInternBody.GetWeight() - 1f;
playerGrabberController.carryWeight = Mathf.Clamp(playerGrabberController.carryWeight + weightToGain, 1f, 10f);
weightToGain = NpcController.Npc.carryWeight - 1f < 0f ? 0f : NpcController.Npc.carryWeight - 1f;
playerGrabberController.carryWeight = Mathf.Clamp(playerGrabberController.carryWeight + weightToGain, 1f, 10f);
// Register held interns
InternManager.Instance.RegisterHeldInternForLocalPlayer((int)NpcController.Npc.playerClientId);
// Hide of held ragdoll > 1 is done on BodyReplacementBasePatch after creation of replacementDeadBody
}
if (HeldItem != null)
{
HeldItem.EnableItemMeshes(enable: false);
}
// Hide intern
NpcController.Npc.localVisor.position = NpcController.Npc.playersManager.notSpawnedPosition.position;
InternManager.Instance.DisableInternControllerModel(NpcController.Npc.gameObject, NpcController.Npc, enable: false, disableLocalArms: false);
NpcController.Npc.transform.position = NpcController.Npc.playersManager.notSpawnedPosition.position;
StopSinkingState();
NpcController.Npc.ResetFallGravity();
NpcController.OrderToStopMoving();
// Register body for animation culling
InternManager.Instance.RegisterInternBodyForAnimationCulling(ragdollBodyDeadBodyInfo, HasInternModelReplacementAPI());
}
private void InstantiateDeadBodyInfo(PlayerControllerB playerReference, Vector3 bodyVelocity = default)
{
float num = 1.32f;
int deathAnimation = 0;
Transform parent = null!;
if (playerReference.isInElevator)
{
parent = playerReference.playersManager.elevatorTransform;
}
Vector3 position = NpcController.Npc.thisPlayerBody.position + Vector3.up * num;
Quaternion rotation = NpcController.Npc.thisPlayerBody.rotation;
if (ragdollBodyDeadBodyInfo == null)
{
GameObject gameObject = Instantiate(NpcController.Npc.playersManager.playerRagdolls[deathAnimation],
position,
rotation,
parent);
ragdollBodyDeadBodyInfo = gameObject.GetComponent<DeadBodyInfo>();
}
ragdollBodyDeadBodyInfo.transform.position = position;
ragdollBodyDeadBodyInfo.transform.rotation = rotation;
ragdollBodyDeadBodyInfo.transform.parent = parent;
if (playerReference.physicsParent != null)
{
ragdollBodyDeadBodyInfo.SetPhysicsParent(playerReference.physicsParent);
}
ragdollBodyDeadBodyInfo.parentedToShip = playerReference.isInElevator;
ragdollBodyDeadBodyInfo.playerObjectId = (int)NpcController.Npc.playerClientId;
Rigidbody[] componentsInChildren = ragdollBodyDeadBodyInfo.gameObject.GetComponentsInChildren<Rigidbody>();
for (int i = 0; i < componentsInChildren.Length; i++)
{
componentsInChildren[i].velocity = bodyVelocity;
}
// Scale ragdoll (without stretching the body parts)
ResizeRagdoll(ragdollBodyDeadBodyInfo.transform);
// False with model replacement API
ragdollBodyDeadBodyInfo.gameObject.GetComponentInChildren<SkinnedMeshRenderer>().enabled = true;
// Set suit ID
if (ragdollBodyDeadBodyInfo.setMaterialToPlayerSuit)
{
SkinnedMeshRenderer skinnedMeshRenderer = ragdollBodyDeadBodyInfo.gameObject.GetComponentInChildren<SkinnedMeshRenderer>();
if (skinnedMeshRenderer != null)
{
skinnedMeshRenderer.sharedMaterial = StartOfRound.Instance.unlockablesList.unlockables[NpcController.Npc.currentSuitID].suitMaterial;
skinnedMeshRenderer.renderingLayerMask = 513U | 1U << ragdollBodyDeadBodyInfo.playerObjectId + 12;
}
}
}
/// <summary>
/// Scale ragdoll (without stretching the body parts)
/// </summary>
/// <param name="transform"></param>
private void ResizeRagdoll(Transform transform)
{
// https://discussions.unity.com/t/joint-system-scale-problems/182154/4
// https://stackoverflow.com/questions/68663372/how-to-enlarge-a-ragdoll-in-game-unity
// Grab references to joints anchors, to update them during the game.
Joint[] joints;
List<Vector3> connectedAnchors = new List<Vector3>();
List<Vector3> anchors = new List<Vector3>();
joints = transform.GetComponentsInChildren<Joint>();
Joint curJoint;
for (int i = 0; i < joints.Length; i++)
{
curJoint = joints[i];
connectedAnchors.Add(curJoint.connectedAnchor);
anchors.Add(curJoint.anchor);
}
transform.localScale = new Vector3(PluginRuntimeProvider.Context.Config.InternSizeScale, PluginRuntimeProvider.Context.Config.InternSizeScale, PluginRuntimeProvider.Context.Config.InternSizeScale);
// Update joints by resetting them to their original values
Joint joint;
for (int i = 0; i < joints.Length; i++)
{
joint = joints[i];
joint.connectedAnchor = connectedAnchors[i];
joint.anchor = anchors[i];
}
}
#endregion
#region Release intern
public void SyncReleaseIntern(PlayerControllerB playerGrabberController)
{
// Make the pos slightly different so the interns separate on teleport
Random randomInstance = new Random();
Vector3 randomPos = new Vector3(playerGrabberController.transform.position.x + (float)randomInstance.NextDouble() * 0.1f,
playerGrabberController.transform.position.y,
playerGrabberController.transform.position.z + (float)randomInstance.NextDouble() * 0.1f);
if (IsServer)
{
ReleaseInternClientRpc(playerGrabberController.playerClientId,
randomPos,
!playerGrabberController.isInsideFactory,
isUsingEntrance: false);
}
else
{
ReleaseInternServerRpc(playerGrabberController.playerClientId,
randomPos,
!playerGrabberController.isInsideFactory,
isUsingEntrance: false);
}
}
[ServerRpc]
private void ReleaseInternServerRpc(ulong idPlayerGrabberController,
Vector3 pos, bool setOutside, bool isUsingEntrance)
{
ReleaseInternClientRpc(idPlayerGrabberController, pos, setOutside, isUsingEntrance);
}
[ClientRpc]
private void ReleaseInternClientRpc(ulong idPlayerGrabberController,
Vector3 pos, bool setOutside, bool isUsingEntrance)
{
ReleaseIntern(idPlayerGrabberController);
TeleportIntern(pos, setOutside, isUsingEntrance);
}
private void ReleaseIntern(ulong idPlayerGrabberController)
{
if (idPlayerGrabberController == StartOfRound.Instance.localPlayerController.playerClientId)
{
// Remove weight of body
PlayerControllerB playerGrabberController = StartOfRound.Instance.allPlayerScripts[idPlayerGrabberController];
float weightToLose = RagdollInternBody.GetWeight() - 1f < 0f ? 0f : RagdollInternBody.GetWeight() - 1f;
playerGrabberController.carryWeight = Mathf.Clamp(playerGrabberController.carryWeight - weightToLose, 1f, 10f);
weightToLose = NpcController.Npc.carryWeight - 1f < 0f ? 0f : NpcController.Npc.carryWeight - 1f;
playerGrabberController.carryWeight = Mathf.Clamp(playerGrabberController.carryWeight - weightToLose, 1f, 10f);
// Unregister held interns
InternManager.Instance.UnregisterHeldInternForLocalPlayer((int)NpcController.Npc.playerClientId);
InternManager.Instance.HideShowRagdollModel(NpcController.Npc, show: true);
}
if (HeldItem != null)
{
HeldItem.EnableItemMeshes(enable: true);
}
RagdollInternBody.Hide();
// Enable model
InternManager.Instance.DisableInternControllerModel(NpcController.Npc.gameObject, NpcController.Npc, enable: true, disableLocalArms: true);
// Set intern to follow
SetCommandToFollowPlayer();
}
#endregion
#region Spawn animation
public bool IsSpawningAnimationRunning()
{
return spawnAnimationCoroutine != null;
}
public Coroutine BeginInternSpawnAnimation(EnumSpawnAnimation enumSpawnAnimation)
{
switch (enumSpawnAnimation)
{
case EnumSpawnAnimation.None:
return StartCoroutine(CoroutineNoSpawnAnimation());
case EnumSpawnAnimation.OnlyPlayerSpawnAnimation:
return StartCoroutine(CoroutineOnlyPlayerSpawnAnimation());
case EnumSpawnAnimation.RagdollFromDropShipAndPlayerSpawnAnimation:
return StartCoroutine(CoroutineFromDropShipAndPlayerSpawnAnimation());
default:
return StartCoroutine(CoroutineNoSpawnAnimation());
}
}
private IEnumerator CoroutineNoSpawnAnimation()
{
if (!IsOwner)
{
spawnAnimationCoroutine = null;
yield break;
}
if (IsOwner)
{
// Change ai state
SyncAssignTargetAndSetMovingTo(GetClosestIrlPlayer());
}
yield return null;
if (IsOwner)
{
// Teleport again, cuz I don't know why the teleport does not work first time
TeleportAgentAIAndBody(GameNetworkManager.Instance.localPlayerController.transform.position);
}
spawnAnimationCoroutine = null;
yield break;
}
private IEnumerator CoroutineOnlyPlayerSpawnAnimation()
{
if (!IsOwner)
{
// Wait for spawn player animation
yield return new WaitForSeconds(3f);
NpcController.Npc.inSpecialInteractAnimation = false;
spawnAnimationCoroutine = null;
yield break;
}
UpdateInternSpecialAnimationValue(specialAnimation: true, timed: 0f, climbingLadder: false);
NpcController.Npc.inSpecialInteractAnimation = true;
NpcController.Npc.playerBodyAnimator.ResetTrigger("SpawnPlayer");
NpcController.Npc.playerBodyAnimator.SetTrigger("SpawnPlayer");
yield return new WaitForSeconds(3f);
NpcController.Npc.inSpecialInteractAnimation = false;
UpdateInternSpecialAnimationValue(specialAnimation: false, timed: 0f, climbingLadder: false);
// Change ai state
SyncAssignTargetAndSetMovingTo(GetClosestIrlPlayer());
spawnAnimationCoroutine = null;
yield break;
}
private IEnumerator CoroutineFromDropShipAndPlayerSpawnAnimation()
{
if (PluginRuntimeProvider.Context.IsModModelReplacementAPILoaded)
{
// Wait for model replacement to add its component
yield return new WaitForEndOfFrame();
// Wait for model replacement to init replacement models
yield return new WaitForEndOfFrame();
}
animationCoroutineRagdollingRunning = true;
PlayerControllerB closestPlayer = GetClosestIrlPlayer();
// Spawn ragdoll
InstantiateDeadBodyInfo(closestPlayer, GetRandomPushForce(InternManager.Instance.ItemDropShipPos + new Vector3(0, -1f, 0), NpcController.Npc.transform.position, 4f));
RagdollInternBody.SetFreeRagdoll(ragdollBodyDeadBodyInfo);
// Hide intern
if (PluginRuntimeProvider.Context.IsModModelReplacementAPILoaded)
{
ModelReplacementAPIHook.HideShowReplacementModelOnlyBody?.Invoke(Npc, this, show: false);
}
else
{
InternManager.Instance.DisableInternControllerModel(NpcController.Npc.gameObject, NpcController.Npc, enable: false, disableLocalArms: false);
HideShowLevelStickerBetaBadge(show: false);
}
yield return null;
// Voice
InternIdentity.Voice.TryPlayVoiceAudio(new PlayVoiceParameters()
{
VoiceState = EnumVoicesState.Hit,
CanTalkIfOtherInternTalk = true,
WaitForCooldown = false,
CutCurrentVoiceStateToTalk = true,
CanRepeatVoiceState = false,
ShouldSync = false,
IsInternInside = NpcController.Npc.isInsideFactory,
AllowSwearing = PluginRuntimeProvider.Context.Config.AllowSwearing
});
// Wait in ragdoll state
yield return new WaitForSeconds(2.5f);
// End of ragdoll wait
animationCoroutineRagdollingRunning = false;
// Enable model
if (PluginRuntimeProvider.Context.IsModModelReplacementAPILoaded)
{
ModelReplacementAPIHook.HideShowReplacementModelOnlyBody?.Invoke(Npc, this, show: true);
}
else
{
InternManager.Instance.DisableInternControllerModel(NpcController.Npc.gameObject, NpcController.Npc, enable: true, disableLocalArms: true);
HideShowLevelStickerBetaBadge(show: true);
}
// Hide ragdoll
RagdollInternBody.Hide();
if (!IsOwner)
{
// Wait for spawn player animation
yield return new WaitForSeconds(3f);
NpcController.Npc.inSpecialInteractAnimation = false;
spawnAnimationCoroutine = null;
yield break;
}
DeadBodyInfo? deadBodyInfo = RagdollInternBody.GetDeadBodyInfo();
TeleportAgentAIAndBody(deadBodyInfo == null ? NpcController.Npc.transform.position : deadBodyInfo.transform.position);
UpdateInternSpecialAnimationValue(specialAnimation: true, timed: 0f, climbingLadder: false);
NpcController.Npc.inSpecialInteractAnimation = true;
NpcController.Npc.playerBodyAnimator.ResetTrigger("SpawnPlayer");
NpcController.Npc.playerBodyAnimator.SetTrigger("SpawnPlayer");
// Wait in spawn player animation
yield return new WaitForSeconds(3f);
NpcController.Npc.inSpecialInteractAnimation = false;
UpdateInternSpecialAnimationValue(specialAnimation: false, timed: 0f, climbingLadder: false);
// Change ai state
SyncAssignTargetAndSetMovingTo(closestPlayer);
spawnAnimationCoroutine = null;
yield break;
}
private PlayerControllerB GetClosestIrlPlayer()
{
PlayerControllerB closest = null!;
for (int i = 0; i < InternManager.Instance.IndexBeginOfInterns; i++)
{
PlayerControllerB player = StartOfRound.Instance.allPlayerScripts[i];
if (!player.isPlayerControlled
|| player.isPlayerDead)
{
continue;
}
if (closest == null
|| (player.transform.position - NpcController.Npc.transform.position).sqrMagnitude < (closest.transform.position - NpcController.Npc.transform.position).sqrMagnitude)
{
closest = player;
}
}
return closest;
}
private Vector3 GetRandomPushForce(Vector3 origin, Vector3 point, float forceMean)
{
point.y += UnityEngine.Random.Range(2f, 4f);
//DrawUtil.DrawWhiteLine(LineRendererUtil.GetLineRenderer(), new Ray(origin, point - origin), Vector3.Distance(point, origin));
float force = UnityEngine.Random.Range(forceMean * 0.5f, forceMean * 1.5f);
return Vector3.Normalize(point - origin) * force / Vector3.Distance(point, origin);
}
#endregion
#region Jump RPC
/// <summary>
/// Sync the intern doing a jump between server and clients
/// </summary>
public void SyncJump()
{
if (IsServer)
{
JumpClientRpc();
}
else
{
JumpServerRpc();
}
}
/// <summary>
/// Server side, call clients to update the intern doing a jump
/// </summary>
[ServerRpc(RequireOwnership = false)]
private void JumpServerRpc()
{
JumpClientRpc();
}
/// <summary>
/// Client side, update the action of intern doing a jump
/// only for not the owner
/// </summary>
[ClientRpc]
private void JumpClientRpc()
{
if (!IsClientOwnerOfIntern())
{
PlayerControllerBHook.PlayJumpAudio_ReversePatch?.Invoke(NpcController.Npc);
}
}
#endregion
#region Land from Jump RPC
/// <summary>
/// Sync the landing of the jump of the intern, between server and clients
/// </summary>
/// <param name="fallHard"></param>
public void SyncLandFromJump(bool fallHard)
{
if (IsServer)
{
JumpLandFromClientRpc(fallHard);
}
else
{
JumpLandFromServerRpc(fallHard);
}
}
/// <summary>
/// Server side, call clients to update the action of intern land from jump
/// </summary>
/// <param name="fallHard"></param>
[ServerRpc(RequireOwnership = false)]
private void JumpLandFromServerRpc(bool fallHard)
{
JumpLandFromClientRpc(fallHard);
}
/// <summary>
/// Client side, update the action of intern land from jump
/// </summary>
/// <param name="fallHard"></param>
[ClientRpc]
private void JumpLandFromClientRpc(bool fallHard)
{
if (fallHard)
{
NpcController.Npc.movementAudio.PlayOneShot(StartOfRound.Instance.playerHitGroundHard, 1f);
return;
}
NpcController.Npc.movementAudio.PlayOneShot(StartOfRound.Instance.playerHitGroundSoft, 0.7f);
}
#endregion
#region Sinking RPC
/// <summary>
/// Sync the state of sink of the intern between server and clients
/// </summary>
/// <param name="startSinking"></param>
/// <param name="sinkingSpeed"></param>
/// <param name="audioClipIndex"></param>
public void SyncChangeSinkingState(bool startSinking, float sinkingSpeed = 0f, int audioClipIndex = 0)
{
if (IsServer)
{
ChangeSinkingStateClientRpc(startSinking, sinkingSpeed, audioClipIndex);
}
else
{
ChangeSinkingStateServerRpc(startSinking, sinkingSpeed, audioClipIndex);
}
}
/// <summary>
/// Server side, call clients to update the state of sink of the intern
/// </summary>
/// <param name="startSinking"></param>
/// <param name="sinkingSpeed"></param>
/// <param name="audioClipIndex"></param>
[ServerRpc]
private void ChangeSinkingStateServerRpc(bool startSinking, float sinkingSpeed, int audioClipIndex)
{
ChangeSinkingStateClientRpc(startSinking, sinkingSpeed, audioClipIndex);
}
/// <summary>
/// Client side, update the state of sink of the intern
/// </summary>
/// <param name="startSinking"></param>
/// <param name="sinkingSpeed"></param>
/// <param name="audioClipIndex"></param>
[ClientRpc]
private void ChangeSinkingStateClientRpc(bool startSinking, float sinkingSpeed, int audioClipIndex)
{
if (startSinking)
{
NpcController.Npc.sinkingSpeedMultiplier = sinkingSpeed;
NpcController.Npc.isSinking = true;
NpcController.Npc.statusEffectAudio.clip = StartOfRound.Instance.statusEffectClips[audioClipIndex];
NpcController.Npc.statusEffectAudio.Play();
}
else
{
StopSinkingState();
}
}
public void StopSinkingState()
{
NpcController.Npc.isSinking = false;
NpcController.Npc.statusEffectAudio.volume = 0f;
NpcController.Npc.statusEffectAudio.Stop();
NpcController.Npc.voiceMuffledByEnemy = false;
NpcController.Npc.sourcesCausingSinking = 0;
NpcController.Npc.isMovementHindered = 0;
NpcController.Npc.hinderedMultiplier = 1f;
NpcController.Npc.isUnderwater = false;
NpcController.Npc.underwaterCollider = null;
}
#endregion
#region Disable Jetpack RPC
/// <summary>
/// Sync the disabling of jetpack mode between server and clients
/// </summary>
public void SyncDisableJetpackMode()
{
if (IsServer)
{
DisableJetpackModeClientRpc();
}
else
{
DisableJetpackModeServerRpc();
}
}
/// <summary>
/// Server side, call clients to update the disabling of jetpack mode between server and clients
/// </summary>
[ServerRpc]
private void DisableJetpackModeServerRpc()
{
DisableJetpackModeClientRpc();
}
/// <summary>
/// Client side, update the disabling of jetpack mode between server and clients
/// </summary>
[ClientRpc]
private void DisableJetpackModeClientRpc()
{
NpcController.Npc.DisableJetpackControlsLocally();
}
#endregion
#region Stop performing emote RPC
/// <summary>
/// Sync the stopping the perfoming of emote between server and clients
/// </summary>
public void SyncStopPerformingEmote()
{
if (IsServer)
{
StopPerformingEmoteClientRpc();
}
else
{
StopPerformingEmoteServerRpc();
}
}
/// <summary>
/// Server side, call clients to update the stopping the perfoming of emote
/// </summary>
[ServerRpc]
private void StopPerformingEmoteServerRpc()
{
StopPerformingEmoteClientRpc();
}
/// <summary>
/// Update the stopping the perfoming of emote
/// </summary>
[ClientRpc]
private void StopPerformingEmoteClientRpc()
{
NpcController.Npc.performingEmote = false;
}
#endregion
#region Interns suits
[ServerRpc(RequireOwnership = false)]
public void ChangeSuitInternServerRpc(ulong idInternController, int suitID)
{
ChangeSuitIntern(idInternController, suitID, playAudio: true);
ChangeSuitInternClientRpc(idInternController, suitID);
}
[ClientRpc]
private void ChangeSuitInternClientRpc(ulong idInternController, int suitID)
{
if (IsServer)
{
return;
}
ChangeSuitIntern(idInternController, suitID, playAudio: true);
}
public void ChangeSuitIntern(ulong idInternController, int suitID, bool playAudio = false)
{
if (suitID > StartOfRound.Instance.unlockablesList.unlockables.Count())
{
suitID = 0;
}
PlayerControllerB internController = StartOfRound.Instance.allPlayerScripts[idInternController];
UnlockableSuit.SwitchSuitForPlayer(internController, suitID, playAudio);
internController.thisPlayerModelArms.enabled = false;
StartCoroutine(WaitSecondsForChangeSuitToApply());
InternIdentity.SuitID = suitID;
PluginLoggerHook.LogDebug?.Invoke($"Changed suit of intern {NpcController.Npc.playerUsername} to {suitID}: {StartOfRound.Instance.unlockablesList.unlockables[suitID].unlockableName}");
}
public bool HasInternModelReplacementAPI()
{
return PluginRuntimeProvider.Context.IsModModelReplacementAPILoaded ? ModelReplacementAPIHook.HasComponentModelReplacementAPI?.Invoke(NpcController.Npc.gameObject) ?? false : false;
}
private IEnumerator WaitSecondsForChangeSuitToApply()
{
yield return new WaitForSeconds(0.2f);
NpcController.RefreshBillBoardPosition();
IInternCullingBodyInfo? internCullingBodyInfo = InternManager.Instance.GetInternCullingBodyInfo(NpcController.Npc.gameObject);
if (internCullingBodyInfo != null)
{
internCullingBodyInfo.HasModelReplacement = HasInternModelReplacementAPI();
}
yield break;
}
#endregion
#region Emotes
[ServerRpc(RequireOwnership = false)]
public void StartPerformingEmoteInternServerRpc(int emoteID)
{
StartPerformingEmoteInternClientRpc(emoteID);
}
[ClientRpc]
private void StartPerformingEmoteInternClientRpc(int emoteID)
{
NpcController.Npc.performingEmote = true;
NpcController.Npc.playerBodyAnimator.SetInteger("emoteNumber", emoteID);
}
#endregion
#region TooManyEmotes
[ServerRpc(RequireOwnership = false)]
public void PerformTooManyEmoteInternServerRpc(int tooManyEmoteID)
{
PerformTooManyInternClientRpc(tooManyEmoteID);
}
[ClientRpc]
private void PerformTooManyInternClientRpc(int tooManyEmoteID)
{
NpcController.PerformTooManyEmote(tooManyEmoteID);
}
[ServerRpc(RequireOwnership = false)]
public void StopPerformTooManyEmoteInternServerRpc()
{
StopPerformTooManyInternClientRpc();
}
[ClientRpc]
private void StopPerformTooManyInternClientRpc()
{
NpcController.StopPerformingTooManyEmote();
}
#endregion
#region Npc adapter
public Vector3 GetBillBoardPosition(GameObject bodyModel)
{
return npcController.GetBillBoardPosition(bodyModel, Npc.usernameCanvas.transform.localPosition);
}
#endregion
public float GetAngleFOVWithLocalPlayer(Transform localPlayerCameraTransform, Vector3 internBodyPos)
{
return this.AngleFOVWithLocalPlayerTimedCheck.GetAngleFOVWithLocalPlayer(localPlayerCameraTransform, internBodyPos);
}
public float GetClosestPlayerDistance()
{
if (GetClosestPlayerDistanceTimed == null)
{
GetClosestPlayerDistanceTimed = new TimedGetClosestPlayerDistance();
}
return GetClosestPlayerDistanceTimed.GetClosestPlayerDistance(this.Npc.transform.position);
}
#region GiantKiwi stuff
[ServerRpc(RequireOwnership = false)]
public void SyncWatchingThreatGiantKiwiServerRpc(NetworkObjectReference giantKiwiNOR)
{
SyncWatchingThreatGiantKiwiClientRpc(giantKiwiNOR);
}
[ClientRpc]
private void SyncWatchingThreatGiantKiwiClientRpc(NetworkObjectReference giantKiwiNOR)
{
giantKiwiNOR.TryGet(out NetworkObject giantKiwiNO);
GiantKiwiAI? giantKiwiAI = giantKiwiNO.gameObject.GetComponent<GiantKiwiAI>();
if (giantKiwiAI == null)
{
PluginLoggerHook.LogError?.Invoke($"SyncWatchingThreatGiantKiwiClientRpc intern {Npc.playerClientId} giantKiwiNOR -> giantKiwiAI null");
return;
}
Type typeGiantKiwiAI = giantKiwiAI.GetType();
IVisibleThreat? watchingThreat = this.npcController.Npc.GetComponent<IVisibleThreat>();
if (giantKiwiAI == null)
{
PluginLoggerHook.LogError?.Invoke($"SyncWatchingThreatGiantKiwiClientRpc intern {Npc.playerClientId} no IVisibleThreat");
return;
}
typeGiantKiwiAI.GetField("watchingThreat", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)?.SetValue(giantKiwiAI, watchingThreat);
}
[ServerRpc(RequireOwnership = false)]
public void SyncAttackingThreatGiantKiwiServerRpc(NetworkObjectReference giantKiwiNOR)
{
SyncAttackingThreatGiantKiwiClientRpc(giantKiwiNOR);
}
[ClientRpc]
private void SyncAttackingThreatGiantKiwiClientRpc(NetworkObjectReference giantKiwiNOR)
{
giantKiwiNOR.TryGet(out NetworkObject giantKiwiNO);
GiantKiwiAI? giantKiwiAI = giantKiwiNO.gameObject.GetComponent<GiantKiwiAI>();
if (giantKiwiAI == null)
{
PluginLoggerHook.LogError?.Invoke($"SyncAttackingThreatGiantKiwiClientRpc intern {Npc.playerClientId} giantKiwiNOR -> giantKiwiAI null");
return;
}
Type typeGiantKiwiAI = giantKiwiAI.GetType();
IVisibleThreat? attackingThreat = this.npcController.Npc.GetComponent<IVisibleThreat>();
if (giantKiwiAI == null)
{
PluginLoggerHook.LogError?.Invoke($"SyncAttackingThreatGiantKiwiClientRpc intern {Npc.playerClientId} no IVisibleThreat");
return;
}
typeGiantKiwiAI.GetField("watchingThreat", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)?.SetValue(giantKiwiAI, attackingThreat);
typeGiantKiwiAI.GetField("attackingThreat", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)?.SetValue(giantKiwiAI, attackingThreat);
giantKiwiAI.Screech(enraged: true);
giantKiwiAI.SwitchToBehaviourStateOnLocalClient(stateIndex: 2);
}
#endregion
}
} | 412 | 0.968315 | 1 | 0.968315 | game-dev | MEDIA | 0.985963 | game-dev | 0.838816 | 1 | 0.838816 |
GregHib/void | 1,237 | game/src/main/kotlin/content/area/morytania/slayer_tower/AberrantSpectre.kt | package content.area.morytania.slayer_tower
import content.entity.combat.hit.npcCombatAttack
import content.entity.player.equip.Equipment
import world.gregs.voidps.engine.entity.character.player.Player
import world.gregs.voidps.engine.entity.character.player.equip.equipped
import world.gregs.voidps.engine.entity.character.player.skill.Skill
import world.gregs.voidps.engine.event.Script
import world.gregs.voidps.network.login.protocol.visual.update.player.EquipSlot
@Script
class AberrantSpectre {
init {
npcCombatAttack("aberrant_spectre") {
if (target !is Player) {
return@npcCombatAttack
}
if (!Equipment.isNosePeg(target.equipped(EquipSlot.Hat).id)) {
target.levels.drain(Skill.Attack, multiplier = 0.8)
target.levels.drain(Skill.Strength, multiplier = 0.8)
target.levels.drain(Skill.Defence, multiplier = 0.6)
target.levels.drain(Skill.Ranged, multiplier = 0.8)
target.levels.drain(Skill.Magic, multiplier = 0.8)
target.levels.drain(Skill.Prayer, multiplier = 0.5)
target.levels.drain(Skill.Agility, multiplier = 0.6)
}
}
}
}
| 412 | 0.747585 | 1 | 0.747585 | game-dev | MEDIA | 0.856034 | game-dev | 0.899846 | 1 | 0.899846 |
hiperbou/kotlin-phaser | 1,954 | examples/src/main/kotlin/examples/display/Gradient.kt |
package examples.display
import Phaser.*
class Gradient: State() {
//var game = Phaser.Game(800, 600, Phaser.CANVAS, "phaser-example", object{ var preload= preload; var create= create })
override fun preload() {
// game.load.image("hotdog", "assets/sprites/hotdog.png")
}
override fun create() {
game.stage.backgroundColor = "#0c9fc7"
/**
* Interpolates the two given colours based on the supplied step and currentStep properties.
*
* @method Phaser.Color.interpolateColor
* @static
* @param object{ var number} color1 - The first color value.
* @param object{ var number} color2 - The second color value.
* @param object{ var number} steps - The number of steps to run the interpolation over.
* @param object{ var number} currentStep - The currentStep value. If the interpolation will take 100 steps, a currentStep value of 50 would be half-way between the two.
* @param object{ var number} alpha - The alpha of the returned color.
* @returns object{ var number} The interpolated color value.
*/
// interpolateColor: fun (color1, color2, steps, currentStep, alpha) {
var out = mutableListOf<String>()
var bmd = game.add.bitmapData(800, 600)
bmd.addToWorld()
var y = 0
for(i in 0..30-1)
{
var c = Phaser.Color.interpolateColor(0x66d973, 0x40b54d, 30, i)
// console.log(Phaser.Color.getWebRGB(c))
bmd.rect(0, y, 800, y+2, Phaser.Color.getWebRGB(c))
out.add(Phaser.Color.getWebRGB(c))
y += 2
}
for(i in 0..60-1)
{
var c = Phaser.Color.interpolateColor(0x40b54d, 0x1d962b, 60, i)
// console.log(Phaser.Color.getWebRGB(c))
bmd.rect(0, y, 800, y+2, Phaser.Color.getWebRGB(c))
out.add(Phaser.Color.getWebRGB(c))
y += 2
}
// console.log(out)
console.log(JSON.stringify(out))
}
} | 412 | 0.630351 | 1 | 0.630351 | game-dev | MEDIA | 0.672318 | game-dev,graphics-rendering | 0.810247 | 1 | 0.810247 |
lua9520/source-engine-2018-hl2_src | 22,665 | engine/GameEventManager.cpp | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
// GameEventManager.cpp: implementation of the CGameEventManager class.
//
//////////////////////////////////////////////////////////////////////
#include "GameEventManager.h"
#include "filesystem_engine.h"
#include "server.h"
#include "client.h"
#include "tier0/vprof.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
static CGameEventManager s_GameEventManager;
CGameEventManager &g_GameEventManager = s_GameEventManager;
static const char *s_GameEnventTypeMap[] =
{ "local", // 0 : don't network this field
"string", // 1 : zero terminated ASCII string
"float", // 2 : float 32 bit
"long", // 3 : signed int 32 bit
"short", // 4 : signed int 16 bit
"byte", // 5 : unsigned int 8 bit
"bool", // 6 : unsigned int 1 bit
NULL };
static ConVar net_showevents( "net_showevents", "0", FCVAR_CHEAT, "Dump game events to console (1=client only, 2=all)." );
// Expose CVEngineServer to the engine.
EXPOSE_SINGLE_INTERFACE_GLOBALVAR( CGameEventManager, IGameEventManager2, INTERFACEVERSION_GAMEEVENTSMANAGER2, s_GameEventManager );
CGameEvent::CGameEvent( CGameEventDescriptor *descriptor )
{
Assert( descriptor );
m_pDescriptor = descriptor;
m_pDataKeys = new KeyValues( descriptor->name );
}
CGameEvent::~CGameEvent()
{
m_pDataKeys->deleteThis();
}
bool CGameEvent::GetBool( const char *keyName, bool defaultValue)
{
return m_pDataKeys->GetInt( keyName, defaultValue ) != 0;
}
int CGameEvent::GetInt( const char *keyName, int defaultValue)
{
return m_pDataKeys->GetInt( keyName, defaultValue );
}
float CGameEvent::GetFloat( const char *keyName, float defaultValue )
{
return m_pDataKeys->GetFloat( keyName, defaultValue );
}
const char *CGameEvent::GetString( const char *keyName, const char *defaultValue )
{
return m_pDataKeys->GetString( keyName, defaultValue );
}
void CGameEvent::SetBool( const char *keyName, bool value )
{
m_pDataKeys->SetInt( keyName, value?1:0 );
}
void CGameEvent::SetInt( const char *keyName, int value )
{
m_pDataKeys->SetInt( keyName, value );
}
void CGameEvent::SetFloat( const char *keyName, float value )
{
m_pDataKeys->SetFloat( keyName, value );
}
void CGameEvent::SetString( const char *keyName, const char *value )
{
m_pDataKeys->SetString( keyName, value );
}
bool CGameEvent::IsEmpty( const char *keyName )
{
return m_pDataKeys->IsEmpty( keyName );
}
const char *CGameEvent::GetName() const
{
return m_pDataKeys->GetName();
}
bool CGameEvent::IsLocal() const
{
return m_pDescriptor->local;
}
bool CGameEvent::IsReliable() const
{
return m_pDescriptor->reliable;
}
CGameEventManager::CGameEventManager()
{
Reset();
}
CGameEventManager::~CGameEventManager()
{
Reset();
}
bool CGameEventManager::Init()
{
Reset();
LoadEventsFromFile( "resource/serverevents.res" );
return true;
}
void CGameEventManager::Shutdown()
{
Reset();
}
void CGameEventManager::Reset()
{
int number = m_GameEvents.Count();
for (int i = 0; i<number; i++)
{
CGameEventDescriptor &e = m_GameEvents.Element( i );
if ( e.keys )
{
e.keys->deleteThis(); // free the value keys
e.keys = NULL;
}
e.listeners.Purge(); // remove listeners
}
m_GameEvents.Purge();
m_Listeners.PurgeAndDeleteElements();
m_EventFiles.RemoveAll();
m_EventFileNames.RemoveAll();
m_bClientListenersChanged = true;
Assert( m_GameEvents.Count() == 0 );
}
bool CGameEventManager::HasClientListenersChanged( bool bReset /* = true */)
{
if ( !m_bClientListenersChanged )
return false;
if ( bReset )
m_bClientListenersChanged = false;
return true;
}
void CGameEventManager::WriteEventList(SVC_GameEventList *msg)
{
// reset event ids to -1 first
msg->m_nNumEvents = 0;
for (int i=0; i < m_GameEvents.Count(); i++ )
{
CGameEventDescriptor &descriptor = m_GameEvents[i];
if ( descriptor.local )
continue;
Assert( descriptor.eventid >= 0 && descriptor.eventid < MAX_EVENT_NUMBER );
msg->m_DataOut.WriteUBitLong( descriptor.eventid, MAX_EVENT_BITS );
msg->m_DataOut.WriteString( descriptor.name );
KeyValues *key = descriptor.keys->GetFirstSubKey();
while ( key )
{
int type = key->GetInt();
if ( type != TYPE_LOCAL )
{
msg->m_DataOut.WriteUBitLong( type, 3 );
msg->m_DataOut.WriteString( key->GetName() );
}
key = key->GetNextKey();
}
msg->m_DataOut.WriteUBitLong( TYPE_LOCAL, 3 ); // end marker
msg->m_nNumEvents++;
}
}
bool CGameEventManager::ParseEventList(SVC_GameEventList *msg)
{
int i;
// reset eventids to -1 first
for ( i=0; i < m_GameEvents.Count(); i++ )
{
CGameEventDescriptor &descriptor = m_GameEvents[i];
descriptor.eventid = -1;
}
// map server event IDs
for (i = 0; i<msg->m_nNumEvents; i++)
{
int id = msg->m_DataIn.ReadUBitLong( MAX_EVENT_BITS );
char name[MAX_EVENT_NAME_LENGTH];
msg->m_DataIn.ReadString( name, sizeof(name) );
CGameEventDescriptor *descriptor = GetEventDescriptor( name );
if ( !descriptor )
{
// event unknown to client, skip data
while ( msg->m_DataIn.ReadUBitLong( 3 ) )
msg->m_DataIn.ReadString( name, sizeof(name) );
continue;
}
// remove old definition list
if ( descriptor->keys )
descriptor->keys->deleteThis();
descriptor->keys = new KeyValues("descriptor");
int datatype = msg->m_DataIn.ReadUBitLong( 3 );
while ( datatype != TYPE_LOCAL )
{
msg->m_DataIn.ReadString( name, sizeof(name) );
descriptor->keys->SetInt( name, datatype );
datatype = msg->m_DataIn.ReadUBitLong( 3 );
}
descriptor->eventid = id;
}
// force client to answer what events he listens to
m_bClientListenersChanged = true;
return true;
}
void CGameEventManager::WriteListenEventList(CLC_ListenEvents *msg)
{
msg->m_EventArray.ClearAll();
// and know tell the server what events we want to listen to
for (int i=0; i < m_GameEvents.Count(); i++ )
{
CGameEventDescriptor &descriptor = m_GameEvents[i];
bool bHasClientListener = false;
for ( int j=0; j<descriptor.listeners.Count(); j++ )
{
CGameEventCallback *listener = descriptor.listeners[j];
if ( listener->m_nListenerType == CGameEventManager::CLIENTSIDE ||
listener->m_nListenerType == CGameEventManager::CLIENTSIDE_OLD )
{
// if we have a client side listener and server knows this event, add it
bHasClientListener = true;
break;
}
}
if ( !bHasClientListener )
continue;
if ( descriptor.eventid == -1 )
{
DevMsg("Warning! Client listens to event '%s' unknown by server.\n", descriptor.name );
continue;
}
msg->m_EventArray.Set( descriptor.eventid );
}
}
IGameEvent *CGameEventManager::CreateEvent( CGameEventDescriptor *descriptor )
{
return new CGameEvent ( descriptor );
}
IGameEvent *CGameEventManager::CreateEvent( const char *name, bool bForce )
{
if ( !name || !name[0] )
return NULL;
CGameEventDescriptor *descriptor = GetEventDescriptor( name );
// check if this event name is known
if ( !descriptor )
{
DevMsg( "CreateEvent: event '%s' not registered.\n", name );
return NULL;
}
// event is known but no one listen to it
if ( descriptor->listeners.Count() == 0 && !bForce )
{
return NULL;
}
// create & return the new event
return new CGameEvent ( descriptor );
}
bool CGameEventManager::FireEvent( IGameEvent *event, bool bServerOnly )
{
return FireEventIntern( event, bServerOnly, false );
}
bool CGameEventManager::FireEventClientSide( IGameEvent *event )
{
return FireEventIntern( event, false, true );
}
IGameEvent *CGameEventManager::DuplicateEvent( IGameEvent *event )
{
CGameEvent *gameEvent = dynamic_cast<CGameEvent*>(event);
if ( !gameEvent )
return NULL;
// create new instance
CGameEvent *newEvent = new CGameEvent ( gameEvent->m_pDescriptor );
// free keys
newEvent->m_pDataKeys->deleteThis();
// and make copy
newEvent->m_pDataKeys = gameEvent->m_pDataKeys->MakeCopy();
return newEvent;
}
void CGameEventManager::ConPrintEvent( IGameEvent *event)
{
CGameEventDescriptor *descriptor = GetEventDescriptor( event );
if ( !descriptor )
return;
KeyValues *key = descriptor->keys->GetFirstSubKey();
while ( key )
{
const char * keyName = key->GetName();
int type = key->GetInt();
switch ( type )
{
case TYPE_LOCAL : ConMsg( "- \"%s\" = \"%s\" (local)\n", keyName, event->GetString(keyName) ); break;
case TYPE_STRING : ConMsg( "- \"%s\" = \"%s\"\n", keyName, event->GetString(keyName) ); break;
case TYPE_FLOAT : ConMsg( "- \"%s\" = \"%.2f\"\n", keyName, event->GetFloat(keyName) ); break;
default: ConMsg( "- \"%s\" = \"%i\"\n", keyName, event->GetInt(keyName) ); break;
}
key = key->GetNextKey();
}
}
bool CGameEventManager::FireEventIntern( IGameEvent *event, bool bServerOnly, bool bClientOnly )
{
if ( event == NULL )
return false;
Assert( !(bServerOnly && bClientOnly) ); // it can't be both
VPROF_("CGameEventManager::FireEvent", 1, VPROF_BUDGETGROUP_OTHER_UNACCOUNTED, false,
bClientOnly ? BUDGETFLAG_CLIENT : ( bServerOnly ? BUDGETFLAG_SERVER : BUDGETFLAG_OTHER ) );
CGameEventDescriptor *descriptor = GetEventDescriptor( event );
if ( descriptor == NULL )
{
DevMsg( "FireEvent: event '%s' not registered.\n", event->GetName() );
FreeEvent( event );
return false;
}
tmZoneFiltered( TELEMETRY_LEVEL0, 50, TMZF_NONE, "%s (name: %s listeners: %d)", __FUNCTION__, tmDynamicString( TELEMETRY_LEVEL0, event->GetName() ), descriptor->listeners.Count() );
// show game events in console
if ( net_showevents.GetInt() > 0 )
{
if ( bClientOnly )
{
ConMsg( "Game event \"%s\", Tick %i:\n", descriptor->name, cl.GetClientTickCount() );
ConPrintEvent( event );
}
else if ( net_showevents.GetInt() > 1 )
{
ConMsg( "Server event \"%s\", Tick %i:\n", descriptor->name, sv.GetTick() );
ConPrintEvent( event );
}
}
for ( int i = 0; i < descriptor->listeners.Count(); i++ )
{
CGameEventCallback *listener = descriptor->listeners.Element( i );
Assert ( listener );
// don't trigger server listners for clientside only events
if ( ( listener->m_nListenerType == SERVERSIDE ||
listener->m_nListenerType == SERVERSIDE_OLD ) &&
bClientOnly )
continue;
// don't trigger clientside events, if not explicit a clientside event
if ( ( listener->m_nListenerType == CLIENTSIDE ||
listener->m_nListenerType == CLIENTSIDE_OLD ) &&
!bClientOnly )
continue;
// don't broadcast events if server side only
if ( listener->m_nListenerType == CLIENTSTUB && (bServerOnly || bClientOnly) )
continue;
// TODO optimized the serialize event for clients, call only once and not per client
// fire event in this listener module
if ( listener->m_nListenerType == CLIENTSIDE_OLD ||
listener->m_nListenerType == SERVERSIDE_OLD )
{
tmZone( TELEMETRY_LEVEL1, TMZF_NONE, "FireGameEvent (i: %d, listenertype: %d (old))", i, listener->m_nListenerType );
// legacy support for old system
IGameEventListener *pCallback = static_cast<IGameEventListener*>(listener->m_pCallback);
CGameEvent *pEvent = static_cast<CGameEvent*>(event);
pCallback->FireGameEvent( pEvent->m_pDataKeys );
}
else
{
tmZone( TELEMETRY_LEVEL1, TMZF_NONE, "FireGameEvent (i: %d, listenertype: %d (new))", i, listener->m_nListenerType );
// new system
IGameEventListener2 *pCallback = static_cast<IGameEventListener2*>(listener->m_pCallback);
pCallback->FireGameEvent( event );
}
}
// free event resources
FreeEvent( event );
return true;
}
bool CGameEventManager::SerializeEvent( IGameEvent *event, bf_write* buf )
{
CGameEventDescriptor *descriptor = GetEventDescriptor( event );
Assert( descriptor );
buf->WriteUBitLong( descriptor->eventid, MAX_EVENT_BITS );
// now iterate trough all fields described in gameevents.res and put them in the buffer
KeyValues * key = descriptor->keys->GetFirstSubKey();
if ( net_showevents.GetInt() > 2 )
{
DevMsg("Serializing event '%s' (%i):\n", descriptor->name, descriptor->eventid );
}
while ( key )
{
const char * keyName = key->GetName();
int type = key->GetInt();
if ( net_showevents.GetInt() > 2 )
{
DevMsg(" - %s (%i)\n", keyName, type );
}
//Make sure every key is used in the event
// Assert( event->FindKey(keyName) && "GameEvent field not found in passed KeyValues" );
// see s_GameEnventTypeMap for index
switch ( type )
{
case TYPE_LOCAL : break; // don't network this guy
case TYPE_STRING: buf->WriteString( event->GetString( keyName, "") ); break;
case TYPE_FLOAT : buf->WriteFloat( event->GetFloat( keyName, 0.0f) ); break;
case TYPE_LONG : buf->WriteLong( event->GetInt( keyName, 0) ); break;
case TYPE_SHORT : buf->WriteShort( event->GetInt( keyName, 0) ); break;
case TYPE_BYTE : buf->WriteByte( event->GetInt( keyName, 0) ); break;
case TYPE_BOOL : buf->WriteOneBit( event->GetInt( keyName, 0) ); break;
default: DevMsg(1, "CGameEventManager: unkown type %i for key '%s'.\n", type, key->GetName() ); break;
}
key = key->GetNextKey();
}
return !buf->IsOverflowed();
}
IGameEvent *CGameEventManager::UnserializeEvent( bf_read *buf)
{
char databuf[MAX_EVENT_BYTES];
// read event id
int eventid = buf->ReadUBitLong( MAX_EVENT_BITS );
// get event description
CGameEventDescriptor *descriptor = GetEventDescriptor( eventid );
if ( descriptor == NULL )
{
DevMsg( "CGameEventManager::UnserializeEvent:: unknown event id %i.\n", eventid );
return NULL;
}
// create new event
IGameEvent *event = CreateEvent( descriptor );
if ( !event )
{
DevMsg( "CGameEventManager::UnserializeEvent:: failed to create event %s.\n", descriptor->name );
return NULL;
}
KeyValues * key = descriptor->keys->GetFirstSubKey();
while ( key )
{
const char * keyName = key->GetName();
int type = key->GetInt();
switch ( type )
{
case TYPE_LOCAL : break; // ignore
case TYPE_STRING : if ( buf->ReadString( databuf, sizeof(databuf) ) )
event->SetString( keyName, databuf );
break;
case TYPE_FLOAT : event->SetFloat( keyName, buf->ReadFloat() ); break;
case TYPE_LONG : event->SetInt( keyName, buf->ReadLong() ); break;
case TYPE_SHORT : event->SetInt( keyName, buf->ReadShort() ); break;
case TYPE_BYTE : event->SetInt( keyName, buf->ReadByte() ); break;
case TYPE_BOOL : event->SetInt( keyName, buf->ReadOneBit() ); break;
default: DevMsg(1, "CGameEventManager: unknown type %i for key '%s'.\n", type, key->GetName() ); break;
}
key = key->GetNextKey();
}
return event;
}
// returns true if this listener is listens to given event
bool CGameEventManager::FindListener( IGameEventListener2 *listener, const char *name )
{
CGameEventDescriptor *pDescriptor = GetEventDescriptor( name );
if ( !pDescriptor )
return false; // event is unknown
CGameEventCallback *pCallback = FindEventListener( listener );
if ( !pCallback )
return false; // listener is unknown
// see if listener is in the list for this event
return pDescriptor->listeners.IsValidIndex( pDescriptor->listeners.Find( pCallback ) );
}
CGameEventCallback* CGameEventManager::FindEventListener( void* pCallback )
{
for (int i=0; i < m_Listeners.Count(); i++ )
{
CGameEventCallback *listener = m_Listeners.Element(i);
if ( listener->m_pCallback == pCallback )
{
return listener;
}
}
return NULL;
}
void CGameEventManager::RemoveListener(IGameEventListener2 *listener)
{
CGameEventCallback *pCallback = FindEventListener( listener );
if ( pCallback == NULL )
{
return;
}
// remove reference from events
for (int i=0; i < m_GameEvents.Count(); i++ )
{
CGameEventDescriptor &et = m_GameEvents.Element( i );
et.listeners.FindAndRemove( pCallback );
}
// and from global list
m_Listeners.FindAndRemove( pCallback );
if ( pCallback->m_nListenerType == CLIENTSIDE )
{
m_bClientListenersChanged = true;
}
delete pCallback;
}
int CGameEventManager::LoadEventsFromFile( const char * filename )
{
if ( UTL_INVAL_SYMBOL == m_EventFiles.Find( filename ) )
{
CUtlSymbol id = m_EventFiles.AddString( filename );
m_EventFileNames.AddToTail( id );
}
KeyValues * key = new KeyValues(filename);
KeyValues::AutoDelete autodelete_key( key );
if ( !key->LoadFromFile( g_pFileSystem, filename, "GAME" ) )
return false;
int count = 0; // number new events
KeyValues * subkey = key->GetFirstSubKey();
while ( subkey )
{
if ( subkey->GetDataType() == KeyValues::TYPE_NONE )
{
RegisterEvent( subkey );
count++;
}
subkey = subkey->GetNextKey();
}
if ( net_showevents.GetBool() )
DevMsg( "Event System loaded %i events from file %s.\n", m_GameEvents.Count(), filename );
return m_GameEvents.Count();
}
void CGameEventManager::ReloadEventDefinitions()
{
for ( int i=0; i< m_EventFileNames.Count(); i++ )
{
const char *filename = m_EventFiles.String( m_EventFileNames[i] );
LoadEventsFromFile( filename );
}
// we are the server, build string table now
int number = m_GameEvents.Count();
for (int j = 0; j<number; j++)
{
m_GameEvents[j].eventid = j;
}
}
bool CGameEventManager::AddListener( IGameEventListener2 *listener, const char *event, bool bServerSide )
{
if ( !event )
return false;
// look for the event descriptor
CGameEventDescriptor *descriptor = GetEventDescriptor( event );
if ( !descriptor )
{
DevMsg( "CGameEventManager::AddListener: event '%s' unknown.\n", event );
return false; // that should not happen
}
return AddListener( listener, descriptor, bServerSide ? SERVERSIDE : CLIENTSIDE );
}
bool CGameEventManager::AddListener( void *listener, CGameEventDescriptor *descriptor, int nListenerType )
{
if ( !listener || !descriptor )
return false; // bahh
// check if we already know this listener
CGameEventCallback *pCallback = FindEventListener( listener );
if ( pCallback == NULL )
{
// add new callback
pCallback = new CGameEventCallback;
m_Listeners.AddToTail( pCallback );
pCallback->m_nListenerType = nListenerType;
pCallback->m_pCallback = listener;
}
else
{
// make sure that it hasn't changed:
Assert( pCallback->m_nListenerType == nListenerType );
Assert( pCallback->m_pCallback == listener );
}
// add to event listeners list if not already in there
if ( descriptor->listeners.Find( pCallback ) == descriptor->listeners.InvalidIndex() )
{
descriptor->listeners.AddToTail( pCallback );
if ( nListenerType == CLIENTSIDE || nListenerType == CLIENTSIDE_OLD )
m_bClientListenersChanged = true;
}
return true;
}
bool CGameEventManager::RegisterEvent( KeyValues * event)
{
if ( event == NULL )
return false;
if ( m_GameEvents.Count() == MAX_EVENT_NUMBER )
{
DevMsg( "CGameEventManager: couldn't register event '%s', limit reached (%i).\n",
event->GetName(), MAX_EVENT_NUMBER );
return false;
}
CGameEventDescriptor *descriptor = GetEventDescriptor( event->GetName() );
if ( !descriptor )
{
// event not known yet, create new one
int index = m_GameEvents.AddToTail();
descriptor = &m_GameEvents.Element(index);
AssertMsg2( V_strlen( event->GetName() ) <= MAX_EVENT_NAME_LENGTH, "Event named '%s' exceeds maximum name length %d", event->GetName(), MAX_EVENT_NAME_LENGTH );
Q_strncpy( descriptor->name, event->GetName(), MAX_EVENT_NAME_LENGTH );
}
else
{
// descriptor already know, but delete old definitions
descriptor->keys->deleteThis();
}
// create new descriptor keys
descriptor->keys = new KeyValues("descriptor");
KeyValues *subkey = event->GetFirstSubKey();
// interate through subkeys
while ( subkey )
{
const char *keyName = subkey->GetName();
// ok, check it's data type
const char * type = subkey->GetString();
if ( !Q_strcmp( "local", keyName) )
{
descriptor->local = Q_atoi( type ) != 0;
}
else if ( !Q_strcmp( "reliable", keyName) )
{
descriptor->reliable = Q_atoi( type ) != 0;
}
else
{
int i;
for (i = TYPE_LOCAL; i <= TYPE_BOOL; i++ )
{
if ( !Q_strcmp( type, s_GameEnventTypeMap[i]) )
{
// set data type
descriptor->keys->SetInt( keyName, i ); // set data type
break;
}
}
if ( i > TYPE_BOOL )
{
descriptor->keys->SetInt( keyName, 0 ); // unknown
DevMsg( "CGameEventManager:: unknown type '%s' for key '%s'.\n", type, subkey->GetName() );
}
}
subkey = subkey->GetNextKey();
}
return true;
}
CGameEventDescriptor *CGameEventManager::GetEventDescriptor(IGameEvent *event)
{
CGameEvent *gameevent = dynamic_cast<CGameEvent*>(event);
if ( !gameevent )
return NULL;
return gameevent->m_pDescriptor;
}
CGameEventDescriptor *CGameEventManager::GetEventDescriptor(int eventid) // returns event name or NULL
{
if ( eventid < 0 )
return NULL;
for ( int i = 0; i < m_GameEvents.Count(); i++ )
{
CGameEventDescriptor *descriptor = &m_GameEvents[i];
if ( descriptor->eventid == eventid )
return descriptor;
}
return NULL;
}
void CGameEventManager::FreeEvent( IGameEvent *event )
{
if ( !event )
return;
delete event;
}
CGameEventDescriptor *CGameEventManager::GetEventDescriptor(const char * name)
{
if ( !name || !name[0] )
return NULL;
for (int i=0; i < m_GameEvents.Count(); i++ )
{
CGameEventDescriptor *descriptor = &m_GameEvents[i];
if ( Q_strcmp( descriptor->name, name ) == 0 )
return descriptor;
}
return NULL;
}
bool CGameEventManager::AddListenerAll( void *listener, int nListenerType )
{
if ( !listener )
return false;
for (int i=0; i < m_GameEvents.Count(); i++ )
{
CGameEventDescriptor *descriptor = &m_GameEvents[i];
AddListener( listener, descriptor, nListenerType );
}
DevMsg("Warning! Game event listener registerd for all events. Use newer game event interface.\n");
return true;
}
void CGameEventManager::RemoveListenerOld( void *listener)
{
CGameEventCallback *pCallback = FindEventListener( listener );
if ( pCallback == NULL )
{
DevMsg("RemoveListenerOld: couldn't find listener\n");
return;
}
// remove reference from events
for (int i=0; i < m_GameEvents.Count(); i++ )
{
CGameEventDescriptor &et = m_GameEvents.Element( i );
et.listeners.FindAndRemove( pCallback );
}
// and from global list
m_Listeners.FindAndRemove( pCallback );
if ( pCallback->m_nListenerType == CLIENTSIDE_OLD )
{
m_bClientListenersChanged = true;
}
delete pCallback;
}
| 412 | 0.923457 | 1 | 0.923457 | game-dev | MEDIA | 0.923546 | game-dev | 0.898273 | 1 | 0.898273 |
suijingfeng/vkQuake3 | 31,433 | code/game/g_active.c | /*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
//
#include "g_local.h"
/*
===============
G_DamageFeedback
Called just before a snapshot is sent to the given player.
Totals up all damage and generates both the player_state_t
damage values to that client for pain blends and kicks, and
global pain sound events for all clients.
===============
*/
void P_DamageFeedback( gentity_t *player ) {
gclient_t *client;
float count;
vec3_t angles;
client = player->client;
if ( client->ps.pm_type == PM_DEAD ) {
return;
}
// total points of damage shot at the player this frame
count = client->damage_blood + client->damage_armor;
if ( count == 0 ) {
return; // didn't take any damage
}
if ( count > 255 ) {
count = 255;
}
// send the information to the client
// world damage (falling, slime, etc) uses a special code
// to make the blend blob centered instead of positional
if ( client->damage_fromWorld ) {
client->ps.damagePitch = 255;
client->ps.damageYaw = 255;
client->damage_fromWorld = qfalse;
} else {
vectoangles( client->damage_from, angles );
client->ps.damagePitch = angles[PITCH]/360.0 * 256;
client->ps.damageYaw = angles[YAW]/360.0 * 256;
}
// play an appropriate pain sound
if ( (level.time > player->pain_debounce_time) && !(player->flags & FL_GODMODE) ) {
player->pain_debounce_time = level.time + 700;
G_AddEvent( player, EV_PAIN, player->health );
client->ps.damageEvent++;
}
client->ps.damageCount = count;
//
// clear totals
//
client->damage_blood = 0;
client->damage_armor = 0;
client->damage_knockback = 0;
}
/*
=============
P_WorldEffects
Check for lava / slime contents and drowning
=============
*/
void P_WorldEffects( gentity_t *ent ) {
qboolean envirosuit;
int waterlevel;
if ( ent->client->noclip ) {
ent->client->airOutTime = level.time + 12000; // don't need air
return;
}
waterlevel = ent->waterlevel;
envirosuit = ent->client->ps.powerups[PW_BATTLESUIT] > level.time;
//
// check for drowning
//
if ( waterlevel == 3 ) {
// envirosuit give air
if ( envirosuit ) {
ent->client->airOutTime = level.time + 10000;
}
// if out of air, start drowning
if ( ent->client->airOutTime < level.time) {
// drown!
ent->client->airOutTime += 1000;
if ( ent->health > 0 ) {
// take more damage the longer underwater
ent->damage += 2;
if (ent->damage > 15)
ent->damage = 15;
// don't play a normal pain sound
ent->pain_debounce_time = level.time + 200;
G_Damage (ent, NULL, NULL, NULL, NULL,
ent->damage, DAMAGE_NO_ARMOR, MOD_WATER);
}
}
} else {
ent->client->airOutTime = level.time + 12000;
ent->damage = 2;
}
//
// check for sizzle damage (move to pmove?)
//
if (waterlevel &&
(ent->watertype&(CONTENTS_LAVA|CONTENTS_SLIME)) ) {
if (ent->health > 0
&& ent->pain_debounce_time <= level.time ) {
if ( envirosuit ) {
G_AddEvent( ent, EV_POWERUP_BATTLESUIT, 0 );
} else {
if (ent->watertype & CONTENTS_LAVA) {
G_Damage (ent, NULL, NULL, NULL, NULL,
30*waterlevel, 0, MOD_LAVA);
}
if (ent->watertype & CONTENTS_SLIME) {
G_Damage (ent, NULL, NULL, NULL, NULL,
10*waterlevel, 0, MOD_SLIME);
}
}
}
}
}
/*
===============
G_SetClientSound
===============
*/
void G_SetClientSound( gentity_t *ent ) {
#ifdef MISSIONPACK
if( ent->s.eFlags & EF_TICKING ) {
ent->client->ps.loopSound = G_SoundIndex( "sound/weapons/proxmine/wstbtick.wav");
}
else
#endif
if (ent->waterlevel && (ent->watertype&(CONTENTS_LAVA|CONTENTS_SLIME)) ) {
ent->client->ps.loopSound = level.snd_fry;
} else {
ent->client->ps.loopSound = 0;
}
}
//==============================================================
/*
==============
ClientImpacts
==============
*/
void ClientImpacts( gentity_t *ent, pmove_t *pm ) {
int i, j;
trace_t trace;
gentity_t *other;
memset( &trace, 0, sizeof( trace ) );
for (i=0 ; i<pm->numtouch ; i++) {
for (j=0 ; j<i ; j++) {
if (pm->touchents[j] == pm->touchents[i] ) {
break;
}
}
if (j != i) {
continue; // duplicated
}
other = &g_entities[ pm->touchents[i] ];
if ( ( ent->r.svFlags & SVF_BOT ) && ( ent->touch ) ) {
ent->touch( ent, other, &trace );
}
if ( !other->touch ) {
continue;
}
other->touch( other, ent, &trace );
}
}
/*
============
G_TouchTriggers
Find all trigger entities that ent's current position touches.
Spectators will only interact with teleporters.
============
*/
void G_TouchTriggers( gentity_t *ent ) {
int i, num;
int touch[MAX_GENTITIES];
gentity_t *hit;
trace_t trace;
vec3_t mins, maxs;
static vec3_t range = { 40, 40, 52 };
if ( !ent->client ) {
return;
}
// dead clients don't activate triggers!
if ( ent->client->ps.stats[STAT_HEALTH] <= 0 ) {
return;
}
VectorSubtract( ent->client->ps.origin, range, mins );
VectorAdd( ent->client->ps.origin, range, maxs );
num = trap_EntitiesInBox( mins, maxs, touch, MAX_GENTITIES );
// can't use ent->absmin, because that has a one unit pad
VectorAdd( ent->client->ps.origin, ent->r.mins, mins );
VectorAdd( ent->client->ps.origin, ent->r.maxs, maxs );
for ( i=0 ; i<num ; i++ ) {
hit = &g_entities[touch[i]];
if ( !hit->touch && !ent->touch ) {
continue;
}
if ( !( hit->r.contents & CONTENTS_TRIGGER ) ) {
continue;
}
// ignore most entities if a spectator
if ( ent->client->sess.sessionTeam == TEAM_SPECTATOR ) {
if ( hit->s.eType != ET_TELEPORT_TRIGGER &&
// this is ugly but adding a new ET_? type will
// most likely cause network incompatibilities
hit->touch != Touch_DoorTrigger) {
continue;
}
}
// use separate code for determining if an item is picked up
// so you don't have to actually contact its bounding box
if ( hit->s.eType == ET_ITEM ) {
if ( !BG_PlayerTouchesItem( &ent->client->ps, &hit->s, level.time ) ) {
continue;
}
} else {
if ( !trap_EntityContact( mins, maxs, hit ) ) {
continue;
}
}
memset( &trace, 0, sizeof(trace) );
if ( hit->touch ) {
hit->touch (hit, ent, &trace);
}
if ( ( ent->r.svFlags & SVF_BOT ) && ( ent->touch ) ) {
ent->touch( ent, hit, &trace );
}
}
// if we didn't touch a jump pad this pmove frame
if ( ent->client->ps.jumppad_frame != ent->client->ps.pmove_framecount ) {
ent->client->ps.jumppad_frame = 0;
ent->client->ps.jumppad_ent = 0;
}
}
/*
=================
SpectatorThink
=================
*/
void SpectatorThink( gentity_t *ent, usercmd_t *ucmd ) {
pmove_t pm;
gclient_t *client;
client = ent->client;
if ( client->sess.spectatorState != SPECTATOR_FOLLOW || !( client->ps.pm_flags & PMF_FOLLOW ) ) {
if ( client->sess.spectatorState == SPECTATOR_FREE ) {
if ( client->noclip ) {
client->ps.pm_type = PM_NOCLIP;
} else {
client->ps.pm_type = PM_SPECTATOR;
}
} else {
client->ps.pm_type = PM_FREEZE;
}
client->ps.speed = 400; // faster than normal
// set up for pmove
memset (&pm, 0, sizeof(pm));
pm.ps = &client->ps;
pm.cmd = *ucmd;
pm.tracemask = MASK_PLAYERSOLID & ~CONTENTS_BODY; // spectators can fly through bodies
pm.trace = trap_Trace;
pm.pointcontents = trap_PointContents;
// perform a pmove
Pmove (&pm);
// save results of pmove
VectorCopy( client->ps.origin, ent->s.origin );
G_TouchTriggers( ent );
trap_UnlinkEntity( ent );
}
client->oldbuttons = client->buttons;
client->buttons = ucmd->buttons;
// attack button cycles through spectators
if ( ( client->buttons & BUTTON_ATTACK ) && ! ( client->oldbuttons & BUTTON_ATTACK ) ) {
Cmd_FollowCycle_f( ent, 1 );
}
}
/*
=================
ClientInactivityTimer
Returns qfalse if the client is dropped
=================
*/
qboolean ClientInactivityTimer( gclient_t *client ) {
if ( ! g_inactivity.integer ) {
// give everyone some time, so if the operator sets g_inactivity during
// gameplay, everyone isn't kicked
client->inactivityTime = level.time + 60 * 1000;
client->inactivityWarning = qfalse;
} else if ( client->pers.cmd.forwardmove ||
client->pers.cmd.rightmove ||
client->pers.cmd.upmove ||
(client->pers.cmd.buttons & BUTTON_ATTACK) ) {
client->inactivityTime = level.time + g_inactivity.integer * 1000;
client->inactivityWarning = qfalse;
} else if ( !client->pers.localClient ) {
if ( level.time > client->inactivityTime ) {
trap_DropClient( client - level.clients, "Dropped due to inactivity" );
return qfalse;
}
if ( level.time > client->inactivityTime - 10000 && !client->inactivityWarning ) {
client->inactivityWarning = qtrue;
trap_SendServerCommand( client - level.clients, "cp \"Ten seconds until inactivity drop!\n\"" );
}
}
return qtrue;
}
/*
==================
ClientTimerActions
Actions that happen once a second
==================
*/
void ClientTimerActions( gentity_t *ent, int msec ) {
gclient_t *client;
#ifdef MISSIONPACK
int maxHealth;
#endif
client = ent->client;
client->timeResidual += msec;
while ( client->timeResidual >= 1000 ) {
client->timeResidual -= 1000;
// regenerate
#ifdef MISSIONPACK
if( bg_itemlist[client->ps.stats[STAT_PERSISTANT_POWERUP]].giTag == PW_GUARD ) {
maxHealth = client->ps.stats[STAT_MAX_HEALTH] / 2;
}
else if ( client->ps.powerups[PW_REGEN] ) {
maxHealth = client->ps.stats[STAT_MAX_HEALTH];
}
else {
maxHealth = 0;
}
if( maxHealth ) {
if ( ent->health < maxHealth ) {
ent->health += 15;
if ( ent->health > maxHealth * 1.1 ) {
ent->health = maxHealth * 1.1;
}
G_AddEvent( ent, EV_POWERUP_REGEN, 0 );
} else if ( ent->health < maxHealth * 2) {
ent->health += 5;
if ( ent->health > maxHealth * 2 ) {
ent->health = maxHealth * 2;
}
G_AddEvent( ent, EV_POWERUP_REGEN, 0 );
}
#else
if ( client->ps.powerups[PW_REGEN] ) {
if ( ent->health < client->ps.stats[STAT_MAX_HEALTH]) {
ent->health += 15;
if ( ent->health > client->ps.stats[STAT_MAX_HEALTH] * 1.1 ) {
ent->health = client->ps.stats[STAT_MAX_HEALTH] * 1.1;
}
G_AddEvent( ent, EV_POWERUP_REGEN, 0 );
} else if ( ent->health < client->ps.stats[STAT_MAX_HEALTH] * 2) {
ent->health += 5;
if ( ent->health > client->ps.stats[STAT_MAX_HEALTH] * 2 ) {
ent->health = client->ps.stats[STAT_MAX_HEALTH] * 2;
}
G_AddEvent( ent, EV_POWERUP_REGEN, 0 );
}
#endif
} else {
// count down health when over max
if ( ent->health > client->ps.stats[STAT_MAX_HEALTH] ) {
ent->health--;
}
}
// count down armor when over max
if ( client->ps.stats[STAT_ARMOR] > client->ps.stats[STAT_MAX_HEALTH] ) {
client->ps.stats[STAT_ARMOR]--;
}
}
#ifdef MISSIONPACK
if( bg_itemlist[client->ps.stats[STAT_PERSISTANT_POWERUP]].giTag == PW_AMMOREGEN ) {
int w, max, inc, t, i;
int weapList[]={WP_MACHINEGUN,WP_SHOTGUN,WP_GRENADE_LAUNCHER,WP_ROCKET_LAUNCHER,WP_LIGHTNING,WP_RAILGUN,WP_PLASMAGUN,WP_BFG,WP_NAILGUN,WP_PROX_LAUNCHER,WP_CHAINGUN};
int weapCount = ARRAY_LEN( weapList );
//
for (i = 0; i < weapCount; i++) {
w = weapList[i];
switch(w) {
case WP_MACHINEGUN: max = 50; inc = 4; t = 1000; break;
case WP_SHOTGUN: max = 10; inc = 1; t = 1500; break;
case WP_GRENADE_LAUNCHER: max = 10; inc = 1; t = 2000; break;
case WP_ROCKET_LAUNCHER: max = 10; inc = 1; t = 1750; break;
case WP_LIGHTNING: max = 50; inc = 5; t = 1500; break;
case WP_RAILGUN: max = 10; inc = 1; t = 1750; break;
case WP_PLASMAGUN: max = 50; inc = 5; t = 1500; break;
case WP_BFG: max = 10; inc = 1; t = 4000; break;
case WP_NAILGUN: max = 10; inc = 1; t = 1250; break;
case WP_PROX_LAUNCHER: max = 5; inc = 1; t = 2000; break;
case WP_CHAINGUN: max = 100; inc = 5; t = 1000; break;
default: max = 0; inc = 0; t = 1000; break;
}
client->ammoTimes[w] += msec;
if ( client->ps.ammo[w] >= max ) {
client->ammoTimes[w] = 0;
}
if ( client->ammoTimes[w] >= t ) {
while ( client->ammoTimes[w] >= t )
client->ammoTimes[w] -= t;
client->ps.ammo[w] += inc;
if ( client->ps.ammo[w] > max ) {
client->ps.ammo[w] = max;
}
}
}
}
#endif
}
/*
====================
ClientIntermissionThink
====================
*/
void ClientIntermissionThink( gclient_t *client ) {
client->ps.eFlags &= ~EF_TALK;
client->ps.eFlags &= ~EF_FIRING;
// the level will exit when everyone wants to or after timeouts
// swap and latch button actions
client->oldbuttons = client->buttons;
client->buttons = client->pers.cmd.buttons;
if ( client->buttons & ( BUTTON_ATTACK | BUTTON_USE_HOLDABLE ) & ( client->oldbuttons ^ client->buttons ) ) {
// this used to be an ^1 but once a player says ready, it should stick
client->readyToExit = 1;
}
}
/*
================
ClientEvents
Events will be passed on to the clients for presentation,
but any server game effects are handled here
================
*/
void ClientEvents( gentity_t *ent, int oldEventSequence ) {
int i, j;
int event;
gclient_t *client;
int damage;
vec3_t origin, angles;
// qboolean fired;
gitem_t *item;
gentity_t *drop;
client = ent->client;
if ( oldEventSequence < client->ps.eventSequence - MAX_PS_EVENTS ) {
oldEventSequence = client->ps.eventSequence - MAX_PS_EVENTS;
}
for ( i = oldEventSequence ; i < client->ps.eventSequence ; i++ ) {
event = client->ps.events[ i & (MAX_PS_EVENTS-1) ];
switch ( event ) {
case EV_FALL_MEDIUM:
case EV_FALL_FAR:
if ( ent->s.eType != ET_PLAYER ) {
break; // not in the player model
}
if ( g_dmflags.integer & DF_NO_FALLING ) {
break;
}
if ( event == EV_FALL_FAR ) {
damage = 10;
} else {
damage = 5;
}
ent->pain_debounce_time = level.time + 200; // no normal pain sound
G_Damage (ent, NULL, NULL, NULL, NULL, damage, 0, MOD_FALLING);
break;
case EV_FIRE_WEAPON:
FireWeapon( ent );
break;
case EV_USE_ITEM1: // teleporter
// drop flags in CTF
item = NULL;
j = 0;
if ( ent->client->ps.powerups[ PW_REDFLAG ] ) {
item = BG_FindItemForPowerup( PW_REDFLAG );
j = PW_REDFLAG;
} else if ( ent->client->ps.powerups[ PW_BLUEFLAG ] ) {
item = BG_FindItemForPowerup( PW_BLUEFLAG );
j = PW_BLUEFLAG;
} else if ( ent->client->ps.powerups[ PW_NEUTRALFLAG ] ) {
item = BG_FindItemForPowerup( PW_NEUTRALFLAG );
j = PW_NEUTRALFLAG;
}
if ( item ) {
drop = Drop_Item( ent, item, 0 );
// decide how many seconds it has left
drop->count = ( ent->client->ps.powerups[ j ] - level.time ) / 1000;
if ( drop->count < 1 ) {
drop->count = 1;
}
ent->client->ps.powerups[ j ] = 0;
}
#ifdef MISSIONPACK
if ( g_gametype.integer == GT_HARVESTER ) {
if ( ent->client->ps.generic1 > 0 ) {
if ( ent->client->sess.sessionTeam == TEAM_RED ) {
item = BG_FindItem( "Blue Cube" );
} else {
item = BG_FindItem( "Red Cube" );
}
if ( item ) {
for ( j = 0; j < ent->client->ps.generic1; j++ ) {
drop = Drop_Item( ent, item, 0 );
if ( ent->client->sess.sessionTeam == TEAM_RED ) {
drop->spawnflags = TEAM_BLUE;
} else {
drop->spawnflags = TEAM_RED;
}
}
}
ent->client->ps.generic1 = 0;
}
}
#endif
SelectSpawnPoint( ent->client->ps.origin, origin, angles, qfalse );
TeleportPlayer( ent, origin, angles );
break;
case EV_USE_ITEM2: // medkit
ent->health = ent->client->ps.stats[STAT_MAX_HEALTH] + 25;
break;
#ifdef MISSIONPACK
case EV_USE_ITEM3: // kamikaze
// make sure the invulnerability is off
ent->client->invulnerabilityTime = 0;
// start the kamikze
G_StartKamikaze( ent );
break;
case EV_USE_ITEM4: // portal
if( ent->client->portalID ) {
DropPortalSource( ent );
}
else {
DropPortalDestination( ent );
}
break;
case EV_USE_ITEM5: // invulnerability
ent->client->invulnerabilityTime = level.time + 10000;
break;
#endif
default:
break;
}
}
}
#ifdef MISSIONPACK
/*
==============
StuckInOtherClient
==============
*/
static int StuckInOtherClient(gentity_t *ent) {
int i;
gentity_t *ent2;
ent2 = &g_entities[0];
for ( i = 0; i < MAX_CLIENTS; i++, ent2++ ) {
if ( ent2 == ent ) {
continue;
}
if ( !ent2->inuse ) {
continue;
}
if ( !ent2->client ) {
continue;
}
if ( ent2->health <= 0 ) {
continue;
}
//
if (ent2->r.absmin[0] > ent->r.absmax[0])
continue;
if (ent2->r.absmin[1] > ent->r.absmax[1])
continue;
if (ent2->r.absmin[2] > ent->r.absmax[2])
continue;
if (ent2->r.absmax[0] < ent->r.absmin[0])
continue;
if (ent2->r.absmax[1] < ent->r.absmin[1])
continue;
if (ent2->r.absmax[2] < ent->r.absmin[2])
continue;
return qtrue;
}
return qfalse;
}
#endif
void BotTestSolid(vec3_t origin);
/*
==============
SendPendingPredictableEvents
==============
*/
void SendPendingPredictableEvents( playerState_t *ps ) {
gentity_t *t;
int event, seq;
int extEvent, number;
// if there are still events pending
if ( ps->entityEventSequence < ps->eventSequence ) {
// create a temporary entity for this event which is sent to everyone
// except the client who generated the event
seq = ps->entityEventSequence & (MAX_PS_EVENTS-1);
event = ps->events[ seq ] | ( ( ps->entityEventSequence & 3 ) << 8 );
// set external event to zero before calling BG_PlayerStateToEntityState
extEvent = ps->externalEvent;
ps->externalEvent = 0;
// create temporary entity for event
t = G_TempEntity( ps->origin, event );
number = t->s.number;
BG_PlayerStateToEntityState( ps, &t->s, qtrue );
t->s.number = number;
t->s.eType = ET_EVENTS + event;
t->s.eFlags |= EF_PLAYER_EVENT;
t->s.otherEntityNum = ps->clientNum;
// send to everyone except the client who generated the event
t->r.svFlags |= SVF_NOTSINGLECLIENT;
t->r.singleClient = ps->clientNum;
// set back external event
ps->externalEvent = extEvent;
}
}
/*
==============
ClientThink
This will be called once for each client frame, which will
usually be a couple times for each server frame on fast clients.
If "g_synchronousClients 1" is set, this will be called exactly
once for each server frame, which makes for smooth demo recording.
==============
*/
void ClientThink_real( gentity_t *ent ) {
gclient_t *client;
pmove_t pm;
int oldEventSequence;
int msec;
usercmd_t *ucmd;
client = ent->client;
// don't think if the client is not yet connected (and thus not yet spawned in)
if (client->pers.connected != CON_CONNECTED) {
return;
}
// mark the time, so the connection sprite can be removed
ucmd = &ent->client->pers.cmd;
// sanity check the command time to prevent speedup cheating
if ( ucmd->serverTime > level.time + 200 ) {
ucmd->serverTime = level.time + 200;
// G_Printf("serverTime <<<<<\n" );
}
if ( ucmd->serverTime < level.time - 1000 ) {
ucmd->serverTime = level.time - 1000;
// G_Printf("serverTime >>>>>\n" );
}
msec = ucmd->serverTime - client->ps.commandTime;
// following others may result in bad times, but we still want
// to check for follow toggles
if ( msec < 1 && client->sess.spectatorState != SPECTATOR_FOLLOW ) {
return;
}
if ( msec > 200 ) {
msec = 200;
}
if ( pmove_msec.integer < 8 ) {
trap_Cvar_Set("pmove_msec", "8");
trap_Cvar_Update(&pmove_msec);
}
else if (pmove_msec.integer > 33) {
trap_Cvar_Set("pmove_msec", "33");
trap_Cvar_Update(&pmove_msec);
}
if ( pmove_fixed.integer || client->pers.pmoveFixed ) {
ucmd->serverTime = ((ucmd->serverTime + pmove_msec.integer-1) / pmove_msec.integer) * pmove_msec.integer;
//if (ucmd->serverTime - client->ps.commandTime <= 0)
// return;
}
//
// check for exiting intermission
//
if ( level.intermissiontime ) {
ClientIntermissionThink( client );
return;
}
// spectators don't do much
if ( client->sess.sessionTeam == TEAM_SPECTATOR ) {
if ( client->sess.spectatorState == SPECTATOR_SCOREBOARD ) {
return;
}
SpectatorThink( ent, ucmd );
return;
}
// check for inactivity timer, but never drop the local client of a non-dedicated server
if ( !ClientInactivityTimer( client ) ) {
return;
}
// clear the rewards if time
if ( level.time > client->rewardTime ) {
client->ps.eFlags &= ~(EF_AWARD_IMPRESSIVE | EF_AWARD_EXCELLENT | EF_AWARD_GAUNTLET | EF_AWARD_ASSIST | EF_AWARD_DEFEND | EF_AWARD_CAP );
}
if ( client->noclip ) {
client->ps.pm_type = PM_NOCLIP;
} else if ( client->ps.stats[STAT_HEALTH] <= 0 ) {
client->ps.pm_type = PM_DEAD;
} else {
client->ps.pm_type = PM_NORMAL;
}
client->ps.gravity = g_gravity.value;
// set speed
client->ps.speed = g_speed.value;
#ifdef MISSIONPACK
if( bg_itemlist[client->ps.stats[STAT_PERSISTANT_POWERUP]].giTag == PW_SCOUT ) {
client->ps.speed *= 1.5;
}
else
#endif
if ( client->ps.powerups[PW_HASTE] ) {
client->ps.speed *= 1.3;
}
// Let go of the hook if we aren't firing
if ( client->ps.weapon == WP_GRAPPLING_HOOK &&
client->hook && !( ucmd->buttons & BUTTON_ATTACK ) ) {
Weapon_HookFree(client->hook);
}
// set up for pmove
oldEventSequence = client->ps.eventSequence;
memset (&pm, 0, sizeof(pm));
// check for the hit-scan gauntlet, don't let the action
// go through as an attack unless it actually hits something
if ( client->ps.weapon == WP_GAUNTLET && !( ucmd->buttons & BUTTON_TALK ) &&
( ucmd->buttons & BUTTON_ATTACK ) && client->ps.weaponTime <= 0 ) {
pm.gauntletHit = CheckGauntletAttack( ent );
}
if ( ent->flags & FL_FORCE_GESTURE ) {
ent->flags &= ~FL_FORCE_GESTURE;
ent->client->pers.cmd.buttons |= BUTTON_GESTURE;
}
#ifdef MISSIONPACK
// check for invulnerability expansion before doing the Pmove
if (client->ps.powerups[PW_INVULNERABILITY] ) {
if ( !(client->ps.pm_flags & PMF_INVULEXPAND) ) {
vec3_t mins = { -42, -42, -42 };
vec3_t maxs = { 42, 42, 42 };
vec3_t oldmins, oldmaxs;
VectorCopy (ent->r.mins, oldmins);
VectorCopy (ent->r.maxs, oldmaxs);
// expand
VectorCopy (mins, ent->r.mins);
VectorCopy (maxs, ent->r.maxs);
trap_LinkEntity(ent);
// check if this would get anyone stuck in this player
if ( !StuckInOtherClient(ent) ) {
// set flag so the expanded size will be set in PM_CheckDuck
client->ps.pm_flags |= PMF_INVULEXPAND;
}
// set back
VectorCopy (oldmins, ent->r.mins);
VectorCopy (oldmaxs, ent->r.maxs);
trap_LinkEntity(ent);
}
}
#endif
pm.ps = &client->ps;
pm.cmd = *ucmd;
if ( pm.ps->pm_type == PM_DEAD ) {
pm.tracemask = MASK_PLAYERSOLID & ~CONTENTS_BODY;
}
else if ( ent->r.svFlags & SVF_BOT ) {
pm.tracemask = MASK_PLAYERSOLID | CONTENTS_BOTCLIP;
}
else {
pm.tracemask = MASK_PLAYERSOLID;
}
pm.trace = trap_Trace;
pm.pointcontents = trap_PointContents;
pm.debugLevel = g_debugMove.integer;
pm.noFootsteps = ( g_dmflags.integer & DF_NO_FOOTSTEPS ) > 0;
pm.pmove_fixed = pmove_fixed.integer | client->pers.pmoveFixed;
pm.pmove_msec = pmove_msec.integer;
VectorCopy( client->ps.origin, client->oldOrigin );
#ifdef MISSIONPACK
if (level.intermissionQueued != 0 && g_singlePlayer.integer) {
if ( level.time - level.intermissionQueued >= 1000 ) {
pm.cmd.buttons = 0;
pm.cmd.forwardmove = 0;
pm.cmd.rightmove = 0;
pm.cmd.upmove = 0;
if ( level.time - level.intermissionQueued >= 2000 && level.time - level.intermissionQueued <= 2500 ) {
trap_SendConsoleCommand( EXEC_APPEND, "centerview\n");
}
ent->client->ps.pm_type = PM_SPINTERMISSION;
}
}
Pmove (&pm);
#else
Pmove (&pm);
#endif
// save results of pmove
if ( ent->client->ps.eventSequence != oldEventSequence ) {
ent->eventTime = level.time;
}
if (g_smoothClients.integer) {
BG_PlayerStateToEntityStateExtraPolate( &ent->client->ps, &ent->s, ent->client->ps.commandTime, qtrue );
}
else {
BG_PlayerStateToEntityState( &ent->client->ps, &ent->s, qtrue );
}
SendPendingPredictableEvents( &ent->client->ps );
if ( !( ent->client->ps.eFlags & EF_FIRING ) ) {
client->fireHeld = qfalse; // for grapple
}
// use the snapped origin for linking so it matches client predicted versions
VectorCopy( ent->s.pos.trBase, ent->r.currentOrigin );
VectorCopy (pm.mins, ent->r.mins);
VectorCopy (pm.maxs, ent->r.maxs);
ent->waterlevel = pm.waterlevel;
ent->watertype = pm.watertype;
// execute client events
ClientEvents( ent, oldEventSequence );
// link entity now, after any personal teleporters have been used
trap_LinkEntity (ent);
if ( !ent->client->noclip ) {
G_TouchTriggers( ent );
}
// NOTE: now copy the exact origin over otherwise clients can be snapped into solid
VectorCopy( ent->client->ps.origin, ent->r.currentOrigin );
//test for solid areas in the AAS file
BotTestAAS(ent->r.currentOrigin);
// touch other objects
ClientImpacts( ent, &pm );
// save results of triggers and client events
if (ent->client->ps.eventSequence != oldEventSequence) {
ent->eventTime = level.time;
}
// swap and latch button actions
client->oldbuttons = client->buttons;
client->buttons = ucmd->buttons;
client->latched_buttons |= client->buttons & ~client->oldbuttons;
// check for respawning
if ( client->ps.stats[STAT_HEALTH] <= 0 ) {
// wait for the attack button to be pressed
if ( level.time > client->respawnTime ) {
// forcerespawn is to prevent users from waiting out powerups
if ( g_forcerespawn.integer > 0 &&
( level.time - client->respawnTime ) > g_forcerespawn.integer * 1000 ) {
ClientRespawn( ent );
return;
}
// pressing attack or use is the normal respawn method
if ( ucmd->buttons & ( BUTTON_ATTACK | BUTTON_USE_HOLDABLE ) ) {
ClientRespawn( ent );
}
}
return;
}
// perform once-a-second actions
ClientTimerActions( ent, msec );
}
/*
==================
ClientThink
A new command has arrived from the client
==================
*/
void ClientThink( int clientNum ) {
gentity_t *ent;
ent = g_entities + clientNum;
trap_GetUsercmd( clientNum, &ent->client->pers.cmd );
// mark the time we got info, so we can display the
// phone jack if they don't get any for a while
ent->client->lastCmdTime = level.time;
if ( !(ent->r.svFlags & SVF_BOT) && !g_synchronousClients.integer ) {
ClientThink_real( ent );
}
}
void G_RunClient( gentity_t *ent ) {
if ( !(ent->r.svFlags & SVF_BOT) && !g_synchronousClients.integer ) {
return;
}
ent->client->pers.cmd.serverTime = level.time;
ClientThink_real( ent );
}
/*
==================
SpectatorClientEndFrame
==================
*/
void SpectatorClientEndFrame( gentity_t *ent ) {
gclient_t *cl;
// if we are doing a chase cam or a remote view, grab the latest info
if ( ent->client->sess.spectatorState == SPECTATOR_FOLLOW ) {
int clientNum, flags;
clientNum = ent->client->sess.spectatorClient;
// team follow1 and team follow2 go to whatever clients are playing
if ( clientNum == -1 ) {
clientNum = level.follow1;
} else if ( clientNum == -2 ) {
clientNum = level.follow2;
}
if ( clientNum >= 0 ) {
cl = &level.clients[ clientNum ];
if ( cl->pers.connected == CON_CONNECTED && cl->sess.sessionTeam != TEAM_SPECTATOR ) {
flags = (cl->ps.eFlags & ~(EF_VOTED | EF_TEAMVOTED)) | (ent->client->ps.eFlags & (EF_VOTED | EF_TEAMVOTED));
ent->client->ps = cl->ps;
ent->client->ps.pm_flags |= PMF_FOLLOW;
ent->client->ps.eFlags = flags;
return;
}
}
if ( ent->client->ps.pm_flags & PMF_FOLLOW ) {
// drop them to free spectators unless they are dedicated camera followers
if ( ent->client->sess.spectatorClient >= 0 ) {
ent->client->sess.spectatorState = SPECTATOR_FREE;
}
ClientBegin( ent->client - level.clients );
}
}
if ( ent->client->sess.spectatorState == SPECTATOR_SCOREBOARD ) {
ent->client->ps.pm_flags |= PMF_SCOREBOARD;
} else {
ent->client->ps.pm_flags &= ~PMF_SCOREBOARD;
}
}
/*
==============
ClientEndFrame
Called at the end of each server frame for each connected client
A fast client will have multiple ClientThink for each ClientEdFrame,
while a slow client may have multiple ClientEndFrame between ClientThink.
==============
*/
void ClientEndFrame( gentity_t *ent ) {
int i;
if ( ent->client->sess.sessionTeam == TEAM_SPECTATOR ) {
SpectatorClientEndFrame( ent );
return;
}
// turn off any expired powerups
for ( i = 0 ; i < MAX_POWERUPS ; i++ ) {
if ( ent->client->ps.powerups[ i ] < level.time ) {
ent->client->ps.powerups[ i ] = 0;
}
}
#ifdef MISSIONPACK
// set powerup for player animation
if( bg_itemlist[ent->client->ps.stats[STAT_PERSISTANT_POWERUP]].giTag == PW_GUARD ) {
ent->client->ps.powerups[PW_GUARD] = level.time;
}
if( bg_itemlist[ent->client->ps.stats[STAT_PERSISTANT_POWERUP]].giTag == PW_SCOUT ) {
ent->client->ps.powerups[PW_SCOUT] = level.time;
}
if( bg_itemlist[ent->client->ps.stats[STAT_PERSISTANT_POWERUP]].giTag == PW_DOUBLER ) {
ent->client->ps.powerups[PW_DOUBLER] = level.time;
}
if( bg_itemlist[ent->client->ps.stats[STAT_PERSISTANT_POWERUP]].giTag == PW_AMMOREGEN ) {
ent->client->ps.powerups[PW_AMMOREGEN] = level.time;
}
if ( ent->client->invulnerabilityTime > level.time ) {
ent->client->ps.powerups[PW_INVULNERABILITY] = level.time;
}
#endif
// save network bandwidth
#if 0
if ( !g_synchronousClients->integer && ent->client->ps.pm_type == PM_NORMAL ) {
// FIXME: this must change eventually for non-sync demo recording
VectorClear( ent->client->ps.viewangles );
}
#endif
//
// If the end of unit layout is displayed, don't give
// the player any normal movement attributes
//
if ( level.intermissiontime ) {
return;
}
// burn from lava, etc
P_WorldEffects (ent);
// apply all the damage taken this frame
P_DamageFeedback (ent);
// add the EF_CONNECTION flag if we haven't gotten commands recently
if ( level.time - ent->client->lastCmdTime > 1000 ) {
ent->client->ps.eFlags |= EF_CONNECTION;
} else {
ent->client->ps.eFlags &= ~EF_CONNECTION;
}
ent->client->ps.stats[STAT_HEALTH] = ent->health; // FIXME: get rid of ent->health...
G_SetClientSound (ent);
// set the latest infor
if (g_smoothClients.integer) {
BG_PlayerStateToEntityStateExtraPolate( &ent->client->ps, &ent->s, ent->client->ps.commandTime, qtrue );
}
else {
BG_PlayerStateToEntityState( &ent->client->ps, &ent->s, qtrue );
}
SendPendingPredictableEvents( &ent->client->ps );
// set the bit for the reachability area the client is currently in
// i = trap_AAS_PointReachabilityAreaIndex( ent->client->ps.origin );
// ent->client->areabits[i >> 3] |= 1 << (i & 7);
}
| 412 | 0.992287 | 1 | 0.992287 | game-dev | MEDIA | 0.741558 | game-dev | 0.982059 | 1 | 0.982059 |
mojontwins/MK1 | 36,307 | examples/old/Julifrustris/dev - orig/engine.h | // Motor.h
// Funciones:
unsigned char collide (unsigned char x1, unsigned char y1, unsigned char x2, unsigned char y2) {
// Colisin segura y guarra.
unsigned char l1x, l1y, l2x, l2y;
l1x = (x1 > 13) ? x1 - 13 : 0;
l2x = x1 + 13;
l1y = (y1 > 12) ? y1 - 12 : 0;
l2y = y1 + 12;
return (x2 >= l1x && x2 <= l2x && y2 >= l1y && y2 <= l2y);
}
void srand (unsigned int new_seed) {
seed [0] = new_seed;
}
unsigned char rand () {
unsigned char res;
#asm
.rand16
ld hl, _seed
ld a, (hl)
ld e, a
inc hl
ld a, (hl)
ld d, a
;; Ahora DE = [SEED]
ld a, d
ld h, e
ld l, 253
or a
sbc hl, de
sbc a, 0
sbc hl, de
ld d, 0
sbc a, d
ld e, a
sbc hl, de
jr nc, nextrand
inc hl
.nextrand
ld d, h
ld e, l
ld hl, _seed
ld a, e
ld (hl), a
inc hl
ld a, d
ld (hl), a
;; Ahora [SEED] = HL
ld hl, _asm_int
ld a, e
ld (hl), a
inc hl
ld a, d
ld (hl), a
;; Ahora [ASM_INT] = HL
#endasm
res = asm_int [0];
return res;
}
unsigned int abs (int n) {
if (n < 0)
return (unsigned int) (-n);
else
return (unsigned int) n;
}
void step () {
#asm
ld a, 16
out (254), a
nop
nop
nop
nop
nop
nop
nop
nop
nop
xor 16
out (254), a
#endasm
}
void cortina () {
#asm
;; Antes que nada vamos a limpiar el PAPER de toda la pantalla
;; para que no queden artefactos feos
ld de, 22528 ; Apuntamos con DE a la zona de atributos
ld b, 3 ; Procesamos 3 tercios
.clearb1
push bc
ld b, 255 ; Procesamos los 256 atributos de cada tercio
.clearb2
ld a, (de) ; Nos traemos un atributo
and 199 ; Le hacemos la mscara 11000111 y dejamos PAPER a 0
ld (de), a ; Y lo volvemos a poner
inc de ; Siguiente atributo
djnz clearb2
pop bc
djnz clearb1
;; Y ahora el cdigo original que escrib para UWOL:
ld a, 8
.repitatodo
ld c, a ; Salvamos el contador de "repitatodo" en 'c'
ld hl, 16384
ld a, 12
.bucle
ld b, a ; Salvamos el contador de "bucle" en 'b'
ld a, 255
.bucle1
sla (hl)
inc hl
dec a
jr nz, bucle1
ld a, 255
.bucle2
srl (hl)
inc hl
dec a
jr nz, bucle2
ld a, b ; Restituimos el contador de "bucle" a 'a'
dec a
jr nz, bucle
ld a, c ; Restituimos el contador de "repitatodo" a 'a'
dec a
jr nz, repitatodo
#endasm
// Estoy llorando
}
// Game
char espera_activa (int espera) {
// jL
// Esta funcin espera un rato o hasta que se pulse una tecla.
// Si se pulsa una tecla, devuelve 0
// Esta funcin slo funciona en Spectrum.
// en CPC no hay una interrupcin cada 20ms, asn que esto no
// sirve "pa n".
char res = 1;
int i;
int j;
for (i = 0; i < espera && res; i ++) {
for (j = 0; j < 250; j ++) {
res = 1;
}
if (sp_GetKey ())
res = 0;
}
return res;
}
void game_ending () {
unsigned char x;
sp_UpdateNow();
unpack ((unsigned int) (s_ending));
for (x = 0; x < 4; x ++) {
peta_el_beeper (7);
peta_el_beeper (2);
}
peta_el_beeper (9);
espera_activa (500);
}
void game_over () {
unsigned char x, y;
for (y = 11; y < 14; y ++)
for (x = 10; x < 22; x ++)
sp_PrintAtInv (y, x, 95, 0);
sp_PrintAtInv (12, 11, 95, 39);
sp_PrintAtInv (12, 12, 95, 33);
sp_PrintAtInv (12, 13, 95, 45);
sp_PrintAtInv (12, 14, 95, 37);
sp_PrintAtInv (12, 16, 95, 47);
sp_PrintAtInv (12, 17, 95, 54);
sp_PrintAtInv (12, 18, 95, 37);
sp_PrintAtInv (12, 19, 95, 50);
sp_PrintAtInv (12, 20, 95, 1);
sp_UpdateNow ();
for (x = 0; x < 4; x ++) {
peta_el_beeper (7);
peta_el_beeper (2);
}
peta_el_beeper (9);
espera_activa (500);
}
#ifndef DEACTIVATE_KEYS
void clear_cerrojo (unsigned char np, unsigned char x, unsigned char y) {
unsigned char i;
// search & toggle
for (i = 0; i < MAX_CERROJOS; i ++)
if (cerrojos [i].x == x && cerrojos [i].y == y && cerrojos [i].np == np)
cerrojos [i].st = 0;
}
void init_cerrojos () {
unsigned char i;
// Activa todos los cerrojos
for (i = 0; i < MAX_CERROJOS; i ++)
cerrojos [i].st = 1;
}
#endif
#ifdef PLAYER_CAN_FIRE
void init_bullets () {
unsigned char i;
// Inicializa las balas
for (i = 0; i < MAX_BULLETS; i ++)
bullets [i].estado = 0;
}
#endif
#if defined(PLAYER_KILLS_ENEMIES) || defined (PLAYER_CAN_FIRE)
void init_malotes () {
unsigned char i;
for (i = 0; i < MAP_W * MAP_H * 3; i ++) {
malotes [i].t = malotes [i].t & 15;
#ifdef PLAYER_CAN_FIRE
malotes [i].life = ENEMIES_LIFE_GAUGE;
#ifdef RANDOM_RESPAWN
if (malotes [i].t == 5)
malotes [i].t |= 16;
#endif
#endif
}
}
#endif
#ifdef PLAYER_CAN_FIRE
void fire_bullet () {
unsigned char i;
// Buscamos una bala libre
for (i = 0; i < MAX_BULLETS; i ++) {
if (bullets [i].estado == 0) {
bullets [i].estado = 1;
if (player.facing == 0) {
bullets [i].x = (player.x >> 6) - 4;
bullets [i].mx = -PLAYER_BULLET_SPEED;
} else {
bullets [i].x = (player.x >> 6) + 12;
bullets [i].mx = PLAYER_BULLET_SPEED;
}
bullets [i].y = (player.y >> 6) + PLAYER_BULLET_Y_OFFSET;
peta_el_beeper (6);
break;
}
}
}
#endif
#ifdef RANDOM_RESPAWN
char player_hidden () {
unsigned char x, y, xx, yy;
x = player.x >> 6;
y = player.y >> 6;
xx = x >> 4;
yy = y >> 4;
if ( (y & 15) == 0 && player.vx == 0 )
if (attr (xx, yy) == 2 || (attr (1 + xx, yy) == 2 && (x & 15) != 0) )
return 1;
return 0;
}
#endif
#ifdef PLAYER_PUSH_BOXES
void move_tile (unsigned char x0, unsigned char y0, unsigned char x1, unsigned char y1) {
// Mover
map_attr [15 * y1 + x1] = 8;
map_buff [15 * y1 + x1] = 14;
map_attr [15 * y0 + x0] = 0;
map_buff [15 * y0 + x0] = 0;
// Pintar
draw_coloured_tile (VIEWPORT_X + x0 + x0, VIEWPORT_Y + y0 + y0, 0);
draw_coloured_tile (VIEWPORT_X + x1 + x1, VIEWPORT_Y + y1 + y1, 14);
// Sonido
peta_el_beeper (2);
}
#endif
unsigned char move (unsigned char n_pant) {
unsigned char xx, yy;
unsigned char x, y;
unsigned char i, allpurp;
int cx, cy;
cx = player.x;
cy = player.y;
i = (joyfunc) (&keys); // Leemos del teclado
/* Por partes. Primero el movimiento vertical. La ecuacin de movimien-
to viene a ser, en cada ciclo:
1.- vy = vy + g
2.- y = y + vy
O sea la velocidad afectada por la gravedad.
Para no colarnos con los nmeros, ponemos limitadores:
*/
#ifndef PLAYER_MOGGY_STYLE
// Si el tipo de movimiento no es MOGGY_STYLE, entonces nos afecta la gravedad.
if (player.vy < PLAYER_MAX_VY_CAYENDO)
player.vy += player.g;
else
player.vy = PLAYER_MAX_VY_CAYENDO;
if (player.gotten) player.vy = 0;
#else
// Si lo es, entonces el movimiento vertical se comporta exactamente igual que
// el horizontal.
if ( ! ((i & sp_UP) == 0 || (i & sp_DOWN) == 0))
if (player.vy > 0) {
player.vy -= player.rx;
if (player.vy < 0)
player.vy = 0;
} else if (player.vy < 0) {
player.vy += player.rx;
if (player.vy > 0)
player.vy = 0;
}
if ((i & sp_UP) == 0)
if (player.vy > -PLAYER_MAX_VX) {
player.vy -= player.ax;
}
if ((i & sp_DOWN) == 0)
if (player.vy < PLAYER_MAX_VX) {
player.vy += player.ax;
}
#endif
player.y += player.vy;
// Safe
if (player.y < 0)
player.y = 0;
if (player.y > 9216)
player.y = 9216;
/* El problema es que no es tan fcil... Hay que ver si no nos chocamos.
Si esto pasa, hay que "recular" hasta el borde del obstculo.
Por eso miramos el signo de vy, para que los clculos sean ms sencillos.
De paso vamos a precalcular un par de cosas para que esto vaya ms rpido.
*/
x = player.x >> 6; // dividimos entre 64 para pixels, y luego entre 16 para tiles.
y = player.y >> 6;
xx = x >> 4;
yy = y >> 4;
// Ya
if (player.vy < 0) { // estamos ascendiendo
//if (player.y >= 1024)
if (attr (xx, yy) > 7 || ((x & 15) != 0 && attr (xx + 1, yy) > 7)) {
// paramos y ajustamos:
player.vy = 0;
player.y = (yy + 1) << 10;
}
} else if (player.vy > 0 && (y & 15) < 8) { // estamos descendiendo
if (player.y < 9216)
if (attr (xx, yy + 1) > 3 || ((x & 15) != 0 && attr (xx + 1, yy + 1) > 3))
{
// paramos y ajustamos:
player.vy = 0;
player.y = yy << 10;
}
}
/* Salto: El salto se reduce a dar un valor negativo a vy. Esta es la forma ms
sencilla. Sin embargo, para ms control, usamos el tipo de salto "mario bros".
Para ello, en cada pulsacin dejaremos decrementar vy hasta un mnimo, y de-
tectando que no se vuelva a pulsar cuando estemos en el aire. Juego de banderas ;)
*/
#ifdef PLAYER_HAS_JUMP
#ifdef PLAYER_CAN_FIRE
if (((i & sp_UP) == 0) && ((player.vy == 0 && player.saltando == 0 && (attr (xx, yy + 1) > 3 || ((x & 15) != 0 && attr (xx + 1, yy + 1) > 3))) || player.gotten)) {
player.saltando = 1;
player.cont_salto = 0;
peta_el_beeper (3);
}
if ( ((i & sp_UP) == 0) && player.saltando ) {
player.vy -= (player.salto + PLAYER_INCR_SALTO - (player.cont_salto>>1));
if (player.vy < -PLAYER_MAX_VY_SALTANDO) player.vy = -PLAYER_MAX_VY_SALTANDO;
player.cont_salto ++;
if (player.cont_salto == 8)
player.saltando = 0;
}
if ((i & sp_UP) != 0)
player.saltando = 0;
#else
if (((i & sp_FIRE) == 0) && ((player.vy == 0 && player.saltando == 0 && (attr (xx, yy + 1) > 3 || ((x & 15) != 0 && attr (xx + 1, yy + 1) > 3))) || player.gotten)) {
player.saltando = 1;
player.cont_salto = 0;
peta_el_beeper (3);
}
if ( ((i & sp_FIRE) == 0) && player.saltando ) {
player.vy -= (player.salto + PLAYER_INCR_SALTO - (player.cont_salto>>1));
if (player.vy < -PLAYER_MAX_VY_SALTANDO) player.vy = -PLAYER_MAX_VY_SALTANDO;
player.cont_salto ++;
if (player.cont_salto == 8)
player.saltando = 0;
}
if ((i & sp_FIRE) != 0)
player.saltando = 0;
#endif
#endif
#ifdef PLAYER_HAS_JETPAC
if (i & sp_UP == 0) {
player.vy -= PLAYER_INCR_JETPAC;
if (player.vy < -PLAYER_MAX_VY_JETPAC) player.vy = -PLAYER_MAX_VY_JETPAC;
}
#endif
// ------ ok con el movimiento vertical.
/* Movimiento horizontal:
Mientras se pulse una tecla de direccin,
x = x + vx
vx = vx + ax
Si no se pulsa nada:
x = x + vx
vx = vx - rx
*/
if ( ! ((i & sp_LEFT) == 0 || (i & sp_RIGHT) == 0))
if (player.vx > 0) {
player.vx -= player.rx;
if (player.vx < 0)
player.vx = 0;
} else if (player.vx < 0) {
player.vx += player.rx;
if (player.vx > 0)
player.vx = 0;
}
if ((i & sp_LEFT) == 0)
if (player.vx > -PLAYER_MAX_VX) {
player.facing = 0;
player.vx -= player.ax;
}
if ((i & sp_RIGHT) == 0)
if (player.vx < PLAYER_MAX_VX) {
player.vx += player.ax;
player.facing = 1;
}
player.x = player.x + player.vx;
// Safe
if (player.x < 0)
player.x = 0;
if (player.x > 14336)
player.x = 14336;
/* Ahora, como antes, vemos si nos chocamos con algo, y en ese caso
paramos y reculamos */
y = player.y >> 6;
x = player.x >> 6;
yy = y >> 4;
xx = x >> 4;
if (player.vx < 0) {
if (attr (xx, yy) > 7 || ((y & 15) != 0 && attr (xx, yy + 1) > 7)) {
// paramos y ajustamos:
player.vx = 0;
player.x = (xx + 1) << 10;
}
} else {
if (attr (xx + 1, yy) > 7 || ((y & 15) != 0 && attr (xx + 1, yy + 1) > 7)) {
// paramos y ajustamos:
player.vx = 0;
player.x = xx << 10;
}
}
#ifdef PLAYER_CAN_FIRE
// Disparos
#ifdef PLAYER_MOGGY_STYLE
// TODO
#else
if ((i & sp_FIRE) == 0 && player.disparando == 0) {
player.disparando = 1;
fire_bullet ();
}
if ((i & sp_FIRE) != 0)
player.disparando = 0;
#endif
#endif
#ifndef DEACTIVATE_KEYS
// Abrir cerrojo
if ((x & 15) == 0 && (y & 15) == 0) {
if (qtile (xx + 1, yy) == 15 && player.keys > 0) {
map_attr [15 * yy + xx + 1] = 0;
map_buff [15 * yy + xx + 1] = 0;
clear_cerrojo (n_pant, xx + 1, yy);
draw_coloured_tile (VIEWPORT_X + xx + xx + 2, VIEWPORT_Y + yy + yy, 0);
player.keys --;
peta_el_beeper (8);
} else if (qtile (xx - 1, yy) == 15 && player.keys > 0) {
map_attr [15 * yy + xx - 1] = 0;
map_buff [15 * yy + xx - 1] = 0;
clear_cerrojo (n_pant, xx - 1, yy);
draw_coloured_tile (VIEWPORT_X + xx + xx - 2, VIEWPORT_Y + yy + yy, 0);
player.keys --;
peta_el_beeper (8);
}
}
#endif
// Calculamos el frame que hay que poner:
#ifdef PLAYER_PUSH_BOXES
// Empujar cajas (tile #14)
#ifdef PLAYER_MOGGY_STYLE
if ((i & sp_FIRE) == 0) {
#endif
x = player.x >> 6;
y = player.y >> 6;
xx = x >> 4;
yy = y >> 4;
#ifdef PLAYER_AUTO_CHANGE_SCREEN
// En este caso, las cajas no se pararn automticamente en los bordes de la
// pantalla... Tenemos que comprobar de forma explcita que no se salen:
// En modo plataformas, no se puede empujar verticalmente
#ifdef PLAYER_MOGGY_STYLE
// Verticalmente, cuando player.y est alineado a tile:
if ((y & 15) == 0) {
// Segn la tecla que pulse...
if ((i & sp_UP) == 0 && yy > 1) {
if (qtile (xx, yy - 1) == 14 && attr (xx, yy - 2) == 0) {
move_tile (xx, yy - 1, xx, yy - 2);
}
if ((x & 15) != 0) {
if (qtile (xx + 1, yy - 1) == 14 && attr (xx + 1, yy - 2) == 0) {
move_tile (xx + 1, yy - 1, xx + 1, yy - 2);
}
}
} else if ((i & sp_DOWN) == 0 && yy < 8) {
if (qtile (xx, yy + 1) == 14 && attr (xx, yy + 2) == 0) {
move_tile (xx, yy + 1, xx, yy + 2);
}
if ((x & 15) != 0) {
if (qtile (xx + 1, yy + 1) == 14 && attr (xx + 1, yy + 2) == 0) {
move_tile (xx + 1, yy + 1, xx + 1, yy + 2);
}
}
}
}
#endif
// Horizontalmente, cuando player.x est alineado a tile:
if ((x & 15) == 0) {
// Segn la tecla que pulse...
if ((i & sp_RIGHT) == 0 && xx < 14) {
if (qtile (xx + 1, yy) == 14 && attr (xx + 2, yy) == 0) {
move_tile (xx + 1, yy, xx + 2, yy);
}
if ((y & 15) != 0) {
if (qtile (xx + 1, yy + 1) == 14 && attr (xx + 2, yy + 1) == 0) {
move_tile (xx + 1, yy + 1, xx + 2, yy + 1);
}
}
} else if ((i & sp_LEFT) == 0 && xx > 1) {
if (qtile (xx - 1, yy) == 14 && attr (xx - 2, yy) == 0) {
move_tile (xx - 1, yy, xx - 2, yy);
}
if ((y & 15) != 0) {
if (qtile (xx - 1, yy + 1) == 14 && attr (xx - 2, yy + 1) == 0) {
move_tile (xx - 1, yy + 1, xx - 2, yy + 1);
}
}
}
}
#else
// En modo plataformas, no se puede empujar verticalmente
#ifdef PLAYER_MOGGY_STYLE
// Verticalmente, cuando player.y est alineado a tile:
if ((y & 15) == 0) {
// Segn la tecla que pulse...
if ((i & sp_UP) == 0) {
if (qtile (xx, yy - 1) == 14 && attr (xx, yy - 2) == 0) {
move_tile (xx, yy - 1, xx, yy - 2);
}
if ((x & 15) != 0) {
if (qtile (xx + 1, yy - 1) == 14 && attr (xx + 1, yy - 2) == 0) {
move_tile (xx + 1, yy - 1, xx + 1, yy - 2);
}
}
} else if ((i & sp_DOWN) == 0) {
if (qtile (xx, yy + 1) == 14 && attr (xx, yy + 2) == 0) {
move_tile (xx, yy + 1, xx, yy + 2);
}
if ((x & 15) != 0) {
if (qtile (xx + 1, yy + 1) == 14 && attr (xx + 1, yy + 2) == 0) {
move_tile (xx + 1, yy + 1, xx + 1, yy + 2);
}
}
}
}
#endif
// Horizontalmente, cuando player.x est alineado a tile:
if ((x & 15) == 0) {
// Segn la tecla que pulse...
if ((i & sp_RIGHT) == 0) {
if (qtile (xx + 1, yy) == 14 && attr (xx + 2, yy) == 0) {
move_tile (xx + 1, yy, xx + 2, yy);
}
if ((y & 15) != 0) {
if (qtile (xx + 1, yy + 1) == 14 && attr (xx + 2, yy + 1) == 0) {
move_tile (xx + 1, yy + 1, xx + 2, yy + 1);
}
}
} else if ((i & sp_LEFT) == 0) {
if (qtile (xx - 1, yy) == 14 && attr (xx - 2, yy) == 0) {
move_tile (xx - 1, yy, xx - 2, yy);
}
if ((y & 15) != 0) {
if (qtile (xx - 1, yy + 1) == 14 && attr (xx - 2, yy + 1) == 0) {
move_tile (xx - 1, yy + 1, xx - 2, yy + 1);
}
}
}
}
#endif
#ifdef PLAYER_MOGGY_STYLE
}
#endif
#endif
#ifndef DEACTIVATE_EVIL_TILE
// Tiles que te matan.
x = player.x >> 6; // dividimos entre 64 para pixels, y luego entre 16 para tiles.
y = player.y >> 6;
xx = x >> 4;
yy = y >> 4;
if (attr (xx, yy) == 1 ||
((x & 15) != 0 && attr (xx + 1, yy) == 1) ||
((y & 15) != 0 && attr (xx, yy + 1) == 1) ||
((x & 15) != 0 && (y & 15) != 0 && attr (xx + 1, yy + 1) == 1)) {
#ifdef PLAYER_FLICKERS
if (player.life > 0 && player.estado == EST_NORMAL) {
player.estado = EST_PARP;
player.ct_estado = 50;
#else
if (player.life > 0) {
#endif
peta_el_beeper (4);
player.life --;
}
player.x = cx;
player.y = cy;
player.vy = -player.vy;
player.vx = -player.vx;
}
#endif
#ifndef PLAYER_MOGGY_STYLE
// En este caso, el spriteset es:
// 1 2 3 4 5 6 7 8
// R1 R2 R3 RJ L1 L2 L3 LJ
if (player.vy != 0) {
if (player.facing == 0)
player.next_frame = sprite_8_a;
else
player.next_frame = sprite_4_a;
} else {
if (player.vx == 0) {
if (player.facing == 0)
#ifdef PLAYER_ALTERNATE_ANIMATION
player.next_frame = sprite_5_a;
#else
player.next_frame = sprite_6_a;
#endif
else
#ifdef PLAYER_ALTERNATE_ANIMATION
player.next_frame = sprite_1_a;
#else
player.next_frame = sprite_2_a;
#endif
} else {
player.subframe ++;
if (player.subframe == 4) {
player.subframe = 0;
#ifdef PLAYER_ALTERNATE_ANIMATION
player.frame ++;
if (player.frame == 3)
player.frame = 0;
#else
player.frame = (player.frame + 1) & 3;
#endif
step ();
}
#ifdef PLAYER_ALTERNATE_ANIMATION
if (player.facing == 0) {
if (player.frame == 0)
player.next_frame = sprite_5_a;
else if (player.frame == 1)
player.next_frame = sprite_6_a;
else if (player.frame == 2)
player.next_frame = sprite_7_a;
} else {
if (player.frame == 0)
player.next_frame = sprite_1_a;
else if (player.frame == 1)
player.next_frame = sprite_2_a;
else if (player.frame == 2)
player.next_frame = sprite_3_a;
}
#else
if (player.facing == 0) {
if (player.frame == 1 || player.frame == 3)
player.next_frame = sprite_6_a;
else if (player.frame == 0)
player.next_frame = sprite_5_a;
else if (player.frame == 2)
player.next_frame = sprite_7_a;
} else {
if (player.frame == 1 || player.frame == 3)
player.next_frame = sprite_2_a;
else if (player.frame == 0)
player.next_frame = sprite_1_a;
else if (player.frame == 2)
player.next_frame = sprite_3_a;
}
#endif
}
}
#else
// En este caso, el spriteset es:
// 1 2 3 4 5 6 7 8
// R1 R2 L1 L2 U1 U2 D1 D2
if (player.vx != 0 || player.vy != 0) {
player.subframe ++;
if (player.subframe == 4) {
player.subframe = 0;
player.frame = !player.frame;
step ();
}
}
if (player.vx > 0) {
if (player.frame)
player.next_frame = sprite_1_a;
else
player.next_frame = sprite_2_a;
} else if (player.vx < 0) {
if (player.frame)
player.next_frame = sprite_3_a;
else
player.next_frame = sprite_4_a;
} else {
if (player.vy < 0) {
if (player.frame)
player.next_frame = sprite_5_a;
else
player.next_frame = sprite_6_a;
} else {
if (player.frame)
player.next_frame = sprite_7_a;
else
player.next_frame = sprite_8_a;
}
}
#endif
}
void init_player () {
// Inicializa player con los valores iniciales
// (de ah lo de inicializar).
player.x = PLAYER_INI_X << 10;
player.y = PLAYER_INI_Y << 10;
player.vy = 0;
player.g = PLAYER_G;
player.vx = 0;
player.ax = PLAYER_AX;
player.rx = PLAYER_RX;
player.salto = PLAYER_VY_INICIAL_SALTO;
player.cont_salto = 1;
player.saltando = 0;
player.frame = 0;
player.subframe = 0;
player.facing = 1;
player.estado = EST_NORMAL;
player.ct_estado = 0;
player.life = PLAYER_LIFE;
player.objs = 0;
player.keys = 0;
player.killed = 0;
player.disparando = 0;
pant_final = SCR_FIN;
}
void init_hotspots () {
unsigned char i;
for (i = 0; i < MAP_W * MAP_H; i ++)
hotspots [i].act = 1;
}
void draw_scr (unsigned char n_pant) {
// Desempaqueta y dibuja una pantalla, actualiza el array map_attr
// y hace algunas otras cosillas ms (cambiar sprites de enemigos/plataformas, etc)
unsigned char x = 0, y = 0, i, d, t1, t2;
#ifdef UNPACKED_MAP
unsigned int idx = n_pant * 150;
#else
unsigned int idx = n_pant * 75;
#endif
unsigned char location = 0;
#ifdef UNPACKED_MAP
// Mapa tipo UNPACKED
for (i = 0; i < 150; i ++) {
d = mapa [idx++];
map_attr [location] = comportamiento_tiles [d];
map_buff [location] = d;
draw_coloured_tile (VIEWPORT_X + x, VIEWPORT_Y + y, d);
location ++;
x += 2;
if (x == 30) {
x = 0;
y += 2;
}
}
#else
// Mapa tipo PACKED
for (i = 0; i < 75; i ++) {
location = 15 * (y >> 1) + (x >> 1);
d = mapa [idx++];
t1 = d >> 4;
t2 = d & 15;
map_attr [location] = comportamiento_tiles [t1];
if ((rand () & 15) < 2 && t1 == 0 && map_buff [location - 16] == 0)
t1 = 19;
draw_coloured_tile (VIEWPORT_X + x, VIEWPORT_Y + y, t1);
map_buff [location] = t1;
x += 2;
if (x == 30) {
x = 0;
y += 2;
}
location ++;
map_attr [location] = comportamiento_tiles [t2];
if ((rand () & 15) < 2 && t2 == 0 && map_buff [location - 16] == 0)
t2 = 19;
draw_coloured_tile (VIEWPORT_X + x, VIEWPORT_Y + y, t2);
map_buff [location] = t2;
x += 2;
if (x == 30) {
x = 0;
y += 2;
}
}
#endif
// Hay objeto en esta pantalla?
hotspot_x = hotspot_y = 240;
if (hotspots [n_pant].act == 1) {
if (hotspots [n_pant].tipo != 0) {
// Sacamos la posicin a nivel de tiles del objeto
x = (hotspots [n_pant].xy >> 4);
y = (hotspots [n_pant].xy & 15);
// Convertimos la posicin almacenada en pxels
hotspot_x = x << 4;
hotspot_y = y << 4;
// Guardamos el tile que hay originalmente
orig_tile = map_buff [15 * y + x];
// Pintamos el incono del objeto
draw_coloured_tile (VIEWPORT_X + x + x, VIEWPORT_Y + y + y, 16 + hotspots [n_pant].tipo);
}
} else if (hotspots [n_pant].act == 0) {
// Aleatoriamente, ponemos una recarga de vida si no hay objeto activo.
if (rand () % 3 == 2) {
// Sacamos la posicin a nivel de tiles del objeto
x = (hotspots [n_pant].xy >> 4);
y = (hotspots [n_pant].xy & 15);
// Convertimos la posicin almacenada en pxels
hotspot_x = x << 4;
hotspot_y = y << 4;
// Guardamos el tile que hay originalmente
orig_tile = map_buff [15 * y + x];
// Pintamos el incono del objeto
draw_coloured_tile (VIEWPORT_X + x + x, VIEWPORT_Y + y + y, 16);
}
}
#ifndef DEACTIVATE_KEYS
// Borramos los cerrojos abiertos
for (i = 0; i < MAX_CERROJOS; i ++) {
if (cerrojos [i].np == n_pant && !cerrojos [i].st) {
draw_coloured_tile (VIEWPORT_X + cerrojos [i].x + cerrojos [i].x, VIEWPORT_Y + cerrojos [i].y + cerrojos [i].y, 0);
location = 15 * cerrojos [i].y + cerrojos [i].x;
map_attr [location] = 0;
map_buff [location] = 0;
}
}
#endif
// Movemos y cambiamos a los enemigos segn el tipo que tengan
enoffs = n_pant * 3;
for (i = 0; i < 3; i ++) {
en_an [i].frame = 0;
en_an [i].count = 0;
#ifdef RANDOM_RESPAWN
en_an [i].fanty_activo = 0;
#endif
switch (malotes [enoffs + i].t) {
case 0:
sp_MoveSprAbs (sp_moviles [i], spritesClip, 0, 22, 0, 0, 0);
break;
case 1:
en_an [i].next_frame = sprite_9_a;
break;
case 2:
en_an [i].next_frame = sprite_11_a;
break;
case 3:
en_an [i].next_frame = sprite_13_a;
break;
case 4:
en_an [i].next_frame = sprite_15_a;
break;
#ifdef PLAYER_KILLS_ENEMIES
default:
en_an [i].next_frame = sprite_18_a;
#endif
#ifdef PLAYER_CAN_FIRE
default:
en_an [i].next_frame = sprite_18_a;
#endif
}
}
#ifdef ACTIVATE_SCRIPTING
// Ejecutamos los scripts de entrar en pantalla:
script = e_scripts [MAP_W * MAP_H + 1];
run_script ();
script = e_scripts [n_pant];
run_script ();
#endif
#ifdef PLAYER_CAN_FIRE
init_bullets ();
#endif
}
// Esto se emplea en el men
// 1 KEYS
// 2 KEMPSTON
// 3 SINCLAIR
void select_joyfunc () {
unsigned int key_1, key_2, key_3;
unsigned char terminado = 0;
key_1 = sp_LookupKey('1');
key_2 = sp_LookupKey('2');
key_3 = sp_LookupKey('3');
#asm
; Music generated by beepola
call musicstart
#endasm
while (!terminado) {
if (sp_KeyPressed (key_1)) {
terminado = 1;
joyfunc = sp_JoyKeyboard;
} else if (sp_KeyPressed (key_2)) {
terminado = 1;
joyfunc = sp_JoyKempston;
} else if (sp_KeyPressed (key_3)) {
terminado = 1;
joyfunc = sp_JoySinclair1;
}
}
#asm
di
#endasm
}
#ifdef PLAYER_CAN_FIRE
void mueve_bullets () {
unsigned char i;
unsigned char j;
#ifdef PLAYER_MOGGY_STYLE
// TODO
#else
for (i = 0; i < MAX_BULLETS; i ++) {
bullets [i].x += bullets [i].mx;
if (attr (bullets [i].x >> 4, bullets [i].y >> 4) > 7) {
bullets [i].estado = 0;
}
if (bullets [i].x < 8 || bullets [i].x > 240)
bullets [i].estado = 0;
}
#endif
}
#endif
void mueve_bicharracos (unsigned char n_pant) {
// Vamos a mover un frame todos los bicharracos activos.
unsigned char i, j, enoffsmasi, x, y, xx, yy;
unsigned char cx, cy;
unsigned char ccx, ccy;
// Para que si hay dos enemigos que lo toquen en el mismo frame, slo uno acte
unsigned char tocado = 0;
player.gotten = 0;
for (i = 0; i < 3; i ++) {
enoffsmasi = enoffs + i;
if (malotes [enoffsmasi].t != 0) {
cx = malotes [enoffsmasi].x;
cy = malotes [enoffsmasi].y;
#ifdef RANDOM_RESPAWN
if (!en_an [i].fanty_activo) {
malotes [enoffsmasi].x += malotes [enoffsmasi].mx;
malotes [enoffsmasi].y += malotes [enoffsmasi].my;
}
#else
malotes [enoffsmasi].x += malotes [enoffsmasi].mx;
malotes [enoffsmasi].y += malotes [enoffsmasi].my;
#endif
#ifdef PLAYER_PUSH_BOXES
// Colisiones:
x = malotes [enoffsmasi].x >> 4;
y = malotes [enoffsmasi].y >> 4;
if (malotes [enoffsmasi].mx != 0) {
if (attr (x + ctileoff (malotes [enoffsmasi].mx), y) > 7 ||
((malotes [enoffsmasi].y & 15) != 0 && attr (x + ctileoff (malotes [enoffsmasi].mx), y + 1) > 7)) {
malotes [enoffsmasi].mx = -malotes [enoffsmasi].mx;
malotes [enoffsmasi].x = cx;
}
}
if (malotes [enoffsmasi].my != 0) {
if (attr (x, y + ctileoff (malotes [enoffsmasi].my)) > 7 ||
((malotes [enoffsmasi].x & 15) != 0 && attr (x + 1, y + ctileoff (malotes [enoffsmasi].mx)) > 7)) {
malotes [enoffsmasi].my = -malotes [enoffsmasi].my;
malotes [enoffsmasi].y = cy;
}
}
#endif
en_an [i].count ++;
if (en_an [i].count == 4) {
en_an [i].count = 0;
en_an [i].frame = !en_an [i].frame;
switch (malotes [enoffsmasi].t) {
case 1:
en_an [i].next_frame = en_an [i].frame ? sprite_9_a : sprite_10_a;
break;
case 2:
en_an [i].next_frame = en_an [i].frame ? sprite_11_a : sprite_12_a;
break;
case 3:
en_an [i].next_frame = en_an [i].frame ? sprite_13_a : sprite_14_a;
break;
case 4:
en_an [i].next_frame = en_an [i].frame ? sprite_15_a : sprite_16_a;
#ifdef RANDOM_RESPAWN
break;
default:
if (en_an [i].fanty_activo)
en_an [i].next_frame = en_an [i].frame ? sprite_13_a : sprite_14_a;
#endif
}
}
x = player.x >> 6;
y = player.y >> 6;
#ifdef RANDOM_RESPAWN
if (en_an [i].fanty_activo) {
ccx = en_an [i].x >> 6;
ccy = en_an [i].y >> 6;
} else {
ccx = malotes [enoffsmasi].x;
ccy = malotes [enoffsmasi].y;
}
#else
ccx = malotes [enoffsmasi].x;
ccy = malotes [enoffsmasi].y;
#endif
#ifndef PLAYER_MOGGY_STYLE
if (malotes [enoffsmasi].t == 4) {
// Arrastrar plataforma:
xx = player.x >> 10;
// Vertical
if (malotes [enoffsmasi].my < 0) {
// Subir.
if (x >= ccx - 15 && x <= ccx + 15 && y >= ccy - 16 && y <= ccy - 11 && player.vy >= -(PLAYER_INCR_SALTO)) {
player.gotten = 1;
player.y = (ccy - 16) << 6;
player.vy = 0;
yy = player.y >> 10;
// No nos estaremos metiendo en un tile no?
if (player.y > 1024)
if (attr (xx, yy) > 7 || ((x & 15) != 0 && attr (xx + 1, yy) > 7)) {
// ajustamos:
player.y = (yy + 1) << 10;
}
}
} else if (malotes [enoffsmasi].my > 0) {
// bajar
if (x >= ccx - 15 && x <= ccx + 15 && y >= ccy - 20 && y <= ccy - 14 && player.vy >= 0) {
player.gotten = 1;
player.y = (ccy - 16) << 6;
player.vy = 0;
yy = player.y >> 10;
// No nos estaremos metiendo en un tile no?
if (player.y < 9216)
if (attr (xx, yy + 1) > 7 || ((x & 15) != 0 && attr (xx + 1, yy + 1) > 7)) {
// ajustamos:
player.y = yy << 10;
}
}
}
y = player.y >> 6;
yy = player.y >> 10;
// Horizontal
if (malotes [enoffsmasi].mx != 0 && x >= ccx - 15 && x <= ccx + 15 && y >= ccy - 16 && y <= ccy - 8 && player.vy >= 0) {
player.gotten = 1;
player.y = (ccy - 16) << 6;
yy = player.y >> 10;
x = x + malotes [enoffsmasi].mx;
player.x = x << 6;
xx = player.x >> 10;
if (malotes [enoffsmasi].mx < 0) {
if (attr (xx, yy) > 7 || ((y & 15) != 0 && attr (xx, yy + 1) > 7)) {
// paramos y ajustamos:
player.vx = 0;
player.x = (xx + 1) << 10;
}
} else if (malotes [enoffsmasi].mx > 0) {
if (attr (xx + 1, yy) > 7 || ((y & 15) != 0 && attr (xx + 1, yy + 1) > 7)) {
// paramos y ajustamos:
player.vx = 0;
player.x = xx << 10;
}
}
}
// Colisin matadora
#ifdef RANDOM_RESPAWN
} else if (!tocado && collide (x, y, ccx, ccy) && (malotes [enoffsmasi].t < 16 || en_an [i].fanty_activo == 1) && player.estado == EST_NORMAL) {
#else
} else if (!tocado && collide (x, y, ccx, ccy) && malotes [enoffsmasi].t < 16 && player.estado == EST_NORMAL) {
#endif
#else
#ifdef RANDOM_RESPAWN
if (!tocado && collide (x, y, ccx, ccy) && (malotes [enoffsmasi].t < 16 || en_an [i].fanty_activo == 1) && player.estado == EST_NORMAL) {
#else
if (!tocado && collide (x, y, ccx, ccy) && malotes [enoffsmasi].t < 16 && player.estado == EST_NORMAL) {
#endif
#endif
#ifdef PLAYER_KILLS_ENEMIES
if (y < ccy - 2 && player.vy >= 0 && malotes [enoffsmasi].t >= PLAYER_MIN_KILLABLE) {
// matar enemigo:
en_an [i].next_frame = sprite_17_a;
sp_MoveSprAbs (sp_moviles [i], spritesClip, en_an [i].next_frame - en_an [i].current_frame, VIEWPORT_Y + (malotes [enoffs + i].y >> 3), VIEWPORT_X + (malotes [enoffs + i].x >> 3), malotes [enoffs + i].x & 7, malotes [enoffs + i].y & 7);
en_an [i].current_frame = en_an [i].next_frame;
sp_UpdateNow ();
peta_el_beeper (5);
en_an [i].next_frame = sprite_18_a;
malotes [enoffsmasi].t |= 16; // Marcamos como "estoy muelto"
// Contamos un enemigo muerto ms
player.killed ++;
#ifdef ACTIVATE_SCRIPTING
// Vemos si hay algn script por ejecutar
script = f_scripts [n_pant];
run_script ();
// Modificacin *********
script = e_scripts [MAP_W * MAP_H + 1];
run_script ();
#endif
} else if (player.life > 0) {
#else
if (player.life > 0) {
#endif
tocado = 1;
peta_el_beeper (4);
player.life --;
#ifdef PLAYER_BOUNCES
#ifndef PLAYER_MOGGY_STYLE
#ifdef RANDOM_RESPAWN
if (!en_an [i].fanty_activo) {
// Repulsin: Empuja en la direccin mx, my del movimiento del malote
// incrementando vy con PLAYER_MAX_VX con el signo correcto.
if (malotes [enoffsmasi].mx > 0) player.vx = PLAYER_MAX_VX;
if (malotes [enoffsmasi].mx < 0) player.vx = -PLAYER_MAX_VX;
if (malotes [enoffsmasi].my > 0) player.vy = PLAYER_MAX_VX;
if (malotes [enoffsmasi].my < 0) player.vy = -PLAYER_MAX_VX;
} else {
player.vx = en_an [i].vx + en_an [i].vx;
player.vy = en_an [i].vy + en_an [i].vy;
}
#else
// Repulsin: Empuja en la direccin mx, my del movimiento del malote
// incrementando vy con PLAYER_MAX_VX con el signo correcto.
if (malotes [enoffsmasi].mx > 0) player.vx = (PLAYER_MAX_VX + PLAYER_MAX_VX);
if (malotes [enoffsmasi].mx < 0) player.vx = -(PLAYER_MAX_VX + PLAYER_MAX_VX);
if (malotes [enoffsmasi].my > 0) player.vy = (PLAYER_MAX_VX + PLAYER_MAX_VX);
if (malotes [enoffsmasi].my < 0) player.vy = -(PLAYER_MAX_VX + PLAYER_MAX_VX);
#endif
#else
// Vamos a empujar al player en el sentido de la diagonal que los une, con la
// direccin que los haga separarse, con 2*v del enemigo
// x
if (malotes [enoffsmasi].mx != 0) {
if (x < ccx) {
player.vx = - (abs (malotes [enoffsmasi].mx + malotes [enoffsmasi].mx) << 7);
} else {
player.vx = abs (malotes [enoffsmasi].mx + malotes [enoffsmasi].mx) << 7;
}
}
// y
if (malotes [enoffsmasi].my != 0) {
if (y < ccy) {
player.vy = - (abs (malotes [enoffsmasi].my + malotes [enoffsmasi].my) << 7);
} else {
player.vy = abs (malotes [enoffsmasi].my + malotes [enoffsmasi].my) << 7;
}
}
#endif
#endif
#ifdef PLAYER_FLICKERS
// El jugador parpadear durante unos momentos
// y ser invulnerable mientras tanto.
player.estado = EST_PARP;
player.ct_estado = 50;
#endif
}
}
// Lmites de trayectoria.
#ifdef RANDOM_RESPAWN
if (en_an [i].fanty_activo) {
if (player_hidden ()) {
if (player.x < en_an [i].x && en_an [i].vx < FANTY_MAX_V)
en_an [i].vx += FANTY_A >> 1;
else if (player.x > en_an [i].x && en_an [i].vx > -FANTY_MAX_V)
en_an [i].vx -= FANTY_A >> 1;
if (player.y < en_an [i].y && en_an [i].vy < FANTY_MAX_V)
en_an [i].vy += FANTY_A >> 1;
else if (player.y > en_an [i].y && en_an [i].vy > -FANTY_MAX_V)
en_an [i].vy -= FANTY_A >> 1;
} else if ((rand () & 7) > 1) {
if (player.x > en_an [i].x && en_an [i].vx < FANTY_MAX_V)
en_an [i].vx += FANTY_A;
else if (player.x < en_an [i].x && en_an [i].vx > -FANTY_MAX_V)
en_an [i].vx -= FANTY_A;
if (player.y > en_an [i].y && en_an [i].vy < FANTY_MAX_V)
en_an [i].vy += FANTY_A;
else if (player.y < en_an [i].y && en_an [i].vy > -FANTY_MAX_V)
en_an [i].vy -= FANTY_A;
}
en_an [i].x += en_an [i].vx;
en_an [i].y += en_an [i].vy;
if (en_an [i].x > 15360) en_an [i].x = 15360;
if (en_an [i].x < -1024) en_an [i].x = -1024;
if (en_an [i].y > 10240) en_an [i].y = 10240;
if (en_an [i].y < -1024) en_an [i].y = -1024;
} else {
#endif
if (ccx == malotes [enoffsmasi].x1 || ccx == malotes [enoffsmasi].x2)
malotes [enoffsmasi].mx = -malotes [enoffsmasi].mx;
if (ccy == malotes [enoffsmasi].y1 || ccy == malotes [enoffsmasi].y2)
malotes [enoffsmasi].my = -malotes [enoffsmasi].my;
#ifdef RANDOM_RESPAWN
}
#endif
#ifdef PLAYER_CAN_FIRE
// Colisin con balas
#ifdef RANDOM_RESPAWN
if (malotes [enoffsmasi].t < 16 || en_an [i].fanty_activo == 1) {
#else
if (malotes [enoffsmasi].t < 16) {
#endif
for (j = 0; j < MAX_BULLETS; j ++) {
if (bullets [j].estado == 1) {
if (bullets [j].y >= ccy - 4 && bullets [j].y <= ccy + 12 && bullets [j].x >= ccx - 4 && bullets [j].x <= ccx + 12) {
#ifdef RANDOM_RESPAWN
if (en_an [i].fanty_activo)
en_an [i].vx += (bullets [i].mx > 0 ? 128 : -128);
#endif
en_an [i].next_frame = sprite_17_a;
en_an [i].morido = 1;
bullets [j].estado = 0;
if (malotes [enoffsmasi].t != 4)
malotes [enoffsmasi].life --;
if (malotes [enoffsmasi].life == 0) {
// matar enemigo:
sp_MoveSprAbs (sp_moviles [i], spritesClip, en_an [i].next_frame - en_an [i].current_frame, VIEWPORT_Y + (ccy >> 3), VIEWPORT_X + (ccx >> 3), ccx & 7, ccy & 7);
en_an [i].current_frame = en_an [i].next_frame;
sp_UpdateNow ();
peta_el_beeper (5);
en_an [i].next_frame = sprite_18_a;
malotes [enoffsmasi].t |= 16; // Marcamos como "estoy muelto"
// Contamos un enemigo muerto ms
player.killed ++;
#ifdef RANDOM_RESPAWN
en_an [i].fanty_activo = 0;
malotes [enoffsmasi].life = FANTIES_LIFE_GAUGE;
#endif
}
}
}
}
}
#endif
#ifdef RANDOM_RESPAWN
// Activar fanty
if (malotes [enoffsmasi].t > 15 && en_an [i].fanty_activo == 0 && (rand () & 31) == 1) {
en_an [i].fanty_activo = 1;
if (player.y > 5120)
en_an [i].y = -1024;
else
en_an [i].y = 10240;
en_an [i].x = (rand () % 240 - 8) << 6;
en_an [i].vx = en_an [i].vy = 0;
}
#endif
}
}
}
| 412 | 0.807979 | 1 | 0.807979 | game-dev | MEDIA | 0.947749 | game-dev | 0.876547 | 1 | 0.876547 |
FWGS/hlsdk-portable | 3,456 | cl_dll/hl/hl_events.cpp | /***
*
* Copyright (c) 1996-2002, Valve LLC. All rights reserved.
*
* This product contains software technology licensed from Id
* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc.
* All Rights Reserved.
*
* Use, distribution, and modification of this source code and/or resulting
* object code is restricted to non-commercial enhancements to products from
* Valve LLC. All other use, distribution, or modification is prohibited
* without written permission from Valve LLC.
*
****/
#include "../hud.h"
#include "../cl_util.h"
#include "event_api.h"
extern "C"
{
// HLDM
void EV_FireGlock1( struct event_args_s *args );
void EV_FireGlock2( struct event_args_s *args );
void EV_FireShotGunSingle( struct event_args_s *args );
void EV_FireShotGunDouble( struct event_args_s *args );
void EV_FireMP5( struct event_args_s *args );
void EV_FireMP52( struct event_args_s *args );
void EV_FirePython( struct event_args_s *args );
void EV_FireGauss( struct event_args_s *args );
void EV_SpinGauss( struct event_args_s *args );
void EV_Crowbar( struct event_args_s *args );
void EV_FireCrossbow( struct event_args_s *args );
void EV_FireCrossbow2( struct event_args_s *args );
void EV_FireRpg( struct event_args_s *args );
void EV_EgonFire( struct event_args_s *args );
void EV_EgonStop( struct event_args_s *args );
void EV_HornetGunFire( struct event_args_s *args );
void EV_TripmineFire( struct event_args_s *args );
void EV_SnarkFire( struct event_args_s *args );
void EV_TrainPitchAdjust( struct event_args_s *args );
void EV_VehiclePitchAdjust( event_args_t *args );
}
/*
======================
Game_HookEvents
Associate script file name with callback functions. Callback's must be extern "C" so
the engine doesn't get confused about name mangling stuff. Note that the format is
always the same. Of course, a clever mod team could actually embed parameters, behavior
into the actual .sc files and create a .sc file parser and hook their functionality through
that.. i.e., a scripting system.
That was what we were going to do, but we ran out of time...oh well.
======================
*/
void Game_HookEvents( void )
{
gEngfuncs.pfnHookEvent( "events/glock1.sc", EV_FireGlock1 );
gEngfuncs.pfnHookEvent( "events/glock2.sc", EV_FireGlock2 );
gEngfuncs.pfnHookEvent( "events/shotgun1.sc", EV_FireShotGunSingle );
gEngfuncs.pfnHookEvent( "events/shotgun2.sc", EV_FireShotGunDouble );
gEngfuncs.pfnHookEvent( "events/mp5.sc", EV_FireMP5 );
gEngfuncs.pfnHookEvent( "events/mp52.sc", EV_FireMP52 );
gEngfuncs.pfnHookEvent( "events/python.sc", EV_FirePython );
gEngfuncs.pfnHookEvent( "events/gauss.sc", EV_FireGauss );
gEngfuncs.pfnHookEvent( "events/gaussspin.sc", EV_SpinGauss );
gEngfuncs.pfnHookEvent( "events/train.sc", EV_TrainPitchAdjust );
gEngfuncs.pfnHookEvent( "events/crowbar.sc", EV_Crowbar );
gEngfuncs.pfnHookEvent( "events/crossbow1.sc", EV_FireCrossbow );
gEngfuncs.pfnHookEvent( "events/crossbow2.sc", EV_FireCrossbow2 );
gEngfuncs.pfnHookEvent( "events/rpg.sc", EV_FireRpg );
gEngfuncs.pfnHookEvent( "events/egon_fire.sc", EV_EgonFire );
gEngfuncs.pfnHookEvent( "events/egon_stop.sc", EV_EgonStop );
gEngfuncs.pfnHookEvent( "events/firehornet.sc", EV_HornetGunFire );
gEngfuncs.pfnHookEvent( "events/tripfire.sc", EV_TripmineFire );
gEngfuncs.pfnHookEvent( "events/snarkfire.sc", EV_SnarkFire );
gEngfuncs.pfnHookEvent( "events/vehicle.sc", EV_VehiclePitchAdjust );
}
| 412 | 0.556547 | 1 | 0.556547 | game-dev | MEDIA | 0.825635 | game-dev | 0.715716 | 1 | 0.715716 |
double-commander/doublecmd | 108,366 | components/viewer/viewercontrol.pas | {
Double Commander
-------------------------------------------------------------------------
Show file in the text, bin, hex or dec mode
Copyright (C) 2004 Radek Cervinka (radek.cervinka@centrum.cz)
Copyright (C) 2006-2025 Alexander Koblov (alexx2000@mail.ru)
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
}
(*
TODO:
a) File mapping blocks writing into file by other processes.
Either:
+ Open small text files by reading them all into memory (done).
- Add optional custom loading/caching portions of file in memory
and only reading from file when neccessary.
b) Selecting text does not work well with composed Unicode characters
(characters that are composed of multiple Unicode characters).
c) Drawing/selecting text does not work correctly with RTL (right to left) text.
d) FTextHeight is unreliable with complex unicode characters. It should be
calculated based on currently displayed text (get max from each line's height).
*)
unit ViewerControl;
{$mode objfpc}{$H+}
interface
uses
SysUtils, Classes, Controls, StdCtrls, LCLVersion, LMessages, fgl;
const
MaxMemSize = $400000; // 4 Mb
type
TViewerControlMode = (vcmBin, vcmHex, vcmText, vcmWrap, vcmBook, vcmDec);
TDataAccess = (dtMmap, dtNothing);
TCharSide = (csBefore, csLeft, csRight, csAfter);
TPtrIntList = specialize TFPGList<PtrInt>;
TGuessEncodingEvent = function(const s: string): string;
TFileOpenEvent = function(const FileName: String; Mode: LongWord): System.THandle;
TCustomCharsPresentation = class;
TCharToCustomValueTransformProc = function(AChar:AnsiChar;AMaxDigitsCount:integer):AnsiString of object;
{ TCustomCharsPresentation }
{
Presentation one char is called Value
Function for convert char to Value is ChrToValueProc
}
TCustomCharsPresentation = class
public
ValuesPerLine :integer; // = 16 for Hex by default
MaxValueDigits :integer; // the max width of present char (255) - 3 symbols
MaxAddrDigits :integer; // = 8;
StartOfs :integer; // = OffsetWidth + 2; // ': '
EndOfs :integer; // = StartOfs + (ValuesPerLine * (ValueMaxDigits+SpaceCount));
StartAscii :integer; // = StartOfs + (ValuesPerLine * (ValueMaxDigits+SpaceCount)) + 2; // ' '
SpaceCount :integer; // = 1 - one spacebar between Values
SeparatorSpace :AnsiString; // spacebar * SpaceCount
SeparatorChar :AnsiChar; // '|'
CountSeperate :integer; // insert SeparatorChar after every CountSeperate values
ChrToValueProc :TCharToCustomValueTransformProc; // procedure which return presentation of one char
constructor Create(APresentValuesPerLine,ACharMaxPresentWidth,AOffsetWidth,ACountSeparate:integer;AChrToValueProc:TCharToCustomValueTransformProc);
destructor Destroy();override;
end;
type
// If additional encodings are added they should be also supported by:
// - GetNextCharAsAscii
// - GetPrevCharAsAscii
// - GetNextCharAsUtf8
// - ConvertToUTF8
// - UpdateSelection
TViewerEncoding = (veAutoDetect,
veUtf8,
veUtf8bom,
veAnsi,
veOem,
veCp1250,
veCp1251,
veCp1252,
veCp1253,
veCp1254,
veCp1255,
veCp1256,
veCp1257,
veCp1258,
veCp437,
veCp850,
veCp852,
veCp866,
veCp874,
veCp932,
veCp936,
veCp949,
veCp950,
veIso88591,
veIso88592,
veKoi8r,
veKoi8u,
veKoi8ru,
veUcs2le,
veUcs2be,
veUtf16le,
veUtf16be,
veUtf32le, // = ucs4le
veUtf32be); // = ucs4be
TViewerEncodings = set of TViewerEncoding;
const
ViewerEncodingsNames: array [TViewerEncoding] of string =
('Auto-detect',
'UTF-8',
'UTF-8BOM',
'ANSI',
'OEM',
'CP1250',
'CP1251',
'CP1252',
'CP1253',
'CP1254',
'CP1255',
'CP1256',
'CP1257',
'CP1258',
'CP437',
'CP850',
'CP852',
'CP866',
'CP874',
'CP932',
'CP936',
'CP949',
'CP950',
'ISO-8859-1',
'ISO-8859-2',
'KOI8-R',
'KOI8-U',
'KOI8-RU',
'UCS-2LE',
'UCS-2BE',
'UTF-16LE',
'UTF-16BE',
'UTF-32LE',
'UTF-32BE');
const
ViewerEncodingOem: TViewerEncodings = [
veCp437, veCp850, veCp852, veCp866];
ViewerEncodingMultiByte: TViewerEncodings = [
veCp932, veCp936, veCp949, veCp950,
veUtf8, veUtf8bom, veUcs2le, veUcs2be,
veUtf16le, veUtf16be, veUtf32le, veUtf32be];
ViewerEncodingDoubleByte: TViewerEncodings = [
veUcs2le, veUcs2be, veUtf16le, veUtf16be ];
type
{ TViewerControl }
TViewerControl = class(TCustomControl)
protected
FEncoding: TViewerEncoding;
FViewerControlMode: TViewerControlMode;
FFileName: String;
FFileHandle: THandle;
FFileSize: Int64;
FMappingHandle: THandle;
FMappedFile: Pointer;
FPosition: PtrInt;
FHPosition: Integer; // Tab for text during horizontal scroll
FHLowEnd: Integer; // End for HPosition (string with max char)
FVisibleOffset: PtrInt; // Offset in symbols for current line (see IsVisible and MakeVisible)
FLowLimit: PtrInt; // Lowest possible value for Position
FHighLimit: PtrInt; // Position cannot reach this value
FBOMLength: Integer;
FLineList: TPtrIntList;
FBlockBeg: PtrInt;
FBlockEnd: PtrInt;
FCaretPos: PtrInt;
FCaretPoint: TPoint;
FMouseBlockBeg: PtrInt;
FMouseBlockSide: TCharSide;
FSelecting: Boolean;
FTextWidth: Integer; // max char count or width in window
FTextHeight: Integer; // measured values of font, rec calc at font changed
FScrollBarVert: TScrollBar;
FScrollBarHorz: TScrollBar;
FOnPositionChanged: TNotifyEvent;
FUpdateScrollBarPos: Boolean; // used to block updating of scrollbar
FScrollBarPosition: Integer; // for updating vertical scrollbar based on Position
FHScrollBarPosition: Integer; // for updating horizontal scrollbar based on HPosition
FColCount: Integer;
FTabSpaces: Integer; // tab width in spaces
FMaxTextWidth: Integer; // maximum of chars on one line unwrapped text (max 16384)
FExtraLineSpacing: Integer;
FLeftMargin: Integer;
FOnGuessEncoding: TGuessEncodingEvent;
FOnFileOpen: TFileOpenEvent;
FCaretVisible: Boolean;
FShowCaret: Boolean;
FAutoCopy: Boolean;
FLastError: String;
FText: String;
FHex:TCustomCharsPresentation;
FDec:TCustomCharsPresentation;
FCustom:TCustomCharsPresentation;
function GetPercent: Integer;
procedure SetPercent(const AValue: Integer);
procedure SetBlockBegin(const AValue: PtrInt);
procedure SetBlockEnd(const AValue: PtrInt);
procedure SetPosition(Value: PtrInt); virtual;
procedure SetHPosition(Value: Integer);
procedure SetPosition(Value: PtrInt; Force: Boolean); overload;
procedure SetHPosition(Value: Integer; Force: Boolean); overload;
procedure SetEncoding(AEncoding: TViewerEncoding);
function GetEncodingName: string;
procedure SetEncodingName(AEncodingName: string);
procedure SetViewerMode(Value: TViewerControlMode);
procedure SetColCount(const AValue: Integer);
procedure SetMaxTextWidth(const AValue: Integer);
procedure SetTabSpaces(const AValue: Integer);
procedure SetShowCaret(AValue: Boolean);
procedure SetCaretPos(AValue: PtrInt);
{en
Returns how many lines (given current FTextHeight) will fit into the window.
}
function GetClientHeightInLines(Whole: Boolean = True): Integer; inline;
{en
Calculates how many lines can be displayed from given position.
param(FromPosition
Position from which to check. It should point to a start of a line.)
@param(LastLineReached
If it is set to @true when the function returns, then the last
line of text was reached when scanning.
This means that there are no more lines to be displayed other than
the ones scanned from FromPosition. In other words:
SetPosition(GetStartOfNextLine(FromPosition)) will be one line
too many and will be scrolled back.)
}
function GetLinesTillEnd(FromPosition: PtrInt; out LastLineReached: Boolean): Integer;
function GetBomLength: Integer;
procedure UpdateLimits;
{en
@param(iStartPos
Should point to start of a line.
It is increased by the amount of parsed data (with line endings).)
@param(aLimit
Position which cannot be reached while reading from file.)
@param(DataLength
It is length in bytes of parsed data without any line endings.
iStartPos is moved beyond the line endings though.)
}
function CalcTextLineLength(var iStartPos: PtrInt; const aLimit: Int64; out DataLength: PtrInt): Integer;
function GetStartOfLine(aPosition: PtrInt): PtrInt;
function GetEndOfLine(aPosition: PtrInt): PtrInt;
function GetStartOfPrevLine(aPosition: PtrInt): PtrInt;
function GetStartOfNextLine(aPosition: PtrInt): PtrInt;
{en
Changes the value of aPosition to X lines back or forward.
@param(aPosition
File position to change.)
@param(iLines
Nr of lines to scroll.
If positive the position is increased by iLines lines,
if negative the position is decreased by -iLines lines.)
}
function ScrollPosition(var aPosition: PtrInt; iLines: Integer): Boolean;
{en
Calculates (x,y) cursor position to a position within file.
@param(x
Client X coordinate of mouse cursor.)
@param(y
Client Y coordinate of mouse cursor.)
@param(CharSide
To which side of a character at returned position the (x,y) points to.
Only valid if returned position is not -1.)
@returns(Position in file to which (x,y) points to, based on what is
currently displayed.
Returns -1 if (x,y) doesn't point to any position (outside of
the text for example).)
}
function XYPos2Adr(x, y: Integer; out CharSide: TCharSide): PtrInt;
procedure OutText(x, y: Integer; const sText: String; StartPos: PtrInt; DataLength: Integer);
procedure OutBin(x, y: Integer; const sText: String; StartPos: PtrInt; DataLength: Integer);
procedure OutCustom(x, y: Integer; const sText: String;StartPos: PtrInt; DataLength: Integer); // render one line
function TransformCustom(var APosition: PtrInt; ALimit: PtrInt; AWithAdditionalData: Boolean = True): String;
function TransformCustomBlock(var APosition: PtrInt; DataLength: Integer; ASeparatorsOn, AAlignData: Boolean; out AChars: String): String;
function HexToValueProc(AChar:AnsiChar;AMaxDigitsCount:integer):AnsiString;
function DecToValueProc(AChar:AnsiChar;AMaxDigitsCount:integer):AnsiString;
procedure WriteBin;
procedure WriteText;
procedure WriteCustom; virtual;
function TransformText(const sText: String; const Xoffset: Integer): String;
function TransformBin(var aPosition: PtrInt; aLimit: PtrInt): String;
function TransformHex(var aPosition: PtrInt; aLimit: PtrInt): AnsiString;virtual;
procedure AddLineOffset(const iOffset: PtrInt); inline;
procedure DrawLastError;
function MapFile(const sFileName: String): Boolean;
procedure UnMapFile;
procedure SetFileName(const sFileName: String);
procedure UpdateScrollbars;
procedure ViewerResize(Sender: TObject);
{en
Returns next unicode character from the file, depending on Encoding.
It is a faster version, which does as little conversion as possible,
but only Ascii values are guaranteed to be valid (0-127).
Other unicode values may/may not be valid, so shouldn't be tested.
This function is used for reading pure ascii characters such as
line endings, tabs, white spaces, etc.
}
function GetNextCharAsAscii(const iPosition: PtrInt; out CharLenInBytes: Integer): Cardinal;
function GetPrevCharAsAscii(const iPosition: PtrInt; out CharLenInBytes: Integer): Cardinal;
{en
Retrieve next character from the file depending on encoding and
automatically convert it to UTF-8.
If CharLenInBytes is greater than 0 but the result is an empty string
then it's possible there was no appropriate UTF-8 character for the
next character of the current encoding.
}
function GetNextCharAsUtf8(const iPosition: PtrInt; out CharLenInBytes: Integer): String;
procedure ReReadFile;
{en
Searches for an ASCII character.
@param(aPosition
Position from where the search starts.)
@param(aMaxBytes
How many bytes are available for reading.)
@param(AsciiChars
The function searches for any character that this string contains.)
@param(bFindNotIn
If @true searches for first character not included in AsciiChars.
If @false searches for first character included in AsciiChars.)
}
function FindAsciiSetForward(aPosition, aMaxBytes: PtrInt;
const AsciiChars: String;
bFindNotIn: Boolean): PtrInt;
{en
Same as FindForward but it searches backwards from pAdr.
aMaxBytes must be number of available bytes for reading backwards from pAdr.
}
function FindAsciiSetBackward(aPosition, aMaxBytes: PtrInt;
const AsciiChars: String;
bFindNotIn: Boolean): PtrInt;
{en
Checks if current selection is still valid given current viewer mode and encoding.
For example checks if selection is not in the middle of a unicode character.
}
procedure UpdateSelection;
function GetViewerRect: TRect;
procedure ScrollBarVertScroll(Sender: TObject; ScrollCode: TScrollCode;
var ScrollPos: Integer);
procedure ScrollBarHorzScroll(Sender: TObject; ScrollCode: TScrollCode;
var ScrollPos: Integer);
function GetText(const StartPos, Len: PtrInt; const Xoffset: Integer): string;
procedure SetText(const AValue: String);
protected
procedure WMSetFocus(var Message: TLMSetFocus); message LM_SETFOCUS;
procedure WMKillFocus(var Message: TLMKillFocus); message LM_KILLFOCUS;
procedure FontChanged(Sender: TObject); override;
procedure KeyDown(var Key: word; Shift: TShiftState); override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
function DoMouseWheelDown(Shift: TShiftState; MousePos: TPoint): Boolean; override;
function DoMouseWheelUp(Shift: TShiftState; MousePos: TPoint): Boolean; override;
function DoMouseWheelLeft(Shift: TShiftState; MousePos: TPoint): Boolean; override;
function DoMouseWheelRight(Shift: TShiftState; MousePos: TPoint): Boolean; override;
procedure DoAutoAdjustLayout(const AMode: TLayoutAdjustmentPolicy; const AXProportion, AYProportion: Double); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Paint; override;
{en
Scrolls the displayed text in the window.
@param(iLines
Nr of lines to scroll.
If positive the text is scrolled downwards,
if negative the text is scrolled upwards.)
@returns(@true if the text was scrolled.)
}
function Scroll(iLines: Integer): Boolean;
function HScroll(iSymbols: Integer): Boolean;
procedure PageUp;
procedure PageDown;
procedure GoHome;
procedure GoEnd;
procedure HPageUp;
procedure HPageDown;
procedure HGoHome;
procedure HGoEnd;
procedure CaretGoHome;
procedure CaretGoEnd;
function GetDataAdr: Pointer;
procedure SelectAll;
procedure SelectText(AStart, AEnd: PtrInt);
procedure CopyToClipboard;
procedure CopyToClipboardF;
function Selection: String;
function IsVisible(const aPosition: PtrInt): Boolean; overload;
procedure MakeVisible(const aPosition: PtrInt);
function ConvertToUTF8(const sText: AnsiString): String;
function ConvertFromUTF8(const sText: String): AnsiString;
function FindUtf8Text(iStartPos: PtrInt; const sSearchText: String;
bCaseSensitive: Boolean; bSearchBackwards: Boolean): PtrInt;
procedure ResetEncoding;
function IsFileOpen: Boolean; inline;
function DetectEncoding: TViewerEncoding;
procedure GetSupportedEncodings(List: TStrings);
property Text: String read FText write SetText;
property Percent: Integer Read GetPercent Write SetPercent;
property Position: PtrInt Read FPosition Write SetPosition;
property FileSize: Int64 Read FFileSize;
property FileHandle: THandle read FFileHandle;
property CaretPos: PtrInt Read FCaretPos Write SetCaretPos;
property SelectionStart: PtrInt Read FBlockBeg Write SetBlockBegin;
property SelectionEnd: PtrInt Read FBlockEnd Write SetBlockEnd;
property EncodingName: string Read GetEncodingName Write SetEncodingName;
property ColCount: Integer Read FColCount Write SetColCount;
property MaxTextWidth: Integer read FMaxTextWidth write SetMaxTextWidth;
property TabSpaces: Integer read FTabSpaces write SetTabSpaces;
property LeftMargin: Integer read FLeftMargin write FLeftMargin;
property ExtraLineSpacing: Integer read FExtraLineSpacing write FExtraLineSpacing;
property AutoCopy: Boolean read FAutoCopy write FAutoCopy;
property OnGuessEncoding: TGuessEncodingEvent Read FOnGuessEncoding Write FOnGuessEncoding;
property OnFileOpen: TFileOpenEvent read FOnFileOpen write FOnFileOpen;
published
property Mode: TViewerControlMode Read FViewerControlMode Write SetViewerMode default vcmWrap;
property FileName: String Read FFileName Write SetFileName;
property Encoding: TViewerEncoding Read FEncoding Write SetEncoding default veAutoDetect;
property OnPositionChanged: TNotifyEvent Read FOnPositionChanged Write FOnPositionChanged;
property ShowCaret: Boolean read FShowCaret write SetShowCaret;
property OnClick;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnMouseWheelUp;
property OnMouseWheelDown;
property Align;
property Color;
property Cursor default crIBeam;
property Font;
property ParentColor default False;
property TabStop default True;
end;
procedure Register;
implementation
uses
Math, LCLType, Graphics, Forms, LCLProc, Clipbrd, LConvEncoding,
DCUnicodeUtils, LCLIntf, LazUTF8, DCOSUtils , DCConvertEncoding
{$IF LCL_FULLVERSION >= 4990000}
, LazUTF16
{$ENDIF}
{$IF DEFINED(UNIX)}
, BaseUnix, Unix, DCUnix
{$ELSEIF DEFINED(WINDOWS)}
, Windows, DCWindows
{$ENDIF};
const
cBinWidth = 80;
// These strings must be Ascii only.
sNonCharacter: string = ' !"#$%&''()*+,-./:;<=>?@[\]^`{|}~'#13#10#9;
sWhiteSpace : string = ' '#13#10#9#8;
const
ASCII_TABLE: array[0..31] of String =
(
'.', '☺', '☻', '♥', '♦', '♣', '♠', '•', '◘', '○', '◙', '♂', '♀', '♪', '♫', '☼',
'►', '◄', '↕', '‼', '¶', '§', '▬', '↨', '↑', '↓', '→', '←', '∟', '↔', '▲', '▼'
);
{ TCustomCharsPresentation }
constructor TCustomCharsPresentation.Create(APresentValuesPerLine,
ACharMaxPresentWidth, AOffsetWidth, ACountSeparate: integer;AChrToValueProc:TCharToCustomValueTransformProc);
begin
SpaceCount:=1; // count of spacebars between values, =1
ValuesPerLine := APresentValuesPerLine; // default for hex: 16 values
MaxAddrDigits := AOffsetWidth; // = 8 , count of symbols for display caret offset
StartOfs := AOffsetWidth + 2; // ': '
MaxValueDigits := ACharMaxPresentWidth; // hex char (FF) - 2 symbols, dec char (255) - 3 symbols
EndOfs := StartOfs + (ValuesPerLine * (MaxValueDigits+SpaceCount)); // +1 - take in spacebar
StartAscii := StartOfs + (ValuesPerLine * (MaxValueDigits+SpaceCount)) + 2; // ' '
SeparatorChar:='|';
CountSeperate:=ACountSeparate;
SeparatorSpace:=' ';
ChrToValueProc:=AChrToValueProc; // method for convert char to Value
end;
destructor TCustomCharsPresentation.Destroy;
begin
inherited;
end;
// ----------------------------------------------------------------------------
constructor TViewerControl.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Cursor := crIBeam;
ParentColor := False;
DoubleBuffered := True;
ControlStyle := ControlStyle + [csTripleClicks, csOpaque];
TabStop := True; // so that it can get keyboard focus
FEncoding := veAutoDetect;
FViewerControlMode := vcmText;
FCustom := nil;
FFileName := '';
FMappedFile := nil;
FFileHandle := 0;
FMappingHandle := 0;
FPosition := 0;
FHPosition := 0;
FHLowEnd := 0;
FLowLimit := 0;
FHighLimit := 0;
FBOMLength := 0;
FTextHeight:= 14; // dummy value
FColCount := 1;
FTabSpaces := 8;
FLeftMargin := 4;
FMaxTextWidth := 1024;
FAutoCopy := True;
FLineList := TPtrIntList.Create;
FScrollBarVert := TScrollBar.Create(Self);
FScrollBarVert.Parent := Self;
FScrollBarVert.Kind := sbVertical;
FScrollBarVert.Align := alRight;
FScrollBarVert.OnScroll := @ScrollBarVertScroll;
FScrollBarVert.TabStop := False;
FScrollBarVert.PageSize := 0;
FScrollBarHorz := TScrollBar.Create(Self);
FScrollBarHorz.Parent := Self;
FScrollBarHorz.Kind := sbHorizontal;
FScrollBarHorz.Align := alBottom;
FScrollBarHorz.OnScroll := @ScrollBarHorzScroll;
FScrollBarHorz.TabStop := False;
FScrollBarHorz.PageSize := 0;
FUpdateScrollBarPos := True;
FScrollBarPosition := 0;
FHScrollBarPosition := 0;
FOnPositionChanged := nil;
FOnGuessEncoding := nil;
OnResize := @ViewerResize;
FHex:=TCustomCharsPresentation.Create(16,2,8,8,@HexToValueProc);
FDec:=TCustomCharsPresentation.Create(15,3,8,5,@DecToValueProc); // for set bigger ValuePerLine need to improve method GetEndOfLine
end;
destructor TViewerControl.Destroy;
begin
FHex.Free;
FDec.Free;
FHex:=nil;
FDec:=nil;
FCustom:=nil;
UnMapFile;
if Assigned(FLineList) then
FreeAndNil(FLineList);
inherited Destroy;
end;
procedure TViewerControl.DrawLastError;
var
AStyle: TTextStyle;
begin
AStyle:= Canvas.TextStyle;
AStyle.Alignment:= taCenter;
AStyle.Layout:= tlCenter;
Canvas.Pen.Color := Canvas.Font.Color;
Canvas.Line(0, 0, ClientWidth - 1, ClientHeight - 1);
Canvas.Line(0, ClientHeight - 1, ClientWidth - 1, 0);
Canvas.TextRect(GetViewerRect, 0, 0, FLastError, AStyle);
end;
procedure TViewerControl.Paint;
var
AText: String;
begin
if not IsFileOpen then
begin
DrawLastError;
Exit;
end;
if FShowCaret and FCaretVisible then
begin
FCaretPoint.X := -1;
FCaretVisible := not LCLIntf.HideCaret(Handle);
end;
Canvas.Font := Self.Font;
Canvas.Brush.Color := Self.Color;
{$IF DEFINED(LCLQT) and (LCL_FULLVERSION < 093100)}
Canvas.Brush.Style := bsSolid;
Canvas.FillRect(ClientRect);
{$ENDIF}
Canvas.Brush.Style := bsClear;
FTextHeight := Canvas.TextHeight('Wg') + FExtraLineSpacing;
if FViewerControlMode = vcmBook then
FTextWidth := ((ClientWidth - (Canvas.TextWidth('W') * FColCount)) div FColCount)
else begin
AText := StringOfChar('W', FMaxTextWidth);
FTextWidth := Canvas.TextFitInfo(AText, GetViewerRect.Width - FLeftMargin);
end;
FLineList.Clear;
case FViewerControlMode of
vcmBin : WriteBin;
vcmText: WriteText;
vcmWrap: WriteText;
vcmBook: WriteText;
vcmDec,vcmHex : WriteCustom;
end;
if FShowCaret and (FCaretPoint.X > -1) then
begin
LCLIntf.SetCaretPos(FCaretPoint.X, FCaretPoint.Y);
if not FCaretVisible then FCaretVisible:= LCLIntf.ShowCaret(Handle);
end;
end;
procedure TViewerControl.SetViewerMode(Value: TViewerControlMode);
begin
if not (csDesigning in ComponentState) then
begin
FLineList.Clear; // do not use cache from previous mode
FViewerControlMode := Value;
case FViewerControlMode of
vcmHex: FCustom := FHex;
vcmDec: FCustom := FDec;
else
FCustom := nil;
end;
if not IsFileOpen then
Exit;
// Take limits into account for selection.
FBlockBeg := FBlockBeg + (GetDataAdr - FMappedFile);
FBlockEnd := FBlockEnd + (GetDataAdr - FMappedFile);
FHPosition := 0;
FBOMLength := GetBomLength;
UpdateLimits;
// Take limits into account for selection.
FBlockBeg := FBlockBeg - (GetDataAdr - FMappedFile);
FBlockEnd := FBlockEnd - (GetDataAdr - FMappedFile);
UpdateSelection;
// Force recalculating position.
SetPosition(FPosition, True);
SetHPosition(FHPosition, True);
UpdateScrollbars;
Invalidate;
end
else
FViewerControlMode := Value;
end;
procedure TViewerControl.SetColCount(const AValue: Integer);
begin
if AValue > 0 then FColCount := AValue
else FColCount := 1;
end;
procedure TViewerControl.SetMaxTextWidth(const AValue: Integer);
begin
if AValue < 80 then
FMaxTextWidth := 80
else if AValue > 16384 then
FMaxTextWidth := 16384
else
FMaxTextWidth:= AValue;
end;
procedure TViewerControl.SetTabSpaces(const AValue: Integer);
begin
if AValue < 1 then
FTabSpaces := 1
else if AValue > 32 then
FTabSpaces := 32
else
FTabSpaces := AValue;
end;
function TViewerControl.ScrollPosition(var aPosition: PtrInt; iLines: Integer): Boolean;
var
i: Integer;
NewPos: PtrInt;
begin
Result := False;
NewPos := aPosition;
if iLines < 0 then
for i := 1 to -iLines do
NewPos := GetStartOfPrevLine(NewPos)
else
for i := 1 to iLines do
NewPos := GetStartOfNextLine(NewPos);
Result := aPosition <> NewPos;
aPosition := NewPos;
end;
function TViewerControl.Scroll(iLines: Integer): Boolean;
var
aPosition: PtrInt;
begin
if not IsFileOpen then
Exit(False);
aPosition := FPosition;
Result := ScrollPosition(aPosition, iLines);
if aPosition <> FPosition then
SetPosition(aPosition);
end;
function TViewerControl.HScroll(iSymbols: Integer): Boolean;
var
newPos: Integer;
begin
if not IsFileOpen then
Exit(False);
newPos := FHPosition + iSymbols;
if newPos < 0 then
newPos := 0
else if (newPos > FHLowEnd - FTextWidth) and (FHLowEnd - FTextWidth > 0) then
newPos := FHLowEnd - FTextWidth;
if newPos <> FHPosition then
SetHPosition(newPos);
Result:= True;
end;
function TViewerControl.GetText(const StartPos, Len: PtrInt; const Xoffset: Integer): string;
begin
SetString(Result, GetDataAdr + StartPos, Len);
Result := TransformText(ConvertToUTF8(Result), Xoffset);
end;
procedure TViewerControl.SetText(const AValue: String);
begin
UnMapFile;
FText:= AValue;
FileName:= EmptyStr;
FFileSize:= Length(FText);
FMappedFile:= Pointer(FText);
end;
function TViewerControl.GetViewerRect: TRect;
begin
Result:= GetClientRect;
if Assigned(FScrollBarHorz) and FScrollBarHorz.Visible then
Dec(Result.Bottom, FScrollBarHorz.Height);
if Assigned(FScrollBarVert) and FScrollBarVert.Visible then
Dec(Result.Right, FScrollBarVert.Width);
end;
procedure TViewerControl.WMSetFocus(var Message: TLMSetFocus);
begin
if FShowCaret then
begin
LCLIntf.CreateCaret(Handle, 0, 2, FTextHeight);
LCLIntf.ShowCaret(Handle);
FCaretVisible:= True;
end;
end;
procedure TViewerControl.WMKillFocus(var Message: TLMKillFocus);
begin
if FShowCaret then
begin
FCaretVisible:= False;
LCLIntf.DestroyCaret(Handle);
end;
end;
procedure TViewerControl.FontChanged(Sender: TObject);
begin
inherited FontChanged(Sender);
if HandleAllocated then
begin
FTextHeight := Canvas.TextHeight('Wg') + FExtraLineSpacing;
if FShowCaret then LCLIntf.CreateCaret(Handle, 0, 2, FTextHeight);
end;
end;
function TViewerControl.CalcTextLineLength(var iStartPos: PtrInt; const aLimit: Int64; out DataLength: PtrInt): Integer;
var
MaxLineLength: Boolean;
CharLenInBytes: Integer;
OldPos, LastSpacePos: PtrInt;
LastSpaceResult: Integer;
begin
Result := 0;
DataLength := 0;
LastSpacePos := -1;
MaxLineLength := True;
OldPos := iStartPos;
while MaxLineLength and (iStartPos < aLimit) do
begin
case GetNextCharAsAscii(iStartPos, CharLenInBytes) of
9: // tab
Inc(Result, FTabSpaces - Result mod FTabSpaces);
10: // stroka
begin
DataLength := iStartPos - OldPos;
iStartPos := iStartPos + CharLenInBytes;
Exit;
end;
13: // karetka
begin
DataLength := iStartPos - OldPos;
iStartPos := iStartPos + CharLenInBytes;
// Move after possible #10.
if (iStartPos < aLimit) and (GetNextCharAsAscii(iStartPos, CharLenInBytes) = 10) then
Inc(iStartPos, CharLenInBytes);
Exit;
end;
32, 33, 40, 41, 44, 45, 46, 47, 92, 58, 59, 63, 91, 93: //probel
begin
Inc(Result, 1);
LastSpacePos := iStartPos + CharLenInBytes;
LastSpaceResult := Result;
end;
else
Inc(Result, 1);
end;
if CharLenInBytes = 0 then // End of data or invalid character.
break;
iStartPos := iStartPos + CharLenInBytes;
DataLength := iStartPos - OldPos;
case FViewerControlMode of
vcmText: MaxLineLength := Result < FMaxTextWidth;
vcmWrap: MaxLineLength := Result < FTextWidth;
vcmBook: MaxLineLength := Canvas.TextWidth(GetText(OldPos, DataLength, 0)) < FTextWidth;
else
Exit;
end;
end;
if (not MaxLineLength) and (LastSpacePos <> -1) then
begin
iStartPos := LastSpacePos;
Result := LastSpaceResult;
DataLength := iStartPos - OldPos;
end;
end;
function TViewerControl.TransformText(const sText: String; const Xoffset: Integer): String;
var
c: AnsiChar;
i: Integer;
Dos: Boolean;
begin
Result := '';
Dos:= FEncoding in ViewerEncodingOem;
for i := 1 to Length(sText) do
begin
c := sText[i];
// Parse only ASCII chars.
case c of
#9:
Result := Result + StringOfChar(' ',
FTabSpaces - (UTF8Length(Result) + Xoffset) mod FTabSpaces);
else
begin
if c < ' ' then
begin
if Dos then
Result := Result + ASCII_TABLE[Ord(c)]
else
Result := Result + ' ';
end
else
Result := Result + c;
end;
end;
end;
end;
function TViewerControl.TransformBin(var aPosition: PtrInt; aLimit: PtrInt): String;
var
S: String;
C: AnsiChar;
P: PAnsiChar;
Len: Integer;
I, L: Integer;
SingleByte: Boolean;
begin
Result := EmptyStr;
if (APosition + cBinWidth) > aLimit then
Len:= aLimit - APosition
else begin
Len:= cBinWidth;
end;
SetString(S, PAnsiChar(GetDataAdr) + aPosition, Len);
SingleByte:= not (FEncoding in ViewerEncodingMultiByte);
if SingleByte then
begin
S:= ConvertToUTF8(S);
end;
L:= Length(S);
P:= PAnsiChar(S);
for I := 1 to L do
begin
C := P^;
if C < ' ' then
Result := Result + '.'
else if SingleByte then
Result := Result + C
else if C > #127 then
Result := Result + '.'
else begin
Result := Result + C;
end;
Inc(P);
end;
Inc(aPosition, Len);
end;
function TViewerControl.TransformHex(var aPosition: PtrInt; aLimit: PtrInt): AnsiString;
begin
Result:=TransformCustom(aPosition,aLimit);
end;
function TViewerControl.TransformCustom(var APosition: PtrInt; ALimit: PtrInt;
AWithAdditionalData: boolean): String;
var
sAscii: string = '';
sRez : string = '';
tPos : integer;
begin
tPos:=APosition;
sRez:=TransformCustomBlock(APosition,FCustom.ValuesPerLine,True,True,sAscii);
// Result := LineFormat(sRez, sStr, aStartOffset) else
if AWithAdditionalData then
begin
sRez := Format('%s: %s', [IntToHex(tPos, FCustom.MaxAddrDigits), sRez]);
if Length(sRez) < FCustom.ValuesPerLine * (FCustom.SpaceCount+FCustom.MaxValueDigits) then
sRez := sRez + StringOfChar(' ', FCustom.ValuesPerLine * (FCustom.SpaceCount+FCustom.MaxValueDigits) - Length(sRez));
sRez := sRez + ' ';
sRez := sRez + sAscii;
end;
Result:=sRez;
end;
function TViewerControl.TransformCustomBlock(var APosition: PtrInt;
DataLength: Integer; ASeparatorsOn, AAlignData: Boolean; out AChars: String): String;
var
S: String;
C: AnsiChar;
P: PAnsiChar;
Len: Integer;
I, L: Integer;
sEmpty: String;
iSep: Integer = 1;
SingleByte: Boolean;
begin
Result:= EmptyStr;
if (APosition + DataLength) > FHighLimit then
Len:= FHighLimit - APosition
else begin
Len:= DataLength;
end;
SetString(S, PAnsiChar(GetDataAdr) + aPosition, Len);
SingleByte:= not (FEncoding in ViewerEncodingMultiByte);
if SingleByte then
begin
S:= ConvertToUTF8(S);
end;
L:= Length(S);
P:= PAnsiChar(S);
AChars:= EmptyStr;
for I := 1 to L do
begin
C := P^;
if C < ' ' then
AChars := AChars + '.'
else if SingleByte then
AChars := AChars + C
else if C > #127 then
AChars := AChars + '.'
else begin
AChars := AChars + C;
end;
Inc(P);
end;
P:= PAnsiChar(GetDataAdr);
for I := 0 to Len - 1 do
begin
C := P[aPosition];
Result += FCustom.ChrToValueProc(C, FCustom.MaxValueDigits);
if (iSep = FCustom.CountSeperate) and ASeparatorsOn and
(I < (FCustom.ValuesPerLine - 1))then
begin
iSep := 0;
Result += FCustom.SeparatorChar;
end else
begin
Result += FCustom.SeparatorSpace;
end;
Inc(aPosition);
Inc(iSep);
end;
if AAlignData then
begin
sEmpty := StringOfChar(#32, FCustom.MaxValueDigits);
while (I < FCustom.ValuesPerLine - 1) do
begin
Result += sEmpty + FCustom.SeparatorSpace;
Inc(I);
end;
end;
end;
function TViewerControl.DecToValueProc(AChar:AnsiChar;AMaxDigitsCount:integer):AnsiString;
begin
Result:= IntToStr(Ord(AChar));
while Length(Result) < AMaxDigitsCount do
Result:= '0' + Result;
end;
function TViewerControl.HexToValueProc(AChar:AnsiChar;AMaxDigitsCount:integer):AnsiString;
begin
Result:=IntToHex(Ord(AChar), AMaxDigitsCount);
while length(Result)<AMaxDigitsCount do
Result:=' '+Result;
end;
function TViewerControl.GetStartOfLine(aPosition: PtrInt): PtrInt;
function GetStartOfLineText: PtrInt;
var
tmpPos, LineStartPos: PtrInt;
DataLength: PtrInt;
prevChar: Cardinal;
MaxLineLength: Boolean;
CharLenInBytes: Integer;
begin
prevChar := GetPrevCharAsAscii(aPosition, CharLenInBytes);
if CharLenInBytes = 0 then
Exit(aPosition);
// Check if this already is not a start of line (if previous char is #10).
if prevChar = 10 then
Exit(aPosition);
tmpPos := aPosition - CharLenInBytes;
if tmpPos <= FLowLimit then
Exit(FLowLimit);
// Check if we're not in the middle of line ending
// (previous char is #13, current char is #10).
if (prevChar = 13) and
(GetNextCharAsAscii(aPosition, CharLenInBytes) = 10) then
begin
prevChar := GetPrevCharAsAscii(tmpPos, CharLenInBytes);
if CharLenInBytes = 0 then
Exit(aPosition);
Dec(tmpPos, CharLenInBytes);
end;
if tmpPos <= FLowLimit then
Exit(FLowLimit);
DataLength:= 0;
// Search for real start of line.
while (not (prevChar in [10, 13])) and (tmpPos > FLowLimit) do
begin
prevChar := GetPrevCharAsAscii(tmpPos, CharLenInBytes);
if CharLenInBytes = 0 then
Break;
Dec(tmpPos, CharLenInBytes);
case prevChar of
9:
Inc(DataLength, FTabSpaces - DataLength mod FTabSpaces);
else
Inc(DataLength, 1);
end;
case FViewerControlMode of
vcmText: MaxLineLength := DataLength < FMaxTextWidth;
vcmWrap: MaxLineLength := DataLength < FTextWidth;
end;
if not MaxLineLength then Exit(tmpPos);
end;
// Previous end of line not found and there are no more data to check.
if (not (prevChar in [10, 13])) and (tmpPos <= FLowLimit) then
Exit(FLowLimit);
// Move forward to first non-line ending character.
Inc(tmpPos, CharLenInBytes);
// Search for start of real line or wrapped line.
while True do
begin
LineStartPos := tmpPos;
CalcTextLineLength(tmpPos, FHighLimit, DataLength);
if tmpPos = aPosition then
begin
if aPosition < FHighLimit then
Exit(aPosition) // aPosition is already at start of a line
else
Exit(LineStartPos); // aPosition points to end of file so return start of this line
end
else if tmpPos > aPosition then
Exit(LineStartPos); // Found start of line
end;
end;
function GetStartOfLineFixed(aFixedWidth: Integer): PtrInt;
begin
Result := aPosition - (aPosition mod aFixedWidth);
end;
var
i: Integer;
begin
if aPosition <= FLowLimit then
Exit(FLowLimit)
else if aPosition >= FHighLimit then
aPosition := FHighLimit; // search from the end of the file
// Speedup for currently displayed positions.
if (FLineList.Count > 0) and
(aPosition >= FLineList.Items[0]) and
(aPosition <= FLineList.Items[FLineList.Count - 1]) then
begin
for i := FLineList.Count - 1 downto 0 do
if FLineList.Items[i] <= aPosition then
Exit(FLineList.Items[i]);
end;
case FViewerControlMode of
vcmBin:
Result := GetStartOfLineFixed(cBinWidth);
vcmHex, vcmDec:
Result := GetStartOfLineFixed(FCustom.ValuesPerLine);
vcmText, vcmWrap, vcmBook:
Result := GetStartOfLineText;
else
Result := aPosition;
end;
end;
function TViewerControl.GetEndOfLine(aPosition: PtrInt): PtrInt;
function GetEndOfLineText: PtrInt;
var
tmpPos: PtrInt;
DataLength: PtrInt;
begin
Result := GetStartOfLine(aPosition);
tmpPos := Result;
CalcTextLineLength(tmpPos, FHighLimit, DataLength);
Result := Result + DataLength;
if Result < aPosition then
Result := aPosition;
end;
function GetEndOfLineFixed(aFixedWidth: Integer): PtrInt;
begin
Result := aPosition - (aPosition mod aFixedWidth) + aFixedWidth;
end;
begin
case FViewerControlMode of
vcmBin:
Result := GetEndOfLineFixed(cBinWidth);
vcmHex,vcmDec:
Result := GetEndOfLineFixed(FCustom.ValuesPerLine);
vcmText, vcmWrap, vcmBook:
Result := GetEndOfLineText;
else
Result := aPosition;
end;
end;
function TViewerControl.GetStartOfPrevLine(aPosition: PtrInt): PtrInt;
function GetPrevLineText: PtrInt;
var
tmpPos, LineStartPos: PtrInt;
DataLength: PtrInt;
prevChar: Cardinal;
MaxLineLength: Boolean;
CharLenInBytes: Integer;
begin
prevChar := GetPrevCharAsAscii(aPosition, CharLenInBytes);
if CharLenInBytes = 0 then
Exit(aPosition);
tmpPos := aPosition - CharLenInBytes; // start search from previous character
if tmpPos <= FLowLimit then
Exit(FLowLimit);
// Check if we're not in the middle of line ending
// (previous char is #13, current char is #10).
if (prevChar = 13) and
(GetNextCharAsAscii(aPosition, CharLenInBytes) = 10) then
begin
prevChar := GetPrevCharAsAscii(tmpPos, CharLenInBytes);
if CharLenInBytes = 0 then
Exit(aPosition);
Dec(tmpPos, CharLenInBytes);
end
else
begin
// Bypass possible end of previous line.
if prevChar = 10 then
begin
prevChar := GetPrevCharAsAscii(tmpPos, CharLenInBytes);
if CharLenInBytes = 0 then
Exit(aPosition);
Dec(tmpPos, CharLenInBytes);
end;
if prevChar = 13 then
begin
prevChar := GetPrevCharAsAscii(tmpPos, CharLenInBytes);
if CharLenInBytes = 0 then
Exit(aPosition);
Dec(tmpPos, CharLenInBytes);
end;
end;
if tmpPos <= FLowLimit then
Exit(FLowLimit);
DataLength:= 0;
// Search for real start of line.
while (not (prevChar in [10, 13])) and (tmpPos > FLowLimit) do
begin
prevChar := GetPrevCharAsAscii(tmpPos, CharLenInBytes);
if CharLenInBytes = 0 then
Break;
Dec(tmpPos, CharLenInBytes);
case prevChar of
9:
Inc(DataLength, FTabSpaces - DataLength mod FTabSpaces);
else
Inc(DataLength, 1);
end;
case FViewerControlMode of
vcmText: MaxLineLength := DataLength < FMaxTextWidth;
vcmWrap: MaxLineLength := DataLength < FTextWidth;
end;
if not MaxLineLength then Exit(tmpPos);
end;
// Move forward to first non-line ending character.
Inc(tmpPos, CharLenInBytes);
// Search for start of real line or wrapped line.
while True do
begin
LineStartPos := tmpPos;
CalcTextLineLength(tmpPos, aPosition, DataLength);
if tmpPos >= aPosition then
Exit(LineStartPos); // Found start of line
end;
end;
function GetPrevLineFixed(aFixedWidth: Integer): PtrInt;
begin
Result := aPosition - (aPosition mod aFixedWidth);
if Result >= aFixedWidth then
Result := Result - aFixedWidth;
end;
var
i: Integer;
begin
if aPosition <= FLowLimit then
Exit(FLowLimit)
else if aPosition >= FHighLimit then
aPosition := FHighLimit; // search from the end of the file
// Speedup for currently displayed positions.
if (FLineList.Count > 0) and
(aPosition >= FLineList.Items[0]) and
(aPosition <= FLineList.Items[FLineList.Count - 1]) then
begin
for i := FLineList.Count - 1 downto 0 do
if FLineList.Items[i] < aPosition then
Exit(FLineList.Items[i]);
end;
case FViewerControlMode of
vcmBin:
Result := GetPrevLineFixed(cBinWidth);
vcmHex,vcmDec:
Result := GetPrevLineFixed(FCustom.ValuesPerLine);
vcmText, vcmWrap, vcmBook:
Result := GetPrevLineText;
else
Result := aPosition;
end;
end;
function TViewerControl.GetStartOfNextLine(aPosition: PtrInt): PtrInt;
function GetNextLineText: PtrInt;
var
tmpPos: PtrInt;
DataLength: PtrInt;
prevChar: Cardinal;
CharLenInBytes: Integer;
begin
tmpPos := aPosition;
// This might not be a real start of line (it may be start of wrapped line).
// Search for start of line.
while (tmpPos > FLowLimit) do
begin
prevChar := GetPrevCharAsAscii(tmpPos, CharLenInBytes);
if CharLenInBytes = 0 then
Break;
if (prevChar in [10, 13]) then
Break
else
Dec(tmpPos, CharLenInBytes);
end;
// Now we know we are at the start of a line, search the start of next line.
while True do
begin
CalcTextLineLength(tmpPos, FHighLimit, DataLength);
if tmpPos >= aPosition then
Exit(tmpPos); // Found start of line
end;
end;
function GetNextLineFixed(aFixedWidth: Integer): PtrInt;
begin
Result := aPosition - (aPosition mod aFixedWidth);
if Result + aFixedWidth < FHighLimit then
Result := Result + aFixedWidth;
end;
var
i: Integer;
begin
if aPosition < FLowLimit then
aPosition := FLowLimit // search from the start of the file
else if aPosition >= FHighLimit then
aPosition := FHighLimit; // search from the end of the file
// Speedup for currently displayed positions.
if (FLineList.Count > 0) and
(aPosition >= FLineList.Items[0]) and
(aPosition <= FLineList.Items[FLineList.Count - 1]) then
begin
for i := 0 to FLineList.Count - 1 do
if FLineList.Items[i] > aPosition then
Exit(FLineList.Items[i]);
end;
case FViewerControlMode of
vcmBin:
Result := GetNextLineFixed(cBinWidth);
vcmHex,vcmDec:
Result := GetNextLineFixed(FCustom.ValuesPerLine);
vcmText, vcmWrap, vcmBook:
Result := GetNextLineText;
else
Result := aPosition;
end;
end;
procedure TViewerControl.PageUp;
var
H: Integer;
begin
H := GetClientHeightInLines * FColCount - 1;
if H <= 0 then
H := 1;
Scroll(-H);
end;
procedure TViewerControl.HPageUp;
var
H: Integer;
begin
H := FHPosition - FTextWidth;
if H <= 0 then
H := FHPosition else H:= FTextWidth;
HScroll(-H);
end;
procedure TViewerControl.PageDown;
var
H: Integer;
begin
H := GetClientHeightInLines * FColCount - 1;
if H <= 0 then
H := 1;
Scroll(H);
end;
procedure TViewerControl.HPageDown;
var
H: Integer;
begin
H := FHLowEnd - FHPosition;
if H > FTextWidth then H := FTextWidth ;
HScroll(H);
end;
procedure TViewerControl.GoHome;
begin
Position := FLowLimit;
end;
procedure TViewerControl.GoEnd;
begin
Position := FHighLimit;
end;
procedure TViewerControl.HGoHome;
begin
HScroll (-FHPosition);
end;
procedure TViewerControl.HGoEnd;
begin
HScroll (FHLowEnd-FHPosition);
end;
procedure TViewerControl.CaretGoHome;
begin
HScroll (-FHPosition);
CaretPos := GetStartOfLine(CaretPos);
end;
procedure TViewerControl.CaretGoEnd;
begin
if FViewerControlMode in [vcmBin, vcmHex, vcmDec] then
CaretPos := GetEndOfLine(CaretPos) - 1
else begin
CaretPos := GetEndOfLine(CaretPos);
end;
if FViewerControlMode = vcmText then
begin
if not IsVisible(CaretPos) then
begin
if (FVisibleOffset < FHPosition) or
(FVisibleOffset > FHPosition + FTextWidth) then
begin
SetHPosition(FVisibleOffset);
HScroll(-1);
end;
end;
end;
end;
procedure TViewerControl.SetFileName(const sFileName: String);
begin
if not (csDesigning in ComponentState) then
begin
UnMapFile;
if sFileName <> '' then
begin
if MapFile(sFileName) then
begin
FFileName := sFileName;
// Detect encoding if needed.
if FEncoding = veAutoDetect then
FEncoding := DetectEncoding;
ReReadFile;
CaretPos := FLowLimit;
end;
end;
end
else
FFileName := sFileName;
end;
function TViewerControl.MapFile(const sFileName: String): Boolean;
function ReadFile: Boolean; inline;
begin
FMappedFile := GetMem(FFileSize);
Result := (FileRead(FFileHandle, FMappedFile^, FFileSize) = FFileSize);
if not Result then
begin
FLastError := mbSysErrorMessage;
FreeMemAndNil(FMappedFile);
end;
FileClose(FFileHandle);
FFileHandle := 0;
end;
{$IFDEF LINUX}
var
Sbfs: TStatFS;
{$ENDIF}
begin
Result := False;
FLastError := EmptyStr;
if Assigned(FMappedFile) then
UnMapFile; // if needed
if Assigned(FOnFileOpen) then
FFileHandle := FOnFileOpen(sFileName, fmOpenRead or fmShareDenyNone)
else begin
FFileHandle := mbFileOpen(sFileName, fmOpenRead or fmShareDenyNone);
end;
if FFileHandle = feInvalidHandle then
begin
FLastError := mbSysErrorMessage;
FFileHandle := 0;
Exit;
end;
FFileSize := FileGetSize(FFileHandle);
if (FFileSize < 0) then
begin
FLastError := mbSysErrorMessage;
FileClose(FFileHandle);
FFileHandle := 0;
Exit;
end;
{$IFDEF LINUX}
if (fpFStatFS(FFileHandle, @Sbfs) = 0) then
begin
// Special case for PROC_FS and SYS_FS
if (sbfs.fstype = PROC_SUPER_MAGIC) or (sbfs.fstype = SYSFS_MAGIC) then
begin
FMappedFile := GetMem(MaxMemSize - 1);
FFileSize := FileRead(FFileHandle, FMappedFile^, MaxMemSize - 1);
Result := (FFileSize > 0);
FileClose(FFileHandle);
FFileHandle := 0;
Exit;
end;
end;
{$ENDIF}
if (FFileSize < MaxMemSize) then
begin
Result := ReadFile;
Exit;
end;
{$IFDEF MSWINDOWS}
FMappingHandle := CreateFileMapping(FFileHandle, nil, PAGE_READONLY, 0, 0, nil);
if FMappingHandle = 0 then
begin
FLastError := mbSysErrorMessage;
FMappedFile := nil;
UnMapFile;
end
else begin
FMappedFile := MapViewOfFile(FMappingHandle, FILE_MAP_READ, 0, 0, 0);
if (FMappedFile = nil) then
begin
FLastError := mbSysErrorMessage;
UnMapFile;
end;
end;
{$ELSE}
FMappedFile := fpmmap(nil, FFileSize, PROT_READ, MAP_PRIVATE{SHARED}, FFileHandle, 0);
if FMappedFile = MAP_FAILED then
begin
FLastError := mbSysErrorMessage;
FMappedFile:= nil;
FileClose(FFileHandle);
FFileHandle := 0;
Exit;
end;
{$ENDIF}
Result := Assigned(FMappedFile);
end;
procedure TViewerControl.UnMapFile;
begin
if FMappedFile = Pointer(FText) then
begin
FMappedFile:= nil;
FText:= EmptyStr;
end;
if (FFileSize < MaxMemSize) then
begin
if Assigned(FMappedFile) then
begin
FreeMem(FMappedFile);
FMappedFile := nil;
end;
end;
{$IFDEF MSWINDOWS}
if Assigned(FMappedFile) then
begin
UnmapViewOfFile(FMappedFile);
FMappedFile := nil;
end;
if FMappingHandle <> 0 then
begin
CloseHandle(FMappingHandle);
FMappingHandle := 0;
end;
{$ELSE}
if Assigned(FMappedFile) then
begin
if fpmunmap(FMappedFile, FFileSize) = -1 then
DebugLn('Error unmapping file: ', SysErrorMessage(fpgeterrno));
FMappedFile := nil;
end;
{$ENDIF}
if FFileHandle <> 0 then
begin
FileClose(FFileHandle);
FFileHandle := 0;
end;
FFileName := '';
FFileSize := 0;
Position := 0;
FLowLimit := 0;
FHighLimit := 0;
FBOMLength := 0;
FBlockBeg := 0;
FBlockEnd := 0;
end;
procedure TViewerControl.WriteText;
var
yIndex, xIndex, w, i: Integer;
LineStart, iPos: PtrInt;
CharLenInBytes: Integer;
DataLength: PtrInt;
sText: String;
procedure DrawCaret(X, Y: Integer; LinePos: PtrInt);
begin
if FShowCaret and (FCaretPos = LinePos) then
begin
FCaretPoint.X:= X;
FCaretPoint.Y:= Y;
end;
end;
begin
iPos := FPosition;
if Mode = vcmBook then
w := Width div FColCount
else begin
w := 0;
end;
for xIndex := 0 to FColCount-1 do
begin
for yIndex := 0 to GetClientHeightInLines(False) - 1 do
begin
if iPos > FHighLimit then
Break;
if iPos = FHighLimit then
begin
if GetPrevCharAsAscii(iPos, CharLenInBytes) = 10 then
begin
DrawCaret(0, yIndex * FTextHeight, iPos);
end;
Break;
end;
AddLineOffset(iPos);
LineStart := iPos;
i := CalcTextLineLength(iPos, FHighLimit, DataLength);
if i > FHLowEnd then FHLowEnd:= i;
if DataLength = 0 then
DrawCaret(0, yIndex * FTextHeight, LineStart)
else begin
if (Mode = vcmText) and (FHPosition > 0) then
begin
for i:= 1 to FHPosition do
begin
GetNextCharAsAscii(LineStart, CharLenInBytes);
DataLength -= CharLenInBytes;
LineStart += CharLenInBytes;
end;
if (DataLength <= 0) then Continue;
end;
sText := GetText(LineStart, DataLength, 0);
OutText(FLeftMargin + xIndex * w, yIndex * FTextHeight, sText, LineStart, DataLength);
end;
end;
end;
end;
procedure TViewerControl.WriteCustom;
// this method render visible page of text
var
yIndex: Integer;
iPos, LineStart: PtrInt;
s: string;
begin
iPos := FPosition;
for yIndex := 0 to GetClientHeightInLines(False) - 1 do
begin
if iPos >= FHighLimit then
Break;
LineStart := iPos;
AddLineOffset(iPos);
s := TransformCustom(iPos, FHighLimit); // get line text for render
if s <> '' then
OutCustom(FLeftMargin, yIndex * FTextHeight, s, LineStart, iPos - LineStart); // render line to canvas
end;
end;
procedure TViewerControl.WriteBin;
var
yIndex: Integer;
iPos, LineStart: PtrInt;
s: string;
begin
iPos := FPosition;
for yIndex := 0 to GetClientHeightInLines(False) - 1 do
begin
if iPos >= FHighLimit then
Break;
LineStart := iPos;
AddLineOffset(iPos);
s := TransformBin(iPos, FHighLimit);
if s <> '' then
OutBin(FLeftMargin, yIndex * FTextHeight, s, LineStart, iPos - LineStart);
end;
end;
function TViewerControl.GetDataAdr: Pointer;
begin
case FViewerControlMode of
vcmText, vcmWrap, vcmBook:
Result := FMappedFile + FBOMLength;
else
Result := FMappedFile;
end;
end;
procedure TViewerControl.SetPosition(Value: PtrInt);
begin
SetPosition(Value, False);
end;
procedure TViewerControl.SetHPosition(Value: Integer);
begin
SetHPosition(Value, False);
end;
procedure TViewerControl.SetHPosition(Value: Integer; Force: Boolean);
begin
if not IsFileOpen then
Exit;
FHPosition := Value;
// Set new scroll position.
if (FHPosition > 0) and (FHLowEnd - FTextWidth > 0) then
FHScrollBarPosition := FHPosition * 100 div (FHLowEnd - FTextWidth)
else
FHScrollBarPosition := 0;
// Update scrollbar position.
if FUpdateScrollBarPos then
begin
if FScrollBarHorz.Position <> FHScrollBarPosition then
begin
// Workaround for bug: http://bugs.freepascal.org/view.php?id=23815
{$IF DEFINED(LCLQT) and (LCL_FULLVERSION < 1010000)}
FScrollBarHorz.OnScroll := nil;
FScrollBarHorz.Position := FHScrollBarPosition;
Application.ProcessMessages; // Skip message
FScrollBarHorz.OnScroll := @ScrollBarHorzScroll;
{$ELSE}
FScrollBarHorz.Position := FHScrollBarPosition;
{$ENDIF}
end;
end;
// else the scrollbar position will be updated in ScrollBarVertScroll
Invalidate;
end;
procedure TViewerControl.SetPosition(Value: PtrInt; Force: Boolean);
var
LinesTooMany: Integer;
LastLineReached: Boolean;
begin
if not IsFileOpen then
Exit;
// Double byte text can have only even position
if (Encoding in ViewerEncodingDoubleByte) and Odd(Value) then
begin
Value := Value - 1;
end;
// Speedup if total nr of lines is less then nr of lines that can be displayed.
if (FPosition = FLowLimit) and // only if already at the top
(FLineList.Count > 0) and (FLineList.Count < GetClientHeightInLines)
then
Value := FLowLimit
else
// Boundary checks are done in GetStartOfLine.
Value := GetStartOfLine(Value);
if (Value <> FPosition) or Force then
begin
// Don't allow empty lines at the bottom of the control.
LinesTooMany := GetClientHeightInLines - GetLinesTillEnd(Value, LastLineReached);
if LinesTooMany > 0 then
begin
// scroll back upwards
ScrollPosition(Value, -LinesTooMany);
end;
FPosition := Value;
if Assigned(FOnPositionChanged) then
FOnPositionChanged(Self);
Invalidate;
// Set new scroll position.
if LastLineReached and (Value > 0) then
FScrollBarPosition := 100
else
FScrollBarPosition := Percent;
end;
// Update scrollbar position.
if FUpdateScrollBarPos then
begin
if FScrollBarVert.Position <> FScrollBarPosition then
begin
// Workaround for bug: http://bugs.freepascal.org/view.php?id=23815
{$IF DEFINED(LCLQT) and (LCL_FULLVERSION < 1010000)}
FScrollBarVert.OnScroll := nil;
FScrollBarVert.Position := FScrollBarPosition;
Application.ProcessMessages; // Skip message
FScrollBarVert.OnScroll := @ScrollBarVertScroll;
{$ELSE}
FScrollBarVert.Position := FScrollBarPosition;
{$ENDIF}
end;
end;
// else the scrollbar position will be updated in ScrollBarVertScroll
end;
procedure TViewerControl.SetEncoding(AEncoding: TViewerEncoding);
begin
if not (csDesigning in ComponentState) then
begin
if AEncoding = veAutoDetect then
FEncoding := DetectEncoding
else
FEncoding := AEncoding;
ReReadFile;
end
else
FEncoding := AEncoding;
end;
function TViewerControl.GetEncodingName: string;
begin
Result := ViewerEncodingsNames[FEncoding];
end;
procedure TViewerControl.SetEncodingName(AEncodingName: string);
var
i: TViewerEncoding;
begin
for i := Low(TViewerEncoding) to High(TViewerEncoding) do
if NormalizeEncoding(ViewerEncodingsNames[i]) = NormalizeEncoding(AEncodingName) then
begin
SetEncoding(i);
break;
end;
end;
function TViewerControl.GetClientHeightInLines(Whole: Boolean): Integer;
begin
if FTextHeight > 0 then
begin
if Whole then
Result := GetViewerRect.Height div FTextHeight
else
Result := Ceil(GetViewerRect.Height / FTextHeight);
end
else
Result := 0;
end;
function TViewerControl.GetLinesTillEnd(FromPosition: PtrInt;
out LastLineReached: Boolean): Integer;
var
iPos: PtrInt;
yIndex: Integer;
DataLength: PtrInt;
CharLenInBytes: Integer;
begin
Result := 0;
iPos := FromPosition;
for yIndex := 0 to GetClientHeightInLines - 1 do
begin
if iPos >= FHighLimit then
Break;
Inc(Result, 1);
case Mode of
vcmBin:
iPos := iPos + cBinWidth;
vcmHex,vcmDec:
iPos := iPos + FCustom.ValuesPerLine;
vcmText, vcmWrap, vcmBook:
CalcTextLineLength(iPos, FHighLimit, DataLength);
end;
end;
LastLineReached := (iPos >= FHighLimit);
if LastLineReached and (FViewerControlMode in [vcmText, vcmWrap, vcmBook]) then
begin
if (GetPrevCharAsAscii(FHighLimit, CharLenInBytes) = 10) then
Inc(Result);
end;
end;
procedure TViewerControl.SetShowCaret(AValue: Boolean);
begin
if FShowCaret <> AValue then
begin
FShowCaret:= AValue;
if HandleAllocated then
begin
if FShowCaret then
begin
LCLIntf.CreateCaret(Handle, 0, 2, FTextHeight);
LCLIntf.ShowCaret(Handle);
FCaretVisible:= True;
Invalidate;
end
else begin
FCaretVisible:= False;
LCLIntf.HideCaret(Handle);
LCLIntf.DestroyCaret(Handle);
end;
end;
end;
end;
procedure TViewerControl.SetCaretPos(AValue: PtrInt);
begin
if FCaretPos <> AValue then
begin
FCaretPos := AValue;
if FShowCaret then Invalidate;
end;
end;
function TViewerControl.GetPercent: Integer;
begin
if FHighLimit - FLowLimit > 0 then
Result := (Int64(FPosition - FLowLimit) * 100) div Int64(FHighLimit - FLowLimit)
else
Result := 0;
end;
procedure TViewerControl.SetPercent(const AValue: Integer);
begin
if FHighLimit - FLowLimit > 0 then
Position := Int64(AValue) * (Int64(FHighLimit - FLowLimit) div 100) + FLowLimit
else
Position := 0;
end;
procedure TViewerControl.SetBlockBegin(const AValue: PtrInt);
begin
if (AValue >= FLowLimit) and (AValue < FHighLimit) then
begin
if FBlockEnd < AValue then
FBlockEnd := AValue;
FBlockBeg := AValue;
Invalidate;
end;
end;
procedure TViewerControl.SetBlockEnd(const AValue: PtrInt);
begin
if (AValue >= FLowLimit) and (AValue < FHighLimit) then
begin
if FBlockBeg > AValue then
FBlockBeg := AValue;
FBlockEnd := AValue;
Invalidate;
end;
end;
procedure TViewerControl.OutText(x, y: Integer; const sText: String;
StartPos: PtrInt; DataLength: Integer);
var
pBegLine, pEndLine: PtrInt;
iBegDrawIndex, iEndDrawIndex: PtrInt;
begin
pBegLine := StartPos;
pEndLine := pBegLine + DataLength;
Canvas.Font.Color := Font.Color;
if FShowCaret and (FCaretPos >= pBegLine) and (FCaretPos <= pEndLine) then
begin
FCaretPoint.Y:= Y;
FCaretPoint.X:= X + Canvas.TextWidth(GetText(StartPos, FCaretPos - pBegLine, 0));
end;
// Out of selection, draw normal
if ((FBlockEnd - FBlockBeg) = 0) or ((FBlockBeg < pBegLine) and (FBlockEnd < pBegLine)) or // before
((FBlockBeg > pEndLine) and (FBlockEnd > pEndLine)) then // after
begin
Canvas.TextOut(x, y, sText);
Exit;
end;
// Get selection start
if (FBlockBeg <= pBegLine) then
iBegDrawIndex := pBegLine
else
iBegDrawIndex := FBlockBeg;
// Get selection end
if (FBlockEnd < pEndLine) then
iEndDrawIndex := FBlockEnd
else
iEndDrawIndex := pEndLine;
// Text after selection.
if pEndLine - iEndDrawIndex > 0 then
Canvas.TextOut(x, y, sText);
// Text before selection + selected text
Canvas.Brush.Color := clHighlight;
Canvas.Font.Color := clHighlightText;
Canvas.TextOut(X, Y, GetText(StartPos, iEndDrawIndex - pBegLine, 0));
// Restore previous canvas settings
Canvas.Brush.Color := Color;
Canvas.Font.Color := Font.Color;
// Text before selection
if iBegDrawIndex - pBegLine > 0 then
Canvas.TextOut(X, Y, GetText(StartPos, iBegDrawIndex - pBegLine, 0));
end;
procedure TViewerControl.OutCustom(x, y: Integer; const sText: String;
StartPos: PtrInt; DataLength: Integer);
var
sTmpText: String;
pBegLine, pEndLine: PtrInt;
iBegDrawIndex, iEndDrawIndex: PtrInt;
begin
pBegLine := StartPos;
pEndLine := pBegLine + DataLength;
Canvas.Font.Color := Font.Color;
if FShowCaret and (FCaretPos >= pBegLine) and (FCaretPos <= pEndLine) then
begin
FCaretPoint.Y:= Y;
FCaretPoint.X:= X + Canvas.TextWidth(Copy(sText, 1, FCustom.StartAscii + (FCaretPos - pBegLine)));
end;
// Out of selection, draw normal
if ((FBlockEnd - FBlockBeg) = 0) or ((FBlockBeg < pBegLine) and (FBlockEnd <= pBegLine)) or // before
((FBlockBeg > pEndLine) and (FBlockEnd > pEndLine)) then // after
begin
// Offset + hex part + space between hex and ascii
sTmpText:= Copy(sText, 1, FCustom.EndOfs) + ' ';
Canvas.TextOut(x, y, sTmpText);
x := x + Canvas.TextWidth(sTmpText);
// Ascii part
sTmpText := Copy(sText, 1 + FCustom.StartAscii, MaxInt);
Canvas.TextOut(x, y, sTmpText);
Exit;
end;
// Get selection start
if (FBlockBeg <= pBegLine) then
iBegDrawIndex := pBegLine
else begin
iBegDrawIndex := FBlockBeg;
end;
// Get selection end
if (FBlockEnd < pEndLine) then
iEndDrawIndex := FBlockEnd
else begin
iEndDrawIndex := pEndLine;
end;
// Text after selection (hex part)
if pEndLine - iEndDrawIndex > 0 then
begin
sTmpText := Copy(sText, 1, FCustom.StartOfs + (pEndLine - pBegLine) * (FCustom.MaxValueDigits + FCustom.SpaceCount));
Canvas.TextOut(x, y, sTmpText);
end;
// Text before selection + selected text (hex part)
sTmpText := Copy(sText, 1, FCustom.StartOfs + (iEndDrawIndex - pBegLine) * (FCustom.MaxValueDigits + FCustom.SpaceCount) - 1);
Canvas.Brush.Color := clHighlight;
Canvas.Font.Color := clHighlightText;
Canvas.TextOut(x, y, sTmpText);
// Restore previous canvas settings
Canvas.Brush.Color := Color;
Canvas.Font.Color := Font.Color;
// Offset + text before selection (hex part)
sTmpText := Copy(sText, 1, FCustom.StartOfs + (iBegDrawIndex - pBegLine) * (FCustom.MaxValueDigits + FCustom.SpaceCount));
Canvas.TextOut(x, y, sTmpText);
// Offset + hex part + space between hex and ascii
sTmpText:= Copy(sText, 1, FCustom.EndOfs) + ' ';
x := x + Canvas.TextWidth(sTmpText);
// Text after selection (ascii part)
if pEndLine - iEndDrawIndex > 0 then
begin
sTmpText := Copy(sText, FCustom.StartAscii + 1, MaxInt);
Canvas.TextOut(x, y, sTmpText);
end;
// Text before selection + selected text (ascii part)
if (iEndDrawIndex - pBegLine) = FCustom.ValuesPerLine then
sTmpText := Copy(sText, 1 + FCustom.StartAscii, MaxInt)
else begin
sTmpText := UTF8Copy(sText, 1 + FCustom.StartAscii, iEndDrawIndex - pBegLine);
end;
Canvas.Brush.Color := clHighlight;
Canvas.Font.Color := clHighlightText;
Canvas.TextOut(x, y, sTmpText);
// Restore background color
Canvas.Brush.Color := Color;
Canvas.Font.Color := Font.Color;
// Text before selection (ascii part)
if iBegDrawIndex - pBegLine > 0 then
begin
sTmpText := UTF8Copy(sText, 1 + FCustom.StartAscii, iBegDrawIndex - pBegLine);
Canvas.TextOut(x, y, sTmpText);
end;
end;
procedure TViewerControl.OutBin(x, y: Integer; const sText: String;
StartPos: PtrInt; DataLength: Integer);
var
pBegLine, pEndLine: PtrInt;
iBegDrawIndex, iEndDrawIndex: PtrInt;
begin
pBegLine := StartPos;
pEndLine := pBegLine + DataLength;
Canvas.Font.Color := Font.Color;
if FShowCaret and (FCaretPos >= pBegLine) and (FCaretPos <= pEndLine) then
begin
FCaretPoint.Y:= Y;
FCaretPoint.X:= X + Canvas.TextWidth(Copy(sText, 1, FCaretPos - pBegLine));
end;
// Out of selection, draw normal
if ((FBlockEnd - FBlockBeg) = 0) or ((FBlockBeg < pBegLine) and (FBlockEnd < pBegLine)) or // before
((FBlockBeg > pEndLine) and (FBlockEnd > pEndLine)) then //after
begin
Canvas.TextOut(x, y, sText);
Exit;
end;
// Get selection start/end.
if (FBlockBeg <= pBegLine) then
iBegDrawIndex := pBegLine
else begin
iBegDrawIndex := FBlockBeg;
end;
if (FBlockEnd < pEndLine) then
iEndDrawIndex := FBlockEnd
else begin
iEndDrawIndex := pEndLine;
end;
// Text after selection.
if pEndLine - iEndDrawIndex > 0 then
Canvas.TextOut(x, y, sText);
// Text before selection + selected text
Canvas.Brush.Color := clHighlight;
Canvas.Font.Color := clHighlightText;
// Whole line selected
if (iEndDrawIndex - pBegLine) = DataLength then
Canvas.TextOut(X, Y, sText)
else begin
Canvas.TextOut(X, Y, UTF8Copy(sText, 1, iEndDrawIndex - pBegLine));
end;
// Restore previous canvas settings
Canvas.Brush.Color := Color;
Canvas.Font.Color := Font.Color;
// Text before selection
if iBegDrawIndex - pBegLine > 0 then
Canvas.TextOut(X, Y, UTF8Copy(sText, 1, iBegDrawIndex - pBegLine));
end;
procedure TViewerControl.AddLineOffset(const iOffset: PtrInt);
begin
FLineList.Add(iOffset);
end;
procedure TViewerControl.KeyDown(var Key: word; Shift: TShiftState);
var
CharLenInBytes: Integer;
begin
if Shift = [] then
begin
case Key of
VK_DOWN:
begin
Key := 0;
Scroll(1);
end;
VK_UP:
begin
Key := 0;
Scroll(-1);
end;
VK_RIGHT:
begin
Key := 0;
HScroll(1);
end;
VK_LEFT:
begin
Key := 0;
HScroll(-1);
end;
VK_HOME:
begin
Key := 0;
CaretGoHome;
end;
VK_END:
begin
Key := 0;
CaretGoEnd;
end;
VK_PRIOR:
begin
Key := 0;
PageUp;
end;
VK_NEXT:
begin
Key := 0;
PageDown;
end;
else
inherited KeyDown(Key, Shift);
end;
end
else if Shift = [ssCtrl] then
begin
case Key of
VK_HOME:
begin
Key := 0;
CaretPos := FLowLimit;
MakeVisible(FCaretPos)
end;
VK_END:
begin
Key := 0;
CaretPos := FHighLimit;
MakeVisible(FCaretPos);
end;
else
inherited KeyDown(Key, Shift);
end;
end
else
inherited KeyDown(Key, Shift);
end;
function TViewerControl.FindAsciiSetForward(aPosition, aMaxBytes: PtrInt;
const AsciiChars: String;
bFindNotIn: Boolean): PtrInt;
var
i: Integer;
found: Boolean;
u: Cardinal;
CharLenInBytes: Integer;
begin
Result := -1;
while aMaxBytes > 0 do
begin
u := GetNextCharAsAscii(aPosition, CharLenInBytes);
if CharLenInBytes = 0 then
Exit;
if not bFindNotIn then
begin
for i := 1 to Length(AsciiChars) do
if u = ord(AsciiChars[i]) then
Exit(aPosition);
end
else
begin
found := False;
for i := 1 to Length(AsciiChars) do
if u = ord(AsciiChars[i]) then
begin
found := True;
break;
end;
if not found then
Exit(aPosition);
end;
Inc(aPosition, CharLenInBytes);
Dec(aMaxBytes, CharLenInBytes);
end;
end;
function TViewerControl.FindAsciiSetBackward(aPosition, aMaxBytes: PtrInt;
const AsciiChars: String;
bFindNotIn: Boolean): PtrInt;
var
i: Integer;
found: Boolean;
u: Cardinal;
CharLenInBytes: Integer;
begin
Result := -1;
while aMaxBytes > 0 do
begin
u := GetPrevCharAsAscii(aPosition, CharLenInBytes);
if CharLenInBytes = 0 then
Exit;
if not bFindNotIn then
begin
for i := 1 to Length(AsciiChars) do
if u = ord(AsciiChars[i]) then
Exit(aPosition);
end
else
begin
found := False;
for i := 1 to Length(AsciiChars) do
if u = ord(AsciiChars[i]) then
begin
found := True;
break;
end;
if not found then
Exit(aPosition);
end;
Dec(aPosition, CharLenInBytes);
Dec(aMaxBytes, CharLenInBytes);
end;
end;
procedure TViewerControl.MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
var
LineBegin, LineEnd: PtrInt;
ClickPos: PtrInt;
CharSide: TCharSide;
CharLenInBytes: Integer;
begin
inherited;
SetFocus;
if not IsFileOpen then
Exit;
case Button of
mbLeft:
begin
if Shift * [ssDouble, ssTriple] = [] then
begin
// Single click.
ClickPos := XYPos2Adr(x, y, CharSide);
if ClickPos <> -1 then
begin
FBlockBeg := ClickPos;
FBlockEnd := ClickPos;
FCaretPos := ClickPos;
FMouseBlockBeg := ClickPos;
FMouseBlockSide := CharSide;
FSelecting := True;
if CharSide in [csRight, csAfter] then
begin
if FViewerControlMode in [vcmDec, vcmHex, vcmBin] then
CharLenInBytes := 1
else begin
GetNextCharAsAscii(FCaretPos, CharLenInBytes);
end;
FCaretPos := FCaretPos + CharLenInBytes;
end;
Invalidate;
end
else
FSelecting := False;
end
else // if double click or triple click
begin
FSelecting := False;
LineBegin := GetStartOfLine(FMouseBlockBeg);
LineEnd := GetEndOfLine(FMouseBlockBeg);
if ssDouble in Shift then
begin
// Select word with double-click.
FBlockBeg := FindAsciiSetBackward(FMouseBlockBeg,
FMouseBlockBeg - LineBegin, sNonCharacter, False);
FBlockEnd := FindAsciiSetForward(FMouseBlockBeg,
LineEnd - FMouseBlockBeg, sNonCharacter, False);
end
else if ssTriple in Shift then
begin
// Select line with triple-click.
FBlockBeg := FindAsciiSetForward(LineBegin,
LineEnd - LineBegin, sWhiteSpace, True);
FBlockEnd := FindAsciiSetBackward(LineEnd,
LineEnd - LineBegin, sWhiteSpace, True);
end;
if FBlockBeg = -1 then
FBlockBeg := LineBegin;
if FBlockEnd = -1 then
FBlockEnd := LineEnd;
if FBlockBeg > FBlockEnd then
FBlockEnd := FBlockBeg;
if FAutoCopy then
CopyToClipboard;
Invalidate;
end;
end; // mbLeft
end; // case
end;
procedure TViewerControl.MouseMove(Shift: TShiftState; X, Y: Integer);
procedure MoveOneChar(var aPosition: PtrInt);
var
CharLenInBytes: Integer;
begin
if FViewerControlMode in [vcmDec, vcmHex, vcmBin] then
CharLenInBytes := 1
else begin
GetNextCharAsAscii(aPosition, CharLenInBytes);
end;
aPosition := aPosition + CharLenInBytes;
end;
procedure MoveOneCharByMouseSide(var aPosition: PtrInt);
begin
if FMouseBlockSide in [csRight, csAfter] then
MoveOneChar(aPosition);
end;
var
ClickPos: PtrInt;
CharSide: TCharSide;
begin
inherited;
if FSelecting then
begin
if y < FTextHeight then
Scroll(-3)
else if y > ClientHeight - FTextHeight then
Scroll(3);
ClickPos := XYPos2Adr(x, y, CharSide);
if ClickPos <> -1 then
begin
if ClickPos < FMouseBlockBeg then
begin
// Got a new beginning.
FBlockBeg := ClickPos;
FBlockEnd := FMouseBlockBeg;
// Move end beyond last character.
MoveOneCharByMouseSide(FBlockEnd);
// When selecting from right to left, the current selected side must be
// either csLeft or csBefore, otherwise current position is not included.
if not (CharSide in [csLeft, csBefore]) then
begin
// Current position should not be included in selection.
// Move beginning after first character.
MoveOneChar(FBlockBeg);
end;
FCaretPos:= FBlockBeg;
end
else if ClickPos > FMouseBlockBeg then
begin
// Got a new end.
FBlockBeg := FMouseBlockBeg;
FBlockEnd := ClickPos;
// Move beginning after first character.
MoveOneCharByMouseSide(FBlockBeg);
// When selecting from left to right, the current selected side must be
// either csRight or csAfter, otherwise current position is not included.
if CharSide in [csRight, csAfter] then
begin
// Current position should be included in selection.
// Move end beyond last character.
MoveOneChar(FBlockEnd);
end;
FCaretPos:= FBlockEnd;
end
else if FMouseBlockSide <> CharSide then
begin
// Same position but changed side of the character.
FBlockBeg := FMouseBlockBeg;
FBlockEnd := FMouseBlockBeg;
if ((FMouseBlockSide in [csBefore, csLeft]) and
(CharSide in [csRight, csAfter])) or
((FMouseBlockSide in [csRight, csAfter]) and
(CharSide in [csBefore, csLeft])) then
begin
// Move end beyond last character.
MoveOneChar(FBlockEnd);
end;
FCaretPos:= FBlockEnd;
end
else
begin
FBlockBeg := FMouseBlockBeg;
FBlockEnd := FMouseBlockBeg;
end;
Invalidate;
end;
end;
end;
procedure TViewerControl.MouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
begin
inherited;
if FSelecting and (Button = mbLeft) and (Shift * [ssDouble, ssTriple] = []) then
begin
if FAutoCopy then
CopyToClipboard;
FSelecting := False;
end;
end;
function TViewerControl.DoMouseWheelDown(Shift: TShiftState; MousePos: TPoint): Boolean;
begin
Result := inherited;
if not Result then
Result := Scroll(Mouse.WheelScrollLines);
end;
function TViewerControl.DoMouseWheelUp(Shift: TShiftState; MousePos: TPoint): Boolean;
begin
Result := inherited;
if not Result then
Result := Scroll(-Mouse.WheelScrollLines);
end;
function TViewerControl.DoMouseWheelLeft(Shift: TShiftState; MousePos: TPoint): Boolean;
begin
Result:= inherited DoMouseWheelLeft(Shift, MousePos);
if not Result then
Result := HScroll(-Mouse.WheelScrollLines);
end;
function TViewerControl.DoMouseWheelRight(Shift: TShiftState; MousePos: TPoint): Boolean;
begin
Result:= inherited DoMouseWheelRight(Shift, MousePos);
if not Result then
Result := HScroll(Mouse.WheelScrollLines);
end;
procedure TViewerControl.DoAutoAdjustLayout(const AMode: TLayoutAdjustmentPolicy; const AXProportion, AYProportion: Double);
begin
FScrollBarVert.Width := LCLIntf.GetSystemMetrics(SM_CYVSCROLL);
FScrollBarHorz.Height := LCLIntf.GetSystemMetrics(SM_CYHSCROLL);
inherited DoAutoAdjustLayout(AMode, AXProportion, AYProportion);
end;
function TViewerControl.XYPos2Adr(x, y: Integer; out CharSide: TCharSide): PtrInt;
var
yIndex: Integer;
StartLine, EndLine: PtrInt;
function XYPos2AdrBin: PtrInt;
var
I, J, L: Integer;
charWidth: Integer;
textWidth: Integer;
tmpPosition: PtrInt;
s, ss, sText: String;
InvalidCharLen: Integer;
begin
J:= 1;
ss := EmptyStr;
tmpPosition := StartLine;
sText := TransformBin(tmpPosition, EndLine);
L:= Length(sText);
for I := 1 to L do
begin
charWidth:= SafeUTF8NextCharLen(PByte(@sText[J]), (L - J) + 1, InvalidCharLen);
s:= Copy(sText, J, charWidth);
Inc(J, charWidth);
ss := ss + s;
textWidth := Canvas.TextWidth(ss);
if textWidth > x then
begin
charWidth := Canvas.TextWidth(s);
if textWidth - charWidth div 2 > x then
CharSide := csLeft
else
CharSide := csRight;
Exit(StartLine + I - 1); // -1 because we count from 1
end;
end;
CharSide := csBefore;
Result := EndLine;
end;
function XYPos2AdrCustom: PtrInt;
// | offset part | custom part | native part |
// | 0000AAAA: | FF AA CC AE | djfjks |
var
I, J, L: Integer;
charWidth: Integer;
textWidth: Integer;
tmpPosition: PtrInt;
InvalidCharLen: Integer;
ss, sText, sPartialText: String;
begin
tmpPosition := StartLine;
sText := TransformCustom(tmpPosition, EndLine);
if sText = '' then Exit;
// Clicked on offset part
ss := Copy(sText, 1, FCustom.StartOfs);
textWidth := Canvas.TextWidth(ss);
if textWidth > x then
begin
CharSide := csBefore;
Exit(StartLine);
end;
// Clicked on custom part
for I := 0 to FCustom.ValuesPerLine - 1 do
begin
sPartialText := Copy(sText, 1 + FCustom.StartOfs + I * (FCustom.MaxValueDigits + FCustom.SpaceCount), FCustom.MaxValueDigits);
ss := ss + sPartialText;
textWidth := Canvas.TextWidth(ss);
if textWidth > x then
begin
// Check if we're not after end of data.
if StartLine + I >= EndLine then
begin
CharSide := csBefore;
Exit(EndLine);
end;
charWidth := Canvas.TextWidth(sPartialText);
if textWidth - charWidth div 2 > x then
CharSide := csLeft
else
CharSide := csRight;
Exit(StartLine + I);
end;
// Space after hex number.
ss := ss + string(sText[1 + FCustom.StartOfs + I * (FCustom.MaxValueDigits + 1) + FCustom.MaxValueDigits]);
textWidth := Canvas.TextWidth(ss);
if textWidth > x then
begin
CharSide := csAfter;
Exit(StartLine + I);
end;
end;
// Clicked between hex and ascii.
sPartialText := Copy(sText, 1 + FCustom.StartOfs, FCustom.StartAscii - FCustom.EndOfs);
ss := ss + sPartialText;
textWidth := Canvas.TextWidth(ss);
if textWidth > x then
begin
Exit(-1); // No position.
end;
// Clicked on ascii part.
L:= Length(sText);
J:= 1 + FCustom.StartAscii;
for I := 0 to FCustom.ValuesPerLine - 1 do
begin
charWidth := SafeUTF8NextCharLen(PByte(@sText[J]), (L - J) + 1, InvalidCharLen);
sPartialText := Copy(sText, J, charWidth);
Inc(J, charWidth);
ss := ss + sPartialText;
textWidth := Canvas.TextWidth(ss);
if textWidth > x then
begin
// Check if we're not after end of data.
if StartLine + I >= EndLine then
begin
CharSide := csBefore;
Exit(EndLine);
end;
charWidth := Canvas.TextWidth(sPartialText);
if textWidth - charWidth div 2 > x then
CharSide := csLeft
else
CharSide := csRight;
Exit(StartLine + I);
end;
end;
CharSide := csBefore;
Result := EndLine;
end;
function XYPos2AdrText: PtrInt;
var
i: PtrInt;
Dos: Boolean;
charWidth: Integer;
textWidth: Integer;
len: Integer = 0;
CharLenInBytes: Integer;
s: String;
ss: String;
begin
ss := '';
i := StartLine;
Dos:= FEncoding in ViewerEncodingOem;
while i < EndLine do
begin
s := GetNextCharAsUtf8(i, CharLenInBytes);
if CharLenInBytes = 0 then
Break;
// Check if the conversion to UTF-8 was successful.
if Length(s) > 0 then
begin
if s = #9 then
begin
s := StringOfChar(' ', FTabSpaces - len mod FTabSpaces);
len := len + (FTabSpaces - len mod FTabSpaces);
end
else
Inc(len); // Assume there is one character after conversion
// (otherwise use Inc(len, UTF8Length(s))).
if (Mode = vcmText) and (len <= FHPosition) then
begin
i := i + CharLenInBytes;
Continue;
end;
if (CharLenInBytes = 1) and (s[1] < ' ') then
begin
if Dos then
s := ASCII_TABLE[Ord(s[1])]
else
s := ' ';
end;
ss := ss + s;
textWidth := Canvas.TextWidth(ss);
if textWidth > x then
begin
charWidth := Canvas.TextWidth(s);
if textWidth - charWidth div 2 > x then
CharSide := csLeft
else
CharSide := csRight;
Exit(i);
end;
end;
i := i + CharLenInBytes;
end;
CharSide := csBefore;
Result := EndLine;
end;
begin
if FLineList.Count = 0 then
Exit(-1);
if (x < FLeftMargin) then
x := 0
else begin
x := x - FLeftMargin;
end;
yIndex := y div FTextHeight;
if yIndex >= FLineList.Count then
yIndex := FLineList.Count - 1;
if yIndex < 0 then
yIndex := 0;
// Get position of first character of the line.
StartLine := FLineList.Items[yIndex];
// Get position of last character of the line.
EndLine := GetEndOfLine(StartLine);
if (x = 0) and ((Mode <> vcmText) or (FHPosition = 0)) then
begin
CharSide := csBefore;
Exit(StartLine);
end;
case Mode of
vcmBin:
Result := XYPos2AdrBin;
vcmHex,vcmDec:
Result := XYPos2AdrCustom; // XYPos2AdrHex;
vcmText, vcmWrap, vcmBook:
Result := XYPos2AdrText;
else
raise Exception.Create('Invalid viewer mode');
end;
end;
procedure TViewerControl.SelectAll;
begin
SelectText(FLowLimit, FHighLimit);
end;
procedure TViewerControl.SelectText(AStart, AEnd: PtrInt);
begin
if AStart < FLowLimit then
AStart := FLowLimit;
if AEnd > FHighLimit then
AEnd := FHighLimit;
if AStart <= AEnd then
begin
FBlockBeg := AStart;
FBlockEnd := AEnd;
Invalidate;
end;
end;
procedure TViewerControl.CopyToClipboard;
var
sText, utf8Text: string;
begin
if (FBlockEnd - FBlockBeg) <= 0 then
Exit;
if (FBlockEnd - FBlockBeg) > 1024 * 1024 then // Max 1 MB to clipboard
Exit;
SetString(sText, GetDataAdr + FBlockBeg, FBlockEnd - FBlockBeg);
utf8Text := ConvertToUTF8(sText);
{$IFDEF LCLGTK2}
// Workaround for Lazarus bug #0021453. LCL adds trailing zero to clipboard in Clipboard.AsText.
Clipboard.Clear;
Clipboard.AddFormat(PredefinedClipboardFormat(pcfText), utf8Text[1], Length(utf8Text));
{$ELSE}
Clipboard.AsText := utf8Text;
{$ENDIF}
end;
procedure TViewerControl.CopyToClipboardF;
var
s,sText, utf8Text: string;
len: Integer;
begin
len:=FBlockEnd-FBlockBeg;
if len=0 then exit;
sText:=TransformCustomBlock(FBlockBeg,len,False,False,s);
utf8Text := ConvertToUTF8(sText);
{$IFDEF LCLGTK2}
// Workaround for Lazarus bug #0021453. LCL adds trailing zero to clipboard in Clipboard.AsText.
Clipboard.Clear;
Clipboard.AddFormat(PredefinedClipboardFormat(pcfText), utf8Text[1], Length(utf8Text));
{$ELSE}
Clipboard.AsText := utf8Text;
{$ENDIF}
end;
function TViewerControl.Selection: String;
const
MAX_LEN = 512;
var
sText: String;
AIndex: PtrInt;
ALength: PtrInt;
CharLenInBytes: Integer;
begin
if (FBlockEnd - FBlockBeg) <= 0 then
Exit(EmptyStr);
ALength:= FBlockEnd - FBlockBeg;
if ALength <= MAX_LEN then
begin
SetString(sText, GetDataAdr + FBlockBeg, ALength);
Result := ConvertToUTF8(sText);
end
else begin
Result:= EmptyStr;
AIndex:= FBlockBeg;
ALength:= AIndex + MAX_LEN;
while AIndex < ALength do
begin
sText := GetNextCharAsUtf8(AIndex, CharLenInBytes);
if CharLenInBytes = 0 then
Break;
Result:= Result + sText;
AIndex:= AIndex + CharLenInBytes;
end;
end;
end;
function TViewerControl.GetNextCharAsAscii(const iPosition: PtrInt; out CharLenInBytes: Integer): Cardinal;
var
u1, u2: Word;
InvalidCharLen: Integer;
begin
Result := 0;
case FEncoding of
veUtf8, veUtf8bom:
begin
if iPosition < FHighLimit then
begin
CharLenInBytes := SafeUTF8NextCharLen(GetDataAdr + iPosition,
FHighLimit - iPosition,
InvalidCharLen);
// It's enough to only return Ascii.
if CharLenInBytes = 1 then
Result := PByte(GetDataAdr)[iPosition];
// Full conversion:
// Result := UTF8CodepointToUnicode(PAnsiChar(GetDataAdr + iPosition), CharLenInBytes);
end
else
CharLenInBytes := 0;
end;
veAnsi, veOem,
veCp1250..veCp874,
veIso88591,
veIso88592,
veKoi8r,
veKoi8u,
veKoi8ru:
if iPosition < FHighLimit then
begin
Result := PByte(GetDataAdr)[iPosition];
CharLenInBytes := 1;
end
else
CharLenInBytes := 0;
veUcs2be:
if iPosition + SizeOf(Word) - 1 < FHighLimit then
begin
Result := BEtoN(PWord(GetDataAdr + iPosition)[0]);
CharLenInBytes := SizeOf(Word);
end
else
CharLenInBytes := 0;
veUcs2le:
if iPosition + SizeOf(Word) - 1 < FHighLimit then
begin
Result := LEtoN(PWord(GetDataAdr + iPosition)[0]);
CharLenInBytes := SizeOf(Word);
end
else
CharLenInBytes := 0;
veUtf16be:
if iPosition + SizeOf(Word) - 1 < FHighLimit then
begin
u1 := BEtoN(PWord(GetDataAdr + iPosition)[0]);
CharLenInBytes := UTF16CharacterLength(@u1);
if CharLenInBytes = 1 then
begin
Result := u1;
end
else if iPosition + SizeOf(Word) * CharLenInBytes - 1 < FHighLimit then
begin
u2 := BEtoN(PWord(GetDataAdr + iPosition)[1]);
Result := utf16PairToUnicode(u1, u2);
end;
CharLenInBytes := CharLenInBytes * SizeOf(Word);
end
else
CharLenInBytes := 0;
veUtf16le:
if iPosition + SizeOf(Word) - 1 < FHighLimit then
begin
u1 := LEtoN(PWord(GetDataAdr + iPosition)[0]);
CharLenInBytes := UTF16CharacterLength(@u1);
if CharLenInBytes = 1 then
begin
Result := u1;
end
else if iPosition + SizeOf(Word) * CharLenInBytes - 1 < FHighLimit then
begin
u2 := LEtoN(PWord(GetDataAdr + iPosition)[1]);
Result := utf16PairToUnicode(u1, u2);
end
else
CharLenInBytes := 0;
CharLenInBytes := CharLenInBytes * SizeOf(Word);
end
else
CharLenInBytes := 0;
veUtf32be:
if iPosition + SizeOf(LongWord) - 1 < FHighLimit then
begin
Result := BEtoN(PLongWord(GetDataAdr + iPosition)[0]);
CharLenInBytes := SizeOf(LongWord);
end
else
CharLenInBytes := 0;
veUtf32le:
if iPosition + SizeOf(LongWord) - 1 < FHighLimit then
begin
Result := LEtoN(PLongWord(GetDataAdr + iPosition)[0]);
CharLenInBytes := SizeOf(LongWord);
end
else
CharLenInBytes := 0;
veCp932, // Unsupported variable-width encodings
veCp936, // TODO: Add cp932, cp936, cp949, cp950 encoding support
veCp949,
veCp950:
if iPosition < FHighLimit then
begin
Result := PByte(GetDataAdr)[iPosition];
CharLenInBytes := 1;
end
else
CharLenInBytes := 0;
else
raise Exception.Create('Unsupported viewer encoding');
end;
end;
function TViewerControl.GetPrevCharAsAscii(const iPosition: PtrInt; out CharLenInBytes: Integer): Cardinal;
var
u1, u2: Word;
InvalidCharLen: Integer;
begin
Result := 0;
case FEncoding of
veUtf8, veUtf8bom:
begin
if iPosition > FLowLimit then
begin
CharLenInBytes := SafeUTF8PrevCharLen(GetDataAdr + iPosition,
iPosition - FLowLimit,
InvalidCharLen);
// It's enough to only return Ascii.
if CharLenInBytes = 1 then
Result := PByte(GetDataAdr)[iPosition - 1];
// Full conversion:
// Result := UTF8CodepointToUnicode(PAnsiChar(GetDataAdr + iPosition - CharLenInBytes), CharLenInBytes);
end
else
CharLenInBytes := 0;
end;
veAnsi, veOem,
veCp1250..veCp874,
veIso88591,
veIso88592,
veKoi8r,
veKoi8u,
veKoi8ru:
if iPosition > FLowLimit then
begin
Result := PByte(GetDataAdr + iPosition)[-1];
CharLenInBytes := 1;
end
else
CharLenInBytes := 0;
veUcs2be:
if iPosition >= FLowLimit + SizeOf(Word) then
begin
Result := BEtoN(PWord(GetDataAdr + iPosition)[-1]);
CharLenInBytes := SizeOf(Word);
end
else
CharLenInBytes := 0;
veUcs2le:
if iPosition >= FLowLimit + SizeOf(Word) then
begin
Result := LEtoN(PWord(GetDataAdr + iPosition)[-1]);
CharLenInBytes := SizeOf(Word);
end
else
CharLenInBytes := 0;
veUtf16be:
if iPosition >= FLowLimit + SizeOf(Word) then
begin
u1 := BEtoN(PWord(GetDataAdr + iPosition)[-1]);
CharLenInBytes := UTF16CharacterLength(@u1);
if CharLenInBytes = 1 then
begin
Result := u1;
end
else if iPosition >= FLowLimit + SizeOf(Word) * CharLenInBytes then
begin
u2 := BEtoN(PWord(GetDataAdr + iPosition)[-2]);
// u2 is the first, u1 is the second value of the pair
Result := utf16PairToUnicode(u2, u1);
end;
CharLenInBytes := CharLenInBytes * SizeOf(Word);
end
else
CharLenInBytes := 0;
veUtf16le:
if iPosition >= FLowLimit + SizeOf(Word) then
begin
u1 := LEtoN(PWord(GetDataAdr + iPosition)[-1]);
CharLenInBytes := UTF16CharacterLength(@u1);
if CharLenInBytes = 1 then
begin
Result := u1;
end
else if iPosition >= FLowLimit + SizeOf(Word) * CharLenInBytes then
begin
u2 := LEtoN(PWord(GetDataAdr + iPosition)[-2]);
// u2 is the first, u1 is the second value of the pair
Result := utf16PairToUnicode(u2, u1);
end;
CharLenInBytes := CharLenInBytes * SizeOf(Word);
end
else
CharLenInBytes := 0;
veUtf32be:
if iPosition >= FLowLimit + SizeOf(LongWord) then
begin
Result := BEtoN(PLongWord(GetDataAdr + iPosition)[-1]);
CharLenInBytes := SizeOf(LongWord);
end
else
CharLenInBytes := 0;
veUtf32le:
if iPosition >= FLowLimit + SizeOf(LongWord) then
begin
Result := LEtoN(PLongWord(GetDataAdr + iPosition)[-1]);
CharLenInBytes := SizeOf(LongWord);
end
else
CharLenInBytes := 0;
veCp932, // Unsupported variable-width encodings
veCp936, // TODO: Add cp932, cp936, cp949, cp950 encoding support
veCp949,
veCp950:
if iPosition > FLowLimit then
begin
Result := PByte(GetDataAdr + iPosition)[-1];
CharLenInBytes := 1;
end
else
CharLenInBytes := 0;
else
raise Exception.Create('Unsupported viewer encoding');
end;
end;
function TViewerControl.GetNextCharAsUtf8(const iPosition: PtrInt; out CharLenInBytes: Integer): String;
var
u1: Word;
s: string;
InvalidCharLen: Integer;
begin
Result := '';
case FEncoding of
veUtf8, veUtf8bom:
CharLenInBytes := SafeUTF8NextCharLen(GetDataAdr + iPosition,
FHighLimit - iPosition,
InvalidCharLen);
veAnsi, veOem,
veCp1250..veCp874,
veIso88591,
veIso88592,
veKoi8r,
veKoi8u,
veKoi8ru:
CharLenInBytes := 1;
veUcs2be, veUcs2le:
CharLenInBytes := 2;
veUtf16be:
if iPosition + SizeOf(Word) - 1 < FHighLimit then
begin
u1 := BEtoN(PWord(GetDataAdr + iPosition)[0]);
CharLenInBytes := UTF16CharacterLength(@u1) * SizeOf(Word);
end
else
CharLenInBytes := 0;
veUtf16le:
if iPosition + SizeOf(Word) - 1 < FHighLimit then
begin
u1 := LEtoN(PWord(GetDataAdr + iPosition)[0]);
CharLenInBytes := UTF16CharacterLength(@u1) * SizeOf(Word);
end
else
CharLenInBytes := 0;
veUtf32be, veUtf32le:
CharLenInBytes := 4;
veCp932, // Unsupported variable-width encodings
veCp936, // TODO: Add cp932, cp936, cp949, cp950 encoding support
veCp949,
veCp950:
CharLenInBytes := 1;
else
raise Exception.Create('Unsupported viewer encoding');
end;
if (CharLenInBytes > 0) and (iPosition + CharLenInBytes - 1 < FHighLimit) then
begin
SetString(s, GetDataAdr + iPosition, CharLenInBytes);
Result := ConvertToUTF8(s);
end
else
Result := '';
end;
function TViewerControl.ConvertToUTF8(const sText: AnsiString): String;
begin
if FEncoding = veAutoDetect then
FEncoding := DetectEncoding; // Force detect encoding.
case FEncoding of
veAutoDetect: ;
veAnsi:
Result := CeAnsiToUtf8(sText);
veOem:
Result := CeOemToUtf8(sText);
veUtf8, veUtf8bom:
Result := Utf8ReplaceBroken(sText);
veUtf16be:
Result := Utf16BEToUtf8(sText);
veUtf16le:
Result := Utf16LEToUtf8(sText);
veUtf32be:
Result := Utf32BEToUtf8(sText);
veUtf32le:
Result := Utf32LEToUtf8(sText);
else
Result := LConvEncoding.ConvertEncoding(sText,
ViewerEncodingsNames[FEncoding], EncodingUTF8);
end;
end;
function TViewerControl.ConvertFromUTF8(const sText: String): AnsiString;
begin
if FEncoding = veAutoDetect then
FEncoding := DetectEncoding; // Force detect encoding.
case FEncoding of
veAutoDetect: ;
veAnsi:
Result := CeUtf8ToAnsi(sText);
veOem:
Result := CeUtf8ToOem(sText);
veUtf8, veUtf8bom:
Result := sText;
veUtf16be:
Result := Utf8ToUtf16BE(sText);
veUtf16le:
Result := Utf8ToUtf16LE(sText);
veUtf32be:
Result := '';//Utf8ToUtf32BE(sText);
veUtf32le:
Result := '';//Utf8ToUtf32LE(sText);
else
Result := LConvEncoding.ConvertEncoding(sText,
EncodingUTF8, ViewerEncodingsNames[FEncoding]);
end;
end;
function TViewerControl.IsVisible(const aPosition: PtrInt): Boolean;
var
StartPos: PtrInt;
CharLenInBytes: Integer;
begin
if IsFileOpen and (FLineList.Count > 0) then
begin
FVisibleOffset:= 0;
StartPos:= GetStartOfLine(aPosition);
// Calculate horizontal offset in symbols
while (StartPos < aPosition) do
begin
GetNextCharAsAscii(StartPos, CharLenInBytes);
Inc(StartPos, CharLenInBytes);
Inc(FVisibleOffset);
end;
Result := (aPosition >= FLineList.Items[0]) and
(aPosition <= FLineList.Items[FLineList.Count - 1]) and
(FVisibleOffset >= FHPosition) and
(FVisibleOffset <= FHPosition + FTextWidth);
end
else
Result := False;
end;
procedure TViewerControl.MakeVisible(const aPosition: PtrInt);
var
Offset: Integer;
LastLine: Boolean;
begin
if not IsVisible(aPosition) then
begin
SetPosition(aPosition);
Offset:= GetLinesTillEnd(aPosition, LastLine);
if (Offset > 4) and (LastLine = False) then Scroll(-4);
Update;
if FViewerControlMode = vcmText then
begin
if (FVisibleOffset < FHPosition) or
(FVisibleOffset > FHPosition + FTextWidth) then
begin
SetHPosition(FVisibleOffset);
HScroll(-1);
end;
end;
end;
end;
procedure TViewerControl.ScrollBarVertScroll(Sender: TObject;
ScrollCode: TScrollCode; var ScrollPos: Integer);
begin
FUpdateScrollBarPos := False;
case ScrollCode of
scLineUp: Scroll(-1);
scLineDown: Scroll(1);
scPageUp: PageUp;
scPageDown: PageDown;
scTop: GoHome;
scBottom: GoEnd;
scTrack,
scPosition:
begin
// This check helps avoiding loops if changing ScrollPos below
// triggers another scPosition message.
if (ScrollCode = scTrack) or (ScrollPos <> FScrollBarPosition) then
begin
if ScrollPos = 0 then
GoHome
else if ScrollPos = 100 then
GoEnd
else
Percent := ScrollPos;
end;
end;
scEndScroll:
begin
end;
end;
ScrollPos := FScrollBarPosition;
FUpdateScrollBarPos := True;
end;
procedure TViewerControl.ScrollBarHorzScroll(Sender: TObject;
ScrollCode: TScrollCode; var ScrollPos: Integer);
begin
FUpdateScrollBarPos := False;
case ScrollCode of
scLineUp: HScroll(-1);
scLineDown: HScroll(1);
scPageUp: HPageUp;
scPageDown: HPageDown;
scTop: HGoHome;
scBottom: HGoEnd;
scTrack,
scPosition:
begin
// This check helps avoiding loops if changing ScrollPos below
// triggers another scPosition message.
if (ScrollCode = scTrack) or (ScrollPos <> FHScrollBarPosition) then
begin
if ScrollPos = 0 then
HGoHome
else if ScrollPos = 100 then
HGoEnd
else
HScroll((FHLowEnd - FTextWidth) * ScrollPos div 100 - FHPosition);
end;
end;
scEndScroll:
begin
end;
end;
ScrollPos := FHScrollBarPosition;
FUpdateScrollBarPos := True;
end;
procedure TViewerControl.UpdateScrollbars;
begin
FScrollBarVert.LargeChange := GetClientHeightInLines - 1;
case Mode of
vcmBin, vcmHex:
begin
//FScrollBarVert.PageSize :=
// ((FHighLimit div cHexWidth - GetClientHeightInLines) div 100);
end
else
FScrollBarVert.PageSize := 1;
end;
FScrollBarHorz.Visible:= (FViewerControlMode = vcmText);
end;
procedure TViewerControl.ViewerResize(Sender: TObject);
begin
UpdateScrollbars;
// Force recalculating position.
SetPosition(FPosition);
SetHPosition(FHPosition);
end;
procedure TViewerControl.ReReadFile;
begin
FBlockBeg := 0;
FBlockEnd := 0;
FBOMLength := GetBomLength;
UpdateLimits;
UpdateScrollbars;
Invalidate;
end;
function TViewerControl.IsFileOpen: Boolean;
begin
Result := Assigned(FMappedFile);
end;
function TViewerControl.DetectEncoding: TViewerEncoding;
var
DetectStringLength: Integer = 4096; // take first 4kB of the file to detect encoding
DetectString: String;
DetectedEncodingName: String;
Enc: TViewerEncoding;
begin
if IsFileOpen then
begin
// Default to Ansi in case encoding cannot be detected or is unsupported.
Result := veAnsi;
if FFileSize < DetectStringLength then
DetectStringLength := FFileSize;
SetString(DetectString, PAnsiChar(FMappedFile), DetectStringLength);
if Assigned(FOnGuessEncoding) then
DetectedEncodingName := FOnGuessEncoding(DetectString)
else
DetectedEncodingName := LConvEncoding.GuessEncoding(DetectString);
if DetectedEncodingName <> '' then
begin
DetectedEncodingName := NormalizeEncoding(DetectedEncodingName);
// Map UCS-2 to UTF-16.
if DetectedEncodingName = 'ucs2le' then
DetectedEncodingName := 'utf16le'
else if DetectedEncodingName = 'ucs2be' then
DetectedEncodingName := 'utf16be';
for Enc := Low(TViewerEncoding) to High(TViewerEncoding) do
begin
if NormalizeEncoding(ViewerEncodingsNames[Enc]) = DetectedEncodingName then
begin
Result := Enc;
break;
end;
end;
end;
end
else
Result := veAutoDetect;
end;
procedure TViewerControl.GetSupportedEncodings(List: TStrings);
var
Enc: TViewerEncoding;
begin
for Enc := Low(TViewerEncoding) to High(TViewerEncoding) do
List.Add(ViewerEncodingsNames[Enc]);
end;
function TViewerControl.GetBomLength: Integer;
begin
Result := 0;
case FEncoding of
veUtf8, veUtf8bom:
if (FFileSize >= 3) and
(PByte(FMappedFile)[0] = $EF) and
(PByte(FMappedFile)[1] = $BB) and
(PByte(FMappedFile)[2] = $BF) then
begin
Result := 3;
end;
veUcs2be, veUtf16be:
if (FFileSize >= 2) and
(PByte(FMappedFile)[0] = $FE) and
(PByte(FMappedFile)[1] = $FF) then
begin
Result := 2;
end;
veUcs2le, veUtf16le:
if (FFileSize >= 2) and
(PByte(FMappedFile)[0] = $FF) and
(PByte(FMappedFile)[1] = $FE) then
begin
Result := 2;
end;
veUtf32be:
if (FFileSize >= 4) and
(PByte(FMappedFile)[0] = $00) and
(PByte(FMappedFile)[1] = $00) and
(PByte(FMappedFile)[2] = $FE) and
(PByte(FMappedFile)[3] = $FF) then
begin
Result := 4;
end;
veUtf32le:
if (FFileSize >= 4) and
(PByte(FMappedFile)[0] = $00) and
(PByte(FMappedFile)[1] = $00) and
(PByte(FMappedFile)[2] = $FF) and
(PByte(FMappedFile)[3] = $FE) then
begin
Result := 4;
end;
end;
end;
procedure TViewerControl.UpdateLimits;
begin
if FEncoding = veAutoDetect then
FEncoding := DetectEncoding;
FBOMLength := GetBomLength;
case FViewerControlMode of
vcmText, vcmWrap, vcmBook:
begin
FLowLimit := 0;
FHighLimit := FFileSize - FBOMLength;
end;
else
begin
FLowLimit := 0;
FHighLimit := FFileSize;
end;
end;
end;
procedure TViewerControl.UpdateSelection;
procedure Check(var aPosition: PtrInt; Backwards: Boolean);
var
CharStart: Pointer;
begin
case FEncoding of
veUtf8, veUtf8bom:
begin
if not Backwards then
begin
CharStart := SafeUTF8NextCharStart(GetDataAdr + aPosition,
FHighLimit - aPosition);
if Assigned(CharStart) then
aPosition := CharStart - GetDataAdr
else
aPosition := 0;
end
else
begin
CharStart := SafeUTF8PrevCharEnd(GetDataAdr + aPosition,
aPosition - FLowLimit);
if Assigned(CharStart) then
aPosition := CharStart - GetDataAdr
else
aPosition := 0;
end;
end;
veAnsi, veOem,
veCp1250..veCp874,
veIso88591,
veIso88592,
veKoi8r,
veKoi8u,
veKoi8ru:
; // any position allowed
veUcs2be, veUcs2le:
aPosition := ((aPosition - FLowLimit) and not 1) + FLowLimit;
veUtf16be, veUtf16le:
// todo: check if not in the middle of utf-16 character
aPosition := ((aPosition - FLowLimit) and not 1) + FLowLimit;
veUtf32be, veUtf32le:
aPosition := ((aPosition - FLowLimit) and not 3) + FLowLimit;
veCp932, // Unsupported variable-width encodings
veCp936, // TODO: Add cp932, cp936, cp949, cp950 encoding support
veCp949,
veCp950:
;
else
raise Exception.Create('Unsupported viewer encoding');
end;
end;
begin
if (FBlockBeg < FLowLimit) or (FBlockBeg >= FHighLimit) or
(FBlockEnd < FLowLimit) or (FBlockEnd >= FHighLimit) then
begin
FBlockBeg := FLowLimit;
FBlockEnd := FLowLimit;
end
else
begin
case FViewerControlMode of
vcmText, vcmWrap, vcmBook:
begin
Check(FBlockBeg, False);
Check(FBlockEnd, True);
if (FBlockBeg < FLowLimit) or (FBlockBeg >= FHighLimit) or
(FBlockEnd < FLowLimit) or (FBlockEnd >= FHighLimit) or
(FBlockEnd < FBlockBeg) then
begin
FBlockBeg := FLowLimit;
FBlockEnd := FLowLimit;
end;
end;
// In non-text modes any selection is valid.
end;
end;
end;
function TViewerControl.FindUtf8Text(iStartPos: PtrInt; const sSearchText: String;
bCaseSensitive: Boolean; bSearchBackwards: Boolean): PtrInt;
var
SearchTextLength: Integer;
sSearchChars: array of String;
pCurrentAddr, pEndAddr: PtrInt;
i, charLen: Integer;
function sPos2(pAdr: PtrInt):Boolean;
var
curChr:String;
i, charLen: Integer;
begin
Result := False;
for i := 0 to SearchTextLength-1 do
begin
curChr:=GetNextCharAsUtf8(pAdr,charLen);
case bCaseSensitive of
False: if UTF8UpperCase(curChr) <> UTF8UpperCase(sSearchChars[i]) then Exit;
True : if curChr <> sSearchChars[i] then Exit;
end;
if charLen>0 then
pAdr:=pAdr+charLen
else
Inc(pAdr);
end;
Result:=True;
end;
begin
Result := PtrInt(-1);
SearchTextLength := UTF8Length(sSearchText);
if (SearchTextLength <= 0) then
Exit;
setLength(sSearchChars,SearchTextLength);
for i:=1 to SearchTextLength do
sSearchChars[i-1]:=UTF8Copy(sSearchText,i,1);
pCurrentAddr := iStartPos;
pEndAddr := FHighLimit - Length(ConvertFromUTF8(sSearchText));
if bSearchBackwards and (pCurrentAddr > pEndAddr) then
// Move to the first possible position for searching backwards.
pCurrentAddr := pEndAddr;
if (pEndAddr < 0) or (pCurrentAddr < 0) or (pCurrentAddr > pEndAddr) then
Exit;
while True do
begin
if (pCurrentAddr > pEndAddr) or (pCurrentAddr < 0) then
Exit;
if sPos2(pCurrentAddr) then
begin
Result := pCurrentAddr;
Exit;
end;
case bSearchBackwards of
False:
begin
GetNextCharAsUtf8(pCurrentAddr,charLen);
if charLen>0 then
pCurrentAddr:=pCurrentAddr+charLen
else
Inc(pCurrentAddr);
end;
True : Dec(pCurrentAddr);
end;
end;
end;
procedure TViewerControl.ResetEncoding;
begin
FEncoding:= veAutoDetect;
end;
procedure Register;
begin
RegisterComponents('SeksiCmd', [TViewerControl]);
end;
end.
| 412 | 0.981036 | 1 | 0.981036 | game-dev | MEDIA | 0.508897 | game-dev,desktop-app | 0.933282 | 1 | 0.933282 |
MrShieh-X/console-minecraft-launcher | 31,456 | src/main/java/com/mrshiehx/cmcl/modules/extra/forge/ForgeMerger.java | /*
* Console Minecraft Launcher
* Copyright (C) 2021-2024 MrShiehX
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.mrshiehx.cmcl.modules.extra.forge;
import com.mrshiehx.cmcl.CMCL;
import com.mrshiehx.cmcl.api.download.DownloadSource;
import com.mrshiehx.cmcl.bean.Pair;
import com.mrshiehx.cmcl.bean.SplitLibraryName;
import com.mrshiehx.cmcl.bean.arguments.Arguments;
import com.mrshiehx.cmcl.exceptions.ExceptionWithDescription;
import com.mrshiehx.cmcl.modules.extra.ExtraMerger;
import com.mrshiehx.cmcl.modules.version.downloaders.LibrariesDownloader;
import com.mrshiehx.cmcl.utils.FileUtils;
import com.mrshiehx.cmcl.utils.Utils;
import com.mrshiehx.cmcl.utils.cmcl.version.VersionLibraryUtils;
import com.mrshiehx.cmcl.utils.console.InteractionUtils;
import com.mrshiehx.cmcl.utils.console.PrintingUtils;
import com.mrshiehx.cmcl.utils.internet.DownloadUtils;
import com.mrshiehx.cmcl.utils.internet.NetworkUtils;
import com.mrshiehx.cmcl.utils.json.JSONUtils;
import org.jetbrains.annotations.Nullable;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.spi.FileSystemProvider;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.stream.Collectors;
import java.util.zip.ZipFile;
import static com.mrshiehx.cmcl.CMCL.*;
public class ForgeMerger implements ExtraMerger {
private static final String MODLOADER_NAME = "Forge";
private static final SimpleDateFormat TIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
private static boolean clChecked = false;
private static ClassLoader parentClassLoader = null;
/**
* 将 Forge 的JSON合并到原版JSON
*
* @return key: 如果无法安装 Forge,是否继续安装;value:如果成功合并,则为需要安装的依赖库集合,否则为空
**/
public Pair<Boolean, List<JSONObject>> merge(String minecraftVersion, JSONObject headJSONObject, File minecraftJarFile, boolean askContinue, @Nullable String extraVersion) {
Map<String, JSONObject> installableForges;
try {
installableForges = getInstallableForges(minecraftVersion);
} catch (Exception e) {
System.out.println(e.getMessage());
return new Pair<>(askContinue && InteractionUtils.yesOrNo(getString("INSTALL_MODLOADER_UNABLE_DO_YOU_WANT_TO_CONTINUE", MODLOADER_NAME)), null);
}
if (installableForges.size() == 0) {
System.out.println(getString("INSTALL_MODLOADER_NO_INSTALLABLE_VERSION_2", MODLOADER_NAME));
return new Pair<>(askContinue && InteractionUtils.yesOrNo(getString("INSTALL_MODLOADER_UNABLE_DO_YOU_WANT_TO_CONTINUE", MODLOADER_NAME)), null);
}
JSONObject forge;
if (isEmpty(extraVersion)) {
List<Map.Entry<String, JSONObject>> list = new LinkedList<>(installableForges.entrySet());
list.sort((o1, o2) -> {
//2021-06-14T15:14:23.68Z
try {
Date dt1 = TIME_FORMAT.parse(o1.getValue().optString("modified").substring(0, 19) + "+0000");
Date dt2 = TIME_FORMAT.parse(o2.getValue().optString("modified").substring(0, 19) + "+0000");
return Long.compare(dt2.getTime(), dt1.getTime());
} catch (Exception ignore) {
//ignore.printStackTrace();
}
return 0;
});
PrintingUtils.printListItems(list.stream().map(Map.Entry::getKey).collect(Collectors.toList()), true, 4, 2, true);
String forgeVersionInput = ExtraMerger.selectExtraVersion(getString("INSTALL_MODLOADER_SELECT", MODLOADER_NAME, list.get(0).getKey()), installableForges, list.get(0).getKey(), MODLOADER_NAME);
if (forgeVersionInput == null)
return new Pair<>(false, null);
forge = installableForges.get(forgeVersionInput);
if (forge == null)
return new Pair<>(false, null);
} else {
forge = installableForges.get(extraVersion);
if (forge == null) {
System.out.println(getString("INSTALL_MODLOADER_FAILED_NOT_FOUND_TARGET_VERSION", extraVersion).replace("${NAME}", "Forge"));
return new Pair<>(askContinue && InteractionUtils.yesOrNo(getString("INSTALL_MODLOADER_UNABLE_DO_YOU_WANT_TO_CONTINUE", MODLOADER_NAME)), null);
}
}
try {
return installInternal(forge, headJSONObject, minecraftVersion, minecraftJarFile);
} catch (Exception e) {
System.out.println(e.getMessage());
return new Pair<>(askContinue && InteractionUtils.yesOrNo(getString("INSTALL_MODLOADER_UNABLE_DO_YOU_WANT_TO_CONTINUE", MODLOADER_NAME)), null);
}
}
public static Map<String, JSONObject> getInstallableForges(String minecraftVersion) throws ExceptionWithDescription {
JSONArray jsonArray;
try {
jsonArray = listForgeLoaderVersions(minecraftVersion);
} catch (Exception e) {
//e.printStackTrace();
throw new ExceptionWithDescription(getString("INSTALL_MODLOADER_FAILED_TO_GET_INSTALLABLE_VERSION", MODLOADER_NAME));
}
if (jsonArray.length() == 0) {
throw new ExceptionWithDescription(getString("INSTALL_MODLOADER_NO_INSTALLABLE_VERSION", MODLOADER_NAME));
}
String category = "installer";
String format = "jar";
Map<String, JSONObject> forges = new LinkedHashMap<>();
for (Object object : jsonArray) {
if (object instanceof JSONObject) {
JSONObject jsonObject = (JSONObject) object;
JSONArray files = jsonObject.optJSONArray("files");
if (files != null && files.length() > 0) {
inside:
for (Object o : files) {
if (o instanceof JSONObject) {
JSONObject jsonObject2 = (JSONObject) o;
if (category.equals(jsonObject2.optString("category")) && format.equals(jsonObject2.optString("format"))) {
forges.put(jsonObject.optString("version"), jsonObject);
break inside;
}
}
}
}
}
}
return forges;
}
public static Pair<Boolean, List<JSONObject>> installInternal(JSONObject forge, JSONObject headJSONObject, String minecraftVersion, File minecraftJarFile) throws ExceptionWithDescription {
String category = "installer";
String format = "jar";
String forgeVersion = forge.optString("version");
String branch = forge.optString("branch");
String mcversion = forge.optString("mcversion");
String s = minecraftVersion + "-" + forgeVersion
+ (!isEmpty(branch) ? "-" + branch : "");//1.18.2-40.0.9
String fileName1 = "forge-" + s + "-" + category + "." + format;
String fileName2 = "forge-" + s + "-" + minecraftVersion + "-" + category + "." + format;
String first = DownloadSource.getProvider().forgeMaven() + "net/minecraftforge/forge/" + s + "/" + fileName1;
String second = DownloadSource.getProvider().forgeMaven() + "net/minecraftforge/forge/" + s + "-" + minecraftVersion + "/" + fileName2;
//https://bmclapi2.bangbang93.com/forge/download?mcversion=1.18.2&version=40.0.35&category=installer&format=jar
File installer = new File(CMCL.getCMCLWorkingDirectory(), "forge-" + s + ".jar");
System.out.println(getString("INSTALL_MODLOADER_DOWNLOADING_FILE"));
String finalDownload;
try {
DownloadUtils.downloadFile(first, installer);
finalDownload = first;
} catch (Exception ignore) {
try {
DownloadUtils.downloadFile(second, installer);
finalDownload = second;
} catch (Exception ignored) {
StringBuilder stringBuilder = new StringBuilder();
char start = '?';
if (!isEmpty(mcversion)) {
stringBuilder.append(start).append("mcversion=").append(mcversion);
start = '&';
}
if (!isEmpty(forgeVersion)) {
stringBuilder.append(start).append("version=").append(forgeVersion);
start = '&';
}
if (!isEmpty(branch)) {
stringBuilder.append(start).append("branch=").append(branch);
start = '&';
}
stringBuilder.append(start).append("category=").append(category);
start = '&';
stringBuilder.append(start).append("format=").append(format);
//start='&';
String third = DownloadSource.getProvider().thirdPartyForge() + stringBuilder;
try {
//应该是常规的下载文件函数下载不了这个链接,所以才下载了bytes弄去文件那里;也可能下载bytes的函数下载不了,才这样特别
URL ConnectUrl = new URL(third);
HttpURLConnection connection;
try {
connection = (HttpURLConnection) ConnectUrl.openConnection();
} catch (IOException e) {
if (Utils.getConfig().optBoolean("proxyEnabled"))
System.err.println(Utils.getString("EXCEPTION_NETWORK_WRONG_PLEASE_CHECK_PROXY"));
throw e;
}
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setDoOutput(true);
connection.setRequestMethod("GET");
byte[] bytes;
try {
bytes = NetworkUtils.httpURLConnection2Bytes(connection);
} catch (IOException e) {
if (Utils.getConfig().optBoolean("proxyEnabled"))
System.err.println(Utils.getString("EXCEPTION_NETWORK_WRONG_PLEASE_CHECK_PROXY"));
throw e;
}
FileUtils.bytes2File(installer, bytes, false);
finalDownload = third;
} catch (Exception e) {
throw new ExceptionWithDescription(getString("INSTALL_MODLOADER_FAILED_DOWNLOAD", MODLOADER_NAME) + ": " + e);
}
}
}
if (!installer.exists() || installer.length() == 0) {
throw new ExceptionWithDescription(getString("INSTALL_MODLOADER_FAILED_DOWNLOAD", MODLOADER_NAME));
}
JSONObject installProfile;
ZipFile zipFile;
try {
zipFile = new ZipFile(installer);
installProfile = new JSONObject(Utils.inputStream2String(zipFile.getInputStream(zipFile.getEntry("install_profile.json"))));
} catch (IOException e) {
throw new ExceptionWithDescription(getString("INSTALL_MODLOADER_FAILED_WITH_REASON", MODLOADER_NAME, getString("EXCEPTION_READ_FILE_WITH_PATH", installer.getAbsolutePath()) + ": " + e));
} catch (JSONException e) {
throw new ExceptionWithDescription(getString("INSTALL_MODLOADER_FAILED_WITH_REASON", MODLOADER_NAME, getString("EXCEPTION_PARSE_FILE")));
}
JSONObject version = null;
List<JSONObject> librariesNeedToInstall;
if (installProfile.has("spec")) {
//new
if (!installProfile.optString("minecraft").equals(minecraftVersion)) {
throw new ExceptionWithDescription(getString("INSTALL_MODLOADER_FAILED_MC_VERSION_MISMATCH", MODLOADER_NAME));
}
String json = installProfile.optString("json");
FileSystem installerFileSystem = null;//不会NULL
for (FileSystemProvider fileSystemProvider : FileSystemProvider.installedProviders()) {
if (fileSystemProvider.getScheme().equalsIgnoreCase("jar")) {
try {
version = new JSONObject(new String(Files.readAllBytes((installerFileSystem = (fileSystemProvider.newFileSystem(installer.toPath(), new HashMap<>()))).getPath(json))));
break;
} catch (IOException e) {
throw new ExceptionWithDescription(getString("INSTALL_MODLOADER_FAILED_WITH_REASON", MODLOADER_NAME, getString("EXCEPTION_READ_FILE_WITH_PATH", json) + ": " + e));
} catch (JSONException e) {
throw new ExceptionWithDescription(getString("INSTALL_MODLOADER_FAILED_WITH_REASON", MODLOADER_NAME, getString("EXCEPTION_PARSE_FILE_WITH_PATH", json)));
}
}
}
if (version == null) {
throw new ExceptionWithDescription(getString("INSTALL_MODLOADER_FAILED_WITH_REASON", MODLOADER_NAME, getString("EXCEPTION_READ_FILE_WITH_PATH", json)));
}
JSONArray installProfileLibraries = installProfile.optJSONArray("libraries");
if (installProfileLibraries != null && installProfileLibraries.length() > 0) {
for (Object object : installProfileLibraries) {
if (object instanceof JSONObject) {
JSONObject library = (JSONObject) object;
Pair<String, String> pair = VersionLibraryUtils.getLibraryDownloadURLAndStoragePath(library);
if (pair == null) {
System.out.println(getString("MESSAGE_NOT_FOUND_LIBRARY_DOWNLOAD_URL", library.optString("name")));
continue;
}
String url = pair.getKey();
if (isEmpty(url)) {
String path = pair.getValue();
File file = new File(librariesDir, path);
if (file.length() <= 0) {
String path2 = "/maven" + (!path.startsWith("/") ? "/" + path : path);
try {
System.out.println(getString("MESSAGE_UNZIPPING_FILE", path2));
FileUtils.createFile(file, true);
FileUtils.bytes2File(file, Files.readAllBytes(installerFileSystem.getPath(path2)), false);
} catch (Exception e) {
System.out.println(getString("MESSAGE_FAILED_TO_DECOMPRESS_FILE", path2, e));
}
}
} else {
LibrariesDownloader.downloadSingleLibrary(library);
}
}
}
}
{
String forgePath = installProfile.optString("path");
if (!isEmpty(forgePath)) {
SplitLibraryName nameSplit = VersionLibraryUtils.splitLibraryName(forgePath);
if (nameSplit != null) {
String fileName = nameSplit.getFileName();
String path = Utils.getPathFromLibraryName(nameSplit) + "/" + fileName;
File file = new File(librariesDir, path);
if (file.length() <= 0) {
String path2 = "/maven" + (!path.startsWith("/") ? "/" + path : path);
try {
System.out.println(getString("MESSAGE_UNZIPPING_FILE", path2));
FileUtils.createFile(file, true);
FileUtils.bytes2File(file, Files.readAllBytes(installerFileSystem.getPath(path2)), false);
} catch (Exception e) {
System.out.println(getString("MESSAGE_FAILED_TO_DECOMPRESS_FILE", path2, e));
}
}
}
}
}
Map<String, String> data = new HashMap<>();
File temp = new File(CMCL.getCMCLWorkingDirectory(), "forge" + System.currentTimeMillis());
temp.mkdirs();
JSONObject dataJSON = installProfile.optJSONObject("data");
for (Map.Entry<String, Object> entry : dataJSON.toMap().entrySet()) {
if ((entry.getValue() instanceof Map)) {
Object clientObject = ((Map<?, ?>) entry.getValue()).get("client");
if (!(clientObject instanceof String)) continue;
String client = (String) clientObject;
if (!Utils.isEmpty(client)) {
String key = entry.getKey();
if (client.charAt(0) == '[' && client.charAt(client.length() - 1) == ']') { //Artifact
String inside = client.substring(1, client.length() - 1);
SplitLibraryName nameSplit = SplitLibraryName.valueOf(inside);
if (nameSplit == null) continue;
File libraryFile = nameSplit.getPhysicalFile();
data.put(key, libraryFile.getAbsolutePath());
} else if (client.charAt(0) == '\'' && client.charAt(client.length() - 1) == '\'') { //Literal
String inside = client.substring(1, client.length() - 1);
data.put(key, inside);
} else {
File target = new File(temp, client);
try {
if (target.exists()) target.delete();
FileUtils.bytes2File(target, Files.readAllBytes(installerFileSystem.getPath(client)), false);
} catch (Exception e) {
System.out.println(getString("MESSAGE_FAILED_TO_DECOMPRESS_FILE", client, e));
}
data.put(key, target.getAbsolutePath());
}
}
}
}
data.put("SIDE", "client");
data.put("MINECRAFT_JAR", minecraftJarFile.getAbsolutePath());
data.put("MINECRAFT_VERSION", installProfile.optString("minecraft"));
data.put("ROOT", gameDir.getAbsolutePath());
data.put("INSTALLER", installer.getAbsolutePath());
data.put("LIBRARY_DIR", librariesDir.getAbsolutePath());
JSONArray processorsJSON = installProfile.optJSONArray("processors");
List<JSONObject> processors = JSONUtils.jsonArrayToJSONObjectList(processorsJSON, jsonObject -> {
JSONArray sides = jsonObject.optJSONArray("sides");
boolean contains = false;
if (sides != null && sides.length() > 0) {
for (Object side : sides) {
if ("client".equals(side)) {
contains = true;
break;
}
}
} else {
contains = true;
}
return contains;
});
for (JSONObject processor : processors) {
SplitLibraryName splitLibraryName = SplitLibraryName.valueOf(processor.optString("jar"));
if (splitLibraryName == null) {
continue;
}
File processorJarPhysicalFile = splitLibraryName.getPhysicalFile();
if (!processorJarPhysicalFile.exists() || !processorJarPhysicalFile.isFile()) {
continue;
}
try (JarFile jarFile = new JarFile(processorJarPhysicalFile)) {
String mainClass = jarFile.getManifest().getMainAttributes().getValue(Attributes.Name.MAIN_CLASS);
List<URL> classpath = new ArrayList<>();
classpath.add(processorJarPhysicalFile.toURI().toURL());
for (Object o : processor.optJSONArray("classpath")) {
if (o instanceof String) {
SplitLibraryName splitLibraryName1 = SplitLibraryName.valueOf((String) o);
if (splitLibraryName1 != null) {
classpath.add(splitLibraryName1.getPhysicalFile().toURI().toURL());
}
}
}
List<String> args = new ArrayList<>();
for (Object o : processor.optJSONArray("args")) {
if (o instanceof String) {
String arg = (String) o;
char start = arg.charAt(0);
char end = arg.charAt(arg.length() - 1);
if (start == '[' && end == ']') {
SplitLibraryName splitLibraryName1 = SplitLibraryName.valueOf(arg.substring(1, arg.length() - 1));
if (splitLibraryName1 == null) continue;
args.add(splitLibraryName1.getPhysicalFile().getAbsolutePath());
} else {
args.add(replaceTokens(data, arg));
}
}
}
ClassLoader cl = new URLClassLoader(classpath.toArray(new URL[0]), getParentClassloader());
// Set the thread context classloader to be our newly constructed one so that service loaders work
Thread currentThread = Thread.currentThread();
ClassLoader threadClassloader = currentThread.getContextClassLoader();
currentThread.setContextClassLoader(cl);
try {
Class<?> cls = Class.forName(mainClass, true, cl);
Method main = cls.getDeclaredMethod("main", String[].class);
main.invoke(null, (Object) args.toArray(new String[0]));
} catch (InvocationTargetException ite) {
Throwable e = ite.getCause();
e.printStackTrace();
} catch (Throwable e) {
e.printStackTrace();
} finally {
// Set back to the previous classloader
currentThread.setContextClassLoader(threadClassloader);
}
} catch (Exception e) {
System.out.println(getString("MESSAGE_INSTALL_FORGE_FAILED_EXECUTE_PROCESSOR", e));
}
}
Utils.close(zipFile);
installer.delete();
FileUtils.deleteDirectory(temp);
} else if (installProfile.optJSONObject("install") != null && installProfile.optJSONObject("versionInfo") != null) {
///old
if (!installProfile.optJSONObject("install", new JSONObject()).optString("minecraft").equals(minecraftVersion)) {
throw new ExceptionWithDescription(getString("INSTALL_MODLOADER_FAILED_MC_VERSION_MISMATCH", MODLOADER_NAME));
}
version = installProfile.optJSONObject("versionInfo");
JSONObject installJSONObject = installProfile.optJSONObject("install");
String path = installJSONObject.optString("path");
String filePath = installJSONObject.optString("filePath");
SplitLibraryName nameSplit = VersionLibraryUtils.splitLibraryName(path);
File libraryFile = nameSplit.getPhysicalFile();
try {
FileUtils.inputStream2File(zipFile.getInputStream(zipFile.getEntry(filePath)), libraryFile);
zipFile.close();
installer.delete();
} catch (IOException e) {
throw new ExceptionWithDescription(getString("INSTALL_MODLOADER_FAILED_WITH_REASON", MODLOADER_NAME, getString("MESSAGE_FAILED_TO_DECOMPRESS_FILE", filePath, e)));
}
} else {
throw new ExceptionWithDescription(getString("INSTALL_MODLOADER_FAILED_UNKNOWN_TYPE", MODLOADER_NAME));
}
JSONArray forgeLibraries = version.optJSONArray("libraries");
librariesNeedToInstall = new LinkedList<>();
if (forgeLibraries != null) {
for (Object o : forgeLibraries) {
if (o instanceof JSONObject) {
JSONObject j = (JSONObject) o;
String name = j.optString("name");
if (!name.startsWith("net.minecraftforge:forge:")) {
SplitLibraryName nameSplit2 = VersionLibraryUtils.splitLibraryName(name);
if (nameSplit2 != null) {
File file = nameSplit2.getPhysicalFile();
if (!file.exists() && file.length() == 0) librariesNeedToInstall.add(j);
}
}
}
}
JSONArray mcLibraries = headJSONObject.optJSONArray("libraries");
headJSONObject.put("libraries", VersionLibraryUtils.mergeLibraries(JSONUtils.jsonArrayToJSONObjectList(mcLibraries), JSONUtils.jsonArrayToJSONObjectList(forgeLibraries)));
}
String mainClass = version.optString("mainClass");
if (!Utils.isEmpty(mainClass)) headJSONObject.put("mainClass", mainClass);
JSONObject forgeInHead = new JSONObject();
forgeInHead.put("version", forgeVersion);
forgeInHead.put("jarUrl", finalDownload);
headJSONObject.put("forge", forgeInHead);
String minecraftArguments = version.optString("minecraftArguments");
JSONObject arguments = version.optJSONObject("arguments");
if (!isEmpty(minecraftArguments)) {
String hmca = headJSONObject.optString("minecraftArguments");
if (hmca.isEmpty())
headJSONObject.put("minecraftArguments", minecraftArguments);
else {
Arguments arguments1 = new Arguments(hmca, false);
Arguments arguments2 = new Arguments(minecraftArguments, false);
arguments1.merge(arguments2);
headJSONObject.put("minecraftArguments", minecraftArguments = arguments1.toString("--"));
}
}
if (arguments != null) {
JSONObject argumentsMC = headJSONObject.optJSONObject("arguments");
if (argumentsMC != null) {
JSONArray gameMC = argumentsMC.optJSONArray("game");
JSONArray jvmMC = argumentsMC.optJSONArray("jvm");
JSONArray game = arguments.optJSONArray("game");
if (game != null && game.length() > 0) {
if (gameMC == null) argumentsMC.put("game", gameMC = new JSONArray());
gameMC.putAll(game);
}
JSONArray jvm = arguments.optJSONArray("jvm");
if (jvm != null && jvm.length() > 0) {
if (jvmMC == null) argumentsMC.put("jvm", jvmMC = new JSONArray());
jvmMC.putAll(jvm);
}
} else {
headJSONObject.put("arguments", arguments);
}
}
return new Pair<>(true, librariesNeedToInstall);
}
private static JSONArray listForgeLoaderVersions(String minecraftVersion) throws IOException {
return new JSONArray(NetworkUtils.get(DownloadSource.getProvider().forge() + "minecraft/" + minecraftVersion));
}
/**
* @from ForgeInstaller
**/
public static String replaceTokens(Map<String, String> tokens, String value) {
StringBuilder buf = new StringBuilder();
for (int x = 0; x < value.length(); x++) {
char c = value.charAt(x);
if (c == '\\') {
if (x == value.length() - 1)
throw new IllegalArgumentException("Illegal pattern (Bad escape): " + value);
buf.append(value.charAt(++x));
} else if (c == '{' || c == '\'') {
StringBuilder key = new StringBuilder();
for (int y = x + 1; y <= value.length(); y++) {
if (y == value.length())
throw new IllegalArgumentException("Illegal pattern (Unclosed " + c + "): " + value);
char d = value.charAt(y);
if (d == '\\') {
if (y == value.length() - 1)
throw new IllegalArgumentException("Illegal pattern (Bad escape): " + value);
key.append(value.charAt(++y));
} else if (c == '{' && d == '}') {
x = y;
break;
} else if (c == '\'' && d == '\'') {
x = y;
break;
} else
key.append(d);
}
if (c == '\'')
buf.append(key);
else {
if (!tokens.containsKey(key.toString()))
throw new IllegalArgumentException("Illegal pattern: " + value + " Missing Key: " + key);
buf.append(tokens.get(key.toString()));
}
} else {
buf.append(c);
}
}
return buf.toString();
}
/**
* @from ForgeInstaller
**/
private static synchronized ClassLoader getParentClassloader() { //Reflectively try and get the platform classloader, done this way to prevent hard dep on J9.
if (!clChecked) {
clChecked = true;
if (!System.getProperty("java.version").startsWith("1.")) { //in 9+ the changed from 1.8 to just 9. So this essentially detects if we're <9
try {
Method getPlatform = ClassLoader.class.getDeclaredMethod("getPlatformClassLoader");
parentClassLoader = (ClassLoader) getPlatform.invoke(null);
} catch (Exception ignore) {
}
}
}
return parentClassLoader;
}
}
| 412 | 0.983311 | 1 | 0.983311 | game-dev | MEDIA | 0.752276 | game-dev | 0.961902 | 1 | 0.961902 |
beanbag44/Nuker | 2,993 | src/main/kotlin/me/beanbag/nuker/module/settings/AbstractSetting.kt | package me.beanbag.nuker.module.settings
import com.google.gson.JsonElement
import com.google.gson.JsonPrimitive
import me.beanbag.nuker.handlers.ChatHandler
import me.beanbag.nuker.utils.FileManager
import me.beanbag.nuker.utils.IJsonable
import net.minecraft.text.Text
import net.minecraft.util.Formatting
import java.util.function.Consumer
import java.util.function.Supplier
import kotlin.reflect.KProperty
import meteordevelopment.meteorclient.settings.Setting as MeteorSetting
import org.rusherhack.core.setting.Setting as RusherSetting
abstract class AbstractSetting<T : Any>(
private var name: String,
private var description: String,
private val defaultValue: T,
onChange: MutableList<Consumer<T>>?,
private var visible: Supplier<Boolean>
) : IJsonable {
private var value: T = defaultValue
private var onChange: MutableList<Consumer<T>> = onChange ?: mutableListOf()
operator fun getValue(thisRef: Any?, property: KProperty<*>) =
value
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
setValue(value)
}
fun setValue(value: T) {
if (this.value != value) {
this.value = value
onChange.forEach { it.accept(value) }
FileManager.saveModuleConfigs()
}
}
fun getName() = name
fun getDescription() = description
fun getDefaultValue() = defaultValue
fun getValue() = value
fun getOnChange() = onChange
fun isVisible() = visible.get()
fun setValueFromString(value: String) {
valueFromString(value)?.let { setValue(it) }
}
abstract fun valueFromString(value: String): T?
abstract fun valueToString(): String
abstract fun possibleValues(): List<String>?
protected abstract fun toRusherSetting(): RusherSetting<*>?
protected abstract fun toMeteorSetting(): MeteorSetting<*>
fun getMeteorSetting(): MeteorSetting<*> {
val meteorSetting = toMeteorSetting()
return meteorSetting
}
fun getRusherSetting(): RusherSetting<*>? {
val rusherSetting = toRusherSetting()
return rusherSetting
}
fun helpText(): Text {
val text = Text.literal("${ChatHandler.toCamelCaseName(name)} - ${description}\n")
if (value is Enum<*>) {
text.append(Text.literal("Possible values:\n"))
for (enum in (value as Enum<*>).declaringJavaClass.enumConstants) {
text.append(Text.literal(" ${enum.name}"))
if (value is Describable) {
text.append(Text.literal(" - ${(value as Describable).description}").styled { it.withColor(Formatting.GRAY) })
}
text.append(Text.literal("\n"))
}
}
return text
}
override fun toJson(): JsonElement {
return JsonPrimitive(valueToString())
}
override fun fromJson(json: JsonElement) {
valueFromString(json.asString)?.let { setValue(it) }
}
} | 412 | 0.774183 | 1 | 0.774183 | game-dev | MEDIA | 0.727072 | game-dev | 0.911042 | 1 | 0.911042 |
wy19910222/Unity-ControlSystem | 3,992 | Assets/Tools/Demigiant/DOTweenPro/DOTweenProShortcuts.cs | // Author: Daniele Giardini - http://www.demigiant.com
// Created: 2018/07/13
using System;
using DG.Tweening.Core;
using DG.Tweening.Plugins;
using UnityEngine;
#pragma warning disable 1591
namespace DG.Tweening
{
public static class DOTweenProShortcuts
{
static DOTweenProShortcuts()
{
// Create stub instances of custom plugins, in order to allow IL2CPP to understand they must be included in the build
#pragma warning disable 219
SpiralPlugin stub = new SpiralPlugin();
#pragma warning restore 219
}
#region Shortcuts
#region Transform
/// <summary>Tweens a Transform's localPosition in a spiral shape.
/// Also stores the transform as the tween's target so it can be used for filtered operations</summary>
/// <param name="duration">The duration of the tween</param>
/// <param name="axis">The axis around which the spiral will rotate</param>
/// <param name="mode">The type of spiral movement</param>
/// <param name="speed">Speed of the rotations</param>
/// <param name="frequency">Frequency of the rotation. Lower values lead to wider spirals</param>
/// <param name="depth">Indicates how much the tween should move along the spiral's axis</param>
/// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param>
public static Tweener DOSpiral(
this Transform target, float duration, Vector3? axis = null, SpiralMode mode = SpiralMode.Expand,
float speed = 1, float frequency = 10, float depth = 0, bool snapping = false
) {
if (Mathf.Approximately(speed, 0)) speed = 1;
if (axis == null || axis == Vector3.zero) axis = Vector3.forward;
TweenerCore<Vector3, Vector3, SpiralOptions> t = DOTween.To(SpiralPlugin.Get(), () => target.localPosition, x => target.localPosition = x, (Vector3)axis, duration)
.SetTarget(target);
t.plugOptions.mode = mode;
t.plugOptions.speed = speed;
t.plugOptions.frequency = frequency;
t.plugOptions.depth = depth;
t.plugOptions.snapping = snapping;
return t;
}
#endregion
#if true // PHYSICS_MARKER
#region Rigidbody
/// <summary>Tweens a Rigidbody's position in a spiral shape.
/// Also stores the transform as the tween's target so it can be used for filtered operations</summary>
/// <param name="duration">The duration of the tween</param>
/// <param name="axis">The axis around which the spiral will rotate</param>
/// <param name="mode">The type of spiral movement</param>
/// <param name="speed">Speed of the rotations</param>
/// <param name="frequency">Frequency of the rotation. Lower values lead to wider spirals</param>
/// <param name="depth">Indicates how much the tween should move along the spiral's axis</param>
/// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param>
public static Tweener DOSpiral(
this Rigidbody target, float duration, Vector3? axis = null, SpiralMode mode = SpiralMode.Expand,
float speed = 1, float frequency = 10, float depth = 0, bool snapping = false
) {
if (Mathf.Approximately(speed, 0)) speed = 1;
if (axis == null || axis == Vector3.zero) axis = Vector3.forward;
TweenerCore<Vector3, Vector3, SpiralOptions> t = DOTween.To(SpiralPlugin.Get(), () => target.position, target.MovePosition, (Vector3)axis, duration)
.SetTarget(target);
t.plugOptions.mode = mode;
t.plugOptions.speed = speed;
t.plugOptions.frequency = frequency;
t.plugOptions.depth = depth;
t.plugOptions.snapping = snapping;
return t;
}
#endregion
#endif
#endregion
}
}
| 412 | 0.898917 | 1 | 0.898917 | game-dev | MEDIA | 0.822573 | game-dev | 0.852026 | 1 | 0.852026 |
The-Cataclysm-Preservation-Project/TrinityCore | 82,900 | src/server/game/DungeonFinding/LFGMgr.cpp | /*
* This file is part of the TrinityCore Project. See AUTHORS file for Copyright information
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "LFGMgr.h"
#include "Common.h"
#include "DatabaseEnv.h"
#include "DBCStores.h"
#include "DisableMgr.h"
#include "GameEventMgr.h"
#include "GameTime.h"
#include "Group.h"
#include "GroupMgr.h"
#include "InstanceSaveMgr.h"
#include "LFGGroupData.h"
#include "LFGPlayerData.h"
#include "LFGScripts.h"
#include "LFGQueue.h"
#include "Log.h"
#include "Map.h"
#include "MotionMaster.h"
#include "ObjectAccessor.h"
#include "ObjectMgr.h"
#include "Player.h"
#include "Map.h"
#include "RBAC.h"
#include "SharedDefines.h"
#include "SocialMgr.h"
#include "World.h"
#include "WorldSession.h"
namespace lfg
{
LFGDungeonData::LFGDungeonData(LFGDungeonEntry const* dbc) : id(dbc->ID), name(dbc->Name), map(dbc->MapID),
type(dbc->TypeID), expansion(dbc->ExpansionLevel), group(dbc->Group_ID),
minlevel(dbc->MinLevel), maxlevel(dbc->Maxlevel), difficulty(Difficulty(dbc->DifficultyID)),
seasonal((dbc->Flags & LFG_FLAG_SEASONAL) != 0), x(0.0f), y(0.0f), z(0.0f), o(0.0f),
requiredItemLevel(0), requiredTanks(dbc->Count_tank), requiredHealers(dbc->Count_healer),
requiredDamageDealers(dbc->Count_damage)
{
}
LFGMgr::LFGMgr(): m_QueueTimer(0), m_lfgProposalId(1),
m_options(sWorld->getIntConfig(CONFIG_LFG_OPTIONSMASK))
{
}
LFGMgr::~LFGMgr()
{
for (LfgRewardContainer::iterator itr = RewardMapStore.begin(); itr != RewardMapStore.end(); ++itr)
delete itr->second;
}
void LFGMgr::_LoadFromDB(Field* fields, ObjectGuid guid)
{
if (!fields)
return;
if (!guid.IsGroup())
return;
SetLeader(guid, ObjectGuid(HighGuid::Player, fields[0].GetUInt32()));
uint32 dungeon = fields[17].GetUInt32();
uint8 state = fields[18].GetUInt8();
if (!dungeon || !state)
return;
SetDungeon(guid, dungeon);
switch (state)
{
case LFG_STATE_DUNGEON:
case LFG_STATE_FINISHED_DUNGEON:
SetState(guid, (LfgState)state);
break;
default:
break;
}
}
void LFGMgr::_SaveToDB(ObjectGuid guid, uint32 db_guid)
{
if (!guid.IsGroup())
return;
CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction();
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_LFG_DATA);
stmt->setUInt32(0, db_guid);
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_LFG_DATA);
stmt->setUInt32(0, db_guid);
stmt->setUInt32(1, GetDungeon(guid));
stmt->setUInt32(2, GetState(guid));
trans->Append(stmt);
CharacterDatabase.CommitTransaction(trans);
}
/// Load rewards for completing dungeons
void LFGMgr::LoadRewards()
{
uint32 oldMSTime = getMSTime();
for (LfgRewardContainer::iterator itr = RewardMapStore.begin(); itr != RewardMapStore.end(); ++itr)
delete itr->second;
RewardMapStore.clear();
// ORDER BY is very important for GetRandomDungeonReward!
QueryResult result = WorldDatabase.Query("SELECT dungeonId, maxLevel, firstQuestId, otherQuestId, shortageQuestId, completionsPerPeriod, dailyReset FROM lfg_dungeon_rewards ORDER BY dungeonId, maxLevel ASC");
if (!result)
{
TC_LOG_ERROR("server.loading", ">> Loaded 0 lfg dungeon rewards. DB table `lfg_dungeon_rewards` is empty!");
return;
}
uint32 count = 0;
Field* fields = nullptr;
do
{
fields = result->Fetch();
uint32 dungeonId = fields[0].GetUInt32();
uint32 maxLevel = fields[1].GetUInt8();
uint32 firstQuestId = fields[2].GetUInt32();
uint32 otherQuestId = fields[3].GetUInt32();
uint32 shortageQuestId = fields[4].GetUInt32();
uint32 completionsPerPeriod = fields[5].GetUInt8();
bool dailyReset = fields[6].GetUInt8();
if (!GetLFGDungeonEntry(dungeonId))
{
TC_LOG_ERROR("sql.sql", "Dungeon %u specified in table `lfg_dungeon_rewards` does not exist!", dungeonId);
continue;
}
if (!maxLevel || maxLevel > sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL))
{
TC_LOG_ERROR("sql.sql", "Level %u specified for dungeon %u in table `lfg_dungeon_rewards` can never be reached!", maxLevel, dungeonId);
maxLevel = sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL);
}
if (!firstQuestId || !sObjectMgr->GetQuestTemplate(firstQuestId))
{
TC_LOG_ERROR("sql.sql", "First quest %u specified for dungeon %u in table `lfg_dungeon_rewards` does not exist!", firstQuestId, dungeonId);
continue;
}
if (otherQuestId && !sObjectMgr->GetQuestTemplate(otherQuestId))
{
TC_LOG_ERROR("sql.sql", "Other quest %u specified for dungeon %u in table `lfg_dungeon_rewards` does not exist!", otherQuestId, dungeonId);
otherQuestId = 0;
}
if (shortageQuestId && !sObjectMgr->GetQuestTemplate(shortageQuestId))
{
TC_LOG_ERROR("sql.sql", "Shortage quest %u specified for dungeon %u in table `lfg_dungeon_rewards` does not exist!", shortageQuestId, dungeonId);
shortageQuestId = 0;
}
RewardMapStore.insert(LfgRewardContainer::value_type(dungeonId, new LfgReward(maxLevel, firstQuestId, otherQuestId, shortageQuestId, completionsPerPeriod, dailyReset)));
++count;
}
while (result->NextRow());
TC_LOG_INFO("server.loading", ">> Loaded %u lfg dungeon rewards in %u ms", count, GetMSTimeDiffToNow(oldMSTime));
}
LFGDungeonData const* LFGMgr::GetLFGDungeon(uint32 id)
{
LFGDungeonContainer::const_iterator itr = LfgDungeonStore.find(id);
if (itr != LfgDungeonStore.end())
return &(itr->second);
return nullptr;
}
void LFGMgr::LoadLFGDungeons(bool reload /* = false */)
{
uint32 oldMSTime = getMSTime();
LfgDungeonStore.clear();
// Initialize Dungeon map with data from dbcs
for (uint32 i = 0; i < sLFGDungeonStore.GetNumRows(); ++i)
{
LFGDungeonEntry const* dungeon = sLFGDungeonStore.LookupEntry(i);
if (!dungeon)
continue;
switch (dungeon->TypeID)
{
case LFG_TYPE_DUNGEON:
case LFG_TYPE_HEROIC:
case LFG_TYPE_RAID:
LfgDungeonStore.insert(LFGDungeonContainer::value_type(dungeon->ID, LFGDungeonData(dungeon)));
break;
case LFG_TYPE_RANDOM:
LfgDungeonStore.insert(LFGDungeonContainer::value_type(dungeon->ID, LFGDungeonData(dungeon)));
ShortageRoleMaskStore[dungeon->ID] = 0;
break;
}
}
// Fill teleport locations from DB
QueryResult result = WorldDatabase.Query("SELECT dungeonId, position_x, position_y, position_z, orientation, requiredItemLevel FROM lfg_dungeon_template");
if (!result)
{
TC_LOG_ERROR("server.loading", ">> Loaded 0 lfg dungeon templates. DB table `lfg_dungeon_template` is empty!");
return;
}
uint32 count = 0;
do
{
Field* fields = result->Fetch();
uint32 dungeonId = fields[0].GetUInt32();
LFGDungeonContainer::iterator dungeonItr = LfgDungeonStore.find(dungeonId);
if (dungeonItr == LfgDungeonStore.end())
{
TC_LOG_ERROR("sql.sql", "table `lfg_dungeon_template` contains coordinates for wrong dungeon %u", dungeonId);
continue;
}
LFGDungeonData& data = dungeonItr->second;
data.x = fields[1].GetFloat();
data.y = fields[2].GetFloat();
data.z = fields[3].GetFloat();
data.o = fields[4].GetFloat();
data.requiredItemLevel = fields[5].GetUInt16();
++count;
}
while (result->NextRow());
TC_LOG_INFO("server.loading", ">> Loaded %u lfg dungeon templates in %u ms", count, GetMSTimeDiffToNow(oldMSTime));
// Fill all other teleport coords from areatriggers
for (LFGDungeonContainer::iterator itr = LfgDungeonStore.begin(); itr != LfgDungeonStore.end(); ++itr)
{
LFGDungeonData& dungeon = itr->second;
// No teleport coords in database, load from areatriggers
if (dungeon.type != LFG_TYPE_RANDOM && dungeon.x == 0.0f && dungeon.y == 0.0f && dungeon.z == 0.0f)
{
AreaTriggerStruct const* at = sObjectMgr->GetMapEntranceTrigger(dungeon.map);
if (!at)
{
TC_LOG_ERROR("sql.sql", "Failed to load dungeon %s (Id: %u), cant find areatrigger for map %u", dungeon.name.c_str(), dungeon.id, dungeon.map);
continue;
}
dungeon.map = at->target_mapId;
dungeon.x = at->target_X;
dungeon.y = at->target_Y;
dungeon.z = at->target_Z;
dungeon.o = at->target_Orientation;
}
if (dungeon.type == LFG_TYPE_RANDOM)
AddDungeonsFromGroupingMap(CachedDungeonMapStore, dungeon.group, dungeon.id);
else
CachedDungeonMapStore[dungeon.group].insert(dungeon.id);
CachedDungeonMapStore[0].insert(dungeon.id);
}
if (reload)
CachedDungeonMapStore.clear();
}
LFGMgr* LFGMgr::instance()
{
static LFGMgr instance;
return &instance;
}
void LFGMgr::Update(uint32 diff)
{
if (!isOptionEnabled(LFG_OPTION_ENABLE_DUNGEON_FINDER | LFG_OPTION_ENABLE_RAID_BROWSER))
return;
time_t currTime = GameTime::GetGameTime();
// Remove obsolete role checks
for (LfgRoleCheckContainer::iterator it = RoleChecksStore.begin(); it != RoleChecksStore.end();)
{
LfgRoleCheckContainer::iterator itRoleCheck = it++;
LfgRoleCheck& roleCheck = itRoleCheck->second;
if (currTime < roleCheck.cancelTime)
continue;
roleCheck.state = LFG_ROLECHECK_MISSING_ROLE;
for (LfgRolesMap::const_iterator itRoles = roleCheck.roles.begin(); itRoles != roleCheck.roles.end(); ++itRoles)
{
ObjectGuid guid = itRoles->first;
RestoreState(guid, "Remove Obsolete RoleCheck");
SendLfgRoleCheckUpdate(guid, roleCheck);
if (guid == roleCheck.leader)
SendLfgJoinResult(guid, LfgJoinResultData(LFG_JOIN_ROLE_CHECK_FAILED, LFG_ROLECHECK_MISSING_ROLE));
}
RestoreState(itRoleCheck->first, "Remove Obsolete RoleCheck");
RoleChecksStore.erase(itRoleCheck);
}
// Remove obsolete proposals
for (LfgProposalContainer::iterator it = ProposalsStore.begin(); it != ProposalsStore.end();)
{
LfgProposalContainer::iterator itRemove = it++;
if (itRemove->second.cancelTime < currTime)
RemoveProposal(itRemove, LFG_UPDATETYPE_PROPOSAL_FAILED);
}
// Remove obsolete kicks
for (LfgPlayerBootContainer::iterator it = BootsStore.begin(); it != BootsStore.end();)
{
LfgPlayerBootContainer::iterator itBoot = it++;
LfgPlayerBoot& boot = itBoot->second;
if (boot.cancelTime < currTime)
{
boot.inProgress = false;
for (LfgAnswerContainer::const_iterator itVotes = boot.votes.begin(); itVotes != boot.votes.end(); ++itVotes)
{
ObjectGuid pguid = itVotes->first;
if (pguid != boot.victim)
SendLfgBootProposalUpdate(pguid, boot);
}
SetVoteKick(itBoot->first, false);
BootsStore.erase(itBoot);
}
}
uint32 lastProposalId = m_lfgProposalId;
// Check if a proposal can be formed with the new groups being added
for (LfgQueueContainer::iterator it = QueuesStore.begin(); it != QueuesStore.end(); ++it)
if (uint8 newProposals = it->second.FindGroups())
TC_LOG_DEBUG("lfg.update", "Found %u new groups in queue %u", newProposals, it->first);
if (lastProposalId != m_lfgProposalId)
{
// FIXME lastProposalId ? lastProposalId +1 ?
for (LfgProposalContainer::const_iterator itProposal = ProposalsStore.find(m_lfgProposalId); itProposal != ProposalsStore.end(); ++itProposal)
{
uint32 proposalId = itProposal->first;
LfgProposal& proposal = ProposalsStore[proposalId];
ObjectGuid guid;
for (LfgProposalPlayerContainer::const_iterator itPlayers = proposal.players.begin(); itPlayers != proposal.players.end(); ++itPlayers)
{
guid = itPlayers->first;
SetState(guid, LFG_STATE_PROPOSAL);
if (ObjectGuid gguid = GetGroup(guid))
{
SetState(gguid, LFG_STATE_PROPOSAL);
SendLfgUpdateStatus(guid, LfgUpdateData(LFG_UPDATETYPE_PROPOSAL_BEGIN, GetSelectedDungeons(guid), GetComment(guid)), true);
}
else
SendLfgUpdateStatus(guid, LfgUpdateData(LFG_UPDATETYPE_PROPOSAL_BEGIN, GetSelectedDungeons(guid), GetComment(guid)), false);
SendLfgUpdateProposal(guid, proposal);
}
if (proposal.state == LFG_PROPOSAL_SUCCESS)
UpdateProposal(proposalId, guid, true);
}
}
// Update all players status queue info and shortage status
if (m_QueueTimer > LFG_QUEUEUPDATE_INTERVAL)
{
m_QueueTimer = 0;
LfgQueueRoleContainer rolesPerDungeonId;
for (LfgQueueContainer::iterator it = QueuesStore.begin(); it != QueuesStore.end(); ++it)
it->second.UpdateQueueTimers(it->first, currTime, rolesPerDungeonId);
if (isOptionEnabled(LFG_OPTION_ENABLE_SHORTAGE_REWARDS))
{
// Update shortages
for (LFGDungeonEntry const* dungeon : sLFGDungeonStore)
{
if (dungeon->TypeID != LFG_TYPE_RANDOM)
continue;
uint32 dpsCount = 0;
uint32 tankCount = 0;
uint32 healerCount = 0;
for (auto it : rolesPerDungeonId)
{
dpsCount += it.second.currentDps;
healerCount += it.second.currentHealers;
tankCount += it.second.currentTanks;
}
uint32 dpsCountAbsolute = dpsCount ? std::floor(dpsCount / 3) : 0;
uint32 roleMask = 0;
if (dpsCountAbsolute >= tankCount || healerCount >= tankCount)
roleMask |= PLAYER_ROLE_TANK;
if (dpsCountAbsolute >= healerCount || tankCount >= healerCount)
roleMask |= PLAYER_ROLE_HEALER;
if (dpsCountAbsolute < tankCount && dpsCountAbsolute < healerCount)
roleMask |= PLAYER_ROLE_DAMAGE;
SetShortageRoleMask(dungeon->ID, roleMask);
}
}
}
else
m_QueueTimer += diff;
}
/**
Adds the player/group to lfg queue. If player is in a group then it is the leader
of the group tying to join the group. Join conditions are checked before adding
to the new queue.
@param[in] player Player trying to join (or leader of group trying to join)
@param[in] roles Player selected roles
@param[in] dungeons Dungeons the player/group is applying for
@param[in] comment Player selected comment
*/
void LFGMgr::JoinLfg(Player* player, uint8 roles, LfgDungeonSet& dungeons, const std::string& comment)
{
if (!player || !player->GetSession() || dungeons.empty())
return;
Group* grp = player->GetGroup();
ObjectGuid guid = player->GetGUID();
ObjectGuid gguid = grp ? grp->GetGUID() : guid;
LfgJoinResultData joinData;
GuidSet players;
uint32 rDungeonId = 0;
bool isContinue = grp && grp->isLFGGroup() && GetState(gguid) != LFG_STATE_FINISHED_DUNGEON;
// Do not allow to change dungeon in the middle of a current dungeon
if (isContinue)
{
dungeons.clear();
dungeons.insert(GetDungeon(gguid));
}
// Already in queue?
LfgState state = GetState(gguid);
if (state == LFG_STATE_QUEUED)
{
LFGQueue& queue = GetQueue(gguid);
queue.RemoveFromQueue(gguid);
}
// Check player or group member restrictions
if (!player->GetSession()->HasPermission(rbac::RBAC_PERM_JOIN_DUNGEON_FINDER))
joinData.result = LFG_JOIN_NOT_MEET_REQS;
else if (player->InBattleground() || player->InArena() || player->InBattlegroundQueue())
joinData.result = LFG_JOIN_USING_BG_SYSTEM;
else if (player->HasAura(LFG_SPELL_DUNGEON_DESERTER))
joinData.result = LFG_JOIN_DESERTER;
else if (!isContinue && player->HasAura(LFG_SPELL_DUNGEON_COOLDOWN))
joinData.result = LFG_JOIN_RANDOM_COOLDOWN;
else if (dungeons.empty())
joinData.result = LFG_JOIN_NOT_MEET_REQS;
else if (player->HasAura(9454)) // check Freeze debuff
joinData.result = LFG_JOIN_NOT_MEET_REQS;
else if (!CanPerformSelectedRoles(player->getClass(), roles))
joinData.result = LFG_JOIN_INTERNAL_ERROR;
else if (grp)
{
if (grp->GetMembersCount() > MAXGROUPSIZE)
joinData.result = LFG_JOIN_TOO_MUCH_MEMBERS;
else
{
uint8 memberCount = 0;
for (GroupReference* itr = grp->GetFirstMember(); itr != nullptr && joinData.result == LFG_JOIN_OK; itr = itr->next())
{
if (Player* plrg = itr->GetSource())
{
if (!plrg->GetSession()->HasPermission(rbac::RBAC_PERM_JOIN_DUNGEON_FINDER))
joinData.result = LFG_JOIN_INTERNAL_ERROR;
if (plrg->HasAura(LFG_SPELL_DUNGEON_DESERTER))
joinData.result = LFG_JOIN_PARTY_DESERTER;
else if (!isContinue && plrg->HasAura(LFG_SPELL_DUNGEON_COOLDOWN))
joinData.result = LFG_JOIN_PARTY_RANDOM_COOLDOWN;
else if (plrg->InBattleground() || plrg->InArena() || plrg->InBattlegroundQueue())
joinData.result = LFG_JOIN_USING_BG_SYSTEM;
++memberCount;
players.insert(plrg->GetGUID());
}
}
if (joinData.result == LFG_JOIN_OK && memberCount != grp->GetMembersCount())
joinData.result = LFG_JOIN_DISCONNECTED;
}
}
else
players.insert(player->GetGUID());
// Check if all dungeons are valid
bool isRaid = false;
if (joinData.result == LFG_JOIN_OK)
{
bool isDungeon = false;
for (LfgDungeonSet::const_iterator it = dungeons.begin(); it != dungeons.end() && joinData.result == LFG_JOIN_OK; ++it)
{
LfgType type = GetDungeonType(*it);
switch (type)
{
case LFG_TYPE_RAID:
if (isDungeon)
joinData.result = LFG_JOIN_MIXED_RAID_DUNGEON;
isRaid = true;
break;
case LFG_TYPE_RANDOM:
if (dungeons.size() > 1) // Only allow 1 random dungeon
joinData.result = LFG_JOIN_DUNGEON_INVALID;
else
rDungeonId = (*dungeons.begin());
[[fallthrough]];
case LFG_TYPE_HEROIC:
case LFG_TYPE_DUNGEON:
if (isRaid)
joinData.result = LFG_JOIN_MIXED_RAID_DUNGEON;
isDungeon = true;
break;
default:
joinData.result = LFG_JOIN_DUNGEON_INVALID;
break;
}
}
// it could be changed
if (joinData.result == LFG_JOIN_OK)
{
// Expand random dungeons and check restrictions
if (rDungeonId)
dungeons = GetDungeonsByRandom(rDungeonId);
// if we have lockmap then there are no compatible dungeons
GetCompatibleDungeons(dungeons, players, joinData.lockmap, isContinue);
if (dungeons.empty())
joinData.result = grp ? LFG_JOIN_INTERNAL_ERROR : LFG_JOIN_NOT_MEET_REQS;
}
}
// Can't join. Send result
if (joinData.result != LFG_JOIN_OK)
{
TC_LOG_DEBUG("lfg.join", "%s joining with %u members. Result: %u, Dungeons: %s",
guid.ToString().c_str(), grp ? grp->GetMembersCount() : 1, joinData.result, ConcatenateDungeons(dungeons).c_str());
if (!dungeons.empty()) // Only should show lockmap when have no dungeons available
joinData.lockmap.clear();
player->GetSession()->SendLfgJoinResult(joinData);
return;
}
SetComment(guid, comment);
if (rDungeonId && !grp && GetShortageRoleMask(rDungeonId) & roles)
SetEnligibleForShortageRewards(guid, true);
WorldPackets::LFG::RideTicket ticket;
ticket.RequesterGuid = guid;
ticket.Id = GetQueueId(gguid);
ticket.Type = WorldPackets::LFG::RideType::Lfg;
ticket.Time = int32(GameTime::GetGameTime());
std::string debugNames = "";
if (grp) // Begin rolecheck
{
// Create new rolecheck
LfgRoleCheck& roleCheck = RoleChecksStore[gguid];
roleCheck.cancelTime = GameTime::GetGameTime() + LFG_TIME_ROLECHECK;
roleCheck.state = LFG_ROLECHECK_INITIALITING;
roleCheck.leader = guid;
roleCheck.dungeons = dungeons;
roleCheck.rDungeonId = rDungeonId;
if (rDungeonId)
{
dungeons.clear();
dungeons.insert(rDungeonId);
}
SetState(gguid, LFG_STATE_ROLECHECK);
// Send update to player
LfgUpdateData updateData = LfgUpdateData(LFG_UPDATETYPE_JOIN_QUEUE, dungeons, comment);
for (GroupReference* itr = grp->GetFirstMember(); itr != nullptr; itr = itr->next())
{
if (Player* plrg = itr->GetSource())
{
ObjectGuid pguid = plrg->GetGUID();
plrg->GetSession()->SendLfgUpdateStatus(updateData, true);
SetState(pguid, LFG_STATE_ROLECHECK);
SetTicket(pguid, ticket);
if (!isContinue)
SetSelectedDungeons(pguid, dungeons);
roleCheck.roles[pguid] = 0;
if (!debugNames.empty())
debugNames.append(", ");
debugNames.append(plrg->GetName());
}
}
// Update leader role
UpdateRoleCheck(gguid, guid, roles);
}
else // Add player to queue
{
LfgRolesMap rolesMap;
rolesMap[guid] = roles;
LFGQueue& queue = GetQueue(guid);
queue.AddQueueData(guid, GameTime::GetGameTime(), dungeons, rolesMap);
if (!isContinue)
{
if (rDungeonId)
{
dungeons.clear();
dungeons.insert(rDungeonId);
}
SetSelectedDungeons(guid, dungeons);
}
// Send update to player
SetTicket(guid, ticket);
SetRoles(guid, roles);
player->GetSession()->SendLfgUpdateStatus(LfgUpdateData(LFG_UPDATETYPE_JOIN_QUEUE_INITIAL, dungeons, comment), false);
SetState(guid, isRaid ? LFG_STATE_RAIDBROWSER : LFG_STATE_QUEUED);
player->GetSession()->SendLfgUpdateStatus(LfgUpdateData(isRaid ? LFG_UPDATETYPE_JOIN_RAIDBROWSER : LFG_UPDATETYPE_ADDED_TO_QUEUE, dungeons, comment), false);
player->GetSession()->SendLfgJoinResult(joinData);
debugNames.append(player->GetName());
}
TC_LOG_DEBUG("lfg.join", "%s joined (%s), Members: %s. Dungeons (%u): %s", guid.ToString().c_str(),
grp ? "group" : "player", debugNames.c_str(), uint32(dungeons.size()), ConcatenateDungeons(dungeons).c_str());
}
/**
Leaves Dungeon System. Player/Group is removed from queue, rolechecks, proposals
or votekicks. Player or group needs to be not nullptr and using Dungeon System
@param[in] guid Player or group guid
*/
void LFGMgr::LeaveLfg(ObjectGuid guid, bool disconnected)
{
ObjectGuid gguid = guid.IsGroup() ? guid : GetGroup(guid);
TC_LOG_DEBUG("lfg.leave", "%s left (%s)", guid.ToString().c_str(), guid == gguid ? "group" : "player");
LfgState state = GetState(guid);
switch (state)
{
case LFG_STATE_QUEUED:
case LFG_STATE_RAIDBROWSER:
{
lfg::LfgUpdateType type = state == LFG_STATE_QUEUED ?
LFG_UPDATETYPE_REMOVED_FROM_QUEUE : LFG_UPDATETYPE_LEAVE_RAIDBROWSER;
if (gguid)
{
LfgState newState = LFG_STATE_NONE;
LfgState oldState = GetOldState(gguid);
// Set the new state to LFG_STATE_DUNGEON/LFG_STATE_FINISHED_DUNGEON if the group is already in a dungeon
// This is required in case a LFG group vote-kicks a player in a dungeon, queues, then leaves the queue (maybe to queue later again)
if (Group* group = sGroupMgr->GetGroupByGUID(gguid.GetCounter()))
if (group->isLFGGroup() && GetDungeon(gguid) && (oldState == LFG_STATE_DUNGEON || oldState == LFG_STATE_FINISHED_DUNGEON))
newState = oldState;
LFGQueue& queue = GetQueue(gguid);
queue.RemoveFromQueue(gguid);
SetState(gguid, newState);
GuidSet const& players = GetPlayers(gguid);
for (GuidSet::const_iterator it = players.begin(); it != players.end(); ++it)
{
SetState(*it, newState);
SendLfgUpdateStatus(*it, LfgUpdateData(type), true);
}
}
else
{
LFGQueue& queue = GetQueue(guid);
queue.RemoveFromQueue(guid);
SendLfgUpdateStatus(guid, LfgUpdateData(type), false);
SetState(guid, LFG_STATE_NONE);
}
break;
}
case LFG_STATE_ROLECHECK:
if (gguid)
UpdateRoleCheck(gguid); // No player to update role = LFG_ROLECHECK_ABORTED
break;
case LFG_STATE_PROPOSAL:
{
// Remove from Proposals
LfgProposalContainer::iterator it = ProposalsStore.begin();
ObjectGuid pguid = gguid == guid ? GetLeader(gguid) : guid;
while (it != ProposalsStore.end())
{
LfgProposalPlayerContainer::iterator itPlayer = it->second.players.find(pguid);
if (itPlayer != it->second.players.end())
{
// Mark the player/leader of group who left as didn't accept the proposal
itPlayer->second.accept = LFG_ANSWER_DENY;
break;
}
++it;
}
// Remove from queue - if proposal is found, RemoveProposal will call RemoveFromQueue
if (it != ProposalsStore.end())
RemoveProposal(it, LFG_UPDATETYPE_PROPOSAL_DECLINED);
break;
}
case LFG_STATE_NONE:
break;
case LFG_STATE_DUNGEON:
case LFG_STATE_FINISHED_DUNGEON:
if (guid != gguid && !disconnected) // Player
SetState(guid, LFG_STATE_NONE);
break;
}
SetEnligibleForShortageRewards(guid, false);
}
WorldPackets::LFG::RideTicket const* LFGMgr::GetTicket(ObjectGuid guid) const
{
auto itr = PlayersStore.find(guid);
if (itr != PlayersStore.end())
return &itr->second.GetTicket();
return nullptr;
}
/**
Update the Role check info with the player selected role.
@param[in] grp Group guid to update rolecheck
@param[in] guid Player guid (0 = rolecheck failed)
@param[in] roles Player selected roles
*/
void LFGMgr::UpdateRoleCheck(ObjectGuid gguid, ObjectGuid guid /* = ObjectGuid::Empty */, uint8 roles /* = PLAYER_ROLE_NONE */)
{
if (!gguid)
return;
LfgRolesMap check_roles;
LfgRoleCheckContainer::iterator itRoleCheck = RoleChecksStore.find(gguid);
if (itRoleCheck == RoleChecksStore.end())
return;
LfgRoleCheck& roleCheck = itRoleCheck->second;
bool sendRoleChosen = roleCheck.state != LFG_ROLECHECK_DEFAULT && guid;
LfgDungeonSet dungeons;
if (roleCheck.rDungeonId)
dungeons.insert(roleCheck.rDungeonId);
else
dungeons = roleCheck.dungeons;
LFGDungeonData const* dungeon = nullptr;
if (!dungeons.empty())
dungeon = sLFGMgr->GetLFGDungeon(*dungeons.begin());
if (!guid)
roleCheck.state = LFG_ROLECHECK_ABORTED;
else if (roles < PLAYER_ROLE_TANK) // Player selected no role.
roleCheck.state = LFG_ROLECHECK_NO_ROLE;
else
{
roleCheck.roles[guid] = roles;
// Check if all players have selected a role
LfgRolesMap::const_iterator itRoles = roleCheck.roles.begin();
while (itRoles != roleCheck.roles.end() && itRoles->second != PLAYER_ROLE_NONE)
++itRoles;
if (itRoles == roleCheck.roles.end())
{
// use temporal var to check roles, CheckGroupRoles modifies the roles
check_roles = roleCheck.roles;
roleCheck.state = (dungeon && CheckGroupRoles(check_roles, dungeon)) ? LFG_ROLECHECK_FINISHED : LFG_ROLECHECK_WRONG_ROLES;
}
}
LfgJoinResultData joinData = LfgJoinResultData(LFG_JOIN_ROLE_CHECK_FAILED, roleCheck.state);
for (LfgRolesMap::const_iterator it = roleCheck.roles.begin(); it != roleCheck.roles.end(); ++it)
{
ObjectGuid pguid = it->first;
if (sendRoleChosen)
SendLfgRoleChosen(pguid, guid, roles);
SendLfgRoleCheckUpdate(pguid, roleCheck);
switch (roleCheck.state)
{
case LFG_ROLECHECK_INITIALITING:
continue;
case LFG_ROLECHECK_FINISHED:
SetState(pguid, LFG_STATE_QUEUED);
SetRoles(pguid, it->second);
SendLfgUpdateStatus(pguid, LfgUpdateData(LFG_UPDATETYPE_ADDED_TO_QUEUE, dungeons, GetComment(pguid)), true);
break;
default:
if (roleCheck.leader == pguid)
SendLfgJoinResult(pguid, joinData);
SendLfgUpdateStatus(pguid, LfgUpdateData(LFG_UPDATETYPE_ROLECHECK_FAILED), true);
RestoreState(pguid, "Rolecheck Failed");
break;
}
}
if (roleCheck.state == LFG_ROLECHECK_FINISHED)
{
SetState(gguid, LFG_STATE_QUEUED);
LFGQueue& queue = GetQueue(gguid);
queue.AddQueueData(gguid, GameTime::GetGameTime(), roleCheck.dungeons, roleCheck.roles);
RoleChecksStore.erase(itRoleCheck);
}
else if (roleCheck.state != LFG_ROLECHECK_INITIALITING)
{
RestoreState(gguid, "Rolecheck Failed");
RoleChecksStore.erase(itRoleCheck);
}
}
/**
Given a list of dungeons remove the dungeons players have restrictions.
@param[in, out] dungeons Dungeons to check restrictions
@param[in] players Set of players to check their dungeon restrictions
@param[out] lockMap Map of players Lock status info of given dungeons (Empty if dungeons is not empty)
*/
void LFGMgr::GetCompatibleDungeons(LfgDungeonSet& dungeons, GuidSet const& players, LfgLockPartyMap& lockMap, bool isContinue)
{
lockMap.clear();
std::map<uint32, uint32> lockedDungeons;
for (GuidSet::const_iterator it = players.begin(); it != players.end() && !dungeons.empty(); ++it)
{
ObjectGuid guid = (*it);
LfgLockMap const& cachedLockMap = GetLockedDungeons(guid);
Player* player = ObjectAccessor::FindConnectedPlayer(guid);
for (LfgLockMap::const_iterator it2 = cachedLockMap.begin(); it2 != cachedLockMap.end() && !dungeons.empty(); ++it2)
{
uint32 dungeonId = (it2->first & 0x00FFFFFF); // Compare dungeon ids
LfgDungeonSet::iterator itDungeon = dungeons.find(dungeonId);
if (itDungeon != dungeons.end())
{
bool eraseDungeon = true;
// Don't remove the dungeon if team members are trying to continue a locked instance
if (it2->second.lockStatus == LFG_LOCKSTATUS_RAID_LOCKED && isContinue)
{
LFGDungeonData const* dungeon = GetLFGDungeon(dungeonId);
ASSERT(dungeon);
ASSERT(player);
if (InstancePlayerBind* playerBind = player->GetBoundInstance(dungeon->map, Difficulty(dungeon->difficulty)))
{
if (InstanceSave* playerSave = playerBind->save)
{
uint32 dungeonInstanceId = playerSave->GetInstanceId();
auto itLockedDungeon = lockedDungeons.find(dungeonId);
if (itLockedDungeon == lockedDungeons.end() || itLockedDungeon->second == dungeonInstanceId)
eraseDungeon = false;
lockedDungeons[dungeonId] = dungeonInstanceId;
}
}
}
if (eraseDungeon)
dungeons.erase(itDungeon);
lockMap[guid][dungeonId] = it2->second;
}
}
}
if (!dungeons.empty())
lockMap.clear();
}
/**
Check if a group can be formed with the given group roles
@param[in] groles Map of roles to check
@return True if roles are compatible
*/
bool LFGMgr::CheckGroupRoles(LfgRolesMap& groles, LFGDungeonData const* dungeon)
{
ASSERT(dungeon);
if (groles.empty())
return false;
uint8 damage = 0;
uint8 tank = 0;
uint8 healer = 0;
for (LfgRolesMap::iterator it = groles.begin(); it != groles.end(); ++it)
{
uint8 role = it->second & ~PLAYER_ROLE_LEADER;
if (role == PLAYER_ROLE_NONE)
return false;
if (role & PLAYER_ROLE_DAMAGE)
{
if (role != PLAYER_ROLE_DAMAGE)
{
it->second -= PLAYER_ROLE_DAMAGE;
if (CheckGroupRoles(groles, dungeon))
return true;
it->second += PLAYER_ROLE_DAMAGE;
}
else if (damage == dungeon->requiredDamageDealers)
return false;
else
damage++;
}
if (role & PLAYER_ROLE_HEALER)
{
if (role != PLAYER_ROLE_HEALER)
{
it->second -= PLAYER_ROLE_HEALER;
if (CheckGroupRoles(groles, dungeon))
return true;
it->second += PLAYER_ROLE_HEALER;
}
else if (healer == dungeon->requiredHealers)
return false;
else
healer++;
}
if (role & PLAYER_ROLE_TANK)
{
if (role != PLAYER_ROLE_TANK)
{
it->second -= PLAYER_ROLE_TANK;
if (CheckGroupRoles(groles, dungeon))
return true;
it->second += PLAYER_ROLE_TANK;
}
else if (tank == dungeon->requiredTanks)
return false;
else
tank++;
}
}
return (tank + healer + damage) == uint8(groles.size());
}
/**
Makes a new group given a proposal
@param[in] proposal Proposal to get info from
*/
void LFGMgr::MakeNewGroup(LfgProposal const& proposal)
{
GuidList players, tankPlayers, healPlayers, dpsPlayers;
GuidList playersToTeleport;
for (LfgProposalPlayerContainer::const_iterator it = proposal.players.begin(); it != proposal.players.end(); ++it)
{
ObjectGuid guid = it->first;
if (guid == proposal.leader)
players.push_back(guid);
else
switch (it->second.role & ~PLAYER_ROLE_LEADER)
{
case PLAYER_ROLE_TANK:
tankPlayers.push_back(guid);
break;
case PLAYER_ROLE_HEALER:
healPlayers.push_back(guid);
break;
case PLAYER_ROLE_DAMAGE:
dpsPlayers.push_back(guid);
break;
default:
ASSERT(false, "Invalid LFG role %u", it->second.role);
break;
}
if (proposal.isNew || GetGroup(guid) != proposal.group)
playersToTeleport.push_back(guid);
}
players.splice(players.end(), tankPlayers);
players.splice(players.end(), healPlayers);
players.splice(players.end(), dpsPlayers);
// Set the dungeon difficulty
LFGDungeonData const* dungeon = GetLFGDungeon(proposal.dungeonId);
ASSERT(dungeon);
Group* grp = proposal.group ? sGroupMgr->GetGroupByGUID(proposal.group.GetCounter()) : nullptr;
for (GuidList::const_iterator it = players.begin(); it != players.end(); ++it)
{
ObjectGuid pguid = (*it);
Player* player = ObjectAccessor::FindConnectedPlayer(pguid);
if (!player)
continue;
Group* group = player->GetGroup();
if (group && group != grp)
group->RemoveMember(player->GetGUID());
if (!grp)
{
grp = new Group();
if (dungeon->IsRaid())
grp->ConvertToLFR();
else
grp->ConvertToLFG();
grp->Create(player);
ObjectGuid gguid = grp->GetGUID();
SetState(gguid, LFG_STATE_PROPOSAL);
sGroupMgr->AddGroup(grp);
}
else if (group != grp)
grp->AddMember(player);
grp->SetLfgRoles(pguid, proposal.players.find(pguid)->second.role);
for (GuidList::const_iterator itr = players.begin(); itr != players.end(); ++itr)
{
ObjectGuid temppguid = (*itr);
player->GetSession()->SendNameQueryOpcode(temppguid);
}
// Add the cooldown spell if queued for a random dungeon
const LfgDungeonSet& dungeons = GetSelectedDungeons(player->GetGUID());
if (!dungeons.empty())
{
uint32 rDungeonId = (*dungeons.begin());
LFGDungeonEntry const* dungeon = sLFGDungeonStore.LookupEntry(rDungeonId);
if (dungeon && dungeon->TypeID == LFG_TYPE_RANDOM)
player->CastSpell(player, LFG_SPELL_DUNGEON_COOLDOWN, false);
}
}
ASSERT(grp);
if (dungeon->IsRaid())
grp->SetRaidDifficulty(Difficulty(dungeon->difficulty));
else
grp->SetDungeonDifficulty(Difficulty(dungeon->difficulty));
ObjectGuid gguid = grp->GetGUID();
SetDungeon(gguid, dungeon->Entry());
SetState(gguid, LFG_STATE_DUNGEON);
_SaveToDB(gguid, grp->GetDbStoreId());
// Update group info
grp->SendUpdate();
// Teleport Player
for (GuidList::const_iterator it = playersToTeleport.begin(); it != playersToTeleport.end(); ++it)
if (Player* player = ObjectAccessor::FindPlayer(*it))
TeleportPlayer(player, false);
}
uint32 LFGMgr::AddProposal(LfgProposal& proposal)
{
proposal.id = ++m_lfgProposalId;
ProposalsStore[m_lfgProposalId] = proposal;
return m_lfgProposalId;
}
/**
Update Proposal info with player answer
@param[in] proposalId Proposal id to be updated
@param[in] guid Player guid to update answer
@param[in] accept Player answer
*/
void LFGMgr::UpdateProposal(uint32 proposalId, ObjectGuid guid, bool accept)
{
// Check if the proposal exists
LfgProposalContainer::iterator itProposal = ProposalsStore.find(proposalId);
if (itProposal == ProposalsStore.end())
return;
LfgProposal& proposal = itProposal->second;
// Check if proposal have the current player
LfgProposalPlayerContainer::iterator itProposalPlayer = proposal.players.find(guid);
if (itProposalPlayer == proposal.players.end())
return;
LfgProposalPlayer& player = itProposalPlayer->second;
player.accept = LfgAnswer(accept);
TC_LOG_DEBUG("lfg.proposal.update", "%s, Proposal %u, Selection: %u", guid.ToString().c_str(), proposalId, accept);
if (!accept)
{
RemoveProposal(itProposal, LFG_UPDATETYPE_PROPOSAL_DECLINED);
return;
}
// check if all have answered and reorder players (leader first)
bool allAnswered = true;
for (LfgProposalPlayerContainer::const_iterator itPlayers = proposal.players.begin(); itPlayers != proposal.players.end(); ++itPlayers)
if (itPlayers->second.accept != LFG_ANSWER_AGREE) // No answer (-1) or not accepted (0)
allAnswered = false;
if (!allAnswered)
{
for (LfgProposalPlayerContainer::const_iterator it = proposal.players.begin(); it != proposal.players.end(); ++it)
SendLfgUpdateProposal(it->first, proposal);
return;
}
bool sendUpdate = proposal.state != LFG_PROPOSAL_SUCCESS;
proposal.state = LFG_PROPOSAL_SUCCESS;
time_t joinTime = GameTime::GetGameTime();
LFGQueue& queue = GetQueue(guid);
LfgUpdateData updateData = LfgUpdateData(LFG_UPDATETYPE_GROUP_FOUND, GetSelectedDungeons(guid), GetComment(guid));
for (LfgProposalPlayerContainer::const_iterator it = proposal.players.begin(); it != proposal.players.end(); ++it)
{
ObjectGuid pguid = it->first;
ObjectGuid gguid = it->second.group;
uint32 dungeonId = (*GetSelectedDungeons(pguid).begin());
int32 waitTime = -1;
if (sendUpdate)
SendLfgUpdateProposal(pguid, proposal);
if (gguid)
{
waitTime = int32((joinTime - queue.GetJoinTime(gguid)) / IN_MILLISECONDS);
SendLfgUpdateStatus(pguid, updateData, true);
}
else
{
waitTime = int32((joinTime - queue.GetJoinTime(pguid)) / IN_MILLISECONDS);
SendLfgUpdateStatus(pguid, updateData, false);
}
// Update timers
uint8 role = GetRoles(pguid);
role &= ~PLAYER_ROLE_LEADER;
switch (role)
{
case PLAYER_ROLE_DAMAGE:
queue.UpdateWaitTimeDps(waitTime, dungeonId);
break;
case PLAYER_ROLE_HEALER:
queue.UpdateWaitTimeHealer(waitTime, dungeonId);
break;
case PLAYER_ROLE_TANK:
queue.UpdateWaitTimeTank(waitTime, dungeonId);
break;
default:
queue.UpdateWaitTimeAvg(waitTime, dungeonId);
break;
}
SetState(pguid, LFG_STATE_DUNGEON);
}
// Remove players/groups from Queue
for (GuidList::const_iterator it = proposal.queues.begin(); it != proposal.queues.end(); ++it)
queue.RemoveFromQueue(*it);
MakeNewGroup(proposal);
ProposalsStore.erase(itProposal);
}
/**
Remove a proposal from the pool, remove the group that didn't accept (if needed) and readd the other members to the queue
@param[in] itProposal Iterator to the proposal to remove
@param[in] type Type of removal (LFG_UPDATETYPE_PROPOSAL_FAILED, LFG_UPDATETYPE_PROPOSAL_DECLINED)
*/
void LFGMgr::RemoveProposal(LfgProposalContainer::iterator itProposal, LfgUpdateType type)
{
LfgProposal& proposal = itProposal->second;
proposal.state = LFG_PROPOSAL_FAILED;
TC_LOG_DEBUG("lfg.proposal.remove", "Proposal %u, state FAILED, UpdateType %u", itProposal->first, type);
// Mark all people that didn't answered as no accept
if (type == LFG_UPDATETYPE_PROPOSAL_FAILED)
for (LfgProposalPlayerContainer::iterator it = proposal.players.begin(); it != proposal.players.end(); ++it)
if (it->second.accept == LFG_ANSWER_PENDING)
it->second.accept = LFG_ANSWER_DENY;
// Mark players/groups to be removed
GuidSet toRemove;
for (LfgProposalPlayerContainer::iterator it = proposal.players.begin(); it != proposal.players.end(); ++it)
{
if (it->second.accept == LFG_ANSWER_AGREE)
continue;
ObjectGuid guid = it->second.group ? it->second.group : it->first;
// Player didn't accept or still pending when no secs left
if (it->second.accept == LFG_ANSWER_DENY || type == LFG_UPDATETYPE_PROPOSAL_FAILED)
{
it->second.accept = LFG_ANSWER_DENY;
toRemove.insert(guid);
}
}
// Notify players
for (LfgProposalPlayerContainer::const_iterator it = proposal.players.begin(); it != proposal.players.end(); ++it)
{
ObjectGuid guid = it->first;
ObjectGuid gguid = it->second.group ? it->second.group : guid;
SendLfgUpdateProposal(guid, proposal);
if (toRemove.find(gguid) != toRemove.end()) // Didn't accept or in same group that someone that didn't accept
{
LfgUpdateData updateData;
if (it->second.accept == LFG_ANSWER_DENY)
{
updateData.updateType = type;
TC_LOG_DEBUG("lfg.proposal.remove", "%s didn't accept. Removing from queue and compatible cache", guid.ToString().c_str());
}
else
{
updateData.updateType = LFG_UPDATETYPE_REMOVED_FROM_QUEUE;
TC_LOG_DEBUG("lfg.proposal.remove", "%s in same group that someone that didn't accept. Removing from queue and compatible cache", guid.ToString().c_str());
}
RestoreState(guid, "Proposal Fail (didn't accepted or in group with someone that didn't accept");
if (gguid != guid)
{
RestoreState(it->second.group, "Proposal Fail (someone in group didn't accepted)");
SendLfgUpdateStatus(guid, updateData, true);
}
else
SendLfgUpdateStatus(guid, updateData, false);
}
else
{
TC_LOG_DEBUG("lfg.proposal.remove", "Readding %s to queue.", guid.ToString().c_str());
SetState(guid, LFG_STATE_QUEUED);
if (gguid != guid)
{
SetState(gguid, LFG_STATE_QUEUED);
SendLfgUpdateStatus(guid, LfgUpdateData(LFG_UPDATETYPE_ADDED_TO_QUEUE, GetSelectedDungeons(guid), GetComment(guid)), true);
}
else
SendLfgUpdateStatus(guid, LfgUpdateData(LFG_UPDATETYPE_ADDED_TO_QUEUE, GetSelectedDungeons(guid), GetComment(guid)), false);
}
}
LFGQueue& queue = GetQueue(proposal.players.begin()->first);
// Remove players/groups from queue
for (GuidSet::const_iterator it = toRemove.begin(); it != toRemove.end(); ++it)
{
ObjectGuid guid = *it;
queue.RemoveFromQueue(guid);
proposal.queues.remove(guid);
}
// Readd to queue
for (GuidList::const_iterator it = proposal.queues.begin(); it != proposal.queues.end(); ++it)
{
ObjectGuid guid = *it;
queue.AddToQueue(guid, true);
}
ProposalsStore.erase(itProposal);
}
/**
Initialize a boot kick vote
@param[in] gguid Group the vote kicks belongs to
@param[in] kicker Kicker guid
@param[in] victim Victim guid
@param[in] reason Kick reason
*/
void LFGMgr::InitBoot(ObjectGuid gguid, ObjectGuid kicker, ObjectGuid victim, std::string const& reason)
{
SetVoteKick(gguid, true);
LfgPlayerBoot& boot = BootsStore[gguid];
boot.inProgress = true;
boot.cancelTime = GameTime::GetGameTime() + LFG_TIME_BOOT;
boot.reason = reason;
boot.victim = victim;
GuidSet const& players = GetPlayers(gguid);
// Set votes
for (GuidSet::const_iterator itr = players.begin(); itr != players.end(); ++itr)
{
ObjectGuid guid = (*itr);
boot.votes[guid] = LFG_ANSWER_PENDING;
}
boot.votes[victim] = LFG_ANSWER_DENY; // Victim auto vote NO
boot.votes[kicker] = LFG_ANSWER_AGREE; // Kicker auto vote YES
// Notify players
for (GuidSet::const_iterator it = players.begin(); it != players.end(); ++it)
SendLfgBootProposalUpdate(*it, boot);
}
/**
Update Boot info with player answer
@param[in] guid Player who has answered
@param[in] player answer
*/
void LFGMgr::UpdateBoot(ObjectGuid guid, bool accept)
{
ObjectGuid gguid = GetGroup(guid);
if (!gguid)
return;
LfgPlayerBootContainer::iterator itBoot = BootsStore.find(gguid);
if (itBoot == BootsStore.end())
return;
LfgPlayerBoot& boot = itBoot->second;
if (boot.votes[guid] != LFG_ANSWER_PENDING) // Cheat check: Player can't vote twice
return;
boot.votes[guid] = LfgAnswer(accept);
uint8 votesNum = 0;
uint8 agreeNum = 0;
for (LfgAnswerContainer::const_iterator itVotes = boot.votes.begin(); itVotes != boot.votes.end(); ++itVotes)
{
if (itVotes->second != LFG_ANSWER_PENDING)
{
++votesNum;
if (itVotes->second == LFG_ANSWER_AGREE)
++agreeNum;
}
}
bool raidFinderGroup = false;
if (Group* group = sGroupMgr->GetGroupByGUID(gguid.GetCounter()))
if (group->isLFRGroup())
raidFinderGroup = true;
// if we don't have enough votes (agree or deny) do nothing
if (agreeNum < (raidFinderGroup ? LFR_GROUP_KICK_VOTES_NEEDED : LFG_GROUP_KICK_VOTES_NEEDED)
&& (votesNum - agreeNum) < (raidFinderGroup ? LFR_GROUP_KICK_VOTES_NEEDED : LFG_GROUP_KICK_VOTES_NEEDED))
return;
// Send update info to all players
boot.inProgress = false;
for (LfgAnswerContainer::const_iterator itVotes = boot.votes.begin(); itVotes != boot.votes.end(); ++itVotes)
{
ObjectGuid pguid = itVotes->first;
if (pguid != boot.victim)
SendLfgBootProposalUpdate(pguid, boot);
}
SetVoteKick(gguid, false);
if (agreeNum == (raidFinderGroup ? LFR_GROUP_KICK_VOTES_NEEDED : LFG_GROUP_KICK_VOTES_NEEDED)) // Vote passed - Kick player
{
if (Group* group = sGroupMgr->GetGroupByGUID(gguid.GetCounter()))
Player::RemoveFromGroup(group, boot.victim, GROUP_REMOVEMETHOD_KICK_LFG);
DecreaseKicksLeft(gguid);
}
BootsStore.erase(itBoot);
}
/**
Teleports the player in or out the dungeon
@param[in] player Player to teleport
@param[in] out Teleport out (true) or in (false)
@param[in] fromOpcode Function called from opcode handlers? (Default false)
*/
void LFGMgr::TeleportPlayer(Player* player, bool out, bool fromOpcode /*= false*/, bool saveEntryPoint /*= true*/)
{
LFGDungeonData const* dungeon = nullptr;
Group* group = player->GetGroup();
if (group && group->isLFGGroup())
dungeon = GetLFGDungeon(GetDungeon(group->GetGUID()));
if (!dungeon)
{
TC_LOG_DEBUG("lfg.teleport", "Player %s not in group/lfggroup or dungeon not found!",
player->GetName().c_str());
player->GetSession()->SendLfgTeleportError(LFG_TELEPORT_RESULT_NO_RETURN_LOCATION);
return;
}
if (out)
{
TC_LOG_DEBUG("lfg.teleport", "Player %s is being teleported out. Current Map %u - Expected Map %u",
player->GetName().c_str(), player->GetMapId(), uint32(dungeon->map));
if (player->GetMapId() == uint32(dungeon->map))
player->TeleportToBGEntryPoint();
return;
}
LfgTeleportResult error = LFG_TELEPORT_RESULT_NONE;
if (!player->IsAlive())
error = LFG_TELEPORT_RESULT_DEAD;
else if (player->IsFalling() || player->HasUnitState(UNIT_STATE_JUMPING))
error = LFG_TELEPORT_RESULT_FALLING;
else if (player->IsMirrorTimerActive(FATIGUE_TIMER))
error = LFG_TELEPORT_RESULT_EXHAUSTION;
else if (player->GetVehicle())
error = LFG_TELEPORT_RESULT_ON_TRANSPORT;
else if (player->GetCharmedGUID())
error = LFG_TELEPORT_RESULT_IMMUNE_TO_SUMMONS;
else if (player->HasAura(9454)) // check Freeze debuff
error = LFG_TELEPORT_RESULT_NO_RETURN_LOCATION;
else if (player->GetMapId() != uint32(dungeon->map)) // Do not teleport players in dungeon to the entrance
{
uint32 mapid = dungeon->map;
float x = dungeon->x;
float y = dungeon->y;
float z = dungeon->z;
float orientation = dungeon->o;
if (!fromOpcode && saveEntryPoint)
{
// Select a player inside to be teleported to
for (GroupReference* itr = group->GetFirstMember(); itr != nullptr; itr = itr->next())
{
Player* plrg = itr->GetSource();
if (plrg && plrg != player && plrg->GetMapId() == uint32(dungeon->map))
{
mapid = plrg->GetMapId();
x = plrg->GetPositionX();
y = plrg->GetPositionY();
z = plrg->GetPositionZ();
orientation = plrg->GetOrientation();
break;
}
}
}
else if (player->HasValidLFGLeavePoint(mapid) && saveEntryPoint)
{
Position pos;
player->GetLFGLeavePoint(&pos);
x = pos.m_positionX;
y = pos.m_positionY;
z = pos.m_positionZ;
orientation = pos.GetOrientation();
}
if (!player->GetMap()->IsDungeon() && saveEntryPoint)
player->SetBattlegroundEntryPoint();
if (player->IsInFlight())
{
player->GetMotionMaster()->MovementExpired();
player->CleanupAfterTaxiFlight();
}
if (!player->TeleportTo(mapid, x, y, z, orientation))
error = LFG_TELEPORT_RESULT_NO_RETURN_LOCATION;
}
else
{
if (player->IsInCombat())
error = LFG_TELEPORT_RESULT_IMMUNE_TO_SUMMONS;
else if (player->GetMapId() == uint32(dungeon->map))
{
player->SetLFGLeavePoint();
player->TeleportToBGEntryPoint();
}
}
if (error != LFG_TELEPORT_RESULT_NONE)
player->GetSession()->SendLfgTeleportError(error);
TC_LOG_DEBUG("lfg.teleport", "Player %s is being teleported in to map %u "
"(x: %f, y: %f, z: %f) Result: %u", player->GetName().c_str(), dungeon->map,
dungeon->x, dungeon->y, dungeon->z, error);
}
/**
Finish a dungeon and give reward, if any.
@param[in] guid Group guid
@param[in] dungeonId Dungeonid
*/
void LFGMgr::FinishDungeon(ObjectGuid gguid, const uint32 dungeonId, Map const* currMap)
{
uint32 gDungeonId = GetDungeon(gguid);
if (gDungeonId != dungeonId)
{
TC_LOG_DEBUG("lfg.dungeon.finish", "Group %s finished dungeon %u but queued for %u", gguid.ToString().c_str(), dungeonId, gDungeonId);
return;
}
if (GetState(gguid) == LFG_STATE_FINISHED_DUNGEON) // Shouldn't happen. Do not reward multiple times
{
TC_LOG_DEBUG("lfg.dungeon.finish", "Group: %s already rewarded", gguid.ToString().c_str());
return;
}
SetState(gguid, LFG_STATE_FINISHED_DUNGEON);
GuidSet const& players = GetPlayers(gguid);
for (GuidSet::const_iterator it = players.begin(); it != players.end(); ++it)
{
ObjectGuid guid = (*it);
if (GetState(guid) == LFG_STATE_FINISHED_DUNGEON)
{
TC_LOG_DEBUG("lfg.dungeon.finish", "Group: %s, Player: %s already rewarded", gguid.ToString().c_str(), guid.ToString().c_str());
continue;
}
uint32 rDungeonId = 0;
const LfgDungeonSet& dungeons = GetSelectedDungeons(guid);
if (!dungeons.empty())
rDungeonId = (*dungeons.begin());
SetState(guid, LFG_STATE_FINISHED_DUNGEON);
SendLfgUpdateStatus(guid, LfgUpdateData(LFG_UPDATETYPE_DUNGEON_FINISHED, GetSelectedDungeons(guid), GetComment(guid)), true);
// Give rewards only if its a random dungeon
LFGDungeonData const* dungeon = GetLFGDungeon(rDungeonId);
if (!dungeon || (dungeon->type != LFG_TYPE_RANDOM && !dungeon->seasonal))
{
TC_LOG_DEBUG("lfg.dungeon.finish", "Group: %s, Player: %s dungeon %u is not random or seasonal", gguid.ToString().c_str(), guid.ToString().c_str(), rDungeonId);
continue;
}
Player* player = ObjectAccessor::FindPlayer(guid);
if (!player)
{
TC_LOG_DEBUG("lfg.dungeon.finish", "Group: %s, Player: %s not found in world", gguid.ToString().c_str(), guid.ToString().c_str());
continue;
}
if (player->FindMap() != currMap)
{
TC_LOG_DEBUG("lfg.dungeon.finish", "Group: %s, Player: %s is in a different map", gguid.ToString().c_str(), guid.ToString().c_str());
continue;
}
player->RemoveAurasDueToSpell(LFG_SPELL_DUNGEON_COOLDOWN);
LFGDungeonData const* dungeonDone = GetLFGDungeon(dungeonId);
uint32 mapId = dungeonDone ? uint32(dungeonDone->map) : 0;
if (player->GetMapId() != mapId)
{
TC_LOG_DEBUG("lfg.dungeon.finish", "Group: %s, Player: %s is in map %u and should be in %u to get reward", gguid.ToString().c_str(), guid.ToString().c_str(), player->GetMapId(), mapId);
continue;
}
// Update achievements
if (dungeon->difficulty == DUNGEON_DIFFICULTY_HEROIC)
player->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_USE_LFD_TO_GROUP_WITH_PLAYERS, 1);
LfgReward const* reward = GetRandomDungeonReward(rDungeonId, player->getLevel());
if (!reward)
continue;
bool firstReward = true;
Quest const* quest = sObjectMgr->GetQuestTemplate(reward->firstQuest);
if (!quest)
continue;
// CanRewardQuest to check currency caps, SatisfyFirstLFGReward to check weekly/daily reward caps for first quest
if (player->CanRewardQuest(quest, false) && player->SatisfyFirstLFGReward(rDungeonId, reward->completionsPerPeriod))
{
if (reward->completionsPerPeriod)
player->SetLFGRewardStatus(rDungeonId, reward->dailyReset);
player->RewardQuest(quest, 0, nullptr, false);
}
else
{
firstReward = false;
quest = sObjectMgr->GetQuestTemplate(reward->otherQuest);
if (!quest)
continue;
// we give reward without informing client (retail does this)
player->RewardQuest(quest, 0, nullptr, false);
}
Quest const* shortageQuest = nullptr;
if (IsEnligibleForShortageRewards(guid))
{
shortageQuest = sObjectMgr->GetQuestTemplate(reward->shortageQuest);
if (shortageQuest)
{
player->RewardQuest(shortageQuest, 0, nullptr, false);
SetEnligibleForShortageRewards(guid, false);
}
}
// Give rewards
TC_LOG_DEBUG("lfg.dungeon.finish", "Group: %s, Player: %s done dungeon %u, %s previously done.", gguid.ToString().c_str(), guid.ToString().c_str(), GetDungeon(gguid), !firstReward ? " " : " not");
LfgPlayerRewardData data = LfgPlayerRewardData(dungeon->Entry(), GetDungeon(gguid, false), !firstReward, quest, shortageQuest);
player->GetSession()->SendLfgPlayerReward(data);
}
}
// --------------------------------------------------------------------------//
// Auxiliar Functions
// --------------------------------------------------------------------------//
/**
Get the dungeon list that can be done given a random dungeon entry.
@param[in] randomdungeon Random dungeon id (if value = 0 will return all dungeons)
@returns Set of dungeons that can be done.
*/
LfgDungeonSet const& LFGMgr::GetDungeonsByRandom(uint32 randomdungeon)
{
LFGDungeonData const* dungeon = GetLFGDungeon(randomdungeon);
uint32 group = dungeon ? dungeon->group : 0;
return CachedDungeonMapStore[group];
}
/**
Get the reward of a given random dungeon at a certain level
@param[in] dungeon dungeon id
@param[in] level Player level
@returns Reward
*/
LfgReward const* LFGMgr::GetRandomDungeonReward(uint32 dungeon, uint8 level)
{
LfgReward const* rew = nullptr;
LfgRewardContainerBounds bounds = RewardMapStore.equal_range(dungeon & 0x00FFFFFF);
for (LfgRewardContainer::const_iterator itr = bounds.first; itr != bounds.second; ++itr)
{
rew = itr->second;
// ordered properly at loading
if (itr->second->maxLevel >= level)
break;
}
return rew;
}
/**
Given a Dungeon id returns the dungeon Type
@param[in] dungeon dungeon id
@returns Dungeon type
*/
LfgType LFGMgr::GetDungeonType(uint32 dungeonId)
{
LFGDungeonData const* dungeon = GetLFGDungeon(dungeonId);
if (!dungeon)
return LFG_TYPE_NONE;
return LfgType(dungeon->type);
}
LfgState LFGMgr::GetState(ObjectGuid guid)
{
LfgState state;
if (guid.IsGroup())
{
state = GroupsStore[guid].GetState();
TC_LOG_TRACE("lfg.data.group.state.get", "Group: %s, State: %s", guid.ToString().c_str(), GetStateString(state).c_str());
}
else
{
state = PlayersStore[guid].GetState();
TC_LOG_TRACE("lfg.data.player.state.get", "Player: %s, State: %s", guid.ToString().c_str(), GetStateString(state).c_str());
}
return state;
}
LfgState LFGMgr::GetOldState(ObjectGuid guid)
{
LfgState state;
if (guid.IsGroup())
{
state = GroupsStore[guid].GetOldState();
TC_LOG_TRACE("lfg.data.group.oldstate.get", "Group: %s, Old state: %u", guid.ToString().c_str(), state);
}
else
{
state = PlayersStore[guid].GetOldState();
TC_LOG_TRACE("lfg.data.player.oldstate.get", "Player: %s, Old state: %u", guid.ToString().c_str(), state);
}
return state;
}
bool LFGMgr::IsVoteKickActive(ObjectGuid gguid)
{
ASSERT(gguid.IsGroup());
bool active = GroupsStore[gguid].IsVoteKickActive();
TC_LOG_TRACE("lfg.data.group.votekick.get", "Group: %s, Active: %d", gguid.ToString().c_str(), active);
return active;
}
uint32 LFGMgr::GetDungeon(ObjectGuid guid, bool asId /*= true */)
{
uint32 dungeon = GroupsStore[guid].GetDungeon(asId);
TC_LOG_TRACE("lfg.data.group.dungeon.get", "Group: %s, asId: %u, Dungeon: %u", guid.ToString().c_str(), asId, dungeon);
return dungeon;
}
uint32 LFGMgr::GetDungeonMapId(ObjectGuid guid)
{
uint32 dungeonId = GroupsStore[guid].GetDungeon(true);
uint32 mapId = 0;
if (dungeonId)
if (LFGDungeonData const* dungeon = GetLFGDungeon(dungeonId))
mapId = dungeon->map;
TC_LOG_TRACE("lfg.data.group.dungeon.map", "Group: %s, MapId: %u (DungeonId: %u)", guid.ToString().c_str(), mapId, dungeonId);
return mapId;
}
uint32 LFGMgr::GetDungeonIdForDifficulty(uint32 dungeonId, Difficulty difficulty)
{
if (LFGDungeonData const* baseDungeon = GetLFGDungeon(dungeonId))
{
uint16 mapId = baseDungeon->map;
LfgDungeonSet const& dungeons = GetDungeonsByRandom(0);
for (LfgDungeonSet::const_iterator it = dungeons.begin(); it != dungeons.end(); ++it)
if (LFGDungeonData const* dungeon = GetLFGDungeon(*it))
if (dungeon->map == mapId && Difficulty(dungeon->difficulty) == difficulty)
return dungeon->id;
}
return 0;
}
uint8 LFGMgr::GetRoles(ObjectGuid guid)
{
uint8 roles = PlayersStore[guid].GetRoles();
TC_LOG_TRACE("lfg.data.player.role.get", "Player: %s, Role: %u", guid.ToString().c_str(), roles);
return roles;
}
const std::string& LFGMgr::GetComment(ObjectGuid guid)
{
TC_LOG_TRACE("lfg.data.player.comment.get", "Player: %s, Comment: %s", guid.ToString().c_str(), PlayersStore[guid].GetComment().c_str());
return PlayersStore[guid].GetComment();
}
LfgDungeonSet const& LFGMgr::GetSelectedDungeons(ObjectGuid guid)
{
TC_LOG_TRACE("lfg.data.player.dungeons.selected.get", "Player: %s, Selected Dungeons: %s", guid.ToString().c_str(), ConcatenateDungeons(PlayersStore[guid].GetSelectedDungeons()).c_str());
return PlayersStore[guid].GetSelectedDungeons();
}
LfgLockMap const LFGMgr::GetLockedDungeons(ObjectGuid guid)
{
TC_LOG_TRACE("lfg.data.player.dungeons.locked.get", "Player: %s, LockedDungeons.", guid.ToString().c_str());
LfgLockMap lock;
Player* player = ObjectAccessor::FindConnectedPlayer(guid);
if (!player)
{
TC_LOG_WARN("lfg.data.player.dungeons.locked.get", "Player: %s not ingame while retrieving his LockedDungeons.", guid.ToString().c_str());
return lock;
}
uint8 level = player->getLevel();
uint8 expansion = player->GetSession()->GetExpansion();
LfgDungeonSet const& dungeons = GetDungeonsByRandom(0);
bool denyJoin = !player->GetSession()->HasPermission(rbac::RBAC_PERM_JOIN_DUNGEON_FINDER);
for (LfgDungeonSet::const_iterator it = dungeons.begin(); it != dungeons.end(); ++it)
{
LFGDungeonData const* dungeon = GetLFGDungeon(*it);
if (!dungeon) // should never happen - We provide a list from sLFGDungeonStore
continue;
uint32 lockStatus = 0;
if (denyJoin)
lockStatus = LFG_LOCKSTATUS_RAID_LOCKED;
else if (dungeon->expansion > expansion)
lockStatus = LFG_LOCKSTATUS_INSUFFICIENT_EXPANSION;
else if (DisableMgr::IsDisabledFor(DISABLE_TYPE_MAP, dungeon->map, player))
lockStatus = LFG_LOCKSTATUS_NOT_IN_SEASON;
else if (DisableMgr::IsDisabledFor(DISABLE_TYPE_LFG_MAP, dungeon->map, player))
lockStatus = LFG_LOCKSTATUS_RAID_LOCKED;
else if (dungeon->difficulty > DUNGEON_DIFFICULTY_NORMAL && player->GetBoundInstance(dungeon->map, Difficulty(dungeon->difficulty)))
lockStatus = LFG_LOCKSTATUS_RAID_LOCKED;
else if (dungeon->difficulty > DUNGEON_DIFFICULTY_NORMAL && player->GetBoundInstance(dungeon->map, Difficulty(dungeon->difficulty), dungeon->type == LFG_TYPE_RAID))
lockStatus = LFG_LOCKSTATUS_RAID_LOCKED;
else if (dungeon->minlevel > level)
lockStatus = LFG_LOCKSTATUS_TOO_LOW_LEVEL;
else if (dungeon->maxlevel < level)
lockStatus = LFG_LOCKSTATUS_TOO_HIGH_LEVEL;
else if (dungeon->seasonal && !IsSeasonActive(dungeon->id))
lockStatus = LFG_LOCKSTATUS_NOT_IN_SEASON;
else if (dungeon->requiredItemLevel > player->GetAverageItemLevel())
lockStatus = LFG_LOCKSTATUS_TOO_LOW_GEAR_SCORE;
else if (AccessRequirement const* ar = sObjectMgr->GetAccessRequirement(dungeon->map, Difficulty(dungeon->difficulty)))
{
if (ar->achievement && !player->HasAchieved(ar->achievement))
lockStatus = LFG_LOCKSTATUS_MISSING_ACHIEVEMENT;
else if (player->GetTeam() == ALLIANCE && ar->quest_A && !player->GetQuestRewardStatus(ar->quest_A))
lockStatus = LFG_LOCKSTATUS_QUEST_NOT_COMPLETED;
else if (player->GetTeam() == HORDE && ar->quest_H && !player->GetQuestRewardStatus(ar->quest_H))
lockStatus = LFG_LOCKSTATUS_QUEST_NOT_COMPLETED;
else
if (ar->item)
{
if (!player->HasItemCount(ar->item) && (!ar->item2 || !player->HasItemCount(ar->item2)))
lockStatus = LFG_LOCKSTATUS_MISSING_ITEM;
}
else if (ar->item2 && !player->HasItemCount(ar->item2))
lockStatus = LFG_LOCKSTATUS_MISSING_ITEM;
}
/* @todo VoA closed if WG is not under team control (LFG_LOCKSTATUS_RAID_LOCKED)
lockData = LFG_LOCKSTATUS_TOO_HIGH_GEAR_SCORE;
lockData = LFG_LOCKSTATUS_ATTUNEMENT_TOO_LOW_LEVEL;
lockData = LFG_LOCKSTATUS_ATTUNEMENT_TOO_HIGH_LEVEL;
*/
if (lockStatus)
lock[dungeon->Entry()] = LfgLockInfoData(lockStatus, dungeon->requiredItemLevel, player->GetAverageItemLevel());
}
return lock;
}
uint8 LFGMgr::GetKicksLeft(ObjectGuid guid)
{
uint8 kicks = GroupsStore[guid].GetKicksLeft();
TC_LOG_TRACE("lfg.data.group.kickleft.get", "Group: %s, Kicks left: %u", guid.ToString().c_str(), kicks);
return kicks;
}
void LFGMgr::RestoreState(ObjectGuid guid, char const* debugMsg)
{
if (guid.IsGroup())
{
LfgGroupData& data = GroupsStore[guid];
TC_LOG_TRACE("lfg.data.group.state.restore", "Group: %s (%s), State: %s, Old state: %s",
guid.ToString().c_str(), debugMsg, GetStateString(data.GetState()).c_str(),
GetStateString(data.GetOldState()).c_str());
data.RestoreState();
}
else
{
LfgPlayerData& data = PlayersStore[guid];
TC_LOG_TRACE("lfg.data.player.state.restore", "Player: %s (%s), State: %s, Old state: %s",
guid.ToString().c_str(), debugMsg, GetStateString(data.GetState()).c_str(),
GetStateString(data.GetOldState()).c_str());
data.RestoreState();
}
}
void LFGMgr::SetState(ObjectGuid guid, LfgState state)
{
if (guid.IsGroup())
{
LfgGroupData& data = GroupsStore[guid];
TC_LOG_TRACE("lfg.data.group.state.set", "Group: %s, New state: %s, Previous: %s, Old state: %s",
guid.ToString().c_str(), GetStateString(state).c_str(), GetStateString(data.GetState()).c_str(),
GetStateString(data.GetOldState()).c_str());
data.SetState(state);
}
else
{
LfgPlayerData& data = PlayersStore[guid];
TC_LOG_TRACE("lfg.data.player.state.set", "Player: %s, New state: %s, Previous: %s, OldState: %s",
guid.ToString().c_str(), GetStateString(state).c_str(), GetStateString(data.GetState()).c_str(),
GetStateString(data.GetOldState()).c_str());
data.SetState(state);
}
}
void LFGMgr::SetVoteKick(ObjectGuid gguid, bool active)
{
ASSERT(gguid.IsGroup());
LfgGroupData& data = GroupsStore[gguid];
TC_LOG_TRACE("lfg.data.group.votekick.set", "Group: %s, New state: %d, Previous: %d",
gguid.ToString().c_str(), active, data.IsVoteKickActive());
data.SetVoteKick(active);
}
void LFGMgr::SetDungeon(ObjectGuid guid, uint32 dungeon)
{
TC_LOG_TRACE("lfg.data.group.dungeon.set", "Group: %s, Dungeon: %u", guid.ToString().c_str(), dungeon);
GroupsStore[guid].SetDungeon(dungeon);
}
void LFGMgr::SetRoles(ObjectGuid guid, uint8 roles)
{
TC_LOG_TRACE("lfg.data.player.role.set", "Player: %s, Roles: %u", guid.ToString().c_str(), roles);
PlayersStore[guid].SetRoles(roles);
}
void LFGMgr::SetComment(ObjectGuid guid, std::string const& comment)
{
TC_LOG_TRACE("lfg.data.player.comment.set", "Player: %s, Comment: %s", guid.ToString().c_str(), comment.c_str());
PlayersStore[guid].SetComment(comment);
}
void LFGMgr::SetSelectedDungeons(ObjectGuid guid, LfgDungeonSet const& dungeons)
{
TC_LOG_TRACE("lfg.data.player.dungeon.selected.set", "Player: %s, Dungeons: %s", guid.ToString().c_str(), ConcatenateDungeons(dungeons).c_str());
PlayersStore[guid].SetSelectedDungeons(dungeons);
}
void LFGMgr::DecreaseKicksLeft(ObjectGuid guid)
{
GroupsStore[guid].DecreaseKicksLeft();
TC_LOG_TRACE("lfg.data.group.kicksleft.decrease", "Group: %s, Kicks: %u", guid.ToString().c_str(), GroupsStore[guid].GetKicksLeft());
}
void LFGMgr::SetTicket(ObjectGuid guid, WorldPackets::LFG::RideTicket const& ticket)
{
PlayersStore[guid].SetTicket(ticket);
}
void LFGMgr::RemovePlayerData(ObjectGuid guid)
{
TC_LOG_TRACE("lfg.data.player.remove", "Player: %s", guid.ToString().c_str());
LfgPlayerDataContainer::iterator it = PlayersStore.find(guid);
if (it != PlayersStore.end())
PlayersStore.erase(it);
}
void LFGMgr::RemoveGroupData(ObjectGuid guid)
{
TC_LOG_TRACE("lfg.data.group.remove", "Group: %s", guid.ToString().c_str());
LfgGroupDataContainer::iterator it = GroupsStore.find(guid);
if (it == GroupsStore.end())
return;
LfgState state = GetState(guid);
// If group is being formed after proposal success do nothing more
GuidSet const& players = it->second.GetPlayers();
for (ObjectGuid playerGUID : players)
{
SetGroup(playerGUID, ObjectGuid::Empty);
if (state != LFG_STATE_PROPOSAL)
{
SetState(playerGUID, LFG_STATE_NONE);
SendLfgUpdateStatus(playerGUID, LfgUpdateData(LFG_UPDATETYPE_REMOVED_FROM_QUEUE), true);
}
}
GroupsStore.erase(it);
}
uint8 LFGMgr::GetTeam(ObjectGuid guid)
{
uint8 team = PlayersStore[guid].GetTeam();
TC_LOG_TRACE("lfg.data.player.team.get", "Player: %s, Team: %u", guid.ToString().c_str(), team);
return team;
}
uint8 LFGMgr::RemovePlayerFromGroup(ObjectGuid gguid, ObjectGuid guid)
{
return GroupsStore[gguid].RemovePlayer(guid);
}
void LFGMgr::AddPlayerToGroup(ObjectGuid gguid, ObjectGuid guid)
{
GroupsStore[gguid].AddPlayer(guid);
}
void LFGMgr::SetLeader(ObjectGuid gguid, ObjectGuid leader)
{
GroupsStore[gguid].SetLeader(leader);
}
void LFGMgr::SetTeam(ObjectGuid guid, uint8 team)
{
if (sWorld->getBoolConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_GROUP))
team = 0;
PlayersStore[guid].SetTeam(team);
}
ObjectGuid LFGMgr::GetGroup(ObjectGuid guid)
{
return PlayersStore[guid].GetGroup();
}
void LFGMgr::SetGroup(ObjectGuid guid, ObjectGuid group)
{
PlayersStore[guid].SetGroup(group);
}
GuidSet const& LFGMgr::GetPlayers(ObjectGuid guid)
{
return GroupsStore[guid].GetPlayers();
}
uint8 LFGMgr::GetPlayerCount(ObjectGuid guid)
{
return GroupsStore[guid].GetPlayerCount();
}
ObjectGuid LFGMgr::GetLeader(ObjectGuid guid)
{
return GroupsStore[guid].GetLeader();
}
bool LFGMgr::HasIgnore(ObjectGuid guid1, ObjectGuid guid2)
{
Player* plr1 = ObjectAccessor::FindConnectedPlayer(guid1);
Player* plr2 = ObjectAccessor::FindConnectedPlayer(guid2);
return plr1 && plr2 && (plr1->GetSocial()->HasIgnore(guid2) || plr2->GetSocial()->HasIgnore(guid1));
}
void LFGMgr::SendLfgRoleChosen(ObjectGuid guid, ObjectGuid pguid, uint8 roles)
{
if (Player* player = ObjectAccessor::FindConnectedPlayer(guid))
player->GetSession()->SendLfgRoleChosen(pguid, roles);
}
void LFGMgr::SendLfgRoleCheckUpdate(ObjectGuid guid, LfgRoleCheck const& roleCheck)
{
if (Player* player = ObjectAccessor::FindConnectedPlayer(guid))
player->GetSession()->SendLfgRoleCheckUpdate(roleCheck);
}
void LFGMgr::SendLfgUpdateStatus(ObjectGuid guid, LfgUpdateData const& data, bool party)
{
if (Player* player = ObjectAccessor::FindConnectedPlayer(guid))
player->GetSession()->SendLfgUpdateStatus(data, party);
}
void LFGMgr::SendLfgJoinResult(ObjectGuid guid, LfgJoinResultData const& data)
{
if (Player* player = ObjectAccessor::FindConnectedPlayer(guid))
player->GetSession()->SendLfgJoinResult(data);
}
void LFGMgr::SendLfgBootProposalUpdate(ObjectGuid guid, LfgPlayerBoot const& boot)
{
if (Player* player = ObjectAccessor::FindConnectedPlayer(guid))
player->GetSession()->SendLfgBootProposalUpdate(boot);
}
void LFGMgr::SendLfgUpdateProposal(ObjectGuid guid, LfgProposal const& proposal)
{
if (Player* player = ObjectAccessor::FindConnectedPlayer(guid))
player->GetSession()->SendLfgUpdateProposal(proposal);
}
void LFGMgr::SendLfgQueueStatus(ObjectGuid guid, LfgQueueStatusData const& data)
{
if (Player* player = ObjectAccessor::FindConnectedPlayer(guid))
player->GetSession()->SendLfgQueueStatus(data);
}
bool LFGMgr::IsLfgGroup(ObjectGuid guid)
{
return guid && guid.IsGroup() && GroupsStore[guid].IsLfgGroup();
}
uint8 LFGMgr::GetQueueId(ObjectGuid guid)
{
if (guid.IsGroup())
{
GuidSet const& players = GetPlayers(guid);
ObjectGuid pguid = players.empty() ? ObjectGuid::Empty : (*players.begin());
if (pguid)
return GetTeam(pguid);
}
return GetTeam(guid);
}
LFGQueue& LFGMgr::GetQueue(ObjectGuid guid)
{
uint8 queueId = GetQueueId(guid);
return QueuesStore[queueId];
}
bool LFGMgr::AllQueued(GuidList const& check)
{
if (check.empty())
return false;
for (GuidList::const_iterator it = check.begin(); it != check.end(); ++it)
{
LfgState state = GetState(*it);
if (state != LFG_STATE_QUEUED)
{
if (state != LFG_STATE_PROPOSAL)
TC_LOG_DEBUG("lfg.allqueued", "Unexpected state found while trying to form new group. Guid: %s, State: %s", (*it).ToString().c_str(), GetStateString(state).c_str());
return false;
}
}
return true;
}
time_t LFGMgr::GetQueueJoinTime(ObjectGuid guid)
{
uint8 queueId = GetQueueId(guid);
LfgQueueContainer::const_iterator itr = QueuesStore.find(queueId);
if (itr != QueuesStore.end())
return itr->second.GetJoinTime(guid);
return 0;
}
// Only for debugging purposes
void LFGMgr::Clean()
{
QueuesStore.clear();
}
bool LFGMgr::isOptionEnabled(uint32 option)
{
return (m_options & option) != 0;
}
uint32 LFGMgr::GetOptions()
{
return m_options;
}
void LFGMgr::SetOptions(uint32 options)
{
m_options = options;
}
LfgUpdateData LFGMgr::GetLfgStatus(ObjectGuid guid)
{
LfgPlayerData& playerData = PlayersStore[guid];
return LfgUpdateData(LFG_UPDATETYPE_UPDATE_STATUS, playerData.GetState(), playerData.GetSelectedDungeons());
}
bool LFGMgr::IsSeasonActive(uint32 dungeonId)
{
switch (dungeonId)
{
case 285: // The Headless Horseman
return IsHolidayActive(HOLIDAY_HALLOWS_END);
case 286: // The Frost Lord Ahune
return IsHolidayActive(HOLIDAY_FIRE_FESTIVAL);
case 287: // Coren Direbrew
return IsHolidayActive(HOLIDAY_BREWFEST);
case 288: // The Crown Chemical Co.
return IsHolidayActive(HOLIDAY_LOVE_IS_IN_THE_AIR);
}
return false;
}
std::string LFGMgr::DumpQueueInfo(bool full)
{
uint32 size = uint32(QueuesStore.size());
std::ostringstream o;
o << "Number of Queues: " << size << "\n";
for (LfgQueueContainer::const_iterator itr = QueuesStore.begin(); itr != QueuesStore.end(); ++itr)
{
std::string const& queued = itr->second.DumpQueueInfo();
std::string const& compatibles = itr->second.DumpCompatibleInfo(full);
o << queued << compatibles;
}
return o.str();
}
void LFGMgr::SetupGroupMember(ObjectGuid guid, ObjectGuid gguid)
{
LfgDungeonSet dungeons;
dungeons.insert(GetDungeon(gguid));
SetSelectedDungeons(guid, dungeons);
SetState(guid, GetState(gguid));
SetGroup(guid, gguid);
AddPlayerToGroup(gguid, guid);
}
bool LFGMgr::selectedRandomLfgDungeon(ObjectGuid guid)
{
if (GetState(guid) != LFG_STATE_NONE)
{
LfgDungeonSet const& dungeons = GetSelectedDungeons(guid);
if (!dungeons.empty())
{
LFGDungeonData const* dungeon = GetLFGDungeon(*dungeons.begin());
if (dungeon && (dungeon->type == LFG_TYPE_RANDOM || dungeon->seasonal))
return true;
}
}
return false;
}
bool LFGMgr::inLfgDungeonMap(ObjectGuid guid, uint32 map, Difficulty difficulty)
{
if (!guid.IsGroup())
guid = GetGroup(guid);
if (uint32 dungeonId = GetDungeon(guid, true))
if (LFGDungeonData const* dungeon = GetLFGDungeon(dungeonId))
if (uint32(dungeon->map) == map && dungeon->difficulty == difficulty)
return true;
return false;
}
uint32 LFGMgr::GetLFGDungeonEntry(uint32 id)
{
if (id)
if (LFGDungeonData const* dungeon = GetLFGDungeon(id))
return dungeon->Entry();
return 0;
}
LfgDungeonSet LFGMgr::GetRandomAndSeasonalDungeons(uint8 level, uint8 expansion)
{
LfgDungeonSet randomDungeons;
for (lfg::LFGDungeonContainer::const_iterator itr = LfgDungeonStore.begin(); itr != LfgDungeonStore.end(); ++itr)
{
lfg::LFGDungeonData const& dungeon = itr->second;
if ((dungeon.type == lfg::LFG_TYPE_RANDOM || dungeon.IsRaid()|| (dungeon.seasonal && sLFGMgr->IsSeasonActive(dungeon.id)))
&& dungeon.expansion <= expansion && dungeon.minlevel <= level && level <= dungeon.maxlevel)
randomDungeons.insert(dungeon.Entry());
}
return randomDungeons;
}
bool LFGDungeonData::IsRaid() const
{
if (MapEntry const* mapInfo = sMapStore.LookupEntry(map))
return mapInfo->IsRaid();
return false;
}
void LFGMgr::AddDungeonsFromGroupingMap(LfgCachedDungeonContainer& container, uint32 groupId, uint32 dungeonId)
{
// Check for grouped dungeons from grouping map
for (auto itr : sLFGDungeonsGroupingMapStore)
{
if (itr->Random_lfgDungeonsID == dungeonId)
{
if (container[groupId].find(itr->LfgDungeonsID) == container[groupId].end())
container[groupId].insert(itr->LfgDungeonsID);
}
}
}
void LFGMgr::SetEnligibleForShortageRewards(ObjectGuid guid, bool enligible)
{
PlayersStore[guid].SetEnligibleForShortageRewards(enligible);
}
bool LFGMgr::IsEnligibleForShortageRewards(ObjectGuid guid)
{
return PlayersStore[guid].IsEnligibleForShortageRewards();
}
void LFGMgr::SetShortageRoleMask(uint32 dungeonId, uint8 role)
{
ShortageRoleMaskStore[dungeonId] = role;
}
uint32 LFGMgr::GetShortageRoleMask(uint32 dungeonId)
{
return ShortageRoleMaskStore[dungeonId];
}
bool LFGMgr::CanPerformSelectedRoles(uint8 playerClass, uint8 roles) const
{
// Role Validation
if (roles & lfg::PLAYER_ROLE_TANK && (playerClass != CLASS_DEATH_KNIGHT && playerClass != CLASS_DRUID
&& playerClass != CLASS_PALADIN && playerClass != CLASS_WARRIOR))
return false;
if (roles & lfg::PLAYER_ROLE_HEALER && (playerClass != CLASS_PALADIN && playerClass != CLASS_DRUID
&& playerClass != CLASS_PRIEST && playerClass != CLASS_SHAMAN))
return false;
return true;
}
} // namespace lfg
| 412 | 0.931187 | 1 | 0.931187 | game-dev | MEDIA | 0.67269 | game-dev,databases | 0.932851 | 1 | 0.932851 |
ww-rm/SpineViewer | 5,169 | SpineRuntimes/SpineRuntime38/AnimationStateData.cs | /******************************************************************************
* Spine Runtimes License Agreement
* Last updated January 1, 2020. Replaces all prior versions.
*
* Copyright (c) 2013-2020, Esoteric Software LLC
*
* Integration of the Spine Runtimes into software or otherwise creating
* derivative works of the Spine Runtimes is permitted under the terms and
* conditions of Section 2 of the Spine Editor License Agreement:
* http://esotericsoftware.com/spine-editor-license
*
* Otherwise, it is permitted to integrate the Spine Runtimes into software
* or otherwise create derivative works of the Spine Runtimes (collectively,
* "Products"), provided that each user of the Products must obtain their own
* Spine Editor license and redistribution of the Products in any form must
* include this license and copyright notice.
*
* THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES,
* BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*****************************************************************************/
using System;
using System.Collections.Generic;
namespace SpineRuntime38 {
/// <summary>Stores mix (crossfade) durations to be applied when AnimationState animations are changed.</summary>
public class AnimationStateData {
internal SkeletonData skeletonData;
readonly Dictionary<AnimationPair, float> animationToMixTime = new Dictionary<AnimationPair, float>(AnimationPairComparer.Instance);
internal float defaultMix;
/// <summary>The SkeletonData to look up animations when they are specified by name.</summary>
public SkeletonData SkeletonData { get { return skeletonData; } }
/// <summary>
/// The mix duration to use when no mix duration has been specifically defined between two animations.</summary>
public float DefaultMix { get { return defaultMix; } set { defaultMix = value; } }
public AnimationStateData (SkeletonData skeletonData) {
if (skeletonData == null) throw new ArgumentException("skeletonData cannot be null.", "skeletonData");
this.skeletonData = skeletonData;
}
/// <summary>Sets a mix duration by animation names.</summary>
public void SetMix (string fromName, string toName, float duration) {
Animation from = skeletonData.FindAnimation(fromName);
if (from == null) throw new ArgumentException("Animation not found: " + fromName, "fromName");
Animation to = skeletonData.FindAnimation(toName);
if (to == null) throw new ArgumentException("Animation not found: " + toName, "toName");
SetMix(from, to, duration);
}
/// <summary>Sets a mix duration when changing from the specified animation to the other.
/// See TrackEntry.MixDuration.</summary>
public void SetMix (Animation from, Animation to, float duration) {
if (from == null) throw new ArgumentNullException("from", "from cannot be null.");
if (to == null) throw new ArgumentNullException("to", "to cannot be null.");
AnimationPair key = new AnimationPair(from, to);
animationToMixTime.Remove(key);
animationToMixTime.Add(key, duration);
}
/// <summary>
/// The mix duration to use when changing from the specified animation to the other,
/// or the DefaultMix if no mix duration has been set.
/// </summary>
public float GetMix (Animation from, Animation to) {
if (from == null) throw new ArgumentNullException("from", "from cannot be null.");
if (to == null) throw new ArgumentNullException("to", "to cannot be null.");
AnimationPair key = new AnimationPair(from, to);
float duration;
if (animationToMixTime.TryGetValue(key, out duration)) return duration;
return defaultMix;
}
public struct AnimationPair {
public readonly Animation a1;
public readonly Animation a2;
public AnimationPair (Animation a1, Animation a2) {
this.a1 = a1;
this.a2 = a2;
}
public override string ToString () {
return a1.name + "->" + a2.name;
}
}
// Avoids boxing in the dictionary.
public class AnimationPairComparer : IEqualityComparer<AnimationPair> {
public static readonly AnimationPairComparer Instance = new AnimationPairComparer();
bool IEqualityComparer<AnimationPair>.Equals (AnimationPair x, AnimationPair y) {
return ReferenceEquals(x.a1, y.a1) && ReferenceEquals(x.a2, y.a2);
}
int IEqualityComparer<AnimationPair>.GetHashCode (AnimationPair obj) {
// from Tuple.CombineHashCodes // return (((h1 << 5) + h1) ^ h2);
int h1 = obj.a1.GetHashCode();
return (((h1 << 5) + h1) ^ obj.a2.GetHashCode());
}
}
}
}
| 412 | 0.904413 | 1 | 0.904413 | game-dev | MEDIA | 0.394936 | game-dev | 0.795938 | 1 | 0.795938 |
oot-pc-port/oot-pc-port | 1,640 | asm/non_matchings/overlays/actors/ovl_En_Mk/func_80AACB14.s | glabel func_80AACB14
/* 00214 80AACB14 27BDFFE0 */ addiu $sp, $sp, 0xFFE0 ## $sp = FFFFFFE0
/* 00218 80AACB18 AFBF001C */ sw $ra, 0x001C($sp)
/* 0021C 80AACB1C AFA50024 */ sw $a1, 0x0024($sp)
/* 00220 80AACB20 0C00BCCD */ jal func_8002F334
/* 00224 80AACB24 AFA40020 */ sw $a0, 0x0020($sp)
/* 00228 80AACB28 1040000C */ beq $v0, $zero, .L80AACB5C
/* 0022C 80AACB2C 8FA40020 */ lw $a0, 0x0020($sp)
/* 00230 80AACB30 3C0E80AB */ lui $t6, %hi(func_80AACA94) ## $t6 = 80AB0000
/* 00234 80AACB34 3C014248 */ lui $at, 0x4248 ## $at = 42480000
/* 00238 80AACB38 44812000 */ mtc1 $at, $f4 ## $f4 = 50.00
/* 0023C 80AACB3C 25CECA94 */ addiu $t6, $t6, %lo(func_80AACA94) ## $t6 = 80AACA94
/* 00240 80AACB40 AC8E0284 */ sw $t6, 0x0284($a0) ## 00000284
/* 00244 80AACB44 3C07461C */ lui $a3, 0x461C ## $a3 = 461C0000
/* 00248 80AACB48 34E74000 */ ori $a3, $a3, 0x4000 ## $a3 = 461C4000
/* 0024C 80AACB4C 8FA50024 */ lw $a1, 0x0024($sp)
/* 00250 80AACB50 24060025 */ addiu $a2, $zero, 0x0025 ## $a2 = 00000025
/* 00254 80AACB54 0C00BD0D */ jal func_8002F434
/* 00258 80AACB58 E7A40010 */ swc1 $f4, 0x0010($sp)
.L80AACB5C:
/* 0025C 80AACB5C 8FBF001C */ lw $ra, 0x001C($sp)
/* 00260 80AACB60 27BD0020 */ addiu $sp, $sp, 0x0020 ## $sp = 00000000
/* 00264 80AACB64 03E00008 */ jr $ra
/* 00268 80AACB68 00000000 */ nop
| 412 | 0.662385 | 1 | 0.662385 | game-dev | MEDIA | 0.887817 | game-dev | 0.622538 | 1 | 0.622538 |
DeveloperPaul123/byte-knight | 1,849 | chess/src/non_slider_piece.rs | /*
* non_slider_pieces.rs
* Part of the byte-knight project
* Created Date: Thursday, April 24th 2025
* Author: Paul Tsouchlos (DeveloperPaul123) (developer.paul.123@gmail.com)
* -----
* Last Modified: Fri Apr 25 2025
* -----
* Copyright (c) 2025 Paul Tsouchlos (DeveloperPaul123)
* GNU General Public License v3.0 or later
* https://www.gnu.org/licenses/gpl-3.0-standalone.html
*
*/
use crate::pieces::Piece;
/// Representation of non-slider pieces only.
#[derive(Debug, PartialEq, Eq, PartialOrd, Copy, Clone)]
pub enum NonSliderPiece {
King,
Knight,
Pawn,
}
impl NonSliderPiece {
/// Returns the piece type of the non-slider piece.
pub fn piece_type(&self) -> Piece {
match self {
NonSliderPiece::King => Piece::King,
NonSliderPiece::Knight => Piece::Knight,
NonSliderPiece::Pawn => Piece::Pawn,
}
}
}
impl TryFrom<Piece> for NonSliderPiece {
type Error = ();
fn try_from(value: Piece) -> Result<Self, Self::Error> {
match value {
Piece::King => Ok(NonSliderPiece::King),
Piece::Knight => Ok(NonSliderPiece::Knight),
Piece::Pawn => Ok(NonSliderPiece::Pawn),
_ => Err(()),
}
}
}
#[cfg(test)]
mod tests {
use super::NonSliderPiece;
use crate::pieces::Piece;
#[test]
fn try_from() {
for piece in [Piece::King, Piece::Knight, Piece::Pawn] {
let try_piece = NonSliderPiece::try_from(piece);
assert!(try_piece.is_ok());
let non_slider_piece = try_piece.unwrap();
assert_eq!(non_slider_piece.piece_type(), piece);
}
for piece in [Piece::Queen, Piece::Bishop, Piece::Rook] {
let try_piece = NonSliderPiece::try_from(piece);
assert!(try_piece.is_err());
}
}
}
| 412 | 0.876329 | 1 | 0.876329 | game-dev | MEDIA | 0.675003 | game-dev | 0.634601 | 1 | 0.634601 |
MACURD/Hearthbuddy8.7.6 | 1,531 | Routines/DefaultRoutine/Silverfish/cards/1130-暗影崛起/Sim_DAL_366t4.cs | using System;
using System.Collections.Generic;
using System.Text;
namespace HREngine.Bots
{
class Sim_DAL_366t4 : SimTemplate //* 叛变合约 Turncoat Contract
//Destroy a minion. It_deals its damage to adjacent minions.
//消灭一个随从。对其相邻的随从造成等同于其攻击力的伤害。
{
public override void onCardPlay(Playfield p, bool ownplay, Minion target, int choice)
{
p.minionGetDestroyed(target);
if (target.Angr>0)
{
int dmg = target.Angr;
List<Minion> temp = (ownplay) ? p.enemyMinions : p.ownMinions;
foreach (Minion m in p.enemyMinions)
{
if (m.zonepos + 1 == target.zonepos || m.zonepos-1 == target.zonepos)
{
/*int oldhp = m.Hp;
p.minionGetDamageOrHeal(m, dmg);
if (!target.silenced && (target.handcard.card.name == CardDB.cardName.waterelemental ||target.handcard.card.name == CardDB.cardName.snowchugger) && m.Hp < oldhp) m.frozen=true;
if (!target.silenced && m.Hp < oldhp && target.poisonous) p.minionGetDestroyed(m);*/
p.minionAttacksMinion(target, m, true);
}
}
}
}
public override PlayReq[] GetPlayReqs()
{
return new PlayReq[] {
new PlayReq(CardDB.ErrorType2.REQ_TARGET_TO_PLAY),
new PlayReq(CardDB.ErrorType2.REQ_MINION_TARGET),
};
}
}
} | 412 | 0.97504 | 1 | 0.97504 | game-dev | MEDIA | 0.935342 | game-dev | 0.821004 | 1 | 0.821004 |
Kadeko/VRCBreeze | 5,305 | Assets/VRCBreeze/Scripts/VRCBreezeCreator.cs | using UnityEngine;
using VRC.SDKBase;
using VRC.SDK3.Avatars.Components;
using VRC.SDK3.Dynamics.Constraint.Components;
using nadena.dev.ndmf;
using nadena.dev.ndmf.runtime;
using nadena.dev.ndmf.animator;
namespace VRCBreeze
{
[System.Serializable]
public class BoneObjects
{
[Tooltip("Bone, that will be controlled by wind.")]
public GameObject breezeBone;
[Tooltip("How much is this bone influenced by wind. The weight multiplies by Wind Strength.\nWind Strength * Weight."), Range(0f, 2f)]
public float breezeBoneWeight = 1f;
[Tooltip("Inverts rotation in X axis. (left / right)")]
public bool invertX = false;
[Tooltip("Inverts rotation in Z axis. (forward / backward)")]
public bool invertZ = false;
}
[AddComponentMenu("VRCBreeze/VRC Breeze Creator")]
[HelpURL("https://github.com/Kadeko/VRCBreeze/")]
public class VRCBreezeCreator : MonoBehaviour, IEditorOnly, IVirtualizeAnimatorController
{
#region Variables
[Header("Wind Settings:"), Tooltip("Assign your desired Wind Anchor here. We recommend that to be 'Hips' or 'Head'.")]
public GameObject windAnchor;
[Tooltip("How strong is the wind."), Min(0f)]
public float windStrength = 10f;
[Tooltip("How long does the wind blow. Higher Number = Slower Movement. By default, it's 1."), Min(0.5f)]
public float windLength = 1f;
[Tooltip("If enabled, Bone keyframes are slightly randomized around the middle of the AnimationClip.\nIf disabled, Bone keyframes are placed in the middle of the AnimationClip.")]
public bool moveBonesAtRandomTime = false;
[Space, Tooltip("Drag any root bones here!")]
public BoneObjects[] boneObjects;
[Header("Important Components:"), Tooltip("Do not remove this, unless you know what you are doing!\nYou can find this component at: 'Rotation_Source' GameObject.")]
public VRCRotationConstraint rotationConstraint;
[Tooltip("Requires 'FX_Breeze' Animator Controller.\nYou can find this at: 'Assets/VRCBreeze/Animations/FX_Breeze.controller'")]
public RuntimeAnimatorController sourceAnimatorController;
[Space, Header("Debug:"), Tooltip("Automatically tries to check, if your FX is using Write Defaults ON/OFF during Avatar installment. If your controller has mixed Write Defaults, we recommend to disable this option.")]
public bool enableAutomaticWriteDefaults = true;
[Tooltip("Show gizmos on selected Breeze Bones. Avatar (or VRCBreeze Object) must be selected and Unity Gizmos enabled! Useful when setting up Wind Strength and Breeze Bone Weight."), SerializeField]
private bool enableGizmos = false;
private bool isAbsolute;
#endregion
#region VirtualizeAnimatorController
RuntimeAnimatorController IVirtualizeAnimatorController.AnimatorController
{
get => sourceAnimatorController;
set => sourceAnimatorController = value;
}
object IVirtualizeAnimatorController.TargetControllerKey => VRCAvatarDescriptor.AnimLayerType.FX;
string IVirtualizeAnimatorController.GetMotionBasePath(object ndmfBuildContext, bool clearPath)
{
var wasAbsolute = isAbsolute;
isAbsolute |= clearPath;
#if UNITY_EDITOR
if (!wasAbsolute && ndmfBuildContext is BuildContext context)
return RuntimeUtil.RelativePath(context.AvatarRootTransform, transform) ?? "";
#endif
return "";
}
#endregion
#region Gizmos
private void OnDrawGizmosSelected()
{
if (!enableGizmos) return;
if (boneObjects.Length == 0) return;
float height = 0.05f;
int circleSegments = 8;
Gizmos.color = Color.cyan;
for (int i = 0; i < boneObjects.Length; i++)
{
if (boneObjects[i].breezeBone == null) continue;
float radius = Mathf.Tan(windStrength * boneObjects[i].breezeBoneWeight * Mathf.Deg2Rad) * height;
Vector3 origin = boneObjects[i].breezeBone.transform.position;
Vector3 direction = boneObjects[i].breezeBone.transform.up * height;
Gizmos.DrawLine(origin, origin + direction);
Vector3 baseCenter = origin + direction;
Quaternion rotation = Quaternion.LookRotation(boneObjects[i].breezeBone.transform.up);
Vector3 prevPoint = Vector3.zero;
for (int c = 0; c <= circleSegments; c++)
{
float theta = (c / (float)circleSegments) * Mathf.PI * 2;
Vector3 localPos = new Vector3(Mathf.Cos(theta) * radius, Mathf.Sin(theta) * radius, 0);
Vector3 worldPos = rotation * localPos + baseCenter;
if (c > 0)
Gizmos.DrawLine(prevPoint, worldPos);
Gizmos.DrawLine(origin, worldPos);
prevPoint = worldPos;
}
}
}
#endregion
}
public enum Direction
{
Left, // +X
Right, // -X
Forward, // +Z
Backward, // -Z
}
}
| 412 | 0.893027 | 1 | 0.893027 | game-dev | MEDIA | 0.891563 | game-dev | 0.64486 | 1 | 0.64486 |
BentoBoxWorld/BentoBox | 1,272 | src/main/java/world/bentobox/bentobox/api/events/island/IslandNameEvent.java | package world.bentobox.bentobox.api.events.island;
import java.util.UUID;
import org.bukkit.Location;
import org.bukkit.event.HandlerList;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.Nullable;
import world.bentobox.bentobox.api.events.IslandBaseEvent;
import world.bentobox.bentobox.database.objects.Island;
/**
* Fired when a player names or renames an island.
* Cancellation has no effect.
*/
public class IslandNameEvent extends IslandBaseEvent {
private final String previousName;
private static final HandlerList handlers = new HandlerList();
@Override
public @NonNull HandlerList getHandlers() {
return getHandlerList();
}
public static HandlerList getHandlerList() {
return handlers;
}
public IslandNameEvent(Island island, UUID player, boolean admin, Location location, @Nullable String previousName) {
// Final variables have to be declared in the constructor
super(island, player, admin, location);
this.previousName = previousName;
}
/**
* @return the previous name of the island, if any. May be null if no name previously used.
*/
@Nullable
public String getPreviousNameIsland() {
return previousName;
}
} | 412 | 0.725098 | 1 | 0.725098 | game-dev | MEDIA | 0.37713 | game-dev | 0.632538 | 1 | 0.632538 |
Jermesa-Studio/JRS_Vehicle_Physics_Controller | 1,426 | Library/PackageCache/com.unity.visualscripting@1.9.4/Editor/VisualScripting.Core/Inspection/Reflection/LooseAssemblyNameInspector.cs | using UnityEditor;
using UnityEngine;
namespace Unity.VisualScripting
{
[Inspector(typeof(LooseAssemblyName))]
public sealed class LooseAssemblyNameInspector : Inspector
{
public LooseAssemblyNameInspector(Metadata metadata) : base(metadata) { }
protected override float GetHeight(float width, GUIContent label)
{
return HeightWithLabel(metadata, width, EditorGUIUtility.singleLineHeight, label);
}
protected override void OnGUI(Rect position, GUIContent label)
{
position = BeginLabeledBlock(metadata, position, label);
var fieldPosition = new Rect
(
position.x,
position.y,
position.width,
EditorGUIUtility.singleLineHeight
);
var popupLabel = StringUtility.FallbackEmpty(((LooseAssemblyName)metadata.value).name, "(No Assembly)");
var newAssemblyName = (LooseAssemblyName)LudiqGUI.FuzzyPopup
(
fieldPosition,
() => new LooseAssemblyNameOptionTree(),
((LooseAssemblyName)metadata.value),
new GUIContent(popupLabel)
);
if (EndBlock(metadata))
{
metadata.RecordUndo();
metadata.value = newAssemblyName;
}
}
}
}
| 412 | 0.852025 | 1 | 0.852025 | game-dev | MEDIA | 0.389417 | game-dev | 0.963124 | 1 | 0.963124 |
dotnet/dotnet | 4,524 | src/runtime/src/tests/JIT/Methodical/explicit/rotate/rotarg_float.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using Xunit;
namespace Rotate_rotarg_float_cs
{
public class App
{
public static int s_weightCount = 1;
public static int s_objCount = 0;
private class Node
{
public float m_weight;
public Node m_leftChild, m_rightChild;
public Node()
{
s_objCount++;
m_weight = (float)(s_weightCount++);
}
~Node()
{
//Console.WriteLine("Deleting " + m_weight.ToString());
s_objCount--;
}
public void growTree(int maxHeight, String indent)
{
//Console.WriteLine(indent + m_weight.ToString());
if (maxHeight > 0)
{
m_leftChild = new Node();
m_leftChild.growTree(maxHeight - 1, indent + " ");
m_rightChild = new Node();
m_rightChild.growTree(maxHeight - 1, indent + " ");
}
else
m_leftChild = m_rightChild = null;
}
public void rotateTree(ref float leftWeight, ref float rightWeight)
{
//Console.WriteLine("rotateTree(" + m_weight.ToString() + ") - begin");
Node newLeftChild = null, newRightChild = null;
int objCount = s_objCount;
if (m_leftChild != null)
{
newRightChild = new Node();
objCount++;
newRightChild.m_leftChild = m_leftChild.m_leftChild;
newRightChild.m_rightChild = m_leftChild.m_rightChild;
newRightChild.m_weight = m_leftChild.m_weight;
}
if (m_rightChild != null)
{
newLeftChild = new Node();
objCount++;
newLeftChild.m_leftChild = m_rightChild.m_leftChild;
newLeftChild.m_rightChild = m_rightChild.m_rightChild;
newLeftChild.m_weight = m_rightChild.m_weight;
}
m_leftChild = newLeftChild;
m_rightChild = newRightChild;
for (int I = 0; I < 1024; I++) { int[] u = new int[1024]; }
GC.Collect();
if (m_rightChild != null)
{
if (m_rightChild.m_leftChild != null &&
m_rightChild.m_rightChild != null)
{
m_rightChild.rotateTree(
ref m_rightChild.m_leftChild.m_weight,
ref m_rightChild.m_rightChild.m_weight);
}
else
{
float minus1 = -1;
m_rightChild.rotateTree(ref minus1, ref minus1);
}
if (leftWeight != m_rightChild.m_weight)
{
Console.WriteLine("left weight do not match.");
throw new Exception();
}
}
if (m_leftChild != null)
{
if (m_leftChild.m_leftChild != null &&
m_leftChild.m_rightChild != null)
{
m_leftChild.rotateTree(
ref m_leftChild.m_leftChild.m_weight,
ref m_leftChild.m_rightChild.m_weight);
}
else
{
float minus1 = -1;
m_leftChild.rotateTree(ref minus1, ref minus1);
}
if (rightWeight != m_leftChild.m_weight)
{
Console.WriteLine("right weight do not match.");
throw new Exception();
}
}
//Console.WriteLine("rotateTree(" + m_weight.ToString() + ") - end");
}
}
[Fact]
public static void TestEntryPoint()
{
Node root = new Node();
root.growTree(4, "");
root.rotateTree(ref root.m_leftChild.m_weight, ref root.m_rightChild.m_weight);
}
}
}
| 412 | 0.862307 | 1 | 0.862307 | game-dev | MEDIA | 0.597349 | game-dev | 0.990377 | 1 | 0.990377 |
webbukkit/DynmapBlockScan | 11,298 | forge-1.21/src/main/java/org/dynmapblockscan/forge_1_20_4/DynmapBlockScanPlugin.java | package org.dynmapblockscan.forge_1_20_4;
import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.dynmapblockscan.core.AbstractBlockScanBase;
import org.dynmapblockscan.core.BlockScanLog;
import org.dynmapblockscan.core.BlockStateOverrides.BlockStateOverride;
import org.dynmapblockscan.core.blockstate.BSBlockState;
import org.dynmapblockscan.core.blockstate.VariantList;
import org.dynmapblockscan.core.model.BlockModel;
import org.dynmapblockscan.core.statehandlers.StateContainer.StateRec;
import org.dynmapblockscan.forge_1_20_4.statehandlers.ForgeStateContainer;
import com.google.common.collect.ImmutableMap;
import net.minecraft.core.BlockPos;
import net.minecraft.core.IdMapper;
import net.minecraft.core.Registry;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.StringRepresentable;
import net.minecraft.world.level.EmptyBlockGetter;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.StateDefinition;
import net.minecraft.world.level.block.state.properties.Property;
import net.minecraftforge.fml.ModContainer;
import net.minecraftforge.fml.ModList;
import net.minecraftforge.forgespi.language.IModFileInfo;
import net.minecraftforge.forgespi.language.IModInfo;
import net.minecraftforge.forgespi.locating.IModFile;
import net.minecraft.world.level.block.state.BlockState;
public class DynmapBlockScanPlugin extends AbstractBlockScanBase
{
public static DynmapBlockScanPlugin plugin;
public DynmapBlockScanPlugin(MinecraftServer srv)
{
plugin = this;
logger = new OurLog();
}
public void buildAssetMap() {
assetmap = new HashMap<String, PathElement>();
List<IModInfo> mcl = ModList.get().getMods();
for (IModInfo mc : mcl) {
String mid = mc.getModId().toLowerCase();
IModFileInfo mfi = mc.getOwningFile();
if (mfi == null) continue;
IModFile mf = mfi.getFile();
if (mf == null) continue;
try {
File src = mf.getFilePath().toFile();
// Process mod file
processModFile(mid, src);
}
catch (UnsupportedOperationException ex) {
logger.warning("jar in jar method found, skipping: " + ex.getMessage());
}
}
}
public void onEnable() {
}
public void onDisable() {
}
public void serverStarted() {
}
public void serverStarting() {
logger.info("buildAssetMap");
buildAssetMap();
logger.info("loadOverrideResources");
// Load override resources
loadOverrideResources();
logger.info("scan for overrides");
// Scan other modules for block overrides
for (IModInfo mod : ModList.get().getMods()) {
loadModuleOverrideResources(mod.getModId());
}
Map<String, BlockRecord> blockRecords = new LinkedHashMap<String, BlockRecord>();
logger.info("Start processing states");
// Now process models from block records
Map<String, BlockModel> models = new LinkedHashMap<String, BlockModel>();
IdMapper<BlockState> bsids = Block.BLOCK_STATE_REGISTRY;
Block baseb = null;
Iterator<BlockState> iter = bsids.iterator();
// Scan blocks and block states
while (iter.hasNext()) {
BlockState blkstate = iter.next();
Block b = blkstate.getBlock();
if (b == baseb) { continue; }
baseb = b;
ResourceLocation rl = BuiltInRegistries.BLOCK.getKey(b);
StateDefinition<Block, BlockState> bsc = b.getStateDefinition();
// See if any of the block states use MODEL
boolean uses_model = false;
boolean uses_nonmodel = false;
for (BlockState bs : bsc.getPossibleStates()) {
switch (bs.getRenderShape()) {
case MODEL:
uses_model = true;
break;
case INVISIBLE:
uses_nonmodel = true;
if (verboselogging)
logger.info(String.format("%s: Invisible block - nothing to render", rl));
break;
case ENTITYBLOCK_ANIMATED:
uses_nonmodel = true;
if (verboselogging)
logger.info(String.format("%s: Animated block - needs to be handled specially", rl));
break;
// case LIQUID:
// uses_nonmodel = true;
// if (DynmapBlockScanMod.verboselogging)
// logger.info(String.format("%s: Liquid block - special handling", rl));
// break;
}
}
// Not model block - nothing else to do yet
if (!uses_model) {
continue;
}
else if (uses_nonmodel) {
logger.warning(String.format("%s: Block mixes model and nonmodel state handling!", rl));
}
// Generate property value map
Map<String, List<String>> propMap = buildPropoertyMap(bsc);
// Try to find blockstate file
//Material mat = blkstate.getMaterial();
//MaterialColor matcol = mat.getColor();
BSBlockState blockstate = loadBlockState(rl.getNamespace(), rl.getPath(), overrides, propMap);
// Build block record
BlockRecord br = new BlockRecord();
// Process blockstate
if (blockstate != null) {
br.renderProps = blockstate.getRenderProps();
br.materialColorID = MaterialColorID.byID(b.defaultMapColor().id);
br.lightAttenuation = 15;
try { // Workaround for mods with broken block state logic...
br.lightAttenuation = blkstate.isSolidRender(EmptyBlockGetter.INSTANCE, BlockPos.ZERO) ? 15 : (blkstate.propagatesSkylightDown(EmptyBlockGetter.INSTANCE, BlockPos.ZERO) ? 0 : 1);
} catch (Exception x) {
logger.warning(String.format("Exception while checking lighting data for block state: %s", blkstate));
logger.verboseinfo("Exception: " + x.toString());
}
}
// Build generic block state container for block
br.sc = new ForgeStateContainer(b, br.renderProps, propMap);
if (blockstate != null) {
BlockStateOverride ovr = overrides.getOverride(rl.getNamespace(), rl.getPath());
br.varList = new LinkedHashMap<StateRec, List<VariantList>>();
// Loop through rendering states in state container
for (StateRec sr : br.sc.getValidStates()) {
Map<String, String> prop = sr.getProperties();
// If we've got key=value for block (multiple blocks in same state file)
if ((ovr != null) && (ovr.blockStateKey != null) && (ovr.blockStateValue != null)) {
prop = new HashMap<String, String>(prop);
prop.put(ovr.blockStateKey, ovr.blockStateValue);
}
List<VariantList> vlist = blockstate.getMatchingVariants(prop, models);
br.varList.put(sr, vlist);
}
}
else {
br.varList = Collections.emptyMap();
}
// Check for matching handler
blockRecords.put(rl.toString(), br);
}
logger.info("Loading models....");
loadModels(blockRecords, models);
logger.info("Variant models loaded");
// Now, resolve all parent references - load additional models
resolveParentReferences(models);
logger.info("Parent models loaded and resolved");
resolveAllElements(blockRecords, models);
logger.info("Elements generated");
publishDynmapModData();
assetmap = null;
}
@Override
public InputStream openResource(String modid, String rname) {
if (modid.equals("minecraft")) modid = "dynmapblockscan"; // We supply resources (1.13.2 doesn't have assets in server jar)
String rname_lc = rname.toLowerCase();
Optional<? extends ModContainer> mc = ModList.get().getModContainerById(modid);
Object mod = (mc.isPresent())?mc.get().getMod():null;
ClassLoader cl = MinecraftServer.class.getClassLoader();
if (mod != null) {
cl = mod.getClass().getClassLoader();
}
if (cl != null) {
InputStream is = cl.getResourceAsStream(rname_lc);
if (is == null) {
is = cl.getResourceAsStream(rname);
}
if (is != null) {
return is;
}
}
return null;
}
public Map<String, List<String>> buildPropoertyMap(StateDefinition<Block, BlockState> bsc) {
Map<String, List<String>> renderProperties = new LinkedHashMap<String, List<String>>();
// Build table of render properties and valid values
for (Property<?> p : bsc.getProperties()) {
String pn = p.getName();
ArrayList<String> pvals = new ArrayList<String>();
for (Comparable<?> val : p.getPossibleValues()) {
if (val instanceof StringRepresentable) {
pvals.add(((StringRepresentable)val).getSerializedName());
}
else {
pvals.add(val.toString());
}
}
renderProperties.put(pn, pvals);
}
return renderProperties;
}
// Build Map<String, String> from properties in BlockState
public Map<String, String> fromBlockState(BlockState bs) {
ImmutableMap.Builder<String,String> bld = ImmutableMap.builder();
for (Property<?> x : bs.getProperties()) {
Object v = bs.getValue(x);
if (v instanceof StringRepresentable) {
bld.put(x.getName(), ((StringRepresentable)v).getSerializedName());
}
else {
bld.put(x.getName(), v.toString());
}
}
return bld.build();
}
public static class OurLog implements BlockScanLog {
Logger log;
public static final String DM = "[DynmapBlockScan] ";
OurLog() {
log = LogManager.getLogger("DynmapBlockScan");
}
public void debug(String s) {
log.debug(DM + s);
}
public void info(String s) {
log.info(DM + s);
}
public void severe(Throwable t) {
log.fatal(t);
}
public void severe(String s) {
log.fatal(DM + s);
}
public void severe(String s, Throwable t) {
log.fatal(DM + s, t);
}
public void verboseinfo(String s) {
log.info(DM + s);
}
public void warning(String s) {
log.warn(DM + s);
}
public void warning(String s, Throwable t) {
log.warn(DM + s, t);
}
}
}
| 412 | 0.936523 | 1 | 0.936523 | game-dev | MEDIA | 0.970252 | game-dev | 0.942208 | 1 | 0.942208 |
MichaelJW/DorsalVR | 11,411 | Assets/OldDorsalDevice.cs | using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.XR;
using UnityEngine.XR.OpenXR.Input;
// No longer used - but not deleting quite yet because will need it to create an IMUDorsalDevice
public class OldDorsalDevice {
/*
// Hacky - for callback. Fix later.
public OldDSU.DSUDevice callbackDSUDevice;
// For internal representation of controller
Vector3[] pos;
double[] velX;
double[] velY;
double[] velZ;
Vector3[] accel;
Quaternion[] gyro;
Vector3[] gyroRate;
Vector3[] dGravity;
double[] timestamp;
double minTimeDiff = 0.1; // s
private int samples = 50;
private int samplesTaken = 0;
Quaternion relativeRotation = Quaternion.identity;
Vector3 dRight;
Vector3 dUp;
Vector3 dForward;
// For other classes to read from this device
DeviceType deviceType = DeviceType.Undefined;
public Vector3 gyroscopeRate = new Vector3();
public Vector3 accelerometer = new Vector3();
public Int64 lastTimestamp = 0;
public bool primaryButton = false;
public bool secondaryButton = false;
public bool gripButton = false;
public float grip = 0f;
public bool triggerButton = false;
public float trigger = 0f;
public Vector2 primary2DAxis = new Vector2();
public bool primary2DAxisClick = false;
public Quaternion deviceRotation = new Quaternion();
public Vector3 devicePosition = new Vector3();
// For getting data from physical controller
InputAction poseAction;
InputAction positionAction;
InputAction rotationAction;
UnityEngine.XR.InputDevice inputDevice;
// For screen position, to calculate pointer
Vector3 screenCentre;
Vector3 screenNormal;
float screenWidth; // m
float screenHeight; // m
public enum DeviceType {
Undefined = 0,
HMD = 1,
LeftHand = 2,
RightHand = 3
}
public OldDorsalDevice(DeviceType _deviceType) {
pos = new Vector3[samples]; // metres
velX = new double[samples]; // m/s
velY = new double[samples];
velZ = new double[samples];
accel = new Vector3[samples]; // g
gyro = new Quaternion[samples]; // deg
gyroRate = new Vector3[samples]; // deg/s
dGravity = new Vector3[samples]; // g
timestamp = new double[samples]; // seconds
screenCentre = GameObject.Find("Screen").GetComponent<Transform>().position;
screenNormal = -GameObject.Find("Screen").GetComponent<Transform>().forward;
screenWidth = GameObject.Find("Screen").GetComponent<Transform>().localScale.x;
screenHeight = GameObject.Find("Screen").GetComponent<Transform>().localScale.y;
SetDeviceType(_deviceType);
}
public void SetRelativeRotation(Quaternion _relativeRotation) {
relativeRotation = _relativeRotation;
}
public void SetDeviceType(DeviceType _deviceType) {
deviceType = _deviceType;
RegisterDevices();
UnityEngine.XR.InputDevices.deviceConnected += OnDeviceConnected;
}
private void OnDeviceConnected(UnityEngine.XR.InputDevice device) {
RegisterDevices();
}
private void RegisterDevices() {
// For now, we keep this simple:
// We look at all connected devices and add as "the" inputDevice if the type matches the `device` field selected.
// We don't do anything with ambidextrous controllers or if, say, the user has two HMDs connected.
// Nor do we do anything if a controller is disconnected.
List<UnityEngine.XR.InputDevice> allInputDevices = new List<UnityEngine.XR.InputDevice>();
UnityEngine.XR.InputDevices.GetDevices(allInputDevices);
List<XRNodeState> allNodeStates = new List<XRNodeState>();
UnityEngine.XR.InputTracking.GetNodeStates(allNodeStates);
for (int i = 0; i < allInputDevices.Count; i++) {
if ((allInputDevices[i].characteristics & UnityEngine.XR.InputDeviceCharacteristics.HeadMounted) == UnityEngine.XR.InputDeviceCharacteristics.HeadMounted) {
if (deviceType == DeviceType.HMD) {
inputDevice = allInputDevices[i];
positionAction = new InputAction();
positionAction.AddBinding(new InputBinding("<XRHMD>/centerEyePosition"));
positionAction.performed += OnPositionAction;
positionAction.Enable();
rotationAction = new InputAction();
rotationAction.AddBinding(new InputBinding("<XRHMD>/centerEyeRotation"));
rotationAction.performed += OnRotationAction;
rotationAction.Enable();
}
} else if ((allInputDevices[i].characteristics & UnityEngine.XR.InputDeviceCharacteristics.HeldInHand) == UnityEngine.XR.InputDeviceCharacteristics.HeldInHand) {
if ((allInputDevices[i].characteristics & UnityEngine.XR.InputDeviceCharacteristics.Left) == UnityEngine.XR.InputDeviceCharacteristics.Left) {
if (deviceType == DeviceType.LeftHand) {
inputDevice = allInputDevices[i];
poseAction = new InputAction();
poseAction.AddBinding("<XRController>{LeftHand}/pointer");
poseAction.performed += OnPoseAction;
poseAction.Enable();
}
} else if ((allInputDevices[i].characteristics & UnityEngine.XR.InputDeviceCharacteristics.Right) == UnityEngine.XR.InputDeviceCharacteristics.Right) {
if (deviceType == DeviceType.RightHand) {
inputDevice = allInputDevices[i];
poseAction = new InputAction();
poseAction.AddBinding("<XRController>{RightHand}/pointer");
poseAction.performed += OnPoseAction;
poseAction.Enable();
}
}
}
}
}
private void OnRotationAction(InputAction.CallbackContext obj) {
deviceRotation = relativeRotation * obj.action.ReadValue<Quaternion>();
}
private void OnPoseAction(InputAction.CallbackContext obj) {
UnityEngine.XR.OpenXR.Input.Pose pose = (UnityEngine.XR.OpenXR.Input.Pose)obj.action.ReadValueAsObject();
deviceRotation = pose.rotation * relativeRotation;
devicePosition = pose.position;
if (obj.time > timestamp[0]) {
UpdateOutputs(pose.position, obj.time);
}
}
private void UpdateOutputs(Vector3 pos, double time) {
inputDevice.TryGetFeatureValue(UnityEngine.XR.CommonUsages.deviceRotation, out Quaternion dRot);
inputDevice.TryGetFeatureValue(UnityEngine.XR.CommonUsages.deviceAngularVelocity, out Vector3 dRotRate);
dForward = (dRot * relativeRotation * Vector3.forward);
dUp = (dRot * relativeRotation * Vector3.up);
dRight = (dRot * relativeRotation * Vector3.right);
for (int i = samplesTaken - 1; i >= 1; i--) {
this.pos[i] = this.pos[i - 1];
velX[i] = velX[i - 1];
velY[i] = velY[i - 1];
velZ[i] = velZ[i - 1];
accel[i] = accel[i - 1];
gyro[i] = gyro[i - 1];
gyroRate[i] = gyroRate[i - 1];
dGravity[i] = dGravity[i - 1];
timestamp[i] = timestamp[i - 1];
}
if ((float)time - timestamp[0] > 1) {
timestamp[0] = Time.realtimeSinceStartup;
} else {
timestamp[0] = (float)time;
}
this.pos[0] = pos;
// Apply smoothing if samples are too close together
int j = 1;
while (timestamp[0] - timestamp[j] <= minTimeDiff & j < samplesTaken) {
j++;
}
if (j > 0) {
double diffTime = timestamp[0] - timestamp[j];
// m/s
velX[0] = (this.pos[0].x - this.pos[j].x) / diffTime;
velY[0] = (this.pos[0].y - this.pos[j].y) / diffTime;
velZ[0] = (this.pos[0].z - this.pos[j].z) / diffTime;
gyroRate[0] = dRotRate * (float)(180f / Math.PI);
if (samplesTaken >= samples) {
// Divide by 9.8 to get g since v/dt will be in m/s/s
accel[0] = new Vector3(
(float)((velX[0] - velX[j]) / (9.8f * diffTime)),
(float)((velY[0] - velY[j]) / (9.8f * diffTime)),
(float)((velZ[0] - velZ[j]) / (9.8f * diffTime))
);
}
}
// We need movement relative to the device's own axes, so use dot products
dGravity[0] = new Vector3(
Vector3.Dot(Vector3.up, -dRight),
Vector3.Dot(Vector3.up, -dUp),
Vector3.Dot(Vector3.up, dForward)
);
Vector3 dAccel = new Vector3(
Vector3.Dot(accel[0], dRight),
Vector3.Dot(accel[0], dUp),
Vector3.Dot(accel[0], -dForward)
);
samplesTaken++;
if (samplesTaken >= samples) {
samplesTaken = samples;
// Debug here if needed
}
// Don't forget to get pointer location and buttons
// Also will need to check that gyro rate works OK with this smoothing - may also need to derive that
if (timestamp[0] - timestamp[j] >= minTimeDiff) {
lastTimestamp = (Int64)(timestamp[0] * 1000000);
accelerometer = dAccel + dGravity[0];
gyroscopeRate = new Vector3(
gyroRate[0].x,
gyroRate[0].z,
-gyroRate[0].y
);
inputDevice.TryGetFeatureValue(UnityEngine.XR.CommonUsages.primaryButton, out primaryButton);
inputDevice.TryGetFeatureValue(UnityEngine.XR.CommonUsages.secondaryButton, out secondaryButton);
inputDevice.TryGetFeatureValue(UnityEngine.XR.CommonUsages.gripButton, out gripButton);
inputDevice.TryGetFeatureValue(UnityEngine.XR.CommonUsages.grip, out grip);
inputDevice.TryGetFeatureValue(UnityEngine.XR.CommonUsages.triggerButton, out triggerButton);
inputDevice.TryGetFeatureValue(UnityEngine.XR.CommonUsages.trigger, out trigger);
inputDevice.TryGetFeatureValue(UnityEngine.XR.CommonUsages.primary2DAxis, out primary2DAxis);
inputDevice.TryGetFeatureValue(UnityEngine.XR.CommonUsages.primary2DAxisClick, out primary2DAxisClick);
if (callbackDSUDevice != null) {
callbackDSUDevice.UpdateFromDorsalDevice();
}
}
}
private void OnPositionAction(InputAction.CallbackContext obj) {
devicePosition = obj.action.ReadValue<Vector3>();
UpdateOutputs(obj.action.ReadValue<Vector3>(), obj.time);
}
public Vector2 GetScreenPoint() {
float d = Vector3.Dot(screenCentre - pos[0], screenNormal) / Vector3.Dot(dForward, screenNormal);
Vector3 intersection = pos[0] + (d * dForward);
Vector2 nIntersection = new Vector2(
(intersection.x - screenCentre.x + (screenWidth / 2)) / screenWidth,
(screenCentre.y - intersection.y + (screenHeight / 2)) / screenHeight
);
return nIntersection;
}
*/
}
| 412 | 0.826063 | 1 | 0.826063 | game-dev | MEDIA | 0.880111 | game-dev | 0.962956 | 1 | 0.962956 |
alexkulya/pandaria_5.4.8 | 3,642 | src/server/scripts/Pet/pet_warlock.cpp | /*
* This file is part of the Pandaria 5.4.8 Project. See THANKS file for Copyright information
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* Ordered alphabetically using scriptname.
* Scriptnames of files in this file should be prefixed with "npc_pet_sha_".
*/
#include "Pet.h"
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
enum ShamanSpells
{
SPELL_WARLOCK_FIREBOLT = 104318,
SPELL_WARLOCK_MOLTEN_CORE_AURA = 122351,
SPELL_WARLOCK_MOLTEN_CORE = 122355,
};
class npc_wild_imp : public CreatureScript
{
public:
npc_wild_imp() : CreatureScript("npc_wild_imp") { }
struct npc_wild_impAI : public ScriptedAI
{
uint32 charges;
npc_wild_impAI(Creature* creature) : ScriptedAI(creature)
{
charges = 10;
me->SetReactState(REACT_ASSIST);
}
void Reset()
{
me->SetReactState(REACT_ASSIST);
if (me->GetOwner())
if (me->GetOwner()->GetVictim())
AttackStart(me->GetOwner()->GetVictim());
}
void UpdateAI(uint32 diff)
{
if (me->GetReactState() != REACT_ASSIST)
me->SetReactState(REACT_ASSIST);
if (!me->GetOwner())
return;
if (!me->GetOwner()->ToPlayer())
return;
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
if (!charges)
{
me->DespawnOrUnsummon();
return;
}
if ((me->GetVictim() || me->GetOwner()->getAttackerForHelper()))
{
me->CastSpell(me->GetVictim() ? me->GetVictim() : me->GetOwner()->getAttackerForHelper(), SPELL_WARLOCK_FIREBOLT, false);
me->GetOwner()->EnergizeBySpell(me->GetOwner(), SPELL_WARLOCK_FIREBOLT, 5, POWER_DEMONIC_FURY);
charges--;
if (me->GetOwner()->HasAura(SPELL_WARLOCK_MOLTEN_CORE_AURA))
if (roll_chance_i(8))
me->GetOwner()->CastSpell(me->GetOwner(), SPELL_WARLOCK_MOLTEN_CORE, true);
}
else if (Pet* pet = me->GetOwner()->ToPlayer()->GetPet())
{
if (pet->getAttackerForHelper())
{
me->CastSpell(me->GetVictim() ? me->GetVictim() : pet->getAttackerForHelper(), SPELL_WARLOCK_FIREBOLT, false);
me->GetOwner()->EnergizeBySpell(me->GetOwner(), SPELL_WARLOCK_FIREBOLT, 5, POWER_DEMONIC_FURY);
charges--;
if (me->GetOwner()->HasAura(SPELL_WARLOCK_MOLTEN_CORE_AURA))
if (roll_chance_i(8))
me->GetOwner()->CastSpell(me->GetOwner(), SPELL_WARLOCK_MOLTEN_CORE, true);
}
}
}
};
CreatureAI* GetAI(Creature* creature) const
{
return new npc_wild_impAI(creature);
}
};
void AddSC_warlock_pet_scripts()
{
new npc_wild_imp();
}
| 412 | 0.95894 | 1 | 0.95894 | game-dev | MEDIA | 0.756321 | game-dev | 0.993652 | 1 | 0.993652 |
RedPandaProjects/STALKERonUE | 42,536 | gamedata/scripts/smart_terrain.script | local DEATH_IDLE_TIME = 10*60 --
local RESPAWN_IDLE = 1000 --
local RESPAWN_RADIUS = 150 -- ( , )
SMART_TERRAIN_SECT = "smart_terrain"
smart_terrains_by_name = {}
local locations_ini = ini_file("misc\\smart_terrain_masks.ltx")
nearest_to_actor_smart = {id = nil , dist = math.huge}
local path_fields = { "path_walk", "path_main", "path_home", "center_point" }
local valid_territory = {
default = true,
base = true,
resource = true,
territory = true
}
--' ,
local function job_avail_to_npc(npc_info, job_info, smart)
--printf("job_avail_to_npc %s job %s smart %s", npc_info.se_obj:name(), tostring(job_info.job_id), smart:name())
local job = smart.job_data[job_info.job_id]
if job ~= nil then
job = job.section
end
if smart.dead_time[job_info.job_id] ~= nil then
return false
end
-- ""
if job_info._precondition_is_monster ~= nil and job_info._precondition_is_monster ~= npc_info.is_monster then
return false
end
--'
if job_info._precondition_function ~= nil then
if not job_info._precondition_function(npc_info.se_obj, smart, job_info._precondition_params, npc_info) then
return false
end
end
return true
end
-- , , , .
-- .
-- , , .
local function job_iterator(jobs, npc_data, selected_job_prior, smart)
--printf(" iterate")
--
local current_job_prior = selected_job_prior
local selected_job_id = nil
local selected_job_link = nil
for k,v in pairs(jobs) do
-- , -
if current_job_prior > v._prior then
return selected_job_id, current_job_prior, selected_job_link
end
-- ,
if job_avail_to_npc(npc_data, v, smart) then
-- - -.
if v.job_id == nil then
--
selected_job_id, current_job_prior, selected_job_link = job_iterator(v.jobs, npc_data, selected_job_prior, smart)
else
-- - .
if v.npc_id == nil then
return v.job_id, v._prior, v
elseif v.job_id == npc_data.job_id then
return v.job_id, v._prior, v
end
end
end
end
return selected_job_id, current_job_prior, selected_job_link
end
--
local function arrived_to_smart(obj, smart)
local obj_gv, obj_pos
local storage = db.storage[obj.id]
if storage == nil then
obj_gv, obj_pos = game_graph():vertex(obj.m_game_vertex_id), obj.position
else
local obj = db.storage[obj.id].object
obj_gv, obj_pos = game_graph():vertex(obj:game_vertex_id()), obj:position()
end
local smart_gv = game_graph():vertex(smart.m_game_vertex_id)
if obj.group_id then
local squad = smart.board.squads[obj.group_id]
if squad ~= nil and squad.current_action then
if squad.current_action.name == "reach_target" then
local squad_target = simulation_objects.get_sim_obj_registry().objects[squad.assigned_target_id]
if squad_target ~= nil then
return squad_target:am_i_reached(squad)
else
return alife():object(squad.assigned_target_id):am_i_reached(squad)
end
elseif squad.current_action.name == "stay_point" then
return true
end
end
end
if obj_gv:level_id() == smart_gv:level_id() then
return obj_pos:distance_to_sqr(smart.position) <= 10000 -- 100
else
return false
end
end
----------------------------------------------------------------------------------------------------------------------
-- "se_smart_terrain". smart terrain .
----------------------------------------------------------------------------------------------------------------------
class "se_smart_terrain" (cse_alife_smart_zone)
function se_smart_terrain:__init(section) super(section)
self.initialized = false
self.b_registred = false
self.population = 0
self.npc_to_register = {}
self.npc_by_job_section = {}
self.dead_time = {}
--
self.npc_info = {} -- ,
self.arriving_npc = {} -- .
end
function se_smart_terrain:on_before_register()
cse_alife_smart_zone.on_before_register(self)
self.board = sim_board.get_sim_board()
self.board:register_smart(self)
self.smart_level = alife():level_name(game_graph():vertex(self.m_game_vertex_id):level_id())
--printf("SMARTLEVEL %s level %s", self:name(), tostring(self.smart_level))
end
function se_smart_terrain:on_register()
cse_alife_smart_zone.on_register(self)
-- .
story_objects.check_spawn_ini_for_story_id(self)
simulation_objects.get_sim_obj_registry():register(self)
printf("register smart %s", self:name())
if dev_dedug then
self:refresh()
end
printf("Returning alife task for object [%s] game_vertex [%s] level_vertex [%s] position %s", self.id, self.m_game_vertex_id, self.m_level_vertex_id, vec_to_str(self.position))
self.smart_alife_task = CALifeSmartTerrainTask(self.m_game_vertex_id, self.m_level_vertex_id)
smart_terrains_by_name[self:name()] = self
self.b_registred = true
self:load_jobs()
self.board:init_smart(self)
if self.need_init_npc == true then
self.need_init_npc = false
self:init_npc_after_load()
end
-- , . ( )
self:register_delayed_npc()
self.check_time = time_global()
end
-- .
-- .
function se_smart_terrain:on_unregister()
cse_alife_smart_zone.on_unregister(self)
self.board:unregister_smart(self)
smart_terrains_by_name[self:name()] = nil
unregister_story_object_by_id(self.id)
simulation_objects.get_sim_obj_registry():unregister(self)
end
-- custom data.
function se_smart_terrain:read_params()
self.ini = self:spawn_ini()
if not self.ini:section_exist( SMART_TERRAIN_SECT ) then
abort( "[smart_terrain %s] no configuration!", self:name() )
self.disabled = true
return
end
local filename = utils.cfg_get_string(self.ini, SMART_TERRAIN_SECT, "cfg", self, false, "")
local fs = getFS()
if filename then
if fs:exist("$game_config$",filename) then
self.ini = ini_file(filename)
else
abort("There is no configuration file [%s] in smart_terrain [%s]", filename, self:name())
end
end
local ini = self.ini
self.sim_type = utils.cfg_get_string(ini, SMART_TERRAIN_SECT, "sim_type", self, false, "", "default")
--'
if valid_territory[self.sim_type] == nil then
abort("Wrong sim_type value [%s] in smart [%s]", self.sim_type, self:name())
end
self.squad_id = utils.cfg_get_number(ini, SMART_TERRAIN_SECT, "squad_id", self, false, 0)
self.respawn_sector = utils.cfg_get_string(ini, SMART_TERRAIN_SECT, "respawn_sector", self, false, "")
self.respawn_radius = utils.cfg_get_number(ini, SMART_TERRAIN_SECT, "respawn_radius", self, false, 150)
if self.respawn_sector ~= nil then
if self.respawn_sector == "default" then
self.respawn_sector = "all"
end
self.respawn_sector = xr_logic.parse_condlist(nil, SMART_TERRAIN_SECT, "respawn_sector", self.respawn_sector)
end
self.mutant_lair = utils.cfg_get_bool(ini, SMART_TERRAIN_SECT, "mutant_lair", self, false)
self.no_mutant = utils.cfg_get_bool(ini, SMART_TERRAIN_SECT, "no_mutant", self, false)
if self.no_mutant == true then
printf("Found no mutant point %s", self:name())
end
self.forbidden_point = utils.cfg_get_string(ini, SMART_TERRAIN_SECT, "forbidden_point", self, false, "")
--'
self.def_restr = utils.cfg_get_string(ini, SMART_TERRAIN_SECT, "def_restr", self, false, "", nil)
self.att_restr = utils.cfg_get_string(ini, SMART_TERRAIN_SECT, "att_restr", self, false, "", nil)
self.safe_restr = utils.cfg_get_string(ini, SMART_TERRAIN_SECT, "safe_restr", self, false, "", nil)
self.spawn_point = utils.cfg_get_string(ini, SMART_TERRAIN_SECT, "spawn_point", self, false, "")
self.arrive_dist = utils.cfg_get_number(ini, SMART_TERRAIN_SECT, "arrive_dist", self, false, 30)
-- self.max_population = utils.cfg_get_number(ini, SMART_TERRAIN_SECT, "max_population", self, false, 0)
local max_population = utils.cfg_get_string(ini, SMART_TERRAIN_SECT, "max_population", self, false, "", 0)
local parsed_condlist = xr_logic.parse_condlist(nil, SMART_TERRAIN_SECT, "max_population", max_population)
self.max_population = tonumber(xr_logic.pick_section_from_condlist(get_story_object("actor"), nil, parsed_condlist))
-- self.sim_avail = utils.cfg_get_string(ini, SMART_TERRAIN_SECT, "sim_avail", self, false, "")
-- if self.sim_avail ~= nil then
-- self.sim_avail = xr_logic.parse_condlist(nil, SMART_TERRAIN_SECT, "sim_avail", self.sim_avail)
-- end
local respawn_params = utils.cfg_get_string(ini, SMART_TERRAIN_SECT, "respawn_params", self, false, "", nil)
self.respawn_only_smart = utils.cfg_get_bool(ini, SMART_TERRAIN_SECT, "respawn_only_smart", self, false, false)
local smart_control_section = utils.cfg_get_string(ini, SMART_TERRAIN_SECT, "smart_control", self, false, "", nil)
if smart_control_section ~= nil then
self.base_on_actor_control = smart_terrain_control.CBaseOnActorControl(self, ini, smart_control_section)
end
self.respawn_point = false
if respawn_params ~= nil then
self:check_respawn_params(respawn_params)
end
if level.patrol_path_exists(self:name() .. "_traveller_actor") then
printf("Smart_terrain [%s] has no traveller_actor path!!!!!", self:name())
self.traveler_actor_path = self:name() .. "_traveller_actor"
end
if level.patrol_path_exists(self:name() .. "_traveller_squad") then
printf("Smart_terrain [%s] has no traveller_squad path!!!!!", self:name())
self.traveler_squad_path = self:name() .. "_traveller_squad"
end
if not locations_ini:section_exist(self:name()) then
printf("! SMART_TERRAIN [%s] has no terrain_mask section in smart_terrain_masks.ltx!!!",self:name())
end
end
--*******************************************************
--
--*******************************************************
--
-- profile_name()
function se_smart_terrain:fill_npc_info(obj)
local npc_info = {}
printf("filling npc_info for obj [%s]", tostring(obj:name()))
local is_stalker = IsStalker(obj)
npc_info.se_obj = obj
npc_info.is_monster = not is_stalker
npc_info.need_job = "nil" -- . .
npc_info.job_prior = -1
npc_info.job_id = -1
npc_info.begin_job = false
if is_stalker then
npc_info.stype = modules.stype_stalker
else
npc_info.stype = modules.stype_mobile
end
return npc_info
end
function se_smart_terrain:refresh_script_logic(obj_id)
local object = alife():object(obj_id)
local stype = modules.stype_mobile
if IsStalker(object) then
stype = modules.stype_stalker
end
xr_logic.initialize_obj(db.storage[object.id].object, db.storage[object.id], false, db.actor, stype)
end
-- npc smart terrain.
function se_smart_terrain:register_npc(obj)
printf("[smart_terrain %s] register called obj=%s", self:name(), obj:name())
self.population = self.population + 1
if self.b_registred == false then
table.insert(self.npc_to_register, obj)
return
end
-- , .
if not IsStalker(obj) then
obj:smart_terrain_task_activate()
end
obj.m_smart_terrain_id = self.id
if arrived_to_smart(obj, self) then
self.npc_info[obj.id] = self:fill_npc_info(obj)
-- , .
self.dead_time = {}
--
self:select_npc_job(self.npc_info[obj.id])
else
self.arriving_npc[obj.id] = obj
end
end
-- . ,
function se_smart_terrain:register_delayed_npc()
for k,v in pairs(self.npc_to_register) do
self:register_npc(v)
end
self.npc_to_register = {}
end
-- npc
function se_smart_terrain:unregister_npc(obj)
--callstack()
printf("smart [%s] unregister npc [%s]", self:name(), obj:name())
self.population = self.population - 1
if self.npc_info[obj.id] ~= nil then
-- TODO:
self.npc_info[obj.id].job_link.npc_id = nil
self.npc_info[obj.id] = nil
obj:clear_smart_terrain()
if db.storage[obj.id] ~= nil then
local object = db.storage[obj.id].object
local stype = modules.stype_mobile
if IsStalker(obj) then
stype = modules.stype_stalker
end
xr_logic.initialize_obj(object, db.storage[obj.id], false, db.actor, stype)
end
return
end
if self.arriving_npc[obj.id] ~= nil then
self.arriving_npc[obj.id] = nil
obj:clear_smart_terrain()
return
end
abort("self.npc_info[obj.id] = nil !!! obj.id=%d", obj.id)
end
--
function se_smart_terrain:clear_dead(obj)
if self.npc_info[obj.id] ~= nil then
--
self.dead_time[self.npc_info[obj.id].job_id] = game.get_game_time()
self.npc_info[obj.id].job_link.npc_id = nil
self.npc_info[obj.id] = nil
obj:clear_smart_terrain()
return
end
if self.arriving_npc[obj.id] ~= nil then
self.arriving_npc[obj.id] = nil
obj:clear_smart_terrain()
return
end
abort("self.npc_info[obj.id] = nil !!! obj.id=%d", obj.id)
end
-- .
function se_smart_terrain:task(obj)
if self.arriving_npc[obj.id] ~= nil then
return self.smart_alife_task
end
return self.job_data[self.npc_info[obj.id].job_id].alife_task
end
--*******************************************************
--
--*******************************************************
-- ( gulag_general)
function se_smart_terrain:load_jobs()
--printf("LOAD JOBS %s", self:name())
--
self.jobs = gulag_general.load_job(self)
-- ltx .
self.ltx, self.ltx_name = xr_gulag.loadLtx(self:name())
--
--
local function sort_jobs(jobs)
for k,v in pairs(jobs) do
if v.jobs ~= nil then
sort_jobs(v.jobs)
end
end
table.sort(jobs, function(a,b) return a._prior > b._prior end )
end
-- if self:name() == "jup_a10_smart_terrain" then
-- printf("before sort")
-- store_table(self.jobs)
-- end
sort_jobs(self.jobs)
--if self:name() == "jup_a10_smart_terrain" then
-- printf("after sort")
-- store_table(self.jobs)
--end
-- .
-- :
--self.job_data[job_id] = {}
local id = 0
self.job_data = {}
local function get_jobs_data(jobs)
for k,v in pairs(jobs) do
if v.jobs ~= nil then
get_jobs_data(v.jobs)
else
if v.job_id == nil then
print_table(self.jobs)
abort("Incorrect job table")
end
self.job_data[id] = v.job_id
self.job_data[id]._prior = v._prior --
v.job_id = id
id = id + 1
end
end
end
get_jobs_data(self.jobs)
-- alife_task
for k,v in pairs(self.job_data) do
local section = v.section
local ltx = v.ini_file or self.ltx
if not ltx:line_exist(section, "active") then
abort("gulag: ltx=%s no 'active' in section %s", self.ltx_name, section)
end
local active_section = ltx:r_string(section, "active")
-- printf("job_type %s job_section %s", tostring(v.job_type), tostring(section))
-- alife_path
if v.job_type == "path_job" then --
local path_field
for i,vv in pairs(path_fields) do
if ltx:line_exist(active_section, vv) then
path_field = vv
break
end
end
--printf("path_field %s prefix_name %s active_section %s", tostring(path_field), tostring(v.prefix_name), tostring(active_section))
local path_name = ltx:r_string(active_section, path_field)
if v.prefix_name ~= nil then
path_name = v.prefix_name .. "_" .. path_name
else
path_name = self:name() .. "_" .. path_name
end
if path_field == "center_point" then --' TODO
if level.patrol_path_exists(path_name .. "_task") then
path_name = path_name .. "_task"
end
end
v.alife_task = CALifeSmartTerrainTask(path_name)
elseif v.job_type == "smartcover_job" then --
local smartcover_name = ltx:r_string(active_section, "cover_name")
local smartcover = se_smart_cover.registered_smartcovers[smartcover_name]
if smartcover == nil then
abort("There is an exclusive job with wrong smatrcover name [%s] smartterrain [%s]", tostring(smartcover_name), self:name())
end
printf("Returning alife task for object [%s] game_vertex [%s] level_vertex [%s] position %s", smartcover.id, smartcover.m_game_vertex_id, smartcover.m_level_vertex_id, vec_to_str(smartcover.position))
v.alife_task = CALifeSmartTerrainTask(smartcover.m_game_vertex_id, smartcover.m_level_vertex_id)
elseif v.job_type == "point_job" then --
v.alife_task = self.smart_alife_task
end
v.game_vertex_id = v.alife_task:game_vertex_id()
v.level_id = game_graph():vertex(v.game_vertex_id):level_id()
v.position = v.alife_task:position()
end
end
-- .
-- object,
function se_smart_terrain:update_jobs()
self:check_alarm()
--printf("UPDATE JOBS %s", self:name())
-- , -
for k,v in pairs(self.arriving_npc) do
if arrived_to_smart(v, self) then
self.npc_info[v.id] = self:fill_npc_info(v)
-- , .
self.dead_time = {}
--
self:select_npc_job(self.npc_info[v.id])
self.arriving_npc[k] = nil
end
end
--
table.sort(self.npc_info, function(a,b) return a.job_prior < b.job_prior end )
for k,v in pairs(self.npc_info) do
self:select_npc_job(v)
end
end
--
function se_smart_terrain:select_npc_job(npc_info)
--
local selected_job_id, selected_job_prior, selected_job_link = job_iterator(self.jobs, npc_info, 0, self)
if selected_job_id == nil then
print_table(self.jobs)
abort("Insufficient smart_terrain jobs %s", self:name())
end
--
if selected_job_id ~= npc_info.job_id and selected_job_link ~= nil then
--
--printf("NPC %s FOUND JOB %s SECTION %s", npc_info.se_obj:name(), selected_job_id, self.job_data[selected_job_link.job_id].section)
-- - .
if npc_info.job_link ~= nil then
self.npc_by_job_section[self.job_data[npc_info.job_link.job_id].section] = nil
npc_info.job_link.npc_id = nil
end
selected_job_link.npc_id = npc_info.se_obj.id
self.npc_by_job_section[self.job_data[selected_job_link.job_id].section] = selected_job_link.npc_id
npc_info.job_id = selected_job_link.job_id
npc_info.job_prior = selected_job_link._prior
npc_info.begin_job = false
-- ,
npc_info.job_link = selected_job_link
--
local obj_storage = db.storage[npc_info.se_obj.id]
if obj_storage ~= nil then
xr_logic.switch_to_section(obj_storage.object, self.ltx, "nil")
end
end
if npc_info.begin_job ~= true then
-- , ( )
local job_data = self.job_data[npc_info.job_id]
--
printf("[smart_terrain %s] gulag: beginJob: obj=%s job= %s", self:name(), npc_info.se_obj:name(), job_data.section)
-- , .
db.offline_objects[npc_info.se_obj.id] = {}
npc_info.begin_job = true
local obj_storage = db.storage[npc_info.se_obj.id]
if obj_storage ~= nil then
self:setup_logic(obj_storage.object)
end
end
end
-- , .
function se_smart_terrain:setup_logic(obj)
--printf("setup npc logic %s", obj:name())
-- callstack()
local npc_data = self.npc_info[obj:id()]
local job = self.job_data[npc_data.job_id]
local ltx = job.ini_file or self.ltx
local ltx_name = job.ini_path or self.ltx_name
xr_logic.configure_schemes(obj, ltx, ltx_name, npc_data.stype, job.section, job.prefix_name or self:name())
local sect = xr_logic.determine_section_to_activate(obj, ltx, job.section, db.actor)
if utils.get_scheme_by_section(job.section) == "nil" then
abort("[smart_terrain %s] section=%s, don't use section 'nil'!", self:name(), sect)
end
xr_logic.activate_by_section(obj, ltx, sect, job.prefix_name or self:name(), false)
end
-- ,
function se_smart_terrain:getJob(obj_id)
return self.npc_info[obj_id] and self.job_data[self.npc_info[obj_id].job_id]
end
-- , .
function se_smart_terrain:idNPCOnJob(job_name)
return self.npc_by_job_section[job_name]
end
function se_smart_terrain:switch_to_desired_job(npc)
--
local npc_id = npc:id()
local npc_info = self.npc_info[npc_id]
--printf("***** %s -> %s", npc:name(), tostring(npc_info.need_job))
local changing_npc_id = self.npc_by_job_section[npc_info.need_job]
--printf("changing_npc_id %s", tostring(changing_npc_id))
if changing_npc_id == nil then
-- ,
self.npc_info[npc_id].job_link = nil
self.npc_info[npc_id].job_id = -1
self.npc_info[npc_id].job_prior = -1
self:select_npc_job(self.npc_info[npc_id])
--print_table(self.npc_by_job_section)
--abort("ERROR during channging NPC")
return
end
if self.npc_info[changing_npc_id] == nil then
-- ,
self.npc_info[npc_id].job_link = nil
self.npc_info[npc_id].job_id = -1
self.npc_info[npc_id].job_prior = -1
self:select_npc_job(self.npc_info[npc_id])
--print_table(self.npc_by_job_section)
--abort("ERROR during channging NPC")
return
end
local desired_job = self.npc_info[changing_npc_id].job_id
--
if npc_info.job_link ~= nil then
self.npc_by_job_section[self.job_data[npc_info.job_link.job_id].section] = nil
npc_info.job_link.npc_id = nil
end
local selected_job_link = self.npc_info[changing_npc_id].job_link
selected_job_link.npc_id = npc_info.se_obj.id
self.npc_by_job_section[self.job_data[selected_job_link.job_id].section] = selected_job_link.npc_id
npc_info.job_id = selected_job_link.job_id
npc_info.job_prior = selected_job_link._prior
npc_info.begin_job = true
-- ,
npc_info.job_link = selected_job_link
npc_info.need_job = "nil"
local obj_storage = db.storage[npc_id]
if obj_storage ~= nil then
self:setup_logic(obj_storage.object)
end
-- ,
self.npc_info[changing_npc_id].job_link = nil
self.npc_info[changing_npc_id].job_id = -1
self.npc_info[changing_npc_id].job_prior = -1
self:select_npc_job(self.npc_info[changing_npc_id])
end
--*******************************************************
-- /
--*******************************************************
--
function se_smart_terrain:STATE_Write(packet)
cse_alife_smart_zone.STATE_Write(self, packet)
set_save_marker(packet, "save", false, "se_smart_terrain")
-- ,
local n = 0
for k,v in pairs(self.arriving_npc) do
n = n + 1
end
packet:w_u8(n)
for k,v in pairs(self.arriving_npc) do
packet:w_u16(k)
end
--
n = 0
for k,v in pairs(self.npc_info) do
n = n + 1
end
packet:w_u8(n)
for k,v in pairs(self.npc_info) do
packet:w_u16(k)
packet:w_u8(v.job_prior)
packet:w_u8(v.job_id)
packet:w_bool(v.begin_job)
packet:w_stringZ(v.need_job)
end
n = 0
for k,v in pairs(self.dead_time) do
n = n + 1
end
packet:w_u8(n)
for k,v in pairs(self.dead_time) do
packet:w_u8(k)
utils.w_CTime(packet, v)
end
if self.base_on_actor_control ~= nil then
packet:w_bool(true)
self.base_on_actor_control:save(packet)
else
packet:w_bool(false)
end
if self.respawn_point then
packet:w_bool(true)
local n = 0
for k,v in pairs(self.already_spawned) do
n = n + 1
end
packet:w_u8(n)
for k,v in pairs(self.already_spawned) do
packet:w_stringZ(k)
packet:w_u8(v.num)
end
if self.last_respawn_update ~= nil then
packet:w_bool(true)
utils.w_CTime(packet, self.last_respawn_update)
else
packet:w_bool(false)
end
else
packet:w_bool(false)
end
if self.population < 0 then
abort("Smart_terrain [%s] population can't be less than zero!!!", self:name())
end
packet:w_u8(self.population)
set_save_marker(packet, "save", true, "se_smart_terrain")
end
--
function se_smart_terrain:STATE_Read(packet, size)
cse_alife_smart_zone.STATE_Read(self, packet, size)
-- LevelEditor
if editor() then
return
end
set_save_marker(packet, "load", false, "se_smart_terrain")
self:read_params()
-- ,
local n = packet:r_u8()
self.arriving_npc = {}
for i = 1,n do
local id = packet:r_u16()
self.arriving_npc[id] = false
end
--
n = packet:r_u8()
--printf("load %s npc", tostring(n))
self.npc_info = {}
for i = 1,n do
local id = packet:r_u16()
--printf("__ id %s", tostring(id))
self.npc_info[id] = {}
local npc_info = self.npc_info[id]
npc_info.job_prior = packet:r_u8()
--printf("__ job_prior %s", tostring(npc_info.job_prior))
if npc_info.job_prior == 255 then
npc_info.job_prior = -1
end
npc_info.job_id = packet:r_u8()
--printf("__ job_id %s", tostring(npc_info.job_id))
if npc_info.job_id == 255 then
npc_info.job_id = -1
end
npc_info.begin_job = packet:r_bool()
--printf("__ begin_job %s", tostring(npc_info.begin_job))
npc_info.need_job = packet:r_stringZ()
end
n = packet:r_u8()
self.dead_time = {}
--printf("load %s dead_time", tostring(n))
for i =1,n do
local job_id = packet:r_u8()
--printf("__ job_id %s", tostring(job_id))
local dead_time = utils.r_CTime(packet)
self.dead_time[job_id] = dead_time
end
self.need_init_npc = true
if self.script_version > 9 then
if packet:r_bool() == true then
--self.base_on_actor_control
self.base_on_actor_control:load(packet)
end
end
local respawn_point = packet:r_bool()
--printf("LOAD RESPAWN %s", self:name())
if respawn_point then
n = packet:r_u8()
for i = 1, n do
local id = packet:r_stringZ()
local num = packet:r_u8()
self.already_spawned[id].num = num
end
if self.script_version > 11 then
local exist = packet:r_bool()
if exist then
self.last_respawn_update = utils.r_CTime(packet)
else
self.last_respawn_update = nil
end
end
end
self.population = packet:r_u8()
set_save_marker(packet, "load", true, "se_smart_terrain")
end
-- .
function se_smart_terrain:init_npc_after_load()
local function find_job(jobs, npc_info)
for k,v in pairs(jobs) do
if v.jobs ~= nil then
find_job(v.jobs, npc_info)
else
if v.job_id == npc_info.job_id then
npc_info.job_link = v
v.npc_id = npc_info.se_obj.id
return
end
end
end
end
local sim = alife()
--printf("[%s] init_npc_after_load", self:name())
for k,v in pairs(self.arriving_npc) do
local sobj = sim:object(k)
if sobj ~= nil then
self.arriving_npc[k] = sobj
else
self.arriving_npc[k] = nil
end
end
for k,v in pairs(self.npc_info) do
local sobj = sim:object(k)
if sobj ~= nil then
local npc_info = self:fill_npc_info(sobj)
npc_info.job_prior = v.job_prior
npc_info.job_id = v.job_id
npc_info.begin_job = v.begin_job
npc_info.need_job = v.need_job
-- .
find_job(self.jobs, npc_info)
self.npc_info[k] = npc_info
if npc_info.job_link ~= nil then
self.npc_by_job_section[self.job_data[npc_info.job_link.job_id].section] = k
end
else
self.npc_info[k] = nil
end
end
end
--'
function se_smart_terrain:get_smart_props()
local props = smart_names.get_smart_terrain_name(self)
if(props==nil) or (_G.dev_debug) then
props = self:name().." ["..self.id.."]\\n"..
self.sim_type.."\\n"..
"squad_id = "..tostring(self.id).."\\n"..
"capacity = "..tostring(self.max_population).." ("..sim_board.get_sim_board():get_smart_population(self)..")\\n"
if self.respawn_point ~= nil and self.already_spawned ~= nil then
props = props.."\\nalready_spawned :\n"
for k,v in pairs(self.already_spawned) do
props = props.."["..k.."] = "..v.num.."("..xr_logic.pick_section_from_condlist(db.actor, nil,self.respawn_params[k].num)..")\\n"
end
if self.last_respawn_update then
props = props.."\\ntime_to_spawn:"..tostring(RESPAWN_IDLE - game.get_game_time():diffSec(self.last_respawn_update)).."\\n"
end
end
--'
for k,v in pairs(sim_board.get_sim_board().smarts[self.id].squads) do
props = props .. tostring(v.id) .. "\\n"
end
end
return props
end
--'
function se_smart_terrain:show()
local time = time_global()
if(self.showtime~=nil) and (self.showtime+200>=time) then
return
end
self.showtime = time
local player = self.player_name
local spot = "neutral"
if self.sim_avail == nil or xr_logic.pick_section_from_condlist(db.actor or alife():actor(), self, self.sim_avail) == "true" then
spot = "friend"
else
spot = "enemy"
end
if(self.smrt_showed_spot==spot) then
level.map_change_spot_hint(self.id, "alife_presentation_smart_"..self.sim_type.."_"..self.smrt_showed_spot, self:get_smart_props())
return
end
if(_G.dev_debug) then
if(self.smrt_showed_spot~=nil) then
level.map_remove_object_spot(self.id, "alife_presentation_smart_"..self.sim_type.."_"..self.smrt_showed_spot)
end
level.map_add_object_spot(self.id, "alife_presentation_smart_"..self.sim_type.."_"..spot, self:get_smart_props())
self.smrt_showed_spot = spot
else
if(self.smrt_showed_spot~=nil) and
(level.map_has_object_spot(self.id, "alife_presentation_smart_"..self.sim_type.."_"..self.smrt_showed_spot)~=0)
then
level.map_remove_object_spot(self.id, "alife_presentation_smart_base_"..self.smrt_showed_spot)
end
end
end
--'
function se_smart_terrain:refresh()
self:show()
end
--'
function se_smart_terrain:hide()
if self.smrt_showed_spot == nil then
return
end
level.map_remove_object_spot(self.id, "alife_presentation_smart_"..self.sim_type.."_"..self.smrt_showed_spot)
end
local function is_only_monsters_on_jobs(npc_info)
for k,v in pairs (npc_info) do
if v.is_monster == false then
return false
end
end
return true
end
-- .
-- binder.
-- xr_effects
function se_smart_terrain:update()
cse_alife_smart_zone.update( self )
if dev_debug then
self:refresh() --
end
local current_time = time_global()
if simulation_objects.is_on_the_same_level(self, alife():actor()) then
local dist_to_actor = self.position:distance_to(alife():actor().position)
local old_dist_to_actor = (nearest_to_actor_smart.id == nil and nearest_to_actor_smart.dist) or alife():object(nearest_to_actor_smart.id).position:distance_to(alife():actor().position)
if dist_to_actor < old_dist_to_actor then
nearest_to_actor_smart.id = self.id
nearest_to_actor_smart.dist = dist_to_actor
end
end
-- .
if self.respawn_params ~= nil then
self:try_respawn()
end
if self.check_time~=nil and current_time < self.check_time then
return
end
-- - , ,
-- , ...
if is_only_monsters_on_jobs(self.npc_info) and self.campfires_on then
bind_campfire.turn_off_campfires_by_smart_name(self:name())
self.campfires_on = false
elseif not is_only_monsters_on_jobs(self.npc_info) and not self.campfires_on then
bind_campfire.turn_on_campfires_by_smart_name(self:name())
self.campfires_on = true
end
if db.actor ~= nil then
local distance = db.actor:position():distance_to_sqr(self.position)
local idle_time = math.max(60, 0.003 * distance)
self.check_time = current_time + idle_time
else
self.check_time = current_time + 10
end
-- , ,
local current_time = game.get_game_time()
for k,v in pairs(self.dead_time) do
if current_time:diffSec(v) >= DEATH_IDLE_TIME then
self.dead_time[k] = nil
end
end
--
self:update_jobs()
--
if self.base_on_actor_control ~= nil then
self.base_on_actor_control:update()
end
-- .
simulation_objects.get_sim_obj_registry():update_avaliability(self)
end
--
function se_smart_terrain:set_alarm()
self.smart_alarm_time = game.get_game_time()
end
-- .
function se_smart_terrain:check_alarm()
if self.smart_alarm_time == nil then
return
end
if game.get_game_time():diffSec(self.smart_alarm_time) > 21600 then -- 6
self.smart_alarm_time = nil
end
end
-- , .
-- net_spawn()
function setup_gulag_and_logic_on_spawn(obj, st, sobject, stype, loaded)
local sim = alife()
local sobject = alife():object(obj:id())
if sim ~= nil and sobject then
local strn_id = sobject.m_smart_terrain_id
printf( "setup_gulag_and_logic_on_spawn obj=%s, strn_id=%s, loaded=%s", obj:name(), tostring(strn_id), tostring(loaded))
if strn_id ~= nil and strn_id ~= 65535 then
local strn = sim:object(strn_id)
local need_setup_logic = (not loaded) and (strn.npc_info[obj:id()] and strn.npc_info[obj:id()].begin_job == true)
if need_setup_logic then
strn:setup_logic(obj)
else
xr_logic.initialize_obj(obj, st, loaded, db.actor, stype)
end
else
xr_logic.initialize_obj(obj, st, loaded, db.actor, stype)
end
else
xr_logic.initialize_obj(obj, st, loaded, db.actor, stype)
end
end
--
function on_death(obj)
local sim = alife()
if sim then
local obj = sim:object(obj.id)
if obj == nil then return end
local strn_id = obj:smart_terrain_id()
if strn_id ~= 65535 then
printf("clear dead object %s", obj:name())
sim:object(strn_id):clear_dead(obj)
end
end
end
--***********************************************************************************************
--* SIMULATION_TARGET_SMART *
--***********************************************************************************************
-- , , .
function se_smart_terrain:get_location()
return self.position, self.m_level_vertex_id, self.m_game_vertex_id
end
-- .
function se_smart_terrain:am_i_reached(squad)
local squad_pos, squad_lv_id, squad_gv_id = squad:get_location()
local target_pos, target_lv_id, target_gv_id = self:get_location()
if game_graph():vertex(squad_gv_id):level_id() ~= game_graph():vertex(target_gv_id):level_id() then
return false
end
if IsMonster(alife():object(squad:commander_id())) and squad:get_script_target() == nil then
return squad_pos:distance_to_sqr(target_pos) <= 25
end
return squad.always_arrived or squad_pos:distance_to_sqr(target_pos) <= self.arrive_dist^2
end
-- 1 .
function se_smart_terrain:on_after_reach(squad)
for k in squad:squad_members() do
local obj = k.object
squad.board:setup_squad_and_group(obj)
end
squad.current_target_id = self.id
end
-- 1 .
function se_smart_terrain:on_reach_target(squad)
-- squad.sound_manager:set_storyteller(squad:commander_id())
-- squad.sound_manager:set_story("squad_begin_attack")
squad:set_location_types(self:name())
self.board:assign_squad_to_smart(squad, self.id)
for k in squad:squad_members() do
if db.offline_objects[k.id] ~= nil then
db.offline_objects[k.id] = {}
end
end
-- self.board:exit_smart(squad, squad.smart_id)
end
-- CALifeSmartTerrainTask , smart_terrain:task()
function se_smart_terrain:get_alife_task()
return self.smart_alife_task
end
function smart_terrain_squad_count(board_smart_squads)
local count = 0
for k,v in pairs(board_smart_squads) do
if v:get_script_target() == nil then
count = count + 1
end
end
return count
end
function se_smart_terrain:sim_available()
if self.base_on_actor_control ~= nil and self.base_on_actor_control.status ~= smart_terrain_control.NORMAL then
return false
end
return true
end
local is_squad_monster =
{
["monster_predatory_day"] = true,
["monster_predatory_night"] = true,
["monster_vegetarian"] = true,
["monster_zombied_day"] = true,
["monster_zombied_night"] = true,
["monster_special"] = true
}
function surge_stats()
local sim_obj_registry = simulation_objects.get_sim_obj_registry().objects
local sim_squads = {
["zaton"] = {},
["jupiter"] = {},
["pripyat"] = {}
}
local sim_smarts = {
["zaton"] = {},
["jupiter"] = {},
["pripyat"] = {}
}
for k,v in pairs(sim_obj_registry) do
if v:clsid() == clsid.smart_terrain and tonumber(v.props["surge"]) > 0 then
local level_name = alife():level_name(game_graph():vertex(v.m_game_vertex_id):level_id())
if sim_smarts[level_name] ~= nil then
table.insert(sim_smarts[level_name], v)
end
end
if v:clsid() == clsid.online_offline_group_s then
local squad_params = sim_board.simulation_activities[v.player_id]
if squad_params ~= nil then
local smart_params = squad_params.smart.surge
if smart_params ~= nil then
local level_name = alife():level_name(game_graph():vertex(v.m_game_vertex_id):level_id())
if sim_squads[level_name] ~= nil then
table.insert(sim_squads[level_name], v)
end
end
end
end
end
local function print_smarts_and_squads_by_level(level_name)
printf("LEVEL: [%s]", level_name)
local max_capacity_total = 0
for i = 1, #sim_smarts[level_name] do
local smart = sim_smarts[level_name][i]
max_capacity_total = max_capacity_total + smart.max_population
local squad_count = smart_terrain_squad_count(sim_board.get_sim_board().smarts[smart.id].squads)
printf("smart: [%s] max_population [%d] squad_count [%d]", smart:name(),smart.max_population, squad_count)
end
printf("TOTAL: capacity total : [%d] squads total [%d]" , max_capacity_total, #sim_squads[level_name])
end
print_smarts_and_squads_by_level("zaton")
print_smarts_and_squads_by_level("jupiter")
print_smarts_and_squads_by_level("pripyat")
end
-- .
function se_smart_terrain:target_precondition(squad, need_to_dec_population)
if self.respawn_only_smart == true then
return false
end
local squad_count = smart_terrain_squad_count(self.board.smarts[self.id].squads)
if need_to_dec_population then
squad_count = squad_count - 1
end
if squad_count ~= nil and (self.max_population <= squad_count) then
--printf("smart terrain [%s] precondition returns false for squad [%s]", self:name(), squad:name())
-- if tonumber(self.props["surge"]) > 0 and xr_conditions.surge_started() then
-- printf("SURGE_SMART_STATS : smart [%s]\n max_population = %d \ squad_count = %d", self:name(), self.max_population, squad_count)
-- end
return false
end
local squad_params = sim_board.simulation_activities[squad.player_id]
if squad_params == nil or squad_params.smart == nil then
--printf("smart terrain [%s] precondition returns false for squad [%s]", self:name(), squad:name())
return false
end
if tonumber(self.props["resource"] )> 0 then
local smart_params = squad_params.smart.resource
if smart_params ~= nil and smart_params.prec(squad, self) then
return true
end
end
if tonumber(self.props["base"] )> 0 then
local smart_params = squad_params.smart.base
if smart_params ~= nil and smart_params.prec(squad, self) then
return true
end
end
if tonumber(self.props["lair"] )> 0 then
local smart_params = squad_params.smart.lair
if smart_params ~= nil and smart_params.prec(squad, self) then
return true
end
end
if tonumber(self.props["territory"] )> 0 then
local smart_params = squad_params.smart.territory
if smart_params ~= nil and smart_params.prec(squad, self) then
return true
end
end
if tonumber(self.props["surge"] )> 0 then
local smart_params = squad_params.smart.surge
if smart_params ~= nil and smart_params.prec(squad, self) then
return true
end
end
--printf("smart terrain [%s] precondition returns false for squad [%s]", self:name(), squad:name())
return false
--[[
local squad_count = smart_terrain_squad_count(self.board.smarts[self.id].squads)
if squad_count ~= nil and (self.max_population <= squad_count) then return false end
if squad.player_id == "stalker" and in_time_interval(9,19) and tonumber(self.props["resource"] )> 0 then
return true
end
--if squad.player_id ~= "monster_predatory" and squad.player_id ~= "monster_vegetarian" then
if not is_squad_monster[squad.player_id] then
if tonumber(self.props["base"]) > 0 and in_time_interval(20,8) then
return true
end
if tonumber(self.props["base"] ) > 0 and xr_conditions.surge_started() then
return true
end
else
if tonumber(self.props["lair"] ) > 0 and xr_conditions.surge_started() then
return true
end
if tonumber(self.props["lair"] ) > 0 and in_time_interval(7,20) then
return true
end
end
return false
]]
end
-- .
function se_smart_terrain:evaluate_prior(squad)
return simulation_objects.evaluate_prior(self, squad)
end
-- .
function se_smart_terrain:check_respawn_params(respawn_params)
--printf("CHECK RESPAWN PARAMS %s", self:name())
self.respawn_params = {}
self.already_spawned = {}
self.respawn_point = true
if not self.ini:section_exist(respawn_params) then
abort("Wrong smatr_terrain respawn_params section [%s](there is no section)", respawn_params)
end
local n = self.ini:line_count(respawn_params)
if n == 0 then
abort("Wrong smatr_terrain respawn_params section [%s](empty params)", respawn_params)
end
for j=0,n-1 do
local result, prop_name, prop_condlist = self.ini:r_line(respawn_params,j,"","")
if not self.ini:section_exist(prop_name) then
abort("Wrong smatr_terrain respawn_params section [%s] prop [%s](there is no section)", respawn_params, prop_name)
end
local spawn_squads = utils.cfg_get_string(self.ini, prop_name, "spawn_squads", self, false, "", nil)
local spawn_num = utils.cfg_get_string(self.ini, prop_name, "spawn_num", self, false, "", nil)
if spawn_squads == nil then
abort("Wrong smatr_terrain respawn_params section [%s] prop [%s] line [spawn_squads](there is no line)", respawn_params, prop_name)
elseif spawn_num == nil then
abort("Wrong smatr_terrain respawn_params section [%s] prop [%s] line [spawn_num](there is no line)", respawn_params, prop_name)
end
spawn_squads = utils.parse_names(spawn_squads)
spawn_num = xr_logic.parse_condlist(nil, prop_name, "spawn_num", spawn_num)
self.respawn_params[prop_name] = {}
self.already_spawned[prop_name] = {}
self.respawn_params[prop_name].squads = spawn_squads
self.respawn_params[prop_name].num = spawn_num
self.already_spawned[prop_name].num = 0
end
end
function se_smart_terrain:call_respawn()
local available_sects = {}
printf("respawn called from smart_terrain [%s]", self:name())
for k,v in pairs(self.respawn_params) do
if tonumber(xr_logic.pick_section_from_condlist(db.actor, nil,v.num)) > self.already_spawned[k].num then
table.insert(available_sects,k)
end
end
if #available_sects > 0 then
local sect_to_spawn = available_sects[math.random(1,#available_sects)]
local sect_to_spawn_params = self.respawn_params[sect_to_spawn]
local squad = sect_to_spawn_params.squads[math.random(1,#sect_to_spawn_params.squads)]
squad = self.board:create_squad(self, squad)
squad.respawn_point_id = self.id
squad.respawn_point_prop_section = sect_to_spawn
self.board:enter_smart(squad, self.id)
for m in squad:squad_members() do
self.board:setup_squad_and_group(m.object)
end
self.already_spawned[sect_to_spawn].num = self.already_spawned[sect_to_spawn].num + 1
end
end
function se_smart_terrain:try_respawn()
--printf("TRY RESPAWN %s", self:name())
local curr_time = game.get_game_time()
if self.last_respawn_update == nil or curr_time:diffSec(self.last_respawn_update) > RESPAWN_IDLE then
self.last_respawn_update = curr_time
if self.sim_avail ~= nil and xr_logic.pick_section_from_condlist(db.actor or alife():actor(), self, self.sim_avail) ~= "true" then return end
local squad_count = smart_terrain_squad_count(self.board.smarts[self.id].squads)
if self.max_population <= squad_count then printf("%s cannot respawn due to squad_count %s of %s", self:name(), self.max_population, squad_count) return end
local dist_to_actor = alife():actor().position:distance_to_sqr(self.position)
if dist_to_actor < RESPAWN_RADIUS^2 then printf("%s cannot respawn due to distance", self:name()) return end
self:call_respawn()
end
end | 412 | 0.878475 | 1 | 0.878475 | game-dev | MEDIA | 0.967752 | game-dev | 0.980817 | 1 | 0.980817 |
MartinTheDragon/Nuclear-Tech-Mod-Remake | 8,127 | src/main/kotlin/at/martinthedragon/nucleartech/menu/MenuFunctions.kt | package at.martinthedragon.nucleartech.menu
import at.martinthedragon.nucleartech.api.fluid.trait.AttachedFluidTrait
import at.martinthedragon.nucleartech.api.fluid.trait.FluidTrait
import at.martinthedragon.nucleartech.api.fluid.trait.getTraitForFluidStack
import at.martinthedragon.nucleartech.block.entity.UpgradeableMachine
import at.martinthedragon.nucleartech.capability.CapabilityCache
import at.martinthedragon.nucleartech.extensions.ifPresentInline
import at.martinthedragon.nucleartech.fluid.trait.FluidTraitManager
import at.martinthedragon.nucleartech.item.upgrades.MachineUpgradeItem
import it.unimi.dsi.fastutil.objects.Object2ObjectArrayMap
import net.minecraft.client.Minecraft
import net.minecraft.network.FriendlyByteBuf
import net.minecraft.tags.TagKey
import net.minecraft.world.Container
import net.minecraft.world.entity.player.Player
import net.minecraft.world.inventory.AbstractContainerMenu
import net.minecraft.world.inventory.Slot
import net.minecraft.world.item.Item
import net.minecraft.world.item.ItemStack
import net.minecraft.world.level.block.entity.BlockEntity
import net.minecraft.world.level.material.Fluid
import net.minecraftforge.common.capabilities.Capability
import net.minecraftforge.common.util.LazyOptional
import net.minecraftforge.energy.CapabilityEnergy
import net.minecraftforge.fluids.FluidStack
import net.minecraftforge.fluids.capability.CapabilityFluidHandler
import net.minecraftforge.fluids.capability.IFluidHandler
import net.minecraftforge.fluids.capability.templates.FluidTank
import net.minecraftforge.fml.DistExecutor
import net.minecraftforge.fml.DistExecutor.SafeSupplier
inline fun addPlayerInventory(
addSlot: (Slot) -> Slot,
playerInventory: Container,
xStart: Int,
yStart: Int,
slotCreator: (inventory: Container, index: Int, x: Int, y: Int) -> Slot = ::Slot
) {
val slotSize = 18
val rows = 3
val columns = 9
for (i in 0 until rows)
for (j in 0 until columns) {
addSlot(slotCreator(playerInventory, j + i * 9 + 9, xStart + j * slotSize, yStart + i * slotSize))
}
val newYStart = yStart + slotSize * rows + 4
for (i in 0 until columns) {
addSlot(slotCreator(playerInventory, i, xStart + i * slotSize, newYStart))
}
}
/** Should not be used outside Container.quickMoveStack */
fun AbstractContainerMenu.tryMoveInPlayerInventory(index: Int, inventoryStart: Int, itemStack: ItemStack): Boolean {
if (index >= inventoryStart && index < (slots.size - 9).coerceAtLeast(inventoryStart + 1)) {
if (!moveItemStackTo(itemStack, (slots.size - 9).coerceAtLeast(inventoryStart), slots.size, false))
return false
} else if (index >= (slots.size - 9) && index < slots.size && !moveItemStackTo(itemStack, inventoryStart, (slots.size - 9), false))
return false
return true
}
inline fun AbstractContainerMenu.quickMoveStackBoilerplate(player: Player, index: Int, playerInventoryStart: Int, outputSlots: IntArray, moveContextBuilder: MenuMoveFunctionContext.() -> IntRange?): ItemStack {
var returnStack = ItemStack.EMPTY
val slot = slots[index]
if (slot.hasItem()) {
val itemStack = slot.item
returnStack = itemStack.copy()
if (index in outputSlots) {
if (!moveItemStackTo(itemStack, playerInventoryStart, slots.size, true)) return ItemStack.EMPTY
slot.onQuickCraft(itemStack, returnStack)
} else if (index !in 0 until playerInventoryStart) {
val context = MenuMoveFunctionContext(this, itemStack)
val defaultSlots = context.run(moveContextBuilder)
val success = context.evaluate()
if (!success &&
defaultSlots?.let { !moveItemStackTo(itemStack, defaultSlots.first, defaultSlots.last + 1, false) } == true &&
!tryMoveInPlayerInventory(index, playerInventoryStart, itemStack)
) {
return ItemStack.EMPTY
}
} else if (!moveItemStackTo(itemStack, playerInventoryStart, slots.size, false)) return ItemStack.EMPTY
if (itemStack.isEmpty) slot.set(ItemStack.EMPTY)
else slot.setChanged()
if (itemStack.count == returnStack.count) return ItemStack.EMPTY
slot.onTake(player, itemStack)
}
return returnStack
}
class MenuMoveFunctionContext(private val menu: AbstractContainerMenu, val itemStack: ItemStack) {
private val conditionMap = Object2ObjectArrayMap<(ItemStack) -> Boolean, IntRange>()
fun evaluate(): Boolean {
for ((condition, slots) in conditionMap.object2ObjectEntrySet()) {
if (condition(itemStack) && menu.moveItemStackTo(itemStack, slots.first, slots.last + 1, false))
return true
}
return false
}
infix fun IntRange.check(condition: (ItemStack) -> Boolean) {
conditionMap += condition to this
}
infix fun Int.check(condition: (ItemStack) -> Boolean) {
this..this check condition
}
infix fun ((ItemStack) -> Boolean).and(condition: (ItemStack) -> Boolean) = { stack: ItemStack -> this(stack) && condition(stack) }
fun itemTagCondition(tag: TagKey<Item>) = { stack: ItemStack -> stack.`is`(tag) }
inline fun <reified T> itemIsInstanceCondition() = { stack: ItemStack -> stack.item is T }
fun compatibleMachineUpgradeCondition(machine: UpgradeableMachine) = { stack: ItemStack -> MachineUpgradeItem.isValidFor(machine, stack) }
private val capabilityCache = CapabilityCache()
fun <T : Any> getCapability(capability: Capability<T>): LazyOptional<T> = capabilityCache.getOrAddToCache(capability, null, itemStack::getCapability)
fun hasCapability(capability: Capability<*>) = getCapability(capability).isPresent
fun supportsEnergyCondition() = { _: ItemStack -> hasCapability(CapabilityEnergy.ENERGY) }
fun supportsFluidsCondition() = { _: ItemStack -> hasCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY) }
fun containsFluidCondition(fluid: Fluid) = { _: ItemStack -> getCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY).ifPresentInline { !it.drain(FluidStack(fluid, Int.MAX_VALUE), IFluidHandler.FluidAction.SIMULATE).isEmpty } == true }
fun canDrainTankCondition(outputTank: FluidTank) = { _: ItemStack -> getCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY).ifPresentInline { it.fill(FluidStack(outputTank.fluid.rawFluid, 1), IFluidHandler.FluidAction.SIMULATE) > 0 || it.fill(FluidStack(outputTank.fluid.rawFluid, outputTank.capacity), IFluidHandler.FluidAction.SIMULATE) > 0 } == true }
fun canFillTankCondition(inputTank: FluidTank) = { _: ItemStack -> getCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY).ifPresentInline { !it.drain(FluidStack(inputTank.fluid.rawFluid, 1), IFluidHandler.FluidAction.SIMULATE).isEmpty || !it.drain(FluidStack(inputTank.fluid.rawFluid, inputTank.capacity), IFluidHandler.FluidAction.SIMULATE).isEmpty } == true }
inline fun <reified T : FluidTrait> fluidTraitCondition(crossinline fluidGetter: (ItemStack) -> Fluid, crossinline condition: (AttachedFluidTrait<T>) -> Boolean) = { stack: ItemStack -> FluidTraitManager.getTraitForFluidStack<T>(FluidStack(fluidGetter(stack), 1000))?.let(condition) == true }
}
fun <T : BlockEntity> getBlockEntityForContainer(buffer: FriendlyByteBuf): T = DistExecutor.safeRunForDist({ ClientBlockEntityGetter(buffer) }, ::ServerBlockEntityGetter)
private class ServerBlockEntityGetter : SafeSupplier<Nothing> {
override fun get(): Nothing {
throw IllegalAccessException("Cannot call function on server")
}
}
private class ClientBlockEntityGetter<out T : BlockEntity>(private val buffer: FriendlyByteBuf) : SafeSupplier<@UnsafeVariance T> {
@Suppress("UNCHECKED_CAST")
override fun get(): T {
val pos = buffer.readBlockPos()
return (Minecraft.getInstance().level?.getBlockEntity(pos) ?: throw IllegalStateException("Invalid block entity position sent from server: $pos"))
as? T ?: throw IllegalStateException("Cannot open container on wrong block entity")
}
}
| 412 | 0.921948 | 1 | 0.921948 | game-dev | MEDIA | 0.98901 | game-dev | 0.976493 | 1 | 0.976493 |
Advanced-Rocketry/AdvancedRocketry | 1,438 | src/main/java/zmaster587/advancedRocketry/network/PacketMoveRocketInSpace.java | package zmaster587.advancedRocketry.network;
import io.netty.buffer.ByteBuf;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import zmaster587.advancedRocketry.util.SpacePosition;
import zmaster587.libVulpes.network.BasePacket;
public class PacketMoveRocketInSpace extends BasePacket {
SpacePosition position;
int dimId = 0, starId=0;
boolean hasWorld;
boolean hasStar;
public PacketMoveRocketInSpace() {
}
public PacketMoveRocketInSpace(SpacePosition position) {
this.position = position;
}
@Override
public void write(ByteBuf out) {
out.writeDouble(position.x);
out.writeDouble(position.y);
out.writeDouble(position.z);
hasWorld = position.world == null;
hasStar = position.star == null;
out.writeBoolean(hasWorld);
if(hasWorld)
out.writeInt(position.world.getId());
out.writeBoolean(hasStar);
if(hasStar)
out.writeInt(position.star.getId());
}
@Override
public void readClient(ByteBuf in) {
}
@Override
public void read(ByteBuf in) {
position.x = in.readDouble();
position.y = in.readDouble();
position.z = in.readDouble();
hasWorld = in.readBoolean();
if(hasWorld)
dimId = in.readInt();
hasStar = in.readBoolean();
if(hasStar)
starId = in.readInt();
}
@Override
public void executeClient(EntityPlayer thePlayer) {
}
@Override
public void executeServer(EntityPlayerMP player)
{
}
}
| 412 | 0.85495 | 1 | 0.85495 | game-dev | MEDIA | 0.750626 | game-dev | 0.90533 | 1 | 0.90533 |
MaxOhn/rosu-pp | 3,015 | src/any/difficulty/skills.rs | use crate::util::{float_ext::FloatExt, hint::unlikely, strains_vec::StrainsVec};
pub trait StrainSkill: Sized {
type DifficultyObject<'a>;
type DifficultyObjects<'a>: ?Sized;
const DECAY_WEIGHT: f64 = 0.9;
const SECTION_LENGTH: i32 = 400;
fn process<'a>(
&mut self,
curr: &Self::DifficultyObject<'a>,
objects: &Self::DifficultyObjects<'a>,
);
fn count_top_weighted_strains(&self, difficulty_value: f64) -> f64;
fn save_current_peak(&mut self);
fn start_new_section_from<'a>(
&mut self,
time: f64,
curr: &Self::DifficultyObject<'a>,
objects: &Self::DifficultyObjects<'a>,
);
fn into_current_strain_peaks(self) -> StrainsVec;
fn get_current_strain_peaks(
mut strain_peaks: StrainsVec,
current_section_peak: f64,
) -> StrainsVec {
strain_peaks.push(current_section_peak);
strain_peaks
}
fn difficulty_value(current_strain_peaks: StrainsVec) -> f64;
fn into_difficulty_value(self) -> f64;
fn cloned_difficulty_value(&self) -> f64;
}
pub trait StrainDecaySkill: StrainSkill {
fn calculate_initial_strain<'a>(
&self,
time: f64,
curr: &Self::DifficultyObject<'a>,
objects: &Self::DifficultyObjects<'a>,
) -> f64;
fn strain_value_at<'a>(
&mut self,
curr: &Self::DifficultyObject<'a>,
objects: &Self::DifficultyObjects<'a>,
) -> f64;
fn strain_decay(ms: f64) -> f64;
}
pub fn count_top_weighted_strains(object_strains: &[f64], difficulty_value: f64) -> f64 {
if unlikely(object_strains.is_empty()) {
return 0.0;
}
// * What would the top strain be if all strain values were identical
let consistent_top_strain = difficulty_value / 10.0;
if unlikely(FloatExt::eq(consistent_top_strain, 0.0)) {
return object_strains.len() as f64;
}
// * Use a weighted sum of all strains. Constants are arbitrary and give nice values
object_strains
.iter()
.map(|s| 1.1 / (1.0 + f64::exp(-10.0 * (s / consistent_top_strain - 0.88))))
.sum()
}
pub fn difficulty_value(current_strain_peaks: StrainsVec, decay_weight: f64) -> f64 {
let mut difficulty = 0.0;
let mut weight = 1.0;
// * Sections with 0 strain are excluded to avoid worst-case time complexity of the following sort (e.g. /b/2351871).
// * These sections will not contribute to the difficulty.
let mut peaks = current_strain_peaks;
peaks.retain_non_zero_and_sort();
// SAFETY: we just removed all zeros
let peaks = unsafe { peaks.transmute_into_vec() };
// * Difficulty is the weighted sum of the highest strains from every section.
// * We're sorting from highest to lowest strain.
for strain in peaks {
difficulty += strain * weight;
weight *= decay_weight;
}
difficulty
}
pub fn strain_decay(ms: f64, strain_decay_base: f64) -> f64 {
f64::powf(strain_decay_base, ms / 1000.0)
}
| 412 | 0.87946 | 1 | 0.87946 | game-dev | MEDIA | 0.36479 | game-dev | 0.955301 | 1 | 0.955301 |
ReactiveDrop/reactivedrop_public_src | 11,146 | src/game/client/swarm/vgui/asw_vgui_computer_splash.cpp | #include "cbase.h"
#include "asw_vgui_computer_splash.h"
#include "asw_vgui_computer_frame.h"
#include "vgui/ISurface.h"
#include "c_asw_hack_computer.h"
#include <vgui/IInput.h>
#include <vgui_controls/AnimationController.h>
#include <vgui_controls/ImagePanel.h>
#include "vgui/ILocalize.h"
#include "c_asw_computer_area.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
#define ASW_COMPUTER_GLITCH_INTERVAL 0.01f
CASW_VGUI_Computer_Splash::CASW_VGUI_Computer_Splash( vgui::Panel *pParent, const char *pElementName, C_ASW_Hack_Computer* pHackComputer )
: vgui::Panel( pParent, pElementName ),
CASW_VGUI_Ingame_Panel(),
m_hHackComputer( pHackComputer )
{
m_pLogoImage = new vgui::ImagePanel(this, "SplashImage");
m_pLogoGlitchImage = new vgui::ImagePanel(this, "SplashImage");
if (IsPDA())
{
m_pSynTekLabel = new vgui::Label(this, "SynTekHeader", "");
m_pSloganLabel = new vgui::Label(this, "SloganLabel", g_pVGuiLocalize->Find("#asw_SynTekPDA"));
if (m_hHackComputer.Get() && m_hHackComputer->GetComputerArea() )
{
// set the label based on PDA name
wchar_t wnamebuffer[64];
if ( const wchar_t *pwszName = g_pVGuiLocalize->Find( m_hHackComputer->GetComputerArea()->m_PDAName.Get() ) )
{
V_wcsncpy( wnamebuffer, pwszName, sizeof( wnamebuffer ) );
}
else
{
g_pVGuiLocalize->ConvertANSIToUnicode( m_hHackComputer->GetComputerArea()->m_PDAName.Get(), wnamebuffer, sizeof( wnamebuffer ) );
}
wchar_t wbuffer[256];
g_pVGuiLocalize->ConstructString( wbuffer, sizeof(wbuffer),
g_pVGuiLocalize->Find("#asw_SynTekAccount"), 1,
wnamebuffer);
m_pSynTekLabel->SetText(wbuffer);
}
}
else
{
m_pSynTekLabel = new vgui::Label(this, "SynTekHeader", g_pVGuiLocalize->Find("#asw_SynTekMegacorp"));
m_pSloganLabel = new vgui::Label(this, "SloganLabel", "");
switch (random->RandomInt(0,4))
{
case 0: m_pSloganLabel->SetText("#asw_SynTekSlogan1"); break;
case 1: m_pSloganLabel->SetText("#asw_SynTekSlogan2"); break;
case 2: m_pSloganLabel->SetText("#asw_SynTekSlogan3"); break;
case 3: m_pSloganLabel->SetText("#asw_SynTekSlogan4"); break;
default: m_pSloganLabel->SetText("#asw_SynTekSlogan5"); break;
}
}
char buffer[1024];
for (int i=0;i<ASW_SPLASH_SCROLL_LINES;i++)
{
m_pScrollLine[i] = new vgui::Label(this, "SplashScrollLine", "");
Q_snprintf(buffer, sizeof(buffer), "#asw_SynTekScrollLine%d", i);
m_pScrollLine[i]->SetText(buffer);
}
// todo: fill in line X with the marine's name
m_fLastThinkTime = gpGlobals->curtime;
m_fNextGlitchTime= gpGlobals->curtime;
m_fShowGlitchTime = 0;
m_fSoundTime = gpGlobals->curtime + 0.2f;
m_bPlayedSound = false;
m_fSlideOutTime = gpGlobals->curtime + 2.2f;
//m_fSlideOutTime = gpGlobals->curtime + 0.2f; // shortcut?
m_bSlidOut = false;
m_iNumLines = 0;
m_fStartScrollingTime = gpGlobals->curtime + 0.7f;
//m_fStartScrollingTime = gpGlobals->curtime + 0.1f; // shortcut
m_fFadeScrollerOutTime = 0;
m_bSetAlpha = false;
}
CASW_VGUI_Computer_Splash::~CASW_VGUI_Computer_Splash()
{
if (IsPDA())
C_BaseEntity::StopSound( -1 /*SOUND_FROM_LOCAL_PLAYER*/, CHAN_STATIC, "ASWComputer.SyntekPDA" );
else
C_BaseEntity::StopSound( -1 /*SOUND_FROM_LOCAL_PLAYER*/, CHAN_STATIC, "ASWComputer.Startup" );
}
void CASW_VGUI_Computer_Splash::PerformLayout()
{
m_fScale = ScreenHeight() / 768.0f;
int w = GetParent()->GetWide();
int h = GetParent()->GetTall();
SetWide(w);
SetTall(h);
SetPos(ScreenWidth()*0.5f - w*0.5f, ScreenHeight()*0.5f - h*0.5f);
m_pLogoImage->SetShouldScaleImage(true);
m_pLogoImage->SetPos(w*0.25f,h*0.15f);
m_pLogoImage->SetSize(w*0.5f, h*0.5f);
m_pLogoImage->SetImage("swarm/Computer/SynTekLogo2");
m_pLogoImage->SetZPos(160);
m_pLogoGlitchImage->SetShouldScaleImage(true);
m_pLogoGlitchImage->SetPos(w*0.25f,h*0.25f);
m_pLogoGlitchImage->SetSize(w*0.5f, h*0.5f);
m_pLogoGlitchImage->SetImage("swarm/Computer/SynTekLogo2");
m_pLogoGlitchImage->SetZPos(159);
m_pSloganLabel->SetSize(w, h * 0.2f);
m_pSloganLabel->SetContentAlignment(vgui::Label::a_center);
m_pSloganLabel->SetPos(0, h*0.75f);
m_pSloganLabel->SetZPos(160);
m_pSynTekLabel->SetSize(w, h * 0.2f);
m_pSynTekLabel->SetContentAlignment(vgui::Label::a_center);
m_pSynTekLabel->SetPos(0, h*0.65f);
m_pSynTekLabel->SetZPos(160);
for (int i=0;i<ASW_SPLASH_SCROLL_LINES;i++)
{
m_pScrollLine[i]->SetSize(w, h * 0.2f);
m_pScrollLine[i]->SetContentAlignment(vgui::Label::a_northwest);
}
if (m_bSlidOut)
{
m_pLogoImage->SetBounds( w*0.05f, h*0.05f, w*0.13f, h*0.13f);
m_pSynTekLabel->SetPos(0, 0);
}
SetZPos(161);
}
void CASW_VGUI_Computer_Splash::ASWInit()
{
m_pLogoImage->SetAlpha(0);
vgui::GetAnimationController()->RunAnimationCommand(m_pLogoImage, "Alpha", 255, 0.3f, 1.7f, vgui::AnimationController::INTERPOLATOR_LINEAR);
m_pLogoGlitchImage->SetAlpha(0);
SetPaintBackgroundType(0);
SetPaintBackgroundEnabled(false);
SetBgColor( Color(0,0,0,0) );
SetAlpha(255);
m_pSloganLabel->SetAlpha(0);
vgui::GetAnimationController()->RunAnimationCommand(m_pSloganLabel, "Alpha", 255, 0.8f, 1.7f, vgui::AnimationController::INTERPOLATOR_LINEAR);
m_pSynTekLabel->SetAlpha(0);
vgui::GetAnimationController()->RunAnimationCommand(m_pSynTekLabel, "Alpha", 255, 0.3f, 1.7f, vgui::AnimationController::INTERPOLATOR_LINEAR);
}
void CASW_VGUI_Computer_Splash::ApplySchemeSettings(vgui::IScheme *pScheme)
{
BaseClass::ApplySchemeSettings(pScheme);
SetPaintBackgroundType(0);
SetPaintBackgroundEnabled(false);
SetBgColor( Color(0,0,0,0) );
SetMouseInputEnabled(true);
if (!m_bSetAlpha)
{
m_pLogoImage->SetAlpha(0);
vgui::GetAnimationController()->RunAnimationCommand(m_pLogoImage, "Alpha", 255, 0.9f, 1.7f, vgui::AnimationController::INTERPOLATOR_LINEAR);
m_pLogoGlitchImage->SetAlpha(0);
m_pSloganLabel->SetAlpha(0);
vgui::GetAnimationController()->RunAnimationCommand(m_pSloganLabel, "Alpha", 255, 0.9f, 1.7f, vgui::AnimationController::INTERPOLATOR_LINEAR);
m_pSynTekLabel->SetAlpha(0);
vgui::GetAnimationController()->RunAnimationCommand(m_pSynTekLabel, "Alpha", 255, 0.9f, 1.7f, vgui::AnimationController::INTERPOLATOR_LINEAR);
}
vgui::HFont SloganFont = pScheme->GetFont( "CleanHUD", IsProportional() );
m_pSloganLabel->SetFont(SloganFont);
m_pSloganLabel->SetFgColor(Color(255,255,255,255));
vgui::HFont HeaderFont = pScheme->GetFont( "DefaultLarge", IsProportional() );
m_pSynTekLabel->SetFont(HeaderFont);
m_pSynTekLabel->SetFgColor(Color(255,255,255,255));
vgui::HFont ScrollerFont = pScheme->GetFont( "Courier", IsProportional() );
for (int i=0;i<ASW_SPLASH_SCROLL_LINES;i++)
{
m_pScrollLine[i]->SetFont(ScrollerFont);
m_pScrollLine[i]->SetFgColor(Color(19,21,41,255));
m_pScrollLine[i]->SetAlpha(0); // it's okay for these to be hidden if player changes res and this gets called again
}
if (m_bSlidOut)
{
m_pSloganLabel->SetAlpha(0);
m_pLogoGlitchImage->SetAlpha(0);
}
m_bSetAlpha = true;
}
bool CASW_VGUI_Computer_Splash::IsPDA()
{
if ( m_hHackComputer.Get() && m_hHackComputer->GetComputerArea() )
return m_hHackComputer->GetComputerArea()->IsPDA();
return false;
}
#define ASW_SPLASH_SCROLL_INTERVAL 0.03f
void CASW_VGUI_Computer_Splash::OnThink()
{
if (!m_bPlayedSound && m_fSoundTime <= gpGlobals->curtime)
{
CLocalPlayerFilter filter;
if (IsPDA())
C_BaseEntity::EmitSound( filter, -1 /*SOUND_FROM_LOCAL_PLAYER*/, "ASWComputer.SyntekPDA" );
else
C_BaseEntity::EmitSound( filter, -1 /*SOUND_FROM_LOCAL_PLAYER*/, "ASWComputer.Startup" );
m_bPlayedSound = true;
}
int x,y,w,t;
GetBounds(x,y,w,t);
if (!m_bSlidOut && m_fSlideOutTime <= gpGlobals->curtime)
{
m_bSlidOut = true;
// slide/fade out our elements
vgui::GetAnimationController()->RunAnimationCommand(m_pLogoImage, "xpos", w*0.05f, 0.0f, 0.8f, vgui::AnimationController::INTERPOLATOR_LINEAR);
vgui::GetAnimationController()->RunAnimationCommand(m_pLogoImage, "ypos", t*0.05f, 0.0f, 0.8f, vgui::AnimationController::INTERPOLATOR_LINEAR);
vgui::GetAnimationController()->RunAnimationCommand(m_pLogoImage, "wide", w*0.13f, 0.0f, 0.8f, vgui::AnimationController::INTERPOLATOR_LINEAR);
vgui::GetAnimationController()->RunAnimationCommand(m_pLogoImage, "tall", t*0.13f, 0.0f, 0.8f, vgui::AnimationController::INTERPOLATOR_LINEAR);
vgui::GetAnimationController()->RunAnimationCommand(m_pSynTekLabel, "ypos", 0, 0.0f, 0.8f, vgui::AnimationController::INTERPOLATOR_LINEAR);
vgui::GetAnimationController()->RunAnimationCommand(m_pSloganLabel, "Alpha", 0, 0.0f, 0.4f, vgui::AnimationController::INTERPOLATOR_LINEAR);
}
if (m_iNumLines < ASW_SPLASH_SCROLL_LINES && m_fStartScrollingTime <= gpGlobals->curtime)
{
m_iNumLines++;
//m_iNumLines = clamp(((gpGlobals->curtime - m_fStartScrollingTime) / ASW_SPLASH_SCROLL_INTERVAL) + 1, 0, ASW_SPLASH_SCROLL_LINES);
if (m_iNumLines == ASW_SPLASH_SCROLL_LINES)
m_fFadeScrollerOutTime = gpGlobals->curtime + 0.8f;
float font_tall = vgui::surface()->GetFontTall(m_pScrollLine[0]->GetFont());
for (int i=0;i<m_iNumLines;i++)
{
m_pScrollLine[i]->SetAlpha(128);
m_pScrollLine[i]->SetPos(0.02f * w, t - ((m_iNumLines - i) * font_tall + 0.02f * w));
}
m_fStartScrollingTime = gpGlobals->curtime + ASW_SPLASH_SCROLL_INTERVAL * (random->RandomInt(1,5));
}
if (m_fFadeScrollerOutTime != 0 && gpGlobals->curtime >= m_fFadeScrollerOutTime)
{
m_fFadeScrollerOutTime = 0;
for (int i=0;i<ASW_SPLASH_SCROLL_LINES;i++)
{
vgui::GetAnimationController()->RunAnimationCommand(m_pScrollLine[i], "Alpha", 0, 0.0f, 0.4f, vgui::AnimationController::INTERPOLATOR_LINEAR);
}
// notify the main frame we're done
CASW_VGUI_Computer_Frame *pFrame = dynamic_cast<CASW_VGUI_Computer_Frame*>(GetParent());
if (pFrame && !IsPDA())
pFrame->SplashFinished();
}
m_pLogoImage->GetBounds(x,y,w,t);
// make our glitch less bright
if (m_bSlidOut || gpGlobals->curtime > m_fShowGlitchTime)
{
m_pLogoGlitchImage->SetAlpha(0);
if (gpGlobals->curtime > m_fNextGlitchTime)
{
if (random->RandomFloat() < 0.03f)
m_fShowGlitchTime = gpGlobals->curtime + 0.4f;
m_fNextGlitchTime += ASW_COMPUTER_GLITCH_INTERVAL;
}
}
else
{
m_pLogoGlitchImage->SetAlpha(m_pLogoImage->GetAlpha() * 0.07f);
// scale it randomly
if (gpGlobals->curtime > m_fNextGlitchTime)
{
float x_scale = random->RandomFloat(0.7f, 1.3f);
float y_scale = random->RandomFloat(0.7f, 1.3f);
m_pLogoGlitchImage->SetSize(w * x_scale, t * y_scale);
m_pLogoGlitchImage->SetPos(x - w * 0.5f * x_scale + w * 0.5f, y - t * 0.5f * y_scale + t * 0.5f);
m_fNextGlitchTime += ASW_COMPUTER_GLITCH_INTERVAL;
}
}
//float deltatime = gpGlobals->curtime - m_fLastThinkTime;
m_fLastThinkTime = gpGlobals->curtime;
}
void CASW_VGUI_Computer_Splash::SetHidden(bool bHidden)
{
if (bHidden && GetAlpha() > 0)
{
vgui::GetAnimationController()->RunAnimationCommand(this, "Alpha", 0, 0, 0.7f, vgui::AnimationController::INTERPOLATOR_LINEAR);
}
else if (!bHidden && GetAlpha() <= 0)
{
vgui::GetAnimationController()->RunAnimationCommand(this, "Alpha", 255, 0, 0.7f, vgui::AnimationController::INTERPOLATOR_LINEAR);
}
} | 412 | 0.806719 | 1 | 0.806719 | game-dev | MEDIA | 0.709213 | game-dev | 0.924399 | 1 | 0.924399 |
ShortTailLab/ph-open | 2,603 | libs/cocos2dx-common/src/CCShake.cpp | /****************************************************************************
Author: Luma (stubma@gmail.com)
https://github.com/stubma/cocos2dx-common
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "CCShake.h"
NS_CC_BEGIN
CCShake::~CCShake() {
}
CCShake* CCShake::create(float duration, float radius) {
CCShake* a = new CCShake();
a->initWithDuration(duration, radius);
return (CCShake*)a->autorelease();
}
bool CCShake::initWithDuration(float d, float r) {
m_fDuration = d;
m_radius = r;
return true;
}
CCObject* CCShake::copyWithZone(CCZone *pZone) {
CCZone* pNewZone = NULL;
CCShake* pCopy = NULL;
if(pZone && pZone->m_pCopyObject) {
// in case of being called at sub class
pCopy = (CCShake*)(pZone->m_pCopyObject);
} else {
pCopy = new CCShake();
pZone = pNewZone = new CCZone(pCopy);
}
CCActionInterval::copyWithZone(pZone);
pCopy->initWithDuration(m_fDuration, m_radius);
CC_SAFE_DELETE(pNewZone);
return pCopy;
}
CCActionInterval* CCShake::reverse() {
return create(m_fDuration, m_radius);
}
void CCShake::update(float t) {
if(t >= 1) {
getTarget()->setPosition(m_originalX, m_originalY);
} else {
getTarget()->setPosition(m_originalX + m_radius * CCRANDOM_MINUS1_1(),
m_originalY + m_radius * CCRANDOM_MINUS1_1());
}
}
void CCShake::startWithTarget(CCNode* pTarget) {
CCActionInterval::startWithTarget(pTarget);
m_originalX = pTarget->getPositionX();
m_originalY = pTarget->getPositionY();
}
NS_CC_END | 412 | 0.69166 | 1 | 0.69166 | game-dev | MEDIA | 0.95123 | game-dev | 0.927458 | 1 | 0.927458 |
HushengStudent/myGameFramework | 1,417 | Client/Assets/ThirdParty/ParadoxNotion/NodeCanvas/Modules/BehaviourTrees/Nodes/Leafs/ActionNode.cs | using NodeCanvas.Framework;
using ParadoxNotion.Design;
using UnityEngine;
namespace NodeCanvas.BehaviourTrees
{
[Name("Action")]
[Description("Executes an action and returns Success or Failure.\nReturns Running until the action is finished.")]
[Icon("Action")]
public class ActionNode : BTNode, ITaskAssignable<ActionTask>
{
[SerializeField]
private ActionTask _action;
public Task task {
get { return action; }
set { action = (ActionTask)value; }
}
public ActionTask action {
get { return _action; }
set { _action = value; }
}
public override string name {
get { return base.name.ToUpper(); }
}
protected override Status OnExecute(Component agent, IBlackboard blackboard) {
if ( action == null ) {
return Status.Optional;
}
if ( status == Status.Resting || status == Status.Running ) {
return action.ExecuteAction(agent, blackboard);
}
return status;
}
protected override void OnReset() {
if ( action != null ) {
action.EndAction(null);
}
}
public override void OnGraphPaused() {
if ( action != null ) {
action.PauseAction();
}
}
}
} | 412 | 0.69071 | 1 | 0.69071 | game-dev | MEDIA | 0.792138 | game-dev | 0.900504 | 1 | 0.900504 |
Kirby64Ret/kirby64 | 3,820 | asm/non_matchings/ovl10/ovl10_2/func_801EAA98_ovl10.s | glabel func_801EAA98_ovl10
/* 1DB808 801EAA98 3C028005 */ lui $v0, %hi(D_8004A7C4) # $v0, 0x8005
/* 1DB80C 801EAA9C 8C42A7C4 */ lw $v0, %lo(D_8004A7C4)($v0)
/* 1DB810 801EAAA0 27BDFFE8 */ addiu $sp, $sp, -0x18
/* 1DB814 801EAAA4 AFBF0014 */ sw $ra, 0x14($sp)
/* 1DB818 801EAAA8 AFA40018 */ sw $a0, 0x18($sp)
/* 1DB81C 801EAAAC 8C430000 */ lw $v1, ($v0)
/* 1DB820 801EAAB0 3C0E800F */ lui $t6, %hi(D_800E9E20)
/* 1DB824 801EAAB4 3C06800F */ lui $a2, %hi(D_800EA520) # $a2, 0x800f
/* 1DB828 801EAAB8 00031880 */ sll $v1, $v1, 2
/* 1DB82C 801EAABC 01C37021 */ addu $t6, $t6, $v1
/* 1DB830 801EAAC0 8DCE9E20 */ lw $t6, %lo(D_800E9E20)($t6)
/* 1DB834 801EAAC4 24C6A520 */ addiu $a2, %lo(D_800EA520) # addiu $a2, $a2, -0x5ae0
/* 1DB838 801EAAC8 00C37821 */ addu $t7, $a2, $v1
/* 1DB83C 801EAACC 51C0002F */ beql $t6, $zero, .L801EAB8C_ovl10
/* 1DB840 801EAAD0 8FBF0014 */ lw $ra, 0x14($sp)
/* 1DB844 801EAAD4 8DE50000 */ lw $a1, ($t7)
/* 1DB848 801EAAD8 3C03800F */ lui $v1, %hi(D_800EA6E0) # $v1, 0x800f
/* 1DB84C 801EAADC 3C0140A0 */ li $at, 0x40A00000 # 5.000000
/* 1DB850 801EAAE0 00052880 */ sll $a1, $a1, 2
/* 1DB854 801EAAE4 00C5C021 */ addu $t8, $a2, $a1
/* 1DB858 801EAAE8 8F190000 */ lw $t9, ($t8)
/* 1DB85C 801EAAEC 53200027 */ beql $t9, $zero, .L801EAB8C_ovl10
/* 1DB860 801EAAF0 8FBF0014 */ lw $ra, 0x14($sp)
/* 1DB864 801EAAF4 44812000 */ mtc1 $at, $f4
/* 1DB868 801EAAF8 2463A6E0 */ addiu $v1, %lo(D_800EA6E0) # addiu $v1, $v1, -0x5920
/* 1DB86C 801EAAFC 00654021 */ addu $t0, $v1, $a1
/* 1DB870 801EAB00 E5040000 */ swc1 $f4, ($t0)
/* 1DB874 801EAB04 8C490000 */ lw $t1, ($v0)
/* 1DB878 801EAB08 00095080 */ sll $t2, $t1, 2
/* 1DB87C 801EAB0C 00CA5821 */ addu $t3, $a2, $t2
/* 1DB880 801EAB10 8D6C0000 */ lw $t4, ($t3)
/* 1DB884 801EAB14 000C6880 */ sll $t5, $t4, 2
/* 1DB888 801EAB18 006D7021 */ addu $t6, $v1, $t5
/* 1DB88C 801EAB1C C5C60000 */ lwc1 $f6, ($t6)
/* 1DB890 801EAB20 4600320D */ trunc.w.s $f8, $f6
/* 1DB894 801EAB24 44044000 */ mfc1 $a0, $f8
/* 1DB898 801EAB28 0C02F07F */ jal func_800BC1FC
/* 1DB89C 801EAB2C 00000000 */ nop
/* 1DB8A0 801EAB30 3C01800D */ lui $at, %hi(D_800D6B10) # $at, 0x800d
/* 1DB8A4 801EAB34 0C02BB30 */ jal func_800AECC0
/* 1DB8A8 801EAB38 C42C6B10 */ lwc1 $f12, %lo(D_800D6B10)($at)
/* 1DB8AC 801EAB3C 3C01800D */ lui $at, %hi(D_800D6B10) # $at, 0x800d
/* 1DB8B0 801EAB40 0C02BB48 */ jal func_800AED20
/* 1DB8B4 801EAB44 C42C6B10 */ lwc1 $f12, %lo(D_800D6B10)($at)
/* 1DB8B8 801EAB48 3C028005 */ lui $v0, %hi(D_8004A7C4) # $v0, 0x8005
/* 1DB8BC 801EAB4C 8C42A7C4 */ lw $v0, %lo(D_8004A7C4)($v0)
/* 1DB8C0 801EAB50 3C01800E */ lui $at, %hi(gEntityVtableIndexArray)
/* 1DB8C4 801EAB54 24180001 */ li $t8, 1
/* 1DB8C8 801EAB58 8C590000 */ lw $t9, ($v0)
/* 1DB8CC 801EAB5C 3C04800E */ lui $a0, %hi(gEntityGObjProcessArray)
/* 1DB8D0 801EAB60 3C05801F */ lui $a1, %hi(D_801EA784) # $a1, 0x801f
/* 1DB8D4 801EAB64 00194080 */ sll $t0, $t9, 2
/* 1DB8D8 801EAB68 00280821 */ addu $at, $at, $t0
/* 1DB8DC 801EAB6C AC38DC50 */ sw $t8, %lo(gEntityVtableIndexArray)($at)
/* 1DB8E0 801EAB70 8C490000 */ lw $t1, ($v0)
/* 1DB8E4 801EAB74 24A5A784 */ addiu $a1, %lo(D_801EA784) # addiu $a1, $a1, -0x587c
/* 1DB8E8 801EAB78 00095080 */ sll $t2, $t1, 2
/* 1DB8EC 801EAB7C 008A2021 */ addu $a0, $a0, $t2
/* 1DB8F0 801EAB80 0C02C7B2 */ jal assign_new_process_entry
/* 1DB8F4 801EAB84 8C84E510 */ lw $a0, %lo(gEntityGObjProcessArray)($a0)
/* 1DB8F8 801EAB88 8FBF0014 */ lw $ra, 0x14($sp)
.L801EAB8C_ovl10:
/* 1DB8FC 801EAB8C 27BD0018 */ addiu $sp, $sp, 0x18
/* 1DB900 801EAB90 03E00008 */ jr $ra
/* 1DB904 801EAB94 00000000 */ nop
.type func_801EAA98_ovl10, @function
.size func_801EAA98_ovl10, . - func_801EAA98_ovl10
| 412 | 0.792612 | 1 | 0.792612 | game-dev | MEDIA | 0.625454 | game-dev | 0.633917 | 1 | 0.633917 |
ambrosiogabe/MathAnimation | 5,093 | Animations/include/editor/UndoSystem.h | #ifndef MATH_ANIM_UNDO_SYSTEM_H
#define MATH_ANIM_UNDO_SYSTEM_H
#include "core.h"
namespace MathAnim
{
struct AnimationManagerData;
struct UndoSystemData;
struct AnimObject;
typedef AnimObjId ObjOrAnimId;
enum class U8Vec4PropType : uint8
{
// Base
FillColor = 0,
StrokeColor,
// Generic
AnimateU8Vec4Target,
};
enum class Vec2PropType : uint8
{
// Scale
AnimateScaleTarget,
};
enum class Vec2iPropType : uint8
{
// Camera
AspectRatio = 0,
// Axis
AxisXRange,
AxisYRange,
AxisZRange,
};
enum class Vec3PropType : uint8
{
// Base
Position = 0,
Scale,
Rotation,
// Generic
ModifyAnimationVec3Target,
// Axis
AxisAxesLength,
// Animations
MoveToTargetPos
};
enum class Vec4PropType : uint8
{
// Camera
CameraBackgroundColor = 0,
// Circumscribe
CircumscribeColor,
};
enum class StringPropType : uint8
{
// Base
Name = 0,
// Text Object
TextObjectText,
// Codeblock
CodeBlockText,
// LaTeX Object
LaTexText,
// Svg Object
SvgFilepath,
// Image Object
ImageFilepath,
// Script Object
ScriptFile,
};
enum class FloatPropType : uint8
{
// Base
StrokeWidth = 0,
LagRatio,
// Camera
CameraFieldOfView,
CameraNearPlane,
CameraFarPlane,
CameraFocalDistance,
CameraOrthoZoomLevel,
// Circumscribe
CircumscribeTimeWidth,
CircumscribeBufferSize,
// Square
SquareSideLength,
// Circle
CircleRadius,
// Arrow
ArrowStemLength,
ArrowStemWidth,
ArrowTipLength,
ArrowTipWidth,
// Cube
CubeSideLength,
// Axis
AxisXStep,
AxisYStep,
AxisZStep,
AxisTickWidth,
AxisFontSizePixels,
AxisLabelPadding,
AxisLabelStrokeWidth,
};
enum class EnumPropType : uint8
{
// Base
EaseType = 0,
EaseDirection,
PlaybackType,
// Codeblock
HighlighterLanguage,
HighlighterTheme,
// Camera
CameraMode,
// Circumscribe
CircumscribeShape,
CircumscribeFade,
// Image Object
ImageSampleMode,
ImageRepeat,
};
enum class AnimDragDropType : uint8
{
// Replacement
ReplacementTransformSrc = 0,
ReplacementTransformDst,
// MoveTo
MoveToTarget,
// Scale
AnimateScaleTarget,
// Circumscribe
CircumscribeTarget,
};
enum class BoolPropType : uint8
{
// Axis
AxisDrawNumbers,
};
class Command
{
public:
Command() {}
virtual ~Command() {};
virtual void execute(void* userContext) = 0;
virtual void undo(void* userContext) = 0;
virtual void free(void*) {}
};
namespace UndoSystem
{
// TODO: Come up with AnimationManagerUndoSystem so that the animation manager and text editor stuff is separate
UndoSystemData* init(void* userContext, int maxHistory);
void free(UndoSystemData* us);
void setUserContext(UndoSystemData* us, void* ctx);
void pushAndExecuteCommand(UndoSystemData* us, Command* command);
// Returns the index the command was inserted at
uint32 pushCommand(UndoSystemData* us, Command* command);
void iterate(UndoSystemData* us);
void undo(UndoSystemData* us);
void redo(UndoSystemData* us);
void setBoolProp(UndoSystemData* us, ObjOrAnimId id, bool oldBool, bool newBool, BoolPropType propType);
void applyU8Vec4ToChildren(UndoSystemData* us, ObjOrAnimId id, U8Vec4PropType propType);
void setU8Vec4Prop(UndoSystemData* us, ObjOrAnimId id, const glm::u8vec4& oldVec, const glm::u8vec4& newVec, U8Vec4PropType propType);
void setEnumProp(UndoSystemData* us, ObjOrAnimId id, int oldEnum, int newEnum, EnumPropType propType);
void setFloatProp(UndoSystemData* us, ObjOrAnimId id, float oldValue, float newValue, FloatPropType propType);
void setVec2Prop(UndoSystemData* us, ObjOrAnimId id, const Vec2& oldVec, const Vec2& newVec, Vec2PropType propType);
void setVec2iProp(UndoSystemData* us, ObjOrAnimId id, const Vec2i& oldVec, const Vec2i& newVec, Vec2iPropType propType);
void setVec3Prop(UndoSystemData* us, ObjOrAnimId id, const Vec3& oldVec, const Vec3& newVec, Vec3PropType propType);
void setVec4Prop(UndoSystemData* us, ObjOrAnimId id, const Vec4& oldVec, const Vec4& newVec, Vec4PropType propType);
void setStringProp(UndoSystemData* us, ObjOrAnimId id, const std::string& oldString, const std::string& newString, StringPropType propType);
void setFont(UndoSystemData* us, ObjOrAnimId id, const std::string& oldFont, const std::string& newFont);
void animDragDropInput(UndoSystemData* us, AnimObjId oldTarget, AnimObjId newTarget, AnimId animToAddTo, AnimDragDropType type);
void addObjectToAnim(UndoSystemData* us, AnimObjId objToAdd, AnimId animToAddTo);
void removeObjectFromAnim(UndoSystemData* us, AnimObjId objToAdd, AnimId animToAddTo);
void addNewObjToScene(UndoSystemData* us, int animObjType);
void removeObjFromScene(UndoSystemData* us, AnimObjId objId);
void setAnimationTime(UndoSystemData* us, AnimId id, int oldFrameStart, int oldFrameDuration, int newFrameStart, int newFrameDuration);
void addNewAnimationToTimeline(UndoSystemData* us, int animType, int frameStart, int frameDuration, int trackIndex);
void removeAnimationFromTimeline(UndoSystemData* us, AnimId animId);
}
}
#endif | 412 | 0.784909 | 1 | 0.784909 | game-dev | MEDIA | 0.633604 | game-dev,graphics-rendering | 0.867714 | 1 | 0.867714 |
ihmcrobotics/ihmc-open-robotics-software | 3,639 | ihmc-interfaces/src/main/generated-idl/toolbox_msgs/msg/AStarBodyPathPlannerParametersPacket_.idl | #ifndef __toolbox_msgs__msg__AStarBodyPathPlannerParametersPacket__idl__
#define __toolbox_msgs__msg__AStarBodyPathPlannerParametersPacket__idl__
module toolbox_msgs
{
module msg
{
module dds
{
const double DEFAULT_NO_VALUE =
-11.1;
/**
* This message is part of the IHMC footstep planning module.
* This message defines the parameters for the A* body path planner.
*/
@TypeCode(type="toolbox_msgs::msg::dds_::AStarBodyPathPlannerParametersPacket_")
struct AStarBodyPathPlannerParametersPacket
{
/**
* Unique ID used to identify this message.
*/
unsigned long long sequence_id;
/**
* Whether or not the planner checks for collisions.
*/
boolean check_for_collisions;
/**
* Whether the body path plan is post-processed with the smoother.
*/
boolean perform_smoothing;
/**
* The node height of a vertex is determined as the average height of all cells within this radius.
*/
double snap_radius;
/**
* When computing the vertex height, cells that are this distance below the max height are ignored when taking the average.
*/
double min_snap_height_threshold;
/**
* Weight assigned to minimizing the incline the path takes.
*/
double incline_cost_weight;
/**
* Deadband applied to the incline in the search.
*/
double incline_cost_deadband;
/**
* The maximum incline, in degrees, that is allowed for the body path planner to traverse.
*/
double max_incline;
/**
* Width of the collision box used for checking collisions with the environment.
*/
double collision_box_size_y;
/**
* Depth of the collision box used for checking collisions with the environment.
*/
double collision_box_size_x;
/**
* Intersection height below which collisions are ignored.
*/
double collision_box_ground_clearance;
/**
* Weight placed on the gradient for avoiding collisions in the smoother.
*/
double smoother_collision_weight;
/**
* Weight placed on the gradient for minimizing the angle between successive segments of the body path.
*/
double smoother_smoothness_weight;
/**
* Discount applied to the smoothness gradients of turn points.
*/
double smoother_turn_point_smoothness_discount;
/**
* Minimum curvature in degrees to penalize with a gradient.
*/
double smoother_min_curvature_to_penalize;
/**
* Weight placed on the gradient for making vertices of the body path plan an equal distance apart.
*/
double smoother_equal_spacing_weight;
/**
* Weight placed on a gradient that drives the waypoint towards the initial value.
*/
double smoother_displacement_weight;
/**
* Gain applied to the smoother gradient for iterative modifications.
*/
double smoother_hill_climb_gain;
/**
* Minimum gradient vector magnitude to terminate the smoother iterations.
*/
double smoother_gradient_threshold_to_terminate;
/**
* Distance from the start to perform collision checking. Avoids false-positive collisions of the robot or gantry, for example.
*/
double collision_start_tolerance;
};
};
};
};
#endif
| 412 | 0.817224 | 1 | 0.817224 | game-dev | MEDIA | 0.383878 | game-dev | 0.501248 | 1 | 0.501248 |
lua9520/source-engine-2018-cstrike15_src | 8,755 | tools/commedit/commentarynodebrowserpanel.cpp | //===== Copyright 1996-2005, Valve Corporation, All rights reserved. ======//
//
// Purpose: Singleton dialog that generates and presents the entity report.
//
//===========================================================================//
#include "CommentaryNodeBrowserPanel.h"
#include "tier1/keyvalues.h"
#include "tier1/utlbuffer.h"
#include "iregistry.h"
#include "vgui/ivgui.h"
#include "vgui_controls/listpanel.h"
#include "vgui_controls/textentry.h"
#include "vgui_controls/checkbutton.h"
#include "vgui_controls/combobox.h"
#include "vgui_controls/radiobutton.h"
#include "vgui_controls/messagebox.h"
#include "commeditdoc.h"
#include "commedittool.h"
#include "datamodel/dmelement.h"
#include "vgui/keycode.h"
// memdbgon must be the last include file in a .cpp file!!!
#include <tier0/memdbgon.h>
using namespace vgui;
//-----------------------------------------------------------------------------
// Sort by target name
//-----------------------------------------------------------------------------
static int __cdecl TargetNameSortFunc( vgui::ListPanel *pPanel, const ListPanelItem &item1, const ListPanelItem &item2 )
{
const char *string1 = item1.kv->GetString("targetname");
const char *string2 = item2.kv->GetString("targetname");
int nRetVal = Q_stricmp( string1, string2 );
if ( nRetVal != 0 )
return nRetVal;
string1 = item1.kv->GetString("classname");
string2 = item2.kv->GetString("classname");
return Q_stricmp( string1, string2 );
}
//-----------------------------------------------------------------------------
// Sort by class name
//-----------------------------------------------------------------------------
static int __cdecl ClassNameSortFunc( vgui::ListPanel *pPanel, const ListPanelItem &item1, const ListPanelItem &item2 )
{
const char *string1 = item1.kv->GetString("classname");
const char *string2 = item2.kv->GetString("classname");
int nRetVal = Q_stricmp( string1, string2 );
if ( nRetVal != 0 )
return nRetVal;
string1 = item1.kv->GetString("targetname");
string2 = item2.kv->GetString("targetname");
return Q_stricmp( string1, string2 );
}
//-----------------------------------------------------------------------------
// Constructor
//-----------------------------------------------------------------------------
CCommentaryNodeBrowserPanel::CCommentaryNodeBrowserPanel( CCommEditDoc *pDoc, vgui::Panel* pParent, const char *pName )
: BaseClass( pParent, pName ), m_pDoc( pDoc )
{
SetPaintBackgroundEnabled( true );
m_pEntities = new vgui::ListPanel( this, "Entities" );
m_pEntities->AddColumnHeader( 0, "targetname", "Name", 52, ListPanel::COLUMN_RESIZEWITHWINDOW );
m_pEntities->AddColumnHeader( 1, "classname", "Class Name", 52, ListPanel::COLUMN_RESIZEWITHWINDOW );
m_pEntities->SetColumnSortable( 0, true );
m_pEntities->SetColumnSortable( 1, true );
m_pEntities->SetEmptyListText( "No Entities" );
// m_pEntities->SetDragEnabled( true );
m_pEntities->AddActionSignalTarget( this );
m_pEntities->SetSortFunc( 0, TargetNameSortFunc );
m_pEntities->SetSortFunc( 1, ClassNameSortFunc );
m_pEntities->SetSortColumn( 0 );
LoadControlSettingsAndUserConfig( "resource/commentarynodebrowserpanel.res" );
UpdateEntityList();
}
CCommentaryNodeBrowserPanel::~CCommentaryNodeBrowserPanel()
{
SaveUserConfig();
}
//-----------------------------------------------------------------------------
// Purpose: Shows the most recent selected object in properties window
//-----------------------------------------------------------------------------
void CCommentaryNodeBrowserPanel::OnProperties( )
{
if ( m_pEntities->GetSelectedItemsCount() == 0 )
{
g_pCommEditTool->ShowEntityInEntityProperties( NULL );
return;
}
int iSel = m_pEntities->GetSelectedItem( 0 );
KeyValues *kv = m_pEntities->GetItem( iSel );
CDmeCommentaryNodeEntity *pEntity = CastElement< CDmeCommentaryNodeEntity >( (CDmElement *)kv->GetPtr( "entity" ) );
g_pCommEditTool->ShowEntityInEntityProperties( pEntity );
}
//-----------------------------------------------------------------------------
// Purpose: Deletes the marked objects.
//-----------------------------------------------------------------------------
void CCommentaryNodeBrowserPanel::OnDeleteEntities(void)
{
int iSel = m_pEntities->GetSelectedItem( 0 );
{
// This is undoable
CAppUndoScopeGuard guard( NOTIFY_SETDIRTYFLAG, "Delete Entities", "Delete Entities" );
//
// Build a list of objects to delete.
//
int nCount = m_pEntities->GetSelectedItemsCount();
for (int i = 0; i < nCount; i++)
{
int nItemID = m_pEntities->GetSelectedItem(i);
KeyValues *kv = m_pEntities->GetItem( nItemID );
CDmElement *pEntity = (CDmElement *)kv->GetPtr( "entity" );
if ( pEntity )
{
m_pDoc->DeleteCommentaryNode( pEntity );
}
}
}
// Update the list box selection.
if (iSel >= m_pEntities->GetItemCount())
{
iSel = m_pEntities->GetItemCount() - 1;
}
m_pEntities->SetSingleSelectedItem( iSel );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CCommentaryNodeBrowserPanel::OnKeyCodeTyped( vgui::KeyCode code )
{
if ( code == KEY_DELETE )
{
OnDeleteEntities();
}
else
{
BaseClass::OnKeyCodeTyped( code );
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CCommentaryNodeBrowserPanel::OnItemSelected( void )
{
OnProperties();
}
//-----------------------------------------------------------------------------
// Select a particular node
//-----------------------------------------------------------------------------
void CCommentaryNodeBrowserPanel::SelectNode( CDmeCommentaryNodeEntity *pNode )
{
m_pEntities->ClearSelectedItems();
for ( int nItemID = m_pEntities->FirstItem(); nItemID != m_pEntities->InvalidItemID(); nItemID = m_pEntities->NextItem( nItemID ) )
{
KeyValues *kv = m_pEntities->GetItem( nItemID );
CDmElement *pEntity = (CDmElement *)kv->GetPtr( "entity" );
if ( pEntity == pNode )
{
m_pEntities->AddSelectedItem( nItemID );
break;
}
}
}
//-----------------------------------------------------------------------------
// Called when buttons are clicked
//-----------------------------------------------------------------------------
void CCommentaryNodeBrowserPanel::OnCommand( const char *pCommand )
{
if ( !Q_stricmp( pCommand, "delete" ) )
{
// Confirm we want to do it
MessageBox *pConfirm = new MessageBox( "#CommEditDeleteObjects", "#CommEditDeleteObjectsMsg", g_pCommEditTool->GetRootPanel() );
pConfirm->AddActionSignalTarget( this );
pConfirm->SetOKButtonText( "Yes" );
pConfirm->SetCommand( new KeyValues( "DeleteEntities" ) );
pConfirm->SetCancelButtonVisible( true );
pConfirm->SetCancelButtonText( "No" );
pConfirm->DoModal();
return;
}
if ( !Q_stricmp( pCommand, "Save" ) )
{
g_pCommEditTool->Save();
return;
}
if ( !Q_stricmp( pCommand, "CenterView" ) )
{
if ( m_pEntities->GetSelectedItemsCount() == 1 )
{
int iSel = m_pEntities->GetSelectedItem( 0 );
KeyValues *kv = m_pEntities->GetItem( iSel );
CDmeCommentaryNodeEntity *pEntity = CastElement< CDmeCommentaryNodeEntity >( (CDmElement *)kv->GetPtr( "entity" ) );
g_pCommEditTool->CenterView( pEntity );
}
return;
}
if ( !Q_stricmp( pCommand, "SaveAndTest" ) )
{
g_pCommEditTool->SaveAndTest();
return;
}
if ( !Q_stricmp( pCommand, "DropNodes" ) )
{
g_pCommEditTool->EnterNodeDropMode();
return;
}
BaseClass::OnCommand( pCommand );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CCommentaryNodeBrowserPanel::UpdateEntityList(void)
{
m_pEntities->RemoveAll();
CDmrCommentaryNodeEntityList entityList( m_pDoc->GetEntityList() );
if ( !entityList.IsValid() )
return;
int nCount = entityList.Count();
for ( int i = 0; i < nCount; ++i )
{
CDmElement *pEntity = entityList[i];
Assert( pEntity );
if ( !pEntity )
continue;
const char *pClassName = pEntity->GetValueString( "classname" );
if ( !pClassName || !pClassName[0] )
{
pClassName = "<no class>";
}
KeyValues *kv = new KeyValues( "node" );
kv->SetString( "classname", pClassName );
kv->SetPtr( "entity", pEntity );
const char *pTargetname = pEntity->GetValueString( "targetname" );
if ( !pTargetname || !pTargetname[0] )
{
pTargetname = "<no targetname>";
}
kv->SetString( "targetname", pTargetname );
m_pEntities->AddItem( kv, 0, false, false );
}
m_pEntities->SortList();
}
| 412 | 0.889689 | 1 | 0.889689 | game-dev | MEDIA | 0.494129 | game-dev,networking,desktop-app | 0.903365 | 1 | 0.903365 |
RelativityMC/C2ME-fabric | 3,954 | c2me-opts-dfc/src/main/java/com/ishland/c2me/opts/dfc/mixin/MixinChunkNoiseSampler.java | package com.ishland.c2me.opts.dfc.mixin;
import com.ishland.c2me.opts.dfc.common.ducks.IArrayCacheCapable;
import com.ishland.c2me.opts.dfc.common.ducks.ICoordinatesFilling;
import com.ishland.c2me.opts.dfc.common.gen.DelegatingBlendingAwareVisitor;
import com.ishland.c2me.opts.dfc.common.util.ArrayCache;
import net.minecraft.world.gen.chunk.Blender;
import net.minecraft.world.gen.chunk.ChunkNoiseSampler;
import net.minecraft.world.gen.densityfunction.DensityFunction;
import net.minecraft.world.gen.densityfunction.DensityFunctionTypes;
import org.jetbrains.annotations.NotNull;
import org.spongepowered.asm.mixin.Final;
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.ModifyArg;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
@Mixin(ChunkNoiseSampler.class)
public abstract class MixinChunkNoiseSampler implements IArrayCacheCapable, ICoordinatesFilling {
@Shadow @Final private int verticalCellBlockCount;
@Shadow @Final private int horizontalCellBlockCount;
@Shadow private int startBlockY;
@Shadow private int startBlockX;
@Shadow private int startBlockZ;
@Shadow private boolean isInInterpolationLoop;
@Shadow public abstract Blender getBlender();
private final ArrayCache c2me$arrayCache = new ArrayCache();
@Override
public ArrayCache c2me$getArrayCache() {
return this.c2me$arrayCache != null ? this.c2me$arrayCache : new ArrayCache();
}
@Override
public void c2me$fillCoordinates(int[] x, int[] y, int[] z) {
int index = 0;
for (int i = this.verticalCellBlockCount - 1; i >= 0; i--) {
int blockY = this.startBlockY + i;
for (int j = 0; j < this.horizontalCellBlockCount; j++) {
int blockX = this.startBlockX + j;
for (int k = 0; k < this.horizontalCellBlockCount; k++) {
int blockZ = this.startBlockZ + k;
x[index] = blockX;
y[index] = blockY;
z[index] = blockZ;
index++;
}
}
}
}
@Inject(method = "getActualDensityFunctionImpl", at = @At("HEAD"))
private void protectInterpolationLoop(DensityFunction function, CallbackInfoReturnable<DensityFunction> cir) {
if (this.isInInterpolationLoop && function instanceof DensityFunctionTypes.Wrapping) {
throw new IllegalStateException("Cannot create more wrapping during interpolation loop");
}
}
@ModifyArg(method = "<init>", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/gen/noise/NoiseRouter;apply(Lnet/minecraft/world/gen/densityfunction/DensityFunction$DensityFunctionVisitor;)Lnet/minecraft/world/gen/noise/NoiseRouter;"))
private DensityFunction.DensityFunctionVisitor modifyVisitor1(DensityFunction.DensityFunctionVisitor visitor) {
return c2me$getDelegatingBlendingAwareVisitor(visitor);
}
@Unique
private @NotNull DelegatingBlendingAwareVisitor c2me$getDelegatingBlendingAwareVisitor(DensityFunction.DensityFunctionVisitor visitor) {
return new DelegatingBlendingAwareVisitor(visitor, this.getBlender() != Blender.getNoBlending());
}
@ModifyArg(method = {"<init>", "createMultiNoiseSampler"}, at = @At(value = "INVOKE", target = "Lnet/minecraft/world/gen/densityfunction/DensityFunction;apply(Lnet/minecraft/world/gen/densityfunction/DensityFunction$DensityFunctionVisitor;)Lnet/minecraft/world/gen/densityfunction/DensityFunction;"), require = 7, expect = 7)
private DensityFunction.DensityFunctionVisitor modifyVisitor2(DensityFunction.DensityFunctionVisitor visitor) {
return c2me$getDelegatingBlendingAwareVisitor(visitor);
}
}
| 412 | 0.965071 | 1 | 0.965071 | game-dev | MEDIA | 0.811228 | game-dev | 0.92247 | 1 | 0.92247 |
huzongyao/NostalgiaLite | 3,681 | appnes/src/main/cpp/fceux/boards/28.cpp | /*
Copyright (C) 2012 FCEUX team
This file 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 file 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 the this software. If not, see <http://www.gnu.org/licenses/>.
*/
#include "mapinc.h"
// http://wiki.nesdev.com/w/index.php/INES_Mapper_028
//config
static int prg_mask_16k;
// state
uint8 reg;
uint8 chr;
uint8 prg;
uint8 mode;
uint8 outer;
void SyncMirror()
{
switch (mode & 3)
{
case 0: setmirror(MI_0); break;
case 1: setmirror(MI_1); break;
case 2: setmirror(MI_V); break;
case 3: setmirror(MI_H); break;
}
}
void Mirror(uint8 value)
{
if ((mode & 2) == 0)
{
mode &= 0xfe;
mode |= value >> 4 & 1;
}
SyncMirror();
}
static void Sync()
{
int prglo;
int prghi;
int outb = outer << 1;
//this can probably be rolled up, but i have no motivation to do so
//until it's been tested
switch (mode & 0x3c)
{
//32K modes
case 0x00:
case 0x04:
prglo = outb;
prghi = outb | 1;
break;
case 0x10:
case 0x14:
prglo = (outb & ~2) | (prg << 1 & 2);
prghi = (outb & ~2) | (prg << 1 & 2) | 1;
break;
case 0x20:
case 0x24:
prglo = (outb & ~6) | (prg << 1 & 6);
prghi = (outb & ~6) | (prg << 1 & 6) | 1;
break;
case 0x30:
case 0x34:
prglo = (outb & ~14) | (prg << 1 & 14);
prghi = (outb & ~14) | (prg << 1 & 14) | 1;
break;
//bottom fixed modes
case 0x08:
prglo = outb;
prghi = outb | prg & 1;
break;
case 0x18:
prglo = outb;
prghi = outb & ~2 | prg & 3;
break;
case 0x28:
prglo = outb;
prghi = outb & ~6 | prg & 7;
break;
case 0x38:
prglo = outb;
prghi = outb & ~14 | prg & 15;
break;
//top fixed modes
case 0x0c:
prglo = outb | prg & 1;
prghi = outb | 1;
break;
case 0x1c:
prglo = outb & ~2 | prg & 3;
prghi = outb | 1;
break;
case 0x2c:
prglo = outb & ~6 | prg & 7;
prghi = outb | 1;
break;
case 0x3c:
prglo = outb & ~14 | prg & 15;
prghi = outb | 1;
break;
}
prglo &= prg_mask_16k;
prghi &= prg_mask_16k;
setprg16(0x8000, prglo);
setprg16(0xC000, prghi);
setchr8(chr);
}
static DECLFW(WriteEXP)
{
uint32 addr = A;
uint8 value = V;
reg = value & 0x81;
}
static DECLFW(WritePRG)
{
uint32 addr = A;
uint8 value = V;
switch (reg)
{
case 0x00:
chr = value & 3;
Mirror(value);
break;
case 0x01:
prg = value & 15;
Mirror(value);
Sync();
break;
case 0x80:
mode = value & 63;
SyncMirror();
Sync();
break;
case 0x81:
outer = value & 63;
Sync();
break;
}
}
static void M28Reset(void)
{
outer = 63;
prg = 15;
Sync();
}
static void M28Power(void)
{
prg_mask_16k = PRGsize[0] - 1;
//EXP
SetWriteHandler(0x5000,0x5FFF,WriteEXP);
//PRG
SetWriteHandler(0x8000,0xFFFF,WritePRG);
SetReadHandler(0x8000,0xFFFF,CartBR);
//WRAM
SetReadHandler(0x6000,0x7FFF,CartBR);
SetWriteHandler(0x6000,0x7FFF,CartBW);
M28Reset();
}
static void M28Close(void)
{
}
static SFORMAT StateRegs[]=
{
{®, 1, "REG"},
{&chr, 1, "CHR"},
{&prg, 1, "PRG"},
{&mode, 1, "MODE"},
{&outer, 1, "OUTR"},
{0}
};
static void StateRestore(int version)
{
Sync();
}
void Mapper28_Init(CartInfo* info)
{
info->Power=M28Power;
info->Reset=M28Reset;
info->Close=M28Close;
GameStateRestore=StateRestore;
AddExState(&StateRegs, ~0, 0, 0);
}
| 412 | 0.885656 | 1 | 0.885656 | game-dev | MEDIA | 0.702788 | game-dev | 0.981294 | 1 | 0.981294 |
MIT-PAC/droidsafe-src | 14,546 | modeling/api/android/text/MeasuredText.java | /*
* Copyright (C) 2015, Massachusetts Institute of Technology
*
* 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.
*
* Please email droidsafe@lists.csail.mit.edu if you need additional
* information or have any questions.
*
*
* This file incorporates work covered by the following copyright and
* permission notice:
*
* Copyright (C) 2010 The Android Open Source Project
*
* 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.
*/
/***** THIS FILE HAS BEEN MODIFIED FROM THE ORIGINAL BY THE DROIDSAFE PROJECT. *****/
package android.text;
// Droidsafe Imports
import droidsafe.runtime.*;
import droidsafe.helpers.*;
import droidsafe.annotations.*;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.text.style.MetricAffectingSpan;
import android.text.style.ReplacementSpan;
import android.util.Log;
import com.android.internal.util.ArrayUtils;
class MeasuredText {
@DSComment("Package priviledge")
@DSBan(DSCat.DEFAULT_MODIFIER)
@DSGenerator(tool_name = "Doppelganger", tool_version = "2.0", generated_on = "2013-12-30 12:28:04.865 -0500", hash_original_method = "A730A63711FAF2BA11082F3B340B807C", hash_generated_method = "4E6EA45AE978894F4D87BFC28F424B02")
static MeasuredText obtain() {
MeasuredText mt;
synchronized (sLock) {
for (int i = sCached.length; --i >= 0;) {
if (sCached[i] != null) {
mt = sCached[i];
sCached[i] = null;
return mt;
}
}
}
mt = new MeasuredText();
if (localLOGV) {
Log.v("MEAS", "new: " + mt);
}
return mt;
}
@DSComment("Package priviledge")
@DSBan(DSCat.DEFAULT_MODIFIER)
@DSGenerator(tool_name = "Doppelganger", tool_version = "2.0", generated_on = "2013-12-30 12:28:04.868 -0500", hash_original_method = "1BAFA51CED79ACBA501A721EFAD84840", hash_generated_method = "DAE5FF8228279CA81A7486B6EBB19B06")
static MeasuredText recycle(MeasuredText mt) {
mt.mText = null;
if (mt.mLen < 1000) {
synchronized(sLock) {
for (int i = 0; i < sCached.length; ++i) {
if (sCached[i] == null) {
sCached[i] = mt;
mt.mText = null;
break;
}
}
}
}
return null;
}
@DSGeneratedField(tool_name = "Doppelganger", tool_version = "2.0", generated_on = "2013-12-30 12:28:04.824 -0500", hash_original_field = "7A06C0A50B73200DDC70097F2AFFF800", hash_generated_field = "761D2619615A389BF902F171CC86D6A4")
private static final boolean localLOGV = false;
@DSGeneratedField(tool_name = "Doppelganger", tool_version = "2.0", generated_on = "2013-12-30 12:28:04.860 -0500", hash_original_field = "14A59CFC333E208499C98B6D3860ADDD", hash_generated_field = "6FA9B47DB08FC419C50F72FDCF40883C")
private static final Object[] sLock = new Object[0];
@DSGeneratedField(tool_name = "Doppelganger", tool_version = "2.0", generated_on = "2013-12-30 12:28:04.862 -0500", hash_original_field = "AB3E4D5A7F78AED2968C08570B2AE9AB", hash_generated_field = "E84B170D94FAA90534173168110EF774")
private static MeasuredText[] sCached = new MeasuredText[3];
@DSGeneratedField(tool_name = "Doppelganger", tool_version = "2.0", generated_on = "2013-12-30 12:28:04.827 -0500", hash_original_field = "A59BBC07E5E46996D793B2F37E80BD24", hash_generated_field = "A59BBC07E5E46996D793B2F37E80BD24")
CharSequence mText;
@DSGeneratedField(tool_name = "Doppelganger", tool_version = "2.0", generated_on = "2013-12-30 12:28:04.829 -0500", hash_original_field = "56525EE47BD7FA6F8CF4F7593CA30653", hash_generated_field = "56525EE47BD7FA6F8CF4F7593CA30653")
int mTextStart;
@DSGeneratedField(tool_name = "Doppelganger", tool_version = "2.0", generated_on = "2013-12-30 12:28:04.832 -0500", hash_original_field = "F268DBF02C69AE56F5D7B811DF02DD71", hash_generated_field = "F268DBF02C69AE56F5D7B811DF02DD71")
float[] mWidths;
@DSGeneratedField(tool_name = "Doppelganger", tool_version = "2.0", generated_on = "2013-12-30 12:28:04.834 -0500", hash_original_field = "221D78AA948575C2C408290E651B0D1C", hash_generated_field = "221D78AA948575C2C408290E651B0D1C")
char[] mChars;
@DSGeneratedField(tool_name = "Doppelganger", tool_version = "2.0", generated_on = "2013-12-30 12:28:04.837 -0500", hash_original_field = "653966A07B2E0880FE25B3845B58F732", hash_generated_field = "653966A07B2E0880FE25B3845B58F732")
byte[] mLevels;
@DSGeneratedField(tool_name = "Doppelganger", tool_version = "2.0", generated_on = "2013-12-30 12:28:04.840 -0500", hash_original_field = "1D096AE80A1F47FBC923E53A1E78A2C9", hash_generated_field = "1D096AE80A1F47FBC923E53A1E78A2C9")
int mDir;
@DSGeneratedField(tool_name = "Doppelganger", tool_version = "2.0", generated_on = "2013-12-30 12:28:04.846 -0500", hash_original_field = "E7219AC9CF15F6988B4E84BAD92B2CE6", hash_generated_field = "E7219AC9CF15F6988B4E84BAD92B2CE6")
boolean mEasy;
@DSGeneratedField(tool_name = "Doppelganger", tool_version = "2.0", generated_on = "2013-12-30 12:28:04.849 -0500", hash_original_field = "4B68EEB0ED264408F73553B8964D2663", hash_generated_field = "4B68EEB0ED264408F73553B8964D2663")
int mLen;
@DSGeneratedField(tool_name = "Doppelganger", tool_version = "2.0", generated_on = "2013-12-30 12:28:04.851 -0500", hash_original_field = "25A5DEAC26D49039381CEC3AC02D8D8E", hash_generated_field = "649CC94BF1D5A5FECFE4D2F006B35728")
private int mPos;
@DSGeneratedField(tool_name = "Doppelganger", tool_version = "2.0", generated_on = "2013-12-30 12:28:04.854 -0500", hash_original_field = "B28AC88C47D899E85CEE0110DCCDCA16", hash_generated_field = "BD23BE48855C3EDD93B6A5A7CA353122")
private TextPaint mWorkPaint;
@DSComment("Private Method")
@DSBan(DSCat.PRIVATE_METHOD)
@DSGenerator(tool_name = "Doppelganger", tool_version = "2.0", generated_on = "2013-12-30 12:28:04.857 -0500", hash_original_method = "D598B3CBC464CFD963CF00BDB269B2BE", hash_generated_method = "AFF644A9C87997303EA454A23F283D57")
private MeasuredText() {
mWorkPaint = new TextPaint();
}
/**
* Analyzes text for bidirectional runs. Allocates working buffers.
*/
@DSComment("Package priviledge")
@DSBan(DSCat.DEFAULT_MODIFIER)
@DSGenerator(tool_name = "Doppelganger", tool_version = "2.0", generated_on = "2013-12-30 12:28:04.871 -0500", hash_original_method = "AA7EC2CF46DA02829550CC76130A18E2", hash_generated_method = "AA7EC2CF46DA02829550CC76130A18E2")
void setPara(CharSequence text, int start, int end, TextDirectionHeuristic textDir) {
mText = text;
mTextStart = start;
int len = end - start;
mLen = len;
mPos = 0;
if (mWidths == null || mWidths.length < len) {
mWidths = new float[ArrayUtils.idealFloatArraySize(len)];
}
if (mChars == null || mChars.length < len) {
mChars = new char[ArrayUtils.idealCharArraySize(len)];
}
TextUtils.getChars(text, start, end, mChars, 0);
if (text instanceof Spanned) {
Spanned spanned = (Spanned) text;
ReplacementSpan[] spans = spanned.getSpans(start, end,
ReplacementSpan.class);
for (int i = 0; i < spans.length; i++) {
int startInPara = spanned.getSpanStart(spans[i]) - start;
int endInPara = spanned.getSpanEnd(spans[i]) - start;
for (int j = startInPara; j < endInPara; j++) {
mChars[j] = '\uFFFC';
}
}
}
if ((textDir == TextDirectionHeuristics.LTR ||
textDir == TextDirectionHeuristics.FIRSTSTRONG_LTR ||
textDir == TextDirectionHeuristics.ANYRTL_LTR) &&
TextUtils.doesNotNeedBidi(mChars, 0, len)) {
mDir = Layout.DIR_LEFT_TO_RIGHT;
mEasy = true;
} else {
if (mLevels == null || mLevels.length < len) {
mLevels = new byte[ArrayUtils.idealByteArraySize(len)];
}
int bidiRequest;
if (textDir == TextDirectionHeuristics.LTR) {
bidiRequest = Layout.DIR_REQUEST_LTR;
} else if (textDir == TextDirectionHeuristics.RTL) {
bidiRequest = Layout.DIR_REQUEST_RTL;
} else if (textDir == TextDirectionHeuristics.FIRSTSTRONG_LTR) {
bidiRequest = Layout.DIR_REQUEST_DEFAULT_LTR;
} else if (textDir == TextDirectionHeuristics.FIRSTSTRONG_RTL) {
bidiRequest = Layout.DIR_REQUEST_DEFAULT_RTL;
} else {
boolean isRtl = textDir.isRtl(mChars, 0, len);
bidiRequest = isRtl ? Layout.DIR_REQUEST_RTL : Layout.DIR_REQUEST_LTR;
}
mDir = AndroidBidi.bidi(bidiRequest, mChars, mLevels, len, false);
mEasy = false;
}
}
@DSGenerator(tool_name = "Doppelganger", tool_version = "2.0", generated_on = "2013-12-30 12:28:04.875 -0500", hash_original_method = "DC7A3D7065A333C10C0F305EED7320B6", hash_generated_method = "DC7A3D7065A333C10C0F305EED7320B6")
float addStyleRun(TextPaint paint, int len, Paint.FontMetricsInt fm) {
if (fm != null) {
paint.getFontMetricsInt(fm);
}
int p = mPos;
mPos = p + len;
if (mEasy) {
int flags = mDir == Layout.DIR_LEFT_TO_RIGHT
? Canvas.DIRECTION_LTR : Canvas.DIRECTION_RTL;
return paint.getTextRunAdvances(mChars, p, len, p, len, flags, mWidths, p);
}
float totalAdvance = 0;
int level = mLevels[p];
for (int q = p, i = p + 1, e = p + len;; ++i) {
if (i == e || mLevels[i] != level) {
int flags = (level & 0x1) == 0 ? Canvas.DIRECTION_LTR : Canvas.DIRECTION_RTL;
totalAdvance +=
paint.getTextRunAdvances(mChars, q, i - q, q, i - q, flags, mWidths, q);
if (i == e) {
break;
}
q = i;
level = mLevels[i];
}
}
return totalAdvance;
}
@DSGenerator(tool_name = "Doppelganger", tool_version = "2.0", generated_on = "2013-12-30 12:28:04.878 -0500", hash_original_method = "18B04B5B33F859850D856F2E2DC299C7", hash_generated_method = "CD1CBD9438950B6E7CD602AED538814D")
float addStyleRun(TextPaint paint, MetricAffectingSpan[] spans, int len,
Paint.FontMetricsInt fm) {
TextPaint workPaint = mWorkPaint;
workPaint.set(paint);
// XXX paint should not have a baseline shift, but...
workPaint.baselineShift = 0;
ReplacementSpan replacement = null;
for (int i = 0; i < spans.length; i++) {
MetricAffectingSpan span = spans[i];
if (span instanceof ReplacementSpan) {
replacement = (ReplacementSpan)span;
} else {
span.updateMeasureState(workPaint);
}
}
float wid;
if (replacement == null) {
wid = addStyleRun(workPaint, len, fm);
} else {
// Use original text. Shouldn't matter.
wid = replacement.getSize(workPaint, mText, mTextStart + mPos,
mTextStart + mPos + len, fm);
float[] w = mWidths;
w[mPos] = wid;
for (int i = mPos + 1, e = mPos + len; i < e; i++)
w[i] = 0;
mPos += len;
}
if (fm != null) {
if (workPaint.baselineShift < 0) {
fm.ascent += workPaint.baselineShift;
fm.top += workPaint.baselineShift;
} else {
fm.descent += workPaint.baselineShift;
fm.bottom += workPaint.baselineShift;
}
}
return wid;
}
@DSComment("Package priviledge")
@DSBan(DSCat.DEFAULT_MODIFIER)
@DSGenerator(tool_name = "Doppelganger", tool_version = "2.0", generated_on = "2013-12-30 12:28:04.881 -0500", hash_original_method = "F30A282CEAB73A5948442153B9251096", hash_generated_method = "F30A282CEAB73A5948442153B9251096")
int breakText(int start, int limit, boolean forwards, float width) {
float[] w = mWidths;
if (forwards) {
for (int i = start; i < limit; ++i) {
if ((width -= w[i]) < 0) {
return i - start;
}
}
} else {
for (int i = limit; --i >= start;) {
if ((width -= w[i]) < 0) {
return limit - i -1;
}
}
}
return limit - start;
}
@DSComment("Package priviledge")
@DSBan(DSCat.DEFAULT_MODIFIER)
@DSGenerator(tool_name = "Doppelganger", tool_version = "2.0", generated_on = "2013-12-30 12:28:04.884 -0500", hash_original_method = "053843F92349BBB89263F41FED96E473", hash_generated_method = "053843F92349BBB89263F41FED96E473")
float measure(int start, int limit) {
float width = 0;
float[] w = mWidths;
for (int i = start; i < limit; ++i) {
width += w[i];
}
return width;
}
}
| 412 | 0.743841 | 1 | 0.743841 | game-dev | MEDIA | 0.211738 | game-dev | 0.896358 | 1 | 0.896358 |
RektSuddenDeath/College-Champ-Data-pack | 1,478 | Lab-RP/data/gr/functions/rooms/archived/mesa_range/pink/complete.mcfunction |
# Open Gates
execute as @e[type=minecraft:area_effect_cloud,tag=gr_pinkanchor] at @s run summon area_effect_cloud ~ ~10 ~15 {Duration:9999999,Tags:["gr_opener"]}
execute as @e[type=minecraft:area_effect_cloud,tag=gr_pinkanchor] at @s run fill ~26 101 ~1 ~28 103 ~29 air replace black_stained_glass_pane
# Playsound
execute as @a[team=pink] at @s run playsound gr.roomcomplete record @s
# Save times
scoreboard players operation @e[type=area_effect_cloud,tag=gr_general,tag=gr_pinkany] gr_room2time = pink gr_currenttime
# Trim
execute as @e[type=minecraft:area_effect_cloud,tag=gr_pinkanchor] at @s run fill ~1 111 ~-1 ~31 111 ~31 pink_terracotta replace smooth_quartz
# Calculate Position, and update scoreboard
scoreboard players add pink gr_completeroom 1
scoreboard players add 2 gr_indvroom 1
function gr:scoreboard/moveup/pink
scoreboard players operation pink gr_currentpos = 2 gr_indvroom
function gr:scoreboard/calc
# Announce position
tellraw @a[team=!pink] ["",{"translate":"team.pink"},"§7第",{"score":{"name": "2","objective": "gr_indvroom"},"color": "aqua"},"§7个完成了房间","§e[","§6Mesa Range","§e]"]
tellraw @a[team=pink] ["","§7你","§7第",{"score":{"name": "2","objective": "gr_indvroom"},"color": "aqua"},"§7个完成了房间","§e[","§6Mesa Range","§e]"]
# Initiate next room
scoreboard players add pink gr_teamphase 1
execute as @e[type=minecraft:area_effect_cloud,tag=gr_pinkanchor] at @s run tp @s ~-47 ~ ~
function gr:rooms/3/pink/divider
function gr:rooms/3/pink/master | 412 | 0.894785 | 1 | 0.894785 | game-dev | MEDIA | 0.918033 | game-dev | 0.79168 | 1 | 0.79168 |
FirstPersonKSP/AvionicsSystems | 3,973 | GameData/MOARdV/MAS_ASET/Push_Button_Modular/ManualButtons/pb_GPWS_ON-OFF-SH01-B6-C2.cfg | PROP
{
name = MAS_pb_GPWS_ON-OFF-SH01-B6-C2
MODEL
{
model = ASET/ASET_Props/Control/Push_Button_Modular/models/pb_SplitHorizontal_Cap
texture = pb_Full_Cap_Black,ASET/ASET_Props/Control/Push_Button_Modular/models/pb_Full_Cap_Black
texture = Switch_TUMBLEDiffuse,ASET/ASET_Props/Control/Switch_Tumble/Switch_TUMBLEDiffuse
}
MODEL
{
model = ASET/ASET_Props/Control/Push_Button_Modular/models/pb_Bcklt_6
texture = Switch_TUMBLEDiffuse,ASET/ASET_Props/Control/Switch_Tumble/Switch_TUMBLEDiffuse
}
MODEL
{
model = ASET/ASET_Props/Control/Push_Button_Modular/models/pb_Cover02
texture = pb_Glass_Diffuse,ASET/ASET_Props/Control/Push_Button_Modular/models/pb_Glass_Diffuse
texture = Switch_TUMBLEDiffuse,ASET/ASET_Props/Control/Switch_Tumble/Switch_TUMBLEDiffuse
}
MODEL
{
model = ASET/ASET_Props/Control/Push_Button_Modular/models/pb_Collider
}
MODULE
{
name = MASComponent
COLLIDER_EVENT
{
name = Button Collider
collider = pb_Collider
onClick = fc.TogglePersistent("GPWS_ON")
sound = ASET/ASET_Props/Sounds/pb_Push01
volume = 1
}
ANIMATION
{
name = Button Animation
animation = pb_PushAnim
variable = fc.GetPersistent("GPWS_ON")
speed = 5
}
ANIMATION
{
name = Cover Animation
animation = pb_Cover_Anim
variable = fc.GetPersistent("%AUTOID%-Cover")
speed = 5
}
COLLIDER_EVENT
{
name = Cover Collider
collider = pb_Cover_Collider
onClick = fc.TogglePersistent("%AUTOID%-Cover")
sound = ASET/ASET_Props/Sounds/pb_Cover02
volume = 1
}
TEXT_LABEL
{
name = Top Label
transform = PanelTextTop_cover
fontSize = 5.0
oneshot = true
font = Liberation Sans
style = Bold
alignment = Center
anchor = LowerCenter
emissive = active
variable = fc.Conditioned(fc.GetPersistentAsNumber("Backlight"))
blend = true
activeColor = COLOR_ASET_SWITCHER_NAME_POSITIVECOLOR
passiveColor = COLOR_ASET_SWITCHER_NAME_ZEROCOLOR
text = GPWS
}
TEXT_LABEL
{
name = Button Top Label
transform = Legend_Upper
fontSize = 4.5
oneshot = true
font = Liberation Sans
style = Bold
alignment = Center
anchor = MiddleCenter
emissive = active
variable = fc.Conditioned(fc.GetPersistentAsNumber("GPWS_ON"))
blend = true
activeColor = COLOR_MOARdV_IndicatorLampGreen
passiveColor = COLOR_MOARdV_PassiveBacklightText
text = ON
}
TEXT_LABEL
{
name = Button Bottom Label
transform = Legend_Lower
fontSize = 4.5
oneshot = true
font = Liberation Sans
style = Bold
alignment = Center
anchor = MiddleCenter
emissive = active
variable = fc.Conditioned(fc.GetPersistentAsNumber("GPWS_ON"))
activeColor = COLOR_MOARdV_IndicatorLampAmber
passiveColor = COLOR_MOARdV_PassiveBacklightText
text = OFF
blend = true
}
COLOR_SHIFT
{
name = Bottom Lens
transform = pb_SH_BottomLens_obj
passiveColor = 0, 0, 0, 255
activeColor = COLOR_ASET_mpb_ORANGE
variable = fc.Conditioned(fc.GetPersistentAsNumber("GPWS_ON") == 0)
}
TEXTURE_SHIFT
{
name = Bottom Lens
transform = pb_SH_BottomLens_obj
startUV = 0, 0
endUV = 0, -0.5
layers = _Emissive
variable = fc.Conditioned(fc.GetPersistentAsNumber("GPWS_ON") == 0)
blend = true
}
COLOR_SHIFT
{
name = Top Lens
transform = pb_SH_TopLens_obj
passiveColor = 0, 0, 0, 255
activeColor = COLOR_ASET_mpb_GREEN
variable = fc.Conditioned(fc.GetPersistentAsNumber("GPWS_ON"))
}
TEXTURE_SHIFT
{
name = Top Lens
transform = pb_SH_TopLens_obj
startUV = 0, 0
endUV = 0, -0.5
layers = _Emissive
variable = fc.Conditioned(fc.GetPersistentAsNumber("GPWS_ON"))
blend = true
}
COLOR_SHIFT
{
name = Border Glow
transform = GlowBorder
passiveColor = 0, 0, 0, 255
activeColor = COLOR_ASET_SWITCHER_BORDER_POSITIVECOLOR
variable = fc.Conditioned(fc.GetPersistentAsNumber("Backlight"))
blend = true
}
}
} | 412 | 0.847266 | 1 | 0.847266 | game-dev | MEDIA | 0.647523 | game-dev,graphics-rendering | 0.872353 | 1 | 0.872353 |
shit-ware/IW4 | 14,766 | maps/mp/gametypes/_killcam.gsc | #include maps\mp\_utility;
#include maps\mp\gametypes\_hud_util;
init()
{
precacheString(&"PLATFORM_PRESS_TO_SKIP");
precacheString(&"PLATFORM_PRESS_TO_RESPAWN");
precacheString(&"PLATFORM_PRESS_TO_COPYCAT");
precacheShader("specialty_copycat");
level.killcam = maps\mp\gametypes\_tweakables::getTweakableValue( "game", "allowkillcam" );
}
killcam(
attackerNum, // entity number of the attacker
killcamentityindex, // entity number of the entity to view (grenade, airstrike, etc)
killcamentitystarttime, // time at which the killcamentity came into being
sWeapon, // killing weapon
predelay, // time between player death and beginning of killcam
offsetTime, // something to do with how far back in time the killer was seeing the world when he made the kill; latency related, sorta
timeUntilRespawn, // will the player be allowed to respawn after the killcam?
maxtime, // time remaining until map ends; the killcam will never last longer than this. undefined = no limit
attacker, // entity object of attacker
victim // entity object of the victim
)
{
// monitors killcam and hides HUD elements during killcam session
//if ( !level.splitscreen )
// self thread killcam_HUD_off();
self endon("disconnect");
self endon("spawned");
level endon("game_ended");
if ( attackerNum < 0 )
return;
// length from killcam start to killcam end
if (getdvar("scr_killcam_time") == "") {
if ( sWeapon == "artillery_mp" || sWeapon == "stealth_bomb_mp" )
camtime = (gettime() - killcamentitystarttime) / 1000 - predelay - .1;
else if ( level.showingFinalKillcam )
camtime = 4.0;
else if ( sWeapon == "javelin_mp" )
camtime = 8;
else if ( issubstr( sWeapon, "remotemissile_" ) )
camtime = 5;
else if ( !timeUntilRespawn || timeUntilRespawn > 5.0 ) // if we're not going to respawn, we can take more time to watch what happened
camtime = 5.0;
else if ( sWeapon == "frag_grenade_mp" || sWeapon == "frag_grenade_short_mp" || sWeapon == "semtex_mp" )
camtime = 4.25; // show long enough to see grenade thrown
else
camtime = 2.5;
}
else
camtime = getdvarfloat("scr_killcam_time");
if (isdefined(maxtime)) {
if (camtime > maxtime)
camtime = maxtime;
if (camtime < .05)
camtime = .05;
}
// time after player death that killcam continues for
if (getdvar("scr_killcam_posttime") == "")
postdelay = 2;
else {
postdelay = getdvarfloat("scr_killcam_posttime");
if (postdelay < 0.05)
postdelay = 0.05;
}
/* timeline:
| camtime | postdelay |
| | predelay |
^ killcam start ^ player death ^ killcam end
^ player starts watching killcam
*/
killcamlength = camtime + postdelay;
// don't let the killcam last past the end of the round.
if (isdefined(maxtime) && killcamlength > maxtime)
{
// first trim postdelay down to a minimum of 1 second.
// if that doesn't make it short enough, trim camtime down to a minimum of 1 second.
// if that's still not short enough, cancel the killcam.
if ( maxtime < 2 )
return;
if (maxtime - camtime >= 1) {
// reduce postdelay so killcam ends at end of match
postdelay = maxtime - camtime;
}
else {
// distribute remaining time over postdelay and camtime
postdelay = 1;
camtime = maxtime - 1;
}
// recalc killcamlength
killcamlength = camtime + postdelay;
}
killcamoffset = camtime + predelay;
startTime = getTime();
self notify ( "begin_killcam", startTime );
self.sessionstate = "spectator";
self.forcespectatorclient = attackerNum;
self.killcamentity = -1;
if ( killcamentityindex >= 0 )
self thread setKillCamEntity( killcamentityindex, killcamoffset, killcamentitystarttime );
self.archivetime = killcamoffset;
self.killcamlength = killcamlength;
self.psoffsettime = offsetTime;
// ignore spectate permissions
self allowSpectateTeam("allies", true);
self allowSpectateTeam("axis", true);
self allowSpectateTeam("freelook", true);
self allowSpectateTeam("none", true);
if ( isDefined( attacker ) && level.showingFinalKillcam ) // attacker may have disconnected
{
self openMenu( "killedby_card_display" );
self SetCardDisplaySlot( attacker, 7 );
}
self thread endedKillcamCleanup();
// wait till the next server frame to allow code a chance to update archivetime if it needs trimming
wait 0.05;
assertex( self.archivetime <= killcamoffset + 0.0001, "archivetime: " + self.archivetime + ", killcamoffset: " + killcamoffset );
if ( self.archivetime < killcamoffset )
println( "WARNING: Code trimmed killcam time by " + (killcamoffset - self.archivetime) + " seconds because it doesn't have enough game time recorded!" );
camtime = self.archivetime - .05 - predelay;
killcamlength = camtime + postdelay;
self.killcamlength = killcamlength;
if ( camtime <= 0 ) // if we're not looking back in time far enough to even see the death, cancel
{
println( "Cancelling killcam because we don't even have enough recorded to show the death." );
self.sessionstate = "dead";
self.forcespectatorclient = -1;
self.killcamentity = -1;
self.archivetime = 0;
self.psoffsettime = 0;
self notify ( "killcam_ended" );
return;
}
if ( level.showingFinalKillcam )
thread doFinalKillCamFX( camtime );
self.killcam = true;
self initKCElements();
if ( !level.splitscreen )
{
self.kc_timer.alpha = 1;
self.kc_timer setTenthsTimer(camtime);
}
if ( timeUntilRespawn && !level.gameEnded )
{
if ( timeUntilRespawn > 0 )
setLowerMessage( "kc_info", game["strings"]["waiting_to_spawn"], timeUntilRespawn );
else
setLowerMessage( "kc_info", &"PLATFORM_PRESS_TO_SKIP" );
}
else if ( !level.gameEnded )
{
setLowerMessage( "kc_info", &"PLATFORM_PRESS_TO_RESPAWN" );
}
if ( !level.showingFinalKillcam )
self.kc_skiptext.alpha = 1;
else
self.kc_skiptext.alpha = 0;
self.kc_othertext.alpha = 0;
self.kc_icon.alpha = 0;
self thread spawnedKillcamCleanup();
if ( self == victim && victim _hasPerk( "specialty_copycat" ) && isDefined( victim.pers["copyCatLoadout"] ) )
self thread waitKCCopyCatButton( attacker );
if ( !level.showingFinalKillcam )
self thread waitSkipKillcamButton( timeUntilRespawn );
else
self notify ( "showing_final_killcam" );
self thread endKillcamIfNothingToShow();
self waittillKillcamOver();
if ( level.showingFinalKillcam )
{
self thread maps\mp\gametypes\_playerlogic::spawnEndOfGame();
return;
}
self thread calculateKillCamTime( startTime );
self thread killcamCleanup( true );
}
doFinalKillCamFX( camTime )
{
if ( isDefined( level.doingFinalKillcamFx ) )
return;
level.doingFinalKillcamFx = true;
intoSlowMoTime = camTime;
if ( intoSlowMoTime > 1.0 )
{
intoSlowMoTime = 1.0;
wait( camTime - 1.0 );
}
setSlowMotion( 1.0, 0.25, intoSlowMoTime ); // start timescale, end timescale, lerp duration
wait( intoSlowMoTime + .5 );
setSlowMotion( 0.25, 1, 1.0 );
level.doingFinalKillcamFx = undefined;
}
calculateKillCamTime( startTime )
{
watchedTime = int(getTime() - startTime);
self incPlayerStat( "killcamtimewatched", watchedTime );
}
waittillKillcamOver()
{
self endon("abort_killcam");
wait(self.killcamlength - 0.05);
}
setKillCamEntity( killcamentityindex, killcamoffset, starttime )
{
self endon("disconnect");
self endon("killcam_ended");
killcamtime = (gettime() - killcamoffset * 1000);
if ( starttime > killcamtime )
{
wait .05;
// code may have trimmed archivetime after the first frame if we couldn't go back in time as far as requested.
killcamoffset = self.archivetime;
killcamtime = (gettime() - killcamoffset * 1000);
if ( starttime > killcamtime )
wait (starttime - killcamtime) / 1000;
}
self.killcamentity = killcamentityindex;
}
waitSkipKillcamButton( timeUntilRespawn )
{
self endon("disconnect");
self endon("killcam_ended");
while(self useButtonPressed())
wait .05;
while(!(self useButtonPressed()))
wait .05;
if ( !matchMakingGame() )
self incPlayerStat( "killcamskipped", 1 );
if ( timeUntilRespawn <= 0 )
clearLowerMessage( "kc_info" );
self notify("abort_killcam");
}
waitKCCopyCatButton( attacker )
{
self endon("disconnect");
self endon("killcam_ended");
self waitCopyCatButton( attacker );
self notify("abort_killcam");
}
waitDeathCopyCatButton( attacker )
{
self endon ( "disconnect" );
self initKCElements();
usedCopycat = self waitCopyCatButton( attacker );
if ( !isDefined( usedCopycat ) )
{
self.kc_icon.alpha = 0;
self.kc_othertext.alpha = 0;
}
}
waitCopyCatButton( attacker )
{
self endon ( "spawned_player" );
self endon ( "death_delay_finished" );
self.kc_icon setShader( "specialty_copycat", 48, 48 );
self.kc_othertext setText( &"PLATFORM_PRESS_TO_COPYCAT" );
self.kc_othertext.alpha = 1;
self.kc_icon.alpha = 1;
self notifyOnPlayerCommand( "use_copycat", "weapnext" );
self waittill( "use_copycat" );
self.pers["copyCatLoadout"]["inUse"] = true;
self.pers["copyCatLoadout"]["owner"] = attacker;
self.kc_othertext fadeOverTime( 0.5 );
self.kc_othertext.alpha = 0;
self.kc_icon fadeOverTime( 0.25 );
self.kc_icon scaleOverTime( 0.25, 512, 512 );
self.kc_icon.alpha = 0;
if ( isDefined( attacker ) )
attacker thread maps\mp\gametypes\_hud_message::playerCardSplashNotify( "copied", self );
self playLocalSound( "copycat_steal_class" );
return true;
}
waitSkipKillcamSafeSpawnButton()
{
self endon("disconnect");
self endon("killcam_ended");
if ( !self maps\mp\gametypes\_playerlogic::maySpawn() )
return;
while(self fragButtonPressed())
wait .05;
while(!(self fragButtonPressed()))
wait .05;
self.wantSafeSpawn = true;
self notify("abort_killcam");
}
endKillcamIfNothingToShow()
{
self endon("disconnect");
self endon("killcam_ended");
while(1)
{
// code may trim our archivetime to zero if there is nothing "recorded" to show.
// this can happen when the person we're watching in our killcam goes into killcam himself.
// in this case, end the killcam.
if ( self.archivetime <= 0 )
break;
wait .05;
}
self notify("abort_killcam");
}
spawnedKillcamCleanup()
{
self endon("disconnect");
self endon("killcam_ended");
self waittill("spawned");
self thread killcamCleanup( false );
}
endedKillcamCleanup()
{
self endon("disconnect");
self endon("killcam_ended");
level waittill("game_ended");
self thread killcamCleanup( true );
}
killcamCleanup( clearState )
{
if(isDefined(self.kc_skiptext))
self.kc_skiptext.alpha = 0;
if(isDefined(self.kc_timer))
self.kc_timer.alpha = 0;
if(isDefined(self.kc_icon))
self.kc_icon.alpha = 0;
if(isDefined(self.kc_othertext))
self.kc_othertext.alpha = 0;
self.killcam = undefined;
if ( !level.gameEnded )
self clearLowerMessage( "kc_info" );
self thread maps\mp\gametypes\_spectating::setSpectatePermissions();
self notify("killcam_ended"); // do this last, in case this function was called from a thread ending on it
if ( !clearState )
return;
self.sessionstate = "dead";
self ClearKillcamState();
}
cancelKillCamOnUse()
{
self.cancelKillcam = false;
self thread cancelKillCamOnUse_specificButton( ::cancelKillCamUseButton, ::cancelKillCamCallback );
//self thread cancelKillCamOnUse_specificButton( ::cancelKillCamSafeSpawnButton, ::cancelKillCamSafeSpawnCallback );
}
cancelKillCamUseButton()
{
return self useButtonPressed();
}
cancelKillCamSafeSpawnButton()
{
return self fragButtonPressed();
}
cancelKillCamCallback()
{
self.cancelKillcam = true;
}
cancelKillCamSafeSpawnCallback()
{
self.cancelKillcam = true;
self.wantSafeSpawn = true;
}
cancelKillCamOnUse_specificButton( pressingButtonFunc, finishedFunc )
{
self endon ( "death_delay_finished" );
self endon ( "disconnect" );
level endon ( "game_ended" );
for ( ;; )
{
if ( !self [[pressingButtonFunc]]() )
{
wait ( 0.05 );
continue;
}
buttonTime = 0;
while( self [[pressingButtonFunc]]() )
{
buttonTime += 0.05;
wait ( 0.05 );
}
if ( buttonTime >= 0.5 )
continue;
buttonTime = 0;
while ( !self [[pressingButtonFunc]]() && buttonTime < 0.5 )
{
buttonTime += 0.05;
wait ( 0.05 );
}
if ( buttonTime >= 0.5 )
continue;
self [[finishedFunc]]();
return;
}
}
initKCElements()
{
if ( !isDefined( self.kc_skiptext ) )
{
self.kc_skiptext = newClientHudElem(self);
self.kc_skiptext.archived = false;
self.kc_skiptext.x = 0;
self.kc_skiptext.alignX = "center";
self.kc_skiptext.alignY = "top";
self.kc_skiptext.horzAlign = "center_adjustable";
self.kc_skiptext.vertAlign = "top_adjustable";
self.kc_skiptext.sort = 1; // force to draw after the bars
self.kc_skiptext.font = "default";
self.kc_skiptext.foreground = true;
self.kc_skiptext.hideWhenInMenu = true;
if ( level.splitscreen )
{
self.kc_skiptext.y = 20;
self.kc_skiptext.fontscale = 1.2; // 1.8/1.5
}
else
{
self.kc_skiptext.y = 32;
self.kc_skiptext.fontscale = 1.8;
}
}
if ( !isDefined( self.kc_othertext ) )
{
self.kc_othertext = newClientHudElem(self);
self.kc_othertext.archived = false;
self.kc_othertext.y = 18;
self.kc_othertext.alignX = "left";
self.kc_othertext.alignY = "top";
self.kc_othertext.horzAlign = "center";
self.kc_othertext.vertAlign = "middle";
self.kc_othertext.sort = 10; // force to draw after the bars
self.kc_othertext.font = "small";
self.kc_othertext.foreground = true;
self.kc_othertext.hideWhenInMenu = true;
if ( level.splitscreen )
{
self.kc_othertext.x = 16;
self.kc_othertext.fontscale = 1.2;
}
else
{
self.kc_othertext.x = 62;
self.kc_othertext.fontscale = 1.6;
}
}
if ( !isDefined( self.kc_icon ) )
{
self.kc_icon = newClientHudElem(self);
self.kc_icon.archived = false;
self.kc_icon.x = 16;
self.kc_icon.y = 16;
self.kc_icon.alignX = "left";
self.kc_icon.alignY = "top";
self.kc_icon.horzAlign = "center";
self.kc_icon.vertAlign = "middle";
self.kc_icon.sort = 1; // force to draw after the bars
self.kc_icon.foreground = true;
self.kc_icon.hideWhenInMenu = true;
}
if ( !level.splitscreen )
{
if ( !isdefined( self.kc_timer ) )
{
self.kc_timer = createFontString( "hudbig", 1.0 );
self.kc_timer.archived = false;
self.kc_timer.x = 0;
self.kc_timer.alignX = "center";
self.kc_timer.alignY = "middle";
self.kc_timer.horzAlign = "center_safearea";
self.kc_timer.vertAlign = "top_adjustable";
self.kc_timer.y = 42;
self.kc_timer.sort = 1; // force to draw after the bars
self.kc_timer.font = "hudbig";
self.kc_timer.foreground = true;
self.kc_timer.color = (0.85,0.85,0.85);
self.kc_timer.hideWhenInMenu = true;
}
}
}
| 412 | 0.79601 | 1 | 0.79601 | game-dev | MEDIA | 0.879113 | game-dev | 0.882744 | 1 | 0.882744 |
It-Life/Deer_GameFramework_Wolong | 5,880 | Assets/Standard Assets/ThirdParty/Demigiant/DOTween/Modules/DOTweenModuleUtils.cs | // Author: Daniele Giardini - http://www.demigiant.com
// Created: 2018/07/13
using System;
using System.Reflection;
using UnityEngine;
using DG.Tweening.Core;
using DG.Tweening.Plugins.Core.PathCore;
using DG.Tweening.Plugins.Options;
#pragma warning disable 1591
namespace DG.Tweening
{
/// <summary>
/// Utility functions that deal with available Modules.
/// Modules defines:
/// - DOTAUDIO
/// - DOTPHYSICS
/// - DOTPHYSICS2D
/// - DOTSPRITE
/// - DOTUI
/// Extra defines set and used for implementation of external assets:
/// - DOTWEEN_TMP ► TextMesh Pro
/// - DOTWEEN_TK2D ► 2D Toolkit
/// </summary>
public static class DOTweenModuleUtils
{
static bool _initialized;
#region Reflection
/// <summary>
/// Called via Reflection by DOTweenComponent on Awake
/// </summary>
#if UNITY_2018_1_OR_NEWER
[UnityEngine.Scripting.Preserve]
#endif
public static void Init()
{
if (_initialized) return;
_initialized = true;
DOTweenExternalCommand.SetOrientationOnPath += Physics.SetOrientationOnPath;
#if UNITY_EDITOR
#if UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_5 || UNITY_2017_1
UnityEditor.EditorApplication.playmodeStateChanged += PlaymodeStateChanged;
#else
UnityEditor.EditorApplication.playModeStateChanged += PlaymodeStateChanged;
#endif
#endif
}
#if UNITY_2018_1_OR_NEWER
#pragma warning disable
[UnityEngine.Scripting.Preserve]
// Just used to preserve methods when building, never called
static void Preserver()
{
Assembly[] loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies();
MethodInfo mi = typeof(MonoBehaviour).GetMethod("Stub");
}
#pragma warning restore
#endif
#endregion
#if UNITY_EDITOR
// Fires OnApplicationPause in DOTweenComponent even when Editor is paused (otherwise it's only fired at runtime)
#if UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_5 || UNITY_2017_1
static void PlaymodeStateChanged()
#else
static void PlaymodeStateChanged(UnityEditor.PlayModeStateChange state)
#endif
{
if (DOTween.instance == null) return;
DOTween.instance.OnApplicationPause(UnityEditor.EditorApplication.isPaused);
}
#endif
// █████████████████████████████████████████████████████████████████████████████████████████████████████████████████████
// ███ INTERNAL CLASSES ████████████████████████████████████████████████████████████████████████████████████████████████
// █████████████████████████████████████████████████████████████████████████████████████████████████████████████████████
public static class Physics
{
// Called via DOTweenExternalCommand callback
public static void SetOrientationOnPath(PathOptions options, Tween t, Quaternion newRot, Transform trans)
{
#if true // PHYSICS_MARKER
if (options.isRigidbody) ((Rigidbody)t.target).rotation = newRot;
else trans.rotation = newRot;
#else
trans.rotation = newRot;
#endif
}
// Returns FALSE if the DOTween's Physics2D Module is disabled, or if there's no Rigidbody2D attached
public static bool HasRigidbody2D(Component target)
{
#if true // PHYSICS2D_MARKER
return target.GetComponent<Rigidbody2D>() != null;
#else
return false;
#endif
}
#region Called via Reflection
// Called via Reflection by DOTweenPathInspector
// Returns FALSE if the DOTween's Physics Module is disabled, or if there's no rigidbody attached
#if UNITY_2018_1_OR_NEWER
[UnityEngine.Scripting.Preserve]
#endif
public static bool HasRigidbody(Component target)
{
#if true // PHYSICS_MARKER
return target.GetComponent<Rigidbody>() != null;
#else
return false;
#endif
}
// Called via Reflection by DOTweenPath
#if UNITY_2018_1_OR_NEWER
[UnityEngine.Scripting.Preserve]
#endif
public static TweenerCore<Vector3, Path, PathOptions> CreateDOTweenPathTween(
MonoBehaviour target, bool tweenRigidbody, bool isLocal, Path path, float duration, PathMode pathMode
){
TweenerCore<Vector3, Path, PathOptions> t = null;
bool rBodyFoundAndTweened = false;
#if true // PHYSICS_MARKER
if (tweenRigidbody) {
Rigidbody rBody = target.GetComponent<Rigidbody>();
if (rBody != null) {
rBodyFoundAndTweened = true;
t = isLocal
? rBody.DOLocalPath(path, duration, pathMode)
: rBody.DOPath(path, duration, pathMode);
}
}
#endif
#if true // PHYSICS2D_MARKER
if (!rBodyFoundAndTweened && tweenRigidbody) {
Rigidbody2D rBody2D = target.GetComponent<Rigidbody2D>();
if (rBody2D != null) {
rBodyFoundAndTweened = true;
t = isLocal
? rBody2D.DOLocalPath(path, duration, pathMode)
: rBody2D.DOPath(path, duration, pathMode);
}
}
#endif
if (!rBodyFoundAndTweened) {
t = isLocal
? target.transform.DOLocalPath(path, duration, pathMode)
: target.transform.DOPath(path, duration, pathMode);
}
return t;
}
#endregion
}
}
}
| 412 | 0.85663 | 1 | 0.85663 | game-dev | MEDIA | 0.969353 | game-dev | 0.932024 | 1 | 0.932024 |
Raku/nqp | 9,288 | src/vm/jvm/runtime/org/raku/nqp/sixmodel/reprs/VMArrayInstance_n.java | package org.raku.nqp.sixmodel.reprs;
import java.lang.System;
import java.util.Arrays;
import org.raku.nqp.runtime.ExceptionHandling;
import org.raku.nqp.runtime.ThreadContext;
import org.raku.nqp.sixmodel.SixModelObject;
public class VMArrayInstance_n extends VMArrayInstanceBase {
public int elems;
public int start;
public double[] slots;
@Override
public void at_pos_native(ThreadContext tc, long index) {
if (index < 0) {
index += elems;
if (index < 0)
throw ExceptionHandling.dieInternal(tc, "VMArray: Index out of bounds");
}
else if (index >= elems) {
tc.native_type = ThreadContext.NATIVE_NUM;
tc.native_n = 0.0;
return;
}
tc.native_type = ThreadContext.NATIVE_NUM;
tc.native_n = slots[start + (int)index];
}
@Override
public long exists_pos(ThreadContext tc, long key) {
if (key < 0) {
key += this.elems;
}
if (key >= 0 && key < this.elems) {
return 1;
}
return 0;
}
private void set_size_internal(ThreadContext tc, long n) {
long elems = this.elems;
long start = this.start;
long ssize = this.slots == null ? 0 : this.slots.length;
double[] slots = this.slots;
if (n < 0)
throw ExceptionHandling.dieInternal(tc, "VMArray: Can't resize to negative elements");
if (n == elems)
return;
if (start > 0 && n + start > ssize) {
/* if there aren't enough slots at the end, shift off empty slots
* from the beginning first */
if (elems > 0)
memmove(slots, 0, start, elems);
this.start = 0;
/* fill out any unused slots with zeros */
while (elems < ssize) {
slots[(int)elems] = 0.0;
elems++;
}
}
else if (n < elems) {
/* we're downsizing; clear off extra slots */
while (n < elems) {
elems--;
slots[(int)(start + elems)] = 0.0;
}
}
this.elems = (int)n;
if (n <= ssize) {
/* we already have n slots available, we can just return */
return;
}
/* We need more slots. If the current slot size is less
* than 8K, use the larger of twice the current slot size
* or the actual number of elements needed. Otherwise,
* grow the slots to the next multiple of 4096 (0x1000). */
if (ssize < 8192) {
ssize *= 2;
if (n > ssize) ssize = n;
if (ssize < 8) ssize = 8;
}
else {
ssize = (n + 0x1000) & ~0xfff;
}
/* now allocate the new slot buffer */
if (slots == null) {
slots = new double[(int)ssize];
}
else {
slots = Arrays.copyOf(slots, (int)ssize);
}
this.slots = slots;
}
@Override
public void bind_pos_native(ThreadContext tc, long index) {
if (index < 0) {
index += elems;
if (index < 0)
throw ExceptionHandling.dieInternal(tc, "VMArray: Index out of bounds");
}
else if (index >= elems)
set_size_internal(tc, index + 1);
tc.native_type = ThreadContext.NATIVE_NUM;
slots[start + (int)index] = tc.native_n;
}
@Override
public long elems(ThreadContext tc) {
return elems;
}
@Override
public void set_elems(ThreadContext tc, long count) {
set_size_internal(tc, count);
}
@Override
public void push_native(ThreadContext tc) {
set_size_internal(tc, elems + 1);
tc.native_type = ThreadContext.NATIVE_NUM;
slots[start + elems - 1] = tc.native_n;
}
@Override
public void pop_native(ThreadContext tc) {
if (elems < 1)
throw ExceptionHandling.dieInternal(tc, "VMArray: Can't pop from an empty array");
elems--;
tc.native_type = ThreadContext.NATIVE_NUM;
tc.native_n = slots[start + elems];
}
@Override
public void unshift_native(ThreadContext tc) {
/* If we don't have room at the beginning of the slots,
* make some room (8 slots) for unshifting */
if (start < 1) {
int n = 8;
int i;
/* grow the array */
int origElems = elems;
set_size_internal(tc, elems + n);
/* move elements and set start */
memmove(slots, n, 0, origElems);
start = n;
elems = origElems;
/* clear out beginning elements */
for (i = 0; i < n; i++)
slots[i] = 0.0;
}
/* Now do the unshift */
start--;
tc.native_type = ThreadContext.NATIVE_NUM;
slots[start] = tc.native_n;
elems++;
}
@Override
public void shift_native(ThreadContext tc) {
if (elems < 1)
throw ExceptionHandling.dieInternal(tc, "VMArray: Can't shift from an empty array");
tc.native_type = ThreadContext.NATIVE_NUM;
tc.native_n = slots[start];
start++;
elems--;
}
@Override
public SixModelObject slice(ThreadContext tc, SixModelObject dest, long beginning, long end) {
beginning = beginning < 0 ? this.elems + beginning : beginning;
end = end < 0 ? this.elems + end : end;
if ( end < beginning || beginning < 0 || end < 0
|| this.elems <= beginning || this.elems <= end )
{
throw ExceptionHandling.dieInternal(tc, "VMArray: Slice index out of bounds");
}
long numWanted = end - beginning + 1;
if (0 < numWanted) {
for (long i = 0; i < numWanted; i++) {
this.at_pos_native(tc, beginning + i);
dest.bind_pos_native(tc, i);
}
}
return dest;
}
/* This can be optimized for the case we have two VMArray representation objects. */
@Override
public void splice(ThreadContext tc, SixModelObject from, long offset, long count) {
long elems0 = elems;
long elems1 = from.elems(tc);
long start;
long tail;
double[] slots = null;
/* start from end? */
if (offset < 0) {
offset += elems0;
if (offset < 0)
throw ExceptionHandling.dieInternal(tc, "VMArray: Illegal splice offset");
}
/* When offset == 0, then we may be able to reduce the memmove
* calls and reallocs by adjusting SELF's start, elems0, and
* count to better match the incoming splice. In particular,
* we're seeking to adjust C<count> to as close to C<elems1>
* as we can. */
if (offset == 0) {
long n = elems1 - count;
start = this.start;
if (n > start)
n = start;
if (n <= -elems0) {
elems0 = 0;
count = 0;
this.start = 0;
this.elems = (int)elems0;
}
else if (n != 0) {
elems0 += n;
count += n;
this.start = (int)(start - n);
this.elems = (int)elems0;
}
}
/* if count == 0 and elems1 == 0, there's nothing left
* to copy or remove, so the splice is done! */
if (count == 0 && elems1 == 0)
return;
/* number of elements to right of splice (the "tail") */
tail = elems0 - offset - count;
if (tail < 0)
tail = 0;
else if (tail > 0 && count > elems1) {
/* We're shrinking the array, so first move the tail left */
slots = this.slots;
start = this.start;
memmove(slots, start + offset + elems1, start + offset + count, tail);
}
/* now resize the array */
set_size_internal(tc, offset + elems1 + tail);
slots = this.slots;
start = this.start;
if (tail > 0 && count < elems1) {
/* The array grew, so move the tail to the right */
memmove(slots, start + offset + elems1, start + offset + count, tail);
}
/* now copy C<from>'s elements into SELF */
if (elems1 > 0) {
int i;
int from_pos = (int)(start + offset);
for (i = 0; i < elems1; i++) {
from.at_pos_native(tc, i);
slots[from_pos + i] = tc.native_n;
}
}
}
private void memmove(double[] slots, long dest_start, long src_start, long l_n) {
System.arraycopy(slots, (int)src_start, slots, (int)dest_start, (int)l_n);
}
public SixModelObject clone(ThreadContext tc) {
try {
VMArrayInstance_n clone = (VMArrayInstance_n)this.clone();
clone.sc = null;
if (clone.slots != null)
clone.slots = this.slots.clone();
return clone;
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
}
}
| 412 | 0.947424 | 1 | 0.947424 | game-dev | MEDIA | 0.328804 | game-dev | 0.983418 | 1 | 0.983418 |
leecrossley/cordova-plugin-game-center | 1,125 | www/gamecenter.js |
var exec = require("cordova/exec");
var GameCenter = function () {
this.name = "GameCenter";
};
GameCenter.prototype.auth = function (success, failure) {
exec(success, failure, "GameCenter", "auth", []);
};
GameCenter.prototype.getPlayerImage = function (success, failure) {
exec(success, failure, "GameCenter", "getPlayerImage", []);
};
GameCenter.prototype.submitScore = function (success, failure, data) {
exec(success, failure, "GameCenter", "submitScore", [data]);
};
GameCenter.prototype.showLeaderboard = function (success, failure, data) {
exec(success, failure, "GameCenter", "showLeaderboard", [data]);
};
GameCenter.prototype.reportAchievement = function (success, failure, data) {
exec(success, failure, "GameCenter", "reportAchievement", [data]);
};
GameCenter.prototype.resetAchievements = function (success, failure) {
exec(success, failure, "GameCenter", "resetAchievements", []);
};
GameCenter.prototype.getAchievements = function (success, failure) {
exec(success, failure, "GameCenter", "getAchievements", []);
};
module.exports = new GameCenter();
| 412 | 0.573319 | 1 | 0.573319 | game-dev | MEDIA | 0.748746 | game-dev,testing-qa | 0.692694 | 1 | 0.692694 |
UPenn-RoboCup/UPennalizers | 5,426 | Lib/Platform/NaoV4/NaoQiV5/src/actuator_process.cpp.brindza | #include "actuator_process.h"
#include "shm_util.h"
#include "albroker.h"
#include "dcmproxy.h"
#include "almemoryfastaccess.h"
#include <vector>
#include <string>
#include <unistd.h>
#include <stdlib.h>
#include <sys/time.h>
using namespace AL;
static DCMProxy *dcm;
typedef struct {
unsigned int size;
std::vector<double *> shmPtrs;
ALValue dcmCommand;
int priority;
} structCommand;
static std::vector<structCommand> commands;
static double *actuatorPtrDisable;
static double *actuatorPtrPosition;
static double *actuatorPtrCommand;
static double *actuatorPtrVelocity;
static double *actuatorPtrHardness;
int actuator_process_init(ALPtr<ALBroker> pBroker) {
ALMemoryFastAccess memoryFastAccess;
try {
dcm = new DCMProxy(pBroker);
}
catch(ALError &e) {
std::cerr << "Could not open dcm: " << e.toString() << std::endl;
return -1;
}
int ret = actuator_shm_open();
if (ret) {
std::cerr << "Could not open actuator shm" << std::endl;
return ret;
}
commands.clear();
// Setup corresponding DCM and SHM pointers
struct structActuatorKeys *actuatorKey = actuatorKeys;
while (actuatorKey->key != NULL) {
printf("Setting up actuator key: %s[%d]\n", actuatorKey->key, actuatorKey->size);
int nval = actuatorKey->size;
// Pointer in shared memory
double *pr = actuator_shm_set_ptr(actuatorKey->key, nval);
std::string key(actuatorKey->key);
// If there are corresponding DCM names, setup DCM access arrays:
if (actuatorKey->names != NULL) {
structCommand cmd;
cmd.size = nval;
cmd.shmPtrs.resize(nval);
for (int i = 0; i < nval; i++) {
cmd.shmPtrs[i] = pr + i;
}
// led and us are low priority commands
if (key.find("led") != std::string::npos) {
cmd.priority = 10;
}
else if (key.find("us") != std::string::npos) {
//cmd.priority = 20;
cmd.priority = 1000000000;
}
else {
cmd.priority = 1;
}
// Setup DCM alias:
ALValue alias;
alias.arraySetSize(2);
alias[0] = key;
alias[1].arraySetSize(nval);
for (int i = 0; i < nval; i++)
alias[1][i] = std::string(actuatorKey->names[i]);
try {
dcm->createAlias(alias);
}
catch (ALError &e) {
std::cerr << "Could not create DCM alias: " << e.toString() << std::endl;
}
// Setup DCM command values:
cmd.dcmCommand.arraySetSize(6);
cmd.dcmCommand[0] = key;
// "ClearAll" is much slower than "Merge"
// when commands are added in the future
cmd.dcmCommand[1] = "Merge";
cmd.dcmCommand[2] = "time-separate";
cmd.dcmCommand[3] = 0;
cmd.dcmCommand[4].arraySetSize(1);
cmd.dcmCommand[5].arraySetSize(nval);
for (int i = 0; i < nval; i++)
cmd.dcmCommand[5][i].arraySetSize(1);
commands.push_back(cmd);
}
actuatorKey++;
}
actuatorPtrDisable = actuator_shm_get_ptr("disable");
actuatorPtrCommand = actuator_shm_get_ptr("command");
actuatorPtrVelocity = actuator_shm_get_ptr("velocity");
actuatorPtrPosition = actuator_shm_get_ptr("position");
actuatorPtrHardness = actuator_shm_get_ptr("hardness");
printf("Number of commands arrays: %d\n", commands.size());
return 0;
}
int actuator_process() {
static unsigned int count = 0;
count++;
struct timeval tv;
gettimeofday(&tv, NULL);
// double t = tv.tv_sec + 1E-6*tv.tv_usec;
int tDcm = (unsigned int)(tv.tv_usec/1000) +
(unsigned int)(tv.tv_sec*1000);
if (*actuatorPtrDisable > 0) {
return 1;
}
for (int i = 0; i < nJoint; i++) {
double hardness = actuatorPtrHardness[i];
if (hardness <= 0) continue;
double vel = actuatorPtrVelocity[i];
if (vel > 0) {
double delta = actuatorPtrCommand[i] - actuatorPtrPosition[i];
double deltaMax = 0.010*vel;
if (delta > deltaMax) delta = deltaMax;
else if (delta < -deltaMax) delta = -deltaMax;
actuatorPtrPosition[i] += delta;
}
else {
actuatorPtrPosition[i] = actuatorPtrCommand[i];
}
}
// Copy shared memory values to DCM commands:
for (unsigned int k = 0; k < commands.size(); k++) {
structCommand &cmd = commands[k];
// Periodically skip low priority commands
if ((count % cmd.priority) != 0) continue;
cmd.dcmCommand[4][0] = tDcm;
for (unsigned int i = 0; i < cmd.size; i++) {
cmd.dcmCommand[5][i][0] = *cmd.shmPtrs[i];
}
// Send DCM command
try {
dcm->setAlias(cmd.dcmCommand);
}
catch (ALError& e) {
std::cerr << "Could not send DCM command: " << e.toString() << std::endl;
}
}
return 0;
}
int init_us() {
struct timeval tv;
gettimeofday(&tv, NULL);
// double t = tv.tv_sec + 1E-6*tv.tv_usec;
int tDcm = (unsigned int)(tv.tv_usec/1000) +
(unsigned int)(tv.tv_sec*1000);
// find us command
for (unsigned int k = 0; k < commands.size(); k++) {
structCommand &cmd = commands[k];
std::string key(cmd.dcmCommand[0]);
if (key.find("us") != std::string::npos) {
cmd.dcmCommand[4][0] = tDcm;
for (unsigned int i = 0; i < cmd.size; i++) {
cmd.dcmCommand[5][i][0] = 68;
}
// Send DCM command
try {
dcm->setAlias(cmd.dcmCommand);
}
catch (ALError& e) {
std::cerr << "Could not send DCM command: " << e.toString() << std::endl;
}
}
}
return 0;
}
int actuator_process_exit() {
actuator_shm_close();
if (dcm) delete dcm;
return 0;
}
| 412 | 0.599439 | 1 | 0.599439 | game-dev | MEDIA | 0.39278 | game-dev | 0.65756 | 1 | 0.65756 |
worleydl/uwp-dep | 16,929 | x64/include/SDL2/SDL_scancode.h | /*
Simple DirectMedia Layer
Copyright (C) 1997-2023 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
/**
* \file SDL_scancode.h
*
* Defines keyboard scancodes.
*/
#ifndef SDL_scancode_h_
#define SDL_scancode_h_
#include "SDL_stdinc.h"
/**
* \brief The SDL keyboard scancode representation.
*
* Values of this type are used to represent keyboard keys, among other places
* in the \link SDL_Keysym::scancode key.keysym.scancode \endlink field of the
* SDL_Event structure.
*
* The values in this enumeration are based on the USB usage page standard:
* https://www.usb.org/sites/default/files/documents/hut1_12v2.pdf
*/
typedef enum
{
SDL_SCANCODE_UNKNOWN = 0,
/**
* \name Usage page 0x07
*
* These values are from usage page 0x07 (USB keyboard page).
*/
/* @{ */
SDL_SCANCODE_A = 4,
SDL_SCANCODE_B = 5,
SDL_SCANCODE_C = 6,
SDL_SCANCODE_D = 7,
SDL_SCANCODE_E = 8,
SDL_SCANCODE_F = 9,
SDL_SCANCODE_G = 10,
SDL_SCANCODE_H = 11,
SDL_SCANCODE_I = 12,
SDL_SCANCODE_J = 13,
SDL_SCANCODE_K = 14,
SDL_SCANCODE_L = 15,
SDL_SCANCODE_M = 16,
SDL_SCANCODE_N = 17,
SDL_SCANCODE_O = 18,
SDL_SCANCODE_P = 19,
SDL_SCANCODE_Q = 20,
SDL_SCANCODE_R = 21,
SDL_SCANCODE_S = 22,
SDL_SCANCODE_T = 23,
SDL_SCANCODE_U = 24,
SDL_SCANCODE_V = 25,
SDL_SCANCODE_W = 26,
SDL_SCANCODE_X = 27,
SDL_SCANCODE_Y = 28,
SDL_SCANCODE_Z = 29,
SDL_SCANCODE_1 = 30,
SDL_SCANCODE_2 = 31,
SDL_SCANCODE_3 = 32,
SDL_SCANCODE_4 = 33,
SDL_SCANCODE_5 = 34,
SDL_SCANCODE_6 = 35,
SDL_SCANCODE_7 = 36,
SDL_SCANCODE_8 = 37,
SDL_SCANCODE_9 = 38,
SDL_SCANCODE_0 = 39,
SDL_SCANCODE_RETURN = 40,
SDL_SCANCODE_ESCAPE = 41,
SDL_SCANCODE_BACKSPACE = 42,
SDL_SCANCODE_TAB = 43,
SDL_SCANCODE_SPACE = 44,
SDL_SCANCODE_MINUS = 45,
SDL_SCANCODE_EQUALS = 46,
SDL_SCANCODE_LEFTBRACKET = 47,
SDL_SCANCODE_RIGHTBRACKET = 48,
SDL_SCANCODE_BACKSLASH = 49, /**< Located at the lower left of the return
* key on ISO keyboards and at the right end
* of the QWERTY row on ANSI keyboards.
* Produces REVERSE SOLIDUS (backslash) and
* VERTICAL LINE in a US layout, REVERSE
* SOLIDUS and VERTICAL LINE in a UK Mac
* layout, NUMBER SIGN and TILDE in a UK
* Windows layout, DOLLAR SIGN and POUND SIGN
* in a Swiss German layout, NUMBER SIGN and
* APOSTROPHE in a German layout, GRAVE
* ACCENT and POUND SIGN in a French Mac
* layout, and ASTERISK and MICRO SIGN in a
* French Windows layout.
*/
SDL_SCANCODE_NONUSHASH = 50, /**< ISO USB keyboards actually use this code
* instead of 49 for the same key, but all
* OSes I've seen treat the two codes
* identically. So, as an implementor, unless
* your keyboard generates both of those
* codes and your OS treats them differently,
* you should generate SDL_SCANCODE_BACKSLASH
* instead of this code. As a user, you
* should not rely on this code because SDL
* will never generate it with most (all?)
* keyboards.
*/
SDL_SCANCODE_SEMICOLON = 51,
SDL_SCANCODE_APOSTROPHE = 52,
SDL_SCANCODE_GRAVE = 53, /**< Located in the top left corner (on both ANSI
* and ISO keyboards). Produces GRAVE ACCENT and
* TILDE in a US Windows layout and in US and UK
* Mac layouts on ANSI keyboards, GRAVE ACCENT
* and NOT SIGN in a UK Windows layout, SECTION
* SIGN and PLUS-MINUS SIGN in US and UK Mac
* layouts on ISO keyboards, SECTION SIGN and
* DEGREE SIGN in a Swiss German layout (Mac:
* only on ISO keyboards), CIRCUMFLEX ACCENT and
* DEGREE SIGN in a German layout (Mac: only on
* ISO keyboards), SUPERSCRIPT TWO and TILDE in a
* French Windows layout, COMMERCIAL AT and
* NUMBER SIGN in a French Mac layout on ISO
* keyboards, and LESS-THAN SIGN and GREATER-THAN
* SIGN in a Swiss German, German, or French Mac
* layout on ANSI keyboards.
*/
SDL_SCANCODE_COMMA = 54,
SDL_SCANCODE_PERIOD = 55,
SDL_SCANCODE_SLASH = 56,
SDL_SCANCODE_CAPSLOCK = 57,
SDL_SCANCODE_F1 = 58,
SDL_SCANCODE_F2 = 59,
SDL_SCANCODE_F3 = 60,
SDL_SCANCODE_F4 = 61,
SDL_SCANCODE_F5 = 62,
SDL_SCANCODE_F6 = 63,
SDL_SCANCODE_F7 = 64,
SDL_SCANCODE_F8 = 65,
SDL_SCANCODE_F9 = 66,
SDL_SCANCODE_F10 = 67,
SDL_SCANCODE_F11 = 68,
SDL_SCANCODE_F12 = 69,
SDL_SCANCODE_PRINTSCREEN = 70,
SDL_SCANCODE_SCROLLLOCK = 71,
SDL_SCANCODE_PAUSE = 72,
SDL_SCANCODE_INSERT = 73, /**< insert on PC, help on some Mac keyboards (but
does send code 73, not 117) */
SDL_SCANCODE_HOME = 74,
SDL_SCANCODE_PAGEUP = 75,
SDL_SCANCODE_DELETE = 76,
SDL_SCANCODE_END = 77,
SDL_SCANCODE_PAGEDOWN = 78,
SDL_SCANCODE_RIGHT = 79,
SDL_SCANCODE_LEFT = 80,
SDL_SCANCODE_DOWN = 81,
SDL_SCANCODE_UP = 82,
SDL_SCANCODE_NUMLOCKCLEAR = 83, /**< num lock on PC, clear on Mac keyboards
*/
SDL_SCANCODE_KP_DIVIDE = 84,
SDL_SCANCODE_KP_MULTIPLY = 85,
SDL_SCANCODE_KP_MINUS = 86,
SDL_SCANCODE_KP_PLUS = 87,
SDL_SCANCODE_KP_ENTER = 88,
SDL_SCANCODE_KP_1 = 89,
SDL_SCANCODE_KP_2 = 90,
SDL_SCANCODE_KP_3 = 91,
SDL_SCANCODE_KP_4 = 92,
SDL_SCANCODE_KP_5 = 93,
SDL_SCANCODE_KP_6 = 94,
SDL_SCANCODE_KP_7 = 95,
SDL_SCANCODE_KP_8 = 96,
SDL_SCANCODE_KP_9 = 97,
SDL_SCANCODE_KP_0 = 98,
SDL_SCANCODE_KP_PERIOD = 99,
SDL_SCANCODE_NONUSBACKSLASH = 100, /**< This is the additional key that ISO
* keyboards have over ANSI ones,
* located between left shift and Y.
* Produces GRAVE ACCENT and TILDE in a
* US or UK Mac layout, REVERSE SOLIDUS
* (backslash) and VERTICAL LINE in a
* US or UK Windows layout, and
* LESS-THAN SIGN and GREATER-THAN SIGN
* in a Swiss German, German, or French
* layout. */
SDL_SCANCODE_APPLICATION = 101, /**< windows contextual menu, compose */
SDL_SCANCODE_POWER = 102, /**< The USB document says this is a status flag,
* not a physical key - but some Mac keyboards
* do have a power key. */
SDL_SCANCODE_KP_EQUALS = 103,
SDL_SCANCODE_F13 = 104,
SDL_SCANCODE_F14 = 105,
SDL_SCANCODE_F15 = 106,
SDL_SCANCODE_F16 = 107,
SDL_SCANCODE_F17 = 108,
SDL_SCANCODE_F18 = 109,
SDL_SCANCODE_F19 = 110,
SDL_SCANCODE_F20 = 111,
SDL_SCANCODE_F21 = 112,
SDL_SCANCODE_F22 = 113,
SDL_SCANCODE_F23 = 114,
SDL_SCANCODE_F24 = 115,
SDL_SCANCODE_EXECUTE = 116,
SDL_SCANCODE_HELP = 117, /**< AL Integrated Help Center */
SDL_SCANCODE_MENU = 118, /**< Menu (show menu) */
SDL_SCANCODE_SELECT = 119,
SDL_SCANCODE_STOP = 120, /**< AC Stop */
SDL_SCANCODE_AGAIN = 121, /**< AC Redo/Repeat */
SDL_SCANCODE_UNDO = 122, /**< AC Undo */
SDL_SCANCODE_CUT = 123, /**< AC Cut */
SDL_SCANCODE_COPY = 124, /**< AC Copy */
SDL_SCANCODE_PASTE = 125, /**< AC Paste */
SDL_SCANCODE_FIND = 126, /**< AC Find */
SDL_SCANCODE_MUTE = 127,
SDL_SCANCODE_VOLUMEUP = 128,
SDL_SCANCODE_VOLUMEDOWN = 129,
/* not sure whether there's a reason to enable these */
/* SDL_SCANCODE_LOCKINGCAPSLOCK = 130, */
/* SDL_SCANCODE_LOCKINGNUMLOCK = 131, */
/* SDL_SCANCODE_LOCKINGSCROLLLOCK = 132, */
SDL_SCANCODE_KP_COMMA = 133,
SDL_SCANCODE_KP_EQUALSAS400 = 134,
SDL_SCANCODE_INTERNATIONAL1 = 135, /**< used on Asian keyboards, see
footnotes in USB doc */
SDL_SCANCODE_INTERNATIONAL2 = 136,
SDL_SCANCODE_INTERNATIONAL3 = 137, /**< Yen */
SDL_SCANCODE_INTERNATIONAL4 = 138,
SDL_SCANCODE_INTERNATIONAL5 = 139,
SDL_SCANCODE_INTERNATIONAL6 = 140,
SDL_SCANCODE_INTERNATIONAL7 = 141,
SDL_SCANCODE_INTERNATIONAL8 = 142,
SDL_SCANCODE_INTERNATIONAL9 = 143,
SDL_SCANCODE_LANG1 = 144, /**< Hangul/English toggle */
SDL_SCANCODE_LANG2 = 145, /**< Hanja conversion */
SDL_SCANCODE_LANG3 = 146, /**< Katakana */
SDL_SCANCODE_LANG4 = 147, /**< Hiragana */
SDL_SCANCODE_LANG5 = 148, /**< Zenkaku/Hankaku */
SDL_SCANCODE_LANG6 = 149, /**< reserved */
SDL_SCANCODE_LANG7 = 150, /**< reserved */
SDL_SCANCODE_LANG8 = 151, /**< reserved */
SDL_SCANCODE_LANG9 = 152, /**< reserved */
SDL_SCANCODE_ALTERASE = 153, /**< Erase-Eaze */
SDL_SCANCODE_SYSREQ = 154,
SDL_SCANCODE_CANCEL = 155, /**< AC Cancel */
SDL_SCANCODE_CLEAR = 156,
SDL_SCANCODE_PRIOR = 157,
SDL_SCANCODE_RETURN2 = 158,
SDL_SCANCODE_SEPARATOR = 159,
SDL_SCANCODE_OUT = 160,
SDL_SCANCODE_OPER = 161,
SDL_SCANCODE_CLEARAGAIN = 162,
SDL_SCANCODE_CRSEL = 163,
SDL_SCANCODE_EXSEL = 164,
SDL_SCANCODE_KP_00 = 176,
SDL_SCANCODE_KP_000 = 177,
SDL_SCANCODE_THOUSANDSSEPARATOR = 178,
SDL_SCANCODE_DECIMALSEPARATOR = 179,
SDL_SCANCODE_CURRENCYUNIT = 180,
SDL_SCANCODE_CURRENCYSUBUNIT = 181,
SDL_SCANCODE_KP_LEFTPAREN = 182,
SDL_SCANCODE_KP_RIGHTPAREN = 183,
SDL_SCANCODE_KP_LEFTBRACE = 184,
SDL_SCANCODE_KP_RIGHTBRACE = 185,
SDL_SCANCODE_KP_TAB = 186,
SDL_SCANCODE_KP_BACKSPACE = 187,
SDL_SCANCODE_KP_A = 188,
SDL_SCANCODE_KP_B = 189,
SDL_SCANCODE_KP_C = 190,
SDL_SCANCODE_KP_D = 191,
SDL_SCANCODE_KP_E = 192,
SDL_SCANCODE_KP_F = 193,
SDL_SCANCODE_KP_XOR = 194,
SDL_SCANCODE_KP_POWER = 195,
SDL_SCANCODE_KP_PERCENT = 196,
SDL_SCANCODE_KP_LESS = 197,
SDL_SCANCODE_KP_GREATER = 198,
SDL_SCANCODE_KP_AMPERSAND = 199,
SDL_SCANCODE_KP_DBLAMPERSAND = 200,
SDL_SCANCODE_KP_VERTICALBAR = 201,
SDL_SCANCODE_KP_DBLVERTICALBAR = 202,
SDL_SCANCODE_KP_COLON = 203,
SDL_SCANCODE_KP_HASH = 204,
SDL_SCANCODE_KP_SPACE = 205,
SDL_SCANCODE_KP_AT = 206,
SDL_SCANCODE_KP_EXCLAM = 207,
SDL_SCANCODE_KP_MEMSTORE = 208,
SDL_SCANCODE_KP_MEMRECALL = 209,
SDL_SCANCODE_KP_MEMCLEAR = 210,
SDL_SCANCODE_KP_MEMADD = 211,
SDL_SCANCODE_KP_MEMSUBTRACT = 212,
SDL_SCANCODE_KP_MEMMULTIPLY = 213,
SDL_SCANCODE_KP_MEMDIVIDE = 214,
SDL_SCANCODE_KP_PLUSMINUS = 215,
SDL_SCANCODE_KP_CLEAR = 216,
SDL_SCANCODE_KP_CLEARENTRY = 217,
SDL_SCANCODE_KP_BINARY = 218,
SDL_SCANCODE_KP_OCTAL = 219,
SDL_SCANCODE_KP_DECIMAL = 220,
SDL_SCANCODE_KP_HEXADECIMAL = 221,
SDL_SCANCODE_LCTRL = 224,
SDL_SCANCODE_LSHIFT = 225,
SDL_SCANCODE_LALT = 226, /**< alt, option */
SDL_SCANCODE_LGUI = 227, /**< windows, command (apple), meta */
SDL_SCANCODE_RCTRL = 228,
SDL_SCANCODE_RSHIFT = 229,
SDL_SCANCODE_RALT = 230, /**< alt gr, option */
SDL_SCANCODE_RGUI = 231, /**< windows, command (apple), meta */
SDL_SCANCODE_MODE = 257, /**< I'm not sure if this is really not covered
* by any of the above, but since there's a
* special KMOD_MODE for it I'm adding it here
*/
/* @} *//* Usage page 0x07 */
/**
* \name Usage page 0x0C
*
* These values are mapped from usage page 0x0C (USB consumer page).
* See https://usb.org/sites/default/files/hut1_2.pdf
*
* There are way more keys in the spec than we can represent in the
* current scancode range, so pick the ones that commonly come up in
* real world usage.
*/
/* @{ */
SDL_SCANCODE_AUDIONEXT = 258,
SDL_SCANCODE_AUDIOPREV = 259,
SDL_SCANCODE_AUDIOSTOP = 260,
SDL_SCANCODE_AUDIOPLAY = 261,
SDL_SCANCODE_AUDIOMUTE = 262,
SDL_SCANCODE_MEDIASELECT = 263,
SDL_SCANCODE_WWW = 264, /**< AL Internet Browser */
SDL_SCANCODE_MAIL = 265,
SDL_SCANCODE_CALCULATOR = 266, /**< AL Calculator */
SDL_SCANCODE_COMPUTER = 267,
SDL_SCANCODE_AC_SEARCH = 268, /**< AC Search */
SDL_SCANCODE_AC_HOME = 269, /**< AC Home */
SDL_SCANCODE_AC_BACK = 270, /**< AC Back */
SDL_SCANCODE_AC_FORWARD = 271, /**< AC Forward */
SDL_SCANCODE_AC_STOP = 272, /**< AC Stop */
SDL_SCANCODE_AC_REFRESH = 273, /**< AC Refresh */
SDL_SCANCODE_AC_BOOKMARKS = 274, /**< AC Bookmarks */
/* @} *//* Usage page 0x0C */
/**
* \name Walther keys
*
* These are values that Christian Walther added (for mac keyboard?).
*/
/* @{ */
SDL_SCANCODE_BRIGHTNESSDOWN = 275,
SDL_SCANCODE_BRIGHTNESSUP = 276,
SDL_SCANCODE_DISPLAYSWITCH = 277, /**< display mirroring/dual display
switch, video mode switch */
SDL_SCANCODE_KBDILLUMTOGGLE = 278,
SDL_SCANCODE_KBDILLUMDOWN = 279,
SDL_SCANCODE_KBDILLUMUP = 280,
SDL_SCANCODE_EJECT = 281,
SDL_SCANCODE_SLEEP = 282, /**< SC System Sleep */
SDL_SCANCODE_APP1 = 283,
SDL_SCANCODE_APP2 = 284,
/* @} *//* Walther keys */
/**
* \name Usage page 0x0C (additional media keys)
*
* These values are mapped from usage page 0x0C (USB consumer page).
*/
/* @{ */
SDL_SCANCODE_AUDIOREWIND = 285,
SDL_SCANCODE_AUDIOFASTFORWARD = 286,
/* @} *//* Usage page 0x0C (additional media keys) */
/**
* \name Mobile keys
*
* These are values that are often used on mobile phones.
*/
/* @{ */
SDL_SCANCODE_SOFTLEFT = 287, /**< Usually situated below the display on phones and
used as a multi-function feature key for selecting
a software defined function shown on the bottom left
of the display. */
SDL_SCANCODE_SOFTRIGHT = 288, /**< Usually situated below the display on phones and
used as a multi-function feature key for selecting
a software defined function shown on the bottom right
of the display. */
SDL_SCANCODE_CALL = 289, /**< Used for accepting phone calls. */
SDL_SCANCODE_ENDCALL = 290, /**< Used for rejecting phone calls. */
/* @} *//* Mobile keys */
/* Add any other keys here. */
SDL_NUM_SCANCODES = 512 /**< not a key, just marks the number of scancodes
for array bounds */
} SDL_Scancode;
#endif /* SDL_scancode_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| 412 | 0.777221 | 1 | 0.777221 | game-dev | MEDIA | 0.448114 | game-dev | 0.577799 | 1 | 0.577799 |
Minestom/VanillaReimplementation | 6,511 | commands/src/main/java/net/minestom/vanilla/commands/ForceloadCommand.java | package net.minestom.vanilla.commands;
import net.minestom.server.command.CommandSender;
import net.minestom.server.command.builder.Command;
import net.minestom.server.command.builder.CommandContext;
import net.minestom.server.command.builder.arguments.ArgumentType;
import net.minestom.server.coordinate.CoordConversion;
import net.minestom.server.coordinate.Vec;
import net.minestom.server.entity.Player;
import net.minestom.server.instance.Instance;
import net.minestom.server.utils.location.RelativeVec;
import net.minestom.vanilla.instancemeta.tickets.TicketManager;
import net.minestom.vanilla.instancemeta.tickets.TicketUtils;
import java.util.List;
/**
* "forceload":
* Description: "Forces chunks to constantly be loaded or not. "
* BE: false
* EE: false
* JE: true
* OP_Level: 2
* BE_EE_OP_Level: 0
* MP_Only: false
*/
public class ForceloadCommand extends Command {
public ForceloadCommand() {
super("forceload");
// forceload add <from> [<to>]
// Forces the chunk at the <from> position (through to <to> if set) in the dimension of the command's execution to be loaded constantly.
this.addSyntax(
this::usageAddFrom,
ArgumentType.Literal("add"),
ArgumentType.RelativeVec2("from")
);
this.addSyntax(
this::usageAddFromTo,
ArgumentType.Literal("add"),
ArgumentType.RelativeVec2("from"),
ArgumentType.RelativeVec2("to")
);
// forceload remove <from> [<to>]
// Unforces the chunk at the <from> position (through to <to> if set) in the dimension of the command's execution to be loaded constantly.
this.addSyntax(
this::usageRemoveFrom,
ArgumentType.Literal("remove"),
ArgumentType.RelativeVec2("from")
);
this.addSyntax(
this::usageRemoveFromTo,
ArgumentType.Literal("remove"),
ArgumentType.RelativeVec2("from"),
ArgumentType.RelativeVec2("to")
);
}
private void addForceLoad(Instance instance, int chunkX, int chunkZ) {
addForceLoad(instance, CoordConversion.chunkIndex(chunkX, chunkZ));
}
private void addForceLoad(Instance instance, long chunkIndex) {
TicketManager.Ticket ticketToAdd = TicketManager.Ticket.from(TicketManager.FORCED_TICKET, chunkIndex);
TicketUtils.waitingTickets(instance, List.of(ticketToAdd));
}
private void removeForceLoad(Instance instance, int chunkX, int chunkZ) {
removeForceLoad(instance, CoordConversion.chunkIndex(chunkX, chunkZ));
}
private void removeForceLoad(Instance instance, long chunkIndex) {
TicketManager.Ticket ticketToRemove = TicketManager.Ticket.from(TicketManager.FORCED_TICKET, chunkIndex);
TicketUtils.removingTickets(instance, List.of(ticketToRemove));
}
private void usageAddFrom(CommandSender sender, CommandContext context) {
if (!(sender instanceof Player player)) {
sender.sendMessage("This command must be executed by a player!");
return;
}
RelativeVec fromVec = context.get("from");
Vec position = fromVec.from(player.getPosition());
// Get chunk position
int chunkX = CoordConversion.globalToChunk(position.x());
int chunkZ = CoordConversion.globalToChunk(position.z());
// Add the force load
Instance instance = player.getInstance();
addForceLoad(instance, chunkX, chunkZ);
}
private void usageAddFromTo(CommandSender sender, CommandContext context) {
if (!(sender instanceof Player player)) {
sender.sendMessage("This command must be executed by a player!");
return;
}
RelativeVec fromVec = context.get("from");
RelativeVec toVec = context.get("to");
Vec from = fromVec.from(player.getPosition());
Vec to = toVec.from(player.getPosition());
int startX = Math.min(from.blockX(), to.blockX());
int endX = Math.max(from.blockX(), to.blockX());
int startZ = Math.min(from.blockZ(), to.blockZ());
int endZ = Math.max(from.blockZ(), to.blockZ());
Instance instance = player.getInstance();
for (int offX = startX; offX < endX; offX += 16) {
for (int offZ = startZ; offZ < endZ; offZ += 16) {
// Get chunk position
int chunkX = CoordConversion.globalToChunk(offX);
int chunkZ = CoordConversion.globalToChunk(offZ);
removeForceLoad(instance, chunkX, chunkZ);
}
}
}
private void usageRemoveFrom(CommandSender sender, CommandContext context) {
if (!(sender instanceof Player player)) {
sender.sendMessage("This command must be executed by a player!");
return;
}
RelativeVec fromVec = context.get("from");
Vec position = fromVec.from(player.getPosition());
// Get chunk position
int chunkX = CoordConversion.globalToChunk(position.x());
int chunkZ = CoordConversion.globalToChunk(position.z());
// Remove force load
Instance instance = player.getInstance();
removeForceLoad(instance, chunkX, chunkZ);
}
private void usageRemoveFromTo(CommandSender sender, CommandContext context) {
if (!(sender instanceof Player player)) {
sender.sendMessage("This command must be executed by a player!");
return;
}
RelativeVec fromVec = context.get("from");
RelativeVec toVec = context.get("to");
Vec from = fromVec.from(player.getPosition());
Vec to = toVec.from(player.getPosition());
int minX = Math.min(from.blockX(), to.blockX());
int maxX = Math.max(from.blockX(), to.blockX());
int minZ = Math.min(from.blockZ(), to.blockZ());
int maxZ = Math.max(from.blockZ(), to.blockZ());
Instance instance = player.getInstance();
for (int offX = minX; offX <= maxX; offX += 16) {
for (int offZ = minZ; offZ <= maxZ; offZ += 16) {
// Get chunk position
int chunkX = CoordConversion.globalToChunk(offX);
int chunkZ = CoordConversion.globalToChunk(offZ);
// Remove the force load
removeForceLoad(instance, chunkX, chunkZ);
}
}
}
}
| 412 | 0.792457 | 1 | 0.792457 | game-dev | MEDIA | 0.857157 | game-dev | 0.942828 | 1 | 0.942828 |
johnnemann/museum-of-mechanics-lockpicking | 11,208 | Open Museum/Assets/Scripts/HillsfarLockpickGame.cs | using DG.Tweening;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
//A note:
//The non-open-source version of the Museum uses a Unity Asset Store package called "InControl" to handle controller and MKB input
//It's a good package, I think it's worth a purchase. Obviously, though, I cannot distribute that code as part of this
//release. So the input code here has been modified to use only Unity, and as a consequence may only support MKB controls, depending on game
//This also means input handling may be slightly worse than the other version of the game
//A shape is a simple thing that has an ID (for easy comparison) and a sprite for the visual representation. A single pick has two shapes.
[System.Serializable]
public class Shape
{
public Sprite sprite;
public int id;
}
//Hillsfar's game is a matching game - the player has to find the pick that matches the negative space of each tumbler in the lock
//To complicate matters, each pick has two ends, one of which is upside down. AND, there's a timer. So finding the right matches for
//three tumblers in a row can be challenging
public class HillsfarLockpickGame : LockpickGame
{
Player thePlayer;
//An index 0-9, but depending on the value of the corresponding flipped value
int selectedLockpickPair = 0;
//The tumbler the player is working on
int currentTumbler;
//Whether the current lockpick is flipped or not
bool flipped;
//A set of tumbler IDs
int[] tumblers = new int[3];
//UI Stuff
public GameObject Panel;
//This is the number of different types of lockpick/tumbler there are. Hillsfar seems to have ten pairs, so twenty total.
public int variationCount = 20;
//The amount of time the player has to complete the entire lockpicking. Hillsfar is VERY agressive with this, we may want to be a little softer
public float PickTimer = 20f;
float CurrentPickTimer;
bool inFailureState;
//Add the starting positions of the tumblers here - the most foolproof way of making sure they start where they should
public Vector3[] TumblerStartingPositions;
//Sprites for tumblers and lockpicks (20 tumblers, 10 lockpicks)
public List<Shape> tumblerSprites;
public List<Shape> pickSprites;
//Image for current active lockpick, up near the lock
public Image activeLockpickA;
public Image activeLockpickB;
//Gameobjects for the lockpick
public GameObject[] LockpickObjects;
//Images for lockpick choosing menu - one for each pick end
public Image[] lockpicks;
//Images for selector under each lockpick
public Image[] selectors;
//The set of three images that we will put sprites on when we generate the puzzle
public Image[] tumblerImages;
//For the timer fuse
public Image FuseImage;
//The panel we display on failure
public GameObject FailurePanel;
public override void BeginLockpicking(Player player)
{
Panel.SetActive(true);
thePlayer = player;
thePlayer.FreezePlayer();
ResetTumblerPositions();
CurrentPickTimer = PickTimer;
inFailureState = false;
currentTumbler = 0;
SetupInitialUI();
}
void SetupInitialUI()
{
selectedLockpickPair = 0;
//randomize tumblers and set up the images and object IDs
List<Shape> shuffledTumblers = ShuffleShapeList(tumblerSprites);
for (int i = 0; i < tumblerImages.Length; i++)
{
tumblerImages[i].sprite = shuffledTumblers[i].sprite;
tumblers[i] = shuffledTumblers[i].id;
}
//randomize picks
List<Shape> shuffledPicks = ShuffleShapeList(pickSprites);
//This is interesting because we can have a mismatch here - we have 19 pick images but 20 slots to fill! So we need to redo one, and it's easiest to just redo the first
//(although this code redoes the first N < double, but for us N should be 1)
for (int i = 0; i < lockpicks.Length; i++)
{
if (i < shuffledPicks.Count)
{
lockpicks[i].sprite = shuffledPicks[i].sprite;
lockpicks[i].GetComponent<HillsfarPick>().shape = shuffledPicks[i];
}
else
{
lockpicks[i].sprite = shuffledPicks[i - shuffledPicks.Count].sprite;
lockpicks[i].GetComponent<HillsfarPick>().shape = shuffledPicks[i - shuffledPicks.Count];
}
}
//disable selectors except for the first
for (int i = 1; i < selectors.Length; i++)
{
selectors[i].gameObject.SetActive(false);
}
UpdateActiveLockpick();
}
public override void OnFailure()
{
//Display failure dialog
FailurePanel.SetActive(true);
inFailureState = true;
}
public override void OnSuccess()
{
OpenLock();
EndLockpicking();
}
//This is what actually ends the game if the player fails
public void AfterFailure()
{
FailurePanel.SetActive(false);
ResetTumblerPositions();
EndLockpicking();
}
public override void EndLockpicking()
{
Panel.SetActive(false);
thePlayer.UnfreezePlayer();
}
void Update()
{
//Get input and respond accordingly
if (Input.GetKeyUp(KeyCode.Escape))
{
EndLockpicking();
}
//Don't need to do anything else in here if we're waiting on the player to acknowledge their abject failure
if (inFailureState)
{
if (Input.GetKeyDown(KeyCode.Space))
{
AfterFailure();
}
return;
}
//"Flipping" changes which end of the current lockpick is active
if (Input.GetKeyDown(KeyCode.F))
{
FlipSelectedLockpick();
}
//"Picking" tests the current active pick and end against the current tumbler
if (Input.GetKeyDown(KeyCode.Space))
{
Pick();
}
//The player selects from lockpicks by navigating a grid of all available lockpicks - they can move up, down, left, or right to go through the grid
//movement should move up, down, left, right from current slot, not wrapping at edges
//Hillsfar has two rows of four and a row of two, which seems annoying. I think we'll do two rows of five
if (Input.GetKeyDown(KeyCode.LeftArrow) || Input.GetKeyDown(KeyCode.A))
{
if (selectedLockpickPair != 0 && selectedLockpickPair != 5)
{
SetSelectedLockpickPair(selectedLockpickPair - 1);
}
}
if (Input.GetKeyDown(KeyCode.RightArrow) || Input.GetKeyDown(KeyCode.D))
{
if (selectedLockpickPair != 9 && selectedLockpickPair != 4)
{
SetSelectedLockpickPair(selectedLockpickPair + 1);
}
}
if (Input.GetKeyDown(KeyCode.UpArrow) || Input.GetKeyDown(KeyCode.W))
{
if (selectedLockpickPair > 4)
{
SetSelectedLockpickPair(selectedLockpickPair - 5);
}
}
if (Input.GetKeyDown(KeyCode.DownArrow) || Input.GetKeyDown(KeyCode.S))
{
if (selectedLockpickPair <= 4)
{
SetSelectedLockpickPair(selectedLockpickPair + 5);
}
}
//update timer and check if we've failed due to time limit
CurrentPickTimer -= Time.deltaTime;
if (CurrentPickTimer <= 0)
{
//Failure!
OnFailure();
}
else
{
float percentage = CurrentPickTimer / PickTimer;
FuseImage.fillAmount = percentage;
}
}
void Pick()
{
//Test selected lockpick against current tumbler
if (lockpicks[GetCurrentLockpickIndex()].GetComponent<HillsfarPick>().shape.id == tumblers[currentTumbler])
{
//Animate the tumbler
tumblerImages[currentTumbler].transform.DOLocalMoveY(transform.localPosition.y - 160, 0.5f);
//A success. Move on to the next tumbler, or, if we've reached the end, unlock the lock.
currentTumbler += 1;
if (currentTumbler >= tumblerImages.Length)
{
ResetTumblerPositions();
OnSuccess();
}
}
else
{
OnFailure();
//A failure!
}
}
//Go through all the tumblers and reset them to the top for a new game
void ResetTumblerPositions()
{
for (int i = 0; i < tumblerImages.Length; i++)
{
DOTween.CompleteAll();
//Reset the tumbler positions
tumblerImages[i].transform.localPosition = TumblerStartingPositions[i];
}
}
int GetCurrentLockpickIndex()
{
//The index of the lockpick pair should be 0-9, but the corresponding tumbler/pick sprites are actually (index * 2) and (index * 2) + 1
return selectedLockpickPair * 2 + (flipped ? 1 : 0);
}
void SetSelectedLockpickPair(int index)
{
flipped = false;
//Lockpick Pairs are a set of two lockpicks that can be flipped to access the other one.
//Set the arrow selector to visible on the selected lockpick
selectors[selectedLockpickPair].gameObject.SetActive(false);
selectors[index].gameObject.SetActive(true);
//Set index
selectedLockpickPair = index;
//Set current lockpick sprite to our sprite (correctly flipped)
UpdateActiveLockpick();
}
//This updates the visual state of the active lockpick, which is shown larger, up near the lock
private void UpdateActiveLockpick()
{
//We want the current TWO indices for the lockpicks - we need to set both ends of the lockpick
int pickA = GetCurrentLockpickIndex();
int pickB = selectedLockpickPair * 2 + (flipped ? 0 : 1);
//There might be a better way to do this, if we shuffled the list in-place we could use the index instead of grabbing the sprite from the lockpick?
activeLockpickA.sprite = lockpicks[pickA].sprite;
activeLockpickB.sprite = lockpicks[pickB].sprite;
}
//This just sets our flipped flag and re-does the visuals to indicate that it's turned around
void FlipSelectedLockpick()
{
flipped = !flipped;
UpdateActiveLockpick();
}
//A function to shuffle the shapes to get random ones - it just goes through and swaps each element for another random one in the list
List<Shape> ShuffleShapeList(List<Shape> list)
{
List<Shape> ShuffledList = list;
for (int i = 0; i < ShuffledList.Count; i++)
{
Shape temp = ShuffledList[i];
int randomIndex = Random.Range(i, ShuffledList.Count);
ShuffledList[i] = ShuffledList[randomIndex];
ShuffledList[randomIndex] = temp;
}
return ShuffledList;
}
public override string GetFriendlyName()
{
return "Hillsfar";
}
}
| 412 | 0.908061 | 1 | 0.908061 | game-dev | MEDIA | 0.638818 | game-dev | 0.942377 | 1 | 0.942377 |
Sduibek/fixtsrc | 8,537 | SCRIPTS/SENTRY.SSL | procedure start; variable SrcObj := 0; variable SrcIsParty := 0;
procedure look_at_p_proc;// script_action == 21
procedure damage_p_proc;// script_action == 14
procedure pickup_p_proc;// script_action == 4
procedure talk_p_proc;// script_action == 11
procedure critter_p_proc;// script_action == 12
procedure destroy_p_proc;// script_action == 18
procedure node01;
procedure node02;
procedure node03;
procedure node04;
procedure node05;
procedure node06;
procedure node07;
procedure node08;
procedure node09;
procedure node11;
procedure node12;
procedure node_exit;
variable initialized := 0;
variable hostile;
variable weaponPtr;
procedure start
begin
if local_var(12) != 1 then begin// Fallout Fixt lvar12 - this code block heals critter to full HP one time (first time player enters the map) to make sure they always start with full HP.
if metarule(14, 0) then begin// Fallout Fixt lvar12 - first visit to map?
if metarule(22, 0) == 0 then begin// Fallout Fixt lvar12 - Not currently loading a save?
if get_critter_stat(self_obj, 7) > 0 then begin critter_heal(self_obj, 999); end// if obj_is_carrying_obj_pid(self_obj, 46) > 0 then begin display_msg("S-bag " + proto_data(obj_pid(self_obj), 1)); end if obj_is_carrying_obj_pid(self_obj, 90) > 0 then begin display_msg("Pack " + proto_data(obj_pid(self_obj), 1)); end if obj_is_carrying_obj_pid(self_obj, 93) > 0 then begin display_msg("M-bag " + proto_data(obj_pid(self_obj), 1)); end
if global_var(330) then begin if critter_inven_obj(self_obj, 0) <= 0 then begin// Equip held armor if not currently wearing any.
variable A; if obj_carrying_pid_obj(self_obj, 17) then begin debug_msg("Fallout Fixt - Warning: CRITTER " + obj_pid(self_obj) + " HAD ARMOR BUT EMPTY ARMOR SLOT. EQUIPPING COMBAT ARMOR..."); A := obj_carrying_pid_obj(self_obj, 17); rm_obj_from_inven(self_obj, A); add_obj_to_inven(self_obj, A); wield_obj_critter(self_obj, A); end else begin if obj_carrying_pid_obj(self_obj, 2) then begin debug_msg("Fallout Fixt - Warning: CRITTER " + obj_pid(self_obj) + " HAD ARMOR BUT EMPTY ARMOR SLOT. EQUIPPING METAL ARMOR..."); A := obj_carrying_pid_obj(self_obj, 2); rm_obj_from_inven(self_obj, A); add_obj_to_inven(self_obj, A); wield_obj_critter(self_obj, A); end else begin if obj_carrying_pid_obj(self_obj, 1) then begin debug_msg("Fallout Fixt - Warning: CRITTER " + obj_pid(self_obj) + " HAD ARMOR BUT EMPTY ARMOR SLOT. EQUIPPING LEATHER ARMOR..."); A := obj_carrying_pid_obj(self_obj, 1); rm_obj_from_inven(self_obj, A); add_obj_to_inven(self_obj, A); wield_obj_critter(self_obj, A); end else begin if obj_carrying_pid_obj(self_obj, 74) then begin debug_msg("Fallout Fixt - Warning: CRITTER " + obj_pid(self_obj) + " HAD ARMOR BUT EMPTY ARMOR SLOT. EQUIPPING LEATHER JACKET..."); A := obj_carrying_pid_obj(self_obj, 74); rm_obj_from_inven(self_obj, A); add_obj_to_inven(self_obj, A); wield_obj_critter(self_obj, A); end else begin if obj_carrying_pid_obj(self_obj, 113) then begin debug_msg("Fallout Fixt - Warning: CRITTER " + obj_pid(self_obj) + " HAD ARMOR BUT EMPTY ARMOR SLOT. EQUIPPING ROBES..."); A := obj_carrying_pid_obj(self_obj, 113); rm_obj_from_inven(self_obj, A); add_obj_to_inven(self_obj, A); wield_obj_critter(self_obj, A); end end end end end end end
set_local_var(12, 1);
end
end
end
if not(initialized) then begin
/* TEAM_NUM */ critter_add_trait(self_obj, 1, 6, 44);
/* AI_PACKET */ critter_add_trait(self_obj, 1, 5, 65);
anim(self_obj, 1000, 2);
if (local_var(0) == 0) then begin
set_local_var(0, 1);
weaponPtr := create_object_sid(28, 0, 0, -1);
add_obj_to_inven(self_obj, weaponPtr);
wield_obj_critter(self_obj, weaponPtr);
add_obj_to_inven(self_obj, create_object_sid(39, 0, 0, -1));
end
initialized := 1;
end
if (script_action == 21) then begin//MOUSE-OVER DESCRIPTION -- look_at_p_proc - (usually brief length. hovered mouse over object, haven't clicked on it.)
call look_at_p_proc;
end
else begin
if (script_action == 14) then begin//<-- damage_p_proc - has this Critter or Object been shot, hit with TNT, punched, etc.
call damage_p_proc;
end
else begin
if (script_action == 4) then begin//<---caught stealing! (pickup_p_proc)
call pickup_p_proc;
end
else begin
if (script_action == 11) then begin//<--- talk_p_proc (Face icon), can also call "do_dialogue" or "do_dialog"
call talk_p_proc;
end
else begin
if (script_action == 12) then begin//<-- critter_p_proc - (can also be "Critter_Action") - do they see you, should they wander, should they attack you, etc..
call critter_p_proc;
end
else begin
if (script_action == 18) then begin//destroy_p_proc - Object or Critter has been killed or otherwise eradicated. Fall down go boom.
call destroy_p_proc;
end
end
end
end
end
end
end
procedure look_at_p_proc
begin
script_overrides;
display_msg(message_str(324, 100));
end
procedure damage_p_proc
begin
end
procedure pickup_p_proc
begin
if source_obj > 0 then begin SrcObj := 0; SrcIsParty := 0; SrcObj := obj_pid(source_obj); if party_member_obj(SrcObj) then begin SrcIsParty := 1; end end if (source_obj == dude_obj) or (SrcIsParty == 1) then begin
hostile := 1;
end
end
procedure talk_p_proc
begin
anim(dude_obj, 1000, rotation_to_tile(tile_num(dude_obj), tile_num(self_obj)));
if (local_var(1) == 0) then begin
set_local_var(1, 1);
start_gdialog(324, self_obj, 4, -1, -1);
gsay_start;
if (global_var(108) != 2) then begin
call node01;
end
else begin
call node09;
end
gsay_end;
end_dialogue;
end
else begin
display_msg(message_str(324, 150));
end
end
procedure critter_p_proc
begin
if (hostile) then begin// This must come FIRST as an if/then/else before "attack dude" type code, otherwise it runs too soon and can override other attack calls
hostile := 0;
attack_complex(dude_obj, 0, 1, 0, 0, 30000, 0, 0);
end
end
procedure destroy_p_proc
begin
if source_obj > 0 then begin SrcObj := 0; SrcIsParty := 0; SrcObj := obj_pid(source_obj); if party_member_obj(SrcObj) then begin SrcIsParty := 1; end end if (source_obj == dude_obj) or (SrcIsParty == 1) then begin
if (((global_var(160) + global_var(159)) >= 25) and ((global_var(159) > (2 * global_var(160))) or (global_var(317) == 1))) then begin
set_global_var(317, 1);
set_global_var(157, 0);
end
if (((global_var(160) + global_var(159)) >= 25) and ((global_var(160) > (3 * global_var(159))) or (global_var(157) == 1))) then begin
set_global_var(157, 1);
set_global_var(317, 0);
end
set_global_var(159, global_var(159) + 1);// THIS MONSTER WAS A GOOD GUY. INCREASE GoodGuysKilled COUNTER
if ((global_var(159) % 2) == 0) then begin
set_global_var(155, (global_var(155) - 1));
end
end
end
procedure node01
begin
gsay_reply(324, 101);
giq_option(-3, 324, message_str(324, 102) + proto_data(obj_pid(dude_obj), 1) + message_str(324, 103), node02, 50);
giq_option(4, 324, message_str(324, 104) + proto_data(obj_pid(dude_obj), 1) + message_str(324, 105), node04, 50);
giq_option(4, 324, 106, node12, 50);
end
procedure node02
begin
gsay_reply(324, message_str(324, 107) + proto_data(obj_pid(dude_obj), 1) + message_str(324, 108));
giq_option(-3, 324, 109, node03, 50);
end
procedure node03
begin
gsay_reply(324, 110);
giq_option(-3, 324, 111, node_exit, 50);
end
procedure node04
begin
gsay_reply(324, 112);
giq_option(4, 324, 113, node05, 50);
end
procedure node05
begin
gsay_reply(324, 114);
giq_option(4, 324, 115, node06, 50);
giq_option(4, 324, 116, node07, 50);
end
procedure node06
begin
gsay_reply(324, 117);
giq_option(4, 324, 118, node_exit, 50);
giq_option(4, 324, 119, node07, 50);
end
procedure node07
begin
gsay_reply(324, 120);
if (global_var(108) != 2) then begin
giq_option(4, 324, 121, node08, 50);
end
else begin
giq_option(4, 324, 121, node11, 50);
end
end
procedure node08
begin
gsay_message(324, message_str(324, 122) + proto_data(obj_pid(dude_obj), 1) + message_str(324, 123), 50);
end
procedure node09
begin
gsay_reply(324, message_str(324, 124) + proto_data(obj_pid(dude_obj), 1) + message_str(324, 125));
giq_option(-3, 324, 126, node02, 50);
giq_option(4, 324, 127, node04, 50);
end
procedure node11
begin
gsay_reply(324, message_str(324, 130) + proto_data(obj_pid(dude_obj), 1) + message_str(324, 131));
giq_option(4, 324, 132, node_exit, 50);
end
procedure node12
begin
gsay_message(324, 133, 50);
end
procedure node_exit
begin
end
| 412 | 0.786958 | 1 | 0.786958 | game-dev | MEDIA | 0.936171 | game-dev | 0.902788 | 1 | 0.902788 |
signaldust/bunny-jit | 7,369 | src/opt-dom.cpp |
#include "bjit.h"
using namespace bjit;
void Proc::rebuild_cfg()
{
// Redo liveblocks .. sometimes this is called before DCE
for(auto & b : live) blocks[b].flags.live = false;
todo.clear();
live.clear();
todo.push_back(0);
live.push_back(0);
blocks[0].flags.live = true;
while(todo.size())
{
auto b = todo.back();
todo.pop_back();
auto & jmp = ops[blocks[b].code.back()];
if(jmp.opcode <= ops::jmp)
for(int k = 0; k < 2; ++k)
{
if(k && jmp.opcode == ops::jmp) break;
if(!blocks[jmp.label[k]].flags.live)
{
todo.push_back(jmp.label[k]);
live.push_back(jmp.label[k]);
blocks[jmp.label[k]].flags.live = true;
}
}
}
// rebuild comeFrom, should delay this until iteration done
for(int b = live.size();b--;) blocks[live[b]].comeFrom.clear();
for(int b = live.size();b--;)
{
// if this fails, we're probably missing return
BJIT_ASSERT(blocks[live[b]].code.size());
BJIT_ASSERT(blocks[live[b]].code.back() != noVal);
BJIT_ASSERT(ops[blocks[live[b]].code.back()].opcode <= ops::tcalln);
auto & op = ops[blocks[live[b]].code.back()];
if(op.opcode < ops::jmp)
{
blocks[op.label[1]].comeFrom.push_back(live[b]);
}
if(op.opcode <= ops::jmp)
{
blocks[op.label[0]].comeFrom.push_back(live[b]);
}
}
// cleanup dead phi alternatives
for(auto & b : live)
{
int j = 0;
auto & alts = blocks[b].alts;
for(int i = 0; i < alts.size(); ++i)
{
if(ops[alts[i].val].opcode == ops::nop) continue;
bool keep = false;
for(auto s : blocks[b].comeFrom)
{
if(alts[i].src != s) continue;
keep = true;
break;
}
if(!keep) continue;
if(i != j) alts[j] = alts[i];
++j;
}
if(j != alts.size()) alts.resize(j);
}
}
void Proc::rebuild_dom()
{
rebuild_cfg();
// find dominator algorithm
//
// start with every node dominating itself
// iterate blocks n until no change:
// tdom(n) = blocks
// for p in comeFrom(n):
// tdom(n) = sdom(n) intersect dom(p)
// dom(n) = { n } union sdom(n)
// We run the same algorithm twice, first for post-dominators
// then for dominators. We only keep immediate post-dominators
// but we rebuild (in order) the full-list for dominators.
//
// We do post-dominators first so we can use .dom as temp for both
// which saves some useless per-block allocation.
int domIters = 0;
bool iterate = true;
std::vector<uint16_t> tdom;
// post dominators first, so we can reuse .dom
for(auto & b : live)
{
// reset postdominators
if(ops[blocks[b].code.back()].opcode > ops::jmp)
{
blocks[b].dom.clear();
blocks[b].dom.push_back(b);
}
else blocks[b].dom = live;
}
while(iterate)
{
iterate = false;
++domIters;
// backwards
for(int bi = live.size(); bi--;)
{
auto & b = blocks[live[bi]];
auto & jmp = ops[b.code.back()];
// this is an exit block
if(jmp.opcode > ops::jmp) continue;
int nLabel = (jmp.opcode == ops::jmp) ? 1 : 2;
tdom = live;
for(int k = 0; k < nLabel; ++k)
{
for(int t = 0; t < tdom.size();)
{
bool found = false;
for(auto & d : blocks[jmp.label[k]].dom)
{
if(d == tdom[t]) found = true;
}
if(found) { ++t; }
else
{
std::swap(tdom[t], tdom.back());
tdom.pop_back();
}
}
}
bool foundSelf = false;
for(auto & t : tdom)
{ if(t != live[bi]) continue; foundSelf = true; break; }
if(!foundSelf) tdom.push_back(live[bi]);
if(tdom.size() != b.dom.size()) iterate = true;
// save copy, we'll reset tdom above anyway
std::swap(b.dom, tdom);
}
}
// push theoretical exit-block (unifies multiple returns)
for(auto & b : live) { blocks[b].dom.push_back(noVal); }
// find immediate post-dominators: we use the fact that the immediate
// dominator must have exactly one less dominator
for(auto & b : live)
{
blocks[b].pdom = noVal;
for(auto & d : blocks[b].dom)
{
if(d == noVal) continue; // no common post-dominator
if(blocks[d].dom.size() == blocks[b].dom.size() - 1)
{
blocks[b].pdom = d;
break;
}
}
}
// forward pass
for(auto & b : live)
{
// reset dominators
if(!b) {
blocks[b].dom.clear();
blocks[b].dom.push_back(b);
}
else blocks[b].dom = live;
}
iterate = true;
while(iterate)
{
iterate = false;
++domIters;
for(auto & b : live)
{
// this is entry block
if(!b) continue;
BJIT_ASSERT(blocks[b].comeFrom.size());
tdom = live;
for(auto & f : blocks[b].comeFrom)
{
for(int t = 0; t < tdom.size();)
{
bool found = false;
for(auto & d : blocks[f].dom)
{
if(d == tdom[t]) found = true;
}
if(found) { ++t; }
else
{
std::swap(tdom[t], tdom.back());
tdom.pop_back();
}
}
}
bool foundSelf = false;
for(auto & t : tdom) { if(t != b) continue; foundSelf = true; break; }
if(!foundSelf) tdom.push_back(b);
if(tdom.size() != blocks[b].dom.size()) iterate = true;
// save copy, we'll reset tdom above anyway
std::swap(blocks[b].dom, tdom);
}
}
// find immediate dominators: we use the fact that the immediate
// dominator must have exactly one less dominator
for(auto & b : live)
{
blocks[b].idom = 0;
for(auto & d : blocks[b].dom)
{
if(blocks[d].dom.size() == blocks[b].dom.size() - 1)
{
blocks[b].idom = d;
break;
}
}
}
// order dominators; we use these for CCD in CSE
for(auto & b : live)
{
for(auto & d : blocks[b].dom) d = noVal;
for(int d = b, i = blocks[b].dom.size(); i--;)
{
blocks[b].dom[i] = d;
d = blocks[d].idom;
}
}
BJIT_LOG(" Dom:%d", domIters);
}; | 412 | 0.940113 | 1 | 0.940113 | game-dev | MEDIA | 0.45111 | game-dev | 0.973553 | 1 | 0.973553 |
BladeRunnerJS/brjs | 1,577 | brjs-legacy/src/main/java/org/bladerunnerjs/legacy/command/test/testrunner/JsTestDriverBundleSet.java | package org.bladerunnerjs.legacy.command.test.testrunner;
import java.util.List;
import org.bladerunnerjs.api.Asset;
import org.bladerunnerjs.api.BundleSet;
import org.bladerunnerjs.api.LinkedAsset;
import org.bladerunnerjs.api.SourceModule;
import org.bladerunnerjs.api.BundlableNode;
public class JsTestDriverBundleSet implements BundleSet {
private BundleSet bundleSet;
private JsTestDriverBundlableNode bundlableNode;
public JsTestDriverBundleSet(JsTestDriverBundlableNode bundlableNode, BundleSet bundleSet) {
this.bundlableNode = bundlableNode;
this.bundleSet = bundleSet;
}
public BundlableNode bundlableNode() {
return bundlableNode;
}
@Override
public List<Asset> assets(String... prefixes)
{
return bundleSet.assets(prefixes);
}
@Override
public <AT extends Asset> List<AT> assets(Class<? extends AT> assetType, String... prefixes)
{
return bundleSet.assets(assetType, prefixes);
}
@Override
public List<Asset> assets(List<Class<? extends Asset>> assetTypes, String... prefixes)
{
return bundleSet.assets(assetTypes, prefixes);
}
@Override
public List<SourceModule> sourceModules() {
return bundleSet.sourceModules();
}
@Override
public <AT extends SourceModule> List<AT> sourceModules(Class<? extends AT> assetType) {
return bundleSet.sourceModules(assetType);
}
@Override
public List<SourceModule> sourceModules(List<Class<? extends SourceModule>> assetTypes) {
return bundleSet.sourceModules(assetTypes);
}
@Override
public List<LinkedAsset> seedAssets()
{
return bundleSet.seedAssets();
}
}
| 412 | 0.77107 | 1 | 0.77107 | game-dev | MEDIA | 0.422161 | game-dev | 0.511201 | 1 | 0.511201 |
discordia-space/CEV-Eris | 1,344 | code/modules/mob/living/carbon/superior_animal/giant_spider/giant_spider.dm | //basic spider mob, these generally guard nests
/mob/living/carbon/superior_animal/giant_spider
name = "Senshi Spider"
desc = "An overgrown tarantula. It's fangs are coated in a discolored fluid, and it's chitin seems incredibly thick."
icon_state = "guard"
icon_living = "guard"
pass_flags = PASSTABLE
mob_size = MOB_MEDIUM
maxHealth = 120
health = 120
//spawn_values
rarity_value = 37.5
spawn_frequency = 10
spawn_tags = SPAWN_TAG_SPIDER
attack_sound = 'sound/weapons/spiderlunge.ogg'
speak_emote = list("chitters")
emote_see = list("chitters", "rubs its legs")
speak_chance = 5
move_to_delay = 5
turns_per_move = 5
see_in_dark = 10
meat_type = /obj/item/reagent_containers/food/snacks/meat/spider
meat_amount = 3
stop_automated_movement_when_pulled = 0
melee_damage_lower = 12
melee_damage_upper = 17
min_breath_required_type = 3
min_air_pressure = 15 //below this, brute damage is dealt
var/poison_per_bite = 5
var/poison_type = "pararein"
pass_flags = PASSTABLE
faction = "spiders"
/mob/living/carbon/superior_animal/giant_spider/New(var/location, var/atom/parent)
get_light_and_color(parent)
..()
/mob/living/carbon/superior_animal/giant_spider/UnarmedAttack(atom/A, proximity)
. = ..()
var/mob/living/L = A
if(istype(L) && L.reagents)
L.reagents.add_reagent(poison_type, poison_per_bite)
| 412 | 0.958402 | 1 | 0.958402 | game-dev | MEDIA | 0.999285 | game-dev | 0.516307 | 1 | 0.516307 |
phasync/phasync | 1,573 | src/Util/WaitGroup.php | <?php
namespace phasync\Util;
use phasync\SelectableInterface;
/**
* This class provides an efficient tool for waiting until multiple coroutines have
* completed their task.
*/
final class WaitGroup implements SelectableInterface
{
private int $counter = 0;
public function isReady(): bool
{
return 0 === $this->counter;
}
/**
* Add work to the WaitGroup.
*/
public function add(): void
{
++$this->counter;
}
/**
* Signal that work has been completed to the WaitGroup.
*
* @throws \LogicException
*/
public function done(): void
{
if (0 === $this->counter) {
throw new \LogicException('Call WaitGroup::done() before calling WaitGroup::add()');
}
if (0 === --$this->counter) {
// Activate any waiting coroutines
\phasync::raiseFlag($this);
}
}
/**
* Wait until the WaitGroup has signalled that all work
* is done.
*
* @throws \Throwable
*/
public function await(float $timeout = \PHP_FLOAT_MAX): void
{
$timesOut = \microtime(true) + $timeout;
if (!$this->isReady()) {
\phasync::awaitFlag($this, $timesOut - \microtime(true));
}
}
/**
* This function was renamed to {@see WaitGroup::await()} to harmonize
* with the SelectableInterface API.
*
* @see WaitGroup::await()
* @deprecated
*
* @throws \Throwable
*/
public function wait(): void
{
$this->await();
}
}
| 412 | 0.854272 | 1 | 0.854272 | game-dev | MEDIA | 0.435586 | game-dev | 0.958797 | 1 | 0.958797 |
Ragebones/StormCore | 3,763 | src/server/scripts/EasternKingdoms/ScarletMonastery/boss_azshir_the_sleepless.cpp | /*
* Copyright (C) 2014-2017 StormCore
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "scarlet_monastery.h"
enum Spells
{
SPELL_CALL_OF_THE_GRAVE = 17831,
SPELL_TERRIFY = 7399,
SPELL_SOUL_SIPHON = 7290
};
enum Events
{
EVENT_CALL_OF_GRAVE = 1,
EVENT_TERRIFY,
EVENT_SOUL_SIPHON
};
class boss_azshir_the_sleepless : public CreatureScript
{
public:
boss_azshir_the_sleepless() : CreatureScript("boss_azshir_the_sleepless") { }
struct boss_azshir_the_sleeplessAI : public BossAI
{
boss_azshir_the_sleeplessAI(Creature* creature) : BossAI(creature, DATA_AZSHIR)
{
_siphon = false;
}
void Reset() override
{
_Reset();
_siphon = false;
}
void EnterCombat(Unit* /*who*/) override
{
_EnterCombat();
events.ScheduleEvent(EVENT_CALL_OF_GRAVE, 30000);
events.ScheduleEvent(EVENT_TERRIFY, 20000);
}
void JustDied(Unit* /*killer*/) override
{
_JustDied();
}
void DamageTaken(Unit* /*attacker*/, uint32& damage) override
{
if (!_siphon && me->HealthBelowPctDamaged(50, damage))
{
DoCastVictim(SPELL_SOUL_SIPHON);
events.ScheduleEvent(EVENT_SOUL_SIPHON, 20000);
_siphon = true;
}
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
events.Update(diff);
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
while (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_CALL_OF_GRAVE:
DoCastVictim(SPELL_CALL_OF_THE_GRAVE);
events.ScheduleEvent(EVENT_CALL_OF_GRAVE, 30000);
break;
case EVENT_TERRIFY:
DoCastVictim(SPELL_TERRIFY);
events.ScheduleEvent(EVENT_TERRIFY, 20000);
break;
case EVENT_SOUL_SIPHON:
DoCastVictim(SPELL_SOUL_SIPHON);
events.ScheduleEvent(EVENT_SOUL_SIPHON, 20000);
break;
default:
break;
}
}
DoMeleeAttackIfReady();
}
private:
bool _siphon;
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetScarletMonasteryAI<boss_azshir_the_sleeplessAI>(creature);
}
};
void AddSC_boss_azshir_the_sleepless()
{
new boss_azshir_the_sleepless();
}
| 412 | 0.950611 | 1 | 0.950611 | game-dev | MEDIA | 0.973539 | game-dev | 0.932776 | 1 | 0.932776 |
KospY/BasSDK | 2,029 | Assets/SDK/Scripts/Catalog/Skill/Implementation/Skills/Fire/SkillHeatwave.cs | using System;
#if ODIN_INSPECTOR
using Sirenix.OdinInspector;
#endif
using UnityEngine;
namespace ThunderRoad.Skill.Spell
{
public class SkillHeatwave : SpellSkillData
{
#if ODIN_INSPECTOR
[BoxGroup("Effect"), ValueDropdown(nameof(GetAllEffectID))]
#endif
public string effectId;
#if ODIN_INSPECTOR
[BoxGroup("Status Effect"), ValueDropdown(nameof(GetAllStatusEffectID))]
#endif
public string statusEffectId = "Burning";
[NonSerialized]
public StatusData status;
#if ODIN_INSPECTOR
[BoxGroup("Damage")]
#endif
public float radius = 1.5f;
#if ODIN_INSPECTOR
[BoxGroup("Damage")]
#endif
public int pushLevel = 1;
#if ODIN_INSPECTOR
[BoxGroup("Damage")]
#endif
public float force = 10f;
#if ODIN_INSPECTOR
[BoxGroup("Damage")]
#endif
public float damage = 10f;
#if ODIN_INSPECTOR
[BoxGroup("Damage")]
#endif
public float heat = 40f;
#if ODIN_INSPECTOR
[BoxGroup("Detection")]
#endif
public float punchStartMinMagnitude = 4;
[NonSerialized]
public float punchStartMinSqrMagnitude;
#if ODIN_INSPECTOR
[BoxGroup("Detection")]
#endif
public float punchStopMaxMagnitude = 0.5f;
[NonSerialized]
public float punchStopMaxSqrMagnitude;
#if ODIN_INSPECTOR
[BoxGroup("Detection")]
#endif
public float punchStopWindow = 0.1f;
#if ODIN_INSPECTOR
[BoxGroup("Detection")]
#endif
public float punchDelay = 0.3f;
[NonSerialized]
public EffectData effectData;
}
public class HeatwavePuncher : ThunderBehaviour
{
public override ManagedLoops EnabledManagedLoops => ManagedLoops.Update;
public SkillHeatwave skill;
public SpellCastProjectile fire;
public RagdollHand hand;
public bool active;
public float lastPunchingTime;
public Vector3 lastVelocity;
private float lastPunch;
}
}
| 412 | 0.744876 | 1 | 0.744876 | game-dev | MEDIA | 0.866557 | game-dev | 0.835232 | 1 | 0.835232 |
PolarisSS13/Polaris | 7,992 | code/game/objects/items/bodybag.dm | //Also contains /obj/structure/closet/body_bag because I doubt anyone would think to look for bodybags in /object/structures
/obj/item/bodybag
name = "body bag"
desc = "A folded bag designed for the storage and transportation of cadavers."
icon = 'icons/obj/closets/bodybag.dmi'
icon_state = "bodybag_folded"
w_class = ITEMSIZE_SMALL
/obj/item/bodybag/attack_self(mob/user)
var/obj/structure/closet/body_bag/R = new /obj/structure/closet/body_bag(user.loc)
R.add_fingerprint(user)
qdel(src)
/obj/item/storage/box/bodybags
name = "body bags"
desc = "This box contains body bags."
icon_state = "bodybags"
starts_with = list(/obj/item/bodybag = 7)
/obj/structure/closet/body_bag
name = "body bag"
desc = "A plastic bag designed for the storage and transportation of cadavers."
icon = 'icons/obj/closets/bodybag.dmi'
closet_appearance = null
open_sound = 'sound/items/zip.ogg'
close_sound = 'sound/items/zip.ogg'
door_anim_time = 0 //Unsupported
var/item_path = /obj/item/bodybag
density = 0
storage_capacity = (MOB_MEDIUM * 2) - 1
var/contains_body = 0
/obj/structure/closet/body_bag/attackby(var/obj/item/W as obj, mob/user as mob)
if (istype(W, /obj/item/pen))
var/t = input(user, "What would you like the label to be?", text("[]", src.name), null) as text
if (user.get_active_hand() != W)
return
if (!in_range(src, user) && src.loc != user)
return
t = sanitizeSafe(t, MAX_NAME_LEN)
if (t)
src.name = "body bag - "
src.name += t
add_overlay("bodybag_label")
else
src.name = "body bag"
//..() //Doesn't need to run the parent. Since when can fucking bodybags be welded shut? -Agouri
return
else if(W.is_wirecutter())
to_chat(user, "You cut the tag off the bodybag")
src.name = "body bag"
cut_overlays()
return
/obj/structure/closet/body_bag/store_mobs(var/stored_units)
contains_body = ..()
return contains_body
/obj/structure/closet/body_bag/close()
if(..())
density = 0
return 1
return 0
/obj/structure/closet/body_bag/MouseDrop(over_object, src_location, over_location)
..()
if((over_object == usr && (in_range(src, usr) || usr.contents.Find(src))))
if(!ishuman(usr)) return 0
if(opened) return 0
if(contents.len) return 0
visible_message("[usr] folds up the [src.name]")
var/folded = new item_path(get_turf(src))
spawn(0)
qdel(src)
return folded
/obj/structure/closet/body_bag/relaymove(mob/user,direction)
if(src.loc != get_turf(src))
src.loc.relaymove(user,direction)
else
..()
/obj/structure/closet/body_bag/proc/get_occupants()
var/list/occupants = list()
for(var/mob/living/carbon/human/H in contents)
occupants += H
return occupants
/obj/structure/closet/body_bag/proc/update(var/broadcast=0)
if(istype(loc, /obj/structure/morgue))
var/obj/structure/morgue/M = loc
M.update(broadcast)
/obj/structure/closet/body_bag/update_icon()
if(opened)
icon_state = "open"
else
icon_state = "closed_unlocked"
cut_overlays()
/obj/item/bodybag/cryobag
name = "stasis bag"
desc = "A non-reusable plastic bag designed to slow down bodily functions such as circulation and breathing, \
especially useful if short on time or in a hostile environment."
icon = 'icons/obj/closets/cryobag.dmi'
icon_state = "bodybag_folded"
item_state = "bodybag_cryo_folded"
origin_tech = list(TECH_BIO = 4)
var/obj/item/reagent_containers/syringe/syringe
/obj/item/bodybag/cryobag/attack_self(mob/user)
var/obj/structure/closet/body_bag/cryobag/R = new /obj/structure/closet/body_bag/cryobag(user.loc)
R.add_fingerprint(user)
if(syringe)
R.syringe = syringe
syringe = null
qdel(src)
/obj/structure/closet/body_bag/cryobag
name = "stasis bag"
desc = "A non-reusable plastic bag designed to slow down bodily functions such as circulation and breathing, \
especially useful if short on time or in a hostile environment."
icon = 'icons/obj/closets/cryobag.dmi'
item_path = /obj/item/bodybag/cryobag
store_misc = 0
store_items = 0
var/used = 0
var/obj/item/tank/tank = null
var/tank_type = /obj/item/tank/stasis/oxygen
var/stasis_level = 3 //Every 'this' life ticks are applied to the mob (when life_ticks%stasis_level == 1)
var/obj/item/reagent_containers/syringe/syringe
/obj/structure/closet/body_bag/cryobag/Destroy()
QDEL_NULL(syringe)
QDEL_NULL(tank)
return ..()
/obj/structure/closet/body_bag/cryobag/Initialize()
. = ..()
if (ispath(tank_type, /obj/item/tank))
tank = new tank_type // no loc to prevent tank being dropped when opened
/obj/structure/closet/body_bag/cryobag/attack_hand(mob/living/user)
if(used)
var/confirm = alert(user, "Are you sure you want to open \the [src]? \
\The [src] will expire upon opening it.", "Confirm Opening", "No", "Yes")
if(confirm == "Yes")
..() // Will call `toggle()` and open the bag.
else
..()
/obj/structure/closet/body_bag/cryobag/open()
. = ..()
if(used)
new /obj/item/usedcryobag(loc)
qdel(src)
/obj/structure/closet/body_bag/cryobag/update_icon()
..()
cut_overlays()
var/image/I = image(icon, "indicator[opened]")
I.appearance_flags = RESET_COLOR
I.color = COLOR_LIME
add_overlay(I)
/obj/structure/closet/body_bag/cryobag/MouseDrop(over_object, src_location, over_location)
. = ..()
if(. && syringe)
var/obj/item/bodybag/cryobag/folded = .
folded.syringe = syringe
syringe = null
/obj/structure/closet/body_bag/cryobag/Entered(atom/movable/AM)
if(ishuman(AM))
var/mob/living/carbon/human/H = AM
H.Stasis(stasis_level)
src.used = 1
inject_occupant(H)
if(istype(AM, /obj/item/organ))
var/obj/item/organ/O = AM
O.preserved = 1
for(var/obj/item/organ/organ in O)
organ.preserved = 1
..()
/obj/structure/closet/body_bag/cryobag/Exited(atom/movable/AM)
if(ishuman(AM))
var/mob/living/carbon/human/H = AM
H.Stasis(0)
if(istype(AM, /obj/item/organ))
var/obj/item/organ/O = AM
O.preserved = 0
for(var/obj/item/organ/organ in O)
organ.preserved = 0
..()
/obj/structure/closet/body_bag/cryobag/return_air() //Used to make stasis bags protect from vacuum.
if(tank)
return tank.air_contents
..()
/obj/structure/closet/body_bag/cryobag/proc/inject_occupant(var/mob/living/carbon/human/H)
if(!syringe)
return
if(H.reagents)
syringe.reagents.trans_to_mob(H, 30, CHEM_BLOOD)
/obj/structure/closet/body_bag/cryobag/examine(mob/user, distance, infix, suffix)
. = ..()
if(distance < 2) //The bag's rather thick and opaque from a distance.
. += "<span class='info'>You peer into \the [src].</span>"
if(syringe)
. += "<span class='info'>It has a syringe added to it.</span>"
for(var/mob/living/L in contents)
. += L.examine(user, distance, infix, suffix)
/obj/structure/closet/body_bag/cryobag/attackby(obj/item/W, mob/user)
if(opened)
..()
else //Allows the bag to respond to a health analyzer by analyzing the mob inside without needing to open it.
if(istype(W,/obj/item/healthanalyzer))
var/obj/item/healthanalyzer/analyzer = W
for(var/mob/living/L in contents)
analyzer.attack(L,user)
else if(istype(W,/obj/item/reagent_containers/syringe))
if(syringe)
to_chat(user,"<span class='warning'>\The [src] already has an injector! Remove it first.</span>")
else
var/obj/item/reagent_containers/syringe/syringe = W
to_chat(user,"<span class='info'>You insert \the [syringe] into \the [src], and it locks into place.</span>")
user.unEquip(syringe)
src.syringe = syringe
syringe.loc = null
for(var/mob/living/carbon/human/H in contents)
inject_occupant(H)
break
else if(W.is_screwdriver())
if(syringe)
if(used)
to_chat(user,"<span class='warning'>The injector cannot be removed now that the stasis bag has been used!</span>")
else
syringe.forceMove(src.loc)
to_chat(user,"<span class='info'>You pry \the [syringe] out of \the [src].</span>")
syringe = null
else
..()
/obj/item/usedcryobag
name = "used stasis bag"
desc = "Pretty useless now.."
icon_state = "bodybag_used"
icon = 'icons/obj/closets/cryobag.dmi'
| 412 | 0.770506 | 1 | 0.770506 | game-dev | MEDIA | 0.652419 | game-dev | 0.737952 | 1 | 0.737952 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.